# Internals

> How the Peios kernel coordinates execution, manages resources, and implements its core subsystems.

---

# Understanding the kernel

_Peios Kernel / Internals / Start here_

> A reading path through the kernel implementation.

Start with the subsystem you are investigating. The shelves group mechanisms
that commonly need to be understood together.

- **Concurrency and synchronisation:** begin with [Locking](</kernel/internals/locking/overview.md>),
  then explore [Scheduling](</kernel/internals/scheduler/index.md>) and [RCU](</kernel/internals/rcu/index.md>).
- **Core services and memory:** use [Core APIs](</kernel/internals/core-api/index.md>) for
  shared facilities and [Memory management](</kernel/internals/mm/index.md>) for allocation,
  address spaces and reclaim. [BPF](</kernel/internals/bpf/index.md>) covers in-kernel programs.
- **Storage and filesystems:** follow the [Block layer](</kernel/internals/block/index.md>)
  and [Filesystem interfaces](</kernel/internals/filesystems/index.md>).
- **Networking:** start with [Networking](</kernel/internals/networking/index.md>), then
  use [Netlink](</kernel/internals/netlink/specs/index.md>) for protocol specifications and messaging.
- **Security and cryptography:** see [Security](</kernel/internals/security/index.md>)
  and [Cryptographic APIs](</kernel/internals/crypto/index.md>).
- **Power and virtualisation:** see [Power management](</kernel/internals/power/index.md>)
  and [Virtualisation](</kernel/internals/virt/index.md>).

For tuning a running system, use [Administration](</kernel/administration/admin-guide/overview/index.md>).
For implementing or testing a change, use [Kernel development](</kernel/development/start-here/overview.md>).

## Native Peios subsystems

- [KACS](</kernel/internals/kacs/start-here/overview.md>): access control and executable trust.
- [KMES](</kernel/internals/kmes/overview.md>): event emission and delivery.
- [LCS](</kernel/internals/lcs/start-here/overview.md>): layered configuration and registry services.
- [StrataFS](</kernel/internals/stratafs/start-here/overview.md>): layered filesystem resolution and mutation.
- [NTFE](</kernel/internals/ntfe/overview.md>): packet policy and flow decisions.

---

# Locking

_Peios Kernel / Internals / Locking_

> Find the locking primitives, usage rules, implementation details, and diagnostic tools used inside the kernel.

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

Kernel code can run concurrently on multiple CPUs and in different execution
contexts. Locking primitives coordinate access to shared state. The appropriate
primitive depends on the context, whether waiting may sleep, and the guarantees
the protected operation requires.

Start with [Lock types and their rules](/kernel/internals/locking/locktypes.md),
which explains sleeping, spinning, and CPU-local locks, their nesting rules,
and how their behaviour changes under PREEMPT_RT.

## Locking primitives

- [Spinlocks](/kernel/internals/locking/spinlocks.md) and [mutexes](/kernel/internals/locking/mutex-design.md).
- [RT-mutexes and priority inheritance](/kernel/internals/locking/rt-mutex.md), with a detailed [implementation guide](/kernel/internals/locking/rt-mutex-design.md).
- [Wound/wait mutexes](/kernel/internals/locking/ww-mutex-design.md) for acquiring multiple locks when their order is not fixed.
- [Sequence counters and sequential locks](/kernel/internals/locking/seqlock.md).
- [Per-CPU reader/writer semaphores](/kernel/internals/locking/percpu-rw-semaphore.md).
- [Hardware spinlocks](/kernel/internals/locking/hwspinlock.md).

## Execution context and userspace coordination

[Locking and preemption](/kernel/internals/locking/preempt-locking.md) describes
protection for per-CPU data, processor state, and critical sections.

The futex articles cover [priority inheritance](/kernel/internals/locking/pi-futex.md),
[requeueing](/kernel/internals/locking/futex-requeue-pi.md),
[robust futexes](/kernel/internals/locking/robust-futexes.md), and the
[robust futex ABI](/kernel/internals/locking/robust-futex-abi.md).

## Validation and diagnostics

- [Lock dependency validation](/kernel/internals/locking/lockdep-design.md) explains lockdep and its annotations.
- [Lock statistics](/kernel/internals/locking/lockstat.md) covers contention and hold-time measurements.
- [Lock torture tests](/kernel/internals/locking/locktorture.md) describes the locking stress-test module.

---

# Lock types and their rules

_Peios Kernel / Internals / Locking_

> Sleeping, spinning, and CPU-local locks, including PREEMPT_RT behaviour and nesting rules.

<a id="rst-lock-types-and-their-rules"></a>
<a id="rst-kernel-hacking-locktypes"></a>

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

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

## Introduction

The kernel provides a variety of locking primitives which can be divided
into three categories:

- Sleeping locks

- CPU local locks

- Spinning locks

This document conceptually describes these lock types and provides rules
for their nesting, including the rules for use under PREEMPT_RT.

<a id="rst-lock-categories"></a>

## Lock categories

<a id="rst-sleeping-locks"></a>

### Sleeping locks

Sleeping locks can only be acquired in preemptible task context.

Although implementations allow try_lock() from other contexts, it is
necessary to carefully evaluate the safety of unlock() as well as of
try_lock().  Furthermore, it is also necessary to evaluate the debugging
versions of these primitives.  In short, don't acquire sleeping locks from
other contexts unless there is no other option.

Sleeping lock types:

- mutex

- rt_mutex

- semaphore

- rw_semaphore

- ww_mutex

- percpu_rw_semaphore

On PREEMPT_RT kernels, these lock types are converted to sleeping locks:

- local_lock

- spinlock_t

- rwlock_t

<a id="rst-cpu-local-locks"></a>

### CPU local locks

- local_lock

On non-PREEMPT_RT kernels, local_lock functions are wrappers around
preemption and interrupt disabling primitives. Contrary to other locking
mechanisms, disabling preemption or interrupts are pure CPU local
concurrency control mechanisms and not suited for inter-CPU concurrency
control.

<a id="rst-spinning-locks"></a>

### Spinning locks

- raw_spinlock_t

- bit spinlocks

On non-PREEMPT_RT kernels, these lock types are also spinning locks:

- spinlock_t

- rwlock_t

Spinning locks implicitly disable preemption and the lock / unlock functions
can have suffixes which apply further protections:

<table>
<tbody>
<tr>
<td><p>_bh()</p></td>
<td><p>Disable / enable bottom halves (soft interrupts)</p></td>
</tr>
<tr>
<td><p>_irq()</p></td>
<td><p>Disable / enable interrupts</p></td>
</tr>
<tr>
<td><p>_irqsave/restore()</p></td>
<td><p>Save and disable / restore interrupt disabled state</p></td>
</tr>
</tbody>
</table>

<a id="rst-owner-semantics"></a>

## Owner semantics

The aforementioned lock types except semaphores have strict owner
semantics:

> The context (task) that acquired the lock must release it.

rw_semaphores have a special interface which allows non-owner release for
readers.

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

## rtmutex

RT-mutexes are mutexes with support for priority inheritance (PI).

PI has limitations on non-PREEMPT_RT kernels due to preemption and
interrupt disabled sections.

PI clearly cannot preempt preemption-disabled or interrupt-disabled
regions of code, even on PREEMPT_RT kernels.  Instead, PREEMPT_RT kernels
execute most such regions of code in preemptible task context, especially
interrupt handlers and soft interrupts.  This conversion allows spinlock_t
and rwlock_t to be implemented via RT-mutexes.

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

## semaphore

semaphore is a counting semaphore implementation.

Semaphores are often used for both serialization and waiting, but new use
cases should instead use separate serialization and wait mechanisms, such
as mutexes and completions.

<a id="rst-semaphores-and-preempt-rt"></a>

### semaphores and PREEMPT_RT

PREEMPT_RT does not change the semaphore implementation because counting
semaphores have no concept of owners, thus preventing PREEMPT_RT from
providing priority inheritance for semaphores.  After all, an unknown
owner cannot be boosted. As a consequence, blocking on semaphores can
result in priority inversion.

<a id="rst-rw-semaphore"></a>

## rw_semaphore

rw_semaphore is a multiple readers and single writer lock mechanism.

On non-PREEMPT_RT kernels the implementation is fair, thus preventing
writer starvation.

rw_semaphore complies by default with the strict owner semantics, but there
exist special-purpose interfaces that allow non-owner release for readers.
These interfaces work independent of the kernel configuration.

<a id="rst-rw-semaphore-and-preempt-rt"></a>

### rw_semaphore and PREEMPT_RT

PREEMPT_RT kernels map rw_semaphore to a separate rt_mutex-based
implementation, thus changing the fairness:

> Because an rw_semaphore writer cannot grant its priority to multiple
> readers, a preempted low-priority reader will continue holding its lock,
> thus starving even high-priority writers.  In contrast, because readers
> can grant their priority to a writer, a preempted low-priority writer will
> have its priority boosted until it releases the lock, thus preventing that
> writer from starving readers.

<a id="rst-local-lock"></a>

## local_lock

local_lock provides a named scope to critical sections which are protected
by disabling preemption or interrupts.

On non-PREEMPT_RT kernels local_lock operations map to the preemption and
interrupt disabling and enabling primitives:

<table>
<tbody>
<tr>
<td><p>local_lock(&amp;llock)</p></td>
<td><p>preempt_disable()</p></td>
</tr>
<tr>
<td><p>local_unlock(&amp;llock)</p></td>
<td><p>preempt_enable()</p></td>
</tr>
<tr>
<td><p>local_lock_irq(&amp;llock)</p></td>
<td><p>local_irq_disable()</p></td>
</tr>
<tr>
<td><p>local_unlock_irq(&amp;llock)</p></td>
<td><p>local_irq_enable()</p></td>
</tr>
<tr>
<td><p>local_lock_irqsave(&amp;llock)</p></td>
<td><p>local_irq_save()</p></td>
</tr>
<tr>
<td><p>local_unlock_irqrestore(&amp;llock)</p></td>
<td><p>local_irq_restore()</p></td>
</tr>
</tbody>
</table>

The named scope of local_lock has two advantages over the regular
primitives:

- The lock name allows static analysis and is also a clear documentation
  of the protection scope while the regular primitives are scopeless and
  opaque.

- If lockdep is enabled the local_lock gains a lockmap which allows to
  validate the correctness of the protection. This can detect cases where
  e.g. a function using preempt_disable() as protection mechanism is
  invoked from interrupt or soft-interrupt context. Aside of that
  lockdep_assert_held(&amp;llock) works as with any other locking primitive.

<a id="rst-local-lock-and-preempt-rt"></a>

### local_lock and PREEMPT_RT

PREEMPT_RT kernels map local_lock to a per-CPU spinlock_t, thus changing
semantics:

- All spinlock_t changes also apply to local_lock.

<a id="rst-local-lock-usage"></a>

### local_lock usage

local_lock should be used in situations where disabling preemption or
interrupts is the appropriate form of concurrency control to protect
per-CPU data structures on a non PREEMPT_RT kernel.

local_lock is not suitable to protect against preemption or interrupts on a
PREEMPT_RT kernel due to the PREEMPT_RT specific spinlock_t semantics.

<a id="rst-cpu-local-scope-and-bottom-half"></a>

### CPU local scope and bottom-half

Per-CPU variables that are accessed only in softirq context should not rely on
the assumption that this context is implicitly protected due to being
non-preemptible. In a PREEMPT_RT kernel, softirq context is preemptible, and
synchronizing every bottom-half-disabled section via implicit context results
in an implicit per-CPU "big kernel lock."

A local_lock_t together with local_lock_nested_bh() and
local_unlock_nested_bh() for locking operations help to identify the locking
scope.

When lockdep is enabled, these functions verify that data structure access
occurs within softirq context.
Unlike local_lock(), local_unlock_nested_bh() does not disable preemption and
does not add overhead when used without lockdep.

On a PREEMPT_RT kernel, local_lock_t behaves as a real lock and
local_unlock_nested_bh() serializes access to the data structure, which allows
removal of serialization via local_bh_disable().

<a id="rst-raw-spinlock-t-and-spinlock-t"></a>

## raw_spinlock_t and spinlock_t

<a id="rst-raw-spinlock-t"></a>

### raw_spinlock_t

raw_spinlock_t is a strict spinning lock implementation in all kernels,
including PREEMPT_RT kernels.  Use raw_spinlock_t only in real critical
core code, low-level interrupt handling and places where disabling
preemption or interrupts is required, for example, to safely access
hardware state.  raw_spinlock_t can sometimes also be used when the
critical section is tiny, thus avoiding RT-mutex overhead.

<a id="rst-spinlock-t"></a>

### spinlock_t

The semantics of spinlock_t change with the state of PREEMPT_RT.

On a non-PREEMPT_RT kernel spinlock_t is mapped to raw_spinlock_t and has
exactly the same semantics.

<a id="rst-spinlock-t-and-preempt-rt"></a>

### spinlock_t and PREEMPT_RT

On a PREEMPT_RT kernel spinlock_t is mapped to a separate implementation
based on rt_mutex which changes the semantics:

- Preemption is not disabled.

- The hard interrupt related suffixes for spin_lock / spin_unlock
  operations (\_irq, \_irqsave / \_irqrestore) do not affect the CPU's
  interrupt disabled state.

- The soft interrupt related suffix (\_bh()) still disables softirq
  handlers.

  Non-PREEMPT_RT kernels disable preemption to get this effect.

  PREEMPT_RT kernels use a per-CPU lock for serialization which keeps
  preemption enabled. The lock disables softirq handlers and also
  prevents reentrancy due to task preemption.

PREEMPT_RT kernels preserve all other spinlock_t semantics:

- Tasks holding a spinlock_t do not migrate.  Non-PREEMPT_RT kernels
  avoid migration by disabling preemption.  PREEMPT_RT kernels instead
  disable migration, which ensures that pointers to per-CPU variables
  remain valid even if the task is preempted.

- Task state is preserved across spinlock acquisition, ensuring that the
  task-state rules apply to all kernel configurations.  Non-PREEMPT_RT
  kernels leave task state untouched.  However, PREEMPT_RT must change
  task state if the task blocks during acquisition.  Therefore, it saves
  the current task state before blocking and the corresponding lock wakeup
  restores it, as shown below:

  ```text
  task->state = TASK_INTERRUPTIBLE
   lock()
     block()
       task->saved_state = task->state
       task->state = TASK_UNINTERRUPTIBLE
       schedule()
                                      lock wakeup
                                        task->state = task->saved_state
  ```

  Other types of wakeups would normally unconditionally set the task state
  to RUNNING, but that does not work here because the task must remain
  blocked until the lock becomes available.  Therefore, when a non-lock
  wakeup attempts to awaken a task blocked waiting for a spinlock, it
  instead sets the saved state to RUNNING.  Then, when the lock
  acquisition completes, the lock wakeup sets the task state to the saved
  state, in this case setting it to RUNNING:

  ```text
  task->state = TASK_INTERRUPTIBLE
   lock()
     block()
       task->saved_state = task->state
       task->state = TASK_UNINTERRUPTIBLE
       schedule()
                                      non lock wakeup
                                        task->saved_state = TASK_RUNNING

                                      lock wakeup
                                        task->state = task->saved_state
  ```

  This ensures that the real wakeup cannot be lost.

<a id="rst-rwlock-t"></a>

## rwlock_t

rwlock_t is a multiple readers and single writer lock mechanism.

Non-PREEMPT_RT kernels implement rwlock_t as a spinning lock and the
suffix rules of spinlock_t apply accordingly. The implementation is fair,
thus preventing writer starvation.

<a id="rst-rwlock-t-and-preempt-rt"></a>

### rwlock_t and PREEMPT_RT

PREEMPT_RT kernels map rwlock_t to a separate rt_mutex-based
implementation, thus changing semantics:

- All the spinlock_t changes also apply to rwlock_t.

- Because an rwlock_t writer cannot grant its priority to multiple
  readers, a preempted low-priority reader will continue holding its lock,
  thus starving even high-priority writers.  In contrast, because readers
  can grant their priority to a writer, a preempted low-priority writer
  will have its priority boosted until it releases the lock, thus
  preventing that writer from starving readers.

<a id="rst-preempt-rt-caveats"></a>

## PREEMPT_RT caveats

<a id="rst-local-lock-on-rt"></a>

### local_lock on RT

The mapping of local_lock to spinlock_t on PREEMPT_RT kernels has a few
implications. For example, on a non-PREEMPT_RT kernel the following code
sequence works as expected:

```c
local_lock_irq(&local_lock);
raw_spin_lock(&lock);
```

and is fully equivalent to:

```c
raw_spin_lock_irq(&lock);
```

On a PREEMPT_RT kernel this code sequence breaks because local_lock_irq()
is mapped to a per-CPU spinlock_t which neither disables interrupts nor
preemption. The following code sequence works perfectly correct on both
PREEMPT_RT and non-PREEMPT_RT kernels:

```c
local_lock_irq(&local_lock);
spin_lock(&lock);
```

Another caveat with local locks is that each local_lock has a specific
protection scope. So the following substitution is wrong:

```text
func1()
{
  local_irq_save(flags);    -> local_lock_irqsave(&local_lock_1, flags);
  func3();
  local_irq_restore(flags); -> local_unlock_irqrestore(&local_lock_1, flags);
}

func2()
{
  local_irq_save(flags);    -> local_lock_irqsave(&local_lock_2, flags);
  func3();
  local_irq_restore(flags); -> local_unlock_irqrestore(&local_lock_2, flags);
}

func3()
{
  lockdep_assert_irqs_disabled();
  access_protected_data();
}
```

On a non-PREEMPT_RT kernel this works correctly, but on a PREEMPT_RT kernel
local_lock_1 and local_lock_2 are distinct and cannot serialize the callers
of func3(). Also the lockdep assert will trigger on a PREEMPT_RT kernel
because local_lock_irqsave() does not disable interrupts due to the
PREEMPT_RT-specific semantics of spinlock_t. The correct substitution is:

```text
func1()
{
  local_irq_save(flags);    -> local_lock_irqsave(&local_lock, flags);
  func3();
  local_irq_restore(flags); -> local_unlock_irqrestore(&local_lock, flags);
}

func2()
{
  local_irq_save(flags);    -> local_lock_irqsave(&local_lock, flags);
  func3();
  local_irq_restore(flags); -> local_unlock_irqrestore(&local_lock, flags);
}

func3()
{
  lockdep_assert_held(&local_lock);
  access_protected_data();
}
```

<a id="rst-spinlock-t-and-rwlock-t"></a>

### spinlock_t and rwlock_t

The changes in spinlock_t and rwlock_t semantics on PREEMPT_RT kernels
have a few implications.  For example, on a non-PREEMPT_RT kernel the
following code sequence works as expected:

```c
local_irq_disable();
spin_lock(&lock);
```

and is fully equivalent to:

```c
spin_lock_irq(&lock);
```

Same applies to rwlock_t and the \_irqsave() suffix variants.

On PREEMPT_RT kernel this code sequence breaks because RT-mutex requires a
fully preemptible context.  Instead, use spin_lock_irq() or
spin_lock_irqsave() and their unlock counterparts.  In cases where the
interrupt disabling and locking must remain separate, PREEMPT_RT offers a
local_lock mechanism.  Acquiring the local_lock pins the task to a CPU,
allowing things like per-CPU interrupt disabled locks to be acquired.
However, this approach should be used only where absolutely necessary.

A typical scenario is protection of per-CPU variables in thread context:

```c
struct foo *p = get_cpu_ptr(&var1);

spin_lock(&p->lock);
p->count += this_cpu_read(var2);
```

This is correct code on a non-PREEMPT_RT kernel, but on a PREEMPT_RT kernel
this breaks. The PREEMPT_RT-specific change of spinlock_t semantics does
not allow to acquire p-&gt;lock because get_cpu_ptr() implicitly disables
preemption. The following substitution works on both kernels:

```c
struct foo *p;

migrate_disable();
p = this_cpu_ptr(&var1);
spin_lock(&p->lock);
p->count += this_cpu_read(var2);
```

migrate_disable() ensures that the task is pinned on the current CPU which
in turn guarantees that the per-CPU access to var1 and var2 are staying on
the same CPU while the task remains preemptible.

The migrate_disable() substitution is not valid for the following
scenario:

```c
func()
{
  struct foo *p;

  migrate_disable();
  p = this_cpu_ptr(&var1);
  p->val = func2();
```

This breaks because migrate_disable() does not protect against reentrancy from
a preempting task. A correct substitution for this case is:

```c
func()
{
  struct foo *p;

  local_lock(&foo_lock);
  p = this_cpu_ptr(&var1);
  p->val = func2();
```

On a non-PREEMPT_RT kernel this protects against reentrancy by disabling
preemption. On a PREEMPT_RT kernel this is achieved by acquiring the
underlying per-CPU spinlock.

<a id="rst-raw-spinlock-t-on-rt"></a>

### raw_spinlock_t on RT

Acquiring a raw_spinlock_t disables preemption and possibly also
interrupts, so the critical section must avoid acquiring a regular
spinlock_t or rwlock_t, for example, the critical section must avoid
allocating memory.  Thus, on a non-PREEMPT_RT kernel the following code
works perfectly:

```c
raw_spin_lock(&lock);
p = kmalloc(sizeof(*p), GFP_ATOMIC);
```

But this code fails on PREEMPT_RT kernels because the memory allocator is
fully preemptible and therefore cannot be invoked from truly atomic
contexts.  However, it is perfectly fine to invoke the memory allocator
while holding normal non-raw spinlocks because they do not disable
preemption on PREEMPT_RT kernels:

```c
spin_lock(&lock);
p = kmalloc(sizeof(*p), GFP_ATOMIC);
```

<a id="rst-bit-spinlocks"></a>

### bit spinlocks

PREEMPT_RT cannot substitute bit spinlocks because a single bit is too
small to accommodate an RT-mutex.  Therefore, the semantics of bit
spinlocks are preserved on PREEMPT_RT kernels, so that the raw_spinlock_t
caveats also apply to bit spinlocks.

Some bit spinlocks are replaced with regular spinlock_t for PREEMPT_RT
using conditional (\#ifdef'ed) code changes at the usage site.  In contrast,
usage-site changes are not needed for the spinlock_t substitution.
Instead, conditionals in header files and the core locking implementation
enable the compiler to do the substitution transparently.

<a id="rst-lock-type-nesting-rules"></a>

## Lock type nesting rules

The most basic rules are:

- Lock types of the same lock category (sleeping, CPU local, spinning)
  can nest arbitrarily as long as they respect the general lock ordering
  rules to prevent deadlocks.

- Sleeping lock types cannot nest inside CPU local and spinning lock types.

- CPU local and spinning lock types can nest inside sleeping lock types.

- Spinning lock types can nest inside all lock types

These constraints apply both in PREEMPT_RT and otherwise.

The fact that PREEMPT_RT changes the lock category of spinlock_t and
rwlock_t from spinning to sleeping and substitutes local_lock with a
per-CPU spinlock_t means that they cannot be acquired while holding a raw
spinlock.  This results in the following nesting ordering:

1. Sleeping locks

2. spinlock_t, rwlock_t, local_lock

3. raw_spinlock_t and bit spinlocks

Lockdep will complain if these constraints are violated, both in
PREEMPT_RT and otherwise.

---

# Spinlocks

_Peios Kernel / Internals / Locking_

> Using spinlocks and reader/writer spinlocks to protect shared kernel data.

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

<a id="rst-lesson-1-spin-locks"></a>

## Lesson 1: Spin locks

The most basic primitive for locking is spinlock:

```c
static DEFINE_SPINLOCK(xxx_lock);

      unsigned long flags;

      spin_lock_irqsave(&xxx_lock, flags);
      ... critical section here ..
      spin_unlock_irqrestore(&xxx_lock, flags);
```

The above is always safe. It will disable interrupts \_locally\_, but the
spinlock itself will guarantee the global lock, so it will guarantee that
there is only one thread-of-control within the region(s) protected by that
lock. This works well even under UP also, so the code does \_not\_ need to
worry about UP vs SMP issues: the spinlocks work correctly under both.

> NOTE\! Implications of spin_locks for memory are further described in:
>
> > [Documentation/memory-barriers.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/memory-barriers.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)
> >
> > > 5. ACQUIRE operations.
> > >
> > > 6. RELEASE operations.

The above is usually pretty simple (you usually need and want only one
spinlock for most things - using more than one spinlock can make things a
lot more complex and even slower and is usually worth it only for
sequences that you **know** need to be split up: avoid it at all cost if you
aren't sure).

This is really the only really hard part about spinlocks: once you start
using spinlocks they tend to expand to areas you might not have noticed
before, because you have to make sure the spinlocks correctly protect the
shared data structures **everywhere** they are used. The spinlocks are most
easily added to places that are completely independent of other code (for
example, internal driver data structures that nobody else ever touches).

> NOTE\! The spin-lock is safe only when you **also** use the lock itself
> to do locking across CPU's, which implies that EVERYTHING that
> touches a shared variable has to agree about the spinlock they want
> to use.

---

<a id="rst-lesson-2-reader-writer-spinlocks"></a>

## Lesson 2: reader-writer spinlocks.

If your data accesses have a very natural pattern where you usually tend
to mostly read from the shared variables, the reader-writer locks
(rw_lock) versions of the spinlocks are sometimes useful. They allow multiple
readers to be in the same critical region at once, but if somebody wants
to change the variables it has to get an exclusive write lock.

> NOTE\! reader-writer locks require more atomic memory operations than
> simple spinlocks.  Unless the reader critical section is long, you
> are better off just using spinlocks.

The routines look the same as above:

```c
rwlock_t xxx_lock = __RW_LOCK_UNLOCKED(xxx_lock);

     unsigned long flags;

     read_lock_irqsave(&xxx_lock, flags);
     .. critical section that only reads the info ...
     read_unlock_irqrestore(&xxx_lock, flags);

     write_lock_irqsave(&xxx_lock, flags);
     .. read and write exclusive access to the info ...
     write_unlock_irqrestore(&xxx_lock, flags);
```

The above kind of lock may be useful for complex data structures like
linked lists, especially searching for entries without changing the list
itself.  The read lock allows many concurrent readers.  Anything that
**changes** the list will have to get the write lock.

> NOTE\! RCU is better for list traversal, but requires careful
> attention to design detail (see [Documentation/RCU/listRCU.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/RCU/listRCU.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)).

Also, you cannot "upgrade" a read-lock to a write-lock, so if you at \_any\_
time need to do any changes (even if you don't do it every time), you have
to get the write-lock at the very beginning.

> NOTE\! We are working hard to remove reader-writer spinlocks in most
> cases, so please don't add a new one without consensus.  (Instead, see
> [Documentation/RCU/rcu.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/RCU/rcu.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for complete information.)

---

<a id="rst-lesson-3-spinlocks-revisited"></a>

## Lesson 3: spinlocks revisited.

The single spin-lock primitives above are by no means the only ones. They
are the most safe ones, and the ones that work under all circumstances,
but partly **because** they are safe they are also fairly slow. They are slower
than they'd need to be, because they do have to disable interrupts
(which is just a single instruction on a x86, but it's an expensive one -
and on other architectures it can be worse).

If you have a case where you have to protect a data structure across
several CPU's and you want to use spinlocks you can potentially use
cheaper versions of the spinlocks. IFF you know that the spinlocks are
never used in interrupt handlers, you can use the non-irq versions:

```c
spin_lock(&lock);
...
spin_unlock(&lock);
```

(and the equivalent read-write versions too, of course). The spinlock will
guarantee the same kind of exclusive access, and it will be much faster.
This is useful if you know that the data in question is only ever
manipulated from a "process context", ie no interrupts involved.

The reasons you mustn't use these versions if you have interrupts that
play with the spinlock is that you can get deadlocks:

```text
spin_lock(&lock);
...
        <- interrupt comes in:
                spin_lock(&lock);
```

where an interrupt tries to lock an already locked variable. This is ok if
the other interrupt happens on another CPU, but it is \_not\_ ok if the
interrupt happens on the same CPU that already holds the lock, because the
lock will obviously never be released (because the interrupt is waiting
for the lock, and the lock-holder is interrupted by the interrupt and will
not continue until the interrupt has been processed).

(This is also the reason why the irq-versions of the spinlocks only need
to disable the \_local\_ interrupts - it's ok to use spinlocks in interrupts
on other CPU's, because an interrupt on another CPU doesn't interrupt the
CPU that holds the lock, so the lock-holder can continue and eventually
releases the lock).

> Linus

---

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

## Reference information:

For dynamic initialization, use spin_lock_init() or rwlock_init() as
appropriate:

```c
spinlock_t xxx_lock;
rwlock_t xxx_rw_lock;

static int __init xxx_init(void)
{
     spin_lock_init(&xxx_lock);
     rwlock_init(&xxx_rw_lock);
     ...
}

module_init(xxx_init);
```

For static initialization, use DEFINE_SPINLOCK() / DEFINE_RWLOCK() or
\__SPIN_LOCK_UNLOCKED() / \__RW_LOCK_UNLOCKED() as appropriate.

---

# Mutexes

_Peios Kernel / Internals / Locking_

> Mutex semantics, implementation paths, debugging, and differences from semaphores.

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

<a id="rst-what-are-mutexes"></a>

## What are mutexes?

In the Linux kernel, mutexes refer to a particular locking primitive
that enforces serialization on shared memory systems, and not only to
the generic term referring to 'mutual exclusion' found in academia
or similar theoretical text books. Mutexes are sleeping locks which
behave similarly to binary semaphores, and were introduced in 2006\[1\]
as an alternative to these. This new data structure provided a number
of advantages, including simpler interfaces, and at that time smaller
code (see Disadvantages).

\[1\] [https://lwn.net/Articles/164802/](<https://lwn.net/Articles/164802/>)

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

## Implementation

Mutexes are represented by 'struct mutex', defined in include/linux/mutex.h
and implemented in kernel/locking/mutex.c. These locks use an atomic variable
(-&gt;owner) to keep track of the lock state during its lifetime.  Field owner
actually contains `struct task_struct *` to the current lock owner and it is
therefore NULL if not currently owned. Since task_struct pointers are aligned
to at least L1_CACHE_BYTES, low bits (3) are used to store extra state (e.g.,
if waiter list is non-empty).  In its most basic form it also includes a
wait-queue and a spinlock that serializes access to it. Furthermore,
CONFIG_MUTEX_SPIN_ON_OWNER=y systems use a spinner MCS lock (-&gt;osq), described
below in (ii).

When acquiring a mutex, there are three possible paths that can be
taken, depending on the state of the lock:

- **(i)** fastpath: tries to atomically acquire the lock by cmpxchg()ing the owner with
  the current task. This only works in the uncontended case (cmpxchg() checks
  against 0UL, so all 3 state bits above have to be 0). If the lock is
  contended it goes to the next possible path.

- **(ii)** midpath: aka optimistic spinning, tries to spin for acquisition
  while the lock owner is running and there are no other tasks ready
  to run that have higher priority (need_resched). The rationale is
  that if the lock owner is running, it is likely to release the lock
  soon. The mutex spinners are queued up using MCS lock so that only
  one spinner can compete for the mutex.

  The MCS lock (proposed by Mellor-Crummey and Scott) is a simple spinlock
  with the desirable properties of being fair and with each cpu trying
  to acquire the lock spinning on a local variable. It avoids expensive
  cacheline bouncing that common test-and-set spinlock implementations
  incur. An MCS-like lock is specially tailored for optimistic spinning
  for sleeping lock implementation. An important feature of the customized
  MCS lock is that it has the extra property that spinners are able to exit
  the MCS spinlock queue when they need to reschedule. This further helps
  avoid situations where MCS spinners that need to reschedule would continue
  waiting to spin on mutex owner, only to go directly to slowpath upon
  obtaining the MCS lock.

- **(iii)** slowpath: last resort, if the lock is still unable to be acquired,
  the task is added to the wait-queue and sleeps until woken up by the
  unlock path. Under normal circumstances it blocks as TASK_UNINTERRUPTIBLE.

While formally kernel mutexes are sleepable locks, it is path (ii) that
makes them more practically a hybrid type. By simply not interrupting a
task and busy-waiting for a few cycles instead of immediately sleeping,
the performance of this lock has been seen to significantly improve a
number of workloads. Note that this technique is also used for rw-semaphores.

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

## Semantics

The mutex subsystem checks and enforces the following rules:

- Only one task can hold the mutex at a time.

- Only the owner can unlock the mutex.

- Multiple unlocks are not permitted.

- Recursive locking/unlocking is not permitted.

- A mutex must only be initialized via the API (see below).

- A task may not exit with a mutex held.

- Memory areas where held locks reside must not be freed.

- Held mutexes must not be reinitialized.

- Mutexes may not be used in hardware or software interrupt
  contexts such as tasklets and timers.

These semantics are fully enforced when CONFIG DEBUG_MUTEXES is enabled.
In addition, the mutex debugging code also implements a number of other
features that make lock debugging easier and faster:

- Uses symbolic names of mutexes, whenever they are printed
  in debug output.

- Point-of-acquire tracking, symbolic lookup of function names,
  list of all locks held in the system, printout of them.

- Owner tracking.

- Detects self-recursing locks and prints out all relevant info.

- Detects multi-task circular deadlocks and prints out all affected
  locks and tasks (and only those tasks).

Mutexes - and most other sleeping locks like rwsems - do not provide an
implicit reference for the memory they occupy, which reference is released
with mutex_unlock().

By contrast, `spin_unlock()` and `completion_done()` can be used to guarantee
that the lock implementation no longer accesses the memory after releasing
the lock.

mutex_unlock() may access the mutex structure even after it has internally
released the lock already - so it's not safe for another context to
acquire the mutex and assume that the mutex_unlock() context is not using
the structure anymore.

The mutex user must ensure that the mutex is not destroyed while a
release operation is still in progress - in other words, callers of
mutex_unlock() must ensure that the mutex stays alive until mutex_unlock()
has returned.

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

## Interfaces

Statically define the mutex:

```c
DEFINE_MUTEX(name);
```

Dynamically initialize the mutex:

```c
mutex_init(mutex);
```

Acquire the mutex, uninterruptible:

```c
void mutex_lock(struct mutex *lock);
void mutex_lock_nested(struct mutex *lock, unsigned int subclass);
int  mutex_trylock(struct mutex *lock);
```

Acquire the mutex, interruptible:

```c
int mutex_lock_interruptible_nested(struct mutex *lock,
                                    unsigned int subclass);
int mutex_lock_interruptible(struct mutex *lock);
```

Acquire the mutex, interruptible, if dec to 0:

```c
int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock);
```

Unlock the mutex:

```c
void mutex_unlock(struct mutex *lock);
```

Test if the mutex is taken:

```c
int mutex_is_locked(struct mutex *lock);
```

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

## Disadvantages

Unlike its original design and purpose, 'struct mutex' is among the largest
locks in the kernel. E.g: on x86-64 it is 32 bytes, where 'struct semaphore'
is 24 bytes and rw_semaphore is 40 bytes. Larger structure sizes mean more CPU
cache and memory footprint.

<a id="rst-when-to-use-mutexes"></a>

## When to use mutexes

Unless the strict semantics of mutexes are unsuitable and/or the critical
region prevents the lock from being shared, always prefer them to any other
locking primitive.

## Credits

started by Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;

updated by Davidlohr Bueso &lt;[davidlohr@hp.com](<mailto:davidlohr@hp.com>)&gt;

---

# RT-mutexes and priority inheritance

_Peios Kernel / Internals / Locking_

> Priority inheritance in RT-mutexes, including ownership and waiter states.

<a id="rst-rt-mutex-subsystem-with-pi-support"></a>

RT-mutexes with priority inheritance are used to support PI-futexes,
which enable pthread_mutex_t priority inheritance attributes
(PTHREAD_PRIO_INHERIT). \[See [Documentation/locking/pi-futex.rst](/kernel/internals/locking/pi-futex.md) for more details
about PI-futexes.\]

This technology was developed in the -rt tree and streamlined for
pthread_mutex support.

<a id="rst-basic-principles"></a>

## Basic principles:

RT-mutexes extend the semantics of simple mutexes by the priority
inheritance protocol.

A low priority owner of a rt-mutex inherits the priority of a higher
priority waiter until the rt-mutex is released. If the temporarily
boosted owner blocks on a rt-mutex itself it propagates the priority
boosting to the owner of the other rt_mutex it gets blocked on. The
priority boosting is immediately removed once the rt_mutex has been
unlocked.

This approach allows us to shorten the block of high-prio tasks on
mutexes which protect shared resources. Priority inheritance is not a
magic bullet for poorly designed applications, but it allows
well-designed applications to use userspace locks in critical parts of
an high priority thread, without losing determinism.

The enqueueing of the waiters into the rtmutex waiter tree is done in
priority order. For same priorities FIFO order is chosen. For each
rtmutex, only the top priority waiter is enqueued into the owner's
priority waiters tree. This tree too queues in priority order. Whenever
the top priority waiter of a task changes (for example it timed out or
got a signal), the priority of the owner task is readjusted. The
priority enqueueing is handled by "pi_waiters".

RT-mutexes are optimized for fastpath operations and have no internal
locking overhead when locking an uncontended mutex or unlocking a mutex
without waiters. The optimized fastpath operations require cmpxchg
support. \[If that is not available then the rt-mutex internal spinlock
is used\]

The state of the rt-mutex is tracked via the owner field of the rt-mutex
structure:

lock-&gt;owner holds the task_struct pointer of the owner. Bit 0 is used to
keep track of the "lock has waiters" state:

<table>
<thead>
<tr>
<th><p>owner</p></th>
<th><p>bit0</p></th>
<th><p>Notes</p></th>
</tr>
</thead>
<tbody>
<tr>
<td><p>NULL</p></td>
<td><p>0</p></td>
<td><p>lock is free (fast acquire possible)</p></td>
</tr>
<tr>
<td><p>NULL</p></td>
<td><p>1</p></td>
<td><p>lock is free and has waiters and the top waiter
is going to take the lock <a href="#rst-footnote-1">1</a></p></td>
</tr>
<tr>
<td><p>taskpointer</p></td>
<td><p>0</p></td>
<td><p>lock is held (fast release possible)</p></td>
</tr>
<tr>
<td><p>taskpointer</p></td>
<td><p>1</p></td>
<td><p>lock is held and has waiters <a href="#rst-footnote-2">2</a></p></td>
</tr>
</tbody>
</table>

The fast atomic compare exchange based acquire and release is only
possible when bit 0 of lock-&gt;owner is 0.

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

**[1]** It also can be a transitional state when grabbing the lock
with -&gt;wait_lock is held. To prevent any fast path cmpxchg to the lock,
we need to set the bit0 before looking at the lock, and the owner may
be NULL in this small time, hence this can be a transitional state.

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

**[2]** There is a small time when bit 0 is set but there are no
waiters. This can happen when grabbing the lock in the slow path.
To prevent a cmpxchg of the owner releasing the lock, we need to
set this bit before looking at the lock.

BTW, there is still technically a "Pending Owner", it's just not called
that anymore. The pending owner happens to be the top_waiter of a lock
that has no owner and has been woken up to grab the lock.

---

# RT-mutex implementation

_Peios Kernel / Internals / Locking_

> Priority-inheritance chains, waiter trees, and the RT-mutex locking algorithm.

<a id="rst-rt-mutex-implementation-design"></a>

Copyright (c) 2006 Steven Rostedt

Licensed under the GNU Free Documentation License, Version 1.2

This document tries to describe the design of the rtmutex.c implementation.
It doesn't describe the reasons why rtmutex.c exists. For that please see
[Documentation/locking/rt-mutex.rst](/kernel/internals/locking/rt-mutex.md).  Although this document does explain problems
that happen without this code, but that is in the concept to understand
what the code actually is doing.

The goal of this document is to help others understand the priority
inheritance (PI) algorithm that is used, as well as reasons for the
decisions that were made to implement PI in the manner that was done.

<a id="rst-unbounded-priority-inversion"></a>

## Unbounded Priority Inversion

Priority inversion is when a lower priority process executes while a higher
priority process wants to run.  This happens for several reasons, and
most of the time it can't be helped.  Anytime a high priority process wants
to use a resource that a lower priority process has (a mutex for example),
the high priority process must wait until the lower priority process is done
with the resource.  This is a priority inversion.  What we want to prevent
is something called unbounded priority inversion.  That is when the high
priority process is prevented from running by a lower priority process for
an undetermined amount of time.

The classic example of unbounded priority inversion is where you have three
processes, let's call them processes A, B, and C, where A is the highest
priority process, C is the lowest, and B is in between. A tries to grab a lock
that C owns and must wait and lets C run to release the lock. But in the
meantime, B executes, and since B is of a higher priority than C, it preempts C,
but by doing so, it is in fact preempting A which is a higher priority process.
Now there's no way of knowing how long A will be sleeping waiting for C
to release the lock, because for all we know, B is a CPU hog and will
never give C a chance to release the lock.  This is called unbounded priority
inversion.

Here's a little ASCII art to show the problem:

```text
   grab lock L1 (owned by C)
     |
A ---+
        C preempted by B
          |
C    +----+

B         +-------->
                B now keeps A from running.
```

<a id="rst-priority-inheritance-pi"></a>

## Priority Inheritance (PI)

There are several ways to solve this issue, but other ways are out of scope
for this document.  Here we only discuss PI.

PI is where a process inherits the priority of another process if the other
process blocks on a lock owned by the current process.  To make this easier
to understand, let's use the previous example, with processes A, B, and C again.

This time, when A blocks on the lock owned by C, C would inherit the priority
of A.  So now if B becomes runnable, it would not preempt C, since C now has
the high priority of A.  As soon as C releases the lock, it loses its
inherited priority, and A then can continue with the resource that C had.

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

## Terminology

Here I explain some terminology that is used in this document to help describe
the design that is used to implement PI.

- **PI chain**

  - The PI chain is an ordered series of locks and processes that cause
    processes to inherit priorities from a previous process that is
    blocked on one of its locks.  This is described in more detail
    later in this document.

- **mutex**

  - In this document, to differentiate from locks that implement
    PI and spin locks that are used in the PI code, from now on
    the PI locks will be called a mutex.

- **lock**

  - In this document from now on, I will use the term lock when
    referring to spin locks that are used to protect parts of the PI
    algorithm.  These locks disable preemption for UP (when
    CONFIG_PREEMPT is enabled) and on SMP prevents multiple CPUs from
    entering critical sections simultaneously.

- **spin lock**

  - Same as lock above.

- **waiter**

  - A waiter is a struct that is stored on the stack of a blocked
    process.  Since the scope of the waiter is within the code for
    a process being blocked on the mutex, it is fine to allocate
    the waiter on the process's stack (local variable).  This
    structure holds a pointer to the task, as well as the mutex that
    the task is blocked on.  It also has rbtree node structures to
    place the task in the waiters rbtree of a mutex as well as the
    pi_waiters rbtree of a mutex owner task (described below).

    waiter is sometimes used in reference to the task that is waiting
    on a mutex. This is the same as waiter-&gt;task.

- **waiters**

  - A list of processes that are blocked on a mutex.

- **top waiter**

  - The highest priority process waiting on a specific mutex.

- **top pi waiter**

  - The highest priority process waiting on one of the mutexes
    that a specific process owns.

- **Note:**

  task and process are used interchangeably in this document, mostly to
  differentiate between two processes that are being described together.

<a id="rst-pi-chain"></a>

## PI chain

The PI chain is a list of processes and mutexes that may cause priority
inheritance to take place.  Multiple chains may converge, but a chain
would never diverge, since a process can't be blocked on more than one
mutex at a time.

Example:

```text
Process:  A, B, C, D, E
Mutexes:  L1, L2, L3, L4

A owns: L1
        B blocked on L1
        B owns L2
               C blocked on L2
               C owns L3
                      D blocked on L3
                      D owns L4
                             E blocked on L4
```

The chain would be:

```text
E->L4->D->L3->C->L2->B->L1->A
```

To show where two chains merge, we could add another process F and
another mutex L5 where B owns L5 and F is blocked on mutex L5.

The chain for F would be:

```text
F->L5->B->L1->A
```

Since a process may own more than one mutex, but never be blocked on more than
one, the chains merge.

Here we show both chains:

```text
E->L4->D->L3->C->L2-+
                    |
                    +->B->L1->A
                    |
              F->L5-+
```

For PI to work, the processes at the right end of these chains (or we may
also call it the Top of the chain) must be equal to or higher in priority
than the processes to the left or below in the chain.

Also since a mutex may have more than one process blocked on it, we can
have multiple chains merge at mutexes.  If we add another process G that is
blocked on mutex L2:

```text
G->L2->B->L1->A
```

And once again, to show how this can grow I will show the merging chains
again:

```text
E->L4->D->L3->C-+
                +->L2-+
                |     |
              G-+     +->B->L1->A
                      |
                F->L5-+
```

If process G has the highest priority in the chain, then all the tasks up
the chain (A and B in this example), must have their priorities increased
to that of G.

<a id="rst-mutex-waiters-tree"></a>

## Mutex Waiters Tree

Every mutex keeps track of all the waiters that are blocked on itself. The
mutex has a rbtree to store these waiters by priority.  This tree is protected
by a spin lock that is located in the struct of the mutex. This lock is called
wait_lock.

<a id="rst-task-pi-tree"></a>

## Task PI Tree

To keep track of the PI chains, each process has its own PI rbtree.  This is
a tree of all top waiters of the mutexes that are owned by the process.
Note that this tree only holds the top waiters and not all waiters that are
blocked on mutexes owned by the process.

The top of the task's PI tree is always the highest priority task that
is waiting on a mutex that is owned by the task.  So if the task has
inherited a priority, it will always be the priority of the task that is
at the top of this tree.

This tree is stored in the task structure of a process as a rbtree called
pi_waiters.  It is protected by a spin lock also in the task structure,
called pi_lock.  This lock may also be taken in interrupt context, so when
locking the pi_lock, interrupts must be disabled.

<a id="rst-depth-of-the-pi-chain"></a>

## Depth of the PI Chain

The maximum depth of the PI chain is not dynamic, and could actually be
defined.  But is very complex to figure it out, since it depends on all
the nesting of mutexes.  Let's look at the example where we have 3 mutexes,
L1, L2, and L3, and four separate functions func1, func2, func3 and func4.
The following shows a locking order of L1-&gt;L2-&gt;L3, but may not actually
be directly nested that way:

```c
void func1(void)
{
      mutex_lock(L1);

      /* do anything */

      mutex_unlock(L1);
}

void func2(void)
{
      mutex_lock(L1);
      mutex_lock(L2);

      /* do something */

      mutex_unlock(L2);
      mutex_unlock(L1);
}

void func3(void)
{
      mutex_lock(L2);
      mutex_lock(L3);

      /* do something else */

      mutex_unlock(L3);
      mutex_unlock(L2);
}

void func4(void)
{
      mutex_lock(L3);

      /* do something again */

      mutex_unlock(L3);
}
```

Now we add 4 processes that run each of these functions separately.
Processes A, B, C, and D which run functions func1, func2, func3 and func4
respectively, and such that D runs first and A last.  With D being preempted
in func4 in the "do something again" area, we have a locking that follows:

```text
D owns L3
       C blocked on L3
       C owns L2
              B blocked on L2
              B owns L1
                     A blocked on L1

And thus we have the chain A->L1->B->L2->C->L3->D.
```

This gives us a PI depth of 4 (four processes), but looking at any of the
functions individually, it seems as though they only have at most a locking
depth of two.  So, although the locking depth is defined at compile time,
it still is very difficult to find the possibilities of that depth.

Now since mutexes can be defined by user-land applications, we don't want a DOS
type of application that nests large amounts of mutexes to create a large
PI chain, and have the code holding spin locks while looking at a large
amount of data.  So to prevent this, the implementation not only implements
a maximum lock depth, but also only holds at most two different locks at a
time, as it walks the PI chain.  More about this below.

<a id="rst-mutex-owner-and-flags"></a>

## Mutex owner and flags

The mutex structure contains a pointer to the owner of the mutex.  If the
mutex is not owned, this owner is set to NULL.  Since all architectures
have the task structure on at least a two byte alignment (and if this is
not true, the rtmutex.c code will be broken\!), this allows for the least
significant bit to be used as a flag.  Bit 0 is used as the "Has Waiters"
flag. It's set whenever there are waiters on a mutex.

See [Documentation/locking/rt-mutex.rst](/kernel/internals/locking/rt-mutex.md) for further details.

<a id="rst-cmpxchg-tricks"></a>

## cmpxchg Tricks

Some architectures implement an atomic cmpxchg (Compare and Exchange).  This
is used (when applicable) to keep the fast path of grabbing and releasing
mutexes short.

cmpxchg is basically the following function performed atomically:

```c
unsigned long _cmpxchg(unsigned long *A, unsigned long *B, unsigned long *C)
{
      unsigned long T = *A;
      if (*A == *B) {
              *A = *C;
      }
      return T;
}
#define cmpxchg(a,b,c) _cmpxchg(&a,&b,&c)
```

This is really nice to have, since it allows you to only update a variable
if the variable is what you expect it to be.  You know if it succeeded if
the return value (the old value of A) is equal to B.

The macro rt_mutex_cmpxchg is used to try to lock and unlock mutexes. If
the architecture does not support CMPXCHG, then this macro is simply set
to fail every time.  But if CMPXCHG is supported, then this will
help out extremely to keep the fast path short.

The use of rt_mutex_cmpxchg with the flags in the owner field help optimize
the system for architectures that support it.  This will also be explained
later in this document.

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

## Priority adjustments

The implementation of the PI code in rtmutex.c has several places that a
process must adjust its priority.  With the help of the pi_waiters of a
process this is rather easy to know what needs to be adjusted.

The functions implementing the task adjustments are rt_mutex_adjust_prio
and rt_mutex_setprio. rt_mutex_setprio is only used in rt_mutex_adjust_prio.

rt_mutex_adjust_prio examines the priority of the task, and the highest
priority process that is waiting any of mutexes owned by the task. Since
the pi_waiters of a task holds an order by priority of all the top waiters
of all the mutexes that the task owns, we simply need to compare the top
pi waiter to its own normal/deadline priority and take the higher one.
Then rt_mutex_setprio is called to adjust the priority of the task to the
new priority. Note that rt_mutex_setprio is defined in kernel/sched/core.c
to implement the actual change in priority.

- **Note:**

  For the "prio" field in task_struct, the lower the number, the
  higher the priority. A "prio" of 5 is of higher priority than a
  "prio" of 10.

It is interesting to note that rt_mutex_adjust_prio can either increase
or decrease the priority of the task.  In the case that a higher priority
process has just blocked on a mutex owned by the task, rt_mutex_adjust_prio
would increase/boost the task's priority.  But if a higher priority task
were for some reason to leave the mutex (timeout or signal), this same function
would decrease/unboost the priority of the task.  That is because the pi_waiters
always contains the highest priority task that is waiting on a mutex owned
by the task, so we only need to compare the priority of that top pi waiter
to the normal priority of the given task.

<a id="rst-high-level-overview-of-the-pi-chain-walk"></a>

## High level overview of the PI chain walk

The PI chain walk is implemented by the function rt_mutex_adjust_prio_chain.

The implementation has gone through several iterations, and has ended up
with what we believe is the best.  It walks the PI chain by only grabbing
at most two locks at a time, and is very efficient.

The rt_mutex_adjust_prio_chain can be used either to boost or lower process
priorities.

rt_mutex_adjust_prio_chain is called with a task to be checked for PI
(de)boosting (the owner of a mutex that a process is blocking on), a flag to
check for deadlocking, the mutex that the task owns, a pointer to a waiter
that is the process's waiter struct that is blocked on the mutex (although this
parameter may be NULL for deboosting), a pointer to the mutex on which the task
is blocked, and a top_task as the top waiter of the mutex.

For this explanation, I will not mention deadlock detection. This explanation
will try to stay at a high level.

When this function is called, there are no locks held.  That also means
that the state of the owner and lock can change when entered into this function.

Before this function is called, the task has already had rt_mutex_adjust_prio
performed on it.  This means that the task is set to the priority that it
should be at, but the rbtree nodes of the task's waiter have not been updated
with the new priorities, and this task may not be in the proper locations
in the pi_waiters and waiters trees that the task is blocked on. This function
solves all that.

The main operation of this function is summarized by Thomas Gleixner in
rtmutex.c. See the 'Chain walk basics and protection scope' comment for further
details.

<a id="rst-taking-of-a-mutex-the-walk-through"></a>

## Taking of a mutex (The walk through)

OK, now let's take a look at the detailed walk through of what happens when
taking a mutex.

The first thing that is tried is the fast taking of the mutex.  This is
done when we have CMPXCHG enabled (otherwise the fast taking automatically
fails).  Only when the owner field of the mutex is NULL can the lock be
taken with the CMPXCHG and nothing else needs to be done.

If there is contention on the lock, we go about the slow path
(rt_mutex_slowlock).

The slow path function is where the task's waiter structure is created on
the stack.  This is because the waiter structure is only needed for the
scope of this function.  The waiter structure holds the nodes to store
the task on the waiters tree of the mutex, and if need be, the pi_waiters
tree of the owner.

The wait_lock of the mutex is taken since the slow path of unlocking the
mutex also takes this lock.

We then call try_to_take_rt_mutex.  This is where the architecture that
does not implement CMPXCHG would always grab the lock (if there's no
contention).

try_to_take_rt_mutex is used every time the task tries to grab a mutex in the
slow path.  The first thing that is done here is an atomic setting of
the "Has Waiters" flag of the mutex's owner field. By setting this flag
now, the current owner of the mutex being contended for can't release the mutex
without going into the slow unlock path, and it would then need to grab the
wait_lock, which this code currently holds. So setting the "Has Waiters" flag
forces the current owner to synchronize with this code.

The lock is taken if the following are true:

1. The lock has no owner

2. The current task is the highest priority against all other
   waiters of the lock

If the task succeeds to acquire the lock, then the task is set as the
owner of the lock, and if the lock still has waiters, the top_waiter
(highest priority task waiting on the lock) is added to this task's
pi_waiters tree.

If the lock is not taken by try_to_take_rt_mutex(), then the
task_blocks_on_rt_mutex() function is called. This will add the task to
the lock's waiter tree and propagate the pi chain of the lock as well
as the lock's owner's pi_waiters tree. This is described in the next
section.

<a id="rst-task-blocks-on-mutex"></a>

## Task blocks on mutex

The accounting of a mutex and process is done with the waiter structure of
the process.  The "task" field is set to the process, and the "lock" field
to the mutex.  The rbtree node of waiter are initialized to the processes
current priority.

Since the wait_lock was taken at the entry of the slow lock, we can safely
add the waiter to the task waiter tree.  If the current process is the
highest priority process currently waiting on this mutex, then we remove the
previous top waiter process (if it exists) from the pi_waiters of the owner,
and add the current process to that tree.  Since the pi_waiter of the owner
has changed, we call rt_mutex_adjust_prio on the owner to see if the owner
should adjust its priority accordingly.

If the owner is also blocked on a lock, and had its pi_waiters changed
(or deadlock checking is on), we unlock the wait_lock of the mutex and go ahead
and run rt_mutex_adjust_prio_chain on the owner, as described earlier.

Now all locks are released, and if the current process is still blocked on a
mutex (waiter "task" field is not NULL), then we go to sleep (call schedule).

<a id="rst-waking-up-in-the-loop"></a>

## Waking up in the loop

- **The task can then wake up for a couple of reasons:**

  1. The previous lock owner released the lock, and the task now is top_waiter

  2. we received a signal or timeout

In both cases, the task will try again to acquire the lock. If it
does, then it will take itself off the waiters tree and set itself back
to the TASK_RUNNING state.

In first case, if the lock was acquired by another task before this task
could get the lock, then it will go back to sleep and wait to be woken again.

The second case is only applicable for tasks that are grabbing a mutex
that can wake up before getting the lock, either due to a signal or
a timeout (i.e. rt_mutex_timed_futex_lock()). When woken, it will try to
take the lock again, if it succeeds, then the task will return with the
lock held, otherwise it will return with -EINTR if the task was woken
by a signal, or -ETIMEDOUT if it timed out.

<a id="rst-unlocking-the-mutex"></a>

## Unlocking the Mutex

The unlocking of a mutex also has a fast path for those architectures with
CMPXCHG.  Since the taking of a mutex on contention always sets the
"Has Waiters" flag of the mutex's owner, we use this to know if we need to
take the slow path when unlocking the mutex.  If the mutex doesn't have any
waiters, the owner field of the mutex would equal the current process and
the mutex can be unlocked by just replacing the owner field with NULL.

If the owner field has the "Has Waiters" bit set (or CMPXCHG is not available),
the slow unlock path is taken.

The first thing done in the slow unlock path is to take the wait_lock of the
mutex.  This synchronizes the locking and unlocking of the mutex.

A check is made to see if the mutex has waiters or not.  On architectures that
do not have CMPXCHG, this is the location that the owner of the mutex will
determine if a waiter needs to be awoken or not.  On architectures that
do have CMPXCHG, that check is done in the fast path, but it is still needed
in the slow path too.  If a waiter of a mutex woke up because of a signal
or timeout between the time the owner failed the fast path CMPXCHG check and
the grabbing of the wait_lock, the mutex may not have any waiters, thus the
owner still needs to make this check. If there are no waiters then the mutex
owner field is set to NULL, the wait_lock is released and nothing more is
needed.

If there are waiters, then we need to wake one up.

On the wake up code, the pi_lock of the current owner is taken.  The top
waiter of the lock is found and removed from the waiters tree of the mutex
as well as the pi_waiters tree of the current owner. The "Has Waiters" bit is
marked to prevent lower priority tasks from stealing the lock.

Finally we unlock the pi_lock of the pending owner and wake it up.

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

## Contact

For updates on this document, please email Steven Rostedt &lt;[rostedt@goodmis.org](<mailto:rostedt@goodmis.org>)&gt;

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

## Credits

Author:  Steven Rostedt &lt;[rostedt@goodmis.org](<mailto:rostedt@goodmis.org>)&gt;

Updated: Alex Shi &lt;[alex.shi@linaro.org](<mailto:alex.shi@linaro.org>)&gt; - 7/6/2017

- **Original Reviewers:**

  Ingo Molnar, Thomas Gleixner, Thomas Duetsch, and
  Randy Dunlap

Update (7/6/2017) Reviewers: Steven Rostedt and Sebastian Siewior

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

## Updates

This document was originally written for 2.6.17-rc3-mm1
was updated on 4.12

---

# Wound/wait mutexes

_Peios Kernel / Internals / Locking_

> Avoiding deadlocks when acquiring multiple buffer locks with wait/die and wound/wait algorithms.

<a id="rst-wound-wait-deadlock-proof-mutex-design"></a>

Please read [mutex-design.rst](/kernel/internals/locking/mutex-design.md) first, as it applies to wait/wound mutexes too.

<a id="rst-motivation-for-ww-mutexes"></a>

## Motivation for WW-Mutexes

GPU's do operations that commonly involve many buffers.  Those buffers
can be shared across contexts/processes, exist in different memory
domains (for example VRAM vs system memory), and so on.  And with
PRIME / dmabuf, they can even be shared across devices.  So there are
a handful of situations where the driver needs to wait for buffers to
become ready.  If you think about this in terms of waiting on a buffer
mutex for it to become available, this presents a problem because
there is no way to guarantee that buffers appear in a execbuf/batch in
the same order in all contexts.  That is directly under control of
userspace, and a result of the sequence of GL calls that an application
makes.  Which results in the potential for deadlock.  The problem gets
more complex when you consider that the kernel may need to migrate the
buffer(s) into VRAM before the GPU operates on the buffer(s), which
may in turn require evicting some other buffers (and you don't want to
evict other buffers which are already queued up to the GPU), but for a
simplified understanding of the problem you can ignore this.

The algorithm that the TTM graphics subsystem came up with for dealing with
this problem is quite simple.  For each group of buffers (execbuf) that need
to be locked, the caller would be assigned a unique reservation id/ticket,
from a global counter.  In case of deadlock while locking all the buffers
associated with a execbuf, the one with the lowest reservation ticket (i.e.
the oldest task) wins, and the one with the higher reservation id (i.e. the
younger task) unlocks all of the buffers that it has already locked, and then
tries again.

In the RDBMS literature, a reservation ticket is associated with a transaction.
and the deadlock handling approach is called Wait-Die. The name is based on
the actions of a locking thread when it encounters an already locked mutex.
If the transaction holding the lock is younger, the locking transaction waits.
If the transaction holding the lock is older, the locking transaction backs off
and dies. Hence Wait-Die.
There is also another algorithm called Wound-Wait:
If the transaction holding the lock is younger, the locking transaction
wounds the transaction holding the lock, requesting it to die.
If the transaction holding the lock is older, it waits for the other
transaction. Hence Wound-Wait.
The two algorithms are both fair in that a transaction will eventually succeed.
However, the Wound-Wait algorithm is typically stated to generate fewer backoffs
compared to Wait-Die, but is, on the other hand, associated with more work than
Wait-Die when recovering from a backoff. Wound-Wait is also a preemptive
algorithm in that transactions are wounded by other transactions, and that
requires a reliable way to pick up the wounded condition and preempt the
running transaction. Note that this is not the same as process preemption. A
Wound-Wait transaction is considered preempted when it dies (returning
-EDEADLK) following a wound.

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

## Concepts

Compared to normal mutexes two additional concepts/objects show up in the lock
interface for w/w mutexes:

Acquire context: To ensure eventual forward progress it is important that a task
trying to acquire locks doesn't grab a new reservation id, but keeps the one it
acquired when starting the lock acquisition. This ticket is stored in the
acquire context. Furthermore the acquire context keeps track of debugging state
to catch w/w mutex interface abuse. An acquire context is representing a
transaction.

W/w class: In contrast to normal mutexes the lock class needs to be explicit for
w/w mutexes, since it is required to initialize the acquire context. The lock
class also specifies what algorithm to use, Wound-Wait or Wait-Die.

Furthermore there are three different class of w/w lock acquire functions:

- Normal lock acquisition with a context, using ww_mutex_lock.

- Slowpath lock acquisition on the contending lock, used by the task that just
  killed its transaction after having dropped all already acquired locks.
  These functions have the \_slow postfix.

  From a simple semantics point-of-view the \_slow functions are not strictly
  required, since simply calling the normal ww_mutex_lock functions on the
  contending lock (after having dropped all other already acquired locks) will
  work correctly. After all if no other ww mutex has been acquired yet there's
  no deadlock potential and hence the ww_mutex_lock call will block and not
  prematurely return -EDEADLK. The advantage of the \_slow functions is in
  interface safety:

  - ww_mutex_lock has a \__must_check int return type, whereas ww_mutex_lock_slow
    has a void return type. Note that since ww mutex code needs loops/retries
    anyway the \__must_check doesn't result in spurious warnings, even though the
    very first lock operation can never fail.

  - When full debugging is enabled ww_mutex_lock_slow checks that all acquired
    ww mutex have been released (preventing deadlocks) and makes sure that we
    block on the contending lock (preventing spinning through the -EDEADLK
    slowpath until the contended lock can be acquired).

- Functions to only acquire a single w/w mutex, which results in the exact same
  semantics as a normal mutex. This is done by calling ww_mutex_lock with a NULL
  context.

  Again this is not strictly required. But often you only want to acquire a
  single lock in which case it's pointless to set up an acquire context (and so
  better to avoid grabbing a deadlock avoidance ticket).

Of course, all the usual variants for handling wake-ups due to signals are also
provided.

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

## Usage

The algorithm (Wait-Die vs Wound-Wait) is chosen by using either
DEFINE_WW_CLASS() (Wound-Wait) or DEFINE_WD_CLASS() (Wait-Die)
As a rough rule of thumb, use Wound-Wait iff you
expect the number of simultaneous competing transactions to be typically small,
and you want to reduce the number of rollbacks.

Three different ways to acquire locks within the same w/w class. Common
definitions for methods \#1 and \#2:

```c
static DEFINE_WW_CLASS(ww_class);

struct obj {
      struct ww_mutex lock;
      /* obj data */
};

struct obj_entry {
      struct list_head head;
      struct obj *obj;
};
```

Method 1, using a list in execbuf-&gt;buffers that's not allowed to be reordered.
This is useful if a list of required objects is already tracked somewhere.
Furthermore the lock helper can use propagate the -EALREADY return code back to
the caller as a signal that an object is twice on the list. This is useful if
the list is constructed from userspace input and the ABI requires userspace to
not have duplicate entries (e.g. for a gpu commandbuffer submission ioctl):

```c
int lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
{
      struct obj *res_obj = NULL;
      struct obj_entry *contended_entry = NULL;
      struct obj_entry *entry;

      ww_acquire_init(ctx, &ww_class);

retry:
      list_for_each_entry (entry, list, head) {
              if (entry->obj == res_obj) {
                      res_obj = NULL;
                      continue;
              }
              ret = ww_mutex_lock(&entry->obj->lock, ctx);
              if (ret < 0) {
                      contended_entry = entry;
                      goto err;
              }
      }

      ww_acquire_done(ctx);
      return 0;

err:
      list_for_each_entry_continue_reverse (entry, list, head)
              ww_mutex_unlock(&entry->obj->lock);

      if (res_obj)
              ww_mutex_unlock(&res_obj->lock);

      if (ret == -EDEADLK) {
              /* we lost out in a seqno race, lock and retry.. */
              ww_mutex_lock_slow(&contended_entry->obj->lock, ctx);
              res_obj = contended_entry->obj;
              goto retry;
      }
      ww_acquire_fini(ctx);

      return ret;
}
```

Method 2, using a list in execbuf-&gt;buffers that can be reordered. Same semantics
of duplicate entry detection using -EALREADY as method 1 above. But the
list-reordering allows for a bit more idiomatic code:

```c
int lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
{
      struct obj_entry *entry, *entry2;

      ww_acquire_init(ctx, &ww_class);

      list_for_each_entry (entry, list, head) {
              ret = ww_mutex_lock(&entry->obj->lock, ctx);
              if (ret < 0) {
                      entry2 = entry;

                      list_for_each_entry_continue_reverse (entry2, list, head)
                              ww_mutex_unlock(&entry2->obj->lock);

                      if (ret != -EDEADLK) {
                              ww_acquire_fini(ctx);
                              return ret;
                      }

                      /* we lost out in a seqno race, lock and retry.. */
                      ww_mutex_lock_slow(&entry->obj->lock, ctx);

                      /*
                       * Move buf to head of the list, this will point
                       * buf->next to the first unlocked entry,
                       * restarting the for loop.
                       */
                      list_del(&entry->head);
                      list_add(&entry->head, list);
              }
      }

      ww_acquire_done(ctx);
      return 0;
}
```

Unlocking works the same way for both methods \#1 and \#2:

```c
void unlock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
{
      struct obj_entry *entry;

      list_for_each_entry (entry, list, head)
              ww_mutex_unlock(&entry->obj->lock);

      ww_acquire_fini(ctx);
}
```

Method 3 is useful if the list of objects is constructed ad-hoc and not upfront,
e.g. when adjusting edges in a graph where each node has its own ww_mutex lock,
and edges can only be changed when holding the locks of all involved nodes. w/w
mutexes are a natural fit for such a case for two reasons:

- They can handle lock-acquisition in any order which allows us to start walking
  a graph from a starting point and then iteratively discovering new edges and
  locking down the nodes those edges connect to.

- Due to the -EALREADY return code signalling that a given objects is already
  held there's no need for additional book-keeping to break cycles in the graph
  or keep track off which looks are already held (when using more than one node
  as a starting point).

Note that this approach differs in two important ways from the above methods:

- Since the list of objects is dynamically constructed (and might very well be
  different when retrying due to hitting the -EDEADLK die condition) there's
  no need to keep any object on a persistent list when it's not locked. We can
  therefore move the list_head into the object itself.

- On the other hand the dynamic object list construction also means that the -EALREADY return
  code can't be propagated.

Note also that methods \#1 and \#2 and method \#3 can be combined, e.g. to first lock a
list of starting nodes (passed in from userspace) using one of the above
methods. And then lock any additional objects affected by the operations using
method \#3 below. The backoff/retry procedure will be a bit more involved, since
when the dynamic locking step hits -EDEADLK we also need to unlock all the
objects acquired with the fixed list. But the w/w mutex debug checks will catch
any interface misuse for these cases.

Also, method 3 can't fail the lock acquisition step since it doesn't return
-EALREADY. Of course this would be different when using the \_interruptible
variants, but that's outside of the scope of these examples here:

```c
struct obj {
      struct ww_mutex ww_mutex;
      struct list_head locked_list;
};

static DEFINE_WW_CLASS(ww_class);

void __unlock_objs(struct list_head *list)
{
      struct obj *entry, *temp;

      list_for_each_entry_safe (entry, temp, list, locked_list) {
              /* need to do that before unlocking, since only the current lock holder is
              allowed to use object */
              list_del(&entry->locked_list);
              ww_mutex_unlock(entry->ww_mutex)
      }
}

void lock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
{
      struct obj *obj;

      ww_acquire_init(ctx, &ww_class);

retry:
      /* re-init loop start state */
      loop {
              /* magic code which walks over a graph and decides which objects
               * to lock */

              ret = ww_mutex_lock(obj->ww_mutex, ctx);
              if (ret == -EALREADY) {
                      /* we have that one already, get to the next object */
                      continue;
              }
              if (ret == -EDEADLK) {
                      __unlock_objs(list);

                      ww_mutex_lock_slow(obj, ctx);
                      list_add(&entry->locked_list, list);
                      goto retry;
              }

              /* locked a new object, add it to the list */
              list_add_tail(&entry->locked_list, list);
      }

      ww_acquire_done(ctx);
      return 0;
}

void unlock_objs(struct list_head *list, struct ww_acquire_ctx *ctx)
{
      __unlock_objs(list);
      ww_acquire_fini(ctx);
}
```

Method 4: Only lock one single objects. In that case deadlock detection and
prevention is obviously overkill, since with grabbing just one lock you can't
produce a deadlock within just one class. To simplify this case the w/w mutex
api can be used with a NULL context.

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

## Implementation Details

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

### Design:

ww_mutex currently encapsulates a struct mutex, this means no extra overhead for
normal mutex locks, which are far more common. As such there is only a small
increase in code size if wait/wound mutexes are not used.

We maintain the following invariants for the wait list:

1. Waiters with an acquire context are sorted by stamp order; waiters
   without an acquire context are interspersed in FIFO order.

2. For Wait-Die, among waiters with contexts, only the first one can have
   other locks acquired already (ctx-&gt;acquired &gt; 0). Note that this waiter
   may come after other waiters without contexts in the list.

The Wound-Wait preemption is implemented with a lazy-preemption scheme:
The wounded status of the transaction is checked only when there is
contention for a new lock and hence a true chance of deadlock. In that
situation, if the transaction is wounded, it backs off, clears the
wounded status and retries. A great benefit of implementing preemption in
this way is that the wounded transaction can identify a contending lock to
wait for before restarting the transaction. Just blindly restarting the
transaction would likely make the transaction end up in a situation where
it would have to back off again.

In general, not much contention is expected. The locks are typically used to
serialize access to resources for devices, and optimization focus should
therefore be directed towards the uncontended cases.

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

### Lockdep:

Special care has been taken to warn for as many cases of api abuse
as possible. Some common api abuses will be caught with
CONFIG_DEBUG_MUTEXES, but CONFIG_PROVE_LOCKING is recommended.

- **Some of the errors which will be warned about:**

  - Forgetting to call ww_acquire_fini or ww_acquire_init.

  - Attempting to lock more mutexes after ww_acquire_done.

  - Attempting to lock the wrong mutex after -EDEADLK and
    unlocking all mutexes.

  - Attempting to lock the right mutex after -EDEADLK,
    before unlocking all mutexes.

  - Calling ww_mutex_lock_slow before -EDEADLK was returned.

  - Unlocking mutexes with the wrong unlock function.

  - Calling one of the ww_acquire\_\* twice on the same context.

  - Using a different ww_class for the mutex than for the ww_acquire_ctx.

  - Normal lockdep errors that can result in deadlocks.

- **Some of the lockdep errors that can result in deadlocks:**

  - Calling ww_acquire_init to initialize a second ww_acquire_ctx before
    having called ww_acquire_fini on the first.

  - 'normal' deadlocks that can occur.

- **FIXME:**

  Update this section once we have the TASK_DEADLOCK task state flag magic
  implemented.

---

# Sequence counters and sequential locks

_Peios Kernel / Internals / Locking_

> Sequence counters, latch counters, sequential locks, and their API reference.

<a id="rst-sequence-counters-and-sequential-locks"></a>

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

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

## Introduction

Sequence counters are a reader-writer consistency mechanism with
lockless readers (read-only retry loops), and no writer starvation. They
are used for data that's rarely written to (e.g. system time), where the
reader wants a consistent set of information and is willing to retry if
that information changes.

A data set is consistent when the sequence count at the beginning of the
read side critical section is even and the same sequence count value is
read again at the end of the critical section. The data in the set must
be copied out inside the read side critical section. If the sequence
count has changed between the start and the end of the critical section,
the reader must retry.

Writers increment the sequence count at the start and the end of their
critical section. After starting the critical section the sequence count
is odd and indicates to the readers that an update is in progress. At
the end of the write side critical section the sequence count becomes
even again which lets readers make progress.

A sequence counter write side critical section must never be preempted
or interrupted by read side sections. Otherwise the reader will spin for
the entire scheduler tick due to the odd sequence count value and the
interrupted writer. If that reader belongs to a real-time scheduling
class, it can spin forever and the kernel will livelock.

This mechanism cannot be used if the protected data contains pointers,
as the writer can invalidate a pointer that the reader is following.

<a id="rst-sequence-counters-seqcount-t"></a>
<a id="rst-seqcount-t"></a>

## Sequence counters (`seqcount_t`)

This is the raw counting mechanism, which does not protect against
multiple writers.  Write side critical sections must thus be serialized
by an external lock.

If the write serialization primitive is not implicitly disabling
preemption, preemption must be explicitly disabled before entering the
write side section. If the read section can be invoked from hardirq or
softirq contexts, interrupts or bottom halves must also be respectively
disabled before entering the write section.

If it's desired to automatically handle the sequence counter
requirements of writer serialization and non-preemptibility, use
[Sequential locks (seqlock_t)](/kernel/internals/locking/seqlock.md#rst-seqlock-t) instead.

Initialization:

```c
/* dynamic */
seqcount_t foo_seqcount;
seqcount_init(&foo_seqcount);

/* static */
static seqcount_t foo_seqcount = SEQCNT_ZERO(foo_seqcount);

/* C99 struct init */
struct {
        .seq   = SEQCNT_ZERO(foo.seq),
} foo;
```

Write path:

```c
/* Serialized context with disabled preemption */

write_seqcount_begin(&foo_seqcount);

/* ... [[write-side critical section]] ... */

write_seqcount_end(&foo_seqcount);
```

Read path:

```c
do {
        seq = read_seqcount_begin(&foo_seqcount);

        /* ... [[read-side critical section]] ... */

} while (read_seqcount_retry(&foo_seqcount, seq));
```

<a id="rst-sequence-counters-with-associated-locks-seqcount-lockname-t"></a>
<a id="rst-seqcount-locktype-t"></a>

### Sequence counters with associated locks (`seqcount_LOCKNAME_t`)

As discussed at [Sequence counters (seqcount_t)](/kernel/internals/locking/seqlock.md#rst-seqcount-t), sequence count write side critical
sections must be serialized and non-preemptible. This variant of
sequence counters associate the lock used for writer serialization at
initialization time, which enables lockdep to validate that the write
side critical sections are properly serialized.

This lock association is a NOOP if lockdep is disabled and has neither
storage nor runtime overhead. If lockdep is enabled, the lock pointer is
stored in struct seqcount and lockdep's "lock is held" assertions are
injected at the beginning of the write side critical section to validate
that it is properly protected.

For lock types which do not implicitly disable preemption, preemption
protection is enforced in the write side function.

The following sequence counters with associated locks are defined:

- `seqcount_spinlock_t`

- `seqcount_raw_spinlock_t`

- `seqcount_rwlock_t`

- `seqcount_mutex_t`

- `seqcount_ww_mutex_t`

The sequence counter read and write APIs can take either a plain
seqcount_t or any of the seqcount_LOCKNAME_t variants above.

Initialization (replace "LOCKNAME" with one of the supported locks):

```c
/* dynamic */
seqcount_LOCKNAME_t foo_seqcount;
seqcount_LOCKNAME_init(&foo_seqcount, &lock);

/* static */
static seqcount_LOCKNAME_t foo_seqcount =
        SEQCNT_LOCKNAME_ZERO(foo_seqcount, &lock);

/* C99 struct init */
struct {
        .seq   = SEQCNT_LOCKNAME_ZERO(foo.seq, &lock),
} foo;
```

Write path: same as in [Sequence counters (seqcount_t)](/kernel/internals/locking/seqlock.md#rst-seqcount-t), while running from a context
with the associated write serialization lock acquired.

Read path: same as in [Sequence counters (seqcount_t)](/kernel/internals/locking/seqlock.md#rst-seqcount-t).

<a id="rst-latch-sequence-counters-seqcount-latch-t"></a>
<a id="rst-seqcount-latch-t"></a>

### Latch sequence counters (`seqcount_latch_t`)

Latch sequence counters are a multiversion concurrency control mechanism
where the embedded seqcount_t counter even/odd value is used to switch
between two copies of protected data. This allows the sequence counter
read path to safely interrupt its own write side critical section.

Use seqcount_latch_t when the write side sections cannot be protected
from interruption by readers. This is typically the case when the read
side can be invoked from NMI handlers.

Check `write_seqcount_latch()` for more information.

<a id="rst-sequential-locks-seqlock-t"></a>
<a id="rst-seqlock-t"></a>

## Sequential locks (`seqlock_t`)

This contains the [Sequence counters (seqcount_t)](/kernel/internals/locking/seqlock.md#rst-seqcount-t) mechanism earlier discussed, plus an
embedded spinlock for writer serialization and non-preemptibility.

If the read side section can be invoked from hardirq or softirq context,
use the write side function variants which disable interrupts or bottom
halves respectively.

Initialization:

```c
/* dynamic */
seqlock_t foo_seqlock;
seqlock_init(&foo_seqlock);

/* static */
static DEFINE_SEQLOCK(foo_seqlock);

/* C99 struct init */
struct {
        .seql   = __SEQLOCK_UNLOCKED(foo.seql)
} foo;
```

Write path:

```c
write_seqlock(&foo_seqlock);

/* ... [[write-side critical section]] ... */

write_sequnlock(&foo_seqlock);
```

Read path, three categories:

1. Normal Sequence readers which never block a writer but they must
   retry if a writer is in progress by detecting change in the sequence
   number.  Writers do not wait for a sequence reader:

   ```c
   do {
           seq = read_seqbegin(&foo_seqlock);

           /* ... [[read-side critical section]] ... */

   } while (read_seqretry(&foo_seqlock, seq));
   ```

2. Locking readers which will wait if a writer or another locking reader
   is in progress. A locking reader in progress will also block a writer
   from entering its critical section. This read lock is
   exclusive. Unlike rwlock_t, only one locking reader can acquire it:

   ```c
   read_seqlock_excl(&foo_seqlock);

   /* ... [[read-side critical section]] ... */

   read_sequnlock_excl(&foo_seqlock);
   ```

3. Conditional lockless reader (as in 1), or locking reader (as in 2),
   according to a passed marker. This is used to avoid lockless readers
   starvation (too much retry loops) in case of a sharp spike in write
   activity. First, a lockless read is tried (even marker passed). If
   that trial fails (sequence counter doesn't match), make the marker
   odd for the next iteration, the lockless read is transformed to a
   full locking read and no retry loop is necessary, for example:

   ```c
   /* marker; even initialization */
   int seq = 1;
   do {
           seq++; /* 2 on the 1st/lockless path, otherwise odd */
           read_seqbegin_or_lock(&foo_seqlock, &seq);

           /* ... [[read-side critical section]] ... */

   } while (need_seqretry(&foo_seqlock, seq));
   done_seqretry(&foo_seqlock, seq);
   ```

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

## API documentation


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

```c
seqcount_init(s)
```

runtime initializer for seqcount_t

**Parameters**

- `s`: Pointer to the seqcount_t instance

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

```c
SEQCNT_ZERO(name)
```

static initializer for seqcount_t

**Parameters**

- `name`: Name of the seqcount_t instance

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

```c
__read_seqcount_begin(s)
```

begin a seqcount_t read section

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Return**

count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

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

```c
raw_read_seqcount_begin(s)
```

begin a seqcount_t read section w/o lockdep

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Return**

count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

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

```c
read_seqcount_begin(s)
```

begin a seqcount_t read critical section

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Return**

count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

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

```c
raw_read_seqcount(s)
```

read the raw seqcount_t counter value

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Description**

raw_read_seqcount opens a read critical section of the given
seqcount_t, without any lockdep checking, and without checking or
masking the sequence counter LSB. Calling code is responsible for
handling that.

**Return**

count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

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

```c
raw_seqcount_try_begin(s, start)
```

begin a seqcount_t read critical section w/o lockdep and w/o counter stabilization

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants
- `start`: count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

**Description**

Similar to [`raw_seqcount_begin()`](#c-raw_seqcount_begin), except it enables eliding the critical
section entirely if odd, instead of doing the speculation knowing it will
fail.

Useful when counter stabilization is more or less equivalent to taking
the lock and there is a slowpath that does that.

If true, start will be set to the (even) sequence count read.

**Return**

true when a read critical section is started.

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

```c
raw_seqcount_begin(s)
```

begin a seqcount_t read critical section w/o lockdep and w/o counter stabilization

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Description**

raw_seqcount_begin opens a read critical section of the given
seqcount_t. Unlike [`read_seqcount_begin()`](#c-read_seqcount_begin), this function will not wait
for the count to stabilize. If a writer is active when it begins, it
will fail the [`read_seqcount_retry()`](#c-read_seqcount_retry) at the end of the read critical
section instead of stabilizing at the beginning of it.

Use this only in special kernel hot paths where the read section is
small and has a high probability of success through other external
means. It will save a single branching instruction.

**Return**

count to be passed to [`read_seqcount_retry()`](#c-read_seqcount_retry)

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

```c
__read_seqcount_retry(s, start)
```

end a seqcount_t read section w/o barrier

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants
- `start`: count, from [`read_seqcount_begin()`](#c-read_seqcount_begin)

**Description**

__read_seqcount_retry is like read_seqcount_retry, but has no `smp_rmb()`
barrier. Callers should ensure that `smp_rmb()` or equivalent ordering is
provided before actually loading any of the variables that are to be
protected in this critical section.

Use carefully, only in critical code, and comment how the barrier is
provided.

**Return**

true if a read section retry is required, else false

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

```c
read_seqcount_retry(s, start)
```

end a seqcount_t read critical section

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants
- `start`: count, from [`read_seqcount_begin()`](#c-read_seqcount_begin)

**Description**

read_seqcount_retry closes the read critical section of given
seqcount_t.  If the critical section was invalid, it must be ignored
(and typically retried).

**Return**

true if a read section retry is required, else false

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

```c
raw_write_seqcount_begin(s)
```

start a seqcount_t write section w/o lockdep

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Context**

check [`write_seqcount_begin()`](#c-write_seqcount_begin)

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

```c
raw_write_seqcount_end(s)
```

end a seqcount_t write section w/o lockdep

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Context**

check [`write_seqcount_end()`](#c-write_seqcount_end)

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

```c
write_seqcount_begin_nested(s, subclass)
```

start a seqcount_t write section with custom lockdep nesting level

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants
- `subclass`: lockdep nesting level

**Description**

See Documentation/locking/lockdep-design.rst

**Context**

check [`write_seqcount_begin()`](#c-write_seqcount_begin)

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

```c
write_seqcount_begin(s)
```

start a seqcount_t write side critical section

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Context**

sequence counter write side sections must be serialized and
non-preemptible. Preemption will be automatically disabled if and
only if the seqcount write serialization lock is associated, and
preemptible.  If readers can be invoked from hardirq or softirq
context, interrupts or bottom halves must be respectively disabled.

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

```c
write_seqcount_end(s)
```

end a seqcount_t write side critical section

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Context**

Preemption will be automatically re-enabled if and only if
the seqcount write serialization lock is associated, and preemptible.

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

```c
raw_write_seqcount_barrier(s)
```

do a seqcount_t write barrier

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Description**

This can be used to provide an ordering guarantee instead of the usual
consistency guarantee. It is one wmb cheaper, because it can collapse
the two back-to-back `wmb()`s.

Note that writes surrounding the barrier should be declared atomic (e.g.
via WRITE_ONCE): a) to ensure the writes become visible to other threads
atomically, avoiding compiler optimizations; b) to document which writes are
meant to propagate to the reader critical section. This is necessary because
neither writes before nor after the barrier are enclosed in a seq-writer
critical section that would ensure readers are aware of ongoing writes:

```text
seqcount_t seq;
bool X = true, Y = false;

void read(void)
{
        bool x, y;

        do {
                int s = read_seqcount_begin(&seq);

                x = X; y = Y;

        } while (read_seqcount_retry(&seq, s));

        BUG_ON(!x && !y);
}

void write(void)
{
        WRITE_ONCE(Y, true);

        raw_write_seqcount_barrier(seq);

        WRITE_ONCE(X, false);
}
```

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

```c
write_seqcount_invalidate(s)
```

invalidate in-progress seqcount_t read side operations

**Parameters**

- `s`: Pointer to seqcount_t or any of the seqcount_LOCKNAME_t variants

**Description**

After write_seqcount_invalidate, no seqcount_t read side operations
will complete successfully and see data older than this.

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

```c
SEQCNT_LATCH_ZERO(seq_name)
```

static initializer for seqcount_latch_t

**Parameters**

- `seq_name`: Name of the seqcount_latch_t instance

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

```c
seqcount_latch_init(s)
```

runtime initializer for seqcount_latch_t

**Parameters**

- `s`: Pointer to the seqcount_latch_t instance

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

```c
unsigned raw_read_seqcount_latch(const seqcount_latch_t *s)
```

pick even/odd latch data copy

**Parameters**

- `const seqcount_latch_t *s`: Pointer to seqcount_latch_t

**Description**

See [`raw_write_seqcount_latch()`](#c-raw_write_seqcount_latch) for details and a full reader/writer
usage example.

**Return**

sequence counter raw value. Use the lowest bit as an index for
picking which data copy to read. The full counter must then be checked
with [`raw_read_seqcount_latch_retry()`](#c-raw_read_seqcount_latch_retry).

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

```c
unsigned read_seqcount_latch(const seqcount_latch_t *s)
```

pick even/odd latch data copy

**Parameters**

- `const seqcount_latch_t *s`: Pointer to seqcount_latch_t

**Description**

See [`write_seqcount_latch()`](#c-write_seqcount_latch) for details and a full reader/writer usage
example.

**Return**

sequence counter raw value. Use the lowest bit as an index for
picking which data copy to read. The full counter must then be checked
with [`read_seqcount_latch_retry()`](#c-read_seqcount_latch_retry).

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

```c
int raw_read_seqcount_latch_retry(const seqcount_latch_t *s, unsigned start)
```

end a seqcount_latch_t read section

**Parameters**

- `const seqcount_latch_t *s`: Pointer to seqcount_latch_t
- `unsigned start`: count, from [`raw_read_seqcount_latch()`](#c-raw_read_seqcount_latch)

**Return**

true if a read section retry is required, else false

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

```c
int read_seqcount_latch_retry(const seqcount_latch_t *s, unsigned start)
```

end a seqcount_latch_t read section

**Parameters**

- `const seqcount_latch_t *s`: Pointer to seqcount_latch_t
- `unsigned start`: count, from [`read_seqcount_latch()`](#c-read_seqcount_latch)

**Return**

true if a read section retry is required, else false

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

```c
void raw_write_seqcount_latch(seqcount_latch_t *s)
```

redirect latch readers to even/odd copy

**Parameters**

- `seqcount_latch_t *s`: Pointer to seqcount_latch_t

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

```c
void write_seqcount_latch_begin(seqcount_latch_t *s)
```

redirect latch readers to odd copy

**Parameters**

- `seqcount_latch_t *s`: Pointer to seqcount_latch_t

**Description**

The latch technique is a multiversion concurrency control method that allows
queries during non-atomic modifications. If you can guarantee queries never
interrupt the modification -- e.g. the concurrency is strictly between CPUs
-- you most likely do not need this.

Where the traditional RCU/lockless data structures rely on atomic
modifications to ensure queries observe either the old or the new state the
latch allows the same for non-atomic updates. The trade-off is doubling the
cost of storage; we have to maintain two copies of the entire data
structure.

Very simply put: we first modify one copy and then the other. This ensures
there is always one copy in a stable state, ready to give us an answer.

The basic form is a data structure like:

```text
struct latch_struct {
        seqcount_latch_t        seq;
        struct data_struct      data[2];
};
```

Where a modification, which is assumed to be externally serialized, does the
following:

```text
void latch_modify(struct latch_struct *latch, ...)
{
        write_seqcount_latch_begin(&latch->seq);
        modify(latch->data[0], ...);
        write_seqcount_latch(&latch->seq);
        modify(latch->data[1], ...);
        write_seqcount_latch_end(&latch->seq);
}
```

The query will have a form like:

```text
struct entry *latch_query(struct latch_struct *latch, ...)
{
        struct entry *entry;
        unsigned seq, idx;

        do {
                seq = read_seqcount_latch(&latch->seq);

                idx = seq & 0x01;
                entry = data_query(latch->data[idx], ...);

        // This includes needed smp_rmb()
        } while (read_seqcount_latch_retry(&latch->seq, seq));

        return entry;
}
```

So during the modification, queries are first redirected to data\[1\]. Then we
modify data\[0\]. When that is complete, we redirect queries back to data\[0\]
and we can modify data\[1\].

**NOTE**

The non-requirement for atomic modifications does _NOT_ include
the publishing of new entries in the case where data is a dynamic
data structure.

An iteration might start in data\[0\] and get suspended long enough
to miss an entire modification sequence, once it resumes it might
observe the new entry.

NOTE2:

When data is a dynamic data structure; one should use regular RCU
patterns to manage the lifetimes of the objects within.

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

```c
void write_seqcount_latch(seqcount_latch_t *s)
```

redirect latch readers to even copy

**Parameters**

- `seqcount_latch_t *s`: Pointer to seqcount_latch_t

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

```c
void write_seqcount_latch_end(seqcount_latch_t *s)
```

end a seqcount_latch_t write section

**Parameters**

- `seqcount_latch_t *s`: Pointer to seqcount_latch_t

**Description**

Marks the end of a seqcount_latch_t writer section, after all copies of the
latch-protected data have been updated.

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

```c
seqlock_init(sl)
```

dynamic initializer for seqlock_t

**Parameters**

- `sl`: Pointer to the seqlock_t instance

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

```c
DEFINE_SEQLOCK(sl)
```

Define a statically allocated seqlock_t

**Parameters**

- `sl`: Name of the seqlock_t instance

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

```c
unsigned read_seqbegin(const seqlock_t *sl)
```

start a seqlock_t read side critical section

**Parameters**

- `const seqlock_t *sl`: Pointer to seqlock_t

**Return**

count, to be passed to [`read_seqretry()`](#c-read_seqretry)

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

```c
unsigned read_seqretry(const seqlock_t *sl, unsigned start)
```

end a seqlock_t read side section

**Parameters**

- `const seqlock_t *sl`: Pointer to seqlock_t
- `unsigned start`: count, from [`read_seqbegin()`](#c-read_seqbegin)

**Description**

read_seqretry closes the read side critical section of given seqlock_t.
If the critical section was invalid, it must be ignored (and typically
retried).

**Return**

true if a read section retry is required, else false

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

```c
void write_seqlock(seqlock_t *sl)
```

start a seqlock_t write side critical section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

write_seqlock opens a write side critical section for the given
seqlock_t.  It also implicitly acquires the spinlock_t embedded inside
that sequential lock. All seqlock_t write side sections are thus
automatically serialized and non-preemptible.

**Context**

if the seqlock_t read section, or other write side critical
sections, can be invoked from hardirq or softirq contexts, use the
_irqsave or _bh variants of this function instead.

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

```c
void write_sequnlock(seqlock_t *sl)
```

end a seqlock_t write side critical section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

write_sequnlock closes the (serialized and non-preemptible) write side
critical section of given seqlock_t.

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

```c
void write_seqlock_bh(seqlock_t *sl)
```

start a softirqs-disabled seqlock_t write section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

_bh variant of [`write_seqlock()`](#c-write_seqlock). Use only if the read side section, or
other write side sections, can be invoked from softirq contexts.

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

```c
void write_sequnlock_bh(seqlock_t *sl)
```

end a softirqs-disabled seqlock_t write section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

write_sequnlock_bh closes the serialized, non-preemptible, and
softirqs-disabled, seqlock_t write side critical section opened with
[`write_seqlock_bh()`](#c-write_seqlock_bh).

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

```c
void write_seqlock_irq(seqlock_t *sl)
```

start a non-interruptible seqlock_t write section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

_irq variant of [`write_seqlock()`](#c-write_seqlock). Use only if the read side section, or
other write sections, can be invoked from hardirq contexts.

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

```c
void write_sequnlock_irq(seqlock_t *sl)
```

end a non-interruptible seqlock_t write section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

write_sequnlock_irq closes the serialized and non-interruptible
seqlock_t write side section opened with [`write_seqlock_irq()`](#c-write_seqlock_irq).

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

```c
write_seqlock_irqsave(lock, flags)
```

start a non-interruptible seqlock_t write section

**Parameters**

- `lock`: Pointer to seqlock_t
- `flags`: Stack-allocated storage for saving caller's local interrupt
  state, to be passed to [`write_sequnlock_irqrestore()`](#c-write_sequnlock_irqrestore).

**Description**

_irqsave variant of [`write_seqlock()`](#c-write_seqlock). Use it only if the read side
section, or other write sections, can be invoked from hardirq context.

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

```c
void write_sequnlock_irqrestore(seqlock_t *sl, unsigned long flags)
```

end non-interruptible seqlock_t write section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t
- `unsigned long flags`: Caller's saved interrupt state, from [`write_seqlock_irqsave()`](#c-write_seqlock_irqsave)

**Description**

write_sequnlock_irqrestore closes the serialized and non-interruptible
seqlock_t write section previously opened with [`write_seqlock_irqsave()`](#c-write_seqlock_irqsave).

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

```c
void read_seqlock_excl(seqlock_t *sl)
```

begin a seqlock_t locking reader section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

read_seqlock_excl opens a seqlock_t locking reader critical section.  A
locking reader exclusively locks out *both* other writers *and* other
locking readers, but it does not update the embedded sequence number.

Locking readers act like a normal `spin_lock()`/`spin_unlock()`.

The opened read section must be closed with [`read_sequnlock_excl()`](#c-read_sequnlock_excl).

**Context**

if the seqlock_t write section, *or other read sections*, can
be invoked from hardirq or softirq contexts, use the _irqsave or _bh
variant of this function instead.

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

```c
void read_sequnlock_excl(seqlock_t *sl)
```

end a seqlock_t locking reader critical section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

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

```c
void read_seqlock_excl_bh(seqlock_t *sl)
```

start a seqlock_t locking reader section with softirqs disabled

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

_bh variant of [`read_seqlock_excl()`](#c-read_seqlock_excl). Use this variant only if the
seqlock_t write side section, *or other read sections*, can be invoked
from softirq contexts.

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

```c
void read_sequnlock_excl_bh(seqlock_t *sl)
```

stop a seqlock_t softirq-disabled locking reader section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

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

```c
void read_seqlock_excl_irq(seqlock_t *sl)
```

start a non-interruptible seqlock_t locking reader section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

**Description**

_irq variant of [`read_seqlock_excl()`](#c-read_seqlock_excl). Use this only if the seqlock_t
write side section, *or other read sections*, can be invoked from a
hardirq context.

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

```c
void read_sequnlock_excl_irq(seqlock_t *sl)
```

end an interrupts-disabled seqlock_t locking reader section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t

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

```c
read_seqlock_excl_irqsave(lock, flags)
```

start a non-interruptible seqlock_t locking reader section

**Parameters**

- `lock`: Pointer to seqlock_t
- `flags`: Stack-allocated storage for saving caller's local interrupt
  state, to be passed to [`read_sequnlock_excl_irqrestore()`](#c-read_sequnlock_excl_irqrestore).

**Description**

_irqsave variant of [`read_seqlock_excl()`](#c-read_seqlock_excl). Use this only if the seqlock_t
write side section, *or other read sections*, can be invoked from a
hardirq context.

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

```c
void read_sequnlock_excl_irqrestore(seqlock_t *sl, unsigned long flags)
```

end non-interruptible seqlock_t locking reader section

**Parameters**

- `seqlock_t *sl`: Pointer to seqlock_t
- `unsigned long flags`: Caller saved interrupt state, from [`read_seqlock_excl_irqsave()`](#c-read_seqlock_excl_irqsave)

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

```c
void read_seqbegin_or_lock(seqlock_t *lock, int *seq)
```

begin a seqlock_t lockless or locking reader

**Parameters**

- `seqlock_t *lock`: Pointer to seqlock_t
- `int *seq`: Marker and return parameter. If the passed value is even, the
  reader will become a *lockless* seqlock_t reader as in [`read_seqbegin()`](#c-read_seqbegin).
  If the passed value is odd, the reader will become a *locking* reader
  as in [`read_seqlock_excl()`](#c-read_seqlock_excl).  In the first call to this function, the
  caller *must* initialize and pass an even value to **seq**; this way, a
  lockless read can be optimistically tried first.

**Description**

read_seqbegin_or_lock is an API designed to optimistically try a normal
lockless seqlock_t read section first.  If an odd counter is found, the
lockless read trial has failed, and the next read iteration transforms
itself into a full seqlock_t locking reader.

This is typically used to avoid seqlock_t lockless readers starvation
(too much retry loops) in the case of a sharp spike in write side
activity.

Check Documentation/locking/seqlock.rst for template example code.

**Context**

if the seqlock_t write section, *or other read sections*, can
be invoked from hardirq or softirq contexts, use the _irqsave or _bh
variant of this function instead.

**Return**

the encountered sequence counter value, through the **seq**
parameter, which is overloaded as a return parameter. This returned
value must be checked with [`need_seqretry()`](#c-need_seqretry). If the read section need to
be retried, this returned value must also be passed as the **seq**
parameter of the next [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock) iteration.

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

```c
int need_seqretry(seqlock_t *lock, int seq)
```

validate seqlock_t "locking or lockless" read section

**Parameters**

- `seqlock_t *lock`: Pointer to seqlock_t
- `int seq`: sequence count, from [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock)

**Return**

true if a read section retry is required, false otherwise

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

```c
void done_seqretry(seqlock_t *lock, int seq)
```

end seqlock_t "locking or lockless" reader section

**Parameters**

- `seqlock_t *lock`: Pointer to seqlock_t
- `int seq`: count, from [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock)

**Description**

done_seqretry finishes the seqlock_t read side critical section started
with [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock) and validated by [`need_seqretry()`](#c-need_seqretry).

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

```c
unsigned long read_seqbegin_or_lock_irqsave(seqlock_t *lock, int *seq)
```

begin a seqlock_t lockless reader, or a non-interruptible locking reader

**Parameters**

- `seqlock_t *lock`: Pointer to seqlock_t
- `int *seq`: Marker and return parameter. Check [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock).

**Description**

This is the _irqsave variant of [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock). Use it only if
the seqlock_t write section, *or other read sections*, can be invoked
from hardirq context.

1. The saved local interrupts state in case of a locking reader, to
   be passed to [`done_seqretry_irqrestore()`](#c-done_seqretry_irqrestore).

2. The encountered sequence counter value, returned through **seq**
   overloaded as a return parameter. Check [`read_seqbegin_or_lock()`](#c-read_seqbegin_or_lock).

**Note**

Interrupts will be disabled only for "locking reader" mode.

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

```c
void done_seqretry_irqrestore(seqlock_t *lock, int seq, unsigned long flags)
```

end a seqlock_t lockless reader, or a non-interruptible locking reader section

**Parameters**

- `seqlock_t *lock`: Pointer to seqlock_t
- `int seq`: Count, from [`read_seqbegin_or_lock_irqsave()`](#c-read_seqbegin_or_lock_irqsave)
- `unsigned long flags`: Caller's saved local interrupt state in case of a locking
  reader, also from [`read_seqbegin_or_lock_irqsave()`](#c-read_seqbegin_or_lock_irqsave)

**Description**

This is the _irqrestore variant of [`done_seqretry()`](#c-done_seqretry). The read section
must've been opened with [`read_seqbegin_or_lock_irqsave()`](#c-read_seqbegin_or_lock_irqsave), and validated
by [`need_seqretry()`](#c-need_seqretry).

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

```c
scoped_seqlock_read(_seqlock, _target)
```

execute the read-side critical section without manual sequence counter handling or calls to other helpers

**Parameters**

- `_seqlock`: pointer to seqlock_t protecting the data
- `_target`: an enum ss_state: one of {ss_lock, ss_lock_irqsave, ss_lockless}
  indicating the type of critical read section

**Description**

Example:

```text
scoped_seqlock_read (&lock, ss_lock) {
    // read-side critical section
}
```

Starts with a lockess pass first. If it fails, restarts the critical
section with the lock held.

---

# Per-CPU reader/writer semaphores

_Peios Kernel / Internals / Locking_

> The per-CPU reader/writer semaphore and its read-side and write-side trade-offs.

<a id="rst-percpu-rw-semaphores"></a>

Percpu rw semaphores is a new read-write semaphore design that is
optimized for locking for reading.

The problem with traditional read-write semaphores is that when multiple
cores take the lock for reading, the cache line containing the semaphore
is bouncing between L1 caches of the cores, causing performance
degradation.

Locking for reading is very fast, it uses RCU and it avoids any atomic
instruction in the lock and unlock path. On the other hand, locking for
writing is very expensive, it calls synchronize_rcu() that can take
hundreds of milliseconds.

The lock is declared with "struct percpu_rw_semaphore" type.
The lock is initialized with percpu_init_rwsem, it returns 0 on success
and -ENOMEM on allocation failure.
The lock must be freed with percpu_free_rwsem to avoid memory leak.

The lock is locked for read with percpu_down_read, percpu_up_read and
for write with percpu_down_write, percpu_up_write.

The idea of using RCU for optimized rw-lock was introduced by
Eric Dumazet &lt;[eric.dumazet@gmail.com](<mailto:eric.dumazet@gmail.com>)&gt;.
The code was written by Mikulas Patocka &lt;[mpatocka@redhat.com](<mailto:mpatocka@redhat.com>)&gt;

---

# Hardware spinlocks

_Peios Kernel / Internals / Locking_

> Requesting and using hardware spinlocks, with driver implementation guidance.

<a id="rst-hardware-spinlock-framework"></a>

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

## Introduction

Hardware spinlock modules provide hardware assistance for synchronization
and mutual exclusion between heterogeneous processors and those not operating
under a single, shared operating system.

For example, OMAP4 has dual Cortex-A9, dual Cortex-M3 and a C64x+ DSP,
each of which is running a different Operating System (the master, A9,
is usually running Linux and the slave processors, the M3 and the DSP,
are running some flavor of RTOS).

A generic hwspinlock framework allows platform-independent drivers to use
the hwspinlock device in order to access data structures that are shared
between remote processors, that otherwise have no alternative mechanism
to accomplish synchronization and mutual exclusion operations.

This is necessary, for example, for Inter-processor communications:
on OMAP4, cpu-intensive multimedia tasks are offloaded by the host to the
remote M3 and/or C64x+ slave processors (by an IPC subsystem called Syslink).

To achieve fast message-based communications, a minimal kernel support
is needed to deliver messages arriving from a remote processor to the
appropriate user process.

This communication is based on simple data structures that is shared between
the remote processors, and access to it is synchronized using the hwspinlock
module (remote processor directly places new messages in this shared data
structure).

A common hwspinlock interface makes it possible to have generic, platform-
independent, drivers.

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

## User API

```c
struct hwspinlock *hwspin_lock_request_specific(unsigned int id);
```

Assign a specific hwspinlock id and return its address, or NULL
if that hwspinlock is already in use. Usually board code will
be calling this function in order to reserve specific hwspinlock
ids for predefined purposes.

Should be called from a process context (might sleep).

```c
int of_hwspin_lock_get_id(struct device_node *np, int index);
```

Retrieve the global lock id for an OF phandle-based specific lock.
This function provides a means for DT users of a hwspinlock module
to get the global lock id of a specific hwspinlock, so that it can
be requested using the normal hwspin_lock_request_specific() API.

The function returns a lock id number on success, -EPROBE_DEFER if
the hwspinlock device is not yet registered with the core, or other
error values.

Should be called from a process context (might sleep).

```c
int hwspin_lock_free(struct hwspinlock *hwlock);
```

Free a previously-assigned hwspinlock; returns 0 on success, or an
appropriate error code on failure (e.g. -EINVAL if the hwspinlock
is already free).

Should be called from a process context (might sleep).

```c
int hwspin_lock_bust(struct hwspinlock *hwlock, unsigned int id);
```

After verifying the owner of the hwspinlock, release a previously acquired
hwspinlock; returns 0 on success, or an appropriate error code on failure
(e.g. -EOPNOTSUPP if the bust operation is not defined for the specific
hwspinlock).

Should be called from a process context (might sleep).

```c
int hwspin_lock_timeout(struct hwspinlock *hwlock, unsigned int timeout);
```

Lock a previously-assigned hwspinlock with a timeout limit (specified in
msecs). If the hwspinlock is already taken, the function will busy loop
waiting for it to be released, but give up when the timeout elapses.
Upon a successful return from this function, preemption is disabled so
the caller must not sleep, and is advised to release the hwspinlock as
soon as possible, in order to minimize remote cores polling on the
hardware interconnect.

Returns 0 when successful and an appropriate error code otherwise (most
notably -ETIMEDOUT if the hwspinlock is still busy after timeout msecs).
The function will never sleep.

```c
int hwspin_lock_timeout_irq(struct hwspinlock *hwlock, unsigned int timeout);
```

Lock a previously-assigned hwspinlock with a timeout limit (specified in
msecs). If the hwspinlock is already taken, the function will busy loop
waiting for it to be released, but give up when the timeout elapses.
Upon a successful return from this function, preemption and the local
interrupts are disabled, so the caller must not sleep, and is advised to
release the hwspinlock as soon as possible.

Returns 0 when successful and an appropriate error code otherwise (most
notably -ETIMEDOUT if the hwspinlock is still busy after timeout msecs).
The function will never sleep.

```c
int hwspin_lock_timeout_irqsave(struct hwspinlock *hwlock, unsigned int to,
                                unsigned long *flags);
```

Lock a previously-assigned hwspinlock with a timeout limit (specified in
msecs). If the hwspinlock is already taken, the function will busy loop
waiting for it to be released, but give up when the timeout elapses.
Upon a successful return from this function, preemption is disabled,
local interrupts are disabled and their previous state is saved at the
given flags placeholder. The caller must not sleep, and is advised to
release the hwspinlock as soon as possible.

Returns 0 when successful and an appropriate error code otherwise (most
notably -ETIMEDOUT if the hwspinlock is still busy after timeout msecs).

The function will never sleep.

```c
int hwspin_lock_timeout_raw(struct hwspinlock *hwlock, unsigned int timeout);
```

Lock a previously-assigned hwspinlock with a timeout limit (specified in
msecs). If the hwspinlock is already taken, the function will busy loop
waiting for it to be released, but give up when the timeout elapses.

Caution: User must protect the routine of getting hardware lock with mutex
or spinlock to avoid dead-lock, that will let user can do some time-consuming
or sleepable operations under the hardware lock.

Returns 0 when successful and an appropriate error code otherwise (most
notably -ETIMEDOUT if the hwspinlock is still busy after timeout msecs).

The function will never sleep.

```c
int hwspin_lock_timeout_in_atomic(struct hwspinlock *hwlock, unsigned int to);
```

Lock a previously-assigned hwspinlock with a timeout limit (specified in
msecs). If the hwspinlock is already taken, the function will busy loop
waiting for it to be released, but give up when the timeout elapses.

This function shall be called only from an atomic context and the timeout
value shall not exceed a few msecs.

Returns 0 when successful and an appropriate error code otherwise (most
notably -ETIMEDOUT if the hwspinlock is still busy after timeout msecs).

The function will never sleep.

```c
int hwspin_trylock(struct hwspinlock *hwlock);
```

Attempt to lock a previously-assigned hwspinlock, but immediately fail if
it is already taken.

Upon a successful return from this function, preemption is disabled so
caller must not sleep, and is advised to release the hwspinlock as soon as
possible, in order to minimize remote cores polling on the hardware
interconnect.

Returns 0 on success and an appropriate error code otherwise (most
notably -EBUSY if the hwspinlock was already taken).
The function will never sleep.

```c
int hwspin_trylock_irq(struct hwspinlock *hwlock);
```

Attempt to lock a previously-assigned hwspinlock, but immediately fail if
it is already taken.

Upon a successful return from this function, preemption and the local
interrupts are disabled so caller must not sleep, and is advised to
release the hwspinlock as soon as possible.

Returns 0 on success and an appropriate error code otherwise (most
notably -EBUSY if the hwspinlock was already taken).

The function will never sleep.

```c
int hwspin_trylock_irqsave(struct hwspinlock *hwlock, unsigned long *flags);
```

Attempt to lock a previously-assigned hwspinlock, but immediately fail if
it is already taken.

Upon a successful return from this function, preemption is disabled,
the local interrupts are disabled and their previous state is saved
at the given flags placeholder. The caller must not sleep, and is advised
to release the hwspinlock as soon as possible.

Returns 0 on success and an appropriate error code otherwise (most
notably -EBUSY if the hwspinlock was already taken).
The function will never sleep.

```c
int hwspin_trylock_raw(struct hwspinlock *hwlock);
```

Attempt to lock a previously-assigned hwspinlock, but immediately fail if
it is already taken.

Caution: User must protect the routine of getting hardware lock with mutex
or spinlock to avoid dead-lock, that will let user can do some time-consuming
or sleepable operations under the hardware lock.

Returns 0 on success and an appropriate error code otherwise (most
notably -EBUSY if the hwspinlock was already taken).
The function will never sleep.

```c
int hwspin_trylock_in_atomic(struct hwspinlock *hwlock);
```

Attempt to lock a previously-assigned hwspinlock, but immediately fail if
it is already taken.

This function shall be called only from an atomic context.

Returns 0 on success and an appropriate error code otherwise (most
notably -EBUSY if the hwspinlock was already taken).
The function will never sleep.

```c
void hwspin_unlock(struct hwspinlock *hwlock);
```

Unlock a previously-locked hwspinlock. Always succeed, and can be called
from any context (the function never sleeps).

> [!NOTE]
>
> code should **never** unlock an hwspinlock which is already unlocked
> (there is no protection against this).

```c
void hwspin_unlock_irq(struct hwspinlock *hwlock);
```

Unlock a previously-locked hwspinlock and enable local interrupts.
The caller should **never** unlock an hwspinlock which is already unlocked.

Doing so is considered a bug (there is no protection against this).
Upon a successful return from this function, preemption and local
interrupts are enabled. This function will never sleep.

```c
void
hwspin_unlock_irqrestore(struct hwspinlock *hwlock, unsigned long *flags);
```

Unlock a previously-locked hwspinlock.

The caller should **never** unlock an hwspinlock which is already unlocked.
Doing so is considered a bug (there is no protection against this).
Upon a successful return from this function, preemption is reenabled,
and the state of the local interrupts is restored to the state saved at
the given flags. This function will never sleep.

```c
void hwspin_unlock_raw(struct hwspinlock *hwlock);
```

Unlock a previously-locked hwspinlock.

The caller should **never** unlock an hwspinlock which is already unlocked.
Doing so is considered a bug (there is no protection against this).
This function will never sleep.

```c
void hwspin_unlock_in_atomic(struct hwspinlock *hwlock);
```

Unlock a previously-locked hwspinlock.

The caller should **never** unlock an hwspinlock which is already unlocked.
Doing so is considered a bug (there is no protection against this).
This function will never sleep.

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

## Typical usage

```c
#include <linux/hwspinlock.h>
#include <linux/err.h>

int hwspinlock_example(void)
{
        struct hwspinlock *hwlock;
        int ret;

        /*
        * assign a specific hwspinlock id - this should be called early
        * by board init code.
        */
        hwlock = hwspin_lock_request_specific(PREDEFINED_LOCK_ID);
        if (!hwlock)
                ...

        /* try to take it, but don't spin on it */
        ret = hwspin_trylock(hwlock);
        if (!ret) {
                pr_info("lock is already taken\n");
                return -EBUSY;
        }

        /*
        * we took the lock, do our thing now, but do NOT sleep
        */

        /* release the lock */
        hwspin_unlock(hwlock);

        /* free the lock */
        ret = hwspin_lock_free(hwlock);
        if (ret)
                ...

        return ret;
}
```

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

## API for implementors

```c
int hwspin_lock_register(struct hwspinlock_device *bank, struct device *dev,
              const struct hwspinlock_ops *ops, int base_id, int num_locks);
```

To be called from the underlying platform-specific implementation, in
order to register a new hwspinlock device (which is usually a bank of
numerous locks). Should be called from a process context (this function
might sleep).

Returns 0 on success, or appropriate error code on failure.

```c
int hwspin_lock_unregister(struct hwspinlock_device *bank);
```

To be called from the underlying vendor-specific implementation, in order
to unregister an hwspinlock device (which is usually a bank of numerous
locks).

Should be called from a process context (this function might sleep).

Returns the address of hwspinlock on success, or NULL on error (e.g.
if the hwspinlock is still in use).

<a id="rst-important-structs"></a>

## Important structs

struct hwspinlock_device is a device which usually contains a bank
of hardware locks. It is registered by the underlying hwspinlock
implementation using the hwspin_lock_register() API.

```c
/**
* struct hwspinlock_device - a device which usually spans numerous hwspinlocks
* @dev: underlying device, will be used to invoke runtime PM api
* @ops: platform-specific hwspinlock handlers
* @base_id: id index of the first lock in this device
* @num_locks: number of locks in this device
* @lock: dynamically allocated array of 'struct hwspinlock'
*/
struct hwspinlock_device {
        struct device *dev;
        const struct hwspinlock_ops *ops;
        int base_id;
        int num_locks;
        struct hwspinlock lock[0];
};
```

struct hwspinlock_device contains an array of hwspinlock structs, each
of which represents a single hardware lock:

```c
/**
* struct hwspinlock - this struct represents a single hwspinlock instance
* @bank: the hwspinlock_device structure which owns this lock
* @lock: initialized and used by hwspinlock core
* @priv: private data, owned by the underlying platform-specific hwspinlock drv
*/
struct hwspinlock {
        struct hwspinlock_device *bank;
        spinlock_t lock;
        void *priv;
};
```

When registering a bank of locks, the hwspinlock driver only needs to
set the priv members of the locks. The rest of the members are set and
initialized by the hwspinlock core itself.

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

## Implementation callbacks

There are three possible callbacks defined in 'struct hwspinlock_ops':

```c
struct hwspinlock_ops {
        int (*trylock)(struct hwspinlock *lock);
        void (*unlock)(struct hwspinlock *lock);
        void (*relax)(struct hwspinlock *lock);
};
```

The first two callbacks are mandatory:

The -&gt;trylock() callback should make a single attempt to take the lock, and
return 0 on failure and 1 on success. This callback may **not** sleep.

The -&gt;unlock() callback releases the lock. It always succeed, and it, too,
may **not** sleep.

The -&gt;relax() callback is optional. It is called by hwspinlock core while
spinning on a lock, and can be used by the underlying implementation to force
a delay between two successive invocations of -&gt;trylock(). It may **not** sleep.

---

# Locking and preemption

_Peios Kernel / Internals / Locking_

> Protecting per-CPU data, processor state, and critical sections in a preemptible kernel.

<a id="rst-proper-locking-under-a-preemptible-kernel-keeping-kernel-code-preempt-safe"></a>

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

## Introduction

A preemptible kernel creates new locking issues.  The issues are the same as
those under SMP: concurrency and reentrancy.  Thankfully, the Linux preemptible
kernel model leverages existing SMP locking mechanisms.  Thus, the kernel
requires explicit additional locking for very few additional situations.

This document is for all kernel hackers.  Developing code in the kernel
requires protecting these situations.

<a id="rst-rule-1-per-cpu-data-structures-need-explicit-protection"></a>

### RULE \#1: Per-CPU data structures need explicit protection

Two similar problems arise. An example code snippet:

```c
struct this_needs_locking tux[NR_CPUS];
tux[smp_processor_id()] = some_value;
/* task is preempted here... */
something = tux[smp_processor_id()];
```

First, since the data is per-CPU, it may not have explicit SMP locking, but
require it otherwise.  Second, when a preempted task is finally rescheduled,
the previous value of smp_processor_id may not equal the current.  You must
protect these situations by disabling preemption around them.

You can also use put_cpu() and get_cpu(), which will disable preemption.

<a id="rst-rule-2-cpu-state-must-be-protected"></a>

### RULE \#2: CPU state must be protected.

Under preemption, the state of the CPU must be protected.  This is arch-
dependent, but includes CPU structures and state not preserved over a context
switch.  For example, on x86, entering and exiting FPU mode is now a critical
section that must occur while preemption is disabled.  Think what would happen
if the kernel is executing a floating-point instruction and is then preempted.
Remember, the kernel does not save FPU state except for user tasks.  Therefore,
upon preemption, the FPU registers will be sold to the lowest bidder.  Thus,
preemption must be disabled around such regions.

Note, some FPU functions are already explicitly preempt safe.  For example,
kernel_fpu_begin and kernel_fpu_end will disable and enable preemption.

<a id="rst-rule-3-lock-acquire-and-release-must-be-performed-by-same-task"></a>

### RULE \#3: Lock acquire and release must be performed by same task

A lock acquired in one task must be released by the same task.  This
means you can't do oddball things like acquire a lock and go off to
play while another task releases it.  If you want to do something
like this, acquire and release the task in the same code path and
have the caller wait on an event by the other task.

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

## Solution

Data protection under preemption is achieved by disabling preemption for the
duration of the critical region.

```text
preempt_enable()              decrement the preempt counter
preempt_disable()             increment the preempt counter
preempt_enable_no_resched()   decrement, but do not immediately preempt
preempt_check_resched()       if needed, reschedule
preempt_count()               return the preempt counter
```

The functions are nestable.  In other words, you can call preempt_disable
n-times in a code path, and preemption will not be reenabled until the n-th
call to preempt_enable.  The preempt statements define to nothing if
preemption is not enabled.

Note that you do not need to explicitly prevent preemption if you are holding
any locks or interrupts are disabled, since preemption is implicitly disabled
in those cases.

But keep in mind that 'irqs disabled' is a fundamentally unsafe way of
disabling preemption - any cond_resched() or cond_resched_lock() might trigger
a reschedule if the preempt count is 0. A simple printk() might trigger a
reschedule. So use this implicit preemption-disabling property only if you
know that the affected codepath does not do any of this. Best policy is to use
this only for small, atomic code that you wrote and which calls no complex
functions.

Example:

```c
cpucache_t *cc; /* this is per-CPU */
preempt_disable();
cc = cc_data(searchp);
if (cc && cc->avail) {
        __free_block(searchp, cc_entry(cc), cc->avail);
        cc->avail = 0;
}
preempt_enable();
return 0;
```

Notice how the preemption statements must encompass every reference of the
critical variables.  Another example:

```c
int buf[NR_CPUS];
set_cpu_val(buf);
if (buf[smp_processor_id()] == -1) printf(KERN_INFO "wee!\n");
spin_lock(&buf_lock);
/* ... */
```

This code is not preempt-safe, but see how easily we can fix it by simply
moving the spin_lock up two lines.

<a id="rst-preventing-preemption-using-interrupt-disabling"></a>

## Preventing preemption using interrupt disabling

It is possible to prevent a preemption event using local_irq_disable and
local_irq_save.  Note, when doing so, you must be very careful to not cause
an event that would set need_resched and result in a preemption check.  When
in doubt, rely on locking or explicit preemption disabling.

Note in 2.5 interrupt disabling is now only per-CPU (e.g. local).

An additional concern is proper usage of local_irq_disable and local_irq_save.
These may be used to protect from preemption, however, on exit, if preemption
may be enabled, a test to see if preemption is required should be done.  If
these are called from the spin_lock and read/write lock macros, the right thing
is done.  They may also be called within a spin-lock protected region, however,
if they are ever called outside of this context, a test for preemption should
be made. Do note that calls from interrupt context or bottom half/ tasklets
are also protected by preemption locks and so may use the versions which do
not check preemption.

## Credits

**Author:** Robert Love &lt;[rml@tech9.net](<mailto:rml@tech9.net>)&gt;

---

# Priority-inheritance futexes

_Peios Kernel / Internals / Locking_

> The motivation and kernel support for lightweight priority-inheritance futexes.

<a id="rst-lightweight-pi-futexes"></a>

We are calling them lightweight for 3 reasons:

- in the user-space fastpath a PI-enabled futex involves no kernel work
  (or any other PI complexity) at all. No registration, no extra kernel
  calls - just pure fast atomic ops in userspace.

- even in the slowpath, the system call and scheduling pattern is very
  similar to normal futexes.

- the in-kernel PI implementation is streamlined around the mutex
  abstraction, with strict rules that keep the implementation
  relatively simple: only a single owner may own a lock (i.e. no
  read-write lock support), only the owner may unlock a lock, no
  recursive locking, etc.

<a id="rst-priority-inheritance-why"></a>

## Priority Inheritance - why?

The short reply: user-space PI helps achieving/improving determinism for
user-space applications. In the best-case, it can help achieve
determinism and well-bound latencies. Even in the worst-case, PI will
improve the statistical distribution of locking related application
delays.

<a id="rst-the-longer-reply"></a>

## The longer reply

Firstly, sharing locks between multiple tasks is a common programming
technique that often cannot be replaced with lockless algorithms. As we
can see it in the kernel \[which is a quite complex program in itself\],
lockless structures are rather the exception than the norm - the current
ratio of lockless vs. locky code for shared data structures is somewhere
between 1:10 and 1:100. Lockless is hard, and the complexity of lockless
algorithms often endangers to ability to do robust reviews of said code.
I.e. critical RT apps often choose lock structures to protect critical
data structures, instead of lockless algorithms. Furthermore, there are
cases (like shared hardware, or other resource limits) where lockless
access is mathematically impossible.

Media players (such as Jack) are an example of reasonable application
design with multiple tasks (with multiple priority levels) sharing
short-held locks: for example, a highprio audio playback thread is
combined with medium-prio construct-audio-data threads and low-prio
display-colory-stuff threads. Add video and decoding to the mix and
we've got even more priority levels.

So once we accept that synchronization objects (locks) are an
unavoidable fact of life, and once we accept that multi-task userspace
apps have a very fair expectation of being able to use locks, we've got
to think about how to offer the option of a deterministic locking
implementation to user-space.

Most of the technical counter-arguments against doing priority
inheritance only apply to kernel-space locks. But user-space locks are
different, there we cannot disable interrupts or make the task
non-preemptible in a critical section, so the 'use spinlocks' argument
does not apply (user-space spinlocks have the same priority inversion
problems as other user-space locking constructs). Fact is, pretty much
the only technique that currently enables good determinism for userspace
locks (such as futex-based pthread mutexes) is priority inheritance:

Currently (without PI), if a high-prio and a low-prio task shares a lock
\[this is a quite common scenario for most non-trivial RT applications\],
even if all critical sections are coded carefully to be deterministic
(i.e. all critical sections are short in duration and only execute a
limited number of instructions), the kernel cannot guarantee any
deterministic execution of the high-prio task: any medium-priority task
could preempt the low-prio task while it holds the shared lock and
executes the critical section, and could delay it indefinitely.

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

## Implementation

As mentioned before, the userspace fastpath of PI-enabled pthread
mutexes involves no kernel work at all - they behave quite similarly to
normal futex-based locks: a 0 value means unlocked, and a value==TID
means locked. (This is the same method as used by list-based robust
futexes.) Userspace uses atomic ops to lock/unlock these mutexes without
entering the kernel.

To handle the slowpath, we have added two new futex ops:

- FUTEX_LOCK_PI

- FUTEX_UNLOCK_PI

If the lock-acquire fastpath fails, \[i.e. an atomic transition from 0 to
TID fails\], then FUTEX_LOCK_PI is called. The kernel does all the
remaining work: if there is no futex-queue attached to the futex address
yet then the code looks up the task that owns the futex \[it has put its
own TID into the futex value\], and attaches a 'PI state' structure to
the futex-queue. The pi_state includes an rt-mutex, which is a PI-aware,
kernel-based synchronization object. The 'other' task is made the owner
of the rt-mutex, and the FUTEX_WAITERS bit is atomically set in the
futex value. Then this task tries to lock the rt-mutex, on which it
blocks. Once it returns, it has the mutex acquired, and it sets the
futex value to its own TID and returns. Userspace has no other work to
perform - it now owns the lock, and futex value contains
FUTEX_WAITERS\|TID.

If the unlock side fastpath succeeds, \[i.e. userspace manages to do a
TID -&gt; 0 atomic transition of the futex value\], then no kernel work is
triggered.

If the unlock fastpath fails (because the FUTEX_WAITERS bit is set),
then FUTEX_UNLOCK_PI is called, and the kernel unlocks the futex on the
behalf of userspace - and it also unlocks the attached
pi_state-&gt;rt_mutex and thus wakes up any potential waiters.

Note that under this approach, contrary to previous PI-futex approaches,
there is no prior 'registration' of a PI-futex. \[which is not quite
possible anyway, due to existing ABI properties of pthread mutexes.\]

Also, under this scheme, 'robustness' and 'PI' are two orthogonal
properties of futexes, and all four combinations are possible: futex,
robust-futex, PI-futex, robust+PI-futex.

More details about priority inheritance can be found in
[Documentation/locking/rt-mutex.rst](/kernel/internals/locking/rt-mutex.md).

---

# Requeueing priority-inheritance futexes

_Peios Kernel / Internals / Locking_

> Requeue operations and proxy locking for priority-inheritance futexes.

<a id="rst-futex-requeue-pi"></a>

Requeueing of tasks from a non-PI futex to a PI futex requires
special handling in order to ensure the underlying rt_mutex is never
left without an owner if it has waiters; doing so would break the PI
boosting logic \[see [rt-mutex-design.rst](/kernel/internals/locking/rt-mutex-design.md)\] For the purposes of
brevity, this action will be referred to as "requeue_pi" throughout
this document.  Priority inheritance is abbreviated throughout as
"PI".

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

## Motivation

Without requeue_pi, the glibc implementation of
pthread_cond_broadcast() must resort to waking all the tasks waiting
on a pthread_condvar and letting them try to sort out which task
gets to run first in classic thundering-herd formation.  An ideal
implementation would wake the highest-priority waiter, and leave the
rest to the natural wakeup inherent in unlocking the mutex
associated with the condvar.

Consider the simplified glibc calls:

```c
/* caller must lock mutex */
pthread_cond_wait(cond, mutex)
{
        lock(cond->__data.__lock);
        unlock(mutex);
        do {
        unlock(cond->__data.__lock);
        futex_wait(cond->__data.__futex);
        lock(cond->__data.__lock);
        } while(...)
        unlock(cond->__data.__lock);
        lock(mutex);
}

pthread_cond_broadcast(cond)
{
        lock(cond->__data.__lock);
        unlock(cond->__data.__lock);
        futex_requeue(cond->data.__futex, cond->mutex);
}
```

Once pthread_cond_broadcast() requeues the tasks, the cond-&gt;mutex
has waiters. Note that pthread_cond_wait() attempts to lock the
mutex only after it has returned to user space.  This will leave the
underlying rt_mutex with waiters, and no owner, breaking the
previously mentioned PI-boosting algorithms.

In order to support PI-aware pthread_condvar's, the kernel needs to
be able to requeue tasks to PI futexes.  This support implies that
upon a successful futex_wait system call, the caller would return to
user space already holding the PI futex.  The glibc implementation
would be modified as follows:

```c
/* caller must lock mutex */
pthread_cond_wait_pi(cond, mutex)
{
        lock(cond->__data.__lock);
        unlock(mutex);
        do {
        unlock(cond->__data.__lock);
        futex_wait_requeue_pi(cond->__data.__futex);
        lock(cond->__data.__lock);
        } while(...)
        unlock(cond->__data.__lock);
        /* the kernel acquired the mutex for us */
}

pthread_cond_broadcast_pi(cond)
{
        lock(cond->__data.__lock);
        unlock(cond->__data.__lock);
        futex_requeue_pi(cond->data.__futex, cond->mutex);
}
```

The actual glibc implementation will likely test for PI and make the
necessary changes inside the existing calls rather than creating new
calls for the PI cases.  Similar changes are needed for
pthread_cond_timedwait() and pthread_cond_signal().

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

## Implementation

In order to ensure the rt_mutex has an owner if it has waiters, it
is necessary for both the requeue code, as well as the waiting code,
to be able to acquire the rt_mutex before returning to user space.
The requeue code cannot simply wake the waiter and leave it to
acquire the rt_mutex as it would open a race window between the
requeue call returning to user space and the waiter waking and
starting to run.  This is especially true in the uncontended case.

The solution involves two new rt_mutex helper routines,
rt_mutex_start_proxy_lock() and rt_mutex_finish_proxy_lock(), which
allow the requeue code to acquire an uncontended rt_mutex on behalf
of the waiter and to enqueue the waiter on a contended rt_mutex.
Two new system calls provide the kernel&lt;-&gt;user interface to
requeue_pi: FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI.

FUTEX_WAIT_REQUEUE_PI is called by the waiter (pthread_cond_wait()
and pthread_cond_timedwait()) to block on the initial futex and wait
to be requeued to a PI-aware futex.  The implementation is the
result of a high-speed collision between futex_wait() and
futex_lock_pi(), with some extra logic to check for the additional
wake-up scenarios.

FUTEX_CMP_REQUEUE_PI is called by the waker
(pthread_cond_broadcast() and pthread_cond_signal()) to requeue and
possibly wake the waiting tasks. Internally, this system call is
still handled by futex_requeue (by passing requeue_pi=1).  Before
requeueing, futex_requeue() attempts to acquire the requeue target
PI futex on behalf of the top waiter.  If it can, this waiter is
woken.  futex_requeue() then proceeds to requeue the remaining
nr_wake+nr_requeue tasks to the PI futex, calling
rt_mutex_start_proxy_lock() prior to each requeue to prepare the
task as a waiter on the underlying rt_mutex.  It is possible that
the lock can be acquired at this stage as well, if so, the next
waiter is woken to finish the acquisition of the lock.

FUTEX_CMP_REQUEUE_PI accepts nr_wake and nr_requeue as arguments, but
their sum is all that really matters.  futex_requeue() will wake or
requeue up to nr_wake + nr_requeue tasks.  It will wake only as many
tasks as it can acquire the lock for, which in the majority of cases
should be 0 as good programming practice dictates that the caller of
either pthread_cond_broadcast() or pthread_cond_signal() acquire the
mutex prior to making the call. FUTEX_CMP_REQUEUE_PI requires that
nr_wake=1.  nr_requeue should be INT_MAX for broadcast and 0 for
signal.

---

# Robust futexes

_Peios Kernel / Internals / Locking_

> Recovering userspace locks when their owner exits, using robust futex lists.

<a id="rst-a-description-of-what-robust-futexes-are"></a>

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

## Background

what are robust futexes? To answer that, we first need to understand
what futexes are: normal futexes are special types of locks that in the
noncontended case can be acquired/released from userspace without having
to enter the kernel.

A futex is in essence a user-space address, e.g. a 32-bit lock variable
field. If userspace notices contention (the lock is already owned and
someone else wants to grab it too) then the lock is marked with a value
that says "there's a waiter pending", and the sys_futex(FUTEX_WAIT)
syscall is used to wait for the other guy to release it. The kernel
creates a 'futex queue' internally, so that it can later on match up the
waiter with the waker - without them having to know about each other.
When the owner thread releases the futex, it notices (via the variable
value) that there were waiter(s) pending, and does the
sys_futex(FUTEX_WAKE) syscall to wake them up.  Once all waiters have
taken and released the lock, the futex is again back to 'uncontended'
state, and there's no in-kernel state associated with it. The kernel
completely forgets that there ever was a futex at that address. This
method makes futexes very lightweight and scalable.

"Robustness" is about dealing with crashes while holding a lock: if a
process exits prematurely while holding a pthread_mutex_t lock that is
also shared with some other process (e.g. yum segfaults while holding a
pthread_mutex_t, or yum is kill -9-ed), then waiters for that lock need
to be notified that the last owner of the lock exited in some irregular
way.

To solve such types of problems, "robust mutex" userspace APIs were
created: pthread_mutex_lock() returns an error value if the owner exits
prematurely - and the new owner can decide whether the data protected by
the lock can be recovered safely.

There is a big conceptual problem with futex based mutexes though: it is
the kernel that destroys the owner task (e.g. due to a SEGFAULT), but
the kernel cannot help with the cleanup: if there is no 'futex queue'
(and in most cases there is none, futexes being fast lightweight locks)
then the kernel has no information to clean up after the held lock\!
Userspace has no chance to clean up after the lock either - userspace is
the one that crashes, so it has no opportunity to clean up. Catch-22.

In practice, when e.g. yum is kill -9-ed (or segfaults), a system reboot
is needed to release that futex based lock. This is one of the leading
bugreports against yum.

To solve this problem, the traditional approach was to extend the vma
(virtual memory area descriptor) concept to have a notion of 'pending
robust futexes attached to this area'. This approach requires 3 new
syscall variants to sys_futex(): FUTEX_REGISTER, FUTEX_DEREGISTER and
FUTEX_RECOVER. At do_exit() time, all vmas are searched to see whether
they have a robust_head set. This approach has two fundamental problems
left:

- it has quite complex locking and race scenarios. The vma-based
  approach had been pending for years, but they are still not completely
  reliable.

- they have to scan \_every\_ vma at sys_exit() time, per thread\!

The second disadvantage is a real killer: pthread_exit() takes around 1
microsecond on Linux, but with thousands (or tens of thousands) of vmas
every pthread_exit() takes a millisecond or more, also totally
destroying the CPU's L1 and L2 caches\!

This is very much noticeable even for normal process sys_exit_group()
calls: the kernel has to do the vma scanning unconditionally\! (this is
because the kernel has no knowledge about how many robust futexes there
are to be cleaned up, because a robust futex might have been registered
in another task, and the futex variable might have been simply mmap()-ed
into this process's address space).

This huge overhead forced the creation of CONFIG_FUTEX_ROBUST so that
normal kernels can turn it off, but worse than that: the overhead makes
robust futexes impractical for any type of generic Linux distribution.

So something had to be done.

<a id="rst-new-approach-to-robust-futexes"></a>

## New approach to robust futexes

At the heart of this new approach there is a per-thread private list of
robust locks that userspace is holding (maintained by glibc) - which
userspace list is registered with the kernel via a new syscall \[this
registration happens at most once per thread lifetime\]. At do_exit()
time, the kernel checks this user-space list: are there any robust futex
locks to be cleaned up?

In the common case, at do_exit() time, there is no list registered, so
the cost of robust futexes is just a simple current-&gt;robust_list \!= NULL
comparison. If the thread has registered a list, then normally the list
is empty. If the thread/process crashed or terminated in some incorrect
way then the list might be non-empty: in this case the kernel carefully
walks the list \[not trusting it\], and marks all locks that are owned by
this thread with the FUTEX_OWNER_DIED bit, and wakes up one waiter (if
any).

The list is guaranteed to be private and per-thread at do_exit() time,
so it can be accessed by the kernel in a lockless way.

There is one race possible though: since adding to and removing from the
list is done after the futex is acquired by glibc, there is a few
instructions window for the thread (or process) to die there, leaving
the futex hung. To protect against this possibility, userspace (glibc)
also maintains a simple per-thread 'list_op_pending' field, to allow the
kernel to clean up if the thread dies after acquiring the lock, but just
before it could have added itself to the list. Glibc sets this
list_op_pending field before it tries to acquire the futex, and clears
it after the list-add (or list-remove) has finished.

That's all that is needed - all the rest of robust-futex cleanup is done
in userspace \[just like with the previous patches\].

Ulrich Drepper has implemented the necessary glibc support for this new
mechanism, which fully enables robust mutexes.

Key differences of this userspace-list based approach, compared to the
vma based method:

- it's much, much faster: at thread exit time, there's no need to loop
  over every vma (\!), which the VM-based method has to do. Only a very
  simple 'is the list empty' op is done.

- no VM changes are needed - 'struct address_space' is left alone.

- no registration of individual locks is needed: robust mutexes don't
  need any extra per-lock syscalls. Robust mutexes thus become a very
  lightweight primitive - so they don't force the application designer
  to do a hard choice between performance and robustness - robust
  mutexes are just as fast.

- no per-lock kernel allocation happens.

- no resource limits are needed.

- no kernel-space recovery call (FUTEX_RECOVER) is needed.

- the implementation and the locking is "obvious", and there are no
  interactions with the VM.

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

## Performance

I have benchmarked the time needed for the kernel to process a list of 1
million (\!) held locks, using the new method \[on a 2GHz CPU\]:

- with FUTEX_WAIT set \[contended mutex\]: 130 msecs

- without FUTEX_WAIT set \[uncontended mutex\]: 30 msecs

I have also measured an approach where glibc does the lock notification
\[which it currently does for \!pshared robust mutexes\], and that took 256
msecs - clearly slower, due to the 1 million FUTEX_WAKE syscalls
userspace had to do.

(1 million held locks are unheard of - we expect at most a handful of
locks to be held at a time. Nevertheless it's nice to know that this
approach scales nicely.)

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

## Implementation details

The patch adds two new syscalls: one to register the userspace list, and
one to query the registered list pointer:

```c
asmlinkage long
sys_set_robust_list(struct robust_list_head __user *head,
                    size_t len);

asmlinkage long
sys_get_robust_list(int pid, struct robust_list_head __user **head_ptr,
                    size_t __user *len_ptr);
```

List registration is very fast: the pointer is simply stored in
current-&gt;robust_list. \[Note that in the future, if robust futexes become
widespread, we could extend sys_clone() to register a robust-list head
for new threads, without the need of another syscall.\]

So there is virtually zero overhead for tasks not using robust futexes,
and even for robust futex users, there is only one extra syscall per
thread lifetime, and the cleanup operation, if it happens, is fast and
straightforward. The kernel doesn't have any internal distinction between
robust and normal futexes.

If a futex is found to be held at exit time, the kernel sets the
following bit of the futex word:

```c
#define FUTEX_OWNER_DIED        0x40000000
```

and wakes up the next futex waiter (if any). User-space does the rest of
the cleanup.

Otherwise, robust futexes are acquired by glibc by putting the TID into
the futex field atomically. Waiters set the FUTEX_WAITERS bit:

```c
#define FUTEX_WAITERS           0x80000000
```

and the remaining bits are for the TID.

<a id="rst-testing-architecture-support"></a>

## Testing, architecture support

I've tested the new syscalls on x86 and x86_64, and have made sure the
parsing of the userspace list is robust \[ ;-) \] even if the list is
deliberately corrupted.

i386 and x86_64 syscalls are wired up at the moment, and Ulrich has
tested the new glibc code (on x86_64 and i386), and it works for his
robust-mutex testcases.

All other architectures should build just fine too - but they won't have
the new syscalls yet.

Architectures need to implement the new futex_atomic_cmpxchg_inatomic()
inline function before writing up the syscalls.

## Credits

**Started by:** Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;

---

# Robust futex ABI

_Peios Kernel / Internals / Locking_

> The userspace list layout and kernel interface for robust futex recovery.

<a id="rst-the-robust-futex-abi"></a>

Robust_futexes provide a mechanism that is used in addition to normal
futexes, for kernel assist of cleanup of held locks on task exit.

The interesting data as to what futexes a thread is holding is kept on a
linked list in user space, where it can be updated efficiently as locks
are taken and dropped, without kernel intervention.  The only additional
kernel intervention required for robust_futexes above and beyond what is
required for futexes is:

1. a one time call, per thread, to tell the kernel where its list of
   held robust_futexes begins, and

2. internal kernel code at exit, to handle any listed locks held
   by the exiting thread.

The existing normal futexes already provide a "Fast Userspace Locking"
mechanism, which handles uncontested locking without needing a system
call, and handles contested locking by maintaining a list of waiting
threads in the kernel.  Options on the sys_futex(2) system call support
waiting on a particular futex, and waking up the next waiter on a
particular futex.

For robust_futexes to work, the user code (typically in a library such
as glibc linked with the application) has to manage and place the
necessary list elements exactly as the kernel expects them.  If it fails
to do so, then improperly listed locks will not be cleaned up on exit,
probably causing deadlock or other such failure of the other threads
waiting on the same locks.

A thread that anticipates possibly using robust_futexes should first
issue the system call:

```c
asmlinkage long
sys_set_robust_list(struct robust_list_head __user *head, size_t len);
```

The pointer 'head' points to a structure in the threads address space
consisting of three words.  Each word is 32 bits on 32 bit arch's, or 64
bits on 64 bit arch's, and local byte order.  Each thread should have
its own thread private 'head'.

If a thread is running in 32 bit compatibility mode on a 64 native arch
kernel, then it can actually have two such structures - one using 32 bit
words for 32 bit compatibility mode, and one using 64 bit words for 64
bit native mode.  The kernel, if it is a 64 bit kernel supporting 32 bit
compatibility mode, will attempt to process both lists on each task
exit, if the corresponding sys_set_robust_list() call has been made to
setup that list.

> The first word in the memory structure at 'head' contains a
> pointer to a single linked list of 'lock entries', one per lock,
> as described below.  If the list is empty, the pointer will point
> to itself, 'head'.  The last 'lock entry' points back to the 'head'.
>
> The second word, called 'offset', specifies the offset from the
> address of the associated 'lock entry', plus or minus, of what will
> be called the 'lock word', from that 'lock entry'.  The 'lock word'
> is always a 32 bit word, unlike the other words above.  The 'lock
> word' holds 2 flag bits in the upper 2 bits, and the thread id (TID)
> of the thread holding the lock in the bottom 30 bits.  See further
> below for a description of the flag bits.
>
> The third word, called 'list_op_pending', contains transient copy of
> the address of the 'lock entry', during list insertion and removal,
> and is needed to correctly resolve races should a thread exit while
> in the middle of a locking or unlocking operation.

Each 'lock entry' on the single linked list starting at 'head' consists
of just a single word, pointing to the next 'lock entry', or back to
'head' if there are no more entries.  In addition, nearby to each 'lock
entry', at an offset from the 'lock entry' specified by the 'offset'
word, is one 'lock word'.

The 'lock word' is always 32 bits, and is intended to be the same 32 bit
lock variable used by the futex mechanism, in conjunction with
robust_futexes.  The kernel will only be able to wakeup the next thread
waiting for a lock on a threads exit if that next thread used the futex
mechanism to register the address of that 'lock word' with the kernel.

For each futex lock currently held by a thread, if it wants this
robust_futex support for exit cleanup of that lock, it should have one
'lock entry' on this list, with its associated 'lock word' at the
specified 'offset'.  Should a thread die while holding any such locks,
the kernel will walk this list, mark any such locks with a bit
indicating their holder died, and wakeup the next thread waiting for
that lock using the futex mechanism.

When a thread has invoked the above system call to indicate it
anticipates using robust_futexes, the kernel stores the passed in 'head'
pointer for that task.  The task may retrieve that value later on by
using the system call:

```c
asmlinkage long
sys_get_robust_list(int pid, struct robust_list_head __user **head_ptr,
                    size_t __user *len_ptr);
```

It is anticipated that threads will use robust_futexes embedded in
larger, user level locking structures, one per lock.  The kernel
robust_futex mechanism doesn't care what else is in that structure, so
long as the 'offset' to the 'lock word' is the same for all
robust_futexes used by that thread.  The thread should link those locks
it currently holds using the 'lock entry' pointers.  It may also have
other links between the locks, such as the reverse side of a double
linked list, but that doesn't matter to the kernel.

By keeping its locks linked this way, on a list starting with a 'head'
pointer known to the kernel, the kernel can provide to a thread the
essential service available for robust_futexes, which is to help clean
up locks held at the time of (a perhaps unexpectedly) exit.

Actual locking and unlocking, during normal operations, is handled
entirely by user level code in the contending threads, and by the
existing futex mechanism to wait for, and wakeup, locks.  The kernels
only essential involvement in robust_futexes is to remember where the
list 'head' is, and to walk the list on thread exit, handling locks
still held by the departing thread, as described below.

There may exist thousands of futex lock structures in a threads shared
memory, on various data structures, at a given point in time. Only those
lock structures for locks currently held by that thread should be on
that thread's robust_futex linked lock list a given time.

A given futex lock structure in a user shared memory region may be held
at different times by any of the threads with access to that region. The
thread currently holding such a lock, if any, is marked with the threads
TID in the lower 30 bits of the 'lock word'.

When adding or removing a lock from its list of held locks, in order for
the kernel to correctly handle lock cleanup regardless of when the task
exits (perhaps it gets an unexpected signal 9 in the middle of
manipulating this list), the user code must observe the following
protocol on 'lock entry' insertion and removal:

On insertion:

1. set the 'list_op_pending' word to the address of the 'lock entry'
   to be inserted,

2. acquire the futex lock,

3. add the lock entry, with its thread id (TID) in the bottom 30 bits
   of the 'lock word', to the linked list starting at 'head', and

4. clear the 'list_op_pending' word.

On removal:

1. set the 'list_op_pending' word to the address of the 'lock entry'
   to be removed,

2. remove the lock entry for this lock from the 'head' list,

3. release the futex lock, and

4. clear the 'lock_op_pending' word.

On exit, the kernel will consider the address stored in
'list_op_pending' and the address of each 'lock word' found by walking
the list starting at 'head'.  For each such address, if the bottom 30
bits of the 'lock word' at offset 'offset' from that address equals the
exiting threads TID, then the kernel will do two things:

1. if bit 31 (0x80000000) is set in that word, then attempt a futex
   wakeup on that address, which will waken the next thread that has
   used to the futex mechanism to wait on that address, and

2. atomically set  bit 30 (0x40000000) in the 'lock word'.

In the above, bit 31 was set by futex waiters on that lock to indicate
they were waiting, and bit 30 is set by the kernel to indicate that the
lock owner died holding the lock.

The kernel exit code will silently stop scanning the list further if at
any point:

1. the 'head' pointer or an subsequent linked list pointer
   is not a valid address of a user space word

2. the calculated location of the 'lock word' (address plus
   'offset') is not the valid address of a 32 bit user space
   word

3. if the list contains more than 1 million (subject to
   future kernel configuration changes) elements.

When the kernel sees a list entry whose 'lock word' doesn't have the
current threads TID in the lower 30 bits, it does nothing with that
entry, and goes on to the next entry.

## Credits

**Author:** Started by Paul Jackson &lt;[pj@sgi.com](<mailto:pj@sgi.com>)&gt;

---

# Lock dependency validation

_Peios Kernel / Internals / Locking_

> Lock classes, dependency checks, nesting, and lockdep annotations.

<a id="rst-runtime-locking-correctness-validator"></a>

additions by Arjan van de Ven &lt;[arjan@linux.intel.com](<mailto:arjan@linux.intel.com>)&gt;

<a id="rst-lock-class"></a>

## Lock-class

The basic object the validator operates upon is a 'class' of locks.

A class of locks is a group of locks that are logically the same with
respect to locking rules, even if the locks may have multiple (possibly
tens of thousands of) instantiations. For example a lock in the inode
struct is one class, while each inode has its own instantiation of that
lock class.

The validator tracks the 'usage state' of lock-classes, and it tracks
the dependencies between different lock-classes. Lock usage indicates
how a lock is used with regard to its IRQ contexts, while lock
dependency can be understood as lock order, where L1 -&gt; L2 suggests that
a task is attempting to acquire L2 while holding L1. From lockdep's
perspective, the two locks (L1 and L2) are not necessarily related; that
dependency just means the order ever happened. The validator maintains a
continuing effort to prove lock usages and dependencies are correct or
the validator will shoot a splat if incorrect.

A lock-class's behavior is constructed by its instances collectively:
when the first instance of a lock-class is used after bootup the class
gets registered, then all (subsequent) instances will be mapped to the
class and hence their usages and dependencies will contribute to those of
the class. A lock-class does not go away when a lock instance does, but
it can be removed if the memory space of the lock class (static or
dynamic) is reclaimed, this happens for example when a module is
unloaded or a workqueue is destroyed.

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

## State

The validator tracks lock-class usage history and divides the usage into
(4 usages \* n STATEs + 1) categories:

where the 4 usages can be:

- 'ever held in STATE context'

- 'ever held as readlock in STATE context'

- 'ever held with STATE enabled'

- 'ever held as readlock with STATE enabled'

where the n STATEs are coded in kernel/locking/lockdep_states.h and as of
now they include:

- hardirq

- softirq

where the last 1 category is:

- 'ever used'                                       \[ == \!unused        \]

When locking rules are violated, these usage bits are presented in the
locking error messages, inside curlies, with a total of 2 \* n STATEs bits.
A contrived example:

```text
modprobe/2287 is trying to acquire lock:
 (&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24

but task is already holding lock:
 (&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24
```

For a given lock, the bit positions from left to right indicate the usage
of the lock and readlock (if exists), for each of the n STATEs listed
above respectively, and the character displayed at each bit position
indicates:

<table>
<tbody>
<tr>
<td><p>&#x27;.&#x27;</p></td>
<td><p>acquired while irqs disabled and not in irq context</p></td>
</tr>
<tr>
<td><p>&#x27;-&#x27;</p></td>
<td><p>acquired in irq context</p></td>
</tr>
<tr>
<td><p>&#x27;+&#x27;</p></td>
<td><p>acquired with irqs enabled</p></td>
</tr>
<tr>
<td><p>&#x27;?&#x27;</p></td>
<td><p>acquired in irq context with irqs enabled.</p></td>
</tr>
</tbody>
</table>

The bits are illustrated with an example:

```text
(&sio_locks[i].lock){-.-.}, at: [<c02867fd>] mutex_lock+0x21/0x24
                     ||||
                     ||| \-> softirq disabled and not in softirq context
                     || \--> acquired in softirq context
                     | \---> hardirq disabled and not in hardirq context
                      \----> acquired in hardirq context
```

For a given STATE, whether the lock is ever acquired in that STATE
context and whether that STATE is enabled yields four possible cases as
shown in the table below. The bit character is able to indicate which
exact case is for the lock as of the reporting time.

<table>
<tbody>
<tr>
<td></td>
<td><p>irq enabled</p></td>
<td><p>irq disabled</p></td>
</tr>
<tr>
<td><p>ever in irq</p></td>
<td><p>&#x27;?&#x27;</p></td>
<td><p>&#x27;-&#x27;</p></td>
</tr>
<tr>
<td><p>never in irq</p></td>
<td><p>&#x27;+&#x27;</p></td>
<td><p>&#x27;.&#x27;</p></td>
</tr>
</tbody>
</table>

The character '-' suggests irq is disabled because if otherwise the
character '?' would have been shown instead. Similar deduction can be
applied for '+' too.

Unused locks (e.g., mutexes) cannot be part of the cause of an error.

<a id="rst-single-lock-state-rules"></a>

## Single-lock state rules:

A lock is irq-safe means it was ever used in an irq context, while a lock
is irq-unsafe means it was ever acquired with irq enabled.

A softirq-unsafe lock-class is automatically hardirq-unsafe as well. The
following states must be exclusive: only one of them is allowed to be set
for any lock-class based on its usage:

```text
<hardirq-safe> or <hardirq-unsafe>
<softirq-safe> or <softirq-unsafe>
```

This is because if a lock can be used in irq context (irq-safe) then it
cannot be ever acquired with irq enabled (irq-unsafe). Otherwise, a
deadlock may happen. For example, in the scenario that after this lock
was acquired but before released, if the context is interrupted this
lock will be attempted to acquire twice, which creates a deadlock,
referred to as lock recursion deadlock.

The validator detects and reports lock usage that violates these
single-lock state rules.

<a id="rst-multi-lock-dependency-rules"></a>

## Multi-lock dependency rules:

The same lock-class must not be acquired twice, because this could lead
to lock recursion deadlocks.

Furthermore, two locks can not be taken in inverse order:

```text
<L1> -> <L2>
<L2> -> <L1>
```

because this could lead to a deadlock - referred to as lock inversion
deadlock - as attempts to acquire the two locks form a circle which
could lead to the two contexts waiting for each other permanently. The
validator will find such dependency circle in arbitrary complexity,
i.e., there can be any other locking sequence between the acquire-lock
operations; the validator will still find whether these locks can be
acquired in a circular fashion.

Furthermore, the following usage based lock dependencies are not allowed
between any two lock-classes:

```text
<hardirq-safe>   ->  <hardirq-unsafe>
<softirq-safe>   ->  <softirq-unsafe>
```

The first rule comes from the fact that a hardirq-safe lock could be
taken by a hardirq context, interrupting a hardirq-unsafe lock - and
thus could result in a lock inversion deadlock. Likewise, a softirq-safe
lock could be taken by an softirq context, interrupting a softirq-unsafe
lock.

The above rules are enforced for any locking sequence that occurs in the
kernel: when acquiring a new lock, the validator checks whether there is
any rule violation between the new lock and any of the held locks.

When a lock-class changes its state, the following aspects of the above
dependency rules are enforced:

- if a new hardirq-safe lock is discovered, we check whether it
  took any hardirq-unsafe lock in the past.

- if a new softirq-safe lock is discovered, we check whether it took
  any softirq-unsafe lock in the past.

- if a new hardirq-unsafe lock is discovered, we check whether any
  hardirq-safe lock took it in the past.

- if a new softirq-unsafe lock is discovered, we check whether any
  softirq-safe lock took it in the past.

(Again, we do these checks too on the basis that an interrupt context
could interrupt \_any\_ of the irq-unsafe or hardirq-unsafe locks, which
could lead to a lock inversion deadlock - even if that lock scenario did
not trigger in practice yet.)

<a id="rst-exception-nested-data-dependencies-leading-to-nested-locking"></a>

## Exception: Nested data dependencies leading to nested locking

There are a few cases where the Linux kernel acquires more than one
instance of the same lock-class. Such cases typically happen when there
is some sort of hierarchy within objects of the same type. In these
cases there is an inherent "natural" ordering between the two objects
(defined by the properties of the hierarchy), and the kernel grabs the
locks in this fixed order on each of the objects.

An example of such an object hierarchy that results in "nested locking"
is that of a "whole disk" block-dev object and a "partition" block-dev
object; the partition is "part of" the whole device and as long as one
always takes the whole disk lock as a higher lock than the partition
lock, the lock ordering is fully correct. The validator does not
automatically detect this natural ordering, as the locking rule behind
the ordering is not static.

In order to teach the validator about this correct usage model, new
versions of the various locking primitives were added that allow you to
specify a "nesting level". An example call, for the block device mutex,
looks like this:

```c
enum bdev_bd_mutex_lock_class
{
     BD_MUTEX_NORMAL,
     BD_MUTEX_WHOLE,
     BD_MUTEX_PARTITION
};

mutex_lock_nested(&bdev->bd_contains->bd_mutex, BD_MUTEX_PARTITION);
```

In this case the locking is done on a bdev object that is known to be a
partition.

The validator treats a lock that is taken in such a nested fashion as a
separate (sub)class for the purposes of validation.

Note: When changing code to use the \_nested() primitives, be careful and
check really thoroughly that the hierarchy is correctly mapped; otherwise
you can get false positives or false negatives.

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

## Annotations

Two constructs can be used to annotate and check where and if certain locks
must be held: lockdep_assert_held\*(&amp;lock) and lockdep\_\*pin_lock(&amp;lock).

As the name suggests, lockdep_assert_held\* family of macros assert that a
particular lock is held at a certain time (and generate a WARN() otherwise).
This annotation is largely used all over the kernel, e.g. kernel/sched/
core.c:

```c
void update_rq_clock(struct rq *rq)
{
      s64 delta;

      lockdep_assert_held(&rq->lock);
      [...]
}
```

where holding rq-&gt;lock is required to safely update a rq's clock.

The other family of macros is lockdep\_\*pin_lock(), which is admittedly only
used for rq-&gt;lock ATM. Despite their limited adoption these annotations
generate a WARN() if the lock of interest is "accidentally" unlocked. This turns
out to be especially helpful to debug code with callbacks, where an upper
layer assumes a lock remains taken, but a lower layer thinks it can maybe drop
and reacquire the lock ("unwittingly" introducing races). lockdep_pin_lock()
returns a 'struct pin_cookie' that is then used by lockdep_unpin_lock() to check
that nobody tampered with the lock, e.g. kernel/sched/sched.h:

```c
static inline void rq_pin_lock(struct rq *rq, struct rq_flags *rf)
{
      rf->cookie = lockdep_pin_lock(&rq->lock);
      [...]
}

static inline void rq_unpin_lock(struct rq *rq, struct rq_flags *rf)
{
      [...]
      lockdep_unpin_lock(&rq->lock, rf->cookie);
}
```

While comments about locking requirements might provide useful information,
the runtime checks performed by annotations are invaluable when debugging
locking problems and they carry the same level of details when inspecting
code.  Always prefer annotations when in doubt\!

<a id="rst-proof-of-100-correctness"></a>

## Proof of 100% correctness:

The validator achieves perfect, mathematical 'closure' (proof of locking
correctness) in the sense that for every simple, standalone single-task
locking sequence that occurred at least once during the lifetime of the
kernel, the validator proves it with a 100% certainty that no
combination and timing of these locking sequences can cause any class of
lock related deadlock. [1](#rst-footnote-1)

I.e. complex multi-CPU and multi-task locking scenarios do not have to
occur in practice to prove a deadlock: only the simple 'component'
locking chains have to occur at least once (anytime, in any
task/context) for the validator to be able to prove correctness. (For
example, complex deadlocks that would normally need more than 3 CPUs and
a very unlikely constellation of tasks, irq-contexts and timings to
occur, can be detected on a plain, lightly loaded single-CPU system as
well\!)

This radically decreases the complexity of locking related QA of the
kernel: what has to be done during QA is to trigger as many "simple"
single-task locking dependencies in the kernel as possible, at least
once, to prove locking correctness - instead of having to trigger every
possible combination of locking interaction between CPUs, combined with
every possible hardirq and softirq nesting scenario (which is impossible
to do in practice).

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

**[1]** assuming that the validator itself is 100% correct, and no other
part of the system corrupts the state of the validator in any way.
We also assume that all NMI/SMM paths \[which could interrupt
even hardirq-disabled codepaths\] are correct and do not interfere
with the validator. We also assume that the 64-bit 'chain hash'
value is unique for every lock-chain in the system. Also, lock
recursion must not be higher than 20.

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

## Performance:

The above rules require **massive** amounts of runtime checking. If we did
that for every lock taken and for every irqs-enable event, it would
render the system practically unusably slow. The complexity of checking
is O(N^2), so even with just a few hundred lock-classes we'd have to do
tens of thousands of checks for every event.

This problem is solved by checking any given 'locking scenario' (unique
sequence of locks taken after each other) only once. A simple stack of
held locks is maintained, and a lightweight 64-bit hash value is
calculated, which hash is unique for every lock chain. The hash value,
when the chain is validated for the first time, is then put into a hash
table, which hash-table can be checked in a lockfree manner. If the
locking chain occurs again later on, the hash table tells us that we
don't have to validate the chain again.

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

## Troubleshooting:

The validator tracks a maximum of MAX_LOCKDEP_KEYS number of lock classes.
Exceeding this number will trigger the following lockdep warning:

```c
(DEBUG_LOCKS_WARN_ON(id >= MAX_LOCKDEP_KEYS))
```

By default, MAX_LOCKDEP_KEYS is currently set to 8191, and typical
desktop systems have less than 1,000 lock classes, so this warning
normally results from lock-class leakage or failure to properly
initialize locks.  These two problems are illustrated below:

1. Repeated module loading and unloading while running the validator
   will result in lock-class leakage.  The issue here is that each
   load of the module will create a new set of lock classes for
   that module's locks, but module unloading does not remove old
   classes (see below discussion of reuse of lock classes for why).
   Therefore, if that module is loaded and unloaded repeatedly,
   the number of lock classes will eventually reach the maximum.

2. Using structures such as arrays that have large numbers of
   locks that are not explicitly initialized.  For example,
   a hash table with 8192 buckets where each bucket has its own
   spinlock_t will consume 8192 lock classes -unless- each spinlock
   is explicitly initialized at runtime, for example, using the
   run-time spin_lock_init() as opposed to compile-time initializers
   such as \__SPIN_LOCK_UNLOCKED().  Failure to properly initialize
   the per-bucket spinlocks would guarantee lock-class overflow.
   In contrast, a loop that called spin_lock_init() on each lock
   would place all 8192 locks into a single lock class.

   The moral of this story is that you should always explicitly
   initialize your locks.

One might argue that the validator should be modified to allow
lock classes to be reused.  However, if you are tempted to make this
argument, first review the code and think through the changes that would
be required, keeping in mind that the lock classes to be removed are
likely to be linked into the lock-dependency graph.  This turns out to
be harder to do than to say.

Of course, if you do run out of lock classes, the next thing to do is
to find the offending lock classes.  First, the following command gives
you the number of lock classes currently in use along with the maximum:

```bash
grep "lock-classes" /proc/lockdep_stats
```

This command produces the following output on a modest system:

```text
lock-classes:                          748 [max: 8191]
```

If the number allocated (748 above) increases continually over time,
then there is likely a leak.  The following command can be used to
identify the leaking lock classes:

```bash
grep "BD" /proc/lockdep
```

Run the command and save the output, then compare against the output from
a later run of this command to identify the leakers.  This same output
can also help you find situations where runtime lock initialization has
been omitted.

<a id="rst-recursive-read-locks"></a>

## Recursive read locks:

The whole of the rest document tries to prove a certain type of cycle is equivalent
to deadlock possibility.

There are three types of lockers: writers (i.e. exclusive lockers, like
spin_lock() or write_lock()), non-recursive readers (i.e. shared lockers, like
down_read()) and recursive readers (recursive shared lockers, like rcu_read_lock()).
And we use the following notations of those lockers in the rest of the document:

> W or E: stands for writers (exclusive lockers).
> r:      stands for non-recursive readers.
> R:      stands for recursive readers.
> S:      stands for all readers (non-recursive + recursive), as both are shared lockers.
> N:      stands for writers and non-recursive readers, as both are not recursive.

Obviously, N is "r or W" and S is "r or R".

Recursive readers, as their name indicates, are the lockers allowed to acquire
even inside the critical section of another reader of the same lock instance,
in other words, allowing nested read-side critical sections of one lock instance.

While non-recursive readers will cause a self deadlock if trying to acquire inside
the critical section of another reader of the same lock instance.

The difference between recursive readers and non-recursive readers is because:
recursive readers get blocked only by a write lock *holder*, while non-recursive
readers could get blocked by a write lock *waiter*. Considering the follow
example:

```text
TASK A:                 TASK B:

read_lock(X);
                        write_lock(X);
read_lock_2(X);
```

Task A gets the reader (no matter whether recursive or non-recursive) on X via
read_lock() first. And when task B tries to acquire writer on X, it will block
and become a waiter for writer on X. Now if read_lock_2() is recursive readers,
task A will make progress, because writer waiters don't block recursive readers,
and there is no deadlock. However, if read_lock_2() is non-recursive readers,
it will get blocked by writer waiter B, and cause a self deadlock.

<a id="rst-block-conditions-on-readers-writers-of-the-same-lock-instance"></a>

## Block conditions on readers/writers of the same lock instance:

There are simply four block conditions:

1. Writers block other writers.

2. Readers block writers.

3. Writers block both recursive readers and non-recursive readers.

4. And readers (recursive or not) don't block other recursive readers but
   may block non-recursive readers (because of the potential co-existing
   writer waiters)

Block condition matrix, Y means the row blocks the column, and N means otherwise.

<table>
<tbody>
<tr>
<td></td>
<td><p>W</p></td>
<td><p>r</p></td>
<td><p>R</p></td>
</tr>
<tr>
<td><p>W</p></td>
<td><p>Y</p></td>
<td><p>Y</p></td>
<td><p>Y</p></td>
</tr>
<tr>
<td><p>r</p></td>
<td><p>Y</p></td>
<td><p>Y</p></td>
<td><p>N</p></td>
</tr>
<tr>
<td><p>R</p></td>
<td><p>Y</p></td>
<td><p>Y</p></td>
<td><p>N</p></td>
</tr>
</tbody>
</table>

(W: writers, r: non-recursive readers, R: recursive readers)

acquired recursively. Unlike non-recursive read locks, recursive read locks
only get blocked by current write lock *holders* other than write lock
*waiters*, for example:

```text
TASK A:                 TASK B:

read_lock(X);

                        write_lock(X);

read_lock(X);
```

is not a deadlock for recursive read locks, as while the task B is waiting for
the lock X, the second read_lock() doesn't need to wait because it's a recursive
read lock. However if the read_lock() is non-recursive read lock, then the above
case is a deadlock, because even if the write_lock() in TASK B cannot get the
lock, but it can block the second read_lock() in TASK A.

Note that a lock can be a write lock (exclusive lock), a non-recursive read
lock (non-recursive shared lock) or a recursive read lock (recursive shared
lock), depending on the lock operations used to acquire it (more specifically,
the value of the 'read' parameter for lock_acquire()). In other words, a single
lock instance has three types of acquisition depending on the acquisition
functions: exclusive, non-recursive read, and recursive read.

To be concise, we call that write locks and non-recursive read locks as
"non-recursive" locks and recursive read locks as "recursive" locks.

Recursive locks don't block each other, while non-recursive locks do (this is
even true for two non-recursive read locks). A non-recursive lock can block the
corresponding recursive lock, and vice versa.

A deadlock case with recursive locks involved is as follow:

```text
TASK A:                 TASK B:

read_lock(X);
                        read_lock(Y);
write_lock(Y);
                        write_lock(X);
```

Task A is waiting for task B to read_unlock() Y and task B is waiting for task
A to read_unlock() X.

<a id="rst-dependency-types-and-strong-dependency-paths"></a>

## Dependency types and strong dependency paths:

Lock dependencies record the orders of the acquisitions of a pair of locks, and
because there are 3 types for lockers, there are, in theory, 9 types of lock
dependencies, but we can show that 4 types of lock dependencies are enough for
deadlock detection.

For each lock dependency:

```text
L1 -> L2
```

, which means lockdep has seen L1 held before L2 held in the same context at runtime.
And in deadlock detection, we care whether we could get blocked on L2 with L1 held,
IOW, whether there is a locker L3 that L1 blocks L3 and L2 gets blocked by L3. So
we only care about 1) what L1 blocks and 2) what blocks L2. As a result, we can combine
recursive readers and non-recursive readers for L1 (as they block the same types) and
we can combine writers and non-recursive readers for L2 (as they get blocked by the
same types).

With the above combination for simplification, there are 4 types of dependency edges
in the lockdep graph:

1. - **-(ER)-&gt;:**

     exclusive writer to recursive reader dependency, "X -(ER)-&gt; Y" means
     X -&gt; Y and X is a writer and Y is a recursive reader.

2. - **-(EN)-&gt;:**

     exclusive writer to non-recursive locker dependency, "X -(EN)-&gt; Y" means
     X -&gt; Y and X is a writer and Y is either a writer or non-recursive reader.

3. - **-(SR)-&gt;:**

     shared reader to recursive reader dependency, "X -(SR)-&gt; Y" means
     X -&gt; Y and X is a reader (recursive or not) and Y is a recursive reader.

4. - **-(SN)-&gt;:**

     shared reader to non-recursive locker dependency, "X -(SN)-&gt; Y" means
     X -&gt; Y and X is a reader (recursive or not) and Y is either a writer or
     non-recursive reader.

Note that given two locks, they may have multiple dependencies between them,
for example:

```text
TASK A:

read_lock(X);
write_lock(Y);
...

TASK B:

write_lock(X);
write_lock(Y);
```

, we have both X -(SN)-&gt; Y and X -(EN)-&gt; Y in the dependency graph.

We use -(xN)-&gt; to represent edges that are either -(EN)-&gt; or -(SN)-&gt;, the
similar for -(Ex)-&gt;, -(xR)-&gt; and -(Sx)-&gt;

A "path" is a series of conjunct dependency edges in the graph. And we define a
"strong" path, which indicates the strong dependency throughout each dependency
in the path, as the path that doesn't have two conjunct edges (dependencies) as
-(xR)-&gt; and -(Sx)-&gt;. In other words, a "strong" path is a path from a lock
walking to another through the lock dependencies, and if X -&gt; Y -&gt; Z is in the
path (where X, Y, Z are locks), and the walk from X to Y is through a -(SR)-&gt; or
-(ER)-&gt; dependency, the walk from Y to Z must not be through a -(SN)-&gt; or
-(SR)-&gt; dependency.

We will see why the path is called "strong" in next section.

<a id="rst-recursive-read-deadlock-detection"></a>

## Recursive Read Deadlock Detection:

We now prove two things:

Lemma 1:

If there is a closed strong path (i.e. a strong circle), then there is a
combination of locking sequences that causes deadlock. I.e. a strong circle is
sufficient for deadlock detection.

Lemma 2:

If there is no closed strong path (i.e. strong circle), then there is no
combination of locking sequences that could cause deadlock. I.e.  strong
circles are necessary for deadlock detection.

With these two Lemmas, we can easily say a closed strong path is both sufficient
and necessary for deadlocks, therefore a closed strong path is equivalent to
deadlock possibility. As a closed strong path stands for a dependency chain that
could cause deadlocks, so we call it "strong", considering there are dependency
circles that won't cause deadlocks.

Proof for sufficiency (Lemma 1):

Let's say we have a strong circle:

```text
L1 -> L2 ... -> Ln -> L1
```

, which means we have dependencies:

```text
L1 -> L2
L2 -> L3
...
Ln-1 -> Ln
Ln -> L1
```

We now can construct a combination of locking sequences that cause deadlock:

Firstly let's make one CPU/task get the L1 in L1 -&gt; L2, and then another get
the L2 in L2 -&gt; L3, and so on. After this, all of the Lx in Lx -&gt; Lx+1 are
held by different CPU/tasks.

And then because we have L1 -&gt; L2, so the holder of L1 is going to acquire L2
in L1 -&gt; L2, however since L2 is already held by another CPU/task, plus L1 -&gt;
L2 and L2 -&gt; L3 are not -(xR)-&gt; and -(Sx)-&gt; (the definition of strong), which
means either L2 in L1 -&gt; L2 is a non-recursive locker (blocked by anyone) or
the L2 in L2 -&gt; L3, is writer (blocking anyone), therefore the holder of L1
cannot get L2, it has to wait L2's holder to release.

Moreover, we can have a similar conclusion for L2's holder: it has to wait L3's
holder to release, and so on. We now can prove that Lx's holder has to wait for
Lx+1's holder to release, and note that Ln+1 is L1, so we have a circular
waiting scenario and nobody can get progress, therefore a deadlock.

Proof for necessary (Lemma 2):

Lemma 2 is equivalent to: If there is a deadlock scenario, then there must be a
strong circle in the dependency graph.

According to Wikipedia\[1\], if there is a deadlock, then there must be a circular
waiting scenario, means there are N CPU/tasks, where CPU/task P1 is waiting for
a lock held by P2, and P2 is waiting for a lock held by P3, ... and Pn is waiting
for a lock held by P1. Let's name the lock Px is waiting as Lx, so since P1 is waiting
for L1 and holding Ln, so we will have Ln -&gt; L1 in the dependency graph. Similarly,
we have L1 -&gt; L2, L2 -&gt; L3, ..., Ln-1 -&gt; Ln in the dependency graph, which means we
have a circle:

```text
Ln -> L1 -> L2 -> ... -> Ln
```

, and now let's prove the circle is strong:

For a lock Lx, Px contributes the dependency Lx-1 -&gt; Lx and Px+1 contributes
the dependency Lx -&gt; Lx+1, and since Px is waiting for Px+1 to release Lx,
so it's impossible that Lx on Px+1 is a reader and Lx on Px is a recursive
reader, because readers (no matter recursive or not) don't block recursive
readers, therefore Lx-1 -&gt; Lx and Lx -&gt; Lx+1 cannot be a -(xR)-&gt; -(Sx)-&gt; pair,
and this is true for any lock in the circle, therefore, the circle is strong.

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

## References:

\[1\]: [https://en.wikipedia.org/wiki/Deadlock](<https://en.wikipedia.org/wiki/Deadlock>)
\[2\]: Shibu, K. (2009). Intro To Embedded Systems (1st ed.). Tata McGraw-Hill

## Credits

started by Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;

---

# Lock statistics

_Peios Kernel / Internals / Locking_

> Collecting and interpreting lock contention and hold-time statistics.

<a id="rst-lock-statistics"></a>

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

## What

As the name suggests, it provides statistics on locks.

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

## Why

Because things like lock contention can severely impact performance.

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

## How

Lockdep already has hooks in the lock functions and maps lock instances to
lock classes. We build on that (see [Documentation/locking/lockdep-design.rst](/kernel/internals/locking/lockdep-design.md)).
The graph below shows the relation between the lock functions and the various
hooks therein:

```text
      __acquire
          |
         lock _____
          |        \
          |    __contended
          |         |
          |       <wait>
          | _______/
          |/
          |
     __acquired
          |
          .
        <hold>
          .
          |
     __release
          |
       unlock

lock, unlock  - the regular lock functions
__*           - the hooks
<>            - states
```

With these hooks we provide the following statistics:

- **con-bounces**

  - number of lock contention that involved x-cpu data

- **contentions**

  - number of lock acquisitions that had to wait

- **wait time**

  - **min**

    - shortest (non-0) time we ever had to wait for a lock

  - **max**

    - longest time we ever had to wait for a lock

  - **total**

    - total time we spend waiting on this lock

  - **avg**

    - average time spent waiting on this lock

- **acq-bounces**

  - number of lock acquisitions that involved x-cpu data

- **acquisitions**

  - number of times we took the lock

- **hold time**

  - **min**

    - shortest (non-0) time we ever held the lock

  - **max**

    - longest time we ever held the lock

  - **total**

    - total time this lock was held

  - **avg**

    - average time this lock was held

These numbers are gathered per lock class, per read/write state (when
applicable).

It also tracks 4 contention points per class. A contention point is a call site
that had to wait on lock acquisition.

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

### Configuration

Lock statistics are enabled via CONFIG_LOCK_STAT.

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

### Usage

Enable collection of statistics:

```console
# echo 1 >/proc/sys/kernel/lock_stat
```

Disable collection of statistics:

```console
# echo 0 >/proc/sys/kernel/lock_stat
```

Look at the current lock statistics:

```text
( line numbers not part of actual output, done for clarity in the explanation
  below )

# less /proc/lock_stat

01 lock_stat version 0.4
02-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
03                              class name    con-bounces    contentions   waittime-min   waittime-max waittime-total   waittime-avg    acq-bounces   acquisitions   holdtime-min   holdtime-max holdtime-total   holdtime-avg
04-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
05
06                         &mm->mmap_sem-W:            46             84           0.26         939.10       16371.53         194.90          47291        2922365           0.16     2220301.69 17464026916.32        5975.99
07                         &mm->mmap_sem-R:            37            100           1.31      299502.61      325629.52        3256.30         212344       34316685           0.10        7744.91    95016910.20           2.77
08                         ---------------
09                           &mm->mmap_sem              1          [<ffffffff811502a7>] khugepaged_scan_mm_slot+0x57/0x280
10                           &mm->mmap_sem             96          [<ffffffff815351c4>] __do_page_fault+0x1d4/0x510
11                           &mm->mmap_sem             34          [<ffffffff81113d77>] vm_mmap_pgoff+0x87/0xd0
12                           &mm->mmap_sem             17          [<ffffffff81127e71>] vm_munmap+0x41/0x80
13                         ---------------
14                           &mm->mmap_sem              1          [<ffffffff81046fda>] dup_mmap+0x2a/0x3f0
15                           &mm->mmap_sem             60          [<ffffffff81129e29>] SyS_mprotect+0xe9/0x250
16                           &mm->mmap_sem             41          [<ffffffff815351c4>] __do_page_fault+0x1d4/0x510
17                           &mm->mmap_sem             68          [<ffffffff81113d77>] vm_mmap_pgoff+0x87/0xd0
18
19.............................................................................................................................................................................................................................
20
21                         unix_table_lock:           110            112           0.21          49.24         163.91           1.46          21094          66312           0.12         624.42       31589.81           0.48
22                         ---------------
23                         unix_table_lock             45          [<ffffffff8150ad8e>] unix_create1+0x16e/0x1b0
24                         unix_table_lock             47          [<ffffffff8150b111>] unix_release_sock+0x31/0x250
25                         unix_table_lock             15          [<ffffffff8150ca37>] unix_find_other+0x117/0x230
26                         unix_table_lock              5          [<ffffffff8150a09f>] unix_autobind+0x11f/0x1b0
27                         ---------------
28                         unix_table_lock             39          [<ffffffff8150b111>] unix_release_sock+0x31/0x250
29                         unix_table_lock             49          [<ffffffff8150ad8e>] unix_create1+0x16e/0x1b0
30                         unix_table_lock             20          [<ffffffff8150ca37>] unix_find_other+0x117/0x230
31                         unix_table_lock              4          [<ffffffff8150a09f>] unix_autobind+0x11f/0x1b0
```

This excerpt shows the first two lock class statistics. Line 01 shows the
output version - each time the format changes this will be updated. Line 02-04
show the header with column descriptions. Lines 05-18 and 20-31 show the actual
statistics. These statistics come in two parts; the actual stats separated by a
short separator (line 08, 13) from the contention points.

Lines 09-12 show the first 4 recorded contention points (the code
which tries to get the lock) and lines 14-17 show the first 4 recorded
contended points (the lock holder). It is possible that the max
con-bounces point is missing in the statistics.

The first lock (05-18) is a read/write lock, and shows two lines above the
short separator. The contention points don't match the column descriptors,
they have two: contentions and \[&lt;IP&gt;\] symbol. The second set of contention
points are the points we're contending with.

The integer part of the time values is in us.

Dealing with nested locks, subclasses may appear:

```text
32...........................................................................................................................................................................................................................
33
34                               &rq->lock:       13128          13128           0.43         190.53      103881.26           7.91          97454        3453404           0.00         401.11    13224683.11           3.82
35                               ---------
36                               &rq->lock          645          [<ffffffff8103bfc4>] task_rq_lock+0x43/0x75
37                               &rq->lock          297          [<ffffffff8104ba65>] try_to_wake_up+0x127/0x25a
38                               &rq->lock          360          [<ffffffff8103c4c5>] select_task_rq_fair+0x1f0/0x74a
39                               &rq->lock          428          [<ffffffff81045f98>] scheduler_tick+0x46/0x1fb
40                               ---------
41                               &rq->lock           77          [<ffffffff8103bfc4>] task_rq_lock+0x43/0x75
42                               &rq->lock          174          [<ffffffff8104ba65>] try_to_wake_up+0x127/0x25a
43                               &rq->lock         4715          [<ffffffff8103ed4b>] double_rq_lock+0x42/0x54
44                               &rq->lock          893          [<ffffffff81340524>] schedule+0x157/0x7b8
45
46...........................................................................................................................................................................................................................
47
48                             &rq->lock/1:        1526          11488           0.33         388.73      136294.31          11.86          21461          38404           0.00          37.93      109388.53           2.84
49                             -----------
50                             &rq->lock/1        11526          [<ffffffff8103ed58>] double_rq_lock+0x4f/0x54
51                             -----------
52                             &rq->lock/1         5645          [<ffffffff8103ed4b>] double_rq_lock+0x42/0x54
53                             &rq->lock/1         1224          [<ffffffff81340524>] schedule+0x157/0x7b8
54                             &rq->lock/1         4336          [<ffffffff8103ed58>] double_rq_lock+0x4f/0x54
55                             &rq->lock/1          181          [<ffffffff8104ba65>] try_to_wake_up+0x127/0x25a
```

Line 48 shows statistics for the second subclass (/1) of &amp;rq-&gt;lock class
(subclass starts from 0), since in this case, as line 50 suggests,
double_rq_lock actually acquires a nested lock of two spinlocks.

View the top contending locks:

```text
# grep : /proc/lock_stat | head
                      clockevents_lock:       2926159        2947636           0.15       46882.81  1784540466.34         605.41        3381345        3879161           0.00        2260.97    53178395.68          13.71
                   tick_broadcast_lock:        346460         346717           0.18        2257.43    39364622.71         113.54        3642919        4242696           0.00        2263.79    49173646.60          11.59
                &mapping->i_mmap_mutex:        203896         203899           3.36      645530.05 31767507988.39      155800.21        3361776        8893984           0.17        2254.15    14110121.02           1.59
                             &rq->lock:        135014         136909           0.18         606.09      842160.68           6.15        1540728       10436146           0.00         728.72    17606683.41           1.69
             &(&zone->lru_lock)->rlock:         93000          94934           0.16          59.18      188253.78           1.98        1199912        3809894           0.15         391.40     3559518.81           0.93
                       tasklist_lock-W:         40667          41130           0.23        1189.42      428980.51          10.43         270278         510106           0.16         653.51     3939674.91           7.72
                       tasklist_lock-R:         21298          21305           0.20        1310.05      215511.12          10.12         186204         241258           0.14        1162.33     1179779.23           4.89
                            rcu_node_1:         47656          49022           0.16         635.41      193616.41           3.95         844888        1865423           0.00         764.26     1656226.96           0.89
     &(&dentry->d_lockref.lock)->rlock:         39791          40179           0.15        1302.08       88851.96           2.21        2790851       12527025           0.10        1910.75     3379714.27           0.27
                            rcu_node_0:         29203          30064           0.16         786.55     1555573.00          51.74          88963         244254           0.00         398.87      428872.51           1.76
```

Clear the statistics:

```console
# echo 0 > /proc/lock_stat
```

---

# Lock torture tests

_Peios Kernel / Internals / Locking_

> Running locking stress tests and selecting their module parameters.

<a id="rst-kernel-lock-torture-test-operation"></a>

<a id="rst-config-lock-torture-test"></a>

## CONFIG_LOCK_TORTURE_TEST

The CONFIG_LOCK_TORTURE_TEST config option provides a kernel module
that runs torture tests on core kernel locking primitives. The kernel
module, 'locktorture', may be built after the fact on the running
kernel to be tested, if desired. The tests periodically output status
messages via printk(), which can be examined via the dmesg (perhaps
grepping for "torture").  The test is started when the module is loaded,
and stops when the module is unloaded. This program is based on how RCU
is tortured, via rcutorture.

This torture test consists of creating a number of kernel threads which
acquire the lock and hold it for specific amount of time, thus simulating
different critical region behaviors. The amount of contention on the lock
can be simulated by either enlarging this critical region hold time and/or
creating more kthreads.

<a id="rst-module-parameters"></a>

## Module Parameters

This module has the following parameters:

<a id="rst-locktorture-specific"></a>

### Locktorture-specific

- **nwriters_stress**

  Number of kernel threads that will stress exclusive lock
  ownership (writers). The default value is twice the number
  of online CPUs.

- **nreaders_stress**

  Number of kernel threads that will stress shared lock
  ownership (readers). The default is the same amount of writer
  locks. If the user did not specify nwriters_stress, then
  both readers and writers be the amount of online CPUs.

- **torture_type**

  Type of lock to torture. By default, only spinlocks will
  be tortured. This module can torture the following locks,
  with string values as follows:

  - - **"lock_busted":**

      Simulates a buggy lock implementation.

  - - **"spin_lock":**

      spin_lock() and spin_unlock() pairs.

  - - **"spin_lock_irq":**

      spin_lock_irq() and spin_unlock_irq() pairs.

  - - **"rw_lock":**

      read/write lock() and unlock() rwlock pairs.

  - - **"rw_lock_irq":**

      read/write lock_irq() and unlock_irq()
      rwlock pairs.

  - - **"mutex_lock":**

      mutex_lock() and mutex_unlock() pairs.

  - - **"rtmutex_lock":**

      rtmutex_lock() and rtmutex_unlock() pairs.
      Kernel must have CONFIG_RT_MUTEXES=y.

  - - **"rwsem_lock":**

      read/write down() and up() semaphore pairs.

<a id="rst-torture-framework-rcu-locking"></a>

### Torture-framework (RCU + locking)

- **shutdown_secs**

  The number of seconds to run the test before terminating
  the test and powering off the system.  The default is
  zero, which disables test termination and system shutdown.
  This capability is useful for automated testing.

- **onoff_interval**

  The number of seconds between each attempt to execute a
  randomly selected CPU-hotplug operation.  Defaults
  to zero, which disables CPU hotplugging.  In
  CONFIG_HOTPLUG_CPU=n kernels, locktorture will silently
  refuse to do any CPU-hotplug operations regardless of
  what value is specified for onoff_interval.

- **onoff_holdoff**

  The number of seconds to wait until starting CPU-hotplug
  operations.  This would normally only be used when
  locktorture was built into the kernel and started
  automatically at boot time, in which case it is useful
  in order to avoid confusing boot-time code with CPUs
  coming and going. This parameter is only useful if
  CONFIG_HOTPLUG_CPU is enabled.

- **stat_interval**

  Number of seconds between statistics-related printk()s.
  By default, locktorture will report stats every 60 seconds.
  Setting the interval to zero causes the statistics to
  be printed -only- when the module is unloaded.

- **stutter**

  The length of time to run the test before pausing for this
  same period of time.  Defaults to "stutter=5", so as
  to run and pause for (roughly) five-second intervals.
  Specifying "stutter=0" causes the test to run continuously
  without pausing.

- **shuffle_interval**

  The number of seconds to keep the test threads affinitized
  to a particular subset of the CPUs, defaults to 3 seconds.
  Used in conjunction with test_no_idle_hz.

- **verbose**

  Enable verbose debugging printing, via printk(). Enabled
  by default. This extra information is mostly related to
  high-level errors and reports from the main 'torture'
  framework.

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

## Statistics

Statistics are printed in the following format:

```text
spin_lock-torture: Writes:  Total: 93746064  Max/Min: 0/0   Fail: 0
   (A)                    (B)            (C)            (D)          (E)

(A): Lock type that is being tortured -- torture_type parameter.

(B): Number of writer lock acquisitions. If dealing with a read/write
     primitive a second "Reads" statistics line is printed.

(C): Number of times the lock was acquired.

(D): Min and max number of times threads failed to acquire the lock.

(E): true/false values if there were errors acquiring the lock. This should
     -only- be positive if there is a bug in the locking primitive's
     implementation. Otherwise a lock should never fail (i.e., spin_lock()).
     Of course, the same applies for (C), above. A dummy example of this is
     the "lock_busted" type.
```

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

## Usage

The following script may be used to torture locks:

```sh
#!/bin/sh

modprobe locktorture
sleep 3600
rmmod locktorture
dmesg | grep torture:
```

The output can be manually inspected for the error flag of "\!\!\!".
One could of course create a more elaborate script that automatically
checked for such errors.  The "rmmod" command forces a "SUCCESS",
"FAILURE", or "RCU_HOTPLUG" indication to be printk()ed.  The first
two are self-explanatory, while the last indicates that while there
were no locking failures, CPU-hotplug problems were detected.

Also see: [Documentation/RCU/torture.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/RCU/torture.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)

---

# Scheduler

_Peios Kernel / Internals / Scheduling_

> Reference for Scheduler.

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

- [Completions - "wait for completion" barrier APIs](</kernel/internals/scheduler/completion.md>)
- [membarrier() System Call](</kernel/internals/scheduler/membarrier.md>)
- [CPU Scheduler implementation hints for architecture specific code](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/scheduler/sched-arch.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [CFS Bandwidth Control](</kernel/internals/scheduler/sched-bwc.md>)
- [Deadline Task Scheduling](</kernel/internals/scheduler/sched-deadline.md>)
- [CFS Scheduler](</kernel/internals/scheduler/sched-design-cfs.md>)
- [EEVDF Scheduler](</kernel/internals/scheduler/sched-eevdf.md>)
- [Scheduler Domains](</kernel/internals/scheduler/sched-domains.md>)
- [Capacity Aware Scheduling](</kernel/internals/scheduler/sched-capacity.md>)
- [Energy Aware Scheduling](</kernel/internals/scheduler/sched-energy.md>)
- [Schedutil](</kernel/internals/scheduler/schedutil.md>)
- [Utilization Clamping](</kernel/internals/scheduler/sched-util-clamp.md>)
- [Scheduler Nice Design](</kernel/internals/scheduler/sched-nice-design.md>)
- [Real-Time group scheduling](</kernel/internals/scheduler/sched-rt-group.md>)
- [Scheduler Statistics](</kernel/internals/scheduler/sched-stats.md>)
- [Extensible Scheduler Class](</kernel/internals/scheduler/sched-ext.md>)
- [Scheduler debugfs](</kernel/internals/scheduler/sched-debug.md>)
- [text_files](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/scheduler/text_files.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# Completions - "wait for completion" barrier APIs

_Peios Kernel / Internals / Scheduling_

> If you have one or more threads that must wait for some kernel activity to have reached a point or a specific state, completions can provide a race-free solution to this problem. Semantically they are somewhat like a pthread_barrier() and…

<a id="rst-completions-wait-for-completion-barrier-apis"></a>

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

## Introduction:

If you have one or more threads that must wait for some kernel activity to have reached a point or a specific state, completions can provide a race-free solution to this problem. Semantically they are somewhat like a pthread_barrier() and have similar use-cases.

Completions are a code synchronization mechanism which is preferable to any misuse of locks/semaphores and busy-loops. Any time you think of using yield() or some quirky msleep(1) loop to allow something else to proceed, you probably want to look into using one of the wait_for_completion\*() calls and complete() instead.

The advantage of using completions is that they have a well defined, focused purpose which makes it very easy to see the intent of the code, but they also result in more efficient code as all threads can continue execution until the result is actually needed, and both the waiting and the signalling is highly efficient using low level scheduler sleep/wakeup facilities.

Completions are built on top of the waitqueue and wakeup infrastructure of the Linux scheduler. The event the threads on the waitqueue are waiting for is reduced to a simple flag in 'struct completion', appropriately called "done".

As completions are scheduling related, the code can be found in kernel/sched/completion.c.

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

## Usage:

There are three main parts to using completions:

> - the initialization of the 'struct completion' synchronization object
>
> - the waiting part through a call to one of the variants of wait_for_completion(),
>
> - the signaling side through a call to complete() or complete_all().

There are also some helper functions for checking the state of completions. Note that while initialization must happen first, the waiting and signaling part can happen in any order. I.e. it's entirely normal for a thread to have marked a completion as 'done' before another thread checks whether it has to wait for it.

To use completions you need to \#include &lt;linux/completion.h&gt; and create a static or dynamic variable of type 'struct completion', which has only two fields:



```text
struct completion {
        unsigned int done;
        struct swait_queue_head wait;
};
```

This provides the -&gt;wait waitqueue to place tasks on for waiting (if any), and the -&gt;done completion flag for indicating whether it's completed or not.

Completions should be named to refer to the event that is being synchronized on. A good example is:



```text
wait_for_completion(&early_console_added);

complete(&early_console_added);
```

Good, intuitive naming (as always) helps code readability. Naming a completion 'complete' is not helpful unless the purpose is super obvious...

<a id="rst-initializing-completions"></a>

## Initializing completions:

Dynamically allocated completion objects should preferably be embedded in data structures that are assured to be alive for the life-time of the function/driver, to prevent races with asynchronous complete() calls from occurring.

Particular care should be taken when using the \_timeout() or \_killable()/\_interruptible() variants of wait_for_completion(), as it must be assured that memory de-allocation does not happen until all related activities (complete() or reinit_completion()) have taken place, even if these wait functions return prematurely due to a timeout or a signal triggering.

Initializing of dynamically allocated completion objects is done via a call to init_completion():



```text
init_completion(&dynamic_object->done);
```

In this call we initialize the waitqueue and set -&gt;done to 0, i.e. "not completed" or "not done".

The re-initialization function, reinit_completion(), simply resets the -&gt;done field to 0 ("not done"), without touching the waitqueue. Callers of this function must make sure that there are no racy wait_for_completion() calls going on in parallel.

Calling init_completion() on the same completion object twice is most likely a bug as it re-initializes the queue to an empty queue and enqueued tasks could get "lost" - use reinit_completion() in that case, but be aware of other races.

For static declaration and initialization, macros are available.

For static (or global) declarations in file scope you can use DECLARE_COMPLETION():



```text
static DECLARE_COMPLETION(setup_done);
DECLARE_COMPLETION(setup_done);
```

Note that in this case the completion is boot time (or module load time) initialized to 'not done' and doesn't require an init_completion() call.

When a completion is declared as a local variable within a function, then the initialization should always use DECLARE_COMPLETION_ONSTACK() explicitly, not just to make lockdep happy, but also to make it clear that limited scope had been considered and is intentional:



```text
DECLARE_COMPLETION_ONSTACK(setup_done)
```

Note that when using completion objects as local variables you must be acutely aware of the short life time of the function stack: the function must not return to a calling context until all activities (such as waiting threads) have ceased and the completion object is completely unused.

To emphasise this again: in particular when using some of the waiting API variants with more complex outcomes, such as the timeout or signalling (\_timeout(), \_killable() and \_interruptible()) variants, the wait might complete prematurely while the object might still be in use by another thread - and a return from the wait_on_completion\*() caller function will deallocate the function stack and cause subtle data corruption if a complete() is done in some other thread. Simple testing might not trigger these kinds of races.

If unsure, use dynamically allocated completion objects, preferably embedded in some other long lived object that has a boringly long life time which exceeds the life time of any helper threads using the completion object, or has a lock or other synchronization mechanism to make sure complete() is not called on a freed object.

A naive DECLARE_COMPLETION() on the stack triggers a lockdep warning.

<a id="rst-waiting-for-completions"></a>

## Waiting for completions:

For a thread to wait for some concurrent activity to finish, it calls wait_for_completion() on the initialized completion structure:



```text
void wait_for_completion(struct completion *done)
```

A typical usage scenario is:



```text
CPU#1                                   CPU#2

struct completion setup_done;

init_completion(&setup_done);
initialize_work(...,&setup_done,...);

/* run non-dependent code */            /* do setup */

wait_for_completion(&setup_done);       complete(&setup_done);
```

This is not implying any particular order between wait_for_completion() and the call to complete() - if the call to complete() happened before the call to wait_for_completion() then the waiting side simply will continue immediately as all dependencies are satisfied; if not, it will block until completion is signaled by complete().

Note that wait_for_completion() is calling spin_lock_irq()/spin_unlock_irq(), so it can only be called safely when you know that interrupts are enabled. Calling it from IRQs-off atomic contexts will result in hard-to-detect spurious enabling of interrupts.

The default behavior is to wait without a timeout and to mark the task as uninterruptible. wait_for_completion() and its variants are only safe in process context (as they can sleep) but not in atomic context, interrupt context, with disabled IRQs, or preemption is disabled - see also try_wait_for_completion() below for handling completion in atomic/interrupt context.

As all variants of wait_for_completion() can (obviously) block for a long time depending on the nature of the activity they are waiting for, so in most cases you probably don't want to call this with held mutexes.

<a id="rst-wait-for-completion-variants-available"></a>

## wait_for_completion\*() variants available:

The below variants all return status and this status should be checked in most(/all) cases - in cases where the status is deliberately not checked you probably want to make a note explaining this (e.g. see arch/arm/kernel/smp.c:\__cpu_up()).

A common problem that occurs is to have unclean assignment of return types, so take care to assign return-values to variables of the proper type.

Checking for the specific meaning of return values also has been found to be quite inaccurate, e.g. constructs like:



```text
if (!wait_for_completion_interruptible_timeout(...))
```

... would execute the same code path for successful completion and for the interrupted case - which is probably not what you want:



```text
int wait_for_completion_interruptible(struct completion *done)
```

This function marks the task TASK_INTERRUPTIBLE while it is waiting. If a signal was received while waiting it will return -ERESTARTSYS; 0 otherwise:



```text
unsigned long wait_for_completion_timeout(struct completion *done, unsigned long timeout)
```

The task is marked as TASK_UNINTERRUPTIBLE and will wait at most 'timeout' jiffies. If a timeout occurs it returns 0, else the remaining time in jiffies (but at least 1).

Timeouts are preferably calculated with msecs_to_jiffies() or usecs_to_jiffies(), to make the code largely HZ-invariant.

If the returned timeout value is deliberately ignored a comment should probably explain why (e.g. see drivers/mfd/wm8350-core.c wm8350_read_auxadc()):



```text
long wait_for_completion_interruptible_timeout(struct completion *done, unsigned long timeout)
```

This function passes a timeout in jiffies and marks the task as TASK_INTERRUPTIBLE. If a signal was received it will return -ERESTARTSYS; otherwise it returns 0 if the completion timed out, or the remaining time in jiffies if completion occurred.

Further variants include \_killable which uses TASK_KILLABLE as the designated tasks state and will return -ERESTARTSYS if it is interrupted, or 0 if completion was achieved.  There is a \_timeout variant as well:



```text
long wait_for_completion_killable(struct completion *done)
long wait_for_completion_killable_timeout(struct completion *done, unsigned long timeout)
```

The \_io variants wait_for_completion_io() behave the same as the non-\_io variants, except for accounting waiting time as 'waiting on IO', which has an impact on how the task is accounted in scheduling/IO stats:



```text
void wait_for_completion_io(struct completion *done)
unsigned long wait_for_completion_io_timeout(struct completion *done, unsigned long timeout)
```

<a id="rst-signaling-completions"></a>

## Signaling completions:

A thread that wants to signal that the conditions for continuation have been achieved calls complete() to signal exactly one of the waiters that it can continue:



```text
void complete(struct completion *done)
```

... or calls complete_all() to signal all current and future waiters:



```text
void complete_all(struct completion *done)
```

The signaling will work as expected even if completions are signaled before a thread starts waiting. This is achieved by the waiter "consuming" (decrementing) the done field of 'struct completion'. Waiting threads wakeup order is the same in which they were enqueued (FIFO order).

If complete() is called multiple times then this will allow for that number of waiters to continue - each call to complete() will simply increment the done field. Calling complete_all() multiple times is a bug though. Both complete() and complete_all() can be called in IRQ/atomic context safely.

There can only be one thread calling complete() or complete_all() on a particular 'struct completion' at any time - serialized through the wait queue spinlock. Any such concurrent calls to complete() or complete_all() probably are a design bug.

Signaling completion from IRQ context is fine as it will appropriately lock with spin_lock_irqsave()/spin_unlock_irqrestore() and it will never sleep.

<a id="rst-try-wait-for-completion-completion-done"></a>

## try_wait_for_completion()/completion_done():

The try_wait_for_completion() function will not put the thread on the wait queue but rather returns false if it would need to enqueue (block) the thread, else it consumes one posted completion and returns true:



```text
bool try_wait_for_completion(struct completion *done)
```

Finally, to check the state of a completion without changing it in any way, call completion_done(), which returns false if there are no posted completions that were not yet consumed by waiters (implying that there are waiters) and true otherwise:



```text
bool completion_done(struct completion *done)
```

Both try_wait_for_completion() and completion_done() are safe to be called in IRQ or atomic context.

---

# membarrier() System Call

_Peios Kernel / Internals / Scheduling_

> The commands MEMBARRIER_CMD_PRIVATE_EXPEDITED and MEMBARRIER_CMD_GLOBAL_EXPEDITED require each architecture to have a full memory barrier after coming from user-space, before updating rq->curr. This barrier is implied by the sequence…

<a id="rst-membarrier-system-call"></a>

<a id="rst-membarrier-cmd-private-global-expedited-architecture-requirements"></a>

## MEMBARRIER_CMD\_\{PRIVATE,GLOBAL\}\_EXPEDITED - Architecture requirements

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

<a id="rst-memory-barriers-before-updating-rq-curr"></a>

## Memory barriers before updating rq-&gt;curr

The commands MEMBARRIER_CMD_PRIVATE_EXPEDITED and MEMBARRIER_CMD_GLOBAL_EXPEDITED require each architecture to have a full memory barrier after coming from user-space, before updating rq-&gt;curr.  This barrier is implied by the sequence rq_lock(); smp_mb__after_spinlock() in \__schedule().  The barrier matches a full barrier in the proximity of the membarrier system call exit, cf. membarrier\_\{private,global\}\_expedited().

<a id="rst-memory-barriers-after-updating-rq-curr"></a>

## Memory barriers after updating rq-&gt;curr

The commands MEMBARRIER_CMD_PRIVATE_EXPEDITED and MEMBARRIER_CMD_GLOBAL_EXPEDITED require each architecture to have a full memory barrier after updating rq-&gt;curr, before returning to user-space.  The schemes providing this barrier on the various architectures are as follows.

> - alpha, arc, arm, hexagon, mips rely on the full barrier implied by spin_unlock() in finish_lock_switch().
>
> - arm64 relies on the full barrier implied by switch_to().
>
> - powerpc, riscv, s390, sparc, x86 rely on the full barrier implied by switch_mm(), if mm is not NULL; they rely on the full barrier implied by mmdrop(), otherwise.  On powerpc and riscv, switch_mm() relies on membarrier_arch_switch_mm().

The barrier matches a full barrier in the proximity of the membarrier system call entry, cf. membarrier\_\{private,global\}\_expedited().

---

# CPU Scheduler implementation hints for architecture specific code

_Peios Kernel / Internals / Scheduling_

> Nick Piggin, 2005

<a id="rst-cpu-scheduler-implementation-hints-for-architecture-specific-code"></a>

> Nick Piggin, 2005

<a id="rst-context-switch"></a>

## Context switch

1\. Runqueue locking By default, the switch\_to arch function is called with the runqueue locked. This is usually not a problem unless switch\_to may need to take the runqueue lock. This is usually due to a wake up operation in the context switch.

To request the scheduler call switch\_to with the runqueue unlocked, you must `#define __ARCH_WANT_UNLOCKED_CTXSW` in a header file (typically the one where switch\_to is defined).

Unlocked context switches introduce only a very minor performance penalty to the core scheduler implementation in the CONFIG\_SMP case.

<a id="rst-cpu-idle"></a>

## CPU idle

Your cpu\_idle routines need to obey the following rules:

1. Preempt should now disabled over idle routines. Should only be enabled to call schedule() then disabled again.

2. need\_resched/TIF\_NEED\_RESCHED is only ever set, and will never be cleared until the running task has called schedule(). Idle threads need only ever query need\_resched, and may never set or clear it.

3. When cpu\_idle finds (need\_resched() == 'true'), it should call schedule(). It should not call schedule() otherwise.

4. The only time interrupts need to be disabled when checking need\_resched is if we are about to sleep the processor until the next interrupt (this doesn't provide any protection of need\_resched, it prevents losing an interrupt):

   > 4a. Common problem with this type of sleep appears to be:
   >
   >
   >
   > ```text
   > local_irq_disable();
   > if (!need_resched()) {
   >         local_irq_enable();
   >         *** resched interrupt arrives here ***
   >         __asm__("sleep until next interrupt");
   > }
   > ```

5. TIF\_POLLING\_NRFLAG can be set by idle routines that do not need an interrupt to wake them up when need\_resched goes high. In other words, they must be periodically polling need\_resched, although it may be reasonable to do some background work or enter a low CPU priority.

   > - 5a. If TIF\_POLLING\_NRFLAG is set, and we do decide to enter an interrupt sleep, it needs to be cleared then a memory barrier issued (followed by a test of need\_resched with interrupts disabled, as explained in 3).

arch/x86/kernel/process.c has examples of both polling and sleeping idle functions.

<a id="rst-possible-arch-problems"></a>

## Possible arch/ problems

Possible arch problems I found (and either tried to fix or didn't):

- **sparc - IRQs on at this point(?), change local\_irq\_save to \_disable.**

  - TODO: needs secondary CPUs to disable preempt (See \#1)

---

# CFS Bandwidth Control

_Peios Kernel / Internals / Scheduling_

> CFS bandwidth control is a CONFIG_FAIR_GROUP_SCHED extension which allows the specification of the maximum CPU bandwidth available to a group or hierarchy.

<a id="rst-cfs-bandwidth-control"></a>

> [!NOTE]
>
> This document only discusses CPU bandwidth control for SCHED_NORMAL. The SCHED_RT case is covered in [Documentation/scheduler/sched-rt-group.rst](/kernel/internals/scheduler/sched-rt-group.md)

CFS bandwidth control is a CONFIG_FAIR_GROUP_SCHED extension which allows the specification of the maximum CPU bandwidth available to a group or hierarchy.

The bandwidth allowed for a group is specified using a quota and period. Within each given "period" (microseconds), a task group is allocated up to "quota" microseconds of CPU time. That quota is assigned to per-cpu run queues in slices as threads in the cgroup become runnable. Once all quota has been assigned any additional requests for quota will result in those threads being throttled. Throttled threads will not be able to run again until the next period when the quota is replenished.

A group's unassigned quota is globally tracked, being refreshed back to cfs_quota units at each period boundary. As threads consume this bandwidth it is transferred to cpu-local "silos" on a demand basis. The amount transferred within each of these updates is tunable and described as the "slice".

<a id="rst-burst-feature"></a>

## Burst feature

This feature borrows time now against our future underrun, at the cost of increased interference against the other system users. All nicely bounded.

Traditional (UP-EDF) bandwidth control is something like:

> (U = Sum u_i) &lt;= 1

This guaranteeds both that every deadline is met and that the system is stable. After all, if U were &gt; 1, then for every second of walltime, we'd have to run more than a second of program time, and obviously miss our deadline, but the next deadline will be further out still, there is never time to catch up, unbounded fail.

The burst feature observes that a workload doesn't always executes the full quota; this enables one to describe u_i as a statistical distribution.

For example, have u_i = \{x,e\}\_i, where x is the p(95) and x+e p(100) (the traditional WCET). This effectively allows u to be smaller, increasing the efficiency (we can pack more tasks in the system), but at the cost of missing deadlines when all the odds line up. However, it does maintain stability, since every overrun must be paired with an underrun as long as our x is above the average.

That is, suppose we have 2 tasks, both specify a p(95) value, then we have a p(95)\*p(95) = 90.25% chance both tasks are within their quota and everything is good. At the same time we have a p(5)p(5) = 0.25% chance both tasks will exceed their quota at the same time (guaranteed deadline fail). Somewhere in between there's a threshold where one exceeds and the other doesn't underrun enough to compensate; this depends on the specific CDFs.

At the same time, we can say that the worst case deadline miss, will be Sum e_i; that is, there is a bounded tardiness (under the assumption that x+e is indeed WCET).

The interference when using burst is valued by the possibilities for missing the deadline and the average WCET. Test results showed that when there many cgroups or CPU is under utilized, the interference is limited. More details are shown in: [https://lore.kernel.org/lkml/5371BD36-55AE-4F71-B9D7-B86DC32E3D2B@linux.alibaba.com/](<https://lore.kernel.org/lkml/5371BD36-55AE-4F71-B9D7-B86DC32E3D2B@linux.alibaba.com/>)

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

## Management

Quota, period and burst are managed within the cpu subsystem via cgroupfs.

> [!NOTE]
>
> The cgroupfs files described in this section are only applicable to cgroup v1. For cgroup v2, see [Documentation/admin-guide/cgroup-v2.rst](</kernel/administration/admin-guide/resources/cgroup-v2.md#rst-cgroup-v2-cpu>).

- cpu.cfs_quota_us: run-time replenished within a period (in microseconds)

- cpu.cfs_period_us: the length of a period (in microseconds)

- cpu.stat: exports throttling statistics \[explained further below\]

- cpu.cfs_burst_us: the maximum accumulated run-time (in microseconds)

The default values are:



```text
cpu.cfs_period_us=100ms
cpu.cfs_quota_us=-1
cpu.cfs_burst_us=0
```

A value of -1 for cpu.cfs_quota_us indicates that the group does not have any bandwidth restriction in place, such a group is described as an unconstrained bandwidth group. This represents the traditional work-conserving behavior for CFS.

Writing any (valid) positive value(s) no smaller than cpu.cfs_burst_us will enact the specified bandwidth limit. The minimum quota allowed for the quota or period is 1ms. There is also an upper bound on the period length of 1s. Additional restrictions exist when bandwidth limits are used in a hierarchical fashion, these are explained in more detail below.

Writing any negative value to cpu.cfs_quota_us will remove the bandwidth limit and return the group to an unconstrained state once more.

A value of 0 for cpu.cfs_burst_us indicates that the group can not accumulate any unused bandwidth. It makes the traditional bandwidth control behavior for CFS unchanged. Writing any (valid) positive value(s) no larger than cpu.cfs_quota_us into cpu.cfs_burst_us will enact the cap on unused bandwidth accumulation.

Any updates to a group's bandwidth specification will result in it becoming unthrottled if it is in a constrained state.

<a id="rst-system-wide-settings"></a>

## System wide settings

For efficiency run-time is transferred between the global pool and CPU local "silos" in a batch fashion. This greatly reduces global accounting pressure on large systems. The amount transferred each time such an update is required is described as the "slice".

This is tunable via procfs:



```text
/proc/sys/kernel/sched_cfs_bandwidth_slice_us (default=5ms)
```

Larger slice values will reduce transfer overheads, while smaller values allow for more fine-grained consumption.

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

## Statistics

A group's bandwidth statistics are exported via 5 fields in cpu.stat.

cpu.stat:

- nr_periods: Number of enforcement intervals that have elapsed.

- nr_throttled: Number of times the group has been throttled/limited.

- throttled_time: The total time duration (in nanoseconds) for which entities of the group have been throttled.

- nr_bursts: Number of periods burst occurs.

- burst_time: Cumulative wall-time (in nanoseconds) that any CPUs has used above quota in respective periods.

This interface is read-only.

<a id="rst-hierarchical-considerations"></a>

## Hierarchical considerations

The interface enforces that an individual entity's bandwidth is always attainable, that is: max(c_i) &lt;= C. However, over-subscription in the aggregate case is explicitly allowed to enable work-conserving semantics within a hierarchy:

> e.g. Sum (c_i) may exceed C

\[ Where C is the parent's bandwidth, and c_i its children \]

There are two ways in which a group may become throttled:

> - **a.** it fully consumes its own quota within a period
>
> - **b.** a parent's quota is fully consumed within its period

In case b) above, even though the child may have runtime remaining it will not be allowed to until the parent's runtime is refreshed.

<a id="rst-cfs-bandwidth-quota-caveats"></a>

## CFS Bandwidth Quota Caveats

Once a slice is assigned to a cpu it does not expire.  However all but 1ms of the slice may be returned to the global pool if all threads on that cpu become unrunnable. This is configured at compile time by the min_cfs_rq_runtime variable. This is a performance tweak that helps prevent added contention on the global lock.

The fact that cpu-local slices do not expire results in some interesting corner cases that should be understood.

For cgroup cpu constrained applications that are cpu limited this is a relatively moot point because they will naturally consume the entirety of their quota as well as the entirety of each cpu-local slice in each period. As a result it is expected that nr_periods roughly equal nr_throttled, and that cpuacct.usage will increase roughly equal to cfs_quota_us in each period.

For highly-threaded, non-cpu bound applications this non-expiration nuance allows applications to briefly burst past their quota limits by the amount of unused slice on each cpu that the task group is running on (typically at most 1ms per cpu or as defined by min_cfs_rq_runtime).  This slight burst only applies if quota had been assigned to a cpu and then not fully used or returned in previous periods. This burst amount will not be transferred between cores. As a result, this mechanism still strictly limits the task group to quota average usage, albeit over a longer time window than a single period.  This also limits the burst ability to no more than 1ms per cpu.  This provides better more predictable user experience for highly threaded applications with small quota limits on high core count machines. It also eliminates the propensity to throttle these applications while simultaneously using less than quota amounts of cpu. Another way to say this, is that by allowing the unused portion of a slice to remain valid across periods we have decreased the possibility of wastefully expiring quota on cpu-local silos that don't need a full slice's amount of cpu time.

The interaction between cpu-bound and non-cpu-bound-interactive applications should also be considered, especially when single core usage hits 100%. If you gave each of these applications half of a cpu-core and they both got scheduled on the same CPU it is theoretically possible that the non-cpu bound application will use up to 1ms additional quota in some periods, thereby preventing the cpu-bound application from fully using its quota by that same amount. In these instances it will be up to the CFS algorithm (see [sched-design-CFS.rst](/kernel/internals/scheduler/sched-design-cfs.md)) to decide which application is chosen to run, as they will both be runnable and have remaining quota. This runtime discrepancy will be made up in the following periods when the interactive application idles.

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

## Examples

1. Limit a group to 1 CPU worth of runtime:



   ```text
   If period is 250ms and quota is also 250ms, the group will get
   1 CPU worth of runtime every 250ms.

   # echo 250000 > cpu.cfs_quota_us /* quota = 250ms */
   # echo 250000 > cpu.cfs_period_us /* period = 250ms */
   ```

2. Limit a group to 2 CPUs worth of runtime on a multi-CPU machine

   With 500ms period and 1000ms quota, the group can get 2 CPUs worth of runtime every 500ms:



   ```text
   # echo 1000000 > cpu.cfs_quota_us /* quota = 1000ms */
   # echo 500000 > cpu.cfs_period_us /* period = 500ms */

   The larger period here allows for increased burst capacity.
   ```

3. Limit a group to 20% of 1 CPU.

   With 50ms period, 10ms quota will be equivalent to 20% of 1 CPU:



   ```text
   # echo 10000 > cpu.cfs_quota_us /* quota = 10ms */
   # echo 50000 > cpu.cfs_period_us /* period = 50ms */
   ```

   By using a small period here we are ensuring a consistent latency response at the expense of burst capacity.

4. Limit a group to 40% of 1 CPU, and allow accumulate up to 20% of 1 CPU additionally, in case accumulation has been done.

   With 50ms period, 20ms quota will be equivalent to 40% of 1 CPU. And 10ms burst will be equivalent to 20% of 1 CPU:



   ```text
   # echo 20000 > cpu.cfs_quota_us /* quota = 20ms */
   # echo 50000 > cpu.cfs_period_us /* period = 50ms */
   # echo 10000 > cpu.cfs_burst_us /* burst = 10ms */
   ```

   Larger buffer setting (no larger than quota) allows greater burst capacity.

---

# Capacity Aware Scheduling

_Peios Kernel / Internals / Scheduling_

> Conventional, homogeneous SMP platforms are composed of purely identical CPUs. Heterogeneous platforms on the other hand are composed of CPUs with different performance characteristics - on such platforms, not all CPUs can be considered…

<a id="rst-capacity-aware-scheduling"></a>

<a id="rst-cpu-capacity"></a>

## 1. CPU Capacity

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

### 1.1 Introduction

Conventional, homogeneous SMP platforms are composed of purely identical CPUs. Heterogeneous platforms on the other hand are composed of CPUs with different performance characteristics - on such platforms, not all CPUs can be considered equal.

CPU capacity is a measure of the performance a CPU can reach, normalized against the most performant CPU in the system. Heterogeneous systems are also called asymmetric CPU capacity systems, as they contain CPUs of different capacities.

Disparity in maximum attainable performance (IOW in maximum CPU capacity) stems from two factors:

- not all CPUs may have the same microarchitecture (µarch).

- with Dynamic Voltage and Frequency Scaling (DVFS), not all CPUs may be physically able to attain the higher Operating Performance Points (OPP).

Arm big.LITTLE systems are an example of both. The big CPUs are more performance-oriented than the LITTLE ones (more pipeline stages, bigger caches, smarter predictors, etc), and can usually reach higher OPPs than the LITTLE ones can.

CPU performance is usually expressed in Millions of Instructions Per Second (MIPS), which can also be expressed as a given amount of instructions attainable per Hz, leading to:



```text
capacity(cpu) = work_per_hz(cpu) * max_freq(cpu)
```

<a id="rst-scheduler-terms"></a>

### 1.2 Scheduler terms

Two different capacity values are used within the scheduler. A CPU's `original capacity` is its maximum attainable capacity, i.e. its maximum attainable performance level. This original capacity is returned by the function arch_scale_cpu_capacity(). A CPU's `capacity` is its `original capacity` to which some loss of available performance (e.g. time spent handling IRQs) is subtracted.

Note that a CPU's `capacity` is solely intended to be used by the CFS class, while `original capacity` is class-agnostic. The rest of this document will use the term `capacity` interchangeably with `original capacity` for the sake of brevity.

<a id="rst-platform-examples"></a>

### 1.3 Platform examples

<a id="rst-identical-opps"></a>

#### 1.3.1 Identical OPPs

Consider an hypothetical dual-core asymmetric CPU capacity system where

- work_per_hz(CPU0) = W

- work_per_hz(CPU1) = W/2

- all CPUs are running at the same fixed frequency

By the above definition of capacity:

- capacity(CPU0) = C

- capacity(CPU1) = C/2

To draw the parallel with Arm big.LITTLE, CPU0 would be a big while CPU1 would be a LITTLE.

With a workload that periodically does a fixed amount of work, you will get an execution trace like so:



```text
CPU0 work ^
          |     ____                ____                ____
          |    |    |              |    |              |    |
          +----+----+----+----+----+----+----+----+----+----+-> time

CPU1 work ^
          |     _________           _________           ____
          |    |         |         |         |         |
          +----+----+----+----+----+----+----+----+----+----+-> time
```

CPU0 has the highest capacity in the system (C), and completes a fixed amount of work W in T units of time. On the other hand, CPU1 has half the capacity of CPU0, and thus only completes W/2 in T.

<a id="rst-different-max-opps"></a>

#### 1.3.2 Different max OPPs

Usually, CPUs of different capacity values also have different maximum OPPs. Consider the same CPUs as above (i.e. same work_per_hz()) with:

- max_freq(CPU0) = F

- max_freq(CPU1) = 2/3 \* F

This yields:

- capacity(CPU0) = C

- capacity(CPU1) = C/3

Executing the same workload as described in 1.3.1, which each CPU running at its maximum frequency results in:



```text
CPU0 work ^
          |     ____                ____                ____
          |    |    |              |    |              |    |
          +----+----+----+----+----+----+----+----+----+----+-> time

                           workload on CPU1
CPU1 work ^
          |     ______________      ______________      ____
          |    |              |    |              |    |
          +----+----+----+----+----+----+----+----+----+----+-> time
```

<a id="rst-representation-caveat"></a>

### 1.4 Representation caveat

It should be noted that having a *single* value to represent differences in CPU performance is somewhat of a contentious point. The relative performance difference between two different µarchs could be X% on integer operations, Y% on floating point operations, Z% on branches, and so on. Still, results using this simple approach have been satisfactory for now.

<a id="rst-task-utilization"></a>

## 2. Task utilization

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

### 2.1 Introduction

Capacity aware scheduling requires an expression of a task's requirements with regards to CPU capacity. Each scheduler class can express this differently, and while task utilization is specific to CFS, it is convenient to describe it here in order to introduce more generic concepts.

Task utilization is a percentage meant to represent the throughput requirements of a task. A simple approximation of it is the task's duty cycle, i.e.:



```text
task_util(p) = duty_cycle(p)
```

On an SMP system with fixed frequencies, 100% utilization suggests the task is a busy loop. Conversely, 10% utilization hints it is a small periodic task that spends more time sleeping than executing. Variable CPU frequencies and asymmetric CPU capacities complexify this somewhat; the following sections will expand on these.

<a id="rst-frequency-invariance"></a>

### 2.2 Frequency invariance

One issue that needs to be taken into account is that a workload's duty cycle is directly impacted by the current OPP the CPU is running at. Consider running a periodic workload at a given frequency F:



```text
CPU work ^
         |     ____                ____                ____
         |    |    |              |    |              |    |
         +----+----+----+----+----+----+----+----+----+----+-> time
```

This yields duty_cycle(p) == 25%.

Now, consider running the *same* workload at frequency F/2:



```text
CPU work ^
         |     _________           _________           ____
         |    |         |         |         |         |
         +----+----+----+----+----+----+----+----+----+----+-> time
```

This yields duty_cycle(p) == 50%, despite the task having the exact same behaviour (i.e. executing the same amount of work) in both executions.

The task utilization signal can be made frequency invariant using the following formula:



```text
task_util_freq_inv(p) = duty_cycle(p) * (curr_frequency(cpu) / max_frequency(cpu))
```

Applying this formula to the two examples above yields a frequency invariant task utilization of 25%.

<a id="rst-cpu-invariance"></a>

### 2.3 CPU invariance

CPU capacity has a similar effect on task utilization in that running an identical workload on CPUs of different capacity values will yield different duty cycles.

Consider the system described in 1.3.2., i.e.:



```text
- capacity(CPU0) = C
- capacity(CPU1) = C/3
```

Executing a given periodic workload on each CPU at their maximum frequency would result in:



```text
CPU0 work ^
          |     ____                ____                ____
          |    |    |              |    |              |    |
          +----+----+----+----+----+----+----+----+----+----+-> time

CPU1 work ^
          |     ______________      ______________      ____
          |    |              |    |              |    |
          +----+----+----+----+----+----+----+----+----+----+-> time
```

IOW,

- duty_cycle(p) == 25% if p runs on CPU0 at its maximum frequency

- duty_cycle(p) == 75% if p runs on CPU1 at its maximum frequency

The task utilization signal can be made CPU invariant using the following formula:



```text
task_util_cpu_inv(p) = duty_cycle(p) * (capacity(cpu) / max_capacity)
```

with `max_capacity` being the highest CPU capacity value in the system. Applying this formula to the above example above yields a CPU invariant task utilization of 25%.

<a id="rst-invariant-task-utilization"></a>

### 2.4 Invariant task utilization

Both frequency and CPU invariance need to be applied to task utilization in order to obtain a truly invariant signal. The pseudo-formula for a task utilization that is both CPU and frequency invariant is thus, for a given task p:



```text
                                   curr_frequency(cpu)   capacity(cpu)
task_util_inv(p) = duty_cycle(p) * ------------------- * -------------
                                   max_frequency(cpu)    max_capacity
```

In other words, invariant task utilization describes the behaviour of a task as if it were running on the highest-capacity CPU in the system, running at its maximum frequency.

Any mention of task utilization in the following sections will imply its invariant form.

<a id="rst-utilization-estimation"></a>

### 2.5 Utilization estimation

Without a crystal ball, task behaviour (and thus task utilization) cannot accurately be predicted the moment a task first becomes runnable. The CFS class maintains a handful of CPU and task signals based on the Per-Entity Load Tracking (PELT) mechanism, one of those yielding an *average* utilization (as opposed to instantaneous).

This means that while the capacity aware scheduling criteria will be written considering a "true" task utilization (using a crystal ball), the implementation will only ever be able to use an estimator thereof.

<a id="rst-capacity-aware-scheduling-requirements"></a>

## 3. Capacity aware scheduling requirements

<a id="rst-cpu-capacity-1"></a>

### 3.1 CPU capacity

Linux cannot currently figure out CPU capacity on its own, this information thus needs to be handed to it. Architectures must define arch_scale_cpu_capacity() for that purpose.

The arm, arm64, and RISC-V architectures directly map this to the arch_topology driver CPU scaling data, which is derived from the capacity-dmips-mhz CPU binding; see [Documentation/devicetree/bindings/cpu/cpu-capacity.txt](/kernel/hardware/devicetree/bindings-cpu/cpu-capacity.md).

<a id="rst-frequency-invariance-1"></a>

### 3.2 Frequency invariance

As stated in 2.2, capacity-aware scheduling requires a frequency-invariant task utilization. Architectures must define arch_scale_freq_capacity(cpu) for that purpose.

Implementing this function requires figuring out at which frequency each CPU have been running at. One way to implement this is to leverage hardware counters whose increment rate scale with a CPU's current frequency (APERF/MPERF on x86, AMU on arm64). Another is to directly hook into cpufreq frequency transitions, when the kernel is aware of the switched-to frequency (also employed by arm/arm64).

<a id="rst-scheduler-topology"></a>

## 4. Scheduler topology

During the construction of the sched domains, the scheduler will figure out whether the system exhibits asymmetric CPU capacities. Should that be the case:

- The sched_asym_cpucapacity static key will be enabled.

- The SD_ASYM_CPUCAPACITY_FULL flag will be set at the lowest sched_domain level that spans all unique CPU capacity values.

- The SD_ASYM_CPUCAPACITY flag will be set for any sched_domain that spans CPUs with any range of asymmetry.

The sched_asym_cpucapacity static key is intended to guard sections of code that cater to asymmetric CPU capacity systems. Do note however that said key is *system-wide*. Imagine the following setup using cpusets:



```text
capacity    C/2          C
          ________    ________
         /        \  /        \
CPUs     0  1  2  3  4  5  6  7
         \__/  \______________/
cpusets   cs0         cs1
```

Which could be created via:



```sh
mkdir /sys/fs/cgroup/cpuset/cs0
echo 0-1 > /sys/fs/cgroup/cpuset/cs0/cpuset.cpus
echo 0 > /sys/fs/cgroup/cpuset/cs0/cpuset.mems

mkdir /sys/fs/cgroup/cpuset/cs1
echo 2-7 > /sys/fs/cgroup/cpuset/cs1/cpuset.cpus
echo 0 > /sys/fs/cgroup/cpuset/cs1/cpuset.mems

echo 0 > /sys/fs/cgroup/cpuset/cpuset.sched_load_balance
```

Since there *is* CPU capacity asymmetry in the system, the sched_asym_cpucapacity static key will be enabled. However, the sched_domain hierarchy of CPUs 0-1 spans a single capacity value: SD_ASYM_CPUCAPACITY isn't set in that hierarchy, it describes an SMP island and should be treated as such.

Therefore, the 'canonical' pattern for protecting codepaths that cater to asymmetric CPU capacities is to:

- Check the sched_asym_cpucapacity static key

- If it is enabled, then also check for the presence of SD_ASYM_CPUCAPACITY in the sched_domain hierarchy (if relevant, i.e. the codepath targets a specific CPU or group thereof)

<a id="rst-capacity-aware-scheduling-implementation"></a>

## 5. Capacity aware scheduling implementation

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

### 5.1 CFS

<a id="rst-capacity-fitness"></a>

#### 5.1.1 Capacity fitness

The main capacity scheduling criterion of CFS is:



```text
task_util(p) < capacity(task_cpu(p))
```

This is commonly called the capacity fitness criterion, i.e. CFS must ensure a task "fits" on its CPU. If it is violated, the task will need to achieve more work than what its CPU can provide: it will be CPU-bound.

Furthermore, uclamp lets userspace specify a minimum and a maximum utilization value for a task, either via sched_setattr() or via the cgroup interface (see [Documentation/admin-guide/cgroup-v2.rst](/kernel/administration/admin-guide/resources/cgroup-v2.md)). As its name imply, this can be used to clamp task_util() in the previous criterion.

<a id="rst-wakeup-cpu-selection"></a>

#### 5.1.2 Wakeup CPU selection

CFS task wakeup CPU selection follows the capacity fitness criterion described above. On top of that, uclamp is used to clamp the task utilization values, which lets userspace have more leverage over the CPU selection of CFS tasks. IOW, CFS wakeup CPU selection searches for a CPU that satisfies:



```text
clamp(task_util(p), task_uclamp_min(p), task_uclamp_max(p)) < capacity(cpu)
```

By using uclamp, userspace can e.g. allow a busy loop (100% utilization) to run on any CPU by giving it a low uclamp.max value. Conversely, it can force a small periodic task (e.g. 10% utilization) to run on the highest-performance CPUs by giving it a high uclamp.min value.

> [!NOTE]
>
> Wakeup CPU selection in CFS can be eclipsed by Energy Aware Scheduling (EAS), which is described in [Documentation/scheduler/sched-energy.rst](/kernel/internals/scheduler/sched-energy.md).

<a id="rst-load-balancing"></a>

#### 5.1.3 Load balancing

A pathological case in the wakeup CPU selection occurs when a task rarely sleeps, if at all - it thus rarely wakes up, if at all. Consider:



```text
w == wakeup event

capacity(CPU0) = C
capacity(CPU1) = C / 3

                         workload on CPU0
CPU work ^
         |     _________           _________           ____
         |    |         |         |         |         |
         +----+----+----+----+----+----+----+----+----+----+-> time
              w                   w                   w

                         workload on CPU1
CPU work ^
         |     ____________________________________________
         |    |
         +----+----+----+----+----+----+----+----+----+----+->
              w
```

This workload should run on CPU0, but if the task either:

- was improperly scheduled from the start (inaccurate initial utilization estimation)

- was properly scheduled from the start, but suddenly needs more processing power

then it might become CPU-bound, IOW `task_util(p) > capacity(task_cpu(p))`; the CPU capacity scheduling criterion is violated, and there may not be any more wakeup event to fix this up via wakeup CPU selection.

Tasks that are in this situation are dubbed "misfit" tasks, and the mechanism put in place to handle this shares the same name. Misfit task migration leverages the CFS load balancer, more specifically the active load balance part (which caters to migrating currently running tasks). When load balance happens, a misfit active load balance will be triggered if a misfit task can be migrated to a CPU with more capacity than its current one.

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

### 5.2 RT

<a id="rst-wakeup-cpu-selection-1"></a>

#### 5.2.1 Wakeup CPU selection

RT task wakeup CPU selection searches for a CPU that satisfies:



```text
task_uclamp_min(p) <= capacity(task_cpu(cpu))
```

while still following the usual priority constraints. If none of the candidate CPUs can satisfy this capacity criterion, then strict priority based scheduling is followed and CPU capacities are ignored.

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

### 5.3 DL

<a id="rst-wakeup-cpu-selection-2"></a>

#### 5.3.1 Wakeup CPU selection

DL task wakeup CPU selection searches for a CPU that satisfies:



```text
task_bandwidth(p) < capacity(task_cpu(p))
```

while still respecting the usual bandwidth and deadline constraints. If none of the candidate CPUs can satisfy this capacity criterion, then the task will remain on its current CPU.

---

# Deadline Task Scheduling

_Peios Kernel / Internals / Scheduling_

> Fiddling with these settings can result in an unpredictable or even unstable system behavior. As for -rt (group) scheduling, it is assumed that root users know what they're doing.

<a id="rst-deadline-task-scheduling"></a>

<!-- CONTENTS

0. WARNING
1. Overview
2. Scheduling algorithm
  2.1 Main algorithm
  2.2 Bandwidth reclaiming
3. Scheduling Real-Time Tasks
  3.1 Definitions
  3.2 Schedulability Analysis for Uniprocessor Systems
  3.3 Schedulability Analysis for Multiprocessor Systems
  3.4 Relationship with SCHED_DEADLINE Parameters
4. Bandwidth management
  4.1 System-wide settings
  4.2 Task interface
  4.3 Default behavior
  4.4 Behavior of sched_yield()
5. Tasks CPU affinity
  5.1 Using cgroup v1 cpuset controller
  5.2 Using cgroup v2 cpuset controller
6. Future plans
A. Test suite
B. Minimal main() -->

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

## 0. WARNING

> Fiddling with these settings can result in an unpredictable or even unstable system behavior. As for -rt (group) scheduling, it is assumed that root users know what they're doing.

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

## 1. Overview

> The SCHED_DEADLINE policy contained inside the sched_dl scheduling class is basically an implementation of the Earliest Deadline First (EDF) scheduling algorithm, augmented with a mechanism (called Constant Bandwidth Server, CBS) that makes it possible to isolate the behavior of tasks between each other.

<a id="rst-scheduling-algorithm"></a>

## 2. Scheduling algorithm

<a id="rst-main-algorithm"></a>

### 2.1 Main algorithm

> SCHED_DEADLINE \[18\] uses three parameters, named "runtime", "period", and "deadline", to schedule tasks. A SCHED_DEADLINE task should receive "runtime" microseconds of execution time every "period" microseconds, and these "runtime" microseconds are available within "deadline" microseconds from the beginning of the period.  In order to implement this behavior, every time the task wakes up, the scheduler computes a "scheduling deadline" consistent with the guarantee (using the CBS\[2,3\] algorithm). Tasks are then scheduled using EDF\[1\] on these scheduling deadlines (the task with the earliest scheduling deadline is selected for execution). Notice that the task actually receives "runtime" time units within "deadline" if a proper "admission control" strategy (see Section "4. Bandwidth management") is used (clearly, if the system is overloaded this guarantee cannot be respected).
>
> Summing up, the CBS\[2,3\] algorithm assigns scheduling deadlines to tasks so that each task runs for at most its runtime every period, avoiding any interference between different tasks (bandwidth isolation), while the EDF\[1\] algorithm selects the task with the earliest scheduling deadline as the one to be executed next. Thanks to this feature, tasks that do not strictly comply with the "traditional" real-time task model (see Section 3) can effectively use the new policy.
>
> In more details, the CBS algorithm assigns scheduling deadlines to tasks in the following way:
>
> > - Each SCHED_DEADLINE task is characterized by the "runtime", "deadline", and "period" parameters;
> >
> > - The state of the task is described by a "scheduling deadline", and a "remaining runtime". These two parameters are initially set to 0;
> >
> > - When a SCHED_DEADLINE task wakes up (becomes ready for execution), the scheduler checks if:
> >
> >
> >
> >   ```text
> >            remaining runtime                  runtime
> >   ----------------------------------    >    ---------
> >   scheduling deadline - current time           period
> >   ```
> >
> >   then, if the scheduling deadline is smaller than the current time, or this condition is verified, the scheduling deadline and the remaining runtime are re-initialized as
> >
> >   > scheduling deadline = current time + deadline remaining runtime = runtime
> >
> >   otherwise, the scheduling deadline and the remaining runtime are left unchanged;
> >
> > - When a SCHED_DEADLINE task executes for an amount of time t, its remaining runtime is decreased as:
> >
> >
> >
> >   ```text
> >   remaining runtime = remaining runtime - t
> >   ```
> >
> >   (technically, the runtime is decreased at every tick, or when the task is descheduled / preempted);
> >
> > - When the remaining runtime becomes less or equal than 0, the task is said to be "throttled" (also known as "depleted" in real-time literature) and cannot be scheduled until its scheduling deadline. The "replenishment time" for this task (see next item) is set to be equal to the current value of the scheduling deadline;
> >
> > - When the current time is equal to the replenishment time of a throttled task, the scheduling deadline and the remaining runtime are updated as:
> >
> >
> >
> >   ```text
> >   scheduling deadline = scheduling deadline + period
> >   remaining runtime = remaining runtime + runtime
> >   ```
>
> The SCHED_FLAG_DL_OVERRUN flag in sched_attr's sched_flags field allows a task to get informed about runtime overruns through the delivery of SIGXCPU signals.

<a id="rst-bandwidth-reclaiming"></a>

### 2.2 Bandwidth reclaiming

> Bandwidth reclaiming for deadline tasks is based on the GRUB (Greedy Reclamation of Unused Bandwidth) algorithm \[15, 16, 17\] and it is enabled when flag SCHED_FLAG_RECLAIM is set.
>
> The following diagram illustrates the state names for tasks handled by GRUB:
>
>
>
> ```text
>                     ------------
>         (d)        |   Active   |
>      ------------->|            |
>      |             | Contending |
>      |              ------------
>      |                A      |
>  ----------           |      |
> |          |          |      |
> | Inactive |          |(b)   | (a)
> |          |          |      |
>  ----------           |      |
>      A                |      V
>      |              ------------
>      |             |   Active   |
>      --------------|     Non    |
>         (c)        | Contending |
>                     ------------
> ```
>
> A task can be in one of the following states:
>
> > - ActiveContending: if it is ready for execution (or executing);
> >
> > - ActiveNonContending: if it just blocked and has not yet surpassed the 0-lag time;
> >
> > - Inactive: if it is blocked and has surpassed the 0-lag time.
>
> State transitions:
>
> > - **(a)** When a task blocks, it does not become immediately inactive since its bandwidth cannot be immediately reclaimed without breaking the real-time guarantees. It therefore enters a transitional state called ActiveNonContending. The scheduler arms the "inactive timer" to fire at the 0-lag time, when the task's bandwidth can be reclaimed without breaking the real-time guarantees.
> >
> >   The 0-lag time for a task entering the ActiveNonContending state is computed as:
> >
> >
> >
> >   ```text
> >              (runtime * dl_period)
> >   deadline - ---------------------
> >                   dl_runtime
> >   ```
> >
> >   where runtime is the remaining runtime, while dl_runtime and dl_period are the reservation parameters.
> >
> > - **(b)** If the task wakes up before the inactive timer fires, the task re-enters the ActiveContending state and the "inactive timer" is canceled. In addition, if the task wakes up on a different runqueue, then the task's utilization must be removed from the previous runqueue's active utilization and must be added to the new runqueue's active utilization. In order to avoid races between a task waking up on a runqueue while the "inactive timer" is running on a different CPU, the "dl_non_contending" flag is used to indicate that a task is not on a runqueue but is active (so, the flag is set when the task blocks and is cleared when the "inactive timer" fires or when the task  wakes up).
> >
> > - **(c)** When the "inactive timer" fires, the task enters the Inactive state and its utilization is removed from the runqueue's active utilization.
> >
> > - **(d)** When an inactive task wakes up, it enters the ActiveContending state and its utilization is added to the active utilization of the runqueue where it has been enqueued.
>
> For each runqueue, the algorithm GRUB keeps track of two different bandwidths:
>
> > - Active bandwidth (running_bw): this is the sum of the bandwidths of all tasks in active state (i.e., ActiveContending or ActiveNonContending);
> >
> > - Total bandwidth (this_bw): this is the sum of all tasks "belonging" to the runqueue, including the tasks in Inactive state.
> >
> > - Maximum usable bandwidth (max_bw): This is the maximum bandwidth usable by deadline tasks and is currently set to the RT capacity.
>
> The algorithm reclaims the bandwidth of the tasks in Inactive state. It does so by decrementing the runtime of the executing task Ti at a pace equal to
>
> > dq = -(max\{ Ui, (Umax - Uinact - Uextra) \} / Umax) dt
>
> where:
>
> > - Ui is the bandwidth of task Ti;
> >
> > - Umax is the maximum reclaimable utilization (subjected to RT throttling limits);
> >
> > - Uinact is the (per runqueue) inactive utilization, computed as (this_bq - running_bw);
> >
> > - Uextra is the (per runqueue) extra reclaimable utilization (subjected to RT throttling limits).
>
> Let's now see a trivial example of two deadline tasks with runtime equal to 4 and period equal to 8 (i.e., bandwidth equal to 0.5):
>
>
>
> ```text
>        A            Task T1
>        |
>        |                               |
>        |                               |
>        |--------                       |----
>        |       |                       V
>        |---|---|---|---|---|---|---|---|--------->t
>        0   1   2   3   4   5   6   7   8
>
>
>        A            Task T2
>        |
>        |                               |
>        |                               |
>        |       ------------------------|
>        |       |                       V
>        |---|---|---|---|---|---|---|---|--------->t
>        0   1   2   3   4   5   6   7   8
>
>
>        A            running_bw
>        |
>      1 -----------------               ------
>        |               |               |
>     0.5-               -----------------
>        |                               |
>        |---|---|---|---|---|---|---|---|--------->t
>        0   1   2   3   4   5   6   7   8
>
>
> - Time t = 0:
>
>   Both tasks are ready for execution and therefore in ActiveContending state.
>   Suppose Task T1 is the first task to start execution.
>   Since there are no inactive tasks, its runtime is decreased as dq = -1 dt.
>
> - Time t = 2:
>
>   Suppose that task T1 blocks
>   Task T1 therefore enters the ActiveNonContending state. Since its remaining
>   runtime is equal to 2, its 0-lag time is equal to t = 4.
>   Task T2 start execution, with runtime still decreased as dq = -1 dt since
>   there are no inactive tasks.
>
> - Time t = 4:
>
>   This is the 0-lag time for Task T1. Since it didn't woken up in the
>   meantime, it enters the Inactive state. Its bandwidth is removed from
>   running_bw.
>   Task T2 continues its execution. However, its runtime is now decreased as
>   dq = - 0.5 dt because Uinact = 0.5.
>   Task T2 therefore reclaims the bandwidth unused by Task T1.
>
> - Time t = 8:
>
>   Task T1 wakes up. It enters the ActiveContending state again, and the
>   running_bw is incremented.
> ```

<a id="rst-energy-aware-scheduling"></a>

### 2.3 Energy-aware scheduling

> When cpufreq's schedutil governor is selected, SCHED_DEADLINE implements the GRUB-PA \[19\] algorithm, reducing the CPU operating frequency to the minimum value that still allows to meet the deadlines. This behavior is currently implemented only for ARM architectures.
>
> A particular care must be taken in case the time needed for changing frequency is of the same order of magnitude of the reservation period. In such cases, setting a fixed CPU frequency results in a lower amount of deadline misses.

<a id="rst-scheduling-real-time-tasks"></a>

## 3. Scheduling Real-Time Tasks

> <!-- BIG FAT WARNING ****************************************************** -->
>
> > [!WARNING]
> >
> > This section contains a (not-thorough) summary on classical deadline scheduling theory, and how it applies to SCHED_DEADLINE. The reader can "safely" skip to Section 4 if only interested in seeing how the scheduling policy can be used. Anyway, we strongly recommend to come back here and continue reading (once the urge for testing is satisfied :P) to be sure of fully understanding all technical details.
>
> <!-- ************************************************************************ -->
>
> There are no limitations on what kind of task can exploit this new scheduling discipline, even if it must be said that it is particularly suited for periodic or sporadic real-time tasks that need guarantees on their timing behavior, e.g., multimedia, streaming, control applications, etc.

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

### 3.1 Definitions

> A typical real-time task is composed of a repetition of computation phases (task instances, or jobs) which are activated on a periodic or sporadic fashion. Each job J_j (where J_j is the j^th job of the task) is characterized by an arrival time r_j (the time when the job starts), an amount of computation time c_j needed to finish the job, and a job absolute deadline d_j, which is the time within which the job should be finished. The maximum execution time max\{c_j\} is called "Worst Case Execution Time" (WCET) for the task. A real-time task can be periodic with period P if r\_\{j+1\} = r_j + P, or sporadic with minimum inter-arrival time P is r\_\{j+1\} &gt;= r_j + P. Finally, d_j = r_j + D, where D is the task's relative deadline. Summing up, a real-time task can be described as
>
> > Task = (WCET, D, P)
>
> The utilization of a real-time task is defined as the ratio between its WCET and its period (or minimum inter-arrival time), and represents the fraction of CPU time needed to execute the task.
>
> If the total utilization U=sum(WCET_i/P_i) is larger than M (with M equal to the number of CPUs), then the scheduler is unable to respect all the deadlines. Note that total utilization is defined as the sum of the utilizations WCET_i/P_i over all the real-time tasks in the system. When considering multiple real-time tasks, the parameters of the i-th task are indicated with the "\_i" suffix. Moreover, if the total utilization is larger than M, then we risk starving non- real-time tasks by real-time tasks. If, instead, the total utilization is smaller than M, then non real-time tasks will not be starved and the system might be able to respect all the deadlines. As a matter of fact, in this case it is possible to provide an upper bound for tardiness (defined as the maximum between 0 and the difference between the finishing time of a job and its absolute deadline). More precisely, it can be proven that using a global EDF scheduler the maximum tardiness of each task is smaller or equal than
>
> > ((M − 1) · WCET_max − WCET_min)/(M − (M − 2) · U_max) + WCET_max
>
> where WCET_max = max\{WCET_i\} is the maximum WCET, WCET_min=min\{WCET_i\} is the minimum WCET, and U_max = max\{WCET_i/P_i\} is the maximum utilization\[12\].

<a id="rst-schedulability-analysis-for-uniprocessor-systems"></a>

### 3.2 Schedulability Analysis for Uniprocessor Systems

> If M=1 (uniprocessor system), or in case of partitioned scheduling (each real-time task is statically assigned to one and only one CPU), it is possible to formally check if all the deadlines are respected. If D_i = P_i for all tasks, then EDF is able to respect all the deadlines of all the tasks executing on a CPU if and only if the total utilization of the tasks running on such a CPU is smaller or equal than 1. If D_i \!= P_i for some task, then it is possible to define the density of a task as WCET_i/min\{D_i,P_i\}, and EDF is able to respect all the deadlines of all the tasks running on a CPU if the sum of the densities of the tasks running on such a CPU is smaller or equal than 1:
>
> > sum(WCET_i / min\{D_i, P_i\}) &lt;= 1
>
> It is important to notice that this condition is only sufficient, and not necessary: there are task sets that are schedulable, but do not respect the condition. For example, consider the task set \{Task_1,Task_2\} composed by Task_1=(50ms,50ms,100ms) and Task_2=(10ms,100ms,100ms). EDF is clearly able to schedule the two tasks without missing any deadline (Task_1 is scheduled as soon as it is released, and finishes just in time to respect its deadline; Task_2 is scheduled immediately after Task_1, hence its response time cannot be larger than 50ms + 10ms = 60ms) even if
>
> > 50 / min\{50,100\} + 10 / min\{100, 100\} = 50 / 50 + 10 / 100 = 1.1
>
> Of course it is possible to test the exact schedulability of tasks with D_i \!= P_i (checking a condition that is both sufficient and necessary), but this cannot be done by comparing the total utilization or density with a constant. Instead, the so called "processor demand" approach can be used, computing the total amount of CPU time h(t) needed by all the tasks to respect all of their deadlines in a time interval of size t, and comparing such a time with the interval size t. If h(t) is smaller than t (that is, the amount of time needed by the tasks in a time interval of size t is smaller than the size of the interval) for all the possible values of t, then EDF is able to schedule the tasks respecting all of their deadlines. Since performing this check for all possible values of t is impossible, it has been proven\[4,5,6\] that it is sufficient to perform the test for values of t between 0 and a maximum value L. The cited papers contain all of the mathematical details and explain how to compute h(t) and L. In any case, this kind of analysis is too complex as well as too time-consuming to be performed on-line. Hence, as explained in Section 4 Linux uses an admission test based on the tasks' utilizations.

<a id="rst-schedulability-analysis-for-multiprocessor-systems"></a>

### 3.3 Schedulability Analysis for Multiprocessor Systems

> On multiprocessor systems with global EDF scheduling (non partitioned systems), a sufficient test for schedulability can not be based on the utilizations or densities: it can be shown that even if D_i = P_i task sets with utilizations slightly larger than 1 can miss deadlines regardless of the number of CPUs.
>
> Consider a set \{Task_1,...Task\_\{M+1\}\} of M+1 tasks on a system with M CPUs, with the first task Task_1=(P,P,P) having period, relative deadline and WCET equal to P. The remaining M tasks Task_i=(e,P-1,P-1) have an arbitrarily small worst case execution time (indicated as "e" here) and a period smaller than the one of the first task. Hence, if all the tasks activate at the same time t, global EDF schedules these M tasks first (because their absolute deadlines are equal to t + P - 1, hence they are smaller than the absolute deadline of Task_1, which is t + P). As a result, Task_1 can be scheduled only at time t + e, and will finish at time t + e + P, after its absolute deadline. The total utilization of the task set is U = M · e / (P - 1) + P / P = M · e / (P - 1) + 1, and for small values of e this can become very close to 1. This is known as "Dhall's effect"\[7\]. Note: the example in the original paper by Dhall has been slightly simplified here (for example, Dhall more correctly computed lim\_\{e-&gt;0\}U).
>
> More complex schedulability tests for global EDF have been developed in real-time literature\[8,9\], but they are not based on a simple comparison between total utilization (or density) and a fixed constant. If all tasks have D_i = P_i, a sufficient schedulability condition can be expressed in a simple way:
>
> > sum(WCET_i / P_i) &lt;= M - (M - 1) · U_max
>
> where U_max = max\{WCET_i / P_i\}\[10\]. Notice that for U_max = 1, M - (M - 1) · U_max becomes M - M + 1 = 1 and this schedulability condition just confirms the Dhall's effect. A more complete survey of the literature about schedulability tests for multi-processor real-time scheduling can be found in \[11\].
>
> As seen, enforcing that the total utilization is smaller than M does not guarantee that global EDF schedules the tasks without missing any deadline (in other words, global EDF is not an optimal scheduling algorithm). However, a total utilization smaller than M is enough to guarantee that non real-time tasks are not starved and that the tardiness of real-time tasks has an upper bound\[12\] (as previously noted). Different bounds on the maximum tardiness experienced by real-time tasks have been developed in various papers\[13,14\], but the theoretical result that is important for SCHED_DEADLINE is that if the total utilization is smaller or equal than M then the response times of the tasks are limited.

<a id="rst-relationship-with-sched-deadline-parameters"></a>

### 3.4 Relationship with SCHED_DEADLINE Parameters

> Finally, it is important to understand the relationship between the SCHED_DEADLINE scheduling parameters described in Section 2 (runtime, deadline and period) and the real-time task parameters (WCET, D, P) described in this section. Note that the tasks' temporal constraints are represented by its absolute deadlines d_j = r_j + D described above, while SCHED_DEADLINE schedules the tasks according to scheduling deadlines (see Section 2). If an admission test is used to guarantee that the scheduling deadlines are respected, then SCHED_DEADLINE can be used to schedule real-time tasks guaranteeing that all the jobs' deadlines of a task are respected. In order to do this, a task must be scheduled by setting:
>
> > - runtime &gt;= WCET
> >
> > - deadline = D
> >
> > - period &lt;= P
>
> IOW, if runtime &gt;= WCET and if period is &lt;= P, then the scheduling deadlines and the absolute deadlines (d_j) coincide, so a proper admission control allows to respect the jobs' absolute deadlines for this task (this is what is called "hard schedulability property" and is an extension of Lemma 1 of \[2\]). Notice that if runtime &gt; deadline the admission control will surely reject this task, as it is not possible to respect its temporal constraints.
>
> References:
>
> > - **1 - C. L. Liu and J. W. Layland. Scheduling algorithms for multiprogram-**
> >
> >   ming in a hard-real-time environment. Journal of the Association for Computing Machinery, 20(1), 1973.
> >
> > - **2 - L. Abeni , G. Buttazzo. Integrating Multimedia Applications in Hard**
> >
> >   Real-Time Systems. Proceedings of the 19th IEEE Real-time Systems Symposium, 1998. [http://retis.sssup.it/\~giorgio/paps/1998/rtss98-cbs.pdf](<http://retis.sssup.it/~giorgio/paps/1998/rtss98-cbs.pdf>)
> >
> > - **3 - L. Abeni. Server Mechanisms for Multimedia Applications. ReTiS Lab**
> >
> >   Technical Report. [http://disi.unitn.it/\~abeni/tr-98-01.pdf](<http://disi.unitn.it/~abeni/tr-98-01.pdf>)
> >
> > - **4 - J. Y. Leung and M.L. Merril. A Note on Preemptive Scheduling of**
> >
> >   Periodic, Real-Time Tasks. Information Processing Letters, vol. 11, no. 3, pp. 115-118, 1980.
> >
> > - **5 - S. K. Baruah, A. K. Mok and L. E. Rosier. Preemptively Scheduling**
> >
> >   Hard-Real-Time Sporadic Tasks on One Processor. Proceedings of the 11th IEEE Real-time Systems Symposium, 1990.
> >
> > - **6 - S. K. Baruah, L. E. Rosier and R. R. Howell. Algorithms and Complexity**
> >
> >   Concerning the Preemptive Scheduling of Periodic Real-Time tasks on One Processor. Real-Time Systems Journal, vol. 4, no. 2, pp 301-324, 1990.
> >
> > - **7 - S. J. Dhall and C. L. Liu. On a real-time scheduling problem. Operations**
> >
> >   research, vol. 26, no. 1, pp 127-140, 1978.
> >
> > - **8 - T. Baker. Multiprocessor EDF and Deadline Monotonic Schedulability**
> >
> >   Analysis. Proceedings of the 24th IEEE Real-Time Systems Symposium, 2003.
> >
> > - **9 - T. Baker. An Analysis of EDF Schedulability on a Multiprocessor.**
> >
> >   IEEE Transactions on Parallel and Distributed Systems, vol. 16, no. 8, pp 760-768, 2005.
> >
> > - **10 - J. Goossens, S. Funk and S. Baruah, Priority-Driven Scheduling of**
> >
> >   Periodic Task Systems on Multiprocessors. Real-Time Systems Journal, vol. 25, no. 2–3, pp. 187–205, 2003.
> >
> > - **11 - R. Davis and A. Burns. A Survey of Hard Real-Time Scheduling for**
> >
> >   Multiprocessor Systems. ACM Computing Surveys, vol. 43, no. 4, 2011. [http://www-users.cs.york.ac.uk/\~robdavis/papers/MPSurveyv5.0.pdf](<http://www-users.cs.york.ac.uk/~robdavis/papers/MPSurveyv5.0.pdf>)
> >
> > - **12 - U. C. Devi and J. H. Anderson. Tardiness Bounds under Global EDF**
> >
> >   Scheduling on a Multiprocessor. Real-Time Systems Journal, vol. 32, no. 2, pp 133-189, 2008.
> >
> > - **13 - P. Valente and G. Lipari. An Upper Bound to the Lateness of Soft**
> >
> >   Real-Time Tasks Scheduled by EDF on Multiprocessors. Proceedings of the 26th IEEE Real-Time Systems Symposium, 2005.
> >
> > - **14 - J. Erickson, U. Devi and S. Baruah. Improved tardiness bounds for**
> >
> >   Global EDF. Proceedings of the 22nd Euromicro Conference on Real-Time Systems, 2010.
> >
> > - **15 - G. Lipari, S. Baruah, Greedy reclamation of unused bandwidth in**
> >
> >   constant-bandwidth servers, 12th IEEE Euromicro Conference on Real-Time Systems, 2000.
> >
> > - **16 - L. Abeni, J. Lelli, C. Scordino, L. Palopoli, Greedy CPU reclaiming for**
> >
> >   SCHED DEADLINE. In Proceedings of the Real-Time Linux Workshop (RTLWS), Dusseldorf, Germany, 2014.
> >
> > - **17 - L. Abeni, G. Lipari, A. Parri, Y. Sun, Multicore CPU reclaiming: parallel**
> >
> >   or sequential?. In Proceedings of the 31st Annual ACM Symposium on Applied Computing, 2016.
> >
> > - **18 - J. Lelli, C. Scordino, L. Abeni, D. Faggioli, Deadline scheduling in the**
> >
> >   Linux kernel, Software: Practice and Experience, 46(6): 821-839, June 2016.
> >
> > - **19 - C. Scordino, L. Abeni, J. Lelli, Energy-Aware Real-Time Scheduling in**
> >
> >   the Linux Kernel, 33rd ACM/SIGAPP Symposium On Applied Computing (SAC 2018), Pau, France, April 2018.

<a id="rst-bandwidth-management"></a>

## 4. Bandwidth management

> As previously mentioned, in order for -deadline scheduling to be effective and useful (that is, to be able to provide "runtime" time units within "deadline"), it is important to have some method to keep the allocation of the available fractions of CPU time to the various tasks under control. This is usually called "admission control" and if it is not performed, then no guarantee can be given on the actual scheduling of the -deadline tasks.
>
> As already stated in Section 3, a necessary condition to be respected to correctly schedule a set of real-time tasks is that the total utilization is smaller than M. When talking about -deadline tasks, this requires that the sum of the ratio between runtime and period for all tasks is smaller than M. Notice that the ratio runtime/period is equivalent to the utilization of a "traditional" real-time task, and is also often referred to as "bandwidth". The interface used to control the CPU bandwidth that can be allocated to -deadline tasks is similar to the one already used for -rt tasks with real-time group scheduling (a.k.a. RT-throttling - see [Documentation/scheduler/sched-rt-group.rst](/kernel/internals/scheduler/sched-rt-group.md)), and is based on readable/ writable control files located in procfs (for system wide settings). Notice that per-group settings (controlled through cgroupfs) are still not defined for -deadline tasks, because more discussion is needed in order to figure out how we want to manage SCHED_DEADLINE bandwidth at the task group level.
>
> A main difference between deadline bandwidth management and RT-throttling is that -deadline tasks have bandwidth on their own (while -rt ones don't\!), and thus we don't need a higher level throttling mechanism to enforce the desired bandwidth. In other words, this means that interface parameters are only used at admission control time (i.e., when the user calls sched_setattr()). Scheduling is then performed considering actual tasks' parameters, so that CPU bandwidth is allocated to SCHED_DEADLINE tasks respecting their needs in terms of granularity. Therefore, using this simple interface we can put a cap on total utilization of -deadline tasks (i.e., Sum (runtime_i / period_i) &lt; global_dl_utilization_cap).

<a id="rst-system-wide-settings"></a>

### 4.1 System wide settings

> The system wide settings are configured under the /proc virtual file system.
>
> For now the -rt knobs are used for -deadline admission control and with CONFIG_RT_GROUP_SCHED the -deadline runtime is accounted against the (root) -rt runtime. With \!CONFIG_RT_GROUP_SCHED the knob only serves for the -dl admission control. We realize that this isn't entirely desirable; however, it is better to have a small interface for now, and be able to change it easily later. The ideal situation (see 5.) is to run -rt tasks from a -deadline server; in which case the -rt bandwidth is a direct subset of dl_bw.
>
> This means that, for a root_domain comprising M CPUs, -deadline tasks can be created while the sum of their bandwidths stays below:
>
> > M \* (sched_rt_runtime_us / sched_rt_period_us)
>
> It is also possible to disable this bandwidth management logic, and be thus free of oversubscribing the system up to any arbitrary level. This is done by writing -1 in /proc/sys/kernel/sched_rt_runtime_us.

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

### 4.2 Task interface

> Specifying a periodic/sporadic task that executes for a given amount of runtime at each instance, and that is scheduled according to the urgency of its own timing constraints needs, in general, a way of declaring:
>
> > - a (maximum/typical) instance execution time,
> >
> > - a minimum interval between consecutive instances,
> >
> > - a time constraint by which each instance must be completed.
>
> Therefore:
>
> > - a new struct sched_attr, containing all the necessary fields is provided;
> >
> > - the new scheduling related syscalls that manipulate it, i.e., sched_setattr() and sched_getattr() are implemented.
>
> For debugging purposes, the leftover runtime and absolute deadline of a SCHED_DEADLINE task can be retrieved through /proc/&lt;pid&gt;/sched (entries dl.runtime and dl.deadline, both values in ns). A programmatic way to retrieve these values from production code is under discussion.

<a id="rst-default-behavior"></a>

### 4.3 Default behavior

> The default value for SCHED_DEADLINE bandwidth is to have rt_runtime equal to 950000. With rt_period equal to 1000000, by default, it means that -deadline tasks can use at most 95%, multiplied by the number of CPUs that compose the root_domain, for each root_domain. This means that non -deadline tasks will receive at least 5% of the CPU time, and that -deadline tasks will receive their runtime with a guaranteed worst-case delay respect to the "deadline" parameter. If "deadline" = "period" and the cpuset mechanism is used to implement partitioned scheduling (see Section 5), then this simple setting of the bandwidth management is able to deterministically guarantee that -deadline tasks will receive their runtime in a period.
>
> Finally, notice that in order not to jeopardize the admission control a -deadline task cannot fork.

<a id="rst-behavior-of-sched-yield"></a>

### 4.4 Behavior of sched_yield()

> When a SCHED_DEADLINE task calls sched_yield(), it gives up its remaining runtime and is immediately throttled, until the next period, when its runtime will be replenished (a special flag dl_yielded is set and used to handle correctly throttling and runtime replenishment after a call to sched_yield()).
>
> This behavior of sched_yield() allows the task to wake-up exactly at the beginning of the next period. Also, this may be useful in the future with bandwidth reclaiming mechanisms, where sched_yield() will make the leftoever runtime available for reclamation by other SCHED_DEADLINE tasks.

<a id="rst-tasks-cpu-affinity"></a>

## 5. Tasks CPU affinity

> Deadline tasks cannot have a cpu affinity mask smaller than the root domain they are created on. So, using `sched_setaffinity(2)` won't work. Instead, the the deadline task should be created in a restricted root domain. This can be done using the cpuset controller of either cgroup v1 (deprecated) or cgroup v2. See [Documentation/admin-guide/cgroup-v1/cpusets.rst](</kernel/administration/admin-guide/cgroup-v1/cpusets.md#rst-cpusets-1>) and [Documentation/admin-guide/cgroup-v2.rst](</kernel/administration/admin-guide/resources/cgroup-v2.md#rst-cgroup-v2>) for more information.

<a id="rst-using-cgroup-v1-cpuset-controller"></a>

### 5.1 Using cgroup v1 cpuset controller

> An example of a simple configuration (pin a -deadline task to CPU0) follows:
>
>
>
> ```text
> mkdir /dev/cpuset
> mount -t cgroup -o cpuset cpuset /dev/cpuset
> cd /dev/cpuset
> mkdir cpu0
> echo 0 > cpu0/cpuset.cpus
> echo 0 > cpu0/cpuset.mems
> echo 1 > cpuset.cpu_exclusive
> echo 0 > cpuset.sched_load_balance
> echo 1 > cpu0/cpuset.cpu_exclusive
> echo 1 > cpu0/cpuset.mem_exclusive
> echo $$ > cpu0/tasks
> chrt --sched-runtime 100000 --sched-period 200000 --deadline 0 yes > /dev/null
> ```

<a id="rst-using-cgroup-v2-cpuset-controller"></a>

### 5.2 Using cgroup v2 cpuset controller

> Assuming the cgroup v2 root is mounted at `/sys/fs/cgroup`.
>
> > cd /sys/fs/cgroup echo '+cpuset' &gt; cgroup.subtree_control mkdir deadline_group echo 0 &gt; deadline_group/cpuset.cpus echo 'root' &gt; deadline_group/cpuset.cpus.partition echo $$ &gt; deadline_group/cgroup.procs chrt --sched-runtime 100000 --sched-period 200000 --deadline 0 yes &gt; /dev/null

<a id="rst-future-plans"></a>

## 6. Future plans

> Still missing:
>
> > - programmatic way to retrieve current runtime and absolute deadline
> >
> > - refinements to deadline inheritance, especially regarding the possibility of retaining bandwidth isolation among non-interacting tasks. This is being studied from both theoretical and practical points of view, and hopefully we should be able to produce some demonstrative code soon;
> >
> > - (c)group based bandwidth management, and maybe scheduling;
> >
> > - access control for non-root users (and related security concerns to address), which is the best way to allow unprivileged use of the mechanisms and how to prevent non-root users "cheat" the system?
>
> As already discussed, we are planning also to merge this work with the EDF throttling patches \[[https://lore.kernel.org/r/cover.1266931410.git.fabio@helm.retis](<https://lore.kernel.org/r/cover.1266931410.git.fabio@helm.retis>)\] but we still are in the preliminary phases of the merge and we really seek feedback that would help us decide on the direction it should take.

<a id="rst-appendix-a-test-suite"></a>

## Appendix A. Test suite

> The SCHED_DEADLINE policy can be easily tested using two applications that are part of a wider Linux Scheduler validation suite. The suite is available as a GitHub repository: [https://github.com/scheduler-tools](<https://github.com/scheduler-tools>).
>
> The first testing application is called rt-app and can be used to start multiple threads with specific parameters. rt-app supports SCHED\_\{OTHER,FIFO,RR,DEADLINE\} scheduling policies and their related parameters (e.g., niceness, priority, runtime/deadline/period). rt-app is a valuable tool, as it can be used to synthetically recreate certain workloads (maybe mimicking real use-cases) and evaluate how the scheduler behaves under such workloads. In this way, results are easily reproducible. rt-app is available at: [https://github.com/scheduler-tools/rt-app](<https://github.com/scheduler-tools/rt-app>).
>
> rt-app does not accept command line arguments, and instead reads from a JSON configuration file. Here is an example `config.json`:
>
>
>
> ```json
> {
>   "tasks": {
>     "dl_task": {
>       "policy": "SCHED_DEADLINE",
>       "priority": 0,
>       "dl-runtime": 10000,
>       "dl-period": 100000,
>       "dl-deadline": 100000
>     },
>     "fifo_task": {
>       "policy": "SCHED_FIFO",
>       "priority": 10,
>       "runtime": 20000,
>       "sleep": 130000
>     }
>   },
>   "global": {
>     "duration": 5
>   }
> }
> ```
>
> On running `rt-app config.json`, it creates 2 threads. The first one, scheduled by SCHED_DEADLINE, executes for 10ms every 100ms. The second one, scheduled at SCHED_FIFO priority 10, executes for 20ms every 150ms. The test will run for a total of 5 seconds.
>
> Please refer to the rt-app documentation for the JSON schema and more examples.
>
> The second testing application is done using chrt which has support for SCHED_DEADLINE.
>
> The usage is straightforward:
>
>
>
> ```text
> # chrt -d -T 10000000 -D 100000000 0 ./my_cpuhog_app
> ```
>
> With this, my_cpuhog_app is put to run inside a SCHED_DEADLINE reservation of 10ms every 100ms (note that parameters are expressed in nanoseconds). You can also use chrt to create a reservation for an already running application, given that you know its pid:
>
>
>
> ```text
> # chrt -d -T 10000000 -D 100000000 -p 0 my_app_pid
> ```

<a id="rst-appendix-b-minimal-main"></a>

## Appendix B. Minimal main()

> We provide in what follows a simple (ugly) self-contained code snippet showing how SCHED_DEADLINE reservations can be created by a real-time application developer:
>
>
>
> ```text
> #define _GNU_SOURCE
> #include <unistd.h>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> #include <time.h>
> #include <linux/unistd.h>
> #include <linux/kernel.h>
> #include <linux/types.h>
> #include <sys/syscall.h>
> #include <pthread.h>
>
> #define gettid() syscall(__NR_gettid)
>
> #define SCHED_DEADLINE       6
>
> /* XXX use the proper syscall numbers */
> #ifdef __x86_64__
> #define __NR_sched_setattr           314
> #define __NR_sched_getattr           315
> #endif
>
> #ifdef __i386__
> #define __NR_sched_setattr           351
> #define __NR_sched_getattr           352
> #endif
>
> #ifdef __arm__
> #define __NR_sched_setattr           380
> #define __NR_sched_getattr           381
> #endif
>
> static volatile int done;
>
> struct sched_attr {
>      __u32 size;
>
>      __u32 sched_policy;
>      __u64 sched_flags;
>
>      /* SCHED_NORMAL, SCHED_BATCH */
>      __s32 sched_nice;
>
>      /* SCHED_FIFO, SCHED_RR */
>      __u32 sched_priority;
>
>      /* SCHED_DEADLINE (nsec) */
>      __u64 sched_runtime;
>      __u64 sched_deadline;
>      __u64 sched_period;
> };
>
> int sched_setattr(pid_t pid,
>                const struct sched_attr *attr,
>                unsigned int flags)
> {
>      return syscall(__NR_sched_setattr, pid, attr, flags);
> }
>
> int sched_getattr(pid_t pid,
>                struct sched_attr *attr,
>                unsigned int size,
>                unsigned int flags)
> {
>      return syscall(__NR_sched_getattr, pid, attr, size, flags);
> }
>
> void *run_deadline(void *data)
> {
>      struct sched_attr attr;
>      int x = 0;
>      int ret;
>      unsigned int flags = 0;
>
>      printf("deadline thread started [%ld]\n", gettid());
>
>      attr.size = sizeof(attr);
>      attr.sched_flags = 0;
>      attr.sched_nice = 0;
>      attr.sched_priority = 0;
>
>      /* This creates a 10ms/30ms reservation */
>      attr.sched_policy = SCHED_DEADLINE;
>      attr.sched_runtime = 10 * 1000 * 1000;
>      attr.sched_period = attr.sched_deadline = 30 * 1000 * 1000;
>
>      ret = sched_setattr(0, &attr, flags);
>      if (ret < 0) {
>              done = 0;
>              perror("sched_setattr");
>              exit(-1);
>      }
>
>      while (!done) {
>              x++;
>      }
>
>      printf("deadline thread dies [%ld]\n", gettid());
>      return NULL;
> }
>
> int main (int argc, char **argv)
> {
>      pthread_t thread;
>
>      printf("main thread [%ld]\n", gettid());
>
>      pthread_create(&thread, NULL, run_deadline, NULL);
>
>      sleep(10);
>
>      done = 1;
>      pthread_join(thread, NULL);
>
>      printf("main dies [%ld]\n", gettid());
>      return 0;
> }
> ```

---

# Scheduler debugfs

_Peios Kernel / Internals / Scheduling_

> Booting a kernel with debugfs enabled will give access to scheduler specific debug files under /sys/kernel/debug/sched. Some of those files are described below.

<a id="rst-scheduler-debugfs"></a>

Booting a kernel with debugfs enabled will give access to scheduler specific debug files under /sys/kernel/debug/sched. Some of those files are described below.

<a id="rst-numa-balancing"></a>

## numa_balancing

`numa_balancing` directory is used to hold files to control NUMA balancing feature.  If the system overhead from the feature is too high then the rate the kernel samples for NUMA hinting faults may be controlled by the `scan_period_min_ms, scan_delay_ms, scan_period_max_ms, scan_size_mb` files.

<a id="rst-scan-period-min-ms-scan-delay-ms-scan-period-max-ms-scan-size-mb"></a>

### scan_period_min_ms, scan_delay_ms, scan_period_max_ms, scan_size_mb

Automatic NUMA balancing scans tasks address space and unmaps pages to detect if pages are properly placed or if the data should be migrated to a memory node local to where the task is running.  Every "scan delay" the task scans the next "scan size" number of pages in its address space. When the end of the address space is reached the scanner restarts from the beginning.

In combination, the "scan delay" and "scan size" determine the scan rate. When "scan delay" decreases, the scan rate increases.  The scan delay and hence the scan rate of every task is adaptive and depends on historical behaviour. If pages are properly placed then the scan delay increases, otherwise the scan delay decreases.  The "scan size" is not adaptive but the higher the "scan size", the higher the scan rate.

Higher scan rates incur higher system overhead as page faults must be trapped and potentially data must be migrated. However, the higher the scan rate, the more quickly a tasks memory is migrated to a local node if the workload pattern changes and minimises performance impact due to remote memory accesses. These files control the thresholds for scan delays and the number of pages scanned.

`scan_period_min_ms` is the minimum time in milliseconds to scan a tasks virtual memory. It effectively controls the maximum scanning rate for each task.

`scan_delay_ms` is the starting "scan delay" used for a task when it initially forks.

`scan_period_max_ms` is the maximum time in milliseconds to scan a tasks virtual memory. It effectively controls the minimum scanning rate for each task.

`scan_size_mb` is how many megabytes worth of pages are scanned for a given scan.

---

# CFS Scheduler

_Peios Kernel / Internals / Scheduling_

> CFS stands for "Completely Fair Scheduler," and is the "desktop" process scheduler implemented by Ingo Molnar and merged in Linux 2.6.23. When originally merged, it was the replacement for the previous vanilla scheduler's SCHED_OTHER…

<a id="rst-cfs-scheduler"></a>
<a id="rst-sched-design-cfs"></a>

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

## 1.  OVERVIEW

CFS stands for "Completely Fair Scheduler," and is the "desktop" process scheduler implemented by Ingo Molnar and merged in Linux 2.6.23. When originally merged, it was the replacement for the previous vanilla scheduler's SCHED_OTHER interactivity code. Nowadays, CFS is making room for EEVDF, for which documentation can be found in [Documentation/scheduler/sched-eevdf.rst](/kernel/internals/scheduler/sched-eevdf.md).

80% of CFS's design can be summed up in a single sentence: CFS basically models an "ideal, precise multi-tasking CPU" on real hardware.

"Ideal multi-tasking CPU" is a (non-existent  :-)) CPU that has 100% physical power and which can run each task at precise equal speed, in parallel, each at 1/nr_running speed.  For example: if there are 2 tasks running, then it runs each at 50% physical power --- i.e., actually in parallel.

On real hardware, we can run only a single task at once, so we have to introduce the concept of "virtual runtime."  The virtual runtime of a task specifies when its next timeslice would start execution on the ideal multi-tasking CPU described above.  In practice, the virtual runtime of a task is its actual runtime normalized to the total number of running tasks.

<a id="rst-few-implementation-details"></a>

## 2.  FEW IMPLEMENTATION DETAILS

In CFS the virtual runtime is expressed and tracked via the per-task p-&gt;se.vruntime (nanosec-unit) value.  This way, it's possible to accurately timestamp and measure the "expected CPU time" a task should have gotten.

> Small detail: on "ideal" hardware, at any time all tasks would have the same p-&gt;se.vruntime value --- i.e., tasks would execute simultaneously and no task would ever get "out of balance" from the "ideal" share of CPU time.

CFS's task picking logic is based on this p-&gt;se.vruntime value and it is thus very simple: it always tries to run the task with the smallest p-&gt;se.vruntime value (i.e., the task which executed least so far).  CFS always tries to split up CPU time between runnable tasks as close to "ideal multitasking hardware" as possible.

Most of the rest of CFS's design just falls out of this really simple concept, with a few add-on embellishments like nice levels, multiprocessing and various algorithm variants to recognize sleepers.

<a id="rst-the-rbtree"></a>

## 3.  THE RBTREE

CFS's design is quite radical: it does not use the old data structures for the runqueues, but it uses a time-ordered rbtree to build a "timeline" of future task execution, and thus has no "array switch" artifacts (by which both the previous vanilla scheduler and RSDL/SD are affected).

CFS also maintains the rq-&gt;cfs.min_vruntime value, which is a monotonic increasing value tracking the smallest vruntime among all tasks in the runqueue.  The total amount of work done by the system is tracked using min_vruntime; that value is used to place newly activated entities on the left side of the tree as much as possible.

The total number of running tasks in the runqueue is accounted through the rq-&gt;cfs.load value, which is the sum of the weights of the tasks queued on the runqueue.

CFS maintains a time-ordered rbtree, where all runnable tasks are sorted by the p-&gt;se.vruntime key. CFS picks the "leftmost" task from this tree and sticks to it. As the system progresses forwards, the executed tasks are put into the tree more and more to the right --- slowly but surely giving a chance for every task to become the "leftmost task" and thus get on the CPU within a deterministic amount of time.

Summing up, CFS works like this: it runs a task a bit, and when the task schedules (or a scheduler tick happens) the task's CPU usage is "accounted for": the (small) time it just spent using the physical CPU is added to p-&gt;se.vruntime.  Once p-&gt;se.vruntime gets high enough so that another task becomes the "leftmost task" of the time-ordered rbtree it maintains (plus a small amount of "granularity" distance relative to the leftmost task so that we do not over-schedule tasks and trash the cache), then the new leftmost task is picked and the current task is preempted.

<a id="rst-some-features-of-cfs"></a>

## 4.  SOME FEATURES OF CFS

CFS uses nanosecond granularity accounting and does not rely on any jiffies or other HZ detail.  Thus the CFS scheduler has no notion of "timeslices" in the way the previous scheduler had, and has no heuristics whatsoever.  There is only one central tunable:

> /sys/kernel/debug/sched/base_slice_ns

which can be used to tune the scheduler from "desktop" (i.e., low latencies) to "server" (i.e., good batching) workloads.  It defaults to a setting suitable for desktop workloads.  SCHED_BATCH is handled by the CFS scheduler module too.

In case CONFIG_HZ results in base_slice_ns &lt; TICK_NSEC, the value of base_slice_ns will have little to no impact on the workloads.

Due to its design, the CFS scheduler is not prone to any of the "attacks" that exist today against the heuristics of the stock scheduler: fiftyp.c, thud.c, chew.c, ring-test.c, massive_intr.c all work fine and do not impact interactivity and produce the expected behavior.

The CFS scheduler has a much stronger handling of nice levels and SCHED_BATCH than the previous vanilla scheduler: both types of workloads are isolated much more aggressively.

SMP load-balancing has been reworked/sanitized: the runqueue-walking assumptions are gone from the load-balancing code now, and iterators of the scheduling modules are used.  The balancing code got quite a bit simpler as a result.

<a id="rst-scheduling-policies"></a>

## 5. Scheduling policies

CFS implements three scheduling policies:

> - SCHED_NORMAL (traditionally called SCHED_OTHER): The scheduling policy that is used for regular tasks.
>
> - SCHED_BATCH: Does not preempt nearly as often as regular tasks would, thereby allowing tasks to run longer and make better use of caches but at the cost of interactivity. This is well suited for batch jobs.
>
> - SCHED_IDLE: This is even weaker than nice 19, but its not a true idle timer scheduler in order to avoid to get into priority inversion problems which would deadlock the machine.

SCHED_FIFO/\_RR are implemented in sched/rt.c and are as specified by POSIX.

The command chrt from util-linux-ng 2.13.1.1 can set all of these except SCHED_IDLE.

<a id="rst-scheduling-classes"></a>

## 6.  SCHEDULING CLASSES

The new CFS scheduler has been designed in such a way to introduce "Scheduling Classes," an extensible hierarchy of scheduler modules.  These modules encapsulate scheduling policy details and are handled by the scheduler core without the core code assuming too much about them.

sched/fair.c implements the CFS scheduler described above.

sched/rt.c implements SCHED_FIFO and SCHED_RR semantics, in a simpler way than the previous vanilla scheduler did.  It uses 100 runqueues (for all 100 RT priority levels, instead of 140 in the previous scheduler) and it needs no expired array.

Scheduling classes are implemented through the sched_class structure, which contains hooks to functions that must be called whenever an interesting event occurs.

This is the (partial) list of the hooks:

> - enqueue_task(...)
>
>   Called when a task enters a runnable state. It puts the scheduling entity (task) into the red-black tree and increments the nr_running variable.
>
> - dequeue_task(...)
>
>   When a task is no longer runnable, this function is called to keep the corresponding scheduling entity out of the red-black tree.  It decrements the nr_running variable.
>
> - yield_task(...)
>
>   This function is basically just a dequeue followed by an enqueue, unless the compat_yield sysctl is turned on; in that case, it places the scheduling entity at the right-most end of the red-black tree.
>
> - wakeup_preempt(...)
>
>   This function checks if a task that entered the runnable state should preempt the currently running task.
>
> - pick_next_task(...)
>
>   This function chooses the most appropriate task eligible to run next.
>
> - set_next_task(...)
>
>   This function is called when a task changes its scheduling class, changes its task group or is scheduled.
>
> - task_tick(...)
>
>   This function is mostly called from time tick functions; it might lead to process switch.  This drives the running preemption.

<a id="rst-group-scheduler-extensions-to-cfs"></a>

## 7.  GROUP SCHEDULER EXTENSIONS TO CFS

Normally, the scheduler operates on individual tasks and strives to provide fair CPU time to each task.  Sometimes, it may be desirable to group tasks and provide fair CPU time to each such task group.  For example, it may be desirable to first provide fair CPU time to each user on the system and then to each task belonging to a user.

CONFIG_CGROUP_SCHED strives to achieve exactly that.  It lets tasks to be grouped and divides CPU time fairly among such groups.

CONFIG_RT_GROUP_SCHED permits to group real-time (i.e., SCHED_FIFO and SCHED_RR) tasks.

CONFIG_FAIR_GROUP_SCHED permits to group CFS (i.e., SCHED_NORMAL and SCHED_BATCH) tasks.

> These options need CONFIG_CGROUPS to be defined, and let the administrator create arbitrary groups of tasks, using the "cgroup" pseudo filesystem.  See [Documentation/admin-guide/cgroup-v1/cgroups.rst](/kernel/administration/admin-guide/cgroup-v1/cgroups.md) for more information about this filesystem.

When CONFIG_FAIR_GROUP_SCHED is defined, a "cpu.shares" file is created for each group created using the pseudo filesystem.  See example steps below to create task groups and modify their CPU share using the "cgroups" pseudo filesystem:



```text
# mount -t tmpfs cgroup_root /sys/fs/cgroup
# mkdir /sys/fs/cgroup/cpu
# mount -t cgroup -ocpu none /sys/fs/cgroup/cpu
# cd /sys/fs/cgroup/cpu

# mkdir multimedia      # create "multimedia" group of tasks
# mkdir browser         # create "browser" group of tasks

# #Configure the multimedia group to receive twice the CPU bandwidth
# #that of browser group

# echo 2048 > multimedia/cpu.shares
# echo 1024 > browser/cpu.shares

# firefox &     # Launch firefox and move it to "browser" group
# echo <firefox_pid> > browser/tasks

# #Launch gmplayer (or your favourite movie player)
# echo <movie_player_pid> > multimedia/tasks
```

---

# Scheduler Domains

_Peios Kernel / Internals / Scheduling_

> Each CPU has a "base" scheduling domain (struct sched_domain). The domain hierarchy is built from these base domains via the ->parent pointer. ->parent MUST be NULL terminated, and domain structures should be per-CPU as they are locklessly…

<a id="rst-scheduler-domains"></a>

Each CPU has a "base" scheduling domain (struct sched_domain). The domain hierarchy is built from these base domains via the -&gt;parent pointer. -&gt;parent MUST be NULL terminated, and domain structures should be per-CPU as they are locklessly updated.

Each scheduling domain spans a number of CPUs (stored in the -&gt;span field). A domain's span MUST be a superset of it child's span (this restriction could be relaxed if the need arises), and a base domain for CPU i MUST span at least i. The top domain for each CPU will generally span all CPUs in the system although strictly it doesn't have to, but this could lead to a case where some CPUs will never be given tasks to run unless the CPUs allowed mask is explicitly set. A sched domain's span means "balance process load among these CPUs".

Each scheduling domain must have one or more CPU groups (struct sched_group) which are organised as a circular one way linked list from the -&gt;groups pointer. The union of cpumasks of these groups MUST be the same as the domain's span. The group pointed to by the -&gt;groups pointer MUST contain the CPU to which the domain belongs. Groups may be shared among CPUs as they contain read only data after they have been set up. The intersection of cpumasks from any two of these groups may be non empty. If this is the case the SD_OVERLAP flag is set on the corresponding scheduling domain and its groups may not be shared between CPUs.

Balancing within a sched domain occurs between groups. That is, each group is treated as one entity. The load of a group is defined as the sum of the load of each of its member CPUs, and only when the load of a group becomes out of balance are tasks moved between groups.

In kernel/sched/core.c, sched_balance_trigger() is run periodically on each CPU through sched_tick(). It raises a softirq after the next regularly scheduled rebalancing event for the current runqueue has arrived. The actual load balancing workhorse, sched_balance_softirq()-&gt;sched_balance_domains(), is then run in softirq context (SCHED_SOFTIRQ).

The latter function takes two arguments: the runqueue of current CPU and whether the CPU was idle at the time the sched_tick() happened and iterates over all sched domains our CPU is on, starting from its base domain and going up the -&gt;parent chain. While doing that, it checks to see if the current domain has exhausted its rebalance interval. If so, it runs sched_balance_rq() on that domain. It then checks the parent sched_domain (if it exists), and the parent of the parent and so forth.

Initially, sched_balance_rq() finds the busiest group in the current sched domain. If it succeeds, it looks for the busiest runqueue of all the CPUs' runqueues in that group. If it manages to find such a runqueue, it locks both our initial CPU's runqueue and the newly found busiest one and starts moving tasks from it to our runqueue. The exact number of tasks amounts to an imbalance previously computed while iterating over this sched domain's groups.

<a id="rst-implementing-sched-domains"></a>

## Implementing sched domains

The "base" domain will "span" the first level of the hierarchy. In the case of SMT, you'll span all siblings of the physical CPU, with each group being a single virtual CPU.

In SMP, the parent of the base domain will span all physical CPUs in the node. Each group being a single physical CPU. Then with NUMA, the parent of the SMP domain will span the entire machine, with each group having the cpumask of a node. Or, you could do multi-level NUMA or Opteron, for example, might have just one domain covering its one NUMA level.

The implementor should read comments in include/linux/sched/sd_flags.h: SD\_\* to get an idea of the specifics and what to tune for the SD flags of a sched_domain.

Architectures may override the generic domain builder and the default SD flags for a given topology level by creating a sched_domain_topology_level array and calling set_sched_topology() with this array as the parameter.

The sched-domains debugging infrastructure can be enabled by 'sched_verbose' to your cmdline. If you forgot to tweak your cmdline, you can also flip the /sys/kernel/debug/sched/verbose knob. This enables an error checking parse of the sched domains which should catch most possible errors (described above). It also prints out the domain structure in a visual format.

---

# EEVDF Scheduler

_Peios Kernel / Internals / Scheduling_

> The "Earliest Eligible Virtual Deadline First" (EEVDF) was first introduced in a scientific publication in 1995 [1]. The Linux kernel began transitioning to EEVDF in version 6.6 (as a new option in 2024), moving away from the earlier…

<a id="rst-eevdf-scheduler"></a>

The "Earliest Eligible Virtual Deadline First" (EEVDF) was first introduced in a scientific publication in 1995 \[1\]. The Linux kernel began transitioning to EEVDF in version 6.6 (as a new option in 2024), moving away from the earlier Completely Fair Scheduler (CFS) in favor of a version of EEVDF proposed by Peter Zijlstra in 2023 \[2-4\]. More information regarding CFS can be found in [Documentation/scheduler/sched-design-CFS.rst](/kernel/internals/scheduler/sched-design-cfs.md).

Similarly to CFS, EEVDF aims to distribute CPU time equally among all runnable tasks with the same priority. To do so, it assigns a virtual run time to each task, creating a "lag" value that can be used to determine whether a task has received its fair share of CPU time. In this way, a task with a positive lag is owed CPU time, while a negative lag means the task has exceeded its portion. EEVDF picks tasks with lag greater or equal to zero and calculates a virtual deadline (VD) for each, selecting the task with the earliest VD to execute next. It's important to note that this allows latency-sensitive tasks with shorter time slices to be prioritized, which helps with their responsiveness.

There are ongoing discussions on how to manage lag, especially for sleeping tasks; but at the time of writing EEVDF uses a "decaying" mechanism based on virtual run time (VRT). This prevents tasks from exploiting the system by sleeping briefly to reset their negative lag: when a task sleeps, it remains on the run queue but marked for "deferred dequeue," allowing its lag to decay over VRT. Hence, long-sleeping tasks eventually have their lag reset. Finally, tasks can preempt others if their VD is earlier, and tasks can request specific time slices using the new sched_setattr() system call, which further facilitates the job of latency-sensitive applications.

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

## REFERENCES

\[1\] [https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=805acf7726282721504c8f00575d91ebfd750564](<https://citeseerx.ist.psu.edu/document?repid=rep1&type=pdf&doi=805acf7726282721504c8f00575d91ebfd750564>)

\[2\] [https://lore.kernel.org/lkml/a79014e6-ea83-b316-1e12-2ae056bda6fa@linux.vnet.ibm.com/](<https://lore.kernel.org/lkml/a79014e6-ea83-b316-1e12-2ae056bda6fa@linux.vnet.ibm.com/>)

\[3\] [https://lwn.net/Articles/969062/](<https://lwn.net/Articles/969062/>)

\[4\] [https://lwn.net/Articles/925371/](<https://lwn.net/Articles/925371/>)

---

# Energy Aware Scheduling

_Peios Kernel / Internals / Scheduling_

> Energy Aware Scheduling (or EAS) gives the scheduler the ability to predict the impact of its decisions on the energy consumed by CPUs. EAS relies on an Energy Model (EM) of the CPUs to select an energy efficient CPU for each task, with a…

<a id="rst-energy-aware-scheduling"></a>

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

## 1. Introduction

Energy Aware Scheduling (or EAS) gives the scheduler the ability to predict the impact of its decisions on the energy consumed by CPUs. EAS relies on an Energy Model (EM) of the CPUs to select an energy efficient CPU for each task, with a minimal impact on throughput. This document aims at providing an introduction on how EAS works, what are the main design decisions behind it, and details what is needed to get it to run.

Before going any further, please note that at the time of writing:



```text
/!\ EAS does not support platforms with symmetric CPU topologies /!\
```

EAS operates only on heterogeneous CPU topologies (such as Arm big.LITTLE) because this is where the potential for saving energy through scheduling is the highest.

The actual EM used by EAS is \_not\_ maintained by the scheduler, but by a dedicated framework. For details about this framework and what it provides, please refer to its documentation (see [Documentation/power/energy-model.rst](/kernel/internals/power/energy-model.md)).

<a id="rst-background-and-terminology"></a>

## 2. Background and Terminology

- **To make it clear from the start:**

  - energy = \[joule\] (resource like a battery on powered devices)

  - power = energy/time = \[joule/second\] = \[watt\]

The goal of EAS is to minimize energy, while still getting the job done. That is, we want to maximize:



```text
performance [inst/s]
--------------------
    power [W]
```

which is equivalent to minimizing:



```text
energy [J]
-----------
instruction
```

while still getting 'good' performance. It is essentially an alternative optimization objective to the current performance-only objective for the scheduler. This alternative considers two objectives: energy-efficiency and performance.

The idea behind introducing an EM is to allow the scheduler to evaluate the implications of its decisions rather than blindly applying energy-saving techniques that may have positive effects only on some platforms. At the same time, the EM must be as simple as possible to minimize the scheduler latency impact.

In short, EAS changes the way CFS tasks are assigned to CPUs. When it is time for the scheduler to decide where a task should run (during wake-up), the EM is used to break the tie between several good CPU candidates and pick the one that is predicted to yield the best energy consumption without harming the system's throughput. The predictions made by EAS rely on specific elements of knowledge about the platform's topology, which include the 'capacity' of CPUs, and their respective energy costs.

<a id="rst-topology-information"></a>

## 3. Topology information

EAS (as well as the rest of the scheduler) uses the notion of 'capacity' to differentiate CPUs with different computing throughput. The 'capacity' of a CPU represents the amount of work it can absorb when running at its highest frequency compared to the most capable CPU of the system. Capacity values are normalized in a 1024 range, and are comparable with the utilization signals of tasks and CPUs computed by the Per-Entity Load Tracking (PELT) mechanism. Thanks to capacity and utilization values, EAS is able to estimate how big/busy a task/CPU is, and to take this into consideration when evaluating performance vs energy trade-offs. The capacity of CPUs is provided via arch-specific code through the arch_scale_cpu_capacity() callback.

The rest of platform knowledge used by EAS is directly read from the Energy Model (EM) framework. The EM of a platform is composed of a power cost table per 'performance domain' in the system (see [Documentation/power/energy-model.rst](/kernel/internals/power/energy-model.md) for further details about performance domains).

The scheduler manages references to the EM objects in the topology code when the scheduling domains are built, or re-built. For each root domain (rd), the scheduler maintains a singly linked list of all performance domains intersecting the current rd-&gt;span. Each node in the list contains a pointer to a struct em_perf_domain as provided by the EM framework.

The lists are attached to the root domains in order to cope with exclusive cpuset configurations. Since the boundaries of exclusive cpusets do not necessarily match those of performance domains, the lists of different root domains can contain duplicate elements.

- **Example 1.**

  Let us consider a platform with 12 CPUs, split in 3 performance domains (pd0, pd4 and pd8), organized as follows:



  ```text
  CPUs:   0 1 2 3 4 5 6 7 8 9 10 11
  PDs:   |--pd0--|--pd4--|---pd8---|
  RDs:   |----rd1----|-----rd2-----|
  ```

  Now, consider that userspace decided to split the system with two exclusive cpusets, hence creating two independent root domains, each containing 6 CPUs. The two root domains are denoted rd1 and rd2 in the above figure. Since pd4 intersects with both rd1 and rd2, it will be present in the linked list '-&gt;pd' attached to each of them:

  > - rd1-&gt;pd: pd0 -&gt; pd4
  >
  > - rd2-&gt;pd: pd4 -&gt; pd8

  Please note that the scheduler will create two duplicate list nodes for pd4 (one for each list). However, both just hold a pointer to the same shared data structure of the EM framework.

Since the access to these lists can happen concurrently with hotplug and other things, they are protected by RCU, like the rest of topology structures manipulated by the scheduler.

EAS also maintains a static key (sched_energy_present) which is enabled when at least one root domain meets all conditions for EAS to start. Those conditions are summarized in Section 6.

<a id="rst-energy-aware-task-placement"></a>

## 4. Energy-Aware task placement

EAS overrides the CFS task wake-up balancing code. It uses the EM of the platform and the PELT signals to choose an energy-efficient target CPU during wake-up balance. When EAS is enabled, select_task_rq_fair() calls find_energy_efficient_cpu() to do the placement decision. This function looks for the CPU with the highest spare capacity (CPU capacity - CPU utilization) in each performance domain since it is the one which will allow us to keep the frequency the lowest. Then, the function checks if placing the task there could save energy compared to leaving it on prev_cpu, i.e. the CPU where the task ran in its previous activation.

find_energy_efficient_cpu() uses compute_energy() to estimate what will be the energy consumed by the system if the waking task was migrated. compute_energy() looks at the current utilization landscape of the CPUs and adjusts it to 'simulate' the task migration. The EM framework provides the em_pd_energy() API which computes the expected energy consumption of each performance domain for the given utilization landscape.

An example of energy-optimized task placement decision is detailed below.

- **Example 2.**

  Let us consider a (fake) platform with 2 independent performance domains composed of two CPUs each. CPU0 and CPU1 are little CPUs; CPU2 and CPU3 are big.

  The scheduler must decide where to place a task P whose util_avg = 200 and prev_cpu = 0.

  The current utilization landscape of the CPUs is depicted on the graph below. CPUs 0-3 have a util_avg of 400, 100, 600 and 500 respectively Each performance domain has three Operating Performance Points (OPPs). The CPU capacity and power cost associated with each OPP is listed in the Energy Model table. The util_avg of P is shown on the figures below as 'PP':



  ```text
  CPU util.
   1024                 - - - - - - -              Energy Model
                                            +-----------+-------------+
                                            |  Little   |     Big     |
    768                 =============       +-----+-----+------+------+
                                            | Cap | Pwr | Cap  | Pwr  |
                                            +-----+-----+------+------+
    512  ===========    - ##- - - - -       | 170 | 50  | 512  | 400  |
                          ##     ##         | 341 | 150 | 768  | 800  |
    341  -PP - - - -      ##     ##         | 512 | 300 | 1024 | 1700 |
          PP              ##     ##         +-----+-----+------+------+
    170  -## - - - -      ##     ##
          ##     ##       ##     ##
        ------------    -------------
         CPU0   CPU1     CPU2   CPU3

   Current OPP: =====       Other OPP: - - -     util_avg (100 each): ##
  ```

  find_energy_efficient_cpu() will first look for the CPUs with the maximum spare capacity in the two performance domains. In this example, CPU1 and CPU3. Then it will estimate the energy of the system if P was placed on either of them, and check if that would save some energy compared to leaving P on CPU0. EAS assumes that OPPs follow utilization (which is coherent with the behaviour of the schedutil CPUFreq governor, see Section 6. for more details on this topic).

  **Case 1. P is migrated to CPU1**:



  ```text
  1024                 - - - - - - -

                                        Energy calculation:
   768                 =============     * CPU0: 200 / 341 * 150 = 88
                                         * CPU1: 300 / 341 * 150 = 131
                                         * CPU2: 600 / 768 * 800 = 625
   512  - - - - - -    - ##- - - - -     * CPU3: 500 / 768 * 800 = 520
                         ##     ##          => total_energy = 1364
   341  ===========      ##     ##
                PP       ##     ##
   170  -## - - PP-      ##     ##
         ##     ##       ##     ##
       ------------    -------------
        CPU0   CPU1     CPU2   CPU3
  ```

  **Case 2. P is migrated to CPU3**:



  ```text
  1024                 - - - - - - -

                                        Energy calculation:
   768                 =============     * CPU0: 200 / 341 * 150 = 88
                                         * CPU1: 100 / 341 * 150 = 43
                                PP       * CPU2: 600 / 768 * 800 = 625
   512  - - - - - -    - ##- - -PP -     * CPU3: 700 / 768 * 800 = 729
                         ##     ##          => total_energy = 1485
   341  ===========      ##     ##
                         ##     ##
   170  -## - - - -      ##     ##
         ##     ##       ##     ##
       ------------    -------------
        CPU0   CPU1     CPU2   CPU3
  ```

  **Case 3. P stays on prev_cpu / CPU 0**:



  ```text
  1024                 - - - - - - -

                                        Energy calculation:
   768                 =============     * CPU0: 400 / 512 * 300 = 234
                                         * CPU1: 100 / 512 * 300 = 58
                                         * CPU2: 600 / 768 * 800 = 625
   512  ===========    - ##- - - - -     * CPU3: 500 / 768 * 800 = 520
                         ##     ##          => total_energy = 1437
   341  -PP - - - -      ##     ##
         PP              ##     ##
   170  -## - - - -      ##     ##
         ##     ##       ##     ##
       ------------    -------------
        CPU0   CPU1     CPU2   CPU3
  ```

  From these calculations, the Case 1 has the lowest total energy. So CPU 1 is the best candidate from an energy-efficiency standpoint.

Big CPUs are generally more power hungry than the little ones and are thus used mainly when a task doesn't fit the littles. However, little CPUs aren't always necessarily more energy-efficient than big CPUs. For some systems, the high OPPs of the little CPUs can be less energy-efficient than the lowest OPPs of the bigs, for example. So, if the little CPUs happen to have enough utilization at a specific point in time, a small task waking up at that moment could be better off executing on the big side in order to save energy, even though it would fit on the little side.

And even in the case where all OPPs of the big CPUs are less energy-efficient than those of the little, using the big CPUs for a small task might still, under specific conditions, save energy. Indeed, placing a task on a little CPU can result in raising the OPP of the entire performance domain, and that will increase the cost of the tasks already running there. If the waking task is placed on a big CPU, its own execution cost might be higher than if it was running on a little, but it won't impact the other tasks of the little CPUs which will keep running at a lower OPP. So, when considering the total energy consumed by CPUs, the extra cost of running that one task on a big core can be smaller than the cost of raising the OPP on the little CPUs for all the other tasks.

The examples above would be nearly impossible to get right in a generic way, and for all platforms, without knowing the cost of running at different OPPs on all CPUs of the system. Thanks to its EM-based design, EAS should cope with them correctly without too many troubles. However, in order to ensure a minimal impact on throughput for high-utilization scenarios, EAS also implements another mechanism called 'over-utilization'.

<a id="rst-over-utilization"></a>

## 5. Over-utilization

From a general standpoint, the use-cases where EAS can help the most are those involving a light/medium CPU utilization. Whenever long CPU-bound tasks are being run, they will require all of the available CPU capacity, and there isn't much that can be done by the scheduler to save energy without severely harming throughput. In order to avoid hurting performance with EAS, CPUs are flagged as 'over-utilized' as soon as they are used at more than 80% of their compute capacity. As long as no CPUs are over-utilized in a root domain, load balancing is disabled and EAS overrides the wake-up balancing code. EAS is likely to load the most energy efficient CPUs of the system more than the others if that can be done without harming throughput. So, the load-balancer is disabled to prevent it from breaking the energy-efficient task placement found by EAS. It is safe to do so when the system isn't overutilized since being below the 80% tipping point implies that:

> - **a.** there is some idle time on all CPUs, so the utilization signals used by EAS are likely to accurately represent the 'size' of the various tasks in the system;
>
> - **b.** all tasks should already be provided with enough CPU capacity, regardless of their nice values;
>
> - **c.** since there is spare capacity all tasks must be blocking/sleeping regularly and balancing at wake-up is sufficient.

As soon as one CPU goes above the 80% tipping point, at least one of the three assumptions above becomes incorrect. In this scenario, the 'overutilized' flag is raised for the entire root domain, EAS is disabled, and the load-balancer is re-enabled. By doing so, the scheduler falls back onto load-based algorithms for wake-up and load balance under CPU-bound conditions. This provides a better respect of the nice values of tasks.

Since the notion of overutilization largely relies on detecting whether or not there is some idle time in the system, the CPU capacity 'stolen' by higher (than CFS) scheduling classes (as well as IRQ) must be taken into account. As such, the detection of overutilization accounts for the capacity used not only by CFS tasks, but also by the other scheduling classes and IRQ.

<a id="rst-dependencies-and-requirements-for-eas"></a>

## 6. Dependencies and requirements for EAS

Energy Aware Scheduling depends on the CPUs of the system having specific hardware properties and on other features of the kernel being enabled. This section lists these dependencies and provides hints as to how they can be met.

<a id="rst-asymmetric-cpu-topology"></a>

### 6.1 - Asymmetric CPU topology

As mentioned in the introduction, EAS is only supported on platforms with asymmetric CPU topologies for now. This requirement is checked at run-time by looking for the presence of the SD_ASYM_CPUCAPACITY_FULL flag when the scheduling domains are built.

See [Documentation/scheduler/sched-capacity.rst](/kernel/internals/scheduler/sched-capacity.md) for requirements to be met for this flag to be set in the sched_domain hierarchy.

Please note that EAS is not fundamentally incompatible with SMP, but no significant savings on SMP platforms have been observed yet. This restriction could be amended in the future if proven otherwise.

<a id="rst-energy-model-presence"></a>

### 6.2 - Energy Model presence

EAS uses the EM of a platform to estimate the impact of scheduling decisions on energy. So, your platform must provide power cost tables to the EM framework in order to make EAS start. To do so, please refer to documentation of the independent EM framework in [Documentation/power/energy-model.rst](/kernel/internals/power/energy-model.md).

Please also note that the scheduling domains need to be re-built after the EM has been registered in order to start EAS.

EAS uses the EM to make a forecasting decision on energy usage and thus it is more focused on the difference when checking possible options for task placement. For EAS it doesn't matter whether the EM power values are expressed in milli-Watts or in an 'abstract scale'.

<a id="rst-energy-model-complexity"></a>

### 6.3 - Energy Model complexity

EAS does not impose any complexity limit on the number of PDs/OPPs/CPUs but restricts the number of CPUs to EM_MAX_NUM_CPUS to prevent overflows during the energy estimation.

<a id="rst-schedutil-governor"></a>

### 6.4 - Schedutil governor

EAS tries to predict at which OPP will the CPUs be running in the close future in order to estimate their energy consumption. To do so, it is assumed that OPPs of CPUs follow their utilization.

Although it is very difficult to provide hard guarantees regarding the accuracy of this assumption in practice (because the hardware might not do what it is told to do, for example), schedutil as opposed to other CPUFreq governors at least \_requests\_ frequencies calculated using the utilization signals. Consequently, the only sane governor to use together with EAS is schedutil, because it is the only one providing some degree of consistency between frequency requests and energy predictions.

Using EAS with any other governor than schedutil is not supported.

<a id="rst-scale-invariant-utilization-signals"></a>

### 6.5 Scale-invariant utilization signals

In order to make accurate predictions across CPUs and for all performance states, EAS needs frequency-invariant and CPU-invariant PELT signals. These can be obtained using the architecture-defined arch_scale\{cpu,freq\}\_capacity() callbacks.

Using EAS on a platform that doesn't implement these two callbacks is not supported.

<a id="rst-multithreading-smt"></a>

### 6.6 Multithreading (SMT)

EAS in its current form is SMT unaware and is not able to leverage multithreaded hardware to save energy. EAS considers threads as independent CPUs, which can actually be counter-productive for both performance and energy.

EAS on SMT is not supported.

---

# Extensible Scheduler Class

_Peios Kernel / Internals / Scheduling_

> sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

<a id="rst-extensible-scheduler-class"></a>
<a id="rst-sched-ext"></a>

sched_ext is a scheduler class whose behavior can be defined by a set of BPF programs - the BPF scheduler.

- sched_ext exports a full scheduling interface so that any scheduling algorithm can be implemented on top.

- The BPF scheduler can group CPUs however it sees fit and schedule them together, as tasks aren't tied to specific CPUs at the time of wakeup.

- The BPF scheduler can be turned on and off dynamically anytime.

- The system integrity is maintained no matter what the BPF scheduler does. The default scheduling behavior is restored anytime an error is detected, a runnable task stalls, or on invoking the SysRq key sequence `SysRq-S`.

- When the BPF scheduler triggers an error, debug information is dumped to aid debugging. The debug dump is passed to and printed out by the scheduler binary. The debug dump can also be accessed through the `sched_ext_dump` tracepoint. The SysRq key sequence `SysRq-D` triggers a debug dump. This doesn't terminate the BPF scheduler and can only be read through the tracepoint.

<a id="rst-switching-to-and-from-sched-ext"></a>

## Switching to and from sched_ext

`CONFIG_SCHED_CLASS_EXT` is the config option to enable sched_ext and `tools/sched_ext` contains the example schedulers. The following config options should be enabled to use sched_ext:



```none
CONFIG_BPF=y
CONFIG_SCHED_CLASS_EXT=y
CONFIG_BPF_SYSCALL=y
CONFIG_BPF_JIT=y
CONFIG_DEBUG_INFO_BTF=y
CONFIG_BPF_JIT_ALWAYS_ON=y
CONFIG_BPF_JIT_DEFAULT_ON=y
```

sched_ext is used only when the BPF scheduler is loaded and running.

If a task explicitly sets its scheduling policy to `SCHED_EXT`, it will be treated as `SCHED_NORMAL` and scheduled by the fair-class scheduler until the BPF scheduler is loaded.

When the BPF scheduler is loaded and `SCX_OPS_SWITCH_PARTIAL` is not set in `ops->flags`, all `SCHED_NORMAL`, `SCHED_BATCH`, `SCHED_IDLE`, and `SCHED_EXT` tasks are scheduled by sched_ext.

However, when the BPF scheduler is loaded and `SCX_OPS_SWITCH_PARTIAL` is set in `ops->flags`, only tasks with the `SCHED_EXT` policy are scheduled by sched_ext, while tasks with `SCHED_NORMAL`, `SCHED_BATCH` and `SCHED_IDLE` policies are scheduled by the fair-class scheduler which has higher sched_class precedence than `SCHED_EXT`.

Terminating the sched_ext scheduler program, triggering `SysRq-S`, or detection of any internal error including stalled runnable tasks aborts the BPF scheduler and reverts all tasks back to the fair-class scheduler.



```none
# make -j16 -C tools/sched_ext
# tools/sched_ext/build/bin/scx_simple
local=0 global=3
local=5 global=24
local=9 global=44
local=13 global=56
local=17 global=72
^CEXIT: BPF scheduler unregistered
```

The current status of the BPF scheduler can be determined as follows:



```none
# cat /sys/kernel/sched_ext/state
enabled
# cat /sys/kernel/sched_ext/root/ops
simple
```

You can check if any BPF scheduler has ever been loaded since boot by examining this monotonically incrementing counter (a value of zero indicates that no BPF scheduler has been loaded):



```none
# cat /sys/kernel/sched_ext/enable_seq
1
```

`tools/sched_ext/scx_show_state.py` is a drgn script which shows more detailed information:



```none
# tools/sched_ext/scx_show_state.py
ops           : simple
enabled       : 1
switching_all : 1
switched_all  : 1
enable_state  : enabled (2)
bypass_depth  : 0
nr_rejected   : 0
enable_seq    : 1
```

Whether a given task is on sched_ext can be determined as follows:



```none
# grep ext /proc/self/sched
ext.enabled                                  :                    1
```

<a id="rst-the-basics"></a>

## The Basics

Userspace can implement an arbitrary BPF scheduler by loading a set of BPF programs that implement `struct sched_ext_ops`. The only mandatory field is `ops.name` which must be a valid BPF object name. All operations are optional. The following modified excerpt is from `tools/sched_ext/scx_simple.bpf.c` showing a minimal global FIFO scheduler.



```c
/*
 * Decide which CPU a task should be migrated to before being
 * enqueued (either at wakeup, fork time, or exec time). If an
 * idle core is found by the default ops.select_cpu() implementation,
 * then insert the task directly into SCX_DSQ_LOCAL and skip the
 * ops.enqueue() callback.
 *
 * Note that this implementation has exactly the same behavior as the
 * default ops.select_cpu implementation. The behavior of the scheduler
 * would be exactly same if the implementation just didn't define the
 * simple_select_cpu() struct_ops prog.
 */
s32 BPF_STRUCT_OPS(simple_select_cpu, struct task_struct *p,
                   s32 prev_cpu, u64 wake_flags)
{
        s32 cpu;
        /* Need to initialize or the BPF verifier will reject the program */
        bool direct = false;

        cpu = scx_bpf_select_cpu_dfl(p, prev_cpu, wake_flags, &direct);

        if (direct)
                scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL, SCX_SLICE_DFL, 0);

        return cpu;
}

/*
 * Do a direct insertion of a task to the global DSQ. This ops.enqueue()
 * callback will only be invoked if we failed to find a core to insert
 * into in ops.select_cpu() above.
 *
 * Note that this implementation has exactly the same behavior as the
 * default ops.enqueue implementation, which just dispatches the task
 * to SCX_DSQ_GLOBAL. The behavior of the scheduler would be exactly same
 * if the implementation just didn't define the simple_enqueue struct_ops
 * prog.
 */
void BPF_STRUCT_OPS(simple_enqueue, struct task_struct *p, u64 enq_flags)
{
        scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
}

s32 BPF_STRUCT_OPS_SLEEPABLE(simple_init)
{
        /*
         * By default, all SCHED_EXT, SCHED_OTHER, SCHED_IDLE, and
         * SCHED_BATCH tasks should use sched_ext.
         */
        return 0;
}

void BPF_STRUCT_OPS(simple_exit, struct scx_exit_info *ei)
{
        exit_type = ei->type;
}

SEC(".struct_ops")
struct sched_ext_ops simple_ops = {
        .select_cpu             = (void *)simple_select_cpu,
        .enqueue                = (void *)simple_enqueue,
        .init                   = (void *)simple_init,
        .exit                   = (void *)simple_exit,
        .name                   = "simple",
};
```

<a id="rst-dispatch-queues"></a>

### Dispatch Queues

To match the impedance between the scheduler core and the BPF scheduler, sched_ext uses DSQs (dispatch queues) which can operate as both a FIFO and a priority queue. By default, there is one global FIFO (`SCX_DSQ_GLOBAL`), and one local DSQ per CPU (`SCX_DSQ_LOCAL`). The BPF scheduler can manage an arbitrary number of DSQs using `scx_bpf_create_dsq()` and `scx_bpf_destroy_dsq()`.

A CPU always executes a task from its local DSQ. A task is "inserted" into a DSQ. A task in a non-local DSQ is "move"d into the target CPU's local DSQ.

When a CPU is looking for the next task to run, if the local DSQ is not empty, the first task is picked. Otherwise, the CPU tries to move a task from the global DSQ. If that doesn't yield a runnable task either, `ops.dispatch()` is invoked.

<a id="rst-scheduling-cycle"></a>

### Scheduling Cycle

The following briefly shows how a waking task is scheduled and executed.

1. When a task is waking up, `ops.select_cpu()` is the first operation invoked. This serves two purposes. First, CPU selection optimization hint. Second, waking up the selected CPU if idle.

   The CPU selected by `ops.select_cpu()` is an optimization hint and not binding. The actual decision is made at the last step of scheduling. However, there is a small performance gain if the CPU `ops.select_cpu()` returns matches the CPU the task eventually runs on.

   A side-effect of selecting a CPU is waking it up from idle. While a BPF scheduler can wake up any cpu using the `scx_bpf_kick_cpu()` helper, using `ops.select_cpu()` judiciously can be simpler and more efficient.

   A task can be immediately inserted into a DSQ from `ops.select_cpu()` by calling `scx_bpf_dsq_insert()`. If the task is inserted into `SCX_DSQ_LOCAL` from `ops.select_cpu()`, it will be inserted into the local DSQ of whichever CPU is returned from `ops.select_cpu()`. Additionally, inserting directly from `ops.select_cpu()` will cause the `ops.enqueue()` callback to be skipped.

   Note that the scheduler core will ignore an invalid CPU selection, for example, if it's outside the allowed cpumask of the task.

2. Once the target CPU is selected, `ops.enqueue()` is invoked (unless the task was inserted directly from `ops.select_cpu()`). `ops.enqueue()` can make one of the following decisions:

   - Immediately insert the task into either the global or a local DSQ by calling `scx_bpf_dsq_insert()` with one of the following options: `SCX_DSQ_GLOBAL`, `SCX_DSQ_LOCAL`, or `SCX_DSQ_LOCAL_ON | cpu`.

   - Immediately insert the task into a custom DSQ by calling `scx_bpf_dsq_insert()` with a DSQ ID which is smaller than 2^63.

   - Queue the task on the BPF side.

3. When a CPU is ready to schedule, it first looks at its local DSQ. If empty, it then looks at the global DSQ. If there still isn't a task to run, `ops.dispatch()` is invoked which can use the following two functions to populate the local DSQ.

   - `scx_bpf_dsq_insert()` inserts a task to a DSQ. Any target DSQ can be used - `SCX_DSQ_LOCAL`, `SCX_DSQ_LOCAL_ON | cpu`, `SCX_DSQ_GLOBAL` or a custom DSQ. While `scx_bpf_dsq_insert()` currently can't be called with BPF locks held, this is being worked on and will be supported. `scx_bpf_dsq_insert()` schedules insertion rather than performing them immediately. There can be up to `ops.dispatch_max_batch` pending tasks.

   - `scx_bpf_move_to_local()` moves a task from the specified non-local DSQ to the dispatching DSQ. This function cannot be called with any BPF locks held. `scx_bpf_move_to_local()` flushes the pending insertions tasks before trying to move from the specified DSQ.

4. After `ops.dispatch()` returns, if there are tasks in the local DSQ, the CPU runs the first one. If empty, the following steps are taken:

   - Try to move from the global DSQ. If successful, run the task.

   - If `ops.dispatch()` has dispatched any tasks, retry \#3.

   - If the previous task is an SCX task and still runnable, keep executing it (see `SCX_OPS_ENQ_LAST`).

   - Go idle.

Note that the BPF scheduler can always choose to dispatch tasks immediately in `ops.enqueue()` as illustrated in the above simple example. If only the built-in DSQs are used, there is no need to implement `ops.dispatch()` as a task is never queued on the BPF scheduler and both the local and global DSQs are executed automatically.

`scx_bpf_dsq_insert()` inserts the task on the FIFO of the target DSQ. Use `scx_bpf_dsq_insert_vtime()` for the priority queue. Internal DSQs such as `SCX_DSQ_LOCAL` and `SCX_DSQ_GLOBAL` do not support priority-queue dispatching, and must be dispatched to with `scx_bpf_dsq_insert()`. See the function documentation and usage in `tools/sched_ext/scx_simple.bpf.c` for more information.

<a id="rst-task-lifecycle"></a>

### Task Lifecycle

The following pseudo-code summarizes the entire lifecycle of a task managed by a sched_ext scheduler:



```c
ops.init_task();            /* A new task is created */
ops.enable();               /* Enable BPF scheduling for the task */

while (task in SCHED_EXT) {
    if (task can migrate)
        ops.select_cpu();   /* Called on wakeup (optimization) */

    ops.runnable();         /* Task becomes ready to run */

    while (task is runnable) {
        if (task is not in a DSQ && task->scx.slice == 0) {
            ops.enqueue();  /* Task can be added to a DSQ */

            /* Any usable CPU becomes available */

            ops.dispatch(); /* Task is moved to a local DSQ */
        }
        ops.running();      /* Task starts running on its assigned CPU */

        while task_is_runnable(p) {
            while (task->scx.slice > 0 && task_is_runnable(p))
                ops.tick();     /* Called every 1/HZ seconds */

            ops.dispatch();     /* task->scx.slice can be refilled */
        }

        ops.stopping();     /* Task stops running (time slice expires or wait) */
    }

    ops.quiescent();        /* Task releases its assigned CPU (wait) */
}

ops.disable();              /* Disable BPF scheduling for the task */
ops.exit_task();            /* Task is destroyed */
```

<a id="rst-where-to-look"></a>

## Where to Look

- `include/linux/sched/ext.h` defines the core data structures, ops table and constants.

- `kernel/sched/ext.c` contains sched_ext core implementation and helpers. The functions prefixed with `scx_bpf_` can be called from the BPF scheduler.

- `kernel/sched/ext_idle.c` contains the built-in idle CPU selection policy.

- `tools/sched_ext/` hosts example BPF scheduler implementations.

  - `scx_simple[.bpf].c`: Minimal global FIFO scheduler example using a custom DSQ.

  - `scx_qmap[.bpf].c`: A multi-level FIFO scheduler supporting five levels of priority implemented with `BPF_MAP_TYPE_QUEUE`.

  - `scx_central[.bpf].c`: A central FIFO scheduler where all scheduling decisions are made on one CPU, demonstrating `LOCAL_ON` dispatching, tickless operation, and kthread preemption.

  - `scx_cpu0[.bpf].c`: A scheduler that queues all tasks to a shared DSQ and only dispatches them on CPU0 in FIFO order. Useful for testing bypass behavior.

  - `scx_flatcg[.bpf].c`: A flattened cgroup hierarchy scheduler implementing hierarchical weight-based cgroup CPU control by compounding each cgroup's share at every level into a single flat scheduling layer.

  - `scx_pair[.bpf].c`: A core-scheduling example that always makes sibling CPU pairs execute tasks from the same CPU cgroup.

  - `scx_sdt[.bpf].c`: A variation of `scx_simple` demonstrating BPF arena memory management for per-task data.

  - `scx_userland[.bpf].c`: A minimal scheduler demonstrating user space scheduling. Tasks with CPU affinity are direct-dispatched in FIFO order; all others are scheduled in user space by a simple vruntime scheduler.

<a id="rst-abi-instability"></a>

## ABI Instability

The APIs provided by sched_ext to BPF schedulers programs have no stability guarantees. This includes the ops table callbacks and constants defined in `include/linux/sched/ext.h`, as well as the `scx_bpf_` kfuncs defined in `kernel/sched/ext.c` and `kernel/sched/ext_idle.c`.

While we will attempt to provide a relatively stable API surface when possible, they are subject to change without warning between kernel versions.

---

# Scheduler Nice Design

_Peios Kernel / Internals / Scheduling_

> This document explains the thinking about the revamped and streamlined nice-levels implementation in the new Linux scheduler.

<a id="rst-scheduler-nice-design"></a>

This document explains the thinking about the revamped and streamlined nice-levels implementation in the new Linux scheduler.

Nice levels were always pretty weak under Linux and people continuously pestered us to make nice +19 tasks use up much less CPU time.

Unfortunately that was not that easy to implement under the old scheduler, (otherwise we'd have done it long ago) because nice level support was historically coupled to timeslice length, and timeslice units were driven by the HZ tick, so the smallest timeslice was 1/HZ.

In the O(1) scheduler (in 2003) we changed negative nice levels to be much stronger than they were before in 2.4 (and people were happy about that change), and we also intentionally calibrated the linear timeslice rule so that nice +19 level would be \_exactly\_ 1 jiffy. To better understand it, the timeslice graph went like this (cheesy ASCII art alert\!):



```text
                  A
            \     | [timeslice length]
             \    |
              \   |
               \  |
                \ |
                 \|___100msecs
                  |^ . _
                  |      ^ . _
                  |            ^ . _
-*----------------------------------*-----> [nice level]
-20               |                +19
                  |
                  |
```

So that if someone wanted to really renice tasks, +19 would give a much bigger hit than the normal linear rule would do. (The solution of changing the ABI to extend priorities was discarded early on.)

This approach worked to some degree for some time, but later on with HZ=1000 it caused 1 jiffy to be 1 msec, which meant 0.1% CPU usage which we felt to be a bit excessive. Excessive \_not\_ because it's too small of a CPU utilization, but because it causes too frequent (once per millisec) rescheduling. (and would thus trash the cache, etc. Remember, this was long ago when hardware was weaker and caches were smaller, and people were running number crunching apps at nice +19.)

So for HZ=1000 we changed nice +19 to 5msecs, because that felt like the right minimal granularity - and this translates to 5% CPU utilization. But the fundamental HZ-sensitive property for nice+19 still remained, and we never got a single complaint about nice +19 being too \_weak\_ in terms of CPU utilization, we only got complaints about it (still) being too \_strong\_ :-)

To sum it up: we always wanted to make nice levels more consistent, but within the constraints of HZ and jiffies and their nasty design level coupling to timeslices and granularity it was not really viable.

The second (less frequent but still periodically occurring) complaint about Linux's nice level support was its asymmetry around the origin (which you can see demonstrated in the picture above), or more accurately: the fact that nice level behavior depended on the \_absolute\_ nice level as well, while the nice API itself is fundamentally "relative":

> int nice(int inc);
>
> asmlinkage long sys_nice(int increment)

(the first one is the glibc API, the second one is the syscall API.) Note that the 'inc' is relative to the current nice level. Tools like bash's "nice" command mirror this relative API.

With the old scheduler, if you for example started a niced task with +1 and another task with +2, the CPU split between the two tasks would depend on the nice level of the parent shell - if it was at nice -10 the CPU split was different than if it was at +5 or +10.

A third complaint against Linux's nice level support was that negative nice levels were not 'punchy enough', so lots of people had to resort to run audio (and other multimedia) apps under RT priorities such as SCHED_FIFO. But this caused other problems: SCHED_FIFO is not starvation proof, and a buggy SCHED_FIFO app can also lock up the system for good.

The new scheduler in v2.6.23 addresses all three types of complaints:

To address the first complaint (of nice levels being not "punchy" enough), the scheduler was decoupled from 'time slice' and HZ concepts (and granularity was made a separate concept from nice levels) and thus it was possible to implement better and more consistent nice +19 support: with the new scheduler nice +19 tasks get a HZ-independent 1.5%, instead of the variable 3%-5%-9% range they got in the old scheduler.

To address the second complaint (of nice levels not being consistent), the new scheduler makes nice(1) have the same CPU utilization effect on tasks, regardless of their absolute nice levels. So on the new scheduler, running a nice +10 and a nice 11 task has the same CPU utilization "split" between them as running a nice -5 and a nice -4 task. (one will get 55% of the CPU, the other 45%.) That is why nice levels were changed to be "multiplicative" (or exponential) - that way it does not matter which nice level you start out from, the 'relative result' will always be the same.

The third complaint (of negative nice levels not being "punchy" enough and forcing audio apps to run under the more dangerous SCHED_FIFO scheduling policy) is addressed by the new scheduler almost automatically: stronger negative nice levels are an automatic side-effect of the recalibrated dynamic range of nice levels.

---

# Real-Time group scheduling

_Peios Kernel / Internals / Scheduling_

> Fiddling with these settings can result in an unstable system, the knobs are root only and assumes root knows what he is doing.

> **Peios:** References to Unix root and file modes below describe the inherited interface conventions. They are not sufficient Peios authorization: native descriptor/handle checks, the separate sysfs write gate, and mapped native privileges apply as appropriate. Debugfs additionally remains subject to integrity lockdown. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-real-time-group-scheduling"></a>

<!-- CONTENTS

0. WARNING
1. Overview
  1.1 The problem
  1.2 The solution
2. The interface
  2.1 System-wide settings
  2.2 Default behaviour
  2.3 Basis for grouping tasks
3. Future plans -->

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

## 0. WARNING

> Fiddling with these settings can result in an unstable system, the knobs are root only and assumes root knows what he is doing.

Most notable:

> - very small values in sched_rt_period_us can result in an unstable system when the period is smaller than either the available hrtimer resolution, or the time it takes to handle the budget refresh itself.
>
> - very small values in sched_rt_runtime_us can result in an unstable system when the runtime is so small the system has difficulty making forward progress (NOTE: the migration thread and kstopmachine both are real-time processes).

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

## 1. Overview

<a id="rst-the-problem"></a>

### 1.1 The problem

Real-time scheduling is all about determinism, a group has to be able to rely on the amount of bandwidth (eg. CPU time) being constant. In order to schedule multiple groups of real-time tasks, each group must be assigned a fixed portion of the CPU time available.  Without a minimum guarantee a real-time group can obviously fall short. A fuzzy upper limit is of no use since it cannot be relied upon. Which leaves us with just the single fixed portion.

<a id="rst-the-solution"></a>

### 1.2 The solution

CPU time is divided by means of specifying how much time can be spent running in a given period. We allocate this "run time" for each real-time group which the other real-time groups will not be permitted to use.

Any time not allocated to a real-time group will be used to run normal priority tasks (SCHED_OTHER). Any allocated run time not used will also be picked up by SCHED_OTHER.

Let's consider an example: a frame fixed real-time renderer must deliver 25 frames a second, which yields a period of 0.04s per frame. Now say it will also have to play some music and respond to input, leaving it with around 80% CPU time dedicated for the graphics. We can then give this group a run time of 0.8 \* 0.04s = 0.032s.

This way the graphics group will have a 0.04s period with a 0.032s run time limit. Now if the audio thread needs to refill the DMA buffer every 0.005s, but needs only about 3% CPU time to do so, it can do with a 0.03 \* 0.005s = 0.00015s. So this group can be scheduled with a period of 0.005s and a run time of 0.00015s.

The remaining CPU time will be used for user input and other tasks. Because real-time tasks have explicitly allocated the CPU time they need to perform their tasks, buffer underruns in the graphics or audio can be eliminated.

NOTE: the above example is not fully implemented yet. We still lack an EDF scheduler to make non-uniform periods usable.

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

## 2. The Interface

<a id="rst-system-wide-settings"></a>

### 2.1 System wide settings

The system wide settings are configured under the /proc virtual file system:

- **/proc/sys/kernel/sched_rt_period_us:**

  The scheduling period that is equivalent to 100% CPU bandwidth.

- **/proc/sys/kernel/sched_rt_runtime_us:**

  A global limit on how much time real-time scheduling may use. This is always less or equal to the period_us, as it denotes the time allocated from the period_us for the real-time tasks. Without CONFIG_RT_GROUP_SCHED enabled, this only serves for admission control of deadline tasks. With CONFIG_RT_GROUP_SCHED=y it also signifies the total bandwidth available to all real-time groups.

  - Time is specified in us because the interface is s32. This gives an operating range from 1us to about 35 minutes.

  - sched_rt_period_us takes values from 1 to INT_MAX.

  - sched_rt_runtime_us takes values from -1 to sched_rt_period_us.

  - A run time of -1 specifies runtime == period, ie. no limit.

  - sched_rt_runtime_us/sched_rt_period_us &gt; 0.05 inorder to preserve bandwidth for fair dl_server. For accurate value check average of runtime/period in /sys/kernel/debug/sched/fair_server/cpuX/

<a id="rst-default-behaviour"></a>

### 2.2 Default behaviour

The default values for sched_rt_period_us (1000000 or 1s) and sched_rt_runtime_us (950000 or 0.95s).  This gives 0.05s to be used by SCHED_OTHER (non-RT tasks). These defaults were chosen so that a run-away real-time tasks will not lock up the machine but leave a little time to recover it.  By setting runtime to -1 you'd get the old behaviour back.

By default all bandwidth is assigned to the root group and new groups get the period from /proc/sys/kernel/sched_rt_period_us and a run time of 0. If you want to assign bandwidth to another group, reduce the root group's bandwidth and assign some or all of the difference to another group.

Real-time group scheduling means you have to assign a portion of total CPU bandwidth to the group before it will accept real-time tasks. Therefore you will not be able to run real-time tasks as any user other than root until you have done that, even if the user has the rights to run processes with real-time priority\!

<a id="rst-basis-for-grouping-tasks"></a>

### 2.3 Basis for grouping tasks

Enabling CONFIG_RT_GROUP_SCHED lets you explicitly allocate real CPU bandwidth to task groups.

This uses the cgroup virtual file system and "&lt;cgroup&gt;/cpu.rt_runtime_us" to control the CPU time reserved for each control group.

For more information on working with control groups, you should read [Documentation/admin-guide/cgroup-v1/cgroups.rst](/kernel/administration/admin-guide/cgroup-v1/cgroups.md) as well.

Group settings are checked against the following limits in order to keep the configuration schedulable:

> Sum\_\{i\} runtime\_\{i\} / global_period &lt;= global_runtime / global_period

For now, this can be simplified to just the following (but see Future plans):

> Sum\_\{i\} runtime\_\{i\} &lt;= global_runtime

<a id="rst-future-plans"></a>

## 3. Future plans

There is work in progress to make the scheduling period for each group ("&lt;cgroup&gt;/cpu.rt_period_us") configurable as well.

The constraint on the period is that a subgroup must have a smaller or equal period to its parent. But realistically its not very useful \_yet\_ as its prone to starvation without deadline scheduling.

Consider two sibling groups A and B; both have 50% bandwidth, but A's period is twice the length of B's.

- group A: period=100000us, runtime=50000us

  > - this runs for 0.05s once every 0.1s

- group B: period= 50000us, runtime=25000us

  > - this runs for 0.025s twice every 0.1s (or once every 0.05 sec).

This means that currently a while (1) loop in A will run for the full period of B and can starve B's tasks (assuming they are of lower priority) for a whole period.

The next project will be SCHED_EDF (Earliest Deadline First scheduling) to bring full deadline scheduling to the linux kernel. Deadline scheduling the above groups and treating end of the period as a deadline will ensure that they both get their allocated time.

Implementing SCHED_EDF might take a while to complete. Priority Inheritance is the biggest challenge as the current linux PI infrastructure is geared towards the limited static priority levels 0-99. With deadline scheduling you need to do deadline inheritance (since priority is inversely proportional to the deadline delta (deadline - now)).

This means the whole PI machinery will have to be reworked - and that is one of the most complex pieces of code we have.

---

# Scheduler Statistics

_Peios Kernel / Internals / Scheduling_

> Version 17 of schedstats removed 'lb_imbalance' field as it has no significance anymore and instead added more relevant fields namely 'lb_imbalance_load', 'lb_imbalance_util', 'lb_imbalance_task' and 'lb_imbalance_misfit'. The domain field…

<a id="rst-scheduler-statistics"></a>

Version 17 of schedstats removed 'lb_imbalance' field as it has no significance anymore and instead added more relevant fields namely 'lb_imbalance_load', 'lb_imbalance_util', 'lb_imbalance_task' and 'lb_imbalance_misfit'. The domain field prints the name of the corresponding sched domain from this version onwards.

Version 16 of schedstats changed the order of definitions within 'enum cpu_idle_type', which changed the order of \[CPU_MAX_IDLE_TYPES\] columns in show_schedstat(). In particular the position of CPU_IDLE and \__CPU_NOT_IDLE changed places. The size of the array is unchanged.

Version 15 of schedstats dropped counters for some sched_yield: yld_exp_empty, yld_act_empty and yld_both_empty. Otherwise, it is identical to version 14. Details are available at

> [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/scheduler/sched-stats.txt?id=1e1dbb259c79b](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/scheduler/sched-stats.txt?id=1e1dbb259c79b>)

Version 14 of schedstats includes support for sched_domains, which hit the mainline kernel in 2.6.20 although it is identical to the stats from version 12 which was in the kernel from 2.6.13-2.6.19 (version 13 never saw a kernel release).  Some counters make more sense to be per-runqueue; other to be per-domain.  Note that domains (and their associated information) will only be pertinent and available on machines utilizing CONFIG_SMP.

In version 14 of schedstat, there is at least one level of domain statistics for each cpu listed, and there may well be more than one domain.  Domains have no particular names in this implementation, but the highest numbered one typically arbitrates balancing across all the cpus on the machine, while domain0 is the most tightly focused domain, sometimes balancing only between pairs of cpus.  At this time, there are no architectures which need more than three domain levels. The first field in the domain stats is a bit map indicating which cpus are affected by that domain. Details are available at

> [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/sched-stats.txt?id=b762f3ffb797c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/sched-stats.txt?id=b762f3ffb797c>)

The schedstat documentation is maintained version 10 onwards and is not updated for version 11 and 12. The details for version 10 are available at

> [https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/sched-stats.txt?id=1da177e4c3f4](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/sched-stats.txt?id=1da177e4c3f4>)

These fields are counters, and only increment.  Programs which make use of these will need to start with a baseline observation and then calculate the change in the counters at each subsequent observation.  A perl script which does this for many of the fields is available at

> [http://eaglet.pdxhosts.com/rick/linux/schedstat/](<http://eaglet.pdxhosts.com/rick/linux/schedstat/>)

Note that any such script will necessarily be version-specific, as the main reason to change versions is changes in the output format.  For those wishing to write their own scripts, the fields are described here.

<a id="rst-cpu-statistics"></a>

## CPU statistics

cpu&lt;N&gt; 1 2 3 4 5 6 7 8 9

First field is a sched_yield() statistic:

> 1. \# of times sched_yield() was called

Next three are schedule() statistics:

> 2. This field is a legacy array expiration count field used in the O(1) scheduler. We kept it for ABI compatibility, but it is always set to zero.
>
> 3. \# of times schedule() was called
>
> 4. \# of times schedule() left the processor idle

Next two are try_to_wake_up() statistics:

> 5. \# of times try_to_wake_up() was called
>
> 6. \# of times try_to_wake_up() was called to wake up the local cpu

Next three are statistics describing scheduling latency:

> 7. sum of all time spent running by tasks on this processor (in nanoseconds)
>
> 8. sum of all time spent waiting to run by tasks on this processor (in nanoseconds)
>
> 9. \# of timeslices run on this cpu

<a id="rst-domain-statistics"></a>

## Domain statistics

One of these is produced per domain for each cpu described. (Note that if CONFIG_SMP is not defined, *no* domains are utilized and these lines will not appear in the output.)

domain&lt;N&gt; &lt;name&gt; &lt;cpumask&gt; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

The &lt;name&gt; field prints the name of the sched domain and is only supported with schedstat version &gt;= 17. On previous versions, &lt;cpumask&gt; is the first field.

The &lt;cpumask&gt; field is a bit mask indicating what cpus this domain operates over.

The next 33 are a variety of sched_balance_rq() statistics in grouped into types of idleness (busy, idle and newly idle):

> > 1. \# of times in this domain sched_balance_rq() was called when the cpu was busy
> >
> > 2. \# of times in this domain sched_balance_rq() checked but found the load did not require balancing when busy
> >
> > 3. \# of times in this domain sched_balance_rq() tried to move one or more tasks and failed, when the cpu was busy
> >
> > 4. Total imbalance in load in this domain when the cpu was busy
> >
> > 5. Total imbalance in utilization in this domain when the cpu was busy
> >
> > 6. Total imbalance in number of tasks in this domain when the cpu was busy
> >
> > 7. Total imbalance due to misfit tasks in this domain when the cpu was busy
> >
> > 8. \# of times in this domain detach_task() was called when busy
> >
> > 9. \# of times in this domain detach_task() was called even though the target task was cache-hot when busy
> >
> > 10. \# of times in this domain sched_balance_rq() was called but did not find a busier queue while the cpu was busy
> >
> > 11. \# of times in this domain a busier queue was found while the cpu was busy but no busier group was found
> >
> > 12. \# of times in this domain sched_balance_rq() was called when the cpu was idle
> >
> > 13. \# of times in this domain sched_balance_rq() checked but found the load did not require balancing when the cpu was idle
> >
> > 14. \# of times in this domain sched_balance_rq() tried to move one or more tasks and failed, when the cpu was idle
> >
> > 15. Total imbalance in load in this domain when the cpu was idle
> >
> > 16. Total imbalance in utilization in this domain when the cpu was idle
> >
> > 17. Total imbalance in number of tasks in this domain when the cpu was idle
> >
> > 18. Total imbalance due to misfit tasks in this domain when the cpu was idle
> >
> > 19. \# of times in this domain detach_task() was called when the cpu was idle
> >
> > 20. \# of times in this domain detach_task() was called even though the target task was cache-hot when idle
> >
> > 21. \# of times in this domain sched_balance_rq() was called but did not find a busier queue while the cpu was idle
> >
> > 22. \# of times in this domain a busier queue was found while the cpu was idle but no busier group was found
> >
> > 23. \# of times in this domain sched_balance_rq() was called when the cpu was just becoming idle
> >
> > 24. \# of times in this domain sched_balance_rq() checked but found the load did not require balancing when the cpu was just becoming idle
> >
> > 25. \# of times in this domain sched_balance_rq() tried to move one or more tasks and failed, when the cpu was just becoming idle
> >
> > 26. Total imbalance in load in this domain when the cpu was just becoming idle
> >
> > 27. Total imbalance in utilization in this domain when the cpu was just becoming idle
> >
> > 28. Total imbalance in number of tasks in this domain when the cpu was just becoming idle
> >
> > 29. Total imbalance due to misfit tasks in this domain when the cpu was just becoming idle
> >
> > 30. \# of times in this domain detach_task() was called when newly idle
> >
> > 31. \# of times in this domain detach_task() was called even though the target task was cache-hot when just becoming idle
> >
> > 32. \# of times in this domain sched_balance_rq() was called but did not find a busier queue while the cpu was just becoming idle
> >
> > 33. \# of times in this domain a busier queue was found while the cpu was just becoming idle but no busier group was found
>
> Next three are active_load_balance() statistics:
>
> > 34. \# of times active_load_balance() was called
> >
> > 35. \# of times active_load_balance() tried to move a task and failed
> >
> > 36. \# of times active_load_balance() successfully moved a task
>
> Next three are sched_balance_exec() statistics:
>
> > 37. sbe_cnt is not used
> >
> > 38. sbe_balanced is not used
> >
> > 39. sbe_pushed is not used
>
> Next three are sched_balance_fork() statistics:
>
> > 40. sbf_cnt is not used
> >
> > 41. sbf_balanced is not used
> >
> > 42. sbf_pushed is not used
>
> Next three are try_to_wake_up() statistics:
>
> > 43. \# of times in this domain try_to_wake_up() awoke a task that last ran on a different cpu in this domain
> >
> > 44. \# of times in this domain try_to_wake_up() moved a task to the waking cpu because it was cache-cold on its own cpu anyway
> >
> > 45. \# of times in this domain try_to_wake_up() started passive balancing

<a id="rst-proc-pid-schedstat"></a>

## /proc/&lt;pid&gt;/schedstat

schedstats also adds a new /proc/&lt;pid&gt;/schedstat file to include some of the same information on a per-process level.  There are three fields in this file correlating for that process to:

> 1. time spent on the cpu (in nanoseconds)
>
> 2. time spent waiting on a runqueue (in nanoseconds)
>
> 3. \# of timeslices run on this cpu

A program could be easily written to make use of these extra fields to report on how well a particular process or set of processes is faring under the scheduler's policies.  A simple version of such a program is available at

> [http://eaglet.pdxhosts.com/rick/linux/schedstat/v12/latency.c](<http://eaglet.pdxhosts.com/rick/linux/schedstat/v12/latency.c>)

---

# Utilization Clamping

_Peios Kernel / Internals / Scheduling_

> Utilization clamping, also known as util clamp or uclamp, is a scheduler feature that allows user space to help in managing the performance requirement of tasks. It was introduced in v5.3 release. The CGroup support was merged in v5.4.

<a id="rst-utilization-clamping"></a>

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

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

## 1. Introduction

Utilization clamping, also known as util clamp or uclamp, is a scheduler feature that allows user space to help in managing the performance requirement of tasks. It was introduced in v5.3 release. The CGroup support was merged in v5.4.

Uclamp is a hinting mechanism that allows the scheduler to understand the performance requirements and restrictions of the tasks, thus it helps the scheduler to make a better decision. And when schedutil cpufreq governor is used, util clamp will influence the CPU frequency selection as well.

Since the scheduler and schedutil are both driven by PELT (util_avg) signals, util clamp acts on that to achieve its goal by clamping the signal to a certain point; hence the name. That is, by clamping utilization we are making the system run at a certain performance point.

The right way to view util clamp is as a mechanism to make request or hint on performance constraints. It consists of two tunables:

> - UCLAMP_MIN, which sets the lower bound.
>
> - UCLAMP_MAX, which sets the upper bound.

These two bounds will ensure a task will operate within this performance range of the system. UCLAMP_MIN implies boosting a task, while UCLAMP_MAX implies capping a task.

One can tell the system (scheduler) that some tasks require a minimum performance point to operate at to deliver the desired user experience. Or one can tell the system that some tasks should be restricted from consuming too much resources and should not go above a specific performance point. Viewing the uclamp values as performance points rather than utilization is a better abstraction from user space point of view.

As an example, a game can use util clamp to form a feedback loop with its perceived Frames Per Second (FPS). It can dynamically increase the minimum performance point required by its display pipeline to ensure no frame is dropped. It can also dynamically 'prime' up these tasks if it knows in the coming few hundred milliseconds a computationally intensive scene is about to happen.

On mobile hardware where the capability of the devices varies a lot, this dynamic feedback loop offers a great flexibility to ensure best user experience given the capabilities of any system.

Of course a static configuration is possible too. The exact usage will depend on the system, application and the desired outcome.

Another example is in Android where tasks are classified as background, foreground, top-app, etc. Util clamp can be used to constrain how much resources background tasks are consuming by capping the performance point they can run at. This constraint helps reserve resources for important tasks, like the ones belonging to the currently active app (top-app group). Beside this helps in limiting how much power they consume. This can be more obvious in heterogeneous systems (e.g. Arm big.LITTLE); the constraint will help bias the background tasks to stay on the little cores which will ensure that:

> 1. The big cores are free to run top-app tasks immediately. top-app tasks are the tasks the user is currently interacting with, hence the most important tasks in the system.
>
> 2. They don't run on a power hungry core and drain battery even if they are CPU intensive tasks.

> [!NOTE]
>
> - ****little cores**:**
>
>   CPUs with capacity &lt; 1024
>
> - ****big cores**:**
>
>   CPUs with capacity = 1024

By making these uclamp performance requests, or rather hints, user space can ensure system resources are used optimally to deliver the best possible user experience.

Another use case is to help with **overcoming the ramp up latency inherit in how scheduler utilization signal is calculated**.

On the other hand, a busy task for instance that requires to run at maximum performance point will suffer a delay of \~200ms (PELT HALFIFE = 32ms) for the scheduler to realize that. This is known to affect workloads like gaming on mobile devices where frames will drop due to slow response time to select the higher frequency required for the tasks to finish their work in time. Setting UCLAMP_MIN=1024 will ensure such tasks will always see the highest performance level when they start running.

The overall visible effect goes beyond better perceived user experience/performance and stretches to help achieve a better overall performance/watt if used effectively.

User space can form a feedback loop with the thermal subsystem too to ensure the device doesn't heat up to the point where it will throttle.

Both SCHED_NORMAL/OTHER and SCHED_FIFO/RR honour uclamp requests/hints.

In the SCHED_FIFO/RR case, uclamp gives the option to run RT tasks at any performance point rather than being tied to MAX frequency all the time. Which can be useful on general purpose systems that run on battery powered devices.

Note that by design RT tasks don't have per-task PELT signal and must always run at a constant frequency to combat undeterministic DVFS rampup delays.

Note that using schedutil always implies a single delay to modify the frequency when an RT task wakes up. This cost is unchanged by using uclamp. Uclamp only helps picking what frequency to request instead of schedutil always requesting MAX for all RT tasks.

See [section 3.4](<#rst-uclamp-default-values>) for default values and [3.4.1](<#rst-sched-util-clamp-min-rt-default>) on how to change RT tasks default value.

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

## 2. Design

Util clamp is a property of every task in the system. It sets the boundaries of its utilization signal; acting as a bias mechanism that influences certain decisions within the scheduler.

The actual utilization signal of a task is never clamped in reality. If you inspect PELT signals at any point of time you should continue to see them as they are intact. Clamping happens only when needed, e.g: when a task wakes up and the scheduler needs to select a suitable CPU for it to run on.

Since the goal of util clamp is to allow requesting a minimum and maximum performance point for a task to run on, it must be able to influence the frequency selection as well as task placement to be most effective. Both of which have implications on the utilization value at CPU runqueue (rq for short) level, which brings us to the main design challenge.

When a task wakes up on an rq, the utilization signal of the rq will be affected by the uclamp settings of all the tasks enqueued on it. For example if a task requests to run at UTIL_MIN = 512, then the util signal of the rq needs to respect to this request as well as all other requests from all of the enqueued tasks.

To be able to aggregate the util clamp value of all the tasks attached to the rq, uclamp must do some housekeeping at every enqueue/dequeue, which is the scheduler hot path. Hence care must be taken since any slow down will have significant impact on a lot of use cases and could hinder its usability in practice.

The way this is handled is by dividing the utilization range into buckets (struct uclamp_bucket) which allows us to reduce the search space from every task on the rq to only a subset of tasks on the top-most bucket.

When a task is enqueued, the counter in the matching bucket is incremented, and on dequeue it is decremented. This makes keeping track of the effective uclamp value at rq level a lot easier.

As tasks are enqueued and dequeued, we keep track of the current effective uclamp value of the rq. See [section 2.1](<#rst-uclamp-buckets>) for details on how this works.

Later at any path that wants to identify the effective uclamp value of the rq, it will simply need to read this effective uclamp value of the rq at that exact moment of time it needs to take a decision.

For task placement case, only Energy Aware and Capacity Aware Scheduling (EAS/CAS) make use of uclamp for now, which implies that it is applied on heterogeneous systems only. When a task wakes up, the scheduler will look at the current effective uclamp value of every rq and compare it with the potential new value if the task were to be enqueued there. Favoring the rq that will end up with the most energy efficient combination.

Similarly in schedutil, when it needs to make a frequency update it will look at the current effective uclamp value of the rq which is influenced by the set of tasks currently enqueued there and select the appropriate frequency that will satisfy constraints from requests.

Other paths like setting overutilization state (which effectively disables EAS) make use of uclamp as well. Such cases are considered necessary housekeeping to allow the 2 main use cases above and will not be covered in detail here as they could change with implementation details.

<a id="rst-buckets"></a>
<a id="rst-uclamp-buckets"></a>

### 2.1. Buckets



```text
                         [struct rq]

(bottom)                                                    (top)

  0                                                          1024
  |                                                           |
  +-----------+-----------+-----------+----   ----+-----------+
  |  Bucket 0 |  Bucket 1 |  Bucket 2 |    ...    |  Bucket N |
  +-----------+-----------+-----------+----   ----+-----------+
     :           :                                   :
     +- p0       +- p3                               +- p4
     :                                               :
     +- p1                                           +- p5
     :
     +- p2
```

> [!NOTE]
>
> The diagram above is an illustration rather than a true depiction of the internal data structure.

To reduce the search space when trying to decide the effective uclamp value of an rq as tasks are enqueued/dequeued, the whole utilization range is divided into N buckets where N is configured at compile time by setting CONFIG_UCLAMP_BUCKETS_COUNT. By default it is set to 5.

The rq has a bucket for each uclamp_id tunables: \[UCLAMP_MIN, UCLAMP_MAX\].

The range of each bucket is 1024/N. For example, for the default value of 5 there will be 5 buckets, each of which will cover the following range:



```text
DELTA = round_closest(1024/5) = 204.8 = 205

Bucket 0: [0:204]
Bucket 1: [205:409]
Bucket 2: [410:614]
Bucket 3: [615:819]
Bucket 4: [820:1024]
```

When a task p with following tunable parameters



```text
p->uclamp[UCLAMP_MIN] = 300
p->uclamp[UCLAMP_MAX] = 1024
```

is enqueued into the rq, bucket 1 will be incremented for UCLAMP_MIN and bucket 4 will be incremented for UCLAMP_MAX to reflect the fact the rq has a task in this range.

The rq then keeps track of its current effective uclamp value for each uclamp_id.

When a task p is enqueued, the rq value changes to:



```text
// update bucket logic goes here
rq->uclamp[UCLAMP_MIN] = max(rq->uclamp[UCLAMP_MIN], p->uclamp[UCLAMP_MIN])
// repeat for UCLAMP_MAX
```

Similarly, when p is dequeued the rq value changes to:



```text
// update bucket logic goes here
rq->uclamp[UCLAMP_MIN] = search_top_bucket_for_highest_value()
// repeat for UCLAMP_MAX
```

When all buckets are empty, the rq uclamp values are reset to system defaults. See [section 3.4](<#rst-uclamp-default-values>) for details on default values.

<a id="rst-max-aggregation"></a>

### 2.2. Max aggregation

Util clamp is tuned to honour the request for the task that requires the highest performance point.

When multiple tasks are attached to the same rq, then util clamp must make sure the task that needs the highest performance point gets it even if there's another task that doesn't need it or is disallowed from reaching this point.

For example, if there are multiple tasks attached to an rq with the following values:



```text
p0->uclamp[UCLAMP_MIN] = 300
p0->uclamp[UCLAMP_MAX] = 900

p1->uclamp[UCLAMP_MIN] = 500
p1->uclamp[UCLAMP_MAX] = 500
```

then assuming both p0 and p1 are enqueued to the same rq, both UCLAMP_MIN and UCLAMP_MAX become:



```text
rq->uclamp[UCLAMP_MIN] = max(300, 500) = 500
rq->uclamp[UCLAMP_MAX] = max(900, 500) = 900
```

As we shall see in [section 5.1](<#rst-uclamp-capping-fail>), this max aggregation is the cause of one of limitations when using util clamp, in particular for UCLAMP_MAX hint when user space would like to save power.

<a id="rst-hierarchical-aggregation"></a>

### 2.3. Hierarchical aggregation

As stated earlier, util clamp is a property of every task in the system. But the actual applied (effective) value can be influenced by more than just the request made by the task or another actor on its behalf (middleware library).

The effective util clamp value of any task is restricted as follows:

> 1. By the uclamp settings defined by the cgroup CPU controller it is attached to, if any.
>
> 2. The restricted value in (1) is then further restricted by the system wide uclamp settings.

[Section 3](<#rst-uclamp-interfaces>) discusses the interfaces and will expand further on that.

For now suffice to say that if a task makes a request, its actual effective value will have to adhere to some restrictions imposed by cgroup and system wide settings.

The system will still accept the request even if effectively will be beyond the constraints, but as soon as the task moves to a different cgroup or a sysadmin modifies the system settings, the request will be satisfied only if it is within new constraints.

In other words, this aggregation will not cause an error when a task changes its uclamp values, but rather the system may not be able to satisfy requests based on those factors.

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

### 2.4. Range

Uclamp performance request has the range of 0 to 1024 inclusive.

For cgroup interface percentage is used (that is 0 to 100 inclusive). Just like other cgroup interfaces, you can use 'max' instead of 100.

<a id="rst-interfaces"></a>
<a id="rst-uclamp-interfaces"></a>

## 3. Interfaces

<a id="rst-per-task-interface"></a>

### 3.1. Per task interface

sched_setattr() syscall was extended to accept two new fields:

- sched_util_min: requests the minimum performance point the system should run at when this task is running. Or lower performance bound.

- sched_util_max: requests the maximum performance point the system should run at when this task is running. Or upper performance bound.

For example, the following scenario have 40% to 80% utilization constraints:



```text
attr->sched_util_min = 40% * 1024;
attr->sched_util_max = 80% * 1024;
```

When task @p is running, **the scheduler should try its best to ensure it starts at 40% performance level**. If the task runs for a long enough time so that its actual utilization goes above 80%, the utilization, or performance level, will be capped.

The special value -1 is used to reset the uclamp settings to the system default.

Note that resetting the uclamp value to system default using -1 is not the same as manually setting uclamp value to system default. This distinction is important because as we shall see in system interfaces, the default value for RT could be changed. SCHED_NORMAL/OTHER might gain similar knobs too in the future.

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

### 3.2. cgroup interface

There are two uclamp related values in the CPU cgroup controller:

- cpu.uclamp.min

- cpu.uclamp.max

When a task is attached to a CPU controller, its uclamp values will be impacted as follows:

- cpu.uclamp.min is a protection as described in [section 3-3 of cgroup v2 documentation](</kernel/administration/admin-guide/resources/cgroup-v2.md#rst-cgroupv2-protections-distributor>).

  If a task uclamp_min value is lower than cpu.uclamp.min, then the task will inherit the cgroup cpu.uclamp.min value.

  In a cgroup hierarchy, effective cpu.uclamp.min is the max of (child, parent).

- cpu.uclamp.max is a limit as described in [section 3-2 of cgroup v2 documentation](</kernel/administration/admin-guide/resources/cgroup-v2.md#rst-cgroupv2-limits-distributor>).

  If a task uclamp_max value is higher than cpu.uclamp.max, then the task will inherit the cgroup cpu.uclamp.max value.

  In a cgroup hierarchy, effective cpu.uclamp.max is the min of (child, parent).

For example, given following parameters:



```text
p0->uclamp[UCLAMP_MIN] = // system default;
p0->uclamp[UCLAMP_MAX] = // system default;

p1->uclamp[UCLAMP_MIN] = 40% * 1024;
p1->uclamp[UCLAMP_MAX] = 50% * 1024;

cgroup0->cpu.uclamp.min = 20% * 1024;
cgroup0->cpu.uclamp.max = 60% * 1024;

cgroup1->cpu.uclamp.min = 60% * 1024;
cgroup1->cpu.uclamp.max = 100% * 1024;
```

when p0 and p1 are attached to cgroup0, the values become:



```text
p0->uclamp[UCLAMP_MIN] = cgroup0->cpu.uclamp.min = 20% * 1024;
p0->uclamp[UCLAMP_MAX] = cgroup0->cpu.uclamp.max = 60% * 1024;

p1->uclamp[UCLAMP_MIN] = 40% * 1024; // intact
p1->uclamp[UCLAMP_MAX] = 50% * 1024; // intact
```

when p0 and p1 are attached to cgroup1, these instead become:



```text
p0->uclamp[UCLAMP_MIN] = cgroup1->cpu.uclamp.min = 60% * 1024;
p0->uclamp[UCLAMP_MAX] = cgroup1->cpu.uclamp.max = 100% * 1024;

p1->uclamp[UCLAMP_MIN] = cgroup1->cpu.uclamp.min = 60% * 1024;
p1->uclamp[UCLAMP_MAX] = 50% * 1024; // intact
```

Note that cgroup interfaces allows cpu.uclamp.max value to be lower than cpu.uclamp.min. Other interfaces don't allow that.

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

### 3.3. System interface

<a id="rst-sched-util-clamp-min"></a>

### 3.3.1 sched_util_clamp_min

System wide limit of allowed UCLAMP_MIN range. By default it is set to 1024, which means that permitted effective UCLAMP_MIN range for tasks is \[0:1024\]. By changing it to 512 for example the range reduces to \[0:512\]. This is useful to restrict how much boosting tasks are allowed to acquire.

Requests from tasks to go above this knob value will still succeed, but they won't be satisfied until it is more than p-&gt;uclamp\[UCLAMP_MIN\].

The value must be smaller than or equal to sched_util_clamp_max.

<a id="rst-sched-util-clamp-max"></a>

### 3.3.2 sched_util_clamp_max

System wide limit of allowed UCLAMP_MAX range. By default it is set to 1024, which means that permitted effective UCLAMP_MAX range for tasks is \[0:1024\].

By changing it to 512 for example the effective allowed range reduces to \[0:512\]. This means is that no task can run above 512, which implies that all rqs are restricted too. IOW, the whole system is capped to half its performance capacity.

This is useful to restrict the overall maximum performance point of the system. For example, it can be handy to limit performance when running low on battery or when the system wants to limit access to more energy hungry performance levels when it's in idle state or screen is off.

Requests from tasks to go above this knob value will still succeed, but they won't be satisfied until it is more than p-&gt;uclamp\[UCLAMP_MAX\].

The value must be greater than or equal to sched_util_clamp_min.

<a id="rst-default-values"></a>
<a id="rst-uclamp-default-values"></a>

### 3.4. Default values

By default all SCHED_NORMAL/SCHED_OTHER tasks are initialized to:



```text
p_fair->uclamp[UCLAMP_MIN] = 0
p_fair->uclamp[UCLAMP_MAX] = 1024
```

That is, by default they're boosted to run at the maximum performance point of changed at boot or runtime. No argument was made yet as to why we should provide this, but can be added in the future.

For SCHED_FIFO/SCHED_RR tasks:



```text
p_rt->uclamp[UCLAMP_MIN] = 1024
p_rt->uclamp[UCLAMP_MAX] = 1024
```

That is by default they're boosted to run at the maximum performance point of the system which retains the historical behavior of the RT tasks.

RT tasks default uclamp_min value can be modified at boot or runtime via sysctl. See below section.

<a id="rst-sched-util-clamp-min-rt-default-1"></a>
<a id="rst-sched-util-clamp-min-rt-default"></a>

### 3.4.1 sched_util_clamp_min_rt_default

Running RT tasks at maximum performance point is expensive on battery powered devices and not necessary. To allow system developer to offer good performance guarantees for these tasks without pushing it all the way to maximum performance point, this sysctl knob allows tuning the best boost value to address the system requirement without burning power running at maximum performance point all the time.

Application developer are encouraged to use the per task util clamp interface to ensure they are performance and power aware. Ideally this knob should be set to 0 by system designers and leave the task of managing performance requirements to the apps.

<a id="rst-how-to-use-util-clamp"></a>

## 4. How to use util clamp

Util clamp promotes the concept of user space assisted power and performance management. At the scheduler level there is no info required to make the best decision. However, with util clamp user space can hint to the scheduler to make better decision about task placement and frequency selection.

Best results are achieved by not making any assumptions about the system the application is running on and to use it in conjunction with a feedback loop to dynamically monitor and adjust. Ultimately this will allow for a better user experience at a better perf/watt.

For some systems and use cases, static setup will help to achieve good results. Portability will be a problem in this case. How much work one can do at 100, 200 or 1024 is different for each system. Unless there's a specific target system, static setup should be avoided.

There are enough possibilities to create a whole framework based on util clamp or self contained app that makes use of it directly.

<a id="rst-boost-important-and-dvfs-latency-sensitive-tasks"></a>

### 4.1. Boost important and DVFS-latency-sensitive tasks

A GUI task might not be busy to warrant driving the frequency high when it wakes up. However, it requires to finish its work within a specific time window to deliver the desired user experience. The right frequency it requires at wakeup will be system dependent. On some underpowered systems it will be high, on other overpowered ones it will be low or 0.

This task can increase its UCLAMP_MIN value every time it misses the deadline to ensure on next wake up it runs at a higher performance point. It should try to approach the lowest UCLAMP_MIN value that allows to meet its deadline on any particular system to achieve the best possible perf/watt for that system.

On heterogeneous systems, it might be important for this task to run on a faster CPU.

**Generally it is advised to perceive the input as performance level or point which will imply both task placement and frequency selection**.

<a id="rst-cap-background-tasks"></a>

### 4.2. Cap background tasks

Like explained for Android case in the introduction. Any app can lower UCLAMP_MAX for some background tasks that don't care about performance but could end up being busy and consume unnecessary system resources on the system.

<a id="rst-powersave-mode"></a>

### 4.3. Powersave mode

sched_util_clamp_max system wide interface can be used to limit all tasks from operating at the higher performance points which are usually energy inefficient.

This is not unique to uclamp as one can achieve the same by reducing max frequency of the cpufreq governor. It can be considered a more convenient alternative interface.

<a id="rst-per-app-performance-restriction"></a>

### 4.4. Per-app performance restriction

Middleware/Utility can provide the user an option to set UCLAMP_MIN/MAX for an app every time it is executed to guarantee a minimum performance point and/or limit it from draining system power at the cost of reduced performance for these apps.

If you want to prevent your laptop from heating up while on the go from compiling the kernel and happy to sacrifice performance to save power, but still would like to keep your browser performance intact, uclamp makes it possible.

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

## 5. Limitations

<a id="rst-capping-frequency-with-uclamp-max-fails-under-certain-conditions"></a>
<a id="rst-uclamp-capping-fail"></a>

### 5.1. Capping frequency with uclamp_max fails under certain conditions

If task p0 is capped to run at 512:



```text
p0->uclamp[UCLAMP_MAX] = 512
```

and it shares the rq with p1 which is free to run at any performance point:



```text
p1->uclamp[UCLAMP_MAX] = 1024
```

then due to max aggregation the rq will be allowed to reach max performance point:



```text
rq->uclamp[UCLAMP_MAX] = max(512, 1024) = 1024
```

Assuming both p0 and p1 have UCLAMP_MIN = 0, then the frequency selection for the rq will depend on the actual utilization value of the tasks.

If p1 is a small task but p0 is a CPU intensive task, then due to the fact that both are running at the same rq, p1 will cause the frequency capping to be left from the rq although p1, which is allowed to run at any performance point, doesn't actually need to run at that frequency.

<a id="rst-uclamp-max-can-break-pelt-util-avg-signal"></a>

### 5.2. UCLAMP_MAX can break PELT (util_avg) signal

PELT assumes that frequency will always increase as the signals grow to ensure there's always some idle time on the CPU. But with UCLAMP_MAX, this frequency increase will be prevented which can lead to no idle time in some circumstances. When there's no idle time, a task will stuck in a busy loop, which would result in util_avg being 1024.

Combing with issue described below, this can lead to unwanted frequency spikes when severely capped tasks share the rq with a small non capped task.

As an example if task p, which have:



```text
p0->util_avg = 300
p0->uclamp[UCLAMP_MAX] = 0
```

wakes up on an idle CPU, then it will run at min frequency (Fmin) this CPU is capable of. The max CPU frequency (Fmax) matters here as well, since it designates the shortest computational time to finish the task's work on this CPU.



```text
rq->uclamp[UCLAMP_MAX] = 0
```

If the ratio of Fmax/Fmin is 3, then maximum value will be:



```text
300 * (Fmax/Fmin) = 900
```

which indicates the CPU will still see idle time since 900 is &lt; 1024. The \_actual\_ util_avg will not be 900 though, but somewhere between 300 and 900. As long as there's idle time, p-&gt;util_avg updates will be off by a some margin, but not proportional to Fmax/Fmin.



```text
p0->util_avg = 300 + small_error
```

Now if the ratio of Fmax/Fmin is 4, the maximum value becomes:



```text
300 * (Fmax/Fmin) = 1200
```

which is higher than 1024 and indicates that the CPU has no idle time. When this happens, then the \_actual\_ util_avg will become:



```text
p0->util_avg = 1024
```

If task p1 wakes up on this CPU, which have:



```text
p1->util_avg = 200
p1->uclamp[UCLAMP_MAX] = 1024
```

then the effective UCLAMP_MAX for the CPU will be 1024 according to max aggregation rule. But since the capped p0 task was running and throttled severely, then the rq-&gt;util_avg will be:



```text
p0->util_avg = 1024
p1->util_avg = 200

rq->util_avg = 1024
rq->uclamp[UCLAMP_MAX] = 1024
```

Hence lead to a frequency spike since if p0 wasn't throttled we should get:



```text
p0->util_avg = 300
p1->util_avg = 200

rq->util_avg = 500
```

and run somewhere near mid performance point of that CPU, not the Fmax we get.

<a id="rst-schedutil-response-time-issues"></a>

### 5.3. Schedutil response time issues

schedutil has three limitations:

> 1. Hardware takes non-zero time to respond to any frequency change request. On some platforms can be in the order of few ms.
>
> 2. Non fast-switch systems require a worker deadline thread to wake up and perform the frequency change, which adds measurable overhead.
>
> 3. schedutil rate_limit_us drops any requests during this rate_limit_us window.

If a relatively small task is doing critical job and requires a certain performance point when it wakes up and starts running, then all these limitations will prevent it from getting what it wants in the time scale it expects.

This limitation is not only impactful when using uclamp, but will be more prevalent as we no longer gradually ramp up or down. We could easily be jumping between frequencies depending on the order tasks wake up, and their respective uclamp values.

We regard that as a limitation of the capabilities of the underlying system itself.

There is room to improve the behavior of schedutil rate_limit_us, but not much to be done for 1 or 2. They are considered hard limitations of the system.

---

# Schedutil

_Peios Kernel / Internals / Scheduling_

> With PELT we track some metrics across the various scheduler entities, from individual tasks to task-group slices to CPU runqueues. As the basis for this we use an Exponentially Weighted Moving Average (EWMA), each period (1024us) is…

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

> [!NOTE]
>
> All this assumes a linear relation between frequency and work capacity, we know this is flawed, but it is the best workable approximation.

<a id="rst-pelt-per-entity-load-tracking"></a>

## PELT (Per Entity Load Tracking)

With PELT we track some metrics across the various scheduler entities, from individual tasks to task-group slices to CPU runqueues. As the basis for this we use an Exponentially Weighted Moving Average (EWMA), each period (1024us) is decayed such that y^32 = 0.5. That is, the most recent 32ms contribute half, while the rest of history contribute the other half.

Specifically:

> ewma_sum(u) := u_0 + u_1\*y + u_2\*y^2 + ...
>
> ewma(u) = ewma_sum(u) / ewma_sum(1)

Since this is essentially a progression of an infinite geometric series, the results are composable, that is ewma(A) + ewma(B) = ewma(A+B). This property is key, since it gives the ability to recompose the averages when tasks move around.

Note that blocked tasks still contribute to the aggregates (task-group slices and CPU runqueues), which reflects their expected contribution when they resume running.

Using this we track 2 key metrics: 'running' and 'runnable'. 'Running' reflects the time an entity spends on the CPU, while 'runnable' reflects the time an entity spends on the runqueue. When there is only a single task these two metrics are the same, but once there is contention for the CPU 'running' will decrease to reflect the fraction of time each task spends on the CPU while 'runnable' will increase to reflect the amount of contention.

For more detail see: kernel/sched/pelt.c

<a id="rst-frequency-cpu-invariance"></a>

## Frequency / CPU Invariance

Because consuming the CPU for 50% at 1GHz is not the same as consuming the CPU for 50% at 2GHz, nor is running 50% on a LITTLE CPU the same as running 50% on a big CPU, we allow architectures to scale the time delta with two ratios, one Dynamic Voltage and Frequency Scaling (DVFS) ratio and one microarch ratio.

For simple DVFS architectures (where software is in full control) we trivially compute the ratio as:



```text
          f_cur
r_dvfs := -----
          f_max
```

For more dynamic systems where the hardware is in control of DVFS we use hardware counters (Intel APERF/MPERF, ARMv8.4-AMU) to provide us this ratio. For Intel specifically, we use:



```text
         APERF
f_cur := ----- * P0
         MPERF

           4C-turbo;  if available and turbo enabled
f_max := { 1C-turbo;  if turbo enabled
           P0;        otherwise

                  f_cur
r_dvfs := min( 1, ----- )
                  f_max
```

We pick 4C turbo over 1C turbo to make it slightly more sustainable.

r_cpu is determined as the ratio of highest performance level of the current CPU vs the highest performance level of any other CPU in the system.

> r_tot = r_dvfs \* r_cpu

The result is that the above 'running' and 'runnable' metrics become invariant of DVFS and CPU type. IOW. we can transfer and compare them between CPUs.

For more detail see:

> - kernel/sched/pelt.h:update_rq_clock_pelt()
>
> - arch/x86/kernel/smpboot.c:"APERF/MPERF frequency ratio computation."
>
> - [Documentation/scheduler/sched-capacity.rst](/kernel/internals/scheduler/sched-capacity.md):"1. CPU Capacity + 2. Task utilization"

<a id="rst-util-est"></a>

## UTIL_EST

Because periodic tasks have their averages decayed while they sleep, even though when running their expected utilization will be the same, they suffer a (DVFS) ramp-up after they are running again.

To alleviate this (a default enabled option) UTIL_EST drives an Infinite Impulse Response (IIR) EWMA with the 'running' value on dequeue -- when it is highest. UTIL_EST filters to instantly increase and only decay on decrease.

A further runqueue wide sum (of runnable tasks) is maintained of:

> util_est := Sum_t max( t_running, t_util_est_ewma )

For more detail see: kernel/sched/fair.c:util_est_dequeue()

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

## UCLAMP

It is possible to set effective u_min and u_max clamps on each CFS or RT task; the runqueue keeps an max aggregate of these clamps for all running tasks.

For more detail see: include/uapi/linux/sched/types.h

<a id="rst-schedutil-dvfs"></a>

## Schedutil / DVFS

Every time the scheduler load tracking is updated (task wakeup, task migration, time progression) we call out to schedutil to update the hardware DVFS state.

The basis is the CPU runqueue's 'running' metric, which per the above it is the frequency invariant utilization estimate of the CPU. From this we compute a desired frequency like:



```text
           max( running, util_est );  if UTIL_EST
u_cfs := { running;                   otherwise

             clamp( u_cfs + u_rt , u_min, u_max );    if UCLAMP_TASK
u_clamp := { u_cfs + u_rt;                            otherwise

u := u_clamp + u_irq + u_dl;          [approx. see source for more detail]

f_des := min( f_max, 1.25 u * f_max )
```

XXX IO-wait: when the update is due to a task wakeup from IO-completion we boost 'u' above.

This frequency is then used to select a P-state/OPP or directly munged into a CPPC style request to the hardware.

XXX: deadline tasks (Sporadic Task Model) allows us to calculate a hard f_min required to satisfy the workload.

Because these callbacks are directly from the scheduler, the DVFS hardware interaction should be 'fast' and non-blocking. Schedutil supports rate-limiting DVFS requests for when hardware interaction is slow and expensive, this reduces effectiveness.

For more information see: kernel/sched/cpufreq_schedutil.c

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

## NOTES

> - On low-load scenarios, where DVFS is most relevant, the 'running' numbers will closely reflect utilization.
>
> - In saturated scenarios task movement will cause some transient dips, suppose we have a CPU saturated with 4 tasks, then when we migrate a task to an idle CPU, the old CPU will have a 'running' value of 0.75 while the new CPU will gain 0.25. This is inevitable and time progression will correct this. XXX do we still guarantee f_max due to no idle-time?
>
> - Much of the above is about avoiding DVFS dips, and independent DVFS domains having to re-learn / ramp-up when load shifts.

---

# Scheduler pelt c program

_Peios Kernel / Internals / Scheduling_

> Reference for Scheduler pelt c program.

<a id="rst-scheduler-pelt-c-program"></a>


```c
/*
 * The following program is used to generate the constants for
 * computing sched averages.
 *
 * ==============================================================
 *              C program (compile with -lm)
 * ==============================================================
 */

#include <math.h>
#include <stdio.h>

#define HALFLIFE 32
#define SHIFT 32

double y;

void calc_runnable_avg_yN_inv(void)
{
        int i;
        unsigned int x;

        /* To silence -Wunused-but-set-variable warnings. */
        printf("static const u32 runnable_avg_yN_inv[] __maybe_unused = {");
        for (i = 0; i < HALFLIFE; i++) {
                x = ((1UL<<32)-1)*pow(y, i);

                if (i % 6 == 0) printf("\n\t");
                printf("0x%8x, ", x);
        }
        printf("\n};\n\n");
}

int sum = 1024;

void calc_runnable_avg_yN_sum(void)
{
        int i;

        printf("static const u32 runnable_avg_yN_sum[] = {\n\t    0,");
        for (i = 1; i <= HALFLIFE; i++) {
                if (i == 1)
                        sum *= y;
                else
                        sum = sum*y + 1024*y;

                if (i % 11 == 0)
                        printf("\n\t");

                printf("%5d,", sum);
        }
        printf("\n};\n\n");
}

int n = -1;
/* first period */
long max = 1024;

void calc_converged_max(void)
{
        long last = 0, y_inv = ((1UL<<32)-1)*y;

        for (; ; n++) {
                if (n > -1)
                        max = ((max*y_inv)>>SHIFT) + 1024;
                        /*
                         * This is the same as:
                         * max = max*y + 1024;
                         */

                if (last == max)
                        break;

                last = max;
        }
        n--;
        printf("#define LOAD_AVG_PERIOD %d\n", HALFLIFE);
        printf("#define LOAD_AVG_MAX %ld\n", max);
//      printf("#define LOAD_AVG_MAX_N %d\n\n", n);
}

void calc_accumulated_sum_32(void)
{
        int i, x = sum;

        printf("static const u32 __accumulated_sum_N32[] = {\n\t     0,");
        for (i = 1; i <= n/HALFLIFE+1; i++) {
                if (i > 1)
                        x = x/2 + sum;

                if (i % 6 == 0)
                        printf("\n\t");

                printf("%6d,", x);
        }
        printf("\n};\n\n");
}

void main(void)
{
        printf("/* Generated by Documentation/scheduler/sched-pelt; do not modify. */\n\n");

        y = pow(0.5, 1/(double)HALFLIFE);

        calc_runnable_avg_yN_inv();
//      calc_runnable_avg_yN_sum();
        calc_converged_max();
//      calc_accumulated_sum_32();
}

```

---

# RCU Handbook

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Reference for RCU Handbook.

<a id="rst-rcu-handbook-1"></a>
<a id="rst-rcu-handbook"></a>

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

- [Review Checklist for RCU Patches](</kernel/internals/rcu/checklist.md>)
- [RCU and lockdep checking](</kernel/internals/rcu/lockdep.md>)
- [Lockdep-RCU Splat](</kernel/internals/rcu/lockdep-splat.md>)
- [RCU and Unloadable Modules](</kernel/internals/rcu/rcubarrier.md>)
- [PROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference()](</kernel/internals/rcu/rcu-dereference.md>)
- [What is RCU?  --  "Read, Copy, Update"](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/RCU/whatisRCU.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [RCU Concepts](</kernel/internals/rcu/rcu.md>)
- [Using RCU hlist_nulls to protect list and objects](</kernel/internals/rcu/rculist-nulls.md>)
- [Reference-count design for elements of lists/arrays protected by RCU](</kernel/internals/rcu/rcuref.md>)
- [RCU Torture Test Operation](</kernel/internals/rcu/torture.md>)
- [Using RCU's CPU Stall Detector](</kernel/internals/rcu/stallwarn.md>)
- [Using RCU to Protect Read-Mostly Linked Lists](</kernel/internals/rcu/listrcu.md>)
- [Using RCU to Protect Dynamic NMI Handlers](</kernel/internals/rcu/nmi-rcu.md>)
- [RCU on Uniprocessor Systems](</kernel/internals/rcu/up.md>)
- [A Tour Through TREE_RCU's Grace-Period Memory Ordering](</kernel/internals/rcu/design-memory-ordering/tree-rcu-memory-ordering.md>)
- [A Tour Through TREE_RCU's Expedited Grace Periods](</kernel/internals/rcu/design-expedited-grace-periods/expedited-grace-periods.md>)
- [A Tour Through RCU's Requirements](</kernel/internals/rcu/design-requirements/requirements.md>)
- [A Tour Through TREE_RCU's Data Structures \[LWN.net\]](</kernel/internals/rcu/design-data-structures/data-structures.md>)

---

# Using RCU to Protect Dynamic NMI Handlers

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Although RCU is usually used to protect read-mostly data structures, it is possible to use RCU to provide dynamic non-maskable interrupt handlers, as well as dynamic irq handlers. This document describes how to do this, drawing loosely…

<a id="rst-using-rcu-to-protect-dynamic-nmi-handlers"></a>
<a id="rst-nmi-rcu-doc"></a>

Although RCU is usually used to protect read-mostly data structures, it is possible to use RCU to provide dynamic non-maskable interrupt handlers, as well as dynamic irq handlers.  This document describes how to do this, drawing loosely from Zwane Mwaikambo's NMI-timer work in an old version of "arch/x86/kernel/traps.c".

The relevant pieces of code are listed below, each followed by a brief explanation:



```text
static int dummy_nmi_callback(struct pt_regs *regs, int cpu)
{
        return 0;
}
```

The dummy_nmi_callback() function is a "dummy" NMI handler that does nothing, but returns zero, thus saying that it did nothing, allowing the NMI handler to take the default machine-specific action:



```text
static nmi_callback_t nmi_callback = dummy_nmi_callback;
```

This nmi_callback variable is a global function pointer to the current NMI handler:



```text
void do_nmi(struct pt_regs * regs, long error_code)
{
        int cpu;

        nmi_enter();

        cpu = smp_processor_id();
        ++nmi_count(cpu);

        if (!rcu_dereference_sched(nmi_callback)(regs, cpu))
                default_do_nmi(regs);

        nmi_exit();
}
```

The do_nmi() function processes each NMI.  It first disables preemption in the same way that a hardware irq would, then increments the per-CPU count of NMIs.  It then invokes the NMI handler stored in the nmi_callback function pointer.  If this handler returns zero, do_nmi() invokes the default_do_nmi() function to handle a machine-specific NMI.  Finally, preemption is restored.

In theory, rcu_dereference_sched() is not needed, since this code runs only on i386, which in theory does not need rcu_dereference_sched() anyway.  However, in practice it is a good documentation aid, particularly for anyone attempting to do something similar on Alpha or on systems with aggressive optimizing compilers.

- **Quick Quiz:**

  Why might the rcu_dereference_sched() be necessary on Alpha, given that the code referenced by the pointer is read-only?

[Answer to Quick Quiz](<#rst-answer-quick-quiz-nmi>)

Back to the discussion of NMI and RCU:



```text
void set_nmi_callback(nmi_callback_t callback)
{
        rcu_assign_pointer(nmi_callback, callback);
}
```

The set_nmi_callback() function registers an NMI handler.  Note that any data that is to be used by the callback must be initialized up -before- the call to set_nmi_callback().  On architectures that do not order writes, the rcu_assign_pointer() ensures that the NMI handler sees the initialized values:



```text
void unset_nmi_callback(void)
{
        rcu_assign_pointer(nmi_callback, dummy_nmi_callback);
}
```

This function unregisters an NMI handler, restoring the original dummy_nmi_handler().  However, there may well be an NMI handler currently executing on some other CPU.  We therefore cannot free up any data structures used by the old NMI handler until execution of it completes on all other CPUs.

One way to accomplish this is via synchronize_rcu(), perhaps as follows:



```text
unset_nmi_callback();
synchronize_rcu();
kfree(my_nmi_data);
```

This works because (as of v4.20) synchronize_rcu() blocks until all CPUs complete any preemption-disabled segments of code that they were executing. Since NMI handlers disable preemption, synchronize_rcu() is guaranteed not to return until all ongoing NMI handlers exit.  It is therefore safe to free up the handler's data as soon as synchronize_rcu() returns.

Important note: for this to work, the architecture in question must invoke nmi_enter() and nmi_exit() on NMI entry and exit, respectively.

<a id="rst-answer-quick-quiz-nmi"></a>

- **Answer to Quick Quiz:**

  Why might the rcu_dereference_sched() be necessary on Alpha, given that the code referenced by the pointer is read-only?

  The caller to set_nmi_callback() might well have initialized some data that is to be used by the new NMI handler.  In this case, the rcu_dereference_sched() would be needed, because otherwise a CPU that received an NMI just after the new handler was set might see the pointer to the new NMI handler, but the old pre-initialized version of the handler's data.

  This same sad story can happen on other CPUs when using a compiler with aggressive pointer-value speculation optimizations.  (But please don't\!)

  More important, the rcu_dereference_sched() makes it clear to someone reading the code that the pointer is being protected by RCU-sched.

---

# RCU on Uniprocessor Systems

_Peios Kernel / Internals / Read-copy-update (RCU)_

> A common misconception is that, on UP systems, the call_rcu() primitive may immediately invoke its function. The basis of this misconception is that since there is only one CPU, it should not be necessary to wait for anything else to get…

<a id="rst-rcu-on-uniprocessor-systems"></a>
<a id="rst-up-doc"></a>

A common misconception is that, on UP systems, the call_rcu() primitive may immediately invoke its function.  The basis of this misconception is that since there is only one CPU, it should not be necessary to wait for anything else to get done, since there are no other CPUs for anything else to be happening on.  Although this approach will *sort of* work a surprising amount of the time, it is a very bad idea in general. This document presents three examples that demonstrate exactly how bad an idea this is.

<a id="rst-example-1-softirq-suicide"></a>

## Example 1: softirq Suicide

Suppose that an RCU-based algorithm scans a linked list containing elements A, B, and C in process context, and can delete elements from this same list in softirq context.  Suppose that the process-context scan is referencing element B when it is interrupted by softirq processing, which deletes element B, and then invokes call_rcu() to free element B after a grace period.

Now, if call_rcu() were to directly invoke its arguments, then upon return from softirq, the list scan would find itself referencing a newly freed element B.  This situation can greatly decrease the life expectancy of your kernel.

This same problem can occur if call_rcu() is invoked from a hardware interrupt handler.

<a id="rst-example-2-function-call-fatality"></a>

## Example 2: Function-Call Fatality

Of course, one could avert the suicide described in the preceding example by having call_rcu() directly invoke its arguments only if it was called from process context.  However, this can fail in a similar manner.

Suppose that an RCU-based algorithm again scans a linked list containing elements A, B, and C in process context, but that it invokes a function on each element as it is scanned.  Suppose further that this function deletes element B from the list, then passes it to call_rcu() for deferred freeing.  This may be a bit unconventional, but it is perfectly legal RCU usage, since call_rcu() must wait for a grace period to elapse. Therefore, in this case, allowing call_rcu() to immediately invoke its arguments would cause it to fail to make the fundamental guarantee underlying RCU, namely that call_rcu() defers invoking its arguments until all RCU read-side critical sections currently executing have completed.

- **Quick Quiz \#1:**

  Why is it *not* legal to invoke synchronize_rcu() in this case?

[Answers to Quick Quiz](<#rst-answer-quick-quiz-up>)

<a id="rst-example-3-death-by-deadlock"></a>

## Example 3: Death by Deadlock

Suppose that call_rcu() is invoked while holding a lock, and that the callback function must acquire this same lock.  In this case, if call_rcu() were to directly invoke the callback, the result would be self-deadlock *even if* this invocation occurred from a later call_rcu() invocation a full grace period later.

In some cases, it would possible to restructure to code so that the call_rcu() is delayed until after the lock is released.  However, there are cases where this can be quite ugly:

1. If a number of items need to be passed to call_rcu() within the same critical section, then the code would need to create a list of them, then traverse the list once the lock was released.

2. In some cases, the lock will be held across some kernel API, so that delaying the call_rcu() until the lock is released requires that the data item be passed up via a common API. It is far better to guarantee that callbacks are invoked with no locks held than to have to modify such APIs to allow arbitrary data items to be passed back up through them.

If call_rcu() directly invokes the callback, painful locking restrictions or API changes would be required.

- **Quick Quiz \#2:**

  What locking restriction must RCU callbacks respect?

[Answers to Quick Quiz](<#rst-answer-quick-quiz-up>)

It is important to note that userspace RCU implementations *do* permit call_rcu() to directly invoke callbacks, but only if a full grace period has elapsed since those callbacks were queued.  This is the case because some userspace environments are extremely constrained. Nevertheless, people writing userspace RCU implementations are strongly encouraged to avoid invoking callbacks from call_rcu(), thus obtaining the deadlock-avoidance benefits called out above.

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

## Summary

Permitting call_rcu() to immediately invoke its arguments breaks RCU, even on a UP system.  So do not do it\!  Even on a UP system, the RCU infrastructure *must* respect grace periods, and *must* invoke callbacks from a known environment in which no locks are held.

Note that it *is* safe for synchronize_rcu() to return immediately on UP systems, including PREEMPT SMP builds running on UP systems.

- **Quick Quiz \#3:**

  Why can't synchronize_rcu() return immediately on UP systems running preemptible RCU?

<a id="rst-answer-quick-quiz-up"></a>

- **Answer to Quick Quiz \#1:**

  Why is it *not* legal to invoke synchronize_rcu() in this case?

  Because the calling function is scanning an RCU-protected linked list, and is therefore within an RCU read-side critical section. Therefore, the called function has been invoked within an RCU read-side critical section, and is not permitted to block.

- **Answer to Quick Quiz \#2:**

  What locking restriction must RCU callbacks respect?

  Any lock that is acquired within an RCU callback must be acquired elsewhere using an \_bh variant of the spinlock primitive. For example, if "mylock" is acquired by an RCU callback, then a process-context acquisition of this lock must use something like spin_lock_bh() to acquire the lock.  Please note that it is also OK to use \_irq variants of spinlocks, for example, spin_lock_irqsave().

  If the process-context code were to simply use spin_lock(), then, since RCU callbacks can be invoked from softirq context, the callback might be called from a softirq that interrupted the process-context critical section.  This would result in self-deadlock.

  This restriction might seem gratuitous, since very few RCU callbacks acquire locks directly.  However, a great many RCU callbacks do acquire locks *indirectly*, for example, via the kfree() primitive.

- **Answer to Quick Quiz \#3:**

  Why can't synchronize_rcu() return immediately on UP systems running preemptible RCU?

  Because some other task might have been preempted in the middle of an RCU read-side critical section.  If synchronize_rcu() simply immediately returned, it would prematurely signal the end of the grace period, which would come as a nasty shock to that other thread when it started running again.

---

# Review Checklist for RCU Patches

_Peios Kernel / Internals / Read-copy-update (RCU)_

> This document contains a checklist for producing and reviewing patches that make use of RCU. Violating any of the rules listed below will result in the same sorts of problems that leaving out a locking primitive would cause. This list is…

<a id="rst-review-checklist-for-rcu-patches"></a>

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

This document contains a checklist for producing and reviewing patches that make use of RCU.  Violating any of the rules listed below will result in the same sorts of problems that leaving out a locking primitive would cause.  This list is based on experiences reviewing such patches over a rather long period of time, but improvements are always welcome\!

0. Is RCU being applied to a read-mostly situation?  If the data structure is updated more than about 10% of the time, then you should strongly consider some other approach, unless detailed performance measurements show that RCU is nonetheless the right tool for the job.  Yes, RCU does reduce read-side overhead by increasing write-side overhead, which is exactly why normal uses of RCU will do much more reading than updating.

   Another exception is where performance is not an issue, and RCU provides a simpler implementation.  An example of this situation is the dynamic NMI code in the Linux 2.6 kernel, at least on architectures where NMIs are rare.

   Yet another exception is where the low real-time latency of RCU's read-side primitives is critically important.

   One final exception is where RCU readers are used to prevent the ABA problem ([https://en.wikipedia.org/wiki/ABA_problem](<https://en.wikipedia.org/wiki/ABA_problem>)) for lockless updates.  This does result in the mildly counter-intuitive situation where rcu_read_lock() and rcu_read_unlock() are used to protect updates, however, this approach can provide the same simplifications to certain types of lockless algorithms that garbage collectors do.

1. Does the update code have proper mutual exclusion?

   RCU does allow *readers* to run (almost) naked, but *writers* must still use some sort of mutual exclusion, such as:

   - **a.** locking,

   - **b.** atomic operations, or

   - **c.** restricting updates to a single task.

   If you choose \#b, be prepared to describe how you have handled memory barriers on weakly ordered machines (pretty much all of them -- even x86 allows later loads to be reordered to precede earlier stores), and be prepared to explain why this added complexity is worthwhile.  If you choose \#c, be prepared to explain how this single task does not become a major bottleneck on large systems (for example, if the task is updating information relating to itself that other tasks can read, there by definition can be no bottleneck).  Note that the definition of "large" has changed significantly:  Eight CPUs was "large" in the year 2000, but a hundred CPUs was unremarkable in 2017.

2. Do the RCU read-side critical sections make proper use of rcu_read_lock() and friends?  These primitives are needed to prevent grace periods from ending prematurely, which could result in data being unceremoniously freed out from under your read-side code, which can greatly increase the actuarial risk of your kernel.

   As a rough rule of thumb, any dereference of an RCU-protected pointer must be covered by rcu_read_lock(), rcu_read_lock_bh(), rcu_read_lock_sched(), or by the appropriate update-side lock. Explicit disabling of preemption (preempt_disable(), for example) can serve as rcu_read_lock_sched(), but is less readable and prevents lockdep from detecting locking issues.  Acquiring a raw spinlock also enters an RCU read-side critical section.

   The guard(rcu)() and scoped_guard(rcu) primitives designate the remainder of the current scope or the next statement, respectively, as the RCU read-side critical section.  Use of these guards can be less error-prone than rcu_read_lock(), rcu_read_unlock(), and friends.

   Please note that you *cannot* rely on code known to be built only in non-preemptible kernels.  Such code can and will break, especially in kernels built with CONFIG_PREEMPT_COUNT=y.

   Letting RCU-protected pointers "leak" out of an RCU read-side critical section is every bit as bad as letting them leak out from under a lock.  Unless, of course, you have arranged some other means of protection, such as a lock or a reference count *before* letting them out of the RCU read-side critical section.

3. Does the update code tolerate concurrent accesses?

   The whole point of RCU is to permit readers to run without any locks or atomic operations.  This means that readers will be running while updates are in progress.  There are a number of ways to handle this concurrency, depending on the situation:

   - **a.** Use the RCU variants of the list and hlist update primitives to add, remove, and replace elements on an RCU-protected list.  Alternatively, use the other RCU-protected data structures that have been added to the Linux kernel.

     This is almost always the best approach.

   - **b.** Proceed as in (a) above, but also maintain per-element locks (that are acquired by both readers and writers) that guard per-element state.  Fields that the readers refrain from accessing can be guarded by some other lock acquired only by updaters, if desired.

     This also works quite well.

   - **c.** Make updates appear atomic to readers.  For example, pointer updates to properly aligned fields will appear atomic, as will individual atomic primitives. Sequences of operations performed under a lock will *not* appear to be atomic to RCU readers, nor will sequences of multiple atomic primitives.  One alternative is to move multiple individual fields to a separate structure, thus solving the multiple-field problem by imposing an additional level of indirection.

     This can work, but is starting to get a bit tricky.

   - **d.** Carefully order the updates and the reads so that readers see valid data at all phases of the update.  This is often more difficult than it sounds, especially given modern CPUs' tendency to reorder memory references.  One must usually liberally sprinkle memory-ordering operations through the code, making it difficult to understand and to test.  Where it works, it is better to use things like smp_store_release() and smp_load_acquire(), but in some cases the smp_mb() full memory barrier is required.

     As noted earlier, it is usually better to group the changing data into a separate structure, so that the change may be made to appear atomic by updating a pointer to reference a new structure containing updated values.

4. Weakly ordered CPUs pose special challenges.  Almost all CPUs are weakly ordered -- even x86 CPUs allow later loads to be reordered to precede earlier stores.  RCU code must take all of the following measures to prevent memory-corruption problems:

   - **a.** Readers must maintain proper ordering of their memory accesses.  The rcu_dereference() primitive ensures that the CPU picks up the pointer before it picks up the data that the pointer points to.  This really is necessary on Alpha CPUs.

     The rcu_dereference() primitive is also an excellent documentation aid, letting the person reading the code know exactly which pointers are protected by RCU. Please note that compilers can also reorder code, and they are becoming increasingly aggressive about doing just that.  The rcu_dereference() primitive therefore also prevents destructive compiler optimizations.  However, with a bit of devious creativity, it is possible to mishandle the return value from rcu_dereference(). Please see [rcu_dereference.rst](/kernel/internals/rcu/rcu-dereference.md) for more information.

     The rcu_dereference() primitive is used by the various "\_rcu()" list-traversal primitives, such as the list_for_each_entry_rcu().  Note that it is perfectly legal (if redundant) for update-side code to use rcu_dereference() and the "\_rcu()" list-traversal primitives.  This is particularly useful in code that is common to readers and updaters.  However, lockdep will complain if you access rcu_dereference() outside of an RCU read-side critical section.  See [lockdep.rst](/kernel/internals/rcu/lockdep.md) to learn what to do about this.

     Of course, neither rcu_dereference() nor the "\_rcu()" list-traversal primitives can substitute for a good concurrency design coordinating among multiple updaters.

   - **b.** If the list macros are being used, the list_add_tail_rcu() and list_add_rcu() primitives must be used in order to prevent weakly ordered machines from misordering structure initialization and pointer planting. Similarly, if the hlist macros are being used, the hlist_add_head_rcu() primitive is required.

   - **c.** If the list macros are being used, the list_del_rcu() primitive must be used to keep list_del()'s pointer poisoning from inflicting toxic effects on concurrent readers.  Similarly, if the hlist macros are being used, the hlist_del_rcu() primitive is required.

     The list_replace_rcu() and hlist_replace_rcu() primitives may be used to replace an old structure with a new one in their respective types of RCU-protected lists.

   - **d.** Rules similar to (4b) and (4c) apply to the "hlist_nulls" type of RCU-protected linked lists.

   - **e.** Updates must ensure that initialization of a given structure happens before pointers to that structure are publicized.  Use the rcu_assign_pointer() primitive when publicizing a pointer to a structure that can be traversed by an RCU read-side critical section.

5. If any of call_rcu(), call_srcu(), call_rcu_tasks(), or call_rcu_tasks_trace() is used, the callback function may be invoked from softirq context, and in any case with bottom halves disabled.  In particular, this callback function cannot block. If you need the callback to block, run that code in a workqueue handler scheduled from the callback.  The queue_rcu_work() function does this for you in the case of call_rcu().

6. Since synchronize_rcu() can block, it cannot be called from any sort of irq context.  The same rule applies for synchronize_srcu(), synchronize_rcu_expedited(), synchronize_srcu_expedited(), synchronize_rcu_tasks(), synchronize_rcu_tasks_rude(), and synchronize_rcu_tasks_trace().

   The expedited forms of these primitives have the same semantics as the non-expedited forms, but expediting is more CPU intensive. Use of the expedited primitives should be restricted to rare configuration-change operations that would not normally be undertaken while a real-time workload is running.  Note that IPI-sensitive real-time workloads can use the rcupdate.rcu_normal kernel boot parameter to completely disable expedited grace periods, though this might have performance implications.

   In particular, if you find yourself invoking one of the expedited primitives repeatedly in a loop, please do everyone a favor: Restructure your code so that it batches the updates, allowing a single non-expedited primitive to cover the entire batch. This will very likely be faster than the loop containing the expedited primitive, and will be much much easier on the rest of the system, especially to real-time workloads running on the rest of the system.  Alternatively, instead use asynchronous primitives such as call_rcu().

7. As of v4.20, a given kernel implements only one RCU flavor, which is RCU-sched for PREEMPTION=n and RCU-preempt for PREEMPTION=y. If the updater uses call_rcu() or synchronize_rcu(), then the corresponding readers may use:  (1) rcu_read_lock() and rcu_read_unlock(), (2) any pair of primitives that disables and re-enables softirq, for example, rcu_read_lock_bh() and rcu_read_unlock_bh(), or (3) any pair of primitives that disables and re-enables preemption, for example, rcu_read_lock_sched() and rcu_read_unlock_sched().  If the updater uses synchronize_srcu() or call_srcu(), then the corresponding readers must use srcu_read_lock() and srcu_read_unlock(), and with the same srcu_struct.  The rules for the expedited RCU grace-period-wait primitives are the same as for their non-expedited counterparts.

   Similarly, it is necessary to correctly use the RCU Tasks flavors:

   - **a.** If the updater uses synchronize_rcu_tasks() or call_rcu_tasks(), then the readers must refrain from executing voluntary context switches, that is, from blocking.

   - **b.** If the updater uses call_rcu_tasks_trace() or synchronize_rcu_tasks_trace(), then the corresponding readers must use rcu_read_lock_trace() and rcu_read_unlock_trace().

   - **c.** If an updater uses synchronize_rcu_tasks_rude(), then the corresponding readers must use anything that disables preemption, for example, preempt_disable() and preempt_enable().

   Mixing things up will result in confusion and broken kernels, and has even resulted in an exploitable security issue.  Therefore, when using non-obvious pairs of primitives, commenting is of course a must.  One example of non-obvious pairing is the XDP feature in networking, which calls BPF programs from network-driver NAPI (softirq) context.  BPF relies heavily on RCU protection for its data structures, but because the BPF program invocation happens entirely within a single local_bh_disable() section in a NAPI poll cycle, this usage is safe.  The reason that this usage is safe is that readers can use anything that disables BH when updaters use call_rcu() or synchronize_rcu().

8. Although synchronize_rcu() is slower than is call_rcu(), it usually results in simpler code.  So, unless update performance is critically important, the updaters cannot block, or the latency of synchronize_rcu() is visible from userspace, synchronize_rcu() should be used in preference to call_rcu(). Furthermore, kfree_rcu() and kvfree_rcu() usually result in even simpler code than does synchronize_rcu() without synchronize_rcu()'s multi-millisecond latency.  So please take advantage of kfree_rcu()'s and kvfree_rcu()'s "fire and forget" memory-freeing capabilities where it applies.

   An especially important property of the synchronize_rcu() primitive is that it automatically self-limits: if grace periods are delayed for whatever reason, then the synchronize_rcu() primitive will correspondingly delay updates.  In contrast, code using call_rcu() should explicitly limit update rate in cases where grace periods are delayed, as failing to do so can result in excessive realtime latencies or even OOM conditions.

   Ways of gaining this self-limiting property when using call_rcu(), kfree_rcu(), or kvfree_rcu() include:

   - **a.** Keeping a count of the number of data-structure elements used by the RCU-protected data structure, including those waiting for a grace period to elapse.  Enforce a limit on this number, stalling updates as needed to allow previously deferred frees to complete.  Alternatively, limit only the number awaiting deferred free rather than the total number of elements.

     One way to stall the updates is to acquire the update-side mutex.  (Don't try this with a spinlock -- other CPUs spinning on the lock could prevent the grace period from ever ending.)  Another way to stall the updates is for the updates to use a wrapper function around the memory allocator, so that this wrapper function simulates OOM when there is too much memory awaiting an RCU grace period.  There are of course many other variations on this theme.

   - **b.** Limiting update rate.  For example, if updates occur only once per hour, then no explicit rate limiting is required, unless your system is already badly broken. Older versions of the dcache subsystem take this approach, guarding updates with a global lock, limiting their rate.

   - **c.** Trusted update -- if updates can only be done manually by superuser or some other trusted user, then it might not be necessary to automatically limit them.  The theory here is that superuser already has lots of ways to crash the machine.

   - **d.** Periodically invoke rcu_barrier(), permitting a limited number of updates per grace period.

   The same cautions apply to call_srcu(), call_rcu_tasks(), and call_rcu_tasks_trace().  This is why there is an srcu_barrier(), rcu_barrier_tasks(), and rcu_barrier_tasks_trace(), respectively.

   Note that although these primitives do take action to avoid memory exhaustion when any given CPU has too many callbacks, a determined user or administrator can still exhaust memory. This is especially the case if a system with a large number of CPUs has been configured to offload all of its RCU callbacks onto a single CPU, or if the system has relatively little free memory.

9. All RCU list-traversal primitives, which include rcu_dereference(), list_for_each_entry_rcu(), and list_for_each_safe_rcu(), must be either within an RCU read-side critical section or must be protected by appropriate update-side locks.  RCU read-side critical sections are delimited by rcu_read_lock() and rcu_read_unlock(), or by similar primitives such as rcu_read_lock_bh() and rcu_read_unlock_bh(), in which case the matching rcu_dereference() primitive must be used in order to keep lockdep happy, in this case, rcu_dereference_bh().

   The reason that it is permissible to use RCU list-traversal primitives when the update-side lock is held is that doing so can be quite helpful in reducing code bloat when common code is shared between readers and updaters.  Additional primitives are provided for this case, as discussed in [lockdep.rst](/kernel/internals/rcu/lockdep.md).

   One exception to this rule is when data is only ever added to the linked data structure, and is never removed during any time that readers might be accessing that structure.  In such cases, READ_ONCE() may be used in place of rcu_dereference() and the read-side markers (rcu_read_lock() and rcu_read_unlock(), for example) may be omitted.

10. Conversely, if you are in an RCU read-side critical section, and you don't hold the appropriate update-side lock, you *must* use the "\_rcu()" variants of the list macros.  Failing to do so will break Alpha, cause aggressive compilers to generate bad code, and confuse people trying to understand your code.

11. Any lock acquired by an RCU callback must be acquired elsewhere with softirq disabled, e.g., via spin_lock_bh().  Failing to disable softirq on a given acquisition of that lock will result in deadlock as soon as the RCU softirq handler happens to run your RCU callback while interrupting that acquisition's critical section.

12. RCU callbacks can be and are executed in parallel.  In many cases, the callback code simply wrappers around kfree(), so that this is not an issue (or, more accurately, to the extent that it is an issue, the memory-allocator locking handles it).  However, if the callbacks do manipulate a shared data structure, they must use whatever locking or other synchronization is required to safely access and/or modify that data structure.

    Do not assume that RCU callbacks will be executed on the same CPU that executed the corresponding call_rcu(), call_srcu(), call_rcu_tasks(), or call_rcu_tasks_trace().  For example, if a given CPU goes offline while having an RCU callback pending, then that RCU callback will execute on some surviving CPU. (If this was not the case, a self-spawning RCU callback would prevent the victim CPU from ever going offline.)  Furthermore, CPUs designated by rcu_nocbs= might well *always* have their RCU callbacks executed on some other CPUs, in fact, for some real-time workloads, this is the whole point of using the rcu_nocbs= kernel boot parameter.

    In addition, do not assume that callbacks queued in a given order will be invoked in that order, even if they all are queued on the same CPU.  Furthermore, do not assume that same-CPU callbacks will be invoked serially.  For example, in recent kernels, CPUs can be switched between offloaded and de-offloaded callback invocation, and while a given CPU is undergoing such a switch, its callbacks might be concurrently invoked by that CPU's softirq handler and that CPU's rcuo kthread.  At such times, that CPU's callbacks might be executed both concurrently and out of order.

13. Unlike most flavors of RCU, it *is* permissible to block in an SRCU read-side critical section (demarked by srcu_read_lock() and srcu_read_unlock()), hence the "SRCU": "sleepable RCU". As with RCU, guard(srcu)() and scoped_guard(srcu) forms are available, and often provide greater ease of use.  Please note that if you don't need to sleep in read-side critical sections, you should be using RCU rather than SRCU, because RCU is almost always faster and easier to use than is SRCU.

    Also unlike other forms of RCU, explicit initialization and cleanup is required either at build time via DEFINE_SRCU(), DEFINE_STATIC_SRCU(), DEFINE_SRCU_FAST(), or DEFINE_STATIC_SRCU_FAST() or at runtime via either init_srcu_struct() or init_srcu_struct_fast() and cleanup_srcu_struct().  These last three are passed a `struct srcu_struct` that defines the scope of a given SRCU domain.  Once initialized, the srcu_struct is passed to srcu_read_lock(), srcu_read_unlock() synchronize_srcu(), synchronize_srcu_expedited(), and call_srcu().  A given synchronize_srcu() waits only for SRCU read-side critical sections governed by srcu_read_lock() and srcu_read_unlock() calls that have been passed the same srcu_struct.  This property is what makes sleeping read-side critical sections tolerable -- a given subsystem delays only its own updates, not those of other subsystems using SRCU.  Therefore, SRCU is less prone to OOM the system than RCU would be if RCU's read-side critical sections were permitted to sleep.

    The ability to sleep in read-side critical sections does not come for free.  First, corresponding srcu_read_lock() and srcu_read_unlock() calls must be passed the same srcu_struct. Second, grace-period-detection overhead is amortized only over those updates sharing a given srcu_struct, rather than being globally amortized as they are for other forms of RCU. Therefore, SRCU should be used in preference to rw_semaphore only in extremely read-intensive situations, or in situations requiring SRCU's read-side deadlock immunity or low read-side realtime latency.  You should also consider percpu_rw_semaphore when you need lightweight readers.

    SRCU's expedited primitive (synchronize_srcu_expedited()) never sends IPIs to other CPUs, so it is easier on real-time workloads than is synchronize_rcu_expedited().

    It is also permissible to sleep in RCU Tasks Trace read-side critical section, which are delimited by rcu_read_lock_trace() and rcu_read_unlock_trace().  However, this is a specialized flavor of RCU, and you should not use it without first checking with its current users.  In most cases, you should instead use SRCU.  As with RCU and SRCU, guard(rcu_tasks_trace)() and scoped_guard(rcu_tasks_trace) are available, and often provide greater ease of use.

    Note that rcu_assign_pointer() relates to SRCU just as it does to other forms of RCU, but instead of rcu_dereference() you should use srcu_dereference() in order to avoid lockdep splats.

14. The whole point of call_rcu(), synchronize_rcu(), and friends is to wait until all pre-existing readers have finished before carrying out some otherwise-destructive operation.  It is therefore critically important to *first* remove any path that readers can follow that could be affected by the destructive operation, and *only then* invoke call_rcu(), synchronize_rcu(), or friends.

    Because these primitives only wait for pre-existing readers, it is the caller's responsibility to guarantee that any subsequent readers will execute safely.

15. The various RCU read-side primitives do *not* necessarily contain memory barriers.  You should therefore plan for the CPU and the compiler to freely reorder code into and out of RCU read-side critical sections.  It is the responsibility of the RCU update-side primitives to deal with this.

    For SRCU readers, you can use smp_mb__after_srcu_read_unlock() immediately after an srcu_read_unlock() to get a full barrier.

16. Use CONFIG_PROVE_LOCKING, CONFIG_DEBUG_OBJECTS_RCU_HEAD, and the \__rcu sparse checks to validate your RCU code.  These can help find problems as follows:

    - **CONFIG_PROVE_LOCKING:**

      check that accesses to RCU-protected data structures are carried out under the proper RCU read-side critical section, while holding the right combination of locks, or whatever other conditions are appropriate.

    - **CONFIG_DEBUG_OBJECTS_RCU_HEAD:**

      check that you don't pass the same object to call_rcu() (or friends) before an RCU grace period has elapsed since the last time that you passed that same object to call_rcu() (or friends).

    - **CONFIG_RCU_STRICT_GRACE_PERIOD:**

      combine with KASAN to check for pointers leaked out of RCU read-side critical sections.  This Kconfig option is tough on both performance and scalability, and so is limited to four-CPU systems.

    - **\__rcu sparse checks:**

      tag the pointer to the RCU-protected data structure with \__rcu, and sparse will warn you if you access that pointer without the services of one of the variants of rcu_dereference().

    These debugging aids can help you find problems that are otherwise extremely difficult to spot.

17. If you pass a callback function defined within a module to one of call_rcu(), call_srcu(), call_rcu_tasks(), or call_rcu_tasks_trace(), then it is necessary to wait for all pending callbacks to be invoked before unloading that module. Note that it is absolutely *not* sufficient to wait for a grace period\!  For example, synchronize_rcu() implementation is *not* guaranteed to wait for callbacks registered on other CPUs via call_rcu().  Or even on the current CPU if that CPU recently went offline and came back online.

    You instead need to use one of the barrier functions:

    - call_rcu() -&gt; rcu_barrier()

    - call_srcu() -&gt; srcu_barrier()

    - call_rcu_tasks() -&gt; rcu_barrier_tasks()

    - call_rcu_tasks_trace() -&gt; rcu_barrier_tasks_trace()

    However, these barrier functions are absolutely *not* guaranteed to wait for a grace period.  For example, if there are no call_rcu() callbacks queued anywhere in the system, rcu_barrier() can and will return immediately.

    So if you need to wait for both a grace period and for all pre-existing callbacks, you will need to invoke both functions, with the pair depending on the flavor of RCU:

    - Either synchronize_rcu() or synchronize_rcu_expedited(), together with rcu_barrier()

    - Either synchronize_srcu() or synchronize_srcu_expedited(), together with and srcu_barrier()

    - synchronize_rcu_tasks() and rcu_barrier_tasks()

    - synchronize_tasks_trace() and rcu_barrier_tasks_trace()

    If necessary, you can use something like workqueues to execute the requisite pair of functions concurrently.

    See [rcubarrier.rst](/kernel/internals/rcu/rcubarrier.md) for more information.

---

# Using RCU to Protect Read-Mostly Linked Lists

_Peios Kernel / Internals / Read-copy-update (RCU)_

> One of the most common uses of RCU is protecting read-mostly linked lists (struct list_head in list.h). One big advantage of this approach is that all of the required memory ordering is provided by the list macros. This document describes…

<a id="rst-using-rcu-to-protect-read-mostly-linked-lists"></a>
<a id="rst-list-rcu-doc"></a>

One of the most common uses of RCU is protecting read-mostly linked lists (`struct list_head` in list.h).  One big advantage of this approach is that all of the required memory ordering is provided by the list macros. This document describes several list-based RCU use cases.

When iterating a list while holding the rcu_read_lock(), writers may modify the list.  The reader is guaranteed to see all of the elements which were added to the list before they acquired the rcu_read_lock() and are still on the list when they drop the rcu_read_unlock(). Elements which are added to, or removed from the list may or may not be seen.  If the writer calls list_replace_rcu(), the reader may see either the old element or the new element; they will not see both, nor will they see neither.

<a id="rst-example-1-read-mostly-list-deferred-destruction"></a>

## Example 1: Read-mostly list: Deferred Destruction

A widely used usecase for RCU lists in the kernel is lockless iteration over all processes in the system. `task_struct::tasks` represents the list node that links all the processes. The list can be traversed in parallel to any list additions or removals.

The traversal of the list is done using `for_each_process()` which is defined by the 2 macros:



```text
#define next_task(p) \
        list_entry_rcu((p)->tasks.next, struct task_struct, tasks)

#define for_each_process(p) \
        for (p = &init_task ; (p = next_task(p)) != &init_task ; )
```

The code traversing the list of all processes typically looks like:



```text
rcu_read_lock();
for_each_process(p) {
        /* Do something with p */
}
rcu_read_unlock();
```

The simplified and heavily inlined code for removing a process from a task list is:



```text
void release_task(struct task_struct *p)
{
        write_lock(&tasklist_lock);
        list_del_rcu(&p->tasks);
        write_unlock(&tasklist_lock);
        call_rcu(&p->rcu, delayed_put_task_struct);
}
```

When a process exits, `release_task()` calls `list_del_rcu(&p->tasks)` via \__exit_signal() and \__unhash_process() under `tasklist_lock` writer lock protection.  The list_del_rcu() invocation removes the task from the list of all tasks. The `tasklist_lock` prevents concurrent list additions/removals from corrupting the list. Readers using `for_each_process()` are not protected with the `tasklist_lock`. To prevent readers from noticing changes in the list pointers, the `task_struct` object is freed only after one or more grace periods elapse, with the help of call_rcu(), which is invoked via put_task_struct_rcu_user(). This deferring of destruction ensures that any readers traversing the list will see valid `p->tasks.next` pointers and deletion/freeing can happen in parallel with traversal of the list. This pattern is also called an **existence lock**, since RCU refrains from invoking the delayed_put_task_struct() callback function until all existing readers finish, which guarantees that the `task_struct` object in question will remain in existence until after the completion of all RCU readers that might possibly have a reference to that object.

<a id="rst-example-2-read-side-action-taken-outside-of-lock-no-in-place-updates"></a>

## Example 2: Read-Side Action Taken Outside of Lock: No In-Place Updates

Some reader-writer locking use cases compute a value while holding the read-side lock, but continue to use that value after that lock is released.  These use cases are often good candidates for conversion to RCU.  One prominent example involves network packet routing. Because the packet-routing data tracks the state of equipment outside of the computer, it will at times contain stale data.  Therefore, once the route has been computed, there is no need to hold the routing table static during transmission of the packet.  After all, you can hold the routing table static all you want, but that won't keep the external Internet from changing, and it is the state of the external Internet that really matters.  In addition, routing entries are typically added or deleted, rather than being modified in place.  This is a rare example of the finite speed of light and the non-zero size of atoms actually helping make synchronization be lighter weight.

A straightforward example of this type of RCU use case may be found in the system-call auditing support.  For example, a reader-writer locked implementation of `audit_filter_task()` might be as follows:



```text
static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
{
        struct audit_entry *e;
        enum audit_state   state;

        read_lock(&auditsc_lock);
        /* Note: audit_filter_mutex held by caller. */
        list_for_each_entry(e, &audit_tsklist, list) {
                if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
                        if (state == AUDIT_STATE_RECORD)
                                *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
                        read_unlock(&auditsc_lock);
                        return state;
                }
        }
        read_unlock(&auditsc_lock);
        return AUDIT_BUILD_CONTEXT;
}
```

Here the list is searched under the lock, but the lock is dropped before the corresponding value is returned.  By the time that this value is acted on, the list may well have been modified.  This makes sense, since if you are turning auditing off, it is OK to audit a few extra system calls.

This means that RCU can be easily applied to the read side, as follows:



```text
static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
{
        struct audit_entry *e;
        enum audit_state   state;

        rcu_read_lock();
        /* Note: audit_filter_mutex held by caller. */
        list_for_each_entry_rcu(e, &audit_tsklist, list) {
                if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
                        if (state == AUDIT_STATE_RECORD)
                                *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
                        rcu_read_unlock();
                        return state;
                }
        }
        rcu_read_unlock();
        return AUDIT_BUILD_CONTEXT;
}
```

The read_lock() and read_unlock() calls have become rcu_read_lock() and rcu_read_unlock(), respectively, and the list_for_each_entry() has become list_for_each_entry_rcu().  The **\_rcu()** list-traversal primitives add READ_ONCE() and diagnostic checks for incorrect use outside of an RCU read-side critical section.

The changes to the update side are also straightforward. A reader-writer lock might be used as follows for deletion and insertion in these simplified versions of audit_del_rule() and audit_add_rule():



```text
static inline int audit_del_rule(struct audit_rule *rule,
                                 struct list_head *list)
{
        struct audit_entry *e;

        write_lock(&auditsc_lock);
        list_for_each_entry(e, list, list) {
                if (!audit_compare_rule(rule, &e->rule)) {
                        list_del(&e->list);
                        write_unlock(&auditsc_lock);
                        return 0;
                }
        }
        write_unlock(&auditsc_lock);
        return -EFAULT;         /* No matching rule */
}

static inline int audit_add_rule(struct audit_entry *entry,
                                 struct list_head *list)
{
        write_lock(&auditsc_lock);
        if (entry->rule.flags & AUDIT_PREPEND) {
                entry->rule.flags &= ~AUDIT_PREPEND;
                list_add(&entry->list, list);
        } else {
                list_add_tail(&entry->list, list);
        }
        write_unlock(&auditsc_lock);
        return 0;
}
```

Following are the RCU equivalents for these two functions:



```text
static inline int audit_del_rule(struct audit_rule *rule,
                                 struct list_head *list)
{
        struct audit_entry *e;

        /* No need to use the _rcu iterator here, since this is the only
         * deletion routine. */
        list_for_each_entry(e, list, list) {
                if (!audit_compare_rule(rule, &e->rule)) {
                        list_del_rcu(&e->list);
                        call_rcu(&e->rcu, audit_free_rule);
                        return 0;
                }
        }
        return -EFAULT;         /* No matching rule */
}

static inline int audit_add_rule(struct audit_entry *entry,
                                 struct list_head *list)
{
        if (entry->rule.flags & AUDIT_PREPEND) {
                entry->rule.flags &= ~AUDIT_PREPEND;
                list_add_rcu(&entry->list, list);
        } else {
                list_add_tail_rcu(&entry->list, list);
        }
        return 0;
}
```

Normally, the write_lock() and write_unlock() would be replaced by a spin_lock() and a spin_unlock(). But in this case, all callers hold `audit_filter_mutex`, so no additional locking is required. The auditsc_lock can therefore be eliminated, since use of RCU eliminates the need for writers to exclude readers.

The list_del(), list_add(), and list_add_tail() primitives have been replaced by list_del_rcu(), list_add_rcu(), and list_add_tail_rcu(). The **\_rcu()** list-manipulation primitives add memory barriers that are needed on weakly ordered CPUs.  The list_del_rcu() primitive omits the pointer poisoning debug-assist code that would otherwise cause concurrent readers to fail spectacularly.

So, when readers can tolerate stale data and when entries are either added or deleted, without in-place modification, it is very easy to use RCU\!

<a id="rst-example-3-handling-in-place-updates"></a>

## Example 3: Handling In-Place Updates

The system-call auditing code does not update auditing rules in place.  However, if it did, the reader-writer-locked code to do so might look as follows (assuming only `field_count` is updated, otherwise, the added fields would need to be filled in):



```text
static inline int audit_upd_rule(struct audit_rule *rule,
                                 struct list_head *list,
                                 __u32 newaction,
                                 __u32 newfield_count)
{
        struct audit_entry *e;
        struct audit_entry *ne;

        write_lock(&auditsc_lock);
        /* Note: audit_filter_mutex held by caller. */
        list_for_each_entry(e, list, list) {
                if (!audit_compare_rule(rule, &e->rule)) {
                        e->rule.action = newaction;
                        e->rule.field_count = newfield_count;
                        write_unlock(&auditsc_lock);
                        return 0;
                }
        }
        write_unlock(&auditsc_lock);
        return -EFAULT;         /* No matching rule */
}
```

The RCU version creates a copy, updates the copy, then replaces the old entry with the newly updated entry.  This sequence of actions, allowing concurrent reads while making a copy to perform an update, is what gives RCU (*read-copy update*) its name.

The RCU version of audit_upd_rule() is as follows:



```text
static inline int audit_upd_rule(struct audit_rule *rule,
                                 struct list_head *list,
                                 __u32 newaction,
                                 __u32 newfield_count)
{
        struct audit_entry *e;
        struct audit_entry *ne;

        list_for_each_entry(e, list, list) {
                if (!audit_compare_rule(rule, &e->rule)) {
                        ne = kmalloc(sizeof(*entry), GFP_ATOMIC);
                        if (ne == NULL)
                                return -ENOMEM;
                        audit_copy_rule(&ne->rule, &e->rule);
                        ne->rule.action = newaction;
                        ne->rule.field_count = newfield_count;
                        list_replace_rcu(&e->list, &ne->list);
                        call_rcu(&e->rcu, audit_free_rule);
                        return 0;
                }
        }
        return -EFAULT;         /* No matching rule */
}
```

Again, this assumes that the caller holds `audit_filter_mutex`.  Normally, the writer lock would become a spinlock in this sort of code.

The update_lsm_rule() does something very similar, for those who would prefer to look at real Linux-kernel code.

Another use of this pattern can be found in the openswitch driver's *connection tracking table* code in `ct_limit_set()`.  The table holds connection tracking entries and has a limit on the maximum entries.  There is one such table per-zone and hence one *limit* per zone.  The zones are mapped to their limits through a hashtable using an RCU-managed hlist for the hash chains. When a new limit is set, a new limit object is allocated and `ct_limit_set()` is called to replace the old limit object with the new one using list_replace_rcu(). The old limit object is then freed after a grace period using kfree_rcu().

<a id="rst-example-4-eliminating-stale-data"></a>

## Example 4: Eliminating Stale Data

The auditing example above tolerates stale data, as do most algorithms that are tracking external state.  After all, given there is a delay from the time the external state changes before Linux becomes aware of the change, and so as noted earlier, a small quantity of additional RCU-induced staleness is generally not a problem.

However, there are many examples where stale data cannot be tolerated. One example in the Linux kernel is the System V IPC (see the shm_lock() function in ipc/shm.c).  This code checks a *deleted* flag under a per-entry spinlock, and, if the *deleted* flag is set, pretends that the entry does not exist.  For this to be helpful, the search function must return holding the per-entry spinlock, as shm_lock() does in fact do.

<a id="rst-quick-quiz"></a>

- **Quick Quiz:**

  For the deleted-flag technique to be helpful, why is it necessary to hold the per-entry lock while returning from the search function?

[Answer to Quick Quiz](<#rst-quick-quiz-answer>)

If the system-call audit module were to ever need to reject stale data, one way to accomplish this would be to add a `deleted` flag and a `lock` spinlock to the `audit_entry` structure, and modify audit_filter_task() as follows:



```text
static struct audit_entry *audit_filter_task(struct task_struct *tsk, char **key)
{
        struct audit_entry *e;
        enum audit_state   state;

        rcu_read_lock();
        list_for_each_entry_rcu(e, &audit_tsklist, list) {
                if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
                        spin_lock(&e->lock);
                        if (e->deleted) {
                                spin_unlock(&e->lock);
                                rcu_read_unlock();
                                return NULL;
                        }
                        rcu_read_unlock();
                        if (state == AUDIT_STATE_RECORD)
                                *key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
                        /* As long as e->lock is held, e is valid and
                         * its value is not stale */
                        return e;
                }
        }
        rcu_read_unlock();
        return NULL;
}
```

The `audit_del_rule()` function would need to set the `deleted` flag under the spinlock as follows:



```text
static inline int audit_del_rule(struct audit_rule *rule,
                                 struct list_head *list)
{
        struct audit_entry *e;

        /* No need to use the _rcu iterator here, since this
         * is the only deletion routine. */
        list_for_each_entry(e, list, list) {
                if (!audit_compare_rule(rule, &e->rule)) {
                        spin_lock(&e->lock);
                        list_del_rcu(&e->list);
                        e->deleted = 1;
                        spin_unlock(&e->lock);
                        call_rcu(&e->rcu, audit_free_rule);
                        return 0;
                }
        }
        return -EFAULT;         /* No matching rule */
}
```

This too assumes that the caller holds `audit_filter_mutex`.

Note that this example assumes that entries are only added and deleted. Additional mechanism is required to deal correctly with the update-in-place performed by audit_upd_rule().  For one thing, audit_upd_rule() would need to hold the locks of both the old `audit_entry` and its replacement while executing the list_replace_rcu().

<a id="rst-example-5-skipping-stale-objects"></a>

## Example 5: Skipping Stale Objects

For some use cases, reader performance can be improved by skipping stale objects during read-side list traversal, where stale objects are those that will be removed and destroyed after one or more grace periods. One such example can be found in the timerfd subsystem. When a `CLOCK_REALTIME` clock is reprogrammed (for example due to setting of the system time) then all programmed `timerfds` that depend on this clock get triggered and processes waiting on them are awakened in advance of their scheduled expiry. To facilitate this, all such timers are added to an RCU-managed `cancel_list` when they are setup in `timerfd_setup_cancel()`:



```text
static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)
{
        spin_lock(&ctx->cancel_lock);
        if ((ctx->clockid == CLOCK_REALTIME ||
             ctx->clockid == CLOCK_REALTIME_ALARM) &&
            (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {
                if (!ctx->might_cancel) {
                        ctx->might_cancel = true;
                        spin_lock(&cancel_lock);
                        list_add_rcu(&ctx->clist, &cancel_list);
                        spin_unlock(&cancel_lock);
                }
        } else {
                __timerfd_remove_cancel(ctx);
        }
        spin_unlock(&ctx->cancel_lock);
}
```

When a timerfd is freed (fd is closed), then the `might_cancel` flag of the timerfd object is cleared, the object removed from the `cancel_list` and destroyed, as shown in this simplified and inlined version of timerfd_release():



```text
int timerfd_release(struct inode *inode, struct file *file)
{
        struct timerfd_ctx *ctx = file->private_data;

        spin_lock(&ctx->cancel_lock);
        if (ctx->might_cancel) {
                ctx->might_cancel = false;
                spin_lock(&cancel_lock);
                list_del_rcu(&ctx->clist);
                spin_unlock(&cancel_lock);
        }
        spin_unlock(&ctx->cancel_lock);

        if (isalarm(ctx))
                alarm_cancel(&ctx->t.alarm);
        else
                hrtimer_cancel(&ctx->t.tmr);
        kfree_rcu(ctx, rcu);
        return 0;
}
```

If the `CLOCK_REALTIME` clock is set, for example by a time server, the hrtimer framework calls `timerfd_clock_was_set()` which walks the `cancel_list` and wakes up processes waiting on the timerfd. While iterating the `cancel_list`, the `might_cancel` flag is consulted to skip stale objects:



```text
void timerfd_clock_was_set(void)
{
        ktime_t moffs = ktime_mono_to_real(0);
        struct timerfd_ctx *ctx;
        unsigned long flags;

        rcu_read_lock();
        list_for_each_entry_rcu(ctx, &cancel_list, clist) {
                if (!ctx->might_cancel)
                        continue;
                spin_lock_irqsave(&ctx->wqh.lock, flags);
                if (ctx->moffs != moffs) {
                        ctx->moffs = KTIME_MAX;
                        ctx->ticks++;
                        wake_up_locked_poll(&ctx->wqh, EPOLLIN);
                }
                spin_unlock_irqrestore(&ctx->wqh.lock, flags);
        }
        rcu_read_unlock();
}
```

The key point is that because RCU-protected traversal of the `cancel_list` happens concurrently with object addition and removal, sometimes the traversal can access an object that has been removed from the list. In this example, a flag is used to skip such objects.

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

## Summary

Read-mostly list-based data structures that can tolerate stale data are the most amenable to use of RCU.  The simplest case is where entries are either added or deleted from the data structure (or atomically modified in place), but non-atomic in-place modifications can be handled by making a copy, updating the copy, then replacing the original with the copy. If stale data cannot be tolerated, then a *deleted* flag may be used in conjunction with a per-entry spinlock in order to allow the search function to reject newly deleted data.

<a id="rst-quick-quiz-answer"></a>

- **Answer to Quick Quiz:**

  For the deleted-flag technique to be helpful, why is it necessary to hold the per-entry lock while returning from the search function?

  If the search function drops the per-entry lock before returning, then the caller will be processing stale data in any case.  If it is really OK to be processing stale data, then you don't need a *deleted* flag.  If processing stale data really is a problem, then you need to hold the per-entry lock across all of the code that uses the value that was returned.

[Back to Quick Quiz](<#rst-quick-quiz>)

---

# Lockdep-RCU Splat

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Lockdep-RCU was added to the Linux kernel in early 2010 (http://lwn.net/Articles/371986/). This facility checks for some common misuses of the RCU API, most notably using one of the rcu_dereference() family to access an RCU-protected…

<a id="rst-lockdep-rcu-splat"></a>

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

Lockdep-RCU was added to the Linux kernel in early 2010 ([http://lwn.net/Articles/371986/](<http://lwn.net/Articles/371986/>)).  This facility checks for some common misuses of the RCU API, most notably using one of the rcu_dereference() family to access an RCU-protected pointer without the proper protection. When such misuse is detected, an lockdep-RCU splat is emitted.

The usual cause of a lockdep-RCU splat is someone accessing an RCU-protected data structure without either (1) being in the right kind of RCU read-side critical section or (2) holding the right update-side lock. This problem can therefore be serious: it might result in random memory overwriting or worse.  There can of course be false positives, this being the real world and all that.

So let's look at an example RCU lockdep splat from 3.0-rc5, one that has long since been fixed:



```text
=============================
WARNING: suspicious RCU usage
-----------------------------
block/cfq-iosched.c:2776 suspicious rcu_dereference_protected() usage!
```

other info that might help us debug this:



```text
rcu_scheduler_active = 1, debug_locks = 0
3 locks held by scsi_scan_6/1552:
#0:  (&shost->scan_mutex){+.+.}, at: [<ffffffff8145efca>]
scsi_scan_host_selected+0x5a/0x150
#1:  (&eq->sysfs_lock){+.+.}, at: [<ffffffff812a5032>]
elevator_exit+0x22/0x60
#2:  (&(&q->__queue_lock)->rlock){-.-.}, at: [<ffffffff812b6233>]
cfq_exit_queue+0x43/0x190

stack backtrace:
Pid: 1552, comm: scsi_scan_6 Not tainted 3.0.0-rc5 #17
Call Trace:
[<ffffffff810abb9b>] lockdep_rcu_dereference+0xbb/0xc0
[<ffffffff812b6139>] __cfq_exit_single_io_context+0xe9/0x120
[<ffffffff812b626c>] cfq_exit_queue+0x7c/0x190
[<ffffffff812a5046>] elevator_exit+0x36/0x60
[<ffffffff812a802a>] blk_cleanup_queue+0x4a/0x60
[<ffffffff8145cc09>] scsi_free_queue+0x9/0x10
[<ffffffff81460944>] __scsi_remove_device+0x84/0xd0
[<ffffffff8145dca3>] scsi_probe_and_add_lun+0x353/0xb10
[<ffffffff817da069>] ? error_exit+0x29/0xb0
[<ffffffff817d98ed>] ? _raw_spin_unlock_irqrestore+0x3d/0x80
[<ffffffff8145e722>] __scsi_scan_target+0x112/0x680
[<ffffffff812c690d>] ? trace_hardirqs_off_thunk+0x3a/0x3c
[<ffffffff817da069>] ? error_exit+0x29/0xb0
[<ffffffff812bcc60>] ? kobject_del+0x40/0x40
[<ffffffff8145ed16>] scsi_scan_channel+0x86/0xb0
[<ffffffff8145f0b0>] scsi_scan_host_selected+0x140/0x150
[<ffffffff8145f149>] do_scsi_scan_host+0x89/0x90
[<ffffffff8145f170>] do_scan_async+0x20/0x160
[<ffffffff8145f150>] ? do_scsi_scan_host+0x90/0x90
[<ffffffff810975b6>] kthread+0xa6/0xb0
[<ffffffff817db154>] kernel_thread_helper+0x4/0x10
[<ffffffff81066430>] ? finish_task_switch+0x80/0x110
[<ffffffff817d9c04>] ? retint_restore_args+0xe/0xe
[<ffffffff81097510>] ? __kthread_init_worker+0x70/0x70
[<ffffffff817db150>] ? gs_change+0xb/0xb
```

Line 2776 of block/cfq-iosched.c in v3.0-rc5 is as follows:



```text
if (rcu_dereference(ioc->ioc_data) == cic) {
```

This form says that it must be in a plain vanilla RCU read-side critical section, but the "other info" list above shows that this is not the case.  Instead, we hold three locks, one of which might be RCU related. And maybe that lock really does protect this reference.  If so, the fix is to inform RCU, perhaps by changing \__cfq_exit_single_io_context() to take the struct request_queue "q" from cfq_exit_queue() as an argument, which would permit us to invoke rcu_dereference_protected as follows:



```text
if (rcu_dereference_protected(ioc->ioc_data,
                              lockdep_is_held(&q->queue_lock)) == cic) {
```

With this change, there would be no lockdep-RCU splat emitted if this code was invoked either from within an RCU read-side critical section or with the -&gt;queue_lock held.  In particular, this would have suppressed the above lockdep-RCU splat because -&gt;queue_lock is held (see \#2 in the list above).

On the other hand, perhaps we really do need an RCU read-side critical section.  In this case, the critical section must span the use of the return value from rcu_dereference(), or at least until there is some reference count incremented or some such.  One way to handle this is to add rcu_read_lock() and rcu_read_unlock() as follows:



```text
rcu_read_lock();
if (rcu_dereference(ioc->ioc_data) == cic) {
        spin_lock(&ioc->lock);
        rcu_assign_pointer(ioc->ioc_data, NULL);
        spin_unlock(&ioc->lock);
}
rcu_read_unlock();
```

With this change, the rcu_dereference() is always within an RCU read-side critical section, which again would have suppressed the above lockdep-RCU splat.

But in this particular case, we don't actually dereference the pointer returned from rcu_dereference().  Instead, that pointer is just compared to the cic pointer, which means that the rcu_dereference() can be replaced by rcu_access_pointer() as follows:



```text
if (rcu_access_pointer(ioc->ioc_data) == cic) {
```

Because it is legal to invoke rcu_access_pointer() without protection, this change would also suppress the above lockdep-RCU splat.

---

# RCU and lockdep checking

_Peios Kernel / Internals / Read-copy-update (RCU)_

> All flavors of RCU have lockdep checking available, so that lockdep is aware of when each task enters and leaves any flavor of RCU read-side critical section. Each flavor of RCU is tracked separately (but note that this is not the case in…

<a id="rst-rcu-and-lockdep-checking"></a>

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

All flavors of RCU have lockdep checking available, so that lockdep is aware of when each task enters and leaves any flavor of RCU read-side critical section.  Each flavor of RCU is tracked separately (but note that this is not the case in 2.6.32 and earlier).  This allows lockdep's tracking to include RCU state, which can sometimes help when debugging deadlocks and the like.

In addition, RCU provides the following primitives that check lockdep's state:



```text
rcu_read_lock_held() for normal RCU.
rcu_read_lock_bh_held() for RCU-bh.
rcu_read_lock_sched_held() for RCU-sched.
rcu_read_lock_any_held() for any of normal RCU, RCU-bh, and RCU-sched.
srcu_read_lock_held() for SRCU.
rcu_read_lock_trace_held() for RCU Tasks Trace.
```

These functions are conservative, and will therefore return 1 if they aren't certain (for example, if CONFIG_DEBUG_LOCK_ALLOC is not set). This prevents things like WARN_ON(\!rcu_read_lock_held()) from giving false positives when lockdep is disabled.

In addition, a separate kernel config parameter CONFIG_PROVE_RCU enables checking of rcu_dereference() primitives:

> - **rcu_dereference(p):**
>
>   Check for RCU read-side critical section.
>
> - **rcu_dereference_bh(p):**
>
>   Check for RCU-bh read-side critical section.
>
> - **rcu_dereference_sched(p):**
>
>   Check for RCU-sched read-side critical section.
>
> - **srcu_dereference(p, sp):**
>
>   Check for SRCU read-side critical section.
>
> - **rcu_dereference_check(p, c):**
>
>   Use explicit check expression "c" along with rcu_read_lock_held().  This is useful in code that is invoked by both RCU readers and updaters.
>
> - **rcu_dereference_bh_check(p, c):**
>
>   Use explicit check expression "c" along with rcu_read_lock_bh_held().  This is useful in code that is invoked by both RCU-bh readers and updaters.
>
> - **rcu_dereference_sched_check(p, c):**
>
>   Use explicit check expression "c" along with rcu_read_lock_sched_held().  This is useful in code that is invoked by both RCU-sched readers and updaters.
>
> - **srcu_dereference_check(p, c):**
>
>   Use explicit check expression "c" along with srcu_read_lock_held().  This is useful in code that is invoked by both SRCU readers and updaters.
>
> - **rcu_dereference_raw(p):**
>
>   Don't check.  (Use sparingly, if at all.)
>
> - **rcu_dereference_raw_check(p):**
>
>   Don't do lockdep at all.  (Use sparingly, if at all.)
>
> - **rcu_dereference_protected(p, c):**
>
>   Use explicit check expression "c", and omit all barriers and compiler constraints.  This is useful when the data structure cannot change, for example, in code that is invoked only by updaters.
>
> - **rcu_access_pointer(p):**
>
>   Return the value of the pointer and omit all barriers, but retain the compiler constraints that prevent duplicating or coalescing.  This is useful when testing the value of the pointer itself, for example, against NULL.

The rcu_dereference_check() check expression can be any boolean expression, but would normally include a lockdep expression.  For a moderately ornate example, consider the following:



```text
file = rcu_dereference_check(fdt->fd[fd],
                             lockdep_is_held(&files->file_lock) ||
                             atomic_read(&files->count) == 1);
```

This expression picks up the pointer "fdt-&gt;fd\[fd\]" in an RCU-safe manner, and, if CONFIG_PROVE_RCU is configured, verifies that this expression is used in:

1. An RCU read-side critical section (implicit), or

2. with files-&gt;file_lock held, or

3. on an unshared files_struct.

In case (1), the pointer is picked up in an RCU-safe manner for vanilla RCU read-side critical sections, in case (2) the -&gt;file_lock prevents any change from taking place, and finally, in case (3) the current task is the only task accessing the file_struct, again preventing any change from taking place.  If the above statement was invoked only from updater code, it could instead be written as follows:



```text
file = rcu_dereference_protected(fdt->fd[fd],
                                 lockdep_is_held(&files->file_lock) ||
                                 atomic_read(&files->count) == 1);
```

This would verify cases \#2 and \#3 above, and furthermore lockdep would complain even if this was used in an RCU read-side critical section unless one of these two cases held.  Because rcu_dereference_protected() omits all barriers and compiler constraints, it generates better code than do the other flavors of rcu_dereference().  On the other hand, it is illegal to use rcu_dereference_protected() if either the RCU-protected pointer or the RCU-protected data that it points to can change concurrently.

Like rcu_dereference(), when lockdep is enabled, RCU list and hlist traversal primitives check for being called from within an RCU read-side critical section.  However, a lockdep expression can be passed to them as an additional optional argument.  With this lockdep expression, these traversal primitives will complain only if the lockdep expression is false and they are called from outside any RCU read-side critical section.

For example, the workqueue for_each_pwq() macro is intended to be used either within an RCU read-side critical section or with wq-&gt;mutex held. It is thus implemented as follows:



```text
#define for_each_pwq(pwq, wq)
        list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,
                                lock_is_held(&(wq->mutex).dep_map))
```

---

# RCU Concepts

_Peios Kernel / Internals / Read-copy-update (RCU)_

> The basic idea behind RCU (read-copy update) is to split destructive operations into two parts, one that prevents anyone from seeing the data item being destroyed, and one that actually carries out the destruction. A "grace period" must…

<a id="rst-rcu-concepts"></a>
<a id="rst-rcu-doc"></a>

The basic idea behind RCU (read-copy update) is to split destructive operations into two parts, one that prevents anyone from seeing the data item being destroyed, and one that actually carries out the destruction. A "grace period" must elapse between the two parts, and this grace period must be long enough that any readers accessing the item being deleted have since dropped their references.  For example, an RCU-protected deletion from a linked list would first remove the item from the list, wait for a grace period to elapse, then free the element.  See [listRCU.rst](/kernel/internals/rcu/listrcu.md) for more information on using RCU with linked lists.

<a id="rst-frequently-asked-questions"></a>

## Frequently Asked Questions

- Why would anyone want to use RCU?

  The advantage of RCU's two-part approach is that RCU readers need not acquire any locks, perform any atomic instructions, write to shared memory, or (on CPUs other than Alpha) execute any memory barriers.  The fact that these operations are quite expensive on modern CPUs is what gives RCU its performance advantages in read-mostly situations.  The fact that RCU readers need not acquire locks can also greatly simplify deadlock-avoidance code.

- How can the updater tell when a grace period has completed if the RCU readers give no indication when they are done?

  Just as with spinlocks, RCU readers are not permitted to block, switch to user-mode execution, or enter the idle loop. Therefore, as soon as a CPU is seen passing through any of these three states, we know that that CPU has exited any previous RCU read-side critical sections.  So, if we remove an item from a linked list, and then wait until all CPUs have switched context, executed in user mode, or executed in the idle loop, we can safely free up that item.

  Preemptible variants of RCU (CONFIG_PREEMPT_RCU) get the same effect, but require that the readers manipulate CPU-local counters.  These counters allow limited types of blocking within RCU read-side critical sections.  SRCU also uses CPU-local counters, and permits general blocking within RCU read-side critical sections.  These variants of RCU detect grace periods by sampling these counters.

- If I am running on a uniprocessor kernel, which can only do one thing at a time, why should I wait for a grace period?

  See [UP.rst](/kernel/internals/rcu/up.md) for more information.

- How can I see where RCU is currently used in the Linux kernel?

  Search for "rcu_read_lock", "rcu_read_unlock", "call_rcu", "rcu_read_lock_bh", "rcu_read_unlock_bh", "srcu_read_lock", "srcu_read_unlock", "synchronize_rcu", "synchronize_net", "synchronize_srcu", and the other RCU primitives.  Or grab one of the cscope databases from:

  ([http://www.rdrop.com/users/paulmck/RCU/linuxusage/rculocktab.html](<http://www.rdrop.com/users/paulmck/RCU/linuxusage/rculocktab.html>)).

- What guidelines should I follow when writing code that uses RCU?

  See [checklist.rst](/kernel/internals/rcu/checklist.md).

- Why the name "RCU"?

  "RCU" stands for "read-copy update". [listRCU.rst](/kernel/internals/rcu/listrcu.md) has more information on where this name came from, search for "read-copy update" to find it.

- I hear that RCU is patented?  What is with that?

  Yes, it is.  There are several known patents related to RCU, search for the string "Patent" in [Documentation/RCU/RTFP.txt](/kernel/internals/rcu/rtfp.md) to find them. Of these, one was allowed to lapse by the assignee, and the others have been contributed to the Linux kernel under GPL. Many (but not all) have long since expired. There are now also LGPL implementations of user-level RCU available ([https://liburcu.org/](<https://liburcu.org/>)).

- I hear that RCU needs work in order to support realtime kernels?

  Realtime-friendly RCU are enabled via the CONFIG_PREEMPTION kernel configuration parameter.

- Where can I find more information on RCU?

  See the [Documentation/RCU/RTFP.txt](/kernel/internals/rcu/rtfp.md) file. Or point your browser at ([https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit](<https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit>)) or ([https://docs.google.com/document/d/1GCdQC8SDbb54W1shjEXqGZ0Rq8a6kIeYutdSIajfpLA/edit?usp=sharing](<https://docs.google.com/document/d/1GCdQC8SDbb54W1shjEXqGZ0Rq8a6kIeYutdSIajfpLA/edit?usp=sharing>)).

---

# PROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference()

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Proper care and feeding of address and data dependencies is critically important to correct use of things like RCU. To this end, the pointers returned from the rcu_dereference() family of primitives carry address and data dependencies.…

<a id="rst-proper-care-and-feeding-of-return-values-from-rcu-dereference"></a>
<a id="rst-rcu-dereference-doc"></a>

Proper care and feeding of address and data dependencies is critically important to correct use of things like RCU.  To this end, the pointers returned from the rcu_dereference() family of primitives carry address and data dependencies.  These dependencies extend from the rcu_dereference() macro's load of the pointer to the later use of that pointer to compute either the address of a later memory access (representing an address dependency) or the value written by a later memory access (representing a data dependency).

Most of the time, these dependencies are preserved, permitting you to freely use values from rcu_dereference().  For example, dereferencing (prefix "\*"), field selection ("-&gt;"), assignment ("="), address-of ("&amp;"), casts, and addition or subtraction of constants all work quite naturally and safely.  However, because current compilers do not take either address or data dependencies into account it is still possible to get into trouble.

Follow these rules to preserve the address and data dependencies emanating from your calls to rcu_dereference() and friends, thus keeping your RCU readers working properly:

- You must use one of the rcu_dereference() family of primitives to load an RCU-protected pointer, otherwise CONFIG_PROVE_RCU will complain.  Worse yet, your code can see random memory-corruption bugs due to games that compilers and DEC Alpha can play. Without one of the rcu_dereference() primitives, compilers can reload the value, and won't your code have fun with two different values for a single pointer\!  Without rcu_dereference(), DEC Alpha can load a pointer, dereference that pointer, and return data preceding initialization that preceded the store of the pointer.  (As noted later, in recent kernels READ_ONCE() also prevents DEC Alpha from playing these tricks.)

  In addition, the volatile cast in rcu_dereference() prevents the compiler from deducing the resulting pointer value.  Please see the section entitled "EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH" for an example where the compiler can in fact deduce the exact value of the pointer, and thus cause misordering.

- In the special case where data is added but is never removed while readers are accessing the structure, READ_ONCE() may be used instead of rcu_dereference().  In this case, use of READ_ONCE() takes on the role of the lockless_dereference() primitive that was removed in v4.15.

- You are only permitted to use rcu_dereference() on pointer values. The compiler simply knows too much about integral values to trust it to carry dependencies through integer operations. There are a very few exceptions, namely that you can temporarily cast the pointer to uintptr_t in order to:

  - Set bits and clear bits down in the must-be-zero low-order bits of that pointer.  This clearly means that the pointer must have alignment constraints, for example, this does *not* work in general for char\* pointers.

  - XOR bits to translate pointers, as is done in some classic buddy-allocator algorithms.

  It is important to cast the value back to pointer before doing much of anything else with it.

- Avoid cancellation when using the "+" and "-" infix arithmetic operators.  For example, for a given variable "x", avoid "(x-(uintptr_t)x)" for char\* pointers.  The compiler is within its rights to substitute zero for this sort of expression, so that subsequent accesses no longer depend on the rcu_dereference(), again possibly resulting in bugs due to misordering.

  Of course, if "p" is a pointer from rcu_dereference(), and "a" and "b" are integers that happen to be equal, the expression "p+a-b" is safe because its value still necessarily depends on the rcu_dereference(), thus maintaining proper ordering.

- If you are using RCU to protect JITed functions, so that the "()" function-invocation operator is applied to a value obtained (directly or indirectly) from rcu_dereference(), you may need to interact directly with the hardware to flush instruction caches. This issue arises on some systems when a newly JITed function is using the same memory that was used by an earlier JITed function.

- Do not use the results from relational operators ("==", "\!=", "&gt;", "&gt;=", "&lt;", or "&lt;=") when dereferencing.  For example, the following (quite strange) code is buggy:



  ```text
  int *p;
  int *q;

  ...

  p = rcu_dereference(gp)
  q = &global_q;
  q += p > &oom_p;
  r1 = *q;  /* BUGGY!!! */
  ```

  As before, the reason this is buggy is that relational operators are often compiled using branches.  And as before, although weak-memory machines such as ARM or PowerPC do order stores after such branches, but can speculate loads, which can again result in misordering bugs.

- Be very careful about comparing pointers obtained from rcu_dereference() against non-NULL values.  As Linus Torvalds explained, if the two pointers are equal, the compiler could substitute the pointer you are comparing against for the pointer obtained from rcu_dereference().  For example:



  ```text
  p = rcu_dereference(gp);
  if (p == &default_struct)
          do_default(p->a);
  ```

  Because the compiler now knows that the value of "p" is exactly the address of the variable "default_struct", it is free to transform this code into the following:



  ```text
  p = rcu_dereference(gp);
  if (p == &default_struct)
          do_default(default_struct.a);
  ```

  On ARM and Power hardware, the load from "default_struct.a" can now be speculated, such that it might happen before the rcu_dereference().  This could result in bugs due to misordering.

  However, comparisons are OK in the following cases:

  - The comparison was against the NULL pointer.  If the compiler knows that the pointer is NULL, you had better not be dereferencing it anyway.  If the comparison is non-equal, the compiler is none the wiser.  Therefore, it is safe to compare pointers from rcu_dereference() against NULL pointers.

  - The pointer is never dereferenced after being compared. Since there are no subsequent dereferences, the compiler cannot use anything it learned from the comparison to reorder the non-existent subsequent dereferences. This sort of comparison occurs frequently when scanning RCU-protected circular linked lists.

    Note that if the pointer comparison is done outside of an RCU read-side critical section, and the pointer is never dereferenced, rcu_access_pointer() should be used in place of rcu_dereference().  In most cases, it is best to avoid accidental dereferences by testing the rcu_access_pointer() return value directly, without assigning it to a variable.

    Within an RCU read-side critical section, there is little reason to use rcu_access_pointer().

  - The comparison is against a pointer that references memory that was initialized "a long time ago."  The reason this is safe is that even if misordering occurs, the misordering will not affect the accesses that follow the comparison.  So exactly how long ago is "a long time ago"?  Here are some possibilities:

    - Compile time.

    - Boot time.

    - Module-init time for module code.

    - Prior to kthread creation for kthread code.

    - During some prior acquisition of the lock that we now hold.

    - Before mod_timer() time for a timer handler.

    There are many other possibilities involving the Linux kernel's wide array of primitives that cause code to be invoked at a later time.

  - The pointer being compared against also came from rcu_dereference().  In this case, both pointers depend on one rcu_dereference() or another, so you get proper ordering either way.

    That said, this situation can make certain RCU usage bugs more likely to happen.  Which can be a good thing, at least if they happen during testing.  An example of such an RCU usage bug is shown in the section titled "EXAMPLE OF AMPLIFIED RCU-USAGE BUG".

  - All of the accesses following the comparison are stores, so that a control dependency preserves the needed ordering. That said, it is easy to get control dependencies wrong. Please see the "CONTROL DEPENDENCIES" section of [Documentation/memory-barriers.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/memory-barriers.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for more details.

  - The pointers are not equal *and* the compiler does not have enough information to deduce the value of the pointer.  Note that the volatile cast in rcu_dereference() will normally prevent the compiler from knowing too much.

    However, please note that if the compiler knows that the pointer takes on only one of two values, a not-equal comparison will provide exactly the information that the compiler needs to deduce the value of the pointer.

- Disable any value-speculation optimizations that your compiler might provide, especially if you are making use of feedback-based optimizations that take data collected from prior runs.  Such value-speculation optimizations reorder operations by design.

  There is one exception to this rule:  Value-speculation optimizations that leverage the branch-prediction hardware are safe on strongly ordered systems (such as x86), but not on weakly ordered systems (such as ARM or Power).  Choose your compiler command-line options wisely\!

<a id="rst-example-of-amplified-rcu-usage-bug"></a>

## EXAMPLE OF AMPLIFIED RCU-USAGE BUG

Because updaters can run concurrently with RCU readers, RCU readers can see stale and/or inconsistent values.  If RCU readers need fresh or consistent values, which they sometimes do, they need to take proper precautions.  To see this, consider the following code fragment:



```text
struct foo {
        int a;
        int b;
        int c;
};
struct foo *gp1;
struct foo *gp2;

void updater(void)
{
        struct foo *p;

        p = kmalloc(...);
        if (p == NULL)
                deal_with_it();
        p->a = 42;  /* Each field in its own cache line. */
        p->b = 43;
        p->c = 44;
        rcu_assign_pointer(gp1, p);
        p->b = 143;
        p->c = 144;
        rcu_assign_pointer(gp2, p);
}

void reader(void)
{
        struct foo *p;
        struct foo *q;
        int r1, r2;

        rcu_read_lock();
        p = rcu_dereference(gp2);
        if (p == NULL)
                return;
        r1 = p->b;  /* Guaranteed to get 143. */
        q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
        if (p == q) {
                /* The compiler decides that q->c is same as p->c. */
                r2 = p->c; /* Could get 44 on weakly order system. */
        } else {
                r2 = p->c - r1; /* Unconditional access to p->c. */
        }
        rcu_read_unlock();
        do_something_with(r1, r2);
}
```

You might be surprised that the outcome (r1 == 143 &amp;&amp; r2 == 44) is possible, but you should not be.  After all, the updater might have been invoked a second time between the time reader() loaded into "r1" and the time that it loaded into "r2".  The fact that this same result can occur due to some reordering from the compiler and CPUs is beside the point.

But suppose that the reader needs a consistent view?

Then one approach is to use locking, for example, as follows:



```text
struct foo {
        int a;
        int b;
        int c;
        spinlock_t lock;
};
struct foo *gp1;
struct foo *gp2;

void updater(void)
{
        struct foo *p;

        p = kmalloc(...);
        if (p == NULL)
                deal_with_it();
        spin_lock(&p->lock);
        p->a = 42;  /* Each field in its own cache line. */
        p->b = 43;
        p->c = 44;
        spin_unlock(&p->lock);
        rcu_assign_pointer(gp1, p);
        spin_lock(&p->lock);
        p->b = 143;
        p->c = 144;
        spin_unlock(&p->lock);
        rcu_assign_pointer(gp2, p);
}

void reader(void)
{
        struct foo *p;
        struct foo *q;
        int r1, r2;

        rcu_read_lock();
        p = rcu_dereference(gp2);
        if (p == NULL)
                return;
        spin_lock(&p->lock);
        r1 = p->b;  /* Guaranteed to get 143. */
        q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
        if (p == q) {
                /* The compiler decides that q->c is same as p->c. */
                r2 = p->c; /* Locking guarantees r2 == 144. */
        } else {
                spin_lock(&q->lock);
                r2 = q->c - r1;
                spin_unlock(&q->lock);
        }
        rcu_read_unlock();
        spin_unlock(&p->lock);
        do_something_with(r1, r2);
}
```

As always, use the right tool for the job\!

<a id="rst-example-where-the-compiler-knows-too-much"></a>

## EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH

If a pointer obtained from rcu_dereference() compares not-equal to some other pointer, the compiler normally has no clue what the value of the first pointer might be.  This lack of knowledge prevents the compiler from carrying out optimizations that otherwise might destroy the ordering guarantees that RCU depends on.  And the volatile cast in rcu_dereference() should prevent the compiler from guessing the value.

But without rcu_dereference(), the compiler knows more than you might expect.  Consider the following code fragment:



```text
struct foo {
        int a;
        int b;
};
static struct foo variable1;
static struct foo variable2;
static struct foo *gp = &variable1;

void updater(void)
{
        initialize_foo(&variable2);
        rcu_assign_pointer(gp, &variable2);
        /*
         * The above is the only store to gp in this translation unit,
         * and the address of gp is not exported in any way.
         */
}

int reader(void)
{
        struct foo *p;

        p = gp;
        barrier();
        if (p == &variable1)
                return p->a; /* Must be variable1.a. */
        else
                return p->b; /* Must be variable2.b. */
}
```

Because the compiler can see all stores to "gp", it knows that the only possible values of "gp" are "variable1" on the one hand and "variable2" on the other.  The comparison in reader() therefore tells the compiler the exact value of "p" even in the not-equals case.  This allows the compiler to make the return values independent of the load from "gp", in turn destroying the ordering between this load and the loads of the return values.  This can result in "p-&gt;b" returning pre-initialization garbage values on weakly ordered systems.

In short, rcu_dereference() is *not* optional when you are going to dereference the resulting pointer.

<a id="rst-which-member-of-the-rcu-dereference-family-should-you-use"></a>

## WHICH MEMBER OF THE rcu_dereference() FAMILY SHOULD YOU USE?

First, please avoid using rcu_dereference_raw() and also please avoid using rcu_dereference_check() and rcu_dereference_protected() with a second argument with a constant value of 1 (or true, for that matter). With that caution out of the way, here is some guidance for which member of the rcu_dereference() to use in various situations:

1. If the access needs to be within an RCU read-side critical section, use rcu_dereference().  With the new consolidated RCU flavors, an RCU read-side critical section is entered using rcu_read_lock(), anything that disables bottom halves, anything that disables interrupts, or anything that disables preemption.  Please note that spinlock critical sections are also implied RCU read-side critical sections, even when they are preemptible, as they are in kernels built with CONFIG_PREEMPT_RT=y.

2. If the access might be within an RCU read-side critical section on the one hand, or protected by (say) my_lock on the other, use rcu_dereference_check(), for example:



   ```text
   p1 = rcu_dereference_check(p->rcu_protected_pointer,
                              lockdep_is_held(&my_lock));
   ```

3. If the access might be within an RCU read-side critical section on the one hand, or protected by either my_lock or your_lock on the other, again use rcu_dereference_check(), for example:



   ```text
   p1 = rcu_dereference_check(p->rcu_protected_pointer,
                              lockdep_is_held(&my_lock) ||
                              lockdep_is_held(&your_lock));
   ```

4. If the access is on the update side, so that it is always protected by my_lock, use rcu_dereference_protected():



   ```text
   p1 = rcu_dereference_protected(p->rcu_protected_pointer,
                                  lockdep_is_held(&my_lock));
   ```

   This can be extended to handle multiple locks as in \#3 above, and both can be extended to check other conditions as well.

5. If the protection is supplied by the caller, and is thus unknown to this code, that is the rare case when rcu_dereference_raw() is appropriate.  In addition, rcu_dereference_raw() might be appropriate when the lockdep expression would be excessively complex, except that a better approach in that case might be to take a long hard look at your synchronization design.  Still, there are data-locking cases where any one of a very large number of locks or reference counters suffices to protect the pointer, so rcu_dereference_raw() does have its place.

   However, its place is probably quite a bit smaller than one might expect given the number of uses in the current kernel. Ditto for its synonym, rcu_dereference_check( ... , 1), and its close relative, rcu_dereference_protected(... , 1).

<a id="rst-sparse-checking-of-rcu-protected-pointers"></a>

## SPARSE CHECKING OF RCU-PROTECTED POINTERS

The sparse static-analysis tool checks for non-RCU access to RCU-protected pointers, which can result in "interesting" bugs due to compiler optimizations involving invented loads and perhaps also load tearing. For example, suppose someone mistakenly does something like this:



```text
p = q->rcu_protected_pointer;
do_something_with(p->a);
do_something_else_with(p->b);
```

If register pressure is high, the compiler might optimize "p" out of existence, transforming the code to something like this:



```text
do_something_with(q->rcu_protected_pointer->a);
do_something_else_with(q->rcu_protected_pointer->b);
```

This could fatally disappoint your code if q-&gt;rcu_protected_pointer changed in the meantime.  Nor is this a theoretical problem:  Exactly this sort of bug cost Paul E. McKenney (and several of his innocent colleagues) a three-day weekend back in the early 1990s.

Load tearing could of course result in dereferencing a mashup of a pair of pointers, which also might fatally disappoint your code.

These problems could have been avoided simply by making the code instead read as follows:



```text
p = rcu_dereference(q->rcu_protected_pointer);
do_something_with(p->a);
do_something_else_with(p->b);
```

Unfortunately, these sorts of bugs can be extremely hard to spot during review.  This is where the sparse tool comes into play, along with the "\__rcu" marker.  If you mark a pointer declaration, whether in a structure or as a formal parameter, with "\__rcu", which tells sparse to complain if this pointer is accessed directly.  It will also cause sparse to complain if a pointer not marked with "\__rcu" is accessed using rcu_dereference() and friends.  For example, -&gt;rcu_protected_pointer might be declared as follows:



```text
struct foo __rcu *rcu_protected_pointer;
```

Use of "\__rcu" is opt-in.  If you choose not to use it, then you should ignore the sparse warnings.

---

# RCU and Unloadable Modules

_Peios Kernel / Internals / Read-copy-update (RCU)_

> [Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]

<a id="rst-rcu-and-unloadable-modules"></a>
<a id="rst-rcu-barrier"></a>

\[Originally published in LWN Jan. 14, 2007: [http://lwn.net/Articles/217484/](<http://lwn.net/Articles/217484/>)\]

RCU updaters sometimes use call_rcu() to initiate an asynchronous wait for a grace period to elapse.  This primitive takes a pointer to an rcu_head struct placed within the RCU-protected data structure and another pointer to a function that may be invoked later to free that structure. Code to delete an element p from the linked list from IRQ context might then be as follows:



```text
list_del_rcu(p);
call_rcu(&p->rcu, p_callback);
```

Since call_rcu() never blocks, this code can safely be used from within IRQ context. The function p_callback() might be defined as follows:



```text
static void p_callback(struct rcu_head *rp)
{
        struct pstruct *p = container_of(rp, struct pstruct, rcu);

        kfree(p);
}
```

<a id="rst-unloading-modules-that-use-call-rcu"></a>

## Unloading Modules That Use call_rcu()

But what if the p_callback() function is defined in an unloadable module?

If we unload the module while some RCU callbacks are pending, the CPUs executing these callbacks are going to be severely disappointed when they are later invoked, as fancifully depicted at [http://lwn.net/images/ns/kernel/rcu-drop.jpg](<http://lwn.net/images/ns/kernel/rcu-drop.jpg>).

We could try placing a synchronize_rcu() in the module-exit code path, but this is not sufficient. Although synchronize_rcu() does wait for a grace period to elapse, it does not wait for the callbacks to complete.

One might be tempted to try several back-to-back synchronize_rcu() calls, but this is still not guaranteed to work. If there is a very heavy RCU-callback load, then some of the callbacks might be deferred in order to allow other processing to proceed. For but one example, such deferral is required in realtime kernels in order to avoid excessive scheduling latencies.

<a id="rst-rcu-barrier-1"></a>

## rcu_barrier()

This situation can be handled by the rcu_barrier() primitive.  Rather than waiting for a grace period to elapse, rcu_barrier() waits for all outstanding RCU callbacks to complete.  Please note that rcu_barrier() does **not** imply synchronize_rcu(), in particular, if there are no RCU callbacks queued anywhere, rcu_barrier() is within its rights to return immediately, without waiting for anything, let alone a grace period.

Pseudo-code using rcu_barrier() is as follows:

> 1. Prevent any new RCU callbacks from being posted.
>
> 2. Execute rcu_barrier().
>
> 3. Allow the module to be unloaded.

There is also an srcu_barrier() function for SRCU, and you of course must match the flavor of srcu_barrier() with that of call_srcu(). If your module uses multiple srcu_struct structures, then it must also use multiple invocations of srcu_barrier() when unloading that module. For example, if it uses call_rcu(), call_srcu() on srcu_struct_1, and call_srcu() on srcu_struct_2, then the following three lines of code will be required when unloading:



```text
1  rcu_barrier();
2  srcu_barrier(&srcu_struct_1);
3  srcu_barrier(&srcu_struct_2);
```

If latency is of the essence, workqueues could be used to run these three functions concurrently.

An ancient version of the rcutorture module makes use of rcu_barrier() in its exit function as follows:



```text
 1  static void
 2  rcu_torture_cleanup(void)
 3  {
 4    int i;
 5
 6    fullstop = 1;
 7    if (shuffler_task != NULL) {
 8      VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
 9      kthread_stop(shuffler_task);
10    }
11    shuffler_task = NULL;
12
13    if (writer_task != NULL) {
14      VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
15      kthread_stop(writer_task);
16    }
17    writer_task = NULL;
18
19    if (reader_tasks != NULL) {
20      for (i = 0; i < nrealreaders; i++) {
21        if (reader_tasks[i] != NULL) {
22          VERBOSE_PRINTK_STRING(
23            "Stopping rcu_torture_reader task");
24          kthread_stop(reader_tasks[i]);
25        }
26        reader_tasks[i] = NULL;
27      }
28      kfree(reader_tasks);
29      reader_tasks = NULL;
30    }
31    rcu_torture_current = NULL;
32
33    if (fakewriter_tasks != NULL) {
34      for (i = 0; i < nfakewriters; i++) {
35        if (fakewriter_tasks[i] != NULL) {
36          VERBOSE_PRINTK_STRING(
37            "Stopping rcu_torture_fakewriter task");
38          kthread_stop(fakewriter_tasks[i]);
39        }
40        fakewriter_tasks[i] = NULL;
41      }
42      kfree(fakewriter_tasks);
43      fakewriter_tasks = NULL;
44    }
45
46    if (stats_task != NULL) {
47      VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
48      kthread_stop(stats_task);
49    }
50    stats_task = NULL;
51
52    /* Wait for all RCU callbacks to fire. */
53    rcu_barrier();
54
55    rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
56
57    if (cur_ops->cleanup != NULL)
58      cur_ops->cleanup();
59    if (atomic_read(&n_rcu_torture_error))
60      rcu_torture_print_module_parms("End of test: FAILURE");
61    else
62      rcu_torture_print_module_parms("End of test: SUCCESS");
63  }
```

Line 6 sets a global variable that prevents any RCU callbacks from re-posting themselves. This will not be necessary in most cases, since RCU callbacks rarely include calls to call_rcu(). However, the rcutorture module is an exception to this rule, and therefore needs to set this global variable.

Lines 7-50 stop all the kernel tasks associated with the rcutorture module. Therefore, once execution reaches line 53, no more rcutorture RCU callbacks will be posted. The rcu_barrier() call on line 53 waits for any pre-existing callbacks to complete.

Then lines 55-62 print status and do operation-specific cleanup, and then return, permitting the module-unload operation to be completed.

<a id="rst-rcubarrier-quiz-1"></a>

- **Quick Quiz \#1:**

  Is there any other situation where rcu_barrier() might be required?

[Answer to Quick Quiz \#1](<#rst-answer-rcubarrier-quiz-1>)

Your module might have additional complications. For example, if your module invokes call_rcu() from timers, you will need to first refrain from posting new timers, cancel (or wait for) all the already-posted timers, and only then invoke rcu_barrier() to wait for any remaining RCU callbacks to complete.

Of course, if your module uses call_rcu(), you will need to invoke rcu_barrier() before unloading.  Similarly, if your module uses call_srcu(), you will need to invoke srcu_barrier() before unloading, and on the same srcu_struct structure.  If your module uses call_rcu() **and** call_srcu(), then (as noted above) you will need to invoke rcu_barrier() **and** srcu_barrier().

<a id="rst-implementing-rcu-barrier"></a>

## Implementing rcu_barrier()

Dipankar Sarma's implementation of rcu_barrier() makes use of the fact that RCU callbacks are never reordered once queued on one of the per-CPU queues. His implementation queues an RCU callback on each of the per-CPU callback queues, and then waits until they have all started executing, at which point, all earlier RCU callbacks are guaranteed to have completed.

The original code for rcu_barrier() was roughly as follows:



```text
 1  void rcu_barrier(void)
 2  {
 3    BUG_ON(in_interrupt());
 4    /* Take cpucontrol mutex to protect against CPU hotplug */
 5    mutex_lock(&rcu_barrier_mutex);
 6    init_completion(&rcu_barrier_completion);
 7    atomic_set(&rcu_barrier_cpu_count, 1);
 8    on_each_cpu(rcu_barrier_func, NULL, 0, 1);
 9    if (atomic_dec_and_test(&rcu_barrier_cpu_count))
10      complete(&rcu_barrier_completion);
11    wait_for_completion(&rcu_barrier_completion);
12    mutex_unlock(&rcu_barrier_mutex);
13  }
```

Line 3 verifies that the caller is in process context, and lines 5 and 12 use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the global completion and counters at a time, which are initialized on lines 6 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is shown below. Note that the final "1" in on_each_cpu()'s argument list ensures that all the calls to rcu_barrier_func() will have completed before on_each_cpu() returns. Line 9 removes the initial count from rcu_barrier_cpu_count, and if this count is now zero, line 10 finalizes the completion, which prevents line 11 from blocking.  Either way, line 11 then waits (if needed) for the completion.

<a id="rst-rcubarrier-quiz-2"></a>

- **Quick Quiz \#2:**

  Why doesn't line 8 initialize rcu_barrier_cpu_count to zero, thereby avoiding the need for lines 9 and 10?

[Answer to Quick Quiz \#2](<#rst-answer-rcubarrier-quiz-2>)

This code was rewritten in 2008 and several times thereafter, but this still gives the general idea.

The rcu_barrier_func() runs on each CPU, where it invokes call_rcu() to post an RCU callback, as follows:



```text
 1  static void rcu_barrier_func(void *notused)
 2  {
 3    int cpu = smp_processor_id();
 4    struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
 5    struct rcu_head *head;
 6
 7    head = &rdp->barrier;
 8    atomic_inc(&rcu_barrier_cpu_count);
 9    call_rcu(head, rcu_barrier_callback);
10  }
```

Lines 3 and 4 locate RCU's internal per-CPU rcu_data structure, which contains the struct rcu_head that needed for the later call to call_rcu(). Line 7 picks up a pointer to this struct rcu_head, and line 8 increments the global counter. This counter will later be decremented by the callback. Line 9 then registers the rcu_barrier_callback() on the current CPU's queue.

The rcu_barrier_callback() function simply atomically decrements the rcu_barrier_cpu_count variable and finalizes the completion when it reaches zero, as follows:



```text
1  static void rcu_barrier_callback(struct rcu_head *notused)
2  {
3    if (atomic_dec_and_test(&rcu_barrier_cpu_count))
4      complete(&rcu_barrier_completion);
5  }
```

<a id="rst-rcubarrier-quiz-3"></a>

- **Quick Quiz \#3:**

  What happens if CPU 0's rcu_barrier_func() executes immediately (thus incrementing rcu_barrier_cpu_count to the value one), but the other CPU's rcu_barrier_func() invocations are delayed for a full grace period? Couldn't this result in rcu_barrier() returning prematurely?

[Answer to Quick Quiz \#3](<#rst-answer-rcubarrier-quiz-3>)

The current rcu_barrier() implementation is more complex, due to the need to avoid disturbing idle CPUs (especially on battery-powered systems) and the need to minimally disturb non-idle CPUs in real-time systems. In addition, a great many optimizations have been applied.  However, the code above illustrates the concepts.

<a id="rst-rcu-barrier-summary"></a>

## rcu_barrier() Summary

The rcu_barrier() primitive is used relatively infrequently, since most code using RCU is in the core kernel rather than in modules. However, if you are using RCU from an unloadable module, you need to use rcu_barrier() so that your module may be safely unloaded.

<a id="rst-answers-to-quick-quizzes"></a>

## Answers to Quick Quizzes

<a id="rst-answer-rcubarrier-quiz-1"></a>

- **Quick Quiz \#1:**

  Is there any other situation where rcu_barrier() might be required?

- **Answer:**

  Interestingly enough, rcu_barrier() was not originally implemented for module unloading. Nikita Danilov was using RCU in a filesystem, which resulted in a similar situation at filesystem-unmount time. Dipankar Sarma coded up rcu_barrier() in response, so that Nikita could invoke it during the filesystem-unmount process.

  Much later, yours truly hit the RCU module-unload problem when implementing rcutorture, and found that rcu_barrier() solves this problem as well.

[Back to Quick Quiz \#1](<#rst-rcubarrier-quiz-1>)

<a id="rst-answer-rcubarrier-quiz-2"></a>

- **Quick Quiz \#2:**

  Why doesn't line 8 initialize rcu_barrier_cpu_count to zero, thereby avoiding the need for lines 9 and 10?

- **Answer:**

  Suppose that the on_each_cpu() function shown on line 8 was delayed, so that CPU 0's rcu_barrier_func() executed and the corresponding grace period elapsed, all before CPU 1's rcu_barrier_func() started executing.  This would result in rcu_barrier_cpu_count being decremented to zero, so that line 11's wait_for_completion() would return immediately, failing to wait for CPU 1's callbacks to be invoked.

  Note that this was not a problem when the rcu_barrier() code was first added back in 2005.  This is because on_each_cpu() disables preemption, which acted as an RCU read-side critical section, thus preventing CPU 0's grace period from completing until on_each_cpu() had dealt with all of the CPUs.

  However, with the RCU flavor consolidation around v4.20, this possibility was once again ruled out, because the consolidated RCU once again waits on nonpreemptible regions of code.

  Nevertheless, that extra count might still be a good idea. Relying on these sort of accidents of implementation can result in later surprise bugs when the implementation changes.

[Back to Quick Quiz \#2](<#rst-rcubarrier-quiz-2>)

<a id="rst-answer-rcubarrier-quiz-3"></a>

- **Quick Quiz \#3:**

  What happens if CPU 0's rcu_barrier_func() executes immediately (thus incrementing rcu_barrier_cpu_count to the value one), but the other CPU's rcu_barrier_func() invocations are delayed for a full grace period? Couldn't this result in rcu_barrier() returning prematurely?

- **Answer:**

  This cannot happen. The reason is that on_each_cpu() has its last argument, the wait flag, set to "1". This flag is passed through to smp_call_function() and further to smp_call_function_on_cpu(), causing this latter to spin until the cross-CPU invocation of rcu_barrier_func() has completed. This by itself would prevent a grace period from completing on non-CONFIG_PREEMPTION kernels, since each CPU must undergo a context switch (or other quiescent state) before the grace period can complete. However, this is of no use in CONFIG_PREEMPTION kernels.

  Therefore, on_each_cpu() disables preemption across its call to smp_call_function() and also across the local call to rcu_barrier_func(). Because recent RCU implementations treat preemption-disabled regions of code as RCU read-side critical sections, this prevents grace periods from completing. This means that all CPUs have executed rcu_barrier_func() before the first rcu_barrier_callback() can possibly execute, in turn preventing rcu_barrier_cpu_count from prematurely reaching zero.

  But if on_each_cpu() ever decides to forgo disabling preemption, as might well happen due to real-time latency considerations, initializing rcu_barrier_cpu_count to one will save the day.

[Back to Quick Quiz \#3](<#rst-rcubarrier-quiz-3>)

---

# Using RCU hlist_nulls to protect list and objects

_Peios Kernel / Internals / Read-copy-update (RCU)_

> This section describes how to use hlist_nulls to protect read-mostly linked lists and objects using SLAB_TYPESAFE_BY_RCU allocations.

<a id="rst-using-rcu-hlist-nulls-to-protect-list-and-objects"></a>

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

This section describes how to use hlist_nulls to protect read-mostly linked lists and objects using SLAB_TYPESAFE_BY_RCU allocations.

Please read the basics in [listRCU.rst](/kernel/internals/rcu/listrcu.md).

<a id="rst-using-nulls"></a>

## Using 'nulls'

Using special makers (called 'nulls') is a convenient way to solve following problem.

Without 'nulls', a typical RCU linked list managing objects which are allocated with SLAB_TYPESAFE_BY_RCU kmem_cache can use the following algorithms.  Following examples assume 'obj' is a pointer to such objects, which is having below type.



```text
struct object {
  struct hlist_node obj_node;
  atomic_t refcnt;
  unsigned int key;
};
```

<a id="rst-lookup-algorithm"></a>

### 1) Lookup algorithm



```text
begin:
rcu_read_lock();
obj = lockless_lookup(key);
if (obj) {
  if (!try_get_ref(obj)) { // might fail for free objects
    rcu_read_unlock();
    goto begin;
  }
  /*
  * Because a writer could delete object, and a writer could
  * reuse these object before the RCU grace period, we
  * must check key after getting the reference on object
  */
  if (obj->key != key) { // not the object we expected
    put_ref(obj);
    rcu_read_unlock();
    goto begin;
  }
}
rcu_read_unlock();
```

Beware that lockless_lookup(key) cannot use traditional hlist_for_each_entry_rcu() but a version with an additional memory barrier (smp_rmb())



```text
lockless_lookup(key)
{
  struct hlist_node *node, *next;
  for (pos = rcu_dereference((head)->first);
       pos && ({ next = pos->next; smp_rmb(); prefetch(next); 1; }) &&
       ({ obj = hlist_entry(pos, typeof(*obj), obj_node); 1; });
       pos = rcu_dereference(next))
    if (obj->key == key)
      return obj;
  return NULL;
}
```

And note the traditional hlist_for_each_entry_rcu() misses this smp_rmb():



```text
struct hlist_node *node;
for (pos = rcu_dereference((head)->first);
     pos && ({ prefetch(pos->next); 1; }) &&
     ({ obj = hlist_entry(pos, typeof(*obj), obj_node); 1; });
     pos = rcu_dereference(pos->next))
  if (obj->key == key)
    return obj;
return NULL;
```

Quoting Corey Minyard:



```text
"If the object is moved from one list to another list in-between the
time the hash is calculated and the next field is accessed, and the
object has moved to the end of a new list, the traversal will not
complete properly on the list it should have, since the object will
be on the end of the new list and there's not a way to tell it's on a
new list and restart the list traversal. I think that this can be
solved by pre-fetching the "next" field (with proper barriers) before
checking the key."
```

<a id="rst-insertion-algorithm"></a>

### 2) Insertion algorithm

We need to make sure a reader cannot read the new 'obj-&gt;obj_node.next' value and previous value of 'obj-&gt;key'. Otherwise, an item could be deleted from a chain, and inserted into another chain. If new chain was empty before the move, 'next' pointer is NULL, and lockless reader can not detect the fact that it missed following items in original chain.



```text
/*
 * Please note that new inserts are done at the head of list,
 * not in the middle or end.
 */
obj = kmem_cache_alloc(...);
lock_chain(); // typically a spin_lock()
obj->key = key;
atomic_set_release(&obj->refcnt, 1); // key before refcnt
hlist_add_head_rcu(&obj->obj_node, list);
unlock_chain(); // typically a spin_unlock()
```

<a id="rst-removal-algorithm"></a>

### 3) Removal algorithm

Nothing special here, we can use a standard RCU hlist deletion. But thanks to SLAB_TYPESAFE_BY_RCU, beware a deleted object can be reused very very fast (before the end of RCU grace period)



```text
if (put_last_reference_on(obj) {
  lock_chain(); // typically a spin_lock()
  hlist_del_init_rcu(&obj->obj_node);
  unlock_chain(); // typically a spin_unlock()
  kmem_cache_free(cachep, obj);
}
```

---

<a id="rst-avoiding-extra-smp-rmb"></a>

## Avoiding extra smp_rmb()

With hlist_nulls we can avoid extra smp_rmb() in lockless_lookup().

For example, if we choose to store the slot number as the 'nulls' end-of-list marker for each slot of the hash table, we can detect a race (some writer did a delete and/or a move of an object to another chain) checking the final 'nulls' value if the lookup met the end of chain. If final 'nulls' value is not the slot number, then we must restart the lookup at the beginning. If the object was moved to the same chain, then the reader doesn't care: It might occasionally scan the list again without harm.

Note that using hlist_nulls means the type of 'obj_node' field of 'struct object' becomes 'struct hlist_nulls_node'.

<a id="rst-lookup-algorithm-1"></a>

### 1) lookup algorithm



```text
head = &table[slot];
begin:
rcu_read_lock();
hlist_nulls_for_each_entry_rcu(obj, node, head, obj_node) {
  if (obj->key == key) {
    if (!try_get_ref(obj)) { // might fail for free objects
      rcu_read_unlock();
      goto begin;
    }
    if (obj->key != key) { // not the object we expected
      put_ref(obj);
      rcu_read_unlock();
      goto begin;
    }
    goto out;
  }
}

// If the nulls value we got at the end of this lookup is
// not the expected one, we must restart lookup.
// We probably met an item that was moved to another chain.
if (get_nulls_value(node) != slot) {
  put_ref(obj);
  rcu_read_unlock();
  goto begin;
}
obj = NULL;

out:
rcu_read_unlock();
```

<a id="rst-insert-algorithm"></a>

### 2) Insert algorithm

Same to the above one, but uses hlist_nulls_add_head_rcu() instead of hlist_add_head_rcu().



```text
/*
 * Please note that new inserts are done at the head of list,
 * not in the middle or end.
 */
obj = kmem_cache_alloc(cachep);
lock_chain(); // typically a spin_lock()
obj->key = key;
atomic_set_release(&obj->refcnt, 1); // key before refcnt
/*
 * insert obj in RCU way (readers might be traversing chain)
 */
hlist_nulls_add_head_rcu(&obj->obj_node, list);
unlock_chain(); // typically a spin_unlock()
```

---

# Reference-count design for elements of lists/arrays protected by RCU

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Please note that the percpu-ref feature is likely your first stop if you need to combine reference counts and RCU. Please see include/linux/percpu-refcount.h for more information. However, in those unusual cases where percpu-ref would…

<a id="rst-reference-count-design-for-elements-of-lists-arrays-protected-by-rcu"></a>

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

Please note that the percpu-ref feature is likely your first stop if you need to combine reference counts and RCU.  Please see include/linux/percpu-refcount.h for more information.  However, in those unusual cases where percpu-ref would consume too much memory, please read on.

---

Reference counting on elements of lists which are protected by traditional reader/writer spinlocks or semaphores are straightforward:

CODE LISTING A:



```text
1.                                      2.
add()                                   search_and_reference()
{                                       {
    alloc_object                            read_lock(&list_lock);
    ...                                     search_for_element
    atomic_set(&el->rc, 1);                 atomic_inc(&el->rc);
    write_lock(&list_lock);                  ...
    add_element                             read_unlock(&list_lock);
    ...                                     ...
    write_unlock(&list_lock);          }
}

3.                                      4.
release_referenced()                    delete()
{                                       {
    ...                                     write_lock(&list_lock);
    if(atomic_dec_and_test(&el->rc))        ...
        kfree(el);
    ...                                     remove_element
}                                           write_unlock(&list_lock);
                                            ...
                                            if (atomic_dec_and_test(&el->rc))
                                                kfree(el);
                                            ...
                                        }
```

If this list/array is made lock free using RCU as in changing the write_lock() in add() and delete() to spin_lock() and changing read_lock() in search_and_reference() to rcu_read_lock(), the atomic_inc() in search_and_reference() could potentially hold reference to an element which has already been deleted from the list/array.  Use atomic_inc_not_zero() in this scenario as follows:

CODE LISTING B:



```text
1.                                      2.
add()                                   search_and_reference()
{                                       {
    alloc_object                            rcu_read_lock();
    ...                                     search_for_element
    atomic_set(&el->rc, 1);                 if (!atomic_inc_not_zero(&el->rc)) {
    spin_lock(&list_lock);                      rcu_read_unlock();
                                                return FAIL;
    add_element                             }
    ...                                     ...
    spin_unlock(&list_lock);                rcu_read_unlock();
}                                       }
3.                                      4.
release_referenced()                    delete()
{                                       {
    ...                                     spin_lock(&list_lock);
    if (atomic_dec_and_test(&el->rc))       ...
        call_rcu(&el->head, el_free);       remove_element
    ...                                     spin_unlock(&list_lock);
}                                           ...
                                            if (atomic_dec_and_test(&el->rc))
                                                call_rcu(&el->head, el_free);
                                            ...
                                        }
```

Sometimes, a reference to the element needs to be obtained in the update (write) stream.  In such cases, atomic_inc_not_zero() might be overkill, since we hold the update-side spinlock.  One might instead use atomic_inc() in such cases.

It is not always convenient to deal with "FAIL" in the search_and_reference() code path.  In such cases, the atomic_dec_and_test() may be moved from delete() to el_free() as follows:

CODE LISTING C:



```text
1.                                      2.
add()                                   search_and_reference()
{                                       {
    alloc_object                            rcu_read_lock();
    ...                                     search_for_element
    atomic_set(&el->rc, 1);                 atomic_inc(&el->rc);
    spin_lock(&list_lock);                  ...

    add_element                             rcu_read_unlock();
    ...                                 }
    spin_unlock(&list_lock);            4.
}                                       delete()
3.                                      {
release_referenced()                        spin_lock(&list_lock);
{                                           ...
    ...                                     remove_element
    if (atomic_dec_and_test(&el->rc))       spin_unlock(&list_lock);
        kfree(el);                          ...
    ...                                     call_rcu(&el->head, el_free);
}                                           ...
5.                                      }
void el_free(struct rcu_head *rhp)
{
    release_referenced();
}
```

The key point is that the initial reference added by add() is not removed until after a grace period has elapsed following removal.  This means that search_and_reference() cannot find this element, which means that the value of el-&gt;rc cannot increase.  Thus, once it reaches zero, there are no readers that can or ever will be able to reference the element.  The element can therefore safely be freed.  This in turn guarantees that if any reader finds the element, that reader may safely acquire a reference without checking the value of the reference counter.

A clear advantage of the RCU-based pattern in listing C over the one in listing B is that any call to search_and_reference() that locates a given object will succeed in obtaining a reference to that object, even given a concurrent invocation of delete() for that same object. Similarly, a clear advantage of both listings B and C over listing A is that a call to delete() is not delayed even if there are an arbitrarily large number of calls to search_and_reference() searching for the same object that delete() was invoked on.  Instead, all that is delayed is the eventual invocation of kfree(), which is usually not a problem on modern computer systems, even the small ones.

In cases where delete() can sleep, synchronize_rcu() can be called from delete(), so that el_free() can be subsumed into delete as follows:



```text
4.
delete()
{
    spin_lock(&list_lock);
    ...
    remove_element
    spin_unlock(&list_lock);
    ...
    synchronize_rcu();
    if (atomic_dec_and_test(&el->rc))
        kfree(el);
    ...
}
```

As additional examples in the kernel, the pattern in listing C is used by reference counting of struct pid, while the pattern in listing B is used by struct posix_acl.

---

# Using RCU's CPU Stall Detector

_Peios Kernel / Internals / Read-copy-update (RCU)_

> This document first discusses what sorts of issues RCU's CPU stall detector can locate, and then discusses kernel parameters and Kconfig options that can be used to fine-tune the detector's operation. Finally, this document explains the…

<a id="rst-using-rcu-s-cpu-stall-detector"></a>

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

This document first discusses what sorts of issues RCU's CPU stall detector can locate, and then discusses kernel parameters and Kconfig options that can be used to fine-tune the detector's operation.  Finally, this document explains the stall detector's "splat" format.

<a id="rst-what-causes-rcu-cpu-stall-warnings"></a>

## What Causes RCU CPU Stall Warnings?

So your kernel printed an RCU CPU stall warning.  The next question is "What caused it?"  The following problems can result in RCU CPU stall warnings:

- A CPU looping in an RCU read-side critical section.

- A CPU looping with interrupts disabled.

- A CPU looping with preemption disabled.

- A CPU looping with bottom halves disabled.

- For \!CONFIG_PREEMPTION kernels, a CPU looping anywhere in the kernel without potentially invoking schedule().  If the looping in the kernel is really expected and desirable behavior, you might need to add some calls to cond_resched().

- Booting Linux using a console connection that is too slow to keep up with the boot-time console-message rate.  For example, a 115Kbaud serial console can be *way* too slow to keep up with boot-time message rates, and will frequently result in RCU CPU stall warning messages.  Especially if you have added debug printk()s.

- Anything that prevents RCU's grace-period kthreads from running. This can result in the "All QSes seen" console-log message. This message will include information on when the kthread last ran and how often it should be expected to run.  It can also result in the `rcu_.*kthread starved for` console-log message, which will include additional debugging information.

- A CPU-bound real-time task in a CONFIG_PREEMPTION kernel, which might happen to preempt a low-priority task in the middle of an RCU read-side critical section.   This is especially damaging if that low-priority task is not permitted to run on any other CPU, in which case the next RCU grace period can never complete, which will eventually cause the system to run out of memory and hang. While the system is in the process of running itself out of memory, you might see stall-warning messages.

- A CPU-bound real-time task in a CONFIG_PREEMPT_RT kernel that is running at a higher priority than the RCU softirq threads. This will prevent RCU callbacks from ever being invoked, and in a CONFIG_PREEMPT_RCU kernel will further prevent RCU grace periods from ever completing.  Either way, the system will eventually run out of memory and hang.  In the CONFIG_PREEMPT_RCU case, you might see stall-warning messages.

  You can use the rcutree.kthread_prio kernel boot parameter to increase the scheduling priority of RCU's kthreads, which can help avoid this problem.  However, please note that doing this can increase your system's context-switch rate and thus degrade performance.

- A periodic interrupt whose handler takes longer than the time interval between successive pairs of interrupts.  This can prevent RCU's kthreads and softirq handlers from running. Note that certain high-overhead debugging options, for example the function_graph tracer, can result in interrupt handler taking considerably longer than normal, which can in turn result in RCU CPU stall warnings.

- Testing a workload on a fast system, tuning the stall-warning timeout down to just barely avoid RCU CPU stall warnings, and then running the same workload with the same stall-warning timeout on a slow system.  Note that thermal throttling and on-demand governors can cause a single system to be sometimes fast and sometimes slow\!

- A hardware or software issue shuts off the scheduler-clock interrupt on a CPU that is not in dyntick-idle mode.  This problem really has happened, and seems to be most likely to result in RCU CPU stall warnings for CONFIG_NO_HZ_COMMON=n kernels.

- A hardware or software issue that prevents time-based wakeups from occurring.  These issues can range from misconfigured or buggy timer hardware through bugs in the interrupt or exception path (whether hardware, firmware, or software) through bugs in Linux's timer subsystem through bugs in the scheduler, and, yes, even including bugs in RCU itself.  It can also result in the `rcu_.*timer wakeup didn't happen for` console-log message, which will include additional debugging information.

- A timer issue causes time to appear to jump forward, so that RCU believes that the RCU CPU stall-warning timeout has been exceeded when in fact much less time has passed.  This could be due to timer hardware bugs, timer driver bugs, or even corruption of the "jiffies" global variable.  These sorts of timer hardware and driver bugs are not uncommon when testing new hardware.

- A low-level kernel issue that either fails to invoke one of the variants of rcu_eqs_enter(true), rcu_eqs_exit(true), ct_idle_enter(), ct_idle_exit(), ct_irq_enter(), or ct_irq_exit() on the one hand, or that invokes one of them too many times on the other. Historically, the most frequent issue has been an omission of either irq_enter() or irq_exit(), which in turn invoke ct_irq_enter() or ct_irq_exit(), respectively.  Building your kernel with CONFIG_RCU_EQS_DEBUG=y can help track down these types of issues, which sometimes arise in architecture-specific code.

- A bug in the RCU implementation.

- A hardware failure.  This is quite unlikely, but is not at all uncommon in large datacenter.  In one memorable case some decades back, a CPU failed in a running system, becoming unresponsive, but not causing an immediate crash.  This resulted in a series of RCU CPU stall warnings, eventually leading to the realization that the CPU had failed.

The RCU, RCU-sched, RCU-tasks, and RCU-tasks-trace implementations have CPU stall warning.  Note that SRCU does *not* have CPU stall warnings. Please note that RCU only detects CPU stalls when there is a grace period in progress.  No grace period, no CPU stall warnings.

To diagnose the cause of the stall, inspect the stack traces. The offending function will usually be near the top of the stack. If you have a series of stall warnings from a single extended stall, comparing the stack traces can often help determine where the stall is occurring, which will usually be in the function nearest the top of that portion of the stack which remains the same from trace to trace. If you can reliably trigger the stall, ftrace can be quite helpful.

RCU bugs can often be debugged with the help of CONFIG_RCU_TRACE and with RCU's event tracing.  For information on RCU's event tracing, see include/trace/events/rcu.h.

<a id="rst-fine-tuning-the-rcu-cpu-stall-detector"></a>

## Fine-Tuning the RCU CPU Stall Detector

The rcuupdate.rcu_cpu_stall_suppress module parameter disables RCU's CPU stall detector, which detects conditions that unduly delay RCU grace periods.  This module parameter enables CPU stall detection by default, but may be overridden via boot-time parameter or at runtime via sysfs. The stall detector's idea of what constitutes "unduly delayed" is controlled by a set of kernel configuration variables and cpp macros:

<a id="rst-config-rcu-cpu-stall-timeout"></a>

### CONFIG_RCU_CPU_STALL_TIMEOUT

> This kernel configuration parameter defines the period of time that RCU will wait from the beginning of a grace period until it issues an RCU CPU stall warning.  This time period is normally 21 seconds.
>
> This configuration parameter may be changed at runtime via the /sys/module/rcupdate/parameters/rcu_cpu_stall_timeout, however this parameter is checked only at the beginning of a cycle. So if you are 10 seconds into a 40-second stall, setting this sysfs parameter to (say) five will shorten the timeout for the *next* stall, or the following warning for the current stall (assuming the stall lasts long enough).  It will not affect the timing of the next warning for the current stall.
>
> Stall-warning messages may be enabled and disabled completely via /sys/module/rcupdate/parameters/rcu_cpu_stall_suppress.

<a id="rst-config-rcu-exp-cpu-stall-timeout"></a>

### CONFIG_RCU_EXP_CPU_STALL_TIMEOUT

> Same as the CONFIG_RCU_CPU_STALL_TIMEOUT parameter but only for the expedited grace period. This parameter defines the period of time that RCU will wait from the beginning of an expedited grace period until it issues an RCU CPU stall warning. This time period is normally 20 milliseconds on Android devices.  A zero value causes the CONFIG_RCU_CPU_STALL_TIMEOUT value to be used, after conversion to milliseconds.
>
> This configuration parameter may be changed at runtime via the /sys/module/rcupdate/parameters/rcu_exp_cpu_stall_timeout, however this parameter is checked only at the beginning of a cycle. If you are in a current stall cycle, setting it to a new value will change the timeout for the -next- stall.
>
> Stall-warning messages may be enabled and disabled completely via /sys/module/rcupdate/parameters/rcu_cpu_stall_suppress.

<a id="rst-rcu-stall-delay-delta"></a>

### RCU_STALL_DELAY_DELTA

> Although the lockdep facility is extremely useful, it does add some overhead.  Therefore, under CONFIG_PROVE_RCU, the RCU_STALL_DELAY_DELTA macro allows five extra seconds before giving an RCU CPU stall warning message.  (This is a cpp macro, not a kernel configuration parameter.)

<a id="rst-rcu-stall-rat-delay"></a>

### RCU_STALL_RAT_DELAY

> The CPU stall detector tries to make the offending CPU print its own warnings, as this often gives better-quality stack traces. However, if the offending CPU does not detect its own stall in the number of jiffies specified by RCU_STALL_RAT_DELAY, then some other CPU will complain.  This delay is normally set to two jiffies.  (This is a cpp macro, not a kernel configuration parameter.)

<a id="rst-rcupdate-rcu-task-stall-timeout"></a>

### rcupdate.rcu_task_stall_timeout

> This boot/sysfs parameter controls the RCU-tasks and RCU-tasks-trace stall warning intervals.  A value of zero or less suppresses RCU-tasks stall warnings.  A positive value sets the stall-warning interval in seconds.  An RCU-tasks stall warning starts with the line:
>
> > INFO: rcu_tasks detected stalls on tasks:
>
> And continues with the output of sched_show_task() for each task stalling the current RCU-tasks grace period.
>
> An RCU-tasks-trace stall warning starts (and continues) similarly:
>
> > INFO: rcu_tasks_trace detected stalls on tasks

<a id="rst-interpreting-rcu-s-cpu-stall-detector-splats"></a>

## Interpreting RCU's CPU Stall-Detector "Splats"

For non-RCU-tasks flavors of RCU, when a CPU detects that some other CPU is stalling, it will print a message similar to the following:



```text
INFO: rcu_sched detected stalls on CPUs/tasks:
2-...: (3 GPs behind) idle=06c/0/0 softirq=1453/1455 fqs=0
16-...: (0 ticks this GP) idle=81c/0/0 softirq=764/764 fqs=0
(detected by 32, t=2603 jiffies, g=7075, q=625)
```

This message indicates that CPU 32 detected that CPUs 2 and 16 were both causing stalls, and that the stall was affecting RCU-sched.  This message will normally be followed by stack dumps for each CPU.  Please note that PREEMPT_RCU builds can be stalled by tasks as well as by CPUs, and that the tasks will be indicated by PID, for example, "P3421".  It is even possible for an rcu_state stall to be caused by both CPUs *and* tasks, in which case the offending CPUs and tasks will all be called out in the list. In some cases, CPUs will detect themselves stalling, which will result in a self-detected stall.

CPU 2's "(3 GPs behind)" indicates that this CPU has not interacted with the RCU core for the past three grace periods.  In contrast, CPU 16's "(0 ticks this GP)" indicates that this CPU has not taken any scheduling-clock interrupts during the current stalled grace period.

The "idle=" portion of the message prints the dyntick-idle state. The hex number before the first "/" is the low-order 16 bits of the dynticks counter, which will have an even-numbered value if the CPU is in dyntick-idle mode and an odd-numbered value otherwise.  The hex number between the two "/"s is the value of the nesting, which will be a small non-negative number if in the idle loop (as shown above) and a very large positive number otherwise.  The number following the final "/" is the NMI nesting, which will be a small non-negative number.

The "softirq=" portion of the message tracks the number of RCU softirq handlers that the stalled CPU has executed.  The number before the "/" is the number that had executed since boot at the time that this CPU last noted the beginning of a grace period, which might be the current (stalled) grace period, or it might be some earlier grace period (for example, if the CPU might have been in dyntick-idle mode for an extended time period).  The number after the "/" is the number that have executed since boot until the current time.  If this latter number stays constant across repeated stall-warning messages, it is possible that RCU's softirq handlers are no longer able to execute on this CPU.  This can happen if the stalled CPU is spinning with interrupts are disabled, or, in -rt kernels, if a high-priority process is starving RCU's softirq handler.

The "fqs=" shows the number of force-quiescent-state idle/offline detection passes that the grace-period kthread has made across this CPU since the last time that this CPU noted the beginning of a grace period.

The "detected by" line indicates which CPU detected the stall (in this case, CPU 32), how many jiffies have elapsed since the start of the grace period (in this case 2603), the grace-period sequence number (7075), and an estimate of the total number of RCU callbacks queued across all CPUs (625 in this case).

If the grace period ends just as the stall warning starts printing, there will be a spurious stall-warning message, which will include the following:



```text
INFO: Stall ended before state dump start
```

This is rare, but does happen from time to time in real life.  It is also possible for a zero-jiffy stall to be flagged in this case, depending on how the stall warning and the grace-period initialization happen to interact.  Please note that it is not possible to entirely eliminate this sort of false positive without resorting to things like stop_machine(), which is overkill for this sort of problem.

If all CPUs and tasks have passed through quiescent states, but the grace period has nevertheless failed to end, the stall-warning splat will include something like the following:



```text
All QSes seen, last rcu_preempt kthread activity 23807 (4297905177-4297881370), jiffies_till_next_fqs=3, root ->qsmask 0x0
```

The "23807" indicates that it has been more than 23 thousand jiffies since the grace-period kthread ran.  The "jiffies_till_next_fqs" indicates how frequently that kthread should run, giving the number of jiffies between force-quiescent-state scans, in this case three, which is way less than 23807.  Finally, the root rcu_node structure's -&gt;qsmask field is printed, which will normally be zero.

If the relevant grace-period kthread has been unable to run prior to the stall warning, as was the case in the "All QSes seen" line above, the following additional line is printed:



```text
rcu_sched kthread starved for 23807 jiffies! g7075 f0x0 RCU_GP_WAIT_FQS(3) ->state=0x1 ->cpu=5
Unless rcu_sched kthread gets sufficient CPU time, OOM is now expected behavior.
```

Starving the grace-period kthreads of CPU time can of course result in RCU CPU stall warnings even when all CPUs and tasks have passed through the required quiescent states.  The "g" number shows the current grace-period sequence number, the "f" precedes the -&gt;gp_flags command to the grace-period kthread, the "RCU_GP_WAIT_FQS" indicates that the kthread is waiting for a short timeout, the "state" precedes value of the task_struct -&gt;state field, and the "cpu" indicates that the grace-period kthread last ran on CPU 5.

If the relevant grace-period kthread does not wake from FQS wait in a reasonable time, then the following additional line is printed:



```text
kthread timer wakeup didn't happen for 23804 jiffies! g7076 f0x0 RCU_GP_WAIT_FQS(5) ->state=0x402
```

The "23804" indicates that kthread's timer expired more than 23 thousand jiffies ago.  The rest of the line has meaning similar to the kthread starvation case.

Additionally, the following line is printed:



```text
Possible timer handling issue on cpu=4 timer-softirq=11142
```

Here "cpu" indicates that the grace-period kthread last ran on CPU 4, where it queued the fqs timer.  The number following the "timer-softirq" is the current `TIMER_SOFTIRQ` count on cpu 4.  If this value does not change on successive RCU CPU stall warnings, there is further reason to suspect a timer problem.

These messages are usually followed by stack dumps of the CPUs and tasks involved in the stall.  These stack traces can help you locate the cause of the stall, keeping in mind that the CPU detecting the stall will have an interrupt frame that is mainly devoted to detecting the stall.

<a id="rst-multiple-warnings-from-one-stall"></a>

## Multiple Warnings From One Stall

If a stall lasts long enough, multiple stall-warning messages will be printed for it.  The second and subsequent messages are printed at longer intervals, so that the time between (say) the first and second message will be about three times the interval between the beginning of the stall and the first message.  It can be helpful to compare the stack dumps for the different messages for the same stalled grace period.

<a id="rst-stall-warnings-for-expedited-grace-periods"></a>

## Stall Warnings for Expedited Grace Periods

If an expedited grace period detects a stall, it will place a message like the following in dmesg:



```text
INFO: rcu_sched detected expedited stalls on CPUs/tasks: { 7-... } 21119 jiffies s: 73 root: 0x2/.
```

This indicates that CPU 7 has failed to respond to a reschedule IPI. The three periods (".") following the CPU number indicate that the CPU is online (otherwise the first period would instead have been "O"), that the CPU was online at the beginning of the expedited grace period (otherwise the second period would have instead been "o"), and that the CPU has been online at least once since boot (otherwise, the third period would instead have been "N").  The number before the "jiffies" indicates that the expedited grace period has been going on for 21,119 jiffies.  The number following the "s:" indicates that the expedited grace-period sequence counter is 73.  The fact that this last value is odd indicates that an expedited grace period is in flight.  The number following "root:" is a bitmask that indicates which children of the root rcu_node structure correspond to CPUs and/or tasks that are blocking the current expedited grace period.  If the tree had more than one level, additional hex numbers would be printed for the states of the other rcu_node structures in the tree.

As with normal grace periods, PREEMPT_RCU builds can be stalled by tasks as well as by CPUs, and that the tasks will be indicated by PID, for example, "P3421".

It is entirely possible to see stall warnings from normal and from expedited grace periods at about the same time during the same run.

<a id="rst-rcu-cpu-stall-cputime"></a>

## RCU_CPU_STALL_CPUTIME

In kernels built with CONFIG_RCU_CPU_STALL_CPUTIME=y or booted with rcupdate.rcu_cpu_stall_cputime=1, the following additional information is supplied with each RCU CPU stall warning:



```text
rcu:          hardirqs   softirqs   csw/system
rcu:  number:      624         45            0
rcu: cputime:       69          1         2425   ==> 2500(ms)
```

These statistics are collected during the sampling period. The values in row "number:" are the number of hard interrupts, number of soft interrupts, and number of context switches on the stalled CPU. The first three values in row "cputime:" indicate the CPU time in milliseconds consumed by hard interrupts, soft interrupts, and tasks on the stalled CPU.  The last number is the measurement interval, again in milliseconds.  Because user-mode tasks normally do not cause RCU CPU stalls, these tasks are typically kernel tasks, which is why only the system CPU time are considered.

The sampling period is shown as follows:



```text
|<------------first timeout---------->|<-----second timeout----->|
|<--half timeout-->|<--half timeout-->|                          |
|                  |<--first period-->|                          |
|                  |<-----------second sampling period---------->|
|                  |                  |                          |
           snapshot time point    1st-stall                  2nd-stall
```

The following describes four typical scenarios:

1. A CPU looping with interrupts disabled.



   ```text
   rcu:          hardirqs   softirqs   csw/system
   rcu:  number:        0          0            0
   rcu: cputime:        0          0            0   ==> 2500(ms)
   ```

   Because interrupts have been disabled throughout the measurement interval, there are no interrupts and no context switches. Furthermore, because CPU time consumption was measured using interrupt handlers, the system CPU consumption is misleadingly measured as zero. This scenario will normally also have "(0 ticks this GP)" printed on this CPU's summary line.

2. A CPU looping with bottom halves disabled.

   This is similar to the previous example, but with non-zero number of and CPU time consumed by hard interrupts, along with non-zero CPU time consumed by in-kernel execution:



   ```text
   rcu:          hardirqs   softirqs   csw/system
   rcu:  number:      624          0            0
   rcu: cputime:       49          0         2446   ==> 2500(ms)
   ```

   The fact that there are zero softirqs gives a hint that these were disabled, perhaps via local_bh_disable().  It is of course possible that there were no softirqs, perhaps because all events that would result in softirq execution are confined to other CPUs.  In this case, the diagnosis should continue as shown in the next example.

3. A CPU looping with preemption disabled.

   Here, only the number of context switches is zero:



   ```text
   rcu:          hardirqs   softirqs   csw/system
   rcu:  number:      624         45            0
   rcu: cputime:       69          1         2425   ==> 2500(ms)
   ```

   This situation hints that the stalled CPU was looping with preemption disabled.

4. No looping, but massive hard and soft interrupts.



   ```text
   rcu:          hardirqs   softirqs   csw/system
   rcu:  number:       xx         xx            0
   rcu: cputime:       xx         xx            0   ==> 2500(ms)
   ```

   Here, the number and CPU time of hard interrupts are all non-zero, but the number of context switches and the in-kernel CPU time consumed are zero. The number and cputime of soft interrupts will usually be non-zero, but could be zero, for example, if the CPU was spinning within a single hard interrupt handler.

   If this type of RCU CPU stall warning can be reproduced, you can narrow it down by looking at /proc/interrupts or by writing code to trace each interrupt, for example, by referring to show_interrupts().

---

# RCU Torture Test Operation

_Peios Kernel / Internals / Read-copy-update (RCU)_

> The CONFIG_RCU_TORTURE_TEST config option is available for all RCU implementations. It creates an rcutorture kernel module that can be loaded to run a torture test. The test periodically outputs status messages via printk(), which can be…

<a id="rst-rcu-torture-test-operation"></a>

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

<a id="rst-config-rcu-torture-test"></a>

## CONFIG_RCU_TORTURE_TEST

The CONFIG_RCU_TORTURE_TEST config option is available for all RCU implementations.  It creates an rcutorture kernel module that can be loaded to run a torture test.  The test periodically outputs status messages via printk(), which can be examined via the dmesg command (perhaps grepping for "torture").  The test is started when the module is loaded, and stops when the module is unloaded.

Module parameters are prefixed by "rcutorture." in [Documentation/admin-guide/kernel-parameters.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/admin-guide/kernel-parameters.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92).

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

## Output

The statistics output is as follows:



```text
rcu-torture:--- Start of test: nreaders=16 nfakewriters=4 stat_interval=30 verbose=0 test_no_idle_hz=1 shuffle_interval=3 stutter=5 irqreader=1 fqs_duration=0 fqs_holdoff=0 fqs_stutter=3 test_boost=1/0 test_boost_interval=7 test_boost_duration=4
rcu-torture: rtc:           (null) ver: 155441 tfle: 0 rta: 155441 rtaf: 8884 rtf: 155440 rtmbe: 0 rtbe: 0 rtbke: 0 rtbre: 0 rtbf: 0 rtb: 0 nt: 3055767
rcu-torture: Reader Pipe:  727860534 34213 0 0 0 0 0 0 0 0 0
rcu-torture: Reader Batch:  727877838 17003 0 0 0 0 0 0 0 0 0
rcu-torture: Free-Block Circulation:  155440 155440 155440 155440 155440 155440 155440 155440 155440 155440 0
rcu-torture:--- End of test: SUCCESS: nreaders=16 nfakewriters=4 stat_interval=30 verbose=0 test_no_idle_hz=1 shuffle_interval=3 stutter=5 irqreader=1 fqs_duration=0 fqs_holdoff=0 fqs_stutter=3 test_boost=1/0 test_boost_interval=7 test_boost_duration=4
```

The command "dmesg \| grep torture:" will extract this information on most systems.  On more esoteric configurations, it may be necessary to use other commands to access the output of the printk()s used by the RCU torture test.  The printk()s use KERN_ALERT, so they should be evident.  ;-)

The first and last lines show the rcutorture module parameters, and the last line shows either "SUCCESS" or "FAILURE", based on rcutorture's automatic determination as to whether RCU operated correctly.

The entries are as follows:

- "rtc": The hexadecimal address of the structure currently visible to readers.

- "ver": The number of times since boot that the RCU writer task has changed the structure visible to readers.

- "tfle": If non-zero, indicates that the "torture freelist" containing structures to be placed into the "rtc" area is empty. This condition is important, since it can fool you into thinking that RCU is working when it is not.  :-/

- "rta": Number of structures allocated from the torture freelist.

- "rtaf": Number of allocations from the torture freelist that have failed due to the list being empty.  It is not unusual for this to be non-zero, but it is bad for it to be a large fraction of the value indicated by "rta".

- "rtf": Number of frees into the torture freelist.

- "rtmbe": A non-zero value indicates that rcutorture believes that rcu_assign_pointer() and rcu_dereference() are not working correctly.  This value should be zero.

- "rtbe": A non-zero value indicates that one of the rcu_barrier() family of functions is not working correctly.

- "rtbke": rcutorture was unable to create the real-time kthreads used to force RCU priority inversion.  This value should be zero.

- "rtbre": Although rcutorture successfully created the kthreads used to force RCU priority inversion, it was unable to set them to the real-time priority level of 1.  This value should be zero.

- "rtbf": The number of times that RCU priority boosting failed to resolve RCU priority inversion.

- "rtb": The number of times that rcutorture attempted to force an RCU priority inversion condition.  If you are testing RCU priority boosting via the "test_boost" module parameter, this value should be non-zero.

- "nt": The number of times rcutorture ran RCU read-side code from within a timer handler.  This value should be non-zero only if you specified the "irqreader" module parameter.

- "Reader Pipe": Histogram of "ages" of structures seen by readers. If any entries past the first two are non-zero, RCU is broken. And rcutorture prints the error flag string "\!\!\!" to make sure you notice.  The age of a newly allocated structure is zero, it becomes one when removed from reader visibility, and is incremented once per grace period subsequently -- and is freed after passing through (RCU_TORTURE_PIPE_LEN-2) grace periods.

  The output displayed above was taken from a correctly working RCU.  If you want to see what it looks like when broken, break it yourself.  ;-)

- "Reader Batch": Another histogram of "ages" of structures seen by readers, but in terms of counter flips (or batches) rather than in terms of grace periods.  The legal number of non-zero entries is again two.  The reason for this separate view is that it is sometimes easier to get the third entry to show up in the "Reader Batch" list than in the "Reader Pipe" list.

- "Free-Block Circulation": Shows the number of torture structures that have reached a given point in the pipeline.  The first element should closely correspond to the number of structures allocated, the second to the number that have been removed from reader view, and all but the last remaining to the corresponding number of passes through a grace period.  The last entry should be zero, as it is only incremented if a torture structure's counter somehow gets incremented farther than it should.

Different implementations of RCU can provide implementation-specific additional information.  For example, Tree SRCU provides the following additional line:



```text
srcud-torture: Tree SRCU per-CPU(idx=0): 0(35,-21) 1(-4,24) 2(1,1) 3(-26,20) 4(28,-47) 5(-9,4) 6(-10,14) 7(-14,11) T(1,6)
```

This line shows the per-CPU counter state, in this case for Tree SRCU using a dynamically allocated srcu_struct (hence "srcud-" rather than "srcu-").  The numbers in parentheses are the values of the "old" and "current" counters for the corresponding CPU.  The "idx" value maps the "old" and "current" values to the underlying array, and is useful for debugging.  The final "T" entry contains the totals of the counters.

<a id="rst-usage-on-specific-kernel-builds"></a>

## Usage on Specific Kernel Builds

It is sometimes desirable to torture RCU on a specific kernel build, for example, when preparing to put that kernel build into production. In that case, the kernel should be built with CONFIG_RCU_TORTURE_TEST=m so that the test can be started using modprobe and terminated using rmmod.

For example, the following script may be used to torture RCU:



```text
#!/bin/sh

modprobe rcutorture
sleep 3600
rmmod rcutorture
dmesg | grep torture:
```

The output can be manually inspected for the error flag of "\!\!\!". One could of course create a more elaborate script that automatically checked for such errors.  The "rmmod" command forces a "SUCCESS", "FAILURE", or "RCU_HOTPLUG" indication to be printk()ed.  The first two are self-explanatory, while the last indicates that while there were no RCU failures, CPU-hotplug problems were detected.

<a id="rst-usage-on-mainline-kernels"></a>

## Usage on Mainline Kernels

When using rcutorture to test changes to RCU itself, it is often necessary to build a number of kernels in order to test that change across a broad range of combinations of the relevant Kconfig options and of the relevant kernel boot parameters.  In this situation, use of modprobe and rmmod can be quite time-consuming and error-prone.

Therefore, the tools/testing/selftests/rcutorture/bin/kvm.sh script is available for mainline testing for x86, arm64, and powerpc.  By default, it will run the series of tests specified by tools/testing/selftests/rcutorture/configs/rcu/CFLIST, with each test running for 30 minutes within a guest OS using a minimal userspace supplied by an automatically generated initrd.  After the tests are complete, the resulting build products and console output are analyzed for errors and the results of the runs are summarized.

On larger systems, rcutorture testing can be accelerated by passing the --cpus argument to kvm.sh.  For example, on a 64-CPU system, "--cpus 43" would use up to 43 CPUs to run tests concurrently, which as of v5.4 would complete all the scenarios in two batches, reducing the time to complete from about eight hours to about one hour (not counting the time to build the sixteen kernels).  The "--dryrun sched" argument will not run tests, but rather tell you how the tests would be scheduled into batches.  This can be useful when working out how many CPUs to specify in the --cpus argument.

Not all changes require that all scenarios be run.  For example, a change to Tree SRCU might run only the SRCU-N and SRCU-P scenarios using the --configs argument to kvm.sh as follows:  "--configs 'SRCU-N SRCU-P'". Large systems can run multiple copies of the full set of scenarios, for example, a system with 448 hardware threads can run five instances of the full set concurrently.  To make this happen:



```text
kvm.sh --cpus 448 --configs '5*CFLIST'
```

Alternatively, such a system can run 56 concurrent instances of a single eight-CPU scenario:



```text
kvm.sh --cpus 448 --configs '56*TREE04'
```

Or 28 concurrent instances of each of two eight-CPU scenarios:



```text
kvm.sh --cpus 448 --configs '28*TREE03 28*TREE04'
```

Of course, each concurrent instance will use memory, which can be limited using the --memory argument, which defaults to 512M.  Small values for memory may require disabling the callback-flooding tests using the --bootargs parameter discussed below.

Sometimes additional debugging is useful, and in such cases the --kconfig parameter to kvm.sh may be used, for example, `--kconfig 'CONFIG_RCU_EQS_DEBUG=y'`. In addition, there are the --gdb, --kasan, and --kcsan parameters. Note that --gdb limits you to one scenario per kvm.sh run and requires that you have another window open from which to run `gdb` as instructed by the script.

Kernel boot arguments can also be supplied, for example, to control rcutorture's module parameters.  For example, to test a change to RCU's CPU stall-warning code, use "--bootargs 'rcutorture.stall_cpu=30'". This will of course result in the scripting reporting a failure, namely the resulting RCU CPU stall warning.  As noted above, reducing memory may require disabling rcutorture's callback-flooding tests:



```text
kvm.sh --cpus 448 --configs '56*TREE04' --memory 128M \
        --bootargs 'rcutorture.fwd_progress=0'
```

Sometimes all that is needed is a full set of kernel builds.  This is what the --buildonly parameter does.

The --duration parameter can override the default run time of 30 minutes. For example, `--duration 2d` would run for two days, `--duration 3h` would run for three hours, `--duration 5m` would run for five minutes, and `--duration 45s` would run for 45 seconds.  This last can be useful for tracking down rare boot-time failures.

Finally, the --trust-make parameter allows each kernel build to reuse what it can from the previous kernel build.  Please note that without the --trust-make parameter, your tags files may be demolished.

There are additional more arcane arguments that are documented in the source code of the kvm.sh script.

If a run contains failures, the number of buildtime and runtime failures is listed at the end of the kvm.sh output, which you really should redirect to a file.  The build products and console output of each run is kept in tools/testing/selftests/rcutorture/res in timestamped directories.  A given directory can be supplied to kvm-find-errors.sh in order to have it cycle you through summaries of errors and full error logs.  For example:



```text
tools/testing/selftests/rcutorture/bin/kvm-find-errors.sh \
        tools/testing/selftests/rcutorture/res/2020.01.20-15.54.23
```

However, it is often more convenient to access the files directly. Files pertaining to all scenarios in a run reside in the top-level directory (2020.01.20-15.54.23 in the example above), while per-scenario files reside in a subdirectory named after the scenario (for example, "TREE04").  If a given scenario ran more than once (as in "--configs '56\*TREE04'" above), the directories corresponding to the second and subsequent runs of that scenario include a sequence number, for example, "TREE04.2", "TREE04.3", and so on.

The most frequently used file in the top-level directory is testid.txt. If the test ran in a git repository, then this file contains the commit that was tested and any uncommitted changes in diff format.

The most frequently used files in each per-scenario-run directory are:

- **.config:**

  This file contains the Kconfig options.

- **Make.out:**

  This contains build output for a specific scenario.

- **console.log:**

  This contains the console output for a specific scenario. This file may be examined once the kernel has booted, but it might not exist if the build failed.

- **vmlinux:**

  This contains the kernel, which can be useful with tools like objdump and gdb.

A number of additional files are available, but are less frequently used. Many are intended for debugging of rcutorture itself or of its scripting.

As of v5.4, a successful run with the default set of scenarios produces the following summary at the end of the run on a 12-CPU system:



```text
SRCU-N ------- 804233 GPs (148.932/s) [srcu: g10008272 f0x0 ]
SRCU-P ------- 202320 GPs (37.4667/s) [srcud: g1809476 f0x0 ]
SRCU-t ------- 1122086 GPs (207.794/s) [srcu: g0 f0x0 ]
SRCU-u ------- 1111285 GPs (205.794/s) [srcud: g1 f0x0 ]
TASKS01 ------- 19666 GPs (3.64185/s) [tasks: g0 f0x0 ]
TASKS02 ------- 20541 GPs (3.80389/s) [tasks: g0 f0x0 ]
TASKS03 ------- 19416 GPs (3.59556/s) [tasks: g0 f0x0 ]
TINY01 ------- 836134 GPs (154.84/s) [rcu: g0 f0x0 ] n_max_cbs: 34198
TINY02 ------- 850371 GPs (157.476/s) [rcu: g0 f0x0 ] n_max_cbs: 2631
TREE01 ------- 162625 GPs (30.1157/s) [rcu: g1124169 f0x0 ]
TREE02 ------- 333003 GPs (61.6672/s) [rcu: g2647753 f0x0 ] n_max_cbs: 35844
TREE03 ------- 306623 GPs (56.782/s) [rcu: g2975325 f0x0 ] n_max_cbs: 1496497
CPU count limited from 16 to 12
TREE04 ------- 246149 GPs (45.5831/s) [rcu: g1695737 f0x0 ] n_max_cbs: 434961
TREE05 ------- 314603 GPs (58.2598/s) [rcu: g2257741 f0x2 ] n_max_cbs: 193997
TREE07 ------- 167347 GPs (30.9902/s) [rcu: g1079021 f0x0 ] n_max_cbs: 478732
CPU count limited from 16 to 12
TREE09 ------- 752238 GPs (139.303/s) [rcu: g13075057 f0x0 ] n_max_cbs: 99011
```

<a id="rst-repeated-runs"></a>

## Repeated Runs

Suppose that you are chasing down a rare boot-time failure.  Although you could use kvm.sh, doing so will rebuild the kernel on each run.  If you need (say) 1,000 runs to have confidence that you have fixed the bug, these pointless rebuilds can become extremely annoying.

This is why kvm-again.sh exists.

Suppose that a previous kvm.sh run left its output in this directory:



```text
tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28
```

Then this run can be re-run without rebuilding as follow:



```text
kvm-again.sh tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28
```

A few of the original run's kvm.sh parameters may be overridden, perhaps most notably --duration and --bootargs.  For example:



```text
kvm-again.sh tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28 \
        --duration 45s
```

would re-run the previous test, but for only 45 seconds, thus facilitating tracking down the aforementioned rare boot-time failure.

<a id="rst-distributed-runs"></a>

## Distributed Runs

Although kvm.sh is quite useful, its testing is confined to a single system.  It is not all that hard to use your favorite framework to cause (say) 5 instances of kvm.sh to run on your 5 systems, but this will very likely unnecessarily rebuild kernels.  In addition, manually distributing the desired rcutorture scenarios across the available systems can be painstaking and error-prone.

And this is why the kvm-remote.sh script exists.

If the following command works:



```text
ssh system0 date
```

and if it also works for system1, system2, system3, system4, and system5, and all of these systems have 64 CPUs, you can type:



```text
kvm-remote.sh "system0 system1 system2 system3 system4 system5" \
        --cpus 64 --duration 8h --configs "5*CFLIST"
```

This will build each default scenario's kernel on the local system, then spread each of five instances of each scenario over the systems listed, running each scenario for eight hours.  At the end of the runs, the results will be gathered, recorded, and printed.  Most of the parameters that kvm.sh will accept can be passed to kvm-remote.sh, but the list of systems must come first.

The kvm.sh `--dryrun scenarios` argument is useful for working out how many scenarios may be run in one batch across a group of systems.

You can also re-run a previous remote run in a manner similar to kvm.sh:



```text
kvm-remote.sh "system0 system1 system2 system3 system4 system5" \
        tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28-remote \
        --duration 24h
```

In this case, most of the kvm-again.sh parameters may be supplied following the pathname of the old run-results directory.

---

# What is RCU?  --  "Read, Copy, Update"

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Please note that the "What is RCU?" LWN series is an excellent place to start learning about RCU:

<a id="rst-what-is-rcu-read-copy-update"></a>
<a id="rst-whatisrcu-doc"></a>

Please note that the "What is RCU?" LWN series is an excellent place to start learning about RCU:

1\.    What is RCU, Fundamentally?  [https://lwn.net/Articles/262464/](<https://lwn.net/Articles/262464/>)<br>
2\.    What is RCU? Part 2: Usage   [https://lwn.net/Articles/263130/](<https://lwn.net/Articles/263130/>)<br>
3\.    RCU part 3: the RCU API      [https://lwn.net/Articles/264090/](<https://lwn.net/Articles/264090/>)<br>
4\.    The RCU API, 2010 Edition    [https://lwn.net/Articles/418853/](<https://lwn.net/Articles/418853/>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2010 Big API Table           [https://lwn.net/Articles/419086/](<https://lwn.net/Articles/419086/>)<br>
5\.    The RCU API, 2014 Edition    [https://lwn.net/Articles/609904/](<https://lwn.net/Articles/609904/>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2014 Big API Table           [https://lwn.net/Articles/609973/](<https://lwn.net/Articles/609973/>)<br>
6\.    The RCU API, 2019 Edition    [https://lwn.net/Articles/777036/](<https://lwn.net/Articles/777036/>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2019 Big API Table           [https://lwn.net/Articles/777165/](<https://lwn.net/Articles/777165/>)<br>
7\.    The RCU API, 2024 Edition    [https://lwn.net/Articles/988638/](<https://lwn.net/Articles/988638/>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2024 Background Information  [https://lwn.net/Articles/988641/](<https://lwn.net/Articles/988641/>)<br>
&nbsp;&nbsp;&nbsp;&nbsp;2024 Big API Table           [https://lwn.net/Articles/988666/](<https://lwn.net/Articles/988666/>)

For those preferring video:

1\.    Unraveling RCU Mysteries: Fundamentals          [https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries](<https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries>)<br>
2\.    Unraveling RCU Mysteries: Additional Use Cases  [https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries-additional-use-cases](<https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries-additional-use-cases>)

What is RCU?

RCU is a synchronization mechanism that was added to the Linux kernel during the 2.5 development effort that is optimized for read-mostly situations.  Although RCU is actually quite simple, making effective use of it requires you to think differently about your code.  Another part of the problem is the mistaken assumption that there is "one true way" to describe and to use RCU.  Instead, the experience has been that different people must take different paths to arrive at an understanding of RCU, depending on their experiences and use cases.  This document provides several different paths, as follows:

[1. RCU OVERVIEW](<#rst-whatisrcu>)

[2. WHAT IS RCU'S CORE API?](<#rst-whatisrcu-1>)

[3. WHAT ARE SOME EXAMPLE USES OF CORE RCU API?](<#rst-whatisrcu-2>)

[4. WHAT IF MY UPDATING THREAD CANNOT BLOCK?](<#rst-whatisrcu-3>)

[5. WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?](<#rst-whatisrcu-4>)

[6. ANALOGY WITH READER-WRITER LOCKING](<#rst-whatisrcu-5>)

[7. ANALOGY WITH REFERENCE COUNTING](<#rst-whatisrcu-6>)

[8. FULL LIST OF RCU APIs](<#rst-whatisrcu-7>)

[9. ANSWERS TO QUICK QUIZZES](<#rst-whatisrcu-8>)

People who prefer starting with a conceptual overview should focus on Section 1, though most readers will profit by reading this section at some point.  People who prefer to start with an API that they can then experiment with should focus on Section 2.  People who prefer to start with example uses should focus on Sections 3 and 4.  People who need to understand the RCU implementation should focus on Section 5, then dive into the kernel source code.  People who reason best by analogy should focus on Section 6 and 7.  Section 8 serves as an index to the docbook API documentation, and Section 9 is the traditional answer key.

So, start with the section that makes the most sense to you and your preferred method of learning.  If you need to know everything about everything, feel free to read the whole thing -- but if you are really that type of person, you have perused the source code and will therefore never need this document anyway.  ;-)

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

## 1.  RCU OVERVIEW

The basic idea behind RCU is to split updates into "removal" and "reclamation" phases.  The removal phase removes references to data items within a data structure (possibly by replacing them with references to new versions of these data items), and can run concurrently with readers. The reason that it is safe to run the removal phase concurrently with readers is the semantics of modern CPUs guarantee that readers will see either the old or the new version of the data structure rather than a partially updated reference.  The reclamation phase does the work of reclaiming (e.g., freeing) the data items removed from the data structure during the removal phase.  Because reclaiming data items can disrupt any readers concurrently referencing those data items, the reclamation phase must not start until readers no longer hold references to those data items.

Splitting the update into removal and reclamation phases permits the updater to perform the removal phase immediately, and to defer the reclamation phase until all readers active during the removal phase have completed, either by blocking until they finish or by registering a callback that is invoked after they finish.  Only readers that are active during the removal phase need be considered, because any reader starting after the removal phase will be unable to gain a reference to the removed data items, and therefore cannot be disrupted by the reclamation phase.

So the typical RCU update sequence goes something like the following:

- **a.** Remove pointers to a data structure, so that subsequent readers cannot gain a reference to it.

- **b.** Wait for all previous readers to complete their RCU read-side critical sections.

- **c.** At this point, there cannot be any readers who hold references to the data structure, so it now may safely be reclaimed (e.g., kfree()d).

Step (b) above is the key idea underlying RCU's deferred destruction. The ability to wait until all readers are done allows RCU readers to use much lighter-weight synchronization, in some cases, absolutely no synchronization at all.  In contrast, in more conventional lock-based schemes, readers must use heavy-weight synchronization in order to prevent an updater from deleting the data structure out from under them. This is because lock-based updaters typically update data items in place, and must therefore exclude readers.  In contrast, RCU-based updaters typically take advantage of the fact that writes to single aligned pointers are atomic on modern CPUs, allowing atomic insertion, removal, and replacement of data items in a linked structure without disrupting readers.  Concurrent RCU readers can then continue accessing the old versions, and can dispense with the atomic operations, memory barriers, and communications cache misses that are so expensive on present-day SMP computer systems, even in absence of lock contention.

In the three-step procedure shown above, the updater is performing both the removal and the reclamation step, but it is often helpful for an entirely different thread to do the reclamation, as is in fact the case in the Linux kernel's directory-entry cache (dcache).  Even if the same thread performs both the update step (step (a) above) and the reclamation step (step (c) above), it is often helpful to think of them separately. For example, RCU readers and updaters need not communicate at all, but RCU provides implicit low-overhead communication between readers and reclaimers, namely, in step (b) above.

So how the heck can a reclaimer tell when a reader is done, given that readers are not doing any sort of synchronization operations??? Read on to learn about how RCU's API makes this easy.

<a id="rst-what-is-rcu-s-core-api"></a>
<a id="rst-whatisrcu-1"></a>

## 2.  WHAT IS RCU'S CORE API?

The core RCU API is quite small:

- **a.** rcu\_read\_lock()

- **b.** rcu\_read\_unlock()

- **c.** synchronize\_rcu() / call\_rcu()

- **d.** rcu\_assign\_pointer()

- **e.** rcu\_dereference()

There are many other members of the RCU API, but the rest can be expressed in terms of these five, though most implementations instead express synchronize\_rcu() in terms of the call\_rcu() callback API.

The five core RCU APIs are described below, the other 18 will be enumerated later.  See the kernel docbook documentation for more info, or look directly at the function header comments.

<a id="rst-rcu-read-lock"></a>

### rcu\_read\_lock()

> void rcu\_read\_lock(void);
>
> This temporal primitive is used by a reader to inform the reclaimer that the reader is entering an RCU read-side critical section.  It is illegal to block while in an RCU read-side critical section, though kernels built with CONFIG\_PREEMPT\_RCU can preempt RCU read-side critical sections.  Any RCU-protected data structure accessed during an RCU read-side critical section is guaranteed to remain unreclaimed for the full duration of that critical section.  Reference counts may be used in conjunction with RCU to maintain longer-term references to data structures.
>
> Note that anything that disables bottom halves, preemption, or interrupts also enters an RCU read-side critical section. Acquiring a spinlock also enters an RCU read-side critical sections, even for spinlocks that do not disable preemption, as is the case in kernels built with CONFIG\_PREEMPT\_RT=y. Sleeplocks do <em>not</em> enter RCU read-side critical sections.

<a id="rst-rcu-read-unlock"></a>

### rcu\_read\_unlock()

> void rcu\_read\_unlock(void);
>
> This temporal primitives is used by a reader to inform the reclaimer that the reader is exiting an RCU read-side critical section.  Anything that enables bottom halves, preemption, or interrupts also exits an RCU read-side critical section. Releasing a spinlock also exits an RCU read-side critical section.
>
> Note that RCU read-side critical sections may be nested and/or overlapping.

<a id="rst-synchronize-rcu"></a>

### synchronize\_rcu()

> void synchronize\_rcu(void);
>
> This temporal primitive marks the end of updater code and the beginning of reclaimer code.  It does this by blocking until all pre-existing RCU read-side critical sections on all CPUs have completed.  Note that synchronize\_rcu() will <strong>not</strong> necessarily wait for any subsequent RCU read-side critical sections to complete.  For example, consider the following sequence of events:
>
>
>
> ```text
>         CPU 0                  CPU 1                 CPU 2
>     ----------------- ------------------------- ---------------
> 1.  rcu_read_lock()
> 2.                    enters synchronize_rcu()
> 3.                                               rcu_read_lock()
> 4.  rcu_read_unlock()
> 5.                     exits synchronize_rcu()
> 6.                                              rcu_read_unlock()
> ```
>
> To reiterate, synchronize\_rcu() waits only for ongoing RCU read-side critical sections to complete, not necessarily for any that begin after synchronize\_rcu() is invoked.
>
> Of course, synchronize\_rcu() does not necessarily return <strong>immediately</strong> after the last pre-existing RCU read-side critical section completes.  For one thing, there might well be scheduling delays.  For another thing, many RCU implementations process requests in batches in order to improve efficiencies, which can further delay synchronize\_rcu().
>
> Since synchronize\_rcu() is the API that must figure out when readers are done, its implementation is key to RCU.  For RCU to be useful in all but the most read-intensive situations, synchronize\_rcu()'s overhead must also be quite small.
>
> The call\_rcu() API is an asynchronous callback form of synchronize\_rcu(), and is described in more detail in a later section.  Instead of blocking, it registers a function and argument which are invoked after all ongoing RCU read-side critical sections have completed.  This callback variant is particularly useful in situations where it is illegal to block or where update-side performance is critically important.
>
> However, the call\_rcu() API should not be used lightly, as use of the synchronize\_rcu() API generally results in simpler code. In addition, the synchronize\_rcu() API has the nice property of automatically limiting update rate should grace periods be delayed.  This property results in system resilience in face of denial-of-service attacks.  Code using call\_rcu() should limit update rate in order to gain this same sort of resilience.  See [checklist.rst](/kernel/internals/rcu/checklist.md) for some approaches to limiting the update rate.

<a id="rst-rcu-assign-pointer"></a>

### rcu\_assign\_pointer()

> void rcu\_assign\_pointer(p, typeof(p) v);
>
> Yes, rcu\_assign\_pointer() <strong>is</strong> implemented as a macro, though it would be cool to be able to declare a function in this manner. (And there has been some discussion of adding overloaded functions to the C language, so who knows?)
>
> The updater uses this spatial macro to assign a new value to an RCU-protected pointer, in order to safely communicate the change in value from the updater to the reader.  This is a spatial (as opposed to temporal) macro.  It does not evaluate to an rvalue, but it does provide any compiler directives and memory-barrier instructions required for a given compile or CPU architecture. Its ordering properties are that of a store-release operation, that is, any prior loads and stores required to initialize the structure are ordered before the store that publishes the pointer to that structure.
>
> Perhaps just as important, rcu\_assign\_pointer() serves to document (1) which pointers are protected by RCU and (2) the point at which a given structure becomes accessible to other CPUs.  That said, rcu\_assign\_pointer() is most frequently used indirectly, via the \_rcu list-manipulation primitives such as list\_add\_rcu().

<a id="rst-rcu-dereference"></a>

### rcu\_dereference()

> typeof(p) rcu\_dereference(p);
>
> Like rcu\_assign\_pointer(), rcu\_dereference() must be implemented as a macro.
>
> The reader uses the spatial rcu\_dereference() macro to fetch an RCU-protected pointer, which returns a value that may then be safely dereferenced.  Note that rcu\_dereference() does not actually dereference the pointer, instead, it protects the pointer for later dereferencing.  It also executes any needed memory-barrier instructions for a given CPU architecture.  Currently, only Alpha needs memory barriers within rcu\_dereference() -- on other CPUs, it compiles to a volatile load.  However, no mainstream C compilers respect address dependencies, so rcu\_dereference() uses volatile casts, which, in combination with the coding guidelines listed in [rcu\_dereference.rst](/kernel/internals/rcu/rcu-dereference.md), prevent current compilers from breaking these dependencies.
>
> Common coding practice uses rcu\_dereference() to copy an RCU-protected pointer to a local variable, then dereferences this local variable, for example as follows:
>
>
>
> ```text
> p = rcu_dereference(head.next);
> return p->data;
> ```
>
> However, in this case, one could just as easily combine these into one statement:
>
>
>
> ```text
> return rcu_dereference(head.next)->data;
> ```
>
> If you are going to be fetching multiple fields from the RCU-protected structure, using the local variable is of course preferred.  Repeated rcu\_dereference() calls look ugly, do not guarantee that the same pointer will be returned if an update happened while in the critical section, and incur unnecessary overhead on Alpha CPUs.
>
> Note that the value returned by rcu\_dereference() is valid only within the enclosing RCU read-side critical section <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1). For example, the following is <strong>not</strong> legal:
>
>
>
> ```text
> rcu_read_lock();
> p = rcu_dereference(head.next);
> rcu_read_unlock();
> x = p->address; /* BUG!!! */
> rcu_read_lock();
> y = p->data;    /* BUG!!! */
> rcu_read_unlock();
> ```
>
> Holding a reference from one RCU read-side critical section to another is just as illegal as holding a reference from one lock-based critical section to another\!  Similarly, using a reference outside of the critical section in which it was acquired is just as illegal as doing so with normal locking.
>
> As with rcu\_assign\_pointer(), an important function of rcu\_dereference() is to document which pointers are protected by RCU, in particular, flagging a pointer that is subject to changing at any time, including immediately after the rcu\_dereference(). And, again like rcu\_assign\_pointer(), rcu\_dereference() is typically used indirectly, via the \_rcu list-manipulation primitives, such as list\_for\_each\_entry\_rcu() <a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2).

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



**[1]** The variant rcu\_dereference\_protected() can be used outside of an RCU read-side critical section as long as the usage is protected by locks acquired by the update-side code.  This variant avoids the lockdep warning that would happen when using (for example) rcu\_dereference() without rcu\_read\_lock() protection. Using rcu\_dereference\_protected() also has the advantage of permitting compiler optimizations that rcu\_dereference() must prohibit.  The rcu\_dereference\_protected() variant takes a lockdep expression to indicate which locks must be acquired by the caller. If the indicated protection is not provided, a lockdep splat is emitted.  See Design/Requirements/Requirements.rst and the API's code comments for more details and example usage.

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



**[2]** If the list\_for\_each\_entry\_rcu() instance might be used by update-side code as well as by RCU readers, then an additional lockdep expression can be added to its list of arguments. For example, given an additional "lock\_is\_held(&amp;mylock)" argument, the RCU lockdep code would complain only if this instance was invoked outside of an RCU read-side critical section and without the protection of mylock.

The following diagram shows how each API communicates among the reader, updater, and reclaimer.



```text
rcu_assign_pointer()
                        +--------+
+---------------------->| reader |---------+
|                       +--------+         |
|                           |              |
|                           |              | Protect:
|                           |              | rcu_read_lock()
|                           |              | rcu_read_unlock()
|        rcu_dereference()  |              |
+---------+                 |              |
| updater |<----------------+              |
+---------+                                V
|                                    +-----------+
+----------------------------------->| reclaimer |
                                     +-----------+
  Defer:
  synchronize_rcu() & call_rcu()
```

The RCU infrastructure observes the temporal sequence of rcu\_read\_lock(), rcu\_read\_unlock(), synchronize\_rcu(), and call\_rcu() invocations in order to determine when (1) synchronize\_rcu() invocations may return to their callers and (2) call\_rcu() callbacks may be invoked.  Efficient implementations of the RCU infrastructure make heavy use of batching in order to amortize their overhead over many uses of the corresponding APIs. The rcu\_assign\_pointer() and rcu\_dereference() invocations communicate spatial changes via stores to and loads from the RCU-protected pointer in question.

There are at least three flavors of RCU usage in the Linux kernel. The diagram above shows the most common one. On the updater side, the rcu\_assign\_pointer(), synchronize\_rcu() and call\_rcu() primitives used are the same for all three flavors. However for protection (on the reader side), the primitives used vary depending on the flavor:

- **a.** rcu\_read\_lock() / rcu\_read\_unlock() rcu\_dereference()

- **b.** rcu\_read\_lock\_bh() / rcu\_read\_unlock\_bh() local\_bh\_disable() / local\_bh\_enable() rcu\_dereference\_bh()

- **c.** rcu\_read\_lock\_sched() / rcu\_read\_unlock\_sched() preempt\_disable() / preempt\_enable() local\_irq\_save() / local\_irq\_restore() hardirq enter / hardirq exit NMI enter / NMI exit rcu\_dereference\_sched()

These three flavors are used as follows:

- **a.** RCU applied to normal data structures.

- **b.** RCU applied to networking data structures that may be subjected to remote denial-of-service attacks.

- **c.** RCU applied to scheduler and interrupt/NMI-handler tasks.

Again, most uses will be of (a).  The (b) and (c) cases are important for specialized uses, but are relatively uncommon.  The SRCU, RCU-Tasks, RCU-Tasks-Rude, and RCU-Tasks-Trace have similar relationships among their assorted primitives.

<a id="rst-what-are-some-example-uses-of-core-rcu-api"></a>
<a id="rst-whatisrcu-2"></a>

## 3.  WHAT ARE SOME EXAMPLE USES OF CORE RCU API?

This section shows a simple use of the core RCU API to protect a global pointer to a dynamically allocated structure.  More-typical uses of RCU may be found in [listRCU.rst](/kernel/internals/rcu/listrcu.md) and [NMI-RCU.rst](/kernel/internals/rcu/nmi-rcu.md).



```text
struct foo {
        int a;
        char b;
        long c;
};
DEFINE_SPINLOCK(foo_mutex);

struct foo __rcu *gbl_foo;

/*
 * Create a new struct foo that is the same as the one currently
 * pointed to by gbl_foo, except that field "a" is replaced
 * with "new_a".  Points gbl_foo to the new structure, and
 * frees up the old structure after a grace period.
 *
 * Uses rcu_assign_pointer() to ensure that concurrent readers
 * see the initialized version of the new structure.
 *
 * Uses synchronize_rcu() to ensure that any readers that might
 * have references to the old structure complete before freeing
 * the old structure.
 */
void foo_update_a(int new_a)
{
        struct foo *new_fp;
        struct foo *old_fp;

        new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
        spin_lock(&foo_mutex);
        old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex));
        *new_fp = *old_fp;
        new_fp->a = new_a;
        rcu_assign_pointer(gbl_foo, new_fp);
        spin_unlock(&foo_mutex);
        synchronize_rcu();
        kfree(old_fp);
}

/*
 * Return the value of field "a" of the current gbl_foo
 * structure.  Use rcu_read_lock() and rcu_read_unlock()
 * to ensure that the structure does not get deleted out
 * from under us, and use rcu_dereference() to ensure that
 * we see the initialized version of the structure (important
 * for DEC Alpha and for people reading the code).
 */
int foo_get_a(void)
{
        int retval;

        rcu_read_lock();
        retval = rcu_dereference(gbl_foo)->a;
        rcu_read_unlock();
        return retval;
}
```

So, to sum up:

- Use rcu\_read\_lock() and rcu\_read\_unlock() to guard RCU read-side critical sections.

- Within an RCU read-side critical section, use rcu\_dereference() to dereference RCU-protected pointers.

- Use some solid design (such as locks or semaphores) to keep concurrent updates from interfering with each other.

- Use rcu\_assign\_pointer() to update an RCU-protected pointer. This primitive protects concurrent readers from the updater, <strong>not</strong> concurrent updates from each other\!  You therefore still need to use locking (or something similar) to keep concurrent rcu\_assign\_pointer() primitives from interfering with each other.

- Use synchronize\_rcu() <strong>after</strong> removing a data element from an RCU-protected data structure, but <strong>before</strong> reclaiming/freeing the data element, in order to wait for the completion of all RCU read-side critical sections that might be referencing that data item.

See [checklist.rst](/kernel/internals/rcu/checklist.md) for additional rules to follow when using RCU. And again, more-typical uses of RCU may be found in [listRCU.rst](/kernel/internals/rcu/listrcu.md) and [NMI-RCU.rst](/kernel/internals/rcu/nmi-rcu.md).

<a id="rst-what-if-my-updating-thread-cannot-block"></a>
<a id="rst-whatisrcu-3"></a>

## 4.  WHAT IF MY UPDATING THREAD CANNOT BLOCK?

In the example above, foo\_update\_a() blocks until a grace period elapses. This is quite simple, but in some cases one cannot afford to wait so long -- there might be other high-priority work to be done.

In such cases, one uses call\_rcu() rather than synchronize\_rcu(). The call\_rcu() API is as follows:



```text
void call_rcu(struct rcu_head *head, rcu_callback_t func);
```

This function invokes func(head) after a grace period has elapsed. This invocation might happen from either softirq or process context, so the function is not permitted to block.  The foo struct needs to have an rcu\_head structure added, perhaps as follows:



```text
struct foo {
        int a;
        char b;
        long c;
        struct rcu_head rcu;
};
```

The foo\_update\_a() function might then be written as follows:



```text
/*
 * Create a new struct foo that is the same as the one currently
 * pointed to by gbl_foo, except that field "a" is replaced
 * with "new_a".  Points gbl_foo to the new structure, and
 * frees up the old structure after a grace period.
 *
 * Uses rcu_assign_pointer() to ensure that concurrent readers
 * see the initialized version of the new structure.
 *
 * Uses call_rcu() to ensure that any readers that might have
 * references to the old structure complete before freeing the
 * old structure.
 */
void foo_update_a(int new_a)
{
        struct foo *new_fp;
        struct foo *old_fp;

        new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
        spin_lock(&foo_mutex);
        old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex));
        *new_fp = *old_fp;
        new_fp->a = new_a;
        rcu_assign_pointer(gbl_foo, new_fp);
        spin_unlock(&foo_mutex);
        call_rcu(&old_fp->rcu, foo_reclaim);
}
```

The foo\_reclaim() function might appear as follows:



```text
void foo_reclaim(struct rcu_head *rp)
{
        struct foo *fp = container_of(rp, struct foo, rcu);

        foo_cleanup(fp->a);

        kfree(fp);
}
```

The container\_of() primitive is a macro that, given a pointer into a struct, the type of the struct, and the pointed-to field within the struct, returns a pointer to the beginning of the struct.

The use of call\_rcu() permits the caller of foo\_update\_a() to immediately regain control, without needing to worry further about the old version of the newly updated element.  It also clearly shows the RCU distinction between updater, namely foo\_update\_a(), and reclaimer, namely foo\_reclaim().

The summary of advice is the same as for the previous section, except that we are now using call\_rcu() rather than synchronize\_rcu():

- Use call\_rcu() <strong>after</strong> removing a data element from an RCU-protected data structure in order to register a callback function that will be invoked after the completion of all RCU read-side critical sections that might be referencing that data item.

If the callback for call\_rcu() is not doing anything more than calling kfree() on the structure, you can use kfree\_rcu() instead of call\_rcu() to avoid having to write your own callback:



```text
kfree_rcu(old_fp, rcu);
```

If the occasional sleep is permitted, the single-argument form may be used, omitting the rcu\_head structure from struct foo.

> kfree\_rcu\_mightsleep(old\_fp);

This variant almost never blocks, but might do so by invoking synchronize\_rcu() in response to memory-allocation failure.

Again, see [checklist.rst](/kernel/internals/rcu/checklist.md) for additional rules governing the use of RCU.

<a id="rst-what-are-some-simple-implementations-of-rcu"></a>
<a id="rst-whatisrcu-4"></a>

## 5.  WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?

One of the nice things about RCU is that it has extremely simple "toy" implementations that are a good first step towards understanding the production-quality implementations in the Linux kernel.  This section presents two such "toy" implementations of RCU, one that is implemented in terms of familiar locking primitives, and another that more closely resembles "classic" RCU.  Both are way too simple for real-world use, lacking both functionality and performance.  However, they are useful in getting a feel for how RCU works.  See kernel/rcu/update.c for a production-quality implementation, and see:

> [https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit](<https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit>)

for papers describing the Linux kernel RCU implementation.  The OLS'01 and OLS'02 papers are a good introduction, and the dissertation provides more details on the current implementation as of early 2004.

<a id="rst-a-toy-implementation-1-locking"></a>

### 5A.  "TOY" IMPLEMENTATION \#1: LOCKING

This section presents a "toy" RCU implementation that is based on familiar locking primitives.  Its overhead makes it a non-starter for real-life use, as does its lack of scalability.  It is also unsuitable for realtime use, since it allows scheduling latency to "bleed" from one read-side critical section to another.  It also assumes recursive reader-writer locks:  If you try this with non-recursive locks, and you allow nested rcu\_read\_lock() calls, you can deadlock.

However, it is probably the easiest implementation to relate to, so is a good starting point.

It is extremely simple:



```text
static DEFINE_RWLOCK(rcu_gp_mutex);

void rcu_read_lock(void)
{
        read_lock(&rcu_gp_mutex);
}

void rcu_read_unlock(void)
{
        read_unlock(&rcu_gp_mutex);
}

void synchronize_rcu(void)
{
        write_lock(&rcu_gp_mutex);
        smp_mb__after_spinlock();
        write_unlock(&rcu_gp_mutex);
}
```

\[You can ignore rcu\_assign\_pointer() and rcu\_dereference() without missing much.  But here are simplified versions anyway.  And whatever you do, don't forget about them when submitting patches making use of RCU\!\]:



```text
#define rcu_assign_pointer(p, v) \
({ \
        smp_store_release(&(p), (v)); \
})

#define rcu_dereference(p) \
({ \
        typeof(p) _________p1 = READ_ONCE(p); \
        (_________p1); \
})
```

The rcu\_read\_lock() and rcu\_read\_unlock() primitive read-acquire and release a global reader-writer lock.  The synchronize\_rcu() primitive write-acquires this same lock, then releases it.  This means that once synchronize\_rcu() exits, all RCU read-side critical sections that were in progress before synchronize\_rcu() was called are guaranteed to have completed -- there is no way that synchronize\_rcu() would have been able to write-acquire the lock otherwise.  The smp\_mb\_\_after\_spinlock() promotes synchronize\_rcu() to a full memory barrier in compliance with the "Memory-Barrier Guarantees" listed in:

> Design/Requirements/Requirements.rst

It is possible to nest rcu\_read\_lock(), since reader-writer locks may be recursively acquired.  Note also that rcu\_read\_lock() is immune from deadlock (an important property of RCU).  The reason for this is that the only thing that can block rcu\_read\_lock() is a synchronize\_rcu(). But synchronize\_rcu() does not acquire any locks while holding rcu\_gp\_mutex, so there can be no deadlock cycle.

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

- **Quick Quiz \#1:**

  Why is this argument naive?  How could a deadlock occur when using this algorithm in a real-world Linux kernel?  How could this deadlock be avoided?

[Answers to Quick Quiz](<#rst-whatisrcu-8>)

<a id="rst-b-toy-example-2-classic-rcu"></a>

### 5B.  "TOY" EXAMPLE \#2: CLASSIC RCU

This section presents a "toy" RCU implementation that is based on "classic RCU".  It is also short on performance (but only for updates) and on features such as hotplug CPU and the ability to run in CONFIG\_PREEMPTION kernels.  The definitions of rcu\_dereference() and rcu\_assign\_pointer() are the same as those shown in the preceding section, so they are omitted.



```text
void rcu_read_lock(void) { }

void rcu_read_unlock(void) { }

void synchronize_rcu(void)
{
        int cpu;

        for_each_possible_cpu(cpu)
                run_on(cpu);
}
```

Note that rcu\_read\_lock() and rcu\_read\_unlock() do absolutely nothing. This is the great strength of classic RCU in a non-preemptive kernel: read-side overhead is precisely zero, at least on non-Alpha CPUs. And there is absolutely no way that rcu\_read\_lock() can possibly participate in a deadlock cycle\!

The implementation of synchronize\_rcu() simply schedules itself on each CPU in turn.  The run\_on() primitive can be implemented straightforwardly in terms of the sched\_setaffinity() primitive.  Of course, a somewhat less "toy" implementation would restore the affinity upon completion rather than just leaving all tasks running on the last CPU, but when I said "toy", I meant <strong>toy</strong>\!

So how the heck is this supposed to work???

Remember that it is illegal to block while in an RCU read-side critical section.  Therefore, if a given CPU executes a context switch, we know that it must have completed all preceding RCU read-side critical sections. Once <strong>all</strong> CPUs have executed a context switch, then <strong>all</strong> preceding RCU read-side critical sections will have completed.

So, suppose that we remove a data item from its structure and then invoke synchronize\_rcu().  Once synchronize\_rcu() returns, we are guaranteed that there are no RCU read-side critical sections holding a reference to that data item, so we can safely reclaim it.

<a id="rst-quiz-2"></a>

- **Quick Quiz \#2:**

  Give an example where Classic RCU's read-side overhead is <strong>negative</strong>.

[Answers to Quick Quiz](<#rst-whatisrcu-8>)

<a id="rst-quiz-3"></a>

- **Quick Quiz \#3:**

  If it is illegal to block in an RCU read-side critical section, what the heck do you do in CONFIG\_PREEMPT\_RT, where normal spinlocks can block???

[Answers to Quick Quiz](<#rst-whatisrcu-8>)

<a id="rst-analogy-with-reader-writer-locking"></a>
<a id="rst-whatisrcu-5"></a>

## 6.  ANALOGY WITH READER-WRITER LOCKING

Although RCU can be used in many different ways, a very common use of RCU is analogous to reader-writer locking.  The following unified diff shows how closely related RCU and reader-writer locking can be.



```text
@@ -5,5 +5,5 @@ struct el {
        int data;
        /* Other data fields */
 };
-rwlock_t listmutex;
+spinlock_t listmutex;
 struct el head;

@@ -13,15 +14,15 @@
        struct list_head *lp;
        struct el *p;

-       read_lock(&listmutex);
-       list_for_each_entry(p, head, lp) {
+       rcu_read_lock();
+       list_for_each_entry_rcu(p, head, lp) {
                if (p->key == key) {
                        *result = p->data;
-                       read_unlock(&listmutex);
+                       rcu_read_unlock();
                        return 1;
                }
        }
-       read_unlock(&listmutex);
+       rcu_read_unlock();
        return 0;
 }

@@ -29,15 +30,16 @@
 {
        struct el *p;

-       write_lock(&listmutex);
+       spin_lock(&listmutex);
        list_for_each_entry(p, head, lp) {
                if (p->key == key) {
-                       list_del(&p->list);
-                       write_unlock(&listmutex);
+                       list_del_rcu(&p->list);
+                       spin_unlock(&listmutex);
+                       synchronize_rcu();
                        kfree(p);
                        return 1;
                }
        }
-       write_unlock(&listmutex);
+       spin_unlock(&listmutex);
        return 0;
 }
```

Or, for those who prefer a side-by-side listing:



```text
1 struct el {                          1 struct el {
2   struct list_head list;             2   struct list_head list;
3   long key;                          3   long key;
4   spinlock_t mutex;                  4   spinlock_t mutex;
5   int data;                          5   int data;
6   /* Other data fields */            6   /* Other data fields */
7 };                                   7 };
8 rwlock_t listmutex;                  8 spinlock_t listmutex;
9 struct el head;                      9 struct el head;
```



```text
 1 int search(long key, int *result)    1 int search(long key, int *result)
 2 {                                    2 {
 3   struct list_head *lp;              3   struct list_head *lp;
 4   struct el *p;                      4   struct el *p;
 5                                      5
 6   read_lock(&listmutex);             6   rcu_read_lock();
 7   list_for_each_entry(p, head, lp) { 7   list_for_each_entry_rcu(p, head, lp) {
 8     if (p->key == key) {             8     if (p->key == key) {
 9       *result = p->data;             9       *result = p->data;
10       read_unlock(&listmutex);      10       rcu_read_unlock();
11       return 1;                     11       return 1;
12     }                               12     }
13   }                                 13   }
14   read_unlock(&listmutex);          14   rcu_read_unlock();
15   return 0;                         15   return 0;
16 }                                   16 }
```



```text
 1 int delete(long key)                 1 int delete(long key)
 2 {                                    2 {
 3   struct el *p;                      3   struct el *p;
 4                                      4
 5   write_lock(&listmutex);            5   spin_lock(&listmutex);
 6   list_for_each_entry(p, head, lp) { 6   list_for_each_entry(p, head, lp) {
 7     if (p->key == key) {             7     if (p->key == key) {
 8       list_del(&p->list);            8       list_del_rcu(&p->list);
 9       write_unlock(&listmutex);      9       spin_unlock(&listmutex);
                                       10       synchronize_rcu();
10       kfree(p);                     11       kfree(p);
11       return 1;                     12       return 1;
12     }                               13     }
13   }                                 14   }
14   write_unlock(&listmutex);         15   spin_unlock(&listmutex);
15   return 0;                         16   return 0;
16 }                                   17 }
```

Either way, the differences are quite small.  Read-side locking moves to rcu\_read\_lock() and rcu\_read\_unlock, update-side locking moves from a reader-writer lock to a simple spinlock, and a synchronize\_rcu() precedes the kfree().

However, there is one potential catch: the read-side and update-side critical sections can now run concurrently.  In many cases, this will not be a problem, but it is necessary to check carefully regardless. For example, if multiple independent list updates must be seen as a single atomic update, converting to RCU will require special care.

Also, the presence of synchronize\_rcu() means that the RCU version of delete() can now block.  If this is a problem, there is a callback-based mechanism that never blocks, namely call\_rcu() or kfree\_rcu(), that can be used in place of synchronize\_rcu().

<a id="rst-analogy-with-reference-counting"></a>
<a id="rst-whatisrcu-6"></a>

## 7.  ANALOGY WITH REFERENCE COUNTING

The reader-writer analogy (illustrated by the previous section) is not always the best way to think about using RCU.  Another helpful analogy considers RCU an effective reference count on everything which is protected by RCU.

A reference count typically does not prevent the referenced object's values from changing, but does prevent changes to type -- particularly the gross change of type that happens when that object's memory is freed and re-allocated for some other purpose.  Once a type-safe reference to the object is obtained, some other mechanism is needed to ensure consistent access to the data in the object.  This could involve taking a spinlock, but with RCU the typical approach is to perform reads with SMP-aware operations such as smp\_load\_acquire(), to perform updates with atomic read-modify-write operations, and to provide the necessary ordering. RCU provides a number of support functions that embed the required operations and ordering, such as the list\_for\_each\_entry\_rcu() macro used in the previous section.

A more focused view of the reference counting behavior is that, between rcu\_read\_lock() and rcu\_read\_unlock(), any reference taken with rcu\_dereference() on a pointer marked as `__rcu` can be treated as though a reference-count on that object has been temporarily increased. This prevents the object from changing type.  Exactly what this means will depend on normal expectations of objects of that type, but it typically includes that spinlocks can still be safely locked, normal reference counters can be safely manipulated, and `__rcu` pointers can be safely dereferenced.

Some operations that one might expect to see on an object for which an RCU reference is held include:

> - Copying out data that is guaranteed to be stable by the object's type.
>
> - Using kref\_get\_unless\_zero() or similar to get a longer-term reference.  This may fail of course.
>
> - Acquiring a spinlock in the object, and checking if the object still is the expected object and if so, manipulating it freely.

The understanding that RCU provides a reference that only prevents a change of type is particularly visible with objects allocated from a slab cache marked `SLAB_TYPESAFE_BY_RCU`.  RCU operations may yield a reference to an object from such a cache that has been concurrently freed and the memory reallocated to a completely different object, though of the same type.  In this case RCU doesn't even protect the identity of the object from changing, only its type.  So the object found may not be the one expected, but it will be one where it is safe to take a reference (and then potentially acquiring a spinlock), allowing subsequent code to check whether the identity matches expectations.  It is tempting to simply acquire the spinlock without first taking the reference, but unfortunately any spinlock in a `SLAB_TYPESAFE_BY_RCU` object must be initialized after each and every call to kmem\_cache\_alloc(), which renders reference-free spinlock acquisition completely unsafe.  Therefore, when using `SLAB_TYPESAFE_BY_RCU`, make proper use of a reference counter. If using refcount\_t, the specialized refcount\_\{add\|inc\}\_not\_zero\_acquire() and refcount\_set\_release() APIs should be used to ensure correct operation ordering when verifying object identity and when initializing newly allocated objects. Acquire fence in refcount\_\{add\|inc\}\_not\_zero\_acquire() ensures that identity checks happen <em>after</em> reference count is taken. refcount\_set\_release() should be called after a newly allocated object is fully initialized and release fence ensures that new values are visible <em>before</em> refcount can be successfully taken by other users. Once refcount\_set\_release() is called, the object should be considered visible by other tasks. (Those willing to initialize their locks in a kmem\_cache constructor may also use locking, including cache-friendly sequence locking.)

With traditional reference counting -- such as that implemented by the kref library in Linux -- there is typically code that runs when the last reference to an object is dropped.  With kref, this is the function passed to kref\_put().  When RCU is being used, such finalization code must not be run until all `__rcu` pointers referencing the object have been updated, and then a grace period has passed.  Every remaining globally visible pointer to the object must be considered to be a potential counted reference, and the finalization code is typically run using call\_rcu() only after all those pointers have been changed.

To see how to choose between these two analogies -- of RCU as a reader-writer lock and RCU as a reference counting system -- it is useful to reflect on the scale of the thing being protected.  The reader-writer lock analogy looks at larger multi-part objects such as a linked list and shows how RCU can facilitate concurrency while elements are added to, and removed from, the list.  The reference-count analogy looks at the individual objects and looks at how they can be accessed safely within whatever whole they are a part of.

<a id="rst-full-list-of-rcu-apis"></a>
<a id="rst-whatisrcu-7"></a>

## 8.  FULL LIST OF RCU APIs

The RCU APIs are documented in docbook-format header comments in the Linux-kernel source code, but it helps to have a full list of the APIs, since there does not appear to be a way to categorize them in docbook.  Here is the list, by category.

RCU list traversal:



```text
list_entry_rcu
list_entry_lockless
list_first_entry_rcu
list_first_or_null_rcu
list_tail_rcu
list_next_rcu
list_next_or_null_rcu
list_for_each_entry_rcu
list_for_each_entry_continue_rcu
list_for_each_entry_from_rcu
list_for_each_entry_lockless
hlist_first_rcu
hlist_next_rcu
hlist_pprev_rcu
hlist_for_each_entry_rcu
hlist_for_each_entry_rcu_notrace
hlist_for_each_entry_rcu_bh
hlist_for_each_entry_from_rcu
hlist_for_each_entry_continue_rcu
hlist_for_each_entry_continue_rcu_bh
hlist_nulls_first_rcu
hlist_nulls_next_rcu
hlist_nulls_for_each_entry_rcu
hlist_nulls_for_each_entry_safe
hlist_bl_first_rcu
hlist_bl_for_each_entry_rcu
```

RCU pointer/list update:



```text
rcu_assign_pointer
rcu_replace_pointer
INIT_LIST_HEAD_RCU
list_add_rcu
list_add_tail_rcu
list_del_rcu
list_replace_rcu
list_splice_init_rcu
list_splice_tail_init_rcu
hlist_add_behind_rcu
hlist_add_before_rcu
hlist_add_head_rcu
hlist_add_tail_rcu
hlist_del_rcu
hlist_del_init_rcu
hlist_replace_rcu
hlist_nulls_del_init_rcu
hlist_nulls_del_rcu
hlist_nulls_add_head_rcu
hlist_nulls_add_tail_rcu
hlist_nulls_add_fake
hlists_swap_heads_rcu
hlist_bl_add_head_rcu
hlist_bl_del_rcu
hlist_bl_set_first_rcu
```

RCU:



```text
Critical sections               Grace period            Barrier

rcu_read_lock                   synchronize_net         rcu_barrier
rcu_read_unlock                 synchronize_rcu
guard(rcu)()                    synchronize_rcu_expedited
scoped_guard(rcu)               synchronize_rcu_mult
rcu_dereference                 call_rcu
rcu_dereference_check           call_rcu_hurry
rcu_dereference_protected       kfree_rcu
rcu_read_lock_held              kvfree_rcu
rcu_read_lock_any_held          kfree_rcu_mightsleep
rcu_pointer_handoff             cond_synchronize_rcu
unrcu_pointer                   cond_synchronize_rcu_full
                                cond_synchronize_rcu_expedited
                                cond_synchronize_rcu_expedited_full
                                get_completed_synchronize_rcu
                                get_completed_synchronize_rcu_full
                                get_state_synchronize_rcu
                                get_state_synchronize_rcu_full
                                poll_state_synchronize_rcu
                                poll_state_synchronize_rcu_full
                                same_state_synchronize_rcu
                                same_state_synchronize_rcu_full
                                start_poll_synchronize_rcu
                                start_poll_synchronize_rcu_full
                                start_poll_synchronize_rcu_expedited
                                start_poll_synchronize_rcu_expedited_full
```

bh:



```text
Critical sections       Grace period            Barrier

rcu_read_lock_bh        [Same as RCU]           [Same as RCU]
rcu_read_unlock_bh
[local_bh_disable]
[and friends]
rcu_dereference_bh
rcu_dereference_bh_check
rcu_dereference_bh_protected
rcu_read_lock_bh_held
```

sched:



```text
Critical sections       Grace period            Barrier

rcu_read_lock_sched     [Same as RCU]           [Same as RCU]
rcu_read_unlock_sched
[preempt_disable]
[and friends]
rcu_read_lock_sched_notrace
rcu_read_unlock_sched_notrace
rcu_dereference_sched
rcu_dereference_sched_check
rcu_dereference_sched_protected
rcu_read_lock_sched_held
```

RCU: Initialization/cleanup/ordering:



```text
RCU_INIT_POINTER
RCU_INITIALIZER
RCU_POINTER_INITIALIZER
init_rcu_head
destroy_rcu_head
init_rcu_head_on_stack
destroy_rcu_head_on_stack
SLAB_TYPESAFE_BY_RCU
```

RCU: Quiescents states and control:



```text
cond_resched_tasks_rcu_qs
rcu_all_qs
rcu_softirq_qs_periodic
rcu_end_inkernel_boot
rcu_expedite_gp
rcu_gp_is_expedited
rcu_unexpedite_gp
rcu_cpu_stall_reset
rcu_head_after_call_rcu
rcu_is_watching
```

RCU-sync primitive:



```text
rcu_sync_is_idle
rcu_sync_init
rcu_sync_enter
rcu_sync_exit
rcu_sync_dtor
```

RCU-Tasks:



```text
Critical sections       Grace period                    Barrier

N/A                     call_rcu_tasks                  rcu_barrier_tasks
                        synchronize_rcu_tasks
```

RCU-Tasks-Rude:



```text
Critical sections       Grace period                    Barrier

N/A                     synchronize_rcu_tasks_rude      rcu_barrier_tasks_rude
                        call_rcu_tasks_rude
```

RCU-Tasks-Trace:



```text
Critical sections       Grace period                    Barrier

rcu_read_lock_trace     call_rcu_tasks_trace            rcu_barrier_tasks_trace
rcu_read_unlock_trace   synchronize_rcu_tasks_trace
guard(rcu_tasks_trace)()
scoped_guard(rcu_tasks_trace)
```

- **SRCU list traversal::**

  list\_for\_each\_entry\_srcu hlist\_for\_each\_entry\_srcu

SRCU:



```text
Critical sections               Grace period            Barrier

srcu_read_lock                  call_srcu               srcu_barrier
srcu_read_unlock                synchronize_srcu
srcu_read_lock_fast             synchronize_srcu_expedited
srcu_read_unlock_fast           get_state_synchronize_srcu
srcu_read_lock_nmisafe          start_poll_synchronize_srcu
srcu_read_unlock_nmisafe        start_poll_synchronize_srcu_expedited
srcu_read_lock_notrace          poll_state_synchronize_srcu
srcu_read_unlock_notrace
srcu_down_read
srcu_up_read
srcu_down_read_fast
srcu_up_read_fast
guard(srcu)()
scoped_guard(srcu)
srcu_read_lock_held
srcu_dereference
srcu_dereference_check
srcu_dereference_notrace
srcu_read_lock_held
```

SRCU: Initialization/cleanup/ordering:



```text
DEFINE_SRCU
DEFINE_STATIC_SRCU
DEFINE_SRCU_FAST        // for srcu_read_lock_fast() and friends
DEFINE_STATIC_SRCU_FAST // for srcu_read_lock_fast() and friends
init_srcu_struct
init_srcu_struct_fast
cleanup_srcu_struct
smp_mb__after_srcu_read_unlock
```

All: lockdep-checked RCU utility APIs:



```text
RCU_LOCKDEP_WARN
rcu_sleep_check
```

All: Unchecked RCU-protected pointer access:



```text
rcu_dereference_raw
```

All: Unchecked RCU-protected pointer access with dereferencing prohibited:



```text
rcu_access_pointer
```

See the comment headers in the source code (or the docbook generated from them) for more information.

However, given that there are no fewer than four families of RCU APIs in the Linux kernel, how do you choose which one to use?  The following list can be helpful:

- **a.** Will readers need to block?  If so, you need SRCU.

- **b.** Will readers need to block and are you doing tracing, for example, ftrace or BPF?  If so, you need RCU-tasks, RCU-tasks-rude, and/or RCU-tasks-trace.

- **c.** What about the -rt patchset?  If readers would need to block in an non-rt kernel, you need SRCU.  If readers would block when acquiring spinlocks in a -rt kernel, but not in a non-rt kernel, SRCU is not necessary.  (The -rt patchset turns spinlocks into sleeplocks, hence this distinction.)

- **d.** Do you need to treat NMI handlers, hardirq handlers, and code segments with preemption disabled (whether via preempt\_disable(), local\_irq\_save(), local\_bh\_disable(), or some other mechanism) as if they were explicit RCU readers? If so, RCU-sched readers are the only choice that will work for you, but since about v4.20 you use can use the vanilla RCU update primitives.

- **e.** Do you need RCU grace periods to complete even in the face of softirq monopolization of one or more of the CPUs?  For example, is your code subject to network-based denial-of-service attacks? If so, you should disable softirq across your readers, for example, by using rcu\_read\_lock\_bh().  Since about v4.20 you use can use the vanilla RCU update primitives.

- **f.** Is your workload too update-intensive for normal use of RCU, but inappropriate for other synchronization mechanisms? If so, consider SLAB\_TYPESAFE\_BY\_RCU (which was originally named SLAB\_DESTROY\_BY\_RCU).  But please be careful\!

- **g.** Do you need read-side critical sections that are respected even on CPUs that are deep in the idle loop, during entry to or exit from user-mode execution, or on an offlined CPU?  If so, SRCU and RCU Tasks Trace are the only choices that will work for you, with SRCU being strongly preferred in almost all cases.

- **h.** Otherwise, use RCU.

Of course, this all assumes that you have determined that RCU is in fact the right tool for your job.

<a id="rst-answers-to-quick-quizzes"></a>
<a id="rst-whatisrcu-8"></a>

## 9.  ANSWERS TO QUICK QUIZZES

- **Quick Quiz \#1:**

  Why is this argument naive?  How could a deadlock occur when using this algorithm in a real-world Linux kernel?  \[Referring to the lock-based "toy" RCU algorithm.\]

- **Answer:**

  Consider the following sequence of events:

  1. CPU 0 acquires some unrelated lock, call it "problematic\_lock", disabling irq via spin\_lock\_irqsave().

  2. CPU 1 enters synchronize\_rcu(), write-acquiring rcu\_gp\_mutex.

  3. CPU 0 enters rcu\_read\_lock(), but must wait because CPU 1 holds rcu\_gp\_mutex.

  4. CPU 1 is interrupted, and the irq handler attempts to acquire problematic\_lock.

  The system is now deadlocked.

  One way to avoid this deadlock is to use an approach like that of CONFIG\_PREEMPT\_RT, where all normal spinlocks become blocking locks, and all irq handlers execute in the context of special tasks.  In this case, in step 4 above, the irq handler would block, allowing CPU 1 to release rcu\_gp\_mutex, avoiding the deadlock.

  Even in the absence of deadlock, this RCU implementation allows latency to "bleed" from readers to other readers through synchronize\_rcu().  To see this, consider task A in an RCU read-side critical section (thus read-holding rcu\_gp\_mutex), task B blocked attempting to write-acquire rcu\_gp\_mutex, and task C blocked in rcu\_read\_lock() attempting to read\_acquire rcu\_gp\_mutex.  Task A's RCU read-side latency is holding up task C, albeit indirectly via task B.

  Realtime RCU implementations therefore use a counter-based approach where tasks in RCU read-side critical sections cannot be blocked by tasks executing synchronize\_rcu().

[Back to Quick Quiz \#1](<#rst-quiz-1>)

- **Quick Quiz \#2:**

  Give an example where Classic RCU's read-side overhead is <strong>negative</strong>.

- **Answer:**

  Imagine a single-CPU system with a non-CONFIG\_PREEMPTION kernel where a routing table is used by process-context code, but can be updated by irq-context code (for example, by an "ICMP REDIRECT" packet).  The usual way of handling this would be to have the process-context code disable interrupts while searching the routing table.  Use of RCU allows such interrupt-disabling to be dispensed with. Thus, without RCU, you pay the cost of disabling interrupts, and with RCU you don't.

  One can argue that the overhead of RCU in this case is negative with respect to the single-CPU interrupt-disabling approach.  Others might argue that the overhead of RCU is merely zero, and that replacing the positive overhead of the interrupt-disabling scheme with the zero-overhead RCU scheme does not constitute negative overhead.

  In real life, of course, things are more complex.  But even the theoretical possibility of negative overhead for a synchronization primitive is a bit unexpected.  ;-)

[Back to Quick Quiz \#2](<#rst-quiz-2>)

- **Quick Quiz \#3:**

  If it is illegal to block in an RCU read-side critical section, what the heck do you do in CONFIG\_PREEMPT\_RT, where normal spinlocks can block???

- **Answer:**

  Just as CONFIG\_PREEMPT\_RT permits preemption of spinlock critical sections, it permits preemption of RCU read-side critical sections.  It also permits spinlocks blocking while in RCU read-side critical sections.

  Why the apparent inconsistency?  Because it is possible to use priority boosting to keep the RCU grace periods short if need be (for example, if running short of memory).  In contrast, if blocking waiting for (say) network reception, there is no way to know what should be boosted.  Especially given that the process we need to boost might well be a human being who just went out for a pizza or something.  And although a computer-operated cattle prod might arouse serious interest, it might also provoke serious objections. Besides, how does the computer know what pizza parlor the human being went to???

[Back to Quick Quiz \#3](<#rst-quiz-3>)

ACKNOWLEDGEMENTS

My thanks to the people who helped make this human-readable, including Jon Walpole, Josh Triplett, Serge Hallyn, Suzanne Wood, and Alan Stern.

For more information, see [http://www.rdrop.com/users/paulmck/RCU](<http://www.rdrop.com/users/paulmck/RCU>).

---

# A Tour Through TREE_RCU's Data Structures [LWN.net]

_Peios Kernel / Internals / Read-copy-update (RCU) / Design / Data-Structures_

> December 18, 2016

<a id="rst-a-tour-through-tree-rcu-s-data-structures-lwn-net"></a>

December 18, 2016

This article was contributed by Paul E. McKenney

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

## Introduction

This document describes RCU's major data structures and their relationship to each other.

<a id="rst-data-structure-relationships"></a>

## Data-Structure Relationships

RCU is for all intents and purposes a large state machine, and its data structures maintain the state in such a way as to allow RCU readers to execute extremely quickly, while also processing the RCU grace periods requested by updaters in an efficient and extremely scalable fashion. The efficiency and scalability of RCU updaters is provided primarily by a combining tree, as shown below:

![](/kernel/internals/rcu/design-data-structures/asset-0ebc4af538b2-bigtreeclassicrcu.svg)

This diagram shows an enclosing `rcu_state` structure containing a tree of `rcu_node` structures. Each leaf node of the `rcu_node` tree has up to 16 `rcu_data` structures associated with it, so that there are `NR_CPUS` number of `rcu_data` structures, one for each possible CPU. This structure is adjusted at boot time, if needed, to handle the common case where `nr_cpu_ids` is much less than `NR_CPUs`. For example, a number of Linux distributions set `NR_CPUs=4096`, which results in a three-level `rcu_node` tree. If the actual hardware has only 16 CPUs, RCU will adjust itself at boot time, resulting in an `rcu_node` tree with only a single node.

The purpose of this combining tree is to allow per-CPU events such as quiescent states, dyntick-idle transitions, and CPU hotplug operations to be processed efficiently and scalably. Quiescent states are recorded by the per-CPU `rcu_data` structures, and other events are recorded by the leaf-level `rcu_node` structures. All of these events are combined at each level of the tree until finally grace periods are completed at the tree's root `rcu_node` structure. A grace period can be completed at the root once every CPU (or, in the case of `CONFIG_PREEMPT_RCU`, task) has passed through a quiescent state. Once a grace period has completed, record of that fact is propagated back down the tree.

As can be seen from the diagram, on a 64-bit system a two-level tree with 64 leaves can accommodate 1,024 CPUs, with a fanout of 64 at the root and a fanout of 16 at the leaves.


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


**Quick Quiz**:

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


Why isn't the fanout at the leaves also 64?

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


**Answer**:

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


Because there are more types of events that affect the leaf-level `rcu_node` structures than further up the tree. Therefore, if the leaf `rcu_node` structures have fanout of 64, the contention on these structures' `->structures` becomes excessive. Experimentation on a wide variety of systems has shown that a fanout of 16 works well for the leaves of the `rcu_node` tree.

Of course, further experience with systems having hundreds or thousands of CPUs may demonstrate that the fanout for the non-leaf `rcu_node` structures must also be reduced. Such reduction can be easily carried out when and if it proves necessary. In the meantime, if you are using such a system and running into contention problems on the non-leaf `rcu_node` structures, you may use the `CONFIG_RCU_FANOUT` kernel configuration parameter to reduce the non-leaf fanout as needed.

Kernels built for systems with strong NUMA characteristics might also need to adjust `CONFIG_RCU_FANOUT` so that the domains of the `rcu_node` structures align with hardware boundaries. However, there has thus far been no need for this.

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

If your system has more than 1,024 CPUs (or more than 512 CPUs on a 32-bit system), then RCU will automatically add more levels to the tree. For example, if you are crazy enough to build a 64-bit system with 65,536 CPUs, RCU would configure the `rcu_node` tree as follows:

![](/kernel/internals/rcu/design-data-structures/asset-b20b6095531d-hugetreeclassicrcu.svg)

RCU currently permits up to a four-level tree, which on a 64-bit system accommodates up to 4,194,304 CPUs, though only a mere 524,288 CPUs for 32-bit systems. On the other hand, you can set both `CONFIG_RCU_FANOUT` and `CONFIG_RCU_FANOUT_LEAF` to be as small as 2, which would result in a 16-CPU test using a 4-level tree. This can be useful for testing large-system capabilities on small test machines.

This multi-level combining tree allows us to get most of the performance and scalability benefits of partitioning, even though RCU grace-period detection is inherently a global operation. The trick here is that only the last CPU to report a quiescent state into a given `rcu_node` structure need advance to the `rcu_node` structure at the next level up the tree. This means that at the leaf-level `rcu_node` structure, only one access out of sixteen will progress up the tree. For the internal `rcu_node` structures, the situation is even more extreme: Only one access out of sixty-four will progress up the tree. Because the vast majority of the CPUs do not progress up the tree, the lock contention remains roughly constant up the tree. No matter how many CPUs there are in the system, at most 64 quiescent-state reports per grace period will progress all the way to the root `rcu_node` structure, thus ensuring that the lock contention on that root `rcu_node` structure remains acceptably low.

In effect, the combining tree acts like a big shock absorber, keeping lock contention under control at all tree levels regardless of the level of loading on the system.

RCU updaters wait for normal grace periods by registering RCU callbacks, either directly via `call_rcu()` or indirectly via `synchronize_rcu()` and friends. RCU callbacks are represented by `rcu_head` structures, which are queued on `rcu_data` structures while they are waiting for a grace period to elapse, as shown in the following figure:

![](/kernel/internals/rcu/design-data-structures/asset-97e9e4459bef-bigtreepreemptrcubhdyntickcb.svg)

This figure shows how `TREE_RCU`'s and `PREEMPT_RCU`'s major data structures are related. Lesser data structures will be introduced with the algorithms that make use of them.

Note that each of the data structures in the above figure has its own synchronization:

1. Each `rcu_state` structures has a lock and a mutex, and some fields are protected by the corresponding root `rcu_node` structure's lock.

2. Each `rcu_node` structure has a spinlock.

3. The fields in `rcu_data` are private to the corresponding CPU, although a few can be read and written by other CPUs.

It is important to note that different data structures can have very different ideas about the state of RCU at any given time. For but one example, awareness of the start or end of a given RCU grace period propagates slowly through the data structures. This slow propagation is absolutely necessary for RCU to have good read-side performance. If this balkanized implementation seems foreign to you, one useful trick is to consider each instance of these data structures to be a different person, each having the usual slightly different view of reality.

The general role of each of these data structures is as follows:

1. `rcu_state`: This structure forms the interconnection between the `rcu_node` and `rcu_data` structures, tracks grace periods, serves as short-term repository for callbacks orphaned by CPU-hotplug events, maintains `rcu_barrier()` state, tracks expedited grace-period state, and maintains state used to force quiescent states when grace periods extend too long,

2. `rcu_node`: This structure forms the combining tree that propagates quiescent-state information from the leaves to the root, and also propagates grace-period information from the root to the leaves. It provides local copies of the grace-period state in order to allow this information to be accessed in a synchronized manner without suffering the scalability limitations that would otherwise be imposed by global locking. In `CONFIG_PREEMPT_RCU` kernels, it manages the lists of tasks that have blocked while in their current RCU read-side critical section. In `CONFIG_PREEMPT_RCU` with `CONFIG_RCU_BOOST`, it manages the per-`rcu_node` priority-boosting kernel threads (kthreads) and state. Finally, it records CPU-hotplug state in order to determine which CPUs should be ignored during a given grace period.

3. `rcu_data`: This per-CPU structure is the focus of quiescent-state detection and RCU callback queuing. It also tracks its relationship to the corresponding leaf `rcu_node` structure to allow more-efficient propagation of quiescent states up the `rcu_node` combining tree. Like the `rcu_node` structure, it provides a local copy of the grace-period information to allow for-free synchronized access to this information from the corresponding CPU. Finally, this structure records past dyntick-idle state for the corresponding CPU and also tracks statistics.

4. `rcu_head`: This structure represents RCU callbacks, and is the only structure allocated and managed by RCU users. The `rcu_head` structure is normally embedded within the RCU-protected data structure.

If all you wanted from this article was a general notion of how RCU's data structures are related, you are done. Otherwise, each of the following sections give more details on the `rcu_state`, `rcu_node` and `rcu_data` data structures.

<a id="rst-the-rcu-state-structure"></a>

### The `rcu_state` Structure

The `rcu_state` structure is the base structure that represents the state of RCU in the system. This structure forms the interconnection between the `rcu_node` and `rcu_data` structures, tracks grace periods, contains the lock used to synchronize with CPU-hotplug events, and maintains state used to force quiescent states when grace periods extend too long,

A few of the `rcu_state` structure's fields are discussed, singly and in groups, in the following sections. The more specialized fields are covered in the discussion of their use.

<a id="rst-relationship-to-rcu-node-and-rcu-data-structures"></a>

#### Relationship to rcu_node and rcu_data Structures

This portion of the `rcu_state` structure is declared as follows:



```text
1   struct rcu_node node[NUM_RCU_NODES];
2   struct rcu_node *level[NUM_RCU_LVLS + 1];
3   struct rcu_data __percpu *rda;
```


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


**Quick Quiz**:

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


Wait a minute\! You said that the `rcu_node` structures formed a tree, but they are declared as a flat array\! What gives?

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


**Answer**:

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


The tree is laid out in the array. The first node In the array is the head, the next set of nodes in the array are children of the head node, and so on until the last set of nodes in the array are the leaves. See the following diagrams to see how this works.

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

The `rcu_node` tree is embedded into the `->node[]` array as shown in the following figure:

![](/kernel/internals/rcu/design-data-structures/asset-80ff88555096-treemapping.svg)

One interesting consequence of this mapping is that a breadth-first traversal of the tree is implemented as a simple linear scan of the array, which is in fact what the `rcu_for_each_node_breadth_first()` macro does. This macro is used at the beginning and ends of grace periods.

Each entry of the `->level` array references the first `rcu_node` structure on the corresponding level of the tree, for example, as shown below:

![](/kernel/internals/rcu/design-data-structures/asset-0503375d9f45-treemappinglevel.svg)

The zero<sup>th</sup> element of the array references the root `rcu_node` structure, the first element references the first child of the root `rcu_node`, and finally the second element references the first leaf `rcu_node` structure.

For whatever it is worth, if you draw the tree to be tree-shaped rather than array-shaped, it is easy to draw a planar representation:

![](/kernel/internals/rcu/design-data-structures/asset-0c5aeceff3c2-treelevel.svg)

Finally, the `->rda` field references a per-CPU pointer to the corresponding CPU's `rcu_data` structure.

All of these fields are constant once initialization is complete, and therefore need no protection.

<a id="rst-grace-period-tracking"></a>

#### Grace-Period Tracking

This portion of the `rcu_state` structure is declared as follows:



```text
1   unsigned long gp_seq;
```

RCU grace periods are numbered, and the `->gp_seq` field contains the current grace-period sequence number. The bottom two bits are the state of the current grace period, which can be zero for not yet started or one for in progress. In other words, if the bottom two bits of `->gp_seq` are zero, then RCU is idle. Any other value in the bottom two bits indicates that something is broken. This field is protected by the root `rcu_node` structure's `->lock` field.

There are `->gp_seq` fields in the `rcu_node` and `rcu_data` structures as well. The fields in the `rcu_state` structure represent the most current value, and those of the other structures are compared in order to detect the beginnings and ends of grace periods in a distributed fashion. The values flow from `rcu_state` to `rcu_node` (down the tree from the root to the leaves) to `rcu_data`.


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


**Quick Quiz**:

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


Given that the root rcu_node structure has a gp_seq field, why does RCU maintain a separate gp_seq in the rcu_state structure? Why not just use the root rcu_node's gp_seq as the official record and update it directly when starting a new grace period?

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


**Answer**:

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


On single-node RCU trees (where the root node is also a leaf), updating the root node's gp_seq immediately would create unnecessary lock contention. Here's why:

If we did rcu_seq_start() directly on the root node's gp_seq:

1. All CPUs would immediately see their node's gp_seq from their rdp's gp_seq, in rcu_pending(). They would all then invoke the RCU-core.

2. Which calls note_gp_changes() and try to acquire the node lock.

3. But rnp-&gt;qsmask isn't initialized yet (happens later in rcu_gp_init())

4. So each CPU would acquire the lock, find it can't determine if it needs to report quiescent state (no qsmask), update rdp-&gt;gp_seq, and release the lock.

5. Result: Lots of lock acquisitions with no grace period progress

By having a separate rcu_state.gp_seq, we can increment the official grace period counter without immediately affecting what CPUs see in their nodes. The hierarchical propagation in rcu_gp_init() then updates the root node's gp_seq and qsmask together under the same lock acquisition, avoiding this useless contention.

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

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

#### Miscellaneous

This portion of the `rcu_state` structure is declared as follows:



```text
1   unsigned long gp_max;
2   char abbr;
3   char *name;
```

The `->gp_max` field tracks the duration of the longest grace period in jiffies. It is protected by the root `rcu_node`'s `->lock`.

The `->name` and `->abbr` fields distinguish between preemptible RCU (“rcu_preempt” and “p”) and non-preemptible RCU (“rcu_sched” and “s”). These fields are used for diagnostic and tracing purposes.

<a id="rst-the-rcu-node-structure"></a>

### The `rcu_node` Structure

The `rcu_node` structures form the combining tree that propagates quiescent-state information from the leaves to the root and also that propagates grace-period information from the root down to the leaves. They provides local copies of the grace-period state in order to allow this information to be accessed in a synchronized manner without suffering the scalability limitations that would otherwise be imposed by global locking. In `CONFIG_PREEMPT_RCU` kernels, they manage the lists of tasks that have blocked while in their current RCU read-side critical section. In `CONFIG_PREEMPT_RCU` with `CONFIG_RCU_BOOST`, they manage the per-`rcu_node` priority-boosting kernel threads (kthreads) and state. Finally, they record CPU-hotplug state in order to determine which CPUs should be ignored during a given grace period.

The `rcu_node` structure's fields are discussed, singly and in groups, in the following sections.

<a id="rst-connection-to-combining-tree"></a>

#### Connection to Combining Tree

This portion of the `rcu_node` structure is declared as follows:



```text
1   struct rcu_node *parent;
2   u8 level;
3   u8 grpnum;
4   unsigned long grpmask;
5   int grplo;
6   int grphi;
```

The `->parent` pointer references the `rcu_node` one level up in the tree, and is `NULL` for the root `rcu_node`. The RCU implementation makes heavy use of this field to push quiescent states up the tree. The `->level` field gives the level in the tree, with the root being at level zero, its children at level one, and so on. The `->grpnum` field gives this node's position within the children of its parent, so this number can range between 0 and 31 on 32-bit systems and between 0 and 63 on 64-bit systems. The `->level` and `->grpnum` fields are used only during initialization and for tracing. The `->grpmask` field is the bitmask counterpart of `->grpnum`, and therefore always has exactly one bit set. This mask is used to clear the bit corresponding to this `rcu_node` structure in its parent's bitmasks, which are described later. Finally, the `->grplo` and `->grphi` fields contain the lowest and highest numbered CPU served by this `rcu_node` structure, respectively.

All of these fields are constant, and thus do not require any synchronization.

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

#### Synchronization

This field of the `rcu_node` structure is declared as follows:



```text
1   raw_spinlock_t lock;
```

This field is used to protect the remaining fields in this structure, unless otherwise stated. That said, all of the fields in this structure can be accessed without locking for tracing purposes. Yes, this can result in confusing traces, but better some tracing confusion than to be heisenbugged out of existence.

<a id="rst-grace-period-tracking-2"></a>
<a id="rst-grace-period-tracking-1"></a>

#### Grace-Period Tracking

This portion of the `rcu_node` structure is declared as follows:



```text
1   unsigned long gp_seq;
2   unsigned long gp_seq_needed;
```

The `rcu_node` structures' `->gp_seq` fields are the counterparts of the field of the same name in the `rcu_state` structure. They each may lag up to one step behind their `rcu_state` counterpart. If the bottom two bits of a given `rcu_node` structure's `->gp_seq` field is zero, then this `rcu_node` structure believes that RCU is idle.

The `>gp_seq` field of each `rcu_node` structure is updated at the beginning and the end of each grace period.

The `->gp_seq_needed` fields record the furthest-in-the-future grace period request seen by the corresponding `rcu_node` structure. The request is considered fulfilled when the value of the `->gp_seq` field equals or exceeds that of the `->gp_seq_needed` field.


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


**Quick Quiz**:

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


Suppose that this `rcu_node` structure doesn't see a request for a very long time. Won't wrapping of the `->gp_seq` field cause problems?

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


**Answer**:

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


No, because if the `->gp_seq_needed` field lags behind the `->gp_seq` field, the `->gp_seq_needed` field will be updated at the end of the grace period. Modulo-arithmetic comparisons therefore will always get the correct answer, even with wrapping.

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

<a id="rst-quiescent-state-tracking"></a>

#### Quiescent-State Tracking

These fields manage the propagation of quiescent states up the combining tree.

This portion of the `rcu_node` structure has fields as follows:



```text
1   unsigned long qsmask;
2   unsigned long expmask;
3   unsigned long qsmaskinit;
4   unsigned long expmaskinit;
```

The `->qsmask` field tracks which of this `rcu_node` structure's children still need to report quiescent states for the current normal grace period. Such children will have a value of 1 in their corresponding bit. Note that the leaf `rcu_node` structures should be thought of as having `rcu_data` structures as their children. Similarly, the `->expmask` field tracks which of this `rcu_node` structure's children still need to report quiescent states for the current expedited grace period. An expedited grace period has the same conceptual properties as a normal grace period, but the expedited implementation accepts extreme CPU overhead to obtain much lower grace-period latency, for example, consuming a few tens of microseconds worth of CPU time to reduce grace-period duration from milliseconds to tens of microseconds. The `->qsmaskinit` field tracks which of this `rcu_node` structure's children cover for at least one online CPU. This mask is used to initialize `->qsmask`, and `->expmaskinit` is used to initialize `->expmask` and the beginning of the normal and expedited grace periods, respectively.


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


**Quick Quiz**:

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


Why are these bitmasks protected by locking? Come on, haven't you heard of atomic instructions???

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


**Answer**:

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


Lockless grace-period computation\! Such a tantalizing possibility\! But consider the following sequence of events:

1. CPU 0 has been in dyntick-idle mode for quite some time. When it wakes up, it notices that the current RCU grace period needs it to report in, so it sets a flag where the scheduling clock interrupt will find it.

2. Meanwhile, CPU 1 is running `force_quiescent_state()`, and notices that CPU 0 has been in dyntick idle mode, which qualifies as an extended quiescent state.

3. CPU 0's scheduling clock interrupt fires in the middle of an RCU read-side critical section, and notices that the RCU core needs something, so commences RCU softirq processing.

4. CPU 0's softirq handler executes and is just about ready to report its quiescent state up the `rcu_node` tree.

5. But CPU 1 beats it to the punch, completing the current grace period and starting a new one.

6. CPU 0 now reports its quiescent state for the wrong grace period. That grace period might now end before the RCU read-side critical section. If that happens, disaster will ensue.

So the locking is absolutely required in order to coordinate clearing of the bits with updating of the grace-period sequence number in `->gp_seq`.

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

<a id="rst-blocked-task-management"></a>

#### Blocked-Task Management

`PREEMPT_RCU` allows tasks to be preempted in the midst of their RCU read-side critical sections, and these tasks must be tracked explicitly. The details of exactly why and how they are tracked will be covered in a separate article on RCU read-side processing. For now, it is enough to know that the `rcu_node` structure tracks them.



```text
1   struct list_head blkd_tasks;
2   struct list_head *gp_tasks;
3   struct list_head *exp_tasks;
4   bool wait_blkd_tasks;
```

The `->blkd_tasks` field is a list header for the list of blocked and preempted tasks. As tasks undergo context switches within RCU read-side critical sections, their `task_struct` structures are enqueued (via the `task_struct`'s `->rcu_node_entry` field) onto the head of the `->blkd_tasks` list for the leaf `rcu_node` structure corresponding to the CPU on which the outgoing context switch executed. As these tasks later exit their RCU read-side critical sections, they remove themselves from the list. This list is therefore in reverse time order, so that if one of the tasks is blocking the current grace period, all subsequent tasks must also be blocking that same grace period. Therefore, a single pointer into this list suffices to track all tasks blocking a given grace period. That pointer is stored in `->gp_tasks` for normal grace periods and in `->exp_tasks` for expedited grace periods. These last two fields are `NULL` if either there is no grace period in flight or if there are no blocked tasks preventing that grace period from completing. If either of these two pointers is referencing a task that removes itself from the `->blkd_tasks` list, then that task must advance the pointer to the next task on the list, or set the pointer to `NULL` if there are no subsequent tasks on the list.

For example, suppose that tasks T1, T2, and T3 are all hard-affinitied to the largest-numbered CPU in the system. Then if task T1 blocked in an RCU read-side critical section, then an expedited grace period started, then task T2 blocked in an RCU read-side critical section, then a normal grace period started, and finally task 3 blocked in an RCU read-side critical section, then the state of the last leaf `rcu_node` structure's blocked-task list would be as shown below:

![](/kernel/internals/rcu/design-data-structures/asset-986e8e02aaa9-blkd-task.svg)

Task T1 is blocking both grace periods, task T2 is blocking only the normal grace period, and task T3 is blocking neither grace period. Note that these tasks will not remove themselves from this list immediately upon resuming execution. They will instead remain on the list until they execute the outermost `rcu_read_unlock()` that ends their RCU read-side critical section.

The `->wait_blkd_tasks` field indicates whether or not the current grace period is waiting on a blocked task.

<a id="rst-sizing-the-rcu-node-array"></a>

#### Sizing the `rcu_node` Array

The `rcu_node` array is sized via a series of C-preprocessor expressions as follows:



```text
 1 #ifdef CONFIG_RCU_FANOUT
 2 #define RCU_FANOUT CONFIG_RCU_FANOUT
 3 #else
 4 # ifdef CONFIG_64BIT
 5 # define RCU_FANOUT 64
 6 # else
 7 # define RCU_FANOUT 32
 8 # endif
 9 #endif
10
11 #ifdef CONFIG_RCU_FANOUT_LEAF
12 #define RCU_FANOUT_LEAF CONFIG_RCU_FANOUT_LEAF
13 #else
14 # ifdef CONFIG_64BIT
15 # define RCU_FANOUT_LEAF 64
16 # else
17 # define RCU_FANOUT_LEAF 32
18 # endif
19 #endif
20
21 #define RCU_FANOUT_1        (RCU_FANOUT_LEAF)
22 #define RCU_FANOUT_2        (RCU_FANOUT_1 * RCU_FANOUT)
23 #define RCU_FANOUT_3        (RCU_FANOUT_2 * RCU_FANOUT)
24 #define RCU_FANOUT_4        (RCU_FANOUT_3 * RCU_FANOUT)
25
26 #if NR_CPUS <= RCU_FANOUT_1
27 #  define RCU_NUM_LVLS        1
28 #  define NUM_RCU_LVL_0        1
29 #  define NUM_RCU_NODES        NUM_RCU_LVL_0
30 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0 }
31 #  define RCU_NODE_NAME_INIT  { "rcu_node_0" }
32 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0" }
33 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0" }
34 #elif NR_CPUS <= RCU_FANOUT_2
35 #  define RCU_NUM_LVLS        2
36 #  define NUM_RCU_LVL_0        1
37 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
38 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1)
39 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1 }
40 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1" }
41 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1" }
42 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1" }
43 #elif NR_CPUS <= RCU_FANOUT_3
44 #  define RCU_NUM_LVLS        3
45 #  define NUM_RCU_LVL_0        1
46 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
47 #  define NUM_RCU_LVL_2        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
48 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2)
49 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2 }
50 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1", "rcu_node_2" }
51 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2" }
52 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2" }
53 #elif NR_CPUS <= RCU_FANOUT_4
54 #  define RCU_NUM_LVLS        4
55 #  define NUM_RCU_LVL_0        1
56 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_3)
57 #  define NUM_RCU_LVL_2        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
58 #  define NUM_RCU_LVL_3        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
59 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2 + NUM_RCU_LVL_3)
60 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2, NUM_RCU_LVL_3 }
61 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1", "rcu_node_2", "rcu_node_3" }
62 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2", "rcu_node_fqs_3" }
63 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2", "rcu_node_exp_3" }
64 #else
65 # error "CONFIG_RCU_FANOUT insufficient for NR_CPUS"
66 #endif
```

The maximum number of levels in the `rcu_node` structure is currently limited to four, as specified by lines 21-24 and the structure of the subsequent “if” statement. For 32-bit systems, this allows 16\*32\*32\*32=524,288 CPUs, which should be sufficient for the next few years at least. For 64-bit systems, 16\*64\*64\*64=4,194,304 CPUs is allowed, which should see us through the next decade or so. This four-level tree also allows kernels built with `CONFIG_RCU_FANOUT=8` to support up to 4096 CPUs, which might be useful in very large systems having eight CPUs per socket (but please note that no one has yet shown any measurable performance degradation due to misaligned socket and `rcu_node` boundaries). In addition, building kernels with a full four levels of `rcu_node` tree permits better testing of RCU's combining-tree code.

The `RCU_FANOUT` symbol controls how many children are permitted at each non-leaf level of the `rcu_node` tree. If the `CONFIG_RCU_FANOUT` Kconfig option is not specified, it is set based on the word size of the system, which is also the Kconfig default.

The `RCU_FANOUT_LEAF` symbol controls how many CPUs are handled by each leaf `rcu_node` structure. Experience has shown that allowing a given leaf `rcu_node` structure to handle 64 CPUs, as permitted by the number of bits in the `->qsmask` field on a 64-bit system, results in excessive contention for the leaf `rcu_node` structures' `->lock` fields. The number of CPUs per leaf `rcu_node` structure is therefore limited to 16 given the default value of `CONFIG_RCU_FANOUT_LEAF`. If `CONFIG_RCU_FANOUT_LEAF` is unspecified, the value selected is based on the word size of the system, just as for `CONFIG_RCU_FANOUT`. Lines 11-19 perform this computation.

Lines 21-24 compute the maximum number of CPUs supported by a single-level (which contains a single `rcu_node` structure), two-level, three-level, and four-level `rcu_node` tree, respectively, given the fanout specified by `RCU_FANOUT` and `RCU_FANOUT_LEAF`. These numbers of CPUs are retained in the `RCU_FANOUT_1`, `RCU_FANOUT_2`, `RCU_FANOUT_3`, and `RCU_FANOUT_4` C-preprocessor variables, respectively.

These variables are used to control the C-preprocessor `#if` statement spanning lines 26-66 that computes the number of `rcu_node` structures required for each level of the tree, as well as the number of levels required. The number of levels is placed in the `NUM_RCU_LVLS` C-preprocessor variable by lines 27, 35, 44, and 54. The number of `rcu_node` structures for the topmost level of the tree is always exactly one, and this value is unconditionally placed into `NUM_RCU_LVL_0` by lines 28, 36, 45, and 55. The rest of the levels (if any) of the `rcu_node` tree are computed by dividing the maximum number of CPUs by the fanout supported by the number of levels from the current level down, rounding up. This computation is performed by lines 37, 46-47, and 56-58. Lines 31-33, 40-42, 50-52, and 62-63 create initializers for lockdep lock-class names. Finally, lines 64-66 produce an error if the maximum number of CPUs is too large for the specified fanout.

<a id="rst-the-rcu-segcblist-structure"></a>

### The `rcu_segcblist` Structure

The `rcu_segcblist` structure maintains a segmented list of callbacks as follows:



```text
 1 #define RCU_DONE_TAIL        0
 2 #define RCU_WAIT_TAIL        1
 3 #define RCU_NEXT_READY_TAIL  2
 4 #define RCU_NEXT_TAIL        3
 5 #define RCU_CBLIST_NSEGS     4
 6
 7 struct rcu_segcblist {
 8   struct rcu_head *head;
 9   struct rcu_head **tails[RCU_CBLIST_NSEGS];
10   unsigned long gp_seq[RCU_CBLIST_NSEGS];
11   long len;
12   long len_lazy;
13 };
```

The segments are as follows:

1. `RCU_DONE_TAIL`: Callbacks whose grace periods have elapsed. These callbacks are ready to be invoked.

2. `RCU_WAIT_TAIL`: Callbacks that are waiting for the current grace period. Note that different CPUs can have different ideas about which grace period is current, hence the `->gp_seq` field.

3. `RCU_NEXT_READY_TAIL`: Callbacks waiting for the next grace period to start.

4. `RCU_NEXT_TAIL`: Callbacks that have not yet been associated with a grace period.

The `->head` pointer references the first callback or is `NULL` if the list contains no callbacks (which is *not* the same as being empty). Each element of the `->tails[]` array references the `->next` pointer of the last callback in the corresponding segment of the list, or the list's `->head` pointer if that segment and all previous segments are empty. If the corresponding segment is empty but some previous segment is not empty, then the array element is identical to its predecessor. Older callbacks are closer to the head of the list, and new callbacks are added at the tail. This relationship between the `->head` pointer, the `->tails[]` array, and the callbacks is shown in this diagram:

![](/kernel/internals/rcu/design-data-structures/asset-24a34ba242d9-nxtlist.svg)

In this figure, the `->head` pointer references the first RCU callback in the list. The `->tails[RCU_DONE_TAIL]` array element references the `->head` pointer itself, indicating that none of the callbacks is ready to invoke. The `->tails[RCU_WAIT_TAIL]` array element references callback CB 2's `->next` pointer, which indicates that CB 1 and CB 2 are both waiting on the current grace period, give or take possible disagreements about exactly which grace period is the current one. The `->tails[RCU_NEXT_READY_TAIL]` array element references the same RCU callback that `->tails[RCU_WAIT_TAIL]` does, which indicates that there are no callbacks waiting on the next RCU grace period. The `->tails[RCU_NEXT_TAIL]` array element references CB 4's `->next` pointer, indicating that all the remaining RCU callbacks have not yet been assigned to an RCU grace period. Note that the `->tails[RCU_NEXT_TAIL]` array element always references the last RCU callback's `->next` pointer unless the callback list is empty, in which case it references the `->head` pointer.

There is one additional important special case for the `->tails[RCU_NEXT_TAIL]` array element: It can be `NULL` when this list is *disabled*. Lists are disabled when the corresponding CPU is offline or when the corresponding CPU's callbacks are offloaded to a kthread, both of which are described elsewhere.

CPUs advance their callbacks from the `RCU_NEXT_TAIL` to the `RCU_NEXT_READY_TAIL` to the `RCU_WAIT_TAIL` to the `RCU_DONE_TAIL` list segments as grace periods advance.

The `->gp_seq[]` array records grace-period numbers corresponding to the list segments. This is what allows different CPUs to have different ideas as to which is the current grace period while still avoiding premature invocation of their callbacks. In particular, this allows CPUs that go idle for extended periods to determine which of their callbacks are ready to be invoked after reawakening.

The `->len` counter contains the number of callbacks in `->head`, and the `->len_lazy` contains the number of those callbacks that are known to only free memory, and whose invocation can therefore be safely deferred.

> [!IMPORTANT]
>
> It is the `->len` field that determines whether or not there are callbacks associated with this `rcu_segcblist` structure, *not* the `->head` pointer. The reason for this is that all the ready-to-invoke callbacks (that is, those in the `RCU_DONE_TAIL` segment) are extracted all at once at callback-invocation time (`rcu_do_batch`), due to which `->head` may be set to NULL if there are no not-done callbacks remaining in the `rcu_segcblist`. If callback invocation must be postponed, for example, because a high-priority process just woke up on this CPU, then the remaining callbacks are placed back on the `RCU_DONE_TAIL` segment and `->head` once again points to the start of the segment. In short, the head field can briefly be `NULL` even though the CPU has callbacks present the entire time. Therefore, it is not appropriate to test the `->head` pointer for `NULL`.

In contrast, the `->len` and `->len_lazy` counts are adjusted only after the corresponding callbacks have been invoked. This means that the `->len` count is zero only if the `rcu_segcblist` structure really is devoid of callbacks. Of course, off-CPU sampling of the `->len` count requires careful use of appropriate synchronization, for example, memory barriers. This synchronization can be a bit subtle, particularly in the case of `rcu_barrier()`.

<a id="rst-the-rcu-data-structure"></a>

### The `rcu_data` Structure

The `rcu_data` maintains the per-CPU state for the RCU subsystem. The fields in this structure may be accessed only from the corresponding CPU (and from tracing) unless otherwise stated. This structure is the focus of quiescent-state detection and RCU callback queuing. It also tracks its relationship to the corresponding leaf `rcu_node` structure to allow more-efficient propagation of quiescent states up the `rcu_node` combining tree. Like the `rcu_node` structure, it provides a local copy of the grace-period information to allow for-free synchronized access to this information from the corresponding CPU. Finally, this structure records past dyntick-idle state for the corresponding CPU and also tracks statistics.

The `rcu_data` structure's fields are discussed, singly and in groups, in the following sections.

<a id="rst-connection-to-other-data-structures"></a>

#### Connection to Other Data Structures

This portion of the `rcu_data` structure is declared as follows:



```text
1   int cpu;
2   struct rcu_node *mynode;
3   unsigned long grpmask;
4   bool beenonline;
```

The `->cpu` field contains the number of the corresponding CPU and the `->mynode` field references the corresponding `rcu_node` structure. The `->mynode` is used to propagate quiescent states up the combining tree. These two fields are constant and therefore do not require synchronization.

The `->grpmask` field indicates the bit in the `->mynode->qsmask` corresponding to this `rcu_data` structure, and is also used when propagating quiescent states. The `->beenonline` flag is set whenever the corresponding CPU comes online, which means that the debugfs tracing need not dump out any `rcu_data` structure for which this flag is not set.

<a id="rst-quiescent-state-and-grace-period-tracking"></a>

#### Quiescent-State and Grace-Period Tracking

This portion of the `rcu_data` structure is declared as follows:



```text
1   unsigned long gp_seq;
2   unsigned long gp_seq_needed;
3   bool cpu_no_qs;
4   bool core_needs_qs;
5   bool gpwrap;
```

The `->gp_seq` field is the counterpart of the field of the same name in the `rcu_state` and `rcu_node` structures. The `->gp_seq_needed` field is the counterpart of the field of the same name in the rcu_node structure. They may each lag up to one behind their `rcu_node` counterparts, but in `CONFIG_NO_HZ_IDLE` and `CONFIG_NO_HZ_FULL` kernels can lag arbitrarily far behind for CPUs in dyntick-idle mode (but these counters will catch up upon exit from dyntick-idle mode). If the lower two bits of a given `rcu_data` structure's `->gp_seq` are zero, then this `rcu_data` structure believes that RCU is idle.


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


**Quick Quiz**:

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


All this replication of the grace period numbers can only cause massive confusion. Why not just keep a global sequence number and be done with it???

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


**Answer**:

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


Because if there was only a single global sequence numbers, there would need to be a single global lock to allow safely accessing and updating it. And if we are not going to have a single global lock, we need to carefully manage the numbers on a per-node basis. Recall from the answer to a previous Quick Quiz that the consequences of applying a previously sampled quiescent state to the wrong grace period are quite severe.

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

The `->cpu_no_qs` flag indicates that the CPU has not yet passed through a quiescent state, while the `->core_needs_qs` flag indicates that the RCU core needs a quiescent state from the corresponding CPU. The `->gpwrap` field indicates that the corresponding CPU has remained idle for so long that the `gp_seq` counter is in danger of overflow, which will cause the CPU to disregard the values of its counters on its next exit from idle.

<a id="rst-rcu-callback-handling"></a>

#### RCU Callback Handling

In the absence of CPU-hotplug events, RCU callbacks are invoked by the same CPU that registered them. This is strictly a cache-locality optimization: callbacks can and do get invoked on CPUs other than the one that registered them. After all, if the CPU that registered a given callback has gone offline before the callback can be invoked, there really is no other choice.

This portion of the `rcu_data` structure is declared as follows:



```text
1 struct rcu_segcblist cblist;
2 long qlen_last_fqs_check;
3 unsigned long n_cbs_invoked;
4 unsigned long n_nocbs_invoked;
5 unsigned long n_cbs_orphaned;
6 unsigned long n_cbs_adopted;
7 unsigned long n_force_qs_snap;
8 long blimit;
```

The `->cblist` structure is the segmented callback list described earlier. The CPU advances the callbacks in its `rcu_data` structure whenever it notices that another RCU grace period has completed. The CPU detects the completion of an RCU grace period by noticing that the value of its `rcu_data` structure's `->gp_seq` field differs from that of its leaf `rcu_node` structure. Recall that each `rcu_node` structure's `->gp_seq` field is updated at the beginnings and ends of each grace period.

The `->qlen_last_fqs_check` and `->n_force_qs_snap` coordinate the forcing of quiescent states from `call_rcu()` and friends when callback lists grow excessively long.

The `->n_cbs_invoked`, `->n_cbs_orphaned`, and `->n_cbs_adopted` fields count the number of callbacks invoked, sent to other CPUs when this CPU goes offline, and received from other CPUs when those other CPUs go offline. The `->n_nocbs_invoked` is used when the CPU's callbacks are offloaded to a kthread.

Finally, the `->blimit` counter is the maximum number of RCU callbacks that may be invoked at a given time.

<a id="rst-dyntick-idle-handling"></a>

#### Dyntick-Idle Handling

This portion of the `rcu_data` structure is declared as follows:



```text
1   int watching_snap;
2   unsigned long dynticks_fqs;
```

The `->watching_snap` field is used to take a snapshot of the corresponding CPU's dyntick-idle state when forcing quiescent states, and is therefore accessed from other CPUs. Finally, the `->dynticks_fqs` field is used to count the number of times this CPU is determined to be in dyntick-idle state, and is used for tracing and debugging purposes.

This portion of the rcu_data structure is declared as follows:



```text
1   long nesting;
2   long nmi_nesting;
3   atomic_t dynticks;
4   bool rcu_need_heavy_qs;
5   bool rcu_urgent_qs;
```

These fields in the rcu_data structure maintain the per-CPU dyntick-idle state for the corresponding CPU. The fields may be accessed only from the corresponding CPU (and from tracing) unless otherwise stated.

The `->nesting` field counts the nesting depth of process execution, so that in normal circumstances this counter has value zero or one. NMIs, irqs, and tracers are counted by the `->nmi_nesting` field. Because NMIs cannot be masked, changes to this variable have to be undertaken carefully using an algorithm provided by Andy Lutomirski. The initial transition from idle adds one, and nested transitions add two, so that a nesting level of five is represented by a `->nmi_nesting` value of nine. This counter can therefore be thought of as counting the number of reasons why this CPU cannot be permitted to enter dyntick-idle mode, aside from process-level transitions.

However, it turns out that when running in non-idle kernel context, the Linux kernel is fully capable of entering interrupt handlers that never exit and perhaps also vice versa. Therefore, whenever the `->nesting` field is incremented up from zero, the `->nmi_nesting` field is set to a large positive number, and whenever the `->nesting` field is decremented down to zero, the `->nmi_nesting` field is set to zero. Assuming that the number of misnested interrupts is not sufficient to overflow the counter, this approach corrects the `->nmi_nesting` field every time the corresponding CPU enters the idle loop from process context.

The `->dynticks` field counts the corresponding CPU's transitions to and from either dyntick-idle or user mode, so that this counter has an even value when the CPU is in dyntick-idle mode or user mode and an odd value otherwise. The transitions to/from user mode need to be counted for user mode adaptive-ticks support (see [Documentation/timers/no_hz.rst](/kernel/internals/timers/no-hz.md)).

The `->rcu_need_heavy_qs` field is used to record the fact that the RCU core code would really like to see a quiescent state from the corresponding CPU, so much so that it is willing to call for heavy-weight dyntick-counter operations. This flag is checked by RCU's context-switch and `cond_resched()` code, which provide a momentary idle sojourn in response.

Finally, the `->rcu_urgent_qs` field is used to record the fact that the RCU core code would really like to see a quiescent state from the corresponding CPU, with the various other fields indicating just how badly RCU wants this quiescent state. This flag is checked by RCU's context-switch path (`rcu_note_context_switch`) and the cond_resched code.


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


**Quick Quiz**:

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


Why not simply combine the `->nesting` and `->nmi_nesting` counters into a single counter that just counts the number of reasons that the corresponding CPU is non-idle?

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


**Answer**:

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


Because this would fail in the presence of interrupts whose handlers never return and of handlers that manage to return from a made-up interrupt.

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

Additional fields are present for some special-purpose builds, and are discussed separately.

<a id="rst-the-rcu-head-structure"></a>

### The `rcu_head` Structure

Each `rcu_head` structure represents an RCU callback. These structures are normally embedded within RCU-protected data structures whose algorithms use asynchronous grace periods. In contrast, when using algorithms that block waiting for RCU grace periods, RCU users need not provide `rcu_head` structures.

The `rcu_head` structure has fields as follows:



```text
1   struct rcu_head *next;
2   void (*func)(struct rcu_head *head);
```

The `->next` field is used to link the `rcu_head` structures together in the lists within the `rcu_data` structures. The `->func` field is a pointer to the function to be called when the callback is ready to be invoked, and this function is passed a pointer to the `rcu_head` structure. However, `kfree_rcu()` uses the `->func` field to record the offset of the `rcu_head` structure within the enclosing RCU-protected data structure.

Both of these fields are used internally by RCU. From the viewpoint of RCU users, this structure is an opaque “cookie”.


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


**Quick Quiz**:

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


Given that the callback function `->func` is passed a pointer to the `rcu_head` structure, how is that function supposed to find the beginning of the enclosing RCU-protected data structure?

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


**Answer**:

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


In actual practice, there is a separate callback function per type of RCU-protected data structure. The callback function can therefore use the `container_of()` macro in the Linux kernel (or other pointer-manipulation facilities in other software environments) to find the beginning of the enclosing structure.

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

<a id="rst-rcu-specific-fields-in-the-task-struct-structure"></a>

### RCU-Specific Fields in the `task_struct` Structure

The `CONFIG_PREEMPT_RCU` implementation uses some additional fields in the `task_struct` structure:



```text
 1 #ifdef CONFIG_PREEMPT_RCU
 2   int rcu_read_lock_nesting;
 3   union rcu_special rcu_read_unlock_special;
 4   struct list_head rcu_node_entry;
 5   struct rcu_node *rcu_blocked_node;
 6 #endif /* #ifdef CONFIG_PREEMPT_RCU */
 7 #ifdef CONFIG_TASKS_RCU
 8   unsigned long rcu_tasks_nvcsw;
 9   bool rcu_tasks_holdout;
10   struct list_head rcu_tasks_holdout_list;
11   int rcu_tasks_idle_cpu;
12 #endif /* #ifdef CONFIG_TASKS_RCU */
```

The `->rcu_read_lock_nesting` field records the nesting level for RCU read-side critical sections, and the `->rcu_read_unlock_special` field is a bitmask that records special conditions that require `rcu_read_unlock()` to do additional work. The `->rcu_node_entry` field is used to form lists of tasks that have blocked within preemptible-RCU read-side critical sections and the `->rcu_blocked_node` field references the `rcu_node` structure whose list this task is a member of, or `NULL` if it is not blocked within a preemptible-RCU read-side critical section.

The `->rcu_tasks_nvcsw` field tracks the number of voluntary context switches that this task had undergone at the beginning of the current tasks-RCU grace period, `->rcu_tasks_holdout` is set if the current tasks-RCU grace period is waiting on this task, `->rcu_tasks_holdout_list` is a list element enqueuing this task on the holdout list, and `->rcu_tasks_idle_cpu` tracks which CPU this idle task is running, but only if the task is currently running, that is, if the CPU is currently idle.

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

### Accessor Functions

The following listing shows the `rcu_get_root()`, `rcu_for_each_node_breadth_first` and `rcu_for_each_leaf_node()` function and macros:



```text
 1 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
 2 {
 3   return &rsp->node[0];
 4 }
 5
 6 #define rcu_for_each_node_breadth_first(rsp, rnp) \
 7   for ((rnp) = &(rsp)->node[0]; \
 8        (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)
 9
10 #define rcu_for_each_leaf_node(rsp, rnp) \
11   for ((rnp) = (rsp)->level[NUM_RCU_LVLS - 1]; \
12        (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)
```

The `rcu_get_root()` simply returns a pointer to the first element of the specified `rcu_state` structure's `->node[]` array, which is the root `rcu_node` structure.

As noted earlier, the `rcu_for_each_node_breadth_first()` macro takes advantage of the layout of the `rcu_node` structures in the `rcu_state` structure's `->node[]` array, performing a breadth-first traversal by simply traversing the array in order. Similarly, the `rcu_for_each_leaf_node()` macro traverses only the last part of the array, thus traversing only the leaf `rcu_node` structures.


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


**Quick Quiz**:

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


What does `rcu_for_each_leaf_node()` do if the `rcu_node` tree contains only a single node?

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


**Answer**:

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


In the single-node case, `rcu_for_each_leaf_node()` traverses the single node.

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

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

### Summary

So the state of RCU is represented by an `rcu_state` structure, which contains a combining tree of `rcu_node` and `rcu_data` structures. Finally, in `CONFIG_NO_HZ_IDLE` kernels, each CPU's dyntick-idle state is tracked by dynticks-related fields in the `rcu_data` structure. If you made it this far, you are well prepared to read the code walkthroughs in the other articles in this series.

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

### Acknowledgments

I owe thanks to Cyrill Gorcunov, Mathieu Desnoyers, Dhaval Giani, Paul Turner, Abhishek Srivastava, Matt Kowalczyk, and Serge Hallyn for helping me get this document into a more human-readable state.

<a id="rst-legal-statement"></a>

### Legal Statement

This work represents the view of the author and does not necessarily represent the view of IBM.

Linux is a registered trademark of Linus Torvalds.

Other company, product, and service names may be trademarks or service marks of others.

---

# A Tour Through TREE_RCU's Expedited Grace Periods

_Peios Kernel / Internals / Read-copy-update (RCU) / Design / Expedited-Grace-Periods_

> This document describes RCU's expedited grace periods. Unlike RCU's normal grace periods, which accept long latencies to attain high efficiency and minimal disturbance, expedited grace periods accept lower efficiency and significant…

<a id="rst-a-tour-through-tree-rcu-s-expedited-grace-periods"></a>

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

## Introduction

This document describes RCU's expedited grace periods. Unlike RCU's normal grace periods, which accept long latencies to attain high efficiency and minimal disturbance, expedited grace periods accept lower efficiency and significant disturbance to attain shorter latencies.

There are two flavors of RCU (RCU-preempt and RCU-sched), with an earlier third RCU-bh flavor having been implemented in terms of the other two. Each of the two implementations is covered in its own section.

<a id="rst-expedited-grace-period-design"></a>

## Expedited Grace Period Design

The expedited RCU grace periods cannot be accused of being subtle, given that they for all intents and purposes hammer every CPU that has not yet provided a quiescent state for the current expedited grace period. The one saving grace is that the hammer has grown a bit smaller over time:  The old call to `try_stop_cpus()` has been replaced with a set of calls to `smp_call_function_single()`, each of which results in an IPI to the target CPU. The corresponding handler function checks the CPU's state, motivating a faster quiescent state where possible, and triggering a report of that quiescent state. As always for RCU, once everything has spent some time in a quiescent state, the expedited grace period has completed.

The details of the `smp_call_function_single()` handler's operation depend on the RCU flavor, as described in the following sections.

<a id="rst-rcu-preempt-expedited-grace-periods"></a>

## RCU-preempt Expedited Grace Periods

`CONFIG_PREEMPTION=y` kernels implement RCU-preempt. The overall flow of the handling of a given CPU by an RCU-preempt expedited grace period is shown in the following diagram:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-4ee2bdc343a7-exprcuflow.svg)

The solid arrows denote direct action, for example, a function call. The dotted arrows denote indirect action, for example, an IPI or a state that is reached after some time.

If a given CPU is offline or idle, `synchronize_rcu_expedited()` will ignore it because idle and offline CPUs are already residing in quiescent states. Otherwise, the expedited grace period will use `smp_call_function_single()` to send the CPU an IPI, which is handled by `rcu_exp_handler()`.

However, because this is preemptible RCU, `rcu_exp_handler()` can check to see if the CPU is currently running in an RCU read-side critical section. If not, the handler can immediately report a quiescent state. Otherwise, it sets flags so that the outermost `rcu_read_unlock()` invocation will provide the needed quiescent-state report. This flag-setting avoids the previous forced preemption of all CPUs that might have RCU read-side critical sections. In addition, this flag-setting is done so as to avoid increasing the overhead of the common-case fastpath through the scheduler.

Again because this is preemptible RCU, an RCU read-side critical section can be preempted. When that happens, RCU will enqueue the task, which will the continue to block the current expedited grace period until it resumes and finds its outermost `rcu_read_unlock()`. The CPU will report a quiescent state just after enqueuing the task because the CPU is no longer blocking the grace period. It is instead the preempted task doing the blocking. The list of blocked tasks is managed by `rcu_preempt_ctxt_queue()`, which is called from `rcu_preempt_note_context_switch()`, which in turn is called from `rcu_note_context_switch()`, which in turn is called from the scheduler.


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


**Quick Quiz**:

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


Why not just have the expedited grace period check the state of all the CPUs? After all, that would avoid all those real-time-unfriendly IPIs.

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


**Answer**:

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


Because we want the RCU read-side critical sections to run fast, which means no memory barriers. Therefore, it is not possible to safely check the state from some other CPU. And even if it was possible to safely check the state, it would still be necessary to IPI the CPU to safely interact with the upcoming `rcu_read_unlock()` invocation, which means that the remote state testing would not help the worst-case latency that real-time applications care about.

One way to prevent your real-time application from getting hit with these IPIs is to build your kernel with `CONFIG_NO_HZ_FULL=y`. RCU would then perceive the CPU running your application as being idle, and it would be able to safely detect that state without needing to IPI the CPU.

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

Please note that this is just the overall flow: Additional complications can arise due to races with CPUs going idle or offline, among other things.

<a id="rst-rcu-sched-expedited-grace-periods"></a>

### RCU-sched Expedited Grace Periods

`CONFIG_PREEMPTION=n` kernels implement RCU-sched. The overall flow of the handling of a given CPU by an RCU-sched expedited grace period is shown in the following diagram:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-943f6f31e0a6-expschedflow.svg)

As with RCU-preempt, RCU-sched's `synchronize_rcu_expedited()` ignores offline and idle CPUs, again because they are in remotely detectable quiescent states. However, because the `rcu_read_lock_sched()` and `rcu_read_unlock_sched()` leave no trace of their invocation, in general it is not possible to tell whether or not the current CPU is in an RCU read-side critical section. The best that RCU-sched's `rcu_exp_handler()` can do is to check for idle, on the off-chance that the CPU went idle while the IPI was in flight. If the CPU is idle, then `rcu_exp_handler()` reports the quiescent state.

Otherwise, the handler forces a future context switch by setting the NEED_RESCHED flag of the current task's thread flag and the CPU preempt counter. At the time of the context switch, the CPU reports the quiescent state. Should the CPU go offline first, it will report the quiescent state at that time.

<a id="rst-expedited-grace-period-and-cpu-hotplug"></a>

### Expedited Grace Period and CPU Hotplug

The expedited nature of expedited grace periods require a much tighter interaction with CPU hotplug operations than is required for normal grace periods. In addition, attempting to IPI offline CPUs will result in splats, but failing to IPI online CPUs can result in too-short grace periods. Neither option is acceptable in production kernels.

The interaction between expedited grace periods and CPU hotplug operations is carried out at several levels:

1. The number of CPUs that have ever been online is tracked by the `rcu_state` structure's `->ncpus` field. The `rcu_state` structure's `->ncpus_snap` field tracks the number of CPUs that have ever been online at the beginning of an RCU expedited grace period. Note that this number never decreases, at least in the absence of a time machine.

2. The identities of the CPUs that have ever been online is tracked by the `rcu_node` structure's `->expmaskinitnext` field. The `rcu_node` structure's `->expmaskinit` field tracks the identities of the CPUs that were online at least once at the beginning of the most recent RCU expedited grace period. The `rcu_state` structure's `->ncpus` and `->ncpus_snap` fields are used to detect when new CPUs have come online for the first time, that is, when the `rcu_node` structure's `->expmaskinitnext` field has changed since the beginning of the last RCU expedited grace period, which triggers an update of each `rcu_node` structure's `->expmaskinit` field from its `->expmaskinitnext` field.

3. Each `rcu_node` structure's `->expmaskinit` field is used to initialize that structure's `->expmask` at the beginning of each RCU expedited grace period. This means that only those CPUs that have been online at least once will be considered for a given grace period.

4. Any CPU that goes offline will clear its bit in its leaf `rcu_node` structure's `->qsmaskinitnext` field, so any CPU with that bit clear can safely be ignored. However, it is possible for a CPU coming online or going offline to have this bit set for some time while `cpu_online` returns `false`.

5. For each non-idle CPU that RCU believes is currently online, the grace period invokes `smp_call_function_single()`. If this succeeds, the CPU was fully online. Failure indicates that the CPU is in the process of coming online or going offline, in which case it is necessary to wait for a short time period and try again. The purpose of this wait (or series of waits, as the case may be) is to permit a concurrent CPU-hotplug operation to complete.

6. In the case of RCU-sched, one of the last acts of an outgoing CPU is to invoke `rcutree_report_cpu_dead()`, which reports a quiescent state for that CPU. However, this is likely paranoia-induced redundancy.


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


**Quick Quiz**:

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


Why all the dancing around with multiple counters and masks tracking CPUs that were once online? Why not just have a single set of masks tracking the currently online CPUs and be done with it?

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


**Answer**:

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


Maintaining single set of masks tracking the online CPUs *sounds* easier, at least until you try working out all the race conditions between grace-period initialization and CPU-hotplug operations. For example, suppose initialization is progressing down the tree while a CPU-offline operation is progressing up the tree. This situation can result in bits set at the top of the tree that have no counterparts at the bottom of the tree. Those bits will never be cleared, which will result in grace-period hangs. In short, that way lies madness, to say nothing of a great many bugs, hangs, and deadlocks. In contrast, the current multi-mask multi-counter scheme ensures that grace-period initialization will always see consistent masks up and down the tree, which brings significant simplifications over the single-mask method.

This is an instance of [deferring work in order to avoid synchronization](<http://www.cs.columbia.edu/~library/TR-repository/reports/reports-1992/cucs-039-92.ps.gz>). Lazily recording CPU-hotplug events at the beginning of the next grace period greatly simplifies maintenance of the CPU-tracking bitmasks in the `rcu_node` tree.

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

<a id="rst-expedited-grace-period-refinements"></a>

### Expedited Grace Period Refinements

<a id="rst-idle-cpu-checks"></a>

#### Idle-CPU Checks

Each expedited grace period checks for idle CPUs when initially forming the mask of CPUs to be IPIed and again just before IPIing a CPU (both checks are carried out by `sync_rcu_exp_select_cpus()`). If the CPU is idle at any time between those two times, the CPU will not be IPIed. Instead, the task pushing the grace period forward will include the idle CPUs in the mask passed to `rcu_report_exp_cpu_mult()`.

For RCU-sched, there is an additional check: If the IPI has interrupted the idle loop, then `rcu_exp_handler()` invokes `rcu_report_exp_rdp()` to report the corresponding quiescent state.

For RCU-preempt, there is no specific check for idle in the IPI handler (`rcu_exp_handler()`), but because RCU read-side critical sections are not permitted within the idle loop, if `rcu_exp_handler()` sees that the CPU is within RCU read-side critical section, the CPU cannot possibly be idle. Otherwise, `rcu_exp_handler()` invokes `rcu_report_exp_rdp()` to report the corresponding quiescent state, regardless of whether or not that quiescent state was due to the CPU being idle.

In summary, RCU expedited grace periods check for idle when building the bitmask of CPUs that must be IPIed, just before sending each IPI, and (either explicitly or implicitly) within the IPI handler.

<a id="rst-batching-via-sequence-counter"></a>

#### Batching via Sequence Counter

If each grace-period request was carried out separately, expedited grace periods would have abysmal scalability and problematic high-load characteristics. Because each grace-period operation can serve an unlimited number of updates, it is important to *batch* requests, so that a single expedited grace-period operation will cover all requests in the corresponding batch.

This batching is controlled by a sequence counter named `->expedited_sequence` in the `rcu_state` structure. This counter has an odd value when there is an expedited grace period in progress and an even value otherwise, so that dividing the counter value by two gives the number of completed grace periods. During any given update request, the counter must transition from even to odd and then back to even, thus indicating that a grace period has elapsed. Therefore, if the initial value of the counter is `s`, the updater must wait until the counter reaches at least the value `(s+3)&~0x1`. This counter is managed by the following access functions:

1. `rcu_exp_gp_seq_start()`, which marks the start of an expedited grace period.

2. `rcu_exp_gp_seq_end()`, which marks the end of an expedited grace period.

3. `rcu_exp_gp_seq_snap()`, which obtains a snapshot of the counter.

4. `rcu_exp_gp_seq_done()`, which returns `true` if a full expedited grace period has elapsed since the corresponding call to `rcu_exp_gp_seq_snap()`.

Again, only one request in a given batch need actually carry out a grace-period operation, which means there must be an efficient way to identify which of many concurrent requests will initiate the grace period, and that there be an efficient way for the remaining requests to wait for that grace period to complete. However, that is the topic of the next section.

<a id="rst-funnel-locking-and-wait-wakeup"></a>

#### Funnel Locking and Wait/Wakeup

The natural way to sort out which of a batch of updaters will initiate the expedited grace period is to use the `rcu_node` combining tree, as implemented by the `exp_funnel_lock()` function. The first updater corresponding to a given grace period arriving at a given `rcu_node` structure records its desired grace-period sequence number in the `->exp_seq_rq` field and moves up to the next level in the tree. Otherwise, if the `->exp_seq_rq` field already contains the sequence number for the desired grace period or some later one, the updater blocks on one of four wait queues in the `->exp_wq[]` array, using the second-from-bottom and third-from bottom bits as an index. An `->exp_lock` field in the `rcu_node` structure synchronizes access to these fields.

An empty `rcu_node` tree is shown in the following diagram, with the white cells representing the `->exp_seq_rq` field and the red cells representing the elements of the `->exp_wq[]` array.

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-309ba263549e-funnel0.svg)

The next diagram shows the situation after the arrival of Task A and Task B at the leftmost and rightmost leaf `rcu_node` structures, respectively. The current value of the `rcu_state` structure's `->expedited_sequence` field is zero, so adding three and clearing the bottom bit results in the value two, which both tasks record in the `->exp_seq_rq` field of their respective `rcu_node` structures:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-456d54316ada-funnel1.svg)

Each of Tasks A and B will move up to the root `rcu_node` structure. Suppose that Task A wins, recording its desired grace-period sequence number and resulting in the state shown below:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-d831d2358361-funnel2.svg)

Task A now advances to initiate a new grace period, while Task B moves up to the root `rcu_node` structure, and, seeing that its desired sequence number is already recorded, blocks on `->exp_wq[1]`.


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


**Quick Quiz**:

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


Why `->exp_wq[1]`? Given that the value of these tasks' desired sequence number is two, so shouldn't they instead block on `->exp_wq[2]`?

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


**Answer**:

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


No. Recall that the bottom bit of the desired sequence number indicates whether or not a grace period is currently in progress. It is therefore necessary to shift the sequence number right one bit position to obtain the number of the grace period. This results in `->exp_wq[1]`.

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

If Tasks C and D also arrive at this point, they will compute the same desired grace-period sequence number, and see that both leaf `rcu_node` structures already have that value recorded. They will therefore block on their respective `rcu_node` structures' `->exp_wq[1]` fields, as shown below:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-66b22526be32-funnel3.svg)

Task A now acquires the `rcu_state` structure's `->exp_mutex` and initiates the grace period, which increments `->expedited_sequence`. Therefore, if Tasks E and F arrive, they will compute a desired sequence number of 4 and will record this value as shown below:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-19889b5e4dc8-funnel4.svg)

Tasks E and F will propagate up the `rcu_node` combining tree, with Task F blocking on the root `rcu_node` structure and Task E wait for Task A to finish so that it can start the next grace period. The resulting state is as shown below:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-9453c918e49b-funnel5.svg)

Once the grace period completes, Task A starts waking up the tasks waiting for this grace period to complete, increments the `->expedited_sequence`, acquires the `->exp_wake_mutex` and then releases the `->exp_mutex`. This results in the following state:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-190061b7db22-funnel6.svg)

Task E can then acquire `->exp_mutex` and increment `->expedited_sequence` to the value three. If new tasks G and H arrive and moves up the combining tree at the same time, the state will be as follows:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-5431608c3cb6-funnel7.svg)

Note that three of the root `rcu_node` structure's waitqueues are now occupied. However, at some point, Task A will wake up the tasks blocked on the `->exp_wq` waitqueues, resulting in the following state:

![](/kernel/internals/rcu/design-expedited-grace-periods/asset-0b0592126109-funnel8.svg)

Execution will continue with Tasks E and H completing their grace periods and carrying out their wakeups.


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


**Quick Quiz**:

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


What happens if Task A takes so long to do its wakeups that Task E's grace period completes?

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


**Answer**:

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


Then Task E will block on the `->exp_wake_mutex`, which will also prevent it from releasing `->exp_mutex`, which in turn will prevent the next grace period from starting. This last is important in preventing overflow of the `->exp_wq[]` array.

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

<a id="rst-use-of-workqueues"></a>

#### Use of Workqueues

In earlier implementations, the task requesting the expedited grace period also drove it to completion. This straightforward approach had the disadvantage of needing to account for POSIX signals sent to user tasks, so more recent implementations use the Linux kernel's workqueues (see [Documentation/core-api/workqueue.rst](/kernel/internals/core-api/workqueue.md)).

The requesting task still does counter snapshotting and funnel-lock processing, but the task reaching the top of the funnel lock does a `schedule_work()` (from `_synchronize_rcu_expedited()` so that a workqueue kthread does the actual grace-period processing. Because workqueue kthreads do not accept POSIX signals, grace-period-wait processing need not allow for POSIX signals. In addition, this approach allows wakeups for the previous expedited grace period to be overlapped with processing for the next expedited grace period. Because there are only four sets of waitqueues, it is necessary to ensure that the previous grace period's wakeups complete before the next grace period's wakeups start. This is handled by having the `->exp_mutex` guard expedited grace-period processing and the `->exp_wake_mutex` guard wakeups. The key point is that the `->exp_mutex` is not released until the first wakeup is complete, which means that the `->exp_wake_mutex` has already been acquired at that point. This approach ensures that the previous grace period's wakeups can be carried out while the current grace period is in process, but that these wakeups will complete before the next grace period starts. This means that only three waitqueues are required, guaranteeing that the four that are provided are sufficient.

<a id="rst-stall-warnings"></a>

#### Stall Warnings

Expediting grace periods does nothing to speed things up when RCU readers take too long, and therefore expedited grace periods check for stalls just as normal grace periods do.


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


**Quick Quiz**:

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


But why not just let the normal grace-period machinery detect the stalls, given that a given reader must block both normal and expedited grace periods?

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


**Answer**:

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


Because it is quite possible that at a given time there is no normal grace period in progress, in which case the normal grace period cannot emit a stall warning.

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

The `synchronize_sched_expedited_wait()` function loops waiting for the expedited grace period to end, but with a timeout set to the current RCU CPU stall-warning time. If this time is exceeded, any CPUs or `rcu_node` structures blocking the current grace period are printed. Each stall warning results in another pass through the loop, but the second and subsequent passes use longer stall times.

<a id="rst-mid-boot-operation"></a>

#### Mid-boot operation

The use of workqueues has the advantage that the expedited grace-period code need not worry about POSIX signals. Unfortunately, it has the corresponding disadvantage that workqueues cannot be used until they are initialized, which does not happen until some time after the scheduler spawns the first task. Given that there are parts of the kernel that really do want to execute grace periods during this mid-boot “dead zone”, expedited grace periods must do something else during this time.

What they do is to fall back to the old practice of requiring that the requesting task drive the expedited grace period, as was the case before the use of workqueues. However, the requesting task is only required to drive the grace period during the mid-boot dead zone. Before mid-boot, a synchronous grace period is a no-op. Some time after mid-boot, workqueues are used.

Non-expedited non-SRCU synchronous grace periods must also operate normally during mid-boot. This is handled by causing non-expedited grace periods to take the expedited code path during mid-boot.

The current code assumes that there are no POSIX signals during the mid-boot dead zone. However, if an overwhelming need for POSIX signals somehow arises, appropriate adjustments can be made to the expedited stall-warning code. One such adjustment would reinstate the pre-workqueue stall-warning checks, but only during the mid-boot dead zone.

With this refinement, synchronous grace periods can now be used from task context pretty much any time during the life of the kernel. That is, aside from some points in the suspend, hibernate, or shutdown code path.

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

#### Summary

Expedited grace periods use a sequence-number approach to promote batching, so that a single grace-period operation can serve numerous requests. A funnel lock is used to efficiently identify the one task out of a concurrent group that will request the grace period. All members of the group will block on waitqueues provided in the `rcu_node` structure. The actual grace-period processing is carried out by a workqueue.

CPU-hotplug operations are noted lazily in order to prevent the need for tight synchronization between expedited grace periods and CPU-hotplug operations. The dyntick-idle counters are used to avoid sending IPIs to idle CPUs, at least in the common case. RCU-preempt and RCU-sched use different IPI handlers and different code to respond to the state changes carried out by those handlers, but otherwise use common code.

Quiescent states are tracked using the `rcu_node` tree, and once all necessary quiescent states have been reported, all tasks waiting on this expedited grace period are awakened. A pair of mutexes are used to allow one grace period's wakeups to proceed concurrently with the next grace period's processing.

This combination of mechanisms allows expedited grace periods to run reasonably efficiently. However, for non-time-critical tasks, normal grace periods should be used instead because their longer duration permits much higher degrees of batching, and thus much lower per-request overheads.

---

# A Tour Through TREE_RCU's Grace-Period Memory Ordering

_Peios Kernel / Internals / Read-copy-update (RCU) / Design / Memory-Ordering_

> August 8, 2017

<a id="rst-a-tour-through-tree-rcu-s-grace-period-memory-ordering"></a>

August 8, 2017

This article was contributed by Paul E. McKenney

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

## Introduction

This document gives a rough visual overview of how Tree RCU's grace-period memory ordering guarantee is provided.

<a id="rst-what-is-tree-rcu-s-grace-period-memory-ordering-guarantee"></a>

## What Is Tree RCU's Grace Period Memory Ordering Guarantee?

RCU grace periods provide extremely strong memory-ordering guarantees for non-idle non-offline code. Any code that happens after the end of a given RCU grace period is guaranteed to see the effects of all accesses prior to the beginning of that grace period that are within RCU read-side critical sections. Similarly, any code that happens before the beginning of a given RCU grace period is guaranteed to not see the effects of all accesses following the end of that grace period that are within RCU read-side critical sections.

Note well that RCU-sched read-side critical sections include any region of code for which preemption is disabled. Given that each individual machine instruction can be thought of as an extremely small region of preemption-disabled code, one can think of `synchronize_rcu()` as `smp_mb()` on steroids.

RCU updaters use this guarantee by splitting their updates into two phases, one of which is executed before the grace period and the other of which is executed after the grace period. In the most common use case, phase one removes an element from a linked RCU-protected data structure, and phase two frees that element. For this to work, any readers that have witnessed state prior to the phase-one update (in the common case, removal) must not witness state following the phase-two update (in the common case, freeing).

The RCU implementation provides this guarantee using a network of lock-based critical sections, memory barriers, and per-CPU processing, as is described in the following sections.

<a id="rst-tree-rcu-grace-period-memory-ordering-building-blocks"></a>

## Tree RCU Grace Period Memory Ordering Building Blocks

The workhorse for RCU's grace-period memory ordering is the critical section for the `rcu_node` structure's `->lock`. These critical sections use helper functions for lock acquisition, including `raw_spin_lock_rcu_node()`, `raw_spin_lock_irq_rcu_node()`, and `raw_spin_lock_irqsave_rcu_node()`. Their lock-release counterparts are `raw_spin_unlock_rcu_node()`, `raw_spin_unlock_irq_rcu_node()`, and `raw_spin_unlock_irqrestore_rcu_node()`, respectively. For completeness, a `raw_spin_trylock_rcu_node()` is also provided. The key point is that the lock-acquisition functions, including `raw_spin_trylock_rcu_node()`, all invoke `smp_mb__after_unlock_lock()` immediately after successful acquisition of the lock.

Therefore, for any given `rcu_node` structure, any access happening before one of the above lock-release functions will be seen by all CPUs as happening before any access happening after a later one of the above lock-acquisition functions. Furthermore, any access happening before one of the above lock-release function on any given CPU will be seen by all CPUs as happening before any access happening after a later one of the above lock-acquisition functions executing on that same CPU, even if the lock-release and lock-acquisition functions are operating on different `rcu_node` structures. Tree RCU uses these two ordering guarantees to form an ordering network among all CPUs that were in any way involved in the grace period, including any CPUs that came online or went offline during the grace period in question.

The following litmus test exhibits the ordering effects of these lock-acquisition and lock-release functions:



```text
 1 int x, y, z;
 2
 3 void task0(void)
 4 {
 5   raw_spin_lock_rcu_node(rnp);
 6   WRITE_ONCE(x, 1);
 7   r1 = READ_ONCE(y);
 8   raw_spin_unlock_rcu_node(rnp);
 9 }
10
11 void task1(void)
12 {
13   raw_spin_lock_rcu_node(rnp);
14   WRITE_ONCE(y, 1);
15   r2 = READ_ONCE(z);
16   raw_spin_unlock_rcu_node(rnp);
17 }
18
19 void task2(void)
20 {
21   WRITE_ONCE(z, 1);
22   smp_mb();
23   r3 = READ_ONCE(x);
24 }
25
26 WARN_ON(r1 == 0 && r2 == 0 && r3 == 0);
```

The `WARN_ON()` is evaluated at "the end of time", after all changes have propagated throughout the system. Without the `smp_mb__after_unlock_lock()` provided by the acquisition functions, this `WARN_ON()` could trigger, for example on PowerPC. The `smp_mb__after_unlock_lock()` invocations prevent this `WARN_ON()` from triggering.


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


**Quick Quiz**:

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


But the chain of rcu_node-structure lock acquisitions guarantees that new readers will see all of the updater's pre-grace-period accesses and also guarantees that the updater's post-grace-period accesses will see all of the old reader's accesses.  So why do we need all of those calls to smp_mb__after_unlock_lock()?

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


**Answer**:

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


Because we must provide ordering for RCU's polling grace-period primitives, for example, get_state_synchronize_rcu() and poll_state_synchronize_rcu().  Consider this code:



```text
CPU 0                                     CPU 1
----                                      ----
WRITE_ONCE(X, 1)                          WRITE_ONCE(Y, 1)
g = get_state_synchronize_rcu()           smp_mb()
while (!poll_state_synchronize_rcu(g))    r1 = READ_ONCE(X)
        continue;
r0 = READ_ONCE(Y)
```

RCU guarantees that the outcome r0 == 0 &amp;&amp; r1 == 0 will not happen, even if CPU 1 is in an RCU extended quiescent state (idle or offline) and thus won't interact directly with the RCU core processing at all.

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

This approach must be extended to include idle CPUs, which need RCU's grace-period memory ordering guarantee to extend to any RCU read-side critical sections preceding and following the current idle sojourn. This case is handled by calls to the strongly ordered `atomic_add_return()` read-modify-write atomic operation that is invoked within `ct_kernel_exit_state()` at idle-entry time and within `ct_kernel_enter_state()` at idle-exit time. The grace-period kthread invokes first `ct_rcu_watching_cpu_acquire()` (preceded by a full memory barrier) and `rcu_watching_snap_stopped_since()` (both of which rely on acquire semantics) to detect idle CPUs.


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


**Quick Quiz**:

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


But what about CPUs that remain offline for the entire grace period?

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


**Answer**:

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


Such CPUs will be offline at the beginning of the grace period, so the grace period won't expect quiescent states from them. Races between grace-period start and CPU-hotplug operations are mediated by the CPU's leaf `rcu_node` structure's `->lock` as described above.

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

The approach must be extended to handle one final case, that of waking a task blocked in `synchronize_rcu()`. This task might be affined to a CPU that is not yet aware that the grace period has ended, and thus might not yet be subject to the grace period's memory ordering. Therefore, there is an `smp_mb()` after the return from `wait_for_completion()` in the `synchronize_rcu()` code path.


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


**Quick Quiz**:

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


What? Where??? I don't see any `smp_mb()` after the return from `wait_for_completion()`\!\!\!

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


**Answer**:

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


That would be because I spotted the need for that `smp_mb()` during the creation of this documentation, and it is therefore unlikely to hit mainline before v4.14. Kudos to Lance Roy, Will Deacon, Peter Zijlstra, and Jonathan Cameron for asking questions that sensitized me to the rather elaborate sequence of events that demonstrate the need for this memory barrier.

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

Tree RCU's grace--period memory-ordering guarantees rely most heavily on the `rcu_node` structure's `->lock` field, so much so that it is necessary to abbreviate this pattern in the diagrams in the next section. For example, consider the `rcu_prepare_for_idle()` function shown below, which is one of several functions that enforce ordering of newly arrived RCU callbacks against future grace periods:



```text
 1 static void rcu_prepare_for_idle(void)
 2 {
 3   bool needwake;
 4   struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
 5   struct rcu_node *rnp;
 6   int tne;
 7
 8   lockdep_assert_irqs_disabled();
 9   if (rcu_rdp_is_offloaded(rdp))
10     return;
11
12   /* Handle nohz enablement switches conservatively. */
13   tne = READ_ONCE(tick_nohz_active);
14   if (tne != rdp->tick_nohz_enabled_snap) {
15     if (!rcu_segcblist_empty(&rdp->cblist))
16       invoke_rcu_core(); /* force nohz to see update. */
17     rdp->tick_nohz_enabled_snap = tne;
18     return;
19   }
20   if (!tne)
21     return;
22
23   /*
24    * If we have not yet accelerated this jiffy, accelerate all
25    * callbacks on this CPU.
26   */
27   if (rdp->last_accelerate == jiffies)
28     return;
29   rdp->last_accelerate = jiffies;
30   if (rcu_segcblist_pend_cbs(&rdp->cblist)) {
31     rnp = rdp->mynode;
32     raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
33     needwake = rcu_accelerate_cbs(rnp, rdp);
34     raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
35     if (needwake)
36       rcu_gp_kthread_wake();
37   }
38 }
```

But the only part of `rcu_prepare_for_idle()` that really matters for this discussion are lines 32–34. We will therefore abbreviate this function as follows:

![](/kernel/internals/rcu/design-memory-ordering/asset-b997d8059ba4-rcu-node-lock.svg)

The box represents the `rcu_node` structure's `->lock` critical section, with the double line on top representing the additional `smp_mb__after_unlock_lock()`.

<a id="rst-tree-rcu-grace-period-memory-ordering-components"></a>

### Tree RCU Grace Period Memory Ordering Components

Tree RCU's grace-period memory-ordering guarantee is provided by a number of RCU components:

1. [Callback Registry](<#rst-callback-registry>)

2. [Grace-Period Initialization](<#rst-grace-period-initialization>)

3. [Self-Reported Quiescent States](<#rst-self-reported-quiescent-states>)

4. [Dynamic Tick Interface](<#rst-dynamic-tick-interface>)

5. [CPU-Hotplug Interface](<#rst-cpu-hotplug-interface>)

6. [Forcing Quiescent States](<#rst-forcing-quiescent-states>)

7. [Grace-Period Cleanup](<#rst-grace-period-cleanup>)

8. [Callback Invocation](<#rst-callback-invocation>)

Each of the following section looks at the corresponding component in detail.

<a id="rst-callback-registry"></a>

#### Callback Registry

If RCU's grace-period guarantee is to mean anything at all, any access that happens before a given invocation of `call_rcu()` must also happen before the corresponding grace period. The implementation of this portion of RCU's grace period guarantee is shown in the following figure:

![](/kernel/internals/rcu/design-memory-ordering/asset-cf4489bffaee-treercu-callback-registry.svg)

Because `call_rcu()` normally acts only on CPU-local state, it provides no ordering guarantees, either for itself or for phase one of the update (which again will usually be removal of an element from an RCU-protected data structure). It simply enqueues the `rcu_head` structure on a per-CPU list, which cannot become associated with a grace period until a later call to `rcu_accelerate_cbs()`, as shown in the diagram above.

One set of code paths shown on the left invokes `rcu_accelerate_cbs()` via `note_gp_changes()`, either directly from `call_rcu()` (if the current CPU is inundated with queued `rcu_head` structures) or more likely from an `RCU_SOFTIRQ` handler. Another code path in the middle is taken only in kernels built with `CONFIG_RCU_FAST_NO_HZ=y`, which invokes `rcu_accelerate_cbs()` via `rcu_prepare_for_idle()`. The final code path on the right is taken only in kernels built with `CONFIG_HOTPLUG_CPU=y`, which invokes `rcu_accelerate_cbs()` via `rcu_advance_cbs()`, `rcu_migrate_callbacks`, `rcutree_migrate_callbacks()`, and `takedown_cpu()`, which in turn is invoked on a surviving CPU after the outgoing CPU has been completely offlined.

There are a few other code paths within grace-period processing that opportunistically invoke `rcu_accelerate_cbs()`. However, either way, all of the CPU's recently queued `rcu_head` structures are associated with a future grace-period number under the protection of the CPU's lead `rcu_node` structure's `->lock`. In all cases, there is full ordering against any prior critical section for that same `rcu_node` structure's `->lock`, and also full ordering against any of the current task's or CPU's prior critical sections for any `rcu_node` structure's `->lock`.

The next section will show how this ordering ensures that any accesses prior to the `call_rcu()` (particularly including phase one of the update) happen before the start of the corresponding grace period.


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


**Quick Quiz**:

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


But what about `synchronize_rcu()`?

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


**Answer**:

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


The `synchronize_rcu()` passes `call_rcu()` to `wait_rcu_gp()`, which invokes it. So either way, it eventually comes down to `call_rcu()`.

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

<a id="rst-grace-period-initialization"></a>

#### Grace-Period Initialization

Grace-period initialization is carried out by the grace-period kernel thread, which makes several passes over the `rcu_node` tree within the `rcu_gp_init()` function. This means that showing the full flow of ordering through the grace-period computation will require duplicating this tree. If you find this confusing, please note that the state of the `rcu_node` changes over time, just like Heraclitus's river. However, to keep the `rcu_node` river tractable, the grace-period kernel thread's traversals are presented in multiple parts, starting in this section with the various phases of grace-period initialization.

The first ordering-related grace-period initialization action is to advance the `rcu_state` structure's `->gp_seq` grace-period-number counter, as shown below:

![](/kernel/internals/rcu/design-memory-ordering/asset-63b7d02ababc-treercu-gp-init-1.svg)

The actual increment is carried out using `smp_store_release()`, which helps reject false-positive RCU CPU stall detection. Note that only the root `rcu_node` structure is touched.

The first pass through the `rcu_node` tree updates bitmasks based on CPUs having come online or gone offline since the start of the previous grace period. In the common case where the number of online CPUs for this `rcu_node` structure has not transitioned to or from zero, this pass will scan only the leaf `rcu_node` structures. However, if the number of online CPUs for a given leaf `rcu_node` structure has transitioned from zero, `rcu_init_new_rnp()` will be invoked for the first incoming CPU. Similarly, if the number of online CPUs for a given leaf `rcu_node` structure has transitioned to zero, `rcu_cleanup_dead_rnp()` will be invoked for the last outgoing CPU. The diagram below shows the path of ordering if the leftmost `rcu_node` structure onlines its first CPU and if the next `rcu_node` structure has no online CPUs (or, alternatively if the leftmost `rcu_node` structure offlines its last CPU and if the next `rcu_node` structure has no online CPUs).

![](/kernel/internals/rcu/design-memory-ordering/asset-c7de8919a7d4-treercu-gp-init-2.svg)

The final `rcu_gp_init()` pass through the `rcu_node` tree traverses breadth-first, setting each `rcu_node` structure's `->gp_seq` field to the newly advanced value from the `rcu_state` structure, as shown in the following diagram.

![](/kernel/internals/rcu/design-memory-ordering/asset-a5eba301f40a-treercu-gp-init-3.svg)

This change will also cause each CPU's next call to `__note_gp_changes()` to notice that a new grace period has started, as described in the next section. But because the grace-period kthread started the grace period at the root (with the advancing of the `rcu_state` structure's `->gp_seq` field) before setting each leaf `rcu_node` structure's `->gp_seq` field, each CPU's observation of the start of the grace period will happen after the actual start of the grace period.


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


**Quick Quiz**:

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


But what about the CPU that started the grace period? Why wouldn't it see the start of the grace period right when it started that grace period?

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


**Answer**:

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


In some deep philosophical and overly anthromorphized sense, yes, the CPU starting the grace period is immediately aware of having done so. However, if we instead assume that RCU is not self-aware, then even the CPU starting the grace period does not really become aware of the start of this grace period until its first call to `__note_gp_changes()`. On the other hand, this CPU potentially gets early notification because it invokes `__note_gp_changes()` during its last `rcu_gp_init()` pass through its leaf `rcu_node` structure.

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

<a id="rst-self-reported-quiescent-states"></a>

#### Self-Reported Quiescent States

When all entities that might block the grace period have reported quiescent states (or as described in a later section, had quiescent states reported on their behalf), the grace period can end. Online non-idle CPUs report their own quiescent states, as shown in the following diagram:

![](/kernel/internals/rcu/design-memory-ordering/asset-2e68671f56a7-treercu-qs.svg)

This is for the last CPU to report a quiescent state, which signals the end of the grace period. Earlier quiescent states would push up the `rcu_node` tree only until they encountered an `rcu_node` structure that is waiting for additional quiescent states. However, ordering is nevertheless preserved because some later quiescent state will acquire that `rcu_node` structure's `->lock`.

Any number of events can lead up to a CPU invoking `note_gp_changes` (or alternatively, directly invoking `__note_gp_changes()`), at which point that CPU will notice the start of a new grace period while holding its leaf `rcu_node` lock. Therefore, all execution shown in this diagram happens after the start of the grace period. In addition, this CPU will consider any RCU read-side critical section that started before the invocation of `__note_gp_changes()` to have started before the grace period, and thus a critical section that the grace period must wait on.


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


**Quick Quiz**:

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


But a RCU read-side critical section might have started after the beginning of the grace period (the advancing of `->gp_seq` from earlier), so why should the grace period wait on such a critical section?

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


**Answer**:

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


It is indeed not necessary for the grace period to wait on such a critical section. However, it is permissible to wait on it. And it is furthermore important to wait on it, as this lazy approach is far more scalable than a “big bang” all-at-once grace-period start could possibly be.

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

If the CPU does a context switch, a quiescent state will be noted by `rcu_note_context_switch()` on the left. On the other hand, if the CPU takes a scheduler-clock interrupt while executing in usermode, a quiescent state will be noted by `rcu_sched_clock_irq()` on the right. Either way, the passage through a quiescent state will be noted in a per-CPU variable.

The next time an `RCU_SOFTIRQ` handler executes on this CPU (for example, after the next scheduler-clock interrupt), `rcu_core()` will invoke `rcu_check_quiescent_state()`, which will notice the recorded quiescent state, and invoke `rcu_report_qs_rdp()`. If `rcu_report_qs_rdp()` verifies that the quiescent state really does apply to the current grace period, it invokes `rcu_report_rnp()` which traverses up the `rcu_node` tree as shown at the bottom of the diagram, clearing bits from each `rcu_node` structure's `->qsmask` field, and propagating up the tree when the result is zero.

Note that traversal passes upwards out of a given `rcu_node` structure only if the current CPU is reporting the last quiescent state for the subtree headed by that `rcu_node` structure. A key point is that if a CPU's traversal stops at a given `rcu_node` structure, then there will be a later traversal by another CPU (or perhaps the same one) that proceeds upwards from that point, and the `rcu_node` `->lock` guarantees that the first CPU's quiescent state happens before the remainder of the second CPU's traversal. Applying this line of thought repeatedly shows that all CPUs' quiescent states happen before the last CPU traverses through the root `rcu_node` structure, the “last CPU” being the one that clears the last bit in the root `rcu_node` structure's `->qsmask` field.

<a id="rst-dynamic-tick-interface"></a>

#### Dynamic Tick Interface

Due to energy-efficiency considerations, RCU is forbidden from disturbing idle CPUs. CPUs are therefore required to notify RCU when entering or leaving idle state, which they do via fully ordered value-returning atomic operations on a per-CPU variable. The ordering effects are as shown below:

![](/kernel/internals/rcu/design-memory-ordering/asset-9de1f221af9d-treercu-dyntick.svg)

The RCU grace-period kernel thread samples the per-CPU idleness variable while holding the corresponding CPU's leaf `rcu_node` structure's `->lock`. This means that any RCU read-side critical sections that precede the idle period (the oval near the top of the diagram above) will happen before the end of the current grace period. Similarly, the beginning of the current grace period will happen before any RCU read-side critical sections that follow the idle period (the oval near the bottom of the diagram above).

Plumbing this into the full grace-period execution is described [below](<#rst-forcing-quiescent-states>).

<a id="rst-cpu-hotplug-interface"></a>

#### CPU-Hotplug Interface

RCU is also forbidden from disturbing offline CPUs, which might well be powered off and removed from the system completely. CPUs are therefore required to notify RCU of their comings and goings as part of the corresponding CPU hotplug operations. The ordering effects are shown below:

![](/kernel/internals/rcu/design-memory-ordering/asset-9dbefee32f96-treercu-hotplug.svg)

Because CPU hotplug operations are much less frequent than idle transitions, they are heavier weight, and thus acquire the CPU's leaf `rcu_node` structure's `->lock` and update this structure's `->qsmaskinitnext`. The RCU grace-period kernel thread samples this mask to detect CPUs having gone offline since the beginning of this grace period.

Plumbing this into the full grace-period execution is described [below](<#rst-forcing-quiescent-states>).

<a id="rst-forcing-quiescent-states"></a>

#### Forcing Quiescent States

As noted above, idle and offline CPUs cannot report their own quiescent states, and therefore the grace-period kernel thread must do the reporting on their behalf. This process is called “forcing quiescent states”, it is repeated every few jiffies, and its ordering effects are shown below:

![](/kernel/internals/rcu/design-memory-ordering/asset-6f3097c790a9-treercu-gp-fqs.svg)

Each pass of quiescent state forcing is guaranteed to traverse the leaf `rcu_node` structures, and if there are no new quiescent states due to recently idled and/or offlined CPUs, then only the leaves are traversed. However, if there is a newly offlined CPU as illustrated on the left or a newly idled CPU as illustrated on the right, the corresponding quiescent state will be driven up towards the root. As with self-reported quiescent states, the upwards driving stops once it reaches an `rcu_node` structure that has quiescent states outstanding from other CPUs.


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


**Quick Quiz**:

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


The leftmost drive to root stopped before it reached the root `rcu_node` structure, which means that there are still CPUs subordinate to that structure on which the current grace period is waiting. Given that, how is it possible that the rightmost drive to root ended the grace period?

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


**Answer**:

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


Good analysis\! It is in fact impossible in the absence of bugs in RCU. But this diagram is complex enough as it is, so simplicity overrode accuracy. You can think of it as poetic license, or you can think of it as misdirection that is resolved in the [stitched-together diagram](<#rst-putting-it-all-together>).

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

<a id="rst-grace-period-cleanup"></a>

#### Grace-Period Cleanup

Grace-period cleanup first scans the `rcu_node` tree breadth-first advancing all the `->gp_seq` fields, then it advances the `rcu_state` structure's `->gp_seq` field. The ordering effects are shown below:

![](/kernel/internals/rcu/design-memory-ordering/asset-eabce48a80be-treercu-gp-cleanup.svg)

As indicated by the oval at the bottom of the diagram, once grace-period cleanup is complete, the next grace period can begin.


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


**Quick Quiz**:

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


But when precisely does the grace period end?

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


**Answer**:

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


There is no useful single point at which the grace period can be said to end. The earliest reasonable candidate is as soon as the last CPU has reported its quiescent state, but it may be some milliseconds before RCU becomes aware of this. The latest reasonable candidate is once the `rcu_state` structure's `->gp_seq` field has been updated, but it is quite possible that some CPUs have already completed phase two of their updates by that time. In short, if you are going to work with RCU, you need to learn to embrace uncertainty.

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

<a id="rst-callback-invocation"></a>

#### Callback Invocation

Once a given CPU's leaf `rcu_node` structure's `->gp_seq` field has been updated, that CPU can begin invoking its RCU callbacks that were waiting for this grace period to end. These callbacks are identified by `rcu_advance_cbs()`, which is usually invoked by `__note_gp_changes()`. As shown in the diagram below, this invocation can be triggered by the scheduling-clock interrupt (`rcu_sched_clock_irq()` on the left) or by idle entry (`rcu_cleanup_after_idle()` on the right, but only for kernels build with `CONFIG_RCU_FAST_NO_HZ=y`). Either way, `RCU_SOFTIRQ` is raised, which results in `rcu_do_batch()` invoking the callbacks, which in turn allows those callbacks to carry out (either directly or indirectly via wakeup) the needed phase-two processing for each update.

![](/kernel/internals/rcu/design-memory-ordering/asset-90f27ace54ae-treercu-callback-invocation.svg)

Please note that callback invocation can also be prompted by any number of corner-case code paths, for example, when a CPU notes that it has excessive numbers of callbacks queued. In all cases, the CPU acquires its leaf `rcu_node` structure's `->lock` before invoking callbacks, which preserves the required ordering against the newly completed grace period.

However, if the callback function communicates to other CPUs, for example, doing a wakeup, then it is that function's responsibility to maintain ordering. For example, if the callback function wakes up a task that runs on some other CPU, proper ordering must in place in both the callback function and the task being awakened. To see why this is important, consider the top half of the [grace-period cleanup](<#rst-grace-period-cleanup>) diagram. The callback might be running on a CPU corresponding to the leftmost leaf `rcu_node` structure, and awaken a task that is to run on a CPU corresponding to the rightmost leaf `rcu_node` structure, and the grace-period kernel thread might not yet have reached the rightmost leaf. In this case, the grace period's memory ordering might not yet have reached that CPU, so again the callback function and the awakened task must supply proper ordering.

<a id="rst-putting-it-all-together"></a>

### Putting It All Together

A stitched-together diagram is here:

![](/kernel/internals/rcu/design-memory-ordering/asset-6bae209a0ed7-treercu-gp.svg)

<a id="rst-legal-statement"></a>

### Legal Statement

This work represents the view of the author and does not necessarily represent the view of IBM.

Linux is a registered trademark of Linus Torvalds.

Other company, product, and service names may be trademarks or service marks of others.

---

# A Tour Through RCU's Requirements

_Peios Kernel / Internals / Read-copy-update (RCU) / Design / Requirements_

> Copyright IBM Corporation, 2015

<a id="rst-a-tour-through-rcu-s-requirements"></a>

Copyright IBM Corporation, 2015

Author: Paul E. McKenney

The initial version of this document appeared in the [LWN](<https://lwn.net/>)<a id="rst-lwn"></a> on those articles: [part 1](<https://lwn.net/Articles/652156/>)<a id="rst-part-1"></a>, [part 2](<https://lwn.net/Articles/652677/>)<a id="rst-part-2"></a>, and [part 3](<https://lwn.net/Articles/653326/>)<a id="rst-part-3"></a>.

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

## Introduction

Read-copy update (RCU) is a synchronization mechanism that is often used as a replacement for reader-writer locking. RCU is unusual in that updaters do not block readers, which means that RCU's read-side primitives can be exceedingly fast and scalable. In addition, updaters can make useful forward progress concurrently with readers. However, all this concurrency between RCU readers and updaters does raise the question of exactly what RCU readers are doing, which in turn raises the question of exactly what RCU's requirements are.

This document therefore summarizes RCU's requirements, and can be thought of as an informal, high-level specification for RCU. It is important to understand that RCU's specification is primarily empirical in nature; in fact, I learned about many of these requirements the hard way. This situation might cause some consternation, however, not only has this learning process been a lot of fun, but it has also been a great privilege to work with so many people willing to apply technologies in interesting new ways.

All that aside, here are the categories of currently known RCU requirements:

1. [Fundamental Requirements](<#rst-fundamental-requirements>)

2. [Fundamental Non-Requirements](<#rst-fundamental-non-requirements>)

3. [Parallelism Facts of Life](<#rst-parallelism-facts-of-life>)

4. [Quality-of-Implementation Requirements](<#rst-quality-of-implementation-requirements>)

5. [Linux Kernel Complications](<#rst-linux-kernel-complications>)

6. [Software-Engineering Requirements](<#rst-software-engineering-requirements>)

7. [Other RCU Flavors](<#rst-other-rcu-flavors>)

8. [Possible Future Changes](<#rst-possible-future-changes>)

This is followed by a [summary](<#rst-summary>), however, the answers to each quick quiz immediately follows the quiz. Select the big white space with your mouse to see the answer.

<a id="rst-fundamental-requirements"></a>

## Fundamental Requirements

RCU's fundamental requirements are the closest thing RCU has to hard mathematical requirements. These are:

1. [Grace-Period Guarantee](<#rst-grace-period-guarantee>)

2. [Publish/Subscribe Guarantee](<#rst-publish-subscribe-guarantee>)

3. [Memory-Barrier Guarantees](<#rst-memory-barrier-guarantees>)

4. [RCU Primitives Guaranteed to Execute Unconditionally](<#rst-rcu-primitives-guaranteed-to-execute-unconditionally>)

5. [Guaranteed Read-to-Write Upgrade](<#rst-guaranteed-read-to-write-upgrade>)

<a id="rst-grace-period-guarantee"></a>

### Grace-Period Guarantee

RCU's grace-period guarantee is unusual in being premeditated: Jack Slingwine and I had this guarantee firmly in mind when we started work on RCU (then called “rclock”) in the early 1990s. That said, the past two decades of experience with RCU have produced a much more detailed understanding of this guarantee.

RCU's grace-period guarantee allows updaters to wait for the completion of all pre-existing RCU read-side critical sections. An RCU read-side critical section begins with the marker rcu_read_lock() and ends with the marker rcu_read_unlock(). These markers may be nested, and RCU treats a nested set as one big RCU read-side critical section. Production-quality implementations of rcu_read_lock() and rcu_read_unlock() are extremely lightweight, and in fact have exactly zero overhead in Linux kernels built for production use with `CONFIG_PREEMPTION=n`.

This guarantee allows ordering to be enforced with extremely low overhead to readers, for example:

>
>
> ```text
>  1 int x, y;
>  2
>  3 void thread0(void)
>  4 {
>  5   rcu_read_lock();
>  6   r1 = READ_ONCE(x);
>  7   r2 = READ_ONCE(y);
>  8   rcu_read_unlock();
>  9 }
> 10
> 11 void thread1(void)
> 12 {
> 13   WRITE_ONCE(x, 1);
> 14   synchronize_rcu();
> 15   WRITE_ONCE(y, 1);
> 16 }
> ```

Because the synchronize_rcu() on line 14 waits for all pre-existing readers, any instance of thread0() that loads a value of zero from `x` must complete before thread1() stores to `y`, so that instance must also load a value of zero from `y`. Similarly, any instance of thread0() that loads a value of one from `y` must have started after the synchronize_rcu() started, and must therefore also load a value of one from `x`. Therefore, the outcome:

>
>
> ```text
> (r1 == 0 && r2 == 1)
> ```

cannot happen.


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


**Quick Quiz**:

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


Wait a minute\! You said that updaters can make useful forward progress concurrently with readers, but pre-existing readers will block synchronize_rcu()\!\!\! Just who are you trying to fool???

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


**Answer**:

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


First, if updaters do not wish to be blocked by readers, they can use call_rcu() or kfree_rcu(), which will be discussed later. Second, even when using synchronize_rcu(), the other update-side code does run concurrently with readers, whether pre-existing or not.

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

This scenario resembles one of the first uses of RCU in [DYNIX/ptx](<https://en.wikipedia.org/wiki/DYNIX>), which managed a distributed lock manager's transition into a state suitable for handling recovery from node failure, more or less as follows:

>
>
> ```text
>  1 #define STATE_NORMAL        0
>  2 #define STATE_WANT_RECOVERY 1
>  3 #define STATE_RECOVERING    2
>  4 #define STATE_WANT_NORMAL   3
>  5
>  6 int state = STATE_NORMAL;
>  7
>  8 void do_something_dlm(void)
>  9 {
> 10   int state_snap;
> 11
> 12   rcu_read_lock();
> 13   state_snap = READ_ONCE(state);
> 14   if (state_snap == STATE_NORMAL)
> 15     do_something();
> 16   else
> 17     do_something_carefully();
> 18   rcu_read_unlock();
> 19 }
> 20
> 21 void start_recovery(void)
> 22 {
> 23   WRITE_ONCE(state, STATE_WANT_RECOVERY);
> 24   synchronize_rcu();
> 25   WRITE_ONCE(state, STATE_RECOVERING);
> 26   recovery();
> 27   WRITE_ONCE(state, STATE_WANT_NORMAL);
> 28   synchronize_rcu();
> 29   WRITE_ONCE(state, STATE_NORMAL);
> 30 }
> ```

The RCU read-side critical section in do_something_dlm() works with the synchronize_rcu() in start_recovery() to guarantee that do_something() never runs concurrently with recovery(), but with little or no synchronization overhead in do_something_dlm().


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


**Quick Quiz**:

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


Why is the synchronize_rcu() on line 28 needed?

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


**Answer**:

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


Without that extra grace period, memory reordering could result in do_something_dlm() executing do_something() concurrently with the last bits of recovery().

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

In order to avoid fatal problems such as deadlocks, an RCU read-side critical section must not contain calls to synchronize_rcu(). Similarly, an RCU read-side critical section must not contain anything that waits, directly or indirectly, on completion of an invocation of synchronize_rcu().

Although RCU's grace-period guarantee is useful in and of itself, with [quite a few use cases](<https://lwn.net/Articles/573497/>), it would be good to be able to use RCU to coordinate read-side access to linked data structures. For this, the grace-period guarantee is not sufficient, as can be seen in function add_gp_buggy() below. We will look at the reader's code later, but in the meantime, just think of the reader as locklessly picking up the `gp` pointer, and, if the value loaded is non-`NULL`, locklessly accessing the `->a` and `->b` fields.

>
>
> ```text
>  1 bool add_gp_buggy(int a, int b)
>  2 {
>  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
>  4   if (!p)
>  5     return -ENOMEM;
>  6   spin_lock(&gp_lock);
>  7   if (rcu_access_pointer(gp)) {
>  8     spin_unlock(&gp_lock);
>  9     return false;
> 10   }
> 11   p->a = a;
> 12   p->b = a;
> 13   gp = p; /* ORDERING BUG */
> 14   spin_unlock(&gp_lock);
> 15   return true;
> 16 }
> ```

The problem is that both the compiler and weakly ordered CPUs are within their rights to reorder this code as follows:

>
>
> ```text
>  1 bool add_gp_buggy_optimized(int a, int b)
>  2 {
>  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
>  4   if (!p)
>  5     return -ENOMEM;
>  6   spin_lock(&gp_lock);
>  7   if (rcu_access_pointer(gp)) {
>  8     spin_unlock(&gp_lock);
>  9     return false;
> 10   }
> 11   gp = p; /* ORDERING BUG */
> 12   p->a = a;
> 13   p->b = a;
> 14   spin_unlock(&gp_lock);
> 15   return true;
> 16 }
> ```

If an RCU reader fetches `gp` just after `add_gp_buggy_optimized` executes line 11, it will see garbage in the `->a` and `->b` fields. And this is but one of many ways in which compiler and hardware optimizations could cause trouble. Therefore, we clearly need some way to prevent the compiler and the CPU from reordering in this manner, which brings us to the publish-subscribe guarantee discussed in the next section.

<a id="rst-publish-subscribe-guarantee"></a>

### Publish/Subscribe Guarantee

RCU's publish-subscribe guarantee allows data to be inserted into a linked data structure without disrupting RCU readers. The updater uses rcu_assign_pointer() to insert the new data, and readers use rcu_dereference() to access data, whether new or old. The following shows an example of insertion:

>
>
> ```text
>  1 bool add_gp(int a, int b)
>  2 {
>  3   p = kmalloc(sizeof(*p), GFP_KERNEL);
>  4   if (!p)
>  5     return -ENOMEM;
>  6   spin_lock(&gp_lock);
>  7   if (rcu_access_pointer(gp)) {
>  8     spin_unlock(&gp_lock);
>  9     return false;
> 10   }
> 11   p->a = a;
> 12   p->b = a;
> 13   rcu_assign_pointer(gp, p);
> 14   spin_unlock(&gp_lock);
> 15   return true;
> 16 }
> ```

The rcu_assign_pointer() on line 13 is conceptually equivalent to a simple assignment statement, but also guarantees that its assignment will happen after the two assignments in lines 11 and 12, similar to the C11 `memory_order_release` store operation. It also prevents any number of “interesting” compiler optimizations, for example, the use of `gp` as a scratch location immediately preceding the assignment.


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


**Quick Quiz**:

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


But rcu_assign_pointer() does nothing to prevent the two assignments to `p->a` and `p->b` from being reordered. Can't that also cause problems?

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


**Answer**:

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


No, it cannot. The readers cannot see either of these two fields until the assignment to `gp`, by which time both fields are fully initialized. So reordering the assignments to `p->a` and `p->b` cannot possibly cause any problems.

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

It is tempting to assume that the reader need not do anything special to control its accesses to the RCU-protected data, as shown in do_something_gp_buggy() below:

>
>
> ```text
>  1 bool do_something_gp_buggy(void)
>  2 {
>  3   rcu_read_lock();
>  4   p = gp;  /* OPTIMIZATIONS GALORE!!! */
>  5   if (p) {
>  6     do_something(p->a, p->b);
>  7     rcu_read_unlock();
>  8     return true;
>  9   }
> 10   rcu_read_unlock();
> 11   return false;
> 12 }
> ```

However, this temptation must be resisted because there are a surprisingly large number of ways that the compiler (or weak ordering CPUs like the DEC Alpha) can trip this code up. For but one example, if the compiler were short of registers, it might choose to refetch from `gp` rather than keeping a separate copy in `p` as follows:

>
>
> ```text
>  1 bool do_something_gp_buggy_optimized(void)
>  2 {
>  3   rcu_read_lock();
>  4   if (gp) { /* OPTIMIZATIONS GALORE!!! */
>  5     do_something(gp->a, gp->b);
>  6     rcu_read_unlock();
>  7     return true;
>  8   }
>  9   rcu_read_unlock();
> 10   return false;
> 11 }
> ```

If this function ran concurrently with a series of updates that replaced the current structure with a new one, the fetches of `gp->a` and `gp->b` might well come from two different structures, which could cause serious confusion. To prevent this (and much else besides), do_something_gp() uses rcu_dereference() to fetch from `gp`:

>
>
> ```text
>  1 bool do_something_gp(void)
>  2 {
>  3   rcu_read_lock();
>  4   p = rcu_dereference(gp);
>  5   if (p) {
>  6     do_something(p->a, p->b);
>  7     rcu_read_unlock();
>  8     return true;
>  9   }
> 10   rcu_read_unlock();
> 11   return false;
> 12 }
> ```

The rcu_dereference() uses volatile casts and (for DEC Alpha) memory barriers in the Linux kernel. Should a [high-quality implementation of C11 `memory_order_consume` \[PDF\]](<http://www.rdrop.com/users/paulmck/RCU/consume.2015.07.13a.pdf>) ever appear, then rcu_dereference() could be implemented as a `memory_order_consume` load. Regardless of the exact implementation, a pointer fetched by rcu_dereference() may not be used outside of the outermost RCU read-side critical section containing that rcu_dereference(), unless protection of the corresponding data element has been passed from RCU to some other synchronization mechanism, most commonly locking or reference counting (see ../../rcuref.rst).

<a id="rst-high-quality-implementation-of-c11-memory-order-consume-pdf"></a>



In short, updaters use rcu_assign_pointer() and readers use rcu_dereference(), and these two RCU API elements work together to ensure that readers have a consistent view of newly added data elements.

Of course, it is also necessary to remove elements from RCU-protected data structures, for example, using the following process:

1. Remove the data element from the enclosing structure.

2. Wait for all pre-existing RCU read-side critical sections to complete (because only pre-existing readers can possibly have a reference to the newly removed data element).

3. At this point, only the updater has a reference to the newly removed data element, so it can safely reclaim the data element, for example, by passing it to kfree().

This process is implemented by remove_gp_synchronous():

>
>
> ```text
>  1 bool remove_gp_synchronous(void)
>  2 {
>  3   struct foo *p;
>  4
>  5   spin_lock(&gp_lock);
>  6   p = rcu_access_pointer(gp);
>  7   if (!p) {
>  8     spin_unlock(&gp_lock);
>  9     return false;
> 10   }
> 11   rcu_assign_pointer(gp, NULL);
> 12   spin_unlock(&gp_lock);
> 13   synchronize_rcu();
> 14   kfree(p);
> 15   return true;
> 16 }
> ```

This function is straightforward, with line 13 waiting for a grace period before line 14 frees the old data element. This waiting ensures that readers will reach line 7 of do_something_gp() before the data element referenced by `p` is freed. The rcu_access_pointer() on line 6 is similar to rcu_dereference(), except that:

1. The value returned by rcu_access_pointer() cannot be dereferenced. If you want to access the value pointed to as well as the pointer itself, use rcu_dereference() instead of rcu_access_pointer().

2. The call to rcu_access_pointer() need not be protected. In contrast, rcu_dereference() must either be within an RCU read-side critical section or in a code segment where the pointer cannot change, for example, in code protected by the corresponding update-side lock.


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


**Quick Quiz**:

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


Without the rcu_dereference() or the rcu_access_pointer(), what destructive optimizations might the compiler make use of?

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


**Answer**:

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


Let's start with what happens to do_something_gp() if it fails to use rcu_dereference(). It could reuse a value formerly fetched from this same pointer. It could also fetch the pointer from `gp` in a byte-at-a-time manner, resulting in *load tearing*, in turn resulting a bytewise mash-up of two distinct pointer values. It might even use value-speculation optimizations, where it makes a wrong guess, but by the time it gets around to checking the value, an update has changed the pointer to match the wrong guess. Too bad about any dereferences that returned pre-initialization garbage in the meantime\! For remove_gp_synchronous(), as long as all modifications to `gp` are carried out while holding `gp_lock`, the above optimizations are harmless. However, `sparse` will complain if you define `gp` with `__rcu` and then access it without using either rcu_access_pointer() or rcu_dereference().

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

In short, RCU's publish-subscribe guarantee is provided by the combination of rcu_assign_pointer() and rcu_dereference(). This guarantee allows data elements to be safely added to RCU-protected linked data structures without disrupting RCU readers. This guarantee can be used in combination with the grace-period guarantee to also allow data elements to be removed from RCU-protected linked data structures, again without disrupting RCU readers.

This guarantee was only partially premeditated. DYNIX/ptx used an explicit memory barrier for publication, but had nothing resembling rcu_dereference() for subscription, nor did it have anything resembling the dependency-ordering barrier that was later subsumed into rcu_dereference() and later still into READ_ONCE(). The need for these operations made itself known quite suddenly at a late-1990s meeting with the DEC Alpha architects, back in the days when DEC was still a free-standing company. It took the Alpha architects a good hour to convince me that any sort of barrier would ever be needed, and it then took me a good *two* hours to convince them that their documentation did not make this point clear. More recent work with the C and C++ standards committees have provided much education on tricks and traps from the compiler. In short, compilers were much less tricky in the early 1990s, but in 2015, don't even think about omitting rcu_dereference()\!

<a id="rst-memory-barrier-guarantees"></a>

### Memory-Barrier Guarantees

The previous section's simple linked-data-structure scenario clearly demonstrates the need for RCU's stringent memory-ordering guarantees on systems with more than one CPU:

1. Each CPU that has an RCU read-side critical section that begins before synchronize_rcu() starts is guaranteed to execute a full memory barrier between the time that the RCU read-side critical section ends and the time that synchronize_rcu() returns. Without this guarantee, a pre-existing RCU read-side critical section might hold a reference to the newly removed `struct foo` after the kfree() on line 14 of remove_gp_synchronous().

2. Each CPU that has an RCU read-side critical section that ends after synchronize_rcu() returns is guaranteed to execute a full memory barrier between the time that synchronize_rcu() begins and the time that the RCU read-side critical section begins. Without this guarantee, a later RCU read-side critical section running after the kfree() on line 14 of remove_gp_synchronous() might later run do_something_gp() and find the newly deleted `struct foo`.

3. If the task invoking synchronize_rcu() remains on a given CPU, then that CPU is guaranteed to execute a full memory barrier sometime during the execution of synchronize_rcu(). This guarantee ensures that the kfree() on line 14 of remove_gp_synchronous() really does execute after the removal on line 11.

4. If the task invoking synchronize_rcu() migrates among a group of CPUs during that invocation, then each of the CPUs in that group is guaranteed to execute a full memory barrier sometime during the execution of synchronize_rcu(). This guarantee also ensures that the kfree() on line 14 of remove_gp_synchronous() really does execute after the removal on line 11, but also in the case where the thread executing the synchronize_rcu() migrates in the meantime.


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


**Quick Quiz**:

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


Given that multiple CPUs can start RCU read-side critical sections at any time without any ordering whatsoever, how can RCU possibly tell whether or not a given RCU read-side critical section starts before a given instance of synchronize_rcu()?

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


**Answer**:

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


If RCU cannot tell whether or not a given RCU read-side critical section starts before a given instance of synchronize_rcu(), then it must assume that the RCU read-side critical section started first. In other words, a given instance of synchronize_rcu() can avoid waiting on a given RCU read-side critical section only if it can prove that synchronize_rcu() started first. A related question is “When rcu_read_lock() doesn't generate any code, why does it matter how it relates to a grace period?” The answer is that it is not the relationship of rcu_read_lock() itself that is important, but rather the relationship of the code within the enclosed RCU read-side critical section to the code preceding and following the grace period. If we take this viewpoint, then a given RCU read-side critical section begins before a given grace period when some access preceding the grace period observes the effect of some access within the critical section, in which case none of the accesses within the critical section may observe the effects of any access following the grace period.

As of late 2016, mathematical models of RCU take this viewpoint, for example, see slides 62 and 63 of the [2016 LinuxCon EU](<http://www2.rdrop.com/users/paulmck/scalability/paper/LinuxMM.2016.10.04c.LCE.pdf>) presentation.

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


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


**Quick Quiz**:

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


The first and second guarantees require unbelievably strict ordering\! Are all these memory barriers *really* required?

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


**Answer**:

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


Yes, they really are required. To see why the first guarantee is required, consider the following sequence of events:

1. CPU 1: rcu_read_lock()

2. CPU 1: `q = rcu_dereference(gp); /* Very likely to return p. */`

3. CPU 0: `list_del_rcu(p);`

4. CPU 0: synchronize_rcu() starts.

5. CPU 1: `do_something_with(q->a);` `/* No smp_mb(), so might happen after kfree(). */`

6. CPU 1: rcu_read_unlock()

7. CPU 0: synchronize_rcu() returns.

8. CPU 0: `kfree(p);`

Therefore, there absolutely must be a full memory barrier between the end of the RCU read-side critical section and the end of the grace period.

The sequence of events demonstrating the necessity of the second rule is roughly similar:

1. CPU 0: `list_del_rcu(p);`

2. CPU 0: synchronize_rcu() starts.

3. CPU 1: rcu_read_lock()

4. CPU 1: `q = rcu_dereference(gp);` `/* Might return p if no memory barrier. */`

5. CPU 0: synchronize_rcu() returns.

6. CPU 0: `kfree(p);`

7. CPU 1: `do_something_with(q->a); /* Boom!!! */`

8. CPU 1: rcu_read_unlock()

And similarly, without a memory barrier between the beginning of the grace period and the beginning of the RCU read-side critical section, CPU 1 might end up accessing the freelist.

The “as if” rule of course applies, so that any implementation that acts as if the appropriate memory barriers were in place is a correct implementation. That said, it is much easier to fool yourself into believing that you have adhered to the as-if rule than it is to actually adhere to it\!

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


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


**Quick Quiz**:

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


You claim that rcu_read_lock() and rcu_read_unlock() generate absolutely no code in some kernel builds. This means that the compiler might arbitrarily rearrange consecutive RCU read-side critical sections. Given such rearrangement, if a given RCU read-side critical section is done, how can you be sure that all prior RCU read-side critical sections are done? Won't the compiler rearrangements make that impossible to determine?

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


**Answer**:

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


In cases where rcu_read_lock() and rcu_read_unlock() generate absolutely no code, RCU infers quiescent states only at special locations, for example, within the scheduler. Because calls to schedule() had better prevent calling-code accesses to shared variables from being rearranged across the call to schedule(), if RCU detects the end of a given RCU read-side critical section, it will necessarily detect the end of all prior RCU read-side critical sections, no matter how aggressively the compiler scrambles the code. Again, this all assumes that the compiler cannot scramble code across calls to the scheduler, out of interrupt handlers, into the idle loop, into user-mode code, and so on. But if your kernel build allows that sort of scrambling, you have broken far more than just RCU\!

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

Note that these memory-barrier requirements do not replace the fundamental RCU requirement that a grace period wait for all pre-existing readers. On the contrary, the memory barriers called out in this section must operate in such a way as to *enforce* this fundamental requirement. Of course, different implementations enforce this requirement in different ways, but enforce it they must.

<a id="rst-rcu-primitives-guaranteed-to-execute-unconditionally"></a>

### RCU Primitives Guaranteed to Execute Unconditionally

The common-case RCU primitives are unconditional. They are invoked, they do their job, and they return, with no possibility of error, and no need to retry. This is a key RCU design philosophy.

However, this philosophy is pragmatic rather than pigheaded. If someone comes up with a good justification for a particular conditional RCU primitive, it might well be implemented and added. After all, this guarantee was reverse-engineered, not premeditated. The unconditional nature of the RCU primitives was initially an accident of implementation, and later experience with synchronization primitives with conditional primitives caused me to elevate this accident to a guarantee. Therefore, the justification for adding a conditional primitive to RCU would need to be based on detailed and compelling use cases.

<a id="rst-guaranteed-read-to-write-upgrade"></a>

### Guaranteed Read-to-Write Upgrade

As far as RCU is concerned, it is always possible to carry out an update within an RCU read-side critical section. For example, that RCU read-side critical section might search for a given data element, and then might acquire the update-side spinlock in order to update that element, all while remaining in that RCU read-side critical section. Of course, it is necessary to exit the RCU read-side critical section before invoking synchronize_rcu(), however, this inconvenience can be avoided through use of the call_rcu() and kfree_rcu() API members described later in this document.


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


**Quick Quiz**:

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


But how does the upgrade-to-write operation exclude other readers?

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


**Answer**:

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


It doesn't, just like normal RCU updates, which also do not exclude RCU readers.

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

This guarantee allows lookup code to be shared between read-side and update-side code, and was premeditated, appearing in the earliest DYNIX/ptx RCU documentation.

<a id="rst-fundamental-non-requirements"></a>

## Fundamental Non-Requirements

RCU provides extremely lightweight readers, and its read-side guarantees, though quite useful, are correspondingly lightweight. It is therefore all too easy to assume that RCU is guaranteeing more than it really is. Of course, the list of things that RCU does not guarantee is infinitely long, however, the following sections list a few non-guarantees that have caused confusion. Except where otherwise noted, these non-guarantees were premeditated.

1. [Readers Impose Minimal Ordering](<#rst-readers-impose-minimal-ordering>)

2. [Readers Do Not Exclude Updaters](<#rst-readers-do-not-exclude-updaters>)

3. [Updaters Only Wait For Old Readers](<#rst-updaters-only-wait-for-old-readers>)

4. [Grace Periods Don't Partition Read-Side Critical Sections](<#rst-grace-periods-don-t-partition-read-side-critical-sections>)

5. [Read-Side Critical Sections Don't Partition Grace Periods](<#rst-read-side-critical-sections-don-t-partition-grace-periods>)

<a id="rst-readers-impose-minimal-ordering"></a>

### Readers Impose Minimal Ordering

Reader-side markers such as rcu_read_lock() and rcu_read_unlock() provide absolutely no ordering guarantees except through their interaction with the grace-period APIs such as synchronize_rcu(). To see this, consider the following pair of threads:

>
>
> ```text
>  1 void thread0(void)
>  2 {
>  3   rcu_read_lock();
>  4   WRITE_ONCE(x, 1);
>  5   rcu_read_unlock();
>  6   rcu_read_lock();
>  7   WRITE_ONCE(y, 1);
>  8   rcu_read_unlock();
>  9 }
> 10
> 11 void thread1(void)
> 12 {
> 13   rcu_read_lock();
> 14   r1 = READ_ONCE(y);
> 15   rcu_read_unlock();
> 16   rcu_read_lock();
> 17   r2 = READ_ONCE(x);
> 18   rcu_read_unlock();
> 19 }
> ```

After thread0() and thread1() execute concurrently, it is quite possible to have

>
>
> ```text
> (r1 == 1 && r2 == 0)
> ```

(that is, `y` appears to have been assigned before `x`), which would not be possible if rcu_read_lock() and rcu_read_unlock() had much in the way of ordering properties. But they do not, so the CPU is within its rights to do significant reordering. This is by design: Any significant ordering constraints would slow down these fast-path APIs.


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


**Quick Quiz**:

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


Can't the compiler also reorder this code?

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


**Answer**:

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


No, the volatile casts in READ_ONCE() and WRITE_ONCE() prevent the compiler from reordering in this particular case.

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

<a id="rst-readers-do-not-exclude-updaters"></a>

### Readers Do Not Exclude Updaters

Neither rcu_read_lock() nor rcu_read_unlock() exclude updates. All they do is to prevent grace periods from ending. The following example illustrates this:

>
>
> ```text
>  1 void thread0(void)
>  2 {
>  3   rcu_read_lock();
>  4   r1 = READ_ONCE(y);
>  5   if (r1) {
>  6     do_something_with_nonzero_x();
>  7     r2 = READ_ONCE(x);
>  8     WARN_ON(!r2); /* BUG!!! */
>  9   }
> 10   rcu_read_unlock();
> 11 }
> 12
> 13 void thread1(void)
> 14 {
> 15   spin_lock(&my_lock);
> 16   WRITE_ONCE(x, 1);
> 17   WRITE_ONCE(y, 1);
> 18   spin_unlock(&my_lock);
> 19 }
> ```

If the thread0() function's rcu_read_lock() excluded the thread1() function's update, the WARN_ON() could never fire. But the fact is that rcu_read_lock() does not exclude much of anything aside from subsequent grace periods, of which thread1() has none, so the WARN_ON() can and does fire.

<a id="rst-updaters-only-wait-for-old-readers"></a>

### Updaters Only Wait For Old Readers

It might be tempting to assume that after synchronize_rcu() completes, there are no readers executing. This temptation must be avoided because new readers can start immediately after synchronize_rcu() starts, and synchronize_rcu() is under no obligation to wait for these new readers.


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


**Quick Quiz**:

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


Suppose that synchronize_rcu() did wait until *all* readers had completed instead of waiting only on pre-existing readers. For how long would the updater be able to rely on there being no readers?

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


**Answer**:

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


For no time at all. Even if synchronize_rcu() were to wait until all readers had completed, a new reader might start immediately after synchronize_rcu() completed. Therefore, the code following synchronize_rcu() can *never* rely on there being no readers.

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

<a id="rst-grace-periods-don-t-partition-read-side-critical-sections"></a>

### Grace Periods Don't Partition Read-Side Critical Sections

It is tempting to assume that if any part of one RCU read-side critical section precedes a given grace period, and if any part of another RCU read-side critical section follows that same grace period, then all of the first RCU read-side critical section must precede all of the second. However, this just isn't the case: A single grace period does not partition the set of RCU read-side critical sections. An example of this situation can be illustrated as follows, where `x`, `y`, and `z` are initially all zero:

>
>
> ```text
>  1 void thread0(void)
>  2 {
>  3   rcu_read_lock();
>  4   WRITE_ONCE(a, 1);
>  5   WRITE_ONCE(b, 1);
>  6   rcu_read_unlock();
>  7 }
>  8
>  9 void thread1(void)
> 10 {
> 11   r1 = READ_ONCE(a);
> 12   synchronize_rcu();
> 13   WRITE_ONCE(c, 1);
> 14 }
> 15
> 16 void thread2(void)
> 17 {
> 18   rcu_read_lock();
> 19   r2 = READ_ONCE(b);
> 20   r3 = READ_ONCE(c);
> 21   rcu_read_unlock();
> 22 }
> ```

It turns out that the outcome:

>
>
> ```text
> (r1 == 1 && r2 == 0 && r3 == 1)
> ```

is entirely possible. The following figure show how this can happen, with each circled `QS` indicating the point at which RCU recorded a *quiescent state* for each thread, that is, a state in which RCU knows that the thread cannot be in the midst of an RCU read-side critical section that started before the current grace period:

![](/kernel/internals/rcu/design-requirements/asset-5fbf59860fab-gppartitionreaders1.svg)

If it is necessary to partition RCU read-side critical sections in this manner, it is necessary to use two grace periods, where the first grace period is known to end before the second grace period starts:

>
>
> ```text
>  1 void thread0(void)
>  2 {
>  3   rcu_read_lock();
>  4   WRITE_ONCE(a, 1);
>  5   WRITE_ONCE(b, 1);
>  6   rcu_read_unlock();
>  7 }
>  8
>  9 void thread1(void)
> 10 {
> 11   r1 = READ_ONCE(a);
> 12   synchronize_rcu();
> 13   WRITE_ONCE(c, 1);
> 14 }
> 15
> 16 void thread2(void)
> 17 {
> 18   r2 = READ_ONCE(c);
> 19   synchronize_rcu();
> 20   WRITE_ONCE(d, 1);
> 21 }
> 22
> 23 void thread3(void)
> 24 {
> 25   rcu_read_lock();
> 26   r3 = READ_ONCE(b);
> 27   r4 = READ_ONCE(d);
> 28   rcu_read_unlock();
> 29 }
> ```

Here, if `(r1 == 1)`, then thread0()'s write to `b` must happen before the end of thread1()'s grace period. If in addition `(r4 == 1)`, then thread3()'s read from `b` must happen after the beginning of thread2()'s grace period. If it is also the case that `(r2 == 1)`, then the end of thread1()'s grace period must precede the beginning of thread2()'s grace period. This mean that the two RCU read-side critical sections cannot overlap, guaranteeing that `(r3 == 1)`. As a result, the outcome:

>
>
> ```text
> (r1 == 1 && r2 == 1 && r3 == 0 && r4 == 1)
> ```

cannot happen.

This non-requirement was also non-premeditated, but became apparent when studying RCU's interaction with memory ordering.

<a id="rst-read-side-critical-sections-don-t-partition-grace-periods"></a>

### Read-Side Critical Sections Don't Partition Grace Periods

It is also tempting to assume that if an RCU read-side critical section happens between a pair of grace periods, then those grace periods cannot overlap. However, this temptation leads nowhere good, as can be illustrated by the following, with all variables initially zero:

>
>
> ```text
>  1 void thread0(void)
>  2 {
>  3   rcu_read_lock();
>  4   WRITE_ONCE(a, 1);
>  5   WRITE_ONCE(b, 1);
>  6   rcu_read_unlock();
>  7 }
>  8
>  9 void thread1(void)
> 10 {
> 11   r1 = READ_ONCE(a);
> 12   synchronize_rcu();
> 13   WRITE_ONCE(c, 1);
> 14 }
> 15
> 16 void thread2(void)
> 17 {
> 18   rcu_read_lock();
> 19   WRITE_ONCE(d, 1);
> 20   r2 = READ_ONCE(c);
> 21   rcu_read_unlock();
> 22 }
> 23
> 24 void thread3(void)
> 25 {
> 26   r3 = READ_ONCE(d);
> 27   synchronize_rcu();
> 28   WRITE_ONCE(e, 1);
> 29 }
> 30
> 31 void thread4(void)
> 32 {
> 33   rcu_read_lock();
> 34   r4 = READ_ONCE(b);
> 35   r5 = READ_ONCE(e);
> 36   rcu_read_unlock();
> 37 }
> ```

In this case, the outcome:

>
>
> ```text
> (r1 == 1 && r2 == 1 && r3 == 1 && r4 == 0 && r5 == 1)
> ```

is entirely possible, as illustrated below:

![](/kernel/internals/rcu/design-requirements/asset-48eba113ec88-readerspartitiongp1.svg)

Again, an RCU read-side critical section can overlap almost all of a given grace period, just so long as it does not overlap the entire grace period. As a result, an RCU read-side critical section cannot partition a pair of RCU grace periods.


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


**Quick Quiz**:

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


How long a sequence of grace periods, each separated by an RCU read-side critical section, would be required to partition the RCU read-side critical sections at the beginning and end of the chain?

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


**Answer**:

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


In theory, an infinite number. In practice, an unknown number that is sensitive to both implementation details and timing considerations. Therefore, even in practice, RCU users must abide by the theoretical rather than the practical answer.

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

<a id="rst-parallelism-facts-of-life"></a>

## Parallelism Facts of Life

These parallelism facts of life are by no means specific to RCU, but the RCU implementation must abide by them. They therefore bear repeating:

1. Any CPU or task may be delayed at any time, and any attempts to avoid these delays by disabling preemption, interrupts, or whatever are completely futile. This is most obvious in preemptible user-level environments and in virtualized environments (where a given guest OS's VCPUs can be preempted at any time by the underlying hypervisor), but can also happen in bare-metal environments due to ECC errors, NMIs, and other hardware events. Although a delay of more than about 20 seconds can result in splats, the RCU implementation is obligated to use algorithms that can tolerate extremely long delays, but where “extremely long” is not long enough to allow wrap-around when incrementing a 64-bit counter.

2. Both the compiler and the CPU can reorder memory accesses. Where it matters, RCU must use compiler directives and memory-barrier instructions to preserve ordering.

3. Conflicting writes to memory locations in any given cache line will result in expensive cache misses. Greater numbers of concurrent writes and more-frequent concurrent writes will result in more dramatic slowdowns. RCU is therefore obligated to use algorithms that have sufficient locality to avoid significant performance and scalability problems.

4. As a rough rule of thumb, only one CPU's worth of processing may be carried out under the protection of any given exclusive lock. RCU must therefore use scalable locking designs.

5. Counters are finite, especially on 32-bit systems. RCU's use of counters must therefore tolerate counter wrap, or be designed such that counter wrap would take way more time than a single system is likely to run. An uptime of ten years is quite possible, a runtime of a century much less so. As an example of the latter, RCU's dyntick-idle nesting counter allows 54 bits for interrupt nesting level (this counter is 64 bits even on a 32-bit system). Overflowing this counter requires 2<sup>54</sup> half-interrupts on a given CPU without that CPU ever going idle. If a half-interrupt happened every microsecond, it would take 570 years of runtime to overflow this counter, which is currently believed to be an acceptably long time.

6. Linux systems can have thousands of CPUs running a single Linux kernel in a single shared-memory environment. RCU must therefore pay close attention to high-end scalability.

This last parallelism fact of life means that RCU must pay special attention to the preceding facts of life. The idea that Linux might scale to systems with thousands of CPUs would have been met with some skepticism in the 1990s, but these requirements would have otherwise have been unsurprising, even in the early 1990s.

<a id="rst-quality-of-implementation-requirements"></a>

## Quality-of-Implementation Requirements

These sections list quality-of-implementation requirements. Although an RCU implementation that ignores these requirements could still be used, it would likely be subject to limitations that would make it inappropriate for industrial-strength production use. Classes of quality-of-implementation requirements are as follows:

1. [Specialization](<#rst-specialization>)

2. [Performance and Scalability](<#rst-performance-and-scalability>)

3. [Forward Progress](<#rst-forward-progress>)

4. [Composability](<#rst-composability>)

5. [Corner Cases](<#rst-corner-cases>)

These classes is covered in the following sections.

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

### Specialization

RCU is and always has been intended primarily for read-mostly situations, which means that RCU's read-side primitives are optimized, often at the expense of its update-side primitives. Experience thus far is captured by the following list of situations:

1. Read-mostly data, where stale and inconsistent data is not a problem: RCU works great\!

2. Read-mostly data, where data must be consistent: RCU works well.

3. Read-write data, where data must be consistent: RCU *might* work OK. Or not.

4. Write-mostly data, where data must be consistent: RCU is very unlikely to be the right tool for the job, with the following exceptions, where RCU can provide:

   - **a.** Existence guarantees for update-friendly mechanisms.

   - **b.** Wait-free read-side primitives for real-time use.

This focus on read-mostly situations means that RCU must interoperate with other synchronization primitives. For example, the add_gp() and remove_gp_synchronous() examples discussed earlier use RCU to protect readers and locking to coordinate updaters. However, the need extends much farther, requiring that a variety of synchronization primitives be legal within RCU read-side critical sections, including spinlocks, sequence locks, atomic operations, reference counters, and memory barriers.


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


**Quick Quiz**:

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


What about sleeping locks?

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


**Answer**:

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


These are forbidden within Linux-kernel RCU read-side critical sections because it is not legal to place a quiescent state (in this case, voluntary context switch) within an RCU read-side critical section. However, sleeping locks may be used within userspace RCU read-side critical sections, and also within Linux-kernel sleepable RCU [(SRCU)](<#rst-sleepable-rcu>) read-side critical sections. In addition, the -rt patchset turns spinlocks into a sleeping locks so that the corresponding critical sections can be preempted, which also means that these sleeplockified spinlocks (but not other sleeping locks\!) may be acquire within -rt-Linux-kernel RCU read-side critical sections. Note that it *is* legal for a normal RCU read-side critical section to conditionally acquire a sleeping locks (as in mutex_trylock()), but only as long as it does not loop indefinitely attempting to conditionally acquire that sleeping locks. The key point is that things like mutex_trylock() either return with the mutex held, or return an error indication if the mutex was not immediately available. Either way, mutex_trylock() returns immediately without sleeping.

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

It often comes as a surprise that many algorithms do not require a consistent view of data, but many can function in that mode, with network routing being the poster child. Internet routing algorithms take significant time to propagate updates, so that by the time an update arrives at a given system, that system has been sending network traffic the wrong way for a considerable length of time. Having a few threads continue to send traffic the wrong way for a few more milliseconds is clearly not a problem: In the worst case, TCP retransmissions will eventually get the data where it needs to go. In general, when tracking the state of the universe outside of the computer, some level of inconsistency must be tolerated due to speed-of-light delays if nothing else.

Furthermore, uncertainty about external state is inherent in many cases. For example, a pair of veterinarians might use heartbeat to determine whether or not a given cat was alive. But how long should they wait after the last heartbeat to decide that the cat is in fact dead? Waiting less than 400 milliseconds makes no sense because this would mean that a relaxed cat would be considered to cycle between death and life more than 100 times per minute. Moreover, just as with human beings, a cat's heart might stop for some period of time, so the exact wait period is a judgment call. One of our pair of veterinarians might wait 30 seconds before pronouncing the cat dead, while the other might insist on waiting a full minute. The two veterinarians would then disagree on the state of the cat during the final 30 seconds of the minute following the last heartbeat.

Interestingly enough, this same situation applies to hardware. When push comes to shove, how do we tell whether or not some external server has failed? We send messages to it periodically, and declare it failed if we don't receive a response within a given period of time. Policy decisions can usually tolerate short periods of inconsistency. The policy was decided some time ago, and is only now being put into effect, so a few milliseconds of delay is normally inconsequential.

However, there are algorithms that absolutely must see consistent data. For example, the translation between a user-level SystemV semaphore ID to the corresponding in-kernel data structure is protected by RCU, but it is absolutely forbidden to update a semaphore that has just been removed. In the Linux kernel, this need for consistency is accommodated by acquiring spinlocks located in the in-kernel data structure from within the RCU read-side critical section, and this is indicated by the green box in the figure above. Many other techniques may be used, and are in fact used within the Linux kernel.

In short, RCU is not required to maintain consistency, and other mechanisms may be used in concert with RCU when consistency is required. RCU's specialization allows it to do its job extremely well, and its ability to interoperate with other synchronization mechanisms allows the right mix of synchronization tools to be used for a given job.

<a id="rst-performance-and-scalability"></a>

### Performance and Scalability

Energy efficiency is a critical component of performance today, and Linux-kernel RCU implementations must therefore avoid unnecessarily awakening idle CPUs. I cannot claim that this requirement was premeditated. In fact, I learned of it during a telephone conversation in which I was given “frank and open” feedback on the importance of energy efficiency in battery-powered systems and on specific energy-efficiency shortcomings of the Linux-kernel RCU implementation. In my experience, the battery-powered embedded community will consider any unnecessary wakeups to be extremely unfriendly acts. So much so that mere Linux-kernel-mailing-list posts are insufficient to vent their ire.

Memory consumption is not particularly important for in most situations, and has become decreasingly so as memory sizes have expanded and memory costs have plummeted. However, as I learned from Matt Mackall's [bloatwatch](<http://elinux.org/Linux_Tiny-FAQ>) efforts, memory footprint is critically important on single-CPU systems with non-preemptible (`CONFIG_PREEMPTION=n`) kernels, and thus [tiny RCU](<https://lore.kernel.org/r/20090113221724.GA15307@linux.vnet.ibm.com>) was born. Josh Triplett has since taken over the small-memory banner with his [Linux kernel tinification](<https://tiny.wiki.kernel.org/>) project, which resulted in [SRCU](<#rst-sleepable-rcu>) becoming optional for those kernels not needing it.

The remaining performance requirements are, for the most part, unsurprising. For example, in keeping with RCU's read-side specialization, rcu_dereference() should have negligible overhead (for example, suppression of a few minor compiler optimizations). Similarly, in non-preemptible environments, rcu_read_lock() and rcu_read_unlock() should have exactly zero overhead.

In preemptible environments, in the case where the RCU read-side critical section was not preempted (as will be the case for the highest-priority real-time process), rcu_read_lock() and rcu_read_unlock() should have minimal overhead. In particular, they should not contain atomic read-modify-write operations, memory-barrier instructions, preemption disabling, interrupt disabling, or backwards branches. However, in the case where the RCU read-side critical section was preempted, rcu_read_unlock() may acquire spinlocks and disable interrupts. This is why it is better to nest an RCU read-side critical section within a preempt-disable region than vice versa, at least in cases where that critical section is short enough to avoid unduly degrading real-time latencies.

The synchronize_rcu() grace-period-wait primitive is optimized for throughput. It may therefore incur several milliseconds of latency in addition to the duration of the longest RCU read-side critical section. On the other hand, multiple concurrent invocations of synchronize_rcu() are required to use batching optimizations so that they can be satisfied by a single underlying grace-period-wait operation. For example, in the Linux kernel, it is not unusual for a single grace-period-wait operation to serve more than [1,000 separate invocations](<https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response>) of synchronize_rcu(), thus amortizing the per-invocation overhead down to nearly zero. However, the grace-period optimization is also required to avoid measurable degradation of real-time scheduling and interrupt latencies.

In some cases, the multi-millisecond synchronize_rcu() latencies are unacceptable. In these cases, synchronize_rcu_expedited() may be used instead, reducing the grace-period latency down to a few tens of microseconds on small systems, at least in cases where the RCU read-side critical sections are short. There are currently no special latency requirements for synchronize_rcu_expedited() on large systems, but, consistent with the empirical nature of the RCU specification, that is subject to change. However, there most definitely are scalability requirements: A storm of synchronize_rcu_expedited() invocations on 4096 CPUs should at least make reasonable forward progress. In return for its shorter latencies, synchronize_rcu_expedited() is permitted to impose modest degradation of real-time latency on non-idle online CPUs. Here, “modest” means roughly the same latency degradation as a scheduling-clock interrupt.

There are a number of situations where even synchronize_rcu_expedited()'s reduced grace-period latency is unacceptable. In these situations, the asynchronous call_rcu() can be used in place of synchronize_rcu() as follows:

>
>
> ```text
>  1 struct foo {
>  2   int a;
>  3   int b;
>  4   struct rcu_head rh;
>  5 };
>  6
>  7 static void remove_gp_cb(struct rcu_head *rhp)
>  8 {
>  9   struct foo *p = container_of(rhp, struct foo, rh);
> 10
> 11   kfree(p);
> 12 }
> 13
> 14 bool remove_gp_asynchronous(void)
> 15 {
> 16   struct foo *p;
> 17
> 18   spin_lock(&gp_lock);
> 19   p = rcu_access_pointer(gp);
> 20   if (!p) {
> 21     spin_unlock(&gp_lock);
> 22     return false;
> 23   }
> 24   rcu_assign_pointer(gp, NULL);
> 25   call_rcu(&p->rh, remove_gp_cb);
> 26   spin_unlock(&gp_lock);
> 27   return true;
> 28 }
> ```

A definition of `struct foo` is finally needed, and appears on lines 1-5. The function remove_gp_cb() is passed to call_rcu() on line 25, and will be invoked after the end of a subsequent grace period. This gets the same effect as remove_gp_synchronous(), but without forcing the updater to wait for a grace period to elapse. The call_rcu() function may be used in a number of situations where neither synchronize_rcu() nor synchronize_rcu_expedited() would be legal, including within preempt-disable code, local_bh_disable() code, interrupt-disable code, and interrupt handlers. However, even call_rcu() is illegal within NMI handlers and from idle and offline CPUs. The callback function (remove_gp_cb() in this case) will be executed within softirq (software interrupt) environment within the Linux kernel, either within a real softirq handler or under the protection of local_bh_disable(). In both the Linux kernel and in userspace, it is bad practice to write an RCU callback function that takes too long. Long-running operations should be relegated to separate threads or (in the Linux kernel) workqueues.


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


**Quick Quiz**:

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


Why does line 19 use rcu_access_pointer()? After all, call_rcu() on line 25 stores into the structure, which would interact badly with concurrent insertions. Doesn't this mean that rcu_dereference() is required?

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


**Answer**:

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


Presumably the `->gp_lock` acquired on line 18 excludes any changes, including any insertions that rcu_dereference() would protect against. Therefore, any insertions will be delayed until after `->gp_lock` is released on line 25, which in turn means that rcu_access_pointer() suffices.

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

However, all that remove_gp_cb() is doing is invoking kfree() on the data element. This is a common idiom, and is supported by kfree_rcu(), which allows “fire and forget” operation as shown below:

>
>
> ```text
>  1 struct foo {
>  2   int a;
>  3   int b;
>  4   struct rcu_head rh;
>  5 };
>  6
>  7 bool remove_gp_faf(void)
>  8 {
>  9   struct foo *p;
> 10
> 11   spin_lock(&gp_lock);
> 12   p = rcu_dereference(gp);
> 13   if (!p) {
> 14     spin_unlock(&gp_lock);
> 15     return false;
> 16   }
> 17   rcu_assign_pointer(gp, NULL);
> 18   kfree_rcu(p, rh);
> 19   spin_unlock(&gp_lock);
> 20   return true;
> 21 }
> ```

Note that remove_gp_faf() simply invokes kfree_rcu() and proceeds, without any need to pay any further attention to the subsequent grace period and kfree(). It is permissible to invoke kfree_rcu() from the same environments as for call_rcu(). Interestingly enough, DYNIX/ptx had the equivalents of call_rcu() and kfree_rcu(), but not synchronize_rcu(). This was due to the fact that RCU was not heavily used within DYNIX/ptx, so the very few places that needed something like synchronize_rcu() simply open-coded it.


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


**Quick Quiz**:

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


Earlier it was claimed that call_rcu() and kfree_rcu() allowed updaters to avoid being blocked by readers. But how can that be correct, given that the invocation of the callback and the freeing of the memory (respectively) must still wait for a grace period to elapse?

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


**Answer**:

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


We could define things this way, but keep in mind that this sort of definition would say that updates in garbage-collected languages cannot complete until the next time the garbage collector runs, which does not seem at all reasonable. The key point is that in most cases, an updater using either call_rcu() or kfree_rcu() can proceed to the next update as soon as it has invoked call_rcu() or kfree_rcu(), without having to wait for a subsequent grace period.

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

But what if the updater must wait for the completion of code to be executed after the end of the grace period, but has other tasks that can be carried out in the meantime? The polling-style get_state_synchronize_rcu() and cond_synchronize_rcu() functions may be used for this purpose, as shown below:

>
>
> ```text
>  1 bool remove_gp_poll(void)
>  2 {
>  3   struct foo *p;
>  4   unsigned long s;
>  5
>  6   spin_lock(&gp_lock);
>  7   p = rcu_access_pointer(gp);
>  8   if (!p) {
>  9     spin_unlock(&gp_lock);
> 10     return false;
> 11   }
> 12   rcu_assign_pointer(gp, NULL);
> 13   spin_unlock(&gp_lock);
> 14   s = get_state_synchronize_rcu();
> 15   do_something_while_waiting();
> 16   cond_synchronize_rcu(s);
> 17   kfree(p);
> 18   return true;
> 19 }
> ```

On line 14, get_state_synchronize_rcu() obtains a “cookie” from RCU, then line 15 carries out other tasks, and finally, line 16 returns immediately if a grace period has elapsed in the meantime, but otherwise waits as required. The need for `get_state_synchronize_rcu` and cond_synchronize_rcu() has appeared quite recently, so it is too early to tell whether they will stand the test of time.

RCU thus provides a range of tools to allow updaters to strike the required tradeoff between latency, flexibility and CPU overhead.

<a id="rst-forward-progress"></a>

### Forward Progress

In theory, delaying grace-period completion and callback invocation is harmless. In practice, not only are memory sizes finite but also callbacks sometimes do wakeups, and sufficiently deferred wakeups can be difficult to distinguish from system hangs. Therefore, RCU must provide a number of mechanisms to promote forward progress.

These mechanisms are not foolproof, nor can they be. For one simple example, an infinite loop in an RCU read-side critical section must by definition prevent later grace periods from ever completing. For a more involved example, consider a 64-CPU system built with `CONFIG_RCU_NOCB_CPU=y` and booted with `rcu_nocbs=1-63`, where CPUs 1 through 63 spin in tight loops that invoke call_rcu(). Even if these tight loops also contain calls to cond_resched() (thus allowing grace periods to complete), CPU 0 simply will not be able to invoke callbacks as fast as the other 63 CPUs can register them, at least not until the system runs out of memory. In both of these examples, the Spiderman principle applies: With great power comes great responsibility. However, short of this level of abuse, RCU is required to ensure timely completion of grace periods and timely invocation of callbacks.

RCU takes the following steps to encourage timely completion of grace periods:

1. If a grace period fails to complete within 100 milliseconds, RCU causes future invocations of cond_resched() on the holdout CPUs to provide an RCU quiescent state. RCU also causes those CPUs' need_resched() invocations to return `true`, but only after the corresponding CPU's next scheduling-clock.

2. CPUs mentioned in the `nohz_full` kernel boot parameter can run indefinitely in the kernel without scheduling-clock interrupts, which defeats the above need_resched() strategem. RCU will therefore invoke resched_cpu() on any `nohz_full` CPUs still holding out after 109 milliseconds.

3. In kernels built with `CONFIG_RCU_BOOST=y`, if a given task that has been preempted within an RCU read-side critical section is holding out for more than 500 milliseconds, RCU will resort to priority boosting.

4. If a CPU is still holding out 10 seconds into the grace period, RCU will invoke resched_cpu() on it regardless of its `nohz_full` state.

The above values are defaults for systems running with `HZ=1000`. They will vary as the value of `HZ` varies, and can also be changed using the relevant Kconfig options and kernel boot parameters. RCU currently does not do much sanity checking of these parameters, so please use caution when changing them. Note that these forward-progress measures are provided only for RCU, not for [SRCU](<#rst-sleepable-rcu>) or [Tasks RCU](<#rst-tasks-rcu>).

RCU takes the following steps in call_rcu() to encourage timely invocation of callbacks when any given non-`rcu_nocbs` CPU has 10,000 callbacks, or has 10,000 more callbacks than it had the last time encouragement was provided:

1. Starts a grace period, if one is not already in progress.

2. Forces immediate checking for quiescent states, rather than waiting for three milliseconds to have elapsed since the beginning of the grace period.

3. Immediately tags the CPU's callbacks with their grace period completion numbers, rather than waiting for the `RCU_SOFTIRQ` handler to get around to it.

4. Lifts callback-execution batch limits, which speeds up callback invocation at the expense of degrading realtime response.

Again, these are default values when running at `HZ=1000`, and can be overridden. Again, these forward-progress measures are provided only for RCU, not for [SRCU](<#rst-sleepable-rcu>) or [Tasks RCU](<#rst-tasks-rcu>). Even for RCU, callback-invocation forward progress for `rcu_nocbs` CPUs is much less well-developed, in part because workloads benefiting from `rcu_nocbs` CPUs tend to invoke call_rcu() relatively infrequently. If workloads emerge that need both `rcu_nocbs` CPUs and high call_rcu() invocation rates, then additional forward-progress work will be required.

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

### Composability

Composability has received much attention in recent years, perhaps in part due to the collision of multicore hardware with object-oriented techniques designed in single-threaded environments for single-threaded use. And in theory, RCU read-side critical sections may be composed, and in fact may be nested arbitrarily deeply. In practice, as with all real-world implementations of composable constructs, there are limitations.

Implementations of RCU for which rcu_read_lock() and rcu_read_unlock() generate no code, such as Linux-kernel RCU when `CONFIG_PREEMPTION=n`, can be nested arbitrarily deeply. After all, there is no overhead. Except that if all these instances of rcu_read_lock() and rcu_read_unlock() are visible to the compiler, compilation will eventually fail due to exhausting memory, mass storage, or user patience, whichever comes first. If the nesting is not visible to the compiler, as is the case with mutually recursive functions each in its own translation unit, stack overflow will result. If the nesting takes the form of loops, perhaps in the guise of tail recursion, either the control variable will overflow or (in the Linux kernel) you will get an RCU CPU stall warning. Nevertheless, this class of RCU implementations is one of the most composable constructs in existence.

RCU implementations that explicitly track nesting depth are limited by the nesting-depth counter. For example, the Linux kernel's preemptible RCU limits nesting to `INT_MAX`. This should suffice for almost all practical purposes. That said, a consecutive pair of RCU read-side critical sections between which there is an operation that waits for a grace period cannot be enclosed in another RCU read-side critical section. This is because it is not legal to wait for a grace period within an RCU read-side critical section: To do so would result either in deadlock or in RCU implicitly splitting the enclosing RCU read-side critical section, neither of which is conducive to a long-lived and prosperous kernel.

It is worth noting that RCU is not alone in limiting composability. For example, many transactional-memory implementations prohibit composing a pair of transactions separated by an irrevocable operation (for example, a network receive operation). For another example, lock-based critical sections can be composed surprisingly freely, but only if deadlock is avoided.

In short, although RCU read-side critical sections are highly composable, care is required in some situations, just as is the case for any other composable synchronization mechanism.

<a id="rst-corner-cases"></a>

### Corner Cases

A given RCU workload might have an endless and intense stream of RCU read-side critical sections, perhaps even so intense that there was never a point in time during which there was not at least one RCU read-side critical section in flight. RCU cannot allow this situation to block grace periods: As long as all the RCU read-side critical sections are finite, grace periods must also be finite.

That said, preemptible RCU implementations could potentially result in RCU read-side critical sections being preempted for long durations, which has the effect of creating a long-duration RCU read-side critical section. This situation can arise only in heavily loaded systems, but systems using real-time priorities are of course more vulnerable. Therefore, RCU priority boosting is provided to help deal with this case. That said, the exact requirements on RCU priority boosting will likely evolve as more experience accumulates.

Other workloads might have very high update rates. Although one can argue that such workloads should instead use something other than RCU, the fact remains that RCU must handle such workloads gracefully. This requirement is another factor driving batching of grace periods, but it is also the driving force behind the checks for large numbers of queued RCU callbacks in the call_rcu() code path. Finally, high update rates should not delay RCU read-side critical sections, although some small read-side delays can occur when using synchronize_rcu_expedited(), courtesy of this function's use of smp_call_function_single().

Although all three of these corner cases were understood in the early 1990s, a simple user-level test consisting of `close(open(path))` in a tight loop in the early 2000s suddenly provided a much deeper appreciation of the high-update-rate corner case. This test also motivated addition of some RCU code to react to high update rates, for example, if a given CPU finds itself with more than 10,000 RCU callbacks queued, it will cause RCU to take evasive action by more aggressively starting grace periods and more aggressively forcing completion of grace-period processing. This evasive action causes the grace period to complete more quickly, but at the cost of restricting RCU's batching optimizations, thus increasing the CPU overhead incurred by that grace period.

<a id="rst-software-engineering-requirements"></a>

## Software-Engineering Requirements

Between Murphy's Law and “To err is human”, it is necessary to guard against mishaps and misuse:

1. It is all too easy to forget to use rcu_read_lock() everywhere that it is needed, so kernels built with `CONFIG_PROVE_RCU=y` will splat if rcu_dereference() is used outside of an RCU read-side critical section. Update-side code can use rcu_dereference_protected(), which takes a [lockdep expression](<https://lwn.net/Articles/371986/>) to indicate what is providing the protection. If the indicated protection is not provided, a lockdep splat is emitted. Code shared between readers and updaters can use rcu_dereference_check(), which also takes a lockdep expression, and emits a lockdep splat if neither rcu_read_lock() nor the indicated protection is in place. In addition, rcu_dereference_raw() is used in those (hopefully rare) cases where the required protection cannot be easily described. Finally, rcu_read_lock_held() is provided to allow a function to verify that it has been invoked within an RCU read-side critical section. I was made aware of this set of requirements shortly after Thomas Gleixner audited a number of RCU uses.

2. A given function might wish to check for RCU-related preconditions upon entry, before using any other RCU API. The rcu_lockdep_assert() does this job, asserting the expression in kernels having lockdep enabled and doing nothing otherwise.

3. It is also easy to forget to use rcu_assign_pointer() and rcu_dereference(), perhaps (incorrectly) substituting a simple assignment. To catch this sort of error, a given RCU-protected pointer may be tagged with `__rcu`, after which sparse will complain about simple-assignment accesses to that pointer. Arnd Bergmann made me aware of this requirement, and also supplied the needed [patch series](<https://lwn.net/Articles/376011/>).

4. Kernels built with `CONFIG_DEBUG_OBJECTS_RCU_HEAD=y` will splat if a data element is passed to call_rcu() twice in a row, without a grace period in between. (This error is similar to a double free.) The corresponding `rcu_head` structures that are dynamically allocated are automatically tracked, but `rcu_head` structures allocated on the stack must be initialized with init_rcu_head_on_stack() and cleaned up with destroy_rcu_head_on_stack(). Similarly, statically allocated non-stack `rcu_head` structures must be initialized with init_rcu_head() and cleaned up with destroy_rcu_head(). Mathieu Desnoyers made me aware of this requirement, and also supplied the needed [patch](<https://lore.kernel.org/r/20100319013024.GA28456@Krystal>).

5. An infinite loop in an RCU read-side critical section will eventually trigger an RCU CPU stall warning splat, with the duration of “eventually” being controlled by the `RCU_CPU_STALL_TIMEOUT` `Kconfig` option, or, alternatively, by the `rcupdate.rcu_cpu_stall_timeout` boot/sysfs parameter. However, RCU is not obligated to produce this splat unless there is a grace period waiting on that particular RCU read-side critical section.

   Some extreme workloads might intentionally delay RCU grace periods, and systems running those workloads can be booted with `rcupdate.rcu_cpu_stall_suppress` to suppress the splats. This kernel parameter may also be set via `sysfs`. Furthermore, RCU CPU stall warnings are counter-productive during sysrq dumps and during panics. RCU therefore supplies the rcu_sysrq_start() and rcu_sysrq_end() API members to be called before and after long sysrq dumps. RCU also supplies the rcu_panic() notifier that is automatically invoked at the beginning of a panic to suppress further RCU CPU stall warnings.

   This requirement made itself known in the early 1990s, pretty much the first time that it was necessary to debug a CPU stall. That said, the initial implementation in DYNIX/ptx was quite generic in comparison with that of Linux.

6. Although it would be very good to detect pointers leaking out of RCU read-side critical sections, there is currently no good way of doing this. One complication is the need to distinguish between pointers leaking and pointers that have been handed off from RCU to some other synchronization mechanism, for example, reference counting.

7. In kernels built with `CONFIG_RCU_TRACE=y`, RCU-related information is provided via event tracing.

8. Open-coded use of rcu_assign_pointer() and rcu_dereference() to create typical linked data structures can be surprisingly error-prone. Therefore, RCU-protected [linked lists](<https://lwn.net/Articles/609973/#RCU%20List%20APIs>) and, more recently, RCU-protected [hash tables](<https://lwn.net/Articles/612100/>) are available. Many other special-purpose RCU-protected data structures are available in the Linux kernel and the userspace RCU library.

9. Some linked structures are created at compile time, but still require `__rcu` checking. The RCU_POINTER_INITIALIZER() macro serves this purpose.

10. It is not necessary to use rcu_assign_pointer() when creating linked structures that are to be published via a single external pointer. The RCU_INIT_POINTER() macro is provided for this task.

This not a hard-and-fast list: RCU's diagnostic capabilities will continue to be guided by the number and type of usage bugs found in real-world RCU usage.

<a id="rst-linux-kernel-complications"></a>

## Linux Kernel Complications

The Linux kernel provides an interesting environment for all kinds of software, including RCU. Some of the relevant points of interest are as follows:

1. [Configuration](<#rst-configuration>)

2. [Firmware Interface](<#rst-firmware-interface>)

3. [Early Boot](<#rst-early-boot>)

4. [Interrupts and NMIs](<#rst-interrupts-and-nmis>)

5. [Loadable Modules](<#rst-loadable-modules>)

6. [Hotplug CPU](<#rst-hotplug-cpu>)

7. [Scheduler and RCU](<#rst-scheduler-and-rcu>)

8. [Tracing and RCU](<#rst-tracing-and-rcu>)

9. [Accesses to User Memory and RCU](<#rst-accesses-to-user-memory-and-rcu>)

10. [Energy Efficiency](<#rst-energy-efficiency>)

11. [Scheduling-Clock Interrupts and RCU](<#rst-scheduling-clock-interrupts-and-rcu>)

12. [Memory Efficiency](<#rst-memory-efficiency>)

13. [Performance, Scalability, Response Time, and Reliability](<#rst-performance-scalability-response-time-and-reliability>)

This list is probably incomplete, but it does give a feel for the most notable Linux-kernel complications. Each of the following sections covers one of the above topics.

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

### Configuration

RCU's goal is automatic configuration, so that almost nobody needs to worry about RCU's `Kconfig` options. And for almost all users, RCU does in fact work well “out of the box.”

However, there are specialized use cases that are handled by kernel boot parameters and `Kconfig` options. Unfortunately, the `Kconfig` system will explicitly ask users about new `Kconfig` options, which requires almost all of them be hidden behind a `CONFIG_RCU_EXPERT` `Kconfig` option.

This all should be quite obvious, but the fact remains that Linus Torvalds recently had to [remind](<https://lore.kernel.org/r/CA+55aFy4wcCwaL4okTs8wXhGZ5h-ibecy_Meg9C4MNQrUnwMcg@mail.gmail.com>) me of this requirement.

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

### Firmware Interface

In many cases, kernel obtains information about the system from the firmware, and sometimes things are lost in translation. Or the translation is accurate, but the original message is bogus.

For example, some systems' firmware overreports the number of CPUs, sometimes by a large factor. If RCU naively believed the firmware, as it used to do, it would create too many per-CPU kthreads. Although the resulting system will still run correctly, the extra kthreads needlessly consume memory and can cause confusion when they show up in `ps` listings.

RCU must therefore wait for a given CPU to actually come online before it can allow itself to believe that the CPU actually exists. The resulting “ghost CPUs” (which are never going to come online) cause a number of [interesting complications](<https://paulmck.livejournal.com/37494.html>).

<a id="rst-early-boot"></a>

### Early Boot

The Linux kernel's boot sequence is an interesting process, and RCU is used early, even before rcu_init() is invoked. In fact, a number of RCU's primitives can be used as soon as the initial task's `task_struct` is available and the boot CPU's per-CPU variables are set up. The read-side primitives (rcu_read_lock(), rcu_read_unlock(), rcu_dereference(), and rcu_access_pointer()) will operate normally very early on, as will rcu_assign_pointer().

Although call_rcu() may be invoked at any time during boot, callbacks are not guaranteed to be invoked until after all of RCU's kthreads have been spawned, which occurs at early_initcall() time. This delay in callback invocation is due to the fact that RCU does not invoke callbacks until it is fully initialized, and this full initialization cannot occur until after the scheduler has initialized itself to the point where RCU can spawn and run its kthreads. In theory, it would be possible to invoke callbacks earlier, however, this is not a panacea because there would be severe restrictions on what operations those callbacks could invoke.

Perhaps surprisingly, synchronize_rcu() and synchronize_rcu_expedited(), will operate normally during very early boot, the reason being that there is only one CPU and preemption is disabled. This means that the call synchronize_rcu() (or friends) itself is a quiescent state and thus a grace period, so the early-boot implementation can be a no-op.

However, once the scheduler has spawned its first kthread, this early boot trick fails for synchronize_rcu() (as well as for synchronize_rcu_expedited()) in `CONFIG_PREEMPTION=y` kernels. The reason is that an RCU read-side critical section might be preempted, which means that a subsequent synchronize_rcu() really does have to wait for something, as opposed to simply returning immediately. Unfortunately, synchronize_rcu() can't do this until all of its kthreads are spawned, which doesn't happen until some time during early_initcalls() time. But this is no excuse: RCU is nevertheless required to correctly handle synchronous grace periods during this time period. Once all of its kthreads are up and running, RCU starts running normally.


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


**Quick Quiz**:

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


How can RCU possibly handle grace periods before all of its kthreads have been spawned???

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


**Answer**:

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


Very carefully\! During the “dead zone” between the time that the scheduler spawns the first task and the time that all of RCU's kthreads have been spawned, all synchronous grace periods are handled by the expedited grace-period mechanism. At runtime, this expedited mechanism relies on workqueues, but during the dead zone the requesting task itself drives the desired expedited grace period. Because dead-zone execution takes place within task context, everything works. Once the dead zone ends, expedited grace periods go back to using workqueues, as is required to avoid problems that would otherwise occur when a user task received a POSIX signal while driving an expedited grace period.

And yes, this does mean that it is unhelpful to send POSIX signals to random tasks between the time that the scheduler spawns its first kthread and the time that RCU's kthreads have all been spawned. If there ever turns out to be a good reason for sending POSIX signals during that time, appropriate adjustments will be made. (If it turns out that POSIX signals are sent during this time for no good reason, other adjustments will be made, appropriate or otherwise.)

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

I learned of these boot-time requirements as a result of a series of system hangs.

<a id="rst-interrupts-and-nmis"></a>

### Interrupts and NMIs

The Linux kernel has interrupts, and RCU read-side critical sections are legal within interrupt handlers and within interrupt-disabled regions of code, as are invocations of call_rcu().

Some Linux-kernel architectures can enter an interrupt handler from non-idle process context, and then just never leave it, instead stealthily transitioning back to process context. This trick is sometimes used to invoke system calls from inside the kernel. These “half-interrupts” mean that RCU has to be very careful about how it counts interrupt nesting levels. I learned of this requirement the hard way during a rewrite of RCU's dyntick-idle code.

The Linux kernel has non-maskable interrupts (NMIs), and RCU read-side critical sections are legal within NMI handlers. Thankfully, RCU update-side primitives, including call_rcu(), are prohibited within NMI handlers.

The name notwithstanding, some Linux-kernel architectures can have nested NMIs, which RCU must handle correctly. Andy Lutomirski [surprised me](<https://lore.kernel.org/r/CALCETrXLq1y7e_dKFPgou-FKHB6Pu-r8+t-6Ds+8=va7anBWDA@mail.gmail.com>) with this requirement; he also kindly surprised me with [an algorithm](<https://lore.kernel.org/r/CALCETrXSY9JpW3uE6H8WYk81sg56qasA2aqmjMPsq5dOtzso=g@mail.gmail.com>) that meets this requirement.

Furthermore, NMI handlers can be interrupted by what appear to RCU to be normal interrupts. One way that this can happen is for code that directly invokes ct_irq_enter() and ct_irq_exit() to be called from an NMI handler. This astonishing fact of life prompted the current code structure, which has ct_irq_enter() invoking ct_nmi_enter() and ct_irq_exit() invoking ct_nmi_exit(). And yes, I also learned of this requirement the hard way.

<a id="rst-loadable-modules"></a>

### Loadable Modules

The Linux kernel has loadable modules, and these modules can also be unloaded. After a given module has been unloaded, any attempt to call one of its functions results in a segmentation fault. The module-unload functions must therefore cancel any delayed calls to loadable-module functions, for example, any outstanding mod_timer() must be dealt with via timer_shutdown_sync() or similar.

Unfortunately, there is no way to cancel an RCU callback; once you invoke call_rcu(), the callback function is eventually going to be invoked, unless the system goes down first. Because it is normally considered socially irresponsible to crash the system in response to a module unload request, we need some other way to deal with in-flight RCU callbacks.

RCU therefore provides rcu_barrier(), which waits until all in-flight RCU callbacks have been invoked. If a module uses call_rcu(), its exit function should therefore prevent any future invocation of call_rcu(), then invoke rcu_barrier(). In theory, the underlying module-unload code could invoke rcu_barrier() unconditionally, but in practice this would incur unacceptable latencies.

Nikita Danilov noted this requirement for an analogous filesystem-unmount situation, and Dipankar Sarma incorporated rcu_barrier() into RCU. The need for rcu_barrier() for module unloading became apparent later.

> [!IMPORTANT]
>
> The rcu_barrier() function is not, repeat, *not*, obligated to wait for a grace period. It is instead only required to wait for RCU callbacks that have already been posted. Therefore, if there are no RCU callbacks posted anywhere in the system, rcu_barrier() is within its rights to return immediately. Even if there are callbacks posted, rcu_barrier() does not necessarily need to wait for a grace period.


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


**Quick Quiz**:

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


Wait a minute\! Each RCU callbacks must wait for a grace period to complete, and rcu_barrier() must wait for each pre-existing callback to be invoked. Doesn't rcu_barrier() therefore need to wait for a full grace period if there is even one callback posted anywhere in the system?

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


**Answer**:

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


Absolutely not\!\!\! Yes, each RCU callbacks must wait for a grace period to complete, but it might well be partly (or even completely) finished waiting by the time rcu_barrier() is invoked. In that case, rcu_barrier() need only wait for the remaining portion of the grace period to elapse. So even if there are quite a few callbacks posted, rcu_barrier() might well return quite quickly.

So if you need to wait for a grace period as well as for all pre-existing callbacks, you will need to invoke both synchronize_rcu() and rcu_barrier(). If latency is a concern, you can always use workqueues to invoke them concurrently.

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

<a id="rst-hotplug-cpu"></a>

### Hotplug CPU

The Linux kernel supports CPU hotplug, which means that CPUs can come and go. It is of course illegal to use any RCU API member from an offline CPU, with the exception of [SRCU](<#rst-sleepable-rcu>) read-side critical sections. This requirement was present from day one in DYNIX/ptx, but on the other hand, the Linux kernel's CPU-hotplug implementation is “interesting.”

The Linux-kernel CPU-hotplug implementation has notifiers that are used to allow the various kernel subsystems (including RCU) to respond appropriately to a given CPU-hotplug operation. Most RCU operations may be invoked from CPU-hotplug notifiers, including even synchronous grace-period operations such as (synchronize_rcu() and synchronize_rcu_expedited()).  However, these synchronous operations do block and therefore cannot be invoked from notifiers that execute via stop_machine(), specifically those between the `CPUHP_AP_OFFLINE` and `CPUHP_AP_ONLINE` states.

In addition, all-callback-wait operations such as rcu_barrier() may not be invoked from any CPU-hotplug notifier.  This restriction is due to the fact that there are phases of CPU-hotplug operations where the outgoing CPU's callbacks will not be invoked until after the CPU-hotplug operation ends, which could also result in deadlock. Furthermore, rcu_barrier() blocks CPU-hotplug operations during its execution, which results in another type of deadlock when invoked from a CPU-hotplug notifier.

Finally, RCU must avoid deadlocks due to interaction between hotplug, timers and grace period processing. It does so by maintaining its own set of books that duplicate the centrally maintained `cpu_online_mask`, and also by reporting quiescent states explicitly when a CPU goes offline.  This explicit reporting of quiescent states avoids any need for the force-quiescent-state loop (FQS) to report quiescent states for offline CPUs.  However, as a debugging measure, the FQS loop does splat if offline CPUs block an RCU grace period for too long.

An offline CPU's quiescent state will be reported either:

1. As the CPU goes offline using RCU's hotplug notifier (rcutree_report_cpu_dead()).

2. When grace period initialization (rcu_gp_init()) detects a race either with CPU offlining or with a task unblocking on a leaf `rcu_node` structure whose CPUs are all offline.

The CPU-online path (rcutree_report_cpu_starting()) should never need to report a quiescent state for an offline CPU.  However, as a debugging measure, it does emit a warning if a quiescent state was not already reported for that CPU.

During the checking/modification of RCU's hotplug bookkeeping, the corresponding CPU's leaf node lock is held. This avoids race conditions between RCU's hotplug notifier hooks, the grace period initialization code, and the FQS loop, all of which refer to or modify this bookkeeping.

Note that grace period initialization (rcu_gp_init()) must carefully sequence CPU hotplug scanning with grace period state changes. For example, the following race could occur in rcu_gp_init() if rcu_seq_start() were to happen after the CPU hotplug scanning:



```text
CPU0 (rcu_gp_init)                   CPU1                          CPU2
---------------------                ----                          ----
// Hotplug scan first (WRONG ORDER)
rcu_for_each_leaf_node(rnp) {
    rnp->qsmaskinit = rnp->qsmaskinitnext;
}
                                     rcutree_report_cpu_starting()
                                         rnp->qsmaskinitnext |= mask;
                                     rcu_read_lock()
                                     r0 = *X;
                                                                   r1 = *X;
                                                                   X = NULL;
                                                                   cookie = get_state_synchronize_rcu();
                                                                   // cookie = 8 (future GP)
rcu_seq_start(&rcu_state.gp_seq);
// gp_seq = 5

// CPU1 now invisible to this GP!
rcu_for_each_node_breadth_first() {
    rnp->qsmask = rnp->qsmaskinit;
    // CPU1 not included!
}

// GP completes without CPU1
rcu_seq_end(&rcu_state.gp_seq);
// gp_seq = 8
                                                                   poll_state_synchronize_rcu(cookie);
                                                                   // Returns true!
                                                                   kfree(r1);
                                     r2 = *r0; // USE-AFTER-FREE!
```

By incrementing `gp_seq` first, CPU1's RCU read-side critical section is guaranteed to not be missed by CPU2.

<a id="rst-concurrent-quiescent-state-reporting-for-offline-cpus"></a>

#### Concurrent Quiescent State Reporting for Offline CPUs

RCU must ensure that CPUs going offline report quiescent states to avoid blocking grace periods. This requires careful synchronization to handle race conditions

<a id="rst-race-condition-causing-offline-cpu-to-hang-gp"></a>

#### Race condition causing Offline CPU to hang GP

A race between CPU offlining and new GP initialization (gp_init()) may occur because rcu_report_qs_rnp() in rcutree_report_cpu_dead() must temporarily release the `rcu_node` lock to wake the RCU grace-period kthread:



```text
CPU1 (going offline)                 CPU0 (GP kthread)
--------------------                 -----------------
rcutree_report_cpu_dead()
  rcu_report_qs_rnp()
    // Must release rnp->lock to wake GP kthread
    raw_spin_unlock_irqrestore_rcu_node()
                                     // Wakes up and starts new GP
                                     rcu_gp_init()
                                       // First loop:
                                       copies qsmaskinitnext->qsmaskinit
                                       // CPU1 still in qsmaskinitnext!

                                       // Second loop:
                                       rnp->qsmask = rnp->qsmaskinit
                                       mask = rnp->qsmask & ~rnp->qsmaskinitnext
                                       // mask is 0! CPU1 still in both masks
    // Reacquire lock (but too late)
  rnp->qsmaskinitnext &= ~mask       // Finally clears bit
```

Without `ofl_lock`, the new grace period includes the offline CPU and waits forever for its quiescent state causing a GP hang.

<a id="rst-a-solution-with-ofl-lock"></a>

#### A solution with ofl_lock

The `ofl_lock` (offline lock) prevents rcu_gp_init() from running during the vulnerable window when rcu_report_qs_rnp() has released `rnp->lock`:



```text
CPU0 (rcu_gp_init)                   CPU1 (rcutree_report_cpu_dead)
------------------                   ------------------------------
rcu_for_each_leaf_node(rnp) {
    arch_spin_lock(&ofl_lock) -----> arch_spin_lock(&ofl_lock) [BLOCKED]

    // Safe: CPU1 can't interfere
    rnp->qsmaskinit = rnp->qsmaskinitnext

    arch_spin_unlock(&ofl_lock) ---> // Now CPU1 can proceed
}                                    // But snapshot already taken
```

<a id="rst-another-race-causing-gp-hangs-in-rcu-gpu-init-reporting-qs-for-now-offline-cpus"></a>

#### Another race causing GP hangs in rcu_gpu_init(): Reporting QS for Now-offline CPUs

After the first loop takes an atomic snapshot of online CPUs, as shown above, the second loop in rcu_gp_init() detects CPUs that went offline between releasing `ofl_lock` and acquiring the per-node `rnp->lock`. This detection is crucial because:

1. The CPU might have gone offline after the snapshot but before the second loop

2. The offline CPU cannot report its own QS if it's already dead

3. Without this detection, the grace period would wait forever for CPUs that are now offline.

The second loop performs this detection safely:



```text
rcu_for_each_node_breadth_first(rnp) {
    raw_spin_lock_irqsave_rcu_node(rnp, flags);
    rnp->qsmask = rnp->qsmaskinit;  // Apply the snapshot

    // Detect CPUs offline after snapshot
    mask = rnp->qsmask & ~rnp->qsmaskinitnext;

    if (mask && rcu_is_leaf_node(rnp))
        rcu_report_qs_rnp(mask, ...)  // Report QS for offline CPUs
}
```

This approach ensures atomicity: quiescent state reporting for offline CPUs happens either in rcu_gp_init() (second loop) or in rcutree_report_cpu_dead(), never both and never neither. The `rnp->lock` held throughout the sequence prevents races - rcutree_report_cpu_dead() also acquires this lock when clearing `qsmaskinitnext`, ensuring mutual exclusion.

<a id="rst-scheduler-and-rcu"></a>

### Scheduler and RCU

RCU makes use of kthreads, and it is necessary to avoid excessive CPU-time accumulation by these kthreads. This requirement was no surprise, but RCU's violation of it when running context-switch-heavy workloads when built with `CONFIG_NO_HZ_FULL=y` [did come as a surprise \[PDF\]](<http://www.rdrop.com/users/paulmck/scalability/paper/BareMetal.2015.01.15b.pdf>). RCU has made good progress towards meeting this requirement, even for context-switch-heavy `CONFIG_NO_HZ_FULL=y` workloads, but there is room for further improvement.

There is no longer any prohibition against holding any of scheduler's runqueue or priority-inheritance spinlocks across an rcu_read_unlock(), even if interrupts and preemption were enabled somewhere within the corresponding RCU read-side critical section. Therefore, it is now perfectly legal to execute rcu_read_lock() with preemption enabled, acquire one of the scheduler locks, and hold that lock across the matching rcu_read_unlock().

Similarly, the RCU flavor consolidation has removed the need for negative nesting.  The fact that interrupt-disabled regions of code act as RCU read-side critical sections implicitly avoids earlier issues that used to result in destructive recursion via interrupt handler's use of RCU.

<a id="rst-tracing-and-rcu"></a>

### Tracing and RCU

It is possible to use tracing on RCU code, but tracing itself uses RCU. For this reason, rcu_dereference_raw_check() is provided for use by tracing, which avoids the destructive recursion that could otherwise ensue. This API is also used by virtualization in some architectures, where RCU readers execute in environments in which tracing cannot be used. The tracing folks both located the requirement and provided the needed fix, so this surprise requirement was relatively painless.

<a id="rst-accesses-to-user-memory-and-rcu"></a>

### Accesses to User Memory and RCU

The kernel needs to access user-space memory, for example, to access data referenced by system-call parameters.  The get_user() macro does this job.

However, user-space memory might well be paged out, which means that get_user() might well page-fault and thus block while waiting for the resulting I/O to complete.  It would be a very bad thing for the compiler to reorder a get_user() invocation into an RCU read-side critical section.

For example, suppose that the source code looked like this:

>
>
> ```text
> 1 rcu_read_lock();
> 2 p = rcu_dereference(gp);
> 3 v = p->value;
> 4 rcu_read_unlock();
> 5 get_user(user_v, user_p);
> 6 do_something_with(v, user_v);
> ```

The compiler must not be permitted to transform this source code into the following:

>
>
> ```text
> 1 rcu_read_lock();
> 2 p = rcu_dereference(gp);
> 3 get_user(user_v, user_p); // BUG: POSSIBLE PAGE FAULT!!!
> 4 v = p->value;
> 5 rcu_read_unlock();
> 6 do_something_with(v, user_v);
> ```

If the compiler did make this transformation in a `CONFIG_PREEMPTION=n` kernel build, and if get_user() did page fault, the result would be a quiescent state in the middle of an RCU read-side critical section.  This misplaced quiescent state could result in line 4 being a use-after-free access, which could be bad for your kernel's actuarial statistics.  Similar examples can be constructed with the call to get_user() preceding the rcu_read_lock().

Unfortunately, get_user() doesn't have any particular ordering properties, and in some architectures the underlying `asm` isn't even marked `volatile`.  And even if it was marked `volatile`, the above access to `p->value` is not volatile, so the compiler would not have any reason to keep those two accesses in order.

Therefore, the Linux-kernel definitions of rcu_read_lock() and rcu_read_unlock() must act as compiler barriers, at least for outermost instances of rcu_read_lock() and rcu_read_unlock() within a nested set of RCU read-side critical sections.

<a id="rst-energy-efficiency"></a>

### Energy Efficiency

Interrupting idle CPUs is considered socially unacceptable, especially by people with battery-powered embedded systems. RCU therefore conserves energy by detecting which CPUs are idle, including tracking CPUs that have been interrupted from idle. This is a large part of the energy-efficiency requirement, so I learned of this via an irate phone call.

Because RCU avoids interrupting idle CPUs, it is illegal to execute an RCU read-side critical section on an idle CPU. (Kernels built with `CONFIG_PROVE_RCU=y` will splat if you try it.)

It is similarly socially unacceptable to interrupt an `nohz_full` CPU running in userspace. RCU must therefore track `nohz_full` userspace execution. RCU must therefore be able to sample state at two points in time, and be able to determine whether or not some other CPU spent any time idle and/or executing in userspace.

These energy-efficiency requirements have proven quite difficult to understand and to meet, for example, there have been more than five clean-sheet rewrites of RCU's energy-efficiency code, the last of which was finally able to demonstrate [real energy savings running on real hardware \[PDF\]](<http://www.rdrop.com/users/paulmck/realtime/paper/AMPenergy.2013.04.19a.pdf>). As noted earlier, I learned of many of these requirements via angry phone calls: Flaming me on the Linux-kernel mailing list was apparently not sufficient to fully vent their ire at RCU's energy-efficiency bugs\!

<a id="rst-scheduling-clock-interrupts-and-rcu"></a>

### Scheduling-Clock Interrupts and RCU

The kernel transitions between in-kernel non-idle execution, userspace execution, and the idle loop. Depending on kernel configuration, RCU handles these states differently:


<table>
<thead>
<tr>
<th>


`HZ` Kconfig

</th>
<th>


In-Kernel

</th>
<th>


Usermode

</th>
<th>


Idle

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


`HZ_PERIODIC`

</td>
<td>


Can rely on scheduling-clock interrupt.

</td>
<td>


Can rely on scheduling-clock interrupt and its detection of interrupt from usermode.

</td>
<td>


Can rely on RCU's dyntick-idle detection.

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


`NO_HZ_IDLE`

</td>
<td>


Can rely on scheduling-clock interrupt.

</td>
<td>


Can rely on scheduling-clock interrupt and its detection of interrupt from usermode.

</td>
<td>


Can rely on RCU's dyntick-idle detection.

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


`NO_HZ_FULL`

</td>
<td>


Can only sometimes rely on scheduling-clock interrupt. In other cases, it is necessary to bound kernel execution times and/or use IPIs.

</td>
<td>


Can rely on RCU's dyntick-idle detection.

</td>
<td>


Can rely on RCU's dyntick-idle detection.

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


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


**Quick Quiz**:

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


Why can't `NO_HZ_FULL` in-kernel execution rely on the scheduling-clock interrupt, just like `HZ_PERIODIC` and `NO_HZ_IDLE` do?

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


**Answer**:

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


Because, as a performance optimization, `NO_HZ_FULL` does not necessarily re-enable the scheduling-clock interrupt on entry to each and every system call.

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

However, RCU must be reliably informed as to whether any given CPU is currently in the idle loop, and, for `NO_HZ_FULL`, also whether that CPU is executing in usermode, as discussed [earlier](<#rst-energy-efficiency>). It also requires that the scheduling-clock interrupt be enabled when RCU needs it to be:

1. If a CPU is either idle or executing in usermode, and RCU believes it is non-idle, the scheduling-clock tick had better be running. Otherwise, you will get RCU CPU stall warnings. Or at best, very long (11-second) grace periods, with a pointless IPI waking the CPU from time to time.

2. If a CPU is in a portion of the kernel that executes RCU read-side critical sections, and RCU believes this CPU to be idle, you will get random memory corruption. **DON'T DO THIS\!\!\!** This is one reason to test with lockdep, which will complain about this sort of thing.

3. If a CPU is in a portion of the kernel that is absolutely positively no-joking guaranteed to never execute any RCU read-side critical sections, and RCU believes this CPU to be idle, no problem. This sort of thing is used by some architectures for light-weight exception handlers, which can then avoid the overhead of ct_irq_enter() and ct_irq_exit() at exception entry and exit, respectively. Some go further and avoid the entireties of irq_enter() and irq_exit(). Just make very sure you are running some of your tests with `CONFIG_PROVE_RCU=y`, just in case one of your code paths was in fact joking about not doing RCU read-side critical sections.

4. If a CPU is executing in the kernel with the scheduling-clock interrupt disabled and RCU believes this CPU to be non-idle, and if the CPU goes idle (from an RCU perspective) every few jiffies, no problem. It is usually OK for there to be the occasional gap between idle periods of up to a second or so. If the gap grows too long, you get RCU CPU stall warnings.

5. If a CPU is either idle or executing in usermode, and RCU believes it to be idle, of course no problem.

6. If a CPU is executing in the kernel, the kernel code path is passing through quiescent states at a reasonable frequency (preferably about once per few jiffies, but the occasional excursion to a second or so is usually OK) and the scheduling-clock interrupt is enabled, of course no problem. If the gap between a successive pair of quiescent states grows too long, you get RCU CPU stall warnings.


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


**Quick Quiz**:

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


But what if my driver has a hardware interrupt handler that can run for many seconds? I cannot invoke schedule() from an hardware interrupt handler, after all\!

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


**Answer**:

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


One approach is to do `ct_irq_exit();ct_irq_enter();` every so often. But given that long-running interrupt handlers can cause other problems, not least for response time, shouldn't you work to keep your interrupt handler's runtime within reasonable bounds?

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

But as long as RCU is properly informed of kernel state transitions between in-kernel execution, usermode execution, and idle, and as long as the scheduling-clock interrupt is enabled when RCU needs it to be, you can rest assured that the bugs you encounter will be in some other part of RCU or some other part of the kernel\!

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

### Memory Efficiency

Although small-memory non-realtime systems can simply use Tiny RCU, code size is only one aspect of memory efficiency. Another aspect is the size of the `rcu_head` structure used by call_rcu() and kfree_rcu(). Although this structure contains nothing more than a pair of pointers, it does appear in many RCU-protected data structures, including some that are size critical. The `page` structure is a case in point, as evidenced by the many occurrences of the `union` keyword within that structure.

This need for memory efficiency is one reason that RCU uses hand-crafted singly linked lists to track the `rcu_head` structures that are waiting for a grace period to elapse. It is also the reason why `rcu_head` structures do not contain debug information, such as fields tracking the file and line of the call_rcu() or kfree_rcu() that posted them. Although this information might appear in debug-only kernel builds at some point, in the meantime, the `->func` field will often provide the needed debug information.

However, in some cases, the need for memory efficiency leads to even more extreme measures. Returning to the `page` structure, the `rcu_head` field shares storage with a great many other structures that are used at various points in the corresponding page's lifetime. In order to correctly resolve certain [race conditions](<https://lore.kernel.org/r/1439976106-137226-1-git-send-email-kirill.shutemov@linux.intel.com>), the Linux kernel's memory-management subsystem needs a particular bit to remain zero during all phases of grace-period processing, and that bit happens to map to the bottom bit of the `rcu_head` structure's `->next` field. RCU makes this guarantee as long as call_rcu() is used to post the callback, as opposed to kfree_rcu() or some future “lazy” variant of call_rcu() that might one day be created for energy-efficiency purposes.

That said, there are limits. RCU requires that the `rcu_head` structure be aligned to a two-byte boundary, and passing a misaligned `rcu_head` structure to one of the call_rcu() family of functions will result in a splat. It is therefore necessary to exercise caution when packing structures containing fields of type `rcu_head`. Why not a four-byte or even eight-byte alignment requirement? Because the m68k architecture provides only two-byte alignment, and thus acts as alignment's least common denominator.

The reason for reserving the bottom bit of pointers to `rcu_head` structures is to leave the door open to “lazy” callbacks whose invocations can safely be deferred. Deferring invocation could potentially have energy-efficiency benefits, but only if the rate of non-lazy callbacks decreases significantly for some important workload. In the meantime, reserving the bottom bit keeps this option open in case it one day becomes useful.

<a id="rst-performance-scalability-response-time-and-reliability"></a>

### Performance, Scalability, Response Time, and Reliability

Expanding on the [earlier discussion](<#rst-performance-and-scalability>), RCU is used heavily by hot code paths in performance-critical portions of the Linux kernel's networking, security, virtualization, and scheduling code paths. RCU must therefore use efficient implementations, especially in its read-side primitives. To that end, it would be good if preemptible RCU's implementation of rcu_read_lock() could be inlined, however, doing this requires resolving `#include` issues with the `task_struct` structure.

The Linux kernel supports hardware configurations with up to 4096 CPUs, which means that RCU must be extremely scalable. Algorithms that involve frequent acquisitions of global locks or frequent atomic operations on global variables simply cannot be tolerated within the RCU implementation. RCU therefore makes heavy use of a combining tree based on the `rcu_node` structure. RCU is required to tolerate all CPUs continuously invoking any combination of RCU's runtime primitives with minimal per-operation overhead. In fact, in many cases, increasing load must *decrease* the per-operation overhead, witness the batching optimizations for synchronize_rcu(), call_rcu(), synchronize_rcu_expedited(), and rcu_barrier(). As a general rule, RCU must cheerfully accept whatever the rest of the Linux kernel decides to throw at it.

The Linux kernel is used for real-time workloads, especially in conjunction with the [-rt patchset](<https://wiki.linuxfoundation.org/realtime/>). The real-time-latency response requirements are such that the traditional approach of disabling preemption across RCU read-side critical sections is inappropriate. Kernels built with `CONFIG_PREEMPTION=y` therefore use an RCU implementation that allows RCU read-side critical sections to be preempted. This requirement made its presence known after users made it clear that an earlier [real-time patch](<https://lwn.net/Articles/107930/>) did not meet their needs, in conjunction with some [RCU issues](<https://lore.kernel.org/r/20050318002026.GA2693@us.ibm.com>) encountered by a very early version of the -rt patchset.

In addition, RCU must make do with a sub-100-microsecond real-time latency budget. In fact, on smaller systems with the -rt patchset, the Linux kernel provides sub-20-microsecond real-time latencies for the whole kernel, including RCU. RCU's scalability and latency must therefore be sufficient for these sorts of configurations. To my surprise, the sub-100-microsecond real-time latency budget [applies to even the largest systems \[PDF\]](<http://www.rdrop.com/users/paulmck/realtime/paper/bigrt.2013.01.31a.LCA.pdf>), up to and including systems with 4096 CPUs. This real-time requirement motivated the grace-period kthread, which also simplified handling of a number of race conditions.

RCU must avoid degrading real-time response for CPU-bound threads, whether executing in usermode (which is one use case for `CONFIG_NO_HZ_FULL=y`) or in the kernel. That said, CPU-bound loops in the kernel must execute cond_resched() at least once per few tens of milliseconds in order to avoid receiving an IPI from RCU.

Finally, RCU's status as a synchronization primitive means that any RCU failure can result in arbitrary memory corruption that can be extremely difficult to debug. This means that RCU must be extremely reliable, which in practice also means that RCU must have an aggressive stress-test suite. This stress-test suite is called `rcutorture`.

Although the need for `rcutorture` was no surprise, the current immense popularity of the Linux kernel is posing interesting—and perhaps unprecedented—validation challenges. To see this, keep in mind that there are well over one billion instances of the Linux kernel running today, given Android smartphones, Linux-powered televisions, and servers. This number can be expected to increase sharply with the advent of the celebrated Internet of Things.

Suppose that RCU contains a race condition that manifests on average once per million years of runtime. This bug will be occurring about three times per *day* across the installed base. RCU could simply hide behind hardware error rates, given that no one should really expect their smartphone to last for a million years. However, anyone taking too much comfort from this thought should consider the fact that in most jurisdictions, a successful multi-year test of a given mechanism, which might include a Linux kernel, suffices for a number of types of safety-critical certifications. In fact, rumor has it that the Linux kernel is already being used in production for safety-critical applications. I don't know about you, but I would feel quite bad if a bug in RCU killed someone. Which might explain my recent focus on validation and verification.

<a id="rst-other-rcu-flavors"></a>

## Other RCU Flavors

One of the more surprising things about RCU is that there are now no fewer than five *flavors*, or API families. In addition, the primary flavor that has been the sole focus up to this point has two different implementations, non-preemptible and preemptible. The other four flavors are listed below, with requirements for each described in a separate section.

1. [Bottom-Half Flavor (Historical)](<#rst-bottom-half-flavor-historical>)

2. [Sched Flavor (Historical)](<#rst-sched-flavor-historical>)

3. [Sleepable RCU](<#rst-sleepable-rcu>)

4. [Tasks RCU](<#rst-tasks-rcu>)

5. [Tasks Trace RCU](<#rst-tasks-trace-rcu>)

<a id="rst-bottom-half-flavor-historical"></a>

### Bottom-Half Flavor (Historical)

The RCU-bh flavor of RCU has since been expressed in terms of the other RCU flavors as part of a consolidation of the three flavors into a single flavor. The read-side API remains, and continues to disable softirq and to be accounted for by lockdep. Much of the material in this section is therefore strictly historical in nature.

The softirq-disable (AKA “bottom-half”, hence the “\_bh” abbreviations) flavor of RCU, or *RCU-bh*, was developed by Dipankar Sarma to provide a flavor of RCU that could withstand the network-based denial-of-service attacks researched by Robert Olsson. These attacks placed so much networking load on the system that some of the CPUs never exited softirq execution, which in turn prevented those CPUs from ever executing a context switch, which, in the RCU implementation of that time, prevented grace periods from ever ending. The result was an out-of-memory condition and a system hang.

The solution was the creation of RCU-bh, which does local_bh_disable() across its read-side critical sections, and which uses the transition from one type of softirq processing to another as a quiescent state in addition to context switch, idle, user mode, and offline. This means that RCU-bh grace periods can complete even when some of the CPUs execute in softirq indefinitely, thus allowing algorithms based on RCU-bh to withstand network-based denial-of-service attacks.

Because rcu_read_lock_bh() and rcu_read_unlock_bh() disable and re-enable softirq handlers, any attempt to start a softirq handlers during the RCU-bh read-side critical section will be deferred. In this case, rcu_read_unlock_bh() will invoke softirq processing, which can take considerable time. One can of course argue that this softirq overhead should be associated with the code following the RCU-bh read-side critical section rather than rcu_read_unlock_bh(), but the fact is that most profiling tools cannot be expected to make this sort of fine distinction. For example, suppose that a three-millisecond-long RCU-bh read-side critical section executes during a time of heavy networking load. There will very likely be an attempt to invoke at least one softirq handler during that three milliseconds, but any such invocation will be delayed until the time of the rcu_read_unlock_bh(). This can of course make it appear at first glance as if rcu_read_unlock_bh() was executing very slowly.

The [RCU-bh API](<https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>) includes rcu_read_lock_bh(), rcu_read_unlock_bh(), rcu_dereference_bh(), rcu_dereference_bh_check(), and rcu_read_lock_bh_held(). However, the old RCU-bh update-side APIs are now gone, replaced by synchronize_rcu(), synchronize_rcu_expedited(), call_rcu(), and rcu_barrier().  In addition, anything that disables bottom halves also marks an RCU-bh read-side critical section, including local_bh_disable() and local_bh_enable(), local_irq_save() and local_irq_restore(), and so on.

<a id="rst-sched-flavor-historical"></a>

### Sched Flavor (Historical)

The RCU-sched flavor of RCU has since been expressed in terms of the other RCU flavors as part of a consolidation of the three flavors into a single flavor. The read-side API remains, and continues to disable preemption and to be accounted for by lockdep. Much of the material in this section is therefore strictly historical in nature.

Before preemptible RCU, waiting for an RCU grace period had the side effect of also waiting for all pre-existing interrupt and NMI handlers. However, there are legitimate preemptible-RCU implementations that do not have this property, given that any point in the code outside of an RCU read-side critical section can be a quiescent state. Therefore, *RCU-sched* was created, which follows “classic” RCU in that an RCU-sched grace period waits for pre-existing interrupt and NMI handlers. In kernels built with `CONFIG_PREEMPTION=n`, the RCU and RCU-sched APIs have identical implementations, while kernels built with `CONFIG_PREEMPTION=y` provide a separate implementation for each.

Note well that in `CONFIG_PREEMPTION=y` kernels, rcu_read_lock_sched() and rcu_read_unlock_sched() disable and re-enable preemption, respectively. This means that if there was a preemption attempt during the RCU-sched read-side critical section, rcu_read_unlock_sched() will enter the scheduler, with all the latency and overhead entailed. Just as with rcu_read_unlock_bh(), this can make it look as if rcu_read_unlock_sched() was executing very slowly. However, the highest-priority task won't be preempted, so that task will enjoy low-overhead rcu_read_unlock_sched() invocations.

The [RCU-sched API](<https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>) includes rcu_read_lock_sched(), rcu_read_unlock_sched(), rcu_read_lock_sched_notrace(), rcu_read_unlock_sched_notrace(), rcu_dereference_sched(), rcu_dereference_sched_check(), and rcu_read_lock_sched_held().  However, the old RCU-sched update-side APIs are now gone, replaced by synchronize_rcu(), synchronize_rcu_expedited(), call_rcu(), and rcu_barrier().  In addition, anything that disables preemption also marks an RCU-sched read-side critical section, including preempt_disable() and preempt_enable(), local_irq_save() and local_irq_restore(), and so on.

<a id="rst-sleepable-rcu"></a>

### Sleepable RCU

For well over a decade, someone saying “I need to block within an RCU read-side critical section” was a reliable indication that this someone did not understand RCU. After all, if you are always blocking in an RCU read-side critical section, you can probably afford to use a higher-overhead synchronization mechanism. However, that changed with the advent of the Linux kernel's notifiers, whose RCU read-side critical sections almost never sleep, but sometimes need to. This resulted in the introduction of [sleepable RCU](<https://lwn.net/Articles/202847/>), or *SRCU*.

SRCU allows different domains to be defined, with each such domain defined by an instance of an `srcu_struct` structure. A pointer to this structure must be passed in to each SRCU function, for example, `synchronize_srcu(&ss)`, where `ss` is the `srcu_struct` structure. The key benefit of these domains is that a slow SRCU reader in one domain does not delay an SRCU grace period in some other domain. That said, one consequence of these domains is that read-side code must pass a “cookie” from srcu_read_lock() to srcu_read_unlock(), for example, as follows:

>
>
> ```text
> 1 int idx;
> 2
> 3 idx = srcu_read_lock(&ss);
> 4 do_something();
> 5 srcu_read_unlock(&ss, idx);
> ```

As noted above, it is legal to block within SRCU read-side critical sections, however, with great power comes great responsibility. If you block forever in one of a given domain's SRCU read-side critical sections, then that domain's grace periods will also be blocked forever. Of course, one good way to block forever is to deadlock, which can happen if any operation in a given domain's SRCU read-side critical section can wait, either directly or indirectly, for that domain's grace period to elapse. For example, this results in a self-deadlock:

>
>
> ```text
> 1 int idx;
> 2
> 3 idx = srcu_read_lock(&ss);
> 4 do_something();
> 5 synchronize_srcu(&ss);
> 6 srcu_read_unlock(&ss, idx);
> ```

However, if line 5 acquired a mutex that was held across a synchronize_srcu() for domain `ss`, deadlock would still be possible. Furthermore, if line 5 acquired a mutex that was held across a synchronize_srcu() for some other domain `ss1`, and if an `ss1`-domain SRCU read-side critical section acquired another mutex that was held across as `ss`-domain synchronize_srcu(), deadlock would again be possible. Such a deadlock cycle could extend across an arbitrarily large number of different SRCU domains. Again, with great power comes great responsibility, though lockdep is now able to detect this sort of deadlock.

Unlike the other RCU flavors, SRCU read-side critical sections can run on idle and even offline CPUs, with the exception of srcu_read_lock_fast() and friends.  This ability requires that srcu_read_lock() and srcu_read_unlock() contain memory barriers, which means that SRCU readers will run a bit slower than would RCU readers. It also motivates the smp_mb__after_srcu_read_unlock() API, which, in combination with srcu_read_unlock(), guarantees a full memory barrier.

Also unlike other RCU flavors, synchronize_srcu() may **not** be invoked from CPU-hotplug notifiers, due to the fact that SRCU grace periods make use of timers and the possibility of timers being temporarily “stranded” on the outgoing CPU. This stranding of timers means that timers posted to the outgoing CPU will not fire until late in the CPU-hotplug process. The problem is that if a notifier is waiting on an SRCU grace period, that grace period is waiting on a timer, and that timer is stranded on the outgoing CPU, then the notifier will never be awakened, in other words, deadlock has occurred. This same situation of course also prohibits srcu_barrier() from being invoked from CPU-hotplug notifiers.

SRCU also differs from other RCU flavors in that SRCU's expedited and non-expedited grace periods are implemented by the same mechanism. This means that in the current SRCU implementation, expediting a future grace period has the side effect of expediting all prior grace periods that have not yet completed. (But please note that this is a property of the current implementation, not necessarily of future implementations.) In addition, if SRCU has been idle for longer than the interval specified by the `srcutree.exp_holdoff` kernel boot parameter (25 microseconds by default), and if a synchronize_srcu() invocation ends this idle period, that invocation will be automatically expedited.

As of v4.12, SRCU's callbacks are maintained per-CPU, eliminating a locking bottleneck present in prior kernel versions. Although this will allow users to put much heavier stress on call_srcu(), it is important to note that SRCU does not yet take any special steps to deal with callback flooding. So if you are posting (say) 10,000 SRCU callbacks per second per CPU, you are probably totally OK, but if you intend to post (say) 1,000,000 SRCU callbacks per second per CPU, please run some tests first. SRCU just might need a few adjustment to deal with that sort of load. Of course, your mileage may vary based on the speed of your CPUs and the size of your memory.

The [SRCU API](<https://lwn.net/Articles/609973/#RCU%20Per-Flavor%20API%20Table>) includes srcu_read_lock(), srcu_read_unlock(), srcu_dereference(), srcu_dereference_check(), synchronize_srcu(), synchronize_srcu_expedited(), call_srcu(), srcu_barrier(), and srcu_read_lock_held(). It also includes DEFINE_SRCU(), DEFINE_STATIC_SRCU(), DEFINE_SRCU_FAST(), DEFINE_STATIC_SRCU_FAST(), init_srcu_struct(), and init_srcu_struct_fast() APIs for defining and initializing `srcu_struct` structures.

More recently, the SRCU API has added polling interfaces:

1. start_poll_synchronize_srcu() returns a cookie identifying the completion of a future SRCU grace period and ensures that this grace period will be started.

2. poll_state_synchronize_srcu() returns `true` iff the specified cookie corresponds to an already-completed SRCU grace period.

3. get_state_synchronize_srcu() returns a cookie just like start_poll_synchronize_srcu() does, but differs in that it does nothing to ensure that any future SRCU grace period will be started.

These functions are used to avoid unnecessary SRCU grace periods in certain types of buffer-cache algorithms having multi-stage age-out mechanisms.  The idea is that by the time the block has aged completely from the cache, an SRCU grace period will be very likely to have elapsed.

<a id="rst-tasks-rcu"></a>

### Tasks RCU

Some forms of tracing use “trampolines” to handle the binary rewriting required to install different types of probes. It would be good to be able to free old trampolines, which sounds like a job for some form of RCU. However, because it is necessary to be able to install a trace anywhere in the code, it is not possible to use read-side markers such as rcu_read_lock() and rcu_read_unlock(). In addition, it does not work to have these markers in the trampoline itself, because there would need to be instructions following rcu_read_unlock(). Although synchronize_rcu() would guarantee that execution reached the rcu_read_unlock(), it would not be able to guarantee that execution had completely left the trampoline. Worse yet, in some situations the trampoline's protection must extend a few instructions *prior* to execution reaching the trampoline.  For example, these few instructions might calculate the address of the trampoline, so that entering the trampoline would be pre-ordained a surprisingly long time before execution actually reached the trampoline itself.

The solution, in the form of [Tasks RCU](<https://lwn.net/Articles/607117/>), is to have implicit read-side critical sections that are delimited by voluntary context switches, that is, calls to schedule(), cond_resched(), and synchronize_rcu_tasks(). In addition, transitions to and from userspace execution also delimit tasks-RCU read-side critical sections. Idle tasks are ignored by Tasks RCU, and Tasks Rude RCU may be used to interact with them.

Note well that involuntary context switches are *not* Tasks-RCU quiescent states.  After all, in preemptible kernels, a task executing code in a trampoline might be preempted.  In this case, the Tasks-RCU grace period clearly cannot end until that task resumes and its execution leaves that trampoline.  This means, among other things, that cond_resched() does not provide a Tasks RCU quiescent state.  (Instead, use rcu_softirq_qs() from softirq or rcu_tasks_classic_qs() otherwise.)

The tasks-RCU API is quite compact, consisting only of call_rcu_tasks(), synchronize_rcu_tasks(), and rcu_barrier_tasks(). In `CONFIG_PREEMPTION=n` kernels, trampolines cannot be preempted, so these APIs map to call_rcu(), synchronize_rcu(), and rcu_barrier(), respectively. In `CONFIG_PREEMPTION=y` kernels, trampolines can be preempted, and these three APIs are therefore implemented by separate functions that check for voluntary context switches.

<a id="rst-tasks-rude-rcu"></a>

### Tasks Rude RCU

Some forms of tracing need to wait for all preemption-disabled regions of code running on any online CPU, including those executed when RCU is not watching.  This means that synchronize_rcu() is insufficient, and Tasks Rude RCU must be used instead.  This flavor of RCU does its work by forcing a workqueue to be scheduled on each online CPU, hence the "Rude" moniker.  And this operation is considered to be quite rude by real-time workloads that don't want their `nohz_full` CPUs receiving IPIs and by battery-powered systems that don't want their idle CPUs to be awakened.

Once kernel entry/exit and deep-idle functions have been properly tagged `noinstr`, Tasks RCU can start paying attention to idle tasks (except those that are idle from RCU's perspective) and then Tasks Rude RCU can be removed from the kernel.

The tasks-rude-RCU API is also reader-marking-free and thus quite compact, consisting solely of synchronize_rcu_tasks_rude().

<a id="rst-tasks-trace-rcu"></a>

### Tasks Trace RCU

Some forms of tracing need to sleep in readers, but cannot tolerate SRCU's read-side overhead, which includes a full memory barrier in both srcu_read_lock() and srcu_read_unlock().  This need is handled by a Tasks Trace RCU API implemented as thin wrappers around SRCU-fast, which avoids the read-side memory barriers, at least for architectures that apply noinstr to kernel entry/exit code (or that build with `CONFIG_TASKS_TRACE_RCU_NO_MB=y`.

The tasks-trace-RCU API is also reasonably compact, consisting of rcu_read_lock_trace(), rcu_read_unlock_trace(), rcu_read_lock_trace_held(), call_rcu_tasks_trace(), synchronize_rcu_tasks_trace(), and rcu_barrier_tasks_trace().

<a id="rst-possible-future-changes"></a>

## Possible Future Changes

One of the tricks that RCU uses to attain update-side scalability is to increase grace-period latency with increasing numbers of CPUs. If this becomes a serious problem, it will be necessary to rework the grace-period state machine so as to avoid the need for the additional latency.

RCU disables CPU hotplug in a few places, perhaps most notably in the rcu_barrier() operations. If there is a strong reason to use rcu_barrier() in CPU-hotplug notifiers, it will be necessary to avoid disabling CPU hotplug. This would introduce some complexity, so there had better be a *very* good reason.

The tradeoff between grace-period latency on the one hand and interruptions of other CPUs on the other hand may need to be re-examined. The desire is of course for zero grace-period latency as well as zero interprocessor interrupts undertaken during an expedited grace period operation. While this ideal is unlikely to be achievable, it is quite possible that further improvements can be made.

The multiprocessor implementations of RCU use a combining tree that groups CPUs so as to reduce lock contention and increase cache locality. However, this combining tree does not spread its memory across NUMA nodes nor does it align the CPU groups with hardware features such as sockets or cores. Such spreading and alignment is currently believed to be unnecessary because the hotpath read-side primitives do not access the combining tree, nor does call_rcu() in the common case. If you believe that your architecture needs such spreading and alignment, then your architecture should also benefit from the `rcutree.rcu_fanout_leaf` boot parameter, which can be set to the number of CPUs in a socket, NUMA node, or whatever. If the number of CPUs is too large, use a fraction of the number of CPUs. If the number of CPUs is a large prime number, well, that certainly is an “interesting” architectural choice\! More flexible arrangements might be considered, but only if `rcutree.rcu_fanout_leaf` has proven inadequate, and only if the inadequacy has been demonstrated by a carefully run and realistic system-level workload.

Please note that arrangements that require RCU to remap CPU numbers will require extremely good demonstration of need and full exploration of alternatives.

RCU's various kthreads are reasonably recent additions. It is quite likely that adjustments will be required to more gracefully handle extreme loads. It might also be necessary to be able to relate CPU utilization by RCU's kthreads and softirq handlers to the code that instigated this CPU utilization. For example, RCU callback overhead might be charged back to the originating call_rcu() instance, though probably not in production kernels.

Additional work may be required to provide reasonable forward-progress guarantees under heavy load for grace periods and for callback invocation.

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

## Summary

This document has presented more than two decade's worth of RCU requirements. Given that the requirements keep changing, this will not be the last word on this subject, but at least it serves to get an important subset of the requirements set forth.

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

## Acknowledgments

I am grateful to Steven Rostedt, Lai Jiangshan, Ingo Molnar, Oleg Nesterov, Borislav Petkov, Peter Zijlstra, Boqun Feng, and Andy Lutomirski for their help in rendering this article human readable, and to Michelle Rankin for her support of this effort. Other contributions are acknowledged in the Linux kernel's git archive.

---

# Read the Fscking Papers!

_Peios Kernel / Internals / Read-copy-update (RCU)_

> Kernel reference: Read the Fscking Papers!.

This document describes RCU-related publications, and is followed by
the corresponding bibtex entries.  A number of the publications may
be found at http://www.rdrop.com/users/paulmck/RCU/.  For others, browsers
and search engines will usually find what you are looking for.

The first thing resembling RCU was published in 1980, when Kung and Lehman
\[Kung80\] recommended use of a garbage collector to defer destruction
of nodes in a parallel binary search tree in order to simplify its
implementation.  This works well in environments that have garbage
collectors, but most production garbage collectors incur significant
overhead.

In 1982, Manber and Ladner \[Manber82,Manber84\] recommended deferring
destruction until all threads running at that time have terminated, again
for a parallel binary search tree.  This approach works well in systems
with short-lived threads, such as the K42 research operating system.
However, Linux has long-lived tasks, so more is needed.

In 1986, Hennessy, Osisek, and Seigh \[Hennessy89\] introduced passive
serialization, which is an RCU-like mechanism that relies on the presence
of "quiescent states" in the VM/XA hypervisor that are guaranteed not
to be referencing the data structure.  However, this mechanism was not
optimized for modern computer systems, which is not surprising given
that these overheads were not so expensive in the mid-80s.  Nonetheless,
passive serialization appears to be the first deferred-destruction
mechanism to be used in production.  Furthermore, the relevant patent
has lapsed, so this approach may be used in non-GPL software, if desired.
(In contrast, implementation of RCU is permitted only in software licensed
under either GPL or LGPL.  Sorry!!!)

In 1987, Rashid et al. described lazy TLB-flush \[RichardRashid87a\].
At first glance, this has nothing to do with RCU, but nevertheless
this paper helped inspire the update-side batching used in the later
RCU implementation in DYNIX/ptx.  In 1988, Barbara Liskov published
a description of Argus that noted that use of out-of-date values can
be tolerated in some situations.  Thus, this paper provides some early
theoretical justification for use of stale data.

In 1990, Pugh \[Pugh90\] noted that explicitly tracking which threads
were reading a given data structure permitted deferred free to operate
in the presence of non-terminating threads.  However, this explicit
tracking imposes significant read-side overhead, which is undesirable
in read-mostly situations.  This algorithm does take pains to avoid
write-side contention and parallelize the other write-side overheads by
providing a fine-grained locking design, however, it would be interesting
to see how much of the performance advantage reported in 1990 remains
today.

At about this same time, Andrews \[Andrews91textbook\] described \`\`chaotic
relaxation'', where the normal barriers between successive iterations
of convergent numerical algorithms are relaxed, so that iteration $n$
might use data from iteration $n-1$ or even $n-2$.  This introduces
error, which typically slows convergence and thus increases the number of
iterations required.  However, this increase is sometimes more than made
up for by a reduction in the number of expensive barrier operations,
which are otherwise required to synchronize the threads at the end
of each iteration.  Unfortunately, chaotic relaxation requires highly
structured data, such as the matrices used in scientific programs, and
is thus inapplicable to most data structures in operating-system kernels.

In 1992, Henry (now Alexia) Massalin completed a dissertation advising
parallel programmers to defer processing when feasible to simplify
synchronization \[HMassalinPhD\].  RCU makes extremely heavy use of
this advice.

In 1993, Jacobson \[Jacobson93\] verbally described what is perhaps the
simplest deferred-free technique: simply waiting a fixed amount of time
before freeing blocks awaiting deferred free.  Jacobson did not describe
any write-side changes he might have made in this work using SGI's Irix
kernel.  Aju John published a similar technique in 1995 \[AjuJohn95\].
This works well if there is a well-defined upper bound on the length of
time that reading threads can hold references, as there might well be in
hard real-time systems.  However, if this time is exceeded, perhaps due
to preemption, excessive interrupts, or larger-than-anticipated load,
memory corruption can ensue, with no reasonable means of diagnosis.
Jacobson's technique is therefore inappropriate for use in production
operating-system kernels, except when such kernels can provide hard
real-time response guarantees for all operations.

Also in 1995, Pu et al. \[Pu95a\] applied a technique similar to that of Pugh's
read-side-tracking to permit replugging of algorithms within a commercial
Unix operating system.  However, this replugging permitted only a single
reader at a time.  The following year, this same group of researchers
extended their technique to allow for multiple readers \[Cowan96a\].
Their approach requires memory barriers (and thus pipeline stalls),
but reduces memory latency, contention, and locking overheads.

1995 also saw the first publication of DYNIX/ptx's RCU mechanism
\[Slingwine95\], which was optimized for modern CPU architectures,
and was successfully applied to a number of situations within the
DYNIX/ptx kernel.  The corresponding conference paper appeared in 1998
\[McKenney98\].

In 1999, the Tornado and K42 groups described their "generations"
mechanism, which is quite similar to RCU \[Gamsa99\].  These operating
systems made pervasive use of RCU in place of "existence locks", which
greatly simplifies locking hierarchies and helps avoid deadlocks.

The year 2000 saw an email exchange that would likely have
led to yet another independent invention of something like RCU
\[RustyRussell2000a,RustyRussell2000b\].  Instead, 2001 saw the first
RCU presentation involving Linux \[McKenney01a\] at OLS.  The resulting
abundance of RCU patches was presented the following year \[McKenney02a\],
and use of RCU in dcache was first described that same year \[Linder02a\].

Also in 2002, Michael \[Michael02b,Michael02a\] presented "hazard-pointer"
techniques that defer the destruction of data structures to simplify
non-blocking synchronization (wait-free synchronization, lock-free
synchronization, and obstruction-free synchronization are all examples of
non-blocking synchronization).  The corresponding journal article appeared
in 2004 \[MagedMichael04a\].  This technique eliminates locking, reduces
contention, reduces memory latency for readers, and parallelizes pipeline
stalls and memory latency for writers.  However, these techniques still
impose significant read-side overhead in the form of memory barriers.
Researchers at Sun worked along similar lines in the same timeframe
\[HerlihyLM02\].  These techniques can be thought of as inside-out reference
counts, where the count is represented by the number of hazard pointers
referencing a given data structure rather than the more conventional
counter field within the data structure itself.  The key advantage
of inside-out reference counts is that they can be stored in immortal
variables, thus allowing races between access and deletion to be avoided.

By the same token, RCU can be thought of as a "bulk reference count",
where some form of reference counter covers all reference by a given CPU
or thread during a set timeframe.  This timeframe is related to, but
not necessarily exactly the same as, an RCU grace period.  In classic
RCU, the reference counter is the per-CPU bit in the "bitmask" field,
and each such bit covers all references that might have been made by
the corresponding CPU during the prior grace period.  Of course, RCU
can be thought of in other terms as well.

In 2003, the K42 group described how RCU could be used to create
hot-pluggable implementations of operating-system functions \[Appavoo03a\].
Later that year saw a paper describing an RCU implementation
of System V IPC \[Arcangeli03\] (following up on a suggestion by
Hugh Dickins \[Dickins02a\] and an implementation by Mingming Cao
\[MingmingCao2002IPCRCU\]), and an introduction to RCU in Linux Journal
\[McKenney03a\].

2004 has seen a Linux-Journal article on use of RCU in dcache
\[McKenney04a\], a performance comparison of locking to RCU on several
different CPUs \[McKenney04b\], a dissertation describing use of RCU in a
number of operating-system kernels \[PaulEdwardMcKenneyPhD\], a paper
describing how to make RCU safe for soft-realtime applications \[Sarma04c\],
and a paper describing SELinux performance with RCU \[JamesMorris04b\].

2005 brought further adaptation of RCU to realtime use, permitting
preemption of RCU realtime critical sections \[PaulMcKenney05a,
PaulMcKenney05b\].

2006 saw the first best-paper award for an RCU paper \[ThomasEHart2006a\],
as well as further work on efficient implementations of preemptible
RCU \[PaulEMcKenney2006b\], but priority-boosting of RCU read-side critical
sections proved elusive.  An RCU implementation permitting general
blocking in read-side critical sections appeared \[PaulEMcKenney2006c\],
Robert Olsson described an RCU-protected trie-hash combination
\[RobertOlsson2006a\].

2007 saw the journal version of the award-winning RCU paper from 2006
\[ThomasEHart2007a\], as well as a paper demonstrating use of Promela
and Spin to mechanically verify an optimization to Oleg Nesterov's
QRCU \[PaulEMcKenney2007QRCUspin\], a design document describing
preemptible RCU \[PaulEMcKenney2007PreemptibleRCU\], and the three-part
LWN "What is RCU?" series \[PaulEMcKenney2007WhatIsRCUFundamentally,
PaulEMcKenney2008WhatIsRCUUsage, and PaulEMcKenney2008WhatIsRCUAPI\].

2008 saw a journal paper on real-time RCU \[DinakarGuniguntala2008IBMSysJ\],
a history of how Linux changed RCU more than RCU changed Linux
\[PaulEMcKenney2008RCUOSR\], and a design overview of hierarchical RCU
\[PaulEMcKenney2008HierarchicalRCU\].

2009 introduced user-level RCU algorithms \[PaulEMcKenney2009MaliciousURCU\],
which Mathieu Desnoyers is now maintaining \[MathieuDesnoyers2009URCU\]
\[MathieuDesnoyersPhD\].  TINY\_RCU \[PaulEMcKenney2009BloatWatchRCU\] made
its appearance, as did expedited RCU \[PaulEMcKenney2009expeditedRCU\].
The problem of resizable RCU-protected hash tables may now be on a path
to a solution \[JoshTriplett2009RPHash\].  A few academic researchers are now
using RCU to solve their parallel problems \[HariKannan2009DynamicAnalysisRCU\].

2010 produced a simpler preemptible-RCU implementation
based on TREE\_RCU \[PaulEMcKenney2010SimpleOptRCU\], lockdep-RCU
\[PaulEMcKenney2010LockdepRCU\], another resizable RCU-protected hash
table \[HerbertXu2010RCUResizeHash\] (this one consuming more memory,
but allowing arbitrary changes in hash function, as required for DoS
avoidance in the networking code), realization of the 2009 RCU-protected
hash table with atomic node move \[JoshTriplett2010RPHash\], an update on
the RCU API \[PaulEMcKenney2010RCUAPI\].

2011 marked the inclusion of Nick Piggin's fully lockless dentry search
\[LinusTorvalds2011Linux2:6:38:rc1:NPigginVFS\], an RCU-protected red-black
tree using software transactional memory to protect concurrent updates
(strange, but true!) \[PhilHoward2011RCUTMRBTree\], yet another variant of
RCU-protected resizable hash tables \[Triplett:2011:RPHash\], the 3.0 RCU
trainwreck \[PaulEMcKenney2011RCU3.0trainwreck\], and Neil Brown's "Meet the
Lockers" LWN article \[NeilBrown2011MeetTheLockers\].  Some academic
work looked at debugging uses of RCU \[Seyster:2011:RFA:2075416.2075425\].

In 2012, Josh Triplett received his Ph.D. with his dissertation
covering RCU-protected resizable hash tables and the relationship
between memory barriers and read-side traversal order:  If the updater
is making changes in the opposite direction from the read-side traversal
order, the updater need only execute a memory-barrier instruction,
but if in the same direction, the updater needs to wait for a grace
period between the individual updates \[JoshTriplettPhD\].  Also in 2012,
after seventeen years of attempts, an RCU paper made it into a top-flight
academic journal, IEEE Transactions on Parallel and Distributed Systems
\[MathieuDesnoyers2012URCU\].  A group of researchers in Spain applied
user-level RCU to crowd simulation \[GuillermoVigueras2012RCUCrowd\], and
another group of researchers in Europe produced a formal description of
RCU based on separation logic \[AlexeyGotsman2012VerifyGraceExtended\],
which was published in the 2013 European Symposium on Programming
\[AlexeyGotsman2013ESOPRCU\].

Bibtex Entries

```bibtex
@article{Kung80
,author="H. T. Kung and Q. Lehman"
,title="Concurrent Manipulation of Binary Search Trees"
,Year="1980"
,Month="September"
,journal="ACM Transactions on Database Systems"
,volume="5"
,number="3"
,pages="354-382"
,annotation={
	Use garbage collector to clean up data after everyone is done with it.
	.
	Oldest use of something vaguely resembling RCU that I have found.
	http://portal.acm.org/citation.cfm?id=320619&dl=GUIDE,
	[Viewed December 3, 2007]
}
}
```

```bibtex
@techreport{Manber82
,author="Udi Manber and Richard E. Ladner"
,title="Concurrency Control in a Dynamic Search Structure"
,institution="Department of Computer Science, University of Washington"
,address="Seattle, Washington"
,year="1982"
,number="82-01-01"
,month="January"
,pages="28"
,annotation={
	.
	Superseded by Manber84.
	.
	Describes concurrent AVL tree implementation.  Uses a
	garbage-collection mechanism to handle concurrent use and deletion
	of nodes in the tree, but lacks the summary-of-execution-history
	concept of read-copy locking.
	.
	Keeps full list of processes that were active when a given
	node was to be deleted, and waits until all such processes have
	-terminated- before allowing this node to be reused.  This is
	not described in great detail -- one could imagine using process
	IDs for this if the ID space was large enough that overlapping
	never occurred.
	.
	This restriction makes this algorithm unsuitable for use in
	systems comprised of long-lived processes.  It also produces
	completely unacceptable overhead in systems with large numbers
	of processes.  Finally, it is specific to AVL trees.
	.
	Cites Kung80, so not an independent invention, but the first
	RCU-like usage that does not rely on an automatic garbage
	collector.
}
}
```

```bibtex
@article{Manber84
,author="Udi Manber and Richard E. Ladner"
,title="Concurrency Control in a Dynamic Search Structure"
,Year="1984"
,Month="September"
,journal="ACM Transactions on Database Systems"
,volume="9"
,number="3"
,pages="439-455"
,annotation={
	Describes concurrent AVL tree implementation.  Uses a
	garbage-collection mechanism to handle concurrent use and deletion
	of nodes in the tree, but lacks the summary-of-execution-history
	concept of read-copy locking.
	.
	Keeps full list of processes that were active when a given
	node was to be deleted, and waits until all such processes have
	-terminated- before allowing this node to be reused.  This is
	not described in great detail -- one could imagine using process
	IDs for this if the ID space was large enough that overlapping
	never occurred.
	.
	This restriction makes this algorithm unsuitable for use in
	systems comprised of long-lived processes.  It also produces
	completely unacceptable overhead in systems with large numbers
	of processes.  Finally, it is specific to AVL trees.
}
}
```

```bibtex
@Conference{RichardRashid87a
,Author="Richard Rashid and Avadis Tevanian and Michael Young and
David Golub and Robert Baron and David Black and William Bolosky and
Jonathan Chew"
,Title="Machine-Independent Virtual Memory Management for Paged
Uniprocessor and Multiprocessor Architectures"
,Booktitle="{2\textsuperscript{nd} Symposium on Architectural Support
for Programming Languages and Operating Systems}"
,Publisher="Association for Computing Machinery"
,Month="October"
,Year="1987"
,pages="31-39"
,Address="Palo Alto, CA"
,note="Available:
\url{http://www.cse.ucsc.edu/~randal/221/rashid-machvm.pdf}
[Viewed February 17, 2005]"
,annotation={
	Describes lazy TLB flush, where one waits for each CPU to pass
	through a scheduling-clock interrupt before reusing a given range
	of virtual address.  Does not describe how one determines that
	all CPUs have in fact taken such an interrupt, though there are
	no shortage of straightforward methods for accomplishing this.
	.
	Note that it does not make sense to just wait a fixed amount of
	time, since a given CPU might have interrupts disabled for an
	extended amount of time.
}
}
```

```bibtex
@article{BarbaraLiskov1988ArgusCACM
,author = {Barbara Liskov}
,title = {Distributed programming in {Argus}}
,journal = {Commun. ACM}
,volume = {31}
,number = {3}
,year = {1988}
,issn = {0001-0782}
,pages = {300--312}
,doi = {http://doi.acm.org/10.1145/42392.42399}
,publisher = {ACM}
,address = {New York, NY, USA}
,annotation={
	At the top of page 307: "Conflicts with deposits and withdrawals
	are necessary if the reported total is to be up to date.  They
	could be avoided by having total return a sum that is slightly
	out of date."  Relies on semantics -- approximate numerical
	values sometimes OK.
}
}
```

```bibtex
@techreport{Hennessy89
,author="James P. Hennessy and Damian L. Osisek and Joseph W. {Seigh II}"
,title="Passive Serialization in a Multitasking Environment"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1989"
,number="US Patent 4,809,168 (lapsed)"
,month="February"
,pages="11"
}
```

```bibtex
@techreport{Pugh90
,author="William Pugh"
,title="Concurrent Maintenance of Skip Lists"
,institution="Institute of Advanced Computer Science Studies, Department of Computer Science, University of Maryland"
,address="College Park, Maryland"
,year="1990"
,number="CS-TR-2222.1"
,month="June"
,annotation={
	Concurrent access to skip lists.  Has both weak and strong search.
	Uses concept of ``garbage queue'', but has no real way of cleaning
	the garbage efficiently.
	.
	Appears to be an independent invention of an RCU-like mechanism.
}
}

# Was Adams91, see also syncrefs.bib.
```

```bibtex
@Book{Andrews91textbook
,Author="Gregory R. Andrews"
,title="Concurrent Programming, Principles, and Practices"
,Publisher="Benjamin Cummins"
,Year="1991"
,annotation={
	Has a few paragraphs describing ``chaotic relaxation'', a
	numerical analysis technique that allows multiprocessors to
	avoid synchronization overhead by using possibly-stale data.
	.
	Seems like this is descended from yet another independent
	invention of RCU-like function -- but this is restricted
	in that reclamation is not necessary.
}
}
```

```bibtex
@phdthesis{HMassalinPhD
,author="H. Massalin"
,title="Synthesis: An Efficient Implementation of Fundamental Operating
System Services"
,school="Columbia University"
,address="New York, NY"
,year="1992"
,annotation={
	Mondo optimizing compiler.
	Wait-free stuff.
	Good advice: defer work to avoid synchronization.  See page 90
		(PDF page 106), Section 5.4, fourth bullet point.
}
}
```

```bibtex
@unpublished{Jacobson93
,author="Van Jacobson"
,title="Avoid Read-Side Locking Via Delayed Free"
,year="1993"
,month="September"
,note="private communication"
,annotation={
	Use fixed time delay to approximate grace period.  Very simple,
	but subject to random memory corruption under heavy load.
	.
	Independent invention of RCU-like mechanism.
}
}
```

```bibtex
@Conference{AjuJohn95
,Author="Aju John"
,Title="Dynamic vnodes -- Design and Implementation"
,Booktitle="{USENIX Winter 1995}"
,Publisher="USENIX Association"
,Month="January"
,Year="1995"
,pages="11-23"
,Address="New Orleans, LA"
,note="Available:
\url{https://www.usenix.org/publications/library/proceedings/neworl/full_papers/john.a}
[Viewed October 1, 2010]"
,annotation={
	Age vnodes out of the cache, and have a fixed time set by a kernel
	parameter.  Not clear that all races were in fact correctly handled.
	Used a 20-minute time by default, which would most definitely not
	be suitable during DoS attacks or virus scans.
	.
	Apparently independent invention of RCU-like mechanism.
}
}
```

```bibtex
@conference{Pu95a
,Author = "Calton Pu and Tito Autrey and Andrew Black and Charles Consel and
Crispin Cowan and Jon Inouye and Lakshmi Kethana and Jonathan Walpole and
Ke Zhang"
,Title = "Optimistic Incremental Specialization: Streamlining a Commercial
,Operating System"
,Booktitle = "15\textsuperscript{th} ACM Symposium on
,Operating Systems Principles (SOSP'95)"
,address = "Copper Mountain, CO"
,month="December"
,year="1995"
,pages="314-321"
,annotation={
	Uses a replugger, but with a flag to signal when people are
	using the resource at hand.  Only one reader at a time.
}
}
```

```bibtex
@conference{Cowan96a
,Author = "Crispin Cowan and Tito Autrey and Charles Krasic and
,Calton Pu and Jonathan Walpole"
,Title = "Fast Concurrent Dynamic Linking for an Adaptive Operating System"
,Booktitle = "International Conference on Configurable Distributed Systems
(ICCDS'96)"
,address = "Annapolis, MD"
,month="May"
,year="1996"
,pages="108"
,isbn="0-8186-7395-8"
,annotation={
	Uses a replugger, but with a counter to signal when people are
	using the resource at hand.  Allows multiple readers.
}
}
```

```bibtex
@techreport{Slingwine95
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and Method for Achieving Reduced Overhead Mutual
Exclusion and Maintaining Coherency in a Multiprocessor System
Utilizing Execution History and Thread Monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1995"
,number="US Patent 5,442,758"
,month="August"
,annotation={
	Describes the parallel RCU infrastructure.  Includes NUMA aspect
	(structure of bitmap can reflect bus structure of computer system).
	.
	Another independent invention of an RCU-like mechanism, but the
	"real" RCU this time!
}
}
```

```bibtex
@techreport{Slingwine97
,author="John D. Slingwine and Paul E. McKenney"
,title="Method for Maintaining Data Coherency Using Thread Activity
Summaries in a Multicomputer System"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1997"
,number="US Patent 5,608,893"
,month="March"
,pages="19"
,annotation={
	Describes use of RCU to synchronize data between a pair of
	SMP/NUMA computer systems.
}
}
```

```bibtex
@techreport{Slingwine98
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and Method for Achieving Reduced Overhead Mutual
Exclusion and Maintaining Coherency in a Multiprocessor System
Utilizing Execution History and Thread Monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1998"
,number="US Patent 5,727,209"
,month="March"
,annotation={
	Describes doing an atomic update by copying the data item and
	then substituting it into the data structure.
}
}
```

```bibtex
@Conference{McKenney98
,Author="Paul E. McKenney and John D. Slingwine"
,Title="Read-Copy Update: Using Execution History to Solve Concurrency
Problems"
,Booktitle="{Parallel and Distributed Computing and Systems}"
,Month="October"
,Year="1998"
,pages="509-518"
,Address="Las Vegas, NV"
,annotation={
	Describes and analyzes RCU mechanism in DYNIX/ptx.  Describes
	application to linked list update and log-buffer flushing.
	Defines 'quiescent state'.  Includes both measured and analytic
	evaluation.
	http://www.rdrop.com/users/paulmck/RCU/rclockpdcsproof.pdf
	[Viewed December 3, 2007]
}
}
```

```bibtex
@Conference{Gamsa99
,Author="Ben Gamsa and Orran Krieger and Jonathan Appavoo and Michael Stumm"
,Title="Tornado: Maximizing Locality and Concurrency in a Shared Memory
Multiprocessor Operating System"
,Booktitle="{Proceedings of the 3\textsuperscript{rd} Symposium on
Operating System Design and Implementation}"
,Month="February"
,Year="1999"
,pages="87-100"
,Address="New Orleans, LA"
,annotation={
	Use of RCU-like facility in K42/Tornado.  Another independent
	invention of RCU.
	See especially pages 7-9 (Section 5).
	http://www.usenix.org/events/osdi99/full_papers/gamsa/gamsa.pdf
	[Viewed August 30, 2006]
}
}
```

```bibtex
@unpublished{RustyRussell2000a
,Author="Rusty Russell"
,Title="Re: modular net drivers"
,month="June"
,year="2000"
,day="23"
,note="Available:
\url{http://oss.sgi.com/projects/netdev/archive/2000-06/msg00250.html}
[Viewed April 10, 2006]"
,annotation={
	Proto-RCU proposal from Phil Rumpf and Rusty Russell.
	Yet another independent invention of RCU.
	Outline of algorithm to unload modules...
	.
	Appeared on net-dev mailing list.
}
}
```

```bibtex
@unpublished{RustyRussell2000b
,Author="Rusty Russell"
,Title="Re: modular net drivers"
,month="June"
,year="2000"
,day="24"
,note="Available:
\url{http://oss.sgi.com/projects/netdev/archive/2000-06/msg00254.html}
[Viewed April 10, 2006]"
,annotation={
	Proto-RCU proposal from Phil Rumpf and Rusty Russell.
	.
	Appeared on net-dev mailing list.
}
}
```

```bibtex
@unpublished{McKenney01b
,Author="Paul E. McKenney and Dipankar Sarma"
,Title="Read-Copy Update Mutual Exclusion in {Linux}"
,month="February"
,year="2001"
,note="Available:
\url{http://lse.sourceforge.net/locking/rcu/rcupdate_doc.html}
[Viewed October 18, 2004]"
,annotation={
	Prototypical Linux documentation for RCU.
}
}
```

```bibtex
@techreport{Slingwine01
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and Method for Achieving Reduced Overhead Mutual
Exclusion and Maintaining Coherency in a Multiprocessor System
Utilizing Execution History and Thread Monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2001"
,number="US Patent 6,219,690"
,month="April"
,annotation={
	'Change in mode' aspect of RCU.  Can be thought of as a lazy barrier.
}
}
```

```bibtex
@Conference{McKenney01a
,Author="Paul E. McKenney and Jonathan Appavoo and Andi Kleen and
Orran Krieger and Rusty Russell and Dipankar Sarma and Maneesh Soni"
,Title="Read-Copy Update"
,Booktitle="{Ottawa Linux Symposium}"
,Month="July"
,Year="2001"
,note="Available:
\url{https://kernel.org/doc/ols/2001/read-copy.pdf}
\url{http://www.rdrop.com/users/paulmck/RCU/rclock_OLS.2001.05.01c.pdf}
[Viewed June 23, 2004]"
,annotation={
	Described RCU, and presented some patches implementing and using
	it in the Linux kernel.
}
}
```

```bibtex
@unpublished{McKenney01f
,Author="Paul E. McKenney"
,Title="{RFC:} patch to allow lock-free traversal of lists with insertion"
,month="October"
,year="2001"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=100259266316456&w=2}
[Viewed June 23, 2004]"
,annotation={
	Memory-barrier and Alpha thread.  100 messages, not too bad...
}
}
```

```bibtex
@unpublished{Spraul01
,Author="Manfred Spraul"
,Title="Re: {RFC:} patch to allow lock-free traversal of lists with insertion"
,month="October"
,year="2001"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=100264675012867&w=2}
[Viewed June 23, 2004]"
,annotation={
	Suggested burying memory barriers in Linux's list-manipulation
	primitives.
}
}
```

```bibtex
@unpublished{LinusTorvalds2001a
,Author="Linus Torvalds"
,Title="{Re:} {[Lse-tech]} {Re:} {RFC:} patch to allow lock-free traversal of lists with insertion"
,month="October"
,year="2001"
,note="Available:
\url{https://lore.kernel.org/r/Pine.LNX.4.33.0110131015410.8707-100000@penguin.transmeta.com}
[Viewed August 21, 2004]"
,annotation={
}
}
```

```bibtex
@unpublished{Blanchard02a
,Author="Anton Blanchard"
,Title="some RCU dcache and ratcache results"
,month="March"
,year="2002"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=101637107412972&w=2}
[Viewed October 18, 2004]"
}
```

```bibtex
@conference{Michael02b
,author="Maged M. Michael"
,title="High Performance Dynamic Lock-Free Hash Tables and List-Based Sets"
,Year="2002"
,Month="August"
,booktitle="{Proceedings of the 14\textsuperscript{th} Annual ACM
Symposium on Parallel
Algorithms and Architecture}"
,pages="73-82"
,annotation={
Like the title says...
}
}
```

```bibtex
@Conference{Linder02a
,Author="Hanna Linder and Dipankar Sarma and Maneesh Soni"
,Title="Scalability of the Directory Entry Cache"
,Booktitle="{Ottawa Linux Symposium}"
,Month="June"
,Year="2002"
,pages="289-300"
,annotation={
	Measured scalability of Linux 2.4 kernel's directory-entry cache
	(dcache), and measured some scalability enhancements.
}
}
```

```bibtex
@Conference{McKenney02a
,Author="Paul E. McKenney and Dipankar Sarma and
Andrea Arcangeli and Andi Kleen and Orran Krieger and Rusty Russell"
,Title="Read-Copy Update"
,Booktitle="{Ottawa Linux Symposium}"
,Month="June"
,Year="2002"
,pages="338-367"
,note="Available:
\url{http://www.linux.org.uk/~ajh/ols2002_proceedings.pdf.gz}
[Viewed June 23, 2004]"
,annotation={
	Presented and compared a number of RCU implementations for the
	Linux kernel.
}
}
```

```bibtex
@unpublished{Sarma02a
,Author="Dipankar Sarma"
,Title="specweb99: dcache scalability results"
,month="July"
,year="2002"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=102645767914212&w=2}
[Viewed June 23, 2004]"
,annotation={
	Compare fastwalk and RCU for dcache.  RCU won.
}
}
```

```bibtex
@unpublished{Barbieri02
,Author="Luca Barbieri"
,Title="Re: {[PATCH]} Initial support for struct {vfs\_cred}"
,month="August"
,year="2002"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=103082050621241&w=2}
[Viewed: June 23, 2004]"
,annotation={
	Suggested RCU for vfs\_shared\_cred.
}
}
```

```bibtex
@conference{Michael02a
,author="Maged M. Michael"
,title="Safe Memory Reclamation for Dynamic Lock-Free Objects Using Atomic
Reads and Writes"
,Year="2002"
,Month="August"
,booktitle="{Proceedings of the 21\textsuperscript{st} Annual ACM
Symposium on Principles of Distributed Computing}"
,pages="21-30"
,annotation={
	Each thread keeps an array of pointers to items that it is
	currently referencing.	Sort of an inside-out garbage collection
	mechanism, but one that requires the accessing code to explicitly
	state its needs.  Also requires read-side memory barriers on
	most architectures.
}
}
```

```bibtex
@unpublished{Dickins02a
,author="Hugh Dickins"
,title="Use RCU for System-V IPC"
,year="2002"
,month="October"
,note="private communication"
}
```

```bibtex
@InProceedings{HerlihyLM02
,author={Maurice Herlihy and Victor Luchangco and Mark Moir}
,title="The Repeat Offender Problem: A Mechanism for Supporting Dynamic-Sized,
Lock-Free Data Structures"
,booktitle={Proceedings of 16\textsuperscript{th} International
Symposium on Distributed Computing}
,year=2002
,month="October"
,pages="339-353"
}
```

```bibtex
@unpublished{Sarma02b
,Author="Dipankar Sarma"
,Title="Some dcache\_rcu benchmark numbers"
,month="October"
,year="2002"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=103462075416638&w=2}
[Viewed June 23, 2004]"
,annotation={
	Performance of dcache RCU on kernbench for 16x NUMA-Q and 1x,
	2x, and 4x systems.  RCU does no harm, and helps on 16x.
}
}
```

```bibtex
@unpublished{MingmingCao2002IPCRCU
,Author="Mingming Cao"
,Title="[PATCH]updated ipc lock patch"
,month="October"
,year="2002"
,note="Available:
\url{https://lore.kernel.org/r/3DB86B05.447E7410@us.ibm.com}
[Viewed February 15, 2014]"
,annotation={
	Mingming Cao's patch to introduce RCU to SysV IPC.
}
}
```

```bibtex
@unpublished{LinusTorvalds2003a
,Author="Linus Torvalds"
,Title="Re: {[PATCH]} small fixes in brlock.h"
,month="March"
,year="2003"
,note="Available:
\url{https://lore.kernel.org/r/Pine.LNX.4.44.0303091831560.2129-100000@home.transmeta.com}
[Viewed March 13, 2006]"
,annotation={
	Linus suggests replacing brlock with RCU and/or seqlocks:
	.
	'It's entirely possible that the current user could be replaced
	by RCU and/or seqlocks, and we could get rid of brlocks entirely.'
	.
	Stephen Hemminger responds by replacing them with RCU.
}
}
```

```bibtex
@article{Appavoo03a
,author="J. Appavoo and K. Hui and C. A. N. Soules and R. W. Wisniewski and
D. M. {Da Silva} and O. Krieger and M. A. Auslander and D. J. Edelsohn and
B. Gamsa and G. R. Ganger and P. McKenney and M. Ostrowski and
B. Rosenburg and M. Stumm and J. Xenidis"
,title="Enabling Autonomic Behavior in Systems Software With Hot Swapping"
,Year="2003"
,Month="January"
,journal="IBM Systems Journal"
,volume="42"
,number="1"
,pages="60-76"
,annotation={
	Use of RCU to enable hot-swapping for autonomic behavior in K42.
}
}
```

```bibtex
@unpublished{Seigh03
,author="Joseph W. {Seigh II}"
,title="Read Copy Update"
,Year="2003"
,Month="March"
,note="email correspondence"
,annotation={
	Described the relationship of the VM/XA passive serialization to RCU.
}
}
```

```bibtex
@Conference{Arcangeli03
,Author="Andrea Arcangeli and Mingming Cao and Paul E. McKenney and
Dipankar Sarma"
,Title="Using Read-Copy Update Techniques for {System V IPC} in the
{Linux} 2.5 Kernel"
,Booktitle="Proceedings of the 2003 USENIX Annual Technical Conference
(FREENIX Track)"
,Publisher="USENIX Association"
,year="2003"
,month="June"
,pages="297-310"
,annotation={
	Compared updated RCU implementations for the Linux kernel, and
	described System V IPC use of RCU, including order-of-magnitude
	performance improvements.
	http://www.rdrop.com/users/paulmck/RCU/rcu.FREENIX.2003.06.14.pdf
}
}
```

```bibtex
@Conference{Soules03a
,Author="Craig A. N. Soules and Jonathan Appavoo and Kevin Hui and
Dilma {Da Silva} and Gregory R. Ganger and Orran Krieger and
Michael Stumm and Robert W. Wisniewski and Marc Auslander and
Michal Ostrowski and Bryan Rosenburg and Jimi Xenidis"
,Title="System Support for Online Reconfiguration"
,Booktitle="Proceedings of the 2003 USENIX Annual Technical Conference"
,Publisher="USENIX Association"
,year="2003"
,month="June"
,pages="141-154"
}
```

```bibtex
@article{McKenney03a
,author="Paul E. McKenney"
,title="Using {RCU} in the {Linux} 2.5 Kernel"
,Year="2003"
,Month="October"
,journal="Linux Journal"
,volume="1"
,number="114"
,pages="18-26"
,note="Available:
\url{http://www.linuxjournal.com/article/6993}
[Viewed November 14, 2007]"
,annotation={
	Reader-friendly intro to RCU, with the infamous old-man-and-brat
	cartoon.
}
}
```

```bibtex
@unpublished{Sarma03a
,Author="Dipankar Sarma"
,Title="RCU low latency patches"
,month="December"
,year="2003"
,note="Message ID: 20031222180114.GA2248@in.ibm.com"
,annotation={
	dipankar/ct.2004.03.27/RCUll.2003.12.22.patch
}
}
```

```bibtex
@techreport{Friedberg03a
,author="Stuart A. Friedberg"
,title="Lock-Free Wild Card Search Data Structure and Method"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2003"
,number="US Patent 6,662,184"
,month="December"
,pages="112"
,annotation={
	Applies RCU to a wildcard-search Patricia tree in order to permit
	synchronization-free lookup.  RCU is used to retain removed nodes
	for a grace period before freeing them.
}
}
```

```bibtex
@article{McKenney04a
,author="Paul E. McKenney and Dipankar Sarma and Maneesh Soni"
,title="Scaling dcache with {RCU}"
,Year="2004"
,Month="January"
,journal="Linux Journal"
,volume="1"
,number="118"
,pages="38-46"
,annotation={
	Reader friendly intro to dcache and RCU.
	http://www.linuxjournal.com/node/7124
	[Viewed December 26, 2010]
}
}
```

```bibtex
@Conference{McKenney04b
,Author="Paul E. McKenney"
,Title="{RCU} vs. Locking Performance on Different {CPUs}"
,Booktitle="{linux.conf.au}"
,Month="January"
,Year="2004"
,Address="Adelaide, Australia"
,note="Available:
\url{http://www.linux.org.au/conf/2004/abstracts.html#90}
\url{http://www.rdrop.com/users/paulmck/RCU/lockperf.2004.01.17a.pdf}
[Viewed June 23, 2004]"
,annotation={
	Compares performance of RCU to that of other locking primitives
	over a number of CPUs (x86, Opteron, Itanium, and PPC).
}
}
```

```bibtex
@unpublished{Sarma04a
,Author="Dipankar Sarma"
,Title="{[PATCH]} {RCU} for low latency (experimental)"
,month="March"
,year="2004"
,note="\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=108003746402892&w=2}"
,annotation={
	Head of thread: dipankar/2004.03.23/rcu-low-lat.1.patch
}
}
```

```bibtex
@unpublished{Sarma04b
,Author="Dipankar Sarma"
,Title="Re: {[PATCH]} {RCU} for low latency (experimental)"
,month="March"
,year="2004"
,note="\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=108016474829546&w=2}"
,annotation={
	dipankar/rcuth.2004.03.24/rcu-throttle.patch
}
}
```

```bibtex
@unpublished{Spraul04a
,Author="Manfred Spraul"
,Title="[RFC] 0/5 rcu lock update"
,month="May"
,year="2004"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=108546407726602&w=2}
[Viewed June 23, 2004]"
,annotation={
	Hierarchical-bitmap patch for RCU infrastructure.
}
}
```

```bibtex
@unpublished{Steiner04a
,Author="Jack Steiner"
,Title="Re: [Lse-tech] [RFC, PATCH] 1/5 rcu lock update:
Add per-cpu batch counter"
,month="May"
,year="2004"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=108551764515332&w=2}
[Viewed June 23, 2004]"
,annotation={
	RCU runs reasonably on a 512-CPU SGI using Manfred Spraul's patches,
	which may be found at:
	https://lore.kernel.org/r/40AC9823.6020709@colorfullife.com (split vars into cachelines)
	https://lore.kernel.org/r/Pine.LNX.4.44.0405222141260.11106-100000@dbl.q-ag.de (cpu_quiet() patch)
	https://lore.kernel.org/r/200405250535.i4P5ZJo8017583@dbl.q-ag.de (0/5)
	https://lore.kernel.org/r/200405250535.i4P5ZKAQ017591@dbl.q-ag.de (1/5)
		https://lore.kernel.org/r/20040525203215.GB5127@sgi.com (works for Jack)
	https://lore.kernel.org/r/200405250535.i4P5ZLiR017599@dbl.q-ag.de (2/5)
	https://lore.kernel.org/r/200405250535.i4P5ZMFt017607@dbl.q-ag.de (3/5)
	https://lore.kernel.org/r/200405250535.i4P5ZN6g017615@dbl.q-ag.de (4/5)
	https://lore.kernel.org/r/200405250535.i4P5ZO7I017623@dbl.q-ag.de (5/5)
}
}
```

```bibtex
@Conference{Sarma04c
,Author="Dipankar Sarma and Paul E. McKenney"
,Title="Making {RCU} Safe for Deep Sub-Millisecond Response
Realtime Applications"
,Booktitle="Proceedings of the 2004 USENIX Annual Technical Conference
(FREENIX Track)"
,Publisher="USENIX Association"
,year="2004"
,month="June"
,pages="182-191"
,annotation={
	Describes and compares a number of modifications to the Linux RCU
	implementation that make it friendly to realtime applications.
	https://www.usenix.org/conference/2004-usenix-annual-technical-conference/making-rcu-safe-deep-sub-millisecond-response
	[Viewed July 26, 2012]
}
}
```

```bibtex
@article{MagedMichael04a
,author="Maged M. Michael"
,title="Hazard Pointers: Safe Memory Reclamation for Lock-Free Objects"
,Year="2004"
,Month="June"
,journal="IEEE Transactions on Parallel and Distributed Systems"
,volume="15"
,number="6"
,pages="491-504"
,url="Available:
\url{http://www.research.ibm.com/people/m/michael/ieeetpds-2004.pdf}
[Viewed March 1, 2005]"
,annotation={
	New canonical hazard-pointer citation.
}
}
```

```bibtex
@phdthesis{PaulEdwardMcKenneyPhD
,author="Paul E. McKenney"
,title="Exploiting Deferred Destruction:
An Analysis of Read-Copy-Update Techniques
in Operating System Kernels"
,school="OGI School of Science and Engineering at
Oregon Health and Sciences University"
,year="2004"
,annotation={
	Describes RCU implementations and presents design patterns
	corresponding to common uses of RCU in several operating-system
	kernels.
	http://www.rdrop.com/users/paulmck/RCU/RCUdissertation.2004.07.14e1.pdf
	[Viewed October 15, 2004]
}
}
```

```bibtex
@unpublished{PaulEMcKenney2004rcu:dereference
,Author="Dipankar Sarma"
,Title="{Re: RCU : Abstracted RCU dereferencing [5/5]}"
,month="August"
,year="2004"
,note="Available:
\url{https://lore.kernel.org/r/20040807192424.GF3936@in.ibm.com}
[Viewed June 8, 2010]"
,annotation={
	Introduce rcu_dereference().
}
}
```

```bibtex
@unpublished{JimHouston04a
,Author="Jim Houston"
,Title="{[RFC\&PATCH] Alternative {RCU} implementation}"
,month="August"
,year="2004"
,note="Available:
\url{https://lore.kernel.org/r/1093873222.984.12.camel@new.localdomain}
[Viewed February 17, 2005]"
,annotation={
	Uses active code in rcu_read_lock() and rcu_read_unlock() to
	make RCU happen, allowing RCU to function on CPUs that do not
	receive a scheduling-clock interrupt.
}
}
```

```bibtex
@unpublished{TomHart04a
,Author="Thomas E. Hart"
,Title="Master's Thesis: Applying Lock-free Techniques to the {Linux} Kernel"
,month="October"
,year="2004"
,note="Available:
\url{http://www.cs.toronto.edu/~tomhart/masters_thesis.html}
[Viewed October 15, 2004]"
,annotation={
	Proposes comparing RCU to lock-free methods for the Linux kernel.
}
}
```

```bibtex
@unpublished{Vaddagiri04a
,Author="Srivatsa Vaddagiri"
,Title="Subject: [RFC] Use RCU for tcp\_ehash lookup"
,month="October"
,year="2004"
,note="Available:
\url{http://marc.theaimsgroup.com/?t=109395731700004&r=1&w=2}
[Viewed October 18, 2004]"
,annotation={
	Srivatsa's RCU patch for tcp_ehash lookup.
}
}
```

```bibtex
@unpublished{Thirumalai04a
,Author="Ravikiran Thirumalai"
,Title="Subject: [patchset] Lockfree fd lookup 0 of 5"
,month="October"
,year="2004"
,note="Available:
\url{http://marc.theaimsgroup.com/?t=109144217400003&r=1&w=2}
[Viewed October 18, 2004]"
,annotation={
	Ravikiran's lockfree FD patch.
}
}
```

```bibtex
@unpublished{Thirumalai04b
,Author="Ravikiran Thirumalai"
,Title="Subject: Re: [patchset] Lockfree fd lookup 0 of 5"
,month="October"
,year="2004"
,note="Available:
\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=109152521410459&w=2}
[Viewed October 18, 2004]"
,annotation={
	Ravikiran's lockfree FD patch.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2004rcu:assign:pointer
,Author="Paul E. McKenney"
,Title="{[PATCH 1/3] RCU: \url{rcu_assign_pointer()} removal of memory barriers}"
,month="October"
,year="2004"
,note="Available:
\url{https://lore.kernel.org/r/20041023202723.GA1930@us.ibm.com}
[Viewed June 8, 2010]"
,annotation={
	Introduce rcu_assign_pointer().
}
}
```

```bibtex
@unpublished{JamesMorris04a
,Author="James Morris"
,Title="{[PATCH 2/3] SELinux} scalability - convert {AVC} to {RCU}"
,day="15"
,month="November"
,year="2004"
,note="\url{http://marc.theaimsgroup.com/?l=linux-kernel&m=110054979416004&w=2}"
,annotation={
	James Morris posts Kaigai Kohei's patch to LKML.
	[Viewed December 10, 2004]
	Kaigai's patch is at https://lore.kernel.org/r/200409271057.i8RAvcA1007873@mailsv.bs1.fc.nec.co.jp
}
}
```

```bibtex
@unpublished{JamesMorris04b
,Author="James Morris"
,Title="Recent Developments in {SELinux} Kernel Performance"
,month="December"
,year="2004"
,note="Available:
\url{http://www.livejournal.com/users/james_morris/2153.html}
[Viewed December 10, 2004]"
,annotation={
	RCU helps SELinux performance.  ;-)  Made LWN.
}
}
```

```bibtex
@unpublished{PaulMcKenney2005RCUSemantics
,Author="Paul E. McKenney and Jonathan Walpole"
,Title="{RCU} Semantics: A First Attempt"
,month="January"
,year="2005"
,day="30"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/rcu-semantics.2005.01.30a.pdf}
[Viewed December 6, 2009]"
,annotation={
	Early derivation of RCU semantics.
}
}
```

```bibtex
@unpublished{PaulMcKenney2005e
,Author="Paul E. McKenney"
,Title="Real-Time Preemption and {RCU}"
,month="March"
,year="2005"
,day="17"
,note="Available:
\url{https://lore.kernel.org/r/20050318002026.GA2693@us.ibm.com}
[Viewed September 5, 2005]"
,annotation={
	First posting showing how RCU can be safely adapted for
	preemptible RCU read side critical sections.
}
}
```

```bibtex
@unpublished{EsbenNeilsen2005a
,Author="Esben Neilsen"
,Title="Re: Real-Time Preemption and {RCU}"
,month="March"
,year="2005"
,day="18"
,note="Available:
\url{https://lore.kernel.org/r/Pine.OSF.4.05.10503181336310.2466-100000@da410.phys.au.dk}
[Viewed March 30, 2006]"
,annotation={
	Esben Neilsen suggests read-side suppression of grace-period
	processing for crude-but-workable realtime RCU.  The downside
	is indefinite grace periods...  But this is OK for experimentation
	and testing.
}
}
```

```bibtex
@unpublished{TomHart05a
,Author="Thomas E. Hart and Paul E. McKenney and Angela Demke Brown"
,Title="Efficient Memory Reclamation is Necessary for Fast Lock-Free
Data Structures"
,month="March"
,year="2005"
,note="Available:
\url{ftp://ftp.cs.toronto.edu/csrg-technical-reports/515/}
[Viewed March 4, 2005]"
,annotation={
	Comparison of RCU, QBSR, and EBSR.  RCU wins for read-mostly
	workloads.  ;-)
}
}
```

```bibtex
@unpublished{JonCorbet2005DeprecateSyncKernel
,Author="Jonathan Corbet"
,Title="API change: synchronize_kernel() deprecated"
,month="May"
,day="3"
,year="2005"
,note="Available:
\url{http://lwn.net/Articles/134484/}
[Viewed May 3, 2005]"
,annotation={
	Jon Corbet describes deprecation of synchronize_kernel()
	in favor of synchronize_rcu() and synchronize_sched().
}
}
```

```bibtex
@unpublished{PaulMcKenney05a
,Author="Paul E. McKenney"
,Title="{[RFC]} {RCU} and {CONFIG\_PREEMPT\_RT} progress"
,month="May"
,year="2005"
,note="Available:
\url{https://lore.kernel.org/r/20050510012444.GA3011@us.ibm.com}
[Viewed May 13, 2005]"
,annotation={
	First publication of working lock-based deferred free patches
	for the CONFIG_PREEMPT_RT environment.
}
}
```

```bibtex
@conference{PaulMcKenney05b
,Author="Paul E. McKenney and Dipankar Sarma"
,Title="Towards Hard Realtime Response from the {Linux} Kernel on {SMP} Hardware"
,Booktitle="linux.conf.au 2005"
,month="April"
,year="2005"
,address="Canberra, Australia"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/realtimeRCU.2005.04.23a.pdf}
[Viewed May 13, 2005]"
,annotation={
	Realtime turns into making RCU yet more realtime friendly.
	http://lca2005.linux.org.au/Papers/Paul%20McKenney/Towards%20Hard%20Realtime%20Response%20from%20the%20Linux%20Kernel/LKS.2005.04.22a.pdf
}
}
```

```bibtex
@unpublished{PaulEMcKenneyHomePage
,Author="Paul E. McKenney"
,Title="{Paul} {E.} {McKenney}"
,month="May"
,year="2005"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/}
[Viewed May 25, 2005]"
,annotation={
	Paul McKenney's home page.
}
}
```

```bibtex
@unpublished{PaulEMcKenneyRCUPage
,Author="Paul E. McKenney"
,Title="Read-Copy Update {(RCU)}"
,month="May"
,year="2005"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU}
[Viewed May 25, 2005]"
,annotation={
	Paul McKenney's RCU page.
}
}
```

```bibtex
@unpublished{JosephSeigh2005a
,Author="Joseph Seigh"
,Title="{RCU}+{SMR} (hazard pointers)"
,month="July"
,year="2005"
,note="Personal communication"
,annotation={
	Joe Seigh announcing his atomic-ptr-plus project.
	http://sourceforge.net/projects/atomic-ptr-plus/
}
}
```

```bibtex
@unpublished{JosephSeigh2005b
,Author="Joseph Seigh"
,Title="Lock-free synchronization primitives"
,month="July"
,day="6"
,year="2005"
,note="Available:
\url{http://sourceforge.net/projects/atomic-ptr-plus/}
[Viewed August 8, 2005]"
,annotation={
	Joe Seigh's atomic-ptr-plus project.
}
}
```

```bibtex
@unpublished{PaulMcKenney2005c
,Author="Paul E.McKenney"
,Title="{[RFC,PATCH] RCU} and {CONFIG\_PREEMPT\_RT} sane patch"
,month="August"
,day="1"
,year="2005"
,note="Available:
\url{https://lore.kernel.org/r/20050801171137.GA1754@us.ibm.com}
[Viewed March 14, 2006]"
,annotation={
	First operating counter-based realtime RCU patch posted to LKML.
}
}
```

```bibtex
@unpublished{PaulMcKenney2005d
,Author="Paul E. McKenney"
,Title="Re: [Fwd: Re: [patch] Real-Time Preemption, -RT-2.6.13-rc4-V0.7.52-01]"
,month="August"
,day="8"
,year="2005"
,note="Available:
\url{https://lore.kernel.org/r/20050808144216.GA1307@us.ibm.com}
[Viewed March 14, 2006]"
,annotation={
	First operating counter-based realtime RCU patch posted to LKML,
	but fixed so that various unusual combinations of configuration
	parameters all function properly.
}
}
```

```bibtex
@unpublished{PaulMcKenney2005rcutorture
,Author="Paul E. McKenney"
,Title="{[PATCH]} {RCU} torture testing"
,month="October"
,day="1"
,year="2005"
,note="Available:
\url{https://lore.kernel.org/r/20051001182056.GA1613@us.ibm.com}
[Viewed March 14, 2006]"
,annotation={
	First rcutorture patch.
}
}
```

```bibtex
@unpublished{DavidSMiller2006HashedLocking
,Author="David S. Miller"
,Title="Re: [{PATCH}, {RFC}] {RCU} : {OOM} avoidance and lower latency"
,month="January"
,day="6"
,year="2006"
,note="Available:
\url{https://lore.kernel.org/r/20060106.231054.43576567.davem@davemloft.net}
[Viewed February 29, 2012]"
,annotation={
	David Miller's view on hashed arrays of locks: used to really
	like it, but time he saw an opportunity for this technique,
	something else always proved superior.  Partitioning or RCU.  ;-)
}
}
```

```bibtex
@conference{ThomasEHart2006a
,Author="Thomas E. Hart and Paul E. McKenney and Angela Demke Brown"
,Title="Making Lockless Synchronization Fast: Performance Implications
of Memory Reclamation"
,Booktitle="20\textsuperscript{th} {IEEE} International Parallel and
Distributed Processing Symposium"
,month="April"
,year="2006"
,day="25-29"
,address="Rhodes, Greece"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/hart_ipdps06.pdf}
[Viewed April 28, 2008]"
,annotation={
	Compares QSBR, HPBR, EBR, and lock-free reference counting.
	http://www.cs.toronto.edu/~tomhart/perflab/ipdps06.tgz
}
}
```

```bibtex
@unpublished{NickPiggin2006radixtree
,Author="Nick Piggin"
,Title="[patch 3/3] radix-tree: {RCU} lockless readside"
,month="June"
,day="20"
,year="2006"
,note="Available:
\url{https://lore.kernel.org/r/20060408134707.22479.33814.sendpatchset@linux.site}
[Viewed March 25, 2008]"
,annotation={
	RCU-protected radix tree.
}
}
```

```bibtex
@Conference{PaulEMcKenney2006b
,Author="Paul E. McKenney and Dipankar Sarma and Ingo Molnar and
Suparna Bhattacharya"
,Title="Extending {RCU} for Realtime and Embedded Workloads"
,Booktitle="{Ottawa Linux Symposium}"
,Month="July"
,Year="2006"
,pages="v2 123-138"
,note="Available:
\url{https://kernel.org/doc/ols/2006/ols2006v2-pages-131-146.pdf}
\url{http://www.rdrop.com/users/paulmck/RCU/OLSrtRCU.2006.08.11a.pdf}
[Viewed January 1, 2007]"
,annotation={
	Described how to improve the -rt implementation of realtime RCU.
}
}
```

```bibtex
@unpublished{WikipediaRCU
,Author="Paul E. McKenney and Chris Purcell and Algae and Ben Schumin and
Gaius Cornelius and Qwertyus and Neil Conway and Sbw and Blainster and
Canis Rufus and Zoicon5 and Anome and Hal Eisen"
,Title="Read-Copy Update"
,month="July"
,day="8"
,year="2006"
,note="\url{https://en.wikipedia.org/wiki/Read-copy-update}"
,annotation={
	Wikipedia RCU page as of July 8 2006.
	[Viewed August 21, 2006]
}
}
```

```bibtex
@Conference{NickPiggin2006LocklessPageCache
,Author="Nick Piggin"
,Title="A Lockless Pagecache in Linux---Introduction, Progress, Performance"
,Booktitle="{Ottawa Linux Symposium}"
,Month="July"
,Year="2006"
,pages="v2 249-254"
,note="Available:
\url{https://kernel.org/doc/ols/2006/ols2006v2-pages-249-262.pdf}
[Viewed January 11, 2009]"
,annotation={
	Uses RCU-protected radix tree for a lockless page cache.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2006c
,Author="Paul E. McKenney"
,Title="Sleepable {RCU}"
,month="October"
,day="9"
,year="2006"
,note="Available:
\url{http://lwn.net/Articles/202847/}
Revised:
\url{http://www.rdrop.com/users/paulmck/RCU/srcu.2007.01.14a.pdf}
[Viewed August 21, 2006]"
,annotation={
	LWN article introducing SRCU.
}
}
```

```bibtex
@unpublished{RobertOlsson2006a
,Author="Robert Olsson and Stefan Nilsson"
,Title="{TRASH}: A dynamic {LC}-trie and hash data structure"
,month="August"
,day="18"
,year="2006"
,note="\url{http://www.nada.kth.se/~snilsson/publications/TRASH/trash.pdf}"
,annotation={
	RCU-protected dynamic trie-hash combination.
	[Viewed March 4, 2011]
}
}
```

```bibtex
@unpublished{ChristophHellwig2006RCU2SRCU
,Author="Christoph Hellwig"
,Title="Re: {[-mm PATCH 1/4]} {RCU}: split classic rcu"
,month="September"
,day="28"
,year="2006"
,note="Available:
\url{https://lore.kernel.org/r/20060928142616.GA20185@infradead.org}
[Viewed March 27, 2008]"
}
```

```bibtex
@unpublished{PaulEMcKenneyRCUusagePage
,Author="Paul E. McKenney"
,Title="{RCU} {Linux} Usage"
,month="October"
,year="2006"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/linuxusage.html}
[Viewed January 14, 2007]"
,annotation={
	Paul McKenney's RCU page showing graphs plotting Linux-kernel
	usage of RCU.
}
}
```

```bibtex
@unpublished{PaulEMcKenneyRCUusageRawDataPage
,Author="Paul E. McKenney"
,Title="Read-Copy Update {(RCU)} Usage in {Linux} Kernel"
,month="October"
,year="2006"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/linuxusage/rculocktab.html}
[Viewed January 14, 2007]"
,annotation={
	Paul McKenney's RCU page showing Linux usage of RCU in tabular
	form, with links to corresponding cscope databases.
}
}
```

```bibtex
@unpublished{GauthamShenoy2006RCUrwlock
,Author="Gautham R. Shenoy"
,Title="[PATCH 4/5] lock\_cpu\_hotplug: Redesign - Lightweight implementation of lock\_cpu\_hotplug"
,month="October"
,year="2006"
,day=26
,note="Available:
\url{https://lore.kernel.org/r/20061026105731.GE11803@in.ibm.com}
[Viewed January 26, 2009]"
,annotation={
	RCU-based reader-writer lock that allows readers to proceed with
	no memory barriers or atomic instruction in absence of writers.
	If writer do show up, readers must of course wait as required by
	the semantics of reader-writer locking.  This is a recursive
	lock.
}
}
```

```bibtex
@unpublished{JensAxboe2006SlowSRCU
,Author="Jens Axboe"
,Title="Re: [patch] cpufreq: mark \url{cpufreq_tsc()} as
\url{core_initcall_sync}"
,month="November"
,year="2006"
,day=17
,note="Available:
\url{https://lore.kernel.org/r/20061117092925.GT7164@kernel.dk}
[Viewed May 28, 2007]"
,annotation={
	SRCU's grace periods are too slow for Jens, even after a
	factor-of-three speedup.
	Sped-up version of SRCU at https://lore.kernel.org/r/20061118002845.GF2632@us.ibm.com.
}
}
```

```bibtex
@unpublished{OlegNesterov2006QRCU
,Author="Oleg Nesterov"
,Title="Re: [patch] cpufreq: mark {\tt cpufreq\_tsc()} as
{\tt core\_initcall\_sync}"
,month="November"
,year="2006"
,day=19
,note="Available:
\url{https://lore.kernel.org/r/20061119190027.GA3676@oleg}
[Viewed May 28, 2007]"
,annotation={
	First cut of QRCU.  Expanded/corrected versions followed.
	Used to be OlegNesterov2007QRCU, now time-corrected.
}
}
```

```bibtex
@unpublished{OlegNesterov2006aQRCU
,Author="Oleg Nesterov"
,Title="Re: [RFC, PATCH 1/2] qrcu: {"quick"} srcu implementation"
,month="November"
,year="2006"
,day=30
,note="Available:
\url{https://lore.kernel.org/r/20061130015714.GC1350@oleg}
[Viewed November 26, 2008]"
,annotation={
	Expanded/corrected version of QRCU.
	Used to be OlegNesterov2007aQRCU, now time-corrected.
}
}
```

```bibtex
@unpublished{EvgeniyPolyakov2006RCUslowdown
,Author="Evgeniy Polyakov"
,Title="Badness in postponing work"
,month="December"
,year="2006"
,day=05
,note="Available:
\url{http://www.ioremap.net/node/41}
[Viewed October 28, 2008]"
,annotation={
	Using RCU as a pure delay leads to a 2.5x slowdown in skbs in
	the Linux kernel.
}
}
```

```bibtex
@inproceedings{ChrisMatthews2006ClusteredObjectsRCU
,author = {Matthews, Chris and Coady, Yvonne and Appavoo, Jonathan}
,title = {Portability events: a programming model for scalable system infrastructures}
,booktitle = {PLOS '06: Proceedings of the 3rd workshop on Programming languages and operating systems}
,year = {2006}
,isbn = {1-59593-577-0}
,pages = {11}
,location = {San Jose, California}
,doi = {http://doi.acm.org/10.1145/1215995.1216006}
,publisher = {ACM}
,address = {New York, NY, USA}
,annotation={
	Uses K42's RCU-like functionality to manage clustered-object
	lifetimes.
}
}
```

```bibtex
@article{DilmaDaSilva2006K42
,author = {Silva, Dilma Da and Krieger, Orran and Wisniewski, Robert W. and Waterland, Amos and Tam, David and Baumann, Andrew}
,title = {K42: an infrastructure for operating system research}
,journal = {SIGOPS Oper. Syst. Rev.}
,volume = {40}
,number = {2}
,year = {2006}
,issn = {0163-5980}
,pages = {34--42}
,doi = {http://doi.acm.org/10.1145/1131322.1131333}
,publisher = {ACM}
,address = {New York, NY, USA}
,annotation={
	Describes relationship of K42 generations to RCU.
}
}

# CoreyMinyard2007list_splice_rcu
```

```bibtex
@unpublished{CoreyMinyard2007list:splice:rcu
,Author="Corey Minyard and Paul E. McKenney"
,Title="{[PATCH]} add an {RCU} version of list splicing"
,month="January"
,year="2007"
,day=3
,note="Available:
\url{https://lore.kernel.org/r/20070103152738.GA16063@localdomain}
[Viewed May 28, 2007]"
,annotation={
	Patch for list_splice_rcu().
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007rcubarrier
,Author="Paul E. McKenney"
,Title="{RCU} and Unloadable Modules"
,month="January"
,day="14"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/217484/}
[Viewed November 22, 2007]"
,annotation={
	LWN article introducing the rcu_barrier() primitive.
}
}
```

```bibtex
@unpublished{PeterZijlstra2007SyncBarrier
,Author="Peter Zijlstra and Ingo Molnar"
,Title="{[PATCH 3/7]} barrier: a scalable synchonisation barrier"
,month="January"
,year="2007"
,day=28
,note="Available:
\url{https://lore.kernel.org/r/20070128120509.719287000@programming.kicks-ass.net}
[Viewed March 27, 2008]"
,annotation={
	RCU-like implementation for frequent updaters and rare readers(!).
	Subsumed into QRCU.  Maybe...
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007BoostRCU
,Author="Paul E. McKenney"
,Title="Priority-Boosting {RCU} Read-Side Critical Sections"
,month="February"
,day="5"
,year="2007"
,note="\url{http://lwn.net/Articles/220677/}"
,annotation={
	LWN article introducing RCU priority boosting.
	Revised:
	http://www.rdrop.com/users/paulmck/RCU/RCUbooststate.2007.04.16a.pdf
	[Viewed September 7, 2007]
}
}
```

```bibtex
@unpublished{PaulMcKenney2007QRCUpatch
,Author="Paul E. McKenney"
,Title="{[PATCH]} {QRCU} with lockless fastpath"
,month="February"
,year="2007"
,day=24
,note="Available:
\url{https://lore.kernel.org/r/20070225062349.GA17468@linux.vnet.ibm.com}
[Viewed March 27, 2008]"
,annotation={
	Patch for QRCU supplying lock-free fast path.
}
}
```

```bibtex
@article{JonathanAppavoo2007K42RCU
,author = {Appavoo, Jonathan and Silva, Dilma Da and Krieger, Orran and Auslander, Marc and Ostrowski, Michal and Rosenburg, Bryan and Waterland, Amos and Wisniewski, Robert W. and Xenidis, Jimi and Stumm, Michael and Soares, Livio}
,title = {Experience distributing objects in an SMMP OS}
,journal = {ACM Trans. Comput. Syst.}
,volume = {25}
,number = {3}
,year = {2007}
,issn = {0734-2071}
,pages = {6/1--6/52}
,doi = {http://doi.acm.org/10.1145/1275517.1275518}
,publisher = {ACM}
,address = {New York, NY, USA}
,annotation={
	Role of RCU in K42.
}
}
```

```bibtex
@conference{RobertOlsson2007Trash
,Author="Robert Olsson and Stefan Nilsson"
,Title="{TRASH}: A dynamic {LC}-trie and hash data structure"
,booktitle="Workshop on High Performance Switching and Routing (HPSR'07)"
,month="May"
,year="2007"
,note="Available:
\url{http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4281239}
[Viewed October 1, 2010]"
,annotation={
	RCU-protected dynamic trie-hash combination.
}
}
```

```bibtex
@conference{PeterZijlstra2007ConcurrentPagecacheRCU
,Author="Peter Zijlstra"
,Title="Concurrent Pagecache"
,Booktitle="Linux Symposium"
,month="June"
,year="2007"
,address="Ottawa, Canada"
,note="Available:
\url{http://ols.108.redhat.com/2007/Reprints/zijlstra-Reprint.pdf}
[Viewed April 14, 2008]"
,annotation={
	Page-cache modifications permitting RCU readers and concurrent
	updates.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007whatisRCU
,Author="Paul E. McKenney"
,Title="What is {RCU}?"
,year="2007"
,month="07"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/whatisRCU.html}
[Viewed July 6, 2007]"
,annotation={
	Describes RCU in Linux kernel.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007QRCUspin
,Author="Paul E. McKenney"
,Title="Using {Promela} and {Spin} to verify parallel algorithms"
,month="August"
,day="1"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/243851/}
[Viewed September 8, 2007]"
,annotation={
	LWN article describing Promela and spin, and also using Oleg
	Nesterov's QRCU as an example (with Paul McKenney's fastpath).
	Merged patch at: https://lore.kernel.org/r/20070225062349.GA17468@linux.vnet.ibm.com
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007WG21DDOatomics
,Author="Paul E. McKenney and Hans-J. Boehm and Lawrence Crowl"
,Title="C++ Data-Dependency Ordering: Atomics and Memory Model"
,month="August"
,day="3"
,year="2007"
,note="Available:
\url{http://open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2664.htm}
[Viewed December 7, 2009]"
,annotation={
	RCU for C++, parts 1 and 2.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007WG21DDOannotation
,Author="Paul E. McKenney and Lawrence Crowl"
,Title="C++ Data-Dependency Ordering: Function Annotation"
,month="September"
,day="18"
,year="2008"
,note="Available:
\url{http://open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2782.htm}
[Viewed December 7, 2009]"
,annotation={
	RCU for C++, part 2, updated many times.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007PreemptibleRCUPatch
,Author="Paul E. McKenney"
,Title="[PATCH RFC 0/9] {RCU}: Preemptible {RCU}"
,month="September"
,day="10"
,year="2007"
,note="Available:
\url{https://lore.kernel.org/r/20070910183004.GA3299@linux.vnet.ibm.com}
[Viewed October 25, 2007]"
,annotation={
	Final patch for preemptible RCU to -rt.  (Later patches were
	to mainline, eventually incorporated.)
}
}
```

```bibtex
@unpublished{PaulEMcKenney2007PreemptibleRCU
,Author="Paul E. McKenney"
,Title="The design of preemptible read-copy-update"
,month="October"
,day="8"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/253651/}
[Viewed October 25, 2007]"
,annotation={
	LWN article describing the design of preemptible RCU.
}
}
```

```bibtex
@article{ThomasEHart2007a
,Author="Thomas E. Hart and Paul E. McKenney and Angela Demke Brown and Jonathan Walpole"
,Title="Performance of memory reclamation for lockless synchronization"
,journal="J. Parallel Distrib. Comput."
,volume={67}
,number="12"
,year="2007"
,issn="0743-7315"
,pages="1270--1285"
,doi="http://dx.doi.org/10.1016/j.jpdc.2007.04.010"
,publisher="Academic Press, Inc."
,address="Orlando, FL, USA"
,annotation={
	Compares QSBR, HPBR, EBR, and lock-free reference counting.
	Journal version of ThomasEHart2006a.
}
}

# MathieuDesnoyers2007call_rcu_schedNeeded
```

```bibtex
@unpublished{MathieuDesnoyers2007call:rcu:schedNeeded
,Author="Mathieu Desnoyers"
,Title="Re: [patch 1/2] {Linux} Kernel Markers - Support Multiple Probes"
,month="December"
,day="20"
,year="2007"
,note="Available:
\url{https://lore.kernel.org/r/20071220142540.GB22523@Krystal}
[Viewed March 27, 2008]"
,annotation={
	Request for call_rcu_sched() and rcu_barrier_sched().
}
}


########################################################################
#
#	"What is RCU?" LWN series.
#
#	http://lwn.net/Articles/262464/ (What is RCU, Fundamentally?)
#	http://lwn.net/Articles/263130/ (What is RCU's Usage?)
#	http://lwn.net/Articles/264090/ (What is RCU's API?)
```

```bibtex
@unpublished{PaulEMcKenney2007WhatIsRCUFundamentally
,Author="Paul E. McKenney and Jonathan Walpole"
,Title="What is {RCU}, Fundamentally?"
,month="December"
,day="17"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/262464/}
[Viewed December 27, 2007]"
,annotation={
	Lays out the three basic components of RCU: (1) publish-subscribe,
	(2) wait for pre-existing readers to complete, and (2) maintain
	multiple versions.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2008WhatIsRCUUsage
,Author="Paul E. McKenney"
,Title="What is {RCU}? Part 2: Usage"
,month="January"
,day="4"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/263130/}
[Viewed January 4, 2008]"
,annotation={
	Lays out six uses of RCU:
	1. RCU is a Reader-Writer Lock Replacement
	2. RCU is a Restricted Reference-Counting Mechanism
	3. RCU is a Bulk Reference-Counting Mechanism
	4. RCU is a Poor Man's Garbage Collector
	5. RCU is a Way of Providing Existence Guarantees
	6. RCU is a Way of Waiting for Things to Finish
}
}
```

```bibtex
@unpublished{PaulEMcKenney2008WhatIsRCUAPI
,Author="Paul E. McKenney"
,Title="{RCU} part 3: the {RCU} {API}"
,month="January"
,day="17"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/264090/}
[Viewed January 10, 2008]"
,annotation={
	Gives an overview of the Linux-kernel RCU API and a brief annotated RCU
	bibliography.
}
}

#
#	"What is RCU?" LWN series.
#
########################################################################
```

```bibtex
@unpublished{SteveRostedt2008dyntickRCUpatch
,Author="Steven Rostedt and Paul E. McKenney"
,Title="{[PATCH]} add support for dynamic ticks and preempt rcu"
,month="January"
,day="29"
,year="2008"
,note="Available:
\url{https://lore.kernel.org/r/Pine.LNX.4.58.0801291113350.20371@gandalf.stny.rr.com}
[Viewed March 27, 2008]"
,annotation={
	Patch that prevents preemptible RCU from unnecessarily waking
	up dynticks-idle CPUs.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2008LKMLDependencyOrdering
,Author="Paul E. McKenney"
,Title="Re: [PATCH 02/22 -v7] Add basic support for gcc profiler instrumentation"
,month="February"
,day="1"
,year="2008"
,note="Available:
\url{https://lore.kernel.org/r/20080202214124.GA28612@linux.vnet.ibm.com}
[Viewed October 18, 2008]"
,annotation={
	Explanation of compilers violating dependency ordering.
}
}
```

```bibtex
@Conference{PaulEMcKenney2008Beijing
,Author="Paul E. McKenney"
,Title="Introducing Technology Into {Linux} Or:
Introducing your technology Into {Linux} will require introducing a
lot of {Linux} into your technology!!!"
,Booktitle="2008 Linux Developer Symposium - China"
,Publisher="OSS China"
,Month="February"
,Year="2008"
,Address="Beijing, China"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/TechIntroLinux.2008.02.19a.pdf}
[Viewed August 12, 2008]"
}
```

```bibtex
@unpublished{PaulEMcKenney2008dynticksRCU
,Author="Paul E. McKenney and Steven Rostedt"
,Title="Integrating and Validating dynticks and Preemptable RCU"
,month="April"
,day="24"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/279077/}
[Viewed April 24, 2008]"
,annotation={
	Describes use of Promela and Spin to validate (and fix!) the
	dynticks/RCU interface.
}
}
```

```bibtex
@article{DinakarGuniguntala2008IBMSysJ
,author="D. Guniguntala and P. E. McKenney and J. Triplett and J. Walpole"
,title="The read-copy-update mechanism for supporting real-time applications on shared-memory multiprocessor systems with {Linux}"
,Year="2008"
,Month="May"
,journal="IBM Systems Journal"
,volume="47"
,number="2"
,pages="221-236"
,annotation={
	RCU, realtime RCU, sleepable RCU, performance.
	http://www.research.ibm.com/journal/sj/472/guniguntala.pdf
	[Viewed April 24, 2008]
}
}
```

```bibtex
@unpublished{LaiJiangshan2008NewClassicAlgorithm
,Author="Lai Jiangshan"
,Title="[{RFC}][{PATCH}] rcu classic: new algorithm for callbacks-processing"
,month="June"
,day="3"
,year="2008"
,note="Available:
\url{https://lore.kernel.org/r/4844BE83.5010401@cn.fujitsu.com}
[Viewed December 10, 2008]"
,annotation={
	Updated RCU classic algorithm.  Introduced multi-tailed list
	for RCU callbacks and also pulling common code into
	__call_rcu().
}
}
```

```bibtex
@article{PaulEMcKenney2008RCUOSR
,author="Paul E. McKenney and Jonathan Walpole"
,title="Introducing technology into the {Linux} kernel: a case study"
,Year="2008"
,journal="SIGOPS Oper. Syst. Rev."
,volume="42"
,number="5"
,pages="4--17"
,issn="0163-5980"
,doi={http://doi.acm.org/10.1145/1400097.1400099}
,publisher="ACM"
,address="New York, NY, USA"
,annotation={
	Linux changed RCU to a far greater degree than RCU has changed Linux.
	http://portal.acm.org/citation.cfm?doid=1400097.1400099
}
}
```

```bibtex
@unpublished{ManfredSpraul2008StateMachineRCU
,Author="Manfred Spraul"
,Title="[{RFC}, {PATCH}] state machine based rcu"
,month="August"
,day="21"
,year="2008"
,note="Available:
\url{https://lore.kernel.org/r/48AD8969.7060900@colorfullife.com}
[Viewed December 8, 2008]"
,annotation={
	State-based RCU.  One key thing that this patch does is to
	separate the dynticks handling of NMIs and IRQs.
}
}
```

```bibtex
@unpublished{ManfredSpraul2008dyntickIRQNMI
,Author="Manfred Spraul"
,Title="Re: [{RFC}, {PATCH}] v4 scalable classic {RCU} implementation"
,month="September"
,day="6"
,year="2008"
,note="Available:
\url{https://lore.kernel.org/r/48C2B1D2.5070801@colorfullife.com}
[Viewed December 8, 2008]"
,annotation={
	Manfred notes a fix required to my attempt to separate irq
	and NMI processing for hierarchical RCU's dynticks interface.
}
}

# Was PaulEMcKenney2011cyclicRCU
```

```bibtex
@techreport{PaulEMcKenney2008cyclicRCU
,author="Paul E. McKenney"
,title="Efficient Support of Consistent Cyclic Search With Read-Copy Update"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2008"
,number="US Patent 7,426,511"
,month="September"
,pages="23"
,annotation={
	Maintains an additional level of indirection to allow
	readers to confine themselves to the desired snapshot of the
	data structure.  Only permits one update at a time.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2008HierarchicalRCU
,Author="Paul E. McKenney"
,Title="Hierarchical {RCU}"
,month="November"
,day="3"
,year="2008"
,note="\url{http://lwn.net/Articles/305782/}"
,annotation={
	RCU with combining-tree-based grace-period detection,
	permitting it to handle thousands of CPUs.
	[Viewed November 6, 2008]
}
}
```

```bibtex
@unpublished{PaulEMcKenney2009BloatwatchRCU
,Author="Paul E. McKenney"
,Title="Re: [PATCH fyi] RCU: the bloatwatch edition"
,month="January"
,day="14"
,year="2009"
,note="Available:
\url{https://lore.kernel.org/r/20090114202044.GJ6734@linux.vnet.ibm.com}
[Viewed January 15, 2009]"
,annotation={
	Small-footprint implementation of RCU for uniprocessor
	embedded applications -- and also for exposition purposes.
}
}
```

```bibtex
@conference{PaulEMcKenney2009MaliciousURCU
,Author="Paul E. McKenney"
,Title="Using a Malicious User-Level {RCU} to Torture {RCU}-Based Algorithms"
,Booktitle="linux.conf.au 2009"
,month="January"
,year="2009"
,address="Hobart, Australia"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/urcutorture.2009.01.22a.pdf}
[Viewed February 2, 2009]"
,annotation={
	Realtime RCU and torture-testing RCU uses.
}
}
```

```bibtex
@unpublished{MathieuDesnoyers2009URCU
,Author="Mathieu Desnoyers"
,Title="[{RFC} git tree] Userspace {RCU} (urcu) for {Linux}"
,month="February"
,day="5"
,year="2009"
,note="\url{http://lttng.org/urcu}"
,annotation={
	Mathieu Desnoyers's user-space RCU implementation.
	git://lttng.org/userspace-rcu.git
	http://lttng.org/cgi-bin/gitweb.cgi?p=userspace-rcu.git
	http://lttng.org/urcu
	https://lore.kernel.org/r/20090206030543.GB8560@Krystal
}
}
```

```bibtex
@unpublished{PaulEMcKenney2009LWNBloatWatchRCU
,Author="Paul E. McKenney"
,Title="{RCU}: The {Bloatwatch} Edition"
,month="March"
,day="17"
,year="2009"
,note="Available:
\url{http://lwn.net/Articles/323929/}
[Viewed March 20, 2009]"
,annotation={
	Uniprocessor assumptions allow simplified RCU implementation.
}
}
```

```bibtex
@unpublished{EvgeniyPolyakov2009EllipticsNetwork
,Author="Evgeniy Polyakov"
,Title="The Elliptics Network"
,month="April"
,day="17"
,year="2009"
,note="Available:
\url{http://www.ioremap.net/projects/elliptics}
[Viewed April 30, 2009]"
,annotation={
	Distributed hash table with transactions, using elliptic
	hash functions to distribute data.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2009expeditedRCU
,Author="Paul E. McKenney"
,Title="[{PATCH} -tip 0/3] expedited 'big hammer' {RCU} grace periods"
,month="June"
,day="25"
,year="2009"
,note="Available:
\url{https://lore.kernel.org/r/20090625160706.GA9467@linux.vnet.ibm.com}
[Viewed August 16, 2009]"
,annotation={
	First posting of expedited RCU to be accepted into -tip.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2009fastRTRCU
,Author="Paul E. McKenney"
,Title="[{PATCH} {RFC} -tip 0/4] {RCU} cleanups and simplified preemptable {RCU}"
,month="July"
,day="23"
,year="2009"
,note="Available:
\url{https://lore.kernel.org/r/20090724001429.GA17374@linux.vnet.ibm.com}
[Viewed August 15, 2009]"
,annotation={
	First posting of simple and fast preemptible RCU.
}
}
```

```bibtex
@unpublished{JoshTriplett2009RPHash
,Author="Josh Triplett"
,Title="Scalable concurrent hash tables via relativistic programming"
,month="September"
,year="2009"
,note="Linux Plumbers Conference presentation"
,annotation={
	RP fun with hash tables.
	Superseded by JoshTriplett2010RPHash
}
}
```

```bibtex
@phdthesis{MathieuDesnoyersPhD
, title  = "Low-Impact Operating System Tracing"
, author = "Mathieu Desnoyers"
, school = "Ecole Polytechnique de Montr\'{e}al"
, month  = "December"
, year   = 2009
,note="Available:
\url{http://www.lttng.org/pub/thesis/desnoyers-dissertation-2009-12.pdf}
[Viewed December 9, 2009]"
,annotation={
	Chapter 6 (page 97) covers user-level RCU.
}
}
```

```bibtex
@unpublished{RelativisticProgrammingWiki
,Author="Josh Triplett and Paul E. McKenney and Jonathan Walpole"
,Title="Relativistic Programming"
,month="September"
,year="2009"
,note="Available:
\url{http://wiki.cs.pdx.edu/rp/}
[Viewed December 9, 2009]"
,annotation={
	Main Relativistic Programming Wiki.
}
}
```

```bibtex
@conference{PaulEMcKenney2009DeterministicRCU
,Author="Paul E. McKenney"
,Title="Deterministic Synchronization in Multicore Systems: the Role of {RCU}"
,Booktitle="Eleventh Real Time Linux Workshop"
,month="September"
,year="2009"
,address="Dresden, Germany"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/realtime/paper/DetSyncRCU.2009.08.18a.pdf}
[Viewed January 14, 2009]"
}
```

```bibtex
@unpublished{PaulEMcKenney2009HuntingHeisenbugs
,Author="Paul E. McKenney"
,Title="Hunting Heisenbugs"
,month="November"
,year="2009"
,day="1"
,note="Available:
\url{http://paulmck.livejournal.com/14639.html}
[Viewed June 4, 2010]"
,annotation={
	Day-one bug in Tree RCU that took forever to track down.
}
}
```

```bibtex
@unpublished{MathieuDesnoyers2009defer:rcu
,Author="Mathieu Desnoyers"
,Title="Kernel RCU: shrink the size of the struct rcu\_head"
,month="December"
,year="2009"
,note="Available:
\url{https://lore.kernel.org/r/20091018232918.GA7385@Krystal}
[Viewed December 29, 2009]"
,annotation={
	Mathieu proposed defer_rcu() with fixed-size per-thread pool
	of RCU callbacks.
}
}
```

```bibtex
@unpublished{MathieuDesnoyers2009VerifPrePub
,Author="Mathieu Desnoyers and Paul E. McKenney and Michel R. Dagenais"
,Title="Multi-Core Systems Modeling for Formal Verification of Parallel Algorithms"
,month="December"
,year="2009"
,note="Submitted to IEEE TPDS"
,annotation={
	OOMem model for Mathieu's user-level RCU mechanical proof of
	correctness.
}
}
```

```bibtex
@unpublished{MathieuDesnoyers2009URCUPrePub
,Author="Mathieu Desnoyers and Paul E. McKenney and Alan Stern and Michel R. Dagenais and Jonathan Walpole"
,Title="User-Level Implementations of Read-Copy Update"
,month="December"
,year="2010"
,url={\url{http://www.computer.org/csdl/trans/td/2012/02/ttd2012020375-abs.html}}
,annotation={
	RCU overview, desiderata, semi-formal semantics, user-level RCU
	usage scenarios, three classes of RCU implementation, wait-free
	RCU updates, RCU grace-period batching, update overhead,
	http://www.rdrop.com/users/paulmck/RCU/urcu-main-accepted.2011.08.30a.pdf
	http://www.rdrop.com/users/paulmck/RCU/urcu-supp-accepted.2011.08.30a.pdf
	Superseded by MathieuDesnoyers2012URCU.
}
}
```

```bibtex
@inproceedings{HariKannan2009DynamicAnalysisRCU
,author = {Kannan, Hari}
,title = {Ordering decoupled metadata accesses in multiprocessors}
,booktitle = {MICRO 42: Proceedings of the 42nd Annual IEEE/ACM International Symposium on Microarchitecture}
,year = {2009}
,isbn = {978-1-60558-798-1}
,pages = {381--390}
,location = {New York, New York}
,doi = {http://doi.acm.org/10.1145/1669112.1669161}
,publisher = {ACM}
,address = {New York, NY, USA}
,annotation={
	Uses RCU to protect metadata used in dynamic analysis.
}
}
```

```bibtex
@conference{PaulEMcKenney2010SimpleOptRCU
,Author="Paul E. McKenney"
,Title="Simplicity Through Optimization"
,Booktitle="linux.conf.au 2010"
,month="January"
,year="2010"
,address="Wellington, New Zealand"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/SimplicityThruOptimization.2010.01.21f.pdf}
[Viewed October 10, 2010]"
,annotation={
	TREE_PREEMPT_RCU optimizations greatly simplified the old
	PREEMPT_RCU implementation.
}
}
```

```bibtex
@unpublished{PaulEMcKenney2010LockdepRCU
,Author="Paul E. McKenney"
,Title="Lockdep-{RCU}"
,month="February"
,year="2010"
,day="1"
,note="\url{https://lwn.net/Articles/371986/}"
,annotation={
	CONFIG_PROVE_RCU, or at least an early version.
	[Viewed June 4, 2010]
}
}
```

```bibtex
@unpublished{AviKivity2010KVM2RCU
,Author="Avi Kivity"
,Title="[{PATCH} 37/40] {KVM}: Bump maximum vcpu count to 64"
,month="February"
,year="2010"
,note="Available:
\url{http://www.mail-archive.com/kvm@vger.kernel.org/msg28640.html}
[Viewed March 20, 2010]"
,annotation={
	Use of RCU permits KVM to increase the size of guest OSes from
	16 CPUs to 64 CPUs.
}
}
```

```bibtex
@unpublished{HerbertXu2010RCUResizeHash
,Author="Herbert Xu"
,Title="bridge: Add core IGMP snooping support"
,month="February"
,year="2010"
,note="Available:
\url{http://thread.gmane.org/gmane.linux.network/153338}
[Viewed June 9, 2014]"
,annotation={
	Use a pair of list_head structures to support RCU-protected
	resizable hash tables.
}
}
```

```bibtex
@mastersthesis{AbhinavDuggal2010Masters
,author="Abhinav Duggal"
,title="Stopping Data Races Using Redflag"
,school="Stony Brook University"
,year="2010"
,annotation={
	Data-race detector incorporating RCU.
	http://www.filesystems.org/docs/abhinav-thesis/abhinav_thesis.pdf
}
}
```

```bibtex
@article{JoshTriplett2010RPHash
,author="Josh Triplett and Paul E. McKenney and Jonathan Walpole"
,title="Scalable Concurrent Hash Tables via Relativistic Programming"
,journal="ACM Operating Systems Review"
,year=2010
,volume=44
,number=3
,month="July"
,annotation={
	RP fun with hash tables.
	http://portal.acm.org/citation.cfm?id=1842733.1842750
}
}
```

```bibtex
@unpublished{PaulEMcKenney2010RCUAPI
,Author="Paul E. McKenney"
,Title="The {RCU} {API}, 2010 Edition"
,month="December"
,day="8"
,year="2010"
,note="\url{http://lwn.net/Articles/418853/}"
,annotation={
	Includes updated software-engineering features.
	[Viewed December 8, 2010]
}
}
```

```bibtex
@mastersthesis{AndrejPodzimek2010masters
,author="Andrej Podzimek"
,title="Read-Copy-Update for OpenSolaris"
,school="Charles University in Prague"
,year="2010"
,note="Available:
\url{https://andrej.podzimek.org/thesis.pdf}
[Viewed January 31, 2011]"
,annotation={
	Reviews RCU implementations and creates a few for OpenSolaris.
	Drives quiescent-state detection from RCU read-side primitives,
	in a manner roughly similar to that of Jim Houston.
}
}
```

```bibtex
@unpublished{LinusTorvalds2011Linux2:6:38:rc1:NPigginVFS
,Author="Linus Torvalds"
,Title="Linux 2.6.38-rc1"
,month="January"
,year="2011"
,note="Available:
\url{https://lore.kernel.org/r/AANLkTimajU0x1v6y3rH2+jr-bZ=tNLs1S_agXdGGAa3S@mail.gmail.com}
[Viewed March 4, 2011]"
,annotation={
	"The RCU-based name lookup is at the other end of the spectrum - the
	absolute anti-gimmick. It's some seriously good stuff, and gets rid of
	the last main global lock that really tends to hurt some kernel loads.
	The dentry lock is no longer a big serializing issue. What's really
	nice about it is that it actually improves performance a lot even for
	single-threaded loads (on an SMP kernel), because it gets rid of some
	of the most expensive parts of path component lookup, which was the
	d_lock on every component lookup. So I'm seeing improvements of 30-50%
	on some seriously pathname-lookup intensive loads."
}
}
```

```bibtex
@techreport{JoshTriplett2011RPScalableCorrectOrdering
,author = {Josh Triplett and Philip W. Howard and Paul E. McKenney and Jonathan Walpole}
,title = {Scalable Correct Memory Ordering via Relativistic Programming}
,year = {2011}
,number = {11-03}
,institution = {Portland State University}
,note = {\url{http://www.cs.pdx.edu/pdfs/tr1103.pdf}}
}
```

```bibtex
@inproceedings{PhilHoward2011RCUTMRBTree
,author = {Philip W. Howard and Jonathan Walpole}
,title = {A Relativistic Enhancement to Software Transactional Memory}
,booktitle = {Proceedings of the 3rd USENIX conference on Hot topics in parallelism}
,series = {HotPar'11}
,year = {2011}
,location = {Berkeley, CA}
,pages = {1--6}
,numpages = {6}
,url = {http://www.usenix.org/event/hotpar11/tech/final_files/Howard.pdf}
,publisher = {USENIX Association}
,address = {Berkeley, CA, USA}
}
```

```bibtex
@techreport{PaulEMcKenney2011cyclicparallelRCU
,author="Paul E. McKenney and Jonathan Walpole"
,title="Efficient Support of Consistent Cyclic Search With Read-Copy Update and Parallel Updates"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2011"
,number="US Patent 7,953,778"
,month="May"
,pages="34"
,annotation={
	Maintains an array of generation numbers to track in-flight
	updates and keeps an additional level of indirection to allow
	readers to confine themselves to the desired snapshot of the
	data structure.
}
}
```

```bibtex
@inproceedings{Triplett:2011:RPHash
,author = {Triplett, Josh and McKenney, Paul E. and Walpole, Jonathan}
,title = {Resizable, Scalable, Concurrent Hash Tables via Relativistic Programming}
,booktitle = {Proceedings of the 2011 USENIX Annual Technical Conference}
,month = {June}
,year = {2011}
,pages = {145--158}
,numpages = {14}
,url={http://www.usenix.org/event/atc11/tech/final_files/Triplett.pdf}
,publisher = {The USENIX Association}
,address = {Portland, OR USA}
}
```

```bibtex
@unpublished{PaulEMcKenney2011RCU3.0trainwreck
,Author="Paul E. McKenney"
,Title="3.0 and {RCU:} what went wrong"
,month="July"
,day="27"
,year="2011"
,note="\url{http://lwn.net/Articles/453002/}"
,annotation={
	Analysis of the RCU trainwreck in Linux kernel 3.0.
	[Viewed July 27, 2011]
}
}
```

```bibtex
@unpublished{NeilBrown2011MeetTheLockers
,Author="Neil Brown"
,Title="Meet the {Lockers}"
,month="August"
,day="3"
,year="2011"
,note="Available:
\url{http://lwn.net/Articles/453685/}
[Viewed September 2, 2011]"
,annotation={
	The Locker family as an analogy for locking, reference counting,
	RCU, and seqlock.
}
}
```

```bibtex
@inproceedings{Seyster:2011:RFA:2075416.2075425
,author = {Seyster, Justin and Radhakrishnan, Prabakar and Katoch, Samriti and Duggal, Abhinav and Stoller, Scott D. and Zadok, Erez}
,title = {Redflag: a framework for analysis of Kernel-level concurrency}
,booktitle = {Proceedings of the 11th international conference on Algorithms and architectures for parallel processing - Volume Part I}
,series = {ICA3PP'11}
,year = {2011}
,isbn = {978-3-642-24649-4}
,location = {Melbourne, Australia}
,pages = {66--79}
,numpages = {14}
,url = {http://dl.acm.org/citation.cfm?id=2075416.2075425}
,acmid = {2075425}
,publisher = {Springer-Verlag}
,address = {Berlin, Heidelberg}
}
```

```bibtex
@phdthesis{JoshTriplettPhD
,author="Josh Triplett"
,title="Relativistic Causal Ordering: A Memory Model for Scalable Concurrent Data Structures"
,school="Portland State University"
,year="2012"
,annotation={
	RCU-protected hash tables, barriers vs. read-side traversal order.
	.
	If the updater is making changes in the opposite direction from
	the read-side traversal order, the updater need only execute a
	memory-barrier instruction, but if in the same direction, the
	updater needs to wait for a grace period between the individual
	updates.
}
}
```

```bibtex
@article{MathieuDesnoyers2012URCU
,Author="Mathieu Desnoyers and Paul E. McKenney and Alan Stern and Michel R. Dagenais and Jonathan Walpole"
,Title="User-Level Implementations of Read-Copy Update"
,journal="IEEE Transactions on Parallel and Distributed Systems"
,volume={23}
,year="2012"
,issn="1045-9219"
,pages="375-382"
,doi="http://doi.ieeecomputersociety.org/10.1109/TPDS.2011.159"
,publisher="IEEE Computer Society"
,address="Los Alamitos, CA, USA"
,annotation={
	RCU overview, desiderata, semi-formal semantics, user-level RCU
	usage scenarios, three classes of RCU implementation, wait-free
	RCU updates, RCU grace-period batching, update overhead,
	http://www.rdrop.com/users/paulmck/RCU/urcu-main-accepted.2011.08.30a.pdf
	http://www.rdrop.com/users/paulmck/RCU/urcu-supp-accepted.2011.08.30a.pdf
	http://www.computer.org/cms/Computer.org/dl/trans/td/2012/02/extras/ttd2012020375s.pdf
}
}
```

```bibtex
@inproceedings{AustinClements2012RCULinux:mmapsem
,author = {Austin Clements and Frans Kaashoek and Nickolai Zeldovich}
,title = {Scalable Address Spaces Using {RCU} Balanced Trees}
,booktitle = {Architectural Support for Programming Languages and Operating Systems (ASPLOS 2012)}
,month = {March}
,year = {2012}
,pages = {199--210}
,numpages = {12}
,publisher = {ACM}
,address = {London, UK}
,url="http://people.csail.mit.edu/nickolai/papers/clements-bonsai.pdf"
}
```

```bibtex
@unpublished{PaulEMcKenney2012ELCbattery
,Author="Paul E. McKenney"
,Title="Making {RCU} Safe For Battery-Powered Devices"
,month="February"
,day="15"
,year="2012"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/RCUdynticks.2012.02.15b.pdf}
[Viewed March 1, 2012]"
,annotation={
	RCU_FAST_NO_HZ, round 2.
}
}
```

```bibtex
@article{GuillermoVigueras2012RCUCrowd
,author = {Vigueras, Guillermo and Ordu\~{n}a, Juan M. and Lozano, Miguel}
,day = {25}
,doi = {10.1007/s11227-012-0766-x}
,issn = {0920-8542}
,journal = {The Journal of Supercomputing}
,keywords = {linux, simulation}
,month = apr
,posted-at = {2012-05-03 09:12:04}
,priority = {2}
,title = {{A Read-Copy Update based parallel server for distributed crowd simulations}}
,url = {http://dx.doi.org/10.1007/s11227-012-0766-x}
,year = {2012}
}
```

```bibtex
@unpublished{JonCorbet2012ACCESS:ONCE
,Author="Jon Corbet"
,Title="{ACCESS\_ONCE()}"
,month="August"
,day="1"
,year="2012"
,note="\url{http://lwn.net/Articles/508991/}"
,annotation={
	A couple of simple specific compiler optimizations that motivate
	ACCESS_ONCE().
}
}
```

```bibtex
@unpublished{AlexeyGotsman2012VerifyGraceExtended
,Author="Alexey Gotsman and Noam Rinetzky and Hongseok Yang"
,Title="Verifying Highly Concurrent Algorithms with Grace (extended version)"
,month="July"
,day="10"
,year="2012"
,note="\url{http://software.imdea.org/~gotsman/papers/recycling-esop13-ext.pdf}"
,annotation={
	Separation-logic formulation of RCU uses.
}
}
```

```bibtex
@unpublished{PaulMcKenney2012RCUUsage
,Author="Paul E. McKenney and Silas Boyd-Wickizer and Jonathan Walpole"
,Title="{RCU} Usage In the Linux Kernel: One Decade Later"
,month="September"
,day="17"
,year="2012"
,url=http://rdrop.com/users/paulmck/techreports/survey.2012.09.17a.pdf
,note="Technical report paulmck.2012.09.17"
,annotation={
	Overview of the first variant of no-CBs CPUs for RCU.
}
}
```

```bibtex
@unpublished{JonCorbet2012NOCB
,Author="Jon Corbet"
,Title="Relocating RCU callbacks"
,month="October"
,day="31"
,year="2012"
,note="\url{http://lwn.net/Articles/522262/}"
,annotation={
	Overview of the first variant of no-CBs CPUs for RCU.
}
}
```

```bibtex
@phdthesis{JustinSeyster2012PhD
,author="Justin Seyster"
,title="Runtime Verification of Kernel-Level Concurrency Using Compiler-Based Instrumentation"
,school="Stony Brook University"
,year="2012"
,annotation={
	Looking for data races, including those involving RCU.
	Proposal:
	http://www.fsl.cs.sunysb.edu/docs/jseyster-proposal/redflag.pdf
	Dissertation:
	http://www.fsl.cs.sunysb.edu/docs/jseyster-dissertation/redflag.pdf
}
}
```

```bibtex
@unpublished{PaulEMcKenney2013RCUUsage
,Author="Paul E. McKenney and Silas Boyd-Wickizer and Jonathan Walpole"
,Title="{RCU} Usage in the {Linux} Kernel: One Decade Later"
,month="February"
,day="24"
,year="2013"
,note="\url{http://rdrop.com/users/paulmck/techreports/RCUUsage.2013.02.24a.pdf}"
,annotation={
	Usage of RCU within the Linux kernel.
}
}
```

```bibtex
@inproceedings{AlexeyGotsman2013ESOPRCU
,author = {Alexey Gotsman and Noam Rinetzky and Hongseok Yang}
,title = {Verifying concurrent memory reclamation algorithms with grace}
,booktitle = {ESOP'13: European Symposium on Programming}
,year = {2013}
,pages = {249--269}
,publisher = {Springer}
,address = {Rome, Italy}
,annotation={
	http://software.imdea.org/~gotsman/papers/recycling-esop13.pdf
}
}
```

```bibtex
@unpublished{PaulEMcKenney2013NoTinyPreempt
,Author="Paul E. McKenney"
,Title="Simplifying RCU"
,month="March"
,day="6"
,year="2013"
,note="\url{http://lwn.net/Articles/541037/}"
,annotation={
	Getting rid of TINY_PREEMPT_RCU.
}
}
```

---

# Overview

_Peios Kernel / Internals / KMES_

> KMES is the sole event emission path in Peios, used by kernel subsystems and userspace alike, and the terms this chapter uses for it.

<a id="trm-2-1"></a>

The Kernel Mediated Event Subsystem (KMES) is the sole event emission path in
Peios. Kernel subsystems and userspace processes alike emit events
exclusively through KMES — there is no alternative path. KMES stamps
each event with trusted metadata at emission time, buffers it in
per-CPU shared memory ring buffers, and delivers it to userspace
consumers that map those buffers directly. It does not persist, index,
or query events, and it imposes no schema or naming convention on them;
those are consumer concerns, handled by eventd.

KMES serves a similar role to ETW in the Windows kernel and auditd in
Linux, but is compatible with neither at the wire, format, or API
level. The design — structured events with a fixed binary header and a
msgpack payload, shared memory delivery, one emission path for kernel
and userspace — was chosen for unified observability with
kernel-trusted metadata.

The consumer-facing contract — the event header layout, the mapped
ring buffer regions, and the protocols a consumer follows to drain,
sleep, and survive buffer swaps — is specified in PSPK's KMES event
stream chapter. This chapter describes the kernel side: how events are
constructed and stamped ([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)), the in-kernel emission API ([Emission API](</kernel/internals/kmes/emission-api.md#trm-2-3>)), the
syscall surface ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)), how the ring buffers are organised and written
([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)), self-configuration through the registry ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)), behaviour
under failure ([Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)), and the emission policy that decides which of
the kernel's own event types are written ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

<a id="trm-2-1-1"></a>

## Terminology

An **event** is an indivisible record: a packed binary **header**
carrying KMES-intrinsic metadata, followed by a msgpack-encoded
**payload** whose structure is defined by the emitter. Header and
payload are produced, stored, and consumed together as one contiguous
byte sequence; neither is meaningful alone. KMES treats the payload as
opaque.

The **stamp** fields are the header fields KMES populates itself at
emission time: the timestamp, sequence number, CPU identifier, and
origin class, plus three identity GUIDs captured from KACS — the
**effective token GUID** (the token governing the emitting thread's
access rights, which is the impersonation token when the thread is
impersonating), the **true token GUID** (the process's primary token,
regardless of impersonation), and the **process GUID** (assigned by
KACS at fork and unchanged across exec). The **null GUID** — sixteen
zero bytes — stamps an identity field whose value is unavailable. <a id="cite-event.null-guid-means-unavailable"></a>

The **sequence number** is a per-CPU, per-boot monotonic 64-bit
counter. Each CPU counts independently; the counter starts at zero
when PKM loads and is incremented before its value is taken, so the
first event on each CPU carries sequence number 1 and sequence 0 is
never assigned. <a id="cite-event.sequence-starts-at-one"></a> A gap in one CPU's sequence indicates lost events. The
pair (`cpu_id`, `sequence`) uniquely identifies an event within a
boot; there is no global sequence. <a id="cite-event.sequence-scoped-per-cpu"></a>

The **origin class** is a header byte identifying the emission path:
userspace (0), KMES itself (1), KACS (2), or LCS (3). Values 4–255 are
unassigned. <a id="cite-event.origin-classes-assigned"></a>

The **event type** is a length-prefixed UTF-8 string in the header
identifying the kind of event. KMES imposes no structure on it and
compares nothing against it; types are consumer vocabulary. <a id="cite-event.type-opaque"></a>

A **ring buffer** is a per-CPU shared memory region — producer
metadata page, consumer metadata page, and a data region — created
and managed by KMES and mapped by consumers. A **consumer** is a
userspace process that maps one or more ring buffers and drains events
from them, typically with one thread per CPU. **Boot-time ring
buffers** are the ordinary per-CPU buffers created at module load
using compiled-in defaults; they are the live consumer-facing buffers
from the first instant, not a separate class. <a id="cite-ring.boot-buffers-ordinary"></a>

<a id="trm-2-b-6"></a>

## Build configuration <a id="cite-build.config-security-pkm"></a>

KMES is built by `CONFIG_SECURITY_PKM`, a boolean option, so it is
linked into `vmlinux` rather than loaded. `CONFIG_RUST=y` is required:
the MessagePack validator is Rust. The subsystem lives in
`security/pkm/kmes`, with tracepoint declarations in
`include/trace/events/kmes.h`.

The three syscall numbers are registered in
`arch/x86/entry/syscalls/syscall_64.tbl` and the corresponding table
under `tools/perf/`. They are registered `common` in the table, but the
kernel is built without `CONFIG_X86_X32_ABI`, so the only entry point
that exists is x86-64: an x32 invocation (the number with bit 30 set)
fails `ENOSYS` like any other x32 syscall on this
kernel. <a id="cite-build.syscalls-registered-common"></a>

`CONFIG_SECURITY_PKM_KUNIT` compiles in the in-kernel test harness.

## Related explanations

- [Self-configuration](</kernel/internals/kmes/self-configuration.md>)
- [ABI semantics and limits](</kernel/userspace/native/kmes/abi-semantics-and-limits.md>)

## Calling the subsystem

The [native KMES interface reference](</kernel/userspace/native/kmes/overview.md>) collects the caller contracts and generated ABI tables.

---

# Event Model

_Peios Kernel / Internals / KMES_

> What an event is on the wire — the packed header, the stamps the kernel applies, ordering, the msgpack payload and the size limits.

<a id="trm-2-2"></a>

<a id="trm-2-2-1"></a>

## Structure <a id="cite-event.wire-structure"></a>

An event is a packed binary header followed immediately by its msgpack
payload, written and delivered as a single contiguous byte sequence
with no padding or alignment gaps anywhere. The header is never
represented as a C struct in the kernel; it is serialised field by
field, in order, directly into the ring buffer. The field-by-field
layout — offsets, sizes, and endianness — is part of the consumer
contract and is defined in the PSPK event stream specification. In
summary: all fields before the event type string sit at fixed offsets,
the event type string begins at offset 77 with its `u16` length at
offset 75, the header is exactly `77 + type_len` bytes, the payload
occupies the bytes from `header_size` to `event_size`, and the next
event begins at offset `event_size` from the start of the current one.
All multi-byte header integers are little-endian; the identity GUIDs
are copied as opaque 16-byte values.

`event_size`, `header_size`, and `type_len` are structural fields
computed by KMES during construction. The emitter supplies only the
event type string and the payload, and KMES copies both verbatim. <a id="cite-event.emitter-bytes-verbatim"></a>

<a id="trm-2-2-2"></a>

## Intrinsic stamps <a id="cite-event.stamps-unconditional"></a>

KMES populates four intrinsic stamp fields at emission time,
unconditionally; the emitter cannot supply them.

- **`timestamp`** — wall clock time (`CLOCK_REALTIME`, via
  `ktime_get_real_ns()`) at the moment KMES accepts the event, in
  nanoseconds since the Unix epoch. <a id="cite-event.stamp.timestamp-realtime"></a>
- **`sequence`** — the emitting CPU's per-boot counter, incremented
  and then read, so the first event on each CPU gets 1. <a id="cite-event.stamp.sequence-increment-then-read"></a>
- **`cpu_id`** — the CPU on which the ring buffer write occurs, which
  identifies the per-CPU buffer holding the event. <a id="cite-event.stamp.cpu-id-of-write"></a>
- **`origin_class`** — for syscall emission, set unconditionally to 0
  (userspace); the caller cannot influence it. For kernel emission,
  the value the calling subsystem passed, written to the header
  without validation — kernel emitters are trusted to pass an
  assigned value. <a id="cite-event.stamp.origin-class-trust"></a>

The timestamp is captured before the sequence number is assigned, so
two events with the same timestamp on the same CPU are ordered by
sequence. <a id="cite-event.stamp.timestamp-before-sequence"></a>

<a id="trm-2-2-3"></a>

## Identity stamps <a id="cite-event.identity-at-write-time"></a>

The three identity GUIDs are captured by calling KACS accessors during
the preemption-disabled ring buffer write phase, after the sequence
number is taken and before the header is built. All three accessors
are safe with preemption disabled — each is a handful of pointer
dereferences and a 16-byte copy, with no allocation and no sleeping.
The stamps therefore reflect the thread's identity at the moment of
the ring buffer write, not at syscall entry.

- `kacs_effective_token_guid()` reads the thread's *subjective*
  credentials (`current_cred()`), so during impersonation — which
  installs the impersonation token via `override_creds()` — it yields
  the impersonation token's GUID. Otherwise it equals the true token
  GUID. <a id="cite-event.identity.effective-follows-impersonation"></a>
- `kacs_primary_token_guid()` reads the *real* credentials
  (`current_real_cred()`), which impersonation leaves untouched, so it
  always yields the process's primary token GUID. <a id="cite-event.identity.true-ignores-impersonation"></a>
- `kacs_process_guid()` reads the process GUID KACS assigned when the
  process's security state was created at fork. Threads created with
  `CLONE_THREAD` share the process state, and no exec path writes the
  field, so the GUID is stable for the process's lifetime. <a id="cite-event.identity.process-guid-stable"></a>

All three accessors return the null GUID when there is no task context
(`!current` or not `in_task()`), and the token accessors also return it
when the token cannot be resolved. A fully null identity triple
therefore indicates emission before KACS initialisation, from a kernel
thread, or from interrupt or softirq context. No event is ever stamped
with the identity of a task that merely happened to be interrupted. <a id="cite-event.identity.null-without-task-context"></a>

For batch emission, the timestamp and the three identity GUIDs are
captured once, before the per-event loop, and shared by every event in
the batch: the batch executes with preemption disabled on one CPU, so
the emitting thread's identity cannot change mid-batch. Each event
still receives its own sequence number. <a id="cite-event.identity.batch-captured-once"></a>

<a id="trm-2-2-4"></a>

## Ordering <a id="cite-event.ordering-contract"></a>

Within one CPU, `sequence` is the reliable ordering primitive, monotonic
even across wall-clock discontinuities. Keep the CPU and boot context with
it. A consumer can sort records from different CPUs by `timestamp`, but
wall-clock timestamps do not establish a total causal order. Equal timestamps
do not prove that operations were simultaneous or independent.

<a id="trm-2-2-5"></a>

## Catalog field names

Consumers expose header information through the catalog's field names:

| Catalog field | Header member |
|---|---|
| `event.type` | `type`, supplied by the emitter |
| `event.time` | `timestamp` |
| `event.sequence` | `sequence` |
| `event.cpu` | `cpu_id` |
| `emitter.class` | `origin_class` |
| `emitter.token.guid` | `effective_token_guid` |
| `emitter.true-token.guid` | `true_token_guid` |
| `emitter.process.guid` | `process_guid` |

`event.boot.guid` is consumer-supplied boot context, not a header member.
The structural sizes are framing information, not catalog payload fields.
The platform definitions live in `peios/packages/data/evman/kernel.evman`.
A conforming payload does not repeat header information.

The origin class describes the emission path, not the event type's prefix.
Userspace emits with class 0. StrataFS records emitted through KACS carry the
KACS class. Null identity stamps do not establish an actor; interpret them
using the identity-stamp rules in this article.

## Payload

The payload is a single msgpack value. KMES neither interprets nor
modifies it — buffering and delivery are content-blind — and it
performs no payload validation at all for kernel emitters, which are
trusted callers inside PKM. <a id="cite-event.payload.kernel-not-validated"></a>

Payloads arriving through the syscall interface are validated before
acceptance by an iterative (non-recursive) msgpack walker implemented
in Rust, operating on the kernel's staged copy of the payload:

- The payload is exactly one well-formed top-level msgpack value.
  Trailing bytes after it are rejected, as is the never-used `0xc1`
  type byte. <a id="cite-event.payload.exactly-one-value"></a> A zero-length payload is rejected — an empty byte
  sequence is not a msgpack value — so syscall events always carry a
  payload. <a id="cite-event.payload.empty-rejected"></a> (Kernel emitters can emit header-only events with
  `event_size == header_size`.)
- Nesting depth is bounded by the configured `MaxNestingDepth`
  ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). Depth counts from 1 at the top-level value; each child of an
  array or map sits one deeper than its container. A non-empty
  container at the maximum depth is invalid, because its children
  would exceed the limit; an empty array or map at the maximum depth
  is valid, consuming no depth. Map keys and values each occupy a
  child slot, so a map contributes twice its entry count of children. <a id="cite-event.payload.depth-model"></a>
- The walker's own stack is 256 frames, matching the upper bound of
  the `MaxNestingDepth` range; a configured depth outside 1–256 causes
  every payload to be rejected rather than any to be waved through. <a id="cite-event.payload.bad-depth-config-rejects-all"></a>
- Length prefixes inside msgpack are big-endian, per the MessagePack
  specification — the one big-endian ingredient in an otherwise
  little-endian event.

A rejected payload fails the syscall with `EINVAL` and nothing is
written to the ring buffer. <a id="cite-event.payload.reject-writes-nothing"></a>

The event type string is validated as UTF-8 on the syscall path by the
same staged-copy pass; kernel emitters' type strings are trusted and
copied as given. Types are compared by consumers as raw bytes — no
case folding or normalisation is applied anywhere. <a id="cite-event.type-utf8-on-syscall-path"></a>

<a id="trm-2-2-6"></a>

## Size limits <a id="cite-event.size-limits"></a>

Three structural bounds apply to every event, and one configurable
policy bound applies to syscall emitters only:

- The event type length fits the header's `u16` `type_len` field and
  is nonzero. Syscall emitters cannot express an overlong type — the
  ABI length field is already `u16` — but the kernel emission API
  takes a `size_t` and enforces the bound itself. <a id="cite-event.limits.type-len-u16-nonzero"></a>
- The total event size (header + payload) fits a `u32`, checked with
  overflow-safe arithmetic on the declared lengths. <a id="cite-event.limits.total-fits-u32"></a>
- The total event size does not exceed 50% of the per-CPU ring buffer
  capacity — a fixed ratio, not configurable, protecting a CPU's
  event history from a single giant event. An event of exactly half
  the capacity is accepted. Capacity is always a power of two, so the
  halving is exact. <a id="cite-event.limits.half-capacity"></a>
- Syscall events are additionally bounded by the registry-configurable
  `MaxEventSize` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)), rejected with `ENOSPC` when exceeded. Kernel
  emitters are exempt from this policy limit. <a id="cite-event.limits.max-event-size-syscall-only"></a>

---

# Emission API

_Peios Kernel / Internals / KMES_

> The in-kernel emission interface — single and batch emission, the structural checks that drop an event, and what happens when a ring is full.

<a id="trm-2-3"></a>

The emission API is the internal kernel interface through which PKM
subsystems emit events — an ordinary function call inside the module,
not a syscall. Userspace emission goes through the syscall interface
([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)). There are two entry points: single emission
(`pkm_kmes_emit_kernel`) and batch emission
(`pkm_kmes_emit_kernel_batch`). Both return nothing: kernel emission
is fire-and-forget, and the emitting subsystem is never notified of a
drop. <a id="cite-kernel-emit.fire-and-forget"></a>

Neither entry point consults the emission policy. Whether a type is
switched on is decided by the emitter before it builds the event, with
the check described in [Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>); an event that reaches the emission API is
written.

<a id="trm-2-3-1"></a>

## Single emission

A kernel emitter passes an origin class, an event type (pointer and
length), and a payload (pointer and length). It does not choose a CPU
or buffer: KMES writes the event to the ring buffer of the CPU the
calling code is executing on. <a id="cite-kernel-emit.executing-cpu"></a>

The entire emission path runs with preemption and bottom halves
disabled — from before the current CPU is determined until after the
ring buffer write — which guarantees the emitting thread cannot
migrate mid-write and preserves the single-writer-per-buffer
invariant. For kernel emitters this covers the full path, timestamp
capture through ring write; the payloads are small and trusted, and
the window is a few hundred nanoseconds.

Bottom halves matter because rings are written from softirq context as
well as from tasks: the packet engine reports from the network receive
path, and RCU callbacks run in softirq. With only preemption disabled,
a softirq taken on interrupt exit could write the same CPU's ring
between a task writer's sequence increment and its `write_pos`
publication, interleaving two events in one reservation. Every ring
writer — single, kernel batch and the emit syscalls — therefore holds
bottom halves off across its reservation and write. A writer that runs
with interrupts already disabled needs no more: neither a softirq nor
a hard interrupt can reach its CPU. <a id="cite-kernel-emit.bottom-halves-held"></a>

Emission from hard interrupt or NMI context is refused. Bottom halves
cannot be held off there, and such a writer could interrupt one
holding the ring, so the event is dropped before any ring is touched:
no sequence number is consumed, no ring drop is counted, and KMES
tallies it in a private counter and logs the first such drop once. No
kernel emitter runs in hard interrupt context. <a id="cite-kernel-emit.hardirq-refused"></a>

The consumer wake that follows a write takes the futex hash bucket
lock, which the futex core takes with bottom halves enabled; a softirq
taking it while a task on the same CPU held it would spin forever. A
writer outside task context therefore does not wake consumers itself:
the write still advances the futex counter, and the wake is handed to
a work item on the ring, which holds a reference to the ring until it
has run in process context. <a id="cite-kernel-emit.softirq-wake-deferred"></a>

Construction proceeds in order: capture the wall clock timestamp;
increment the CPU's sequence counter and take the new value; capture
the three identity GUIDs from KACS; build the packed header; write
header and payload contiguously into the ring. The ordering
consequences of these steps are described in [Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>).

KMES trusts kernel emitters. It does not validate the origin class,
the type string's encoding, or the payload — only the structural
checks below run. A null event-type pointer is not checked on the
single-emission path; passing one faults. <a id="cite-kernel-emit.trusted-unvalidated"></a>

<a id="trm-2-3-2"></a>

## Structural checks and drops <a id="cite-kernel-emit.structural-checks"></a>

Every kernel emission is checked for: nonzero event type length; type
length within `u16`; total event size within `u32` (overflow-checked);
and total event size within 50% of the per-CPU ring capacity.

A failing event is not written — but its sequence number has already
been consumed, so the drop is visible to consumers as a gap in that
CPU's sequence, and an internal per-CPU dropped-event counter is
incremented. <a id="cite-kernel-emit.drop-consumes-sequence"></a> That counter also aggregates events discarded by
overwrite when the buffer wraps; it is not exposed in the ring buffer
metadata and is readable only by the KUnit test harness. <a id="cite-kernel-emit.drop-counter-internal"></a>

Two further situations discard kernel events entirely outside this
accounting:

- Before KMES initialisation completes, emission is a silent no-op: no
  sequence number is consumed, the drop counter is not incremented,
  and no gap is visible. Events emitted in this window are simply
  gone. KMES tallies them in a private counter and logs the total once
  when the rings come up. <a id="cite-kernel-emit.pre-init-silent"></a>
- If the ring's recorded CPU identity does not match the executing
  CPU, the ring selection itself is untrustworthy, so every emission
  path — single, kernel batch and syscall — returns early without
  consuming a sequence number or counting a drop. <a id="cite-kernel-emit.cpu-mismatch-discard"></a>

<a id="trm-2-3-3"></a>

## Ring buffer full <a id="cite-kernel-emit.never-blocks"></a>

Each per-CPU buffer is circular. When it is full, KMES overwrites the
oldest events to make room; the write position advances
unconditionally, and emission never blocks and never fails from buffer
pressure. Consumers detect the overwritten events as sequence gaps,
and a consumer whose read position has been overtaken re-anchors to
the oldest surviving event, as specified in the PSPK event stream
chapter. The overwrite mechanics are described with the write protocol
in [Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>).

<a id="trm-2-3-4"></a>

## Batch emission

The batch API emits multiple events in one operation: an origin class
applied to the whole batch, an array of event descriptors (type
pointer and length, payload pointer and length each), and a count.
There is no upper bound on the kernel batch count — unlike the syscall
batch, which caps at 256 entries — so the non-preemptible window is
bounded only by the caller's restraint.

The batch executes as one section with preemption and bottom halves
disabled:

1. One wall clock timestamp is captured; every event in the batch
   shares it.
2. The three identity GUIDs are captured once and shared.
3. Each event, in order: structural checks, sequence assignment,
   header build, ring write. The batch structural check is slightly
   stronger than the single-emission one — it also rejects a null
   type pointer, a null payload pointer with a nonzero length, and a
   header size beyond `u32`. <a id="cite-kernel-emit.batch-stronger-checks"></a> A failing event is dropped exactly as in
   single emission (sequence consumed, gap visible, counter
   incremented) and the batch continues with the next event — kernel
   emitters are trusted, and an individual structural failure
   indicates a kernel bug rather than hostile input. <a id="cite-kernel-emit.batch-continues-past-failure"></a> This differs
   deliberately from the syscall batch, which stops at the first
   failure so the untrusted caller learns which entry was bad.
4. After the loop, provided at least one event was actually written,
   the new tail position and then the new write position are published
   with release stores — one publication for the whole batch — and
   the consumer wake flag is checked once, incrementing the futex
   counter if a consumer is asleep. A batch in which every event
   failed publishes nothing and performs no wake check. <a id="cite-kernel-emit.batch-publishes-once"></a>
5. Preemption and bottom halves are re-enabled, and only then is the
   futex wake performed, outside the window — or, outside task
   context, handed to the ring's work item.

Deferring publication gives batch atomicity: consumers observe either
none of the batch or all of it, since the data is fully written before
the single `write_pos` release store. <a id="cite-kernel-emit.batch-atomic-visibility"></a> During the batch, the overwrite
check runs against an internal running write offset — the consumer-
visible `write_pos` stays untouched until the end. The tail position
is likewise kept local and published only at the end.

<a id="trm-2-3-5"></a>

## Write atomicity <a id="cite-event.write-atomicity"></a>

Individual event writes are atomic from the consumer's perspective: an
event's bytes are fully written into the data region before the
`write_pos` release store makes them reachable, so a consumer bounded
by `write_pos` can never observe a partially written event. The
memory-ordering contract this rests on is part of the PSPK event
stream specification; the kernel-side implementation of the write
protocol is described in [Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>).

---

# Ring Buffers

_Peios Kernel / Internals / KMES_

> One ring per logical CPU — how they are organised, the two producer metadata pages, wrap handling, the write protocol and notification.

<a id="trm-2-5"></a>

<a id="trm-2-5-1"></a>

## Organisation

KMES maintains one ring buffer per logical CPU, created for every CPU
in the kernel's possible-CPU set when the module initialises — before
LCS exists, using the compiled-in default capacity — and buffering
events from that first instant. These boot-time buffers are ordinary
buffers: same layout, same overwrite semantics, same generation
model, immediately attachable. If LCS never becomes available they
simply remain the live buffers indefinitely. <a id="cite-ring.created-at-init-for-possible-cpus"></a>

Each ring is an independent, reference-counted object holding its
capacity, generation, sequence counter, write and tail positions,
futex counter, dropped-event counter, two metadata pages, and the data
region. There is no shared state between rings on the write path: each
CPU writes only to its own ring, using plain non-atomic fields under
preemption disablement, and the only ordering machinery is a set of
release stores at publication points. Fds taken by consumers hold
references, so a ring — including a superseded generation — survives
until the last consumer releases it. <a id="cite-ring.independent-refcounted"></a>

The data region is a `vzalloc` allocation of exactly `capacity` bytes,
zeroed once at creation and never scrubbed afterwards; overwritten
regions retain stale bytes, which is why the consumer contract forbids
reading beyond an event's `event_size`. <a id="cite-ring.data-zeroed-once-not-scrubbed"></a> Capacity is always a power of
two — enforced at every entry point — so position wrap is a bitwise
AND with `capacity - 1`. The permitted range is 64 KB to 256 MB, with
a 4 MB default. <a id="cite-ring.capacity-range"></a>

<a id="trm-2-5-2"></a>

## The two producer metadata pages <a id="cite-ring.mirrored-metadata-stores"></a>

Producer metadata exists twice. The kernel writes its working copy to
a private page allocated with the ring, and mirrors every store to a
second, consumer-visible page. The consumer-visible page is
shmem-backed and allocated lazily at the first `kmes_attach` for the
ring; shmem backing is what makes the notification futex work, since
a shared (inode-keyed) futex needs a page-backed mapping. <a id="cite-ring.shared-page-lazy-shmem"></a> Every
producer store — `write_pos`, `tail_pos`, `futex_counter`,
`generation` — is a release store performed to both pages; the static
fields are initialised at ring creation and re-stamped when the shared
page appears. The mmap handler exposes only the shared page. The field
offsets on the page are part of the consumer contract, defined in the
PSPK event stream chapter.

<a id="trm-2-5-3"></a>

## Consumer mapping permissions <a id="cite-consumer.mapping-permissions"></a>

The producer metadata page and both aliases of the data region are read-only
to consumers. The consumer metadata page is read-write: ordinary stores and
authorised `process_vm_writev` writes can set `need_wake`. A consumer can remove
write permission from that page with `mprotect` and restore it later.

A write-enabling `mprotect` covering any producer or data byte fails with
`EACCES`, including requests spanning the consumer page and a protected region.
Write faults and writable page pins must not upgrade the protected pages.
These boundaries follow the original mapping offsets when `mprotect` splits a
VMA; a new VMA start does not move the consumer page. Process access gates for
remote writes still apply.

<a id="trm-2-5-4"></a>

## Wrap handling <a id="cite-ring.consumer-sees-contiguous-wrap"></a>

The consumer's data region is double virtual mapped — the same
physical pages appear twice consecutively — so a consumer reads an
event that crosses the physical end of the buffer as one contiguous
byte sequence. The producer side has no such mapping: kernel writes
into the `vzalloc` region are wrap-aware, splitting a byte-range copy
that crosses the boundary into two `memcpy` calls and masking scalar
stores per byte. The contiguity guarantee is a property of the
consumer's view, produced by the mmap layout rather than by the
writer.

<a id="trm-2-5-5"></a>

## Write protocol

Each ring has exactly one writer — its CPU — and the write path takes
no locks and performs no cross-CPU atomics. For a single kernel
emission: capture the timestamp; take the next sequence number; if
the event fails a structural check, count the drop and stop ([Emission API](</kernel/internals/kmes/emission-api.md#trm-2-3>));
otherwise make room, write the event at `write_pos & (capacity - 1)`,
publish the new `write_pos` (old value plus event size) with a
release store, and check `need_wake`. The release store is what makes
the event atomic from the consumer's side: the bytes are complete
before the position that makes them reachable moves.

Making room is the overwrite walk. While the live span
(`write_pos - tail_pos`) plus the incoming event exceeds capacity,
KMES reads the `event_size` of the event at the tail and advances
`tail_pos` past it, counting each overwritten event in the internal
dropped-event counter, and publishes the advanced tail with a release
store before the new data lands on top of it. <a id="cite-ring.overwrite-advances-tail-first"></a> Walking the tail is
sequential and possibly cache-cold — the tail can be megabytes from
the write position — a cost accepted in preference to maintaining an
index of event offsets on the hot write path.

The walk carries a corruption guard: if the size field read at the
tail is zero, larger than the capacity, or larger than the live span,
KMES abandons the walk and resynchronises by jumping `tail_pos`
straight to `write_pos`, discarding the entire surviving window in
one step (the discarded span is not itemised in the drop counter) and
emitting a tracepoint. <a id="cite-ring.tail-resync-guard"></a>

For a batch, KMES first walks the reservations for every accepted event
using local write and tail positions. It publishes the resulting tail
with one release store **before writing any event bytes**, so a
concurrent consumer can detect that the record it was reading has been
overwritten. Publishing the tail only after the writes would allow the
consumer's tail re-check to accept torn data.

After writing the events, KMES publishes the final write position with
one release store and checks `need_wake` once, provided at least one
event was written. New batch records become available at that final
write-position store; the tail still transitions once per batch rather
than once per overwritten event. <a id="cite-ring.batch-one-tail-transition"></a>

<a id="trm-2-5-6"></a>

## Notification <a id="cite-ring.need-wake-protocol"></a>

The wake path reads the consumer page's `need_wake` byte — the single
consumer-writable byte KMES ever reads, treated as a boolean and
trusted for nothing else. If it is zero, notification costs that one
read. If set, KMES increments the futex counter with a release store
and wakes every thread waiting on it. The futex is a shared,
inode-keyed futex on the shmem producer page at the counter's offset —
a consequence a consumer must match: a `FUTEX_PRIVATE_FLAG` wait on
the mapped address is never woken. <a id="cite-ring.futex-is-shared-inode-keyed"></a> Before any consumer has attached,
the shared page does not exist and the wake is skipped entirely,
though the private counter still advances. <a id="cite-ring.wake-skipped-before-attach"></a>

The `futex_wake` call itself is issued after preemption is re-enabled,
outside the write window; only the counter increment happens inside
it. Waking a thread that is already awake is a harmless no-op, which
is also why the consumer's relaxed clearing of `need_wake` is safe.

<a id="trm-2-5-7"></a>

## Capacity swaps <a id="cite-ring.swap-under-stop-machine"></a>

A valid `BufferCapacity` configuration change replaces every ring.
New rings are allocated first, at the old generation plus one, fully
initialised before any CPU can see them. The switch itself runs under
`stop_machine`: with every CPU quiesced, each ring's surviving events
are migrated to its replacement, the per-CPU live pointers are
switched, and each old ring's published generation is bumped to the
new value — signalling consumers on the old mapping to re-attach. <a id="cite-ring.swap.generation-bump-signals-reattach"></a> If
an old ring's `need_wake` is set, its futex counter is bumped inside
the quiesced section and the wake is issued after it, so consumers
asleep on a dead generation do not sleep forever. <a id="cite-ring.swap.wakes-stale-sleepers"></a>

The outgoing live references remain held until `stop_machine` returns.
They are released after the pending wakes, in a context where cleanup
can sleep. The quiesced callback never performs the final release of
an old ring, which can unmap and free its pages.

Migration copies the surviving span in sequence order, re-compacted
contiguously from position zero: the new ring starts with
`tail_pos = 0` and `write_pos` equal to the bytes copied, and the
sequence and dropped-event counters carry over, so sequence numbers
are continuous across a swap. <a id="cite-ring.swap.migration-recompacts"></a> When the new capacity is smaller than
the surviving span, the oldest events are skipped from the tail
forward until the suffix fits — loss is bounded to the oldest prefix,
traced but not counted as drops. <a id="cite-ring.swap.shrink-skips-oldest"></a> Old positions are meaningless in the
new ring; a consumer re-locates by sequence number, per the PSPK
protocol.

If allocating the new rings fails, the old rings stay live at their
size, no generation changes, and the failure is reported through a
`kmes.buffer.swap.failed` event ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). <a id="cite-ring.swap.alloc-failure-keeps-old"></a> A migration abort — a corrupt
size field encountered inside the quiesced section — abandons the
swap the same way and is reported the same way, with `-EIO` as the
error. <a id="cite-ring.swap.abort-emits-event"></a> There is no automatic retry;
the next configuration write or reboot tries again. A superseded
generation's pages stay valid for as long as any consumer keeps them
mapped, so during and after a swap old and new rings coexist until
the last old fd closes. <a id="cite-ring.swap.generations-coexist"></a>

---

# Self-configuration

_Peios Kernel / Internals / KMES_

> The four parameters KMES reads from the registry, how it bootstraps before LCS exists, and the watch that keeps them current.

<a id="trm-2-6"></a>

KMES reads four operational parameters from the registry under
`Machine\System\KMES\`. Compiled-in defaults carry it from module load
until LCS becomes available; from then on a persistent kernel-internal
watch keeps it current. The key names, types, defaults, and ranges are
in [KMES ABI Reference](</kernel/userspace/native/kmes/generated-abi-tables.md#trm-2-a>).

At no point does KMES wait for configuration. The defaults are always
sufficient, and if LCS never appears KMES runs on them indefinitely. <a id="cite-config.defaults-carry-until-lcs"></a>

<a id="trm-2-6-1"></a>

## Reading and validating

Value names are matched with LCS's value-name comparison rules —
Unicode Simple Case Folding, case-preserving and case-insensitive.
Names in the subtree that do not fold to one of the four canonical
names are unknown keys: they are counted and ignored. <a id="cite-config.names-case-folded-unknown-ignored"></a>

A `REG_DWORD` value carries exactly four little-endian payload bytes
and a `REG_QWORD` exactly eight. A value whose type tag is right but
whose payload length is wrong is not a malformed number — it is
classified as a wrong-type value, and reported as such. <a id="cite-config.wrong-length-is-wrong-type"></a>

Values are never clamped or silently corrected. A value outside its
range, of the wrong type, of the wrong payload length, absent, or (for
`BufferCapacity`) not a power of two is rejected outright and the
previously active value is retained — the compiled-in default, or the
last accepted value. The registry write itself succeeds, because the
source does not enforce kernel semantics; the registry therefore shows
what was written while the event log shows what KMES is actually
using. <a id="cite-config.invalid-rejected-not-clamped"></a> Validation happens twice: once when the change plan is built,
and again in C before the plan is applied, so an out-of-range field
reaching the second gate fails the whole application with `EINVAL`. <a id="cite-config.validated-twice"></a>

The capacity swap runs first, and a `BufferCapacity` change that
cannot be applied rolls back the capacity and nothing else:
`MaxEventSize`, `MaxNestingDepth`, and `MaxEmitRatePerProcess` still
commit in the same pass, against the capacity that is actually live,
so the stored configuration describes the running system rather than
the requested one. The situation that makes a swap fail — memory
pressure — is exactly the one in which an administrator raising
`MaxEventSize` and `BufferCapacity` together needs the `MaxEventSize`
change to survive. <a id="cite-config.swap-failure-rolls-back-capacity-only"></a> A
`MaxEmitRatePerProcess` change additionally reconfigures every live
rate bucket, clamping any bucket holding more tokens than the new
capacity ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)).

A valid `BufferCapacity` different from the current one triggers a
ring buffer swap ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)). <a id="cite-config.capacity-change-swaps"></a>

<a id="trm-2-6-2"></a>

## Self-configuration events <a id="cite-config.self-events-origin-kmes"></a>

KMES reports its own configuration handling through KMES, with origin
class 1. These events are best-effort diagnostics: emission runs
before the configuration is applied and its result is discarded, so a
failed emission neither rolls back a valid application nor activates
an invalid value. Each event's payload is built by a small in-kernel
msgpack writer into a 768-byte buffer; a payload that would exceed it
is silently skipped. <a id="cite-config.self-events-best-effort"></a>

`kmes.config.value.rejected` reports one missing or invalid value. Its
payload follows the event-field rules of PGSS [Overview](</kernel/internals/ntfe/overview.md#trm-6-1>): each dotted field
path is a nested msgpack map, one per segment, and a field that does
not apply is absent rather than nil. Every field lives under a single
top-level `config` map of five keys, in order:

- `config.key.path` — always `Machine\System\KMES`.
- `config.name` — the canonical value name.
- `config.expected.type`, `config.expected.min` and
  `config.expected.max` — the registry type code and range from the
  key's definition.
- `config.received.kind` — one of `missing`, `wrong-type` or
  `out-of-range`. A malformed payload length reports `wrong-type`. A
  `REG_DWORD` and a `REG_QWORD` value out of range both report
  `out-of-range`, since `config.expected.type` already gives the
  width. `config.received.type` (the actual registry type code) is
  present exactly when the kind is `wrong-type`, and
  `config.received.value` (the number received) exactly when it is
  `out-of-range`. A missing value carries the kind alone.
- `config.value` — the value KMES continues to use, read before any
  part of the plan was applied. <a id="cite-config.invalid-event-nine-keys"></a>

One read reports at most four of these events, which is exactly the
number of configuration keys. A plan that would need more is rejected
before anything is applied, and the entire configuration read is
abandoned. <a id="cite-config.at-most-four-reports"></a>

On a first boot where the KMES key exists but is empty, all four keys
are missing, so the read emits four `kmes.config.value.rejected`
events and retains all four defaults. <a id="cite-config.empty-key-emits-four"></a>

`kmes.buffer.swap.failed` reports a valid `BufferCapacity` change that
could not be applied. Its payload is two maps: `buffer`, holding
`buffer.capacity-requested` (the capacity asked for) and
`buffer.capacity` (the capacity kept), and `outcome`, holding
`outcome.errno` as a negative signed integer — `-ENOMEM` when the
replacement rings could not be allocated, which is the usual case.
The swap is system-wide, so no CPU or ring is named. <a id="cite-config.swap-failed-event"></a>
Every failure is reported, not only allocation: a swap abandoned
because migration met a corrupt size field reports `-EIO`, and one the
kernel could not quiesce the CPUs for reports what `stop_machine`
returned. <a id="cite-config.swap-failed-every-errno"></a>

`kmes.config.applied` records a read of `Machine\System\KMES` that
reached the commit, after the rejection reports and the commit
itself. Its payload is three maps: `config`, holding `config.key.path`
and `config.counts` with the four counts `applied`, `retained-missing`,
`retained-invalid` and `ignored-unknown`; `buffer`, holding
`buffer.capacity`; and `emission`, holding `emission.rate-limit`. The
capacity and rate are read back after the commit, so they are what is
in force rather than what the plan asked for. <a id="cite-config.applied-event"></a>
A read whose capacity swap failed still reaches the commit — the other
three settings commit without it — so it is recorded as applied too,
with the capacity kept, beside the `kmes.buffer.swap.failed` that says
why. <a id="cite-config.applied-after-failed-swap"></a> `MaxEventSize` and
`MaxNestingDepth` in force are not in the record: the catalogue has no
field for either yet.

`kmes.config.refresh.failed` records a re-read, after the watch saw a
change, that failed: the source did not answer, answered with
something malformed, or the plan was refused (more than four rejection
reports, or a configuration the second gate rejects). Its payload is
`config`, holding `config.key.path`, and `outcome`, holding
`outcome.errno`. The configuration in force stays as it was. The
record is `essential`: the registry and the running kernel disagree
until the next change, and it is the only sign. A failed capacity swap
is not a failed read and does not produce one. <a id="cite-config.refresh-failed-event"></a>
A read that fails during the bootstrap refresh is not recorded this
way: it fails that refresh, which is traced and leaves the machine-root
fallback armed to try again (LCS [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)). The emission policy reports
a failed walk of `Machine\Generic\Events` with the same record ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

<a id="trm-2-6-3"></a>

## Bootstrap and watching <a id="cite-config.bootstrap-sequence"></a>

1. PKM loads. KMES initialises with compiled-in defaults and creates
   per-CPU rings at the default capacity. They are live immediately.
2. The first Machine-hive source registers, making LCS usable. KMES
   enumerates every value under `Machine\System\KMES\`.
3. Valid values are applied. A `BufferCapacity` differing from the
   current one drives a swap; a matching or absent one changes
   nothing.
4. KMES arms a persistent watch on the key through LCS's internal
   watch mechanism — a kernel-internal registration, not a
   userspace fd-based watch. Delivery is filtered to value-set and
   value-deleted notifications on the key itself, so changes in keys
   below `Machine\System\KMES` do not trigger a re-read. <a id="cite-config.watch-filtered-to-key"></a>
5. If the key does not exist yet, the fallback watch is armed on the
   Machine hive root and fires on subkey creation at any depth. When
   it fires, KMES re-runs the whole bootstrap: discover the key, read
   it, and re-arm the targeted watch. Deleting the key afterwards
   does not re-arm the fallback. <a id="cite-config.fallback-watch-on-hive-root"></a>
6. On subsequent changes — administrator edit, or a Group Policy push
   at a higher-precedence layer — the watch fires and KMES re-reads,
   validates, and applies or rejects.

<a id="trm-2-6-4"></a>

## Access to the configuration

The configuration keys inherit the Machine hive root security
descriptor, which grants `KEY_ALL_ACCESS` to SYSTEM and
Administrators and `KEY_READ` to Authenticated Users, so unprivileged processes cannot
change KMES's operational parameters. Enforcement is LCS's, not
KMES's — KMES reads values that LCS has already decided the caller
was entitled to write. Domain policy at a higher-precedence layer
provides defence against a compromised local administrator, since
creating a layer above precedence 0 requires SeTcbPrivilege.

The boot-time capacity is the compiled-in default and is not
separately configurable: making it so would need a channel to deliver
a value to the kernel before the registry exists. Once LCS is
available, capacity changes go through the ordinary swap. <a id="cite-config.boot-capacity-compiled-in"></a>

<a id="trm-2-b-4"></a>

## Configuration keys

Registry path `Machine\System\KMES\`. The type codes, defaults and
ranges are in [KMES ABI Reference](</kernel/userspace/native/kmes/generated-abi-tables.md#trm-2-a>); what each key does is here.

| Key | Effect |
|---|---|
| `BufferCapacity` | Per-CPU ring size in bytes. Must be a power of two. Changing it swaps every ring; see [Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>). |
| `MaxEventSize` | Largest event a syscall emitter may produce. |
| `MaxNestingDepth` | Deepest MessagePack container nesting the validator will accept. |
| `MaxEmitRatePerProcess` | Token-bucket rate, events per second, per process. |

`MaxEventSize`, `MaxNestingDepth` and `MaxEmitRatePerProcess` apply only
to syscall emitters. A kernel emitter is not rate-limited and its payload
is not parsed as MessagePack, but it is still checked structurally —
non-empty type string within `PKM_KMES_MAX_KERNEL_TYPE_LEN`, a payload
pointer if the length is non-zero, no size arithmetic overflow, and the
50% bound. A kernel event that fails is dropped with
`KMES_DROP_VALIDATE`, not emitted.

A key that is missing, of the wrong type, or out of range does not fail
the read: the previous value is retained and the disagreement is
recorded as an audit intent. At most four such intents are carried out
of one read, so a configuration with five bad keys reports four.

---

# Failure Modes

_Peios Kernel / Internals / KMES_

> Ring overrun, event drops, consumer crashes, buffer swap failure, LCS unavailability and clock discontinuity — what each does.

<a id="trm-2-7"></a>

KMES has no external trust boundary on the write path: kernel emitters
are trusted, and userspace emitters are validated at the syscall
boundary ([Syscall Interface](</kernel/userspace/native/kmes/emission-and-attachment-syscalls.md#trm-2-4>)). Its failure semantics are correspondingly simpler
than a subsystem like LCS that spans the kernel-userspace boundary in
both directions.

<a id="trm-2-7-1"></a>

## Ring overrun <a id="cite-failure.overrun-is-normal"></a>

When events are emitted faster than consumers drain them, the buffer
fills and KMES overwrites the oldest events. The write path is never
blocked and emission never fails from buffer pressure. Consumers see
the loss as gaps in the per-CPU sequence, and a consumer whose read
position has been overtaken re-anchors to the oldest surviving event.

Overrun is a normal operating condition under load, not an error: the
system degrades by keeping recent events, losing old ones, and telling
consumers that it did.

Two bulk-loss cases sit outside that model. The tail resynchronisation
guard ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>)) can discard an entire surviving window at once when a
size field reads back implausibly, and a shrinking capacity swap drops
the oldest events that do not fit the new ring. Neither itemises the
discarded events in the drop counter, though both are traced. <a id="cite-failure.bulk-loss-outside-drop-counter"></a>

<a id="trm-2-7-2"></a>

## Event drop

An event is dropped without reaching the buffer when a structural
limit is exceeded — an event type length that cannot be encoded in the
header's `u16` field, or an event larger than half the ring capacity —
and, for syscall emitters only, when the event exceeds `MaxEventSize`
or the payload fails msgpack validation.

The two paths differ in what a consumer sees. For kernel emitters the
sequence number is consumed before the structural checks run, so the
drop appears as a sequence gap; the emitting subsystem is not
notified, since emission is fire-and-forget. For syscall emitters
validation completes before the write phase, so no sequence number is
consumed and no gap appears — the drop is visible only to the caller,
as the syscall's error return. <a id="cite-failure.drop-visibility-differs"></a>

Events emitted before KMES initialisation completes are discarded with
no sequence consumed and no counter incremented, and are therefore
invisible to consumers in both ways.

The internal per-CPU dropped-event counter aggregates structural drops
and overwrite losses together. It is not exposed in the ring metadata
and is reachable only through the KUnit test interface.

<a id="trm-2-7-3"></a>

## Consumer crash <a id="cite-failure.consumer-crash-contained"></a>

A crashed consumer's mappings are cleaned up by the ordinary kernel
path when its file descriptors close on process exit, and the rings
themselves are reference-counted, so they survive until the last
reference goes. KMES is unaffected and keeps writing regardless of
whether any consumer is attached — a system with no consumers behaves
identically to one with consumers, events simply being stamped,
buffered, and eventually overwritten. A restarted consumer re-attaches
and sees every surviving event, with the outage visible as a sequence
gap.

<a id="trm-2-7-4"></a>

## Buffer swap failure

If replacement rings cannot be allocated, or the migration meets a
corrupt ring, the existing rings stay live at their current size, the
capacity change is not applied, no generation changes, and consumers
are unaffected. A `kmes.buffer.swap.failed` event records the
requested and retained capacities as `buffer.capacity-requested` and
`buffer.capacity`, and the error as `outcome.errno` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>)). KMES does
not retry; the next configuration write or a reboot triggers another
attempt.

<a id="trm-2-7-5"></a>

## Configuration that cannot be read

A re-read of `Machine\System\KMES` that fails keeps the configuration
in force, and a walk of the emission policy that fails keeps the mask
in force; each is recorded as `kmes.config.refresh.failed` ([Self-Configuration](</kernel/internals/kmes/self-configuration.md#trm-2-6>),
[Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)). Nothing retries on its own: the next change under the key reads
it again.

<a id="trm-2-7-6"></a>

## LCS unavailable <a id="cite-failure.lcs-never-required"></a>

If no source ever registers, KMES runs indefinitely on compiled-in
defaults with the boot-time rings live and the configuration watch
never armed. This is a valid operating mode, not a failure — the only
consequence is that the parameters cannot be tuned.

<a id="trm-2-7-7"></a>

## Clock discontinuity <a id="cite-failure.clock-jump-reorders-timestamps-only"></a>

Timestamps come from `CLOCK_REALTIME`, so an NTP adjustment can move
them forward or backward and consumers sorting by timestamp will see
an apparent reordering. Sequence numbers are unaffected: they are
independent monotonic counters, never derived from the clock, and
remain the reliable ordering primitive within a CPU. KMES neither
detects nor compensates for discontinuities. Cross-CPU ordering near a
jump is best-effort — an inherent cost of wall-clock timestamps,
accepted for their readability and cross-boot comparability. Rate
limiting is immune, being driven by the monotonic clock.

System suspend and hibernate are special cases of the same thing. Ring
contents survive suspend to RAM, and are restored from the hibernate
image on resume; in both cases the clock jumps forward by the sleep
duration, so consumers see a wall-clock gap with no sequence gap. <a id="cite-failure.suspend-no-sequence-gap"></a>

<a id="trm-2-7-8"></a>

## CPU topology <a id="cite-failure.topology-fixed-at-init"></a>

The set of rings is fixed at initialisation from the kernel's
possible-CPU set, and topology changes are not handled dynamically.

A CPU that was possible but offline at initialisation already has a
ring: if it comes online later, its events go to that ring, and
consumers can attach to it throughout. A CPU whose logical index was
outside the possible-CPU set has no ring, and `kmes_attach` rejects
that index; KMES neither creates rings for such CPUs nor publishes
topology-change notifications. A CPU taken offline through `cpu_online` keeps its ring,
and a consumer draining it simply sleeps indefinitely, unable to
distinguish a quiet CPU from a departed one. <a id="cite-failure.offline-cpu-ring-quiet"></a> Hot-add is the realistic
case — hypervisors adding vCPUs to a running guest — while hot-remove
is rare outside mainframes.

Anything that fixes this is additive: a topology-change notification,
whether a generation bump meaning "re-enumerate", a dedicated
descriptor, or a status field in the metadata page, fits the existing
attach-per-CPU design without changing the ring format, the event
format, or the emission API.

One structural caveat applies to attach discovery. The index bound is
the count of rings successfully created, while rings are indexed by
logical CPU id. On a system whose possible-CPU mask has holes, the two
differ: the "attach with incrementing indexes until `EINVAL`" loop
stops early, and rings at high logical indexes are unreachable.

Each logical CPU — each hardware thread under SMT — gets its own ring,
so ring memory scales with threads rather than cores: at the 4 MB
default a 64-core, 128-thread machine holds 512 MB of ring buffers.
This follows from events being emitted per logical CPU and `cpu_id`
naming the logical CPU.

<a id="trm-2-7-9"></a>

## Memory bounding

Ring memory in steady state is `num_cpus × BufferCapacity` for the
fixed CPU count fixed at initialisation, plus two metadata pages per CPU and one shmem page
per ring that has ever been attached. During a capacity swap old and
new rings coexist until every mapping of the old generation is
released.

Transient allocation during emission is bounded by the event size for
a single emit and freed as soon as the event is written. A batch is
different: every entry is staged in kernel memory simultaneously, so a
batch holds up to `count × MaxEventSize` — 256 entries at a 4 MB
maximum event size — until its write phase completes.

Each `kmes_attach` creates one file descriptor, bounded by
`RLIMIT_NOFILE` and by the SeSecurityPrivilege requirement. No
KMES-specific global memory cap exists; the capacity configuration and
standard Linux resource limits are the bounds.

<a id="trm-2-7-10"></a>

## Allocation and timing choices

The data region is a plain `vzalloc` allocation of 4 KB pages, and the
mmap handler inserts pages one at a time, so hugepage backing is not
available to it. The difference is substantial for TLB coverage: a 4 MB
ring needs 1024 standard pages against 2 hugepages, and because the
double mapping doubles the virtual range, 2048 standard pages against
4 hugepages. Allocation is not NUMA-aware: pages come from the
general allocator with no attempt to place a ring on the node local to
its CPU, so writes on a CPU whose ring landed on a remote node cross
the interconnect — roughly 100-150 ns against about 70 ns for a local
node. Timestamps use the full `ktime_get_real_ns()` rather
than `ktime_get_real_fast_ns()`, which avoids the timekeeper seqlock
and costs roughly 15-25 ns less per event at the price of being up to
one tick stale when a timer interrupt is updating the timekeeper
concurrently. Headers are built field by field
on every event with no precomputed per-CPU template, msgpack
validation is scalar, and each staged syscall event takes its own
`kvmalloc` rather than drawing on a per-CPU staging buffer.

None of these choices affects the ring format, the event header, or
the consumer protocol.

---

# Emission Policy

_Peios Kernel / Internals / KMES_

> How the kernel decides which of its own event types are switched on — the generated type table, the cached enabled mask, the walk of Machine\Generic\Events, the watch that keeps it current, and the tier defaults it runs on until the registry can be read.

<a id="trm-2-8"></a>

An event type that is switched off is never written. PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>) defines
the policy: a tree of keys under `Machine\Generic\Events`, one per
event-type segment, any of which may hold an `Enabled` `REG_DWORD` of
0 or 1, where the deepest value on a type's path decides and the
type's tier decides when there is none. This section is how the kernel
applies that policy to the event types it writes itself. Userspace
components apply it to their own types through libpeios, peios-rs and
libp-go; KMES does not enforce the policy on what userspace emits.

<a id="trm-2-8-1"></a>

## The kernel's event types

The kernel writes a closed set of event types, fixed when it is built.
They are generated from the kernel's own evman fragments
(`peios/packages/data/evman/*.evman`) by `peios/gen-kmes-event-table.py` into a C
header and a matching Rust module, each type with an id, its type
string and its tier. The generator has a `--check` mode, so a type
cannot change tier in its fragment without the kernel's table
following. <a id="cite-policy.closed-kernel-type-table"></a>

The policy is cached as a 64-bit mask with one bit per kernel type:
bit *i* set means type *i* is switched on. A walk of the registry
computes a whole new mask and publishes it with a single store, and an
emitter reads it with a single load, so a decision is a load and a bit
test and no lock is taken on any emission path. A mask is never
published half-computed. <a id="cite-policy.mask-one-bit-per-type"></a>

An emitter asks before it builds a payload, with
`pkm_kmes_event_enabled(id)`, and Rust emitters through the generated
module's `enabled()`. An `essential` type's tier is a compile-time
constant, so the check for it folds to *on* when the emitter is
compiled and never reads the mask: no policy can switch an essential
type off, whatever the tree holds. <a id="cite-policy.essential-never-consults"></a>
The policy and an event type's own gating — a SACL, an alarm mask, a
`REPORT` level — combine by AND, the policy first because it is the
cheaper of the two.

Every kernel emitter makes the check, and makes it first: before it
resolves the subject, looks up a path, sizes the payload or allocates
anything. A type that is switched off therefore costs one check and
nothing else, and the emitter carries on as though the record had been
written. Each emitter names its type with the generated table's string
rather than one of its own, so the type written and the type the policy
decided on cannot drift apart.

> [!NOTE]
> `kacs.impersonation.reverted` is the kernel's one `verbose` type, so on
> a machine whose policy says nothing about it, it is not written. An
> administrator who wants each revert recorded sets `Enabled` to 1 on
> `Machine\Generic\Events\kacs\impersonation\reverted`, or on a key
> above it.

<a id="trm-2-8-2"></a>

## Before the policy can be read

From the moment PKM initialises until a registry source for the
`Machine` hive has registered and the first walk has finished, the
mask holds the tier defaults: every `essential` and `standard` type on,
every `verbose` and `debug` type off. That is PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s rule for an
emitter that cannot read the policy, and the kernel writes events from
long before any source exists, so it is the policy the kernel runs on
for the whole of early boot. No event is ever held back to wait for
the registry. <a id="cite-policy.early-boot-tier-defaults"></a>

A `verbose` type the registry switches on is therefore not written
before the walk, and a `standard` type the registry switches off is. A
boot-time event that must be written whatever the policy says has the
`essential` tier and nothing else.

If `Machine\Generic\Events` does not exist, no `Enabled` value can be
found anywhere and the tier decides for every type: the kernel
publishes the tier defaults. A bootstrap refresh that finds the key
gone after it existed does the same, so deleting the key undoes the
policy it held. <a id="cite-policy.absent-key-is-tier-defaults"></a>

<a id="trm-2-8-3"></a>

## The walk

One walk resolves every kernel type at once. It reads `Enabled` on
`Machine\Generic\Events` itself, then descends the trie of the kernel
types' segments — `kacs`, `kacs\audit`, `kacs\audit\access` and so on
— looking up only the keys some kernel type's path passes through.
Each key that exists costs one `RSI_LOOKUP` and one `RSI_QUERY_VALUES`.
<a id="cite-policy.walk-follows-kernel-types"></a>

A key that does not exist ends the walk down that path, and nothing
beneath it is asked for: an empty `Events` key costs one query and one
lookup per root. A key that is a link is not followed and ends the
walk the same way. <a id="cite-policy.missing-key-ends-walk"></a>

Only an `Enabled` value that is a `REG_DWORD` holding 0 or 1 is a
setting. A value of another type, of the wrong length, or holding any
other number is ignored as though it were absent, and the setting
found above it stands. Nothing reports the ignored value. Value names
compare ignoring case, as the registry does.
<a id="cite-policy.enabled-dword-only"></a>

From what it read the walk computes the mask by PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s procedure:
for each type, the `Enabled` on the deepest existing key on its path
decides; with none, the tier decides; an essential type is on. The
mask is then published. <a id="cite-policy.resolution"></a> <a id="cite-policy.walk-publishes"></a>

A walk that fails — the source does not answer in time, or answers
with something malformed — publishes nothing. The mask in force stays,
whether that is the tier defaults or the last mask a walk computed,
and a `kmes.config.refresh.failed` record names
`Machine\Generic\Events` and the error. <a id="cite-policy.failed-walk-keeps-mask"></a>

<a id="trm-2-8-4"></a>

## Noticing a change

At bootstrap, after the KMES, layer, port reservation and network
policy keys, LCS discovers `Machine\Generic\Events` and walks it. If
it exists it gets an internal watch of its own; if not, the machine
root fallback watch stays armed (LCS [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)), and creating the key —
`Generic` and `Events` two levels below `Machine`, with or without
`Generic` already there — re-runs the bootstrap, which then walks it
and watches it. <a id="cite-policy.discovered-at-bootstrap"></a>

The watch covers the whole subtree at any depth, but it passes on only
what can change a kernel type: a change on `Events` itself, a change
beneath one of the kernel's five roots (`kacs`, `kmes`, `lcs`, `ntfe`,
`stratafs`), and among value changes only those to a value named
`Enabled`. A vendor writing under `Events\org\…`, which PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)
lets an emitter ignore, costs the kernel nothing.
<a id="cite-policy.watch-filtered-to-kernel-roots"></a>

What the watch passes on is coalesced. The first change of a burst
schedules one re-walk 50 ms later; changes that arrive before it runs
join it rather than postponing it, and a change that arrives while a
walk is running schedules the next one. **A change to the policy
applies within about 50 ms plus one walk** of the write that made it —
or, when a walk is already in progress, after that walk and one more —
however busy the tree is, which is inside PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)'s one second.
<a id="cite-policy.change-applies-within-50ms-plus-one-walk"></a>

A change is not retroactive. An event already written stays written,
and a decision made before the walk publishes stays made.

<a id="trm-2-8-5"></a>

## The shipped seed

The kernel package ships a registry seed, `event-policy.reg` in
`/usr/share/regim/`, that creates `Machine\Generic\Events` and sets no
`Enabled` anywhere: with nothing set, the tiers decide, which is the
policy a machine ships with. The key is there so the policy has a home
for an administrator to write beneath. Like every seed it is inert
until an image names it in `[registry] autoapply`, and until then
every emitter decides by tier just the same. <a id="cite-policy.seed-creates-key-without-enabled"></a>

The seed gives the key the SACL PGSS [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>) asks for, one that audits
writes: `S:(AL;CI;0x10002;;;WD)`, a `SYSTEM_ALARM` ACE for Everyone,
inherited by every key beneath, over `KEY_SET_VALUE | DELETE`. A handle
opened for writing anywhere in the policy tree carries that
continuous-audit mask, so each change to what is recorded can itself be
recorded. Only the SACL is set; the owner and DACL stay inherited from
the `Machine` hive. <a id="cite-policy.seed-sacl-audits-writes"></a>

---

# Overview

_Peios Kernel / Internals / LCS / Start here_

> LCS is the kernel half of the Peios registry — where it sits, its semantic core, what is layered and what is not, and where the model diverges.

<a id="trm-5-1"></a>

LCS — the Layered Configuration Subsystem — is the kernel half of the
Peios registry: a hierarchical, access-controlled configuration store
modelled on the Windows registry. It owns the namespace, the security
model, change observation, transactions, and the layer system that
gives the registry its name. It owns no storage at all.

Storage belongs to **sources**: userspace processes that hold registry
data and answer questions about it over the Registry Source Interface.
A source stores what it is told and returns everything it holds; it
never resolves layers, never filters by visibility, never sees the
identity of a caller, and never interprets a path beyond the parent and
child names it is given. Every decision about what a caller may see or
do is made in the kernel. loregd is the first source, and the one that
provides `Machine\` and `Users\` at boot, but nothing in LCS knows that:
hive routing is built entirely from what registers.

Userspace never talks to a source. Processes reach the registry through
three syscalls and eighteen ioctls, and the fd those syscalls return is
a capability — an open key carries the access mask it was granted, and
carries it wherever the fd goes.

<a id="trm-5-1-1"></a>

## Where it sits

LCS is a subsystem of PKM, peer to KACS and KMES, implemented in
`security/pkm/lcs` and built by `CONFIG_SECURITY_PKM` — a
boolean option, so it is linked into `vmlinux` rather than loaded. Its
three syscalls occupy 1100–1102 in the PKM range, registered in
`arch/x86/entry/syscalls/syscall_64.tbl`.

It depends on KACS and KACS does not depend on it. Every access
decision LCS makes is a call into the KACS AccessCheck function against
a Security Descriptor the source returned; LCS defines no access
control mechanism of its own. Security Descriptor inheritance at key
creation is likewise KACS's computation, not LCS's. Audit events go to
KMES.

A substantial part of LCS is Rust. The `lcs-core` implementation lives
in `security/pkm/lcs/lcs_core` and holds
the parts where correctness is a matter of pure decision rather than
kernel plumbing: layer resolution, the RSI wire codec, the backup
stream serialiser, the transaction mutation log, watch dispatch, case
folding, and configuration validation. The C half owns fds, the char
device, memory, locking, and the syscall boundary.

<a id="trm-5-1-2"></a>

## The semantic core

Six rules generate the rest of the model. Every behaviour described in
this chapter is a consequence of one of them.

1. **Names are layered.** A key's presence at a path is per-layer.
   Different layers can name different keys at the same path, and
   removing a layer removes its names.
2. **Values are layered.** Every write is tagged with a layer; the
   effective value is the highest-precedence entry. Tombstones can
   actively mask lower layers.
3. **Key identity is not layered.** A key's GUID, Security Descriptor,
   volatile flag, symlink flag and last write time belong to the key
   object, not to any layer, and are never automatically reverted.
4. **Security is key-bound, not layer-bound.** Modifying a Security
   Descriptor is a permanent change to the key. Removing a layer does
   not revert it. Security policy is operational state, not
   configuration overlay.
5. **Handles are capabilities granted at open.** An open key fd carries
   an access mask computed once, by AccessCheck, at open time. Later
   operations test the mask, not the descriptor. Changing a descriptor
   does not affect an fd that already exists.
6. **Sources persist, the kernel decides meaning.** A source stores
   path entries, key records and value entries and returns all of them.
   Everything else is the kernel's.

The consequence that surprises people most often is the fourth. A
layer is a configuration overlay and reverts cleanly; an access control
change is not configuration and does not.

<a id="trm-5-1-3"></a>

## What is layered and what is not

| Property | Layered | Resolved by | Survives layer deletion |
|---|---|---|---|
| Path existence | Yes | Highest precedence, then highest sequence | No |
| Values | Yes | Highest precedence, then highest sequence | No |
| Value tombstones | Yes | Masking lower precedence | No |
| Blanket tombstones | Yes | Masking all lower-precedence values on the key | No |
| Key hiding | Yes | Masking lower precedence | No |
| Key GUID | No | Direct on the key object | Yes |
| Security Descriptor | No | Direct on the key object | Yes |
| Volatile flag | No | Direct on the key object | Yes |
| Symlink flag | No | Direct on the key object | Yes |
| Last write time | No | Direct on the key object | Yes |

A watch is bound to the key object rather than to either, and stays on
that object whatever happens to the name ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

<a id="trm-5-1-4"></a>

## registry.pol

One external format constrains the design. `registry.pol` is the binary
format Active Directory Group Policy uses to deliver configuration to
domain-joined machines, and the registry exists so that Peios can
consume it without loss. Everything `registry.pol` can express, the
registry can represent.

Three consequences run all the way through:

- The **full Windows value type set** is supported, including the three
  hardware-resource types that carry no Peios semantics at all. They
  behave exactly as `REG_BINARY`; they exist so a value copied from a
  Windows hive round-trips with its type tag intact ([Values](</kernel/internals/lcs/data-model/values.md#trm-5-2-6>)).
- **Paths are backslash-separated, case-preserving and
  case-insensitive.** This is not negotiable and it is the reason case
  folding appears in the kernel at all ([Names and Case](</kernel/internals/lcs/data-model/names-and-case.md#trm-5-2-8>)).
- **Registry access rights occupy the Windows bit positions**, so a
  Security Descriptor containing registry ACEs is binary-compatible
  ([Access Rights](</kernel/internals/lcs/security/access-rights.md#trm-5-4-2>)).

Tombstones and blanket tombstones exist for the same reason: the
`**Del.ValueName` and `**DelVals` directives express *absence*, which a
purely additive overlay cannot ([Tombstones](</kernel/internals/lcs/data-model/tombstones.md#trm-5-2-7>)).

LCS does not parse `registry.pol`. Parsing is a userspace concern; LCS
provides the model that makes a faithful translation possible.

No other parity with Windows is claimed. The binary compatibility of a
Security Descriptor is a KACS guarantee, not an LCS one.

<a id="trm-5-1-5"></a>

## Where the model diverges from Windows

LCS is modelled on the Windows Configuration Manager, and departs from
it in seven places. All seven are decisions rather than gaps.

| | Windows | LCS |
|---|---|---|
| Backing store | Kernel-internal hive files | Userspace sources over the RSI, so a storage backend is not a kernel change |
| Hive routing | A fixed set of predefined hives | Any source may register any name at runtime |
| Layers | None; `registry.pol` is applied by flattening values | Precedence-ordered layers with tombstones, resolved at query time, so removal reverts rather than tattoos |
| Change observation | `RegNotifyChangeKeyValue`, single-shot | Persistent watches, closing the re-registration race |
| Key identity | Hive cell offsets | GUIDs, stable across storage reorganisation |
| Forward slash | Not accepted | Accepted on input, normalised to backslash |
| Case comparison | `RtlCompareUnicodeString` | Unicode Simple Case Folding, pinned to a version |

<a id="trm-5-1-6"></a>

## Windows features that are absent

Four have been evaluated and deliberately excluded.

**Key classes.** The `class` parameter of `RegCreateKeyEx` is
documented by Microsoft as reserved, and no consumer of it is known.

**`RegOverridePredefKey`.** Per-process key redirection, and specific
to COM. It would require unbounded per-process state in the kernel, and
private hives and private layers cover the uses that are legitimate.

**WoW64 redirection.** Splitting keys by pointer width. Peios has no
32-bit compatibility concern to split for.

**The `HKEY_CLASSES_ROOT` merged overlay.** A merge of `HKLM` and
`HKCU` `Software\Classes`, again COM-specific, with no Peios
equivalent.

<a id="trm-5-1-7"></a>

## This chapter

[Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>) covers the data model — hives, keys, path entries, values,
tombstones, names, and what happens to a key that loses its last name.
[The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>) covers layers: the model, the base layer, where layer metadata
lives and the circularity that implies, who may write into a layer, and
the resolution algorithm and the sequence counter that drives it. [The Access Flow](</kernel/internals/lcs/security/the-access-flow.md#trm-5-4-1>)
covers security: the access flow, the rights, inheritance, and the audit
events LCS emits. [The Fd Model](</kernel/userspace/native/lcs/file-descriptors-and-buffer-conventions.md#trm-5-5-1>) covers the syscall and ioctl interface and the
error model. [The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md#trm-5-6-1>) covers watches, [Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>) transactions, and [The Source Model](</kernel/internals/lcs/sources/the-source-model.md#trm-5-8-1>) the source
model — registration, dispatch, validation, and the intricate business
of what a late response means. [The Stream](</kernel/internals/lcs/backup-and-restore/the-stream.md#trm-5-9-1>) covers backup and restore, [The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>) how
LCS configures itself out of the registry it is serving, and [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>) the
ABI.

Two contracts extracted from LCS are specified rather than described,
because a third party implements the other side of each: the Registry
Source Interface and the registry backup format. Both are chapters of
PSPK.

<a id="trm-5-b-2"></a>

## Build configuration

LCS is built by `CONFIG_SECURITY_PKM`, a boolean option, so it is linked
into `vmlinux` rather than loaded. <a id="cite-lcs-abi-notes.built-in-by-config-security-pkm"></a>

`CONFIG_RUST=y` is required: the resolution core, the RSI codec, the
backup serialiser and the transaction log are Rust, implemented in
`security/pkm/lcs/lcs_core`. <a id="cite-lcs-abi-notes.requires-config-rust"></a>

`CONFIG_SECURITY_PKM_KUNIT` compiles in the in-kernel test
harness. <a id="cite-lcs-abi-notes.kunit-option-compiles-test-harness"></a>

The three syscall numbers are registered in
`arch/x86/entry/syscalls/syscall_64.tbl` and the corresponding table
under `tools/perf/`. <a id="cite-lcs-abi-notes.syscall-numbers-added-by-patch"></a>

They are registered `common`, so the same row serves the x32 ABI
wherever that ABI is built in; the Peios kernel does not build it. <a id="cite-lcs-abi-notes.syscalls-registered-common"></a>

## Related explanations

- [File descriptors and buffer conventions](</kernel/userspace/native/lcs/file-descriptors-and-buffer-conventions.md>)

## Calling the subsystem

The [native LCS interface reference](</kernel/userspace/native/lcs/overview.md>) collects the caller contracts and generated ABI tables.

## Topics

- [Data model](</kernel/internals/lcs/data-model/overview.md>)
- [Layers](</kernel/internals/lcs/layers/overview.md>)
- [Security](</kernel/internals/lcs/security/overview.md>)
- [Watches](</kernel/internals/lcs/watches/overview.md>)
- [Transactions](</kernel/internals/lcs/transactions/overview.md>)
- [Sources](</kernel/internals/lcs/sources/overview.md>)
- [Backup and restore](</kernel/internals/lcs/backup-and-restore/overview.md>)
- [Bootstrap](</kernel/internals/lcs/bootstrap/overview.md>)

---

# Data model

_Peios Kernel / Internals / LCS / Data model_

> Find the Peios kernel articles about data model.

Use these articles to understand data model in the Peios kernel.

- [Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md>)
- [Private Hives](</kernel/internals/lcs/data-model/private-hives.md>)
- [Keys](</kernel/internals/lcs/data-model/keys.md>)
- [Symlinks](</kernel/internals/lcs/data-model/symlinks.md>)
- [Path Entries](</kernel/internals/lcs/data-model/path-entries.md>)
- [Values](</kernel/internals/lcs/data-model/values.md>)
- [Tombstones](</kernel/internals/lcs/data-model/tombstones.md>)
- [Names and Case](</kernel/internals/lcs/data-model/names-and-case.md>)
- [Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md>)

---

# Hives and Routing

_Peios Kernel / Internals / LCS / Data model_

> A hive is the first component of every path — the routing table that maps hive names to sources, and the two names the kernel knows itself.

<a id="trm-5-2-1"></a>

A hive is a top-level namespace — the first component of every registry
path. LCS keeps a routing table mapping hive names to registered
sources, and that table is built entirely from what registers. There is
no static configuration. <a id="cite-hive.routing-table.built-from-registrations"></a>

| Field | Description |
|---|---|
| Name | The hive name, e.g. `Machine`, `Users`. Case-preserving, compared case-insensitively. <a id="cite-hive.field.name-case-insensitive"></a> |
| Root GUID | The GUID of the hive's root key, supplied by the source at registration. <a id="cite-hive.field.root-guid-supplied-by-source"></a> |
| Source | The source slot backing this hive. |
| Status | Active or Unavailable, tracking source connectivity. <a id="cite-hive.field.status-active-or-unavailable"></a> |

Status is a property of the source slot rather than of the individual
hive, which amounts to the same thing: a slot's hives are exactly one
source's, and they go Down together. <a id="cite-hive.status-is-per-source-slot"></a>

<a id="trm-5-2-1-1"></a>

## Route identity

A hive route is identified by the pair **(case-folded name, scope)**,
where the scope is either the global namespace or one private scope
GUID. <a id="cite-hive.route-identity.name-and-scope"></a>

That pair must be unique across every registered source; a source
claiming one another source already holds is rejected. <a id="cite-hive.route-identity.must-be-unique"></a>

The same name may appear in different scopes, which is precisely how a
private hive shadows a global one without colliding with it. <a id="cite-hive.route-identity.same-name-in-different-scopes"></a>

A hive is backed by exactly one source. A source may back many. <a id="cite-hive.one-source-per-hive"></a>

<a id="trm-5-2-1-2"></a>

## Routing a path

LCS takes the first component of a path — everything before the first
separator — and looks it up. <a id="cite-hive.routing.uses-first-component"></a>

- Registered and active routes to the backing source. <a id="cite-hive.routing.active-routes-to-source"></a>
- Not registered is `ENOENT`. <a id="cite-hive.routing.unregistered-is-enoent"></a>
- Registered but Down is `EIO`. <a id="cite-hive.routing.down-is-eio"></a>

Before any source registers, the table is empty and every path yields
`ENOENT` ([The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>)).

<a id="trm-5-2-1-3"></a>

## `CurrentUser` is not a hive

`CurrentUser\` is a kernel-level alias. When a caller-supplied absolute
path starts with it, LCS reads the user SID from the calling thread's
effective token and rewrites the path to `Users\<SID>\...` before
routing. <a id="cite-hive.currentuser.rewrites-to-users-sid"></a>

The rewritten path is re-checked against the total-length limit, since
a textual SID is longer than the alias it replaced. <a id="cite-hive.currentuser.rewritten-path-rechecked-for-length"></a>

Three constraints keep this safe.

It applies **only to the first component** of a path, and only to a
caller-supplied absolute one. <a id="cite-hive.currentuser.first-component-of-caller-path-only"></a>

It does **not** apply to symlink targets: a target beginning with
`CurrentUser\` is followed literally, routes as a hive of that name,
and finds nothing. <a id="cite-hive.currentuser.not-applied-to-symlink-targets"></a> Without that rule, a symlink
containing `CurrentUser\` would redirect a privileged service into the
service's own user hive — a confused deputy.

And `CurrentUser` cannot be registered as a hive name. LCS rejects the
registration with `EINVAL`, so the alias can never collide with a real
hive. <a id="cite-hive.currentuser.cannot-be-registered-einval"></a>

Symlink targets *are* subject to ordinary hive routing, private hives
included. <a id="cite-hive.symlink-targets-use-ordinary-routing"></a> A sandboxed process resolving a symlink sees the same
registry through it that it sees directly, which is the point of
sandboxing it.

<a id="trm-5-2-1-4"></a>

## Two names the kernel knows

LCS is source-agnostic about routing but not entirely ignorant of
names. `Users` is compiled in as the target of `CurrentUser\`
rewriting. `Machine` is matched, case-insensitively and only for a
global hive, to decide when to run the bootstrap refresh that reads
LCS's own configuration ([The Boot Sequence](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-2>)).

Neither is a routing decision — an unregistered `Machine` routes
nowhere like any other name — but the two names do exist in the kernel. <a id="cite-hive.known-names.get-no-routing-privilege"></a>

In practice loregd registers `Machine` and `Users` at boot. Other
sources may register other hives at any time.

<a id="trm-5-2-1-5"></a>

## Names

Hive names follow the same rules as key name components: no backslash,
no forward slash, no null byte, valid UTF-8, non-empty, and no longer
than `MaxPathComponentLength`. <a id="cite-hive.name.follows-key-component-rules"></a> They are case-preserving and compared
case-insensitively ([Names and Case](</kernel/internals/lcs/data-model/names-and-case.md#trm-5-2-8>)).

---

# Private Hives

_Peios Kernel / Internals / LCS / Data model_

> Hives invisible in the global namespace, reachable only through a scope GUID on the calling token — routing, lifecycle and registration rules.

<a id="trm-5-2-2"></a>

A private hive is registered with the `RSI_HIVE_PRIVATE` flag and a
scope GUID. <a id="cite-private-hive.registered-with-flag-and-scope-guid"></a>

It is invisible in the global namespace and reachable only by a thread
whose token carries that scope GUID. <a id="cite-private-hive.invisible-globally-and-scope-gated"></a>

<a id="trm-5-2-2-1"></a>

## Routing

Private hives are checked **before** global ones. <a id="cite-private-hive.routing.checked-before-global"></a>

For each scope GUID on the calling thread's token, in the order the
token carries them, LCS looks for a private hive with the path's name
and that scope. The first match wins. Only if none matches is the
global table consulted. <a id="cite-private-hive.routing.token-order-first-match-wins"></a>

A private hive can therefore shadow a global one, and no name is exempt
— a thread with a private `Machine\` sees the private one. <a id="cite-private-hive.routing.shadows-any-global-name"></a> That is what
makes complete registry isolation possible for a container or a
sandbox without giving it a differently-named hive to notice.

`MaxScopeGUIDsPerToken`, default 8, bounds the per-syscall iteration
cost; a token above the cap fails every registry operation with `E2BIG`
([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-private-hive.scope.max-guids-per-token"></a> Duplicate scope GUIDs on a token are rejected.

<a id="trm-5-2-2-2"></a>

## Scope GUIDs on a token

Scope GUIDs reach a thread through the KACS token's LCS credential
extension: a versioned block in the token specification carrying the
thread's scope GUIDs and its private layer names ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). It parses at
a fixed offset, and:

- rejects a nil scope GUID; <a id="cite-private-hive.credential.rejects-nil-guid"></a>
- rejects duplicate scope GUIDs; <a id="cite-private-hive.credential.rejects-duplicate-guids"></a>
- caps the count at 256 — a hard KACS limit, above the configurable
  LCS one. <a id="cite-private-hive.credential.caps-count-at-256"></a>

The credentials propagate across fork, duplication and impersonation
like the rest of the token. <a id="cite-private-hive.credential.propagates-across-fork-and-impersonation"></a>

Attaching them is gated by `SeCreateTokenPrivilege`, because scope
GUIDs can only enter a token when the token is created. <a id="cite-private-hive.scope.attaching-gated-by-secreatetokenprivilege"></a> That is a
blanket privilege rather than a per-scope authorisation: a caller that
can create tokens at all can create one claiming any scope. Isolation
between private hives therefore rests on who may create tokens, not on
who owns a scope.

<a id="trm-5-2-2-3"></a>

## Scope lifecycle

A scope GUID is an opaque 128-bit value with no lifecycle. LCS neither
creates nor tracks one; it only compares. <a id="cite-private-hive.scope.opaque-and-untracked-by-lcs"></a> A scope exists as long as
some private hive or some token references it, and when the last
reference goes it is simply a number nobody uses.

Nothing in the kernel generates scope GUIDs. <a id="cite-private-hive.scope.not-generated-by-kernel"></a> Key GUIDs and token GUIDs
come from the kernel's UUIDv4 generator; scope GUIDs are supplied by
userspace, and choosing them unpredictably is userspace's
responsibility.

<a id="trm-5-2-2-4"></a>

## Registration rules

Registration enforces more than the route-identity uniqueness of
[Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>) — the full list is [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>), and the rules that exist for private
hives are these:

- A hive's root GUID may not be nil.
- The root GUIDs within one registration request must be
  distinct.
- A hive without the `RSI_HIVE_PRIVATE` flag may not carry a non-nil
  scope GUID.
- A hive **with** the flag may not carry a nil one. <a id="cite-private-hive.registration.private-hive-requires-scope-guid"></a> No token
  can carry a nil scope GUID, so such a hive would be registrable and
  then permanently unroutable — holding its name against other sources
  in that scope while every lookup returned `ENOENT`.
- Unknown flag bits are rejected.
- Opening `/dev/pkm_registry` at all requires an **enabled**
  `SeTcbPrivilege`, checked in the device's `open()` handler
  ([Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>)).

---

# Keys

_Peios Kernel / Internals / LCS / Data model_

> A key is a container of subkeys and values — its identity, its properties, volatile keys, and the rules for naming one.

<a id="trm-5-2-3"></a>

A key is a node in the hierarchy: a container holding subkeys and
values. The filesystem analogy is an inode. A key carries identity and
properties; naming lives in path entries ([Path Entries](</kernel/internals/lcs/data-model/path-entries.md#trm-5-2-5>)).

| Field | Mutable | Layered | Description |
|---|---|---|---|
| GUID | No | No | Identity, assigned by LCS at creation, persisted by the source. |
| Name | No | No | The key's own name component. Informational; the path entry resolves the identity. `QUERY_KEY_INFO` preserves this spelling only when it folds to that resolved leaf, and audits and refuses a mismatch with `EIO`. <a id="cite-key.field.name-is-informational"></a> |
| Parent GUID | No | No | The parent key. Nil for a hive root. <a id="cite-key.field.parent-guid-nil-for-hive-root"></a> |
| Security Descriptor | Yes | No | Computed from the parent at creation; changed at runtime with `WRITE_DAC` / `WRITE_OWNER`. <a id="cite-key.field.security-descriptor-computed-from-parent"></a> |
| Last write time | Yes | No | Updated when a value is written or deleted or the descriptor changes. <a id="cite-key.field.last-write-time-updates"></a> |
| Volatile | No | No | The source stores this key in non-persistent storage only. |
| Symlink | No | No | This key is a symbolic link ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)). |

**No key property is layer-qualified.** Properties belong to the object. <a id="cite-key.no-property-is-layer-qualified"></a>
Changing a key's structural type through a layer is not a matter of
setting a flag; the layer hides the original key and creates a new one
at the same path, which is the ordinary overlay pattern.

<a id="trm-5-2-3-1"></a>

## Identity

A key's identity is its GUID, not its path. Two keys occupying the same
path at different times are different objects with different GUIDs. <a id="cite-key.identity.is-guid-not-path"></a> A
path is a name that maps to an identity; the identity outlives the
name.

GUIDs are assigned by LCS — never by a source — and pushed to the
source at creation, where they become the primary key of its
storage. <a id="cite-key.identity.guid-assigned-by-lcs-not-source"></a>

Once a path has been resolved to a GUID at open time, every subsequent
RSI operation uses the GUID directly. <a id="cite-key.identity.rsi-uses-guid-after-open"></a>

The generator is the kernel's version-4 GUID generator: random bytes
from the kernel CSPRNG with the version and variant bits set in the
PCDS layout — the version nibble in the high nibble of byte 7, because
`Data3` is little-endian in bytes 6–7, and the variant bits in byte 8. <a id="cite-key.identity.guid-generator-is-uuidv4"></a>

Freshness is the collision resistance of UUIDv4 plus a check against
the keys LCS currently tracks, with a bounded retry. <a id="cite-key.identity.freshness-checked-against-tracked-keys"></a>

There is **no persistent retired-GUID catalogue**, and no code anywhere
that would maintain one. A GUID dropped by orphan cleanup is not
remembered. <a id="cite-key.identity.no-retired-guid-catalogue"></a>

If a source answers `RSI_CREATE_KEY` for a freshly generated GUID with
`RSI_ALREADY_EXISTS`, that is not a race to retry — the kernel believes
the GUID is unused and the source disagrees. LCS treats it as source
inconsistency and fails closed with `EIO`. <a id="cite-key.identity.create-key-already-exists-is-eio"></a>

It is never retried as an open and `EEXIST` never reaches userspace
from `reg_create_key`. <a id="cite-key.identity.no-eexist-from-reg-create-key"></a>

A GUID appears at exactly one canonical location. LCS validates that
and rejects a source that reports otherwise.

<a id="trm-5-2-3-2"></a>

## Volatile keys

Volatile is a flag LCS carries and forwards. Storing a volatile key in
non-persistent storage is the source's obligation; nothing in the
kernel enforces it. <a id="cite-key.volatile.storage-is-the-source-obligation"></a>

What the kernel does enforce is the containment rule: **a non-volatile
key may not be created under a volatile parent** (`EINVAL`). <a id="cite-key.volatile.non-volatile-under-volatile-parent-is-einval"></a>

The converse is allowed — a volatile key under a persistent parent is
ordinary. <a id="cite-key.volatile.volatile-under-persistent-parent-allowed"></a>

<a id="trm-5-2-3-3"></a>

## Naming

Three bytes are forbidden in a key name component: backslash and
forward slash, both of which are separators, and the null
byte. <a id="cite-key.name.three-forbidden-bytes"></a>

Every other valid UTF-8 sequence is permitted, spaces and arbitrary
Unicode included. <a id="cite-key.name.any-other-utf8-permitted"></a>

Empty components are forbidden, which rules out a leading separator and
consecutive separators (`Machine\\System`). <a id="cite-key.name.empty-components-forbidden"></a>

A trailing separator (`Machine\System\`) is likewise
invalid. <a id="cite-key.name.trailing-separator-invalid"></a>

Length limits are byte counts: `MaxPathComponentLength` per component,
`MaxTotalPathLength` for the whole path, `MaxKeyDepth` for nesting.

Forward slash normalisation is achieved by treating `/` as a separator
wherever a separator is recognised, rather than by rewriting the string
— so a materialised component never contains either separator, and the
canonical form is per-component rather than a canonicalised string.

---

# Symlinks

_Peios Kernel / Internals / LCS / Data model_

> The two load-bearing mechanisms behind a symlink key — the structural flag and the target value — plus resolution, depth and opening the link itself.

<a id="trm-5-2-4"></a>

A symlink key uses two mechanisms, and both are load-bearing.

The **symlink flag** on the key record marks the key's structural type.
It is set at creation by `REG_OPTION_CREATE_LINK` and is immutable
afterwards. <a id="cite-symlink.flag.set-at-creation-and-immutable"></a>

`RSI_WRITE_KEY` can update only the descriptor and the last write time,
so there is no operation that could change it. <a id="cite-symlink.flag.rsi-write-key-cannot-change-it"></a>

The **default value, of type `REG_LINK`,** supplies the target
path. <a id="cite-symlink.target.is-the-reg-link-default-value"></a>

It is an ordinary layered value, which means a higher-precedence layer
can redirect a symlink by writing a different `REG_LINK` default value,
and removing that layer restores the original target. <a id="cite-symlink.target.layer-can-redirect-and-revert"></a>

The flag marks identity; the value provides the target.

<a id="trm-5-2-4-1"></a>

## Resolution

LCS follows symlinks during path resolution and the fd it returns
refers to the resolved target — its GUID, its position in the tree, its
ancestor chain — not to the link. <a id="cite-symlink.resolution.fd-refers-to-the-target"></a>

The target is resolved by issuing a separate `RSI_QUERY_VALUES` for the
key's default value (the empty name) and applying ordinary layer
resolution to the result, so the target participates in the layer
system exactly as any other value does. <a id="cite-symlink.resolution.target-read-with-layer-resolution"></a>

If the effective default value is missing, or is not of type
`REG_LINK`, resolution fails with `EINVAL`. <a id="cite-symlink.resolution.missing-or-wrong-type-is-einval"></a>

LCS does **not** validate the type at write time: a layer that writes a
`REG_SZ` default value over a symlink's target breaks resolution at the
next open, and removing that layer fixes it. <a id="cite-symlink.resolution.target-type-not-validated-at-write-time"></a>

The offending value stays in the registry; a failed resolution writes
nothing. <a id="cite-symlink.resolution.failed-resolution-writes-nothing"></a>

<a id="trm-5-2-4-2"></a>

## The target path

The `REG_LINK` payload is a length-delimited UTF-8 registry path. No
trailing null is required or permitted — the length delimits it, and a
null byte inside that length is rejected like any
other. <a id="cite-symlink.target-path.length-delimited-no-trailing-null"></a> Forward
slashes are handled as separators as everywhere else.

The target is validated with exactly the same rules as a syscall path:
UTF-8, no null bytes, per-component and total length, no empty
components, no trailing separator, maximum depth. <a id="cite-symlink.target-path.validated-like-a-syscall-path"></a> The only difference
is that a syscall path arrives null-terminated and has its terminator
stripped first.

A target is always interpreted as absolute — its first component is
routed as a hive name. <a id="cite-symlink.target-path.always-absolute"></a>

Resolution has no check that rejects a relative-looking target as
malformed. A target of `Sub\Key` is not an error; it is a request for a
hive named `Sub`, and it yields `ENOENT` unless such a hive happens to
be registered, in which case it resolves there. <a id="cite-symlink.target-path.relative-looking-target-not-rejected"></a>

Writing one is different. `REG_IOC_SET_VALUE` of a `REG_LINK` value
routes the target's first component at write time, with the writer's
scope GUIDs, and answers `EINVAL` if it names no registered hive. That
is what stops a dangling target being captured later by whoever
registers a private hive of that name: a target that cannot be written
cannot be captured, and the failure lands on whoever authored it. The
cost is that a symlink cannot forward-reference a hive registered after
it. A target that arrives in source data or a backup stream is not
gated, which is why resolution still has to treat the shape as a hive
request. <a id="cite-symlink.target-path.write-time-routing-gate"></a>

`CurrentUser\` rewriting is not applied ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)), so a target beginning
with `CurrentUser\` routes as a hive of that name and cannot be
registered, and therefore always fails. Ordinary hive routing does
apply, private hives included, for the resolving thread.

<a id="trm-5-2-4-3"></a>

## Depth

Symlink resolution is bounded by `SymlinkDepthLimit`, default 16,
configurable from 1 to 64. Exceeding it is `ELOOP`. <a id="cite-symlink.depth.exceeding-the-limit-is-eloop"></a>

<a id="trm-5-2-4-4"></a>

## Opening the link itself

`REG_OPEN_LINK` on `reg_open_key` opens the symlink key rather than
following it, which is how a symlink is managed at all — deleted,
retargeted, inspected. <a id="cite-symlink.open-link.opens-the-link-not-the-target"></a>

It applies to the **final path component only**. A symlink encountered
part-way along a path is followed whether or not the flag is
set. <a id="cite-symlink.open-link.final-component-only"></a>

The access check follows the same rule: with `REG_OPEN_LINK` the check
is against the link, otherwise against the target. <a id="cite-symlink.open-link.access-check-follows-the-flag"></a>

<a id="trm-5-2-4-5"></a>

## Creation

Creating a symlink needs all of:

- `KEY_CREATE_SUB_KEY` on the parent, as for any key; <a id="cite-symlink.create.requires-key-create-sub-key"></a>
- `KEY_CREATE_LINK` on the parent; <a id="cite-symlink.create.requires-key-create-link"></a>
- either an enabled `SeTcbPrivilege` or membership of Administrators. <a id="cite-symlink.create.requires-setcbprivilege-or-administrators"></a>

The last is a genuine disjunction — either satisfies it — and the
privilege branch marks the privilege used. <a id="cite-symlink.create.privilege-branch-marks-privilege-used"></a>

Failing it is `EPERM`. <a id="cite-symlink.create.failure-is-eperm"></a>

---

# Path Entries

_Peios Kernel / Internals / LCS / Data model_

> Key existence and naming are layer-qualified while key identity is not — the per-layer path entry that separates them, and hiding.

<a id="trm-5-2-5"></a>

Key existence and naming are layer-qualified; key identity is not. The
source stores a **path entry** per layer, which separates the two. <a id="cite-path-entry.existence-and-naming-are-layer-qualified"></a> The
overlay-filesystem analogy is exact: directory entries are per-layer,
inodes are shared.

| Field | Description |
|---|---|
| Parent GUID | The parent key. |
| Child name | The key's name under that parent — one component, not a path. <a id="cite-path-entry.field.child-name-is-one-component"></a> |
| Layer | The layer this entry belongs to. |
| Target | The GUID of the key at this path in this layer, or HIDDEN. <a id="cite-path-entry.field.target-is-a-guid-or-hidden"></a> |
| Sequence | A monotonic number assigned by LCS at creation, used for tiebreaking within a precedence tier. |

On the wire a HIDDEN entry is a target type of 1 with an all-zero GUID
([LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>)). <a id="cite-path-entry.hidden.wire-form-is-type-1-and-zero-guid"></a>

A source returning a non-zero GUID on a HIDDEN entry is returning
malformed data. <a id="cite-path-entry.hidden.non-zero-guid-is-malformed"></a>

<a id="trm-5-2-5-1"></a>

## Creating a key

Creating a key in a layer always assigns a fresh GUID and produces two
records: a path entry `(parent, name, layer) → GUID` with a new
sequence number, and a key record carrying that GUID. <a id="cite-path-entry.create.fresh-guid-and-two-records"></a>

LCS sends `RSI_CREATE_ENTRY` first and `RSI_CREATE_KEY`
second. <a id="cite-path-entry.create.entry-before-key"></a>

That order matters for the race: if another caller got there first, the
entry creation returns `RSI_ALREADY_EXISTS` and LCS retries the whole
thing as an open, reporting `REG_OPENED_EXISTING`. <a id="cite-path-entry.create.entry-already-exists-retries-as-open"></a> Failure on the
*second* call, for a GUID LCS just minted, is not a race and fails
closed ([Keys](</kernel/internals/lcs/data-model/keys.md#trm-5-2-3>)).

If a different layer already has a key at that path, the new layer gets
its own distinct GUID. Each layer has its own key object, and
resolution decides which is visible. <a id="cite-path-entry.create.other-layer-gets-a-distinct-guid"></a>

**No operation creates a path entry pointing at an existing GUID.**
`reg_create_key` always mints a new one. The namespace is a tree, never
a graph. <a id="cite-path-entry.create.never-points-at-an-existing-guid"></a>

<a id="trm-5-2-5-2"></a>

## No GUID sharing across layers

The path table's shape would technically permit two entries referencing
one GUID, which would be a hard link. No API exposes it. <a id="cite-path-entry.no-hard-links.no-api-exposes-guid-sharing"></a>

Every key has exactly one canonical parent and name, and LCS validates
that a source is not reporting otherwise: the key record's parent must
be the parent the key was reached through, and its name must fold to the
component the key was reached by. A record that says otherwise is
malformed key metadata — `REG_IOC_QUERY_KEY_INFO` answers
`EIO` and the source-data validation failure is audited. <a id="cite-path-entry.no-hard-links.one-canonical-parent-and-name"></a>

Aliasing has an explicit, visible mechanism, and it is symlinks. Hard
links would make parent-GUID semantics, descriptor inheritance, subtree
enumeration and watch dispatch all ambiguous at once.

<a id="trm-5-2-5-3"></a>

## Hiding

A layer can create a HIDDEN entry at a path, making the key invisible
regardless of what lower-precedence layers say. <a id="cite-path-entry.hiding.hidden-entry-makes-a-key-invisible"></a>

It is the path-level equivalent of a value tombstone, and when the
hiding layer is removed the lower key reappears. <a id="cite-path-entry.hiding.removing-the-layer-restores-the-lower-key"></a>

A HIDDEN entry gets a sequence number like any other entry, so a
conflict between a GUID entry in one layer and a HIDDEN entry in
another at the same precedence resolves deterministically: the higher
sequence number wins. <a id="cite-path-entry.hiding.hidden-entry-carries-a-sequence-number"></a>

<a id="trm-5-2-5-4"></a>

## Hide and replace

A single layer can hide an existing key and put a new one at the same
path, and no special mechanism is needed for it. The layer creates its
own path entry pointing at its own new GUID; lower-precedence entries
for the same `(parent, name)` are masked because this layer's entry
wins on precedence. <a id="cite-path-entry.hide-and-replace.layer-entry-masks-lower-entries"></a>

Removing the layer removes both the new key and its masking effect, and
the lower key comes back. <a id="cite-path-entry.hide-and-replace.removing-the-layer-restores-the-lower-key"></a>

This falls out of per-layer path entries and precedence ordering
without a line of code that knows about it.

<a id="trm-5-2-5-5"></a>

## Hive roots

A hive root has no parent GUID and no child name, so there is no
`(parent, name, layer)` tuple to remove or mask. <a id="cite-path-entry.hive-root.has-no-parent-or-child-name"></a>

Deleting or hiding a hive root fd is `EINVAL`, rejected before source
dispatch, before transaction enlistment, before sequence allocation and
before any watch event is generated. <a id="cite-path-entry.hive-root.delete-or-hide-is-einval"></a>

---

# Values

_Peios Kernel / Internals / LCS / Data model_

> A named, typed datum inside a key — one name with many layer entries, the type set, REG_TOMBSTONE, naming and size.

<a id="trm-5-2-6"></a>

A value is a named, typed datum inside a key. Values hold the
configuration data; keys hold values.

| Field | Description |
|---|---|
| Key GUID | The key this value belongs to. |
| Name | The value's name; the empty string is the default value. Case-preserving, compared case-insensitively. <a id="cite-value.field.empty-name-is-the-default-value"></a> |
| Type | A registry value type. |
| Data | An opaque byte array, up to `MaxValueSize` (default 1 MB). <a id="cite-value.field.data-bounded-by-max-value-size"></a> |
| Layer | The layer this entry belongs to. Every write is tagged. <a id="cite-value.field.every-write-is-layer-tagged"></a> |
| Sequence | Assigned by LCS at write time, for tiebreaking within a precedence tier. |

A key holds many values with distinct names, and at most one unnamed
one. <a id="cite-value.at-most-one-unnamed-value-per-key"></a>

<a id="trm-5-2-6-1"></a>

## One name, many entries

A single `(key GUID, value name)` pair can have several entries in the
source — one per layer that has written to it. <a id="cite-value.one-name-many-entries.one-entry-per-writing-layer"></a>

The source stores them all and returns them all. <a id="cite-value.one-name-many-entries.source-returns-every-entry"></a>

LCS resolves the effective value at read time ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

That is the mechanism that makes layer deletion revert configuration
automatically. Delete the layer, its entries go, and the
next-highest-precedence entry becomes effective. Nothing has to be
recomputed or rewritten.

<a id="trm-5-2-6-2"></a>

## Types

The full Windows type set is supported, for `registry.pol` fidelity:
`REG_NONE`, `REG_SZ`, `REG_EXPAND_SZ`, `REG_BINARY`, `REG_DWORD`,
`REG_DWORD_BIG_ENDIAN`, `REG_LINK`, `REG_MULTI_SZ`,
`REG_RESOURCE_LIST`, `REG_FULL_RESOURCE_DESCRIPTOR`,
`REG_RESOURCE_REQUIREMENTS_LIST` and `REG_QWORD`, numbered 0 to 11. <a id="cite-value.types.full-windows-set-numbered-0-to-11"></a>
Values are in [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>).

LCS stores the type tag and returns it on read but does not interpret
the data. <a id="cite-value.types.tag-stored-and-returned-uninterpreted"></a> The single exception is `REG_LINK` read as a symlink key's
default value, which triggers target resolution ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)).

The three hardware-resource types, 8 to 10, describe device resource
assignments in the Windows `HKLM\HARDWARE` hive, which the Windows
kernel rebuilds at every boot. Peios has no equivalent: hardware
enumeration belongs to the Linux device model, sysfs and `/proc/iomem`,
not to the registry. LCS accepts these tags only so a value carrying
one round-trips without loss. They have no semantics, LCS never
produces one, and for every operation they behave as `REG_BINARY`. <a id="cite-value.types.hardware-resource-types-behave-as-reg-binary"></a>
Rejecting a faithfully-copied value would break the fidelity guarantee
that is the reason the registry exists.

Type tags are validated at every write boundary, before sequence
allocation, transaction enlistment or source dispatch. An unknown code
is `EINVAL`. <a id="cite-value.types.unknown-type-code-is-einval"></a>

<a id="trm-5-2-6-3"></a>

## `REG_TOMBSTONE`

One further type, `REG_TOMBSTONE` (`0xFFFF`), is internal. It is never
returned to a caller reading a value — a caller whose effective entry
is a tombstone gets `ENOENT`, which is exactly what a tombstone
means. <a id="cite-value.reg-tombstone.never-returned-to-a-caller"></a>

There is no separate tombstone flag in the `REG_IOC_SET_VALUE`
argument. Writing type `REG_TOMBSTONE` **is** the explicit tombstone
operation. <a id="cite-value.reg-tombstone.written-by-setting-the-type"></a>

It must carry zero-length data; non-empty tombstone data is `EINVAL`,
again before sequence allocation, enlistment or dispatch. <a id="cite-value.reg-tombstone.non-empty-data-is-einval"></a>

<a id="trm-5-2-6-4"></a>

## Naming

Value names use the same case rules as key names: Unicode Simple Case
Folding, case-preserving, case-insensitive. <a id="cite-value.name.same-case-rules-as-key-names"></a>

They differ in one respect. **Backslash and forward slash are permitted
in a value name.** Value names are not hierarchical, so a separator has
no meaning in one. <a id="cite-value.name.separators-are-permitted"></a>

Only the null byte is forbidden, and invalid UTF-8 is rejected. The
empty string is reserved for the default value. <a id="cite-value.name.only-the-null-byte-is-forbidden"></a>

That difference is why watch event path components are length-prefixed
rather than joined by a separator ([Event Records](</kernel/internals/lcs/watches/event-records.md#trm-5-6-2>)) — a value name can contain
the separator.

<a id="trm-5-2-6-5"></a>

## Size

`MaxValueSize` defaults to 1 MB and is configurable from 4 KB to 64 MB
([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)).

Value data is opaque bytes and is not subject to the UTF-8 validation
that applies to every string in the interface. <a id="cite-value.data.opaque-and-not-utf8-validated"></a>

<a id="trm-5-2-6-6"></a>

## Tool value encodings

`reg`, Registry Editor and the `peios` Rust crate use these representations:

- `REG_SZ` and `REG_EXPAND_SZ`: UTF-8 ending in one null byte, rather than
  Windows' UTF-16 representation.
- `REG_LINK`: the absolute target path in UTF-8, with no null byte. Its
  length determines its end; a target containing a null is not followed.
- `REG_MULTI_SZ`: each string followed by a null byte, with one additional
  null byte ending the list.
- Integers: little-endian, except for `REG_DWORD_BIG_ENDIAN`.

These are data conventions shared by tools. LCS still treats ordinary
value payloads as opaque bytes; its special handling of a link key's
`REG_LINK` default value is described in [Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>). For choosing and entering
a type as an operator, see
[Keys, values, and types](https://learn.peios.org/peios/using-peios/registry/reg/).

---

# Tombstones

_Peios Kernel / Internals / LCS / Data model_

> An overlay that can only add is not enough — value and blanket tombstones, how they compete, and what a watcher sees.

<a id="trm-5-2-7"></a>

An overlay that can only add is not enough. `registry.pol` expresses
*absence* — `**Del.ValueName` deletes a specific value,
`**DelVals` deletes every value in a key before applying new ones — and
a higher-precedence layer that can only override cannot say "this value
must not be configured". Tombstones are how absence is expressed.

Both kinds are per-layer, and both vanish with their layer, restoring
whatever they were masking. <a id="cite-tombstone.per-layer-and-vanish-with-the-layer"></a>

<a id="trm-5-2-7-1"></a>

## Value tombstones

A value tombstone is a layer entry that says the value does not exist
in this layer and lower-precedence layers are masked. <a id="cite-tombstone.value.masks-lower-precedence-layers"></a>

Resolution treats a winning tombstone as "not found" without falling
through. <a id="cite-tombstone.value.winning-tombstone-does-not-fall-through"></a>

In the source's storage it is an entry of type `REG_TOMBSTONE` with no
data. A caller who wins with one gets `ENOENT`.

Removing the tombstone's layer makes the lower-precedence value
effective again, which is the whole point.

<a id="trm-5-2-7-2"></a>

## Blanket tombstones

A blanket tombstone is a per-layer marker on a **key** that masks every
value from lower-precedence layers, whatever its name. <a id="cite-tombstone.blanket.masks-every-value-name"></a>

Where a value tombstone names one value, a blanket names none and
covers all — including values whose names were not known when the
blanket was written, which is exactly what `**DelVals`
requires. <a id="cite-tombstone.blanket.covers-names-unknown-when-written"></a>

It is stored as a flag on the `(key GUID, layer)` relationship and
occupies no per-name entry. It has its own sequence
number. <a id="cite-tombstone.blanket.stored-as-a-flag-with-its-own-sequence"></a>

<a id="trm-5-2-7-2-1"></a>

### How it competes

A blanket does not short-circuit resolution. It enters the candidate
pool as a tombstone candidate **for every value name**, at its own
`(precedence, sequence)`, <a id="cite-tombstone.blanket.enters-the-candidate-pool-for-every-name"></a> and the ordinary rule picks the winner
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

So a per-value entry that beats the blanket on the tuple overrides it,
and one that loses is masked. <a id="cite-tombstone.blanket.per-value-entry-wins-or-loses-on-the-tuple"></a>

A layer can write a blanket *and* write specific values in the same
layer: the specific values are visible because they were written
afterwards and carry higher sequence numbers, and everything else from
below is masked. <a id="cite-tombstone.blanket.same-layer-writes-after-a-blanket-stay-visible"></a> That is `**DelVals` followed by new writes,
expressed without a special case.

An exact tie — same precedence *and* same sequence — between a blanket
and a per-value entry is not resolved in the blanket's favour or
anyone's. It is malformed source data and the operation fails with
`EIO` ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)).

<a id="trm-5-2-7-2-2"></a>

### Enumeration

Enumerating a key with a blanket applies the same per-name rule to each
name, so what a caller sees is the set of names whose winning candidate
is not the blanket. <a id="cite-tombstone.blanket.enumeration-applies-the-per-name-rule"></a>

It is not simply "the blanket's layer and above": a different layer at
the *same* precedence with a higher sequence number surfaces, and one
with a lower sequence number does not. <a id="cite-tombstone.blanket.enumeration-surfaces-higher-sequence-at-same-precedence"></a>

<a id="trm-5-2-7-2-3"></a>

### Removal

Removing a blanket, or the layer holding it, unmasks everything it was
hiding. <a id="cite-tombstone.blanket.removal-unmasks-everything-it-hid"></a>

<a id="trm-5-2-7-3"></a>

## What a watcher sees

Nothing about tombstones. Writing a blanket produces one
`VALUE_DELETED` per name it newly masks; removing one produces one
`VALUE_SET` per name that became visible. A watcher sees per-value
effective state and never has to know the mechanism ([The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md#trm-5-6-1>)).

---

# Names and Case

_Peios Kernel / Internals / LCS / Data model_

> Every string in the LCS interface is UTF-8 — length as byte count, separators, and how case folding works.

<a id="trm-5-2-8"></a>

Every string in the LCS interface — key names, value names, hive names,
layer names, paths — is UTF-8. Invalid UTF-8 is rejected with `EINVAL`
before parsing, routing, folding, layer resolution or source
dispatch. <a id="cite-name.utf8.invalid-utf8-is-einval-before-any-other-work"></a>

Null bytes are rejected in all of them. <a id="cite-name.utf8.null-bytes-rejected-in-every-string"></a>
The rejection is `EINVAL` where the string is length-delimited — ioctl
and RSI strings — because there the null byte sits inside the counted
length. A syscall argument (a path or `reg_create_key`'s layer name) is
a C string, and a null byte there is its terminator: the name the
kernel validates ends at it, and nothing after it is read. <a id="cite-name.utf8.syscall-strings-end-at-the-null"></a>

The one thing that is not a string is value data, which is opaque
bytes.

<a id="trm-5-2-8-1"></a>

## Lengths are byte counts

Every configured length limit is measured in UTF-8 bytes, not Unicode
scalar values and not display characters. <a id="cite-name.length.measured-in-utf8-bytes"></a>

- `MaxPathComponentLength` (default 255) bounds one component or one
  value or layer name. <a id="cite-name.length.max-path-component-length-bounds-a-component"></a>
- `MaxTotalPathLength` (default 16383) bounds a whole
  path. <a id="cite-name.length.max-total-path-length-bounds-a-path"></a>
- `MaxKeyDepth` (default 512) bounds nesting. <a id="cite-name.length.max-key-depth-bounds-nesting"></a>

A syscall path arrives as a null-terminated C string, is copied under a
hard bound, and has its terminator stripped before anything is
measured — so the terminator is not part of the
length. <a id="cite-name.length.syscall-path-terminator-is-not-counted"></a>

Ioctl and RSI strings are length-delimited and need no terminator; a
terminator byte included in the length is a null byte and is therefore
invalid. <a id="cite-name.length.ioctl-and-rsi-strings-are-length-delimited"></a>

<a id="trm-5-2-8-2"></a>

## Separators

Backslash is canonical. Forward slash is accepted on input and treated
as a separator wherever a separator is recognised, so a component can
never contain either. <a id="cite-name.separator.forward-slash-is-a-separator"></a>

There is no string-rewriting step: normalisation is a property of how
paths are split rather than a transformation applied to
them. <a id="cite-name.separator.no-string-rewriting-step"></a>

<a id="trm-5-2-8-3"></a>

## Case folding

Comparison is case-insensitive and storage is
case-preserving. <a id="cite-name.case.insensitive-comparison-preserving-storage"></a>

The algorithm is **Unicode Simple Case Folding** — the `C` and `S`
status entries of `CaseFolding.txt`, with the full (`F`) and Turkic
(`T`) entries excluded. <a id="cite-name.case.simple-case-folding-c-and-s-entries-only"></a>

It is a fixed one-to-one codepoint mapping with no locale input,
applied after decoding from UTF-8, never to raw
bytes. <a id="cite-name.case.folding-applied-to-codepoints-not-bytes"></a>

The Unicode version is **pinned at 16.0**. <a id="cite-name.case.unicode-version-pinned-at-16-0"></a> The table is generated by
`peios/generate-casefold-table.py` and checked in with the
digest of the source data, so adopting a newer Unicode version means
regenerating the table deliberately. It is not something that happens
by updating a dependency.

This gives practical compatibility with Windows'
`RtlCompareUnicodeString` without claiming byte-identical behaviour in
every edge case.

**Unicode normalisation is not performed.** NFC and NFD forms of the
same visual character are different names, matching
Windows. <a id="cite-name.case.no-unicode-normalisation"></a>

Case folding is what "identity" means throughout: a layer's identity is
its folded name, a hive route's identity includes its folded name, and
a duplicate is a folded-equal duplicate. `RoleA` and `rolea` are one
layer, not two. <a id="cite-name.case.identity-is-the-folded-name"></a>

Every comparison folds, on both sides of the kernel boundary. The
Kernel Access Control Subsystem (KACS) parses private layer names into
a token and rejects a duplicate with `EINVAL`; that duplicate check
uses the same folding routine and the same table as LCS, so a pair
that LCS treats as one layer cannot occupy two of a token's slots.
There were two ASCII-only comparators, the `base` check on two of its
call sites and this KACS check, and both are gone ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>) for
`base`). <a id="cite-name.case.every-comparison-folds"></a>

---

# Deletion and Orphans

_Peios Kernel / Internals / LCS / Data model_

> Deletion works on two levels because naming and identity are separate — layer deletion, orphaned keys, and what happens to their watches.

<a id="trm-5-2-9"></a>

Deletion operates on two levels, because naming and identity are
separate things.

<a id="trm-5-2-9-1"></a>

## Deleting a key

`REG_IOC_DELETE_KEY` removes **one layer's path entry**. The key's data
— its GUID, descriptor and values — is untouched; only a name is
removed. <a id="cite-orphan.delete-key.removes-one-layer-path-entry"></a>

LCS derives the parent GUID from the fd's ancestor chain and the child
name from the last component of its resolved path, and sends
`RSI_DELETE_ENTRY`. <a id="cite-orphan.delete-key.parent-and-name-derived-from-the-fd"></a>

If path entries remain in other layers, the key is still visible
through them. <a id="cite-orphan.delete-key.remaining-entries-keep-the-key-visible"></a>

If none remain anywhere, the key is orphaned. <a id="cite-orphan.delete-key.last-entry-removed-orphans-the-key"></a>

A key with **visible children** cannot be deleted:
`ENOTEMPTY`. <a id="cite-orphan.delete-key.visible-children-is-enotempty"></a>

Visibility is evaluated globally, across all enabled layers, and
deliberately ignores the caller's private layer set — so whether a
deletion succeeds does not depend on who is asking. <a id="cite-orphan.delete-key.visibility-ignores-the-callers-private-layers"></a>

Recursive deletion is a client-side tree walk, not a kernel
primitive. <a id="cite-orphan.delete-key.no-recursive-delete-primitive"></a>

Deleting a key does not delete its values. Values belong to the GUID,
not to the path entry, and go when the GUID goes. <a id="cite-orphan.delete-key.values-survive-entry-deletion"></a>

Hive roots cannot be deleted or hidden ([Path Entries](</kernel/internals/lcs/data-model/path-entries.md#trm-5-2-5>)).

<a id="trm-5-2-9-2"></a>

## Layer deletion

Deleting a layer removes all of its path entries, value entries and
blanket tombstones, across every source. <a id="cite-orphan.layer-delete.removes-every-entry-across-all-sources"></a>

LCS broadcasts `RSI_DELETE_LAYER` and each source returns the GUIDs
that lost their last path entry as a
result. <a id="cite-orphan.layer-delete.sources-report-newly-orphaned-guids"></a>

Effects on live state follow from the model with no special cases:

- keys named only by that layer become
  orphaned; <a id="cite-orphan.layer-delete.keys-named-only-by-it-become-orphaned"></a>
- where the layer held the winning value entry, the next layer's value
  becomes effective; <a id="cite-orphan.layer-delete.next-layers-value-becomes-effective"></a>
- blanket tombstones it held are removed and unmask what they were
  hiding;
- and Security Descriptors are unchanged, because they were never
  layered. <a id="cite-orphan.layer-delete.security-descriptors-unchanged"></a>

Watchers are notified by whatever recovery mechanism applies —
per-key events for the orphaned keys, and a source-wide `OVERFLOW` for
the rest ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Before sending `RSI_DELETE_LAYER`, LCS aborts every bound transaction
whose mutation log touched that layer. <a id="cite-orphan.layer-delete.aborts-transactions-touching-the-layer"></a> Otherwise a transaction could
commit writes into a layer that no longer exists.

Those transactions return `EINVAL` on their next operation or commit
attempt. <a id="cite-orphan.layer-delete.aborted-transactions-return-einval"></a>

Layer deletion is what role uninstallation and Group Policy removal
are.

<a id="trm-5-2-9-3"></a>

## Orphaned keys

An orphaned key is a GUID with no path entry in any layer. It follows
the Linux unlink model: alive but unnamed. <a id="cite-orphan.definition.guid-with-no-path-entry-anywhere"></a>

Existing fds keep working. Operations that address the key by GUID
proceed normally:

- querying, setting and deleting values; <a id="cite-orphan.allowed.value-operations"></a>
- setting and removing blanket tombstones; <a id="cite-orphan.allowed.blanket-tombstone-operations"></a>
- querying and setting the Security Descriptor; <a id="cite-orphan.allowed.security-descriptor-operations"></a>
- querying key metadata; <a id="cite-orphan.allowed.query-key-metadata"></a>
- flushing the key's hive; <a id="cite-orphan.allowed.flush-the-hive"></a>
- closing the fd. <a id="cite-orphan.allowed.close-the-fd"></a>

Namespace operations return `ENOENT`:

- creating a child key under it; <a id="cite-orphan.refused.create-a-child-key"></a>
- opening or creating anything relative to it; <a id="cite-orphan.refused.relative-open-or-create"></a>
- deleting its path entry; <a id="cite-orphan.refused.delete-its-path-entry"></a>
- hiding it; <a id="cite-orphan.refused.hide-it"></a>
- backing it up. <a id="cite-orphan.refused.back-it-up"></a>

The reason is that an orphaned key is no longer a reachable subtree
root. Allowing new names beneath an unnamed key would build a subgraph
nothing can reach.

<a id="trm-5-2-9-4"></a>

## Watches on an orphaned key

A watch armed before the key was orphaned stays armed, and the
transition delivers `KEY_DELETED`. <a id="cite-orphan.watch.stays-armed-and-delivers-key-deleted"></a>

After that the watch may still observe GUID-local changes made through
the surviving fds, though the subtree is no longer expanded through the
orphaned key. <a id="cite-orphan.watch.still-sees-guid-local-changes"></a>

Arming a *new* watch on an already-orphaned key is
`ENOENT`. <a id="cite-orphan.watch.arming-a-new-watch-is-enoent"></a>

Re-arming one that is already armed is allowed. <a id="cite-orphan.watch.re-arming-an-armed-watch-is-allowed"></a>

<a id="trm-5-2-9-5"></a>

## Dropping the GUID

When the last fd to an orphaned key closes and the source is Active,
LCS sends `RSI_DROP_KEY`, which purges the key record, every value
entry across every layer, and any remaining blanket
tombstones. <a id="cite-orphan.drop.last-close-sends-rsi-drop-key"></a>

It is dispatched **before** the in-kernel key state is
released. <a id="cite-orphan.drop.dispatched-before-state-is-released"></a>

The request is asynchronous: nothing waits for the answer, and a valid
response is processed as an ordinary response rather than as a late
one ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)). <a id="cite-orphan.drop.request-is-asynchronous"></a> That distinction is load-bearing — `RSI_DROP_KEY` is a
mutating operation, and without it the arrival of a perfectly normal
answer to a caller-less request would look like an unaccounted
mutation and tear the source down.

If the source is Down, LCS releases its in-kernel state and does **not**
queue a deferred drop. There is no deferred-drop
queue. <a id="cite-orphan.drop.down-source-queues-no-deferred-drop"></a> Recovering the
key record then falls to the source's own startup obligation, under
the Registry Source Interface specification in PSPK, to purge records
with no path entries before it becomes Active.

`close()` never reports orphan cleanup failure to userspace, and never
can: it returns 0 unconditionally. <a id="cite-orphan.drop.close-always-returns-zero"></a>

<a id="trm-5-2-9-6"></a>

## A new key at the same path

A layer can create a new key where another layer's key already exists.
Each layer has its own path entry pointing at its own GUID, and
resolution decides which is visible.

Fds referencing the other GUID are completely isolated from it:
different identity, different data, different value entries. Nothing
observable connects two keys that merely share a name. <a id="cite-orphan.same-path.fds-to-the-other-guid-stay-isolated"></a>

---

# Layers

_Peios Kernel / Internals / LCS / Layers_

> Find the Peios kernel articles about layers.

Use these articles to understand layers in the Peios kernel.

- [The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md>)
- [The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md>)
- [Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md>)
- [Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md>)
- [Private Layers](</kernel/internals/lcs/layers/private-layers.md>)
- [Resolution](</kernel/internals/lcs/layers/resolution.md>)
- [The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md>)

---

# The Layer Model

_Peios Kernel / Internals / LCS / Layers_

> A named collection of registry writes managed as a unit — precedence tiers, caps, and why layers are global while entries are per-source.

<a id="trm-5-3-1"></a>

A layer is a named collection of registry writes that can be managed as
a unit. Layers have precedence, and the highest-precedence entry wins.
They are how role installation, Group Policy and configuration revert
all work, and they are the reason removing a role does not leave its
settings behind.

| Field | Mutable | Description |
|---|---|---|
| Name | No | The layer's identity — not a GUID, not an integer. Case-preserving, compared with Unicode Simple Case Folding. Bounded by `MaxPathComponentLength`. <a id="cite-layer.model.name-is-the-identity"></a> |
| Precedence | Yes | Higher wins. Default 0. |
| Enabled | Yes | A disabled layer is invisible during resolution unless it is attached to the resolving thread's credentials ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). Default true. |
| Owner | — | The SID of the principal that created the layer. Informational only. |

The name being the identity is deliberate. Layer names are
code-generated and meaningful by construction —
`role-jellyfin`, `gpo-security-baseline` — so there is nothing an
opaque identifier would add.

`Owner` is never used for an access check; authorisation is the
descriptor on the layer's metadata key ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). <a id="cite-layer.model.owner-never-used-for-an-access-check"></a>

It is also not quite immutable as a field: a refresh re-reads the
`Owner` value and re-selects it, so rewriting the value does change what
is cached. <a id="cite-layer.model.owner-re-selected-by-refresh"></a> Because nothing
consults it, that has no effect on anything.

<a id="trm-5-3-1-1"></a>

## Precedence tiers

The base layer and role layers all sit at precedence 0. Within one
tier, the most recent write wins — the highest sequence number. Group
Policy layers sit above 0 and override both.

Establishing or raising a layer's precedence above 0 requires
`SeTcbPrivilege` ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). That is what keeps the tier boundary
meaningful.

<a id="trm-5-3-1-2"></a>

## Caps

`MaxTotalLayers`, default 1024, bounds the in-memory layer table, the
base layer included: a table holding that many entries admits no more. <a id="cite-layer.model.max-total-layers-default-1024"></a>

Creating a layer when it is full returns `ENOSPC`. The refusal happens
at the creation of the metadata key under `Layers\`, before anything
reaches the source, so a full table never leaves a metadata key behind
that the table cannot publish. <a id="cite-layer.model.layer-table-full-is-enospc"></a>

The table is sized to `MaxTotalLayers` rather than fixed at build. It
is allocated on the first publication and grows, under the table lock,
whenever a publication finds every slot taken while the configured
bound still admits one more; it never shrinks. <a id="cite-layer.model.table-grows-to-max-total-layers"></a>

So a value anywhere in the configurable range, 16 to 65536, binds.
Raising `MaxTotalLayers` above the default admits layers past 1024;
lowering it below the current occupancy admits no new layer until
enough have been deleted, and discards nothing. <a id="cite-layer.model.max-total-layers-binds-across-the-range"></a>

`MaxLayersPerValue`, default 128, bounds how many layers may write to
the same `(key GUID, value name)` pair. <a id="cite-layer.model.max-layers-per-value-default-128"></a> It is a guard against
amplification — every read of that value has to resolve every entry —
not an access control boundary.

It is enforced at `REG_IOC_SET_VALUE` time, before the source is
contacted, by querying the source for the current entry count. <a id="cite-layer.model.max-layers-per-value-checked-at-set-value"></a>

A write that replaces an existing entry in the *same* layer does not
increase the count and is not checked. <a id="cite-layer.model.max-layers-per-value-same-layer-replace-exempt"></a>
Exceeding the cap is `ENOSPC`. <a id="cite-layer.model.max-layers-per-value-exceeded-is-enospc"></a>

The check is deliberately **best-effort admission control**, not a
storage invariant. <a id="cite-layer.model.max-layers-per-value-is-best-effort"></a> It queries and then dispatches without holding
anything, so concurrent writers can both observe room and both proceed.
Sources are not required to enforce it atomically.

Once LCS observes a count at or above the cap, further new-layer writes
are refused. <a id="cite-layer.model.max-layers-per-value-refuses-once-observed-full"></a>

Blanket tombstones and value deletions are not subject to it. <a id="cite-layer.model.max-layers-per-value-exempts-blankets-and-deletions"></a>

<a id="trm-5-3-1-3"></a>

## Layers are global; entries are per-source <a id="cite-layer.model.table-is-global-entries-are-per-source"></a>

There is one authoritative layer table, held by the kernel. Each source
stores layer *entries* — path entries and value writes tagged with
layer name strings — for its own hives. Layer *metadata* is global and
lives in one place.

A source never needs the layer table. It stores what it is told, tagged
with whatever name it is given, and returns everything on request. A
source that has never seen a particular layer name simply stores
entries carrying it. Resolution — precedence, enabled state, tombstone
evaluation — happens entirely in the kernel, and the layer snapshot is
passed into each operation rather than pushed to sources. There is no
RSI operation that hands a source the layer list. <a id="cite-layer.model.no-rsi-operation-sends-the-layer-list"></a>

---

# The Base Layer

_Peios Kernel / Internals / LCS / Layers_

> The kernel-reserved layer that exists unconditionally before any source registers — its persisted metadata and the two ways it is matched.

<a id="trm-5-3-2"></a>

The base layer, named `base`, is a kernel-reserved implicit layer. It
exists unconditionally, before any source registers and whether or not
any metadata has ever been persisted for it. <a id="cite-layer.base.exists-unconditionally"></a>

It is a static constant in the kernel: precedence 0, enabled. <a id="cite-layer.base.is-precedence-zero-and-enabled"></a> It is
never stored in the dynamic layer table. <a id="cite-layer.base.not-in-the-dynamic-layer-table"></a>

It is always emitted first in every layer snapshot, and is handed out
even when the dynamic table is empty. <a id="cite-layer.base.emitted-first-in-every-snapshot"></a> A source that registers with a
completely empty database is therefore immediately usable, because the
one layer that writes need is not in the database.

Four things cannot happen to it:

- it cannot be deleted; <a id="cite-layer.base.cannot-be-deleted"></a>
- it cannot be disabled; <a id="cite-layer.base.cannot-be-disabled"></a>
- its precedence cannot be changed; <a id="cite-layer.base.precedence-cannot-be-changed"></a>
- a layer table row for it cannot be published at all. <a id="cite-layer.base.row-cannot-be-published"></a>

Each of those is enforced in more than one place. Deletion is refused by
the layer table, by the resolution core, by the `RSI_DELETE_LAYER`
dispatch path, and by the transaction layer-abort path. Publication of a
`base` row is rejected outright, and the refresh path short-circuits for
`base` **before** it would read `Precedence` or `Enabled`, so persisted
values for those are never even consulted.

<a id="trm-5-3-2-1"></a>

## Persisted metadata

`Machine\System\Registry\Layers\base\` may exist, though nothing in a
Peios system creates it, and where it does it decorates the base layer
rather than defining it. What LCS takes
from it is the metadata key's GUID and its cached Security Descriptor —
which is to say, who may write into the base layer ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)). <a id="cite-layer.base.metadata-key-supplies-guid-and-descriptor"></a>

Its `Precedence` and `Enabled` values are ignored. <a id="cite-layer.base.persisted-precedence-and-enabled-ignored"></a>

The internal self-watch also ignores a `SUBKEY_DELETED` for `base`: if a
higher-precedence HIDDEN entry masks the base layer's metadata key, that
is not a layer deletion and is not processed as one. <a id="cite-layer.base.subkey-deleted-is-ignored"></a> The base layer's
existence is hardcoded and layer mechanics cannot reach it.

<a id="trm-5-3-2-2"></a>

## The default target

A write that names no layer targets the base layer. <a id="cite-layer.base.is-the-default-write-target"></a> That is the default
for manual administration, for system initialisation, and for what a
person keeps under their own `Users\<SID>\`.

While the base layer's metadata key does not exist, LCS uses a
compiled-in default descriptor granting SYSTEM and Administrators
`KEY_ALL_ACCESS` and Authenticated Users `KEY_SET_VALUE`, so writes into
the base layer are possible from the very beginning, by anyone who has
authenticated, to whatever the target key's own descriptor lets them
write. The compiled-in default is replaced by the key's descriptor as
soon as the key is created ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

<a id="trm-5-3-2-3"></a>

## `base` is matched like every other layer name <a id="cite-layer.base.name-matched-by-case-folding"></a>

The reserved name is recognised with Unicode Simple Case Folding, the
same algorithm and the same table used for every other layer-name
comparison.

There was a second, ASCII case-insensitive comparator beside it, used on
two call sites. For the literal string `base` the two agreed — a length
pre-check made a non-ASCII case pair fail before folding could matter —
so the divergence was latent rather than absent, and would have become
live the moment anything about the reserved name changed. It is gone;
both call sites now take the folding comparator and propagate its error
rather than collapsing it into a `bool`.

---

# Layer Metadata

_Peios Kernel / Internals / LCS / Layers_

> Layer metadata lives in the registry it configures — the circularity that creates, why publication is atomic, and when the refresh runs.

<a id="trm-5-3-3"></a>

Layer metadata lives in the registry, under
`Machine\System\Registry\Layers\<LayerName>\`. <a id="cite-layer.metadata.lives-under-the-layers-key"></a> Each layer's key holds
three values:

| Value | Type | Default if missing |
|---|---|---|
| `Precedence` | `REG_DWORD` | 0 <a id="cite-layer.metadata.precedence-is-dword-default-0"></a> |
| `Enabled` | `REG_DWORD`, 0 or 1 | true <a id="cite-layer.metadata.enabled-is-dword-default-true"></a> |
| `Owner` | `REG_BINARY`, a SID | the creating token's SID for a new layer <a id="cite-layer.metadata.owner-is-binary-sid"></a> |

Three things are malformed metadata, and are rejected rather than
coerced:

- a value of the wrong type; <a id="cite-layer.metadata.wrong-type-is-malformed"></a>
- a `REG_DWORD` that is not exactly four bytes; <a id="cite-layer.metadata.dword-must-be-exactly-four-bytes"></a>
- an `Enabled` greater than 1. <a id="cite-layer.metadata.enabled-above-one-is-malformed"></a>

`Owner` selection has a fallback chain: the metadata value; failing
that, the creator's SID for a newly created layer; failing that, the
previous known-good owner; failing that, the owner SID from the
metadata key's own descriptor. <a id="cite-layer.metadata.owner-fallback-chain"></a>

If none of those is available the layer cannot be published. <a id="cite-layer.metadata.unresolvable-owner-blocks-publication"></a> Every one
of these is informational and none grants access.

There is no "create layer" or "delete layer" syscall. Creating a key
under `Layers\` creates a layer; deleting that key deletes it. <a id="cite-layer.metadata.key-creation-and-deletion-are-the-lifecycle"></a>
Creation should be done inside a transaction so that all three values
are present when the refresh runs.

<a id="trm-5-3-3-1"></a>

## Circularity

Layer metadata is stored in the registry, which is itself layered.
That is circular, and it is safe, because resolution never re-enters
itself.

LCS always resolves using its **currently published** layer table —
including when resolving layer metadata values. <a id="cite-layer.metadata.resolved-with-the-published-table"></a> When a write to the
metadata subtree commits, the refresh reads the affected metadata using
the current table and then publishes an updated one.

The table is never re-resolved mid-operation; each operation takes one
snapshot and uses it throughout. <a id="cite-layer.metadata.one-snapshot-per-operation"></a>

So a high-precedence layer can override another layer's precedence, and
that is useful and intended. It simply takes effect at the next
publication rather than recursively. <a id="cite-layer.metadata.override-takes-effect-at-next-publication"></a>

<a id="trm-5-3-3-2"></a>

## Publication is atomic

A layer is not merely a name and a precedence. The published unit is
three things together: the layer table entry, the metadata key's GUID,
and the cached Security Descriptor of that key. <a id="cite-layer.metadata.published-unit-is-three-things"></a>

All three are written under one lock, and a snapshot reader that finds
them incomplete returns `EIO` rather than a half-populated layer. <a id="cite-layer.metadata.incomplete-publication-is-eio"></a>

A layer that has no metadata key GUID and no authorisation descriptor
is not visible in the table at all. <a id="cite-layer.metadata.layer-without-guid-or-descriptor-is-invisible"></a> There is no window in which a layer
exists but nobody can be authorised against it.

Creating the metadata key is ordinary key creation, so LCS computes its
descriptor from parent inheritance through KACS before the source
persists it. <a id="cite-layer.metadata.descriptor-computed-by-inheritance-before-persist"></a> On the normal path the key therefore has a descriptor
before the layer can be published.

<a id="trm-5-3-3-3"></a>

## When the refresh runs

Changes under `Layers\` mark the affected layer names dirty. After the
mutating operation commits, and **before the syscall returns to
userspace**, LCS runs a bounded refresh for those names: it reads the
committed metadata key, its values and its descriptor, and publishes
the new entry atomically. <a id="cite-layer.metadata.refresh-runs-before-the-syscall-returns"></a>

For a transaction the refresh runs once, after the source commit
succeeds and before `REG_IOC_COMMIT` returns. <a id="cite-layer.metadata.transaction-refresh-runs-once-before-commit-returns"></a>

The internal self-watch is what notices the subtree changed, but the
watch callback is not the atomicity boundary and must never publish a
partial entry. LCS does not perform source round trips while holding
the watch-map or layer-table publication locks. <a id="cite-layer.metadata.no-source-round-trips-under-publication-locks"></a>

<a id="trm-5-3-3-4"></a>

## When the metadata descriptor will not parse

If the metadata key's descriptor cannot be read or parsed during a
refresh, the source has returned malformed data. LCS emits an audit
event, does not publish or update that layer's entry, and keeps the
previous known-good one. <a id="cite-layer.metadata.unparseable-descriptor-keeps-previous-entry"></a>

The same isolation holds at bootstrap. The refresh that runs on source
registration visits every layer under `Layers\` in turn, and one whose
metadata will not parse — the descriptor, or any of the three values —
is skipped, unpublished and counted, while its siblings publish as they
would have without it. Only a failure of the source itself, rather than
of one layer's data, fails the refresh. <a id="cite-layer.metadata.bootstrap-isolates-a-malformed-layer"></a>

If the refresh was required to complete the operation in hand —
creating a layer, say, or exposing one — the syscall fails with `EIO`. <a id="cite-layer.metadata.required-refresh-failure-is-eio"></a>

---

# Writing Into a Layer

_Peios Kernel / Internals / LCS / Layers_

> Every mutation targeting a layer requires layer write access — the base layer before it exists, the precedence gate, and deleting a layer.

<a id="trm-5-3-4"></a>

Every mutating operation that targets a layer — value writes, value
deletions, tombstones, key hides, blanket tombstones, key creation —
requires **layer write authorization**: `KEY_SET_VALUE` on the layer's
metadata key at `Machine\System\Registry\Layers\<LayerName>\`. <a id="cite-layer.authz.write-requires-key-set-value-on-metadata-key"></a>

This is a second AccessCheck, against a different object, and it is in
addition to the fd's granted mask on the target key. Both must pass. <a id="cite-layer.authz.is-a-second-check-additional-to-the-fd-mask"></a>

The descriptor on a layer's metadata key is therefore the answer to
"who may write into this layer". The base layer's, where the key has
been created, is the one inheritance computes from the `Machine` hive
root, like any other key's. <a id="cite-layer.authz.base-descriptor-inherits-from-the-machine-root"></a>
Group Policy layers get restrictive descriptors from the GP client at
creation; role layers get theirs from the role installer.

That closes two escalation paths at once. An unprivileged process
cannot write into a GP layer, and one role's service cannot write into
another role's.

The base layer is the one layer meant to be written by everybody. It
is where a write goes that names no layer, a person's own settings
under `Users\<SID>\` included, so its descriptor lets in anyone who has
authenticated and leaves what they may write to the descriptor of the
key they are writing. A layer check that refused them would make every
key read-only to everyone but SYSTEM and Administrators, whatever the
key's own descriptor said.

The layer metadata descriptors are cached alongside the layer table and
invalidated by the same self-watch ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)). A layer that is not in the
table is `ENOENT` for any operation naming it. <a id="cite-layer.authz.unknown-layer-is-enoent"></a>

<a id="trm-5-3-4-1"></a>

## The base layer before it exists

While `Layers\base\` does not exist, LCS falls back to a compiled-in
default descriptor, so base-layer writes work from the start. It is
owned by SYSTEM and grants `KEY_ALL_ACCESS` to SYSTEM and
Administrators and `KEY_SET_VALUE`, the one right this check asks for,
to Authenticated Users. Nobody else is granted anything: a principal
that has not authenticated cannot write into the base layer, whatever
the target key allows. <a id="cite-layer.authz.base-falls-back-to-a-compiled-in-descriptor"></a>

Nothing in a Peios system creates `Layers\base\`, so on a system as
shipped the compiled-in default is the descriptor in force for as long
as the system runs.

It is replaced by the persisted descriptor the moment the key is
created. <a id="cite-layer.authz.base-fallback-replaced-at-seed-restore"></a>

> [!WARNING]
> Creating `Layers\base\` changes who may write the registry. The new
> key inherits from the `Machine` hive root, which grants Authenticated
> Users `KEY_READ` and not `KEY_SET_VALUE`, so from that moment no
> ordinary principal can write anything, its own `Users\<SID>\`
> included. Whoever creates the key has to give it a descriptor that
> says what they mean, in the transaction that creates it.

<a id="trm-5-3-4-2"></a>

## Layer lifecycle

| Operation | Requirement |
|---|---|
| Create a layer at precedence 0 | `KEY_CREATE_SUB_KEY` on `Layers\` <a id="cite-layer.authz.create-requires-create-sub-key"></a> |
| Create a layer above precedence 0 | `KEY_CREATE_SUB_KEY` on `Layers\` **and** `SeTcbPrivilege` |
| Write into a layer | `KEY_SET_VALUE` on the layer's metadata key |
| Modify layer metadata | `KEY_SET_VALUE` on the metadata key; raising precedence above 0 additionally requires `SeTcbPrivilege` <a id="cite-layer.authz.modify-metadata-requires-key-set-value"></a> |
| Delete a layer | `DELETE` on the metadata key's fd <a id="cite-layer.authz.delete-requires-delete-on-the-metadata-fd"></a> |

Everything except the precedence rule is controlled purely by the
descriptor on the metadata key. <a id="cite-layer.authz.only-precedence-needs-a-privilege"></a>

<a id="trm-5-3-4-3"></a>

## The precedence gate

`SeTcbPrivilege` is required specifically to establish or raise a
layer's precedence above 0. <a id="cite-layer.authz.precedence-above-zero-requires-setcbprivilege"></a> It is defence in depth: compromising the
descriptor on `Layers\` is not enough to create a Group Policy-tier
layer.

The check is synchronous and inline at `REG_IOC_SET_VALUE` time, and it
happens early — before sequence allocation, before transaction
enlistment, before the source is contacted. <a id="cite-layer.authz.precedence-gate-runs-before-sequence-and-dispatch"></a>

It runs when three things hold: the target key is a layer metadata key,
the value name folds equal to `Precedence` under the same Unicode
folding used for every other value name, and the data is a positive
`REG_DWORD`. <a id="cite-layer.authz.precedence-gate-trigger-conditions"></a> A key
is a layer metadata key by its path — a direct child of
`Machine\System\Registry\Layers` — or by already being in the set of
published layer metadata keys. The path test is what covers the
recommended creation flow ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)), where `Precedence` is written inside
the transaction that creates the metadata key, before the layer has
been published at all. <a id="cite-layer.authz.precedence-gate-keys-on-the-path"></a>

Failing the privilege check is `EPERM`. <a id="cite-layer.authz.precedence-gate-denial-is-eperm"></a>

The gate tests for a four-byte `REG_DWORD` specifically. A `Precedence`
written with some other type slips past it — and then fails at the
refresh, which rejects a non-`REG_DWORD` `Precedence` as malformed
metadata. The precedence never actually rises. <a id="cite-layer.authz.non-dword-precedence-slips-the-gate-and-fails-at-refresh"></a>

`REG_IOC_RESTORE` has its own equivalent gate, applied to the backup
stream's layer manifest before anything is written ([Restore](</kernel/internals/lcs/backup-and-restore/restore.md#trm-5-9-3>)).

<a id="trm-5-3-4-4"></a>

## Deleting a layer

Deleting the metadata key fires a `SUBKEY_DELETED` on the internal
self-watch. LCS removes the layer from the table and broadcasts
`RSI_DELETE_LAYER` to every registered source, each of which purges
every entry tagged with that name and reports the GUIDs that lost their
last path entry. <a id="cite-layer.authz.deleting-the-metadata-key-removes-the-layer-from-the-table"></a>

Before the broadcast, LCS aborts every bound transaction whose mutation
log touched that layer ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)).

A `SUBKEY_DELETED` for `base` is ignored ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)).

---

# Private Layers

_Peios Kernel / Internals / LCS / Layers_

> A disabled layer attached to a thread's credentials — how it resolves, how it is attached, and the authority retained from its creator.

<a id="trm-5-3-5"></a>

A private layer is a **disabled** layer attached to a thread's
credentials. It is invisible during ordinary resolution and treated as
enabled when resolving on behalf of a thread whose token names it. <a id="cite-layer.private.disabled-layer-active-for-a-naming-thread"></a>

That covers three things a shared registry otherwise cannot do: giving
one session experimental settings without affecting others; injecting
test configuration without touching the shared tree; and giving a
container a different view of the registry without a separate hive.

<a id="trm-5-3-5-1"></a>

## Resolution

A private layer participates in normal precedence ordering. <a id="cite-layer.private.participates-in-normal-precedence"></a> A disabled
layer with precedence 5 attached to a thread resolves at precedence 5,
competing with everything else at that level. It is not an overlay on
top; it is a layer that only that thread can see.

After private-attachment authorization succeeds, a layer is active for a
thread if it is globally enabled, or its name appears in that thread's
private layer set. <a id="cite-layer.private.activity-test"></a>

Name matching uses Unicode Simple Case Folding, like every other layer
name comparison. <a id="cite-layer.private.names-matched-by-case-folding"></a>

<a id="trm-5-3-5-2"></a>

## Attachment

Private layer names reach a thread through the KACS token's LCS
credential extension — the same versioned block that carries scope
GUIDs for private hives ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-layer.private.names-come-from-the-token-credential-extension"></a>

LCS reads the credentials from the effective token on each operation
and passes them into resolution. <a id="cite-layer.private.credentials-read-from-the-effective-token-per-operation"></a>

Private layers are therefore **per-thread, not per-process**: threads
in one process can hold different private layer sets through different
impersonation tokens. <a id="cite-layer.private.are-per-thread-not-per-process"></a>

<a id="trm-5-3-5-3"></a>

## Two things about the caps

`MaxPrivateLayersPerToken`, default 16, is described as a limit on
attachment. <a id="cite-layer.private.max-private-layers-per-token-default-16"></a> It is not enforced there. <a id="cite-layer.private.cap-not-enforced-at-attachment"></a>

KACS applies its own hard cap of 256 names when it parses the token
specification. <a id="cite-layer.private.kacs-hard-cap-of-256-at-parse"></a> The configurable LCS limit is applied later, when
LCS acquires a thread's private credentials for an operation. <a id="cite-layer.private.lcs-cap-applied-at-credential-acquisition"></a>

The consequence is that a token carrying seventeen private layers is
accepted by KACS and then fails every LCS operation, rather than being
refused when it was built. <a id="cite-layer.private.over-cap-token-accepted-then-fails-every-operation"></a> Reading LCS's configured limits from KACS
would invert the dependency between the two, so the cap stays where it
can be read.

The failure is `E2BIG`. <a id="cite-layer.private.over-cap-is-e2big"></a> It was `EACCES`, which read as an access-control
denial and sent anyone debugging it towards descriptors and privileges
rather than towards a count that was fixed when the token was assembled,
possibly in another process.

`MaxScopeGUIDsPerToken` shares the check and the errno. <a id="cite-layer.private.max-scope-guids-shares-the-check-and-errno"></a> A missing token
is still `EACCES`, because that one is an access decision. <a id="cite-layer.private.missing-token-is-eacces"></a>

KACS deduplicates the private layer names it parses with the same
Unicode Simple Case Folding LCS matches them by, so a name that LCS
treats as one layer is one layer here too. <a id="cite-layer.private.kacs-dedupes-names-by-case-folding"></a>

It did not always: an ASCII case-insensitive comparison let two names
differing only in a non-ASCII case relation — `ROLEs` and `roles`, since
U+017F folds to `s` — both sit on one token, spending two of the token's
`MaxPrivateLayersPerToken` slots on a single layer. Resolution still
folded correctly on the LCS side, so the layer activated once, but the
two sides of one identity contract disagreed.

<a id="trm-5-3-5-4"></a>

## Attachment authority

Private-layer names can enter a token only at creation, which requires
`SeCreateTokenPrivilege`. <a id="cite-layer.private.attachment-gated-by-secreatetokenprivilege"></a>
Attaching a known layer above precedence 0 additionally requires enabled
`SeTcbPrivilege` on the **creator**. Without it, creation fails with `EPERM`,
even when the requested child token itself includes TCB privilege. A present
but disabled privilege does not authorize attachment.

The kernel retains the creator's authorization as immutable token state.
A trusted creator can delegate a private high-precedence view to an ordinary
token without giving the consumer TCB privilege. Duplication, restriction,
process propagation and impersonation preserve that attachment authority;
they do not obtain new authority from the duplicating caller.
<a id="cite-layer.private.tcb-authorized-attachment-can-be-delegated"></a>

Layer names need not exist when attached, and precedence can change later.
For each operation acquiring private credentials, LCS checks the retained
authority against the **same layer snapshot** used for resolution. If an
attachment made without TCB authorization now names a layer above precedence
0, the operation fails with `EPERM`. It does not silently choose a lower
layer. This applies to queries through already-open key handles as well as
new opens; a later promotion or creation cannot upgrade the attachment.
Returning the layer to precedence 0 makes the original attachment usable
again. Ordinary key and layer access checks still apply.

KACS invokes an LCS-supplied validator before exposing a newly created token.
The callback is installed during kernel initialization and then read-only;
a private extension cannot be published without its validator. LCS owns the
layer lookup, so KACS does not interpret the layer table. Use-time validation
closes the race between the creation check and a concurrent metadata change.
Successful TCB authorization marks the privilege used on the creator.

This is the PEI-268 behavior; older kernels lack the attachment check.

---

# Resolution

_Peios Kernel / Internals / LCS / Layers_

> Turning several per-layer entries into one effective answer — the rule, why unknown layers are latent rather than wrong, and enumeration.

<a id="trm-5-3-6"></a>

Layer resolution turns several per-layer entries into one effective
answer. It is the mechanism that makes the registry layered, and it is
the same algorithm for path entries and for values — one resolves
existence claims, the other resolves data. <a id="cite-layer.resolution.same-algorithm-for-path-entries-and-values"></a>

<a id="trm-5-3-6-1"></a>

## The rule

Every candidate is a tuple `(precedence, sequence, entry)`. The winner
is the maximum, ordered by precedence first and sequence second. <a id="cite-layer.resolution.winner-is-highest-precedence-then-highest-sequence"></a>

Building the candidate list:

1. For each entry the source returned, look up its layer in the current
   layer table. An entry naming a layer that is not in the table is
   **skipped**, not rejected. <a id="cite-layer.resolution.entry-for-an-unknown-layer-is-skipped"></a>
2. Discard entries from layers that are not active for this thread — a
   layer is active if it is globally enabled or its name is in the
   thread's private layer set ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-layer.resolution.inactive-layers-are-discarded"></a>
3. For values, add every blanket tombstone on the key as a tombstone
   candidate for the requested name, at its own precedence and
   sequence ([Tombstones](</kernel/internals/lcs/data-model/tombstones.md#trm-5-2-7>)). <a id="cite-layer.resolution.blanket-tombstones-join-the-candidate-list"></a>
4. If there are no candidates, the answer is not-found. <a id="cite-layer.resolution.no-candidates-is-not-found"></a>
5. Take the maximum. A winning HIDDEN path entry, a winning
   `REG_TOMBSTONE` value entry, and a winning blanket all mean
   not-found. <a id="cite-layer.resolution.winning-hidden-tombstone-or-blanket-is-not-found"></a>

That is the whole algorithm. Everything the layer system does —
override, revert, mask, hide, hide-and-replace — is a consequence of
it.

<a id="trm-5-3-6-2"></a>

## Unknown layers are latent, not wrong

An entry tagged with a well-formed layer name that is not currently in
the table is a valid **latent** entry. <a id="cite-layer.resolution.latent-entry-is-valid"></a>

It is ignored while the layer is absent, and if a layer with the same
folded identity is later created, that entry becomes eligible for
resolution under the new metadata. <a id="cite-layer.resolution.latent-entry-becomes-eligible-when-the-layer-appears"></a>

This is what makes restore, import and boot ordering work: source
storage can legitimately hold entries before their metadata has been
loaded. It also follows the core rule — sources persist entries, LCS
decides their meaning.

Normal operations do not create such entries. <a id="cite-layer.resolution.normal-operations-do-not-create-latent-entries"></a> A layer-targeting ioctl
naming a layer that is not in the table returns `ENOENT`. Latent
entries come from existing storage, from a restore or import, from a
previous boot, or from source behaviour. Since sources are trusted,
a well-formed latent entry is not malformed merely because its layer is
absent right now.

An entry whose layer *name* is malformed is a different matter, and is
rejected as malformed source data. <a id="cite-layer.resolution.malformed-layer-name-is-rejected"></a>

<a id="trm-5-3-6-3"></a>

## Enumeration

Enumerating values collects the unique names across all layers and
resolves each one, returning only those whose answer is not not-found. <a id="cite-layer.resolution.enum-values-returns-only-resolved-names"></a>

Enumerating subkeys collects the unique child names and resolves each,
returning those that map to a GUID rather than HIDDEN. <a id="cite-layer.resolution.enum-subkeys-skips-hidden-children"></a>

"Unique" means folded-unique. Two entries whose names differ only in
case are one name, which is the only reading consistent with names
being case-insensitive. <a id="cite-layer.resolution.enumeration-uniqueness-is-folded"></a>

A caller sees effective state only. <a id="cite-layer.resolution.callers-see-effective-state-only"></a> Tombstoned values, blanket-masked
values and hidden keys are simply absent. Per-layer raw data is never
visible through a normal operation.

<a id="trm-5-3-6-4"></a>

## Enumeration is index-based, and that has a cost

`REG_IOC_ENUM_VALUES` and `REG_IOC_ENUM_SUBKEYS` return one entry at an
index. Each call re-resolves the full set and returns the entry at that
position, so walking `0..N-1` performs N full resolutions — O(n²) work
overall. <a id="cite-layer.resolution.enumeration-re-resolves-at-every-index"></a>

For a key with a handful of values that does not matter.
`REG_IOC_QUERY_VALUES_BATCH` exists for when it does: one call, the
whole effective value set, one resolution. <a id="cite-layer.resolution.batch-query-resolves-the-whole-set-once"></a>

Enumeration order is not defined, and the index-to-entry mapping can
change between calls if the effective set changes. <a id="cite-layer.resolution.enumeration-order-is-undefined"></a> Indices must not be
cached across mutations. The batch call is also the way to get a
consistent snapshot.

<a id="trm-5-3-6-5"></a>

## Neither party can lie about ordering

Two rules stop a source manipulating the outcome.

A source-returned entry whose sequence number is greater than or equal
to the next sequence LCS would allocate is **malformed data**. <a id="cite-layer.resolution.future-sequence-number-is-malformed"></a> Sources
store the numbers LCS assigns them; they cannot legitimately hold a
future one. Without this, a compromised source could fabricate a
sequence number and win every tie in its own hive.

Every entry in a response is validated this way, whatever layer it
names. <a id="cite-layer.resolution.every-entry-in-a-response-is-sequence-checked"></a>

Duplicate sequence numbers at the same precedence, where they would
actually have to be compared to pick a winner, are also malformed. LCS
rejects the response rather than making an arbitrary choice. <a id="cite-layer.resolution.compared-duplicate-sequences-are-malformed"></a>

Duplicates that never get compared are not an error. <a id="cite-layer.resolution.uncompared-duplicate-sequences-are-not-an-error"></a>

Both produce `EIO` and an `lcs.source.response.rejected` audit event
([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-layer.resolution.sequence-validation-failure-is-eio"></a>

---

# The Sequence Counter

_Peios Kernel / Internals / LCS / Layers_

> The single global monotonic counter stamped on every layer-qualified entry — allocation, initialisation, and what it is not.

<a id="trm-5-3-7"></a>

LCS keeps one global monotonic counter. Every mutation that creates a
layer-qualified entry — a path entry, a value write, a key hide, a
blanket tombstone — takes the next number from it. <a id="cite-layer.sequence.every-layer-qualified-mutation-takes-the-next-number"></a>

The counter is never decremented and never reset. <a id="cite-layer.sequence.never-decremented-or-reset"></a>

It provides deterministic tiebreaking within a precedence tier
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). Wall-clock time is tracked separately, as each key's last
write time, for humans.

<a id="trm-5-3-7-1"></a>

## Allocation

Allocating a number increments the counter. **Allocated numbers are
never reused**, even if the operation later fails, times out, or is
part of a transaction that aborts. <a id="cite-layer.sequence.allocated-numbers-are-never-reused"></a>

Gaps in the sequence space are normal and carry no meaning. <a id="cite-layer.sequence.gaps-are-normal"></a>

A transactional mutation is assigned its number when the operation is
**accepted into the transaction**, not at commit. <a id="cite-layer.sequence.transactional-number-assigned-at-accept-not-commit"></a> That preserves the
order in which the caller performed the operations, which is what layer
tiebreaking and watch ordering need if it commits ([Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md#trm-5-7-2>)).

<a id="trm-5-3-7-2"></a>

## Initialisation

Each source reports the highest sequence number it has persisted in its
registration handshake, and LCS raises the counter to one above the
maximum reported. <a id="cite-layer.sequence.counter-raised-above-the-reported-source-maximum"></a> New writes therefore always outrank anything
already in storage, even after a restart. <a id="cite-layer.sequence.new-writes-outrank-stored-entries"></a>

A source registering later advances the counter the same way, to
`max(current, source_max + 1)`. <a id="cite-layer.sequence.late-registration-advances-the-counter"></a>

If that addition would overflow 64 bits the registration fails with
`EOVERFLOW` and the source is not made Active — the failure happens
before the slot becomes usable. <a id="cite-layer.sequence.registration-overflow-is-eoverflow"></a>

The counter itself refuses to hand out `U64_MAX`, so the value is never
allocated. <a id="cite-layer.sequence.u64-max-is-never-allocated"></a>

<a id="trm-5-3-7-3"></a>

## What a sequence number is not

A sequence number is not a hive generation number.

A **sequence number** orders layer-qualified entries for resolution and
is persisted by sources.

A **hive generation number** is a volatile, per-hive, kernel-owned
change epoch, exposed by `REG_IOC_QUERY_KEY_INFO` ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) so that a
watcher recovering from `OVERFLOW` can tell whether it actually missed
anything. Sources never see it and never persist it. <a id="cite-layer.sequence.generation-number-never-reaches-sources"></a>

Its baseline is initialised from the source's reported maximum sequence
at registration, purely so that observed generations are monotonic
relative to persisted entries; after that the two are unrelated. <a id="cite-layer.sequence.generation-baseline-from-the-reported-source-maximum"></a>

<a id="trm-5-3-7-4"></a>

## Restore

A restore does not write the backup's sequence numbers. It reserves a
fresh range and remaps into it, so restored entries are newer than
everything that was there before while keeping their relative order
from the backup ([Restore](</kernel/internals/lcs/backup-and-restore/restore.md#trm-5-9-3>)).

---

# Security

_Peios Kernel / Internals / LCS / Security_

> Find the Peios kernel articles about security.

Use these articles to understand security in the Peios kernel.

- [The Access Flow](</kernel/internals/lcs/security/the-access-flow.md>)
- [Access Rights](</kernel/internals/lcs/security/access-rights.md>)
- [Inheritance and Hive Roots](</kernel/internals/lcs/security/inheritance-and-hive-roots.md>)
- [Audit](</kernel/internals/lcs/security/audit.md>)

---

# The Access Flow

_Peios Kernel / Internals / LCS / Security_

> The registry's security model is KACS applied to keys — no traverse checking, symlink handling, and why an fd is a capability.

<a id="trm-5-4-1"></a>

The registry's security model is KACS applied to keys. LCS defines no
access control mechanism of its own: the same AccessCheck, the same
Security Descriptors, the same tokens and SIDs that every other Peios
subsystem uses. What this section describes is how those primitives
attach to registry operations.

Every open follows the same five steps.

1. **Token capture.** LCS takes the calling thread's effective token —
   the impersonation token if one is set, otherwise the process primary
   token. This is the same capture KACS performs for every syscall. <a id="cite-access-flow.effective-token-capture"></a>

2. **Path resolution.** LCS walks the path through the layer stack,
   following symlinks. **No access check happens during the walk.**
   Intermediate keys are not evaluated; only the final key matters. <a id="cite-access-flow.no-check-during-walk"></a>

3. **AccessCheck.** LCS calls KACS AccessCheck with the captured token,
   the final key's Security Descriptor as returned by the source, and
   the desired access mask. Every requested right must be granted or
   the open fails with `EACCES`. There is no partial grant: the caller
   gets what it asked for or nothing. <a id="cite-access-flow.all-or-nothing-or-eacces"></a>

   `MAXIMUM_ALLOWED` is the exception, and the only way to ask for
   whatever is available. AccessCheck computes the full allowed set and
   that becomes the granted mask. <a id="cite-access-flow.maximum-allowed-grants-what-is-available"></a>

4. **The granted mask is stored on the fd.** It never changes. <a id="cite-access-flow.granted-mask-fixed-at-open"></a>

5. **Per-ioctl checks are bitmask tests.** Each ioctl has a required
   right; LCS tests the fd's granted mask against it and returns
   `EACCES` without contacting the source if it is absent. The
   Security Descriptor is not re-read and AccessCheck is not
   re-evaluated. <a id="cite-access-flow.per-ioctl-bitmask-test"></a>

<a id="trm-5-4-1-1"></a>

## No traverse checking

LCS checks nothing on the way down. A process can open
`Machine\System\Services\Jellyfin` without holding any access to
`Machine\System\Services` or `Machine\System`.

This matches the Windows registry and is a deliberate difference from
filesystem path semantics, where every directory in a path is checked
for traverse. It means a key's Security Descriptor is the whole story
about who can reach it, and that an ancestor's descriptor confers no
protection on its descendants.

<a id="trm-5-4-1-2"></a>

## Symlinks

Opening a symlink follows it, and AccessCheck runs on the **target**
key, not the link. `REG_OPEN_LINK` opens the link itself instead — but
only for the final path component. A symlink encountered part-way
through a path is followed regardless.

Creating a symlink is privileged: `KEY_CREATE_SUB_KEY` and
`KEY_CREATE_LINK` on the parent, plus either `SeTcbPrivilege` or
membership of Administrators ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)).

<a id="trm-5-4-1-3"></a>

## Fds are capabilities

A key fd can be passed over a Unix socket with `SCM_RIGHTS`, and it
carries its granted mask with it. The recipient gets the access the
original opener was granted, whether or not its own token would have
passed AccessCheck. <a id="cite-access-flow.fd-passing-carries-granted-mask"></a>

This is explicit delegation and it is consistent with how fds work
everywhere else in Peios. Passing a `KEY_WRITE` fd hands over write
access.

Opening relative to a parent fd skips path parsing and AccessCheck for
the parent portion — the caller already proved its access when it
obtained the parent fd. This is the ordinary way to traverse a subtree. <a id="cite-access-flow.parent-fd-skips-check"></a>

<a id="trm-5-4-1-4"></a>

## Changing a descriptor does not revoke a handle

A Security Descriptor change takes effect for future opens. An fd that
already exists keeps the mask it was granted at open, because that is
what semantic rule 5 says ([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>)). <a id="cite-access-flow.descriptor-change-does-not-revoke-fd"></a> The recourse for genuinely revoking
access is to restart the process holding the fd.

Descriptor changes are also not layer-qualified. They are direct
mutations on the key object, and deleting a layer does not undo one
([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>), rule 4).

<a id="trm-5-4-1-5"></a>

## The second check nobody expects

Every layer-qualified mutation runs a **second** AccessCheck, against a
different object: the metadata key of the layer being written to. That
check is for `KEY_SET_VALUE` and it is in addition to the fd's granted
mask on the target key. Both must pass. [Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>) covers it.

---

# Access Rights

_Peios Kernel / Internals / LCS / Security_

> Registry rights at their Windows bit positions — the convenience masks, generic mapping, and validation of what a caller asks and a source returns.

<a id="trm-5-4-2"></a>

Registry rights occupy the Windows bit positions, so a Security
Descriptor carrying registry ACEs is binary-compatible with one written
by Windows tooling. <a id="cite-right.windows-bit-positions"></a> That is a `registry.pol` and Samba requirement, not
an aesthetic choice.

The values are in [LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>). In summary: six specific rights in bits 0–5
(`KEY_QUERY_VALUE`, `KEY_SET_VALUE`, `KEY_CREATE_SUB_KEY`,
`KEY_ENUMERATE_SUB_KEYS`, `KEY_NOTIFY`, `KEY_CREATE_LINK`), the four
standard rights `DELETE`, `READ_CONTROL`, `WRITE_DAC` and
`WRITE_OWNER`, and `ACCESS_SYSTEM_SECURITY` for the SACL, which is
itself gated by `SeSecurityPrivilege`.

There is no execute right on a key. <a id="cite-right.no-execute-right"></a>

<a id="trm-5-4-2-1"></a>

## Convenience masks and generic mapping

`KEY_READ`, `KEY_WRITE` and `KEY_ALL_ACCESS` are concrete masks, not
generic bits — they are unions of the rights above and are usable
directly. <a id="cite-right.convenience-masks-are-concrete"></a>

Separately, LCS accepts the raw KACS generic bits `GENERIC_READ`,
`GENERIC_WRITE`, `GENERIC_EXECUTE` and `GENERIC_ALL` in a caller's
`desired_access` and in ACE masks in a Security Descriptor. Those are
mapped through the registry generic mapping before AccessCheck sees
them. <a id="cite-right.generic-bits-accepted-and-mapped"></a>

`GENERIC_READ` maps to `KEY_READ`, `GENERIC_WRITE` to
`KEY_WRITE`, `GENERIC_ALL` to `KEY_ALL_ACCESS`, and **`GENERIC_EXECUTE`
maps to zero**, because there is nothing to execute. <a id="cite-right.generic-mapping"></a>

<a id="trm-5-4-2-2"></a>

## Validating what a caller asks for

`desired_access` is validated before path resolution or AccessCheck. <a id="cite-right.desired-access-validated-first"></a>

- Zero is `EINVAL`. A caller must ask for something. <a id="cite-right.zero-desired-access-is-einval"></a>
- Any bit outside the valid caller mask is `EINVAL`. <a id="cite-right.unknown-desired-access-bit-is-einval"></a>
- `MAXIMUM_ALLOWED` may appear alone or combined with anything else. <a id="cite-right.maximum-allowed-may-combine"></a>
- `SYNCHRONIZE` (`0x00100000`) is not a registry right, so it is an
  unknown bit and fails `EINVAL`. <a id="cite-right.synchronize-is-not-a-registry-right"></a>

The valid caller mask is a single constant, `REG_VALID_DESIRED_ACCESS_MASK`
([LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>)): the six specific rights, the four standard rights,
`ACCESS_SYSTEM_SECURITY`, `MAXIMUM_ALLOWED` and the four generic bits. <a id="cite-right.valid-desired-access-mask-contents"></a>

<a id="trm-5-4-2-3"></a>

## Validating what a source returns

Source-supplied Security Descriptors are validated too, because a
source is trusted for its data but not for its arithmetic ([Validation](</kernel/internals/lcs/sources/validation.md#trm-5-8-4>)).

An ACE mask may contain concrete registry rights and raw generic bits.
It **may not** contain `MAXIMUM_ALLOWED` — that is a request, not a
grant, and it is meaningless in an ACE. <a id="cite-right.ace-mask-rejects-maximum-allowed"></a>

After generic mapping, an ACE
mask must be a subset of the concrete registry rights plus
`ACCESS_SYSTEM_SECURITY`. <a id="cite-right.ace-mask-subset-after-mapping"></a>

A descriptor that breaks either rule is malformed source data: the
operation fails closed with `EIO` and an
`lcs.source.response.rejected` audit event is emitted ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-right.malformed-descriptor-is-eio"></a>

Two further constants, `REG_VALID_MAPPED_ACCESS_MASK` and
`REG_VALID_ACE_ACCESS_MASK`, express those two bounds.

<a id="trm-5-4-2-4"></a>

## Which right each operation needs

| Operation | Required |
|---|---|
| `REG_IOC_QUERY_VALUE`, `QUERY_VALUES_BATCH`, `ENUM_VALUES` | `KEY_QUERY_VALUE` <a id="cite-right.query-value"></a> |
| `REG_IOC_SET_VALUE`, `DELETE_VALUE`, `BLANKET_TOMBSTONE`, `FLUSH` | `KEY_SET_VALUE` <a id="cite-right.set-value"></a> |
| `REG_IOC_ENUM_SUBKEYS` | `KEY_ENUMERATE_SUB_KEYS` <a id="cite-right.enum-subkeys"></a> |
| `REG_IOC_QUERY_KEY_INFO` | `READ_CONTROL` <a id="cite-right.query-key-info"></a> |
| `REG_IOC_DELETE_KEY`, `HIDE_KEY` | `DELETE` <a id="cite-right.delete-key"></a> |
| `REG_IOC_NOTIFY` | `KEY_NOTIFY` <a id="cite-right.notify"></a> |
| `REG_IOC_GET_SECURITY` | `READ_CONTROL` for owner, group, DACL and label; `ACCESS_SYSTEM_SECURITY` for the SACL <a id="cite-right.get-security"></a> |
| `REG_IOC_SET_SECURITY` | `WRITE_OWNER` for owner, group or label; `WRITE_DAC` for the DACL; `ACCESS_SYSTEM_SECURITY` for the SACL; raising a label above the caller additionally requires enabled `SeRelabelPrivilege` <a id="cite-right.set-security"></a> |
| `REG_IOC_BACKUP` | `SeBackupPrivilege`, no per-key check |
| `REG_IOC_RESTORE` | `SeRestorePrivilege`, no per-key check |
| creating a key | `KEY_CREATE_SUB_KEY` on the parent <a id="cite-right.create-key"></a> |
| creating a symlink key | `KEY_CREATE_SUB_KEY` and `KEY_CREATE_LINK` on the parent, plus `SeTcbPrivilege` or Administrators |

Where a `REG_IOC_SET_SECURITY` or `GET_SECURITY` request names several
components, every right those components imply must be present before
the source is contacted. <a id="cite-right.security-info-needs-every-implied-right"></a>

`REG_IOC_FLUSH` requires `KEY_SET_VALUE` because a flush is only
meaningful to a caller that wrote something and wants it durable.
Requiring a write right stops an unprivileged reader using flush as a
disk-I/O amplifier.

<a id="trm-5-4-2-5"></a>

## Enumeration exposes names, not contents

`REG_IOC_ENUM_SUBKEYS` performs no per-child access check. Every
visible child is returned, whatever the caller's access to it. The
caller learns names, and must open each child separately — with a real
AccessCheck — to read anything. <a id="cite-right.enum-subkeys-no-per-child-check"></a>

Subtree watches work the same way: a watcher is told a descendant was
created without a check on that descendant. <a id="cite-right.subtree-watch-no-per-descendant-check"></a> Structure visibility is
deliberately weaker than content visibility, matching
`RegNotifyChangeKeyValue` and `RegEnumKeyEx`.

---

# Inheritance and Hive Roots

_Peios Kernel / Internals / LCS / Security_

> A new key's descriptor is computed from its parent by the KACS inheritance algorithm — plus hive roots and reading or writing a descriptor.

<a id="trm-5-4-3"></a>

<a id="trm-5-4-3-1"></a>

## Inheritance at creation

When `reg_create_key` creates a key, its initial Security Descriptor is
computed from the parent's by the KACS inheritance algorithm. LCS
supplies the parent descriptor, the creating token, the registry
generic mapping and the valid-mask bound, and hands the result to the
source to persist. It implements no inheritance logic of its own. <a id="cite-inherit.kacs-computes-lcs-persists"></a>

Three things about registry inheritance are worth stating.

**It is static.** The computation happens once, at creation. A later
change to the parent's descriptor does not propagate to children that
already exist. <a id="cite-inherit.static-no-repropagation"></a> Re-propagating is an explicit administrative action — a
client-side tree walk — not a kernel operation, and there is no code
anywhere in LCS that walks a tree to re-propagate.

**Only `CONTAINER_INHERIT_ACE` matters.** Every registry object is a
container: keys hold subkeys and values. Values are not independent
security objects and have no descriptors of their own; they inherit
their key's access control. <a id="cite-inherit.values-have-no-descriptor-of-their-own"></a>

`OBJECT_INHERIT_ACE` is never used to
select an ACE for inheritance. <a id="cite-inherit.object-inherit-ace-never-selects"></a> The child copy clears `OBJECT_INHERIT_ACE`,
`CONTAINER_INHERIT_ACE` and `NO_PROPAGATE_INHERIT_ACE` when
`NO_PROPAGATE_INHERIT_ACE` applies. <a id="cite-inherit.no-propagate-clears-object-inherit"></a>

**A parent with no inheritable ACEs falls back to the creating token's
default DACL.** <a id="cite-inherit.no-inheritable-aces-uses-token-default-dacl"></a>

That fallback covers the DACL only; there is no default
SACL. <a id="cite-inherit.no-default-sacl"></a>

<a id="trm-5-4-3-1-1"></a>

### Creator SIDs and generic rights survive to the next generation

An inheritable ACE naming `CREATOR OWNER` or `CREATOR GROUP`, or carrying
generic rights, is resolved for each new key. When it also propagates to
further subkeys, the child receives two ACEs:

- An effective copy with the child's owner/group substituted and generic
  rights mapped to registry rights. It has `INHERITED_ACE` and no propagation
  flags.
- An inherit-only copy retaining the original SID and generic mask, with
  `INHERITED_ACE` and its propagation flags. This copy resolves afresh when
  the next subkey is created.

This applies to both DACL and SACL entries. An ordinary concrete ACE remains
one copy. `NO_PROPAGATE_INHERIT_ACE` ends the rule at the immediate child,
so it receives only the effective copy. Existing stored descriptors are not
rewritten by upgrading the kernel; an explicit propagation operation is
needed to repair an already-created subtree.

<a id="trm-5-4-3-2"></a>

## Hive roots

A hive root has no parent, so it is the top of every inheritance chain
below it and cannot inherit anything itself. <a id="cite-inherit.hive-root-inherits-nothing"></a> Its descriptor is created
by the **source**, on first boot, and LCS enforces whatever the source
stored. <a id="cite-inherit.hive-root-descriptor-comes-from-the-source"></a>

LCS holds no template. There are no hardcoded SIDs, no default hive
root descriptors, and no code that would construct one — searching for
them finds nothing. The defaults that follow are what loregd writes;
they are conventions of the source, not properties of the kernel.

**`Machine\`:** <a id="cite-inherit.machine-root-default-descriptor"></a>

| Principal | Rights | Inheritance |
|---|---|---|
| SYSTEM | `KEY_ALL_ACCESS` | Container-inherit |
| Administrators | `KEY_ALL_ACCESS` | Container-inherit |
| Authenticated Users | `KEY_READ` | Container-inherit |

**`Users\<SID>\`:** <a id="cite-inherit.user-root-default-descriptor"></a>

| Principal | Rights | Inheritance |
|---|---|---|
| the user's SID | `KEY_ALL_ACCESS` | Container-inherit |
| SYSTEM | `KEY_ALL_ACCESS` | Container-inherit |
| Administrators | `KEY_ALL_ACCESS` | Container-inherit |

These mirror Windows HKLM and HKU. A subsystem needing something
tighter — `Machine\Security\`, say — sets an explicit descriptor on its
own subtree root at creation, overriding what it inherited.

Because there is no traverse checking ([The Access Flow](</kernel/internals/lcs/security/the-access-flow.md#trm-5-4-1>)), a restrictive
descriptor high in the tree protects only the key it is on. Protection
of a subtree comes from the descriptors its keys inherited at creation,
which is exactly why an administrator changing a parent's descriptor
and expecting the subtree to follow will be disappointed.

<a id="trm-5-4-3-3"></a>

## Reading and writing descriptors

`REG_IOC_GET_SECURITY` and `REG_IOC_SET_SECURITY` take a
`security_info` bitmask naming which components to act on: owner,
group, DACL, SACL, or mandatory integrity label (`LABEL_SECURITY_INFORMATION`). <a id="cite-inherit.security-info-selects-components"></a>

Zero is `EINVAL`, and so is any unknown flag; both
are rejected before the source is contacted, before transaction
enlistment and before any mutation. <a id="cite-inherit.security-info-zero-or-unknown-is-einval"></a>

The rights required are computed from every component named. Reading
owner, group, the DACL or the label needs `READ_CONTROL`; reading the SACL needs
`ACCESS_SYSTEM_SECURITY`. Setting owner **or group** needs
`WRITE_OWNER`, as does setting the label; setting the DACL needs `WRITE_DAC`; setting the SACL
needs `ACCESS_SYSTEM_SECURITY`. A request naming several components
must hold all the corresponding rights.

A set is a merge, not a replacement. LCS reads only the components
`security_info` names from the supplied self-relative descriptor and
preserves the existing ones. <a id="cite-inherit.set-security-is-a-merge"></a>

Component selection includes its control flags even when the component
has no bytes. A null ACL remains `PRESENT` clear, but its defaulted,
inheritance and protection flags survive a query or an update to another
component. Replacing a selected DACL or SACL takes that ACL's flags from
the input descriptor, including for a null ACL; unselected component
flags are preserved. An empty ACL remains present with zero ACEs and is
not converted to null. The same preservation rule applies to a defaulted
null group. <a id="cite-inherit.null-acl-control-flags"></a>

`LABEL_SECURITY_INFORMATION` reads only the first effective mandatory-label
ACE from the SACL, omitting inherit-only labels and every non-label ACE.
If there is no effective label, the returned subset has no SACL. Reading
this subset needs `READ_CONTROL`; writing it needs `WRITE_OWNER`. Neither
operation needs `ACCESS_SYSTEM_SECURITY` or `SeSecurityPrivilege`.
<a id="cite-inherit.label-access-and-projection"></a>

A label update removes the existing mandatory-label ACEs and inserts the
supplied label before the remaining SACL entries. An input descriptor
with no SACL clears the explicit label. Non-label SACL entries, SACL
inheritance and protection flags, and all unselected descriptor components
are preserved, including flags on a null DACL. Clearing the last SACL
entry clears `SE_SACL_PRESENT` while retaining the other SACL flags.
<a id="cite-inherit.label-merge-preserves-other-security"></a>

For a label-only subset, a supplied SACL must contain exactly one
mandatory-label ACE with an `S-1-16-<level>` SID and without
`INHERIT_ONLY_ACE`; an empty ACL, an audit ACE, or multiple labels is
`EINVAL`. `SACL_SECURITY_INFORMATION` and `LABEL_SECURITY_INFORMATION`
cannot be combined. These input errors are rejected before source contact
or transaction enlistment. <a id="cite-inherit.label-input-validation"></a>

An explicit label above the current caller's integrity level requires
enabled `SeRelabelPrivilege`, checked before source contact or transaction
enlistment; otherwise the update fails with `EACCES`. Labels at or below
the caller's level do not require that privilege. The same rule applies
to an explicit label inside a whole-SACL write: `SeSecurityPrivilege`
does not substitute for `SeRelabelPrivilege`. Existing fd rights remain
cached, but this privilege check uses the caller performing the update.
<a id="cite-inherit.label-level-constraint"></a>

The result must still have an owner; a
merge that would leave the descriptor ownerless is `EINVAL`. <a id="cite-inherit.merge-must-leave-an-owner"></a>

A null
group SID stays valid. <a id="cite-inherit.null-group-sid-is-valid"></a>

Enlisting a descriptor change in a transaction gives it atomicity with
the rest of the transaction's operations. It does not make it
layer-qualified: the change is still a direct mutation on the key, is
still not reverted by deleting a layer, and is simply not applied at
all if the transaction aborts. <a id="cite-inherit.descriptor-change-in-a-transaction"></a>

---

# Audit

_Peios Kernel / Internals / LCS / Security_

> The fifteen audit events LCS emits, which are unconditional, how registry writes are audited through a key handle's alarm mask, and what happens when emission itself fails.

<a id="trm-5-4-4"></a>

LCS emits audit events through KMES. Fifteen events exist. <a id="cite-lcs-audit.events-through-kmes"></a>

| Event | Emitted when |
|---|---|
| `lcs.audit.key.opened` | A key open matched a SACL audit ACE. <a id="cite-lcs-audit.key-open.on-sacl-match"></a> |
| `lcs.audit.value.set` | A value write through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.value.deleted` | A value delete through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.key.tombstoned` | A blanket tombstone set or cleared through a handle whose audit mask covers `KEY_SET_VALUE`. |
| `lcs.audit.key.deleted` | A key deleted through a handle whose audit mask covers `DELETE`. |
| `lcs.audit.key.hidden` | A key hidden through a handle whose audit mask covers `DELETE`. |
| `lcs.audit.key.created` | A key create that made a key matched a SACL audit ACE on the parent. |
| `lcs.audit.key.descriptor.changed` | A descriptor change included the SACL, or its right is covered by the handle's audit mask. |
| `lcs.audit.transaction.committed` | A transaction that staged an audited write ended. |
| `lcs.audit.backup.started` | After admission checks and before `REG_IOC_BACKUP` requests its read-only snapshot or reads any subtree data. <a id="cite-lcs-audit.backup-start.before-any-read"></a> |
| `lcs.audit.backup.ended` | After a backup completes or fails after starting. <a id="cite-lcs-audit.backup-complete.after-finish-or-failure"></a> |
| `lcs.audit.restore.started` | Before `REG_IOC_RESTORE` modifies any source state. <a id="cite-lcs-audit.restore-start.before-any-mutation"></a> |
| `lcs.audit.restore.ended` | After a restore completes or fails after starting. <a id="cite-lcs-audit.restore-complete.after-finish-or-failure"></a> |
| `lcs.source.response.rejected` | LCS rejected malformed source data. <a id="cite-lcs-audit.validation-failure.on-malformed-source-data"></a> |
| `lcs.config.value.rejected` | LCS rejected an invalid self-configuration value. <a id="cite-lcs-audit.self-config-invalid.on-invalid-value"></a> |

A registry open that a privilege contributed to is also recorded, as KACS's
`kacs.audit.privilege.used`; see [Privilege use on opens](#privilege-use-on-opens).

Backup and restore are audited **unconditionally**, whatever the SACL
on the target key says. <a id="cite-lcs-audit.backup-and-restore-unconditional"></a> They are privilege-gated bulk operations that
bypass per-key access checks entirely, so the audit trail is the only
record that they happened.

Every payload is a single MessagePack map with string keys. <a id="cite-lcs-audit.payload-is-a-msgpack-map"></a>
Each field path is written as nested maps, one per segment, so
`object.key.guid` is `{object: {key: {guid: …}}}`. A value LCS does not
have is left out rather than written as nil, and every map counts only
the keys actually written (PGSS [Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)).

The key GUID, `object.key.guid`, is a 16-byte binary value, and the
caller's SID is a binary KACS encoding. The token and process GUIDs
are not payload fields at all: they ride in the KMES event header, so
the payload never repeats them. <a id="cite-lcs-audit.payload-guid-and-sid-encoding"></a>

<a id="trm-5-4-4-1"></a>

## The caller summary

Every event except `lcs.source.response.rejected` and
`lcs.config.value.rejected` describes the effective token used for the
operation under `subject.token`. It has six fields and no more: `sid`,
`integrity`, `id` (the token's LUID), `auth-id` (its logon session's
LUID), `type` (`primary` or `impersonation`) and `impersonation`, the
impersonation level. <a id="cite-lcs-audit.caller-summary-nine-fields"></a>

The bound is deliberate. Group lists, privilege arrays, claims and
default DACLs are unbounded and are never included. The summary carries
enough to correlate an event with a caller, and nothing that could make
one event arbitrarily large. `lcs.source.response.rejected` and
`lcs.config.value.rejected` carry no caller: neither is a principal
acting.

A primary token reports an impersonation
level of 0. <a id="cite-lcs-audit.primary-token-impersonation-level-zero"></a> An Anonymous impersonation token also
reports 0, which is why `subject.token.type` is recorded beside it.

<a id="trm-5-4-4-2"></a>

## Key opens

`lcs.audit.key.opened` carries the caller summary, then
`object.kind` (always `key`, which names the table the masks decode
against), `object.key.guid`, the requested and granted masks as
`access.requested` and `access.granted`, `outcome.success` (`true`
when the open was allowed), and `trigger.sacl-match` — bit 0 for a
success-audit match, bit 1 for a failure-audit match, no other
bits. <a id="cite-lcs-audit.key-open.payload-fields"></a>

`access.granted` is forced to zero on a denial, and that is enforced
rather than merely intended: a denied event carrying a non-zero granted
mask is rejected as a malformed payload. <a id="cite-lcs-audit.key-open.denied-event-has-zero-granted"></a>

`access.requested` is the mask
after registry generic mapping, with `MAXIMUM_ALLOWED` re-added if the
caller asked for it. <a id="cite-lcs-audit.key-open.requested-access-is-post-mapping"></a>

SACL evaluation follows the KACS AccessCheck algorithm — the SACL is
evaluated alongside the DACL, not separately. <a id="cite-lcs-audit.sacl-evaluated-with-the-dacl"></a>

Reading or modifying a
SACL requires `ACCESS_SYSTEM_SECURITY`, which is itself gated by
`SeSecurityPrivilege`. <a id="cite-lcs-audit.sacl-access-gated-by-sesecurityprivilege"></a>

A request of `MAXIMUM_ALLOWED` **alone** maps to a desired mask of zero,
so AccessCheck's SACL walk matches each audit ACE against the *granted*
mask instead. <a id="cite-lcs-audit.key-open.maximum-allowed-matches-granted-mask"></a> An audit ACE says "audit when someone gets this right",
and with `MAXIMUM_ALLOWED` they did get it.

Such an open therefore
always audits as a success, which is correct: `MAXIMUM_ALLOWED` returns
whatever is available and never fails, so a failure ACE has nothing to
record. <a id="cite-lcs-audit.key-open.maximum-allowed-always-audits-success"></a>

An ACE naming a right the caller did not receive still does not
match. <a id="cite-lcs-audit.key-open.ace-for-ungranted-right-does-not-match"></a>

<a id="trm-5-4-4-3"></a>

## Registry writes

Writes are audited through the key handle, as file operations are
through a file handle. When a key is opened, the access check evaluates
the key's `SYSTEM_ALARM*` ACEs against the caller, and the union of the
masks of the ones that match becomes the handle's **continuous-audit
mask**. <a id="cite-lcs-audit.write.alarm-mask-cached-at-open"></a> Success and failure
`SYSTEM_AUDIT` ACEs do not contribute; they govern the open itself. This
is the continuous auditing of [Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>) with LCS as the enforcement point,
except in two respects: LCS writes records named for the operation
rather than `kacs.audit.handle.used`, and a record it cannot write does
not fail the operation (see below).

The mask is fixed for the life of the handle. A later change to the
key's SACL neither adds to it nor takes from it, so a handle that removes
the alarm ACE is still audited for the change it makes, and handles
opened before an alarm ACE was added are not. <a id="cite-lcs-audit.write.mask-fixed-for-handle-life"></a>

A write through the handle is recorded when the right it needs overlaps
the mask, and not otherwise. <a id="cite-lcs-audit.write.recorded-when-right-overlaps-mask"></a>
The right is the one the handle's own gate checks:

| Event | Operation | Right |
|---|---|---|
| `lcs.audit.value.set` | `REG_IOC_SET_VALUE` | `KEY_SET_VALUE` |
| `lcs.audit.value.deleted` | `REG_IOC_DELETE_VALUE` | `KEY_SET_VALUE` |
| `lcs.audit.key.tombstoned` | `REG_IOC_BLANKET_TOMBSTONE` | `KEY_SET_VALUE` |
| `lcs.audit.key.deleted` | `REG_IOC_DELETE_KEY` | `DELETE` |
| `lcs.audit.key.hidden` | `REG_IOC_HIDE_KEY` | `DELETE` |

<a id="cite-lcs-audit.write.rights-per-event"></a>

A write that fails is recorded too, with `outcome.success` false and
`outcome.errno` the negative errno the caller received. That includes a
write the handle's own gate refuses because the handle lacks the right:
the mask comes from the SACL, not the grant, so it can cover rights the
handle was not given. <a id="cite-lcs-audit.write.failures-recorded"></a>

Every write record carries the caller summary; `object.kind` (`key`),
`object.key.guid` and `object.key.path`, the handle's key and its
resolved path; `object.key.layer.name`, the layer written; the masks
`access.requested` (the right above), `access.granted` (the handle's
grant), `access.matched` and `access.audit-mask`; `transaction.id` when
the write was staged in a transaction; and `outcome.success`, with
`outcome.errno` on a failure. A failure also carries `request.timed-out`.
Value records add `object.key.value.name`; a value write adds the value's
type and length and a digest of its data, and `mutation.sequence`, with
`mutation.sequence-expected` on a compare-and-swap; a tombstone change
adds `operation.name` (`set` or `clear`); a hide adds `mutation.sequence`.
A field the operation had not reached when it failed is left out. <a id="cite-lcs-audit.write.payload-fields"></a>

A value's data is never recorded. In its place a record carries the data's
type, its length and its SHA-256 digest, so two records can be compared
without either holding the data. Every digest LCS records, of a value or
of a security descriptor, is SHA-256. <a id="cite-lcs-audit.write.data-recorded-as-sha256-digest"></a>

A value write outside a transaction also records the value it replaced, as
`object.key.value.type-previous`, `.length-previous` and
`.digest-previous`: the effective value before the write, across every
layer. A value delete records the value it removed the same way. <a id="cite-lcs-audit.write.previous-value-recorded"></a>

A write whose source does not answer before the request timeout fails
with `ETIMEDOUT`, and its record carries `request.timed-out` true. The
source is not told to cancel, so the change may still land; for a value
write or descriptor change outside a transaction, LCS also applies the
write's kernel-side effects when the late reply arrives, and nothing
records who made the write then. Read a timed-out record as "may have
been applied later". <a id="cite-lcs-audit.write.timed-out-may-apply-later"></a>

A write made in a transaction is recorded when it is staged, with
`transaction.id`. Its `outcome.success` then says the source accepted it
into the transaction, not that it took effect. <a id="cite-lcs-audit.write.transacted-recorded-when-staged"></a>

<a id="trm-5-4-4-3-1"></a>

### Transaction ends

A transaction that staged at least one recorded write — a write or a key
creation whose record was emitted — writes one
`lcs.audit.transaction.committed` when it ends, and only one: at a
`REG_IOC_COMMIT` that leaves it committed or otherwise finished, at its
timeout, or when its fd is closed without a commit. A commit that fails
and leaves the transaction open writes nothing yet. <a id="cite-lcs-audit.txn-committed.once-per-recorded-transaction"></a>

It carries the caller summary, `transaction.id` and `transaction.state`,
the state it ended in, and `outcome.success`, true only for `committed`.
A failure adds `transaction.commit-outstanding` and `outcome.reason`:
`aborted` (closed without a commit, or a layer it wrote was deleted),
`timed-out` or `source-error`; and `outcome.errno` when a
`REG_IOC_COMMIT` call failed. <a id="cite-lcs-audit.txn-committed.payload-fields"></a>

On `REG_IOC_COMMIT` the subject is the caller who committed, not the one
who staged the writes. A transaction that ended by timeout or by its fd
closing has nobody acting, and names the subject that staged its first
recorded write. The timer that ends a transaction runs in softirq context,
which cannot build a record; the record is written from the work item
that aborts the transaction at the source. <a id="cite-lcs-audit.txn-committed.subject"></a>

A commit whose reply does not arrive in time reports `timed-out` with
`transaction.commit-outstanding` true: the source may have committed it
before the reply was lost.

<a id="trm-5-4-4-4"></a>

## Key creation

`lcs.audit.key.created` records a key a create made. Creating a key
checks only `KEY_CREATE_SUB_KEY` on its parent, so the parent's SACL
decides, by the rule that decides `lcs.audit.key.opened`: a success audit
ACE on the parent that matches the caller. <a id="cite-lcs-audit.key-created.on-parent-sacl-match"></a>

Only a key that was made is recorded. A create that found the key already
present and opened it instead writes nothing here. The record is written
once the key exists, or is staged in a transaction, so a create whose
handle then fails to reach the caller is still recorded. <a id="cite-lcs-audit.key-created.only-made-keys"></a>

It carries the caller summary; `object.kind`; the new key's
`object.key.guid`, `object.key.path` and `object.key.layer.name`;
`object.key.created` (true), `object.key.volatile`,
`object.key.volatile-requested` and `object.key.symlink`; the new key's
descriptor as `object.sd.length` and `object.sd.owner`; `access.requested`
(`KEY_CREATE_SUB_KEY`) and `access.granted`, from the parent check;
`transaction.id` when staged; and `outcome.success`. <a id="cite-lcs-audit.key-created.payload-fields"></a>

<a id="trm-5-4-4-5"></a>

## Descriptor changes

`lcs.audit.key.descriptor.changed` records `REG_IOC_SET_SECURITY` through
a key handle.

A change that includes the SACL is recorded whatever the handle's mask
says. It is recorded once the handle's own gate has admitted it, which
takes `ACCESS_SYSTEM_SECURITY`: a handle without that right is refused
first, and asking for a SACL change writes no record. <a id="cite-lcs-audit.descriptor-changed.sacl-change-always-recorded"></a>

Any other change is recorded when the right it needs — `WRITE_OWNER` for
the owner or group, `WRITE_DAC` for the DACL — overlaps the handle's
mask, and then failures are recorded as writes' are. <a id="cite-lcs-audit.descriptor-changed.other-changes-follow-mask"></a>

The record carries what a write record does, without a layer, and the
descriptors: `object.sd.components`, the `security_info` bits asked for;
and for the descriptor written and the one it replaced, `object.sd.length`
and `object.sd.length-previous`, their SHA-256 digests `object.sd.digest`
and `object.sd.digest-previous`, and their owners `object.sd.owner` and
`object.sd.owner-previous`. `access.requested` is every right the change
needs, and `access.matched` is zero when only the SACL made the record
exist. <a id="cite-lcs-audit.descriptor-changed.payload-fields"></a>

<a id="trm-5-4-4-6"></a>

## Privilege use on opens

A registry open whose access check used a privilege — `SeSecurityPrivilege`
for `ACCESS_SYSTEM_SECURITY`, `SeTakeOwnershipPrivilege` for
`WRITE_OWNER` — writes KACS's `kacs.audit.privilege.used` when the
caller's token audit policy asks for privilege use, in the shape KACS
uses for its own access checks, with `object.kind` `key`. The key's
identity is not carried. The checks LCS makes for layer writes and on a
create's parent record none. <a id="cite-lcs-audit.open.privilege-use-recorded"></a>

<a id="trm-5-4-4-7"></a>

## Backup and restore

`lcs.audit.backup.started` and `lcs.audit.restore.started` carry the
caller summary, `object.key.guid` for the subtree root, and
`operation.fd`, the descriptor the stream is written to or read from.

`lcs.audit.backup.ended` and `lcs.audit.restore.ended` carry the
caller summary, `object.key.guid` and `outcome.success`. When the
operation failed they also carry `outcome.errno`, the error as a
negative errno; on success it is absent.

<a id="trm-5-4-4-8"></a>

## Source validation failures

`lcs.source.response.rejected` carries the source slot as
`source.rsi.slot` and then, where each is known, the hive name as
`source.rsi.hive`, the RSI request id and operation code as
`request.id` and `request.op-code`, and the key GUID as
`object.key.guid`. <a id="cite-lcs-audit.validation-failure.payload-fields"></a> `outcome.reason` names what was wrong.
There are twelve:

`malformed-security-descriptor`, `malformed-layer-name`,
`unknown-rsi-status-code`, `future-sequence-number`,
`duplicate-winning-sequence-tie`,
`malformed-layer-metadata-security-descriptor`,
`malformed-key-name`, `malformed-value-name`,
`malformed-response-payload`, `malformed-key-metadata`,
`malformed-value-payload`, `malformed-delete-layer-orphan-list`. <a id="cite-lcs-audit.validation-failure.twelve-classes"></a>

The three name classes are field-specific: layer-name fields, key
component or child-name fields, and value-name fields respectively. <a id="cite-lcs-audit.validation-failure.name-classes"></a>

The structural classes cover a response whose operation-specific
payload has the wrong shape or trailing bytes; a lookup or
enumeration whose metadata block is incomplete, duplicated,
unreferenced or nil; a value payload with an invalid type, a
tombstone/data mismatch or oversized data; and an invalid orphan GUID
array from `RSI_DELETE_LAYER`. <a id="cite-lcs-audit.validation-failure.structural-classes"></a>

<a id="trm-5-4-4-9"></a>

## Configuration

`lcs.config.value.rejected` has the same shape as KMES's
`kmes.config.value.rejected`, with every field under one `config`
map. It carries the offending parameter's key and name as
`config.key.path` and `config.name`; the expected type and numeric
range as `config.expected.type`, `config.expected.min` and
`config.expected.max`; what was actually received as
`config.received.kind` — one of `missing`, `wrong-type` or
`out-of-range` — with `config.received.type` for a value of the wrong
type or `config.received.value` for one out of range; and, as
`config.value`, the value LCS retained instead. <a id="cite-lcs-audit.self-config.payload-fields"></a>

Because `missing` counts as invalid, a first boot before seed restore
emits one of these per parameter on each refresh: nineteen events
against an empty `Registry\` key. <a id="cite-lcs-audit.self-config.missing-counts-as-invalid"></a> That is correct and expected, but it
is a noticeable share of the boot audit stream.

<a id="trm-5-4-4-10"></a>

## What happens when emission fails

The policy differs per event, and the differences are the point.

- **`lcs.audit.key.opened`.** If LCS cannot *construct* a valid payload —
  corrupt internal state, allocation failure, anything on the LCS side
  — the open fails with `EIO` and no key fd is published. <a id="cite-lcs-audit.emit-failure.key-open-construct-failure-fails-the-open"></a> If the
  payload is valid but KMES cannot *retain* the event — unavailable,
  ring drops, capacity pressure, no consumer — the access decision and
  the fd publication are unaffected. Loss accounting is KMES's problem. <a id="cite-lcs-audit.emit-failure.key-open-retain-failure-is-harmless"></a>
- **`lcs.audit.backup.started`, `lcs.audit.restore.started`.** Emission
  failure returns `EIO` and the operation does not start. Nothing is
  read and nothing is written. <a id="cite-lcs-audit.emit-failure.start-events-block-the-operation"></a>
- **`lcs.audit.backup.ended`, `lcs.audit.restore.ended`.** The operation
  has already finished. Emission is attempted; failure does not change
  the result. <a id="cite-lcs-audit.emit-failure.complete-events-are-best-effort"></a>
- **`lcs.source.response.rejected`.** The triggering operation is
  already failing with `EIO`. Emission is attempted; failure does not
  change that. <a id="cite-lcs-audit.emit-failure.validation-failure-is-best-effort"></a>
- **`lcs.config.value.rejected`.** The invalid value has already been
  ignored and the previous known-good value retained. Emission is
  attempted; failure leaves the retained configuration in force. <a id="cite-lcs-audit.emit-failure.self-config-is-best-effort"></a>
- **The write, creation, descriptor-change and transaction records.**
  Each is written after the source has applied or refused the operation,
  or after the transaction's state is final. Emission is attempted; a
  record that cannot be built or retained leaves the caller's result as
  it was. <a id="cite-lcs-audit.emit-failure.write-records-preserve-result"></a>
  These records fire no `lcs:lcs_audit_emit` or `lcs:lcs_audit_emit_failed`
  tracepoint; the tracepoints' event-type codes cover the other seven.

The rule underneath them all: an audit failure blocks an operation only
where the audit record is the *point* of the operation being permitted.
A privileged bulk export whose start could not be recorded does not
happen. A key open whose decision could not be recorded does not
happen. Everything downstream of an already-determined outcome records
what it can.

LCS constructs the payload and attempts to enqueue it before
continuing past the audit point. It never waits for a userspace
consumer to observe or retain the event. <a id="cite-lcs-audit.enqueue-without-awaiting-a-consumer"></a>

---

# Watches

_Peios Kernel / Internals / LCS / Watches_

> Find the Peios kernel articles about watches.

Use these articles to understand watches in the Peios kernel.

- [The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md>)
- [Event Records](</kernel/internals/lcs/watches/event-records.md>)
- [Dispatch](</kernel/internals/lcs/watches/dispatch.md>)
- [Queues and Overflow](</kernel/internals/lcs/watches/queues-and-overflow.md>)

---

# The Watch Model

_Peios Kernel / Internals / LCS / Watches_

> A persistent subscription to changes on an open key, following inotify rather than the Windows model — what it observes, its event types and filters.

<a id="trm-5-6-1"></a>

A watch is a persistent subscription to changes on an open key. It
follows the inotify model rather than the Windows one: once armed, it
stays armed until the fd closes, and events keep arriving without
re-registration. <a id="cite-watch.model.persistent-until-fd-close"></a>
`RegNotifyChangeKeyValue` is single-shot, and the window between
receiving a notification and re-registering is a window in which
changes are missed; a persistent watch has no such window.

A watch is armed by `REG_IOC_NOTIFY` on a key fd, which requires
`KEY_NOTIFY` in the fd's granted mask. Arming takes a filter — a bitmask
of event categories — and a subtree flag. After arming, the fd is
pollable: `EPOLLIN` reports pending events, and `read()` returns
structured records. <a id="cite-watch.model.armed-fd-is-pollable"></a>

Each fd carries at most one watch. <a id="cite-watch.model.one-watch-per-fd"></a>

Arming an already-armed fd replaces the filter and the subtree setting
and leaves queued events in place. <a id="cite-watch.model.rearm-replaces-filter-and-keeps-queue"></a>

Arming with a filter of zero disarms: the watch is removed and every
pending event is discarded. <a id="cite-watch.model.zero-filter-disarms-and-discards"></a>
To watch one key under two different filters, open it twice.

Arming a watch on a key that is already orphaned fails with `ENOENT`. A
watch armed before the key was orphaned stays armed ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)).

<a id="trm-5-6-1-1"></a>

## What a watch observes

Events describe changes to **effective** state, not to layer mechanics.
A watcher sees that a value changed; it does not see which layer won,
or that a layer was deleted. <a id="cite-watch.model.reports-effective-state-not-layer-mechanics"></a>
Removing a hiding entry that was concealing a lower-precedence key
produces `SUBKEY_CREATED`. Removing a whole layer is recovery dispatch
rather than a diff, and reaches a watcher as `OVERFLOW` ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). The layer
system is not visible through a watch at all.

The events are computed by diffing the effective state before the
mutation against the effective state after it, which is what makes this
true by construction rather than by careful case analysis. <a id="cite-watch.model.computed-by-diffing-effective-state"></a>

A change that replaces the key at a child name with a different key
object — different GUID, same name — produces `SUBKEY_DELETED` followed
by `SUBKEY_CREATED`, because that is what the diff says happened. <a id="cite-watch.model.key-replacement-is-delete-then-create"></a>

Only committed state is observable. Operations inside an uncommitted
transaction produce nothing; the whole set fires at commit ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

<a id="trm-5-6-1-2"></a>

## Event types

| Event | Code | Name field | Meaning |
|---|---|---|---|
| `REG_WATCH_VALUE_SET` | 1 | value name | The effective value at this name changed or appeared. <a id="cite-watch.model.event-value-set"></a> |
| `REG_WATCH_VALUE_DELETED` | 2 | value name | The effective value at this name disappeared. <a id="cite-watch.model.event-value-deleted"></a> |
| `REG_WATCH_SUBKEY_CREATED` | 3 | subkey name | A child key became visible. <a id="cite-watch.model.event-subkey-created"></a> |
| `REG_WATCH_SUBKEY_DELETED` | 4 | subkey name | A child key became invisible. <a id="cite-watch.model.event-subkey-deleted"></a> |
| `REG_WATCH_SD_CHANGED` | 5 | empty | The watched key's Security Descriptor was modified. <a id="cite-watch.model.event-sd-changed"></a> |
| `REG_WATCH_KEY_DELETED` | 6 | empty | The watched key itself became invisible. <a id="cite-watch.model.event-key-deleted"></a> |
| `REG_WATCH_OVERFLOW` | 7 | empty | Events were dropped; re-read to recover. <a id="cite-watch.model.event-overflow"></a> |

`VALUE_SET` fires when a value is written, and when a tombstone or
blanket tombstone is removed and a lower-precedence value surfaces. <a id="cite-watch.model.value-set-fires-on-write-unmask-or-layer-deletion"></a>

`VALUE_DELETED` fires when the last entry for a name goes away, when a
tombstone masks every entry, and when a blanket tombstone masks this
name. <a id="cite-watch.model.value-deleted-fires-on-last-entry-gone-or-masked"></a>

`SUBKEY_CREATED` and `SUBKEY_DELETED` cover both halves of the naming
model: a path entry appearing or being removed, and a hiding entry
being removed or created. <a id="cite-watch.model.subkey-events-cover-path-and-hiding-entries"></a>

The three no-name events carry no name, and that is enforced: a record
constructed with a name for `SD_CHANGED`, `KEY_DELETED` or `OVERFLOW`
is rejected rather than emitted. <a id="cite-watch.model.no-name-events-reject-a-name"></a>

<a id="trm-5-6-1-3"></a>

## Filters

The filter selects event *categories*, not individual event types. <a id="cite-watch.model.filter-selects-categories"></a>

| Filter bit | Value | Admits |
|---|---|---|
| `REG_NOTIFY_VALUE` | `0x01` | `VALUE_SET`, `VALUE_DELETED` <a id="cite-watch.model.filter-value-admits-value-events"></a> |
| `REG_NOTIFY_SUBKEY` | `0x02` | `SUBKEY_CREATED`, `SUBKEY_DELETED` <a id="cite-watch.model.filter-subkey-admits-subkey-events"></a> |
| `REG_NOTIFY_SD` | `0x04` | `SD_CHANGED` <a id="cite-watch.model.filter-sd-admits-sd-changed"></a> |
| `REG_NOTIFY_ALL` | `0x07` | all three of the above <a id="cite-watch.model.filter-all-admits-all-three-categories"></a> |

`KEY_DELETED` and `OVERFLOW` are delivered unconditionally. They are
not in any category and no filter suppresses them. <a id="cite-watch.model.key-deleted-and-overflow-bypass-the-filter"></a>
The first tells a watcher its key is gone, and the second tells it that
what it has been told is incomplete. Neither is something a watcher can
usefully opt out of.

A filter containing an undefined bit is rejected. <a id="cite-watch.model.undefined-filter-bit-rejected"></a>

A subtree flag other than 0 or 1, or a non-zero padding byte in the
argument structure, is rejected the same way. <a id="cite-watch.model.subtree-flag-must-be-zero-or-one"></a>

<a id="trm-5-6-1-4"></a>

## Blanket tombstones

A watcher never learns that a blanket tombstone exists. <a id="cite-watch.model.blanket-tombstone-never-surfaces-as-such"></a>

When one is written, LCS works out which values it newly masks and
emits one `VALUE_DELETED` per name; when one is removed, one
`VALUE_SET` per name that became visible. <a id="cite-watch.model.blanket-tombstone-expands-to-per-value-events"></a>
The per-value view is the only view.

---

# Event Records

_Peios Kernel / Internals / LCS / Watches_

> Events read from the key fd with read() — the record layout, why not every subtree record carries a path, and forward compatibility.

<a id="trm-5-6-2"></a>

These registry watch records are notifications, not KMES events. They have
no MessagePack payload, KMES envelope, or kernel-stamped emitter identity.
Use them to discover changes that require a fresh read, not as an audit
trail. The `.evman` event catalog does not define this binary interface.

Events are read from the key fd with `read()`. A single call returns as
many complete events as fit in the caller's buffer; an event is never
split across two calls. <a id="cite-watch.record.read-returns-whole-events-only"></a>

If the buffer cannot hold even the first queued event, `read()` fails
with `EINVAL` — the buffer is too small to make progress, and the caller
has to try again with a larger one. <a id="cite-watch.record.buffer-too-small-is-einval"></a>

On an armed fd with an empty queue, `read()` blocks, or returns
`EAGAIN` under `O_NONBLOCK`. <a id="cite-watch.record.empty-queue-blocks-or-eagain"></a>

Only events that were copied out in full are dequeued. <a id="cite-watch.record.only-fully-copied-events-dequeued"></a>

<a id="trm-5-6-2-1"></a>

## Layout

Every record begins with the same four fields. <a id="cite-watch.record.common-header-fields"></a>

| Offset | Size | Field |
|---|---|---|
| 0 | 4 | `total_len` |
| 4 | 2 | `event_type` |
| 6 | 2 | `name_len` |
| 8 | `name_len` | `name`, UTF-8 |

All integers are little-endian. <a id="cite-watch.record.integers-are-little-endian"></a>

`total_len` is the whole record including this header; it is how a
consumer advances to the next event, and it is the only safe way to do
so. <a id="cite-watch.record.total-len-covers-whole-record"></a>

A subtree watch's records carry additional fields after the name,
locating the key the change happened on relative to the watched key: <a id="cite-watch.record.subtree-records-carry-relative-path"></a>

| Size | Field |
|---|---|
| 2 | `path_depth` |
| `2 + n` each | `path_components`: `len` (u16) then that many UTF-8 bytes |

`path_depth` is the number of components from the watched key down to
the changed key; zero means the change was on the watched key itself. <a id="cite-watch.record.path-depth-counts-from-watched-key"></a>

The components are length-prefixed rather than joined with a separator,
because registry names can contain any Unicode character and value
names can contain backslashes — a concatenated path string would be
ambiguous. <a id="cite-watch.record.path-components-are-length-prefixed"></a>

The header offsets are ABI, named in `include/uapi/pkm/lcs.h` and listed in
[LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>).

<a id="trm-5-6-2-2"></a>

## Not every record on a subtree watch has a path

`OVERFLOW` records are emitted in the bare eight-byte form, on every
watch, whether or not that watch is a subtree watch. <a id="cite-watch.record.overflow-is-always-the-bare-form"></a>

`KEY_DELETED` is not: a subtree watcher receives it in the subtree
form, with a `path_depth` of its own. <a id="cite-watch.record.key-deleted-uses-the-subtree-form"></a>

A consumer of a subtree watch therefore cannot assume the subtree
fields are present on every record it reads. `total_len` is the cursor;
`path_depth` is read only when the record is long enough to hold it.

<a id="trm-5-6-2-3"></a>

## Length limits

`name_len` and each component length are 16-bit. <a id="cite-watch.record.length-fields-are-16-bit"></a>

If an event's name or one of its path components is too long to be
represented, LCS does not emit a truncated or malformed record: it
substitutes or preserves an `OVERFLOW` for that watcher instead, which
is a statement the consumer already knows how to act on. <a id="cite-watch.record.unrepresentable-length-becomes-overflow"></a>

<a id="trm-5-6-2-4"></a>

## Forward compatibility <a id="cite-watch.record.appended-fields-are-skipped-by-total-len"></a>

Future versions may append fields after `path_components`. An existing
consumer skips them, because it advances by `total_len`; a newer one
compares `total_len` against what it has parsed to discover whether the
optional fields are present. This is the whole extension mechanism, and
it is why the length field comes first.

---

# Dispatch

_Peios Kernel / Internals / LCS / Watches_

> Given a mutation, which armed watches hear about it — computed from object identity and ancestry, with depth, batching and recovery.

<a id="trm-5-6-3"></a>

Dispatch answers one question: given a mutation on a key, which armed
watches hear about it? The answer is computed from object identity and
from ancestry captured at open time, never from a path string resolved
at the moment of the event. <a id="cite-watch.dispatch.computed-from-identity-and-captured-ancestry"></a>

<a id="trm-5-6-3-1"></a>

## A watch is bound to an object

A watch is registered against the GUID on the fd it was armed through.
It fires for changes to *that object*. <a id="cite-watch.dispatch.registered-against-the-fd-guid"></a>

If a layer change causes a different key to become visible at the same
path, the watch does not move: the new key is a different object with a
different GUID, and nothing about the old watch refers to a name. <a id="cite-watch.dispatch.watch-does-not-follow-the-path"></a>

To follow the path rather than the object, a process detects the change
— through `KEY_DELETED` on the old object, or a subtree watch on the
parent — re-opens the path, and arms a new watch. This is the fd model
applied consistently: an fd is a capability bound to one identity.

The converse also holds. If a watched key is hidden, `KEY_DELETED` is
delivered, but the watch is not removed. <a id="cite-watch.dispatch.hiding-keeps-the-watch-armed"></a>

Should the hiding layer later be deleted, the key reappears at its
original path with the same GUID, and events resume. <a id="cite-watch.dispatch.events-resume-when-the-key-reappears"></a>
There is no re-emergence event; the watcher simply observes the key
being active again. <a id="cite-watch.dispatch.no-re-emergence-event"></a>

<a id="trm-5-6-3-2"></a>

## The ancestor chain

Subtree dispatch needs to know where a key sits in the tree, and it
learns that once, at open.

Resolving a path walks it component by component, and the GUID at each
level is retained on the resulting fd as the **ancestor chain** —
root GUID through parent GUID to the key itself. <a id="cite-watch.dispatch.ancestor-chain-captured-at-open"></a>
It costs nothing extra: the walk had to resolve those components
anyway.

A relative open copies the parent fd's chain and extends it with the
components the relative walk resolved. <a id="cite-watch.dispatch.relative-open-extends-the-parent-chain"></a>

An open that followed a symlink records the chain of the *resolved*
path, so the fd's ancestry reflects the target's real position in the
tree, not the link's. <a id="cite-watch.dispatch.symlink-open-records-the-resolved-chain"></a>

Dispatch uses that captured chain and never re-resolves it. If an
ancestor in the chain is later hidden, deleted, orphaned, or replaced
at the same path by a different key, watches on the original ancestor
GUID still receive subtree events from descendants mutated through fds
opened through that chain. <a id="cite-watch.dispatch.stale-ancestor-still-receives-subtree-events"></a>

Watches on a new key that later appears at the same path receive
nothing from the old one. <a id="cite-watch.dispatch.new-key-at-the-same-path-receives-nothing"></a>

<a id="trm-5-6-3-3"></a>

## The algorithm

Two structures back dispatch. The **watch map** is a hash map from GUID
to the watchers armed on it. The **subtree watch set** is a refcounted
hash set of the GUIDs that have at least one subtree watch, maintained
as watches are armed, re-armed, disarmed and closed.

For a mutation on key *B*, with *B*'s ancestor chain in hand:

1. Look up *B*'s GUID in the watch map and queue the event, with
   `path_depth` 0, to every watcher whose filter admits it. <a id="cite-watch.dispatch.direct-watchers-receive-depth-zero"></a>
2. Walk the ancestor chain outward from *B*'s parent. At each ancestor,
   skip it unless it is in the subtree watch set — that test is what
   makes the walk cheap. For an ancestor that is, queue the event to
   each of its watchers that armed with the subtree flag and whose
   filter admits it, with the path from that ancestor down to *B*. <a id="cite-watch.dispatch.subtree-watchers-receive-the-relative-path"></a>

The cost is O(depth) hash lookups, with no RSI round trips, no trie and
no string comparison. <a id="cite-watch.dispatch.costs-o-depth-hash-lookups-and-no-source-io"></a>
The path components handed to a subtree watcher are sliced out of the
resolved path already stored on the mutating fd.

Dispatch runs under a single global registry lock, so it is serialised
across the whole system rather than per hive or per source.

<a id="trm-5-6-3-4"></a>

## Depth

`MaxSubtreeWatchDepth` bounds how far below a watched key a subtree
watch is told about. The default is 0, meaning unlimited. <a id="cite-watch.dispatch.depth-zero-means-unlimited"></a>

A non-zero value suppresses events whose path is longer than it,
limiting both noise and dispatch cost for a watch armed high in a
tree. <a id="cite-watch.dispatch.depth-limit-suppresses-deeper-events"></a>

The limit applies to watches held by userspace. LCS's own internal
watches are collected before the depth test and are not subject to it
([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

<a id="trm-5-6-3-5"></a>

## Transaction batches

Nothing inside an uncommitted transaction dispatches. <a id="cite-watch.dispatch.uncommitted-transaction-dispatches-nothing"></a>

At commit, and only when the source reports success, the transaction's
mutation log is walked in operation order and the whole set of events
is queued as one batch, under a single hold of the registry lock, so no
other operation interleaves with it. <a id="cite-watch.dispatch.commit-batch-queued-in-operation-order-without-interleaving"></a>

An aborted or failed transaction dispatches nothing and its log is
released. A transaction that timed out after its commit was dispatched
keeps its log, and a late `RSI_OK` still emits the batch ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

A large transaction — a role installation writing thousands of values —
could otherwise fill a watcher's queue atomically. So the batch is
counted per watcher first: any watcher whose share exceeds
`MaxTransactionWatchEventBurst`, default 4096, receives exactly one
`OVERFLOW` and none of its individual events. <a id="cite-watch.dispatch.burst-cap-replaces-a-watchers-batch-with-one-overflow"></a>

That `OVERFLOW` is queued ahead of the batch, so it arrives before
whatever else that watcher is still owed. <a id="cite-watch.dispatch.burst-overflow-queued-ahead-of-the-batch"></a>

<a id="trm-5-6-3-6"></a>

## Recovery dispatch

Some changes alter effective state for keys whose fds nobody holds and
whose descendants the kernel is retaining no context for. Deleting a
layer, changing its precedence, enabling or disabling it, and restoring
a subtree from a stream are all of this kind. <a id="cite-watch.dispatch.recovery-triggering-operations"></a>
Computing an exact diff would mean walking arbitrary parts of the tree
through the source.

LCS does not attempt it. It increments the generation number of every
hive the affected source backs and then queues a no-name `OVERFLOW` to
every armed watch on that source, which is the notification for those
changes. <a id="cite-watch.dispatch.recovery-bumps-generation-and-queues-overflow"></a>
The watcher re-reads, and can compare the generation number it last saw
against the current one ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) to tell whether an *ordinary* write
happened in between; after a recovery it cannot, because the bump is
deliberately conservative. The kernel does not know which hives a layer
operation touched — the source's delete-layer answer names only the
keys it orphaned, and a layer holding hiding or masked entries changes
effective state without orphaning anything — so it bumps every hive
rather than risk a watcher skipping a re-read its hive needed. The
consequence is always a spurious re-read, never a missed change.
<a id="cite-watch.dispatch.recovery-generation-bump-is-source-wide"></a>

Two properties of this delivery are worth stating. It is object-
semantic like every other dispatch — it walks the watch map, resolves
no paths — and it bypasses the filter, because `OVERFLOW` always does.
It does not disarm anything. <a id="cite-watch.dispatch.recovery-does-not-disarm"></a>

The scope is the **source**, not the hive. A source backing several
hives delivers `OVERFLOW` to watches on all of them, including hives
the operation did not touch, and bumps all of their generation
counters. <a id="cite-watch.dispatch.recovery-scope-is-the-source-not-the-hive"></a>
The generation counters are maintained per hive for ordinary writes;
recovery treats the source as the unit.

For a restore, recovery is published only after the source commit
succeeds. A restore that fails or aborts before commit emits nothing. <a id="cite-watch.dispatch.restore-recovery-published-only-after-commit"></a>

<a id="trm-5-6-3-7"></a>

## Source restart

When a source disconnects, watches stay armed and nothing is delivered;
operations needing the source return `EIO`. <a id="cite-watch.dispatch.disconnect-keeps-watches-armed-and-silent"></a>

`OVERFLOW` arrives on **re-registration**, not on disconnect, which is
the only ordering that works: a watcher told to re-read needs the
source to be there when it does. <a id="cite-watch.dispatch.overflow-arrives-on-re-registration"></a>

Existing fds resume without re-opening, and no watcher has to
re-arm. <a id="cite-watch.dispatch.fds-resume-without-re-arming"></a>

---

# Queues and Overflow

_Peios Kernel / Internals / LCS / Watches_

> Each armed fd has its own bounded queue and delivery is best-effort — what a full queue does, and what a watcher does about it.

<a id="trm-5-6-4"></a>

Each armed fd has its own event queue, bounded by
`NotificationQueueSize` — default 256 events, configurable between 16
and 65536 ([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)). <a id="cite-watch.overflow.each-fd-has-its-own-bounded-queue"></a>

Delivery is best-effort. A watcher that reads promptly sees every
change; one that falls behind is told that it has, rather than being
given a partial history it cannot distinguish from a complete one. <a id="cite-watch.overflow.delivery-is-best-effort"></a>

<a id="trm-5-6-4-1"></a>

## What happens when the queue is full

When an event arrives for a full queue and no `OVERFLOW` is present:

1. The oldest queued event is dropped. <a id="cite-watch.overflow.full-queue-drops-the-oldest-event"></a>
2. An `OVERFLOW` record is queued in its place. <a id="cite-watch.overflow.full-queue-queues-an-overflow"></a>
3. The event that triggered this is **discarded**, not queued. <a id="cite-watch.overflow.triggering-event-is-discarded"></a>

Once an `OVERFLOW` is in the queue, subsequent events queue normally:
the oldest non-`OVERFLOW` event is dropped to make room and the new
event is added, so the single `OVERFLOW` is preserved and the queue
continues to carry the most recent history behind it. <a id="cite-watch.overflow.later-events-drop-the-oldest-and-preserve-the-overflow"></a>

A queue therefore holds at most one `OVERFLOW` at a time, and that is
an enforced invariant rather than a convention — an attempt to queue a
second is rejected as a bug. <a id="cite-watch.overflow.at-most-one-overflow-per-queue"></a>

<a id="trm-5-6-4-2"></a>

## What a watcher does about it

`OVERFLOW` means the record it has is incomplete. There is no way to
learn what was dropped, and no attempt is made to describe it. <a id="cite-watch.overflow.dropped-events-are-not-described"></a>

The watcher re-reads the watched key, and its subtree if the watch is a
subtree watch, and continues from the state it finds. Events after the
`OVERFLOW` are complete again. <a id="cite-watch.overflow.events-after-an-overflow-are-complete"></a>

`REG_IOC_QUERY_KEY_INFO` reports a per-hive generation number
([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) that makes this cheaper than it sounds: a watcher that
recorded the generation at its last full read can compare it with the
current one and skip the re-read entirely if nothing committed in
between.

<a id="trm-5-6-4-3"></a>

## Memory

There is no registry-specific global cap on watch memory, and none is
needed. A watch costs at most `NotificationQueueSize` queued events, a
watch requires an fd, and a process holds at most `RLIMIT_NOFILE` fds.
The product of the two is the bound, and it is enforced by machinery
that already exists. <a id="cite-watch.overflow.no-global-cap-beyond-queue-size-times-fd-limit"></a>

The same reasoning covers open key state: per-fd overhead — GUID,
granted mask, ancestor chain, watch state — multiplied by the fd limit.

LCS's own internal watches are outside this. They are delivered
synchronously through a kernel callback rather than queued, so the
queue limit does not apply to them ([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

---

# Transactions

_Peios Kernel / Internals / LCS / Transactions_

> Find the Peios kernel articles about transactions.

Use these articles to understand transactions in the Peios kernel.

- [Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md>)
- [Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md>)
- [Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md>)

---

# Scope and Lifetime

_Peios Kernel / Internals / LCS / Transactions_

> Grouping registry operations so they commit together or not at all — binding, states, timeout, and sources that do not support them.

<a id="trm-5-7-1"></a>

A transaction groups registry operations so that they commit together
or not at all. <a id="cite-txn.lifetime.commit-together-or-not-at-all"></a>
Installing a role writes service definitions, defaults and registry
entries; a transaction is what makes that one event rather than a
sequence of partially-applied ones.

`reg_begin_transaction` takes no arguments and returns a transaction
fd. It contacts no source: it allocates an id, creates an anonymous
inode, starts the lifetime timer, and returns. <a id="cite-txn.lifetime.begin-contacts-no-source"></a>

A transaction begins in the state `REG_TXN_ACTIVE_UNBOUND`. <a id="cite-txn.lifetime.begins-active-unbound"></a>

<a id="trm-5-7-1-1"></a>

## Binding

A write transaction binds to a source on its first **mutating** operation. <a id="cite-txn.lifetime.binds-on-first-mutating-operation"></a>

There are seven: writing a value, deleting a value entry, setting or
removing a blanket tombstone, creating a key, deleting a key's path
entry, hiding a key, and changing a Security Descriptor. <a id="cite-txn.lifetime.the-seven-binding-operations"></a>

Reads never bind a write transaction. <a id="cite-txn.lifetime.reads-never-bind"></a>

A read passed an unbound write transaction fd is sent to the source with a
transaction id of zero and behaves as an ordinary non-transactional
read. <a id="cite-txn.lifetime.unbound-read-is-non-transactional"></a>

`reg_begin_read_transaction` creates a read-only transaction. Its first read
binds the source/hive and fixes the persistent and volatile data snapshot and
layer view. It uses the ordinary lifetime timer and read-only source quota.
The kernel rejects mutations with `EROFS`. Snapshot capture overlapping a
publication returns `EAGAIN`; the caller retries its whole read using a fresh
transaction. Writers continue while an established read snapshot exists.

Once bound, every operation on that fd must target the same hive.
One that does not fails with `EXDEV`, and it fails in the kernel,
before anything reaches a source — a source never sees a cross-hive
operation inside a transaction. <a id="cite-txn.lifetime.cross-hive-operation-is-exdev-in-the-kernel"></a>
Cross-source atomicity would require two-phase commit and is not
supported.

Binding identity is the pair of source and hive root GUID carried on
the transaction object, which identifies the hive exactly. <a id="cite-txn.lifetime.binding-identity-is-source-and-hive-root"></a>

<a id="trm-5-7-1-2"></a>

## Sources that do not support transactions

Because `reg_begin_transaction` chooses no source, it cannot fail for
lack of transaction support. The failure surfaces on the operation that
would have bound: LCS sends `RSI_BEGIN_TRANSACTION`, the source answers
`RSI_TXN_NOT_SUPPORTED`, and the operation returns `ENOTSUP`. <a id="cite-txn.lifetime.unsupported-source-binds-with-enotsup"></a>

The transaction stays `ACTIVE_UNBOUND`, its source binding untouched,
and the caller can use the fd against a different hive. <a id="cite-txn.lifetime.failed-bind-leaves-the-transaction-unbound"></a>

There is no advance check of whether a source supports transactions.
The answer comes from the source, on the attempt.

If the source is Down before the first bind, the binding operation
fails `EIO` under the ordinary rules and the transaction likewise
remains unbound. <a id="cite-txn.lifetime.source-down-before-bind-is-eio"></a>
If a source goes Down after binding, the transaction becomes
`REG_TXN_SOURCE_DOWN` ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

<a id="trm-5-7-1-3"></a>

## States <a id="cite-txn.lifetime.the-six-transaction-states"></a>

| State | Value | Meaning |
|---|---|---|
| `REG_TXN_ACTIVE_UNBOUND` | 0 | Active, no source chosen. |
| `REG_TXN_ACTIVE_BOUND` | 1 | Active, bound to a source. |
| `REG_TXN_COMMITTED` | 2 | Commit completed. |
| `REG_TXN_ABORTED` | 3 | Explicitly or implicitly aborted. |
| `REG_TXN_TIMED_OUT` | 4 | The lifetime timer fired. |
| `REG_TXN_SOURCE_DOWN` | 5 | The bound source went Down. |

`REG_IOC_TXN_STATUS` reports the state and a `terminal_errno`: 0 for
`COMMITTED`, `EINVAL` for `ABORTED`, `ETIMEDOUT` for `TIMED_OUT`, `EIO`
for `SOURCE_DOWN`, and 0 while active.

For `COMMITTED`, `terminal_errno` is not the errno that a further
operation would return. A committed transaction reports 0, but using
its fd again returns `EINVAL`.

<a id="trm-5-7-1-4"></a>

## Reaching a terminal state

- **Commit.** `REG_IOC_COMMIT` on the transaction fd. The source
  applies everything atomically, watch events fire, and the object
  becomes `COMMITTED`. Later use of the fd returns `EINVAL`. The fd
  should be closed. <a id="cite-txn.lifetime.use-after-commit-is-einval"></a>
- **Explicit abort.** `close()` without committing. The source is told
  to discard, and the object becomes `ABORTED` during release. No
  events. <a id="cite-txn.lifetime.close-without-commit-aborts"></a>
- **Implicit abort.** Process death closes the fd, which aborts it.
  There are no orphaned transactions. <a id="cite-txn.lifetime.process-death-aborts-no-orphans"></a>
- **Timeout.** The lifetime timer fires. See below.

The object stays addressable after reaching a terminal state, until the
fd is closed. <a id="cite-txn.lifetime.terminal-object-stays-addressable-until-close"></a>
That is what makes `REG_IOC_TXN_STATUS` useful.

Transaction fds are pollable. Any terminal transition wakes poll
waiters with `POLLERR | POLLHUP`. <a id="cite-txn.lifetime.terminal-transition-wakes-poll-with-pollerr-pollhup"></a>
A caller that needs a race-free reason for the wakeup queries the
status.

<a id="trm-5-7-1-5"></a>

## Timeout

The lifetime timer starts when the fd is created — not at the first
operation — and runs for `TransactionTimeoutMs`, default 30 seconds. <a id="cite-txn.lifetime.timer-starts-at-fd-creation"></a>

When it fires, the object becomes `TIMED_OUT`, poll waiters are woken,
and further use of the fd returns `ETIMEDOUT`. <a id="cite-txn.lifetime.timeout-makes-further-use-etimedout"></a>

The timer updates transaction state from softirq context. Task and
workqueue callers disable bottom halves while holding the shared state
spinlock, so the timer cannot interrupt a holder on the same CPU and
wait for that holder to release it. Synchronous timer cancellation runs
outside the state lock. <a id="cite-txn.lifetime.timer-state-lock-softirq-safe"></a>

If the transaction was bound and no commit is already in flight,
`RSI_ABORT_TRANSACTION` is sent to the source. <a id="cite-txn.lifetime.timeout-aborts-a-bound-transaction-at-the-source"></a>

The fd is not removed from the caller's table; `close()` still releases
it normally. <a id="cite-txn.lifetime.timeout-leaves-the-fd-in-the-table"></a>

The timeout is not a convenience. Sources serialise writers — loregd
does so through SQLite's WAL — so a stalled transaction blocks every
other write to that source. The timer is what bounds the starvation
window, and `MaxBoundTransactionsPerSource` (default 16) is what stops
colluding processes from extending it indefinitely by binding fresh
transactions at each timeout boundary. An operation that would bind
past that cap returns `EBUSY`. <a id="cite-txn.lifetime.bind-past-the-cap-returns-ebusy"></a>

The cap is tested before the source is contacted, but after the
transaction's mutation-log entry has been allocated; that entry is
freed on the way out. <a id="cite-txn.lifetime.cap-tested-after-log-entry-allocation"></a>

<a id="trm-5-7-1-6"></a>

## Constraints

- **No nesting.** Transactions are flat: no savepoints, no
  sub-transactions. The transaction fd accepts only `REG_IOC_COMMIT`
  and `REG_IOC_TXN_STATUS`; every other ioctl is `ENOTTY`. <a id="cite-txn.lifetime.transactions-are-flat"></a>
- **One transaction per fd.** A process may hold many transaction fds
  at once, but each is exactly one transaction. <a id="cite-txn.lifetime.one-transaction-per-fd"></a>
- **Reads are permitted.** A transaction is not write-only, which is
  what makes verify-then-write possible. <a id="cite-txn.lifetime.reads-are-permitted"></a>

---

# Isolation and the Mutation Log

_Peios Kernel / Internals / LCS / Transactions_

> Read-your-own-writes inside a transaction, implemented by the source rather than LCS — the mutation log, sequence numbers and conflicts.

<a id="trm-5-7-2"></a>

<a id="trm-5-7-2-1"></a>

## Read-your-own-writes

Within a bound write transaction, reads see the transaction's own uncommitted
writes. <a id="cite-txn.isolation.read-your-own-writes"></a>
LCS does not implement this; the source does. A read tagged with the
transaction id is executed by the source inside its open transaction,
which naturally includes the pending writes.

No uncommitted registry data is cached in the kernel for the purpose of
resolving reads. <a id="cite-txn.isolation.no-uncommitted-data-cached-in-the-kernel"></a>

Externally, only committed state is visible. A transaction's writes are
invisible to other threads and processes until commit. <a id="cite-txn.isolation.uncommitted-writes-are-invisible-externally"></a>

Read-only transactions preserve their first-read data and layer selection.
The kernel verifies that capture did not overlap a pending mutation or its
completion effects; this includes requests whose original caller timed out.
An overlap fails with `EAGAIN`, rather than mixing a source commit with an
earlier kernel layer table. The fence covers capture only and never holds a
writer lock for the lifetime of a read transaction.

Security descriptors read through `REG_IOC_GET_SECURITY_TRANSACTED` are
historical data, subject to the key fd's granted rights. New transacted opens
check the current descriptor of the historical target GUID and the actual
caller. The snapshot does not preserve an earlier permission to open a key.

<a id="trm-5-7-2-2"></a>

## The mutation log

LCS does keep something: a per-transaction **mutation log**, holding
what the kernel needs to know after a successful commit and cannot ask
the source for afterwards. Each accepted mutating operation records the
affected key, value or layer name, its assigned sequence number, the
ancestor chain for watch dispatch, and enough context to compute
effective-state changes. <a id="cite-txn.isolation.log-records-per-operation-context"></a>

The log is not the source of truth for reads and it is not a rollback
journal — the source's own transaction state is authoritative for
uncommitted data. <a id="cite-txn.isolation.log-is-not-a-rollback-journal"></a>
The log exists so that when the source says "yes", LCS can produce the
hive generation updates and the watch events that correspond to what
was just committed.

It is bounded at 4096 entries. That bound is a compile-time constant
rather than one of the self-configuration parameters. <a id="cite-txn.isolation.log-bounded-at-4096-entries"></a>

Exceeding it fails the operation with `ENOMEM`. <a id="cite-txn.isolation.log-full-fails-the-operation-with-enomem"></a>

An operation whose log entry cannot be allocated fails **before it is
sent to the source**. <a id="cite-txn.isolation.log-allocation-failure-precedes-the-source-send"></a>
That ordering is deliberate: an operation the source applied but the
kernel cannot account for is exactly the state the log exists to
prevent.

The log is released, with no events emitted, on explicit abort, on a
lifetime timeout that fires before a commit is dispatched, on
source-down cancellation, on a late commit error, and on source
teardown while a post-dispatch commit response is still retained. <a id="cite-txn.isolation.log-release-conditions"></a>

It is **retained** across a post-dispatch commit timeout, because the
source may still answer. <a id="cite-txn.isolation.log-retained-across-a-post-dispatch-timeout"></a>

<a id="trm-5-7-2-3"></a>

## Sequence numbers

A transactional mutation is assigned its sequence number when it is
accepted into the transaction, not at commit. <a id="cite-txn.isolation.sequence-assigned-on-accept-not-at-commit"></a>
This preserves the order in which the caller performed the operations,
which is what layer tiebreaking and watch ordering need.

If the transaction aborts, those numbers are simply never used. <a id="cite-txn.isolation.aborted-sequence-numbers-are-never-used"></a>
Gaps in the sequence space are normal and mean nothing ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

<a id="trm-5-7-2-4"></a>

## Layer precedence coherency

Layer metadata lives in the registry, so a transaction can write to it —
and that raises the question of whether a precedence change takes
effect inside the transaction that made it. It does not. <a id="cite-txn.isolation.precedence-change-does-not-take-effect-in-its-own-transaction"></a>

Resolution always uses the published layer cache, which is refreshed
only at commit. <a id="cite-txn.isolation.resolution-uses-the-published-layer-cache"></a>

Reading the `Precedence` value back inside the transaction shows the
new number, because that is an ordinary read-your-own-writes read from
the source. <a id="cite-txn.isolation.precedence-value-reads-back-as-the-new-number"></a>

Resolving any *other* value in the same transaction still uses the old
precedence order. <a id="cite-txn.isolation.other-values-resolve-under-the-old-precedence"></a>
The two are consistent with each other and with the rule that a
transaction's effects become real at commit.

The refresh is deferred to commit, dropped on abort, and performed
before `REG_IOC_COMMIT` returns on success. <a id="cite-txn.isolation.layer-cache-refresh-completes-before-commit-returns"></a>

<a id="trm-5-7-2-5"></a>

## Conflicts

Transactions are atomic. They are not conflict-detecting. <a id="cite-txn.isolation.no-conflict-detection"></a>

If two transactions write the same value, both commits succeed and the
one that committed second wins, because its write carries the higher
sequence number. <a id="cite-txn.isolation.second-committer-wins"></a>
There is no read set, no version check, and no per-key validation
anywhere in the commit path.

Serialising concurrent writers is the source's responsibility, not
LCS's. The RSI requires only that commits are atomic, that writes
within a transaction are ordered, and that concurrent commits are
serialised. <a id="cite-txn.isolation.rsi-requires-atomic-ordered-serialised-commits"></a>

Conditional writes are the mechanism for the cases where losing an
update matters. `REG_IOC_SET_VALUE` takes an `expected_sequence`, the
source verifies it atomically against the layer's own entry, and a
mismatch returns `EAGAIN` ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)).

That is a per-operation check, not a transaction-level one, and it is
deliberately scoped to a single layer: a higher-precedence layer
overriding a value is not a conflict, it is the layer system
working. <a id="cite-txn.isolation.conditional-write-is-per-operation-and-single-layer"></a>

---

# Commit and Failure

_Peios Kernel / Internals / LCS / Transactions_

> What a commit triggers in order, the failures that leave a transaction open, and what happens when the watch events cannot be delivered.

<a id="trm-5-7-3"></a>

`REG_IOC_COMMIT` marks the transaction as having a commit in flight and
sends `RSI_COMMIT_TRANSACTION`. <a id="cite-txn.commit.marks-in-flight-and-sends-rsi-commit"></a>
What happens next depends on the answer.

<a id="trm-5-7-3-1"></a>

## Success

The source's `RSI_OK` triggers, in order: the layer metadata cache
refresh for any layer names the transaction touched, the hive
generation increment, orphan tracking for keys that lost their last
path entry, and the watch event batch derived from the mutation log. <a id="cite-txn.commit.post-commit-step-order"></a>

The object then becomes `COMMITTED`, the log is released, poll waiters
are woken, and the ioctl returns 0. <a id="cite-txn.commit.success-finalises-and-returns-zero"></a>

The hive generation is incremented once per committed transaction per
affected hive, however many operations the transaction contained. <a id="cite-txn.commit.generation-incremented-once-per-transaction-per-hive"></a>

<a id="trm-5-7-3-2"></a>

## Failure that leaves the transaction open

A source that cannot take the write lock answers `RSI_TXN_BUSY`, which
becomes `EBUSY`; a synchronous commit failure becomes `EIO`. <a id="cite-txn.commit.busy-is-ebusy-and-commit-failure-is-eio"></a>

In both cases the transaction stays `ACTIVE_BOUND`: <a id="cite-txn.commit.failed-commit-stays-active-bound"></a>

- the mutation log is retained; <a id="cite-txn.commit.failed-commit-retains-the-log"></a>
- no watch events are emitted; <a id="cite-txn.commit.failed-commit-emits-no-events"></a>
- poll waiters are **not** woken as though the transaction had become
  terminal. <a id="cite-txn.commit.failed-commit-does-not-wake-poll-waiters"></a>

The in-flight marker is cleared, so the caller may simply retry
`REG_IOC_COMMIT`, or close the fd to abort. Nothing has been lost. <a id="cite-txn.commit.in-flight-marker-cleared-so-retry-is-allowed"></a>

<a id="trm-5-7-3-3"></a>

## Timeout after dispatch

If the request timeout expires after the commit was dispatched, the
caller receives `ETIMEDOUT` and the object becomes `TIMED_OUT`, but the
mutation log is kept and the request record stays in the source's
in-flight table. The source may still answer. <a id="cite-txn.commit.post-dispatch-timeout-keeps-log-and-request"></a>

`ETIMEDOUT` on a commit means *may or may not have committed*. A caller
that needs certainty checks state before retrying. <a id="cite-txn.commit.etimedout-is-indeterminate"></a>

A late `RSI_OK` applies the full set of kernel-side effects from the
retained log — the same generation updates and the same watch events an
on-time commit would have produced. Watchers may therefore observe the
effects of a transaction whose caller was told it timed out. <a id="cite-txn.commit.late-ok-applies-the-full-effects"></a>

A late error releases the log with no effects. <a id="cite-txn.commit.late-error-releases-the-log-with-no-effects"></a>

The transaction object does **not** move to `COMMITTED` when a late
success arrives. It stays `TIMED_OUT`, so a caller that queries
`REG_IOC_TXN_STATUS` afterwards is told `TIMED_OUT` with a
`terminal_errno` of `ETIMEDOUT`, even though the writes are durable and
the watch events have gone out. <a id="cite-txn.commit.late-success-leaves-the-state-timed-out"></a>
The state reflects what the caller was told, not what the source did.

<a id="trm-5-7-3-4"></a>

## When the watch events cannot be derived

Two of the post-commit steps query the source. Working out which keys
were orphaned by a key deletion needs a lookup that can only be made
after the commit, and expanding a blanket tombstone into per-value
events needs the value set.

If that derivation cannot complete exactly, LCS does not reinterpret a
successful commit as a failed one and does not emit a partial set of
events. It delivers `OVERFLOW` to the affected watchers instead,
releases the retained replay state, and reports the commit as
successful, which it was. <a id="cite-txn.commit.underivable-events-become-overflow"></a>

A late response arriving afterwards does not resurrect the individual
events once overflow recovery has been chosen. <a id="cite-txn.commit.overflow-recovery-is-not-undone-by-a-late-response"></a>

The carve-out is narrower than it might appear. It covers the orphan
lookup and the watch batch. <a id="cite-txn.commit.carve-out-covers-only-orphan-lookup-and-watch-batch"></a>

The other two post-commit steps — publishing the layer metadata cache
and recording the hive generation — are state updates rather than event
derivation, and a failure in either returns `EIO` and marks the source
Down. <a id="cite-txn.commit.cache-or-generation-failure-is-eio-and-marks-the-source-down"></a>

<a id="trm-5-7-3-5"></a>

## Abort

Aborting generates no events, ever, and releases the log. <a id="cite-txn.commit.abort-emits-no-events-and-releases-the-log"></a>

The source is told to roll back with `RSI_ABORT_TRANSACTION` if the
transaction was bound. <a id="cite-txn.commit.abort-sends-rsi-abort-when-bound"></a>

Process death is the same path: closing the fd aborts.

---

# Sources

_Peios Kernel / Internals / LCS / Sources_

> Find the Peios kernel articles about sources.

Use these articles to understand sources in the Peios kernel.

- [The Source Model](</kernel/internals/lcs/sources/the-source-model.md>)
- [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md>)
- [Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md>)
- [Validation](</kernel/internals/lcs/sources/validation.md>)
- [Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md>)

---

# The Source Model

_Peios Kernel / Internals / LCS / Sources_

> A source is a userspace process holding registry data and answering LCS over RSI — the trust boundary, and why loregd is not special.

<a id="trm-5-8-1"></a>

A source is a userspace process that holds registry data and answers
LCS's questions about it over the Registry Source Interface. LCS is
source-agnostic: it does not know or care how a source stores anything.

The division is the sixth semantic rule ([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>)). A source stores path
entries, key records, value entries and blanket tombstones, and returns
**all** of them on request. <a id="cite-source.model.returns-all-entries"></a>

It does not evaluate access, resolve layers, dispatch watches, interpret
paths beyond the parent and child names it is given, or see the identity
of any caller. LCS does all of that. <a id="cite-source.model.does-no-policy"></a>

A source may back several hives; a hive is backed by exactly one source
([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)).

<a id="trm-5-8-1-1"></a>

## The interface is specified elsewhere

The RSI — its channel, framing, operations, error vocabulary, and the
obligations binding on a conforming source — is a normative
specification, because the userspace side is a role a third party can
implement. It is a chapter of PSPK, and it is where the wire format
lives.

This section covers the kernel's side: how LCS admits a source, how it
dispatches requests and accounts for them, what it refuses to believe,
and what it does when a source dies or answers late.

<a id="trm-5-8-1-2"></a>

## The trust boundary

Sources are in the TCB. LCS trusts the data a source returns —
descriptors, values, symlink targets, key metadata — because it has no
independent copy of any of it. <a id="cite-source.model.lcs-trusts-source-data"></a>

A compromised source therefore has complete control over access
decisions for its hives. It can return a permissive descriptor for any
key and AccessCheck will grant access that should have been denied. LCS
validates that responses are structurally correct, but it cannot detect
data that is well-formed and wrong: a descriptor granting Everyone
`KEY_ALL_ACCESS` on a sensitive key is a perfectly valid descriptor.

Three consequences are worth naming specifically.

**Layer table poisoning.** A compromised source backing `Machine\` can
fabricate the `Precedence` and `Enabled` values under
`Machine\System\Registry\Layers\`, and so control which layer wins
every resolution contest system-wide. The `SeTcbPrivilege` check at
write time does nothing about a fabricated read.

**Layer authorization bypass.** The same source can return permissive
descriptors for layer metadata keys, granting any process write access
to any layer ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

**`SeRestorePrivilege` implies descriptor control.** Restore replaces a
subtree including every descriptor in it, so granting
`SeRestorePrivilege` effectively grants `WRITE_DAC` and `WRITE_OWNER`
over everything in reach of a restore. <a id="cite-source.model.restore-implies-descriptor-control"></a> Operators should
understand it that way.

The mitigations are operational rather than architectural: sources run
with tightly scoped privileges, protected by descriptors on their
service definitions, and managed by peinit with Process Integrity
Protection where available. LCS emits audit events for every source
data validation failure. A harder guarantee — checksumming descriptors
LCS computed during inheritance and verifying them on retrieval — is
possible but not implemented.

<a id="trm-5-8-1-3"></a>

## loregd is not special <a id="cite-source.model.loregd-is-not-special"></a>

loregd is the first source and the one that provides `Machine\` and
`Users\` at boot, which puts it on the critical path to a running
system. Nothing in LCS knows that. Its details are its own manual's
business; what LCS requires of it is exactly what it requires of any
source.

---

# Registration and Slots

_Peios Kernel / Internals / LCS / Sources_

> Reaching LCS through /dev/pkm_registry — what registration validates, how source slots work, and resuming one that went Down.

<a id="trm-5-8-2"></a>

A source reaches LCS through `/dev/pkm_registry`. The device's `open()`
handler checks the calling thread's effective token for an **enabled**
`SeTcbPrivilege` and returns `EPERM` without it, so an unprivileged
process cannot obtain an fd to the device at all. <a id="cite-source.register.open-requires-enabled-setcbprivilege"></a>

Having opened it, the source issues `REG_SRC_REGISTER`, naming the
hives it backs, the root GUID of each, the highest sequence number it
has persisted, and per-hive flags and scope GUID. On success it enters
the request loop: `read()` for requests, `write()` for responses.

<a id="trm-5-8-2-1"></a>

## What registration validates

- Every hive name is valid and is not the reserved `CurrentUser`
  ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)). <a id="cite-source.register.hive-name-valid-and-not-currentuser"></a>
- No route identity — the folded name paired with its scope — collides
  with one held by another **Active** source. <a id="cite-source.register.no-route-identity-collision"></a>
- Private hive collisions are scoped: the same name in different scopes
  is fine ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-source.register.private-hive-collisions-are-scoped"></a>
- A hive's root GUID is not nil. <a id="cite-source.register.root-guid-not-nil"></a>
- The root GUIDs within one request are distinct from each other. <a id="cite-source.register.root-guids-distinct-within-request"></a>
- A hive without `RSI_HIVE_PRIVATE` carries no scope GUID. <a id="cite-source.register.scope-guid-only-for-private-hive"></a>
- No unknown flag bits are set. <a id="cite-source.register.no-unknown-flag-bits"></a>
- The hive count is within `MaxHivesPerSource` (64), and the source
  count is within `MaxRegisteredSources` (32). Either limit is `ENOSPC`;
  a zero hive count is `EINVAL`. <a id="cite-source.register.hive-and-source-counts-are-enospc"></a>
- The reported maximum sequence can be advanced past without
  overflowing 64 bits, or registration fails `EOVERFLOW` and the source
  is never made Active ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)). <a id="cite-source.register.max-sequence-overflow-is-eoverflow"></a>

Root GUIDs are checked for uniqueness within one request, and against
every existing slot, Active or Down: a request whose root GUID is
already the root of a differently-named hive is refused `EEXIST`. A
same-named hive is decided by the identity rules above instead. The
already-registered state is also checked for consistency, and a table
that ever held two hives with one root would fail that check on every
later registration and path walk, which is why admission refuses it. <a id="cite-source.register.root-guids-compared-across-slots"></a>

<a id="trm-5-8-2-2"></a>

## Source slots

Successful registration creates a **source slot**: the kernel object
owning one connection and the hive set registered on it. <a id="cite-source.register.success-creates-a-slot"></a>

Each registered hive has a stable identity — its folded name, its
visibility, its scope GUID for a private hive, and its root GUID. <a id="cite-source.register.hive-identity-fields"></a>

**Down slots keep their identities reserved.** A crash or an fd close
marks the slot Down; it does not unregister anything and does not
retire any hive identity. <a id="cite-source.register.down-slot-keeps-its-identities"></a>

Slots are never freed, and collision checks see Down slots as well as
Active ones. <a id="cite-source.register.collision-checks-see-down-slots"></a>

Status is a property of the slot, not of an individual hive. A source's
hives go Down together. <a id="cite-source.register.status-is-per-slot"></a>

<a id="trm-5-8-2-3"></a>

## Resuming a Down slot

A new process may take over a Down slot if it holds `SeTcbPrivilege`
and registers **exactly the same hive set**: the same folded name,
visibility, scope GUID and root GUID for every hive, and the same
number of them. Partial resume is rejected. <a id="cite-source.register.resume-requires-exact-hive-set"></a>

The distinction between the failures matters. A request whose only
mismatch is stale identity data — a different root GUID for an
otherwise-matching hive — fails `ESTALE`. <a id="cite-source.register.stale-root-guid-is-estale"></a>

Other partial or malformed resume attempts fail `EINVAL`. <a id="cite-source.register.other-resume-mismatch-is-einval"></a>

`EEXIST` is reserved for a collision with an **Active** slot; it never
comes from a Down-slot collision. <a id="cite-source.register.eexist-only-from-active-collision"></a>

When both an Active collision and a stale Down slot apply, `EEXIST`
wins. <a id="cite-source.register.eexist-wins-over-estale"></a>

New hives cannot be added by mutating a Down slot during a resume — the
hive set has to match exactly, so a superset simply fails, and a new
hive needs a new slot. There is no implicit retirement of a Down slot;
retiring one would need an explicit administrative operation, and none
exists. <a id="cite-source.register.no-implicit-down-slot-retirement"></a>

A replacement source is authenticated by `SeTcbPrivilege`, not by
process identity. Nothing records a pid, and nothing could usefully:
process identity does not survive a crash and restart. <a id="cite-source.register.resume-authenticated-by-privilege-not-pid"></a>

<a id="trm-5-8-2-4"></a>

## Coming back

On a successful resume the slot becomes Active, its restart generation
advances, and LCS replays any layer deletions that were pending. <a id="cite-source.register.resume-activates-slot-and-replays"></a>

LCS then delivers `OVERFLOW` to every armed watch on that source
([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Existing key fds resume working without being reopened. Each carries
the restart generation it last saw; when it notices a change it
re-reads its key and continues. <a id="cite-source.register.key-fds-survive-a-resume"></a>

If the key's GUID no longer exists in the restarted source — the
database was restored from an older backup, say — that first operation
returns `ENOENT` and the fd is marked orphaned. <a id="cite-source.register.missing-guid-after-resume-orphans-fd"></a>

---

# Request Dispatch

_Peios Kernel / Internals / LCS / Sources_

> The RSI is multiplexed — request ids and matching, the single deadline covering three waits, and requests with no caller.

<a id="trm-5-8-3"></a>

The RSI is multiplexed. LCS sends concurrent requests tagged with
request ids and matches responses back to the kernel threads waiting on
them. A source may process requests in any order. <a id="cite-source.dispatch.responses-may-arrive-in-any-order"></a>

Request ids are allocated per connection, strictly increasing, and
**never reused** while the connection lives — including after a
timeout. <a id="cite-source.dispatch.request-ids-never-reused"></a>

The id is allocated inside the queue lock, after the in-flight limit has
been checked, so a caller queued waiting for a slot does not hold one
yet. <a id="cite-source.dispatch.id-allocated-after-the-limit-check"></a>

`MaxConcurrentRSIRequests`, default 256, bounds how many requests may
be dispatched and awaiting a response at once. <a id="cite-source.dispatch.max-concurrent-bounds-in-flight"></a> It is back-pressure for
a slow source.

<a id="trm-5-8-3-1"></a>

## One deadline covers three waits

`RequestTimeoutMs`, default 30 seconds, is measured from the point a
kernel operation first attempts to **reserve an in-flight slot**, after
local validation and access checks have already passed. One deadline is
computed there and reused for all three legs: waiting for a slot,
waiting for the source to read the queued request, and waiting for the
response. <a id="cite-source.dispatch.one-deadline-covers-three-waits"></a>

If the deadline expires before a slot is reserved, the caller gets
`ETIMEDOUT` and **no request is sent**. <a id="cite-source.dispatch.timeout-before-a-slot-sends-nothing"></a>

If it expires after dispatch, the caller gets `ETIMEDOUT` and
late-response handling applies ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)). <a id="cite-source.dispatch.timeout-after-dispatch-is-etimedout"></a>

The deadline is checked before admission is attempted, not only after a
contention round is lost. <a id="cite-source.dispatch.deadline-checked-before-admission"></a> It used to be the latter, which meant a request
finding a slot immediately free was dispatched with an already-expired
deadline and timed out in the wait leg instead — so the rule above held
only under contention, the one case where it is hardest to observe.

<a id="trm-5-8-3-2"></a>

## Timed-out requests keep their slot

For every dispatched request LCS keeps a **request record** until a
matching response is processed or the connection is torn down. <a id="cite-source.dispatch.record-kept-until-response-or-teardown"></a>

The record holds the request id, the operation code, the transaction
id, the key GUID it concerns, the runtime limits in force, and any
retained effect the kernel will need if the source later reports
success. <a id="cite-source.dispatch.record-contents"></a>

When the deadline expires after dispatch, LCS detaches the waiting
caller from the record and returns `ETIMEDOUT`. <a id="cite-source.dispatch.timeout-detaches-caller-from-record"></a>

A signal that interrupts the wait after dispatch detaches the caller
the same way, and the call fails with `EINTR` or is restarted. As after
a timeout, the source may still apply the request when it answers. A
response that completed before the caller could be detached wins: the
caller gets that response's result, with the signal still pending. <a id="cite-source.dispatch.completion-beats-a-signal"></a>

**The record stays in the in-flight table and keeps counting against
`MaxConcurrentRSIRequests`.** A timeout does not free a slot; only a
response or a teardown does. <a id="cite-source.dispatch.timeout-does-not-free-a-slot"></a>

A source that accumulates timed-out requests can therefore exhaust its
own in-flight slots until it answers or disconnects. That is the
intended shape: a source that stops answering stops being usable.

<a id="trm-5-8-3-3"></a>

## Requests with no caller

LCS dispatches some requests with nobody waiting: `RSI_DROP_KEY` after
the last fd to an orphaned key closes ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)), and
`RSI_ABORT_TRANSACTION` cleaning up source transaction state. <a id="cite-source.dispatch.callerless-requests-are-dispatched"></a>

Such a record occupies an in-flight slot and is retained like any
other, and its response is validated normally and released normally. <a id="cite-source.dispatch.callerless-record-occupies-a-slot"></a>

But it is **not** a late response, and the retained-effect recovery
rules do not apply to it merely because nobody is waiting. <a id="cite-source.dispatch.callerless-is-not-a-late-response"></a>

The kernel tracks the difference explicitly, with two booleans: whether
a waiter is attached now, and whether one was ever attached. A record
that never had a caller is not a timed-out request; only one whose
caller was detached after its deadline is. <a id="cite-source.dispatch.timed-out-means-caller-detached-after-deadline"></a>

This is load-bearing rather than pedantic. `RSI_DROP_KEY` is a mutating
operation, so without the distinction a perfectly ordinary answer to a
caller-less cleanup request would look like a mutation the kernel could
not account for, and would tear the source down.

<a id="trm-5-8-3-4"></a>

## The channel

`/dev/pkm_registry` is message-oriented. One `read()` returns exactly
one complete request; a buffer too small for the next one returns
`EMSGSIZE` **without consuming it**. <a id="cite-source.dispatch.read-returns-one-request-or-emsgsize"></a>

An empty queue blocks, or returns `EAGAIN` under `O_NONBLOCK`, or
returns 0 if the fd is closing. <a id="cite-source.dispatch.empty-queue-blocks-or-eagain"></a>

One `write()` submits exactly one complete response, and its length
must equal the response's own `total_len` exactly. <a id="cite-source.dispatch.write-submits-one-response-of-exact-length"></a>

`poll` reports the fd readable when a request is queued, writable while
the slot is Active, and `POLLHUP | POLLERR` when the slot is Down or
the fd is closing. <a id="cite-source.dispatch.poll-reports-queue-and-slot-state"></a>

An fd that is open but has not yet registered reports nothing at all. <a id="cite-source.dispatch.unregistered-fd-polls-nothing"></a>

Any rejected `write()` — short, over-long, an unknown or duplicate
request id, an operation code that does not match the request, a
response for another connection — returns `EINVAL` **and tears the
connection down**. <a id="cite-source.dispatch.rejected-write-is-einval-and-tears-down"></a> A source that cannot speak the protocol correctly is
not one whose other answers are worth believing.

<a id="trm-5-8-3-5"></a>

## Negotiated lifetime control

Sources may negotiate lifetime extension version 1 with `REG_SRC_NEGOTIATE`
before `REG_SRC_REGISTER`. Pass version 1, zero flags and zero session; the
kernel returns a nonzero session identifier unique to the open source file.
The RSI request and response frame layouts are unchanged. Sources that do not
negotiate retain the legacy protocol; current loregd requires this extension.
<a id="cite-source.dispatch.lifetime-extension-is-negotiated-before-registration"></a>

After reading a request and before responding, `REG_SRC_REQUEST_CONTEXT` takes
that session and request id and returns three absolute `CLOCK_MONOTONIC`
nanosecond timestamps: the request deadline, transaction lifetime deadline and
cleanup lease deadline. Zero lifetime means an operation-owned transaction
with no separate lifetime ceiling. Zero lease means there is no live transaction
owner. Request metadata remains queryable after caller detachment until the
response is accepted, so cleanup and late-response handling still work.
<a id="cite-source.dispatch.context-preserves-the-original-request-deadline"></a>

`REG_SRC_RENEW` takes the session and transaction id and returns the original
lifetime deadline plus a renewed cleanup deadline, at most five seconds from
now and never beyond the lifetime deadline. It succeeds only for an existing,
nonterminal transaction owned by a live file object or kernel operation on
this source session. Unknown, released, expired and foreign-session identities
return `ESTALE`. Once a lease expires, renewal cannot resurrect it. These
control ioctls consume no ordinary request slots, so request-queue saturation
does not starve renewal.
<a id="cite-source.dispatch.lease-renewal-requires-a-live-owner-and-session"></a>

Final owner release and abort prevent renewal before abort-message delivery.
Client lifetime expiration also prevents renewal. Sources must reject new
operations after expiry and serialize rollback with operations and commit;
an already-admitted commit must resolve its actual outcome. Lease cleanup
does not change the kernel's treatment of late commit responses ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).
<a id="cite-source.dispatch.lease-expiry-does-not-infer-a-commit-outcome"></a>

---

# Validation

_Peios Kernel / Internals / LCS / Sources_

> LCS validates every response before using it — malformed data against malformed protocol, and the asymmetric extensibility between them.

<a id="trm-5-8-4"></a>

LCS validates every response before using it, and the failures split
into two categories with very different consequences. <a id="cite-source.validate.every-response-is-validated"></a>

<a id="trm-5-8-4-1"></a>

## Malformed data

The RSI message is structurally valid but its content is not: a
descriptor that will not parse, a value type that does not exist, a
sequence number that cannot be real, a metadata block that does not
cover the GUIDs it should.

- The request returns `EIO` to its caller. <a id="cite-source.validate.malformed-data-returns-eio"></a>
- An `lcs.source.response.rejected` audit event is emitted, naming the
  source slot and — where known — the hive, the request id, the
  operation code, the key GUID, and which of the twelve validation
  classes applies ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-source.validate.malformed-data-emits-an-audit-event"></a>
- **The source stays alive.** Corruption may be localised, and one bad
  key is not a reason to take a hive offline. <a id="cite-source.validate.malformed-data-keeps-the-source-alive"></a>

What is checked, by category:

- **Security Descriptors**, from lookups and from layer metadata
  refreshes, must parse and must satisfy the ACE mask rules of [Access Rights](</kernel/internals/lcs/security/access-rights.md#trm-5-4-2>). <a id="cite-source.validate.descriptors-must-parse"></a>
  A malformed layer metadata descriptor additionally leaves the
  previous known-good one cached ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)).
- **Names** — layer names, key and child names, value names — must be
  valid under the ordinary rules for their kind. <a id="cite-source.validate.names-must-be-valid"></a>
- **Sequence numbers** must be below the next number LCS would
  allocate, and must not duplicate at the same precedence in a way that
  would decide a winner ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-source.validate.sequence-number-checks"></a>
- **Payload shape** — an otherwise-matched response whose
  operation-specific payload is the wrong shape, carries trailing
  bytes, or encodes a path target invalidly. <a id="cite-source.validate.payload-shape-checks"></a>
- **Metadata closure** — a lookup or enumeration whose per-GUID
  metadata block has missing, duplicate, unreferenced or nil entries. <a id="cite-source.validate.metadata-closure-checks"></a>
  A HIDDEN entry must carry an all-zero GUID and contributes no
  metadata. <a id="cite-source.validate.hidden-entry-carries-a-zero-guid"></a>
- **Value payloads** — invalid types, a tombstone carrying data, data
  above `MaxValueSize`. <a id="cite-source.validate.value-payload-checks"></a>
- **Orphan lists** — a nil or duplicated GUID in an `RSI_DELETE_LAYER`
  response. <a id="cite-source.validate.orphan-list-checks"></a>
- **Status codes** outside the defined vocabulary. <a id="cite-source.validate.unknown-status-code"></a>

<a id="trm-5-8-4-2"></a>

## Malformed protocol

The message itself is structurally invalid: bad framing, a truncated
response, an unknown request id, a duplicate response, an operation
code that does not match the request.

This is treated as a source crash. The connection is torn down, the
in-flight table is destroyed with every waiter completed `EIO`, the
slot is marked Down, its hives become unavailable, and bound
transactions enter `SOURCE_DOWN`. <a id="cite-source.validate.malformed-protocol-is-treated-as-a-crash"></a>

There is one case where malformed *data* also takes the source down:
when the caller had already timed out and the operation was a commit or
a replayable mutation. At that point LCS cannot establish whether a
mutation was applied, and it cannot account for one it cannot describe
([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

<a id="trm-5-8-4-3"></a>

## Asymmetric extensibility

Requests and responses do not extend the same way.

A **request** may carry trailing fields a source does not recognise; a
source skips them using `total_len`. <a id="cite-source.validate.requests-may-carry-trailing-fields"></a> That is how a new optional field
is added without an RSI version bump.

A **response** may not. LCS rejects any trailing bytes in a response
payload as malformed data. Forward compatibility on the response side
comes from new operations, not from extending existing payloads.

---

# Failure and Late Responses

_Peios Kernel / Internals / LCS / Sources_

> What happens when a source dies, and the late-response problem — a late error, a late successful read, and a late successful write.

<a id="trm-5-8-5"></a>

<a id="trm-5-8-5-1"></a>

## When a source dies

The connection closes unexpectedly, and:

1. The slot is marked Down and its hives become unavailable. <a id="cite-source.failure.slot-marked-down-hives-unavailable"></a>
2. Every pending request fails `EIO`, including ones queued but not yet
   delivered. <a id="cite-source.failure.pending-requests-fail-eio"></a>
3. **Open key fds stay valid.** An fd holds a GUID and a granted mask,
   and neither depends on the source. Operations needing a round trip
   return `EIO` until the source comes back. <a id="cite-source.failure.key-fds-stay-valid-round-trips-eio"></a>
4. Bound transactions enter `REG_TXN_SOURCE_DOWN`, their poll waiters
   are woken with `POLLERR | POLLHUP`, their mutation logs are
   released, and further use of those fds returns `EIO`. <a id="cite-source.failure.bound-transactions-enter-source-down"></a>
5. **Watches stay armed.** Watch state is kernel-side and does not
   depend on the source at all. <a id="cite-source.failure.watches-stay-armed"></a> Nothing is delivered during the window,
   and `OVERFLOW` arrives on re-registration rather than on disconnect
   ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Coming back is covered in [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>).

<a id="trm-5-8-5-2"></a>

## The late response problem

A caller that times out after its request was dispatched is gone, but
the request is not. The source may still apply the operation and answer
minutes later, and by then there is nobody to return a value to — while
the *kernel* still has work to do, because a mutation that succeeded
has to produce its generation increment and its watch events.

This is the most intricate part of LCS and the part with the most ways
to be subtly wrong.

A late response is validated exactly like an on-time one. <a id="cite-source.late.validated-like-an-on-time-response"></a> The rules
that follow apply **only** to a request whose caller was detached after
its deadline, never to one that never had a caller ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)).

<a id="trm-5-8-5-2-1"></a>

### A late error <a id="cite-source.late.error-has-no-effects"></a>

The record is released. No watch events, no generation change, nothing.

<a id="trm-5-8-5-2-2"></a>

### A late successful read <a id="cite-source.late.read-is-validated-then-discarded"></a>

Validated, then discarded. There is nobody to give it to and nothing
about it changes kernel state.

<a id="trm-5-8-5-2-3"></a>

### A late successful mutation

The kernel-side effects that correspond to the mutation are applied
from the retained record: the hive generation increment, watch
dispatch, the layer metadata cache refresh, and — for a commit — the
transaction's batch effects and orphan tracking. <a id="cite-source.late.mutation-applies-retained-effects"></a>
The watch dispatch takes the recovery form: a watcher receives an
`OVERFLOW` ahead of the event itself ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Which mutations can actually be replayed is narrower than the set of
operations that count as mutating. A replayable effect is recorded for
`RSI_SET_VALUE` and `RSI_WRITE_KEY`, and only for non-transactional
calls. <a id="cite-source.late.replayable-effects-only-for-set-value-and-write-key"></a>

For the other mutating operations — creating, hiding or deleting a path
entry, creating or dropping a key, deleting a value entry, setting a
blanket tombstone, deleting a layer — no effect was retained, so a late
success is a mutation the kernel cannot account for. LCS tears the
source down and returns `EIO` rather than silently ignoring it. <a id="cite-source.late.unreplayable-mutation-tears-source-down"></a>

That is the conservative direction, and deliberately so: the
alternative is a committed change with no watch event and a stale
generation number, which nothing downstream could detect.

<a id="trm-5-8-5-2-4"></a>

### A late successful transaction operation

A late `RSI_BEGIN_TRANSACTION` has created transaction state in the
source that nobody will ever use, so LCS enqueues an
`RSI_ABORT_TRANSACTION` for that id. <a id="cite-source.late.begin-transaction-enqueues-an-abort"></a>

A late `RSI_ABORT_TRANSACTION` or `RSI_FLUSH` releases the record with
no effects. <a id="cite-source.late.abort-or-flush-releases-the-record"></a>

A late `RSI_COMMIT_TRANSACTION` is a mutating response and applies the
retained commit effects — the same generation update and the same watch
events an on-time commit would have produced. <a id="cite-source.late.commit-applies-retained-commit-effects"></a> Watchers may therefore
observe the effects of a transaction whose caller was told it timed
out ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

<a id="trm-5-8-5-2-5"></a>

### A malformed late response

The ordinary malformed-data and malformed-protocol rules apply. But if
LCS cannot safely process the kernel-side effects of a
possibly-applied mutation because the request metadata it needs is
missing or invalid, it tears the source down and marks it Down rather
than ignoring the response. <a id="cite-source.late.unprocessable-effects-tear-source-down"></a>

A malformed late commit response takes the source down for the same
reason. <a id="cite-source.late.malformed-commit-tears-source-down"></a>

<a id="trm-5-8-5-3"></a>

## What a caller should conclude

`ETIMEDOUT` means *may or may not have completed*. A caller that needs
certainty reads state back before retrying. That applies to every
operation and, especially, to a transaction commit.

<a id="trm-5-8-5-4"></a>

## Fd lifecycle

Key fds and transaction fds are ordinary file descriptors, subject to
`RLIMIT_NOFILE`. There is no registry-specific fd accounting and no
registry-specific leak protection. <a id="cite-source.failure.no-registry-specific-fd-accounting"></a>

Process exit closes them through normal kernel cleanup: key fds
released and their watches removed, transactions aborted. <a id="cite-source.failure.process-exit-releases-fds"></a>

<a id="trm-5-8-5-5"></a>

## Memory

Registry kernel memory needs no global cap, because everything is
bounded by limits that already exist.

- **Watch queues:** `NotificationQueueSize` per queue, times
  `RLIMIT_NOFILE` queues per process.
- **Open key state:** per-fd overhead — GUID, granted mask, ancestor
  chain, watch state — times the same fd limit.
- **Layer table:** bounded by `MaxTotalLayers`, and per-value
  resolution cost by `MaxLayersPerValue`.
- **In-flight requests:** bounded per source by
  `MaxConcurrentRSIRequests`, and separately by the number of threads
  blocked on registry syscalls.

---

# Backup and restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Find the Peios kernel articles about backup and restore.

Use these articles to understand backup and restore in the Peios kernel.

- [The Stream](</kernel/internals/lcs/backup-and-restore/the-stream.md>)
- [Backup](</kernel/internals/lcs/backup-and-restore/backup.md>)
- [Restore](</kernel/internals/lcs/backup-and-restore/restore.md>)

---

# The Stream

_Peios Kernel / Internals / LCS / Backup and restore_

> The streamable binary representation of a key and everything beneath it with full layer fidelity — what the design buys, and how it is versioned.

<a id="trm-5-9-1"></a>

The registry backup format is a streamable binary representation of a
key and everything beneath it, with full layer fidelity. It is used by
`REG_IOC_BACKUP` and `REG_IOC_RESTORE`, by first-boot seeding, by
disaster recovery and by offline migration.

It is an **LCS-level** format. Sources never see it: LCS serialises
from source data on the way out and deserialises into RSI operations on
the way in. <a id="cite-backup.stream.lcs-level-sources-never-see-it"></a>

Because a third party writes and reads these streams directly — that is
what migration and recovery mean — the format is a normative
specification rather than a description. It is a chapter of PSPK, and
every byte layout, record type, ordering rule and validation
requirement lives there. This section covers what LCS does with it.

<a id="trm-5-9-1-1"></a>

## What the design buys

**Streamable.** It is written to an arbitrary fd — a file, a pipe, a
socket — with no seeking, in a single pass, and read back the same way. <a id="cite-backup.stream.written-and-read-without-seeking"></a>

**Full layer fidelity.** Every path entry, value, tombstone and blanket
tombstone is stored with its layer tag, so restoring reconstructs the
layered state rather than a flattened snapshot of it. <a id="cite-backup.stream.entries-carry-their-layer-tag"></a>

**Depth-first pre-order.** A parent always appears before its children,
so a restore can create keys top-down without buffering a tree. <a id="cite-backup.stream.depth-first-pre-order"></a>

**Descriptors inline.** Each key record carries its own descriptor with
no deduplication. <a id="cite-backup.stream.descriptors-inline-without-dedup"></a> Redundancy is external compression's problem; piping
through zstd handles it.

**Self-verifying.** A trailer carries a record count and a SHA-256 over
everything before it, so truncation and corruption are detected. <a id="cite-backup.stream.trailer-carries-count-and-sha256"></a>

<a id="trm-5-9-1-2"></a>

## Versioning

The header carries a format version and a **minimum reader version**. A
writer that used only older features sets a lower minimum, letting
older readers restore the stream. <a id="cite-backup.stream.header-carries-version-and-minimum-reader"></a>

A reader that finds a minimum above its own supported version rejects
the stream outright, before touching anything. <a id="cite-backup.stream.rejects-minimum-above-supported-version"></a>

Both are 21 in the current implementation, and the reader supports 21. <a id="cite-backup.stream.current-version-is-21"></a>

Unknown record types are skipped when the minimum reader version allows
it, and they still count toward the record count and the checksum. <a id="cite-backup.stream.unknown-records-skipped-but-counted"></a> A
writer that adds a record type a restore genuinely needs must raise the
minimum reader version, so that an older reader refuses the stream
rather than restoring an incomplete one.

Extension is by new **record types** only. Existing record payloads
must be consumed exactly; trailing bytes inside a known record are an
error. <a id="cite-backup.stream.trailing-bytes-in-a-record-are-an-error"></a> This is the opposite of the RSI's request convention ([Validation](</kernel/internals/lcs/sources/validation.md#trm-5-8-4>)),
and the difference is deliberate: a stream is replayed into mutations
long after it was written, and a field silently ignored there is data
silently lost.

---

# Backup

_Peios Kernel / Internals / LCS / Backup and restore_

> Writing a subtree to a stream under SeBackupPrivilege with no per-key access check — the snapshot, the audit, and what is written.

<a id="trm-5-9-2"></a>

`REG_IOC_BACKUP` exports the key on the fd and its entire subtree to
another fd, preserving parent/child relationships even when traversal
must grow its internal storage. <a id="cite-backup.exports-the-key-and-its-subtree"></a>

It requires `SeBackupPrivilege` and performs **no per-key AccessCheck**
whatsoever. <a id="cite-backup.requires-sebackupprivilege-and-checks-no-key"></a> The privilege is the whole authorisation, which is
why the operation is audited unconditionally ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)).

The output fd must be writable, or `EBADF`. <a id="cite-backup.output-fd-must-be-writable"></a>

<a id="trm-5-9-2-1"></a>

## The snapshot

Before reading anything, LCS opens a **read-only** source transaction —
`RSI_BEGIN_TRANSACTION` with mode `RSI_TXN_READ_ONLY` — so that the
whole export is a point-in-time snapshot. Concurrent mutations do not
appear part-way through the stream. <a id="cite-backup.opens-a-read-only-snapshot-transaction"></a>

That transaction is **released with `RSI_ABORT_TRANSACTION` and never
committed**. There is no commit call anywhere in the backup path; a
read-only transaction has nothing to commit. <a id="cite-backup.snapshot-released-with-abort-never-committed"></a>

A source that does not support read-only snapshots answers
`RSI_TXN_NOT_SUPPORTED` and the backup fails `ENOTSUP`. <a id="cite-backup.unsupported-snapshot-is-enotsup"></a>

A source already holding `MaxReadOnlyTransactionsPerSource` snapshots
(default 16) yields `EBUSY` — which bounds snapshot-holding without
treating backups as write-lock holders, since they are not. <a id="cite-backup.snapshot-limit-is-ebusy"></a>

Backing up an orphaned key is `ENOENT`: it is no longer a reachable
subtree root ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)). <a id="cite-backup.orphaned-key-is-enoent"></a>

<a id="trm-5-9-2-2"></a>

## Audit

`lcs.audit.backup.started` is emitted **before any subtree data is read**, and
if it cannot be emitted the backup returns `EIO` and does not start. <a id="cite-backup.start-event-precedes-any-data-or-eio"></a>

After privilege, output-fd and key validation, START precedes the request for
the read-only snapshot. A refused or failed snapshot therefore emits both
START and END, with END carrying the failure errno; no subtree is exported
and no unopened snapshot is released. A START emission failure prevents the
snapshot request itself. <a id="cite-backup.snapshot-refusal-is-audited"></a>

`lcs.audit.backup.ended` is emitted afterwards, carrying the result, and a
failure to emit it cannot change a result that has already happened. <a id="cite-backup.complete-event-cannot-change-the-result"></a>

<a id="trm-5-9-2-3"></a>

## What is written

The stream is a header, the layer manifest, then each key in
depth-first pre-order with its path entries, values and blanket
tombstones, then the trailer. The exact shapes are in the PSPK chapter.

Two things about the exporter are worth stating here, because they
constrain a reader more tightly than the format does.

The exporter writes **no GUID-bearing path entries for the backup
root**. The root's section contains only its hidden entries. <a id="cite-backup.root-section-has-no-guid-path-entries"></a>

A reader tolerates and skips them if some other writer produces them,
but this one does not emit them, because on restore the target key's
existing name is authoritative and they would be discarded anyway. <a id="cite-backup.reader-skips-root-path-entries"></a>

Hidden entries belong to the **parent's** section, not to a section of
their own — a hidden entry has no key to have a section for. <a id="cite-backup.hidden-entries-live-in-the-parent-section"></a>

A hidden entry masking a name where no key exists in any layer is still
valid; it expresses "this layer hides this name" whether or not
anything is there to hide. <a id="cite-backup.hidden-entry-without-a-key-is-valid"></a>

The layer manifest is written from the live layer table, and it is a
manifest: it records what the layers looked like at backup time so that
a restore can validate the stream against them. It is not a backup of
the layer definitions. <a id="cite-backup.manifest-is-written-from-the-live-layer-table"></a>

A layer definition is backed up only when
`Machine\System\Registry\Layers\<Name>\` is itself inside the subtree
being exported, in which case it is ordinary key and value data like
anything else. <a id="cite-backup.layer-definition-backed-up-only-if-inside-the-subtree"></a>

This includes definitions for unused layers in a whole-hive export.
Their metadata remains ordinary registry data; an unused definition
does not by itself require an entry in the layer manifest.

---

# Restore

_Peios Kernel / Internals / LCS / Backup and restore_

> Restore is a replace rather than a merge — one transaction, the surviving target key, the order of operations, and the precedence gate.

<a id="trm-5-9-3"></a>

`REG_IOC_RESTORE` **replaces** the key on the fd and its entire subtree
from a stream. It is not a merge: the target's contents and descendants
are torn down before the stream's contents are written. <a id="cite-restore.replaces-rather-than-merges"></a>

It requires `SeRestorePrivilege` and, like backup, performs no per-key
AccessCheck and is audited unconditionally. <a id="cite-restore.requires-serestoreprivilege-and-checks-no-key"></a>

The input fd must be readable, or `EBADF`. <a id="cite-restore.input-fd-must-be-readable"></a> Restoring onto an orphaned
key is `ENOENT`. <a id="cite-restore.orphaned-target-is-enoent"></a>

Because restore rewrites every descriptor in the subtree,
`SeRestorePrivilege` effectively confers `WRITE_DAC` and `WRITE_OWNER`
over everything within reach of one ([The Source Model](</kernel/internals/lcs/sources/the-source-model.md#trm-5-8-1>)).

<a id="trm-5-9-3-1"></a>

## One transaction

The entire restore — teardown and rebuild together — is wrapped in a
single read-write source transaction. <a id="cite-restore.wrapped-in-one-read-write-transaction"></a>

A source that answers `RSI_TXN_NOT_SUPPORTED` for `RSI_TXN_READ_WRITE`
cannot be a restore target: restore requires atomicity and there is no
partial-restore mode. <a id="cite-restore.requires-read-write-transaction-support"></a>

Every failure path aborts the transaction, so a failed restore rolls
back the teardown as well. <a id="cite-restore.failure-rolls-back-the-teardown"></a>

<a id="trm-5-9-3-2"></a>

## The target key survives

The stream's header names a root GUID, and that GUID is **remapped** to
the already-open target key everywhere it appears — in parent
references, in child references, in value key references — before
anything is validated or dispatched. <a id="cite-restore.root-guid-remapped-to-the-target"></a>

The target key **object** is not replaced. Its GUID, parent, name,
volatile flag and symlink flag remain what they were; they are never
taken from the stream. <a id="cite-restore.target-key-object-is-not-replaced"></a>

What the stream's root record supplies is the mutable part: the
Security Descriptor and the last write time, written to the target with
`RSI_WRITE_KEY` inside the transaction. <a id="cite-restore.root-record-supplies-descriptor-and-write-time"></a>

The root record's immutable flags must **match** the target's. A backup
of a volatile key restored onto a non-volatile one, or a symlink onto a
non-symlink, is `EINVAL`. <a id="cite-restore.immutable-flag-mismatch-is-einval"></a>

Descendants keep their backup GUIDs. Those are written into the target
verbatim. <a id="cite-restore.descendants-keep-their-backup-guids"></a>

<a id="trm-5-9-3-3"></a>

## Order of operations

1. Validate the whole stream, including the trailer's record count and
   checksum, and retain every replayable record. <a id="cite-restore.validates-the-whole-stream-first"></a>
2. Read the layer manifest and apply the precedence gate (below).
3. Verify the root record and its immutable flags against the live
   target.
4. Tear down the target's contents and descendants — path entries,
   values, blanket tombstones, and descendant key records — inside the
   transaction. <a id="cite-restore.tears-down-the-target-inside-the-transaction"></a>
5. Write the root's mutable fields, then replay its section's values
   and blanket tombstones. <a id="cite-restore.writes-root-mutable-fields-then-its-section"></a>
6. For each non-root key in stream order: create it, write its last
   write time, then replay its path entries, values and blanket
   tombstones. <a id="cite-restore.replays-non-root-keys-in-stream-order"></a>
7. Commit.

The stream is read from the fd exactly once, sequentially. Nothing
seeks, so a pipe is a valid input. <a id="cite-restore.stream-read-once-sequentially"></a>

Validating the whole stream first is stronger than the format requires:
a checksum failure aborts before any source mutation rather than after
some. The cost is memory rather than seeking — the replayable records
are retained in kernel memory across the teardown.

<a id="trm-5-9-3-4"></a>

## The precedence gate

Before any key record is written, LCS checks the layer manifest. If any
declared layer has a precedence above 0, **or** any existing cached
layer table entry with the same folded identity does, and the caller
does not hold `SeTcbPrivilege`, the restore aborts with `EPERM` before
a single byte reaches the source. <a id="cite-restore.precedence-gate-is-eperm-without-setcbprivilege"></a>

And if the stream contains ordinary key and value records for
`Machine\System\Registry\Layers\<Name>\`, writes that create or raise
persisted metadata above precedence 0 hit the ordinary inline
`SeTcbPrivilege` check as well ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

Both exist so that `SeRestorePrivilege` cannot be used to smuggle a
Group Policy-tier layer past the defence in depth that guards
precedence.

<a id="trm-5-9-3-5"></a>

## Layers in a restored stream

Manifest records create, update, delete, enable, disable and authorise
nothing. <a id="cite-restore.manifest-records-change-no-layers"></a>

If restored entries reference a layer that is not in the current table,
and the stream does not also restore that layer's metadata subtree as
ordinary registry data, those entries become latent unknown-layer
entries and are ignored during resolution until real metadata exists
([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-restore.unknown-layer-entries-become-latent"></a>

If the metadata subtree *is* included, it is restored through the
ordinary path, and those records — not the manifest — are what define
the layer. <a id="cite-restore.included-metadata-subtree-defines-the-layer"></a>

<a id="trm-5-9-3-6"></a>

## Sequence remapping

Backup sequence numbers preserve the backup's internal ordering, but a
restore is a new mutation and its entries must outrank everything
already present. So the numbers are remapped rather than written
through. <a id="cite-restore.sequences-are-remapped-not-written-through"></a>

Before dispatching the first layer-qualified record, LCS takes the
global sequence-allocation gate and records the current next sequence
as the offset. <a id="cite-restore.takes-the-sequence-gate-before-the-first-record"></a>

Every restored record is then written with `offset + backup_sequence`,
which preserves relative order while placing the whole set above
pre-restore state. <a id="cite-restore.remapped-sequence-is-offset-plus-backup"></a>

The gate is held until the restore reaches a terminal state. Other
sequence-allocating mutations wait; reads are not blocked. <a id="cite-restore.gate-blocks-mutations-not-reads"></a>

A restore with no layer-qualified records at all never takes it. <a id="cite-restore.no-layer-records-never-takes-the-gate"></a>

If a remapped value would overflow, the restore fails `EOVERFLOW` — and
it fails at validation, before teardown, rather than part-way through. <a id="cite-restore.sequence-remap-overflow-is-eoverflow"></a>
The valid remapped range stops just below `U64_MAX`, which is never
handed out ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)).

When the restore reaches any terminal state — commit, abort, failure or
cancellation — LCS advances the global counter past the highest number
it dispatched, and **does not roll that back**. <a id="cite-restore.counter-advanced-at-any-terminal-state"></a> Sequence numbers a
failed restore dispatched become unused gaps, exactly like those of any
other failed write.

<a id="trm-5-9-3-7"></a>

## GUID collisions

A GUID that appears twice in one stream, other than the root, is
`EINVAL`. <a id="cite-restore.duplicate-guid-in-the-stream-is-einval"></a> So is a non-root GUID equal to the target root's. <a id="cite-restore.non-root-guid-equal-to-the-root-is-einval"></a>

A non-root GUID that already exists **outside** the subtree being
replaced is `EEXIST` — but it is discovered by the source rejecting the
create during replay, not by a check beforehand. LCS has no index of
which GUIDs exist elsewhere, so the collision surfaces mid-restore, and
the transaction rolls back. <a id="cite-restore.external-guid-collision-is-eexist-mid-restore"></a>

The parent of every path entry, after remapping, must be either the
restore root or a key record already processed earlier in the stream. <a id="cite-restore.path-entry-parent-must-be-in-the-stream"></a>
That check *is* made up front, and it is what stops a crafted backup
injecting path entries into arbitrary parts of the existing namespace
outside the subtree being replaced.

<a id="trm-5-9-3-8"></a>

## Watches

A restore is an arbitrary subtree replacement and LCS retains no exact
before-and-after diff for it. On a successful commit it publishes the
affected hive's generation increment and dispatches a no-name
`OVERFLOW` to the armed watches on that source ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-restore.commit-publishes-generation-and-overflow"></a>

A restore that fails or aborts before commit emits nothing. <a id="cite-restore.failed-restore-emits-nothing"></a>

---

# Bootstrap

_Peios Kernel / Internals / LCS / Bootstrap_

> Find the Peios kernel articles about bootstrap.

Use these articles to understand bootstrap in the Peios kernel.

- [Dependencies and boot sequence](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md>)
- [Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md>)
- [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md>)

---

# Dependencies and boot sequence

_Peios Kernel / Internals / LCS / Bootstrap_

> The registry has to configure itself — the three circular dependencies, and the three rules that break them.

<a id="trm-5-10-1"></a>

The registry is the configuration store for the whole system, and it
has to configure itself. Three circular dependencies have to be broken
before it can serve anyone.

**peinit needs the registry to start services, but the registry source
is a service.** Service definitions live in the registry, and the
process that would serve them has not started.

**LCS needs operational parameters from the registry, but the registry
needs LCS.** Timeouts, caps and limits live under
`Machine\System\Registry\`, in a hive LCS itself routes.

**A fresh install has no data at all.** The source's database is empty;
there is nothing to read.

Three rules break all three.

<a id="trm-5-10-1-1"></a>

## Rule 1: compiled-in defaults

Every operational parameter has a compiled-in default, and LCS runs on
those defaults from the moment PKM initialises. <a id="cite-boot.defaults-active-from-init"></a>

There is no "waiting for configuration" state, no flag, and no wait
queue: the limits structure is statically initialised at load, the
source char device is registered without consulting configuration, and
the first attempt to read configuration happens on a workqueue after a
source has already registered. <a id="cite-boot.no-waiting-for-configuration-state"></a>

Before any source registers, the routing table is empty, so every
operation that names a hive returns `ENOENT`. <a id="cite-boot.empty-routing-table-enoent"></a>
That is the only sense in which LCS is not yet useful, and it is not a
distinct state — it is just an empty table.

<a id="trm-5-10-1-2"></a>

## Rule 2: the base layer exists unconditionally

The base layer is a static constant in the kernel: name `base`,
precedence 0, enabled. It is handed out whenever the dynamic layer
table is empty and is always written first into every layer snapshot.

A source that registers with an entirely empty database is fully
functional, because the one layer that writes need is not in the
database. Persisted metadata under
`Machine\System\Registry\Layers\base\` may exist and may decorate the
base layer, but it is not required and cannot contradict it ([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)).

<a id="trm-5-10-1-3"></a>

## Rule 3: hot-swap, not restart <a id="cite-boot.hot-swap-not-restart"></a>

When configuration becomes available, LCS reads it, validates it, and
swaps the values in place. It does not restart, re-initialise, or
block. The whole transition from compiled-in defaults to registry-backed
configuration is driven by the internal self-watch ([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

<a id="trm-5-10-1-4"></a>

## Source dependencies are the source's problem <a id="cite-boot.source-dependencies-not-lcs-concern"></a>

LCS neither knows nor cares what a source depends on. A source that
needs the root filesystem, a SYSTEM token, or a particular kernel
feature arranges that for itself. LCS's only requirement is that the
process can open `/dev/pkm_registry` and speak RSI.

<a id="trm-5-10-2"></a>

<a id="trm-5-10-2-1"></a>

## Normal boot <a id="cite-boot.normal-sequence"></a>

```
Kernel boots
  → PKM initialises; LCS runs on compiled-in defaults
  → /dev/pkm_registry registered
  → the base layer exists in memory

A source registers — loregd, started by peinit
  → opens /dev/pkm_registry (SeTcbPrivilege checked at open)
  → REG_SRC_REGISTER: hive names, root GUIDs, max persisted sequence
  → LCS initialises or advances next_sequence to max + 1

Bootstrap refresh is queued
  → resolve Machine\System\Registry     → read and hot-swap parameters
  → resolve Machine\System\Registry\Layers → populate the layer table
  → arm internal subtree watches
```

The bootstrap refresh runs on a workqueue after `REG_SRC_REGISTER`
returns, so registration never blocks on configuration and a source
that registers can start answering immediately. <a id="cite-boot.refresh-on-workqueue-after-register"></a>

The refresh is triggered by the arrival of a **global hive named
`Machine`**. <a id="cite-boot.refresh-triggered-by-machine-hive"></a> That name is matched case-insensitively in the
kernel and is one of the two hive names LCS knows about; the other is
`Users`, the target of `CurrentUser\` rewriting ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)). Neither is a
routing decision — routing is entirely dynamic — but the claim that the
kernel holds no hive names at all would not be true.

<a id="trm-5-10-2-2"></a>

## First boot <a id="cite-boot.first-boot-retains-defaults"></a>

An empty source has no `Machine\System\Registry` to read.

```
Source detects an empty database on first startup
  → generates root GUIDs for the hives it backs
  → creates root key records with their default SDs
  → persists them, then registers with LCS

LCS resolves Machine\System\Registry → does not exist
  → compiled-in defaults retained
  → subtree watch armed on the Machine\ hive root instead

peinit notices the registry is empty and restores the seed backup.
That is peinit's decision, not LCS's.

Seed restore populates Machine\ through REG_IOC_RESTORE
  → the fallback subtree watch fires
  → LCS re-runs the bootstrap refresh: resolves the specific GUIDs,
    re-arms targeted watches, validates and hot-swaps the seed values,
    and re-reads layer metadata
```

Hive root Security Descriptors are set by the source, not by LCS. LCS
holds no template for them and enforces whatever the source stores
([Inheritance and Hive Roots](</kernel/internals/lcs/security/inheritance-and-hive-roots.md#trm-5-4-3>)).

<a id="trm-5-10-2-3"></a>

## Watch arming in practice

The spec-level description above says the fallback watch is armed
*instead of* the targeted ones. What the kernel actually arms is a
**mixed** set: targeted watches on whichever of the two roots exist,
*plus* the `Machine\` root fallback. The fallback is a superset rather
than a substitute, and it stays armed until a refresh finds both roots
present.

A third internal watch is armed by the same sequence, on
`Machine\System\KMES`, which is not LCS configuration at all — it is
how KMES picks up its own parameters from the registry LCS serves.

<a id="trm-5-10-2-4"></a>

## The bootstrap contract

Four properties hold throughout and are relied on elsewhere:

1. **LCS is always operational with compiled-in defaults.** It accepts
   syscalls from the moment PKM initialises.
2. **The base layer requires no persisted state.**
3. **Hot-swap is the only configuration transition.** LCS never blocks,
   restarts, or re-initialises.
4. **Source dependencies are the source's concern.**

---

# Operational Parameters

_Peios Kernel / Internals / LCS / Bootstrap_

> The nineteen parameters LCS reads from the registry, how they are validated, and what hot-swapping one does to in-flight operations.

<a id="trm-5-10-3"></a>

LCS reads nineteen parameters from `Machine\System\Registry\`. <a id="cite-param.nineteen-under-registry-key"></a>

All are `REG_DWORD`. <a id="cite-param.all-are-reg-dword"></a> Each has a compiled-in default and a valid
range, and LCS runs on the defaults until the registry says otherwise.

| Value | Default | Range | Bounds |
|---|---:|---|---|
| `RequestTimeoutMs` | 30000 | 1000–600000 | A source round trip ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)). <a id="cite-param.request-timeout-ms"></a> |
| `TransactionTimeoutMs` | 30000 | 1000–600000 | The lifetime of an open transaction ([Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>)). <a id="cite-param.transaction-timeout-ms"></a> |
| `NotificationQueueSize` | 256 | 16–65536 | Queued events per watcher before overflow ([Queues and Overflow](</kernel/internals/lcs/watches/queues-and-overflow.md#trm-5-6-4>)). <a id="cite-param.notification-queue-size"></a> |
| `SymlinkDepthLimit` | 16 | 1–64 | Symlink resolution depth ([Symlinks](</kernel/internals/lcs/data-model/symlinks.md#trm-5-2-4>)). <a id="cite-param.symlink-depth-limit"></a> |
| `MaxValueSize` | 1048576 | 4096–67108864 | One value's data, in bytes. <a id="cite-param.max-value-size"></a> |
| `MaxKeyDepth` | 512 | 32–4096 | Key hierarchy nesting. <a id="cite-param.max-key-depth"></a> |
| `MaxPathComponentLength` | 255 | 64–1024 | One key, value or layer name, in UTF-8 bytes. <a id="cite-param.max-path-component-length"></a> |
| `MaxTotalPathLength` | 16383 | 1024–65535 | A whole path, in UTF-8 bytes. <a id="cite-param.max-total-path-length"></a> |
| `MaxLayersPerValue` | 128 | 1–1024 | Layers writing to one `(key, value name)` ([The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>)). <a id="cite-param.max-layers-per-value"></a> |
| `MaxBoundTransactionsPerSource` | 16 | 1–256 | Concurrently bound transactions per source ([Scope and Lifetime](</kernel/internals/lcs/transactions/scope-and-lifetime.md#trm-5-7-1>)). <a id="cite-param.max-bound-transactions-per-source"></a> |
| `MaxReadOnlyTransactionsPerSource` | 16 | 1–256 | Concurrent public read transactions and backup snapshots per source ([Backup](</kernel/internals/lcs/backup-and-restore/backup.md#trm-5-9-2>)). <a id="cite-param.max-read-only-transactions-per-source"></a> |
| `MaxTotalLayers` | 1024 | 16–65536 | Distinct layers in the in-memory table ([The Layer Model](</kernel/internals/lcs/layers/the-layer-model.md#trm-5-3-1>)). <a id="cite-param.max-total-layers"></a> |
| `MaxRegisteredSources` | 32 | 1–256 | Concurrently registered sources. <a id="cite-param.max-registered-sources"></a> |
| `MaxHivesPerSource` | 64 | 1–1024 | Hives one source may register. <a id="cite-param.max-hives-per-source"></a> |
| `MaxConcurrentRSIRequests` | 256 | 8–4096 | In-flight RSI requests per source ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)). <a id="cite-param.max-concurrent-rsi-requests"></a> |
| `MaxScopeGUIDsPerToken` | 8 | 1–256 | Private hive scope GUIDs on a token ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-param.max-scope-guids-per-token"></a> |
| `MaxPrivateLayersPerToken` | 16 | 1–256 | Private layer names on a token ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)). <a id="cite-param.max-private-layers-per-token"></a> |
| `MaxSubtreeWatchDepth` | 0 | 0–4096 | Subtree watch depth; 0 is unlimited ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-param.max-subtree-watch-depth"></a> |
| `MaxTransactionWatchEventBurst` | 4096 | 256–65536 | Watch events per watcher from one commit ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). <a id="cite-param.max-transaction-watch-event-burst"></a> |

Unknown values under this key are ignored. <a id="cite-param.unknown-values-ignored"></a> There are exactly
nineteen parameters and no undocumented ones; a separate set under
`Machine\System\KMES\` belongs to KMES.

Two limits are not among them. The **transaction mutation log** is
capped at 4096 entries by a compile-time constant ([Isolation and the Mutation Log](</kernel/internals/lcs/transactions/isolation-and-the-mutation-log.md#trm-5-7-2>)), and hard
ceilings on total path length and key depth exist independently of
configuration — set equal to the range maxima above, so they never
conflict. <a id="cite-param.hard-ceilings-match-range-maxima"></a>

<a id="trm-5-10-3-1"></a>

## Where a configured value does not fully bind

One of the nineteen does not do everything its range suggests.

`MaxPrivateLayersPerToken` is described as an attachment-time limit but
is not enforced at attachment. KACS applies its own hard cap of 256 and
LCS applies the configured value later, at use, with `E2BIG` ([Private Layers](</kernel/internals/lcs/layers/private-layers.md#trm-5-3-5>)).
`MaxScopeGUIDsPerToken` behaves the same way.

<a id="trm-5-10-3-2"></a>

## Validation

A value is checked against its range when it is read.

- **Valid** — hot-swapped into the in-memory configuration and used by
  new operations. <a id="cite-param.validation.valid-is-hot-swapped"></a>
- **Invalid** — out of range, the wrong type, or missing — the value is
  **ignored** and the previously active one is kept: the compiled-in
  default or the last known-good. <a id="cite-param.validation.invalid-is-ignored-previous-kept"></a>
  An `lcs.config.value.rejected` audit event is emitted naming the
  parameter, what was wrong, and the value being retained ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)).

**Values are never clamped or silently corrected.** <a id="cite-param.validation.never-clamped"></a> There is no
`min`/`max` on any configuration path. A write to the registry
succeeds, because the source does not enforce kernel semantics, and LCS
simply refuses to use it. The registry shows what was written; the
audit log shows what LCS is running on.

Because "missing" is invalid, a first boot before seed restore emits
nineteen of these events per refresh — provided `Machine\System\Registry`
itself exists. If the key is absent there is nothing to read and
nothing is reported; the fallback watch of [The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>) waits for it.

<a id="trm-5-10-3-3"></a>

## Hot-swap and in-flight operations

Configuration is published as a whole structure under a seqlock, and a
reader takes a complete copy of it. <a id="cite-param.hot-swap.published-as-one-structure"></a>

A syscall entry point snapshots it once and threads that snapshot
through the operation, so in-flight work uses the values that were
current when it started and new work uses the updated ones. <a id="cite-param.hot-swap.syscall-snapshots-once"></a>

That is the rule, and mostly the practice. Some deeper paths take a
second snapshot part-way through, and a few call sites read a single
live value rather than a snapshot — `reg_begin_transaction`'s timeout,
the bound-transaction cap, and the in-flight request cap among them.
For those, a hot-swap can be observed mid-operation. <a id="cite-param.hot-swap.some-call-sites-read-live-values"></a>

<a id="trm-5-10-3-4"></a>

## Security

`Machine\System\Registry\` inherits the `Machine` hive root descriptor
— SYSTEM and Administrators with `KEY_ALL_ACCESS`, Authenticated Users
with `KEY_READ` — so an unprivileged process cannot change any of
this. <a id="cite-param.security.unprivileged-cannot-change"></a>

Domain policy at a higher-precedence layer defends against a
compromised local administrator, which is the reason `SeTcbPrivilege`
guards precedence above 0 ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

## Operator verification

Inspect the stored configuration and installed manual before tuning LCS:

```sh
reg get Machine/System/Registry
regman 'Machine\System\Registry'
```

Keep a recovery value. A successful write confirms storage, not adoption;
inspect `lcs.config.value.rejected` events as well. Deleting a parameter does
not reset an already accepted running value. Write the intended valid value
and verify it at the documented application point.

An unavailable hive is a source problem, distinct from an absent parameter.
For loregd, inspect the output captured by Peinit before readiness and the
stored service logs after logging starts. Missing configuration alone is not
evidence that a database needs replacement or reseeding.

---

# The Self-Watch

_Peios Kernel / Internals / LCS / Bootstrap_

> LCS watches its own configuration through the same machinery userspace uses — what it drives, how it is armed, and why the callback is not the atomicity boundary.

<a id="trm-5-10-4"></a>

LCS watches its own configuration and layer metadata subtrees, and it
does so through the same machinery userspace uses — but not through the
same interface.

An internal watch is an entry in the same watch map, taking a reference
on the same subtree watch set, distinguished only by a kind marker. It
has **no fd, no granted access mask and no filter**. <a id="cite-self-watch.no-fd-mask-or-filter"></a>

Events reach it through a kernel callback rather than being queued for
a `read()`, and it is therefore not subject to
`NotificationQueueSize`. <a id="cite-self-watch.exempt-from-notification-queue-size"></a>

It is also not subject to `MaxSubtreeWatchDepth`, nor to the
transaction burst suppressor: internal collection happens before either
test. <a id="cite-self-watch.exempt-from-depth-and-burst-limits"></a>

Because there is no filter, deliverability is decided per target rather
than by a bitmask. Each internal target admits only the event types it
cares about: value events on the watched key itself for the
configuration subtrees, and subkey events at depth 0 or value and
descriptor events at depth 1 for the layer metadata subtree. <a id="cite-self-watch.admits-event-types-per-target"></a>

<a id="trm-5-10-4-1"></a>

## What it drives

**Self-configuration.** A change under `Machine\System\Registry\`
triggers a re-read and validation of the parameters ([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)). <a id="cite-self-watch.drives.parameter-re-read"></a>

**The layer table.** A change under `Machine\System\Registry\Layers\`
marks the affected layer names dirty and drives a bounded refresh of
their precedence, enabled state, owner and cached descriptor. Within
one delivery — a transaction's commit, say, whose batch creates a
layer and then writes its three values — each dirty layer is refreshed
once, however many of the batch's events named it. <a id="cite-self-watch.layer-refreshed-once-per-delivery"></a>

**Layer lifecycle.** `SUBKEY_CREATED` and `SUBKEY_DELETED` under
`Layers\` add and remove layers, except for `base`, which is ignored
([The Base Layer](</kernel/internals/lcs/layers/the-base-layer.md#trm-5-3-2>)). <a id="cite-self-watch.drives.layer-lifecycle-from-subkey-events"></a>

**KMES configuration.** A third internal watch, on
`Machine\System\KMES\`, exists for KMES's own parameters. <a id="cite-self-watch.drives.kmes-configuration"></a> It is not
LCS configuration, but the registry is where it lives and this is the
mechanism that notices it change.

<a id="trm-5-10-4-2"></a>

## The callback is not the atomicity boundary

For layer metadata, internal delivery identifies which layer names are
dirty. It does not itself publish anything, and it must not: publishing
a layer means publishing its table entry, metadata key GUID and cached
descriptor together ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)), and a callback that published a partial
entry would create a window in which a layer exists and nobody can be
authorised against it. <a id="cite-self-watch.callback-does-not-publish"></a>

LCS also does not perform source round trips while holding the
watch-map or layer-table publication locks. <a id="cite-self-watch.no-source-round-trip-under-locks"></a> The refresh runs outside
them, after the mutating operation commits and before the syscall
returns.

<a id="trm-5-10-4-3"></a>

## Arming

At bootstrap, LCS resolves the GUIDs for `Machine\System\Registry\` and
`Machine\System\Registry\Layers\` through `RSI_LOOKUP` and arms
targeted subtree watches. <a id="cite-self-watch.arming.targeted-via-rsi-lookup"></a>

If either does not exist — first boot, empty database — it arms a
subtree watch on the `Machine\` hive root instead, so that seed restore
creating the subtree is noticed. <a id="cite-self-watch.arming.fallback-on-machine-root"></a>

That fallback event re-enters the whole bootstrap refresh, which
resolves the specific GUIDs and arms the targeted watches. <a id="cite-self-watch.arming.fallback-event-re-enters-refresh"></a>

In practice the kernel arms both: targeted watches for whichever roots
exist, **plus** the `Machine\` root fallback, until a refresh finds
everything present. <a id="cite-self-watch.arming.mixed-superset"></a> It is a superset of what is needed rather
than a substitute for it.

The same arming covers every key the kernel reads for itself, not only
LCS's own: KMES configuration, the port reservation table
(`Machine\System\Network\TcpIp\PortReservations\`, see the KACS
chapter on network objects), the network policy key
(`Machine\System\Network\`, whose rules and inventory the packet
engine reads — see the network policy chapter) and the event emission
policy (`Machine\Generic\Events\`, see the KMES chapter) are
discovered in the same refresh and get the same targeted-or-fallback
treatment. <a id="cite-self-watch.arming.covers-every-kernel-read-key"></a>

The two policy watches are the depth-unbounded, every-mutation ones.
For the network policy, rules are keys and exceptions are subkeys, so
anything written anywhere beneath the key may be policy. <a id="cite-self-watch.arming.policy-watch-is-depth-unbounded"></a>
The emission policy has a key per event-type segment at any depth, and
its watch passes on only changes on `Events` itself, beneath the
kernel's own roots, and to `Enabled` values (KMES [Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)).

**A refresh that fails still arms the fallback.** A stage can fail
transiently — a source answering a lookup while a concurrent write has
half-created a key was the case that found this — and if the refresh
simply returned, no watch would exist and no kernel-read key would load
for the life of the boot. So when any stage before arming fails, LCS
arms the `Machine\` root fallback alone: the next subkey creation under
the hive re-enters the refresh, which then arms the targeted watches as
above. <a id="cite-self-watch.arming.failed-refresh-arms-fallback-alone"></a>

The failure and the fallback arm are both traced by
`lcs:lcs_bootstrap_refresh`. <a id="cite-self-watch.arming.failure-is-traced"></a>

<a id="trm-5-10-4-4"></a>

## Bootstrap interaction

1. A source registers. LCS reads `Machine\System\Registry\*`; the keys
   do not exist; compiled-in defaults are retained.
2. Seed restore populates them. The subtree watch fires, LCS validates
   and hot-swaps to the seed values.
3. Subsequent administrative changes fire the watch again, and LCS
   validates and hot-swaps, or rejects with an audit event.

At no point is there a state in which LCS is waiting for
configuration.

---

# BPF Documentation

_Peios Kernel / Internals / BPF_

> This directory contains documentation for the BPF (Berkeley Packet Filter) facility, with a focus on the extended BPF version (eBPF).

<a id="rst-bpf-documentation"></a>

This directory contains documentation for the BPF (Berkeley Packet Filter) facility, with a focus on the extended BPF version (eBPF).

This kernel side documentation is still work in progress. The Cilium project also maintains a [BPF and XDP Reference Guide](<https://docs.cilium.io/en/latest/bpf/>) that goes into great technical depth about the BPF Architecture.

- [eBPF verifier](</kernel/internals/bpf/verifier.md>)
- [libbpf](</kernel/internals/bpf/libbpf/index.md>)
- [BPF Standardization](</kernel/internals/bpf/standardization/index.md>)
- [BPF Type Format (BTF)](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/btf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Frequently asked questions (FAQ)](</kernel/internals/bpf/faq.md>)
- [Syscall API](</kernel/internals/bpf/syscall-api.md>)
- [Helper functions](</kernel/internals/bpf/helpers.md>)
- [BPF Kernel Functions (kfuncs)](</kernel/internals/bpf/kfuncs.md>)
- [BPF cpumask kfuncs](</kernel/internals/bpf/cpumasks.md>)
- [BPF filesystem kfuncs](</kernel/internals/bpf/fs-kfuncs.md>)
- [Program Types](</kernel/internals/bpf/programs.md>)
- [BPF maps](</kernel/internals/bpf/maps.md>)
- [Running BPF programs from userspace](</kernel/internals/bpf/bpf-prog-run.md>)
- [Classic BPF vs eBPF](</kernel/internals/bpf/classic-vs-extended.md>)
- [BPF Iterators](</kernel/internals/bpf/bpf-iterators.md>)
- [BPF licensing](</kernel/internals/bpf/bpf-licensing.md>)
- [Testing and debugging BPF](</kernel/internals/bpf/test-debug.md>)
- [Contents](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/clang-notes.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Contents](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/linux-notes.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Other](</kernel/internals/bpf/other.md>)
- [Redirect](</kernel/internals/bpf/redirect.md>)

<!-- Links: -->

<a id="rst-bpf-and-xdp-reference-guide"></a>

---

# BPF Design Q&A

_Peios Kernel / Internals / BPF_

> BPF extensibility and applicability to networking, tracing, security in the linux kernel and several user space implementations of BPF virtual machine led to a number of misunderstanding on what BPF actually is. This short QA is an attempt…

<a id="rst-bpf-design-q-a"></a>

BPF extensibility and applicability to networking, tracing, security in the linux kernel and several user space implementations of BPF virtual machine led to a number of misunderstanding on what BPF actually is. This short QA is an attempt to address that and outline a direction of where BPF is heading long term.

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



<a id="rst-questions-and-answers"></a>

## Questions and Answers

<a id="rst-q-is-bpf-a-generic-instruction-set-similar-to-x64-and-arm64"></a>

### Q: Is BPF a generic instruction set similar to x64 and arm64?

A: NO.

<a id="rst-q-is-bpf-a-generic-virtual-machine"></a>

### Q: Is BPF a generic virtual machine ?

A: NO.

<a id="rst-bpf-is-generic-instruction-set-with-c-calling-convention"></a>

### BPF is generic instruction set *with* C calling convention.

<a id="rst-q-why-c-calling-convention-was-chosen"></a>

#### Q: Why C calling convention was chosen?

A: Because BPF programs are designed to run in the linux kernel which is written in C, hence BPF defines instruction set compatible with two most used architectures x64 and arm64 (and takes into consideration important quirks of other architectures) and defines calling convention that is compatible with C calling convention of the linux kernel on those architectures.

<a id="rst-q-can-multiple-return-values-be-supported-in-the-future"></a>

#### Q: Can multiple return values be supported in the future?

A: NO. BPF allows only register R0 to be used as return value.

<a id="rst-q-can-more-than-5-function-arguments-be-supported-in-the-future"></a>

#### Q: Can more than 5 function arguments be supported in the future?

A: NO. BPF calling convention only allows registers R1-R5 to be used as arguments. BPF is not a standalone instruction set. (unlike x64 ISA that allows msft, cdecl and other conventions)

<a id="rst-q-can-bpf-programs-access-instruction-pointer-or-return-address"></a>

### Q: Can BPF programs access instruction pointer or return address?

A: NO.

<a id="rst-q-can-bpf-programs-access-stack-pointer"></a>

### Q: Can BPF programs access stack pointer ?

A: NO.

Only frame pointer (register R10) is accessible. From compiler point of view it's necessary to have stack pointer. For example, LLVM defines register R11 as stack pointer in its BPF backend, but it makes sure that generated code never uses it.

<a id="rst-q-does-c-calling-convention-diminishes-possible-use-cases"></a>

### Q: Does C-calling convention diminishes possible use cases?

A: YES.

BPF design forces addition of major functionality in the form of kernel helper functions and kernel objects like BPF maps with seamless interoperability between them. It lets kernel call into BPF programs and programs call kernel helpers with zero overhead, as all of them were native C code. That is particularly the case for JITed BPF programs that are indistinguishable from native kernel C code.

<a id="rst-q-does-it-mean-that-innovative-extensions-to-bpf-code-are-disallowed"></a>

### Q: Does it mean that 'innovative' extensions to BPF code are disallowed?

A: Soft yes.

At least for now, until BPF core has support for bpf-to-bpf calls, indirect calls, loops, global variables, jump tables, read-only sections, and all other normal constructs that C code can produce.

<a id="rst-q-can-loops-be-supported-in-a-safe-way"></a>

### Q: Can loops be supported in a safe way?

A: It's not clear yet.

BPF developers are trying to find a way to support bounded loops.

<a id="rst-q-what-are-the-verifier-limits"></a>

### Q: What are the verifier limits?

A: The only limit known to the user space is BPF_MAXINSNS (4096). It's the maximum number of instructions that the unprivileged bpf program can have. The verifier has various internal limits. Like the maximum number of instructions that can be explored during program analysis. Currently, that limit is set to 1 million. Which essentially means that the largest program can consist of 1 million NOP instructions. There is a limit to the maximum number of subsequent branches, a limit to the number of nested bpf-to-bpf calls, a limit to the number of the verifier states per instruction, a limit to the number of maps used by the program. All these limits can be hit with a sufficiently complex program. There are also non-numerical limits that can cause the program to be rejected. The verifier used to recognize only pointer + constant expressions. Now it can recognize pointer + bounded_register. bpf_lookup_map_elem(key) had a requirement that 'key' must be a pointer to the stack. Now, 'key' can be a pointer to map value. The verifier is steadily getting 'smarter'. The limits are being removed. The only way to know that the program is going to be accepted by the verifier is to try to load it. The bpf development process guarantees that the future kernel versions will accept all bpf programs that were accepted by the earlier versions.

<a id="rst-instruction-level-questions"></a>

### Instruction level questions

<a id="rst-q-ld-abs-and-ld-ind-instructions-vs-c-code"></a>

#### Q: LD_ABS and LD_IND instructions vs C code

Q: How come LD_ABS and LD_IND instruction are present in BPF whereas C code cannot express them and has to use builtin intrinsics?

A: This is artifact of compatibility with classic BPF. Modern networking code in BPF performs better without them. See 'direct packet access'.

<a id="rst-q-bpf-instructions-mapping-not-one-to-one-to-native-cpu"></a>

#### Q: BPF instructions mapping not one-to-one to native CPU

Q: It seems not all BPF instructions are one-to-one to native CPU. For example why BPF_JNE and other compare and jumps are not cpu-like?

A: This was necessary to avoid introducing flags into ISA which are impossible to make generic and efficient across CPU architectures.

<a id="rst-q-why-bpf-div-instruction-doesn-t-map-to-x64-div"></a>

#### Q: Why BPF_DIV instruction doesn't map to x64 div?

A: Because if we picked one-to-one relationship to x64 it would have made it more complicated to support on arm64 and other archs. Also it needs div-by-zero runtime check.

<a id="rst-q-why-bpf-has-implicit-prologue-and-epilogue"></a>

#### Q: Why BPF has implicit prologue and epilogue?

A: Because architectures like sparc have register windows and in general there are enough subtle differences between architectures, so naive store return address into stack won't work. Another reason is BPF has to be safe from division by zero (and legacy exception path of LD_ABS insn). Those instructions need to invoke epilogue and return implicitly.

<a id="rst-q-why-bpf-jlt-and-bpf-jle-instructions-were-not-introduced-in-the-beginning"></a>

#### Q: Why BPF_JLT and BPF_JLE instructions were not introduced in the beginning?

A: Because classic BPF didn't have them and BPF authors felt that compiler workaround would be acceptable. Turned out that programs lose performance due to lack of these compare instructions and they were added. These two instructions is a perfect example what kind of new BPF instructions are acceptable and can be added in the future. These two already had equivalent instructions in native CPUs. New instructions that don't have one-to-one mapping to HW instructions will not be accepted.

<a id="rst-q-bpf-32-bit-subregister-requirements"></a>

#### Q: BPF 32-bit subregister requirements

Q: BPF 32-bit subregisters have a requirement to zero upper 32-bits of BPF registers which makes BPF inefficient virtual machine for 32-bit CPU architectures and 32-bit HW accelerators. Can true 32-bit registers be added to BPF in the future?

A: NO.

But some optimizations on zero-ing the upper 32 bits for BPF registers are available, and can be leveraged to improve the performance of JITed BPF programs for 32-bit architectures.

Starting with version 7, LLVM is able to generate instructions that operate on 32-bit subregisters, provided the option -mattr=+alu32 is passed for compiling a program. Furthermore, the verifier can now mark the instructions for which zero-ing the upper bits of the destination register is required, and insert an explicit zero-extension (zext) instruction (a mov32 variant). This means that for architectures without zext hardware support, the JIT back-ends do not need to clear the upper bits for subregisters written by alu32 instructions or narrow loads. Instead, the back-ends simply need to support code generation for that mov32 variant, and to overwrite bpf_jit_needs_zext() to make it return "true" (in order to enable zext insertion in the verifier).

Note that it is possible for a JIT back-end to have partial hardware support for zext. In that case, if verifier zext insertion is enabled, it could lead to the insertion of unnecessary zext instructions. Such instructions could be removed by creating a simple peephole inside the JIT back-end: if one instruction has hardware support for zext and if the next instruction is an explicit zext, then the latter can be skipped when doing the code generation.

<a id="rst-q-does-bpf-have-a-stable-abi"></a>

### Q: Does BPF have a stable ABI?

A: YES. BPF instructions, arguments to BPF programs, set of helper functions and their arguments, recognized return codes are all part of ABI. However there is one specific exception to tracing programs which are using helpers like bpf_probe_read() to walk kernel internal data structures and compile with kernel internal headers. Both of these kernel internals are subject to change and can break with newer kernels such that the program needs to be adapted accordingly.

New BPF functionality is generally added through the use of kfuncs instead of new helpers. Kfuncs are not considered part of the stable API, and have their own lifecycle expectations as described in [3. kfunc lifecycle expectations](</kernel/internals/bpf/kfuncs.md#rst-bpf-kfunc-lifecycle-expectations>).

<a id="rst-q-are-tracepoints-part-of-the-stable-abi"></a>

### Q: Are tracepoints part of the stable ABI?

A: NO. Tracepoints are tied to internal implementation details hence they are subject to change and can break with newer kernels. BPF programs need to change accordingly when this happens.

<a id="rst-q-are-places-where-kprobes-can-attach-part-of-the-stable-abi"></a>

### Q: Are places where kprobes can attach part of the stable ABI?

A: NO. The places to which kprobes can attach are internal implementation details, which means that they are subject to change and can break with newer kernels. BPF programs need to change accordingly when this happens.

<a id="rst-q-how-much-stack-space-a-bpf-program-uses"></a>

### Q: How much stack space a BPF program uses?

A: Currently all program types are limited to 512 bytes of stack space, but the verifier computes the actual amount of stack used and both interpreter and most JITed code consume necessary amount.

<a id="rst-q-can-bpf-be-offloaded-to-hw"></a>

### Q: Can BPF be offloaded to HW?

A: YES. BPF HW offload is supported by NFP driver.

<a id="rst-q-does-classic-bpf-interpreter-still-exist"></a>

### Q: Does classic BPF interpreter still exist?

A: NO. Classic BPF programs are converted into extend BPF instructions.

<a id="rst-q-can-bpf-call-arbitrary-kernel-functions"></a>

### Q: Can BPF call arbitrary kernel functions?

A: NO. BPF programs can only call specific functions exposed as BPF helpers or kfuncs. The set of available functions is defined for every program type.

<a id="rst-q-can-bpf-overwrite-arbitrary-kernel-memory"></a>

### Q: Can BPF overwrite arbitrary kernel memory?

A: NO.

Tracing bpf programs can *read* arbitrary memory with bpf_probe_read() and bpf_probe_read_str() helpers. Networking programs cannot read arbitrary memory, since they don't have access to these helpers. Programs can never read or write arbitrary memory directly.

<a id="rst-q-can-bpf-overwrite-arbitrary-user-memory"></a>

### Q: Can BPF overwrite arbitrary user memory?

A: Sort-of.

Tracing BPF programs can overwrite the user memory of the current task with bpf_probe_write_user(). Every time such program is loaded the kernel will print warning message, so this helper is only useful for experiments and prototypes. Tracing BPF programs are root only.

<a id="rst-q-new-functionality-via-kernel-modules"></a>

### Q: New functionality via kernel modules?

Q: Can BPF functionality such as new program or map types, new helpers, etc be added out of kernel module code?

A: Yes, through kfuncs and kptrs

The core BPF functionality such as program types, maps and helpers cannot be added to by modules. However, modules can expose functionality to BPF programs by exporting kfuncs (which may return pointers to module-internal data structures as kptrs).

<a id="rst-q-directly-calling-kernel-function-is-an-abi"></a>

### Q: Directly calling kernel function is an ABI?

Q: Some kernel functions (e.g. tcp_slow_start) can be called by BPF programs.  Do these kernel functions become an ABI?

A: NO.

The kernel function protos will change and the bpf programs will be rejected by the verifier.  Also, for example, some of the bpf-callable kernel functions have already been used by other kernel tcp cc (congestion-control) implementations.  If any of these kernel functions has changed, both the in-tree and out-of-tree kernel tcp cc implementations have to be changed.  The same goes for the bpf programs and they have to be adjusted accordingly. See [3. kfunc lifecycle expectations](</kernel/internals/bpf/kfuncs.md#rst-bpf-kfunc-lifecycle-expectations>) for details.

<a id="rst-q-attaching-to-arbitrary-kernel-functions-is-an-abi"></a>

### Q: Attaching to arbitrary kernel functions is an ABI?

Q: BPF programs can be attached to many kernel functions.  Do these kernel functions become part of the ABI?

A: NO.

The kernel function prototypes will change, and BPF programs attaching to them will need to change.  The BPF compile-once-run-everywhere (CO-RE) should be used in order to make it easier to adapt your BPF programs to different versions of the kernel.

<a id="rst-q-marking-a-function-with-btf-id-makes-that-function-an-abi"></a>

### Q: Marking a function with BTF_ID makes that function an ABI?

A: NO.

The BTF_ID macro does not cause a function to become part of the ABI any more than does the EXPORT_SYMBOL_GPL macro.

<a id="rst-q-what-is-the-compatibility-story-for-special-bpf-types-in-map-values"></a>

### Q: What is the compatibility story for special BPF types in map values?

Q: Users are allowed to embed bpf_spin_lock, bpf_timer fields in their BPF map values (when using BTF support for BPF maps). This allows to use helpers for such objects on these fields inside map values. Users are also allowed to embed pointers to some kernel types (with \__kptr_untrusted and \__kptr BTF tags). Will the kernel preserve backwards compatibility for these features?

A: It depends. For bpf_spin_lock, bpf_timer: YES, for kptr and everything else: NO, but see below.

For struct types that have been added already, like bpf_spin_lock and bpf_timer, the kernel will preserve backwards compatibility, as they are part of UAPI.

For kptrs, they are also part of UAPI, but only with respect to the kptr mechanism. The types that you can use with a \__kptr_untrusted and \__kptr tagged pointer in your struct are NOT part of the UAPI contract. The supported types can and will change across kernel releases. However, operations like accessing kptr fields and bpf_kptr_xchg() helper will continue to be supported across kernel releases for the supported types.

For any other supported struct type, unless explicitly stated in this document and added to bpf.h UAPI header, such types can and will arbitrarily change their size, type, and alignment, or any other user visible API or ABI detail across kernel releases. The users must adapt their BPF programs to the new changes and update them to make sure their programs continue to work correctly.

NOTE: BPF subsystem specially reserves the 'bpf\_' prefix for type names, in order to introduce more special fields in the future. Hence, user programs must avoid defining types with 'bpf\_' prefix to not be broken in future releases. In other words, no backwards compatibility is guaranteed if one using a type in BTF with 'bpf\_' prefix.

<a id="rst-q-what-is-the-compatibility-story-for-special-bpf-types-in-allocated-objects"></a>

### Q: What is the compatibility story for special BPF types in allocated objects?

Q: Same as above, but for allocated objects (i.e. objects allocated using bpf_obj_new for user defined types). Will the kernel preserve backwards compatibility for these features?

A: NO.

Unlike map value types, the API to work with allocated objects and any support for special fields inside them is exposed through kfuncs, and thus has the same lifecycle expectations as the kfuncs themselves. See [3. kfunc lifecycle expectations](</kernel/internals/bpf/kfuncs.md#rst-bpf-kfunc-lifecycle-expectations>) for details.

---

# HOWTO interact with BPF subsystem

_Peios Kernel / Internals / BPF_

> This document provides information for the BPF subsystem about various workflows related to reporting bugs, submitting patches, and queueing patches for stable kernels.

<a id="rst-howto-interact-with-bpf-subsystem"></a>

This document provides information for the BPF subsystem about various workflows related to reporting bugs, submitting patches, and queueing patches for stable kernels.

For general information about submitting patches, please refer to [Documentation/process/submitting-patches.rst](/kernel/development/process/submitting-patches.md). This document only describes additional specifics related to BPF.

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



<a id="rst-reporting-bugs"></a>

## Reporting bugs

<a id="rst-q-how-do-i-report-bugs-for-bpf-kernel-code"></a>

### Q: How do I report bugs for BPF kernel code?

A: Since all BPF kernel development as well as bpftool and iproute2 BPF loader development happens through the bpf kernel mailing list, please report any found issues around BPF to the following mailing list:

> [bpf@vger.kernel.org](<mailto:bpf@vger.kernel.org>)

This may also include issues related to XDP, BPF tracing, etc.

Given netdev has a high volume of traffic, please also add the BPF maintainers to Cc (from kernel `MAINTAINERS` file):

- Alexei Starovoitov &lt;[ast@kernel.org](<mailto:ast@kernel.org>)&gt;

- Daniel Borkmann &lt;[daniel@iogearbox.net](<mailto:daniel@iogearbox.net>)&gt;

In case a buggy commit has already been identified, make sure to keep the actual commit authors in Cc as well for the report. They can typically be identified through the kernel's git tree.

**Please do NOT report BPF issues to bugzilla.kernel.org since it is a guarantee that the reported issue will be overlooked.**

<a id="rst-submitting-patches"></a>

## Submitting patches

<a id="rst-q-how-do-i-run-bpf-ci-on-my-changes-before-sending-them-out-for-review"></a>

### Q: How do I run BPF CI on my changes before sending them out for review?

A: BPF CI is GitHub based and hosted at [https://github.com/kernel-patches/bpf](<https://github.com/kernel-patches/bpf>). While GitHub also provides a CLI that can be used to accomplish the same results, here we focus on the UI based workflow.

The following steps lay out how to start a CI run for your patches:

- Create a fork of the aforementioned repository in your own account (one time action)

- Clone the fork locally, check out a new branch tracking either the bpf-next or bpf branch, and apply your to-be-tested patches on top of it

- Push the local branch to your fork and create a pull request against kernel-patches/bpf's bpf-next_base or bpf_base branch, respectively

Shortly after the pull request has been created, the CI workflow will run. Note that capacity is shared with patches submitted upstream being checked and so depending on utilization the run can take a while to finish.

Note furthermore that both base branches (bpf-next_base and bpf_base) will be updated as patches are pushed to the respective upstream branches they track. As such, your patch set will automatically (be attempted to) be rebased as well. This behavior can result in a CI run being aborted and restarted with the new base line.

<a id="rst-q-to-which-mailing-list-do-i-need-to-submit-my-bpf-patches"></a>

### Q: To which mailing list do I need to submit my BPF patches?

A: Please submit your BPF patches to the bpf kernel mailing list:

> [bpf@vger.kernel.org](<mailto:bpf@vger.kernel.org>)

In case your patch has changes in various different subsystems (e.g. networking, tracing, security, etc), make sure to Cc the related kernel mailing lists and maintainers from there as well, so they are able to review the changes and provide their Acked-by's to the patches.

<a id="rst-q-where-can-i-find-patches-currently-under-discussion-for-bpf-subsystem"></a>

### Q: Where can I find patches currently under discussion for BPF subsystem?

A: All patches that are Cc'ed to netdev are queued for review under netdev patchwork project:

> [https://patchwork.kernel.org/project/netdevbpf/list/](<https://patchwork.kernel.org/project/netdevbpf/list/>)

Those patches which target BPF, are assigned to a 'bpf' delegate for further processing from BPF maintainers. The current queue with patches under review can be found at:

> [https://patchwork.kernel.org/project/netdevbpf/list/?delegate=121173](<https://patchwork.kernel.org/project/netdevbpf/list/?delegate=121173>)

Once the patches have been reviewed by the BPF community as a whole and approved by the BPF maintainers, their status in patchwork will be changed to 'Accepted' and the submitter will be notified by mail. This means that the patches look good from a BPF perspective and have been applied to one of the two BPF kernel trees.

In case feedback from the community requires a respin of the patches, their status in patchwork will be set to 'Changes Requested', and purged from the current review queue. Likewise for cases where patches would get rejected or are not applicable to the BPF trees (but assigned to the 'bpf' delegate).

<a id="rst-q-how-do-the-changes-make-their-way-into-linux"></a>

### Q: How do the changes make their way into Linux?

A: There are two BPF kernel trees (git repositories). Once patches have been accepted by the BPF maintainers, they will be applied to one of the two BPF trees:

> - [https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf.git/](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf.git/>)
>
> - [https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/>)

The bpf tree itself is for fixes only, whereas bpf-next for features, cleanups or other kind of improvements ("next-like" content). This is analogous to net and net-next trees for networking. Both bpf and bpf-next will only have a master branch in order to simplify against which branch patches should get rebased to.

Accumulated BPF patches in the bpf tree will regularly get pulled into the net kernel tree. Likewise, accumulated BPF patches accepted into the bpf-next tree will make their way into net-next tree. net and net-next are both run by David S. Miller. From there, they will go into the kernel mainline tree run by Linus Torvalds. To read up on the process of net and net-next being merged into the mainline tree, see the documentation on netdev subsystem at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md).

Occasionally, to prevent merge conflicts, we might send pull requests to other trees (e.g. tracing) with a small subset of the patches, but net and net-next are always the main trees targeted for integration.

The pull requests will contain a high-level summary of the accumulated patches and can be searched on netdev kernel mailing list through the following subject lines (`yyyy-mm-dd` is the date of the pull request):



```text
pull-request: bpf yyyy-mm-dd
pull-request: bpf-next yyyy-mm-dd
```

<a id="rst-q-how-do-i-indicate-which-tree-bpf-vs-bpf-next-my-patch-should-be-applied-to"></a>

### Q: How do I indicate which tree (bpf vs. bpf-next) my patch should be applied to?

A: The process is the very same as described in the netdev subsystem documentation at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md), so please read up on it. The subject line must indicate whether the patch is a fix or rather "next-like" content in order to let the maintainers know whether it is targeted at bpf or bpf-next.

For fixes eventually landing in bpf -&gt; net tree, the subject must look like:



```text
git format-patch --subject-prefix='PATCH bpf' start..finish
```

For features/improvements/etc that should eventually land in bpf-next -&gt; net-next, the subject must look like:



```text
git format-patch --subject-prefix='PATCH bpf-next' start..finish
```

If unsure whether the patch or patch series should go into bpf or net directly, or bpf-next or net-next directly, it is not a problem either if the subject line says net or net-next as target. It is eventually up to the maintainers to do the delegation of the patches.

If it is clear that patches should go into bpf or bpf-next tree, please make sure to rebase the patches against those trees in order to reduce potential conflicts.

In case the patch or patch series has to be reworked and sent out again in a second or later revision, it is also required to add a version number (`v2`, `v3`, ...) into the subject prefix:



```text
git format-patch --subject-prefix='PATCH bpf-next v2' start..finish
```

When changes have been requested to the patch series, always send the whole patch series again with the feedback incorporated (never send individual diffs on top of the old series).

<a id="rst-q-what-does-it-mean-when-a-patch-gets-applied-to-bpf-or-bpf-next-tree"></a>

### Q: What does it mean when a patch gets applied to bpf or bpf-next tree?

A: It means that the patch looks good for mainline inclusion from a BPF point of view.

Be aware that this is not a final verdict that the patch will automatically get accepted into net or net-next trees eventually:

On the bpf kernel mailing list reviews can come in at any point in time. If discussions around a patch conclude that they cannot get included as-is, we will either apply a follow-up fix or drop them from the trees entirely. Therefore, we also reserve to rebase the trees when deemed necessary. After all, the purpose of the tree is to:

- **i)** accumulate and stage BPF patches for integration into trees like net and net-next, and

- **ii)** run extensive BPF test suite and workloads on the patches before they make their way any further.

Once the BPF pull request was accepted by David S. Miller, then the patches end up in net or net-next tree, respectively, and make their way from there further into mainline. Again, see the documentation for netdev subsystem at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md) for additional information e.g. on how often they are merged to mainline.

<a id="rst-q-how-long-do-i-need-to-wait-for-feedback-on-my-bpf-patches"></a>

### Q: How long do I need to wait for feedback on my BPF patches?

A: We try to keep the latency low. The usual time to feedback will be around 2 or 3 business days. It may vary depending on the complexity of changes and current patch load.

<a id="rst-q-how-often-do-you-send-pull-requests-to-major-kernel-trees-like-net-or-net-next"></a>

### Q: How often do you send pull requests to major kernel trees like net or net-next?

A: Pull requests will be sent out rather often in order to not accumulate too many patches in bpf or bpf-next.

As a rule of thumb, expect pull requests for each tree regularly at the end of the week. In some cases pull requests could additionally come also in the middle of the week depending on the current patch load or urgency.

<a id="rst-q-are-patches-applied-to-bpf-next-when-the-merge-window-is-open"></a>

### Q: Are patches applied to bpf-next when the merge window is open?

A: For the time when the merge window is open, bpf-next will not be processed. This is roughly analogous to net-next patch processing, so feel free to read up on the netdev docs at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md) about further details.

During those two weeks of merge window, we might ask you to resend your patch series once bpf-next is open again. Once Linus released a `v*-rc1` after the merge window, we continue processing of bpf-next.

For non-subscribers to kernel mailing lists, there is also a status page run by David S. Miller on net-next that provides guidance:

> [http://vger.kernel.org/\~davem/net-next.html](<http://vger.kernel.org/~davem/net-next.html>)

<a id="rst-q-verifier-changes-and-test-cases"></a>

### Q: Verifier changes and test cases

Q: I made a BPF verifier change, do I need to add test cases for BPF kernel [selftests](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/>)?

A: If the patch has changes to the behavior of the verifier, then yes, it is absolutely necessary to add test cases to the BPF kernel [selftests](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/>) suite. If they are not present and we think they are needed, then we might ask for them before accepting any changes.

In particular, test_verifier.c is tracking a high number of BPF test cases, including a lot of corner cases that LLVM BPF back end may generate out of the restricted C code. Thus, adding test cases is absolutely crucial to make sure future changes do not accidentally affect prior use-cases. Thus, treat those test cases as: verifier behavior that is not tracked in test_verifier.c could potentially be subject to change.

<a id="rst-q-samples-bpf-preference-vs-selftests"></a>

### Q: samples/bpf preference vs selftests?

Q: When should I add code to `samples/bpf/` and when to BPF kernel [selftests](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/>)?

A: In general, we prefer additions to BPF kernel [selftests](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/>) rather than `samples/bpf/`. The rationale is very simple: kernel selftests are regularly run by various bots to test for kernel regressions.

The more test cases we add to BPF selftests, the better the coverage and the less likely it is that those could accidentally break. It is not that BPF kernel selftests cannot demo how a specific feature can be used.

That said, `samples/bpf/` may be a good place for people to get started, so it might be advisable that simple demos of features could go into `samples/bpf/`, but advanced functional and corner-case testing rather into kernel selftests.

If your sample looks like a test case, then go for BPF kernel selftests instead\!

<a id="rst-q-when-should-i-add-code-to-the-bpftool"></a>

### Q: When should I add code to the bpftool?

A: The main purpose of bpftool (under tools/bpf/bpftool/) is to provide a central user space tool for debugging and introspection of BPF programs and maps that are active in the kernel. If UAPI changes related to BPF enable for dumping additional information of programs or maps, then bpftool should be extended as well to support dumping them.

<a id="rst-q-when-should-i-add-code-to-iproute2-s-bpf-loader"></a>

### Q: When should I add code to iproute2's BPF loader?

A: For UAPI changes related to the XDP or tc layer (e.g. `cls_bpf`), the convention is that those control-path related changes are added to iproute2's BPF loader as well from user space side. This is not only useful to have UAPI changes properly designed to be usable, but also to make those changes available to a wider user base of major downstream distributions.

<a id="rst-q-do-you-accept-patches-as-well-for-iproute2-s-bpf-loader"></a>

### Q: Do you accept patches as well for iproute2's BPF loader?

A: Patches for the iproute2's BPF loader have to be sent to:

> [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>)

While those patches are not processed by the BPF kernel maintainers, please keep them in Cc as well, so they can be reviewed.

The official git repository for iproute2 is run by Stephen Hemminger and can be found at:

> [https://git.kernel.org/pub/scm/linux/kernel/git/shemminger/iproute2.git/](<https://git.kernel.org/pub/scm/linux/kernel/git/shemminger/iproute2.git/>)

The patches need to have a subject prefix of '`[PATCH iproute2 master]`' or '`[PATCH iproute2 net-next]`'. '`master`' or '`net-next`' describes the target branch where the patch should be applied to. Meaning, if kernel changes went into the net-next kernel tree, then the related iproute2 changes need to go into the iproute2 net-next branch, otherwise they can be targeted at master branch. The iproute2 net-next branch will get merged into the master branch after the current iproute2 version from master has been released.

Like BPF, the patches end up in patchwork under the netdev project and are delegated to 'shemminger' for further processing:

> [http://patchwork.ozlabs.org/project/netdev/list/?delegate=389](<http://patchwork.ozlabs.org/project/netdev/list/?delegate=389>)

<a id="rst-q-what-is-the-minimum-requirement-before-i-submit-my-bpf-patches"></a>

### Q: What is the minimum requirement before I submit my BPF patches?

A: When submitting patches, always take the time and properly test your patches *prior* to submission. Never rush them\! If maintainers find that your patches have not been properly tested, it is a good way to get them grumpy. Testing patch submissions is a hard requirement\!

Note, fixes that go to bpf tree *must* have a `Fixes:` tag included. The same applies to fixes that target bpf-next, where the affected commit is in net-next (or in some cases bpf-next). The `Fixes:` tag is crucial in order to identify follow-up commits and tremendously helps for people having to do backporting, so it is a must have\!

We also don't accept patches with an empty commit message. Take your time and properly write up a high quality commit message, it is essential\!

Think about it this way: other developers looking at your code a month from now need to understand *why* a certain change has been done that way, and whether there have been flaws in the analysis or assumptions that the original author did. Thus providing a proper rationale and describing the use-case for the changes is a must.

Patch submissions with &gt;1 patch must have a cover letter which includes a high level description of the series. This high level summary will then be placed into the merge commit by the BPF maintainers such that it is also accessible from the git log for future reference.

<a id="rst-q-features-changing-bpf-jit-and-or-llvm"></a>

### Q: Features changing BPF JIT and/or LLVM

Q: What do I need to consider when adding a new instruction or feature that would require BPF JIT and/or LLVM integration as well?

A: We try hard to keep all BPF JITs up to date such that the same user experience can be guaranteed when running BPF programs on different architectures without having the program punt to the less efficient interpreter in case the in-kernel BPF JIT is enabled.

If you are unable to implement or test the required JIT changes for certain architectures, please work together with the related BPF JIT developers in order to get the feature implemented in a timely manner. Please refer to the git log (`arch/*/net/`) to locate the necessary people for helping out.

Also always make sure to add BPF test cases (e.g. test_bpf.c and test_verifier.c) for new instructions, so that they can receive broad test coverage and help run-time testing the various BPF JITs.

In case of new BPF instructions, once the changes have been accepted into the Linux kernel, please implement support into LLVM's BPF back end. See [LLVM](<#rst-llvm>) section below for further information.

<a id="rst-q-what-bpf-internal-symbol-namespace-is-for"></a>

### Q: What "BPF_INTERNAL" symbol namespace is for?

A: Symbols exported as BPF_INTERNAL can only be used by BPF infrastructure like preload kernel modules with light skeleton. Most symbols outside of BPF_INTERNAL are not expected to be used by code outside of BPF either. Symbols may lack the designation because they predate the namespaces, or due to an oversight.

<a id="rst-stable-submission"></a>

## Stable submission

<a id="rst-q-i-need-a-specific-bpf-commit-in-stable-kernels-what-should-i-do"></a>

### Q: I need a specific BPF commit in stable kernels. What should I do?

A: In case you need a specific fix in stable kernels, first check whether the commit has already been applied in the related `linux-*.y` branches:

> [https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git/>)

If not the case, then drop an email to the BPF maintainers with the netdev kernel mailing list in Cc and ask for the fix to be queued up:

> [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>)

The process in general is the same as on netdev itself, see also the the documentation on networking subsystem at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md).

<a id="rst-q-do-you-also-backport-to-kernels-not-currently-maintained-as-stable"></a>

### Q: Do you also backport to kernels not currently maintained as stable?

A: No. If you need a specific BPF commit in kernels that are currently not maintained by the stable maintainers, then you are on your own.

The current stable and longterm stable kernels are all listed here:

> [https://www.kernel.org/](<https://www.kernel.org/>)

<a id="rst-q-the-bpf-patch-i-am-about-to-submit-needs-to-go-to-stable-as-well"></a>

### Q: The BPF patch I am about to submit needs to go to stable as well

What should I do?

A: The same rules apply as with netdev patch submissions in general, see the netdev docs at [Documentation/process/maintainer-netdev.rst](/kernel/development/process/maintainer-netdev.md).

Never add "`Cc: stable@vger.kernel.org`" to the patch description, but ask the BPF maintainers to queue the patches instead. This can be done with a note, for example, under the `---` part of the patch which does not go into the git log. Alternatively, this can be done as a simple request by mail instead.

<a id="rst-q-queue-stable-patches"></a>

### Q: Queue stable patches

Q: Where do I find currently queued BPF patches that will be submitted to stable?

A: Once patches that fix critical bugs got applied into the bpf tree, they are queued up for stable submission under:

> [http://patchwork.ozlabs.org/bundle/bpf/stable/?state=\*](<http://patchwork.ozlabs.org/bundle/bpf/stable/?state=*>)

They will be on hold there at minimum until the related commit made its way into the mainline kernel tree.

After having been under broader exposure, the queued patches will be submitted by the BPF maintainers to the stable maintainers.

<a id="rst-testing-patches"></a>

## Testing patches

<a id="rst-q-how-to-run-bpf-selftests"></a>

### Q: How to run BPF selftests

A: After you have booted into the newly compiled kernel, navigate to the BPF [selftests](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/>) suite in order to test BPF functionality (current working directory points to the root of the cloned git tree):



```text
$ cd tools/testing/selftests/bpf/
$ make
```

To run the verifier tests:



```text
$ sudo ./test_verifier
```

The verifier tests print out all the current checks being performed. The summary at the end of running all tests will dump information of test successes and failures:



```text
Summary: 418 PASSED, 0 FAILED
```

In order to run through all BPF selftests, the following command is needed:



```text
$ sudo make run_tests
```

See [kernel selftest documentation](</kernel/development/dev-tools/kselftest.md>) for details.

To maximize the number of tests passing, the .config of the kernel under test should match the config file fragment in tools/testing/selftests/bpf as closely as possible.

Finally to ensure support for latest BPF Type Format features - discussed in [Documentation/bpf/btf.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/btf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) - pahole version 1.16 is required for kernels built with CONFIG_DEBUG_INFO_BTF=y. pahole is delivered in the dwarves package or can be built from source at

[https://github.com/acmel/dwarves](<https://github.com/acmel/dwarves>)

pahole starts to use libbpf definitions and APIs since v1.13 after the commit 21507cd3e97b ("pahole: add libbpf as submodule under lib/bpf"). It works well with the git repository because the libbpf submodule will use "git submodule update --init --recursive" to update.

Unfortunately, the default github release source code does not contain libbpf submodule source code and this will cause build issues, the tarball from [https://git.kernel.org/pub/scm/devel/pahole/pahole.git/](<https://git.kernel.org/pub/scm/devel/pahole/pahole.git/>) is same with github, you can get the source tarball with corresponding libbpf submodule codes from

[https://fedorapeople.org/\~acme/dwarves](<https://fedorapeople.org/~acme/dwarves>)

Some distros have pahole version 1.16 packaged already, e.g. Fedora, Gentoo.

<a id="rst-q-which-bpf-kernel-selftests-version-should-i-run-my-kernel-against"></a>

### Q: Which BPF kernel selftests version should I run my kernel against?

A: If you run a kernel `xyz`, then always run the BPF kernel selftests from that kernel `xyz` as well. Do not expect that the BPF selftest from the latest mainline tree will pass all the time.

In particular, test_bpf.c and test_verifier.c have a large number of test cases and are constantly updated with new BPF test sequences, or existing ones are adapted to verifier changes e.g. due to verifier becoming smarter and being able to better track certain things.

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

## LLVM

<a id="rst-q-where-do-i-find-llvm-with-bpf-support"></a>

### Q: Where do I find LLVM with BPF support?

A: The BPF back end for LLVM is upstream in LLVM since version 3.7.1.

All major distributions these days ship LLVM with BPF back end enabled, so for the majority of use-cases it is not required to compile LLVM by hand anymore, just install the distribution provided package.

LLVM's static compiler lists the supported targets through `llc --version`, make sure BPF targets are listed. Example:



```text
$ llc --version
LLVM (http://llvm.org/):
  LLVM version 10.0.0
  Optimized build.
  Default target: x86_64-unknown-linux-gnu
  Host CPU: skylake

  Registered Targets:
    aarch64    - AArch64 (little endian)
    bpf        - BPF (host endian)
    bpfeb      - BPF (big endian)
    bpfel      - BPF (little endian)
    x86        - 32-bit X86: Pentium-Pro and above
    x86-64     - 64-bit X86: EM64T and AMD64
```

For developers in order to utilize the latest features added to LLVM's BPF back end, it is advisable to run the latest LLVM releases. Support for new BPF kernel features such as additions to the BPF instruction set are often developed together.

All LLVM releases can be found at: [http://releases.llvm.org/](<http://releases.llvm.org/>)

<a id="rst-q-got-it-so-how-do-i-build-llvm-manually-anyway"></a>

### Q: Got it, so how do I build LLVM manually anyway?

A: We recommend that developers who want the fastest incremental builds use the Ninja build system, you can find it in your system's package manager, usually the package is ninja or ninja-build.

You need ninja, cmake and gcc-c++ as build requisites for LLVM. Once you have that set up, proceed with building the latest LLVM and clang version from the git repositories:



```text
$ git clone https://github.com/llvm/llvm-project.git
$ mkdir -p llvm-project/llvm/build
$ cd llvm-project/llvm/build
$ cmake .. -G "Ninja" -DLLVM_TARGETS_TO_BUILD="BPF;X86" \
           -DLLVM_ENABLE_PROJECTS="clang"    \
           -DCMAKE_BUILD_TYPE=Release        \
           -DLLVM_BUILD_RUNTIME=OFF
$ ninja
```

The built binaries can then be found in the build/bin/ directory, where you can point the PATH variable to.

Set `-DLLVM_TARGETS_TO_BUILD` equal to the target you wish to build, you will find a full list of targets within the llvm-project/llvm/lib/Target directory.

<a id="rst-q-reporting-llvm-bpf-issues"></a>

### Q: Reporting LLVM BPF issues

Q: Should I notify BPF kernel maintainers about issues in LLVM's BPF code generation back end or about LLVM generated code that the verifier refuses to accept?

A: Yes, please do\!

LLVM's BPF back end is a key piece of the whole BPF infrastructure and it ties deeply into verification of programs from the kernel side. Therefore, any issues on either side need to be investigated and fixed whenever necessary.

Therefore, please make sure to bring them up at netdev kernel mailing list and Cc BPF maintainers for LLVM and kernel bits:

- Yonghong Song &lt;[yhs@fb.com](<mailto:yhs@fb.com>)&gt;

- Alexei Starovoitov &lt;[ast@kernel.org](<mailto:ast@kernel.org>)&gt;

- Daniel Borkmann &lt;[daniel@iogearbox.net](<mailto:daniel@iogearbox.net>)&gt;

LLVM also has an issue tracker where BPF related bugs can be found:

> [https://bugs.llvm.org/buglist.cgi?quicksearch=bpf](<https://bugs.llvm.org/buglist.cgi?quicksearch=bpf>)

However, it is better to reach out through mailing lists with having maintainers in Cc.

<a id="rst-q-new-bpf-instruction-for-kernel-and-llvm"></a>

### Q: New BPF instruction for kernel and LLVM

Q: I have added a new BPF instruction to the kernel, how can I integrate it into LLVM?

A: LLVM has a `-mcpu` selector for the BPF back end in order to allow the selection of BPF instruction set extensions. Before llvm version 20, the `generic` processor target is used, which is the base instruction set (v1) of BPF. Since llvm 20, the default processor target has changed to instruction set v3.

LLVM has an option to select `-mcpu=probe` where it will probe the host kernel for supported BPF instruction set extensions and selects the optimal set automatically.

For cross-compilation, a specific version can be select manually as well



```text
$ llc -march bpf -mcpu=help
Available CPUs for this target:

  generic - Select the generic processor.
  probe   - Select the probe processor.
  v1      - Select the v1 processor.
  v2      - Select the v2 processor.
[...]
```

Newly added BPF instructions to the Linux kernel need to follow the same scheme, bump the instruction set version and implement probing for the extensions such that `-mcpu=probe` users can benefit from the optimization transparently when upgrading their kernels.

If you are unable to implement support for the newly added BPF instruction please reach out to BPF developers for help.

By the way, the BPF kernel selftests run with `-mcpu=probe` for better test coverage.

<a id="rst-q-clang-flag-for-target-bpf"></a>

### Q: clang flag for target bpf?

Q: In some cases clang flag `--target=bpf` is used but in other cases the default clang target, which matches the underlying architecture, is used. What is the difference and when I should use which?

A: Although LLVM IR generation and optimization try to stay architecture independent, `--target=<arch>` still has some impact on generated code:

- BPF program may recursively include header file(s) with file scope inline assembly codes. The default target can handle this well, while `bpf` target may fail if bpf backend assembler does not understand these assembly codes, which is true in most cases.

- When compiled without `-g`, additional elf sections, e.g., .eh_frame and .rela.eh_frame, may be present in the object file with default target, but not with `bpf` target.

- The default target may turn a C switch statement into a switch table lookup and jump operation. Since the switch table is placed in the global readonly section, the bpf program will fail to load. The bpf target does not support switch table optimization. The clang option `-fno-jump-tables` can be used to disable switch table generation.

- For clang `--target=bpf`, it is guaranteed that pointer or long / unsigned long types will always have a width of 64 bit, no matter whether underlying clang binary or default target (or kernel) is 32 bit. However, when native clang target is used, then it will compile these types based on the underlying architecture's conventions, meaning in case of 32 bit architecture, pointer or long / unsigned long types e.g. in BPF context structure will have width of 32 bit while the BPF LLVM back end still operates in 64 bit. The native target is mostly needed in tracing for the case of walking `pt_regs` or other kernel structures where CPU's register width matters. Otherwise, `clang --target=bpf` is generally recommended.

You should use default target when:

- Your program includes a header file, e.g., ptrace.h, which eventually pulls in some header files containing file scope host assembly codes.

- You can add `-fno-jump-tables` to work around the switch table issue.

Otherwise, you can use `bpf` target. Additionally, you *must* use bpf target when:

- Your program uses data structures with pointer or long / unsigned long types that interface with BPF helpers or context data structures. Access into these structures is verified by the BPF verifier and may result in verification failures if the native architecture is not aligned with the BPF architecture, e.g. 64-bit. An example of this is BPF_PROG_TYPE_SK_MSG require `--target=bpf`

<!-- Links -->

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



Happy BPF hacking\!

---

# BPF Iterators

_Peios Kernel / Internals / BPF_

> BPF supports two separate entities collectively known as "BPF iterators": BPF iterator program type and open-coded BPF iterators. The former is a stand-alone BPF program type which, when attached and activated by user, will be called once…

<a id="rst-bpf-iterators"></a>

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

## Overview

BPF supports two separate entities collectively known as "BPF iterators": BPF iterator *program type* and *open-coded* BPF iterators. The former is a stand-alone BPF program type which, when attached and activated by user, will be called once for each entity (task_struct, cgroup, etc) that is being iterated. The latter is a set of BPF-side APIs implementing iterator functionality and available across multiple BPF program types. Open-coded iterators provide similar functionality to BPF iterator programs, but gives more flexibility and control to all other BPF program types. BPF iterator programs, on the other hand, can be used to implement anonymous or BPF FS-mounted special files, whose contents are generated by attached BPF iterator program, backed by seq_file functionality. Both are useful depending on specific needs.

When adding a new BPF iterator program, it is expected that similar functionality will be added as open-coded iterator for maximum flexibility. It's also expected that iteration logic and code will be maximally shared and reused between two iterator API surfaces.

<a id="rst-open-coded-bpf-iterators"></a>

## Open-coded BPF Iterators

Open-coded BPF iterators are implemented as tightly-coupled trios of kfuncs (constructor, next element fetch, destructor) and iterator-specific type describing on-the-stack iterator state, which is guaranteed by the BPF verifier to not be tampered with outside of the corresponding constructor/destructor/next APIs.

Each kind of open-coded BPF iterator has its own associated struct bpf_iter\_&lt;type&gt;, where &lt;type&gt; denotes a specific type of iterator. bpf_iter\_&lt;type&gt; state needs to live on BPF program stack, so make sure it's small enough to fit on BPF stack. For performance reasons its best to avoid dynamic memory allocation for iterator state and size the state struct big enough to fit everything necessary. But if necessary, dynamic memory allocation is a way to bypass BPF stack limitations. Note, state struct size is part of iterator's user-visible API, so changing it will break backwards compatibility, so be deliberate about designing it.

All kfuncs (constructor, next, destructor) have to be named consistently as bpf_iter\_&lt;type&gt;\_\{new,next,destroy\}(), respectively. &lt;type&gt; represents iterator type, and iterator state should be represented as a matching `struct bpf_iter_<type>` state type. Also, all iter kfuncs should have a pointer to this `struct bpf_iter_<type>` as the very first argument.

- **Additionally:**

  - Constructor, i.e., `bpf_iter_<type>_new()`, can have arbitrary extra number of arguments. Return type is not enforced either.

  - Next method, i.e., `bpf_iter_<type>_next()`, has to return a pointer type and should have exactly one argument: `struct bpf_iter_<type> *` (const/volatile/restrict and typedefs are ignored).

  - Destructor, i.e., `bpf_iter_<type>_destroy()`, should return void and should have exactly one argument, similar to the next method.

  - `struct bpf_iter_<type>` size is enforced to be positive and a multiple of 8 bytes (to fit stack slots correctly).

Such strictness and consistency allows to build generic helpers abstracting important, but boilerplate, details to be able to use open-coded iterators effectively and ergonomically (see libbpf's bpf_for_each() macro). This is enforced at kfunc registration point by the kernel.

- **Constructor/next/destructor implementation contract is as follows:**

  - constructor, `bpf_iter_<type>_new()`, always initializes iterator state on the stack. If any of the input arguments are invalid, constructor should make sure to still initialize it such that subsequent next() calls will return NULL. I.e., on error, *return error and construct empty iterator*. Constructor kfunc is marked with KF_ITER_NEW flag.

  - next method, `bpf_iter_<type>_next()`, accepts pointer to iterator state and produces an element. Next method should always return a pointer. The contract between BPF verifier is that next method *guarantees* that it will eventually return NULL when elements are exhausted. Once NULL is returned, subsequent next calls *should keep returning NULL*. Next method is marked with KF_ITER_NEXT (and should also have KF_RET_NULL as NULL-returning kfunc, of course).

  - destructor, `bpf_iter_<type>_destroy()`, is always called once. Even if constructor failed or next returned nothing.  Destructor frees up any resources and marks stack space used by `struct bpf_iter_<type>` as usable for something else. Destructor is marked with KF_ITER_DESTROY flag.

Any open-coded BPF iterator implementation has to implement at least these three methods. It is enforced that for any given type of iterator only applicable constructor/destructor/next are callable. I.e., verifier ensures you can't pass number iterator state into, say, cgroup iterator's next method.

From a 10,000-feet BPF verification point of view, next methods are the points of forking a verification state, which are conceptually similar to what verifier is doing when validating conditional jumps. Verifier is branching out `call bpf_iter_<type>_next` instruction and simulates two outcomes: NULL (iteration is done) and non-NULL (new element is returned). NULL is simulated first and is supposed to reach exit without looping. After that non-NULL case is validated and it either reaches exit (for trivial examples with no real loop), or reaches another `call bpf_iter_<type>_next` instruction with the state equivalent to already (partially) validated one. State equivalency at that point means we technically are going to be looping forever without "breaking out" out of established "state envelope" (i.e., subsequent iterations don't add any new knowledge or constraints to the verifier state, so running 1, 2, 10, or a million of them doesn't matter). But taking into account the contract stating that iterator next method *has to* return NULL eventually, we can conclude that loop body is safe and will eventually terminate. Given we validated logic outside of the loop (NULL case), and concluded that loop body is safe (though potentially looping many times), verifier can claim safety of the overall program logic.

<a id="rst-bpf-iterators-motivation"></a>

## BPF Iterators Motivation

There are a few existing ways to dump kernel data into user space. The most popular one is the `/proc` system. For example, `cat /proc/net/tcp6` dumps all tcp6 sockets in the system, and `cat /proc/net/netlink` dumps all netlink sockets in the system. However, their output format tends to be fixed, and if users want more information about these sockets, they have to patch the kernel, which often takes time to publish upstream and release. The same is true for popular tools like [ss](<https://man7.org/linux/man-pages/man8/ss.8.html>)<a id="rst-ss"></a> where any additional information needs a kernel patch.

To solve this problem, the [drgn](<https://www.kernel.org/doc/html/latest/bpf/drgn.html>)<a id="rst-drgn"></a> tool is often used to dig out the kernel data with no kernel change. However, the main drawback for drgn is performance, as it cannot do pointer tracing inside the kernel. In addition, drgn cannot validate a pointer value and may read invalid data if the pointer becomes invalid inside the kernel.

The BPF iterator solves the above problem by providing flexibility on what data (e.g., tasks, bpf_maps, etc.) to collect by calling BPF programs for each kernel data object.

<a id="rst-how-bpf-iterators-work"></a>

## How BPF Iterators Work

A BPF iterator is a type of BPF program that allows users to iterate over specific types of kernel objects. Unlike traditional BPF tracing programs that allow users to define callbacks that are invoked at particular points of execution in the kernel, BPF iterators allow users to define callbacks that should be executed for every entry in a variety of kernel data structures.

For example, users can define a BPF iterator that iterates over every task on the system and dumps the total amount of CPU runtime currently used by each of them. Another BPF task iterator may instead dump the cgroup information for each task. Such flexibility is the core value of BPF iterators.

A BPF program is always loaded into the kernel at the behest of a user space process. A user space process loads a BPF program by opening and initializing the program skeleton as required and then invoking a syscall to have the BPF program verified and loaded by the kernel.

In traditional tracing programs, a program is activated by having user space obtain a `bpf_link` to the program with `bpf_program__attach()`. Once activated, the program callback will be invoked whenever the tracepoint is triggered in the main kernel. For BPF iterator programs, a `bpf_link` to the program is obtained using `bpf_link_create()`, and the program callback is invoked by issuing system calls from user space.

Next, let us see how you can use the iterators to iterate on kernel objects and read data.

<a id="rst-how-to-use-bpf-iterators"></a>

## How to Use BPF iterators

BPF selftests are a great resource to illustrate how to use the iterators. In this section, we’ll walk through a BPF selftest which shows how to load and use a BPF iterator program.   To begin, we’ll look at [bpf_iter.c](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/prog_tests/bpf_iter.c>)<a id="rst-bpf-iter-c"></a>, which illustrates how to load and trigger BPF iterators on the user space side. Later, we’ll look at a BPF program that runs in kernel space.

Loading a BPF iterator in the kernel from user space typically involves the following steps:

- The BPF program is loaded into the kernel through `libbpf`. Once the kernel has verified and loaded the program, it returns a file descriptor (fd) to user space.

- Obtain a `link_fd` to the BPF program by calling the `bpf_link_create()` specified with the BPF program file descriptor received from the kernel.

- Next, obtain a BPF iterator file descriptor (`bpf_iter_fd`) by calling the `bpf_iter_create()` specified with the `bpf_link` received from Step 2.

- Trigger the iteration by calling `read(bpf_iter_fd)` until no data is available.

- Close the iterator fd using `close(bpf_iter_fd)`.

- If needed to reread the data, get a new `bpf_iter_fd` and do the read again.

The following are a few examples of selftest BPF iterator programs:

- [bpf_iter_tcp4.c](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/progs/bpf_iter_tcp4.c>)<a id="rst-bpf-iter-tcp4-c"></a>

- [bpf_iter_task_vmas.c](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/progs/bpf_iter_task_vmas.c>)<a id="rst-bpf-iter-task-vmas-c"></a>

- [bpf_iter_task_file.c](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/tools/testing/selftests/bpf/progs/bpf_iter_task_file.c>)<a id="rst-bpf-iter-task-file-c"></a>

Let us look at `bpf_iter_task_file.c`, which runs in kernel space:

Here is the definition of `bpf_iter__task_file` in [vmlinux.h](<https://facebookmicrosites.github.io/bpf/blog/2020/02/19/bpf-portability-and-co-re.html#btf>)<a id="rst-vmlinux-h"></a>. Any struct name in `vmlinux.h` in the format `bpf_iter__<iter_name>` represents a BPF iterator. The suffix `<iter_name>` represents the type of iterator.



```text
struct bpf_iter__task_file {
        union {
            struct bpf_iter_meta *meta;
        };
        union {
            struct task_struct *task;
        };
        u32 fd;
        union {
            struct file *file;
        };
};
```

In the above code, the field 'meta' contains the metadata, which is the same for all BPF iterator programs. The rest of the fields are specific to different iterators. For example, for task_file iterators, the kernel layer provides the 'task', 'fd' and 'file' field values. The 'task' and 'file' are [reference counted](<https://facebookmicrosites.github.io/bpf/blog/2018/08/31/object-lifetime.html#file-descriptors-and-reference-counters>)<a id="rst-reference-counted"></a>, so they won't go away when the BPF program runs.

Here is a snippet from the  `bpf_iter_task_file.c` file:



```text
SEC("iter/task_file")
int dump_task_file(struct bpf_iter__task_file *ctx)
{
  struct seq_file *seq = ctx->meta->seq;
  struct task_struct *task = ctx->task;
  struct file *file = ctx->file;
  __u32 fd = ctx->fd;

  if (task == NULL || file == NULL)
    return 0;

  if (ctx->meta->seq_num == 0) {
    count = 0;
    BPF_SEQ_PRINTF(seq, "    tgid      gid       fd      file\n");
  }

  if (tgid == task->tgid && task->tgid != task->pid)
    count++;

  if (last_tgid != task->tgid) {
    last_tgid = task->tgid;
    unique_tgid_count++;
  }

  BPF_SEQ_PRINTF(seq, "%8d %8d %8d %lx\n", task->tgid, task->pid, fd,
          (long)file->f_op);
  return 0;
}
```

In the above example, the section name `SEC(iter/task_file)`, indicates that the program is a BPF iterator program to iterate all files from all tasks. The context of the program is `bpf_iter__task_file` struct.

The user space program invokes the BPF iterator program running in the kernel by issuing a `read()` syscall. Once invoked, the BPF program can export data to user space using a variety of BPF helper functions. You can use either `bpf_seq_printf()` (and BPF_SEQ_PRINTF helper macro) or `bpf_seq_write()` function based on whether you need formatted output or just binary data, respectively. For binary-encoded data, the user space applications can process the data from `bpf_seq_write()` as needed. For the formatted data, you can use `cat <path>` to print the results similar to `cat /proc/net/netlink` after pinning the BPF iterator to the bpffs mount. Later, use  `rm -f <path>` to remove the pinned iterator.

For example, you can use the following command to create a BPF iterator from the `bpf_iter_ipv6_route.o` object file and pin it to the `/sys/fs/bpf/my_route` path:



```text
$ bpftool iter pin ./bpf_iter_ipv6_route.o  /sys/fs/bpf/my_route
```

And then print out the results using the following command:



```text
$ cat /sys/fs/bpf/my_route
```

<a id="rst-implement-kernel-support-for-bpf-iterator-program-types"></a>

## Implement Kernel Support for BPF Iterator Program Types

To implement a BPF iterator in the kernel, the developer must make a one-time change to the following key data structure defined in the [bpf.h](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/tree/include/linux/bpf.h>)<a id="rst-bpf-h"></a> file.



```text
struct bpf_iter_reg {
          const char *target;
          bpf_iter_attach_target_t attach_target;
          bpf_iter_detach_target_t detach_target;
          bpf_iter_show_fdinfo_t show_fdinfo;
          bpf_iter_fill_link_info_t fill_link_info;
          bpf_iter_get_func_proto_t get_func_proto;
          u32 ctx_arg_info_size;
          u32 feature;
          struct bpf_ctx_arg_aux ctx_arg_info[BPF_ITER_CTX_ARG_MAX];
          const struct bpf_iter_seq_info *seq_info;
};
```

After filling the data structure fields, call `bpf_iter_reg_target()` to register the iterator to the main BPF iterator subsystem.

The following is the breakdown for each field in struct `bpf_iter_reg`.


<table>
<thead>
<tr>
<th>


Fields

</th>
<th>


Description

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


target

</td>
<td>


Specifies the name of the BPF iterator. For example: `bpf_map`, `bpf_map_elem`. The name should be different from other `bpf_iter` target names in the kernel.

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


attach_target and detach_target

</td>
<td>


Allows for target specific `link_create` action since some targets may need special processing. Called during the user space link_create stage.

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


show_fdinfo and fill_link_info

</td>
<td>


Called to fill target specific information when user tries to get link info associated with the iterator.

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


get_func_proto

</td>
<td>


Permits a BPF iterator to access BPF helpers specific to the iterator.

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


ctx_arg_info_size and ctx_arg_info

</td>
<td>


Specifies the verifier states for BPF program arguments associated with the bpf iterator.

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


feature

</td>
<td>


Specifies certain action requests in the kernel BPF iterator infrastructure. Currently, only BPF_ITER_RESCHED is supported. This means that the kernel function cond_resched() is called to avoid other kernel subsystem (e.g., rcu) misbehaving.

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


seq_info

</td>
<td>


Specifies the set of seq operations for the BPF iterator and helpers to initialize/free the private data for the corresponding `seq_file`.

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

[Click here](<https://lore.kernel.org/bpf/20210212183107.50963-2-songliubraving@fb.com/>)<a id="rst-click-here"></a> to see an implementation of the `task_vma` BPF iterator in the kernel.

<a id="rst-parameterizing-bpf-task-iterators"></a>

## Parameterizing BPF Task Iterators

By default, BPF iterators walk through all the objects of the specified types (processes, cgroups, maps, etc.) across the entire system to read relevant kernel data. But often, there are cases where we only care about a much smaller subset of iterable kernel objects, such as only iterating tasks within a specific process. Therefore, BPF iterator programs support filtering out objects from iteration by allowing user space to configure the iterator program when it is attached.

<a id="rst-bpf-task-iterator-program"></a>

## BPF Task Iterator Program

The following code is a BPF iterator program to print files and task information through the `seq_file` of the iterator. It is a standard BPF iterator program that visits every file of an iterator. We will use this BPF program in our example later.



```text
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>

char _license[] SEC("license") = "GPL";

SEC("iter/task_file")
int dump_task_file(struct bpf_iter__task_file *ctx)
{
      struct seq_file *seq = ctx->meta->seq;
      struct task_struct *task = ctx->task;
      struct file *file = ctx->file;
      __u32 fd = ctx->fd;
      if (task == NULL || file == NULL)
              return 0;
      if (ctx->meta->seq_num == 0) {
              BPF_SEQ_PRINTF(seq, "    tgid      pid       fd      file\n");
      }
      BPF_SEQ_PRINTF(seq, "%8d %8d %8d %lx\n", task->tgid, task->pid, fd,
                      (long)file->f_op);
      return 0;
}
```

<a id="rst-creating-a-file-iterator-with-parameters"></a>

## Creating a File Iterator with Parameters

Now, let us look at how to create an iterator that includes only files of a process.

First,  fill the `bpf_iter_attach_opts` struct as shown below:



```text
LIBBPF_OPTS(bpf_iter_attach_opts, opts);
union bpf_iter_link_info linfo;
memset(&linfo, 0, sizeof(linfo));
linfo.task.pid = getpid();
opts.link_info = &linfo;
opts.link_info_len = sizeof(linfo);
```

`linfo.task.pid`, if it is non-zero, directs the kernel to create an iterator that only includes opened files for the process with the specified `pid`. In this example, we will only be iterating files for our process. If `linfo.task.pid` is zero, the iterator will visit every opened file of every process. Similarly, `linfo.task.tid` directs the kernel to create an iterator that visits opened files of a specific thread, not a process. In this example, `linfo.task.tid` is different from `linfo.task.pid` only if the thread has a separate file descriptor table. In most circumstances, all process threads share a single file descriptor table.

Now, in the userspace program, pass the pointer of struct to the `bpf_program__attach_iter()`.



```text
link = bpf_program__attach_iter(prog, &opts);
iter_fd = bpf_iter_create(bpf_link__fd(link));
```

If both *tid* and *pid* are zero, an iterator created from this struct `bpf_iter_attach_opts` will include every opened file of every task in the system (in the namespace, actually.) It is the same as passing a NULL as the second argument to `bpf_program__attach_iter()`.

The whole program looks like the following code:



```text
#include <stdio.h>
#include <unistd.h>
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include "bpf_iter_task_ex.skel.h"

static int do_read_opts(struct bpf_program *prog, struct bpf_iter_attach_opts *opts)
{
      struct bpf_link *link;
      char buf[16] = {};
      int iter_fd = -1, len;
      int ret = 0;

      link = bpf_program__attach_iter(prog, opts);
      if (!link) {
              fprintf(stderr, "bpf_program__attach_iter() fails\n");
              return -1;
      }
      iter_fd = bpf_iter_create(bpf_link__fd(link));
      if (iter_fd < 0) {
              fprintf(stderr, "bpf_iter_create() fails\n");
              ret = -1;
              goto free_link;
      }
      /* not check contents, but ensure read() ends without error */
      while ((len = read(iter_fd, buf, sizeof(buf) - 1)) > 0) {
              buf[len] = 0;
              printf("%s", buf);
      }
      printf("\n");
free_link:
      if (iter_fd >= 0)
              close(iter_fd);
      bpf_link__destroy(link);
      return 0;
}

static void test_task_file(void)
{
      LIBBPF_OPTS(bpf_iter_attach_opts, opts);
      struct bpf_iter_task_ex *skel;
      union bpf_iter_link_info linfo;
      skel = bpf_iter_task_ex__open_and_load();
      if (skel == NULL)
              return;
      memset(&linfo, 0, sizeof(linfo));
      linfo.task.pid = getpid();
      opts.link_info = &linfo;
      opts.link_info_len = sizeof(linfo);
      printf("PID %d\n", getpid());
      do_read_opts(skel->progs.dump_task_file, &opts);
      bpf_iter_task_ex__destroy(skel);
}

int main(int argc, const char * const * argv)
{
      test_task_file();
      return 0;
}
```

The following lines are the output of the program.



```text
PID 1859

   tgid      pid       fd      file
   1859     1859        0 ffffffff82270aa0
   1859     1859        1 ffffffff82270aa0
   1859     1859        2 ffffffff82270aa0
   1859     1859        3 ffffffff82272980
   1859     1859        4 ffffffff8225e120
   1859     1859        5 ffffffff82255120
   1859     1859        6 ffffffff82254f00
   1859     1859        7 ffffffff82254d80
   1859     1859        8 ffffffff8225abe0
```

<a id="rst-without-parameters"></a>

## Without Parameters

Let us look at how a BPF iterator without parameters skips files of other processes in the system. In this case, the BPF program has to check the pid or the tid of tasks, or it will receive every opened file in the system (in the current *pid* namespace, actually). So, we usually add a global variable in the BPF program to pass a *pid* to the BPF program.

The BPF program would look like the following block.

>
>
> ```text
> ......
> int target_pid = 0;
>
> SEC("iter/task_file")
> int dump_task_file(struct bpf_iter__task_file *ctx)
> {
>       ......
>       if (task->tgid != target_pid) /* Check task->pid instead to check thread IDs */
>               return 0;
>       BPF_SEQ_PRINTF(seq, "%8d %8d %8d %lx\n", task->tgid, task->pid, fd,
>                       (long)file->f_op);
>       return 0;
> }
> ```

The user space program would look like the following block:

>
>
> ```text
> ......
> static void test_task_file(void)
> {
>       ......
>       skel = bpf_iter_task_ex__open_and_load();
>       if (skel == NULL)
>               return;
>       skel->bss->target_pid = getpid(); /* process ID.  For thread id, use gettid() */
>       memset(&linfo, 0, sizeof(linfo));
>       linfo.task.pid = getpid();
>       opts.link_info = &linfo;
>       opts.link_info_len = sizeof(linfo);
>       ......
> }
> ```

`target_pid` is a global variable in the BPF program. The user space program should initialize the variable with a process ID to skip opened files of other processes in the BPF program. When you parametrize a BPF iterator, the iterator calls the BPF program fewer times which can save significant resources.

<a id="rst-parametrizing-vma-iterators"></a>

## Parametrizing VMA Iterators

By default, a BPF VMA iterator includes every VMA in every process.  However, you can still specify a process or a thread to include only its VMAs. Unlike files, a thread can not have a separate address space (since Linux 2.6.0-test6). Here, using *tid* makes no difference from using *pid*.

<a id="rst-parametrizing-task-iterators"></a>

## Parametrizing Task Iterators

A BPF task iterator with *pid* includes all tasks (threads) of a process. The BPF program receives these tasks one after another. You can specify a BPF task iterator with *tid* parameter to include only the tasks that match the given *tid*.

---

# BPF licensing

_Peios Kernel / Internals / BPF_

> Classic BPF was BSD licensed

<a id="rst-bpf-licensing"></a>

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

## Background

- Classic BPF was BSD licensed

"BPF" was originally introduced as BSD Packet Filter in [http://www.tcpdump.org/papers/bpf-usenix93.pdf](<http://www.tcpdump.org/papers/bpf-usenix93.pdf>). The corresponding instruction set and its implementation came from BSD with BSD license. That original instruction set is now known as "classic BPF".

However an instruction set is a specification for machine-language interaction, similar to a programming language.  It is not a code. Therefore, the application of a BSD license may be misleading in a certain context, as the instruction set may enjoy no copyright protection.

- eBPF (extended BPF) instruction set continues to be BSD

In 2014, the classic BPF instruction set was significantly extended. We typically refer to this instruction set as eBPF to disambiguate it from cBPF. The eBPF instruction set is still BSD licensed.

<a id="rst-implementations-of-ebpf"></a>

## Implementations of eBPF

Using the eBPF instruction set requires implementing code in both kernel space and user space.

<a id="rst-in-linux-kernel"></a>

### In Linux Kernel

The reference implementations of the eBPF interpreter and various just-in-time compilers are part of Linux and are GPLv2 licensed. The implementation of eBPF helper functions is also GPLv2 licensed. Interpreters, JITs, helpers, and verifiers are called eBPF runtime.

<a id="rst-in-user-space"></a>

### In User Space

There are also implementations of eBPF runtime (interpreter, JITs, helper functions) under Apache2 ([https://github.com/iovisor/ubpf](<https://github.com/iovisor/ubpf>)), MIT ([https://github.com/qmonnet/rbpf](<https://github.com/qmonnet/rbpf>)), and BSD ([https://github.com/DPDK/dpdk/blob/main/lib/librte_bpf](<https://github.com/DPDK/dpdk/blob/main/lib/librte_bpf>)).

<a id="rst-in-hw"></a>

### In HW

The HW can choose to execute eBPF instruction natively and provide eBPF runtime in HW or via the use of implementing firmware with a proprietary license.

<a id="rst-in-other-operating-systems"></a>

### In other operating systems

Other kernels or user space implementations of eBPF instruction set and runtime can have proprietary licenses.

<a id="rst-using-bpf-programs-in-the-linux-kernel"></a>

## Using BPF programs in the Linux kernel

Linux Kernel (while being GPLv2) allows linking of proprietary kernel modules under these rules: [Documentation/process/license-rules.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/license-rules.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)

When a kernel module is loaded, the linux kernel checks which functions it intends to use. If any function is marked as "GPL only," the corresponding module or program has to have GPL compatible license.

Loading BPF program into the Linux kernel is similar to loading a kernel module. BPF is loaded at run time and not statically linked to the Linux kernel. BPF program loading follows the same license checking rules as kernel modules. BPF programs can be proprietary if they don't use "GPL only" BPF helper functions.

Further, some BPF program types - Linux Security Modules (LSM) and TCP Congestion Control (struct_ops), as of Aug 2021 - are required to be GPL compatible even if they don't use "GPL only" helper functions directly. The registration step of LSM and TCP congestion control modules of the Linux kernel is done through EXPORT_SYMBOL_GPL kernel functions. In that sense LSM and struct_ops BPF programs are implicitly calling "GPL only" functions. The same restriction applies to BPF programs that call kernel functions directly via unstable interface also known as "kfunc".

<a id="rst-packaging-bpf-programs-with-user-space-applications"></a>

## Packaging BPF programs with user space applications

Generally, proprietary-licensed applications and GPL licensed BPF programs written for the Linux kernel in the same package can co-exist because they are separate executable processes. This applies to both cBPF and eBPF programs.

---

# Running BPF programs from userspace

_Peios Kernel / Internals / BPF_

> This document describes the BPF_PROG_RUN facility for running BPF programs from userspace.

<a id="rst-running-bpf-programs-from-userspace"></a>

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

This document describes the `BPF_PROG_RUN` facility for running BPF programs from userspace.

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



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

## Overview

The `BPF_PROG_RUN` command can be used through the `bpf()` syscall to execute a BPF program in the kernel and return the results to userspace. This can be used to unit test BPF programs against user-supplied context objects, and as way to explicitly execute programs in the kernel for their side effects. The command was previously named `BPF_PROG_TEST_RUN`, and both constants continue to be defined in the UAPI header, aliased to the same value.

The `BPF_PROG_RUN` command can be used to execute BPF programs of the following types:

- `BPF_PROG_TYPE_SOCKET_FILTER`

- `BPF_PROG_TYPE_SCHED_CLS`

- `BPF_PROG_TYPE_SCHED_ACT`

- `BPF_PROG_TYPE_XDP`

- `BPF_PROG_TYPE_SK_LOOKUP`

- `BPF_PROG_TYPE_CGROUP_SKB`

- `BPF_PROG_TYPE_LWT_IN`

- `BPF_PROG_TYPE_LWT_OUT`

- `BPF_PROG_TYPE_LWT_XMIT`

- `BPF_PROG_TYPE_FLOW_DISSECTOR`

- `BPF_PROG_TYPE_STRUCT_OPS`

- `BPF_PROG_TYPE_RAW_TRACEPOINT`

- `BPF_PROG_TYPE_SYSCALL`

- `BPF_PROG_TYPE_TRACING`

- `BPF_PROG_TYPE_NETFILTER`

When using the `BPF_PROG_RUN` command, userspace supplies an input context object and (for program types operating on network packets) a buffer containing the packet data that the BPF program will operate on. The kernel will then execute the program and return the results to userspace. Note that programs will not have any side effects while being run in this mode; in particular, packets will not actually be redirected or dropped, the program return code will just be returned to userspace. A separate mode for live execution of XDP programs is provided, documented separately below.

<a id="rst-running-xdp-programs-in-live-frame-mode"></a>

## Running XDP programs in "live frame mode"

The `BPF_PROG_RUN` command has a separate mode for running live XDP programs, which can be used to execute XDP programs in a way where packets will actually be processed by the kernel after the execution of the XDP program as if they arrived on a physical interface. This mode is activated by setting the `BPF_F_TEST_XDP_LIVE_FRAMES` flag when supplying an XDP program to `BPF_PROG_RUN`.

The live packet mode is optimised for high performance execution of the supplied XDP program many times (suitable for, e.g., running as a traffic generator), which means the semantics are not quite as straight-forward as the regular test run mode. Specifically:

- When executing an XDP program in live frame mode, the result of the execution will not be returned to userspace; instead, the kernel will perform the operation indicated by the program's return code (drop the packet, redirect it, etc). For this reason, setting the `data_out` or `ctx_out` attributes in the syscall parameters when running in this mode will be rejected. In addition, not all failures will be reported back to userspace directly; specifically, only fatal errors in setup or during execution (like memory allocation errors) will halt execution and return an error. If an error occurs in packet processing, like a failure to redirect to a given interface, execution will continue with the next repetition; these errors can be detected via the same trace points as for regular XDP programs.

- Userspace can supply an ifindex as part of the context object, just like in the regular (non-live) mode. The XDP program will be executed as though the packet arrived on this interface; i.e., the `ingress_ifindex` of the context object will point to that interface. Furthermore, if the XDP program returns `XDP_PASS`, the packet will be injected into the kernel networking stack as though it arrived on that ifindex, and if it returns `XDP_TX`, the packet will be transmitted *out* of that same interface. Do note, though, that because the program execution is not happening in driver context, an `XDP_TX` is actually turned into the same action as an `XDP_REDIRECT` to that same interface (i.e., it will only work if the driver has support for the `ndo_xdp_xmit` driver op).

- When running the program with multiple repetitions, the execution will happen in batches. The batch size defaults to 64 packets (which is same as the maximum NAPI receive batch size), but can be specified by userspace through the `batch_size` parameter, up to a maximum of 256 packets. For each batch, the kernel executes the XDP program repeatedly, each invocation getting a separate copy of the packet data. For each repetition, if the program drops the packet, the data page is immediately recycled (see below). Otherwise, the packet is buffered until the end of the batch, at which point all packets buffered this way during the batch are transmitted at once.

- When setting up the test run, the kernel will initialise a pool of memory pages of the same size as the batch size. Each memory page will be initialised with the initial packet data supplied by userspace at `BPF_PROG_RUN` invocation. When possible, the pages will be recycled on future program invocations, to improve performance. Pages will generally be recycled a full batch at a time, except when a packet is dropped (by return code or because of, say, a redirection error), in which case that page will be recycled immediately. If a packet ends up being passed to the regular networking stack (because the XDP program returns `XDP_PASS`, or because it ends up being redirected to an interface that injects it into the stack), the page will be released and a new one will be allocated when the pool is empty.

  When recycling, the page content is not rewritten; only the packet boundary pointers (`data`, `data_end` and `data_meta`) in the context object will be reset to the original values. This means that if a program rewrites the packet contents, it has to be prepared to see either the original content or the modified version on subsequent invocations.

---

# BPF Type Format (BTF)

_Peios Kernel / Internals / BPF_

> BTF (BPF Type Format) is the metadata format which encodes the debug info related to BPF program/map. The name BTF was used initially to describe data types. The BTF was later extended to include function info for defined subroutines, and…

<a id="rst-bpf-type-format-btf"></a>

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

## 1. Introduction

BTF (BPF Type Format) is the metadata format which encodes the debug info related to BPF program/map. The name BTF was used initially to describe data types. The BTF was later extended to include function info for defined subroutines, and line info for source/line information.

The debug info is used for map pretty print, function signature, etc. The function signature enables better bpf program/function kernel symbol. The line info helps generate source annotated translated byte code, jited code and verifier log.

- **The BTF specification contains two parts,**

  - BTF kernel API

  - BTF ELF file format

The kernel API is the contract between user space and kernel. The kernel verifies the BTF info before using it. The ELF file format is a user space contract between ELF file and libbpf loader.

The type and string sections are part of the BTF kernel API, describing the debug info (mostly types related) referenced by the bpf program. These two sections are discussed in details in [2. BTF Type and String Encoding](<#rst-btf-type-string>).

<a id="rst-btf-type-and-string-encoding"></a>
<a id="rst-btf-type-string"></a>

## 2. BTF Type and String Encoding

The file `include/uapi/linux/btf.h` provides high-level definition of how types/strings are encoded.

The beginning of data blob must be:



```text
struct btf_header {
    __u16   magic;
    __u8    version;
    __u8    flags;
    __u32   hdr_len;

    /* All offsets are in bytes relative to the end of this header */
    __u32   type_off;       /* offset of type section       */
    __u32   type_len;       /* length of type section       */
    __u32   str_off;        /* offset of string section     */
    __u32   str_len;        /* length of string section     */
};
```

The magic is `0xeB9F`, which has different encoding for big and little endian systems, and can be used to test whether BTF is generated for big- or little-endian target. The `btf_header` is designed to be extensible with `hdr_len` equal to `sizeof(struct btf_header)` when a data blob is generated.

<a id="rst-string-encoding"></a>

### 2.1 String Encoding

The first string in the string section must be a null string. The rest of string table is a concatenation of other null-terminated strings.

<a id="rst-type-encoding"></a>

### 2.2 Type Encoding

The type id `0` is reserved for `void` type. The type section is parsed sequentially and type id is assigned to each recognized type starting from id `1`. Currently, the following types are supported:



```text
#define BTF_KIND_INT            1       /* Integer      */
#define BTF_KIND_PTR            2       /* Pointer      */
#define BTF_KIND_ARRAY          3       /* Array        */
#define BTF_KIND_STRUCT         4       /* Struct       */
#define BTF_KIND_UNION          5       /* Union        */
#define BTF_KIND_ENUM           6       /* Enumeration up to 32-bit values */
#define BTF_KIND_FWD            7       /* Forward      */
#define BTF_KIND_TYPEDEF        8       /* Typedef      */
#define BTF_KIND_VOLATILE       9       /* Volatile     */
#define BTF_KIND_CONST          10      /* Const        */
#define BTF_KIND_RESTRICT       11      /* Restrict     */
#define BTF_KIND_FUNC           12      /* Function     */
#define BTF_KIND_FUNC_PROTO     13      /* Function Proto       */
#define BTF_KIND_VAR            14      /* Variable     */
#define BTF_KIND_DATASEC        15      /* Section      */
#define BTF_KIND_FLOAT          16      /* Floating point       */
#define BTF_KIND_DECL_TAG       17      /* Decl Tag     */
#define BTF_KIND_TYPE_TAG       18      /* Type Tag     */
#define BTF_KIND_ENUM64         19      /* Enumeration up to 64-bit values */
```

Note that the type section encodes debug info, not just pure types. `BTF_KIND_FUNC` is not a type, and it represents a defined subprogram.

Each type contains the following common data:



```text
struct btf_type {
    __u32 name_off;
    /* "info" bits arrangement
     * bits  0-15: vlen (e.g. # of struct's members)
     * bits 16-23: unused
     * bits 24-28: kind (e.g. int, ptr, array...etc)
     * bits 29-30: unused
     * bit     31: kind_flag, currently used by
     *             struct, union, enum, fwd, enum64,
     *             decl_tag and type_tag
     */
    __u32 info;
    /* "size" is used by INT, ENUM, STRUCT, UNION and ENUM64.
     * "size" tells the size of the type it is describing.
     *
     * "type" is used by PTR, TYPEDEF, VOLATILE, CONST, RESTRICT,
     * FUNC, FUNC_PROTO, DECL_TAG and TYPE_TAG.
     * "type" is a type_id referring to another type.
     */
    union {
            __u32 size;
            __u32 type;
    };
};
```

For certain kinds, the common data are followed by kind-specific data. The `name_off` in `struct btf_type` specifies the offset in the string table. The following sections detail encoding of each kind.

<a id="rst-btf-kind-int"></a>

#### 2.2.1 BTF\_KIND\_INT

- **`struct btf_type` encoding requirement:**

  - `name_off`: any valid offset

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_INT

  - `info.vlen`: 0

  - `size`: the size of the int type in bytes.

`btf_type` is followed by a `u32` with the following bits arrangement:



```text
#define BTF_INT_ENCODING(VAL)   (((VAL) & 0x0f000000) >> 24)
#define BTF_INT_OFFSET(VAL)     (((VAL) & 0x00ff0000) >> 16)
#define BTF_INT_BITS(VAL)       ((VAL)  & 0x000000ff)
```

The `BTF_INT_ENCODING` has the following attributes:



```text
#define BTF_INT_SIGNED  (1 << 0)
#define BTF_INT_CHAR    (1 << 1)
#define BTF_INT_BOOL    (1 << 2)
```

The `BTF_INT_ENCODING()` provides extra information: signedness, char, or bool, for the int type. The char and bool encoding are mostly useful for pretty print. At most one encoding can be specified for the int type.

The `BTF_INT_BITS()` specifies the number of actual bits held by this int type. For example, a 4-bit bitfield encodes `BTF_INT_BITS()` equals to 4. The `btf_type.size * 8` must be equal to or greater than `BTF_INT_BITS()` for the type. The maximum value of `BTF_INT_BITS()` is 128.

The `BTF_INT_OFFSET()` specifies the starting bit offset to calculate values for this int. For example, a bitfield struct member has:

> - btf member bit offset 100 from the start of the structure,
>
> - btf member pointing to an int type,
>
> - the int type has `BTF_INT_OFFSET() = 2` and `BTF_INT_BITS() = 4`

Then in the struct memory layout, this member will occupy `4` bits starting from bits `100 + 2 = 102`.

Alternatively, the bitfield struct member can be the following to access the same bits as the above:

> - btf member bit offset 102,
>
> - btf member pointing to an int type,
>
> - the int type has `BTF_INT_OFFSET() = 0` and `BTF_INT_BITS() = 4`

The original intention of `BTF_INT_OFFSET()` is to provide flexibility of bitfield encoding. Currently, both llvm and pahole generate `BTF_INT_OFFSET() = 0` for all int types.

<a id="rst-btf-kind-ptr"></a>

#### 2.2.2 BTF\_KIND\_PTR

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_PTR

  - `info.vlen`: 0

  - `type`: the pointee type of the pointer

No additional type data follow `btf_type`.

<a id="rst-btf-kind-array"></a>

#### 2.2.3 BTF\_KIND\_ARRAY

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_ARRAY

  - `info.vlen`: 0

  - `size/type`: 0, not used

`btf_type` is followed by one `struct btf_array`:



```text
struct btf_array {
    __u32   type;
    __u32   index_type;
    __u32   nelems;
};
```

- **The `struct btf_array` encoding:**

  - `type`: the element type

  - `index_type`: the index type

  - `nelems`: the number of elements for this array (`0` is also allowed).

The `index_type` can be any regular int type (`u8`, `u16`, `u32`, `u64`, `unsigned __int128`). The original design of including `index_type` follows DWARF, which has an `index_type` for its array type. Currently in BTF, beyond type verification, the `index_type` is not used.

The `struct btf_array` allows chaining through element type to represent multidimensional arrays. For example, for `int a[5][6]`, the following type information illustrates the chaining:

> - \[1\]: int
>
> - \[2\]: array, `btf_array.type = [1]`, `btf_array.nelems = 6`
>
> - \[3\]: array, `btf_array.type = [2]`, `btf_array.nelems = 5`

Currently, both pahole and llvm collapse multidimensional array into one-dimensional array, e.g., for `a[5][6]`, the `btf_array.nelems` is equal to `30`. This is because the original use case is map pretty print where the whole array is dumped out so one-dimensional array is enough. As more BTF usage is explored, pahole and llvm can be changed to generate proper chained representation for multidimensional arrays.

<a id="rst-btf-kind-struct"></a>

#### 2.2.4 BTF\_KIND\_STRUCT

<a id="rst-btf-kind-union"></a>

#### 2.2.5 BTF\_KIND\_UNION

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0 or offset to a valid C identifier

  - `info.kind_flag`: 0 or 1

  - `info.kind`: BTF\_KIND\_STRUCT or BTF\_KIND\_UNION

  - `info.vlen`: the number of struct/union members

  - `info.size`: the size of the struct/union in bytes

`btf_type` is followed by `info.vlen` number of `struct btf_member`.:



```text
struct btf_member {
    __u32   name_off;
    __u32   type;
    __u32   offset;
};
```

- **`struct btf_member` encoding:**

  - `name_off`: offset to a valid C identifier

  - `type`: the member type

  - `offset`: &lt;see below&gt;

If the type info `kind_flag` is not set, the offset contains only bit offset of the member. Note that the base type of the bitfield can only be int or enum type. If the bitfield size is 32, the base type can be either int or enum type. If the bitfield size is not 32, the base type must be int, and int type `BTF_INT_BITS()` encodes the bitfield size.

If the `kind_flag` is set, the `btf_member.offset` contains both member bitfield size and bit offset. The bitfield size and bit offset are calculated as below.:



```text
#define BTF_MEMBER_BITFIELD_SIZE(val)   ((val) >> 24)
#define BTF_MEMBER_BIT_OFFSET(val)      ((val) & 0xffffff)
```

In this case, if the base type is an int type, it must be a regular int type:

> - `BTF_INT_OFFSET()` must be 0.
>
> - `BTF_INT_BITS()` must be equal to `{1,2,4,8,16} * 8`.

Commit 9d5f9f701b18 introduced `kind_flag` and explains why both modes exist.

<a id="rst-btf-kind-enum"></a>

#### 2.2.6 BTF\_KIND\_ENUM

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0 or offset to a valid C identifier

  - `info.kind_flag`: 0 for unsigned, 1 for signed

  - `info.kind`: BTF\_KIND\_ENUM

  - `info.vlen`: number of enum values

  - `size`: 1/2/4/8

`btf_type` is followed by `info.vlen` number of `struct btf_enum`.:



```text
struct btf_enum {
    __u32   name_off;
    __s32   val;
};
```

- **The `btf_enum` encoding:**

  - `name_off`: offset to a valid C identifier

  - `val`: any value

If the original enum value is signed and the size is less than 4, that value will be sign extended into 4 bytes. If the size is 8, the value will be truncated into 4 bytes.

<a id="rst-btf-kind-fwd"></a>

#### 2.2.7 BTF\_KIND\_FWD

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a valid C identifier

  - `info.kind_flag`: 0 for struct, 1 for union

  - `info.kind`: BTF\_KIND\_FWD

  - `info.vlen`: 0

  - `type`: 0

No additional type data follow `btf_type`.

<a id="rst-btf-kind-typedef"></a>

#### 2.2.8 BTF\_KIND\_TYPEDEF

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a valid C identifier

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_TYPEDEF

  - `info.vlen`: 0

  - `type`: the type which can be referred by name at `name_off`

No additional type data follow `btf_type`.

<a id="rst-btf-kind-volatile"></a>

#### 2.2.9 BTF\_KIND\_VOLATILE

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_VOLATILE

  - `info.vlen`: 0

  - `type`: the type with `volatile` qualifier

No additional type data follow `btf_type`.

<a id="rst-btf-kind-const"></a>

#### 2.2.10 BTF\_KIND\_CONST

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_CONST

  - `info.vlen`: 0

  - `type`: the type with `const` qualifier

No additional type data follow `btf_type`.

<a id="rst-btf-kind-restrict"></a>

#### 2.2.11 BTF\_KIND\_RESTRICT

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_RESTRICT

  - `info.vlen`: 0

  - `type`: the type with `restrict` qualifier

No additional type data follow `btf_type`.

<a id="rst-btf-kind-func"></a>

#### 2.2.12 BTF\_KIND\_FUNC

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a valid C identifier

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_FUNC

  - - **`info.vlen`: linkage information (BTF\_FUNC\_STATIC, BTF\_FUNC\_GLOBAL**

      or BTF\_FUNC\_EXTERN - see [2.3.1 Function Linkage Constant Values](<#rst-btf-function-linkage-constants>))

  - `type`: a BTF\_KIND\_FUNC\_PROTO type

No additional type data follow `btf_type`.

A BTF\_KIND\_FUNC defines not a type, but a subprogram (function) whose signature is defined by `type`. The subprogram is thus an instance of that type. The BTF\_KIND\_FUNC may in turn be referenced by a func\_info in the [4.2 .BTF.ext section](<#rst-btf-ext-section>) (ELF) or in the arguments to [3.3 BPF\_PROG\_LOAD](<#rst-bpf-prog-load>) (ABI).

Currently, only linkage values of BTF\_FUNC\_STATIC and BTF\_FUNC\_GLOBAL are supported in the kernel.

<a id="rst-btf-kind-func-proto"></a>

#### 2.2.13 BTF\_KIND\_FUNC\_PROTO

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_FUNC\_PROTO

  - `info.vlen`: \# of parameters

  - `type`: the return type

`btf_type` is followed by `info.vlen` number of `struct btf_param`.:



```text
struct btf_param {
    __u32   name_off;
    __u32   type;
};
```

If a BTF\_KIND\_FUNC\_PROTO type is referred by a BTF\_KIND\_FUNC type, then `btf_param.name_off` must point to a valid C identifier except for the possible last argument representing the variable argument. The btf\_param.type refers to parameter type.

If the function has variable arguments, the last parameter is encoded with `name_off = 0` and `type = 0`.

<a id="rst-btf-kind-var"></a>

#### 2.2.14 BTF\_KIND\_VAR

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a valid C identifier

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_VAR

  - `info.vlen`: 0

  - `type`: the type of the variable

`btf_type` is followed by a single `struct btf_variable` with the following data:



```text
struct btf_var {
    __u32   linkage;
};
```

`btf_var.linkage` may take the values: BTF\_VAR\_STATIC, BTF\_VAR\_GLOBAL\_ALLOCATED or BTF\_VAR\_GLOBAL\_EXTERN - see [2.3.2 Variable Linkage Constant Values](<#rst-btf-var-linkage-constants>).

Not all type of global variables are supported by LLVM at this point. The following is currently available:

> - static variables with or without section attributes
>
> - global variables with section attributes

The latter is for future extraction of map key/value type id's from a map definition.

<a id="rst-btf-kind-datasec"></a>

#### 2.2.15 BTF\_KIND\_DATASEC

- **`struct btf_type` encoding requirement:**

  - - **`name_off`: offset to a valid name associated with a variable or**

      one of .data/.bss/.rodata

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_DATASEC

  - `info.vlen`: \# of variables

  - - **`size`: total section size in bytes (0 at compilation time, patched**

      to actual size by BPF loaders such as libbpf)

`btf_type` is followed by `info.vlen` number of `struct btf_var_secinfo`.:



```text
struct btf_var_secinfo {
    __u32   type;
    __u32   offset;
    __u32   size;
};
```

- **`struct btf_var_secinfo` encoding:**

  - `type`: the type of the BTF\_KIND\_VAR variable

  - `offset`: the in-section offset of the variable

  - `size`: the size of the variable in bytes

<a id="rst-btf-kind-float"></a>

#### 2.2.16 BTF\_KIND\_FLOAT

- **`struct btf_type` encoding requirement:**

  - `name_off`: any valid offset

  - `info.kind_flag`: 0

  - `info.kind`: BTF\_KIND\_FLOAT

  - `info.vlen`: 0

  - `size`: the size of the float type in bytes: 2, 4, 8, 12 or 16.

No additional type data follow `btf_type`.

<a id="rst-btf-kind-decl-tag"></a>

#### 2.2.17 BTF\_KIND\_DECL\_TAG

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a non-empty string

  - `info.kind_flag`: 0 or 1

  - `info.kind`: BTF\_KIND\_DECL\_TAG

  - `info.vlen`: 0

  - `type`: `struct`, `union`, `func`, `var` or `typedef`

`btf_type` is followed by `struct btf_decl_tag`.:



```text
struct btf_decl_tag {
    __u32   component_idx;
};
```

The `type` should be `struct`, `union`, `func`, `var` or `typedef`. For `var` or `typedef` type, `btf_decl_tag.component_idx` must be `-1`. For the other three types, if the btf\_decl\_tag attribute is applied to the `struct`, `union` or `func` itself, `btf_decl_tag.component_idx` must be `-1`. Otherwise, the attribute is applied to a `struct`/`union` member or a `func` argument, and `btf_decl_tag.component_idx` should be a valid index (starting from 0) pointing to a member or an argument.

If `info.kind_flag` is 0, then this is a normal decl tag, and the `name_off` encodes btf\_decl\_tag attribute string.

If `info.kind_flag` is 1, then the decl tag represents an arbitrary \_\_attribute\_\_. In this case, `name_off` encodes a string representing the attribute-list of the attribute specifier. For example, for an `__attribute__((aligned(4)))` the string's contents is `aligned(4)`.

<a id="rst-btf-kind-type-tag"></a>

#### 2.2.18 BTF\_KIND\_TYPE\_TAG

- **`struct btf_type` encoding requirement:**

  - `name_off`: offset to a non-empty string

  - `info.kind_flag`: 0 or 1

  - `info.kind`: BTF\_KIND\_TYPE\_TAG

  - `info.vlen`: 0

  - `type`: the type with `btf_type_tag` attribute

Currently, `BTF_KIND_TYPE_TAG` is only emitted for pointer types. It has the following btf type chain:



```text
ptr -> [type_tag]*
    -> [const | volatile | restrict | typedef]*
    -> base_type
```

Basically, a pointer type points to zero or more type\_tag, then zero or more const/volatile/restrict/typedef and finally the base type. The base type is one of int, ptr, array, struct, union, enum, func\_proto and float types.

Similarly to decl tags, if the `info.kind_flag` is 0, then this is a normal type tag, and the `name_off` encodes btf\_type\_tag attribute string.

If `info.kind_flag` is 1, then the type tag represents an arbitrary \_\_attribute\_\_, and the `name_off` encodes a string representing the attribute-list of the attribute specifier.

<a id="rst-btf-kind-enum64"></a>

#### 2.2.19 BTF\_KIND\_ENUM64

- **`struct btf_type` encoding requirement:**

  - `name_off`: 0 or offset to a valid C identifier

  - `info.kind_flag`: 0 for unsigned, 1 for signed

  - `info.kind`: BTF\_KIND\_ENUM64

  - `info.vlen`: number of enum values

  - `size`: 1/2/4/8

`btf_type` is followed by `info.vlen` number of `struct btf_enum64`.:



```text
struct btf_enum64 {
    __u32   name_off;
    __u32   val_lo32;
    __u32   val_hi32;
};
```

- **The `btf_enum64` encoding:**

  - `name_off`: offset to a valid C identifier

  - `val_lo32`: lower 32-bit value for a 64-bit value

  - `val_hi32`: high 32-bit value for a 64-bit value

If the original enum value is signed and the size is less than 8, that value will be sign extended into 8 bytes.

<a id="rst-constant-values"></a>

### 2.3 Constant Values

<a id="rst-function-linkage-constant-values"></a>
<a id="rst-btf-function-linkage-constants"></a>

#### 2.3.1 Function Linkage Constant Values


<table>
<caption>Function Linkage Values and Meanings</caption>
<thead>
<tr>
<th>


kind

</th>
<th>


value

</th>
<th>


description

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


`BTF_FUNC_STATIC`

</td>
<td>


0x0

</td>
<td>


definition of subprogram not visible outside containing compilation unit

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


`BTF_FUNC_GLOBAL`

</td>
<td>


0x1

</td>
<td>


definition of subprogram visible outside containing compilation unit

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


`BTF_FUNC_EXTERN`

</td>
<td>


0x2

</td>
<td>


declaration of a subprogram whose definition is outside the containing compilation unit

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

<a id="rst-variable-linkage-constant-values"></a>
<a id="rst-btf-var-linkage-constants"></a>

#### 2.3.2 Variable Linkage Constant Values


<table>
<caption>Variable Linkage Values and Meanings</caption>
<thead>
<tr>
<th>


kind

</th>
<th>


value

</th>
<th>


description

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


`BTF_VAR_STATIC`

</td>
<td>


0x0

</td>
<td>


definition of global variable not visible outside containing compilation unit

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


`BTF_VAR_GLOBAL_ALLOCATED`

</td>
<td>


0x1

</td>
<td>


definition of global variable visible outside containing compilation unit

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


`BTF_VAR_GLOBAL_EXTERN`

</td>
<td>


0x2

</td>
<td>


declaration of global variable whose definition is outside the containing compilation unit

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

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

## 3. BTF Kernel API

- **The following bpf syscall command involves BTF:**

  - BPF\_BTF\_LOAD: load a blob of BTF data into kernel

  - BPF\_MAP\_CREATE: map creation with btf key and value type info.

  - BPF\_PROG\_LOAD: prog load with btf function and line info.

  - BPF\_BTF\_GET\_FD\_BY\_ID: get a btf fd

  - BPF\_OBJ\_GET\_INFO\_BY\_FD: btf, func\_info, line\_info and other btf related info are returned.

The workflow typically looks like:



```text
Application:
    BPF_BTF_LOAD
        |
        v
    BPF_MAP_CREATE and BPF_PROG_LOAD
        |
        V
    ......

Introspection tool:
    ......
    BPF_{PROG,MAP}_GET_NEXT_ID (get prog/map id's)
        |
        V
    BPF_{PROG,MAP}_GET_FD_BY_ID (get a prog/map fd)
        |
        V
    BPF_OBJ_GET_INFO_BY_FD (get bpf_prog_info/bpf_map_info with btf_id)
        |                                     |
        V                                     |
    BPF_BTF_GET_FD_BY_ID (get btf_fd)         |
        |                                     |
        V                                     |
    BPF_OBJ_GET_INFO_BY_FD (get btf)          |
        |                                     |
        V                                     V
    pretty print types, dump func signatures and line info, etc.
```

<a id="rst-bpf-btf-load"></a>

### 3.1 BPF\_BTF\_LOAD

Load a blob of BTF data into kernel. A blob of data, described in [2. BTF Type and String Encoding](<#rst-btf-type-string>), can be directly loaded into the kernel. A `btf_fd` is returned to a userspace.

<a id="rst-bpf-map-create"></a>

### 3.2 BPF\_MAP\_CREATE

A map can be created with `btf_fd` and specified key/value type id.:



```text
__u32   btf_fd;         /* fd pointing to a BTF type data */
__u32   btf_key_type_id;        /* BTF type_id of the key */
__u32   btf_value_type_id;      /* BTF type_id of the value */
```

In libbpf, the map can be defined with extra annotation like below:



```text
struct {
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __type(key, int);
    __type(value, struct ipv_counts);
    __uint(max_entries, 4);
} btf_map SEC(".maps");
```

During ELF parsing, libbpf is able to extract key/value type\_id's and assign them to BPF\_MAP\_CREATE attributes automatically.

<a id="rst-bpf-prog-load-1"></a>
<a id="rst-bpf-prog-load"></a>

### 3.3 BPF\_PROG\_LOAD

During prog\_load, func\_info and line\_info can be passed to kernel with proper values for the following attributes:



```text
__u32           insn_cnt;
__aligned_u64   insns;
......
__u32           prog_btf_fd;    /* fd pointing to BTF type data */
__u32           func_info_rec_size;     /* userspace bpf_func_info size */
__aligned_u64   func_info;      /* func info */
__u32           func_info_cnt;  /* number of bpf_func_info records */
__u32           line_info_rec_size;     /* userspace bpf_line_info size */
__aligned_u64   line_info;      /* line info */
__u32           line_info_cnt;  /* number of bpf_line_info records */
```

The func\_info and line\_info are an array of below, respectively.:



```text
struct bpf_func_info {
    __u32   insn_off; /* [0, insn_cnt - 1] */
    __u32   type_id;  /* pointing to a BTF_KIND_FUNC type */
};
struct bpf_line_info {
    __u32   insn_off; /* [0, insn_cnt - 1] */
    __u32   file_name_off; /* offset to string table for the filename */
    __u32   line_off; /* offset to string table for the source line */
    __u32   line_col; /* line number and column number */
};
```

func\_info\_rec\_size is the size of each func\_info record, and line\_info\_rec\_size is the size of each line\_info record. Passing the record size to kernel make it possible to extend the record itself in the future.

- **Below are requirements for func\_info:**

  - func\_info\[0\].insn\_off must be 0.

  - the func\_info insn\_off is in strictly increasing order and matches bpf func boundaries.

- **Below are requirements for line\_info:**

  - the first insn in each func must have a line\_info record pointing to it.

  - the line\_info insn\_off is in strictly increasing order.

For line\_info, the line number and column number are defined as below:



```text
#define BPF_LINE_INFO_LINE_NUM(line_col)        ((line_col) >> 10)
#define BPF_LINE_INFO_LINE_COL(line_col)        ((line_col) & 0x3ff)
```

<a id="rst-bpf-prog-map-get-next-id"></a>

### 3.4 BPF\_\{PROG,MAP\}\_GET\_NEXT\_ID

In kernel, every loaded program, map or btf has a unique id. The id won't change during the lifetime of a program, map, or btf.

The bpf syscall command BPF\_\{PROG,MAP\}\_GET\_NEXT\_ID returns all id's, one for each command, to user space, for bpf program or maps, respectively, so an inspection tool can inspect all programs and maps.

<a id="rst-bpf-prog-map-get-fd-by-id"></a>

### 3.5 BPF\_\{PROG,MAP\}\_GET\_FD\_BY\_ID

An introspection tool cannot use id to get details about program or maps. A file descriptor needs to be obtained first for reference-counting purpose.

<a id="rst-bpf-obj-get-info-by-fd"></a>

### 3.6 BPF\_OBJ\_GET\_INFO\_BY\_FD

Once a program/map fd is acquired, an introspection tool can get the detailed information from kernel about this fd, some of which are BTF-related. For example, `bpf_map_info` returns `btf_id` and key/value type ids. `bpf_prog_info` returns `btf_id`, func\_info, and line info for translated bpf byte codes, and jited\_line\_info.

<a id="rst-bpf-btf-get-fd-by-id"></a>

### 3.7 BPF\_BTF\_GET\_FD\_BY\_ID

With `btf_id` obtained in `bpf_map_info` and `bpf_prog_info`, bpf syscall command BPF\_BTF\_GET\_FD\_BY\_ID can retrieve a btf fd. Then, with command BPF\_OBJ\_GET\_INFO\_BY\_FD, the btf blob, originally loaded into the kernel with BPF\_BTF\_LOAD, can be retrieved.

With the btf blob, `bpf_map_info`, and `bpf_prog_info`, an introspection tool has full btf knowledge and is able to pretty print map key/values, dump func signatures and line info, along with byte/jit codes.

<a id="rst-elf-file-format-interface"></a>

## 4. ELF File Format Interface

<a id="rst-btf-section"></a>

### 4.1 .BTF section

The .BTF section contains type and string data. The format of this section is same as the one describe in [2. BTF Type and String Encoding](<#rst-btf-type-string>).

<a id="rst-btf-ext-section-1"></a>
<a id="rst-btf-ext-section"></a>

### 4.2 .BTF.ext section

The .BTF.ext section encodes func\_info, line\_info and CO-RE relocations which needs loader manipulation before loading into the kernel.

The specification for .BTF.ext section is defined at `tools/lib/bpf/btf.h` and `tools/lib/bpf/btf.c`.

The current header of .BTF.ext section:



```text
struct btf_ext_header {
    __u16   magic;
    __u8    version;
    __u8    flags;
    __u32   hdr_len;

    /* All offsets are in bytes relative to the end of this header */
    __u32   func_info_off;
    __u32   func_info_len;
    __u32   line_info_off;
    __u32   line_info_len;

    /* optional part of .BTF.ext header */
    __u32   core_relo_off;
    __u32   core_relo_len;
};
```

It is very similar to .BTF section. Instead of type/string section, it contains func\_info, line\_info and core\_relo sub-sections. See [3.3 BPF\_PROG\_LOAD](<#rst-bpf-prog-load>) for details about func\_info and line\_info record format.

The func\_info is organized as below.:



```text
func_info_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* func_info for section #1 */
btf_ext_info_sec for section #2 /* func_info for section #2 */
...
```

`func_info_rec_size` specifies the size of `bpf_func_info` structure when .BTF.ext is generated. `btf_ext_info_sec`, defined below, is a collection of func\_info for each specific ELF section.:



```text
struct btf_ext_info_sec {
   __u32   sec_name_off; /* offset to section name */
   __u32   num_info;
   /* Followed by num_info * record_size number of bytes */
   __u8    data[0];
};
```

Here, num\_info must be greater than 0.

The line\_info is organized as below.:



```text
line_info_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* line_info for section #1 */
btf_ext_info_sec for section #2 /* line_info for section #2 */
...
```

`line_info_rec_size` specifies the size of `bpf_line_info` structure when .BTF.ext is generated.

The interpretation of `bpf_func_info->insn_off` and `bpf_line_info->insn_off` is different between kernel API and ELF API. For kernel API, the `insn_off` is the instruction offset in the unit of `struct bpf_insn`. For ELF API, the `insn_off` is the byte offset from the beginning of section (`btf_ext_info_sec->sec_name_off`).

The core\_relo is organized as below.:



```text
core_relo_rec_size              /* __u32 value */
btf_ext_info_sec for section #1 /* core_relo for section #1 */
btf_ext_info_sec for section #2 /* core_relo for section #2 */
```

`core_relo_rec_size` specifies the size of `bpf_core_relo` structure when .BTF.ext is generated. All `bpf_core_relo` structures within a single `btf_ext_info_sec` describe relocations applied to section named by `btf_ext_info_sec->sec_name_off`.

See [Documentation/bpf/llvm\_reloc.rst](</kernel/internals/bpf/llvm-reloc.md#rst-btf-co-re-relocations>) for more information on CO-RE relocations.

<a id="rst-btf-ids-section"></a>

### 4.3 .BTF\_ids section

The .BTF\_ids section encodes BTF ID values that are used within the kernel.

This section is created during the kernel compilation with the help of macros defined in `include/linux/btf_ids.h` header file. Kernel code can use them to create lists and sets (sorted lists) of BTF ID values.

The `BTF_ID_LIST` and `BTF_ID` macros define unsorted list of BTF ID values, with following syntax:



```text
BTF_ID_LIST(list)
BTF_ID(type1, name1)
BTF_ID(type2, name2)
```

resulting in following layout in .BTF\_ids section:



```text
__BTF_ID__type1__name1__1:
.zero 4
__BTF_ID__type2__name2__2:
.zero 4
```

The `u32 list[];` variable is defined to access the list.

The `BTF_ID_UNUSED` macro defines 4 zero bytes. It's used when we want to define unused entry in BTF\_ID\_LIST, like:



```text
BTF_ID_LIST(bpf_skb_output_btf_ids)
BTF_ID(struct, sk_buff)
BTF_ID_UNUSED
BTF_ID(struct, task_struct)
```

The `BTF_SET_START/END` macros pair defines sorted list of BTF ID values and their count, with following syntax:



```text
BTF_SET_START(set)
BTF_ID(type1, name1)
BTF_ID(type2, name2)
BTF_SET_END(set)
```

resulting in following layout in .BTF\_ids section:



```text
__BTF_ID__set__set:
.zero 4
__BTF_ID__type1__name1__3:
.zero 4
__BTF_ID__type2__name2__4:
.zero 4
```

The `struct btf_id_set set;` variable is defined to access the list.

The `typeX` name can be one of following:



```text
struct, union, typedef, func
```

and is used as a filter when resolving the BTF ID value.

All the BTF ID lists and sets are compiled in the .BTF\_ids section and resolved during the linking phase of kernel build by `resolve_btfids` tool.

<a id="rst-btf-base-section"></a>

### 4.4 .BTF.base section

Split BTF - where the .BTF section only contains types not in the associated base .BTF section - is an extremely efficient way to encode type information for kernel modules, since they generally consist of a few module-specific types along with a large set of shared kernel types. The former are encoded in split BTF, while the latter are encoded in base BTF, resulting in more compact representations. A type in split BTF that refers to a type in base BTF refers to it using its base BTF ID, and split BTF IDs start at last\_base\_BTF\_ID + 1.

The downside of this approach however is that this makes the split BTF somewhat brittle - when the base BTF changes, base BTF ID references are no longer valid and the split BTF itself becomes useless. The role of the .BTF.base section is to make split BTF more resilient for cases where the base BTF may change, as is the case for kernel modules not built every time the kernel is for example. .BTF.base contains named base types; INTs, FLOATs, STRUCTs, UNIONs, ENUM\[64\]s and FWDs. INTs and FLOATs are fully described in .BTF.base sections, while composite types like structs and unions are not fully defined - the .BTF.base type simply serves as a description of the type the split BTF referred to, so structs/unions have 0 members in the .BTF.base section. ENUM\[64\]s are similarly recorded with 0 members. Any other types are added to the split BTF. This distillation process then leaves us with a .BTF.base section with such minimal descriptions of base types and .BTF split section which refers to those base types. Later, we can relocate the split BTF using both the information stored in the .BTF.base section and the new .BTF base; the type information in the .BTF.base section allows us to update the split BTF references to point at the corresponding new base BTF IDs.

BTF relocation happens on kernel module load when a kernel module has a .BTF.base section, and libbpf also provides a btf\_\_relocate() API to accomplish this.

As an example consider the following base BTF:



```text
[1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[2] STRUCT 'foo' size=8 vlen=2
        'f1' type_id=1 bits_offset=0
        'f2' type_id=1 bits_offset=32
```

...and associated split BTF:



```text
[3] PTR '(anon)' type_id=2
```

i.e. split BTF describes a pointer to struct foo \{ int f1; int f2 \};

.BTF.base will consist of:



```text
[1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[2] STRUCT 'foo' size=8 vlen=0
```

If we relocate the split BTF later using the following new base BTF:



```text
[1] INT 'long unsigned int' size=8 bits_offset=0 nr_bits=64 encoding=(none)
[2] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[3] STRUCT 'foo' size=8 vlen=2
        'f1' type_id=2 bits_offset=0
        'f2' type_id=2 bits_offset=32
```

...we can use our .BTF.base description to know that the split BTF reference is to struct foo, and relocation results in new split BTF:



```text
[4] PTR '(anon)' type_id=3
```

Note that we had to update BTF ID and start BTF ID for the split BTF.

So we see how .BTF.base plays the role of facilitating later relocation, leading to more resilient split BTF.

.BTF.base sections will be generated automatically for out-of-tree kernel module builds - i.e. where KBUILD\_EXTMOD is set (as it would be for "make M=path/2/mod" cases). .BTF.base generation requires pahole support for the "distilled\_base" BTF feature; this is available in pahole v1.28 and later.

<a id="rst-using-btf"></a>

## 5. Using BTF

<a id="rst-bpftool-map-pretty-print"></a>

### 5.1 bpftool map pretty print

With BTF, the map key/value can be printed based on fields rather than simply raw bytes. This is especially valuable for large structure or if your data structure has bitfields. For example, for the following map,:



```text
enum A { A1, A2, A3, A4, A5 };
typedef enum A ___A;
struct tmp_t {
     char a1:4;
     int  a2:4;
     int  :4;
     __u32 a3:4;
     int b;
     ___A b1:4;
     enum A b2:4;
};
struct {
     __uint(type, BPF_MAP_TYPE_ARRAY);
     __type(key, int);
     __type(value, struct tmp_t);
     __uint(max_entries, 1);
} tmpmap SEC(".maps");
```

bpftool is able to pretty print like below:



```text
[{
      "key": 0,
      "value": {
          "a1": 0x2,
          "a2": 0x4,
          "a3": 0x6,
          "b": 7,
          "b1": 0x8,
          "b2": 0xa
      }
  }
]
```

<a id="rst-bpftool-prog-dump"></a>

### 5.2 bpftool prog dump

The following is an example showing how func\_info and line\_info can help prog dump with better kernel symbol names, function prototypes and line information.:



```text
$ bpftool prog dump jited pinned /sys/fs/bpf/test_btf_haskv
[...]
int test_long_fname_2(struct dummy_tracepoint_args * arg):
bpf_prog_44a040bf25481309_test_long_fname_2:
; static int test_long_fname_2(struct dummy_tracepoint_args *arg)
   0:   push   %rbp
   1:   mov    %rsp,%rbp
   4:   sub    $0x30,%rsp
   b:   sub    $0x28,%rbp
   f:   mov    %rbx,0x0(%rbp)
  13:   mov    %r13,0x8(%rbp)
  17:   mov    %r14,0x10(%rbp)
  1b:   mov    %r15,0x18(%rbp)
  1f:   xor    %eax,%eax
  21:   mov    %rax,0x20(%rbp)
  25:   xor    %esi,%esi
; int key = 0;
  27:   mov    %esi,-0x4(%rbp)
; if (!arg->sock)
  2a:   mov    0x8(%rdi),%rdi
; if (!arg->sock)
  2e:   cmp    $0x0,%rdi
  32:   je     0x0000000000000070
  34:   mov    %rbp,%rsi
; counts = bpf_map_lookup_elem(&btf_map, &key);
[...]
```

<a id="rst-verifier-log"></a>

### 5.3 Verifier Log

The following is an example of how line\_info can help debugging verification failure.:



```text
   /* The code at tools/testing/selftests/bpf/test_xdp_noinline.c
    * is modified as below.
    */
   data = (void *)(long)xdp->data;
   data_end = (void *)(long)xdp->data_end;
   /*
   if (data + 4 > data_end)
           return XDP_DROP;
   */
   *(u32 *)data = dst->dst;

$ bpftool prog load ./test_xdp_noinline.o /sys/fs/bpf/test_xdp_noinline type xdp
    ; data = (void *)(long)xdp->data;
    224: (79) r2 = *(u64 *)(r10 -112)
    225: (61) r2 = *(u32 *)(r2 +0)
    ; *(u32 *)data = dst->dst;
    226: (63) *(u32 *)(r2 +0) = r1
    invalid access to packet, off=0 size=4, R2(id=0,off=0,r=0)
    R2 offset is outside of the packet
```

<a id="rst-btf-generation"></a>

## 6. BTF Generation

You need latest pahole

> [https://git.kernel.org/pub/scm/devel/pahole/pahole.git/](<https://git.kernel.org/pub/scm/devel/pahole/pahole.git/>)

or llvm (8.0 or later). The pahole acts as a dwarf2btf converter. It doesn't support .BTF.ext and btf BTF\_KIND\_FUNC type yet. For example,:



```text
-bash-4.4$ cat t.c
struct t {
  int a:2;
  int b:3;
  int c:2;
} g;
-bash-4.4$ gcc -c -O2 -g t.c
-bash-4.4$ pahole -JV t.o
File t.o:
[1] STRUCT t kind_flag=1 size=4 vlen=3
        a type_id=2 bitfield_size=2 bits_offset=0
        b type_id=2 bitfield_size=3 bits_offset=2
        c type_id=2 bitfield_size=2 bits_offset=5
[2] INT int size=4 bit_offset=0 nr_bits=32 encoding=SIGNED
```

The llvm is able to generate .BTF and .BTF.ext directly with -g for bpf target only. The assembly code (-S) is able to show the BTF encoding in assembly format.:



```text
-bash-4.4$ cat t2.c
typedef int __int32;
struct t2 {
  int a2;
  int (*f2)(char q1, __int32 q2, ...);
  int (*f3)();
} g2;
int main() { return 0; }
int test() { return 0; }
-bash-4.4$ clang -c -g -O2 --target=bpf t2.c
-bash-4.4$ readelf -S t2.o
  ......
  [ 8] .BTF              PROGBITS         0000000000000000  00000247
       000000000000016e  0000000000000000           0     0     1
  [ 9] .BTF.ext          PROGBITS         0000000000000000  000003b5
       0000000000000060  0000000000000000           0     0     1
  [10] .rel.BTF.ext      REL              0000000000000000  000007e0
       0000000000000040  0000000000000010          16     9     8
  ......
-bash-4.4$ clang -S -g -O2 --target=bpf t2.c
-bash-4.4$ cat t2.s
  ......
        .section        .BTF,"",@progbits
        .short  60319                   # 0xeb9f
        .byte   1
        .byte   0
        .long   24
        .long   0
        .long   220
        .long   220
        .long   122
        .long   0                       # BTF_KIND_FUNC_PROTO(id = 1)
        .long   218103808               # 0xd000000
        .long   2
        .long   83                      # BTF_KIND_INT(id = 2)
        .long   16777216                # 0x1000000
        .long   4
        .long   16777248                # 0x1000020
  ......
        .byte   0                       # string offset=0
        .ascii  ".text"                 # string offset=1
        .byte   0
        .ascii  "/home/yhs/tmp-pahole/t2.c" # string offset=7
        .byte   0
        .ascii  "int main() { return 0; }" # string offset=33
        .byte   0
        .ascii  "int test() { return 0; }" # string offset=58
        .byte   0
        .ascii  "int"                   # string offset=83
  ......
        .section        .BTF.ext,"",@progbits
        .short  60319                   # 0xeb9f
        .byte   1
        .byte   0
        .long   24
        .long   0
        .long   28
        .long   28
        .long   44
        .long   8                       # FuncInfo
        .long   1                       # FuncInfo section string offset=1
        .long   2
        .long   .Lfunc_begin0
        .long   3
        .long   .Lfunc_begin1
        .long   5
        .long   16                      # LineInfo
        .long   1                       # LineInfo section string offset=1
        .long   2
        .long   .Ltmp0
        .long   7
        .long   33
        .long   7182                    # Line 7 Col 14
        .long   .Ltmp3
        .long   7
        .long   58
        .long   8206                    # Line 8 Col 14
```

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

## 7. Testing

The kernel BPF selftest [tools/testing/selftests/bpf/prog\_tests/btf.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/prog_tests/btf.c>) provides an extensive set of BTF-related tests.

<!-- Links -->

<a id="rst-tools-testing-selftests-bpf-prog-tests-btf-c"></a>

---

# Contents

_Peios Kernel / Internals / BPF_

> 1 Clang implementation notes

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



<a id="rst-clang-implementation-notes"></a>

## 1   Clang implementation notes

This document provides more details specific to the Clang/LLVM implementation of the eBPF instruction set.

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

### 1.1   Versions

Clang defined "CPU" versions, where a CPU version of 3 corresponds to the current eBPF ISA.

Clang can select the eBPF ISA version using `-mcpu=v3` for example to select version 3.

<a id="rst-arithmetic-instructions"></a>

### 1.2   Arithmetic instructions

For CPU versions prior to 3, Clang v7.0 and later can enable `BPF_ALU` support with `-Xclang -target-feature -Xclang +alu32`.  In CPU version 3, support is automatically included.

<a id="rst-jump-instructions"></a>

### 1.3   Jump instructions

If `-O0` is used, Clang will generate the `BPF_CALL | BPF_X | BPF_JMP` (0x8d) instruction, which is not supported by the Linux kernel verifier.

<a id="rst-atomic-operations"></a>

### 1.4   Atomic operations

Clang can generate atomic instructions by default when `-mcpu=v3` is enabled. If a lower version for `-mcpu` is set, the only atomic instruction Clang can generate is `BPF_ADD` <em>without</em> `BPF_FETCH`. If you need to enable the atomics features, while keeping a lower `-mcpu` version, you can use `-Xclang -target-feature -Xclang +alu32`.

---

# Classic BPF vs eBPF

_Peios Kernel / Internals / BPF_

> eBPF is designed to be JITed with one to one mapping, which can also open up the possibility for GCC/LLVM compilers to generate optimized eBPF code through an eBPF backend that performs almost as fast as natively compiled code.

<a id="rst-classic-bpf-vs-ebpf"></a>

eBPF is designed to be JITed with one to one mapping, which can also open up the possibility for GCC/LLVM compilers to generate optimized eBPF code through an eBPF backend that performs almost as fast as natively compiled code.

Some core changes of the eBPF format from classic BPF:

- Number of registers increase from 2 to 10:

  The old format had two registers A and X, and a hidden frame pointer. The new layout extends this to be 10 internal registers and a read-only frame pointer. Since 64-bit CPUs are passing arguments to functions via registers the number of args from eBPF program to in-kernel function is restricted to 5 and one register is used to accept return value from an in-kernel function. Natively, x86_64 passes first 6 arguments in registers, aarch64/ sparcv9/mips64 have 7 - 8 registers for arguments; x86_64 has 6 callee saved registers, and aarch64/sparcv9/mips64 have 11 or more callee saved registers.

  Thus, all eBPF registers map one to one to HW registers on x86_64, aarch64, etc, and eBPF calling convention maps directly to ABIs used by the kernel on 64-bit architectures.

  On 32-bit architectures JIT may map programs that use only 32-bit arithmetic and may let more complex programs to be interpreted.

  R0 - R5 are scratch registers and eBPF program needs spill/fill them if necessary across calls. Note that there is only one eBPF program (== one eBPF main routine) and it cannot call other eBPF functions, it can only call predefined in-kernel functions, though.

- Register width increases from 32-bit to 64-bit:

  Still, the semantics of the original 32-bit ALU operations are preserved via 32-bit subregisters. All eBPF registers are 64-bit with 32-bit lower subregisters that zero-extend into 64-bit if they are being written to. That behavior maps directly to x86_64 and arm64 subregister definition, but makes other JITs more difficult.

  32-bit architectures run 64-bit eBPF programs via interpreter. Their JITs may convert BPF programs that only use 32-bit subregisters into native instruction set and let the rest being interpreted.

  Operation is 64-bit, because on 64-bit architectures, pointers are also 64-bit wide, and we want to pass 64-bit values in/out of kernel functions, so 32-bit eBPF registers would otherwise require to define register-pair ABI, thus, there won't be able to use a direct eBPF register to HW register mapping and JIT would need to do combine/split/move operations for every register in and out of the function, which is complex, bug prone and slow. Another reason is the use of atomic 64-bit counters.

- Conditional jt/jf targets replaced with jt/fall-through:

  While the original design has constructs such as `if (cond) jump_true; else jump_false;`, they are being replaced into alternative constructs like `if (cond) jump_true; /* else fall-through */`.

- Introduces bpf_call insn and register passing convention for zero overhead calls from/to other kernel functions:

  Before an in-kernel function call, the eBPF program needs to place function arguments into R1 to R5 registers to satisfy calling convention, then the interpreter will take them from registers and pass to in-kernel function. If R1 - R5 registers are mapped to CPU registers that are used for argument passing on given architecture, the JIT compiler doesn't need to emit extra moves. Function arguments will be in the correct registers and BPF_CALL instruction will be JITed as single 'call' HW instruction. This calling convention was picked to cover common call situations without performance penalty.

  After an in-kernel function call, R1 - R5 are reset to unreadable and R0 has a return value of the function. Since R6 - R9 are callee saved, their state is preserved across the call.

  For example, consider three C functions:



  ```text
  u64 f1() { return (*_f2)(1); }
  u64 f2(u64 a) { return f3(a + 1, a); }
  u64 f3(u64 a, u64 b) { return a - b; }
  ```

  GCC can compile f1, f3 into x86_64:



  ```text
  f1:
      movl $1, %edi
      movq _f2(%rip), %rax
      jmp  *%rax
  f3:
      movq %rdi, %rax
      subq %rsi, %rax
      ret
  ```

  Function f2 in eBPF may look like:



  ```text
  f2:
      bpf_mov R2, R1
      bpf_add R1, 1
      bpf_call f3
      bpf_exit
  ```

  If f2 is JITed and the pointer stored to `_f2`. The calls f1 -&gt; f2 -&gt; f3 and returns will be seamless. Without JIT, \__bpf_prog_run() interpreter needs to be used to call into f2.

  For practical reasons all eBPF programs have only one argument 'ctx' which is already placed into R1 (e.g. on \__bpf_prog_run() startup) and the programs can call kernel functions with up to 5 arguments. Calls with 6 or more arguments are currently not supported, but these restrictions can be lifted if necessary in the future.

  On 64-bit architectures all register map to HW registers one to one. For example, x86_64 JIT compiler can map them as ...



  ```text
  R0 - rax
  R1 - rdi
  R2 - rsi
  R3 - rdx
  R4 - rcx
  R5 - r8
  R6 - rbx
  R7 - r13
  R8 - r14
  R9 - r15
  R10 - rbp
  ```

  ... since x86_64 ABI mandates rdi, rsi, rdx, rcx, r8, r9 for argument passing and rbx, r12 - r15 are callee saved.

  Then the following eBPF pseudo-program:



  ```text
  bpf_mov R6, R1 /* save ctx */
  bpf_mov R2, 2
  bpf_mov R3, 3
  bpf_mov R4, 4
  bpf_mov R5, 5
  bpf_call foo
  bpf_mov R7, R0 /* save foo() return value */
  bpf_mov R1, R6 /* restore ctx for next call */
  bpf_mov R2, 6
  bpf_mov R3, 7
  bpf_mov R4, 8
  bpf_mov R5, 9
  bpf_call bar
  bpf_add R0, R7
  bpf_exit
  ```

  After JIT to x86_64 may look like:



  ```text
  push %rbp
  mov %rsp,%rbp
  sub $0x228,%rsp
  mov %rbx,-0x228(%rbp)
  mov %r13,-0x220(%rbp)
  mov %rdi,%rbx
  mov $0x2,%esi
  mov $0x3,%edx
  mov $0x4,%ecx
  mov $0x5,%r8d
  callq foo
  mov %rax,%r13
  mov %rbx,%rdi
  mov $0x6,%esi
  mov $0x7,%edx
  mov $0x8,%ecx
  mov $0x9,%r8d
  callq bar
  add %r13,%rax
  mov -0x228(%rbp),%rbx
  mov -0x220(%rbp),%r13
  leaveq
  retq
  ```

  Which is in this example equivalent in C to:



  ```text
  u64 bpf_filter(u64 ctx)
  {
      return foo(ctx, 2, 3, 4, 5) + bar(ctx, 6, 7, 8, 9);
  }
  ```

  In-kernel functions foo() and bar() with prototype: u64 (\*)(u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5); will receive arguments in proper registers and place their return value into `%rax` which is R0 in eBPF. Prologue and epilogue are emitted by JIT and are implicit in the interpreter. R0-R5 are scratch registers, so eBPF program needs to preserve them across the calls as defined by calling convention.

  For example the following program is invalid:



  ```text
  bpf_mov R1, 1
  bpf_call foo
  bpf_mov R0, R1
  bpf_exit
  ```

  After the call the registers R1-R5 contain junk values and cannot be read. An in-kernel [verifier.rst](/kernel/internals/bpf/verifier.md) is used to validate eBPF programs.

Also in the new design, eBPF is limited to 4096 insns, which means that any program will terminate quickly and will only call a fixed number of kernel functions. Original BPF and eBPF are two operand instructions, which helps to do one-to-one mapping between eBPF insn and x86 insn during JIT.

The input context pointer for invoking the interpreter function is generic, its content is defined by a specific use case. For seccomp register R1 points to seccomp_data, for converted BPF filters R1 points to a skb.

A program, that is translated internally consists of the following elements:



```text
op:16, jt:8, jf:8, k:32    ==>    op:8, dst_reg:4, src_reg:4, off:16, imm:32
```

So far 87 eBPF instructions were implemented. 8-bit 'op' opcode field has room for new instructions. Some of them may use 16/24/32 byte encoding. New instructions must be multiple of 8 bytes to preserve backward compatibility.

eBPF is a general purpose RISC instruction set. Not every register and every instruction are used during translation from original BPF to eBPF. For example, socket filters are not using `exclusive add` instruction, but tracing filters may do to maintain counters of events, for example. Register R9 is not used by socket filters either, but more complex filters may be running out of registers and would have to resort to spill/fill to stack.

eBPF can be used as a generic assembler for last step performance optimizations, socket filters and seccomp are using it as assembler. Tracing filters may use it as assembler to generate code from kernel. In kernel usage may not be bounded by security considerations, since generated eBPF code may be optimizing internal code path and not being exposed to the user space. Safety of eBPF can come from the [verifier.rst](/kernel/internals/bpf/verifier.md). In such use cases as described, it may be used as safe instruction set.

Just like the original BPF, eBPF runs within a controlled environment, is deterministic and the kernel can easily prove that. The safety of the program can be determined in two steps: first step does depth-first-search to disallow loops and other CFG validation; second step starts from the first insn and descends all possible paths. It simulates execution of every insn and observes the state change of registers and stack.

<a id="rst-opcode-encoding"></a>

## opcode encoding

eBPF is reusing most of the opcode encoding from classic to simplify conversion of classic BPF to eBPF.

For arithmetic and jump instructions the 8-bit 'code' field is divided into three parts:



```text
+----------------+--------+--------------------+
|   4 bits       |  1 bit |   3 bits           |
| operation code | source | instruction class  |
+----------------+--------+--------------------+
(MSB)                                      (LSB)
```

Three LSB bits store instruction class which is one of:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Classic BPF classes
>
> </th>
> <th>
>
>
> eBPF classes
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> BPF_LD    0x00
>
> </td>
> <td>
>
>
> BPF_LD    0x00
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_LDX   0x01
>
> </td>
> <td>
>
>
> BPF_LDX   0x01
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_ST    0x02
>
> </td>
> <td>
>
>
> BPF_ST    0x02
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_STX   0x03
>
> </td>
> <td>
>
>
> BPF_STX   0x03
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_ALU   0x04
>
> </td>
> <td>
>
>
> BPF_ALU   0x04
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_JMP   0x05
>
> </td>
> <td>
>
>
> BPF_JMP   0x05
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_RET   0x06
>
> </td>
> <td>
>
>
> BPF_JMP32 0x06
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> BPF_MISC  0x07
>
> </td>
> <td>
>
>
> BPF_ALU64 0x07
>
> </td>
> </tr>
> </tbody>
> </table>

The 4th bit encodes the source operand ...

> >
> >
> > ```text
> > BPF_K     0x00
> > BPF_X     0x08
> > ```
>
> - in classic BPF, this means:
>
>
>
>   ```text
>   BPF_SRC(code) == BPF_X - use register X as source operand
>   BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
>   ```
>
> - in eBPF, this means:
>
>
>
>   ```text
>   BPF_SRC(code) == BPF_X - use 'src_reg' register as source operand
>   BPF_SRC(code) == BPF_K - use 32-bit immediate as source operand
>   ```

... and four MSB bits store operation code.

If BPF_CLASS(code) == BPF_ALU or BPF_ALU64 \[ in eBPF \], BPF_OP(code) is one of:



```text
BPF_ADD   0x00
BPF_SUB   0x10
BPF_MUL   0x20
BPF_DIV   0x30
BPF_OR    0x40
BPF_AND   0x50
BPF_LSH   0x60
BPF_RSH   0x70
BPF_NEG   0x80
BPF_MOD   0x90
BPF_XOR   0xa0
BPF_MOV   0xb0  /* eBPF only: mov reg to reg */
BPF_ARSH  0xc0  /* eBPF only: sign extending shift right */
BPF_END   0xd0  /* eBPF only: endianness conversion */
```

If BPF_CLASS(code) == BPF_JMP or BPF_JMP32 \[ in eBPF \], BPF_OP(code) is one of:



```text
BPF_JA    0x00  /* BPF_JMP only */
BPF_JEQ   0x10
BPF_JGT   0x20
BPF_JGE   0x30
BPF_JSET  0x40
BPF_JNE   0x50  /* eBPF only: jump != */
BPF_JSGT  0x60  /* eBPF only: signed '>' */
BPF_JSGE  0x70  /* eBPF only: signed '>=' */
BPF_CALL  0x80  /* eBPF BPF_JMP only: function call */
BPF_EXIT  0x90  /* eBPF BPF_JMP only: function return */
BPF_JLT   0xa0  /* eBPF only: unsigned '<' */
BPF_JLE   0xb0  /* eBPF only: unsigned '<=' */
BPF_JSLT  0xc0  /* eBPF only: signed '<' */
BPF_JSLE  0xd0  /* eBPF only: signed '<=' */
```

So BPF_ADD \| BPF_X \| BPF_ALU means 32-bit addition in both classic BPF and eBPF. There are only two registers in classic BPF, so it means A += X. In eBPF it means dst_reg = (u32) dst_reg + (u32) src_reg; similarly, BPF_XOR \| BPF_K \| BPF_ALU means A ^= imm32 in classic BPF and analogous src_reg = (u32) src_reg ^ (u32) imm32 in eBPF.

Classic BPF is using BPF_MISC class to represent A = X and X = A moves. eBPF is using BPF_MOV \| BPF_X \| BPF_ALU code instead. Since there are no BPF_MISC operations in eBPF, the class 7 is used as BPF_ALU64 to mean exactly the same operations as BPF_ALU, but with 64-bit wide operands instead. So BPF_ADD \| BPF_X \| BPF_ALU64 means 64-bit addition, i.e.: dst_reg = dst_reg + src_reg

Classic BPF wastes the whole BPF_RET class to represent a single `ret` operation. Classic BPF_RET \| BPF_K means copy imm32 into return register and perform function exit. eBPF is modeled to match CPU, so BPF_JMP \| BPF_EXIT in eBPF means function exit only. The eBPF program needs to store return value into register R0 before doing a BPF_EXIT. Class 6 in eBPF is used as BPF_JMP32 to mean exactly the same operations as BPF_JMP, but with 32-bit wide operands for the comparisons instead.

For load and store instructions the 8-bit 'code' field is divided as:



```text
+--------+--------+-------------------+
| 3 bits | 2 bits |   3 bits          |
|  mode  |  size  | instruction class |
+--------+--------+-------------------+
(MSB)                             (LSB)
```

Size modifier is one of ...



```text
BPF_W   0x00    /* word */
BPF_H   0x08    /* half word */
BPF_B   0x10    /* byte */
BPF_DW  0x18    /* eBPF only, double word */
```

... which encodes size of load/store operation:



```text
B  - 1 byte
H  - 2 byte
W  - 4 byte
DW - 8 byte (eBPF only)
```

Mode modifier is one of:



```text
BPF_IMM     0x00  /* used for 32-bit mov in classic BPF and 64-bit in eBPF */
BPF_ABS     0x20
BPF_IND     0x40
BPF_MEM     0x60
BPF_LEN     0x80  /* classic BPF only, reserved in eBPF */
BPF_MSH     0xa0  /* classic BPF only, reserved in eBPF */
BPF_ATOMIC  0xc0  /* eBPF only, atomic operations */
```

---

# BPF cpumask kfuncs

_Peios Kernel / Internals / BPF_

> struct cpumask is a bitmap data structure in the kernel whose indices reflect the CPUs on the system. Commonly, cpumasks are used to track which CPUs a task is affinitized to, but they can also be used to e.g. track which cores are…

<a id="rst-bpf-cpumask-kfuncs"></a>
<a id="rst-cpumasks-header-label"></a>

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

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

## 1. Introduction

`struct cpumask` is a bitmap data structure in the kernel whose indices reflect the CPUs on the system. Commonly, cpumasks are used to track which CPUs a task is affinitized to, but they can also be used to e.g. track which cores are associated with a scheduling domain, which cores on a machine are idle, etc.

BPF provides programs with a set of [BPF Kernel Functions (kfuncs)](</kernel/internals/bpf/kfuncs.md#rst-kfuncs-header-label>) that can be used to allocate, mutate, query, and free cpumasks.

<a id="rst-bpf-cpumask-objects"></a>

## 2. BPF cpumask objects

There are two different types of cpumasks that can be used by BPF programs.

<a id="rst-struct-bpf-cpumask"></a>

### 2.1 `struct bpf_cpumask *`

`struct bpf_cpumask *` is a cpumask that is allocated by BPF, on behalf of a BPF program, and whose lifecycle is entirely controlled by BPF. These cpumasks are RCU-protected, can be mutated, can be used as kptrs, and can be safely cast to a `struct cpumask *`.

<a id="rst-struct-bpf-cpumask-lifecycle"></a>

### 2.1.1 `struct bpf_cpumask *` lifecycle

A `struct bpf_cpumask *` is allocated, acquired, and released, using the following functions:


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

```c
__bpf_kfunc struct bpf_cpumask * bpf_cpumask_create(void)
```

Create a mutable BPF cpumask.

**Parameters**

- `void`: no arguments

**Description**

Allocates a cpumask that can be queried, mutated, acquired, and released by
a BPF program. The cpumask returned by this function must either be embedded
in a map as a kptr, or freed with [`bpf_cpumask_release()`](#c-bpf_cpumask_release).

[`bpf_cpumask_create()`](#c-bpf_cpumask_create) allocates memory using the BPF memory allocator, and
will not block. It may return NULL if no memory is available.

**Return**

* A pointer to a new struct bpf_cpumask instance on success.
* NULL if the BPF memory allocator is out of memory.



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

```c
__bpf_kfunc struct bpf_cpumask * bpf_cpumask_acquire(struct bpf_cpumask *cpumask)
```

Acquire a reference to a BPF cpumask.

**Parameters**

- `struct bpf_cpumask *cpumask`: The BPF cpumask being acquired. The cpumask must be a trusted
  pointer.

**Description**

Acquires a reference to a BPF cpumask. The cpumask returned by this function
must either be embedded in a map as a kptr, or freed with
[`bpf_cpumask_release()`](#c-bpf_cpumask_release).

**Return**

* The struct bpf_cpumask pointer passed to the function.



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

```c
__bpf_kfunc void bpf_cpumask_release(struct bpf_cpumask *cpumask)
```

Release a previously acquired BPF cpumask.

**Parameters**

- `struct bpf_cpumask *cpumask`: The cpumask being released.

**Description**

Releases a previously acquired reference to a BPF cpumask. When the final
reference of the BPF cpumask has been released, it is subsequently freed in
an RCU callback in the BPF memory allocator.


For example:



```c
struct cpumask_map_value {
        struct bpf_cpumask __kptr * cpumask;
};

struct array_map {
        __uint(type, BPF_MAP_TYPE_ARRAY);
        __type(key, int);
        __type(value, struct cpumask_map_value);
        __uint(max_entries, 65536);
} cpumask_map SEC(".maps");

static int cpumask_map_insert(struct bpf_cpumask *mask, u32 pid)
{
        struct cpumask_map_value local, *v;
        long status;
        struct bpf_cpumask *old;
        u32 key = pid;

        local.cpumask = NULL;
        status = bpf_map_update_elem(&cpumask_map, &key, &local, 0);
        if (status) {
                bpf_cpumask_release(mask);
                return status;
        }

        v = bpf_map_lookup_elem(&cpumask_map, &key);
        if (!v) {
                bpf_cpumask_release(mask);
                return -ENOENT;
        }

        old = bpf_kptr_xchg(&v->cpumask, mask);
        if (old)
                bpf_cpumask_release(old);

        return 0;
}

/**
 * A sample tracepoint showing how a task's cpumask can be queried and
 * recorded as a kptr.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(record_task_cpumask, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *cpumask;
        int ret;

        cpumask = bpf_cpumask_create();
        if (!cpumask)
                return -ENOMEM;

        if (!bpf_cpumask_full(task->cpus_ptr))
                bpf_printk("task %s has CPU affinity", task->comm);

        bpf_cpumask_copy(cpumask, task->cpus_ptr);
        return cpumask_map_insert(cpumask, task->pid);
}
```

---

<a id="rst-struct-bpf-cpumask-as-kptrs"></a>

### 2.1.1 `struct bpf_cpumask *` as kptrs

As mentioned and illustrated above, these `struct bpf_cpumask *` objects can also be stored in a map and used as kptrs. If a `struct bpf_cpumask *` is in a map, the reference can be removed from the map with bpf_kptr_xchg(), or opportunistically acquired using RCU:



```c
/* struct containing the struct bpf_cpumask kptr which is stored in the map. */
struct cpumasks_kfunc_map_value {
        struct bpf_cpumask __kptr * bpf_cpumask;
};

/* The map containing struct cpumasks_kfunc_map_value entries. */
struct {
        __uint(type, BPF_MAP_TYPE_ARRAY);
        __type(key, int);
        __type(value, struct cpumasks_kfunc_map_value);
        __uint(max_entries, 1);
} cpumasks_kfunc_map SEC(".maps");

/* ... */

/**
 * A simple example tracepoint program showing how a
 * struct bpf_cpumask * kptr that is stored in a map can
 * be passed to kfuncs using RCU protection.
 */
SEC("tp_btf/cgroup_mkdir")
int BPF_PROG(cgrp_ancestor_example, struct cgroup *cgrp, const char *path)
{
        struct bpf_cpumask *kptr;
        struct cpumasks_kfunc_map_value *v;
        u32 key = 0;

        /* Assume a bpf_cpumask * kptr was previously stored in the map. */
        v = bpf_map_lookup_elem(&cpumasks_kfunc_map, &key);
        if (!v)
                return -ENOENT;

        bpf_rcu_read_lock();
        /* Acquire a reference to the bpf_cpumask * kptr that's already stored in the map. */
        kptr = v->cpumask;
        if (!kptr) {
                /* If no bpf_cpumask was present in the map, it's because
                 * we're racing with another CPU that removed it with
                 * bpf_kptr_xchg() between the bpf_map_lookup_elem()
                 * above, and our load of the pointer from the map.
                 */
                bpf_rcu_read_unlock();
                return -EBUSY;
        }

        bpf_cpumask_setall(kptr);
        bpf_rcu_read_unlock();

        return 0;
}
```

---

<a id="rst-struct-cpumask"></a>

### 2.2 `struct cpumask`

`struct cpumask` is the object that actually contains the cpumask bitmap being queried, mutated, etc. A `struct bpf_cpumask` wraps a `struct cpumask`, which is why it's safe to cast it as such (note however that it is **not** safe to cast a `struct cpumask *` to a `struct bpf_cpumask *`, and the verifier will reject any program that tries to do so).

As we'll see below, any kfunc that mutates its cpumask argument will take a `struct bpf_cpumask *` as that argument. Any argument that simply queries the cpumask will instead take a `struct cpumask *`.

<a id="rst-cpumask-kfuncs"></a>

## 3. cpumask kfuncs

Above, we described the kfuncs that can be used to allocate, acquire, release, etc a `struct bpf_cpumask *`. This section of the document will describe the kfuncs for mutating and querying cpumasks.

<a id="rst-mutating-cpumasks"></a>

### 3.1 Mutating cpumasks

Some cpumask kfuncs are "read-only" in that they don't mutate any of their arguments, whereas others mutate at least one argument (which means that the argument must be a `struct bpf_cpumask *`, as described above).

This section will describe all of the cpumask kfuncs which mutate at least one argument. [3.2 Querying cpumasks](<#rst-cpumasks-querying-label>) below describes the read-only kfuncs.

<a id="rst-setting-and-clearing-cpus"></a>

### 3.1.1 Setting and clearing CPUs

bpf_cpumask_set_cpu() and bpf_cpumask_clear_cpu() can be used to set and clear a CPU in a `struct bpf_cpumask` respectively:


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

```c
__bpf_kfunc void bpf_cpumask_set_cpu(u32 cpu, struct bpf_cpumask *cpumask)
```

Set a bit for a CPU in a BPF cpumask.

**Parameters**

- `u32 cpu`: The CPU to be set in the cpumask.
- `struct bpf_cpumask *cpumask`: The BPF cpumask in which a bit is being set.

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

```c
__bpf_kfunc void bpf_cpumask_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask)
```

Clear a bit for a CPU in a BPF cpumask.

**Parameters**

- `u32 cpu`: The CPU to be cleared from the cpumask.
- `struct bpf_cpumask *cpumask`: The BPF cpumask in which a bit is being cleared.


These kfuncs are pretty straightforward, and can be used, for example, as follows:



```c
/**
 * A sample tracepoint showing how a cpumask can be queried.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(test_set_clear_cpu, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *cpumask;

        cpumask = bpf_cpumask_create();
        if (!cpumask)
                return -ENOMEM;

        bpf_cpumask_set_cpu(0, cpumask);
        if (!bpf_cpumask_test_cpu(0, cast(cpumask)))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_clear_cpu(0, cpumask);
        if (bpf_cpumask_test_cpu(0, cast(cpumask)))
                /* Should never happen. */
                goto release_exit;

        /* struct cpumask * pointers such as task->cpus_ptr can also be queried. */
        if (bpf_cpumask_test_cpu(0, task->cpus_ptr))
                bpf_printk("task %s can use CPU %d", task->comm, 0);

release_exit:
        bpf_cpumask_release(cpumask);
        return 0;
}
```

---

bpf_cpumask_test_and_set_cpu() and bpf_cpumask_test_and_clear_cpu() are complementary kfuncs that allow callers to atomically test and set (or clear) CPUs:


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

```c
__bpf_kfunc bool bpf_cpumask_test_and_set_cpu(u32 cpu, struct bpf_cpumask *cpumask)
```

Atomically test and set a CPU in a BPF cpumask.

**Parameters**

- `u32 cpu`: The CPU being set and queried for.
- `struct bpf_cpumask *cpumask`: The BPF cpumask being set and queried for containing a CPU.

**Return**

* true  - **cpu** is set in the cpumask
* false - **cpu** was not set in the cpumask, or **cpu** is invalid.

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

```c
__bpf_kfunc bool bpf_cpumask_test_and_clear_cpu(u32 cpu, struct bpf_cpumask *cpumask)
```

Atomically test and clear a CPU in a BPF cpumask.

**Parameters**

- `u32 cpu`: The CPU being cleared and queried for.
- `struct bpf_cpumask *cpumask`: The BPF cpumask being cleared and queried for containing a CPU.

**Return**

* true  - **cpu** is set in the cpumask
* false - **cpu** was not set in the cpumask, or **cpu** is invalid.


---

We can also set and clear entire `struct bpf_cpumask *` objects in one operation using bpf_cpumask_setall() and bpf_cpumask_clear():


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

```c
__bpf_kfunc void bpf_cpumask_setall(struct bpf_cpumask *cpumask)
```

Set all of the bits in a BPF cpumask.

**Parameters**

- `struct bpf_cpumask *cpumask`: The BPF cpumask having all of its bits set.

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

```c
__bpf_kfunc void bpf_cpumask_clear(struct bpf_cpumask *cpumask)
```

Clear all of the bits in a BPF cpumask.

**Parameters**

- `struct bpf_cpumask *cpumask`: The BPF cpumask being cleared.


<a id="rst-operations-between-cpumasks"></a>

### 3.1.2 Operations between cpumasks

In addition to setting and clearing individual CPUs in a single cpumask, callers can also perform bitwise operations between multiple cpumasks using bpf_cpumask_and(), bpf_cpumask_or(), and bpf_cpumask_xor():


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

```c
__bpf_kfunc bool bpf_cpumask_and(struct bpf_cpumask *dst, const struct cpumask *src1, const struct cpumask *src2)
```

AND two cpumasks and store the result.

**Parameters**

- `struct bpf_cpumask *dst`: The BPF cpumask where the result is being stored.
- `const struct cpumask *src1`: The first input.
- `const struct cpumask *src2`: The second input.

**Return**

* true  - **dst** has at least one bit set following the operation
* false - **dst** is empty following the operation

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

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

```c
__bpf_kfunc void bpf_cpumask_or(struct bpf_cpumask *dst, const struct cpumask *src1, const struct cpumask *src2)
```

OR two cpumasks and store the result.

**Parameters**

- `struct bpf_cpumask *dst`: The BPF cpumask where the result is being stored.
- `const struct cpumask *src1`: The first input.
- `const struct cpumask *src2`: The second input.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

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

```c
__bpf_kfunc void bpf_cpumask_xor(struct bpf_cpumask *dst, const struct cpumask *src1, const struct cpumask *src2)
```

XOR two cpumasks and store the result.

**Parameters**

- `struct bpf_cpumask *dst`: The BPF cpumask where the result is being stored.
- `const struct cpumask *src1`: The first input.
- `const struct cpumask *src2`: The second input.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.


The following is an example of how they may be used. Note that some of the kfuncs shown in this example will be covered in more detail below.



```c
/**
 * A sample tracepoint showing how a cpumask can be mutated using
   bitwise operators (and queried).
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(test_and_or_xor, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *mask1, *mask2, *dst1, *dst2;

        mask1 = bpf_cpumask_create();
        if (!mask1)
                return -ENOMEM;

        mask2 = bpf_cpumask_create();
        if (!mask2) {
                bpf_cpumask_release(mask1);
                return -ENOMEM;
        }

        // ...Safely create the other two masks... */

        bpf_cpumask_set_cpu(0, mask1);
        bpf_cpumask_set_cpu(1, mask2);
        bpf_cpumask_and(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_empty((const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_or(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_test_cpu(0, (const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        if (!bpf_cpumask_test_cpu(1, (const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_xor(dst2, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_equal((const struct cpumask *)dst1,
                               (const struct cpumask *)dst2))
                /* Should never happen. */
                goto release_exit;

 release_exit:
        bpf_cpumask_release(mask1);
        bpf_cpumask_release(mask2);
        bpf_cpumask_release(dst1);
        bpf_cpumask_release(dst2);
        return 0;
}
```

---

The contents of an entire cpumask may be copied to another using bpf_cpumask_copy():


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

```c
__bpf_kfunc void bpf_cpumask_copy(struct bpf_cpumask *dst, const struct cpumask *src)
```

Copy the contents of a cpumask into a BPF cpumask.

**Parameters**

- `struct bpf_cpumask *dst`: The BPF cpumask being copied into.
- `const struct cpumask *src`: The cpumask being copied.

**Description**

A struct bpf_cpumask pointer may be safely passed to **src**.


---

<a id="rst-querying-cpumasks"></a>
<a id="rst-cpumasks-querying-label"></a>

### 3.2 Querying cpumasks

In addition to the above kfuncs, there is also a set of read-only kfuncs that can be used to query the contents of cpumasks.


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

```c
__bpf_kfunc u32 bpf_cpumask_first(const struct cpumask *cpumask)
```

Get the index of the first nonzero bit in the cpumask.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being queried.

**Description**

Find the index of the first nonzero bit of the cpumask. A struct bpf_cpumask
pointer may be safely passed to this function.

**Return**

* The index of the first nonzero bit in the struct cpumask.

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

```c
__bpf_kfunc u32 bpf_cpumask_first_zero(const struct cpumask *cpumask)
```

Get the index of the first unset bit in the cpumask.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being queried.

**Description**

Find the index of the first unset bit of the cpumask. A struct bpf_cpumask
pointer may be safely passed to this function.

**Return**

* The index of the first zero bit in the struct cpumask.

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

```c
__bpf_kfunc u32 bpf_cpumask_first_and(const struct cpumask *src1, const struct cpumask *src2)
```

Return the index of the first nonzero bit from the AND of two cpumasks.

**Parameters**

- `const struct cpumask *src1`: The first cpumask.
- `const struct cpumask *src2`: The second cpumask.

**Description**

Find the index of the first nonzero bit of the AND of two cpumasks.
struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

**Return**

* The index of the first bit that is nonzero in both cpumask instances.

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

```c
__bpf_kfunc bool bpf_cpumask_test_cpu(u32 cpu, const struct cpumask *cpumask)
```

Test whether a CPU is set in a cpumask.

**Parameters**

- `u32 cpu`: The CPU being queried for.
- `const struct cpumask *cpumask`: The cpumask being queried for containing a CPU.

**Return**

* true  - **cpu** is set in the cpumask
* false - **cpu** was not set in the cpumask, or **cpu** is an invalid cpu.

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

```c
__bpf_kfunc u32 bpf_cpumask_weight(const struct cpumask *cpumask)
```

Return the number of bits in **cpumask**.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being queried.

**Description**

Count the number of set bits in the given cpumask.

**Return**

* The number of bits set in the mask.



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

```c
__bpf_kfunc bool bpf_cpumask_equal(const struct cpumask *src1, const struct cpumask *src2)
```

Check two cpumasks for equality.

**Parameters**

- `const struct cpumask *src1`: The first input.
- `const struct cpumask *src2`: The second input.

**Return**

* true   - **src1** and **src2** have the same bits set.
* false  - **src1** and **src2** differ in at least one bit.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

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

```c
__bpf_kfunc bool bpf_cpumask_intersects(const struct cpumask *src1, const struct cpumask *src2)
```

Check two cpumasks for overlap.

**Parameters**

- `const struct cpumask *src1`: The first input.
- `const struct cpumask *src2`: The second input.

**Return**

* true   - **src1** and **src2** have at least one of the same bits set.
* false  - **src1** and **src2** don't have any of the same bits set.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

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

```c
__bpf_kfunc bool bpf_cpumask_subset(const struct cpumask *src1, const struct cpumask *src2)
```

Check if a cpumask is a subset of another.

**Parameters**

- `const struct cpumask *src1`: The first cpumask being checked as a subset.
- `const struct cpumask *src2`: The second cpumask being checked as a superset.

**Return**

* true   - All of the bits of **src1** are set in **src2**.
* false  - At least one bit in **src1** is not set in **src2**.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.

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

```c
__bpf_kfunc bool bpf_cpumask_empty(const struct cpumask *cpumask)
```

Check if a cpumask is empty.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being checked.

**Return**

* true   - None of the bits in **cpumask** are set.
* false  - At least one bit in **cpumask** is set.

**Description**

A struct bpf_cpumask pointer may be safely passed to **cpumask**.

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

```c
__bpf_kfunc bool bpf_cpumask_full(const struct cpumask *cpumask)
```

Check if a cpumask has all bits set.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being checked.

**Return**

* true   - All of the bits in **cpumask** are set.
* false  - At least one bit in **cpumask** is cleared.

**Description**

A struct bpf_cpumask pointer may be safely passed to **cpumask**.



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

```c
__bpf_kfunc u32 bpf_cpumask_any_distribute(const struct cpumask *cpumask)
```

Return a random set CPU from a cpumask.

**Parameters**

- `const struct cpumask *cpumask`: The cpumask being queried.

**Return**

* A random set bit within \[0, num_cpus) if at least one bit is set.
* >= num_cpus if no bit is set.

**Description**

A struct bpf_cpumask pointer may be safely passed to **src**.

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

```c
__bpf_kfunc u32 bpf_cpumask_any_and_distribute(const struct cpumask *src1, const struct cpumask *src2)
```

Return a random set CPU from the AND of two cpumasks.

**Parameters**

- `const struct cpumask *src1`: The first cpumask.
- `const struct cpumask *src2`: The second cpumask.

**Return**

* A random set bit within \[0, num_cpus) from the AND of two cpumasks, if at
  least one bit is set.
* >= num_cpus if no bit is set.

**Description**

struct bpf_cpumask pointers may be safely passed to **src1** and **src2**.


---

Some example usages of these querying kfuncs were shown above. We will not replicate those examples here. Note, however, that all of the aforementioned kfuncs are tested in [tools/testing/selftests/bpf/progs/cpumask_success.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/progs/cpumask_success.c>), so please take a look there if you're looking for more examples of how they can be used.

<a id="rst-tools-testing-selftests-bpf-progs-cpumask-success-c"></a>



<a id="rst-adding-bpf-cpumask-kfuncs"></a>

## 4. Adding BPF cpumask kfuncs

The set of supported BPF cpumask kfuncs are not (yet) a 1-1 match with the cpumask operations in include/linux/cpumask.h. Any of those cpumask operations could easily be encapsulated in a new kfunc if and when required. If you'd like to support a new cpumask operation, please feel free to submit a patch. If you do add a new cpumask kfunc, please document it here, and add any relevant selftest testcases to the cpumask selftest suite.

---

# BPF drgn tools

_Peios Kernel / Internals / BPF_

> drgn scripts is a convenient and easy to use mechanism to retrieve arbitrary kernel data structures. drgn is not relying on kernel UAPI to read the data. Instead it's reading directly from /proc/kcore or vmcore and pretty prints the data…

<a id="rst-bpf-drgn-tools"></a>

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

drgn scripts is a convenient and easy to use mechanism to retrieve arbitrary kernel data structures. drgn is not relying on kernel UAPI to read the data. Instead it's reading directly from `/proc/kcore` or vmcore and pretty prints the data based on DWARF debug information from vmlinux.

This document describes BPF related drgn tools.

See [drgn/tools](<https://github.com/osandov/drgn/tree/master/tools>) for all tools available at the moment and [drgn/doc](<https://drgn.readthedocs.io/en/latest/>) for more details on drgn itself.

<a id="rst-bpf-inspect-py"></a>

## bpf_inspect.py

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

### Description

[bpf_inspect.py](<https://github.com/osandov/drgn/blob/master/tools/bpf_inspect.py>) is a tool intended to inspect BPF programs and maps. It can iterate over all programs and maps in the system and print basic information about these objects, including id, type and name.

The main use-case [bpf_inspect.py](<https://github.com/osandov/drgn/blob/master/tools/bpf_inspect.py>) covers is to show BPF programs of types `BPF_PROG_TYPE_EXT` and `BPF_PROG_TYPE_TRACING` attached to other BPF programs via `freplace`/`fentry`/`fexit` mechanisms, since there is no user-space API to get this information.

<a id="rst-getting-started"></a>

### Getting started

List BPF programs (full names are obtained from BTF):



```text
% sudo bpf_inspect.py prog
    27: BPF_PROG_TYPE_TRACEPOINT         tracepoint__tcp__tcp_send_reset
  4632: BPF_PROG_TYPE_CGROUP_SOCK_ADDR   tw_ipt_bind
 49464: BPF_PROG_TYPE_RAW_TRACEPOINT     raw_tracepoint__sched_process_exit
```

List BPF maps:



```text
% sudo bpf_inspect.py map
  2577: BPF_MAP_TYPE_HASH                tw_ipt_vips
  4050: BPF_MAP_TYPE_STACK_TRACE         stack_traces
  4069: BPF_MAP_TYPE_PERCPU_ARRAY        ned_dctcp_cntr
```

Find BPF programs attached to BPF program `test_pkt_access`:



```text
% sudo bpf_inspect.py p | grep test_pkt_access
   650: BPF_PROG_TYPE_SCHED_CLS          test_pkt_access
   654: BPF_PROG_TYPE_TRACING            test_main                        linked:[650->25: BPF_TRAMP_FEXIT test_pkt_access->test_pkt_access()]
   655: BPF_PROG_TYPE_TRACING            test_subprog1                    linked:[650->29: BPF_TRAMP_FEXIT test_pkt_access->test_pkt_access_subprog1()]
   656: BPF_PROG_TYPE_TRACING            test_subprog2                    linked:[650->31: BPF_TRAMP_FEXIT test_pkt_access->test_pkt_access_subprog2()]
   657: BPF_PROG_TYPE_TRACING            test_subprog3                    linked:[650->21: BPF_TRAMP_FEXIT test_pkt_access->test_pkt_access_subprog3()]
   658: BPF_PROG_TYPE_EXT                new_get_skb_len                  linked:[650->16: BPF_TRAMP_REPLACE test_pkt_access->get_skb_len()]
   659: BPF_PROG_TYPE_EXT                new_get_skb_ifindex              linked:[650->23: BPF_TRAMP_REPLACE test_pkt_access->get_skb_ifindex()]
   660: BPF_PROG_TYPE_EXT                new_get_constant                 linked:[650->19: BPF_TRAMP_REPLACE test_pkt_access->get_constant()]
```

It can be seen that there is a program `test_pkt_access`, id 650 and there are multiple other tracing and ext programs attached to functions in `test_pkt_access`.

For example the line:



```text
658: BPF_PROG_TYPE_EXT                new_get_skb_len                  linked:[650->16: BPF_TRAMP_REPLACE test_pkt_access->get_skb_len()]
```

, means that BPF program id 658, type `BPF_PROG_TYPE_EXT`, name `new_get_skb_len` replaces (`BPF_TRAMP_REPLACE`) function `get_skb_len()` that has BTF id 16 in BPF program id 650, name `test_pkt_access`.

Getting help:



```none
% sudo bpf_inspect.py
usage: bpf_inspect.py [-h] {prog,p,map,m} ...

drgn script to list BPF programs or maps and their properties
unavailable via kernel API.

See https://github.com/osandov/drgn/ for more details on drgn.

optional arguments:
  -h, --help      show this help message and exit

subcommands:
  {prog,p,map,m}
    prog (p)      list BPF programs
    map (m)       list BPF maps
```

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

### Customization

The script is intended to be customized by developers to print relevant information about BPF programs, maps and other objects.

For example, to print `struct bpf_prog_aux` for BPF program id 53077:



```none
% git diff
diff --git a/tools/bpf_inspect.py b/tools/bpf_inspect.py
index 650e228..aea2357 100755
--- a/tools/bpf_inspect.py
+++ b/tools/bpf_inspect.py
@@ -112,7 +112,9 @@ def list_bpf_progs(args):
         if linked:
             linked = f" linked:[{linked}]"

-        print(f"{id_:>6}: {type_:32} {name:32} {linked}")
+        if id_ == 53077:
+            print(f"{id_:>6}: {type_:32} {name:32}")
+            print(f"{bpf_prog.aux}")


 def list_bpf_maps(args):
```

It produces the output:



```text
% sudo bpf_inspect.py p
 53077: BPF_PROG_TYPE_XDP                tw_xdp_policer
*(struct bpf_prog_aux *)0xffff8893fad4b400 = {
        .refcnt = (atomic64_t){
                .counter = (long)58,
        },
        .used_map_cnt = (u32)1,
        .max_ctx_offset = (u32)8,
        .max_pkt_offset = (u32)15,
        .max_tp_access = (u32)0,
        .stack_depth = (u32)8,
        .id = (u32)53077,
        .func_cnt = (u32)0,
        .func_idx = (u32)0,
        .attach_btf_id = (u32)0,
        .linked_prog = (struct bpf_prog *)0x0,
        .verifier_zext = (bool)0,
        .offload_requested = (bool)0,
        .attach_btf_trace = (bool)0,
        .func_proto_unreliable = (bool)0,
        .trampoline_prog_type = (enum bpf_tramp_prog_type)BPF_TRAMP_FENTRY,
        .trampoline = (struct bpf_trampoline *)0x0,
        .tramp_hlist = (struct hlist_node){
                .next = (struct hlist_node *)0x0,
                .pprev = (struct hlist_node **)0x0,
        },
        .attach_func_proto = (const struct btf_type *)0x0,
        .attach_func_name = (const char *)0x0,
        .func = (struct bpf_prog **)0x0,
        .jit_data = (void *)0x0,
        .poke_tab = (struct bpf_jit_poke_descriptor *)0x0,
        .size_poke_tab = (u32)0,
        .ksym_tnode = (struct latch_tree_node){
                .node = (struct rb_node [2]){
                        {
                                .__rb_parent_color = (unsigned long)18446612956263126665,
                                .rb_right = (struct rb_node *)0x0,
                                .rb_left = (struct rb_node *)0xffff88a0be3d0088,
                        },
                        {
                                .__rb_parent_color = (unsigned long)18446612956263126689,
                                .rb_right = (struct rb_node *)0x0,
                                .rb_left = (struct rb_node *)0xffff88a0be3d00a0,
                        },
                },
        },
        .ksym_lnode = (struct list_head){
                .next = (struct list_head *)0xffff88bf481830b8,
                .prev = (struct list_head *)0xffff888309f536b8,
        },
        .ops = (const struct bpf_prog_ops *)xdp_prog_ops+0x0 = 0xffffffff820fa350,
        .used_maps = (struct bpf_map **)0xffff889ff795de98,
        .prog = (struct bpf_prog *)0xffffc9000cf2d000,
        .user = (struct user_struct *)root_user+0x0 = 0xffffffff82444820,
        .load_time = (u64)2408348759285319,
        .cgroup_storage = (struct bpf_map *[2]){},
        .name = (char [16])"tw_xdp_policer",
        .security = (void *)0xffff889ff795d548,
        .offload = (struct bpf_prog_offload *)0x0,
        .btf = (struct btf *)0xffff8890ce6d0580,
        .func_info = (struct bpf_func_info *)0xffff889ff795d240,
        .func_info_aux = (struct bpf_func_info_aux *)0xffff889ff795de20,
        .linfo = (struct bpf_line_info *)0xffff888a707afc00,
        .jited_linfo = (void **)0xffff8893fad48600,
        .func_info_cnt = (u32)1,
        .nr_linfo = (u32)37,
        .linfo_idx = (u32)0,
        .num_exentries = (u32)0,
        .extable = (struct exception_table_entry *)0xffffffffa032d950,
        .stats = (struct bpf_prog_stats *)0x603fe3a1f6d0,
        .work = (struct work_struct){
                .data = (atomic_long_t){
                        .counter = (long)0,
                },
                .entry = (struct list_head){
                        .next = (struct list_head *)0x0,
                        .prev = (struct list_head *)0x0,
                },
                .func = (work_func_t)0x0,
        },
        .rcu = (struct callback_head){
                .next = (struct callback_head *)0x0,
                .func = (void (*)(struct callback_head *))0x0,
        },
}
```

<!-- Links -->

<a id="rst-drgn-doc"></a>



<a id="rst-drgn-tools"></a>



<a id="rst-bpf-inspect-py-1"></a>

---

# Frequently asked questions (FAQ)

_Peios Kernel / Internals / BPF_

> Two sets of Questions and Answers (Q&A) are maintained.

<a id="rst-frequently-asked-questions-faq"></a>

Two sets of Questions and Answers (Q&amp;A) are maintained.

- [BPF Design Q&amp;A](</kernel/internals/bpf/bpf-design-qa.md>)
- [HOWTO interact with BPF subsystem](</kernel/internals/bpf/bpf-devel-qa.md>)

---

# BPF filesystem kfuncs

_Peios Kernel / Internals / BPF_

> BPF LSM programs need to access filesystem data from LSM hooks. The following BPF kfuncs can be used to get these data.

<a id="rst-bpf-filesystem-kfuncs"></a>
<a id="rst-fs-kfuncs-header-label"></a>

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

BPF LSM programs need to access filesystem data from LSM hooks. The following BPF kfuncs can be used to get these data.

> - `bpf_get_file_xattr()`
>
> - `bpf_get_fsverity_digest()`

To avoid recursions, these kfuncs follow the following rules:

1. These kfuncs are only permitted from BPF LSM function.

2. These kfuncs should not call into other LSM hooks, i.e. security\_\*(). For example, `bpf_get_file_xattr()` does not use `vfs_getxattr()`, because the latter calls LSM hook `security_inode_getxattr`.

---

# BPF Graph Data Structures

_Peios Kernel / Internals / BPF_

> This document describes implementation details of new-style "graph" data structures (linked_list, rbtree), with particular focus on the verifier's implementation of semantics specific to those data structures.

<a id="rst-bpf-graph-data-structures"></a>

This document describes implementation details of new-style "graph" data structures (linked_list, rbtree), with particular focus on the verifier's implementation of semantics specific to those data structures.

Although no specific verifier code is referred to in this document, the document assumes that the reader has general knowledge of BPF verifier internals, BPF maps, and BPF program writing.

Note that the intent of this document is to describe the current state of these graph data structures. **No guarantees** of stability for either semantics or APIs are made or implied here.

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



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

## Introduction

The BPF map API has historically been the main way to expose data structures of various types for use within BPF programs. Some data structures fit naturally with the map API (HASH, ARRAY), others less so. Consequently, programs interacting with the latter group of data structures can be hard to parse for kernel programmers without previous BPF experience.

Luckily, some restrictions which necessitated the use of BPF map semantics are no longer relevant. With the introduction of kfuncs, kptrs, and the any-context BPF allocator, it is now possible to implement BPF data structures whose API and semantics more closely match those exposed to the rest of the kernel.

Two such data structures - linked_list and rbtree - have many verification details in common. Because both have "root"s ("head" for linked_list) and "node"s, the verifier code and this document refer to common functionality as "graph_api", "graph_root", "graph_node", etc.

Unless otherwise stated, examples and semantics below apply to both graph data structures.

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

## Unstable API

Data structures implemented using the BPF map API have historically used BPF helper functions - either standard map API helpers like `bpf_map_update_elem` or map-specific helpers. The new-style graph data structures instead use kfuncs to define their manipulation helpers. Because there are no stability guarantees for kfuncs, the API and semantics for these data structures can be evolved in a way that breaks backwards compatibility if necessary.

Root and node types for the new data structures are opaquely defined in the `uapi/linux/bpf.h` header.

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

## Locking

The new-style data structures are intrusive and are defined similarly to their vanilla kernel counterparts:



```c
struct node_data {
  long key;
  long data;
  struct bpf_rb_node node;
};

struct bpf_spin_lock glock;
struct bpf_rb_root groot __contains(node_data, node);
```

The "root" type for both linked_list and rbtree expects to be in a map_value which also contains a `bpf_spin_lock` - in the above example both global variables are placed in a single-value arraymap. The verifier considers this spin_lock to be associated with the `bpf_rb_root` by virtue of both being in the same map_value and will enforce that the correct lock is held when verifying BPF programs that manipulate the tree. Since this lock checking happens at verification time, there is no runtime penalty.

<a id="rst-non-owning-references"></a>

## Non-owning references

**Motivation**

Consider the following BPF code:



```c
struct node_data *n = bpf_obj_new(typeof(*n)); /* ACQUIRED */

bpf_spin_lock(&lock);

bpf_rbtree_add(&tree, n); /* PASSED */

bpf_spin_unlock(&lock);
```

From the verifier's perspective, the pointer `n` returned from `bpf_obj_new` has type `PTR_TO_BTF_ID | MEM_ALLOC`, with a `btf_id` of `struct node_data` and a nonzero `ref_obj_id`. Because it holds `n`, the program has ownership of the pointee's (object pointed to by `n`) lifetime. The BPF program must pass off ownership before exiting - either via `bpf_obj_drop`, which `free`'s the object, or by adding it to `tree` with `bpf_rbtree_add`.

(`ACQUIRED` and `PASSED` comments in the example denote statements where "ownership is acquired" and "ownership is passed", respectively)

What should the verifier do with `n` after ownership is passed off? If the object was `free`'d with `bpf_obj_drop` the answer is obvious: the verifier should reject programs which attempt to access `n` after `bpf_obj_drop` as the object is no longer valid. The underlying memory may have been reused for some other allocation, unmapped, etc.

When ownership is passed to `tree` via `bpf_rbtree_add` the answer is less obvious. The verifier could enforce the same semantics as for `bpf_obj_drop`, but that would result in programs with useful, common coding patterns being rejected, e.g.:



```c
int x;
struct node_data *n = bpf_obj_new(typeof(*n)); /* ACQUIRED */

bpf_spin_lock(&lock);

bpf_rbtree_add(&tree, n); /* PASSED */
x = n->data;
n->data = 42;

bpf_spin_unlock(&lock);
```

Both the read from and write to `n->data` would be rejected. The verifier can do better, though, by taking advantage of two details:

> - Graph data structure APIs can only be used when the `bpf_spin_lock` associated with the graph root is held
>
> - Both graph data structures have pointer stability
>
>   > - Because graph nodes are allocated with `bpf_obj_new` and adding / removing from the root involves fiddling with the `bpf_{list,rb}_node` field of the node struct, a graph node will remain at the same address after either operation.

Because the associated `bpf_spin_lock` must be held by any program adding or removing, if we're in the critical section bounded by that lock, we know that no other program can add or remove until the end of the critical section. This combined with pointer stability means that, until the critical section ends, we can safely access the graph node through `n` even after it was used to pass ownership.

The verifier considers such a reference a *non-owning reference*. The ref returned by `bpf_obj_new` is accordingly considered an *owning reference*. Both terms currently only have meaning in the context of graph nodes and API.

**Details**

Let's enumerate the properties of both types of references.

*owning reference*

> - This reference controls the lifetime of the pointee
>
> - Ownership of pointee must be 'released' by passing it to some graph API kfunc, or via `bpf_obj_drop`, which `free`'s the pointee
>
>   - If not released before program ends, verifier considers program invalid
>
> - Access to the pointee's memory will not page fault

*non-owning reference*

> - This reference does not own the pointee
>
>   > - It cannot be used to add the graph node to a graph root, nor `free`'d via `bpf_obj_drop`
>
> - No explicit control of lifetime, but can infer valid lifetime based on non-owning ref existence (see explanation below)
>
> - Access to the pointee's memory will not page fault

From verifier's perspective non-owning references can only exist between spin_lock and spin_unlock. Why? After spin_unlock another program can do arbitrary operations on the data structure like removing and `free`-ing via bpf_obj_drop. A non-owning ref to some chunk of memory that was remove'd, `free`'d, and reused via bpf_obj_new would point to an entirely different thing. Or the memory could go away.

To prevent this logic violation all non-owning references are invalidated by the verifier after a critical section ends. This is necessary to ensure the "will not page fault" property of non-owning references. So if the verifier hasn't invalidated a non-owning ref, accessing it will not page fault.

Currently `bpf_obj_drop` is not allowed in the critical section, so if there's a valid non-owning ref, we must be in a critical section, and can conclude that the ref's memory hasn't been dropped-and- `free`'d or dropped-and-reused.

Any reference to a node that is in an rbtree \_must\_ be non-owning, since the tree has control of the pointee's lifetime. Similarly, any ref to a node that isn't in rbtree \_must\_ be owning. This results in a nice property: graph API add / remove implementations don't need to check if a node has already been added (or already removed), as the ownership model allows the verifier to prevent such a state from being valid by simply checking types.

However, pointer aliasing poses an issue for the above "nice property". Consider the following example:



```c
struct node_data *n, *m, *o, *p;
n = bpf_obj_new(typeof(*n));     /* 1 */

bpf_spin_lock(&lock);

bpf_rbtree_add(&tree, n);        /* 2 */
m = bpf_rbtree_first(&tree);     /* 3 */

o = bpf_rbtree_remove(&tree, n); /* 4 */
p = bpf_rbtree_remove(&tree, m); /* 5 */

bpf_spin_unlock(&lock);

bpf_obj_drop(o);
bpf_obj_drop(p); /* 6 */
```

Assume the tree is empty before this program runs. If we track verifier state changes here using numbers in above comments:

> 1. n is an owning reference
>
> 2. n is a non-owning reference, it's been added to the tree
>
> 3. n and m are non-owning references, they both point to the same node
>
> 4. o is an owning reference, n and m non-owning, all point to same node
>
> 5. o and p are owning, n and m non-owning, all point to the same node
>
> 6. a double-free has occurred, since o and p point to same node and o was `free`'d in previous statement

States 4 and 5 violate our "nice property", as there are non-owning refs to a node which is not in an rbtree. Statement 5 will try to remove a node which has already been removed as a result of this violation. State 6 is a dangerous double-free.

At a minimum we should prevent state 6 from being possible. If we can't also prevent state 5 then we must abandon our "nice property" and check whether a node has already been removed at runtime.

We prevent both by generalizing the "invalidate non-owning references" behavior of `bpf_spin_unlock` and doing similar invalidation after `bpf_rbtree_remove`. The logic here being that any graph API kfunc which:

> - takes an arbitrary node argument
>
> - removes it from the data structure
>
> - returns an owning reference to the removed node

May result in a state where some other non-owning reference points to the same node. So `remove`-type kfuncs must be considered a non-owning reference invalidation point as well.

---

# Helper functions

_Peios Kernel / Internals / BPF_

> bpf-helpers(7) maintains a list of helpers available to eBPF programs.

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

- [bpf-helpers(7)](<https://man7.org/linux/man-pages/man7/bpf-helpers.7.html>) maintains a list of helpers available to eBPF programs.

<!-- Links -->

<a id="rst-bpf-helpers-7"></a>

---

# BPF Kernel Functions (kfuncs)

_Peios Kernel / Internals / BPF_

> BPF Kernel Functions or more commonly known as kfuncs are functions in the Linux kernel which are exposed for use by BPF programs. Unlike normal BPF helpers, kfuncs do not have a stable interface and can change from one kernel release to…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-bpf-kernel-functions-kfuncs"></a>
<a id="rst-kfuncs-header-label"></a>

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

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

## 1. Introduction

BPF Kernel Functions or more commonly known as kfuncs are functions in the Linux kernel which are exposed for use by BPF programs. Unlike normal BPF helpers, kfuncs do not have a stable interface and can change from one kernel release to another. Hence, BPF programs need to be updated in response to changes in the kernel. See [3. kfunc lifecycle expectations](<#rst-bpf-kfunc-lifecycle-expectations>) for more information.

<a id="rst-defining-a-kfunc"></a>

## 2. Defining a kfunc

There are two ways to expose a kernel function to BPF programs, either make an existing function in the kernel visible, or add a new wrapper for BPF. In both cases, care must be taken that BPF program can only call such function in a valid context. To enforce this, visibility of a kfunc can be per program type.

If you are not creating a BPF wrapper for existing kernel function, skip ahead to [2.4 Using an existing kernel function](<#rst-bpf-kfunc-nodef>).

<a id="rst-creating-a-wrapper-kfunc"></a>

### 2.1 Creating a wrapper kfunc

When defining a wrapper kfunc, the wrapper function should have extern linkage. This prevents the compiler from optimizing away dead code, as this wrapper kfunc is not invoked anywhere in the kernel itself. It is not necessary to provide a prototype in a header for the wrapper kfunc.

An example is given below:



```text
/* Disables missing prototype warnings */
__bpf_kfunc_start_defs();

__bpf_kfunc struct task_struct *bpf_find_get_task_by_vpid(pid_t nr)
{
        return find_get_task_by_vpid(nr);
}

__bpf_kfunc_end_defs();
```

A wrapper kfunc is often needed when we need to annotate parameters of the kfunc. Otherwise one may directly make the kfunc visible to the BPF program by registering it with the BPF subsystem. See [2.4 Using an existing kernel function](<#rst-bpf-kfunc-nodef>).

<a id="rst-kfunc-parameters"></a>

### 2.2 kfunc Parameters

All kfuncs now require trusted arguments by default. This means that all pointer arguments must be valid, and all pointers to BTF objects must be passed in their unmodified form (at a zero offset, and without having been obtained from walking another pointer, with exceptions described below).

There are two types of pointers to kernel objects which are considered "trusted":

1. Pointers which are passed as tracepoint or struct_ops callback arguments.

2. Pointers which were returned from a KF_ACQUIRE kfunc.

Pointers to non-BTF objects (e.g. scalar pointers) may also be passed to kfuncs, and may have a non-zero offset.

The definition of "valid" pointers is subject to change at any time, and has absolutely no ABI stability guarantees.

As mentioned above, a nested pointer obtained from walking a trusted pointer is no longer trusted, with one exception. If a struct type has a field that is guaranteed to be valid (trusted or rcu, as in KF_RCU description below) as long as its parent pointer is valid, the following macros can be used to express that to the verifier:

- `BTF_TYPE_SAFE_TRUSTED`

- `BTF_TYPE_SAFE_RCU`

- `BTF_TYPE_SAFE_RCU_OR_NULL`

For example,



```c
BTF_TYPE_SAFE_TRUSTED(struct socket) {
        struct sock *sk;
};
```

or



```c
BTF_TYPE_SAFE_RCU(struct task_struct) {
        const cpumask_t *cpus_ptr;
        struct css_set __rcu *cgroups;
        struct task_struct __rcu *real_parent;
        struct task_struct *group_leader;
};
```

In other words, you must:

1. Wrap the valid pointer type in a `BTF_TYPE_SAFE_*` macro.

2. Specify the type and name of the valid nested field. This field must match the field in the original type definition exactly.

A new type declared by a `BTF_TYPE_SAFE_*` macro also needs to be emitted so that it appears in BTF. For example, `BTF_TYPE_SAFE_TRUSTED(struct socket)` is emitted in the `type_is_trusted()` function as follows:



```c
BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
```

<a id="rst-annotating-kfunc-parameters"></a>

### 2.3 Annotating kfunc parameters

Similar to BPF helpers, there is sometime need for additional context required by the verifier to make the usage of kernel functions safer and more useful. Hence, we can annotate a parameter by suffixing the name of the argument of the kfunc with a \__tag, where tag may be one of the supported annotations.

<a id="rst-sz-annotation"></a>

### 2.3.1 \__sz Annotation

This annotation is used to indicate a memory and size pair in the argument list. An example is given below:



```text
__bpf_kfunc void bpf_memzero(void *mem, int mem__sz)
{
...
}
```

Here, the verifier will treat first argument as a PTR_TO_MEM, and second argument as its size. By default, without \__sz annotation, the size of the type of the pointer is used. Without \__sz annotation, a kfunc cannot accept a void pointer.

<a id="rst-k-annotation"></a>

### 2.3.2 \__k Annotation

This annotation is only understood for scalar arguments, where it indicates that the verifier must check the scalar argument to be a known constant, which does not indicate a size parameter, and the value of the constant is relevant to the safety of the program.

An example is given below:



```text
__bpf_kfunc void *bpf_obj_new(u32 local_type_id__k, ...)
{
...
}
```

Here, bpf_obj_new uses local_type_id argument to find out the size of that type ID in program's BTF and return a sized pointer to it. Each type ID will have a distinct size, hence it is crucial to treat each such call as distinct when values don't match during verifier state pruning checks.

Hence, whenever a constant scalar argument is accepted by a kfunc which is not a size parameter, and the value of the constant matters for program safety, \__k suffix should be used.

<a id="rst-uninit-annotation"></a>

### 2.3.3 \__uninit Annotation

This annotation is used to indicate that the argument will be treated as uninitialized.

An example is given below:



```text
__bpf_kfunc int bpf_dynptr_from_skb(..., struct bpf_dynptr_kern *ptr__uninit)
{
...
}
```

Here, the dynptr will be treated as an uninitialized dynptr. Without this annotation, the verifier will reject the program if the dynptr passed in is not initialized.

<a id="rst-nullable-annotation"></a>

### 2.3.4 \__nullable Annotation

This annotation is used to indicate that the pointer argument may be NULL. The verifier will allow passing NULL for such arguments.

An example is given below:



```text
__bpf_kfunc void bpf_task_release(struct task_struct *task__nullable)
{
...
}
```

Here, the task pointer may be NULL. The kfunc is responsible for checking if the pointer is NULL before dereferencing it.

The \__nullable annotation can be combined with other annotations. For example, when used with \__sz or \__szk annotations for memory and size pairs, the verifier will skip size validation when a NULL pointer is passed, but will still process the size argument to extract constant size information when needed:



```text
__bpf_kfunc void *bpf_dynptr_slice(..., void *buffer__nullable,
                                   u32 buffer__szk)
```

Here, the buffer may be NULL. If the buffer is not NULL, it must be at least buffer__szk bytes in size. The kfunc is responsible for checking if the buffer is NULL before using it.

<a id="rst-str-annotation"></a>

### 2.3.5 \__str Annotation

This annotation is used to indicate that the argument is a constant string.

An example is given below:



```text
__bpf_kfunc bpf_get_file_xattr(..., const char *name__str, ...)
{
...
}
```

In this case, `bpf_get_file_xattr()` can be called as:



```text
bpf_get_file_xattr(..., "xattr_name", ...);
```

Or:



```text
const char name[] = "xattr_name";  /* This need to be global */
int BPF_PROG(...)
{
        ...
        bpf_get_file_xattr(..., name, ...);
        ...
}
```

<a id="rst-using-an-existing-kernel-function"></a>
<a id="rst-bpf-kfunc-nodef"></a>

### 2.4 Using an existing kernel function

When an existing function in the kernel is fit for consumption by BPF programs, it can be directly registered with the BPF subsystem. However, care must still be taken to review the context in which it will be invoked by the BPF program and whether it is safe to do so.

<a id="rst-annotating-kfuncs"></a>

### 2.5 Annotating kfuncs

In addition to kfuncs' arguments, verifier may need more information about the type of kfunc(s) being registered with the BPF subsystem. To do so, we define flags on a set of kfuncs as follows:



```text
BTF_KFUNCS_START(bpf_task_set)
BTF_ID_FLAGS(func, bpf_get_task_pid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_put_pid, KF_RELEASE)
BTF_KFUNCS_END(bpf_task_set)
```

This set encodes the BTF ID of each kfunc listed above, and encodes the flags along with it. Ofcourse, it is also allowed to specify no flags.

kfunc definitions should also always be annotated with the `__bpf_kfunc` macro. This prevents issues such as the compiler inlining the kfunc if it's a static kernel function, or the function being elided in an LTO build as it's not used in the rest of the kernel. Developers should not manually add annotations to their kfunc to prevent these issues. If an annotation is required to prevent such an issue with your kfunc, it is a bug and should be added to the definition of the macro so that other kfuncs are similarly protected. An example is given below:



```text
__bpf_kfunc struct task_struct *bpf_get_task_pid(s32 pid)
{
...
}
```

<a id="rst-kf-acquire-flag"></a>

### 2.5.1 KF_ACQUIRE flag

The KF_ACQUIRE flag is used to indicate that the kfunc returns a pointer to a refcounted object. The verifier will then ensure that the pointer to the object is eventually released using a release kfunc, or transferred to a map using a referenced kptr (by invoking bpf_kptr_xchg). If not, the verifier fails the loading of the BPF program until no lingering references remain in all possible explored states of the program.

<a id="rst-kf-ret-null-flag"></a>

### 2.5.2 KF_RET_NULL flag

The KF_RET_NULL flag is used to indicate that the pointer returned by the kfunc may be NULL. Hence, it forces the user to do a NULL check on the pointer returned from the kfunc before making use of it (dereferencing or passing to another helper). This flag is often used in pairing with KF_ACQUIRE flag, but both are orthogonal to each other.

<a id="rst-kf-release-flag"></a>

### 2.5.3 KF_RELEASE flag

The KF_RELEASE flag is used to indicate that the kfunc releases the pointer passed in to it. There can be only one referenced pointer that can be passed in. All copies of the pointer being released are invalidated as a result of invoking kfunc with this flag.

<a id="rst-kf-sleepable-flag"></a>

### 2.5.4 KF_SLEEPABLE flag

The KF_SLEEPABLE flag is used for kfuncs that may sleep. Such kfuncs can only be called by sleepable BPF programs (BPF_F_SLEEPABLE).

<a id="rst-kf-destructive-flag"></a>

### 2.5.5 KF_DESTRUCTIVE flag

The KF_DESTRUCTIVE flag is used to indicate functions calling which is destructive to the system. For example such a call can result in system rebooting or panicking. Due to this additional restrictions apply to these calls. At the moment they only require CAP_SYS_BOOT capability, but more can be added later.

<a id="rst-kf-rcu-flag"></a>

### 2.5.6 KF_RCU flag

The KF_RCU flag allows kfuncs to opt out of the default trusted args requirement and accept RCU pointers with weaker guarantees. The kfuncs marked with KF_RCU expect either PTR_TRUSTED or MEM_RCU arguments. The verifier guarantees that the objects are valid and there is no use-after-free. The pointers are not NULL, but the object's refcount could have reached zero. The kfuncs need to consider doing refcnt \!= 0 check, especially when returning a KF_ACQUIRE pointer. Note as well that a KF_ACQUIRE kfunc that is KF_RCU should very likely also be KF_RET_NULL.

<a id="rst-kf-rcu-protected-flag"></a>

### 2.5.7 KF_RCU_PROTECTED flag

The KF_RCU_PROTECTED flag is used to indicate that the kfunc must be invoked in an RCU critical section. This is assumed by default in non-sleepable programs, and must be explicitly ensured by calling `bpf_rcu_read_lock` for sleepable ones.

If the kfunc returns a pointer value, this flag also enforces that the returned pointer is RCU protected, and can only be used while the RCU critical section is active.

The flag is distinct from the `KF_RCU` flag, which only ensures that its arguments are at least RCU protected pointers. This may transitively imply that RCU protection is ensured, but it does not work in cases of kfuncs which require RCU protection but do not take RCU protected arguments.

<a id="rst-kf-deprecated-flag-1"></a>
<a id="rst-kf-deprecated-flag"></a>

### 2.5.8 KF_DEPRECATED flag

The KF_DEPRECATED flag is used for kfuncs which are scheduled to be changed or removed in a subsequent kernel release. A kfunc that is marked with KF_DEPRECATED should also have any relevant information captured in its kernel doc. Such information typically includes the kfunc's expected remaining lifespan, a recommendation for new functionality that can replace it if any is available, and possibly a rationale for why it is being removed.

Note that while on some occasions, a KF_DEPRECATED kfunc may continue to be supported and have its KF_DEPRECATED flag removed, it is likely to be far more difficult to remove a KF_DEPRECATED flag after it's been added than it is to prevent it from being added in the first place. As described in [3. kfunc lifecycle expectations](<#rst-bpf-kfunc-lifecycle-expectations>), users that rely on specific kfuncs are encouraged to make their use-cases known as early as possible, and participate in upstream discussions regarding whether to keep, change, deprecate, or remove those kfuncs if and when such discussions occur.

<a id="rst-kf-implicit-args-flag"></a>

### 2.5.9 KF_IMPLICIT_ARGS flag

The KF_IMPLICIT_ARGS flag is used to indicate that the BPF signature of the kfunc is different from it's kernel signature, and the values for implicit arguments are provided at load time by the verifier.

Only arguments of specific types are implicit. Currently only `struct bpf_prog_aux *` type is supported.

A kfunc with KF_IMPLICIT_ARGS flag therefore has two types in BTF: one function matching the kernel declaration (with \_impl suffix in the name by convention), and another matching the intended BPF API.

Verifier only allows calls to the non-\_impl version of a kfunc, that uses a signature without the implicit arguments.

Example declaration:



```c
__bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct bpf_task_work *tw,
                                              void *map__map, bpf_task_work_callback_t callback,
                                              struct bpf_prog_aux *aux) { ... }
```

Example usage in BPF program:



```c
/* note that the last argument is omitted */
bpf_task_work_schedule_signal(task, &work->tw, &arrmap, task_work_callback);
```

<a id="rst-registering-the-kfuncs"></a>

### 2.6 Registering the kfuncs

Once the kfunc is prepared for use, the final step to making it visible is registering it with the BPF subsystem. Registration is done per BPF program type. An example is shown below:



```text
BTF_KFUNCS_START(bpf_task_set)
BTF_ID_FLAGS(func, bpf_get_task_pid, KF_ACQUIRE | KF_RET_NULL)
BTF_ID_FLAGS(func, bpf_put_pid, KF_RELEASE)
BTF_KFUNCS_END(bpf_task_set)

static const struct btf_kfunc_id_set bpf_task_kfunc_set = {
        .owner = THIS_MODULE,
        .set   = &bpf_task_set,
};

static int init_subsystem(void)
{
        return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_task_kfunc_set);
}
late_initcall(init_subsystem);
```

<a id="rst-specifying-no-cast-aliases-with-init"></a>

### 2.7  Specifying no-cast aliases with \___init

The verifier will always enforce that the BTF type of a pointer passed to a kfunc by a BPF program, matches the type of pointer specified in the kfunc definition. The verifier, does, however, allow types that are equivalent according to the C standard to be passed to the same kfunc arg, even if their BTF_IDs differ.

For example, for the following type definition:



```c
struct bpf_cpumask {
        cpumask_t cpumask;
        refcount_t usage;
};
```

The verifier would allow a `struct bpf_cpumask *` to be passed to a kfunc taking a `cpumask_t *` (which is a typedef of `struct cpumask *`). For instance, both `struct cpumask *` and `struct bpf_cpmuask *` can be passed to bpf_cpumask_test_cpu().

In some cases, this type-aliasing behavior is not desired. `struct nf_conn___init` is one such example:



```c
struct nf_conn___init {
        struct nf_conn ct;
};
```

The C standard would consider these types to be equivalent, but it would not always be safe to pass either type to a trusted kfunc. `struct nf_conn___init` represents an allocated `struct nf_conn` object that has *not yet been initialized*, so it would therefore be unsafe to pass a `struct nf_conn___init *` to a kfunc that's expecting a fully initialized `struct nf_conn *` (e.g. `bpf_ct_change_timeout()`).

In order to accommodate such requirements, the verifier will enforce strict PTR_TO_BTF_ID type matching if two types have the exact same name, with one being suffixed with `___init`.

<a id="rst-kfunc-lifecycle-expectations"></a>
<a id="rst-bpf-kfunc-lifecycle-expectations"></a>

## 3. kfunc lifecycle expectations

kfuncs provide a kernel &lt;-&gt; kernel API, and thus are not bound by any of the strict stability restrictions associated with kernel &lt;-&gt; user UAPIs. This means they can be thought of as similar to EXPORT_SYMBOL_GPL, and can therefore be modified or removed by a maintainer of the subsystem they're defined in when it's deemed necessary.

Like any other change to the kernel, maintainers will not change or remove a kfunc without having a reasonable justification.  Whether or not they'll choose to change a kfunc will ultimately depend on a variety of factors, such as how widely used the kfunc is, how long the kfunc has been in the kernel, whether an alternative kfunc exists, what the norm is in terms of stability for the subsystem in question, and of course what the technical cost is of continuing to support the kfunc.

There are several implications of this:

- **a)** kfuncs that are widely used or have been in the kernel for a long time will be more difficult to justify being changed or removed by a maintainer. In other words, kfuncs that are known to have a lot of users and provide significant value provide stronger incentives for maintainers to invest the time and complexity in supporting them. It is therefore important for developers that are using kfuncs in their BPF programs to communicate and explain how and why those kfuncs are being used, and to participate in discussions regarding those kfuncs when they occur upstream.

- **b)** Unlike regular kernel symbols marked with EXPORT_SYMBOL_GPL, BPF programs that call kfuncs are generally not part of the kernel tree. This means that refactoring cannot typically change callers in-place when a kfunc changes, as is done for e.g. an upstreamed driver being updated in place when a kernel symbol is changed.

  Unlike with regular kernel symbols, this is expected behavior for BPF symbols, and out-of-tree BPF programs that use kfuncs should be considered relevant to discussions and decisions around modifying and removing those kfuncs. The BPF community will take an active role in participating in upstream discussions when necessary to ensure that the perspectives of such users are taken into account.

- **c)** A kfunc will never have any hard stability guarantees. BPF APIs cannot and will not ever hard-block a change in the kernel purely for stability reasons. That being said, kfuncs are features that are meant to solve problems and provide value to users. The decision of whether to change or remove a kfunc is a multivariate technical decision that is made on a case-by-case basis, and which is informed by data points such as those mentioned above. It is expected that a kfunc being removed or changed with no warning will not be a common occurrence or take place without sound justification, but it is a possibility that must be accepted if one is to use kfuncs.

<a id="rst-kfunc-deprecation"></a>

### 3.1 kfunc deprecation

As described above, while sometimes a maintainer may find that a kfunc must be changed or removed immediately to accommodate some changes in their subsystem, usually kfuncs will be able to accommodate a longer and more measured deprecation process. For example, if a new kfunc comes along which provides superior functionality to an existing kfunc, the existing kfunc may be deprecated for some period of time to allow users to migrate their BPF programs to use the new one. Or, if a kfunc has no known users, a decision may be made to remove the kfunc (without providing an alternative API) after some deprecation period so as to provide users with a window to notify the kfunc maintainer if it turns out that the kfunc is actually being used.

It's expected that the common case will be that kfuncs will go through a deprecation period rather than being changed or removed without warning. As described in [2.5.8 KF_DEPRECATED flag](<#rst-kf-deprecated-flag>), the kfunc framework provides the KF_DEPRECATED flag to kfunc developers to signal to users that a kfunc has been deprecated. Once a kfunc has been marked with KF_DEPRECATED, the following procedure is followed for removal:

1. Any relevant information for deprecated kfuncs is documented in the kfunc's kernel docs. This documentation will typically include the kfunc's expected remaining lifespan, a recommendation for new functionality that can replace the usage of the deprecated function (or an explanation as to why no such replacement exists), etc.

2. The deprecated kfunc is kept in the kernel for some period of time after it was first marked as deprecated. This time period will be chosen on a case-by-case basis, and will typically depend on how widespread the use of the kfunc is, how long it has been in the kernel, and how hard it is to move to alternatives. This deprecation time period is "best effort", and as described [above](<#rst-bpf-kfunc-lifecycle-expectations>), circumstances may sometimes dictate that the kfunc be removed before the full intended deprecation period has elapsed.

3. After the deprecation period the kfunc will be removed. At this point, BPF programs calling the kfunc will be rejected by the verifier.

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

## 4. Core kfuncs

The BPF subsystem provides a number of "core" kfuncs that are potentially applicable to a wide variety of different possible use cases and programs. Those kfuncs are documented here.

<a id="rst-struct-task-struct-kfuncs"></a>

### 4.1 struct task_struct \* kfuncs

There are a number of kfuncs that allow `struct task_struct *` objects to be used as kptrs:


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

```c
__bpf_kfunc struct task_struct * bpf_task_acquire(struct task_struct *p)
```

Acquire a reference to a task. A task acquired by this kfunc which is not stored in a map as a kptr, must be released by calling [`bpf_task_release()`](#c-bpf_task_release).

**Parameters**

- `struct task_struct *p`: The task on which a reference is being acquired.

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

```c
__bpf_kfunc void bpf_task_release(struct task_struct *p)
```

Release the reference acquired on a task.

**Parameters**

- `struct task_struct *p`: The task on which a reference is being released.


These kfuncs are useful when you want to acquire or release a reference to a `struct task_struct *` that was passed as e.g. a tracepoint arg, or a struct_ops callback arg. For example:



```c
/**
 * A trivial example tracepoint program that shows how to
 * acquire and release a struct task_struct * pointer.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(task_acquire_release_example, struct task_struct *task, u64 clone_flags)
{
        struct task_struct *acquired;

        acquired = bpf_task_acquire(task);
        if (acquired)
                /*
                 * In a typical program you'd do something like store
                 * the task in a map, and the map will automatically
                 * release it later. Here, we release it manually.
                 */
                bpf_task_release(acquired);
        return 0;
}
```

References acquired on `struct task_struct *` objects are RCU protected. Therefore, when in an RCU read region, you can obtain a pointer to a task embedded in a map value without having to acquire a reference:



```c
#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
private(TASK) static struct task_struct *global;

/**
 * A trivial example showing how to access a task stored
 * in a map using RCU.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(task_rcu_read_example, struct task_struct *task, u64 clone_flags)
{
        struct task_struct *local_copy;

        bpf_rcu_read_lock();
        local_copy = global;
        if (local_copy)
                /*
                 * We could also pass local_copy to kfuncs or helper functions here,
                 * as we're guaranteed that local_copy will be valid until we exit
                 * the RCU read region below.
                 */
                bpf_printk("Global task %s is valid", local_copy->comm);
        else
                bpf_printk("No global task found");
        bpf_rcu_read_unlock();

        /* At this point we can no longer reference local_copy. */

        return 0;
}
```

---

A BPF program can also look up a task from a pid. This can be useful if the caller doesn't have a trusted pointer to a `struct task_struct *` object that it can acquire a reference on with bpf_task_acquire().


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

```c
__bpf_kfunc struct task_struct * bpf_task_from_pid(s32 pid)
```

Find a struct task_struct from its pid by looking it up in the root pid namespace idr. If a task is returned, it must either be stored in a map, or released with [`bpf_task_release()`](#c-bpf_task_release).

**Parameters**

- `s32 pid`: The pid of the task being looked up.


Here is an example of it being used:



```c
SEC("tp_btf/task_newtask")
int BPF_PROG(task_get_pid_example, struct task_struct *task, u64 clone_flags)
{
        struct task_struct *lookup;

        lookup = bpf_task_from_pid(task->pid);
        if (!lookup)
                /* A task should always be found, as %task is a tracepoint arg. */
                return -ENOENT;

        if (lookup->pid != task->pid) {
                /* bpf_task_from_pid() looks up the task via its
                 * globally-unique pid from the init_pid_ns. Thus,
                 * the pid of the lookup task should always be the
                 * same as the input task.
                 */
                bpf_task_release(lookup);
                return -EINVAL;
        }

        /* bpf_task_from_pid() returns an acquired reference,
         * so it must be dropped before returning from the
         * tracepoint handler.
         */
        bpf_task_release(lookup);
        return 0;
}
```

<a id="rst-struct-cgroup-kfuncs"></a>

### 4.2 struct cgroup \* kfuncs

`struct cgroup *` objects also have acquire and release functions:


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

```c
__bpf_kfunc struct cgroup * bpf_cgroup_acquire(struct cgroup *cgrp)
```

Acquire a reference to a cgroup. A cgroup acquired by this kfunc which is not stored in a map as a kptr, must be released by calling [`bpf_cgroup_release()`](#c-bpf_cgroup_release).

**Parameters**

- `struct cgroup *cgrp`: The cgroup on which a reference is being acquired.

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

```c
__bpf_kfunc void bpf_cgroup_release(struct cgroup *cgrp)
```

Release the reference acquired on a cgroup. If this kfunc is invoked in an RCU read region, the cgroup is guaranteed to not be freed until the current grace period has ended, even if its refcount drops to 0.

**Parameters**

- `struct cgroup *cgrp`: The cgroup on which a reference is being released.


These kfuncs are used in exactly the same manner as bpf_task_acquire() and bpf_task_release() respectively, so we won't provide examples for them.

---

Other kfuncs available for interacting with `struct cgroup *` objects are bpf_cgroup_ancestor() and bpf_cgroup_from_id(), allowing callers to access the ancestor of a cgroup and find a cgroup by its ID, respectively. Both return a cgroup kptr.


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

```c
__bpf_kfunc struct cgroup * bpf_cgroup_ancestor(struct cgroup *cgrp, int level)
```

Perform a lookup on an entry in a cgroup's ancestor array. A cgroup returned by this kfunc which is not subsequently stored in a map, must be released by calling [`bpf_cgroup_release()`](#c-bpf_cgroup_release).

**Parameters**

- `struct cgroup *cgrp`: The cgroup for which we're performing a lookup.
- `int level`: The level of ancestor to look up.



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

```c
__bpf_kfunc struct cgroup * bpf_cgroup_from_id(u64 cgid)
```

Find a cgroup from its ID. A cgroup returned by this kfunc which is not subsequently stored in a map, must be released by calling [`bpf_cgroup_release()`](#c-bpf_cgroup_release).

**Parameters**

- `u64 cgid`: cgroup id.


Eventually, BPF should be updated to allow this to happen with a normal memory load in the program itself. This is currently not possible without more work in the verifier. bpf_cgroup_ancestor() can be used as follows:



```c
/**
 * Simple tracepoint example that illustrates how a cgroup's
 * ancestor can be accessed using bpf_cgroup_ancestor().
 */
SEC("tp_btf/cgroup_mkdir")
int BPF_PROG(cgrp_ancestor_example, struct cgroup *cgrp, const char *path)
{
        struct cgroup *parent;

        /* The parent cgroup resides at the level before the current cgroup's level. */
        parent = bpf_cgroup_ancestor(cgrp, cgrp->level - 1);
        if (!parent)
                return -ENOENT;

        bpf_printk("Parent id is %d", parent->self.id);

        /* Return the parent cgroup that was acquired above. */
        bpf_cgroup_release(parent);
        return 0;
}
```

<a id="rst-struct-cpumask-kfuncs"></a>

### 4.3 struct cpumask \* kfuncs

BPF provides a set of kfuncs that can be used to query, allocate, mutate, and destroy struct cpumask \* objects. Please refer to [BPF cpumask kfuncs](</kernel/internals/bpf/cpumasks.md#rst-cpumasks-header-label>) for more details.

---

# Contents

_Peios Kernel / Internals / BPF_

> 1 Linux implementation notes

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



<a id="rst-linux-implementation-notes"></a>

## 1   Linux implementation notes

This document provides more details specific to the Linux kernel implementation of the eBPF instruction set.

<a id="rst-byte-swap-instructions"></a>

### 1.1   Byte swap instructions

`BPF_FROM_LE` and `BPF_FROM_BE` exist as aliases for `BPF_TO_LE` and `BPF_TO_BE` respectively.

<a id="rst-jump-instructions"></a>

### 1.2   Jump instructions

`BPF_CALL | BPF_X | BPF_JMP` (0x8d), where the helper function integer would be read from a specified register, is not currently supported by the verifier.  Any programs with this instruction will fail to load until such support is added.

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

### 1.3   Maps

Linux only supports the 'map\_val(map)' operation on array maps with a single element.

Linux uses an fd\_array to store maps associated with a BPF program. Thus, map\_by\_idx(imm) uses the fd at that index in the array.

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

### 1.4   Variables

The following 64-bit immediate instruction specifies that a variable address, which corresponds to some integer stored in the 'imm' field, should be loaded:


<table>
<thead>
<tr>
<th>



opcode construction

</th>
<th>



opcode

</th>
<th>



src

</th>
<th>



pseudocode

</th>
<th>



imm type

</th>
<th>



dst type

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



BPF\_IMM \| BPF\_DW \| BPF\_LD

</td>
<td>



0x18

</td>
<td>



0x3

</td>
<td>



dst = var\_addr(imm)

</td>
<td>



variable id

</td>
<td>



data pointer

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

On Linux, this integer is a BTF ID.

<a id="rst-legacy-bpf-packet-access-instructions"></a>

### 1.5   Legacy BPF Packet access instructions

As mentioned in the [ISA standard documentation](</kernel/internals/bpf/standardization/instruction-set.md#rst-legacy-bpf-packet-access-instructions>)<a id="rst-isa-standard-documentation"></a>, Linux has special eBPF instructions for access to packet data that have been carried over from classic BPF to retain the performance of legacy socket filters running in the eBPF interpreter.

The instructions come in two forms: `BPF_ABS | <size> | BPF_LD` and `BPF_IND | <size> | BPF_LD`.

These instructions are used to access packet data and can only be used when the program context is a pointer to a networking packet.  `BPF_ABS` accesses packet data at an absolute offset specified by the immediate data and `BPF_IND` access packet data at an offset that includes the value of a register in addition to the immediate data.

These instructions have seven implicit operands:

- Register R6 is an implicit input that must contain a pointer to a struct sk\_buff.

- Register R0 is an implicit output which contains the data fetched from the packet.

- Registers R1-R5 are scratch registers that are clobbered by the instruction.

These instructions have an implicit program exit condition as well. If an eBPF program attempts access data beyond the packet boundary, the program execution will be aborted.

`BPF_ABS | BPF_W | BPF_LD` (0x20) means:



```text
R0 = ntohl(*(u32 *) ((struct sk_buff *) R6->data + imm))
```

where `ntohl()` converts a 32-bit value from network byte order to host byte order.

`BPF_IND | BPF_W | BPF_LD` (0x40) means:



```text
R0 = ntohl(*(u32 *) ((struct sk_buff *) R6->data + src + imm))
```

---

# BPF LLVM Relocations

_Peios Kernel / Internals / BPF_

> This document describes LLVM BPF backend relocation types.

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

<a id="rst-bpf-llvm-relocations"></a>

## BPF LLVM Relocations

This document describes LLVM BPF backend relocation types.

<a id="rst-relocation-record"></a>

### Relocation Record

LLVM BPF backend records each relocation with the following 16-byte ELF structure:



```text
typedef struct
{
  Elf64_Addr    r_offset;  // Offset from the beginning of section.
  Elf64_Xword   r_info;    // Relocation type and symbol index.
} Elf64_Rel;
```

For example, for the following code:



```text
int g1 __attribute__((section("sec")));
int g2 __attribute__((section("sec")));
static volatile int l1 __attribute__((section("sec")));
static volatile int l2 __attribute__((section("sec")));
int test() {
  return g1 + g2 + l1 + l2;
}
```

Compiled with `clang --target=bpf -O2 -c test.c`, the following is the code with `llvm-objdump -dr test.o`:



```text
 0:       18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll
          0000000000000000:  R_BPF_64_64  g1
 2:       61 11 00 00 00 00 00 00 r1 = *(u32 *)(r1 + 0)
 3:       18 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r2 = 0 ll
          0000000000000018:  R_BPF_64_64  g2
 5:       61 20 00 00 00 00 00 00 r0 = *(u32 *)(r2 + 0)
 6:       0f 10 00 00 00 00 00 00 r0 += r1
 7:       18 01 00 00 08 00 00 00 00 00 00 00 00 00 00 00 r1 = 8 ll
          0000000000000038:  R_BPF_64_64  sec
 9:       61 11 00 00 00 00 00 00 r1 = *(u32 *)(r1 + 0)
10:       0f 10 00 00 00 00 00 00 r0 += r1
11:       18 01 00 00 0c 00 00 00 00 00 00 00 00 00 00 00 r1 = 12 ll
          0000000000000058:  R_BPF_64_64  sec
13:       61 11 00 00 00 00 00 00 r1 = *(u32 *)(r1 + 0)
14:       0f 10 00 00 00 00 00 00 r0 += r1
15:       95 00 00 00 00 00 00 00 exit
```

There are four relocations in the above for four `LD_imm64` instructions. The following `llvm-readelf -r test.o` shows the binary values of the four relocations:



```text
Relocation section '.rel.text' at offset 0x190 contains 4 entries:
    Offset             Info             Type               Symbol's Value  Symbol's Name
0000000000000000  0000000600000001 R_BPF_64_64            0000000000000000 g1
0000000000000018  0000000700000001 R_BPF_64_64            0000000000000004 g2
0000000000000038  0000000400000001 R_BPF_64_64            0000000000000000 sec
0000000000000058  0000000400000001 R_BPF_64_64            0000000000000000 sec
```

Each relocation is represented by `Offset` (8 bytes) and `Info` (8 bytes). For example, the first relocation corresponds to the first instruction (Offset 0x0) and the corresponding `Info` indicates the relocation type of `R_BPF_64_64` (type 1) and the entry in the symbol table (entry 6). The following is the symbol table with `llvm-readelf -s test.o`:



```text
Symbol table '.symtab' contains 8 entries:
   Num:    Value          Size Type    Bind   Vis       Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT   UND
     1: 0000000000000000     0 FILE    LOCAL  DEFAULT   ABS test.c
     2: 0000000000000008     4 OBJECT  LOCAL  DEFAULT     4 l1
     3: 000000000000000c     4 OBJECT  LOCAL  DEFAULT     4 l2
     4: 0000000000000000     0 SECTION LOCAL  DEFAULT     4 sec
     5: 0000000000000000   128 FUNC    GLOBAL DEFAULT     2 test
     6: 0000000000000000     4 OBJECT  GLOBAL DEFAULT     4 g1
     7: 0000000000000004     4 OBJECT  GLOBAL DEFAULT     4 g2
```

The 6th entry is global variable `g1` with value 0.

Similarly, the second relocation is at `.text` offset `0x18`, instruction 3, has a type of `R_BPF_64_64` and refers to entry 7 in the symbol table. The second relocation resolves to global variable `g2` which has a symbol value 4. The symbol value represents the offset from the start of `.data` section where the initial value of the global variable `g2` is stored.

The third and fourth relocations refer to static variables `l1` and `l2`. From the `.rel.text` section above, it is not clear to which symbols they really refer as they both refer to symbol table entry 4, symbol `sec`, which has `STT_SECTION` type and represents a section. So for a static variable or function, the section offset is written to the original insn buffer, which is called `A` (addend). Looking at above insn `7` and `11`, they have section offset `8` and `12`. From symbol table, we can find that they correspond to entries `2` and `3` for `l1` and `l2`.

In general, the `A` is 0 for global variables and functions, and is the section offset or some computation result based on section offset for static variables/functions. The non-section-offset case refers to function calls. See below for more details.

<a id="rst-different-relocation-types"></a>

### Different Relocation Types

Six relocation types are supported. The following is an overview and `S` represents the value of the symbol in the symbol table:



```text
Enum  ELF Reloc Type     Description      BitSize  Offset        Calculation
0     R_BPF_NONE         None
1     R_BPF_64_64        ld_imm64 insn    32       r_offset + 4  S + A
2     R_BPF_64_ABS64     normal data      64       r_offset      S + A
3     R_BPF_64_ABS32     normal data      32       r_offset      S + A
4     R_BPF_64_NODYLD32  .BTF[.ext] data  32       r_offset      S + A
10    R_BPF_64_32        call insn        32       r_offset + 4  (S + A) / 8 - 1
```

For example, `R_BPF_64_64` relocation type is used for `ld_imm64` instruction. The actual to-be-relocated data (0 or section offset) is stored at `r_offset + 4` and the read/write data bitsize is 32 (4 bytes). The relocation can be resolved with the symbol value plus implicit addend. Note that the `BitSize` is 32 which means the section offset must be less than or equal to `UINT32_MAX` and this is enforced by LLVM BPF backend.

In another case, `R_BPF_64_ABS64` relocation type is used for normal 64-bit data. The actual to-be-relocated data is stored at `r_offset` and the read/write data bitsize is 64 (8 bytes). The relocation can be resolved with the symbol value plus implicit addend.

Both `R_BPF_64_ABS32` and `R_BPF_64_NODYLD32` types are for 32-bit data. But `R_BPF_64_NODYLD32` specifically refers to relocations in `.BTF` and `.BTF.ext` sections. For cases like bcc where llvm `ExecutionEngine RuntimeDyld` is involved, `R_BPF_64_NODYLD32` types of relocations should not be resolved to actual function/variable address. Otherwise, `.BTF` and `.BTF.ext` become unusable by bcc and kernel.

Type `R_BPF_64_32` is used for call instruction. The call target section offset is stored at `r_offset + 4` (32bit) and calculated as `(S + A) / 8 - 1`.

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

### Examples

Types `R_BPF_64_64` and `R_BPF_64_32` are used to resolve `ld_imm64` and `call` instructions. For example:



```text
__attribute__((noinline)) __attribute__((section("sec1")))
int gfunc(int a, int b) {
  return a * b;
}
static __attribute__((noinline)) __attribute__((section("sec1")))
int lfunc(int a, int b) {
  return a + b;
}
int global __attribute__((section("sec2")));
int test(int a, int b) {
  return gfunc(a, b) +  lfunc(a, b) + global;
}
```

Compiled with `clang --target=bpf -O2 -c test.c`, we will have following code with `` llvm-objdump -dr test.o` ``:



```text
Disassembly of section .text:

0000000000000000 <test>:
       0:       bf 26 00 00 00 00 00 00 r6 = r2
       1:       bf 17 00 00 00 00 00 00 r7 = r1
       2:       85 10 00 00 ff ff ff ff call -1
                0000000000000010:  R_BPF_64_32  gfunc
       3:       bf 08 00 00 00 00 00 00 r8 = r0
       4:       bf 71 00 00 00 00 00 00 r1 = r7
       5:       bf 62 00 00 00 00 00 00 r2 = r6
       6:       85 10 00 00 02 00 00 00 call 2
                0000000000000030:  R_BPF_64_32  sec1
       7:       0f 80 00 00 00 00 00 00 r0 += r8
       8:       18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll
                0000000000000040:  R_BPF_64_64  global
      10:       61 11 00 00 00 00 00 00 r1 = *(u32 *)(r1 + 0)
      11:       0f 10 00 00 00 00 00 00 r0 += r1
      12:       95 00 00 00 00 00 00 00 exit

Disassembly of section sec1:

0000000000000000 <gfunc>:
       0:       bf 20 00 00 00 00 00 00 r0 = r2
       1:       2f 10 00 00 00 00 00 00 r0 *= r1
       2:       95 00 00 00 00 00 00 00 exit

0000000000000018 <lfunc>:
       3:       bf 20 00 00 00 00 00 00 r0 = r2
       4:       0f 10 00 00 00 00 00 00 r0 += r1
       5:       95 00 00 00 00 00 00 00 exit
```

The first relocation corresponds to `gfunc(a, b)` where `gfunc` has a value of 0, so the `call` instruction offset is `(0 + 0)/8 - 1 = -1`. The second relocation corresponds to `lfunc(a, b)` where `lfunc` has a section offset `0x18`, so the `call` instruction offset is `(0 + 0x18)/8 - 1 = 2`. The third relocation corresponds to ld_imm64 of `global`, which has a section offset `0`.

The following is an example to show how R_BPF_64_ABS64 could be generated:



```text
int global() { return 0; }
struct t { void *g; } gbl = { global };
```

Compiled with `clang --target=bpf -O2 -g -c test.c`, we will see a relocation below in `.data` section with command `llvm-readelf -r test.o`:



```text
Relocation section '.rel.data' at offset 0x458 contains 1 entries:
    Offset             Info             Type               Symbol's Value  Symbol's Name
0000000000000000  0000000700000002 R_BPF_64_ABS64         0000000000000000 global
```

The relocation says the first 8-byte of `.data` section should be filled with address of `global` variable.

With `llvm-readelf` output, we can see that dwarf sections have a bunch of `R_BPF_64_ABS32` and `R_BPF_64_ABS64` relocations:



```text
Relocation section '.rel.debug_info' at offset 0x468 contains 13 entries:
    Offset             Info             Type               Symbol's Value  Symbol's Name
0000000000000006  0000000300000003 R_BPF_64_ABS32         0000000000000000 .debug_abbrev
000000000000000c  0000000400000003 R_BPF_64_ABS32         0000000000000000 .debug_str
0000000000000012  0000000400000003 R_BPF_64_ABS32         0000000000000000 .debug_str
0000000000000016  0000000600000003 R_BPF_64_ABS32         0000000000000000 .debug_line
000000000000001a  0000000400000003 R_BPF_64_ABS32         0000000000000000 .debug_str
000000000000001e  0000000200000002 R_BPF_64_ABS64         0000000000000000 .text
000000000000002b  0000000400000003 R_BPF_64_ABS32         0000000000000000 .debug_str
0000000000000037  0000000800000002 R_BPF_64_ABS64         0000000000000000 gbl
0000000000000040  0000000400000003 R_BPF_64_ABS32         0000000000000000 .debug_str
......
```

The .BTF/.BTF.ext sections has R_BPF_64_NODYLD32 relocations:



```text
Relocation section '.rel.BTF' at offset 0x538 contains 1 entries:
    Offset             Info             Type               Symbol's Value  Symbol's Name
0000000000000084  0000000800000004 R_BPF_64_NODYLD32      0000000000000000 gbl

Relocation section '.rel.BTF.ext' at offset 0x548 contains 2 entries:
    Offset             Info             Type               Symbol's Value  Symbol's Name
000000000000002c  0000000200000004 R_BPF_64_NODYLD32      0000000000000000 .text
0000000000000040  0000000200000004 R_BPF_64_NODYLD32      0000000000000000 .text
```

<a id="rst-co-re-relocations"></a>
<a id="rst-btf-co-re-relocations"></a>

## CO-RE Relocations

From object file point of view CO-RE mechanism is implemented as a set of CO-RE specific relocation records. These relocation records are not related to ELF relocations and are encoded in .BTF.ext section. See [Documentation/bpf/btf.rst](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/btf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for more information on .BTF.ext structure.

CO-RE relocations are applied to BPF instructions to update immediate or offset fields of the instruction at load time with information relevant for target kernel.

Field to patch is selected basing on the instruction class:

- For BPF_ALU, BPF_ALU64, BPF_LD `immediate` field is patched;

- For BPF_LDX, BPF_STX, BPF_ST `offset` field is patched;

- BPF_JMP, BPF_JMP32 instructions **should not** be patched.

<a id="rst-relocation-kinds"></a>

### Relocation kinds

There are several kinds of CO-RE relocations that could be split in three groups:

- Field-based - patch instruction with field related information, e.g. change offset field of the BPF_LDX instruction to reflect offset of a specific structure field in the target kernel.

- Type-based - patch instruction with type related information, e.g. change immediate field of the BPF_ALU move instruction to 0 or 1 to reflect if specific type is present in the target kernel.

- Enum-based - patch instruction with enum related information, e.g. change immediate field of the BPF_LD_IMM64 instruction to reflect value of a specific enum literal in the target kernel.

The complete list of relocation kinds is represented by the following enum:



```c
enum bpf_core_relo_kind {
       BPF_CORE_FIELD_BYTE_OFFSET = 0,  /* field byte offset */
       BPF_CORE_FIELD_BYTE_SIZE   = 1,  /* field size in bytes */
       BPF_CORE_FIELD_EXISTS      = 2,  /* field existence in target kernel */
       BPF_CORE_FIELD_SIGNED      = 3,  /* field signedness (0 - unsigned, 1 - signed) */
       BPF_CORE_FIELD_LSHIFT_U64  = 4,  /* bitfield-specific left bitshift */
       BPF_CORE_FIELD_RSHIFT_U64  = 5,  /* bitfield-specific right bitshift */
       BPF_CORE_TYPE_ID_LOCAL     = 6,  /* type ID in local BPF object */
       BPF_CORE_TYPE_ID_TARGET    = 7,  /* type ID in target kernel */
       BPF_CORE_TYPE_EXISTS       = 8,  /* type existence in target kernel */
       BPF_CORE_TYPE_SIZE         = 9,  /* type size in bytes */
       BPF_CORE_ENUMVAL_EXISTS    = 10, /* enum value existence in target kernel */
       BPF_CORE_ENUMVAL_VALUE     = 11, /* enum value integer value */
       BPF_CORE_TYPE_MATCHES      = 12, /* type match in target kernel */
};
```

Notes:

- `BPF_CORE_FIELD_LSHIFT_U64` and `BPF_CORE_FIELD_RSHIFT_U64` are supposed to be used to read bitfield values using the following algorithm:



  ```c
  // To read bitfield ``f`` from ``struct s``
  is_signed = relo(s->f, BPF_CORE_FIELD_SIGNED)
  off = relo(s->f, BPF_CORE_FIELD_BYTE_OFFSET)
  sz  = relo(s->f, BPF_CORE_FIELD_BYTE_SIZE)
  l   = relo(s->f, BPF_CORE_FIELD_LSHIFT_U64)
  r   = relo(s->f, BPF_CORE_FIELD_RSHIFT_U64)
  // define ``v`` as signed or unsigned integer of size ``sz``
  v = *({s|u}<sz> *)((void *)s + off)
  v <<= l
  v >>= r
  ```

- The `BPF_CORE_TYPE_MATCHES` queries matching relation, defined as follows:

  - for integers: types match if size and signedness match;

  - for arrays &amp; pointers: target types are recursively matched;

  - for structs &amp; unions:

    - local members need to exist in target with the same name;

    - for each member we recursively check match unless it is already behind a pointer, in which case we only check matching names and compatible kind;

  - for enums:

    - local variants have to have a match in target by symbolic name (but not numeric value);

    - size has to match (but enum may match enum64 and vice versa);

  - for function pointers:

    - number and position of arguments in local type has to match target;

    - for each argument and the return value we recursively check match.

<a id="rst-co-re-relocation-record"></a>

### CO-RE Relocation Record

Relocation record is encoded as the following structure:



```c
struct bpf_core_relo {
       __u32 insn_off;
       __u32 type_id;
       __u32 access_str_off;
       enum bpf_core_relo_kind kind;
};
```

- `insn_off` - instruction offset (in bytes) within a code section associated with this relocation;

- `type_id` - BTF type ID of the "root" (containing) entity of a relocatable type or field;

- `access_str_off` - offset into corresponding .BTF string section. String interpretation depends on specific relocation kind:

  - for field-based relocations, string encodes an accessed field using a sequence of field and array indices, separated by colon (:). It's conceptually very close to LLVM's [getelementptr](<https://llvm.org/docs/LangRef.html#getelementptr-instruction>)<a id="rst-getelementptr"></a> instruction's arguments for identifying offset to a field. For example, consider the following C code:



    ```c
    struct sample {
        int a;
        int b;
        struct { int c[10]; };
    } __attribute__((preserve_access_index));
    struct sample *s;
    ```

    - Access to `s[0].a` would be encoded as `0:0`:

      - `0`: first element of `s` (as if `s` is an array);

      - `0`: index of field `a` in `struct sample`.

    - Access to `s->a` would be encoded as `0:0` as well.

    - Access to `s->b` would be encoded as `0:1`:

      - `0`: first element of `s`;

      - `1`: index of field `b` in `struct sample`.

    - Access to `s[1].c[5]` would be encoded as `1:2:0:5`:

      - `1`: second element of `s`;

      - `2`: index of anonymous structure field in `struct sample`;

      - `0`: index of field `c` in anonymous structure;

      - `5`: access to array element \#5.

  - for type-based relocations, string is expected to be just "0";

  - - **for enum value-based relocations, string contains an index of enum**

      value within its enum type;

- `kind` - one of `enum bpf_core_relo_kind`.

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



<a id="rst-co-re-relocation-examples"></a>
<a id="rst-btf-co-re-relocation-examples"></a>

### CO-RE Relocation Examples

For the following C code:



```c
struct foo {
  int a;
  int b;
  unsigned c:15;
} __attribute__((preserve_access_index));

enum bar { U, V };
```

With the following BTF definitions:



```text
...
[2] STRUCT 'foo' size=8 vlen=2
       'a' type_id=3 bits_offset=0
       'b' type_id=3 bits_offset=32
       'c' type_id=4 bits_offset=64 bitfield_size=15
[3] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[4] INT 'unsigned int' size=4 bits_offset=0 nr_bits=32 encoding=(none)
...
[16] ENUM 'bar' encoding=UNSIGNED size=4 vlen=2
       'U' val=0
       'V' val=1
```

Field offset relocations are generated automatically when `__attribute__((preserve_access_index))` is used, for example:



```c
void alpha(struct foo *s, volatile unsigned long *g) {
  *g = s->a;
  s->a = 1;
}

00 <alpha>:
  0:  r3 = *(s32 *)(r1 + 0x0)
         00:  CO-RE <byte_off> [2] struct foo::a (0:0)
  1:  *(u64 *)(r2 + 0x0) = r3
  2:  *(u32 *)(r1 + 0x0) = 0x1
         10:  CO-RE <byte_off> [2] struct foo::a (0:0)
  3:  exit
```

All relocation kinds could be requested via built-in functions. E.g. field-based relocations:



```c
void bravo(struct foo *s, volatile unsigned long *g) {
  *g = __builtin_preserve_field_info(s->b, 0 /* field byte offset */);
  *g = __builtin_preserve_field_info(s->b, 1 /* field byte size */);
  *g = __builtin_preserve_field_info(s->b, 2 /* field existence */);
  *g = __builtin_preserve_field_info(s->b, 3 /* field signedness */);
  *g = __builtin_preserve_field_info(s->c, 4 /* bitfield left shift */);
  *g = __builtin_preserve_field_info(s->c, 5 /* bitfield right shift */);
}

20 <bravo>:
   4:     r1 = 0x4
          20:  CO-RE <byte_off> [2] struct foo::b (0:1)
   5:     *(u64 *)(r2 + 0x0) = r1
   6:     r1 = 0x4
          30:  CO-RE <byte_sz> [2] struct foo::b (0:1)
   7:     *(u64 *)(r2 + 0x0) = r1
   8:     r1 = 0x1
          40:  CO-RE <field_exists> [2] struct foo::b (0:1)
   9:     *(u64 *)(r2 + 0x0) = r1
  10:     r1 = 0x1
          50:  CO-RE <signed> [2] struct foo::b (0:1)
  11:     *(u64 *)(r2 + 0x0) = r1
  12:     r1 = 0x31
          60:  CO-RE <lshift_u64> [2] struct foo::c (0:2)
  13:     *(u64 *)(r2 + 0x0) = r1
  14:     r1 = 0x31
          70:  CO-RE <rshift_u64> [2] struct foo::c (0:2)
  15:     *(u64 *)(r2 + 0x0) = r1
  16:     exit
```

Type-based relocations:



```c
void charlie(struct foo *s, volatile unsigned long *g) {
  *g = __builtin_preserve_type_info(*s, 0 /* type existence */);
  *g = __builtin_preserve_type_info(*s, 1 /* type size */);
  *g = __builtin_preserve_type_info(*s, 2 /* type matches */);
  *g = __builtin_btf_type_id(*s, 0 /* type id in this object file */);
  *g = __builtin_btf_type_id(*s, 1 /* type id in target kernel */);
}

88 <charlie>:
  17:     r1 = 0x1
          88:  CO-RE <type_exists> [2] struct foo
  18:     *(u64 *)(r2 + 0x0) = r1
  19:     r1 = 0xc
          98:  CO-RE <type_size> [2] struct foo
  20:     *(u64 *)(r2 + 0x0) = r1
  21:     r1 = 0x1
          a8:  CO-RE <type_matches> [2] struct foo
  22:     *(u64 *)(r2 + 0x0) = r1
  23:     r1 = 0x2 ll
          b8:  CO-RE <local_type_id> [2] struct foo
  25:     *(u64 *)(r2 + 0x0) = r1
  26:     r1 = 0x2 ll
          d0:  CO-RE <target_type_id> [2] struct foo
  28:     *(u64 *)(r2 + 0x0) = r1
  29:     exit
```

Enum-based relocations:



```c
void delta(struct foo *s, volatile unsigned long *g) {
  *g = __builtin_preserve_enum_value(*(enum bar *)U, 0 /* enum literal existence */);
  *g = __builtin_preserve_enum_value(*(enum bar *)V, 1 /* enum literal value */);
}

f0 <delta>:
  30:     r1 = 0x1 ll
          f0:  CO-RE <enumval_exists> [16] enum bar::U = 0
  32:     *(u64 *)(r2 + 0x0) = r1
  33:     r1 = 0x1 ll
          108:  CO-RE <enumval_value> [16] enum bar::V = 1
  35:     *(u64 *)(r2 + 0x0) = r1
  36:     exit
```

---

# BPF_MAP_TYPE_ARRAY and BPF_MAP_TYPE_PERCPU_ARRAY

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_ARRAY and BPF_MAP_TYPE_PERCPU_ARRAY provide generic array storage. The key type is an unsigned 32-bit integer (4 bytes) and the map is of constant size. The size of the array is defined in max_entries at creation time. All…

<a id="rst-bpf-map-type-array-and-bpf-map-type-percpu-array"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_ARRAY` was introduced in kernel version 3.19
>
> - `BPF_MAP_TYPE_PERCPU_ARRAY` was introduced in version 4.6

`BPF_MAP_TYPE_ARRAY` and `BPF_MAP_TYPE_PERCPU_ARRAY` provide generic array storage. The key type is an unsigned 32-bit integer (4 bytes) and the map is of constant size. The size of the array is defined in `max_entries` at creation time. All array elements are pre-allocated and zero initialized when created. `BPF_MAP_TYPE_PERCPU_ARRAY` uses a different memory region for each CPU whereas `BPF_MAP_TYPE_ARRAY` uses the same memory region. The value stored can be of any size for `BPF_MAP_TYPE_ARRAY` and not more than `PCPU_MIN_UNIT_SIZE` (32 kB) for `BPF_MAP_TYPE_PERCPU_ARRAY`. All array elements are aligned to 8 bytes.

Since kernel 5.5, memory mapping may be enabled for `BPF_MAP_TYPE_ARRAY` by setting the flag `BPF_F_MMAPABLE`. The map definition is page-aligned and starts on the first page. Sufficient page-sized and page-aligned blocks of memory are allocated to store all array values, starting on the second page, which in some cases will result in over-allocation of memory. The benefit of using this is increased performance and ease of use since userspace programs would not be required to use helper functions to access and mutate data.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

Array elements can be retrieved using the `bpf_map_lookup_elem()` helper. This helper returns a pointer into the array element, so to avoid data races with userspace reading the value, the user must use primitives like `__sync_fetch_and_add()` when updating the value in-place.

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
```

Array elements can be updated using the `bpf_map_update_elem()` helper.

`bpf_map_update_elem()` returns 0 on success, or negative error in case of failure.

Since the array is of constant size, `bpf_map_delete_elem()` is not supported. To clear an array element, you may use `bpf_map_update_elem()` to insert a zero value to that index.

<a id="rst-per-cpu-array"></a>

### Per CPU Array

Values stored in `BPF_MAP_TYPE_ARRAY` can be accessed by multiple programs across different CPUs. To restrict storage to a single CPU, you may use a `BPF_MAP_TYPE_PERCPU_ARRAY`.

When using a `BPF_MAP_TYPE_PERCPU_ARRAY` the `bpf_map_update_elem()` and `bpf_map_lookup_elem()` helpers automatically access the slot for the current CPU.

<a id="rst-bpf-map-lookup-percpu-elem"></a>

#### bpf_map_lookup_percpu_elem()



```c
void *bpf_map_lookup_percpu_elem(struct bpf_map *map, const void *key, u32 cpu)
```

The `bpf_map_lookup_percpu_elem()` helper can be used to lookup the array value for a specific CPU. Returns value on success , or `NULL` if no entry was found or `cpu` is invalid.

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

### Concurrency

Since kernel version 5.1, the BPF infrastructure provides `struct bpf_spin_lock` to synchronize access.

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

### Userspace

Access from userspace uses libbpf APIs with the same names as above, with the map identified by its `fd`.

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

## Examples

Please see the `tools/testing/selftests/bpf` directory for functional examples. The code samples below demonstrate API usage.

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

This snippet shows how to declare an array in a BPF program.



```c
struct {
        __uint(type, BPF_MAP_TYPE_ARRAY);
        __type(key, u32);
        __type(value, long);
        __uint(max_entries, 256);
} my_map SEC(".maps");
```

This example BPF program shows how to access an array element.



```c
int bpf_prog(struct __sk_buff *skb)
{
        struct iphdr ip;
        int index;
        long *value;

        if (bpf_skb_load_bytes(skb, ETH_HLEN, &ip, sizeof(ip)) < 0)
                return 0;

        index = ip.protocol;
        value = bpf_map_lookup_elem(&my_map, &index);
        if (value)
                __sync_fetch_and_add(value, skb->len);

        return 0;
}
```

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

### Userspace

<a id="rst-bpf-map-type-array"></a>

#### BPF_MAP_TYPE_ARRAY

This snippet shows how to create an array, using `bpf_map_create_opts` to set flags.



```c
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

int create_array()
{
        int fd;
        LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);

        fd = bpf_map_create(BPF_MAP_TYPE_ARRAY,
                            "example_array",       /* name */
                            sizeof(__u32),         /* key size */
                            sizeof(long),          /* value size */
                            256,                   /* max entries */
                            &opts);                /* create opts */
        return fd;
}
```

This snippet shows how to initialize the elements of an array.



```c
int initialize_array(int fd)
{
        __u32 i;
        long value;
        int ret;

        for (i = 0; i < 256; i++) {
                value = i;
                ret = bpf_map_update_elem(fd, &i, &value, BPF_ANY);
                if (ret < 0)
                        return ret;
        }

        return ret;
}
```

This snippet shows how to retrieve an element value from an array.



```c
int lookup(int fd)
{
        __u32 index = 42;
        long value;
        int ret;

        ret = bpf_map_lookup_elem(fd, &index, &value);
        if (ret < 0)
                return ret;

        /* use value here */
        assert(value == 42);

        return ret;
}
```

<a id="rst-bpf-map-type-percpu-array"></a>

#### BPF_MAP_TYPE_PERCPU_ARRAY

This snippet shows how to initialize the elements of a per CPU array.



```c
int initialize_array(int fd)
{
        int ncpus = libbpf_num_possible_cpus();
        long values[ncpus];
        __u32 i, j;
        int ret;

        for (i = 0; i < 256 ; i++) {
                for (j = 0; j < ncpus; j++)
                        values[j] = i;
                ret = bpf_map_update_elem(fd, &i, &values, BPF_ANY);
                if (ret < 0)
                        return ret;
        }

        return ret;
}
```

This snippet shows how to access the per CPU elements of an array value.



```c
int lookup(int fd)
{
        int ncpus = libbpf_num_possible_cpus();
        __u32 index = 42, j;
        long values[ncpus];
        int ret;

        ret = bpf_map_lookup_elem(fd, &index, &values);
        if (ret < 0)
                return ret;

        for (j = 0; j < ncpus; j++) {
                /* Use per CPU value here */
                assert(values[j] == 42);
        }

        return ret;
}
```

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

## Semantics

As shown in the example above, when accessing a `BPF_MAP_TYPE_PERCPU_ARRAY` in userspace, each value is an array with `ncpus` elements.

When calling `bpf_map_update_elem()` the flag `BPF_NOEXIST` can not be used for these maps.

---

# BPF_MAP_TYPE_BLOOM_FILTER

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_BLOOM_FILTER provides a BPF bloom filter map. Bloom filters are a space-efficient probabilistic data structure used to quickly test whether an element exists in a set. In a bloom filter, false positives are possible whereas…

<a id="rst-bpf-map-type-bloom-filter"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_BLOOM_FILTER` was introduced in kernel version 5.16

`BPF_MAP_TYPE_BLOOM_FILTER` provides a BPF bloom filter map. Bloom filters are a space-efficient probabilistic data structure used to quickly test whether an element exists in a set. In a bloom filter, false positives are possible whereas false negatives are not.

The bloom filter map does not have keys, only values. When the bloom filter map is created, it must be created with a `key_size` of 0.  The bloom filter map supports two operations:

- push: adding an element to the map

- peek: determining whether an element is present in the map

BPF programs must use `bpf_map_push_elem` to add an element to the bloom filter map and `bpf_map_peek_elem` to query the map. These operations are exposed to userspace applications using the existing `bpf` syscall in the following way:

- `BPF_MAP_UPDATE_ELEM` -&gt; push

- `BPF_MAP_LOOKUP_ELEM` -&gt; peek

The `max_entries` size that is specified at map creation time is used to approximate a reasonable bitmap size for the bloom filter, and is not otherwise strictly enforced. If the user wishes to insert more entries into the bloom filter than `max_entries`, this may lead to a higher false positive rate.

The number of hashes to use for the bloom filter is configurable using the lower 4 bits of `map_extra` in `union bpf_attr` at map creation time. If no number is specified, the default used will be 5 hash functions. In general, using more hashes decreases both the false positive rate and the speed of a lookup.

It is not possible to delete elements from a bloom filter map. A bloom filter map may be used as an inner map. The user is responsible for synchronising concurrent updates and lookups to ensure no false negative lookups occur.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-map-push-elem"></a>

#### bpf_map_push_elem()



```c
long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 flags)
```

A `value` can be added to a bloom filter using the `bpf_map_push_elem()` helper. The `flags` parameter must be set to `BPF_ANY` when adding an entry to the bloom filter. This helper returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-peek-elem"></a>

#### bpf_map_peek_elem()



```c
long bpf_map_peek_elem(struct bpf_map *map, void *value)
```

The `bpf_map_peek_elem()` helper is used to determine whether `value` is present in the bloom filter map. This helper returns `0` if `value` is probably present in the map, or `-ENOENT` if `value` is definitely not present in the map.

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

### Userspace

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem (int fd, const void *key, const void *value, __u64 flags)
```

A userspace program can add a `value` to a bloom filter using libbpf's `bpf_map_update_elem` function. The `key` parameter must be set to `NULL` and `flags` must be set to `BPF_ANY`. Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem (int fd, const void *key, void *value)
```

A userspace program can determine the presence of `value` in a bloom filter using libbpf's `bpf_map_lookup_elem` function. The `key` parameter must be set to `NULL`. Returns `0` if `value` is probably present in the map, or `-ENOENT` if `value` is definitely not present in the map.

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

## Examples

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

This snippet shows how to declare a bloom filter in a BPF program:



```c
struct {
        __uint(type, BPF_MAP_TYPE_BLOOM_FILTER);
        __type(value, __u32);
        __uint(max_entries, 1000);
        __uint(map_extra, 3);
} bloom_filter SEC(".maps");
```

This snippet shows how to determine presence of a value in a bloom filter in a BPF program:



```c
void *lookup(__u32 key)
{
        if (bpf_map_peek_elem(&bloom_filter, &key) == 0) {
                /* Verify not a false positive and fetch an associated
                 * value using a secondary lookup, e.g. in a hash table
                 */
                return bpf_map_lookup_elem(&hash_table, &key);
        }
        return 0;
}
```

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

### Userspace

This snippet shows how to use libbpf to create a bloom filter map from userspace:



```c
int create_bloom()
{
        LIBBPF_OPTS(bpf_map_create_opts, opts,
                    .map_extra = 3);             /* number of hashes */

        return bpf_map_create(BPF_MAP_TYPE_BLOOM_FILTER,
                              "ipv6_bloom",      /* name */
                              0,                 /* key size, must be zero */
                              sizeof(ipv6_addr), /* value size */
                              10000,             /* max entries */
                              &opts);            /* create options */
}
```

This snippet shows how to add an element to a bloom filter from userspace:



```c
int add_element(struct bpf_map *bloom_map, __u32 value)
{
        int bloom_fd = bpf_map__fd(bloom_map);
        return bpf_map_update_elem(bloom_fd, NULL, &value, BPF_ANY);
}
```

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

## References

[https://lwn.net/ml/bpf/20210831225005.2762202-1-joannekoong@fb.com/](<https://lwn.net/ml/bpf/20210831225005.2762202-1-joannekoong@fb.com/>)

---

# BPF_MAP_TYPE_CGROUP_STORAGE

_Peios Kernel / Internals / BPF_

> The BPF_MAP_TYPE_CGROUP_STORAGE map type represents a local fix-sized storage. It is only available with CONFIG_CGROUP_BPF, and to programs that attach to cgroups; the programs are made available by the same Kconfig. The storage is…

<a id="rst-bpf-map-type-cgroup-storage"></a>

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

<!-- Copyright (C) 2020 Google LLC. -->

The `BPF_MAP_TYPE_CGROUP_STORAGE` map type represents a local fix-sized storage. It is only available with `CONFIG_CGROUP_BPF`, and to programs that attach to cgroups; the programs are made available by the same Kconfig. The storage is identified by the cgroup the program is attached to.

The map provide a local storage at the cgroup that the BPF program is attached to. It provides a faster and simpler access than the general purpose hash table, which performs a hash table lookups, and requires user to track live cgroups on their own.

This document describes the usage and semantics of the `BPF_MAP_TYPE_CGROUP_STORAGE` map type. Some of its behaviors was changed in Linux 5.9 and this document will describe the differences.

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

## Usage

The map uses key of type of either `__u64 cgroup_inode_id` or `struct bpf_cgroup_storage_key`, declared in `linux/bpf.h`:



```text
struct bpf_cgroup_storage_key {
        __u64 cgroup_inode_id;
        __u32 attach_type;
};
```

`cgroup_inode_id` is the inode id of the cgroup directory. `attach_type` is the program's attach type.

Linux 5.9 added support for type `__u64 cgroup_inode_id` as the key type. When this key type is used, then all attach types of the particular cgroup and map will share the same storage. Otherwise, if the type is `struct bpf_cgroup_storage_key`, then programs of different attach types be isolated and see different storages.

To access the storage in a program, use `bpf_get_local_storage`:



```text
void *bpf_get_local_storage(void *map, u64 flags)
```

`flags` is reserved for future use and must be 0.

There is no implicit synchronization. Storages of `BPF_MAP_TYPE_CGROUP_STORAGE` can be accessed by multiple programs across different CPUs, and user should take care of synchronization by themselves. The bpf infrastructure provides `struct bpf_spin_lock` to synchronize the storage. See `tools/testing/selftests/bpf/progs/test_spin_lock.c`.

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

## Examples

Usage with key type as `struct bpf_cgroup_storage_key`:



```text
#include <bpf/bpf.h>

struct {
        __uint(type, BPF_MAP_TYPE_CGROUP_STORAGE);
        __type(key, struct bpf_cgroup_storage_key);
        __type(value, __u32);
} cgroup_storage SEC(".maps");

int program(struct __sk_buff *skb)
{
        __u32 *ptr = bpf_get_local_storage(&cgroup_storage, 0);
        __sync_fetch_and_add(ptr, 1);

        return 0;
}
```

Userspace accessing map declared above:



```text
#include <linux/bpf.h>
#include <linux/libbpf.h>

__u32 map_lookup(struct bpf_map *map, __u64 cgrp, enum bpf_attach_type type)
{
        struct bpf_cgroup_storage_key = {
                .cgroup_inode_id = cgrp,
                .attach_type = type,
        };
        __u32 value;
        bpf_map_lookup_elem(bpf_map__fd(map), &key, &value);
        // error checking omitted
        return value;
}
```

Alternatively, using just `__u64 cgroup_inode_id` as key type:



```text
#include <bpf/bpf.h>

struct {
        __uint(type, BPF_MAP_TYPE_CGROUP_STORAGE);
        __type(key, __u64);
        __type(value, __u32);
} cgroup_storage SEC(".maps");

int program(struct __sk_buff *skb)
{
        __u32 *ptr = bpf_get_local_storage(&cgroup_storage, 0);
        __sync_fetch_and_add(ptr, 1);

        return 0;
}
```

And userspace:



```text
#include <linux/bpf.h>
#include <linux/libbpf.h>

__u32 map_lookup(struct bpf_map *map, __u64 cgrp, enum bpf_attach_type type)
{
        __u32 value;
        bpf_map_lookup_elem(bpf_map__fd(map), &cgrp, &value);
        // error checking omitted
        return value;
}
```

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

## Semantics

`BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE` is a variant of this map type. This per-CPU variant will have different memory regions for each CPU for each storage. The non-per-CPU will have the same memory region for each storage.

Prior to Linux 5.9, the lifetime of a storage is precisely per-attachment, and for a single `CGROUP_STORAGE` map, there can be at most one program loaded that uses the map. A program may be attached to multiple cgroups or have multiple attach types, and each attach creates a fresh zeroed storage. The storage is freed upon detach.

There is a one-to-one association between the map of each type (per-CPU and non-per-CPU) and the BPF program during load verification time. As a result, each map can only be used by one BPF program and each BPF program can only use one storage map of each type. Because of map can only be used by one BPF program, sharing of this cgroup's storage with other BPF programs were impossible.

Since Linux 5.9, storage can be shared by multiple programs. When a program is attached to a cgroup, the kernel would create a new storage only if the map does not already contain an entry for the cgroup and attach type pair, or else the old storage is reused for the new attachment. If the map is attach type shared, then attach type is simply ignored during comparison. Storage is freed only when either the map or the cgroup attached to is being freed. Detaching will not directly free the storage, but it may cause the reference to the map to reach zero and indirectly freeing all storage in the map.

The map is not associated with any BPF program, thus making sharing possible. However, the BPF program can still only associate with one map of each type (per-CPU and non-per-CPU). A BPF program cannot use more than one `BPF_MAP_TYPE_CGROUP_STORAGE` or more than one `BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE`.

In all versions, userspace may use the attach parameters of cgroup and attach type pair in `struct bpf_cgroup_storage_key` as the key to the BPF map APIs to read or update the storage for a given attachment. For Linux 5.9 attach type shared storages, only the first value in the struct, cgroup inode id, is used during comparison, so userspace may just specify a `__u64` directly.

The storage is bound at attach time. Even if the program is attached to parent and triggers in child, the storage still belongs to the parent.

Userspace cannot create a new entry in the map or delete an existing entry. Program test runs always use a temporary storage.

---

# BPF_MAP_TYPE_CGRP_STORAGE

_Peios Kernel / Internals / BPF_

> The BPF_MAP_TYPE_CGRP_STORAGE map type represents a local fix-sized storage for cgroups. It is only available with CONFIG_CGROUPS. The programs are made available by the same Kconfig. The data for a particular cgroup can be retrieved by…

<a id="rst-bpf-map-type-cgrp-storage"></a>

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

<!-- Copyright (C) 2022 Meta Platforms, Inc. and affiliates. -->

The `BPF_MAP_TYPE_CGRP_STORAGE` map type represents a local fix-sized storage for cgroups. It is only available with `CONFIG_CGROUPS`. The programs are made available by the same Kconfig. The data for a particular cgroup can be retrieved by looking up the map with that cgroup.

This document describes the usage and semantics of the `BPF_MAP_TYPE_CGRP_STORAGE` map type.

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

## Usage

The map key must be `sizeof(int)` representing a cgroup fd. To access the storage in a program, use `bpf_cgrp_storage_get`:



```text
void *bpf_cgrp_storage_get(struct bpf_map *map, struct cgroup *cgroup, void *value, u64 flags)
```

`flags` could be 0 or `BPF_LOCAL_STORAGE_GET_F_CREATE` which indicates that a new local storage will be created if one does not exist.

The local storage can be removed with `bpf_cgrp_storage_delete`:



```text
long bpf_cgrp_storage_delete(struct bpf_map *map, struct cgroup *cgroup)
```

The map is available to all program types.

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

## Examples

A BPF program example with BPF_MAP_TYPE_CGRP_STORAGE:



```text
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

struct {
        __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
        __uint(map_flags, BPF_F_NO_PREALLOC);
        __type(key, int);
        __type(value, long);
} cgrp_storage SEC(".maps");

SEC("tp_btf/sys_enter")
int BPF_PROG(on_enter, struct pt_regs *regs, long id)
{
        struct task_struct *task = bpf_get_current_task_btf();
        long *ptr;

        ptr = bpf_cgrp_storage_get(&cgrp_storage, task->cgroups->dfl_cgrp, 0,
                                   BPF_LOCAL_STORAGE_GET_F_CREATE);
        if (ptr)
            __sync_fetch_and_add(ptr, 1);

        return 0;
}
```

Userspace accessing map declared above:



```text
#include <linux/bpf.h>
#include <linux/libbpf.h>

__u32 map_lookup(struct bpf_map *map, int cgrp_fd)
{
        __u32 *value;
        value = bpf_map_lookup_elem(bpf_map__fd(map), &cgrp_fd);
        if (value)
            return *value;
        return 0;
}
```

<a id="rst-difference-between-bpf-map-type-cgrp-storage-and-bpf-map-type-cgroup-storage"></a>

## Difference Between BPF_MAP_TYPE_CGRP_STORAGE and BPF_MAP_TYPE_CGROUP_STORAGE

The old cgroup storage map `BPF_MAP_TYPE_CGROUP_STORAGE` has been marked as deprecated (renamed to `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED`). The new `BPF_MAP_TYPE_CGRP_STORAGE` map should be used instead. The following illusates the main difference between `BPF_MAP_TYPE_CGRP_STORAGE` and `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED`.

- **(1). `BPF_MAP_TYPE_CGRP_STORAGE` can be used by all program types while**

  `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED` is available only to cgroup program types like BPF_CGROUP_INET_INGRESS or BPF_CGROUP_SOCK_OPS, etc.

- **(2). `BPF_MAP_TYPE_CGRP_STORAGE` supports local storage for more than one**

  cgroup while `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED` only supports one cgroup which is attached by a BPF program.

- **(3). `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED` allocates local storage at attach time so**

  `bpf_get_local_storage()` always returns non-NULL local storage. `BPF_MAP_TYPE_CGRP_STORAGE` allocates local storage at runtime so it is possible that `bpf_cgrp_storage_get()` may return null local storage. To avoid such null local storage issue, user space can do `bpf_map_update_elem()` to pre-allocate local storage before a BPF program is attached.

- **(4). `BPF_MAP_TYPE_CGRP_STORAGE` supports deleting local storage by a BPF program**

  while `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED` only deletes storage during prog detach time.

So overall, `BPF_MAP_TYPE_CGRP_STORAGE` supports all `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED` functionality and beyond. It is recommended to use `BPF_MAP_TYPE_CGRP_STORAGE` instead of `BPF_MAP_TYPE_CGROUP_STORAGE_DEPRECATED`.

---

# BPF_MAP_TYPE_CPUMAP

_Peios Kernel / Internals / BPF_

> An example use-case for this map type is software based Receive Side Scaling (RSS).

<a id="rst-bpf-map-type-cpumap"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_CPUMAP` was introduced in kernel version 4.15


The 'cpumap' is primarily used as a backend map for XDP BPF helper
call `bpf_redirect_map()` and XDP_REDIRECT action, like 'devmap'.

Unlike devmap which redirects XDP frames out to another NIC device,
this map type redirects raw XDP frames to another CPU.  The remote
CPU will do SKB-allocation and call the normal network stack.


An example use-case for this map type is software based Receive Side Scaling (RSS).

The CPUMAP represents the CPUs in the system indexed as the map-key, and the map-value is the config setting (per CPUMAP entry). Each CPUMAP entry has a dedicated kernel thread bound to the given CPU to represent the remote CPU execution unit.

Starting from Linux kernel version 5.9 the CPUMAP can run a second XDP program on the remote CPU. This allows an XDP program to split its processing across multiple CPUs. For example, a scenario where the initial CPU (that sees/receives the packets) needs to do minimal packet processing and the remote CPU (to which the packet is directed) can afford to spend more cycles processing the frame. The initial CPU is where the XDP redirect program is executed. The remote CPU receives raw `xdp_frame` objects.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-redirect-map"></a>

#### bpf_redirect_map()



```c
long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
```

Redirect the packet to the endpoint referenced by `map` at index `key`. For `BPF_MAP_TYPE_CPUMAP` this map contains references to CPUs.

The lower two bits of `flags` are used as the return code if the map lookup fails. This is so that the return value can be one of the XDP program return codes up to `XDP_TX`, as chosen by the caller.

<a id="rst-user-space"></a>

### User space

> [!NOTE]
>
> CPUMAP entries can only be updated/looked up/deleted from user space and not from an eBPF program. Trying to call these functions from a kernel eBPF program will result in the program failing to load and a verifier warning.

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);
```

CPU entries can be added or updated using the `bpf_map_update_elem()` helper. This helper replaces existing elements atomically. The `value` parameter can be `struct bpf_cpumap_val`.

>
>
> ```c
> struct bpf_cpumap_val {
>     __u32 qsize;  /* queue size to remote target CPU */
>     union {
>         int   fd; /* prog fd on map write */
>         __u32 id; /* prog id on map read */
>     } bpf_prog;
> };
> ```

- **The flags argument can be one of the following:**

  - BPF_ANY: Create a new element or update an existing element.

  - BPF_NOEXIST: Create a new element only if it did not exist.

  - BPF_EXIST: Update an existing element.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem(int fd, const void *key, void *value);
```

CPU entries can be retrieved using the `bpf_map_lookup_elem()` helper.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
int bpf_map_delete_elem(int fd, const void *key);
```

CPU entries can be deleted using the `bpf_map_delete_elem()` helper. This helper will return 0 on success, or negative error in case of failure.

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

## Examples

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

### Kernel

The following code snippet shows how to declare a `BPF_MAP_TYPE_CPUMAP` called `cpu_map` and how to redirect packets to a remote CPU using a round robin scheme.



```c
struct {
     __uint(type, BPF_MAP_TYPE_CPUMAP);
     __type(key, __u32);
     __type(value, struct bpf_cpumap_val);
     __uint(max_entries, 12);
 } cpu_map SEC(".maps");

 struct {
     __uint(type, BPF_MAP_TYPE_ARRAY);
     __type(key, __u32);
     __type(value, __u32);
     __uint(max_entries, 12);
 } cpus_available SEC(".maps");

 struct {
     __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
     __type(key, __u32);
     __type(value, __u32);
     __uint(max_entries, 1);
 } cpus_iterator SEC(".maps");

 SEC("xdp")
 int  xdp_redir_cpu_round_robin(struct xdp_md *ctx)
 {
     __u32 key = 0;
     __u32 cpu_dest = 0;
     __u32 *cpu_selected, *cpu_iterator;
     __u32 cpu_idx;

     cpu_iterator = bpf_map_lookup_elem(&cpus_iterator, &key);
     if (!cpu_iterator)
         return XDP_ABORTED;
     cpu_idx = *cpu_iterator;

     *cpu_iterator += 1;
     if (*cpu_iterator == bpf_num_possible_cpus())
         *cpu_iterator = 0;

     cpu_selected = bpf_map_lookup_elem(&cpus_available, &cpu_idx);
     if (!cpu_selected)
         return XDP_ABORTED;
     cpu_dest = *cpu_selected;

     if (cpu_dest >= bpf_num_possible_cpus())
         return XDP_ABORTED;

     return bpf_redirect_map(&cpu_map, cpu_dest, 0);
 }
```

<a id="rst-user-space-1"></a>

### User space

The following code snippet shows how to dynamically set the max_entries for a CPUMAP to the max number of cpus available on the system.



```c
int set_max_cpu_entries(struct bpf_map *cpu_map)
{
    if (bpf_map__set_max_entries(cpu_map, libbpf_num_possible_cpus()) < 0) {
        fprintf(stderr, "Failed to set max entries for cpu_map map: %s",
            strerror(errno));
        return -1;
    }
    return 0;
}
```

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

## References

- [https://developers.redhat.com/blog/2021/05/13/receive-side-scaling-rss-with-ebpf-and-cpumap\#redirecting_into_a_cpumap](<https://developers.redhat.com/blog/2021/05/13/receive-side-scaling-rss-with-ebpf-and-cpumap#redirecting_into_a_cpumap>)

---

# BPF_MAP_TYPE_DEVMAP and BPF_MAP_TYPE_DEVMAP_HASH

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_DEVMAP and BPF_MAP_TYPE_DEVMAP_HASH are BPF maps primarily used as backend maps for the XDP BPF helper call bpf_redirect_map(). BPF_MAP_TYPE_DEVMAP is backed by an array that uses the key as the index to lookup a reference to…

<a id="rst-bpf-map-type-devmap-and-bpf-map-type-devmap-hash"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_DEVMAP` was introduced in kernel version 4.14
>
> - `BPF_MAP_TYPE_DEVMAP_HASH` was introduced in kernel version 5.4

`BPF_MAP_TYPE_DEVMAP` and `BPF_MAP_TYPE_DEVMAP_HASH` are BPF maps primarily used as backend maps for the XDP BPF helper call `bpf_redirect_map()`. `BPF_MAP_TYPE_DEVMAP` is backed by an array that uses the key as the index to lookup a reference to a net device. While `BPF_MAP_TYPE_DEVMAP_HASH` is backed by a hash table that uses a key to lookup a reference to a net device. The user provides either &lt;`key`/ `ifindex`&gt; or &lt;`key`/ `struct bpf_devmap_val`&gt; pairs to update the maps with new net devices.

> [!NOTE]
>
> - The key to a hash map doesn't have to be an `ifindex`.
>
> - While `BPF_MAP_TYPE_DEVMAP_HASH` allows for densely packing the net devices it comes at the cost of a hash of the key when performing a look up.

The setup and packet enqueue/send code is shared between the two types of devmap; only the lookup and insertion is different.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-redirect-map"></a>

#### bpf\_redirect\_map()



```c
long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
```

Redirect the packet to the endpoint referenced by `map` at index `key`. For `BPF_MAP_TYPE_DEVMAP` and `BPF_MAP_TYPE_DEVMAP_HASH` this map contains references to net devices (for forwarding packets through other ports).

The lower two bits of <em>flags</em> are used as the return code if the map lookup fails. This is so that the return value can be one of the XDP program return codes up to `XDP_TX`, as chosen by the caller. The higher bits of `flags` can be set to `BPF_F_BROADCAST` or `BPF_F_EXCLUDE_INGRESS` as defined below.

With `BPF_F_BROADCAST` the packet will be broadcast to all the interfaces in the map, with `BPF_F_EXCLUDE_INGRESS` the ingress interface will be excluded from the broadcast.

> [!NOTE]
>
> - The key is ignored if BPF\_F\_BROADCAST is set.
>
> - The broadcast feature can also be used to implement multicast forwarding: simply create multiple DEVMAPs, each one corresponding to a single multicast group.

This helper will return `XDP_REDIRECT` on success, or the value of the two lower bits of the `flags` argument if the map lookup fails.

More information about redirection can be found [Redirect](</kernel/internals/bpf/redirect.md>)

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf\_map\_lookup\_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

Net device entries can be retrieved using the `bpf_map_lookup_elem()` helper.

<a id="rst-user-space"></a>

### User space

> [!NOTE]
>
> DEVMAP entries can only be updated/deleted from user space and not from an eBPF program. Trying to call these functions from a kernel eBPF program will result in the program failing to load and a verifier warning.

<a id="rst-bpf-map-update-elem"></a>

#### bpf\_map\_update\_elem()



```c
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);
```

Net device entries can be added or updated using the `bpf_map_update_elem()` helper. This helper replaces existing elements atomically. The `value` parameter can be `struct bpf_devmap_val` or a simple `int ifindex` for backwards compatibility.

>
>
> ```c
> struct bpf_devmap_val {
>     __u32 ifindex;   /* device index */
>     union {
>         int   fd;  /* prog fd on map write */
>         __u32 id;  /* prog id on map read */
>     } bpf_prog;
> };
> ```

- **The `flags` argument can be one of the following:**

  - `BPF_ANY`: Create a new element or update an existing element.

  - `BPF_NOEXIST`: Create a new element only if it did not exist.

  - `BPF_EXIST`: Update an existing element.

DEVMAPs can associate a program with a device entry by adding a `bpf_prog.fd` to `struct bpf_devmap_val`. Programs are run after `XDP_REDIRECT` and have access to both Rx device and Tx device. The  program associated with the `fd` must have type XDP with expected attach type `xdp_devmap`. When a program is associated with a device index, the program is run on an `XDP_REDIRECT` and before the buffer is added to the per-cpu queue. Examples of how to attach/use xdp\_devmap progs can be found in the kernel selftests:

- `tools/testing/selftests/bpf/prog_tests/xdp_devmap_attach.c`

- `tools/testing/selftests/bpf/progs/test_xdp_with_devmap_helpers.c`

<a id="rst-bpf-map-lookup-elem-1"></a>

#### bpf\_map\_lookup\_elem()

<a id="c-bpf_map_lookup_elem"></a>



```c
int bpf_map_lookup_elem(int fd, const void *key, void *value);
```

Net device entries can be retrieved using the `bpf_map_lookup_elem()` helper.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf\_map\_delete\_elem()

<a id="c-bpf_map_delete_elem"></a>



```c
int bpf_map_delete_elem(int fd, const void *key);
```

Net device entries can be deleted using the `bpf_map_delete_elem()` helper. This helper will return 0 on success, or negative error in case of failure.

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

## Examples

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

The following code snippet shows how to declare a `BPF_MAP_TYPE_DEVMAP` called tx\_port.



```c
struct {
    __uint(type, BPF_MAP_TYPE_DEVMAP);
    __type(key, __u32);
    __type(value, __u32);
    __uint(max_entries, 256);
} tx_port SEC(".maps");
```

The following code snippet shows how to declare a `BPF_MAP_TYPE_DEVMAP_HASH` called forward\_map.



```c
struct {
    __uint(type, BPF_MAP_TYPE_DEVMAP_HASH);
    __type(key, __u32);
    __type(value, struct bpf_devmap_val);
    __uint(max_entries, 32);
} forward_map SEC(".maps");
```

> [!NOTE]
>
> The value type in the DEVMAP above is a `struct bpf_devmap_val`

The following code snippet shows a simple xdp\_redirect\_map program. This program would work with a user space program that populates the devmap `forward_map` based on ingress ifindexes. The BPF program (below) is redirecting packets using the ingress `ifindex` as the `key`.



```c
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
    int index = ctx->ingress_ifindex;

    return bpf_redirect_map(&forward_map, index, 0);
}
```

The following code snippet shows a BPF program that is broadcasting packets to all the interfaces in the `tx_port` devmap.



```c
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
    return bpf_redirect_map(&tx_port, 0, BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS);
}
```

<a id="rst-user-space-1"></a>

### User space

The following code snippet shows how to update a devmap called `tx_port`.



```c
int update_devmap(int ifindex, int redirect_ifindex)
{
    int ret;

    ret = bpf_map_update_elem(bpf_map__fd(tx_port), &ifindex, &redirect_ifindex, 0);
    if (ret < 0) {
        fprintf(stderr, "Failed to update devmap_ value: %s\n",
            strerror(errno));
    }

    return ret;
}
```

The following code snippet shows how to update a hash\_devmap called `forward_map`.



```c
int update_devmap(int ifindex, int redirect_ifindex)
{
    struct bpf_devmap_val devmap_val = { .ifindex = redirect_ifindex };
    int ret;

    ret = bpf_map_update_elem(bpf_map__fd(forward_map), &ifindex, &devmap_val, 0);
    if (ret < 0) {
        fprintf(stderr, "Failed to update devmap_ value: %s\n",
            strerror(errno));
    }
    return ret;
}
```

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

## References

- [https://lwn.net/Articles/728146/](<https://lwn.net/Articles/728146/>)

- [https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=6f9d451ab1a33728adb72d7ff66a7b374d665176](<https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=6f9d451ab1a33728adb72d7ff66a7b374d665176>)

- [https://elixir.bootlin.com/linux/latest/source/net/core/filter.c\#L4106](<https://elixir.bootlin.com/linux/latest/source/net/core/filter.c#L4106>)

---

# BPF_MAP_TYPE_HASH, with PERCPU and LRU Variants

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_HASH and BPF_MAP_TYPE_PERCPU_HASH provide general purpose hash map storage. Both the key and the value can be structs, allowing for composite keys and values.

<a id="rst-bpf-map-type-hash-with-percpu-and-lru-variants"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

<!-- Copyright (C) 2022-2023 Isovalent, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_HASH` was introduced in kernel version 3.19
>
> - `BPF_MAP_TYPE_PERCPU_HASH` was introduced in version 4.6
>
> - Both `BPF_MAP_TYPE_LRU_HASH` and `BPF_MAP_TYPE_LRU_PERCPU_HASH` were introduced in version 4.10

`BPF_MAP_TYPE_HASH` and `BPF_MAP_TYPE_PERCPU_HASH` provide general purpose hash map storage. Both the key and the value can be structs, allowing for composite keys and values.

The kernel is responsible for allocating and freeing key/value pairs, up to the max_entries limit that you specify. Hash maps use pre-allocation of hash table elements by default. The `BPF_F_NO_PREALLOC` flag can be used to disable pre-allocation when it is too memory expensive.

`BPF_MAP_TYPE_PERCPU_HASH` provides a separate value slot per CPU. The per-cpu values are stored internally in an array.

The `BPF_MAP_TYPE_LRU_HASH` and `BPF_MAP_TYPE_LRU_PERCPU_HASH` variants add LRU semantics to their respective hash tables. An LRU hash will automatically evict the least recently used entries when the hash table reaches capacity. An LRU hash maintains an internal LRU list that is used to select elements for eviction. This internal LRU list is shared across CPUs but it is possible to request a per CPU LRU list with the `BPF_F_NO_COMMON_LRU` flag when calling `bpf_map_create`.  The following table outlines the properties of LRU maps depending on the a map type and the flags used to create the map.


<table>
<thead>
<tr>
<th>


Flag

</th>
<th>


`BPF_MAP_TYPE_LRU_HASH`

</th>
<th>


`BPF_MAP_TYPE_LRU_PERCPU_HASH`

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


**BPF_F_NO_COMMON_LRU**

</td>
<td>


Per-CPU LRU, global map

</td>
<td>


Per-CPU LRU, per-cpu map

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


**\!BPF_F_NO_COMMON_LRU**

</td>
<td>


Global LRU, global map

</td>
<td>


Global LRU, per-cpu map

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

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
```

Hash entries can be added or updated using the `bpf_map_update_elem()` helper. This helper replaces existing elements atomically. The `flags` parameter can be used to control the update behaviour:

- `BPF_ANY` will create a new element or update an existing element

- `BPF_NOEXIST` will create a new element only if one did not already exist

- `BPF_EXIST` will update an existing element

`bpf_map_update_elem()` returns 0 on success, or negative error in case of failure.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

Hash entries can be retrieved using the `bpf_map_lookup_elem()` helper. This helper returns a pointer to the value associated with `key`, or `NULL` if no entry was found.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
long bpf_map_delete_elem(struct bpf_map *map, const void *key)
```

Hash entries can be deleted using the `bpf_map_delete_elem()` helper. This helper will return 0 on success, or negative error in case of failure.

<a id="rst-per-cpu-hashes"></a>

### Per CPU Hashes

For `BPF_MAP_TYPE_PERCPU_HASH` and `BPF_MAP_TYPE_LRU_PERCPU_HASH` the `bpf_map_update_elem()` and `bpf_map_lookup_elem()` helpers automatically access the hash slot for the current CPU.

<a id="rst-bpf-map-lookup-percpu-elem"></a>

#### bpf_map_lookup_percpu_elem()



```c
void *bpf_map_lookup_percpu_elem(struct bpf_map *map, const void *key, u32 cpu)
```

The `bpf_map_lookup_percpu_elem()` helper can be used to lookup the value in the hash slot for a specific CPU. Returns value associated with `key` on `cpu` , or `NULL` if no entry was found or `cpu` is invalid.

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

### Concurrency

Values stored in `BPF_MAP_TYPE_HASH` can be accessed concurrently by programs running on different CPUs.  Since Kernel version 5.1, the BPF infrastructure provides `struct bpf_spin_lock` to synchronise access. See `tools/testing/selftests/bpf/progs/test_spin_lock.c`.

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

### Userspace

<a id="rst-bpf-map-get-next-key"></a>

#### bpf_map_get_next_key()



```c
int bpf_map_get_next_key(int fd, const void *cur_key, void *next_key)
```

In userspace, it is possible to iterate through the keys of a hash using libbpf's `bpf_map_get_next_key()` function. The first key can be fetched by calling `bpf_map_get_next_key()` with `cur_key` set to `NULL`. Subsequent calls will fetch the next key that follows the current key. `bpf_map_get_next_key()` returns 0 on success, -ENOENT if cur_key is the last key in the hash, or negative error in case of failure.

Note that if `cur_key` gets deleted then `bpf_map_get_next_key()` will instead return the *first* key in the hash table which is undesirable. It is recommended to use batched lookup if there is going to be key deletion intermixed with `bpf_map_get_next_key()`.

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

## Examples

Please see the `tools/testing/selftests/bpf` directory for functional examples.  The code snippets below demonstrates API usage.

This example shows how to declare an LRU Hash with a struct key and a struct value.



```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct key {
    __u32 srcip;
};

struct value {
    __u64 packets;
    __u64 bytes;
};

struct {
        __uint(type, BPF_MAP_TYPE_LRU_HASH);
        __uint(max_entries, 32);
        __type(key, struct key);
        __type(value, struct value);
} packet_stats SEC(".maps");
```

This example shows how to create or update hash values using atomic instructions:



```c
static void update_stats(__u32 srcip, int bytes)
{
        struct key key = {
                .srcip = srcip,
        };
        struct value *value = bpf_map_lookup_elem(&packet_stats, &key);

        if (value) {
                __sync_fetch_and_add(&value->packets, 1);
                __sync_fetch_and_add(&value->bytes, bytes);
        } else {
                struct value newval = { 1, bytes };

                bpf_map_update_elem(&packet_stats, &key, &newval, BPF_NOEXIST);
        }
}
```

Userspace walking the map elements from the map declared above:



```c
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

static void walk_hash_elements(int map_fd)
{
        struct key *cur_key = NULL;
        struct key next_key;
        struct value value;
        int err;

        for (;;) {
                err = bpf_map_get_next_key(map_fd, cur_key, &next_key);
                if (err)
                        break;

                bpf_map_lookup_elem(map_fd, &next_key, &value);

                // Use key and value here

                cur_key = &next_key;
        }
}
```

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

## Internals

This section of the document is targeted at Linux developers and describes aspects of the map implementations that are not considered stable ABI. The following details are subject to change in future versions of the kernel.

<a id="rst-bpf-map-type-lru-hash-and-variants"></a>

### `BPF_MAP_TYPE_LRU_HASH` and variants

Updating elements in LRU maps may trigger eviction behaviour when the capacity of the map is reached. There are various steps that the update algorithm attempts in order to enforce the LRU property which have increasing impacts on other CPUs involved in the following operation attempts:

- Attempt to use CPU-local state to batch operations

- Attempt to fetch `target_free` free nodes from global lists

- Attempt to pull any node from a global list and remove it from the hashmap

- Attempt to pull any node from any CPU's list and remove it from the hashmap

The number of nodes to borrow from the global list in a batch, `target_free`, depends on the size of the map. Larger batch size reduces lock contention, but may also exhaust the global structure. The value is computed at map init to avoid exhaustion, by limiting aggregate reservation by all CPUs to half the map size. With a minimum of a single element and maximum budget of 128 at a time.

This algorithm is described visually in the following diagram. See the description in commit 3a08c2fd7634 ("bpf: LRU List") for a full explanation of the corresponding operations:

```mermaid
flowchart TB
  n5(["begin<br/>bpf_map_update()"])
  n6{"Local freelist<br/>node available?"}
  n7["Use node owned<br/>by this CPU"]
  n8{"Map created with<br/>common LRU?<br/>(!BPF_F_NO_COMMON_LRU)"}
  n9["Flush local pending,<br/>Rotate Global list, move<br/>target_free<br/>from global -#62; local"]
  n10{"Able to free<br/>target_free<br/>nodes?"}
  n11["Shrink inactive list<br/>up to remaining<br/>target_free<br/>(global LRU -#62; local)"]
  n12{"#62; 0 entries in<br/>local free list?"}
  n13["Steal one node from<br/>inactive, or if empty,<br/>from active global list"]
  n14["Try to remove<br/>node from hashtab"]
  n15{"Htab removal<br/>successful?"}
  n16{"Map created with<br/>common LRU?<br/>(!BPF_F_NO_COMMON_LRU)"}
  n22["Use node that was<br/>not recently referenced"]
  n23["Use node that was<br/>actively referenced<br/>in global list"]
  n24(["return -ENOMEM"])
  n25["Use node that was<br/>actively referenced<br/>in (another?) CPU's cache"]
  n26["Update hashmap<br/>with new element"]
  n27(["return 0"])
  n28(["return -EBUSY"])
  n29(["return -EEXIST"])
  n30(["return -ENOENT"])
  subgraph g0["Key<br/>(locks held during operation)"]
    direction TB
    n0["remote CPU LRU lock"]
    n1["hashtab lock"]
    n2["LRU lock"]
    n3["local CPU LRU lock"]
    n4["no locks held"]
  end
  subgraph g1["Iterate through CPUs<br/>(start from current)"]
    direction LR
    n17{"Steal a node from<br/>per-cpu freelist?"}
    n18["Steal a node from<br/>(1) Unreferenced pending, or<br/>(2) Any pending node"]
    n19["Try to remove<br/>node from hashtab"]
    n20{"Stole node<br/>from remote<br/>CPU?"}
    n21{"Iterated<br/>all CPUs?"}
  end
  n5 --> n6
  n6 -->|"Y"| n7
  n6 -->|"N"| n8
  n8 -->|"Y"| n9
  n8 -->|"N"| n11
  n9 --> n10
  n10 -->|"Y"| n22
  n10 -->|"N"| n11
  n11 --> n12
  n12 -->|"Y"| n22
  n12 -->|"N"| n13
  n13 --> n14
  n14 --> n15
  n15 -->|"Y"| n23
  n15 -->|"N"| n16
  n16 -->|"Y"| n17
  n16 -->|"N"| n24
  n17 -->|"Y"| n20
  n17 -->|"N"| n18
  n18 --> n19
  n19 --> n20
  n20 -->|"Y"| n25
  n20 -->|"N"| n21
  n21 -->|"Y"| n24
  n21 -->|"N"| n17
  n25 --> n26
  n7 --> n26
  n22 --> n26
  n23 --> n26
  n26 -->|"Success"| n27
  n26 -->|"Hashtab lock failed"| n28
  n26 -->|"BPF_EXIST set and<br/>key already exists"| n29
  n26 -->|"BPF_NOEXIST set<br/>and no such entry"| n30
  style n0 fill:#ffff99,color:#111
  style n1 fill:#fdc086,color:#111
  style n2 fill:#beaed4,color:#111
  style n3 fill:#7fc97f,color:#111
  style n6 fill:#7fc97f,color:#111
  style n9 fill:#beaed4,color:#111
  style n10 fill:#beaed4,color:#111
  style n11 fill:#fdc086,color:#111
  style n12 fill:#beaed4,color:#111
  style n13 fill:#beaed4,color:#111
  style n14 fill:#fdc086,color:#111
  style n17 fill:#ffff99,color:#111
  style n18 fill:#ffff99,color:#111
  style n19 fill:#fdc086,color:#111
  style n26 fill:#fdc086,color:#111
  style g1 stroke-dasharray:6 4
```

Diagram outlining the LRU eviction steps taken during map update.

LRU hash eviction during map update for `BPF_MAP_TYPE_LRU_HASH` and
variants. See the dot file source for kernel function name code references.

Map updates start from the oval in the top right "begin `bpf_map_update()`" and progress through the graph towards the bottom where the result may be either a successful update or a failure with various error codes. The key in the top right provides indicators for which locks may be involved in specific operations. This is intended as a visual hint for reasoning about how map contention may impact update operations, though the map type and flags may impact the actual contention on those locks, based on the logic described in the table above. For instance, if the map is created with type `BPF_MAP_TYPE_LRU_PERCPU_HASH` and flags `BPF_F_NO_COMMON_LRU` then all map properties would be per-cpu.

---

# BPF_MAP_TYPE_LPM_TRIE

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_LPM_TRIE provides a longest prefix match algorithm that can be used to match IP addresses to a stored set of prefixes. Internally, data is stored in an unbalanced trie of nodes that uses prefixlen,data pairs as its keys. The…

<a id="rst-bpf-map-type-lpm-trie"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_LPM_TRIE` was introduced in kernel version 4.11

`BPF_MAP_TYPE_LPM_TRIE` provides a longest prefix match algorithm that can be used to match IP addresses to a stored set of prefixes. Internally, data is stored in an unbalanced trie of nodes that uses `prefixlen,data` pairs as its keys. The `data` is interpreted in network byte order, i.e. big endian, so `data[0]` stores the most significant byte.

LPM tries may be created with a maximum prefix length that is a multiple of 8, in the range from 8 to 2048. The key used for lookup and update operations is a `struct bpf_lpm_trie_key_u8`, extended by `max_prefixlen/8` bytes.

- For IPv4 addresses the data length is 4 bytes

- For IPv6 addresses the data length is 16 bytes

The value type stored in the LPM trie can be any user defined type.

> [!NOTE]
>
> When creating a map of type `BPF_MAP_TYPE_LPM_TRIE` you must set the `BPF_F_NO_PREALLOC` flag.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

The longest prefix entry for a given data value can be found using the `bpf_map_lookup_elem()` helper. This helper returns a pointer to the value associated with the longest matching `key`, or `NULL` if no entry was found.

The `key` should have `prefixlen` set to `max_prefixlen` when performing longest prefix lookups. For example, when searching for the longest prefix match for an IPv4 address, `prefixlen` should be set to `32`.

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
```

Prefix entries can be added or updated using the `bpf_map_update_elem()` helper. This helper replaces existing elements atomically.

`bpf_map_update_elem()` returns `0` on success, or negative error in case of failure.

> > [!NOTE]
> >
> > The flags parameter must be one of BPF_ANY, BPF_NOEXIST or BPF_EXIST, but the value is ignored, giving BPF_ANY semantics.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
long bpf_map_delete_elem(struct bpf_map *map, const void *key)
```

Prefix entries can be deleted using the `bpf_map_delete_elem()` helper. This helper will return 0 on success, or negative error in case of failure.

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

### Userspace

Access from userspace uses libbpf APIs with the same names as above, with the map identified by `fd`.

<a id="rst-bpf-map-get-next-key"></a>

#### bpf_map_get_next_key()



```c
int bpf_map_get_next_key (int fd, const void *cur_key, void *next_key)
```

A userspace program can iterate through the entries in an LPM trie using libbpf's `bpf_map_get_next_key()` function. The first key can be fetched by calling `bpf_map_get_next_key()` with `cur_key` set to `NULL`. Subsequent calls will fetch the next key that follows the current key. `bpf_map_get_next_key()` returns `0` on success, `-ENOENT` if `cur_key` is the last key in the trie, or negative error in case of failure.

`bpf_map_get_next_key()` will iterate through the LPM trie elements from leftmost leaf first. This means that iteration will return more specific keys before less specific ones.

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

## Examples

Please see `tools/testing/selftests/bpf/test_lpm_map.c` for examples of LPM trie usage from userspace. The code snippets below demonstrate API usage.

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

The following BPF code snippet shows how to declare a new LPM trie for IPv4 address prefixes:



```c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct ipv4_lpm_key {
        __u32 prefixlen;
        __u32 data;
};

struct {
        __uint(type, BPF_MAP_TYPE_LPM_TRIE);
        __type(key, struct ipv4_lpm_key);
        __type(value, __u32);
        __uint(map_flags, BPF_F_NO_PREALLOC);
        __uint(max_entries, 255);
} ipv4_lpm_map SEC(".maps");
```

The following BPF code snippet shows how to lookup by IPv4 address:



```c
void *lookup(__u32 ipaddr)
{
        struct ipv4_lpm_key key = {
                .prefixlen = 32,
                .data = ipaddr
        };

        return bpf_map_lookup_elem(&ipv4_lpm_map, &key);
}
```

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

### Userspace

The following snippet shows how to insert an IPv4 prefix entry into an LPM trie:



```c
int add_prefix_entry(int lpm_fd, __u32 addr, __u32 prefixlen, struct value *value)
{
        struct ipv4_lpm_key ipv4_key = {
                .prefixlen = prefixlen,
                .data = addr
        };
        return bpf_map_update_elem(lpm_fd, &ipv4_key, value, BPF_ANY);
}
```

The following snippet shows a userspace program walking through the entries of an LPM trie:



```c
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

void iterate_lpm_trie(int map_fd)
{
        struct ipv4_lpm_key *cur_key = NULL;
        struct ipv4_lpm_key next_key;
        struct value value;
        int err;

        for (;;) {
                err = bpf_map_get_next_key(map_fd, cur_key, &next_key);
                if (err)
                        break;

                bpf_map_lookup_elem(map_fd, &next_key, &value);

                /* Use key and value here */

                cur_key = &next_key;
        }
}
```

---

# BPF_MAP_TYPE_ARRAY_OF_MAPS and BPF_MAP_TYPE_HASH_OF_MAPS

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_ARRAY_OF_MAPS and BPF_MAP_TYPE_HASH_OF_MAPS provide general purpose support for map in map storage. One level of nesting is supported, where an outer map contains instances of a single type of inner map, for example…

<a id="rst-bpf-map-type-array-of-maps-and-bpf-map-type-hash-of-maps"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_ARRAY_OF_MAPS` and `BPF_MAP_TYPE_HASH_OF_MAPS` were introduced in kernel version 4.12

`BPF_MAP_TYPE_ARRAY_OF_MAPS` and `BPF_MAP_TYPE_HASH_OF_MAPS` provide general purpose support for map in map storage. One level of nesting is supported, where an outer map contains instances of a single type of inner map, for example `array_of_maps->sock_map`.

When creating an outer map, an inner map instance is used to initialize the metadata that the outer map holds about its inner maps. This inner map has a separate lifetime from the outer map and can be deleted after the outer map has been created.

The outer map supports element lookup, update and delete from user space using the syscall API. A BPF program is only allowed to do element lookup in the outer map.

> [!NOTE]
>
> - Multi-level nesting is not supported.
>
> - Any BPF map type can be used as an inner map, except for `BPF_MAP_TYPE_PROG_ARRAY`.
>
> - A BPF program cannot update or delete outer map entries.

For `BPF_MAP_TYPE_ARRAY_OF_MAPS` the key is an unsigned 32-bit integer index into the array. The array is a fixed size with `max_entries` elements that are zero initialized when created.

For `BPF_MAP_TYPE_HASH_OF_MAPS` the key type can be chosen when defining the map. The kernel is responsible for allocating and freeing key/value pairs, up to the max_entries limit that you specify. Hash maps use pre-allocation of hash table elements by default. The `BPF_F_NO_PREALLOC` flag can be used to disable pre-allocation when it is too memory expensive.

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

## Usage

<a id="rst-kernel-bpf-helper"></a>

### Kernel BPF Helper

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

Inner maps can be retrieved using the `bpf_map_lookup_elem()` helper. This helper returns a pointer to the inner map, or `NULL` if no entry was found.

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

## Examples

<a id="rst-kernel-bpf-example"></a>

### Kernel BPF Example

This snippet shows how to create and initialise an array of devmaps in a BPF program. Note that the outer array can only be modified from user space using the syscall API.



```c
struct inner_map {
        __uint(type, BPF_MAP_TYPE_DEVMAP);
        __uint(max_entries, 10);
        __type(key, __u32);
        __type(value, __u32);
} inner_map1 SEC(".maps"), inner_map2 SEC(".maps");

struct {
        __uint(type, BPF_MAP_TYPE_ARRAY_OF_MAPS);
        __uint(max_entries, 2);
        __type(key, __u32);
        __array(values, struct inner_map);
} outer_map SEC(".maps") = {
        .values = { &inner_map1,
                    &inner_map2 }
};
```

See `progs/test_btf_map_in_map.c` in `tools/testing/selftests/bpf` for more examples of declarative initialisation of outer maps.

<a id="rst-user-space"></a>

### User Space

This snippet shows how to create an array based outer map:



```c
int create_outer_array(int inner_fd) {
        LIBBPF_OPTS(bpf_map_create_opts, opts, .inner_map_fd = inner_fd);
        int fd;

        fd = bpf_map_create(BPF_MAP_TYPE_ARRAY_OF_MAPS,
                            "example_array",       /* name */
                            sizeof(__u32),         /* key size */
                            sizeof(__u32),         /* value size */
                            256,                   /* max entries */
                            &opts);                /* create opts */
        return fd;
}
```

This snippet shows how to add an inner map to an outer map:



```c
int add_devmap(int outer_fd, int index, const char *name) {
        int fd;

        fd = bpf_map_create(BPF_MAP_TYPE_DEVMAP, name,
                            sizeof(__u32), sizeof(__u32), 256, NULL);
        if (fd < 0)
                return fd;

        return bpf_map_update_elem(outer_fd, &index, &fd, BPF_ANY);
}
```

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

## References

- [https://lore.kernel.org/netdev/20170322170035.923581-3-kafai@fb.com/](<https://lore.kernel.org/netdev/20170322170035.923581-3-kafai@fb.com/>)

- [https://lore.kernel.org/netdev/20170322170035.923581-4-kafai@fb.com/](<https://lore.kernel.org/netdev/20170322170035.923581-4-kafai@fb.com/>)

---

# BPF_MAP_TYPE_QUEUE and BPF_MAP_TYPE_STACK

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_QUEUE provides FIFO storage and BPF_MAP_TYPE_STACK provides LIFO storage for BPF programs. These maps support peek, pop and push operations that are exposed to BPF programs through the respective helpers. These operations are…

<a id="rst-bpf-map-type-queue-and-bpf-map-type-stack"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_QUEUE` and `BPF_MAP_TYPE_STACK` were introduced in kernel version 4.20

`BPF_MAP_TYPE_QUEUE` provides FIFO storage and `BPF_MAP_TYPE_STACK` provides LIFO storage for BPF programs. These maps support peek, pop and push operations that are exposed to BPF programs through the respective helpers. These operations are exposed to userspace applications using the existing `bpf` syscall in the following way:

- `BPF_MAP_LOOKUP_ELEM` -&gt; peek

- `BPF_MAP_LOOKUP_AND_DELETE_ELEM` -&gt; pop

- `BPF_MAP_UPDATE_ELEM` -&gt; push

`BPF_MAP_TYPE_QUEUE` and `BPF_MAP_TYPE_STACK` do not support `BPF_F_NO_PREALLOC`.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-map-push-elem"></a>

#### bpf_map_push_elem()



```c
long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 flags)
```

An element `value` can be added to a queue or stack using the `bpf_map_push_elem` helper. The `flags` parameter must be set to `BPF_ANY` or `BPF_EXIST`. If `flags` is set to `BPF_EXIST` then, when the queue or stack is full, the oldest element will be removed to make room for `value` to be added. Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-peek-elem"></a>

#### bpf_map_peek_elem()



```c
long bpf_map_peek_elem(struct bpf_map *map, void *value)
```

This helper fetches an element `value` from a queue or stack without removing it. Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-pop-elem"></a>

#### bpf_map_pop_elem()



```c
long bpf_map_pop_elem(struct bpf_map *map, void *value)
```

This helper removes an element into `value` from a queue or stack. Returns `0` on success, or negative error in case of failure.

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

### Userspace

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem (int fd, const void *key, const void *value, __u64 flags)
```

A userspace program can push `value` onto a queue or stack using libbpf's `bpf_map_update_elem` function. The `key` parameter must be set to `NULL` and `flags` must be set to `BPF_ANY` or `BPF_EXIST`, with the same semantics as the `bpf_map_push_elem` kernel helper. Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem (int fd, const void *key, void *value)
```

A userspace program can peek at the `value` at the head of a queue or stack using the libbpf `bpf_map_lookup_elem` function. The `key` parameter must be set to `NULL`.  Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-lookup-and-delete-elem"></a>

#### bpf_map_lookup_and_delete_elem()



```c
int bpf_map_lookup_and_delete_elem (int fd, const void *key, void *value)
```

A userspace program can pop a `value` from the head of a queue or stack using the libbpf `bpf_map_lookup_and_delete_elem` function. The `key` parameter must be set to `NULL`. Returns `0` on success, or negative error in case of failure.

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

## Examples

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

This snippet shows how to declare a queue in a BPF program:



```c
struct {
        __uint(type, BPF_MAP_TYPE_QUEUE);
        __type(value, __u32);
        __uint(max_entries, 10);
} queue SEC(".maps");
```

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

### Userspace

This snippet shows how to use libbpf's low-level API to create a queue from userspace:



```c
int create_queue()
{
        return bpf_map_create(BPF_MAP_TYPE_QUEUE,
                              "sample_queue", /* name */
                              0,              /* key size, must be zero */
                              sizeof(__u32),  /* value size */
                              10,             /* max entries */
                              NULL);          /* create options */
}
```

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

## References

[https://lwn.net/ml/netdev/153986858555.9127.14517764371945179514.stgit@kernel/](<https://lwn.net/ml/netdev/153986858555.9127.14517764371945179514.stgit@kernel/>)

---

# BPF_MAP_TYPE_SK_STORAGE

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_SK_STORAGE is used to provide socket-local storage for BPF programs. A map of type BPF_MAP_TYPE_SK_STORAGE declares the type of storage to be provided and acts as the handle for accessing the socket-local storage. The values…

<a id="rst-bpf-map-type-sk-storage"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_SK_STORAGE` was introduced in kernel version 5.2

`BPF_MAP_TYPE_SK_STORAGE` is used to provide socket-local storage for BPF programs. A map of type `BPF_MAP_TYPE_SK_STORAGE` declares the type of storage to be provided and acts as the handle for accessing the socket-local storage. The values for maps of type `BPF_MAP_TYPE_SK_STORAGE` are stored locally with each socket instead of with the map. The kernel is responsible for allocating storage for a socket when requested and for freeing the storage when either the map or the socket is deleted.

> [!NOTE]
>
> - The key type must be `int` and `max_entries` must be set to `0`.
>
> - The `BPF_F_NO_PREALLOC` flag must be used when creating a map for socket-local storage.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-sk-storage-get"></a>

#### bpf_sk_storage_get()



```c
void *bpf_sk_storage_get(struct bpf_map *map, void *sk, void *value, u64 flags)
```

Socket-local storage for `map` can be retrieved from socket `sk` using the `bpf_sk_storage_get()` helper. If the `BPF_LOCAL_STORAGE_GET_F_CREATE` flag is used then `bpf_sk_storage_get()` will create the storage for `sk` if it does not already exist. `value` can be used together with `BPF_LOCAL_STORAGE_GET_F_CREATE` to initialize the storage value, otherwise it will be zero initialized. Returns a pointer to the storage on success, or `NULL` in case of failure.

> [!NOTE]
>
> - `sk` is a kernel `struct sock` pointer for LSM or tracing programs.
>
> - `sk` is a `struct bpf_sock` pointer for other program types.

<a id="rst-bpf-sk-storage-delete"></a>

#### bpf_sk_storage_delete()



```c
long bpf_sk_storage_delete(struct bpf_map *map, void *sk)
```

Socket-local storage for `map` can be deleted from socket `sk` using the `bpf_sk_storage_delete()` helper. Returns `0` on success, or negative error in case of failure.

<a id="rst-user-space"></a>

### User space

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem(int map_fd, const void *key, const void *value, __u64 flags)
```

Socket-local storage for map `map_fd` can be added or updated locally to a socket using the `bpf_map_update_elem()` libbpf function. The socket is identified by a `socket` `fd` stored in the pointer `key`. The pointer `value` has the data to be added or updated to the socket `fd`. The type and size of `value` should be the same as the value type of the map definition.

The `flags` parameter can be used to control the update behaviour:

- `BPF_ANY` will create storage for `socket` `fd` or update existing storage.

- `BPF_NOEXIST` will create storage for `socket` `fd` only if it did not already exist, otherwise the call will fail with `-EEXIST`.

- `BPF_EXIST` will update existing storage for `socket` `fd` if it already exists, otherwise the call will fail with `-ENOENT`.

Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem(int map_fd, const void *key, void *value)
```

Socket-local storage for map `map_fd` can be retrieved from a socket using the `bpf_map_lookup_elem()` libbpf function. The storage is retrieved from the socket identified by a `socket` `fd` stored in the pointer `key`. Returns `0` on success, or negative error in case of failure.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
int bpf_map_delete_elem(int map_fd, const void *key)
```

Socket-local storage for map `map_fd` can be deleted from a socket using the `bpf_map_delete_elem()` libbpf function. The storage is deleted from the socket identified by a `socket` `fd` stored in the pointer `key`. Returns `0` on success, or negative error in case of failure.

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

## Examples

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

This snippet shows how to declare socket-local storage in a BPF program:



```c
struct {
        __uint(type, BPF_MAP_TYPE_SK_STORAGE);
        __uint(map_flags, BPF_F_NO_PREALLOC);
        __type(key, int);
        __type(value, struct my_storage);
} socket_storage SEC(".maps");
```

This snippet shows how to retrieve socket-local storage in a BPF program:



```c
SEC("sockops")
int _sockops(struct bpf_sock_ops *ctx)
{
        struct my_storage *storage;
        struct bpf_sock *sk;

        sk = ctx->sk;
        if (!sk)
                return 1;

        storage = bpf_sk_storage_get(&socket_storage, sk, 0,
                                     BPF_LOCAL_STORAGE_GET_F_CREATE);
        if (!storage)
                return 1;

        /* Use 'storage' here */

        return 1;
}
```

Please see the `tools/testing/selftests/bpf` directory for functional examples.

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

## References

[https://lwn.net/ml/netdev/20190426171103.61892-1-kafai@fb.com/](<https://lwn.net/ml/netdev/20190426171103.61892-1-kafai@fb.com/>)

---

# BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH

_Peios Kernel / Internals / BPF_

> BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH maps can be used to redirect skbs between sockets or to apply policy at the socket level based on the result of a BPF (verdict) program with the help of the BPF helpers bpf_sk_redirect_map(),…

<a id="rst-bpf-map-type-sockmap-and-bpf-map-type-sockhash"></a>

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

<!-- Copyright Red Hat -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_SOCKMAP` was introduced in kernel version 4.14
>
> - `BPF_MAP_TYPE_SOCKHASH` was introduced in kernel version 4.18

`BPF_MAP_TYPE_SOCKMAP` and `BPF_MAP_TYPE_SOCKHASH` maps can be used to redirect skbs between sockets or to apply policy at the socket level based on the result of a BPF (verdict) program with the help of the BPF helpers `bpf_sk_redirect_map()`, `bpf_sk_redirect_hash()`, `bpf_msg_redirect_map()` and `bpf_msg_redirect_hash()`.

`BPF_MAP_TYPE_SOCKMAP` is backed by an array that uses an integer key as the index to look up a reference to a `struct sock`. The map values are socket descriptors. Similarly, `BPF_MAP_TYPE_SOCKHASH` is a hash backed BPF map that holds references to sockets via their socket descriptors.

> [!NOTE]
>
> The value type is either \__u32 or \__u64; the latter (\__u64) is to support returning socket cookies to userspace. Returning the `struct sock *` that the map holds to user-space is neither safe nor useful.

These maps may have BPF programs attached to them, specifically a parser program and a verdict program. The parser program determines how much data has been parsed and therefore how much data needs to be queued to come to a verdict. The verdict program is essentially the redirect program and can return a verdict of `__SK_DROP`, `__SK_PASS`, or `__SK_REDIRECT`.

When a socket is inserted into one of these maps, its socket callbacks are replaced and a `struct sk_psock` is attached to it. Additionally, this `sk_psock` inherits the programs that are attached to the map.

A sock object may be in multiple maps, but can only inherit a single parse or verdict program. If adding a sock object to a map would result in having multiple parser programs the update will return an EBUSY error.

The supported programs to attach to these maps are:



```c
struct sk_psock_progs {
        struct bpf_prog *msg_parser;
        struct bpf_prog *stream_parser;
        struct bpf_prog *stream_verdict;
        struct bpf_prog *skb_verdict;
};
```

> [!NOTE]
>
> Users are not allowed to attach `stream_verdict` and `skb_verdict` programs to the same map.

The attach types for the map programs are:

- `msg_parser` program - `BPF_SK_MSG_VERDICT`.

- `stream_parser` program - `BPF_SK_SKB_STREAM_PARSER`.

- `stream_verdict` program - `BPF_SK_SKB_STREAM_VERDICT`.

- `skb_verdict` program - `BPF_SK_SKB_VERDICT`.

There are additional helpers available to use with the parser and verdict programs: `bpf_msg_apply_bytes()` and `bpf_msg_cork_bytes()`. With `bpf_msg_apply_bytes()` BPF programs can tell the infrastructure how many bytes the given verdict should apply to. The helper `bpf_msg_cork_bytes()` handles a different case where a BPF program cannot reach a verdict on a msg until it receives more bytes AND the program doesn't want to forward the packet until it is known to be good.

Finally, the helpers `bpf_msg_pull_data()` and `bpf_msg_push_data()` are available to `BPF_PROG_TYPE_SK_MSG` BPF programs to pull in data and set the start and end pointers to given values or to add metadata to the `struct sk_msg_buff *msg`.

All these helpers will be described in more detail below.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-msg-redirect-map"></a>

#### bpf_msg_redirect_map()



```c
long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags)
```

This helper is used in programs implementing policies at the socket level. If the message `msg` is allowed to pass (i.e., if the verdict BPF program returns `SK_PASS`), redirect it to the socket referenced by `map` (of type `BPF_MAP_TYPE_SOCKMAP`) at index `key`. Both ingress and egress interfaces can be used for redirection. The `BPF_F_INGRESS` value in `flags` is used to select the ingress path otherwise the egress path is selected. This is the only flag supported for now.

Returns `SK_PASS` on success, or `SK_DROP` on error.

<a id="rst-bpf-sk-redirect-map"></a>

#### bpf_sk_redirect_map()



```c
long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key u64 flags)
```

Redirect the packet to the socket referenced by `map` (of type `BPF_MAP_TYPE_SOCKMAP`) at index `key`. Both ingress and egress interfaces can be used for redirection. The `BPF_F_INGRESS` value in `flags` is used to select the ingress path otherwise the egress path is selected. This is the only flag supported for now.

Returns `SK_PASS` on success, or `SK_DROP` on error.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

socket entries of type `struct sock *` can be retrieved using the `bpf_map_lookup_elem()` helper.

<a id="rst-bpf-sock-map-update"></a>

#### bpf_sock_map_update()



```c
long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
```

Add an entry to, or update a `map` referencing sockets. The `skops` is used as a new value for the entry associated to `key`. The `flags` argument can be one of the following:

- `BPF_ANY`: Create a new element or update an existing element.

- `BPF_NOEXIST`: Create a new element only if it did not exist.

- `BPF_EXIST`: Update an existing element.

If the `map` has BPF programs (parser and verdict), those will be inherited by the socket being added. If the socket is already attached to BPF programs, this results in an error.

Returns 0 on success, or a negative error in case of failure.

<a id="rst-bpf-sock-hash-update"></a>

#### bpf_sock_hash_update()



```c
long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
```

Add an entry to, or update a sockhash `map` referencing sockets. The `skops` is used as a new value for the entry associated to `key`.

The `flags` argument can be one of the following:

- `BPF_ANY`: Create a new element or update an existing element.

- `BPF_NOEXIST`: Create a new element only if it did not exist.

- `BPF_EXIST`: Update an existing element.

If the `map` has BPF programs (parser and verdict), those will be inherited by the socket being added. If the socket is already attached to BPF programs, this results in an error.

Returns 0 on success, or a negative error in case of failure.

<a id="rst-bpf-msg-redirect-hash"></a>

#### bpf_msg_redirect_hash()



```c
long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags)
```

This helper is used in programs implementing policies at the socket level. If the message `msg` is allowed to pass (i.e., if the verdict BPF program returns `SK_PASS`), redirect it to the socket referenced by `map` (of type `BPF_MAP_TYPE_SOCKHASH`) using hash `key`. Both ingress and egress interfaces can be used for redirection. The `BPF_F_INGRESS` value in `flags` is used to select the ingress path otherwise the egress path is selected. This is the only flag supported for now.

Returns `SK_PASS` on success, or `SK_DROP` on error.

<a id="rst-bpf-sk-redirect-hash"></a>

#### bpf_sk_redirect_hash()



```c
long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags)
```

This helper is used in programs implementing policies at the skb socket level. If the sk_buff `skb` is allowed to pass (i.e., if the verdict BPF program returns `SK_PASS`), redirect it to the socket referenced by `map` (of type `BPF_MAP_TYPE_SOCKHASH`) using hash `key`. Both ingress and egress interfaces can be used for redirection. The `BPF_F_INGRESS` value in `flags` is used to select the ingress path otherwise the egress path is selected. This is the only flag supported for now.

Returns `SK_PASS` on success, or `SK_DROP` on error.

<a id="rst-bpf-msg-apply-bytes"></a>

#### bpf_msg_apply_bytes()



```c
long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes)
```

For socket policies, apply the verdict of the BPF program to the next (number of `bytes`) of message `msg`. For example, this helper can be used in the following cases:

- A single `sendmsg()` or `sendfile()` system call contains multiple logical messages that the BPF program is supposed to read and for which it should apply a verdict.

- A BPF program only cares to read the first `bytes` of a `msg`. If the message has a large payload, then setting up and calling the BPF program repeatedly for all bytes, even though the verdict is already known, would create unnecessary overhead.

Returns 0

<a id="rst-bpf-msg-cork-bytes"></a>

#### bpf_msg_cork_bytes()



```c
long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes)
```

For socket policies, prevent the execution of the verdict BPF program for message `msg` until the number of `bytes` have been accumulated.

This can be used when one needs a specific number of bytes before a verdict can be assigned, even if the data spans multiple `sendmsg()` or `sendfile()` calls.

Returns 0

<a id="rst-bpf-msg-pull-data"></a>

#### bpf_msg_pull_data()



```c
long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags)
```

For socket policies, pull in non-linear data from user space for `msg` and set pointers `msg->data` and `msg->data_end` to `start` and `end` bytes offsets into `msg`, respectively.

If a program of type `BPF_PROG_TYPE_SK_MSG` is run on a `msg` it can only parse data that the (`data`, `data_end`) pointers have already consumed. For `sendmsg()` hooks this is likely the first scatterlist element. But for calls relying on MSG_SPLICE_PAGES (e.g., `sendfile()`) this will be the range (**0**, **0**) because the data is shared with user space and by default the objective is to avoid allowing user space to modify data while (or after) BPF verdict is being decided. This helper can be used to pull in data and to set the start and end pointers to given values. Data will be copied if necessary (i.e., if data was not linear and if start and end pointers do not point to the same chunk).

A call to this helper is susceptible to change the underlying packet buffer. Therefore, at load time, all checks on pointers previously done by the verifier are invalidated and must be performed again, if the helper is used in combination with direct packet access.

All values for `flags` are reserved for future usage, and must be left at zero.

Returns 0 on success, or a negative error in case of failure.

<a id="rst-bpf-map-lookup-elem-1"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

Look up a socket entry in the sockmap or sockhash map.

Returns the socket entry associated to `key`, or NULL if no entry was found.

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
```

Add or update a socket entry in a sockmap or sockhash.

The flags argument can be one of the following:

- BPF_ANY: Create a new element or update an existing element.

- BPF_NOEXIST: Create a new element only if it did not exist.

- BPF_EXIST: Update an existing element.

Returns 0 on success, or a negative error in case of failure.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
long bpf_map_delete_elem(struct bpf_map *map, const void *key)
```

Delete a socket entry from a sockmap or a sockhash.

Returns 0 on success, or a negative error in case of failure.

<a id="rst-user-space"></a>

### User space

<a id="rst-bpf-map-update-elem-1"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags)
```

Sockmap entries can be added or updated using the `bpf_map_update_elem()` function. The `key` parameter is the index value of the sockmap array. And the `value` parameter is the FD value of that socket.

Under the hood, the sockmap update function uses the socket FD value to retrieve the associated socket and its attached psock.

The flags argument can be one of the following:

- BPF_ANY: Create a new element or update an existing element.

- BPF_NOEXIST: Create a new element only if it did not exist.

- BPF_EXIST: Update an existing element.

<a id="rst-bpf-map-lookup-elem-2"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem(int fd, const void *key, void *value)
```

Sockmap entries can be retrieved using the `bpf_map_lookup_elem()` function.

> [!NOTE]
>
> The entry returned is a socket cookie rather than a socket itself.

<a id="rst-bpf-map-delete-elem-1"></a>

#### bpf_map_delete_elem()



```c
int bpf_map_delete_elem(int fd, const void *key)
```

Sockmap entries can be deleted using the `bpf_map_delete_elem()` function.

Returns 0 on success, or negative error in case of failure.

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

## Examples

<a id="rst-kernel-bpf-1"></a>

### Kernel BPF

Several examples of the use of sockmap APIs can be found in:

- [tools/testing/selftests/bpf/progs/test_sockmap_kern.h](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_kern.h>)

- [tools/testing/selftests/bpf/progs/sockmap_parse_prog.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_parse_prog.c>)

- [tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c>)

- [tools/testing/selftests/bpf/progs/test_sockmap_listen.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_listen.c>)

- [tools/testing/selftests/bpf/progs/test_sockmap_update.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_update.c>)

The following code snippet shows how to declare a sockmap.



```c
struct {
        __uint(type, BPF_MAP_TYPE_SOCKMAP);
        __uint(max_entries, 1);
        __type(key, __u32);
        __type(value, __u64);
} sock_map_rx SEC(".maps");
```

The following code snippet shows a sample parser program.



```c
SEC("sk_skb/stream_parser")
int bpf_prog_parser(struct __sk_buff *skb)
{
        return skb->len;
}
```

The following code snippet shows a simple verdict program that interacts with a sockmap to redirect traffic to another socket based on the local port.



```c
SEC("sk_skb/stream_verdict")
int bpf_prog_verdict(struct __sk_buff *skb)
{
        __u32 lport = skb->local_port;
        __u32 idx = 0;

        if (lport == 10000)
                return bpf_sk_redirect_map(skb, &sock_map_rx, idx, 0);

        return SK_PASS;
}
```

The following code snippet shows how to declare a sockhash map.



```c
struct socket_key {
        __u32 src_ip;
        __u32 dst_ip;
        __u32 src_port;
        __u32 dst_port;
};

struct {
        __uint(type, BPF_MAP_TYPE_SOCKHASH);
        __uint(max_entries, 1);
        __type(key, struct socket_key);
        __type(value, __u64);
} sock_hash_rx SEC(".maps");
```

The following code snippet shows a simple verdict program that interacts with a sockhash to redirect traffic to another socket based on a hash of some of the skb parameters.



```c
static inline
void extract_socket_key(struct __sk_buff *skb, struct socket_key *key)
{
        key->src_ip = skb->remote_ip4;
        key->dst_ip = skb->local_ip4;
        key->src_port = skb->remote_port >> 16;
        key->dst_port = (bpf_htonl(skb->local_port)) >> 16;
}

SEC("sk_skb/stream_verdict")
int bpf_prog_verdict(struct __sk_buff *skb)
{
        struct socket_key key;

        extract_socket_key(skb, &key);

        return bpf_sk_redirect_hash(skb, &sock_hash_rx, &key, 0);
}
```

<a id="rst-user-space-1"></a>

### User space

Several examples of the use of sockmap APIs can be found in:

- [tools/testing/selftests/bpf/prog_tests/sockmap_basic.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/prog_tests/sockmap_basic.c>)

- [tools/testing/selftests/bpf/test_sockmap.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_sockmap.c>)

- [tools/testing/selftests/bpf/test_maps.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_maps.c>)

The following code sample shows how to create a sockmap, attach a parser and verdict program, as well as add a socket entry.



```c
int create_sample_sockmap(int sock, int parse_prog_fd, int verdict_prog_fd)
{
        int index = 0;
        int map, err;

        map = bpf_map_create(BPF_MAP_TYPE_SOCKMAP, NULL, sizeof(int), sizeof(int), 1, NULL);
        if (map < 0) {
                fprintf(stderr, "Failed to create sockmap: %s\n", strerror(errno));
                return -1;
        }

        err = bpf_prog_attach(parse_prog_fd, map, BPF_SK_SKB_STREAM_PARSER, 0);
        if (err){
                fprintf(stderr, "Failed to attach_parser_prog_to_map: %s\n", strerror(errno));
                goto out;
        }

        err = bpf_prog_attach(verdict_prog_fd, map, BPF_SK_SKB_STREAM_VERDICT, 0);
        if (err){
                fprintf(stderr, "Failed to attach_verdict_prog_to_map: %s\n", strerror(errno));
                goto out;
        }

        err = bpf_map_update_elem(map, &index, &sock, BPF_NOEXIST);
        if (err) {
                fprintf(stderr, "Failed to update sockmap: %s\n", strerror(errno));
                goto out;
        }

out:
        close(map);
        return err;
}
```

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

## References

- [https://github.com/jrfastab/linux-kernel-xdp/commit/c89fd73cb9d2d7f3c716c3e00836f07b1aeb261f](<https://github.com/jrfastab/linux-kernel-xdp/commit/c89fd73cb9d2d7f3c716c3e00836f07b1aeb261f>)

- [https://lwn.net/Articles/731133/](<https://lwn.net/Articles/731133/>)

- [http://vger.kernel.org/lpc_net2018_talks/ktls_bpf_paper.pdf](<http://vger.kernel.org/lpc_net2018_talks/ktls_bpf_paper.pdf>)

- [https://lwn.net/Articles/748628/](<https://lwn.net/Articles/748628/>)

- [https://lore.kernel.org/bpf/20200218171023.844439-7-jakub@cloudflare.com/](<https://lore.kernel.org/bpf/20200218171023.844439-7-jakub@cloudflare.com/>)

<a id="rst-tools-testing-selftests-bpf-progs-test-sockmap-kern-h"></a>



<a id="rst-tools-testing-selftests-bpf-progs-sockmap-parse-prog-c"></a>



<a id="rst-tools-testing-selftests-bpf-progs-sockmap-verdict-prog-c"></a>



<a id="rst-tools-testing-selftests-bpf-prog-tests-sockmap-basic-c"></a>



<a id="rst-tools-testing-selftests-bpf-test-sockmap-c"></a>



<a id="rst-tools-testing-selftests-bpf-test-maps-c"></a>



<a id="rst-tools-testing-selftests-bpf-progs-test-sockmap-listen-c"></a>



<a id="rst-tools-testing-selftests-bpf-progs-test-sockmap-update-c"></a>

---

# BPF_MAP_TYPE_XSKMAP

_Peios Kernel / Internals / BPF_

> The BPF_MAP_TYPE_XSKMAP is used as a backend map for XDP BPF helper call bpf_redirect_map() and XDP_REDIRECT action, like 'devmap' and 'cpumap'. This map type redirects raw XDP frames to AF_XDP sockets (XSKs), a new type of address family…

<a id="rst-bpf-map-type-xskmap"></a>

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

> [!NOTE]
>
> - `BPF_MAP_TYPE_XSKMAP` was introduced in kernel version 4.18

The `BPF_MAP_TYPE_XSKMAP` is used as a backend map for XDP BPF helper call `bpf_redirect_map()` and `XDP_REDIRECT` action, like 'devmap' and 'cpumap'. This map type redirects raw XDP frames to [AF_XDP](<https://www.kernel.org/doc/html/latest/networking/af_xdp.html>) sockets (XSKs), a new type of address family in the kernel that allows redirection of frames from a driver to user space without having to traverse the full network stack. An AF_XDP socket binds to a single netdev queue. A mapping of XSKs to queues is shown below:



```none
+---------------------------------------------------+
|     xsk A      |     xsk B       |      xsk C     |<---+ User space
=========================================================|==========
|    Queue 0     |     Queue 1     |     Queue 2    |    |  Kernel
+---------------------------------------------------+    |
|                  Netdev eth0                      |    |
+---------------------------------------------------+    |
|                            +=============+        |    |
|                            | key |  xsk  |        |    |
|  +---------+               +=============+        |    |
|  |         |               |  0  | xsk A |        |    |
|  |         |               +-------------+        |    |
|  |         |               |  1  | xsk B |        |    |
|  | BPF     |-- redirect -->+-------------+-------------+
|  | prog    |               |  2  | xsk C |        |
|  |         |               +-------------+        |
|  |         |                                      |
|  |         |                                      |
|  +---------+                                      |
|                                                   |
+---------------------------------------------------+
```

> [!NOTE]
>
> An AF_XDP socket that is bound to a certain &lt;netdev/queue_id&gt; will *only* accept XDP frames from that &lt;netdev/queue_id&gt;. If an XDP program tries to redirect from a &lt;netdev/queue_id&gt; other than what the socket is bound to, the frame will not be received on the socket.

Typically an XSKMAP is created per netdev. This map contains an array of XSK File Descriptors (FDs). The number of array elements is typically set or adjusted using the `max_entries` map parameter. For AF_XDP `max_entries` is equal to the number of queues supported by the netdev.

> [!NOTE]
>
> Both the map key and map value size must be 4 bytes.

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

## Usage

<a id="rst-kernel-bpf"></a>

### Kernel BPF

<a id="rst-bpf-redirect-map"></a>

#### bpf_redirect_map()



```c
long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
```

Redirect the packet to the endpoint referenced by `map` at index `key`. For `BPF_MAP_TYPE_XSKMAP` this map contains references to XSK FDs for sockets attached to a netdev's queues.

> [!NOTE]
>
> If the map is empty at an index, the packet is dropped. This means that it is necessary to have an XDP program loaded with at least one XSK in the XSKMAP to be able to get any traffic to user space through the socket.

<a id="rst-bpf-map-lookup-elem"></a>

#### bpf_map_lookup_elem()



```c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
```

XSK entry references of type `struct xdp_sock *` can be retrieved using the `bpf_map_lookup_elem()` helper.

<a id="rst-user-space"></a>

### User space

> [!NOTE]
>
> XSK entries can only be updated/deleted from user space and not from a BPF program. Trying to call these functions from a kernel BPF program will result in the program failing to load and a verifier warning.

<a id="rst-bpf-map-update-elem"></a>

#### bpf_map_update_elem()



```c
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags)
```

XSK entries can be added or updated using the `bpf_map_update_elem()` helper. The `key` parameter is equal to the queue_id of the queue the XSK is attaching to. And the `value` parameter is the FD value of that socket.

Under the hood, the XSKMAP update function uses the XSK FD value to retrieve the associated `struct xdp_sock` instance.

The flags argument can be one of the following:

- BPF_ANY: Create a new element or update an existing element.

- BPF_NOEXIST: Create a new element only if it did not exist.

- BPF_EXIST: Update an existing element.

<a id="rst-bpf-map-lookup-elem-1"></a>

#### bpf_map_lookup_elem()



```c
int bpf_map_lookup_elem(int fd, const void *key, void *value)
```

Returns `struct xdp_sock *` or negative error in case of failure.

<a id="rst-bpf-map-delete-elem"></a>

#### bpf_map_delete_elem()



```c
int bpf_map_delete_elem(int fd, const void *key)
```

XSK entries can be deleted using the `bpf_map_delete_elem()` helper. This helper will return 0 on success, or negative error in case of failure.

> [!NOTE]
>
> When [libxdp](<https://github.com/xdp-project/xdp-tools/tree/master/lib/libxdp>) deletes an XSK it also removes the associated socket entry from the XSKMAP.

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

## Examples

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

### Kernel

The following code snippet shows how to declare a `BPF_MAP_TYPE_XSKMAP` called `xsks_map` and how to redirect packets to an XSK.



```c
struct {
        __uint(type, BPF_MAP_TYPE_XSKMAP);
        __type(key, __u32);
        __type(value, __u32);
        __uint(max_entries, 64);
} xsks_map SEC(".maps");


SEC("xdp")
int xsk_redir_prog(struct xdp_md *ctx)
{
        __u32 index = ctx->rx_queue_index;

        if (bpf_map_lookup_elem(&xsks_map, &index))
                return bpf_redirect_map(&xsks_map, index, 0);
        return XDP_PASS;
}
```

<a id="rst-user-space-1"></a>

### User space

The following code snippet shows how to update an XSKMAP with an XSK entry.



```c
int update_xsks_map(struct bpf_map *xsks_map, int queue_id, int xsk_fd)
{
        int ret;

        ret = bpf_map_update_elem(bpf_map__fd(xsks_map), &queue_id, &xsk_fd, 0);
        if (ret < 0)
                fprintf(stderr, "Failed to update xsks_map: %s\n", strerror(errno));

        return ret;
}
```

For an example on how create AF_XDP sockets, please see the AF_XDP-example and AF_XDP-forwarding programs in the [bpf-examples](<https://github.com/xdp-project/bpf-examples>) directory in the [libxdp](<https://github.com/xdp-project/xdp-tools/tree/master/lib/libxdp>) repository. For a detailed explanation of the AF_XDP interface please see:

- [libxdp-readme](<https://github.com/xdp-project/xdp-tools/tree/master/lib/libxdp#using-af_xdp-sockets>).

- [AF_XDP](<https://www.kernel.org/doc/html/latest/networking/af_xdp.html>) kernel documentation.

> [!NOTE]
>
> The most comprehensive resource for using XSKMAPs and AF_XDP is [libxdp](<https://github.com/xdp-project/xdp-tools/tree/master/lib/libxdp>).

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



<a id="rst-af-xdp"></a>



<a id="rst-bpf-examples"></a>



<a id="rst-libxdp-readme"></a>

---

# BPF maps

_Peios Kernel / Internals / BPF_

> BPF 'maps' provide generic storage of different types for sharing data between kernel and user space. There are several storage types available, including hash, array, bloom filter and radix-tree. Several of the map types exist to support…

<a id="rst-bpf-maps"></a>

BPF 'maps' provide generic storage of different types for sharing data between kernel and user space. There are several storage types available, including hash, array, bloom filter and radix-tree. Several of the map types exist to support specific BPF helpers that perform actions based on the map contents. The maps are accessed from BPF programs via BPF helpers which are documented in the [man-pages](<https://www.kernel.org/doc/man-pages/>) for [bpf-helpers(7)](<https://man7.org/linux/man-pages/man7/bpf-helpers.7.html>).

BPF maps are accessed from user space via the `bpf` syscall, which provides commands to create maps, lookup elements, update elements and delete elements. More details of the BPF syscall are available in [ebpf-syscall](<https://docs.kernel.org/userspace-api/ebpf/syscall.html>) and in the [man-pages](<https://www.kernel.org/doc/man-pages/>) for [bpf(2)](<https://man7.org/linux/man-pages/man2/bpf.2.html>).

<a id="rst-map-types"></a>

## Map Types

- [BPF_MAP_TYPE_ARRAY and BPF_MAP_TYPE_PERCPU_ARRAY](</kernel/internals/bpf/map-array.md>)
- [BPF_MAP_TYPE_BLOOM_FILTER](</kernel/internals/bpf/map-bloom-filter.md>)
- [BPF_MAP_TYPE_CGROUP_STORAGE](</kernel/internals/bpf/map-cgroup-storage.md>)
- [BPF_MAP_TYPE_CGRP_STORAGE](</kernel/internals/bpf/map-cgrp-storage.md>)
- [BPF_MAP_TYPE_CPUMAP](</kernel/internals/bpf/map-cpumap.md>)
- [map_devmap](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/map_devmap.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [BPF_MAP_TYPE_HASH, with PERCPU and LRU Variants](</kernel/internals/bpf/map-hash.md>)
- [BPF_MAP_TYPE_LPM_TRIE](</kernel/internals/bpf/map-lpm-trie.md>)
- [BPF_MAP_TYPE_ARRAY_OF_MAPS and BPF_MAP_TYPE_HASH_OF_MAPS](</kernel/internals/bpf/map-of-maps.md>)
- [BPF_MAP_TYPE_QUEUE and BPF_MAP_TYPE_STACK](</kernel/internals/bpf/map-queue-stack.md>)
- [BPF_MAP_TYPE_SK_STORAGE](</kernel/internals/bpf/map-sk-storage.md>)
- [BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH](</kernel/internals/bpf/map-sockmap.md>)
- [BPF_MAP_TYPE_XSKMAP](</kernel/internals/bpf/map-xskmap.md>)

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

## Usage Notes





<a id="c-bpf"></a>

```c
int bpf(int command, union bpf_attr *attr, u32 size)
```

Use the `bpf()` system call to perform the operation specified by `command`. The operation takes parameters provided in `attr`. The `size` argument is the size of the `union bpf_attr` in `attr`.

**BPF_MAP_CREATE**

Create a map with the desired type and attributes in `attr`:



```c
int fd;
union bpf_attr attr = {
        .map_type = BPF_MAP_TYPE_ARRAY;  /* mandatory */
        .key_size = sizeof(__u32);       /* mandatory */
        .value_size = sizeof(__u32);     /* mandatory */
        .max_entries = 256;              /* mandatory */
        .map_flags = BPF_F_MMAPABLE;
        .map_name = "example_array";
};

fd = bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
```

Returns a process-local file descriptor on success, or negative error in case of failure. The map can be deleted by calling `close(fd)`. Maps held by open file descriptors will be deleted automatically when a process exits.

> [!NOTE]
>
> Valid characters for `map_name` are `A-Z`, `a-z`, `0-9`, `'_'` and `'.'`.

**BPF_MAP_LOOKUP_ELEM**

Lookup key in a given map using `attr->map_fd`, `attr->key`, `attr->value`. Returns zero and stores found elem into `attr->value` on success, or negative error on failure.

**BPF_MAP_UPDATE_ELEM**

Create or update key/value pair in a given map using `attr->map_fd`, `attr->key`, `attr->value`. Returns zero on success or negative error on failure.

**BPF_MAP_DELETE_ELEM**

Find and delete element by key in a given map using `attr->map_fd`, `attr->key`. Returns zero on success or negative error on failure.

<!-- Links: -->

<a id="rst-man-pages"></a>



<a id="rst-bpf-2"></a>



<a id="rst-bpf-helpers-7"></a>



<a id="rst-ebpf-syscall"></a>

---

# Other

_Peios Kernel / Internals / BPF_

> Reference for Other.

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

- [BPF ring buffer](</kernel/internals/bpf/ringbuf.md>)
- [BPF LLVM Relocations](</kernel/internals/bpf/llvm-reloc.md>)
- [BPF Graph Data Structures](</kernel/internals/bpf/graph-ds-impl.md>)

---

# BPF_PROG_TYPE_CGROUP_SOCKOPT

_Peios Kernel / Internals / BPF_

> BPF_PROG_TYPE_CGROUP_SOCKOPT program type can be attached to two cgroup hooks:

<a id="rst-bpf-prog-type-cgroup-sockopt"></a>

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

`BPF_PROG_TYPE_CGROUP_SOCKOPT` program type can be attached to two cgroup hooks:

- `BPF_CGROUP_GETSOCKOPT` - called every time process executes `getsockopt` system call.

- `BPF_CGROUP_SETSOCKOPT` - called every time process executes `setsockopt` system call.

The context (`struct bpf_sockopt`) has associated socket (`sk`) and all input arguments: `level`, `optname`, `optval` and `optlen`.

<a id="rst-bpf-cgroup-setsockopt"></a>

## BPF_CGROUP_SETSOCKOPT

`BPF_CGROUP_SETSOCKOPT` is triggered *before* the kernel handling of sockopt and it has writable context: it can modify the supplied arguments before passing them down to the kernel. This hook has access to the cgroup and socket local storage.

If BPF program sets `optlen` to -1, the control will be returned back to the userspace after all other BPF programs in the cgroup chain finish (i.e. kernel `setsockopt` handling will *not* be executed).

Note, that `optlen` can not be increased beyond the user-supplied value. It can only be decreased or set to -1. Any other value will trigger `EFAULT`.

<a id="rst-return-type"></a>

### Return Type

- `0` - reject the syscall, `EPERM` will be returned to the userspace.

- `1` - success, continue with next BPF program in the cgroup chain.

<a id="rst-bpf-cgroup-getsockopt"></a>

## BPF_CGROUP_GETSOCKOPT

`BPF_CGROUP_GETSOCKOPT` is triggered *after* the kernel handing of sockopt. The BPF hook can observe `optval`, `optlen` and `retval` if it's interested in whatever kernel has returned. BPF hook can override the values above, adjust `optlen` and reset `retval` to 0. If `optlen` has been increased above initial `getsockopt` value (i.e. userspace buffer is too small), `EFAULT` is returned.

This hook has access to the cgroup and socket local storage.

Note, that the only acceptable value to set to `retval` is 0 and the original value that the kernel returned. Any other value will trigger `EFAULT`.

<a id="rst-return-type-1"></a>

### Return Type

- `0` - reject the syscall, `EPERM` will be returned to the userspace.

- `1` - success: copy `optval` and `optlen` to userspace, return `retval` from the syscall (note that this can be overwritten by the BPF program from the parent cgroup).

<a id="rst-cgroup-inheritance"></a>

## Cgroup Inheritance

Suppose, there is the following cgroup hierarchy where each cgroup has `BPF_CGROUP_GETSOCKOPT` attached at each level with `BPF_F_ALLOW_MULTI` flag:



```text
A (root, parent)
 \
  B (child)
```

When the application calls `getsockopt` syscall from the cgroup B, the programs are executed from the bottom up: B, A. First program (B) sees the result of kernel's `getsockopt`. It can optionally adjust `optval`, `optlen` and reset `retval` to 0. After that control will be passed to the second (A) program which will see the same context as B including any potential modifications.

Same for `BPF_CGROUP_SETSOCKOPT`: if the program is attached to A and B, the trigger order is B, then A. If B does any changes to the input arguments (`level`, `optname`, `optval`, `optlen`), then the next program in the chain (A) will see those changes, *not* the original input `setsockopt` arguments. The potentially modified values will be then passed down to the kernel.

<a id="rst-large-optval"></a>

## Large optval

When the `optval` is greater than the `PAGE_SIZE`, the BPF program can access only the first `PAGE_SIZE` of that data. So it has to options:

- Set `optlen` to zero, which indicates that the kernel should use the original buffer from the userspace. Any modifications done by the BPF program to the `optval` are ignored.

- Set `optlen` to the value less than `PAGE_SIZE`, which indicates that the kernel should use BPF's trimmed `optval`.

When the BPF program returns with the `optlen` greater than `PAGE_SIZE`, the userspace will receive original kernel buffers without any modifications that the BPF program might have applied.

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

## Example

Recommended way to handle BPF programs is as follows:



```c
SEC("cgroup/getsockopt")
int getsockopt(struct bpf_sockopt *ctx)
{
        /* Custom socket option. */
        if (ctx->level == MY_SOL && ctx->optname == MY_OPTNAME) {
                ctx->retval = 0;
                optval[0] = ...;
                ctx->optlen = 1;
                return 1;
        }

        /* Modify kernel's socket option. */
        if (ctx->level == SOL_IP && ctx->optname == IP_FREEBIND) {
                ctx->retval = 0;
                optval[0] = ...;
                ctx->optlen = 1;
                return 1;
        }

        /* optval larger than PAGE_SIZE use kernel's buffer. */
        if (ctx->optlen > PAGE_SIZE)
                ctx->optlen = 0;

        return 1;
}

SEC("cgroup/setsockopt")
int setsockopt(struct bpf_sockopt *ctx)
{
        /* Custom socket option. */
        if (ctx->level == MY_SOL && ctx->optname == MY_OPTNAME) {
                /* do something */
                ctx->optlen = -1;
                return 1;
        }

        /* Modify kernel's socket option. */
        if (ctx->level == SOL_IP && ctx->optname == IP_FREEBIND) {
                optval[0] = ...;
                return 1;
        }

        /* optval larger than PAGE_SIZE use kernel's buffer. */
        if (ctx->optlen > PAGE_SIZE)
                ctx->optlen = 0;

        return 1;
}
```

See `tools/testing/selftests/bpf/progs/sockopt_sk.c` for an example of BPF program that handles socket options.

---

# BPF_PROG_TYPE_CGROUP_SYSCTL

_Peios Kernel / Internals / BPF_

> This document describes BPF_PROG_TYPE_CGROUP_SYSCTL program type that provides cgroup-bpf hook for sysctl.

<a id="rst-bpf-prog-type-cgroup-sysctl"></a>

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

This document describes `BPF_PROG_TYPE_CGROUP_SYSCTL` program type that provides cgroup-bpf hook for sysctl.

The hook has to be attached to a cgroup and will be called every time a process inside that cgroup tries to read from or write to sysctl knob in proc.

<a id="rst-attach-type"></a>

## 1. Attach type

`BPF_CGROUP_SYSCTL` attach type has to be used to attach `BPF_PROG_TYPE_CGROUP_SYSCTL` program to a cgroup.

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

## 2. Context

`BPF_PROG_TYPE_CGROUP_SYSCTL` provides access to the following context from BPF program:



```text
struct bpf_sysctl {
    __u32 write;
    __u32 file_pos;
};
```

- `write` indicates whether sysctl value is being read (`0`) or written (`1`). This field is read-only.

- `file_pos` indicates file position sysctl is being accessed at, read or written. This field is read-write. Writing to the field sets the starting position in sysctl proc file `read(2)` will be reading from or `write(2)` will be writing to. Writing zero to the field can be used e.g. to override whole sysctl value by `bpf_sysctl_set_new_value()` on `write(2)` even when it's called by user space on `file_pos > 0`. Writing non-zero value to the field can be used to access part of sysctl value starting from specified `file_pos`. Not all sysctl support access with `file_pos != 0`, e.g. writes to numeric sysctl entries must always be at file position `0`. See also `kernel.sysctl_writes_strict` sysctl.

See [linux/bpf.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/bpf.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for more details on how context field can be accessed.

<a id="rst-return-code"></a>

## 3. Return code

`BPF_PROG_TYPE_CGROUP_SYSCTL` program must return one of the following return codes:

- `0` means "reject access to sysctl";

- `1` means "proceed with access".

If program returns `0` user space will get `-1` from `read(2)` or `write(2)` and `errno` will be set to `EPERM`.

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

## 4. Helpers

Since sysctl knob is represented by a name and a value, sysctl specific BPF helpers focus on providing access to these properties:

- `bpf_sysctl_get_name()` to get sysctl name as it is visible in `/proc/sys` into provided by BPF program buffer;

- `bpf_sysctl_get_current_value()` to get string value currently held by sysctl into provided by BPF program buffer. This helper is available on both `read(2)` from and `write(2)` to sysctl;

- `bpf_sysctl_get_new_value()` to get new string value currently being written to sysctl before actual write happens. This helper can be used only on `ctx->write == 1`;

- `bpf_sysctl_set_new_value()` to override new string value currently being written to sysctl before actual write happens. Sysctl value will be overridden starting from the current `ctx->file_pos`. If the whole value has to be overridden BPF program can set `file_pos` to zero before calling to the helper. This helper can be used only on `ctx->write == 1`. New string value set by the helper is treated and verified by kernel same way as an equivalent string passed by user space.

BPF program sees sysctl value same way as user space does in proc filesystem, i.e. as a string. Since many sysctl values represent an integer or a vector of integers, the following helpers can be used to get numeric value from the string:

- `bpf_strtol()` to convert initial part of the string to long integer similar to user space [strtol(3)](<http://man7.org/linux/man-pages/man3/strtol.3p.html>);

- `bpf_strtoul()` to convert initial part of the string to unsigned long integer similar to user space [strtoul(3)](<http://man7.org/linux/man-pages/man3/strtoul.3p.html>);

See [linux/bpf.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/bpf.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for more details on helpers described here.

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

## 5. Examples

See [test\_sysctl\_prog.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/progs/test_sysctl_prog.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for an example of BPF program in C that access sysctl name and value, parses string value to get vector of integers and uses the result to make decision whether to allow or deny access to sysctl.

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

## 6. Notes

`BPF_PROG_TYPE_CGROUP_SYSCTL` is intended to be used in <strong>trusted</strong> root environment, for example to monitor sysctl usage or catch unreasonable values an application, running as root in a separate cgroup, is trying to set.

Since `task_dfl_cgroup(current)` is called at `sys_read` / `sys_write` time it may return results different from that at `sys_open` time, i.e. process that opened sysctl file in proc filesystem may differ from process that is trying to read from / write to it and two such processes may run in different cgroups, what means `BPF_PROG_TYPE_CGROUP_SYSCTL` should not be used as a security mechanism to limit sysctl usage.

As with any cgroup-bpf program additional care should be taken if an application running as root in a cgroup should not be allowed to detach/replace BPF program attached by administrator.

<!-- Links -->

<a id="rst-linux-bpf-h"></a>



<a id="rst-strtol-3"></a>



<a id="rst-strtoul-3"></a>



<a id="rst-test-sysctl-prog-c"></a>

---

# BPF_PROG_TYPE_FLOW_DISSECTOR

_Peios Kernel / Internals / BPF_

> Flow dissector is a routine that parses metadata out of the packets. It's used in the various places in the networking subsystem (RFS, flow hash, etc).

<a id="rst-bpf-prog-type-flow-dissector"></a>

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

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

## Overview

Flow dissector is a routine that parses metadata out of the packets. It's used in the various places in the networking subsystem (RFS, flow hash, etc).

BPF flow dissector is an attempt to reimplement C-based flow dissector logic in BPF to gain all the benefits of BPF verifier (namely, limits on the number of instructions and tail calls).

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

## API

BPF flow dissector programs operate on an `__sk_buff`. However, only the limited set of fields is allowed: `data`, `data_end` and `flow_keys`. `flow_keys` is `struct bpf_flow_keys` and contains flow dissector input and output arguments.

- **The inputs are:**

  - `nhoff` - initial offset of the networking header

  - `thoff` - initial offset of the transport header, initialized to nhoff

  - `n_proto` - L3 protocol type, parsed out of L2 header

  - `flags` - optional flags

Flow dissector BPF program should fill out the rest of the `struct bpf_flow_keys` fields. Input arguments `nhoff/thoff/n_proto` should be also adjusted accordingly.

The return code of the BPF program is either BPF_OK to indicate successful dissection, or BPF_DROP to indicate parsing error.

<a id="rst-sk-buff-data"></a>

## \__sk_buff-&gt;data

In the VLAN-less case, this is what the initial state of the BPF flow dissector looks like:



```text
+------+------+------------+-----------+
| DMAC | SMAC | ETHER_TYPE | L3_HEADER |
+------+------+------------+-----------+
                            ^
                            |
                            +-- flow dissector starts here
```



```c
skb->data + flow_keys->nhoff point to the first byte of L3_HEADER
flow_keys->thoff = nhoff
flow_keys->n_proto = ETHER_TYPE
```

In case of VLAN, flow dissector can be called with the two different states.

Pre-VLAN parsing:



```text
+------+------+------+-----+-----------+-----------+
| DMAC | SMAC | TPID | TCI |ETHER_TYPE | L3_HEADER |
+------+------+------+-----+-----------+-----------+
                      ^
                      |
                      +-- flow dissector starts here
```



```c
skb->data + flow_keys->nhoff point the to first byte of TCI
flow_keys->thoff = nhoff
flow_keys->n_proto = TPID
```

Please note that TPID can be 802.1AD and, hence, BPF program would have to parse VLAN information twice for double tagged packets.

Post-VLAN parsing:



```text
+------+------+------+-----+-----------+-----------+
| DMAC | SMAC | TPID | TCI |ETHER_TYPE | L3_HEADER |
+------+------+------+-----+-----------+-----------+
                                        ^
                                        |
                                        +-- flow dissector starts here
```



```c
skb->data + flow_keys->nhoff point the to first byte of L3_HEADER
flow_keys->thoff = nhoff
flow_keys->n_proto = ETHER_TYPE
```

In this case VLAN information has been processed before the flow dissector and BPF flow dissector is not required to handle it.

The takeaway here is as follows: BPF flow dissector program can be called with the optional VLAN header and should gracefully handle both cases: when single or double VLAN is present and when it is not present. The same program can be called for both cases and would have to be written carefully to handle both cases.

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

## Flags

`flow_keys->flags` might contain optional input flags that work as follows:

- `BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG` - tells BPF flow dissector to continue parsing first fragment; the default expected behavior is that flow dissector returns as soon as it finds out that the packet is fragmented; used by `eth_get_headlen` to estimate length of all headers for GRO.

- `BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL` - tells BPF flow dissector to stop parsing as soon as it reaches IPv6 flow label; used by `___skb_get_hash` to get flow hash.

- `BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP` - tells BPF flow dissector to stop parsing as soon as it reaches encapsulated headers; used by routing infrastructure.

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

## Reference Implementation

See `tools/testing/selftests/bpf/progs/bpf_flow.c` for the reference implementation and `tools/testing/selftests/bpf/flow_dissector_load.[hc]` for the loader. bpftool can be used to load BPF flow dissector program as well.

- **The reference implementation is organized as follows:**

  - `jmp_table` map that contains sub-programs for each supported L3 protocol

  - `_dissect` routine - entry point; it does input `n_proto` parsing and does `bpf_tail_call` to the appropriate L3 handler

Since BPF at this point doesn't support looping (or any jumping back), jmp_table is used instead to handle multiple levels of encapsulation (and IPv6 options).

<a id="rst-current-limitations"></a>

## Current Limitations

BPF flow dissector doesn't support exporting all the metadata that in-kernel C-based implementation can export. Notable example is single VLAN (802.1Q) and double VLAN (802.1AD) tags. Please refer to the `struct bpf_flow_keys` for a set of information that's currently can be exported from the BPF context.

When BPF flow dissector is attached to the root network namespace (machine-wide policy), users can't override it in their child network namespaces.

---

# LSM BPF Programs

_Peios Kernel / Internals / BPF_

> These BPF programs allow runtime instrumentation of the LSM hooks by privileged users to implement system-wide MAC (Mandatory Access Control) and Audit policies using eBPF.

> **Peios:** This is reference material for an upstream LSM or its configuration. Peios configures `landlock,lockdown,integrity,pkm`; alternative MAC LSMs are incompatible with PKM, and this article is not an instruction to replace the Peios security stack. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-lsm-bpf-programs"></a>

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

<!-- Copyright (C) 2020 Google LLC. -->

These BPF programs allow runtime instrumentation of the LSM hooks by privileged users to implement system-wide MAC (Mandatory Access Control) and Audit policies using eBPF.

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

## Structure

The example shows an eBPF program that can be attached to the `file_mprotect` LSM hook:





<a id="c-file_mprotect"></a>

```c
int file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot);
```

Other LSM hooks which can be instrumented can be found in `security/security.c`.

eBPF programs that use [Documentation/bpf/btf.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/btf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) do not need to include kernel headers for accessing information from the attached eBPF program's context. They can simply declare the structures in the eBPF program and only specify the fields that need to be accessed.



```c
struct mm_struct {
        unsigned long start_brk, brk, start_stack;
} __attribute__((preserve_access_index));

struct vm_area_struct {
        unsigned long start_brk, brk, start_stack;
        unsigned long vm_start, vm_end;
        struct mm_struct *vm_mm;
} __attribute__((preserve_access_index));
```

> [!NOTE]
>
> The order of the fields is irrelevant.

This can be further simplified (if one has access to the BTF information at build time) by generating the `vmlinux.h` with:



```console
# bpftool btf dump file <path-to-btf-vmlinux> format c > vmlinux.h
```

> [!NOTE]
>
> `path-to-btf-vmlinux` can be `/sys/kernel/btf/vmlinux` if the build environment matches the environment the BPF programs are deployed in.

The `vmlinux.h` can then simply be included in the BPF programs without requiring the definition of the types.

The eBPF programs can be declared using the\`\`BPF_PROG\`\` macros defined in [tools/lib/bpf/bpf_tracing.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/lib/bpf/bpf_tracing.h>). In this example:

> - `"lsm/file_mprotect"` indicates the LSM hook that the program must be attached to
>
> - `mprotect_audit` is the name of the eBPF program



```c
SEC("lsm/file_mprotect")
int BPF_PROG(mprotect_audit, struct vm_area_struct *vma,
             unsigned long reqprot, unsigned long prot, int ret)
{
        /* ret is the return value from the previous BPF program
         * or 0 if it's the first hook.
         */
        if (ret != 0)
                return ret;

        int is_heap;

        is_heap = (vma->vm_start >= vma->vm_mm->start_brk &&
                   vma->vm_end <= vma->vm_mm->brk);

        /* Return an -EPERM or write information to the perf events buffer
         * for auditing
         */
        if (is_heap)
                return -EPERM;
}
```

The `__attribute__((preserve_access_index))` is a clang feature that allows the BPF verifier to update the offsets for the access at runtime using the [Documentation/bpf/btf.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/btf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) information. Since the BPF verifier is aware of the types, it also validates all the accesses made to the various types in the eBPF program.

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

## Loading

eBPF programs can be loaded with the `bpf(2)` syscall's `BPF_PROG_LOAD` operation:



```c
struct bpf_object *obj;

obj = bpf_object__open("./my_prog.o");
bpf_object__load(obj);
```

This can be simplified by using a skeleton header generated by `bpftool`:



```console
# bpftool gen skeleton my_prog.o > my_prog.skel.h
```

and the program can be loaded by including `my_prog.skel.h` and using the generated helper, `my_prog__open_and_load`.

<a id="rst-attachment-to-lsm-hooks"></a>

## Attachment to LSM Hooks

The LSM allows attachment of eBPF programs as LSM hooks using `bpf(2)` syscall's `BPF_RAW_TRACEPOINT_OPEN` operation or more simply by using the libbpf helper `bpf_program__attach_lsm`.

The program can be detached from the LSM hook by *destroying* the `link` link returned by `bpf_program__attach_lsm` using `bpf_link__destroy`.

One can also use the helpers generated in `my_prog.skel.h` i.e. `my_prog__attach` for attachment and `my_prog__destroy` for cleaning up.

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

## Examples

An example eBPF program can be found in [tools/testing/selftests/bpf/progs/lsm.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/progs/lsm.c>) and the corresponding userspace code in [tools/testing/selftests/bpf/prog_tests/test_lsm.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/prog_tests/test_lsm.c>)

<!-- Links -->

<a id="rst-tools-lib-bpf-bpf-tracing-h"></a>



<a id="rst-tools-testing-selftests-bpf-progs-lsm-c"></a>



<a id="rst-tools-testing-selftests-bpf-prog-tests-test-lsm-c"></a>

---

# BPF sk_lookup program

_Peios Kernel / Internals / BPF_

> BPF sk_lookup program type (BPF_PROG_TYPE_SK_LOOKUP) introduces programmability into the socket lookup performed by the transport layer when a packet is to be delivered locally.

<a id="rst-bpf-sk-lookup-program"></a>

<!-- SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) -->

BPF sk_lookup program type (`BPF_PROG_TYPE_SK_LOOKUP`) introduces programmability into the socket lookup performed by the transport layer when a packet is to be delivered locally.

When invoked BPF sk_lookup program can select a socket that will receive the incoming packet by calling the `bpf_sk_assign()` BPF helper function.

Hooks for a common attach point (`BPF_SK_LOOKUP`) exist for both TCP and UDP.

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

## Motivation

BPF sk_lookup program type was introduced to address setup scenarios where binding sockets to an address with `bind()` socket call is impractical, such as:

1. receiving connections on a range of IP addresses, e.g. 192.0.2.0/24, when binding to a wildcard address `INADRR_ANY` is not possible due to a port conflict,

2. receiving connections on all or a wide range of ports, i.e. an L7 proxy use case.

Such setups would require creating and `bind()`'ing one socket to each of the IP address/port in the range, leading to resource consumption and potential latency spikes during socket lookup.

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

## Attachment

BPF sk_lookup program can be attached to a network namespace with `bpf(BPF_LINK_CREATE, ...)` syscall using the `BPF_SK_LOOKUP` attach type and a netns FD as attachment `target_fd`.

Multiple programs can be attached to one network namespace. Programs will be invoked in the same order as they were attached.

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

## Hooks

The attached BPF sk_lookup programs run whenever the transport layer needs to find a listening (TCP) or an unconnected (UDP) socket for an incoming packet.

Incoming traffic to established (TCP) and connected (UDP) sockets is delivered as usual without triggering the BPF sk_lookup hook.

The attached BPF programs must return with either `SK_PASS` or `SK_DROP` verdict code. As for other BPF program types that are network filters, `SK_PASS` signifies that the socket lookup should continue on to regular hashtable-based lookup, while `SK_DROP` causes the transport layer to drop the packet.

A BPF sk_lookup program can also select a socket to receive the packet by calling `bpf_sk_assign()` BPF helper. Typically, the program looks up a socket in a map holding sockets, such as `SOCKMAP` or `SOCKHASH`, and passes a `struct bpf_sock *` to `bpf_sk_assign()` helper to record the selection. Selecting a socket only takes effect if the program has terminated with `SK_PASS` code.

When multiple programs are attached, the end result is determined from return codes of all the programs according to the following rules:

1. If any program returned `SK_PASS` and selected a valid socket, the socket is used as the result of the socket lookup.

2. If more than one program returned `SK_PASS` and selected a socket, the last selection takes effect.

3. If any program returned `SK_DROP`, and no program returned `SK_PASS` and selected a socket, socket lookup fails.

4. If all programs returned `SK_PASS` and none of them selected a socket, socket lookup continues on.

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

## API

In its context, an instance of `struct bpf_sk_lookup`, BPF sk_lookup program receives information about the packet that triggered the socket lookup. Namely:

- IP version (`AF_INET` or `AF_INET6`),

- L4 protocol identifier (`IPPROTO_TCP` or `IPPROTO_UDP`),

- source and destination IP address,

- source and destination L4 port,

- the socket that has been selected with `bpf_sk_assign()`.

Refer to `struct bpf_sk_lookup` declaration in `linux/bpf.h` user API header, and [bpf-helpers(7)](<https://man7.org/linux/man-pages/man7/bpf-helpers.7.html>)<a id="rst-bpf-helpers-7"></a> man-page section for `bpf_sk_assign()` for details.

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

## Example

See `tools/testing/selftests/bpf/prog_tests/sk_lookup.c` for the reference implementation.

---

# Program Types

_Peios Kernel / Internals / BPF_

> For a list of all program types, see program_types_and_elf in the libbpf documentation.

<a id="rst-program-types"></a>

- [BPF_PROG_TYPE_CGROUP_SOCKOPT](</kernel/internals/bpf/prog-cgroup-sockopt.md>)
- [BPF_PROG_TYPE_CGROUP_SYSCTL](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/prog_cgroup_sysctl.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [BPF_PROG_TYPE_FLOW_DISSECTOR](</kernel/internals/bpf/prog-flow-dissector.md>)
- [LSM BPF Programs](</kernel/internals/bpf/prog-lsm.md>)
- [BPF sk_lookup program](</kernel/internals/bpf/prog-sk-lookup.md>)

For a list of all program types, see [Program Types and ELF Sections](</kernel/internals/bpf/libbpf/program-types.md#rst-program-types-and-elf>) in the [libbpf](</kernel/internals/bpf/libbpf/index.md#rst-libbpf-1>) documentation.

---

# Redirect

_Peios Kernel / Internals / BPF_

> XDP_REDIRECT works with the following map types:

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

<a id="rst-xdp-redirect"></a>

## XDP_REDIRECT

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

<!-- Copyright (C) 2022 Red Hat, Inc. -->

<a id="rst-supported-maps"></a>

## Supported maps

XDP_REDIRECT works with the following map types:

- `BPF_MAP_TYPE_DEVMAP`

- `BPF_MAP_TYPE_DEVMAP_HASH`

- `BPF_MAP_TYPE_CPUMAP`

- `BPF_MAP_TYPE_XSKMAP`

For more information on these maps, please see the specific map documentation.

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

## Process


XDP_REDIRECT works by a three-step process, implemented in the functions
below:

1. The `bpf_redirect()` and `bpf_redirect_map()` helpers will lookup the target
   of the redirect and store it (along with some other metadata) in a per-CPU
   struct bpf_redirect_info.

2. When the program returns the XDP_REDIRECT return code, the driver will
   call `xdp_do_redirect()` which will use the information in struct
   bpf_redirect_info to actually enqueue the frame into a map type-specific
   bulk queue structure.

3. Before exiting its NAPI poll loop, the driver will call
   `xdp_do_flush()`, which will flush all the different bulk queues,
   thus completing the redirect. Note that `xdp_do_flush()` must be
   called before [`napi_complete_done()`](/kernel/internals/networking/kapi.md#c-napi_complete_done) in the driver, as the
   XDP_REDIRECT logic relies on being inside a single NAPI instance
   through to the `xdp_do_flush()` call for RCU protection of all
   in-kernel data structures.


> [!NOTE]
>
> Not all drivers support transmitting frames after a redirect, and for those that do, not all of them support non-linear frames. Non-linear xdp bufs/frames are bufs/frames that contain more than one fragment.

<a id="rst-debugging-packet-drops"></a>

## Debugging packet drops

Silent packet drops for XDP_REDIRECT can be debugged using:

- bpf_trace

- perf_record

<a id="rst-bpf-trace"></a>

### bpf_trace

The following bpftrace command can be used to capture and count all XDP tracepoints:



```none
sudo bpftrace -e 'tracepoint:xdp:* { @cnt[probe] = count(); }'
Attaching 12 probes...
^C

@cnt[tracepoint:xdp:mem_connect]: 18
@cnt[tracepoint:xdp:mem_disconnect]: 18
@cnt[tracepoint:xdp:xdp_exception]: 19605
@cnt[tracepoint:xdp:xdp_devmap_xmit]: 1393604
@cnt[tracepoint:xdp:xdp_redirect]: 22292200
```

> [!NOTE]
>
> The various xdp tracepoints can be found in `source/include/trace/events/xdp.h`

The following bpftrace command can be used to extract the `ERRNO` being returned as part of the err parameter:



```none
sudo bpftrace -e \
'tracepoint:xdp:xdp_redirect*_err {@redir_errno[-args->err] = count();}
tracepoint:xdp:xdp_devmap_xmit {@devmap_errno[-args->err] = count();}'
```

<a id="rst-perf-record"></a>

### perf record

The perf tool also supports recording tracepoints:



```none
perf record -a -e xdp:xdp_redirect_err \
    -e xdp:xdp_redirect_map_err \
    -e xdp:xdp_exception \
    -e xdp:xdp_devmap_xmit
```

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

#### References

- [https://github.com/xdp-project/xdp-tutorial/tree/master/tracing02-xdp-monitor](<https://github.com/xdp-project/xdp-tutorial/tree/master/tracing02-xdp-monitor>)

---

# BPF ring buffer

_Peios Kernel / Internals / BPF_

> This document describes BPF ring buffer design, API, and implementation details.

<a id="rst-bpf-ring-buffer"></a>

This document describes BPF ring buffer design, API, and implementation details.

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



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

## Motivation

There are two distinctive motivators for this work, which are not satisfied by existing perf buffer, which prompted creation of a new ring buffer implementation.

- more efficient memory utilization by sharing ring buffer across CPUs;

- preserving ordering of events that happen sequentially in time, even across multiple CPUs (e.g., fork/exec/exit events for a task).

These two problems are independent, but perf buffer fails to satisfy both. Both are a result of a choice to have per-CPU perf ring buffer.  Both can be also solved by having an MPSC implementation of ring buffer. The ordering problem could technically be solved for perf buffer with some in-kernel counting, but given the first one requires an MPSC buffer, the same solution would solve the second problem automatically.

<a id="rst-semantics-and-apis"></a>

## Semantics and APIs

Single ring buffer is presented to BPF programs as an instance of BPF map of type `BPF_MAP_TYPE_RINGBUF`. Two other alternatives considered, but ultimately rejected.

One way would be to, similar to `BPF_MAP_TYPE_PERF_EVENT_ARRAY`, make `BPF_MAP_TYPE_RINGBUF` could represent an array of ring buffers, but not enforce "same CPU only" rule. This would be more familiar interface compatible with existing perf buffer use in BPF, but would fail if application needed more advanced logic to lookup ring buffer by arbitrary key. `BPF_MAP_TYPE_HASH_OF_MAPS` addresses this with current approach. Additionally, given the performance of BPF ringbuf, many use cases would just opt into a simple single ring buffer shared among all CPUs, for which current approach would be an overkill.

Another approach could introduce a new concept, alongside BPF map, to represent generic "container" object, which doesn't necessarily have key/value interface with lookup/update/delete operations. This approach would add a lot of extra infrastructure that has to be built for observability and verifier support. It would also add another concept that BPF developers would have to familiarize themselves with, new syntax in libbpf, etc. But then would really provide no additional benefits over the approach of using a map.  `BPF_MAP_TYPE_RINGBUF` doesn't support lookup/update/delete operations, but so doesn't few other map types (e.g., queue and stack; array doesn't support delete, etc).

The approach chosen has an advantage of re-using existing BPF map infrastructure (introspection APIs in kernel, libbpf support, etc), being familiar concept (no need to teach users a new type of object in BPF program), and utilizing existing tooling (bpftool). For common scenario of using a single ring buffer for all CPUs, it's as simple and straightforward, as would be with a dedicated "container" object. On the other hand, by being a map, it can be combined with `ARRAY_OF_MAPS` and `HASH_OF_MAPS` map-in-maps to implement a wide variety of topologies, from one ring buffer for each CPU (e.g., as a replacement for perf buffer use cases), to a complicated application hashing/sharding of ring buffers (e.g., having a small pool of ring buffers with hashed task's tgid being a look up key to preserve order, but reduce contention).

Key and value sizes are enforced to be zero. `max_entries` is used to specify the size of ring buffer and has to be a power of 2 value.

There are a bunch of similarities between perf buffer (`BPF_MAP_TYPE_PERF_EVENT_ARRAY`) and new BPF ring buffer semantics:

- variable-length records;

- if there is no more space left in ring buffer, reservation fails, no blocking;

- memory-mappable data area for user-space applications for ease of consumption and high performance;

- epoll notifications for new incoming data;

- but still the ability to do busy polling for new data to achieve the lowest latency, if necessary.

BPF ringbuf provides two sets of APIs to BPF programs:

- `bpf_ringbuf_output()` allows to *copy* data from one place to a ring buffer, similarly to `bpf_perf_event_output()`;

- `bpf_ringbuf_reserve()`/`bpf_ringbuf_commit()`/`bpf_ringbuf_discard()` APIs split the whole process into two steps. First, a fixed amount of space is reserved. If successful, a pointer to a data inside ring buffer data area is returned, which BPF programs can use similarly to a data inside array/hash maps. Once ready, this piece of memory is either committed or discarded. Discard is similar to commit, but makes consumer ignore the record.

`bpf_ringbuf_output()` has disadvantage of incurring extra memory copy, because record has to be prepared in some other place first. But it allows to submit records of the length that's not known to verifier beforehand. It also closely matches `bpf_perf_event_output()`, so will simplify migration significantly.

`bpf_ringbuf_reserve()` avoids the extra copy of memory by providing a memory pointer directly to ring buffer memory. In a lot of cases records are larger than BPF stack space allows, so many programs have use extra per-CPU array as a temporary heap for preparing sample. bpf_ringbuf_reserve() avoid this needs completely. But in exchange, it only allows a known constant size of memory to be reserved, such that verifier can verify that BPF program can't access memory outside its reserved record space. bpf_ringbuf_output(), while slightly slower due to extra memory copy, covers some use cases that are not suitable for `bpf_ringbuf_reserve()`.

The difference between commit and discard is very small. Discard just marks a record as discarded, and such records are supposed to be ignored by consumer code. Discard is useful for some advanced use-cases, such as ensuring all-or-nothing multi-record submission, or emulating temporary `malloc()`/`free()` within single BPF program invocation.

Each reserved record is tracked by verifier through existing reference-tracking logic, similar to socket ref-tracking. It is thus impossible to reserve a record, but forget to submit (or discard) it.

`bpf_ringbuf_query()` helper allows to query various properties of ring buffer.  Currently 4 are supported:

- `BPF_RB_AVAIL_DATA` returns amount of unconsumed data in ring buffer;

- `BPF_RB_RING_SIZE` returns the size of ring buffer;

- `BPF_RB_CONS_POS`/`BPF_RB_PROD_POS` returns current logical position of consumer/producer, respectively.

Returned values are momentarily snapshots of ring buffer state and could be off by the time helper returns, so this should be used only for debugging/reporting reasons or for implementing various heuristics, that take into account highly-changeable nature of some of those characteristics.

One such heuristic might involve more fine-grained control over poll/epoll notifications about new data availability in ring buffer. Together with `BPF_RB_NO_WAKEUP`/`BPF_RB_FORCE_WAKEUP` flags for output/commit/discard helpers, it allows BPF program a high degree of control and, e.g., more efficient batched notifications. Default self-balancing strategy, though, should be adequate for most applications and will work reliable and efficiently already.

<a id="rst-design-and-implementation"></a>

## Design and Implementation

This reserve/commit schema allows a natural way for multiple producers, either on different CPUs or even on the same CPU/in the same BPF program, to reserve independent records and work with them without blocking other producers. This means that if BPF program was interrupted by another BPF program sharing the same ring buffer, they will both get a record reserved (provided there is enough space left) and can work with it and submit it independently. This applies to NMI context as well, except that due to using a spinlock during reservation, in NMI context, `bpf_ringbuf_reserve()` might fail to get a lock, in which case reservation will fail even if ring buffer is not full.

The ring buffer itself internally is implemented as a power-of-2 sized circular buffer, with two logical and ever-increasing counters (which might wrap around on 32-bit architectures, that's not a problem):

- consumer counter shows up to which logical position consumer consumed the data;

- producer counter denotes amount of data reserved by all producers.

Each time a record is reserved, producer that "owns" the record will successfully advance producer counter. At that point, data is still not yet ready to be consumed, though. Each record has 8 byte header, which contains the length of reserved record, as well as two extra bits: busy bit to denote that record is still being worked on, and discard bit, which might be set at commit time if record is discarded. In the latter case, consumer is supposed to skip the record and move on to the next one. Record header also encodes record's relative offset from the beginning of ring buffer data area (in pages). This allows `bpf_ringbuf_commit()`/`bpf_ringbuf_discard()` to accept only the pointer to the record itself, without requiring also the pointer to ring buffer itself. Ring buffer memory location will be restored from record metadata header. This significantly simplifies verifier, as well as improving API usability.

Producer counter increments are serialized under spinlock, so there is a strict ordering between reservations. Commits, on the other hand, are completely lockless and independent. All records become available to consumer in the order of reservations, but only after all previous records where already committed. It is thus possible for slow producers to temporarily hold off submitted records, that were reserved later.

One interesting implementation bit, that significantly simplifies (and thus speeds up as well) implementation of both producers and consumers is how data area is mapped twice contiguously back-to-back in the virtual memory. This allows to not take any special measures for samples that have to wrap around at the end of the circular buffer data area, because the next page after the last data page would be first data page again, and thus the sample will still appear completely contiguous in virtual memory. See comment and a simple ASCII diagram showing this visually in `bpf_ringbuf_area_alloc()`.

Another feature that distinguishes BPF ringbuf from perf ring buffer is a self-pacing notifications of new data being availability. `bpf_ringbuf_commit()` implementation will send a notification of new record being available after commit only if consumer has already caught up right up to the record being committed. If not, consumer still has to catch up and thus will see new data anyways without needing an extra poll notification. Benchmarks (see tools/testing/selftests/bpf/benchs/bench_ringbufs.c) show that this allows to achieve a very high throughput without having to resort to tricks like "notify only every Nth sample", which are necessary with perf buffer. For extreme cases, when BPF program wants more manual control of notifications, commit/discard/output helpers accept `BPF_RB_NO_WAKEUP` and `BPF_RB_FORCE_WAKEUP` flags, which give full control over notifications of data availability, but require extra caution and diligence in using this API.

---

# Testing BPF on s390

_Peios Kernel / Internals / BPF_

> IBM Z are mainframe computers, which are descendants of IBM System/360 from year 1964. They are supported by the Linux kernel under the name "s390". This document describes how to test BPF in an s390 QEMU guest.

<a id="rst-testing-bpf-on-s390"></a>

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

## 1. Introduction

IBM Z are mainframe computers, which are descendants of IBM System/360 from year 1964. They are supported by the Linux kernel under the name "s390". This document describes how to test BPF in an s390 QEMU guest.

<a id="rst-one-time-setup"></a>

## 2. One-time setup

The following is required to build and run the test suite:

> - s390 GCC
>
> - s390 development headers and libraries
>
> - Clang with BPF support
>
> - QEMU with s390 support
>
> - Disk image with s390 rootfs

Debian supports installing compiler and libraries for s390 out of the box. Users of other distros may use debootstrap in order to set up a Debian chroot:



```text
sudo debootstrap \
  --variant=minbase \
  --include=sudo \
  testing \
  ./s390-toolchain
sudo mount --rbind /dev ./s390-toolchain/dev
sudo mount --rbind /proc ./s390-toolchain/proc
sudo mount --rbind /sys ./s390-toolchain/sys
sudo chroot ./s390-toolchain
```

Once on Debian, the build prerequisites can be installed as follows:



```text
sudo dpkg --add-architecture s390x
sudo apt-get update
sudo apt-get install \
  bc \
  bison \
  cmake \
  debootstrap \
  dwarves \
  flex \
  g++ \
  gcc \
  g++-s390x-linux-gnu \
  gcc-s390x-linux-gnu \
  gdb-multiarch \
  git \
  make \
  python3 \
  qemu-system-misc \
  qemu-utils \
  rsync \
  libcap-dev:s390x \
  libelf-dev:s390x \
  libncurses-dev
```

Latest Clang targeting BPF can be installed as follows:



```text
git clone https://github.com/llvm/llvm-project.git
ln -s ../../clang llvm-project/llvm/tools/
mkdir llvm-project-build
cd llvm-project-build
cmake \
  -DLLVM_TARGETS_TO_BUILD=BPF \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_INSTALL_PREFIX=/opt/clang-bpf \
  ../llvm-project/llvm
make
sudo make install
export PATH=/opt/clang-bpf/bin:$PATH
```

The disk image can be prepared using a loopback mount and debootstrap:



```text
qemu-img create -f raw ./s390.img 1G
sudo losetup -f ./s390.img
sudo mkfs.ext4 /dev/loopX
mkdir ./s390.rootfs
sudo mount /dev/loopX ./s390.rootfs
sudo debootstrap \
  --foreign \
  --arch=s390x \
  --variant=minbase \
  --include=" \
    iproute2, \
    iputils-ping, \
    isc-dhcp-client, \
    kmod, \
    libcap2, \
    libelf1, \
    netcat, \
    procps" \
  testing \
  ./s390.rootfs
sudo umount ./s390.rootfs
sudo losetup -d /dev/loopX
```

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

## 3. Compilation

In addition to the usual Kconfig options required to run the BPF test suite, it is also helpful to select:



```text
CONFIG_NET_9P=y
CONFIG_9P_FS=y
CONFIG_NET_9P_VIRTIO=y
CONFIG_VIRTIO_PCI=y
```

as that would enable a very easy way to share files with the s390 virtual machine.

Compiling kernel, modules and testsuite, as well as preparing gdb scripts to simplify debugging, can be done using the following commands:



```text
make ARCH=s390 CROSS_COMPILE=s390x-linux-gnu- menuconfig
make ARCH=s390 CROSS_COMPILE=s390x-linux-gnu- bzImage modules scripts_gdb
make ARCH=s390 CROSS_COMPILE=s390x-linux-gnu- \
  -C tools/testing/selftests \
  TARGETS=bpf \
  INSTALL_PATH=$PWD/tools/testing/selftests/kselftest_install \
  install
```

<a id="rst-running-the-test-suite"></a>

## 4. Running the test suite

The virtual machine can be started as follows:



```text
qemu-system-s390x \
  -cpu max,zpci=on \
  -smp 2 \
  -m 4G \
  -kernel linux/arch/s390/boot/compressed/vmlinux \
  -drive file=./s390.img,if=virtio,format=raw \
  -nographic \
  -append 'root=/dev/vda rw console=ttyS1' \
  -virtfs local,path=./linux,security_model=none,mount_tag=linux \
  -object rng-random,filename=/dev/urandom,id=rng0 \
  -device virtio-rng-ccw,rng=rng0 \
  -netdev user,id=net0 \
  -device virtio-net-ccw,netdev=net0
```

When using this on a real IBM Z, `-enable-kvm` may be added for better performance. When starting the virtual machine for the first time, disk image setup must be finalized using the following command:



```text
/debootstrap/debootstrap --second-stage
```

Directory with the code built on the host as well as `/proc` and `/sys` need to be mounted as follows:



```text
mkdir -p /linux
mount -t 9p linux /linux
mount -t proc proc /proc
mount -t sysfs sys /sys
```

After that, the test suite can be run using the following commands:



```text
cd /linux/tools/testing/selftests/kselftest_install
./run_kselftest.sh
```

As usual, tests can be also run individually:



```text
cd /linux/tools/testing/selftests/bpf
./test_verifier
```

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

## 5. Debugging

It is possible to debug the s390 kernel using QEMU GDB stub, which is activated by passing `-s` to QEMU.

It is preferable to turn KASLR off, so that gdb would know where to find the kernel image in memory, by building the kernel with:



```text
RANDOMIZE_BASE=n
```

GDB can then be attached using the following command:



```text
gdb-multiarch -ex 'target remote localhost:1234' ./vmlinux
```

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

## 6. Network

In case one needs to use the network in the virtual machine in order to e.g. install additional packages, it can be configured using:



```text
dhclient eth0
```

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

## 7. Links

This document is a compilation of techniques, whose more comprehensive descriptions can be found by following these links:

- [Debootstrap](<https://wiki.debian.org/EmDebian/CrossDebootstrap>)<a id="rst-debootstrap"></a>

- [Multiarch](<https://wiki.debian.org/Multiarch/HOWTO>)<a id="rst-multiarch"></a>

- [Building LLVM](<https://llvm.org/docs/CMake.html>)<a id="rst-building-llvm"></a>

- [Cross-compiling the kernel](<https://wiki.gentoo.org/wiki/Embedded_Handbook/General/Cross-compiling_the_kernel>)<a id="rst-cross-compiling-the-kernel"></a>

- [QEMU s390x Guest Support](<https://wiki.qemu.org/Documentation/Platforms/S390X>)<a id="rst-qemu-s390x-guest-support"></a>

- [Plan 9 folder sharing over Virtio](<https://wiki.qemu.org/Documentation/9psetup>)<a id="rst-plan-9-folder-sharing-over-virtio"></a>

- [Using GDB with QEMU](<https://wiki.osdev.org/Kernel_Debugging#Use_GDB_with_QEMU>)<a id="rst-using-gdb-with-qemu"></a>

---

# Syscall API

_Peios Kernel / Internals / BPF_

> The primary info for the bpf syscall is available in the man-pages for bpf(2). For more information about the userspace API, see Documentation/userspace-api/ebpf/index.rst.

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

The primary info for the bpf syscall is available in the [man-pages](<https://www.kernel.org/doc/man-pages/>) for [bpf(2)](<https://man7.org/linux/man-pages/man2/bpf.2.html>). For more information about the userspace API, see [Documentation/userspace-api/ebpf/index.rst](/kernel/userspace/userspace-api/ebpf/index.md).

<!-- Links: -->

<a id="rst-man-pages"></a>



<a id="rst-bpf-2"></a>

---

# Testing and debugging BPF

_Peios Kernel / Internals / BPF_

> Reference for Testing and debugging BPF.

<a id="rst-testing-and-debugging-bpf"></a>

- [BPF drgn tools](</kernel/internals/bpf/drgn.md>)
- [Testing BPF on s390](</kernel/internals/bpf/s390.md>)

---

# eBPF verifier

_Peios Kernel / Internals / BPF_

> The safety of the eBPF program is determined in two steps.

<a id="rst-ebpf-verifier"></a>

The safety of the eBPF program is determined in two steps.

First step does DAG check to disallow loops and other CFG validation. In particular it will detect programs that have unreachable instructions. (though classic BPF checker allows them)

Second step starts from the first insn and descends all possible paths. It simulates execution of every insn and observes the state change of registers and stack.

At the start of the program the register R1 contains a pointer to context and has type PTR_TO_CTX. If verifier sees an insn that does R2=R1, then R2 has now type PTR_TO_CTX as well and can be used on the right hand side of expression. If R1=PTR_TO_CTX and insn is R2=R1+R1, then R2=SCALAR_VALUE, since addition of two valid pointers makes invalid pointer. (In 'secure' mode verifier will reject any type of pointer arithmetic to make sure that kernel addresses don't leak to unprivileged users)

If register was never written to, it's not readable:



```text
bpf_mov R0 = R2
bpf_exit
```

will be rejected, since R2 is unreadable at the start of the program.

After kernel function call, R1-R5 are reset to unreadable and R0 has a return type of the function.

Since R6-R9 are callee saved, their state is preserved across the call.



```text
bpf_mov R6 = 1
bpf_call foo
bpf_mov R0 = R6
bpf_exit
```

is a correct program. If there was R1 instead of R6, it would have been rejected.

load/store instructions are allowed only with registers of valid types, which are PTR_TO_CTX, PTR_TO_MAP, PTR_TO_STACK. They are bounds and alignment checked. For example:



```text
bpf_mov R1 = 1
bpf_mov R2 = 2
bpf_xadd *(u32 *)(R1 + 3) += R2
bpf_exit
```

will be rejected, since R1 doesn't have a valid pointer type at the time of execution of instruction bpf_xadd.

At the start R1 type is PTR_TO_CTX (a pointer to generic `struct bpf_context`) A callback is used to customize verifier to restrict eBPF program access to only certain fields within ctx structure with specified size and alignment.

For example, the following insn:



```text
bpf_ld R0 = *(u32 *)(R6 + 8)
```

intends to load a word from address R6 + 8 and store it into R0 If R6=PTR_TO_CTX, via is_valid_access() callback the verifier will know that offset 8 of size 4 bytes can be accessed for reading, otherwise the verifier will reject the program. If R6=PTR_TO_STACK, then access should be aligned and be within stack bounds, which are \[-MAX_BPF_STACK, 0). In this example offset is 8, so it will fail verification, since it's out of bounds.

The verifier will allow eBPF program to read data from stack only after it wrote into it.

Classic BPF verifier does similar check with M\[0-15\] memory slots. For example:



```text
bpf_ld R0 = *(u32 *)(R10 - 4)
bpf_exit
```

is invalid program. Though R10 is correct read-only register and has type PTR_TO_STACK and R10 - 4 is within stack bounds, there were no stores into that location.

Pointer register spill/fill is tracked as well, since four (R6-R9) callee saved registers may not be enough for some programs.

Allowed function calls are customized with bpf_verifier_ops-&gt;get_func_proto() The eBPF verifier will check that registers match argument constraints. After the call register R0 will be set to return type of the function.

Function calls is a main mechanism to extend functionality of eBPF programs. Socket filters may let programs to call one set of functions, whereas tracing filters may allow completely different set.

If a function made accessible to eBPF program, it needs to be thought through from safety point of view. The verifier will guarantee that the function is called with valid arguments.

seccomp vs socket filters have different security restrictions for classic BPF. Seccomp solves this by two stage verifier: classic BPF verifier is followed by seccomp verifier. In case of eBPF one configurable verifier is shared for all use cases.

See details of eBPF verifier in kernel/bpf/verifier.c

<a id="rst-register-value-tracking"></a>

## Register value tracking

In order to determine the safety of an eBPF program, the verifier must track the range of possible values in each register and also in each stack slot. This is done with `struct bpf_reg_state`, defined in include/linux/ bpf_verifier.h, which unifies tracking of scalar and pointer values.  Each register state has a type, which is either NOT_INIT (the register has not been written to), SCALAR_VALUE (some value which is not usable as a pointer), or a pointer type.  The types of pointers describe their base, as follows:

> - **PTR_TO_CTX**
>
>   Pointer to bpf_context.
>
> - **CONST_PTR_TO_MAP**
>
>   Pointer to struct bpf_map.  "Const" because arithmetic on these pointers is forbidden.
>
> - **PTR_TO_MAP_VALUE**
>
>   Pointer to the value stored in a map element.
>
> - **PTR_TO_MAP_VALUE_OR_NULL**
>
>   Either a pointer to a map value, or NULL; map accesses (see [maps.rst](/kernel/internals/bpf/maps.md)) return this type, which becomes a PTR_TO_MAP_VALUE when checked \!= NULL. Arithmetic on these pointers is forbidden.
>
> - **PTR_TO_STACK**
>
>   Frame pointer.
>
> - **PTR_TO_PACKET**
>
>   skb-&gt;data.
>
> - **PTR_TO_PACKET_END**
>
>   skb-&gt;data + headlen; arithmetic forbidden.
>
> - **PTR_TO_SOCKET**
>
>   Pointer to struct bpf_sock_ops, implicitly refcounted.
>
> - **PTR_TO_SOCKET_OR_NULL**
>
>   Either a pointer to a socket, or NULL; socket lookup returns this type, which becomes a PTR_TO_SOCKET when checked \!= NULL. PTR_TO_SOCKET is reference-counted, so programs must release the reference through the socket release function before the end of the program. Arithmetic on these pointers is forbidden.

However, a pointer may be offset from this base (as a result of pointer arithmetic), and this is tracked in two parts: the 'fixed offset' and 'variable offset'.  The former is used when an exactly-known value (e.g. an immediate operand) is added to a pointer, while the latter is used for values which are not exactly known.  The variable offset is also used in SCALAR_VALUEs, to track the range of possible values in the register.

The verifier's knowledge about the variable offset consists of:

- minimum and maximum values as unsigned

- minimum and maximum values as signed

- knowledge of the values of individual bits, in the form of a 'tnum': a u64 'mask' and a u64 'value'.  1s in the mask represent bits whose value is unknown; 1s in the value represent bits known to be 1.  Bits known to be 0 have 0 in both mask and value; no bit should ever be 1 in both.  For example, if a byte is read into a register from memory, the register's top 56 bits are known zero, while the low 8 are unknown - which is represented as the tnum (0x0; 0xff).  If we then OR this with 0x40, we get (0x40; 0xbf), then if we add 1 we get (0x0; 0x1ff), because of potential carries.

Besides arithmetic, the register state can also be updated by conditional branches.  For instance, if a SCALAR_VALUE is compared &gt; 8, in the 'true' branch it will have a umin_value (unsigned minimum value) of 9, whereas in the 'false' branch it will have a umax_value of 8.  A signed compare (with BPF_JSGT or BPF_JSGE) would instead update the signed minimum/maximum values.  Information from the signed and unsigned bounds can be combined; for instance if a value is first tested &lt; 8 and then tested s&gt; 4, the verifier will conclude that the value is also &gt; 4 and s&lt; 8, since the bounds prevent crossing the sign boundary.

PTR_TO_PACKETs with a variable offset part have an 'id', which is common to all pointers sharing that same variable offset.  This is important for packet range checks: after adding a variable to a packet pointer register A, if you then copy it to another register B and then add a constant 4 to A, both registers will share the same 'id' but the A will have a fixed offset of +4.  Then if A is bounds-checked and found to be less than a PTR_TO_PACKET_END, the register B is now known to have a safe range of at least 4 bytes.  See 'Direct packet access', below, for more on PTR_TO_PACKET ranges.

The 'id' field is also used on PTR_TO_MAP_VALUE_OR_NULL, common to all copies of the pointer returned from a map lookup.  This means that when one copy is checked and found to be non-NULL, all copies can become PTR_TO_MAP_VALUEs. As well as range-checking, the tracked information is also used for enforcing alignment of pointer accesses.  For instance, on most systems the packet pointer is 2 bytes after a 4-byte alignment.  If a program adds 14 bytes to that to jump over the Ethernet header, then reads IHL and adds (IHL \* 4), the resulting pointer will have a variable offset known to be 4n+2 for some n, so adding the 2 bytes (NET_IP_ALIGN) gives a 4-byte alignment and so word-sized accesses through that pointer are safe. The 'id' field is also used on PTR_TO_SOCKET and PTR_TO_SOCKET_OR_NULL, common to all copies of the pointer returned from a socket lookup. This has similar behaviour to the handling for PTR_TO_MAP_VALUE_OR_NULL-&gt;PTR_TO_MAP_VALUE, but it also handles reference tracking for the pointer. PTR_TO_SOCKET implicitly represents a reference to the corresponding `struct sock`. To ensure that the reference is not leaked, it is imperative to NULL-check the reference and in the non-NULL case, and pass the valid reference to the socket release function.

<a id="rst-direct-packet-access"></a>

## Direct packet access

In cls_bpf and act_bpf programs the verifier allows direct access to the packet data via skb-&gt;data and skb-&gt;data_end pointers. Ex:



```text
1:  r4 = *(u32 *)(r1 +80)  /* load skb->data_end */
2:  r3 = *(u32 *)(r1 +76)  /* load skb->data */
3:  r5 = r3
4:  r5 += 14
5:  if r5 > r4 goto pc+16
R1=ctx R3=pkt(id=0,off=0,r=14) R4=pkt_end R5=pkt(id=0,off=14,r=14) R10=fp
6:  r0 = *(u16 *)(r3 +12) /* access 12 and 13 bytes of the packet */
```

this 2byte load from the packet is safe to do, since the program author did check `if (skb->data + 14 > skb->data_end) goto err` at insn \#5 which means that in the fall-through case the register R3 (which points to skb-&gt;data) has at least 14 directly accessible bytes. The verifier marks it as R3=pkt(id=0,off=0,r=14). id=0 means that no additional variables were added to the register. off=0 means that no additional constants were added. r=14 is the range of safe access which means that bytes \[R3, R3 + 14) are ok. Note that R5 is marked as R5=pkt(id=0,off=14,r=14). It also points to the packet data, but constant 14 was added to the register, so it now points to `skb->data + 14` and accessible range is \[R5, R5 + 14 - 14) which is zero bytes.

More complex packet access may look like:



```text
R0=inv1 R1=ctx R3=pkt(id=0,off=0,r=14) R4=pkt_end R5=pkt(id=0,off=14,r=14) R10=fp
6:  r0 = *(u8 *)(r3 +7) /* load 7th byte from the packet */
7:  r4 = *(u8 *)(r3 +12)
8:  r4 *= 14
9:  r3 = *(u32 *)(r1 +76) /* load skb->data */
10:  r3 += r4
11:  r2 = r1
12:  r2 <<= 48
13:  r2 >>= 48
14:  r3 += r2
15:  r2 = r3
16:  r2 += 8
17:  r1 = *(u32 *)(r1 +80) /* load skb->data_end */
18:  if r2 > r1 goto pc+2
R0=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) R1=pkt_end R2=pkt(id=2,off=8,r=8) R3=pkt(id=2,off=0,r=8) R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)) R5=pkt(id=0,off=14,r=14) R10=fp
19:  r1 = *(u8 *)(r3 +4)
```

The state of the register R3 is R3=pkt(id=2,off=0,r=8) id=2 means that two `r3 += rX` instructions were seen, so r3 points to some offset within a packet and since the program author did `if (r3 + 8 > r1) goto err` at insn \#18, the safe range is \[R3, R3 + 8). The verifier only allows 'add'/'sub' operations on packet registers. Any other operation will set the register state to 'SCALAR_VALUE' and it won't be available for direct packet access.

Operation `r3 += rX` may overflow and become less than original skb-&gt;data, therefore the verifier has to prevent that.  So when it sees `r3 += rX` instruction and rX is more than 16-bit value, any subsequent bounds-check of r3 against skb-&gt;data_end will not give us 'range' information, so attempts to read through the pointer will give "invalid access to packet" error.

Ex. after insn `r4 = *(u8 *)(r3 +12)` (insn \#7 above) the state of r4 is R4=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) which means that upper 56 bits of the register are guaranteed to be zero, and nothing is known about the lower 8 bits. After insn `r4 *= 14` the state becomes R4=inv(id=0,umax_value=3570,var_off=(0x0; 0xfffe)), since multiplying an 8-bit value by constant 14 will keep upper 52 bits as zero, also the least significant bit will be zero as 14 is even.  Similarly `r2 >>= 48` will make R2=inv(id=0,umax_value=65535,var_off=(0x0; 0xffff)), since the shift is not sign extending.  This logic is implemented in adjust_reg_min_max_vals() function, which calls adjust_ptr_min_max_vals() for adding pointer to scalar (or vice versa) and adjust_scalar_min_max_vals() for operations on two scalars.

The end result is that bpf program author can access packet directly using normal C code as:



```text
void *data = (void *)(long)skb->data;
void *data_end = (void *)(long)skb->data_end;
struct eth_hdr *eth = data;
struct iphdr *iph = data + sizeof(*eth);
struct udphdr *udp = data + sizeof(*eth) + sizeof(*iph);

if (data + sizeof(*eth) + sizeof(*iph) + sizeof(*udp) > data_end)
        return 0;
if (eth->h_proto != htons(ETH_P_IP))
        return 0;
if (iph->protocol != IPPROTO_UDP || iph->ihl != 5)
        return 0;
if (udp->dest == 53 || udp->source == 9)
        ...;
```

which makes such programs easier to write comparing to LD_ABS insn and significantly faster.

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

## Pruning

The verifier does not actually walk all possible paths through the program.  For each new branch to analyse, the verifier looks at all the states it's previously been in when at this instruction.  If any of them contain the current state as a subset, the branch is 'pruned' - that is, the fact that the previous state was accepted implies the current state would be as well.  For instance, if in the previous state, r1 held a packet-pointer, and in the current state, r1 holds a packet-pointer with a range as long or longer and at least as strict an alignment, then r1 is safe.  Similarly, if r2 was NOT_INIT before then it can't have been used by any path from that point, so any value in r2 (including another NOT_INIT) is safe.  The implementation is in the function regsafe(). Pruning considers not only the registers but also the stack (and any spilled registers it may hold).  They must all be safe for the branch to be pruned. This is implemented in states_equal().

Some technical details about state pruning implementation could be found below.

<a id="rst-register-liveness-tracking"></a>

### Register liveness tracking

In order to make state pruning effective, liveness state is tracked for each register and stack slot. The basic idea is to track which registers and stack slots are actually used during subseqeuent execution of the program, until program exit is reached. Registers and stack slots that were never used could be removed from the cached state thus making more states equivalent to a cached state. This could be illustrated by the following program:



```text
0: call bpf_get_prandom_u32()
1: r1 = 0
2: if r0 == 0 goto +1
3: r0 = 1
--- checkpoint ---
4: r0 = r1
5: exit
```

Suppose that a state cache entry is created at instruction \#4 (such entries are also called "checkpoints" in the text below). The verifier could reach the instruction with one of two possible register states:

- r0 = 1, r1 = 0

- r0 = 0, r1 = 0

However, only the value of register `r1` is important to successfully finish verification. The goal of the liveness tracking algorithm is to spot this fact and figure out that both states are actually equivalent.

<a id="rst-understanding-ebpf-verifier-messages"></a>

## Understanding eBPF verifier messages

The following are few examples of invalid eBPF programs and verifier error messages as seen in the log:

Program with unreachable instructions:



```text
static struct bpf_insn prog[] = {
BPF_EXIT_INSN(),
BPF_EXIT_INSN(),
};
```

Error:



```text
unreachable insn 1
```

Program that reads uninitialized register:



```text
BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
BPF_EXIT_INSN(),
```

Error:



```text
0: (bf) r0 = r2
R2 !read_ok
```

Program that doesn't initialize R0 before exiting:



```text
BPF_MOV64_REG(BPF_REG_2, BPF_REG_1),
BPF_EXIT_INSN(),
```

Error:



```text
0: (bf) r2 = r1
1: (95) exit
R0 !read_ok
```

Program that accesses stack out of bounds:



```text
BPF_ST_MEM(BPF_DW, BPF_REG_10, 8, 0),
BPF_EXIT_INSN(),
```

Error:



```text
0: (7a) *(u64 *)(r10 +8) = 0
invalid stack off=8 size=8
```

Program that doesn't initialize stack before passing its address into function:



```text
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_LD_MAP_FD(BPF_REG_1, 0),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_EXIT_INSN(),
```

Error:



```text
0: (bf) r2 = r10
1: (07) r2 += -8
2: (b7) r1 = 0x0
3: (85) call 1
invalid indirect read from stack off -8+0 size 8
```

Program that uses invalid map_fd=0 while calling to map_lookup_elem() function:



```text
BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_LD_MAP_FD(BPF_REG_1, 0),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_EXIT_INSN(),
```

Error:



```text
0: (7a) *(u64 *)(r10 -8) = 0
1: (bf) r2 = r10
2: (07) r2 += -8
3: (b7) r1 = 0x0
4: (85) call 1
fd 0 is not pointing to valid bpf_map
```

Program that doesn't check return value of map_lookup_elem() before accessing map element:



```text
BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_LD_MAP_FD(BPF_REG_1, 0),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
BPF_EXIT_INSN(),
```

Error:



```text
0: (7a) *(u64 *)(r10 -8) = 0
1: (bf) r2 = r10
2: (07) r2 += -8
3: (b7) r1 = 0x0
4: (85) call 1
5: (7a) *(u64 *)(r0 +0) = 0
R0 invalid mem access 'map_value_or_null'
```

Program that correctly checks map_lookup_elem() returned value for NULL, but accesses the memory with incorrect alignment:



```text
BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_LD_MAP_FD(BPF_REG_1, 0),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 1),
BPF_ST_MEM(BPF_DW, BPF_REG_0, 4, 0),
BPF_EXIT_INSN(),
```

Error:



```text
0: (7a) *(u64 *)(r10 -8) = 0
1: (bf) r2 = r10
2: (07) r2 += -8
3: (b7) r1 = 1
4: (85) call 1
5: (15) if r0 == 0x0 goto pc+1
 R0=map_ptr R10=fp
6: (7a) *(u64 *)(r0 +4) = 0
misaligned access off 4 size 8
```

Program that correctly checks map_lookup_elem() returned value for NULL and accesses memory with correct alignment in one side of 'if' branch, but fails to do so in the other side of 'if' branch:



```text
BPF_ST_MEM(BPF_DW, BPF_REG_10, -8, 0),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_LD_MAP_FD(BPF_REG_1, 0),
BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 0),
BPF_EXIT_INSN(),
BPF_ST_MEM(BPF_DW, BPF_REG_0, 0, 1),
BPF_EXIT_INSN(),
```

Error:



```text
0: (7a) *(u64 *)(r10 -8) = 0
1: (bf) r2 = r10
2: (07) r2 += -8
3: (b7) r1 = 1
4: (85) call 1
5: (15) if r0 == 0x0 goto pc+2
 R0=map_ptr R10=fp
6: (7a) *(u64 *)(r0 +0) = 0
7: (95) exit

from 5 to 8: R0=imm0 R10=fp
8: (7a) *(u64 *)(r0 +0) = 1
R0 invalid mem access 'imm'
```

Program that performs a socket lookup then sets the pointer to NULL without checking it:



```text
BPF_MOV64_IMM(BPF_REG_2, 0),
BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_MOV64_IMM(BPF_REG_3, 4),
BPF_MOV64_IMM(BPF_REG_4, 0),
BPF_MOV64_IMM(BPF_REG_5, 0),
BPF_EMIT_CALL(BPF_FUNC_sk_lookup_tcp),
BPF_MOV64_IMM(BPF_REG_0, 0),
BPF_EXIT_INSN(),
```

Error:



```text
0: (b7) r2 = 0
1: (63) *(u32 *)(r10 -8) = r2
2: (bf) r2 = r10
3: (07) r2 += -8
4: (b7) r3 = 4
5: (b7) r4 = 0
6: (b7) r5 = 0
7: (85) call bpf_sk_lookup_tcp#65
8: (b7) r0 = 0
9: (95) exit
Unreleased reference id=1, alloc_insn=7
```

Program that performs a socket lookup but does not NULL-check the returned value:



```text
BPF_MOV64_IMM(BPF_REG_2, 0),
BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_2, -8),
BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),
BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -8),
BPF_MOV64_IMM(BPF_REG_3, 4),
BPF_MOV64_IMM(BPF_REG_4, 0),
BPF_MOV64_IMM(BPF_REG_5, 0),
BPF_EMIT_CALL(BPF_FUNC_sk_lookup_tcp),
BPF_EXIT_INSN(),
```

Error:



```text
0: (b7) r2 = 0
1: (63) *(u32 *)(r10 -8) = r2
2: (bf) r2 = r10
3: (07) r2 += -8
4: (b7) r3 = 4
5: (b7) r4 = 0
6: (b7) r5 = 0
7: (85) call bpf_sk_lookup_tcp#65
8: (95) exit
Unreleased reference id=1, alloc_insn=7
```

---

# libbpf

_Peios Kernel / Internals / BPF / libbpf_

> Duplicate implicit target name: "libbpf".

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

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

If you are looking to develop BPF applications using the libbpf library, this directory contains important documentation that you should read.

To get started, it is recommended to begin with the [libbpf Overview](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/libbpf/libbpf_overview.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) document, which provides a high-level understanding of the libbpf APIs and their usage. This will give you a solid foundation to start exploring and utilizing the various features of libbpf to develop your BPF applications.

- [libbpf_overview](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/libbpf/libbpf_overview.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [API Documentation](<https://libbpf.readthedocs.io/en/latest/api.html>)
- [Program Types and ELF Sections](</kernel/internals/bpf/libbpf/program-types.md>)
- [API naming convention](</kernel/internals/bpf/libbpf/libbpf-naming-convention.md>)
- [Building libbpf](</kernel/internals/bpf/libbpf/libbpf-build.md>)

All general BPF questions, including kernel functionality, libbpf APIs and their application, should be sent to [bpf@vger.kernel.org](<mailto:bpf@vger.kernel.org>) mailing list.  You can [subscribe](<http://vger.kernel.org/vger-lists.html#bpf>)<a id="rst-subscribe"></a> to the mailing list search its [archive](<https://lore.kernel.org/bpf/>)<a id="rst-archive"></a>.  Please search the archive before asking new questions. It may be that this was already addressed or answered before.

---

# Building libbpf

_Peios Kernel / Internals / BPF / libbpf_

> libelf and zlib are internal dependencies of libbpf and thus are required to link against and must be installed on the system for applications to work. pkg-config is used by default to find libelf, and the program called can be overridden…

<a id="rst-building-libbpf"></a>

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

libelf and zlib are internal dependencies of libbpf and thus are required to link against and must be installed on the system for applications to work. pkg-config is used by default to find libelf, and the program called can be overridden with PKG_CONFIG.

If using pkg-config at build time is not desired, it can be disabled by setting NO_PKG_CONFIG=1 when calling make.

To build both static libbpf.a and shared libbpf.so:



```bash
$ cd src
$ make
```

To build only static libbpf.a library in directory build/ and install them together with libbpf headers in a staging directory root/:



```bash
$ cd src
$ mkdir build root
$ BUILD_STATIC_ONLY=y OBJDIR=build DESTDIR=root make install
```

To build both static libbpf.a and shared libbpf.so against a custom libelf dependency installed in /build/root/ and install them together with libbpf headers in a build directory /build/root/:



```bash
$ cd src
$ PKG_CONFIG_PATH=/build/root/lib64/pkgconfig DESTDIR=/build/root make
```

---

# API naming convention

_Peios Kernel / Internals / BPF / libbpf_

> libbpf API provides access to a few logically separated groups of functions and types. Every group has its own naming convention described here. It's recommended to follow these conventions whenever a new function or type is added to keep…

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

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

## API naming convention

libbpf API provides access to a few logically separated groups of functions and types. Every group has its own naming convention described here. It's recommended to follow these conventions whenever a new function or type is added to keep libbpf API clean and consistent.

All types and functions provided by libbpf API should have one of the following prefixes: `bpf_`, `btf_`, `libbpf_`, `btf_dump_`, `ring_buffer_`, `perf_buffer_`.

<a id="rst-system-call-wrappers"></a>

### System call wrappers

System call wrappers are simple wrappers for commands supported by sys_bpf system call. These wrappers should go to `bpf.h` header file and map one to one to corresponding commands.

For example `bpf_map_lookup_elem` wraps `BPF_MAP_LOOKUP_ELEM` command of sys_bpf, `bpf_prog_attach` wraps `BPF_PROG_ATTACH`, etc.

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

### Objects

Another class of types and functions provided by libbpf API is "objects" and functions to work with them. Objects are high-level abstractions such as BPF program or BPF map. They're represented by corresponding structures such as `struct bpf_object`, `struct bpf_program`, `struct bpf_map`, etc.

Structures are forward declared and access to their fields should be provided via corresponding getters and setters rather than directly.

These objects are associated with corresponding parts of ELF object that contains compiled BPF programs.

For example `struct bpf_object` represents ELF object itself created from an ELF file or from a buffer, `struct bpf_program` represents a program in ELF object and `struct bpf_map` is a map.

Functions that work with an object have names built from object name, double underscore and part that describes function purpose.

For example `bpf_object__open` consists of the name of corresponding object, `bpf_object`, double underscore and `open` that defines the purpose of the function to open ELF file and create `bpf_object` from it.

All objects and corresponding functions other than BTF related should go to `libbpf.h`. BTF types and functions should go to `btf.h`.

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

### Auxiliary functions

Auxiliary functions and types that don't fit well in any of categories described above should have `libbpf_` prefix, e.g. `libbpf_get_error` or `libbpf_prog_type_by_name`.

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

### ABI

libbpf can be both linked statically or used as DSO. To avoid possible conflicts with other libraries an application is linked with, all non-static libbpf symbols should have one of the prefixes mentioned in API documentation above. See API naming convention to choose the right name for a new symbol.

<a id="rst-symbol-visibility"></a>

### Symbol visibility

libbpf follow the model when all global symbols have visibility "hidden" by default and to make a symbol visible it has to be explicitly attributed with `LIBBPF_API` macro. For example:



```c
LIBBPF_API int bpf_prog_get_fd_by_id(__u32 id);
```

This prevents from accidentally exporting a symbol, that is not supposed to be a part of ABI what, in turn, improves both libbpf developer- and user-experiences.

<a id="rst-abi-versioning"></a>

### ABI versioning

To make future ABI extensions possible libbpf ABI is versioned. Versioning is implemented by `libbpf.map` version script that is passed to linker.

Version name is `LIBBPF_` prefix + three-component numeric version, starting from `0.0.1`.

Every time ABI is being changed, e.g. because a new symbol is added or semantic of existing symbol is changed, ABI version should be bumped. This bump in ABI version is at most once per kernel development cycle.

For example, if current state of `libbpf.map` is:



```none
LIBBPF_0.0.1 {
        global:
                bpf_func_a;
                bpf_func_b;
        local:
                \*;
};
```

, and a new symbol `bpf_func_c` is being introduced, then `libbpf.map` should be changed like this:



```none
LIBBPF_0.0.1 {
        global:
                bpf_func_a;
                bpf_func_b;
        local:
                \*;
};
LIBBPF_0.0.2 {
        global:
                bpf_func_c;
} LIBBPF_0.0.1;
```

, where new version `LIBBPF_0.0.2` depends on the previous `LIBBPF_0.0.1`.

Format of version script and ways to handle ABI changes, including incompatible ones, described in details in \[1\].

<a id="rst-stand-alone-build"></a>

### Stand-alone build

Under [https://github.com/libbpf/libbpf](<https://github.com/libbpf/libbpf>) there is a (semi-)automated mirror of the mainline's version of libbpf for a stand-alone build.

However, all changes to libbpf's code base must be upstreamed through the mainline kernel tree.

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

## API documentation convention

The libbpf API is documented via comments above definitions in header files. These comments can be rendered by doxygen and sphinx for well organized html output. This section describes the convention in which these comments should be formatted.

Here is an example from btf.h:



```c
/**
 * @brief **btf__new()** creates a new instance of a BTF object from the raw
 * bytes of an ELF's BTF section
 * @param data raw bytes
 * @param size number of bytes passed in `data`
 * @return new BTF object instance which has to be eventually freed with
 * **btf__free()**
 *
 * On error, error-code-encoded-as-pointer is returned, not a NULL. To extract
 * error code from such a pointer `libbpf_get_error()` should be used. If
 * `libbpf_set_strict_mode(LIBBPF_STRICT_CLEAN_PTRS)` is enabled, NULL is
 * returned on error instead. In both cases thread-local `errno` variable is
 * always set to error code as well.
 */
```

The comment must start with a block comment of the form '/\*\*'.

The documentation always starts with a @brief directive. This line is a short description about this API. It starts with the name of the API, denoted in bold like so: **api_name**. Please include an open and close parenthesis if this is a function. Follow with the short description of the API. A longer form description can be added below the last directive, at the bottom of the comment.

Parameters are denoted with the @param directive, there should be one for each parameter. If this is a function with a non-void return, use the @return directive to document it.

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

### License

libbpf is dual-licensed under LGPL 2.1 and BSD 2-Clause.

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

### Links

- **\[1\] [https://www.akkadia.org/drepper/dsohowto.pdf](<https://www.akkadia.org/drepper/dsohowto.pdf>)**

  (Chapter 3. Maintaining APIs and ABIs).

---

# libbpf Overview

_Peios Kernel / Internals / BPF / libbpf_

> libbpf is a C-based library containing a BPF loader that takes compiled BPF object files and prepares and loads them into the Linux kernel. libbpf takes the heavy lifting of loading, verifying, and attaching BPF programs to various kernel…

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

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

libbpf is a C-based library containing a BPF loader that takes compiled BPF object files and prepares and loads them into the Linux kernel. libbpf takes the heavy lifting of loading, verifying, and attaching BPF programs to various kernel hooks, allowing BPF application developers to focus only on BPF program correctness and performance.

The following are the high-level features supported by libbpf:

- Provides high-level and low-level APIs for user space programs to interact with BPF programs. The low-level APIs wrap all the bpf system call functionality, which is useful when users need more fine-grained control over the interactions between user space and BPF programs.

- Provides overall support for the BPF object skeleton generated by bpftool. The skeleton file simplifies the process for the user space programs to access global variables and work with BPF programs.

- Provides BPF-side APIS, including BPF helper definitions, BPF maps support, and tracing helpers, allowing developers to simplify BPF code writing.

- Supports BPF CO-RE mechanism, enabling BPF developers to write portable BPF programs that can be compiled once and run across different kernel versions.

This document will delve into the above concepts in detail, providing a deeper understanding of the capabilities and advantages of libbpf and how it can help you develop BPF applications efficiently.

<a id="rst-bpf-app-lifecycle-and-libbpf-apis"></a>

## BPF App Lifecycle and libbpf APIs

A BPF application consists of one or more BPF programs (either cooperating or completely independent), BPF maps, and global variables. The global variables are shared between all BPF programs, which allows them to cooperate on a common set of data. libbpf provides APIs that user space programs can use to manipulate the BPF programs by triggering different phases of a BPF application lifecycle.

The following section provides a brief overview of each phase in the BPF life cycle:

- <strong>Open phase</strong>: In this phase, libbpf parses the BPF object file and discovers BPF maps, BPF programs, and global variables. After a BPF app is opened, user space apps can make additional adjustments (setting BPF program types, if necessary; pre-setting initial values for global variables, etc.) before all the entities are created and loaded.

- <strong>Load phase</strong>: In the load phase, libbpf creates BPF maps, resolves various relocations, and verifies and loads BPF programs into the kernel. At this point, libbpf validates all the parts of a BPF application and loads the BPF program into the kernel, but no BPF program has yet been executed. After the load phase, it’s possible to set up the initial BPF map state without racing with the BPF program code execution.

- <strong>Attachment phase</strong>: In this phase, libbpf attaches BPF programs to various BPF hook points (e.g., tracepoints, kprobes, cgroup hooks, network packet processing pipeline, etc.). During this phase, BPF programs perform useful work such as processing packets, or updating BPF maps and global variables that can be read from user space.

- <strong>Tear down phase</strong>: In the tear down phase, libbpf detaches BPF programs and unloads them from the kernel. BPF maps are destroyed, and all the resources used by the BPF app are freed.

<a id="rst-bpf-object-skeleton-file"></a>

## BPF Object Skeleton File

BPF skeleton is an alternative interface to libbpf APIs for working with BPF objects. Skeleton code abstract away generic libbpf APIs to significantly simplify code for manipulating BPF programs from user space. Skeleton code includes a bytecode representation of the BPF object file, simplifying the process of distributing your BPF code. With BPF bytecode embedded, there are no extra files to deploy along with your application binary.

You can generate the skeleton header file `(.skel.h)` for a specific object file by passing the BPF object to the bpftool. The generated BPF skeleton provides the following custom functions that correspond to the BPF lifecycle, each of them prefixed with the specific object name:

- `<name>__open()` – creates and opens BPF application (`<name>` stands for the specific bpf object name)

- `<name>__load()` – instantiates, loads,and verifies BPF application parts

- `<name>__attach()` – attaches all auto-attachable BPF programs (it’s optional, you can have more control by using libbpf APIs directly)

- `<name>__destroy()` – detaches all BPF programs and frees up all used resources

Using the skeleton code is the recommended way to work with bpf programs. Keep in mind, BPF skeleton provides access to the underlying BPF object, so whatever was possible to do with generic libbpf APIs is still possible even when the BPF skeleton is used. It's an additive convenience feature, with no syscalls, and no cumbersome code.

<a id="rst-other-advantages-of-using-skeleton-file"></a>

### Other Advantages of Using Skeleton File

- BPF skeleton provides an interface for user space programs to work with BPF global variables. The skeleton code memory maps global variables as a struct into user space. The struct interface allows user space programs to initialize BPF programs before the BPF load phase and fetch and update data from user space afterward.

- The `skel.h` file reflects the object file structure by listing out the available maps, programs, etc. BPF skeleton provides direct access to all the BPF maps and BPF programs as struct fields. This eliminates the need for string-based lookups with `bpf_object_find_map_by_name()` and `bpf_object_find_program_by_name()` APIs, reducing errors due to BPF source code and user-space code getting out of sync.

- The embedded bytecode representation of the object file ensures that the skeleton and the BPF object file are always in sync.

<a id="rst-bpf-helpers"></a>

## BPF Helpers

libbpf provides BPF-side APIs that BPF programs can use to interact with the system. The BPF helpers definition allows developers to use them in BPF code as any other plain C function. For example, there are helper functions to print debugging messages, get the time since the system was booted, interact with BPF maps, manipulate network packets, etc.

For a complete description of what the helpers do, the arguments they take, and the return value, see the [bpf-helpers](<https://man7.org/linux/man-pages/man7/bpf-helpers.7.html>)<a id="rst-bpf-helpers-1"></a> man page.

<a id="rst-bpf-co-re-compile-once-run-everywhere"></a>

## BPF CO-RE (Compile Once – Run Everywhere)

BPF programs work in the kernel space and have access to kernel memory and data structures. One limitation that BPF applications come across is the lack of portability across different kernel versions and configurations. [BCC](<https://github.com/iovisor/bcc/>)<a id="rst-bcc"></a> is one of the solutions for BPF portability. However, it comes with runtime overhead and a large binary size from embedding the compiler with the application.

libbpf steps up the BPF program portability by supporting the BPF CO-RE concept. BPF CO-RE brings together BTF type information, libbpf, and the compiler to produce a single executable binary that you can run on multiple kernel versions and configurations.

To make BPF programs portable libbpf relies on the BTF type information of the running kernel. Kernel also exposes this self-describing authoritative BTF information through `sysfs` at `/sys/kernel/btf/vmlinux`.

You can generate the BTF information for the running kernel with the following command:



```text
$ bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
```

The command generates a `vmlinux.h` header file with all kernel types ([BTF types](</kernel/internals/bpf/btf.md>)) that the running kernel uses. Including `vmlinux.h` in your BPF program eliminates dependency on system-wide kernel headers.

libbpf enables portability of BPF programs by looking at the BPF program’s recorded BTF type and relocation information and matching them to BTF information (vmlinux) provided by the running kernel. libbpf then resolves and matches all the types and fields, and updates necessary offsets and other relocatable data to ensure that BPF program’s logic functions correctly for a specific kernel on the host. BPF CO-RE concept thus eliminates overhead associated with BPF development and allows developers to write portable BPF applications without modifications and runtime source code compilation on the target machine.

The following code snippet shows how to read the parent field of a kernel `task_struct` using BPF CO-RE and libbf. The basic helper to read a field in a CO-RE relocatable manner is `bpf_core_read(dst, sz, src)`, which will read `sz` bytes from the field referenced by `src` into the memory pointed to by `dst`.



```C
 //...
 struct task_struct *task = (void *)bpf_get_current_task();
 struct task_struct *parent_task;
 int err;

 err = bpf_core_read(&parent_task, sizeof(void *), &task->parent);
 if (err) {
   /* handle error */
 }

 /* parent_task contains the value of task->parent pointer */
```

In the code snippet, we first get a pointer to the current `task_struct` using `bpf_get_current_task()`.  We then use `bpf_core_read()` to read the parent field of task struct into the `parent_task` variable. `bpf_core_read()` is just like `bpf_probe_read_kernel()` BPF helper, except it records information about the field that should be relocated on the target kernel. i.e, if the `parent` field gets shifted to a different offset within `struct task_struct` due to some new field added in front of it, libbpf will automatically adjust the actual offset to the proper value.

<a id="rst-getting-started-with-libbpf"></a>

## Getting Started with libbpf

Check out the [libbpf-bootstrap](<https://github.com/libbpf/libbpf-bootstrap>)<a id="rst-libbpf-bootstrap"></a> repository with simple examples of using libbpf to build various BPF applications.

See also [libbpf API documentation](<https://libbpf.readthedocs.io/en/latest/api.html>)<a id="rst-libbpf-api-documentation"></a>.

<a id="rst-libbpf-and-rust"></a>

## libbpf and Rust

If you are building BPF applications in Rust, it is recommended to use the [Libbpf-rs](<https://github.com/libbpf/libbpf-rs>)<a id="rst-libbpf-rs"></a> library instead of bindgen bindings directly to libbpf. Libbpf-rs wraps libbpf functionality in Rust-idiomatic interfaces and provides libbpf-cargo plugin to handle BPF code compilation and skeleton generation. Using Libbpf-rs will make building user space part of the BPF application easier. Note that the BPF program themselves must still be written in plain C.

<a id="rst-libbpf-logging"></a>

## libbpf logging

By default, libbpf logs informational and warning messages to stderr. The verbosity of these messages can be controlled by setting the environment variable LIBBPF\_LOG\_LEVEL to either warn, info, or debug. A custom log callback can be set using `libbpf_set_print()`.

<a id="rst-additional-documentation"></a>

## Additional Documentation

- [Program types and ELF Sections](<https://libbpf.readthedocs.io/en/latest/program_types.html>)<a id="rst-program-types-and-elf-sections"></a>

- [API naming convention](<https://libbpf.readthedocs.io/en/latest/libbpf_naming_convention.html>)<a id="rst-api-naming-convention"></a>

- [Building libbpf](<https://libbpf.readthedocs.io/en/latest/libbpf_build.html>)<a id="rst-building-libbpf"></a>

- [API documentation Convention](<https://libbpf.readthedocs.io/en/latest/libbpf_naming_convention.html#api-documentation-convention>)<a id="rst-api-documentation-convention"></a>

---

# Program Types and ELF Sections

_Peios Kernel / Internals / BPF / libbpf_

> The table below lists the program types, their attach types where relevant and the ELF section names supported by libbpf for them. The ELF section names follow these rules:

<a id="rst-program-types-and-elf-sections"></a>
<a id="rst-program-types-and-elf"></a>

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

The table below lists the program types, their attach types where relevant and the ELF section names supported by libbpf for them. The ELF section names follow these rules:

- `type` is an exact match, e.g. `SEC("socket")`

- `type+` means it can be either exact `SEC("type")` or well-formed `SEC("type/extras")` with a '`/`' separator between `type` and `extras`.

When `extras` are specified, they provide details of how to auto-attach the BPF program.  The format of `extras` depends on the program type, e.g. `SEC("tracepoint/<category>/<name>")` for tracepoints or `SEC("usdt/<path>:<provider>:<name>")` for USDT probes. The extras are described in more detail in the footnotes.


<table>
<thead>
<tr>
<th>


Program Type

</th>
<th>


Attach Type

</th>
<th>


ELF Section Name

</th>
<th>


Sleepable

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


`BPF_PROG_TYPE_CGROUP_DEVICE`

</td>
<td>


`BPF_CGROUP_DEVICE`

</td>
<td>


`cgroup/dev`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="3">


`BPF_PROG_TYPE_CGROUP_SKB`

</td>
<td>




</td>
<td>


`cgroup/skb`

</td>
<td>




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


`BPF_CGROUP_INET_EGRESS`

</td>
<td>


`cgroup_skb/egress`

</td>
<td>




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


`BPF_CGROUP_INET_INGRESS`

</td>
<td>


`cgroup_skb/ingress`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_CGROUP_SOCKOPT`

</td>
<td>


`BPF_CGROUP_GETSOCKOPT`

</td>
<td>


`cgroup/getsockopt`

</td>
<td>




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


`BPF_CGROUP_SETSOCKOPT`

</td>
<td>


`cgroup/setsockopt`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="17">


`BPF_PROG_TYPE_CGROUP_SOCK_ADDR`

</td>
<td>


`BPF_CGROUP_INET4_BIND`

</td>
<td>


`cgroup/bind4`

</td>
<td>




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


`BPF_CGROUP_INET4_CONNECT`

</td>
<td>


`cgroup/connect4`

</td>
<td>




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


`BPF_CGROUP_INET4_GETPEERNAME`

</td>
<td>


`cgroup/getpeername4`

</td>
<td>




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


`BPF_CGROUP_INET4_GETSOCKNAME`

</td>
<td>


`cgroup/getsockname4`

</td>
<td>




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


`BPF_CGROUP_INET6_BIND`

</td>
<td>


`cgroup/bind6`

</td>
<td>




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


`BPF_CGROUP_INET6_CONNECT`

</td>
<td>


`cgroup/connect6`

</td>
<td>




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


`BPF_CGROUP_INET6_GETPEERNAME`

</td>
<td>


`cgroup/getpeername6`

</td>
<td>




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


`BPF_CGROUP_INET6_GETSOCKNAME`

</td>
<td>


`cgroup/getsockname6`

</td>
<td>




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


`BPF_CGROUP_UDP4_RECVMSG`

</td>
<td>


`cgroup/recvmsg4`

</td>
<td>




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


`BPF_CGROUP_UDP4_SENDMSG`

</td>
<td>


`cgroup/sendmsg4`

</td>
<td>




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


`BPF_CGROUP_UDP6_RECVMSG`

</td>
<td>


`cgroup/recvmsg6`

</td>
<td>




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


`BPF_CGROUP_UDP6_SENDMSG`

</td>
<td>


`cgroup/sendmsg6`

</td>
<td>




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


`BPF_CGROUP_UNIX_CONNECT`

</td>
<td>


`cgroup/connect_unix`

</td>
<td>




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


`BPF_CGROUP_UNIX_SENDMSG`

</td>
<td>


`cgroup/sendmsg_unix`

</td>
<td>




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


`BPF_CGROUP_UNIX_RECVMSG`

</td>
<td>


`cgroup/recvmsg_unix`

</td>
<td>




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


`BPF_CGROUP_UNIX_GETPEERNAME`

</td>
<td>


`cgroup/getpeername_unix`

</td>
<td>




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


`BPF_CGROUP_UNIX_GETSOCKNAME`

</td>
<td>


`cgroup/getsockname_unix`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="5">


`BPF_PROG_TYPE_CGROUP_SOCK`

</td>
<td>


`BPF_CGROUP_INET4_POST_BIND`

</td>
<td>


`cgroup/post_bind4`

</td>
<td>




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


`BPF_CGROUP_INET6_POST_BIND`

</td>
<td>


`cgroup/post_bind6`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_CGROUP_INET_SOCK_CREATE`

</td>
<td>


`cgroup/sock_create`

</td>
<td>




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


`cgroup/sock`

</td>
<td>




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


`BPF_CGROUP_INET_SOCK_RELEASE`

</td>
<td>


`cgroup/sock_release`

</td>
<td>




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


`BPF_PROG_TYPE_CGROUP_SYSCTL`

</td>
<td>


`BPF_CGROUP_SYSCTL`

</td>
<td>


`cgroup/sysctl`

</td>
<td>




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


`BPF_PROG_TYPE_EXT`

</td>
<td>




</td>
<td>


`freplace+` <a id="rst-footnote-reference-1"></a>[1](#rst-fentry)

</td>
<td>




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


`BPF_PROG_TYPE_FLOW_DISSECTOR`

</td>
<td>


`BPF_FLOW_DISSECTOR`

</td>
<td>


`flow_dissector`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="19">


`BPF_PROG_TYPE_KPROBE`

</td>
<td rowspan="10">




</td>
<td>


`kprobe+` <a id="rst-footnote-reference-2"></a>[2](#rst-kprobe)

</td>
<td>




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


`kretprobe+` <a id="rst-footnote-reference-3"></a>[2](#rst-kprobe)

</td>
<td>




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


`ksyscall+` <a id="rst-footnote-reference-4"></a>[3](#rst-ksyscall)

</td>
<td>




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


`kretsyscall+` <a id="rst-footnote-reference-5"></a>[3](#rst-ksyscall)

</td>
<td>




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


`uprobe+` <a id="rst-footnote-reference-6"></a>[4](#rst-uprobe)

</td>
<td>




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


`uprobe.s+` <a id="rst-footnote-reference-7"></a>[4](#rst-uprobe)

</td>
<td>


Yes

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


`uretprobe+` <a id="rst-footnote-reference-8"></a>[4](#rst-uprobe)

</td>
<td>




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


`uretprobe.s+` <a id="rst-footnote-reference-9"></a>[4](#rst-uprobe)

</td>
<td>


Yes

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


`usdt+` <a id="rst-footnote-reference-10"></a>[6](#rst-usdt)

</td>
<td>




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


`usdt.s+` <a id="rst-footnote-reference-11"></a>[6](#rst-usdt)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_TRACE_KPROBE_MULTI`

</td>
<td>


`kprobe.multi+` <a id="rst-footnote-reference-12"></a>[7](#rst-kpmulti)

</td>
<td>




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


`kretprobe.multi+` <a id="rst-footnote-reference-13"></a>[7](#rst-kpmulti)

</td>
<td>




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


`BPF_TRACE_KPROBE_SESSION`

</td>
<td>


`kprobe.session+` <a id="rst-footnote-reference-14"></a>[7](#rst-kpmulti)

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="4">


`BPF_TRACE_UPROBE_MULTI`

</td>
<td>


`uprobe.multi+` <a id="rst-footnote-reference-15"></a>[5](#rst-upmul)

</td>
<td>




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


`uprobe.multi.s+` <a id="rst-footnote-reference-16"></a>[5](#rst-upmul)

</td>
<td>


Yes

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


`uretprobe.multi+` <a id="rst-footnote-reference-17"></a>[5](#rst-upmul)

</td>
<td>




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


`uretprobe.multi.s+` <a id="rst-footnote-reference-18"></a>[5](#rst-upmul)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_TRACE_UPROBE_SESSION`

</td>
<td>


`uprobe.session+` <a id="rst-footnote-reference-19"></a>[5](#rst-upmul)

</td>
<td>




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


`uprobe.session.s+` <a id="rst-footnote-reference-20"></a>[5](#rst-upmul)

</td>
<td>


Yes

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


`BPF_PROG_TYPE_LIRC_MODE2`

</td>
<td>


`BPF_LIRC_MODE2`

</td>
<td>


`lirc_mode2`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="3">


`BPF_PROG_TYPE_LSM`

</td>
<td>


`BPF_LSM_CGROUP`

</td>
<td>


`lsm_cgroup+`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_LSM_MAC`

</td>
<td>


`lsm+` <a id="rst-footnote-reference-21"></a>[8](#rst-lsm)

</td>
<td>




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


`lsm.s+` <a id="rst-footnote-reference-22"></a>[8](#rst-lsm)

</td>
<td>


Yes

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


`BPF_PROG_TYPE_LWT_IN`

</td>
<td>




</td>
<td>


`lwt_in`

</td>
<td>




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


`BPF_PROG_TYPE_LWT_OUT`

</td>
<td>




</td>
<td>


`lwt_out`

</td>
<td>




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


`BPF_PROG_TYPE_LWT_SEG6LOCAL`

</td>
<td>




</td>
<td>


`lwt_seg6local`

</td>
<td>




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


`BPF_PROG_TYPE_LWT_XMIT`

</td>
<td>




</td>
<td>


`lwt_xmit`

</td>
<td>




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


`BPF_PROG_TYPE_NETFILTER`

</td>
<td>




</td>
<td>


`netfilter`

</td>
<td>




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


`BPF_PROG_TYPE_PERF_EVENT`

</td>
<td>




</td>
<td>


`perf_event`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE`

</td>
<td rowspan="2">




</td>
<td>


`raw_tp.w+` <a id="rst-footnote-reference-23"></a>[9](#rst-rawtp)

</td>
<td>




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


`raw_tracepoint.w+`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_RAW_TRACEPOINT`

</td>
<td rowspan="2">




</td>
<td>


`raw_tp+` <a id="rst-footnote-reference-24"></a>[9](#rst-rawtp)

</td>
<td>




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


`raw_tracepoint+`

</td>
<td>




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


`BPF_PROG_TYPE_SCHED_ACT`

</td>
<td>




</td>
<td>


`action` <a id="rst-footnote-reference-25"></a>[10](#rst-tc-legacy)

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="8">


`BPF_PROG_TYPE_SCHED_CLS`

</td>
<td rowspan="2">




</td>
<td>


`classifier` <a id="rst-footnote-reference-26"></a>[10](#rst-tc-legacy)

</td>
<td>




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


`tc` <a id="rst-footnote-reference-27"></a>[10](#rst-tc-legacy)

</td>
<td>




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


`BPF_NETKIT_PRIMARY`

</td>
<td>


`netkit/primary`

</td>
<td>




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


`BPF_NETKIT_PEER`

</td>
<td>


`netkit/peer`

</td>
<td>




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


`BPF_TCX_INGRESS`

</td>
<td>


`tc/ingress`

</td>
<td>




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


`BPF_TCX_EGRESS`

</td>
<td>


`tc/egress`

</td>
<td>




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


`BPF_TCX_INGRESS`

</td>
<td>


`tcx/ingress`

</td>
<td>




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


`BPF_TCX_EGRESS`

</td>
<td>


`tcx/egress`

</td>
<td>




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


`BPF_PROG_TYPE_SK_LOOKUP`

</td>
<td>


`BPF_SK_LOOKUP`

</td>
<td>


`sk_lookup`

</td>
<td>




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


`BPF_PROG_TYPE_SK_MSG`

</td>
<td>


`BPF_SK_MSG_VERDICT`

</td>
<td>


`sk_msg`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_SK_REUSEPORT`

</td>
<td>


`BPF_SK_REUSEPORT_SELECT_OR_MIGRATE`

</td>
<td>


`sk_reuseport/migrate`

</td>
<td>




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


`BPF_SK_REUSEPORT_SELECT`

</td>
<td>


`sk_reuseport`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="3">


`BPF_PROG_TYPE_SK_SKB`

</td>
<td>




</td>
<td>


`sk_skb`

</td>
<td>




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


`BPF_SK_SKB_STREAM_PARSER`

</td>
<td>


`sk_skb/stream_parser`

</td>
<td>




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


`BPF_SK_SKB_STREAM_VERDICT`

</td>
<td>


`sk_skb/stream_verdict`

</td>
<td>




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


`BPF_PROG_TYPE_SOCKET_FILTER`

</td>
<td>




</td>
<td>


`socket`

</td>
<td>




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


`BPF_PROG_TYPE_SOCK_OPS`

</td>
<td>


`BPF_CGROUP_SOCK_OPS`

</td>
<td>


`sockops`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_STRUCT_OPS`

</td>
<td rowspan="2">




</td>
<td>


`struct_ops+` <a id="rst-footnote-reference-28"></a>[11](#rst-struct-ops)

</td>
<td>




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


`struct_ops.s+` <a id="rst-footnote-reference-29"></a>[11](#rst-struct-ops)

</td>
<td>


Yes

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


`BPF_PROG_TYPE_SYSCALL`

</td>
<td>




</td>
<td>


`syscall`

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_PROG_TYPE_TRACEPOINT`

</td>
<td rowspan="2">




</td>
<td>


`tp+` <a id="rst-footnote-reference-30"></a>[12](#rst-tp)

</td>
<td>




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


`tracepoint+` <a id="rst-footnote-reference-31"></a>[12](#rst-tp)

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="9">


`BPF_PROG_TYPE_TRACING`

</td>
<td rowspan="2">


`BPF_MODIFY_RETURN`

</td>
<td>


`fmod_ret+` <a id="rst-footnote-reference-32"></a>[1](#rst-fentry)

</td>
<td>




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


`fmod_ret.s+` <a id="rst-footnote-reference-33"></a>[1](#rst-fentry)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_TRACE_FENTRY`

</td>
<td>


`fentry+` <a id="rst-footnote-reference-34"></a>[1](#rst-fentry)

</td>
<td>




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


`fentry.s+` <a id="rst-footnote-reference-35"></a>[1](#rst-fentry)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_TRACE_FEXIT`

</td>
<td>


`fexit+` <a id="rst-footnote-reference-36"></a>[1](#rst-fentry)

</td>
<td>




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


`fexit.s+` <a id="rst-footnote-reference-37"></a>[1](#rst-fentry)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td rowspan="2">


`BPF_TRACE_ITER`

</td>
<td>


`iter+` <a id="rst-footnote-reference-38"></a>[13](#rst-iter)

</td>
<td>




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


`iter.s+` <a id="rst-footnote-reference-39"></a>[13](#rst-iter)

</td>
<td>


Yes

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


`BPF_TRACE_RAW_TP`

</td>
<td>


`tp_btf+` <a id="rst-footnote-reference-40"></a>[1](#rst-fentry)

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="6">


`BPF_PROG_TYPE_XDP`

</td>
<td rowspan="2">


`BPF_XDP_CPUMAP`

</td>
<td>


`xdp.frags/cpumap`

</td>
<td>




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


`xdp/cpumap`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_XDP_DEVMAP`

</td>
<td>


`xdp.frags/devmap`

</td>
<td>




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


`xdp/devmap`

</td>
<td>




</td>
</tr>
<tr>
<td rowspan="2">


`BPF_XDP`

</td>
<td>


`xdp.frags`

</td>
<td>




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


`xdp`

</td>
<td>




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

**Footnotes**

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



**[1]** The `fentry` attach format is `fentry[.s]/<function>`.

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



**[2]** The `kprobe` attach format is `kprobe/<function>[+<offset>]`. Valid characters for `function` are `a-zA-Z0-9_.` and `offset` must be a valid non-negative integer.

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



**[3]** The `ksyscall` attach format is `ksyscall/<syscall>`.

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



**[4]** The `uprobe` attach format is `uprobe[.s]/<path>:<function>[+<offset>]`.

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



**[5]** The `uprobe.multi` attach format is `uprobe.multi[.s]/<path>:<function-pattern>` where `function-pattern` supports `*` and `?` wildcards.

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



**[6]** The `usdt` attach format is `usdt/<path>:<provider>:<name>`.

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



**[7]** The `kprobe.multi` attach format is `kprobe.multi/<pattern>` where `pattern` supports `*` and `?` wildcards. Valid characters for pattern are `a-zA-Z0-9_.*?`.

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



**[8]** The `lsm` attachment format is `lsm[.s]/<hook>`.

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



**[9]** The `raw_tp` attach format is `raw_tracepoint[.w]/<tracepoint>`.

<a id="rst-tc-legacy"></a>



**[10]** The `tc`, `classifier` and `action` attach types are deprecated, use `tcx/*` instead.

<a id="rst-struct-ops"></a>



**[11]** The `struct_ops` attach format supports `struct_ops[.s]/<name>` convention, but `name` is ignored and it is recommended to just use plain `SEC("struct_ops[.s]")`. The attachments are defined in a struct initializer that is tagged with `SEC(".struct_ops[.link]")`.

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



**[12]** The `tracepoint` attach format is `tracepoint/<category>/<name>`.

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



**[13]** The `iter` attach format is `iter[.s]/<struct-name>`.

---

# BPF Standardization

_Peios Kernel / Internals / BPF / standardization_

> This directory contains documents that are being iterated on as part of the BPF standardization effort with the IETF. See the IETF BPF Working Group page for the working group charter, documents, and more.

<a id="rst-bpf-standardization"></a>

<!-- SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) -->

This directory contains documents that are being iterated on as part of the BPF standardization effort with the IETF. See the [IETF BPF Working Group](<https://datatracker.ietf.org/wg/bpf/about/>) page for the working group charter, documents, and more.

- [instruction-set](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/standardization/instruction-set.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Contents](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/bpf/standardization/abi.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

<!-- Links: -->

<a id="rst-ietf-bpf-working-group"></a>

---

# Contents

_Peios Kernel / Internals / BPF / standardization_

> 1 BPF ABI Recommended Conventions and Guidelines v1.0

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



<a id="rst-bpf-abi-recommended-conventions-and-guidelines-v1-0"></a>

## 1   BPF ABI Recommended Conventions and Guidelines v1.0

This is version 1.0 of an informational document containing recommended conventions and guidelines for producing portable BPF program binaries.

<a id="rst-registers-and-calling-convention"></a>

### 1.1   Registers and calling convention

BPF has 10 general purpose registers and a read-only frame pointer register, all of which are 64-bits wide.

The BPF calling convention is defined as:

- R0: return value from function calls, and exit value for BPF programs

- R1 - R5: arguments for function calls

- R6 - R9: callee saved registers that function calls will preserve

- R10: read-only frame pointer to access stack

R0 - R5 are scratch registers and BPF programs needs to spill/fill them if necessary across calls.

The BPF program needs to store the return value into register R0 before doing an `EXIT`.

---

# Contents

_Peios Kernel / Internals / BPF / standardization_

> 1 BPF Instruction Set Architecture (ISA)

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



<a id="rst-bpf-instruction-set-architecture-isa"></a>

## 1   BPF Instruction Set Architecture (ISA)

eBPF, also commonly referred to as BPF, is a technology with origins in the Linux kernel that can run untrusted programs in a privileged context such as an operating system kernel. This document specifies the BPF instruction set architecture (ISA).

As a historical note, BPF originally stood for Berkeley Packet Filter, but now that it can do so much more than packet filtering, the acronym no longer makes sense. BPF is now considered a standalone term that does not stand for anything.  The original BPF is sometimes referred to as cBPF (classic BPF) to distinguish it from the now widely deployed eBPF (extended BPF).

<a id="rst-documentation-conventions"></a>

### 1.1   Documentation conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [https://www.rfc-editor.org/info/rfc2119](<https://www.rfc-editor.org/info/rfc2119>)<a id="rst-https-www-rfc-editor-org-info-rfc2119"></a> [https://www.rfc-editor.org/info/rfc8174](<https://www.rfc-editor.org/info/rfc8174>)<a id="rst-https-www-rfc-editor-org-info-rfc8174"></a> when, and only when, they appear in all capitals, as shown here.

For brevity and consistency, this document refers to families of types using a shorthand syntax and refers to several expository, mnemonic functions when describing the semantics of instructions. The range of valid values for those types and the semantics of those functions are defined in the following subsections.

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

#### 1.1.1   Types

This document refers to integer types with the notation `SN` to specify a type's signedness (`S`) and bit width (`N`), respectively.


<table>
<caption>

Meaning of signedness notation

</caption>
<thead>
<tr>
<th>



S

</th>
<th>



Meaning

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



u

</td>
<td>



unsigned

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



s

</td>
<td>



signed

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


<table>
<caption>

Meaning of bit-width notation

</caption>
<thead>
<tr>
<th>



N

</th>
<th>



Bit width

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



8

</td>
<td>



8 bits

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



16

</td>
<td>



16 bits

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



32

</td>
<td>



32 bits

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



64

</td>
<td>



64 bits

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



128

</td>
<td>



128 bits

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

For example, `u32` is a type whose valid values are all the 32-bit unsigned numbers and `s16` is a type whose valid values are all the 16-bit signed numbers.

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

#### 1.1.2   Functions

The following byteswap functions are direction-agnostic.  That is, the same function is used for conversion in either direction discussed below.

- be16: Takes an unsigned 16-bit number and converts it between host byte order and big-endian ([IEN137](<https://www.rfc-editor.org/ien/ien137.txt>)<a id="rst-ien137"></a>) byte order.

- be32: Takes an unsigned 32-bit number and converts it between host byte order and big-endian byte order.

- be64: Takes an unsigned 64-bit number and converts it between host byte order and big-endian byte order.

- bswap16: Takes an unsigned 16-bit number in either big- or little-endian format and returns the equivalent number with the same bit width but opposite endianness.

- bswap32: Takes an unsigned 32-bit number in either big- or little-endian format and returns the equivalent number with the same bit width but opposite endianness.

- bswap64: Takes an unsigned 64-bit number in either big- or little-endian format and returns the equivalent number with the same bit width but opposite endianness.

- le16: Takes an unsigned 16-bit number and converts it between host byte order and little-endian byte order.

- le32: Takes an unsigned 32-bit number and converts it between host byte order and little-endian byte order.

- le64: Takes an unsigned 64-bit number and converts it between host byte order and little-endian byte order.

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

#### 1.1.3   Definitions



- **<a id="rst-term-sign-extend"></a>Sign Extend**

  To `sign extend an` `X` `-bit number, A, to a` `Y` `-bit number, B  ,` means to

  1. Copy all `X` bits from `A` to the lower `X` bits of `B`.

  2. Set the value of the remaining `Y` - `X` bits of `B` to the value of the  most-significant bit of `A`.

> [!NOTE]
>
> **Example**
>
> Sign extend an 8-bit number `A` to a 16-bit number `B` on a big-endian platform:
>
>
>
> ```text
> A:          10000110
> B: 11111111 10000110
> ```

<a id="rst-conformance-groups"></a>

#### 1.1.4   Conformance groups

An implementation does not need to support all instructions specified in this document (e.g., deprecated instructions).  Instead, a number of conformance groups are specified.  An implementation MUST support the base32 conformance group and MAY support additional conformance groups, where supporting a conformance group means it MUST support all instructions in that conformance group.

The use of named conformance groups enables interoperability between a runtime that executes instructions, and tools such as compilers that generate instructions for the runtime.  Thus, capability discovery in terms of conformance groups might be done manually by users or automatically by tools.

Each conformance group has a short ASCII label (e.g., "base32") that corresponds to a set of instructions that are mandatory.  That is, each instruction has one or more conformance groups of which it is a member.

This document defines the following conformance groups:

- base32: includes all instructions defined in this specification unless otherwise noted.

- base64: includes base32, plus instructions explicitly noted as being in the base64 conformance group.

- atomic32: includes 32-bit atomic operation instructions (see [Atomic operations](<#rst-atomic-operations>)).

- atomic64: includes atomic32, plus 64-bit atomic operation instructions.

- divmul32: includes 32-bit division, multiplication, and modulo instructions.

- divmul64: includes divmul32, plus 64-bit division, multiplication, and modulo instructions.

- packet: deprecated packet access instructions.

<a id="rst-instruction-encoding"></a>

### 1.2   Instruction encoding

BPF has two instruction encodings:

- the basic instruction encoding, which uses 64 bits to encode an instruction

- the wide instruction encoding, which appends a second 64 bits after the basic instruction for a total of 128 bits.

<a id="rst-basic-instruction-encoding"></a>

#### 1.2.1   Basic instruction encoding

A basic instruction is encoded as follows:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|    opcode     |     regs      |            offset             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                              imm                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

- **<strong>opcode</strong>**

  operation to perform, encoded as follows:



  ```text
  +-+-+-+-+-+-+-+-+
  |specific |class|
  +-+-+-+-+-+-+-+-+
  ```

  - **<strong>specific</strong>**

    The format of these bits varies by instruction class

  - **<strong>class</strong>**

    The instruction class (see [Instruction classes](<#rst-instruction-classes>))

- **<strong>regs</strong>**

  The source and destination register numbers, encoded as follows on a little-endian host:



  ```text
  +-+-+-+-+-+-+-+-+
  |src_reg|dst_reg|
  +-+-+-+-+-+-+-+-+
  ```

  and as follows on a big-endian host:



  ```text
  +-+-+-+-+-+-+-+-+
  |dst_reg|src_reg|
  +-+-+-+-+-+-+-+-+
  ```

  - **<strong>src\_reg</strong>**

    the source register number (0-10), except where otherwise specified ([64-bit immediate instructions](<#rst-bit-immediate-instructions>) reuse this field for other purposes)

  - **<strong>dst\_reg</strong>**

    destination register number (0-10), unless otherwise specified (future instructions might reuse this field for other purposes)

- **<strong>offset</strong>**

  signed integer offset used with pointer arithmetic, except where otherwise specified (some arithmetic instructions reuse this field for other purposes)

- **<strong>imm</strong>**

  signed integer immediate value

Note that the contents of multi-byte fields ('offset' and 'imm') are stored using big-endian byte ordering on big-endian hosts and little-endian byte ordering on little-endian hosts.

For example:



```text
opcode                  offset imm          assembly
       src_reg dst_reg
07     0       1        00 00  44 33 22 11  r1 += 0x11223344 // little
       dst_reg src_reg
07     1       0        00 00  11 22 33 44  r1 += 0x11223344 // big
```

Note that most instructions do not use all of the fields. Unused fields SHALL be cleared to zero.

<a id="rst-wide-instruction-encoding"></a>

#### 1.2.2   Wide instruction encoding

Some instructions are defined to use the wide instruction encoding, which uses two 32-bit immediate values.  The 64 bits following the basic instruction format contain a pseudo instruction with 'opcode', 'dst\_reg', 'src\_reg', and 'offset' all set to zero.

This is depicted in the following figure:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|    opcode     |     regs      |            offset             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                              imm                              |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           reserved                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           next_imm                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

- **<strong>opcode</strong>**

  operation to perform, encoded as explained above

- **<strong>regs</strong>**

  The source and destination register numbers (unless otherwise specified), encoded as explained above

- **<strong>offset</strong>**

  signed integer offset used with pointer arithmetic, unless otherwise specified

- **<strong>imm</strong>**

  signed integer immediate value

- **<strong>reserved</strong>**

  unused, set to zero

- **<strong>next\_imm</strong>**

  second signed integer immediate value

<a id="rst-instruction-classes"></a>

#### 1.2.3   Instruction classes

The three least significant bits of the 'opcode' field store the instruction class:


<table>
<caption>

Instruction class

</caption>
<thead>
<tr>
<th>



class

</th>
<th>



value

</th>
<th>



description

</th>
<th>



reference

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



LD

</td>
<td>



0x0

</td>
<td>



non-standard load operations

</td>
<td>



[Load and store instructions](<#rst-load-and-store-instructions>)

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



LDX

</td>
<td>



0x1

</td>
<td>



load into register operations

</td>
<td>



[Load and store instructions](<#rst-load-and-store-instructions>)

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



ST

</td>
<td>



0x2

</td>
<td>



store from immediate operations

</td>
<td>



[Load and store instructions](<#rst-load-and-store-instructions>)

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



STX

</td>
<td>



0x3

</td>
<td>



store from register operations

</td>
<td>



[Load and store instructions](<#rst-load-and-store-instructions>)

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



ALU

</td>
<td>



0x4

</td>
<td>



32-bit arithmetic operations

</td>
<td>



[Arithmetic and jump instructions](<#rst-arithmetic-and-jump-instructions>)

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



JMP

</td>
<td>



0x5

</td>
<td>



64-bit jump operations

</td>
<td>



[Arithmetic and jump instructions](<#rst-arithmetic-and-jump-instructions>)

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



JMP32

</td>
<td>



0x6

</td>
<td>



32-bit jump operations

</td>
<td>



[Arithmetic and jump instructions](<#rst-arithmetic-and-jump-instructions>)

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



ALU64

</td>
<td>



0x7

</td>
<td>



64-bit arithmetic operations

</td>
<td>



[Arithmetic and jump instructions](<#rst-arithmetic-and-jump-instructions>)

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

<a id="rst-arithmetic-and-jump-instructions"></a>

### 1.3   Arithmetic and jump instructions

For arithmetic and jump instructions (`ALU`, `ALU64`, `JMP` and `JMP32`), the 8-bit 'opcode' field is divided into three parts:



```text
+-+-+-+-+-+-+-+-+
|  code |s|class|
+-+-+-+-+-+-+-+-+
```

- **<strong>code</strong>**

  the operation code, whose meaning varies by instruction class

- **<strong>s (source)</strong>**

  the source operand location, which unless otherwise specified is one of:


  <table>
  <caption>

  Source operand location

  </caption>
  <thead>
  <tr>
  <th>



  source

  </th>
  <th>



  value

  </th>
  <th>



  description

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



  K

  </td>
  <td>



  0

  </td>
  <td>



  use 32-bit 'imm' value as source operand

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



  X

  </td>
  <td>



  1

  </td>
  <td>



  use 'src\_reg' register value as source operand

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

- **<strong>instruction class</strong>**

  the instruction class (see [Instruction classes](<#rst-instruction-classes>))

<a id="rst-arithmetic-instructions"></a>

#### 1.3.1   Arithmetic instructions

`ALU` uses 32-bit wide operands while `ALU64` uses 64-bit wide operands for otherwise identical operations. `ALU64` instructions belong to the base64 conformance group unless noted otherwise. The 'code' field encodes the operation as below, where 'src' refers to the the source operand and 'dst' refers to the value of the destination register.


<table>
<caption>

Arithmetic instructions

</caption>
<thead>
<tr>
<th>



name

</th>
<th>



code

</th>
<th>



offset

</th>
<th>



description

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



ADD

</td>
<td>



0x0

</td>
<td>



0

</td>
<td>



dst += src

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



SUB

</td>
<td>



0x1

</td>
<td>



0

</td>
<td>



dst -= src

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



MUL

</td>
<td>



0x2

</td>
<td>



0

</td>
<td>



dst \*= src

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



DIV

</td>
<td>



0x3

</td>
<td>



0

</td>
<td>



dst = (src \!= 0) ? (dst / src) : 0

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



SDIV

</td>
<td>



0x3

</td>
<td>



1

</td>
<td>



dst = (src == 0) ? 0 : ((src == -1 &amp;&amp; dst == LLONG\_MIN) ? LLONG\_MIN : (dst s/ src))

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



OR

</td>
<td>



0x4

</td>
<td>



0

</td>
<td>



dst \|= src

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



AND

</td>
<td>



0x5

</td>
<td>



0

</td>
<td>



dst &amp;= src

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



LSH

</td>
<td>



0x6

</td>
<td>



0

</td>
<td>



dst &lt;&lt;= (src &amp; mask)

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



RSH

</td>
<td>



0x7

</td>
<td>



0

</td>
<td>



dst &gt;&gt;= (src &amp; mask)

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



NEG

</td>
<td>



0x8

</td>
<td>



0

</td>
<td>



dst = -dst

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



MOD

</td>
<td>



0x9

</td>
<td>



0

</td>
<td>



dst = (src \!= 0) ? (dst % src) : dst

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



SMOD

</td>
<td>



0x9

</td>
<td>



1

</td>
<td>



dst = (src == 0) ? dst : ((src == -1 &amp;&amp; dst == LLONG\_MIN) ? 0: (dst s% src))

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



XOR

</td>
<td>



0xa

</td>
<td>



0

</td>
<td>



dst ^= src

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



MOV

</td>
<td>



0xb

</td>
<td>



0

</td>
<td>



dst = src

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



MOVSX

</td>
<td>



0xb

</td>
<td>



8/16/32

</td>
<td>



dst = (s8,s16,s32)src

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



ARSH

</td>
<td>



0xc

</td>
<td>



0

</td>
<td>



[sign extending](<#rst-term-sign-extend>) dst &gt;&gt;= (src &amp; mask)

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



END

</td>
<td>



0xd

</td>
<td>



0

</td>
<td>



byte swap operations (see [Byte swap instructions](<#rst-byte-swap-instructions>) below)

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

Underflow and overflow are allowed during arithmetic operations, meaning the 64-bit or 32-bit value will wrap. If BPF program execution would result in division by zero, the destination register is instead set to zero. Otherwise, for `ALU64`, if execution would result in `LLONG_MIN` divided by -1, the destination register is instead set to `LLONG_MIN`. For `ALU`, if execution would result in `INT_MIN` divided by -1, the destination register is instead set to `INT_MIN`.

If execution would result in modulo by zero, for `ALU64` the value of the destination register is unchanged whereas for `ALU` the upper 32 bits of the destination register are zeroed. Otherwise, for `ALU64`, if execution would resuslt in `LLONG_MIN` modulo -1, the destination register is instead set to 0. For `ALU`, if execution would result in `INT_MIN` modulo -1, the destination register is instead set to 0.

`{ADD, X, ALU}`, where 'code' = `ADD`, 'source' = `X`, and 'class' = `ALU`, means:



```text
dst = (u32) ((u32) dst + (u32) src)
```

where '(u32)' indicates that the upper 32 bits are zeroed.

`{ADD, X, ALU64}` means:



```text
dst = dst + src
```

`{XOR, K, ALU}` means:



```text
dst = (u32) dst ^ (u32) imm
```

`{XOR, K, ALU64}` means:



```text
dst = dst ^ imm
```

Note that most arithmetic instructions have 'offset' set to 0. Only three instructions (`SDIV`, `SMOD`, `MOVSX`) have a non-zero 'offset'.

Division, multiplication, and modulo operations for `ALU` are part of the "divmul32" conformance group, and division, multiplication, and modulo operations for `ALU64` are part of the "divmul64" conformance group. The division and modulo operations support both unsigned and signed flavors.

For unsigned operations (`DIV` and `MOD`), for `ALU`, 'imm' is interpreted as a 32-bit unsigned value. For `ALU64`, 'imm' is first [sign extended](<#rst-term-sign-extend>) from 32 to 64 bits, and then interpreted as a 64-bit unsigned value.

For signed operations (`SDIV` and `SMOD`), for `ALU`, 'imm' is interpreted as a 32-bit signed value. For `ALU64`, 'imm' is first [sign extended](<#rst-term-sign-extend>) from 32 to 64 bits, and then interpreted as a 64-bit signed value.

Note that there are varying definitions of the signed modulo operation when the dividend or divisor are negative, where implementations often vary by language such that Python, Ruby, etc.  differ from C, Go, Java, etc. This specification requires that signed modulo MUST use truncated division (where -13 % 3 == -1) as implemented in C, Go, etc.:



```text
a % n = a - n * trunc(a / n)
```

The `MOVSX` instruction does a move operation with sign extension. `{MOVSX, X, ALU}` [sign extends](<#rst-term-sign-extend>) 8-bit and 16-bit operands into 32-bit operands, and zeroes the remaining upper 32 bits. `{MOVSX, X, ALU64}` [sign extends](<#rst-term-sign-extend>) 8-bit, 16-bit, and 32-bit operands into 64-bit operands.  Unlike other arithmetic instructions, `MOVSX` is only defined for register source operands (`X`).

`{MOV, K, ALU64}` means:



```text
dst = (s64)imm
```

`{MOV, X, ALU}` means:



```text
dst = (u32)src
```

`{MOVSX, X, ALU}` with 'offset' 8 means:



```text
dst = (u32)(s32)(s8)src
```

The `NEG` instruction is only defined when the source bit is clear (`K`).

Shift operations use a mask of 0x3F (63) for 64-bit operations and 0x1F (31) for 32-bit operations.

<a id="rst-byte-swap-instructions"></a>

#### 1.3.2   Byte swap instructions

The byte swap instructions use instruction classes of `ALU` and `ALU64` and a 4-bit 'code' field of `END`.

The byte swap instructions operate on the destination register only and do not use a separate source register or immediate value.

For `ALU`, the 1-bit source operand field in the opcode is used to select what byte order the operation converts from or to. For `ALU64`, the 1-bit source operand field in the opcode is reserved and MUST be set to 0.


<table>
<caption>

Byte swap instructions

</caption>
<thead>
<tr>
<th>



class

</th>
<th>



source

</th>
<th>



value

</th>
<th>



description

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



ALU

</td>
<td>



LE

</td>
<td>



0

</td>
<td>



convert between host byte order and little endian

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



ALU

</td>
<td>



BE

</td>
<td>



1

</td>
<td>



convert between host byte order and big endian

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



ALU64

</td>
<td>



Reserved

</td>
<td>



0

</td>
<td>



do byte swap unconditionally

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

The 'imm' field encodes the width of the swap operations.  The following widths are supported: 16, 32 and 64.  Width 64 operations belong to the base64 conformance group and other swap operations belong to the base32 conformance group.

Examples:

`{END, LE, ALU}` with 'imm' = 16/32/64 means:



```text
dst = le16(dst)
dst = le32(dst)
dst = le64(dst)
```

`{END, BE, ALU}` with 'imm' = 16/32/64 means:



```text
dst = be16(dst)
dst = be32(dst)
dst = be64(dst)
```

`{END, TO, ALU64}` with 'imm' = 16/32/64 means:



```text
dst = bswap16(dst)
dst = bswap32(dst)
dst = bswap64(dst)
```

<a id="rst-jump-instructions"></a>

#### 1.3.3   Jump instructions

`JMP32` uses 32-bit wide operands and indicates the base32 conformance group, while `JMP` uses 64-bit wide operands for otherwise identical operations, and indicates the base64 conformance group unless otherwise specified. The 'code' field encodes the operation as below:


<table>
<caption>

Jump instructions

</caption>
<thead>
<tr>
<th>



code

</th>
<th>



value

</th>
<th>



src\_reg

</th>
<th>



description

</th>
<th>



notes

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



JA

</td>
<td>



0x0

</td>
<td>



0x0

</td>
<td>



PC += offset

</td>
<td>



\{JA, K, JMP\} only

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



JA

</td>
<td>



0x0

</td>
<td>



0x0

</td>
<td>



PC += imm

</td>
<td>



\{JA, K, JMP32\} only

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



JEQ

</td>
<td>



0x1

</td>
<td>



any

</td>
<td>



PC += offset if dst == src

</td>
<td>





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



JGT

</td>
<td>



0x2

</td>
<td>



any

</td>
<td>



PC += offset if dst &gt; src

</td>
<td>



unsigned

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



JGE

</td>
<td>



0x3

</td>
<td>



any

</td>
<td>



PC += offset if dst &gt;= src

</td>
<td>



unsigned

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



JSET

</td>
<td>



0x4

</td>
<td>



any

</td>
<td>



PC += offset if dst &amp; src

</td>
<td>





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



JNE

</td>
<td>



0x5

</td>
<td>



any

</td>
<td>



PC += offset if dst \!= src

</td>
<td>





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



JSGT

</td>
<td>



0x6

</td>
<td>



any

</td>
<td>



PC += offset if dst &gt; src

</td>
<td>



signed

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



JSGE

</td>
<td>



0x7

</td>
<td>



any

</td>
<td>



PC += offset if dst &gt;= src

</td>
<td>



signed

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



CALL

</td>
<td>



0x8

</td>
<td>



0x0

</td>
<td>



call helper function by static ID

</td>
<td>



\{CALL, K, JMP\} only, see [Helper functions](<#rst-helper-functions>)

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



CALL

</td>
<td>



0x8

</td>
<td>



0x1

</td>
<td>



call PC += imm

</td>
<td>



\{CALL, K, JMP\} only, see [Program-local functions](<#rst-program-local-functions>)

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



CALL

</td>
<td>



0x8

</td>
<td>



0x2

</td>
<td>



call helper function by BTF ID

</td>
<td>



\{CALL, K, JMP\} only, see [Helper functions](<#rst-helper-functions>)

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



EXIT

</td>
<td>



0x9

</td>
<td>



0x0

</td>
<td>



return

</td>
<td>



\{CALL, K, JMP\} only

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



JLT

</td>
<td>



0xa

</td>
<td>



any

</td>
<td>



PC += offset if dst &lt; src

</td>
<td>



unsigned

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



JLE

</td>
<td>



0xb

</td>
<td>



any

</td>
<td>



PC += offset if dst &lt;= src

</td>
<td>



unsigned

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



JSLT

</td>
<td>



0xc

</td>
<td>



any

</td>
<td>



PC += offset if dst &lt; src

</td>
<td>



signed

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



JSLE

</td>
<td>



0xd

</td>
<td>



any

</td>
<td>



PC += offset if dst &lt;= src

</td>
<td>



signed

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

where 'PC' denotes the program counter, and the offset to increment by is in units of 64-bit instructions relative to the instruction following the jump instruction.  Thus 'PC += 1' skips execution of the next instruction if it's a basic instruction or results in undefined behavior if the next instruction is a 128-bit wide instruction.

Example:

`{JSGE, X, JMP32}` means:



```text
if (s32)dst s>= (s32)src goto +offset
```

where 's&gt;=' indicates a signed '&gt;=' comparison.

`{JLE, K, JMP}` means:



```text
if dst <= (u64)(s64)imm goto +offset
```

`{JA, K, JMP32}` means:



```text
gotol +imm
```

where 'imm' means the branch offset comes from the 'imm' field.

Note that there are two flavors of `JA` instructions. The `JMP` class permits a 16-bit jump offset specified by the 'offset' field, whereas the `JMP32` class permits a 32-bit jump offset specified by the 'imm' field. A &gt; 16-bit conditional jump may be converted to a &lt; 16-bit conditional jump plus a 32-bit unconditional jump.

All `CALL` and `JA` instructions belong to the base32 conformance group.

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

##### 1.3.3.1   Helper functions

Helper functions are a concept whereby BPF programs can call into a set of function calls exposed by the underlying platform.

Historically, each helper function was identified by a static ID encoded in the 'imm' field.  Further documentation of helper functions is outside the scope of this document and standardization is left for future work, but use is widely deployed and more information can be found in platform-specific documentation (e.g., Linux kernel documentation).

Platforms that support the BPF Type Format (BTF) support identifying a helper function by a BTF ID encoded in the 'imm' field, where the BTF ID identifies the helper name and type.  Further documentation of BTF is outside the scope of this document and standardization is left for future work, but use is widely deployed and more information can be found in platform-specific documentation (e.g., Linux kernel documentation).

<a id="rst-program-local-functions"></a>

##### 1.3.3.2   Program-local functions

Program-local functions are functions exposed by the same BPF program as the caller, and are referenced by offset from the instruction following the call instruction, similar to `JA`.  The offset is encoded in the 'imm' field of the call instruction. An `EXIT` within the program-local function will return to the caller.

<a id="rst-load-and-store-instructions"></a>

### 1.4   Load and store instructions

For load and store instructions (`LD`, `LDX`, `ST`, and `STX`), the 8-bit 'opcode' field is divided as follows:



```text
+-+-+-+-+-+-+-+-+
|mode |sz |class|
+-+-+-+-+-+-+-+-+
```

- **<strong>mode</strong>**

  The mode modifier is one of:


  <table>
  <caption>

  Mode modifier

  </caption>
  <thead>
  <tr>
  <th>



  mode modifier

  </th>
  <th>



  value

  </th>
  <th>



  description

  </th>
  <th>



  reference

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



  IMM

  </td>
  <td>



  0

  </td>
  <td>



  64-bit immediate instructions

  </td>
  <td>



  [64-bit immediate instructions](<#rst-bit-immediate-instructions>)

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



  ABS

  </td>
  <td>



  1

  </td>
  <td>



  legacy BPF packet access (absolute)

  </td>
  <td>



  [Legacy BPF Packet access instructions](<#rst-legacy-bpf-packet-access-instructions>)

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



  IND

  </td>
  <td>



  2

  </td>
  <td>



  legacy BPF packet access (indirect)

  </td>
  <td>



  [Legacy BPF Packet access instructions](<#rst-legacy-bpf-packet-access-instructions>)

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



  MEM

  </td>
  <td>



  3

  </td>
  <td>



  regular load and store operations

  </td>
  <td>



  [Regular load and store operations](<#rst-regular-load-and-store-operations>)

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



  MEMSX

  </td>
  <td>



  4

  </td>
  <td>



  sign-extension load operations

  </td>
  <td>



  [Sign-extension load operations](<#rst-sign-extension-load-operations>)

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



  ATOMIC

  </td>
  <td>



  6

  </td>
  <td>



  atomic operations

  </td>
  <td>



  [Atomic operations](<#rst-atomic-operations>)

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

- **<strong>sz (size)</strong>**

  The size modifier is one of:


  <table>
  <caption>

  Size modifier

  </caption>
  <thead>
  <tr>
  <th>



  size

  </th>
  <th>



  value

  </th>
  <th>



  description

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



  W

  </td>
  <td>



  0

  </td>
  <td>



  word        (4 bytes)

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



  H

  </td>
  <td>



  1

  </td>
  <td>



  half word   (2 bytes)

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



  B

  </td>
  <td>



  2

  </td>
  <td>



  byte

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



  DW

  </td>
  <td>



  3

  </td>
  <td>



  double word (8 bytes)

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

  Instructions using `DW` belong to the base64 conformance group.

- **<strong>class</strong>**

  The instruction class (see [Instruction classes](<#rst-instruction-classes>))

<a id="rst-regular-load-and-store-operations"></a>

#### 1.4.1   Regular load and store operations

The `MEM` mode modifier is used to encode regular load and store instructions that transfer data between a register and memory.

`{MEM, <size>, STX}` means:



```text
*(size *) (dst + offset) = src
```

`{MEM, <size>, ST}` means:



```text
*(size *) (dst + offset) = imm
```

`{MEM, <size>, LDX}` means:



```text
dst = *(unsigned size *) (src + offset)
```

Where '&lt;size&gt;' is one of: `B`, `H`, `W`, or `DW`, and 'unsigned size' is one of: u8, u16, u32, or u64.

<a id="rst-sign-extension-load-operations"></a>

#### 1.4.2   Sign-extension load operations

The `MEMSX` mode modifier is used to encode [sign-extension](<#rst-term-sign-extend>) load instructions that transfer data between a register and memory.

`{MEMSX, <size>, LDX}` means:



```text
dst = *(signed size *) (src + offset)
```

Where '&lt;size&gt;' is one of: `B`, `H`, or `W`, and 'signed size' is one of: s8, s16, or s32.

<a id="rst-atomic-operations"></a>

#### 1.4.3   Atomic operations

Atomic operations are operations that operate on memory and can not be interrupted or corrupted by other access to the same memory region by other BPF programs or means outside of this specification.

All atomic operations supported by BPF are encoded as store operations that use the `ATOMIC` mode modifier as follows:

- `{ATOMIC, W, STX}` for 32-bit operations, which are part of the "atomic32" conformance group.

- `{ATOMIC, DW, STX}` for 64-bit operations, which are part of the "atomic64" conformance group.

- 8-bit and 16-bit wide atomic operations are not supported.

The 'imm' field is used to encode the actual atomic operation. Simple atomic operation use a subset of the values defined to encode arithmetic operations in the 'imm' field to encode the atomic operation:


<table>
<caption>

Simple atomic operations

</caption>
<thead>
<tr>
<th>



imm

</th>
<th>



value

</th>
<th>



description

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



ADD

</td>
<td>



0x00

</td>
<td>



atomic add

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



OR

</td>
<td>



0x40

</td>
<td>



atomic or

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



AND

</td>
<td>



0x50

</td>
<td>



atomic and

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



XOR

</td>
<td>



0xa0

</td>
<td>



atomic xor

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

`{ATOMIC, W, STX}` with 'imm' = ADD means:



```text
*(u32 *)(dst + offset) += src
```

`{ATOMIC, DW, STX}` with 'imm' = ADD means:



```text
*(u64 *)(dst + offset) += src
```

In addition to the simple atomic operations, there also is a modifier and two complex atomic operations:


<table>
<caption>

Complex atomic operations

</caption>
<thead>
<tr>
<th>



imm

</th>
<th>



value

</th>
<th>



description

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



FETCH

</td>
<td>



0x01

</td>
<td>



modifier: return old value

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



XCHG

</td>
<td>



0xe0 \| FETCH

</td>
<td>



atomic exchange

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



CMPXCHG

</td>
<td>



0xf0 \| FETCH

</td>
<td>



atomic compare and exchange

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

The `FETCH` modifier is optional for simple atomic operations, and always set for the complex atomic operations.  If the `FETCH` flag is set, then the operation also overwrites `src` with the value that was in memory before it was modified.

The `XCHG` operation atomically exchanges `src` with the value addressed by `dst + offset`.

The `CMPXCHG` operation atomically compares the value addressed by `dst + offset` with `R0`. If they match, the value addressed by `dst + offset` is replaced with `src`. In either case, the value that was at `dst + offset` before the operation is zero-extended and loaded back to `R0`.

<a id="rst-bit-immediate-instructions"></a>

#### 1.4.4   64-bit immediate instructions

Instructions with the `IMM` 'mode' modifier use the wide instruction encoding defined in [Instruction encoding](<#rst-instruction-encoding>), and use the 'src\_reg' field of the basic instruction to hold an opcode subtype.

The following table defines a set of `{IMM, DW, LD}` instructions with opcode subtypes in the 'src\_reg' field, using new terms such as "map" defined further below:


<table>
<caption>

64-bit immediate instructions

</caption>
<thead>
<tr>
<th>



src\_reg

</th>
<th>



pseudocode

</th>
<th>



imm type

</th>
<th>



dst type

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



0x0

</td>
<td>



dst = (next\_imm &lt;&lt; 32) \| imm

</td>
<td>



integer

</td>
<td>



integer

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



0x1

</td>
<td>



dst = map\_by\_fd(imm)

</td>
<td>



map fd

</td>
<td>



map

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



0x2

</td>
<td>



dst = map\_val(map\_by\_fd(imm)) + next\_imm

</td>
<td>



map fd

</td>
<td>



data address

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



0x3

</td>
<td>



dst = var\_addr(imm)

</td>
<td>



variable id

</td>
<td>



data address

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



0x4

</td>
<td>



dst = code\_addr(imm)

</td>
<td>



integer

</td>
<td>



code address

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



0x5

</td>
<td>



dst = map\_by\_idx(imm)

</td>
<td>



map index

</td>
<td>



map

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



0x6

</td>
<td>



dst = map\_val(map\_by\_idx(imm)) + next\_imm

</td>
<td>



map index

</td>
<td>



data address

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

where

- map\_by\_fd(imm) means to convert a 32-bit file descriptor into an address of a map (see [Maps](<#rst-maps>))

- map\_by\_idx(imm) means to convert a 32-bit index into an address of a map

- map\_val(map) gets the address of the first value in a given map

- var\_addr(imm) gets the address of a platform variable (see [Platform Variables](<#rst-platform-variables>)) with a given id

- code\_addr(imm) gets the address of the instruction at a specified relative offset in number of (64-bit) instructions

- the 'imm type' can be used by disassemblers for display

- the 'dst type' can be used for verification and JIT compilation purposes

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

##### 1.4.4.1   Maps

Maps are shared memory regions accessible by BPF programs on some platforms. A map can have various semantics as defined in a separate document, and may or may not have a single contiguous memory region, but the 'map\_val(map)' is currently only defined for maps that do have a single contiguous memory region.

Each map can have a file descriptor (fd) if supported by the platform, where 'map\_by\_fd(imm)' means to get the map with the specified file descriptor. Each BPF program can also be defined to use a set of maps associated with the program at load time, and 'map\_by\_idx(imm)' means to get the map with the given index in the set associated with the BPF program containing the instruction.

<a id="rst-platform-variables"></a>

##### 1.4.4.2   Platform Variables

Platform variables are memory regions, identified by integer ids, exposed by the runtime and accessible by BPF programs on some platforms.  The 'var\_addr(imm)' operation means to get the address of the memory region identified by the given id.

<a id="rst-legacy-bpf-packet-access-instructions"></a>

#### 1.4.5   Legacy BPF Packet access instructions

BPF previously introduced special instructions for access to packet data that were carried over from classic BPF. These instructions used an instruction class of `LD`, a size modifier of `W`, `H`, or `B`, and a mode modifier of `ABS` or `IND`.  The 'dst\_reg' and 'offset' fields were set to zero, and 'src\_reg' was set to zero for `ABS`.  However, these instructions are deprecated and SHOULD no longer be used.  All legacy packet access instructions belong to the "packet" conformance group.

---

# Core API Documentation

_Peios Kernel / Internals / Core APIs_

> This is the beginning of a manual for core kernel APIs. The conversion (and writing!) of documents for this manual is much appreciated!

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

This is the beginning of a manual for core kernel APIs.  The conversion (and writing\!) of documents for this manual is much appreciated\!

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

## Core utilities

This section has general and "core core" documentation.  The first is a massive grab-bag of kerneldoc info left over from the docbook days; it should really be broken up someday when somebody finds the energy to do it.

- [The Linux Kernel API](</kernel/internals/core-api/kernel-api.md>)
- [Workqueue](</kernel/internals/core-api/workqueue.md>)
- [General notification mechanism](</kernel/internals/core-api/watch-queue.md>)
- [Message logging with printk](</kernel/internals/core-api/printk-basics.md>)
- [How to get printk format specifiers right](</kernel/internals/core-api/printk-formats.md>)
- [Printk Index](</kernel/internals/core-api/printk-index.md>)
- [Symbol Namespaces](</kernel/internals/core-api/symbol-namespaces.md>)
- [Assembler Annotations](</kernel/internals/core-api/asm-annotations.md>)
- [Real-time preemption](</kernel/internals/core-api/real-time/index.md>)
- [Housekeeping](</kernel/internals/core-api/housekeeping.md>)

<a id="rst-data-structures-and-low-level-utilities"></a>

## Data structures and low-level utilities

Library functionality that is used throughout the kernel.

- [Everything you never wanted to know about kobjects, ksets, and ktypes](</kernel/internals/core-api/kobject.md>)
- [Adding reference counters (krefs) to kernel objects](</kernel/internals/core-api/kref.md>)
- [Scope-based Cleanup Helpers](</kernel/internals/core-api/cleanup.md>)
- [Generic Associative Array Implementation](</kernel/internals/core-api/assoc-array.md>)
- [Folio Queue](</kernel/internals/core-api/folio-queue.md>)
- [XArray](</kernel/internals/core-api/xarray.md>)
- [Maple Tree](</kernel/internals/core-api/maple-tree.md>)
- [ID Allocation](</kernel/internals/core-api/idr.md>)
- [Circular Buffers](</kernel/internals/core-api/circular-buffers.md>)
- [Red-black Trees (rbtree) in Linux](</kernel/internals/core-api/rbtree.md>)
- [Generic radix trees/sparse arrays](</kernel/internals/core-api/generic-radix-tree.md>)
- [Generic bitfield packing and unpacking functions](</kernel/internals/core-api/packing.md>)
- [this_cpu operations](</kernel/internals/core-api/this-cpu-ops.md>)
- [ktime accessors](</kernel/internals/core-api/timekeeping.md>)
- [The errseq_t datatype](</kernel/internals/core-api/errseq.md>)
- [atomic_t](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/core-api/wrappers/atomic_t.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [atomic_bitops](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/core-api/wrappers/atomic_bitops.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Floating-point API](</kernel/internals/core-api/floating-point.md>)
- [Union-Find in Linux](</kernel/internals/core-api/union-find.md>)
- [Min Heap API](</kernel/internals/core-api/min-heap.md>)
- [Generic parser](</kernel/internals/core-api/parser.md>)
- [Linked Lists in Linux](</kernel/internals/core-api/list.md>)

<a id="rst-low-level-entry-and-exit"></a>

## Low level entry and exit

- [Entry/exit handling for exceptions, interrupts, syscalls and KVM](</kernel/internals/core-api/entry.md>)

<a id="rst-concurrency-primitives"></a>

## Concurrency primitives

How Linux keeps everything from happening at the same time.  See [Documentation/locking/index.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/locking/index.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for more related documentation.

- [refcount_t API compared to atomic_t](</kernel/internals/core-api/refcount-vs-atomic.md>)
- [IRQs](</kernel/internals/core-api/irq/index.md>)
- [Semantics and Behavior of Local Atomic Operations](</kernel/internals/core-api/local-ops.md>)
- [The padata parallel execution mechanism](</kernel/internals/core-api/padata.md>)
- [RCU Handbook](</kernel/internals/rcu/index.md>)
- [memory-barriers](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/core-api/wrappers/memory-barriers.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

<a id="rst-low-level-hardware-management"></a>

## Low-level hardware management

Cache management, managing CPU hotplug, etc.

- [Cache and TLB Flushing Under Linux](</kernel/internals/core-api/cachetlb.md>)
- [CPU hotplug in the Kernel](</kernel/internals/core-api/cpu-hotplug.md>)
- [Memory hotplug](</kernel/internals/core-api/memory-hotplug.md>)
- [Linux generic IRQ handling](</kernel/internals/core-api/genericirq.md>)
- [Memory Protection Keys](</kernel/internals/core-api/protection-keys.md>)

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

## Memory management

How to allocate and use memory in the kernel.  Note that there is a lot more memory-management documentation in [Documentation/mm/index.rst](/kernel/internals/mm/index.md).

- [Memory Allocation Guide](</kernel/internals/core-api/memory-allocation.md>)
- [Unaligned Memory Accesses](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/core-api/unaligned-memory-access.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Dynamic DMA mapping using the generic device](</kernel/internals/core-api/dma-api.md>)
- [Dynamic DMA mapping Guide](</kernel/internals/core-api/dma-api-howto.md>)
- [DMA attributes](</kernel/internals/core-api/dma-attributes.md>)
- [DMA with ISA and LPC devices](</kernel/internals/core-api/dma-isa-lpc.md>)
- [DMA and swiotlb](</kernel/internals/core-api/swiotlb.md>)
- [Memory Management APIs](</kernel/internals/core-api/mm-api.md>)
- [Cgroup Kernel APIs](</kernel/internals/core-api/cgroup.md>)
- [The genalloc/genpool subsystem](</kernel/internals/core-api/genalloc.md>)
- [pin_user_pages() and related calls](</kernel/internals/core-api/pin-user-pages.md>)
- [Boot time memory management](</kernel/internals/core-api/boot-time-mm.md>)
- [GFP masks used from FS/IO context](</kernel/internals/core-api/gfp-mask-from-fs-io.md>)
- [Kexec Handover Subsystem](</kernel/internals/core-api/kho/index.md>)

<a id="rst-interfaces-for-kernel-debugging"></a>

## Interfaces for kernel debugging

- [The object-lifetime debugging infrastructure](</kernel/internals/core-api/debug-objects.md>)
- [The Linux Kernel Tracepoint API](</kernel/internals/core-api/tracepoint.md>)
- [Using physical DMA provided by OHCI-1394 FireWire controllers for debugging](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/core-api/debugging-via-ohci1394.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

<a id="rst-everything-else"></a>

## Everything else

Documents that don't fit elsewhere or which have yet to be categorized.

- [Reed-Solomon Library Programming Interface](</kernel/internals/core-api/librs.md>)
- [Live Update Orchestrator](</kernel/internals/core-api/liveupdate.md>)
- [Netlink notes for kernel developers](</kernel/internals/core-api/netlink.md>)

---

# Assembler Annotations

_Peios Kernel / Internals / Core APIs_

> Copyright (c) 2017-2019 Jiri Slaby

<a id="rst-assembler-annotations"></a>

Copyright (c) 2017-2019 Jiri Slaby

This document describes the new macros for annotation of data and code in assembly. In particular, it contains information about `SYM_FUNC_START`, `SYM_FUNC_END`, `SYM_CODE_START`, and similar.

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

## Rationale

Some code like entries, trampolines, or boot code needs to be written in assembly. The same as in C, such code is grouped into functions and accompanied with data. Standard assemblers do not force users into precisely marking these pieces as code, data, or even specifying their length. Nevertheless, assemblers provide developers with such annotations to aid debuggers throughout assembly. On top of that, developers also want to mark some functions as *global* in order to be visible outside of their translation units.

Over time, the Linux kernel has adopted macros from various projects (like `binutils`) to facilitate such annotations. So for historic reasons, developers have been using `ENTRY`, `END`, `ENDPROC`, and other annotations in assembly.  Due to the lack of their documentation, the macros are used in rather wrong contexts at some locations. Clearly, `ENTRY` was intended to denote the beginning of global symbols (be it data or code). `END` used to mark the end of data or end of special functions with *non-standard* calling convention. In contrast, `ENDPROC` should annotate only ends of *standard* functions.

When these macros are used correctly, they help assemblers generate a nice object with both sizes and types set correctly. For example, the result of `arch/x86/lib/putuser.S`:



```text
Num:    Value          Size Type    Bind   Vis      Ndx Name
 25: 0000000000000000    33 FUNC    GLOBAL DEFAULT    1 __put_user_1
 29: 0000000000000030    37 FUNC    GLOBAL DEFAULT    1 __put_user_2
 32: 0000000000000060    36 FUNC    GLOBAL DEFAULT    1 __put_user_4
 35: 0000000000000090    37 FUNC    GLOBAL DEFAULT    1 __put_user_8
```

This is not only important for debugging purposes. When there are properly annotated objects like this, tools can be run on them to generate more useful information. In particular, on properly annotated objects, `objtool` can be run to check and fix the object if needed. Currently, `objtool` can report missing frame pointer setup/destruction in functions. It can also automatically generate annotations for the ORC unwinder ([Documentation/arch/x86/orc-unwinder.rst](/kernel/hardware/arch/x86/orc-unwinder.md)) for most code. Both of these are especially important to support reliable stack traces which are in turn necessary for kernel live patching ([Documentation/livepatch/livepatch.rst](/kernel/development/livepatch/livepatch.md)).

<a id="rst-caveat-and-discussion"></a>

## Caveat and Discussion

As one might realize, there were only three macros previously. That is indeed insufficient to cover all the combinations of cases:

- standard/non-standard function

- code/data

- global/local symbol

There was a [discussion](<https://lore.kernel.org/r/20170217104757.28588-1-jslaby@suse.cz>) and instead of extending the current `ENTRY/END*` macros, it was decided that brand new macros should be introduced instead:



```text
So how about using macro names that actually show the purpose, instead
of importing all the crappy, historic, essentially randomly chosen
debug symbol macro names from the binutils and older kernels?
```

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



<a id="rst-macros-description"></a>

## Macros Description

The new macros are prefixed with the `SYM_` prefix and can be divided into three main groups:

1. `SYM_FUNC_*` -- to annotate C-like functions. This means functions with standard C calling conventions. For example, on x86, this means that the stack contains a return address at the predefined place and a return from the function can happen in a standard way. When frame pointers are enabled, save/restore of frame pointer shall happen at the start/end of a function, respectively, too.

   Checking tools like `objtool` should ensure such marked functions conform to these rules. The tools can also easily annotate these functions with debugging information (like *ORC data*) automatically.

2. `SYM_CODE_*` -- special functions called with special stack. Be it interrupt handlers with special stack content, trampolines, or startup functions.

   Checking tools mostly ignore checking of these functions. But some debug information still can be generated automatically. For correct debug data, this code needs hints like `UNWIND_HINT_REGS` provided by developers.

3. `SYM_DATA*` -- obviously data belonging to `.data` sections and not to `.text`. Data do not contain instructions, so they have to be treated specially by the tools: they should not treat the bytes as instructions, nor assign any debug information to them.

<a id="rst-instruction-macros"></a>

### Instruction Macros

This section covers `SYM_FUNC_*` and `SYM_CODE_*` enumerated above.

`objtool` requires that all code must be contained in an ELF symbol. Symbol names that have a `.L` prefix do not emit symbol table entries. `.L` prefixed symbols can be used within a code region, but should be avoided for denoting a range of code via `SYM_*_START/END` annotations.

- `SYM_FUNC_START` and `SYM_FUNC_START_LOCAL` are supposed to be **the most frequent markings**. They are used for functions with standard calling conventions -- global and local. Like in C, they both align the functions to architecture specific `__ALIGN` bytes. There are also `_NOALIGN` variants for special cases where developers do not want this implicit alignment.

  `SYM_FUNC_START_WEAK` and `SYM_FUNC_START_WEAK_NOALIGN` markings are also offered as an assembler counterpart to the *weak* attribute known from C.

  All of these **shall** be coupled with `SYM_FUNC_END`. First, it marks the sequence of instructions as a function and computes its size to the generated object file. Second, it also eases checking and processing such object files as the tools can trivially find exact function boundaries.

  So in most cases, developers should write something like in the following example, having some asm instructions in between the macros, of course:



  ```text
  SYM_FUNC_START(memset)
      ... asm insns ...
  SYM_FUNC_END(memset)
  ```

  In fact, this kind of annotation corresponds to the now deprecated `ENTRY` and `ENDPROC` macros.

- `SYM_FUNC_ALIAS`, `SYM_FUNC_ALIAS_LOCAL`, and `SYM_FUNC_ALIAS_WEAK` can be used to define multiple names for a function. The typical use is:



  ```text
  SYM_FUNC_START(__memset)
      ... asm insns ...
  SYN_FUNC_END(__memset)
  SYM_FUNC_ALIAS(memset, __memset)
  ```

  In this example, one can call `__memset` or `memset` with the same result, except the debug information for the instructions is generated to the object file only once -- for the non-`ALIAS` case.

- `SYM_CODE_START` and `SYM_CODE_START_LOCAL` should be used only in special cases -- if you know what you are doing. This is used exclusively for interrupt handlers and similar where the calling convention is not the C one. `_NOALIGN` variants exist too. The use is the same as for the `FUNC` category above:



  ```text
  SYM_CODE_START_LOCAL(bad_put_user)
      ... asm insns ...
  SYM_CODE_END(bad_put_user)
  ```

  Again, every `SYM_CODE_START*` **shall** be coupled by `SYM_CODE_END`.

  To some extent, this category corresponds to deprecated `ENTRY` and `END`. Except `END` had several other meanings too.

- `SYM_INNER_LABEL*` is used to denote a label inside some `SYM_{CODE,FUNC}_START` and `SYM_{CODE,FUNC}_END`.  They are very similar to C labels, except they can be made global. An example of use:



  ```text
  SYM_CODE_START(ftrace_caller)
      /* save_mcount_regs fills in first two parameters */
      ...

  SYM_INNER_LABEL(ftrace_caller_op_ptr, SYM_L_GLOBAL)
      /* Load the ftrace_ops into the 3rd parameter */
      ...

  SYM_INNER_LABEL(ftrace_call, SYM_L_GLOBAL)
      call ftrace_stub
      ...
      retq
  SYM_CODE_END(ftrace_caller)
  ```

<a id="rst-data-macros"></a>

### Data Macros

Similar to instructions, there is a couple of macros to describe data in the assembly.

- `SYM_DATA_START` and `SYM_DATA_START_LOCAL` mark the start of some data and shall be used in conjunction with either `SYM_DATA_END`, or `SYM_DATA_END_LABEL`. The latter adds also a label to the end, so that people can use `lstack` and (local) `lstack_end` in the following example:



  ```text
  SYM_DATA_START_LOCAL(lstack)
      .skip 4096
  SYM_DATA_END_LABEL(lstack, SYM_L_LOCAL, lstack_end)
  ```

- `SYM_DATA` and `SYM_DATA_LOCAL` are variants for simple, mostly one-line data:



  ```text
  SYM_DATA(HEAP,     .long rm_heap)
  SYM_DATA(heap_end, .long rm_stack)
  ```

  In the end, they expand to `SYM_DATA_START` with `SYM_DATA_END` internally.

<a id="rst-support-macros"></a>

### Support Macros

All the above reduce themselves to some invocation of `SYM_START`, `SYM_END`, or `SYM_ENTRY` at last. Normally, developers should avoid using these.

Further, in the above examples, one could see `SYM_L_LOCAL`. There are also `SYM_L_GLOBAL` and `SYM_L_WEAK`. All are intended to denote linkage of a symbol marked by them. They are used either in `_LABEL` variants of the earlier macros, or in `SYM_START`.

<a id="rst-overriding-macros"></a>

### Overriding Macros

Architecture can also override any of the macros in their own `asm/linkage.h`, including macros specifying the type of a symbol (`SYM_T_FUNC`, `SYM_T_OBJECT`, and `SYM_T_NONE`).  As every macro described in this file is surrounded by `#ifdef` + `#endif`, it is enough to define the macros differently in the aforementioned architecture-dependent header.

---

# Generic Associative Array Implementation

_Peios Kernel / Internals / Core APIs_

> This associative array implementation is an object container with the following properties:

<a id="rst-generic-associative-array-implementation"></a>

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

## Overview

This associative array implementation is an object container with the following properties:

1. Objects are opaque pointers.  The implementation does not care where they point (if anywhere) or what they point to (if anything).

   > [!NOTE]
   >
   > Pointers to objects \_must\_ be zero in the least significant bit.

2. Objects do not need to contain linkage blocks for use by the array.  This permits an object to be located in multiple arrays simultaneously. Rather, the array is made up of metadata blocks that point to objects.

3. Objects require index keys to locate them within the array.

4. Index keys must be unique.  Inserting an object with the same key as one already in the array will replace the old object.

5. Index keys can be of any length and can be of different lengths.

6. Index keys should encode the length early on, before any variation due to length is seen.

7. Index keys can include a hash to scatter objects throughout the array.

8. The array can iterated over.  The objects will not necessarily come out in key order.

9. The array can be iterated over while it is being modified, provided the RCU readlock is being held by the iterator.  Note, however, under these circumstances, some objects may be seen more than once.  If this is a problem, the iterator should lock against modification.  Objects will not be missed, however, unless deleted.

10. Objects in the array can be looked up by means of their index key.

11. Objects can be looked up while the array is being modified, provided the RCU readlock is being held by the thread doing the look up.

The implementation uses a tree of 16-pointer nodes internally that are indexed on each level by nibbles from the index key in the same manner as in a radix tree.  To improve memory efficiency, shortcuts can be emplaced to skip over what would otherwise be a series of single-occupancy nodes.  Further, nodes pack leaf object pointers into spare space in the node rather than making an extra branch until as such time an object needs to be added to a full node.

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

## The Public API

The public API can be found in `<linux/assoc_array.h>`.  The associative array is rooted on the following structure:



```text
struct assoc_array {
        ...
};
```

The code is selected by enabling `CONFIG_ASSOCIATIVE_ARRAY` with:



```text
./script/config -e ASSOCIATIVE_ARRAY
```

<a id="rst-edit-script"></a>

### Edit Script

The insertion and deletion functions produce an 'edit script' that can later be applied to effect the changes without risking `ENOMEM`. This retains the preallocated metadata blocks that will be installed in the internal tree and keeps track of the metadata blocks that will be removed from the tree when the script is applied.

This is also used to keep track of dead blocks and dead objects after the script has been applied so that they can be freed later.  The freeing is done after an RCU grace period has passed - thus allowing access functions to proceed under the RCU read lock.

The script appears as outside of the API as a pointer of the type:



```text
struct assoc_array_edit;
```

There are two functions for dealing with the script:

1. Apply an edit script:



   ```text
   void assoc_array_apply_edit(struct assoc_array_edit *edit);
   ```

   This will perform the edit functions, interpolating various write barriers to permit accesses under the RCU read lock to continue.  The edit script will then be passed to `call_rcu()` to free it and any dead stuff it points to.

2. Cancel an edit script:



   ```text
   void assoc_array_cancel_edit(struct assoc_array_edit *edit);
   ```

   This frees the edit script and all preallocated memory immediately. If this was for insertion, the new object is *not* released by this function, but must rather be released by the caller.

These functions are guaranteed not to fail.

<a id="rst-operations-table"></a>

### Operations Table

Various functions take a table of operations:



```text
struct assoc_array_ops {
        ...
};
```

This points to a number of methods, all of which need to be provided:

1. Get a chunk of index key from caller data:



   ```text
   unsigned long (*get_key_chunk)(const void *index_key, int level);
   ```

   This should return a chunk of caller-supplied index key starting at the *bit* position given by the level argument.  The level argument will be a multiple of `ASSOC_ARRAY_KEY_CHUNK_SIZE` and the function should return `ASSOC_ARRAY_KEY_CHUNK_SIZE bits`.  No error is possible.

2. Get a chunk of an object's index key:



   ```text
   unsigned long (*get_object_key_chunk)(const void *object, int level);
   ```

   As the previous function, but gets its data from an object in the array rather than from a caller-supplied index key.

3. See if this is the object we're looking for:



   ```text
   bool (*compare_object)(const void *object, const void *index_key);
   ```

   Compare the object against an index key and return `true` if it matches and `false` if it doesn't.

4. Diff the index keys of two objects:



   ```text
   int (*diff_objects)(const void *object, const void *index_key);
   ```

   Return the bit position at which the index key of the specified object differs from the given index key or -1 if they are the same.

5. Free an object:



   ```text
   void (*free_object)(void *object);
   ```

   Free the specified object.  Note that this may be called an RCU grace period after `assoc_array_apply_edit()` was called, so `synchronize_rcu()` may be necessary on module unloading.

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

### Manipulation Functions

There are a number of functions for manipulating an associative array:

1. Initialise an associative array:



   ```text
   void assoc_array_init(struct assoc_array *array);
   ```

   This initialises the base structure for an associative array.  It can't fail.

2. Insert/replace an object in an associative array:



   ```text
   struct assoc_array_edit *
   assoc_array_insert(struct assoc_array *array,
                      const struct assoc_array_ops *ops,
                      const void *index_key,
                      void *object);
   ```

   This inserts the given object into the array.  Note that the least significant bit of the pointer must be zero as it's used to type-mark pointers internally.

   If an object already exists for that key then it will be replaced with the new object and the old one will be freed automatically.

   The `index_key` argument should hold index key information and is passed to the methods in the ops table when they are called.

   This function makes no alteration to the array itself, but rather returns an edit script that must be applied.  `-ENOMEM` is returned in the case of an out-of-memory error.

   The caller should lock exclusively against other modifiers of the array.

3. Delete an object from an associative array:



   ```text
   struct assoc_array_edit *
   assoc_array_delete(struct assoc_array *array,
                      const struct assoc_array_ops *ops,
                      const void *index_key);
   ```

   This deletes an object that matches the specified data from the array.

   The `index_key` argument should hold index key information and is passed to the methods in the ops table when they are called.

   This function makes no alteration to the array itself, but rather returns an edit script that must be applied.  `-ENOMEM` is returned in the case of an out-of-memory error.  `NULL` will be returned if the specified object is not found within the array.

The caller should lock exclusively against other modifiers of the array.

4. Delete all objects from an associative array:



   ```text
   struct assoc_array_edit *
   assoc_array_clear(struct assoc_array *array,
                     const struct assoc_array_ops *ops);
   ```

   This deletes all the objects from an associative array and leaves it completely empty.

   This function makes no alteration to the array itself, but rather returns an edit script that must be applied.  `-ENOMEM` is returned in the case of an out-of-memory error.

   The caller should lock exclusively against other modifiers of the array.

5. Destroy an associative array, deleting all objects:



   ```text
   void assoc_array_destroy(struct assoc_array *array,
                            const struct assoc_array_ops *ops);
   ```

   This destroys the contents of the associative array and leaves it completely empty.  It is not permitted for another thread to be traversing the array under the RCU read lock at the same time as this function is destroying it as no RCU deferral is performed on memory release - something that would require memory to be allocated.

   The caller should lock exclusively against other modifiers and accessors of the array.

6. Garbage collect an associative array:



   ```text
   int assoc_array_gc(struct assoc_array *array,
                      const struct assoc_array_ops *ops,
                      bool (*iterator)(void *object, void *iterator_data),
                      void *iterator_data);
   ```

   This iterates over the objects in an associative array and passes each one to `iterator()`.  If `iterator()` returns `true`, the object is kept. If it returns `false`, the object will be freed.  If the `iterator()` function returns `true`, it must perform any appropriate refcount incrementing on the object before returning.

   The internal tree will be packed down if possible as part of the iteration to reduce the number of nodes in it.

   The `iterator_data` is passed directly to `iterator()` and is otherwise ignored by the function.

   The function will return `0` if successful and `-ENOMEM` if there wasn't enough memory.

   It is possible for other threads to iterate over or search the array under the RCU read lock while this function is in progress.  The caller should lock exclusively against other modifiers of the array.

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

### Access Functions

There are two functions for accessing an associative array:

1. Iterate over all the objects in an associative array:



   ```text
   int assoc_array_iterate(const struct assoc_array *array,
                           int (*iterator)(const void *object,
                                           void *iterator_data),
                           void *iterator_data);
   ```

   This passes each object in the array to the iterator callback function. `iterator_data` is private data for that function.

   This may be used on an array at the same time as the array is being modified, provided the RCU read lock is held.  Under such circumstances, it is possible for the iteration function to see some objects twice.  If this is a problem, then modification should be locked against.  The iteration algorithm should not, however, miss any objects.

   The function will return `0` if no objects were in the array or else it will return the result of the last iterator function called.  Iteration stops immediately if any call to the iteration function results in a non-zero return.

2. Find an object in an associative array:



   ```text
   void *assoc_array_find(const struct assoc_array *array,
                          const struct assoc_array_ops *ops,
                          const void *index_key);
   ```

   This walks through the array's internal tree directly to the object specified by the index key.

   This may be used on an array at the same time as the array is being modified, provided the RCU read lock is held.

   The function will return the object if found (and set `*_type` to the object type) or will return `NULL` if the object was not found.

<a id="rst-index-key-form"></a>

### Index Key Form

The index key can be of any form, but since the algorithms aren't told how long the key is, it is strongly recommended that the index key includes its length very early on before any variation due to the length would have an effect on comparisons.

This will cause leaves with different length keys to scatter away from each other - and those with the same length keys to cluster together.

It is also recommended that the index key begin with a hash of the rest of the key to maximise scattering throughout keyspace.

The better the scattering, the wider and lower the internal tree will be.

Poor scattering isn't too much of a problem as there are shortcuts and nodes can contain mixtures of leaves and metadata pointers.

The index key is read in chunks of machine word.  Each chunk is subdivided into one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and on a 64-bit CPU, 16 levels.  Unless the scattering is really poor, it is unlikely that more than one word of any particular index key will have to be used.

<a id="rst-internal-workings"></a>

## Internal Workings

The associative array data structure has an internal tree.  This tree is constructed of two types of metadata blocks: nodes and shortcuts.

A node is an array of slots.  Each slot can contain one of four things:

- A NULL pointer, indicating that the slot is empty.

- A pointer to an object (a leaf).

- A pointer to a node at the next level.

- A pointer to a shortcut.

<a id="rst-basic-internal-tree-layout"></a>

### Basic Internal Tree Layout

Ignoring shortcuts for the moment, the nodes form a multilevel tree.  The index key space is strictly subdivided by the nodes in the tree and nodes occur on fixed levels.  For example:



```text
Level: 0               1               2               3
       =============== =============== =============== ===============
                                                       NODE D
                       NODE B          NODE C  +------>+---+
               +------>+---+   +------>+---+   |       | 0 |
       NODE A  |       | 0 |   |       | 0 |   |       +---+
       +---+   |       +---+   |       +---+   |       :   :
       | 0 |   |       :   :   |       :   :   |       +---+
       +---+   |       +---+   |       +---+   |       | f |
       | 1 |---+       | 3 |---+       | 7 |---+       +---+
       +---+           +---+           +---+
       :   :           :   :           | 8 |---+
       +---+           +---+           +---+   |       NODE E
       | e |---+       | f |           :   :   +------>+---+
       +---+   |       +---+           +---+           | 0 |
       | f |   |                       | f |           +---+
       +---+   |                       +---+           :   :
               |       NODE F                          +---+
               +------>+---+                           | f |
                       | 0 |           NODE G          +---+
                       +---+   +------>+---+
                       :   :   |       | 0 |
                       +---+   |       +---+
                       | 6 |---+       :   :
                       +---+           +---+
                       :   :           | f |
                       +---+           +---+
                       | f |
                       +---+
```

In the above example, there are 7 nodes (A-G), each with 16 slots (0-f). Assuming no other meta data nodes in the tree, the key space is divided thusly:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> KEY PREFIX
>
> </th>
> <th>
>
>
> NODE
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 137\*
>
> </td>
> <td>
>
>
> D
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 138\*
>
> </td>
> <td>
>
>
> E
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 13\[0-69-f\]\*
>
> </td>
> <td>
>
>
> C
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1\[0-24-f\]\*
>
> </td>
> <td>
>
>
> B
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e6\*
>
> </td>
> <td>
>
>
> G
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e\[0-57-f\]\*
>
> </td>
> <td>
>
>
> F
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> \[02-df\]\*
>
> </td>
> <td>
>
>
> A
>
> </td>
> </tr>
> </tbody>
> </table>

So, for instance, keys with the following example index keys will be found in the appropriate nodes:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> INDEX KEY
>
> </th>
> <th>
>
>
> PREFIX
>
> </th>
> <th>
>
>
> NODE
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 13694892892489
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> C
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 13795289025897
>
> </td>
> <td>
>
>
> 137
>
> </td>
> <td>
>
>
> D
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 13889dde88793
>
> </td>
> <td>
>
>
> 138
>
> </td>
> <td>
>
>
> E
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 138bbb89003093
>
> </td>
> <td>
>
>
> 138
>
> </td>
> <td>
>
>
> E
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1394879524789
>
> </td>
> <td>
>
>
> 12
>
> </td>
> <td>
>
>
> C
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1458952489
>
> </td>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> B
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 9431809de993ba
>
> </td>
> <td>
>
>
> -
>
> </td>
> <td>
>
>
> A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> b4542910809cd
>
> </td>
> <td>
>
>
> -
>
> </td>
> <td>
>
>
> A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e5284310def98
>
> </td>
> <td>
>
>
> e
>
> </td>
> <td>
>
>
> F
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e68428974237
>
> </td>
> <td>
>
>
> e6
>
> </td>
> <td>
>
>
> G
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e7fffcbd443
>
> </td>
> <td>
>
>
> e
>
> </td>
> <td>
>
>
> F
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> f3842239082
>
> </td>
> <td>
>
>
> -
>
> </td>
> <td>
>
>
> A
>
> </td>
> </tr>
> </tbody>
> </table>

To save memory, if a node can hold all the leaves in its portion of keyspace, then the node will have all those leaves in it and will not have any metadata pointers - even if some of those leaves would like to be in the same slot.

A node can contain a heterogeneous mix of leaves and metadata pointers. Metadata pointers must be in the slots that match their subdivisions of key space.  The leaves can be in any slot not occupied by a metadata pointer.  It is guaranteed that none of the leaves in a node will match a slot occupied by a metadata pointer.  If the metadata pointer is there, any leaf whose key matches the metadata key prefix must be in the subtree that the metadata pointer points to.

In the above example list of index keys, node A will contain:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> SLOT
>
> </th>
> <th>
>
>
> CONTENT
>
> </th>
> <th>
>
>
> INDEX KEY (PREFIX)
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> PTR TO NODE B
>
> </td>
> <td>
>
>
> 1\*
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> any
>
> </td>
> <td>
>
>
> LEAF
>
> </td>
> <td>
>
>
> 9431809de993ba
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> any
>
> </td>
> <td>
>
>
> LEAF
>
> </td>
> <td>
>
>
> b4542910809cd
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> e
>
> </td>
> <td>
>
>
> PTR TO NODE F
>
> </td>
> <td>
>
>
> e\*
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> any
>
> </td>
> <td>
>
>
> LEAF
>
> </td>
> <td>
>
>
> f3842239082
>
> </td>
> </tr>
> </tbody>
> </table>

and node B:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> SLOT
>
> </th>
> <th>
>
>
> CONTENT
>
> </th>
> <th>
>
>
> INDEX KEY (PREFIX)
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> PTR TO NODE C
>
> </td>
> <td>
>
>
> 13\*
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> any
>
> </td>
> <td>
>
>
> LEAF
>
> </td>
> <td>
>
>
> 1458952489
>
> </td>
> </tr>
> </tbody>
> </table>

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

### Shortcuts

Shortcuts are metadata records that jump over a piece of keyspace.  A shortcut is a replacement for a series of single-occupancy nodes ascending through the levels.  Shortcuts exist to save memory and to speed up traversal.

It is possible for the root of the tree to be a shortcut - say, for example, the tree contains at least 17 nodes all with key prefix `1111`.  The insertion algorithm will insert a shortcut to skip over the `1111` keyspace in a single bound and get to the fourth level where these actually become different.

<a id="rst-splitting-and-collapsing-nodes"></a>

### Splitting And Collapsing Nodes

Each node has a maximum capacity of 16 leaves and metadata pointers.  If the insertion algorithm finds that it is trying to insert a 17th object into a node, that node will be split such that at least two leaves that have a common key segment at that level end up in a separate node rooted on that slot for that common key segment.

If the leaves in a full node and the leaf that is being inserted are sufficiently similar, then a shortcut will be inserted into the tree.

When the number of objects in the subtree rooted at a node falls to 16 or fewer, then the subtree will be collapsed down to a single node - and this will ripple towards the root if possible.

<a id="rst-non-recursive-iteration"></a>

### Non-Recursive Iteration

Each node and shortcut contains a back pointer to its parent and the number of slot in that parent that points to it.  None-recursive iteration uses these to proceed rootwards through the tree, going to the parent node, slot N + 1 to make sure progress is made without the need for a stack.

The backpointers, however, make simultaneous alteration and iteration tricky.

<a id="rst-simultaneous-alteration-and-iteration"></a>

### Simultaneous Alteration And Iteration

There are a number of cases to consider:

1. Simple insert/replace.  This involves simply replacing a NULL or old matching leaf pointer with the pointer to the new leaf after a barrier. The metadata blocks don't change otherwise.  An old leaf won't be freed until after the RCU grace period.

2. Simple delete.  This involves just clearing an old matching leaf.  The metadata blocks don't change otherwise.  The old leaf won't be freed until after the RCU grace period.

3. Insertion replacing part of a subtree that we haven't yet entered.  This may involve replacement of part of that subtree - but that won't affect the iteration as we won't have reached the pointer to it yet and the ancestry blocks are not replaced (the layout of those does not change).

4. Insertion replacing nodes that we're actively processing.  This isn't a problem as we've passed the anchoring pointer and won't switch onto the new layout until we follow the back pointers - at which point we've already examined the leaves in the replaced node (we iterate over all the leaves in a node before following any of its metadata pointers).

   We might, however, re-see some leaves that have been split out into a new branch that's in a slot further along than we were at.

5. Insertion replacing nodes that we're processing a dependent branch of. This won't affect us until we follow the back pointers.  Similar to (4).

6. Deletion collapsing a branch under us.  This doesn't affect us because the back pointers will get us back to the parent of the new node before we could see the new node.  The entire collapsed subtree is thrown away unchanged - and will still be rooted on the same slot, so we shouldn't process it a second time as we'll go back to slot + 1.

> [!NOTE]
>
> Under some circumstances, we need to simultaneously change the parent pointer and the parent slot pointer on a node (say, for example, we inserted another node before it and moved it up a level).  We cannot do this without locking against a read - so we have to replace that node too.
>
> However, when we're changing a shortcut into a node this isn't a problem as shortcuts only have one slot and so the parent slot number isn't used when traversing backwards over one.  This means that it's okay to change the slot number first - provided suitable barriers are used to make sure the parent slot number is read after the back pointer.

Obsolete blocks and leaves are freed up after an RCU grace period has passed, so as long as anyone doing walking or iteration holds the RCU read lock, the old superstructure should not go away on them.

---

# Boot time memory management

_Peios Kernel / Internals / Core APIs_

> Early system initialization cannot use "normal" memory management simply because it is not set up yet. But there is still need to allocate memory for various data structures, for instance for the physical page allocator.

<a id="rst-boot-time-memory-management"></a>

Early system initialization cannot use "normal" memory management simply because it is not set up yet. But there is still need to allocate memory for various data structures, for instance for the physical page allocator.

A specialized allocator called `memblock` performs the boot time memory management. The architecture specific initialization must set it up in `setup_arch()` and tear it down in `mem_init()` functions.

Once the early memory management is available it offers a variety of functions and macros for memory allocations. The allocation request may be directed to the first (and probably the only) node or to a particular node in a NUMA system. There are API variants that panic when an allocation fails and those that don't.

Memblock also offers a variety of APIs that control its own behaviour.

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

## Memblock Overview


Memblock is a method of managing memory regions during the early
boot period when the usual kernel memory allocators are not up and
running.

Memblock views the system memory as collections of contiguous
regions. There are several types of these collections:

* `memory` - describes the physical memory available to the
  kernel; this may differ from the actual physical memory installed
  in the system, for instance when the memory is restricted with
  `mem=` command line parameter
* `reserved` - describes the regions that were allocated
* `physmem` - describes the actual physical memory available during
  boot regardless of the possible restrictions and memory hot(un)plug;
  the `physmem` type is only available on some architectures.

Each region is represented by struct memblock_region that
defines the region extents, its attributes and NUMA node id on NUMA
systems. Every memory type is described by the struct memblock_type
which contains an array of memory regions along with
the allocator metadata. The "memory" and "reserved" types are nicely
wrapped with struct memblock. This structure is statically
initialized at build time. The region arrays are initially sized to
`INIT_MEMBLOCK_MEMORY_REGIONS` for "memory" and
`INIT_MEMBLOCK_RESERVED_REGIONS` for "reserved". The region array
for "physmem" is initially sized to `INIT_PHYSMEM_REGIONS`.
The `memblock_allow_resize()` enables automatic resizing of the region
arrays during addition of new regions. This feature should be used
with care so that memory allocated for the region array will not
overlap with areas that should be reserved, for example initrd.

The early architecture setup should tell memblock what the physical
memory layout is by using [`memblock_add()`](#c-memblock_add) or [`memblock_add_node()`](#c-memblock_add_node)
functions. The first function does not assign the region to a NUMA
node and it is appropriate for UMA systems. Yet, it is possible to
use it on NUMA systems as well and assign the region to a NUMA node
later in the setup process using [`memblock_set_node()`](#c-memblock_set_node). The
[`memblock_add_node()`](#c-memblock_add_node) performs such an assignment directly.

Once memblock is setup the memory can be allocated using one of the
API variants:

* memblock_phys_alloc*() - these functions return the **physical**
  address of the allocated memory
* memblock_alloc*() - these functions return the **virtual** address
  of the allocated memory.

Note, that both API variants use implicit assumptions about allowed
memory ranges and the fallback methods. Consult the documentation
of [`memblock_alloc_internal()`](#c-memblock_alloc_internal) and [`memblock_alloc_range_nid()`](#c-memblock_alloc_range_nid)
functions for more elaborate description.

As the system boot progresses, the architecture specific `mem_init()`
function frees all the memory to the buddy page allocator.

Unless an architecture enables `CONFIG_ARCH_KEEP_MEMBLOCK`, the
memblock data structures (except "physmem") will be discarded after the
system initialization completes.


<a id="rst-functions-and-structures"></a>

## Functions and structures

Here is the description of memblock data structures, functions and macros. Some of them are actually internal, but since they are documented it would be silly to omit them. Besides, reading the descriptions for the internal functions can help to understand what really happens under the hood.


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

definition of memory region attributes

**Constants**

- `MEMBLOCK_NONE`: no special request
- `MEMBLOCK_HOTPLUG`: memory region indicated in the firmware-provided memory
  map during early boot as hot(un)pluggable system RAM (e.g., memory range
  that might get hotunplugged later). With "movable_node" set on the kernel
  commandline, try keeping this memory region hotunpluggable. Does not apply
  to memblocks added ("hotplugged") after early boot.
- `MEMBLOCK_MIRROR`: mirrored region
- `MEMBLOCK_NOMAP`: don't add to kernel direct mapping and treat as
  reserved in the memory map; refer to [`memblock_mark_nomap()`](#c-memblock_mark_nomap) description
  for further details
- `MEMBLOCK_DRIVER_MANAGED`: memory region that is always detected and added
  via a driver, and never indicated in the firmware-provided memory map as
  system RAM. This corresponds to IORESOURCE_SYSRAM_DRIVER_MANAGED in the
  kernel resource tree.
- `MEMBLOCK_RSRV_NOINIT`: reserved memory region for which struct pages are not
  fully initialized. Users of this flag are responsible to properly initialize
  struct pages of this region
- `MEMBLOCK_RSRV_KERN`: memory region that is reserved for kernel use,
  either explictitly with `memblock_reserve_kern()` or via memblock
  allocation APIs. All memblock allocations set this flag.
- `MEMBLOCK_KHO_SCRATCH`: memory region that kexec can pass to the next
  kernel in handover mode. During early boot, we do not know about all
  memory reservations yet, so we get scratch memory from the previous
  kernel that we know is good to use. It is the only memory that
  allocations may happen from in this phase.

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

represents a memory region

**Definition**

```c
struct memblock_region {
        phys_addr_t base;
        phys_addr_t size;
        enum memblock_flags flags;
    #ifdef CONFIG_NUMA;
        int nid;
    #endif;
};
```

**Members**

- `base`: base address of the region
- `size`: size of the region
- `flags`: memory region attributes
- `nid`: NUMA node id

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

collection of memory regions of certain type

**Definition**

```c
struct memblock_type {
    unsigned long cnt;
    unsigned long max;
    phys_addr_t total_size;
    struct memblock_region *regions;
    char *name;
};
```

**Members**

- `cnt`: number of regions
- `max`: size of the allocated array
- `total_size`: size of all regions
- `regions`: array of regions
- `name`: the memory type symbolic name

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

memblock allocator metadata

**Definition**

```c
struct memblock {
    bool bottom_up;
    phys_addr_t current_limit;
    struct memblock_type memory;
    struct memblock_type reserved;
};
```

**Members**

- `bottom_up`: is bottom up direction?
- `current_limit`: physical address of the current allocation limit
- `memory`: usable memory regions
- `reserved`: reserved memory regions

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

```c
for_each_physmem_range(i, type, p_start, p_end)
```

iterate through physmem areas not included in type.

**Parameters**

- `i`: u64 used as loop variable
- `type`: ptr to memblock_type which excludes from the iteration, can be `NULL`
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`

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

```c
__for_each_mem_range(i, type_a, type_b, nid, flags, p_start, p_end, p_nid)
```

iterate through memblock areas from type_a and not included in type_b. Or just type_a if type_b is NULL.

**Parameters**

- `i`: u64 used as loop variable
- `type_a`: ptr to memblock_type to iterate
- `type_b`: ptr to memblock_type which excludes from the iteration
- `nid`: node selector, `NUMA_NO_NODE` for all nodes
- `flags`: pick from blocks based on memory attributes
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `p_nid`: ptr to int for nid of the range, can be `NULL`

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

```c
__for_each_mem_range_rev(i, type_a, type_b, nid, flags, p_start, p_end, p_nid)
```

reverse iterate through memblock areas from type_a and not included in type_b. Or just type_a if type_b is NULL.

**Parameters**

- `i`: u64 used as loop variable
- `type_a`: ptr to memblock_type to iterate
- `type_b`: ptr to memblock_type which excludes from the iteration
- `nid`: node selector, `NUMA_NO_NODE` for all nodes
- `flags`: pick from blocks based on memory attributes
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `p_nid`: ptr to int for nid of the range, can be `NULL`

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

```c
for_each_mem_range(i, p_start, p_end)
```

iterate through memory areas.

**Parameters**

- `i`: u64 used as loop variable
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`

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

```c
for_each_mem_range_rev(i, p_start, p_end)
```

reverse iterate through memblock areas from type_a and not included in type_b. Or just type_a if type_b is NULL.

**Parameters**

- `i`: u64 used as loop variable
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`

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

```c
for_each_reserved_mem_range(i, p_start, p_end)
```

iterate over all reserved memblock areas

**Parameters**

- `i`: u64 used as loop variable
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`

**Description**

Walks over reserved areas of memblock. Available as soon as memblock
is initialized.

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

```c
for_each_mem_pfn_range(i, nid, p_start, p_end, p_nid)
```

early memory pfn range iterator

**Parameters**

- `i`: an integer used as loop variable
- `nid`: node selector, `MAX_NUMNODES` for all nodes
- `p_start`: ptr to ulong for start pfn of the range, can be `NULL`
- `p_end`: ptr to ulong for end pfn of the range, can be `NULL`
- `p_nid`: ptr to int for nid of the range, can be `NULL`

**Description**

Walks over configured memory ranges.

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

```c
for_each_free_mem_range(i, nid, flags, p_start, p_end, p_nid)
```

iterate through free memblock areas

**Parameters**

- `i`: u64 used as loop variable
- `nid`: node selector, `NUMA_NO_NODE` for all nodes
- `flags`: pick from blocks based on memory attributes
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `p_nid`: ptr to int for nid of the range, can be `NULL`

**Description**

Walks over free (memory && !reserved) areas of memblock.  Available as
soon as memblock is initialized.

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

```c
for_each_free_mem_range_reverse(i, nid, flags, p_start, p_end, p_nid)
```

rev-iterate through free memblock areas

**Parameters**

- `i`: u64 used as loop variable
- `nid`: node selector, `NUMA_NO_NODE` for all nodes
- `flags`: pick from blocks based on memory attributes
- `p_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `p_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `p_nid`: ptr to int for nid of the range, can be `NULL`

**Description**

Walks over free (memory && !reserved) areas of memblock in reverse
order.  Available as soon as memblock is initialized.

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

```c
void memblock_set_current_limit(phys_addr_t limit)
```

Set the current allocation limit to allow limiting allocations to what is currently accessible during boot

**Parameters**

- `phys_addr_t limit`: New limit value (physical address)

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

```c
unsigned long memblock_region_memory_base_pfn(const struct memblock_region *reg)
```

get the lowest pfn of the memory region

**Parameters**

- `const struct memblock_region *reg`: memblock_region structure

**Return**

the lowest pfn intersecting with the memory region

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

```c
unsigned long memblock_region_memory_end_pfn(const struct memblock_region *reg)
```

get the end pfn of the memory region

**Parameters**

- `const struct memblock_region *reg`: memblock_region structure

**Return**

the end_pfn of the reserved region

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

```c
unsigned long memblock_region_reserved_base_pfn(const struct memblock_region *reg)
```

get the lowest pfn of the reserved region

**Parameters**

- `const struct memblock_region *reg`: memblock_region structure

**Return**

the lowest pfn intersecting with the reserved region

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

```c
unsigned long memblock_region_reserved_end_pfn(const struct memblock_region *reg)
```

get the end pfn of the reserved region

**Parameters**

- `const struct memblock_region *reg`: memblock_region structure

**Return**

the end_pfn of the reserved region

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

```c
for_each_mem_region(region)
```

iterate over memory regions

**Parameters**

- `region`: loop variable

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

```c
for_each_reserved_mem_region(region)
```

itereate over reserved memory regions

**Parameters**

- `region`: loop variable



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

```c
phys_addr_t __init_memblock __memblock_find_range_bottom_up(phys_addr_t start, phys_addr_t end, phys_addr_t size, phys_addr_t align, int nid, enum memblock_flags flags)
```

find free area utility in bottom-up

**Parameters**

- `phys_addr_t start`: start of candidate range
- `phys_addr_t end`: end of candidate range, can be `MEMBLOCK_ALLOC_ANYWHERE` or
  `MEMBLOCK_ALLOC_ACCESSIBLE`
- `phys_addr_t size`: size of free area to find
- `phys_addr_t align`: alignment of free area to find
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node
- `enum memblock_flags flags`: pick from blocks based on memory attributes

**Description**

Utility called from [`memblock_find_in_range_node()`](#c-memblock_find_in_range_node), find free area bottom-up.

**Return**

Found address on success, 0 on failure.

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

```c
phys_addr_t __init_memblock __memblock_find_range_top_down(phys_addr_t start, phys_addr_t end, phys_addr_t size, phys_addr_t align, int nid, enum memblock_flags flags)
```

find free area utility, in top-down

**Parameters**

- `phys_addr_t start`: start of candidate range
- `phys_addr_t end`: end of candidate range, can be `MEMBLOCK_ALLOC_ANYWHERE` or
  `MEMBLOCK_ALLOC_ACCESSIBLE`
- `phys_addr_t size`: size of free area to find
- `phys_addr_t align`: alignment of free area to find
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node
- `enum memblock_flags flags`: pick from blocks based on memory attributes

**Description**

Utility called from [`memblock_find_in_range_node()`](#c-memblock_find_in_range_node), find free area top-down.

**Return**

Found address on success, 0 on failure.

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

```c
phys_addr_t __init_memblock memblock_find_in_range_node(phys_addr_t size, phys_addr_t align, phys_addr_t start, phys_addr_t end, int nid, enum memblock_flags flags)
```

find free area in given range and node

**Parameters**

- `phys_addr_t size`: size of free area to find
- `phys_addr_t align`: alignment of free area to find
- `phys_addr_t start`: start of candidate range
- `phys_addr_t end`: end of candidate range, can be `MEMBLOCK_ALLOC_ANYWHERE` or
  `MEMBLOCK_ALLOC_ACCESSIBLE`
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node
- `enum memblock_flags flags`: pick from blocks based on memory attributes

**Description**

Find **size** free area aligned to **align** in the specified range and node.

**Return**

Found address on success, 0 on failure.

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

```c
phys_addr_t __init_memblock memblock_find_in_range(phys_addr_t start, phys_addr_t end, phys_addr_t size, phys_addr_t align)
```

find free area in given range

**Parameters**

- `phys_addr_t start`: start of candidate range
- `phys_addr_t end`: end of candidate range, can be `MEMBLOCK_ALLOC_ANYWHERE` or
  `MEMBLOCK_ALLOC_ACCESSIBLE`
- `phys_addr_t size`: size of free area to find
- `phys_addr_t align`: alignment of free area to find

**Description**

Find **size** free area aligned to **align** in the specified range.

**Return**

Found address on success, 0 on failure.

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

```c
void memblock_discard(void)
```

discard memory and reserved arrays if they were allocated

**Parameters**

- `void`: no arguments

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

```c
int __init_memblock memblock_double_array(struct memblock_type *type, phys_addr_t new_area_start, phys_addr_t new_area_size)
```

double the size of the memblock regions array

**Parameters**

- `struct memblock_type *type`: memblock type of the regions array being doubled
- `phys_addr_t new_area_start`: starting address of memory range to avoid overlap with
- `phys_addr_t new_area_size`: size of memory range to avoid overlap with

**Description**

Double the size of the **type** regions array. If memblock is being used to
allocate memory for a new reserved regions array and there is a previously
allocated memory range \[**new_area_start**, **new_area_start** + **new_area_size**\]
waiting to be reserved, ensure the memory used by the new array does
not overlap.

**Return**

0 on success, -1 on failure.

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

```c
void __init_memblock memblock_merge_regions(struct memblock_type *type, unsigned long start_rgn, unsigned long end_rgn)
```

merge neighboring compatible regions

**Parameters**

- `struct memblock_type *type`: memblock type to scan
- `unsigned long start_rgn`: start scanning from (**start_rgn** - 1)
- `unsigned long end_rgn`: end scanning at (**end_rgn** - 1)
  Scan **type** and merge neighboring compatible regions in \[**start_rgn** - 1, **end_rgn**)

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

```c
void __init_memblock memblock_insert_region(struct memblock_type *type, int idx, phys_addr_t base, phys_addr_t size, int nid, enum memblock_flags flags)
```

insert new memblock region

**Parameters**

- `struct memblock_type *type`: memblock type to insert into
- `int idx`: index for the insertion point
- `phys_addr_t base`: base address of the new region
- `phys_addr_t size`: size of the new region
- `int nid`: node id of the new region
- `enum memblock_flags flags`: flags of the new region

**Description**

Insert new memblock region \[**base**, **base** + **size**) into **type** at **idx**.
**type** must already have extra room to accommodate the new region.

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

```c
int __init_memblock memblock_add_range(struct memblock_type *type, phys_addr_t base, phys_addr_t size, int nid, enum memblock_flags flags)
```

add new memblock region

**Parameters**

- `struct memblock_type *type`: memblock type to add new region into
- `phys_addr_t base`: base address of the new region
- `phys_addr_t size`: size of the new region
- `int nid`: nid of the new region
- `enum memblock_flags flags`: flags of the new region

**Description**

Add new memblock region \[**base**, **base** + **size**) into **type**.  The new region
is allowed to overlap with existing ones - overlaps don't affect already
existing regions.  **type** is guaranteed to be minimal (all neighbouring
compatible regions are merged) after the addition.

**Return**

0 on success, -errno on failure.

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

```c
int __init_memblock memblock_add_node(phys_addr_t base, phys_addr_t size, int nid, enum memblock_flags flags)
```

add new memblock region within a NUMA node

**Parameters**

- `phys_addr_t base`: base address of the new region
- `phys_addr_t size`: size of the new region
- `int nid`: nid of the new region
- `enum memblock_flags flags`: flags of the new region

**Description**

Add new memblock region \[**base**, **base** + **size**) to the "memory"
type. See [`memblock_add_range()`](#c-memblock_add_range) description for mode details

**Return**

0 on success, -errno on failure.

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

```c
int __init_memblock memblock_add(phys_addr_t base, phys_addr_t size)
```

add new memblock region

**Parameters**

- `phys_addr_t base`: base address of the new region
- `phys_addr_t size`: size of the new region

**Description**

Add new memblock region \[**base**, **base** + **size**) to the "memory"
type. See [`memblock_add_range()`](#c-memblock_add_range) description for mode details

**Return**

0 on success, -errno on failure.

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

```c
bool __init_memblock memblock_validate_numa_coverage(unsigned long threshold_bytes)
```

check if amount of memory with no node ID assigned is less than a threshold

**Parameters**

- `unsigned long threshold_bytes`: maximal memory size that can have unassigned node
  ID (in bytes).

**Description**

A buggy firmware may report memory that does not belong to any node.
Check if amount of such memory is below **threshold_bytes**.

**Return**

true on success, false on failure.

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

```c
int __init_memblock memblock_isolate_range(struct memblock_type *type, phys_addr_t base, phys_addr_t size, int *start_rgn, int *end_rgn)
```

isolate given range into disjoint memblocks

**Parameters**

- `struct memblock_type *type`: memblock type to isolate range for
- `phys_addr_t base`: base of range to isolate
- `phys_addr_t size`: size of range to isolate
- `int *start_rgn`: out parameter for the start of isolated region
- `int *end_rgn`: out parameter for the end of isolated region

**Description**

Walk **type** and ensure that regions don't cross the boundaries defined by
\[**base**, **base** + **size**).  Crossing regions are split at the boundaries,
which may create at most two more regions.  The index of the first
region inside the range is returned in **\*start_rgn** and the index of the
first region after the range is returned in **\*end_rgn**.

**Return**

0 on success, -errno on failure.

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

```c
void __init_memblock memblock_free(void *ptr, size_t size)
```

free boot memory allocation

**Parameters**

- `void *ptr`: starting address of the  boot memory allocation
- `size_t size`: size of the boot memory block in bytes

**Description**

Free boot memory block previously allocated by `memblock_alloc_xx()` API.
The freeing memory will not be released to the buddy allocator.

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

```c
int __init_memblock memblock_phys_free(phys_addr_t base, phys_addr_t size)
```

free boot memory block

**Parameters**

- `phys_addr_t base`: phys starting address of the  boot memory block
- `phys_addr_t size`: size of the boot memory block in bytes

**Description**

Free boot memory block previously allocated by `memblock_phys_alloc_xx()` API.
The freeing memory will not be released to the buddy allocator.

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

```c
int __init_memblock memblock_setclr_flag(struct memblock_type *type, phys_addr_t base, phys_addr_t size, int set, int flag)
```

set or clear flag for a memory region

**Parameters**

- `struct memblock_type *type`: memblock type to set/clear flag for
- `phys_addr_t base`: base address of the region
- `phys_addr_t size`: size of the region
- `int set`: set or clear the flag
- `int flag`: the flag to update

**Description**

This function isolates region \[**base**, **base** + **size**), and sets/clears flag

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_mark_hotplug"></a>`memblock_mark_hotplug()`

```c
int __init_memblock memblock_mark_hotplug(phys_addr_t base, phys_addr_t size)
```

Mark hotpluggable memory with flag MEMBLOCK_HOTPLUG.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_clear_hotplug"></a>`memblock_clear_hotplug()`

```c
int __init_memblock memblock_clear_hotplug(phys_addr_t base, phys_addr_t size)
```

Clear flag MEMBLOCK_HOTPLUG for a specified region.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_mark_mirror"></a>`memblock_mark_mirror()`

```c
int __init_memblock memblock_mark_mirror(phys_addr_t base, phys_addr_t size)
```

Mark mirrored memory with flag MEMBLOCK_MIRROR.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_mark_nomap"></a>`memblock_mark_nomap()`

```c
int __init_memblock memblock_mark_nomap(phys_addr_t base, phys_addr_t size)
```

Mark a memory region with flag MEMBLOCK_NOMAP.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Description**

The memory regions marked with `MEMBLOCK_NOMAP` will not be added to the
direct mapping of the physical memory. These regions will still be
covered by the memory map. The struct page representing NOMAP memory
frames in the memory map will be `PageReserved()`

**Note**

if the memory being marked `MEMBLOCK_NOMAP` was allocated from
memblock, the caller must inform kmemleak to ignore that memory

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_clear_nomap"></a>`memblock_clear_nomap()`

```c
int __init_memblock memblock_clear_nomap(phys_addr_t base, phys_addr_t size)
```

Clear flag MEMBLOCK_NOMAP for a specified region.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_reserved_mark_noinit"></a>`memblock_reserved_mark_noinit()`

```c
int __init_memblock memblock_reserved_mark_noinit(phys_addr_t base, phys_addr_t size)
```

Mark a reserved memory region with flag MEMBLOCK_RSRV_NOINIT

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Description**

The struct pages for the reserved regions marked `MEMBLOCK_RSRV_NOINIT` will
not be fully initialized to allow the caller optimize their initialization.

When `CONFIG_DEFERRED_STRUCT_PAGE_INIT` is enabled, setting this flag
completely bypasses the initialization of struct pages for such region.

When `CONFIG_DEFERRED_STRUCT_PAGE_INIT` is disabled, struct pages in this
region will be initialized with default values but won't be marked as
reserved.

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_mark_kho_scratch"></a>`memblock_mark_kho_scratch()`

```c
int memblock_mark_kho_scratch(phys_addr_t base, phys_addr_t size)
```

Mark a memory region as MEMBLOCK_KHO_SCRATCH.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Description**

Only memory regions marked with `MEMBLOCK_KHO_SCRATCH` will be considered
for allocations during early boot with kexec handover.

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_clear_kho_scratch"></a>`memblock_clear_kho_scratch()`

```c
int memblock_clear_kho_scratch(phys_addr_t base, phys_addr_t size)
```

Clear MEMBLOCK_KHO_SCRATCH flag for a specified region.

**Parameters**

- `phys_addr_t base`: the base phys addr of the region
- `phys_addr_t size`: the size of the region

**Return**

0 on success, -errno on failure.

#### <a id="c-__next_mem_range"></a>`__next_mem_range()`

```c
void __next_mem_range(u64 *idx, int nid, enum memblock_flags flags, struct memblock_type *type_a, struct memblock_type *type_b, phys_addr_t *out_start, phys_addr_t *out_end, int *out_nid)
```

next function for [`for_each_free_mem_range()`](#c-for_each_free_mem_range) etc.

**Parameters**

- `u64 *idx`: pointer to u64 loop variable
- `int nid`: node selector, `NUMA_NO_NODE` for all nodes
- `enum memblock_flags flags`: pick from blocks based on memory attributes
- `struct memblock_type *type_a`: pointer to memblock_type from where the range is taken
- `struct memblock_type *type_b`: pointer to memblock_type which excludes memory from being taken
- `phys_addr_t *out_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `phys_addr_t *out_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `int *out_nid`: ptr to int for nid of the range, can be `NULL`

**Description**

Find the first area from **\*idx** which matches **nid**, fill the out
parameters, and update **\*idx** for the next iteration.  The lower 32bit of
**\*idx** contains index into type_a and the upper 32bit indexes the
areas before each region in type_b.  For example, if type_b regions
look like the following,

0:\[0-16), 1:\[32-48), 2:\[128-130)

The upper 32bit indexes the following regions.

0:\[0-0), 1:\[16-32), 2:\[48-128), 3:\[130-MAX)

As both region arrays are sorted, the function advances the two indices
in lockstep and returns each intersection.

#### <a id="c-__next_mem_range_rev"></a>`__next_mem_range_rev()`

```c
void __init_memblock __next_mem_range_rev(u64 *idx, int nid, enum memblock_flags flags, struct memblock_type *type_a, struct memblock_type *type_b, phys_addr_t *out_start, phys_addr_t *out_end, int *out_nid)
```

generic next function for for_each_*`_range_rev()`

**Parameters**

- `u64 *idx`: pointer to u64 loop variable
- `int nid`: node selector, `NUMA_NO_NODE` for all nodes
- `enum memblock_flags flags`: pick from blocks based on memory attributes
- `struct memblock_type *type_a`: pointer to memblock_type from where the range is taken
- `struct memblock_type *type_b`: pointer to memblock_type which excludes memory from being taken
- `phys_addr_t *out_start`: ptr to phys_addr_t for start address of the range, can be `NULL`
- `phys_addr_t *out_end`: ptr to phys_addr_t for end address of the range, can be `NULL`
- `int *out_nid`: ptr to int for nid of the range, can be `NULL`

**Description**

Finds the next range from type_a which is not marked as unsuitable
in type_b.

Reverse of [`__next_mem_range()`](#c-__next_mem_range).

#### <a id="c-memblock_set_node"></a>`memblock_set_node()`

```c
int __init_memblock memblock_set_node(phys_addr_t base, phys_addr_t size, struct memblock_type *type, int nid)
```

set node ID on memblock regions

**Parameters**

- `phys_addr_t base`: base of area to set node ID for
- `phys_addr_t size`: size of area to set node ID for
- `struct memblock_type *type`: memblock type to set node ID for
- `int nid`: node ID to set

**Description**

Set the nid of memblock **type** regions in \[**base**, **base** + **size**) to **nid**.
Regions which cross the area boundaries are split as necessary.

**Return**

0 on success, -errno on failure.

#### <a id="c-memblock_alloc_range_nid"></a>`memblock_alloc_range_nid()`

```c
phys_addr_t memblock_alloc_range_nid(phys_addr_t size, phys_addr_t align, phys_addr_t start, phys_addr_t end, int nid, bool exact_nid)
```

allocate boot memory block

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t start`: the lower bound of the memory region to allocate (phys address)
- `phys_addr_t end`: the upper bound of the memory region to allocate (phys address)
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node
- `bool exact_nid`: control the allocation fall back to other nodes

**Description**

The allocation is performed from memory region limited by
memblock.current_limit if **end** == `MEMBLOCK_ALLOC_ACCESSIBLE`.

If the specified node can not hold the requested memory and **exact_nid**
is false, the allocation falls back to any node in the system.

For systems with memory mirroring, the allocation is attempted first
from the regions with mirroring enabled and then retried from any
memory region.

In addition, function using kmemleak_alloc_phys for allocated boot
memory block, it is never reported as leaks.

**Return**

Physical address of allocated memory block on success, `0` on failure.

#### <a id="c-memblock_phys_alloc_range"></a>`memblock_phys_alloc_range()`

```c
phys_addr_t memblock_phys_alloc_range(phys_addr_t size, phys_addr_t align, phys_addr_t start, phys_addr_t end)
```

allocate a memory block inside specified range

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t start`: the lower bound of the memory region to allocate (physical address)
- `phys_addr_t end`: the upper bound of the memory region to allocate (physical address)

**Description**

Allocate **size** bytes in the between **start** and **end**.

**Return**

physical address of the allocated memory block on success,
`0` on failure.

#### <a id="c-memblock_phys_alloc_try_nid"></a>`memblock_phys_alloc_try_nid()`

```c
phys_addr_t memblock_phys_alloc_try_nid(phys_addr_t size, phys_addr_t align, int nid)
```

allocate a memory block from specified NUMA node

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node

**Description**

Allocates memory block from the specified NUMA node. If the node
has no available memory, attempts to allocated from any node in the
system.

**Return**

physical address of the allocated memory block on success,
`0` on failure.

#### <a id="c-memblock_alloc_internal"></a>`memblock_alloc_internal()`

```c
void * memblock_alloc_internal(phys_addr_t size, phys_addr_t align, phys_addr_t min_addr, phys_addr_t max_addr, int nid, bool exact_nid)
```

allocate boot memory block

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t min_addr`: the lower bound of the memory region to allocate (phys address)
- `phys_addr_t max_addr`: the upper bound of the memory region to allocate (phys address)
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node
- `bool exact_nid`: control the allocation fall back to other nodes

**Description**

Allocates memory block using [`memblock_alloc_range_nid()`](#c-memblock_alloc_range_nid) and
converts the returned physical address to virtual.

The **min_addr** limit is dropped if it can not be satisfied and the allocation
will fall back to memory below **min_addr**. Other constraints, such
as node and mirrored memory will be handled again in
[`memblock_alloc_range_nid()`](#c-memblock_alloc_range_nid).

**Return**

Virtual address of allocated memory block on success, NULL on failure.

#### <a id="c-memblock_alloc_exact_nid_raw"></a>`memblock_alloc_exact_nid_raw()`

```c
void * memblock_alloc_exact_nid_raw(phys_addr_t size, phys_addr_t align, phys_addr_t min_addr, phys_addr_t max_addr, int nid)
```

allocate boot memory block on the exact node without zeroing memory

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t min_addr`: the lower bound of the memory region from where the allocation
  is preferred (phys address)
- `phys_addr_t max_addr`: the upper bound of the memory region from where the allocation
  is preferred (phys address), or `MEMBLOCK_ALLOC_ACCESSIBLE` to
  allocate only from memory limited by memblock.current_limit value
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node

**Description**

Public function, provides additional debug information (including caller
info), if enabled. Does not zero allocated memory.

**Return**

Virtual address of allocated memory block on success, NULL on failure.

#### <a id="c-memblock_alloc_try_nid_raw"></a>`memblock_alloc_try_nid_raw()`

```c
void * memblock_alloc_try_nid_raw(phys_addr_t size, phys_addr_t align, phys_addr_t min_addr, phys_addr_t max_addr, int nid)
```

allocate boot memory block without zeroing memory and without panicking

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t min_addr`: the lower bound of the memory region from where the allocation
  is preferred (phys address)
- `phys_addr_t max_addr`: the upper bound of the memory region from where the allocation
  is preferred (phys address), or `MEMBLOCK_ALLOC_ACCESSIBLE` to
  allocate only from memory limited by memblock.current_limit value
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node

**Description**

Public function, provides additional debug information (including caller
info), if enabled. Does not zero allocated memory, does not panic if request
cannot be satisfied.

**Return**

Virtual address of allocated memory block on success, NULL on failure.

#### <a id="c-memblock_alloc_try_nid"></a>`memblock_alloc_try_nid()`

```c
void * memblock_alloc_try_nid(phys_addr_t size, phys_addr_t align, phys_addr_t min_addr, phys_addr_t max_addr, int nid)
```

allocate boot memory block

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `phys_addr_t min_addr`: the lower bound of the memory region from where the allocation
  is preferred (phys address)
- `phys_addr_t max_addr`: the upper bound of the memory region from where the allocation
  is preferred (phys address), or `MEMBLOCK_ALLOC_ACCESSIBLE` to
  allocate only from memory limited by memblock.current_limit value
- `int nid`: nid of the free area to find, `NUMA_NO_NODE` for any node

**Description**

Public function, provides additional debug information (including caller
info), if enabled. This function zeroes the allocated memory.

**Return**

Virtual address of allocated memory block on success, NULL on failure.

#### <a id="c-__memblock_alloc_or_panic"></a>`__memblock_alloc_or_panic()`

```c
void * __memblock_alloc_or_panic(phys_addr_t size, phys_addr_t align, const char *func)
```

Try to allocate memory and panic on failure

**Parameters**

- `phys_addr_t size`: size of memory block to be allocated in bytes
- `phys_addr_t align`: alignment of the region and block's size
- `const char *func`: caller func name

**Description**

This function attempts to allocate memory using memblock_alloc,
and in case of failure, it calls panic with the formatted message.
This function should not be used directly, please use the macro memblock_alloc_or_panic.

#### <a id="c-memblock_free_late"></a>`memblock_free_late()`

```c
void memblock_free_late(phys_addr_t base, phys_addr_t size)
```

free pages directly to buddy allocator

**Parameters**

- `phys_addr_t base`: phys starting address of the  boot memory block
- `phys_addr_t size`: size of the boot memory block in bytes

**Description**

This is only useful when the memblock allocator has already been torn
down, but we are still initializing the system.  Pages are released directly
to the buddy allocator.

#### <a id="c-memblock_estimated_nr_free_pages"></a>`memblock_estimated_nr_free_pages()`

```c
unsigned long memblock_estimated_nr_free_pages(void)
```

return estimated number of free pages from memblock point of view

**Parameters**

- `void`: no arguments

**Description**

During bootup, subsystems might need a rough estimate of the number of free
pages in the whole system, before precise numbers are available from the
buddy. Especially with CONFIG_DEFERRED_STRUCT_PAGE_INIT, the numbers
obtained from the buddy might be very imprecise during bootup.

**Return**

An estimated number of free pages from memblock point of view.

#### <a id="c-memblock_is_region_memory"></a>`memblock_is_region_memory()`

```c
bool __init_memblock memblock_is_region_memory(phys_addr_t base, phys_addr_t size)
```

check if a region is a subset of memory

**Parameters**

- `phys_addr_t base`: base of region to check
- `phys_addr_t size`: size of region to check

**Description**

Check if the region \[**base**, **base** + **size**) is a subset of a memory block.

**Return**

0 if false, non-zero if true

#### <a id="c-memblock_is_region_reserved"></a>`memblock_is_region_reserved()`

```c
bool __init_memblock memblock_is_region_reserved(phys_addr_t base, phys_addr_t size)
```

check if a region intersects reserved memory

**Parameters**

- `phys_addr_t base`: base of region to check
- `phys_addr_t size`: size of region to check

**Description**

Check if the region \[**base**, **base** + **size**) intersects a reserved
memory block.

**Return**

True if they intersect, false if not.

#### <a id="c-memblock_free_all"></a>`memblock_free_all()`

```c
void memblock_free_all(void)
```

release free pages to the buddy allocator

**Parameters**

- `void`: no arguments

#### <a id="c-reserve_mem_find_by_name"></a>`reserve_mem_find_by_name()`

```c
int reserve_mem_find_by_name(const char *name, phys_addr_t *start, phys_addr_t *size)
```

Find reserved memory region with a given name

**Parameters**

- `const char *name`: The name that is attached to a reserved memory region
- `phys_addr_t *start`: If found, holds the start address
- `phys_addr_t *size`: If found, holds the size of the address.

**Description**

**start** and **size** are only updated if **name** is found.

**Return**

1 if found or 0 if not found.

#### <a id="c-reserve_mem_release_by_name"></a>`reserve_mem_release_by_name()`

```c
int reserve_mem_release_by_name(const char *name)
```

Release reserved memory region with a given name

**Parameters**

- `const char *name`: The name that is attached to a reserved memory region

**Description**

Forcibly release the pages in the reserved memory region so that those memory
can be used as free memory. After released the reserved region size becomes 0.

**Return**

1 if released or 0 if not found.

---

# Cache and TLB Flushing Under Linux

_Peios Kernel / Internals / Core APIs_

> This document describes the cache/tlb flushing interfaces called by the Linux VM subsystem. It enumerates over each interface, describes its intended purpose, and what side effect is expected after the interface is invoked.

<a id="rst-cache-and-tlb-flushing-under-linux"></a>

**Author:** David S. Miller &lt;[davem@redhat.com](<mailto:davem@redhat.com>)&gt;

This document describes the cache/tlb flushing interfaces called by the Linux VM subsystem.  It enumerates over each interface, describes its intended purpose, and what side effect is expected after the interface is invoked.

The side effects described below are stated for a uniprocessor implementation, and what is to happen on that single processor.  The SMP cases are a simple extension, in that you just extend the definition such that the side effect for a particular interface occurs on all processors in the system.  Don't let this scare you into thinking SMP cache/tlb flushing must be so inefficient, this is in fact an area where many optimizations are possible.  For example, if it can be proven that a user address space has never executed on a cpu (see mm_cpumask()), one need not perform a flush for this address space on that cpu.

First, the TLB flushing interfaces, since they are the simplest.  The "TLB" is abstracted under Linux as something the cpu uses to cache virtual--&gt;physical address translations obtained from the software page tables.  Meaning that if the software page tables change, it is possible for stale translations to exist in this "TLB" cache. Therefore when software page table changes occur, the kernel will invoke one of the following flush methods \_after\_ the page table changes occur:

1. `void flush_tlb_all(void)`

   > The most severe flush of all.  After this interface runs, any previous page table modification whatsoever will be visible to the cpu.
   >
   > This is usually invoked when the kernel page tables are changed, since such translations are "global" in nature.

2. `void flush_tlb_mm(struct mm_struct *mm)`

   > This interface flushes an entire user address space from the TLB.  After running, this interface must make sure that any previous page table modifications for the address space 'mm' will be visible to the cpu.  That is, after running, there will be no entries in the TLB for 'mm'.
   >
   > This interface is used to handle whole address space page table operations such as what happens during fork, and exec.

3. `void flush_tlb_range(struct vm_area_struct *vma, unsigned long start, unsigned long end)`

   > Here we are flushing a specific range of (user) virtual address translations from the TLB.  After running, this interface must make sure that any previous page table modifications for the address space 'vma-&gt;vm_mm' in the range 'start' to 'end-1' will be visible to the cpu.  That is, after running, there will be no entries in the TLB for 'mm' for virtual addresses in the range 'start' to 'end-1'.
   >
   > The "vma" is the backing store being used for the region. Primarily, this is used for munmap() type operations.
   >
   > The interface is provided in hopes that the port can find a suitably efficient method for removing multiple page sized translations from the TLB, instead of having the kernel call flush_tlb_page (see below) for each entry which may be modified.

4. `void flush_tlb_page(struct vm_area_struct *vma, unsigned long addr)`

   > This time we need to remove the PAGE_SIZE sized translation from the TLB.  The 'vma' is the backing structure used by Linux to keep track of mmap'd regions for a process, the address space is available via vma-&gt;vm_mm.  Also, one may test (vma-&gt;vm_flags &amp; VM_EXEC) to see if this region is executable (and thus could be in the 'instruction TLB' in split-tlb type setups).
   >
   > After running, this interface must make sure that any previous page table modification for address space 'vma-&gt;vm_mm' for user virtual address 'addr' will be visible to the cpu.  That is, after running, there will be no entries in the TLB for 'vma-&gt;vm_mm' for virtual address 'addr'.
   >
   > This is used primarily during fault processing.

5. `void update_mmu_cache_range(struct vm_fault *vmf, struct vm_area_struct *vma, unsigned long address, pte_t *ptep, unsigned int nr)`

   > At the end of every page fault, this routine is invoked to tell the architecture specific code that translations now exists in the software page tables for address space "vma-&gt;vm_mm" at virtual address "address" for "nr" consecutive pages.
   >
   > This routine is also invoked in various other places which pass a NULL "vmf".
   >
   > A port may use this information in any way it so chooses. For example, it could use this event to pre-load TLB translations for software managed TLB configurations. The sparc64 port currently does this.

Next, we have the cache flushing interfaces.  In general, when Linux is changing an existing virtual--&gt;physical mapping to a new value, the sequence will be in one of the following forms:



```text
1) flush_cache_mm(mm);
   change_all_page_tables_of(mm);
   flush_tlb_mm(mm);

2) flush_cache_range(vma, start, end);
   change_range_of_page_tables(mm, start, end);
   flush_tlb_range(vma, start, end);

3) flush_cache_page(vma, addr, pfn);
   set_pte(pte_pointer, new_pte_val);
   flush_tlb_page(vma, addr);
```

The cache level flush will always be first, because this allows us to properly handle systems whose caches are strict and require a virtual--&gt;physical translation to exist for a virtual address when that virtual address is flushed from the cache.  The HyperSparc cpu is one such cpu with this attribute.

The cache flushing routines below need only deal with cache flushing to the extent that it is necessary for a particular cpu.  Mostly, these routines must be implemented for cpus which have virtually indexed caches which must be flushed when virtual--&gt;physical translations are changed or removed.  So, for example, the physically indexed physically tagged caches of IA32 processors have no need to implement these interfaces since the caches are fully synchronized and have no dependency on translation information.

Here are the routines, one by one:

1. `void flush_cache_mm(struct mm_struct *mm)`

   > This interface flushes an entire user address space from the caches.  That is, after running, there will be no cache lines associated with 'mm'.
   >
   > This interface is used to handle whole address space page table operations such as what happens during exit and exec.

2. `void flush_cache_dup_mm(struct mm_struct *mm)`

   > This interface flushes an entire user address space from the caches.  That is, after running, there will be no cache lines associated with 'mm'.
   >
   > This interface is used to handle whole address space page table operations such as what happens during fork.
   >
   > This option is separate from flush_cache_mm to allow some optimizations for VIPT caches.

3. `void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end)`

   > Here we are flushing a specific range of (user) virtual addresses from the cache.  After running, there will be no entries in the cache for 'vma-&gt;vm_mm' for virtual addresses in the range 'start' to 'end-1'.
   >
   > The "vma" is the backing store being used for the region. Primarily, this is used for munmap() type operations.
   >
   > The interface is provided in hopes that the port can find a suitably efficient method for removing multiple page sized regions from the cache, instead of having the kernel call flush_cache_page (see below) for each entry which may be modified.

4. `void flush_cache_page(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn)`

   > This time we need to remove a PAGE_SIZE sized range from the cache.  The 'vma' is the backing structure used by Linux to keep track of mmap'd regions for a process, the address space is available via vma-&gt;vm_mm.  Also, one may test (vma-&gt;vm_flags &amp; VM_EXEC) to see if this region is executable (and thus could be in the 'instruction cache' in "Harvard" type cache layouts).
   >
   > The 'pfn' indicates the physical page frame (shift this value left by PAGE_SHIFT to get the physical address) that 'addr' translates to.  It is this mapping which should be removed from the cache.
   >
   > After running, there will be no entries in the cache for 'vma-&gt;vm_mm' for virtual address 'addr' which translates to 'pfn'.
   >
   > This is used primarily during fault processing.

5. `void flush_cache_kmaps(void)`

   > This routine need only be implemented if the platform utilizes highmem.  It will be called right before all of the kmaps are invalidated.
   >
   > After running, there will be no entries in the cache for the kernel virtual address range PKMAP_ADDR(0) to PKMAP_ADDR(LAST_PKMAP).
   >
   > This routing should be implemented in asm/highmem.h

6. `void flush_cache_vmap(unsigned long start, unsigned long end)` `void flush_cache_vunmap(unsigned long start, unsigned long end)`

   > Here in these two interfaces we are flushing a specific range of (kernel) virtual addresses from the cache.  After running, there will be no entries in the cache for the kernel address space for virtual addresses in the range 'start' to 'end-1'.
   >
   > The first of these two routines is invoked after vmap_range() has installed the page table entries.  The second is invoked before vunmap_range() deletes the page table entries.

There exists another whole class of cpu cache issues which currently require a whole different set of interfaces to handle properly. The biggest problem is that of virtual aliasing in the data cache of a processor.

Is your port susceptible to virtual aliasing in its D-cache? Well, if your D-cache is virtually indexed, is larger in size than PAGE_SIZE, and does not prevent multiple cache lines for the same physical address from existing at once, you have this problem.

If your D-cache has this problem, first define asm/shmparam.h SHMLBA properly, it should essentially be the size of your virtually addressed D-cache (or if the size is variable, the largest possible size).  This setting will force the SYSv IPC layer to only allow user processes to mmap shared memory at address which are a multiple of this value.

> [!NOTE]
>
> This does not fix shared mmaps, check out the sparc64 port for one way to solve this (in particular SPARC_FLAG_MMAPSHARED).

Next, you have to solve the D-cache aliasing issue for all other cases.  Please keep in mind that fact that, for a given page mapped into some user address space, there is always at least one more mapping, that of the kernel in its linear mapping starting at PAGE_OFFSET.  So immediately, once the first user maps a given physical page into its address space, by implication the D-cache aliasing problem has the potential to exist since the kernel already maps this page at its virtual address.

> `void copy_user_page(void *to, void *from, unsigned long addr, struct page *page)` `void clear_user_page(void *to, unsigned long addr, struct page *page)`
>
> > These two routines store data in user anonymous or COW pages.  It allows a port to efficiently avoid D-cache alias issues between userspace and the kernel.
> >
> > For example, a port may temporarily map 'from' and 'to' to kernel virtual addresses during the copy.  The virtual address for these two pages is chosen in such a way that the kernel load/store instructions happen to virtual addresses which are of the same "color" as the user mapping of the page.  Sparc64 for example, uses this technique.
> >
> > The 'addr' parameter tells the virtual address where the user will ultimately have this page mapped, and the 'page' parameter gives a pointer to the struct page of the target.
> >
> > If D-cache aliasing is not an issue, these two routines may simply call memcpy/memset directly and do nothing more.
>
> `void flush_dcache_folio(struct folio *folio)`
>
> > This routines must be called when:
> >
> > > - **a)** the kernel did write to a page that is in the page cache page and / or in high memory
> > >
> > > - **b)** the kernel is about to read from a page cache page and user space shared/writable mappings of this page potentially exist.  Note that \{get,pin\}\_user_pages\{\_fast\} already call flush_dcache_folio on any page found in the user address space and thus driver code rarely needs to take this into account.
> >
> > > [!NOTE]
> > >
> > > This routine need only be called for page cache pages which can potentially ever be mapped into the address space of a user process.  So for example, VFS layer code handling vfs symlinks in the page cache need not call this interface at all.
> >
> > The phrase "kernel writes to a page cache page" means, specifically, that the kernel executes store instructions that dirty data in that page at the kernel virtual mapping of that page.  It is important to flush here to handle D-cache aliasing, to make sure these kernel stores are visible to user space mappings of that page.
> >
> > The corollary case is just as important, if there are users which have shared+writable mappings of this file, we must make sure that kernel reads of these pages will see the most recent stores done by the user.
> >
> > If D-cache aliasing is not an issue, this routine may simply be defined as a nop on that architecture.
> >
> > There is a bit set aside in folio-&gt;flags (PG_arch_1) as "architecture private".  The kernel guarantees that, for pagecache pages, it will clear this bit when such a page first enters the pagecache.
> >
> > This allows these interfaces to be implemented much more efficiently.  It allows one to "defer" (perhaps indefinitely) the actual flush if there are currently no user processes mapping this page.  See sparc64's flush_dcache_folio and update_mmu_cache_range implementations for an example of how to go about doing this.
> >
> > The idea is, first at flush_dcache_folio() time, if folio_flush_mapping() returns a mapping, and mapping_mapped() on that mapping returns %false, just mark the architecture private page flag bit.  Later, in update_mmu_cache_range(), a check is made of this flag bit, and if set the flush is done and the flag bit is cleared.
> >
> > > [!IMPORTANT]
> > >
> > > It is often important, if you defer the flush, that the actual flush occurs on the same CPU as did the cpu stores into the page to make it dirty.  Again, see sparc64 for examples of how to deal with this.
>
> `void copy_to_user_page(struct vm_area_struct *vma, struct page *page, unsigned long user_vaddr, void *dst, void *src, int len)` `void copy_from_user_page(struct vm_area_struct *vma, struct page *page, unsigned long user_vaddr, void *dst, void *src, int len)`
>
> > When the kernel needs to copy arbitrary data in and out of arbitrary user pages (f.e. for ptrace()) it will use these two routines.
> >
> > Any necessary cache flushing or other coherency operations that need to occur should happen here.  If the processor's instruction cache does not snoop cpu stores, it is very likely that you will need to flush the instruction cache for copy_to_user_page().
>
> `void flush_anon_page(struct vm_area_struct *vma, struct page *page, unsigned long vmaddr)`
>
> > When the kernel needs to access the contents of an anonymous page, it calls this function (currently only get_user_pages()).  Note: flush_dcache_folio() deliberately doesn't work for an anonymous page.  The default implementation is a nop (and should remain so for all coherent architectures).  For incoherent architectures, it should flush the cache of the page at vmaddr.
>
> `void flush_icache_range(unsigned long start, unsigned long end)`
>
> > When the kernel stores into addresses that it will execute out of (eg when loading modules), this function is called.
> >
> > If the icache does not snoop stores then this routine will need to flush it.
>
> `void flush_icache_page(struct vm_area_struct *vma, struct page *page)`
>
> > All the functionality of flush_icache_page can be implemented in flush_dcache_folio and update_mmu_cache_range. In the future, the hope is to remove this interface completely.

The final category of APIs is for I/O to deliberately aliased address ranges inside the kernel.  Such aliases are set up by use of the vmap/vmalloc API.  Since kernel I/O goes via physical pages, the I/O subsystem assumes that the user mapping and kernel offset mapping are the only aliases.  This isn't true for vmap aliases, so anything in the kernel trying to do I/O to vmap areas must manually manage coherency.  It must do this by flushing the vmap range before doing I/O and invalidating it after the I/O returns.

> `void flush_kernel_vmap_range(void *vaddr, int size)`
>
> > flushes the kernel cache for a given virtual address range in the vmap area.  This is to make sure that any data the kernel modified in the vmap range is made visible to the physical page.  The design is to make this area safe to perform I/O on. Note that this API does *not* also flush the offset map alias of the area.
>
> `void invalidate_kernel_vmap_range(void *vaddr, int size) invalidates`
>
> > the cache for a given virtual address range in the vmap area which prevents the processor from making the cache stale by speculatively reading data while the I/O was occurring to the physical pages.  This is only necessary for data reads into the vmap area.

---

# Cgroup Kernel APIs

_Peios Kernel / Internals / Core APIs_

> Reference for Cgroup Kernel APIs.

<a id="rst-cgroup-kernel-apis"></a>

<a id="rst-device-memory-cgroup-api-dmemcg"></a>

## Device Memory Cgroup API (dmemcg)


#### <a id="c-dmem_cgroup_state_evict_valuable"></a>`dmem_cgroup_state_evict_valuable()`

```c
bool dmem_cgroup_state_evict_valuable(struct dmem_cgroup_pool_state *limit_pool, struct dmem_cgroup_pool_state *test_pool, bool ignore_low, bool *ret_hit_low)
```

Check if we should evict from test_pool

**Parameters**

- `struct dmem_cgroup_pool_state *limit_pool`: The pool for which we hit limits
- `struct dmem_cgroup_pool_state *test_pool`: The pool for which to test
- `bool ignore_low`: Whether we have to respect low watermarks.
- `bool *ret_hit_low`: Pointer to whether it makes sense to consider low watermark.

**Description**

This function returns true if we can evict from **test_pool**, false if not.
When returning false and **ignore_low** is false, **ret_hit_low** may
be set to true to indicate this function can be retried with **ignore_low**
set to true.

**Return**

bool

#### <a id="c-dmem_cgroup_unregister_region"></a>`dmem_cgroup_unregister_region()`

```c
void dmem_cgroup_unregister_region(struct dmem_cgroup_region *region)
```

Unregister a previously registered region.

**Parameters**

- `struct dmem_cgroup_region *region`: The region to unregister.

**Description**

This function undoes dmem_cgroup_register_region.

#### <a id="c-dmem_cgroup_register_region"></a>`dmem_cgroup_register_region()`

```c
struct dmem_cgroup_region * dmem_cgroup_register_region(u64 size, const char *fmt, ...)
```

Register a regions for dev cgroup.

**Parameters**

- `u64 size`: Size of region to register, in bytes.
- `const char *fmt`: Region parameters to register
- `...`: variable arguments

**Description**

This function registers a node in the dmem cgroup with the
name given. After calling this function, the region can be
used for allocations.

**Return**

NULL or a struct on success, PTR_ERR on failure.

#### <a id="c-dmem_cgroup_pool_state_put"></a>`dmem_cgroup_pool_state_put()`

```c
void dmem_cgroup_pool_state_put(struct dmem_cgroup_pool_state *pool)
```

Drop a reference to a dmem_cgroup_pool_state

**Parameters**

- `struct dmem_cgroup_pool_state *pool`: `dmem_cgroup_pool_state`

**Description**

Called to drop a reference to the limiting pool returned by
[`dmem_cgroup_try_charge()`](#c-dmem_cgroup_try_charge).

#### <a id="c-dmem_cgroup_uncharge"></a>`dmem_cgroup_uncharge()`

```c
void dmem_cgroup_uncharge(struct dmem_cgroup_pool_state *pool, u64 size)
```

Uncharge a pool.

**Parameters**

- `struct dmem_cgroup_pool_state *pool`: Pool to uncharge.
- `u64 size`: Size to uncharge.

**Description**

Undoes the effects of dmem_cgroup_try_charge.
Must be called with the returned pool as argument,
and same **index** and **size**.

#### <a id="c-dmem_cgroup_try_charge"></a>`dmem_cgroup_try_charge()`

```c
int dmem_cgroup_try_charge(struct dmem_cgroup_region *region, u64 size, struct dmem_cgroup_pool_state **ret_pool, struct dmem_cgroup_pool_state **ret_limit_pool)
```

Try charging a new allocation to a region.

**Parameters**

- `struct dmem_cgroup_region *region`: dmem region to charge
- `u64 size`: Size (in bytes) to charge.
- `struct dmem_cgroup_pool_state **ret_pool`: On succesfull allocation, the pool that is charged.
- `struct dmem_cgroup_pool_state **ret_limit_pool`: On a failed allocation, the limiting pool.

**Description**

This function charges the **region** region for a size of **size** bytes.

If the function succeeds, **ret_pool** is set, which must be passed to
[`dmem_cgroup_uncharge()`](#c-dmem_cgroup_uncharge) when undoing the allocation.

When this function fails with -EAGAIN and **ret_limit_pool** is non-null, it
will be set to the pool for which the limit is hit. This can be used for
eviction as argument to `dmem_cgroup_evict_valuable()`. This reference must be freed
with **dmem_cgroup_pool_state_put()**.

**Return**

0 on success, -EAGAIN on hitting a limit, or a negative errno on failure.

---

# Circular Buffers

_Peios Kernel / Internals / Core APIs_

> Linux provides a number of features that can be used to implement circular buffering. There are two sets of such features:

<a id="rst-circular-buffers"></a>

**Author:** David Howells &lt;[dhowells@redhat.com](<mailto:dhowells@redhat.com>)&gt;

**Author:** Paul E. McKenney &lt;[paulmck@linux.ibm.com](<mailto:paulmck@linux.ibm.com>)&gt;

Linux provides a number of features that can be used to implement circular buffering.  There are two sets of such features:

> 1. Convenience functions for determining information about power-of-2 sized buffers.
>
> 2. Memory barriers for when the producer and the consumer of objects in the buffer don't want to share a lock.

To use these facilities, as discussed below, there needs to be just one producer and just one consumer.  It is possible to handle multiple producers by serialising them, and to handle multiple consumers by serialising them.

<!-- Contents:

(*) What is a circular buffer?

(*) Measuring power-of-2 buffers.

(*) Using memory barriers with circular buffers.
    - The producer.
    - The consumer. -->

<a id="rst-what-is-a-circular-buffer"></a>

## What is a circular buffer?

First of all, what is a circular buffer?  A circular buffer is a buffer of fixed, finite size into which there are two indices:

> 1. A 'head' index - the point at which the producer inserts items into the buffer.
>
> 2. A 'tail' index - the point at which the consumer finds the next item in the buffer.

Typically when the tail pointer is equal to the head pointer, the buffer is empty; and the buffer is full when the head pointer is one less than the tail pointer.

The head index is incremented when items are added, and the tail index when items are removed.  The tail index should never jump the head index, and both indices should be wrapped to 0 when they reach the end of the buffer, thus allowing an infinite amount of data to flow through the buffer.

Typically, items will all be of the same unit size, but this isn't strictly required to use the techniques below.  The indices can be increased by more than 1 if multiple items or variable-sized items are to be included in the buffer, provided that neither index overtakes the other.  The implementer must be careful, however, as a region more than one unit in size may wrap the end of the buffer and be broken into two segments.

<a id="rst-measuring-power-of-2-buffers"></a>

## Measuring power-of-2 buffers

Calculation of the occupancy or the remaining capacity of an arbitrarily sized circular buffer would normally be a slow operation, requiring the use of a modulus (divide) instruction.  However, if the buffer is of a power-of-2 size, then a much quicker bitwise-AND instruction can be used instead.

Linux provides a set of macros for handling power-of-2 circular buffers.  These can be made use of by:



```text
#include <linux/circ_buf.h>
```

The macros are:

> 1. Measure the remaining capacity of a buffer:
>
>
>
>    ```text
>    CIRC_SPACE(head_index, tail_index, buffer_size);
>    ```
>
>    This returns the amount of space left in the buffer\[1\] into which items can be inserted.
>
> 2. Measure the maximum consecutive immediate space in a buffer:
>
>
>
>    ```text
>    CIRC_SPACE_TO_END(head_index, tail_index, buffer_size);
>    ```
>
>    This returns the amount of consecutive space left in the buffer\[1\] into which items can be immediately inserted without having to wrap back to the beginning of the buffer.
>
> 3. Measure the occupancy of a buffer:
>
>
>
>    ```text
>    CIRC_CNT(head_index, tail_index, buffer_size);
>    ```
>
>    This returns the number of items currently occupying a buffer\[2\].
>
> 4. Measure the non-wrapping occupancy of a buffer:
>
>
>
>    ```text
>    CIRC_CNT_TO_END(head_index, tail_index, buffer_size);
>    ```
>
>    This returns the number of consecutive items\[2\] that can be extracted from the buffer without having to wrap back to the beginning of the buffer.

Each of these macros will nominally return a value between 0 and buffer_size-1, however:

> 1. CIRC_SPACE\*() are intended to be used in the producer.  To the producer they will return a lower bound as the producer controls the head index, but the consumer may still be depleting the buffer on another CPU and moving the tail index.
>
>    To the consumer it will show an upper bound as the producer may be busy depleting the space.
>
> 2. CIRC_CNT\*() are intended to be used in the consumer.  To the consumer they will return a lower bound as the consumer controls the tail index, but the producer may still be filling the buffer on another CPU and moving the head index.
>
>    To the producer it will show an upper bound as the consumer may be busy emptying the buffer.
>
> 3. To a third party, the order in which the writes to the indices by the producer and consumer become visible cannot be guaranteed as they are independent and may be made on different CPUs - so the result in such a situation will merely be a guess, and may even be negative.

<a id="rst-using-memory-barriers-with-circular-buffers"></a>

## Using memory barriers with circular buffers

By using memory barriers in conjunction with circular buffers, you can avoid the need to:

> 1. use a single lock to govern access to both ends of the buffer, thus allowing the buffer to be filled and emptied at the same time; and
>
> 2. use atomic counter operations.

There are two sides to this: the producer that fills the buffer, and the consumer that empties it.  Only one thing should be filling a buffer at any one time, and only one thing should be emptying a buffer at any one time, but the two sides can operate simultaneously.

<a id="rst-the-producer"></a>

### The producer

The producer will look something like this:



```text
spin_lock(&producer_lock);

unsigned long head = buffer->head;
/* The spin_unlock() and next spin_lock() provide needed ordering. */
unsigned long tail = READ_ONCE(buffer->tail);

if (CIRC_SPACE(head, tail, buffer->size) >= 1) {
        /* insert one item into the buffer */
        struct item *item = buffer[head];

        produce_item(item);

        smp_store_release(buffer->head,
                          (head + 1) & (buffer->size - 1));

        /* wake_up() will make sure that the head is committed before
         * waking anyone up */
        wake_up(consumer);
}

spin_unlock(&producer_lock);
```

This will instruct the CPU that the contents of the new item must be written before the head index makes it available to the consumer and then instructs the CPU that the revised head index must be written before the consumer is woken.

Note that wake_up() does not guarantee any sort of barrier unless something is actually awakened.  We therefore cannot rely on it for ordering.  However, there is always one element of the array left empty.  Therefore, the producer must produce two elements before it could possibly corrupt the element currently being read by the consumer.  Therefore, the unlock-lock pair between consecutive invocations of the consumer provides the necessary ordering between the read of the index indicating that the consumer has vacated a given element and the write by the producer to that same element.

<a id="rst-the-consumer"></a>

### The Consumer

The consumer will look something like this:



```text
spin_lock(&consumer_lock);

/* Read index before reading contents at that index. */
unsigned long head = smp_load_acquire(buffer->head);
unsigned long tail = buffer->tail;

if (CIRC_CNT(head, tail, buffer->size) >= 1) {

        /* extract one item from the buffer */
        struct item *item = buffer[tail];

        consume_item(item);

        /* Finish reading descriptor before incrementing tail. */
        smp_store_release(buffer->tail,
                          (tail + 1) & (buffer->size - 1));
}

spin_unlock(&consumer_lock);
```

This will instruct the CPU to make sure the index is up to date before reading the new item, and then it shall make sure the CPU has finished reading the item before it writes the new tail pointer, which will erase the item.

Note the use of READ_ONCE() and smp_load_acquire() to read the opposition index.  This prevents the compiler from discarding and reloading its cached value.  This isn't strictly needed if you can be sure that the opposition index will \_only\_ be used the once. The smp_load_acquire() additionally forces the CPU to order against subsequent memory references.  Similarly, smp_store_release() is used in both algorithms to write the thread's index.  This documents the fact that we are writing to something that can be read concurrently, prevents the compiler from tearing the store, and enforces ordering against previous accesses.

<a id="rst-further-reading"></a>

## Further reading

See also [Documentation/memory-barriers.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/memory-barriers.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for a description of Linux's memory barrier facilities.

---

# Scope-based Cleanup Helpers

_Peios Kernel / Internals / Core APIs_

> Reference for Scope-based Cleanup Helpers.

<a id="rst-scope-based-cleanup-helpers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


The "goto error" pattern is notorious for introducing subtle resource
leaks. It is tedious and error prone to add new resource acquisition
constraints into code paths that already have several unwind
conditions. The "cleanup" helpers enable the compiler to help with
this tedium and can aid in maintaining LIFO (last in first out)
unwind ordering to avoid unintentional leaks.

As drivers make up the majority of the kernel code base, here is an
example of using these helpers to clean up PCI drivers. The target of
the cleanups are occasions where a goto is used to unwind a device
reference ([`pci_dev_put()`](/kernel/hardware/driver-api/pci/pci.md#c-pci_dev_put)), or unlock the device (`pci_dev_unlock()`)
before returning.

The `DEFINE_FREE()` macro can arrange for PCI device references to be
dropped when the associated variable goes out of scope:

```text
DEFINE_FREE(pci_dev_put, struct pci_dev *, if (_T) pci_dev_put(_T))
...
struct pci_dev *dev __free(pci_dev_put) =
        pci_get_slot(parent, PCI_DEVFN(0, 0));
```

The above will automatically call [`pci_dev_put()`](/kernel/hardware/driver-api/pci/pci.md#c-pci_dev_put) if **dev** is non-NULL
when **dev** goes out of scope (automatic variable scope). If a function
wants to invoke [`pci_dev_put()`](/kernel/hardware/driver-api/pci/pci.md#c-pci_dev_put) on error, but return **dev** (i.e. without
freeing it) on success, it can do:

```text
return no_free_ptr(dev);
```

...or::

return_ptr(dev);

The `DEFINE_GUARD()` macro can arrange for the PCI device lock to be
dropped when the scope where `guard()` is invoked ends:

```text
DEFINE_GUARD(pci_dev, struct pci_dev *, pci_dev_lock(_T), pci_dev_unlock(_T))
...
guard(pci_dev)(dev);
```

The lifetime of the lock obtained by the `guard()` helper follows the
scope of automatic variable declaration. Take the following example:

```text
func(...)
{
        if (...) {
                ...
                guard(pci_dev)(dev); // pci_dev_lock() invoked here
                ...
        } // <- implied pci_dev_unlock() triggered here
}
```

Observe the lock is held for the remainder of the "if ()" block not
the remainder of "`func()`".

The `ACQUIRE()` macro can be used in all places that `guard()` can be
used and additionally support conditional locks:

```text
DEFINE_GUARD_COND(pci_dev, _try, pci_dev_trylock(_T))
...
ACQUIRE(pci_dev_try, lock)(dev);
rc = ACQUIRE_ERR(pci_dev_try, &lock);
if (rc)
        return rc;
// @lock is held
```

Now, when a function uses both `__free()` and `guard()`/`ACQUIRE()`, or
multiple instances of `__free()`, the LIFO order of variable definition
order matters. GCC documentation says:

"When multiple variables in the same scope have cleanup attributes,
at exit from the scope their associated cleanup functions are run in
reverse order of definition (last defined, first cleanup)."

When the unwind order matters it requires that variables be defined
mid-function scope rather than at the top of the file.  Take the
following example and notice the bug highlighted by "!!":

```text
LIST_HEAD(list);
DEFINE_MUTEX(lock);

struct object {
        struct list_head node;
};

static struct object *alloc_add(void)
{
        struct object *obj;

        lockdep_assert_held(&lock);
        obj = kzalloc(sizeof(*obj), GFP_KERNEL);
        if (obj) {
                LIST_HEAD_INIT(&obj->node);
                list_add(obj->node, &list):
        }
        return obj;
}

static void remove_free(struct object *obj)
{
        lockdep_assert_held(&lock);
        list_del(&obj->node);
        kfree(obj);
}

DEFINE_FREE(remove_free, struct object *, if (_T) remove_free(_T))
static int init(void)
{
        struct object *obj __free(remove_free) = NULL;
        int err;

        guard(mutex)(&lock);
        obj = alloc_add();

        if (!obj)
                return -ENOMEM;

        err = other_init(obj);
        if (err)
                return err; // remove_free() called without the lock!!

        no_free_ptr(obj);
        return 0;
}
```

That bug is fixed by changing `init()` to call `guard()` and define +
initialize **obj** in this order:

```text
guard(mutex)(&lock);
struct object *obj __free(remove_free) = alloc_add();
```

Given that the "__free(...) = NULL" pattern for variables defined at
the top of the function poses this potential interdependency problem
the recommendation is to always define and assign variables in one
statement and not group variable definitions at the top of the
function when `__free()` is used.

Lastly, given that the benefit of cleanup helpers is removal of
"goto", and that the "goto" statement can jump between scopes, the
expectation is that usage of "goto" and cleanup helpers is never
mixed in the same function. I.e. for a given routine, convert all
resources that need a "goto" cleanup to scope-based cleanup, or
convert none of them.

---

# CPU hotplug in the Kernel

_Peios Kernel / Internals / Core APIs_

> Modern advances in system architectures have introduced advanced error reporting and correction capabilities in processors. There are couple OEMS that support NUMA hardware which are hot pluggable as well, where physical node insertion and…

<a id="rst-cpu-hotplug-in-the-kernel"></a>

**Date:** September, 2021

**Author:** Sebastian Andrzej Siewior &lt;[bigeasy@linutronix.de](<mailto:bigeasy@linutronix.de>)&gt;, Rusty Russell &lt;[rusty@rustcorp.com.au](<mailto:rusty@rustcorp.com.au>)&gt;, Srivatsa Vaddagiri &lt;[vatsa@in.ibm.com](<mailto:vatsa@in.ibm.com>)&gt;, Ashok Raj &lt;[ashok.raj@intel.com](<mailto:ashok.raj@intel.com>)&gt;, Joel Schopp &lt;[jschopp@austin.ibm.com](<mailto:jschopp@austin.ibm.com>)&gt;, Thomas Gleixner &lt;[tglx@kernel.org](<mailto:tglx@kernel.org>)&gt;

<a id="rst-introduction"></a>

## Introduction

Modern advances in system architectures have introduced advanced error reporting and correction capabilities in processors. There are couple OEMS that support NUMA hardware which are hot pluggable as well, where physical node insertion and removal require support for CPU hotplug.

Such advances require CPUs available to a kernel to be removed either for provisioning reasons, or for RAS purposes to keep an offending CPU off system execution path. Hence the need for CPU hotplug support in the Linux kernel.

A more novel use of CPU-hotplug support is its use today in suspend resume support for SMP. Dual-core and HT support makes even a laptop run SMP kernels which didn't support these methods.

<a id="rst-command-line-switches"></a>

## Command Line Switches

- **`maxcpus=n`**

  Restrict boot time CPUs to *n*. Say if you have four CPUs, using `maxcpus=2` will only boot two. You can choose to bring the other CPUs later online.

- **`nr_cpus=n`**

  Restrict the total amount of CPUs the kernel will support. If the number supplied here is lower than the number of physically available CPUs, then those CPUs can not be brought online later.

- **`possible_cpus=n`**

  This option sets `possible_cpus` bits in `cpu_possible_mask`.

  This option is limited to the X86 and S390 architecture.

- **`cpu0_hotplug`**

  Allow to shutdown CPU0.

  This option is limited to the X86 architecture.

<a id="rst-cpu-maps"></a>

## CPU maps

- **`cpu_possible_mask`**

  Bitmap of possible CPUs that can ever be available in the system. This is used to allocate some boot time memory for per_cpu variables that aren't designed to grow/shrink as CPUs are made available or removed. Once set during boot time discovery phase, the map is static, i.e no bits are added or removed anytime. Trimming it accurately for your system needs upfront can save some boot time memory.

- **`cpu_online_mask`**

  Bitmap of all CPUs currently online. Its set in `__cpu_up()` after a CPU is available for kernel scheduling and ready to receive interrupts from devices. Its cleared when a CPU is brought down using `__cpu_disable()`, before which all OS services including interrupts are migrated to another target CPU.

- **`cpu_present_mask`**

  Bitmap of CPUs currently present in the system. Not all of them may be online. When physical hotplug is processed by the relevant subsystem (e.g ACPI) can change and new bit either be added or removed from the map depending on the event is hot-add/hot-remove. There are currently no locking rules as of now. Typical usage is to init topology during boot, at which time hotplug is disabled.

You really don't need to manipulate any of the system CPU maps. They should be read-only for most use. When setting up per-cpu resources almost always use `cpu_possible_mask` or `for_each_possible_cpu()` to iterate. To macro `for_each_cpu()` can be used to iterate over a custom CPU mask.

Never use anything other than `cpumask_t` to represent bitmap of CPUs.

<a id="rst-using-cpu-hotplug"></a>

## Using CPU hotplug

The kernel option *CONFIG_HOTPLUG_CPU* needs to be enabled. It is currently available on multiple architectures including ARM, MIPS, PowerPC and X86. The configuration is done via the sysfs interface:



```text
$ ls -lh /sys/devices/system/cpu
total 0
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu0
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu1
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu2
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu3
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu4
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu5
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu6
drwxr-xr-x  9 root root    0 Dec 21 16:33 cpu7
drwxr-xr-x  2 root root    0 Dec 21 16:33 hotplug
-r--r--r--  1 root root 4.0K Dec 21 16:33 offline
-r--r--r--  1 root root 4.0K Dec 21 16:33 online
-r--r--r--  1 root root 4.0K Dec 21 16:33 possible
-r--r--r--  1 root root 4.0K Dec 21 16:33 present
```

The files *offline*, *online*, *possible*, *present* represent the CPU masks. Each CPU folder contains an *online* file which controls the logical on (1) and off (0) state. To logically shutdown CPU4:



```text
$ echo 0 > /sys/devices/system/cpu/cpu4/online
 smpboot: CPU 4 is now offline
```

Once the CPU is shutdown, it will be removed from */proc/interrupts*, */proc/cpuinfo* and should also not be shown visible by the *top* command. To bring CPU4 back online:



```text
$ echo 1 > /sys/devices/system/cpu/cpu4/online
smpboot: Booting Node 0 Processor 4 APIC 0x1
```

The CPU is usable again. This should work on all CPUs, but CPU0 is often special and excluded from CPU hotplug.

<a id="rst-the-cpu-hotplug-coordination"></a>

## The CPU hotplug coordination

<a id="rst-the-offline-case"></a>

### The offline case

Once a CPU has been logically shutdown the teardown callbacks of registered hotplug states will be invoked, starting with `CPUHP_ONLINE` and terminating at state `CPUHP_OFFLINE`. This includes:

- If tasks are frozen due to a suspend operation then *cpuhp_tasks_frozen* will be set to true.

- All processes are migrated away from this outgoing CPU to new CPUs. The new CPU is chosen from each process' current cpuset, which may be a subset of all online CPUs.

- All interrupts targeted to this CPU are migrated to a new CPU

- timers are also migrated to a new CPU

- Once all services are migrated, kernel calls an arch specific routine `__cpu_disable()` to perform arch specific cleanup.

<a id="rst-the-cpu-hotplug-api"></a>

## The CPU hotplug API

<a id="rst-cpu-hotplug-state-machine"></a>

### CPU hotplug state machine

CPU hotplug uses a trivial state machine with a linear state space from CPUHP_OFFLINE to CPUHP_ONLINE. Each state has a startup and a teardown callback.

When a CPU is onlined, the startup callbacks are invoked sequentially until the state CPUHP_ONLINE is reached. They can also be invoked when the callbacks of a state are set up or an instance is added to a multi-instance state.

When a CPU is offlined the teardown callbacks are invoked in the reverse order sequentially until the state CPUHP_OFFLINE is reached. They can also be invoked when the callbacks of a state are removed or an instance is removed from a multi-instance state.

If a usage site requires only a callback in one direction of the hotplug operations (CPU online or CPU offline) then the other not-required callback can be set to NULL when the state is set up.

The state space is divided into three sections:

- The PREPARE section

  The PREPARE section covers the state space from CPUHP_OFFLINE to CPUHP_BRINGUP_CPU.

  The startup callbacks in this section are invoked before the CPU is started during a CPU online operation. The teardown callbacks are invoked after the CPU has become dysfunctional during a CPU offline operation.

  The callbacks are invoked on a control CPU as they can't obviously run on the hotplugged CPU which is either not yet started or has become dysfunctional already.

  The startup callbacks are used to setup resources which are required to bring a CPU successfully online. The teardown callbacks are used to free resources or to move pending work to an online CPU after the hotplugged CPU became dysfunctional.

  The startup callbacks are allowed to fail. If a callback fails, the CPU online operation is aborted and the CPU is brought down to the previous state (usually CPUHP_OFFLINE) again.

  The teardown callbacks in this section are not allowed to fail.

- The STARTING section

  The STARTING section covers the state space between CPUHP_BRINGUP_CPU + 1 and CPUHP_AP_ONLINE.

  The startup callbacks in this section are invoked on the hotplugged CPU with interrupts disabled during a CPU online operation in the early CPU setup code. The teardown callbacks are invoked with interrupts disabled on the hotplugged CPU during a CPU offline operation shortly before the CPU is completely shut down.

  The callbacks in this section are not allowed to fail.

  The callbacks are used for low level hardware initialization/shutdown and for core subsystems.

- The ONLINE section

  The ONLINE section covers the state space between CPUHP_AP_ONLINE + 1 and CPUHP_ONLINE.

  The startup callbacks in this section are invoked on the hotplugged CPU during a CPU online operation. The teardown callbacks are invoked on the hotplugged CPU during a CPU offline operation.

  The callbacks are invoked in the context of the per CPU hotplug thread, which is pinned on the hotplugged CPU. The callbacks are invoked with interrupts and preemption enabled.

  The callbacks are allowed to fail. When a callback fails the hotplug operation is aborted and the CPU is brought back to the previous state.

<a id="rst-cpu-online-offline-operations"></a>

### CPU online/offline operations

A successful online operation looks like this:



```text
[CPUHP_OFFLINE]
[CPUHP_OFFLINE + 1]->startup()       -> success
[CPUHP_OFFLINE + 2]->startup()       -> success
[CPUHP_OFFLINE + 3]                  -> skipped because startup == NULL
...
[CPUHP_BRINGUP_CPU]->startup()       -> success
=== End of PREPARE section
[CPUHP_BRINGUP_CPU + 1]->startup()   -> success
...
[CPUHP_AP_ONLINE]->startup()         -> success
=== End of STARTUP section
[CPUHP_AP_ONLINE + 1]->startup()     -> success
...
[CPUHP_ONLINE - 1]->startup()        -> success
[CPUHP_ONLINE]
```

A successful offline operation looks like this:



```text
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown()       -> success
...
[CPUHP_AP_ONLINE + 1]->teardown()    -> success
=== Start of STARTUP section
[CPUHP_AP_ONLINE]->teardown()        -> success
...
[CPUHP_BRINGUP_ONLINE - 1]->teardown()
...
=== Start of PREPARE section
[CPUHP_BRINGUP_CPU]->teardown()
[CPUHP_OFFLINE + 3]->teardown()
[CPUHP_OFFLINE + 2]                  -> skipped because teardown == NULL
[CPUHP_OFFLINE + 1]->teardown()
[CPUHP_OFFLINE]
```

A failed online operation looks like this:



```text
[CPUHP_OFFLINE]
[CPUHP_OFFLINE + 1]->startup()       -> success
[CPUHP_OFFLINE + 2]->startup()       -> success
[CPUHP_OFFLINE + 3]                  -> skipped because startup == NULL
...
[CPUHP_BRINGUP_CPU]->startup()       -> success
=== End of PREPARE section
[CPUHP_BRINGUP_CPU + 1]->startup()   -> success
...
[CPUHP_AP_ONLINE]->startup()         -> success
=== End of STARTUP section
[CPUHP_AP_ONLINE + 1]->startup()     -> success
---
[CPUHP_AP_ONLINE + N]->startup()     -> fail
[CPUHP_AP_ONLINE + (N - 1)]->teardown()
...
[CPUHP_AP_ONLINE + 1]->teardown()
=== Start of STARTUP section
[CPUHP_AP_ONLINE]->teardown()
...
[CPUHP_BRINGUP_ONLINE - 1]->teardown()
...
=== Start of PREPARE section
[CPUHP_BRINGUP_CPU]->teardown()
[CPUHP_OFFLINE + 3]->teardown()
[CPUHP_OFFLINE + 2]                  -> skipped because teardown == NULL
[CPUHP_OFFLINE + 1]->teardown()
[CPUHP_OFFLINE]
```

A failed offline operation looks like this:



```text
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown()       -> success
...
[CPUHP_ONLINE - N]->teardown()       -> fail
[CPUHP_ONLINE - (N - 1)]->startup()
...
[CPUHP_ONLINE - 1]->startup()
[CPUHP_ONLINE]
```

Recursive failures cannot be handled sensibly. Look at the following example of a recursive fail due to a failed offline operation:



```text
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown()       -> success
...
[CPUHP_ONLINE - N]->teardown()       -> fail
[CPUHP_ONLINE - (N - 1)]->startup()  -> success
[CPUHP_ONLINE - (N - 2)]->startup()  -> fail
```

The CPU hotplug state machine stops right here and does not try to go back down again because that would likely result in an endless loop:



```text
[CPUHP_ONLINE - (N - 1)]->teardown() -> success
[CPUHP_ONLINE - N]->teardown()       -> fail
[CPUHP_ONLINE - (N - 1)]->startup()  -> success
[CPUHP_ONLINE - (N - 2)]->startup()  -> fail
[CPUHP_ONLINE - (N - 1)]->teardown() -> success
[CPUHP_ONLINE - N]->teardown()       -> fail
```

Lather, rinse and repeat. In this case the CPU left in state:



```text
[CPUHP_ONLINE - (N - 1)]
```

which at least lets the system make progress and gives the user a chance to debug or even resolve the situation.

<a id="rst-allocating-a-state"></a>

### Allocating a state

There are two ways to allocate a CPU hotplug state:

- Static allocation

  Static allocation has to be used when the subsystem or driver has ordering requirements versus other CPU hotplug states. E.g. the PERF core startup callback has to be invoked before the PERF driver startup callbacks during a CPU online operation. During a CPU offline operation the driver teardown callbacks have to be invoked before the core teardown callback. The statically allocated states are described by constants in the cpuhp_state enum which can be found in include/linux/cpuhotplug.h.

  Insert the state into the enum at the proper place so the ordering requirements are fulfilled. The state constant has to be used for state setup and removal.

  Static allocation is also required when the state callbacks are not set up at runtime and are part of the initializer of the CPU hotplug state array in kernel/cpu.c.

- Dynamic allocation

  When there are no ordering requirements for the state callbacks then dynamic allocation is the preferred method. The state number is allocated by the setup function and returned to the caller on success.

  Only the PREPARE and ONLINE sections provide a dynamic allocation range. The STARTING section does not as most of the callbacks in that section have explicit ordering requirements.

<a id="rst-setup-of-a-cpu-hotplug-state"></a>

### Setup of a CPU hotplug state

The core code provides the following functions to setup a state:

- cpuhp_setup_state(state, name, startup, teardown)

- cpuhp_setup_state_nocalls(state, name, startup, teardown)

- cpuhp_setup_state_cpuslocked(state, name, startup, teardown)

- cpuhp_setup_state_nocalls_cpuslocked(state, name, startup, teardown)

For cases where a driver or a subsystem has multiple instances and the same CPU hotplug state callbacks need to be invoked for each instance, the CPU hotplug core provides multi-instance support. The advantage over driver specific instance lists is that the instance related functions are fully serialized against CPU hotplug operations and provide the automatic invocations of the state callbacks on add and removal. To set up such a multi-instance state the following function is available:

- cpuhp_setup_state_multi(state, name, startup, teardown)

The @state argument is either a statically allocated state or one of the constants for dynamically allocated states - CPUHP_BP_PREPARE_DYN, CPUHP_AP_ONLINE_DYN - depending on the state section (PREPARE, ONLINE) for which a dynamic state should be allocated.

The @name argument is used for sysfs output and for instrumentation. The naming convention is "subsys:mode" or "subsys/driver:mode", e.g. "perf:mode" or "perf/x86:mode". The common mode names are:


<table>
<tbody>
<tr>
<td>


prepare

</td>
<td>


For states in the PREPARE section

</td>
</tr>
<tr>
<td>


dead

</td>
<td>


For states in the PREPARE section which do not provide a startup callback

</td>
</tr>
<tr>
<td>


starting

</td>
<td>


For states in the STARTING section

</td>
</tr>
<tr>
<td>


dying

</td>
<td>


For states in the STARTING section which do not provide a startup callback

</td>
</tr>
<tr>
<td>


online

</td>
<td>


For states in the ONLINE section

</td>
</tr>
<tr>
<td>


offline

</td>
<td>


For states in the ONLINE section which do not provide a startup callback

</td>
</tr>
</tbody>
</table>

As the @name argument is only used for sysfs and instrumentation other mode descriptors can be used as well if they describe the nature of the state better than the common ones.

Examples for @name arguments: "perf/online", "perf/x86:prepare", "RCU/tree:dying", "sched/waitempty"

The @startup argument is a function pointer to the callback which should be invoked during a CPU online operation. If the usage site does not require a startup callback set the pointer to NULL.

The @teardown argument is a function pointer to the callback which should be invoked during a CPU offline operation. If the usage site does not require a teardown callback set the pointer to NULL.

The functions differ in the way how the installed callbacks are treated:

> - cpuhp_setup_state_nocalls(), cpuhp_setup_state_nocalls_cpuslocked() and cpuhp_setup_state_multi() only install the callbacks
>
> - cpuhp_setup_state() and cpuhp_setup_state_cpuslocked() install the callbacks and invoke the @startup callback (if not NULL) for all online CPUs which have currently a state greater than the newly installed state. Depending on the state section the callback is either invoked on the current CPU (PREPARE section) or on each online CPU (ONLINE section) in the context of the CPU's hotplug thread.
>
>   If a callback fails for CPU N then the teardown callback for CPU 0 .. N-1 is invoked to rollback the operation. The state setup fails, the callbacks for the state are not installed and in case of dynamic allocation the allocated state is freed.

The state setup and the callback invocations are serialized against CPU hotplug operations. If the setup function has to be called from a CPU hotplug read locked region, then the \_cpuslocked() variants have to be used. These functions cannot be used from within CPU hotplug callbacks.

- **The function return values:**


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Statically allocated state was successfully set up

  </td>
  </tr>
  <tr>
  <td>


  &gt;0

  </td>
  <td>


  Dynamically allocated state was successfully set up.

  The returned number is the state number which was allocated. If the state callbacks have to be removed later, e.g. module removal, then this number has to be saved by the caller and used as @state argument for the state remove function. For multi-instance states the dynamically allocated state number is also required as @state argument for the instance add/remove operations.

  </td>
  </tr>
  <tr>
  <td>


  &lt;0

  </td>
  <td>


  Operation failed

  </td>
  </tr>
  </tbody>
  </table>

<a id="rst-removal-of-a-cpu-hotplug-state"></a>

### Removal of a CPU hotplug state

To remove a previously set up state, the following functions are provided:

- cpuhp_remove_state(state)

- cpuhp_remove_state_nocalls(state)

- cpuhp_remove_state_nocalls_cpuslocked(state)

- cpuhp_remove_multi_state(state)

The @state argument is either a statically allocated state or the state number which was allocated in the dynamic range by cpuhp_setup_state\*(). If the state is in the dynamic range, then the state number is freed and available for dynamic allocation again.

The functions differ in the way how the installed callbacks are treated:

> - cpuhp_remove_state_nocalls(), cpuhp_remove_state_nocalls_cpuslocked() and cpuhp_remove_multi_state() only remove the callbacks.
>
> - cpuhp_remove_state() removes the callbacks and invokes the teardown callback (if not NULL) for all online CPUs which have currently a state greater than the removed state. Depending on the state section the callback is either invoked on the current CPU (PREPARE section) or on each online CPU (ONLINE section) in the context of the CPU's hotplug thread.
>
>   In order to complete the removal, the teardown callback should not fail.

The state removal and the callback invocations are serialized against CPU hotplug operations. If the remove function has to be called from a CPU hotplug read locked region, then the \_cpuslocked() variants have to be used. These functions cannot be used from within CPU hotplug callbacks.

If a multi-instance state is removed then the caller has to remove all instances first.

<a id="rst-multi-instance-state-instance-management"></a>

### Multi-Instance state instance management

Once the multi-instance state is set up, instances can be added to the state:

> - cpuhp_state_add_instance(state, node)
>
> - cpuhp_state_add_instance_nocalls(state, node)

The @state argument is either a statically allocated state or the state number which was allocated in the dynamic range by cpuhp_setup_state_multi().

The @node argument is a pointer to an hlist_node which is embedded in the instance's data structure. The pointer is handed to the multi-instance state callbacks and can be used by the callback to retrieve the instance via container_of().

The functions differ in the way how the installed callbacks are treated:

> - cpuhp_state_add_instance_nocalls() and only adds the instance to the multi-instance state's node list.
>
> - cpuhp_state_add_instance() adds the instance and invokes the startup callback (if not NULL) associated with @state for all online CPUs which have currently a state greater than @state. The callback is only invoked for the to be added instance. Depending on the state section the callback is either invoked on the current CPU (PREPARE section) or on each online CPU (ONLINE section) in the context of the CPU's hotplug thread.
>
>   If a callback fails for CPU N then the teardown callback for CPU 0 .. N-1 is invoked to rollback the operation, the function fails and the instance is not added to the node list of the multi-instance state.

To remove an instance from the state's node list these functions are available:

> - cpuhp_state_remove_instance(state, node)
>
> - cpuhp_state_remove_instance_nocalls(state, node)

The arguments are the same as for the cpuhp_state_add_instance\*() variants above.

The functions differ in the way how the installed callbacks are treated:

> - cpuhp_state_remove_instance_nocalls() only removes the instance from the state's node list.
>
> - cpuhp_state_remove_instance() removes the instance and invokes the teardown callback (if not NULL) associated with @state for all online CPUs which have currently a state greater than @state.  The callback is only invoked for the to be removed instance.  Depending on the state section the callback is either invoked on the current CPU (PREPARE section) or on each online CPU (ONLINE section) in the context of the CPU's hotplug thread.
>
>   In order to complete the removal, the teardown callback should not fail.

The node list add/remove operations and the callback invocations are serialized against CPU hotplug operations. These functions cannot be used from within CPU hotplug callbacks and CPU hotplug read locked regions.

<a id="rst-examples"></a>

### Examples

Setup and teardown a statically allocated state in the STARTING section for notifications on online and offline operations:



```text
ret = cpuhp_setup_state(CPUHP_SUBSYS_STARTING, "subsys:starting", subsys_cpu_starting, subsys_cpu_dying);
if (ret < 0)
     return ret;
....
cpuhp_remove_state(CPUHP_SUBSYS_STARTING);
```

Setup and teardown a dynamically allocated state in the ONLINE section for notifications on offline operations:



```text
state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "subsys:offline", NULL, subsys_cpu_offline);
if (state < 0)
    return state;
....
cpuhp_remove_state(state);
```

Setup and teardown a dynamically allocated state in the ONLINE section for notifications on online operations without invoking the callbacks:



```text
state = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, NULL);
if (state < 0)
    return state;
....
cpuhp_remove_state_nocalls(state);
```

Setup, use and teardown a dynamically allocated multi-instance state in the ONLINE section for notifications on online and offline operation:



```text
state = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, subsys_cpu_offline);
if (state < 0)
    return state;
....
ret = cpuhp_state_add_instance(state, &inst1->node);
if (ret)
     return ret;
....
ret = cpuhp_state_add_instance(state, &inst2->node);
if (ret)
     return ret;
....
cpuhp_remove_instance(state, &inst1->node);
....
cpuhp_remove_instance(state, &inst2->node);
....
cpuhp_remove_multi_state(state);
```

<a id="rst-testing-of-hotplug-states"></a>

## Testing of hotplug states

One way to verify whether a custom state is working as expected or not is to shutdown a CPU and then put it online again. It is also possible to put the CPU to certain state (for instance *CPUHP_AP_ONLINE*) and then go back to *CPUHP_ONLINE*. This would simulate an error one state after *CPUHP_AP_ONLINE* which would lead to rollback to the online state.

All registered states are enumerated in `/sys/devices/system/cpu/hotplug/states`



```text
$ tail /sys/devices/system/cpu/hotplug/states
138: mm/vmscan:online
139: mm/vmstat:online
140: lib/percpu_cnt:online
141: acpi/cpu-drv:online
142: base/cacheinfo:online
143: virtio/net:online
144: x86/mce:online
145: printk:online
168: sched:active
169: online
```

To rollback CPU4 to `lib/percpu_cnt:online` and back online just issue:



```text
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
$ echo 140 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
140
```

It is important to note that the teardown callback of state 140 have been invoked. And now get back online:



```text
$ echo 169 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
```

With trace events enabled, the individual steps are visible, too:



```text
#  TASK-PID   CPU#    TIMESTAMP  FUNCTION
#     | |       |        |         |
    bash-394  [001]  22.976: cpuhp_enter: cpu: 0004 target: 140 step: 169 (cpuhp_kick_ap_work)
 cpuhp/4-31   [004]  22.977: cpuhp_enter: cpu: 0004 target: 140 step: 168 (sched_cpu_deactivate)
 cpuhp/4-31   [004]  22.990: cpuhp_exit:  cpu: 0004  state: 168 step: 168 ret: 0
 cpuhp/4-31   [004]  22.991: cpuhp_enter: cpu: 0004 target: 140 step: 144 (mce_cpu_pre_down)
 cpuhp/4-31   [004]  22.992: cpuhp_exit:  cpu: 0004  state: 144 step: 144 ret: 0
 cpuhp/4-31   [004]  22.993: cpuhp_multi_enter: cpu: 0004 target: 140 step: 143 (virtnet_cpu_down_prep)
 cpuhp/4-31   [004]  22.994: cpuhp_exit:  cpu: 0004  state: 143 step: 143 ret: 0
 cpuhp/4-31   [004]  22.995: cpuhp_enter: cpu: 0004 target: 140 step: 142 (cacheinfo_cpu_pre_down)
 cpuhp/4-31   [004]  22.996: cpuhp_exit:  cpu: 0004  state: 142 step: 142 ret: 0
    bash-394  [001]  22.997: cpuhp_exit:  cpu: 0004  state: 140 step: 169 ret: 0
    bash-394  [005]  95.540: cpuhp_enter: cpu: 0004 target: 169 step: 140 (cpuhp_kick_ap_work)
 cpuhp/4-31   [004]  95.541: cpuhp_enter: cpu: 0004 target: 169 step: 141 (acpi_soft_cpu_online)
 cpuhp/4-31   [004]  95.542: cpuhp_exit:  cpu: 0004  state: 141 step: 141 ret: 0
 cpuhp/4-31   [004]  95.543: cpuhp_enter: cpu: 0004 target: 169 step: 142 (cacheinfo_cpu_online)
 cpuhp/4-31   [004]  95.544: cpuhp_exit:  cpu: 0004  state: 142 step: 142 ret: 0
 cpuhp/4-31   [004]  95.545: cpuhp_multi_enter: cpu: 0004 target: 169 step: 143 (virtnet_cpu_online)
 cpuhp/4-31   [004]  95.546: cpuhp_exit:  cpu: 0004  state: 143 step: 143 ret: 0
 cpuhp/4-31   [004]  95.547: cpuhp_enter: cpu: 0004 target: 169 step: 144 (mce_cpu_online)
 cpuhp/4-31   [004]  95.548: cpuhp_exit:  cpu: 0004  state: 144 step: 144 ret: 0
 cpuhp/4-31   [004]  95.549: cpuhp_enter: cpu: 0004 target: 169 step: 145 (console_cpu_notify)
 cpuhp/4-31   [004]  95.550: cpuhp_exit:  cpu: 0004  state: 145 step: 145 ret: 0
 cpuhp/4-31   [004]  95.551: cpuhp_enter: cpu: 0004 target: 169 step: 168 (sched_cpu_activate)
 cpuhp/4-31   [004]  95.552: cpuhp_exit:  cpu: 0004  state: 168 step: 168 ret: 0
    bash-394  [005]  95.553: cpuhp_exit:  cpu: 0004  state: 169 step: 140 ret: 0
```

As it an be seen, CPU4 went down until timestamp 22.996 and then back up until 95.552. All invoked callbacks including their return codes are visible in the trace.

<a id="rst-architecture-s-requirements"></a>

## Architecture's requirements

The following functions and configurations are required:

- **`CONFIG_HOTPLUG_CPU`**

  This entry needs to be enabled in Kconfig

- **`__cpu_up()`**

  Arch interface to bring up a CPU

- **`__cpu_disable()`**

  Arch interface to shutdown a CPU, no more interrupts can be handled by the kernel after the routine returns. This includes the shutdown of the timer.

- **`__cpu_die()`**

  This actually supposed to ensure death of the CPU. Actually look at some example code in other arch that implement CPU hotplug. The processor is taken down from the `idle()` loop for that specific architecture. `__cpu_die()` typically waits for some per_cpu state to be set, to ensure the processor dead routine is called to be sure positively.

<a id="rst-user-space-notification"></a>

## User Space Notification

After CPU successfully onlined or offline udev events are sent. A udev rule like:



```text
SUBSYSTEM=="cpu", DRIVERS=="processor", DEVPATH=="/devices/system/cpu/*", RUN+="the_hotplug_receiver.sh"
```

will receive all events. A script like:



```text
#!/bin/sh

if [ "${ACTION}" = "offline" ]
then
    echo "CPU ${DEVPATH##*/} offline"

elif [ "${ACTION}" = "online" ]
then
    echo "CPU ${DEVPATH##*/} online"

fi
```

can process the event further.

When changes to the CPUs in the system occur, the sysfs file /sys/devices/system/cpu/crash_hotplug contains '1' if the kernel updates the kdump capture kernel list of CPUs itself (via elfcorehdr and other relevant kexec segment), or '0' if userspace must update the kdump capture kernel list of CPUs.

The availability depends on the CONFIG_HOTPLUG_CPU kernel configuration option.

To skip userspace processing of CPU hot un/plug events for kdump (i.e. the unload-then-reload to obtain a current list of CPUs), this sysfs file can be used in a udev rule as follows:

> SUBSYSTEM=="cpu", ATTRS\{crash_hotplug\}=="1", GOTO="kdump_reload_end"

For a CPU hot un/plug event, if the architecture supports kernel updates of the elfcorehdr (which contains the list of CPUs) and other relevant kexec segments, then the rule skips the unload-then-reload of the kdump capture kernel.

<a id="rst-kernel-inline-documentations-reference"></a>

## Kernel Inline Documentations Reference


#### <a id="c-cpuhp_setup_state"></a>`cpuhp_setup_state()`

```c
int cpuhp_setup_state(enum cpuhp_state state, const char *name, int (*startup)(unsigned int cpu), int (*teardown)(unsigned int cpu))
```

Setup hotplug state callbacks with calling the **startup** callback

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are installed
- `const char *name`: Name of the callback (will be used in debug output)
- `int (*startup)(unsigned int cpu)`: startup callback function or NULL if not required
- `int (*teardown)(unsigned int cpu)`: teardown callback function or NULL if not required

**Description**

Installs the callback functions and invokes the **startup** callback on
the online cpus which have already reached the **state**.

#### <a id="c-cpuhp_setup_state_cpuslocked"></a>`cpuhp_setup_state_cpuslocked()`

```c
int cpuhp_setup_state_cpuslocked(enum cpuhp_state state, const char *name, int (*startup)(unsigned int cpu), int (*teardown)(unsigned int cpu))
```

Setup hotplug state callbacks with calling **startup** callback from a `cpus_read_lock()` held region

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are installed
- `const char *name`: Name of the callback (will be used in debug output)
- `int (*startup)(unsigned int cpu)`: startup callback function or NULL if not required
- `int (*teardown)(unsigned int cpu)`: teardown callback function or NULL if not required

**Description**

Same as [`cpuhp_setup_state()`](#c-cpuhp_setup_state) except that it must be invoked from within a
`cpus_read_lock()` held region.

#### <a id="c-cpuhp_setup_state_nocalls"></a>`cpuhp_setup_state_nocalls()`

```c
int cpuhp_setup_state_nocalls(enum cpuhp_state state, const char *name, int (*startup)(unsigned int cpu), int (*teardown)(unsigned int cpu))
```

Setup hotplug state callbacks without calling the **startup** callback

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are installed
- `const char *name`: Name of the callback.
- `int (*startup)(unsigned int cpu)`: startup callback function or NULL if not required
- `int (*teardown)(unsigned int cpu)`: teardown callback function or NULL if not required

**Description**

Same as [`cpuhp_setup_state()`](#c-cpuhp_setup_state) except that the **startup** callback is not
invoked during installation. NOP if SMP=n or HOTPLUG_CPU=n.

#### <a id="c-cpuhp_setup_state_nocalls_cpuslocked"></a>`cpuhp_setup_state_nocalls_cpuslocked()`

```c
int cpuhp_setup_state_nocalls_cpuslocked(enum cpuhp_state state, const char *name, int (*startup)(unsigned int cpu), int (*teardown)(unsigned int cpu))
```

Setup hotplug state callbacks without invoking the **startup** callback from a `cpus_read_lock()` held region callbacks

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are installed
- `const char *name`: Name of the callback.
- `int (*startup)(unsigned int cpu)`: startup callback function or NULL if not required
- `int (*teardown)(unsigned int cpu)`: teardown callback function or NULL if not required

**Description**

Same as [`cpuhp_setup_state_nocalls()`](#c-cpuhp_setup_state_nocalls) except that it must be invoked from
within a `cpus_read_lock()` held region.

#### <a id="c-cpuhp_setup_state_multi"></a>`cpuhp_setup_state_multi()`

```c
int cpuhp_setup_state_multi(enum cpuhp_state state, const char *name, int (*startup)(unsigned int cpu, struct hlist_node *node), int (*teardown)(unsigned int cpu, struct hlist_node *node))
```

Add callbacks for multi state

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are installed
- `const char *name`: Name of the callback.
- `int (*startup)(unsigned int cpu, struct hlist_node *node)`: startup callback function or NULL if not required
- `int (*teardown)(unsigned int cpu, struct hlist_node *node)`: teardown callback function or NULL if not required

**Description**

Sets the internal multi_instance flag and prepares a state to work as a multi
instance callback. No callbacks are invoked at this point. The callbacks are
invoked once an instance for this state are registered via
[`cpuhp_state_add_instance()`](#c-cpuhp_state_add_instance) or [`cpuhp_state_add_instance_nocalls()`](#c-cpuhp_state_add_instance_nocalls)

#### <a id="c-cpuhp_state_add_instance"></a>`cpuhp_state_add_instance()`

```c
int cpuhp_state_add_instance(enum cpuhp_state state, struct hlist_node *node)
```

Add an instance for a state and invoke startup callback.

**Parameters**

- `enum cpuhp_state state`: The state for which the instance is installed
- `struct hlist_node *node`: The node for this individual state.

**Description**

Installs the instance for the **state** and invokes the registered startup
callback on the online cpus which have already reached the **state**. The
**state** must have been earlier marked as multi-instance by
[`cpuhp_setup_state_multi()`](#c-cpuhp_setup_state_multi).

#### <a id="c-cpuhp_state_add_instance_nocalls"></a>`cpuhp_state_add_instance_nocalls()`

```c
int cpuhp_state_add_instance_nocalls(enum cpuhp_state state, struct hlist_node *node)
```

Add an instance for a state without invoking the startup callback.

**Parameters**

- `enum cpuhp_state state`: The state for which the instance is installed
- `struct hlist_node *node`: The node for this individual state.

**Description**

Installs the instance for the **state**. The **state** must have been earlier
marked as multi-instance by cpuhp_setup_state_multi. NOP if SMP=n or
HOTPLUG_CPU=n.

#### <a id="c-cpuhp_state_add_instance_nocalls_cpuslocked"></a>`cpuhp_state_add_instance_nocalls_cpuslocked()`

```c
int cpuhp_state_add_instance_nocalls_cpuslocked(enum cpuhp_state state, struct hlist_node *node)
```

Add an instance for a state without invoking the startup callback from a `cpus_read_lock()` held region.

**Parameters**

- `enum cpuhp_state state`: The state for which the instance is installed
- `struct hlist_node *node`: The node for this individual state.

**Description**

Same as [`cpuhp_state_add_instance_nocalls()`](#c-cpuhp_state_add_instance_nocalls) except that it must be
invoked from within a `cpus_read_lock()` held region.

#### <a id="c-cpuhp_remove_state"></a>`cpuhp_remove_state()`

```c
void cpuhp_remove_state(enum cpuhp_state state)
```

Remove hotplug state callbacks and invoke the teardown

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are removed

**Description**

Removes the callback functions and invokes the teardown callback on
the online cpus which have already reached the **state**.

#### <a id="c-cpuhp_remove_state_nocalls"></a>`cpuhp_remove_state_nocalls()`

```c
void cpuhp_remove_state_nocalls(enum cpuhp_state state)
```

Remove hotplug state callbacks without invoking the teardown callback

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are removed

#### <a id="c-cpuhp_remove_state_nocalls_cpuslocked"></a>`cpuhp_remove_state_nocalls_cpuslocked()`

```c
void cpuhp_remove_state_nocalls_cpuslocked(enum cpuhp_state state)
```

Remove hotplug state callbacks without invoking teardown from a `cpus_read_lock()` held region.

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are removed

**Description**

Same as cpuhp_remove_state `nocalls()` except that it must be invoked
from within a `cpus_read_lock()` held region.

#### <a id="c-cpuhp_remove_multi_state"></a>`cpuhp_remove_multi_state()`

```c
void cpuhp_remove_multi_state(enum cpuhp_state state)
```

Remove hotplug multi state callback

**Parameters**

- `enum cpuhp_state state`: The state for which the calls are removed

**Description**

Removes the callback functions from a multi state. This is the reverse of
[`cpuhp_setup_state_multi()`](#c-cpuhp_setup_state_multi). All instances should have been removed before
invoking this function.

#### <a id="c-cpuhp_state_remove_instance"></a>`cpuhp_state_remove_instance()`

```c
int cpuhp_state_remove_instance(enum cpuhp_state state, struct hlist_node *node)
```

Remove hotplug instance from state and invoke the teardown callback

**Parameters**

- `enum cpuhp_state state`: The state from which the instance is removed
- `struct hlist_node *node`: The node for this individual state.

**Description**

Removes the instance and invokes the teardown callback on the online cpus
which have already reached **state**.

#### <a id="c-cpuhp_state_remove_instance_nocalls"></a>`cpuhp_state_remove_instance_nocalls()`

```c
int cpuhp_state_remove_instance_nocalls(enum cpuhp_state state, struct hlist_node *node)
```

Remove hotplug instance from state without invoking the teardown callback

**Parameters**

- `enum cpuhp_state state`: The state from which the instance is removed
- `struct hlist_node *node`: The node for this individual state.

**Description**

Removes the instance without invoking the teardown callback.

---

# The object-lifetime debugging infrastructure

_Peios Kernel / Internals / Core APIs_

> debugobjects is a generic infrastructure to track the life time of kernel objects and validate the operations on those.

<a id="rst-the-object-lifetime-debugging-infrastructure"></a>

**Author:** Thomas Gleixner

<a id="rst-introduction"></a>

## Introduction

debugobjects is a generic infrastructure to track the life time of kernel objects and validate the operations on those.

debugobjects is useful to check for the following error patterns:

- Activation of uninitialized objects

- Initialization of active objects

- Usage of freed/destroyed objects

debugobjects is not changing the data structure of the real object so it can be compiled in with a minimal runtime impact and enabled on demand with a kernel command line option.

<a id="rst-howto-use-debugobjects"></a>

## Howto use debugobjects

A kernel subsystem needs to provide a data structure which describes the object type and add calls into the debug code at appropriate places. The data structure to describe the object type needs at minimum the name of the object type. Optional functions can and should be provided to fixup detected problems so the kernel can continue to work and the debug information can be retrieved from a live system instead of hard core debugging with serial consoles and stack trace transcripts from the monitor.

The debug calls provided by debugobjects are:

- debug_object_init

- debug_object_init_on_stack

- debug_object_activate

- debug_object_deactivate

- debug_object_destroy

- debug_object_free

- debug_object_assert_init

Each of these functions takes the address of the real object and a pointer to the object type specific debug description structure.

Each detected error is reported in the statistics and a limited number of errors are printk'ed including a full stack trace.

The statistics are available via /sys/kernel/debug/debug_objects/stats. They provide information about the number of warnings and the number of successful fixups along with information about the usage of the internal tracking objects and the state of the internal tracking objects pool.

<a id="rst-debug-functions"></a>

## Debug functions


#### <a id="c-debug_object_init"></a>`debug_object_init()`

```c
void debug_object_init(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object is initialized

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called whenever the initialization function of a real object is called.

When the real object is already tracked by debugobjects it is checked, whether the object can be initialized. Initializing is not allowed for active and destroyed objects. When debugobjects detects an error, then it calls the fixup_init function of the object type description structure if provided by the caller. The fixup function can correct the problem before the real initialization of the object happens. E.g. it can deactivate an active object in order to prevent damage to the subsystem.

When the real object is not yet tracked by debugobjects, debugobjects allocates a tracker object for the real object and sets the tracker object state to ODEBUG_STATE_INIT. It verifies that the object is not on the callers stack. If it is on the callers stack then a limited number of warnings including a full stack trace is printk'ed. The calling code must use debug_object_init_on_stack() and remove the object before leaving the function which allocated it. See next section.


#### <a id="c-debug_object_init_on_stack"></a>`debug_object_init_on_stack()`

```c
void debug_object_init_on_stack(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object on stack is initialized

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called whenever the initialization function of a real object which resides on the stack is called.

When the real object is already tracked by debugobjects it is checked, whether the object can be initialized. Initializing is not allowed for active and destroyed objects. When debugobjects detects an error, then it calls the fixup_init function of the object type description structure if provided by the caller. The fixup function can correct the problem before the real initialization of the object happens. E.g. it can deactivate an active object in order to prevent damage to the subsystem.

When the real object is not yet tracked by debugobjects debugobjects allocates a tracker object for the real object and sets the tracker object state to ODEBUG_STATE_INIT. It verifies that the object is on the callers stack.

An object which is on the stack must be removed from the tracker by calling debug_object_free() before the function which allocates the object returns. Otherwise we keep track of stale objects.


#### <a id="c-debug_object_activate"></a>`debug_object_activate()`

```c
int debug_object_activate(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object is activated

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure
  Returns 0 for success, -EINVAL for check failed.


This function is called whenever the activation function of a real object is called.

When the real object is already tracked by debugobjects it is checked, whether the object can be activated. Activating is not allowed for active and destroyed objects. When debugobjects detects an error, then it calls the fixup_activate function of the object type description structure if provided by the caller. The fixup function can correct the problem before the real activation of the object happens. E.g. it can deactivate an active object in order to prevent damage to the subsystem.

When the real object is not yet tracked by debugobjects then the fixup_activate function is called if available. This is necessary to allow the legitimate activation of statically allocated and initialized objects. The fixup function checks whether the object is valid and calls the debug_objects_init() function to initialize the tracking of this object.

When the activation is legitimate, then the state of the associated tracker object is set to ODEBUG_STATE_ACTIVE.


#### <a id="c-debug_object_deactivate"></a>`debug_object_deactivate()`

```c
void debug_object_deactivate(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object is deactivated

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called whenever the deactivation function of a real object is called.

When the real object is tracked by debugobjects it is checked, whether the object can be deactivated. Deactivating is not allowed for untracked or destroyed objects.

When the deactivation is legitimate, then the state of the associated tracker object is set to ODEBUG_STATE_INACTIVE.


#### <a id="c-debug_object_destroy"></a>`debug_object_destroy()`

```c
void debug_object_destroy(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object is destroyed

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called to mark an object destroyed. This is useful to prevent the usage of invalid objects, which are still available in memory: either statically allocated objects or objects which are freed later.

When the real object is tracked by debugobjects it is checked, whether the object can be destroyed. Destruction is not allowed for active and destroyed objects. When debugobjects detects an error, then it calls the fixup_destroy function of the object type description structure if provided by the caller. The fixup function can correct the problem before the real destruction of the object happens. E.g. it can deactivate an active object in order to prevent damage to the subsystem.

When the destruction is legitimate, then the state of the associated tracker object is set to ODEBUG_STATE_DESTROYED.


#### <a id="c-debug_object_free"></a>`debug_object_free()`

```c
void debug_object_free(void *addr, const struct debug_obj_descr *descr)
```

debug checks when an object is freed

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called before an object is freed.

When the real object is tracked by debugobjects it is checked, whether the object can be freed. Free is not allowed for active objects. When debugobjects detects an error, then it calls the fixup_free function of the object type description structure if provided by the caller. The fixup function can correct the problem before the real free of the object happens. E.g. it can deactivate an active object in order to prevent damage to the subsystem.

Note that debug_object_free removes the object from the tracker. Later usage of the object is detected by the other debug checks.


#### <a id="c-debug_object_assert_init"></a>`debug_object_assert_init()`

```c
void debug_object_assert_init(void *addr, const struct debug_obj_descr *descr)
```

debug checks when object should be init-ed

**Parameters**

- `void *addr`: address of the object
- `const struct debug_obj_descr *descr`: pointer to an object specific debug description structure


This function is called to assert that an object has been initialized.

When the real object is not tracked by debugobjects, it calls fixup_assert_init of the object type description structure provided by the caller, with the hardcoded object state ODEBUG_NOT_AVAILABLE. The fixup function can correct the problem by calling debug_object_init and other specific initializing functions.

When the real object is already tracked by debugobjects it is ignored.

<a id="rst-fixup-functions"></a>

## Fixup functions

<a id="rst-debug-object-type-description-structure"></a>

### Debug object type description structure


#### <a id="c-struct-debug_obj"></a>`struct debug_obj`

representation of an tracked object

**Definition**

```c
struct debug_obj {
    struct hlist_node               node;
    enum debug_obj_state            state;
    unsigned int                    astate;
    union {
        void *object;
        struct hlist_node       *batch_last;
    };
    const struct debug_obj_descr *descr;
};
```

**Members**

- `node`: hlist node to link the object into the tracker list
- `state`: tracked object state
- `astate`: current active state
- `{unnamed_union}`: anonymous
- `object`: pointer to the real object
- `batch_last`: pointer to the last hlist node in a batch
- `descr`: pointer to an object type specific debug description structure

#### <a id="c-struct-debug_obj_descr"></a>`struct debug_obj_descr`

object type specific debug description structure

**Definition**

```c
struct debug_obj_descr {
    const char              *name;
    void *(*debug_hint)(void *addr);
    bool (*is_static_object)(void *addr);
    bool (*fixup_init)(void *addr, enum debug_obj_state state);
    bool (*fixup_activate)(void *addr, enum debug_obj_state state);
    bool (*fixup_destroy)(void *addr, enum debug_obj_state state);
    bool (*fixup_free)(void *addr, enum debug_obj_state state);
    bool (*fixup_assert_init)(void *addr, enum debug_obj_state state);
};
```

**Members**

- `name`: name of the object typee
- `debug_hint`: function returning address, which have associated
  kernel symbol, to allow identify the object
- `is_static_object`: return true if the obj is static, otherwise return false
- `fixup_init`: fixup function, which is called when the init check
  fails. All fixup functions must return true if fixup
  was successful, otherwise return false
- `fixup_activate`: fixup function, which is called when the activate check
  fails
- `fixup_destroy`: fixup function, which is called when the destroy check
  fails
- `fixup_free`: fixup function, which is called when the free check
  fails
- `fixup_assert_init`: fixup function, which is called when the assert_init
  check fails


<a id="rst-fixup-init"></a>

### fixup_init

This function is called from the debug code whenever a problem in debug_object_init is detected. The function takes the address of the object and the state which is currently recorded in the tracker.

Called from debug_object_init when the object state is:

- ODEBUG_STATE_ACTIVE

The function returns true when the fixup was successful, otherwise false. The return value is used to update the statistics.

Note, that the function needs to call the debug_object_init() function again, after the damage has been repaired in order to keep the state consistent.

<a id="rst-fixup-activate"></a>

### fixup_activate

This function is called from the debug code whenever a problem in debug_object_activate is detected.

Called from debug_object_activate when the object state is:

- ODEBUG_STATE_NOTAVAILABLE

- ODEBUG_STATE_ACTIVE

The function returns true when the fixup was successful, otherwise false. The return value is used to update the statistics.

Note that the function needs to call the debug_object_activate() function again after the damage has been repaired in order to keep the state consistent.

The activation of statically initialized objects is a special case. When debug_object_activate() has no tracked object for this object address then fixup_activate() is called with object state ODEBUG_STATE_NOTAVAILABLE. The fixup function needs to check whether this is a legitimate case of a statically initialized object or not. In case it is it calls debug_object_init() and debug_object_activate() to make the object known to the tracker and marked active. In this case the function should return false because this is not a real fixup.

<a id="rst-fixup-destroy"></a>

### fixup_destroy

This function is called from the debug code whenever a problem in debug_object_destroy is detected.

Called from debug_object_destroy when the object state is:

- ODEBUG_STATE_ACTIVE

The function returns true when the fixup was successful, otherwise false. The return value is used to update the statistics.

<a id="rst-fixup-free"></a>

### fixup_free

This function is called from the debug code whenever a problem in debug_object_free is detected. Further it can be called from the debug checks in kfree/vfree, when an active object is detected from the debug_check_no_obj_freed() sanity checks.

Called from debug_object_free() or debug_check_no_obj_freed() when the object state is:

- ODEBUG_STATE_ACTIVE

The function returns true when the fixup was successful, otherwise false. The return value is used to update the statistics.

<a id="rst-fixup-assert-init"></a>

### fixup_assert_init

This function is called from the debug code whenever a problem in debug_object_assert_init is detected.

Called from debug_object_assert_init() with a hardcoded state ODEBUG_STATE_NOTAVAILABLE when the object is not found in the debug bucket.

The function returns true when the fixup was successful, otherwise false. The return value is used to update the statistics.

Note, this function should make sure debug_object_init() is called before returning.

The handling of statically initialized objects is a special case. The fixup function should check if this is a legitimate case of a statically initialized object or not. In this case only debug_object_init() should be called to make the object known to the tracker. Then the function should return false because this is not a real fixup.

<a id="rst-known-bugs-and-assumptions"></a>

## Known Bugs And Assumptions

None (knock on wood).

---

# Using physical DMA provided by OHCI-1394 FireWire controllers for debugging

_Peios Kernel / Internals / Core APIs_

> Basically all FireWire controllers which are in use today are compliant to the OHCI-1394 specification which defines the controller to be a PCI bus master which uses DMA to offload data transfers from the CPU and has a "Physical Response…

<a id="rst-using-physical-dma-provided-by-ohci-1394-firewire-controllers-for-debugging"></a>

<a id="rst-introduction"></a>

## Introduction

Basically all FireWire controllers which are in use today are compliant to the OHCI-1394 specification which defines the controller to be a PCI bus master which uses DMA to offload data transfers from the CPU and has a "Physical Response Unit" which executes specific requests by employing PCI-Bus master DMA after applying filters defined by the OHCI-1394 driver.

Once properly configured, remote machines can send these requests to ask the OHCI-1394 controller to perform read and write requests on physical system memory and, for read requests, send the result of the physical memory read back to the requester.

With that, it is possible to debug issues by reading interesting memory locations such as buffers like the printk buffer or the process table.

Retrieving a full system memory dump is also possible over the FireWire, using data transfer rates in the order of 10MB/s or more.

With most FireWire controllers, memory access is limited to the low 4 GB of physical address space.  This can be a problem on machines where memory is located mostly above that limit, but it is rarely a problem on more common hardware such as x86, x86-64 and PowerPC.

At least LSI FW643e and FW643e2 controllers are known to support access to physical addresses above 4 GB, but this feature is currently not enabled by Linux.

Together with a early initialization of the OHCI-1394 controller for debugging, this facility proved most useful for examining long debugs logs in the printk buffer on to debug early boot problems in areas like ACPI where the system fails to boot and other means for debugging (serial port) are either not available (notebooks) or too slow for extensive debug information (like ACPI).

<a id="rst-drivers"></a>

## Drivers

The firewire-ohci driver in drivers/firewire uses filtered physical DMA by default, which is more secure but not suitable for remote debugging. Pass the remote\_dma=1 parameter to the driver to get unfiltered physical DMA.

Because the firewire-ohci driver depends on the PCI enumeration to be completed, an initialization routine which runs pretty early has been implemented for x86.  This routine runs long before console\_init() can be called, i.e. before the printk buffer appears on the console.

To activate it, enable CONFIG\_PROVIDE\_OHCI1394\_DMA\_INIT (Kernel hacking menu: Remote debugging over FireWire early on boot) and pass the parameter "ohci1394\_dma=early" to the recompiled kernel on boot.

<a id="rst-tools"></a>

## Tools

firescope - Originally developed by Benjamin Herrenschmidt, Andi Kleen ported it from PowerPC to x86 and x86\_64 and added functionality, firescope can now be used to view the printk buffer of a remote machine, even with live update.

Bernhard Kaindl enhanced firescope to support accessing 64-bit machines from 32-bit firescope and vice versa: - [http://v3.sk/\~lkundrak/firescope/](<http://v3.sk/~lkundrak/firescope/>)

and he implemented fast system dump (alpha version - read README.txt): - [http://halobates.de/firewire/firedump-0.1.tar.bz2](<http://halobates.de/firewire/firedump-0.1.tar.bz2>)

There is also a gdb proxy for firewire which allows to use gdb to access data which can be referenced from symbols found by gdb in vmlinux: - [http://halobates.de/firewire/fireproxy-0.33.tar.bz2](<http://halobates.de/firewire/fireproxy-0.33.tar.bz2>)

The latest version of this gdb proxy (fireproxy-0.34) can communicate (not yet stable) with kgdb over an memory-based communication module (kgdbom).

<a id="rst-getting-started"></a>

## Getting Started

The OHCI-1394 specification regulates that the OHCI-1394 controller must disable all physical DMA on each bus reset.

This means that if you want to debug an issue in a system state where interrupts are disabled and where no polling of the OHCI-1394 controller for bus resets takes place, you have to establish any FireWire cable connections and fully initialize all FireWire hardware \_\_before\_\_ the system enters such state.

Step-by-step instructions for using firescope with early OHCI initialization:

1. Verify that your hardware is supported:

   Load the firewire-ohci module and check your kernel logs. You should see a line similar to:



   ```text
   firewire_ohci 0000:15:00.1: added OHCI v1.0 device as card 2, 4 IR + 4 IT
   ... contexts, quirks 0x11
   ```

   when loading the driver. If you have no supported controller, many PCI, CardBus and even some Express cards which are fully compliant to OHCI-1394 specification are available. If it requires no driver for Windows operating systems, it most likely is. Only specialized shops have cards which are not compliant, they are based on TI PCILynx chips and require drivers for Windows operating systems.

   The mentioned kernel log message contains the string "physUB" if the controller implements a writable Physical Upper Bound register.  This is required for physical DMA above 4 GB (but not utilized by Linux yet).

2. Establish a working FireWire cable connection:

   Any FireWire cable, as long at it provides electrically and mechanically stable connection and has matching connectors (there are small 4-pin and large 6-pin FireWire ports) will do.

   If an driver is running on both machines you should see a line like:



   ```text
   firewire_core 0000:15:00.1: created device fw1: GUID 00061b0020105917, S400
   ```

   on both machines in the kernel log when the cable is plugged in and connects the two machines.

3. Test physical DMA using firescope:

   On the debug host, make sure that /dev/fw\* is accessible, then start firescope:



   ```text
       $ firescope
       Port 0 (/dev/fw1) opened, 2 nodes detected

       FireScope
       ---------
       Target : <unspecified>
       Gen    : 1
       [Ctrl-T] choose target
       [Ctrl-H] this menu
       [Ctrl-Q] quit

   ------> Press Ctrl-T now, the output should be similar to:

       2 nodes available, local node is: 0
        0: ffc0, uuid: 00000000 00000000 [LOCAL]
        1: ffc1, uuid: 00279000 ba4bb801
   ```

   Besides the \[LOCAL\] node, it must show another node without error message.

4. Prepare for debugging with early OHCI-1394 initialization:

   4.1) Kernel compilation and installation on debug target

   Compile the kernel to be debugged with CONFIG\_PROVIDE\_OHCI1394\_DMA\_INIT (Kernel hacking: Provide code for enabling DMA over FireWire early on boot) enabled and install it on the machine to be debugged (debug target).

   4.2) Transfer the System.map of the debugged kernel to the debug host

   Copy the System.map of the kernel be debugged to the debug host (the host which is connected to the debugged machine over the FireWire cable).

5. Retrieving the printk buffer contents:

   With the FireWire cable connected, the OHCI-1394 driver on the debugging host loaded, reboot the debugged machine, booting the kernel which has CONFIG\_PROVIDE\_OHCI1394\_DMA\_INIT enabled, with the option ohci1394\_dma=early.

   Then, on the debugging host, run firescope, for example by using -A:



   ```text
   firescope -A System.map-of-debug-target-kernel
   ```

   Note: -A automatically attaches to the first non-local node. It only works reliably if only connected two machines are connected using FireWire.

   After having attached to the debug target, press Ctrl-D to view the complete printk buffer or Ctrl-U to enter auto update mode and get an updated live view of recent kernel messages logged on the debug target.

   Call "firescope -h" to get more information on firescope's options.

<a id="rst-notes"></a>

## Notes

Documentation and specifications: [http://halobates.de/firewire/](<http://halobates.de/firewire/>)

FireWire is a trademark of Apple Inc. - for more information please refer to: [https://en.wikipedia.org/wiki/FireWire](<https://en.wikipedia.org/wiki/FireWire>)

---

# Dynamic DMA mapping Guide

_Peios Kernel / Internals / Core APIs_

> This is a guide to device driver writers on how to use the DMA API with example pseudo-code. For a concise description of the API, see Documentation/core-api/dma-api.rst.

<a id="rst-dynamic-dma-mapping-guide"></a>

**Author:** David S. Miller &lt;[davem@redhat.com](<mailto:davem@redhat.com>)&gt;

**Author:** Richard Henderson &lt;[rth@cygnus.com](<mailto:rth@cygnus.com>)&gt;

**Author:** Jakub Jelinek &lt;[jakub@redhat.com](<mailto:jakub@redhat.com>)&gt;

This is a guide to device driver writers on how to use the DMA API with example pseudo-code.  For a concise description of the API, see [Documentation/core-api/dma-api.rst](/kernel/internals/core-api/dma-api.md).

<a id="rst-cpu-and-dma-addresses"></a>

## CPU and DMA addresses

There are several kinds of addresses involved in the DMA API, and it's important to understand the differences.

The kernel normally uses virtual addresses.  Any address returned by kmalloc(), vmalloc(), and similar interfaces is a virtual address and can be stored in a `void *`.

The virtual memory system (TLB, page tables, etc.) translates virtual addresses to CPU physical addresses, which are stored as "phys_addr_t" or "resource_size_t".  The kernel manages device resources like registers as physical addresses.  These are the addresses in /proc/iomem.  The physical address is not directly useful to a driver; it must use ioremap() to map the space and produce a virtual address.

I/O devices use a third kind of address: a "bus address".  If a device has registers at an MMIO address, or if it performs DMA to read or write system memory, the addresses used by the device are bus addresses.  In some systems, bus addresses are identical to CPU physical addresses, but in general they are not.  IOMMUs and host bridges can produce arbitrary mappings between physical and bus addresses.

From a device's point of view, DMA uses the bus address space, but it may be restricted to a subset of that space.  For example, even if a system supports 64-bit addresses for main memory and PCI BARs, it may use an IOMMU so devices only need to use 32-bit DMA addresses.

Here's a picture and some examples:



```text
             CPU                  CPU                  Bus
           Virtual              Physical             Address
           Address              Address               Space
            Space                Space

          +-------+             +------+             +------+
          |       |             |MMIO  |   Offset    |      |
          |       |  Virtual    |Space |   applied   |      |
        C +-------+ --------> B +------+ ----------> +------+ A
          |       |  mapping    |      |   by host   |      |
+-----+   |       |             |      |   bridge    |      |   +--------+
|     |   |       |             +------+             |      |   |        |
| CPU |   |       |             | RAM  |             |      |   | Device |
|     |   |       |             |      |             |      |   |        |
+-----+   +-------+             +------+             +------+   +--------+
          |       |  Virtual    |Buffer|   Mapping   |      |
        X +-------+ --------> Y +------+ <---------- +------+ Z
          |       |  mapping    | RAM  |   by IOMMU
          |       |             |      |
          |       |             |      |
          +-------+             +------+
```

During the enumeration process, the kernel learns about I/O devices and their MMIO space and the host bridges that connect them to the system.  For example, if a PCI device has a BAR, the kernel reads the bus address (A) from the BAR and converts it to a CPU physical address (B).  The address B is stored in a struct resource and usually exposed via /proc/iomem.  When a driver claims a device, it typically uses ioremap() to map physical address B at a virtual address (C).  It can then use, e.g., ioread32(C), to access the device registers at bus address A.

If the device supports DMA, the driver sets up a buffer using kmalloc() or a similar interface, which returns a virtual address (X).  The virtual memory system maps X to a physical address (Y) in system RAM.  The driver can use virtual address X to access the buffer, but the device itself cannot because DMA doesn't go through the CPU virtual memory system.

In some simple systems, the device can do DMA directly to physical address Y.  But in many others, there is IOMMU hardware that translates DMA addresses to physical addresses, e.g., it translates Z to Y.  This is part of the reason for the DMA API: the driver can give a virtual address X to an interface like dma_map_single(), which sets up any required IOMMU mapping and returns the DMA address Z.  The driver then tells the device to do DMA to Z, and the IOMMU maps it to the buffer at address Y in system RAM.

So that Linux can use the dynamic DMA mapping, it needs some help from the drivers, namely it has to take into account that DMA addresses should be mapped only for the time they are actually used and unmapped after the DMA transfer.

The following API will work of course even on platforms where no such hardware exists.

Note that the DMA API works with any bus independent of the underlying microprocessor architecture. You should use the DMA API rather than the bus-specific DMA API, i.e., use the dma_map\_\*() interfaces rather than the pci_map\_\*() interfaces.

First of all, you should make sure:



```text
#include <linux/dma-mapping.h>
```

is in your driver, which provides the definition of dma_addr_t.  This type can hold any valid DMA address for the platform and should be used everywhere you hold a DMA address returned from the DMA mapping functions.

<a id="rst-what-memory-is-dma-able"></a>

## What memory is DMA'able?

The first piece of information you must know is what kernel memory can be used with the DMA mapping facilities.  There has been an unwritten set of rules regarding this, and this text is an attempt to finally write them down.

If you acquired your memory via the page allocator (i.e. \__get_free_page\*()) or the generic memory allocators (i.e. kmalloc() or kmem_cache_alloc()) then you may DMA to/from that memory using the addresses returned from those routines.

This means specifically that you may \_not\_ use the memory/addresses returned from vmalloc() for DMA.  It is possible to DMA to the \_underlying\_ memory mapped into a vmalloc() area, but this requires walking page tables to get the physical addresses, and then translating each of those pages back to a kernel address using something like \__va().  \[ EDIT: Update this when we integrate Gerd Knorr's generic code which does this. \]

This rule also means that you may use neither kernel image addresses (items in data/text/bss segments), nor module image addresses, nor stack addresses for DMA.  These could all be mapped somewhere entirely different than the rest of physical memory.  Even if those classes of memory could physically work with DMA, you'd need to ensure the I/O buffers were cacheline-aligned.  Without that, you'd see cacheline sharing problems (data corruption) on CPUs with DMA-incoherent caches. (The CPU could write to one word, DMA would write to a different one in the same cache line, and one of them could be overwritten.)

Also, this means that you cannot take the return of a kmap() call and DMA to/from that.  This is similar to vmalloc().

What about block I/O and networking buffers?  The block I/O and networking subsystems make sure that the buffers they use are valid for you to DMA from/to.

<a id="rst-dma-from-device-group-begin-end-annotations"></a>

## \__dma_from_device_group_begin/end annotations

As explained previously, when a structure contains a DMA_FROM_DEVICE / DMA_BIDIRECTIONAL buffer (device writes to memory) alongside fields that the CPU writes to, cache line sharing between the DMA buffer and CPU-written fields can cause data corruption on CPUs with DMA-incoherent caches.

The `__dma_from_device_group_begin(GROUP)/__dma_from_device_group_end(GROUP)` macros ensure proper alignment to prevent this:



```text
struct my_device {
        spinlock_t lock1;
        __dma_from_device_group_begin();
        char dma_buffer1[16];
        char dma_buffer2[16];
        __dma_from_device_group_end();
        spinlock_t lock2;
};
```

To isolate a DMA buffer from adjacent fields, use `__dma_from_device_group_begin(GROUP)` before the first DMA buffer field and `__dma_from_device_group_end(GROUP)` after the last DMA buffer field (with the same GROUP name). This protects both the head and tail of the buffer from cache line sharing.

The GROUP parameter is an optional identifier that names the DMA buffer group (in case you have several in the same structure):



```text
struct my_device {
        spinlock_t lock1;
        __dma_from_device_group_begin(buffer1);
        char dma_buffer1[16];
        __dma_from_device_group_end(buffer1);
        spinlock_t lock2;
        __dma_from_device_group_begin(buffer2);
        char dma_buffer2[16];
        __dma_from_device_group_end(buffer2);
};
```

On cache-coherent platforms these macros expand to zero-length array markers. On non-coherent platforms, they also ensure the minimal DMA alignment, which can be as large as 128 bytes.

> [!NOTE]
>
> It is allowed (though somewhat fragile) to include extra fields, not intended for DMA from the device, within the group (in order to pack the structure tightly) - but only as long as the CPU does not write these fields while any fields in the group are mapped for DMA_FROM_DEVICE or DMA_BIDIRECTIONAL.

<a id="rst-dma-addressing-capabilities"></a>

## DMA addressing capabilities

By default, the kernel assumes that your device can address 32-bits of DMA addressing.  For a 64-bit capable device, this needs to be increased, and for a device with limitations, it needs to be decreased.

Special note about PCI: PCI-X specification requires PCI-X devices to support 64-bit addressing (DAC) for all transactions.  And at least one platform (SGI SN2) requires 64-bit coherent allocations to operate correctly when the IO bus is in PCI-X mode.

For correct operation, you must set the DMA mask to inform the kernel about your devices DMA addressing capabilities.

This is performed via a call to dma_set_mask_and_coherent():



```text
int dma_set_mask_and_coherent(struct device *dev, u64 mask);
```

which will set the mask for both streaming and coherent APIs together.  If you have some special requirements, then the following two separate calls can be used instead:

> The setup for streaming mappings is performed via a call to dma_set_mask():
>
>
>
> ```text
> int dma_set_mask(struct device *dev, u64 mask);
> ```
>
> The setup for coherent allocations is performed via a call to dma_set_coherent_mask():
>
>
>
> ```text
> int dma_set_coherent_mask(struct device *dev, u64 mask);
> ```

Here, dev is a pointer to the device struct of your device, and mask is a bit mask describing which bits of an address your device supports.  Often the device struct of your device is embedded in the bus-specific device struct of your device.  For example, &amp;pdev-&gt;dev is a pointer to the device struct of a PCI device (pdev is a pointer to the PCI device struct of your device).

These calls usually return zero to indicate your device can perform DMA properly on the machine given the address mask you provided, but they might return an error if the mask is too small to be supportable on the given system.  If it returns non-zero, your device cannot perform DMA properly on this platform, and attempting to do so will result in undefined behavior. You must not use DMA on this device unless the dma_set_mask family of functions has returned success.

This means that in the failure case, you have two options:

1. Use some non-DMA mode for data transfer, if possible.

2. Ignore this device and do not initialize it.

It is recommended that your driver print a kernel KERN_WARNING message when setting the DMA mask fails.  In this manner, if a user of your driver reports that performance is bad or that the device is not even detected, you can ask them for the kernel messages to find out exactly why.

The 24-bit addressing device would do something like this:



```text
if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(24))) {
        dev_warn(dev, "mydev: No suitable DMA available\n");
        goto ignore_this_device;
}
```

The standard 64-bit addressing device would do something like this:



```text
dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64))
```

dma_set_mask_and_coherent() never return fail when DMA_BIT_MASK(64). Typical error code like:



```text
/* Wrong code */
if (dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64)))
        dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32))
```

dma_set_mask_and_coherent() will never return failure when bigger than 32. So typical code like:



```text
/* Recommended code */
if (support_64bit)
        dma_set_mask_and_coherent(dev, DMA_BIT_MASK(64));
else
        dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32));
```

If the device only supports 32-bit addressing for descriptors in the coherent allocations, but supports full 64-bits for streaming mappings it would look like this:



```text
if (dma_set_mask(dev, DMA_BIT_MASK(64))) {
        dev_warn(dev, "mydev: No suitable DMA available\n");
        goto ignore_this_device;
}
```

The coherent mask will always be able to set the same or a smaller mask as the streaming mask. However for the rare case that a device driver only uses coherent allocations, one would have to check the return value from dma_set_coherent_mask().

Finally, if your device can only drive the low 24-bits of address you might do something like:



```text
if (dma_set_mask(dev, DMA_BIT_MASK(24))) {
        dev_warn(dev, "mydev: 24-bit DMA addressing not available\n");
        goto ignore_this_device;
}
```

When dma_set_mask() or dma_set_mask_and_coherent() is successful, and returns zero, the kernel saves away this mask you have provided.  The kernel will use this information later when you make DMA mappings.

There is a case which we are aware of at this time, which is worth mentioning in this documentation.  If your device supports multiple functions (for example a sound card provides playback and record functions) and the various different functions have \_different\_ DMA addressing limitations, you may wish to probe each mask and only provide the functionality which the machine can handle.  It is important that the last call to dma_set_mask() be for the most specific mask.

Here is pseudo-code showing how this might be done:



```text
#define PLAYBACK_ADDRESS_BITS   DMA_BIT_MASK(32)
#define RECORD_ADDRESS_BITS     DMA_BIT_MASK(24)

struct my_sound_card *card;
struct device *dev;

...
if (!dma_set_mask(dev, PLAYBACK_ADDRESS_BITS)) {
        card->playback_enabled = 1;
} else {
        card->playback_enabled = 0;
        dev_warn(dev, "%s: Playback disabled due to DMA limitations\n",
               card->name);
}
if (!dma_set_mask(dev, RECORD_ADDRESS_BITS)) {
        card->record_enabled = 1;
} else {
        card->record_enabled = 0;
        dev_warn(dev, "%s: Record disabled due to DMA limitations\n",
               card->name);
}
```

A sound card was used as an example here because this genre of PCI devices seems to be littered with ISA chips given a PCI front end, and thus retaining the 16MB DMA addressing limitations of ISA.

<a id="rst-types-of-dma-mappings"></a>

## Types of DMA mappings

There are two types of DMA mappings:

- Coherent DMA mappings which are usually mapped at driver initialization, unmapped at the end and for which the hardware should guarantee that the device and the CPU can access the data in parallel and will see updates made by each other without any explicit software flushing.

  Think of "coherent" as "synchronous".

  The current default is to return coherent memory in the low 32 bits of the DMA space.  However, for future compatibility you should set the coherent mask even if this default is fine for your driver.

  Good examples of what to use coherent mappings for are:

  > - Network card DMA ring descriptors.
  >
  > - SCSI adapter mailbox command data structures.
  >
  > - Device firmware microcode executed out of main memory.

  The invariant these examples all require is that any CPU store to memory is immediately visible to the device, and vice versa.  Coherent mappings guarantee this.

  > [!IMPORTANT]
  >
  > Coherent DMA memory does not preclude the usage of proper memory barriers.  The CPU may reorder stores to coherent memory just as it may normal memory.  Example: if it is important for the device to see the first word of a descriptor updated before the second, you must do something like:
  >
  >
  >
  > ```text
  > desc->word0 = address;
  > wmb();
  > desc->word1 = DESC_VALID;
  > ```
  >
  > in order to get correct behavior on all platforms.
  >
  > Also, on some platforms your driver may need to flush CPU write buffers in much the same way as it needs to flush write buffers found in PCI bridges (such as by reading a register's value after writing it).

- Streaming DMA mappings which are usually mapped for one DMA transfer, unmapped right after it (unless you use dma_sync\_\* below) and for which hardware can optimize for sequential accesses.

  Think of "streaming" as "asynchronous" or "outside the coherency domain".

  Good examples of what to use streaming mappings for are:

  > - Networking buffers transmitted/received by a device.
  >
  > - Filesystem buffers written/read by a SCSI device.

  The interfaces for using this type of mapping were designed in such a way that an implementation can make whatever performance optimizations the hardware allows.  To this end, when using such mappings you must be explicit about what you want to happen.

Neither type of DMA mapping has alignment restrictions that come from the underlying bus, although some devices may have such restrictions. Also, systems with caches that aren't DMA-coherent will work better when the underlying buffers don't share cache lines with other data.

<a id="rst-using-coherent-dma-mappings"></a>

## Using Coherent DMA mappings

To allocate and map large (PAGE_SIZE or so) coherent DMA regions, you should do:



```text
dma_addr_t dma_handle;

cpu_addr = dma_alloc_coherent(dev, size, &dma_handle, gfp);
```

where device is a `struct device *`. This may be called in interrupt context with the GFP_ATOMIC flag.

Size is the length of the region you want to allocate, in bytes.

This routine will allocate RAM for that region, so it acts similarly to \__get_free_pages() (but takes size instead of a page order).  If your driver needs regions sized smaller than a page, you may prefer using the dma_pool interface, described below.

The coherent DMA mapping interfaces, will by default return a DMA address which is 32-bit addressable.  Even if the device indicates (via the DMA mask) that it may address the upper 32-bits, coherent allocation will only return &gt; 32-bit addresses for DMA if the coherent DMA mask has been explicitly changed via dma_set_coherent_mask().  This is true of the dma_pool interface as well.

dma_alloc_coherent() returns two values: the virtual address which you can use to access it from the CPU and dma_handle which you pass to the card.

The CPU virtual address and the DMA address are both guaranteed to be aligned to the smallest PAGE_SIZE order which is greater than or equal to the requested size.  This invariant exists (for example) to guarantee that if you allocate a chunk which is smaller than or equal to 64 kilobytes, the extent of the buffer you receive will not cross a 64K boundary.

To unmap and free such a DMA region, you call:



```text
dma_free_coherent(dev, size, cpu_addr, dma_handle);
```

where dev, size are the same as in the above call and cpu_addr and dma_handle are the values dma_alloc_coherent() returned to you. This function may not be called in interrupt context.

If your driver needs lots of smaller memory regions, you can write custom code to subdivide pages returned by dma_alloc_coherent(), or you can use the dma_pool API to do that.  A dma_pool is like a kmem_cache, but it uses dma_alloc_coherent(), not \__get_free_pages(). Also, it understands common hardware constraints for alignment, like queue heads needing to be aligned on N byte boundaries.

Create a dma_pool like this:



```text
struct dma_pool *pool;

pool = dma_pool_create(name, dev, size, align, boundary);
```

The "name" is for diagnostics (like a kmem_cache name); dev and size are as above.  The device's hardware alignment requirement for this type of data is "align" (which is expressed in bytes, and must be a power of two).  If your device has no boundary crossing restrictions, pass 0 for boundary; passing 4096 says memory allocated from this pool must not cross 4KByte boundaries (but at that time it may be better to use dma_alloc_coherent() directly instead).

Allocate memory from a DMA pool like this:



```text
cpu_addr = dma_pool_alloc(pool, flags, &dma_handle);
```

flags are GFP_KERNEL if blocking is permitted (not in_interrupt nor holding SMP locks), GFP_ATOMIC otherwise.  Like dma_alloc_coherent(), this returns two values, cpu_addr and dma_handle.

Free memory that was allocated from a dma_pool like this:



```text
dma_pool_free(pool, cpu_addr, dma_handle);
```

where pool is what you passed to dma_pool_alloc(), and cpu_addr and dma_handle are the values dma_pool_alloc() returned. This function may be called in interrupt context.

Destroy a dma_pool by calling:



```text
dma_pool_destroy(pool);
```

Make sure you've called dma_pool_free() for all memory allocated from a pool before you destroy the pool. This function may not be called in interrupt context.

<a id="rst-dma-direction"></a>

## DMA Direction

The interfaces described in subsequent portions of this document take a DMA direction argument, which is an integer and takes on one of the following values:



```text
DMA_BIDIRECTIONAL
DMA_TO_DEVICE
DMA_FROM_DEVICE
DMA_NONE
```

You should provide the exact DMA direction if you know it.

DMA_TO_DEVICE means "from main memory to the device" DMA_FROM_DEVICE means "from the device to main memory" It is the direction in which the data moves during the DMA transfer.

You are \_strongly\_ encouraged to specify this as precisely as you possibly can.

If you absolutely cannot know the direction of the DMA transfer, specify DMA_BIDIRECTIONAL.  It means that the DMA can go in either direction.  The platform guarantees that you may legally specify this, and that it will work, but this may be at the cost of performance for example.

The value DMA_NONE is to be used for debugging.  One can hold this in a data structure before you come to know the precise direction, and this will help catch cases where your direction tracking logic has failed to set things up properly.

Another advantage of specifying this value precisely (outside of potential platform-specific optimizations of such) is for debugging. Some platforms actually have a write permission boolean which DMA mappings can be marked with, much like page protections in the user program address space.  Such platforms can and do report errors in the kernel logs when the DMA controller hardware detects violation of the permission setting.

Only streaming mappings specify a direction, coherent mappings implicitly have a direction attribute setting of DMA_BIDIRECTIONAL.

The SCSI subsystem tells you the direction to use in the 'sc_data_direction' member of the SCSI command your driver is working on.

For Networking drivers, it's a rather simple affair.  For transmit packets, map/unmap them with the DMA_TO_DEVICE direction specifier.  For receive packets, just the opposite, map/unmap them with the DMA_FROM_DEVICE direction specifier.

<a id="rst-using-streaming-dma-mappings"></a>

## Using Streaming DMA mappings

The streaming DMA mapping routines can be called from interrupt context.  There are two versions of each map/unmap, one which will map/unmap a single memory region, and one which will map/unmap a scatterlist.

To map a single region, you do:



```text
struct device *dev = &my_dev->dev;
dma_addr_t dma_handle;
void *addr = buffer->ptr;
size_t size = buffer->len;

dma_handle = dma_map_single(dev, addr, size, direction);
if (dma_mapping_error(dev, dma_handle)) {
        /*
         * reduce current DMA mapping usage,
         * delay and try again later or
         * reset driver.
         */
        goto map_error_handling;
}
```

and to unmap it:



```text
dma_unmap_single(dev, dma_handle, size, direction);
```

You should call dma_mapping_error() as dma_map_single() could fail and return error.  Doing so will ensure that the mapping code will work correctly on all DMA implementations without any dependency on the specifics of the underlying implementation. Using the returned address without checking for errors could result in failures ranging from panics to silent data corruption.  The same applies to dma_map_page() as well.

You should call dma_unmap_single() when the DMA activity is finished, e.g., from the interrupt which told you that the DMA transfer is done.

Using CPU pointers like this for single mappings has a disadvantage: you cannot reference HIGHMEM memory in this way.  Thus, there is a map/unmap interface pair akin to dma\_\{map,unmap\}\_single().  These interfaces deal with page/offset pairs instead of CPU pointers. Specifically:



```text
struct device *dev = &my_dev->dev;
dma_addr_t dma_handle;
struct page *page = buffer->page;
unsigned long offset = buffer->offset;
size_t size = buffer->len;

dma_handle = dma_map_page(dev, page, offset, size, direction);
if (dma_mapping_error(dev, dma_handle)) {
        /*
         * reduce current DMA mapping usage,
         * delay and try again later or
         * reset driver.
         */
        goto map_error_handling;
}

...

dma_unmap_page(dev, dma_handle, size, direction);
```

Here, "offset" means byte offset within the given page.

You should call dma_mapping_error() as dma_map_page() could fail and return error as outlined under the dma_map_single() discussion.

You should call dma_unmap_page() when the DMA activity is finished, e.g., from the interrupt which told you that the DMA transfer is done.

With scatterlists, you map a region gathered from several regions by:



```text
int i, count = dma_map_sg(dev, sglist, nents, direction);
struct scatterlist *sg;

for_each_sg(sglist, sg, count, i) {
        hw_address[i] = sg_dma_address(sg);
        hw_len[i] = sg_dma_len(sg);
}
```

where nents is the number of entries in the sglist.

The implementation is free to merge several consecutive sglist entries into one (e.g. if DMA mapping is done with PAGE_SIZE granularity, any consecutive sglist entries can be merged into one provided the first one ends and the second one starts on a page boundary - in fact this is a huge advantage for cards which either cannot do scatter-gather or have very limited number of scatter-gather entries) and returns the actual number of sg entries it mapped them to. On failure 0 is returned.

Then you should loop count times (note: this can be less than nents times) and use sg_dma_address() and sg_dma_len() macros where you previously accessed sg-&gt;address and sg-&gt;length as shown above.

To unmap a scatterlist, just call:



```text
dma_unmap_sg(dev, sglist, nents, direction);
```

Again, make sure DMA activity has already finished.

> [!NOTE]
>
> The 'nents' argument to the dma_unmap_sg call must be the \_same\_ one you passed into the dma_map_sg call, it should \_NOT\_ be the 'count' value \_returned\_ from the dma_map_sg call.

Every dma_map\_\{single,sg\}() call should have its dma_unmap\_\{single,sg\}() counterpart, because the DMA address space is a shared resource and you could render the machine unusable by consuming all DMA addresses.

If you need to use the same streaming DMA region multiple times and touch the data in between the DMA transfers, the buffer needs to be synced properly in order for the CPU and device to see the most up-to-date and correct copy of the DMA buffer.

So, firstly, just map it with dma_map\_\{single,sg\}(), and after each DMA transfer call either:



```text
dma_sync_single_for_cpu(dev, dma_handle, size, direction);
```

or:



```text
dma_sync_sg_for_cpu(dev, sglist, nents, direction);
```

as appropriate.

Then, if you wish to let the device get at the DMA area again, finish accessing the data with the CPU, and then before actually giving the buffer to the hardware call either:



```text
dma_sync_single_for_device(dev, dma_handle, size, direction);
```

or:



```text
dma_sync_sg_for_device(dev, sglist, nents, direction);
```

as appropriate.

> [!NOTE]
>
> The 'nents' argument to dma_sync_sg_for_cpu() and dma_sync_sg_for_device() must be the same passed to dma_map_sg(). It is \_NOT\_ the count returned by dma_map_sg().

After the last DMA transfer call one of the DMA unmap routines dma_unmap\_\{single,sg\}(). If you don't touch the data from the first dma_map\_\*() call till dma_unmap\_\*(), then you don't have to call the dma_sync\_\*() routines at all.

Here is pseudo code which shows a situation in which you would need to use the dma_sync\_\*() interfaces:



```text
my_card_setup_receive_buffer(struct my_card *cp, char *buffer, int len)
{
        dma_addr_t mapping;

        mapping = dma_map_single(cp->dev, buffer, len, DMA_FROM_DEVICE);
        if (dma_mapping_error(cp->dev, mapping)) {
                /*
                 * reduce current DMA mapping usage,
                 * delay and try again later or
                 * reset driver.
                 */
                goto map_error_handling;
        }

        cp->rx_buf = buffer;
        cp->rx_len = len;
        cp->rx_dma = mapping;

        give_rx_buf_to_card(cp);
}

...

my_card_interrupt_handler(int irq, void *devid, struct pt_regs *regs)
{
        struct my_card *cp = devid;

        ...
        if (read_card_status(cp) == RX_BUF_TRANSFERRED) {
                struct my_card_header *hp;

                /* Examine the header to see if we wish
                 * to accept the data.  But synchronize
                 * the DMA transfer with the CPU first
                 * so that we see updated contents.
                 */
                dma_sync_single_for_cpu(&cp->dev, cp->rx_dma,
                                        cp->rx_len,
                                        DMA_FROM_DEVICE);

                /* Now it is safe to examine the buffer. */
                hp = (struct my_card_header *) cp->rx_buf;
                if (header_is_ok(hp)) {
                        dma_unmap_single(&cp->dev, cp->rx_dma, cp->rx_len,
                                         DMA_FROM_DEVICE);
                        pass_to_upper_layers(cp->rx_buf);
                        make_and_setup_new_rx_buf(cp);
                } else {
                        /* CPU should not write to
                         * DMA_FROM_DEVICE-mapped area,
                         * so dma_sync_single_for_device() is
                         * not needed here. It would be required
                         * for DMA_BIDIRECTIONAL mapping if
                         * the memory was modified.
                         */
                        give_rx_buf_to_card(cp);
                }
        }
}
```

<a id="rst-handling-errors"></a>

## Handling Errors

DMA address space is limited on some architectures and an allocation failure can be determined by:

- checking if dma_alloc_coherent() returns NULL or dma_map_sg returns 0

- checking the dma_addr_t returned from dma_map_single() and dma_map_page() by using dma_mapping_error():



  ```text
  dma_addr_t dma_handle;

  dma_handle = dma_map_single(dev, addr, size, direction);
  if (dma_mapping_error(dev, dma_handle)) {
          /*
           * reduce current DMA mapping usage,
           * delay and try again later or
           * reset driver.
           */
          goto map_error_handling;
  }
  ```

- unmap pages that are already mapped, when mapping error occurs in the middle of a multiple page mapping attempt. These example are applicable to dma_map_page() as well.

Example 1:



```text
dma_addr_t dma_handle1;
dma_addr_t dma_handle2;

dma_handle1 = dma_map_single(dev, addr, size, direction);
if (dma_mapping_error(dev, dma_handle1)) {
        /*
         * reduce current DMA mapping usage,
         * delay and try again later or
         * reset driver.
         */
        goto map_error_handling1;
}
dma_handle2 = dma_map_single(dev, addr, size, direction);
if (dma_mapping_error(dev, dma_handle2)) {
        /*
         * reduce current DMA mapping usage,
         * delay and try again later or
         * reset driver.
         */
        goto map_error_handling2;
}

...

map_error_handling2:
        dma_unmap_single(dma_handle1);
map_error_handling1:
```

Example 2:



```text
/*
 * if buffers are allocated in a loop, unmap all mapped buffers when
 * mapping error is detected in the middle
 */

dma_addr_t dma_addr;
dma_addr_t array[DMA_BUFFERS];
int save_index = 0;

for (i = 0; i < DMA_BUFFERS; i++) {

        ...

        dma_addr = dma_map_single(dev, addr, size, direction);
        if (dma_mapping_error(dev, dma_addr)) {
                /*
                 * reduce current DMA mapping usage,
                 * delay and try again later or
                 * reset driver.
                 */
                goto map_error_handling;
        }
        array[i].dma_addr = dma_addr;
        save_index++;
}

...

map_error_handling:

for (i = 0; i < save_index; i++) {

        ...

        dma_unmap_single(array[i].dma_addr);
}
```

Networking drivers must call dev_kfree_skb() to free the socket buffer and return NETDEV_TX_OK if the DMA mapping fails on the transmit hook (ndo_start_xmit). This means that the socket buffer is just dropped in the failure case.

SCSI drivers must return SCSI_MLQUEUE_HOST_BUSY if the DMA mapping fails in the queuecommand hook. This means that the SCSI subsystem passes the command to the driver again later.

<a id="rst-optimizing-unmap-state-space-consumption"></a>

## Optimizing Unmap State Space Consumption

On many platforms, dma_unmap\_\{single,page\}() is simply a nop. Therefore, keeping track of the mapping address and length is a waste of space.  Instead of filling your drivers up with ifdefs and the like to "work around" this (which would defeat the whole purpose of a portable API) the following facilities are provided.

Actually, instead of describing the macros one by one, we'll transform some example code.

1. Use DEFINE_DMA_UNMAP\_\{ADDR,LEN\} in state saving structures. Example, before:



   ```text
   struct ring_state {
           struct sk_buff *skb;
           dma_addr_t mapping;
           __u32 len;
   };
   ```

   after:



   ```text
   struct ring_state {
           struct sk_buff *skb;
           DEFINE_DMA_UNMAP_ADDR(mapping);
           DEFINE_DMA_UNMAP_LEN(len);
   };
   ```

2. Use dma_unmap\_\{addr,len\}\_set() to set these values. Example, before:



   ```text
   ringp->mapping = FOO;
   ringp->len = BAR;
   ```

   after:



   ```text
   dma_unmap_addr_set(ringp, mapping, FOO);
   dma_unmap_len_set(ringp, len, BAR);
   ```

3. Use dma_unmap\_\{addr,len\}() to access these values. Example, before:



   ```text
   dma_unmap_single(dev, ringp->mapping, ringp->len,
                    DMA_FROM_DEVICE);
   ```

   after:



   ```text
   dma_unmap_single(dev,
                    dma_unmap_addr(ringp, mapping),
                    dma_unmap_len(ringp, len),
                    DMA_FROM_DEVICE);
   ```

It really should be self-explanatory.  We treat the ADDR and LEN separately, because it is possible for an implementation to only need the address in order to perform the unmap operation.

<a id="rst-platform-issues"></a>

## Platform Issues

If you are just writing drivers for Linux and do not maintain an architecture port for the kernel, you can safely skip down to "Closing".

1. Struct scatterlist requirements.

   You need to enable CONFIG_NEED_SG_DMA_LENGTH if the architecture supports IOMMUs (including software IOMMU).

2. ARCH_DMA_MINALIGN

   Architectures must ensure that kmalloc'ed buffer is DMA-safe. Drivers and subsystems depend on it. If an architecture isn't fully DMA-coherent (i.e. hardware doesn't ensure that data in the CPU cache is identical to data in main memory), ARCH_DMA_MINALIGN must be set so that the memory allocator makes sure that kmalloc'ed buffer doesn't share a cache line with the others. See arch/arm/include/asm/cache.h as an example.

   Note that ARCH_DMA_MINALIGN is about DMA memory alignment constraints. You don't need to worry about the architecture data alignment constraints (e.g. the alignment constraints about 64-bit objects).

<a id="rst-closing"></a>

## Closing

This document, and the API itself, would not be in its current form without the feedback and suggestions from numerous individuals. We would like to specifically mention, in no particular order, the following people:



```text
Russell King <rmk@arm.linux.org.uk>
Leo Dagum <dagum@barrel.engr.sgi.com>
Ralf Baechle <ralf@oss.sgi.com>
Grant Grundler <grundler@cup.hp.com>
Jay Estabrook <Jay.Estabrook@compaq.com>
Thomas Sailer <sailer@ife.ee.ethz.ch>
Andrea Arcangeli <andrea@suse.de>
Jens Axboe <jens.axboe@oracle.com>
David Mosberger-Tang <davidm@hpl.hp.com>
```

---

# Dynamic DMA mapping using the generic device

_Peios Kernel / Internals / Core APIs_

> This document describes the DMA API. For a more gentle introduction of the API (and actual examples), see Documentation/core-api/dma-api-howto.rst.

<a id="rst-dynamic-dma-mapping-using-the-generic-device"></a>

**Author:** James E.J. Bottomley &lt;[James.Bottomley@HansenPartnership.com](<mailto:James.Bottomley@HansenPartnership.com>)&gt;

This document describes the DMA API.  For a more gentle introduction of the API (and actual examples), see [Documentation/core-api/dma-api-howto.rst](/kernel/internals/core-api/dma-api-howto.md).

This API is split into two pieces.  Part I describes the basic API. Part II describes extensions for supporting non-coherent memory machines.  Unless you know that your driver absolutely has to support non-coherent platforms (this is usually only legacy platforms) you should only use the API described in part I.

<a id="rst-part-i-dma-api"></a>

## Part I - DMA API

To get the DMA API, you must \#include &lt;linux/dma-mapping.h&gt;.  This provides dma_addr_t and the interfaces described below.

A dma_addr_t can hold any valid DMA address for the platform.  It can be given to a device to use as a DMA source or target.  A CPU cannot reference a dma_addr_t directly because there may be translation between its physical address space and the DMA address space.

<a id="rst-part-ia-using-large-dma-coherent-buffers"></a>

## Part Ia - Using large DMA-coherent buffers



```text
void *
dma_alloc_coherent(struct device *dev, size_t size,
                   dma_addr_t *dma_handle, gfp_t flag)
```

Coherent memory is memory for which a write by either the device or the processor can immediately be read by the processor or device without having to worry about caching effects.  (You may however need to make sure to flush the processor's write buffers before telling devices to read that memory.)

This routine allocates a region of &lt;size&gt; bytes of coherent memory.

It returns a pointer to the allocated region (in the processor's virtual address space) or NULL if the allocation failed.

It also returns a &lt;dma_handle&gt; which may be cast to an unsigned integer the same width as the bus and given to the device as the DMA address base of the region.

Note: coherent memory can be expensive on some platforms, and the minimum allocation length may be as big as a page, so you should consolidate your requests for coherent memory as much as possible. The simplest way to do that is to use the dma_pool calls (see below).

The flag parameter allows the caller to specify the `GFP_` flags (see kmalloc()) for the allocation (the implementation may ignore flags that affect the location of the returned memory, like GFP_DMA).



```text
void
dma_free_coherent(struct device *dev, size_t size, void *cpu_addr,
                  dma_addr_t dma_handle)
```

Free a previously allocated region of coherent memory.  dev, size and dma_handle must all be the same as those passed into dma_alloc_coherent().  cpu_addr must be the virtual address returned by dma_alloc_coherent().

Note that unlike the sibling allocation call, this routine may only be called with IRQs enabled.

<a id="rst-part-ib-using-small-dma-coherent-buffers"></a>

## Part Ib - Using small DMA-coherent buffers

To get this part of the DMA API, you must \#include &lt;linux/dmapool.h&gt;

Many drivers need lots of small DMA-coherent memory regions for DMA descriptors or I/O buffers.  Rather than allocating in units of a page or more using dma_alloc_coherent(), you can use DMA pools.  These work much like a struct kmem_cache, except that they use the DMA-coherent allocator, not \__get_free_pages().  Also, they understand common hardware constraints for alignment, like queue heads needing to be aligned on N-byte boundaries.


#### <a id="c-dma_pool_create_node"></a>`dma_pool_create_node()`

```c
struct dma_pool * dma_pool_create_node(const char *name, struct device *dev, size_t size, size_t align, size_t boundary, int node)
```

Creates a pool of coherent DMA memory blocks.

**Parameters**

- `const char *name`: name of pool, for diagnostics
- `struct device *dev`: device that will be doing the DMA
- `size_t size`: size of the blocks in this pool.
- `size_t align`: alignment requirement for blocks; must be a power of two
- `size_t boundary`: returned blocks won't cross this power of two boundary
- `int node`: optional NUMA node to allocate structs 'dma_pool' and 'dma_page' on

**Context**

not `in_interrupt()`

**Description**

Given one of these pools, [`dma_pool_alloc()`](#c-dma_pool_alloc)
may be used to allocate memory.  Such memory will all have coherent
DMA mappings, accessible by the device and its driver without using
cache flushing primitives.  The actual size of blocks allocated may be
larger than requested because of alignment.

If **boundary** is nonzero, objects returned from [`dma_pool_alloc()`](#c-dma_pool_alloc) won't
cross that size boundary.  This is useful for devices which have
addressing restrictions on individual DMA transfers, such as not crossing
boundaries of 4KBytes.

**Return**

a dma allocation pool with the requested characteristics, or
`NULL` if one can't be created.

#### <a id="c-dma_pool_destroy"></a>`dma_pool_destroy()`

```c
void dma_pool_destroy(struct dma_pool *pool)
```

destroys a pool of dma memory blocks.

**Parameters**

- `struct dma_pool *pool`: dma pool that will be destroyed

**Context**

\!`in_interrupt()`

**Description**

Caller guarantees that no more memory from the pool is in use,
and that nothing will try to use the pool after this call.

#### <a id="c-dma_pool_alloc"></a>`dma_pool_alloc()`

```c
void * dma_pool_alloc(struct dma_pool *pool, gfp_t mem_flags, dma_addr_t *handle)
```

get a block of coherent memory

**Parameters**

- `struct dma_pool *pool`: dma pool that will produce the block
- `gfp_t mem_flags`: GFP_* bitmask
- `dma_addr_t *handle`: pointer to dma address of block

**Return**

the kernel virtual address of a currently unused block,
and reports its dma address through the handle.
If such a memory block can't be allocated, `NULL` is returned.

#### <a id="c-dma_pool_free"></a>`dma_pool_free()`

```c
void dma_pool_free(struct dma_pool *pool, void *vaddr, dma_addr_t dma)
```

put block back into dma pool

**Parameters**

- `struct dma_pool *pool`: the dma pool holding the block
- `void *vaddr`: virtual address of block
- `dma_addr_t dma`: dma address of block

**Description**

Caller promises neither device nor driver will again touch this block
unless it is first re-allocated.

#### <a id="c-dmam_pool_create"></a>`dmam_pool_create()`

```c
struct dma_pool * dmam_pool_create(const char *name, struct device *dev, size_t size, size_t align, size_t allocation)
```

Managed `dma_pool_create()`

**Parameters**

- `const char *name`: name of pool, for diagnostics
- `struct device *dev`: device that will be doing the DMA
- `size_t size`: size of the blocks in this pool.
- `size_t align`: alignment requirement for blocks; must be a power of two
- `size_t allocation`: returned blocks won't cross this boundary (or zero)

**Description**

Managed `dma_pool_create()`.  DMA pool created with this function is
automatically destroyed on driver detach.

**Return**

a managed dma allocation pool with the requested
characteristics, or `NULL` if one can't be created.

#### <a id="c-dmam_pool_destroy"></a>`dmam_pool_destroy()`

```c
void dmam_pool_destroy(struct dma_pool *pool)
```

Managed [`dma_pool_destroy()`](#c-dma_pool_destroy)

**Parameters**

- `struct dma_pool *pool`: dma pool that will be destroyed

**Description**

Managed [`dma_pool_destroy()`](#c-dma_pool_destroy).



#### <a id="c-dma_pool_zalloc"></a>`dma_pool_zalloc()`

```c
void * dma_pool_zalloc(struct dma_pool *pool, gfp_t mem_flags, dma_addr_t *handle)
```

Get a zero-initialized block of DMA coherent memory.

**Parameters**

- `struct dma_pool *pool`: dma pool that will produce the block
- `gfp_t mem_flags`: GFP_* bitmask
- `dma_addr_t *handle`: pointer to dma address of block

**Description**

Same as [`dma_pool_alloc()`](#c-dma_pool_alloc), but the returned memory is zeroed.


<a id="rst-part-ic-dma-addressing-limitations"></a>

## Part Ic - DMA addressing limitations

DMA mask is a bit mask of the addressable region for the device. In other words, if applying the DMA mask (a bitwise AND operation) to the DMA address of a memory region does not clear any bits in the address, then the device can perform DMA to that memory region.

All the below functions which set a DMA mask may fail if the requested mask cannot be used with the device, or if the device is not capable of doing DMA.



```text
int
dma_set_mask_and_coherent(struct device *dev, u64 mask)
```

Updates both streaming and coherent DMA masks.

Returns: 0 if successful and a negative error if not.



```text
int
dma_set_mask(struct device *dev, u64 mask)
```

Updates only the streaming DMA mask.

Returns: 0 if successful and a negative error if not.



```text
int
dma_set_coherent_mask(struct device *dev, u64 mask)
```

Updates only the coherent DMA mask.

Returns: 0 if successful and a negative error if not.



```text
u64
dma_get_required_mask(struct device *dev)
```

This API returns the mask that the platform requires to operate efficiently.  Usually this means the returned mask is the minimum required to cover all of memory.  Examining the required mask gives drivers with variable descriptor sizes the opportunity to use smaller descriptors as necessary.

Requesting the required mask does not alter the current mask.  If you wish to take advantage of it, you should issue a dma_set_mask() call to set the mask to the value returned.



```text
size_t
dma_max_mapping_size(struct device *dev);
```

Returns the maximum size of a mapping for the device. The size parameter of the mapping functions like dma_map_single(), dma_map_page() and others should not be larger than the returned value.



```text
size_t
dma_opt_mapping_size(struct device *dev);
```

Returns the maximum optimal size of a mapping for the device.

Mapping larger buffers may take much longer in certain scenarios. In addition, for high-rate short-lived streaming mappings, the upfront time spent on the mapping may account for an appreciable part of the total request lifetime. As such, if splitting larger requests incurs no significant performance penalty, then device drivers are advised to limit total DMA streaming mappings length to the returned value.



```text
bool
dma_need_sync(struct device *dev, dma_addr_t dma_addr);
```

Returns %true if dma_sync_single_for\_\{device,cpu\} calls are required to transfer memory ownership.  Returns %false if those calls can be skipped.



```text
unsigned long
dma_get_merge_boundary(struct device *dev);
```

Returns the DMA merge boundary. If the device cannot merge any DMA address segments, the function returns 0.

<a id="rst-part-id-streaming-dma-mappings"></a>

## Part Id - Streaming DMA mappings

Streaming DMA allows to map an existing buffer for DMA transfers and then unmap it when finished.  Map functions are not guaranteed to succeed, so the return value must be checked.

> [!NOTE]
>
> In particular, mapping may fail for memory not addressable by the device, e.g. if it is not within the DMA mask of the device and/or a connecting bus bridge.  Streaming DMA functions try to overcome such addressing constraints, either by using an IOMMU (a device which maps I/O DMA addresses to physical memory addresses), or by copying the data to/from a bounce buffer if the kernel is configured with a [SWIOTLB](</kernel/internals/core-api/swiotlb.md>).  However, these methods are not always available, and even if they are, they may still fail for a number of reasons.
>
> In short, a device driver may need to be wary of where buffers are located in physical memory, especially if the DMA mask is less than 32 bits.



```text
dma_addr_t
dma_map_single(struct device *dev, void *cpu_addr, size_t size,
               enum dma_data_direction direction)
```

Maps a piece of processor virtual memory so it can be accessed by the device and returns the DMA address of the memory.

The DMA API uses a strongly typed enumerator for its direction:


<table>
<tbody>
<tr>
<td>


DMA_NONE

</td>
<td>


no direction (used for debugging)

</td>
</tr>
<tr>
<td>


DMA_TO_DEVICE

</td>
<td>


data is going from the memory to the device

</td>
</tr>
<tr>
<td>


DMA_FROM_DEVICE

</td>
<td>


data is coming from the device to the memory

</td>
</tr>
<tr>
<td>


DMA_BIDIRECTIONAL

</td>
<td>


direction isn't known

</td>
</tr>
</tbody>
</table>

> [!NOTE]
>
> Contiguous kernel virtual space may not be contiguous as physical memory.  Since this API does not provide any scatter/gather capability, it will fail if the user tries to map a non-physically contiguous piece of memory.  For this reason, memory to be mapped by this API should be obtained from sources which guarantee it to be physically contiguous (like kmalloc).

> [!WARNING]
>
> Memory coherency operates at a granularity called the cache line width.  In order for memory mapped by this API to operate correctly, the mapped region must begin exactly on a cache line boundary and end exactly on one (to prevent two separately mapped regions from sharing a single cache line).  Since the cache line size may not be known at compile time, the API will not enforce this requirement.  Therefore, it is recommended that driver writers who don't take special care to determine the cache line size at run time only map virtual regions that begin and end on page boundaries (which are guaranteed also to be cache line boundaries).
>
> DMA_TO_DEVICE synchronisation must be done after the last modification of the memory region by the software and before it is handed off to the device.  Once this primitive is used, memory covered by this primitive should be treated as read-only by the device.  If the device may write to it at any point, it should be DMA_BIDIRECTIONAL (see below).
>
> DMA_FROM_DEVICE synchronisation must be done before the driver accesses data that may be changed by the device.  This memory should be treated as read-only by the driver.  If the driver needs to write to it at any point, it should be DMA_BIDIRECTIONAL (see below).
>
> DMA_BIDIRECTIONAL requires special handling: it means that the driver isn't sure if the memory was modified before being handed off to the device and also isn't sure if the device will also modify it.  Thus, you must always sync bidirectional memory twice: once before the memory is handed off to the device (to make sure all memory changes are flushed from the processor) and once before the data may be accessed after being used by the device (to make sure any processor cache lines are updated with data that the device may have changed).



```text
void
dma_unmap_single(struct device *dev, dma_addr_t dma_addr, size_t size,
                 enum dma_data_direction direction)
```

Unmaps the region previously mapped.  All the parameters passed in must be identical to those passed to (and returned by) dma_map_single().



```text
dma_addr_t
dma_map_page(struct device *dev, struct page *page,
             unsigned long offset, size_t size,
             enum dma_data_direction direction)

void
dma_unmap_page(struct device *dev, dma_addr_t dma_address, size_t size,
               enum dma_data_direction direction)
```

API for mapping and unmapping for pages.  All the notes and warnings for the other mapping APIs apply here.  Also, although the &lt;offset&gt; and &lt;size&gt; parameters are provided to do partial page mapping, it is recommended that you never use these unless you really know what the cache width is.



```text
dma_addr_t
dma_map_resource(struct device *dev, phys_addr_t phys_addr, size_t size,
                 enum dma_data_direction dir, unsigned long attrs)

void
dma_unmap_resource(struct device *dev, dma_addr_t addr, size_t size,
                   enum dma_data_direction dir, unsigned long attrs)
```

API for mapping and unmapping for MMIO resources. All the notes and warnings for the other mapping APIs apply here. The API should only be used to map device MMIO resources, mapping of RAM is not permitted.



```text
int
dma_mapping_error(struct device *dev, dma_addr_t dma_addr)
```

In some circumstances dma_map_single(), dma_map_page() and dma_map_resource() will fail to create a mapping. A driver can check for these errors by testing the returned DMA address with dma_mapping_error(). A non-zero return value means the mapping could not be created and the driver should take appropriate action (e.g. reduce current DMA mapping usage or delay and try again later).



```text
int
dma_map_sg(struct device *dev, struct scatterlist *sg,
           int nents, enum dma_data_direction direction)
```

Maps a scatter/gather list for DMA. Returns the number of DMA address segments mapped, which may be smaller than &lt;nents&gt; passed in if several consecutive sglist entries are merged (e.g. with an IOMMU, or if some adjacent segments just happen to be physically contiguous).

Please note that the sg cannot be mapped again if it has been mapped once. The mapping process is allowed to destroy information in the sg.

As with the other mapping interfaces, dma_map_sg() can fail. When it does, 0 is returned and a driver must take appropriate action. It is critical that the driver do something, in the case of a block driver aborting the request or even oopsing is better than doing nothing and corrupting the filesystem.

With scatterlists, you use the resulting mapping like this:



```text
int i, count = dma_map_sg(dev, sglist, nents, direction);
struct scatterlist *sg;

for_each_sg(sglist, sg, count, i) {
        hw_address[i] = sg_dma_address(sg);
        hw_len[i] = sg_dma_len(sg);
}
```

where nents is the number of entries in the sglist.

The implementation is free to merge several consecutive sglist entries into one.  The returned number is the actual number of sg entries it mapped them to. On failure, 0 is returned.

Then you should loop count times (note: this can be less than nents times) and use sg_dma_address() and sg_dma_len() macros where you previously accessed sg-&gt;address and sg-&gt;length as shown above.



```text
void
dma_unmap_sg(struct device *dev, struct scatterlist *sg,
             int nents, enum dma_data_direction direction)
```

Unmap the previously mapped scatter/gather list.  All the parameters must be the same as those and passed in to the scatter/gather mapping API.

Note: &lt;nents&gt; must be the number you passed in, *not* the number of DMA address entries returned.



```text
void
dma_sync_single_for_cpu(struct device *dev, dma_addr_t dma_handle,
                        size_t size,
                        enum dma_data_direction direction)

void
dma_sync_single_for_device(struct device *dev, dma_addr_t dma_handle,
                           size_t size,
                           enum dma_data_direction direction)

void
dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
                    int nents,
                    enum dma_data_direction direction)

void
dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
                       int nents,
                       enum dma_data_direction direction)
```

Synchronise a single contiguous or scatter/gather mapping for the CPU and device. With the sync_sg API, all the parameters must be the same as those passed into the sg mapping API. With the sync_single API, you can use dma_handle and size parameters that aren't identical to those passed into the single mapping API to do a partial sync.

> [!NOTE]
>
> You must do this:
>
> - Before reading values that have been written by DMA from the device (use the DMA_FROM_DEVICE direction)
>
> - After writing values that will be written to the device using DMA (use the DMA_TO_DEVICE) direction
>
> - before *and* after handing memory to the device if the memory is DMA_BIDIRECTIONAL

See also dma_map_single().



```text
dma_addr_t
dma_map_single_attrs(struct device *dev, void *cpu_addr, size_t size,
                     enum dma_data_direction dir,
                     unsigned long attrs)

void
dma_unmap_single_attrs(struct device *dev, dma_addr_t dma_addr,
                       size_t size, enum dma_data_direction dir,
                       unsigned long attrs)

int
dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl,
                 int nents, enum dma_data_direction dir,
                 unsigned long attrs)

void
dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
                   int nents, enum dma_data_direction dir,
                   unsigned long attrs)
```

The four functions above are just like the counterpart functions without the \_attrs suffixes, except that they pass an optional dma_attrs.

The interpretation of DMA attributes is architecture-specific, and each attribute should be documented in [Documentation/core-api/dma-attributes.rst](/kernel/internals/core-api/dma-attributes.md).

If dma_attrs are 0, the semantics of each of these functions is identical to those of the corresponding function without the \_attrs suffix. As a result dma_map_single_attrs() can generally replace dma_map_single(), etc.

As an example of the use of the `*_attrs` functions, here's how you could pass an attribute DMA_ATTR_FOO when mapping memory for DMA:



```text
#include <linux/dma-mapping.h>
/* DMA_ATTR_FOO should be defined in linux/dma-mapping.h and
* documented in Documentation/core-api/dma-attributes.rst */
...

        unsigned long attr;
        attr |= DMA_ATTR_FOO;
        ....
        n = dma_map_sg_attrs(dev, sg, nents, DMA_TO_DEVICE, attr);
        ....
```

Architectures that care about DMA_ATTR_FOO would check for its presence in their implementations of the mapping and unmapping routines, e.g.::



```text
void whizco_dma_map_sg_attrs(struct device *dev, dma_addr_t dma_addr,
                             size_t size, enum dma_data_direction dir,
                             unsigned long attrs)
{
        ....
        if (attrs & DMA_ATTR_FOO)
                /* twizzle the frobnozzle */
        ....
}
```

<a id="rst-part-ie-iova-based-dma-mappings"></a>

## Part Ie - IOVA-based DMA mappings

These APIs allow a very efficient mapping when using an IOMMU.  They are an optional path that requires extra code and are only recommended for drivers where DMA mapping performance, or the space usage for storing the DMA addresses matter.  All the considerations from the previous section apply here as well.



```text
bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
            phys_addr_t phys, size_t size);
```

Is used to try to allocate IOVA space for mapping operation.  If it returns false this API can't be used for the given device and the normal streaming DMA mapping API should be used.  The `struct dma_iova_state` is allocated by the driver and must be kept around until unmap time.



```text
static inline bool dma_use_iova(struct dma_iova_state *state)
```

Can be used by the driver to check if the IOVA-based API is used after a call to dma_iova_try_alloc.  This can be useful in the unmap path.



```text
int dma_iova_link(struct device *dev, struct dma_iova_state *state,
            phys_addr_t phys, size_t offset, size_t size,
            enum dma_data_direction dir, unsigned long attrs);
```

Is used to link ranges to the IOVA previously allocated.  The start of all but the first call to dma_iova_link for a given state must be aligned to the DMA merge boundary returned by `dma_get_merge_boundary())`, and the size of all but the last range must be aligned to the DMA merge boundary as well.



```text
int dma_iova_sync(struct device *dev, struct dma_iova_state *state,
            size_t offset, size_t size);
```

Must be called to sync the IOMMU page tables for IOVA-range mapped by one or more calls to `dma_iova_link()`.

For drivers that use a one-shot mapping, all ranges can be unmapped and the IOVA freed by calling:



```text
void dma_iova_destroy(struct device *dev, struct dma_iova_state *state,
             size_t mapped_len, enum dma_data_direction dir,
             unsigned long attrs);
```

Alternatively drivers can dynamically manage the IOVA space by unmapping and mapping individual regions.  In that case



```text
void dma_iova_unlink(struct device *dev, struct dma_iova_state *state,
            size_t offset, size_t size, enum dma_data_direction dir,
            unsigned long attrs);
```

is used to unmap a range previously mapped, and



```text
void dma_iova_free(struct device *dev, struct dma_iova_state *state);
```

is used to free the IOVA space.  All regions must have been unmapped using `dma_iova_unlink()` before calling `dma_iova_free()`.

<a id="rst-part-ii-non-coherent-dma-allocations"></a>

## Part II - Non-coherent DMA allocations

These APIs allow to allocate pages that are guaranteed to be DMA addressable by the passed in device, but which need explicit management of memory ownership for the kernel vs the device.

If you don't understand how cache line coherency works between a processor and an I/O device, you should not be using this part of the API.



```text
struct page *
dma_alloc_pages(struct device *dev, size_t size, dma_addr_t *dma_handle,
                enum dma_data_direction dir, gfp_t gfp)
```

This routine allocates a region of &lt;size&gt; bytes of non-coherent memory.  It returns a pointer to first struct page for the region, or NULL if the allocation failed. The resulting struct page can be used for everything a struct page is suitable for.

It also returns a &lt;dma_handle&gt; which may be cast to an unsigned integer the same width as the bus and given to the device as the DMA address base of the region.

The dir parameter specified if data is read and/or written by the device, see dma_map_single() for details.

The gfp parameter allows the caller to specify the `GFP_` flags (see kmalloc()) for the allocation, but rejects flags used to specify a memory zone such as GFP_DMA or GFP_HIGHMEM.

Before giving the memory to the device, dma_sync_single_for_device() needs to be called, and before reading memory written by the device, dma_sync_single_for_cpu(), just like for streaming DMA mappings that are reused.



```text
void
dma_free_pages(struct device *dev, size_t size, struct page *page,
                dma_addr_t dma_handle, enum dma_data_direction dir)
```

Free a region of memory previously allocated using dma_alloc_pages(). dev, size, dma_handle and dir must all be the same as those passed into dma_alloc_pages().  page must be the pointer returned by dma_alloc_pages().



```text
int
dma_mmap_pages(struct device *dev, struct vm_area_struct *vma,
               size_t size, struct page *page)
```

Map an allocation returned from dma_alloc_pages() into a user address space. dev and size must be the same as those passed into dma_alloc_pages(). page must be the pointer returned by dma_alloc_pages().



```text
void *
dma_alloc_noncoherent(struct device *dev, size_t size,
                dma_addr_t *dma_handle, enum dma_data_direction dir,
                gfp_t gfp)
```

This routine is a convenient wrapper around dma_alloc_pages that returns the kernel virtual address for the allocated memory instead of the page structure.



```text
void
dma_free_noncoherent(struct device *dev, size_t size, void *cpu_addr,
                dma_addr_t dma_handle, enum dma_data_direction dir)
```

Free a region of memory previously allocated using dma_alloc_noncoherent(). dev, size, dma_handle and dir must all be the same as those passed into dma_alloc_noncoherent().  cpu_addr must be the virtual address returned by dma_alloc_noncoherent().



```text
struct sg_table *
dma_alloc_noncontiguous(struct device *dev, size_t size,
                        enum dma_data_direction dir, gfp_t gfp,
                        unsigned long attrs);
```

This routine allocates  &lt;size&gt; bytes of non-coherent and possibly non-contiguous memory.  It returns a pointer to struct sg_table that describes the allocated and DMA mapped memory, or NULL if the allocation failed. The resulting memory can be used for struct page mapped into a scatterlist are suitable for.

The return sg_table is guaranteed to have 1 single DMA mapped segment as indicated by sgt-&gt;nents, but it might have multiple CPU side segments as indicated by sgt-&gt;orig_nents.

The dir parameter specified if data is read and/or written by the device, see dma_map_single() for details.

The gfp parameter allows the caller to specify the `GFP_` flags (see kmalloc()) for the allocation, but rejects flags used to specify a memory zone such as GFP_DMA or GFP_HIGHMEM.

The attrs argument must be either 0 or DMA_ATTR_ALLOC_SINGLE_PAGES.

Before giving the memory to the device, dma_sync_sgtable_for_device() needs to be called, and before reading memory written by the device, dma_sync_sgtable_for_cpu(), just like for streaming DMA mappings that are reused.



```text
void
dma_free_noncontiguous(struct device *dev, size_t size,
                       struct sg_table *sgt,
                       enum dma_data_direction dir)
```

Free memory previously allocated using dma_alloc_noncontiguous().  dev, size, and dir must all be the same as those passed into dma_alloc_noncontiguous(). sgt must be the pointer returned by dma_alloc_noncontiguous().



```text
void *
dma_vmap_noncontiguous(struct device *dev, size_t size,
        struct sg_table *sgt)
```

Return a contiguous kernel mapping for an allocation returned from dma_alloc_noncontiguous().  dev and size must be the same as those passed into dma_alloc_noncontiguous().  sgt must be the pointer returned by dma_alloc_noncontiguous().

Once a non-contiguous allocation is mapped using this function, the flush_kernel_vmap_range() and invalidate_kernel_vmap_range() APIs must be used to manage the coherency between the kernel mapping, the device and user space mappings (if any).



```text
void
dma_vunmap_noncontiguous(struct device *dev, void *vaddr)
```

Unmap a kernel mapping returned by dma_vmap_noncontiguous().  dev must be the same the one passed into dma_alloc_noncontiguous().  vaddr must be the pointer returned by dma_vmap_noncontiguous().



```text
int
dma_mmap_noncontiguous(struct device *dev, struct vm_area_struct *vma,
                       size_t size, struct sg_table *sgt)
```

Map an allocation returned from dma_alloc_noncontiguous() into a user address space.  dev and size must be the same as those passed into dma_alloc_noncontiguous().  sgt must be the pointer returned by dma_alloc_noncontiguous().



```text
int
dma_get_cache_alignment(void)
```

Returns the processor cache alignment.  This is the absolute minimum alignment *and* width that you must observe when either mapping memory or doing partial flushes.

> [!NOTE]
>
> This API may return a number *larger* than the actual cache line, but it will guarantee that one or more cache lines fit exactly into the width returned by this call.  It will also always be a power of two for easy alignment.

<a id="rst-part-iii-debug-drivers-use-of-the-dma-api"></a>

## Part III - Debug drivers use of the DMA API

The DMA API as described above has some constraints. DMA addresses must be released with the corresponding function with the same size for example. With the advent of hardware IOMMUs it becomes more and more important that drivers do not violate those constraints. In the worst case such a violation can result in data corruption up to destroyed filesystems.

To debug drivers and find bugs in the usage of the DMA API checking code can be compiled into the kernel which will tell the developer about those violations. If your architecture supports it you can select the "Enable debugging of DMA API usage" option in your kernel configuration. Enabling this option has a performance impact. Do not enable it in production kernels.

If you boot the resulting kernel will contain code which does some bookkeeping about what DMA memory was allocated for which device. If this code detects an error it prints a warning message with some details into your kernel log. An example warning message may look like this:



```text
WARNING: at /data2/repos/linux-2.6-iommu/lib/dma-debug.c:448
        check_unmap+0x203/0x490()
Hardware name:
forcedeth 0000:00:08.0: DMA-API: device driver frees DMA memory with wrong
        function [device address=0x00000000640444be] [size=66 bytes] [mapped as
single] [unmapped as page]
Modules linked in: nfsd exportfs bridge stp llc r8169
Pid: 0, comm: swapper Tainted: G        W  2.6.28-dmatest-09289-g8bb99c0 #1
Call Trace:
<IRQ>  [<ffffffff80240b22>] warn_slowpath+0xf2/0x130
[<ffffffff80647b70>] _spin_unlock+0x10/0x30
[<ffffffff80537e75>] usb_hcd_link_urb_to_ep+0x75/0xc0
[<ffffffff80647c22>] _spin_unlock_irqrestore+0x12/0x40
[<ffffffff8055347f>] ohci_urb_enqueue+0x19f/0x7c0
[<ffffffff80252f96>] queue_work+0x56/0x60
[<ffffffff80237e10>] enqueue_task_fair+0x20/0x50
[<ffffffff80539279>] usb_hcd_submit_urb+0x379/0xbc0
[<ffffffff803b78c3>] cpumask_next_and+0x23/0x40
[<ffffffff80235177>] find_busiest_group+0x207/0x8a0
[<ffffffff8064784f>] _spin_lock_irqsave+0x1f/0x50
[<ffffffff803c7ea3>] check_unmap+0x203/0x490
[<ffffffff803c8259>] debug_dma_unmap_phys+0x49/0x50
[<ffffffff80485f26>] nv_tx_done_optimized+0xc6/0x2c0
[<ffffffff80486c13>] nv_nic_irq_optimized+0x73/0x2b0
[<ffffffff8026df84>] handle_IRQ_event+0x34/0x70
[<ffffffff8026ffe9>] handle_edge_irq+0xc9/0x150
[<ffffffff8020e3ab>] do_IRQ+0xcb/0x1c0
[<ffffffff8020c093>] ret_from_intr+0x0/0xa
<EOI> <4>---[ end trace f6435a98e2a38c0e ]---
```

The driver developer can find the driver and the device including a stacktrace of the DMA API call which caused this warning.

Per default only the first error will result in a warning message. All other errors will only silently counted. This limitation exist to prevent the code from flooding your kernel log. To support debugging a device driver this can be disabled via debugfs. See the debugfs interface documentation below for details.

The debugfs directory for the DMA API debugging code is called dma-api/. In this directory the following files can currently be found:


<table>
<tbody>
<tr>
<td>


dma-api/all_errors

</td>
<td>


This file contains a numeric value. If this value is not equal to zero the debugging code will print a warning for every error it finds into the kernel log. Be careful with this option, as it can easily flood your logs.

</td>
</tr>
<tr>
<td>


dma-api/disabled

</td>
<td>


This read-only file contains the character 'Y' if the debugging code is disabled. This can happen when it runs out of memory or if it was disabled at boot time

</td>
</tr>
<tr>
<td>


dma-api/dump

</td>
<td>


This read-only file contains current DMA mappings.

</td>
</tr>
<tr>
<td>


dma-api/error_count

</td>
<td>


This file is read-only and shows the total numbers of errors found.

</td>
</tr>
<tr>
<td>


dma-api/num_errors

</td>
<td>


The number in this file shows how many warnings will be printed to the kernel log before it stops. This number is initialized to one at system boot and be set by writing into this file

</td>
</tr>
<tr>
<td>


dma-api/min_free_entries

</td>
<td>


This read-only file can be read to get the minimum number of free dma_debug_entries the allocator has ever seen. If this value goes down to zero the code will attempt to increase nr_total_entries to compensate.

</td>
</tr>
<tr>
<td>


dma-api/num_free_entries

</td>
<td>


The current number of free dma_debug_entries in the allocator.

</td>
</tr>
<tr>
<td>


dma-api/nr_total_entries

</td>
<td>


The total number of dma_debug_entries in the allocator, both free and used.

</td>
</tr>
<tr>
<td>


dma-api/driver_filter

</td>
<td>


You can write a name of a driver into this file to limit the debug output to requests from that particular driver. Write an empty string to that file to disable the filter and see all errors again.

</td>
</tr>
</tbody>
</table>

If you have this code compiled into your kernel it will be enabled by default. If you want to boot without the bookkeeping anyway you can provide 'dma_debug=off' as a boot parameter. This will disable DMA API debugging. Notice that you can not enable it again at runtime. You have to reboot to do so.

If you want to see debug messages only for a special device driver you can specify the dma_debug_driver=&lt;drivername&gt; parameter. This will enable the driver filter at boot time. The debug code will only print errors for that driver afterwards. This filter can be disabled or changed later using debugfs.

When the code disables itself at runtime this is most likely because it ran out of dma_debug_entries and was unable to allocate more on-demand. 65536 entries are preallocated at boot - if this is too low for you boot with 'dma_debug_entries=&lt;your_desired_number&gt;' to overwrite the default. Note that the code allocates entries in batches, so the exact number of preallocated entries may be greater than the actual number requested. The code will print to the kernel log each time it has dynamically allocated as many entries as were initially preallocated. This is to indicate that a larger preallocation size may be appropriate, or if it happens continually that a driver may be leaking mappings.



```text
void
debug_dma_mapping_error(struct device *dev, dma_addr_t dma_addr);
```

dma-debug interface debug_dma_mapping_error() to debug drivers that fail to check DMA mapping errors on addresses returned by dma_map_single() and dma_map_page() interfaces. This interface clears a flag set by debug_dma_map_phys() to indicate that dma_mapping_error() has been called by the driver. When driver does unmap, debug_dma_unmap() checks the flag and if this flag is still set, prints warning message that includes call trace that leads up to the unmap. This interface can be called from dma_mapping_error() routines to enable DMA mapping error check debugging.

<a id="rst-functions-and-structures"></a>

### Functions and structures


#### <a id="c-sg_next"></a>`sg_next()`

```c
struct scatterlist * sg_next(struct scatterlist *sg)
```

return the next scatterlist entry in a list

**Parameters**

- `struct scatterlist *sg`: The current sg entry

**Description**

Usually the next entry will be **sg** + 1, but if this sg element is part
of a chained scatterlist, it could jump to the start of a new
scatterlist array.

#### <a id="c-sg_assign_page"></a>`sg_assign_page()`

```c
void sg_assign_page(struct scatterlist *sg, struct page *page)
```

Assign a given page to an SG entry

**Parameters**

- `struct scatterlist *sg`: SG entry
- `struct page *page`: The page

**Description**

Assign page to sg entry. Also see [`sg_set_page()`](#c-sg_set_page), the most commonly used
variant.

#### <a id="c-sg_set_page"></a>`sg_set_page()`

```c
void sg_set_page(struct scatterlist *sg, struct page *page, unsigned int len, unsigned int offset)
```

Set sg entry to point at given page

**Parameters**

- `struct scatterlist *sg`: SG entry
- `struct page *page`: The page
- `unsigned int len`: Length of data
- `unsigned int offset`: Offset into page

**Description**

Use this function to set an sg entry pointing at a page, never assign
the page directly. We encode sg table information in the lower bits
of the page pointer. See `sg_page()` for looking up the page belonging
to an sg entry.

#### <a id="c-sg_set_folio"></a>`sg_set_folio()`

```c
void sg_set_folio(struct scatterlist *sg, struct folio *folio, size_t len, size_t offset)
```

Set sg entry to point at given folio

**Parameters**

- `struct scatterlist *sg`: SG entry
- `struct folio *folio`: The folio
- `size_t len`: Length of data
- `size_t offset`: Offset into folio

**Description**

Use this function to set an sg entry pointing at a folio, never assign
the folio directly. We encode sg table information in the lower bits
of the folio pointer. See `sg_page()` for looking up the page belonging
to an sg entry.

#### <a id="c-sg_set_buf"></a>`sg_set_buf()`

```c
void sg_set_buf(struct scatterlist *sg, const void *buf, unsigned int buflen)
```

Set sg entry to point at given data

**Parameters**

- `struct scatterlist *sg`: SG entry
- `const void *buf`: Data
- `unsigned int buflen`: Data length

#### <a id="c-sg_chain"></a>`sg_chain()`

```c
void sg_chain(struct scatterlist *prv, unsigned int prv_nents, struct scatterlist *sgl)
```

Chain two sglists together

**Parameters**

- `struct scatterlist *prv`: First scatterlist
- `unsigned int prv_nents`: Number of entries in prv
- `struct scatterlist *sgl`: Second scatterlist

**Description**

Links **prv** and **sgl** together, to form a longer scatterlist.

#### <a id="c-sg_mark_end"></a>`sg_mark_end()`

```c
void sg_mark_end(struct scatterlist *sg)
```

Mark the end of the scatterlist

**Parameters**

- `struct scatterlist *sg`: SG entryScatterlist

**Description**

Marks the passed in sg entry as the termination point for the sg
table. A call to [`sg_next()`](#c-sg_next) on this entry will return NULL.

#### <a id="c-sg_unmark_end"></a>`sg_unmark_end()`

```c
void sg_unmark_end(struct scatterlist *sg)
```

Undo setting the end of the scatterlist

**Parameters**

- `struct scatterlist *sg`: SG entryScatterlist

**Description**

Removes the termination marker from the given entry of the scatterlist.

#### <a id="c-sg_dma_is_bus_address"></a>`sg_dma_is_bus_address()`

```c
bool sg_dma_is_bus_address(struct scatterlist *sg)
```

Return whether a given segment was marked as a bus address

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

Returns true if [`sg_dma_mark_bus_address()`](#c-sg_dma_mark_bus_address) has been called on
this segment.

#### <a id="c-sg_dma_mark_bus_address"></a>`sg_dma_mark_bus_address()`

```c
void sg_dma_mark_bus_address(struct scatterlist *sg)
```

Mark the scatterlist entry as a bus address

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

Marks the passed in sg entry to indicate that the dma_address is
a bus address and doesn't need to be unmapped. This should only be
used by `dma_map_sg()` implementations to mark bus addresses
so they can be properly cleaned up in `dma_unmap_sg()`.

#### <a id="c-sg_dma_unmark_bus_address"></a>`sg_dma_unmark_bus_address()`

```c
void sg_dma_unmark_bus_address(struct scatterlist *sg)
```

Unmark the scatterlist entry as a bus address

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

Clears the bus address mark.

#### <a id="c-sg_dma_is_swiotlb"></a>`sg_dma_is_swiotlb()`

```c
bool sg_dma_is_swiotlb(struct scatterlist *sg)
```

Return whether the scatterlist was marked for SWIOTLB bouncing

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

Returns true if the scatterlist was marked for SWIOTLB bouncing. Not all
elements may have been bounced, so the caller would have to check
individual SG entries with `swiotlb_find_pool()`.

#### <a id="c-sg_dma_mark_swiotlb"></a>`sg_dma_mark_swiotlb()`

```c
void sg_dma_mark_swiotlb(struct scatterlist *sg)
```

Mark the scatterlist for SWIOTLB bouncing

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

Marks a a scatterlist for SWIOTLB bounce. Not all SG entries may be
bounced.

#### <a id="c-sg_phys"></a>`sg_phys()`

```c
dma_addr_t sg_phys(struct scatterlist *sg)
```

Return physical address of an sg entry

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

This calls `page_to_phys()` on the page in this sg entry, and adds the
sg offset. The caller must know that it is legal to call `page_to_phys()`
on the sg page.

#### <a id="c-sg_virt"></a>`sg_virt()`

```c
void * sg_virt(struct scatterlist *sg)
```

Return virtual address of an sg entry

**Parameters**

- `struct scatterlist *sg`: SG entry

**Description**

This calls [`page_address()`](/kernel/internals/mm/highmem.md#c-page_address) on the page in this sg entry, and adds the
sg offset. The caller must know that the sg page has a valid virtual
mapping.

#### <a id="c-sg_init_marker"></a>`sg_init_marker()`

```c
void sg_init_marker(struct scatterlist *sgl, unsigned int nents)
```

Initialize markers in sg table

**Parameters**

- `struct scatterlist *sgl`: The SG table
- `unsigned int nents`: Number of entries in table

#### <a id="c-sg_alloc_table_from_pages"></a>`sg_alloc_table_from_pages()`

```c
int sg_alloc_table_from_pages(struct sg_table *sgt, struct page **pages, unsigned int n_pages, unsigned int offset, unsigned long size, gfp_t gfp_mask)
```

Allocate and initialize an sg table from an array of pages

**Parameters**

- `struct sg_table *sgt`: The sg table header to use
- `struct page **pages`: Pointer to an array of page pointers
- `unsigned int n_pages`: Number of pages in the pages array
- `unsigned int offset`: Offset from start of the first page to the start of a buffer
- `unsigned long size`: Number of valid bytes in the buffer (after offset)
- `gfp_t gfp_mask`: GFP allocation mask

**Description**

Allocate and initialize an sg table from a list of pages. Contiguous
ranges of the pages are squashed into a single scatterlist node. A user
may provide an offset at a start and a size of valid data in a buffer
specified by the page array. The returned sg table is released by
sg_free_table.

**Return**

0 on success, negative error on failure

#### <a id="c-sg_page_iter_page"></a>`sg_page_iter_page()`

```c
struct page * sg_page_iter_page(struct sg_page_iter *piter)
```

get the current page held by the page iterator

**Parameters**

- `struct sg_page_iter *piter`: page iterator holding the page

#### <a id="c-sg_page_iter_dma_address"></a>`sg_page_iter_dma_address()`

```c
dma_addr_t sg_page_iter_dma_address(struct sg_dma_page_iter *dma_iter)
```

get the dma address of the current page held by the page iterator.

**Parameters**

- `struct sg_dma_page_iter *dma_iter`: page iterator holding the page

#### <a id="c-for_each_sg_page"></a>`for_each_sg_page()`

```c
for_each_sg_page(sglist, piter, nents, pgoffset)
```

iterate over the pages of the given sg list

**Parameters**

- `sglist`: sglist to iterate over
- `piter`: page iterator to hold current page, sg, sg_pgoffset
- `nents`: maximum number of sg entries to iterate over
- `pgoffset`: starting page offset (in pages)

**Description**

Callers may use [`sg_page_iter_page()`](#c-sg_page_iter_page) to get each page pointer.
In each loop it operates on PAGE_SIZE unit.

#### <a id="c-for_each_sg_dma_page"></a>`for_each_sg_dma_page()`

```c
for_each_sg_dma_page(sglist, dma_iter, dma_nents, pgoffset)
```

iterate over the pages of the given sg list

**Parameters**

- `sglist`: sglist to iterate over
- `dma_iter`: DMA page iterator to hold current page
- `dma_nents`: maximum number of sg entries to iterate over, this is the value
  returned from dma_map_sg
- `pgoffset`: starting page offset (in pages)

**Description**

Callers may use [`sg_page_iter_dma_address()`](#c-sg_page_iter_dma_address) to get each page's DMA address.
In each loop it operates on PAGE_SIZE unit.

#### <a id="c-for_each_sgtable_page"></a>`for_each_sgtable_page()`

```c
for_each_sgtable_page(sgt, piter, pgoffset)
```

iterate over all pages in the sg_table object

**Parameters**

- `sgt`: sg_table object to iterate over
- `piter`: page iterator to hold current page
- `pgoffset`: starting page offset (in pages)

**Description**

Iterates over the all memory pages in the buffer described by
a scatterlist stored in the given sg_table object.
See also [`for_each_sg_page()`](#c-for_each_sg_page). In each loop it operates on PAGE_SIZE unit.

#### <a id="c-for_each_sgtable_dma_page"></a>`for_each_sgtable_dma_page()`

```c
for_each_sgtable_dma_page(sgt, dma_iter, pgoffset)
```

iterate over the DMA mapped sg_table object

**Parameters**

- `sgt`: sg_table object to iterate over
- `dma_iter`: DMA page iterator to hold current page
- `pgoffset`: starting page offset (in pages)

**Description**

Iterates over the all DMA mapped pages in the buffer described by
a scatterlist stored in the given sg_table object.
See also [`for_each_sg_dma_page()`](#c-for_each_sg_dma_page). In each loop it operates on PAGE_SIZE
unit.



#### <a id="c-sg_nents"></a>`sg_nents()`

```c
int sg_nents(struct scatterlist *sg)
```

return total count of entries in scatterlist

**Parameters**

- `struct scatterlist *sg`: The scatterlist

**Description**

Allows to know how many entries are in sg, taking into account
chaining as well

#### <a id="c-sg_nents_for_len"></a>`sg_nents_for_len()`

```c
int sg_nents_for_len(struct scatterlist *sg, u64 len)
```

return total count of entries in scatterlist needed to satisfy the supplied length

**Parameters**

- `struct scatterlist *sg`: The scatterlist
- `u64 len`: The total required length

**Description**

Determines the number of entries in sg that are required to meet
the supplied length, taking into account chaining as well

**Return**

the number of sg entries needed, negative error on failure

#### <a id="c-sg_nents_for_dma"></a>`sg_nents_for_dma()`

```c
int sg_nents_for_dma(struct scatterlist *sgl, unsigned int sglen, size_t len)
```

return the count of DMA-capable entries in scatterlist

**Parameters**

- `struct scatterlist *sgl`: The scatterlist
- `unsigned int sglen`: The current number of entries
- `size_t len`: The maximum length of DMA-capable block

**Description**

Determines the number of entries in **sgl** which would be permitted in
DMA-capable transfer if list had been split accordingly, taking into
account chaining as well.

**Return**

the number of sgl entries needed

#### <a id="c-sg_last"></a>`sg_last()`

```c
struct scatterlist * sg_last(struct scatterlist *sgl, unsigned int nents)
```

return the last scatterlist entry in a list

**Parameters**

- `struct scatterlist *sgl`: First entry in the scatterlist
- `unsigned int nents`: Number of entries in the scatterlist

**Description**

Should only be used casually, it (currently) scans the entire list
to get the last entry.

Note that the **sgl** pointer passed in need not be the first one,
the important bit is that **nents** denotes the number of entries that
exist from **sgl**.

#### <a id="c-sg_init_table"></a>`sg_init_table()`

```c
void sg_init_table(struct scatterlist *sgl, unsigned int nents)
```

Initialize SG table

**Parameters**

- `struct scatterlist *sgl`: The SG table
- `unsigned int nents`: Number of entries in table

**Notes**

If this is part of a chained sg table, [`sg_mark_end()`](#c-sg_mark_end) should be
used only on the last table part.

#### <a id="c-sg_init_one"></a>`sg_init_one()`

```c
void sg_init_one(struct scatterlist *sg, const void *buf, unsigned int buflen)
```

Initialize a single entry sg list

**Parameters**

- `struct scatterlist *sg`: SG entry
- `const void *buf`: Virtual address for IO
- `unsigned int buflen`: IO length

#### <a id="c-__sg_free_table"></a>`__sg_free_table()`

```c
void __sg_free_table(struct sg_table *table, unsigned int max_ents, unsigned int nents_first_chunk, sg_free_fn *free_fn, unsigned int num_ents)
```

Free a previously mapped sg table

**Parameters**

- `struct sg_table *table`: The sg table header to use
- `unsigned int max_ents`: The maximum number of entries per single scatterlist
- `unsigned int nents_first_chunk`: Number of entries int the (preallocated) first
  scatterlist chunk, 0 means no such preallocated first chunk
- `sg_free_fn *free_fn`: Free function
- `unsigned int num_ents`: Number of entries in the table

**Description**

Free an sg table previously allocated and setup with
[`__sg_alloc_table()`](#c-__sg_alloc_table).  The **max_ents** value must be identical to
that previously used with [`__sg_alloc_table()`](#c-__sg_alloc_table).

#### <a id="c-sg_free_append_table"></a>`sg_free_append_table()`

```c
void sg_free_append_table(struct sg_append_table *table)
```

Free a previously allocated append sg table.

**Parameters**

- `struct sg_append_table *table`: The mapped sg append table header

#### <a id="c-sg_free_table"></a>`sg_free_table()`

```c
void sg_free_table(struct sg_table *table)
```

Free a previously allocated sg table

**Parameters**

- `struct sg_table *table`: The mapped sg table header

#### <a id="c-__sg_alloc_table"></a>`__sg_alloc_table()`

```c
int __sg_alloc_table(struct sg_table *table, unsigned int nents, unsigned int max_ents, struct scatterlist *first_chunk, unsigned int nents_first_chunk, gfp_t gfp_mask, sg_alloc_fn *alloc_fn)
```

Allocate and initialize an sg table with given allocator

**Parameters**

- `struct sg_table *table`: The sg table header to use
- `unsigned int nents`: Number of entries in sg list
- `unsigned int max_ents`: The maximum number of entries the allocator returns per call
- `struct scatterlist *first_chunk`: first SGL if preallocated (may be `NULL`)
- `unsigned int nents_first_chunk`: Number of entries in the (preallocated) first
  scatterlist chunk, 0 means no such preallocated chunk provided by user
- `gfp_t gfp_mask`: GFP allocation mask
- `sg_alloc_fn *alloc_fn`: Allocator to use

**Description**

This function returns a **table** **nents** long. The allocator is
defined to return scatterlist chunks of maximum size **max_ents**.
Thus if **nents** is bigger than **max_ents**, the scatterlists will be
chained in units of **max_ents**.

**Notes**

If this function returns non-0 (eg failure), the caller must call
[`__sg_free_table()`](#c-__sg_free_table) to cleanup any leftover allocations.

#### <a id="c-sg_alloc_table"></a>`sg_alloc_table()`

```c
int sg_alloc_table(struct sg_table *table, unsigned int nents, gfp_t gfp_mask)
```

Allocate and initialize an sg table

**Parameters**

- `struct sg_table *table`: The sg table header to use
- `unsigned int nents`: Number of entries in sg list
- `gfp_t gfp_mask`: GFP allocation mask

**Description**

Allocate and initialize an sg table. If **nents** is larger than
SG_MAX_SINGLE_ALLOC a chained sg table will be setup.

#### <a id="c-sg_alloc_append_table_from_pages"></a>`sg_alloc_append_table_from_pages()`

```c
int sg_alloc_append_table_from_pages(struct sg_append_table *sgt_append, struct page **pages, unsigned int n_pages, unsigned int offset, unsigned long size, unsigned int max_segment, unsigned int left_pages, gfp_t gfp_mask)
```

Allocate and initialize an append sg table from an array of pages

**Parameters**

- `struct sg_append_table *sgt_append`: The sg append table to use
- `struct page **pages`: Pointer to an array of page pointers
- `unsigned int n_pages`: Number of pages in the pages array
- `unsigned int offset`: Offset from start of the first page to the start of a buffer
- `unsigned long size`: Number of valid bytes in the buffer (after offset)
- `unsigned int max_segment`: Maximum size of a scatterlist element in bytes
- `unsigned int left_pages`: Left pages caller have to set after this call
- `gfp_t gfp_mask`: GFP allocation mask

**Description**

In the first call it allocate and initialize an sg table from a list of
pages, else reuse the scatterlist from sgt_append. Contiguous ranges of
the pages are squashed into a single scatterlist entry up to the maximum
size specified in **max_segment**.  A user may provide an offset at a start
and a size of valid data in a buffer specified by the page array. The
returned sg table is released by sg_free_append_table

**Return**

0 on success, negative error on failure

**Notes**

If this function returns non-0 (eg failure), the caller must call
[`sg_free_append_table()`](#c-sg_free_append_table) to cleanup any leftover allocations.

In the fist call, sgt_append must by initialized.

#### <a id="c-sg_alloc_table_from_pages_segment"></a>`sg_alloc_table_from_pages_segment()`

```c
int sg_alloc_table_from_pages_segment(struct sg_table *sgt, struct page **pages, unsigned int n_pages, unsigned int offset, unsigned long size, unsigned int max_segment, gfp_t gfp_mask)
```

Allocate and initialize an sg table from an array of pages and given maximum segment.

**Parameters**

- `struct sg_table *sgt`: The sg table header to use
- `struct page **pages`: Pointer to an array of page pointers
- `unsigned int n_pages`: Number of pages in the pages array
- `unsigned int offset`: Offset from start of the first page to the start of a buffer
- `unsigned long size`: Number of valid bytes in the buffer (after offset)
- `unsigned int max_segment`: Maximum size of a scatterlist element in bytes
- `gfp_t gfp_mask`: GFP allocation mask

**Description**

Allocate and initialize an sg table from a list of pages. Contiguous
ranges of the pages are squashed into a single scatterlist node up to the
maximum size specified in **max_segment**. A user may provide an offset at a
start and a size of valid data in a buffer specified by the page array.

The returned sg table is released by sg_free_table.

**Return**

0 on success, negative error on failure

#### <a id="c-sgl_alloc_order"></a>`sgl_alloc_order()`

```c
struct scatterlist * sgl_alloc_order(unsigned long long length, unsigned int order, bool chainable, gfp_t gfp, unsigned int *nent_p)
```

allocate a scatterlist and its pages

**Parameters**

- `unsigned long long length`: Length in bytes of the scatterlist. Must be at least one
- `unsigned int order`: Second argument for [`alloc_pages()`](/kernel/internals/core-api/mm-api.md#c-alloc_pages)
- `bool chainable`: Whether or not to allocate an extra element in the scatterlist
  for scatterlist chaining purposes
- `gfp_t gfp`: Memory allocation flags
- `unsigned int *nent_p`: \[out\] Number of entries in the scatterlist that have pages

**Return**

A pointer to an initialized scatterlist or `NULL` upon failure.

#### <a id="c-sgl_alloc"></a>`sgl_alloc()`

```c
struct scatterlist * sgl_alloc(unsigned long long length, gfp_t gfp, unsigned int *nent_p)
```

allocate a scatterlist and its pages

**Parameters**

- `unsigned long long length`: Length in bytes of the scatterlist
- `gfp_t gfp`: Memory allocation flags
- `unsigned int *nent_p`: \[out\] Number of entries in the scatterlist

**Return**

A pointer to an initialized scatterlist or `NULL` upon failure.

#### <a id="c-sgl_free_n_order"></a>`sgl_free_n_order()`

```c
void sgl_free_n_order(struct scatterlist *sgl, int nents, int order)
```

free a scatterlist and its pages

**Parameters**

- `struct scatterlist *sgl`: Scatterlist with one or more elements
- `int nents`: Maximum number of elements to free
- `int order`: Second argument for [`__free_pages()`](/kernel/internals/core-api/mm-api.md#c-__free_pages)

**Notes**

- If several scatterlists have been chained and each chain element is
  freed separately then it's essential to set nents correctly to avoid that a
  page would get freed twice.
- All pages in a chained scatterlist can be freed at once by setting **nents**
  to a high number.

#### <a id="c-sgl_free_order"></a>`sgl_free_order()`

```c
void sgl_free_order(struct scatterlist *sgl, int order)
```

free a scatterlist and its pages

**Parameters**

- `struct scatterlist *sgl`: Scatterlist with one or more elements
- `int order`: Second argument for [`__free_pages()`](/kernel/internals/core-api/mm-api.md#c-__free_pages)

#### <a id="c-sgl_free"></a>`sgl_free()`

```c
void sgl_free(struct scatterlist *sgl)
```

free a scatterlist and its pages

**Parameters**

- `struct scatterlist *sgl`: Scatterlist with one or more elements

#### <a id="c-sg_miter_start"></a>`sg_miter_start()`

```c
void sg_miter_start(struct sg_mapping_iter *miter, struct scatterlist *sgl, unsigned int nents, unsigned int flags)
```

start mapping iteration over a sg list

**Parameters**

- `struct sg_mapping_iter *miter`: sg mapping iter to be started
- `struct scatterlist *sgl`: sg list to iterate over
- `unsigned int nents`: number of sg entries
- `unsigned int flags`: sg iterator flags

**Description**

Starts mapping iterator **miter**.

**Context**

Don't care.

#### <a id="c-sg_miter_skip"></a>`sg_miter_skip()`

```c
bool sg_miter_skip(struct sg_mapping_iter *miter, off_t offset)
```

reposition mapping iterator

**Parameters**

- `struct sg_mapping_iter *miter`: sg mapping iter to be skipped
- `off_t offset`: number of bytes to plus the current location

**Description**

Sets the offset of **miter** to its current location plus **offset** bytes.
If mapping iterator **miter** has been proceeded by [`sg_miter_next()`](#c-sg_miter_next), this
stops **miter**.

**Context**

Don't care.

**Return**

true if **miter** contains the valid mapping.  false if end of sg
list is reached.

#### <a id="c-sg_miter_next"></a>`sg_miter_next()`

```c
bool sg_miter_next(struct sg_mapping_iter *miter)
```

proceed mapping iterator to the next mapping

**Parameters**

- `struct sg_mapping_iter *miter`: sg mapping iter to proceed

**Description**

Proceeds **miter** to the next mapping.  **miter** should have been started
using [`sg_miter_start()`](#c-sg_miter_start).  On successful return, **miter->page**,
**miter->addr** and **miter->length** point to the current mapping.

**Context**

May sleep if !SG_MITER_ATOMIC && !SG_MITER_LOCAL.

**Return**

true if **miter** contains the next mapping.  false if end of sg
list is reached.

#### <a id="c-sg_miter_stop"></a>`sg_miter_stop()`

```c
void sg_miter_stop(struct sg_mapping_iter *miter)
```

stop mapping iteration

**Parameters**

- `struct sg_mapping_iter *miter`: sg mapping iter to be stopped

**Description**

Stops mapping iterator **miter**.  **miter** should have been started
using [`sg_miter_start()`](#c-sg_miter_start).  A stopped iteration can be resumed by
calling [`sg_miter_next()`](#c-sg_miter_next) on it.  This is useful when resources (kmap)
need to be released during iteration.

**Context**

Don't care otherwise.

#### <a id="c-sg_copy_buffer"></a>`sg_copy_buffer()`

```c
size_t sg_copy_buffer(struct scatterlist *sgl, unsigned int nents, void *buf, size_t buflen, off_t skip, bool to_buffer)
```

Copy data between a linear buffer and an SG list

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `void *buf`: Where to copy from
- `size_t buflen`: The number of bytes to copy
- `off_t skip`: Number of bytes to skip before copying
- `bool to_buffer`: transfer direction (true == from an sg list to a
  buffer, false == from a buffer to an sg list)

**Description**

Returns the number of copied bytes.

#### <a id="c-sg_copy_from_buffer"></a>`sg_copy_from_buffer()`

```c
size_t sg_copy_from_buffer(struct scatterlist *sgl, unsigned int nents, const void *buf, size_t buflen)
```

Copy from a linear buffer to an SG list

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `const void *buf`: Where to copy from
- `size_t buflen`: The number of bytes to copy

**Description**

Returns the number of copied bytes.

#### <a id="c-sg_copy_to_buffer"></a>`sg_copy_to_buffer()`

```c
size_t sg_copy_to_buffer(struct scatterlist *sgl, unsigned int nents, void *buf, size_t buflen)
```

Copy from an SG list to a linear buffer

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `void *buf`: Where to copy to
- `size_t buflen`: The number of bytes to copy

**Description**

Returns the number of copied bytes.

#### <a id="c-sg_pcopy_from_buffer"></a>`sg_pcopy_from_buffer()`

```c
size_t sg_pcopy_from_buffer(struct scatterlist *sgl, unsigned int nents, const void *buf, size_t buflen, off_t skip)
```

Copy from a linear buffer to an SG list

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `const void *buf`: Where to copy from
- `size_t buflen`: The number of bytes to copy
- `off_t skip`: Number of bytes to skip before copying

**Description**

Returns the number of copied bytes.

#### <a id="c-sg_pcopy_to_buffer"></a>`sg_pcopy_to_buffer()`

```c
size_t sg_pcopy_to_buffer(struct scatterlist *sgl, unsigned int nents, void *buf, size_t buflen, off_t skip)
```

Copy from an SG list to a linear buffer

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `void *buf`: Where to copy to
- `size_t buflen`: The number of bytes to copy
- `off_t skip`: Number of bytes to skip before copying

**Description**

Returns the number of copied bytes.

#### <a id="c-sg_zero_buffer"></a>`sg_zero_buffer()`

```c
size_t sg_zero_buffer(struct scatterlist *sgl, unsigned int nents, size_t buflen, off_t skip)
```

Zero-out a part of a SG list

**Parameters**

- `struct scatterlist *sgl`: The SG list
- `unsigned int nents`: Number of SG entries
- `size_t buflen`: The number of bytes to zero out
- `off_t skip`: Number of bytes to skip before zeroing

**Description**

Returns the number of bytes zeroed.

#### <a id="c-extract_iter_to_sg"></a>`extract_iter_to_sg()`

```c
ssize_t extract_iter_to_sg(struct iov_iter *iter, size_t maxsize, struct sg_table *sgtable, unsigned int sg_max, iov_iter_extraction_t extraction_flags)
```

Extract pages from an iterator and add to an sglist

**Parameters**

- `struct iov_iter *iter`: The iterator to extract from
- `size_t maxsize`: The amount of iterator to copy
- `struct sg_table *sgtable`: The scatterlist table to fill in
- `unsigned int sg_max`: Maximum number of elements in **sgtable** that may be filled
- `iov_iter_extraction_t extraction_flags`: Flags to qualify the request

**Description**

Extract the page fragments from the given amount of the source iterator and
add them to a scatterlist that refers to all of those bits, to a maximum
addition of **sg_max** elements.

The pages referred to by UBUF- and IOVEC-type iterators are extracted and
pinned; BVEC-, KVEC-, FOLIOQ- and XARRAY-type are extracted but aren't
pinned; DISCARD-type is not supported.

No end mark is placed on the scatterlist; that's left to the caller.

**extraction_flags** can have ITER_ALLOW_P2PDMA set to request peer-to-peer DMA
be allowed on the pages extracted.

If successful, **sgtable->nents** is updated to include the number of elements
added and the number of bytes added is returned.  **sgtable->orig_nents** is
left unaltered.

The `iov_iter_extract_mode()` function should be used to query how cleanup
should be performed.

---

# DMA attributes

_Peios Kernel / Internals / Core APIs_

> This document describes the semantics of the DMA attributes that are defined in linux/dma-mapping.h.

<a id="rst-dma-attributes"></a>

This document describes the semantics of the DMA attributes that are defined in linux/dma-mapping.h.

<a id="rst-dma-attr-weak-ordering"></a>

## DMA_ATTR_WEAK_ORDERING

DMA_ATTR_WEAK_ORDERING specifies that reads and writes to the mapping may be weakly ordered, that is that reads and writes may pass each other.

Since it is optional for platforms to implement DMA_ATTR_WEAK_ORDERING, those that do not will simply ignore the attribute and exhibit default behavior.

<a id="rst-dma-attr-write-combine"></a>

## DMA_ATTR_WRITE_COMBINE

DMA_ATTR_WRITE_COMBINE specifies that writes to the mapping may be buffered to improve performance.

Since it is optional for platforms to implement DMA_ATTR_WRITE_COMBINE, those that do not will simply ignore the attribute and exhibit default behavior.

<a id="rst-dma-attr-no-kernel-mapping"></a>

## DMA_ATTR_NO_KERNEL_MAPPING

DMA_ATTR_NO_KERNEL_MAPPING lets the platform to avoid creating a kernel virtual mapping for the allocated buffer. On some architectures creating such mapping is non-trivial task and consumes very limited resources (like kernel virtual address space or dma consistent address space). Buffers allocated with this attribute can be only passed to user space by calling dma_mmap_attrs(). By using this API, you are guaranteeing that you won't dereference the pointer returned by dma_alloc_attr(). You can treat it as a cookie that must be passed to dma_mmap_attrs() and dma_free_attrs(). Make sure that both of these also get this attribute set on each call.

Since it is optional for platforms to implement DMA_ATTR_NO_KERNEL_MAPPING, those that do not will simply ignore the attribute and exhibit default behavior.

<a id="rst-dma-attr-skip-cpu-sync"></a>

## DMA_ATTR_SKIP_CPU_SYNC

By default dma_map\_\{single,page,sg\} functions family transfer a given buffer from CPU domain to device domain. Some advanced use cases might require sharing a buffer between more than one device. This requires having a mapping created separately for each device and is usually performed by calling dma_map\_\{single,page,sg\} function more than once for the given buffer with device pointer to each device taking part in the buffer sharing. The first call transfers a buffer from 'CPU' domain to 'device' domain, what synchronizes CPU caches for the given region (usually it means that the cache has been flushed or invalidated depending on the dma direction). However, next calls to dma_map\_\{single,page,sg\}() for other devices will perform exactly the same synchronization operation on the CPU cache. CPU cache synchronization might be a time consuming operation, especially if the buffers are large, so it is highly recommended to avoid it if possible. DMA_ATTR_SKIP_CPU_SYNC allows platform code to skip synchronization of the CPU cache for the given buffer assuming that it has been already transferred to 'device' domain. This attribute can be also used for dma_unmap\_\{single,page,sg\} functions family to force buffer to stay in device domain after releasing a mapping for it. Use this attribute with care\!

<a id="rst-dma-attr-force-contiguous"></a>

## DMA_ATTR_FORCE_CONTIGUOUS

By default DMA-mapping subsystem is allowed to assemble the buffer allocated by dma_alloc_attrs() function from individual pages if it can be mapped as contiguous chunk into device dma address space. By specifying this attribute the allocated buffer is forced to be contiguous also in physical memory.

<a id="rst-dma-attr-alloc-single-pages"></a>

## DMA_ATTR_ALLOC_SINGLE_PAGES

This is a hint to the DMA-mapping subsystem that it's probably not worth the time to try to allocate memory to in a way that gives better TLB efficiency (AKA it's not worth trying to build the mapping out of larger pages).  You might want to specify this if:

- You know that the accesses to this memory won't thrash the TLB. You might know that the accesses are likely to be sequential or that they aren't sequential but it's unlikely you'll ping-pong between many addresses that are likely to be in different physical pages.

- You know that the penalty of TLB misses while accessing the memory will be small enough to be inconsequential.  If you are doing a heavy operation like decryption or decompression this might be the case.

- You know that the DMA mapping is fairly transitory.  If you expect the mapping to have a short lifetime then it may be worth it to optimize allocation (avoid coming up with large pages) instead of getting the slight performance win of larger pages.

Setting this hint doesn't guarantee that you won't get huge pages, but it means that we won't try quite as hard to get them.

> [!NOTE]
>
> At the moment DMA_ATTR_ALLOC_SINGLE_PAGES is only implemented on ARM, though ARM64 patches will likely be posted soon.

<a id="rst-dma-attr-no-warn"></a>

## DMA_ATTR_NO_WARN

This tells the DMA-mapping subsystem to suppress allocation failure reports (similarly to \__GFP_NOWARN).

On some architectures allocation failures are reported with error messages to the system logs.  Although this can help to identify and debug problems, drivers which handle failures (eg, retry later) have no problems with them, and can actually flood the system logs with error messages that aren't any problem at all, depending on the implementation of the retry mechanism.

So, this provides a way for drivers to avoid those error messages on calls where allocation failures are not a problem, and shouldn't bother the logs.

> [!NOTE]
>
> At the moment DMA_ATTR_NO_WARN is only implemented on PowerPC.

<a id="rst-dma-attr-privileged"></a>

## DMA_ATTR_PRIVILEGED

Some advanced peripherals such as remote processors and GPUs perform accesses to DMA buffers in both privileged "supervisor" and unprivileged "user" modes.  This attribute is used to indicate to the DMA-mapping subsystem that the buffer is fully accessible at the elevated privilege level (and ideally inaccessible or at least read-only at the lesser-privileged levels).

<a id="rst-dma-attr-mmio"></a>

## DMA_ATTR_MMIO

This attribute indicates the physical address is not normal system memory. It may not be used with kmap\*()/phys_to_virt()/phys_to_page() functions, it may not be cacheable, and access using CPU load/store instructions may not be allowed.

Usually this will be used to describe MMIO addresses, or other non-cacheable register addresses. When DMA mapping this sort of address we call the operation Peer to Peer as a one device is DMA'ing to another device. For PCI devices the p2pdma APIs must be used to determine if DMA_ATTR_MMIO is appropriate.

For architectures that require cache flushing for DMA coherence DMA_ATTR_MMIO will not perform any cache flushing. The address provided must never be mapped cacheable into the CPU.

<a id="rst-dma-attr-debugging-ignore-cachelines"></a>

## DMA_ATTR_DEBUGGING_IGNORE_CACHELINES

This attribute indicates that CPU cache lines may overlap for buffers mapped with DMA_FROM_DEVICE or DMA_BIDIRECTIONAL.

Such overlap may occur when callers map multiple small buffers that reside within the same cache line. In this case, callers must guarantee that the CPU will not dirty these cache lines after the mappings are established. When this condition is met, multiple buffers can safely share a cache line without risking data corruption.

All mappings that share a cache line must set this attribute to suppress DMA debug warnings about overlapping mappings.

<a id="rst-dma-attr-require-coherent"></a>

## DMA_ATTR_REQUIRE_COHERENT

DMA mapping requests with the DMA_ATTR_REQUIRE_COHERENT fail on any system where SWIOTLB or cache management is required. This should only be used to support uAPI designs that require continuous HW DMA coherence with userspace processes, for example RDMA and DRM. At a minimum the memory being mapped must be userspace memory from pin_user_pages() or similar.

Drivers should consider using dma_mmap_pages() instead of this interface when building their uAPIs, when possible.

It must never be used in an in-kernel driver that only works with kernel memory.

---

# DMA with ISA and LPC devices

_Peios Kernel / Internals / Core APIs_

> This document describes how to do DMA transfers using the old ISA DMA controller. Even though ISA is more or less dead today the LPC bus uses the same DMA system so it will be around for quite some time.

<a id="rst-dma-with-isa-and-lpc-devices"></a>

**Author:** Pierre Ossman &lt;[drzeus@drzeus.cx](<mailto:drzeus@drzeus.cx>)&gt;

This document describes how to do DMA transfers using the old ISA DMA controller. Even though ISA is more or less dead today the LPC bus uses the same DMA system so it will be around for quite some time.

<a id="rst-headers-and-dependencies"></a>

## Headers and dependencies

To do ISA style DMA you need to include two headers:



```text
#include <linux/dma-mapping.h>
#include <asm/dma.h>
```

The first is the generic DMA API used to convert virtual addresses to bus addresses (see [Documentation/core-api/dma-api.rst](/kernel/internals/core-api/dma-api.md) for details).

The second contains the routines specific to ISA DMA transfers. Since this is not present on all platforms make sure you construct your Kconfig to be dependent on ISA_DMA_API (not ISA) so that nobody tries to build your driver on unsupported platforms.

<a id="rst-buffer-allocation"></a>

## Buffer allocation

The ISA DMA controller has some very strict requirements on which memory it can access so extra care must be taken when allocating buffers.

(You usually need a special buffer for DMA transfers instead of transferring directly to and from your normal data structures.)

The DMA-able address space is the lowest 16 MB of \_physical\_ memory. Also the transfer block may not cross page boundaries (which are 64 or 128 KiB depending on which channel you use).

In order to allocate a piece of memory that satisfies all these requirements you pass the flag GFP_DMA to kmalloc.

Unfortunately the memory available for ISA DMA is scarce so unless you allocate the memory during boot-up it's a good idea to also pass \__GFP_RETRY_MAYFAIL and \__GFP_NOWARN to make the allocator try a bit harder.

(This scarcity also means that you should allocate the buffer as early as possible and not release it until the driver is unloaded.)

<a id="rst-address-translation"></a>

## Address translation

To translate the virtual address to a bus address, use the normal DMA API. Do \_not\_ use isa_virt_to_bus() even though it does the same thing. The reason for this is that the function isa_virt_to_bus() will require a Kconfig dependency to ISA, not just ISA_DMA_API which is really all you need. Remember that even though the DMA controller has its origins in ISA it is used elsewhere.

Note: x86_64 had a broken DMA API when it came to ISA but has since been fixed. If your arch has problems then fix the DMA API instead of reverting to the ISA functions.

<a id="rst-channels"></a>

## Channels

A normal ISA DMA controller has 8 channels. The lower four are for 8-bit transfers and the upper four are for 16-bit transfers.

(Actually the DMA controller is really two separate controllers where channel 4 is used to give DMA access for the second controller (0-3). This means that of the four 16-bits channels only three are usable.)

You allocate these in a similar fashion as all basic resources:

extern int request_dma(unsigned int dmanr, const char \* device_id); extern void free_dma(unsigned int dmanr);

The ability to use 16-bit or 8-bit transfers is \_not\_ up to you as a driver author but depends on what the hardware supports. Check your specs or test different channels.

<a id="rst-transfer-data"></a>

## Transfer data

Now for the good stuff, the actual DMA transfer. :)

Before you use any ISA DMA routines you need to claim the DMA lock using claim_dma_lock(). The reason is that some DMA operations are not atomic so only one driver may fiddle with the registers at a time.

The first time you use the DMA controller you should call clear_dma_ff(). This clears an internal register in the DMA controller that is used for the non-atomic operations. As long as you (and everyone else) uses the locking functions then you only need to reset this once.

Next, you tell the controller in which direction you intend to do the transfer using set_dma_mode(). Currently you have the options DMA_MODE_READ and DMA_MODE_WRITE.

Set the address from where the transfer should start (this needs to be 16-bit aligned for 16-bit transfers) and how many bytes to transfer. Note that it's \_bytes\_. The DMA routines will do all the required translation to values that the DMA controller understands.

The final step is enabling the DMA channel and releasing the DMA lock.

Once the DMA transfer is finished (or timed out) you should disable the channel again. You should also check get_dma_residue() to make sure that all data has been transferred.

Example:



```text
int flags, residue;

flags = claim_dma_lock();

clear_dma_ff();

set_dma_mode(channel, DMA_MODE_WRITE);
set_dma_addr(channel, phys_addr);
set_dma_count(channel, num_bytes);

dma_enable(channel);

release_dma_lock(flags);

while (!device_done());

flags = claim_dma_lock();

dma_disable(channel);

residue = dma_get_residue(channel);
if (residue != 0)
        printk(KERN_ERR "driver: Incomplete DMA transfer!"
                " %d bytes left!\n", residue);

release_dma_lock(flags);
```

<a id="rst-suspend-resume"></a>

## Suspend/resume

It is the driver's responsibility to make sure that the machine isn't suspended while a DMA transfer is in progress. Also, all DMA settings are lost when the system suspends so if your driver relies on the DMA controller being in a certain state then you have to restore these registers upon resume.

---

# Entry/exit handling for exceptions, interrupts, syscalls and KVM

_Peios Kernel / Internals / Core APIs_

> All transitions between execution domains require state updates which are subject to strict ordering constraints. State updates are required for the following:

<a id="rst-entry-exit-handling-for-exceptions-interrupts-syscalls-and-kvm"></a>

All transitions between execution domains require state updates which are subject to strict ordering constraints. State updates are required for the following:

> - Lockdep
>
> - RCU / Context tracking
>
> - Preemption counter
>
> - Tracing
>
> - Time accounting

The update order depends on the transition type and is explained below in the transition type sections: [Syscalls](<#rst-syscalls>), [KVM](<#rst-kvm>), [Interrupts and regular exceptions](<#rst-interrupts-and-regular-exceptions>), [NMI and NMI-like exceptions](<#rst-nmi-and-nmi-like-exceptions>).

<a id="rst-non-instrumentable-code-noinstr"></a>

## Non-instrumentable code - noinstr

Most instrumentation facilities depend on RCU, so instrumentation is prohibited for entry code before RCU starts watching and exit code after RCU stops watching. In addition, many architectures must save and restore register state, which means that (for example) a breakpoint in the breakpoint entry code would overwrite the debug registers of the initial breakpoint.

Such code must be marked with the 'noinstr' attribute, placing that code into a special section inaccessible to instrumentation and debug facilities. Some functions are partially instrumentable, which is handled by marking them noinstr and using instrumentation_begin() and instrumentation_end() to flag the instrumentable ranges of code:



```c
noinstr void entry(void)
{
      handle_entry();     // <-- must be 'noinstr' or '__always_inline'
      ...

      instrumentation_begin();
      handle_context();   // <-- instrumentable code
      instrumentation_end();

      ...
      handle_exit();      // <-- must be 'noinstr' or '__always_inline'
}
```

This allows verification of the 'noinstr' restrictions via objtool on supported architectures.

Invoking non-instrumentable functions from instrumentable context has no restrictions and is useful to protect e.g. state switching which would cause malfunction if instrumented.

All non-instrumentable entry/exit code sections before and after the RCU state transitions must run with interrupts disabled.

<a id="rst-syscalls"></a>

## Syscalls

Syscall-entry code starts in assembly code and calls out into low-level C code after establishing low-level architecture-specific state and stack frames. This low-level C code must not be instrumented. A typical syscall handling function invoked from low-level assembly code looks like this:



```c
noinstr void syscall(struct pt_regs *regs, int nr)
{
      arch_syscall_enter(regs);
      nr = syscall_enter_from_user_mode(regs, nr);

      instrumentation_begin();
      if (!invoke_syscall(regs, nr) && nr != -1)
              result_reg(regs) = __sys_ni_syscall(regs);
      instrumentation_end();

      syscall_exit_to_user_mode(regs);
}
```

syscall_enter_from_user_mode() first invokes enter_from_user_mode() which establishes state in the following order:

> - Lockdep
>
> - RCU / Context tracking
>
> - Tracing

and then invokes the various entry work functions like ptrace, seccomp, audit, syscall tracing, etc. After all that is done, the instrumentable invoke_syscall function can be invoked. The instrumentable code section then ends, after which syscall_exit_to_user_mode() is invoked.

syscall_exit_to_user_mode() handles all work which needs to be done before returning to user space like tracing, audit, signals, task work etc. After that it invokes exit_to_user_mode() which again handles the state transition in the reverse order:

> - Tracing
>
> - RCU / Context tracking
>
> - Lockdep

syscall_enter_from_user_mode() and syscall_exit_to_user_mode() are also available as fine grained subfunctions in cases where the architecture code has to do extra work between the various steps. In such cases it has to ensure that enter_from_user_mode() is called first on entry and exit_to_user_mode() is called last on exit.

Do not nest syscalls. Nested syscalls will cause RCU and/or context tracking to print a warning.

<a id="rst-kvm"></a>

## KVM

Entering or exiting guest mode is very similar to syscalls. From the host kernel point of view the CPU goes off into user space when entering the guest and returns to the kernel on exit.

guest_state_enter_irqoff() is a KVM-specific variant of exit_to_user_mode() and guest_state_exit_irqoff() is the KVM variant of enter_from_user_mode(). The state operations have the same ordering.

Task work handling is done separately for guest at the boundary of the vcpu_run() loop via xfer_to_guest_mode_handle_work() which is a subset of the work handled on return to user space.

Do not nest KVM entry/exit transitions because doing so is nonsensical.

<a id="rst-interrupts-and-regular-exceptions"></a>

## Interrupts and regular exceptions

Interrupts entry and exit handling is slightly more complex than syscalls and KVM transitions.

If an interrupt is raised while the CPU executes in user space, the entry and exit handling is exactly the same as for syscalls.

If the interrupt is raised while the CPU executes in kernel space the entry and exit handling is slightly different. RCU state is only updated when the interrupt is raised in the context of the CPU's idle task. Otherwise, RCU will already be watching. Lockdep and tracing have to be updated unconditionally.

irqentry_enter() and irqentry_exit() provide the implementation for this.

The architecture-specific part looks similar to syscall handling:



```c
noinstr void interrupt(struct pt_regs *regs, int nr)
{
      arch_interrupt_enter(regs);
      state = irqentry_enter(regs);

      instrumentation_begin();

      irq_enter_rcu();
      invoke_irq_handler(regs, nr);
      irq_exit_rcu();

      instrumentation_end();

      irqentry_exit(regs, state);
}
```

Note that the invocation of the actual interrupt handler is within a irq_enter_rcu() and irq_exit_rcu() pair.

irq_enter_rcu() updates the preemption count which makes in_hardirq() return true, handles NOHZ tick state and interrupt time accounting. This means that up to the point where irq_enter_rcu() is invoked in_hardirq() returns false.

irq_exit_rcu() handles interrupt time accounting, undoes the preemption count update and eventually handles soft interrupts and NOHZ tick state.

In theory, the preemption count could be updated in irqentry_enter(). In practice, deferring this update to irq_enter_rcu() allows the preemption-count code to be traced, while also maintaining symmetry with irq_exit_rcu() and irqentry_exit(), which are described in the next paragraph. The only downside is that the early entry code up to irq_enter_rcu() must be aware that the preemption count has not yet been updated with the HARDIRQ_OFFSET state.

Note that irq_exit_rcu() must remove HARDIRQ_OFFSET from the preemption count before it handles soft interrupts, whose handlers must run in BH context rather than irq-disabled context. In addition, irqentry_exit() might schedule, which also requires that HARDIRQ_OFFSET has been removed from the preemption count.

Even though interrupt handlers are expected to run with local interrupts disabled, interrupt nesting is common from an entry/exit perspective. For example, softirq handling happens within an irqentry\_\{enter,exit\}() block with local interrupts enabled. Also, although uncommon, nothing prevents an interrupt handler from re-enabling interrupts.

Interrupt entry/exit code doesn't strictly need to handle reentrancy, since it runs with local interrupts disabled. But NMIs can happen anytime, and a lot of the entry code is shared between the two.

<a id="rst-nmi-and-nmi-like-exceptions"></a>

## NMI and NMI-like exceptions

NMIs and NMI-like exceptions (machine checks, double faults, debug interrupts, etc.) can hit any context and must be extra careful with the state.

State changes for debug exceptions and machine-check exceptions depend on whether these exceptions happened in user-space (breakpoints or watchpoints) or in kernel mode (code patching). From user-space, they are treated like interrupts, while from kernel mode they are treated like NMIs.

NMIs and other NMI-like exceptions handle state transitions without distinguishing between user-mode and kernel-mode origin.

The state update on entry is handled in irqentry_nmi_enter() which updates state in the following order:

> - Preemption counter
>
> - Lockdep
>
> - RCU / Context tracking
>
> - Tracing

The exit counterpart irqentry_nmi_exit() does the reverse operation in the reverse order.

Note that the update of the preemption counter has to be the first operation on enter and the last operation on exit. The reason is that both lockdep and RCU rely on in_nmi() returning true in this case. The preemption count modification in the NMI entry/exit case must not be traced.

Architecture-specific code looks like this:



```c
noinstr void nmi(struct pt_regs *regs)
{
      arch_nmi_enter(regs);
      state = irqentry_nmi_enter(regs);

      instrumentation_begin();
      nmi_handler(regs);
      instrumentation_end();

      irqentry_nmi_exit(regs);
}
```

and for e.g. a debug exception it can look like this:



```c
noinstr void debug(struct pt_regs *regs)
{
      arch_nmi_enter(regs);

      debug_regs = save_debug_regs();

      if (user_mode(regs)) {
              state = irqentry_enter(regs);

              instrumentation_begin();
              user_mode_debug_handler(regs, debug_regs);
              instrumentation_end();

              irqentry_exit(regs, state);
      } else {
              state = irqentry_nmi_enter(regs);

              instrumentation_begin();
              kernel_mode_debug_handler(regs, debug_regs);
              instrumentation_end();

              irqentry_nmi_exit(regs, state);
      }
}
```

There is no combined irqentry_nmi_if_kernel() function available as the above cannot be handled in an exception-agnostic way.

NMIs can happen in any context. For example, an NMI-like exception triggered while handling an NMI. So NMI entry code has to be reentrant and state updates need to handle nesting.

---

# The errseq_t datatype

_Peios Kernel / Internals / Core APIs_

> An errseq_t is a way of recording errors in one place, and allowing any number of "subscribers" to tell whether it has changed since a previous point where it was sampled.

<a id="rst-the-errseq-t-datatype"></a>

An errseq_t is a way of recording errors in one place, and allowing any number of "subscribers" to tell whether it has changed since a previous point where it was sampled.

The initial use case for this is tracking errors for file synchronization syscalls (fsync, fdatasync, msync and sync_file_range), but it may be usable in other situations.

It's implemented as an unsigned 32-bit value.  The low order bits are designated to hold an error code (between 1 and MAX_ERRNO).  The upper bits are used as a counter.  This is done with atomics instead of locking so that these functions can be called from any context.

Note that there is a risk of collisions if new errors are being recorded frequently, since we have so few bits to use as a counter.

To mitigate this, the bit between the error value and counter is used as a flag to tell whether the value has been sampled since a new value was recorded.  That allows us to avoid bumping the counter if no one has sampled it since the last time an error was recorded.

Thus we end up with a value that looks something like this:


<table>
<tbody>
<tr>
<td>


31..13

</td>
<td>


12

</td>
<td>


11..0

</td>
</tr>
<tr>
<td>


counter

</td>
<td>


SF

</td>
<td>


errno

</td>
</tr>
</tbody>
</table>

The general idea is for "watchers" to sample an errseq_t value and keep it as a running cursor.  That value can later be used to tell whether any new errors have occurred since that sampling was done, and atomically record the state at the time that it was checked.  This allows us to record errors in one place, and then have a number of "watchers" that can tell whether the value has changed since they last checked it.

A new errseq_t should always be zeroed out.  An errseq_t value of all zeroes is the special (but common) case where there has never been an error. An all zero value thus serves as the "epoch" if one wishes to know whether there has ever been an error set since it was first initialized.

<a id="rst-api-usage"></a>

## API usage

Let me tell you a story about a worker drone.  Now, he's a good worker overall, but the company is a little...management heavy.  He has to report to 77 supervisors today, and tomorrow the "big boss" is coming in from out of town and he's sure to test the poor fellow too.

They're all handing him work to do -- so much he can't keep track of who handed him what, but that's not really a big problem.  The supervisors just want to know when he's finished all of the work they've handed him so far and whether he made any mistakes since they last asked.

He might have made the mistake on work they didn't actually hand him, but he can't keep track of things at that level of detail, all he can remember is the most recent mistake that he made.

Here's our worker_drone representation:



```text
struct worker_drone {
        errseq_t        wd_err; /* for recording errors */
};
```

Every day, the worker_drone starts out with a blank slate:



```text
struct worker_drone wd;

wd.wd_err = (errseq_t)0;
```

The supervisors come in and get an initial read for the day.  They don't care about anything that happened before their watch begins:



```text
struct supervisor {
        errseq_t        s_wd_err; /* private "cursor" for wd_err */
        spinlock_t      s_wd_err_lock; /* protects s_wd_err */
}

struct supervisor       su;

su.s_wd_err = errseq_sample(&wd.wd_err);
spin_lock_init(&su.s_wd_err_lock);
```

Now they start handing him tasks to do.  Every few minutes they ask him to finish up all of the work they've handed him so far.  Then they ask him whether he made any mistakes on any of it:



```text
spin_lock(&su.su_wd_err_lock);
err = errseq_check_and_advance(&wd.wd_err, &su.s_wd_err);
spin_unlock(&su.su_wd_err_lock);
```

Up to this point, that just keeps returning 0.

Now, the owners of this company are quite miserly and have given him substandard equipment with which to do his job. Occasionally it glitches and he makes a mistake.  He sighs a heavy sigh, and marks it down:



```text
errseq_set(&wd.wd_err, -EIO);
```

...and then gets back to work.  The supervisors eventually poll again and they each get the error when they next check.  Subsequent calls will return 0, until another error is recorded, at which point it's reported to each of them once.

Note that the supervisors can't tell how many mistakes he made, only whether one was made since they last checked, and the latest value recorded.

Occasionally the big boss comes in for a spot check and asks the worker to do a one-off job for him. He's not really watching the worker full-time like the supervisors, but he does need to know whether a mistake occurred while his job was processing.

He can just sample the current errseq_t in the worker, and then use that to tell whether an error has occurred later:



```text
errseq_t since = errseq_sample(&wd.wd_err);
/* submit some work and wait for it to complete */
err = errseq_check(&wd.wd_err, since);
```

Since he's just going to discard "since" after that point, he doesn't need to advance it here. He also doesn't need any locking since it's not usable by anyone else.

<a id="rst-serializing-errseq-t-cursor-updates"></a>

## Serializing errseq_t cursor updates

Note that the errseq_t API does not protect the errseq_t cursor during a check_and_advance_operation. Only the canonical error code is handled atomically.  In a situation where more than one task might be using the same errseq_t cursor at the same time, it's important to serialize updates to that cursor.

If that's not done, then it's possible for the cursor to go backward in which case the same error could be reported more than once.

Because of this, it's often advantageous to first do an errseq_check to see if anything has changed, and only later do an errseq_check_and_advance after taking the lock. e.g.:



```text
if (errseq_check(&wd.wd_err, READ_ONCE(su.s_wd_err)) {
        /* su.s_wd_err is protected by s_wd_err_lock */
        spin_lock(&su.s_wd_err_lock);
        err = errseq_check_and_advance(&wd.wd_err, &su.s_wd_err);
        spin_unlock(&su.s_wd_err_lock);
}
```

That avoids the spinlock in the common case where nothing has changed since the last time it was checked.

<a id="rst-functions"></a>

## Functions


#### <a id="c-errseq_set"></a>`errseq_set()`

```c
errseq_t errseq_set(errseq_t *eseq, int err)
```

set a errseq_t for later reporting

**Parameters**

- `errseq_t *eseq`: errseq_t field that should be set
- `int err`: error to set (must be between -1 and -MAX_ERRNO)

**Description**

This function sets the error in **eseq**, and increments the sequence counter
if the last sequence was sampled at some point in the past.

Any error set will always overwrite an existing error.

**Return**

The previous value, primarily for debugging purposes. The
return value should not be used as a previously sampled value in later
calls as it will not have the SEEN flag set.

#### <a id="c-errseq_sample"></a>`errseq_sample()`

```c
errseq_t errseq_sample(errseq_t *eseq)
```

Grab current errseq_t value.

**Parameters**

- `errseq_t *eseq`: Pointer to errseq_t to be sampled.

**Description**

This function allows callers to initialise their errseq_t variable.
If the error has been "seen", new callers will not see an old error.
If there is an unseen error in **eseq**, the caller of this function will
see it the next time it checks for an error.

**Context**

Any context.

**Return**

The current errseq value.

#### <a id="c-errseq_check"></a>`errseq_check()`

```c
int errseq_check(errseq_t *eseq, errseq_t since)
```

Has an error occurred since a particular sample point?

**Parameters**

- `errseq_t *eseq`: Pointer to errseq_t value to be checked.
- `errseq_t since`: Previously-sampled errseq_t from which to check.

**Description**

Grab the value that eseq points to, and see if it has changed **since**
the given value was sampled. The **since** value is not advanced, so there
is no need to mark the value as seen.

**Return**

The latest error set in the errseq_t or 0 if it hasn't changed.

#### <a id="c-errseq_check_and_advance"></a>`errseq_check_and_advance()`

```c
int errseq_check_and_advance(errseq_t *eseq, errseq_t *since)
```

Check an errseq_t and advance to current value.

**Parameters**

- `errseq_t *eseq`: Pointer to value being checked and reported.
- `errseq_t *since`: Pointer to previously-sampled errseq_t to check against and advance.

**Description**

Grab the eseq value, and see whether it matches the value that **since**
points to. If it does, then just return 0.

If it doesn't, then the value has changed. Set the "seen" flag, and try to
swap it into place as the new eseq value. Then, set that value as the new
"since" value, and return whatever the error portion is set to.

Note that no locking is provided here for concurrent updates to the "since"
value. The caller must provide that if necessary. Because of this, callers
may want to do a lockless errseq_check before taking the lock and calling
this.

**Return**

Negative errno if one has been stored, or 0 if no new error has
occurred.

---

# Floating-point API

_Peios Kernel / Internals / Core APIs_

> Kernel code is normally prohibited from using floating-point (FP) registers or instructions, including the C float and double data types. This rule reduces system call overhead, because the kernel does not need to save and restore the…

<a id="rst-floating-point-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Kernel code is normally prohibited from using floating-point (FP) registers or instructions, including the C float and double data types. This rule reduces system call overhead, because the kernel does not need to save and restore the userspace floating-point register state.

However, occasionally drivers or library functions may need to include FP code. This is supported by isolating the functions containing FP code to a separate translation unit (a separate source file), and saving/restoring the FP register state around calls to those functions. This creates "critical sections" of floating-point usage.

The reason for this isolation is to prevent the compiler from generating code touching the FP registers outside these critical sections. Compilers sometimes use FP registers to optimize inlined `memcpy` or variable assignment, as floating-point registers may be wider than general-purpose registers.

Usability of floating-point code within the kernel is architecture-specific. Additionally, because a single kernel may be configured to support platforms both with and without a floating-point unit, FPU availability must be checked both at build time and at run time.

Several architectures implement the generic kernel floating-point API from `linux/fpu.h`, as described below. Some other architectures implement their own unique APIs, which are documented separately.

<a id="rst-build-time-api"></a>

## Build-time API

Floating-point code may be built if the option `ARCH_HAS_KERNEL_FPU_SUPPORT` is enabled. For C code, such code must be placed in a separate file, and that file must have its compilation flags adjusted using the following pattern:



```text
CFLAGS_foo.o += $(CC_FLAGS_FPU)
CFLAGS_REMOVE_foo.o += $(CC_FLAGS_NO_FPU)
```

Architectures are expected to define one or both of these variables in their top-level Makefile as needed. For example:



```text
CC_FLAGS_FPU := -mhard-float
```

or:



```text
CC_FLAGS_NO_FPU := -msoft-float
```

Normal kernel code is assumed to use the equivalent of `CC_FLAGS_NO_FPU`.

<a id="rst-runtime-api"></a>

## Runtime API

The runtime API is provided in `linux/fpu.h`. This header cannot be included from files implementing FP code (those with their compilation flags adjusted as above). Instead, it must be included when defining the FP critical sections.





<a id="c-kernel_fpu_available"></a>

```c
bool kernel_fpu_available( void )
```

This function reports if floating-point code can be used on this CPU or platform. The value returned by this function is not expected to change at runtime, so it only needs to be called once, not before every critical section.





<a id="c-kernel_fpu_begin"></a>

```c
void kernel_fpu_begin( void )
        void kernel_fpu_end( void )
```

These functions create a floating-point critical section. It is only valid to call `kernel_fpu_begin()` after a previous call to `kernel_fpu_available()` returned `true`. These functions are only guaranteed to be callable from (preemptible or non-preemptible) process context.

Preemption may be disabled inside critical sections, so their size should be minimized. They are *not* required to be reentrant. If the caller expects to nest critical sections, it must implement its own reference counting.

---

# Folio Queue

_Peios Kernel / Internals / Core APIs_

> The folio_queue struct forms a single segment in a segmented list of folios that can be used to form an I/O buffer. As such, the list can be iterated over using the ITER_FOLIOQ iov_iter type.

<a id="rst-folio-queue"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** David Howells &lt;[dhowells@redhat.com](<mailto:dhowells@redhat.com>)&gt;

<!-- Contents:

* Overview
* Initialisation
* Adding and removing folios
* Querying information about a folio
* Querying information about a folio_queue
* Folio queue iteration
* Folio marks
* Lockless simultaneous production/consumption issues -->

<a id="rst-overview"></a>

## Overview

The folio_queue struct forms a single segment in a segmented list of folios that can be used to form an I/O buffer.  As such, the list can be iterated over using the ITER_FOLIOQ iov_iter type.

The publicly accessible members of the structure are:



```text
struct folio_queue {
        struct folio_queue *next;
        struct folio_queue *prev;
        ...
};
```

A pair of pointers are provided, `next` and `prev`, that point to the segments on either side of the segment being accessed.  Whilst this is a doubly-linked list, it is intentionally not a circular list; the outward sibling pointers in terminal segments should be NULL.

Each segment in the list also stores:

> - an ordered sequence of folio pointers,
>
> - the size of each folio and
>
> - three 1-bit marks per folio,

but these should not be accessed directly as the underlying data structure may change, but rather the access functions outlined below should be used.

The facility can be made accessible by:



```text
#include <linux/folio_queue.h>
```

and to use the iterator:



```text
#include <linux/uio.h>
```

<a id="rst-initialisation"></a>

## Initialisation

A segment should be initialised by calling:



```text
void folioq_init(struct folio_queue *folioq);
```

with a pointer to the segment to be initialised.  Note that this will not necessarily initialise all the folio pointers, so care must be taken to check the number of folios added.

<a id="rst-adding-and-removing-folios"></a>

## Adding and removing folios

Folios can be set in the next unused slot in a segment struct by calling one of:



```text
unsigned int folioq_append(struct folio_queue *folioq,
                           struct folio *folio);

unsigned int folioq_append_mark(struct folio_queue *folioq,
                                struct folio *folio);
```

Both functions update the stored folio count, store the folio and note its size.  The second function also sets the first mark for the folio added.  Both functions return the number of the slot used.  \[\!\] Note that no attempt is made to check that the capacity wasn't overrun and the list will not be extended automatically.

A folio can be excised by calling:



```text
void folioq_clear(struct folio_queue *folioq, unsigned int slot);
```

This clears the slot in the array and also clears all the marks for that folio, but doesn't change the folio count - so future accesses of that slot must check if the slot is occupied.

<a id="rst-querying-information-about-a-folio"></a>

## Querying information about a folio

Information about the folio in a particular slot may be queried by the following function:



```text
struct folio *folioq_folio(const struct folio_queue *folioq,
                           unsigned int slot);
```

If a folio has not yet been set in that slot, this may yield an undefined pointer.  The size of the folio in a slot may be queried with either of:



```text
unsigned int folioq_folio_order(const struct folio_queue *folioq,
                                unsigned int slot);

size_t folioq_folio_size(const struct folio_queue *folioq,
                         unsigned int slot);
```

The first function returns the size as an order and the second as a number of bytes.

<a id="rst-querying-information-about-a-folio-queue"></a>

## Querying information about a folio_queue

Information may be retrieved about a particular segment with the following functions:



```text
unsigned int folioq_nr_slots(const struct folio_queue *folioq);

unsigned int folioq_count(struct folio_queue *folioq);

bool folioq_full(struct folio_queue *folioq);
```

The first function returns the maximum capacity of a segment.  It must not be assumed that this won't vary between segments.  The second returns the number of folios added to a segments and the third is a shorthand to indicate if the segment has been filled to capacity.

Not that the count and fullness are not affected by clearing folios from the segment.  These are more about indicating how many slots in the array have been initialised, and it assumed that slots won't get reused, but rather the segment will get discarded as the queue is consumed.

<a id="rst-folio-marks"></a>

## Folio marks

Folios within a queue can also have marks assigned to them.  These marks can be used to note information such as if a folio needs folio_put() calling upon it. There are three marks available to be set for each folio.

The marks can be set by:



```text
void folioq_mark(struct folio_queue *folioq, unsigned int slot);
void folioq_mark2(struct folio_queue *folioq, unsigned int slot);
```

Cleared by:



```text
void folioq_unmark(struct folio_queue *folioq, unsigned int slot);
void folioq_unmark2(struct folio_queue *folioq, unsigned int slot);
```

And the marks can be queried by:



```text
bool folioq_is_marked(const struct folio_queue *folioq, unsigned int slot);
bool folioq_is_marked2(const struct folio_queue *folioq, unsigned int slot);
```

The marks can be used for any purpose and are not interpreted by this API.

<a id="rst-folio-queue-iteration"></a>

## Folio queue iteration

A list of segments may be iterated over using the I/O iterator facility using an `iov_iter` iterator of `ITER_FOLIOQ` type.  The iterator may be initialised with:



```text
void iov_iter_folio_queue(struct iov_iter *i, unsigned int direction,
                          const struct folio_queue *folioq,
                          unsigned int first_slot, unsigned int offset,
                          size_t count);
```

This may be told to start at a particular segment, slot and offset within a queue.  The iov iterator functions will follow the next pointers when advancing and prev pointers when reverting when needed.

<a id="rst-lockless-simultaneous-production-consumption-issues"></a>

## Lockless simultaneous production/consumption issues

If properly managed, the list can be extended by the producer at the head end and shortened by the consumer at the tail end simultaneously without the need to take locks.  The ITER_FOLIOQ iterator inserts appropriate barriers to aid with this.

Care must be taken when simultaneously producing and consuming a list.  If the last segment is reached and the folios it refers to are entirely consumed by the IOV iterators, an iov_iter struct will be left pointing to the last segment with a slot number equal to the capacity of that segment.  The iterator will try to continue on from this if there's another segment available when it is used again, but care must be taken lest the segment got removed and freed by the consumer before the iterator was advanced.

It is recommended that the queue always contain at least one segment, even if that segment has never been filled or is entirely spent.  This prevents the head and tail pointers from collapsing.

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-folioq_init"></a>`folioq_init()`

```c
void folioq_init(struct folio_queue *folioq, unsigned int rreq_id)
```

Initialise a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to initialise
- `unsigned int rreq_id`: The request identifier to use in tracelines.

**Description**

Initialise a folio queue segment and set an identifier to be used in traces.

Note that the folio pointers are left uninitialised.

#### <a id="c-folioq_nr_slots"></a>`folioq_nr_slots()`

```c
unsigned int folioq_nr_slots(const struct folio_queue *folioq)
```

Query the capacity of a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to query

**Description**

Query the number of folios that a particular folio queue segment might hold.
\[!\] NOTE: This must not be assumed to be the same for every segment!

#### <a id="c-folioq_count"></a>`folioq_count()`

```c
unsigned int folioq_count(struct folio_queue *folioq)
```

Query the occupancy of a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to query

**Description**

Query the number of folios that have been added to a folio queue segment.
Note that this is not decreased as folios are removed from a segment.

#### <a id="c-folioq_full"></a>`folioq_full()`

```c
bool folioq_full(struct folio_queue *folioq)
```

Query if a folio queue segment is full

**Parameters**

- `struct folio_queue *folioq`: The segment to query

**Description**

Query if a folio queue segment is fully occupied.  Note that this does not
change if folios are removed from a segment.

#### <a id="c-folioq_is_marked"></a>`folioq_is_marked()`

```c
bool folioq_is_marked(const struct folio_queue *folioq, unsigned int slot)
```

Check first folio mark in a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to query
- `unsigned int slot`: The slot number of the folio to query

**Description**

Determine if the first mark is set for the folio in the specified slot in a
folio queue segment.

#### <a id="c-folioq_mark"></a>`folioq_mark()`

```c
void folioq_mark(struct folio_queue *folioq, unsigned int slot)
```

Set the first mark on a folio in a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to modify
- `unsigned int slot`: The slot number of the folio to modify

**Description**

Set the first mark for the folio in the specified slot in a folio queue
segment.

#### <a id="c-folioq_unmark"></a>`folioq_unmark()`

```c
void folioq_unmark(struct folio_queue *folioq, unsigned int slot)
```

Clear the first mark on a folio in a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to modify
- `unsigned int slot`: The slot number of the folio to modify

**Description**

Clear the first mark for the folio in the specified slot in a folio queue
segment.

#### <a id="c-folioq_is_marked2"></a>`folioq_is_marked2()`

```c
bool folioq_is_marked2(const struct folio_queue *folioq, unsigned int slot)
```

Check second folio mark in a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to query
- `unsigned int slot`: The slot number of the folio to query

**Description**

Determine if the second mark is set for the folio in the specified slot in a
folio queue segment.

#### <a id="c-folioq_mark2"></a>`folioq_mark2()`

```c
void folioq_mark2(struct folio_queue *folioq, unsigned int slot)
```

Set the second mark on a folio in a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to modify
- `unsigned int slot`: The slot number of the folio to modify

**Description**

Set the second mark for the folio in the specified slot in a folio queue
segment.

#### <a id="c-folioq_unmark2"></a>`folioq_unmark2()`

```c
void folioq_unmark2(struct folio_queue *folioq, unsigned int slot)
```

Clear the second mark on a folio in a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to modify
- `unsigned int slot`: The slot number of the folio to modify

**Description**

Clear the second mark for the folio in the specified slot in a folio queue
segment.

#### <a id="c-folioq_append"></a>`folioq_append()`

```c
unsigned int folioq_append(struct folio_queue *folioq, struct folio *folio)
```

Add a folio to a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to add to
- `struct folio *folio`: The folio to add

**Description**

Add a folio to the tail of the sequence in a folio queue segment, increasing
the occupancy count and returning the slot number for the folio just added.
The folio size is extracted and stored in the queue and the marks are left
unmodified.

Note that it's left up to the caller to check that the segment capacity will
not be exceeded and to extend the queue.

#### <a id="c-folioq_append_mark"></a>`folioq_append_mark()`

```c
unsigned int folioq_append_mark(struct folio_queue *folioq, struct folio *folio)
```

Add a folio to a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to add to
- `struct folio *folio`: The folio to add

**Description**

Add a folio to the tail of the sequence in a folio queue segment, increasing
the occupancy count and returning the slot number for the folio just added.
The folio size is extracted and stored in the queue, the first mark is set
and and the second and third marks are left unmodified.

Note that it's left up to the caller to check that the segment capacity will
not be exceeded and to extend the queue.

#### <a id="c-folioq_folio"></a>`folioq_folio()`

```c
struct folio * folioq_folio(const struct folio_queue *folioq, unsigned int slot)
```

Get a folio from a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to access
- `unsigned int slot`: The folio slot to access

**Description**

Retrieve the folio in the specified slot from a folio queue segment.  Note
that no bounds check is made and if the slot hasn't been added into yet, the
pointer will be undefined.  If the slot has been cleared, NULL will be
returned.

#### <a id="c-folioq_folio_order"></a>`folioq_folio_order()`

```c
unsigned int folioq_folio_order(const struct folio_queue *folioq, unsigned int slot)
```

Get the order of a folio from a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to access
- `unsigned int slot`: The folio slot to access

**Description**

Retrieve the order of the folio in the specified slot from a folio queue
segment.  Note that no bounds check is made and if the slot hasn't been
added into yet, the order returned will be 0.

#### <a id="c-folioq_folio_size"></a>`folioq_folio_size()`

```c
size_t folioq_folio_size(const struct folio_queue *folioq, unsigned int slot)
```

Get the size of a folio from a folio queue segment

**Parameters**

- `const struct folio_queue *folioq`: The segment to access
- `unsigned int slot`: The folio slot to access

**Description**

Retrieve the size of the folio in the specified slot from a folio queue
segment.  Note that no bounds check is made and if the slot hasn't been
added into yet, the size returned will be PAGE_SIZE.

#### <a id="c-folioq_clear"></a>`folioq_clear()`

```c
void folioq_clear(struct folio_queue *folioq, unsigned int slot)
```

Clear a folio from a folio queue segment

**Parameters**

- `struct folio_queue *folioq`: The segment to clear
- `unsigned int slot`: The folio slot to clear

**Description**

Clear a folio from a sequence in a folio queue segment and clear its marks.
The occupancy count is left unchanged.

---

# The genalloc/genpool subsystem

_Peios Kernel / Internals / Core APIs_

> There are a number of memory-allocation subsystems in the kernel, each aimed at a specific need. Sometimes, however, a kernel developer needs to implement a new allocator for a specific range of special-purpose memory; often that memory is…

<a id="rst-the-genalloc-genpool-subsystem"></a>

There are a number of memory-allocation subsystems in the kernel, each aimed at a specific need.  Sometimes, however, a kernel developer needs to implement a new allocator for a specific range of special-purpose memory; often that memory is located on a device somewhere.  The author of the driver for that device can certainly write a little allocator to get the job done, but that is the way to fill the kernel with dozens of poorly tested allocators.  Back in 2005, Jes Sorensen lifted one of those allocators from the sym53c8xx_2 driver and [posted](<https://lwn.net/Articles/125842/>) it as a generic module for the creation of ad hoc memory allocators.  This code was merged for the 2.6.13 release; it has been modified considerably since then.

<a id="rst-posted"></a>



Code using this allocator should include &lt;linux/genalloc.h&gt;.  The action begins with the creation of a pool using one of:


#### <a id="c-gen_pool_create"></a>`gen_pool_create()`

```c
struct gen_pool * gen_pool_create(int min_alloc_order, int nid)
```

create a new special memory pool

**Parameters**

- `int min_alloc_order`: log base 2 of number of bytes each bitmap bit represents
- `int nid`: node id of the node the pool structure should be allocated on, or -1

**Description**

Create a new special memory pool that can be used to manage special purpose
memory not managed by the regular kmalloc/kfree interface.



#### <a id="c-devm_gen_pool_create"></a>`devm_gen_pool_create()`

```c
struct gen_pool * devm_gen_pool_create(struct device *dev, int min_alloc_order, int nid, const char *name)
```

managed gen_pool_create

**Parameters**

- `struct device *dev`: device that provides the gen_pool
- `int min_alloc_order`: log base 2 of number of bytes each bitmap bit represents
- `int nid`: node selector for allocated gen_pool, `NUMA_NO_NODE` for all nodes
- `const char *name`: name of a gen_pool or NULL, identifies a particular gen_pool on device

**Description**

Create a new special memory pool that can be used to manage special purpose
memory not managed by the regular kmalloc/kfree interface. The pool will be
automatically destroyed by the device management code.


A call to gen_pool_create() will create a pool.  The granularity of allocations is set with min_alloc_order; it is a log-base-2 number like those used by the page allocator, but it refers to bytes rather than pages. So, if min_alloc_order is passed as 3, then all allocations will be a multiple of eight bytes.  Increasing min_alloc_order decreases the memory required to track the memory in the pool.  The nid parameter specifies which NUMA node should be used for the allocation of the housekeeping structures; it can be -1 if the caller doesn't care.

The "managed" interface devm_gen_pool_create() ties the pool to a specific device.  Among other things, it will automatically clean up the pool when the given device is destroyed.

A pool is shut down with:


#### <a id="c-gen_pool_destroy"></a>`gen_pool_destroy()`

```c
void gen_pool_destroy(struct gen_pool *pool)
```

destroy a special memory pool

**Parameters**

- `struct gen_pool *pool`: pool to destroy

**Description**

Destroy the specified special memory pool. Verifies that there are no
outstanding allocations.


It's worth noting that, if there are still allocations outstanding from the given pool, this function will take the rather extreme step of invoking BUG(), crashing the entire system.  You have been warned.

A freshly created pool has no memory to allocate.  It is fairly useless in that state, so one of the first orders of business is usually to add memory to the pool.  That can be done with one of:


#### <a id="c-gen_pool_add"></a>`gen_pool_add()`

```c
int gen_pool_add(struct gen_pool *pool, unsigned long addr, size_t size, int nid)
```

add a new chunk of special memory to the pool

**Parameters**

- `struct gen_pool *pool`: pool to add new memory chunk to
- `unsigned long addr`: starting address of memory chunk to add to pool
- `size_t size`: size in bytes of the memory chunk to add to pool
- `int nid`: node id of the node the chunk structure and bitmap should be
  allocated on, or -1

**Description**

Add a new chunk of special memory to the specified pool.

Returns 0 on success or a -ve errno on failure.



#### <a id="c-gen_pool_add_owner"></a>`gen_pool_add_owner()`

```c
int gen_pool_add_owner(struct gen_pool *pool, unsigned long virt, phys_addr_t phys, size_t size, int nid, void *owner)
```

add a new chunk of special memory to the pool

**Parameters**

- `struct gen_pool *pool`: pool to add new memory chunk to
- `unsigned long virt`: virtual starting address of memory chunk to add to pool
- `phys_addr_t phys`: physical starting address of memory chunk to add to pool
- `size_t size`: size in bytes of the memory chunk to add to pool
- `int nid`: node id of the node the chunk structure and bitmap should be
  allocated on, or -1
- `void *owner`: private data the publisher would like to recall at alloc time

**Description**

Add a new chunk of special memory to the specified pool.

Returns 0 on success or a -ve errno on failure.


A call to gen_pool_add() will place the size bytes of memory starting at addr (in the kernel's virtual address space) into the given pool, once again using nid as the node ID for ancillary memory allocations. The gen_pool_add_virt() variant associates an explicit physical address with the memory; this is only necessary if the pool will be used for DMA allocations.

The functions for allocating memory from the pool (and putting it back) are:


#### <a id="c-gen_pool_alloc"></a>`gen_pool_alloc()`

```c
unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
```

allocate special memory from the pool

**Parameters**

- `struct gen_pool *pool`: pool to allocate from
- `size_t size`: number of bytes to allocate from the pool

**Description**

Allocate the requested number of bytes from the specified pool.
Uses the pool allocation function (with first-fit algorithm by default).
Can not be used in NMI handler on architectures without
NMI-safe cmpxchg implementation.



#### <a id="c-gen_pool_dma_alloc"></a>`gen_pool_dma_alloc()`

```c
void * gen_pool_dma_alloc(struct gen_pool *pool, size_t size, dma_addr_t *dma)
```

allocate special memory from the pool for DMA usage

**Parameters**

- `struct gen_pool *pool`: pool to allocate from
- `size_t size`: number of bytes to allocate from the pool
- `dma_addr_t *dma`: dma-view physical address return value.  Use `NULL` if unneeded.

**Description**

Allocate the requested number of bytes from the specified pool.
Uses the pool allocation function (with first-fit algorithm by default).
Can not be used in NMI handler on architectures without
NMI-safe cmpxchg implementation.

**Return**

virtual address of the allocated memory, or `NULL` on failure



#### <a id="c-gen_pool_free_owner"></a>`gen_pool_free_owner()`

```c
void gen_pool_free_owner(struct gen_pool *pool, unsigned long addr, size_t size, void **owner)
```

free allocated special memory back to the pool

**Parameters**

- `struct gen_pool *pool`: pool to free to
- `unsigned long addr`: starting address of memory to free back to pool
- `size_t size`: size in bytes of memory to free
- `void **owner`: private data stashed at [`gen_pool_add()`](#c-gen_pool_add) time

**Description**

Free previously allocated special memory back to the specified
pool.  Can not be used in NMI handler on architectures without
NMI-safe cmpxchg implementation.


As one would expect, gen_pool_alloc() will allocate size&lt; bytes from the given pool.  The gen_pool_dma_alloc() variant allocates memory for use with DMA operations, returning the associated physical address in the space pointed to by dma.  This will only work if the memory was added with gen_pool_add_virt().  Note that this function departs from the usual genpool pattern of using unsigned long values to represent kernel addresses; it returns a void \* instead.

That all seems relatively simple; indeed, some developers clearly found it to be too simple.  After all, the interface above provides no control over how the allocation functions choose which specific piece of memory to return.  If that sort of control is needed, the following functions will be of interest:


#### <a id="c-gen_pool_alloc_algo_owner"></a>`gen_pool_alloc_algo_owner()`

```c
unsigned long gen_pool_alloc_algo_owner(struct gen_pool *pool, size_t size, genpool_algo_t algo, void *data, void **owner)
```

allocate special memory from the pool

**Parameters**

- `struct gen_pool *pool`: pool to allocate from
- `size_t size`: number of bytes to allocate from the pool
- `genpool_algo_t algo`: algorithm passed from caller
- `void *data`: data passed to algorithm
- `void **owner`: optionally retrieve the chunk owner

**Description**

Allocate the requested number of bytes from the specified pool.
Uses the pool allocation function (with first-fit algorithm by default).
Can not be used in NMI handler on architectures without
NMI-safe cmpxchg implementation.



#### <a id="c-gen_pool_set_algo"></a>`gen_pool_set_algo()`

```c
void gen_pool_set_algo(struct gen_pool *pool, genpool_algo_t algo, void *data)
```

set the allocation algorithm

**Parameters**

- `struct gen_pool *pool`: pool to change allocation algorithm
- `genpool_algo_t algo`: custom algorithm function
- `void *data`: additional data used by **algo**

**Description**

Call **algo** for each memory allocation in the pool.
If **algo** is NULL use gen_pool_first_fit as default
memory allocation function.


Allocations with gen_pool_alloc_algo() specify an algorithm to be used to choose the memory to be allocated; the default algorithm can be set with gen_pool_set_algo().  The data value is passed to the algorithm; most ignore it, but it is occasionally needed.  One can, naturally, write a special-purpose algorithm, but there is a fair set already available:

- gen_pool_first_fit is a simple first-fit allocator; this is the default algorithm if none other has been specified.

- gen_pool_first_fit_align forces the allocation to have a specific alignment (passed via data in a genpool_data_align structure).

- gen_pool_first_fit_order_align aligns the allocation to the order of the size.  A 60-byte allocation will thus be 64-byte aligned, for example.

- gen_pool_best_fit, as one would expect, is a simple best-fit allocator.

- gen_pool_fixed_alloc allocates at a specific offset (passed in a genpool_data_fixed structure via the data parameter) within the pool. If the indicated memory is not available the allocation fails.

There is a handful of other functions, mostly for purposes like querying the space available in the pool or iterating through chunks of memory. Most users, however, should not need much beyond what has been described above.  With luck, wider awareness of this module will help to prevent the writing of special-purpose memory allocators in the future.


#### <a id="c-gen_pool_virt_to_phys"></a>`gen_pool_virt_to_phys()`

```c
phys_addr_t gen_pool_virt_to_phys(struct gen_pool *pool, unsigned long addr)
```

return the physical address of memory

**Parameters**

- `struct gen_pool *pool`: pool to allocate from
- `unsigned long addr`: starting address of memory

**Description**

Returns the physical address on success, or -1 on error.



#### <a id="c-gen_pool_for_each_chunk"></a>`gen_pool_for_each_chunk()`

```c
void gen_pool_for_each_chunk(struct gen_pool *pool, void (*func)(struct gen_pool *pool, struct gen_pool_chunk *chunk, void *data), void *data)
```

call func for every chunk of generic memory pool

**Parameters**

- `struct gen_pool *pool`: the generic memory pool
- `void (*func)(struct gen_pool *pool, struct gen_pool_chunk *chunk, void *data)`: func to call
- `void *data`: additional data used by **func**

**Description**

Call **func** for every chunk of generic memory pool.  The **func** is
called with rcu_read_lock held.



#### <a id="c-gen_pool_has_addr"></a>`gen_pool_has_addr()`

```c
bool gen_pool_has_addr(struct gen_pool *pool, unsigned long start, size_t size)
```

checks if an address falls within the range of a pool

**Parameters**

- `struct gen_pool *pool`: the generic memory pool
- `unsigned long start`: start address
- `size_t size`: size of the region

**Description**

Check if the range of addresses falls within the specified pool. Returns
true if the entire range is contained in the pool and false otherwise.



#### <a id="c-gen_pool_avail"></a>`gen_pool_avail()`

```c
size_t gen_pool_avail(struct gen_pool *pool)
```

get available free space of the pool

**Parameters**

- `struct gen_pool *pool`: pool to get available free space

**Description**

Return available free space of the specified pool.



#### <a id="c-gen_pool_size"></a>`gen_pool_size()`

```c
size_t gen_pool_size(struct gen_pool *pool)
```

get size in bytes of memory managed by the pool

**Parameters**

- `struct gen_pool *pool`: pool to get size

**Description**

Return size in bytes of memory managed by the pool.



#### <a id="c-gen_pool_get"></a>`gen_pool_get()`

```c
struct gen_pool * gen_pool_get(struct device *dev, const char *name)
```

Obtain the gen_pool (if any) for a device

**Parameters**

- `struct device *dev`: device to retrieve the gen_pool from
- `const char *name`: name of a gen_pool or NULL, identifies a particular gen_pool on device

**Description**

Returns the gen_pool for the device if one is present, or NULL.



#### <a id="c-of_gen_pool_get"></a>`of_gen_pool_get()`

```c
struct gen_pool * of_gen_pool_get(struct device_node *np, const char *propname, int index)
```

find a pool by phandle property

**Parameters**

- `struct device_node *np`: device node
- `const char *propname`: property name containing phandle(s)
- `int index`: index into the phandle array

**Description**

Returns the pool that contains the chunk starting at the physical
address of the device tree node pointed at by the phandle property,
or NULL if not found.

---

# Generic radix trees/sparse arrays

_Peios Kernel / Internals / Core APIs_

> Reference for Generic radix trees/sparse arrays.

<a id="rst-generic-radix-trees-sparse-arrays"></a>


Very simple and minimalistic, supporting arbitrary size entries up to
GENRADIX_NODE_SIZE.

A genradix is defined with the type it will store, like so:

static GENRADIX(struct foo) foo_genradix;

The main operations are:

- genradix_init(radix) - initialize an empty genradix

- genradix_free(radix) - free all memory owned by the genradix and
  reinitialize it

- genradix_ptr(radix, idx) - gets a pointer to the entry at idx, returning
  NULL if that entry does not exist

- genradix_ptr_alloc(radix, idx, gfp) - gets a pointer to an entry,
  allocating it if necessary

- genradix_for_each(radix, iter, p) - iterate over each entry in a genradix

The radix tree allocates one page of entries at a time, so entries may exist
that were never explicitly allocated - they will be initialized to all
zeroes.

Internally, a genradix is just a radix tree of pages, and indexing works in
terms of byte offsets. The wrappers in this header file use sizeof on the
type the radix contains to calculate a byte offset from the index - see
__idx_to_offset.


<a id="rst-generic-radix-tree-functions"></a>

## generic radix tree functions


#### <a id="c-genradix_init"></a>`genradix_init()`

```c
genradix_init(_radix)
```

initialize a genradix

**Parameters**

- `_radix`: genradix to initialize

**Description**

Does not fail

#### <a id="c-genradix_free"></a>`genradix_free()`

```c
genradix_free(_radix)
```

free all memory owned by a genradix

**Parameters**

- `_radix`: the genradix to free

**Description**

After freeing, **_radix** will be reinitialized and empty

#### <a id="c-genradix_ptr"></a>`genradix_ptr()`

```c
genradix_ptr(_radix, _idx)
```

get a pointer to a genradix entry

**Parameters**

- `_radix`: genradix to access
- `_idx`: index to fetch

**Description**

Returns a pointer to entry at **_idx**, or NULL if that entry does not exist.

#### <a id="c-genradix_ptr_alloc"></a>`genradix_ptr_alloc()`

```c
genradix_ptr_alloc(_radix, _idx, _gfp)
```

get a pointer to a genradix entry, allocating it if necessary

**Parameters**

- `_radix`: genradix to access
- `_idx`: index to fetch
- `_gfp`: gfp mask

**Description**

Returns a pointer to entry at **_idx**, or NULL on allocation failure

#### <a id="c-genradix_iter_init"></a>`genradix_iter_init()`

```c
genradix_iter_init(_radix, _idx)
```

initialize a genradix_iter

**Parameters**

- `_radix`: genradix that will be iterated over
- `_idx`: index to start iterating from

#### <a id="c-genradix_iter_peek"></a>`genradix_iter_peek()`

```c
genradix_iter_peek(_iter, _radix)
```

get first entry at or above iterator's current position

**Parameters**

- `_iter`: a genradix_iter
- `_radix`: genradix being iterated over

**Description**

If no more entries exist at or above **_iter**'s current position, returns NULL

#### <a id="c-genradix_iter_peek_prev"></a>`genradix_iter_peek_prev()`

```c
genradix_iter_peek_prev(_iter, _radix)
```

get first entry at or below iterator's current position

**Parameters**

- `_iter`: a genradix_iter
- `_radix`: genradix being iterated over

**Description**

If no more entries exist at or below **_iter**'s current position, returns NULL

#### <a id="c-genradix_for_each"></a>`genradix_for_each()`

```c
genradix_for_each(_radix, _iter, _p)
```

iterate over entry in a genradix

**Parameters**

- `_radix`: genradix to iterate over
- `_iter`: a genradix_iter to track current position
- `_p`: pointer to genradix entry type

**Description**

On every iteration, **_p** will point to the current entry, and **_iter.pos**
will be the current entry's index.

#### <a id="c-genradix_for_each_reverse"></a>`genradix_for_each_reverse()`

```c
genradix_for_each_reverse(_radix, _iter, _p)
```

iterate over entry in a genradix, reverse order

**Parameters**

- `_radix`: genradix to iterate over
- `_iter`: a genradix_iter to track current position
- `_p`: pointer to genradix entry type

**Description**

On every iteration, **_p** will point to the current entry, and **_iter.pos**
will be the current entry's index.

#### <a id="c-genradix_prealloc"></a>`genradix_prealloc()`

```c
genradix_prealloc(_radix, _nr, _gfp)
```

preallocate entries in a generic radix tree

**Parameters**

- `_radix`: genradix to preallocate
- `_nr`: number of entries to preallocate
- `_gfp`: gfp mask

**Description**

Returns 0 on success, -ENOMEM on failure

---

# Linux generic IRQ handling

_Peios Kernel / Internals / Core APIs_

> The generic interrupt handling layer is designed to provide a complete abstraction of interrupt handling for device drivers. It is able to handle all the different types of interrupt controller hardware. Device drivers use generic API…

<a id="rst-linux-generic-irq-handling"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2005-2010: Thomas Gleixner

**Copyright:** © 2005-2006:  Ingo Molnar

<a id="rst-introduction"></a>

## Introduction

The generic interrupt handling layer is designed to provide a complete abstraction of interrupt handling for device drivers. It is able to handle all the different types of interrupt controller hardware. Device drivers use generic API functions to request, enable, disable and free interrupts. The drivers do not have to know anything about interrupt hardware details, so they can be used on different platforms without code changes.

This documentation is provided to developers who want to implement an interrupt subsystem based for their architecture, with the help of the generic IRQ handling layer.

<a id="rst-rationale"></a>

## Rationale

The original implementation of interrupt handling in Linux uses the \__do_IRQ() super-handler, which is able to deal with every type of interrupt logic.

Originally, Russell King identified different types of handlers to build a quite universal set for the ARM interrupt handler implementation in Linux 2.5/2.6. He distinguished between:

- Level type

- Edge type

- Simple type

During the implementation we identified another type:

- Fast EOI type

In the SMP world of the \__do_IRQ() super-handler another type was identified:

- Per CPU type

This split implementation of high-level IRQ handlers allows us to optimize the flow of the interrupt handling for each specific interrupt type. This reduces complexity in that particular code path and allows the optimized handling of a given type.

The original general IRQ implementation used hw_interrupt_type structures and their `->ack`, `->end` \[etc.\] callbacks to differentiate the flow control in the super-handler. This leads to a mix of flow logic and low-level hardware logic, and it also leads to unnecessary code duplication: for example in i386, there is an `ioapic_level_irq` and an `ioapic_edge_irq` IRQ-type which share many of the low-level details but have different flow handling.

A more natural abstraction is the clean separation of the 'irq flow' and the 'chip details'.

Analysing a couple of architecture's IRQ subsystem implementations reveals that most of them can use a generic set of 'irq flow' methods and only need to add the chip-level specific code. The separation is also valuable for (sub)architectures which need specific quirks in the IRQ flow itself but not in the chip details - and thus provides a more transparent IRQ subsystem design.

Each interrupt descriptor is assigned its own high-level flow handler, which is normally one of the generic implementations. (This high-level flow handler implementation also makes it simple to provide demultiplexing handlers which can be found in embedded platforms on various architectures.)

The separation makes the generic interrupt handling layer more flexible and extensible. For example, an (sub)architecture can use a generic IRQ-flow implementation for 'level type' interrupts and add a (sub)architecture specific 'edge type' implementation.

To make the transition to the new model easier and prevent the breakage of existing implementations, the \__do_IRQ() super-handler is still available. This leads to a kind of duality for the time being. Over time the new model should be used in more and more architectures, as it enables smaller and cleaner IRQ subsystems. It's deprecated for three years now and about to be removed.

<a id="rst-known-bugs-and-assumptions"></a>

## Known Bugs And Assumptions

None (knock on wood).

<a id="rst-abstraction-layers"></a>

## Abstraction layers

There are three main levels of abstraction in the interrupt code:

1. High-level driver API

2. High-level IRQ flow handlers

3. Chip-level hardware encapsulation

<a id="rst-interrupt-control-flow"></a>

### Interrupt control flow

Each interrupt is described by an interrupt descriptor structure irq_desc. The interrupt is referenced by an 'unsigned int' numeric value which selects the corresponding interrupt description structure in the descriptor structures array. The descriptor structure contains status information and pointers to the interrupt flow method and the interrupt chip structure which are assigned to this interrupt.

Whenever an interrupt triggers, the low-level architecture code calls into the generic interrupt code by calling desc-&gt;handle_irq(). This high-level IRQ handling function only uses desc-&gt;irq_data.chip primitives referenced by the assigned chip descriptor structure.

<a id="rst-high-level-driver-api"></a>

### High-level Driver API

The high-level Driver API consists of following functions:

- request_irq()

- request_threaded_irq()

- free_irq()

- disable_irq()

- enable_irq()

- disable_irq_nosync() (SMP only)

- synchronize_irq() (SMP only)

- irq_set_irq_type()

- irq_set_irq_wake()

- irq_set_handler_data()

- irq_set_chip()

- irq_set_chip_data()

See the autogenerated function documentation for details.

<a id="rst-high-level-irq-flow-handlers"></a>

### High-level IRQ flow handlers

The generic layer provides a set of pre-defined irq-flow methods:

- handle_level_irq()

- handle_edge_irq()

- handle_fasteoi_irq()

- handle_simple_irq()

- handle_percpu_irq()

- handle_edge_eoi_irq()

- handle_bad_irq()

The interrupt flow handlers (either pre-defined or architecture specific) are assigned to specific interrupts by the architecture either during bootup or during device initialization.

<a id="rst-default-flow-implementations"></a>

#### Default flow implementations

<a id="rst-helper-functions"></a>

##### Helper functions

The helper functions call the chip primitives and are used by the default flow implementations. The following helper functions are implemented (simplified excerpt):



```text
default_enable(struct irq_data *data)
{
    desc->irq_data.chip->irq_unmask(data);
}

default_disable(struct irq_data *data)
{
    if (!delay_disable(data))
        desc->irq_data.chip->irq_mask(data);
}

default_ack(struct irq_data *data)
{
    chip->irq_ack(data);
}

default_mask_ack(struct irq_data *data)
{
    if (chip->irq_mask_ack) {
        chip->irq_mask_ack(data);
    } else {
        chip->irq_mask(data);
        chip->irq_ack(data);
    }
}

noop(struct irq_data *data)
{
}
```

<a id="rst-default-flow-handler-implementations"></a>

#### Default flow handler implementations

<a id="rst-default-level-irq-flow-handler"></a>

##### Default Level IRQ flow handler

handle_level_irq provides a generic implementation for level-triggered interrupts.

The following control flow is implemented (simplified excerpt):



```text
desc->irq_data.chip->irq_mask_ack();
handle_irq_event(desc->action);
desc->irq_data.chip->irq_unmask();
```

<a id="rst-default-fast-eoi-irq-flow-handler"></a>

##### Default Fast EOI IRQ flow handler

handle_fasteoi_irq provides a generic implementation for interrupts, which only need an EOI at the end of the handler.

The following control flow is implemented (simplified excerpt):



```text
handle_irq_event(desc->action);
desc->irq_data.chip->irq_eoi();
```

<a id="rst-default-edge-irq-flow-handler"></a>

##### Default Edge IRQ flow handler

handle_edge_irq provides a generic implementation for edge-triggered interrupts.

The following control flow is implemented (simplified excerpt):



```text
if (desc->status & running) {
    desc->irq_data.chip->irq_mask_ack();
    desc->status |= pending | masked;
    return;
}
desc->irq_data.chip->irq_ack();
desc->status |= running;
do {
    if (desc->status & masked)
        desc->irq_data.chip->irq_unmask();
    desc->status &= ~pending;
    handle_irq_event(desc->action);
} while (desc->status & pending);
desc->status &= ~running;
```

<a id="rst-default-simple-irq-flow-handler"></a>

##### Default simple IRQ flow handler

handle_simple_irq provides a generic implementation for simple interrupts.

> [!NOTE]
>
> The simple flow handler does not call any handler/chip primitives.

The following control flow is implemented (simplified excerpt):



```text
handle_irq_event(desc->action);
```

<a id="rst-default-per-cpu-flow-handler"></a>

##### Default per CPU flow handler

handle_percpu_irq provides a generic implementation for per CPU interrupts.

Per CPU interrupts are only available on SMP and the handler provides a simplified version without locking.

The following control flow is implemented (simplified excerpt):



```text
if (desc->irq_data.chip->irq_ack)
    desc->irq_data.chip->irq_ack();
handle_irq_event(desc->action);
if (desc->irq_data.chip->irq_eoi)
    desc->irq_data.chip->irq_eoi();
```

<a id="rst-eoi-edge-irq-flow-handler"></a>

##### EOI Edge IRQ flow handler

handle_edge_eoi_irq provides an abnomination of the edge handler which is solely used to tame a badly wreckaged irq controller on powerpc/cell.

<a id="rst-bad-irq-flow-handler"></a>

##### Bad IRQ flow handler

handle_bad_irq is used for spurious interrupts which have no real handler assigned..

<a id="rst-quirks-and-optimizations"></a>

#### Quirks and optimizations

The generic functions are intended for 'clean' architectures and chips, which have no platform-specific IRQ handling quirks. If an architecture needs to implement quirks on the 'flow' level then it can do so by overriding the high-level irq-flow handler.

<a id="rst-delayed-interrupt-disable"></a>

#### Delayed interrupt disable

This per interrupt selectable feature, which was introduced by Russell King in the ARM interrupt implementation, does not mask an interrupt at the hardware level when disable_irq() is called. The interrupt is kept enabled and is masked in the flow handler when an interrupt event happens. This prevents losing edge interrupts on hardware which does not store an edge interrupt event while the interrupt is disabled at the hardware level. When an interrupt arrives while the IRQ_DISABLED flag is set, then the interrupt is masked at the hardware level and the IRQ_PENDING bit is set. When the interrupt is re-enabled by enable_irq() the pending bit is checked and if it is set, the interrupt is resent either via hardware or by a software resend mechanism. (It's necessary to enable CONFIG_HARDIRQS_SW_RESEND when you want to use the delayed interrupt disable feature and your hardware is not capable of retriggering an interrupt.) The delayed interrupt disable is not configurable.

<a id="rst-chip-level-hardware-encapsulation"></a>

### Chip-level hardware encapsulation

The chip-level hardware descriptor structure `irq_chip` contains all the direct chip relevant functions, which can be utilized by the irq flow implementations.

- `irq_ack`

- `irq_mask_ack` - Optional, recommended for performance

- `irq_mask`

- `irq_unmask`

- `irq_eoi` - Optional, required for EOI flow handlers

- `irq_retrigger` - Optional

- `irq_set_type` - Optional

- `irq_set_wake` - Optional

These primitives are strictly intended to mean what they say: ack means ACK, masking means masking of an IRQ line, etc. It is up to the flow handler(s) to use these basic units of low-level functionality.

<a id="rst-do-irq-entry-point"></a>

## \__do_IRQ entry point

The original implementation \__do_IRQ() was an alternative entry point for all types of interrupts. It no longer exists.

This handler turned out to be not suitable for all interrupt hardware and was therefore reimplemented with split functionality for edge/level/simple/percpu interrupts. This is not only a functional optimization. It also shortens code paths for interrupts.

<a id="rst-locking-on-smp"></a>

## Locking on SMP

The locking of chip registers is up to the architecture that defines the chip primitives. The per-irq structure is protected via desc-&gt;lock, by the generic layer.

<a id="rst-generic-interrupt-chip"></a>

## Generic interrupt chip

To avoid copies of identical implementations of IRQ chips the core provides a configurable generic interrupt chip implementation. Developers should check carefully whether the generic chip fits their needs before implementing the same functionality slightly differently themselves.


#### <a id="c-irq_gc_noop"></a>`irq_gc_noop()`

```c
void irq_gc_noop(struct irq_data *d)
```

NOOP function

**Parameters**

- `struct irq_data *d`: irq_data

#### <a id="c-irq_gc_mask_disable_reg"></a>`irq_gc_mask_disable_reg()`

```c
void irq_gc_mask_disable_reg(struct irq_data *d)
```

Mask chip via disable register

**Parameters**

- `struct irq_data *d`: irq_data

**Description**

Chip has separate enable/disable registers instead of a single mask
register.

#### <a id="c-irq_gc_mask_set_bit"></a>`irq_gc_mask_set_bit()`

```c
void irq_gc_mask_set_bit(struct irq_data *d)
```

Mask chip via setting bit in mask register

**Parameters**

- `struct irq_data *d`: irq_data

**Description**

Chip has a single mask register. Values of this register are cached
and protected by gc->lock

#### <a id="c-irq_gc_mask_clr_bit"></a>`irq_gc_mask_clr_bit()`

```c
void irq_gc_mask_clr_bit(struct irq_data *d)
```

Mask chip via clearing bit in mask register

**Parameters**

- `struct irq_data *d`: irq_data

**Description**

Chip has a single mask register. Values of this register are cached
and protected by gc->lock

#### <a id="c-irq_gc_unmask_enable_reg"></a>`irq_gc_unmask_enable_reg()`

```c
void irq_gc_unmask_enable_reg(struct irq_data *d)
```

Unmask chip via enable register

**Parameters**

- `struct irq_data *d`: irq_data

**Description**

Chip has separate enable/disable registers instead of a single mask
register.

#### <a id="c-irq_gc_ack_set_bit"></a>`irq_gc_ack_set_bit()`

```c
void irq_gc_ack_set_bit(struct irq_data *d)
```

Ack pending interrupt via setting bit

**Parameters**

- `struct irq_data *d`: irq_data

#### <a id="c-irq_gc_mask_disable_and_ack_set"></a>`irq_gc_mask_disable_and_ack_set()`

```c
void irq_gc_mask_disable_and_ack_set(struct irq_data *d)
```

Mask and ack pending interrupt

**Parameters**

- `struct irq_data *d`: irq_data

**Description**

This generic implementation of the irq_mask_ack method is for chips
with separate enable/disable registers instead of a single mask
register and where a pending interrupt is acknowledged by setting a
bit.

**Note**

This is the only permutation currently used.  Similar generic
functions should be added here if other permutations are required.

#### <a id="c-irq_gc_set_wake"></a>`irq_gc_set_wake()`

```c
int irq_gc_set_wake(struct irq_data *d, unsigned int on)
```

Set/clr wake bit for an interrupt

**Parameters**

- `struct irq_data *d`: irq_data
- `unsigned int on`: Indicates whether the wake bit should be set or cleared

**Description**

For chips where the wake from suspend functionality is not
configured in a separate register and the wakeup active state is
just stored in a bitmask.

#### <a id="c-irq_alloc_generic_chip"></a>`irq_alloc_generic_chip()`

```c
struct irq_chip_generic * irq_alloc_generic_chip(const char *name, int num_ct, unsigned int irq_base, void __iomem *reg_base, irq_flow_handler_t handler)
```

Allocate a generic chip and initialize it

**Parameters**

- `const char *name`: Name of the irq chip
- `int num_ct`: Number of irq_chip_type instances associated with this
- `unsigned int irq_base`: Interrupt base nr for this chip
- `void __iomem *reg_base`: Register base address (virtual)
- `irq_flow_handler_t handler`: Default flow handler associated with this chip

**Description**

Returns an initialized irq_chip_generic structure. The chip defaults
to the primary (index 0) irq_chip_type and **handler**

#### <a id="c-irq_domain_alloc_generic_chips"></a>`irq_domain_alloc_generic_chips()`

```c
int irq_domain_alloc_generic_chips(struct irq_domain *d, const struct irq_domain_chip_generic_info *info)
```

Allocate generic chips for an irq domain

**Parameters**

- `struct irq_domain *d`: irq domain for which to allocate chips
- `const struct irq_domain_chip_generic_info *info`: Generic chip information

**Return**

0 on success, negative error code on failure

#### <a id="c-irq_domain_remove_generic_chips"></a>`irq_domain_remove_generic_chips()`

```c
void irq_domain_remove_generic_chips(struct irq_domain *d)
```

Remove generic chips from an irq domain

**Parameters**

- `struct irq_domain *d`: irq domain for which generic chips are to be removed

#### <a id="c-__irq_alloc_domain_generic_chips"></a>`__irq_alloc_domain_generic_chips()`

```c
int __irq_alloc_domain_generic_chips(struct irq_domain *d, int irqs_per_chip, int num_ct, const char *name, irq_flow_handler_t handler, unsigned int clr, unsigned int set, enum irq_gc_flags gcflags)
```

Allocate generic chips for an irq domain

**Parameters**

- `struct irq_domain *d`: irq domain for which to allocate chips
- `int irqs_per_chip`: Number of interrupts each chip handles (max 32)
- `int num_ct`: Number of irq_chip_type instances associated with this
- `const char *name`: Name of the irq chip
- `irq_flow_handler_t handler`: Default flow handler associated with these chips
- `unsigned int clr`: IRQ_* bits to clear in the mapping function
- `unsigned int set`: IRQ_* bits to set in the mapping function
- `enum irq_gc_flags gcflags`: Generic chip specific setup flags

#### <a id="c-irq_get_domain_generic_chip"></a>`irq_get_domain_generic_chip()`

```c
struct irq_chip_generic * irq_get_domain_generic_chip(struct irq_domain *d, unsigned int hw_irq)
```

Get a pointer to the generic chip of a hw_irq

**Parameters**

- `struct irq_domain *d`: irq domain pointer
- `unsigned int hw_irq`: Hardware interrupt number

#### <a id="c-irq_setup_generic_chip"></a>`irq_setup_generic_chip()`

```c
void irq_setup_generic_chip(struct irq_chip_generic *gc, u32 msk, enum irq_gc_flags flags, unsigned int clr, unsigned int set)
```

Setup a range of interrupts with a generic chip

**Parameters**

- `struct irq_chip_generic *gc`: Generic irq chip holding all data
- `u32 msk`: Bitmask holding the irqs to initialize relative to gc->irq_base
- `enum irq_gc_flags flags`: Flags for initialization
- `unsigned int clr`: IRQ_* bits to clear
- `unsigned int set`: IRQ_* bits to set

**Description**

Set up max. 32 interrupts starting from gc->irq_base. Note, this
initializes all interrupts to the primary irq_chip_type and its
associated handler.

#### <a id="c-irq_setup_alt_chip"></a>`irq_setup_alt_chip()`

```c
int irq_setup_alt_chip(struct irq_data *d, unsigned int type)
```

Switch to alternative chip

**Parameters**

- `struct irq_data *d`: irq_data for this interrupt
- `unsigned int type`: Flow type to be initialized

**Description**

Only to be called from chip->`irq_set_type()` callbacks.

#### <a id="c-irq_remove_generic_chip"></a>`irq_remove_generic_chip()`

```c
void irq_remove_generic_chip(struct irq_chip_generic *gc, u32 msk, unsigned int clr, unsigned int set)
```

Remove a chip

**Parameters**

- `struct irq_chip_generic *gc`: Generic irq chip holding all data
- `u32 msk`: Bitmask holding the irqs to initialize relative to gc->irq_base
- `unsigned int clr`: IRQ_* bits to clear
- `unsigned int set`: IRQ_* bits to set

**Description**

Remove up to 32 interrupts starting from gc->irq_base.


<a id="rst-structures"></a>

## Structures

This chapter contains the autogenerated documentation of the structures which are used in the generic IRQ layer.


#### <a id="c-struct-irq_common_data"></a>`struct irq_common_data`

per irq data shared by all irqchips

**Definition**

```c
struct irq_common_data {
        unsigned int  state_use_accessors;
    #ifdef CONFIG_NUMA;
        unsigned int            node;
    #endif;
        void *handler_data;
        struct msi_desc         *msi_desc;
    #ifdef CONFIG_SMP;
        cpumask_var_t affinity;
    #endif;
    #ifdef CONFIG_GENERIC_IRQ_EFFECTIVE_AFF_MASK;
        cpumask_var_t effective_affinity;
    #endif;
    #ifdef CONFIG_GENERIC_IRQ_IPI;
        unsigned int            ipi_offset;
    #endif;
};
```

**Members**

- `state_use_accessors`: status information for irq chip functions.
  Use accessor functions to deal with it
- `node`: node index useful for balancing
- `handler_data`: per-IRQ data for the irq_chip methods
- `msi_desc`: MSI descriptor
- `affinity`: IRQ affinity on SMP. If this is an IPI
  related irq, then this is the mask of the
  CPUs to which an IPI can be sent.
- `effective_affinity`: The effective IRQ affinity on SMP as some irq
  chips do not allow multi CPU destinations.
  A subset of **affinity**.
- `ipi_offset`: Offset of first IPI target cpu in **affinity**. Optional.

#### <a id="c-struct-irq_data"></a>`struct irq_data`

per irq chip data passed down to chip functions

**Definition**

```c
struct irq_data {
        u32 mask;
        unsigned int            irq;
        irq_hw_number_t hwirq;
        struct irq_common_data  *common;
        struct irq_chip         *chip;
        struct irq_domain       *domain;
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        struct irq_data         *parent_data;
    #endif;
        void *chip_data;
};
```

**Members**

- `mask`: precomputed bitmask for accessing the chip registers
- `irq`: interrupt number
- `hwirq`: hardware interrupt number, local to the interrupt domain
- `common`: point to data shared by all irqchips
- `chip`: low level interrupt hardware access
- `domain`: Interrupt translation domain; responsible for mapping
  between hwirq number and linux irq number.
- `parent_data`: pointer to parent struct irq_data to support hierarchy
  irq_domain
- `chip_data`: platform-specific per-chip private data for the chip
  methods, to allow shared chip implementations

#### <a id="c-struct-irq_chip"></a>`struct irq_chip`

hardware interrupt chip descriptor

**Definition**

```c
struct irq_chip {
        const char      *name;
        unsigned int    (*irq_startup)(struct irq_data *data);
        void (*irq_shutdown)(struct irq_data *data);
        void (*irq_enable)(struct irq_data *data);
        void (*irq_disable)(struct irq_data *data);
        void (*irq_ack)(struct irq_data *data);
        void (*irq_mask)(struct irq_data *data);
        void (*irq_mask_ack)(struct irq_data *data);
        void (*irq_unmask)(struct irq_data *data);
        void (*irq_eoi)(struct irq_data *data);
        int (*irq_set_affinity)(struct irq_data *data, const struct cpumask *dest, bool force);
        void (*irq_pre_redirect)(struct irq_data *data);
        int (*irq_retrigger)(struct irq_data *data);
        int (*irq_set_type)(struct irq_data *data, unsigned int flow_type);
        int (*irq_set_wake)(struct irq_data *data, unsigned int on);
        void (*irq_bus_lock)(struct irq_data *data);
        void (*irq_bus_sync_unlock)(struct irq_data *data);
    #ifdef CONFIG_DEPRECATED_IRQ_CPU_ONOFFLINE;
        void (*irq_cpu_online)(struct irq_data *data);
        void (*irq_cpu_offline)(struct irq_data *data);
    #endif;
        void (*irq_suspend)(struct irq_data *data);
        void (*irq_resume)(struct irq_data *data);
        void (*irq_pm_shutdown)(struct irq_data *data);
        void (*irq_calc_mask)(struct irq_data *data);
        void (*irq_print_chip)(struct irq_data *data, struct seq_file *p);
        int (*irq_request_resources)(struct irq_data *data);
        void (*irq_release_resources)(struct irq_data *data);
        void (*irq_compose_msi_msg)(struct irq_data *data, struct msi_msg *msg);
        void (*irq_write_msi_msg)(struct irq_data *data, struct msi_msg *msg);
        int (*irq_get_irqchip_state)(struct irq_data *data, enum irqchip_irq_state which, bool *state);
        int (*irq_set_irqchip_state)(struct irq_data *data, enum irqchip_irq_state which, bool state);
        int (*irq_set_vcpu_affinity)(struct irq_data *data, void *vcpu_info);
        void (*ipi_send_single)(struct irq_data *data, unsigned int cpu);
        void (*ipi_send_mask)(struct irq_data *data, const struct cpumask *dest);
        int (*irq_nmi_setup)(struct irq_data *data);
        void (*irq_nmi_teardown)(struct irq_data *data);
        void (*irq_force_complete_move)(struct irq_data *data);
        unsigned long   flags;
};
```

**Members**

- `name`: name for /proc/interrupts
- `irq_startup`: start up the interrupt (defaults to ->enable if NULL)
- `irq_shutdown`: shut down the interrupt (defaults to ->disable if NULL)
- `irq_enable`: enable the interrupt (defaults to chip->unmask if NULL)
- `irq_disable`: disable the interrupt
- `irq_ack`: start of a new interrupt
- `irq_mask`: mask an interrupt source
- `irq_mask_ack`: ack and mask an interrupt source
- `irq_unmask`: unmask an interrupt source
- `irq_eoi`: end of interrupt
- `irq_set_affinity`: Set the CPU affinity on SMP machines. If the force
  argument is true, it tells the driver to
  unconditionally apply the affinity setting. Sanity
  checks against the supplied affinity mask are not
  required. This is used for CPU hotplug where the
  target CPU is not yet set in the cpu_online_mask.
- `irq_pre_redirect`: Optional function to be invoked before redirecting
  an interrupt via irq_work. Called only on CONFIG_SMP.
- `irq_retrigger`: resend an IRQ to the CPU
- `irq_set_type`: set the flow type (IRQ_TYPE_LEVEL/etc.) of an IRQ
- `irq_set_wake`: enable/disable power-management wake-on of an IRQ
- `irq_bus_lock`: function to lock access to slow bus (i2c) chips
- `irq_bus_sync_unlock`: function to sync and unlock slow bus (i2c) chips
- `irq_cpu_online`: configure an interrupt source for a secondary CPU
- `irq_cpu_offline`: un-configure an interrupt source for a secondary CPU
- `irq_suspend`: function called from core code on suspend once per
  chip, when one or more interrupts are installed
- `irq_resume`: function called from core code on resume once per chip,
  when one ore more interrupts are installed
- `irq_pm_shutdown`: function called from core code on shutdown once per chip
- `irq_calc_mask`: Optional function to set irq_data.mask for special cases
- `irq_print_chip`: optional to print special chip info in show_interrupts
- `irq_request_resources`: optional to request resources before calling
  any other callback related to this irq
- `irq_release_resources`: optional to release resources acquired with
  irq_request_resources
- `irq_compose_msi_msg`: optional to compose message content for MSI
- `irq_write_msi_msg`: optional to write message content for MSI
- `irq_get_irqchip_state`: return the internal state of an interrupt
- `irq_set_irqchip_state`: set the internal state of a interrupt
- `irq_set_vcpu_affinity`: optional to target a vCPU in a virtual machine
- `ipi_send_single`: send a single IPI to destination cpus
- `ipi_send_mask`: send an IPI to destination cpus in cpumask
- `irq_nmi_setup`: function called from core code before enabling an NMI
- `irq_nmi_teardown`: function called from core code after disabling an NMI
- `irq_force_complete_move`: optional function to force complete pending irq move
- `flags`: chip specific flags

#### <a id="c-struct-irq_chip_regs"></a>`struct irq_chip_regs`

register offsets for struct irq_gci

**Definition**

```c
struct irq_chip_regs {
    unsigned long           enable;
    unsigned long           disable;
    unsigned long           mask;
    unsigned long           ack;
    unsigned long           eoi;
    unsigned long           type;
};
```

**Members**

- `enable`: Enable register offset to reg_base
- `disable`: Disable register offset to reg_base
- `mask`: Mask register offset to reg_base
- `ack`: Ack register offset to reg_base
- `eoi`: Eoi register offset to reg_base
- `type`: Type configuration register offset to reg_base

#### <a id="c-struct-irq_chip_type"></a>`struct irq_chip_type`

Generic interrupt chip instance for a flow type

**Definition**

```c
struct irq_chip_type {
    struct irq_chip         chip;
    struct irq_chip_regs    regs;
    irq_flow_handler_t handler;
    u32 type;
    u32 mask_cache_priv;
    u32 *mask_cache;
};
```

**Members**

- `chip`: The real interrupt chip which provides the callbacks
- `regs`: Register offsets for this chip
- `handler`: Flow handler associated with this chip
- `type`: Chip can handle these flow types
- `mask_cache_priv`: Cached mask register private to the chip type
- `mask_cache`: Pointer to cached mask register

**Description**

A irq_generic_chip can have several instances of irq_chip_type when
it requires different functions and register offsets for different
flow types.

#### <a id="c-struct-irq_chip_generic"></a>`struct irq_chip_generic`

Generic irq chip data structure

**Definition**

```c
struct irq_chip_generic {
    raw_spinlock_t lock;
    void __iomem            *reg_base;
    u32 (*reg_readl)(void __iomem *addr);
    void (*reg_writel)(u32 val, void __iomem *addr);
    void (*suspend)(struct irq_chip_generic *gc);
    void (*resume)(struct irq_chip_generic *gc);
    unsigned int            irq_base;
    unsigned int            irq_cnt;
    u32 mask_cache;
    u32 wake_enabled;
    u32 wake_active;
    unsigned int            num_ct;
    void *private;
    unsigned long           installed;
    unsigned long           unused;
    struct irq_domain       *domain;
    struct list_head        list;
    struct irq_chip_type    chip_types[];
};
```

**Members**

- `lock`: Lock to protect register and cache data access
- `reg_base`: Register base address (virtual)
- `reg_readl`: Alternate I/O accessor (defaults to readl if NULL)
- `reg_writel`: Alternate I/O accessor (defaults to writel if NULL)
- `suspend`: Function called from core code on suspend once per
  chip; can be useful instead of irq_chip::suspend to
  handle chip details even when no interrupts are in use
- `resume`: Function called from core code on resume once per chip;
  can be useful instead of irq_chip::suspend to handle
  chip details even when no interrupts are in use
- `irq_base`: Interrupt base nr for this chip
- `irq_cnt`: Number of interrupts handled by this chip
- `mask_cache`: Cached mask register shared between all chip types
- `wake_enabled`: Interrupt can wakeup from suspend
- `wake_active`: Interrupt is marked as an wakeup from suspend source
- `num_ct`: Number of available irq_chip_type instances (usually 1)
- `private`: Private data for non generic chip callbacks
- `installed`: bitfield to denote installed interrupts
- `unused`: bitfield to denote unused interrupts
- `domain`: irq domain pointer
- `list`: List head for keeping track of instances
- `chip_types`: Array of interrupt irq_chip_types

**Description**

Note, that irq_chip_generic can have multiple irq_chip_type
implementations which can be associated to a particular irq line of
an irq_chip_generic instance. That allows to share and protect
state in an irq_chip_generic instance when we need to implement
different flow mechanisms (level/edge) for it.

#### <a id="c-enum-irq_gc_flags"></a>`enum irq_gc_flags`

Initialization flags for generic irq chips

**Constants**

- `IRQ_GC_INIT_MASK_CACHE`: Initialize the mask_cache by reading mask reg
- `IRQ_GC_INIT_NESTED_LOCK`: Set the lock class of the irqs to nested for
  irq chips which need to call `irq_set_wake()` on
  the parent irq. Usually GPIO implementations
- `IRQ_GC_MASK_CACHE_PER_TYPE`: Mask cache is chip type private
- `IRQ_GC_NO_MASK`: Do not calculate irq_data->mask
- `IRQ_GC_BE_IO`: Use big-endian register accesses (default: LE)

#### <a id="c-struct-irq_domain_chip_generic_info"></a>`struct irq_domain_chip_generic_info`

Generic chip information structure

**Definition**

```c
struct irq_domain_chip_generic_info {
    const char              *name;
    irq_flow_handler_t handler;
    unsigned int            irqs_per_chip;
    unsigned int            num_ct;
    unsigned int            irq_flags_to_clear;
    unsigned int            irq_flags_to_set;
    enum irq_gc_flags       gc_flags;
    int (*init)(struct irq_chip_generic *gc);
    void (*exit)(struct irq_chip_generic *gc);
};
```

**Members**

- `name`: Name of the generic interrupt chip
- `handler`: Interrupt handler used by the generic interrupt chip
- `irqs_per_chip`: Number of interrupts each chip handles (max 32)
- `num_ct`: Number of irq_chip_type instances associated with each
  chip
- `irq_flags_to_clear`: IRQ_* bits to clear in the mapping function
- `irq_flags_to_set`: IRQ_* bits to set in the mapping function
- `gc_flags`: Generic chip specific setup flags
- `init`: Function called on each chip when they are created.
  Allow to do some additional chip initialisation.
- `exit`: Function called on each chip when they are destroyed.
  Allow to do some chip cleanup operation.



#### <a id="c-struct-irqaction"></a>`struct irqaction`

per interrupt action descriptor

**Definition**

```c
struct irqaction {
    irq_handler_t handler;
    union {
        void *dev_id;
        void __percpu   *percpu_dev_id;
    };
    const struct cpumask    *affinity;
    struct irqaction        *next;
    irq_handler_t thread_fn;
    struct task_struct      *thread;
    struct irqaction        *secondary;
    unsigned int            irq;
    unsigned int            flags;
    unsigned long           thread_flags;
    unsigned long           thread_mask;
    const char              *name;
    struct proc_dir_entry   *dir;
};
```

**Members**

- `handler`: interrupt handler function
- `{unnamed_union}`: anonymous
- `dev_id`: cookie to identify the device
- `percpu_dev_id`: cookie to identify the device
- `affinity`: CPUs this irqaction is allowed to run on
- `next`: pointer to the next irqaction for shared interrupts
- `thread_fn`: interrupt handler function for threaded interrupts
- `thread`: thread pointer for threaded interrupts
- `secondary`: pointer to secondary irqaction (force threading)
- `irq`: interrupt number
- `flags`: flags (see IRQF_* above)
- `thread_flags`: flags related to **thread**
- `thread_mask`: bitmask for keeping track of **thread** activity
- `name`: name of the device
- `dir`: pointer to the proc/irq/NN/name entry

#### <a id="c-request_irq"></a>`request_irq()`

```c
int request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags, const char *name, void *dev)
```

Add a handler for an interrupt line

**Parameters**

- `unsigned int irq`: The interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
  Primary handler for threaded interrupts
  If NULL, the default primary handler is installed
- `unsigned long flags`: Handling flags
- `const char *name`: Name of the device generating this interrupt
- `void *dev`: A cookie passed to the handler function

**Description**

This call allocates an interrupt and establishes a handler; see
the documentation for [`request_threaded_irq()`](#c-request_threaded_irq) for details.

#### <a id="c-struct-irq_affinity_notify"></a>`struct irq_affinity_notify`

context for notification of IRQ affinity changes

**Definition**

```c
struct irq_affinity_notify {
    unsigned int irq;
    struct kref kref;
    struct work_struct work;
    void (*notify)(struct irq_affinity_notify *, const cpumask_t *mask);
    void (*release)(struct kref *ref);
};
```

**Members**

- `irq`: Interrupt to which notification applies
- `kref`: Reference count, for internal use
- `work`: Work item, for internal use
- `notify`: Function to be called on change.  This will be
  called in process context.
- `release`: Function to be called on release.  This will be
  called in process context.  Once registered, the
  structure must only be freed when this function is
  called or later.

#### <a id="c-struct-irq_affinity"></a>`struct irq_affinity`

Description for automatic irq affinity assignments

**Definition**

```c
struct irq_affinity {
    unsigned int    pre_vectors;
    unsigned int    post_vectors;
    unsigned int    nr_sets;
    unsigned int    set_size[IRQ_AFFINITY_MAX_SETS];
    void (*calc_sets)(struct irq_affinity *, unsigned int nvecs);
    void *priv;
};
```

**Members**

- `pre_vectors`: Don't apply affinity to **pre_vectors** at beginning of
  the MSI(-X) vector space
- `post_vectors`: Don't apply affinity to **post_vectors** at end of
  the MSI(-X) vector space
- `nr_sets`: The number of interrupt sets for which affinity
  spreading is required
- `set_size`: Array holding the size of each interrupt set
- `calc_sets`: Callback for calculating the number and size
  of interrupt sets
- `priv`: Private data for usage by **calc_sets**, usually a
  pointer to driver/device specific data.

#### <a id="c-struct-irq_affinity_desc"></a>`struct irq_affinity_desc`

Interrupt affinity descriptor

**Definition**

```c
struct irq_affinity_desc {
    struct cpumask  mask;
    unsigned int    is_managed : 1;
};
```

**Members**

- `mask`: cpumask to hold the affinity assignment
- `is_managed`: 1 if the interrupt is managed internally

#### <a id="c-irq_update_affinity_hint"></a>`irq_update_affinity_hint()`

```c
int irq_update_affinity_hint(unsigned int irq, const struct cpumask *m)
```

Update the affinity hint

**Parameters**

- `unsigned int irq`: Interrupt to update
- `const struct cpumask *m`: cpumask pointer (NULL to clear the hint)

**Description**

Updates the affinity hint, but does not change the affinity of the interrupt.

#### <a id="c-irq_set_affinity_and_hint"></a>`irq_set_affinity_and_hint()`

```c
int irq_set_affinity_and_hint(unsigned int irq, const struct cpumask *m)
```

Update the affinity hint and apply the provided cpumask to the interrupt

**Parameters**

- `unsigned int irq`: Interrupt to update
- `const struct cpumask *m`: cpumask pointer (NULL to clear the hint)

**Description**

Updates the affinity hint and if **m** is not NULL it applies it as the
affinity of that interrupt.


<a id="rst-public-functions-provided"></a>

## Public Functions Provided

This chapter contains the autogenerated documentation of the kernel API functions which are exported.


#### <a id="c-synchronize_hardirq"></a>`synchronize_hardirq()`

```c
bool synchronize_hardirq(unsigned int irq)
```

wait for pending hard IRQ handlers (on other CPUs)

**Parameters**

- `unsigned int irq`: interrupt number to wait for

**Description**

This function waits for any pending hard IRQ handlers for this interrupt
to complete before returning. If you use this function while holding a
resource the IRQ handler may need you will deadlock. It does not take
associated threaded handlers into account.

Do not use this for shutdown scenarios where you must be sure that all
parts (hardirq and threaded handler) have completed.

This function may be called - with care - from IRQ context.

It does not check whether there is an interrupt in flight at the
hardware level, but not serviced yet, as this might deadlock when called
with interrupts disabled and the target CPU of the interrupt is the
current CPU.

**Return**

false if a threaded handler is active.

#### <a id="c-synchronize_irq"></a>`synchronize_irq()`

```c
void synchronize_irq(unsigned int irq)
```

wait for pending IRQ handlers (on other CPUs)

**Parameters**

- `unsigned int irq`: interrupt number to wait for

**Description**

This function waits for any pending IRQ handlers for this interrupt to
complete before returning. If you use this function while holding a
resource the IRQ handler may need you will deadlock.

Can only be called from preemptible code as it might sleep when
an interrupt thread is associated to **irq**.

It optionally makes sure (when the irq chip supports that method)
that the interrupt is not pending in any CPU and waiting for
service.

#### <a id="c-irq_can_set_affinity"></a>`irq_can_set_affinity()`

```c
int irq_can_set_affinity(unsigned int irq)
```

Check if the affinity of a given irq can be set

**Parameters**

- `unsigned int irq`: Interrupt to check

#### <a id="c-irq_can_set_affinity_usr"></a>`irq_can_set_affinity_usr()`

```c
bool irq_can_set_affinity_usr(unsigned int irq)
```

Check if affinity of a irq can be set from user space

**Parameters**

- `unsigned int irq`: Interrupt to check

**Description**

Like [`irq_can_set_affinity()`](#c-irq_can_set_affinity) above, but additionally checks for the
AFFINITY_MANAGED flag.

#### <a id="c-irq_set_thread_affinity"></a>`irq_set_thread_affinity()`

```c
void irq_set_thread_affinity(struct irq_desc *desc)
```

Notify irq threads to adjust affinity

**Parameters**

- `struct irq_desc *desc`: irq descriptor which has affinity changed

**Description**

Just set IRQTF_AFFINITY and delegate the affinity setting to the
interrupt thread itself. We can not call [`set_cpus_allowed_ptr()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-set_cpus_allowed_ptr) here as
we hold desc->lock and this code can be called from hard interrupt
context.

#### <a id="c-irq_affinity_schedule_notify_work"></a>`irq_affinity_schedule_notify_work()`

```c
void irq_affinity_schedule_notify_work(struct irq_desc *desc)
```

Schedule work to notify about affinity change

**Parameters**

- `struct irq_desc *desc`: Interrupt descriptor whose affinity changed

#### <a id="c-irq_update_affinity_desc"></a>`irq_update_affinity_desc()`

```c
int irq_update_affinity_desc(unsigned int irq, struct irq_affinity_desc *affinity)
```

Update affinity management for an interrupt

**Parameters**

- `unsigned int irq`: The interrupt number to update
- `struct irq_affinity_desc *affinity`: Pointer to the affinity descriptor

**Description**

This interface can be used to configure the affinity management of
interrupts which have been allocated already.

There are certain limitations on when it may be used - attempts to use it
for when the kernel is configured for generic IRQ reservation mode (in
config GENERIC_IRQ_RESERVATION_MODE) will fail, as it may conflict with
managed/non-managed interrupt accounting. In addition, attempts to use it on
an interrupt which is already started or which has already been configured
as managed will also fail, as these mean invalid init state or double init.

#### <a id="c-irq_set_affinity"></a>`irq_set_affinity()`

```c
int irq_set_affinity(unsigned int irq, const struct cpumask *cpumask)
```

Set the irq affinity of a given irq

**Parameters**

- `unsigned int irq`: Interrupt to set affinity
- `const struct cpumask *cpumask`: cpumask

**Description**

Fails if cpumask does not contain an online CPU

#### <a id="c-irq_force_affinity"></a>`irq_force_affinity()`

```c
int irq_force_affinity(unsigned int irq, const struct cpumask *cpumask)
```

Force the irq affinity of a given irq

**Parameters**

- `unsigned int irq`: Interrupt to set affinity
- `const struct cpumask *cpumask`: cpumask

**Description**

Same as irq_set_affinity, but without checking the mask against
online cpus.

Solely for low level cpu hotplug code, where we need to make per
cpu interrupts affine before the cpu becomes online.

#### <a id="c-irq_set_affinity_notifier"></a>`irq_set_affinity_notifier()`

```c
int irq_set_affinity_notifier(unsigned int irq, struct irq_affinity_notify *notify)
```

control notification of IRQ affinity changes

**Parameters**

- `unsigned int irq`: Interrupt for which to enable/disable notification
- `struct irq_affinity_notify *notify`: Context for notification, or `NULL` to disable
  notification.  Function pointers must be initialised;
  the other fields will be initialised by this function.

**Description**

Must be called in process context.  Notification may only be enabled
after the IRQ is allocated and must be disabled before the IRQ is freed
using [`free_irq()`](#c-free_irq).

#### <a id="c-irq_set_vcpu_affinity"></a>`irq_set_vcpu_affinity()`

```c
int irq_set_vcpu_affinity(unsigned int irq, void *vcpu_info)
```

Set vcpu affinity for the interrupt

**Parameters**

- `unsigned int irq`: interrupt number to set affinity
- `void *vcpu_info`: vCPU specific data or pointer to a percpu array of vCPU
  specific data for percpu_devid interrupts

**Description**

This function uses the vCPU specific data to set the vCPU affinity for
an irq. The vCPU specific data is passed from outside, such as KVM. One
example code path is as below: KVM -> IOMMU -> [`irq_set_vcpu_affinity()`](#c-irq_set_vcpu_affinity).

#### <a id="c-disable_irq_nosync"></a>`disable_irq_nosync()`

```c
void disable_irq_nosync(unsigned int irq)
```

disable an irq without waiting

**Parameters**

- `unsigned int irq`: Interrupt to disable

**Description**

Disable the selected interrupt line.  Disables and Enables are
nested.
Unlike [`disable_irq()`](#c-disable_irq), this function does not ensure existing
instances of the IRQ handler have completed before returning.

This function may be called from IRQ context.

#### <a id="c-disable_irq"></a>`disable_irq()`

```c
void disable_irq(unsigned int irq)
```

disable an irq and wait for completion

**Parameters**

- `unsigned int irq`: Interrupt to disable

**Description**

Disable the selected interrupt line.  Enables and Disables are nested.

This function waits for any pending IRQ handlers for this interrupt to
complete before returning. If you use this function while holding a
resource the IRQ handler may need you will deadlock.

Can only be called from preemptible code as it might sleep when an
interrupt thread is associated to **irq**.

#### <a id="c-disable_hardirq"></a>`disable_hardirq()`

```c
bool disable_hardirq(unsigned int irq)
```

disables an irq and waits for hardirq completion

**Parameters**

- `unsigned int irq`: Interrupt to disable

**Description**

Disable the selected interrupt line.  Enables and Disables are nested.

This function waits for any pending hard IRQ handlers for this interrupt
to complete before returning. If you use this function while holding a
resource the hard IRQ handler may need you will deadlock.

When used to optimistically disable an interrupt from atomic context the
return value must be checked.

This function may be called - with care - from IRQ context.

**Return**

false if a threaded handler is active.

#### <a id="c-disable_nmi_nosync"></a>`disable_nmi_nosync()`

```c
void disable_nmi_nosync(unsigned int irq)
```

disable an nmi without waiting

**Parameters**

- `unsigned int irq`: Interrupt to disable

**Description**

Disable the selected interrupt line. Disables and enables are nested.

The interrupt to disable must have been requested through request_nmi.
Unlike `disable_nmi()`, this function does not ensure existing
instances of the IRQ handler have completed before returning.

#### <a id="c-enable_irq"></a>`enable_irq()`

```c
void enable_irq(unsigned int irq)
```

enable handling of an irq

**Parameters**

- `unsigned int irq`: Interrupt to enable

**Description**

Undoes the effect of one call to [`disable_irq()`](#c-disable_irq).  If this matches the
last disable, processing of interrupts on this IRQ line is re-enabled.

This function may be called from IRQ context only when
desc->irq_data.chip->bus_lock and desc->chip->bus_sync_unlock are NULL !

#### <a id="c-enable_nmi"></a>`enable_nmi()`

```c
void enable_nmi(unsigned int irq)
```

enable handling of an nmi

**Parameters**

- `unsigned int irq`: Interrupt to enable

**Description**

The interrupt to enable must have been requested through request_nmi.
Undoes the effect of one call to `disable_nmi()`. If this matches the last
disable, processing of interrupts on this IRQ line is re-enabled.

#### <a id="c-irq_set_irq_wake"></a>`irq_set_irq_wake()`

```c
int irq_set_irq_wake(unsigned int irq, unsigned int on)
```

control irq power management wakeup

**Parameters**

- `unsigned int irq`: interrupt to control
- `unsigned int on`: enable/disable power management wakeup

**Description**

Enable/disable power management wakeup mode, which is disabled by
default.  Enables and disables must match, just as they match for
non-wakeup mode support.

Wakeup mode lets this IRQ wake the system from sleep states like
"suspend to RAM".

**Note**

irq enable/disable state is completely orthogonal to the
enable/disable state of irq wake. An irq can be disabled with
[`disable_irq()`](#c-disable_irq) and still wake the system as long as the irq has wake
enabled. If this does not hold, then the underlying irq chip and the
related driver need to be investigated.

#### <a id="c-irq_wake_thread"></a>`irq_wake_thread()`

```c
void irq_wake_thread(unsigned int irq, void *dev_id)
```

wake the irq thread for the action identified by dev_id

**Parameters**

- `unsigned int irq`: Interrupt line
- `void *dev_id`: Device identity for which the thread should be woken

#### <a id="c-free_irq"></a>`free_irq()`

```c
const void * free_irq(unsigned int irq, void *dev_id)
```

free an interrupt allocated with request_irq

**Parameters**

- `unsigned int irq`: Interrupt line to free
- `void *dev_id`: Device identity to free

**Description**

Remove an interrupt handler. The handler is removed and if the interrupt
line is no longer in use by any driver it is disabled.  On a shared IRQ
the caller must ensure the interrupt is disabled on the card it drives
before calling this function. The function does not return until any
executing interrupts for this IRQ have completed.

This function must not be called from interrupt context.

Returns the devname argument passed to request_irq.

#### <a id="c-request_threaded_irq"></a>`request_threaded_irq()`

```c
int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn, unsigned long irqflags, const char *devname, void *dev_id)
```

allocate an interrupt line

**Parameters**

- `unsigned int irq`: Interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
  Primary handler for threaded interrupts.
  If handler is NULL and thread_fn != NULL
  the default primary handler is installed.
- `irq_handler_t thread_fn`: Function called from the irq handler thread
  If NULL, no irq thread is created
- `unsigned long irqflags`: Interrupt type flags
- `const char *devname`: An ascii name for the claiming device
- `void *dev_id`: A cookie passed back to the handler function

**Description**

This call allocates interrupt resources and enables the interrupt line
and IRQ handling. From the point this call is made your handler function
may be invoked. Since your handler function must clear any interrupt the
board raises, you must take care both to initialise your hardware and to
set up the interrupt handler in the right order.

If you want to set up a threaded irq handler for your device then you
need to supply **handler** and **thread_fn**. **handler** is still called in hard
interrupt context and has to check whether the interrupt originates from
the device. If yes it needs to disable the interrupt on the device and
return IRQ_WAKE_THREAD which will wake up the handler thread and run
**thread_fn**. This split handler design is necessary to support shared
interrupts.

**dev_id** must be globally unique. Normally the address of the device data
structure is used as the cookie. Since the handler receives this value
it makes sense to use it.

If your interrupt is shared you must pass a non NULL dev_id as this is
required when freeing the interrupt.

Flags:

IRQF_SHARED             Interrupt is shared
IRQF_TRIGGER_*          Specify active edge(s) or level
IRQF_ONESHOT            Run thread_fn with interrupt line masked

#### <a id="c-request_any_context_irq"></a>`request_any_context_irq()`

```c
int request_any_context_irq(unsigned int irq, irq_handler_t handler, unsigned long flags, const char *name, void *dev_id)
```

allocate an interrupt line

**Parameters**

- `unsigned int irq`: Interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
  Threaded handler for threaded interrupts.
- `unsigned long flags`: Interrupt type flags
- `const char *name`: An ascii name for the claiming device
- `void *dev_id`: A cookie passed back to the handler function

**Description**

This call allocates interrupt resources and enables the interrupt line
and IRQ handling. It selects either a hardirq or threaded handling
method depending on the context.

**Return**

On failure, it returns a negative value. On success, it returns either
IRQC_IS_HARDIRQ or IRQC_IS_NESTED.

#### <a id="c-request_nmi"></a>`request_nmi()`

```c
int request_nmi(unsigned int irq, irq_handler_t handler, unsigned long irqflags, const char *name, void *dev_id)
```

allocate an interrupt line for NMI delivery

**Parameters**

- `unsigned int irq`: Interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
  Threaded handler for threaded interrupts.
- `unsigned long irqflags`: Interrupt type flags
- `const char *name`: An ascii name for the claiming device
- `void *dev_id`: A cookie passed back to the handler function

**Description**

This call allocates interrupt resources and enables the interrupt line
and IRQ handling. It sets up the IRQ line to be handled as an NMI.

An interrupt line delivering NMIs cannot be shared and IRQ handling
cannot be threaded.

Interrupt lines requested for NMI delivering must produce per cpu
interrupts and have auto enabling setting disabled.

**dev_id** must be globally unique. Normally the address of the device data
structure is used as the cookie. Since the handler receives this value
it makes sense to use it.

If the interrupt line cannot be used to deliver NMIs, function will fail
and return a negative value.

#### <a id="c-irq_percpu_is_enabled"></a>`irq_percpu_is_enabled()`

```c
bool irq_percpu_is_enabled(unsigned int irq)
```

Check whether the per cpu irq is enabled

**Parameters**

- `unsigned int irq`: Linux irq number to check for

**Description**

Must be called from a non migratable context. Returns the enable
state of a per cpu interrupt on the current cpu.

#### <a id="c-free_percpu_irq"></a>`free_percpu_irq()`

```c
void free_percpu_irq(unsigned int irq, void __percpu *dev_id)
```

free an interrupt allocated with request_percpu_irq

**Parameters**

- `unsigned int irq`: Interrupt line to free
- `void __percpu *dev_id`: Device identity to free

**Description**

Remove a percpu interrupt handler. The handler is removed, but the
interrupt line is not disabled. This must be done on each CPU before
calling this function. The function does not return until any executing
interrupts for this IRQ have completed.

This function must not be called from interrupt context.

#### <a id="c-request_percpu_irq_affinity"></a>`request_percpu_irq_affinity()`

```c
int request_percpu_irq_affinity(unsigned int irq, irq_handler_t handler, const char *devname, const cpumask_t *affinity, void __percpu *dev_id)
```

allocate a percpu interrupt line

**Parameters**

- `unsigned int irq`: Interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
- `const char *devname`: An ascii name for the claiming device
- `const cpumask_t *affinity`: A cpumask describing the target CPUs for this interrupt
- `void __percpu *dev_id`: A percpu cookie passed back to the handler function

**Description**

This call allocates interrupt resources, but doesn't enable the interrupt
on any CPU, as all percpu-devid interrupts are flagged with IRQ_NOAUTOEN.
It has to be done on each CPU using `enable_percpu_irq()`.

**dev_id** must be globally unique. It is a per-cpu variable, and
the handler gets called with the interrupted CPU's instance of
that variable.

#### <a id="c-request_percpu_nmi"></a>`request_percpu_nmi()`

```c
int request_percpu_nmi(unsigned int irq, irq_handler_t handler, const char *name, const struct cpumask *affinity, void __percpu *dev_id)
```

allocate a percpu interrupt line for NMI delivery

**Parameters**

- `unsigned int irq`: Interrupt line to allocate
- `irq_handler_t handler`: Function to be called when the IRQ occurs.
- `const char *name`: An ascii name for the claiming device
- `const struct cpumask *affinity`: A cpumask describing the target CPUs for this interrupt
- `void __percpu *dev_id`: A percpu cookie passed back to the handler function

**Description**

This call allocates interrupt resources for a per CPU NMI. Per CPU NMIs
have to be setup on each CPU by calling [`prepare_percpu_nmi()`](#c-prepare_percpu_nmi) before
being enabled on the same CPU by using `enable_percpu_nmi()`.

**dev_id** must be globally unique. It is a per-cpu variable, and the
handler gets called with the interrupted CPU's instance of that
variable.

Interrupt lines requested for NMI delivering should have auto enabling
setting disabled.

If the interrupt line cannot be used to deliver NMIs, function
will fail returning a negative value.

#### <a id="c-prepare_percpu_nmi"></a>`prepare_percpu_nmi()`

```c
int prepare_percpu_nmi(unsigned int irq)
```

performs CPU local setup for NMI delivery

**Parameters**

- `unsigned int irq`: Interrupt line to prepare for NMI delivery

**Description**

This call prepares an interrupt line to deliver NMI on the current CPU,
before that interrupt line gets enabled with `enable_percpu_nmi()`.

As a CPU local operation, this should be called from non-preemptible
context.

If the interrupt line cannot be used to deliver NMIs, function will fail
returning a negative value.

#### <a id="c-teardown_percpu_nmi"></a>`teardown_percpu_nmi()`

```c
void teardown_percpu_nmi(unsigned int irq)
```

undoes NMI setup of IRQ line

**Parameters**

- `unsigned int irq`: Interrupt line from which CPU local NMI configuration should be removed

**Description**

This call undoes the setup done by [`prepare_percpu_nmi()`](#c-prepare_percpu_nmi).

IRQ line should not be enabled for the current CPU.
As a CPU local operation, this should be called from non-preemptible
context.

#### <a id="c-irq_get_irqchip_state"></a>`irq_get_irqchip_state()`

```c
int irq_get_irqchip_state(unsigned int irq, enum irqchip_irq_state which, bool *state)
```

returns the irqchip state of a interrupt.

**Parameters**

- `unsigned int irq`: Interrupt line that is forwarded to a VM
- `enum irqchip_irq_state which`: One of IRQCHIP_STATE_* the caller wants to know about
- `bool *state`: a pointer to a boolean where the state is to be stored

**Description**

This call snapshots the internal irqchip state of an interrupt,
returning into **state** the bit corresponding to stage **which**

This function should be called with preemption disabled if the interrupt
controller has per-cpu registers.

#### <a id="c-irq_set_irqchip_state"></a>`irq_set_irqchip_state()`

```c
int irq_set_irqchip_state(unsigned int irq, enum irqchip_irq_state which, bool val)
```

set the state of a forwarded interrupt.

**Parameters**

- `unsigned int irq`: Interrupt line that is forwarded to a VM
- `enum irqchip_irq_state which`: State to be restored (one of IRQCHIP_STATE_*)
- `bool val`: Value corresponding to **which**

**Description**

This call sets the internal irqchip state of an interrupt, depending on
the value of **which**.

This function should be called with migration disabled if the interrupt
controller has per-cpu registers.

#### <a id="c-irq_has_action"></a>`irq_has_action()`

```c
bool irq_has_action(unsigned int irq)
```

Check whether an interrupt is requested

**Parameters**

- `unsigned int irq`: The linux irq number

**Return**

A snapshot of the current state

#### <a id="c-irq_check_status_bit"></a>`irq_check_status_bit()`

```c
bool irq_check_status_bit(unsigned int irq, unsigned int bitmask)
```

Check whether bits in the irq descriptor status are set

**Parameters**

- `unsigned int irq`: The linux irq number
- `unsigned int bitmask`: The bitmask to evaluate

**Return**

True if one of the bits in **bitmask** is set



#### <a id="c-irq_set_chip"></a>`irq_set_chip()`

```c
int irq_set_chip(unsigned int irq, const struct irq_chip *chip)
```

set the irq chip for an irq

**Parameters**

- `unsigned int irq`: irq number
- `const struct irq_chip *chip`: pointer to irq chip description structure

#### <a id="c-irq_set_irq_type"></a>`irq_set_irq_type()`

```c
int irq_set_irq_type(unsigned int irq, unsigned int type)
```

set the irq trigger type for an irq

**Parameters**

- `unsigned int irq`: irq number
- `unsigned int type`: IRQ_TYPE_{LEVEL,EDGE}_* value - see include/linux/irq.h

#### <a id="c-irq_set_handler_data"></a>`irq_set_handler_data()`

```c
int irq_set_handler_data(unsigned int irq, void *data)
```

set irq handler data for an irq

**Parameters**

- `unsigned int irq`: Interrupt number
- `void *data`: Pointer to interrupt specific data

**Description**

Set the hardware irq controller data for an irq

#### <a id="c-irq_set_chip_data"></a>`irq_set_chip_data()`

```c
int irq_set_chip_data(unsigned int irq, void *data)
```

set irq chip data for an irq

**Parameters**

- `unsigned int irq`: Interrupt number
- `void *data`: Pointer to chip specific data

**Description**

Set the hardware irq chip data for an irq

#### <a id="c-handle_nested_irq"></a>`handle_nested_irq()`

```c
void handle_nested_irq(unsigned int irq)
```

Handle a nested irq from a irq thread

**Parameters**

- `unsigned int irq`: the interrupt number

**Description**

Handle interrupts which are nested into a threaded interrupt
handler. The handler function is called inside the calling threads
context.

#### <a id="c-handle_simple_irq"></a>`handle_simple_irq()`

```c
void handle_simple_irq(struct irq_desc *desc)
```

Simple and software-decoded IRQs.

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Simple interrupts are either sent from a demultiplexing interrupt
handler or come from hardware, where no interrupt hardware control is
necessary.

**Note**

The caller is expected to handle the ack, clear, mask and unmask
issues if necessary.

#### <a id="c-handle_untracked_irq"></a>`handle_untracked_irq()`

```c
void handle_untracked_irq(struct irq_desc *desc)
```

Simple and software-decoded IRQs.

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Untracked interrupts are sent from a demultiplexing interrupt handler
when the demultiplexer does not know which device it its multiplexed irq
domain generated the interrupt. IRQ's handled through here are not
subjected to stats tracking, randomness, or spurious interrupt
detection.

**Note**

Like handle_simple_irq, the caller is expected to handle the ack,
clear, mask and unmask issues if necessary.

#### <a id="c-handle_level_irq"></a>`handle_level_irq()`

```c
void handle_level_irq(struct irq_desc *desc)
```

Level type irq handler

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Level type interrupts are active as long as the hardware line has the
active level. This may require to mask the interrupt and unmask it after
the associated handler has acknowledged the device, so the interrupt
line is back to inactive.

#### <a id="c-handle_fasteoi_irq"></a>`handle_fasteoi_irq()`

```c
void handle_fasteoi_irq(struct irq_desc *desc)
```

irq handler for transparent controllers

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Only a single callback will be issued to the chip: an ->`eoi()` call when
the interrupt has been serviced. This enables support for modern forms
of interrupt handlers, which handle the flow details in hardware,
transparently.

#### <a id="c-handle_fasteoi_nmi"></a>`handle_fasteoi_nmi()`

```c
void handle_fasteoi_nmi(struct irq_desc *desc)
```

irq handler for NMI interrupt lines

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

A simple NMI-safe handler, considering the restrictions
from request_nmi.

Only a single callback will be issued to the chip: an ->`eoi()`
call when the interrupt has been serviced. This enables support
for modern forms of interrupt handlers, which handle the flow
details in hardware, transparently.

#### <a id="c-handle_edge_irq"></a>`handle_edge_irq()`

```c
void handle_edge_irq(struct irq_desc *desc)
```

edge type IRQ handler

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Interrupt occurs on the falling and/or rising edge of a hardware
signal. The occurrence is latched into the irq controller hardware and
must be acked in order to be reenabled. After the ack another interrupt
can happen on the same source even before the first one is handled by
the associated event handler. If this happens it might be necessary to
disable (mask) the interrupt depending on the controller hardware. This
requires to reenable the interrupt inside of the loop which handles the
interrupts which have arrived while the handler was running. If all
pending interrupts are handled, the loop is left.

#### <a id="c-handle_fasteoi_ack_irq"></a>`handle_fasteoi_ack_irq()`

```c
void handle_fasteoi_ack_irq(struct irq_desc *desc)
```

irq handler for edge hierarchy stacked on transparent controllers

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Like [`handle_fasteoi_irq()`](#c-handle_fasteoi_irq), but for use with hierarchy where the irq_chip
also needs to have its ->`irq_ack()` function called.

#### <a id="c-handle_fasteoi_mask_irq"></a>`handle_fasteoi_mask_irq()`

```c
void handle_fasteoi_mask_irq(struct irq_desc *desc)
```

irq handler for level hierarchy stacked on transparent controllers

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Like [`handle_fasteoi_irq()`](#c-handle_fasteoi_irq), but for use with hierarchy where the irq_chip
also needs to have its ->`irq_mask_ack()` function called.

#### <a id="c-irq_chip_set_parent_state"></a>`irq_chip_set_parent_state()`

```c
int irq_chip_set_parent_state(struct irq_data *data, enum irqchip_irq_state which, bool val)
```

set the state of a parent interrupt.

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `enum irqchip_irq_state which`: State to be restored (one of IRQCHIP_STATE_*)
- `bool val`: Value corresponding to **which**

**Description**

Conditional success, if the underlying irqchip does not implement it.

#### <a id="c-irq_chip_get_parent_state"></a>`irq_chip_get_parent_state()`

```c
int irq_chip_get_parent_state(struct irq_data *data, enum irqchip_irq_state which, bool *state)
```

get the state of a parent interrupt.

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `enum irqchip_irq_state which`: one of IRQCHIP_STATE_* the caller wants to know
- `bool *state`: a pointer to a boolean where the state is to be stored

**Description**

Conditional success, if the underlying irqchip does not implement it.

#### <a id="c-irq_chip_shutdown_parent"></a>`irq_chip_shutdown_parent()`

```c
void irq_chip_shutdown_parent(struct irq_data *data)
```

Shutdown the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

**Description**

Invokes the `irq_shutdown()` callback of the parent if available or falls
back to [`irq_chip_disable_parent()`](#c-irq_chip_disable_parent).

#### <a id="c-irq_chip_startup_parent"></a>`irq_chip_startup_parent()`

```c
unsigned int irq_chip_startup_parent(struct irq_data *data)
```

Startup the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

**Description**

Invokes the `irq_startup()` callback of the parent if available or falls
back to [`irq_chip_enable_parent()`](#c-irq_chip_enable_parent).

#### <a id="c-irq_chip_enable_parent"></a>`irq_chip_enable_parent()`

```c
void irq_chip_enable_parent(struct irq_data *data)
```

Enable the parent interrupt (defaults to unmask if NULL)

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_disable_parent"></a>`irq_chip_disable_parent()`

```c
void irq_chip_disable_parent(struct irq_data *data)
```

Disable the parent interrupt (defaults to mask if NULL)

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_ack_parent"></a>`irq_chip_ack_parent()`

```c
void irq_chip_ack_parent(struct irq_data *data)
```

Acknowledge the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_mask_parent"></a>`irq_chip_mask_parent()`

```c
void irq_chip_mask_parent(struct irq_data *data)
```

Mask the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_mask_ack_parent"></a>`irq_chip_mask_ack_parent()`

```c
void irq_chip_mask_ack_parent(struct irq_data *data)
```

Mask and acknowledge the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_unmask_parent"></a>`irq_chip_unmask_parent()`

```c
void irq_chip_unmask_parent(struct irq_data *data)
```

Unmask the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_eoi_parent"></a>`irq_chip_eoi_parent()`

```c
void irq_chip_eoi_parent(struct irq_data *data)
```

Invoke EOI on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_set_affinity_parent"></a>`irq_chip_set_affinity_parent()`

```c
int irq_chip_set_affinity_parent(struct irq_data *data, const struct cpumask *dest, bool force)
```

Set affinity on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `const struct cpumask *dest`: The affinity mask to set
- `bool force`: Flag to enforce setting (disable online checks)

**Description**

Conditional, as the underlying parent chip might not implement it.

#### <a id="c-irq_chip_set_type_parent"></a>`irq_chip_set_type_parent()`

```c
int irq_chip_set_type_parent(struct irq_data *data, unsigned int type)
```

Set IRQ type on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `unsigned int type`: IRQ_TYPE_{LEVEL,EDGE}_* value - see include/linux/irq.h

**Description**

Conditional, as the underlying parent chip might not implement it.

#### <a id="c-irq_chip_retrigger_hierarchy"></a>`irq_chip_retrigger_hierarchy()`

```c
int irq_chip_retrigger_hierarchy(struct irq_data *data)
```

Retrigger an interrupt in hardware

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

**Description**

Iterate through the domain hierarchy of the interrupt and check
whether a hw retrigger function exists. If yes, invoke it.

#### <a id="c-irq_chip_set_vcpu_affinity_parent"></a>`irq_chip_set_vcpu_affinity_parent()`

```c
int irq_chip_set_vcpu_affinity_parent(struct irq_data *data, void *vcpu_info)
```

Set vcpu affinity on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `void *vcpu_info`: The vcpu affinity information

#### <a id="c-irq_chip_set_wake_parent"></a>`irq_chip_set_wake_parent()`

```c
int irq_chip_set_wake_parent(struct irq_data *data, unsigned int on)
```

Set/reset wake-up on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `unsigned int on`: Whether to set or reset the wake-up capability of this irq

**Description**

Conditional, as the underlying parent chip might not implement it.

#### <a id="c-irq_chip_request_resources_parent"></a>`irq_chip_request_resources_parent()`

```c
int irq_chip_request_resources_parent(struct irq_data *data)
```

Request resources on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

#### <a id="c-irq_chip_release_resources_parent"></a>`irq_chip_release_resources_parent()`

```c
void irq_chip_release_resources_parent(struct irq_data *data)
```

Release resources on the parent interrupt

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data


<a id="rst-internal-functions-provided"></a>

## Internal Functions Provided

This chapter contains the autogenerated documentation of the internal functions.


#### <a id="c-irq_get_nr_irqs"></a>`irq_get_nr_irqs()`

```c
unsigned int irq_get_nr_irqs(void)
```

Number of interrupts supported by the system.

**Parameters**

- `void`: no arguments

#### <a id="c-irq_set_nr_irqs"></a>`irq_set_nr_irqs()`

```c
unsigned int irq_set_nr_irqs(unsigned int nr)
```

Set the number of interrupts supported by the system.

**Parameters**

- `unsigned int nr`: New number of interrupts.

**Return**

**nr**.

#### <a id="c-generic_handle_irq"></a>`generic_handle_irq()`

```c
int generic_handle_irq(unsigned int irq)
```

Invoke the handler for a particular irq

**Parameters**

- `unsigned int irq`: The irq number to handle

**Return**

0 on success, or -EINVAL if conversion has failed

**Description**

This function must be called from an IRQ context with irq regs
initialized.

#### <a id="c-generic_handle_irq_safe"></a>`generic_handle_irq_safe()`

```c
int generic_handle_irq_safe(unsigned int irq)
```

Invoke the handler for a particular irq from any context.

**Parameters**

- `unsigned int irq`: The irq number to handle

**Return**

0 on success, a negative value on error.

**Description**

This function can be called from any context (IRQ or process context). It
will report an error if not invoked from IRQ context and the irq has been
marked to enforce IRQ-context only.

#### <a id="c-generic_handle_domain_irq"></a>`generic_handle_domain_irq()`

```c
int generic_handle_domain_irq(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Invoke the handler for a HW irq belonging to a domain.

**Parameters**

- `struct irq_domain *domain`: The domain where to perform the lookup
- `irq_hw_number_t hwirq`: The HW irq number to convert to a logical one

**Return**

0 on success, or -EINVAL if conversion has failed

**Description**

This function must be called from an IRQ context with irq regs
initialized.

#### <a id="c-generic_handle_domain_nmi"></a>`generic_handle_domain_nmi()`

```c
int generic_handle_domain_nmi(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Invoke the handler for a HW nmi belonging to a domain.

**Parameters**

- `struct irq_domain *domain`: The domain where to perform the lookup
- `irq_hw_number_t hwirq`: The HW irq number to convert to a logical one

**Return**

0 on success, or -EINVAL if conversion has failed

**Description**

This function must be called from an NMI context with irq regs
initialized.

#### <a id="c-generic_handle_demux_domain_irq"></a>`generic_handle_demux_domain_irq()`

```c
bool generic_handle_demux_domain_irq(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Invoke the handler for a hardware interrupt of a demultiplexing domain.

**Parameters**

- `struct irq_domain *domain`: The domain where to perform the lookup
- `irq_hw_number_t hwirq`: The hardware interrupt number to convert to a logical one

**Return**

True on success, or false if lookup has failed

#### <a id="c-irq_free_descs"></a>`irq_free_descs()`

```c
void irq_free_descs(unsigned int from, unsigned int cnt)
```

free irq descriptors

**Parameters**

- `unsigned int from`: Start of descriptor range
- `unsigned int cnt`: Number of consecutive irqs to free

#### <a id="c-__irq_alloc_descs"></a>`__irq_alloc_descs()`

```c
int __ref __irq_alloc_descs(int irq, unsigned int from, unsigned int cnt, int node, struct module *owner, const struct irq_affinity_desc *affinity)
```

allocate and initialize a range of irq descriptors

**Parameters**

- `int irq`: Allocate for specific irq number if irq >= 0
- `unsigned int from`: Start the search from this irq number
- `unsigned int cnt`: Number of consecutive irqs to allocate.
- `int node`: Preferred node on which the irq descriptor should be allocated
- `struct module *owner`: Owning module (can be NULL)
- `const struct irq_affinity_desc *affinity`: Optional pointer to an affinity mask array of size **cnt** which
  hints where the irq descriptors should be allocated and which
  default affinities to use

**Description**

Returns the first irq number or error code

#### <a id="c-irq_get_next_irq"></a>`irq_get_next_irq()`

```c
unsigned int irq_get_next_irq(unsigned int offset)
```

get next allocated irq number

**Parameters**

- `unsigned int offset`: where to start the search

**Description**

Returns next irq number after offset or nr_irqs if none is found.

#### <a id="c-kstat_irqs_cpu"></a>`kstat_irqs_cpu()`

```c
unsigned int kstat_irqs_cpu(unsigned int irq, int cpu)
```

Get the statistics for an interrupt on a cpu

**Parameters**

- `unsigned int irq`: The interrupt number
- `int cpu`: The cpu number

**Description**

Returns the sum of interrupt counts on **cpu** since boot for
**irq**. The caller must ensure that the interrupt is not removed
concurrently.

#### <a id="c-kstat_irqs_usr"></a>`kstat_irqs_usr()`

```c
unsigned int kstat_irqs_usr(unsigned int irq)
```

Get the statistics for an interrupt from thread context

**Parameters**

- `unsigned int irq`: The interrupt number

**Description**

Returns the sum of interrupt counts on all cpus since boot for **irq**.

It uses rcu to protect the access since a concurrent removal of an
interrupt descriptor is observing an rcu grace period before
`delayed_free_desc()`/`irq_kobj_release()`.



#### <a id="c-handle_bad_irq"></a>`handle_bad_irq()`

```c
void handle_bad_irq(struct irq_desc *desc)
```

handle spurious and unhandled irqs

**Parameters**

- `struct irq_desc *desc`: description of the interrupt

**Description**

Handles spurious and unhandled IRQ's. It also prints a debugmessage.

#### <a id="c-generic_handle_arch_irq"></a>`generic_handle_arch_irq()`

```c
void noinstr generic_handle_arch_irq(struct pt_regs *regs)
```

root irq handler for architectures which do no entry accounting themselves

**Parameters**

- `struct pt_regs *regs`: Register file coming from the low-level handling code



#### <a id="c-irq_set_msi_desc_off"></a>`irq_set_msi_desc_off()`

```c
int irq_set_msi_desc_off(unsigned int irq_base, unsigned int irq_offset, struct msi_desc *entry)
```

set MSI descriptor data for an irq at offset

**Parameters**

- `unsigned int irq_base`: Interrupt number base
- `unsigned int irq_offset`: Interrupt number offset
- `struct msi_desc *entry`: Pointer to MSI descriptor data

**Description**

Set the MSI descriptor entry for an irq at offset

#### <a id="c-irq_set_msi_desc"></a>`irq_set_msi_desc()`

```c
int irq_set_msi_desc(unsigned int irq, struct msi_desc *entry)
```

set MSI descriptor data for an irq

**Parameters**

- `unsigned int irq`: Interrupt number
- `struct msi_desc *entry`: Pointer to MSI descriptor data

**Description**

Set the MSI descriptor entry for an irq

#### <a id="c-irq_disable"></a>`irq_disable()`

```c
void irq_disable(struct irq_desc *desc)
```

Mark interrupt disabled

**Parameters**

- `struct irq_desc *desc`: irq descriptor which should be disabled

**Description**

If the chip does not implement the irq_disable callback, we
use a lazy disable approach. That means we mark the interrupt
disabled, but leave the hardware unmasked. That's an
optimization because we avoid the hardware access for the
common case where no interrupt happens after we marked it
disabled. If an interrupt happens, then the interrupt flow
handler masks the line at the hardware level and marks it
pending.

If the interrupt chip does not implement the irq_disable callback,
a driver can disable the lazy approach for a particular irq line by
calling 'irq_set_status_flags(irq, IRQ_DISABLE_UNLAZY)'. This can
be used for devices which cannot disable the interrupt at the
device level under certain circumstances and have to use
disable_irq\[_nosync\] instead.

#### <a id="c-handle_percpu_irq"></a>`handle_percpu_irq()`

```c
void handle_percpu_irq(struct irq_desc *desc)
```

Per CPU local irq handler

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Per CPU interrupts on SMP machines without locking requirements

#### <a id="c-handle_percpu_devid_irq"></a>`handle_percpu_devid_irq()`

```c
void handle_percpu_devid_irq(struct irq_desc *desc)
```

Per CPU local irq handler with per cpu dev ids

**Parameters**

- `struct irq_desc *desc`: the interrupt description structure for this irq

**Description**

Per CPU interrupts on SMP machines without locking requirements. Same as
[`handle_percpu_irq()`](#c-handle_percpu_irq) above but with the following extras:

action->percpu_dev_id is a pointer to percpu variables which
contain the real device id for the cpu on which this handler is
called

#### <a id="c-irq_cpu_online"></a>`irq_cpu_online()`

```c
void irq_cpu_online(void)
```

Invoke all irq_cpu_online functions.

**Parameters**

- `void`: no arguments

**Description**

Iterate through all irqs and invoke the chip.[`irq_cpu_online()`](#c-irq_cpu_online)
for each.

#### <a id="c-irq_cpu_offline"></a>`irq_cpu_offline()`

```c
void irq_cpu_offline(void)
```

Invoke all irq_cpu_offline functions.

**Parameters**

- `void`: no arguments

**Description**

Iterate through all irqs and invoke the chip.[`irq_cpu_offline()`](#c-irq_cpu_offline)
for each.

#### <a id="c-irq_chip_compose_msi_msg"></a>`irq_chip_compose_msi_msg()`

```c
int irq_chip_compose_msi_msg(struct irq_data *data, struct msi_msg *msg)
```

Compose msi message for a irq chip

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data
- `struct msi_msg *msg`: Pointer to the MSI message

**Description**

For hierarchical domains we find the first chip in the hierarchy
which implements the irq_compose_msi_msg callback. For non
hierarchical we use the top level chip.

#### <a id="c-irq_chip_pm_get"></a>`irq_chip_pm_get()`

```c
int irq_chip_pm_get(struct irq_data *data)
```

Enable power for an IRQ chip

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

**Description**

Enable the power to the IRQ chip referenced by the interrupt data
structure.

#### <a id="c-irq_chip_pm_put"></a>`irq_chip_pm_put()`

```c
void irq_chip_pm_put(struct irq_data *data)
```

Drop a PM reference on an IRQ chip

**Parameters**

- `struct irq_data *data`: Pointer to interrupt specific data

**Description**

Drop a power management reference, acquired via [`irq_chip_pm_get()`](#c-irq_chip_pm_get), on the IRQ
chip represented by the interrupt data structure.

Note that this will not disable power to the IRQ chip until this function
has been called for all IRQs that have called [`irq_chip_pm_get()`](#c-irq_chip_pm_get) and it may
not disable power at all (if user space prevents that, for example).


<a id="rst-credits"></a>

## Credits

The following people have contributed to this document:

1. Thomas Gleixner [tglx@kernel.org](<mailto:tglx@kernel.org>)

2. Ingo Molnar [mingo@elte.hu](<mailto:mingo@elte.hu>)

---

# GFP masks used from FS/IO context

_Peios Kernel / Internals / Core APIs_

> Code paths in the filesystem and IO stacks must be careful when allocating memory to prevent recursion deadlocks caused by direct memory reclaim calling back into the FS or IO paths and blocking on already held resources (e.g. locks - most…

<a id="rst-gfp-masks-used-from-fs-io-context"></a>
<a id="rst-gfp-mask-from-fs-io"></a>

**Date:** May, 2018

**Author:** Michal Hocko &lt;[mhocko@kernel.org](<mailto:mhocko@kernel.org>)&gt;

<a id="rst-introduction"></a>

## Introduction

Code paths in the filesystem and IO stacks must be careful when allocating memory to prevent recursion deadlocks caused by direct memory reclaim calling back into the FS or IO paths and blocking on already held resources (e.g. locks - most commonly those used for the transaction context).

The traditional way to avoid this deadlock problem is to clear \__GFP_FS respectively \__GFP_IO (note the latter implies clearing the first as well) in the gfp mask when calling an allocator. GFP_NOFS respectively GFP_NOIO can be used as shortcut. It turned out though that above approach has led to abuses when the restricted gfp mask is used "just in case" without a deeper consideration which leads to problems because an excessive use of GFP_NOFS/GFP_NOIO can lead to memory over-reclaim or other memory reclaim issues.

<a id="rst-new-api"></a>

## New API

Since 4.12 we do have a generic scope API for both NOFS and NOIO context `memalloc_nofs_save`, `memalloc_nofs_restore` respectively `memalloc_noio_save`, `memalloc_noio_restore` which allow to mark a scope to be a critical section from a filesystem or I/O point of view. Any allocation from that scope will inherently drop \__GFP_FS respectively \__GFP_IO from the given mask so no memory allocation can recurse back in the FS/IO.


#### <a id="c-memalloc_nofs_save"></a>`memalloc_nofs_save()`

```c
unsigned int memalloc_nofs_save(void)
```

Marks implicit GFP_NOFS allocation scope.

**Parameters**

- `void`: no arguments

**Description**

This functions marks the beginning of the GFP_NOFS allocation scope.
All further allocations will implicitly drop __GFP_FS flag and so
they are safe for the FS critical section from the allocation recursion
point of view. Use memalloc_nofs_restore to end the scope with flags
returned by this function.

**Context**

This function is safe to be used from any context.

**Return**

The saved flags to be passed to memalloc_nofs_restore.

#### <a id="c-memalloc_nofs_restore"></a>`memalloc_nofs_restore()`

```c
void memalloc_nofs_restore(unsigned int flags)
```

Ends the implicit GFP_NOFS scope.

**Parameters**

- `unsigned int flags`: Flags to restore.

**Description**

Ends the implicit GFP_NOFS scope started by memalloc_nofs_save function.
Always make sure that the given flags is the return value from the
pairing memalloc_nofs_save call.



#### <a id="c-memalloc_noio_save"></a>`memalloc_noio_save()`

```c
unsigned int memalloc_noio_save(void)
```

Marks implicit GFP_NOIO allocation scope.

**Parameters**

- `void`: no arguments

**Description**

This functions marks the beginning of the GFP_NOIO allocation scope.
All further allocations will implicitly drop __GFP_IO flag and so
they are safe for the IO critical section from the allocation recursion
point of view. Use memalloc_noio_restore to end the scope with flags
returned by this function.

**Context**

This function is safe to be used from any context.

**Return**

The saved flags to be passed to memalloc_noio_restore.

#### <a id="c-memalloc_noio_restore"></a>`memalloc_noio_restore()`

```c
void memalloc_noio_restore(unsigned int flags)
```

Ends the implicit GFP_NOIO scope.

**Parameters**

- `unsigned int flags`: Flags to restore.

**Description**

Ends the implicit GFP_NOIO scope started by memalloc_noio_save function.
Always make sure that the given flags is the return value from the
pairing memalloc_noio_save call.


FS/IO code then simply calls the appropriate save function before any critical section with respect to the reclaim is started - e.g. lock shared with the reclaim context or when a transaction context nesting would be possible via reclaim. The restore function should be called when the critical section ends. All that ideally along with an explanation what is the reclaim context for easier maintenance.

Please note that the proper pairing of save/restore functions allows nesting so it is safe to call `memalloc_noio_save` or `memalloc_noio_restore` respectively from an existing NOIO or NOFS scope.

<a id="rst-what-about-vmalloc-gfp-nofs"></a>

## What about \__vmalloc(GFP_NOFS)

Since v5.17, and specifically after the commit 451769ebb7e79 ("mm/vmalloc: alloc GFP_NO\{FS,IO\} for vmalloc"), GFP_NOFS/GFP_NOIO are now supported in `[k]vmalloc` by implicitly using scope API.

In earlier kernels `vmalloc` didn't support GFP_NOFS semantic because there were hardcoded GFP_KERNEL allocations deep inside the allocator. That means that calling `vmalloc` with GFP_NOFS/GFP_NOIO was almost always a bug.

In the ideal world, upper layers should already mark dangerous contexts and so no special care is required and `vmalloc` should be called without any problems. Sometimes if the context is not really clear or there are layering violations then the recommended way around that (on pre-v5.17 kernels) is to wrap `vmalloc` by the scope API with a comment explaining the problem.

---

# Housekeeping

_Peios Kernel / Internals / Core APIs_

> CPU Isolation moves away kernel work that may otherwise run on any CPU. The purpose of its related features is to reduce the OS jitter that some extreme workloads can't stand, such as in some DPDK usecases.

<a id="rst-housekeeping"></a>

CPU Isolation moves away kernel work that may otherwise run on any CPU. The purpose of its related features is to reduce the OS jitter that some extreme workloads can't stand, such as in some DPDK usecases.

The kernel work moved away by CPU isolation is commonly described as "housekeeping" because it includes ground work that performs cleanups, statistics maintainance and actions relying on them, memory release, various deferrals etc...

Sometimes housekeeping is just some unbound work (unbound workqueues, unbound timers, ...) that gets easily assigned to non-isolated CPUs. But sometimes housekeeping is tied to a specific CPU and requires elaborated tricks to be offloaded to non-isolated CPUs (RCU_NOCB, remote scheduler tick, etc...).

Thus, a housekeeping CPU can be considered as the reverse of an isolated CPU. It is simply a CPU that can execute housekeeping work. There must always be at least one online housekeeping CPU at any time. The CPUs that are not isolated are automatically assigned as housekeeping.

Housekeeping is currently divided in four features described by the `enum hk_type type`:

1. HK_TYPE_DOMAIN matches the work moved away by scheduler domain isolation performed through `isolcpus=domain` boot parameter or isolated cpuset partitions in cgroup v2. This includes scheduler load balancing, unbound workqueues and timers.

2. HK_TYPE_KERNEL_NOISE matches the work moved away by tick isolation performed through `nohz_full=` or `isolcpus=nohz` boot parameters. This includes remote scheduler tick, vmstat and lockup watchdog.

3. HK_TYPE_MANAGED_IRQ matches the IRQ handlers moved away by managed IRQ isolation performed through `isolcpus=managed_irq`.

4. HK_TYPE_DOMAIN_BOOT matches the work moved away by scheduler domain isolation performed through `isolcpus=domain` only. It is similar to HK_TYPE_DOMAIN except it ignores the isolation performed by cpusets.

<a id="rst-housekeeping-cpumasks"></a>

## Housekeeping cpumasks

Housekeeping cpumasks include the CPUs that can execute the work moved away by the matching isolation feature. These cpumasks are returned by the following function:



```text
const struct cpumask *housekeeping_cpumask(enum hk_type type)
```

By default, if neither `nohz_full=`, nor `isolcpus`, nor cpuset's isolated partitions are used, which covers most usecases, this function returns the cpu_possible_mask.

Otherwise the function returns the cpumask complement of the isolation feature. For example:

With isolcpus=domain,7 the following will return a mask with all possible CPUs except 7:



```text
housekeeping_cpumask(HK_TYPE_DOMAIN)
```

Similarly with nohz_full=5,6 the following will return a mask with all possible CPUs except 5,6:



```text
housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)
```

<a id="rst-synchronization-against-cpusets"></a>

## Synchronization against cpusets

Cpuset can modify the HK_TYPE_DOMAIN housekeeping cpumask while creating, modifying or deleting an isolated partition.

The users of HK_TYPE_DOMAIN cpumask must then make sure to synchronize properly against cpuset in order to make sure that:

1. The cpumask snapshot stays coherent.

2. No housekeeping work is queued on a newly made isolated CPU.

3. Pending housekeeping work that was queued to a non isolated CPU which just turned isolated through cpuset must be flushed before the related created/modified isolated partition is made available to userspace.

This synchronization is maintained by an RCU based scheme. The cpuset update side waits for an RCU grace period after updating the HK_TYPE_DOMAIN cpumask and before flushing pending works. On the read side, care must be taken to gather the housekeeping target election and the work enqueue within the same RCU read side critical section.

A typical layout example would look like this on the update side (`housekeeping_update()`):



```text
rcu_assign_pointer(housekeeping_cpumasks[type], trial);
synchronize_rcu();
flush_workqueue(example_workqueue);
```

And then on the read side:



```text
rcu_read_lock();
cpu = housekeeping_any_cpu(HK_TYPE_DOMAIN);
queue_work_on(cpu, example_workqueue, work);
rcu_read_unlock();
```

---

# ID Allocation

_Peios Kernel / Internals / Core APIs_

> A common problem to solve is allocating identifiers (IDs); generally small numbers which identify a thing. Examples include file descriptors, process IDs, packet identifiers in networking protocols, SCSI tags and device instance numbers.…

<a id="rst-id-allocation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** Matthew Wilcox

<a id="rst-overview"></a>

## Overview

A common problem to solve is allocating identifiers (IDs); generally small numbers which identify a thing.  Examples include file descriptors, process IDs, packet identifiers in networking protocols, SCSI tags and device instance numbers.  The IDR and the IDA provide a reasonable solution to the problem to avoid everybody inventing their own.  The IDR provides the ability to map an ID to a pointer, while the IDA provides only ID allocation, and as a result is much more memory-efficient.

The IDR interface is deprecated; please use the [XArray](</kernel/internals/core-api/xarray.md>) instead.

<a id="rst-idr-usage"></a>

## IDR usage

Start by initialising an IDR, either with DEFINE_IDR() for statically allocated IDRs or idr_init() for dynamically allocated IDRs.

You can call idr_alloc() to allocate an unused ID.  Look up the pointer you associated with the ID by calling idr_find() and free the ID by calling idr_remove().

If you need to change the pointer associated with an ID, you can call idr_replace().  One common reason to do this is to reserve an ID by passing a `NULL` pointer to the allocation function; initialise the object with the reserved ID and finally insert the initialised object into the IDR.

Some users need to allocate IDs larger than `INT_MAX`.  So far all of these users have been content with a `UINT_MAX` limit, and they use idr_alloc_u32().  If you need IDs that will not fit in a u32, we will work with you to address your needs.

If you need to allocate IDs sequentially, you can use idr_alloc_cyclic().  The IDR becomes less efficient when dealing with larger IDs, so using this function comes at a slight cost.

To perform an action on all pointers used by the IDR, you can either use the callback-based idr_for_each() or the iterator-style idr_for_each_entry().  You may need to use idr_for_each_entry_continue() to continue an iteration.  You can also use idr_get_next() if the iterator doesn't fit your needs.

When you have finished using an IDR, you can call idr_destroy() to release the memory used by the IDR.  This will not free the objects pointed to from the IDR; if you want to do that, use one of the iterators to do it.

You can use idr_is_empty() to find out whether there are any IDs currently allocated.

If you need to take a lock while allocating a new ID from the IDR, you may need to pass a restrictive set of GFP flags, which can lead to the IDR being unable to allocate memory.  To work around this, you can call idr_preload() before taking the lock, and then idr_preload_end() after the allocation.


idr synchronization (stolen from radix-tree.h)

[`idr_find()`](#c-idr_find) is able to be called locklessly, using RCU. The caller must
ensure calls to this function are made within [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) regions.
Other readers (lock-free or otherwise) and modifications may be running
concurrently.

It is still required that the caller manage the synchronization and
lifetimes of the items. So if RCU lock-free lookups are used, typically
this would mean that the items have their own locks, or are amenable to
lock-free access; and that the items are freed by RCU (or only freed after
having been deleted from the idr tree *and* a [`synchronize_rcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_rcu) grace
period).


<a id="rst-ida-usage"></a>

## IDA usage


The IDA is an ID allocator which does not provide the ability to
associate an ID with a pointer.  As such, it only needs to store one
bit per ID, and so is more space efficient than an IDR.  To use an IDA,
define it using `DEFINE_IDA()` (or embed a `struct ida` in a data structure,
then initialise it using `ida_init()`).  To allocate a new ID, call
[`ida_alloc()`](#c-ida_alloc), [`ida_alloc_min()`](#c-ida_alloc_min), [`ida_alloc_max()`](#c-ida_alloc_max) or [`ida_alloc_range()`](#c-ida_alloc_range).
To free an ID, call [`ida_free()`](#c-ida_free).

[`ida_destroy()`](#c-ida_destroy) can be used to dispose of an IDA without needing to
free the individual IDs in it.  You can use `ida_is_empty()` to find
out whether the IDA has any IDs currently allocated.

The IDA handles its own locking.  It is safe to call any of the IDA
functions without synchronisation in your code.

IDs are currently limited to the range \[0-INT_MAX\].  If this is an awkward
limitation, it should be quite straightforward to raise the maximum.


<a id="rst-functions-and-structures"></a>

## Functions and structures


#### <a id="c-IDR_INIT"></a>`IDR_INIT()`

```c
IDR_INIT(name)
```

Initialise an IDR.

**Parameters**

- `name`: Name of IDR.

**Description**

A freshly-initialised IDR contains no IDs.

#### <a id="c-DEFINE_IDR"></a>`DEFINE_IDR()`

```c
DEFINE_IDR(name)
```

Define a statically-allocated IDR.

**Parameters**

- `name`: Name of IDR.

**Description**

An IDR defined using this macro is ready for use with no additional
initialisation required.  It contains no IDs.

#### <a id="c-idr_get_cursor"></a>`idr_get_cursor()`

```c
unsigned int idr_get_cursor(const struct idr *idr)
```

Return the current position of the cyclic allocator

**Parameters**

- `const struct idr *idr`: idr handle

**Description**

The value returned is the value that will be next returned from
[`idr_alloc_cyclic()`](#c-idr_alloc_cyclic) if it is free (otherwise the search will start from
this position).

#### <a id="c-idr_set_cursor"></a>`idr_set_cursor()`

```c
void idr_set_cursor(struct idr *idr, unsigned int val)
```

Set the current position of the cyclic allocator

**Parameters**

- `struct idr *idr`: idr handle
- `unsigned int val`: new position

**Description**

The next call to [`idr_alloc_cyclic()`](#c-idr_alloc_cyclic) will return **val** if it is free
(otherwise the search will start from this position).

#### <a id="c-idr_init_base"></a>`idr_init_base()`

```c
void idr_init_base(struct idr *idr, int base)
```

Initialise an IDR.

**Parameters**

- `struct idr *idr`: IDR handle.
- `int base`: The base value for the IDR.

**Description**

This variation of [`idr_init()`](#c-idr_init) creates an IDR which will allocate IDs
starting at `base`.

#### <a id="c-idr_init"></a>`idr_init()`

```c
void idr_init(struct idr *idr)
```

Initialise an IDR.

**Parameters**

- `struct idr *idr`: IDR handle.

**Description**

Initialise a dynamically allocated IDR.  To initialise a
statically allocated IDR, use [`DEFINE_IDR()`](#c-DEFINE_IDR).

#### <a id="c-idr_is_empty"></a>`idr_is_empty()`

```c
bool idr_is_empty(const struct idr *idr)
```

Are there any IDs allocated?

**Parameters**

- `const struct idr *idr`: IDR handle.

**Return**

`true` if any IDs have been allocated from this IDR.

#### <a id="c-idr_preload_end"></a>`idr_preload_end()`

```c
void idr_preload_end(void)
```

end preload section started with `idr_preload()`

**Parameters**

- `void`: no arguments

**Description**

Each `idr_preload()` should be matched with an invocation of this
function.  See `idr_preload()` for details.

#### <a id="c-idr_for_each_entry"></a>`idr_for_each_entry()`

```c
idr_for_each_entry(idr, entry, id)
```

Iterate over an IDR's elements of a given type.

**Parameters**

- `idr`: IDR handle.
- `entry`: The type * to use as cursor
- `id`: Entry ID.

**Description**

**entry** and **id** do not need to be initialized before the loop, and
after normal termination **entry** is left with the value NULL.  This
is convenient for a "not found" value.

#### <a id="c-idr_for_each_entry_ul"></a>`idr_for_each_entry_ul()`

```c
idr_for_each_entry_ul(idr, entry, tmp, id)
```

Iterate over an IDR's elements of a given type.

**Parameters**

- `idr`: IDR handle.
- `entry`: The type * to use as cursor.
- `tmp`: A temporary placeholder for ID.
- `id`: Entry ID.

**Description**

**entry** and **id** do not need to be initialized before the loop, and
after normal termination **entry** is left with the value NULL.  This
is convenient for a "not found" value.

#### <a id="c-idr_for_each_entry_continue"></a>`idr_for_each_entry_continue()`

```c
idr_for_each_entry_continue(idr, entry, id)
```

Continue iteration over an IDR's elements of a given type

**Parameters**

- `idr`: IDR handle.
- `entry`: The type * to use as a cursor.
- `id`: Entry ID.

**Description**

Continue to iterate over entries, continuing after the current position.

#### <a id="c-idr_for_each_entry_continue_ul"></a>`idr_for_each_entry_continue_ul()`

```c
idr_for_each_entry_continue_ul(idr, entry, tmp, id)
```

Continue iteration over an IDR's elements of a given type

**Parameters**

- `idr`: IDR handle.
- `entry`: The type * to use as a cursor.
- `tmp`: A temporary placeholder for ID.
- `id`: Entry ID.

**Description**

Continue to iterate over entries, continuing after the current position.
After normal termination **entry** is left with the value NULL.  This
is convenient for a "not found" value.

#### <a id="c-ida_alloc"></a>`ida_alloc()`

```c
int ida_alloc(struct ida *ida, gfp_t gfp)
```

Allocate an unused ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocate an ID between 0 and `INT_MAX`, inclusive.

**Context**

Any context. It is safe to call this function without
locking in your code.

**Return**

The allocated ID, or `-ENOMEM` if memory could not be allocated,
or `-ENOSPC` if there are no free IDs.

#### <a id="c-ida_alloc_min"></a>`ida_alloc_min()`

```c
int ida_alloc_min(struct ida *ida, unsigned int min, gfp_t gfp)
```

Allocate an unused ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `unsigned int min`: Lowest ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocate an ID between **min** and `INT_MAX`, inclusive.

**Context**

Any context. It is safe to call this function without
locking in your code.

**Return**

The allocated ID, or `-ENOMEM` if memory could not be allocated,
or `-ENOSPC` if there are no free IDs.

#### <a id="c-ida_alloc_max"></a>`ida_alloc_max()`

```c
int ida_alloc_max(struct ida *ida, unsigned int max, gfp_t gfp)
```

Allocate an unused ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `unsigned int max`: Highest ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocate an ID between 0 and **max**, inclusive.

**Context**

Any context. It is safe to call this function without
locking in your code.

**Return**

The allocated ID, or `-ENOMEM` if memory could not be allocated,
or `-ENOSPC` if there are no free IDs.



#### <a id="c-idr_alloc_u32"></a>`idr_alloc_u32()`

```c
int idr_alloc_u32(struct idr *idr, void *ptr, u32 *nextid, unsigned long max, gfp_t gfp)
```

Allocate an ID.

**Parameters**

- `struct idr *idr`: IDR handle.
- `void *ptr`: Pointer to be associated with the new ID.
- `u32 *nextid`: Pointer to an ID.
- `unsigned long max`: The maximum ID to allocate (inclusive).
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocates an unused ID in the range specified by **nextid** and **max**.
Note that **max** is inclusive whereas the **end** parameter to [`idr_alloc()`](#c-idr_alloc)
is exclusive.  The new ID is assigned to **nextid** before the pointer
is inserted into the IDR, so if **nextid** points into the object pointed
to by **ptr**, a concurrent lookup will not find an uninitialised ID.

The caller should provide their own locking to ensure that two
concurrent modifications to the IDR are not possible.  Read-only
accesses to the IDR may be done under the RCU read lock or may
exclude simultaneous writers.

**Return**

0 if an ID was allocated, -ENOMEM if memory allocation failed,
or -ENOSPC if no free IDs could be found.  If an error occurred,
**nextid** is unchanged.

#### <a id="c-idr_alloc"></a>`idr_alloc()`

```c
int idr_alloc(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
```

Allocate an ID.

**Parameters**

- `struct idr *idr`: IDR handle.
- `void *ptr`: Pointer to be associated with the new ID.
- `int start`: The minimum ID (inclusive).
- `int end`: The maximum ID (exclusive).
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocates an unused ID in the range specified by **start** and **end**.  If
**end** is \<= 0, it is treated as one larger than `INT_MAX`.  This allows
callers to use **start** + N as **end** as long as N is within integer range.

The caller should provide their own locking to ensure that two
concurrent modifications to the IDR are not possible.  Read-only
accesses to the IDR may be done under the RCU read lock or may
exclude simultaneous writers.

**Return**

The newly allocated ID, -ENOMEM if memory allocation failed,
or -ENOSPC if no free IDs could be found.

#### <a id="c-idr_alloc_cyclic"></a>`idr_alloc_cyclic()`

```c
int idr_alloc_cyclic(struct idr *idr, void *ptr, int start, int end, gfp_t gfp)
```

Allocate an ID cyclically.

**Parameters**

- `struct idr *idr`: IDR handle.
- `void *ptr`: Pointer to be associated with the new ID.
- `int start`: The minimum ID (inclusive).
- `int end`: The maximum ID (exclusive).
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocates an unused ID in the range specified by **start** and **end**.  If
**end** is \<= 0, it is treated as one larger than `INT_MAX`.  This allows
callers to use **start** + N as **end** as long as N is within integer range.
The search for an unused ID will start at the last ID allocated and will
wrap around to **start** if no free IDs are found before reaching **end**.

The caller should provide their own locking to ensure that two
concurrent modifications to the IDR are not possible.  Read-only
accesses to the IDR may be done under the RCU read lock or may
exclude simultaneous writers.

**Return**

The newly allocated ID, -ENOMEM if memory allocation failed,
or -ENOSPC if no free IDs could be found.

#### <a id="c-idr_remove"></a>`idr_remove()`

```c
void * idr_remove(struct idr *idr, unsigned long id)
```

Remove an ID from the IDR.

**Parameters**

- `struct idr *idr`: IDR handle.
- `unsigned long id`: Pointer ID.

**Description**

Removes this ID from the IDR.  If the ID was not previously in the IDR,
this function returns `NULL`.

Since this function modifies the IDR, the caller should provide their
own locking to ensure that concurrent modification of the same IDR is
not possible.

**Return**

The pointer formerly associated with this ID.

#### <a id="c-idr_find"></a>`idr_find()`

```c
void * idr_find(const struct idr *idr, unsigned long id)
```

Return pointer for given ID.

**Parameters**

- `const struct idr *idr`: IDR handle.
- `unsigned long id`: Pointer ID.

**Description**

Looks up the pointer associated with this ID.  A `NULL` pointer may
indicate that **id** is not allocated or that the `NULL` pointer was
associated with this ID.

This function can be called under [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock), given that the leaf
pointers lifetimes are correctly managed.

**Return**

The pointer associated with this ID.

#### <a id="c-idr_for_each"></a>`idr_for_each()`

```c
int idr_for_each(const struct idr *idr, int (*fn)(int id, void *p, void *data), void *data)
```

Iterate through all stored pointers.

**Parameters**

- `const struct idr *idr`: IDR handle.
- `int (*fn)(int id, void *p, void *data)`: Function to be called for each pointer.
- `void *data`: Data passed to callback function.

**Description**

The callback function will be called for each entry in **idr**, passing
the ID, the entry and **data**.

If **fn** returns anything other than `0`, the iteration stops and that
value is returned from this function.

[`idr_for_each()`](#c-idr_for_each) can be called concurrently with [`idr_alloc()`](#c-idr_alloc) and
[`idr_remove()`](#c-idr_remove) if protected by RCU.  Newly added entries may not be
seen and deleted entries may be seen, but adding and removing entries
will not cause other entries to be skipped, nor spurious ones to be seen.

#### <a id="c-idr_get_next_ul"></a>`idr_get_next_ul()`

```c
void * idr_get_next_ul(struct idr *idr, unsigned long *nextid)
```

Find next populated entry.

**Parameters**

- `struct idr *idr`: IDR handle.
- `unsigned long *nextid`: Pointer to an ID.

**Description**

Returns the next populated entry in the tree with an ID greater than
or equal to the value pointed to by **nextid**.  On exit, **nextid** is updated
to the ID of the found value.  To use in a loop, the value pointed to by
nextid must be incremented by the user.

#### <a id="c-idr_get_next"></a>`idr_get_next()`

```c
void * idr_get_next(struct idr *idr, int *nextid)
```

Find next populated entry.

**Parameters**

- `struct idr *idr`: IDR handle.
- `int *nextid`: Pointer to an ID.

**Description**

Returns the next populated entry in the tree with an ID greater than
or equal to the value pointed to by **nextid**.  On exit, **nextid** is updated
to the ID of the found value.  To use in a loop, the value pointed to by
nextid must be incremented by the user.

#### <a id="c-idr_replace"></a>`idr_replace()`

```c
void * idr_replace(struct idr *idr, void *ptr, unsigned long id)
```

replace pointer for given ID.

**Parameters**

- `struct idr *idr`: IDR handle.
- `void *ptr`: New pointer to associate with the ID.
- `unsigned long id`: ID to change.

**Description**

Replace the pointer registered with an ID and return the old value.
This function can be called under the RCU read lock concurrently with
[`idr_alloc()`](#c-idr_alloc) and [`idr_remove()`](#c-idr_remove) (as long as the ID being removed is not
the one being replaced!).

**Return**

the old value on success.  `-ENOENT` indicates that **id** was not
found.  `-EINVAL` indicates that **ptr** was not valid.

#### <a id="c-ida_alloc_range"></a>`ida_alloc_range()`

```c
int ida_alloc_range(struct ida *ida, unsigned int min, unsigned int max, gfp_t gfp)
```

Allocate an unused ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `unsigned int min`: Lowest ID to allocate.
- `unsigned int max`: Highest ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Allocate an ID between **min** and **max**, inclusive.  The allocated ID will
not exceed `INT_MAX`, even if **max** is larger.

**Context**

Any context. It is safe to call this function without
locking in your code.

**Return**

The allocated ID, or `-ENOMEM` if memory could not be allocated,
or `-ENOSPC` if there are no free IDs.

#### <a id="c-ida_find_first_range"></a>`ida_find_first_range()`

```c
int ida_find_first_range(struct ida *ida, unsigned int min, unsigned int max)
```

Get the lowest used ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `unsigned int min`: Lowest ID to get.
- `unsigned int max`: Highest ID to get.

**Description**

Get the lowest used ID between **min** and **max**, inclusive.  The returned
ID will not exceed `INT_MAX`, even if **max** is larger.

**Context**

Any context. Takes and releases the xa_lock.

**Return**

The lowest used ID, or errno if no used ID is found.

#### <a id="c-ida_free"></a>`ida_free()`

```c
void ida_free(struct ida *ida, unsigned int id)
```

Release an allocated ID.

**Parameters**

- `struct ida *ida`: IDA handle.
- `unsigned int id`: Previously allocated ID.

**Context**

Any context. It is safe to call this function without
locking in your code.

#### <a id="c-ida_destroy"></a>`ida_destroy()`

```c
void ida_destroy(struct ida *ida)
```

Free all IDs.

**Parameters**

- `struct ida *ida`: IDA handle.

**Description**

Calling this function frees all IDs and releases all resources used
by an IDA.  When this call returns, the IDA is empty and can be reused
or freed.  If the IDA is already empty, there is no need to call this
function.

**Context**

Any context. It is safe to call this function without
locking in your code.

---

# The Linux Kernel API

_Peios Kernel / Internals / Core APIs_

> When writing drivers, you cannot in general use routines which are from the C Library. Some of the functions have been found generally useful and they are listed below. The behaviour of these functions may vary slightly from those defined…

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-the-linux-kernel-api"></a>

<a id="rst-basic-c-library-functions"></a>

## Basic C Library Functions

When writing drivers, you cannot in general use routines which are from the C Library. Some of the functions have been found generally useful and they are listed below. The behaviour of these functions may vary slightly from those defined by ANSI, and these deviations are noted in the text.

<a id="rst-string-conversions"></a>

### String Conversions


#### <a id="c-simple_strtoull"></a>`simple_strtoull()`

```c
unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
```

convert a string to an unsigned long long

**Parameters**

- `const char *cp`: The start of the string
- `char **endp`: A pointer to the end of the parsed string will be placed here
- `unsigned int base`: The number base to use

**Description**

This function has caveats. Please use kstrtoull instead.

#### <a id="c-simple_strtoul"></a>`simple_strtoul()`

```c
unsigned long simple_strtoul(const char *cp, char **endp, unsigned int base)
```

convert a string to an unsigned long

**Parameters**

- `const char *cp`: The start of the string
- `char **endp`: A pointer to the end of the parsed string will be placed here
- `unsigned int base`: The number base to use

**Description**

This function has caveats. Please use kstrtoul instead.

#### <a id="c-simple_strtol"></a>`simple_strtol()`

```c
long simple_strtol(const char *cp, char **endp, unsigned int base)
```

convert a string to a signed long

**Parameters**

- `const char *cp`: The start of the string
- `char **endp`: A pointer to the end of the parsed string will be placed here
- `unsigned int base`: The number base to use

**Description**

This function has caveats. Please use kstrtol instead.

#### <a id="c-simple_strtoll"></a>`simple_strtoll()`

```c
long long simple_strtoll(const char *cp, char **endp, unsigned int base)
```

convert a string to a signed long long

**Parameters**

- `const char *cp`: The start of the string
- `char **endp`: A pointer to the end of the parsed string will be placed here
- `unsigned int base`: The number base to use

**Description**

This function has caveats. Please use kstrtoll instead.

#### <a id="c-vsnprintf"></a>`vsnprintf()`

```c
int vsnprintf(char *buf, size_t size, const char *fmt_str, va_list args)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `size_t size`: The size of the buffer, including the trailing null space
- `const char *fmt_str`: The format string to use
- `va_list args`: Arguments for the format string

**Description**

This function generally follows C99 vsnprintf, but has some
extensions and a few limitations:

- `%n` is unsupported
- `%p*` is handled by `pointer()`

See `pointer()` or Documentation/core-api/printk-formats.rst for more
extensive description.

**Please update the documentation in both places when making changes**

The return value is the number of characters which would
be generated for the given input, excluding the trailing
'\0', as per ISO C99. If you want to have the exact
number of characters written into **buf** as return value
(not including the trailing '\0'), use [`vscnprintf()`](#c-vscnprintf). If the
return is greater than or equal to **size**, the resulting
string is truncated.

If you're not already dealing with a va_list consider using [`snprintf()`](#c-snprintf).

#### <a id="c-vscnprintf"></a>`vscnprintf()`

```c
int vscnprintf(char *buf, size_t size, const char *fmt, va_list args)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `size_t size`: The size of the buffer, including the trailing null space
- `const char *fmt`: The format string to use
- `va_list args`: Arguments for the format string

**Description**

The return value is the number of characters which have been written into
the **buf** not including the trailing '\0'. If **size** is == 0 the function
returns 0.

If you're not already dealing with a va_list consider using [`scnprintf()`](#c-scnprintf).

See the [`vsnprintf()`](#c-vsnprintf) documentation for format string extensions over C99.

#### <a id="c-snprintf"></a>`snprintf()`

```c
int snprintf(char *buf, size_t size, const char *fmt, ...)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `size_t size`: The size of the buffer, including the trailing null space
- `const char *fmt`: The format string to use
- `...`: Arguments for the format string

**Description**

The return value is the number of characters which would be
generated for the given input, excluding the trailing null,
as per ISO C99.  If the return is greater than or equal to
**size**, the resulting string is truncated.

See the [`vsnprintf()`](#c-vsnprintf) documentation for format string extensions over C99.

#### <a id="c-scnprintf"></a>`scnprintf()`

```c
int scnprintf(char *buf, size_t size, const char *fmt, ...)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `size_t size`: The size of the buffer, including the trailing null space
- `const char *fmt`: The format string to use
- `...`: Arguments for the format string

**Description**

The return value is the number of characters written into **buf** not including
the trailing '\0'. If **size** is == 0 the function returns 0.

#### <a id="c-vsprintf"></a>`vsprintf()`

```c
int vsprintf(char *buf, const char *fmt, va_list args)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `const char *fmt`: The format string to use
- `va_list args`: Arguments for the format string

**Description**

The return value is the number of characters written into **buf** not including
the trailing '\0'. Use [`vsnprintf()`](#c-vsnprintf) or [`vscnprintf()`](#c-vscnprintf) in order to avoid
buffer overflows.

If you're not already dealing with a va_list consider using [`sprintf()`](#c-sprintf).

See the [`vsnprintf()`](#c-vsnprintf) documentation for format string extensions over C99.

#### <a id="c-sprintf"></a>`sprintf()`

```c
int sprintf(char *buf, const char *fmt, ...)
```

Format a string and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `const char *fmt`: The format string to use
- `...`: Arguments for the format string

**Description**

The return value is the number of characters written into **buf** not including
the trailing '\0'. Use [`snprintf()`](#c-snprintf) or [`scnprintf()`](#c-scnprintf) in order to avoid
buffer overflows.

See the [`vsnprintf()`](#c-vsnprintf) documentation for format string extensions over C99.

#### <a id="c-vbin_printf"></a>`vbin_printf()`

```c
int vbin_printf(u32 *bin_buf, size_t size, const char *fmt_str, va_list args)
```

Parse a format string and place args' binary value in a buffer

**Parameters**

- `u32 *bin_buf`: The buffer to place args' binary value
- `size_t size`: The size of the buffer(by words(32bits), not characters)
- `const char *fmt_str`: The format string to use
- `va_list args`: Arguments for the format string

**Description**

The format follows C99 vsnprintf, except `n` is ignored, and its argument
is skipped.

The return value is the number of words(32bits) which would be generated for
the given input.

**NOTE**

If the return value is greater than **size**, the resulting bin_buf is NOT
valid for [`bstr_printf()`](#c-bstr_printf).

#### <a id="c-bstr_printf"></a>`bstr_printf()`

```c
int bstr_printf(char *buf, size_t size, const char *fmt_str, const u32 *bin_buf)
```

Format a string from binary arguments and place it in a buffer

**Parameters**

- `char *buf`: The buffer to place the result into
- `size_t size`: The size of the buffer, including the trailing null space
- `const char *fmt_str`: The format string to use
- `const u32 *bin_buf`: Binary arguments for the format string

**Description**

This function like C99 vsnprintf, but the difference is that vsnprintf gets
arguments from stack, and bstr_printf gets arguments from **bin_buf** which is
a binary buffer that generated by vbin_printf.

- The format follows C99 vsnprintf, but has some extensions:
  see vsnprintf comment for details.

The return value is the number of characters which would
be generated for the given input, excluding the trailing
'\0', as per ISO C99. If you want to have the exact
number of characters written into **buf** as return value
(not including the trailing '\0'), use [`vscnprintf()`](#c-vscnprintf). If the
return is greater than or equal to **size**, the resulting
string is truncated.

#### <a id="c-vsscanf"></a>`vsscanf()`

```c
int vsscanf(const char *buf, const char *fmt, va_list args)
```

Unformat a buffer into a list of arguments

**Parameters**

- `const char *buf`: input buffer
- `const char *fmt`: format of buffer
- `va_list args`: arguments

#### <a id="c-sscanf"></a>`sscanf()`

```c
int sscanf(const char *buf, const char *fmt, ...)
```

Unformat a buffer into a list of arguments

**Parameters**

- `const char *buf`: input buffer
- `const char *fmt`: formatting of buffer
- `...`: resulting arguments



#### <a id="c-kstrtoul"></a>`kstrtoul()`

```c
int kstrtoul(const char *s, unsigned int base, unsigned long *res)
```

convert a string to an unsigned long

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign, but not a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `unsigned long *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtoul()`](#c-simple_strtoul). Return code must be checked.

#### <a id="c-kstrtol"></a>`kstrtol()`

```c
int kstrtol(const char *s, unsigned int base, long *res)
```

convert a string to a long

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign or a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `long *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtol()`](#c-simple_strtol). Return code must be checked.



#### <a id="c-kstrtoull"></a>`kstrtoull()`

```c
int kstrtoull(const char *s, unsigned int base, unsigned long long *res)
```

convert a string to an unsigned long long

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign, but not a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `unsigned long long *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtoull()`](#c-simple_strtoull). Return code must be checked.

#### <a id="c-kstrtoll"></a>`kstrtoll()`

```c
int kstrtoll(const char *s, unsigned int base, long long *res)
```

convert a string to a long long

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign or a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `long long *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtoll()`](#c-simple_strtoll). Return code must be checked.

#### <a id="c-kstrtouint"></a>`kstrtouint()`

```c
int kstrtouint(const char *s, unsigned int base, unsigned int *res)
```

convert a string to an unsigned int

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign, but not a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `unsigned int *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtoul()`](#c-simple_strtoul). Return code must be checked.

#### <a id="c-kstrtoint"></a>`kstrtoint()`

```c
int kstrtoint(const char *s, unsigned int base, int *res)
```

convert a string to an int

**Parameters**

- `const char *s`: The start of the string. The string must be null-terminated, and may also
  include a single newline before its terminating null. The first character
  may also be a plus sign or a minus sign.
- `unsigned int base`: The number base to use. The maximum supported base is 16. If base is
  given as 0, then the base of the string is automatically detected with the
  conventional semantics - If it begins with 0x the number will be parsed as a
  hexadecimal (case insensitive), if it otherwise begins with 0, it will be
  parsed as an octal number. Otherwise it will be parsed as a decimal.
- `int *res`: Where to write the result of the conversion on success.

**Description**

Returns 0 on success, -ERANGE on overflow and -EINVAL on parsing error.
Preferred over [`simple_strtol()`](#c-simple_strtol). Return code must be checked.

#### <a id="c-kstrtobool"></a>`kstrtobool()`

```c
int kstrtobool(const char *s, bool *res)
```

convert common user inputs into boolean values

**Parameters**

- `const char *s`: input string
- `bool *res`: result

**Description**

This routine returns 0 iff the first character is one of 'EeYyTt1DdNnFf0',
or \[oO\]\[NnFf\] for "on" and "off". Otherwise it will return -EINVAL.  Value
pointed to by res is updated upon finding a match.



#### <a id="c-string_get_size"></a>`string_get_size()`

```c
int string_get_size(u64 size, u64 blk_size, const enum string_size_units units, char *buf, int len)
```

get the size in the specified units

**Parameters**

- `u64 size`: The size to be converted in blocks
- `u64 blk_size`: Size of the block (use 1 for size in bytes)
- `const enum string_size_units units`: Units to use (powers of 1000 or 1024), whether to include space separator
- `char *buf`: buffer to format to
- `int len`: length of buffer

**Description**

This function returns a string formatted to 3 significant figures
giving the size in the required units.  **buf** should have room for
at least 9 bytes and will always be zero terminated.

Return value: number of characters of output that would have been written
(which may be greater than len, if output was truncated).

#### <a id="c-parse_int_array_user"></a>`parse_int_array_user()`

```c
int parse_int_array_user(const char __user *from, size_t count, int **array)
```

Split string into a sequence of integers

**Parameters**

- `const char __user *from`: The user space buffer to read from
- `size_t count`: The maximum number of bytes to read
- `int **array`: Returned pointer to sequence of integers

**Description**

On success **array** is allocated and initialized with a sequence of
integers extracted from the **from** plus an additional element that
begins the sequence and specifies the integers count.

Caller takes responsibility for freeing **array** when it is no longer
needed.

#### <a id="c-string_unescape"></a>`string_unescape()`

```c
int string_unescape(char *src, char *dst, size_t size, unsigned int flags)
```

unquote characters in the given string

**Parameters**

- `char *src`: source buffer (escaped)
- `char *dst`: destination buffer (unescaped)
- `size_t size`: size of the destination buffer (0 to unlimit)
- `unsigned int flags`: combination of the flags.

**Description**

The function unquotes characters in the given string.

Because the size of the output will be the same as or less than the size of
the input, the transformation may be performed in place.

Caller must provide valid source and destination pointers. Be aware that
destination buffer will always be NULL-terminated. Source string must be
NULL-terminated as well.  The supported flags are:

```text
UNESCAPE_SPACE:
        '\f' - form feed
        '\n' - new line
        '\r' - carriage return
        '\t' - horizontal tab
        '\v' - vertical tab
UNESCAPE_OCTAL:
        '\NNN' - byte with octal value NNN (1 to 3 digits)
UNESCAPE_HEX:
        '\xHH' - byte with hexadecimal value HH (1 to 2 digits)
UNESCAPE_SPECIAL:
        '\"' - double quote
        '\\' - backslash
        '\a' - alert (BEL)
        '\e' - escape
UNESCAPE_ANY:
        all previous together
```

**Return**

The amount of the characters processed to the destination buffer excluding
trailing '\0' is returned.

#### <a id="c-string_escape_mem"></a>`string_escape_mem()`

```c
int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz, unsigned int flags, const char *only)
```

quote characters in the given memory buffer

**Parameters**

- `const char *src`: source buffer (unescaped)
- `size_t isz`: source buffer size
- `char *dst`: destination buffer (escaped)
- `size_t osz`: destination buffer size
- `unsigned int flags`: combination of the flags
- `const char *only`: NULL-terminated string containing characters used to limit
  the selected escape class. If characters are included in **only**
  that would not normally be escaped by the classes selected
  in **flags**, they will be copied to **dst** unescaped.

**Description**

The process of escaping byte buffer includes several parts. They are applied
in the following sequence.

1. The character is not matched to the one from **only** string and thus
   must go as-is to the output.
2. The character is matched to the printable and ASCII classes, if asked,
   and in case of match it passes through to the output.
3. The character is matched to the printable or ASCII class, if asked,
   and in case of match it passes through to the output.
4. The character is checked if it falls into the class given by **flags**.
   `ESCAPE_OCTAL` and `ESCAPE_HEX` are going last since they cover any
   character. Note that they actually can't go together, otherwise
   `ESCAPE_HEX` will be ignored.

Caller must provide valid source and destination pointers. Be aware that
destination buffer will not be NULL-terminated, thus caller have to append
it if needs. The supported flags are:

```text
%ESCAPE_SPACE: (special white space, not space itself)
        '\f' - form feed
        '\n' - new line
        '\r' - carriage return
        '\t' - horizontal tab
        '\v' - vertical tab
%ESCAPE_SPECIAL:
        '\"' - double quote
        '\\' - backslash
        '\a' - alert (BEL)
        '\e' - escape
%ESCAPE_NULL:
        '\0' - null
%ESCAPE_OCTAL:
        '\NNN' - byte with octal value NNN (3 digits)
%ESCAPE_ANY:
        all previous together
%ESCAPE_NP:
        escape only non-printable characters, checked by isprint()
%ESCAPE_ANY_NP:
        all previous together
%ESCAPE_HEX:
        '\xHH' - byte with hexadecimal value HH (2 digits)
%ESCAPE_NA:
        escape only non-ascii characters, checked by isascii()
%ESCAPE_NAP:
        escape only non-printable or non-ascii characters
%ESCAPE_APPEND:
        append characters from @only to be escaped by the given classes
```

`ESCAPE_APPEND` would help to pass additional characters to the escaped, when
one of `ESCAPE_NP`, `ESCAPE_NA`, or `ESCAPE_NAP` is provided.

One notable caveat, the `ESCAPE_NAP`, `ESCAPE_NP` and `ESCAPE_NA` have the
higher priority than the rest of the flags (`ESCAPE_NAP` is the highest).
It doesn't make much sense to use either of them without `ESCAPE_OCTAL`
or `ESCAPE_HEX`, because they cover most of the other character classes.
`ESCAPE_NAP` can utilize `ESCAPE_SPACE` or `ESCAPE_SPECIAL` in addition to
the above.

**Return**

The total size of the escaped output that would be generated for
the given input and flags. To check whether the output was
truncated, compare the return value to osz. There is room left in
dst for a '\0' terminator if and only if ret \< osz.

#### <a id="c-kasprintf_strarray"></a>`kasprintf_strarray()`

```c
char ** kasprintf_strarray(gfp_t gfp, const char *prefix, size_t n)
```

allocate and fill array of sequential strings

**Parameters**

- `gfp_t gfp`: flags for the slab allocator
- `const char *prefix`: prefix to be used
- `size_t n`: amount of lines to be allocated and filled

**Description**

Allocates and fills **n** strings using pattern "`s-``zu`", where prefix
is provided by caller. The caller is responsible to free them with
[`kfree_strarray()`](#c-kfree_strarray) after use.

Returns array of strings or NULL when memory can't be allocated.

#### <a id="c-kfree_strarray"></a>`kfree_strarray()`

```c
void kfree_strarray(char **array, size_t n)
```

free a number of dynamically allocated strings contained in an array and the array itself

**Parameters**

- `char **array`: Dynamically allocated array of strings to free.
- `size_t n`: Number of strings (starting from the beginning of the array) to free.

**Description**

Passing a non-NULL **array** and **n** == 0 as well as NULL **array** are valid
use-cases. If **array** is NULL, the function does nothing.

#### <a id="c-skip_spaces"></a>`skip_spaces()`

```c
char * skip_spaces(const char *str)
```

Removes leading whitespace from **str**.

**Parameters**

- `const char *str`: The string to be stripped.

**Description**

Returns a pointer to the first non-whitespace character in **str**.

#### <a id="c-strim"></a>`strim()`

```c
char * strim(char *s)
```

Removes leading and trailing whitespace from **s**.

**Parameters**

- `char *s`: The string to be stripped.

**Description**

Note that the first trailing whitespace is replaced with a `NUL-terminator`
in the given string **s**. Returns a pointer to the first non-whitespace
character in **s**.

#### <a id="c-sysfs_streq"></a>`sysfs_streq()`

```c
bool sysfs_streq(const char *s1, const char *s2)
```

return true if strings are equal, modulo trailing newline

**Parameters**

- `const char *s1`: one string
- `const char *s2`: another string

**Description**

This routine returns true iff two strings are equal, treating both
NUL and newline-then-NUL as equivalent string terminations.  It's
geared for use with sysfs input strings, which generally terminate
with newlines but are compared against values without newlines.

#### <a id="c-match_string"></a>`match_string()`

```c
int match_string(const char * const *array, size_t n, const char *string)
```

matches given string in an array

**Parameters**

- `const char * const *array`: array of strings
- `size_t n`: number of strings in the array or -1 for NULL terminated arrays
- `const char *string`: string to match with

**Description**

This routine will look for a string in an array of strings up to the
n-th element in the array or until the first NULL element.

Historically the value of -1 for **n**, was used to search in arrays that
are NULL terminated. However, the function does not make a distinction
when finishing the search: either **n** elements have been compared OR
the first NULL element was found.

**Return**

index of a **string** in the **array** if matches, or `-EINVAL` otherwise.

#### <a id="c-__sysfs_match_string"></a>`__sysfs_match_string()`

```c
int __sysfs_match_string(const char * const *array, size_t n, const char *str)
```

matches given string in an array

**Parameters**

- `const char * const *array`: array of strings
- `size_t n`: number of strings in the array or -1 for NULL terminated arrays
- `const char *str`: string to match with

**Description**

Returns index of **str** in the **array** or -EINVAL, just like [`match_string()`](#c-match_string).
Uses sysfs_streq instead of strcmp for matching.

This routine will look for a string in an array of strings up to the
n-th element in the array or until the first NULL element.

Historically the value of -1 for **n**, was used to search in arrays that
are NULL terminated. However, the function does not make a distinction
when finishing the search: either **n** elements have been compared OR
the first NULL element was found.

#### <a id="c-strreplace"></a>`strreplace()`

```c
char * strreplace(char *str, char old, char new)
```

Replace all occurrences of character in string.

**Parameters**

- `char *str`: The string to operate on.
- `char old`: The character being replaced.
- `char new`: The character **old** is replaced with.

**Description**

Replaces the each **old** character with a **new** one in the given string **str**.

**Return**

pointer to the string **str** itself.

#### <a id="c-memcpy_and_pad"></a>`memcpy_and_pad()`

```c
void memcpy_and_pad(void *dest, size_t dest_len, const void *src, size_t count, int pad)
```

Copy one buffer to another with padding

**Parameters**

- `void *dest`: Where to copy to
- `size_t dest_len`: The destination buffer size
- `const void *src`: Where to copy from
- `size_t count`: The number of bytes to copy
- `int pad`: Character to use for padding if space is left in destination.


<a id="rst-string-manipulation"></a>

### String Manipulation


#### <a id="c-unsafe_memcpy"></a>`unsafe_memcpy()`

```c
unsafe_memcpy(dst, src, bytes, justification)
```

memcpy implementation with no FORTIFY bounds checking

**Parameters**

- `dst`: Destination memory address to write to
- `src`: Source memory address to read from
- `bytes`: How many bytes to write to **dst** from **src**
- `justification`: Free-form text or comment describing why the use is needed

**Description**

This should be used for corner cases where the compiler cannot do the
right thing, or during transitions between APIs, etc. It should be used
very rarely, and includes a place for justification detailing where bounds
checking has happened, and why existing solutions cannot be employed.

#### <a id="c-strncpy"></a>`strncpy()`

```c
char * strncpy(char * const p, const char *q, __kernel_size_t size)
```

Copy a string to memory with non-guaranteed NUL padding

**Parameters**

- `char * const p`: pointer to destination of copy
- `const char *q`: pointer to NUL-terminated source string to copy
- `__kernel_size_t size`: bytes to write at **p**

**Description**

If strlen(**q**) >= **size**, the copy of **q** will stop after **size** bytes,
and **p** will NOT be NUL-terminated

If strlen(**q**) \< **size**, following the copy of **q**, trailing NUL bytes
will be written to **p** until **size** total bytes have been written.

Do not use this function. While FORTIFY_SOURCE tries to avoid
over-reads of **q**, it cannot defend against writing unterminated
results to **p**. Using [`strncpy()`](#c-strncpy) remains ambiguous and fragile.
Instead, please choose an alternative, so that the expectation
of **p**'s contents is unambiguous:

```text
+--------------------+--------------------+------------+
| **p** needs to be: | padded to **size** | not padded |
+====================+====================+============+
|     NUL-terminated | strscpy_pad()      | strscpy()  |
+--------------------+--------------------+------------+
| not NUL-terminated | strtomem_pad()     | strtomem() |
+--------------------+--------------------+------------+
```

Note strscpy*()'s differing return values for detecting truncation,
and strtomem*()'s expectation that the destination is marked with
__nonstring when it is a character array.

#### <a id="c-strnlen"></a>`strnlen()`

```c
__kernel_size_t strnlen(const char * const p, __kernel_size_t maxlen)
```

Return bounded count of characters in a NUL-terminated string

**Parameters**

- `const char * const p`: pointer to NUL-terminated string to count.
- `__kernel_size_t maxlen`: maximum number of characters to count.

**Description**

Returns number of characters in **p** (NOT including the final NUL), or
**maxlen**, if no NUL has been found up to there.

#### <a id="c-strlen"></a>`strlen()`

```c
strlen(p)
```

Return count of characters in a NUL-terminated string

**Parameters**

- `p`: pointer to NUL-terminated string to count.

**Description**

Do not use this function unless the string length is known at
compile-time. When **p** is unterminated, this function may crash
or return unexpected counts that could lead to memory content
exposures. Prefer [`strnlen()`](#c-strnlen).

Returns number of characters in **p** (NOT including the final NUL).

#### <a id="c-strlcat"></a>`strlcat()`

```c
size_t strlcat(char * const p, const char * const q, size_t avail)
```

Append a string to an existing string

**Parameters**

- `char * const p`: pointer to `NUL-terminated` string to append to
- `const char * const q`: pointer to `NUL-terminated` string to append from
- `size_t avail`: Maximum bytes available in **p**

**Description**

Appends `NUL-terminated` string **q** after the `NUL-terminated`
string at **p**, but will not write beyond **avail** bytes total,
potentially truncating the copy from **q**. **p** will stay
`NUL-terminated` only if a `NUL` already existed within
the **avail** bytes of **p**. If so, the resulting number of
bytes copied from **q** will be at most "**avail** - strlen(**p**) - 1".

Do not use this function. While FORTIFY_SOURCE tries to avoid
read and write overflows, this is only possible when the sizes
of **p** and **q** are known to the compiler. Prefer building the
string with formatting, via [`scnprintf()`](#c-scnprintf), seq_buf, or similar.

Returns total bytes that _would_ have been contained by **p**
regardless of truncation, similar to [`snprintf()`](#c-snprintf). If return
value is >= **avail**, the string has been truncated.

#### <a id="c-strcat"></a>`strcat()`

```c
char * strcat(char * const p, const char *q)
```

Append a string to an existing string

**Parameters**

- `char * const p`: pointer to NUL-terminated string to append to
- `const char *q`: pointer to NUL-terminated source string to append from

**Description**

Do not use this function. While FORTIFY_SOURCE tries to avoid
read and write overflows, this is only possible when the
destination buffer size is known to the compiler. Prefer
building the string with formatting, via [`scnprintf()`](#c-scnprintf) or similar.
At the very least, use [`strncat()`](#c-strncat).

Returns **p**.

#### <a id="c-strncat"></a>`strncat()`

```c
char * strncat(char * const p, const char * const q, __kernel_size_t count)
```

Append a string to an existing string

**Parameters**

- `char * const p`: pointer to NUL-terminated string to append to
- `const char * const q`: pointer to source string to append from
- `__kernel_size_t count`: Maximum bytes to read from **q**

**Description**

Appends at most **count** bytes from **q** (stopping at the first
NUL byte) after the NUL-terminated string at **p**. **p** will be
NUL-terminated.

Do not use this function. While FORTIFY_SOURCE tries to avoid
read and write overflows, this is only possible when the sizes
of **p** and **q** are known to the compiler. Prefer building the
string with formatting, via [`scnprintf()`](#c-scnprintf) or similar.

Returns **p**.

#### <a id="c-strcpy"></a>`strcpy()`

```c
char * strcpy(char * const p, const char * const q)
```

Copy a string into another string buffer

**Parameters**

- `char * const p`: pointer to destination of copy
- `const char * const q`: pointer to NUL-terminated source string to copy

**Description**

Do not use this function. While FORTIFY_SOURCE tries to avoid
overflows, this is only possible when the sizes of **q** and **p** are
known to the compiler. Prefer [`strscpy()`](#c-strscpy), though note its different
return values for detecting truncation.

Returns **p**.



#### <a id="c-strncasecmp"></a>`strncasecmp()`

```c
int strncasecmp(const char *s1, const char *s2, size_t len)
```

Case insensitive, length-limited string comparison

**Parameters**

- `const char *s1`: One string
- `const char *s2`: The other string
- `size_t len`: the maximum number of characters to compare

#### <a id="c-stpcpy"></a>`stpcpy()`

```c
char * stpcpy(char *__restrict__ dest, const char *__restrict__ src)
```

copy a string from src to dest returning a pointer to the new end of dest, including src's `NUL-terminator`. May overrun dest.

**Parameters**

- `char *__restrict__ dest`: pointer to end of string being copied into. Must be large enough
  to receive copy.
- `const char *__restrict__ src`: pointer to the beginning of string being copied from. Must not overlap
  dest.

**Description**

stpcpy differs from strcpy in a key way: the return value is a pointer
to the new `NUL-terminating` character in **dest**. (For strcpy, the return
value is a pointer to the start of **dest**). This interface is considered
unsafe as it doesn't perform bounds checking of the inputs. As such it's
not recommended for usage. Instead, its definition is provided in case
the compiler lowers other libcalls to stpcpy.

#### <a id="c-strcmp"></a>`strcmp()`

```c
int strcmp(const char *cs, const char *ct)
```

Compare two strings

**Parameters**

- `const char *cs`: One string
- `const char *ct`: Another string

#### <a id="c-strncmp"></a>`strncmp()`

```c
int strncmp(const char *cs, const char *ct, size_t count)
```

Compare two length-limited strings

**Parameters**

- `const char *cs`: One string
- `const char *ct`: Another string
- `size_t count`: The maximum number of bytes to compare

#### <a id="c-strchr"></a>`strchr()`

```c
char * strchr(const char *s, int c)
```

Find the first occurrence of a character in a string

**Parameters**

- `const char *s`: The string to be searched
- `int c`: The character to search for

**Description**

Note that the `NUL-terminator` is considered part of the string, and can
be searched for.

#### <a id="c-strchrnul"></a>`strchrnul()`

```c
char * strchrnul(const char *s, int c)
```

Find and return a character in a string, or end of string

**Parameters**

- `const char *s`: The string to be searched
- `int c`: The character to search for

**Description**

Returns pointer to first occurrence of 'c' in s. If c is not found, then
return a pointer to the null byte at the end of s.

#### <a id="c-strrchr"></a>`strrchr()`

```c
char * strrchr(const char *s, int c)
```

Find the last occurrence of a character in a string

**Parameters**

- `const char *s`: The string to be searched
- `int c`: The character to search for

#### <a id="c-strnchr"></a>`strnchr()`

```c
char * strnchr(const char *s, size_t count, int c)
```

Find a character in a length limited string

**Parameters**

- `const char *s`: The string to be searched
- `size_t count`: The number of characters to be searched
- `int c`: The character to search for

**Description**

Note that the `NUL-terminator` is considered part of the string, and can
be searched for.

#### <a id="c-strspn"></a>`strspn()`

```c
size_t strspn(const char *s, const char *accept)
```

Calculate the length of the initial substring of **s** which only contain letters in **accept**

**Parameters**

- `const char *s`: The string to be searched
- `const char *accept`: The string to search for

#### <a id="c-strcspn"></a>`strcspn()`

```c
size_t strcspn(const char *s, const char *reject)
```

Calculate the length of the initial substring of **s** which does not contain letters in **reject**

**Parameters**

- `const char *s`: The string to be searched
- `const char *reject`: The string to avoid

#### <a id="c-strpbrk"></a>`strpbrk()`

```c
char * strpbrk(const char *cs, const char *ct)
```

Find the first occurrence of a set of characters

**Parameters**

- `const char *cs`: The string to be searched
- `const char *ct`: The characters to search for

#### <a id="c-strsep"></a>`strsep()`

```c
char * strsep(char **s, const char *ct)
```

Split a string into tokens

**Parameters**

- `char **s`: The string to be searched
- `const char *ct`: The characters to search for

**Description**

[`strsep()`](#c-strsep) updates **s** to point after the token, ready for the next call.

It returns empty tokens, too, behaving exactly like the libc function
of that name. In fact, it was stolen from glibc2 and de-fancy-fied.
Same semantics, slimmer shape. ;)

#### <a id="c-memset"></a>`memset()`

```c
void * memset(void *s, int c, size_t count)
```

Fill a region of memory with the given value

**Parameters**

- `void *s`: Pointer to the start of the area.
- `int c`: The byte to fill the area with
- `size_t count`: The size of the area.

**Description**

Do not use [`memset()`](#c-memset) to access IO space, use `memset_io()` instead.

#### <a id="c-memset16"></a>`memset16()`

```c
void * memset16(uint16_t *s, uint16_t v, size_t count)
```

Fill a memory area with a uint16_t

**Parameters**

- `uint16_t *s`: Pointer to the start of the area.
- `uint16_t v`: The value to fill the area with
- `size_t count`: The number of values to store

**Description**

Differs from [`memset()`](#c-memset) in that it fills with a uint16_t instead
of a byte.  Remember that **count** is the number of uint16_ts to
store, not the number of bytes.

#### <a id="c-memset32"></a>`memset32()`

```c
void * memset32(uint32_t *s, uint32_t v, size_t count)
```

Fill a memory area with a uint32_t

**Parameters**

- `uint32_t *s`: Pointer to the start of the area.
- `uint32_t v`: The value to fill the area with
- `size_t count`: The number of values to store

**Description**

Differs from [`memset()`](#c-memset) in that it fills with a uint32_t instead
of a byte.  Remember that **count** is the number of uint32_ts to
store, not the number of bytes.

#### <a id="c-memset64"></a>`memset64()`

```c
void * memset64(uint64_t *s, uint64_t v, size_t count)
```

Fill a memory area with a uint64_t

**Parameters**

- `uint64_t *s`: Pointer to the start of the area.
- `uint64_t v`: The value to fill the area with
- `size_t count`: The number of values to store

**Description**

Differs from [`memset()`](#c-memset) in that it fills with a uint64_t instead
of a byte.  Remember that **count** is the number of uint64_ts to
store, not the number of bytes.

#### <a id="c-memcpy"></a>`memcpy()`

```c
void * memcpy(void *dest, const void *src, size_t count)
```

Copy one area of memory to another

**Parameters**

- `void *dest`: Where to copy to
- `const void *src`: Where to copy from
- `size_t count`: The size of the area.

**Description**

You should not use this function to access IO space, use `memcpy_toio()`
or `memcpy_fromio()` instead.

#### <a id="c-memmove"></a>`memmove()`

```c
void * memmove(void *dest, const void *src, size_t count)
```

Copy one area of memory to another

**Parameters**

- `void *dest`: Where to copy to
- `const void *src`: Where to copy from
- `size_t count`: The size of the area.

**Description**

Unlike [`memcpy()`](#c-memcpy), [`memmove()`](#c-memmove) copes with overlapping areas.

#### <a id="c-memcmp"></a>`memcmp()`

```c
__visible int memcmp(const void *cs, const void *ct, size_t count)
```

Compare two areas of memory

**Parameters**

- `const void *cs`: One area of memory
- `const void *ct`: Another area of memory
- `size_t count`: The size of the area.

#### <a id="c-bcmp"></a>`bcmp()`

```c
int bcmp(const void *a, const void *b, size_t len)
```

returns 0 if and only if the buffers have identical contents.

**Parameters**

- `const void *a`: pointer to first buffer.
- `const void *b`: pointer to second buffer.
- `size_t len`: size of buffers.

**Description**

The sign or magnitude of a non-zero return value has no particular
meaning, and architectures may implement their own more efficient [`bcmp()`](#c-bcmp). So
while this particular implementation is a simple (tail) call to memcmp, do
not rely on anything but whether the return value is zero or non-zero.

#### <a id="c-memscan"></a>`memscan()`

```c
void * memscan(void *addr, int c, size_t size)
```

Find a character in an area of memory.

**Parameters**

- `void *addr`: The memory area
- `int c`: The byte to search for
- `size_t size`: The size of the area.

**Description**

returns the address of the first occurrence of **c**, or 1 byte past
the area if **c** is not found

#### <a id="c-strstr"></a>`strstr()`

```c
char * strstr(const char *s1, const char *s2)
```

Find the first substring in a `NUL` terminated string

**Parameters**

- `const char *s1`: The string to be searched
- `const char *s2`: The string to search for

#### <a id="c-strnstr"></a>`strnstr()`

```c
char * strnstr(const char *s1, const char *s2, size_t len)
```

Find the first substring in a length-limited string

**Parameters**

- `const char *s1`: The string to be searched
- `const char *s2`: The string to search for
- `size_t len`: the maximum number of characters to search

#### <a id="c-memchr"></a>`memchr()`

```c
void * memchr(const void *s, int c, size_t n)
```

Find a character in an area of memory.

**Parameters**

- `const void *s`: The memory area
- `int c`: The byte to search for
- `size_t n`: The size of the area.

**Description**

returns the address of the first occurrence of **c**, or `NULL`
if **c** is not found

#### <a id="c-memchr_inv"></a>`memchr_inv()`

```c
void * memchr_inv(const void *start, int c, size_t bytes)
```

Find an unmatching character in an area of memory.

**Parameters**

- `const void *start`: The memory area
- `int c`: Find a character other than c
- `size_t bytes`: The size of the area.

**Description**

returns the address of the first character other than **c**, or `NULL`
if the whole buffer contains just **c**.



#### <a id="c-memdup_array_user"></a>`memdup_array_user()`

```c
void * memdup_array_user(const void __user *src, size_t n, size_t size)
```

duplicate array from user space

**Parameters**

- `const void __user *src`: source address in user space
- `size_t n`: number of array members to copy
- `size_t size`: size of one array member

**Return**

an [`ERR_PTR()`](#c-ERR_PTR) on failure. Result is physically
contiguous, to be freed by [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

#### <a id="c-vmemdup_array_user"></a>`vmemdup_array_user()`

```c
void * vmemdup_array_user(const void __user *src, size_t n, size_t size)
```

duplicate array from user space

**Parameters**

- `const void __user *src`: source address in user space
- `size_t n`: number of array members to copy
- `size_t size`: size of one array member

**Return**

an [`ERR_PTR()`](#c-ERR_PTR) on failure. Result may be not
physically contiguous. Use [`kvfree()`](/kernel/internals/core-api/mm-api.md#c-kvfree) to free.

#### <a id="c-strscpy"></a>`strscpy()`

```c
strscpy(dst, src, ...)
```

Copy a C-string into a sized buffer

**Parameters**

- `dst`: Where to copy the string to
- `src`: Where to copy the string from
- `...`: Size of destination buffer (optional)

**Description**

Copy the source string **src**, or as much of it as fits, into the
destination **dst** buffer. The behavior is undefined if the string
buffers overlap. The destination **dst** buffer is always NUL terminated,
unless it's zero-sized.

The size argument @... is only required when **dst** is not an array, or
when the copy needs to be smaller than sizeof(**dst**).

Preferred to [`strncpy()`](#c-strncpy) since it always returns a valid string, and
doesn't unnecessarily force the tail of the destination buffer to be
zero padded. If padding is desired please use [`strscpy_pad()`](#c-strscpy_pad).

Returns the number of characters copied in **dst** (not including the
trailing `NUL`) or -E2BIG if **size** is 0 or the copy from **src** was
truncated.

#### <a id="c-strscpy_pad"></a>`strscpy_pad()`

```c
strscpy_pad(dst, src, ...)
```

Copy a C-string into a sized buffer

**Parameters**

- `dst`: Where to copy the string to
- `src`: Where to copy the string from
- `...`: Size of destination buffer

**Description**

Copy the string, or as much of it as fits, into the dest buffer. The
behavior is undefined if the string buffers overlap. The destination
buffer is always `NUL` terminated, unless it's zero-sized.

If the source string is shorter than the destination buffer, the
remaining bytes in the buffer will be filled with `NUL` bytes.

For full explanation of why you may want to consider using the
'strscpy' functions please see the function docstring for [`strscpy()`](#c-strscpy).

**Return**

* The number of characters copied (not including the trailing `NULs`)
* -E2BIG if count is 0 or **src** was truncated.

#### <a id="c-mem_is_zero"></a>`mem_is_zero()`

```c
bool mem_is_zero(const void *s, size_t n)
```

Check if an area of memory is all 0's.

**Parameters**

- `const void *s`: The memory area
- `size_t n`: The size of the area

**Return**

True if the area of memory is all 0's.

#### <a id="c-sysfs_match_string"></a>`sysfs_match_string()`

```c
sysfs_match_string(_a, _s)
```

matches given string in an array

**Parameters**

- `_a`: array of strings
- `_s`: string to match with

**Description**

Helper for [`__sysfs_match_string()`](#c-__sysfs_match_string). Calculates the size of **a** automatically.

#### <a id="c-memzero_explicit"></a>`memzero_explicit()`

```c
void memzero_explicit(void *s, size_t count)
```

Fill a region of memory (e.g. sensitive keying data) with 0s.

**Parameters**

- `void *s`: Pointer to the start of the area.
- `size_t count`: The size of the area.

**Note**

usually using [`memset()`](#c-memset) is just fine (!), but in cases
where clearing out _local_ data at the end of a scope is
necessary, [`memzero_explicit()`](#c-memzero_explicit) should be used instead in
order to prevent the compiler from optimising away zeroing.

[`memzero_explicit()`](#c-memzero_explicit) doesn't need an arch-specific version as
it just invokes the one of [`memset()`](#c-memset) implicitly.

#### <a id="c-kbasename"></a>`kbasename()`

```c
const char * kbasename(const char *path)
```

return the last part of a pathname.

**Parameters**

- `const char *path`: path to extract the filename from.

**Return**

Pointer to the filename portion inside **path**. If no '/' exists,
returns **path** unchanged.

#### <a id="c-strtomem_pad"></a>`strtomem_pad()`

```c
strtomem_pad(dest, src, pad)
```

Copy NUL-terminated string to non-NUL-terminated buffer

**Parameters**

- `dest`: Pointer of destination character array (marked as __nonstring)
- `src`: Pointer to NUL-terminated string
- `pad`: Padding character to fill any remaining bytes of **dest** after copy

**Description**

This is a replacement for [`strncpy()`](#c-strncpy) uses where the destination is not
a NUL-terminated string, but with bounds checking on the source size, and
an explicit padding character. If padding is not required, use [`strtomem()`](#c-strtomem).

Note that the size of **dest** is not an argument, as the length of **dest**
must be discoverable by the compiler.

#### <a id="c-strtomem"></a>`strtomem()`

```c
strtomem(dest, src)
```

Copy NUL-terminated string to non-NUL-terminated buffer

**Parameters**

- `dest`: Pointer of destination character array (marked as __nonstring)
- `src`: Pointer to NUL-terminated string

**Description**

This is a replacement for [`strncpy()`](#c-strncpy) uses where the destination is not
a NUL-terminated string, but with bounds checking on the source size, and
without trailing padding. If padding is required, use [`strtomem_pad()`](#c-strtomem_pad).

Note that the size of **dest** is not an argument, as the length of **dest**
must be discoverable by the compiler.

#### <a id="c-memtostr"></a>`memtostr()`

```c
memtostr(dest, src)
```

Copy a possibly non-NUL-term string to a NUL-term string

**Parameters**

- `dest`: Pointer to destination NUL-terminates string
- `src`: Pointer to character array (likely marked as __nonstring)

**Description**

This is a replacement for [`strncpy()`](#c-strncpy) uses where the source is not
a NUL-terminated string.

Note that sizes of **dest** and **src** must be known at compile-time.

#### <a id="c-memtostr_pad"></a>`memtostr_pad()`

```c
memtostr_pad(dest, src)
```

Copy a possibly non-NUL-term string to a NUL-term string with NUL padding in the destination

**Parameters**

- `dest`: Pointer to destination NUL-terminates string
- `src`: Pointer to character array (likely marked as __nonstring)

**Description**

This is a replacement for [`strncpy()`](#c-strncpy) uses where the source is not
a NUL-terminated string.

Note that sizes of **dest** and **src** must be known at compile-time.

#### <a id="c-memset_after"></a>`memset_after()`

```c
memset_after(obj, v, member)
```

Set a value after a struct member to the end of a struct

**Parameters**

- `obj`: Address of target struct instance
- `v`: Byte value to repeatedly write
- `member`: after which struct member to start writing bytes

**Description**

This is good for clearing padding following the given member.

#### <a id="c-memset_startat"></a>`memset_startat()`

```c
memset_startat(obj, v, member)
```

Set a value starting at a member to the end of a struct

**Parameters**

- `obj`: Address of target struct instance
- `v`: Byte value to repeatedly write
- `member`: struct member to start writing at

**Description**

Note that if there is padding between the prior member and the target
member, [`memset_after()`](#c-memset_after) should be used to clear the prior padding.

#### <a id="c-str_has_prefix"></a>`str_has_prefix()`

```c
size_t str_has_prefix(const char *str, const char *prefix)
```

Test if a string has a given prefix

**Parameters**

- `const char *str`: The string to test
- `const char *prefix`: The string to see if **str** starts with

**Description**

- A common way to test a prefix of a string is to do:
  strncmp(str, prefix, sizeof(prefix) - 1)

But this can lead to bugs due to typos, or if prefix is a pointer
and not a constant. Instead use [`str_has_prefix()`](#c-str_has_prefix).

**Return**

* strlen(**prefix**) if **str** starts with **prefix**
* 0 if **str** does not start with **prefix**

#### <a id="c-strstarts"></a>`strstarts()`

```c
bool strstarts(const char *str, const char *prefix)
```

does **str** start with **prefix**?

**Parameters**

- `const char *str`: string to examine
- `const char *prefix`: prefix to look for.

**Return**

True if **str** begins with **prefix**. False in all other cases.

#### <a id="c-strends"></a>`strends()`

```c
bool strends(const char *str, const char *suffix)
```

Check if a string ends with another string.

**Parameters**

- `const char *str`: NULL-terminated string to check against **suffix**
- `const char *suffix`: NULL-terminated string defining the suffix to look for in **str**

**Return**

True if **str** ends with **suffix**. False in all other cases.



#### <a id="c-kstrdup"></a>`kstrdup()`

```c
char * kstrdup(const char *s, gfp_t gfp)
```

allocate space for and copy an existing string

**Parameters**

- `const char *s`: the string to duplicate
- `gfp_t gfp`: the GFP mask used in the [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) call when allocating memory

**Return**

newly allocated copy of **s** or `NULL` in case of error

#### <a id="c-kstrdup_const"></a>`kstrdup_const()`

```c
const char * kstrdup_const(const char *s, gfp_t gfp)
```

conditionally duplicate an existing const string

**Parameters**

- `const char *s`: the string to duplicate
- `gfp_t gfp`: the GFP mask used in the [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) call when allocating memory

**Note**

Strings allocated by kstrdup_const should be freed by kfree_const and
must not be passed to `krealloc()`.

**Return**

source string if it is in .rodata section otherwise
fallback to kstrdup.

#### <a id="c-kstrndup"></a>`kstrndup()`

```c
char * kstrndup(const char *s, size_t max, gfp_t gfp)
```

allocate space for and copy an existing string

**Parameters**

- `const char *s`: the string to duplicate
- `size_t max`: read at most **max** chars from **s**
- `gfp_t gfp`: the GFP mask used in the [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) call when allocating memory

**Note**

Use [`kmemdup_nul()`](#c-kmemdup_nul) instead if the size is known exactly.

**Return**

newly allocated copy of **s** or `NULL` in case of error

#### <a id="c-kmemdup"></a>`kmemdup()`

```c
void * kmemdup(const void *src, size_t len, gfp_t gfp)
```

duplicate region of memory

**Parameters**

- `const void *src`: memory region to duplicate
- `size_t len`: memory region length
- `gfp_t gfp`: GFP mask to use

**Return**

newly allocated copy of **src** or `NULL` in case of error,
result is physically contiguous. Use [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) to free.

#### <a id="c-kmemdup_nul"></a>`kmemdup_nul()`

```c
char * kmemdup_nul(const char *s, size_t len, gfp_t gfp)
```

Create a NUL-terminated string from unterminated data

**Parameters**

- `const char *s`: The data to stringify
- `size_t len`: The size of the data
- `gfp_t gfp`: the GFP mask used in the [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) call when allocating memory

**Return**

newly allocated copy of **s** with NUL-termination or `NULL` in
case of error

#### <a id="c-memdup_user"></a>`memdup_user()`

```c
void * memdup_user(const void __user *src, size_t len)
```

duplicate memory region from user space

**Parameters**

- `const void __user *src`: source address in user space
- `size_t len`: number of bytes to copy

**Return**

an [`ERR_PTR()`](#c-ERR_PTR) on failure.  Result is physically
contiguous, to be freed by [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

#### <a id="c-vmemdup_user"></a>`vmemdup_user()`

```c
void * vmemdup_user(const void __user *src, size_t len)
```

duplicate memory region from user space

**Parameters**

- `const void __user *src`: source address in user space
- `size_t len`: number of bytes to copy

**Return**

an [`ERR_PTR()`](#c-ERR_PTR) on failure.  Result may be not
physically contiguous.  Use [`kvfree()`](/kernel/internals/core-api/mm-api.md#c-kvfree) to free.

#### <a id="c-strndup_user"></a>`strndup_user()`

```c
char * strndup_user(const char __user *s, long n)
```

duplicate an existing string from user space

**Parameters**

- `const char __user *s`: The string to duplicate
- `long n`: Maximum number of bytes to copy, including the trailing NUL.

**Return**

newly allocated copy of **s** or an [`ERR_PTR()`](#c-ERR_PTR) in case of error

#### <a id="c-memdup_user_nul"></a>`memdup_user_nul()`

```c
void * memdup_user_nul(const void __user *src, size_t len)
```

duplicate memory region from user space and NUL-terminate

**Parameters**

- `const void __user *src`: source address in user space
- `size_t len`: number of bytes to copy

**Return**

an [`ERR_PTR()`](#c-ERR_PTR) on failure.


<a id="rst-basic-kernel-library-functions"></a>

## Basic Kernel Library Functions

The Linux kernel provides more basic utility functions.

<a id="rst-bit-operations"></a>

### Bit Operations


#### <a id="c-set_bit"></a>`set_bit()`

```c
void set_bit(long nr, volatile unsigned long *addr)
```

Atomically set a bit in memory

**Parameters**

- `long nr`: the bit to set
- `volatile unsigned long *addr`: the address to start counting from

**Description**

This is a relaxed atomic operation (no implied memory barriers).

Note that **nr** may be almost arbitrarily large; this function is not
restricted to acting on a single-word quantity.

#### <a id="c-clear_bit"></a>`clear_bit()`

```c
void clear_bit(long nr, volatile unsigned long *addr)
```

Clears a bit in memory

**Parameters**

- `long nr`: Bit to clear
- `volatile unsigned long *addr`: Address to start counting from

**Description**

This is a relaxed atomic operation (no implied memory barriers).

#### <a id="c-change_bit"></a>`change_bit()`

```c
void change_bit(long nr, volatile unsigned long *addr)
```

Toggle a bit in memory

**Parameters**

- `long nr`: Bit to change
- `volatile unsigned long *addr`: Address to start counting from

**Description**

This is a relaxed atomic operation (no implied memory barriers).

Note that **nr** may be almost arbitrarily large; this function is not
restricted to acting on a single-word quantity.

#### <a id="c-test_and_set_bit"></a>`test_and_set_bit()`

```c
bool test_and_set_bit(long nr, volatile unsigned long *addr)
```

Set a bit and return its old value

**Parameters**

- `long nr`: Bit to set
- `volatile unsigned long *addr`: Address to count from

**Description**

This is an atomic fully-ordered operation (implied full memory barrier).

#### <a id="c-test_and_clear_bit"></a>`test_and_clear_bit()`

```c
bool test_and_clear_bit(long nr, volatile unsigned long *addr)
```

Clear a bit and return its old value

**Parameters**

- `long nr`: Bit to clear
- `volatile unsigned long *addr`: Address to count from

**Description**

This is an atomic fully-ordered operation (implied full memory barrier).

#### <a id="c-test_and_change_bit"></a>`test_and_change_bit()`

```c
bool test_and_change_bit(long nr, volatile unsigned long *addr)
```

Change a bit and return its old value

**Parameters**

- `long nr`: Bit to change
- `volatile unsigned long *addr`: Address to count from

**Description**

This is an atomic fully-ordered operation (implied full memory barrier).



#### <a id="c-___set_bit"></a>`___set_bit()`

```c
void ___set_bit(unsigned long nr, volatile unsigned long *addr)
```

Set a bit in memory

**Parameters**

- `unsigned long nr`: the bit to set
- `volatile unsigned long *addr`: the address to start counting from

**Description**

Unlike [`set_bit()`](#c-set_bit), this function is non-atomic. If it is called on the same
region of memory concurrently, the effect may be that only one operation
succeeds.

#### <a id="c-___clear_bit"></a>`___clear_bit()`

```c
void ___clear_bit(unsigned long nr, volatile unsigned long *addr)
```

Clears a bit in memory

**Parameters**

- `unsigned long nr`: the bit to clear
- `volatile unsigned long *addr`: the address to start counting from

**Description**

Unlike [`clear_bit()`](#c-clear_bit), this function is non-atomic. If it is called on the same
region of memory concurrently, the effect may be that only one operation
succeeds.

#### <a id="c-___change_bit"></a>`___change_bit()`

```c
void ___change_bit(unsigned long nr, volatile unsigned long *addr)
```

Toggle a bit in memory

**Parameters**

- `unsigned long nr`: the bit to change
- `volatile unsigned long *addr`: the address to start counting from

**Description**

Unlike [`change_bit()`](#c-change_bit), this function is non-atomic. If it is called on the same
region of memory concurrently, the effect may be that only one operation
succeeds.

#### <a id="c-___test_and_set_bit"></a>`___test_and_set_bit()`

```c
bool ___test_and_set_bit(unsigned long nr, volatile unsigned long *addr)
```

Set a bit and return its old value

**Parameters**

- `unsigned long nr`: Bit to set
- `volatile unsigned long *addr`: Address to count from

**Description**

This operation is non-atomic. If two instances of this operation race, one
can appear to succeed but actually fail.

#### <a id="c-___test_and_clear_bit"></a>`___test_and_clear_bit()`

```c
bool ___test_and_clear_bit(unsigned long nr, volatile unsigned long *addr)
```

Clear a bit and return its old value

**Parameters**

- `unsigned long nr`: Bit to clear
- `volatile unsigned long *addr`: Address to count from

**Description**

This operation is non-atomic. If two instances of this operation race, one
can appear to succeed but actually fail.

#### <a id="c-___test_and_change_bit"></a>`___test_and_change_bit()`

```c
bool ___test_and_change_bit(unsigned long nr, volatile unsigned long *addr)
```

Change a bit and return its old value

**Parameters**

- `unsigned long nr`: Bit to change
- `volatile unsigned long *addr`: Address to count from

**Description**

This operation is non-atomic. If two instances of this operation race, one
can appear to succeed but actually fail.

#### <a id="c-_test_bit"></a>`_test_bit()`

```c
bool _test_bit(unsigned long nr, const volatile unsigned long *addr)
```

Determine whether a bit is set

**Parameters**

- `unsigned long nr`: bit number to test
- `const volatile unsigned long *addr`: Address to start counting from

#### <a id="c-_test_bit_acquire"></a>`_test_bit_acquire()`

```c
bool _test_bit_acquire(unsigned long nr, const volatile unsigned long *addr)
```

Determine, with acquire semantics, whether a bit is set

**Parameters**

- `unsigned long nr`: bit number to test
- `const volatile unsigned long *addr`: Address to start counting from



#### <a id="c-clear_bit_unlock"></a>`clear_bit_unlock()`

```c
void clear_bit_unlock(long nr, volatile unsigned long *addr)
```

Clear a bit in memory, for unlock

**Parameters**

- `long nr`: the bit to set
- `volatile unsigned long *addr`: the address to start counting from

**Description**

This operation is atomic and provides release barrier semantics.

#### <a id="c-__clear_bit_unlock"></a>`__clear_bit_unlock()`

```c
void __clear_bit_unlock(long nr, volatile unsigned long *addr)
```

Clears a bit in memory

**Parameters**

- `long nr`: Bit to clear
- `volatile unsigned long *addr`: Address to start counting from

**Description**

This is a non-atomic operation but implies a release barrier before the
memory operation. It can be used for an unlock if no other CPUs can
concurrently modify other bits in the word.

#### <a id="c-test_and_set_bit_lock"></a>`test_and_set_bit_lock()`

```c
bool test_and_set_bit_lock(long nr, volatile unsigned long *addr)
```

Set a bit and return its old value, for lock

**Parameters**

- `long nr`: Bit to set
- `volatile unsigned long *addr`: Address to count from

**Description**

This operation is atomic and provides acquire barrier semantics if
the returned value is 0.
It can be used to implement bit locks.

#### <a id="c-xor_unlock_is_negative_byte"></a>`xor_unlock_is_negative_byte()`

```c
bool xor_unlock_is_negative_byte(unsigned long mask, volatile unsigned long *addr)
```

XOR a single byte in memory and test if it is negative, for unlock.

**Parameters**

- `unsigned long mask`: Change the bits which are set in this mask.
- `volatile unsigned long *addr`: The address of the word containing the byte to change.

**Description**

Changes some of bits 0-6 in the word pointed to by **addr**.
This operation is atomic and provides release barrier semantics.
Used to optimise some folio operations which are commonly paired
with an unlock or end of writeback.  Bit 7 is used as PG_waiters to
indicate whether anybody is waiting for the unlock.

**Return**

Whether the top bit of the byte is set.


<a id="rst-bitmap-operations"></a>

### Bitmap Operations


bitmaps provide an array of bits, implemented using an
array of unsigned longs.  The number of valid bits in a
given bitmap does _not_ need to be an exact multiple of
BITS_PER_LONG.

The possible unused bits in the last, partially used word
of a bitmap are 'don't care'.  The implementation makes
no particular effort to keep them zero.  It ensures that
their value will not affect the results of any operation.
The bitmap operations that return Boolean (bitmap_empty,
for example) or scalar (bitmap_weight, for example) results
carefully filter out these unused bits from impacting their
results.

The byte ordering of bitmaps is more natural on little
endian architectures.  See the big-endian headers
include/asm-ppc64/bitops.h and include/asm-s390/bitops.h
for the best explanations of this ordering.



The DECLARE_BITMAP(name,bits) macro, in linux/types.h, can be used
to declare an array named 'name' of just enough unsigned longs to
contain all bit positions from 0 to 'bits' - 1.



The available bitmap operations and their rough meaning in the
case that the bitmap is a single unsigned long are thus:

The generated code is more efficient when nbits is known at
compile-time and at most BITS_PER_LONG.

```text
bitmap_zero(dst, nbits)                     *dst = 0UL
bitmap_fill(dst, nbits)                     *dst = ~0UL
bitmap_copy(dst, src, nbits)                *dst = *src
bitmap_and(dst, src1, src2, nbits)          *dst = *src1 & *src2
bitmap_or(dst, src1, src2, nbits)           *dst = *src1 | *src2
bitmap_weighted_or(dst, src1, src2, nbits)  *dst = *src1 | *src2. Returns Hamming Weight of dst
bitmap_xor(dst, src1, src2, nbits)          *dst = *src1 ^ *src2
bitmap_andnot(dst, src1, src2, nbits)       *dst = *src1 & ~(*src2)
bitmap_complement(dst, src, nbits)          *dst = ~(*src)
bitmap_equal(src1, src2, nbits)             Are *src1 and *src2 equal?
bitmap_intersects(src1, src2, nbits)        Do *src1 and *src2 overlap?
bitmap_subset(src1, src2, nbits)            Is *src1 a subset of *src2?
bitmap_empty(src, nbits)                    Are all bits zero in *src?
bitmap_full(src, nbits)                     Are all bits set in *src?
bitmap_weight(src, nbits)                   Hamming Weight: number set bits
bitmap_weight_and(src1, src2, nbits)        Hamming Weight of and'ed bitmap
bitmap_weight_andnot(src1, src2, nbits)     Hamming Weight of andnot'ed bitmap
bitmap_set(dst, pos, nbits)                 Set specified bit area
bitmap_clear(dst, pos, nbits)               Clear specified bit area
bitmap_find_next_zero_area(buf, len, pos, n, mask)  Find bit free area
bitmap_find_next_zero_area_off(buf, len, pos, n, mask, mask_off)  as above
bitmap_shift_right(dst, src, n, nbits)      *dst = *src >> n
bitmap_shift_left(dst, src, n, nbits)       *dst = *src << n
bitmap_cut(dst, src, first, n, nbits)       Cut n bits from first, copy rest
bitmap_replace(dst, old, new, mask, nbits)  *dst = (*old & ~(*mask)) | (*new & *mask)
bitmap_scatter(dst, src, mask, nbits)       *dst = map(dense, sparse)(src)
bitmap_gather(dst, src, mask, nbits)        *dst = map(sparse, dense)(src)
bitmap_remap(dst, src, old, new, nbits)     *dst = map(old, new)(src)
bitmap_bitremap(oldbit, old, new, nbits)    newbit = map(old, new)(oldbit)
bitmap_onto(dst, orig, relmap, nbits)       *dst = orig relative to relmap
bitmap_fold(dst, orig, sz, nbits)           dst bits = orig bits mod sz
bitmap_parse(buf, buflen, dst, nbits)       Parse bitmap dst from kernel buf
bitmap_parse_user(ubuf, ulen, dst, nbits)   Parse bitmap dst from user buf
bitmap_parselist(buf, dst, nbits)           Parse bitmap dst from kernel buf
bitmap_parselist_user(buf, dst, nbits)      Parse bitmap dst from user buf
bitmap_find_free_region(bitmap, bits, order)  Find and allocate bit region
bitmap_release_region(bitmap, pos, order)   Free specified bit region
bitmap_allocate_region(bitmap, pos, order)  Allocate specified bit region
bitmap_from_arr32(dst, buf, nbits)          Copy nbits from u32[] buf to dst
bitmap_from_arr64(dst, buf, nbits)          Copy nbits from u64[] buf to dst
bitmap_to_arr32(buf, src, nbits)            Copy nbits from buf to u32[] dst
bitmap_to_arr64(buf, src, nbits)            Copy nbits from buf to u64[] dst
bitmap_get_value8(map, start)               Get 8bit value from map at start
bitmap_set_value8(map, value, start)        Set 8bit value to map at start
bitmap_read(map, start, nbits)              Read an nbits-sized value from
                                            map at start
bitmap_write(map, value, start, nbits)      Write an nbits-sized value to
                                            map at start
```

Note, `bitmap_zero()` and `bitmap_fill()` operate over the region of
unsigned longs, that is, bits behind bitmap till the unsigned long
boundary will be zeroed or filled as well. Consider to use
`bitmap_clear()` or `bitmap_set()` to make explicit zeroing or filling
respectively.



Also the following operations in asm/bitops.h apply to bitmaps.:

```text
set_bit(bit, addr)                  *addr |= bit
clear_bit(bit, addr)                *addr &= ~bit
change_bit(bit, addr)               *addr ^= bit
test_bit(bit, addr)                 Is bit set in *addr?
test_and_set_bit(bit, addr)         Set bit and return old value
test_and_clear_bit(bit, addr)       Clear bit and return old value
test_and_change_bit(bit, addr)      Change bit and return old value
find_first_zero_bit(addr, nbits)    Position first zero bit in *addr
find_first_bit(addr, nbits)         Position first set bit in *addr
find_next_zero_bit(addr, nbits, bit)
                                    Position next zero bit in *addr >= bit
find_next_bit(addr, nbits, bit)     Position next set bit in *addr >= bit
find_next_and_bit(addr1, addr2, nbits, bit)
                                    Same as find_next_bit, but in
                                    (*addr1 & *addr2)
```



#### <a id="c-__bitmap_shift_right"></a>`__bitmap_shift_right()`

```c
void __bitmap_shift_right(unsigned long *dst, const unsigned long *src, unsigned shift, unsigned nbits)
```

logical right shift of the bits in a bitmap

**Parameters**

- `unsigned long *dst`: destination bitmap
- `const unsigned long *src`: source bitmap
- `unsigned shift`: shift by this many bits
- `unsigned nbits`: bitmap size, in bits

**Description**

Shifting right (dividing) means moving bits in the MS -> LS bit
direction.  Zeros are fed into the vacated MS positions and the
LS bits shifted off the bottom are lost.

#### <a id="c-__bitmap_shift_left"></a>`__bitmap_shift_left()`

```c
void __bitmap_shift_left(unsigned long *dst, const unsigned long *src, unsigned int shift, unsigned int nbits)
```

logical left shift of the bits in a bitmap

**Parameters**

- `unsigned long *dst`: destination bitmap
- `const unsigned long *src`: source bitmap
- `unsigned int shift`: shift by this many bits
- `unsigned int nbits`: bitmap size, in bits

**Description**

Shifting left (multiplying) means moving bits in the LS -> MS
direction.  Zeros are fed into the vacated LS bit positions
and those MS bits shifted off the top are lost.

#### <a id="c-bitmap_cut"></a>`bitmap_cut()`

```c
void bitmap_cut(unsigned long *dst, const unsigned long *src, unsigned int first, unsigned int cut, unsigned int nbits)
```

remove bit region from bitmap and right shift remaining bits

**Parameters**

- `unsigned long *dst`: destination bitmap, might overlap with src
- `const unsigned long *src`: source bitmap
- `unsigned int first`: start bit of region to be removed
- `unsigned int cut`: number of bits to remove
- `unsigned int nbits`: bitmap size, in bits

**Description**

Set the n-th bit of **dst** iff the n-th bit of **src** is set and
n is less than **first**, or the m-th bit of **src** is set for any
m such that **first** \<= n \< nbits, and m = n + **cut**.

In pictures, example for a big-endian 32-bit architecture:

The **src** bitmap is:

```text
31                                   63
|                                    |
10000000 11000001 11110010 00010101  10000000 11000001 01110010 00010101
                |  |              |                                    |
               16  14             0                                   32
```

if **cut** is 3, and **first** is 14, bits 14-16 in **src** are cut and **dst** is:

```text
31                                   63
|                                    |
10110000 00011000 00110010 00010101  00010000 00011000 00101110 01000010
                   |              |                                    |
                   14 (bit 17     0                                   32
                       from @src)
```

Note that **dst** and **src** might overlap partially or entirely.

This is implemented in the obvious way, with a shift and carry
step for each moved bit. Optimisation is left as an exercise
for the compiler.

#### <a id="c-bitmap_find_next_zero_area_off"></a>`bitmap_find_next_zero_area_off()`

```c
unsigned long bitmap_find_next_zero_area_off(unsigned long *map, unsigned long size, unsigned long start, unsigned int nr, unsigned long align_mask, unsigned long align_offset)
```

find a contiguous aligned zero area

**Parameters**

- `unsigned long *map`: The address to base the search on
- `unsigned long size`: The bitmap size in bits
- `unsigned long start`: The bitnumber to start searching at
- `unsigned int nr`: The number of zeroed bits we're looking for
- `unsigned long align_mask`: Alignment mask for zero area
- `unsigned long align_offset`: Alignment offset for zero area.

**Description**

The **align_mask** should be one less than a power of 2; the effect is that
the bit offset of all zero areas this function finds plus **align_offset**
is multiple of that power of 2.

#### <a id="c-bitmap_remap"></a>`bitmap_remap()`

```c
void bitmap_remap(unsigned long *dst, const unsigned long *src, const unsigned long *old, const unsigned long *new, unsigned int nbits)
```

Apply map defined by a pair of bitmaps to another bitmap

**Parameters**

- `unsigned long *dst`: remapped result
- `const unsigned long *src`: subset to be remapped
- `const unsigned long *old`: defines domain of map
- `const unsigned long *new`: defines range of map
- `unsigned int nbits`: number of bits in each of these bitmaps

**Description**

Let **old** and **new** define a mapping of bit positions, such that
whatever position is held by the n-th set bit in **old** is mapped
to the n-th set bit in **new**.  In the more general case, allowing
for the possibility that the weight 'w' of **new** is less than the
weight of **old**, map the position of the n-th set bit in **old** to
the position of the m-th set bit in **new**, where m == n % w.

If either of the **old** and **new** bitmaps are empty, or if **src** and
**dst** point to the same location, then this routine copies **src**
to **dst**.

The positions of unset bits in **old** are mapped to themselves
(the identity map).

Apply the above specified mapping to **src**, placing the result in
**dst**, clearing any bits previously set in **dst**.

For example, lets say that **old** has bits 4 through 7 set, and
**new** has bits 12 through 15 set.  This defines the mapping of bit
position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
bit positions unchanged.  So if say **src** comes into this routine
with bits 1, 5 and 7 set, then **dst** should leave with bits 1,
13 and 15 set.

#### <a id="c-bitmap_bitremap"></a>`bitmap_bitremap()`

```c
int bitmap_bitremap(int oldbit, const unsigned long *old, const unsigned long *new, int bits)
```

Apply map defined by a pair of bitmaps to a single bit

**Parameters**

- `int oldbit`: bit position to be mapped
- `const unsigned long *old`: defines domain of map
- `const unsigned long *new`: defines range of map
- `int bits`: number of bits in each of these bitmaps

**Description**

Let **old** and **new** define a mapping of bit positions, such that
whatever position is held by the n-th set bit in **old** is mapped
to the n-th set bit in **new**.  In the more general case, allowing
for the possibility that the weight 'w' of **new** is less than the
weight of **old**, map the position of the n-th set bit in **old** to
the position of the m-th set bit in **new**, where m == n % w.

The positions of unset bits in **old** are mapped to themselves
(the identity map).

Apply the above specified mapping to bit position **oldbit**, returning
the new bit position.

For example, lets say that **old** has bits 4 through 7 set, and
**new** has bits 12 through 15 set.  This defines the mapping of bit
position 4 to 12, 5 to 13, 6 to 14 and 7 to 15, and of all other
bit positions unchanged.  So if say **oldbit** is 5, then this routine
returns 13.

#### <a id="c-bitmap_from_arr32"></a>`bitmap_from_arr32()`

```c
void bitmap_from_arr32(unsigned long *bitmap, const u32 *buf, unsigned int nbits)
```

copy the contents of u32 array of bits to bitmap

**Parameters**

- `unsigned long *bitmap`: array of unsigned longs, the destination bitmap
- `const u32 *buf`: array of u32 (in host byte order), the source bitmap
- `unsigned int nbits`: number of bits in **bitmap**

#### <a id="c-bitmap_to_arr32"></a>`bitmap_to_arr32()`

```c
void bitmap_to_arr32(u32 *buf, const unsigned long *bitmap, unsigned int nbits)
```

copy the contents of bitmap to a u32 array of bits

**Parameters**

- `u32 *buf`: array of u32 (in host byte order), the dest bitmap
- `const unsigned long *bitmap`: array of unsigned longs, the source bitmap
- `unsigned int nbits`: number of bits in **bitmap**

#### <a id="c-bitmap_from_arr64"></a>`bitmap_from_arr64()`

```c
void bitmap_from_arr64(unsigned long *bitmap, const u64 *buf, unsigned int nbits)
```

copy the contents of u64 array of bits to bitmap

**Parameters**

- `unsigned long *bitmap`: array of unsigned longs, the destination bitmap
- `const u64 *buf`: array of u64 (in host byte order), the source bitmap
- `unsigned int nbits`: number of bits in **bitmap**

#### <a id="c-bitmap_to_arr64"></a>`bitmap_to_arr64()`

```c
void bitmap_to_arr64(u64 *buf, const unsigned long *bitmap, unsigned int nbits)
```

copy the contents of bitmap to a u64 array of bits

**Parameters**

- `u64 *buf`: array of u64 (in host byte order), the dest bitmap
- `const unsigned long *bitmap`: array of unsigned longs, the source bitmap
- `unsigned int nbits`: number of bits in **bitmap**



#### <a id="c-bitmap_pos_to_ord"></a>`bitmap_pos_to_ord()`

```c
int bitmap_pos_to_ord(const unsigned long *buf, unsigned int pos, unsigned int nbits)
```

find ordinal of set bit at given position in bitmap

**Parameters**

- `const unsigned long *buf`: pointer to a bitmap
- `unsigned int pos`: a bit position in **buf** (0 \<= **pos** \< **nbits**)
- `unsigned int nbits`: number of valid bit positions in **buf**

**Description**

Map the bit at position **pos** in **buf** (of length **nbits**) to the
ordinal of which set bit it is.  If it is not set or if **pos**
is not a valid bit position, map to -1.

If for example, just bits 4 through 7 are set in **buf**, then **pos**
values 4 through 7 will get mapped to 0 through 3, respectively,
and other **pos** values will get mapped to -1.  When **pos** value 7
gets mapped to (returns) **ord** value 3 in this example, that means
that bit 7 is the 3rd (starting with 0th) set bit in **buf**.

The bit positions 0 through **bits** are valid positions in **buf**.

#### <a id="c-bitmap_onto"></a>`bitmap_onto()`

```c
void bitmap_onto(unsigned long *dst, const unsigned long *orig, const unsigned long *relmap, unsigned int bits)
```

translate one bitmap relative to another

**Parameters**

- `unsigned long *dst`: resulting translated bitmap
- `const unsigned long *orig`: original untranslated bitmap
- `const unsigned long *relmap`: bitmap relative to which translated
- `unsigned int bits`: number of bits in each of these bitmaps

**Description**

Set the n-th bit of **dst** iff there exists some m such that the
n-th bit of **relmap** is set, the m-th bit of **orig** is set, and
the n-th bit of **relmap** is also the m-th _set_ bit of **relmap**.
(If you understood the previous sentence the first time your
read it, you're overqualified for your current job.)

In other words, **orig** is mapped onto (surjectively) **dst**,
using the map { \<n, m> | the n-th bit of **relmap** is the
m-th set bit of **relmap** }.

Any set bits in **orig** above bit number W, where W is the
weight of (number of set bits in) **relmap** are mapped nowhere.
In particular, if for all bits m set in **orig**, m >= W, then
**dst** will end up empty.  In situations where the possibility
of such an empty result is not desired, one way to avoid it is
to use the [`bitmap_fold()`](#c-bitmap_fold) operator, below, to first fold the
**orig** bitmap over itself so that all its set bits x are in the
range 0 \<= x \< W.  The [`bitmap_fold()`](#c-bitmap_fold) operator does this by
setting the bit (m % W) in **dst**, for each bit (m) set in **orig**.

- Example \[1\] for [`bitmap_onto()`](#c-bitmap_onto):
  Let's say **relmap** has bits 30-39 set, and **orig** has bits
  1, 3, 5, 7, 9 and 11 set.  Then on return from this routine,
  **dst** will have bits 31, 33, 35, 37 and 39 set.

  When bit 0 is set in **orig**, it means turn on the bit in
  **dst** corresponding to whatever is the first bit (if any)
  that is turned on in **relmap**.  Since bit 0 was off in the
  above example, we leave off that bit (bit 30) in **dst**.

  When bit 1 is set in **orig** (as in the above example), it
  means turn on the bit in **dst** corresponding to whatever
  is the second bit that is turned on in **relmap**.  The second
  bit in **relmap** that was turned on in the above example was
  bit 31, so we turned on bit 31 in **dst**.

  Similarly, we turned on bits 33, 35, 37 and 39 in **dst**,
  because they were the 4th, 6th, 8th and 10th set bits
  set in **relmap**, and the 4th, 6th, 8th and 10th bits of
  **orig** (i.e. bits 3, 5, 7 and 9) were also set.

  When bit 11 is set in **orig**, it means turn on the bit in
  **dst** corresponding to whatever is the twelfth bit that is
  turned on in **relmap**.  In the above example, there were
  only ten bits turned on in **relmap** (30..39), so that bit
  11 was set in **orig** had no affect on **dst**.

- Example \[2\] for [`bitmap_fold()`](#c-bitmap_fold) + [`bitmap_onto()`](#c-bitmap_onto):
  Let's say **relmap** has these ten bits set:

```text
40 41 42 43 45 48 53 61 74 95
```

(for the curious, that's 40 plus the first ten terms of the
Fibonacci sequence.)

Further lets say we use the following code, invoking
[`bitmap_fold()`](#c-bitmap_fold) then bitmap_onto, as suggested above to
avoid the possibility of an empty **dst** result:

```text
unsigned long *tmp;     // a temporary bitmap's bits

bitmap_fold(tmp, orig, bitmap_weight(relmap, bits), bits);
bitmap_onto(dst, tmp, relmap, bits);
```

Then this table shows what various values of **dst** would be, for
various **orig**'s.  I list the zero-based positions of each set bit.
The tmp column shows the intermediate result, as computed by
using [`bitmap_fold()`](#c-bitmap_fold) to fold the **orig** bitmap modulo ten
(the weight of **relmap**):

```text
=============== ============== =================
@orig           tmp            @dst
0                0             40
1                1             41
9                9             95
10               0             40 [#f1]_
1 3 5 7          1 3 5 7       41 43 48 61
0 1 2 3 4        0 1 2 3 4     40 41 42 43 45
0 9 18 27        0 9 8 7       40 61 74 95
0 10 20 30       0             40
0 11 22 33       0 1 2 3       40 41 42 43
0 12 24 36       0 2 4 6       40 42 45 53
78 102 211       1 2 8         41 42 74 [#f1]_
=============== ============== =================
```

If either of **orig** or **relmap** is empty (no set bits), then **dst**
will be returned empty.

If (as explained above) the only set bits in **orig** are in positions
m where m >= W, (where W is the weight of **relmap**) then **dst** will
once again be returned empty.

All bits in **dst** not set by the above rule are cleared.

#### <a id="c-bitmap_fold"></a>`bitmap_fold()`

```c
void bitmap_fold(unsigned long *dst, const unsigned long *orig, unsigned int sz, unsigned int nbits)
```

fold larger bitmap into smaller, modulo specified size

**Parameters**

- `unsigned long *dst`: resulting smaller bitmap
- `const unsigned long *orig`: original larger bitmap
- `unsigned int sz`: specified size
- `unsigned int nbits`: number of bits in each of these bitmaps

**Description**

For each bit oldbit in **orig**, set bit oldbit mod **sz** in **dst**.
Clear all other bits in **dst**.  See further the comment and
Example \[2\] for [`bitmap_onto()`](#c-bitmap_onto) for why and how to use this.



#### <a id="c-bitmap_find_next_zero_area"></a>`bitmap_find_next_zero_area()`

```c
unsigned long bitmap_find_next_zero_area(unsigned long *map, unsigned long size, unsigned long start, unsigned int nr, unsigned long align_mask)
```

find a contiguous aligned zero area

**Parameters**

- `unsigned long *map`: The address to base the search on
- `unsigned long size`: The bitmap size in bits
- `unsigned long start`: The bitnumber to start searching at
- `unsigned int nr`: The number of zeroed bits we're looking for
- `unsigned long align_mask`: Alignment mask for zero area

**Description**

The **align_mask** should be one less than a power of 2; the effect is that
the bit offset of all zero areas this function finds is multiples of that
power of 2. A **align_mask** of 0 means no alignment is required.

#### <a id="c-bitmap_or_equal"></a>`bitmap_or_equal()`

```c
bool bitmap_or_equal(const unsigned long *src1, const unsigned long *src2, const unsigned long *src3, unsigned int nbits)
```

Check whether the or of two bitmaps is equal to a third

**Parameters**

- `const unsigned long *src1`: Pointer to bitmap 1
- `const unsigned long *src2`: Pointer to bitmap 2 will be or'ed with bitmap 1
- `const unsigned long *src3`: Pointer to bitmap 3. Compare to the result of **\*src1** | **\*src2**
- `unsigned int nbits`: number of bits in each of these bitmaps

**Return**

True if (**\*src1** | **\*src2**) == **\*src3**, false otherwise

#### <a id="c-bitmap_scatter"></a>`bitmap_scatter()`

```c
void bitmap_scatter(unsigned long *dst, const unsigned long *src, const unsigned long *mask, unsigned int nbits)
```

Scatter a bitmap according to the given mask

**Parameters**

- `unsigned long *dst`: scattered bitmap
- `const unsigned long *src`: gathered bitmap
- `const unsigned long *mask`: mask representing bits to assign to in the scattered bitmap
- `unsigned int nbits`: number of bits in each of these bitmaps

**Description**

Scatters bitmap with sequential bits according to the given **mask**.

**Example**

If **src** bitmap = 0x005a, with **mask** = 0x1313, **dst** will be 0x0302.

Or in binary form
**src**                 **mask**                   **dst**
0000000001011010     0001001100010011        0000001100000010

(Bits 0, 1, 2, 3, 4, 5 are copied to the bits 0, 1, 4, 8, 9, 12)

A more 'visual' description of the operation:

```text
src:  0000000001011010
                ||||||
         +------+|||||
         |  +----+||||
         |  |+----+|||
         |  ||   +-+||
         |  ||   |  ||
mask: ...v..vv...v..vv
      ...0..11...0..10
dst:  0000001100000010
```

A relationship exists between [`bitmap_scatter()`](#c-bitmap_scatter) and [`bitmap_gather()`](#c-bitmap_gather). See
[`bitmap_gather()`](#c-bitmap_gather) for the bitmap gather detailed operations. TL;DR:
[`bitmap_gather()`](#c-bitmap_gather) can be seen as the 'reverse' [`bitmap_scatter()`](#c-bitmap_scatter) operation.

#### <a id="c-bitmap_gather"></a>`bitmap_gather()`

```c
void bitmap_gather(unsigned long *dst, const unsigned long *src, const unsigned long *mask, unsigned int nbits)
```

Gather a bitmap according to given mask

**Parameters**

- `unsigned long *dst`: gathered bitmap
- `const unsigned long *src`: scattered bitmap
- `const unsigned long *mask`: mask representing bits to extract from in the scattered bitmap
- `unsigned int nbits`: number of bits in each of these bitmaps

**Description**

Gathers bitmap with sparse bits according to the given **mask**.

**Example**

If **src** bitmap = 0x0302, with **mask** = 0x1313, **dst** will be 0x001a.

Or in binary form
**src**                 **mask**                   **dst**
0000001100000010     0001001100010011        0000000000011010

(Bits 0, 1, 4, 8, 9, 12 are copied to the bits 0, 1, 2, 3, 4, 5)

A more 'visual' description of the operation:

```text
mask: ...v..vv...v..vv
src:  0000001100000010
         ^  ^^   ^   0
         |  ||   |  10
         |  ||   > 010
         |  |+--> 1010
         |  +--> 11010
         +----> 011010
dst:  0000000000011010
```

A relationship exists between [`bitmap_gather()`](#c-bitmap_gather) and [`bitmap_scatter()`](#c-bitmap_scatter). See
[`bitmap_scatter()`](#c-bitmap_scatter) for the bitmap scatter detailed operations. TL;DR:
[`bitmap_scatter()`](#c-bitmap_scatter) can be seen as the 'reverse' [`bitmap_gather()`](#c-bitmap_gather) operation.

Suppose scattered computed using bitmap_scatter(scattered, src, mask, n).
The operation bitmap_gather(result, scattered, mask, n) leads to a result
equal or equivalent to src.

The result can be 'equivalent' because [`bitmap_scatter()`](#c-bitmap_scatter) and [`bitmap_gather()`](#c-bitmap_gather)
are not bijective.
The result and src values are equivalent in that sense that a call to
bitmap_scatter(res, src, mask, n) and a call to
bitmap_scatter(res, result, mask, n) will lead to the same res value.

#### <a id="c-bitmap_release_region"></a>`bitmap_release_region()`

```c
void bitmap_release_region(unsigned long *bitmap, unsigned int pos, int order)
```

release allocated bitmap region

**Parameters**

- `unsigned long *bitmap`: array of unsigned longs corresponding to the bitmap
- `unsigned int pos`: beginning of bit region to release
- `int order`: region size (log base 2 of number of bits) to release

**Description**

This is the complement to `__bitmap_find_free_region()` and releases
the found region (by clearing it in the bitmap).

#### <a id="c-bitmap_allocate_region"></a>`bitmap_allocate_region()`

```c
int bitmap_allocate_region(unsigned long *bitmap, unsigned int pos, int order)
```

allocate bitmap region

**Parameters**

- `unsigned long *bitmap`: array of unsigned longs corresponding to the bitmap
- `unsigned int pos`: beginning of bit region to allocate
- `int order`: region size (log base 2 of number of bits) to allocate

**Description**

Allocate (set bits in) a specified region of a bitmap.

**Return**

0 on success, or `-EBUSY` if specified region wasn't
free (not all bits were zero).

#### <a id="c-bitmap_find_free_region"></a>`bitmap_find_free_region()`

```c
int bitmap_find_free_region(unsigned long *bitmap, unsigned int bits, int order)
```

find a contiguous aligned mem region

**Parameters**

- `unsigned long *bitmap`: array of unsigned longs corresponding to the bitmap
- `unsigned int bits`: number of bits in the bitmap
- `int order`: region size (log base 2 of number of bits) to find

**Description**

Find a region of free (zero) bits in a **bitmap** of **bits** bits and
allocate them (set them to one).  Only consider regions of length
a power (**order**) of two, aligned to that power of two, which
makes the search algorithm much faster.

**Return**

the bit offset in bitmap of the allocated region,
or -errno on failure.

#### <a id="c-BITMAP_FROM_U64"></a>`BITMAP_FROM_U64()`

```c
BITMAP_FROM_U64(n)
```

Represent u64 value in the format suitable for bitmap.

**Parameters**

- `n`: u64 value

**Description**

Linux bitmaps are internally arrays of unsigned longs, i.e. 32-bit
integers in 32-bit environment, and 64-bit integers in 64-bit one.

There are four combinations of endianness and length of the word in linux
ABIs: LE64, BE64, LE32 and BE32.

On 64-bit kernels 64-bit LE and BE numbers are naturally ordered in
bitmaps and therefore don't require any special handling.

On 32-bit kernels 32-bit LE ABI orders lo word of 64-bit number in memory
prior to hi, and 32-bit BE orders hi word prior to lo. The bitmap on the
other hand is represented as an array of 32-bit words and the position of
bit N may therefore be calculated as: word #(N/32) and bit #(N`32`) in that
word.  For example, bit #42 is located at 10th position of 2nd word.
It matches 32-bit LE ABI, and we can simply let the compiler store 64-bit
values in memory as it usually does. But for BE we need to swap hi and lo
words manually.

With all that, the macro [`BITMAP_FROM_U64()`](#c-BITMAP_FROM_U64) does explicit reordering of hi and
lo parts of u64.  For LE32 it does nothing, and for BE environment it swaps
hi and lo words, as is expected by bitmap.

#### <a id="c-bitmap_from_u64"></a>`bitmap_from_u64()`

```c
void bitmap_from_u64(unsigned long *dst, u64 mask)
```

Check and swap words within u64.

**Parameters**

- `unsigned long *dst`: destination bitmap
- `u64 mask`: source bitmap

**Description**

In 32-bit Big Endian kernel, when using `(u32 *)(&val)[*]`
to read u64 mask, we will get the wrong word.
That is `(u32 *)(&val)[0]` gets the upper 32 bits,
but we expect the lower 32-bits of u64.

#### <a id="c-bitmap_read"></a>`bitmap_read()`

```c
unsigned long bitmap_read(const unsigned long *map, unsigned long start, unsigned long nbits)
```

read a value of n-bits from the memory region

**Parameters**

- `const unsigned long *map`: address to the bitmap memory region
- `unsigned long start`: bit offset of the n-bit value
- `unsigned long nbits`: size of value in bits, nonzero, up to BITS_PER_LONG

**Return**

value of **nbits** bits located at the **start** bit offset within the
**map** memory region. For **nbits** = 0 and **nbits** > BITS_PER_LONG the return
value is undefined.

#### <a id="c-bitmap_write"></a>`bitmap_write()`

```c
void bitmap_write(unsigned long *map, unsigned long value, unsigned long start, unsigned long nbits)
```

write n-bit value within a memory region

**Parameters**

- `unsigned long *map`: address to the bitmap memory region
- `unsigned long value`: value to write, clamped to nbits
- `unsigned long start`: bit offset of the n-bit value
- `unsigned long nbits`: size of value in bits, nonzero, up to BITS_PER_LONG.

**Description**

[`bitmap_write()`](#c-bitmap_write) behaves as-if implemented as **nbits** calls of `__assign_bit()`,
i.e. bits beyond **nbits** are ignored:

- for (bit = 0; bit \< nbits; bit++)

  __assign_bit(start + bit, bitmap, val & BIT(bit));

For **nbits** == 0 and **nbits** > BITS_PER_LONG no writes are performed.


<a id="rst-command-line-parsing"></a>

### Command-line Parsing


#### <a id="c-get_option"></a>`get_option()`

```c
int get_option(char **str, int *pint)
```

Parse integer from an option string

**Parameters**

- `char **str`: option string
- `int *pint`: (optional output) integer value parsed from **str**

**Description**

Read an int from an option string; if available accept a subsequent
comma as well.

When **pint** is NULL the function can be used as a validator of
the current option in the string.

Return values:
0 - no int in string
1 - int found, no subsequent comma
2 - int found including a subsequent comma
3 - hyphen found to denote a range

Leading hyphen without integer is no integer case, but we consume it
for the sake of simplification.

#### <a id="c-get_options"></a>`get_options()`

```c
char * get_options(const char *str, int nints, int *ints)
```

Parse a string into a list of integers

**Parameters**

- `const char *str`: String to be parsed
- `int nints`: size of integer array
- `int *ints`: integer array (must have room for at least one element)

**Description**

This function parses a string containing a comma-separated
list of integers, a hyphen-separated range of _positive_ integers,
or a combination of both.  The parse halts when the array is
full, or when no more numbers can be retrieved from the
string.

When **nints** is 0, the function just validates the given **str** and
returns the amount of parseable integers as described below.

The first element is filled by the number of collected integers
in the range. The rest is what was parsed from the **str**.

Return value is the character in the string which caused
the parse to end (typically a null terminator, if **str** is
completely parseable).

#### <a id="c-memparse"></a>`memparse()`

```c
unsigned long long memparse(const char *ptr, char **retptr)
```

parse a string with mem suffixes into a number

**Parameters**

- `const char *ptr`: Where parse begins
- `char **retptr`: (output) Optional pointer to next char after parse completes

**Description**

Parses a string into a number.  The number stored at **ptr** is
potentially suffixed with K, M, G, T, P, E.


<a id="rst-error-pointers"></a>

### Error Pointers


#### <a id="c-IS_ERR_VALUE"></a>`IS_ERR_VALUE()`

```c
IS_ERR_VALUE(x)
```

Detect an error pointer.

**Parameters**

- `x`: The pointer to check.

**Description**

Like [`IS_ERR()`](#c-IS_ERR), but does not generate a compiler warning if result is unused.

#### <a id="c-ERR_PTR"></a>`ERR_PTR()`

```c
void * ERR_PTR(long error)
```

Create an error pointer.

**Parameters**

- `long error`: A negative error code.

**Description**

Encodes **error** into a pointer value. Users should consider the result
opaque and not assume anything about how the error is encoded.

**Return**

A pointer with **error** encoded within its value.

#### <a id="c-INIT_ERR_PTR"></a>`INIT_ERR_PTR()`

```c
INIT_ERR_PTR(error)
```

Init a const error pointer.

**Parameters**

- `error`: A negative error code.

**Description**

Like [`ERR_PTR()`](#c-ERR_PTR), but usable to initialize static variables.

#### <a id="c-PTR_ERR"></a>`PTR_ERR()`

```c
long PTR_ERR(__force const void *ptr)
```

Extract the error code from an error pointer.

**Parameters**

- `__force const void *ptr`: An error pointer.

**Return**

The error code within **ptr**.

#### <a id="c-IS_ERR"></a>`IS_ERR()`

```c
bool IS_ERR(__force const void *ptr)
```

Detect an error pointer.

**Parameters**

- `__force const void *ptr`: The pointer to check.

**Return**

true if **ptr** is an error pointer, false otherwise.

#### <a id="c-IS_ERR_OR_NULL"></a>`IS_ERR_OR_NULL()`

```c
bool IS_ERR_OR_NULL(__force const void *ptr)
```

Detect an error pointer or a null pointer.

**Parameters**

- `__force const void *ptr`: The pointer to check.

**Description**

Like [`IS_ERR()`](#c-IS_ERR), but also returns true for a null pointer.

#### <a id="c-ERR_CAST"></a>`ERR_CAST()`

```c
void * ERR_CAST(__force const void *ptr)
```

Explicitly cast an error-valued pointer to another pointer type

**Parameters**

- `__force const void *ptr`: The pointer to cast.

**Description**

Explicitly cast an error-valued pointer to another pointer type in such a
way as to make it clear that's what's going on.

#### <a id="c-PTR_ERR_OR_ZERO"></a>`PTR_ERR_OR_ZERO()`

```c
int PTR_ERR_OR_ZERO(__force const void *ptr)
```

Extract the error code from a pointer if it has one.

**Parameters**

- `__force const void *ptr`: A potential error pointer.

**Description**

Convenience function that can be used inside a function that returns
an error code to propagate errors received as error pointers.
For example, `return PTR_ERR_OR_ZERO(ptr);` replaces:

```c
if (IS_ERR(ptr))
        return PTR_ERR(ptr);
else
        return 0;
```

**Return**

The error code within **ptr** if it is an error pointer; 0 otherwise.


<a id="rst-sorting"></a>

### Sorting


#### <a id="c-sort_r"></a>`sort_r()`

```c
void sort_r(void *base, size_t num, size_t size, cmp_r_func_t cmp_func, swap_r_func_t swap_func, const void *priv)
```

sort an array of elements

**Parameters**

- `void *base`: pointer to data to sort
- `size_t num`: number of elements
- `size_t size`: size of each element
- `cmp_r_func_t cmp_func`: pointer to comparison function
- `swap_r_func_t swap_func`: pointer to swap function or NULL
- `const void *priv`: third argument passed to comparison function

**Description**

This function does a heapsort on the given array.  You may provide
a swap_func function if you need to do something more than a memory
copy (e.g. fix up pointers or auxiliary data), but the built-in swap
avoids a slow retpoline and so is significantly faster.

The comparison function must adhere to specific mathematical
properties to ensure correct and stable sorting:
- Antisymmetry: cmp_func(a, b) must return the opposite sign of
cmp_func(b, a).
- Transitivity: if cmp_func(a, b) \<= 0 and cmp_func(b, c) \<= 0, then
cmp_func(a, c) \<= 0.

Sorting time is O(n log n) both on average and worst-case. While
quicksort is slightly faster on average, it suffers from exploitable
O(n*n) worst-case behavior and extra memory requirements that make
it less suitable for kernel use.

#### <a id="c-sort_r_nonatomic"></a>`sort_r_nonatomic()`

```c
void sort_r_nonatomic(void *base, size_t num, size_t size, cmp_r_func_t cmp_func, swap_r_func_t swap_func, const void *priv)
```

sort an array of elements, with cond_resched

**Parameters**

- `void *base`: pointer to data to sort
- `size_t num`: number of elements
- `size_t size`: size of each element
- `cmp_r_func_t cmp_func`: pointer to comparison function
- `swap_r_func_t swap_func`: pointer to swap function or NULL
- `const void *priv`: third argument passed to comparison function

**Description**

Same as sort_r, but preferred for larger arrays as it does a periodic
`cond_resched()`.



#### <a id="c-list_sort"></a>`list_sort()`

```c
void list_sort(void *priv, struct list_head *head, list_cmp_func_t cmp)
```

sort a list

**Parameters**

- `void *priv`: private data, opaque to [`list_sort()`](#c-list_sort), passed to **cmp**
- `struct list_head *head`: the list to sort
- `list_cmp_func_t cmp`: the elements comparison function

**Description**

The comparison function **cmp** must return > 0 if **a** should sort after
**b** ("**a** > **b**" if you want an ascending sort), and \<= 0 if **a** should
sort before **b** *or* their original order should be preserved.  It is
always called with the element that came first in the input in **a**,
and list_sort is a stable sort, so it is not necessary to distinguish
the **a** \< **b** and **a** == **b** cases.

The comparison function must adhere to specific mathematical properties
to ensure correct and stable sorting:
- Antisymmetry: cmp(**a**, **b**) must return the opposite sign of
cmp(**b**, **a**).
- Transitivity: if cmp(**a**, **b**) \<= 0 and cmp(**b**, **c**) \<= 0, then
cmp(**a**, **c**) \<= 0.

This is compatible with two styles of **cmp** function:
- The traditional style which returns \<0 / =0 / >0, or
- Returning a boolean 0/1.
The latter offers a chance to save a few cycles in the comparison
(which is used by e.g. `plug_ctx_cmp()` in block/blk-mq.c).

A good way to write a multi-word comparison is:

```text
if (a->high != b->high)
        return a->high > b->high;
if (a->middle != b->middle)
        return a->middle > b->middle;
return a->low > b->low;
```

This mergesort is as eager as possible while always performing at least
2:1 balanced merges.  Given two pending sublists of size 2^k, they are
merged to a size-2^(k+1) list as soon as we have 2^k following elements.

Thus, it will avoid cache thrashing as long as 3*2^k elements can
fit into the cache.  Not quite as good as a fully-eager bottom-up
mergesort, but it does use 0.2*n fewer comparisons, so is faster in
the common case that everything fits into L1.

The merging is controlled by "count", the number of elements in the
pending lists.  This is beautifully simple code, but rather subtle.

Each time we increment "count", we set one bit (bit k) and clear
bits k-1 .. 0.  Each time this happens (except the very first time
for each bit, when count increments to 2^k), we merge two lists of
size 2^k into one list of size 2^(k+1).

This merge happens exactly when the count reaches an odd multiple of
2^k, which is when we have 2^k elements pending in smaller lists,
so it's safe to merge away two lists of size 2^k.

After this happens twice, we have created two lists of size 2^(k+1),
which will be merged into a list of size 2^(k+2) before we create
a third list of size 2^(k+1), so there are never more than two pending.

The number of pending lists of size 2^k is determined by the
state of bit k of "count" plus two extra pieces of information:

- The state of bit k-1 (when k == 0, consider bit -1 always set), and
- Whether the higher-order bits are zero or non-zero (i.e.
  is count >= 2^(k+1)).

There are six states we distinguish.  "x" represents some arbitrary
bits, and "y" represents some arbitrary non-zero bits:
0:  00x: 0 pending of size 2^k;           x pending of sizes \< 2^k
1:  01x: 0 pending of size 2^k; 2^(k-1) + x pending of sizes \< 2^k
2: x10x: 0 pending of size 2^k; 2^k     + x pending of sizes \< 2^k
3: x11x: 1 pending of size 2^k; 2^(k-1) + x pending of sizes \< 2^k
4: y00x: 1 pending of size 2^k; 2^k     + x pending of sizes \< 2^k
5: y01x: 2 pending of size 2^k; 2^(k-1) + x pending of sizes \< 2^k
(merge and loop back to state 2)

We gain lists of size 2^k in the 2->3 and 4->5 transitions (because
bit k-1 is set while the more significant bits are non-zero) and
merge them away in the 5->2 transition.  Note in particular that just
before the 5->2 transition, all lower-order bits are 11 (state 3),
so there is one list of each smaller size.

When we reach the end of the input, we merge all the pending
lists, from smallest to largest.  If you work through cases 2 to
5 above, you can see that the number of elements we merge with a list
of size 2^k varies from 2^(k-1) (cases 3 and 5 when x == 0) to
2^(k+1) - 1 (second merge of case 5 when x == 2^(k-1) - 1).


<a id="rst-text-searching"></a>

### Text Searching


INTRODUCTION

The textsearch infrastructure provides text searching facilities for
both linear and non-linear data. Individual search algorithms are
implemented in modules and chosen by the user.

ARCHITECTURE

```none
  User
  +----------------+
  |        finish()|<--------------(6)-----------------+
  |get_next_block()|<--------------(5)---------------+ |
  |                |                     Algorithm   | |
  |                |                    +------------------------------+
  |                |                    |  init()   find()   destroy() |
  |                |                    +------------------------------+
  |                |       Core API           ^       ^          ^
  |                |      +---------------+  (2)     (4)        (8)
  |             (1)|----->| prepare()     |---+       |          |
  |             (3)|----->| find()/next() |-----------+          |
  |             (7)|----->| destroy()     |----------------------+
  +----------------+      +---------------+

(1) User configures a search by calling textsearch_prepare() specifying
    the search parameters such as the pattern and algorithm name.
(2) Core requests the algorithm to allocate and initialize a search
    configuration according to the specified parameters.
(3) User starts the search(es) by calling textsearch_find() or
    textsearch_next() to fetch subsequent occurrences. A state variable
    is provided to the algorithm to store persistent variables.
(4) Core eventually resets the search offset and forwards the find()
    request to the algorithm.
(5) Algorithm calls get_next_block() provided by the user continuously
    to fetch the data to be searched in block by block.
(6) Algorithm invokes finish() after the last call to get_next_block
    to clean up any leftovers from get_next_block. (Optional)
(7) User destroys the configuration by calling textsearch_destroy().
(8) Core notifies the algorithm to destroy algorithm specific
    allocations. (Optional)
```

USAGE

Before a search can be performed, a configuration must be created
by calling [`textsearch_prepare()`](#c-textsearch_prepare) specifying the searching algorithm,
the pattern to look for and flags. As a flag, you can set TS_IGNORECASE
to perform case insensitive matching. But it might slow down
performance of algorithm, so you should use it at own your risk.
The returned configuration may then be used for an arbitrary
amount of times and even in parallel as long as a separate struct
ts_state variable is provided to every instance.

The actual search is performed by either calling
[`textsearch_find_continuous()`](#c-textsearch_find_continuous) for linear data or by providing
an own `get_next_block()` implementation and
calling [`textsearch_find()`](#c-textsearch_find). Both functions return
the position of the first occurrence of the pattern or UINT_MAX if
no match was found. Subsequent occurrences can be found by calling
[`textsearch_next()`](#c-textsearch_next) regardless of the linearity of the data.

Once you're done using a configuration it must be given back via
textsearch_destroy.

EXAMPLE:

```text
int pos;
struct ts_config *conf;
struct ts_state state;
const char *pattern = "chicken";
const char *example = "We dance the funky chicken";

conf = textsearch_prepare("kmp", pattern, strlen(pattern),
                          GFP_KERNEL, TS_AUTOLOAD);
if (IS_ERR(conf)) {
    err = PTR_ERR(conf);
    goto errout;
}

pos = textsearch_find_continuous(conf, &state, example, strlen(example));
if (pos != UINT_MAX)
    panic("Oh my god, dancing chickens at %d\n", pos);

textsearch_destroy(conf);
```



#### <a id="c-textsearch_register"></a>`textsearch_register()`

```c
int textsearch_register(struct ts_ops *ops)
```

register a textsearch module

**Parameters**

- `struct ts_ops *ops`: operations lookup table

**Description**

This function must be called by textsearch modules to announce
their presence. The specified &**ops** must have `name` set to a
unique identifier and the callbacks `find()`, `init()`, `get_pattern()`,
and `get_pattern_len()` must be implemented.

Returns 0 or -EEXISTS if another module has already registered
with same name.

#### <a id="c-textsearch_unregister"></a>`textsearch_unregister()`

```c
int textsearch_unregister(struct ts_ops *ops)
```

unregister a textsearch module

**Parameters**

- `struct ts_ops *ops`: operations lookup table

**Description**

This function must be called by textsearch modules to announce
their disappearance for examples when the module gets unloaded.
The `ops` parameter must be the same as the one during the
registration.

Returns 0 on success or -ENOENT if no matching textsearch
registration was found.

#### <a id="c-textsearch_find_continuous"></a>`textsearch_find_continuous()`

```c
unsigned int textsearch_find_continuous(struct ts_config *conf, struct ts_state *state, const void *data, unsigned int len)
```

search a pattern in continuous/linear data

**Parameters**

- `struct ts_config *conf`: search configuration
- `struct ts_state *state`: search state
- `const void *data`: data to search in
- `unsigned int len`: length of data

**Description**

A simplified version of [`textsearch_find()`](#c-textsearch_find) for continuous/linear data.
Call [`textsearch_next()`](#c-textsearch_next) to retrieve subsequent matches.

Returns the position of first occurrence of the pattern or
`UINT_MAX` if no occurrence was found.

#### <a id="c-textsearch_prepare"></a>`textsearch_prepare()`

```c
struct ts_config * textsearch_prepare(const char *algo, const void *pattern, unsigned int len, gfp_t gfp_mask, int flags)
```

Prepare a search

**Parameters**

- `const char *algo`: name of search algorithm
- `const void *pattern`: pattern data
- `unsigned int len`: length of pattern
- `gfp_t gfp_mask`: allocation mask
- `int flags`: search flags

**Description**

Looks up the search algorithm module and creates a new textsearch
configuration for the specified pattern.

**Note**

- The format of the pattern may not be compatible between

  the various search algorithms.

Returns a new textsearch configuration according to the specified
parameters or a [`ERR_PTR()`](#c-ERR_PTR). If a zero length pattern is passed, this
function returns EINVAL.

#### <a id="c-textsearch_destroy"></a>`textsearch_destroy()`

```c
void textsearch_destroy(struct ts_config *conf)
```

destroy a search configuration

**Parameters**

- `struct ts_config *conf`: search configuration

**Description**

Releases all references of the configuration and frees
up the memory.



#### <a id="c-textsearch_next"></a>`textsearch_next()`

```c
unsigned int textsearch_next(struct ts_config *conf, struct ts_state *state)
```

continue searching for a pattern

**Parameters**

- `struct ts_config *conf`: search configuration
- `struct ts_state *state`: search state

**Description**

Continues a search looking for more occurrences of the pattern.
[`textsearch_find()`](#c-textsearch_find) must be called to find the first occurrence
in order to reset the state.

Returns the position of the next occurrence of the pattern or
UINT_MAX if not match was found.

#### <a id="c-textsearch_find"></a>`textsearch_find()`

```c
unsigned int textsearch_find(struct ts_config *conf, struct ts_state *state)
```

start searching for a pattern

**Parameters**

- `struct ts_config *conf`: search configuration
- `struct ts_state *state`: search state

**Description**

Returns the position of first occurrence of the pattern or
UINT_MAX if no match was found.

#### <a id="c-textsearch_get_pattern"></a>`textsearch_get_pattern()`

```c
void * textsearch_get_pattern(struct ts_config *conf)
```

return head of the pattern

**Parameters**

- `struct ts_config *conf`: search configuration

#### <a id="c-textsearch_get_pattern_len"></a>`textsearch_get_pattern_len()`

```c
unsigned int textsearch_get_pattern_len(struct ts_config *conf)
```

return length of the pattern

**Parameters**

- `struct ts_config *conf`: search configuration


<a id="rst-crc-and-math-functions-in-linux"></a>

## CRC and Math Functions in Linux

<a id="rst-arithmetic-overflow-checking"></a>

### Arithmetic Overflow Checking


#### <a id="c-check_add_overflow"></a>`check_add_overflow()`

```c
check_add_overflow(a, b, d)
```

Calculate addition with overflow checking

**Parameters**

- `a`: first addend
- `b`: second addend
- `d`: pointer to store sum

**Description**

Returns true on wrap-around, false otherwise.

**\*d** holds the results of the attempted addition, regardless of whether
wrap-around occurred.

#### <a id="c-wrapping_add"></a>`wrapping_add()`

```c
wrapping_add(type, a, b)
```

Intentionally perform a wrapping addition

**Parameters**

- `type`: type for result of calculation
- `a`: first addend
- `b`: second addend

**Description**

Return the potentially wrapped-around addition without
tripping any wrap-around sanitizers that may be enabled.

#### <a id="c-wrapping_assign_add"></a>`wrapping_assign_add()`

```c
wrapping_assign_add(var, offset)
```

Intentionally perform a wrapping increment assignment

**Parameters**

- `var`: variable to be incremented
- `offset`: amount to add

**Description**

Increments **var** by **offset** with wrap-around. Returns the resulting
value of **var**. Will not trip any wrap-around sanitizers.

Returns the new value of **var**.

#### <a id="c-check_sub_overflow"></a>`check_sub_overflow()`

```c
check_sub_overflow(a, b, d)
```

Calculate subtraction with overflow checking

**Parameters**

- `a`: minuend; value to subtract from
- `b`: subtrahend; value to subtract from **a**
- `d`: pointer to store difference

**Description**

Returns true on wrap-around, false otherwise.

**\*d** holds the results of the attempted subtraction, regardless of whether
wrap-around occurred.

#### <a id="c-wrapping_sub"></a>`wrapping_sub()`

```c
wrapping_sub(type, a, b)
```

Intentionally perform a wrapping subtraction

**Parameters**

- `type`: type for result of calculation
- `a`: minuend; value to subtract from
- `b`: subtrahend; value to subtract from **a**

**Description**

Return the potentially wrapped-around subtraction without
tripping any wrap-around sanitizers that may be enabled.

#### <a id="c-wrapping_assign_sub"></a>`wrapping_assign_sub()`

```c
wrapping_assign_sub(var, offset)
```

Intentionally perform a wrapping decrement assign

**Parameters**

- `var`: variable to be decremented
- `offset`: amount to subtract

**Description**

Decrements **var** by **offset** with wrap-around. Returns the resulting
value of **var**. Will not trip any wrap-around sanitizers.

Returns the new value of **var**.

#### <a id="c-check_mul_overflow"></a>`check_mul_overflow()`

```c
check_mul_overflow(a, b, d)
```

Calculate multiplication with overflow checking

**Parameters**

- `a`: first factor
- `b`: second factor
- `d`: pointer to store product

**Description**

Returns true on wrap-around, false otherwise.

**\*d** holds the results of the attempted multiplication, regardless of whether
wrap-around occurred.

#### <a id="c-wrapping_mul"></a>`wrapping_mul()`

```c
wrapping_mul(type, a, b)
```

Intentionally perform a wrapping multiplication

**Parameters**

- `type`: type for result of calculation
- `a`: first factor
- `b`: second factor

**Description**

Return the potentially wrapped-around multiplication without
tripping any wrap-around sanitizers that may be enabled.

#### <a id="c-check_shl_overflow"></a>`check_shl_overflow()`

```c
check_shl_overflow(a, s, d)
```

Calculate a left-shifted value and check overflow

**Parameters**

- `a`: Value to be shifted
- `s`: How many bits left to shift
- `d`: Pointer to where to store the result

**Description**

Computes **\*d** = (**a** \<\< **s**)

Returns true if '**\*d**' cannot hold the result or when '**a** \<\< **s**' doesn't
make sense. Example conditions:

- '**a** \<\< **s**' causes bits to be lost when stored in **\*d**.
- '**s**' is garbage (e.g. negative) or so large that the result of
  '**a** \<\< **s**' is guaranteed to be 0.
- '**a**' is negative.
- '**a** \<\< **s**' sets the sign bit, if any, in '**\*d**'.

'**\*d**' will hold the results of the attempted shift, but is not
considered "safe for use" if true is returned.

#### <a id="c-overflows_type"></a>`overflows_type()`

```c
overflows_type(n, T)
```

helper for checking the overflows between value, variables, or data type

**Parameters**

- `n`: source constant value or variable to be checked
- `T`: destination variable or data type proposed to store **x**

**Description**

Compares the **x** expression for whether or not it can safely fit in
the storage of the type in **T**. **x** and **T** can have different types.
If **x** is a constant expression, this will also resolve to a constant
expression.

**Return**

true if overflow can occur, false otherwise.

#### <a id="c-range_overflows"></a>`range_overflows()`

```c
range_overflows(start, size, max)
```

Check if a range is out of bounds

**Parameters**

- `start`: Start of the range.
- `size`: Size of the range.
- `max`: Exclusive upper boundary.

**Description**

A strict check to determine if the range \[**start**, **start** + **size**) is
invalid with respect to the allowable range \[0, **max**). Any range
starting at or beyond **max** is considered an overflow, even if **size** is 0.

**Return**

true if the range is out of bounds.

#### <a id="c-range_overflows_t"></a>`range_overflows_t()`

```c
range_overflows_t(type, start, size, max)
```

Check if a range is out of bounds

**Parameters**

- `type`: Data type to use.
- `start`: Start of the range.
- `size`: Size of the range.
- `max`: Exclusive upper boundary.

**Description**

Same as [`range_overflows()`](#c-range_overflows) but forcing the parameters to **type**.

**Return**

true if the range is out of bounds.

#### <a id="c-range_end_overflows"></a>`range_end_overflows()`

```c
range_end_overflows(start, size, max)
```

Check if a range's endpoint is out of bounds

**Parameters**

- `start`: Start of the range.
- `size`: Size of the range.
- `max`: Exclusive upper boundary.

**Description**

Checks only if the endpoint of a range (**start** + **size**) exceeds **max**.
Unlike [`range_overflows()`](#c-range_overflows), a zero-sized range at the boundary (**start** == **max**)
is not considered an overflow. Useful for iterator-style checks.

**Return**

true if the endpoint exceeds the boundary.

#### <a id="c-range_end_overflows_t"></a>`range_end_overflows_t()`

```c
range_end_overflows_t(type, start, size, max)
```

Check if a range's endpoint is out of bounds

**Parameters**

- `type`: Data type to use.
- `start`: Start of the range.
- `size`: Size of the range.
- `max`: Exclusive upper boundary.

**Description**

Same as [`range_end_overflows()`](#c-range_end_overflows) but forcing the parameters to **type**.

**Return**

true if the endpoint exceeds the boundary.

#### <a id="c-castable_to_type"></a>`castable_to_type()`

```c
castable_to_type(n, T)
```

like `__same_type()`, but also allows for casted literals

**Parameters**

- `n`: variable or constant value
- `T`: variable or data type

**Description**

Unlike the `__same_type()` macro, this allows a constant value as the
first argument. If this value would not overflow into an assignment
of the second argument's type, it returns true. Otherwise, this falls
back to `__same_type()`.

#### <a id="c-size_mul"></a>`size_mul()`

```c
size_t size_mul(size_t factor1, size_t factor2)
```

Calculate size_t multiplication with saturation at SIZE_MAX

**Parameters**

- `size_t factor1`: first factor
- `size_t factor2`: second factor

**Return**

calculate **factor1** * **factor2**, both promoted to size_t,
with any overflow causing the return value to be SIZE_MAX. The
lvalue must be size_t to avoid implicit type conversion.

#### <a id="c-size_add"></a>`size_add()`

```c
size_t size_add(size_t addend1, size_t addend2)
```

Calculate size_t addition with saturation at SIZE_MAX

**Parameters**

- `size_t addend1`: first addend
- `size_t addend2`: second addend

**Return**

calculate **addend1** + **addend2**, both promoted to size_t,
with any overflow causing the return value to be SIZE_MAX. The
lvalue must be size_t to avoid implicit type conversion.

#### <a id="c-size_sub"></a>`size_sub()`

```c
size_t size_sub(size_t minuend, size_t subtrahend)
```

Calculate size_t subtraction with saturation at SIZE_MAX

**Parameters**

- `size_t minuend`: value to subtract from
- `size_t subtrahend`: value to subtract from **minuend**

**Return**

calculate **minuend** - **subtrahend**, both promoted to size_t,
with any overflow causing the return value to be SIZE_MAX. For
composition with the [`size_add()`](#c-size_add) and [`size_mul()`](#c-size_mul) helpers, neither
argument may be SIZE_MAX (or the result with be forced to SIZE_MAX).
The lvalue must be size_t to avoid implicit type conversion.

#### <a id="c-array_size"></a>`array_size()`

```c
array_size(a, b)
```

Calculate size of 2-dimensional array.

**Parameters**

- `a`: dimension one
- `b`: dimension two

**Description**

Calculates size of 2-dimensional array: **a** * **b**.

**Return**

number of bytes needed to represent the array or SIZE_MAX on
overflow.

#### <a id="c-array3_size"></a>`array3_size()`

```c
array3_size(a, b, c)
```

Calculate size of 3-dimensional array.

**Parameters**

- `a`: dimension one
- `b`: dimension two
- `c`: dimension three

**Description**

Calculates size of 3-dimensional array: **a** * **b** * **c**.

**Return**

number of bytes needed to represent the array or SIZE_MAX on
overflow.

#### <a id="c-flex_array_size"></a>`flex_array_size()`

```c
flex_array_size(p, member, count)
```

Calculate size of a flexible array member within an enclosing structure.

**Parameters**

- `p`: Pointer to the structure.
- `member`: Name of the flexible array member.
- `count`: Number of elements in the array.

**Description**

Calculates size of a flexible array of **count** number of **member**
elements, at the end of structure **p**.

**Return**

number of bytes needed or SIZE_MAX on overflow.

#### <a id="c-struct_size"></a>`struct_size()`

```c
struct_size(p, member, count)
```

Calculate size of structure with trailing flexible array.

**Parameters**

- `p`: Pointer to the structure.
- `member`: Name of the array member.
- `count`: Number of elements in the array.

**Description**

Calculates size of memory needed for structure of **p** followed by an
array of **count** number of **member** elements.

**Return**

number of bytes needed or SIZE_MAX on overflow.

#### <a id="c-struct_size_t"></a>`struct_size_t()`

```c
struct_size_t(type, member, count)
```

Calculate size of structure with trailing flexible array

**Parameters**

- `type`: structure type name.
- `member`: Name of the array member.
- `count`: Number of elements in the array.

**Description**

Calculates size of memory needed for structure **type** followed by an
array of **count** number of **member** elements. Prefer using [`struct_size()`](#c-struct_size)
when possible instead, to keep calculations associated with a specific
instance variable of type **type**.

**Return**

number of bytes needed or SIZE_MAX on overflow.

#### <a id="c-struct_offset"></a>`struct_offset()`

```c
struct_offset(p, member)
```

Calculate the offset of a member within a struct

**Parameters**

- `p`: Pointer to the struct
- `member`: Name of the member to get the offset of

**Description**

Calculates the offset of a particular **member** of the structure pointed
to by **p**.

**Return**

number of bytes to the location of **member**.

#### <a id="c-__DEFINE_FLEX"></a>`__DEFINE_FLEX()`

```c
__DEFINE_FLEX(type, name, member, count, trailer...)
```

helper macro for [`DEFINE_FLEX()`](#c-DEFINE_FLEX) family. Enables caller macro to pass arbitrary trailing expressions

**Parameters**

- `type`: structure type name, including "struct" keyword.
- `name`: Name for a variable to define.
- `member`: Name of the array member.
- `count`: Number of elements in the array; must be compile-time const.
- `trailer...`: Trailing expressions for attributes and/or initializers.

#### <a id="c-_DEFINE_FLEX"></a>`_DEFINE_FLEX()`

```c
_DEFINE_FLEX(type, name, member, count, initializer...)
```

helper macro for [`DEFINE_FLEX()`](#c-DEFINE_FLEX) family. Enables caller macro to pass (different) initializer.

**Parameters**

- `type`: structure type name, including "struct" keyword.
- `name`: Name for a variable to define.
- `member`: Name of the array member.
- `count`: Number of elements in the array; must be compile-time const.
- `initializer...`: Initializer expression (e.g., pass `= { }` at minimum).

#### <a id="c-DEFINE_RAW_FLEX"></a>`DEFINE_RAW_FLEX()`

```c
DEFINE_RAW_FLEX(type, name, member, count)
```

Define an on-stack instance of structure with a trailing flexible array member, when it does not have a __counted_by annotation.

**Parameters**

- `type`: structure type name, including "struct" keyword.
- `name`: Name for a variable to define.
- `member`: Name of the array member.
- `count`: Number of elements in the array; must be compile-time const.

**Description**

Define a zeroed, on-stack, instance of **type** structure with a trailing
flexible array member.
Use __struct_size(**name**) to get compile-time size of it afterwards.
Use __member_size(**name->member**) to get compile-time size of **name** members.
Use STACK_FLEX_ARRAY_SIZE(**name**, **member**) to get compile-time number of
elements in array **member**.

#### <a id="c-DEFINE_FLEX"></a>`DEFINE_FLEX()`

```c
DEFINE_FLEX(TYPE, NAME, MEMBER, COUNTER, COUNT)
```

Define an on-stack instance of structure with a trailing flexible array member.

**Parameters**

- `TYPE`: structure type name, including "struct" keyword.
- `NAME`: Name for a variable to define.
- `MEMBER`: Name of the array member.
- `COUNTER`: Name of the __counted_by member.
- `COUNT`: Number of elements in the array; must be compile-time const.

**Description**

Define a zeroed, on-stack, instance of **TYPE** structure with a trailing
flexible array member.
Use __struct_size(**NAME**) to get compile-time size of it afterwards.
Use __member_size(**NAME->member**) to get compile-time size of **NAME** members.
Use STACK_FLEX_ARRAY_SIZE(**name**, **member**) to get compile-time number of
elements in array **member**.

#### <a id="c-STACK_FLEX_ARRAY_SIZE"></a>`STACK_FLEX_ARRAY_SIZE()`

```c
STACK_FLEX_ARRAY_SIZE(name, array)
```

helper macro for [`DEFINE_FLEX()`](#c-DEFINE_FLEX) family. Returns the number of elements in **array**.

**Parameters**

- `name`: Name for a variable defined in [`DEFINE_RAW_FLEX()`](#c-DEFINE_RAW_FLEX)/[`DEFINE_FLEX()`](#c-DEFINE_FLEX).
- `array`: Name of the array member.

#### <a id="c-typeof_flex_counter"></a>`typeof_flex_counter()`

```c
typeof_flex_counter(FAM)
```

Return the type of the counter variable of a given flexible array member annotated by `__counted_by()`.

**Parameters**

- `FAM`: Instance of flexible array member within a given struct.

**Return**

"size_t" if no annotation exists.

#### <a id="c-overflows_flex_counter_type"></a>`overflows_flex_counter_type()`

```c
overflows_flex_counter_type(TYPE, FAM, COUNT)
```

Check if the counter associated with the given flexible array member can represent a value.

**Parameters**

- `TYPE`: Type of the struct that contains the **FAM**.
- `FAM`: Member name of the FAM within **TYPE**.
- `COUNT`: Value to check against the __counted_by annotated **FAM**'s counter.

**Return**

true if **COUNT** can be represented in the **FAM**'s counter. When
**FAM** is not annotated with `__counted_by()`, always returns true.

#### <a id="c-__set_flex_counter"></a>`__set_flex_counter()`

```c
__set_flex_counter(FAM, COUNT)
```

Set the counter associated with the given flexible array member that has been annoated by `__counted_by()`.

**Parameters**

- `FAM`: Instance of flexible array member within a given struct.
- `COUNT`: Value to store to the __counted_by annotated **FAM_PTR**'s counter.

**Description**

This is a no-op if no annotation exists. Count needs to be checked with
[`overflows_flex_counter_type()`](#c-overflows_flex_counter_type) before using this function.


<a id="rst-crc-functions"></a>

### CRC Functions


#### <a id="c-crc4"></a>`crc4()`

```c
uint8_t crc4(uint8_t c, uint64_t x, int bits)
```

calculate the 4-bit crc of a value.

**Parameters**

- `uint8_t c`: starting crc4
- `uint64_t x`: value to checksum
- `int bits`: number of bits in **x** to checksum

**Description**

Returns the crc4 value of **x**, using polynomial 0b10111.

The **x** value is treated as left-aligned, and bits above **bits** are ignored
in the crc calculations.



#### <a id="c-crc7_be"></a>`crc7_be()`

```c
u8 crc7_be(u8 crc, const u8 *buffer, size_t len)
```

update the CRC7 for the data buffer

**Parameters**

- `u8 crc`: previous CRC7 value
- `const u8 *buffer`: data pointer
- `size_t len`: number of bytes in the buffer

**Context**

any

**Description**

Returns the updated CRC7 value.
The CRC7 is left-aligned in the byte (the lsbit is always 0), as that
makes the computation easier, and all callers want it in that form.



#### <a id="c-crc8_populate_msb"></a>`crc8_populate_msb()`

```c
void crc8_populate_msb(u8 table[CRC8_TABLE_SIZE], u8 polynomial)
```

fill crc table for given polynomial in reverse bit order.

**Parameters**

- `u8 table[CRC8_TABLE_SIZE]`: table to be filled.
- `u8 polynomial`: polynomial for which table is to be filled.

#### <a id="c-crc8_populate_lsb"></a>`crc8_populate_lsb()`

```c
void crc8_populate_lsb(u8 table[CRC8_TABLE_SIZE], u8 polynomial)
```

fill crc table for given polynomial in regular bit order.

**Parameters**

- `u8 table[CRC8_TABLE_SIZE]`: table to be filled.
- `u8 polynomial`: polynomial for which table is to be filled.

#### <a id="c-crc8"></a>`crc8()`

```c
u8 crc8(const u8 table[CRC8_TABLE_SIZE], const u8 *pdata, size_t nbytes, u8 crc)
```

calculate a crc8 over the given input data.

**Parameters**

- `const u8 table[CRC8_TABLE_SIZE]`: crc table used for calculation.
- `const u8 *pdata`: pointer to data buffer.
- `size_t nbytes`: number of bytes in data buffer.
- `u8 crc`: previous returned crc8 value.



#### <a id="c-crc16"></a>`crc16()`

```c
u16 crc16(u16 crc, const u8 *p, size_t len)
```

compute the CRC-16 for the data buffer

**Parameters**

- `u16 crc`: previous CRC value
- `const u8 *p`: data pointer
- `size_t len`: number of bytes in the buffer

**Description**

Returns the updated CRC value.



#### <a id="c-crc_ccitt"></a>`crc_ccitt()`

```c
u16 crc_ccitt(u16 crc, u8 const *buffer, size_t len)
```

recompute the CRC (CRC-CCITT variant) for the data buffer

**Parameters**

- `u16 crc`: previous CRC value
- `u8 const *buffer`: data pointer
- `size_t len`: number of bytes in the buffer



#### <a id="c-crc_itu_t"></a>`crc_itu_t()`

```c
u16 crc_itu_t(u16 crc, const u8 *buffer, size_t len)
```

Compute the CRC-ITU-T for the data buffer

**Parameters**

- `u16 crc`: previous CRC value
- `const u8 *buffer`: data pointer
- `size_t len`: number of bytes in the buffer

**Description**

Returns the updated CRC value



#### <a id="c-crc32_le"></a>`crc32_le()`

```c
u32 crc32_le(u32 crc, const void *p, size_t len)
```

Compute least-significant-bit-first IEEE CRC-32

**Parameters**

- `u32 crc`: Initial CRC value.  ~0 (recommended) or 0 for a new CRC computation, or
  the previous CRC value if computing incrementally.
- `const void *p`: Pointer to the data buffer
- `size_t len`: Length of data in bytes

**Description**

This implements the CRC variant that is often known as the IEEE CRC-32, or
simply CRC-32, and is widely used in Ethernet and other applications:

- Polynomial: x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 +
  x^7 + x^5 + x^4 + x^2 + x^1 + x^0
- Bit order: Least-significant-bit-first
- Polynomial in integer form: 0xedb88320

This does *not* invert the CRC at the beginning or end.  The caller is
expected to do that if it needs to.  Inverting at both ends is recommended.

For new applications, prefer to use CRC-32C instead.  See [`crc32c()`](#c-crc32c).

**Context**

Any context

**Return**

The new CRC value

#### <a id="c-crc32_be"></a>`crc32_be()`

```c
u32 crc32_be(u32 crc, const void *p, size_t len)
```

Compute most-significant-bit-first IEEE CRC-32

**Parameters**

- `u32 crc`: Initial CRC value.  ~0 (recommended) or 0 for a new CRC computation, or
  the previous CRC value if computing incrementally.
- `const void *p`: Pointer to the data buffer
- `size_t len`: Length of data in bytes

**Description**

[`crc32_be()`](#c-crc32_be) is the same as [`crc32_le()`](#c-crc32_le) except that [`crc32_be()`](#c-crc32_be) computes the
*most-significant-bit-first* variant of the CRC.  I.e., within each byte, the
most significant bit is processed first (treated as highest order polynomial
coefficient).  The same bit order is also used for the CRC value itself:

- Polynomial: x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 +
  x^7 + x^5 + x^4 + x^2 + x^1 + x^0
- Bit order: Most-significant-bit-first
- Polynomial in integer form: 0x04c11db7

**Context**

Any context

**Return**

The new CRC value

#### <a id="c-crc32c"></a>`crc32c()`

```c
u32 crc32c(u32 crc, const void *p, size_t len)
```

Compute CRC-32C

**Parameters**

- `u32 crc`: Initial CRC value.  ~0 (recommended) or 0 for a new CRC computation, or
  the previous CRC value if computing incrementally.
- `const void *p`: Pointer to the data buffer
- `size_t len`: Length of data in bytes

**Description**

This implements CRC-32C, i.e. the Castagnoli CRC.  This is the recommended
CRC variant to use in new applications that want a 32-bit CRC.

- Polynomial: x^32 + x^28 + x^27 + x^26 + x^25 + x^23 + x^22 + x^20 + x^19 +
  x^18 + x^14 + x^13 + x^11 + x^10 + x^9 + x^8 + x^6 + x^0
- Bit order: Least-significant-bit-first
- Polynomial in integer form: 0x82f63b78

This does *not* invert the CRC at the beginning or end.  The caller is
expected to do that if it needs to.  Inverting at both ends is recommended.

**Context**

Any context

**Return**

The new CRC value



#### <a id="c-crc64_be"></a>`crc64_be()`

```c
u64 crc64_be(u64 crc, const void *p, size_t len)
```

Calculate bitwise big-endian ECMA-182 CRC64

**Parameters**

- `u64 crc`: seed value for computation. 0 or (u64)~0 for a new CRC calculation,
  or the previous crc64 value if computing incrementally.
- `const void *p`: pointer to buffer over which CRC64 is run
- `size_t len`: length of buffer **p**

#### <a id="c-crc64_nvme"></a>`crc64_nvme()`

```c
u64 crc64_nvme(u64 crc, const void *p, size_t len)
```

Calculate CRC64-NVME

**Parameters**

- `u64 crc`: seed value for computation. 0 for a new CRC calculation, or the
  previous crc64 value if computing incrementally.
- `const void *p`: pointer to buffer over which CRC64 is run
- `size_t len`: length of buffer **p**

**Description**

This computes the CRC64 defined in the NVME NVM Command Set Specification,
*including the bitwise inversion at the beginning and end*.


<a id="rst-base-2-log-and-power-functions"></a>

### Base 2 log and power Functions


#### <a id="c-is_power_of_2"></a>`is_power_of_2()`

```c
bool is_power_of_2(unsigned long n)
```

check if a value is a power of two

**Parameters**

- `unsigned long n`: the value to check

**Description**

Determine whether some value is a power of two, where zero is
*not* considered a power of two.

**Return**

true if **n** is a power of 2, otherwise false.

#### <a id="c-__roundup_pow_of_two"></a>`__roundup_pow_of_two()`

```c
unsigned long __roundup_pow_of_two(unsigned long n)
```

round up to nearest power of two

**Parameters**

- `unsigned long n`: value to round up

#### <a id="c-__rounddown_pow_of_two"></a>`__rounddown_pow_of_two()`

```c
unsigned long __rounddown_pow_of_two(unsigned long n)
```

round down to nearest power of two

**Parameters**

- `unsigned long n`: value to round down

#### <a id="c-const_ilog2"></a>`const_ilog2()`

```c
const_ilog2(n)
```

log base 2 of 32-bit or a 64-bit constant unsigned value

**Parameters**

- `n`: parameter

**Description**

Use this where sparse expects a true constant expression, e.g. for array
indices.

#### <a id="c-ilog2"></a>`ilog2()`

```c
ilog2(n)
```

log base 2 of 32-bit or a 64-bit unsigned value

**Parameters**

- `n`: parameter

**Description**

constant-capable log of base 2 calculation
- this can be used to initialise global variables from constant data, hence
the massive ternary operator construction

selects the appropriately-sized optimised version depending on sizeof(n)

#### <a id="c-roundup_pow_of_two"></a>`roundup_pow_of_two()`

```c
roundup_pow_of_two(n)
```

round the given value up to nearest power of two

**Parameters**

- `n`: parameter

**Description**

round the given value up to the nearest power of two
- the result is undefined when n == 0
- this can be used to initialise global variables from constant data

#### <a id="c-rounddown_pow_of_two"></a>`rounddown_pow_of_two()`

```c
rounddown_pow_of_two(n)
```

round the given value down to nearest power of two

**Parameters**

- `n`: parameter

**Description**

round the given value down to the nearest power of two
- the result is undefined when n == 0
- this can be used to initialise global variables from constant data

#### <a id="c-order_base_2"></a>`order_base_2()`

```c
order_base_2(n)
```

calculate the (rounded up) base 2 order of the argument

**Parameters**

- `n`: parameter

**Description**

- The first few values calculated by this routine:
  ob2(0) = 0
  ob2(1) = 0
  ob2(2) = 1
  ob2(3) = 2
  ob2(4) = 2
  ob2(5) = 3
  ... and so on.

#### <a id="c-bits_per"></a>`bits_per()`

```c
bits_per(n)
```

calculate the number of bits required for the argument

**Parameters**

- `n`: parameter

**Description**

This is constant-capable and can be used for compile time
initializations, e.g bitfields.

The first few values calculated by this routine:
bf(0) = 1
bf(1) = 1
bf(2) = 2
bf(3) = 2
bf(4) = 3
... and so on.

#### <a id="c-max_pow_of_two_factor"></a>`max_pow_of_two_factor()`

```c
unsigned int max_pow_of_two_factor(unsigned int n)
```

return highest power-of-2 factor

**Parameters**

- `unsigned int n`: parameter

**Description**

find highest power-of-2 which is evenly divisible into n.
0 is returned for n == 0 or 1.


<a id="rst-integer-log-and-power-functions"></a>

### Integer log and power Functions


#### <a id="c-intlog2"></a>`intlog2()`

```c
unsigned int intlog2(u32 value)
```

computes log2 of a value; the result is shifted left by 24 bits

**Parameters**

- `u32 value`: The value (must be != 0)

**Description**

to use rational values you can use the following method:

intlog2(value) = intlog2(value * 2^x) - x * 2^24

Some usecase examples:

intlog2(8) will give 3 \<\< 24 = 3 * 2^24

intlog2(9) will give 3 \<\< 24 + ... = 3.16... * 2^24

intlog2(1.5) = intlog2(3) - 2^24 = 0.584... * 2^24

**Return**

log2(value) * 2^24

#### <a id="c-intlog10"></a>`intlog10()`

```c
unsigned int intlog10(u32 value)
```

computes log10 of a value; the result is shifted left by 24 bits

**Parameters**

- `u32 value`: The value (must be != 0)

**Description**

to use rational values you can use the following method:

intlog10(value) = intlog10(value * 10^x) - x * 2^24

An usecase example:

intlog10(1000) will give 3 \<\< 24 = 3 * 2^24

due to the implementation intlog10(1000) might be not exactly 3 * 2^24

look at intlog2 for similar examples

**Return**

log10(value) * 2^24



#### <a id="c-int_pow"></a>`int_pow()`

```c
u64 int_pow(u64 base, unsigned int exp)
```

computes the exponentiation of the given base and exponent

**Parameters**

- `u64 base`: base which will be raised to the given power
- `unsigned int exp`: power to be raised to

**Description**

Computes: pow(base, exp), i.e. **base** raised to the **exp** power



#### <a id="c-int_sqrt"></a>`int_sqrt()`

```c
unsigned long int_sqrt(unsigned long x)
```

computes the integer square root

**Parameters**

- `unsigned long x`: integer of which to calculate the sqrt

**Description**

Computes: floor(sqrt(x))

#### <a id="c-int_sqrt64"></a>`int_sqrt64()`

```c
u32 int_sqrt64(u64 x)
```

strongly typed int_sqrt function when minimum 64 bit input is expected.

**Parameters**

- `u64 x`: 64bit integer of which to calculate the sqrt


<a id="rst-division-functions"></a>

### Division Functions


#### <a id="c-do_div"></a>`do_div()`

```c
do_div(n, base)
```

returns 2 values: calculate remainder and update new dividend

**Parameters**

- `n`: uint64_t dividend (will be updated)
- `base`: uint32_t divisor

**Description**

Summary:
`uint32_t remainder = n % base;`
`n = n / base;`

**Return**

(uint32_t)remainder

**NOTE**

macro parameter **n** is evaluated multiple times,
beware of side effects!



#### <a id="c-div_u64_rem"></a>`div_u64_rem()`

```c
u64 div_u64_rem(u64 dividend, u32 divisor, u32 *remainder)
```

unsigned 64bit divide with 32bit divisor with remainder

**Parameters**

- `u64 dividend`: unsigned 64bit dividend
- `u32 divisor`: unsigned 32bit divisor
- `u32 *remainder`: pointer to unsigned 32bit remainder

**Return**

sets `*remainder`, then returns dividend / divisor

**Description**

This is commonly provided by 32bit archs to provide an optimized 64bit
divide.

#### <a id="c-div_s64_rem"></a>`div_s64_rem()`

```c
s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder)
```

signed 64bit divide with 32bit divisor with remainder

**Parameters**

- `s64 dividend`: signed 64bit dividend
- `s32 divisor`: signed 32bit divisor
- `s32 *remainder`: pointer to signed 32bit remainder

**Return**

sets `*remainder`, then returns dividend / divisor

#### <a id="c-div64_u64_rem"></a>`div64_u64_rem()`

```c
u64 div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder)
```

unsigned 64bit divide with 64bit divisor and remainder

**Parameters**

- `u64 dividend`: unsigned 64bit dividend
- `u64 divisor`: unsigned 64bit divisor
- `u64 *remainder`: pointer to unsigned 64bit remainder

**Return**

sets `*remainder`, then returns dividend / divisor

#### <a id="c-div64_u64"></a>`div64_u64()`

```c
u64 div64_u64(u64 dividend, u64 divisor)
```

unsigned 64bit divide with 64bit divisor

**Parameters**

- `u64 dividend`: unsigned 64bit dividend
- `u64 divisor`: unsigned 64bit divisor

**Return**

dividend / divisor

#### <a id="c-div64_s64"></a>`div64_s64()`

```c
s64 div64_s64(s64 dividend, s64 divisor)
```

signed 64bit divide with 64bit divisor

**Parameters**

- `s64 dividend`: signed 64bit dividend
- `s64 divisor`: signed 64bit divisor

**Return**

dividend / divisor

#### <a id="c-div_u64"></a>`div_u64()`

```c
u64 div_u64(u64 dividend, u32 divisor)
```

unsigned 64bit divide with 32bit divisor

**Parameters**

- `u64 dividend`: unsigned 64bit dividend
- `u32 divisor`: unsigned 32bit divisor

**Description**

This is the most common 64bit divide and should be used if possible,
as many 32bit archs can optimize this variant better than a full 64bit
divide.

**Return**

dividend / divisor

#### <a id="c-div_s64"></a>`div_s64()`

```c
s64 div_s64(s64 dividend, s32 divisor)
```

signed 64bit divide with 32bit divisor

**Parameters**

- `s64 dividend`: signed 64bit dividend
- `s32 divisor`: signed 32bit divisor

**Return**

dividend / divisor

#### <a id="c-mul_u64_add_u64_div_u64"></a>`mul_u64_add_u64_div_u64()`

```c
u64 mul_u64_add_u64_div_u64(u64 a, u64 b, u64 c, u64 d)
```

unsigned 64bit multiply, add, and divide

**Parameters**

- `u64 a`: first unsigned 64bit multiplicand
- `u64 b`: second unsigned 64bit multiplicand
- `u64 c`: unsigned 64bit addend
- `u64 d`: unsigned 64bit divisor

**Description**

Multiply two 64bit values together to generate a 128bit product
add a third value and then divide by a fourth.
The Generic code divides by 0 if **d** is zero and returns ~0 on overflow.
Architecture specific code may trap on zero or overflow.

**Return**

(**a** * **b** + **c**) / **d**

#### <a id="c-mul_u64_u64_div_u64"></a>`mul_u64_u64_div_u64()`

```c
mul_u64_u64_div_u64(a, b, d)
```

unsigned 64bit multiply and divide

**Parameters**

- `a`: first unsigned 64bit multiplicand
- `b`: second unsigned 64bit multiplicand
- `d`: unsigned 64bit divisor

**Description**

Multiply two 64bit values together to generate a 128bit product
and then divide by a third value.
The Generic code divides by 0 if **d** is zero and returns ~0 on overflow.
Architecture specific code may trap on zero or overflow.

**Return**

**a** * **b** / **d**

#### <a id="c-mul_u64_u64_div_u64_roundup"></a>`mul_u64_u64_div_u64_roundup()`

```c
mul_u64_u64_div_u64_roundup(a, b, d)
```

unsigned 64bit multiply and divide rounded up

**Parameters**

- `a`: first unsigned 64bit multiplicand
- `b`: second unsigned 64bit multiplicand
- `d`: unsigned 64bit divisor

**Description**

Multiply two 64bit values together to generate a 128bit product
and then divide and round up.
The Generic code divides by 0 if **d** is zero and returns ~0 on overflow.
Architecture specific code may trap on zero or overflow.

**Return**

(**a** * **b** + **d** - 1) / **d**

#### <a id="c-DIV64_U64_ROUND_UP"></a>`DIV64_U64_ROUND_UP()`

```c
DIV64_U64_ROUND_UP(ll, d)
```

unsigned 64bit divide with 64bit divisor rounded up

**Parameters**

- `ll`: unsigned 64bit dividend
- `d`: unsigned 64bit divisor

**Description**

Divide unsigned 64bit dividend by unsigned 64bit divisor
and round up.

**Return**

dividend / divisor rounded up

#### <a id="c-DIV_U64_ROUND_UP"></a>`DIV_U64_ROUND_UP()`

```c
DIV_U64_ROUND_UP(ll, d)
```

unsigned 64bit divide with 32bit divisor rounded up

**Parameters**

- `ll`: unsigned 64bit dividend
- `d`: unsigned 32bit divisor

**Description**

Divide unsigned 64bit dividend by unsigned 32bit divisor
and round up.

**Return**

dividend / divisor rounded up

#### <a id="c-DIV64_U64_ROUND_CLOSEST"></a>`DIV64_U64_ROUND_CLOSEST()`

```c
DIV64_U64_ROUND_CLOSEST(dividend, divisor)
```

unsigned 64bit divide with 64bit divisor rounded to nearest integer

**Parameters**

- `dividend`: unsigned 64bit dividend
- `divisor`: unsigned 64bit divisor

**Description**

Divide unsigned 64bit dividend by unsigned 64bit divisor
and round to closest integer.

**Return**

dividend / divisor rounded to nearest integer

#### <a id="c-DIV_U64_ROUND_CLOSEST"></a>`DIV_U64_ROUND_CLOSEST()`

```c
DIV_U64_ROUND_CLOSEST(dividend, divisor)
```

unsigned 64bit divide with 32bit divisor rounded to nearest integer

**Parameters**

- `dividend`: unsigned 64bit dividend
- `divisor`: unsigned 32bit divisor

**Description**

Divide unsigned 64bit dividend by unsigned 32bit divisor
and round to closest integer.

**Return**

dividend / divisor rounded to nearest integer

#### <a id="c-DIV_S64_ROUND_CLOSEST"></a>`DIV_S64_ROUND_CLOSEST()`

```c
DIV_S64_ROUND_CLOSEST(dividend, divisor)
```

signed 64bit divide with 32bit divisor rounded to nearest integer

**Parameters**

- `dividend`: signed 64bit dividend
- `divisor`: signed 32bit divisor

**Description**

Divide signed 64bit dividend by signed 32bit divisor
and round to closest integer.

**Return**

dividend / divisor rounded to nearest integer

#### <a id="c-roundup_u64"></a>`roundup_u64()`

```c
u64 roundup_u64(u64 x, u32 y)
```

Round up a 64bit value to the next specified 32bit multiple

**Parameters**

- `u64 x`: the value to up
- `u32 y`: 32bit multiple to round up to

**Description**

Rounds **x** to the next multiple of **y**. For 32bit **x** values, see roundup and
the faster `round_up()` for powers of 2.

**Return**

rounded up value.



#### <a id="c-gcd"></a>`gcd()`

```c
unsigned long gcd(unsigned long a, unsigned long b)
```

calculate and return the greatest common divisor of 2 unsigned longs

**Parameters**

- `unsigned long a`: first value
- `unsigned long b`: second value


<a id="rst-uuid-guid"></a>

### UUID/GUID


#### <a id="c-generate_random_uuid"></a>`generate_random_uuid()`

```c
void generate_random_uuid(unsigned char uuid[16])
```

generate a random UUID

**Parameters**

- `unsigned char uuid[16]`: where to put the generated UUID

**Description**

Random UUID interface

Used to create a Boot ID or a filesystem UUID/GUID, but can be
useful for other kernel drivers.

#### <a id="c-uuid_is_valid"></a>`uuid_is_valid()`

```c
bool uuid_is_valid(const char *uuid)
```

checks if a UUID string is valid

**Parameters**

- `const char *uuid`: UUID string to check

**Description**

- It checks if the UUID string is following the format:
  xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

where x is a hex digit.

**Return**

true if input is valid UUID string.


<a id="rst-kernel-ipc-facilities"></a>

## Kernel IPC facilities

<a id="rst-ipc-utilities"></a>

### IPC utilities


#### <a id="c-ipc_init"></a>`ipc_init()`

```c
int ipc_init(void)
```

initialise ipc subsystem

**Parameters**

- `void`: no arguments

**Description**

The various sysv ipc resources (semaphores, messages and shared
memory) are initialised.

A callback routine is registered into the memory hotplug notifier
chain: since msgmni scales to lowmem this callback routine will be
called upon successful memory add / remove to recompute msmgni.

#### <a id="c-ipc_init_ids"></a>`ipc_init_ids()`

```c
void ipc_init_ids(struct ipc_ids *ids)
```

initialise ipc identifiers

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set

**Description**

Set up the sequence range to use for the ipc identifier range (limited
below ipc_mni) then initialise the keys hashtable and ids idr.

#### <a id="c-ipc_init_proc_interface"></a>`ipc_init_proc_interface()`

```c
void ipc_init_proc_interface(const char *path, const char *header, int ids, int (*show)(struct seq_file *, void *))
```

create a proc interface for sysipc types using a seq_file interface.

**Parameters**

- `const char *path`: Path in procfs
- `const char *header`: Banner to be printed at the beginning of the file.
- `int ids`: ipc id table to iterate.
- `int (*show)(struct seq_file *, void *)`: show routine.

#### <a id="c-ipc_findkey"></a>`ipc_findkey()`

```c
struct kern_ipc_perm * ipc_findkey(struct ipc_ids *ids, key_t key)
```

find a key in an ipc identifier set

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `key_t key`: key to find

**Description**

Returns the locked pointer to the ipc structure if found or NULL
otherwise. If key is found ipc points to the owning ipc structure

Called with writer ipc_ids.rwsem held.

#### <a id="c-ipc_addid"></a>`ipc_addid()`

```c
int ipc_addid(struct ipc_ids *ids, struct kern_ipc_perm *new, int limit)
```

add an ipc identifier

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `struct kern_ipc_perm *new`: new ipc permission set
- `int limit`: limit for the number of used ids

**Description**

Add an entry 'new' to the ipc ids idr. The permissions object is
initialised and the first free entry is set up and the index assigned
is returned. The 'new' entry is returned in a locked state on success.

On failure the entry is not locked and a negative err-code is returned.
The caller must use `ipc_rcu_putref()` to free the identifier.

Called with writer ipc_ids.rwsem held.

#### <a id="c-ipcget_new"></a>`ipcget_new()`

```c
int ipcget_new(struct ipc_namespace *ns, struct ipc_ids *ids, const struct ipc_ops *ops, struct ipc_params *params)
```

create a new ipc object

**Parameters**

- `struct ipc_namespace *ns`: ipc namespace
- `struct ipc_ids *ids`: ipc identifier set
- `const struct ipc_ops *ops`: the actual creation routine to call
- `struct ipc_params *params`: its parameters

**Description**

This routine is called by sys_msgget, `sys_semget()` and `sys_shmget()`
when the key is IPC_PRIVATE.

#### <a id="c-ipc_check_perms"></a>`ipc_check_perms()`

```c
int ipc_check_perms(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp, const struct ipc_ops *ops, struct ipc_params *params)
```

check security and permissions for an ipc object

**Parameters**

- `struct ipc_namespace *ns`: ipc namespace
- `struct kern_ipc_perm *ipcp`: ipc permission set
- `const struct ipc_ops *ops`: the actual security routine to call
- `struct ipc_params *params`: its parameters

**Description**

This routine is called by `sys_msgget()`, `sys_semget()` and `sys_shmget()`
when the key is not IPC_PRIVATE and that key already exists in the
ds IDR.

On success, the ipc id is returned.

It is called with ipc_ids.rwsem and ipcp->lock held.

#### <a id="c-ipcget_public"></a>`ipcget_public()`

```c
int ipcget_public(struct ipc_namespace *ns, struct ipc_ids *ids, const struct ipc_ops *ops, struct ipc_params *params)
```

get an ipc object or create a new one

**Parameters**

- `struct ipc_namespace *ns`: ipc namespace
- `struct ipc_ids *ids`: ipc identifier set
- `const struct ipc_ops *ops`: the actual creation routine to call
- `struct ipc_params *params`: its parameters

**Description**

This routine is called by sys_msgget, `sys_semget()` and `sys_shmget()`
when the key is not IPC_PRIVATE.
It adds a new entry if the key is not found and does some permission
/ security checkings if the key is found.

On success, the ipc id is returned.

#### <a id="c-ipc_kht_remove"></a>`ipc_kht_remove()`

```c
void ipc_kht_remove(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
```

remove an ipc from the key hashtable

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `struct kern_ipc_perm *ipcp`: ipc perm structure containing the key to remove

**Description**

ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
before this function is called, and remain locked on the exit.

#### <a id="c-ipc_search_maxidx"></a>`ipc_search_maxidx()`

```c
int ipc_search_maxidx(struct ipc_ids *ids, int limit)
```

search for the highest assigned index

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `int limit`: known upper limit for highest assigned index

**Description**

The function determines the highest assigned index in **ids**. It is intended
to be called when ids->max_idx needs to be updated.
Updating ids->max_idx is necessary when the current highest index ipc
object is deleted.
If no ipc object is allocated, then -1 is returned.

ipc_ids.rwsem needs to be held by the caller.

#### <a id="c-ipc_rmid"></a>`ipc_rmid()`

```c
void ipc_rmid(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
```

remove an ipc identifier

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `struct kern_ipc_perm *ipcp`: ipc perm structure containing the identifier to remove

**Description**

ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
before this function is called, and remain locked on the exit.

#### <a id="c-ipc_set_key_private"></a>`ipc_set_key_private()`

```c
void ipc_set_key_private(struct ipc_ids *ids, struct kern_ipc_perm *ipcp)
```

switch the key of an existing ipc to IPC_PRIVATE

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `struct kern_ipc_perm *ipcp`: ipc perm structure containing the key to modify

**Description**

ipc_ids.rwsem (as a writer) and the spinlock for this ID are held
before this function is called, and remain locked on the exit.

#### <a id="c-ipcperms"></a>`ipcperms()`

```c
int ipcperms(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp, short flag)
```

check ipc permissions

**Parameters**

- `struct ipc_namespace *ns`: ipc namespace
- `struct kern_ipc_perm *ipcp`: ipc permission set
- `short flag`: desired permission set

**Description**

Check user, group, other permissions for access
to ipc resources. return 0 if allowed

**flag** will most probably be 0 or `S_...UGO` from \<linux/stat.h>

#### <a id="c-kernel_to_ipc64_perm"></a>`kernel_to_ipc64_perm()`

```c
void kernel_to_ipc64_perm(struct kern_ipc_perm *in, struct ipc64_perm *out)
```

convert kernel ipc permissions to user

**Parameters**

- `struct kern_ipc_perm *in`: kernel permissions
- `struct ipc64_perm *out`: new style ipc permissions

**Description**

Turn the kernel object **in** into a set of permissions descriptions
for returning to userspace (**out**).

#### <a id="c-ipc64_perm_to_ipc_perm"></a>`ipc64_perm_to_ipc_perm()`

```c
void ipc64_perm_to_ipc_perm(struct ipc64_perm *in, struct ipc_perm *out)
```

convert new ipc permissions to old

**Parameters**

- `struct ipc64_perm *in`: new style ipc permissions
- `struct ipc_perm *out`: old style ipc permissions

**Description**

Turn the new style permissions object **in** into a compatibility
object and store it into the **out** pointer.

#### <a id="c-ipc_obtain_object_idr"></a>`ipc_obtain_object_idr()`

```c
struct kern_ipc_perm * ipc_obtain_object_idr(struct ipc_ids *ids, int id)
```

Look for an id in the ipc ids idr and return associated ipc object.

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `int id`: ipc id to look for

**Description**

Call inside the RCU critical section.
The ipc object is *not* locked on exit.

#### <a id="c-ipc_obtain_object_check"></a>`ipc_obtain_object_check()`

```c
struct kern_ipc_perm * ipc_obtain_object_check(struct ipc_ids *ids, int id)
```

Similar to [`ipc_obtain_object_idr()`](#c-ipc_obtain_object_idr) but also checks the ipc object sequence number.

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `int id`: ipc id to look for

**Description**

Call inside the RCU critical section.
The ipc object is *not* locked on exit.

#### <a id="c-ipcget"></a>`ipcget()`

```c
int ipcget(struct ipc_namespace *ns, struct ipc_ids *ids, const struct ipc_ops *ops, struct ipc_params *params)
```

Common sys_*`get()` code

**Parameters**

- `struct ipc_namespace *ns`: namespace
- `struct ipc_ids *ids`: ipc identifier set
- `const struct ipc_ops *ops`: operations to be called on ipc object creation, permission checks
  and further checks
- `struct ipc_params *params`: the parameters needed by the previous operations.

**Description**

Common routine called by `sys_msgget()`, `sys_semget()` and `sys_shmget()`.

#### <a id="c-ipc_update_perm"></a>`ipc_update_perm()`

```c
int ipc_update_perm(struct ipc64_perm *in, struct kern_ipc_perm *out)
```

update the permissions of an ipc object

**Parameters**

- `struct ipc64_perm *in`: the permission given as input.
- `struct kern_ipc_perm *out`: the permission of the ipc to set.

#### <a id="c-ipcctl_obtain_check"></a>`ipcctl_obtain_check()`

```c
struct kern_ipc_perm * ipcctl_obtain_check(struct ipc_namespace *ns, struct ipc_ids *ids, int id, int cmd, struct ipc64_perm *perm, int extra_perm)
```

retrieve an ipc object and check permissions

**Parameters**

- `struct ipc_namespace *ns`: ipc namespace
- `struct ipc_ids *ids`: the table of ids where to look for the ipc
- `int id`: the id of the ipc to retrieve
- `int cmd`: the cmd to check
- `struct ipc64_perm *perm`: the permission to set
- `int extra_perm`: one extra permission parameter used by msq

**Description**

This function does some common audit and permissions check for some IPC_XXX
cmd and is called from semctl_down, shmctl_down and msgctl_down.

- It:
  - retrieves the ipc object with the given id in the given table.
  - performs some audit and permission check, depending on the given cmd
  - returns a pointer to the ipc object or otherwise, the corresponding
    error.

Call holding the both the rwsem and the rcu read lock.

#### <a id="c-ipc_parse_version"></a>`ipc_parse_version()`

```c
int ipc_parse_version(int *cmd)
```

ipc call version

**Parameters**

- `int *cmd`: pointer to command

**Description**

Return IPC_64 for new style IPC and IPC_OLD for old style IPC.
The **cmd** value is turned from an encoding command and version into
just the command code.

#### <a id="c-sysvipc_find_ipc"></a>`sysvipc_find_ipc()`

```c
struct kern_ipc_perm * sysvipc_find_ipc(struct ipc_ids *ids, loff_t *pos)
```

Find and lock the ipc structure based on seq pos

**Parameters**

- `struct ipc_ids *ids`: ipc identifier set
- `loff_t *pos`: expected position

**Description**

The function finds an ipc structure, based on the sequence file
position **pos**. If there is no ipc structure at position **pos**, then
the successor is selected.
If a structure is found, then it is locked (both [`rcu_read_lock()`](#c-rcu_read_lock) and
`ipc_lock_object()`) and  **pos** is set to the position needed to locate
the found ipc structure.
If nothing is found (i.e. EOF), **pos** is not modified.

The function returns the found ipc structure, or NULL at EOF.


<a id="rst-fifo-buffer"></a>

## FIFO Buffer

<a id="rst-kfifo-interface"></a>

### kfifo interface


#### <a id="c-DECLARE_KFIFO_PTR"></a>`DECLARE_KFIFO_PTR()`

```c
DECLARE_KFIFO_PTR(fifo, type)
```

macro to declare a fifo pointer object

**Parameters**

- `fifo`: name of the declared fifo
- `type`: type of the fifo elements

#### <a id="c-DECLARE_KFIFO"></a>`DECLARE_KFIFO()`

```c
DECLARE_KFIFO(fifo, type, size)
```

macro to declare a fifo object

**Parameters**

- `fifo`: name of the declared fifo
- `type`: type of the fifo elements
- `size`: the number of elements in the fifo, this must be a power of 2

#### <a id="c-INIT_KFIFO"></a>`INIT_KFIFO()`

```c
INIT_KFIFO(fifo)
```

Initialize a fifo declared by DECLARE_KFIFO

**Parameters**

- `fifo`: name of the declared fifo datatype

#### <a id="c-DEFINE_KFIFO"></a>`DEFINE_KFIFO()`

```c
DEFINE_KFIFO(fifo, type, size)
```

macro to define and initialize a fifo

**Parameters**

- `fifo`: name of the declared fifo datatype
- `type`: type of the fifo elements
- `size`: the number of elements in the fifo, this must be a power of 2

**Note**

the macro can be used for global and local fifo data type variables.

#### <a id="c-kfifo_initialized"></a>`kfifo_initialized()`

```c
kfifo_initialized(fifo)
```

Check if the fifo is initialized

**Parameters**

- `fifo`: address of the fifo to check

**Description**

Return `true` if fifo is initialized, otherwise `false`.
Assumes the fifo was 0 before.

#### <a id="c-kfifo_esize"></a>`kfifo_esize()`

```c
kfifo_esize(fifo)
```

returns the size of the element managed by the fifo

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_recsize"></a>`kfifo_recsize()`

```c
kfifo_recsize(fifo)
```

returns the size of the record length field

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_size"></a>`kfifo_size()`

```c
kfifo_size(fifo)
```

returns the size of the fifo in elements

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_reset"></a>`kfifo_reset()`

```c
kfifo_reset(fifo)
```

removes the entire fifo content

**Parameters**

- `fifo`: address of the fifo to be used

**Note**

usage of [`kfifo_reset()`](#c-kfifo_reset) is dangerous. It should be only called when the
fifo is exclusived locked or when it is secured that no other thread is
accessing the fifo.

#### <a id="c-kfifo_reset_out"></a>`kfifo_reset_out()`

```c
kfifo_reset_out(fifo)
```

skip fifo content

**Parameters**

- `fifo`: address of the fifo to be used

**Note**

The usage of [`kfifo_reset_out()`](#c-kfifo_reset_out) is safe until it will be only called
from the reader thread and there is only one concurrent reader. Otherwise
it is dangerous and must be handled in the same way as [`kfifo_reset()`](#c-kfifo_reset).

#### <a id="c-kfifo_len"></a>`kfifo_len()`

```c
kfifo_len(fifo)
```

returns the number of used elements in the fifo

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_is_empty"></a>`kfifo_is_empty()`

```c
kfifo_is_empty(fifo)
```

returns true if the fifo is empty

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_is_empty_spinlocked"></a>`kfifo_is_empty_spinlocked()`

```c
kfifo_is_empty_spinlocked(fifo, lock)
```

returns true if the fifo is empty using a spinlock for locking

**Parameters**

- `fifo`: address of the fifo to be used
- `lock`: spinlock to be used for locking

#### <a id="c-kfifo_is_empty_spinlocked_noirqsave"></a>`kfifo_is_empty_spinlocked_noirqsave()`

```c
kfifo_is_empty_spinlocked_noirqsave(fifo, lock)
```

returns true if the fifo is empty using a spinlock for locking, doesn't disable interrupts

**Parameters**

- `fifo`: address of the fifo to be used
- `lock`: spinlock to be used for locking

#### <a id="c-kfifo_is_full"></a>`kfifo_is_full()`

```c
kfifo_is_full(fifo)
```

returns true if the fifo is full

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_avail"></a>`kfifo_avail()`

```c
kfifo_avail(fifo)
```

returns the number of unused elements in the fifo

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_skip_count"></a>`kfifo_skip_count()`

```c
kfifo_skip_count(fifo, count)
```

skip output data

**Parameters**

- `fifo`: address of the fifo to be used
- `count`: count of data to skip

#### <a id="c-kfifo_skip"></a>`kfifo_skip()`

```c
kfifo_skip(fifo)
```

skip output data

**Parameters**

- `fifo`: address of the fifo to be used

#### <a id="c-kfifo_peek_len"></a>`kfifo_peek_len()`

```c
kfifo_peek_len(fifo)
```

gets the size of the next fifo record

**Parameters**

- `fifo`: address of the fifo to be used

**Description**

This function returns the size of the next fifo record in number of bytes.

#### <a id="c-kfifo_alloc"></a>`kfifo_alloc()`

```c
kfifo_alloc(fifo, size, gfp_mask)
```

dynamically allocates a new fifo buffer

**Parameters**

- `fifo`: pointer to the fifo
- `size`: the number of elements in the fifo, this must be a power of 2
- `gfp_mask`: get_free_pages mask, passed to [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc)

**Description**

This macro dynamically allocates a new fifo buffer.

The number of elements will be rounded-up to a power of 2.
The fifo will be release with [`kfifo_free()`](#c-kfifo_free).
Return 0 if no error, otherwise an error code.

#### <a id="c-kfifo_alloc_node"></a>`kfifo_alloc_node()`

```c
kfifo_alloc_node(fifo, size, gfp_mask, node)
```

dynamically allocates a new fifo buffer on a NUMA node

**Parameters**

- `fifo`: pointer to the fifo
- `size`: the number of elements in the fifo, this must be a power of 2
- `gfp_mask`: get_free_pages mask, passed to [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc)
- `node`: NUMA node to allocate memory on

**Description**

This macro dynamically allocates a new fifo buffer with NUMA node awareness.

The number of elements will be rounded-up to a power of 2.
The fifo will be release with [`kfifo_free()`](#c-kfifo_free).
Return 0 if no error, otherwise an error code.

#### <a id="c-kfifo_free"></a>`kfifo_free()`

```c
kfifo_free(fifo)
```

frees the fifo

**Parameters**

- `fifo`: the fifo to be freed

#### <a id="c-kfifo_init"></a>`kfifo_init()`

```c
kfifo_init(fifo, buffer, size)
```

initialize a fifo using a preallocated buffer

**Parameters**

- `fifo`: the fifo to assign the buffer
- `buffer`: the preallocated buffer to be used
- `size`: the size of the internal buffer, this have to be a power of 2

**Description**

This macro initializes a fifo using a preallocated buffer.

The number of elements will be rounded-up to a power of 2.
Return 0 if no error, otherwise an error code.

#### <a id="c-kfifo_put"></a>`kfifo_put()`

```c
kfifo_put(fifo, val)
```

put data into the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `val`: the data to be added

**Description**

This macro copies the given value into the fifo.
It returns 0 if the fifo was full. Otherwise it returns the number
processed elements.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_get"></a>`kfifo_get()`

```c
kfifo_get(fifo, val)
```

get data from the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `val`: address where to store the data

**Description**

This macro reads the data from the fifo.
It returns 0 if the fifo was empty. Otherwise it returns the number
processed elements.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_peek"></a>`kfifo_peek()`

```c
kfifo_peek(fifo, val)
```

get data from the fifo without removing

**Parameters**

- `fifo`: address of the fifo to be used
- `val`: address where to store the data

**Description**

This reads the data from the fifo without removing it from the fifo.
It returns 0 if the fifo was empty. Otherwise it returns the number
processed elements.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_in"></a>`kfifo_in()`

```c
kfifo_in(fifo, buf, n)
```

put data into the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: the data to be added
- `n`: number of elements to be added

**Description**

This macro copies the given buffer into the fifo and returns the
number of copied elements.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_in_spinlocked"></a>`kfifo_in_spinlocked()`

```c
kfifo_in_spinlocked(fifo, buf, n, lock)
```

put data into the fifo using a spinlock for locking

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: the data to be added
- `n`: number of elements to be added
- `lock`: pointer to the spinlock to use for locking

**Description**

This macro copies the given values buffer into the fifo and returns the
number of copied elements.

#### <a id="c-kfifo_in_spinlocked_noirqsave"></a>`kfifo_in_spinlocked_noirqsave()`

```c
kfifo_in_spinlocked_noirqsave(fifo, buf, n, lock)
```

put data into fifo using a spinlock for locking, don't disable interrupts

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: the data to be added
- `n`: number of elements to be added
- `lock`: pointer to the spinlock to use for locking

**Description**

This is a variant of [`kfifo_in_spinlocked()`](#c-kfifo_in_spinlocked) but uses spin_lock/`unlock()`
for locking and doesn't disable interrupts.

#### <a id="c-kfifo_out"></a>`kfifo_out()`

```c
kfifo_out(fifo, buf, n)
```

get data from the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: pointer to the storage buffer
- `n`: max. number of elements to get

**Description**

This macro gets some data from the fifo and returns the numbers of elements
copied.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_out_spinlocked"></a>`kfifo_out_spinlocked()`

```c
kfifo_out_spinlocked(fifo, buf, n, lock)
```

get data from the fifo using a spinlock for locking

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: pointer to the storage buffer
- `n`: max. number of elements to get
- `lock`: pointer to the spinlock to use for locking

**Description**

This macro gets the data from the fifo and returns the numbers of elements
copied.

#### <a id="c-kfifo_out_spinlocked_noirqsave"></a>`kfifo_out_spinlocked_noirqsave()`

```c
kfifo_out_spinlocked_noirqsave(fifo, buf, n, lock)
```

get data from the fifo using a spinlock for locking, don't disable interrupts

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: pointer to the storage buffer
- `n`: max. number of elements to get
- `lock`: pointer to the spinlock to use for locking

**Description**

This is a variant of [`kfifo_out_spinlocked()`](#c-kfifo_out_spinlocked) which uses spin_lock/`unlock()`
for locking and doesn't disable interrupts.

#### <a id="c-kfifo_from_user"></a>`kfifo_from_user()`

```c
kfifo_from_user(fifo, from, len, copied)
```

puts some data from user space into the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `from`: pointer to the data to be added
- `len`: the length of the data to be added
- `copied`: pointer to output variable to store the number of copied bytes

**Description**

This macro copies at most **len** bytes from the **from** into the
fifo, depending of the available space and returns -EFAULT/0.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_to_user"></a>`kfifo_to_user()`

```c
kfifo_to_user(fifo, to, len, copied)
```

copies data from the fifo into user space

**Parameters**

- `fifo`: address of the fifo to be used
- `to`: where the data must be copied
- `len`: the size of the destination buffer
- `copied`: pointer to output variable to store the number of copied bytes

**Description**

This macro copies at most **len** bytes from the fifo into the
**to** buffer and returns -EFAULT/0.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_dma_in_prepare_mapped"></a>`kfifo_dma_in_prepare_mapped()`

```c
kfifo_dma_in_prepare_mapped(fifo, sgl, nents, len, dma)
```

setup a scatterlist for DMA input

**Parameters**

- `fifo`: address of the fifo to be used
- `sgl`: pointer to the scatterlist array
- `nents`: number of entries in the scatterlist array
- `len`: number of elements to transfer
- `dma`: mapped dma address to fill into **sgl**

**Description**

This macro fills a scatterlist for DMA input.
It returns the number entries in the scatterlist array.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macros.

#### <a id="c-kfifo_dma_in_finish"></a>`kfifo_dma_in_finish()`

```c
kfifo_dma_in_finish(fifo, len)
```

finish a DMA IN operation

**Parameters**

- `fifo`: address of the fifo to be used
- `len`: number of bytes to received

**Description**

This macro finishes a DMA IN operation. The in counter will be updated by
the len parameter. No error checking will be done.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macros.

#### <a id="c-kfifo_dma_out_prepare_mapped"></a>`kfifo_dma_out_prepare_mapped()`

```c
kfifo_dma_out_prepare_mapped(fifo, sgl, nents, len, dma)
```

setup a scatterlist for DMA output

**Parameters**

- `fifo`: address of the fifo to be used
- `sgl`: pointer to the scatterlist array
- `nents`: number of entries in the scatterlist array
- `len`: number of elements to transfer
- `dma`: mapped dma address to fill into **sgl**

**Description**

This macro fills a scatterlist for DMA output which at most **len** bytes
to transfer.
It returns the number entries in the scatterlist array.
A zero means there is no space available and the scatterlist is not filled.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macros.

#### <a id="c-kfifo_dma_out_finish"></a>`kfifo_dma_out_finish()`

```c
kfifo_dma_out_finish(fifo, len)
```

finish a DMA OUT operation

**Parameters**

- `fifo`: address of the fifo to be used
- `len`: number of bytes transferred

**Description**

This macro finishes a DMA OUT operation. The out counter will be updated by
the len parameter. No error checking will be done.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macros.

#### <a id="c-kfifo_out_peek"></a>`kfifo_out_peek()`

```c
kfifo_out_peek(fifo, buf, n)
```

gets some data from the fifo

**Parameters**

- `fifo`: address of the fifo to be used
- `buf`: pointer to the storage buffer
- `n`: max. number of elements to get

**Description**

This macro gets the data from the fifo and returns the numbers of elements
copied. The data is not removed from the fifo.

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_out_linear"></a>`kfifo_out_linear()`

```c
kfifo_out_linear(fifo, tail, n)
```

gets a tail of/offset to available data

**Parameters**

- `fifo`: address of the fifo to be used
- `tail`: pointer to an unsigned int to store the value of tail
- `n`: max. number of elements to point at

**Description**

This macro obtains the offset (tail) to the available data in the fifo
buffer and returns the
numbers of elements available. It returns the available count till the end
of data or till the end of the buffer. So that it can be used for linear
data processing (like [`memcpy()`](#c-memcpy) of (**fifo->data** + **tail**) with count
returned).

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.

#### <a id="c-kfifo_out_linear_ptr"></a>`kfifo_out_linear_ptr()`

```c
kfifo_out_linear_ptr(fifo, ptr, n)
```

gets a pointer to the available data

**Parameters**

- `fifo`: address of the fifo to be used
- `ptr`: pointer to data to store the pointer to tail
- `n`: max. number of elements to point at

**Description**

Similarly to [`kfifo_out_linear()`](#c-kfifo_out_linear), this macro obtains the pointer to the
available data in the fifo buffer and returns the numbers of elements
available. It returns the available count till the end of available data or
till the end of the buffer. So that it can be used for linear data
processing (like [`memcpy()`](#c-memcpy) of **ptr** with count returned).

Note that with only one concurrent reader and one concurrent
writer, you don't need extra locking to use these macro.


<a id="rst-relay-interface-support"></a>

## relay interface support

Relay interface support is designed to provide an efficient mechanism for tools and facilities to relay large amounts of data from kernel space to user space.

<a id="rst-relay-interface"></a>

### relay interface


#### <a id="c-relay_buf_full"></a>`relay_buf_full()`

```c
int relay_buf_full(struct rchan_buf *buf)
```

boolean, is the channel buffer full?

**Parameters**

- `struct rchan_buf *buf`: channel buffer

**Description**

Returns 1 if the buffer is full, 0 otherwise.

#### <a id="c-relay_reset"></a>`relay_reset()`

```c
void relay_reset(struct rchan *chan)
```

reset the channel

**Parameters**

- `struct rchan *chan`: the channel

**Description**

This has the effect of erasing all data from all channel buffers
and restarting the channel in its initial state.  The buffers
are not freed, so any mappings are still in effect.

NOTE. Care should be taken that the channel isn't actually
being used by anything when this call is made.

#### <a id="c-relay_open"></a>`relay_open()`

```c
struct rchan * relay_open(const char *base_filename, struct dentry *parent, size_t subbuf_size, size_t n_subbufs, const struct rchan_callbacks *cb, void *private_data)
```

create a new relay channel

**Parameters**

- `const char *base_filename`: base name of files to create
- `struct dentry *parent`: dentry of parent directory, `NULL` for root directory or buffer
- `size_t subbuf_size`: size of sub-buffers
- `size_t n_subbufs`: number of sub-buffers
- `const struct rchan_callbacks *cb`: client callback functions
- `void *private_data`: user-defined data

**Description**

Returns channel pointer if successful, `NULL` otherwise.

Creates a channel buffer for each cpu using the sizes and
attributes specified.  The created channel buffer files
will be named base_filename0...base_filenameN-1.  File
permissions will be `S_IRUSR`.

#### <a id="c-relay_switch_subbuf"></a>`relay_switch_subbuf()`

```c
size_t relay_switch_subbuf(struct rchan_buf *buf, size_t length)
```

switch to a new sub-buffer

**Parameters**

- `struct rchan_buf *buf`: channel buffer
- `size_t length`: size of current event

**Description**

Returns either the length passed in or 0 if full.

Performs sub-buffer-switch tasks such as invoking callbacks,
updating padding counts, waking up readers, etc.

#### <a id="c-relay_subbufs_consumed"></a>`relay_subbufs_consumed()`

```c
void relay_subbufs_consumed(struct rchan *chan, unsigned int cpu, size_t subbufs_consumed)
```

update the buffer's sub-buffers-consumed count

**Parameters**

- `struct rchan *chan`: the channel
- `unsigned int cpu`: the cpu associated with the channel buffer to update
- `size_t subbufs_consumed`: number of sub-buffers to add to current buf's count

**Description**

Adds to the channel buffer's consumed sub-buffer count.
subbufs_consumed should be the number of sub-buffers newly consumed,
not the total consumed.

NOTE. Kernel clients don't need to call this function if the channel
mode is 'overwrite'.

#### <a id="c-relay_close"></a>`relay_close()`

```c
void relay_close(struct rchan *chan)
```

close the channel

**Parameters**

- `struct rchan *chan`: the channel

**Description**

Closes all channel buffers and frees the channel.

#### <a id="c-relay_flush"></a>`relay_flush()`

```c
void relay_flush(struct rchan *chan)
```

close the channel

**Parameters**

- `struct rchan *chan`: the channel

**Description**

Flushes all channel buffers, i.e. forces buffer switch.



#### <a id="c-relay_mmap_prepare_buf"></a>`relay_mmap_prepare_buf()`

```c
int relay_mmap_prepare_buf(struct rchan_buf *buf, struct vm_area_desc *desc)
```

- mmap channel buffer to process address space

**Parameters**

- `struct rchan_buf *buf`: the relay channel buffer
- `struct vm_area_desc *desc`: describing what to map

**Description**

Returns 0 if ok, negative on error

Caller should already have grabbed mmap_lock.

#### <a id="c-relay_alloc_buf"></a>`relay_alloc_buf()`

```c
void * relay_alloc_buf(struct rchan_buf *buf, size_t *size)
```

allocate a channel buffer

**Parameters**

- `struct rchan_buf *buf`: the buffer struct
- `size_t *size`: total size of the buffer

**Description**

Returns a pointer to the resulting buffer, `NULL` if unsuccessful. The
passed in size will get page aligned, if it isn't already.

#### <a id="c-relay_create_buf"></a>`relay_create_buf()`

```c
struct rchan_buf * relay_create_buf(struct rchan *chan)
```

allocate and initialize a channel buffer

**Parameters**

- `struct rchan *chan`: the relay channel

**Description**

Returns channel buffer if successful, `NULL` otherwise.

#### <a id="c-relay_destroy_channel"></a>`relay_destroy_channel()`

```c
void relay_destroy_channel(struct kref *kref)
```

free the channel struct

**Parameters**

- `struct kref *kref`: target kernel reference that contains the relay channel

**Description**

Should only be called from [`kref_put()`](/kernel/internals/core-api/kref.md#c-kref_put).

#### <a id="c-relay_destroy_buf"></a>`relay_destroy_buf()`

```c
void relay_destroy_buf(struct rchan_buf *buf)
```

destroy an rchan_buf struct and associated buffer

**Parameters**

- `struct rchan_buf *buf`: the buffer struct

#### <a id="c-relay_remove_buf"></a>`relay_remove_buf()`

```c
void relay_remove_buf(struct kref *kref)
```

remove a channel buffer

**Parameters**

- `struct kref *kref`: target kernel reference that contains the relay buffer

**Description**

Removes the file from the filesystem, which also frees the
rchan_buf_struct and the channel buffer.  Should only be called from
[`kref_put()`](/kernel/internals/core-api/kref.md#c-kref_put).

#### <a id="c-relay_buf_empty"></a>`relay_buf_empty()`

```c
int relay_buf_empty(struct rchan_buf *buf)
```

boolean, is the channel buffer empty?

**Parameters**

- `struct rchan_buf *buf`: channel buffer

**Description**

Returns 1 if the buffer is empty, 0 otherwise.

#### <a id="c-wakeup_readers"></a>`wakeup_readers()`

```c
void wakeup_readers(struct irq_work *work)
```

wake up readers waiting on a channel

**Parameters**

- `struct irq_work *work`: contains the channel buffer

**Description**

This is the function used to defer reader waking

#### <a id="c-__relay_reset"></a>`__relay_reset()`

```c
void __relay_reset(struct rchan_buf *buf, unsigned int init)
```

reset a channel buffer

**Parameters**

- `struct rchan_buf *buf`: the channel buffer
- `unsigned int init`: 1 if this is a first-time initialization

**Description**

See [`relay_reset()`](#c-relay_reset) for description of effect.

#### <a id="c-relay_close_buf"></a>`relay_close_buf()`

```c
void relay_close_buf(struct rchan_buf *buf)
```

close a channel buffer

**Parameters**

- `struct rchan_buf *buf`: channel buffer

**Description**

Marks the buffer finalized and restores the default callbacks.
The channel buffer and channel buffer data structure are then freed
automatically when the last reference is given up.

#### <a id="c-relay_stats"></a>`relay_stats()`

```c
size_t relay_stats(struct rchan *chan, int flags)
```

get channel buffer statistics

**Parameters**

- `struct rchan *chan`: the channel
- `int flags`: select particular information to get

**Description**

Returns the count of certain field that caller specifies.

#### <a id="c-relay_file_open"></a>`relay_file_open()`

```c
int relay_file_open(struct inode *inode, struct file *filp)
```

open file op for relay files

**Parameters**

- `struct inode *inode`: the inode
- `struct file *filp`: the file

**Description**

Increments the channel buffer refcount.

#### <a id="c-relay_file_mmap_prepare"></a>`relay_file_mmap_prepare()`

```c
int relay_file_mmap_prepare(struct vm_area_desc *desc)
```

mmap file op for relay files

**Parameters**

- `struct vm_area_desc *desc`: describing what to map

**Description**

Calls upon [`relay_mmap_prepare_buf()`](#c-relay_mmap_prepare_buf) to map the file into user space.

#### <a id="c-relay_file_poll"></a>`relay_file_poll()`

```c
__poll_t relay_file_poll(struct file *filp, poll_table *wait)
```

poll file op for relay files

**Parameters**

- `struct file *filp`: the file
- `poll_table *wait`: poll table

**Description**

Poll implemention.

#### <a id="c-relay_file_release"></a>`relay_file_release()`

```c
int relay_file_release(struct inode *inode, struct file *filp)
```

release file op for relay files

**Parameters**

- `struct inode *inode`: the inode
- `struct file *filp`: the file

**Description**

Decrements the channel refcount, as the filesystem is
no longer using it.

#### <a id="c-relay_file_read_subbuf_avail"></a>`relay_file_read_subbuf_avail()`

```c
size_t relay_file_read_subbuf_avail(size_t read_pos, struct rchan_buf *buf)
```

return bytes available in sub-buffer

**Parameters**

- `size_t read_pos`: file read position
- `struct rchan_buf *buf`: relay channel buffer

#### <a id="c-relay_file_read_start_pos"></a>`relay_file_read_start_pos()`

```c
size_t relay_file_read_start_pos(struct rchan_buf *buf)
```

find the first available byte to read

**Parameters**

- `struct rchan_buf *buf`: relay channel buffer

**Description**

If the read_pos is in the middle of padding, return the
position of the first actually available byte, otherwise
return the original value.

#### <a id="c-relay_file_read_end_pos"></a>`relay_file_read_end_pos()`

```c
size_t relay_file_read_end_pos(struct rchan_buf *buf, size_t read_pos, size_t count)
```

return the new read position

**Parameters**

- `struct rchan_buf *buf`: relay channel buffer
- `size_t read_pos`: file read position
- `size_t count`: number of bytes to be read


<a id="rst-module-support"></a>

## Module Support

<a id="rst-kernel-module-auto-loading"></a>

### Kernel module auto-loading


#### <a id="c-__request_module"></a>`__request_module()`

```c
int __request_module(bool wait, const char *fmt, ...)
```

try to load a kernel module

**Parameters**

- `bool wait`: wait (or not) for the operation to complete
- `const char *fmt`: printf style format string for the name of the module
- `...`: arguments as specified in the format string

**Description**

Load a module using the user mode module loader. The function returns
zero on success or a negative errno code or positive exit code from
"modprobe" on failure. Note that a successful module load does not mean
the module did not then unload and exit on an error of its own. Callers
must check that the service they requested is now available not blindly
invoke it.

If module auto-loading support is disabled then this function
simply returns -ENOENT.


<a id="rst-module-debugging"></a>

### Module debugging


Enabling CONFIG_MODULE_STATS enables module debugging statistics which
are useful to monitor and root cause memory pressure issues with module
loading. These statistics are useful to allow us to improve production
workloads.

The current module debugging statistics supported help keep track of module
loading failures to enable improvements either for kernel module auto-loading
usage (`request_module()`) or interactions with userspace. Statistics are
provided to track all possible failures in the `finit_module()` path and memory
wasted in this process space.  Each of the failure counters are associated
to a type of module loading failure which is known to incur a certain amount
of memory allocation loss. In the worst case loading a module will fail after
a 3 step memory allocation process:

a) memory allocated with `kernel_read_file_from_fd()`
b) module decompression processes the file read from
`kernel_read_file_from_fd()`, and [`vmap()`](/kernel/internals/core-api/mm-api.md#c-vmap) is used to map
the decompressed module to a new local buffer which represents
a copy of the decompressed module passed from userspace. The buffer
from `kernel_read_file_from_fd()` is freed right away.
c) `layout_and_allocate()` allocates space for the final resting
place where we would keep the module if it were to be processed
successfully.

If a failure occurs after these three different allocations only one
counter will be incremented with the summation of the allocated bytes freed
incurred during this failure. Likewise, if module loading failed only after
step b) a separate counter is used and incremented for the bytes freed and
not used during both of those allocations.

Virtual memory space can be limited, for example on x86 virtual memory size
defaults to 128 MiB. We should strive to limit and avoid wasting virtual
memory allocations when possible. These module debugging statistics help
to evaluate how much memory is being wasted on bootup due to module loading
failures.

All counters are designed to be incremental. Atomic counters are used so to
remain simple and avoid delays and deadlocks.


<a id="rst-dup-failed-modules-tracks-duplicate-failed-modules"></a>

#### dup_failed_modules - tracks duplicate failed modules


Linked list of modules which failed to be loaded because an already existing
module with the same name was already being processed or already loaded.
The `finit_module()` system call incurs heavy virtual memory allocations. In
the worst case an `finit_module()` system call can end up allocating virtual
memory 3 times:

1) `kernel_read_file_from_fd()` call uses [`vmalloc()`](/kernel/internals/core-api/mm-api.md#c-vmalloc)
2) optional module decompression uses [`vmap()`](/kernel/internals/core-api/mm-api.md#c-vmap)
3) layout_and `allocate()` can use [`vzalloc()`](/kernel/internals/core-api/mm-api.md#c-vzalloc) or an arch specific variation of
   vmalloc to deal with ELF sections requiring special permissions

In practice on a typical boot today most `finit_module()` calls fail due to
the module with the same name already being loaded or about to be processed.
All virtual memory allocated to these failed modules will be freed with
no functional use.

To help with this the dup_failed_modules allows us to track modules which
failed to load due to the fact that a module was already loaded or being
processed.  There are only two points at which we can fail such calls,
we list them below along with the number of virtual memory allocation
calls:

- a) FAIL_DUP_MOD_BECOMING: at the end of `early_mod_check()` before

  `layout_and_allocate()`.
  - with module decompression: 2 virtual memory allocation calls
  - without module decompression: 1 virtual memory allocation calls
  - b) FAIL_DUP_MOD_LOAD: after `layout_and_allocate()` on `add_unformed_module()`

    - with module decompression 3 virtual memory allocation calls
    - without module decompression 2 virtual memory allocation calls

We should strive to get this list to be as small as possible. If this list
is not empty it is a reflection of possible work or optimizations possible
either in-kernel or in userspace.


<a id="rst-module-statistics-debugfs-counters"></a>

#### module statistics debugfs counters


The total amount of wasted virtual memory allocation space during module
loading can be computed by adding the total from the summation:

* **invalid_kread_bytes** +
  **invalid_decompress_bytes** +
  **invalid_becoming_bytes** +
  **invalid_mod_bytes**

The following debugfs counters are available to inspect module loading
failures:

* total_mod_size: total bytes ever used by all modules we've dealt with on
  this system
* total_text_size: total bytes of the .text and .init.text ELF section
  sizes we've dealt with on this system
* invalid_kread_bytes: bytes allocated and then freed on failures which
  happen due to the initial `kernel_read_file_from_fd()`. `kernel_read_file_from_fd()`
  uses [`vmalloc()`](/kernel/internals/core-api/mm-api.md#c-vmalloc). These should typically not happen unless your system is
  under memory pressure.
* invalid_decompress_bytes: number of bytes allocated and freed due to
  memory allocations in the module decompression path that use [`vmap()`](/kernel/internals/core-api/mm-api.md#c-vmap).
  These typically should not happen unless your system is under memory
  pressure.
* invalid_becoming_bytes: total number of bytes allocated and freed used
  to read the kernel module userspace wants us to read before we
  promote it to be processed to be added to our **modules** linked list. These
  failures can happen if we had a check in between a successful `kernel_read_file_from_fd()`
  call and right before we allocate the our private memory for the module
  which would be kept if the module is successfully loaded. The most common
  reason for this failure is when userspace is racing to load a module
  which it does not yet see loaded. The first module to succeed in
  `add_unformed_module()` will add a module to our `modules` list and
  subsequent loads of modules with the same name will error out at the
  end of `early_mod_check()`. The check for `module_patient_check_exists()`
  at the end of `early_mod_check()` prevents duplicate allocations
  on `layout_and_allocate()` for modules already being processed. These
  duplicate failed modules are non-fatal, however they typically are
  indicative of userspace not seeing a module in userspace loaded yet and
  unnecessarily trying to load a module before the kernel even has a chance
  to begin to process prior requests. Although duplicate failures can be
  non-fatal, we should try to reduce [`vmalloc()`](/kernel/internals/core-api/mm-api.md#c-vmalloc) pressure proactively, so
  ideally after boot this will be close to as 0 as possible.  If module
  decompression was used we also add to this counter the cost of the
  initial `kernel_read_file_from_fd()` of the compressed module. If module
  decompression was not used the value represents the total allocated and
  freed bytes in `kernel_read_file_from_fd()` calls for these type of
  failures. These failures can occur because:

  * `module_sig_check()` - module signature checks
  * `elf_validity_cache_copy()` - some ELF validation issue
  * `early_mod_check()`:

    * blacklisting
    * failed to rewrite section headers
    * version magic
    * live patch requirements didn't check out
    * the module was detected as being already present

* invalid_mod_bytes: these are the total number of bytes allocated and
  freed due to failures after we did all the sanity checks of the module
  which userspace passed to us and after our first check that the module
  is unique.  A module can still fail to load if we detect the module is
  loaded after we allocate space for it with `layout_and_allocate()`, we do
  this check right before processing the module as live and run its
  initialization routines. Note that you have a failure of this type it
  also means the respective `kernel_read_file_from_fd()` memory space was
  also freed and not used, and so we increment this counter with twice
  the size of the module. Additionally if you used module decompression
  the size of the compressed module is also added to this counter.

* modcount: how many modules we've loaded in our kernel life time
* failed_kreads: how many modules failed due to failed `kernel_read_file_from_fd()`
* failed_decompress: how many failed module decompression attempts we've had.
  These really should not happen unless your compression / decompression
  might be broken.
* failed_becoming: how many modules failed after we `kernel_read_file_from_fd()`
  it and before we allocate memory for it with `layout_and_allocate()`. This
  counter is never incremented if you manage to validate the module and
  call `layout_and_allocate()` for it.
* failed_load_modules: how many modules failed once we've allocated our
  private space for our module using `layout_and_allocate()`. These failures
  should hopefully mostly be dealt with already. Races in theory could
  still exist here, but it would just mean the kernel had started processing
  two threads concurrently up to `early_mod_check()` and one thread won.
  These failures are good signs the kernel or userspace is doing something
  seriously stupid or that could be improved. We should strive to fix these,
  but it is perhaps not easy to fix them. A recent example are the modules
  requests incurred for frequency modules, a separate module request was
  being issued for each CPU on a system.


<a id="rst-inter-module-support"></a>

### Inter Module support

Refer to the files in kernel/module/ for more information.

<a id="rst-hardware-interfaces"></a>

## Hardware Interfaces

<a id="rst-dma-channels"></a>

### DMA Channels


#### <a id="c-request_dma"></a>`request_dma()`

```c
int request_dma(unsigned int dmanr, const char * device_id)
```

request and reserve a system DMA channel

**Parameters**

- `unsigned int dmanr`: DMA channel number
- `const char * device_id`: reserving device ID string, used in /proc/dma

#### <a id="c-free_dma"></a>`free_dma()`

```c
void free_dma(unsigned int dmanr)
```

free a reserved system DMA channel

**Parameters**

- `unsigned int dmanr`: DMA channel number


<a id="rst-resources-management"></a>

### Resources Management


#### <a id="c-request_resource_conflict"></a>`request_resource_conflict()`

```c
struct resource * request_resource_conflict(struct resource *root, struct resource *new)
```

request and reserve an I/O or memory resource

**Parameters**

- `struct resource *root`: root resource descriptor
- `struct resource *new`: resource descriptor desired by caller

**Description**

Returns 0 for success, conflict resource on error.

#### <a id="c-find_next_res"></a>`find_next_res()`

```c
int find_next_res(struct resource *parent, resource_size_t start, resource_size_t end, unsigned long flags, unsigned long desc, struct resource *res)
```

Finds the lowest resource that covers part of \[**start**..**end**\].

**Parameters**

- `struct resource *parent`: resource tree root to search
- `resource_size_t start`: start address of the resource searched for
- `resource_size_t end`: end address of same resource
- `unsigned long flags`: flags which the resource must have
- `unsigned long desc`: descriptor the resource must have
- `struct resource *res`: return ptr, if resource found

**Description**

If a resource is found, returns 0 and @*res is overwritten with the part
of the resource that's within \[**start**..**end**\]; if none is found, returns
-ENODEV.  Returns -EINVAL for invalid parameters.

The caller must specify **start**, **end**, **flags**, and **desc**
(which may be IORES_DESC_NONE).

#### <a id="c-reallocate_resource"></a>`reallocate_resource()`

```c
int reallocate_resource(struct resource *root, struct resource *old, resource_size_t newsize, struct resource_constraint *constraint)
```

allocate a slot in the resource tree given range & alignment. The resource will be relocated if the new size cannot be reallocated in the current location.

**Parameters**

- `struct resource *root`: root resource descriptor
- `struct resource *old`: resource descriptor desired by caller
- `resource_size_t newsize`: new size of the resource descriptor
- `struct resource_constraint *constraint`: the memory range and alignment constraints to be met.

#### <a id="c-lookup_resource"></a>`lookup_resource()`

```c
struct resource * lookup_resource(struct resource *root, resource_size_t start)
```

find an existing resource by a resource start address

**Parameters**

- `struct resource *root`: root resource descriptor
- `resource_size_t start`: resource start address

**Description**

Returns a pointer to the resource if found, NULL otherwise

#### <a id="c-insert_resource_conflict"></a>`insert_resource_conflict()`

```c
struct resource * insert_resource_conflict(struct resource *parent, struct resource *new)
```

Inserts resource in the resource tree

**Parameters**

- `struct resource *parent`: parent of the new resource
- `struct resource *new`: new resource to insert

**Description**

Returns 0 on success, conflict resource if the resource can't be inserted.

This function is equivalent to request_resource_conflict when no conflict
happens. If a conflict happens, and the conflicting resources
entirely fit within the range of the new resource, then the new
resource is inserted and the conflicting resources become children of
the new resource.

This function is intended for producers of resources, such as FW modules
and bus drivers.

#### <a id="c-resource_alignment"></a>`resource_alignment()`

```c
resource_size_t resource_alignment(struct resource *res)
```

calculate resource's alignment

**Parameters**

- `struct resource *res`: resource pointer

**Description**

Returns alignment on success, 0 (invalid alignment) on failure.

#### <a id="c-release_mem_region_adjustable"></a>`release_mem_region_adjustable()`

```c
void release_mem_region_adjustable(resource_size_t start, resource_size_t size)
```

release a previously reserved memory region

**Parameters**

- `resource_size_t start`: resource start address
- `resource_size_t size`: resource region size

**Description**

This interface is intended for memory hot-delete.  The requested region
is released from a currently busy memory resource.  The requested region
must either match exactly or fit into a single busy resource entry.  In
the latter case, the remaining resource is adjusted accordingly.

**Note**

- Additional release conditions, such as overlapping region, can be
  supported after they are confirmed as valid cases.
- When a busy memory resource gets split into two entries, its children are
  reassigned to the correct parent based on their range. If a child memory
  resource overlaps with more than one parent, enhance the logic as needed.

#### <a id="c-merge_system_ram_resource"></a>`merge_system_ram_resource()`

```c
void merge_system_ram_resource(struct resource *res)
```

mark the System RAM resource mergeable and try to merge it with adjacent, mergeable resources

**Parameters**

- `struct resource *res`: resource descriptor

**Description**

This interface is intended for memory hotplug, whereby lots of contiguous
system ram resources are added (e.g., via add_memory*()) by a driver, and
the actual resource boundaries are not of interest (e.g., it might be
relevant for DIMMs). Only resources that are marked mergeable, that have the
same parent, and that don't have any children are considered. All mergeable
resources must be immutable during the request.

**Note**

- The caller has to make sure that no pointers to resources that are
  marked mergeable are used anymore after this call - the resource might
  be freed and the pointer might be stale!
- [`release_mem_region_adjustable()`](#c-release_mem_region_adjustable) will split on demand on memory hotunplug



#### <a id="c-request_resource"></a>`request_resource()`

```c
int request_resource(struct resource *root, struct resource *new)
```

request and reserve an I/O or memory resource

**Parameters**

- `struct resource *root`: root resource descriptor
- `struct resource *new`: resource descriptor desired by caller

**Description**

Returns 0 for success, negative error code on error.

#### <a id="c-release_resource"></a>`release_resource()`

```c
int release_resource(struct resource *old)
```

release a previously reserved resource

**Parameters**

- `struct resource *old`: resource pointer

#### <a id="c-walk_iomem_res_desc"></a>`walk_iomem_res_desc()`

```c
int walk_iomem_res_desc(unsigned long desc, unsigned long flags, u64 start, u64 end, void *arg, int (*func)(struct resource *, void *))
```

Walks through iomem resources and calls `func()` with matching resource ranges. *

**Parameters**

- `unsigned long desc`: I/O resource descriptor. Use IORES_DESC_NONE to skip **desc** check.
- `unsigned long flags`: I/O resource flags
- `u64 start`: start addr
- `u64 end`: end addr
- `void *arg`: function argument for the callback **func**
- `int (*func)(struct resource *, void *)`: callback function that is called for each qualifying resource area

**Description**

All the memory ranges which overlap start,end and also match flags and
desc are valid candidates.

**NOTE**

For a new descriptor search, define a new IORES_DESC in
\<linux/ioport.h> and set it in 'desc' of a target resource entry.

#### <a id="c-region_intersects"></a>`region_intersects()`

```c
int region_intersects(resource_size_t start, size_t size, unsigned long flags, unsigned long desc)
```

determine intersection of region with known resources

**Parameters**

- `resource_size_t start`: region start address
- `size_t size`: size of region
- `unsigned long flags`: flags of resource (in iomem_resource)
- `unsigned long desc`: descriptor of resource (in iomem_resource) or IORES_DESC_NONE

**Description**

Check if the specified region partially overlaps or fully eclipses a
resource identified by **flags** and **desc** (optional with IORES_DESC_NONE).
Return REGION_DISJOINT if the region does not overlap **flags**/**desc**,
return REGION_MIXED if the region overlaps **flags**/**desc** and another
resource, and return REGION_INTERSECTS if the region overlaps **flags**/**desc**
and no other defined resource. Note that REGION_INTERSECTS is also
returned in the case when the specified region overlaps RAM and undefined
memory holes.

`region_intersect()` is used by memory remapping functions to ensure
the user is not remapping RAM and is a vast speed up over walking
through the resource table page by page.

#### <a id="c-find_resource_space"></a>`find_resource_space()`

```c
int find_resource_space(struct resource *root, struct resource *new, resource_size_t size, struct resource_constraint *constraint)
```

Find empty space in the resource tree

**Parameters**

- `struct resource *root`: Root resource descriptor
- `struct resource *new`: Resource descriptor awaiting an empty resource space
- `resource_size_t size`: The minimum size of the empty space
- `struct resource_constraint *constraint`: The range and alignment constraints to be met

**Description**

Finds an empty space under **root** in the resource tree satisfying range and
alignment **constraints**.

**Return**

* `0`         - if successful, **new** members start, end, and flags are altered.
* `-EBUSY`    - if no empty space was found.

#### <a id="c-allocate_resource"></a>`allocate_resource()`

```c
int allocate_resource(struct resource *root, struct resource *new, resource_size_t size, resource_size_t min, resource_size_t max, resource_size_t align, resource_alignf alignf, void *alignf_data)
```

allocate empty slot in the resource tree given range & alignment. The resource will be reallocated with a new size if it was already allocated

**Parameters**

- `struct resource *root`: root resource descriptor
- `struct resource *new`: resource descriptor desired by caller
- `resource_size_t size`: requested resource region size
- `resource_size_t min`: minimum boundary to allocate
- `resource_size_t max`: maximum boundary to allocate
- `resource_size_t align`: alignment requested, in bytes
- `resource_alignf alignf`: alignment function, optional, called if not NULL
- `void *alignf_data`: arbitrary data to pass to the **alignf** function

#### <a id="c-insert_resource"></a>`insert_resource()`

```c
int insert_resource(struct resource *parent, struct resource *new)
```

Inserts a resource in the resource tree

**Parameters**

- `struct resource *parent`: parent of the new resource
- `struct resource *new`: new resource to insert

**Description**

Returns 0 on success, -EBUSY if the resource can't be inserted.

This function is intended for producers of resources, such as FW modules
and bus drivers.

#### <a id="c-insert_resource_expand_to_fit"></a>`insert_resource_expand_to_fit()`

```c
void insert_resource_expand_to_fit(struct resource *root, struct resource *new)
```

Insert a resource into the resource tree

**Parameters**

- `struct resource *root`: root resource descriptor
- `struct resource *new`: new resource to insert

**Description**

Insert a resource into the resource tree, possibly expanding it in order
to make it encompass any conflicting resources.

#### <a id="c-remove_resource"></a>`remove_resource()`

```c
int remove_resource(struct resource *old)
```

Remove a resource in the resource tree

**Parameters**

- `struct resource *old`: resource to remove

**Description**

Returns 0 on success, -EINVAL if the resource is not valid.

This function removes a resource previously inserted by [`insert_resource()`](#c-insert_resource)
or [`insert_resource_conflict()`](#c-insert_resource_conflict), and moves the children (if any) up to
where they were before.  [`insert_resource()`](#c-insert_resource) and [`insert_resource_conflict()`](#c-insert_resource_conflict)
insert a new resource, and move any conflicting resources down to the
children of the new resource.

[`insert_resource()`](#c-insert_resource), [`insert_resource_conflict()`](#c-insert_resource_conflict) and [`remove_resource()`](#c-remove_resource) are
intended for producers of resources, such as FW modules and bus drivers.

#### <a id="c-adjust_resource"></a>`adjust_resource()`

```c
int adjust_resource(struct resource *res, resource_size_t start, resource_size_t size)
```

modify a resource's start and size

**Parameters**

- `struct resource *res`: resource to modify
- `resource_size_t start`: new start value
- `resource_size_t size`: new size

**Description**

Given an existing resource, change its start and size to match the
arguments.  Returns 0 on success, -EBUSY if it can't fit.
Existing children of the resource are assumed to be immutable.

#### <a id="c-__request_region"></a>`__request_region()`

```c
struct resource * __request_region(struct resource *parent, resource_size_t start, resource_size_t n, const char *name, int flags)
```

create a new busy resource region

**Parameters**

- `struct resource *parent`: parent resource descriptor
- `resource_size_t start`: resource start address
- `resource_size_t n`: resource region size
- `const char *name`: reserving caller's ID string
- `int flags`: IO resource flags

#### <a id="c-__release_region"></a>`__release_region()`

```c
void __release_region(struct resource *parent, resource_size_t start, resource_size_t n)
```

release a previously reserved resource region

**Parameters**

- `struct resource *parent`: parent resource descriptor
- `resource_size_t start`: resource start address
- `resource_size_t n`: resource region size

**Description**

The described resource region must match a currently busy region.

#### <a id="c-devm_request_resource"></a>`devm_request_resource()`

```c
int devm_request_resource(struct device *dev, struct resource *root, struct resource *new)
```

request and reserve an I/O or memory resource

**Parameters**

- `struct device *dev`: device for which to request the resource
- `struct resource *root`: root of the resource tree from which to request the resource
- `struct resource *new`: descriptor of the resource to request

**Description**

This is a device-managed version of [`request_resource()`](#c-request_resource). There is usually
no need to release resources requested by this function explicitly since
that will be taken care of when the device is unbound from its driver.
If for some reason the resource needs to be released explicitly, because
of ordering issues for example, drivers must call [`devm_release_resource()`](#c-devm_release_resource)
rather than the regular [`release_resource()`](#c-release_resource).

When a conflict is detected between any existing resources and the newly
requested resource, an error message will be printed.

Returns 0 on success or a negative error code on failure.

#### <a id="c-devm_release_resource"></a>`devm_release_resource()`

```c
void devm_release_resource(struct device *dev, struct resource *new)
```

release a previously requested resource

**Parameters**

- `struct device *dev`: device for which to release the resource
- `struct resource *new`: descriptor of the resource to release

**Description**

Releases a resource previously requested using [`devm_request_resource()`](#c-devm_request_resource).

#### <a id="c-devm_request_free_mem_region"></a>`devm_request_free_mem_region()`

```c
struct resource * devm_request_free_mem_region(struct device *dev, struct resource *base, unsigned long size)
```

find free region for device private memory

**Parameters**

- `struct device *dev`: device struct to bind the resource to
- `struct resource *base`: resource tree to look in
- `unsigned long size`: size in bytes of the device memory to add

**Description**

This function tries to find an empty range of physical address big enough to
contain the new resource, so that it can later be hotplugged as ZONE_DEVICE
memory, which in turn allocates struct pages.

#### <a id="c-alloc_free_mem_region"></a>`alloc_free_mem_region()`

```c
struct resource * alloc_free_mem_region(struct resource *base, unsigned long size, unsigned long align, const char *name)
```

find a free region relative to **base**

**Parameters**

- `struct resource *base`: resource that will parent the new resource
- `unsigned long size`: size in bytes of memory to allocate from **base**
- `unsigned long align`: alignment requirements for the allocation
- `const char *name`: resource name

**Description**

Buses like CXL, that can dynamically instantiate new memory regions,
need a method to allocate physical address space for those regions.
Allocate and insert a new resource to cover a free, unclaimed by a
descendant of **base**, range in the span of **base**.


<a id="rst-mtrr-handling"></a>

### MTRR Handling


#### <a id="c-arch_phys_wc_add"></a>`arch_phys_wc_add()`

```c
int arch_phys_wc_add(unsigned long base, unsigned long size)
```

add a WC MTRR and handle errors if PAT is unavailable

**Parameters**

- `unsigned long base`: Physical base address
- `unsigned long size`: Size of region

**Description**

If PAT is available, this does nothing.  If PAT is unavailable, it
attempts to add a WC MTRR covering size bytes starting at base and
logs an error if this fails.

The called should provide a power of two size on an equivalent
power of two boundary.

Drivers must store the return value to pass to mtrr_del_wc_if_needed,
but drivers should not try to interpret that return value.


<a id="rst-security-framework"></a>

## Security Framework


#### <a id="c-lsm_file_alloc"></a>`lsm_file_alloc()`

```c
int lsm_file_alloc(struct file *file)
```

allocate a composite file blob

**Parameters**

- `struct file *file`: the file that needs a blob

**Description**

Allocate the file blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_backing_file_alloc"></a>`lsm_backing_file_alloc()`

```c
int lsm_backing_file_alloc(struct file *backing_file)
```

allocate a composite backing file blob

**Parameters**

- `struct file *backing_file`: the backing file

**Description**

Allocate the backing file blob for all the modules.

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_blob_alloc"></a>`lsm_blob_alloc()`

```c
int lsm_blob_alloc(void **dest, size_t size, gfp_t gfp)
```

allocate a composite blob

**Parameters**

- `void **dest`: the destination for the blob
- `size_t size`: the size of the blob
- `gfp_t gfp`: allocation type

**Description**

Allocate a blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_cred_alloc"></a>`lsm_cred_alloc()`

```c
int lsm_cred_alloc(struct cred *cred, gfp_t gfp)
```

allocate a composite cred blob

**Parameters**

- `struct cred *cred`: the cred that needs a blob
- `gfp_t gfp`: allocation type

**Description**

Allocate the cred blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_inode_alloc"></a>`lsm_inode_alloc()`

```c
int lsm_inode_alloc(struct inode *inode, gfp_t gfp)
```

allocate a composite inode blob

**Parameters**

- `struct inode *inode`: the inode that needs a blob
- `gfp_t gfp`: allocation flags

**Description**

Allocate the inode blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_task_alloc"></a>`lsm_task_alloc()`

```c
int lsm_task_alloc(struct task_struct *task)
```

allocate a composite task blob

**Parameters**

- `struct task_struct *task`: the task that needs a blob

**Description**

Allocate the task blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_ipc_alloc"></a>`lsm_ipc_alloc()`

```c
int lsm_ipc_alloc(struct kern_ipc_perm *kip)
```

allocate a composite ipc blob

**Parameters**

- `struct kern_ipc_perm *kip`: the ipc that needs a blob

**Description**

Allocate the ipc blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_key_alloc"></a>`lsm_key_alloc()`

```c
int lsm_key_alloc(struct key *key)
```

allocate a composite key blob

**Parameters**

- `struct key *key`: the key that needs a blob

**Description**

Allocate the key blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_msg_msg_alloc"></a>`lsm_msg_msg_alloc()`

```c
int lsm_msg_msg_alloc(struct msg_msg *mp)
```

allocate a composite msg_msg blob

**Parameters**

- `struct msg_msg *mp`: the msg_msg that needs a blob

**Description**

Allocate the ipc blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_bdev_alloc"></a>`lsm_bdev_alloc()`

```c
int lsm_bdev_alloc(struct block_device *bdev)
```

allocate a composite block_device blob

**Parameters**

- `struct block_device *bdev`: the block_device that needs a blob

**Description**

Allocate the block_device blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_bpf_map_alloc"></a>`lsm_bpf_map_alloc()`

```c
int lsm_bpf_map_alloc(struct bpf_map *map)
```

allocate a composite bpf_map blob

**Parameters**

- `struct bpf_map *map`: the bpf_map that needs a blob

**Description**

Allocate the bpf_map blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_bpf_prog_alloc"></a>`lsm_bpf_prog_alloc()`

```c
int lsm_bpf_prog_alloc(struct bpf_prog *prog)
```

allocate a composite bpf_prog blob

**Parameters**

- `struct bpf_prog *prog`: the bpf_prog that needs a blob

**Description**

Allocate the bpf_prog blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_bpf_token_alloc"></a>`lsm_bpf_token_alloc()`

```c
int lsm_bpf_token_alloc(struct bpf_token *token)
```

allocate a composite bpf_token blob

**Parameters**

- `struct bpf_token *token`: the bpf_token that needs a blob

**Description**

Allocate the bpf_token blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_superblock_alloc"></a>`lsm_superblock_alloc()`

```c
int lsm_superblock_alloc(struct super_block *sb)
```

allocate a composite superblock blob

**Parameters**

- `struct super_block *sb`: the superblock that needs a blob

**Description**

Allocate the superblock blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-lsm_fill_user_ctx"></a>`lsm_fill_user_ctx()`

```c
int lsm_fill_user_ctx(struct lsm_ctx __user *uctx, u32 *uctx_len, void *val, size_t val_len, u64 id, u64 flags)
```

Fill a user space lsm_ctx structure

**Parameters**

- `struct lsm_ctx __user *uctx`: a userspace LSM context to be filled
- `u32 *uctx_len`: available uctx size (input), used uctx size (output)
- `void *val`: the new LSM context value
- `size_t val_len`: the size of the new LSM context value
- `u64 id`: LSM id
- `u64 flags`: LSM defined flags

**Description**

Fill all of the fields in a userspace lsm_ctx structure.  If **uctx** is NULL
simply calculate the required size to output via **utc_len** and return
success.

Returns 0 on success, -E2BIG if userspace buffer is not large enough,
-EFAULT on a copyout error, -ENOMEM if memory can't be allocated.

#### <a id="c-security_binder_set_context_mgr"></a>`security_binder_set_context_mgr()`

```c
int security_binder_set_context_mgr(const struct cred *mgr)
```

Check if becoming binder ctx mgr is ok

**Parameters**

- `const struct cred *mgr`: task credentials of current binder process

**Description**

Check whether **mgr** is allowed to be the binder context manager.

**Return**

Return 0 if permission is granted.

#### <a id="c-security_binder_transaction"></a>`security_binder_transaction()`

```c
int security_binder_transaction(const struct cred *from, const struct cred *to)
```

Check if a binder transaction is allowed

**Parameters**

- `const struct cred *from`: sending process
- `const struct cred *to`: receiving process

**Description**

Check whether **from** is allowed to invoke a binder transaction call to **to**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_binder_transfer_binder"></a>`security_binder_transfer_binder()`

```c
int security_binder_transfer_binder(const struct cred *from, const struct cred *to)
```

Check if a binder transfer is allowed

**Parameters**

- `const struct cred *from`: sending process
- `const struct cred *to`: receiving process

**Description**

Check whether **from** is allowed to transfer a binder reference to **to**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_binder_transfer_file"></a>`security_binder_transfer_file()`

```c
int security_binder_transfer_file(const struct cred *from, const struct cred *to, const struct file *file)
```

Check if a binder file xfer is allowed

**Parameters**

- `const struct cred *from`: sending process
- `const struct cred *to`: receiving process
- `const struct file *file`: file being transferred

**Description**

Check whether **from** is allowed to transfer **file** to **to**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ptrace_access_check"></a>`security_ptrace_access_check()`

```c
int security_ptrace_access_check(struct task_struct *child, unsigned int mode)
```

Check if tracing is allowed

**Parameters**

- `struct task_struct *child`: target process
- `unsigned int mode`: PTRACE_MODE flags

**Description**

Check permission before allowing the current process to trace the **child**
process.  Security modules may also want to perform a process tracing check
during an execve in the set_security or apply_creds hooks of tracing check
during an execve in the bprm_set_creds hook of binprm_security_ops if the
process is being traced and its security attributes would be changed by the
execve.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ptrace_traceme"></a>`security_ptrace_traceme()`

```c
int security_ptrace_traceme(struct task_struct *parent)
```

Check if tracing is allowed

**Parameters**

- `struct task_struct *parent`: tracing process

**Description**

Check that the **parent** process has sufficient permission to trace the
current process before allowing the current process to present itself to the
**parent** process for tracing.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_capget"></a>`security_capget()`

```c
int security_capget(const struct task_struct *target, kernel_cap_t *effective, kernel_cap_t *inheritable, kernel_cap_t *permitted)
```

Get the capability sets for a process

**Parameters**

- `const struct task_struct *target`: target process
- `kernel_cap_t *effective`: effective capability set
- `kernel_cap_t *inheritable`: inheritable capability set
- `kernel_cap_t *permitted`: permitted capability set

**Description**

Get the **effective**, **inheritable**, and **permitted** capability sets for the
**target** process.  The hook may also perform permission checking to determine
if the current process is allowed to see the capability sets of the **target**
process.

**Return**

Returns 0 if the capability sets were successfully obtained.

#### <a id="c-security_capset"></a>`security_capset()`

```c
int security_capset(struct cred *new, const struct cred *old, const kernel_cap_t *effective, const kernel_cap_t *inheritable, const kernel_cap_t *permitted)
```

Set the capability sets for a process

**Parameters**

- `struct cred *new`: new credentials for the target process
- `const struct cred *old`: current credentials of the target process
- `const kernel_cap_t *effective`: effective capability set
- `const kernel_cap_t *inheritable`: inheritable capability set
- `const kernel_cap_t *permitted`: permitted capability set

**Description**

Set the **effective**, **inheritable**, and **permitted** capability sets for the
current process.

**Return**

Returns 0 and update **new** if permission is granted.

#### <a id="c-security_capable"></a>`security_capable()`

```c
int security_capable(const struct cred *cred, struct user_namespace *ns, int cap, unsigned int opts)
```

Check if a process has the necessary capability

**Parameters**

- `const struct cred *cred`: credentials to examine
- `struct user_namespace *ns`: user namespace
- `int cap`: capability requested
- `unsigned int opts`: capability check options

**Description**

Check whether the **tsk** process has the **cap** capability in the indicated
credentials.  **cap** contains the capability \<include/linux/capability.h>.
**opts** contains options for the capable check \<include/linux/security.h>.

**Return**

Returns 0 if the capability is granted.

#### <a id="c-security_quotactl"></a>`security_quotactl()`

```c
int security_quotactl(int cmds, int type, int id, const struct super_block *sb)
```

Check if a `quotactl()` syscall is allowed for this fs

**Parameters**

- `int cmds`: commands
- `int type`: type
- `int id`: id
- `const struct super_block *sb`: filesystem

**Description**

Check whether the quotactl syscall is allowed for this **sb**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_quota_on"></a>`security_quota_on()`

```c
int security_quota_on(struct dentry *dentry)
```

Check if QUOTAON is allowed for a dentry

**Parameters**

- `struct dentry *dentry`: dentry

**Description**

Check whether QUOTAON is allowed for **dentry**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_syslog"></a>`security_syslog()`

```c
int security_syslog(int type)
```

Check if accessing the kernel message ring is allowed

**Parameters**

- `int type`: SYSLOG_ACTION_* type

**Description**

Check permission before accessing the kernel message ring or changing
logging to the console.  See the syslog(2) manual page for an explanation of
the **type** values.

**Return**

Return 0 if permission is granted.

#### <a id="c-security_settime64"></a>`security_settime64()`

```c
int security_settime64(const struct timespec64 *ts, const struct timezone *tz)
```

Check if changing the system time is allowed

**Parameters**

- `const struct timespec64 *ts`: new time
- `const struct timezone *tz`: timezone

**Description**

Check permission to change the system time, struct timespec64 is defined in
\<include/linux/time64.h> and timezone is defined in \<include/linux/time.h>.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_vm_enough_memory_mm"></a>`security_vm_enough_memory_mm()`

```c
int security_vm_enough_memory_mm(struct mm_struct *mm, long pages)
```

Check if allocating a new mem map is allowed

**Parameters**

- `struct mm_struct *mm`: mm struct
- `long pages`: number of pages

**Description**

Check permissions for allocating a new virtual mapping.  If all LSMs return
a positive value, `__vm_enough_memory()` will be called with cap_sys_admin
set. If at least one LSM returns 0 or negative, `__vm_enough_memory()` will be
called with cap_sys_admin cleared.

**Return**

Returns 0 if permission is granted by the LSM infrastructure to the
caller.

#### <a id="c-security_bprm_creds_for_exec"></a>`security_bprm_creds_for_exec()`

```c
int security_bprm_creds_for_exec(struct linux_binprm *bprm)
```

Prepare the credentials for `exec()`

**Parameters**

- `struct linux_binprm *bprm`: binary program information

**Description**

If the setup in prepare_exec_creds did not setup **bprm->cred->security**
properly for executing **bprm->file**, update the LSM's portion of
**bprm->cred->security** to be what commit_creds needs to install for the new
program.  This hook may also optionally check permissions (e.g. for
transitions between security domains).  The hook must set **bprm->secureexec**
to 1 if AT_SECURE should be set to request libc enable secure mode.  **bprm**
contains the linux_binprm structure.

If execveat(2) is called with the AT_EXECVE_CHECK flag, bprm->is_check is
set.  The result must be the same as without this flag even if the execution
will never really happen and **bprm** will always be dropped.

This hook must not change current->cred, only **bprm->cred**.

**Return**

Returns 0 if the hook is successful and permission is granted.

#### <a id="c-security_bprm_creds_from_file"></a>`security_bprm_creds_from_file()`

```c
int security_bprm_creds_from_file(struct linux_binprm *bprm, const struct file *file)
```

Update linux_binprm creds based on file

**Parameters**

- `struct linux_binprm *bprm`: binary program information
- `const struct file *file`: associated file

**Description**

If **file** is setpcap, suid, sgid or otherwise marked to change privilege upon
exec, update **bprm->cred** to reflect that change. This is called after
finding the binary that will be executed without an interpreter.  This
ensures that the credentials will not be derived from a script that the
binary will need to reopen, which when reopend may end up being a completely
different file.  This hook may also optionally check permissions (e.g. for
transitions between security domains).  The hook must set **bprm->secureexec**
to 1 if AT_SECURE should be set to request libc enable secure mode.  The
hook must add to **bprm->per_clear** any personality flags that should be
cleared from current->personality.  **bprm** contains the linux_binprm
structure.

**Return**

Returns 0 if the hook is successful and permission is granted.

#### <a id="c-security_bprm_check"></a>`security_bprm_check()`

```c
int security_bprm_check(struct linux_binprm *bprm)
```

Mediate binary handler search

**Parameters**

- `struct linux_binprm *bprm`: binary program information

**Description**

This hook mediates the point when a search for a binary handler will begin.
It allows a check against the **bprm->cred->security** value which was set in
the preceding creds_for_exec call.  The argv list and envp list are reliably
available in **bprm**.  This hook may be called multiple times during a single
execve.  **bprm** contains the linux_binprm structure.

**Return**

Returns 0 if the hook is successful and permission is granted.

#### <a id="c-security_bprm_committing_creds"></a>`security_bprm_committing_creds()`

```c
void security_bprm_committing_creds(const struct linux_binprm *bprm)
```

Install creds for a process during `exec()`

**Parameters**

- `const struct linux_binprm *bprm`: binary program information

**Description**

Prepare to install the new security attributes of a process being
transformed by an execve operation, based on the old credentials pointed to
by **current->cred** and the information set in **bprm->cred** by the
bprm_creds_for_exec hook.  **bprm** points to the linux_binprm structure.  This
hook is a good place to perform state changes on the process such as closing
open file descriptors to which access will no longer be granted when the
attributes are changed.  This is called immediately before `commit_creds()`.

#### <a id="c-security_bprm_committed_creds"></a>`security_bprm_committed_creds()`

```c
void security_bprm_committed_creds(const struct linux_binprm *bprm)
```

Tidy up after cred install during `exec()`

**Parameters**

- `const struct linux_binprm *bprm`: binary program information

**Description**

Tidy up after the installation of the new security attributes of a process
being transformed by an execve operation.  The new credentials have, by this
point, been set to **current->cred**.  **bprm** points to the linux_binprm
structure.  This hook is a good place to perform state changes on the
process such as clearing out non-inheritable signal state.  This is called
immediately after `commit_creds()`.

#### <a id="c-security_fs_context_submount"></a>`security_fs_context_submount()`

```c
int security_fs_context_submount(struct fs_context *fc, struct super_block *reference)
```

Initialise fc->security

**Parameters**

- `struct fs_context *fc`: new filesystem context
- `struct super_block *reference`: dentry reference for submount/remount

**Description**

Fill out the ->security field for a new fs_context.

**Return**

Returns 0 on success or negative error code on failure.

#### <a id="c-security_fs_context_dup"></a>`security_fs_context_dup()`

```c
int security_fs_context_dup(struct fs_context *fc, struct fs_context *src_fc)
```

Duplicate a fs_context LSM blob

**Parameters**

- `struct fs_context *fc`: destination filesystem context
- `struct fs_context *src_fc`: source filesystem context

**Description**

Allocate and attach a security structure to sc->security.  This pointer is
initialised to NULL by the caller.  **fc** indicates the new filesystem context.
**src_fc** indicates the original filesystem context.

**Return**

Returns 0 on success or a negative error code on failure.

#### <a id="c-security_fs_context_parse_param"></a>`security_fs_context_parse_param()`

```c
int security_fs_context_parse_param(struct fs_context *fc, struct fs_parameter *param)
```

Configure a filesystem context

**Parameters**

- `struct fs_context *fc`: filesystem context
- `struct fs_parameter *param`: filesystem parameter

**Description**

Userspace provided a parameter to configure a superblock.  The LSM can
consume the parameter or return it to the caller for use elsewhere.

**Return**

If the parameter is used by the LSM it should return 0, if it is
returned to the caller -ENOPARAM is returned, otherwise a negative
error code is returned.

#### <a id="c-security_sb_alloc"></a>`security_sb_alloc()`

```c
int security_sb_alloc(struct super_block *sb)
```

Allocate a super_block LSM blob

**Parameters**

- `struct super_block *sb`: filesystem superblock

**Description**

Allocate and attach a security structure to the sb->s_security field.  The
s_security field is initialized to NULL when the structure is allocated.
**sb** contains the super_block structure to be modified.

**Return**

Returns 0 if operation was successful.

#### <a id="c-security_sb_delete"></a>`security_sb_delete()`

```c
void security_sb_delete(struct super_block *sb)
```

Release super_block LSM associated objects

**Parameters**

- `struct super_block *sb`: filesystem superblock

**Description**

Release objects tied to a superblock (e.g. inodes).  **sb** contains the
super_block structure being released.

#### <a id="c-security_sb_free"></a>`security_sb_free()`

```c
void security_sb_free(struct super_block *sb)
```

Free a super_block LSM blob

**Parameters**

- `struct super_block *sb`: filesystem superblock

**Description**

Deallocate and clear the sb->s_security field.  **sb** contains the super_block
structure to be modified.

#### <a id="c-security_sb_kern_mount"></a>`security_sb_kern_mount()`

```c
int security_sb_kern_mount(const struct super_block *sb)
```

Check if a kernel mount is allowed

**Parameters**

- `const struct super_block *sb`: filesystem superblock

**Description**

Mount this **sb** if allowed by permissions.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sb_show_options"></a>`security_sb_show_options()`

```c
int security_sb_show_options(struct seq_file *m, struct super_block *sb)
```

Output the mount options for a superblock

**Parameters**

- `struct seq_file *m`: output file
- `struct super_block *sb`: filesystem superblock

**Description**

Show (print on **m**) mount options for this **sb**.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_sb_statfs"></a>`security_sb_statfs()`

```c
int security_sb_statfs(struct dentry *dentry)
```

Check if accessing fs stats is allowed

**Parameters**

- `struct dentry *dentry`: superblock handle

**Description**

Check permission before obtaining filesystem statistics for the **mnt**
mountpoint.  **dentry** is a handle on the superblock for the filesystem.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sb_mount"></a>`security_sb_mount()`

```c
int security_sb_mount(const char *dev_name, const struct path *path, const char *type, unsigned long flags, void *data)
```

Check permission for mounting a filesystem

**Parameters**

- `const char *dev_name`: filesystem backing device
- `const struct path *path`: mount point
- `const char *type`: filesystem type
- `unsigned long flags`: mount flags
- `void *data`: filesystem specific data

**Description**

Check permission before an object specified by **dev_name** is mounted on the
mount point named by **nd**.  For an ordinary mount, **dev_name** identifies a
device if the file system type requires a device.  For a remount
(**flags** & MS_REMOUNT), **dev_name** is irrelevant.  For a loopback/bind mount
(**flags** & MS_BIND), **dev_name** identifies the pathname of the object being
mounted.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sb_umount"></a>`security_sb_umount()`

```c
int security_sb_umount(struct vfsmount *mnt, int flags)
```

Check permission for unmounting a filesystem

**Parameters**

- `struct vfsmount *mnt`: mounted filesystem
- `int flags`: unmount flags

**Description**

Check permission before the **mnt** file system is unmounted.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sb_pivotroot"></a>`security_sb_pivotroot()`

```c
int security_sb_pivotroot(const struct path *old_path, const struct path *new_path)
```

Check permissions for pivoting the rootfs

**Parameters**

- `const struct path *old_path`: new location for current rootfs
- `const struct path *new_path`: location of the new rootfs

**Description**

Check permission before pivoting the root filesystem.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_move_mount"></a>`security_move_mount()`

```c
int security_move_mount(const struct path *from_path, const struct path *to_path)
```

Check permissions for moving a mount

**Parameters**

- `const struct path *from_path`: source mount point
- `const struct path *to_path`: destination mount point

**Description**

Check permission before a mount is moved.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_notify"></a>`security_path_notify()`

```c
int security_path_notify(const struct path *path, u64 mask, unsigned int obj_type)
```

Check if setting a watch is allowed

**Parameters**

- `const struct path *path`: file path
- `u64 mask`: event mask
- `unsigned int obj_type`: file path type

**Description**

Check permissions before setting a watch on events as defined by **mask**, on
an object at **path**, whose type is defined by **obj_type**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_alloc"></a>`security_inode_alloc()`

```c
int security_inode_alloc(struct inode *inode, gfp_t gfp)
```

Allocate an inode LSM blob

**Parameters**

- `struct inode *inode`: the inode
- `gfp_t gfp`: allocation flags

**Description**

Allocate and attach a security structure to **inode->i_security**.  The
i_security field is initialized to NULL when the inode structure is
allocated.

**Return**

Return 0 if operation was successful.

#### <a id="c-security_inode_free"></a>`security_inode_free()`

```c
void security_inode_free(struct inode *inode)
```

Free an inode's LSM blob

**Parameters**

- `struct inode *inode`: the inode

**Description**

Release any LSM resources associated with **inode**, although due to the
inode's RCU protections it is possible that the resources will not be
fully released until after the current RCU grace period has elapsed.

It is important for LSMs to note that despite being present in a call to
[`security_inode_free()`](#c-security_inode_free), **inode** may still be referenced in a VFS path walk
and calls to [`security_inode_permission()`](#c-security_inode_permission) may be made during, or after,
a call to [`security_inode_free()`](#c-security_inode_free).  For this reason the inode->i_security
field is released via a [`call_rcu()`](#c-call_rcu) callback and any LSMs which need to
retain inode state for use in [`security_inode_permission()`](#c-security_inode_permission) should only
release that state in the `inode_free_security_rcu()` LSM hook callback.

#### <a id="c-security_inode_init_security_anon"></a>`security_inode_init_security_anon()`

```c
int security_inode_init_security_anon(struct inode *inode, const struct qstr *name, const struct inode *context_inode)
```

Initialize an anonymous inode

**Parameters**

- `struct inode *inode`: the inode
- `const struct qstr *name`: the anonymous inode class
- `const struct inode *context_inode`: an optional related inode

**Description**

Set up the incore security field for the new anonymous inode and return
whether the inode creation is permitted by the security module or not.

**Return**

Returns 0 on success, -EACCES if the security module denies the
creation of this inode, or another -errno upon other errors.

#### <a id="c-security_path_post_mknod"></a>`security_path_post_mknod()`

```c
void security_path_post_mknod(struct mnt_idmap *idmap, struct dentry *dentry)
```

Update inode security after reg file creation

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: new file

**Description**

Update inode security field after a regular file has been created.

#### <a id="c-security_path_rmdir"></a>`security_path_rmdir()`

```c
int security_path_rmdir(const struct path *dir, struct dentry *dentry)
```

Check if removing a directory is allowed

**Parameters**

- `const struct path *dir`: parent directory
- `struct dentry *dentry`: directory to remove

**Description**

Check the permission to remove a directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_symlink"></a>`security_path_symlink()`

```c
int security_path_symlink(const struct path *dir, struct dentry *dentry, const char *old_name)
```

Check if creating a symbolic link is allowed

**Parameters**

- `const struct path *dir`: parent directory
- `struct dentry *dentry`: symbolic link
- `const char *old_name`: file pathname

**Description**

Check the permission to create a symbolic link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_link"></a>`security_path_link()`

```c
int security_path_link(struct dentry *old_dentry, const struct path *new_dir, struct dentry *new_dentry)
```

Check if creating a hard link is allowed

**Parameters**

- `struct dentry *old_dentry`: existing file
- `const struct path *new_dir`: new parent directory
- `struct dentry *new_dentry`: new link

**Description**

Check permission before creating a new hard link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_truncate"></a>`security_path_truncate()`

```c
int security_path_truncate(const struct path *path)
```

Check if truncating a file is allowed

**Parameters**

- `const struct path *path`: file

**Description**

Check permission before truncating the file indicated by path.  Note that
truncation permissions may also be checked based on already opened files,
using the [`security_file_truncate()`](#c-security_file_truncate) hook.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_chmod"></a>`security_path_chmod()`

```c
int security_path_chmod(const struct path *path, umode_t mode)
```

Check if changing the file's mode is allowed

**Parameters**

- `const struct path *path`: file
- `umode_t mode`: new mode

**Description**

Check for permission to change a mode of the file **path**. The new mode is
specified in **mode** which is a bitmask of constants from
\<include/uapi/linux/stat.h>.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_chown"></a>`security_path_chown()`

```c
int security_path_chown(const struct path *path, kuid_t uid, kgid_t gid)
```

Check if changing the file's owner/group is allowed

**Parameters**

- `const struct path *path`: file
- `kuid_t uid`: file owner
- `kgid_t gid`: file group

**Description**

Check for permission to change owner/group of a file or directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_chroot"></a>`security_path_chroot()`

```c
int security_path_chroot(const struct path *path)
```

Check if changing the root directory is allowed

**Parameters**

- `const struct path *path`: directory

**Description**

Check for permission to change root directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_post_create_tmpfile"></a>`security_inode_post_create_tmpfile()`

```c
void security_inode_post_create_tmpfile(struct mnt_idmap *idmap, struct inode *inode)
```

Update inode security of new tmpfile

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct inode *inode`: inode of the new tmpfile

**Description**

Update inode security data after a tmpfile has been created.

#### <a id="c-security_inode_link"></a>`security_inode_link()`

```c
int security_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
```

Check if creating a hard link is allowed

**Parameters**

- `struct dentry *old_dentry`: existing file
- `struct inode *dir`: new parent directory
- `struct dentry *new_dentry`: new link

**Description**

Check permission before creating a new hard link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_unlink"></a>`security_inode_unlink()`

```c
int security_inode_unlink(struct inode *dir, struct dentry *dentry)
```

Check if removing a hard link is allowed

**Parameters**

- `struct inode *dir`: parent directory
- `struct dentry *dentry`: file

**Description**

Check the permission to remove a hard link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_symlink"></a>`security_inode_symlink()`

```c
int security_inode_symlink(struct inode *dir, struct dentry *dentry, const char *old_name)
```

Check if creating a symbolic link is allowed

**Parameters**

- `struct inode *dir`: parent directory
- `struct dentry *dentry`: symbolic link
- `const char *old_name`: existing filename

**Description**

Check the permission to create a symbolic link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_rmdir"></a>`security_inode_rmdir()`

```c
int security_inode_rmdir(struct inode *dir, struct dentry *dentry)
```

Check if removing a directory is allowed

**Parameters**

- `struct inode *dir`: parent directory
- `struct dentry *dentry`: directory to be removed

**Description**

Check the permission to remove a directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_mknod"></a>`security_inode_mknod()`

```c
int security_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
```

Check if creating a special file is allowed

**Parameters**

- `struct inode *dir`: parent directory
- `struct dentry *dentry`: new file
- `umode_t mode`: new file mode
- `dev_t dev`: device number

**Description**

Check permissions when creating a special file (or a socket or a fifo file
created via the mknod system call).  Note that if mknod operation is being
done for a regular file, then the create hook will be called and not this
hook.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_rename"></a>`security_inode_rename()`

```c
int security_inode_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
```

Check if renaming a file is allowed

**Parameters**

- `struct inode *old_dir`: parent directory of the old file
- `struct dentry *old_dentry`: the old file
- `struct inode *new_dir`: parent directory of the new file
- `struct dentry *new_dentry`: the new file
- `unsigned int flags`: flags

**Description**

Check for permission to rename a file or directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_readlink"></a>`security_inode_readlink()`

```c
int security_inode_readlink(struct dentry *dentry)
```

Check if reading a symbolic link is allowed

**Parameters**

- `struct dentry *dentry`: link

**Description**

Check the permission to read the symbolic link.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_follow_link"></a>`security_inode_follow_link()`

```c
int security_inode_follow_link(struct dentry *dentry, struct inode *inode, bool rcu)
```

Check if following a symbolic link is allowed

**Parameters**

- `struct dentry *dentry`: link dentry
- `struct inode *inode`: link inode
- `bool rcu`: true if in RCU-walk mode

**Description**

Check permission to follow a symbolic link when looking up a pathname.  If
**rcu** is true, **inode** is not stable.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_permission"></a>`security_inode_permission()`

```c
int security_inode_permission(struct inode *inode, int mask)
```

Check if accessing an inode is allowed

**Parameters**

- `struct inode *inode`: inode
- `int mask`: access mask

**Description**

Check permission before accessing an inode.  This hook is called by the
existing Linux permission function, so a security module can use it to
provide additional checking for existing Linux permission checks.  Notice
that this hook is called when a file is opened (as well as many other
operations), whereas the file_security_ops permission hook is called when
the actual read/write operations are performed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_post_setattr"></a>`security_inode_post_setattr()`

```c
void security_inode_post_setattr(struct mnt_idmap *idmap, struct dentry *dentry, int ia_valid)
```

Update the inode after a setattr operation

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `int ia_valid`: file attributes set

**Description**

Update inode security field after successful setting file attributes.

#### <a id="c-security_inode_getattr"></a>`security_inode_getattr()`

```c
int security_inode_getattr(const struct path *path)
```

Check if getting file attributes is allowed

**Parameters**

- `const struct path *path`: file

**Description**

Check permission before obtaining file attributes.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_setxattr"></a>`security_inode_setxattr()`

```c
int security_inode_setxattr(struct mnt_idmap *idmap, struct dentry *dentry, const char *name, const void *value, size_t size, int flags)
```

Check if setting file xattrs is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *name`: xattr name
- `const void *value`: xattr value
- `size_t size`: size of xattr value
- `int flags`: flags

**Description**

This hook performs the desired permission checks before setting the extended
attributes (xattrs) on **dentry**.  It is important to note that we have some
additional logic before the main LSM implementation calls to detect if we
need to perform an additional capability check at the LSM layer.

Normally we enforce a capability check prior to executing the various LSM
hook implementations, but if a LSM wants to avoid this capability check,
it can register a 'inode_xattr_skipcap' hook and return a value of 1 for
xattrs that it wants to avoid the capability check, leaving the LSM fully
responsible for enforcing the access control for the specific xattr.  If all
of the enabled LSMs refrain from registering a 'inode_xattr_skipcap' hook,
or return a 0 (the default return value), the capability check is still
performed.  If no 'inode_xattr_skipcap' hooks are registered the capability
check is performed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_set_acl"></a>`security_inode_set_acl()`

```c
int security_inode_set_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name, struct posix_acl *kacl)
```

Check if setting posix acls is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *acl_name`: acl name
- `struct posix_acl *kacl`: acl struct

**Description**

Check permission before setting posix acls, the posix acls in **kacl** are
identified by **acl_name**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_post_set_acl"></a>`security_inode_post_set_acl()`

```c
void security_inode_post_set_acl(struct dentry *dentry, const char *acl_name, struct posix_acl *kacl)
```

Update inode security from posix acls set

**Parameters**

- `struct dentry *dentry`: file
- `const char *acl_name`: acl name
- `struct posix_acl *kacl`: acl struct

**Description**

Update inode security data after successfully setting posix acls on **dentry**.
The posix acls in **kacl** are identified by **acl_name**.

#### <a id="c-security_inode_get_acl"></a>`security_inode_get_acl()`

```c
int security_inode_get_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name)
```

Check if reading posix acls is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *acl_name`: acl name

**Description**

Check permission before getting osix acls, the posix acls are identified by
**acl_name**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_remove_acl"></a>`security_inode_remove_acl()`

```c
int security_inode_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name)
```

Check if removing a posix acl is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *acl_name`: acl name

**Description**

Check permission before removing posix acls, the posix acls are identified
by **acl_name**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_post_remove_acl"></a>`security_inode_post_remove_acl()`

```c
void security_inode_post_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name)
```

Update inode security after rm posix acls

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *acl_name`: acl name

**Description**

Update inode security data after successfully removing posix acls on
**dentry** in **idmap**. The posix acls are identified by **acl_name**.

#### <a id="c-security_inode_post_setxattr"></a>`security_inode_post_setxattr()`

```c
void security_inode_post_setxattr(struct dentry *dentry, const char *name, const void *value, size_t size, int flags)
```

Update the inode after a setxattr operation

**Parameters**

- `struct dentry *dentry`: file
- `const char *name`: xattr name
- `const void *value`: xattr value
- `size_t size`: xattr value size
- `int flags`: flags

**Description**

Update inode security field after successful setxattr operation.

#### <a id="c-security_inode_getxattr"></a>`security_inode_getxattr()`

```c
int security_inode_getxattr(struct dentry *dentry, const char *name)
```

Check if xattr access is allowed

**Parameters**

- `struct dentry *dentry`: file
- `const char *name`: xattr name

**Description**

Check permission before obtaining the extended attributes identified by
**name** for **dentry**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_listxattr"></a>`security_inode_listxattr()`

```c
int security_inode_listxattr(struct dentry *dentry)
```

Check if listing xattrs is allowed

**Parameters**

- `struct dentry *dentry`: file

**Description**

Check permission before obtaining the list of extended attribute names for
**dentry**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_removexattr"></a>`security_inode_removexattr()`

```c
int security_inode_removexattr(struct mnt_idmap *idmap, struct dentry *dentry, const char *name)
```

Check if removing an xattr is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `const char *name`: xattr name

**Description**

This hook performs the desired permission checks before setting the extended
attributes (xattrs) on **dentry**.  It is important to note that we have some
additional logic before the main LSM implementation calls to detect if we
need to perform an additional capability check at the LSM layer.

Normally we enforce a capability check prior to executing the various LSM
hook implementations, but if a LSM wants to avoid this capability check,
it can register a 'inode_xattr_skipcap' hook and return a value of 1 for
xattrs that it wants to avoid the capability check, leaving the LSM fully
responsible for enforcing the access control for the specific xattr.  If all
of the enabled LSMs refrain from registering a 'inode_xattr_skipcap' hook,
or return a 0 (the default return value), the capability check is still
performed.  If no 'inode_xattr_skipcap' hooks are registered the capability
check is performed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_post_removexattr"></a>`security_inode_post_removexattr()`

```c
void security_inode_post_removexattr(struct dentry *dentry, const char *name)
```

Update the inode after a removexattr op

**Parameters**

- `struct dentry *dentry`: file
- `const char *name`: xattr name

**Description**

Update the inode after a successful removexattr operation.

#### <a id="c-security_inode_file_setattr"></a>`security_inode_file_setattr()`

```c
int security_inode_file_setattr(struct dentry *dentry, struct file_kattr *fa)
```

check if setting fsxattr is allowed

**Parameters**

- `struct dentry *dentry`: file to set filesystem extended attributes on
- `struct file_kattr *fa`: extended attributes to set on the inode

**Description**

Called when `file_setattr()` syscall or FS_IOC_FSSETXATTR `ioctl()` is called on
inode

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_file_getattr"></a>`security_inode_file_getattr()`

```c
int security_inode_file_getattr(struct dentry *dentry, struct file_kattr *fa)
```

check if retrieving fsxattr is allowed

**Parameters**

- `struct dentry *dentry`: file to retrieve filesystem extended attributes from
- `struct file_kattr *fa`: extended attributes to get

**Description**

Called when `file_getattr()` syscall or FS_IOC_FSGETXATTR `ioctl()` is called on
inode

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_need_killpriv"></a>`security_inode_need_killpriv()`

```c
int security_inode_need_killpriv(struct dentry *dentry)
```

Check if [`security_inode_killpriv()`](#c-security_inode_killpriv) required

**Parameters**

- `struct dentry *dentry`: associated dentry

**Description**

Called when an inode has been changed to determine if
[`security_inode_killpriv()`](#c-security_inode_killpriv) should be called.

**Return**

Return \<0 on error to abort the inode change operation, return 0 if
[`security_inode_killpriv()`](#c-security_inode_killpriv) does not need to be called, return >0 if
[`security_inode_killpriv()`](#c-security_inode_killpriv) does need to be called.

#### <a id="c-security_inode_killpriv"></a>`security_inode_killpriv()`

```c
int security_inode_killpriv(struct mnt_idmap *idmap, struct dentry *dentry)
```

The setuid bit is removed, update LSM state

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: associated dentry

**Description**

The **dentry**'s setuid bit is being removed.  Remove similar security labels.
Called with the dentry->d_inode->i_mutex held.

**Return**

Return 0 on success.  If error is returned, then the operation
causing setuid bit removal is failed.

#### <a id="c-security_inode_getsecurity"></a>`security_inode_getsecurity()`

```c
int security_inode_getsecurity(struct mnt_idmap *idmap, struct inode *inode, const char *name, void **buffer, bool alloc)
```

Get the xattr security label of an inode

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct inode *inode`: inode
- `const char *name`: xattr name
- `void **buffer`: security label buffer
- `bool alloc`: allocation flag

**Description**

Retrieve a copy of the extended attribute representation of the security
label associated with **name** for **inode** via **buffer**.  Note that **name** is the
remainder of the attribute name after the security prefix has been removed.
**alloc** is used to specify if the call should return a value via the buffer
or just the value length.

**Return**

Returns size of buffer on success.

#### <a id="c-security_inode_setsecurity"></a>`security_inode_setsecurity()`

```c
int security_inode_setsecurity(struct inode *inode, const char *name, const void *value, size_t size, int flags)
```

Set the xattr security label of an inode

**Parameters**

- `struct inode *inode`: inode
- `const char *name`: xattr name
- `const void *value`: security label
- `size_t size`: length of security label
- `int flags`: flags

**Description**

Set the security label associated with **name** for **inode** from the extended
attribute value **value**.  **size** indicates the size of the **value** in bytes.
**flags** may be XATTR_CREATE, XATTR_REPLACE, or 0. Note that **name** is the
remainder of the attribute name after the security. prefix has been removed.

**Return**

Returns 0 on success.

#### <a id="c-security_inode_getlsmprop"></a>`security_inode_getlsmprop()`

```c
void security_inode_getlsmprop(struct inode *inode, struct lsm_prop *prop)
```

Get an inode's LSM data

**Parameters**

- `struct inode *inode`: inode
- `struct lsm_prop *prop`: lsm specific information to return

**Description**

Get the lsm specific information associated with the node.

#### <a id="c-security_kernfs_init_security"></a>`security_kernfs_init_security()`

```c
int security_kernfs_init_security(struct kernfs_node *kn_dir, struct kernfs_node *kn)
```

Init LSM context for a kernfs node

**Parameters**

- `struct kernfs_node *kn_dir`: parent kernfs node
- `struct kernfs_node *kn`: the kernfs node to initialize

**Description**

Initialize the security context of a newly created kernfs node based on its
own and its parent's attributes.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_permission"></a>`security_file_permission()`

```c
int security_file_permission(struct file *file, int mask)
```

Check file permissions

**Parameters**

- `struct file *file`: file
- `int mask`: requested permissions

**Description**

Check file permissions before accessing an open file.  This hook is called
by various operations that read or write files.  A security module can use
this hook to perform additional checking on these operations, e.g. to
revalidate permissions on use to support privilege bracketing or policy
changes.  Notice that this hook is used when the actual read/write
operations are performed, whereas the inode_security_ops hook is called when
a file is opened (as well as many other operations).  Although this hook can
be used to revalidate permissions for various system call operations that
read or write files, it does not address the revalidation of permissions for
memory-mapped files.  Security modules must handle this separately if they
need such revalidation.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_alloc"></a>`security_file_alloc()`

```c
int security_file_alloc(struct file *file)
```

Allocate and init a file's LSM blob

**Parameters**

- `struct file *file`: the file

**Description**

Allocate and attach a security structure to the file->f_security field.  The
security field is initialized to NULL when the structure is first created.

**Return**

Return 0 if the hook is successful and permission is granted.

#### <a id="c-security_file_release"></a>`security_file_release()`

```c
void security_file_release(struct file *file)
```

Perform actions before releasing the file ref

**Parameters**

- `struct file *file`: the file

**Description**

Perform actions before releasing the last reference to a file.

#### <a id="c-security_file_free"></a>`security_file_free()`

```c
void security_file_free(struct file *file)
```

Free a file's LSM blob

**Parameters**

- `struct file *file`: the file

**Description**

Deallocate and free any security structures stored in file->f_security.

#### <a id="c-security_backing_file_alloc"></a>`security_backing_file_alloc()`

```c
int security_backing_file_alloc(struct file *backing_file, const struct file *user_file)
```

Allocate and setup a backing file blob

**Parameters**

- `struct file *backing_file`: the backing file
- `const struct file *user_file`: the associated user visible file

**Description**

Allocate a backing file LSM blob and perform any necessary initialization of
the LSM blob.  There will be some operations where the LSM will not have
access to **user_file** after this point, so any important state associated
with **user_file** that is important to the LSM should be captured in the
backing file's LSM blob.

LSM's should avoid taking a reference to **user_file** in this hook as it will
result in problems later when the system attempts to drop/put the file
references due to a circular dependency.

**Return**

Return 0 if the hook is successful, negative values otherwise.

#### <a id="c-security_backing_file_free"></a>`security_backing_file_free()`

```c
void security_backing_file_free(struct file *backing_file)
```

Free a backing file blob

**Parameters**

- `struct file *backing_file`: the backing file

**Description**

Free any LSM state associate with a backing file's LSM blob, including the
blob itself.

#### <a id="c-security_mmap_file"></a>`security_mmap_file()`

```c
int security_mmap_file(struct file *file, unsigned long prot, unsigned long flags)
```

Check if mmap'ing a file is allowed

**Parameters**

- `struct file *file`: file
- `unsigned long prot`: protection applied by the kernel
- `unsigned long flags`: flags

**Description**

Check permissions for a mmap operation.  The **file** may be NULL, e.g. if
mapping anonymous memory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_mmap_addr"></a>`security_mmap_addr()`

```c
int security_mmap_addr(unsigned long addr)
```

Check if mmap'ing an address is allowed

**Parameters**

- `unsigned long addr`: address

**Description**

Check permissions for a mmap operation at **addr**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_mprotect"></a>`security_file_mprotect()`

```c
int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot, unsigned long prot)
```

Check if changing memory protections is allowed

**Parameters**

- `struct vm_area_struct *vma`: memory region
- `unsigned long reqprot`: application requested protection
- `unsigned long prot`: protection applied by the kernel

**Description**

Check permissions before changing memory access permissions.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_lock"></a>`security_file_lock()`

```c
int security_file_lock(struct file *file, unsigned int cmd)
```

Check if a file lock is allowed

**Parameters**

- `struct file *file`: file
- `unsigned int cmd`: lock operation (e.g. F_RDLCK, F_WRLCK)

**Description**

Check permission before performing file locking operations.  Note the hook
mediates both flock and fcntl style locks.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_fcntl"></a>`security_file_fcntl()`

```c
int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg)
```

Check if `fcntl()` op is allowed

**Parameters**

- `struct file *file`: file
- `unsigned int cmd`: fcntl command
- `unsigned long arg`: command argument

**Description**

Check permission before allowing the file operation specified by **cmd** from
being performed on the file **file**.  Note that **arg** sometimes represents a
user space pointer; in other cases, it may be a simple integer value.  When
**arg** represents a user space pointer, it should never be used by the
security module.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_set_fowner"></a>`security_file_set_fowner()`

```c
void security_file_set_fowner(struct file *file)
```

Set the file owner info in the LSM blob

**Parameters**

- `struct file *file`: the file

**Description**

Save owner security information (typically from current->security) in
file->f_security for later use by the send_sigiotask hook.

This hook is called with file->f_owner.lock held.

**Return**

Returns 0 on success.

#### <a id="c-security_file_send_sigiotask"></a>`security_file_send_sigiotask()`

```c
int security_file_send_sigiotask(struct task_struct *tsk, struct fown_struct *fown, int sig)
```

Check if sending SIGIO/SIGURG is allowed

**Parameters**

- `struct task_struct *tsk`: target task
- `struct fown_struct *fown`: signal sender
- `int sig`: signal to be sent, SIGIO is sent if 0

**Description**

Check permission for the file owner **fown** to send SIGIO or SIGURG to the
process **tsk**.  Note that this hook is sometimes called from interrupt.  Note
that the fown_struct, **fown**, is never outside the context of a struct file,
so the file structure (and associated security information) can always be
obtained: container_of(fown, struct file, f_owner).

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_receive"></a>`security_file_receive()`

```c
int security_file_receive(struct file *file)
```

Check if receiving a file via IPC is allowed

**Parameters**

- `struct file *file`: file being received

**Description**

This hook allows security modules to control the ability of a process to
receive an open file descriptor via socket IPC.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_open"></a>`security_file_open()`

```c
int security_file_open(struct file *file)
```

Save `open()` time state for late use by the LSM

**Parameters**

- `struct file *file`: 

**Description**

Save open-time permission checking state for later use upon file_permission,
and recheck access if anything has changed since inode_permission.

We can check if a file is opened for execution (e.g. execve(2) call), either
directly or indirectly (e.g. ELF's ld.so) by checking file->f_flags &
__FMODE_EXEC .

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_truncate"></a>`security_file_truncate()`

```c
int security_file_truncate(struct file *file)
```

Check if truncating a file is allowed

**Parameters**

- `struct file *file`: file

**Description**

Check permission before truncating a file, i.e. using ftruncate.  Note that
truncation permission may also be checked based on the path, using the
**path_truncate** hook.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_alloc"></a>`security_task_alloc()`

```c
int security_task_alloc(struct task_struct *task, u64 clone_flags)
```

Allocate a task's LSM blob

**Parameters**

- `struct task_struct *task`: the task
- `u64 clone_flags`: flags indicating what is being shared

**Description**

Handle allocation of task-related resources.

**Return**

Returns a zero on success, negative values on failure.

#### <a id="c-security_task_free"></a>`security_task_free()`

```c
void security_task_free(struct task_struct *task)
```

Free a task's LSM blob and related resources

**Parameters**

- `struct task_struct *task`: task

**Description**

Handle release of task-related resources.  Note that this can be called from
interrupt context.

#### <a id="c-security_cred_alloc_blank"></a>`security_cred_alloc_blank()`

```c
int security_cred_alloc_blank(struct cred *cred, gfp_t gfp)
```

Allocate the min memory to allow cred_transfer

**Parameters**

- `struct cred *cred`: credentials
- `gfp_t gfp`: gfp flags

**Description**

Only allocate sufficient memory and attach to **cred** such that
`cred_transfer()` will not get ENOMEM.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_cred_free"></a>`security_cred_free()`

```c
void security_cred_free(struct cred *cred)
```

Free the cred's LSM blob and associated resources

**Parameters**

- `struct cred *cred`: credentials

**Description**

Deallocate and clear the cred->security field in a set of credentials.

#### <a id="c-security_prepare_creds"></a>`security_prepare_creds()`

```c
int security_prepare_creds(struct cred *new, const struct cred *old, gfp_t gfp)
```

Prepare a new set of credentials

**Parameters**

- `struct cred *new`: new credentials
- `const struct cred *old`: original credentials
- `gfp_t gfp`: gfp flags

**Description**

Prepare a new set of credentials by copying the data from the old set.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_transfer_creds"></a>`security_transfer_creds()`

```c
void security_transfer_creds(struct cred *new, const struct cred *old)
```

Transfer creds

**Parameters**

- `struct cred *new`: target credentials
- `const struct cred *old`: original credentials

**Description**

Transfer data from original creds to new creds.

#### <a id="c-security_kernel_act_as"></a>`security_kernel_act_as()`

```c
int security_kernel_act_as(struct cred *new, u32 secid)
```

Set the kernel credentials to act as secid

**Parameters**

- `struct cred *new`: credentials
- `u32 secid`: secid

**Description**

Set the credentials for a kernel service to act as (subjective context).
The current task must be the one that nominated **secid**.

**Return**

Returns 0 if successful.

#### <a id="c-security_kernel_create_files_as"></a>`security_kernel_create_files_as()`

```c
int security_kernel_create_files_as(struct cred *new, struct inode *inode)
```

Set file creation context using an inode

**Parameters**

- `struct cred *new`: target credentials
- `struct inode *inode`: reference inode

**Description**

Set the file creation context in a set of credentials to be the same as the
objective context of the specified inode.  The current task must be the one
that nominated **inode**.

**Return**

Returns 0 if successful.

#### <a id="c-security_kernel_module_request"></a>`security_kernel_module_request()`

```c
int security_kernel_module_request(char *kmod_name)
```

Check if loading a module is allowed

**Parameters**

- `char *kmod_name`: module name

**Description**

Ability to trigger the kernel to automatically upcall to userspace for
userspace to load a kernel module with the given name.

**Return**

Returns 0 if successful.

#### <a id="c-security_task_fix_setuid"></a>`security_task_fix_setuid()`

```c
int security_task_fix_setuid(struct cred *new, const struct cred *old, int flags)
```

Update LSM with new user id attributes

**Parameters**

- `struct cred *new`: updated credentials
- `const struct cred *old`: credentials being replaced
- `int flags`: LSM_SETID_* flag values

**Description**

Update the module's state after setting one or more of the user identity
attributes of the current process.  The **flags** parameter indicates which of
the set*uid system calls invoked this hook.  If **new** is the set of
credentials that will be installed.  Modifications should be made to this
rather than to **current->cred**.

**Return**

Returns 0 on success.

#### <a id="c-security_task_fix_setgid"></a>`security_task_fix_setgid()`

```c
int security_task_fix_setgid(struct cred *new, const struct cred *old, int flags)
```

Update LSM with new group id attributes

**Parameters**

- `struct cred *new`: updated credentials
- `const struct cred *old`: credentials being replaced
- `int flags`: LSM_SETID_* flag value

**Description**

Update the module's state after setting one or more of the group identity
attributes of the current process.  The **flags** parameter indicates which of
the set*gid system calls invoked this hook.  **new** is the set of credentials
that will be installed.  Modifications should be made to this rather than to
**current->cred**.

**Return**

Returns 0 on success.

#### <a id="c-security_task_fix_setgroups"></a>`security_task_fix_setgroups()`

```c
int security_task_fix_setgroups(struct cred *new, const struct cred *old)
```

Update LSM with new supplementary groups

**Parameters**

- `struct cred *new`: updated credentials
- `const struct cred *old`: credentials being replaced

**Description**

Update the module's state after setting the supplementary group identity
attributes of the current process.  **new** is the set of credentials that will
be installed.  Modifications should be made to this rather than to
**current->cred**.

**Return**

Returns 0 on success.

#### <a id="c-security_task_setpgid"></a>`security_task_setpgid()`

```c
int security_task_setpgid(struct task_struct *p, pid_t pgid)
```

Check if setting the pgid is allowed

**Parameters**

- `struct task_struct *p`: task being modified
- `pid_t pgid`: new pgid

**Description**

Check permission before setting the process group identifier of the process
**p** to **pgid**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_getpgid"></a>`security_task_getpgid()`

```c
int security_task_getpgid(struct task_struct *p)
```

Check if getting the pgid is allowed

**Parameters**

- `struct task_struct *p`: task

**Description**

Check permission before getting the process group identifier of the process
**p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_getsid"></a>`security_task_getsid()`

```c
int security_task_getsid(struct task_struct *p)
```

Check if getting the session id is allowed

**Parameters**

- `struct task_struct *p`: task

**Description**

Check permission before getting the session identifier of the process **p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_setnice"></a>`security_task_setnice()`

```c
int security_task_setnice(struct task_struct *p, int nice)
```

Check if setting a task's nice value is allowed

**Parameters**

- `struct task_struct *p`: target task
- `int nice`: nice value

**Description**

Check permission before setting the nice value of **p** to **nice**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_setioprio"></a>`security_task_setioprio()`

```c
int security_task_setioprio(struct task_struct *p, int ioprio)
```

Check if setting a task's ioprio is allowed

**Parameters**

- `struct task_struct *p`: target task
- `int ioprio`: ioprio value

**Description**

Check permission before setting the ioprio value of **p** to **ioprio**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_getioprio"></a>`security_task_getioprio()`

```c
int security_task_getioprio(struct task_struct *p)
```

Check if getting a task's ioprio is allowed

**Parameters**

- `struct task_struct *p`: task

**Description**

Check permission before getting the ioprio value of **p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_prlimit"></a>`security_task_prlimit()`

```c
int security_task_prlimit(const struct cred *cred, const struct cred *tcred, unsigned int flags)
```

Check if get/setting resources limits is allowed

**Parameters**

- `const struct cred *cred`: current task credentials
- `const struct cred *tcred`: target task credentials
- `unsigned int flags`: LSM_PRLIMIT_* flag bits indicating a get/set/both

**Description**

Check permission before getting and/or setting the resource limits of
another task.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_setrlimit"></a>`security_task_setrlimit()`

```c
int security_task_setrlimit(struct task_struct *p, unsigned int resource, struct rlimit *new_rlim)
```

Check if setting a new rlimit value is allowed

**Parameters**

- `struct task_struct *p`: target task's group leader
- `unsigned int resource`: resource whose limit is being set
- `struct rlimit *new_rlim`: new resource limit

**Description**

Check permission before setting the resource limits of process **p** for
**resource** to **new_rlim**.  The old resource limit values can be examined by
dereferencing (p->signal->rlim + resource).

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_setscheduler"></a>`security_task_setscheduler()`

```c
int security_task_setscheduler(struct task_struct *p)
```

Check if setting sched policy/param is allowed

**Parameters**

- `struct task_struct *p`: target task

**Description**

Check permission before setting scheduling policy and/or parameters of
process **p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_getscheduler"></a>`security_task_getscheduler()`

```c
int security_task_getscheduler(struct task_struct *p)
```

Check if getting scheduling info is allowed

**Parameters**

- `struct task_struct *p`: target task

**Description**

Check permission before obtaining scheduling information for process **p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_movememory"></a>`security_task_movememory()`

```c
int security_task_movememory(struct task_struct *p)
```

Check if moving memory is allowed

**Parameters**

- `struct task_struct *p`: task

**Description**

Check permission before moving memory owned by process **p**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_kill"></a>`security_task_kill()`

```c
int security_task_kill(struct task_struct *p, struct kernel_siginfo *info, int sig, const struct cred *cred)
```

Check if sending a signal is allowed

**Parameters**

- `struct task_struct *p`: target process
- `struct kernel_siginfo *info`: signal information
- `int sig`: signal value
- `const struct cred *cred`: credentials of the signal sender, NULL if **current**

**Description**

Check permission before sending signal **sig** to **p**.  **info** can be NULL, the
constant 1, or a pointer to a kernel_siginfo structure.  If **info** is 1 or
SI_FROMKERNEL(info) is true, then the signal should be viewed as coming from
the kernel and should typically be permitted.  SIGIO signals are handled
separately by the send_sigiotask hook in file_security_ops.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_task_prctl"></a>`security_task_prctl()`

```c
int security_task_prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5)
```

Check if a prctl op is allowed

**Parameters**

- `int option`: operation
- `unsigned long arg2`: argument
- `unsigned long arg3`: argument
- `unsigned long arg4`: argument
- `unsigned long arg5`: argument

**Description**

Check permission before performing a process control operation on the
current process.

**Return**

Return -ENOSYS if no-one wanted to handle this op, any other value
to cause `prctl()` to return immediately with that value.

#### <a id="c-security_task_to_inode"></a>`security_task_to_inode()`

```c
void security_task_to_inode(struct task_struct *p, struct inode *inode)
```

Set the security attributes of a task's inode

**Parameters**

- `struct task_struct *p`: task
- `struct inode *inode`: inode

**Description**

Set the security attributes for an inode based on an associated task's
security attributes, e.g. for /proc/pid inodes.

#### <a id="c-security_create_user_ns"></a>`security_create_user_ns()`

```c
int security_create_user_ns(const struct cred *cred)
```

Check if creating a new userns is allowed

**Parameters**

- `const struct cred *cred`: prepared creds

**Description**

Check permission prior to creating a new user namespace.

**Return**

Returns 0 if successful, otherwise \< 0 error code.

#### <a id="c-security_ipc_permission"></a>`security_ipc_permission()`

```c
int security_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
```

Check if sysv ipc access is allowed

**Parameters**

- `struct kern_ipc_perm *ipcp`: ipc permission structure
- `short flag`: requested permissions

**Description**

Check permissions for access to IPC.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ipc_getlsmprop"></a>`security_ipc_getlsmprop()`

```c
void security_ipc_getlsmprop(struct kern_ipc_perm *ipcp, struct lsm_prop *prop)
```

Get the sysv ipc object LSM data

**Parameters**

- `struct kern_ipc_perm *ipcp`: ipc permission structure
- `struct lsm_prop *prop`: pointer to lsm information

**Description**

Get the lsm information associated with the ipc object.

#### <a id="c-security_msg_msg_alloc"></a>`security_msg_msg_alloc()`

```c
int security_msg_msg_alloc(struct msg_msg *msg)
```

Allocate a sysv ipc message LSM blob

**Parameters**

- `struct msg_msg *msg`: message structure

**Description**

Allocate and attach a security structure to the msg->security field.  The
security field is initialized to NULL when the structure is first created.

**Return**

Return 0 if operation was successful and permission is granted.

#### <a id="c-security_msg_msg_free"></a>`security_msg_msg_free()`

```c
void security_msg_msg_free(struct msg_msg *msg)
```

Free a sysv ipc message LSM blob

**Parameters**

- `struct msg_msg *msg`: message structure

**Description**

Deallocate the security structure for this message.

#### <a id="c-security_msg_queue_alloc"></a>`security_msg_queue_alloc()`

```c
int security_msg_queue_alloc(struct kern_ipc_perm *msq)
```

Allocate a sysv ipc msg queue LSM blob

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure

**Description**

Allocate and attach a security structure to **msg**. The security field is
initialized to NULL when the structure is first created.

**Return**

Returns 0 if operation was successful and permission is granted.

#### <a id="c-security_msg_queue_free"></a>`security_msg_queue_free()`

```c
void security_msg_queue_free(struct kern_ipc_perm *msq)
```

Free a sysv ipc msg queue LSM blob

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure

**Description**

Deallocate security field **perm->security** for the message queue.

#### <a id="c-security_msg_queue_associate"></a>`security_msg_queue_associate()`

```c
int security_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
```

Check if a msg queue operation is allowed

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure
- `int msqflg`: operation flags

**Description**

Check permission when a message queue is requested through the msgget system
call. This hook is only called when returning the message queue identifier
for an existing message queue, not when a new message queue is created.

**Return**

Return 0 if permission is granted.

#### <a id="c-security_msg_queue_msgctl"></a>`security_msg_queue_msgctl()`

```c
int security_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
```

Check if a msg queue operation is allowed

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure
- `int cmd`: operation

**Description**

Check permission when a message control operation specified by **cmd** is to be
performed on the message queue with permissions.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_msg_queue_msgsnd"></a>`security_msg_queue_msgsnd()`

```c
int security_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
```

Check if sending a sysv ipc message is allowed

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure
- `struct msg_msg *msg`: message
- `int msqflg`: operation flags

**Description**

Check permission before a message, **msg**, is enqueued on the message queue
with permissions specified in **msq**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_msg_queue_msgrcv"></a>`security_msg_queue_msgrcv()`

```c
int security_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg, struct task_struct *target, long type, int mode)
```

Check if receiving a sysv ipc msg is allowed

**Parameters**

- `struct kern_ipc_perm *msq`: sysv ipc permission structure
- `struct msg_msg *msg`: message
- `struct task_struct *target`: target task
- `long type`: type of message requested
- `int mode`: operation flags

**Description**

Check permission before a message, **msg**, is removed from the message queue.
The **target** task structure contains a pointer to the process that will be
receiving the message (not equal to the current process when inline receives
are being performed).

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_shm_alloc"></a>`security_shm_alloc()`

```c
int security_shm_alloc(struct kern_ipc_perm *shp)
```

Allocate a sysv shm LSM blob

**Parameters**

- `struct kern_ipc_perm *shp`: sysv ipc permission structure

**Description**

Allocate and attach a security structure to the **shp** security field.  The
security field is initialized to NULL when the structure is first created.

**Return**

Returns 0 if operation was successful and permission is granted.

#### <a id="c-security_shm_free"></a>`security_shm_free()`

```c
void security_shm_free(struct kern_ipc_perm *shp)
```

Free a sysv shm LSM blob

**Parameters**

- `struct kern_ipc_perm *shp`: sysv ipc permission structure

**Description**

Deallocate the security structure **perm->security** for the memory segment.

#### <a id="c-security_shm_associate"></a>`security_shm_associate()`

```c
int security_shm_associate(struct kern_ipc_perm *shp, int shmflg)
```

Check if a sysv shm operation is allowed

**Parameters**

- `struct kern_ipc_perm *shp`: sysv ipc permission structure
- `int shmflg`: operation flags

**Description**

Check permission when a shared memory region is requested through the shmget
system call. This hook is only called when returning the shared memory
region identifier for an existing region, not when a new shared memory
region is created.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_shm_shmctl"></a>`security_shm_shmctl()`

```c
int security_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
```

Check if a sysv shm operation is allowed

**Parameters**

- `struct kern_ipc_perm *shp`: sysv ipc permission structure
- `int cmd`: operation

**Description**

Check permission when a shared memory control operation specified by **cmd** is
to be performed on the shared memory region with permissions in **shp**.

**Return**

Return 0 if permission is granted.

#### <a id="c-security_shm_shmat"></a>`security_shm_shmat()`

```c
int security_shm_shmat(struct kern_ipc_perm *shp, char __user *shmaddr, int shmflg)
```

Check if a sysv shm attach operation is allowed

**Parameters**

- `struct kern_ipc_perm *shp`: sysv ipc permission structure
- `char __user *shmaddr`: address of memory region to attach
- `int shmflg`: operation flags

**Description**

Check permissions prior to allowing the shmat system call to attach the
shared memory segment with permissions **shp** to the data segment of the
calling process. The attaching address is specified by **shmaddr**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sem_alloc"></a>`security_sem_alloc()`

```c
int security_sem_alloc(struct kern_ipc_perm *sma)
```

Allocate a sysv semaphore LSM blob

**Parameters**

- `struct kern_ipc_perm *sma`: sysv ipc permission structure

**Description**

Allocate and attach a security structure to the **sma** security field. The
security field is initialized to NULL when the structure is first created.

**Return**

Returns 0 if operation was successful and permission is granted.

#### <a id="c-security_sem_free"></a>`security_sem_free()`

```c
void security_sem_free(struct kern_ipc_perm *sma)
```

Free a sysv semaphore LSM blob

**Parameters**

- `struct kern_ipc_perm *sma`: sysv ipc permission structure

**Description**

Deallocate security structure **sma->security** for the semaphore.

#### <a id="c-security_sem_associate"></a>`security_sem_associate()`

```c
int security_sem_associate(struct kern_ipc_perm *sma, int semflg)
```

Check if a sysv semaphore operation is allowed

**Parameters**

- `struct kern_ipc_perm *sma`: sysv ipc permission structure
- `int semflg`: operation flags

**Description**

Check permission when a semaphore is requested through the semget system
call. This hook is only called when returning the semaphore identifier for
an existing semaphore, not when a new one must be created.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sem_semctl"></a>`security_sem_semctl()`

```c
int security_sem_semctl(struct kern_ipc_perm *sma, int cmd)
```

Check if a sysv semaphore operation is allowed

**Parameters**

- `struct kern_ipc_perm *sma`: sysv ipc permission structure
- `int cmd`: operation

**Description**

Check permission when a semaphore operation specified by **cmd** is to be
performed on the semaphore.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sem_semop"></a>`security_sem_semop()`

```c
int security_sem_semop(struct kern_ipc_perm *sma, struct sembuf *sops, unsigned nsops, int alter)
```

Check if a sysv semaphore operation is allowed

**Parameters**

- `struct kern_ipc_perm *sma`: sysv ipc permission structure
- `struct sembuf *sops`: operations to perform
- `unsigned nsops`: number of operations
- `int alter`: flag indicating changes will be made

**Description**

Check permissions before performing operations on members of the semaphore
set. If the **alter** flag is nonzero, the semaphore set may be modified.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_getselfattr"></a>`security_getselfattr()`

```c
int security_getselfattr(unsigned int attr, struct lsm_ctx __user *uctx, u32 __user *size, u32 flags)
```

Read an LSM attribute of the current process.

**Parameters**

- `unsigned int attr`: which attribute to return
- `struct lsm_ctx __user *uctx`: the user-space destination for the information, or NULL
- `u32 __user *size`: pointer to the size of space available to receive the data
- `u32 flags`: special handling options. LSM_FLAG_SINGLE indicates that only
  attributes associated with the LSM identified in the passed **ctx** be
  reported.

**Description**

A NULL value for **uctx** can be used to get both the number of attributes
and the size of the data.

Returns the number of attributes found on success, negative value
on error. **size** is reset to the total size of the data.
If **size** is insufficient to contain the data -E2BIG is returned.

#### <a id="c-security_setselfattr"></a>`security_setselfattr()`

```c
int security_setselfattr(unsigned int attr, struct lsm_ctx __user *uctx, u32 size, u32 flags)
```

Set an LSM attribute on the current process.

**Parameters**

- `unsigned int attr`: which attribute to set
- `struct lsm_ctx __user *uctx`: the user-space source for the information
- `u32 size`: the size of the data
- `u32 flags`: reserved for future use, must be 0

**Description**

Set an LSM attribute for the current process. The LSM, attribute
and new value are included in **uctx**.

Returns 0 on success, -EINVAL if the input is inconsistent, -EFAULT
if the user buffer is inaccessible, E2BIG if size is too big, or an
LSM specific failure.

#### <a id="c-security_getprocattr"></a>`security_getprocattr()`

```c
int security_getprocattr(struct task_struct *p, int lsmid, const char *name, char **value)
```

Read an attribute for a task

**Parameters**

- `struct task_struct *p`: the task
- `int lsmid`: LSM identification
- `const char *name`: attribute name
- `char **value`: attribute value

**Description**

Read attribute **name** for task **p** and store it into **value** if allowed.

**Return**

Returns the length of **value** on success, a negative value otherwise.

#### <a id="c-security_setprocattr"></a>`security_setprocattr()`

```c
int security_setprocattr(int lsmid, const char *name, void *value, size_t size)
```

Set an attribute for a task

**Parameters**

- `int lsmid`: LSM identification
- `const char *name`: attribute name
- `void *value`: attribute value
- `size_t size`: attribute value size

**Description**

Write (set) the current task's attribute **name** to **value**, size **size** if
allowed.

**Return**

Returns bytes written on success, a negative value otherwise.

#### <a id="c-security_post_notification"></a>`security_post_notification()`

```c
int security_post_notification(const struct cred *w_cred, const struct cred *cred, struct watch_notification *n)
```

Check if a watch notification can be posted

**Parameters**

- `const struct cred *w_cred`: credentials of the task that set the watch
- `const struct cred *cred`: credentials of the task which triggered the watch
- `struct watch_notification *n`: the notification

**Description**

Check to see if a watch notification can be posted to a particular queue.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_watch_key"></a>`security_watch_key()`

```c
int security_watch_key(struct key *key)
```

Check if a task is allowed to watch for key events

**Parameters**

- `struct key *key`: the key to watch

**Description**

Check to see if a process is allowed to watch for event notifications from
a key or keyring.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_netlink_send"></a>`security_netlink_send()`

```c
int security_netlink_send(struct sock *sk, struct sk_buff *skb)
```

Save info and check if netlink sending is allowed

**Parameters**

- `struct sock *sk`: sending socket
- `struct sk_buff *skb`: netlink message

**Description**

Save security information for a netlink message so that permission checking
can be performed when the message is processed.  The security information
can be saved using the eff_cap field of the netlink_skb_parms structure.
Also may be used to provide fine grained control over message transmission.

**Return**

Returns 0 if the information was successfully saved and message is
allowed to be transmitted.

#### <a id="c-security_socket_create"></a>`security_socket_create()`

```c
int security_socket_create(int family, int type, int protocol, int kern)
```

Check if creating a new socket is allowed

**Parameters**

- `int family`: protocol family
- `int type`: communications type
- `int protocol`: requested protocol
- `int kern`: set to 1 if a kernel socket is requested

**Description**

Check permissions prior to creating a new socket.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_post_create"></a>`security_socket_post_create()`

```c
int security_socket_post_create(struct socket *sock, int family, int type, int protocol, int kern)
```

Initialize a newly created socket

**Parameters**

- `struct socket *sock`: socket
- `int family`: protocol family
- `int type`: communications type
- `int protocol`: requested protocol
- `int kern`: set to 1 if a kernel socket is requested

**Description**

This hook allows a module to update or allocate a per-socket security
structure. Note that the security field was not added directly to the socket
structure, but rather, the socket security information is stored in the
associated inode.  Typically, the inode alloc_security hook will allocate
and attach security information to SOCK_INODE(sock)->i_security.  This hook
may be used to update the SOCK_INODE(sock)->i_security field with additional
information that wasn't available when the inode was allocated.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_bind"></a>`security_socket_bind()`

```c
int security_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
```

Check if a socket bind operation is allowed

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr *address`: requested bind address
- `int addrlen`: length of address

**Description**

Check permission before socket protocol layer bind operation is performed
and the socket **sock** is bound to the address specified in the **address**
parameter.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_connect"></a>`security_socket_connect()`

```c
int security_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
```

Check if a socket connect operation is allowed

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr *address`: address of remote connection point
- `int addrlen`: length of address

**Description**

Check permission before socket protocol layer connect operation attempts to
connect socket **sock** to a remote address, **address**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_listen"></a>`security_socket_listen()`

```c
int security_socket_listen(struct socket *sock, int backlog)
```

Check if a socket is allowed to listen

**Parameters**

- `struct socket *sock`: socket
- `int backlog`: connection queue size

**Description**

Check permission before socket protocol layer listen operation.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_accept"></a>`security_socket_accept()`

```c
int security_socket_accept(struct socket *sock, struct socket *newsock)
```

Check if a socket is allowed to accept connections

**Parameters**

- `struct socket *sock`: listening socket
- `struct socket *newsock`: newly creation connection socket

**Description**

Check permission before accepting a new connection.  Note that the new
socket, **newsock**, has been created and some information copied to it, but
the accept operation has not actually been performed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_sendmsg"></a>`security_socket_sendmsg()`

```c
int security_socket_sendmsg(struct socket *sock, struct msghdr *msg, int size)
```

Check if sending a message is allowed

**Parameters**

- `struct socket *sock`: sending socket
- `struct msghdr *msg`: message to send
- `int size`: size of message

**Description**

Check permission before transmitting a message to another socket.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_recvmsg"></a>`security_socket_recvmsg()`

```c
int security_socket_recvmsg(struct socket *sock, struct msghdr *msg, int size, int flags)
```

Check if receiving a message is allowed

**Parameters**

- `struct socket *sock`: receiving socket
- `struct msghdr *msg`: message to receive
- `int size`: size of message
- `int flags`: operational flags

**Description**

Check permission before receiving a message from a socket.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_getsockname"></a>`security_socket_getsockname()`

```c
int security_socket_getsockname(struct socket *sock)
```

Check if reading the socket addr is allowed

**Parameters**

- `struct socket *sock`: socket

**Description**

Check permission before reading the local address (name) of the socket
object.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_getpeername"></a>`security_socket_getpeername()`

```c
int security_socket_getpeername(struct socket *sock)
```

Check if reading the peer's addr is allowed

**Parameters**

- `struct socket *sock`: socket

**Description**

Check permission before the remote address (name) of a socket object.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_getsockopt"></a>`security_socket_getsockopt()`

```c
int security_socket_getsockopt(struct socket *sock, int level, int optname)
```

Check if reading a socket option is allowed

**Parameters**

- `struct socket *sock`: socket
- `int level`: option's protocol level
- `int optname`: option name

**Description**

Check permissions before retrieving the options associated with socket
**sock**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_setsockopt"></a>`security_socket_setsockopt()`

```c
int security_socket_setsockopt(struct socket *sock, int level, int optname)
```

Check if setting a socket option is allowed

**Parameters**

- `struct socket *sock`: socket
- `int level`: option's protocol level
- `int optname`: option name

**Description**

Check permissions before setting the options associated with socket **sock**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_shutdown"></a>`security_socket_shutdown()`

```c
int security_socket_shutdown(struct socket *sock, int how)
```

Checks if shutting down the socket is allowed

**Parameters**

- `struct socket *sock`: socket
- `int how`: flag indicating how sends and receives are handled

**Description**

Checks permission before all or part of a connection on the socket **sock** is
shut down.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_getpeersec_stream"></a>`security_socket_getpeersec_stream()`

```c
int security_socket_getpeersec_stream(struct socket *sock, sockptr_t optval, sockptr_t optlen, unsigned int len)
```

Get the remote peer label

**Parameters**

- `struct socket *sock`: socket
- `sockptr_t optval`: destination buffer
- `sockptr_t optlen`: size of peer label copied into the buffer
- `unsigned int len`: maximum size of the destination buffer

**Description**

This hook allows the security module to provide peer socket security state
for unix or connected tcp sockets to userspace via getsockopt SO_GETPEERSEC.
For tcp sockets this can be meaningful if the socket is associated with an
ipsec SA.

**Return**

Returns 0 if all is well, otherwise, typical getsockopt return
values.

#### <a id="c-lsm_sock_alloc"></a>`lsm_sock_alloc()`

```c
int lsm_sock_alloc(struct sock *sock, gfp_t gfp)
```

allocate a composite sock blob

**Parameters**

- `struct sock *sock`: the sock that needs a blob
- `gfp_t gfp`: allocation mode

**Description**

Allocate the sock blob for all the modules

Returns 0, or -ENOMEM if memory can't be allocated.

#### <a id="c-security_sk_alloc"></a>`security_sk_alloc()`

```c
int security_sk_alloc(struct sock *sk, int family, gfp_t priority)
```

Allocate and initialize a sock's LSM blob

**Parameters**

- `struct sock *sk`: sock
- `int family`: protocol family
- `gfp_t priority`: gfp flags

**Description**

Allocate and attach a security structure to the sk->sk_security field, which
is used to copy security attributes between local stream sockets.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_sk_free"></a>`security_sk_free()`

```c
void security_sk_free(struct sock *sk)
```

Free the sock's LSM blob

**Parameters**

- `struct sock *sk`: sock

**Description**

Deallocate security structure.

#### <a id="c-security_inet_csk_clone"></a>`security_inet_csk_clone()`

```c
void security_inet_csk_clone(struct sock *newsk, const struct request_sock *req)
```

Set new sock LSM state based on request_sock

**Parameters**

- `struct sock *newsk`: new sock
- `const struct request_sock *req`: connection request_sock

**Description**

Set that LSM state of **sock** using the LSM state from **req**.

#### <a id="c-security_mptcp_add_subflow"></a>`security_mptcp_add_subflow()`

```c
int security_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
```

Inherit the LSM label from the MPTCP socket

**Parameters**

- `struct sock *sk`: the owning MPTCP socket
- `struct sock *ssk`: the new subflow

**Description**

Update the labeling for the given MPTCP subflow, to match the one of the
owning MPTCP socket. This hook has to be called after the socket creation and
initialization via the [`security_socket_create()`](#c-security_socket_create) and
[`security_socket_post_create()`](#c-security_socket_post_create) LSM hooks.

**Return**

Returns 0 on success or a negative error code on failure.

#### <a id="c-security_xfrm_policy_clone"></a>`security_xfrm_policy_clone()`

```c
int security_xfrm_policy_clone(struct xfrm_sec_ctx *old_ctx, struct xfrm_sec_ctx **new_ctxp)
```

Clone xfrm policy LSM state

**Parameters**

- `struct xfrm_sec_ctx *old_ctx`: xfrm security context
- `struct xfrm_sec_ctx **new_ctxp`: target xfrm security context

**Description**

Allocate a security structure in new_ctxp that contains the information from
the old_ctx structure.

**Return**

Return 0 if operation was successful.

#### <a id="c-security_xfrm_policy_delete"></a>`security_xfrm_policy_delete()`

```c
int security_xfrm_policy_delete(struct xfrm_sec_ctx *ctx)
```

Check if deleting a xfrm policy is allowed

**Parameters**

- `struct xfrm_sec_ctx *ctx`: xfrm security context

**Description**

Authorize deletion of a SPD entry.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_xfrm_state_alloc_acquire"></a>`security_xfrm_state_alloc_acquire()`

```c
int security_xfrm_state_alloc_acquire(struct xfrm_state *x, struct xfrm_sec_ctx *polsec, u32 secid)
```

Allocate a xfrm state LSM blob

**Parameters**

- `struct xfrm_state *x`: xfrm state being added to the SAD
- `struct xfrm_sec_ctx *polsec`: associated policy's security context
- `u32 secid`: secid from the flow

**Description**

Allocate a security structure to the x->security field; the security field
is initialized to NULL when the xfrm_state is allocated.  Set the context to
correspond to secid.

**Return**

Returns 0 if operation was successful.

#### <a id="c-security_xfrm_state_free"></a>`security_xfrm_state_free()`

```c
void security_xfrm_state_free(struct xfrm_state *x)
```

Free a xfrm state

**Parameters**

- `struct xfrm_state *x`: xfrm state

**Description**

Deallocate x->security.

#### <a id="c-security_xfrm_policy_lookup"></a>`security_xfrm_policy_lookup()`

```c
int security_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid)
```

Check if using a xfrm policy is allowed

**Parameters**

- `struct xfrm_sec_ctx *ctx`: target xfrm security context
- `u32 fl_secid`: flow secid used to authorize access

**Description**

Check permission when a flow selects a xfrm_policy for processing XFRMs on a
packet.  The hook is called when selecting either a per-socket policy or a
generic xfrm policy.

**Return**

Return 0 if permission is granted, -ESRCH otherwise, or -errno on
other errors.

#### <a id="c-security_xfrm_state_pol_flow_match"></a>`security_xfrm_state_pol_flow_match()`

```c
int security_xfrm_state_pol_flow_match(struct xfrm_state *x, struct xfrm_policy *xp, const struct flowi_common *flic)
```

Check for a xfrm match

**Parameters**

- `struct xfrm_state *x`: xfrm state to match
- `struct xfrm_policy *xp`: xfrm policy to check for a match
- `const struct flowi_common *flic`: flow to check for a match.

**Description**

Check **xp** and **flic** for a match with **x**.

**Return**

Returns 1 if there is a match.

#### <a id="c-security_xfrm_decode_session"></a>`security_xfrm_decode_session()`

```c
int security_xfrm_decode_session(struct sk_buff *skb, u32 *secid)
```

Determine the xfrm secid for a packet

**Parameters**

- `struct sk_buff *skb`: xfrm packet
- `u32 *secid`: secid

**Description**

Decode the packet in **skb** and return the security label in **secid**.

**Return**

Return 0 if all xfrms used have the same secid.

#### <a id="c-security_key_alloc"></a>`security_key_alloc()`

```c
int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags)
```

Allocate and initialize a kernel key LSM blob

**Parameters**

- `struct key *key`: key
- `const struct cred *cred`: credentials
- `unsigned long flags`: allocation flags

**Description**

Permit allocation of a key and assign security data. Note that key does not
have a serial number assigned at this point.

**Return**

Return 0 if permission is granted, -ve error otherwise.

#### <a id="c-security_key_free"></a>`security_key_free()`

```c
void security_key_free(struct key *key)
```

Free a kernel key LSM blob

**Parameters**

- `struct key *key`: key

**Description**

Notification of destruction; free security data.

#### <a id="c-security_key_permission"></a>`security_key_permission()`

```c
int security_key_permission(key_ref_t key_ref, const struct cred *cred, enum key_need_perm need_perm)
```

Check if a kernel key operation is allowed

**Parameters**

- `key_ref_t key_ref`: key reference
- `const struct cred *cred`: credentials of actor requesting access
- `enum key_need_perm need_perm`: requested permissions

**Description**

See whether a specific operational right is granted to a process on a key.

**Return**

Return 0 if permission is granted, -ve error otherwise.

#### <a id="c-security_key_getsecurity"></a>`security_key_getsecurity()`

```c
int security_key_getsecurity(struct key *key, char **buffer)
```

Get the key's security label

**Parameters**

- `struct key *key`: key
- `char **buffer`: security label buffer

**Description**

Get a textual representation of the security context attached to a key for
the purposes of honouring KEYCTL_GETSECURITY.  This function allocates the
storage for the NUL-terminated string and the caller should free it.

**Return**

Returns the length of **buffer** (including terminating NUL) or -ve if
an error occurs.  May also return 0 (and a NULL buffer pointer) if
there is no security label assigned to the key.

#### <a id="c-security_key_post_create_or_update"></a>`security_key_post_create_or_update()`

```c
void security_key_post_create_or_update(struct key *keyring, struct key *key, const void *payload, size_t payload_len, unsigned long flags, bool create)
```

Notification of key create or update

**Parameters**

- `struct key *keyring`: keyring to which the key is linked to
- `struct key *key`: created or updated key
- `const void *payload`: data used to instantiate or update the key
- `size_t payload_len`: length of payload
- `unsigned long flags`: key flags
- `bool create`: flag indicating whether the key was created or updated

**Description**

Notify the caller of a key creation or update.

#### <a id="c-security_audit_rule_init"></a>`security_audit_rule_init()`

```c
int security_audit_rule_init(u32 field, u32 op, char *rulestr, void **lsmrule, gfp_t gfp)
```

Allocate and init an LSM audit rule struct

**Parameters**

- `u32 field`: audit action
- `u32 op`: rule operator
- `char *rulestr`: rule context
- `void **lsmrule`: receive buffer for audit rule struct
- `gfp_t gfp`: GFP flag used for kmalloc

**Description**

Allocate and initialize an LSM audit rule structure.

**Return**

Return 0 if **lsmrule** has been successfully set, -EINVAL in case of
an invalid rule.

#### <a id="c-security_audit_rule_known"></a>`security_audit_rule_known()`

```c
int security_audit_rule_known(struct audit_krule *krule)
```

Check if an audit rule contains LSM fields

**Parameters**

- `struct audit_krule *krule`: audit rule

**Description**

Specifies whether given **krule** contains any fields related to the current
LSM.

**Return**

Returns 1 in case of relation found, 0 otherwise.

#### <a id="c-security_audit_rule_free"></a>`security_audit_rule_free()`

```c
void security_audit_rule_free(void *lsmrule)
```

Free an LSM audit rule struct

**Parameters**

- `void *lsmrule`: audit rule struct

**Description**

Deallocate the LSM audit rule structure previously allocated by
`audit_rule_init()`.

#### <a id="c-security_audit_rule_match"></a>`security_audit_rule_match()`

```c
int security_audit_rule_match(struct lsm_prop *prop, u32 field, u32 op, void *lsmrule)
```

Check if a label matches an audit rule

**Parameters**

- `struct lsm_prop *prop`: security label
- `u32 field`: LSM audit field
- `u32 op`: matching operator
- `void *lsmrule`: audit rule

**Description**

Determine if given **secid** matches a rule previously approved by
[`security_audit_rule_known()`](#c-security_audit_rule_known).

**Return**

Returns 1 if secid matches the rule, 0 if it does not, -ERRNO on
failure.

#### <a id="c-security_bpf"></a>`security_bpf()`

```c
int security_bpf(int cmd, union bpf_attr *attr, unsigned int size, bool kernel)
```

Check if the bpf syscall operation is allowed

**Parameters**

- `int cmd`: command
- `union bpf_attr *attr`: bpf attribute
- `unsigned int size`: size
- `bool kernel`: whether or not call originated from kernel

**Description**

Do a initial check for all bpf syscalls after the attribute is copied into
the kernel. The actual security module can implement their own rules to
check the specific cmd they need.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_bpf_map"></a>`security_bpf_map()`

```c
int security_bpf_map(struct bpf_map *map, fmode_t fmode)
```

Check if access to a bpf map is allowed

**Parameters**

- `struct bpf_map *map`: bpf map
- `fmode_t fmode`: mode

**Description**

Do a check when the kernel generates and returns a file descriptor for eBPF
maps.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_bpf_prog"></a>`security_bpf_prog()`

```c
int security_bpf_prog(struct bpf_prog *prog)
```

Check if access to a bpf program is allowed

**Parameters**

- `struct bpf_prog *prog`: bpf program

**Description**

Do a check when the kernel generates and returns a file descriptor for eBPF
programs.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_bpf_map_create"></a>`security_bpf_map_create()`

```c
int security_bpf_map_create(struct bpf_map *map, union bpf_attr *attr, struct bpf_token *token, bool kernel)
```

Check if BPF map creation is allowed

**Parameters**

- `struct bpf_map *map`: BPF map object
- `union bpf_attr *attr`: BPF syscall attributes used to create BPF map
- `struct bpf_token *token`: BPF token used to grant user access
- `bool kernel`: whether or not call originated from kernel

**Description**

Do a check when the kernel creates a new BPF map. This is also the
point where LSM blob is allocated for LSMs that need them.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_bpf_prog_load"></a>`security_bpf_prog_load()`

```c
int security_bpf_prog_load(struct bpf_prog *prog, union bpf_attr *attr, struct bpf_token *token, bool kernel)
```

Check if loading of BPF program is allowed

**Parameters**

- `struct bpf_prog *prog`: BPF program object
- `union bpf_attr *attr`: BPF syscall attributes used to create BPF program
- `struct bpf_token *token`: BPF token used to grant user access to BPF subsystem
- `bool kernel`: whether or not call originated from kernel

**Description**

Perform an access control check when the kernel loads a BPF program and
allocates associated BPF program object. This hook is also responsible for
allocating any required LSM state for the BPF program.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_bpf_token_create"></a>`security_bpf_token_create()`

```c
int security_bpf_token_create(struct bpf_token *token, union bpf_attr *attr, const struct path *path)
```

Check if creating of BPF token is allowed

**Parameters**

- `struct bpf_token *token`: BPF token object
- `union bpf_attr *attr`: BPF syscall attributes used to create BPF token
- `const struct path *path`: path pointing to BPF FS mount point from which BPF token is created

**Description**

Do a check when the kernel instantiates a new BPF token object from BPF FS
instance. This is also the point where LSM blob can be allocated for LSMs.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_bpf_token_cmd"></a>`security_bpf_token_cmd()`

```c
int security_bpf_token_cmd(const struct bpf_token *token, enum bpf_cmd cmd)
```

Check if BPF token is allowed to delegate requested BPF syscall command

**Parameters**

- `const struct bpf_token *token`: BPF token object
- `enum bpf_cmd cmd`: BPF syscall command requested to be delegated by BPF token

**Description**

Do a check when the kernel decides whether provided BPF token should allow
delegation of requested BPF syscall command.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_bpf_token_capable"></a>`security_bpf_token_capable()`

```c
int security_bpf_token_capable(const struct bpf_token *token, int cap)
```

Check if BPF token is allowed to delegate requested BPF-related capability

**Parameters**

- `const struct bpf_token *token`: BPF token object
- `int cap`: capabilities requested to be delegated by BPF token

**Description**

Do a check when the kernel decides whether provided BPF token should allow
delegation of requested BPF-related capabilities.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_bpf_map_free"></a>`security_bpf_map_free()`

```c
void security_bpf_map_free(struct bpf_map *map)
```

Free a bpf map's LSM blob

**Parameters**

- `struct bpf_map *map`: bpf map

**Description**

Clean up the security information stored inside bpf map.

#### <a id="c-security_bpf_prog_free"></a>`security_bpf_prog_free()`

```c
void security_bpf_prog_free(struct bpf_prog *prog)
```

Free a BPF program's LSM blob

**Parameters**

- `struct bpf_prog *prog`: BPF program struct

**Description**

Clean up the security information stored inside BPF program.

#### <a id="c-security_bpf_token_free"></a>`security_bpf_token_free()`

```c
void security_bpf_token_free(struct bpf_token *token)
```

Free a BPF token's LSM blob

**Parameters**

- `struct bpf_token *token`: BPF token struct

**Description**

Clean up the security information stored inside BPF token.

#### <a id="c-security_perf_event_open"></a>`security_perf_event_open()`

```c
int security_perf_event_open(int type)
```

Check if a perf event open is allowed

**Parameters**

- `int type`: type of event

**Description**

Check whether the **type** of perf_event_open syscall is allowed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_perf_event_alloc"></a>`security_perf_event_alloc()`

```c
int security_perf_event_alloc(struct perf_event *event)
```

Allocate a perf event LSM blob

**Parameters**

- `struct perf_event *event`: perf event

**Description**

Allocate and save perf_event security info.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_perf_event_free"></a>`security_perf_event_free()`

```c
void security_perf_event_free(struct perf_event *event)
```

Free a perf event LSM blob

**Parameters**

- `struct perf_event *event`: perf event

**Description**

Release (free) perf_event security info.

#### <a id="c-security_perf_event_read"></a>`security_perf_event_read()`

```c
int security_perf_event_read(struct perf_event *event)
```

Check if reading a perf event label is allowed

**Parameters**

- `struct perf_event *event`: perf event

**Description**

Read perf_event security info if allowed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_perf_event_write"></a>`security_perf_event_write()`

```c
int security_perf_event_write(struct perf_event *event)
```

Check if writing a perf event label is allowed

**Parameters**

- `struct perf_event *event`: perf event

**Description**

Write perf_event security info if allowed.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_uring_override_creds"></a>`security_uring_override_creds()`

```c
int security_uring_override_creds(const struct cred *new)
```

Check if overriding creds is allowed

**Parameters**

- `const struct cred *new`: new credentials

**Description**

Check if the current task, executing an io_uring operation, is allowed to
override it's credentials with **new**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_uring_sqpoll"></a>`security_uring_sqpoll()`

```c
int security_uring_sqpoll(void)
```

Check if IORING_SETUP_SQPOLL is allowed

**Parameters**

- `void`: no arguments

**Description**

Check whether the current task is allowed to spawn a io_uring polling thread
(IORING_SETUP_SQPOLL).

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_uring_cmd"></a>`security_uring_cmd()`

```c
int security_uring_cmd(struct io_uring_cmd *ioucmd)
```

Check if a io_uring passthrough command is allowed

**Parameters**

- `struct io_uring_cmd *ioucmd`: command

**Description**

Check whether the file_operations uring_cmd is allowed to run.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_uring_allowed"></a>`security_uring_allowed()`

```c
int security_uring_allowed(void)
```

Check if `io_uring_setup()` is allowed

**Parameters**

- `void`: no arguments

**Description**

Check whether the current task is allowed to call `io_uring_setup()`.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_initramfs_populated"></a>`security_initramfs_populated()`

```c
void security_initramfs_populated(void)
```

Notify LSMs that initramfs has been loaded

**Parameters**

- `void`: no arguments

**Description**

Tells the LSMs the initramfs has been unpacked into the rootfs.



#### <a id="c-securityfs_create_file"></a>`securityfs_create_file()`

```c
struct dentry * securityfs_create_file(const char *name, umode_t mode, struct dentry *parent, void *data, const struct file_operations *fops)
```

create a file in the securityfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the securityfs filesystem.
- `void *data`: a pointer to something that the caller will want to get to later
  on.  The inode.i_private pointer will point to this value on
  the `open()` call.
- `const struct file_operations *fops`: a pointer to a struct file_operations that should be used for
  this file.

**Description**

This function creates a file in securityfs with the given **name**.

This function returns a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`securityfs_remove()`](#c-securityfs_remove) function when the file is
to be removed (no automatic cleanup happens if your module is unloaded,
you are responsible here).  If an error occurs, the function will return
the error value (via ERR_PTR).

If securityfs is not enabled in the kernel, the value `-ENODEV` is
returned.

#### <a id="c-securityfs_create_dir"></a>`securityfs_create_dir()`

```c
struct dentry * securityfs_create_dir(const char *name, struct dentry *parent)
```

create a directory in the securityfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the directory to
  create.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  directory will be created in the root of the securityfs filesystem.

**Description**

This function creates a directory in securityfs with the given **name**.

This function returns a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`securityfs_remove()`](#c-securityfs_remove) function when the file is
to be removed (no automatic cleanup happens if your module is unloaded,
you are responsible here).  If an error occurs, the function will return
the error value (via ERR_PTR).

If securityfs is not enabled in the kernel, the value `-ENODEV` is
returned.

#### <a id="c-securityfs_create_symlink"></a>`securityfs_create_symlink()`

```c
struct dentry * securityfs_create_symlink(const char *name, struct dentry *parent, const char *target, const struct inode_operations *iops)
```

create a symlink in the securityfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the symlink to
  create.
- `struct dentry *parent`: a pointer to the parent dentry for the symlink.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  directory will be created in the root of the securityfs filesystem.
- `const char *target`: a pointer to a string containing the name of the symlink's target.
  If this parameter is `NULL`, then the **iops** parameter needs to be
  setup to handle .readlink and .get_link inode_operations.
- `const struct inode_operations *iops`: a pointer to the struct inode_operations to use for the symlink. If
  this parameter is `NULL`, then the default simple_symlink_inode
  operations will be used.

**Description**

This function creates a symlink in securityfs with the given **name**.

This function returns a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`securityfs_remove()`](#c-securityfs_remove) function when the file is
to be removed (no automatic cleanup happens if your module is unloaded,
you are responsible here).  If an error occurs, the function will return
the error value (via ERR_PTR).

If securityfs is not enabled in the kernel, the value `-ENODEV` is
returned.

#### <a id="c-securityfs_remove"></a>`securityfs_remove()`

```c
void securityfs_remove(struct dentry *dentry)
```

removes a file or directory from the securityfs filesystem

**Parameters**

- `struct dentry *dentry`: a pointer to a the dentry of the file or directory to be removed.

**Description**

This function removes a file or directory in securityfs that was previously
created with a call to another securityfs function (like
[`securityfs_create_file()`](#c-securityfs_create_file) or variants thereof.)

This function is required to be called in order for the file to be
removed. No automatic cleanup of files will happen when a module is
removed; you are responsible here.

AV: when applied to directory it will take all children out; no need to call
it for descendents if ancestor is getting killed.


<a id="rst-audit-interfaces"></a>

## Audit Interfaces


#### <a id="c-audit_log_start"></a>`audit_log_start()`

```c
struct audit_buffer * audit_log_start(struct audit_context *ctx, gfp_t gfp_mask, int type)
```

obtain an audit buffer

**Parameters**

- `struct audit_context *ctx`: audit_context (may be NULL)
- `gfp_t gfp_mask`: type of allocation
- `int type`: audit message type

**Description**

Returns audit_buffer pointer on success or NULL on error.

Obtain an audit buffer.  This routine does locking to obtain the
audit buffer, but then no locking is required for calls to
audit_log_*format.  If the task (ctx) is a task that is currently in a
syscall, then the syscall is marked as auditable and an audit record
will be written at syscall exit.  If there is no associated task, then
task context (ctx) should be NULL.

#### <a id="c-audit_log_format"></a>`audit_log_format()`

```c
void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
```

format a message into the audit buffer.

**Parameters**

- `struct audit_buffer *ab`: audit_buffer
- `const char *fmt`: format string
- `...`: optional parameters matching **fmt** string

**Description**

All the work is done in audit_log_vformat.

#### <a id="c-audit_log_subj_ctx"></a>`audit_log_subj_ctx()`

```c
int audit_log_subj_ctx(struct audit_buffer *ab, struct lsm_prop *prop)
```

Add LSM subject information

**Parameters**

- `struct audit_buffer *ab`: audit_buffer
- `struct lsm_prop *prop`: LSM subject properties.

**Description**

Add a subj= field and, if necessary, a AUDIT_MAC_TASK_CONTEXTS record.

#### <a id="c-audit_log_end"></a>`audit_log_end()`

```c
void audit_log_end(struct audit_buffer *ab)
```

end one audit record

**Parameters**

- `struct audit_buffer *ab`: the audit_buffer

**Description**

We can not do a netlink send inside an irq context because it blocks (last
arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
queue and a kthread is scheduled to remove them from the queue outside the
irq context.  May be called in any context.

#### <a id="c-audit_log"></a>`audit_log()`

```c
void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type, const char *fmt, ...)
```

Log an audit record

**Parameters**

- `struct audit_context *ctx`: audit context
- `gfp_t gfp_mask`: type of allocation
- `int type`: audit message type
- `const char *fmt`: format string to use
- `...`: variable parameters matching the format string

**Description**

This is a convenience function that calls audit_log_start,
audit_log_vformat, and audit_log_end.  It may be called
in any context.



#### <a id="c-__audit_filter_op"></a>`__audit_filter_op()`

```c
int __audit_filter_op(struct task_struct *tsk, struct audit_context *ctx, struct list_head *list, struct audit_names *name, unsigned long op)
```

common filter helper for operations (syscall/uring/etc)

**Parameters**

- `struct task_struct *tsk`: associated task
- `struct audit_context *ctx`: audit context
- `struct list_head *list`: audit filter list
- `struct audit_names *name`: audit_name (can be NULL)
- `unsigned long op`: current syscall/uring_op

**Description**

Run the udit filters specified in **list** against **tsk** using **ctx**,
**name**, and **op**, as necessary; the caller is responsible for ensuring
that the call is made while the RCU read lock is held. The **name**
parameter can be NULL, but all others must be specified.
Returns 1/true if the filter finds a match, 0/false if none are found.

#### <a id="c-audit_filter_uring"></a>`audit_filter_uring()`

```c
void audit_filter_uring(struct task_struct *tsk, struct audit_context *ctx)
```

apply filters to an io_uring operation

**Parameters**

- `struct task_struct *tsk`: associated task
- `struct audit_context *ctx`: audit context

#### <a id="c-audit_reset_context"></a>`audit_reset_context()`

```c
void audit_reset_context(struct audit_context *ctx)
```

reset a audit_context structure

**Parameters**

- `struct audit_context *ctx`: the audit_context to reset

**Description**

All fields in the audit_context will be reset to an initial state, all
references held by fields will be dropped, and private memory will be
released.  When this function returns the audit_context will be suitable
for reuse, so long as the passed context is not NULL or a dummy context.

#### <a id="c-audit_alloc"></a>`audit_alloc()`

```c
int audit_alloc(struct task_struct *tsk)
```

allocate an audit context block for a task

**Parameters**

- `struct task_struct *tsk`: task

**Description**

Filter on the task information and allocate a per-task audit context
if necessary.  Doing so turns on system call auditing for the
specified task.  This is called from copy_process, so no lock is
needed.

#### <a id="c-audit_log_uring"></a>`audit_log_uring()`

```c
void audit_log_uring(struct audit_context *ctx)
```

generate a AUDIT_URINGOP record

**Parameters**

- `struct audit_context *ctx`: the audit context

#### <a id="c-__audit_free"></a>`__audit_free()`

```c
void __audit_free(struct task_struct *tsk)
```

free a per-task audit context

**Parameters**

- `struct task_struct *tsk`: task whose audit context block to free

**Description**

Called from copy_process, do_exit, and the io_uring code

#### <a id="c-audit_return_fixup"></a>`audit_return_fixup()`

```c
void audit_return_fixup(struct audit_context *ctx, int success, long code)
```

fixup the return codes in the audit_context

**Parameters**

- `struct audit_context *ctx`: the audit_context
- `int success`: true/false value to indicate if the operation succeeded or not
- `long code`: operation return code

**Description**

We need to fixup the return code in the audit logs if the actual return
codes are later going to be fixed by the arch specific signal handlers.

#### <a id="c-__audit_uring_entry"></a>`__audit_uring_entry()`

```c
void __audit_uring_entry(u8 op)
```

prepare the kernel task's audit context for io_uring

**Parameters**

- `u8 op`: the io_uring opcode

**Description**

This is similar to `audit_syscall_entry()` but is intended for use by io_uring
operations.  This function should only ever be called from
`audit_uring_entry()` as we rely on the audit context checking present in that
function.

#### <a id="c-__audit_uring_exit"></a>`__audit_uring_exit()`

```c
void __audit_uring_exit(int success, long code)
```

wrap up the kernel task's audit context after io_uring

**Parameters**

- `int success`: true/false value to indicate if the operation succeeded or not
- `long code`: operation return code

**Description**

This is similar to `audit_syscall_exit()` but is intended for use by io_uring
operations.  This function should only ever be called from
`audit_uring_exit()` as we rely on the audit context checking present in that
function.

#### <a id="c-__audit_syscall_entry"></a>`__audit_syscall_entry()`

```c
void __audit_syscall_entry(int major, unsigned long a1, unsigned long a2, unsigned long a3, unsigned long a4)
```

fill in an audit record at syscall entry

**Parameters**

- `int major`: major syscall type (function)
- `unsigned long a1`: additional syscall register 1
- `unsigned long a2`: additional syscall register 2
- `unsigned long a3`: additional syscall register 3
- `unsigned long a4`: additional syscall register 4

**Description**

Fill in audit context at syscall entry.  This only happens if the
audit context was created when the task was created and the state or
filters demand the audit context be built.  If the state from the
per-task filter or from the per-syscall filter is AUDIT_STATE_RECORD,
then the record will be written at syscall exit time (otherwise, it
will only be written if another part of the kernel requests that it
be written).

#### <a id="c-__audit_syscall_exit"></a>`__audit_syscall_exit()`

```c
void __audit_syscall_exit(int success, long return_code)
```

deallocate audit context after a system call

**Parameters**

- `int success`: success value of the syscall
- `long return_code`: return value of the syscall

**Description**

Tear down after system call.  If the audit context has been marked as
auditable (either because of the AUDIT_STATE_RECORD state from
filtering, or because some other part of the kernel wrote an audit
message), then write out the syscall information.  In call cases,
free the names stored from `getname()`.

#### <a id="c-__audit_getname"></a>`__audit_getname()`

```c
void __audit_getname(struct filename *name)
```

add a name to the list

**Parameters**

- `struct filename *name`: name to add

**Description**

Add a name to the list of audit names for this context.
Called from fs/namei.c:`getname()`.

#### <a id="c-__audit_inode"></a>`__audit_inode()`

```c
void __audit_inode(struct filename *name, const struct dentry *dentry, unsigned int flags)
```

store the inode and device from a lookup

**Parameters**

- `struct filename *name`: name being audited
- `const struct dentry *dentry`: dentry being audited
- `unsigned int flags`: attributes for this particular entry

#### <a id="c-auditsc_get_stamp"></a>`auditsc_get_stamp()`

```c
int auditsc_get_stamp(struct audit_context *ctx, struct audit_stamp *stamp)
```

get local copies of audit_context values

**Parameters**

- `struct audit_context *ctx`: audit_context for the task
- `struct audit_stamp *stamp`: timestamp to record

**Description**

Also sets the context as auditable.

#### <a id="c-__audit_mq_open"></a>`__audit_mq_open()`

```c
void __audit_mq_open(int oflag, umode_t mode, struct mq_attr *attr)
```

record audit data for a POSIX MQ open

**Parameters**

- `int oflag`: open flag
- `umode_t mode`: mode bits
- `struct mq_attr *attr`: queue attributes

#### <a id="c-__audit_mq_sendrecv"></a>`__audit_mq_sendrecv()`

```c
void __audit_mq_sendrecv(mqd_t mqdes, size_t msg_len, unsigned int msg_prio, const struct timespec64 *abs_timeout)
```

record audit data for a POSIX MQ timed send/receive

**Parameters**

- `mqd_t mqdes`: MQ descriptor
- `size_t msg_len`: Message length
- `unsigned int msg_prio`: Message priority
- `const struct timespec64 *abs_timeout`: Message timeout in absolute time

#### <a id="c-__audit_mq_notify"></a>`__audit_mq_notify()`

```c
void __audit_mq_notify(mqd_t mqdes, const struct sigevent *notification)
```

record audit data for a POSIX MQ notify

**Parameters**

- `mqd_t mqdes`: MQ descriptor
- `const struct sigevent *notification`: Notification event

#### <a id="c-__audit_mq_getsetattr"></a>`__audit_mq_getsetattr()`

```c
void __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
```

record audit data for a POSIX MQ get/set attribute

**Parameters**

- `mqd_t mqdes`: MQ descriptor
- `struct mq_attr *mqstat`: MQ flags

#### <a id="c-__audit_ipc_obj"></a>`__audit_ipc_obj()`

```c
void __audit_ipc_obj(struct kern_ipc_perm *ipcp)
```

record audit data for ipc object

**Parameters**

- `struct kern_ipc_perm *ipcp`: ipc permissions

#### <a id="c-__audit_ipc_set_perm"></a>`__audit_ipc_set_perm()`

```c
void __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, umode_t mode)
```

record audit data for new ipc permissions

**Parameters**

- `unsigned long qbytes`: msgq bytes
- `uid_t uid`: msgq user id
- `gid_t gid`: msgq group id
- `umode_t mode`: msgq mode (permissions)

**Description**

Called only after `audit_ipc_obj()`.

#### <a id="c-__audit_socketcall"></a>`__audit_socketcall()`

```c
int __audit_socketcall(int nargs, unsigned long *args)
```

record audit data for sys_socketcall

**Parameters**

- `int nargs`: number of args, which should not be more than AUDITSC_ARGS.
- `unsigned long *args`: args array

#### <a id="c-__audit_fd_pair"></a>`__audit_fd_pair()`

```c
void __audit_fd_pair(int fd1, int fd2)
```

record audit data for pipe and socketpair

**Parameters**

- `int fd1`: the first file descriptor
- `int fd2`: the second file descriptor

#### <a id="c-__audit_sockaddr"></a>`__audit_sockaddr()`

```c
int __audit_sockaddr(int len, void *a)
```

record audit data for sys_bind, sys_connect, sys_sendto

**Parameters**

- `int len`: data length in user space
- `void *a`: data address in kernel space

**Description**

Returns 0 for success or NULL context or \< 0 on error.

#### <a id="c-audit_signal_info_syscall"></a>`audit_signal_info_syscall()`

```c
int audit_signal_info_syscall(struct task_struct *t)
```

record signal info for syscalls

**Parameters**

- `struct task_struct *t`: task being signaled

**Description**

If the audit subsystem is being terminated, record the task (pid)
and uid that is doing that.

#### <a id="c-__audit_log_bprm_fcaps"></a>`__audit_log_bprm_fcaps()`

```c
int __audit_log_bprm_fcaps(struct linux_binprm *bprm, const struct cred *new, const struct cred *old)
```

store information about a loading bprm and relevant fcaps

**Parameters**

- `struct linux_binprm *bprm`: pointer to the bprm being processed
- `const struct cred *new`: the proposed new credentials
- `const struct cred *old`: the old credentials

**Description**

Simply check if the proc already has the caps given by the file and if not
store the priv escalation info for later auditing at the end of the syscall

-Eric

#### <a id="c-__audit_log_capset"></a>`__audit_log_capset()`

```c
void __audit_log_capset(const struct cred *new, const struct cred *old)
```

store information about the arguments to the capset syscall

**Parameters**

- `const struct cred *new`: the new credentials
- `const struct cred *old`: the old (current) credentials

**Description**

Record the arguments userspace sent to sys_capset for later printing by the
audit system if applicable

#### <a id="c-audit_core_dumps"></a>`audit_core_dumps()`

```c
void audit_core_dumps(long signr)
```

record information about processes that end abnormally

**Parameters**

- `long signr`: signal value

**Description**

If a process ends with a core dump, something fishy is going on and we
should record the event for investigation.

#### <a id="c-audit_seccomp"></a>`audit_seccomp()`

```c
void audit_seccomp(unsigned long syscall, long signr, int code)
```

record information about a seccomp action

**Parameters**

- `unsigned long syscall`: syscall number
- `long signr`: signal value
- `int code`: the seccomp action

**Description**

Record the information associated with a seccomp action. Event filtering for
seccomp actions that are not to be logged is done in `seccomp_log()`.
Therefore, this function forces auditing independent of the audit_enabled
and dummy context state because seccomp actions should be logged even when
audit is not in use.



#### <a id="c-audit_rule_change"></a>`audit_rule_change()`

```c
int audit_rule_change(int type, int seq, void *data, size_t datasz)
```

apply all rules to the specified message type

**Parameters**

- `int type`: audit message type
- `int seq`: netlink audit message sequence (serial) number
- `void *data`: payload data
- `size_t datasz`: size of payload data

#### <a id="c-audit_list_rules_send"></a>`audit_list_rules_send()`

```c
int audit_list_rules_send(struct sk_buff *request_skb, int seq)
```

list the audit rules

**Parameters**

- `struct sk_buff *request_skb`: skb of request we are replying to (used to target the reply)
- `int seq`: netlink audit message sequence (serial) number

#### <a id="c-parent_len"></a>`parent_len()`

```c
int parent_len(const char *path)
```

find the length of the parent portion of a pathname

**Parameters**

- `const char *path`: pathname of which to determine length

#### <a id="c-audit_compare_dname_path"></a>`audit_compare_dname_path()`

```c
int audit_compare_dname_path(const struct qstr *dname, const char *path, int parentlen)
```

compare given dentry name with last component in given path. Return of 0 indicates a match.

**Parameters**

- `const struct qstr *dname`: dentry name that we're comparing
- `const char *path`: full pathname that we're comparing
- `int parentlen`: length of the parent if known. Passing in AUDIT_NAME_FULL
  here indicates that we must compute this value.


<a id="rst-accounting-framework"></a>

## Accounting Framework


#### <a id="c-sys_acct"></a>`sys_acct()`

```c
long sys_acct(const char __user * name)
```

enable/disable process accounting

**Parameters**

- `const char __user * name`: file name for accounting records or NULL to shutdown accounting

**Description**

[`sys_acct()`](#c-sys_acct) is the only system call needed to implement process
accounting. It takes the name of the file where accounting records
should be written. If the filename is NULL, accounting will be
shutdown.

**Return**

0 for success or negative errno values for failure.

#### <a id="c-acct_collect"></a>`acct_collect()`

```c
void acct_collect(long exitcode, int group_dead)
```

collect accounting information into pacct_struct

**Parameters**

- `long exitcode`: task exit code
- `int group_dead`: not 0, if this thread is the last one in the process.

#### <a id="c-acct_process"></a>`acct_process()`

```c
void acct_process(void)
```

handles process accounting for an exiting task

**Parameters**

- `void`: no arguments


<a id="rst-block-devices"></a>

## Block Devices


#### <a id="c-bio_advance"></a>`bio_advance()`

```c
void bio_advance(struct bio *bio, unsigned int nbytes)
```

increment/complete a bio by some number of bytes

**Parameters**

- `struct bio *bio`: bio to advance
- `unsigned int nbytes`: number of bytes to complete

**Description**

This updates bi_sector, bi_size and bi_idx; if the number of bytes to
complete doesn't align with a bvec boundary, then bv_len and bv_offset will
be updated on the last bvec as well.

**bio** will then represent the remaining, uncompleted portion of the io.

#### <a id="c-struct-folio_iter"></a>`struct folio_iter`

State for iterating all folios in a bio.

**Definition**

```c
struct folio_iter {
    struct folio *folio;
    size_t offset;
    size_t length;
};
```

**Members**

- `folio`: The current folio we're iterating.  NULL after the last folio.
- `offset`: The byte offset within the current folio.
- `length`: The number of bytes in this iteration (will not cross folio
  boundary).

#### <a id="c-bio_for_each_folio_all"></a>`bio_for_each_folio_all()`

```c
bio_for_each_folio_all(fi, bio)
```

Iterate over each folio in a bio.

**Parameters**

- `fi`: struct folio_iter which is updated for each folio.
- `bio`: struct bio to iterate over.

#### <a id="c-bio_next_split"></a>`bio_next_split()`

```c
struct bio * bio_next_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs)
```

get next **sectors** from a bio, splitting if necessary

**Parameters**

- `struct bio *bio`: bio to split
- `int sectors`: number of sectors to split from the front of **bio**
- `gfp_t gfp`: gfp mask
- `struct bio_set *bs`: bio set to allocate from

**Return**

a bio representing the next **sectors** of **bio** - if the bio is smaller
than **sectors**, returns the original bio unchanged.

#### <a id="c-bio_iov_bounce_nr_vecs"></a>`bio_iov_bounce_nr_vecs()`

```c
unsigned short bio_iov_bounce_nr_vecs(struct iov_iter *iter, blk_opf_t op)
```

calculate number of bvecs for a bounce bio

**Parameters**

- `struct iov_iter *iter`: iter to bounce from
- `blk_opf_t op`: REQ_OP_* for the bio

**Description**

Calculates how many bvecs are needed for the next bio to bounce from/to
**iter**.

#### <a id="c-bio_add_max_vecs"></a>`bio_add_max_vecs()`

```c
unsigned int bio_add_max_vecs(void *kaddr, unsigned int len)
```

number of bio_vecs needed to add data to a bio

**Parameters**

- `void *kaddr`: kernel virtual address to add
- `unsigned int len`: length in bytes to add

**Description**

Calculate how many bio_vecs need to be allocated to add the kernel virtual
address range in \[**kaddr**:**len**\] in the worse case.

#### <a id="c-bio_is_zone_append"></a>`bio_is_zone_append()`

```c
bool bio_is_zone_append(struct bio *bio)
```

is this a zone append bio?

**Parameters**

- `struct bio *bio`: bio to check

**Description**

Check if **bio** is a zone append operation.  Core block layer code and end_io
handlers must use this instead of an open coded REQ_OP_ZONE_APPEND check
because the block layer can rewrite REQ_OP_ZONE_APPEND to REQ_OP_WRITE if
it is not natively supported.



#### <a id="c-blk_queue_flag_set"></a>`blk_queue_flag_set()`

```c
void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
```

atomically set a queue flag

**Parameters**

- `unsigned int flag`: flag to be set
- `struct request_queue *q`: request queue

#### <a id="c-blk_queue_flag_clear"></a>`blk_queue_flag_clear()`

```c
void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
```

atomically clear a queue flag

**Parameters**

- `unsigned int flag`: flag to be cleared
- `struct request_queue *q`: request queue

#### <a id="c-blk_op_str"></a>`blk_op_str()`

```c
const char * blk_op_str(enum req_op op)
```

Return the string "name" for an operation REQ_OP_name.

**Parameters**

- `enum req_op op`: a request operation.

**Description**

Convert a request operation REQ_OP_name into the string "name". Useful for
debugging and tracing BIOs and requests. For an invalid request operation
code, the string "UNKNOWN" is returned.

#### <a id="c-blk_sync_queue"></a>`blk_sync_queue()`

```c
void blk_sync_queue(struct request_queue *q)
```

cancel any pending callbacks on a queue

**Parameters**

- `struct request_queue *q`: the queue

**Description**

The block layer may perform asynchronous callback activity
on a queue, such as calling the unplug function after a timeout.
A block device may call blk_sync_queue to ensure that any
such activity is cancelled, thus allowing it to release resources
that the callbacks might use. The caller must already have made sure
that its ->submit_bio will not re-add plugging prior to calling
this function.

This function does not cancel any asynchronous activity arising
out of elevator or throttling code. That would require `elevator_exit()`
and `blkcg_exit_queue()` to be called with queue lock initialized.

#### <a id="c-blk_set_pm_only"></a>`blk_set_pm_only()`

```c
void blk_set_pm_only(struct request_queue *q)
```

increment pm_only counter

**Parameters**

- `struct request_queue *q`: request queue pointer

#### <a id="c-blk_put_queue"></a>`blk_put_queue()`

```c
void blk_put_queue(struct request_queue *q)
```

decrement the request_queue refcount

**Parameters**

- `struct request_queue *q`: the request_queue structure to decrement the refcount for

**Description**

Decrements the refcount of the request_queue and free it when the refcount
reaches 0.

#### <a id="c-blk_get_queue"></a>`blk_get_queue()`

```c
bool blk_get_queue(struct request_queue *q)
```

increment the request_queue refcount

**Parameters**

- `struct request_queue *q`: the request_queue structure to increment the refcount for

**Description**

Increment the refcount of the request_queue kobject.

**Context**

Any context.

#### <a id="c-submit_bio_noacct"></a>`submit_bio_noacct()`

```c
void submit_bio_noacct(struct bio *bio)
```

re-submit a bio to the block device layer for I/O

**Parameters**

- `struct bio *bio`: The bio describing the location in memory and on the device.

**Description**

This is a version of [`submit_bio()`](#c-submit_bio) that shall only be used for I/O that is
resubmitted to lower level drivers by stacking block drivers.  All file
systems and other upper level users of the block layer should use
[`submit_bio()`](#c-submit_bio) instead.

#### <a id="c-submit_bio"></a>`submit_bio()`

```c
void submit_bio(struct bio *bio)
```

submit a bio to the block device layer for I/O

**Parameters**

- `struct bio *bio`: The `struct bio` which describes the I/O

**Description**

[`submit_bio()`](#c-submit_bio) is used to submit I/O requests to block devices.  It is passed a
fully set up `struct bio` that describes the I/O that needs to be done.  The
bio will be sent to the device described by the bi_bdev field.

The success/failure status of the request, along with notification of
completion, is delivered asynchronously through the ->`bi_end_io()` callback
in **bio**.  The bio must NOT be touched by the caller until ->`bi_end_io()` has
been called.

#### <a id="c-bio_poll"></a>`bio_poll()`

```c
int bio_poll(struct bio *bio, struct io_comp_batch *iob, unsigned int flags)
```

poll for BIO completions

**Parameters**

- `struct bio *bio`: bio to poll for
- `struct io_comp_batch *iob`: batches of IO
- `unsigned int flags`: BLK_POLL_* flags that control the behavior

**Description**

Poll for completions on queue associated with the bio. Returns number of
completed entries found.

**Note**

the caller must either be the context that submitted **bio**, or
be in a RCU critical section to prevent freeing of **bio**.

#### <a id="c-bio_start_io_acct"></a>`bio_start_io_acct()`

```c
unsigned long bio_start_io_acct(struct bio *bio)
```

start I/O accounting for bio based drivers

**Parameters**

- `struct bio *bio`: bio to start account for

**Description**

Returns the start time that should be passed back to `bio_end_io_acct()`.

#### <a id="c-blk_lld_busy"></a>`blk_lld_busy()`

```c
int blk_lld_busy(struct request_queue *q)
```

Check if underlying low-level drivers of a device are busy

**Parameters**

- `struct request_queue *q`: the queue of the device being checked

**Description**

Check if underlying low-level drivers of a device are busy.
If the drivers want to export their busy state, they must set own
exporting function using `blk_queue_lld_busy()` first.

Basically, this function is used only by request stacking drivers
to stop dispatching requests to underlying devices when underlying
devices are busy.  This behavior helps more I/O merging on the queue
of the request stacking driver and prevents I/O throughput regression
on burst I/O load.

**Return**

0 - Not busy (The request stacking driver should dispatch request)
1 - Busy (The request stacking driver should stop dispatching request)

#### <a id="c-blk_start_plug"></a>`blk_start_plug()`

```c
void blk_start_plug(struct blk_plug *plug)
```

initialize blk_plug and track it inside the task_struct

**Parameters**

- `struct blk_plug *plug`: The `struct blk_plug` that needs to be initialized

**Description**

[`blk_start_plug()`](#c-blk_start_plug) indicates to the block layer an intent by the caller
to submit multiple I/O requests in a batch.  The block layer may use
this hint to defer submitting I/Os from the caller until [`blk_finish_plug()`](#c-blk_finish_plug)
is called.  However, the block layer may choose to submit requests
before a call to [`blk_finish_plug()`](#c-blk_finish_plug) if the number of queued I/Os
exceeds `BLK_MAX_REQUEST_COUNT`, or if the size of the I/O is larger than
`BLK_PLUG_FLUSH_SIZE`.  The queued I/Os may also be submitted early if
the task schedules (see below).

Tracking blk_plug inside the task_struct will help with auto-flushing the
pending I/O should the task end up blocking between [`blk_start_plug()`](#c-blk_start_plug) and
[`blk_finish_plug()`](#c-blk_finish_plug). This is important from a performance perspective, but
also ensures that we don't deadlock. For instance, if the task is blocking
for a memory allocation, memory reclaim could end up wanting to free a
page belonging to that request that is currently residing in our private
plug. By flushing the pending I/O when the process goes to sleep, we avoid
this kind of deadlock.

#### <a id="c-blk_finish_plug"></a>`blk_finish_plug()`

```c
void blk_finish_plug(struct blk_plug *plug)
```

mark the end of a batch of submitted I/O

**Parameters**

- `struct blk_plug *plug`: The `struct blk_plug` passed to [`blk_start_plug()`](#c-blk_start_plug)

**Description**

Indicate that a batch of I/O submissions is complete.  This function
must be paired with an initial call to [`blk_start_plug()`](#c-blk_start_plug).  The intent
is to allow the block layer to optimize I/O submission.  See the
documentation for [`blk_start_plug()`](#c-blk_start_plug) for more information.



#### <a id="c-blk_queue_enter"></a>`blk_queue_enter()`

```c
int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
```

try to increase q->q_usage_counter

**Parameters**

- `struct request_queue *q`: request queue pointer
- `blk_mq_req_flags_t flags`: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM



#### <a id="c-blk_rq_map_user_iov"></a>`blk_rq_map_user_iov()`

```c
int blk_rq_map_user_iov(struct request_queue *q, struct request *rq, struct rq_map_data *map_data, const struct iov_iter *iter, gfp_t gfp_mask)
```

map user data to a request, for passthrough requests

**Parameters**

- `struct request_queue *q`: request queue where request should be inserted
- `struct request *rq`: request to map data to
- `struct rq_map_data *map_data`: pointer to the rq_map_data holding pages (if necessary)
- `const struct iov_iter *iter`: iovec iterator
- `gfp_t gfp_mask`: memory allocation flags

**Description**

Data will be mapped directly for zero copy I/O, if possible. Otherwise
a kernel bounce buffer is used.

A matching [`blk_rq_unmap_user()`](#c-blk_rq_unmap_user) must be issued at the end of I/O, while
still in process context.

#### <a id="c-blk_rq_unmap_user"></a>`blk_rq_unmap_user()`

```c
int blk_rq_unmap_user(struct bio *bio)
```

unmap a request with user data

**Parameters**

- `struct bio *bio`: start of bio list

**Description**

Unmap a rq previously mapped by `blk_rq_map_user()`. The caller must
supply the original rq->bio from the `blk_rq_map_user()` return, since
the I/O completion may have changed rq->bio.

#### <a id="c-blk_rq_map_kern"></a>`blk_rq_map_kern()`

```c
int blk_rq_map_kern(struct request *rq, void *kbuf, unsigned int len, gfp_t gfp_mask)
```

map kernel data to a request, for passthrough requests

**Parameters**

- `struct request *rq`: request to fill
- `void *kbuf`: the kernel buffer
- `unsigned int len`: length of user data
- `gfp_t gfp_mask`: memory allocation flags

**Description**

Data will be mapped directly if possible. Otherwise a bounce
buffer is used. Can be called multiple times to append multiple
buffers.



#### <a id="c-blk_register_queue"></a>`blk_register_queue()`

```c
int blk_register_queue(struct gendisk *disk)
```

register a block layer queue with sysfs

**Parameters**

- `struct gendisk *disk`: Disk of which the request queue should be registered with sysfs.

#### <a id="c-blk_unregister_queue"></a>`blk_unregister_queue()`

```c
void blk_unregister_queue(struct gendisk *disk)
```

counterpart of [`blk_register_queue()`](#c-blk_register_queue)

**Parameters**

- `struct gendisk *disk`: Disk of which the request queue should be unregistered from sysfs.

**Note**

the caller is responsible for guaranteeing that this function is called
after [`blk_register_queue()`](#c-blk_register_queue) has finished.



#### <a id="c-blk_set_stacking_limits"></a>`blk_set_stacking_limits()`

```c
void blk_set_stacking_limits(struct queue_limits *lim)
```

set default limits for stacking devices

**Parameters**

- `struct queue_limits *lim`: the queue_limits structure to reset

**Description**

Prepare queue limits for applying limits from underlying devices using
[`blk_stack_limits()`](#c-blk_stack_limits).

#### <a id="c-queue_limits_commit_update"></a>`queue_limits_commit_update()`

```c
int queue_limits_commit_update(struct request_queue *q, struct queue_limits *lim)
```

commit an atomic update of queue limits

**Parameters**

- `struct request_queue *q`: queue to update
- `struct queue_limits *lim`: limits to apply

**Description**

Apply the limits in **lim** that were obtained from `queue_limits_start_update()`
and updated by the caller to **q**.  The caller must have frozen the queue or
ensure that there are no outstanding I/Os by other means.

Returns 0 if successful, else a negative error code.

#### <a id="c-queue_limits_commit_update_frozen"></a>`queue_limits_commit_update_frozen()`

```c
int queue_limits_commit_update_frozen(struct request_queue *q, struct queue_limits *lim)
```

commit an atomic update of queue limits

**Parameters**

- `struct request_queue *q`: queue to update
- `struct queue_limits *lim`: limits to apply

**Description**

Apply the limits in **lim** that were obtained from `queue_limits_start_update()`
and updated with the new values by the caller to **q**.  Freezes the queue
before the update and unfreezes it after.

Returns 0 if successful, else a negative error code.

#### <a id="c-queue_limits_set"></a>`queue_limits_set()`

```c
int queue_limits_set(struct request_queue *q, struct queue_limits *lim)
```

apply queue limits to queue

**Parameters**

- `struct request_queue *q`: queue to update
- `struct queue_limits *lim`: limits to apply

**Description**

Apply the limits in **lim** that were freshly initialized to **q**.
To update existing limits use `queue_limits_start_update()` and
[`queue_limits_commit_update()`](#c-queue_limits_commit_update) instead.

Returns 0 if successful, else a negative error code.

#### <a id="c-blk_stack_limits"></a>`blk_stack_limits()`

```c
int blk_stack_limits(struct queue_limits *t, struct queue_limits *b, sector_t start)
```

adjust queue_limits for stacked devices

**Parameters**

- `struct queue_limits *t`: the stacking driver limits (top device)
- `struct queue_limits *b`: the underlying queue limits (bottom, component device)
- `sector_t start`: first data sector within component device

**Description**

This function is used by stacking drivers like MD and DM to ensure
that all component devices have compatible block sizes and
alignments.  The stacking driver must provide a queue_limits
struct (top) and then iteratively call the stacking function for
all component (bottom) devices.  The stacking function will
attempt to combine the values and ensure proper alignment.

Returns 0 if the top and bottom queue_limits are compatible.  The
top device's block sizes and alignment offsets may be adjusted to
ensure alignment with the bottom device. If no compatible sizes
and alignments exist, -1 is returned and the resulting top
queue_limits will have the misaligned flag set to indicate that
the alignment_offset is undefined.

#### <a id="c-queue_limits_stack_bdev"></a>`queue_limits_stack_bdev()`

```c
void queue_limits_stack_bdev(struct queue_limits *t, struct block_device *bdev, sector_t offset, const char *pfx)
```

adjust queue_limits for stacked devices

**Parameters**

- `struct queue_limits *t`: the stacking driver limits (top device)
- `struct block_device *bdev`: the underlying block device (bottom)
- `sector_t offset`: offset to beginning of data within component device
- `const char *pfx`: prefix to use for warnings logged

**Description**

This function is used by stacking drivers like MD and DM to ensure
that all component devices have compatible block sizes and
alignments.  The stacking driver must provide a queue_limits
struct (top) and then iteratively call the stacking function for
all component (bottom) devices.  The stacking function will
attempt to combine the values and ensure proper alignment.

#### <a id="c-queue_limits_stack_integrity"></a>`queue_limits_stack_integrity()`

```c
bool queue_limits_stack_integrity(struct queue_limits *t, struct queue_limits *b)
```

stack integrity profile

**Parameters**

- `struct queue_limits *t`: target queue limits
- `struct queue_limits *b`: base queue limits

**Description**

Check if the integrity profile in the **b** can be stacked into the
target **t**.  Stacking is possible if either:

a) does not have any integrity information stacked into it yet
b) the integrity profile in **b** is identical to the one in **t**

If **b** can be stacked into **t**, return `true`.  Else return `false` and clear the
integrity information in **t**.

#### <a id="c-blk_set_queue_depth"></a>`blk_set_queue_depth()`

```c
void blk_set_queue_depth(struct request_queue *q, unsigned int depth)
```

tell the block layer about the device queue depth

**Parameters**

- `struct request_queue *q`: the request queue for the device
- `unsigned int depth`: queue depth



#### <a id="c-blkdev_issue_flush"></a>`blkdev_issue_flush()`

```c
int blkdev_issue_flush(struct block_device *bdev)
```

queue a flush

**Parameters**

- `struct block_device *bdev`: blockdev to issue flush for

**Description**

Issue a flush for the block device in question.



#### <a id="c-blkdev_issue_discard"></a>`blkdev_issue_discard()`

```c
int blkdev_issue_discard(struct block_device *bdev, sector_t sector, sector_t nr_sects, gfp_t gfp_mask)
```

queue a discard

**Parameters**

- `struct block_device *bdev`: blockdev to issue discard for
- `sector_t sector`: start sector
- `sector_t nr_sects`: number of sectors to discard
- `gfp_t gfp_mask`: memory allocation flags (for bio_alloc)

**Description**

Issue a discard request for the sectors in question.

#### <a id="c-__blkdev_issue_zeroout"></a>`__blkdev_issue_zeroout()`

```c
int __blkdev_issue_zeroout(struct block_device *bdev, sector_t sector, sector_t nr_sects, gfp_t gfp_mask, struct bio **biop, unsigned flags)
```

generate number of zero filed write bios

**Parameters**

- `struct block_device *bdev`: blockdev to issue
- `sector_t sector`: start sector
- `sector_t nr_sects`: number of sectors to write
- `gfp_t gfp_mask`: memory allocation flags (for bio_alloc)
- `struct bio **biop`: pointer to anchor bio
- `unsigned flags`: controls detailed behavior

**Description**

Zero-fill a block range, either using hardware offload or by explicitly
writing zeroes to the device.

If a device is using logical block provisioning, the underlying space will
not be released if `flags` contains BLKDEV_ZERO_NOUNMAP.

If `flags` contains BLKDEV_ZERO_NOFALLBACK, the function will return
-EOPNOTSUPP if no explicit hardware offload for zeroing is provided.

#### <a id="c-blkdev_issue_zeroout"></a>`blkdev_issue_zeroout()`

```c
int blkdev_issue_zeroout(struct block_device *bdev, sector_t sector, sector_t nr_sects, gfp_t gfp_mask, unsigned flags)
```

zero-fill a block range

**Parameters**

- `struct block_device *bdev`: blockdev to write
- `sector_t sector`: start sector
- `sector_t nr_sects`: number of sectors to write
- `gfp_t gfp_mask`: memory allocation flags (for bio_alloc)
- `unsigned flags`: controls detailed behavior

**Description**

Zero-fill a block range, either using hardware offload or by explicitly
writing zeroes to the device.  See [`__blkdev_issue_zeroout()`](#c-__blkdev_issue_zeroout) for the
valid values for `flags`.






#### <a id="c-blk_trace_ioctl"></a>`blk_trace_ioctl()`

```c
int blk_trace_ioctl(struct block_device *bdev, unsigned cmd, char __user *arg)
```

handle the ioctls associated with tracing

**Parameters**

- `struct block_device *bdev`: the block device
- `unsigned cmd`: the ioctl cmd
- `char __user *arg`: the argument data, if any

#### <a id="c-blk_trace_shutdown"></a>`blk_trace_shutdown()`

```c
void blk_trace_shutdown(struct request_queue *q)
```

stop and cleanup trace structures

**Parameters**

- `struct request_queue *q`: the request queue associated with the device

#### <a id="c-blk_add_trace_rq"></a>`blk_add_trace_rq()`

```c
void blk_add_trace_rq(struct request *rq, blk_status_t error, unsigned int nr_bytes, u64 what, u64 cgid)
```

Add a trace for a request oriented action

**Parameters**

- `struct request *rq`: the source request
- `blk_status_t error`: return status to log
- `unsigned int nr_bytes`: number of completed bytes
- `u64 what`: the action
- `u64 cgid`: the cgroup info

**Description**

Records an action against a request. Will log the bio offset + size.

#### <a id="c-blk_add_trace_bio"></a>`blk_add_trace_bio()`

```c
void blk_add_trace_bio(struct request_queue *q, struct bio *bio, u64 what, int error)
```

Add a trace for a bio oriented action

**Parameters**

- `struct request_queue *q`: queue the io is for
- `struct bio *bio`: the source bio
- `u64 what`: the action
- `int error`: error, if any

**Description**

Records an action against a bio. Will log the bio offset + size.

#### <a id="c-blk_add_trace_bio_remap"></a>`blk_add_trace_bio_remap()`

```c
void blk_add_trace_bio_remap(void *ignore, struct bio *bio, dev_t dev, sector_t from)
```

Add a trace for a bio-remap operation

**Parameters**

- `void *ignore`: trace callback data parameter (not used)
- `struct bio *bio`: the source bio
- `dev_t dev`: source device
- `sector_t from`: source sector

**Description**

Called after a bio is remapped to a different device and/or sector.

#### <a id="c-blk_add_trace_rq_remap"></a>`blk_add_trace_rq_remap()`

```c
void blk_add_trace_rq_remap(void *ignore, struct request *rq, dev_t dev, sector_t from)
```

Add a trace for a request-remap operation

**Parameters**

- `void *ignore`: trace callback data parameter (not used)
- `struct request *rq`: the source request
- `dev_t dev`: target device
- `sector_t from`: source sector

**Description**

Device mapper remaps request to other devices.
Add a trace for that action.



#### <a id="c-disk_release"></a>`disk_release()`

```c
void disk_release(struct device *dev)
```

releases all allocated resources of the gendisk

**Parameters**

- `struct device *dev`: the device representing this disk

**Description**

This function releases all allocated resources of the gendisk.

Drivers which used [`device_add_disk()`](#c-device_add_disk) have a gendisk with a request_queue
assigned. Since the request_queue sits on top of the gendisk for these
drivers we also call [`blk_put_queue()`](#c-blk_put_queue) for them, and we expect the
request_queue refcount to reach 0 at this point, and so the request_queue
will also be freed prior to the disk.

**Context**

can sleep



#### <a id="c-bdev_count_inflight"></a>`bdev_count_inflight()`

```c
unsigned int bdev_count_inflight(struct block_device *part)
```

get the number of inflight IOs for a block device.

**Parameters**

- `struct block_device *part`: the block device.

**Description**

Inflight here means started IO accounting, from `bdev_start_io_acct()` for
bio-based block device, and from `blk_account_io_start()` for rq-based block
device.

#### <a id="c-__register_blkdev"></a>`__register_blkdev()`

```c
int __register_blkdev(unsigned int major, const char *name, void (*probe)(dev_t devt))
```

register a new block device

**Parameters**

- `unsigned int major`: the requested major device number \[1..BLKDEV_MAJOR_MAX-1\]. If
  **major** = 0, try to allocate any unused major number.
- `const char *name`: the name of the new block device as a zero terminated string
- `void (*probe)(dev_t devt)`: pre-devtmpfs / pre-udev callback used to create disks when their
  pre-created device node is accessed. When a probe call uses
  `add_disk()` and it fails the driver must cleanup resources. This
  interface may soon be removed.

**Description**

The **name** must be unique within the system.

The return value depends on the **major** input parameter:

- if a major device number was requested in range \[1..BLKDEV_MAJOR_MAX-1\]
  then the function returns zero on success, or a negative error code
- if any unused major number was requested with **major** = 0 parameter
  then the return value is the allocated major number in range
  \[1..BLKDEV_MAJOR_MAX-1\] or a negative error code otherwise

See Documentation/admin-guide/devices.txt for the list of allocated
major numbers.

Use register_blkdev instead for any new code.

#### <a id="c-add_disk_fwnode"></a>`add_disk_fwnode()`

```c
int add_disk_fwnode(struct device *parent, struct gendisk *disk, const struct attribute_group **groups, struct fwnode_handle *fwnode)
```

add disk information to kernel list with fwnode

**Parameters**

- `struct device *parent`: parent device for the disk
- `struct gendisk *disk`: per-device partitioning information
- `const struct attribute_group **groups`: Additional per-device sysfs groups
- `struct fwnode_handle *fwnode`: attached disk fwnode

**Description**

This function registers the partitioning information in **disk**
with the kernel. Also attach a fwnode to the disk device.

#### <a id="c-device_add_disk"></a>`device_add_disk()`

```c
int device_add_disk(struct device *parent, struct gendisk *disk, const struct attribute_group **groups)
```

add disk information to kernel list

**Parameters**

- `struct device *parent`: parent device for the disk
- `struct gendisk *disk`: per-device partitioning information
- `const struct attribute_group **groups`: Additional per-device sysfs groups

**Description**

This function registers the partitioning information in **disk**
with the kernel.

#### <a id="c-blk_mark_disk_dead"></a>`blk_mark_disk_dead()`

```c
void blk_mark_disk_dead(struct gendisk *disk)
```

mark a disk as dead

**Parameters**

- `struct gendisk *disk`: disk to mark as dead

**Description**

Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
to this disk.

#### <a id="c-del_gendisk"></a>`del_gendisk()`

```c
void del_gendisk(struct gendisk *disk)
```

remove the gendisk

**Parameters**

- `struct gendisk *disk`: the struct gendisk to remove

**Description**

Removes the gendisk and all its associated resources. This deletes the
partitions associated with the gendisk, and unregisters the associated
request_queue.

This is the counter to the respective [`device_add_disk()`](#c-device_add_disk) call.

The final removal of the struct gendisk happens when its refcount reaches 0
with [`put_disk()`](#c-put_disk), which should be called after [`del_gendisk()`](#c-del_gendisk), if
[`device_add_disk()`](#c-device_add_disk) was used.

Drivers exist which depend on the release of the gendisk to be synchronous,
it should not be deferred.

**Context**

can sleep

#### <a id="c-invalidate_disk"></a>`invalidate_disk()`

```c
void invalidate_disk(struct gendisk *disk)
```

invalidate the disk

**Parameters**

- `struct gendisk *disk`: the struct gendisk to invalidate

**Description**

A helper to invalidates the disk. It will clean the disk's associated
buffer/page caches and reset its internal states so that the disk
can be reused by the drivers.

**Context**

can sleep

#### <a id="c-put_disk"></a>`put_disk()`

```c
void put_disk(struct gendisk *disk)
```

decrements the gendisk refcount

**Parameters**

- `struct gendisk *disk`: the struct gendisk to decrement the refcount for

**Description**

This decrements the refcount for the struct gendisk. When this reaches 0
we'll have [`disk_release()`](#c-disk_release) called.

**Note**

for blk-mq disk put_disk must be called before freeing the tag_set
when handling probe errors (that is before `add_disk()` is called).

**Context**

Any context, but the last reference must not be dropped from
atomic context.

#### <a id="c-set_disk_ro"></a>`set_disk_ro()`

```c
void set_disk_ro(struct gendisk *disk, bool read_only)
```

set a gendisk read-only

**Parameters**

- `struct gendisk *disk`: gendisk to operate on
- `bool read_only`: `true` to set the disk read-only, `false` set the disk read/write

**Description**

This function is used to indicate whether a given disk device should have its
read-only flag set. [`set_disk_ro()`](#c-set_disk_ro) is typically used by device drivers to
indicate whether the underlying physical device is write-protected.



#### <a id="c-bdev_validate_blocksize"></a>`bdev_validate_blocksize()`

```c
int bdev_validate_blocksize(struct block_device *bdev, int block_size)
```

check that this block size is acceptable

**Parameters**

- `struct block_device *bdev`: blockdevice to check
- `int block_size`: block size to check

**Description**

For block device users that do not use buffer heads or the block device
page cache, make sure that this block size can be used with the device.

**Return**

On success zero is returned, negative error code on failure.

#### <a id="c-bdev_freeze"></a>`bdev_freeze()`

```c
int bdev_freeze(struct block_device *bdev)
```

lock a filesystem and force it into a consistent state

**Parameters**

- `struct block_device *bdev`: blockdevice to lock

**Description**

If a superblock is found on this device, we take the s_umount semaphore
on it to make sure nobody unmounts until the snapshot creation is done.
The reference counter (bd_fsfreeze_count) guarantees that only the last
unfreeze process can unfreeze the frozen filesystem actually when multiple
freeze requests arrive simultaneously. It counts up in [`bdev_freeze()`](#c-bdev_freeze) and
count down in [`bdev_thaw()`](#c-bdev_thaw). When it becomes 0, `thaw_bdev()` will unfreeze
actually.

**Return**

On success zero is returned, negative error code on failure.

#### <a id="c-bdev_thaw"></a>`bdev_thaw()`

```c
int bdev_thaw(struct block_device *bdev)
```

unlock filesystem

**Parameters**

- `struct block_device *bdev`: blockdevice to unlock

**Description**

Unlocks the filesystem and marks it writeable again after [`bdev_freeze()`](#c-bdev_freeze).

**Return**

On success zero is returned, negative error code on failure.

#### <a id="c-bd_prepare_to_claim"></a>`bd_prepare_to_claim()`

```c
int bd_prepare_to_claim(struct block_device *bdev, void *holder, const struct blk_holder_ops *hops)
```

claim a block device

**Parameters**

- `struct block_device *bdev`: block device of interest
- `void *holder`: holder trying to claim **bdev**
- `const struct blk_holder_ops *hops`: holder ops.

**Description**

Claim **bdev**.  This function fails if **bdev** is already claimed by another
holder and waits if another claiming is in progress. return, the caller
has ownership of bd_claiming and bd_holder\[s\].

**Return**

0 if **bdev** can be claimed, -EBUSY otherwise.

#### <a id="c-bd_abort_claiming"></a>`bd_abort_claiming()`

```c
void bd_abort_claiming(struct block_device *bdev, void *holder)
```

abort claiming of a block device

**Parameters**

- `struct block_device *bdev`: block device of interest
- `void *holder`: holder that has claimed **bdev**

**Description**

Abort claiming of a block device when the exclusive open failed. This can be
also used when exclusive open is not actually desired and we just needed
to block other exclusive openers for a while.

#### <a id="c-bdev_fput"></a>`bdev_fput()`

```c
void bdev_fput(struct file *bdev_file)
```

yield claim to the block device and put the file

**Parameters**

- `struct file *bdev_file`: open block device

**Description**

Yield claim on the block device and put the file. Ensure that the
block device can be reclaimed before the file is closed which is a
deferred operation.

#### <a id="c-lookup_bdev"></a>`lookup_bdev()`

```c
int lookup_bdev(const char *pathname, dev_t *dev)
```

Look up a struct block_device by name.

**Parameters**

- `const char *pathname`: Name of the block device in the filesystem.
- `dev_t *dev`: Pointer to the block device's dev_t, if found.

**Description**

Lookup the block device's dev_t at **pathname** in the current
namespace if possible and return it in **dev**.

**Context**

May sleep.

**Return**

0 if succeeded, negative errno otherwise.

#### <a id="c-bdev_mark_dead"></a>`bdev_mark_dead()`

```c
void bdev_mark_dead(struct block_device *bdev, bool surprise)
```

mark a block device as dead

**Parameters**

- `struct block_device *bdev`: block device to operate on
- `bool surprise`: indicate a surprise removal

**Description**

Tell the file system that this devices or media is dead.  If **surprise** is set
to `true` the device or media is already gone, if not we are preparing for an
orderly removal.

This calls into the file system, which then typicall syncs out all dirty data
and writes back inodes and then invalidates any cached data in the inodes on
the file system.  In addition we also invalidate the block device mapping.


<a id="rst-char-devices"></a>

## Char devices


#### <a id="c-register_chrdev_region"></a>`register_chrdev_region()`

```c
int register_chrdev_region(dev_t from, unsigned count, const char *name)
```

register a range of device numbers

**Parameters**

- `dev_t from`: the first in the desired range of device numbers; must include
  the major number.
- `unsigned count`: the number of consecutive device numbers required
- `const char *name`: the name of the device or driver.

**Description**

Return value is zero on success, a negative error code on failure.

#### <a id="c-alloc_chrdev_region"></a>`alloc_chrdev_region()`

```c
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
```

register a range of char device numbers

**Parameters**

- `dev_t *dev`: output parameter for first assigned number
- `unsigned baseminor`: first of the requested range of minor numbers
- `unsigned count`: the number of minor numbers required
- `const char *name`: the name of the associated device or driver

**Description**

Allocates a range of char device numbers.  The major number will be
chosen dynamically, and returned (along with the first minor number)
in **dev**.  Returns zero or a negative error code.

#### <a id="c-__register_chrdev"></a>`__register_chrdev()`

```c
int __register_chrdev(unsigned int major, unsigned int baseminor, unsigned int count, const char *name, const struct file_operations *fops)
```

create and register a cdev occupying a range of minors

**Parameters**

- `unsigned int major`: major device number or 0 for dynamic allocation
- `unsigned int baseminor`: first of the requested range of minor numbers
- `unsigned int count`: the number of minor numbers required
- `const char *name`: name of this range of devices
- `const struct file_operations *fops`: file operations associated with this devices

**Description**

If **major** == 0 this functions will dynamically allocate a major and return
its number.

If **major** > 0 this function will attempt to reserve a device with the given
major number and will return zero on success.

Returns a -ve errno on failure.

The name of this device has nothing to do with the name of the device in
/dev. It only helps to keep track of the different owners of devices. If
your module name has only one type of devices it's ok to use e.g. the name
of the module here.

#### <a id="c-unregister_chrdev_region"></a>`unregister_chrdev_region()`

```c
void unregister_chrdev_region(dev_t from, unsigned count)
```

unregister a range of device numbers

**Parameters**

- `dev_t from`: the first in the range of numbers to unregister
- `unsigned count`: the number of device numbers to unregister

**Description**

This function will unregister a range of **count** device numbers,
starting with **from**.  The caller should normally be the one who
allocated those numbers in the first place...

#### <a id="c-__unregister_chrdev"></a>`__unregister_chrdev()`

```c
void __unregister_chrdev(unsigned int major, unsigned int baseminor, unsigned int count, const char *name)
```

unregister and destroy a cdev

**Parameters**

- `unsigned int major`: major device number
- `unsigned int baseminor`: first of the range of minor numbers
- `unsigned int count`: the number of minor numbers this cdev is occupying
- `const char *name`: name of this range of devices

**Description**

Unregister and destroy the cdev occupying the region described by
**major**, **baseminor** and **count**.  This function undoes what
[`__register_chrdev()`](#c-__register_chrdev) did.

#### <a id="c-cdev_add"></a>`cdev_add()`

```c
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
```

add a char device to the system

**Parameters**

- `struct cdev *p`: the cdev structure for the device
- `dev_t dev`: the first device number for which this device is responsible
- `unsigned count`: the number of consecutive minor numbers corresponding to this
  device

**Description**

[`cdev_add()`](#c-cdev_add) adds the device represented by **p** to the system, making it
live immediately.  A negative error code is returned on failure.

#### <a id="c-cdev_set_parent"></a>`cdev_set_parent()`

```c
void cdev_set_parent(struct cdev *p, struct kobject *kobj)
```

set the parent kobject for a char device

**Parameters**

- `struct cdev *p`: the cdev structure
- `struct kobject *kobj`: the kobject to take a reference to

**Description**

[`cdev_set_parent()`](#c-cdev_set_parent) sets a parent kobject which will be referenced
appropriately so the parent is not freed before the cdev. This
should be called before cdev_add.

#### <a id="c-cdev_device_add"></a>`cdev_device_add()`

```c
int cdev_device_add(struct cdev *cdev, struct device *dev)
```

add a char device and it's corresponding struct device, linkink

**Parameters**

- `struct cdev *cdev`: the cdev structure
- `struct device *dev`: the device structure

**Description**

[`cdev_device_add()`](#c-cdev_device_add) adds the char device represented by **cdev** to the system,
just as cdev_add does. It then adds **dev** to the system using device_add
The dev_t for the char device will be taken from the struct device which
needs to be initialized first. This helper function correctly takes a
reference to the parent device so the parent will not get released until
all references to the cdev are released.

This helper uses dev->devt for the device number. If it is not set
it will not add the cdev and it will be equivalent to device_add.

This function should be used whenever the struct cdev and the
struct device are members of the same structure whose lifetime is
managed by the struct device.

**NOTE**

Callers must assume that userspace was able to open the cdev and
can call cdev fops callbacks at any time, even if this function fails.

#### <a id="c-cdev_device_del"></a>`cdev_device_del()`

```c
void cdev_device_del(struct cdev *cdev, struct device *dev)
```

inverse of cdev_device_add

**Parameters**

- `struct cdev *cdev`: the cdev structure
- `struct device *dev`: the device structure

**Description**

[`cdev_device_del()`](#c-cdev_device_del) is a helper function to call cdev_del and device_del.
It should be used whenever cdev_device_add is used.

If dev->devt is not set it will not remove the cdev and will be equivalent
to device_del.

**NOTE**

This guarantees that associated sysfs callbacks are not running
or runnable, however any cdevs already open will remain and their fops
will still be callable even after this function returns.

#### <a id="c-cdev_del"></a>`cdev_del()`

```c
void cdev_del(struct cdev *p)
```

remove a cdev from the system

**Parameters**

- `struct cdev *p`: the cdev structure to be removed

**Description**

[`cdev_del()`](#c-cdev_del) removes **p** from the system, possibly freeing the structure
itself.

**NOTE**

This guarantees that cdev device will no longer be able to be
opened, however any cdevs already open will remain and their fops will
still be callable even after cdev_del returns.

#### <a id="c-cdev_alloc"></a>`cdev_alloc()`

```c
struct cdev * cdev_alloc(void)
```

allocate a cdev structure

**Parameters**

- `void`: no arguments

**Description**

Allocates and returns a cdev structure, or NULL on failure.

#### <a id="c-cdev_init"></a>`cdev_init()`

```c
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
```

initialize a cdev structure

**Parameters**

- `struct cdev *cdev`: the structure to initialize
- `const struct file_operations *fops`: the file_operations for this device

**Description**

Initializes **cdev**, remembering **fops**, making it ready to add to the
system with [`cdev_add()`](#c-cdev_add).


<a id="rst-clock-framework"></a>

## Clock Framework

The clock framework defines programming interfaces to support software management of the system clock tree. This framework is widely used with System-On-Chip (SOC) platforms to support power management and various devices which may need custom clock rates. Note that these "clocks" don't relate to timekeeping or real time clocks (RTCs), each of which have separate frameworks. These `struct clk <clk>` instances may be used to manage for example a 96 MHz signal that is used to shift bits into and out of peripherals or busses, or otherwise trigger synchronous state machine transitions in system hardware.

Power management is supported by explicit software clock gating: unused clocks are disabled, so the system doesn't waste power changing the state of transistors that aren't in active use. On some systems this may be backed by hardware clock gating, where clocks are gated without being disabled in software. Sections of chips that are powered but not clocked may be able to retain their last state. This low power state is often called a *retention mode*. This mode still incurs leakage currents, especially with finer circuit geometries, but for CMOS circuits power is mostly used by clocked state changes.

Power-aware drivers only enable their clocks when the device they manage is in active use. Also, system sleep states often differ according to which clock domains are active: while a "standby" state may allow wakeup from several active domains, a "mem" (suspend-to-RAM) state may require a more wholesale shutdown of clocks derived from higher speed PLLs and oscillators, limiting the number of possible wakeup event sources. A driver's suspend method may need to be aware of system-specific clock constraints on the target sleep state.

Some platforms support programmable clock generators. These can be used by external chips of various kinds, such as other CPUs, multimedia codecs, and devices with strict requirements for interface clocking.


#### <a id="c-struct-clk_notifier"></a>`struct clk_notifier`

associate a clk with a notifier

**Definition**

```c
struct clk_notifier {
    struct clk                      *clk;
    struct srcu_notifier_head       notifier_head;
    struct list_head                node;
};
```

**Members**

- `clk`: struct clk * to associate the notifier with
- `notifier_head`: a blocking_notifier_head for this clk
- `node`: linked list pointers

**Description**

A list of struct clk_notifier is maintained by the notifier code.
An entry is created whenever code registers the first notifier on a
particular **clk**.  Future notifiers on that **clk** are added to the
**notifier_head**.

#### <a id="c-struct-clk_notifier_data"></a>`struct clk_notifier_data`

rate data to pass to the notifier callback

**Definition**

```c
struct clk_notifier_data {
    struct clk              *clk;
    unsigned long           old_rate;
    unsigned long           new_rate;
};
```

**Members**

- `clk`: struct clk * being changed
- `old_rate`: previous rate of this clk
- `new_rate`: new rate of this clk

**Description**

For a pre-notifier, old_rate is the clk's rate before this rate
change, and new_rate is what the rate will be in the future.  For a
post-notifier, old_rate and new_rate are both set to the clk's
current rate (this was done to optimize the implementation).

#### <a id="c-struct-clk_bulk_data"></a>`struct clk_bulk_data`

Data used for bulk clk operations.

**Definition**

```c
struct clk_bulk_data {
    const char              *id;
    struct clk              *clk;
};
```

**Members**

- `id`: clock consumer ID
- `clk`: struct clk * to store the associated clock

**Description**

The CLK APIs provide a series of `clk_bulk_()` API calls as
a convenience to consumers which require multiple clks.  This
structure is used to manage data for these calls.

#### <a id="c-clk_notifier_register"></a>`clk_notifier_register()`

```c
int clk_notifier_register(struct clk *clk, struct notifier_block *nb)
```

register a clock rate-change notifier callback

**Parameters**

- `struct clk *clk`: clock whose rate we are interested in
- `struct notifier_block *nb`: notifier block with callback function pointer

**Description**

ProTip: debugging across notifier chains can be frustrating. Make sure that
your notifier callback function prints a nice big warning in case of
failure.

#### <a id="c-clk_notifier_unregister"></a>`clk_notifier_unregister()`

```c
int clk_notifier_unregister(struct clk *clk, struct notifier_block *nb)
```

unregister a clock rate-change notifier callback

**Parameters**

- `struct clk *clk`: clock whose rate we are no longer interested in
- `struct notifier_block *nb`: notifier block which will be unregistered

#### <a id="c-devm_clk_notifier_register"></a>`devm_clk_notifier_register()`

```c
int devm_clk_notifier_register(struct device *dev, struct clk *clk, struct notifier_block *nb)
```

register a managed rate-change notifier callback

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `struct clk *clk`: clock whose rate we are interested in
- `struct notifier_block *nb`: notifier block with callback function pointer

**Description**

Returns 0 on success, -EERROR otherwise

#### <a id="c-clk_get_accuracy"></a>`clk_get_accuracy()`

```c
long clk_get_accuracy(struct clk *clk)
```

obtain the clock accuracy in ppb (parts per billion) for a clock source.

**Parameters**

- `struct clk *clk`: clock source

**Description**

This gets the clock source accuracy expressed in ppb.
A perfect clock returns 0.

#### <a id="c-clk_set_phase"></a>`clk_set_phase()`

```c
int clk_set_phase(struct clk *clk, int degrees)
```

adjust the phase shift of a clock signal

**Parameters**

- `struct clk *clk`: clock signal source
- `int degrees`: number of degrees the signal is shifted

**Description**

Shifts the phase of a clock signal by the specified degrees. Returns 0 on
success, -EERROR otherwise.

#### <a id="c-clk_get_phase"></a>`clk_get_phase()`

```c
int clk_get_phase(struct clk *clk)
```

return the phase shift of a clock signal

**Parameters**

- `struct clk *clk`: clock signal source

**Description**

Returns the phase shift of a clock node in degrees, otherwise returns
-EERROR.

#### <a id="c-clk_set_duty_cycle"></a>`clk_set_duty_cycle()`

```c
int clk_set_duty_cycle(struct clk *clk, unsigned int num, unsigned int den)
```

adjust the duty cycle ratio of a clock signal

**Parameters**

- `struct clk *clk`: clock signal source
- `unsigned int num`: numerator of the duty cycle ratio to be applied
- `unsigned int den`: denominator of the duty cycle ratio to be applied

**Description**

Adjust the duty cycle of a clock signal by the specified ratio. Returns 0 on
success, -EERROR otherwise.

#### <a id="c-clk_get_scaled_duty_cycle"></a>`clk_get_scaled_duty_cycle()`

```c
int clk_get_scaled_duty_cycle(struct clk *clk, unsigned int scale)
```

return the duty cycle ratio of a clock signal

**Parameters**

- `struct clk *clk`: clock signal source
- `unsigned int scale`: scaling factor to be applied to represent the ratio as an integer

**Description**

Returns the duty cycle ratio multiplied by the scale provided, otherwise
returns -EERROR.

#### <a id="c-clk_is_match"></a>`clk_is_match()`

```c
bool clk_is_match(const struct clk *p, const struct clk *q)
```

check if two clk's point to the same hardware clock

**Parameters**

- `const struct clk *p`: clk compared against q
- `const struct clk *q`: clk compared against p

**Description**

Returns true if the two struct clk pointers both point to the same hardware
clock node. Put differently, returns true if **p** and **q**
share the same `struct clk_core` object.

Returns false otherwise. Note that two NULL clks are treated as matching.

#### <a id="c-clk_rate_exclusive_get"></a>`clk_rate_exclusive_get()`

```c
int clk_rate_exclusive_get(struct clk *clk)
```

get exclusivity over the rate control of a producer

**Parameters**

- `struct clk *clk`: clock source

**Description**

This function allows drivers to get exclusive control over the rate of a
provider. It prevents any other consumer to execute, even indirectly,
opereation which could alter the rate of the provider or cause glitches

If exlusivity is claimed more than once on clock, even by the same driver,
the rate effectively gets locked as exclusivity can't be preempted.

Must not be called from within atomic context.

Returns success (0) or negative errno.

#### <a id="c-devm_clk_rate_exclusive_get"></a>`devm_clk_rate_exclusive_get()`

```c
int devm_clk_rate_exclusive_get(struct device *dev, struct clk *clk)
```

devm variant of clk_rate_exclusive_get

**Parameters**

- `struct device *dev`: device the exclusivity is bound to
- `struct clk *clk`: clock source

**Description**

Calls [`clk_rate_exclusive_get()`](#c-clk_rate_exclusive_get) on **clk** and registers a devm cleanup handler
on **dev** to call [`clk_rate_exclusive_put()`](#c-clk_rate_exclusive_put).

Must not be called from within atomic context.

#### <a id="c-clk_rate_exclusive_put"></a>`clk_rate_exclusive_put()`

```c
void clk_rate_exclusive_put(struct clk *clk)
```

release exclusivity over the rate control of a producer

**Parameters**

- `struct clk *clk`: clock source

**Description**

This function allows drivers to release the exclusivity it previously got
from [`clk_rate_exclusive_get()`](#c-clk_rate_exclusive_get)

The caller must balance the number of [`clk_rate_exclusive_get()`](#c-clk_rate_exclusive_get) and
[`clk_rate_exclusive_put()`](#c-clk_rate_exclusive_put) calls.

Must not be called from within atomic context.

#### <a id="c-clk_save_context"></a>`clk_save_context()`

```c
int clk_save_context(void)
```

save clock context for poweroff

**Parameters**

- `void`: no arguments

**Description**

Saves the context of the clock register for powerstates in which the
contents of the registers will be lost. Occurs deep within the suspend
code so locking is not necessary.

#### <a id="c-clk_restore_context"></a>`clk_restore_context()`

```c
void clk_restore_context(void)
```

restore clock context after poweroff

**Parameters**

- `void`: no arguments

**Description**

This occurs with all clocks enabled. Occurs deep within the resume code
so locking is not necessary.

#### <a id="c-clk_prepare"></a>`clk_prepare()`

```c
int clk_prepare(struct clk *clk)
```

prepare a clock source

**Parameters**

- `struct clk *clk`: clock source

**Description**

This prepares the clock source for use.

Must not be called from within atomic context.

#### <a id="c-clk_unprepare"></a>`clk_unprepare()`

```c
void clk_unprepare(struct clk *clk)
```

undo preparation of a clock source

**Parameters**

- `struct clk *clk`: clock source

**Description**

This undoes a previously prepared clock.  The caller must balance
the number of prepare and unprepare calls.

Must not be called from within atomic context.

#### <a id="c-clk_is_enabled_when_prepared"></a>`clk_is_enabled_when_prepared()`

```c
bool clk_is_enabled_when_prepared(struct clk *clk)
```

indicate if preparing a clock also enables it.

**Parameters**

- `struct clk *clk`: clock source

**Description**

Returns true if [`clk_prepare()`](#c-clk_prepare) implicitly enables the clock, effectively
making [`clk_enable()`](#c-clk_enable)/[`clk_disable()`](#c-clk_disable) no-ops, false otherwise.

This is of interest mainly to the power management code where actually
disabling the clock also requires unpreparing it to have any material
effect.

Regardless of the value returned here, the caller must always invoke
[`clk_enable()`](#c-clk_enable) or `clk_prepare_enable()`  and counterparts for usage counts
to be right.

#### <a id="c-clk_get"></a>`clk_get()`

```c
struct clk * clk_get(struct device *dev, const char *id)
```

lookup and obtain a reference to a clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Description**

Returns a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  (IOW, **id** may be identical strings, but
clk_get may return different clock producers depending on **dev**.)

Drivers must assume that the clock source is not enabled.

clk_get should not be called from within interrupt context.

#### <a id="c-clk_bulk_get"></a>`clk_bulk_get()`

```c
int clk_bulk_get(struct device *dev, int num_clks, struct clk_bulk_data *clks)
```

lookup and obtain a number of references to clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Description**

This helper function allows drivers to get several clk consumers in one
operation. If any of the clk cannot be acquired then any clks
that were obtained will be freed before returning to the caller.

Returns 0 if all clocks specified in clk_bulk_data table are obtained
successfully, or valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.
The implementation uses **dev** and **clk_bulk_data.id** to determine the
clock consumer, and thereby the clock producer.
The clock returned is stored in each **clk_bulk_data.clk** field.

Drivers must assume that the clock source is not enabled.

clk_bulk_get should not be called from within interrupt context.

#### <a id="c-clk_bulk_get_all"></a>`clk_bulk_get_all()`

```c
int clk_bulk_get_all(struct device *dev, struct clk_bulk_data **clks)
```

lookup and obtain all available references to clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `struct clk_bulk_data **clks`: pointer to the clk_bulk_data table of consumer

**Description**

This helper function allows drivers to get all clk consumers in one
operation. If any of the clk cannot be acquired then any clks
that were obtained will be freed before returning to the caller.

Returns a positive value for the number of clocks obtained while the
clock references are stored in the clk_bulk_data table in **clks** field.
Returns 0 if there're none and a negative value if something failed.

Drivers must assume that the clock source is not enabled.

clk_bulk_get should not be called from within interrupt context.

#### <a id="c-clk_bulk_get_optional"></a>`clk_bulk_get_optional()`

```c
int clk_bulk_get_optional(struct device *dev, int num_clks, struct clk_bulk_data *clks)
```

lookup and obtain a number of references to clock producer

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Description**

Behaves the same as [`clk_bulk_get()`](#c-clk_bulk_get) except where there is no clock producer.
In this case, instead of returning -ENOENT, the function returns 0 and
NULL for a clk for which a clock producer could not be determined.

#### <a id="c-devm_clk_bulk_get"></a>`devm_clk_bulk_get()`

```c
int devm_clk_bulk_get(struct device *dev, int num_clks, struct clk_bulk_data *clks)
```

managed get multiple clk consumers

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Description**

Return 0 on success, an errno on failure.

This helper function allows drivers to get several clk
consumers in one operation with management, the clks will
automatically be freed when the device is unbound.

#### <a id="c-devm_clk_bulk_get_optional"></a>`devm_clk_bulk_get_optional()`

```c
int devm_clk_bulk_get_optional(struct device *dev, int num_clks, struct clk_bulk_data *clks)
```

managed get multiple optional consumer clocks

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: pointer to the clk_bulk_data table of consumer

**Description**

Behaves the same as [`devm_clk_bulk_get()`](#c-devm_clk_bulk_get) except where there is no clock
producer.  In this case, instead of returning -ENOENT, the function returns
NULL for given clk. It is assumed all clocks in clk_bulk_data are optional.

Returns 0 if all clocks specified in clk_bulk_data table are obtained
successfully or for any clk there was no clk provider available, otherwise
returns valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.
The implementation uses **dev** and **clk_bulk_data.id** to determine the
clock consumer, and thereby the clock producer.
The clock returned is stored in each **clk_bulk_data.clk** field.

Drivers must assume that the clock source is not enabled.

clk_bulk_get should not be called from within interrupt context.

#### <a id="c-devm_clk_bulk_get_optional_enable"></a>`devm_clk_bulk_get_optional_enable()`

```c
int devm_clk_bulk_get_optional_enable(struct device *dev, int num_clks, struct clk_bulk_data *clks)
```

Get and enable optional bulk clocks (managed)

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: pointer to the clk_bulk_data table of consumer

**Description**

Behaves the same as [`devm_clk_bulk_get_optional()`](#c-devm_clk_bulk_get_optional) but also prepares and enables
the clocks in one operation with management. The clks will automatically be
disabled, unprepared and freed when the device is unbound.

**Return**

0 if all clocks specified in clk_bulk_data table are obtained
and enabled successfully, or for any clk there was no clk provider available.
Otherwise returns valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.

#### <a id="c-devm_clk_bulk_get_all"></a>`devm_clk_bulk_get_all()`

```c
int devm_clk_bulk_get_all(struct device *dev, struct clk_bulk_data **clks)
```

managed get multiple clk consumers

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `struct clk_bulk_data **clks`: pointer to the clk_bulk_data table of consumer

**Description**

Returns a positive value for the number of clocks obtained while the
clock references are stored in the clk_bulk_data table in **clks** field.
Returns 0 if there're none and a negative value if something failed.

This helper function allows drivers to get several clk
consumers in one operation with management, the clks will
automatically be freed when the device is unbound.

#### <a id="c-devm_clk_bulk_get_all_enabled"></a>`devm_clk_bulk_get_all_enabled()`

```c
int devm_clk_bulk_get_all_enabled(struct device *dev, struct clk_bulk_data **clks)
```

Get and enable all clocks of the consumer (managed)

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `struct clk_bulk_data **clks`: pointer to the clk_bulk_data table of consumer

**Description**

Returns a positive value for the number of clocks obtained while the
clock references are stored in the clk_bulk_data table in **clks** field.
Returns 0 if there're none and a negative value if something failed.

This helper function allows drivers to get all clocks of the
consumer and enables them in one operation with management.
The clks will automatically be disabled and freed when the device
is unbound.

#### <a id="c-devm_clk_get"></a>`devm_clk_get()`

```c
struct clk * devm_clk_get(struct device *dev, const char *id)
```

lookup and obtain a managed reference to a clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  (IOW, **id** may be identical strings, but
clk_get may return different clock producers depending on **dev**.)

**Description**

Drivers must assume that the clock source is neither prepared nor
enabled.

The clock will automatically be freed when the device is unbound
from the bus.

#### <a id="c-devm_clk_get_prepared"></a>`devm_clk_get_prepared()`

```c
struct clk * devm_clk_get_prepared(struct device *dev, const char *id)
```

[`devm_clk_get()`](#c-devm_clk_get) + [`clk_prepare()`](#c-clk_prepare)

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  (IOW, **id** may be identical strings, but
clk_get may return different clock producers depending on **dev**.)

**Description**

The returned clk (if valid) is prepared. Drivers must however assume
that the clock is not enabled.

The clock will automatically be unprepared and freed when the device
is unbound from the bus.

#### <a id="c-devm_clk_get_enabled"></a>`devm_clk_get_enabled()`

```c
struct clk * devm_clk_get_enabled(struct device *dev, const char *id)
```

[`devm_clk_get()`](#c-devm_clk_get) + `clk_prepare_enable()`

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  (IOW, **id** may be identical strings, but
clk_get may return different clock producers depending on **dev**.)

**Description**

The returned clk (if valid) is prepared and enabled.

The clock will automatically be disabled, unprepared and freed
when the device is unbound from the bus.

#### <a id="c-devm_clk_get_optional"></a>`devm_clk_get_optional()`

```c
struct clk * devm_clk_get_optional(struct device *dev, const char *id)
```

lookup and obtain a managed reference to an optional clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  If no such clk is found, it returns NULL
which serves as a dummy clk.  That's the only difference compared
to [`devm_clk_get()`](#c-devm_clk_get).

**Description**

Drivers must assume that the clock source is neither prepared nor
enabled.

The clock will automatically be freed when the device is unbound
from the bus.

#### <a id="c-devm_clk_get_optional_prepared"></a>`devm_clk_get_optional_prepared()`

```c
struct clk * devm_clk_get_optional_prepared(struct device *dev, const char *id)
```

[`devm_clk_get_optional()`](#c-devm_clk_get_optional) + [`clk_prepare()`](#c-clk_prepare)

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  If no such clk is found, it returns NULL
which serves as a dummy clk.  That's the only difference compared
to [`devm_clk_get_prepared()`](#c-devm_clk_get_prepared).

**Description**

The returned clk (if valid) is prepared. Drivers must however
assume that the clock is not enabled.

The clock will automatically be unprepared and freed when the
device is unbound from the bus.

#### <a id="c-devm_clk_get_optional_enabled"></a>`devm_clk_get_optional_enabled()`

```c
struct clk * devm_clk_get_optional_enabled(struct device *dev, const char *id)
```

[`devm_clk_get_optional()`](#c-devm_clk_get_optional) + `clk_prepare_enable()`

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  If no such clk is found, it returns NULL
which serves as a dummy clk.  That's the only difference compared
to [`devm_clk_get_enabled()`](#c-devm_clk_get_enabled).

**Description**

The returned clk (if valid) is prepared and enabled.

The clock will automatically be disabled, unprepared and freed
when the device is unbound from the bus.

#### <a id="c-devm_clk_get_optional_enabled_with_rate"></a>`devm_clk_get_optional_enabled_with_rate()`

```c
struct clk * devm_clk_get_optional_enabled_with_rate(struct device *dev, const char *id, unsigned long rate)
```

[`devm_clk_get_optional()`](#c-devm_clk_get_optional) + [`clk_set_rate()`](#c-clk_set_rate) + `clk_prepare_enable()`

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID
- `unsigned long rate`: new clock rate

**Context**

May sleep.

**Return**

a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev** and **id** to determine the clock consumer, and thereby
the clock producer.  If no such clk is found, it returns NULL
which serves as a dummy clk.  That's the only difference compared
to [`devm_clk_get_enabled()`](#c-devm_clk_get_enabled).

**Description**

The returned clk (if valid) is prepared and enabled and rate was set.

The clock will automatically be disabled, unprepared and freed
when the device is unbound from the bus.

#### <a id="c-devm_get_clk_from_child"></a>`devm_get_clk_from_child()`

```c
struct clk * devm_get_clk_from_child(struct device *dev, struct device_node *np, const char *con_id)
```

lookup and obtain a managed reference to a clock producer from child node.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `struct device_node *np`: pointer to clock consumer node
- `const char *con_id`: clock consumer ID

**Description**

This function parses the clocks, and uses them to look up the
struct clk from the registered list of clock providers by using
**np** and **con_id**

The clock will automatically be freed when the device is unbound
from the bus.

#### <a id="c-clk_enable"></a>`clk_enable()`

```c
int clk_enable(struct clk *clk)
```

inform the system when the clock source should be running.

**Parameters**

- `struct clk *clk`: clock source

**Description**

If the clock can not be enabled/disabled, this should return success.

May be called from atomic contexts.

Returns success (0) or negative errno.

#### <a id="c-clk_bulk_enable"></a>`clk_bulk_enable()`

```c
int clk_bulk_enable(int num_clks, const struct clk_bulk_data *clks)
```

inform the system when the set of clks should be running.

**Parameters**

- `int num_clks`: the number of clk_bulk_data
- `const struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Description**

May be called from atomic contexts.

Returns success (0) or negative errno.

#### <a id="c-clk_disable"></a>`clk_disable()`

```c
void clk_disable(struct clk *clk)
```

inform the system when the clock source is no longer required.

**Parameters**

- `struct clk *clk`: clock source

**Description**

Inform the system that a clock source is no longer required by
a driver and may be shut down.

May be called from atomic contexts.

Implementation detail: if the clock source is shared between
multiple drivers, [`clk_enable()`](#c-clk_enable) calls must be balanced by the
same number of [`clk_disable()`](#c-clk_disable) calls for the clock source to be
disabled.

#### <a id="c-clk_bulk_disable"></a>`clk_bulk_disable()`

```c
void clk_bulk_disable(int num_clks, const struct clk_bulk_data *clks)
```

inform the system when the set of clks is no longer required.

**Parameters**

- `int num_clks`: the number of clk_bulk_data
- `const struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Description**

Inform the system that a set of clks is no longer required by
a driver and may be shut down.

May be called from atomic contexts.

Implementation detail: if the set of clks is shared between
multiple drivers, [`clk_bulk_enable()`](#c-clk_bulk_enable) calls must be balanced by the
same number of [`clk_bulk_disable()`](#c-clk_bulk_disable) calls for the clock source to be
disabled.

#### <a id="c-clk_get_rate"></a>`clk_get_rate()`

```c
unsigned long clk_get_rate(struct clk *clk)
```

obtain the current clock rate (in Hz) for a clock source. This is only valid once the clock source has been enabled.

**Parameters**

- `struct clk *clk`: clock source

#### <a id="c-clk_put"></a>`clk_put()`

```c
void clk_put(struct clk *clk)
```

"free" the clock source

**Parameters**

- `struct clk *clk`: clock source

**Note**

drivers must ensure that all clk_enable calls made on this
clock source are balanced by clk_disable calls prior to calling
this function.

clk_put should not be called from within interrupt context.

#### <a id="c-clk_bulk_put"></a>`clk_bulk_put()`

```c
void clk_bulk_put(int num_clks, struct clk_bulk_data *clks)
```

"free" the clock source

**Parameters**

- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Note**

drivers must ensure that all clk_bulk_enable calls made on this
clock source are balanced by clk_bulk_disable calls prior to calling
this function.

clk_bulk_put should not be called from within interrupt context.

#### <a id="c-clk_bulk_put_all"></a>`clk_bulk_put_all()`

```c
void clk_bulk_put_all(int num_clks, struct clk_bulk_data *clks)
```

"free" all the clock source

**Parameters**

- `int num_clks`: the number of clk_bulk_data
- `struct clk_bulk_data *clks`: the clk_bulk_data table of consumer

**Note**

drivers must ensure that all clk_bulk_enable calls made on this
clock source are balanced by clk_bulk_disable calls prior to calling
this function.

clk_bulk_put_all should not be called from within interrupt context.

#### <a id="c-devm_clk_put"></a>`devm_clk_put()`

```c
void devm_clk_put(struct device *dev, struct clk *clk)
```

"free" a managed clock source

**Parameters**

- `struct device *dev`: device used to acquire the clock
- `struct clk *clk`: clock source acquired with [`devm_clk_get()`](#c-devm_clk_get)

**Note**

drivers must ensure that all clk_enable calls made on this
clock source are balanced by clk_disable calls prior to calling
this function.

clk_put should not be called from within interrupt context.

#### <a id="c-clk_round_rate"></a>`clk_round_rate()`

```c
long clk_round_rate(struct clk *clk, unsigned long rate)
```

adjust a rate to the exact rate a clock can provide

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long rate`: desired clock rate in Hz

**Description**

This answers the question "if I were to pass **rate** to [`clk_set_rate()`](#c-clk_set_rate),
what clock rate would I end up with?" without changing the hardware
in any way.  In other words:

rate = clk_round_rate(clk, r);

and:

clk_set_rate(clk, r);
rate = clk_get_rate(clk);

are equivalent except the former does not modify the clock hardware
in any way.

Returns rounded clock rate in Hz, or negative errno.

#### <a id="c-clk_set_rate"></a>`clk_set_rate()`

```c
int clk_set_rate(struct clk *clk, unsigned long rate)
```

set the clock rate for a clock source

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long rate`: desired clock rate in Hz

**Description**

Updating the rate starts at the top-most affected clock and then
walks the tree down to the bottom-most clock that needs updating.

Returns success (0) or negative errno.

#### <a id="c-clk_set_rate_exclusive"></a>`clk_set_rate_exclusive()`

```c
int clk_set_rate_exclusive(struct clk *clk, unsigned long rate)
```

set the clock rate and claim exclusivity over clock source

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long rate`: desired clock rate in Hz

**Description**

This helper function allows drivers to atomically set the rate of a producer
and claim exclusivity over the rate control of the producer.

It is essentially a combination of [`clk_set_rate()`](#c-clk_set_rate) and
`clk_rate_exclusite_get()`. Caller must balance this call with a call to
[`clk_rate_exclusive_put()`](#c-clk_rate_exclusive_put)

Returns success (0) or negative errno.

#### <a id="c-clk_has_parent"></a>`clk_has_parent()`

```c
bool clk_has_parent(const struct clk *clk, const struct clk *parent)
```

check if a clock is a possible parent for another

**Parameters**

- `const struct clk *clk`: clock source
- `const struct clk *parent`: parent clock source

**Description**

This function can be used in drivers that need to check that a clock can be
the parent of another without actually changing the parent.

Returns true if **parent** is a possible parent for **clk**, false otherwise.

#### <a id="c-clk_set_rate_range"></a>`clk_set_rate_range()`

```c
int clk_set_rate_range(struct clk *clk, unsigned long min, unsigned long max)
```

set a rate range for a clock source

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long min`: desired minimum clock rate in Hz, inclusive
- `unsigned long max`: desired maximum clock rate in Hz, inclusive

**Description**

Returns success (0) or negative errno.

#### <a id="c-clk_set_min_rate"></a>`clk_set_min_rate()`

```c
int clk_set_min_rate(struct clk *clk, unsigned long rate)
```

set a minimum clock rate for a clock source

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long rate`: desired minimum clock rate in Hz, inclusive

**Description**

Returns success (0) or negative errno.

#### <a id="c-clk_set_max_rate"></a>`clk_set_max_rate()`

```c
int clk_set_max_rate(struct clk *clk, unsigned long rate)
```

set a maximum clock rate for a clock source

**Parameters**

- `struct clk *clk`: clock source
- `unsigned long rate`: desired maximum clock rate in Hz, inclusive

**Description**

Returns success (0) or negative errno.

#### <a id="c-clk_set_parent"></a>`clk_set_parent()`

```c
int clk_set_parent(struct clk *clk, struct clk *parent)
```

set the parent clock source for this clock

**Parameters**

- `struct clk *clk`: clock source
- `struct clk *parent`: parent clock source

**Description**

Returns success (0) or negative errno.

#### <a id="c-clk_get_parent"></a>`clk_get_parent()`

```c
struct clk * clk_get_parent(struct clk *clk)
```

get the parent clock source for this clock

**Parameters**

- `struct clk *clk`: clock source

**Description**

Returns struct clk corresponding to parent clock source, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.

#### <a id="c-clk_get_sys"></a>`clk_get_sys()`

```c
struct clk * clk_get_sys(const char *dev_id, const char *con_id)
```

get a clock based upon the device name

**Parameters**

- `const char *dev_id`: device name
- `const char *con_id`: connection ID

**Description**

Returns a struct clk corresponding to the clock producer, or
valid [`IS_ERR()`](#c-IS_ERR) condition containing errno.  The implementation
uses **dev_id** and **con_id** to determine the clock consumer, and
thereby the clock producer. In contrast to [`clk_get()`](#c-clk_get) this function
takes the device name instead of the device itself for identification.

Drivers must assume that the clock source is not enabled.

clk_get_sys should not be called from within interrupt context.

#### <a id="c-clk_drop_range"></a>`clk_drop_range()`

```c
int clk_drop_range(struct clk *clk)
```

Reset any range set on that clock

**Parameters**

- `struct clk *clk`: clock source

**Description**

Returns success (0) or negative errno.

#### <a id="c-clk_get_optional"></a>`clk_get_optional()`

```c
struct clk * clk_get_optional(struct device *dev, const char *id)
```

lookup and obtain a reference to an optional clock producer.

**Parameters**

- `struct device *dev`: device for clock "consumer"
- `const char *id`: clock consumer ID

**Description**

Behaves the same as [`clk_get()`](#c-clk_get) except where there is no clock producer. In
this case, instead of returning -ENOENT, the function returns NULL.


<a id="rst-synchronization-primitives"></a>

## Synchronization Primitives

<a id="rst-read-copy-update-rcu"></a>

### Read-Copy Update (RCU)


#### <a id="c-same_state_synchronize_rcu"></a>`same_state_synchronize_rcu()`

```c
bool same_state_synchronize_rcu(unsigned long oldstate1, unsigned long oldstate2)
```

Are two old-state values identical?

**Parameters**

- `unsigned long oldstate1`: First old-state value.
- `unsigned long oldstate2`: Second old-state value.

**Description**

The two old-state values must have been obtained from either
[`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu), [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu), or
[`get_completed_synchronize_rcu()`](#c-get_completed_synchronize_rcu).  Returns **true** if the two values are
identical and **false** otherwise.  This allows structures whose lifetimes
are tracked by old-state values to push these values to a list header,
allowing those structures to be slightly smaller.

#### <a id="c-rcu_trace_implies_rcu_gp"></a>`rcu_trace_implies_rcu_gp()`

```c
bool rcu_trace_implies_rcu_gp(void)
```

does an RCU Tasks Trace grace period imply an RCU grace period?

**Parameters**

- `void`: no arguments

**Description**

As an accident of implementation, an RCU Tasks Trace grace period also
acts as an RCU grace period.  However, this could change at any time.
Code relying on this accident must call this function to verify that
this accident is still happening.

You have been warned!

#### <a id="c-cond_resched_tasks_rcu_qs"></a>`cond_resched_tasks_rcu_qs()`

```c
cond_resched_tasks_rcu_qs()
```

Report potential quiescent states to RCU

**Description**

This macro resembles `cond_resched()`, except that it is defined to
report potential quiescent states to RCU-tasks even if the `cond_resched()`
machinery were to be shut off, as some advocate for PREEMPTION kernels.

#### <a id="c-rcu_softirq_qs_periodic"></a>`rcu_softirq_qs_periodic()`

```c
rcu_softirq_qs_periodic(old_ts)
```

Report RCU and RCU-Tasks quiescent states

**Parameters**

- `old_ts`: jiffies at start of processing.

**Description**

This helper is for long-running softirq handlers, such as NAPI threads in
networking. The caller should initialize the variable passed in as **old_ts**
at the beginning of the softirq handler. When invoked frequently, this macro
will invoke [`rcu_softirq_qs()`](#c-rcu_softirq_qs) every 100 milliseconds thereafter, which will
provide both RCU and RCU-Tasks quiescent states. Note that this macro
modifies its old_ts argument.

Because regions of code that have disabled softirq act as RCU read-side
critical sections, this macro should be invoked with softirq (and
preemption) enabled.

The macro is not needed when CONFIG_PREEMPT_RT is defined. RT kernels would
have more chance to invoke `schedule()` calls and provide necessary quiescent
states. As a contrast, calling `cond_resched()` only won't achieve the same
effect because `cond_resched()` does not provide RCU-Tasks quiescent states.

#### <a id="c-RCU_LOCKDEP_WARN"></a>`RCU_LOCKDEP_WARN()`

```c
RCU_LOCKDEP_WARN(c, s)
```

emit lockdep splat if specified condition is met

**Parameters**

- `c`: condition to check
- `s`: informative message

**Description**

This checks `debug_lockdep_rcu_enabled()` before checking (c) to
prevent early boot splats due to lockdep not yet being initialized,
and rechecks it after checking (c) to prevent false-positive splats
due to races with lockdep being disabled.  See commit 3066820034b5dd
("rcu: Reject [`RCU_LOCKDEP_WARN()`](#c-RCU_LOCKDEP_WARN) false positives") for more detail.

#### <a id="c-lockdep_assert_in_rcu_read_lock"></a>`lockdep_assert_in_rcu_read_lock()`

```c
lockdep_assert_in_rcu_read_lock()
```

WARN if not protected by [`rcu_read_lock()`](#c-rcu_read_lock)

**Description**

Splats if lockdep is enabled and there is no [`rcu_read_lock()`](#c-rcu_read_lock) in effect.

#### <a id="c-lockdep_assert_in_rcu_read_lock_bh"></a>`lockdep_assert_in_rcu_read_lock_bh()`

```c
lockdep_assert_in_rcu_read_lock_bh()
```

WARN if not protected by [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh)

**Description**

Splats if lockdep is enabled and there is no [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) in effect.
Note that `local_bh_disable()` and friends do not suffice here, instead an
actual [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) is required.

#### <a id="c-lockdep_assert_in_rcu_read_lock_sched"></a>`lockdep_assert_in_rcu_read_lock_sched()`

```c
lockdep_assert_in_rcu_read_lock_sched()
```

WARN if not protected by [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched)

**Description**

Splats if lockdep is enabled and there is no [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched)
in effect.  Note that `preempt_disable()` and friends do not suffice here,
instead an actual [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched) is required.

#### <a id="c-lockdep_assert_in_rcu_reader"></a>`lockdep_assert_in_rcu_reader()`

```c
lockdep_assert_in_rcu_reader()
```

WARN if not within some type of RCU reader

**Description**

Splats if lockdep is enabled and there is no RCU reader of any
type in effect.  Note that regions of code protected by things like
preempt_disable, `local_bh_disable()`, and `local_irq_disable()` all qualify
as RCU readers.

Note that this will never trigger in PREEMPT_NONE or PREEMPT_VOLUNTARY
kernels that are not also built with PREEMPT_COUNT.  But if you have
lockdep enabled, you might as well also enable PREEMPT_COUNT.

#### <a id="c-unrcu_pointer"></a>`unrcu_pointer()`

```c
unrcu_pointer(p)
```

mark a pointer as not being RCU protected

**Parameters**

- `p`: pointer needing to lose its __rcu property

**Description**

Converts **p** from an __rcu pointer to a __kernel pointer.
This allows an __rcu pointer to be used with `xchg()` and friends.

#### <a id="c-RCU_INITIALIZER"></a>`RCU_INITIALIZER()`

```c
RCU_INITIALIZER(v)
```

statically initialize an RCU-protected global variable

**Parameters**

- `v`: The value to statically initialize with.

#### <a id="c-rcu_assign_pointer"></a>`rcu_assign_pointer()`

```c
rcu_assign_pointer(p, v)
```

assign to RCU-protected pointer

**Parameters**

- `p`: pointer to assign to
- `v`: value to assign (publish)

**Description**

Assigns the specified value to the specified RCU-protected
pointer, ensuring that any concurrent RCU readers will see
any prior initialization.

Inserts memory barriers on architectures that require them
(which is most of them), and also prevents the compiler from
reordering the code that initializes the structure after the pointer
assignment.  More importantly, this call documents which pointers
will be dereferenced by RCU read-side code.

In some special cases, you may use [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) instead
of [`rcu_assign_pointer()`](#c-rcu_assign_pointer).  [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) is a bit faster due
to the fact that it does not constrain either the CPU or the compiler.
That said, using [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) when you should have used
[`rcu_assign_pointer()`](#c-rcu_assign_pointer) is a very bad thing that results in
impossible-to-diagnose memory corruption.  So please be careful.
See the [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) comment header for details.

Note that [`rcu_assign_pointer()`](#c-rcu_assign_pointer) evaluates each of its arguments only
once, appearances notwithstanding.  One of the "extra" evaluations
is in `typeof()` and the other visible only to sparse (__CHECKER__),
neither of which actually execute the argument.  As with most cpp
macros, this execute-arguments-only-once property is important, so
please be careful when making changes to [`rcu_assign_pointer()`](#c-rcu_assign_pointer) and the
other macros that it invokes.

#### <a id="c-rcu_replace_pointer"></a>`rcu_replace_pointer()`

```c
rcu_replace_pointer(rcu_ptr, ptr, c)
```

replace an RCU pointer, returning its old value

**Parameters**

- `rcu_ptr`: RCU pointer, whose old value is returned
- `ptr`: regular pointer
- `c`: the lockdep conditions under which the dereference will take place

**Description**

Perform a replacement, where **rcu_ptr** is an RCU-annotated
pointer and **c** is the lockdep argument that is passed to the
[`rcu_dereference_protected()`](#c-rcu_dereference_protected) call used to read that pointer.  The old
value of **rcu_ptr** is returned, and **rcu_ptr** is set to **ptr**.

#### <a id="c-rcu_access_pointer"></a>`rcu_access_pointer()`

```c
rcu_access_pointer(p)
```

fetch RCU pointer with no dereferencing

**Parameters**

- `p`: The pointer to read

**Description**

Return the value of the specified RCU-protected pointer, but omit the
lockdep checks for being in an RCU read-side critical section.  This is
useful when the value of this pointer is accessed, but the pointer is
not dereferenced, for example, when testing an RCU-protected pointer
against NULL.  Although [`rcu_access_pointer()`](#c-rcu_access_pointer) may also be used in cases
where update-side locks prevent the value of the pointer from changing,
you should instead use [`rcu_dereference_protected()`](#c-rcu_dereference_protected) for this use case.
Within an RCU read-side critical section, there is little reason to
use [`rcu_access_pointer()`](#c-rcu_access_pointer).

It is usually best to test the [`rcu_access_pointer()`](#c-rcu_access_pointer) return value
directly in order to avoid accidental dereferences being introduced
by later inattentive changes.  In other words, assigning the
[`rcu_access_pointer()`](#c-rcu_access_pointer) return value to a local variable results in an
accident waiting to happen.

It is also permissible to use [`rcu_access_pointer()`](#c-rcu_access_pointer) when read-side
access to the pointer was removed at least one grace period ago, as is
the case in the context of the RCU callback that is freeing up the data,
or after a [`synchronize_rcu()`](#c-synchronize_rcu) returns.  This can be useful when tearing
down multi-linked structures after a grace period has elapsed.  However,
[`rcu_dereference_protected()`](#c-rcu_dereference_protected) is normally preferred for this use case.

#### <a id="c-rcu_dereference_check"></a>`rcu_dereference_check()`

```c
rcu_dereference_check(p, c)
```

rcu_dereference with debug checking

**Parameters**

- `p`: The pointer to read, prior to dereferencing
- `c`: The conditions under which the dereference will take place

**Description**

Do an [`rcu_dereference()`](#c-rcu_dereference), but check that the conditions under which the
dereference will take place are correct.  Typically the conditions
indicate the various locking conditions that should be held at that
point.  The check should return true if the conditions are satisfied.
An implicit check for being in an RCU read-side critical section
([`rcu_read_lock()`](#c-rcu_read_lock)) is included.

For example:

bar = rcu_dereference_check(foo->bar, lockdep_is_held(`foo->lock`));

could be used to indicate to lockdep that foo->bar may only be dereferenced
if either [`rcu_read_lock()`](#c-rcu_read_lock) is held, or that the lock required to replace
the bar struct at foo->bar is held.

Note that the list of conditions may also include indications of when a lock
need not be held, for example during initialisation or destruction of the
target struct:

- bar = rcu_dereference_check(foo->bar, lockdep_is_held(`foo->lock`) ||

  atomic_read(`foo->usage`) == 0);

Inserts memory barriers on architectures that require them
(currently only the Alpha), prevents the compiler from refetching
(and from merging fetches), and, more importantly, documents exactly
which pointers are protected by RCU and checks that the pointer is
annotated as __rcu.

#### <a id="c-rcu_dereference_bh_check"></a>`rcu_dereference_bh_check()`

```c
rcu_dereference_bh_check(p, c)
```

rcu_dereference_bh with debug checking

**Parameters**

- `p`: The pointer to read, prior to dereferencing
- `c`: The conditions under which the dereference will take place

**Description**

This is the RCU-bh counterpart to [`rcu_dereference_check()`](#c-rcu_dereference_check).  However,
please note that starting in v5.0 kernels, vanilla RCU grace periods
wait for `local_bh_disable()` regions of code in addition to regions of
code demarked by [`rcu_read_lock()`](#c-rcu_read_lock) and [`rcu_read_unlock()`](#c-rcu_read_unlock).  This means
that [`synchronize_rcu()`](#c-synchronize_rcu), call_rcu, and friends all take not only
[`rcu_read_lock()`](#c-rcu_read_lock) but also [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) into account.

#### <a id="c-rcu_dereference_sched_check"></a>`rcu_dereference_sched_check()`

```c
rcu_dereference_sched_check(p, c)
```

rcu_dereference_sched with debug checking

**Parameters**

- `p`: The pointer to read, prior to dereferencing
- `c`: The conditions under which the dereference will take place

**Description**

This is the RCU-sched counterpart to [`rcu_dereference_check()`](#c-rcu_dereference_check).
However, please note that starting in v5.0 kernels, vanilla RCU grace
periods wait for `preempt_disable()` regions of code in addition to
regions of code demarked by [`rcu_read_lock()`](#c-rcu_read_lock) and [`rcu_read_unlock()`](#c-rcu_read_unlock).
This means that [`synchronize_rcu()`](#c-synchronize_rcu), call_rcu, and friends all take not
only [`rcu_read_lock()`](#c-rcu_read_lock) but also [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched) into account.

#### <a id="c-rcu_dereference_all_check"></a>`rcu_dereference_all_check()`

```c
rcu_dereference_all_check(p, c)
```

rcu_dereference_all with debug checking

**Parameters**

- `p`: The pointer to read, prior to dereferencing
- `c`: The conditions under which the dereference will take place

**Description**

This is similar to [`rcu_dereference_check()`](#c-rcu_dereference_check), but allows protection
by all forms of vanilla RCU readers, including preemption disabled,
bh-disabled, and interrupt-disabled regions of code.  Note that "vanilla
RCU" excludes SRCU and the various Tasks RCU flavors.  Please note
that this macro should not be backported to any Linux-kernel version
preceding v5.0 due to changes in [`synchronize_rcu()`](#c-synchronize_rcu) semantics prior
to that version.

#### <a id="c-rcu_dereference_protected"></a>`rcu_dereference_protected()`

```c
rcu_dereference_protected(p, c)
```

fetch RCU pointer when updates prevented

**Parameters**

- `p`: The pointer to read, prior to dereferencing
- `c`: The conditions under which the dereference will take place

**Description**

Return the value of the specified RCU-protected pointer, but omit
the `READ_ONCE()`.  This is useful in cases where update-side locks
prevent the value of the pointer from changing.  Please note that this
primitive does *not* prevent the compiler from repeating this reference
or combining it with other references, so it should not be used without
protection of appropriate locks.

This function is only for update-side use.  Using this function
when protected only by [`rcu_read_lock()`](#c-rcu_read_lock) will result in infrequent
but very ugly failures.

#### <a id="c-rcu_dereference"></a>`rcu_dereference()`

```c
rcu_dereference(p)
```

fetch RCU-protected pointer for dereferencing

**Parameters**

- `p`: The pointer to read, prior to dereferencing

**Description**

This is a simple wrapper around [`rcu_dereference_check()`](#c-rcu_dereference_check).

#### <a id="c-rcu_dereference_bh"></a>`rcu_dereference_bh()`

```c
rcu_dereference_bh(p)
```

fetch an RCU-bh-protected pointer for dereferencing

**Parameters**

- `p`: The pointer to read, prior to dereferencing

**Description**

Makes [`rcu_dereference_check()`](#c-rcu_dereference_check) do the dirty work.

#### <a id="c-rcu_dereference_sched"></a>`rcu_dereference_sched()`

```c
rcu_dereference_sched(p)
```

fetch RCU-sched-protected pointer for dereferencing

**Parameters**

- `p`: The pointer to read, prior to dereferencing

**Description**

Makes [`rcu_dereference_check()`](#c-rcu_dereference_check) do the dirty work.

#### <a id="c-rcu_dereference_all"></a>`rcu_dereference_all()`

```c
rcu_dereference_all(p)
```

fetch RCU-all-protected pointer for dereferencing

**Parameters**

- `p`: The pointer to read, prior to dereferencing

**Description**

Makes [`rcu_dereference_check()`](#c-rcu_dereference_check) do the dirty work.

#### <a id="c-rcu_pointer_handoff"></a>`rcu_pointer_handoff()`

```c
rcu_pointer_handoff(p)
```

Hand off a pointer from RCU to other mechanism

**Parameters**

- `p`: The pointer to hand off

**Description**

This is simply an identity function, but it documents where a pointer
is handed off from RCU to some other synchronization mechanism, for
example, reference counting or locking.  In C11, it would map to
`kill_dependency()`.  It could be used as follows:

```text
rcu_read_lock();
p = rcu_dereference(gp);
long_lived = is_long_lived(p);
if (long_lived) {
        if (!atomic_inc_not_zero(p->refcnt))
                long_lived = false;
        else
                p = rcu_pointer_handoff(p);
}
rcu_read_unlock();
```

#### <a id="c-rcu_read_lock"></a>`rcu_read_lock()`

```c
void rcu_read_lock(void)
```

mark the beginning of an RCU read-side critical section

**Parameters**

- `void`: no arguments

**Description**

When [`synchronize_rcu()`](#c-synchronize_rcu) is invoked on one CPU while other CPUs
are within RCU read-side critical sections, then the
[`synchronize_rcu()`](#c-synchronize_rcu) is guaranteed to block until after all the other
CPUs exit their critical sections.  Similarly, if [`call_rcu()`](#c-call_rcu) is invoked
on one CPU while other CPUs are within RCU read-side critical
sections, invocation of the corresponding RCU callback is deferred
until after the all the other CPUs exit their critical sections.

Both [`synchronize_rcu()`](#c-synchronize_rcu) and [`call_rcu()`](#c-call_rcu) also wait for regions of code
with preemption disabled, including regions of code with interrupts or
softirqs disabled.

Note, however, that RCU callbacks are permitted to run concurrently
with new RCU read-side critical sections.  One way that this can happen
is via the following sequence of events: (1) CPU 0 enters an RCU
read-side critical section, (2) CPU 1 invokes [`call_rcu()`](#c-call_rcu) to register
an RCU callback, (3) CPU 0 exits the RCU read-side critical section,
(4) CPU 2 enters a RCU read-side critical section, (5) the RCU
callback is invoked.  This is legal, because the RCU read-side critical
section that was running concurrently with the [`call_rcu()`](#c-call_rcu) (and which
therefore might be referencing something that the corresponding RCU
callback would free up) has completed before the corresponding
RCU callback is invoked.

RCU read-side critical sections may be nested.  Any deferred actions
will be deferred until the outermost RCU read-side critical section
completes.

You can avoid reading and understanding the next paragraph by
following this rule: don't put anything in an [`rcu_read_lock()`](#c-rcu_read_lock) RCU
read-side critical section that would block in a !PREEMPTION kernel.
But if you want the full story, read on!

In non-preemptible RCU implementations (pure TREE_RCU and TINY_RCU),
it is illegal to block while in an RCU read-side critical section.
In preemptible RCU implementations (PREEMPT_RCU) in CONFIG_PREEMPTION
kernel builds, RCU read-side critical sections may be preempted,
but explicit blocking is illegal.  Finally, in preemptible RCU
implementations in real-time (with -rt patchset) kernel builds, RCU
read-side critical sections may be preempted and they may also block, but
only when acquiring spinlocks that are subject to priority inheritance.

#### <a id="c-rcu_read_unlock"></a>`rcu_read_unlock()`

```c
void rcu_read_unlock(void)
```

marks the end of an RCU read-side critical section.

**Parameters**

- `void`: no arguments

**Description**

In almost all situations, [`rcu_read_unlock()`](#c-rcu_read_unlock) is immune from deadlock.
This deadlock immunity also extends to the scheduler's runqueue
and priority-inheritance spinlocks, courtesy of the quiescent-state
deferral that is carried out when [`rcu_read_unlock()`](#c-rcu_read_unlock) is invoked with
interrupts disabled.

See [`rcu_read_lock()`](#c-rcu_read_lock) for more information.

#### <a id="c-rcu_read_lock_bh"></a>`rcu_read_lock_bh()`

```c
void rcu_read_lock_bh(void)
```

mark the beginning of an RCU-bh critical section

**Parameters**

- `void`: no arguments

**Description**

This is equivalent to [`rcu_read_lock()`](#c-rcu_read_lock), but also disables softirqs.
Note that anything else that disables softirqs can also serve as an RCU
read-side critical section.  However, please note that this equivalence
applies only to v5.0 and later.  Before v5.0, [`rcu_read_lock()`](#c-rcu_read_lock) and
[`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) were unrelated.

Note that [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) and the matching [`rcu_read_unlock_bh()`](#c-rcu_read_unlock_bh)
must occur in the same context, for example, it is illegal to invoke
[`rcu_read_unlock_bh()`](#c-rcu_read_unlock_bh) from one task if the matching [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh)
was invoked from some other task.

#### <a id="c-rcu_read_unlock_bh"></a>`rcu_read_unlock_bh()`

```c
void rcu_read_unlock_bh(void)
```

marks the end of a softirq-only RCU critical section

**Parameters**

- `void`: no arguments

**Description**

See [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) for more information.

#### <a id="c-rcu_read_lock_sched"></a>`rcu_read_lock_sched()`

```c
void rcu_read_lock_sched(void)
```

mark the beginning of a RCU-sched critical section

**Parameters**

- `void`: no arguments

**Description**

This is equivalent to [`rcu_read_lock()`](#c-rcu_read_lock), but also disables preemption.
Read-side critical sections can also be introduced by anything else that
disables preemption, including `local_irq_disable()` and friends.  However,
please note that the equivalence to [`rcu_read_lock()`](#c-rcu_read_lock) applies only to
v5.0 and later.  Before v5.0, [`rcu_read_lock()`](#c-rcu_read_lock) and [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched)
were unrelated.

Note that [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched) and the matching [`rcu_read_unlock_sched()`](#c-rcu_read_unlock_sched)
must occur in the same context, for example, it is illegal to invoke
[`rcu_read_unlock_sched()`](#c-rcu_read_unlock_sched) from process context if the matching
[`rcu_read_lock_sched()`](#c-rcu_read_lock_sched) was invoked from an NMI handler.

#### <a id="c-rcu_read_unlock_sched"></a>`rcu_read_unlock_sched()`

```c
void rcu_read_unlock_sched(void)
```

marks the end of a RCU-classic critical section

**Parameters**

- `void`: no arguments

**Description**

See [`rcu_read_lock_sched()`](#c-rcu_read_lock_sched) for more information.

#### <a id="c-RCU_INIT_POINTER"></a>`RCU_INIT_POINTER()`

```c
RCU_INIT_POINTER(p, v)
```

initialize an RCU protected pointer

**Parameters**

- `p`: The pointer to be initialized.
- `v`: The value to initialized the pointer to.

**Description**

Initialize an RCU-protected pointer in special cases where readers
do not need ordering constraints on the CPU or the compiler.  These
special cases are:

1. This use of [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) is NULLing out the pointer *or*
2. The caller has taken whatever steps are required to prevent
   RCU readers from concurrently accessing this pointer *or*
3. The referenced data structure has already been exposed to
   readers either at compile time or via [`rcu_assign_pointer()`](#c-rcu_assign_pointer) *and*

   a.      You have not made *any* reader-visible changes to
   this structure since then *or*
   b.      It is OK for readers accessing this structure from its
   new location to see the old state of the structure.  (For
   example, the changes were to statistical counters or to
   other state where exact synchronization is not required.)

Failure to follow these rules governing use of [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) will
result in impossible-to-diagnose memory corruption.  As in the structures
will look OK in crash dumps, but any concurrent RCU readers might
see pre-initialized values of the referenced data structure.  So
please be very careful how you use [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER)!!!

If you are creating an RCU-protected linked structure that is accessed
by a single external-to-structure RCU-protected pointer, then you may
use [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) to initialize the internal RCU-protected
pointers, but you must use [`rcu_assign_pointer()`](#c-rcu_assign_pointer) to initialize the
external-to-structure pointer *after* you have completely initialized
the reader-accessible portions of the linked structure.

Note that unlike [`rcu_assign_pointer()`](#c-rcu_assign_pointer), [`RCU_INIT_POINTER()`](#c-RCU_INIT_POINTER) provides no
ordering guarantees for either the CPU or the compiler.

#### <a id="c-RCU_POINTER_INITIALIZER"></a>`RCU_POINTER_INITIALIZER()`

```c
RCU_POINTER_INITIALIZER(p, v)
```

statically initialize an RCU protected pointer

**Parameters**

- `p`: The pointer to be initialized.
- `v`: The value to initialized the pointer to.

**Description**

GCC-style initialization for an RCU-protected pointer in a structure field.

#### <a id="c-kfree_rcu"></a>`kfree_rcu()`

```c
kfree_rcu(ptr, rhf)
```

kfree an object after a grace period.

**Parameters**

- `ptr`: pointer to kfree for double-argument invocations.
- `rhf`: the name of the struct rcu_head within the type of **ptr**.

**Description**

Many rcu callbacks functions just call [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) on the base structure.
These functions are trivial, but their size adds up, and furthermore
when they are used in a kernel module, that module must invoke the
high-latency [`rcu_barrier()`](#c-rcu_barrier) function at module-unload time.

The [`kfree_rcu()`](#c-kfree_rcu) function handles this issue. In order to have a universal
callback function handling different offsets of rcu_head, the callback needs
to determine the starting address of the freed object, which can be a large
kmalloc or vmalloc allocation. To allow simply aligning the pointer down to
page boundary for those, only offsets up to 4095 bytes can be accommodated.
If the offset is larger than 4095 bytes, a compile-time error will
be generated in `kvfree_rcu_arg_2()`. If this error is triggered, you can
either fall back to use of [`call_rcu()`](#c-call_rcu) or rearrange the structure to
position the rcu_head structure into the first 4096 bytes.

The object to be freed can be allocated either by [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc),
[`kmalloc_nolock()`](/kernel/internals/core-api/mm-api.md#c-kmalloc_nolock), or [`kmem_cache_alloc()`](/kernel/internals/core-api/mm-api.md#c-kmem_cache_alloc).

Note that the allowable offset might decrease in the future.

The BUILD_BUG_ON check must not involve any function calls, hence the
checks are done in macros here.

#### <a id="c-kfree_rcu_mightsleep"></a>`kfree_rcu_mightsleep()`

```c
kfree_rcu_mightsleep(ptr)
```

kfree an object after a grace period.

**Parameters**

- `ptr`: pointer to kfree for single-argument invocations.

**Description**

When it comes to head-less variant, only one argument
is passed and that is just a pointer which has to be
freed after a grace period. Therefore the semantic is

kfree_rcu_mightsleep(ptr);

where **ptr** is the pointer to be freed by [`kvfree()`](/kernel/internals/core-api/mm-api.md#c-kvfree).

Please note, head-less way of freeing is permitted to
use from a context that has to follow `might_sleep()`
annotation. Otherwise, please switch and embed the
rcu_head structure within the type of **ptr**.

#### <a id="c-rcu_head_init"></a>`rcu_head_init()`

```c
void rcu_head_init(struct rcu_head *rhp)
```

Initialize rcu_head for [`rcu_head_after_call_rcu()`](#c-rcu_head_after_call_rcu)

**Parameters**

- `struct rcu_head *rhp`: The rcu_head structure to initialize.

**Description**

If you intend to invoke [`rcu_head_after_call_rcu()`](#c-rcu_head_after_call_rcu) to test whether a
given rcu_head structure has already been passed to [`call_rcu()`](#c-call_rcu), then
you must also invoke this [`rcu_head_init()`](#c-rcu_head_init) function on it just after
allocating that structure.  Calls to this function must not race with
calls to [`call_rcu()`](#c-call_rcu), [`rcu_head_after_call_rcu()`](#c-rcu_head_after_call_rcu), or callback invocation.

#### <a id="c-rcu_head_after_call_rcu"></a>`rcu_head_after_call_rcu()`

```c
bool rcu_head_after_call_rcu(struct rcu_head *rhp, rcu_callback_t f)
```

Has this rcu_head been passed to [`call_rcu()`](#c-call_rcu)?

**Parameters**

- `struct rcu_head *rhp`: The rcu_head structure to test.
- `rcu_callback_t f`: The function passed to [`call_rcu()`](#c-call_rcu) along with **rhp**.

**Description**

Returns **true** if the **rhp** has been passed to [`call_rcu()`](#c-call_rcu) with **func**,
and **false** otherwise.  Emits a warning in any other case, including
the case where **rhp** has already been invoked after a grace period.
Calls to this function must not race with callback invocation.  One way
to avoid such races is to enclose the call to [`rcu_head_after_call_rcu()`](#c-rcu_head_after_call_rcu)
in an RCU read-side critical section that includes a read-side fetch
of the pointer to the structure containing **rhp**.



#### <a id="c-rcu_softirq_qs"></a>`rcu_softirq_qs()`

```c
void rcu_softirq_qs(void)
```

Provide a set of RCU quiescent states in softirq processing

**Parameters**

- `void`: no arguments

**Description**

Mark a quiescent state for RCU, Tasks RCU, and Tasks Trace RCU.
This is a special-purpose function to be used in the softirq
infrastructure and perhaps the occasional long-running softirq
handler.

Note that from RCU's viewpoint, a call to [`rcu_softirq_qs()`](#c-rcu_softirq_qs) is
equivalent to momentarily completely enabling preemption.  For
example, given this code:

```text
local_bh_disable();
do_something();
rcu_softirq_qs();  // A
do_something_else();
local_bh_enable();  // B
```

A call to [`synchronize_rcu()`](#c-synchronize_rcu) that began concurrently with the
call to `do_something()` would be guaranteed to wait only until
execution reached statement A.  Without that [`rcu_softirq_qs()`](#c-rcu_softirq_qs),
that same [`synchronize_rcu()`](#c-synchronize_rcu) would instead be guaranteed to wait
until execution reached statement B.

#### <a id="c-rcu_watching_snap_stopped_since"></a>`rcu_watching_snap_stopped_since()`

```c
bool rcu_watching_snap_stopped_since(struct rcu_data *rdp, int snap)
```

Has RCU stopped watching a given CPU since the specified **snap**?

**Parameters**

- `struct rcu_data *rdp`: The rcu_data corresponding to the CPU for which to check EQS.
- `int snap`: rcu_watching snapshot taken when the CPU wasn't in an EQS.

**Description**

Returns true if the CPU corresponding to **rdp** has spent some time in an
extended quiescent state since **snap**. Note that this doesn't check if it
/still/ is in an EQS, just that it went through one since **snap**.

This is meant to be used in a loop waiting for a CPU to go through an EQS.

#### <a id="c-rcu_is_cpu_rrupt_from_idle"></a>`rcu_is_cpu_rrupt_from_idle()`

```c
int rcu_is_cpu_rrupt_from_idle(void)
```

see if 'interrupted' from idle

**Parameters**

- `void`: no arguments

**Description**

If the current CPU is idle and running at a first-level (not nested)
interrupt, or directly, from idle, return true.

The caller must have at least disabled IRQs.

#### <a id="c-rcu_irq_exit_check_preempt"></a>`rcu_irq_exit_check_preempt()`

```c
void rcu_irq_exit_check_preempt(void)
```

Validate that scheduling is possible

**Parameters**

- `void`: no arguments

#### <a id="c-__rcu_irq_enter_check_tick"></a>`__rcu_irq_enter_check_tick()`

```c
void __rcu_irq_enter_check_tick(void)
```

Enable scheduler tick on CPU if RCU needs it.

**Parameters**

- `void`: no arguments

**Description**

The scheduler tick is not normally enabled when CPUs enter the kernel
from nohz_full userspace execution.  After all, nohz_full userspace
execution is an RCU quiescent state and the time executing in the kernel
is quite short.  Except of course when it isn't.  And it is not hard to
cause a large system to spend tens of seconds or even minutes looping
in the kernel, which can cause a number of problems, include RCU CPU
stall warnings.

Therefore, if a nohz_full CPU fails to report a quiescent state
in a timely manner, the RCU grace-period kthread sets that CPU's
->rcu_urgent_qs flag with the expectation that the next interrupt or
exception will invoke this function, which will turn on the scheduler
tick, which will enable RCU to detect that CPU's quiescent states,
for example, due to `cond_resched()` calls in CONFIG_PREEMPT=n kernels.
The tick will be disabled once a quiescent state is reported for
this CPU.

Of course, in carefully tuned systems, there might never be an
interrupt or exception.  In that case, the RCU grace-period kthread
will eventually cause one to happen.  However, in less carefully
controlled environments, this function allows RCU to get what it
needs without creating otherwise useless interruptions.

#### <a id="c-rcu_is_watching"></a>`rcu_is_watching()`

```c
notrace bool rcu_is_watching(void)
```

RCU read-side critical sections permitted on current CPU?

**Parameters**

- `void`: no arguments

**Description**

Return **true** if RCU is watching the running CPU and **false** otherwise.
An **true** return means that this CPU can safely enter RCU read-side
critical sections.

Although calls to [`rcu_is_watching()`](#c-rcu_is_watching) from most parts of the kernel
will return **true**, there are important exceptions.  For example, if the
current CPU is deep within its idle loop, in kernel entry/exit code,
or offline, [`rcu_is_watching()`](#c-rcu_is_watching) will return **false**.

Make notrace because it can be called by the internal functions of
ftrace, and making this notrace removes unnecessary recursion calls.

#### <a id="c-rcu_set_gpwrap_lag"></a>`rcu_set_gpwrap_lag()`

```c
void rcu_set_gpwrap_lag(unsigned long lag_gps)
```

Set RCU GP sequence overflow lag value.

**Parameters**

- `unsigned long lag_gps`: Set overflow lag to this many grace period worth of counters
  which is used by rcutorture to quickly force a gpwrap situation.
  **lag_gps** = 0 means we reset it back to the boot-time value.

#### <a id="c-call_rcu_hurry"></a>`call_rcu_hurry()`

```c
void call_rcu_hurry(struct rcu_head *head, rcu_callback_t func)
```

Queue RCU callback for invocation after grace period, and flush all lazy callbacks (including the new one) to the main ->cblist while doing so.

**Parameters**

- `struct rcu_head *head`: structure to be used for queueing the RCU updates.
- `rcu_callback_t func`: actual callback function to be invoked after the grace period

**Description**

The callback function will be invoked some time after a full grace
period elapses, in other words after all pre-existing RCU read-side
critical sections have completed.

Use this API instead of [`call_rcu()`](#c-call_rcu) if you don't want the callback to be
delayed for very long periods of time, which can happen on systems without
memory pressure and on systems which are lightly loaded or mostly idle.
This function will cause callbacks to be invoked sooner than later at the
expense of extra power. Other than that, this function is identical to, and
reuses [`call_rcu()`](#c-call_rcu)'s logic. Refer to [`call_rcu()`](#c-call_rcu) for more details about memory
ordering and other functionality.

#### <a id="c-call_rcu"></a>`call_rcu()`

```c
void call_rcu(struct rcu_head *head, rcu_callback_t func)
```

Queue an RCU callback for invocation after a grace period. By default the callbacks are 'lazy' and are kept hidden from the main ->cblist to prevent starting of grace periods too soon. If you desire grace periods to start very soon, use [`call_rcu_hurry()`](#c-call_rcu_hurry).

**Parameters**

- `struct rcu_head *head`: structure to be used for queueing the RCU updates.
- `rcu_callback_t func`: actual callback function to be invoked after the grace period

**Description**

The callback function will be invoked some time after a full grace
period elapses, in other words after all pre-existing RCU read-side
critical sections have completed.  However, the callback function
might well execute concurrently with RCU read-side critical sections
that started after [`call_rcu()`](#c-call_rcu) was invoked.

It is perfectly legal to repost an RCU callback, potentially with
a different callback function, from within its callback function.
The specified function will be invoked after another full grace period
has elapsed.  This use case is similar in form to the common practice
of reposting a timer from within its own handler.

RCU read-side critical sections are delimited by [`rcu_read_lock()`](#c-rcu_read_lock)
and [`rcu_read_unlock()`](#c-rcu_read_unlock), and may be nested.  In addition, but only in
v5.0 and later, regions of code across which interrupts, preemption,
or softirqs have been disabled also serve as RCU read-side critical
sections.  This includes hardware interrupt handlers, softirq handlers,
and NMI handlers.

Note that all CPUs must agree that the grace period extended beyond
all pre-existing RCU read-side critical section.  On systems with more
than one CPU, this means that when "`func()`" is invoked, each CPU is
guaranteed to have executed a full memory barrier since the end of its
last RCU read-side critical section whose beginning preceded the call
to [`call_rcu()`](#c-call_rcu).  It also means that each CPU executing an RCU read-side
critical section that continues beyond the start of "`func()`" must have
executed a memory barrier after the [`call_rcu()`](#c-call_rcu) but before the beginning
of that RCU read-side critical section.  Note that these guarantees
include CPUs that are offline, idle, or executing in user mode, as
well as CPUs that are executing in the kernel.

Furthermore, if CPU A invoked [`call_rcu()`](#c-call_rcu) and CPU B invoked the
resulting RCU callback function "`func()`", then both CPU A and CPU B are
guaranteed to execute a full memory barrier during the time interval
between the call to [`call_rcu()`](#c-call_rcu) and the invocation of "`func()`" -- even
if CPU A and CPU B are the same CPU (but again only if the system has
more than one CPU).

Implementation of these memory-ordering guarantees is described here:
Documentation/RCU/Design/Memory-Ordering/Tree-RCU-Memory-Ordering.rst.

Specific to [`call_rcu()`](#c-call_rcu) (as opposed to the other call_rcu*() functions),
in kernels built with CONFIG_RCU_LAZY=y, [`call_rcu()`](#c-call_rcu) might delay for many
seconds before starting the grace period needed by the corresponding
callback.  This delay can significantly improve energy-efficiency
on low-utilization battery-powered devices.  To avoid this delay,
in latency-sensitive kernel code, use [`call_rcu_hurry()`](#c-call_rcu_hurry).

#### <a id="c-synchronize_rcu"></a>`synchronize_rcu()`

```c
void synchronize_rcu(void)
```

wait until a grace period has elapsed.

**Parameters**

- `void`: no arguments

**Description**

Control will return to the caller some time after a full grace
period has elapsed, in other words after all currently executing RCU
read-side critical sections have completed.  Note, however, that
upon return from [`synchronize_rcu()`](#c-synchronize_rcu), the caller might well be executing
concurrently with new RCU read-side critical sections that began while
[`synchronize_rcu()`](#c-synchronize_rcu) was waiting.

RCU read-side critical sections are delimited by [`rcu_read_lock()`](#c-rcu_read_lock)
and [`rcu_read_unlock()`](#c-rcu_read_unlock), and may be nested.  In addition, but only in
v5.0 and later, regions of code across which interrupts, preemption,
or softirqs have been disabled also serve as RCU read-side critical
sections.  This includes hardware interrupt handlers, softirq handlers,
and NMI handlers.

Note that this guarantee implies further memory-ordering guarantees.
On systems with more than one CPU, when [`synchronize_rcu()`](#c-synchronize_rcu) returns,
each CPU is guaranteed to have executed a full memory barrier since
the end of its last RCU read-side critical section whose beginning
preceded the call to [`synchronize_rcu()`](#c-synchronize_rcu).  In addition, each CPU having
an RCU read-side critical section that extends beyond the return from
[`synchronize_rcu()`](#c-synchronize_rcu) is guaranteed to have executed a full memory barrier
after the beginning of [`synchronize_rcu()`](#c-synchronize_rcu) and before the beginning of
that RCU read-side critical section.  Note that these guarantees include
CPUs that are offline, idle, or executing in user mode, as well as CPUs
that are executing in the kernel.

Furthermore, if CPU A invoked [`synchronize_rcu()`](#c-synchronize_rcu), which returned
to its caller on CPU B, then both CPU A and CPU B are guaranteed
to have executed a full memory barrier during the execution of
[`synchronize_rcu()`](#c-synchronize_rcu) -- even if CPU A and CPU B are the same CPU (but
again only if the system has more than one CPU).

Implementation of these memory-ordering guarantees is described here:
Documentation/RCU/Design/Memory-Ordering/Tree-RCU-Memory-Ordering.rst.

#### <a id="c-get_completed_synchronize_rcu_full"></a>`get_completed_synchronize_rcu_full()`

```c
void get_completed_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
```

Return a full pre-completed polled state cookie

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: Place to put state cookie

**Description**

Stores into **rgosp** a value that will always be treated by functions
like [`poll_state_synchronize_rcu_full()`](#c-poll_state_synchronize_rcu_full) as a cookie whose grace period
has already completed.

#### <a id="c-get_state_synchronize_rcu"></a>`get_state_synchronize_rcu()`

```c
unsigned long get_state_synchronize_rcu(void)
```

Snapshot current RCU state

**Parameters**

- `void`: no arguments

**Description**

Returns a cookie that is used by a later call to [`cond_synchronize_rcu()`](#c-cond_synchronize_rcu)
or [`poll_state_synchronize_rcu()`](#c-poll_state_synchronize_rcu) to determine whether or not a full
grace period has elapsed in the meantime.

#### <a id="c-get_state_synchronize_rcu_full"></a>`get_state_synchronize_rcu_full()`

```c
void get_state_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
```

Snapshot RCU state, both normal and expedited

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: location to place combined normal/expedited grace-period state

**Description**

Places the normal and expedited grace-period states in **rgosp**.  This
state value can be passed to a later call to [`cond_synchronize_rcu_full()`](#c-cond_synchronize_rcu_full)
or [`poll_state_synchronize_rcu_full()`](#c-poll_state_synchronize_rcu_full) to determine whether or not a
grace period (whether normal or expedited) has elapsed in the meantime.
The rcu_gp_oldstate structure takes up twice the memory of an unsigned
long, but is guaranteed to see all grace periods.  In contrast, the
combined state occupies less memory, but can sometimes fail to take
grace periods into account.

This does not guarantee that the needed grace period will actually
start.

#### <a id="c-start_poll_synchronize_rcu"></a>`start_poll_synchronize_rcu()`

```c
unsigned long start_poll_synchronize_rcu(void)
```

Snapshot and start RCU grace period

**Parameters**

- `void`: no arguments

**Description**

Returns a cookie that is used by a later call to [`cond_synchronize_rcu()`](#c-cond_synchronize_rcu)
or [`poll_state_synchronize_rcu()`](#c-poll_state_synchronize_rcu) to determine whether or not a full
grace period has elapsed in the meantime.  If the needed grace period
is not already slated to start, notifies RCU core of the need for that
grace period.

#### <a id="c-start_poll_synchronize_rcu_full"></a>`start_poll_synchronize_rcu_full()`

```c
void start_poll_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
```

Take a full snapshot and start RCU grace period

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: value from [`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full) or [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full)

**Description**

Places the normal and expedited grace-period states in **\*rgos**.  This
state value can be passed to a later call to [`cond_synchronize_rcu_full()`](#c-cond_synchronize_rcu_full)
or [`poll_state_synchronize_rcu_full()`](#c-poll_state_synchronize_rcu_full) to determine whether or not a
grace period (whether normal or expedited) has elapsed in the meantime.
If the needed grace period is not already slated to start, notifies
RCU core of the need for that grace period.

#### <a id="c-poll_state_synchronize_rcu"></a>`poll_state_synchronize_rcu()`

```c
bool poll_state_synchronize_rcu(unsigned long oldstate)
```

Has the specified RCU grace period completed?

**Parameters**

- `unsigned long oldstate`: value from [`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu) or [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu)

**Description**

If a full RCU grace period has elapsed since the earlier call from
which **oldstate** was obtained, return **true**, otherwise return **false**.
If **false** is returned, it is the caller's responsibility to invoke this
function later on until it does return **true**.  Alternatively, the caller
can explicitly wait for a grace period, for example, by passing **oldstate**
to either [`cond_synchronize_rcu()`](#c-cond_synchronize_rcu) or [`cond_synchronize_rcu_expedited()`](#c-cond_synchronize_rcu_expedited)
on the one hand or by directly invoking either [`synchronize_rcu()`](#c-synchronize_rcu) or
[`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited) on the other.

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited for
more than a billion grace periods (and way more on a 64-bit system!).
Those needing to keep old state values for very long time periods
(many hours even on 32-bit systems) should check them occasionally and
either refresh them or set a flag indicating that the grace period has
completed.  Alternatively, they can use [`get_completed_synchronize_rcu()`](#c-get_completed_synchronize_rcu)
to get a guaranteed-completed grace-period state.

In addition, because oldstate compresses the grace-period state for
both normal and expedited grace periods into a single unsigned long,
it can miss a grace period when [`synchronize_rcu()`](#c-synchronize_rcu) runs concurrently
with [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited).  If this is unacceptable, please
instead use the `_full()` variant of these polling APIs.

This function provides the same memory-ordering guarantees that
would be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call
to the function that provided **oldstate**, and that returned at the end
of this function.

#### <a id="c-poll_state_synchronize_rcu_full"></a>`poll_state_synchronize_rcu_full()`

```c
bool poll_state_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
```

Has the specified RCU grace period completed?

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: value from [`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full) or [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full)

**Description**

If a full RCU grace period has elapsed since the earlier call from
which *rgosp was obtained, return **true**, otherwise return **false**.
If **false** is returned, it is the caller's responsibility to invoke this
function later on until it does return **true**.  Alternatively, the caller
can explicitly wait for a grace period, for example, by passing **rgosp**
to [`cond_synchronize_rcu()`](#c-cond_synchronize_rcu) or by directly invoking [`synchronize_rcu()`](#c-synchronize_rcu).

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited
for more than a billion grace periods (and way more on a 64-bit
system!).  Those needing to keep rcu_gp_oldstate values for very
long time periods (many hours even on 32-bit systems) should check
them occasionally and either refresh them or set a flag indicating
that the grace period has completed.  Alternatively, they can use
[`get_completed_synchronize_rcu_full()`](#c-get_completed_synchronize_rcu_full) to get a guaranteed-completed
grace-period state.

This function provides the same memory-ordering guarantees that would
be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call to
the function that provided **rgosp**, and that returned at the end of this
function.  And this guarantee requires that the root rcu_node structure's
->gp_seq field be checked instead of that of the rcu_state structure.
The problem is that the just-ending grace-period's callbacks can be
invoked between the time that the root rcu_node structure's ->gp_seq
field is updated and the time that the rcu_state structure's ->gp_seq
field is updated.  Therefore, if a single [`synchronize_rcu()`](#c-synchronize_rcu) is to
cause a subsequent [`poll_state_synchronize_rcu_full()`](#c-poll_state_synchronize_rcu_full) to return **true**,
then the root rcu_node structure is the one that needs to be polled.

#### <a id="c-cond_synchronize_rcu"></a>`cond_synchronize_rcu()`

```c
void cond_synchronize_rcu(unsigned long oldstate)
```

Conditionally wait for an RCU grace period

**Parameters**

- `unsigned long oldstate`: value from [`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu), [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu), or [`start_poll_synchronize_rcu_expedited()`](#c-start_poll_synchronize_rcu_expedited)

**Description**

If a full RCU grace period has elapsed since the earlier call to
[`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu) or [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu), just return.
Otherwise, invoke [`synchronize_rcu()`](#c-synchronize_rcu) to wait for a full grace period.

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited for
more than 2 billion grace periods (and way more on a 64-bit system!),
so waiting for a couple of additional grace periods should be just fine.

This function provides the same memory-ordering guarantees that
would be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call
to the function that provided **oldstate** and that returned at the end
of this function.

#### <a id="c-cond_synchronize_rcu_full"></a>`cond_synchronize_rcu_full()`

```c
void cond_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
```

Conditionally wait for an RCU grace period

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: value from [`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full), [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full), or [`start_poll_synchronize_rcu_expedited_full()`](#c-start_poll_synchronize_rcu_expedited_full)

**Description**

If a full RCU grace period has elapsed since the call to
[`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full), [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full),
or [`start_poll_synchronize_rcu_expedited_full()`](#c-start_poll_synchronize_rcu_expedited_full) from which **rgosp** was
obtained, just return.  Otherwise, invoke [`synchronize_rcu()`](#c-synchronize_rcu) to wait
for a full grace period.

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited for
more than 2 billion grace periods (and way more on a 64-bit system!),
so waiting for a couple of additional grace periods should be just fine.

This function provides the same memory-ordering guarantees that
would be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call
to the function that provided **rgosp** and that returned at the end of
this function.

#### <a id="c-rcu_barrier"></a>`rcu_barrier()`

```c
void rcu_barrier(void)
```

Wait until all in-flight [`call_rcu()`](#c-call_rcu) callbacks complete.

**Parameters**

- `void`: no arguments

**Description**

Note that this primitive does not necessarily wait for an RCU grace period
to complete.  For example, if there are no RCU callbacks queued anywhere
in the system, then [`rcu_barrier()`](#c-rcu_barrier) is within its rights to return
immediately, without waiting for anything, much less an RCU grace period.
In fact, [`rcu_barrier()`](#c-rcu_barrier) will normally not result in any RCU grace periods
beyond those that were already destined to be executed.

In kernels built with CONFIG_RCU_LAZY=y, this function also hurries all
pending lazy RCU callbacks.

#### <a id="c-rcu_barrier_throttled"></a>`rcu_barrier_throttled()`

```c
void rcu_barrier_throttled(void)
```

Do [`rcu_barrier()`](#c-rcu_barrier), but limit to one per second

**Parameters**

- `void`: no arguments

**Description**

This can be thought of as guard rails around [`rcu_barrier()`](#c-rcu_barrier) that
permits unrestricted userspace use, at least assuming the hardware's
`try_cmpxchg()` is robust.  There will be at most one call per second to
[`rcu_barrier()`](#c-rcu_barrier) system-wide from use of this function, which means that
callers might needlessly wait a second or three.

This is intended for use by test suites to avoid OOM by flushing RCU
callbacks from the previous test before starting the next.  See the
rcutree.do_rcu_barrier module parameter for more information.

Why not simply make [`rcu_barrier()`](#c-rcu_barrier) more scalable?  That might be
the eventual endpoint, but let's keep it simple for the time being.
Note that the module parameter infrastructure serializes calls to a
given .`set()` function, but should concurrent .`set()` invocation ever be
possible, we are ready!



#### <a id="c-synchronize_rcu_expedited"></a>`synchronize_rcu_expedited()`

```c
void synchronize_rcu_expedited(void)
```

Brute-force RCU grace period

**Parameters**

- `void`: no arguments

**Description**

Wait for an RCU grace period, but expedite it.  The basic idea is to
IPI all non-idle non-nohz online CPUs.  The IPI handler checks whether
the CPU is in an RCU critical section, and if so, it sets a flag that
causes the outermost [`rcu_read_unlock()`](#c-rcu_read_unlock) to report the quiescent state
for RCU-preempt or asks the scheduler for help for RCU-sched.  On the
other hand, if the CPU is not in an RCU read-side critical section,
the IPI handler reports the quiescent state immediately.

Although this is a great improvement over previous expedited
implementations, it is still unfriendly to real-time workloads, so is
thus not recommended for any sort of common-case code.  In fact, if
you are using [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited) in a loop, please restructure
your code to batch your updates, and then use a single [`synchronize_rcu()`](#c-synchronize_rcu)
instead.

This has the same semantics as (but is more brutal than) [`synchronize_rcu()`](#c-synchronize_rcu).

#### <a id="c-start_poll_synchronize_rcu_expedited"></a>`start_poll_synchronize_rcu_expedited()`

```c
unsigned long start_poll_synchronize_rcu_expedited(void)
```

Snapshot current RCU state and start expedited grace period

**Parameters**

- `void`: no arguments

**Description**

Returns a cookie to pass to a call to [`cond_synchronize_rcu()`](#c-cond_synchronize_rcu),
[`cond_synchronize_rcu_expedited()`](#c-cond_synchronize_rcu_expedited), or [`poll_state_synchronize_rcu()`](#c-poll_state_synchronize_rcu),
allowing them to determine whether or not any sort of grace period has
elapsed in the meantime.  If the needed expedited grace period is not
already slated to start, initiates that grace period.

#### <a id="c-start_poll_synchronize_rcu_expedited_full"></a>`start_poll_synchronize_rcu_expedited_full()`

```c
void start_poll_synchronize_rcu_expedited_full(struct rcu_gp_oldstate *rgosp)
```

Take a full snapshot and start expedited grace period

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: Place to put snapshot of grace-period state

**Description**

Places the normal and expedited grace-period states in rgosp.  This
state value can be passed to a later call to [`cond_synchronize_rcu_full()`](#c-cond_synchronize_rcu_full)
or [`poll_state_synchronize_rcu_full()`](#c-poll_state_synchronize_rcu_full) to determine whether or not a
grace period (whether normal or expedited) has elapsed in the meantime.
If the needed expedited grace period is not already slated to start,
initiates that grace period.

#### <a id="c-cond_synchronize_rcu_expedited"></a>`cond_synchronize_rcu_expedited()`

```c
void cond_synchronize_rcu_expedited(unsigned long oldstate)
```

Conditionally wait for an expedited RCU grace period

**Parameters**

- `unsigned long oldstate`: value from [`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu), [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu), or [`start_poll_synchronize_rcu_expedited()`](#c-start_poll_synchronize_rcu_expedited)

**Description**

If any type of full RCU grace period has elapsed since the earlier
call to [`get_state_synchronize_rcu()`](#c-get_state_synchronize_rcu), [`start_poll_synchronize_rcu()`](#c-start_poll_synchronize_rcu),
or [`start_poll_synchronize_rcu_expedited()`](#c-start_poll_synchronize_rcu_expedited), just return.  Otherwise,
invoke [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited) to wait for a full grace period.

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited for
more than 2 billion grace periods (and way more on a 64-bit system!),
so waiting for a couple of additional grace periods should be just fine.

This function provides the same memory-ordering guarantees that
would be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call
to the function that provided **oldstate** and that returned at the end
of this function.

#### <a id="c-cond_synchronize_rcu_expedited_full"></a>`cond_synchronize_rcu_expedited_full()`

```c
void cond_synchronize_rcu_expedited_full(struct rcu_gp_oldstate *rgosp)
```

Conditionally wait for an expedited RCU grace period

**Parameters**

- `struct rcu_gp_oldstate *rgosp`: value from [`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full), [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full), or [`start_poll_synchronize_rcu_expedited_full()`](#c-start_poll_synchronize_rcu_expedited_full)

**Description**

If a full RCU grace period has elapsed since the call to
[`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full), [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full),
or [`start_poll_synchronize_rcu_expedited_full()`](#c-start_poll_synchronize_rcu_expedited_full) from which **rgosp** was
obtained, just return.  Otherwise, invoke [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited)
to wait for a full grace period.

Yes, this function does not take counter wrap into account.
But counter wrap is harmless.  If the counter wraps, we have waited for
more than 2 billion grace periods (and way more on a 64-bit system!),
so waiting for a couple of additional grace periods should be just fine.

This function provides the same memory-ordering guarantees that
would be provided by a [`synchronize_rcu()`](#c-synchronize_rcu) that was invoked at the call
to the function that provided **rgosp** and that returned at the end of
this function.



#### <a id="c-rcu_read_lock_held_common"></a>`rcu_read_lock_held_common()`

```c
bool rcu_read_lock_held_common(bool *ret)
```

might we be in RCU-sched read-side critical section?

**Parameters**

- `bool *ret`: Best guess answer if lockdep cannot be relied on

**Description**

Returns true if lockdep must be ignored, in which case `*ret` contains
the best guess described below.  Otherwise returns false, in which
case `*ret` tells the caller nothing and the caller should instead
consult lockdep.

If CONFIG_DEBUG_LOCK_ALLOC is selected, set `*ret` to nonzero iff in an
RCU-sched read-side critical section.  In absence of
CONFIG_DEBUG_LOCK_ALLOC, this assumes we are in an RCU-sched read-side
critical section unless it can prove otherwise.  Note that disabling
of preemption (including disabling irqs) counts as an RCU-sched
read-side critical section.  This is useful for debug checks in functions
that required that they be called within an RCU-sched read-side
critical section.

Check `debug_lockdep_rcu_enabled()` to prevent false positives during boot
and while lockdep is disabled.

Note that if the CPU is in the idle loop from an RCU point of view (ie:
that we are in the section between `ct_idle_enter()` and `ct_idle_exit()`)
then [`rcu_read_lock_held()`](#c-rcu_read_lock_held) sets `*ret` to false even if the CPU did an
[`rcu_read_lock()`](#c-rcu_read_lock).  The reason for this is that RCU ignores CPUs that are
in such a section, considering these as in extended quiescent state,
so such a CPU is effectively never in an RCU read-side critical section
regardless of what RCU primitives it invokes.  This state of affairs is
required --- we need to keep an RCU-free window in idle where the CPU may
possibly enter into low power mode. This way we can notice an extended
quiescent state to other CPUs that started a grace period. Otherwise
we would delay any grace period as long as we run in the idle task.

Similarly, we avoid claiming an RCU read lock held if the current
CPU is offline.

#### <a id="c-rcu_async_hurry"></a>`rcu_async_hurry()`

```c
void rcu_async_hurry(void)
```

Make future async RCU callbacks not lazy.

**Parameters**

- `void`: no arguments

**Description**

After a call to this function, future calls to [`call_rcu()`](#c-call_rcu)
will be processed in a timely fashion.

#### <a id="c-rcu_async_relax"></a>`rcu_async_relax()`

```c
void rcu_async_relax(void)
```

Make future async RCU callbacks lazy.

**Parameters**

- `void`: no arguments

**Description**

After a call to this function, future calls to [`call_rcu()`](#c-call_rcu)
will be processed in a lazy fashion.

#### <a id="c-rcu_expedite_gp"></a>`rcu_expedite_gp()`

```c
void rcu_expedite_gp(void)
```

Expedite future RCU grace periods

**Parameters**

- `void`: no arguments

**Description**

After a call to this function, future calls to [`synchronize_rcu()`](#c-synchronize_rcu) and
friends act as the corresponding [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited) function
had instead been called.

#### <a id="c-rcu_unexpedite_gp"></a>`rcu_unexpedite_gp()`

```c
void rcu_unexpedite_gp(void)
```

Cancel prior [`rcu_expedite_gp()`](#c-rcu_expedite_gp) invocation

**Parameters**

- `void`: no arguments

**Description**

Undo a prior call to [`rcu_expedite_gp()`](#c-rcu_expedite_gp).  If all prior calls to
[`rcu_expedite_gp()`](#c-rcu_expedite_gp) are undone by a subsequent call to [`rcu_unexpedite_gp()`](#c-rcu_unexpedite_gp),
and if the rcu_expedited sysfs/boot parameter is not set, then all
subsequent calls to [`synchronize_rcu()`](#c-synchronize_rcu) and friends will return to
their normal non-expedited behavior.

#### <a id="c-rcu_read_lock_held"></a>`rcu_read_lock_held()`

```c
int notrace rcu_read_lock_held(void)
```

might we be in RCU read-side critical section?

**Parameters**

- `void`: no arguments

**Description**

If CONFIG_DEBUG_LOCK_ALLOC is selected, returns nonzero iff in an RCU
read-side critical section.  In absence of CONFIG_DEBUG_LOCK_ALLOC,
this assumes we are in an RCU read-side critical section unless it can
prove otherwise.  This is useful for debug checks in functions that
require that they be called within an RCU read-side critical section.

Checks `debug_lockdep_rcu_enabled()` to prevent false positives during boot
and while lockdep is disabled.

Note that [`rcu_read_lock()`](#c-rcu_read_lock) and the matching [`rcu_read_unlock()`](#c-rcu_read_unlock) must
occur in the same context, for example, it is illegal to invoke
[`rcu_read_unlock()`](#c-rcu_read_unlock) in process context if the matching [`rcu_read_lock()`](#c-rcu_read_lock)
was invoked from within an irq handler.

Note that [`rcu_read_lock()`](#c-rcu_read_lock) is disallowed if the CPU is either idle or
offline from an RCU perspective, so check for those as well.

#### <a id="c-rcu_read_lock_bh_held"></a>`rcu_read_lock_bh_held()`

```c
int notrace rcu_read_lock_bh_held(void)
```

might we be in RCU-bh read-side critical section?

**Parameters**

- `void`: no arguments

**Description**

Check for bottom half being disabled, which covers both the
CONFIG_PROVE_RCU and not cases.  Note that if someone uses
[`rcu_read_lock_bh()`](#c-rcu_read_lock_bh), but then later enables BH, lockdep (if enabled)
will show the situation.  This is useful for debug checks in functions
that require that they be called within an RCU read-side critical
section.

Check `debug_lockdep_rcu_enabled()` to prevent false positives during boot.

Note that [`rcu_read_lock_bh()`](#c-rcu_read_lock_bh) is disallowed if the CPU is either idle or
offline from an RCU perspective, so check for those as well.

#### <a id="c-wakeme_after_rcu"></a>`wakeme_after_rcu()`

```c
void wakeme_after_rcu(struct rcu_head *head)
```

Callback function to awaken a task after grace period

**Parameters**

- `struct rcu_head *head`: Pointer to rcu_head member within rcu_synchronize structure

**Description**

Awaken the corresponding task now that a grace period has elapsed.

#### <a id="c-init_rcu_head_on_stack"></a>`init_rcu_head_on_stack()`

```c
void init_rcu_head_on_stack(struct rcu_head *head)
```

initialize on-stack rcu_head for debugobjects

**Parameters**

- `struct rcu_head *head`: pointer to rcu_head structure to be initialized

**Description**

This function informs debugobjects of a new rcu_head structure that
has been allocated as an auto variable on the stack.  This function
is not required for rcu_head structures that are statically defined or
that are dynamically allocated on the heap.  This function has no
effect for !CONFIG_DEBUG_OBJECTS_RCU_HEAD kernel builds.

#### <a id="c-destroy_rcu_head_on_stack"></a>`destroy_rcu_head_on_stack()`

```c
void destroy_rcu_head_on_stack(struct rcu_head *head)
```

destroy on-stack rcu_head for debugobjects

**Parameters**

- `struct rcu_head *head`: pointer to rcu_head structure to be initialized

**Description**

This function informs debugobjects that an on-stack rcu_head structure
is about to go out of scope.  As with [`init_rcu_head_on_stack()`](#c-init_rcu_head_on_stack), this
function is not required for rcu_head structures that are statically
defined or that are dynamically allocated on the heap.  Also as with
[`init_rcu_head_on_stack()`](#c-init_rcu_head_on_stack), this function has no effect for
!CONFIG_DEBUG_OBJECTS_RCU_HEAD kernel builds.

#### <a id="c-get_completed_synchronize_rcu"></a>`get_completed_synchronize_rcu()`

```c
unsigned long get_completed_synchronize_rcu(void)
```

Return a pre-completed polled state cookie

**Parameters**

- `void`: no arguments

**Description**

Returns a value that will always be treated by functions like
[`poll_state_synchronize_rcu()`](#c-poll_state_synchronize_rcu) as a cookie whose grace period has already
completed.



#### <a id="c-get_completed_synchronize_srcu"></a>`get_completed_synchronize_srcu()`

```c
unsigned long get_completed_synchronize_srcu(void)
```

Return a pre-completed polled state cookie

**Parameters**

- `void`: no arguments

**Description**

Returns a value that [`poll_state_synchronize_srcu()`](#c-poll_state_synchronize_srcu) will always treat
as a cookie whose grace period has already completed.

#### <a id="c-same_state_synchronize_srcu"></a>`same_state_synchronize_srcu()`

```c
bool same_state_synchronize_srcu(unsigned long oldstate1, unsigned long oldstate2)
```

Are two old-state values identical?

**Parameters**

- `unsigned long oldstate1`: First old-state value.
- `unsigned long oldstate2`: Second old-state value.

**Description**

The two old-state values must have been obtained from either
[`get_state_synchronize_srcu()`](#c-get_state_synchronize_srcu), [`start_poll_synchronize_srcu()`](#c-start_poll_synchronize_srcu), or
[`get_completed_synchronize_srcu()`](#c-get_completed_synchronize_srcu).  Returns **true** if the two values are
identical and **false** otherwise.  This allows structures whose lifetimes
are tracked by old-state values to push these values to a list header,
allowing those structures to be slightly smaller.

#### <a id="c-srcu_read_lock_held"></a>`srcu_read_lock_held()`

```c
int srcu_read_lock_held(const struct srcu_struct *ssp)
```

might we be in SRCU read-side critical section?

**Parameters**

- `const struct srcu_struct *ssp`: The srcu_struct structure to check

**Description**

If CONFIG_DEBUG_LOCK_ALLOC is selected, returns nonzero iff in an SRCU
read-side critical section.  In absence of CONFIG_DEBUG_LOCK_ALLOC,
this assumes we are in an SRCU read-side critical section unless it can
prove otherwise.

Checks `debug_lockdep_rcu_enabled()` to prevent false positives during boot
and while lockdep is disabled.

Note that SRCU is based on its own statemachine and it doesn't
relies on normal RCU, it can be called from the CPU which
is in the idle loop from an RCU point of view or offline.

#### <a id="c-srcu_dereference_check"></a>`srcu_dereference_check()`

```c
srcu_dereference_check(p, ssp, c)
```

fetch SRCU-protected pointer for later dereferencing

**Parameters**

- `p`: the pointer to fetch and protect for later dereferencing
- `ssp`: pointer to the srcu_struct, which is used to check that we
  really are in an SRCU read-side critical section.
- `c`: condition to check for update-side use

**Description**

If PROVE_RCU is enabled, invoking this outside of an RCU read-side
critical section will result in an RCU-lockdep splat, unless **c** evaluates
to 1.  The **c** argument will normally be a logical expression containing
`lockdep_is_held()` calls.

#### <a id="c-srcu_dereference"></a>`srcu_dereference()`

```c
srcu_dereference(p, ssp)
```

fetch SRCU-protected pointer for later dereferencing

**Parameters**

- `p`: the pointer to fetch and protect for later dereferencing
- `ssp`: pointer to the srcu_struct, which is used to check that we
  really are in an SRCU read-side critical section.

**Description**

Makes [`rcu_dereference_check()`](#c-rcu_dereference_check) do the dirty work.  If PROVE_RCU
is enabled, invoking this outside of an RCU read-side critical
section will result in an RCU-lockdep splat.

#### <a id="c-srcu_dereference_notrace"></a>`srcu_dereference_notrace()`

```c
srcu_dereference_notrace(p, ssp)
```

no tracing and no lockdep calls from here

**Parameters**

- `p`: the pointer to fetch and protect for later dereferencing
- `ssp`: pointer to the srcu_struct, which is used to check that we
  really are in an SRCU read-side critical section.

#### <a id="c-srcu_read_lock"></a>`srcu_read_lock()`

```c
int srcu_read_lock(struct srcu_struct *ssp)
```

register a new reader for an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter an SRCU read-side critical section.  Note that SRCU read-side
critical sections may be nested.  However, it is illegal to
call anything that waits on an SRCU grace period for the same
srcu_struct, whether directly or indirectly.  Please note that
one way to indirectly wait on an SRCU grace period is to acquire
a mutex that is held elsewhere while calling [`synchronize_srcu()`](#c-synchronize_srcu) or
[`synchronize_srcu_expedited()`](#c-synchronize_srcu_expedited).

The return value from [`srcu_read_lock()`](#c-srcu_read_lock) is guaranteed to be
non-negative.  This value must be passed unaltered to the matching
[`srcu_read_unlock()`](#c-srcu_read_unlock).  Note that [`srcu_read_lock()`](#c-srcu_read_lock) and the matching
[`srcu_read_unlock()`](#c-srcu_read_unlock) must occur in the same context, for example, it is
illegal to invoke [`srcu_read_unlock()`](#c-srcu_read_unlock) in an irq handler if the matching
[`srcu_read_lock()`](#c-srcu_read_lock) was invoked in process context.  Or, for that matter to
invoke [`srcu_read_unlock()`](#c-srcu_read_unlock) from one task and the matching [`srcu_read_lock()`](#c-srcu_read_lock)
from another.

#### <a id="c-srcu_read_lock_fast"></a>`srcu_read_lock_fast()`

```c
struct srcu_ctr __percpu * srcu_read_lock_fast(struct srcu_struct *ssp)
```

register a new reader for an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter an SRCU read-side critical section, but for a light-weight
`smp_mb()`-free reader.  See [`srcu_read_lock()`](#c-srcu_read_lock) for more information.  This
function is NMI-safe, in a manner similar to [`srcu_read_lock_nmisafe()`](#c-srcu_read_lock_nmisafe).

For [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast) to be used on an srcu_struct structure,
that structure must have been defined using either `DEFINE_SRCU_FAST()`
or `DEFINE_STATIC_SRCU_FAST()` on the one hand or initialized with
[`init_srcu_struct_fast()`](#c-init_srcu_struct_fast) on the other.  Such an srcu_struct structure
cannot be passed to any non-fast variant of srcu_read_{,un}`lock()` or
srcu_{down,up}`_read()`.  In kernels built with CONFIG_PROVE_RCU=y,
`__srcu_check_read_flavor()` will complain bitterly if you ignore this
restriction.

Grace-period auto-expediting is disabled for SRCU-fast srcu_struct
structures because SRCU-fast expedited grace periods invoke
[`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited), IPIs and all.  If you need expedited
SRCU-fast grace periods, use [`synchronize_srcu_expedited()`](#c-synchronize_srcu_expedited).

The [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast) function can be invoked only from those
contexts where RCU is watching, that is, from contexts where it would
be legal to invoke [`rcu_read_lock()`](#c-rcu_read_lock).  Otherwise, lockdep will complain.

#### <a id="c-srcu_read_lock_fast_updown"></a>`srcu_read_lock_fast_updown()`

```c
struct srcu_ctr __percpu * srcu_read_lock_fast_updown(struct srcu_struct *ssp)
```

register a new reader for an SRCU-fast-updown structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter an SRCU read-side critical section, but for a light-weight
`smp_mb()`-free reader.  See [`srcu_read_lock()`](#c-srcu_read_lock) for more information.
This function is compatible with [`srcu_down_read_fast()`](#c-srcu_down_read_fast), but is not
NMI-safe.

For [`srcu_read_lock_fast_updown()`](#c-srcu_read_lock_fast_updown) to be used on an srcu_struct
structure, that structure must have been defined using either
`DEFINE_SRCU_FAST_UPDOWN()` or `DEFINE_STATIC_SRCU_FAST_UPDOWN()` on the one
hand or initialized with [`init_srcu_struct_fast_updown()`](#c-init_srcu_struct_fast_updown) on the other.
Such an srcu_struct structure cannot be passed to any non-fast-updown
variant of srcu_read_{,un}`lock()` or srcu_{down,up}`_read()`.  In kernels
built with CONFIG_PROVE_RCU=y, `__srcu_check_read_flavor()` will complain
bitterly if you ignore this * restriction.

Grace-period auto-expediting is disabled for SRCU-fast-updown
srcu_struct structures because SRCU-fast-updown expedited grace periods
invoke [`synchronize_rcu_expedited()`](#c-synchronize_rcu_expedited), IPIs and all.  If you need expedited
SRCU-fast-updown grace periods, use [`synchronize_srcu_expedited()`](#c-synchronize_srcu_expedited).

The [`srcu_read_lock_fast_updown()`](#c-srcu_read_lock_fast_updown) function can be invoked only from
those contexts where RCU is watching, that is, from contexts where
it would be legal to invoke [`rcu_read_lock()`](#c-rcu_read_lock).  Otherwise, lockdep will
complain.

#### <a id="c-srcu_down_read_fast"></a>`srcu_down_read_fast()`

```c
struct srcu_ctr __percpu * srcu_down_read_fast(struct srcu_struct *ssp)
```

register a new reader for an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter a semaphore-like SRCU read-side critical section, but for
a light-weight `smp_mb()`-free reader.  See [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast) and
[`srcu_down_read()`](#c-srcu_down_read) for more information.

The same srcu_struct may be used concurrently by [`srcu_down_read_fast()`](#c-srcu_down_read_fast)
and [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast).  However, the same definition/initialization
requirements called out for `srcu_read_lock_safe()` apply.

#### <a id="c-srcu_read_lock_nmisafe"></a>`srcu_read_lock_nmisafe()`

```c
int srcu_read_lock_nmisafe(struct srcu_struct *ssp)
```

register a new reader for an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter an SRCU read-side critical section, but in an NMI-safe manner.
See [`srcu_read_lock()`](#c-srcu_read_lock) for more information.

If [`srcu_read_lock_nmisafe()`](#c-srcu_read_lock_nmisafe) is ever used on an srcu_struct structure,
then none of the other flavors may be used, whether before, during,
or after.

#### <a id="c-srcu_down_read"></a>`srcu_down_read()`

```c
int srcu_down_read(struct srcu_struct *ssp)
```

register a new reader for an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to register the new reader.

**Description**

Enter a semaphore-like SRCU read-side critical section.  Note that
SRCU read-side critical sections may be nested.  However, it is
illegal to call anything that waits on an SRCU grace period for the
same srcu_struct, whether directly or indirectly.  Please note that
one way to indirectly wait on an SRCU grace period is to acquire
a mutex that is held elsewhere while calling [`synchronize_srcu()`](#c-synchronize_srcu) or
[`synchronize_srcu_expedited()`](#c-synchronize_srcu_expedited).  But if you want lockdep to help you
keep this stuff straight, you should instead use [`srcu_read_lock()`](#c-srcu_read_lock).

The semaphore-like nature of [`srcu_down_read()`](#c-srcu_down_read) means that the matching
[`srcu_up_read()`](#c-srcu_up_read) can be invoked from some other context, for example,
from some other task or from an irq handler.  However, neither
[`srcu_down_read()`](#c-srcu_down_read) nor [`srcu_up_read()`](#c-srcu_up_read) may be invoked from an NMI handler.

Calls to [`srcu_down_read()`](#c-srcu_down_read) may be nested, similar to the manner in
which calls to `down_read()` may be nested.  The same srcu_struct may be
used concurrently by [`srcu_down_read()`](#c-srcu_down_read) and [`srcu_read_lock()`](#c-srcu_read_lock).

#### <a id="c-srcu_read_unlock"></a>`srcu_read_unlock()`

```c
void srcu_read_unlock(struct srcu_struct *ssp, int idx)
```

unregister a old reader from an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `int idx`: return value from corresponding [`srcu_read_lock()`](#c-srcu_read_lock).

**Description**

Exit an SRCU read-side critical section.

#### <a id="c-srcu_read_unlock_fast"></a>`srcu_read_unlock_fast()`

```c
void srcu_read_unlock_fast(struct srcu_struct *ssp, struct srcu_ctr __percpu *scp)
```

unregister a old reader from an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `struct srcu_ctr __percpu *scp`: return value from corresponding [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast).

**Description**

Exit a light-weight SRCU read-side critical section.

#### <a id="c-srcu_read_unlock_fast_updown"></a>`srcu_read_unlock_fast_updown()`

```c
void srcu_read_unlock_fast_updown(struct srcu_struct *ssp, struct srcu_ctr __percpu *scp)
```

unregister a old reader from an SRCU-fast-updown structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `struct srcu_ctr __percpu *scp`: return value from corresponding [`srcu_read_lock_fast_updown()`](#c-srcu_read_lock_fast_updown).

**Description**

Exit an SRCU-fast-updown read-side critical section.

#### <a id="c-srcu_up_read_fast"></a>`srcu_up_read_fast()`

```c
void srcu_up_read_fast(struct srcu_struct *ssp, struct srcu_ctr __percpu *scp)
```

unregister a old reader from an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `struct srcu_ctr __percpu *scp`: return value from corresponding [`srcu_read_lock_fast()`](#c-srcu_read_lock_fast).

**Description**

Exit an SRCU read-side critical section, but not necessarily from
the same context as the maching [`srcu_down_read_fast()`](#c-srcu_down_read_fast).

#### <a id="c-srcu_read_unlock_nmisafe"></a>`srcu_read_unlock_nmisafe()`

```c
void srcu_read_unlock_nmisafe(struct srcu_struct *ssp, int idx)
```

unregister a old reader from an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `int idx`: return value from corresponding [`srcu_read_lock_nmisafe()`](#c-srcu_read_lock_nmisafe).

**Description**

Exit an SRCU read-side critical section, but in an NMI-safe manner.

#### <a id="c-srcu_up_read"></a>`srcu_up_read()`

```c
void srcu_up_read(struct srcu_struct *ssp, int idx)
```

unregister a old reader from an SRCU-protected structure.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in which to unregister the old reader.
- `int idx`: return value from corresponding [`srcu_read_lock()`](#c-srcu_read_lock).

**Description**

Exit an SRCU read-side critical section, but not necessarily from
the same context as the maching [`srcu_down_read()`](#c-srcu_down_read).

#### <a id="c-smp_mb__after_srcu_read_unlock"></a>`smp_mb__after_srcu_read_unlock()`

```c
void smp_mb__after_srcu_read_unlock(void)
```

ensure full ordering after srcu_read_unlock

**Parameters**

- `void`: no arguments

**Description**

Converts the preceding srcu_read_unlock into a two-way memory barrier.

Call this after srcu_read_unlock, to guarantee that all memory operations
that occur after smp_mb__after_srcu_read_unlock will appear to happen after
the preceding srcu_read_unlock.

#### <a id="c-smp_mb__after_srcu_read_lock"></a>`smp_mb__after_srcu_read_lock()`

```c
void smp_mb__after_srcu_read_lock(void)
```

ensure full ordering after srcu_read_lock

**Parameters**

- `void`: no arguments

**Description**

Converts the preceding srcu_read_lock into a two-way memory barrier.

Call this after srcu_read_lock, to guarantee that all memory operations
that occur after smp_mb__after_srcu_read_lock will appear to happen after
the preceding srcu_read_lock.



#### <a id="c-init_srcu_struct"></a>`init_srcu_struct()`

```c
int init_srcu_struct(struct srcu_struct *ssp)
```

initialize a sleep-RCU structure

**Parameters**

- `struct srcu_struct *ssp`: structure to initialize.

**Description**

Use this in place of `DEFINE_SRCU()` and `DEFINE_STATIC_SRCU()`
for non-static srcu_struct structures that are to be passed to
[`srcu_read_lock()`](#c-srcu_read_lock), [`srcu_read_lock_nmisafe()`](#c-srcu_read_lock_nmisafe), and friends.  It is necessary
to invoke this on a given srcu_struct before passing that srcu_struct
to any other function.  Each srcu_struct represents a separate domain
of SRCU protection.

#### <a id="c-init_srcu_struct_fast"></a>`init_srcu_struct_fast()`

```c
int init_srcu_struct_fast(struct srcu_struct *ssp)
```

initialize a fast-reader sleep-RCU structure

**Parameters**

- `struct srcu_struct *ssp`: structure to initialize.

**Description**

Use this in place of `DEFINE_SRCU_FAST()` and `DEFINE_STATIC_SRCU_FAST()`
for non-static srcu_struct structures that are to be passed to
[`srcu_read_lock_fast()`](#c-srcu_read_lock_fast) and friends.  It is necessary to invoke this on a
given srcu_struct before passing that srcu_struct to any other function.
Each srcu_struct represents a separate domain of SRCU protection.

#### <a id="c-init_srcu_struct_fast_updown"></a>`init_srcu_struct_fast_updown()`

```c
int init_srcu_struct_fast_updown(struct srcu_struct *ssp)
```

initialize a fast-reader up/down sleep-RCU structure

**Parameters**

- `struct srcu_struct *ssp`: structure to initialize.

**Description**

Use this function in place of `DEFINE_SRCU_FAST_UPDOWN()` and
`DEFINE_STATIC_SRCU_FAST_UPDOWN()` for non-static srcu_struct
structures that are to be passed to [`srcu_read_lock_fast_updown()`](#c-srcu_read_lock_fast_updown),
[`srcu_down_read_fast()`](#c-srcu_down_read_fast), and friends.  It is necessary to invoke this on a
given srcu_struct before passing that srcu_struct to any other function.
Each srcu_struct represents a separate domain of SRCU protection.

#### <a id="c-srcu_readers_active"></a>`srcu_readers_active()`

```c
bool srcu_readers_active(struct srcu_struct *ssp)
```

returns true if there are readers. and false otherwise

**Parameters**

- `struct srcu_struct *ssp`: which srcu_struct to count active readers (holding srcu_read_lock).

**Description**

Note that this is not an atomic primitive, and can therefore suffer
severe errors when invoked on an active srcu_struct.  That said, it
can be useful as an error check at cleanup time.

#### <a id="c-cleanup_srcu_struct"></a>`cleanup_srcu_struct()`

```c
void cleanup_srcu_struct(struct srcu_struct *ssp)
```

deconstruct a sleep-RCU structure

**Parameters**

- `struct srcu_struct *ssp`: structure to clean up.

**Description**

Must invoke this after you are finished using a given srcu_struct that
was initialized via [`init_srcu_struct()`](#c-init_srcu_struct), else you leak memory.

#### <a id="c-call_srcu"></a>`call_srcu()`

```c
void call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp, rcu_callback_t func)
```

Queue a callback for invocation after an SRCU grace period

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct in queue the callback
- `struct rcu_head *rhp`: structure to be used for queueing the SRCU callback.
- `rcu_callback_t func`: function to be invoked after the SRCU grace period

**Description**

The callback function will be invoked some time after a full SRCU
grace period elapses, in other words after all pre-existing SRCU
read-side critical sections have completed.  However, the callback
function might well execute concurrently with other SRCU read-side
critical sections that started after [`call_srcu()`](#c-call_srcu) was invoked.  SRCU
read-side critical sections are delimited by [`srcu_read_lock()`](#c-srcu_read_lock) and
[`srcu_read_unlock()`](#c-srcu_read_unlock), and may be nested.

The callback will be invoked from process context, but with bh
disabled.  The callback function must therefore be fast and must
not block.

See the description of [`call_rcu()`](#c-call_rcu) for more detailed information on
memory ordering guarantees.

#### <a id="c-synchronize_srcu_expedited"></a>`synchronize_srcu_expedited()`

```c
void synchronize_srcu_expedited(struct srcu_struct *ssp)
```

Brute-force SRCU grace period

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct with which to synchronize.

**Description**

Wait for an SRCU grace period to elapse, but be more aggressive about
spinning rather than blocking when waiting.

Note that [`synchronize_srcu_expedited()`](#c-synchronize_srcu_expedited) has the same deadlock and
memory-ordering properties as does [`synchronize_srcu()`](#c-synchronize_srcu).

#### <a id="c-synchronize_srcu"></a>`synchronize_srcu()`

```c
void synchronize_srcu(struct srcu_struct *ssp)
```

wait for prior SRCU read-side critical-section completion

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct with which to synchronize.

**Description**

Wait for the count to drain to zero of both indexes. To avoid the
possible starvation of [`synchronize_srcu()`](#c-synchronize_srcu), it waits for the count of
the index=!(ssp->srcu_ctrp - `ssp->sda`->srcu_ctrs\[0\]) to drain to zero
at first, and then flip the ->srcu_ctrp and wait for the count of the
other index.

Can block; must be called from process context.

Note that it is illegal to call [`synchronize_srcu()`](#c-synchronize_srcu) from the corresponding
SRCU read-side critical section; doing so will result in deadlock.
However, it is perfectly legal to call [`synchronize_srcu()`](#c-synchronize_srcu) on one
srcu_struct from some other srcu_struct's read-side critical section,
as long as the resulting graph of srcu_structs is acyclic.

There are memory-ordering constraints implied by [`synchronize_srcu()`](#c-synchronize_srcu).
On systems with more than one CPU, when [`synchronize_srcu()`](#c-synchronize_srcu) returns,
each CPU is guaranteed to have executed a full memory barrier since
the end of its last corresponding SRCU read-side critical section
whose beginning preceded the call to [`synchronize_srcu()`](#c-synchronize_srcu).  In addition,
each CPU having an SRCU read-side critical section that extends beyond
the return from [`synchronize_srcu()`](#c-synchronize_srcu) is guaranteed to have executed a
full memory barrier after the beginning of [`synchronize_srcu()`](#c-synchronize_srcu) and before
the beginning of that SRCU read-side critical section.  Note that these
guarantees include CPUs that are offline, idle, or executing in user mode,
as well as CPUs that are executing in the kernel.

Furthermore, if CPU A invoked [`synchronize_srcu()`](#c-synchronize_srcu), which returned
to its caller on CPU B, then both CPU A and CPU B are guaranteed
to have executed a full memory barrier during the execution of
[`synchronize_srcu()`](#c-synchronize_srcu).  This guarantee applies even if CPU A and CPU B
are the same CPU, but again only if the system has more than one CPU.

Of course, these memory-ordering guarantees apply only when
[`synchronize_srcu()`](#c-synchronize_srcu), [`srcu_read_lock()`](#c-srcu_read_lock), and [`srcu_read_unlock()`](#c-srcu_read_unlock) are
passed the same srcu_struct structure.

Implementation of these memory-ordering guarantees is similar to
that of [`synchronize_rcu()`](#c-synchronize_rcu).

If SRCU is likely idle as determined by `srcu_should_expedite()`,
expedite the first request.  This semantic was provided by Classic SRCU,
and is relied upon by its users, so TREE SRCU must also provide it.
Note that detecting idleness is heuristic and subject to both false
positives and negatives.

#### <a id="c-get_state_synchronize_srcu"></a>`get_state_synchronize_srcu()`

```c
unsigned long get_state_synchronize_srcu(struct srcu_struct *ssp)
```

Provide an end-of-grace-period cookie

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct to provide cookie for.

**Description**

This function returns a cookie that can be passed to
[`poll_state_synchronize_srcu()`](#c-poll_state_synchronize_srcu), which will return true if a full grace
period has elapsed in the meantime.  It is the caller's responsibility
to make sure that grace period happens, for example, by invoking
[`call_srcu()`](#c-call_srcu) after return from [`get_state_synchronize_srcu()`](#c-get_state_synchronize_srcu).

#### <a id="c-start_poll_synchronize_srcu"></a>`start_poll_synchronize_srcu()`

```c
unsigned long start_poll_synchronize_srcu(struct srcu_struct *ssp)
```

Provide cookie and start grace period

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct to provide cookie for.

**Description**

This function returns a cookie that can be passed to
[`poll_state_synchronize_srcu()`](#c-poll_state_synchronize_srcu), which will return true if a full grace
period has elapsed in the meantime.  Unlike [`get_state_synchronize_srcu()`](#c-get_state_synchronize_srcu),
this function also ensures that any needed SRCU grace period will be
started.  This convenience does come at a cost in terms of CPU overhead.

#### <a id="c-poll_state_synchronize_srcu"></a>`poll_state_synchronize_srcu()`

```c
bool poll_state_synchronize_srcu(struct srcu_struct *ssp, unsigned long cookie)
```

Has cookie's grace period ended?

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct to provide cookie for.
- `unsigned long cookie`: Return value from [`get_state_synchronize_srcu()`](#c-get_state_synchronize_srcu) or [`start_poll_synchronize_srcu()`](#c-start_poll_synchronize_srcu).

**Description**

This function takes the cookie that was returned from either
[`get_state_synchronize_srcu()`](#c-get_state_synchronize_srcu) or [`start_poll_synchronize_srcu()`](#c-start_poll_synchronize_srcu), and
returns **true** if an SRCU grace period elapsed since the time that the
cookie was created.

Because cookies are finite in size, wrapping/overflow is possible.
This is more pronounced on 32-bit systems where cookies are 32 bits,
where in theory wrapping could happen in about 14 hours assuming
25-microsecond expedited SRCU grace periods.  However, a more likely
overflow lower bound is on the order of 24 days in the case of
one-millisecond SRCU grace periods.  Of course, wrapping in a 64-bit
system requires geologic timespans, as in more than seven million years
even for expedited SRCU grace periods.

Wrapping/overflow is much more of an issue for CONFIG_SMP=n systems
that also have CONFIG_PREEMPTION=n, which selects Tiny SRCU.  This uses
a 16-bit cookie, which rcutorture routinely wraps in a matter of a
few minutes.  If this proves to be a problem, this counter will be
expanded to the same size as for Tree SRCU.

#### <a id="c-srcu_barrier"></a>`srcu_barrier()`

```c
void srcu_barrier(struct srcu_struct *ssp)
```

Wait until all in-flight [`call_srcu()`](#c-call_srcu) callbacks complete.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct on which to wait for in-flight callbacks.

#### <a id="c-srcu_expedite_current"></a>`srcu_expedite_current()`

```c
void srcu_expedite_current(struct srcu_struct *ssp)
```

Expedite the current SRCU grace period

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct to expedite.

**Description**

Cause the current SRCU grace period to become expedited.  The grace
period following the current one might also be expedited.  If there is
no current grace period, one might be created.  If the current grace
period is currently sleeping, that sleep will complete before expediting
will take effect.

#### <a id="c-srcu_batches_completed"></a>`srcu_batches_completed()`

```c
unsigned long srcu_batches_completed(struct srcu_struct *ssp)
```

return batches completed.

**Parameters**

- `struct srcu_struct *ssp`: srcu_struct on which to report batch completion.

**Description**

Report the number of batches, correlated with, but not necessarily
precisely the same as, the number of grace periods that have elapsed.



#### <a id="c-hlist_bl_del_rcu"></a>`hlist_bl_del_rcu()`

```c
void hlist_bl_del_rcu(struct hlist_bl_node *n)
```

deletes entry from hash list without re-initialization

**Parameters**

- `struct hlist_bl_node *n`: the element to delete from the hash list.

**Note**

`hlist_bl_unhashed()` on entry does not return true after this,
the entry is in an undefined state. It is useful for RCU based
lockfree traversal.

In particular, it means that we can not poison the forward
pointers that may still be used for walking the hash list.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_bl_add_head_rcu()`](#c-hlist_bl_add_head_rcu)
or [`hlist_bl_del_rcu()`](#c-hlist_bl_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
`hlist_bl_for_each_entry()`.

#### <a id="c-hlist_bl_add_head_rcu"></a>`hlist_bl_add_head_rcu()`

```c
void hlist_bl_add_head_rcu(struct hlist_bl_node *n, struct hlist_bl_head *h)
```

**Parameters**

- `struct hlist_bl_node *n`: the element to add to the hash list.
- `struct hlist_bl_head *h`: the list to add to.

**Description**

Adds the specified element to the specified hlist_bl,
while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_bl_add_head_rcu()`](#c-hlist_bl_add_head_rcu)
or [`hlist_bl_del_rcu()`](#c-hlist_bl_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_bl_for_each_entry_rcu()`](#c-hlist_bl_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.  Regardless of the type of CPU, the
list-traversal primitive must be guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_bl_for_each_entry_rcu"></a>`hlist_bl_for_each_entry_rcu()`

```c
hlist_bl_for_each_entry_rcu(tpos, pos, head, member)
```

iterate over rcu list of given type

**Parameters**

- `tpos`: the type * to use as a loop cursor.
- `pos`: the `struct hlist_bl_node` to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_bl_node within the struct.



#### <a id="c-list_for_each_rcu"></a>`list_for_each_rcu()`

```c
list_for_each_rcu(pos, head)
```

Iterate over a list in an RCU-safe fashion

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `head`: the head for your list.

#### <a id="c-list_tail_rcu"></a>`list_tail_rcu()`

```c
list_tail_rcu(head)
```

returns the prev pointer of the head of the list

**Parameters**

- `head`: the head of the list

**Note**

This should only be used with the list header, and even then
only if [`list_del()`](/kernel/internals/core-api/list.md#c-list_del) and similar primitives are not also used on the
list header.

#### <a id="c-list_add_rcu"></a>`list_add_rcu()`

```c
void list_add_rcu(struct list_head *new, struct list_head *head)
```

add a new entry to rcu-protected list

**Parameters**

- `struct list_head *new`: new entry to be added
- `struct list_head *head`: list head to add it after

**Description**

Insert a new entry after the specified head.
This is good for implementing stacks.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`list_add_rcu()`](#c-list_add_rcu)
or [`list_del_rcu()`](#c-list_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`list_for_each_entry_rcu()`](#c-list_for_each_entry_rcu).

#### <a id="c-list_add_tail_rcu"></a>`list_add_tail_rcu()`

```c
void list_add_tail_rcu(struct list_head *new, struct list_head *head)
```

add a new entry to rcu-protected list

**Parameters**

- `struct list_head *new`: new entry to be added
- `struct list_head *head`: list head to add it before

**Description**

Insert a new entry before the specified head.
This is useful for implementing queues.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`list_add_tail_rcu()`](#c-list_add_tail_rcu)
or [`list_del_rcu()`](#c-list_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`list_for_each_entry_rcu()`](#c-list_for_each_entry_rcu).

#### <a id="c-list_del_rcu"></a>`list_del_rcu()`

```c
void list_del_rcu(struct list_head *entry)
```

deletes entry from list without re-initialization

**Parameters**

- `struct list_head *entry`: the element to delete from the list.

**Note**

[`list_empty()`](/kernel/internals/core-api/list.md#c-list_empty) on entry does not return true after this,
the entry is in an undefined state. It is useful for RCU based
lockfree traversal.

In particular, it means that we can not poison the forward
pointers that may still be used for walking the list.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`list_del_rcu()`](#c-list_del_rcu)
or [`list_add_rcu()`](#c-list_add_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`list_for_each_entry_rcu()`](#c-list_for_each_entry_rcu).

Note that the caller is not permitted to immediately free
the newly deleted entry.  Instead, either [`synchronize_rcu()`](#c-synchronize_rcu)
or [`call_rcu()`](#c-call_rcu) must be used to defer freeing until an RCU
grace period has elapsed.

#### <a id="c-list_bidir_del_rcu"></a>`list_bidir_del_rcu()`

```c
void list_bidir_del_rcu(struct list_head *entry)
```

deletes entry from list without re-initialization

**Parameters**

- `struct list_head *entry`: the element to delete from the list.

**Description**

In contrast to [`list_del_rcu()`](#c-list_del_rcu) doesn't poison the prev pointer thus
allowing backwards traversal via `list_bidir_prev_rcu()`.

**Note**

[`list_empty()`](/kernel/internals/core-api/list.md#c-list_empty) on entry does not return true after this because
the entry is in a special undefined state that permits RCU-based
lockfree reverse traversal. In particular this means that we can not
poison the forward and backwards pointers that may still be used for
walking the list.

The caller must take whatever precautions are necessary (such as
holding appropriate locks) to avoid racing with another list-mutation
primitive, such as [`list_bidir_del_rcu()`](#c-list_bidir_del_rcu) or [`list_add_rcu()`](#c-list_add_rcu), running on
this same list. However, it is perfectly legal to run concurrently
with the _rcu list-traversal primitives, such as
[`list_for_each_entry_rcu()`](#c-list_for_each_entry_rcu).

Note that [`list_del_rcu()`](#c-list_del_rcu) and [`list_bidir_del_rcu()`](#c-list_bidir_del_rcu) must not be used on
the same list.

Note that the caller is not permitted to immediately free
the newly deleted entry.  Instead, either [`synchronize_rcu()`](#c-synchronize_rcu)
or [`call_rcu()`](#c-call_rcu) must be used to defer freeing until an RCU
grace period has elapsed.

#### <a id="c-hlist_del_init_rcu"></a>`hlist_del_init_rcu()`

```c
void hlist_del_init_rcu(struct hlist_node *n)
```

deletes entry from hash list with re-initialization

**Parameters**

- `struct hlist_node *n`: the element to delete from the hash list.

**Note**

`list_unhashed()` on the node return true after this. It is
useful for RCU based read lockfree traversal if the writer side
must know if the list entry is still hashed or already unhashed.

In particular, it means that we can not poison the forward pointers
that may still be used for walking the hash list and we can only
zero the pprev pointer so `list_unhashed()` will return true after
this.

The caller must take whatever precautions are necessary (such as
holding appropriate locks) to avoid racing with another
list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu) or
[`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.  However, it is
perfectly legal to run concurrently with the _rcu list-traversal
primitives, such as [`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu).

#### <a id="c-list_replace_rcu"></a>`list_replace_rcu()`

```c
void list_replace_rcu(struct list_head *old, struct list_head *new)
```

replace old entry by new one

**Parameters**

- `struct list_head *old`: the element to be replaced
- `struct list_head *new`: the new element to insert

**Description**

The **old** entry will be replaced with the **new** entry atomically from
the perspective of concurrent readers.  It is the caller's responsibility
to synchronize with concurrent updaters, if any.

**Note**

**old** should not be empty.

#### <a id="c-__list_splice_init_rcu"></a>`__list_splice_init_rcu()`

```c
void __list_splice_init_rcu(struct list_head *list, struct list_head *prev, struct list_head *next, void (*sync)(void))
```

join an RCU-protected list into an existing list.

**Parameters**

- `struct list_head *list`: the RCU-protected list to splice
- `struct list_head *prev`: points to the last element of the existing list
- `struct list_head *next`: points to the first element of the existing list
- `void (*sync)(void)`: synchronize_rcu, synchronize_rcu_expedited, ...

**Description**

The list pointed to by **prev** and **next** can be RCU-read traversed
concurrently with this function.

Note that this function blocks.

Important note: the caller must take whatever action is necessary to prevent
any other updates to the existing list.  In principle, it is possible to
modify the list as soon as `sync()` begins execution. If this sort of thing
becomes necessary, an alternative version based on [`call_rcu()`](#c-call_rcu) could be
created.  But only if -really- needed -- there is no shortage of RCU API
members.

#### <a id="c-list_splice_init_rcu"></a>`list_splice_init_rcu()`

```c
void list_splice_init_rcu(struct list_head *list, struct list_head *head, void (*sync)(void))
```

splice an RCU-protected list into an existing list, designed for stacks.

**Parameters**

- `struct list_head *list`: the RCU-protected list to splice
- `struct list_head *head`: the place in the existing list to splice the first list into
- `void (*sync)(void)`: synchronize_rcu, synchronize_rcu_expedited, ...

#### <a id="c-list_splice_tail_init_rcu"></a>`list_splice_tail_init_rcu()`

```c
void list_splice_tail_init_rcu(struct list_head *list, struct list_head *head, void (*sync)(void))
```

splice an RCU-protected list into an existing list, designed for queues.

**Parameters**

- `struct list_head *list`: the RCU-protected list to splice
- `struct list_head *head`: the place in the existing list to splice the first list into
- `void (*sync)(void)`: synchronize_rcu, synchronize_rcu_expedited, ...

#### <a id="c-list_entry_rcu"></a>`list_entry_rcu()`

```c
list_entry_rcu(ptr, type, member)
```

get the struct for this entry

**Parameters**

- `ptr`: the `struct list_head` pointer.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

This primitive may safely run concurrently with the _rcu list-mutation
primitives such as [`list_add_rcu()`](#c-list_add_rcu) as long as it's guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-list_first_or_null_rcu"></a>`list_first_or_null_rcu()`

```c
list_first_or_null_rcu(ptr, type, member)
```

get the first element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note that if the list is empty, it returns NULL.

This primitive may safely run concurrently with the _rcu list-mutation
primitives such as [`list_add_rcu()`](#c-list_add_rcu) as long as it's guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-list_next_or_null_rcu"></a>`list_next_or_null_rcu()`

```c
list_next_or_null_rcu(head, ptr, type, member)
```

get the next element from a list

**Parameters**

- `head`: the head for the list.
- `ptr`: the list head to take the next element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note that if the ptr is at the end of the list, NULL is returned.

This primitive may safely run concurrently with the _rcu list-mutation
primitives such as [`list_add_rcu()`](#c-list_add_rcu) as long as it's guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-list_for_each_entry_rcu"></a>`list_for_each_entry_rcu()`

```c
list_for_each_entry_rcu(pos, head, member, cond...)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.
- `cond...`: optional lockdep expression if called from non-RCU protection.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`list_add_rcu()`](#c-list_add_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-list_for_each_entry_srcu"></a>`list_for_each_entry_srcu()`

```c
list_for_each_entry_srcu(pos, head, member, cond)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.
- `cond`: lockdep expression for the lock required to traverse the list.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`list_add_rcu()`](#c-list_add_rcu)
as long as the traversal is guarded by [`srcu_read_lock()`](#c-srcu_read_lock).
The lockdep expression [`srcu_read_lock_held()`](#c-srcu_read_lock_held) can be passed as the
cond argument from read side.

#### <a id="c-list_entry_lockless"></a>`list_entry_lockless()`

```c
list_entry_lockless(ptr, type, member)
```

get the struct for this entry

**Parameters**

- `ptr`: the `struct list_head` pointer.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

This primitive may safely run concurrently with the _rcu
list-mutation primitives such as [`list_add_rcu()`](#c-list_add_rcu), but requires some
implicit RCU read-side guarding.  One example is running within a special
exception-time environment where preemption is disabled and where lockdep
cannot be invoked.  Another example is when items are added to the list,
but never deleted.

#### <a id="c-list_for_each_entry_lockless"></a>`list_for_each_entry_lockless()`

```c
list_for_each_entry_lockless(pos, head, member)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_struct within the struct.

**Description**

This primitive may safely run concurrently with the _rcu
list-mutation primitives such as [`list_add_rcu()`](#c-list_add_rcu), but requires some
implicit RCU read-side guarding.  One example is running within a special
exception-time environment where preemption is disabled and where lockdep
cannot be invoked.  Another example is when items are added to the list,
but never deleted.

#### <a id="c-list_for_each_entry_continue_rcu"></a>`list_for_each_entry_continue_rcu()`

```c
list_for_each_entry_continue_rcu(pos, head, member)
```

continue iteration over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Continue to iterate over list of given type, continuing after
the current position which must have been in the list when the RCU read
lock was taken.
This would typically require either that you obtained the node from a
previous walk of the list in the same RCU read-side critical section, or
that you held some sort of non-RCU reference (such as a reference count)
to keep the node alive *and* in the list.

This iterator is similar to [`list_for_each_entry_from_rcu()`](#c-list_for_each_entry_from_rcu) except
this starts after the given position and that one starts at the given
position.

#### <a id="c-list_for_each_entry_from_rcu"></a>`list_for_each_entry_from_rcu()`

```c
list_for_each_entry_from_rcu(pos, head, member)
```

iterate over a list from current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_node within the struct.

**Description**

Iterate over the tail of a list starting from a given position,
which must have been in the list when the RCU read lock was taken.
This would typically require either that you obtained the node from a
previous walk of the list in the same RCU read-side critical section, or
that you held some sort of non-RCU reference (such as a reference count)
to keep the node alive *and* in the list.

This iterator is similar to [`list_for_each_entry_continue_rcu()`](#c-list_for_each_entry_continue_rcu) except
this starts from the given position and that one starts from the position
after the given position.

#### <a id="c-hlist_del_rcu"></a>`hlist_del_rcu()`

```c
void hlist_del_rcu(struct hlist_node *n)
```

deletes entry from hash list without re-initialization

**Parameters**

- `struct hlist_node *n`: the element to delete from the hash list.

**Note**

`list_unhashed()` on entry does not return true after this,
the entry is in an undefined state. It is useful for RCU based
lockfree traversal.

In particular, it means that we can not poison the forward
pointers that may still be used for walking the hash list.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
or [`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_for_each_entry()`](/kernel/internals/core-api/list.md#c-hlist_for_each_entry).

#### <a id="c-hlist_replace_rcu"></a>`hlist_replace_rcu()`

```c
void hlist_replace_rcu(struct hlist_node *old, struct hlist_node *new)
```

replace old entry by new one

**Parameters**

- `struct hlist_node *old`: the element to be replaced
- `struct hlist_node *new`: the new element to insert

**Description**

The **old** entry will be replaced with the **new** entry atomically from
the perspective of concurrent readers.  It is the caller's responsibility
to synchronize with concurrent updaters, if any.

#### <a id="c-hlists_swap_heads_rcu"></a>`hlists_swap_heads_rcu()`

```c
void hlists_swap_heads_rcu(struct hlist_head *left, struct hlist_head *right)
```

swap the lists the hlist heads point to

**Parameters**

- `struct hlist_head *left`: The hlist head on the left
- `struct hlist_head *right`: The hlist head on the right

**Description**

- The lists start out as \[**left**  \]\[node1 ... \] and

  \[**right** \]\[node2 ... \]
- The lists end up as    \[**left**  \]\[node2 ... \]

  \[**right** \]\[node1 ... \]

#### <a id="c-hlist_add_head_rcu"></a>`hlist_add_head_rcu()`

```c
void hlist_add_head_rcu(struct hlist_node *n, struct hlist_head *h)
```

**Parameters**

- `struct hlist_node *n`: the element to add to the hash list.
- `struct hlist_head *h`: the list to add to.

**Description**

Adds the specified element to the specified hlist,
while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
or [`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.  Regardless of the type of CPU, the
list-traversal primitive must be guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_add_tail_rcu"></a>`hlist_add_tail_rcu()`

```c
void hlist_add_tail_rcu(struct hlist_node *n, struct hlist_head *h)
```

**Parameters**

- `struct hlist_node *n`: the element to add to the hash list.
- `struct hlist_head *h`: the list to add to.

**Description**

Adds the specified element to the specified hlist,
while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
or [`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.  Regardless of the type of CPU, the
list-traversal primitive must be guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_add_before_rcu"></a>`hlist_add_before_rcu()`

```c
void hlist_add_before_rcu(struct hlist_node *n, struct hlist_node *next)
```

**Parameters**

- `struct hlist_node *n`: the new element to add to the hash list.
- `struct hlist_node *next`: the existing element to add the new element before.

**Description**

Adds the specified element to the specified hlist
before the specified node while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
or [`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.

#### <a id="c-hlist_add_behind_rcu"></a>`hlist_add_behind_rcu()`

```c
void hlist_add_behind_rcu(struct hlist_node *n, struct hlist_node *prev)
```

**Parameters**

- `struct hlist_node *n`: the new element to add to the hash list.
- `struct hlist_node *prev`: the existing element to add the new element after.

**Description**

Adds the specified element to the specified hlist
after the specified node while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
or [`hlist_del_rcu()`](#c-hlist_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.

#### <a id="c-hlist_for_each_entry_rcu"></a>`hlist_for_each_entry_rcu()`

```c
hlist_for_each_entry_rcu(pos, head, member, cond...)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.
- `cond...`: optional lockdep expression if called from non-RCU protection.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_for_each_entry_srcu"></a>`hlist_for_each_entry_srcu()`

```c
hlist_for_each_entry_srcu(pos, head, member, cond)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.
- `cond`: lockdep expression for the lock required to traverse the list.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`srcu_read_lock()`](#c-srcu_read_lock).
The lockdep expression [`srcu_read_lock_held()`](#c-srcu_read_lock_held) can be passed as the
cond argument from read side.

#### <a id="c-hlist_for_each_entry_rcu_notrace"></a>`hlist_for_each_entry_rcu_notrace()`

```c
hlist_for_each_entry_rcu_notrace(pos, head, member)
```

iterate over rcu list of given type (for tracing)

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

This is the same as [`hlist_for_each_entry_rcu()`](#c-hlist_for_each_entry_rcu) except that it does
not do any RCU debugging or tracing.

#### <a id="c-hlist_for_each_entry_rcu_bh"></a>`hlist_for_each_entry_rcu_bh()`

```c
hlist_for_each_entry_rcu_bh(pos, head, member)
```

iterate over rcu list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.

**Description**

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_for_each_entry_continue_rcu"></a>`hlist_for_each_entry_continue_rcu()`

```c
hlist_for_each_entry_continue_rcu(pos, member)
```

iterate over a hlist continuing after current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_for_each_entry_continue_rcu_bh"></a>`hlist_for_each_entry_continue_rcu_bh()`

```c
hlist_for_each_entry_continue_rcu_bh(pos, member)
```

iterate over a hlist continuing after current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_for_each_entry_from_rcu"></a>`hlist_for_each_entry_from_rcu()`

```c
hlist_for_each_entry_from_rcu(pos, member)
```

iterate over a hlist continuing from current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `member`: the name of the hlist_node within the struct.



#### <a id="c-hlist_nulls_del_init_rcu"></a>`hlist_nulls_del_init_rcu()`

```c
void hlist_nulls_del_init_rcu(struct hlist_nulls_node *n)
```

deletes entry from hash list with re-initialization

**Parameters**

- `struct hlist_nulls_node *n`: the element to delete from the hash list.

**Note**

`hlist_nulls_unhashed()` on the node return true after this. It is
useful for RCU based read lockfree traversal if the writer side
must know if the list entry is still hashed or already unhashed.

In particular, it means that we can not poison the forward pointers
that may still be used for walking the hash list and we can only
zero the pprev pointer so `list_unhashed()` will return true after
this.

The caller must take whatever precautions are necessary (such as
holding appropriate locks) to avoid racing with another
list-mutation primitive, such as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu) or
[`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same list.  However, it is
perfectly legal to run concurrently with the _rcu list-traversal
primitives, such as [`hlist_nulls_for_each_entry_rcu()`](#c-hlist_nulls_for_each_entry_rcu).

#### <a id="c-hlist_nulls_first_rcu"></a>`hlist_nulls_first_rcu()`

```c
hlist_nulls_first_rcu(head)
```

returns the first element of the hash list.

**Parameters**

- `head`: the head of the list.

#### <a id="c-hlist_nulls_next_rcu"></a>`hlist_nulls_next_rcu()`

```c
hlist_nulls_next_rcu(node)
```

returns the element of the list after **node**.

**Parameters**

- `node`: element of the list.

#### <a id="c-hlist_nulls_pprev_rcu"></a>`hlist_nulls_pprev_rcu()`

```c
hlist_nulls_pprev_rcu(node)
```

returns the dereferenced pprev of **node**.

**Parameters**

- `node`: element of the list.

#### <a id="c-hlist_nulls_del_rcu"></a>`hlist_nulls_del_rcu()`

```c
void hlist_nulls_del_rcu(struct hlist_nulls_node *n)
```

deletes entry from hash list without re-initialization

**Parameters**

- `struct hlist_nulls_node *n`: the element to delete from the hash list.

**Note**

`hlist_nulls_unhashed()` on entry does not return true after this,
the entry is in an undefined state. It is useful for RCU based
lockfree traversal.

In particular, it means that we can not poison the forward
pointers that may still be used for walking the hash list.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu)
or [`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
`hlist_nulls_for_each_entry()`.

#### <a id="c-hlist_nulls_add_head_rcu"></a>`hlist_nulls_add_head_rcu()`

```c
void hlist_nulls_add_head_rcu(struct hlist_nulls_node *n, struct hlist_nulls_head *h)
```

**Parameters**

- `struct hlist_nulls_node *n`: the element to add to the hash list.
- `struct hlist_nulls_head *h`: the list to add to.

**Description**

Adds the specified element to the specified hlist_nulls,
while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu)
or [`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_nulls_for_each_entry_rcu()`](#c-hlist_nulls_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.  Regardless of the type of CPU, the
list-traversal primitive must be guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_nulls_add_tail_rcu"></a>`hlist_nulls_add_tail_rcu()`

```c
void hlist_nulls_add_tail_rcu(struct hlist_nulls_node *n, struct hlist_nulls_head *h)
```

**Parameters**

- `struct hlist_nulls_node *n`: the element to add to the hash list.
- `struct hlist_nulls_head *h`: the list to add to.

**Description**

Adds the specified element to the specified hlist_nulls,
while permitting racing traversals.

The caller must take whatever precautions are necessary
(such as holding appropriate locks) to avoid racing
with another list-mutation primitive, such as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu)
or [`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same list.
However, it is perfectly legal to run concurrently with
the _rcu list-traversal primitives, such as
[`hlist_nulls_for_each_entry_rcu()`](#c-hlist_nulls_for_each_entry_rcu), used to prevent memory-consistency
problems on Alpha CPUs.  Regardless of the type of CPU, the
list-traversal primitive must be guarded by [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-hlist_nulls_replace_rcu"></a>`hlist_nulls_replace_rcu()`

```c
void hlist_nulls_replace_rcu(struct hlist_nulls_node *old, struct hlist_nulls_node *new)
```

replace an old entry by a new one

**Parameters**

- `struct hlist_nulls_node *old`: the element to be replaced
- `struct hlist_nulls_node *new`: the new element to insert

**Description**

Replace the old entry with the new one in a RCU-protected hlist_nulls, while
permitting racing traversals.

The caller must take whatever precautions are necessary (such as holding
appropriate locks) to avoid racing with another list-mutation primitive, such
as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu) or [`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same
list.  However, it is perfectly legal to run concurrently with the _rcu
list-traversal primitives, such as [`hlist_nulls_for_each_entry_rcu()`](#c-hlist_nulls_for_each_entry_rcu).

#### <a id="c-hlist_nulls_replace_init_rcu"></a>`hlist_nulls_replace_init_rcu()`

```c
void hlist_nulls_replace_init_rcu(struct hlist_nulls_node *old, struct hlist_nulls_node *new)
```

replace an old entry by a new one and initialize the old

**Parameters**

- `struct hlist_nulls_node *old`: the element to be replaced
- `struct hlist_nulls_node *new`: the new element to insert

**Description**

Replace the old entry with the new one in a RCU-protected hlist_nulls, while
permitting racing traversals, and reinitialize the old entry.

**Note**

**old** must be hashed.

The caller must take whatever precautions are necessary (such as holding
appropriate locks) to avoid racing with another list-mutation primitive, such
as [`hlist_nulls_add_head_rcu()`](#c-hlist_nulls_add_head_rcu) or [`hlist_nulls_del_rcu()`](#c-hlist_nulls_del_rcu), running on this same
list. However, it is perfectly legal to run concurrently with the _rcu
list-traversal primitives, such as [`hlist_nulls_for_each_entry_rcu()`](#c-hlist_nulls_for_each_entry_rcu).

#### <a id="c-hlist_nulls_for_each_entry_rcu"></a>`hlist_nulls_for_each_entry_rcu()`

```c
hlist_nulls_for_each_entry_rcu(tpos, pos, head, member)
```

iterate over rcu list of given type

**Parameters**

- `tpos`: the type * to use as a loop cursor.
- `pos`: the `struct hlist_nulls_node` to use as a loop cursor.
- `head`: the head of the list.
- `member`: the name of the hlist_nulls_node within the struct.

**Description**

The `barrier()` is needed to make sure compiler doesn't cache first element \[1\],
as this loop can be restarted \[2\]
\[1\] Documentation/memory-barriers.txt around line 1533
\[2\] Documentation/RCU/rculist_nulls.rst around line 146

#### <a id="c-hlist_nulls_for_each_entry_safe"></a>`hlist_nulls_for_each_entry_safe()`

```c
hlist_nulls_for_each_entry_safe(tpos, pos, head, member)
```

iterate over list of given type safe against removal of list entry

**Parameters**

- `tpos`: the type * to use as a loop cursor.
- `pos`: the `struct hlist_nulls_node` to use as a loop cursor.
- `head`: the head of the list.
- `member`: the name of the hlist_nulls_node within the struct.



#### <a id="c-rcu_sync_is_idle"></a>`rcu_sync_is_idle()`

```c
bool rcu_sync_is_idle(struct rcu_sync *rsp)
```

Are readers permitted to use their fastpaths?

**Parameters**

- `struct rcu_sync *rsp`: Pointer to rcu_sync structure to use for synchronization

**Description**

Returns true if readers are permitted to use their fastpaths.  Must be
invoked within some flavor of RCU read-side critical section.



#### <a id="c-rcu_sync_init"></a>`rcu_sync_init()`

```c
void rcu_sync_init(struct rcu_sync *rsp)
```

Initialize an rcu_sync structure

**Parameters**

- `struct rcu_sync *rsp`: Pointer to rcu_sync structure to be initialized

#### <a id="c-rcu_sync_func"></a>`rcu_sync_func()`

```c
void rcu_sync_func(struct rcu_head *rhp)
```

Callback function managing reader access to fastpath

**Parameters**

- `struct rcu_head *rhp`: Pointer to rcu_head in rcu_sync structure to use for synchronization

**Description**

This function is passed to [`call_rcu()`](#c-call_rcu) function by [`rcu_sync_enter()`](#c-rcu_sync_enter) and
[`rcu_sync_exit()`](#c-rcu_sync_exit), so that it is invoked after a grace period following the
that invocation of enter/exit.

If it is called by [`rcu_sync_enter()`](#c-rcu_sync_enter) it signals that all the readers were
switched onto slow path.

If it is called by [`rcu_sync_exit()`](#c-rcu_sync_exit) it takes action based on events that
have taken place in the meantime, so that closely spaced [`rcu_sync_enter()`](#c-rcu_sync_enter)
and [`rcu_sync_exit()`](#c-rcu_sync_exit) pairs need not wait for a grace period.

If another [`rcu_sync_enter()`](#c-rcu_sync_enter) is invoked before the grace period
ended, reset state to allow the next [`rcu_sync_exit()`](#c-rcu_sync_exit) to let the
readers back onto their fastpaths (after a grace period).  If both
another [`rcu_sync_enter()`](#c-rcu_sync_enter) and its matching [`rcu_sync_exit()`](#c-rcu_sync_exit) are invoked
before the grace period ended, re-invoke [`call_rcu()`](#c-call_rcu) on behalf of that
[`rcu_sync_exit()`](#c-rcu_sync_exit).  Otherwise, set all state back to idle so that readers
can again use their fastpaths.

#### <a id="c-rcu_sync_enter"></a>`rcu_sync_enter()`

```c
void rcu_sync_enter(struct rcu_sync *rsp)
```

Force readers onto slowpath

**Parameters**

- `struct rcu_sync *rsp`: Pointer to rcu_sync structure to use for synchronization

**Description**

This function is used by updaters who need readers to make use of
a slowpath during the update.  After this function returns, all
subsequent calls to [`rcu_sync_is_idle()`](#c-rcu_sync_is_idle) will return false, which
tells readers to stay off their fastpaths.  A later call to
[`rcu_sync_exit()`](#c-rcu_sync_exit) re-enables reader fastpaths.

When called in isolation, [`rcu_sync_enter()`](#c-rcu_sync_enter) must wait for a grace
period, however, closely spaced calls to [`rcu_sync_enter()`](#c-rcu_sync_enter) can
optimize away the grace-period wait via a state machine implemented
by [`rcu_sync_enter()`](#c-rcu_sync_enter), [`rcu_sync_exit()`](#c-rcu_sync_exit), and [`rcu_sync_func()`](#c-rcu_sync_func).

#### <a id="c-rcu_sync_exit"></a>`rcu_sync_exit()`

```c
void rcu_sync_exit(struct rcu_sync *rsp)
```

Allow readers back onto fast path after grace period

**Parameters**

- `struct rcu_sync *rsp`: Pointer to rcu_sync structure to use for synchronization

**Description**

This function is used by updaters who have completed, and can therefore
now allow readers to make use of their fastpaths after a grace period
has elapsed.  After this grace period has completed, all subsequent
calls to [`rcu_sync_is_idle()`](#c-rcu_sync_is_idle) will return true, which tells readers that
they can once again use their fastpaths.

#### <a id="c-rcu_sync_dtor"></a>`rcu_sync_dtor()`

```c
void rcu_sync_dtor(struct rcu_sync *rsp)
```

Clean up an rcu_sync structure

**Parameters**

- `struct rcu_sync *rsp`: Pointer to rcu_sync structure to be cleaned up



#### <a id="c-struct-rcu_tasks_percpu"></a>`struct rcu_tasks_percpu`

Per-CPU component of definition for a Tasks-RCU-like mechanism.

**Definition**

```c
struct rcu_tasks_percpu {
    struct rcu_segcblist cblist;
    raw_spinlock_t lock;
    unsigned long rtp_jiffies;
    unsigned long rtp_n_lock_retries;
    struct timer_list lazy_timer;
    unsigned int urgent_gp;
    struct work_struct rtp_work;
    struct irq_work rtp_irq_work;
    struct rcu_head barrier_q_head;
    struct list_head rtp_blkd_tasks;
    struct list_head rtp_exit_list;
    int cpu;
    int index;
    struct rcu_tasks *rtpp;
};
```

**Members**

- `cblist`: Callback list.
- `lock`: Lock protecting per-CPU callback list.
- `rtp_jiffies`: Jiffies counter value for statistics.
- `rtp_n_lock_retries`: Rough lock-contention statistic.
- `lazy_timer`: Timer to unlazify callbacks.
- `urgent_gp`: Number of additional non-lazy grace periods.
- `rtp_work`: Work queue for invoking callbacks.
- `rtp_irq_work`: IRQ work queue for deferred wakeups.
- `barrier_q_head`: RCU callback for barrier operation.
- `rtp_blkd_tasks`: List of tasks blocked as readers.
- `rtp_exit_list`: List of tasks in the latter portion of `do_exit()`.
- `cpu`: CPU number corresponding to this entry.
- `index`: Index of this CPU in rtpcp_array of the rcu_tasks structure.
- `rtpp`: Pointer to the rcu_tasks structure.

#### <a id="c-struct-rcu_tasks"></a>`struct rcu_tasks`

Definition for a Tasks-RCU-like mechanism.

**Definition**

```c
struct rcu_tasks {
    struct rcuwait cbs_wait;
    raw_spinlock_t cbs_gbl_lock;
    struct mutex tasks_gp_mutex;
    int gp_state;
    int gp_sleep;
    int init_fract;
    unsigned long gp_jiffies;
    unsigned long gp_start;
    unsigned long tasks_gp_seq;
    unsigned long n_ipis;
    unsigned long n_ipis_fails;
    struct task_struct *kthread_ptr;
    unsigned long lazy_jiffies;
    rcu_tasks_gp_func_t gp_func;
    pregp_func_t pregp_func;
    pertask_func_t pertask_func;
    postscan_func_t postscan_func;
    holdouts_func_t holdouts_func;
    postgp_func_t postgp_func;
    call_rcu_func_t call_func;
    unsigned int wait_state;
    struct rcu_tasks_percpu __percpu *rtpcpu;
    struct rcu_tasks_percpu **rtpcp_array;
    int percpu_enqueue_shift;
    int percpu_enqueue_lim;
    int percpu_dequeue_lim;
    unsigned long percpu_dequeue_gpseq;
    struct mutex barrier_q_mutex;
    atomic_t barrier_q_count;
    struct completion barrier_q_completion;
    unsigned long barrier_q_seq;
    unsigned long barrier_q_start;
    char *name;
    char *kname;
};
```

**Members**

- `cbs_wait`: RCU wait allowing a new callback to get kthread's attention.
- `cbs_gbl_lock`: Lock protecting callback list.
- `tasks_gp_mutex`: Mutex protecting grace period, needed during mid-boot dead zone.
- `gp_state`: Grace period's most recent state transition (debugging).
- `gp_sleep`: Per-grace-period sleep to prevent CPU-bound looping.
- `init_fract`: Initial backoff sleep interval.
- `gp_jiffies`: Time of last **gp_state** transition.
- `gp_start`: Most recent grace-period start in jiffies.
- `tasks_gp_seq`: Number of grace periods completed since boot in upper bits.
- `n_ipis`: Number of IPIs sent to encourage grace periods to end.
- `n_ipis_fails`: Number of IPI-send failures.
- `kthread_ptr`: This flavor's grace-period/callback-invocation kthread.
- `lazy_jiffies`: Number of jiffies to allow callbacks to be lazy.
- `gp_func`: This flavor's grace-period-wait function.
- `pregp_func`: This flavor's pre-grace-period function (optional).
- `pertask_func`: This flavor's per-task scan function (optional).
- `postscan_func`: This flavor's post-task scan function (optional).
- `holdouts_func`: This flavor's holdout-list scan function (optional).
- `postgp_func`: This flavor's post-grace-period function (optional).
- `call_func`: This flavor's [`call_rcu()`](#c-call_rcu)-equivalent function.
- `wait_state`: Task state for synchronous grace-period waits (default TASK_UNINTERRUPTIBLE).
- `rtpcpu`: This flavor's rcu_tasks_percpu structure.
- `rtpcp_array`: Array of pointers to rcu_tasks_percpu structure of CPUs in cpu_possible_mask.
- `percpu_enqueue_shift`: Shift down CPU ID this much when enqueuing callbacks.
- `percpu_enqueue_lim`: Number of per-CPU callback queues in use for enqueuing.
- `percpu_dequeue_lim`: Number of per-CPU callback queues in use for dequeuing.
- `percpu_dequeue_gpseq`: RCU grace-period number to propagate enqueue limit to dequeuers.
- `barrier_q_mutex`: Serialize barrier operations.
- `barrier_q_count`: Number of queues being waited on.
- `barrier_q_completion`: Barrier wait/wakeup mechanism.
- `barrier_q_seq`: Sequence number for barrier operations.
- `barrier_q_start`: Most recent barrier start in jiffies.
- `name`: This flavor's textual name.
- `kname`: This flavor's kthread name.

#### <a id="c-call_rcu_tasks"></a>`call_rcu_tasks()`

```c
void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func)
```

Queue an RCU for invocation task-based grace period

**Parameters**

- `struct rcu_head *rhp`: structure to be used for queueing the RCU updates.
- `rcu_callback_t func`: actual callback function to be invoked after the grace period

**Description**

The callback function will be invoked some time after a full grace
period elapses, in other words after all currently executing RCU
read-side critical sections have completed. [`call_rcu_tasks()`](#c-call_rcu_tasks) assumes
that the read-side critical sections end at a voluntary context
switch (not a preemption!), [`cond_resched_tasks_rcu_qs()`](#c-cond_resched_tasks_rcu_qs), entry into idle,
or transition to usermode execution.  As such, there are no read-side
primitives analogous to [`rcu_read_lock()`](#c-rcu_read_lock) and [`rcu_read_unlock()`](#c-rcu_read_unlock) because
this primitive is intended to determine that all tasks have passed
through a safe state, not so much for data-structure synchronization.

See the description of [`call_rcu()`](#c-call_rcu) for more detailed information on
memory ordering guarantees.

#### <a id="c-synchronize_rcu_tasks"></a>`synchronize_rcu_tasks()`

```c
void synchronize_rcu_tasks(void)
```

wait until an rcu-tasks grace period has elapsed.

**Parameters**

- `void`: no arguments

**Description**

Control will return to the caller some time after a full rcu-tasks
grace period has elapsed, in other words after all currently
executing rcu-tasks read-side critical sections have elapsed.  These
read-side critical sections are delimited by calls to `schedule()`,
[`cond_resched_tasks_rcu_qs()`](#c-cond_resched_tasks_rcu_qs), idle execution, userspace execution, calls
to [`synchronize_rcu_tasks()`](#c-synchronize_rcu_tasks), and (in theory, anyway) `cond_resched()`.

This is a very specialized primitive, intended only for a few uses in
tracing and other situations requiring manipulation of function
preambles and profiling hooks.  The [`synchronize_rcu_tasks()`](#c-synchronize_rcu_tasks) function
is not (yet) intended for heavy use from multiple CPUs.

See the description of [`synchronize_rcu()`](#c-synchronize_rcu) for more detailed information
on memory ordering guarantees.

#### <a id="c-rcu_barrier_tasks"></a>`rcu_barrier_tasks()`

```c
void rcu_barrier_tasks(void)
```

Wait for in-flight [`call_rcu_tasks()`](#c-call_rcu_tasks) callbacks.

**Parameters**

- `void`: no arguments

**Description**

Although the current implementation is guaranteed to wait, it is not
obligated to, for example, if there are no pending callbacks.

#### <a id="c-synchronize_rcu_tasks_rude"></a>`synchronize_rcu_tasks_rude()`

```c
void synchronize_rcu_tasks_rude(void)
```

wait for a rude rcu-tasks grace period

**Parameters**

- `void`: no arguments

**Description**

Control will return to the caller some time after a rude rcu-tasks
grace period has elapsed, in other words after all currently
executing rcu-tasks read-side critical sections have elapsed.  These
read-side critical sections are delimited by calls to `schedule()`,
[`cond_resched_tasks_rcu_qs()`](#c-cond_resched_tasks_rcu_qs), userspace execution (which is a schedulable
context), and (in theory, anyway) `cond_resched()`.

This is a very specialized primitive, intended only for a few uses in
tracing and other situations requiring manipulation of function preambles
and profiling hooks.  The [`synchronize_rcu_tasks_rude()`](#c-synchronize_rcu_tasks_rude) function is not
(yet) intended for heavy use from multiple CPUs.

See the description of [`synchronize_rcu()`](#c-synchronize_rcu) for more detailed information
on memory ordering guarantees.



#### <a id="c-rcu_cpu_stall_reset"></a>`rcu_cpu_stall_reset()`

```c
void rcu_cpu_stall_reset(void)
```

restart stall-warning timeout for current grace period

**Parameters**

- `void`: no arguments

**Description**

To perform the reset request from the caller, disable stall detection until
3 fqs loops have passed. This is required to ensure a fresh jiffies is
loaded.  It should be safe to do from the fqs loop as enough timer
interrupts and context switches should have passed.

The caller must disable hard irqs.

#### <a id="c-rcu_stall_chain_notifier_register"></a>`rcu_stall_chain_notifier_register()`

```c
int rcu_stall_chain_notifier_register(struct notifier_block *n)
```

Add an RCU CPU stall notifier

**Parameters**

- `struct notifier_block *n`: Entry to add.

**Description**

Adds an RCU CPU stall notifier to an atomic notifier chain.
The **action** passed to a notifier will be **RCU_STALL_NOTIFY_NORM** or
friends.  The **data** will be the duration of the stalled grace period,
in jiffies, coerced to a void* pointer.

Returns 0 on success, `-EEXIST` on error.

#### <a id="c-rcu_stall_chain_notifier_unregister"></a>`rcu_stall_chain_notifier_unregister()`

```c
int rcu_stall_chain_notifier_unregister(struct notifier_block *n)
```

Remove an RCU CPU stall notifier

**Parameters**

- `struct notifier_block *n`: Entry to add.

**Description**

Removes an RCU CPU stall notifier from an atomic notifier chain.

Returns zero on success, `-ENOENT` on failure.



#### <a id="c-rcu_read_lock_tasks_trace"></a>`rcu_read_lock_tasks_trace()`

```c
struct srcu_ctr __percpu * rcu_read_lock_tasks_trace(void)
```

mark beginning of RCU-trace read-side critical section

**Parameters**

- `void`: no arguments

**Description**

When [`synchronize_rcu_tasks_trace()`](#c-synchronize_rcu_tasks_trace) is invoked by one task, then that
task is guaranteed to block until all other tasks exit their read-side
critical sections.  Similarly, if `call_rcu_trace()` is invoked on one
task while other tasks are within RCU read-side critical sections,
invocation of the corresponding RCU callback is deferred until after
the all the other tasks exit their critical sections.

For more details, please see the documentation for
[`srcu_read_lock_fast()`](#c-srcu_read_lock_fast).  For a description of how implicit RCU
readers provide the needed ordering for architectures defining the
ARCH_WANTS_NO_INSTR Kconfig option (and thus promising never to trace
code where RCU is not watching), please see the `__srcu_read_lock_fast()`
(non-kerneldoc) header comment.  Otherwise, the `smp_mb()` below provided
the needed ordering.

#### <a id="c-rcu_read_unlock_tasks_trace"></a>`rcu_read_unlock_tasks_trace()`

```c
void rcu_read_unlock_tasks_trace(struct srcu_ctr __percpu *scp)
```

mark end of RCU-trace read-side critical section

**Parameters**

- `struct srcu_ctr __percpu *scp`: return value from corresponding [`rcu_read_lock_tasks_trace()`](#c-rcu_read_lock_tasks_trace).

**Description**

Pairs with the preceding call to [`rcu_read_lock_tasks_trace()`](#c-rcu_read_lock_tasks_trace) that
returned the value passed in via scp.

For more details, please see the documentation for [`rcu_read_unlock()`](#c-rcu_read_unlock).
For memory-ordering information, please see the header comment for the
[`rcu_read_lock_tasks_trace()`](#c-rcu_read_lock_tasks_trace) function.

#### <a id="c-rcu_read_lock_trace"></a>`rcu_read_lock_trace()`

```c
void rcu_read_lock_trace(void)
```

mark beginning of RCU-trace read-side critical section

**Parameters**

- `void`: no arguments

**Description**

When [`synchronize_rcu_tasks_trace()`](#c-synchronize_rcu_tasks_trace) is invoked by one task, then that
task is guaranteed to block until all other tasks exit their read-side
critical sections.  Similarly, if `call_rcu_trace()` is invoked on one
task while other tasks are within RCU read-side critical sections,
invocation of the corresponding RCU callback is deferred until after
the all the other tasks exit their critical sections.

For more details, please see the documentation for [`rcu_read_lock()`](#c-rcu_read_lock).

#### <a id="c-rcu_read_unlock_trace"></a>`rcu_read_unlock_trace()`

```c
void rcu_read_unlock_trace(void)
```

mark end of RCU-trace read-side critical section

**Parameters**

- `void`: no arguments

**Description**

Pairs with a preceding call to [`rcu_read_lock_trace()`](#c-rcu_read_lock_trace), and nesting is
allowed.  Invoking a [`rcu_read_unlock_trace()`](#c-rcu_read_unlock_trace) when there is no matching
[`rcu_read_lock_trace()`](#c-rcu_read_lock_trace) is verboten, and will result in lockdep complaints.

For more details, please see the documentation for [`rcu_read_unlock()`](#c-rcu_read_unlock).

#### <a id="c-call_rcu_tasks_trace"></a>`call_rcu_tasks_trace()`

```c
void call_rcu_tasks_trace(struct rcu_head *rhp, rcu_callback_t func)
```

Queue a callback trace task-based grace period

**Parameters**

- `struct rcu_head *rhp`: structure to be used for queueing the RCU updates.
- `rcu_callback_t func`: actual callback function to be invoked after the grace period

**Description**

The callback function will be invoked some time after a trace rcu-tasks
grace period elapses, in other words after all currently executing
trace rcu-tasks read-side critical sections have completed. These
read-side critical sections are delimited by calls to [`rcu_read_lock_trace()`](#c-rcu_read_lock_trace)
and [`rcu_read_unlock_trace()`](#c-rcu_read_unlock_trace).

See the description of [`call_rcu()`](#c-call_rcu) for more detailed information on
memory ordering guarantees.

#### <a id="c-synchronize_rcu_tasks_trace"></a>`synchronize_rcu_tasks_trace()`

```c
void synchronize_rcu_tasks_trace(void)
```

wait for a trace rcu-tasks grace period

**Parameters**

- `void`: no arguments

**Description**

Control will return to the caller some time after a trace rcu-tasks
grace period has elapsed, in other words after all currently executing
trace rcu-tasks read-side critical sections have elapsed. These read-side
critical sections are delimited by calls to [`rcu_read_lock_trace()`](#c-rcu_read_lock_trace)
and [`rcu_read_unlock_trace()`](#c-rcu_read_unlock_trace).

This is a very specialized primitive, intended only for a few uses in
tracing and other situations requiring manipulation of function preambles
and profiling hooks.  The [`synchronize_rcu_tasks_trace()`](#c-synchronize_rcu_tasks_trace) function is not
(yet) intended for heavy use from multiple CPUs.

See the description of [`synchronize_rcu()`](#c-synchronize_rcu) for more detailed information
on memory ordering guarantees.

#### <a id="c-rcu_barrier_tasks_trace"></a>`rcu_barrier_tasks_trace()`

```c
void rcu_barrier_tasks_trace(void)
```

Wait for in-flight [`call_rcu_tasks_trace()`](#c-call_rcu_tasks_trace) callbacks.

**Parameters**

- `void`: no arguments

**Description**

Note that [`rcu_barrier_tasks_trace()`](#c-rcu_barrier_tasks_trace) is not obligated to actually wait,
for example, if there are no pending callbacks.

#### <a id="c-rcu_tasks_trace_expedite_current"></a>`rcu_tasks_trace_expedite_current()`

```c
void rcu_tasks_trace_expedite_current(void)
```

Expedite the current Tasks Trace RCU grace period

**Parameters**

- `void`: no arguments

**Description**

Cause the current Tasks Trace RCU grace period to become expedited.
The grace period following the current one might also be expedited.
If there is no current grace period, one might be created.  If the
current grace period is currently sleeping, that sleep will complete
before expediting will take effect.



#### <a id="c-synchronize_rcu_mult"></a>`synchronize_rcu_mult()`

```c
synchronize_rcu_mult(...)
```

Wait concurrently for multiple grace periods

**Parameters**

- `...`: List of [`call_rcu()`](#c-call_rcu) functions for different grace periods to wait on

**Description**

This macro waits concurrently for multiple types of RCU grace periods.
For example, synchronize_rcu_mult(call_rcu, call_rcu_tasks) would wait
on concurrent RCU and RCU-tasks grace periods.  Waiting on a given SRCU
domain requires you to write a wrapper function for that SRCU domain's
[`call_srcu()`](#c-call_srcu) function, with this wrapper supplying the pointer to the
corresponding srcu_struct.

Note that [`call_rcu_hurry()`](#c-call_rcu_hurry) should be used instead of [`call_rcu()`](#c-call_rcu)
because in kernels built with CONFIG_RCU_LAZY=y the delay between the
invocation of [`call_rcu()`](#c-call_rcu) and that of the corresponding RCU callback
can be multiple seconds.

The first argument tells Tiny RCU's `_wait_rcu_gp()` not to
bother waiting for RCU.  The reason for this is because anywhere
[`synchronize_rcu_mult()`](#c-synchronize_rcu_mult) can be called is automatically already a full
grace period.



#### <a id="c-rcuref_init"></a>`rcuref_init()`

```c
void rcuref_init(rcuref_t *ref, unsigned int cnt)
```

Initialize a rcuref reference count with the given reference count

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count
- `unsigned int cnt`: The initial reference count typically '1'

#### <a id="c-rcuref_read"></a>`rcuref_read()`

```c
unsigned int rcuref_read(rcuref_t *ref)
```

Read the number of held reference counts of a rcuref

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count

**Return**

The number of held references (0 ... N). The value 0 does not
indicate that it is safe to schedule the object, protected by this reference
counter, for deconstruction.
If you want to know if the reference counter has been marked DEAD (as
signaled by [`rcuref_put()`](#c-rcuref_put)) please use `rcuread_is_dead()`.

#### <a id="c-rcuref_is_dead"></a>`rcuref_is_dead()`

```c
bool rcuref_is_dead(rcuref_t *ref)
```

Check if the rcuref has been already marked dead

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count

**Return**

True if the object has been marked DEAD. This signals that a previous
invocation of [`rcuref_put()`](#c-rcuref_put) returned true on this reference counter meaning
the protected object can safely be scheduled for deconstruction.
Otherwise, returns false.

#### <a id="c-rcuref_get"></a>`rcuref_get()`

```c
bool rcuref_get(rcuref_t *ref)
```

Acquire one reference on a rcuref reference count

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count

**Description**

Similar to [`atomic_inc_not_zero()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-atomic_inc_not_zero) but saturates at RCUREF_MAXREF.

Provides no memory ordering, it is assumed the caller has guaranteed the
object memory to be stable (RCU, etc.). It does provide a control dependency
and thereby orders future stores. See documentation in lib/rcuref.c

True if a reference was successfully acquired

**Return**

False if the attempt to acquire a reference failed. This happens
when the last reference has been put already

#### <a id="c-rcuref_put_rcusafe"></a>`rcuref_put_rcusafe()`

```c
bool rcuref_put_rcusafe(rcuref_t *ref)
```

- Release one reference for a rcuref reference count RCU safe

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count

**Description**

Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that `free()`
must come after.

Can be invoked from contexts, which guarantee that no grace period can
happen which would free the object concurrently if the decrement drops
the last reference and the slowpath races against a concurrent `get()` and
`put()` pair. [`rcu_read_lock()`](#c-rcu_read_lock)'ed and atomic contexts qualify.

False if there are still active references or the `put()` raced
with a concurrent `get()`/`put()` pair. Caller is not allowed to
release the protected object.

**Return**

True if this was the last reference with no future references
possible. This signals the caller that it can safely release the
object which is protected by the reference counter.

#### <a id="c-rcuref_put"></a>`rcuref_put()`

```c
bool rcuref_put(rcuref_t *ref)
```

- Release one reference for a rcuref reference count

**Parameters**

- `rcuref_t *ref`: Pointer to the reference count

**Description**

Can be invoked from any context.

Provides release memory ordering, such that prior loads and stores are done
before, and provides an acquire ordering on success such that `free()`
must come after.

True if this was the last reference with no future references
possible. This signals the caller that it can safely schedule the
object, which is protected by the reference counter, for
deconstruction.

False if there are still active references or the `put()` raced
with a concurrent `get()`/`put()` pair. Caller is not allowed to
deconstruct the protected object.



#### <a id="c-same_state_synchronize_rcu_full"></a>`same_state_synchronize_rcu_full()`

```c
bool same_state_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp1, struct rcu_gp_oldstate *rgosp2)
```

Are two old-state values identical?

**Parameters**

- `struct rcu_gp_oldstate *rgosp1`: First old-state value.
- `struct rcu_gp_oldstate *rgosp2`: Second old-state value.

**Description**

The two old-state values must have been obtained from either
[`get_state_synchronize_rcu_full()`](#c-get_state_synchronize_rcu_full), [`start_poll_synchronize_rcu_full()`](#c-start_poll_synchronize_rcu_full),
or [`get_completed_synchronize_rcu_full()`](#c-get_completed_synchronize_rcu_full).  Returns **true** if the two
values are identical and **false** otherwise.  This allows structures
whose lifetimes are tracked by old-state values to push these values
to a list header, allowing those structures to be slightly smaller.

Note that equality is judged on a bitwise basis, so that an
**rcu_gp_oldstate** structure with an already-completed state in one field
will compare not-equal to a structure with an already-completed state
in the other field.  After all, the **rcu_gp_oldstate** structure is opaque
so how did such a situation come to pass in the first place?

---

# Everything you never wanted to know about kobjects, ksets, and ktypes

_Peios Kernel / Internals / Core APIs_

> Based on an original article by Jon Corbet for lwn.net written October 1, 2003 and located at https://lwn.net/Articles/51437/

<a id="rst-everything-you-never-wanted-to-know-about-kobjects-ksets-and-ktypes"></a>

**Author:** Greg Kroah-Hartman &lt;[gregkh@linuxfoundation.org](<mailto:gregkh@linuxfoundation.org>)&gt;

**Last updated:** December 19, 2007

Based on an original article by Jon Corbet for lwn.net written October 1, 2003 and located at [https://lwn.net/Articles/51437/](<https://lwn.net/Articles/51437/>)

Part of the difficulty in understanding the driver model - and the kobject abstraction upon which it is built - is that there is no obvious starting place. Dealing with kobjects requires understanding a few different types, all of which make reference to each other. In an attempt to make things easier, we'll take a multi-pass approach, starting with vague terms and adding detail as we go. To that end, here are some quick definitions of some terms we will be working with.

> - A kobject is an object of type struct kobject.  Kobjects have a name and a reference count.  A kobject also has a parent pointer (allowing objects to be arranged into hierarchies), a specific type, and, usually, a representation in the sysfs virtual filesystem.
>
>   Kobjects are generally not interesting on their own; instead, they are usually embedded within some other structure which contains the stuff the code is really interested in.
>
>   No structure should **EVER** have more than one kobject embedded within it. If it does, the reference counting for the object is sure to be messed up and incorrect, and your code will be buggy.  So do not do this.
>
> - A ktype is the type of object that embeds a kobject.  Every structure that embeds a kobject needs a corresponding ktype.  The ktype controls what happens to the kobject when it is created and destroyed.
>
> - A kset is a group of kobjects.  These kobjects can be of the same ktype or belong to different ktypes.  The kset is the basic container type for collections of kobjects. Ksets contain their own kobjects, but you can safely ignore that implementation detail as the kset core code handles this kobject automatically.
>
>   When you see a sysfs directory full of other directories, generally each of those directories corresponds to a kobject in the same kset.

We'll look at how to create and manipulate all of these types. A bottom-up approach will be taken, so we'll go back to kobjects.

<a id="rst-embedding-kobjects"></a>

## Embedding kobjects

It is rare for kernel code to create a standalone kobject, with one major exception explained below.  Instead, kobjects are used to control access to a larger, domain-specific object.  To this end, kobjects will be found embedded in other structures.  If you are used to thinking of things in object-oriented terms, kobjects can be seen as a top-level, abstract class from which other classes are derived.  A kobject implements a set of capabilities which are not particularly useful by themselves, but are nice to have in other objects.  The C language does not allow for the direct expression of inheritance, so other techniques - such as structure embedding - must be used.

(As an aside, for those familiar with the kernel linked list implementation, this is analogous as to how "list_head" structs are rarely useful on their own, but are invariably found embedded in the larger objects of interest.)

So, for example, the UIO code in `drivers/uio/uio.c` has a structure that defines the memory region associated with a uio device:



```text
struct uio_map {
        struct kobject kobj;
        struct uio_mem *mem;
};
```

If you have a struct uio_map structure, finding its embedded kobject is just a matter of using the kobj member.  Code that works with kobjects will often have the opposite problem, however: given a struct kobject pointer, what is the pointer to the containing structure?  You must avoid tricks (such as assuming that the kobject is at the beginning of the structure) and, instead, use the container_of() macro, found in `<linux/container_of.h>`:



```text
container_of(ptr, type, member)
```

where:

> - `ptr` is the pointer to the embedded kobject,
>
> - `type` is the type of the containing structure, and
>
> - `member` is the name of the structure field to which `pointer` points.

The return value from container_of() is a pointer to the corresponding container type. So, for example, a pointer `kp` to a struct kobject embedded **within** a struct uio_map could be converted to a pointer to the **containing** uio_map structure with:



```text
struct uio_map *u_map = container_of(kp, struct uio_map, kobj);
```

For convenience, programmers often define a simple macro for **back-casting** kobject pointers to the containing type.  Exactly this happens in the earlier `drivers/uio/uio.c`, as you can see here:



```text
struct uio_map {
        struct kobject kobj;
        struct uio_mem *mem;
};

#define to_map(map) container_of(map, struct uio_map, kobj)
```

where the macro argument "map" is a pointer to the struct kobject in question.  That macro is subsequently invoked with:



```text
struct uio_map *map = to_map(kobj);
```

<a id="rst-initialization-of-kobjects"></a>

## Initialization of kobjects

Code which creates a kobject must, of course, initialize that object. Some of the internal fields are setup with a (mandatory) call to kobject_init():



```text
void kobject_init(struct kobject *kobj, const struct kobj_type *ktype);
```

The ktype is required for a kobject to be created properly, as every kobject must have an associated kobj_type.  After calling kobject_init(), to register the kobject with sysfs, the function kobject_add() must be called:



```text
int kobject_add(struct kobject *kobj, struct kobject *parent,
                const char *fmt, ...);
```

This sets up the parent of the kobject and the name for the kobject properly.  If the kobject is to be associated with a specific kset, kobj-&gt;kset must be assigned before calling kobject_add().  If a kset is associated with a kobject, then the parent for the kobject can be set to NULL in the call to kobject_add() and then the kobject's parent will be the kset itself.

As the name of the kobject is set when it is added to the kernel, the name of the kobject should never be manipulated directly.  If you must change the name of the kobject, call kobject_rename():



```text
int kobject_rename(struct kobject *kobj, const char *new_name);
```

kobject_rename() does not perform any locking or have a solid notion of what names are valid so the caller must provide their own sanity checking and serialization.

There is a function called kobject_set_name() but that is legacy cruft and is being removed.  If your code needs to call this function, it is incorrect and needs to be fixed.

To properly access the name of the kobject, use the function kobject_name():



```text
const char *kobject_name(const struct kobject * kobj);
```

There is a helper function to both initialize and add the kobject to the kernel at the same time, called surprisingly enough kobject_init_and_add():



```text
int kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
                         struct kobject *parent, const char *fmt, ...);
```

The arguments are the same as the individual kobject_init() and kobject_add() functions described above.

<a id="rst-uevents"></a>

## Uevents

After a kobject has been registered with the kobject core, you need to announce to the world that it has been created.  This can be done with a call to kobject_uevent():



```text
int kobject_uevent(struct kobject *kobj, enum kobject_action action);
```

Use the **KOBJ_ADD** action for when the kobject is first added to the kernel. This should be done only after any attributes or children of the kobject have been initialized properly, as userspace will instantly start to look for them when this call happens.

When the kobject is removed from the kernel (details on how to do that are below), the uevent for **KOBJ_REMOVE** will be automatically created by the kobject core, so the caller does not have to worry about doing that by hand.

<a id="rst-reference-counts"></a>

## Reference counts

One of the key functions of a kobject is to serve as a reference counter for the object in which it is embedded. As long as references to the object exist, the object (and the code which supports it) must continue to exist. The low-level functions for manipulating a kobject's reference counts are:



```text
struct kobject *kobject_get(struct kobject *kobj);
void kobject_put(struct kobject *kobj);
```

A successful call to kobject_get() will increment the kobject's reference counter and return the pointer to the kobject.

When a reference is released, the call to kobject_put() will decrement the reference count and, possibly, free the object. Note that kobject_init() sets the reference count to one, so the code which sets up the kobject will need to do a kobject_put() eventually to release that reference.

Because kobjects are dynamic, they must not be declared statically or on the stack, but instead, always allocated dynamically.  Future versions of the kernel will contain a run-time check for kobjects that are created statically and will warn the developer of this improper usage.

If all that you want to use a kobject for is to provide a reference counter for your structure, please use the struct kref instead; a kobject would be overkill.  For more information on how to use struct kref, please see the file [Documentation/core-api/kref.rst](/kernel/internals/core-api/kref.md) in the Linux kernel source tree.

<a id="rst-creating-simple-kobjects"></a>

## Creating "simple" kobjects

Sometimes all that a developer wants is a way to create a simple directory in the sysfs hierarchy, and not have to mess with the whole complication of ksets, show and store functions, and other details.  This is the one exception where a single kobject should be created.  To create such an entry, use the function:



```text
struct kobject *kobject_create_and_add(const char *name, struct kobject *parent);
```

This function will create a kobject and place it in sysfs in the location underneath the specified parent kobject.  To create simple attributes associated with this kobject, use:



```text
int sysfs_create_file(struct kobject *kobj, const struct attribute *attr);
```

or:



```text
int sysfs_create_group(struct kobject *kobj, const struct attribute_group *grp);
```

Both types of attributes used here, with a kobject that has been created with the kobject_create_and_add(), can be of type kobj_attribute, so no special custom attribute is needed to be created.

See the example module, `samples/kobject/kobject-example.c` for an implementation of a simple kobject and attributes.

<a id="rst-ktypes-and-release-methods"></a>

## ktypes and release methods

One important thing still missing from the discussion is what happens to a kobject when its reference count reaches zero. The code which created the kobject generally does not know when that will happen; if it did, there would be little point in using a kobject in the first place. Even predictable object lifecycles become more complicated when sysfs is brought in as other portions of the kernel can get a reference on any kobject that is registered in the system.

The end result is that a structure protected by a kobject cannot be freed before its reference count goes to zero. The reference count is not under the direct control of the code which created the kobject. So that code must be notified asynchronously whenever the last reference to one of its kobjects goes away.

Once you registered your kobject via kobject_add(), you must never use kfree() to free it directly. The only safe way is to use kobject_put(). It is good practice to always use kobject_put() after kobject_init() to avoid errors creeping in.

This notification is done through a kobject's release() method. Usually such a method has a form like:



```text
void my_object_release(struct kobject *kobj)
{
        struct my_object *mine = container_of(kobj, struct my_object, kobj);

        /* Perform any additional cleanup on this object, then... */
        kfree(mine);
}
```

One important point cannot be overstated: every kobject must have a release() method, and the kobject must persist (in a consistent state) until that method is called. If these constraints are not met, the code is flawed. Note that the kernel will warn you if you forget to provide a release() method.  Do not try to get rid of this warning by providing an "empty" release function.

If all your cleanup function needs to do is call kfree(), then you must create a wrapper function which uses container_of() to upcast to the correct type (as shown in the example above) and then calls kfree() on the overall structure.

Note, the name of the kobject is available in the release function, but it must NOT be changed within this callback.  Otherwise there will be a memory leak in the kobject core, which makes people unhappy.

Interestingly, the release() method is not stored in the kobject itself; instead, it is associated with the ktype. So let us introduce struct kobj_type:



```text
struct kobj_type {
        void (*release)(struct kobject *kobj);
        const struct sysfs_ops *sysfs_ops;
        const struct attribute_group **default_groups;
        const struct kobj_ns_type_operations *(*child_ns_type)(struct kobject *kobj);
        const void *(*namespace)(struct kobject *kobj);
        void (*get_ownership)(struct kobject *kobj, kuid_t *uid, kgid_t *gid);
};
```

This structure is used to describe a particular type of kobject (or, more correctly, of containing object). Every kobject needs to have an associated kobj_type structure; a pointer to that structure must be specified when you call kobject_init() or kobject_init_and_add().

The release field in struct kobj_type is, of course, a pointer to the release() method for this type of kobject. The other two fields (sysfs_ops and default_groups) control how objects of this type are represented in sysfs; they are beyond the scope of this document.

The default_groups pointer is a list of default attributes that will be automatically created for any kobject that is registered with this ktype.

<a id="rst-ksets"></a>

## ksets

A kset is merely a collection of kobjects that want to be associated with each other.  There is no restriction that they be of the same ktype, but be very careful if they are not.

A kset serves these functions:

> - It serves as a bag containing a group of objects. A kset can be used by the kernel to track "all block devices" or "all PCI device drivers."
>
> - A kset is also a subdirectory in sysfs, where the associated kobjects with the kset can show up.  Every kset contains a kobject which can be set up to be the parent of other kobjects; the top-level directories of the sysfs hierarchy are constructed in this way.
>
> - Ksets can support the "hotplugging" of kobjects and influence how uevent events are reported to user space.

In object-oriented terms, "kset" is the top-level container class; ksets contain their own kobject, but that kobject is managed by the kset code and should not be manipulated by any other user.

A kset keeps its children in a standard kernel linked list.  Kobjects point back to their containing kset via their kset field. In almost all cases, the kobjects belonging to a kset have that kset (or, strictly, its embedded kobject) in their parent.

As a kset contains a kobject within it, it should always be dynamically created and never declared statically or on the stack.  To create a new kset use:



```text
struct kset *kset_create_and_add(const char *name,
                                 const struct kset_uevent_ops *uevent_ops,
                                 struct kobject *parent_kobj);
```

When you are finished with the kset, call:



```text
void kset_unregister(struct kset *k);
```

to destroy it.  This removes the kset from sysfs and decrements its reference count.  When the reference count goes to zero, the kset will be released. Because other references to the kset may still exist, the release may happen after kset_unregister() returns.

An example of using a kset can be seen in the `samples/kobject/kset-example.c` file in the kernel tree.

If a kset wishes to control the uevent operations of the kobjects associated with it, it can use the struct kset_uevent_ops to handle it:



```text
struct kset_uevent_ops {
        int (* const filter)(struct kobject *kobj);
        const char *(* const name)(struct kobject *kobj);
        int (* const uevent)(struct kobject *kobj, struct kobj_uevent_env *env);
};
```

The filter function allows a kset to prevent a uevent from being emitted to userspace for a specific kobject.  If the function returns 0, the uevent will not be emitted.

The name function will be called to override the default name of the kset that the uevent sends to userspace.  By default, the name will be the same as the kset itself, but this function, if present, can override that name.

The uevent function will be called when the uevent is about to be sent to userspace to allow more environment variables to be added to the uevent.

One might ask how, exactly, a kobject is added to a kset, given that no functions which perform that function have been presented.  The answer is that this task is handled by kobject_add().  When a kobject is passed to kobject_add(), its kset member should point to the kset to which the kobject will belong.  kobject_add() will handle the rest.

If the kobject belonging to a kset has no parent kobject set, it will be added to the kset's directory.  Not all members of a kset do necessarily live in the kset directory.  If an explicit parent kobject is assigned before the kobject is added, the kobject is registered with the kset, but added below the parent kobject.

<a id="rst-kobject-removal"></a>

## Kobject removal

After a kobject has been registered with the kobject core successfully, it must be cleaned up when the code is finished with it.  To do that, call kobject_put().  By doing this, the kobject core will automatically clean up all of the memory allocated by this kobject.  If a `KOBJ_ADD` uevent has been sent for the object, a corresponding `KOBJ_REMOVE` uevent will be sent, and any other sysfs housekeeping will be handled for the caller properly.

If you need to do a two-stage delete of the kobject (say you are not allowed to sleep when you need to destroy the object), then call kobject_del() which will unregister the kobject from sysfs.  This makes the kobject "invisible", but it is not cleaned up, and the reference count of the object is still the same.  At a later time call kobject_put() to finish the cleanup of the memory associated with the kobject.

kobject_del() can be used to drop the reference to the parent object, if circular references are constructed.  It is valid in some cases, that a parent objects references a child.  Circular references \_must\_ be broken with an explicit call to kobject_del(), so that a release functions will be called, and the objects in the former circle release each other.

<a id="rst-example-code-to-copy-from"></a>

## Example code to copy from

For a more complete example of using ksets and kobjects properly, see the example programs `samples/kobject/{kobject-example.c,kset-example.c}`, which will be built as loadable modules if you select `CONFIG_SAMPLE_KOBJECT`.

---

# Adding reference counters (krefs) to kernel objects

_Peios Kernel / Internals / Core APIs_

> A lot of this was lifted from Greg Kroah-Hartman's 2004 OLS paper and presentation on krefs, which can be found at:

<a id="rst-adding-reference-counters-krefs-to-kernel-objects"></a>

**Author:** Corey Minyard &lt;[minyard@acm.org](<mailto:minyard@acm.org>)&gt;

**Author:** Thomas Hellström &lt;[thomas.hellstrom@linux.intel.com](<mailto:thomas.hellstrom@linux.intel.com>)&gt;

A lot of this was lifted from Greg Kroah-Hartman's 2004 OLS paper and presentation on krefs, which can be found at:

> - [http://www.kroah.com/linux/talks/ols_2004_kref_paper/Reprint-Kroah-Hartman-OLS2004.pdf](<http://www.kroah.com/linux/talks/ols_2004_kref_paper/Reprint-Kroah-Hartman-OLS2004.pdf>)
>
> - [http://www.kroah.com/linux/talks/ols_2004_kref_talk/](<http://www.kroah.com/linux/talks/ols_2004_kref_talk/>)

<a id="rst-introduction"></a>

## Introduction

krefs allow you to add reference counters to your objects.  If you have objects that are used in multiple places and passed around, and you don't have refcounts, your code is almost certainly broken.  If you want refcounts, krefs are the way to go.

To use a kref, add one to your data structures like:



```text
struct my_data
{
    .
    .
    struct kref refcount;
    .
    .
};
```

The kref can occur anywhere within the data structure.

<a id="rst-initialization"></a>

## Initialization

You must initialize the kref after you allocate it.  To do this, call kref_init as so:



```text
struct my_data *data;

data = kmalloc(sizeof(*data), GFP_KERNEL);
if (!data)
       return -ENOMEM;
kref_init(&data->refcount);
```

This sets the refcount in the kref to 1.

<a id="rst-kref-rules"></a>

## Kref rules

Once you have an initialized kref, you must follow the following rules:

1. If you make a non-temporary copy of a pointer, especially if it can be passed to another thread of execution, you must increment the refcount with kref_get() before passing it off:



   ```text
   kref_get(&data->refcount);
   ```

   If you already have a valid pointer to a kref-ed structure (the refcount cannot go to zero) you may do this without a lock.

2. When you are done with a pointer, you must call kref_put():



   ```text
   kref_put(&data->refcount, data_release);
   ```

   If this is the last reference to the pointer, the release routine will be called.  If the code never tries to get a valid pointer to a kref-ed structure without already holding a valid pointer, it is safe to do this without a lock.

3. If the code attempts to gain a reference to a kref-ed structure without already holding a valid pointer, it must serialize access where a kref_put() cannot occur during the kref_get(), and the structure must remain valid during the kref_get().

For example, if you allocate some data and then pass it to another thread to process:



```text
void data_release(struct kref *ref)
{
    struct my_data *data = container_of(ref, struct my_data, refcount);
    kfree(data);
}

void more_data_handling(void *cb_data)
{
    struct my_data *data = cb_data;
    .
    . do stuff with data here
    .
    kref_put(&data->refcount, data_release);
}

int my_data_handler(void)
{
    int rv = 0;
    struct my_data *data;
    struct task_struct *task;
    data = kmalloc(sizeof(*data), GFP_KERNEL);
    if (!data)
            return -ENOMEM;
    kref_init(&data->refcount);

    kref_get(&data->refcount);
    task = kthread_run(more_data_handling, data, "more_data_handling");
    if (task == ERR_PTR(-ENOMEM)) {
            rv = -ENOMEM;
            kref_put(&data->refcount, data_release);
            goto out;
    }

    .
    . do stuff with data here
    .
out:
    kref_put(&data->refcount, data_release);
    return rv;
}
```

This way, it doesn't matter what order the two threads handle the data, the kref_put() handles knowing when the data is not referenced any more and releasing it.  The kref_get() does not require a lock, since we already have a valid pointer that we own a refcount for.  The put needs no lock because nothing tries to get the data without already holding a pointer.

In the above example, kref_put() will be called 2 times in both success and error paths. This is necessary because the reference count got incremented 2 times by kref_init() and kref_get().

Note that the "before" in rule 1 is very important.  You should never do something like:



```text
task = kthread_run(more_data_handling, data, "more_data_handling");
if (task == ERR_PTR(-ENOMEM)) {
        rv = -ENOMEM;
        goto out;
} else
        /* BAD BAD BAD - get is after the handoff */
        kref_get(&data->refcount);
```

Don't assume you know what you are doing and use the above construct. First of all, you may not know what you are doing.  Second, you may know what you are doing (there are some situations where locking is involved where the above may be legal) but someone else who doesn't know what they are doing may change the code or copy the code.  It's bad style.  Don't do it.

There are some situations where you can optimize the gets and puts. For instance, if you are done with an object and enqueuing it for something else or passing it off to something else, there is no reason to do a get then a put:



```text
/* Silly extra get and put */
kref_get(&obj->ref);
enqueue(obj);
kref_put(&obj->ref, obj_cleanup);
```

Just do the enqueue.  A comment about this is always welcome:



```text
enqueue(obj);
/* We are done with obj, so we pass our refcount off
   to the queue.  DON'T TOUCH obj AFTER HERE! */
```

The last rule (rule 3) is the nastiest one to handle.  Say, for instance, you have a list of items that are each kref-ed, and you wish to get the first one.  You can't just pull the first item off the list and kref_get() it.  That violates rule 3 because you are not already holding a valid pointer.  You must add a mutex (or some other lock). For instance:



```text
static DEFINE_MUTEX(mutex);
static LIST_HEAD(q);
struct my_data
{
        struct kref      refcount;
        struct list_head link;
};

static struct my_data *get_entry()
{
        struct my_data *entry = NULL;
        mutex_lock(&mutex);
        if (!list_empty(&q)) {
                entry = container_of(q.next, struct my_data, link);
                kref_get(&entry->refcount);
        }
        mutex_unlock(&mutex);
        return entry;
}

static void release_entry(struct kref *ref)
{
        struct my_data *entry = container_of(ref, struct my_data, refcount);

        list_del(&entry->link);
        kfree(entry);
}

static void put_entry(struct my_data *entry)
{
        mutex_lock(&mutex);
        kref_put(&entry->refcount, release_entry);
        mutex_unlock(&mutex);
}
```

The kref_put() return value is useful if you do not want to hold the lock during the whole release operation.  Say you didn't want to call kfree() with the lock held in the example above (since it is kind of pointless to do so).  You could use kref_put() as follows:



```text
static void release_entry(struct kref *ref)
{
        /* All work is done after the return from kref_put(). */
}

static void put_entry(struct my_data *entry)
{
        mutex_lock(&mutex);
        if (kref_put(&entry->refcount, release_entry)) {
                list_del(&entry->link);
                mutex_unlock(&mutex);
                kfree(entry);
        } else
                mutex_unlock(&mutex);
}
```

This is really more useful if you have to call other routines as part of the free operations that could take a long time or might claim the same lock.  Note that doing everything in the release routine is still preferred as it is a little neater.

The above example could also be optimized using kref_get_unless_zero() in the following way:



```text
static struct my_data *get_entry()
{
        struct my_data *entry = NULL;
        mutex_lock(&mutex);
        if (!list_empty(&q)) {
                entry = container_of(q.next, struct my_data, link);
                if (!kref_get_unless_zero(&entry->refcount))
                        entry = NULL;
        }
        mutex_unlock(&mutex);
        return entry;
}

static void release_entry(struct kref *ref)
{
        struct my_data *entry = container_of(ref, struct my_data, refcount);

        mutex_lock(&mutex);
        list_del(&entry->link);
        mutex_unlock(&mutex);
        kfree(entry);
}

static void put_entry(struct my_data *entry)
{
        kref_put(&entry->refcount, release_entry);
}
```

Which is useful to remove the mutex lock around kref_put() in put_entry(), but it's important that kref_get_unless_zero is enclosed in the same critical section that finds the entry in the lookup table, otherwise kref_get_unless_zero may reference already freed memory. Note that it is illegal to use kref_get_unless_zero without checking its return value. If you are sure (by already having a valid pointer) that kref_get_unless_zero() will return true, then use kref_get() instead.

<a id="rst-krefs-and-rcu"></a>

## Krefs and RCU

The function kref_get_unless_zero also makes it possible to use rcu locking for lookups in the above example:



```text
struct my_data
{
        struct rcu_head rhead;
        .
        struct kref refcount;
        .
        .
};

static struct my_data *get_entry_rcu()
{
        struct my_data *entry = NULL;
        rcu_read_lock();
        if (!list_empty(&q)) {
                entry = container_of(q.next, struct my_data, link);
                if (!kref_get_unless_zero(&entry->refcount))
                        entry = NULL;
        }
        rcu_read_unlock();
        return entry;
}

static void release_entry_rcu(struct kref *ref)
{
        struct my_data *entry = container_of(ref, struct my_data, refcount);

        mutex_lock(&mutex);
        list_del_rcu(&entry->link);
        mutex_unlock(&mutex);
        kfree_rcu(entry, rhead);
}

static void put_entry(struct my_data *entry)
{
        kref_put(&entry->refcount, release_entry_rcu);
}
```

But note that the struct kref member needs to remain in valid memory for a rcu grace period after release_entry_rcu was called. That can be accomplished by using kfree_rcu(entry, rhead) as done above, or by calling synchronize_rcu() before using kfree, but note that synchronize_rcu() may sleep for a substantial amount of time.

<a id="rst-functions-and-structures"></a>

## Functions and structures


#### <a id="c-kref_init"></a>`kref_init()`

```c
void kref_init(struct kref *kref)
```

initialize object.

**Parameters**

- `struct kref *kref`: object in question.

#### <a id="c-kref_get"></a>`kref_get()`

```c
void kref_get(struct kref *kref)
```

increment refcount for object.

**Parameters**

- `struct kref *kref`: object.

#### <a id="c-kref_put"></a>`kref_put()`

```c
int kref_put(struct kref *kref, void (*release)(struct kref *kref))
```

Decrement refcount for object

**Parameters**

- `struct kref *kref`: Object
- `void (*release)(struct kref *kref)`: Pointer to the function that will clean up the object when the
  last reference to the object is released.

**Description**

Decrement the refcount, and if 0, call **release**.  The caller may not
pass NULL or [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) as the release function.

**Return**

1 if this call removed the object, otherwise return 0.  Beware,
if this function returns 0, another caller may have removed the object
by the time this function returns.  The return value is only certain
if you want to see if the object is definitely released.

#### <a id="c-kref_put_mutex"></a>`kref_put_mutex()`

```c
int kref_put_mutex(struct kref *kref, void (*release)(struct kref *kref), struct mutex *mutex) __cond_acquires(true# mutex)
```

Decrement refcount for object

**Parameters**

- `struct kref *kref`: Object
- `void (*release)(struct kref *kref)`: Pointer to the function that will clean up the object when the
  last reference to the object is released.
- `struct mutex *mutex) __cond_acquires(true# mutex`: Mutex which protects the release function.

**Description**

This variant of `kref_lock()` calls the **release** function with the **mutex**
held.  The **release** function will release the mutex.

#### <a id="c-kref_put_lock"></a>`kref_put_lock()`

```c
int kref_put_lock(struct kref *kref, void (*release)(struct kref *kref), spinlock_t *lock) __cond_acquires(true# lock)
```

Decrement refcount for object

**Parameters**

- `struct kref *kref`: Object
- `void (*release)(struct kref *kref)`: Pointer to the function that will clean up the object when the
  last reference to the object is released.
- `spinlock_t *lock) __cond_acquires(true# lock`: Spinlock which protects the release function.

**Description**

This variant of `kref_lock()` calls the **release** function with the **lock**
held.  The **release** function will release the lock.

#### <a id="c-kref_get_unless_zero"></a>`kref_get_unless_zero()`

```c
int kref_get_unless_zero(struct kref *kref)
```

Increment refcount for object unless it is zero.

**Parameters**

- `struct kref *kref`: object.

**Description**

This function is intended to simplify locking around refcounting for
objects that can be looked up from a lookup structure, and which are
removed from that lookup structure in the object destructor.
Operations on such objects require at least a read lock around
lookup + kref_get, and a write lock around kref_put + remove from lookup
structure. Furthermore, RCU implementations become extremely tricky.
With a lookup followed by a kref_get_unless_zero *with return value check*
locking in the kref_put path can be deferred to the actual removal from
the lookup structure and RCU lookups become trivial.

**Return**

non-zero if the increment succeeded. Otherwise return 0.

---

# Reed-Solomon Library Programming Interface

_Peios Kernel / Internals / Core APIs_

> The generic Reed-Solomon Library provides encoding, decoding and error correction functions.

<a id="rst-reed-solomon-library-programming-interface"></a>

**Author:** Thomas Gleixner

<a id="rst-introduction"></a>

## Introduction

The generic Reed-Solomon Library provides encoding, decoding and error correction functions.

Reed-Solomon codes are used in communication and storage applications to ensure data integrity.

This documentation is provided for developers who want to utilize the functions provided by the library.

<a id="rst-known-bugs-and-assumptions"></a>

## Known Bugs And Assumptions

None.

<a id="rst-usage"></a>

## Usage

This chapter provides examples of how to use the library.

<a id="rst-initializing"></a>

### Initializing

The init function init_rs returns a pointer to an rs decoder structure, which holds the necessary information for encoding, decoding and error correction with the given polynomial. It either uses an existing matching decoder or creates a new one. On creation all the lookup tables for fast en/decoding are created. The function may take a while, so make sure not to call it in critical code paths.



```text
/* the Reed Solomon control structure */
static struct rs_control *rs_decoder;

/* Symbolsize is 10 (bits)
 * Primitive polynomial is x^10+x^3+1
 * first consecutive root is 0
 * primitive element to generate roots = 1
 * generator polynomial degree (number of roots) = 6
 */
rs_decoder = init_rs (10, 0x409, 0, 1, 6);
```

<a id="rst-encoding"></a>

### Encoding

The encoder calculates the Reed-Solomon code over the given data length and stores the result in the parity buffer. Note that the parity buffer must be initialized before calling the encoder.

The expanded data can be inverted on the fly by providing a non-zero inversion mask. The expanded data is XOR'ed with the mask. This is used e.g. for FLASH ECC, where the all 0xFF is inverted to an all 0x00. The Reed-Solomon code for all 0x00 is all 0x00. The code is inverted before storing to FLASH so it is 0xFF too. This prevents that reading from an erased FLASH results in ECC errors.

The databytes are expanded to the given symbol size on the fly. There is no support for encoding continuous bitstreams with a symbol size \!= 8 at the moment. If it is necessary it should be not a big deal to implement such functionality.



```text
/* Parity buffer. Size = number of roots */
uint16_t par[6];
/* Initialize the parity buffer */
memset(par, 0, sizeof(par));
/* Encode 512 byte in data8. Store parity in buffer par */
encode_rs8 (rs_decoder, data8, 512, par, 0);
```

<a id="rst-decoding"></a>

### Decoding

The decoder calculates the syndrome over the given data length and the received parity symbols and corrects errors in the data.

If a syndrome is available from a hardware decoder then the syndrome calculation is skipped.

The correction of the data buffer can be suppressed by providing a correction pattern buffer and an error location buffer to the decoder. The decoder stores the calculated error location and the correction bitmask in the given buffers. This is useful for hardware decoders which use a weird bit ordering scheme.

The databytes are expanded to the given symbol size on the fly. There is no support for decoding continuous bitstreams with a symbolsize \!= 8 at the moment. If it is necessary it should be not a big deal to implement such functionality.

<a id="rst-decoding-with-syndrome-calculation-direct-data-correction"></a>

#### Decoding with syndrome calculation, direct data correction



```text
/* Parity buffer. Size = number of roots */
uint16_t par[6];
uint8_t  data[512];
int numerr;
/* Receive data */
.....
/* Receive parity */
.....
/* Decode 512 byte in data8.*/
numerr = decode_rs8 (rs_decoder, data8, par, 512, NULL, 0, NULL, 0, NULL);
```

<a id="rst-decoding-with-syndrome-given-by-hardware-decoder-direct-data-correction"></a>

#### Decoding with syndrome given by hardware decoder, direct data correction



```text
/* Parity buffer. Size = number of roots */
uint16_t par[6], syn[6];
uint8_t  data[512];
int numerr;
/* Receive data */
.....
/* Receive parity */
.....
/* Get syndrome from hardware decoder */
.....
/* Decode 512 byte in data8.*/
numerr = decode_rs8 (rs_decoder, data8, par, 512, syn, 0, NULL, 0, NULL);
```

<a id="rst-decoding-with-syndrome-given-by-hardware-decoder-no-direct-data-correction"></a>

#### Decoding with syndrome given by hardware decoder, no direct data correction.

Note: It's not necessary to give data and received parity to the decoder.



```text
/* Parity buffer. Size = number of roots */
uint16_t par[6], syn[6], corr[8];
uint8_t  data[512];
int numerr, errpos[8];
/* Receive data */
.....
/* Receive parity */
.....
/* Get syndrome from hardware decoder */
.....
/* Decode 512 byte in data8.*/
numerr = decode_rs8 (rs_decoder, NULL, NULL, 512, syn, 0, errpos, 0, corr);
for (i = 0; i < numerr; i++) {
    do_error_correction_in_your_buffer(errpos[i], corr[i]);
}
```

<a id="rst-cleanup"></a>

### Cleanup

The function free_rs frees the allocated resources, if the caller is the last user of the decoder.



```text
/* Release resources */
free_rs(rs_decoder);
```

<a id="rst-structures"></a>

## Structures

This chapter contains the autogenerated documentation of the structures which are used in the Reed-Solomon Library and are relevant for a developer.


#### <a id="c-struct-rs_codec"></a>`struct rs_codec`

rs codec data

**Definition**

```c
struct rs_codec {
    int mm;
    int nn;
    uint16_t *alpha_to;
    uint16_t *index_of;
    uint16_t *genpoly;
    int nroots;
    int fcr;
    int prim;
    int iprim;
    int gfpoly;
    int (*gffunc)(int);
    int users;
    struct list_head list;
};
```

**Members**

- `mm`: Bits per symbol
- `nn`: Symbols per block (= (1\<\<mm)-1)
- `alpha_to`: log lookup table
- `index_of`: Antilog lookup table
- `genpoly`: Generator polynomial
- `nroots`: Number of generator roots = number of parity symbols
- `fcr`: First consecutive root, index form
- `prim`: Primitive element, index form
- `iprim`: prim-th root of 1, index form
- `gfpoly`: The primitive generator polynominal
- `gffunc`: Function to generate the field, if non-canonical representation
- `users`: Users of this structure
- `list`: List entry for the rs codec list

#### <a id="c-struct-rs_control"></a>`struct rs_control`

rs control structure per instance

**Definition**

```c
struct rs_control {
    struct rs_codec *codec;
    uint16_t buffers[];
};
```

**Members**

- `codec`: The codec used for this instance
- `buffers`: Internal scratch buffers used in calls to `decode_rs()`

#### <a id="c-init_rs"></a>`init_rs()`

```c
struct rs_control * init_rs(int symsize, int gfpoly, int fcr, int prim, int nroots)
```

Create a RS control struct and initialize it

**Parameters**

- `int symsize`: the symbol size (number of bits)
- `int gfpoly`: the extended Galois field generator polynomial coefficients,
  with the 0th coefficient in the low order bit. The polynomial
  must be primitive;
- `int fcr`: the first consecutive root of the rs code generator polynomial
  in index form
- `int prim`: primitive element to generate polynomial roots
- `int nroots`: RS code generator polynomial degree (number of roots)

**Description**

Allocations use GFP_KERNEL.


<a id="rst-public-functions-provided"></a>

## Public Functions Provided

This chapter contains the autogenerated documentation of the Reed-Solomon functions which are exported.


#### <a id="c-free_rs"></a>`free_rs()`

```c
void free_rs(struct rs_control *rs)
```

Free the rs control structure

**Parameters**

- `struct rs_control *rs`: The control structure which is not longer used by the
  caller

**Description**

Free the control structure. If **rs** is the last user of the associated
codec, free the codec as well.

#### <a id="c-init_rs_gfp"></a>`init_rs_gfp()`

```c
struct rs_control * init_rs_gfp(int symsize, int gfpoly, int fcr, int prim, int nroots, gfp_t gfp)
```

Create a RS control struct and initialize it

**Parameters**

- `int symsize`: the symbol size (number of bits)
- `int gfpoly`: the extended Galois field generator polynomial coefficients,
  with the 0th coefficient in the low order bit. The polynomial
  must be primitive;
- `int fcr`: the first consecutive root of the rs code generator polynomial
  in index form
- `int prim`: primitive element to generate polynomial roots
- `int nroots`: RS code generator polynomial degree (number of roots)
- `gfp_t gfp`: Memory allocation flags.

#### <a id="c-init_rs_non_canonical"></a>`init_rs_non_canonical()`

```c
struct rs_control * init_rs_non_canonical(int symsize, int (*gffunc)(int), int fcr, int prim, int nroots)
```

Allocate rs control struct for fields with non-canonical representation

**Parameters**

- `int symsize`: the symbol size (number of bits)
- `int (*gffunc)(int)`: pointer to function to generate the next field element,
  or the multiplicative identity element if given 0.  Used
  instead of gfpoly if gfpoly is 0
- `int fcr`: the first consecutive root of the rs code generator polynomial
  in index form
- `int prim`: primitive element to generate polynomial roots
- `int nroots`: RS code generator polynomial degree (number of roots)

#### <a id="c-encode_rs8"></a>`encode_rs8()`

```c
int encode_rs8(struct rs_control *rsc, uint8_t *data, int len, uint16_t *par, uint16_t invmsk)
```

Calculate the parity for data values (8bit data width)

**Parameters**

- `struct rs_control *rsc`: the rs control structure
- `uint8_t *data`: data field of a given type
- `int len`: data length
- `uint16_t *par`: parity data, must be initialized by caller (usually all 0)
- `uint16_t invmsk`: invert data mask (will be xored on data)

**Description**

The parity uses a uint16_t data type to enable
symbol size > 8. The calling code must take care of encoding of the
syndrome result for storage itself.

#### <a id="c-decode_rs8"></a>`decode_rs8()`

```c
int decode_rs8(struct rs_control *rsc, uint8_t *data, uint16_t *par, int len, uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk, uint16_t *corr)
```

Decode codeword (8bit data width)

**Parameters**

- `struct rs_control *rsc`: the rs control structure
- `uint8_t *data`: data field of a given type
- `uint16_t *par`: received parity data field
- `int len`: data length
- `uint16_t *s`: syndrome data field, must be in index form
  (if NULL, syndrome is calculated)
- `int no_eras`: number of erasures
- `int *eras_pos`: position of erasures, can be NULL
- `uint16_t invmsk`: invert data mask (will be xored on data, not on parity!)
- `uint16_t *corr`: buffer to store correction bitmask on eras_pos

**Description**

The syndrome and parity uses a uint16_t data type to enable
symbol size > 8. The calling code must take care of decoding of the
syndrome result and the received parity before calling this code.

**Note**

- The rs_control struct **rsc** contains buffers which are used for

  decoding, so the caller has to ensure that decoder invocations are
  serialized.

  Returns the number of corrected symbols or -EBADMSG for uncorrectable
  errors. The count includes errors in the parity.

#### <a id="c-encode_rs16"></a>`encode_rs16()`

```c
int encode_rs16(struct rs_control *rsc, uint16_t *data, int len, uint16_t *par, uint16_t invmsk)
```

Calculate the parity for data values (16bit data width)

**Parameters**

- `struct rs_control *rsc`: the rs control structure
- `uint16_t *data`: data field of a given type
- `int len`: data length
- `uint16_t *par`: parity data, must be initialized by caller (usually all 0)
- `uint16_t invmsk`: invert data mask (will be xored on data, not on parity!)

**Description**

Each field in the data array contains up to symbol size bits of valid data.

#### <a id="c-decode_rs16"></a>`decode_rs16()`

```c
int decode_rs16(struct rs_control *rsc, uint16_t *data, uint16_t *par, int len, uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk, uint16_t *corr)
```

Decode codeword (16bit data width)

**Parameters**

- `struct rs_control *rsc`: the rs control structure
- `uint16_t *data`: data field of a given type
- `uint16_t *par`: received parity data field
- `int len`: data length
- `uint16_t *s`: syndrome data field, must be in index form
  (if NULL, syndrome is calculated)
- `int no_eras`: number of erasures
- `int *eras_pos`: position of erasures, can be NULL
- `uint16_t invmsk`: invert data mask (will be xored on data, not on parity!)
- `uint16_t *corr`: buffer to store correction bitmask on eras_pos

**Description**

Each field in the data array contains up to symbol size bits of valid data.

**Note**

- The rc_control struct **rsc** contains buffers which are used for

  decoding, so the caller has to ensure that decoder invocations are
  serialized.

  Returns the number of corrected symbols or -EBADMSG for uncorrectable
  errors. The count includes errors in the parity.


<a id="rst-credits"></a>

## Credits

The library code for encoding and decoding was written by Phil Karn.



```text
Copyright 2002, Phil Karn, KA9Q
May be used under the terms of the GNU General Public License (GPL)
```

The wrapper functions and interfaces are written by Thomas Gleixner.

Many users have provided bugfixes, improvements and helping hands for testing. Thanks a lot.

The following people have contributed to this document:

Thomas Gleixner[tglx@kernel.org](<mailto:tglx@kernel.org>)

---

# Linked Lists in Linux

_Peios Kernel / Internals / Core APIs_

> Introduction

<a id="rst-linked-lists-in-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** Nicolas Frattaroli &lt;[nicolas.frattaroli@collabora.com](<mailto:nicolas.frattaroli@collabora.com>)&gt;

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

Linked lists are one of the most basic data structures used in many programs. The Linux kernel implements several different flavours of linked lists. The purpose of this document is not to explain linked lists in general, but to show new kernel developers how to use the Linux kernel implementations of linked lists.

Please note that while linked lists certainly are ubiquitous, they are rarely the best data structure to use in cases where a simple array doesn't already suffice. In particular, due to their poor data locality, linked lists are a bad choice in situations where performance may be of consideration. Familiarizing oneself with other in-kernel generic data structures, especially for concurrent accesses, is highly encouraged.

<a id="rst-linux-implementation-of-doubly-linked-lists"></a>

## Linux implementation of doubly linked lists

Linux's linked list implementations can be used by including the header file `<linux/list.h>`.

The doubly-linked list will likely be the most familiar to many readers. It's a list that can efficiently be traversed forwards and backwards.

The Linux kernel's doubly-linked list is circular in nature. This means that to get from the head node to the tail, we can just travel one edge backwards. Similarly, to get from the tail node to the head, we can simply travel forwards "beyond" the tail and arrive back at the head.

<a id="rst-declaring-a-node"></a>

### Declaring a node

A node in a doubly-linked list is declared by adding a struct list_head member to the data structure you wish to be contained in the list:



```c
struct clown {
        unsigned long long shoe_size;
        const char *name;
        struct list_head node;  /* the aforementioned member */
};
```

This may be an unfamiliar approach to some, as the classical explanation of a linked list is a list node data structure with pointers to the previous and next list node, as well the payload data. Linux chooses this approach because it allows for generic list modification code regardless of what data structure is contained within the list. Since the struct list_head member is not a pointer but part of the data structure proper, the container_of() pattern can be used by the list implementation to access the payload data regardless of its type, while staying oblivious to what said type actually is.

<a id="rst-declaring-and-initializing-a-list"></a>

### Declaring and initializing a list

A doubly-linked list can then be declared as just another struct list_head, and initialized with the LIST_HEAD_INIT() macro during initial assignment, or with the INIT_LIST_HEAD() function later:



```c
struct clown_car {
        int tyre_pressure[4];
        struct list_head clowns;        /* Looks like a node! */
};

/* ... Somewhere later in our driver ... */

static int circus_init(struct circus_priv *circus)
{
        struct clown_car other_car = {
              .tyre_pressure = {10, 12, 11, 9},
              .clowns = LIST_HEAD_INIT(other_car.clowns)
        };

        INIT_LIST_HEAD(&circus->car.clowns);

        return 0;
}
```

A further point of confusion to some may be that the list itself doesn't really have its own type. The concept of the entire linked list and a struct list_head member that points to other entries in the list are one and the same.

<a id="rst-adding-nodes-to-the-list"></a>

### Adding nodes to the list

Adding a node to the linked list is done through the list_add() macro.

We'll return to our clown car example to illustrate how nodes get added to the list:



```c
static int circus_fill_car(struct circus_priv *circus)
{
        struct clown_car *car = &circus->car;
        struct clown *grock;
        struct clown *dimitri;

        /* State 1 */

        grock = kzalloc(sizeof(*grock), GFP_KERNEL);
        if (!grock)
                return -ENOMEM;
        grock->name = "Grock";
        grock->shoe_size = 1000;

        /* Note that we're adding the "node" member */
        list_add(&grock->node, &car->clowns);

        /* State 2 */

        dimitri = kzalloc(sizeof(*dimitri), GFP_KERNEL);
        if (!dimitri)
                return -ENOMEM;
        dimitri->name = "Dimitri";
        dimitri->shoe_size = 50;

        list_add(&dimitri->node, &car->clowns);

        /* State 3 */

        return 0;
}
```

In State 1, our list of clowns is still empty:



```text
     .------.
     v      |
.--------.  |
| clowns |--'
'--------'
```

This diagram shows the singular "clowns" node pointing at itself. In this diagram, and all following diagrams, only the forward edges are shown, to aid in clarity.

In State 2, we've added Grock after the list head:



```text
     .--------------------.
     v                    |
.--------.     .-------.  |
| clowns |---->| Grock |--'
'--------'     '-------'
```

This diagram shows the "clowns" node pointing at a new node labeled "Grock". The Grock node is pointing back at the "clowns" node.

In State 3, we've added Dimitri after the list head, resulting in the following:



```text
     .------------------------------------.
     v                                    |
.--------.     .---------.     .-------.  |
| clowns |---->| Dimitri |---->| Grock |--'
'--------'     '---------'     '-------'
```

This diagram shows the "clowns" node pointing at a new node labeled "Dimitri", which then points at the node labeled "Grock". The "Grock" node still points back at the "clowns" node.

If we wanted to have Dimitri inserted at the end of the list instead, we'd use list_add_tail(). Our code would then look like this:



```c
static int circus_fill_car(struct circus_priv *circus)
{
        /* ... */

        list_add_tail(&dimitri->node, &car->clowns);

        /* State 3b */

        return 0;
}
```

This results in the following list:



```text
     .------------------------------------.
     v                                    |
.--------.     .-------.     .---------.  |
| clowns |---->| Grock |---->| Dimitri |--'
'--------'     '-------'     '---------'
```

This diagram shows the "clowns" node pointing at the node labeled "Grock", which points at the new node labeled "Dimitri". The node labeled "Dimitri" points back at the "clowns" node.

<a id="rst-traversing-the-list"></a>

### Traversing the list

To iterate the list, we can loop through all nodes within the list with list_for_each().

In our clown example, this results in the following somewhat awkward code:



```c
static unsigned long long circus_get_max_shoe_size(struct circus_priv *circus)
{
        unsigned long long res = 0;
        struct clown *e;
        struct list_head *cur;

        list_for_each(cur, &circus->car.clowns) {
                e = list_entry(cur, struct clown, node);
                if (e->shoe_size > res)
                        res = e->shoe_size;
        }

        return res;
}
```

The list_entry() macro internally uses the aforementioned container_of() to retrieve the data structure instance that `node` is a member of.

Note how the additional list_entry() call is a little awkward here. It's only there because we're iterating through the `node` members, but we really want to iterate through the payload, i.e. the `struct clown` that contains each node's struct list_head. For this reason, there is a second macro: list_for_each_entry()

Using it would change our code to something like this:



```c
static unsigned long long circus_get_max_shoe_size(struct circus_priv *circus)
{
        unsigned long long res = 0;
        struct clown *e;

        list_for_each_entry(e, &circus->car.clowns, node) {
                if (e->shoe_size > res)
                        res = e->shoe_size;
        }

        return res;
}
```

This eliminates the need for the list_entry() step, and our loop cursor is now of the type of our payload. The macro is given the member name that corresponds to the list's struct list_head within the clown data structure so that it can still walk the list.

<a id="rst-removing-nodes-from-the-list"></a>

### Removing nodes from the list

The list_del() function can be used to remove entries from the list. It not only removes the given entry from the list, but poisons the entry's `prev` and `next` pointers, so that unintended use of the entry after removal does not go unnoticed.

We can extend our previous example to remove one of the entries:



```c
static int circus_fill_car(struct circus_priv *circus)
{
        /* ... */

        list_add(&dimitri->node, &car->clowns);

        /* State 3 */

        list_del(&dimitri->node);

        /* State 4 */

        return 0;
}
```

The result of this would be this:



```text
     .--------------------.
     v                    |
.--------.     .-------.  |      .---------.
| clowns |---->| Grock |--'      | Dimitri |
'--------'     '-------'         '---------'
```

This diagram shows the "clowns" node pointing at the node labeled "Grock", which points back at the "clowns" node. Off to the side is a lone node labeled "Dimitri", which has no arrows pointing anywhere.

Note how the Dimitri node does not point to itself; its pointers are intentionally set to a "poison" value that the list code refuses to traverse.

If we wanted to reinitialize the removed node instead to make it point at itself again like an empty list head, we can use list_del_init() instead:



```c
static int circus_fill_car(struct circus_priv *circus)
{
        /* ... */

        list_add(&dimitri->node, &car->clowns);

        /* State 3 */

        list_del_init(&dimitri->node);

        /* State 4b */

        return 0;
}
```

This results in the deleted node pointing to itself again:



```text
     .--------------------.           .-------.
     v                    |           v       |
.--------.     .-------.  |      .---------.  |
| clowns |---->| Grock |--'      | Dimitri |--'
'--------'     '-------'         '---------'
```

This diagram shows the "clowns" node pointing at the node labeled "Grock", which points back at the "clowns" node. Off to the side is a lone node labeled "Dimitri", which points to itself.

<a id="rst-traversing-whilst-removing-nodes"></a>

### Traversing whilst removing nodes

Deleting entries while we're traversing the list will cause problems if we use list_for_each() and list_for_each_entry(), as deleting the current entry would modify the `next` pointer of it, which means the traversal can't properly advance to the next list entry.

There is a solution to this however: list_for_each_safe() and list_for_each_entry_safe(). These take an additional parameter of a pointer to a struct list_head to use as temporary storage for the next entry during iteration, solving the issue.

An example of how to use it:



```c
static void circus_eject_insufficient_clowns(struct circus_priv *circus)
{
        struct clown *e;
        struct clown *n;      /* temporary storage for safe iteration */

        list_for_each_entry_safe(e, n, &circus->car.clowns, node) {
              if (e->shoe_size < 500)
                      list_del(&e->node);
        }
}
```

Proper memory management (i.e. freeing the deleted node while making sure nothing still references it) in this case is left as an exercise to the reader.

<a id="rst-cutting-a-list"></a>

### Cutting a list

There are two helper functions to cut lists with. Both take elements from the list `head`, and replace the contents of the list `list`.

The first such function is list_cut_position(). It removes all list entries from `head` up to and including `entry`, placing them in `list` instead.

In this example, it's assumed we start with the following list:



```text
     .----------------------------------------------------------------.
     v                                                                |
.--------.     .-------.     .---------.     .-----.     .---------.  |
| clowns |---->| Grock |---->| Dimitri |---->| Pic |---->| Alfredo |--'
'--------'     '-------'     '---------'     '-----'     '---------'
```

With the following code, every clown up to and including "Pic" is moved from the "clowns" list head to a separate struct list_head initialized at local stack variable `retirement`:



```c
static void circus_retire_clowns(struct circus_priv *circus)
{
        struct list_head retirement = LIST_HEAD_INIT(retirement);
        struct clown *grock, *dimitri, *pic, *alfredo;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        list_cut_position(&retirement, &car->clowns, &pic->node);

        /* State 1 */
}
```

The resulting `car->clowns` list would be this:



```text
     .----------------------.
     v                      |
.--------.     .---------.  |
| clowns |---->| Alfredo |--'
'--------'     '---------'
```

Meanwhile, the `retirement` list is transformed to the following:



```text
       .--------------------------------------------------.
       v                                                  |
.------------.     .-------.     .---------.     .-----.  |
| retirement |---->| Grock |---->| Dimitri |---->| Pic |--'
'------------'     '-------'     '---------'     '-----'
```

The second function, list_cut_before(), is much the same, except it cuts before the `entry` node, i.e. it removes all list entries from `head` up to but excluding `entry`, placing them in `list` instead. This example assumes the same initial starting list as the previous example:



```c
static void circus_retire_clowns(struct circus_priv *circus)
{
        struct list_head retirement = LIST_HEAD_INIT(retirement);
        struct clown *grock, *dimitri, *pic, *alfredo;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        list_cut_before(&retirement, &car->clowns, &pic->node);

        /* State 1b */
}
```

The resulting `car->clowns` list would be this:



```text
     .----------------------------------.
     v                                  |
.--------.     .-----.     .---------.  |
| clowns |---->| Pic |---->| Alfredo |--'
'--------'     '-----'     '---------'
```

Meanwhile, the `retirement` list is transformed to the following:



```text
       .--------------------------------------.
       v                                      |
.------------.     .-------.     .---------.  |
| retirement |---->| Grock |---->| Dimitri |--'
'------------'     '-------'     '---------'
```

It should be noted that both functions will destroy links to any existing nodes in the destination `struct list_head *list`.

<a id="rst-moving-entries-and-partial-lists"></a>

### Moving entries and partial lists

The list_move() and list_move_tail() functions can be used to move an entry from one list to another, to either the start or end respectively.

In the following example, we'll assume we start with two lists ("clowns" and "sidewalk" in the following initial state "State 0":



```text
     .----------------------------------------------------------------.
     v                                                                |
.--------.     .-------.     .---------.     .-----.     .---------.  |
| clowns |---->| Grock |---->| Dimitri |---->| Pic |---->| Alfredo |--'
'--------'     '-------'     '---------'     '-----'     '---------'

      .-------------------.
      v                   |
.----------.     .-----.  |
| sidewalk |---->| Pio |--'
'----------'     '-----'
```

We apply the following example code to the two lists:



```c
static void circus_clowns_exit_car(struct circus_priv *circus)
{
        struct list_head sidewalk = LIST_HEAD_INIT(sidewalk);
        struct clown *grock, *dimitri, *pic, *alfredo, *pio;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        /* State 0 */

        list_move(&pic->node, &sidewalk);

        /* State 1 */

        list_move_tail(&dimitri->node, &sidewalk);

        /* State 2 */
}
```

In State 1, we arrive at the following situation:



```text
    .-----------------------------------------------------.
    |                                                     |
    v                                                     |
.--------.     .-------.     .---------.     .---------.  |
| clowns |---->| Grock |---->| Dimitri |---->| Alfredo |--'
'--------'     '-------'     '---------'     '---------'

      .-------------------------------.
      v                               |
.----------.     .-----.     .-----.  |
| sidewalk |---->| Pic |---->| Pio |--'
'----------'     '-----'     '-----'
```

In State 2, after we've moved Dimitri to the tail of sidewalk, the situation changes as follows:



```text
    .-------------------------------------.
    |                                     |
    v                                     |
.--------.     .-------.     .---------.  |
| clowns |---->| Grock |---->| Alfredo |--'
'--------'     '-------'     '---------'

      .-----------------------------------------------.
      v                                               |
.----------.     .-----.     .-----.     .---------.  |
| sidewalk |---->| Pic |---->| Pio |---->| Dimitri |--'
'----------'     '-----'     '-----'     '---------'
```

As long as the source and destination list head are part of the same list, we can also efficiently bulk move a segment of the list to the tail end of the list. We continue the previous example by adding a list_bulk_move_tail() after State 2, moving Pic and Pio to the tail end of the sidewalk list.



```c
static void circus_clowns_exit_car(struct circus_priv *circus)
{
        struct list_head sidewalk = LIST_HEAD_INIT(sidewalk);
        struct clown *grock, *dimitri, *pic, *alfredo, *pio;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        /* State 0 */

        list_move(&pic->node, &sidewalk);

        /* State 1 */

        list_move_tail(&dimitri->node, &sidewalk);

        /* State 2 */

        list_bulk_move_tail(&sidewalk, &pic->node, &pio->node);

        /* State 3 */
}
```

For the sake of brevity, only the altered "sidewalk" list at State 3 is depicted in the following diagram:



```text
      .-----------------------------------------------.
      v                                               |
.----------.     .---------.     .-----.     .-----.  |
| sidewalk |---->| Dimitri |---->| Pic |---->| Pio |--'
'----------'     '---------'     '-----'     '-----'
```

Do note that list_bulk_move_tail() does not do any checking as to whether all three supplied `struct list_head *` parameters really do belong to the same list. If you use it outside the constraints the documentation gives, then the result is a matter between you and the implementation.

<a id="rst-rotating-entries"></a>

### Rotating entries

A common write operation on lists, especially when using them as queues, is to rotate it. A list rotation means entries at the front are sent to the back.

For rotation, Linux provides us with two functions: list_rotate_left() and list_rotate_to_front(). The former can be pictured like a bicycle chain, taking the entry after the supplied `struct list_head *` and moving it to the tail, which in essence means the entire list, due to its circular nature, rotates by one position.

The latter, list_rotate_to_front(), takes the same concept one step further: instead of advancing the list by one entry, it advances it *until* the specified entry is the new front.

In the following example, our starting state, State 0, is the following:



```text
     .-----------------------------------------------------------------.
     v                                                                 |
.--------.   .-------.   .---------.   .-----.   .---------.   .-----. |
| clowns |-->| Grock |-->| Dimitri |-->| Pic |-->| Alfredo |-->| Pio |-'
'--------'   '-------'   '---------'   '-----'   '---------'   '-----'
```

The example code being used to demonstrate list rotations is the following:



```c
static void circus_clowns_rotate(struct circus_priv *circus)
{
        struct clown *grock, *dimitri, *pic, *alfredo, *pio;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        /* State 0 */

        list_rotate_left(&car->clowns);

        /* State 1 */

        list_rotate_to_front(&alfredo->node, &car->clowns);

        /* State 2 */

}
```

In State 1, we arrive at the following situation:



```text
     .-----------------------------------------------------------------.
     v                                                                 |
.--------.   .---------.   .-----.   .---------.   .-----.   .-------. |
| clowns |-->| Dimitri |-->| Pic |-->| Alfredo |-->| Pio |-->| Grock |-'
'--------'   '---------'   '-----'   '---------'   '-----'   '-------'
```

Next, after the list_rotate_to_front() call, we arrive in the following State 2:



```text
     .-----------------------------------------------------------------.
     v                                                                 |
.--------.   .---------.   .-----.   .-------.   .---------.   .-----. |
| clowns |-->| Alfredo |-->| Pio |-->| Grock |-->| Dimitri |-->| Pic |-'
'--------'   '---------'   '-----'   '-------'   '---------'   '-----'
```

As is hopefully evident from the diagrams, the entries in front of "Alfredo" were cycled to the tail end of the list.

<a id="rst-swapping-entries"></a>

### Swapping entries

Another common operation is that two entries need to be swapped with each other.

For this, Linux provides us with list_swap().

In the following example, we have a list with three entries, and swap two of them. This is our starting state in "State 0":



```text
     .-----------------------------------------.
     v                                         |
.--------.   .-------.   .---------.   .-----. |
| clowns |-->| Grock |-->| Dimitri |-->| Pic |-'
'--------'   '-------'   '---------'   '-----'
```



```c
static void circus_clowns_swap(struct circus_priv *circus)
{
        struct clown *grock, *dimitri, *pic;
        struct clown_car *car = &circus->car;

        /* ... clown initialization, list adding ... */

        /* State 0 */

        list_swap(&dimitri->node, &pic->node);

        /* State 1 */
}
```

The resulting list at State 1 is the following:



```text
     .-----------------------------------------.
     v                                         |
.--------.   .-------.   .-----.   .---------. |
| clowns |-->| Grock |-->| Pic |-->| Dimitri |-'
'--------'   '-------'   '-----'   '---------'
```

As is evident by comparing the diagrams, the "Pic" and "Dimitri" nodes have traded places.

<a id="rst-splicing-two-lists-together"></a>

### Splicing two lists together

Say we have two lists, in the following example one represented by a list head we call "knie" and one we call "stey". In a hypothetical circus acquisition, the two list of clowns should be spliced together. The following is our situation in "State 0":



```text
    .-----------------------------------------.
    |                                         |
    v                                         |
.------.   .-------.   .---------.   .-----.  |
| knie |-->| Grock |-->| Dimitri |-->| Pic |--'
'------'   '-------'   '---------'   '-----'

    .-----------------------------.
    v                             |
.------.   .---------.   .-----.  |
| stey |-->| Alfredo |-->| Pio |--'
'------'   '---------'   '-----'
```

The function to splice these two lists together is list_splice(). Our example code is as follows:



```c
static void circus_clowns_splice(void)
{
        struct clown *grock, *dimitri, *pic, *alfredo, *pio;
        struct list_head knie = LIST_HEAD_INIT(knie);
        struct list_head stey = LIST_HEAD_INIT(stey);

        /* ... Clown allocation and initialization here ... */

        list_add_tail(&grock->node, &knie);
        list_add_tail(&dimitri->node, &knie);
        list_add_tail(&pic->node, &knie);
        list_add_tail(&alfredo->node, &stey);
        list_add_tail(&pio->node, &stey);

        /* State 0 */

        list_splice(&stey, &dimitri->node);

        /* State 1 */
}
```

The list_splice() call here adds all the entries in `stey` to the list `dimitri`'s `node` list_head is in, after the `node` of `dimitri`. A somewhat surprising diagram of the resulting "State 1" follows:



```text
    .-----------------------------------------------------------------.
    |                                                                 |
    v                                                                 |
.------.   .-------.   .---------.   .---------.   .-----.   .-----.  |
| knie |-->| Grock |-->| Dimitri |-->| Alfredo |-->| Pio |-->| Pic |--'
'------'   '-------'   '---------'   '---------'   '-----'   '-----'
                                          ^
          .-------------------------------'
          |
.------.  |
| stey |--'
'------'
```

Traversing the `stey` list no longer results in correct behavior. A call of list_for_each() on `stey` results in an infinite loop, as it never returns back to the `stey` list head.

This is because list_splice() did not reinitialize the list_head it took entries from, leaving its pointer pointing into what is now a different list.

If we want to avoid this situation, list_splice_init() can be used. It does the same thing as list_splice(), except reinitalizes the donor list_head after the transplant.

<a id="rst-concurrency-considerations"></a>

### Concurrency considerations

Concurrent access and modification of a list needs to be protected with a lock in most cases. Alternatively and preferably, one may use the RCU primitives for lists in read-mostly use-cases, where read accesses to the list are common but modifications to the list less so. See [Documentation/RCU/listRCU.rst](/kernel/internals/rcu/listrcu.md) for more details.

<a id="rst-further-reading"></a>

### Further reading

- [How does the kernel implements Linked Lists? - KernelNewbies](<https://kernelnewbies.org/FAQ/LinkedLists>)<a id="rst-how-does-the-kernel-implements-linked-lists-kernelnewbies"></a>

<a id="rst-full-list-api"></a>

## Full List API


#### <a id="c-LIST_HEAD_INIT"></a>`LIST_HEAD_INIT()`

```c
LIST_HEAD_INIT(name)
```

initialize a `struct list_head`'s links to point to itself

**Parameters**

- `name`: name of the list_head

#### <a id="c-LIST_HEAD"></a>`LIST_HEAD()`

```c
LIST_HEAD(name)
```

definition of a `struct list_head` with initialization values

**Parameters**

- `name`: name of the list_head

#### <a id="c-INIT_LIST_HEAD"></a>`INIT_LIST_HEAD()`

```c
void INIT_LIST_HEAD(struct list_head *list)
```

Initialize a list_head structure

**Parameters**

- `struct list_head *list`: list_head structure to be initialized.

**Description**

Initializes the list_head to point to itself.  If it is a list header,
the result is an empty list.

#### <a id="c-list_add"></a>`list_add()`

```c
void list_add(struct list_head *new, struct list_head *head)
```

add a new entry

**Parameters**

- `struct list_head *new`: new entry to be added
- `struct list_head *head`: list head to add it after

**Description**

Insert a new entry after the specified head.
This is good for implementing stacks.

#### <a id="c-list_add_tail"></a>`list_add_tail()`

```c
void list_add_tail(struct list_head *new, struct list_head *head)
```

add a new entry

**Parameters**

- `struct list_head *new`: new entry to be added
- `struct list_head *head`: list head to add it before

**Description**

Insert a new entry before the specified head.
This is useful for implementing queues.

#### <a id="c-list_del"></a>`list_del()`

```c
void list_del(struct list_head *entry)
```

deletes entry from list.

**Parameters**

- `struct list_head *entry`: the element to delete from the list.

**Note**

[`list_empty()`](#c-list_empty) on entry does not return true after this, the entry is
in an undefined state.

#### <a id="c-list_replace"></a>`list_replace()`

```c
void list_replace(struct list_head *old, struct list_head *new)
```

replace old entry by new one

**Parameters**

- `struct list_head *old`: the element to be replaced
- `struct list_head *new`: the new element to insert

**Description**

If **old** was empty, it will be overwritten.

#### <a id="c-list_replace_init"></a>`list_replace_init()`

```c
void list_replace_init(struct list_head *old, struct list_head *new)
```

replace old entry by new one and initialize the old one

**Parameters**

- `struct list_head *old`: the element to be replaced
- `struct list_head *new`: the new element to insert

**Description**

If **old** was empty, it will be overwritten.

#### <a id="c-list_swap"></a>`list_swap()`

```c
void list_swap(struct list_head *entry1, struct list_head *entry2)
```

replace entry1 with entry2 and re-add entry1 at entry2's position

**Parameters**

- `struct list_head *entry1`: the location to place entry2
- `struct list_head *entry2`: the location to place entry1

#### <a id="c-list_del_init"></a>`list_del_init()`

```c
void list_del_init(struct list_head *entry)
```

deletes entry from list and reinitialize it.

**Parameters**

- `struct list_head *entry`: the element to delete from the list.

#### <a id="c-list_move"></a>`list_move()`

```c
void list_move(struct list_head *list, struct list_head *head)
```

delete from one list and add as another's head

**Parameters**

- `struct list_head *list`: the entry to move
- `struct list_head *head`: the head that will precede our entry

#### <a id="c-list_move_tail"></a>`list_move_tail()`

```c
void list_move_tail(struct list_head *list, struct list_head *head)
```

delete from one list and add as another's tail

**Parameters**

- `struct list_head *list`: the entry to move
- `struct list_head *head`: the head that will follow our entry

#### <a id="c-list_bulk_move_tail"></a>`list_bulk_move_tail()`

```c
void list_bulk_move_tail(struct list_head *head, struct list_head *first, struct list_head *last)
```

move a subsection of a list to its tail

**Parameters**

- `struct list_head *head`: the head that will follow our entry
- `struct list_head *first`: first entry to move
- `struct list_head *last`: last entry to move, can be the same as first

**Description**

Move all entries between **first** and including **last** before **head**.
All three entries must belong to the same linked list.

#### <a id="c-list_is_first"></a>`list_is_first()`

```c
int list_is_first(const struct list_head *list, const struct list_head *head)
```

- tests whether **list** is the first entry in list **head**

**Parameters**

- `const struct list_head *list`: the entry to test
- `const struct list_head *head`: the head of the list

#### <a id="c-list_is_last"></a>`list_is_last()`

```c
int list_is_last(const struct list_head *list, const struct list_head *head)
```

tests whether **list** is the last entry in list **head**

**Parameters**

- `const struct list_head *list`: the entry to test
- `const struct list_head *head`: the head of the list

#### <a id="c-list_is_head"></a>`list_is_head()`

```c
int list_is_head(const struct list_head *list, const struct list_head *head)
```

tests whether **list** is the list **head**

**Parameters**

- `const struct list_head *list`: the entry to test
- `const struct list_head *head`: the head of the list

#### <a id="c-list_empty"></a>`list_empty()`

```c
int list_empty(const struct list_head *head)
```

tests whether a list is empty

**Parameters**

- `const struct list_head *head`: the list to test.

#### <a id="c-list_del_init_careful"></a>`list_del_init_careful()`

```c
void list_del_init_careful(struct list_head *entry)
```

deletes entry from list and reinitialize it.

**Parameters**

- `struct list_head *entry`: the element to delete from the list.

**Description**

This is the same as [`list_del_init()`](#c-list_del_init), except designed to be used
together with [`list_empty_careful()`](#c-list_empty_careful) in a way to guarantee ordering
of other memory operations.

Any memory operations done before a [`list_del_init_careful()`](#c-list_del_init_careful) are
guaranteed to be visible after a [`list_empty_careful()`](#c-list_empty_careful) test.

#### <a id="c-list_empty_careful"></a>`list_empty_careful()`

```c
int list_empty_careful(const struct list_head *head)
```

tests whether a list is empty and not being modified

**Parameters**

- `const struct list_head *head`: the list to test

**Description**

tests whether a list is empty _and_ checks that no other CPU might be
in the process of modifying either member (next or prev)

**NOTE**

using [`list_empty_careful()`](#c-list_empty_careful) without synchronization
can only be safe if the only activity that can happen
to the list entry is [`list_del_init()`](#c-list_del_init). Eg. it cannot be used
if another CPU could re-[`list_add()`](#c-list_add) it.

#### <a id="c-list_rotate_left"></a>`list_rotate_left()`

```c
void list_rotate_left(struct list_head *head)
```

rotate the list to the left

**Parameters**

- `struct list_head *head`: the head of the list

#### <a id="c-list_rotate_to_front"></a>`list_rotate_to_front()`

```c
void list_rotate_to_front(struct list_head *list, struct list_head *head)
```

Rotate list to specific item.

**Parameters**

- `struct list_head *list`: The desired new front of the list.
- `struct list_head *head`: The head of the list.

**Description**

Rotates list so that **list** becomes the new front of the list.

#### <a id="c-list_is_singular"></a>`list_is_singular()`

```c
int list_is_singular(const struct list_head *head)
```

tests whether a list has just one entry.

**Parameters**

- `const struct list_head *head`: the list to test.

#### <a id="c-list_cut_position"></a>`list_cut_position()`

```c
void list_cut_position(struct list_head *list, struct list_head *head, struct list_head *entry)
```

cut a list into two

**Parameters**

- `struct list_head *list`: a new list to add all removed entries
- `struct list_head *head`: a list with entries
- `struct list_head *entry`: an entry within head, could be the head itself
  and if so we won't cut the list

**Description**

This helper moves the initial part of **head**, up to and
including **entry**, from **head** to **list**. You should
pass on **entry** an element you know is on **head**. **list**
should be an empty list or a list you do not care about
losing its data.

#### <a id="c-list_cut_before"></a>`list_cut_before()`

```c
void list_cut_before(struct list_head *list, struct list_head *head, struct list_head *entry)
```

cut a list into two, before given entry

**Parameters**

- `struct list_head *list`: a new list to add all removed entries
- `struct list_head *head`: a list with entries
- `struct list_head *entry`: an entry within head, could be the head itself

**Description**

This helper moves the initial part of **head**, up to but
excluding **entry**, from **head** to **list**.  You should pass
in **entry** an element you know is on **head**.  **list** should
be an empty list or a list you do not care about losing
its data.
If **entry** == **head**, all entries on **head** are moved to
**list**.

#### <a id="c-list_splice"></a>`list_splice()`

```c
void list_splice(const struct list_head *list, struct list_head *head)
```

join two lists, this is designed for stacks

**Parameters**

- `const struct list_head *list`: the new list to add.
- `struct list_head *head`: the place to add it in the first list.

#### <a id="c-list_splice_tail"></a>`list_splice_tail()`

```c
void list_splice_tail(struct list_head *list, struct list_head *head)
```

join two lists, each list being a queue

**Parameters**

- `struct list_head *list`: the new list to add.
- `struct list_head *head`: the place to add it in the first list.

#### <a id="c-list_splice_init"></a>`list_splice_init()`

```c
void list_splice_init(struct list_head *list, struct list_head *head)
```

join two lists and reinitialise the emptied list.

**Parameters**

- `struct list_head *list`: the new list to add.
- `struct list_head *head`: the place to add it in the first list.

**Description**

The list at **list** is reinitialised

#### <a id="c-list_splice_tail_init"></a>`list_splice_tail_init()`

```c
void list_splice_tail_init(struct list_head *list, struct list_head *head)
```

join two lists and reinitialise the emptied list

**Parameters**

- `struct list_head *list`: the new list to add.
- `struct list_head *head`: the place to add it in the first list.

**Description**

Each of the lists is a queue.
The list at **list** is reinitialised

#### <a id="c-list_entry"></a>`list_entry()`

```c
list_entry(ptr, type, member)
```

get the struct for this entry

**Parameters**

- `ptr`: the `struct list_head` pointer.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_first_entry"></a>`list_first_entry()`

```c
list_first_entry(ptr, type, member)
```

get the first element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note, that list is expected to be not empty.

#### <a id="c-list_last_entry"></a>`list_last_entry()`

```c
list_last_entry(ptr, type, member)
```

get the last element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note, that list is expected to be not empty.

#### <a id="c-list_first_entry_or_null"></a>`list_first_entry_or_null()`

```c
list_first_entry_or_null(ptr, type, member)
```

get the first element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note that if the list is empty, it returns NULL.

#### <a id="c-list_last_entry_or_null"></a>`list_last_entry_or_null()`

```c
list_last_entry_or_null(ptr, type, member)
```

get the last element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the name of the list_head within the struct.

**Description**

Note that if the list is empty, it returns NULL.

#### <a id="c-list_next_entry"></a>`list_next_entry()`

```c
list_next_entry(pos, member)
```

get the next element in list

**Parameters**

- `pos`: the type * to cursor
- `member`: the name of the list_head within the struct.

#### <a id="c-list_next_entry_circular"></a>`list_next_entry_circular()`

```c
list_next_entry_circular(pos, head, member)
```

get the next element in list

**Parameters**

- `pos`: the type * to cursor.
- `head`: the list head to take the element from.
- `member`: the name of the list_head within the struct.

**Description**

Wraparound if pos is the last element (return the first element).
Note, that list is expected to be not empty.

#### <a id="c-list_prev_entry"></a>`list_prev_entry()`

```c
list_prev_entry(pos, member)
```

get the prev element in list

**Parameters**

- `pos`: the type * to cursor
- `member`: the name of the list_head within the struct.

#### <a id="c-list_prev_entry_circular"></a>`list_prev_entry_circular()`

```c
list_prev_entry_circular(pos, head, member)
```

get the prev element in list

**Parameters**

- `pos`: the type * to cursor.
- `head`: the list head to take the element from.
- `member`: the name of the list_head within the struct.

**Description**

Wraparound if pos is the first element (return the last element).
Note, that list is expected to be not empty.

#### <a id="c-list_for_each"></a>`list_for_each()`

```c
list_for_each(pos, head)
```

iterate over a list

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `head`: the head for your list.

#### <a id="c-list_for_each_continue"></a>`list_for_each_continue()`

```c
list_for_each_continue(pos, head)
```

continue iteration over a list

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `head`: the head for your list.

**Description**

Continue to iterate over a list, continuing after the current position.

#### <a id="c-list_for_each_prev"></a>`list_for_each_prev()`

```c
list_for_each_prev(pos, head)
```

iterate over a list backwards

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `head`: the head for your list.

#### <a id="c-list_for_each_safe"></a>`list_for_each_safe()`

```c
list_for_each_safe(pos, n, head)
```

iterate over a list safe against removal of list entry

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `n`: another `struct list_head` to use as temporary storage
- `head`: the head for your list.

#### <a id="c-list_for_each_prev_safe"></a>`list_for_each_prev_safe()`

```c
list_for_each_prev_safe(pos, n, head)
```

iterate over a list backwards safe against removal of list entry

**Parameters**

- `pos`: the `struct list_head` to use as a loop cursor.
- `n`: another `struct list_head` to use as temporary storage
- `head`: the head for your list.

#### <a id="c-list_count_nodes"></a>`list_count_nodes()`

```c
size_t list_count_nodes(struct list_head *head)
```

count nodes in the list

**Parameters**

- `struct list_head *head`: the head for your list.

#### <a id="c-list_entry_is_head"></a>`list_entry_is_head()`

```c
list_entry_is_head(pos, head, member)
```

test if the entry points to the head of the list

**Parameters**

- `pos`: the type * to cursor
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_for_each_entry"></a>`list_for_each_entry()`

```c
list_for_each_entry(pos, head, member)
```

iterate over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_for_each_entry_reverse"></a>`list_for_each_entry_reverse()`

```c
list_for_each_entry_reverse(pos, head, member)
```

iterate backwards over list of given type.

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_prepare_entry"></a>`list_prepare_entry()`

```c
list_prepare_entry(pos, head, member)
```

prepare a pos entry for use in [`list_for_each_entry_continue()`](#c-list_for_each_entry_continue)

**Parameters**

- `pos`: the type * to use as a start point
- `head`: the head of the list
- `member`: the name of the list_head within the struct.

**Description**

Prepares a pos entry for use as a start point in [`list_for_each_entry_continue()`](#c-list_for_each_entry_continue).

#### <a id="c-list_for_each_entry_continue"></a>`list_for_each_entry_continue()`

```c
list_for_each_entry_continue(pos, head, member)
```

continue iteration over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Continue to iterate over list of given type, continuing after
the current position.

#### <a id="c-list_for_each_entry_continue_reverse"></a>`list_for_each_entry_continue_reverse()`

```c
list_for_each_entry_continue_reverse(pos, head, member)
```

iterate backwards from the given point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Start to iterate over list of given type backwards, continuing after
the current position.

#### <a id="c-list_for_each_entry_from"></a>`list_for_each_entry_from()`

```c
list_for_each_entry_from(pos, head, member)
```

iterate over list of given type from the current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type, continuing from current position.

#### <a id="c-list_for_each_entry_from_reverse"></a>`list_for_each_entry_from_reverse()`

```c
list_for_each_entry_from_reverse(pos, head, member)
```

iterate backwards over list of given type from the current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate backwards over list of given type, continuing from current position.

#### <a id="c-list_for_each_entry_safe"></a>`list_for_each_entry_safe()`

```c
list_for_each_entry_safe(pos, n, head, member)
```

iterate over list of given type safe against removal of list entry

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_for_each_entry_safe_continue"></a>`list_for_each_entry_safe_continue()`

```c
list_for_each_entry_safe_continue(pos, n, head, member)
```

continue list iteration safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type, continuing after current point,
safe against removal of list entry.

#### <a id="c-list_for_each_entry_safe_from"></a>`list_for_each_entry_safe_from()`

```c
list_for_each_entry_safe_from(pos, n, head, member)
```

iterate over list from current point safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type from current point, safe against
removal of list entry.

#### <a id="c-list_for_each_entry_safe_reverse"></a>`list_for_each_entry_safe_reverse()`

```c
list_for_each_entry_safe_reverse(pos, n, head, member)
```

iterate backwards over list safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate backwards over list of given type, safe against removal
of list entry.

#### <a id="c-list_safe_reset_next"></a>`list_safe_reset_next()`

```c
list_safe_reset_next(pos, n, member)
```

reset a stale list_for_each_entry_safe loop

**Parameters**

- `pos`: the loop cursor used in the list_for_each_entry_safe loop
- `n`: temporary storage used in list_for_each_entry_safe
- `member`: the name of the list_head within the struct.

**Description**

list_safe_reset_next is not safe to use in general if the list may be
modified concurrently (eg. the lock is dropped in the loop body). An
exception to this is if the cursor element (pos) is pinned in the list,
and list_safe_reset_next is called after re-taking the lock and before
completing the current iteration of the loop body.

#### <a id="c-hlist_unhashed"></a>`hlist_unhashed()`

```c
int hlist_unhashed(const struct hlist_node *h)
```

Has node been removed from list and reinitialized?

**Parameters**

- `const struct hlist_node *h`: Node to be checked

**Description**

Not that not all removal functions will leave a node in unhashed
state.  For example, [`hlist_nulls_del_init_rcu()`](/kernel/internals/core-api/kernel-api.md#c-hlist_nulls_del_init_rcu) does leave the
node in unhashed state, but `hlist_nulls_del()` does not.

#### <a id="c-hlist_unhashed_lockless"></a>`hlist_unhashed_lockless()`

```c
int hlist_unhashed_lockless(const struct hlist_node *h)
```

Version of hlist_unhashed for lockless use

**Parameters**

- `const struct hlist_node *h`: Node to be checked

**Description**

This variant of [`hlist_unhashed()`](#c-hlist_unhashed) must be used in lockless contexts
to avoid potential load-tearing.  The `READ_ONCE()` is paired with the
various `WRITE_ONCE()` in hlist helpers that are defined below.

#### <a id="c-hlist_empty"></a>`hlist_empty()`

```c
int hlist_empty(const struct hlist_head *h)
```

Is the specified hlist_head structure an empty hlist?

**Parameters**

- `const struct hlist_head *h`: Structure to check.

#### <a id="c-hlist_del"></a>`hlist_del()`

```c
void hlist_del(struct hlist_node *n)
```

Delete the specified hlist_node from its list

**Parameters**

- `struct hlist_node *n`: Node to delete.

**Description**

Note that this function leaves the node in hashed state.  Use
[`hlist_del_init()`](#c-hlist_del_init) or similar instead to unhash **n**.

#### <a id="c-hlist_del_init"></a>`hlist_del_init()`

```c
void hlist_del_init(struct hlist_node *n)
```

Delete the specified hlist_node from its list and initialize

**Parameters**

- `struct hlist_node *n`: Node to delete.

**Description**

Note that this function leaves the node in unhashed state.

#### <a id="c-hlist_add_head"></a>`hlist_add_head()`

```c
void hlist_add_head(struct hlist_node *n, struct hlist_head *h)
```

add a new entry at the beginning of the hlist

**Parameters**

- `struct hlist_node *n`: new entry to be added
- `struct hlist_head *h`: hlist head to add it after

**Description**

Insert a new entry after the specified head.
This is good for implementing stacks.

#### <a id="c-hlist_add_before"></a>`hlist_add_before()`

```c
void hlist_add_before(struct hlist_node *n, struct hlist_node *next)
```

add a new entry before the one specified

**Parameters**

- `struct hlist_node *n`: new entry to be added
- `struct hlist_node *next`: hlist node to add it before, which must be non-NULL

#### <a id="c-hlist_add_behind"></a>`hlist_add_behind()`

```c
void hlist_add_behind(struct hlist_node *n, struct hlist_node *prev)
```

add a new entry after the one specified

**Parameters**

- `struct hlist_node *n`: new entry to be added
- `struct hlist_node *prev`: hlist node to add it after, which must be non-NULL

#### <a id="c-hlist_add_fake"></a>`hlist_add_fake()`

```c
void hlist_add_fake(struct hlist_node *n)
```

create a fake hlist consisting of a single headless node

**Parameters**

- `struct hlist_node *n`: Node to make a fake list out of

**Description**

This makes **n** appear to be its own predecessor on a headless hlist.
The point of this is to allow things like [`hlist_del()`](#c-hlist_del) to work correctly
in cases where there is no list.

#### <a id="c-hlist_fake"></a>`hlist_fake()`

```c
bool hlist_fake(struct hlist_node *h)
```

Is this node a fake hlist?

**Parameters**

- `struct hlist_node *h`: Node to check for being a self-referential fake hlist.

#### <a id="c-hlist_is_singular_node"></a>`hlist_is_singular_node()`

```c
bool hlist_is_singular_node(struct hlist_node *n, struct hlist_head *h)
```

is node the only element of the specified hlist?

**Parameters**

- `struct hlist_node *n`: Node to check for singularity.
- `struct hlist_head *h`: Header for potentially singular list.

**Description**

Check whether the node is the only node of the head without
accessing head, thus avoiding unnecessary cache misses.

#### <a id="c-hlist_move_list"></a>`hlist_move_list()`

```c
void hlist_move_list(struct hlist_head *old, struct hlist_head *new)
```

Move an hlist

**Parameters**

- `struct hlist_head *old`: hlist_head for old list.
- `struct hlist_head *new`: hlist_head for new list.

**Description**

Move a list from one list head to another. Fixup the pprev
reference of the first entry if it exists.

#### <a id="c-hlist_splice_init"></a>`hlist_splice_init()`

```c
void hlist_splice_init(struct hlist_head *from, struct hlist_node *last, struct hlist_head *to)
```

move all entries from one list to another

**Parameters**

- `struct hlist_head *from`: hlist_head from which entries will be moved
- `struct hlist_node *last`: last entry on the **from** list
- `struct hlist_head *to`: hlist_head to which entries will be moved

**Description**

**to** can be empty, **from** must contain at least **last**.

#### <a id="c-hlist_for_each_entry"></a>`hlist_for_each_entry()`

```c
hlist_for_each_entry(pos, head, member)
```

iterate over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_for_each_entry_continue"></a>`hlist_for_each_entry_continue()`

```c
hlist_for_each_entry_continue(pos, member)
```

iterate over a hlist continuing after current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_for_each_entry_from"></a>`hlist_for_each_entry_from()`

```c
hlist_for_each_entry_from(pos, member)
```

iterate over a hlist continuing from current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_for_each_entry_safe"></a>`hlist_for_each_entry_safe()`

```c
hlist_for_each_entry_safe(pos, n, head, member)
```

iterate over list of given type safe against removal of list entry

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: a `struct hlist_node` to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the hlist_node within the struct.

#### <a id="c-hlist_count_nodes"></a>`hlist_count_nodes()`

```c
size_t hlist_count_nodes(struct hlist_head *head)
```

count nodes in the hlist

**Parameters**

- `struct hlist_head *head`: the head for your hlist.


<a id="rst-private-list-api"></a>

## Private List API


Provides a set of list primitives identical in function to those in
`<linux/list.h>`, but designed for cases where the embedded
`&struct list_head` is private member.



#### <a id="c-list_private_entry"></a>`list_private_entry()`

```c
list_private_entry(ptr, type, member)
```

get the struct for this entry

**Parameters**

- `ptr`: the `struct list_head` pointer.
- `type`: the type of the struct this is embedded in.
- `member`: the identifier passed to ACCESS_PRIVATE.

#### <a id="c-list_private_first_entry"></a>`list_private_first_entry()`

```c
list_private_first_entry(ptr, type, member)
```

get the first element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the identifier passed to ACCESS_PRIVATE.

#### <a id="c-list_private_last_entry"></a>`list_private_last_entry()`

```c
list_private_last_entry(ptr, type, member)
```

get the last element from a list

**Parameters**

- `ptr`: the list head to take the element from.
- `type`: the type of the struct this is embedded in.
- `member`: the identifier passed to ACCESS_PRIVATE.

#### <a id="c-list_private_next_entry"></a>`list_private_next_entry()`

```c
list_private_next_entry(pos, member)
```

get the next element in list

**Parameters**

- `pos`: the type * to cursor
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_next_entry_circular"></a>`list_private_next_entry_circular()`

```c
list_private_next_entry_circular(pos, head, member)
```

get the next element in list

**Parameters**

- `pos`: the type * to cursor.
- `head`: the list head to take the element from.
- `member`: the name of the list_head within the struct.

**Description**

Wraparound if pos is the last element (return the first element).
Note, that list is expected to be not empty.

#### <a id="c-list_private_prev_entry"></a>`list_private_prev_entry()`

```c
list_private_prev_entry(pos, member)
```

get the prev element in list

**Parameters**

- `pos`: the type * to cursor
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_prev_entry_circular"></a>`list_private_prev_entry_circular()`

```c
list_private_prev_entry_circular(pos, head, member)
```

get the prev element in list

**Parameters**

- `pos`: the type * to cursor.
- `head`: the list head to take the element from.
- `member`: the name of the list_head within the struct.

**Description**

Wraparound if pos is the first element (return the last element).
Note, that list is expected to be not empty.

#### <a id="c-list_private_entry_is_head"></a>`list_private_entry_is_head()`

```c
list_private_entry_is_head(pos, head, member)
```

test if the entry points to the head of the list

**Parameters**

- `pos`: the type * to cursor
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_for_each_entry"></a>`list_private_for_each_entry()`

```c
list_private_for_each_entry(pos, head, member)
```

iterate over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_for_each_entry_reverse"></a>`list_private_for_each_entry_reverse()`

```c
list_private_for_each_entry_reverse(pos, head, member)
```

iterate backwards over list of given type.

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_for_each_entry_continue"></a>`list_private_for_each_entry_continue()`

```c
list_private_for_each_entry_continue(pos, head, member)
```

continue iteration over list of given type

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Continue to iterate over list of given type, continuing after
the current position.

#### <a id="c-list_private_for_each_entry_continue_reverse"></a>`list_private_for_each_entry_continue_reverse()`

```c
list_private_for_each_entry_continue_reverse(pos, head, member)
```

iterate backwards from the given point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Start to iterate over list of given type backwards, continuing after
the current position.

#### <a id="c-list_private_for_each_entry_from"></a>`list_private_for_each_entry_from()`

```c
list_private_for_each_entry_from(pos, head, member)
```

iterate over list of given type from the current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type, continuing from current position.

#### <a id="c-list_private_for_each_entry_from_reverse"></a>`list_private_for_each_entry_from_reverse()`

```c
list_private_for_each_entry_from_reverse(pos, head, member)
```

iterate backwards over list of given type from the current point

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate backwards over list of given type, continuing from current position.

#### <a id="c-list_private_for_each_entry_safe"></a>`list_private_for_each_entry_safe()`

```c
list_private_for_each_entry_safe(pos, n, head, member)
```

iterate over list of given type safe against removal of list entry

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

#### <a id="c-list_private_for_each_entry_safe_continue"></a>`list_private_for_each_entry_safe_continue()`

```c
list_private_for_each_entry_safe_continue(pos, n, head, member)
```

continue list iteration safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type, continuing after current point,
safe against removal of list entry.

#### <a id="c-list_private_for_each_entry_safe_from"></a>`list_private_for_each_entry_safe_from()`

```c
list_private_for_each_entry_safe_from(pos, n, head, member)
```

iterate over list from current point safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate over list of given type from current point, safe against
removal of list entry.

#### <a id="c-list_private_for_each_entry_safe_reverse"></a>`list_private_for_each_entry_safe_reverse()`

```c
list_private_for_each_entry_safe_reverse(pos, n, head, member)
```

iterate backwards over list safe against removal

**Parameters**

- `pos`: the type * to use as a loop cursor.
- `n`: another type * to use as temporary storage
- `head`: the head for your list.
- `member`: the name of the list_head within the struct.

**Description**

Iterate backwards over list of given type, safe against removal
of list entry.

#### <a id="c-list_private_safe_reset_next"></a>`list_private_safe_reset_next()`

```c
list_private_safe_reset_next(pos, n, member)
```

reset a stale list_for_each_entry_safe loop

**Parameters**

- `pos`: the loop cursor used in the list_for_each_entry_safe loop
- `n`: temporary storage used in list_for_each_entry_safe
- `member`: the name of the list_head within the struct.

**Description**

list_safe_reset_next is not safe to use in general if the list may be
modified concurrently (eg. the lock is dropped in the loop body). An
exception to this is if the cursor element (pos) is pinned in the list,
and list_safe_reset_next is called after re-taking the lock and before
completing the current iteration of the loop body.

---

# Live Update Orchestrator

_Peios Kernel / Internals / Core APIs_

> The following types of file descriptors can be preserved

<a id="rst-live-update-orchestrator"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Pasha Tatashin &lt;[pasha.tatashin@soleen.com](<mailto:pasha.tatashin@soleen.com>)&gt;


Live Update is a specialized, kexec-based reboot process that allows a
running kernel to be updated from one version to another while preserving
the state of selected resources and keeping designated hardware devices
operational. For these devices, DMA activity may continue throughout the
kernel transition.

While the primary use case driving this work is supporting live updates of
the Linux kernel when it is used as a hypervisor in cloud environments, the
LUO framework itself is designed to be workload-agnostic. Live Update
facilitates a full kernel version upgrade for any type of system.

For example, a non-hypervisor system running an in-memory cache like
memcached with many gigabytes of data can use LUO. The userspace service
can place its cache into a memfd, have its state preserved by LUO, and
restore it immediately after the kernel kexec.

Whether the system is running virtual machines, containers, a
high-performance database, or networking services, LUO's primary goal is to
enable a full kernel update by preserving critical userspace state and
keeping essential devices operational.

The core of LUO is a mechanism that tracks the progress of a live update,
along with a callback API that allows other kernel subsystems to participate
in the process. Example subsystems that can hook into LUO include: kvm,
iommu, interrupts, vfio, participating filesystems, and memory management.

LUO uses Kexec Handover to transfer memory state from the current kernel to
the next kernel. For more details see Documentation/core-api/kho/index.rst.


<a id="rst-luo-sessions"></a>

## LUO Sessions


LUO Sessions provide the core mechanism for grouping and managing `struct file *` instances that need to be preserved across a kexec-based live
update. Each session acts as a named container for a set of file objects,
allowing a userspace agent to manage the lifecycle of resources critical to a
workload.

Core Concepts:

- Named Containers: Sessions are identified by a unique, user-provided name,
  which is used for both creation in the current kernel and retrieval in the
  next kernel.

- Userspace Interface: Session management is driven from userspace via
  ioctls on /dev/liveupdate.

- Serialization: Session metadata is preserved using the KHO framework. When
  a live update is triggered via kexec, an array of `struct luo_session_ser`
  is populated and placed in a preserved memory region. An FDT node is also
  created, containing the count of sessions and the physical address of this
  array.

Session Lifecycle:

1. Creation: A userspace agent calls `luo_session_create()` to create a
   new, empty session and receives a file descriptor for it.

2. Serialization: When the `reboot(LINUX_REBOOT_CMD_KEXEC)` syscall is
   made, `luo_session_serialize()` is called. It iterates through all
   active sessions and writes their metadata into a memory area preserved
   by KHO.

3. Deserialization (in new kernel): After kexec, `luo_session_deserialize()`
   runs, reading the serialized data and creating a list of `struct    luo_session` objects representing the preserved sessions.

4. Retrieval: A userspace agent in the new kernel can then call
   `luo_session_retrieve()` with a session name to get a new file
   descriptor and access the preserved state.


<a id="rst-luo-preserving-file-descriptors"></a>

## LUO Preserving File Descriptors


LUO provides the infrastructure to preserve specific, stateful file
descriptors across a kexec-based live update. The primary goal is to allow
workloads, such as virtual machines using vfio, memfd, or iommufd, to
retain access to their essential resources without interruption.

The framework is built around a callback-based handler model and a well-
defined lifecycle for each preserved file.

Handler Registration:
Kernel modules responsible for a specific file type (e.g., memfd, vfio)
register a [`struct liveupdate_file_handler`](#c-struct-liveupdate_file_handler). This handler provides a set of
callbacks that LUO invokes at different stages of the update process, most
notably:

- `can_preserve()`: A lightweight check to determine if the handler is
  compatible with a given 'struct file'.
- `preserve()`: The heavyweight operation that saves the file's state and
  returns an opaque u64 handle. This is typically performed while the
  workload is still active to minimize the downtime during the
  actual reboot transition.
- `unpreserve()`: Cleans up any resources allocated by .`preserve()`, called
  if the preservation process is aborted before the reboot (i.e. session is
  closed).
- `freeze()`: A final pre-reboot opportunity to prepare the state for kexec.
  We are already in reboot syscall, and therefore userspace cannot mutate
  the file anymore.
- `unfreeze()`: Undoes the actions of .`freeze()`, called if the live update
  is aborted after the freeze phase.
- `retrieve()`: Reconstructs the file in the new kernel from the preserved
  handle.
- `finish()`: Performs final check and cleanup in the new kernel. After
  succesul finish call, LUO gives up ownership to this file.

File Preservation Lifecycle happy path:

1. Preserve (Normal Operation): A userspace agent preserves files one by one
   via an ioctl. For each file, [`luo_preserve_file()`](#c-luo_preserve_file) finds a compatible
   handler, calls its .`preserve()` operation, and creates an internal [`struct luo_file`](#c-struct-luo_file) to track the live state.

2. Freeze (Pre-Reboot): Just before the kexec, [`luo_file_freeze()`](#c-luo_file_freeze) is called.
   It iterates through all preserved files, calls their respective .`freeze()`
   operation, and serializes their final metadata (compatible string, token,
   and data handle) into a contiguous memory block for KHO.

3. Deserialize: After kexec, [`luo_file_deserialize()`](#c-luo_file_deserialize) runs when session gets
   deserialized (which is when /dev/liveupdate is first opened). It reads the
   serialized data from the KHO memory region and reconstructs the in-memory
   list of [`struct luo_file`](#c-struct-luo_file) instances for the new kernel, linking them to
   their corresponding handlers.

4. Retrieve (New Kernel - Userspace Ready): The userspace agent can now
   restore file descriptors by providing a token. [`luo_retrieve_file()`](#c-luo_retrieve_file)
   searches for the matching token, calls the handler's .`retrieve()` op to
   re-create the 'struct file', and returns a new FD. Files can be
   retrieved in ANY order.

5. Finish (New Kernel - Cleanup): Once a session retrival is complete,
   [`luo_file_finish()`](#c-luo_file_finish) is called. It iterates through all files, invokes their
   .`finish()` operations for final cleanup, and releases all associated kernel
   resources.

File Preservation Lifecycle unhappy paths:

1. Abort Before Reboot: If the userspace agent aborts the live update
   process before calling reboot (e.g., by closing the session file
   descriptor), the session's release handler calls
   [`luo_file_unpreserve_files()`](#c-luo_file_unpreserve_files). This invokes the .`unpreserve()` callback on
   all preserved files, ensuring all allocated resources are cleaned up and
   returning the system to a clean state.

2. Freeze Failure: During the `reboot()` syscall, if any handler's .`freeze()`
   op fails, the .`unfreeze()` op is invoked on all previously *successful*
   freezes to roll back their state. The `reboot()` syscall then returns an
   error to userspace, canceling the live update.

3. Finish Failure: In the new kernel, if a handler's .`finish()` op fails,
   the [`luo_file_finish()`](#c-luo_file_finish) operation is aborted. LUO retains ownership of
   all files within that session, including those that were not yet
   processed. The userspace agent can attempt to call the finish operation
   again later. If the issue cannot be resolved, these resources will be held
   by LUO until the next live update cycle, at which point they will be
   discarded.


<a id="rst-luo-file-lifecycle-bound-global-data"></a>

## LUO File Lifecycle Bound Global Data


File-Lifecycle-Bound (FLB) objects provide a mechanism for managing global
state that is shared across multiple live-updatable files. The lifecycle of
this shared state is tied to the preservation of the files that depend on it.

An FLB represents a global resource, such as the IOMMU core state, that is
required by multiple file descriptors (e.g., all VFIO fds).

The preservation of the FLB's state is triggered when the *first* file
depending on it is preserved. The cleanup of this state (unpreserve or
finish) is triggered when the *last* file depending on it is unpreserved or
finished.

Handler Dependency: A file handler declares its dependency on one or more
FLBs by registering them via [`liveupdate_register_flb()`](#c-liveupdate_register_flb).

Callback Model: Each FLB is defined by a set of operations
([`struct liveupdate_flb_ops`](#c-struct-liveupdate_flb_ops)) that LUO invokes at key points:

- .`preserve()`: Called for the first file. Saves global state.
- .`unpreserve()`: Called for the last file (if aborted pre-reboot).
- .`retrieve()`: Called on-demand in the new kernel to restore the state.
- .`finish()`: Called for the last file in the new kernel for cleanup.

This reference-counted approach ensures that shared state is saved exactly
once and restored exactly once, regardless of how many files depend on it,
and that its lifecycle is correctly managed across the kexec transition.


<a id="rst-live-update-orchestrator-abi"></a>

## Live Update Orchestrator ABI


Live Update Orchestrator uses the stable Application Binary Interface
defined below to pass state from a pre-update kernel to a post-update
kernel. The ABI is built upon the Kexec HandOver framework and uses a
Flattened Device Tree to describe the preserved data.

This interface is a contract. Any modification to the FDT structure, node
properties, compatible strings, or the layout of the `__packed` serialization
structures defined here constitutes a breaking change. Such changes require
incrementing the version number in the relevant `_COMPATIBLE` string to
prevent a new kernel from misinterpreting data from an old kernel.

Changes are allowed provided the compatibility version is incremented;
however, backward/forward compatibility is only guaranteed for kernels
supporting the same ABI version.

- FDT Structure Overview:
  The entire LUO state is encapsulated within a single KHO entry named "LUO".
  This entry contains an FDT with the following layout:

```none
/ {
    compatible = "luo-v1";
    liveupdate-number = <...>;

    luo-session {
        compatible = "luo-session-v1";
        luo-session-header = <phys_addr_of_session_header_ser>;
    };

    luo-flb {
        compatible = "luo-flb-v1";
        luo-flb-header = <phys_addr_of_flb_header_ser>;
    };
};
```

Main LUO Node (/):

- compatible: "luo-v1"
  Identifies the overall LUO ABI version.
- liveupdate-number: u64
  A counter tracking the number of successful live updates performed.

Session Node (luo-session):
This node describes all preserved user-space sessions.

- compatible: "luo-session-v1"
  Identifies the session ABI version.
- luo-session-header: u64
  The physical address of a `struct luo_session_header_ser`. This structure
  is the header for a contiguous block of memory containing an array of
  `struct luo_session_ser`, one for each preserved session.

File-Lifecycle-Bound Node (luo-flb):
This node describes all preserved global objects whose lifecycle is bound
to that of the preserved files (e.g., shared IOMMU state).

- compatible: "luo-flb-v1"
  Identifies the FLB ABI version.
- luo-flb-header: u64
  The physical address of a `struct luo_flb_header_ser`. This structure is
  the header for a contiguous block of memory containing an array of
  `struct luo_flb_ser`, one for each preserved global object.

Serialization Structures:
The FDT properties point to memory regions containing arrays of simple,
`__packed` structures. These structures contain the actual preserved state.

- struct luo_session_header_ser:
  Header for the session array. Contains the total page count of the
  preserved memory block and the number of `struct luo_session_ser`
  entries that follow.

- struct luo_session_ser:
  Metadata for a single session, including its name and a physical pointer
  to another preserved memory block containing an array of
  `struct luo_file_ser` for all files in that session.

- struct luo_file_ser:
  Metadata for a single preserved file. Contains the `compatible` string to
  find the correct handler in the new kernel, a user-provided `token` for
  identification, and an opaque `data` handle for the handler to use.

- struct luo_flb_header_ser:
  Header for the FLB array. Contains the total page count of the
  preserved memory block and the number of `struct luo_flb_ser` entries
  that follow.

- struct luo_flb_ser:
  Metadata for a single preserved global object. Contains its `name`
  (compatible string), an opaque `data` handle, and the `count`
  number of files depending on it.


The following types of file descriptors can be preserved

- [Memfd Preservation via LUO](</kernel/internals/mm/memfd-preservation.md>)

<a id="rst-public-api"></a>

## Public API


#### <a id="c-struct-liveupdate_file_op_args"></a>`struct liveupdate_file_op_args`

Arguments for file operation callbacks.

**Definition**

```c
struct liveupdate_file_op_args {
    struct liveupdate_file_handler *handler;
    int retrieve_status;
    struct file *file;
    u64 serialized_data;
    void *private_data;
};
```

**Members**

- `handler`: The file handler being called.
- `retrieve_status`: The retrieve status for the 'can_finish / finish'
  operation. A value of 0 means the retrieve has not been
  attempted, a positive value means the retrieve was
  successful, and a negative value means the retrieve failed,
  and the value is the error code of the call.
- `file`: The file object. For retrieve: \[OUT\] The callback sets
  this to the new file. For other ops: \[IN\] The caller sets
  this to the file being operated on.
- `serialized_data`: The opaque u64 handle, preserve/prepare/freeze may update
  this field.
- `private_data`: Private data for the file used to hold runtime state that
  is not preserved. Set by the handler's .`preserve()`
  callback, and must be freed in the handler's
  .`unpreserve()` callback.

**Description**

This structure bundles all parameters for the file operation callbacks.
The 'data' and 'file' fields are used for both input and output.

#### <a id="c-struct-liveupdate_file_ops"></a>`struct liveupdate_file_ops`

Callbacks for live-updatable files.

**Definition**

```c
struct liveupdate_file_ops {
    bool (*can_preserve)(struct liveupdate_file_handler *handler, struct file *file);
    int (*preserve)(struct liveupdate_file_op_args *args);
    void (*unpreserve)(struct liveupdate_file_op_args *args);
    int (*freeze)(struct liveupdate_file_op_args *args);
    void (*unfreeze)(struct liveupdate_file_op_args *args);
    int (*retrieve)(struct liveupdate_file_op_args *args);
    bool (*can_finish)(struct liveupdate_file_op_args *args);
    void (*finish)(struct liveupdate_file_op_args *args);
    struct module *owner;
};
```

**Members**

- `can_preserve`: Required. Lightweight check to see if this handler is
  compatible with the given file.
- `preserve`: Required. Performs state-saving for the file.
- `unpreserve`: Required. Cleans up any resources allocated by **preserve**.
- `freeze`: Optional. Final actions just before kernel transition.
- `unfreeze`: Optional. Undo freeze operations.
- `retrieve`: Required. Restores the file in the new kernel.
- `can_finish`: Optional. Check if this FD can finish, i.e. all restoration
  pre-requirements for this FD are satisfied. Called prior to
  finish, in order to do successful finish calls for all
  resources in the session.
- `finish`: Required. Final cleanup in the new kernel.
- `owner`: Module reference

**Description**

All operations (except can_preserve) receive a pointer to a
'struct liveupdate_file_op_args' containing the necessary context.

#### <a id="c-struct-liveupdate_file_handler"></a>`struct liveupdate_file_handler`

Represents a handler for a live-updatable file type.

**Definition**

```c
struct liveupdate_file_handler {
    const struct liveupdate_file_ops *ops;
    const char compatible[LIVEUPDATE_HNDL_COMPAT_LENGTH];
};
```

**Members**

- `ops`: Callback functions
- `compatible`: The compatibility string (e.g., "memfd-v1", "vfiofd-v1")
  that uniquely identifies the file type this handler
  supports. This is matched against the compatible string
  associated with individual [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) instances.

**Description**

Modules that want to support live update for specific file types should
register an instance of this structure. LUO uses this registration to
determine if a given file can be preserved and to find the appropriate
operations to manage its state across the update.

#### <a id="c-struct-liveupdate_flb_op_args"></a>`struct liveupdate_flb_op_args`

Arguments for FLB operation callbacks.

**Definition**

```c
struct liveupdate_flb_op_args {
    struct liveupdate_flb *flb;
    u64 data;
    void *obj;
};
```

**Members**

- `flb`: The global FLB instance for which this call is performed.
- `data`: For .`preserve()`:    \[OUT\] The callback sets this field.
  For .`unpreserve()`:  \[IN\]  The handle from .`preserve()`.
  For .`retrieve()`:    \[IN\]  The handle from .`preserve()`.
- `obj`: For .`preserve()`:    \[OUT\] Sets this to the live object.
  For .`retrieve()`:    \[OUT\] Sets this to the live object.
  For .`finish()`:      \[IN\]  The live object from .`retrieve()`.

**Description**

This structure bundles all parameters for the FLB operation callbacks.

#### <a id="c-struct-liveupdate_flb_ops"></a>`struct liveupdate_flb_ops`

Callbacks for global File-Lifecycle-Bound data.

**Definition**

```c
struct liveupdate_flb_ops {
    int (*preserve)(struct liveupdate_flb_op_args *argp);
    void (*unpreserve)(struct liveupdate_flb_op_args *argp);
    int (*retrieve)(struct liveupdate_flb_op_args *argp);
    void (*finish)(struct liveupdate_flb_op_args *argp);
    struct module *owner;
};
```

**Members**

- `preserve`: Called when the first file using this FLB is preserved.
  The callback must save its state and return a single,
  self-contained u64 handle by setting the 'argp->data'
  field and 'argp->obj'.
- `unpreserve`: Called when the last file using this FLB is unpreserved
  (aborted before reboot). Receives the handle via
  'argp->data' and live object via 'argp->obj'.
- `retrieve`: Called on-demand in the new kernel, the first time a
  component requests access to the shared object. It receives
  the preserved handle via 'argp->data' and must reconstruct
  the live object, returning it by setting the 'argp->obj'
  field.
- `finish`: Called in the new kernel when the last file using this FLB
  is finished. Receives the live object via 'argp->obj' for
  cleanup.
- `owner`: Module reference

**Description**

Operations that manage global shared data with file bound lifecycle,
triggered by the first file that uses it and concluded by the last file that
uses it, across all sessions.

#### <a id="c-struct-liveupdate_flb"></a>`struct liveupdate_flb`

A global definition for a shared data object.

**Definition**

```c
struct liveupdate_flb {
    const struct liveupdate_flb_ops *ops;
    const char compatible[LIVEUPDATE_FLB_COMPAT_LENGTH];
};
```

**Members**

- `ops`: Callback functions
- `compatible`: The compatibility string (e.g., "iommu-core-v1"
  that uniquely identifies the FLB type this handler
  supports. This is matched against the compatible string
  associated with individual [`struct liveupdate_flb`](#c-struct-liveupdate_flb)
  instances.

**Description**

This struct is the "template" that a driver registers to define a shared,
file-lifecycle-bound object. The actual runtime state (the live object,
refcount, etc.) is managed privately by the LUO core.



#### <a id="c-struct-luo_file_ser"></a>`struct luo_file_ser`

Represents the serialized preserves files.

**Definition**

```c
struct luo_file_ser {
    char compatible[LIVEUPDATE_HNDL_COMPAT_LENGTH];
    u64 data;
    u64 token;
};
```

**Members**

- `compatible`: File handler compatible string.
- `data`: Private data
- `token`: User provided token for this file

**Description**

If this structure is modified, LUO_SESSION_COMPATIBLE must be updated.

#### <a id="c-struct-luo_file_set_ser"></a>`struct luo_file_set_ser`

Represents the serialized metadata for file set

**Definition**

```c
struct luo_file_set_ser {
    u64 files;
    u64 count;
};
```

**Members**

- `files`: The physical address of a contiguous memory block that holds
  the serialized state of files (array of luo_file_ser) in this file
  set.
- `count`: The total number of files that were part of this session during
  serialization. Used for iteration and validation during
  restoration.

#### <a id="c-struct-luo_session_header_ser"></a>`struct luo_session_header_ser`

Header for the serialized session data block.

**Definition**

```c
struct luo_session_header_ser {
    u64 count;
};
```

**Members**

- `count`: The number of `struct luo_session_ser` entries that immediately
  follow this header in the memory block.

**Description**

This structure is located at the beginning of a contiguous block of
physical memory preserved across the kexec. It provides the necessary
metadata to interpret the array of session entries that follow.

If this structure is modified, `LUO_FDT_SESSION_COMPATIBLE` must be updated.

#### <a id="c-struct-luo_session_ser"></a>`struct luo_session_ser`

Represents the serialized metadata for a LUO session.

**Definition**

```c
struct luo_session_ser {
    char name[LIVEUPDATE_SESSION_NAME_LENGTH];
    struct luo_file_set_ser file_set_ser;
};
```

**Members**

- `name`: The unique name of the session, provided by the userspace at
  the time of session creation.
- `file_set_ser`: Serialized files belonging to this session,

**Description**

This structure is used to package session-specific metadata for transfer
between kernels via Kexec Handover. An array of these structures (one per
session) is created and passed to the new kernel, allowing it to reconstruct
the session context.

If this structure is modified, `LUO_FDT_SESSION_COMPATIBLE` must be updated.

#### <a id="c-struct-luo_flb_header_ser"></a>`struct luo_flb_header_ser`

Header for the serialized FLB data block.

**Definition**

```c
struct luo_flb_header_ser {
    u64 pgcnt;
    u64 count;
};
```

**Members**

- `pgcnt`: The total number of pages occupied by the entire preserved memory
  region, including this header and the subsequent array of
  [`struct luo_flb_ser`](#c-struct-luo_flb_ser) entries.
- `count`: The number of [`struct luo_flb_ser`](#c-struct-luo_flb_ser) entries that follow this header
  in the memory block.

**Description**

This structure is located at the physical address specified by the
`LUO_FDT_FLB_HEADER` FDT property. It provides the new kernel with the
necessary information to find and iterate over the array of preserved
File-Lifecycle-Bound objects and to manage the underlying memory.

If this structure is modified, LUO_FDT_FLB_COMPATIBLE must be updated.

#### <a id="c-struct-luo_flb_ser"></a>`struct luo_flb_ser`

Represents the serialized state of a single FLB object.

**Definition**

```c
struct luo_flb_ser {
    char name[LIVEUPDATE_FLB_COMPAT_LENGTH];
    u64 data;
    u64 count;
};
```

**Members**

- `name`: The unique compatibility string of the FLB object, used to find the
  corresponding [`struct liveupdate_flb`](#c-struct-liveupdate_flb) handler in the new kernel.
- `data`: The opaque u64 handle returned by the FLB's .`preserve()` operation
  in the old kernel. This handle encapsulates the entire state needed
  for restoration.
- `count`: The reference count at the time of serialization; i.e., the number
  of preserved files that depended on this FLB. This is used by the
  new kernel to correctly manage the FLB's lifecycle.

**Description**

An array of these structures is created in a preserved memory region and
passed to the new kernel. Each entry allows the LUO core to restore one
global, shared object.

If this structure is modified, LUO_FDT_FLB_COMPATIBLE must be updated.











<a id="rst-internal-api"></a>

## Internal API


#### <a id="c-liveupdate_reboot"></a>`liveupdate_reboot()`

```c
int liveupdate_reboot(void)
```

Kernel reboot notifier for live update final serialization.

**Parameters**

- `void`: no arguments

**Description**

This function is invoked directly from the `reboot()` syscall pathway
if kexec is in progress.

If any callback fails, this function aborts KHO, undoes the `freeze()`
callbacks, and returns an error.

#### <a id="c-liveupdate_enabled"></a>`liveupdate_enabled()`

```c
bool liveupdate_enabled(void)
```

Check if the live update feature is enabled.

**Parameters**

- `void`: no arguments

**Description**

This function returns the state of the live update feature flag, which
can be controlled via the `liveupdate` kernel command-line parameter.

**return** true if live update is enabled, false otherwise.



#### <a id="c-luo_flb_file_preserve"></a>`luo_flb_file_preserve()`

```c
int luo_flb_file_preserve(struct liveupdate_file_handler *fh)
```

Notifies FLBs that a file is about to be preserved.

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler for the preserved file.

**Description**

This function iterates through all FLBs associated with the given file
handler. It increments the reference count for each FLB. If the count becomes
1, it triggers the FLB's .`preserve()` callback to save the global state.

This operation is atomic. If any FLB's .`preserve()` op fails, it will roll
back by calling .`unpreserve()` on any FLBs that were successfully preserved
during this call.

**Context**

Called from [`luo_preserve_file()`](#c-luo_preserve_file)

**Return**

0 on success, or a negative errno on failure.

#### <a id="c-luo_flb_file_unpreserve"></a>`luo_flb_file_unpreserve()`

```c
void luo_flb_file_unpreserve(struct liveupdate_file_handler *fh)
```

Notifies FLBs that a dependent file was unpreserved.

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler for the unpreserved file.

**Description**

This function iterates through all FLBs associated with the given file
handler, in reverse order of registration. It decrements the reference count
for each FLB. If the count becomes 0, it triggers the FLB's .`unpreserve()`
callback to clean up the global state.

**Context**

Called when a preserved file is being cleaned up before reboot
(e.g., from [`luo_file_unpreserve_files()`](#c-luo_file_unpreserve_files)).

#### <a id="c-luo_flb_file_finish"></a>`luo_flb_file_finish()`

```c
void luo_flb_file_finish(struct liveupdate_file_handler *fh)
```

Notifies FLBs that a dependent file has been finished.

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler for the finished file.

**Description**

This function iterates through all FLBs associated with the given file
handler, in reverse order of registration. It decrements the incoming
reference count for each FLB. If the count becomes 0, it triggers the FLB's
.`finish()` callback for final cleanup in the new kernel.

**Context**

Called from [`luo_file_finish()`](#c-luo_file_finish) for each file being finished.

#### <a id="c-liveupdate_register_flb"></a>`liveupdate_register_flb()`

```c
int liveupdate_register_flb(struct liveupdate_file_handler *fh, struct liveupdate_flb *flb)
```

Associate an FLB with a file handler and register it globally.

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler that will now depend on the FLB.
- `struct liveupdate_flb *flb`: The File-Lifecycle-Bound object to associate.

**Description**

Establishes a dependency, informing the LUO core that whenever a file of
type **fh** is preserved, the state of **flb** must also be managed.

On the first registration of a given **flb** object, it is added to a global
registry. This function checks for duplicate registrations, both for a
specific handler and globally, and ensures the total number of unique
FLBs does not exceed the system limit.

**Context**

Typically called from a subsystem's module init function after
both the handler and the FLB have been defined and initialized.

**Return**

0 on success. Returns a negative errno on failure:
-EINVAL if arguments are NULL or not initialized.
-ENOMEM on memory allocation failure.
-EEXIST if this FLB is already registered with this handler.
-ENOSPC if the maximum number of global FLBs has been reached.
-EOPNOTSUPP if live update is disabled or not configured.

#### <a id="c-liveupdate_unregister_flb"></a>`liveupdate_unregister_flb()`

```c
int liveupdate_unregister_flb(struct liveupdate_file_handler *fh, struct liveupdate_flb *flb)
```

Remove an FLB dependency from a file handler.

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler that is currently depending on the FLB.
- `struct liveupdate_flb *flb`: The File-Lifecycle-Bound object to remove.

**Description**

Removes the association between the specified file handler and the FLB
previously established by [`liveupdate_register_flb()`](#c-liveupdate_register_flb).

This function manages the global lifecycle of the FLB. It decrements the
FLB's usage count. If this was the last file handler referencing this FLB,
the FLB is removed from the global registry and the reference to its
owner module (acquired during registration) is released.

**Context**

This function ensures the session is quiesced (no active FDs
being created) during the update. It is typically called from a
subsystem's module exit function.

**Return**

0 on success.
-EOPNOTSUPP if live update is disabled.
-EBUSY if the live update session is active and cannot be quiesced.
-ENOENT if the FLB was not found in the file handler's list.

#### <a id="c-liveupdate_flb_get_incoming"></a>`liveupdate_flb_get_incoming()`

```c
int liveupdate_flb_get_incoming(struct liveupdate_flb *flb, void **objp)
```

Retrieve the incoming FLB object.

**Parameters**

- `struct liveupdate_flb *flb`: The FLB definition.
- `void **objp`: Output parameter; will be populated with the live shared object.

**Description**

Returns a pointer to its shared live object for the incoming (post-reboot)
path.

If this is the first time the object is requested in the new kernel, this
function will trigger the FLB's .`retrieve()` callback to reconstruct the
object from its preserved state. Subsequent calls will return the same
cached object.

**Return**

0 on success, or a negative errno on failure. -ENODATA means no
incoming FLB data, -ENOENT means specific flb not found in the incoming
data, and -EOPNOTSUPP when live update is disabled or not configured.

#### <a id="c-liveupdate_flb_get_outgoing"></a>`liveupdate_flb_get_outgoing()`

```c
int liveupdate_flb_get_outgoing(struct liveupdate_flb *flb, void **objp)
```

Retrieve the outgoing FLB object.

**Parameters**

- `struct liveupdate_flb *flb`: The FLB definition.
- `void **objp`: Output parameter; will be populated with the live shared object.

**Description**

Returns a pointer to its shared live object for the outgoing (pre-reboot)
path.

This function assumes the object has already been created by the FLB's
.`preserve()` callback, which is triggered when the first dependent file
is preserved.

**Return**

0 on success, or a negative errno on failure.

#### <a id="c-luo_flb_serialize"></a>`luo_flb_serialize()`

```c
void luo_flb_serialize(void)
```

Serializes all active FLB objects for KHO.

**Parameters**

- `void`: no arguments

**Description**

This function is called from the reboot path. It iterates through all
registered File-Lifecycle-Bound (FLB) objects. For each FLB that has been
preserved (i.e., its reference count is greater than zero), it writes its
metadata into the memory region designated for Kexec Handover.

The serialized data includes the FLB's compatibility string, its opaque
data handle, and the final reference count. This allows the new kernel to
find the appropriate handler and reconstruct the FLB's state.

**Context**

Called from [`liveupdate_reboot()`](#c-liveupdate_reboot) just before `kho_finalize()`.



#### <a id="c-struct-luo_session_header"></a>`struct luo_session_header`

Header struct for managing LUO sessions.

**Definition**

```c
struct luo_session_header {
    long count;
    struct list_head list;
    struct rw_semaphore rwsem;
    struct luo_session_header_ser *header_ser;
    struct luo_session_ser *ser;
    bool active;
};
```

**Members**

- `count`: The number of sessions currently tracked in the **list**.
- `list`: The head of the linked list of `struct luo_session` instances.
- `rwsem`: A read-write semaphore providing synchronized access to the
  session list and other fields in this structure.
- `header_ser`: The header data of serialization array.
- `ser`: The serialized session data (an array of
  `struct luo_session_ser`).
- `active`: Set to true when first initialized. If previous kernel did not
  send session data, active stays false for incoming.

#### <a id="c-struct-luo_session_global"></a>`struct luo_session_global`

Global container for managing LUO sessions.

**Definition**

```c
struct luo_session_global {
    struct luo_session_header incoming;
    struct luo_session_header outgoing;
};
```

**Members**

- `incoming`: The sessions passed from the previous kernel.
- `outgoing`: The sessions that are going to be passed to the next kernel.

#### <a id="c-luo_session_quiesce"></a>`luo_session_quiesce()`

```c
bool luo_session_quiesce(void)
```

Ensure no active sessions exist and lock session lists.

**Parameters**

- `void`: no arguments

**Description**

Acquires exclusive write locks on both incoming and outgoing session lists.
It then validates no sessions exist in either list.

This mechanism is used during file handler un/registration to ensure that no
sessions are currently using the handler, and no new sessions can be created
while un/registration is in progress.

This prevents registering new handlers while sessions are active or
while deserialization is in progress.

**Return**

true  - System is quiescent (0 sessions) and locked.
false - Active sessions exist. The locks are released internally.

#### <a id="c-luo_session_resume"></a>`luo_session_resume()`

```c
void luo_session_resume(void)
```

Unlock session lists and resume normal activity.

**Parameters**

- `void`: no arguments

**Description**

Releases the exclusive locks acquired by a successful call to
[`luo_session_quiesce()`](#c-luo_session_quiesce).



#### <a id="c-struct-luo_file"></a>`struct luo_file`

Represents a single preserved file instance.

**Definition**

```c
struct luo_file {
    struct liveupdate_file_handler *fh;
    struct file *file;
    u64 serialized_data;
    void *private_data;
    int retrieve_status;
    struct mutex mutex;
    struct list_head list;
    u64 token;
};
```

**Members**

- `fh`: Pointer to the [`struct liveupdate_file_handler`](#c-struct-liveupdate_file_handler) that manages
  this type of file.
- `file`: Pointer to the kernel's [`struct file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) that is being preserved.
  This is NULL in the new kernel until the file is successfully
  retrieved.
- `serialized_data`: The opaque u64 handle to the serialized state of the file.
  This handle is passed back to the handler's .`freeze()`,
  .`retrieve()`, and .`finish()` callbacks, allowing it to track
  and update its serialized state across phases.
- `private_data`: Pointer to the private data for the file used to hold runtime
  state that is not preserved. Set by the handler's .`preserve()`
  callback, and must be freed in the handler's .`unpreserve()`
  callback.
- `retrieve_status`: Status code indicating whether a user/kernel in the new kernel has
  successfully called `retrieve()` on this file. This prevents
  multiple retrieval attempts. A value of 0 means a `retrieve()`
  has not been attempted, a positive value means the `retrieve()`
  was successful, and a negative value means the `retrieve()`
  failed, and the value is the error code of the call.
- `mutex`: A mutex that protects the fields of this specific instance
  (e.g., **retrieved**, **file**), ensuring that operations like
  retrieving or finishing a file are atomic.
- `list`: The list_head linking this instance into its parent
  file_set's list of preserved files.
- `token`: The user-provided unique token used to identify this file.

**Description**

This structure is the core in-kernel representation of a single file being
managed through a live update. An instance is created by [`luo_preserve_file()`](#c-luo_preserve_file)
to link a 'struct file' to its corresponding handler, a user-provided token,
and the serialized state handle returned by the handler's .`preserve()`
operation.

These instances are tracked in a per-file_set list. The **serialized_data**
field, which holds a handle to the file's serialized state, may be updated
during the .`freeze()` callback before being serialized for the next kernel.
After reboot, these structures are recreated by [`luo_file_deserialize()`](#c-luo_file_deserialize) and
are finally cleaned up by [`luo_file_finish()`](#c-luo_file_finish).

#### <a id="c-luo_preserve_file"></a>`luo_preserve_file()`

```c
int luo_preserve_file(struct luo_file_set *file_set, u64 token, int fd)
```

Initiate the preservation of a file descriptor.

**Parameters**

- `struct luo_file_set *file_set`: The file_set to which the preserved file will be added.
- `u64 token`: A unique, user-provided identifier for the file.
- `int fd`: The file descriptor to be preserved.

**Description**

This function orchestrates the first phase of preserving a file. Upon entry,
it takes a reference to the 'struct file' via `fget()`, effectively making LUO
a co-owner of the file. This reference is held until the file is either
unpreserved or successfully finished in the next kernel, preventing the file
from being prematurely destroyed.

This function orchestrates the first phase of preserving a file. It performs
the following steps:

1. Validates that the **token** is not already in use within the file_set.
2. Ensures the file_set's memory for files serialization is allocated
   (allocates if needed).
3. Iterates through registered handlers, calling `can_preserve()` to find one
   compatible with the given **fd**.
4. Calls the handler's .`preserve()` operation, which saves the file's state
   and returns an opaque private data handle.
5. Adds the new instance to the file_set's internal list.

On success, LUO takes a reference to the 'struct file' and considers it
under its management until it is unpreserved or finished.

In case of any failure, all intermediate allocations (file reference, memory
for the 'luo_file' struct, etc.) are cleaned up before returning an error.

**Context**

Can be called from an ioctl handler during normal system operation.

**Return**

0 on success. Returns a negative errno on failure:
-EEXIST if the token is already used.
-EBADF if the file descriptor is invalid.
-ENOSPC if the file_set is full.
-ENOENT if no compatible handler is found.
-ENOMEM on memory allocation failure.
Other erros might be returned by .`preserve()`.

#### <a id="c-luo_file_unpreserve_files"></a>`luo_file_unpreserve_files()`

```c
void luo_file_unpreserve_files(struct luo_file_set *file_set)
```

Unpreserves all files from a file_set.

**Parameters**

- `struct luo_file_set *file_set`: The files to be cleaned up.

**Description**

This function serves as the primary cleanup path for a file_set. It is
invoked when the userspace agent closes the file_set's file descriptor.

- For each file, it performs the following cleanup actions:
  1. Calls the handler's .`unpreserve()` callback to allow the handler to
     release any resources it allocated.
  2. Removes the file from the file_set's internal tracking list.
  3. Releases the reference to the 'struct file' that was taken by
     [`luo_preserve_file()`](#c-luo_preserve_file) via `fput()`, returning ownership.
  4. Frees the memory associated with the internal 'struct luo_file'.

After all individual files are unpreserved, it frees the contiguous memory
block that was allocated to hold their serialization data.

#### <a id="c-luo_file_freeze"></a>`luo_file_freeze()`

```c
int luo_file_freeze(struct luo_file_set *file_set, struct luo_file_set_ser *file_set_ser)
```

Freezes all preserved files and serializes their metadata.

**Parameters**

- `struct luo_file_set *file_set`: The file_set whose files are to be frozen.
- `struct luo_file_set_ser *file_set_ser`: Where to put the serialized file_set.

**Description**

This function is called from the `reboot()` syscall path, just before the
kernel transitions to the new image via kexec. Its purpose is to perform the
final preparation and serialization of all preserved files in the file_set.

It iterates through each preserved file in FIFO order (the order of
preservation) and performs two main actions:

1. Freezes the File: It calls the handler's .`freeze()` callback for each
   file. This gives the handler a final opportunity to quiesce the device or
   prepare its state for the upcoming reboot. The handler may update its
   private data handle during this step.

2. Serializes Metadata: After a successful freeze, it copies the final file
   metadata—the handler's compatible string, the user token, and the final
   private data handle—into the pre-allocated contiguous memory buffer
   (file_set->files) that will be handed over to the next kernel via KHO.

Error Handling (Rollback):
This function is atomic. If any handler's .`freeze()` operation fails, the
entire live update is aborted. The `__luo_file_unfreeze()` helper is
immediately called to invoke the .`unfreeze()` op on all files that were
successfully frozen before the point of failure, rolling them back to a
running state. The function then returns an error, causing the `reboot()`
syscall to fail.

**Context**

Called only from the [`liveupdate_reboot()`](#c-liveupdate_reboot) path.

**Return**

0 on success, or a negative errno on failure.

#### <a id="c-luo_file_unfreeze"></a>`luo_file_unfreeze()`

```c
void luo_file_unfreeze(struct luo_file_set *file_set, struct luo_file_set_ser *file_set_ser)
```

Unfreezes all files in a file_set and clear serialization

**Parameters**

- `struct luo_file_set *file_set`: The file_set whose files are to be unfrozen.
- `struct luo_file_set_ser *file_set_ser`: Serialized file_set.

**Description**

This function rolls back the state of all files in a file_set after the
freeze phase has begun but must be aborted. It is the counterpart to
[`luo_file_freeze()`](#c-luo_file_freeze).

It invokes the `__luo_file_unfreeze()` helper with a NULL argument, which
signals the helper to iterate through all files in the file_set and call
their respective .`unfreeze()` handler callbacks.

**Context**

This is called when the live update is aborted during
the `reboot()` syscall, after [`luo_file_freeze()`](#c-luo_file_freeze) has been called.

#### <a id="c-luo_retrieve_file"></a>`luo_retrieve_file()`

```c
int luo_retrieve_file(struct luo_file_set *file_set, u64 token, struct file **filep)
```

Restores a preserved file from a file_set by its token.

**Parameters**

- `struct luo_file_set *file_set`: The file_set from which to retrieve the file.
- `u64 token`: The unique token identifying the file to be restored.
- `struct file **filep`: Output parameter; on success, this is populated with a pointer
  to the newly retrieved 'struct file'.

**Description**

This function is the primary mechanism for recreating a file in the new
kernel after a live update. It searches the file_set's list of deserialized
files for an entry matching the provided **token**.

The operation is idempotent: if a file has already been successfully
retrieved, this function will simply return a pointer to the existing
'struct file' and report success without re-executing the retrieve
operation. This is handled by checking the 'retrieved' flag under a lock.

File retrieval can happen in any order; it is not bound by the order of
preservation.

**Context**

Can be called from an ioctl or other in-kernel code in the new
kernel.

**Return**

0 on success. Returns a negative errno on failure:
-ENOENT if no file with the matching token is found.
Any error code returned by the handler's .`retrieve()` op.

#### <a id="c-luo_file_finish"></a>`luo_file_finish()`

```c
int luo_file_finish(struct luo_file_set *file_set)
```

Completes the lifecycle for all files in a file_set.

**Parameters**

- `struct luo_file_set *file_set`: The file_set to be finalized.

**Description**

This function orchestrates the final teardown of a live update file_set in
the new kernel. It should be called after all necessary files have been
retrieved and the userspace agent is ready to release the preserved state.

The function iterates through all tracked files. For each file, it performs
the following sequence of cleanup actions:

1. If file is not yet retrieved, retrieves it, and calls `can_finish()` on
   every file in the file_set. If all can_finish return true, continue to
   finish.
2. Calls the handler's .`finish()` callback (via luo_file_finish_one) to
   allow for final resource cleanup within the handler.
3. Releases LUO's ownership reference on the 'struct file' via `fput()`. This
   is the counterpart to the `get_file()` call in [`luo_retrieve_file()`](#c-luo_retrieve_file).
4. Removes the 'struct luo_file' from the file_set's internal list.
5. Frees the memory for the 'struct luo_file' instance itself.

After successfully finishing all individual files, it frees the
contiguous memory block that was used to transfer the serialized metadata
from the previous kernel.

Error Handling (Atomic Failure):
This operation is atomic. If any handler's .`can_finish()` op fails, the entire
function aborts immediately and returns an error.

**Context**

Can be called from an ioctl handler in the new kernel.

**Return**

0 on success, or a negative errno on failure.

#### <a id="c-luo_file_deserialize"></a>`luo_file_deserialize()`

```c
int luo_file_deserialize(struct luo_file_set *file_set, struct luo_file_set_ser *file_set_ser)
```

Reconstructs the list of preserved files in the new kernel.

**Parameters**

- `struct luo_file_set *file_set`: The incoming file_set to fill with deserialized data.
- `struct luo_file_set_ser *file_set_ser`: Serialized KHO file_set data from the previous kernel.

**Description**

This function is called during the early boot process of the new kernel. It
takes the raw, contiguous memory block of 'struct luo_file_ser' entries,
provided by the previous kernel, and transforms it back into a live,
in-memory linked list of 'struct luo_file' instances.

- For each serialized entry, it performs the following steps:
  1. Reads the 'compatible' string.
  2. Searches the global list of registered file handlers for one that
     matches the compatible string.
  3. Allocates a new 'struct luo_file'.
  4. Populates the new structure with the deserialized data (token, private
     data handle) and links it to the found handler. The 'file' pointer is
     initialized to NULL, as the file has not been retrieved yet.
  5. Adds the new 'struct luo_file' to the file_set's files_list.

This prepares the file_set for userspace, which can later call
[`luo_retrieve_file()`](#c-luo_retrieve_file) to restore the actual file descriptors.

**Context**

Called from session deserialization.

#### <a id="c-liveupdate_register_file_handler"></a>`liveupdate_register_file_handler()`

```c
int liveupdate_register_file_handler(struct liveupdate_file_handler *fh)
```

Register a file handler with LUO.

**Parameters**

- `struct liveupdate_file_handler *fh`: Pointer to a caller-allocated [`struct liveupdate_file_handler`](#c-struct-liveupdate_file_handler).
  The caller must initialize this structure, including a unique
  'compatible' string and a valid 'fh' callbacks. This function adds the
  handler to the global list of supported file handlers.

**Context**

Typically called during module initialization for file types that
support live update preservation.

**Return**

0 on success. Negative errno on failure.

#### <a id="c-liveupdate_unregister_file_handler"></a>`liveupdate_unregister_file_handler()`

```c
int liveupdate_unregister_file_handler(struct liveupdate_file_handler *fh)
```

Unregister a liveupdate file handler

**Parameters**

- `struct liveupdate_file_handler *fh`: The file handler to unregister

**Description**

Unregisters the file handler from the liveupdate core. This function
reverses the operations of [`liveupdate_register_file_handler()`](#c-liveupdate_register_file_handler).

It ensures safe removal by checking that:
No live update session is currently in progress.
No FLB registered with this file handler.

If the unregistration fails, the internal test state is reverted.

**Return**

0 Success. -EOPNOTSUPP when live update is not enabled. -EBUSY A live
update is in progress, can't quiesce live update or FLB is registred with
this file handler.


<a id="rst-see-also"></a>

## See Also

- [Live Update uAPI](</kernel/userspace/userspace-api/execution/liveupdate.md>)

- [Kexec Handover Subsystem](</kernel/internals/core-api/kho/index.md>)

---

# Semantics and Behavior of Local Atomic Operations

_Peios Kernel / Internals / Core APIs_

> This document explains the purpose of the local atomic operations, how to implement them for any given architecture and shows how they can be used properly. It also stresses on the precautions that must be taken when reading those local…

<a id="rst-semantics-and-behavior-of-local-atomic-operations"></a>
<a id="rst-local-ops"></a>

**Author:** Mathieu Desnoyers

This document explains the purpose of the local atomic operations, how to implement them for any given architecture and shows how they can be used properly. It also stresses on the precautions that must be taken when reading those local variables across CPUs when the order of memory writes matters.

> [!NOTE]
>
> Note that `local_t` based operations are not recommended for general kernel use. Please use the `this_cpu` operations instead unless there is really a special purpose. Most uses of `local_t` in the kernel have been replaced by `this_cpu` operations. `this_cpu` operations combine the relocation with the `local_t` like semantics in a single instruction and yield more compact and faster executing code.

<a id="rst-purpose-of-local-atomic-operations"></a>

## Purpose of local atomic operations

Local atomic operations are meant to provide fast and highly reentrant per CPU counters. They minimize the performance cost of standard atomic operations by removing the LOCK prefix and memory barriers normally required to synchronize across CPUs.

Having fast per CPU atomic counters is interesting in many cases: it does not require disabling interrupts to protect from interrupt handlers and it permits coherent counters in NMI handlers. It is especially useful for tracing purposes and for various performance monitoring counters.

Local atomic operations only guarantee variable modification atomicity wrt the CPU which owns the data. Therefore, care must taken to make sure that only one CPU writes to the `local_t` data. This is done by using per cpu data and making sure that we modify it from within a preemption safe context. It is however permitted to read `local_t` data from any CPU: it will then appear to be written out of order wrt other memory writes by the owner CPU.

<a id="rst-implementation-for-a-given-architecture"></a>

## Implementation for a given architecture

It can be done by slightly modifying the standard atomic operations: only their UP variant must be kept. It typically means removing LOCK prefix (on i386 and x86_64) and any SMP synchronization barrier. If the architecture does not have a different behavior between SMP and UP, including `asm-generic/local.h` in your architecture's `local.h` is sufficient.

The `local_t` type is defined as an opaque `signed long` by embedding an `atomic_long_t` inside a structure. This is made so a cast from this type to a `long` fails. The definition looks like:



```text
typedef struct { atomic_long_t a; } local_t;
```

<a id="rst-rules-to-follow-when-using-local-atomic-operations"></a>

## Rules to follow when using local atomic operations

- Variables touched by local ops must be per cpu variables.

- *Only* the CPU owner of these variables must write to them.

- This CPU can use local ops from any context (process, irq, softirq, nmi, ...) to update its `local_t` variables.

- Preemption (or interrupts) must be disabled when using local ops in process context to make sure the process won't be migrated to a different CPU between getting the per-cpu variable and doing the actual local op.

- When using local ops in interrupt context, no special care must be taken on a mainline kernel, since they will run on the local CPU with preemption already disabled. I suggest, however, to explicitly disable preemption anyway to make sure it will still work correctly on -rt kernels.

- Reading the local cpu variable will provide the current copy of the variable.

- Reads of these variables can be done from any CPU, because updates to "`long`", aligned, variables are always atomic. Since no memory synchronization is done by the writer CPU, an outdated copy of the variable can be read when reading some *other* cpu's variables.

<a id="rst-how-to-use-local-atomic-operations"></a>

## How to use local atomic operations



```text
#include <linux/percpu.h>
#include <asm/local.h>

static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);
```

<a id="rst-counting"></a>

## Counting

Counting is done on all the bits of a signed long.

In preemptible context, use `get_cpu_var()` and `put_cpu_var()` around local atomic operations: it makes sure that preemption is disabled around write access to the per cpu variable. For instance:



```text
local_inc(&get_cpu_var(counters));
put_cpu_var(counters);
```

If you are already in a preemption-safe context, you can use `this_cpu_ptr()` instead:



```text
local_inc(this_cpu_ptr(&counters));
```

<a id="rst-reading-the-counters"></a>

## Reading the counters

Those local counters can be read from foreign CPUs to sum the count. Note that the data seen by local_read across CPUs must be considered to be out of order relatively to other memory writes happening on the CPU that owns the data:



```text
long sum = 0;
for_each_online_cpu(cpu)
        sum += local_read(&per_cpu(counters, cpu));
```

If you want to use a remote local_read to synchronize access to a resource between CPUs, explicit `smp_wmb()` and `smp_rmb()` memory barriers must be used respectively on the writer and the reader CPUs. It would be the case if you use the `local_t` variable as a counter of bytes written in a buffer: there should be a `smp_wmb()` between the buffer write and the counter increment and also a `smp_rmb()` between the counter read and the buffer read.

Here is a sample module which implements a basic per cpu counter using `local.h`:



```text
/* test-local.c
 *
 * Sample module for local.h usage.
 */


#include <asm/local.h>
#include <linux/module.h>
#include <linux/timer.h>

static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);

static struct timer_list test_timer;

/* IPI called on each CPU. */
static void test_each(void *info)
{
        /* Increment the counter from a non preemptible context */
        printk("Increment on cpu %d\n", smp_processor_id());
        local_inc(this_cpu_ptr(&counters));

        /* This is what incrementing the variable would look like within a
         * preemptible context (it disables preemption) :
         *
         * local_inc(&get_cpu_var(counters));
         * put_cpu_var(counters);
         */
}

static void do_test_timer(unsigned long data)
{
        int cpu;

        /* Increment the counters */
        on_each_cpu(test_each, NULL, 1);
        /* Read all the counters */
        printk("Counters read from CPU %d\n", smp_processor_id());
        for_each_online_cpu(cpu) {
                printk("Read : CPU %d, count %ld\n", cpu,
                        local_read(&per_cpu(counters, cpu)));
        }
        mod_timer(&test_timer, jiffies + 1000);
}

static int __init test_init(void)
{
        /* initialize the timer that will increment the counter */
        timer_setup(&test_timer, do_test_timer, 0);
        mod_timer(&test_timer, jiffies + 1);

        return 0;
}

static void __exit test_exit(void)
{
        timer_shutdown_sync(&test_timer);
}

module_init(test_init);
module_exit(test_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mathieu Desnoyers");
MODULE_DESCRIPTION("Local Atomic Ops");
```

---

# Maple Tree

_Peios Kernel / Internals / Core APIs_

> The Maple Tree is a B-Tree data type which is optimized for storing non-overlapping ranges, including ranges of size 1. The tree was designed to be simple to use and does not require a user written search method. It supports iterating over…

<a id="rst-maple-tree"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** Liam R. Howlett

<a id="rst-overview"></a>

## Overview

The Maple Tree is a B-Tree data type which is optimized for storing non-overlapping ranges, including ranges of size 1.  The tree was designed to be simple to use and does not require a user written search method.  It supports iterating over a range of entries and going to the previous or next entry in a cache-efficient manner.  The tree can also be put into an RCU-safe mode of operation which allows reading and writing concurrently.  Writers must synchronize on a lock, which can be the default spinlock, or the user can set the lock to an external lock of a different type.

The Maple Tree maintains a small memory footprint and was designed to use modern processor cache efficiently.  The majority of the users will be able to use the normal API.  An [Advanced API](<#rst-maple-tree-advanced-api>) exists for more complex scenarios.  The most important usage of the Maple Tree is the tracking of the virtual memory areas.

The Maple Tree can store values between `0` and `ULONG_MAX`.  The Maple Tree reserves values with the bottom two bits set to '10' which are below 4096 (ie 2, 6, 10 .. 4094) for internal use.  If the entries may use reserved entries then the users can convert the entries using xa_mk_value() and convert them back by calling xa_to_value().  If the user needs to use a reserved value, then the user can convert the value when using the [Advanced API](<#rst-maple-tree-advanced-api>), but are blocked by the normal API.

The Maple Tree can also be configured to support searching for a gap of a given size (or larger).

Pre-allocating of nodes is also supported using the [Advanced API](<#rst-maple-tree-advanced-api>).  This is useful for users who must guarantee a successful store operation within a given code segment when allocating cannot be done.  Allocations of nodes are relatively small at around 256 bytes.

<a id="rst-normal-api"></a>
<a id="rst-maple-tree-normal-api"></a>

## Normal API

Start by initialising a maple tree, either with DEFINE_MTREE() for statically allocated maple trees or mt_init() for dynamically allocated ones.  A freshly-initialised maple tree contains a `NULL` pointer for the range `0` - `ULONG_MAX`.  There are currently two types of maple trees supported: the allocation tree and the regular tree.  The regular tree has a higher branching factor for internal nodes.  The allocation tree has a lower branching factor but allows the user to search for a gap of a given size or larger from either `0` upwards or `ULONG_MAX` down.  An allocation tree can be used by passing in the `MT_FLAGS_ALLOC_RANGE` flag when initialising the tree.

You can then set entries using mtree_store() or mtree_store_range(). mtree_store() will overwrite any entry with the new entry and return 0 on success or an error code otherwise.  mtree_store_range() works in the same way but takes a range.  mtree_load() is used to retrieve the entry stored at a given index.  You can use mtree_erase() to erase an entire range by only knowing one value within that range, or mtree_store() call with an entry of NULL may be used to partially erase a range or many ranges at once.

If you want to only store a new entry to a range (or index) if that range is currently `NULL`, you can use mtree_insert_range() or mtree_insert() which return -EEXIST if the range is not empty.

You can search for an entry from an index upwards by using mt_find().

You can walk each entry within a range by calling mt_for_each().  You must provide a temporary variable to store a cursor.  If you want to walk each element of the tree then `0` and `ULONG_MAX` may be used as the range.  If the caller is going to hold the lock for the duration of the walk then it is worth looking at the mas_for_each() API in the [Advanced API](<#rst-maple-tree-advanced-api>) section.

Sometimes it is necessary to ensure the next call to store to a maple tree does not allocate memory, please see [Advanced API](<#rst-maple-tree-advanced-api>) for this use case.

You can use mtree_dup() to duplicate an entire maple tree. It is a more efficient way than inserting all elements one by one into a new tree.

Finally, you can remove all entries from a maple tree by calling mtree_destroy().  If the maple tree entries are pointers, you may wish to free the entries first.

<a id="rst-allocating-nodes"></a>

### Allocating Nodes

The allocations are handled by the internal tree code.  See [Advanced Allocating Nodes](<#rst-maple-tree-advanced-alloc>) for other options.

<a id="rst-locking"></a>

### Locking

You do not have to worry about locking.  See [Advanced Locking](<#rst-maple-tree-advanced-locks>) for other options.

The Maple Tree uses RCU and an internal spinlock to synchronise access:

- **Takes RCU read lock:**

  - mtree_load()

  - mt_find()

  - mt_for_each()

  - mt_next()

  - mt_prev()

- **Takes ma_lock internally:**

  - mtree_store()

  - mtree_store_range()

  - mtree_insert()

  - mtree_insert_range()

  - mtree_erase()

  - mtree_dup()

  - mtree_destroy()

  - mt_set_in_rcu()

  - mt_clear_in_rcu()

If you want to take advantage of the internal lock to protect the data structures that you are storing in the Maple Tree, you can call mtree_lock() before calling mtree_load(), then take a reference count on the object you have found before calling mtree_unlock().  This will prevent stores from removing the object from the tree between looking up the object and incrementing the refcount.  You can also use RCU to avoid dereferencing freed memory, but an explanation of that is beyond the scope of this document.

<a id="rst-advanced-api"></a>
<a id="rst-maple-tree-advanced-api"></a>

## Advanced API

The advanced API offers more flexibility and better performance at the cost of an interface which can be harder to use and has fewer safeguards. You must take care of your own locking while using the advanced API. You can use the ma_lock, RCU or an external lock for protection. You can mix advanced and normal operations on the same array, as long as the locking is compatible.  The [Normal API](<#rst-maple-tree-normal-api>) is implemented in terms of the advanced API.

The advanced API is based around the ma_state, this is where the 'mas' prefix originates.  The ma_state struct keeps track of tree operations to make life easier for both internal and external tree users.

Initialising the maple tree is the same as in the [Normal API](<#rst-maple-tree-normal-api>). Please see above.

The maple state keeps track of the range start and end in mas-&gt;index and mas-&gt;last, respectively.

mas_walk() will walk the tree to the location of mas-&gt;index and set the mas-&gt;index and mas-&gt;last according to the range for the entry.

You can set entries using mas_store().  mas_store() will overwrite any entry with the new entry and return the first existing entry that is overwritten. The range is passed in as members of the maple state: index and last.

You can use mas_erase() to erase an entire range by setting index and last of the maple state to the desired range to erase.  This will erase the first range that is found in that range, set the maple state index and last as the range that was erased and return the entry that existed at that location.

You can walk each entry within a range by using mas_for_each().  If you want to walk each element of the tree then `0` and `ULONG_MAX` may be used as the range.  If the lock needs to be periodically dropped, see the locking section mas_pause().

Using a maple state allows mas_next() and mas_prev() to function as if the tree was a linked list.  With such a high branching factor the amortized performance penalty is outweighed by cache optimization.  mas_next() will return the next entry which occurs after the entry at index.  mas_prev() will return the previous entry which occurs before the entry at index.

mas_find() will find the first entry which exists at or above index on the first call, and the next entry from every subsequent calls.

mas_find_rev() will find the first entry which exists at or below the last on the first call, and the previous entry from every subsequent calls.

If the user needs to yield the lock during an operation, then the maple state must be paused using mas_pause().

There are a few extra interfaces provided when using an allocation tree. If you wish to search for a gap within a range, then mas_empty_area() or mas_empty_area_rev() can be used.  mas_empty_area() searches for a gap starting at the lowest index given up to the maximum of the range. mas_empty_area_rev() searches for a gap starting at the highest index given and continues downward to the lower bound of the range.

<a id="rst-advanced-allocating-nodes"></a>
<a id="rst-maple-tree-advanced-alloc"></a>

### Advanced Allocating Nodes

Allocations are usually handled internally to the tree, however if allocations need to occur before a write occurs then calling mas_expected_entries() will allocate the worst-case number of needed nodes to insert the provided number of ranges.  This also causes the tree to enter mass insertion mode.  Once insertions are complete calling mas_destroy() on the maple state will free the unused allocations.

<a id="rst-advanced-locking"></a>
<a id="rst-maple-tree-advanced-locks"></a>

### Advanced Locking

The maple tree uses a spinlock by default, but external locks can be used for tree updates as well.  To use an external lock, the tree must be initialized with the `MT_FLAGS_LOCK_EXTERN flag`, this is usually done with the MTREE_INIT_EXT() \#define, which takes an external lock as an argument.

<a id="rst-functions-and-structures"></a>

## Functions and structures


**Maple tree flags**

* MT_FLAGS_ALLOC_RANGE       - Track gaps in this tree
* MT_FLAGS_USE_RCU           - Operate in RCU mode
* MT_FLAGS_HEIGHT_OFFSET     - The position of the tree height in the flags
* MT_FLAGS_HEIGHT_MASK       - The mask for the maple tree height value
* MT_FLAGS_LOCK_MASK         - How the mt_lock is used
* MT_FLAGS_LOCK_IRQ          - Acquired irq-safe
* MT_FLAGS_LOCK_BH           - Acquired bh-safe
* MT_FLAGS_LOCK_EXTERN       - mt_lock is not used

MAPLE_HEIGHT_MAX     The largest height that can be stored

#### <a id="c-MTREE_INIT"></a>`MTREE_INIT()`

```c
MTREE_INIT(name, __flags)
```

Initialize a maple tree

**Parameters**

- `name`: The maple tree name
- `__flags`: The maple tree flags

#### <a id="c-MTREE_INIT_EXT"></a>`MTREE_INIT_EXT()`

```c
MTREE_INIT_EXT(name, __flags, __lock)
```

Initialize a maple tree with an external lock.

**Parameters**

- `name`: The tree name
- `__flags`: The maple tree flags
- `__lock`: The external lock

#### <a id="c-mtree_empty"></a>`mtree_empty()`

```c
bool mtree_empty(const struct maple_tree *mt)
```

Determine if a tree has any present entries.

**Parameters**

- `const struct maple_tree *mt`: Maple Tree.

**Context**

Any context.

**Return**

`true` if the tree contains only NULL pointers.

#### <a id="c-mas_reset"></a>`mas_reset()`

```c
void mas_reset(struct ma_state *mas)
```

Reset a Maple Tree operation state.

**Parameters**

- `struct ma_state *mas`: Maple Tree operation state.

**Description**

Resets the error or walk state of the **mas** so future walks of the
array will start from the root.  Use this if you have dropped the
lock and want to reuse the ma_state.

**Context**

Any context.

#### <a id="c-mas_for_each"></a>`mas_for_each()`

```c
mas_for_each(__mas, __entry, __max)
```

Iterate over a range of the maple tree.

**Parameters**

- `__mas`: Maple Tree operation state (maple_state)
- `__entry`: Entry retrieved from the tree
- `__max`: maximum index to retrieve from the tree

**Description**

When returned, mas->index and mas->last will hold the entire range for the
entry.

**Note**

may return the zero entry.

#### <a id="c-mas_for_each_rev"></a>`mas_for_each_rev()`

```c
mas_for_each_rev(__mas, __entry, __min)
```

Iterate over a range of the maple tree in reverse order.

**Parameters**

- `__mas`: Maple Tree operation state (maple_state)
- `__entry`: Entry retrieved from the tree
- `__min`: minimum index to retrieve from the tree

**Description**

When returned, mas->index and mas->last will hold the entire range for the
entry.

**Note**

may return the zero entry.

#### <a id="c-__mas_set_range"></a>`__mas_set_range()`

```c
void __mas_set_range(struct ma_state *mas, unsigned long start, unsigned long last)
```

Set up Maple Tree operation state to a sub-range of the current location.

**Parameters**

- `struct ma_state *mas`: Maple Tree operation state.
- `unsigned long start`: New start of range in the Maple Tree.
- `unsigned long last`: New end of range in the Maple Tree.

**Description**

set the internal maple state values to a sub-range.
Please use [`mas_set_range()`](#c-mas_set_range) if you do not know where you are in the tree.

#### <a id="c-mas_set_range"></a>`mas_set_range()`

```c
void mas_set_range(struct ma_state *mas, unsigned long start, unsigned long last)
```

Set up Maple Tree operation state for a different index.

**Parameters**

- `struct ma_state *mas`: Maple Tree operation state.
- `unsigned long start`: New start of range in the Maple Tree.
- `unsigned long last`: New end of range in the Maple Tree.

**Description**

Move the operation state to refer to a different range.  This will
have the effect of starting a walk from the top; see [`mas_next()`](#c-mas_next)
to move to an adjacent index.

#### <a id="c-mas_set"></a>`mas_set()`

```c
void mas_set(struct ma_state *mas, unsigned long index)
```

Set up Maple Tree operation state for a different index.

**Parameters**

- `struct ma_state *mas`: Maple Tree operation state.
- `unsigned long index`: New index into the Maple Tree.

**Description**

Move the operation state to refer to a different index.  This will
have the effect of starting a walk from the top; see [`mas_next()`](#c-mas_next)
to move to an adjacent index.

#### <a id="c-mt_init_flags"></a>`mt_init_flags()`

```c
void mt_init_flags(struct maple_tree *mt, unsigned int flags)
```

Initialise an empty maple tree with flags.

**Parameters**

- `struct maple_tree *mt`: Maple Tree
- `unsigned int flags`: maple tree flags.

**Description**

If you need to initialise a Maple Tree with special flags (eg, an
allocation tree), use this function.

**Context**

Any context.

#### <a id="c-mt_init"></a>`mt_init()`

```c
void mt_init(struct maple_tree *mt)
```

Initialise an empty maple tree.

**Parameters**

- `struct maple_tree *mt`: Maple Tree

**Description**

An empty Maple Tree.

**Context**

Any context.

#### <a id="c-mt_clear_in_rcu"></a>`mt_clear_in_rcu()`

```c
void mt_clear_in_rcu(struct maple_tree *mt)
```

Switch the tree to non-RCU mode.

**Parameters**

- `struct maple_tree *mt`: The Maple Tree

#### <a id="c-mt_set_in_rcu"></a>`mt_set_in_rcu()`

```c
void mt_set_in_rcu(struct maple_tree *mt)
```

Switch the tree to RCU safe mode.

**Parameters**

- `struct maple_tree *mt`: The Maple Tree

#### <a id="c-mt_for_each"></a>`mt_for_each()`

```c
mt_for_each(__tree, __entry, __index, __max)
```

Iterate over each entry starting at index until max.

**Parameters**

- `__tree`: The Maple Tree
- `__entry`: The current entry
- `__index`: The index to start the search from. Subsequently used as iterator.
- `__max`: The maximum limit for **index**

**Description**

This iterator skips all entries, which resolve to a NULL pointer,
e.g. entries which has been reserved with XA_ZERO_ENTRY.



#### <a id="c-mas_prealloc_calc"></a>`mas_prealloc_calc()`

```c
void mas_prealloc_calc(struct ma_wr_state *wr_mas, void *entry)
```

Calculate number of nodes needed for a given store oepration

**Parameters**

- `struct ma_wr_state *wr_mas`: The maple write state
- `void *entry`: The entry to store into the tree

**Return**

Number of nodes required for preallocation.

#### <a id="c-mas_wr_preallocate"></a>`mas_wr_preallocate()`

```c
void mas_wr_preallocate(struct ma_wr_state *wr_mas, void *entry)
```

Preallocate enough nodes for a store operation

**Parameters**

- `struct ma_wr_state *wr_mas`: The maple write state
- `void *entry`: The entry that will be stored

#### <a id="c-mas_insert"></a>`mas_insert()`

```c
void * mas_insert(struct ma_state *mas, void *entry)
```

Internal call to insert a value

**Parameters**

- `struct ma_state *mas`: The maple state
- `void *entry`: The entry to store

**Return**

`NULL` or the contents that already exists at the requested index
otherwise.  The maple state needs to be checked for error conditions.

#### <a id="c-mas_alloc_cyclic"></a>`mas_alloc_cyclic()`

```c
int mas_alloc_cyclic(struct ma_state *mas, unsigned long *startp, void *entry, unsigned long range_lo, unsigned long range_hi, unsigned long *next, gfp_t gfp)
```

Internal call to find somewhere to store an entry

**Parameters**

- `struct ma_state *mas`: The maple state.
- `unsigned long *startp`: Pointer to ID.
- `void *entry`: The entry to store.
- `unsigned long range_lo`: Lower bound of range to search.
- `unsigned long range_hi`: Upper bound of range to search.
- `unsigned long *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: The GFP_FLAGS to use for allocations.

**Return**

0 if the allocation succeeded without wrapping, 1 if the
allocation succeeded after wrapping, or -EBUSY if there are no
free entries.

#### <a id="c-mas_walk"></a>`mas_walk()`

```c
void * mas_walk(struct ma_state *mas)
```

Search for **mas->index** in the tree.

**Parameters**

- `struct ma_state *mas`: The maple state.

**Description**

mas->index and mas->last will be set to the range if there is a value.  If
mas->status is ma_none, reset to ma_start

**Return**

the entry at the location or `NULL`.

#### <a id="c-mte_dead_walk"></a>`mte_dead_walk()`

```c
void __rcu ** mte_dead_walk(struct maple_enode **enode, unsigned char offset)
```

Walk down a dead tree to just before the leaves

**Parameters**

- `struct maple_enode **enode`: The maple encoded node
- `unsigned char offset`: The starting offset

**Note**

This can only be used from the RCU callback context.

#### <a id="c-mt_free_walk"></a>`mt_free_walk()`

```c
void mt_free_walk(struct rcu_head *head)
```

Walk & free a tree in the RCU callback context

**Parameters**

- `struct rcu_head *head`: The RCU head that's within the node.

**Note**

This can only be used from the RCU callback context.

#### <a id="c-mas_store"></a>`mas_store()`

```c
void * mas_store(struct ma_state *mas, void *entry)
```

Store an **entry**.

**Parameters**

- `struct ma_state *mas`: The maple state.
- `void *entry`: The entry to store.

**Description**

The **mas->index** and **mas->last** is used to set the range for the **entry**.

**Return**

the first entry between mas->index and mas->last or `NULL`.

#### <a id="c-mas_store_gfp"></a>`mas_store_gfp()`

```c
int mas_store_gfp(struct ma_state *mas, void *entry, gfp_t gfp)
```

Store a value into the tree.

**Parameters**

- `struct ma_state *mas`: The maple state
- `void *entry`: The entry to store
- `gfp_t gfp`: The GFP_FLAGS to use for allocations if necessary.

**Return**

0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
be allocated.

#### <a id="c-mas_store_prealloc"></a>`mas_store_prealloc()`

```c
void mas_store_prealloc(struct ma_state *mas, void *entry)
```

Store a value into the tree using memory preallocated in the maple state.

**Parameters**

- `struct ma_state *mas`: The maple state
- `void *entry`: The entry to store.

#### <a id="c-mas_preallocate"></a>`mas_preallocate()`

```c
int mas_preallocate(struct ma_state *mas, void *entry, gfp_t gfp)
```

Preallocate enough nodes for a store operation

**Parameters**

- `struct ma_state *mas`: The maple state
- `void *entry`: The entry that will be stored
- `gfp_t gfp`: The GFP_FLAGS to use for allocations.

**Return**

0 on success, -ENOMEM if memory could not be allocated.

#### <a id="c-mas_next"></a>`mas_next()`

```c
void * mas_next(struct ma_state *mas, unsigned long max)
```

Get the next entry.

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long max`: The maximum index to check.

**Description**

Returns the next entry after **mas->index**.
Must hold rcu_read_lock or the write lock.
Can return the zero entry.

**Return**

The next entry or `NULL`

#### <a id="c-mas_next_range"></a>`mas_next_range()`

```c
void * mas_next_range(struct ma_state *mas, unsigned long max)
```

Advance the maple state to the next range

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long max`: The maximum index to check.

**Description**

Sets **mas->index** and **mas->last** to the range.
Must hold rcu_read_lock or the write lock.
Can return the zero entry.

**Return**

The next entry or `NULL`

#### <a id="c-mt_next"></a>`mt_next()`

```c
void * mt_next(struct maple_tree *mt, unsigned long index, unsigned long max)
```

get the next value in the maple tree

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The start index
- `unsigned long max`: The maximum index to check

**Description**

Takes RCU read lock internally to protect the search, which does not
protect the returned pointer after dropping RCU read lock.
See also: Documentation/core-api/maple_tree.rst

**Return**

The entry higher than **index** or `NULL` if nothing is found.

#### <a id="c-mas_prev"></a>`mas_prev()`

```c
void * mas_prev(struct ma_state *mas, unsigned long min)
```

Get the previous entry

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long min`: The minimum value to check.

**Description**

Must hold rcu_read_lock or the write lock.
Will reset mas to ma_start if the status is ma_none.  Will stop on not
searchable nodes.

**Return**

the previous value or `NULL`.

#### <a id="c-mas_prev_range"></a>`mas_prev_range()`

```c
void * mas_prev_range(struct ma_state *mas, unsigned long min)
```

Advance to the previous range

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long min`: The minimum value to check.

**Description**

Sets **mas->index** and **mas->last** to the range.
Must hold rcu_read_lock or the write lock.
Will reset mas to ma_start if the node is ma_none.  Will stop on not
searchable nodes.

**Return**

the previous value or `NULL`.

#### <a id="c-mt_prev"></a>`mt_prev()`

```c
void * mt_prev(struct maple_tree *mt, unsigned long index, unsigned long min)
```

get the previous value in the maple tree

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The start index
- `unsigned long min`: The minimum index to check

**Description**

Takes RCU read lock internally to protect the search, which does not
protect the returned pointer after dropping RCU read lock.
See also: Documentation/core-api/maple_tree.rst

**Return**

The entry before **index** or `NULL` if nothing is found.

#### <a id="c-mas_pause"></a>`mas_pause()`

```c
void mas_pause(struct ma_state *mas)
```

Pause a mas_find/mas_for_each to drop the lock.

**Parameters**

- `struct ma_state *mas`: The maple state to pause

**Description**

Some users need to pause a walk and drop the lock they're holding in
order to yield to a higher priority thread or carry out an operation
on an entry.  Those users should call this function before they drop
the lock.  It resets the **mas** to be suitable for the next iteration
of the loop after the user has reacquired the lock.  If most entries
found during a walk require you to call [`mas_pause()`](#c-mas_pause), the [`mt_for_each()`](#c-mt_for_each)
iterator may be more appropriate.

#### <a id="c-mas_find_setup"></a>`mas_find_setup()`

```c
bool mas_find_setup(struct ma_state *mas, unsigned long max, void **entry)
```

Internal function to set up mas_find*().

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long max`: The maximum index
- `void **entry`: Pointer to the entry

**Return**

True if entry is the answer, false otherwise.

#### <a id="c-mas_find"></a>`mas_find()`

```c
void * mas_find(struct ma_state *mas, unsigned long max)
```

On the first call, find the entry at or after mas->index up to `max`. Otherwise, find the entry after mas->index.

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long max`: The maximum value to check.

**Description**

Must hold rcu_read_lock or the write lock.
If an entry exists, last and index are updated accordingly.
May set **mas->status** to ma_overflow.

**Return**

The entry or `NULL`.

#### <a id="c-mas_find_range"></a>`mas_find_range()`

```c
void * mas_find_range(struct ma_state *mas, unsigned long max)
```

On the first call, find the entry at or after mas->index up to `max`. Otherwise, advance to the next slot mas->index.

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long max`: The maximum value to check.

**Description**

Must hold rcu_read_lock or the write lock.
If an entry exists, last and index are updated accordingly.
May set **mas->status** to ma_overflow.

**Return**

The entry or `NULL`.

#### <a id="c-mas_find_rev_setup"></a>`mas_find_rev_setup()`

```c
bool mas_find_rev_setup(struct ma_state *mas, unsigned long min, void **entry)
```

Internal function to set up mas_find_*`_rev()`

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long min`: The minimum index
- `void **entry`: Pointer to the entry

**Return**

True if entry is the answer, false otherwise.

#### <a id="c-mas_find_rev"></a>`mas_find_rev()`

```c
void * mas_find_rev(struct ma_state *mas, unsigned long min)
```

On the first call, find the first non-null entry at or below mas->index down to `min`. Otherwise find the first non-null entry below mas->index down to `min`.

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long min`: The minimum value to check.

**Description**

Must hold rcu_read_lock or the write lock.
If an entry exists, last and index are updated accordingly.
May set **mas->status** to ma_underflow.

**Return**

The entry or `NULL`.

#### <a id="c-mas_find_range_rev"></a>`mas_find_range_rev()`

```c
void * mas_find_range_rev(struct ma_state *mas, unsigned long min)
```

On the first call, find the first non-null entry at or below mas->index down to `min`. Otherwise advance to the previous slot after mas->index down to `min`.

**Parameters**

- `struct ma_state *mas`: The maple state
- `unsigned long min`: The minimum value to check.

**Description**

Must hold rcu_read_lock or the write lock.
If an entry exists, last and index are updated accordingly.
May set **mas->status** to ma_underflow.

**Return**

The entry or `NULL`.

#### <a id="c-mas_erase"></a>`mas_erase()`

```c
void * mas_erase(struct ma_state *mas)
```

Find the range in which index resides and erase the entire range.

**Parameters**

- `struct ma_state *mas`: The maple state

**Description**

Must hold the write lock.
Searches for **mas->index**, sets **mas->index** and **mas->last** to the range and
erases that range.

**Return**

the entry that was erased or `NULL`, **mas->index** and **mas->last** are updated.

#### <a id="c-mas_nomem"></a>`mas_nomem()`

```c
bool mas_nomem(struct ma_state *mas, gfp_t gfp)
```

Check if there was an error allocating and do the allocation if necessary If there are allocations, then free them.

**Parameters**

- `struct ma_state *mas`: The maple state
- `gfp_t gfp`: The GFP_FLAGS to use for allocations

**Return**

true on allocation, false otherwise.

#### <a id="c-mtree_load"></a>`mtree_load()`

```c
void * mtree_load(struct maple_tree *mt, unsigned long index)
```

Load a value stored in a maple tree

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The index to load

**Return**

the entry or `NULL`

#### <a id="c-mtree_store_range"></a>`mtree_store_range()`

```c
int mtree_store_range(struct maple_tree *mt, unsigned long index, unsigned long last, void *entry, gfp_t gfp)
```

Store an entry at a given range.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The start of the range
- `unsigned long last`: The end of the range
- `void *entry`: The entry to store
- `gfp_t gfp`: The GFP_FLAGS to use for allocations

**Return**

0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
be allocated.

#### <a id="c-mtree_store"></a>`mtree_store()`

```c
int mtree_store(struct maple_tree *mt, unsigned long index, void *entry, gfp_t gfp)
```

Store an entry at a given index.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The index to store the value
- `void *entry`: The entry to store
- `gfp_t gfp`: The GFP_FLAGS to use for allocations

**Return**

0 on success, -EINVAL on invalid request, -ENOMEM if memory could not
be allocated.

#### <a id="c-mtree_insert_range"></a>`mtree_insert_range()`

```c
int mtree_insert_range(struct maple_tree *mt, unsigned long first, unsigned long last, void *entry, gfp_t gfp)
```

Insert an entry at a given range if there is no value.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long first`: The start of the range
- `unsigned long last`: The end of the range
- `void *entry`: The entry to store
- `gfp_t gfp`: The GFP_FLAGS to use for allocations.

**Return**

0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
request, -ENOMEM if memory could not be allocated.

#### <a id="c-mtree_insert"></a>`mtree_insert()`

```c
int mtree_insert(struct maple_tree *mt, unsigned long index, void *entry, gfp_t gfp)
```

Insert an entry at a given index if there is no value.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The index to store the value
- `void *entry`: The entry to store
- `gfp_t gfp`: The GFP_FLAGS to use for allocations.

**Return**

0 on success, -EEXISTS if the range is occupied, -EINVAL on invalid
request, -ENOMEM if memory could not be allocated.

#### <a id="c-mtree_alloc_cyclic"></a>`mtree_alloc_cyclic()`

```c
int mtree_alloc_cyclic(struct maple_tree *mt, unsigned long *startp, void *entry, unsigned long range_lo, unsigned long range_hi, unsigned long *next, gfp_t gfp)
```

Find somewhere to store this entry in the tree.

**Parameters**

- `struct maple_tree *mt`: The maple tree.
- `unsigned long *startp`: Pointer to ID.
- `void *entry`: The entry to store.
- `unsigned long range_lo`: Lower bound of range to search.
- `unsigned long range_hi`: Upper bound of range to search.
- `unsigned long *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: The GFP_FLAGS to use for allocations.

**Description**

Finds an empty entry in **mt** after **next**, stores the new index into
the **id** pointer, stores the entry at that index, then updates **next**.

**mt** must be initialized with the MT_FLAGS_ALLOC_RANGE flag.

**Context**

Any context.  Takes and releases the mt.lock.  May sleep if
the **gfp** flags permit.

**Return**

0 if the allocation succeeded without wrapping, 1 if the
allocation succeeded after wrapping, -ENOMEM if memory could not be
allocated, -EINVAL if **mt** cannot be used, or -EBUSY if there are no
free entries.

#### <a id="c-mtree_erase"></a>`mtree_erase()`

```c
void * mtree_erase(struct maple_tree *mt, unsigned long index)
```

Find an index and erase the entire range.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long index`: The index to erase

**Description**

Erasing is the same as a walk to an entry then a store of a NULL to that
ENTIRE range.  In fact, it is implemented as such using the advanced API.

**Return**

The entry stored at the **index** or `NULL`

#### <a id="c-__mt_dup"></a>`__mt_dup()`

```c
int __mt_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
```

Duplicate an entire maple tree

**Parameters**

- `struct maple_tree *mt`: The source maple tree
- `struct maple_tree *new`: The new maple tree
- `gfp_t gfp`: The GFP_FLAGS to use for allocations

**Description**

This function duplicates a maple tree in Depth-First Search (DFS) pre-order
traversal. It uses [`memcpy()`](/kernel/internals/core-api/kernel-api.md#c-memcpy) to copy nodes in the source tree and allocate
new child nodes in non-leaf nodes. The new node is exactly the same as the
source node except for all the addresses stored in it. It will be faster than
traversing all elements in the source tree and inserting them one by one into
the new tree.
The user needs to ensure that the attributes of the source tree and the new
tree are the same, and the new tree needs to be an empty tree, otherwise
-EINVAL will be returned.
Note that the user needs to manually lock the source tree and the new tree.

**Return**

0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
the attributes of the two trees are different or the new tree is not an empty
tree.

#### <a id="c-mtree_dup"></a>`mtree_dup()`

```c
int mtree_dup(struct maple_tree *mt, struct maple_tree *new, gfp_t gfp)
```

Duplicate an entire maple tree

**Parameters**

- `struct maple_tree *mt`: The source maple tree
- `struct maple_tree *new`: The new maple tree
- `gfp_t gfp`: The GFP_FLAGS to use for allocations

**Description**

This function duplicates a maple tree in Depth-First Search (DFS) pre-order
traversal. It uses [`memcpy()`](/kernel/internals/core-api/kernel-api.md#c-memcpy) to copy nodes in the source tree and allocate
new child nodes in non-leaf nodes. The new node is exactly the same as the
source node except for all the addresses stored in it. It will be faster than
traversing all elements in the source tree and inserting them one by one into
the new tree.
The user needs to ensure that the attributes of the source tree and the new
tree are the same, and the new tree needs to be an empty tree, otherwise
-EINVAL will be returned.

**Return**

0 on success, -ENOMEM if memory could not be allocated, -EINVAL If
the attributes of the two trees are different or the new tree is not an empty
tree.

#### <a id="c-__mt_destroy"></a>`__mt_destroy()`

```c
void __mt_destroy(struct maple_tree *mt)
```

Walk and free all nodes of a locked maple tree.

**Parameters**

- `struct maple_tree *mt`: The maple tree

**Note**

Does not handle locking.

#### <a id="c-mtree_destroy"></a>`mtree_destroy()`

```c
void mtree_destroy(struct maple_tree *mt)
```

Destroy a maple tree

**Parameters**

- `struct maple_tree *mt`: The maple tree

**Description**

Frees all resources used by the tree.  Handles locking.

#### <a id="c-mt_find"></a>`mt_find()`

```c
void * mt_find(struct maple_tree *mt, unsigned long *index, unsigned long max)
```

Search from the start up until an entry is found.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long *index`: Pointer which contains the start location of the search
- `unsigned long max`: The maximum value of the search range

**Description**

Takes RCU read lock internally to protect the search, which does not
protect the returned pointer after dropping RCU read lock.
See also: Documentation/core-api/maple_tree.rst

In case that an entry is found **index** is updated to point to the next
possible entry independent whether the found entry is occupying a
single index or a range if indices.

**Return**

The entry at or after the **index** or `NULL`

#### <a id="c-mt_find_after"></a>`mt_find_after()`

```c
void * mt_find_after(struct maple_tree *mt, unsigned long *index, unsigned long max)
```

Search from the start up until an entry is found.

**Parameters**

- `struct maple_tree *mt`: The maple tree
- `unsigned long *index`: Pointer which contains the start location of the search
- `unsigned long max`: The maximum value to check

**Description**

Same as [`mt_find()`](#c-mt_find) except that it checks **index** for 0 before
searching. If **index** == 0, the search is aborted. This covers a wrap
around of **index** to 0 in an iterator loop.

**Return**

The entry at or after the **index** or `NULL`

---

# Memory Allocation Guide

_Peios Kernel / Internals / Core APIs_

> Linux provides a variety of APIs for memory allocation. You can allocate small chunks using kmalloc or kmem_cache_alloc families, large virtually contiguous areas using vmalloc and its derivatives, or you can directly request pages from…

<a id="rst-memory-allocation-guide"></a>
<a id="rst-memory-allocation"></a>

Linux provides a variety of APIs for memory allocation. You can allocate small chunks using `kmalloc` or `kmem_cache_alloc` families, large virtually contiguous areas using `vmalloc` and its derivatives, or you can directly request pages from the page allocator with `alloc_pages`. It is also possible to use more specialized allocators, for instance `cma_alloc` or `zs_malloc`.

Most of the memory allocation APIs use GFP flags to express how that memory should be allocated. The GFP acronym stands for "get free pages", the underlying memory allocation function.

Diversity of the allocation APIs combined with the numerous GFP flags makes the question "How should I allocate memory?" not that easy to answer, although very likely you should use



```text
kzalloc(<size>, GFP_KERNEL);
```

Of course there are cases when other allocation APIs and different GFP flags must be used.

<a id="rst-get-free-page-flags"></a>

## Get Free Page flags

The GFP flags control the allocators behavior. They tell what memory zones can be used, how hard the allocator should try to find free memory, whether the memory can be accessed by the userspace etc. The [Documentation/core-api/mm-api.rst](</kernel/internals/core-api/mm-api.md#rst-mm-api-gfp-flags>) provides reference documentation for the GFP flags and their combinations and here we briefly outline their recommended usage:

> - Most of the time `GFP_KERNEL` is what you need. Memory for the kernel data structures, DMAable memory, inode cache, all these and many other allocations types can use `GFP_KERNEL`. Note, that using `GFP_KERNEL` implies `GFP_RECLAIM`, which means that direct reclaim may be triggered under memory pressure; the calling context must be allowed to sleep.
>
> - If the allocation is performed from an atomic context, e.g interrupt handler, use `GFP_NOWAIT`. This flag prevents direct reclaim and IO or filesystem operations. Consequently, under memory pressure `GFP_NOWAIT` allocation is likely to fail. Users of this flag need to provide a suitable fallback to cope with such failures where appropriate.
>
> - If you think that accessing memory reserves is justified and the kernel will be stressed unless allocation succeeds, you may use `GFP_ATOMIC`.
>
> - Untrusted allocations triggered from userspace should be a subject of kmem accounting and must have `__GFP_ACCOUNT` bit set. There is the handy `GFP_KERNEL_ACCOUNT` shortcut for `GFP_KERNEL` allocations that should be accounted.
>
> - Userspace allocations should use either of the `GFP_USER`, `GFP_HIGHUSER` or `GFP_HIGHUSER_MOVABLE` flags. The longer the flag name the less restrictive it is.
>
>   `GFP_HIGHUSER_MOVABLE` does not require that allocated memory will be directly accessible by the kernel and implies that the data is movable.
>
>   `GFP_HIGHUSER` means that the allocated memory is not movable, but it is not required to be directly accessible by the kernel. An example may be a hardware allocation that maps data directly into userspace but has no addressing limitations.
>
>   `GFP_USER` means that the allocated memory is not movable and it must be directly accessible by the kernel.

You may notice that quite a few allocations in the existing code specify `GFP_NOIO` or `GFP_NOFS`. Historically, they were used to prevent recursion deadlocks caused by direct memory reclaim calling back into the FS or IO paths and blocking on already held resources. Since 4.12 the preferred way to address this issue is to use new scope APIs described in [Documentation/core-api/gfp_mask-from-fs-io.rst](</kernel/internals/core-api/gfp-mask-from-fs-io.md#rst-gfp-mask-from-fs-io>).

Other legacy GFP flags are `GFP_DMA` and `GFP_DMA32`. They are used to ensure that the allocated memory is accessible by hardware with limited addressing capabilities. So unless you are writing a driver for a device with such restrictions, avoid using these flags. And even with hardware with restrictions it is preferable to use `dma_alloc*` APIs.

<a id="rst-gfp-flags-and-reclaim-behavior"></a>

### GFP flags and reclaim behavior

Memory allocations may trigger direct or background reclaim and it is useful to understand how hard the page allocator will try to satisfy that or another request.

> - `GFP_KERNEL & ~__GFP_RECLAIM` - optimistic allocation without \_any\_ attempt to free memory at all. The most light weight mode which even doesn't kick the background reclaim. Should be used carefully because it might deplete the memory and the next user might hit the more aggressive reclaim.
>
> - `GFP_KERNEL & ~__GFP_DIRECT_RECLAIM` (or `GFP_NOWAIT`)- optimistic allocation without any attempt to free memory from the current context but can wake kswapd to reclaim memory if the zone is below the low watermark. Can be used from either atomic contexts or when the request is a performance optimization and there is another fallback for a slow path.
>
> - `(GFP_KERNEL|__GFP_HIGH) & ~__GFP_DIRECT_RECLAIM` (aka `GFP_ATOMIC`) - non sleeping allocation with an expensive fallback so it can access some portion of memory reserves. Usually used from interrupt/bottom-half context with an expensive slow path fallback.
>
> - `GFP_KERNEL` - both background and direct reclaim are allowed and the **default** page allocator behavior is used. That means that not costly allocation requests are basically no-fail but there is no guarantee of that behavior so failures have to be checked properly by callers (e.g. OOM killer victim is allowed to fail currently).
>
> - `GFP_KERNEL | __GFP_NORETRY` - overrides the default allocator behavior and all allocation requests fail early rather than cause disruptive reclaim (one round of reclaim in this implementation). The OOM killer is not invoked.
>
> - `GFP_KERNEL | __GFP_RETRY_MAYFAIL` - overrides the default allocator behavior and all allocation requests try really hard. The request will fail if the reclaim cannot make any progress. The OOM killer won't be triggered.
>
> - `GFP_KERNEL | __GFP_NOFAIL` - overrides the default allocator behavior and all allocation requests will loop endlessly until they succeed. This might be really dangerous especially for larger orders.

<a id="rst-selecting-memory-allocator"></a>

## Selecting memory allocator

The most straightforward way to allocate memory is to use a function from the kmalloc() family. And, to be on the safe side it's best to use routines that set memory to zero, like kzalloc(). If you need to allocate memory for an array, there are kmalloc_array() and kcalloc() helpers. The helpers struct_size(), array_size() and array3_size() can be used to safely calculate object sizes without overflowing.

The maximal size of a chunk that can be allocated with `kmalloc` is limited. The actual limit depends on the hardware and the kernel configuration, but it is a good practice to use `kmalloc` for objects smaller than page size.

The address of a chunk allocated with `kmalloc` is aligned to at least ARCH_KMALLOC_MINALIGN bytes. For sizes which are a power of two, the alignment is also guaranteed to be at least the respective size. For other sizes, the alignment is guaranteed to be at least the largest power-of-two divisor of the size.

Chunks allocated with kmalloc() can be resized with krealloc(). Similarly to kmalloc_array(): a helper for resizing arrays is provided in the form of krealloc_array().

For large allocations you can use vmalloc() and vzalloc(), or directly request pages from the page allocator. The memory allocated by `vmalloc` and related functions is not physically contiguous.

If you are not sure whether the allocation size is too large for `kmalloc`, it is possible to use kvmalloc() and its derivatives. It will try to allocate memory with `kmalloc` and if the allocation fails it will be retried with `vmalloc`. There are restrictions on which GFP flags can be used with `kvmalloc`; please see kvmalloc_node() reference documentation. Note that `kvmalloc` may return memory that is not physically contiguous.

If you need to allocate many identical objects you can use the slab cache allocator. The cache should be set up with kmem_cache_create() or kmem_cache_create_usercopy() before it can be used. The second function should be used if a part of the cache might be copied to the userspace. After the cache is created kmem_cache_alloc() and its convenience wrappers can allocate memory from that cache.

When the allocated memory is no longer needed it must be freed.

Objects allocated by `kmalloc` can be freed by `kfree` or `kvfree`. Objects allocated by `kmem_cache_alloc` can be freed with `kmem_cache_free`, `kfree` or `kvfree`, where the latter two might be more convenient thanks to not needing the kmem_cache pointer.

The same rules apply to \_bulk and \_rcu flavors of freeing functions.

Memory allocated by `vmalloc` can be freed with `vfree` or `kvfree`. Memory allocated by `kvmalloc` can be freed with `kvfree`. Caches created by `kmem_cache_create` should be freed with `kmem_cache_destroy` only after freeing all the allocated objects first.

---

# Memory hotplug

_Peios Kernel / Internals / Core APIs_

> Hotplugging events are sent to a notification queue.

<a id="rst-memory-hotplug-1"></a>
<a id="rst-memory-hotplug"></a>

<a id="rst-memory-hotplug-event-notifier"></a>

## Memory hotplug event notifier

Hotplugging events are sent to a notification queue.

<a id="rst-memory-notifier"></a>

### Memory notifier

There are six types of notification defined in `include/linux/memory.h`:

- **MEM_GOING_ONLINE**

  Generated before new memory becomes available in order to be able to prepare subsystems to handle memory. The page allocator is still unable to allocate from the new memory.

- **MEM_CANCEL_ONLINE**

  Generated if MEM_GOING_ONLINE fails.

- **MEM_ONLINE**

  Generated when memory has successfully brought online. The callback may allocate pages from the new memory.

- **MEM_GOING_OFFLINE**

  Generated to begin the process of offlining memory. Allocations are no longer possible from the memory but some of the memory to be offlined is still in use. The callback can be used to free memory known to a subsystem from the indicated memory block.

- **MEM_CANCEL_OFFLINE**

  Generated if MEM_GOING_OFFLINE fails. Memory is available again from the memory block that we attempted to offline.

- **MEM_OFFLINE**

  Generated after offlining memory is complete.

A callback routine can be registered by calling:



```text
hotplug_memory_notifier(callback_func, priority)
```

Callback functions with higher values of priority are called before callback functions with lower values.

A callback function must have the following prototype:



```text
int callback_func(
  struct notifier_block *self, unsigned long action, void *arg);
```

The first argument of the callback function (self) is a pointer to the block of the notifier chain that points to the callback function itself. The second argument (action) is one of the event types described above. The third argument (arg) passes a pointer of struct memory_notify:



```text
struct memory_notify {
        unsigned long start_pfn;
        unsigned long nr_pages;
}
```

- start_pfn is start_pfn of online/offline memory.

- nr_pages is \# of pages of online/offline memory.

It is possible to get notified for MEM_CANCEL_ONLINE without having been notified for MEM_GOING_ONLINE, and the same applies to MEM_CANCEL_OFFLINE and MEM_GOING_OFFLINE. This can happen when a consumer fails, meaning we break the callchain and we stop calling the remaining consumers of the notifier. It is then important that users of memory_notify make no assumptions and get prepared to handle such cases.

The callback routine shall return one of the values NOTIFY_DONE, NOTIFY_OK, NOTIFY_BAD, NOTIFY_STOP defined in `include/linux/notifier.h`

NOTIFY_DONE and NOTIFY_OK have no effect on the further processing.

NOTIFY_BAD is used as response to the MEM_GOING_ONLINE, MEM_GOING_OFFLINE, MEM_ONLINE, or MEM_OFFLINE action to cancel hotplugging. It stops further processing of the notification queue.

NOTIFY_STOP stops further processing of the notification queue.

<a id="rst-numa-node-notifier"></a>

### Numa node notifier

There are six types of notification defined in `include/linux/node.h`:

- **NODE_ADDING_FIRST_MEMORY**

  Generated before memory becomes available to this node for the first time.

- **NODE_CANCEL_ADDING_FIRST_MEMORY**

  Generated if NODE_ADDING_FIRST_MEMORY fails.

- **NODE_ADDED_FIRST_MEMORY**

  Generated when memory has become available fo this node for the first time.

- **NODE_REMOVING_LAST_MEMORY**

  Generated when the last memory available to this node is about to be offlined.

- **NODE_CANCEL_REMOVING_LAST_MEMORY**

  Generated when NODE_CANCEL_REMOVING_LAST_MEMORY fails.

- **NODE_REMOVED_LAST_MEMORY**

  Generated when the last memory available to this node has been offlined.

A callback routine can be registered by calling:



```text
hotplug_node_notifier(callback_func, priority)
```

Callback functions with higher values of priority are called before callback functions with lower values.

A callback function must have the following prototype:



```text
int callback_func(

  struct notifier_block *self, unsigned long action, void *arg);
```

The first argument of the callback function (self) is a pointer to the block of the notifier chain that points to the callback function itself. The second argument (action) is one of the event types described above. The third argument (arg) passes a pointer of struct node_notify:



```text
struct node_notify {
        int nid;
}
```

- nid is the node we are adding or removing memory to.

It is possible to get notified for NODE_CANCEL_ADDING_FIRST_MEMORY without having been notified for NODE_ADDING_FIRST_MEMORY, and the same applies to NODE_CANCEL_REMOVING_LAST_MEMORY and NODE_REMOVING_LAST_MEMORY. This can happen when a consumer fails, meaning we break the callchain and we stop calling the remaining consumers of the notifier. It is then important that users of node_notify make no assumptions and get prepared to handle such cases.

The callback routine shall return one of the values NOTIFY_DONE, NOTIFY_OK, NOTIFY_BAD, NOTIFY_STOP defined in `include/linux/notifier.h`

NOTIFY_DONE and NOTIFY_OK have no effect on the further processing.

NOTIFY_BAD is used as response to the NODE_ADDING_FIRST_MEMORY, NODE_REMOVING_LAST_MEMORY, NODE_ADDED_FIRST_MEMORY or NODE_REMOVED_LAST_MEMORY action to cancel hotplugging. It stops further processing of the notification queue.

NOTIFY_STOP stops further processing of the notification queue.

Please note that we should not fail for NODE_ADDED_FIRST_MEMORY / NODE_REMOVED_FIRST_MEMORY, as memory_hotplug code cannot rollback at that point anymore.

<a id="rst-locking-internals"></a>

## Locking Internals

When adding/removing memory that uses memory block devices (i.e. ordinary RAM), the device_hotplug_lock should be held to:

- synchronize against online/offline requests (e.g. via sysfs). This way, memory block devices can only be accessed (.online/.state attributes) by user space once memory has been fully added. And when removing memory, we know nobody is in critical sections.

- synchronize against CPU hotplug and similar (e.g. relevant for ACPI and PPC)

Especially, there is a possible lock inversion that is avoided using device_hotplug_lock when adding memory and user space tries to online that memory faster than expected:

- device_online() will first take the device_lock(), followed by mem_hotplug_lock

- add_memory_resource() will first take the mem_hotplug_lock, followed by the device_lock() (while creating the devices, during bus_add_device()).

As the device is visible to user space before taking the device_lock(), this can result in a lock inversion.

onlining/offlining of memory should be done via device_online()/ device_offline() - to make sure it is properly synchronized to actions via sysfs. Holding device_hotplug_lock is advised (to e.g. protect online_type)

When adding/removing/onlining/offlining memory or adding/removing heterogeneous/device memory, we should always hold the mem_hotplug_lock in write mode to serialise memory hotplug (e.g. access to global/zone variables).

In addition, mem_hotplug_lock (in contrast to device_hotplug_lock) in read mode allows for a quite efficient get_online_mems/put_online_mems implementation, so code accessing memory can protect from that memory vanishing.

---

# Min Heap API

_Peios Kernel / Internals / Core APIs_

> The Min Heap API provides a set of functions and macros for managing min-heaps in the Linux kernel. A min-heap is a binary tree structure where the value of each node is less than or equal to the values of its children, ensuring that the…

<a id="rst-min-heap-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Kuan-Wei Chiu &lt;[visitorckw@gmail.com](<mailto:visitorckw@gmail.com>)&gt;

<a id="rst-introduction"></a>

## Introduction

The Min Heap API provides a set of functions and macros for managing min-heaps in the Linux kernel. A min-heap is a binary tree structure where the value of each node is less than or equal to the values of its children, ensuring that the smallest element is always at the root.

This document provides a guide to the Min Heap API, detailing how to define and use min-heaps. Users should not directly call functions with **\__min_heap\_\*()** prefixes, but should instead use the provided macro wrappers.

In addition to the standard version of the functions, the API also includes a set of inline versions for performance-critical scenarios. These inline functions have the same names as their non-inline counterparts but include an **\_inline** suffix. For example, **\__min_heap_init_inline** and its corresponding macro wrapper **min_heap_init_inline**. The inline versions allow custom comparison and swap functions to be called directly, rather than through indirect function calls. This can significantly reduce overhead, especially when CONFIG_MITIGATION_RETPOLINE is enabled, as indirect function calls become more expensive. As with the non-inline versions, it is important to use the macro wrappers for inline functions instead of directly calling the functions themselves.

<a id="rst-data-structures"></a>

## Data Structures

<a id="rst-min-heap-definition"></a>

### Min-Heap Definition

The core data structure for representing a min-heap is defined using the **MIN_HEAP_PREALLOCATED** and **DEFINE_MIN_HEAP** macros. These macros allow you to define a min-heap with a preallocated buffer or dynamically allocated memory.

Example:



```c
#define MIN_HEAP_PREALLOCATED(_type, _name, _nr)
struct _name {
    size_t nr;         /* Number of elements in the heap */
    size_t size;       /* Maximum number of elements that can be held */
    _type *data;    /* Pointer to the heap data */
    _type preallocated[_nr];  /* Static preallocated array */
}

#define DEFINE_MIN_HEAP(_type, _name) MIN_HEAP_PREALLOCATED(_type, _name, 0)
```

A typical heap structure will include a counter for the number of elements (`nr`), the maximum capacity of the heap (`size`), and a pointer to an array of elements (`data`). Optionally, you can specify a static array for preallocated heap storage using **MIN_HEAP_PREALLOCATED**.

<a id="rst-min-heap-callbacks"></a>

### Min Heap Callbacks

The **struct min_heap_callbacks** provides customization options for ordering elements in the heap and swapping them. It contains two function pointers:



```c
struct min_heap_callbacks {
    bool (*less)(const void *lhs, const void *rhs, void *args);
    void (*swp)(void *lhs, void *rhs, void *args);
};
```

- **less** is the comparison function used to establish the order of elements.

- **swp** is a function for swapping elements in the heap. If swp is set to NULL, the default swap function will be used, which swaps the elements based on their size

<a id="rst-macro-wrappers"></a>

## Macro Wrappers

The following macro wrappers are provided for interacting with the heap in a user-friendly manner. Each macro corresponds to a function that operates on the heap, and they abstract away direct calls to internal functions.

Each macro accepts various parameters that are detailed below.

<a id="rst-heap-initialization"></a>

### Heap Initialization



```c
min_heap_init(heap, data, size);
```

- **heap**: A pointer to the min-heap structure to be initialized.

- **data**: A pointer to the buffer where the heap elements will be stored. If `NULL`, the preallocated buffer within the heap structure will be used.

- **size**: The maximum number of elements the heap can hold.

This macro initializes the heap, setting its initial state. If `data` is `NULL`, the preallocated memory inside the heap structure will be used for storage. Otherwise, the user-provided buffer is used. The operation is **O(1)**.

**Inline Version:** min_heap_init_inline(heap, data, size)

<a id="rst-accessing-the-top-element"></a>

### Accessing the Top Element



```c
element = min_heap_peek(heap);
```

- **heap**: A pointer to the min-heap from which to retrieve the smallest element.

This macro returns a pointer to the smallest element (the root) of the heap, or `NULL` if the heap is empty. The operation is **O(1)**.

**Inline Version:** min_heap_peek_inline(heap)

<a id="rst-heap-insertion"></a>

### Heap Insertion



```c
success = min_heap_push(heap, element, callbacks, args);
```

- **heap**: A pointer to the min-heap into which the element should be inserted.

- **element**: A pointer to the element to be inserted into the heap.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro inserts an element into the heap. It returns `true` if the insertion was successful and `false` if the heap is full. The operation is **O(log n)**.

**Inline Version:** min_heap_push_inline(heap, element, callbacks, args)

<a id="rst-heap-removal"></a>

### Heap Removal



```c
success = min_heap_pop(heap, callbacks, args);
```

- **heap**: A pointer to the min-heap from which to remove the smallest element.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro removes the smallest element (the root) from the heap. It returns `true` if the element was successfully removed, or `false` if the heap is empty. The operation is **O(log n)**.

**Inline Version:** min_heap_pop_inline(heap, callbacks, args)

<a id="rst-heap-maintenance"></a>

### Heap Maintenance

You can use the following macros to maintain the heap's structure:



```c
min_heap_sift_down(heap, pos, callbacks, args);
```

- **heap**: A pointer to the min-heap.

- **pos**: The index from which to start sifting down.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro restores the heap property by moving the element at the specified index (`pos`) down the heap until it is in the correct position. The operation is **O(log n)**.

**Inline Version:** min_heap_sift_down_inline(heap, pos, callbacks, args)



```c
min_heap_sift_up(heap, idx, callbacks, args);
```

- **heap**: A pointer to the min-heap.

- **idx**: The index of the element to sift up.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro restores the heap property by moving the element at the specified index (`idx`) up the heap. The operation is **O(log n)**.

**Inline Version:** min_heap_sift_up_inline(heap, idx, callbacks, args)



```c
min_heapify_all(heap, callbacks, args);
```

- **heap**: A pointer to the min-heap.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro ensures that the entire heap satisfies the heap property. It is called when the heap is built from scratch or after many modifications. The operation is **O(n)**.

**Inline Version:** min_heapify_all_inline(heap, callbacks, args)

<a id="rst-removing-specific-elements"></a>

### Removing Specific Elements



```c
success = min_heap_del(heap, idx, callbacks, args);
```

- **heap**: A pointer to the min-heap.

- **idx**: The index of the element to delete.

- **callbacks**: A pointer to a `struct min_heap_callbacks` providing the `less` and `swp` functions.

- **args**: Optional arguments passed to the `less` and `swp` functions.

This macro removes an element at the specified index (`idx`) from the heap and restores the heap property. The operation is **O(log n)**.

**Inline Version:** min_heap_del_inline(heap, idx, callbacks, args)

<a id="rst-other-utilities"></a>

## Other Utilities

- **min_heap_full(heap)**: Checks whether the heap is full. Complexity: **O(1)**.



```c
bool full = min_heap_full(heap);
```

- `heap`: A pointer to the min-heap to check.

This macro returns `true` if the heap is full, otherwise `false`.

**Inline Version:** min_heap_full_inline(heap)

- **min_heap_empty(heap)**: Checks whether the heap is empty. Complexity: **O(1)**.



```c
bool empty = min_heap_empty(heap);
```

- `heap`: A pointer to the min-heap to check.

This macro returns `true` if the heap is empty, otherwise `false`.

**Inline Version:** min_heap_empty_inline(heap)

<a id="rst-example-usage"></a>

## Example Usage

An example usage of the min-heap API would involve defining a heap structure, initializing it, and inserting and removing elements as needed.



```c
#include <linux/min_heap.h>

int my_less_function(const void *lhs, const void *rhs, void *args) {
    return (*(int *)lhs < *(int *)rhs);
}

struct min_heap_callbacks heap_cb = {
    .less = my_less_function,    /* Comparison function for heap order */
    .swp  = NULL,                /* Use default swap function */
};

void example_usage(void) {
    /* Pre-populate the buffer with elements */
    int buffer[5] = {5, 2, 8, 1, 3};
    /* Declare a min-heap */
    DEFINE_MIN_HEAP(int, my_heap);

    /* Initialize the heap with preallocated buffer and size */
    min_heap_init(&my_heap, buffer, 5);

    /* Build the heap using min_heapify_all */
    my_heap.nr = 5;  /* Set the number of elements in the heap */
    min_heapify_all(&my_heap, &heap_cb, NULL);

    /* Peek at the top element (should be 1 in this case) */
    int *top = min_heap_peek(&my_heap);
    pr_info("Top element: %d\n", *top);

    /* Pop the top element (1) and get the new top (2) */
    min_heap_pop(&my_heap, &heap_cb, NULL);
    top = min_heap_peek(&my_heap);
    pr_info("New top element: %d\n", *top);

    /* Insert a new element (0) and recheck the top */
    int new_element = 0;
    min_heap_push(&my_heap, &new_element, &heap_cb, NULL);
    top = min_heap_peek(&my_heap);
    pr_info("Top element after insertion: %d\n", *top);
}
```

---

# Memory Management APIs

_Peios Kernel / Internals / Core APIs_

> Reference for Memory Management APIs.

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-memory-management-apis"></a>

<a id="rst-user-space-memory-access"></a>

## User Space Memory Access


#### <a id="c-get_user"></a>`get_user()`

```c
get_user(x, ptr)
```

Get a simple variable from user space.

**Parameters**

- `x`: Variable to store result.
- `ptr`: Source address, in user space.

**Context**

User context only. This function may sleep if pagefaults are
enabled.

**Description**

This macro copies a single simple variable from user space to kernel
space.  It supports simple types like char and int, but not larger
data types like structures or arrays.

**ptr** must have pointer-to-simple-variable type, and the result of
dereferencing **ptr** must be assignable to **x** without a cast.

**Return**

zero on success, or -EFAULT on error.
On error, the variable **x** is set to zero.

#### <a id="c-__get_user"></a>`__get_user()`

```c
__get_user(x, ptr)
```

Get a simple variable from user space, with less checking.

**Parameters**

- `x`: Variable to store result.
- `ptr`: Source address, in user space.

**Context**

User context only. This function may sleep if pagefaults are
enabled.

**Description**

This macro copies a single simple variable from user space to kernel
space.  It supports simple types like char and int, but not larger
data types like structures or arrays.

**ptr** must have pointer-to-simple-variable type, and the result of
dereferencing **ptr** must be assignable to **x** without a cast.

Caller must check the pointer with `access_ok()` before calling this
function.

**Return**

zero on success, or -EFAULT on error.
On error, the variable **x** is set to zero.

#### <a id="c-put_user"></a>`put_user()`

```c
put_user(x, ptr)
```

Write a simple value into user space.

**Parameters**

- `x`: Value to copy to user space.
- `ptr`: Destination address, in user space.

**Context**

User context only. This function may sleep if pagefaults are
enabled.

**Description**

This macro copies a single simple value from kernel space to user
space.  It supports simple types like char and int, but not larger
data types like structures or arrays.

**ptr** must have pointer-to-simple-variable type, and **x** must be assignable
to the result of dereferencing **ptr**.

**Return**

zero on success, or -EFAULT on error.

#### <a id="c-__put_user"></a>`__put_user()`

```c
__put_user(x, ptr)
```

Write a simple value into user space, with less checking.

**Parameters**

- `x`: Value to copy to user space.
- `ptr`: Destination address, in user space.

**Context**

User context only. This function may sleep if pagefaults are
enabled.

**Description**

This macro copies a single simple value from kernel space to user
space.  It supports simple types like char and int, but not larger
data types like structures or arrays.

**ptr** must have pointer-to-simple-variable type, and **x** must be assignable
to the result of dereferencing **ptr**.

Caller must check the pointer with `access_ok()` before calling this
function.

**Return**

zero on success, or -EFAULT on error.



#### <a id="c-clear_user"></a>`clear_user()`

```c
unsigned long clear_user(void __user *to, unsigned long n)
```

Zero a block of memory in user space.

**Parameters**

- `void __user *to`: Destination address, in user space.
- `unsigned long n`: Number of bytes to zero.

**Description**

Zero a block of memory in user space.

**Return**

number of bytes that could not be cleared.
On success, this will be zero.

#### <a id="c-__clear_user"></a>`__clear_user()`

```c
unsigned long __clear_user(void __user *to, unsigned long n)
```

Zero a block of memory in user space, with less checking.

**Parameters**

- `void __user *to`: Destination address, in user space.
- `unsigned long n`: Number of bytes to zero.

**Description**

Zero a block of memory in user space.  Caller must check
the specified block with `access_ok()` before calling this function.

**Return**

number of bytes that could not be cleared.
On success, this will be zero.



#### <a id="c-get_user_pages_fast"></a>`get_user_pages_fast()`

```c
int get_user_pages_fast(unsigned long start, int nr_pages, unsigned int gup_flags, struct page **pages)
```

pin user pages in memory

**Parameters**

- `unsigned long start`: starting user address
- `int nr_pages`: number of pages from start to pin
- `unsigned int gup_flags`: flags modifying pin behaviour
- `struct page **pages`: array that receives pointers to the pages pinned.
  Should be at least nr_pages long.

**Description**

Attempt to pin user pages in memory without taking mm->mmap_lock.
If not successful, it will fall back to taking the lock and
calling `get_user_pages()`.

Returns number of pages pinned. This may be fewer than the number requested.
If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
-errno.


<a id="rst-memory-allocation-controls"></a>
<a id="rst-mm-api-gfp-flags"></a>

## Memory Allocation Controls


**Page mobility and placement hints**

These flags provide hints about how mobile the page is. Pages with similar
mobility are placed within the same pageblocks to minimise problems due
to external fragmentation.

`__GFP_MOVABLE` (also a zone modifier) indicates that the page can be
moved by page migration during memory compaction or can be reclaimed.

`__GFP_RECLAIMABLE` is used for slab allocations that specify
SLAB_RECLAIM_ACCOUNT and whose pages can be freed via shrinkers.

`__GFP_WRITE` indicates the caller intends to dirty the page. Where possible,
these pages will be spread between local zones to avoid all the dirty
pages being in one zone (fair zone allocation policy).

`__GFP_HARDWALL` enforces the cpuset memory allocation policy.

`__GFP_THISNODE` forces the allocation to be satisfied from the requested
node with no fallbacks or placement policy enforcements.

`__GFP_ACCOUNT` causes the allocation to be accounted to kmemcg.

`__GFP_NO_OBJ_EXT` causes slab allocation to have no object extension.
`mark_obj_codetag_empty()` should be called upon freeing for objects allocated
with this flag to indicate that their NULL tags are expected and normal.



**Watermark modifiers -- controls access to emergency reserves**

`__GFP_HIGH` indicates that the caller is high-priority and that granting
the request is necessary before the system can make forward progress.
For example creating an IO context to clean pages and requests
from atomic context.

`__GFP_MEMALLOC` allows access to all memory. This should only be used when
the caller guarantees the allocation will allow more memory to be freed
very shortly e.g. process exiting or swapping. Users either should
be the MM or co-ordinating closely with the VM (e.g. swap over NFS).
Users of this flag have to be extremely careful to not deplete the reserve
completely and implement a throttling mechanism which controls the
consumption of the reserve based on the amount of freed memory.
Usage of a pre-allocated pool (e.g. mempool) should be always considered
before using this flag.

`__GFP_NOMEMALLOC` is used to explicitly forbid access to emergency reserves.
This takes precedence over the `__GFP_MEMALLOC` flag if both are set.



**Reclaim modifiers**

Please note that all the following flags are only applicable to sleepable
allocations (e.g. `GFP_NOWAIT` and `GFP_ATOMIC` will ignore them).

`__GFP_IO` can start physical IO.

`__GFP_FS` can call down to the low-level FS. Clearing the flag avoids the
allocator recursing into the filesystem which might already be holding
locks.

`__GFP_DIRECT_RECLAIM` indicates that the caller may enter direct reclaim.
This flag can be cleared to avoid unnecessary delays when a fallback
option is available.

`__GFP_KSWAPD_RECLAIM` indicates that the caller wants to wake kswapd when
the low watermark is reached and have it reclaim pages until the high
watermark is reached. A caller may wish to clear this flag when fallback
options are available and the reclaim is likely to disrupt the system. The
canonical example is THP allocation where a fallback is cheap but
reclaim/compaction may cause indirect stalls.

`__GFP_RECLAIM` is shorthand to allow/forbid both direct and kswapd reclaim.

The default allocator behavior depends on the request size. We have a concept
of so-called costly allocations (with order > `PAGE_ALLOC_COSTLY_ORDER`).
!costly allocations are too essential to fail so they are implicitly
non-failing by default (with some exceptions like OOM victims might fail so
the caller still has to check for failures) while costly requests try to be
not disruptive and back off even without invoking the OOM killer.
The following three modifiers might be used to override some of these
implicit rules. Please note that all of them must be used along with
`__GFP_DIRECT_RECLAIM` flag.

`__GFP_NORETRY`: The VM implementation will try only very lightweight
memory direct reclaim to get some memory under memory pressure (thus
it can sleep). It will avoid disruptive actions like OOM killer. The
caller must handle the failure which is quite likely to happen under
heavy memory pressure. The flag is suitable when failure can easily be
handled at small cost, such as reduced throughput.

`__GFP_RETRY_MAYFAIL`: The VM implementation will retry memory reclaim
procedures that have previously failed if there is some indication
that progress has been made elsewhere.  It can wait for other
tasks to attempt high-level approaches to freeing memory such as
compaction (which removes fragmentation) and page-out.
There is still a definite limit to the number of retries, but it is
a larger limit than with `__GFP_NORETRY`.
Allocations with this flag may fail, but only when there is
genuinely little unused memory. While these allocations do not
directly trigger the OOM killer, their failure indicates that
the system is likely to need to use the OOM killer soon.  The
caller must handle failure, but can reasonably do so by failing
a higher-level request, or completing it only in a much less
efficient manner.
If the allocation does fail, and the caller is in a position to
free some non-essential memory, doing so could benefit the system
as a whole.

`__GFP_NOFAIL`: The VM implementation _must_ retry infinitely: the caller
cannot handle allocation failures. The allocation could block
indefinitely but will never return with failure. Testing for
failure is pointless.
It _must_ be blockable and used together with __GFP_DIRECT_RECLAIM.
It should _never_ be used in non-sleepable contexts.
New users should be evaluated carefully (and the flag should be
used only when there is no reasonable failure policy) but it is
definitely preferable to use the flag rather than opencode endless
loop around allocator.
Allocating pages from the buddy with __GFP_NOFAIL and order > 1 is
not supported. Please consider using `kvmalloc()` instead.



**Useful GFP flag combinations**

Useful GFP flag combinations that are commonly used. It is recommended
that subsystems start with one of these combinations and then set/clear
`__GFP_FOO` flags as necessary.

`GFP_ATOMIC` users can not sleep and need the allocation to succeed. A lower
watermark is applied to allow access to "atomic reserves".
The current implementation doesn't support NMI, nor contexts that disable
preemption under PREEMPT_RT. This includes `raw_spin_lock()` and plain
`preempt_disable()` - see "Memory allocation" in
Documentation/core-api/real-time/differences.rst for more info.

`GFP_KERNEL` is typical for kernel-internal allocations. The caller requires
`ZONE_NORMAL` or a lower zone for direct access but can direct reclaim.

`GFP_KERNEL_ACCOUNT` is the same as GFP_KERNEL, except the allocation is
accounted to kmemcg.

`GFP_NOWAIT` is for kernel allocations that should not stall for direct
reclaim, start physical IO or use any filesystem callback.  It is very
likely to fail to allocate memory, even for very small allocations.
The same restrictions on calling contexts apply as for `GFP_ATOMIC`.

`GFP_NOIO` will use direct reclaim to discard clean pages or slab pages
that do not require the starting of any physical IO.
Please try to avoid using this flag directly and instead use
memalloc_noio_{save,restore} to mark the whole scope which cannot
perform any IO with a short explanation why. All allocation requests
will inherit GFP_NOIO implicitly.

`GFP_NOFS` will use direct reclaim but will not use any filesystem interfaces.
Please try to avoid using this flag directly and instead use
memalloc_nofs_{save,restore} to mark the whole scope which cannot/shouldn't
recurse into the FS layer with a short explanation why. All allocation
requests will inherit GFP_NOFS implicitly.

`GFP_USER` is for userspace allocations that also need to be directly
accessibly by the kernel or hardware. It is typically used by hardware
for buffers that are mapped to userspace (e.g. graphics) that hardware
still must DMA to. cpuset limits are enforced for these allocations.

`GFP_DMA` exists for historical reasons and should be avoided where possible.
The flags indicates that the caller requires that the lowest zone be
used (`ZONE_DMA` or 16M on x86-64). Ideally, this would be removed but
it would require careful auditing as some users really require it and
others use the flag to avoid lowmem reserves in `ZONE_DMA` and treat the
lowest zone as a type of emergency reserve.

`GFP_DMA32` is similar to `GFP_DMA` except that the caller requires a 32-bit
address. Note that kmalloc(..., GFP_DMA32) does not return DMA32 memory
because the DMA32 kmalloc cache array is not implemented.
(Reason: there is no such user in kernel).

`GFP_HIGHUSER` is for userspace allocations that may be mapped to userspace,
do not need to be directly accessible by the kernel but that cannot
move once in use. An example may be a hardware allocation that maps
data directly into userspace but has no addressing limitations.

`GFP_HIGHUSER_MOVABLE` is for userspace allocations that the kernel does not
need direct access to but can use [`kmap()`](/kernel/internals/mm/highmem.md#c-kmap) when access is required. They
are expected to be movable via page reclaim or page migration. Typically,
pages on the LRU would also be allocated with `GFP_HIGHUSER_MOVABLE`.

`GFP_TRANSHUGE` and `GFP_TRANSHUGE_LIGHT` are used for THP allocations. They
are compound allocations that will generally fail quickly if memory is not
available and will not wake kswapd/kcompactd on failure. The _LIGHT
version does not attempt reclaim/compaction at all and is by default used
in page fault path, while the non-light is used by khugepaged.


<a id="rst-the-slab-cache"></a>

## The Slab Cache


#### <a id="c-SLAB_HWCACHE_ALIGN"></a>`SLAB_HWCACHE_ALIGN`

```c
SLAB_HWCACHE_ALIGN
```

Align objects on cache line boundaries.

**Description**

Sufficiently large objects are aligned on cache line boundary. For object
size smaller than a half of cache line size, the alignment is on the half of
cache line size. In general, if object size is smaller than 1/2^n of cache
line size, the alignment is adjusted to 1/2^n.

If explicit alignment is also requested by the respective
[`struct kmem_cache_args`](#c-struct-kmem_cache_args) field, the greater of both is alignments is applied.

#### <a id="c-SLAB_TYPESAFE_BY_RCU"></a>`SLAB_TYPESAFE_BY_RCU`

```c
SLAB_TYPESAFE_BY_RCU
```

**WARNING** READ THIS!

**Description**

This delays freeing the SLAB page by a grace period, it does _NOT_
delay object freeing. This means that if you do [`kmem_cache_free()`](#c-kmem_cache_free)
that memory location is free to be reused at any time. Thus it may
be possible to see another object there in the same RCU grace period.

This feature only ensures the memory location backing the object
stays valid, the trick to using this is relying on an independent
object validation pass. Something like:

```text
begin:
 rcu_read_lock();
 obj = lockless_lookup(key);
 if (obj) {
   if (!try_get_ref(obj)) // might fail for free objects
     rcu_read_unlock();
     goto begin;

   if (obj->key != key) { // not the object we expected
     put_ref(obj);
     rcu_read_unlock();
     goto begin;
   }
 }
rcu_read_unlock();
```

This is useful if we need to approach a kernel structure obliquely,
from its address obtained without the usual locking. We can lock
the structure to stabilize it and check it's still at the given address,
only if we can be sure that the memory has not been meanwhile reused
for some other kind of object (which our subsystem's lock might corrupt).

rcu_read_lock before reading the address, then rcu_read_unlock after
taking the spinlock within the structure expected at that address.

Note that object identity check has to be done *after* acquiring a
reference, therefore user has to ensure proper ordering for loads.
Similarly, when initializing objects allocated with SLAB_TYPESAFE_BY_RCU,
the newly allocated object has to be fully initialized *before* its
refcount gets initialized and proper ordering for stores is required.
refcount_{add|inc}`_not_zero_acquire()` and [`refcount_set_release()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-refcount_set_release) are
designed with the proper fences required for reference counting objects
allocated with SLAB_TYPESAFE_BY_RCU.

Note that it is not possible to acquire a lock within a structure
allocated with SLAB_TYPESAFE_BY_RCU without first acquiring a reference
as described above.  The reason is that SLAB_TYPESAFE_BY_RCU pages
are not zeroed before being given to the slab, which means that any
locks must be initialized after each and every `kmem_struct_alloc()`.
Alternatively, make the ctor passed to [`kmem_cache_create()`](#c-kmem_cache_create) initialize
the locks at page-allocation time, as is done in `__i915_request_ctor()`,
`sighand_ctor()`, and `anon_vma_ctor()`.  Such a ctor permits readers
to safely acquire those ctor-initialized locks under [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock)
protection.

Note that SLAB_TYPESAFE_BY_RCU was originally named SLAB_DESTROY_BY_RCU.

#### <a id="c-SLAB_ACCOUNT"></a>`SLAB_ACCOUNT`

```c
SLAB_ACCOUNT
```

Account allocations to memcg.

**Description**

All object allocations from this cache will be memcg accounted, regardless of
__GFP_ACCOUNT being or not being passed to individual allocations.

#### <a id="c-SLAB_RECLAIM_ACCOUNT"></a>`SLAB_RECLAIM_ACCOUNT`

```c
SLAB_RECLAIM_ACCOUNT
```

Objects are reclaimable.

**Description**

Use this flag for caches that have an associated shrinker. As a result, slab
pages are allocated with __GFP_RECLAIMABLE, which affects grouping pages by
mobility, and are accounted in SReclaimable counter in /proc/meminfo

#### <a id="c-struct-kmem_cache_args"></a>`struct kmem_cache_args`

Less common arguments for [`kmem_cache_create()`](#c-kmem_cache_create)

**Definition**

```c
struct kmem_cache_args {
    unsigned int align;
    unsigned int useroffset;
    unsigned int usersize;
    unsigned int freeptr_offset;
    bool use_freeptr_offset;
    void (*ctor)(void *);
    unsigned int sheaf_capacity;
};
```

**Members**

- `align`: The required alignment for the objects.

  `0` means no specific alignment is requested.
- `useroffset`: Usercopy region offset.

  `0` is a valid offset, when **usersize** is non-`0`
- `usersize`: Usercopy region size.

  `0` means no usercopy region is specified.
- `freeptr_offset`: Custom offset for the free pointer
  in caches with [`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU) or **ctor**

  By default, [`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU) and **ctor** caches place the free
  pointer outside of the object. This might cause the object to grow
  in size. Cache creators that have a reason to avoid this can specify
  a custom free pointer offset in their data structure where the free
  pointer will be placed.

  For caches with [`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU), the caller must ensure that
  the free pointer does not overlay fields required to guard against
  object recycling (See [`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU) for details).

  For caches with **ctor**, the caller must ensure that the free pointer
  does not overlay fields initialized by the constructor.

  Currently, only caches with [`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU) or **ctor**
  may specify **freeptr_offset**.

  Using `0` as a value for **freeptr_offset** is valid. If **freeptr_offset**
  is specified, **use_freeptr_offset** must be set `true`.
- `use_freeptr_offset`: Whether a **freeptr_offset** is used.
- `ctor`: A constructor for the objects.

  The constructor is invoked for each object in a newly allocated slab
  page. It is the cache user's responsibility to free object in the
  same state as after calling the constructor, or deal appropriately
  with any differences between a freshly constructed and a reallocated
  object.

  `NULL` means no constructor.
- `sheaf_capacity`: Enable sheaves of given capacity for the cache.

  With a non-zero value, allocations from the cache go through caching
  arrays called sheaves. Each cpu has a main sheaf that's always
  present, and a spare sheaf that may be not present. When both become
  empty, there's an attempt to replace an empty sheaf with a full sheaf
  from the per-node barn.

  When no full sheaf is available, and gfp flags allow blocking, a
  sheaf is allocated and filled from slab(s) using bulk allocation.
  Otherwise the allocation falls back to the normal operation
  allocating a single object from a slab.

  Analogically when freeing and both percpu sheaves are full, the barn
  may replace it with an empty sheaf, unless it's over capacity. In
  that case a sheaf is bulk freed to slab pages.

  The sheaves do not enforce NUMA placement of objects, so allocations
  via [`kmem_cache_alloc_node()`](#c-kmem_cache_alloc_node) with a node specified other than
  NUMA_NO_NODE will bypass them.

  Bulk allocation and free operations also try to use the cpu sheaves
  and barn, but fallback to using slab pages directly.

  When slub_debug is enabled for the cache, the sheaf_capacity argument
  is ignored.

  `0` means no sheaves will be created.

**Description**

Any uninitialized fields of the structure are interpreted as unused. The
exception is **freeptr_offset** where `0` is a valid value, so
**use_freeptr_offset** must be also set to `true` in order to interpret the field
as used. For **useroffset** `0` is also valid, but only with non-`0`
**usersize**.

When `NULL` args is passed to [`kmem_cache_create()`](#c-kmem_cache_create), it is equivalent to all
fields unused.

#### <a id="c-kmem_cache_create_usercopy"></a>`kmem_cache_create_usercopy()`

```c
struct kmem_cache * kmem_cache_create_usercopy(const char *name, unsigned int size, unsigned int align, slab_flags_t flags, unsigned int useroffset, unsigned int usersize, void (*ctor)(void *))
```

Create a kmem cache with a region suitable for copying to userspace.

**Parameters**

- `const char *name`: A string which is used in /proc/slabinfo to identify this cache.
- `unsigned int size`: The size of objects to be created in this cache.
- `unsigned int align`: The required alignment for the objects.
- `slab_flags_t flags`: SLAB flags
- `unsigned int useroffset`: Usercopy region offset
- `unsigned int usersize`: Usercopy region size
- `void (*ctor)(void *)`: A constructor for the objects, or `NULL`.

**Description**

This is a legacy wrapper, new code should use either `KMEM_CACHE_USERCOPY()`
if whitelisting a single field is sufficient, or [`kmem_cache_create()`](#c-kmem_cache_create) with
the necessary parameters passed via the args parameter (see
[`struct kmem_cache_args`](#c-struct-kmem_cache_args))

**Return**

a pointer to the cache on success, NULL on failure.

#### <a id="c-kmem_cache_create"></a>`kmem_cache_create()`

```c
kmem_cache_create(__name, __object_size, __args, ...)
```

Create a kmem cache.

**Parameters**

- `__name`: A string which is used in /proc/slabinfo to identify this cache.
- `__object_size`: The size of objects to be created in this cache.
- `__args`: Optional arguments, see [`struct kmem_cache_args`](#c-struct-kmem_cache_args). Passing `NULL`
  means defaults will be used for all the arguments.
- `...`: variable arguments

**Description**

This is currently implemented as a macro using `_Generic()` to call
either the new variant of the function, or a legacy one.

The new variant has 4 parameters:
`kmem_cache_create(name, object_size, args, flags)`

See [`__kmem_cache_create_args()`](#c-__kmem_cache_create_args) which implements this.

The legacy variant has 5 parameters:
`kmem_cache_create(name, object_size, align, flags, ctor)`

The align and ctor parameters map to the respective fields of
[`struct kmem_cache_args`](#c-struct-kmem_cache_args)

**Context**

Cannot be called within a interrupt, but can be interrupted.

**Return**

a pointer to the cache on success, NULL on failure.

#### <a id="c-kmem_cache_alloc"></a>`kmem_cache_alloc()`

```c
void * kmem_cache_alloc(struct kmem_cache *cachep, gfp_t flags)
```

Allocate an object

**Parameters**

- `struct kmem_cache *cachep`: The cache to allocate from.
- `gfp_t flags`: See [`kmalloc()`](#c-kmalloc).

**Description**

Allocate an object from this cache.
See `kmem_cache_zalloc()` for a shortcut of adding __GFP_ZERO to flags.

**Return**

pointer to the new object or `NULL` in case of error

#### <a id="c-kmem_cache_charge"></a>`kmem_cache_charge()`

```c
bool kmem_cache_charge(void *objp, gfp_t gfpflags)
```

memcg charge an already allocated slab memory

**Parameters**

- `void *objp`: address of the slab object to memcg charge
- `gfp_t gfpflags`: describe the allocation context

**Description**

kmem_cache_charge allows charging a slab object to the current memcg,
primarily in cases where charging at allocation time might not be possible
because the target memcg is not known (i.e. softirq context)

The objp should be pointer returned by the slab allocator functions like
kmalloc (with __GFP_ACCOUNT in flags) or kmem_cache_alloc. The memcg charge
behavior can be controlled through gfpflags parameter, which affects how the
necessary internal metadata can be allocated. Including __GFP_NOFAIL denotes
that overcharging is requested instead of failure, but is not applied for the
internal metadata allocation.

There are several cases where it will return true even if the charging was
not done:
More specifically:

1. For !CONFIG_MEMCG or cgroup_disable=memory systems.
2. Already charged slab objects.
3. For slab objects from KMALLOC_NORMAL caches - allocated by [`kmalloc()`](#c-kmalloc)
   without __GFP_ACCOUNT
4. Allocating internal metadata has failed

**Return**

true if charge was successful otherwise false.

#### <a id="c-kmalloc"></a>`kmalloc()`

```c
void * kmalloc(size_t size, gfp_t flags)
```

allocate kernel memory

**Parameters**

- `size_t size`: how many bytes of memory are required.
- `gfp_t flags`: describe the allocation context

**Description**

kmalloc is the normal method of allocating memory
for objects smaller than page size in the kernel.

The allocated object address is aligned to at least ARCH_KMALLOC_MINALIGN
bytes. For **size** of power of two bytes, the alignment is also guaranteed
to be at least to the size. For other sizes, the alignment is guaranteed to
be at least the largest power-of-two divisor of **size**.

The **flags** argument may be one of the GFP flags defined at
include/linux/gfp_types.h and described at
Documentation/core-api/mm-api.rst

The recommended usage of the **flags** is described at
Documentation/core-api/memory-allocation.rst

Below is a brief outline of the most useful GFP flags

- `GFP_KERNEL`:
  Allocate normal kernel ram. May sleep.

- `GFP_NOWAIT`:
  Allocation will not sleep.

- `GFP_ATOMIC`:
  Allocation will not sleep.  May use emergency pools.

Also it is possible to set different flags by OR'ing
in one or more of the following additional **flags**:

- `__GFP_ZERO`:
  Zero the allocated memory before returning. Also see [`kzalloc()`](#c-kzalloc).

- `__GFP_HIGH`:
  This allocation has high priority and may use emergency pools.

- `__GFP_NOFAIL`:
  Indicate that this allocation is in no way allowed to fail
  (think twice before using).

- `__GFP_NORETRY`:
  If memory is not immediately available,
  then give up at once.

- `__GFP_NOWARN`:
  If allocation fails, don't issue any warnings.

- `__GFP_RETRY_MAYFAIL`:
  Try really hard to succeed the allocation but fail
  eventually.

#### <a id="c-__alloc_objs"></a>`__alloc_objs()`

```c
__alloc_objs(KMALLOC, GFP, TYPE, COUNT)
```

Allocate objects of a given type using

**Parameters**

- `KMALLOC`: which size-based kmalloc wrapper to allocate with.
- `GFP`: GFP flags for the allocation.
- `TYPE`: type to allocate space for.
- `COUNT`: how many **TYPE** objects to allocate.

**Return**

Newly allocated pointer to (first) **TYPE** of **COUNT**-many
allocated **TYPE** objects, or NULL on failure.

#### <a id="c-__alloc_flex"></a>`__alloc_flex()`

```c
__alloc_flex(KMALLOC, GFP, TYPE, FAM, COUNT)
```

Allocate an object that has a trailing flexible array

**Parameters**

- `KMALLOC`: kmalloc wrapper function to use for allocation.
- `GFP`: GFP flags for the allocation.
- `TYPE`: type of structure to allocate space for.
- `FAM`: The name of the flexible array member of **TYPE** structure.
- `COUNT`: how many **FAM** elements to allocate space for.

**Return**

Newly allocated pointer to **TYPE** with **COUNT**-many trailing
**FAM** elements, or NULL on failure or if **COUNT** cannot be represented
by the member of **TYPE** that counts the **FAM** elements (annotated via
`__counted_by()`).

#### <a id="c-kmalloc_obj"></a>`kmalloc_obj()`

```c
kmalloc_obj(VAR_OR_TYPE, ...)
```

Allocate a single instance of the given type

**Parameters**

- `VAR_OR_TYPE`: Variable or type to allocate.
- `...`: variable arguments

**Return**

newly allocated pointer to a **VAR_OR_TYPE** on success, or NULL
on failure.

#### <a id="c-kmalloc_objs"></a>`kmalloc_objs()`

```c
kmalloc_objs(VAR_OR_TYPE, COUNT, ...)
```

Allocate an array of the given type

**Parameters**

- `VAR_OR_TYPE`: Variable or type to allocate an array of.
- `COUNT`: How many elements in the array.
- `...`: variable arguments

**Return**

newly allocated pointer to array of **VAR_OR_TYPE** on success,
or NULL on failure.

#### <a id="c-kmalloc_flex"></a>`kmalloc_flex()`

```c
kmalloc_flex(VAR_OR_TYPE, FAM, COUNT, ...)
```

Allocate a single instance of the given flexible structure

**Parameters**

- `VAR_OR_TYPE`: Variable or type to allocate (with its flex array).
- `FAM`: The name of the flexible array member of the structure.
- `COUNT`: How many flexible array member elements are desired.
- `...`: variable arguments

**Return**

newly allocated pointer to **VAR_OR_TYPE** on success, NULL on
failure. If **FAM** has been annotated with `__counted_by()`, the allocation
will immediately fail if **COUNT** is larger than what the type of the
struct's counter variable can represent.

#### <a id="c-kmalloc_array"></a>`kmalloc_array()`

```c
void * kmalloc_array(size_t n, size_t size, gfp_t flags)
```

allocate memory for an array.

**Parameters**

- `size_t n`: number of elements.
- `size_t size`: element size.
- `gfp_t flags`: the type of memory to allocate (see kmalloc).

#### <a id="c-krealloc_array"></a>`krealloc_array()`

```c
void * krealloc_array(void *p, size_t new_n, size_t new_size, gfp_t flags)
```

reallocate memory for an array.

**Parameters**

- `void *p`: pointer to the memory chunk to reallocate
- `size_t new_n`: new number of elements to alloc
- `size_t new_size`: new size of a single member of the array
- `gfp_t flags`: the type of memory to allocate (see kmalloc)

**Description**

If __GFP_ZERO logic is requested, callers must ensure that, starting with the
initial memory allocation, every subsequent call to this API for the same
memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
__GFP_ZERO is not fully honored by this API.

See `krealloc_noprof()` for further details.

In any case, the contents of the object pointed to are preserved up to the
lesser of the new and old sizes.

#### <a id="c-kcalloc"></a>`kcalloc()`

```c
kcalloc(n, size, flags)
```

allocate memory for an array. The memory is set to zero.

**Parameters**

- `n`: number of elements.
- `size`: element size.
- `flags`: the type of memory to allocate (see kmalloc).

#### <a id="c-kzalloc"></a>`kzalloc()`

```c
void * kzalloc(size_t size, gfp_t flags)
```

allocate memory. The memory is set to zero.

**Parameters**

- `size_t size`: how many bytes of memory are required.
- `gfp_t flags`: the type of memory to allocate (see kmalloc).

#### <a id="c-kmalloc_size_roundup"></a>`kmalloc_size_roundup()`

```c
size_t kmalloc_size_roundup(size_t size)
```

Report allocation bucket size for the given size

**Parameters**

- `size_t size`: Number of bytes to round up from.

**Description**

This returns the number of bytes that would be available in a [`kmalloc()`](#c-kmalloc)
allocation of **size** bytes. For example, a 126 byte request would be
rounded up to the next sized kmalloc bucket, 128 bytes. (This is strictly
for the general-purpose [`kmalloc()`](#c-kmalloc)-based allocations, and is not for the
pre-sized [`kmem_cache_alloc()`](#c-kmem_cache_alloc)-based allocations.)

Use this to [`kmalloc()`](#c-kmalloc) the full bucket size ahead of time instead of using
[`ksize()`](#c-ksize) to query the size after an allocation.



#### <a id="c-kmem_cache_alloc_node"></a>`kmem_cache_alloc_node()`

```c
void * kmem_cache_alloc_node(struct kmem_cache *s, gfp_t gfpflags, int node)
```

Allocate an object on the specified node

**Parameters**

- `struct kmem_cache *s`: The cache to allocate from.
- `gfp_t gfpflags`: See [`kmalloc()`](#c-kmalloc).
- `int node`: node number of the target node.

**Description**

Identical to kmem_cache_alloc but it will allocate memory on the given
node, which can improve the performance for cpu bound structures.

Fallback to other node is possible if __GFP_THISNODE is not set.

**Return**

pointer to the new object or `NULL` in case of error

#### <a id="c-kmalloc_nolock"></a>`kmalloc_nolock()`

```c
void * kmalloc_nolock(size_t size, gfp_t gfp_flags, int node)
```

Allocate an object of given size from any context.

**Parameters**

- `size_t size`: size to allocate
- `gfp_t gfp_flags`: GFP flags. Only __GFP_ACCOUNT, __GFP_ZERO, __GFP_NO_OBJ_EXT
  allowed.
- `int node`: node number of the target node.

**Return**

pointer to the new object or NULL in case of error.
NULL does not mean EBUSY or EAGAIN. It means ENOMEM.
There is no reason to call it again and expect !NULL.

#### <a id="c-kmem_cache_free"></a>`kmem_cache_free()`

```c
void kmem_cache_free(struct kmem_cache *s, void *x)
```

Deallocate an object

**Parameters**

- `struct kmem_cache *s`: The cache the allocation was from.
- `void *x`: The previously allocated object.

**Description**

Free an object which was previously allocated from this
cache.

#### <a id="c-ksize"></a>`ksize()`

```c
size_t ksize(const void *objp)
```

- Report full size of underlying allocation

**Parameters**

- `const void *objp`: pointer to the object

**Description**

This should only be used internally to query the true size of allocations.
It is not meant to be a way to discover the usable size of an allocation
after the fact. Instead, use [`kmalloc_size_roundup()`](#c-kmalloc_size_roundup). Using memory beyond
the originally requested allocation size may trigger KASAN, UBSAN_BOUNDS,
and/or FORTIFY_SOURCE.

**Return**

size of the actual memory used by **objp** in bytes

#### <a id="c-kfree"></a>`kfree()`

```c
void kfree(const void *object)
```

free previously allocated memory

**Parameters**

- `const void *object`: pointer returned by [`kmalloc()`](#c-kmalloc), [`kmalloc_nolock()`](#c-kmalloc_nolock), or [`kmem_cache_alloc()`](#c-kmem_cache_alloc)

**Description**

If **object** is NULL, no operation is performed.

#### <a id="c-krealloc_node_align"></a>`krealloc_node_align()`

```c
void * krealloc_node_align(const void *p, size_t new_size, unsigned long align, gfp_t flags, int nid)
```

reallocate memory. The contents will remain unchanged.

**Parameters**

- `const void *p`: object to reallocate memory for.
- `size_t new_size`: how many bytes of memory are required.
- `unsigned long align`: desired alignment.
- `gfp_t flags`: the type of memory to allocate.
- `int nid`: NUMA node or NUMA_NO_NODE

**Description**

If **p** is `NULL`, `krealloc()` behaves exactly like [`kmalloc()`](#c-kmalloc).  If **new_size**
is 0 and **p** is not a `NULL` pointer, the object pointed to is freed.

Only alignments up to those guaranteed by [`kmalloc()`](#c-kmalloc) will be honored. Please see
Documentation/core-api/memory-allocation.rst for more details.

If __GFP_ZERO logic is requested, callers must ensure that, starting with the
initial memory allocation, every subsequent call to this API for the same
memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
__GFP_ZERO is not fully honored by this API.

When `slub_debug_orig_size()` is off, `krealloc()` only knows about the bucket
size of an allocation (but not the exact size it was allocated with) and
hence implements the following semantics for shrinking and growing buffers
with __GFP_ZERO:

```text
        new             bucket
0       size             size
|--------|----------------|
|  keep  |      zero      |
```

Otherwise, the original allocation size 'orig_size' could be used to
precisely clear the requested size, and the new size will also be stored
as the new 'orig_size'.

In any case, the contents of the object pointed to are preserved up to the
lesser of the new and old sizes.

**Return**

pointer to the allocated memory or `NULL` in case of error

#### <a id="c-__kvmalloc_node"></a>`__kvmalloc_node()`

```c
void * __kvmalloc_node(size, b, unsigned long align, gfp_t flags, int node)
```

attempt to allocate physically contiguous memory, but upon failure, fall back to non-contiguous (vmalloc) allocation.

**Parameters**

- `size`: size of the request.
- `b`: which set of kmalloc buckets to allocate from.
- `unsigned long align`: desired alignment.
- `gfp_t flags`: gfp mask for the allocation - must be compatible (superset) with GFP_KERNEL.
- `int node`: numa node to allocate from

**Description**

Only alignments up to those guaranteed by [`kmalloc()`](#c-kmalloc) will be honored. Please see
Documentation/core-api/memory-allocation.rst for more details.

Uses kmalloc to get the memory but if the allocation fails then falls back
to the vmalloc allocator. Use kvfree for freeing the memory.

GFP_NOWAIT and GFP_ATOMIC are supported, the __GFP_NORETRY modifier is not.
__GFP_RETRY_MAYFAIL is supported, and it should be used only if kmalloc is
preferable to the vmalloc fallback, due to visible performance drawbacks.

**Return**

pointer to the allocated memory of `NULL` in case of failure

#### <a id="c-kvfree"></a>`kvfree()`

```c
void kvfree(const void *addr)
```

Free memory.

**Parameters**

- `const void *addr`: Pointer to allocated memory.

**Description**

kvfree frees memory allocated by any of [`vmalloc()`](#c-vmalloc), [`kmalloc()`](#c-kmalloc) or `kvmalloc()`.
It is slightly more efficient to use [`kfree()`](#c-kfree) or [`vfree()`](#c-vfree) if you are certain
that you know which one to use.

**Context**

Either preemptible task context or not-NMI interrupt.

#### <a id="c-kvfree_sensitive"></a>`kvfree_sensitive()`

```c
void kvfree_sensitive(const void *addr, size_t len)
```

Free a data object containing sensitive information.

**Parameters**

- `const void *addr`: address of the data object to be freed.
- `size_t len`: length of the data object.

**Description**

Use the special [`memzero_explicit()`](/kernel/internals/core-api/kernel-api.md#c-memzero_explicit) function to clear the content of a
kvmalloc'ed object containing sensitive data to make sure that the
compiler won't optimize out the data clearing.

#### <a id="c-kvrealloc_node_align"></a>`kvrealloc_node_align()`

```c
void * kvrealloc_node_align(const void *p, size_t size, unsigned long align, gfp_t flags, int nid)
```

reallocate memory; contents remain unchanged

**Parameters**

- `const void *p`: object to reallocate memory for
- `size_t size`: the size to reallocate
- `unsigned long align`: desired alignment
- `gfp_t flags`: the flags for the page level allocator
- `int nid`: NUMA node id

**Description**

If **p** is `NULL`, `kvrealloc()` behaves exactly like `kvmalloc()`. If **size** is 0
and **p** is not a `NULL` pointer, the object pointed to is freed.

Only alignments up to those guaranteed by [`kmalloc()`](#c-kmalloc) will be honored. Please see
Documentation/core-api/memory-allocation.rst for more details.

If __GFP_ZERO logic is requested, callers must ensure that, starting with the
initial memory allocation, every subsequent call to this API for the same
memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
__GFP_ZERO is not fully honored by this API.

In any case, the contents of the object pointed to are preserved up to the
lesser of the new and old sizes.

This function must not be called concurrently with itself or [`kvfree()`](#c-kvfree) for the
same memory allocation.

**Return**

pointer to the allocated memory or `NULL` in case of error



#### <a id="c-__kmem_cache_create_args"></a>`__kmem_cache_create_args()`

```c
struct kmem_cache * __kmem_cache_create_args(const char *name, unsigned int object_size, struct kmem_cache_args *args, slab_flags_t flags)
```

Create a kmem cache.

**Parameters**

- `const char *name`: A string which is used in /proc/slabinfo to identify this cache.
- `unsigned int object_size`: The size of objects to be created in this cache.
- `struct kmem_cache_args *args`: Additional arguments for the cache creation (see
  [`struct kmem_cache_args`](#c-struct-kmem_cache_args)).
- `slab_flags_t flags`: See the descriptions of individual flags. The common ones are listed
  in the description below.

**Description**

Not to be called directly, use the [`kmem_cache_create()`](#c-kmem_cache_create) wrapper with the same
parameters.

Commonly used **flags**:

[`SLAB_ACCOUNT`](#c-SLAB_ACCOUNT) - Account allocations to memcg.

[`SLAB_HWCACHE_ALIGN`](#c-SLAB_HWCACHE_ALIGN) - Align objects on cache line boundaries.

[`SLAB_RECLAIM_ACCOUNT`](#c-SLAB_RECLAIM_ACCOUNT) - Objects are reclaimable.

[`SLAB_TYPESAFE_BY_RCU`](#c-SLAB_TYPESAFE_BY_RCU) - Slab page (not individual objects) freeing delayed
by a grace period - see the full description before using.

**Context**

Cannot be called within a interrupt, but can be interrupted.

**Return**

a pointer to the cache on success, NULL on failure.

#### <a id="c-kmem_buckets_create"></a>`kmem_buckets_create()`

```c
kmem_buckets * kmem_buckets_create(const char *name, slab_flags_t flags, unsigned int useroffset, unsigned int usersize, void (*ctor)(void *))
```

Create a set of caches that handle dynamic sized allocations via `kmem_buckets_alloc()`

**Parameters**

- `const char *name`: A prefix string which is used in /proc/slabinfo to identify this
  cache. The individual caches with have their sizes as the suffix.
- `slab_flags_t flags`: SLAB flags (see [`kmem_cache_create()`](#c-kmem_cache_create) for details).
- `unsigned int useroffset`: Starting offset within an allocation that may be copied
  to/from userspace.
- `unsigned int usersize`: How many bytes, starting at **useroffset**, may be copied
  to/from userspace.
- `void (*ctor)(void *)`: A constructor for the objects, run when new allocations are made.

**Description**

Cannot be called within an interrupt, but can be interrupted.

**Return**

a pointer to the cache on success, NULL on failure. When
CONFIG_SLAB_BUCKETS is not enabled, ZERO_SIZE_PTR is returned, and
subsequent calls to `kmem_buckets_alloc()` will fall back to [`kmalloc()`](#c-kmalloc).
(i.e. callers only need to check for NULL on failure.)

#### <a id="c-kmem_cache_shrink"></a>`kmem_cache_shrink()`

```c
int kmem_cache_shrink(struct kmem_cache *cachep)
```

Shrink a cache.

**Parameters**

- `struct kmem_cache *cachep`: The cache to shrink.

**Description**

Releases as many slabs as possible for a cache.
To help debugging, a zero exit status indicates all slabs were released.

**Return**

`0` if all slabs were released, non-zero otherwise

#### <a id="c-kmem_dump_obj"></a>`kmem_dump_obj()`

```c
bool kmem_dump_obj(void *object)
```

Print available slab provenance information

**Parameters**

- `void *object`: slab object for which to find provenance information.

**Description**

This function uses [`pr_cont()`](/kernel/internals/core-api/printk-basics.md#c-pr_cont), so that the caller is expected to have
printed out whatever preamble is appropriate.  The provenance information
depends on the type of object and on how much debugging is enabled.
For a slab-cache object, the fact that it is a slab object is printed,
and, if available, the slab name, return address, and stack trace from
the allocation and last free path of that object.

**Return**

`true` if the pointer is to a not-yet-freed object from
[`kmalloc()`](#c-kmalloc) or [`kmem_cache_alloc()`](#c-kmem_cache_alloc), either `true` or `false` if the pointer
is to an already-freed object, and `false` otherwise.

#### <a id="c-kfree_sensitive"></a>`kfree_sensitive()`

```c
void kfree_sensitive(const void *p)
```

Clear sensitive information in memory before freeing

**Parameters**

- `const void *p`: object to free memory of

**Description**

The memory of the object **p** points to is zeroed before freed.
If **p** is `NULL`, [`kfree_sensitive()`](#c-kfree_sensitive) does nothing.

**Note**

this function zeroes the whole allocated buffer which can be a good
deal bigger than the requested buffer size passed to [`kmalloc()`](#c-kmalloc). So be
careful when using this function in performance sensitive code.

#### <a id="c-kvfree_rcu_barrier"></a>`kvfree_rcu_barrier()`

```c
void kvfree_rcu_barrier(void)
```

Wait until all in-flight `kvfree_rcu()` complete.

**Parameters**

- `void`: no arguments

**Description**

Note that a single argument of `kvfree_rcu()` call has a slow path that
triggers [`synchronize_rcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_rcu) following by freeing a pointer. It is done
before the return from the function. Therefore for any single-argument
call that will result in a [`kfree()`](#c-kfree) to a cache that is to be destroyed
during module exit, it is developer's responsibility to ensure that all
such calls have returned before the call to `kmem_cache_destroy()`.

#### <a id="c-kvfree_rcu_barrier_on_cache"></a>`kvfree_rcu_barrier_on_cache()`

```c
void kvfree_rcu_barrier_on_cache(struct kmem_cache *s)
```

Wait for in-flight `kvfree_rcu()` calls on a specific slab cache.

**Parameters**

- `struct kmem_cache *s`: slab cache to wait for

**Description**

See the description of [`kvfree_rcu_barrier()`](#c-kvfree_rcu_barrier) for details.



#### <a id="c-kfree_const"></a>`kfree_const()`

```c
void kfree_const(const void *x)
```

conditionally free memory

**Parameters**

- `const void *x`: pointer to the memory

**Description**

Function calls kfree only if **x** is not in .rodata section.


<a id="rst-virtually-contiguous-mappings"></a>

## Virtually Contiguous Mappings


#### <a id="c-vm_unmap_aliases"></a>`vm_unmap_aliases()`

```c
void vm_unmap_aliases(void)
```

unmap outstanding lazy aliases in the vmap layer

**Parameters**

- `void`: no arguments

**Description**

The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
to amortize TLB flushing overheads. What this means is that any page you
have now, may, in a former life, have been mapped into kernel virtual
address by the vmap layer and so there might be some CPUs with TLB entries
still referencing that page (additional to the regular 1:1 kernel mapping).

vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
be sure that none of the pages we have control over will have any aliases
from the vmap layer.

#### <a id="c-vm_unmap_ram"></a>`vm_unmap_ram()`

```c
void vm_unmap_ram(const void *mem, unsigned int count)
```

unmap linear kernel address space set up by vm_map_ram

**Parameters**

- `const void *mem`: the pointer returned by vm_map_ram
- `unsigned int count`: the count passed to that vm_map_ram call (cannot unmap partial)

#### <a id="c-vm_map_ram"></a>`vm_map_ram()`

```c
void * vm_map_ram(struct page **pages, unsigned int count, int node)
```

map pages linearly into kernel virtual address (vmalloc space)

**Parameters**

- `struct page **pages`: an array of pointers to the pages to be mapped
- `unsigned int count`: number of pages
- `int node`: prefer to allocate data structures on this node

**Description**

If you use this function for less than VMAP_MAX_ALLOC pages, it could be
faster than vmap so it's good.  But if you mix long-life and short-life
objects with [`vm_map_ram()`](#c-vm_map_ram), it could consume lots of address space through
fragmentation (especially on a 32bit machine).  You could see failures in
the end.  Please use this function for short-lived objects.

**Return**

a pointer to the address that has been mapped, or `NULL` on failure

#### <a id="c-vfree"></a>`vfree()`

```c
void vfree(const void *addr)
```

Release memory allocated by [`vmalloc()`](#c-vmalloc)

**Parameters**

- `const void *addr`: Memory base address

**Description**

Free the virtually continuous memory area starting at **addr**, as obtained
from one of the [`vmalloc()`](#c-vmalloc) family of APIs.  This will usually also free the
physical memory underlying the virtual allocation, but that memory is
reference counted, so it will not be freed until the last user goes away.

If **addr** is NULL, no operation is performed.

**Context**

May sleep if called *not* from interrupt context.
Must not be called in NMI context (strictly speaking, it could be
if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
conventions for [`vfree()`](#c-vfree) arch-dependent would be a really bad idea).

#### <a id="c-vunmap"></a>`vunmap()`

```c
void vunmap(const void *addr)
```

release virtual mapping obtained by [`vmap()`](#c-vmap)

**Parameters**

- `const void *addr`: memory base address

**Description**

Free the virtually contiguous memory area starting at **addr**,
which was created from the page array passed to [`vmap()`](#c-vmap).

Must not be called in interrupt context.

#### <a id="c-vmap"></a>`vmap()`

```c
void * vmap(struct page **pages, unsigned int count, unsigned long flags, pgprot_t prot)
```

map an array of pages into virtually contiguous space

**Parameters**

- `struct page **pages`: array of page pointers
- `unsigned int count`: number of pages to map
- `unsigned long flags`: vm_area->flags
- `pgprot_t prot`: page protection for the mapping

**Description**

Maps **count** pages from **pages** into contiguous kernel virtual space.
If **flags** contains `VM_MAP_PUT_PAGES` the ownership of the pages array itself
(which must be kmalloc or vmalloc memory) and one reference per pages in it
are transferred from the caller to [`vmap()`](#c-vmap), and will be freed / dropped when
[`vfree()`](#c-vfree) is called on the return value.

**Return**

the address of the area or `NULL` on failure

#### <a id="c-vmap_pfn"></a>`vmap_pfn()`

```c
void * vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
```

map an array of PFNs into virtually contiguous space

**Parameters**

- `unsigned long *pfns`: array of PFNs
- `unsigned int count`: number of pages to map
- `pgprot_t prot`: page protection for the mapping

**Description**

Maps **count** PFNs from **pfns** into contiguous kernel virtual space and returns
the start address of the mapping.

#### <a id="c-__vmalloc_node"></a>`__vmalloc_node()`

```c
void * __vmalloc_node(unsigned long size, unsigned long align, gfp_t gfp_mask, int node, const void *caller)
```

allocate virtually contiguous memory

**Parameters**

- `unsigned long size`: allocation size
- `unsigned long align`: desired alignment
- `gfp_t gfp_mask`: flags for the page level allocator
- `int node`: node to use for allocation or NUMA_NO_NODE
- `const void *caller`: caller's return address

**Description**

Allocate enough pages to cover **size** from the page level allocator with
**gfp_mask** flags.  Map them into contiguous kernel virtual space.

Semantics of **gfp_mask** (including reclaim/retry modifiers such as
__GFP_NOFAIL) are the same as in `__vmalloc_node_range_noprof()`.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vmalloc"></a>`vmalloc()`

```c
void * vmalloc(unsigned long size)
```

allocate virtually contiguous memory

**Parameters**

- `unsigned long size`: allocation size

**Description**

Allocate enough pages to cover **size** from the page level
allocator and map them into contiguous kernel virtual space.

For tight control over page level allocator and protection flags
use `__vmalloc()` instead.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vmalloc_huge_node"></a>`vmalloc_huge_node()`

```c
void * vmalloc_huge_node(unsigned long size, gfp_t gfp_mask, int node)
```

allocate virtually contiguous memory, allow huge pages

**Parameters**

- `unsigned long size`: allocation size
- `gfp_t gfp_mask`: flags for the page level allocator
- `int node`: node to use for allocation or NUMA_NO_NODE

**Description**

Allocate enough pages to cover **size** from the page level
allocator and map them into contiguous kernel virtual space.
If **size** is greater than or equal to PMD_SIZE, allow using
huge pages for the memory

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vzalloc"></a>`vzalloc()`

```c
void * vzalloc(unsigned long size)
```

allocate virtually contiguous memory with zero fill

**Parameters**

- `unsigned long size`: allocation size

**Description**

Allocate enough pages to cover **size** from the page level
allocator and map them into contiguous kernel virtual space.
The memory allocated is set to zero.

For tight control over page level allocator and protection flags
use `__vmalloc()` instead.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vmalloc_user"></a>`vmalloc_user()`

```c
void * vmalloc_user(unsigned long size)
```

allocate zeroed virtually contiguous memory for userspace

**Parameters**

- `unsigned long size`: allocation size

**Description**

The resulting memory area is zeroed so it can be mapped to userspace
without leaking data.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vmalloc_node"></a>`vmalloc_node()`

```c
void * vmalloc_node(unsigned long size, int node)
```

allocate memory on a specific node

**Parameters**

- `unsigned long size`: allocation size
- `int node`: numa node

**Description**

Allocate enough pages to cover **size** from the page level
allocator and map them into contiguous kernel virtual space.

For tight control over page level allocator and protection flags
use `__vmalloc()` instead.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vzalloc_node"></a>`vzalloc_node()`

```c
void * vzalloc_node(unsigned long size, int node)
```

allocate memory on a specific node with zero fill

**Parameters**

- `unsigned long size`: allocation size
- `int node`: numa node

**Description**

Allocate enough pages to cover **size** from the page level
allocator and map them into contiguous kernel virtual space.
The memory allocated is set to zero.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vrealloc_node_align"></a>`vrealloc_node_align()`

```c
void * vrealloc_node_align(const void *p, size_t size, unsigned long align, gfp_t flags, int nid)
```

reallocate virtually contiguous memory; contents remain unchanged

**Parameters**

- `const void *p`: object to reallocate memory for
- `size_t size`: the size to reallocate
- `unsigned long align`: requested alignment
- `gfp_t flags`: the flags for the page level allocator
- `int nid`: node number of the target node

**Description**

If **p** is `NULL`, `vrealloc_XXX()` behaves exactly like `vmalloc_XXX()`. If **size**
is 0 and **p** is not a `NULL` pointer, the object pointed to is freed.

If the caller wants the new memory to be on specific node *only*,
__GFP_THISNODE flag should be set, otherwise the function will try to avoid
reallocation and possibly disregard the specified **nid**.

If __GFP_ZERO logic is requested, callers must ensure that, starting with the
initial memory allocation, every subsequent call to this API for the same
memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
__GFP_ZERO is not fully honored by this API.

Requesting an alignment that is bigger than the alignment of the existing
allocation will fail.

In any case, the contents of the object pointed to are preserved up to the
lesser of the new and old sizes.

This function must not be called concurrently with itself or [`vfree()`](#c-vfree) for the
same memory allocation.

**Return**

pointer to the allocated memory; `NULL` if **size** is zero or in case of
failure

#### <a id="c-vmalloc_32"></a>`vmalloc_32()`

```c
void * vmalloc_32(unsigned long size)
```

allocate virtually contiguous memory (32bit addressable)

**Parameters**

- `unsigned long size`: allocation size

**Description**

Allocate enough 32bit PA addressable pages to cover **size** from the
page level allocator and map them into contiguous kernel virtual space.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-vmalloc_32_user"></a>`vmalloc_32_user()`

```c
void * vmalloc_32_user(unsigned long size)
```

allocate zeroed virtually contiguous 32bit memory

**Parameters**

- `unsigned long size`: allocation size

**Description**

The resulting memory area is 32bit addressable and zeroed so it can be
mapped to userspace without leaking data.

**Return**

pointer to the allocated memory or `NULL` on error

#### <a id="c-remap_vmalloc_range"></a>`remap_vmalloc_range()`

```c
int remap_vmalloc_range(struct vm_area_struct *vma, void *addr, unsigned long pgoff)
```

map vmalloc pages to userspace

**Parameters**

- `struct vm_area_struct *vma`: vma to cover (map full range of vma)
- `void *addr`: vmalloc memory
- `unsigned long pgoff`: number of pages into addr before first page to map

**Return**

0 for success, -Exxx on failure

**Description**

This function checks that addr is a valid vmalloc'ed area, and
that it is big enough to cover the vma. Will return failure if
that criteria isn't met.

Similar to [`remap_pfn_range()`](#c-remap_pfn_range) (see mm/memory.c)


<a id="rst-file-mapping-and-page-cache"></a>

## File Mapping and Page Cache

<a id="rst-filemap"></a>

### Filemap


#### <a id="c-filemap_fdatawrite_range"></a>`filemap_fdatawrite_range()`

```c
int filemap_fdatawrite_range(struct address_space *mapping, loff_t start, loff_t end)
```

start writeback on mapping dirty pages in range

**Parameters**

- `struct address_space *mapping`: address space structure to write
- `loff_t start`: offset in bytes where the range starts
- `loff_t end`: offset in bytes where the range ends (inclusive)

**Description**

Start writeback against all of a mapping's dirty pages that lie
within the byte offsets \<start, end> inclusive.

This is a data integrity operation that waits upon dirty or in writeback
pages.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-filemap_flush_range"></a>`filemap_flush_range()`

```c
int filemap_flush_range(struct address_space *mapping, loff_t start, loff_t end)
```

start writeback on a range

**Parameters**

- `struct address_space *mapping`: target address_space
- `loff_t start`: index to start writeback on
- `loff_t end`: last (inclusive) index for writeback

**Description**

This is a non-integrity writeback helper, to start writing back folios
for the indicated range.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-filemap_flush"></a>`filemap_flush()`

```c
int filemap_flush(struct address_space *mapping)
```

mostly a non-blocking flush

**Parameters**

- `struct address_space *mapping`: target address_space

**Description**

This is a mostly non-blocking flush.  Not suitable for data-integrity
purposes - I/O may not be started against all dirty pages.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-filemap_range_has_page"></a>`filemap_range_has_page()`

```c
bool filemap_range_has_page(struct address_space *mapping, loff_t start_byte, loff_t end_byte)
```

check if a page exists in range.

**Parameters**

- `struct address_space *mapping`: address space within which to check
- `loff_t start_byte`: offset in bytes where the range starts
- `loff_t end_byte`: offset in bytes where the range ends (inclusive)

**Description**

Find at least one page in the range supplied, usually used to check if
direct writing in this range will trigger a writeback.

**Return**

`true` if at least one page exists in the specified range,
`false` otherwise.

#### <a id="c-filemap_fdatawait_range"></a>`filemap_fdatawait_range()`

```c
int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte, loff_t end_byte)
```

wait for writeback to complete

**Parameters**

- `struct address_space *mapping`: address space structure to wait for
- `loff_t start_byte`: offset in bytes where the range starts
- `loff_t end_byte`: offset in bytes where the range ends (inclusive)

**Description**

Walk the list of under-writeback pages of the given address space
in the given range and wait for all of them.  Check error status of
the address space and return it.

Since the error status of the address space is cleared by this function,
callers are responsible for checking the return value and handling and/or
reporting the error.

**Return**

error status of the address space.

#### <a id="c-filemap_fdatawait_range_keep_errors"></a>`filemap_fdatawait_range_keep_errors()`

```c
int filemap_fdatawait_range_keep_errors(struct address_space *mapping, loff_t start_byte, loff_t end_byte)
```

wait for writeback to complete

**Parameters**

- `struct address_space *mapping`: address space structure to wait for
- `loff_t start_byte`: offset in bytes where the range starts
- `loff_t end_byte`: offset in bytes where the range ends (inclusive)

**Description**

Walk the list of under-writeback pages of the given address space in the
given range and wait for all of them.  Unlike [`filemap_fdatawait_range()`](#c-filemap_fdatawait_range),
this function does not clear error status of the address space.

Use this function if callers don't handle errors themselves.  Expected
call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
fsfreeze(8)

#### <a id="c-file_fdatawait_range"></a>`file_fdatawait_range()`

```c
int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
```

wait for writeback to complete

**Parameters**

- `struct file *file`: file pointing to address space structure to wait for
- `loff_t start_byte`: offset in bytes where the range starts
- `loff_t end_byte`: offset in bytes where the range ends (inclusive)

**Description**

Walk the list of under-writeback pages of the address space that file
refers to, in the given range and wait for all of them.  Check error
status of the address space vs. the file->f_wb_err cursor and return it.

Since the error status of the file is advanced by this function,
callers are responsible for checking the return value and handling and/or
reporting the error.

**Return**

error status of the address space vs. the file->f_wb_err cursor.

#### <a id="c-filemap_fdatawait_keep_errors"></a>`filemap_fdatawait_keep_errors()`

```c
int filemap_fdatawait_keep_errors(struct address_space *mapping)
```

wait for writeback without clearing errors

**Parameters**

- `struct address_space *mapping`: address space structure to wait for

**Description**

Walk the list of under-writeback pages of the given address space
and wait for all of them.  Unlike `filemap_fdatawait()`, this function
does not clear error status of the address space.

Use this function if callers don't handle errors themselves.  Expected
call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
fsfreeze(8)

**Return**

error status of the address space.

#### <a id="c-filemap_write_and_wait_range"></a>`filemap_write_and_wait_range()`

```c
int filemap_write_and_wait_range(struct address_space *mapping, loff_t lstart, loff_t lend)
```

write out & wait on a file range

**Parameters**

- `struct address_space *mapping`: the address_space for the pages
- `loff_t lstart`: offset in bytes where the range starts
- `loff_t lend`: offset in bytes where the range ends (inclusive)

**Description**

Write out and wait upon file offsets lstart->lend, inclusive.

Note that **lend** is inclusive (describes the last byte to be written) so
that this function can be used to write to the very end-of-file (end = -1).

**Return**

error status of the address space.

#### <a id="c-file_check_and_advance_wb_err"></a>`file_check_and_advance_wb_err()`

```c
int file_check_and_advance_wb_err(struct file *file)
```

report wb error (if any) that was previously and advance wb_err to current one

**Parameters**

- `struct file *file`: struct file on which the error is being reported

**Description**

When userland calls fsync (or something like nfsd does the equivalent), we
want to report any writeback errors that occurred since the last fsync (or
since the file was opened if there haven't been any).

Grab the wb_err from the mapping. If it matches what we have in the file,
then just quickly return 0. The file is all caught up.

If it doesn't match, then take the mapping value, set the "seen" flag in
it and try to swap it into place. If it works, or another task beat us
to it with the new value, then update the f_wb_err and return the error
portion. The error at this point must be reported via proper channels
(a'la fsync, or NFS COMMIT operation, etc.).

While we handle mapping->wb_err with atomic operations, the f_wb_err
value is protected by the f_lock since we must ensure that it reflects
the latest value swapped in for this file descriptor.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-file_write_and_wait_range"></a>`file_write_and_wait_range()`

```c
int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
```

write out & wait on a file range

**Parameters**

- `struct file *file`: file pointing to address_space with pages
- `loff_t lstart`: offset in bytes where the range starts
- `loff_t lend`: offset in bytes where the range ends (inclusive)

**Description**

Write out and wait upon file offsets lstart->lend, inclusive.

Note that **lend** is inclusive (describes the last byte to be written) so
that this function can be used to write to the very end-of-file (end = -1).

After writing out and waiting on the data, we check and advance the
f_wb_err cursor to the latest value, and return any errors detected there.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-replace_page_cache_folio"></a>`replace_page_cache_folio()`

```c
void replace_page_cache_folio(struct folio *old, struct folio *new)
```

replace a pagecache folio with a new one

**Parameters**

- `struct folio *old`: folio to be replaced
- `struct folio *new`: folio to replace with

**Description**

This function replaces a folio in the pagecache with a new one.  On
success it acquires the pagecache reference for the new folio and
drops it for the old folio.  Both the old and new folios must be
locked.  This function does not add the new folio to the LRU, the
caller must do that.

The remove + add is atomic.  This function cannot fail.

#### <a id="c-folio_unlock"></a>`folio_unlock()`

```c
void folio_unlock(struct folio *folio)
```

Unlock a locked folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

Unlocks the folio and wakes up any thread sleeping on the page lock.

**Context**

May be called from interrupt or process context.  May not be
called from NMI context.

#### <a id="c-folio_end_read"></a>`folio_end_read()`

```c
void folio_end_read(struct folio *folio, bool success)
```

End read on a folio.

**Parameters**

- `struct folio *folio`: The folio.
- `bool success`: True if all reads completed successfully.

**Description**

When all reads against a folio have completed, filesystems should
call this function to let the pagecache know that no more reads
are outstanding.  This will unlock the folio and wake up any thread
sleeping on the lock.  The folio will also be marked uptodate if all
reads succeeded.

**Context**

May be called from interrupt or process context.  May not be
called from NMI context.

#### <a id="c-folio_end_private_2"></a>`folio_end_private_2()`

```c
void folio_end_private_2(struct folio *folio)
```

Clear PG_private_2 and wake any waiters.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
it.  The folio reference held for PG_private_2 being set is released.

This is, for example, used when a netfs folio is being written to a local
disk cache, thereby allowing writes to the cache for the same folio to be
serialised.

#### <a id="c-folio_wait_private_2"></a>`folio_wait_private_2()`

```c
void folio_wait_private_2(struct folio *folio)
```

Wait for PG_private_2 to be cleared on a folio.

**Parameters**

- `struct folio *folio`: The folio to wait on.

**Description**

Wait for PG_private_2 to be cleared on a folio.

#### <a id="c-folio_wait_private_2_killable"></a>`folio_wait_private_2_killable()`

```c
int folio_wait_private_2_killable(struct folio *folio)
```

Wait for PG_private_2 to be cleared on a folio.

**Parameters**

- `struct folio *folio`: The folio to wait on.

**Description**

Wait for PG_private_2 to be cleared on a folio or until a fatal signal is
received by the calling task.

**Return**

- 0 if successful.
- -EINTR if a fatal signal was encountered.

#### <a id="c-folio_end_writeback_no_dropbehind"></a>`folio_end_writeback_no_dropbehind()`

```c
void folio_end_writeback_no_dropbehind(struct folio *folio)
```

End writeback against a folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

The folio must actually be under writeback.
This call is intended for filesystems that need to defer dropbehind.

**Context**

May be called from process or interrupt context.

#### <a id="c-folio_end_writeback"></a>`folio_end_writeback()`

```c
void folio_end_writeback(struct folio *folio)
```

End writeback against a folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

The folio must actually be under writeback.

**Context**

May be called from process or interrupt context.

#### <a id="c-__folio_lock"></a>`__folio_lock()`

```c
void __folio_lock(struct folio *folio)
```

Get a lock on the folio, assuming we need to sleep to get it.

**Parameters**

- `struct folio *folio`: The folio to lock

#### <a id="c-page_cache_next_miss"></a>`page_cache_next_miss()`

```c
pgoff_t page_cache_next_miss(struct address_space *mapping, pgoff_t index, unsigned long max_scan)
```

Find the next gap in the page cache.

**Parameters**

- `struct address_space *mapping`: Mapping.
- `pgoff_t index`: Index.
- `unsigned long max_scan`: Maximum range to search.

**Description**

Search the range \[index, min(index + max_scan - 1, ULONG_MAX)\] for the
gap with the lowest index.

This function may be called under the rcu_read_lock.  However, this will
not atomically search a snapshot of the cache at a single point in time.
For example, if a gap is created at index 5, then subsequently a gap is
created at index 10, page_cache_next_miss covering both indices may
return 10 if called under the rcu_read_lock.

**Return**

The index of the gap if found, otherwise an index outside the
range specified (in which case 'return - index >= max_scan' will be true).
In the rare case of index wrap-around, 0 will be returned.

#### <a id="c-page_cache_prev_miss"></a>`page_cache_prev_miss()`

```c
pgoff_t page_cache_prev_miss(struct address_space *mapping, pgoff_t index, unsigned long max_scan)
```

Find the previous gap in the page cache.

**Parameters**

- `struct address_space *mapping`: Mapping.
- `pgoff_t index`: Index.
- `unsigned long max_scan`: Maximum range to search.

**Description**

Search the range \[max(index - max_scan + 1, 0), index\] for the
gap with the highest index.

This function may be called under the rcu_read_lock.  However, this will
not atomically search a snapshot of the cache at a single point in time.
For example, if a gap is created at index 10, then subsequently a gap is
created at index 5, [`page_cache_prev_miss()`](#c-page_cache_prev_miss) covering both indices may
return 5 if called under the rcu_read_lock.

**Return**

The index of the gap if found, otherwise an index outside the
range specified (in which case 'index - return >= max_scan' will be true).
In the rare case of wrap-around, ULONG_MAX will be returned.

#### <a id="c-__filemap_get_folio_mpol"></a>`__filemap_get_folio_mpol()`

```c
struct folio * __filemap_get_folio_mpol(struct address_space *mapping, pgoff_t index, fgf_t fgp_flags, gfp_t gfp, struct mempolicy *policy)
```

Find and get a reference to a folio.

**Parameters**

- `struct address_space *mapping`: The address_space to search.
- `pgoff_t index`: The page index.
- `fgf_t fgp_flags`: `FGP` flags modify how the folio is returned.
- `gfp_t gfp`: Memory allocation flags to use if `FGP_CREAT` is specified.
- `struct mempolicy *policy`: NUMA memory allocation policy to follow.

**Description**

Looks up the page cache entry at **mapping** & **index**.

If `FGP_LOCK` or `FGP_CREAT` are specified then the function may sleep even
if the `GFP` flags specified for `FGP_CREAT` are atomic.

If this function returns a folio, it is returned with an increased refcount.

**Return**

The found folio or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) otherwise.

#### <a id="c-filemap_get_folios"></a>`filemap_get_folios()`

```c
unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
```

Get a batch of folios

**Parameters**

- `struct address_space *mapping`: The address_space to search
- `pgoff_t *start`: The starting page index
- `pgoff_t end`: The final page index (inclusive)
- `struct folio_batch *fbatch`: The batch to fill.

**Description**

Search for and return a batch of folios in the mapping starting at
index **start** and up to index **end** (inclusive).  The folios are returned
in **fbatch** with an elevated reference count.

**Return**

The number of folios which were found.
We also update **start** to index the next folio for the traversal.

#### <a id="c-filemap_get_folios_contig"></a>`filemap_get_folios_contig()`

```c
unsigned filemap_get_folios_contig(struct address_space *mapping, pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
```

Get a batch of contiguous folios

**Parameters**

- `struct address_space *mapping`: The address_space to search
- `pgoff_t *start`: The starting page index
- `pgoff_t end`: The final page index (inclusive)
- `struct folio_batch *fbatch`: The batch to fill

**Description**

[`filemap_get_folios_contig()`](#c-filemap_get_folios_contig) works exactly like [`filemap_get_folios()`](#c-filemap_get_folios),
except the returned folios are guaranteed to be contiguous. This may
not return all contiguous folios if the batch gets filled up.

**Return**

The number of folios found.
Also update **start** to be positioned for traversal of the next folio.

#### <a id="c-filemap_get_folios_tag"></a>`filemap_get_folios_tag()`

```c
unsigned filemap_get_folios_tag(struct address_space *mapping, pgoff_t *start, pgoff_t end, xa_mark_t tag, struct folio_batch *fbatch)
```

Get a batch of folios matching **tag**

**Parameters**

- `struct address_space *mapping`: The address_space to search
- `pgoff_t *start`: The starting page index
- `pgoff_t end`: The final page index (inclusive)
- `xa_mark_t tag`: The tag index
- `struct folio_batch *fbatch`: The batch to fill

**Description**

The first folio may start before **start**; if it does, it will contain
**start**.  The final folio may extend beyond **end**; if it does, it will
contain **end**.  The folios have ascending indices.  There may be gaps
between the folios if there are indices which have no folio in the
page cache.  If folios are added to or removed from the page cache
while this is running, they may or may not be found by this call.
Only returns folios that are tagged with **tag**.

**Return**

The number of folios found.
Also update **start** to index the next folio for traversal.

#### <a id="c-filemap_read"></a>`filemap_read()`

```c
ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter, ssize_t already_read)
```

Read data from the page cache.

**Parameters**

- `struct kiocb *iocb`: The iocb to read.
- `struct iov_iter *iter`: Destination for the data.
- `ssize_t already_read`: Number of bytes already read by the caller.

**Description**

Copies data from the page cache.  If the data is not currently present,
uses the readahead and read_folio address_space operations to fetch it.

**Return**

Total number of bytes copied, including those already read by
the caller.  If an error happens before any bytes are copied, returns
a negative error number.

#### <a id="c-generic_file_read_iter"></a>`generic_file_read_iter()`

```c
ssize_t generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
```

generic filesystem read routine

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct iov_iter *iter`: destination for the data read

**Description**

This is the "`read_iter()`" routine for all filesystems
that can use the page cache directly.

The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
be returned when no data can be read without waiting for I/O requests
to complete; it doesn't prevent readahead.

The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
requests shall be made for the read or for readahead.  When no data
can be read, -EAGAIN shall be returned.  When readahead would be
triggered, a partial, possibly empty read shall be returned.

**Return**

* number of bytes copied, even for partial reads
* negative error code (or 0 if IOCB_NOIO) if nothing was read

#### <a id="c-filemap_splice_read"></a>`filemap_splice_read()`

```c
ssize_t filemap_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags)
```

Splice data from a file's pagecache into a pipe

**Parameters**

- `struct file *in`: The file to read from
- `loff_t *ppos`: Pointer to the file position to read from
- `struct pipe_inode_info *pipe`: The pipe to splice into
- `size_t len`: The amount to splice
- `unsigned int flags`: The SPLICE_F_* flags

**Description**

This function gets folios from a file's pagecache and splices them into the
pipe.  Readahead will be called as necessary to fill more folios.  This may
be used for blockdevs also.

**Return**

On success, the number of bytes read will be returned and **\*ppos**
will be updated if appropriate; 0 will be returned if there is no more data
to be read; -EAGAIN will be returned if the pipe had no space, and some
other negative error code will be returned on error.  A short read may occur
if the pipe has insufficient space, we reach the end of the data or we hit a
hole.

#### <a id="c-filemap_fault"></a>`filemap_fault()`

```c
vm_fault_t filemap_fault(struct vm_fault *vmf)
```

read in file data for page fault handling

**Parameters**

- `struct vm_fault *vmf`: struct vm_fault containing details of the fault

**Description**

[`filemap_fault()`](#c-filemap_fault) is invoked via the vma operations vector for a
mapped memory region to read in file data during a page fault.

The goto's are kind of ugly, but this streamlines the normal case of having
it in the page cache, and handles the special cases reasonably without
having a lot of duplicated code.

vma->vm_mm->mmap_lock must be held on entry.

If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
may be dropped before doing I/O or by `lock_folio_maybe_drop_mmap()`.

If our return value does not have VM_FAULT_RETRY set, the mmap_lock
has not been released.

We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.

**Return**

bitwise-OR of `VM_FAULT_` codes.

#### <a id="c-read_cache_folio"></a>`read_cache_folio()`

```c
struct folio * read_cache_folio(struct address_space *mapping, pgoff_t index, filler_t filler, struct file *file)
```

Read into page cache, fill it if needed.

**Parameters**

- `struct address_space *mapping`: The address_space to read from.
- `pgoff_t index`: The index to read.
- `filler_t filler`: Function to perform the read, or NULL to use aops->`read_folio()`.
- `struct file *file`: Passed to filler function, may be NULL if not required.

**Description**

Read one page into the page cache.  If it succeeds, the folio returned
will contain **index**, but it may not be the first page of the folio.

If the filler function returns an error, it will be returned to the
caller.

**Context**

May sleep.  Expects mapping->invalidate_lock to be held.

**Return**

An uptodate folio on success, [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-mapping_read_folio_gfp"></a>`mapping_read_folio_gfp()`

```c
struct folio * mapping_read_folio_gfp(struct address_space *mapping, pgoff_t index, gfp_t gfp)
```

Read into page cache, using specified allocation flags.

**Parameters**

- `struct address_space *mapping`: The address_space for the folio.
- `pgoff_t index`: The index that the allocated folio will contain.
- `gfp_t gfp`: The page allocator flags to use if allocating.

**Description**

This is the same as "read_cache_folio(mapping, index, NULL, NULL)", but with
any new memory allocations done using the specified allocation flags.

The most likely error from this function is EIO, but ENOMEM is
possible and so is EINTR.  If ->read_folio returns another error,
that will be returned to the caller.

The function expects mapping->invalidate_lock to be already held.

**Return**

Uptodate folio on success, [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-read_cache_page_gfp"></a>`read_cache_page_gfp()`

```c
struct page * read_cache_page_gfp(struct address_space *mapping, pgoff_t index, gfp_t gfp)
```

read into page cache, using specified page allocation flags.

**Parameters**

- `struct address_space *mapping`: the page's address_space
- `pgoff_t index`: the page index
- `gfp_t gfp`: the page allocator flags to use if allocating

**Description**

This is the same as "read_mapping_page(mapping, index, NULL)", but with
any new page allocations done using the specified allocation flags.

If the page does not get brought uptodate, return -EIO.

The function expects mapping->invalidate_lock to be already held.

**Return**

up to date page on success, [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) on failure.

#### <a id="c-__generic_file_write_iter"></a>`__generic_file_write_iter()`

```c
ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
```

write data to a file

**Parameters**

- `struct kiocb *iocb`: IO state structure (file, offset, etc.)
- `struct iov_iter *from`: iov_iter with data to write

**Description**

This function does all the work needed for actually writing data to a
file. It does all basic checks, removes SUID from the file, updates
modification times and calls proper subroutines depending on whether we
do direct IO or a standard buffered write.

It expects i_rwsem to be grabbed unless we work on a block device or similar
object which does not need locking at all.

This function does *not* take care of syncing data in case of O_SYNC write.
A caller has to handle it. This is mainly due to the fact that we want to
avoid syncing under i_rwsem.

**Return**

* number of bytes written, even for truncated writes
* negative error code if no data has been written at all

#### <a id="c-generic_file_write_iter"></a>`generic_file_write_iter()`

```c
ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
```

write data to a file

**Parameters**

- `struct kiocb *iocb`: IO state structure
- `struct iov_iter *from`: iov_iter with data to write

**Description**

This is a wrapper around [`__generic_file_write_iter()`](#c-__generic_file_write_iter) to be used by most
filesystems. It takes care of syncing the file in case of O_SYNC file
and acquires i_rwsem as needed.

**Return**

* negative error code if no data has been written at all of
  [`vfs_fsync_range()`](/kernel/internals/filesystems/api-summary.md#c-vfs_fsync_range) failed for a synchronous write
* number of bytes written, even for truncated writes

#### <a id="c-filemap_release_folio"></a>`filemap_release_folio()`

```c
bool filemap_release_folio(struct folio *folio, gfp_t gfp)
```

Release fs-specific metadata on a folio.

**Parameters**

- `struct folio *folio`: The folio which the kernel is trying to free.
- `gfp_t gfp`: Memory allocation flags (and I/O mode).

**Description**

The address_space is trying to release any data attached to a folio
(presumably at folio->private).

This will also be called if the private_2 flag is set on a page,
indicating that the folio has other metadata associated with it.

The **gfp** argument specifies whether I/O may be performed to release
this page (__GFP_IO), and whether the call may block
(__GFP_RECLAIM & __GFP_FS).

**Return**

`true` if the release was successful, otherwise `false`.

#### <a id="c-filemap_invalidate_inode"></a>`filemap_invalidate_inode()`

```c
int filemap_invalidate_inode(struct inode *inode, bool flush, loff_t start, loff_t end)
```

Invalidate/forcibly write back a range of an inode's pagecache

**Parameters**

- `struct inode *inode`: The inode to flush
- `bool flush`: Set to write back rather than simply invalidate.
- `loff_t start`: First byte to in range.
- `loff_t end`: Last byte in range (inclusive), or LLONG_MAX for everything from start
  onwards.

**Description**

Invalidate all the folios on an inode that contribute to the specified
range, possibly writing them back first.  Whilst the operation is
undertaken, the invalidate lock is held to prevent new folios from being
installed.


<a id="rst-readahead"></a>

### Readahead


Readahead is used to read content into the page cache before it is
explicitly requested by the application.  Readahead only ever
attempts to read folios that are not yet in the page cache.  If a
folio is present but not up-to-date, readahead will not try to read
it. In that case a simple ->`read_folio()` will be requested.

Readahead is triggered when an application read request (whether a
system call or a page fault) finds that the requested folio is not in
the page cache, or that it is in the page cache and has the
readahead flag set.  This flag indicates that the folio was read
as part of a previous readahead request and now that it has been
accessed, it is time for the next readahead.

Each readahead request is partly synchronous read, and partly async
readahead.  This is reflected in the struct file_ra_state which
contains ->size being the total number of pages, and ->async_size
which is the number of pages in the async section.  The readahead
flag will be set on the first folio in this async section to trigger
a subsequent readahead.  Once a series of sequential reads has been
established, there should be no need for a synchronous component and
all readahead request will be fully asynchronous.

When either of the triggers causes a readahead, three numbers need
to be determined: the start of the region to read, the size of the
region, and the size of the async tail.

The start of the region is simply the first page address at or after
the accessed address, which is not currently populated in the page
cache.  This is found with a simple search in the page cache.

The size of the async tail is determined by subtracting the size that
was explicitly requested from the determined request size, unless
this would be less than zero - then zero is used.  NOTE THIS
CALCULATION IS WRONG WHEN THE START OF THE REGION IS NOT THE ACCESSED
PAGE.  ALSO THIS CALCULATION IS NOT USED CONSISTENTLY.

The size of the region is normally determined from the size of the
previous readahead which loaded the preceding pages.  This may be
discovered from the struct file_ra_state for simple sequential reads,
or from examining the state of the page cache when multiple
sequential reads are interleaved.  Specifically: where the readahead
was triggered by the readahead flag, the size of the previous
readahead is assumed to be the number of pages from the triggering
page to the start of the new readahead.  In these cases, the size of
the previous readahead is scaled, often doubled, for the new
readahead, though see `get_next_ra_size()` for details.

If the size of the previous read cannot be determined, the number of
preceding pages in the page cache is used to estimate the size of
a previous read.  This estimate could easily be misled by random
reads being coincidentally adjacent, so it is ignored unless it is
larger than the current request, and it is not scaled up, unless it
is at the start of file.

In general readahead is accelerated at the start of the file, as
reads from there are often sequential.  There are other minor
adjustments to the readahead size in various special cases and these
are best discovered by reading the code.

The above calculation, based on the previous readahead size,
determines the size of the readahead, to which any requested read
size may be added.

Readahead requests are sent to the filesystem using the ->`readahead()`
address space operation, for which [`mpage_readahead()`](/kernel/internals/filesystems/api-summary.md#c-mpage_readahead) is a canonical
implementation.  ->`readahead()` should normally initiate reads on all
folios, but may fail to read any or all folios without causing an I/O
error.  The page cache reading code will issue a ->`read_folio()` request
for any folio which ->`readahead()` did not read, and only an error
from this will be final.

->`readahead()` will generally call [`readahead_folio()`](#c-readahead_folio) repeatedly to get
each folio from those prepared for readahead.  It may fail to read a
folio by:

* not calling [`readahead_folio()`](#c-readahead_folio) sufficiently many times, effectively
  ignoring some folios, as might be appropriate if the path to
  storage is congested.

* failing to actually submit a read request for a given folio,
  possibly due to insufficient resources, or

* getting an error during subsequent processing of a request.

In the last two cases, the folio should be unlocked by the filesystem
to indicate that the read attempt has failed.  In the first case the
folio will be unlocked by the VFS.

Those folios not in the final `async_size` of the request should be
considered to be important and ->`readahead()` should not fail them due
to congestion or temporary resource unavailability, but should wait
for necessary resources (e.g.  memory or indexing information) to
become available.  Folios in the final `async_size` may be
considered less urgent and failure to read them is more acceptable.
In this case it is best to use `filemap_remove_folio()` to remove the
folios from the page cache as is automatically done for folios that
were not fetched with [`readahead_folio()`](#c-readahead_folio).  This will allow a
subsequent synchronous readahead request to try them again.  If they
are left in the page cache, then they will be read individually using
->`read_folio()` which may be less efficient.



#### <a id="c-page_cache_ra_unbounded"></a>`page_cache_ra_unbounded()`

```c
void page_cache_ra_unbounded(struct readahead_control *ractl, unsigned long nr_to_read, unsigned long lookahead_size)
```

Start unchecked readahead.

**Parameters**

- `struct readahead_control *ractl`: Readahead control.
- `unsigned long nr_to_read`: The number of pages to read.
- `unsigned long lookahead_size`: Where to start the next readahead.

**Description**

This function is for filesystems to call when they want to start
readahead beyond a file's stated i_size.  This is almost certainly
not the function you want to call.  Use [`page_cache_async_readahead()`](#c-page_cache_async_readahead)
or [`page_cache_sync_readahead()`](#c-page_cache_sync_readahead) instead.

**Context**

File is referenced by caller, and ractl->mapping->invalidate_lock
must be held by the caller at least in shared mode.  Mutexes may be held by
caller.  May sleep, but will not reenter filesystem to reclaim memory.

#### <a id="c-readahead_expand"></a>`readahead_expand()`

```c
void readahead_expand(struct readahead_control *ractl, loff_t new_start, size_t new_len)
```

Expand a readahead request

**Parameters**

- `struct readahead_control *ractl`: The request to be expanded
- `loff_t new_start`: The revised start
- `size_t new_len`: The revised size of the request

**Description**

Attempt to expand a readahead request outwards from the current size to the
specified size by inserting locked pages before and after the current window
to increase the size to the new window.  This may involve the insertion of
THPs, in which case the window may get expanded even beyond what was
requested.

The algorithm will stop if it encounters a conflicting page already in the
pagecache and leave a smaller expansion than requested.

The caller must check for this by examining the revised **ractl** object for a
different expansion than was requested.


<a id="rst-writeback"></a>

### Writeback


#### <a id="c-balance_dirty_pages_ratelimited_flags"></a>`balance_dirty_pages_ratelimited_flags()`

```c
int balance_dirty_pages_ratelimited_flags(struct address_space *mapping, unsigned int flags)
```

Balance dirty memory state.

**Parameters**

- `struct address_space *mapping`: address_space which was dirtied.
- `unsigned int flags`: BDP flags.

**Description**

Processes which are dirtying memory should call in here once for each page
which was newly dirtied.  The function will periodically check the system's
dirty state and will initiate writeback if needed.

See [`balance_dirty_pages_ratelimited()`](#c-balance_dirty_pages_ratelimited) for details.

**Return**

If **flags** contains BDP_ASYNC, it may return -EAGAIN to
indicate that memory is out of balance and the caller must wait
for I/O to complete.  Otherwise, it will return 0 to indicate
that either memory was already in balance, or it was able to sleep
until the amount of dirty memory returned to balance.

#### <a id="c-balance_dirty_pages_ratelimited"></a>`balance_dirty_pages_ratelimited()`

```c
void balance_dirty_pages_ratelimited(struct address_space *mapping)
```

balance dirty memory state.

**Parameters**

- `struct address_space *mapping`: address_space which was dirtied.

**Description**

Processes which are dirtying memory should call in here once for each page
which was newly dirtied.  The function will periodically check the system's
dirty state and will initiate writeback if needed.

Once we're over the dirty memory limit we decrease the ratelimiting
by a lot, to prevent individual processes from overshooting the limit
by (ratelimit_pages) each.

#### <a id="c-tag_pages_for_writeback"></a>`tag_pages_for_writeback()`

```c
void tag_pages_for_writeback(struct address_space *mapping, pgoff_t start, pgoff_t end)
```

tag pages to be written by writeback

**Parameters**

- `struct address_space *mapping`: address space structure to write
- `pgoff_t start`: starting page index
- `pgoff_t end`: ending page index (inclusive)

**Description**

This function scans the page range from **start** to **end** (inclusive) and tags
all pages that have DIRTY tag set with a special TOWRITE tag.  The caller
can then use the TOWRITE tag to identify pages eligible for writeback.
This mechanism is used to avoid livelocking of writeback by a process
steadily creating new dirty pages in the file (thus it is important for this
function to be quick so that it can tag pages faster than a dirtying process
can create them).

#### <a id="c-writeback_iter"></a>`writeback_iter()`

```c
struct folio * writeback_iter(struct address_space *mapping, struct writeback_control *wbc, struct folio *folio, int *error)
```

iterate folio of a mapping for writeback

**Parameters**

- `struct address_space *mapping`: address space structure to write
- `struct writeback_control *wbc`: writeback context
- `struct folio *folio`: previously iterated folio (`NULL` to start)
- `int *error`: in-out pointer for writeback errors (see below)

**Description**

This function returns the next folio for the writeback operation described by
**wbc** on **mapping** and  should be called in a while loop in the ->writepages
implementation.

To start the writeback operation, `NULL` is passed in the **folio** argument, and
for every subsequent iteration the folio returned previously should be passed
back in.

If there was an error in the per-folio writeback inside the [`writeback_iter()`](#c-writeback_iter)
loop, **error** should be set to the error value.

Once the writeback described in **wbc** has finished, this function will return
`NULL` and if there was an error in any iteration restore it to **error**.

**Note**

callers should not manually break out of the loop using break or goto
but must keep calling [`writeback_iter()`](#c-writeback_iter) until it returns `NULL`.

**Return**

the folio to write or `NULL` if the loop is done.

#### <a id="c-filemap_dirty_folio"></a>`filemap_dirty_folio()`

```c
bool filemap_dirty_folio(struct address_space *mapping, struct folio *folio)
```

Mark a folio dirty for filesystems which do not use buffer_heads.

**Parameters**

- `struct address_space *mapping`: Address space this folio belongs to.
- `struct folio *folio`: Folio to be marked as dirty.

**Description**

Filesystems which do not use buffer heads should call this function
from their dirty_folio address space operation.  It ignores the
contents of `folio_get_private()`, so if the filesystem marks individual
blocks as dirty, the filesystem should handle that itself.

This is also sometimes used by filesystems which use buffer_heads when
a single buffer is being dirtied: we want to set the folio dirty in
that case, but not all the buffers.  This is a "bottom-up" dirtying,
whereas [`block_dirty_folio()`](/kernel/internals/filesystems/buffer.md#c-block_dirty_folio) is a "top-down" dirtying.

The caller must ensure this doesn't race with truncation.  Most will
simply hold the folio lock, but e.g. `zap_pte_range()` calls with the
folio mapped and the pte lock held, which also locks out truncation.

#### <a id="c-folio_redirty_for_writepage"></a>`folio_redirty_for_writepage()`

```c
bool folio_redirty_for_writepage(struct writeback_control *wbc, struct folio *folio)
```

Decline to write a dirty folio.

**Parameters**

- `struct writeback_control *wbc`: The writeback control.
- `struct folio *folio`: The folio.

**Description**

When a writepage implementation decides that it doesn't want to write
**folio** for some reason, it should call this function, unlock **folio** and
return 0.

**Return**

True if we redirtied the folio.  False if someone else dirtied
it first.

#### <a id="c-folio_mark_dirty"></a>`folio_mark_dirty()`

```c
bool folio_mark_dirty(struct folio *folio)
```

Mark a folio as being modified.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

The folio may not be truncated while this function is running.
Holding the folio lock is sufficient to prevent truncation, but some
callers cannot acquire a sleeping lock.  These callers instead hold
the page table lock for a page table which contains at least one page
in this folio.  Truncation will block on the page table lock as it
unmaps pages before removing the folio from its mapping.

**Return**

True if the folio was newly dirtied, false if it was already dirty.

#### <a id="c-folio_wait_writeback"></a>`folio_wait_writeback()`

```c
void folio_wait_writeback(struct folio *folio)
```

Wait for a folio to finish writeback.

**Parameters**

- `struct folio *folio`: The folio to wait for.

**Description**

If the folio is currently being written back to storage, wait for the
I/O to complete.

**Context**

Sleeps.  Must be called in process context and with
no spinlocks held.  Caller should hold a reference on the folio.
If the folio is not locked, writeback may start again after writeback
has finished.

#### <a id="c-folio_wait_writeback_killable"></a>`folio_wait_writeback_killable()`

```c
int folio_wait_writeback_killable(struct folio *folio)
```

Wait for a folio to finish writeback.

**Parameters**

- `struct folio *folio`: The folio to wait for.

**Description**

If the folio is currently being written back to storage, wait for the
I/O to complete or a fatal signal to arrive.

**Context**

Sleeps.  Must be called in process context and with
no spinlocks held.  Caller should hold a reference on the folio.
If the folio is not locked, writeback may start again after writeback
has finished.

**Return**

0 on success, -EINTR if we get a fatal signal while waiting.

#### <a id="c-folio_wait_stable"></a>`folio_wait_stable()`

```c
void folio_wait_stable(struct folio *folio)
```

wait for writeback to finish, if necessary.

**Parameters**

- `struct folio *folio`: The folio to wait on.

**Description**

This function determines if the given folio is related to a backing
device that requires folio contents to be held stable during writeback.
If so, then it will wait for any pending writeback to complete.

**Context**

Sleeps.  Must be called in process context and with
no spinlocks held.  Caller should hold a reference on the folio.
If the folio is not locked, writeback may start again after writeback
has finished.


<a id="rst-truncate"></a>

### Truncate


#### <a id="c-folio_invalidate"></a>`folio_invalidate()`

```c
void folio_invalidate(struct folio *folio, size_t offset, size_t length)
```

Invalidate part or all of a folio.

**Parameters**

- `struct folio *folio`: The folio which is affected.
- `size_t offset`: start of the range to invalidate
- `size_t length`: length of the range to invalidate

**Description**

[`folio_invalidate()`](#c-folio_invalidate) is called when all or part of the folio has become
invalidated by a truncate operation.

[`folio_invalidate()`](#c-folio_invalidate) does not have to release all buffers, but it must
ensure that no dirty buffer is left outside **offset** and that no I/O
is underway against any of the blocks which are outside the truncation
point.  Because the caller is about to free (and possibly reuse) those
blocks on-disk.

#### <a id="c-truncate_inode_pages_range"></a>`truncate_inode_pages_range()`

```c
void truncate_inode_pages_range(struct address_space *mapping, loff_t lstart, uoff_t lend)
```

truncate range of pages specified by start & end byte offsets

**Parameters**

- `struct address_space *mapping`: mapping to truncate
- `loff_t lstart`: offset from which to truncate
- `uoff_t lend`: offset to which to truncate (inclusive)

**Description**

Truncate the page cache, removing the pages that are between
specified offsets (and zeroing out partial pages
if lstart or lend + 1 is not page aligned).

Truncate takes two passes - the first pass is nonblocking.  It will not
block on page locks and it will not block on writeback.  The second pass
will wait.  This is to prevent as much IO as possible in the affected region.
The first pass will remove most pages, so the search cost of the second pass
is low.

We pass down the cache-hot hint to the page freeing code.  Even if the
mapping is large, it is probably the case that the final pages are the most
recently touched, and freeing happens in ascending file offset order.

Note that since ->`invalidate_folio()` accepts range to invalidate
truncate_inode_pages_range is able to handle cases where lend + 1 is not
page aligned properly.

#### <a id="c-truncate_inode_pages"></a>`truncate_inode_pages()`

```c
void truncate_inode_pages(struct address_space *mapping, loff_t lstart)
```

truncate *all* the pages from an offset

**Parameters**

- `struct address_space *mapping`: mapping to truncate
- `loff_t lstart`: offset from which to truncate

**Description**

Called under (and serialised by) inode->i_rwsem and
mapping->invalidate_lock.

**Note**

When this function returns, there can be a page in the process of
deletion (inside `__filemap_remove_folio()`) in the specified range.  Thus
mapping->nrpages can be non-zero when this function returns even after
truncation of the whole mapping.

#### <a id="c-truncate_inode_pages_final"></a>`truncate_inode_pages_final()`

```c
void truncate_inode_pages_final(struct address_space *mapping)
```

truncate *all* pages before inode dies

**Parameters**

- `struct address_space *mapping`: mapping to truncate

**Description**

Called under (and serialized by) inode->i_rwsem.

Filesystems have to use this in the .evict_inode path to inform the
VM that this is the final truncate and the inode is going away.

#### <a id="c-invalidate_mapping_pages"></a>`invalidate_mapping_pages()`

```c
unsigned long invalidate_mapping_pages(struct address_space *mapping, pgoff_t start, pgoff_t end)
```

Invalidate all clean, unlocked cache of one inode

**Parameters**

- `struct address_space *mapping`: the address_space which holds the cache to invalidate
- `pgoff_t start`: the offset 'from' which to invalidate
- `pgoff_t end`: the offset 'to' which to invalidate (inclusive)

**Description**

This function removes pages that are clean, unmapped and unlocked,
as well as shadow entries. It will not block on IO activity.

If you want to remove all the pages of one inode, regardless of
their use and writeback state, use [`truncate_inode_pages()`](#c-truncate_inode_pages).

**Return**

The number of indices that had their contents invalidated

#### <a id="c-invalidate_inode_pages2_range"></a>`invalidate_inode_pages2_range()`

```c
int invalidate_inode_pages2_range(struct address_space *mapping, pgoff_t start, pgoff_t end)
```

remove range of pages from an address_space

**Parameters**

- `struct address_space *mapping`: the address_space
- `pgoff_t start`: the page offset 'from' which to invalidate
- `pgoff_t end`: the page offset 'to' which to invalidate (inclusive)

**Description**

Any pages which are found to be mapped into pagetables are unmapped prior to
invalidation.

**Return**

-EBUSY if any pages could not be invalidated.

#### <a id="c-invalidate_inode_pages2"></a>`invalidate_inode_pages2()`

```c
int invalidate_inode_pages2(struct address_space *mapping)
```

remove all pages from an address_space

**Parameters**

- `struct address_space *mapping`: the address_space

**Description**

Any pages which are found to be mapped into pagetables are unmapped prior to
invalidation.

**Return**

-EBUSY if any pages could not be invalidated.

#### <a id="c-truncate_pagecache"></a>`truncate_pagecache()`

```c
void truncate_pagecache(struct inode *inode, loff_t newsize)
```

unmap and remove pagecache that has been truncated

**Parameters**

- `struct inode *inode`: inode
- `loff_t newsize`: new file size

**Description**

inode's new i_size must already be written before truncate_pagecache
is called.

This function should typically be called before the filesystem
releases resources associated with the freed range (eg. deallocates
blocks). This way, pagecache will always stay logically coherent
with on-disk format, and the filesystem would not have to deal with
situations such as writepage being called for a page that has already
had its underlying blocks deallocated.

#### <a id="c-truncate_setsize"></a>`truncate_setsize()`

```c
void truncate_setsize(struct inode *inode, loff_t newsize)
```

update inode and pagecache for a new file size

**Parameters**

- `struct inode *inode`: inode
- `loff_t newsize`: new file size

**Description**

truncate_setsize updates i_size and performs pagecache truncation (if
necessary) to **newsize**. It will be typically be called from the filesystem's
setattr function when ATTR_SIZE is passed in.

Must be called with a lock serializing truncates and writes (generally
i_rwsem but e.g. xfs uses a different lock) and before all filesystem
specific block truncation has been performed.

#### <a id="c-pagecache_isize_extended"></a>`pagecache_isize_extended()`

```c
void pagecache_isize_extended(struct inode *inode, loff_t from, loff_t to)
```

update pagecache after extension of i_size

**Parameters**

- `struct inode *inode`: inode for which i_size was extended
- `loff_t from`: original inode size
- `loff_t to`: new inode size

**Description**

Handle extension of inode size either caused by extending truncate or
by write starting after current i_size.  We mark the page straddling
current i_size RO so that `page_mkwrite()` is called on the first
write access to the page.  The filesystem will update its per-block
information before user writes to the page via mmap after the i_size
has been changed.

The function must be called after i_size is updated so that page fault
coming after we unlock the folio will already see the new i_size.
The function must be called while we still hold i_rwsem - this not only
makes sure i_size is stable but also that userspace cannot observe new
i_size value before we are prepared to store mmap writes at new inode size.

#### <a id="c-truncate_pagecache_range"></a>`truncate_pagecache_range()`

```c
void truncate_pagecache_range(struct inode *inode, loff_t lstart, loff_t lend)
```

unmap and remove pagecache that is hole-punched

**Parameters**

- `struct inode *inode`: inode
- `loff_t lstart`: offset of beginning of hole
- `loff_t lend`: offset of last byte of hole

**Description**

This function should typically be called before the filesystem
releases resources associated with the freed range (eg. deallocates
blocks). This way, pagecache will always stay logically coherent
with on-disk format, and the filesystem would not have to deal with
situations such as writepage being called for a page that has already
had its underlying blocks deallocated.



#### <a id="c-filemap_set_wb_err"></a>`filemap_set_wb_err()`

```c
void filemap_set_wb_err(struct address_space *mapping, int err)
```

set a writeback error on an address_space

**Parameters**

- `struct address_space *mapping`: mapping in which to set writeback error
- `int err`: error to be set in mapping

**Description**

When writeback fails in some way, we must record that error so that
userspace can be informed when fsync and the like are called.  We endeavor
to report errors on any file that was open at the time of the error.  Some
internal callers also need to know when writeback errors have occurred.

When a writeback error occurs, most filesystems will want to call
filemap_set_wb_err to record the error in the mapping so that it will be
automatically reported whenever fsync is called on the file.

#### <a id="c-filemap_check_wb_err"></a>`filemap_check_wb_err()`

```c
int filemap_check_wb_err(struct address_space *mapping, errseq_t since)
```

has an error occurred since the mark was sampled?

**Parameters**

- `struct address_space *mapping`: mapping to check for writeback errors
- `errseq_t since`: previously-sampled errseq_t

**Description**

Grab the errseq_t value from the mapping, and see if it has changed "since"
the given value was sampled.

If it has then report the latest error set, otherwise return 0.

#### <a id="c-filemap_sample_wb_err"></a>`filemap_sample_wb_err()`

```c
errseq_t filemap_sample_wb_err(struct address_space *mapping)
```

sample the current errseq_t to test for later errors

**Parameters**

- `struct address_space *mapping`: mapping to be sampled

**Description**

Writeback errors are always reported relative to a particular sample point
in the past. This function provides those sample points.

#### <a id="c-file_sample_sb_err"></a>`file_sample_sb_err()`

```c
errseq_t file_sample_sb_err(struct file *file)
```

sample the current errseq_t to test for later errors

**Parameters**

- `struct file *file`: file pointer to be sampled

**Description**

Grab the most current superblock-level errseq_t value for the given
struct file.

#### <a id="c-mapping_set_error"></a>`mapping_set_error()`

```c
void mapping_set_error(struct address_space *mapping, int error)
```

record a writeback error in the address_space

**Parameters**

- `struct address_space *mapping`: the mapping in which an error should be set
- `int error`: the error to set in the mapping

**Description**

When writeback fails in some way, we must record that error so that
userspace can be informed when fsync and the like are called.  We endeavor
to report errors on any file that was open at the time of the error.  Some
internal callers also need to know when writeback errors have occurred.

When a writeback error occurs, most filesystems will want to call
mapping_set_error to record the error in the mapping so that it can be
reported when the application calls fsync(2).

#### <a id="c-mapping_set_large_folios"></a>`mapping_set_large_folios()`

```c
void mapping_set_large_folios(struct address_space *mapping)
```

Indicate the file supports large folios.

**Parameters**

- `struct address_space *mapping`: The address space of the file.

**Description**

The filesystem should call this function in its inode constructor to
indicate that the VFS can use large folios to cache the contents of
the file.

**Context**

This should not be called while the inode is active as it
is non-atomic.

#### <a id="c-mapping_align_index"></a>`mapping_align_index()`

```c
pgoff_t mapping_align_index(const struct address_space *mapping, pgoff_t index)
```

Align index for this mapping.

**Parameters**

- `const struct address_space *mapping`: The address_space.
- `pgoff_t index`: The page index.

**Description**

The index of a folio must be naturally aligned.  If you are adding a
new folio to the page cache and need to know what index to give it,
call this function.

#### <a id="c-folio_flush_mapping"></a>`folio_flush_mapping()`

```c
struct address_space * folio_flush_mapping(struct folio *folio)
```

Find the file mapping this folio belongs to.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

For folios which are in the page cache, return the mapping that this
page belongs to.  Anonymous folios return NULL, even if they're in
the swap cache.  Other kinds of folio also return NULL.

This is ONLY used by architecture cache flushing code.  If you aren't
writing cache flushing code, you want either [`folio_mapping()`](#c-folio_mapping) or
`folio_file_mapping()`.

#### <a id="c-folio_inode"></a>`folio_inode()`

```c
struct inode * folio_inode(struct folio *folio)
```

Get the host inode for this folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

For folios which are in the page cache, return the inode that this folio
belongs to.

Do not call this for folios which aren't in the page cache.

#### <a id="c-folio_attach_private"></a>`folio_attach_private()`

```c
void folio_attach_private(struct folio *folio, void *data)
```

Attach private data to a folio.

**Parameters**

- `struct folio *folio`: Folio to attach data to.
- `void *data`: Data to attach to folio.

**Description**

Attaching private data to a folio increments the page's reference count.
The data must be detached before the folio will be freed.

#### <a id="c-folio_change_private"></a>`folio_change_private()`

```c
void * folio_change_private(struct folio *folio, void *data)
```

Change private data on a folio.

**Parameters**

- `struct folio *folio`: Folio to change the data on.
- `void *data`: Data to set on the folio.

**Description**

Change the private data attached to a folio and return the old
data.  The page must previously have had data attached and the data
must be detached before the folio will be freed.

**Return**

Data that was previously attached to the folio.

#### <a id="c-folio_detach_private"></a>`folio_detach_private()`

```c
void * folio_detach_private(struct folio *folio)
```

Detach private data from a folio.

**Parameters**

- `struct folio *folio`: Folio to detach data from.

**Description**

Removes the data that was previously attached to the folio and decrements
the refcount on the page.

**Return**

Data that was attached to the folio.

#### <a id="c-fgf_t"></a>`typedef fgf_t`

Flags for getting folios from the page cache.

**Description**

Most users of the page cache will not need to use these flags;
there are convenience functions such as [`filemap_get_folio()`](#c-filemap_get_folio) and
[`filemap_lock_folio()`](#c-filemap_lock_folio).  For users which need more control over exactly
what is done with the folios, these flags to `__filemap_get_folio()`
are available.

* `FGP_ACCESSED` - The folio will be marked accessed.
* `FGP_LOCK` - The folio is returned locked.
* `FGP_CREAT` - If no folio is present then a new folio is allocated,
  added to the page cache and the VM's LRU list.  The folio is
  returned locked.
* `FGP_FOR_MMAP` - The caller wants to do its own locking dance if the
  folio is already in cache.  If the folio was allocated, unlock it
  before returning so the caller can do the same dance.
* `FGP_WRITE` - The folio will be written to by the caller.
* `FGP_NOFS` - __GFP_FS will get cleared in gfp.
* `FGP_NOWAIT` - Don't block on the folio lock.
* `FGP_STABLE` - Wait for the folio to be stable (finished writeback)
* `FGP_DONTCACHE` - Uncached buffered IO
* `FGP_WRITEBEGIN` - The flags to use in a filesystem `write_begin()`
  implementation.

#### <a id="c-fgf_set_order"></a>`fgf_set_order()`

```c
fgf_t fgf_set_order(size_t size)
```

Encode a length in the fgf_t flags.

**Parameters**

- `size_t size`: The suggested size of the folio to create.

**Description**

The caller of `__filemap_get_folio()` can use this to suggest a preferred
size for the folio that is created.  If there is already a folio at
the index, it will be returned, no matter what its size.  If a folio
is freshly created, it may be of a different size than requested
due to alignment constraints, memory pressure, or the presence of
other folios at nearby indices.

#### <a id="c-write_begin_get_folio"></a>`write_begin_get_folio()`

```c
struct folio * write_begin_get_folio(const struct kiocb *iocb, struct address_space *mapping, pgoff_t index, size_t len)
```

Get folio for write_begin with flags.

**Parameters**

- `const struct kiocb *iocb`: The kiocb passed from write_begin (may be NULL).
- `struct address_space *mapping`: The address space to search.
- `pgoff_t index`: The page cache index.
- `size_t len`: Length of data being written.

**Description**

This is a helper for filesystem `write_begin()` implementations.
It wraps `__filemap_get_folio()`, setting appropriate flags in
the write begin context.

**Return**

A folio or an ERR_PTR.

#### <a id="c-filemap_get_folio"></a>`filemap_get_folio()`

```c
struct folio * filemap_get_folio(struct address_space *mapping, pgoff_t index)
```

Find and get a folio.

**Parameters**

- `struct address_space *mapping`: The address_space to search.
- `pgoff_t index`: The page index.

**Description**

Looks up the page cache entry at **mapping** & **index**.  If a folio is
present, it is returned with an increased refcount.

**Return**

A folio or ERR_PTR(-ENOENT) if there is no folio in the cache for
this index.  Will not return a shadow, swap or DAX entry.

#### <a id="c-filemap_lock_folio"></a>`filemap_lock_folio()`

```c
struct folio * filemap_lock_folio(struct address_space *mapping, pgoff_t index)
```

Find and lock a folio.

**Parameters**

- `struct address_space *mapping`: The address_space to search.
- `pgoff_t index`: The page index.

**Description**

Looks up the page cache entry at **mapping** & **index**.  If a folio is
present, it is returned locked with an increased refcount.

**Context**

May sleep.

**Return**

A folio or ERR_PTR(-ENOENT) if there is no folio in the cache for
this index.  Will not return a shadow, swap or DAX entry.

#### <a id="c-filemap_grab_folio"></a>`filemap_grab_folio()`

```c
struct folio * filemap_grab_folio(struct address_space *mapping, pgoff_t index)
```

grab a folio from the page cache

**Parameters**

- `struct address_space *mapping`: The address space to search
- `pgoff_t index`: The page index

**Description**

Looks up the page cache entry at **mapping** & **index**. If no folio is found,
a new folio is created. The folio is locked, marked as accessed, and
returned.

**Return**

A found or created folio. ERR_PTR(-ENOMEM) if no folio is found
and failed to create a folio.

#### <a id="c-find_get_page"></a>`find_get_page()`

```c
struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
```

find and get a page reference

**Parameters**

- `struct address_space *mapping`: the address_space to search
- `pgoff_t offset`: the page index

**Description**

Looks up the page cache slot at **mapping** & **offset**.  If there is a
page cache page, it is returned with an increased refcount.

Otherwise, `NULL` is returned.

#### <a id="c-find_lock_page"></a>`find_lock_page()`

```c
struct page * find_lock_page(struct address_space *mapping, pgoff_t index)
```

locate, pin and lock a pagecache page

**Parameters**

- `struct address_space *mapping`: the address_space to search
- `pgoff_t index`: the page index

**Description**

Looks up the page cache entry at **mapping** & **index**.  If there is a
page cache page, it is returned locked and with an increased
refcount.

**Context**

May sleep.

**Return**

A struct page or `NULL` if there is no page in the cache for this
index.

#### <a id="c-find_or_create_page"></a>`find_or_create_page()`

```c
struct page * find_or_create_page(struct address_space *mapping, pgoff_t index, gfp_t gfp_mask)
```

locate or add a pagecache page

**Parameters**

- `struct address_space *mapping`: the page's address_space
- `pgoff_t index`: the page's index into the mapping
- `gfp_t gfp_mask`: page allocation mode

**Description**

Looks up the page cache slot at **mapping** & **offset**.  If there is a
page cache page, it is returned locked and with an increased
refcount.

If the page is not present, a new page is allocated using **gfp_mask**
and added to the page cache and the VM's LRU list.  The page is
returned locked and with an increased refcount.

On memory exhaustion, `NULL` is returned.

[`find_or_create_page()`](#c-find_or_create_page) may sleep, even if **gfp_flags** specifies an
atomic allocation!

#### <a id="c-grab_cache_page_nowait"></a>`grab_cache_page_nowait()`

```c
struct page * grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
```

returns locked page at given index in given cache

**Parameters**

- `struct address_space *mapping`: target address_space
- `pgoff_t index`: the page index

**Description**

Returns locked page at given index in given cache, creating it if
needed, but do not wait if the page is locked or to reclaim memory.
This is intended for speculative data generators, where the data can
be regenerated if the page couldn't be grabbed.  This routine should
be safe to call while holding the lock for another page.

Clear __GFP_FS when allocating the page to avoid recursion into the fs
and deadlock against the caller's locked page.

#### <a id="c-folio_next_index"></a>`folio_next_index()`

```c
pgoff_t folio_next_index(const struct folio *folio)
```

Get the index of the next folio.

**Parameters**

- `const struct folio *folio`: The current folio.

**Return**

The index of the folio which follows this folio in the file.

#### <a id="c-folio_next_pos"></a>`folio_next_pos()`

```c
loff_t folio_next_pos(const struct folio *folio)
```

Get the file position of the next folio.

**Parameters**

- `const struct folio *folio`: The current folio.

**Return**

The position of the folio which follows this folio in the file.

#### <a id="c-folio_file_page"></a>`folio_file_page()`

```c
struct page * folio_file_page(struct folio *folio, pgoff_t index)
```

The page for a particular index.

**Parameters**

- `struct folio *folio`: The folio which contains this index.
- `pgoff_t index`: The index we want to look up.

**Description**

Sometimes after looking up a folio in the page cache, we need to
obtain the specific page for an index (eg a page fault).

**Return**

The page containing the file data for this index.

#### <a id="c-folio_contains"></a>`folio_contains()`

```c
bool folio_contains(const struct folio *folio, pgoff_t index)
```

Does this folio contain this index?

**Parameters**

- `const struct folio *folio`: The folio.
- `pgoff_t index`: The page index within the file.

**Context**

The caller should have the folio locked and ensure
e.g., shmem did not move this folio to the swap cache.

**Return**

true or false.

#### <a id="c-page_pgoff"></a>`page_pgoff()`

```c
pgoff_t page_pgoff(const struct folio *folio, const struct page *page)
```

Calculate the logical page offset of this page.

**Parameters**

- `const struct folio *folio`: The folio containing this page.
- `const struct page *page`: The page which we need the offset of.

**Description**

For file pages, this is the offset from the beginning of the file
in units of PAGE_SIZE.  For anonymous pages, this is the offset from
the beginning of the anon_vma in units of PAGE_SIZE.  This will
return nonsense for KSM pages.

**Context**

Caller must have a reference on the folio or otherwise
prevent it from being split or freed.

**Return**

The offset in units of PAGE_SIZE.

#### <a id="c-folio_pos"></a>`folio_pos()`

```c
loff_t folio_pos(const struct folio *folio)
```

Returns the byte position of this folio in its file.

**Parameters**

- `const struct folio *folio`: The folio.

#### <a id="c-folio_trylock"></a>`folio_trylock()`

```c
bool folio_trylock(struct folio *folio)
```

Attempt to lock a folio.

**Parameters**

- `struct folio *folio`: The folio to attempt to lock.

**Description**

Sometimes it is undesirable to wait for a folio to be unlocked (eg
when the locks are being taken in the wrong order, or if making
progress through a batch of folios is more important than processing
them in order).  Usually [`folio_lock()`](#c-folio_lock) is the correct function to call.

**Context**

Any context.

**Return**

Whether the lock was successfully acquired.

#### <a id="c-folio_lock"></a>`folio_lock()`

```c
void folio_lock(struct folio *folio)
```

Lock this folio.

**Parameters**

- `struct folio *folio`: The folio to lock.

**Description**

The folio lock protects against many things, probably more than it
should.  It is primarily held while a folio is being brought uptodate,
either from its backing file or from swap.  It is also held while a
folio is being truncated from its address_space, so holding the lock
is sufficient to keep folio->mapping stable.

The folio lock is also held while `write()` is modifying the page to
provide POSIX atomicity guarantees (as long as the write does not
cross a page boundary).  Other modifications to the data in the folio
do not hold the folio lock and can race with writes, eg DMA and stores
to mapped pages.

**Context**

May sleep.  If you need to acquire the locks of two or
more folios, they must be in order of ascending index, if they are
in the same address_space.  If they are in different address_spaces,
acquire the lock of the folio which belongs to the address_space which
has the lowest address in memory first.

#### <a id="c-lock_page"></a>`lock_page()`

```c
void lock_page(struct page *page)
```

Lock the folio containing this page.

**Parameters**

- `struct page *page`: The page to lock.

**Description**

See [`folio_lock()`](#c-folio_lock) for a description of what the lock protects.
This is a legacy function and new code should probably use [`folio_lock()`](#c-folio_lock)
instead.

**Context**

May sleep.  Pages in the same folio share a lock, so do not
attempt to lock two pages which share a folio.

#### <a id="c-folio_lock_killable"></a>`folio_lock_killable()`

```c
int folio_lock_killable(struct folio *folio)
```

Lock this folio, interruptible by a fatal signal.

**Parameters**

- `struct folio *folio`: The folio to lock.

**Description**

Attempts to lock the folio, like [`folio_lock()`](#c-folio_lock), except that the sleep
to acquire the lock is interruptible by a fatal signal.

**Context**

May sleep; see [`folio_lock()`](#c-folio_lock).

**Return**

0 if the lock was acquired; -EINTR if a fatal signal was received.

#### <a id="c-filemap_range_needs_writeback"></a>`filemap_range_needs_writeback()`

```c
bool filemap_range_needs_writeback(struct address_space *mapping, loff_t start_byte, loff_t end_byte)
```

check if range potentially needs writeback

**Parameters**

- `struct address_space *mapping`: address space within which to check
- `loff_t start_byte`: offset in bytes where the range starts
- `loff_t end_byte`: offset in bytes where the range ends (inclusive)

**Description**

Find at least one page in the range supplied, usually used to check if
direct writing in this range will trigger a writeback. Used by O_DIRECT
read/write with IOCB_NOWAIT, to see if the caller needs to do
[`filemap_write_and_wait_range()`](#c-filemap_write_and_wait_range) before proceeding.

**Return**

`true` if the caller should do [`filemap_write_and_wait_range()`](#c-filemap_write_and_wait_range) before
doing O_DIRECT to a page in this range, `false` otherwise.

#### <a id="c-struct-readahead_control"></a>`struct readahead_control`

Describes a readahead request.

**Definition**

```c
struct readahead_control {
    struct file *file;
    struct address_space *mapping;
    struct file_ra_state *ra;
};
```

**Members**

- `file`: The file, used primarily by network filesystems for authentication.
  May be NULL if invoked internally by the filesystem.
- `mapping`: Readahead this filesystem object.
- `ra`: File readahead state.  May be NULL.

**Description**

A readahead request is for consecutive pages.  Filesystems which
implement the ->readahead method should call [`readahead_folio()`](#c-readahead_folio) or
`__readahead_batch()` in a loop and attempt to start reads into each
folio in the request.

Most of the fields in this struct are private and should be accessed
by the functions below.

#### <a id="c-page_cache_sync_readahead"></a>`page_cache_sync_readahead()`

```c
void page_cache_sync_readahead(struct address_space *mapping, struct file_ra_state *ra, struct file *file, pgoff_t index, unsigned long req_count)
```

generic file readahead

**Parameters**

- `struct address_space *mapping`: address_space which holds the pagecache and I/O vectors
- `struct file_ra_state *ra`: file_ra_state which holds the readahead state
- `struct file *file`: Used by the filesystem for authentication.
- `pgoff_t index`: Index of first page to be read.
- `unsigned long req_count`: Total number of pages being read by the caller.

**Description**

[`page_cache_sync_readahead()`](#c-page_cache_sync_readahead) should be called when a cache miss happened:
it will submit the read.  The readahead logic may decide to piggyback more
pages onto the read request if access patterns suggest it will improve
performance.

#### <a id="c-page_cache_async_readahead"></a>`page_cache_async_readahead()`

```c
void page_cache_async_readahead(struct address_space *mapping, struct file_ra_state *ra, struct file *file, struct folio *folio, unsigned long req_count)
```

file readahead for marked pages

**Parameters**

- `struct address_space *mapping`: address_space which holds the pagecache and I/O vectors
- `struct file_ra_state *ra`: file_ra_state which holds the readahead state
- `struct file *file`: Used by the filesystem for authentication.
- `struct folio *folio`: The folio which triggered the readahead call.
- `unsigned long req_count`: Total number of pages being read by the caller.

**Description**

[`page_cache_async_readahead()`](#c-page_cache_async_readahead) should be called when a page is used which
is marked as PageReadahead; this is a marker to suggest that the application
has used up enough of the readahead window that we should start pulling in
more pages.

#### <a id="c-readahead_folio"></a>`readahead_folio()`

```c
struct folio * readahead_folio(struct readahead_control *ractl)
```

Get the next folio to read.

**Parameters**

- `struct readahead_control *ractl`: The current readahead request.

**Context**

The folio is locked.  The caller should unlock the folio once
all I/O to that folio has completed.

**Return**

A pointer to the next folio, or `NULL` if we are done.

#### <a id="c-readahead_pos"></a>`readahead_pos()`

```c
loff_t readahead_pos(const struct readahead_control *rac)
```

The byte offset into the file of this readahead request.

**Parameters**

- `const struct readahead_control *rac`: The readahead request.

#### <a id="c-readahead_length"></a>`readahead_length()`

```c
size_t readahead_length(const struct readahead_control *rac)
```

The number of bytes in this readahead request.

**Parameters**

- `const struct readahead_control *rac`: The readahead request.

#### <a id="c-readahead_index"></a>`readahead_index()`

```c
pgoff_t readahead_index(const struct readahead_control *rac)
```

The index of the first page in this readahead request.

**Parameters**

- `const struct readahead_control *rac`: The readahead request.

#### <a id="c-readahead_count"></a>`readahead_count()`

```c
unsigned int readahead_count(const struct readahead_control *rac)
```

The number of pages in this readahead request.

**Parameters**

- `const struct readahead_control *rac`: The readahead request.

#### <a id="c-readahead_batch_length"></a>`readahead_batch_length()`

```c
size_t readahead_batch_length(const struct readahead_control *rac)
```

The number of bytes in the current batch.

**Parameters**

- `const struct readahead_control *rac`: The readahead request.

#### <a id="c-folio_mkwrite_check_truncate"></a>`folio_mkwrite_check_truncate()`

```c
ssize_t folio_mkwrite_check_truncate(const struct folio *folio, const struct inode *inode)
```

check if folio was truncated

**Parameters**

- `const struct folio *folio`: the folio to check
- `const struct inode *inode`: the inode to check the folio against

**Return**

the number of bytes in the folio up to EOF,
or -EFAULT if the folio was truncated.

#### <a id="c-i_blocks_per_folio"></a>`i_blocks_per_folio()`

```c
unsigned int i_blocks_per_folio(const struct inode *inode, const struct folio *folio)
```

How many blocks fit in this folio.

**Parameters**

- `const struct inode *inode`: The inode which contains the blocks.
- `const struct folio *folio`: The folio.

**Description**

If the block size is larger than the size of this folio, return zero.

**Context**

The caller should hold a refcount on the folio to prevent it
from being split.

**Return**

The number of filesystem blocks covered by this folio.


<a id="rst-memory-pools"></a>

## Memory pools


#### <a id="c-mempool_exit"></a>`mempool_exit()`

```c
void mempool_exit(struct mempool *pool)
```

exit a mempool initialized with [`mempool_init()`](#c-mempool_init)

**Parameters**

- `struct mempool *pool`: pointer to the memory pool which was initialized with
  [`mempool_init()`](#c-mempool_init).

**Description**

Free all reserved elements in **pool** and **pool** itself.  This function
only sleeps if the `free_fn()` function sleeps.

May be called on a zeroed but uninitialized mempool (i.e. allocated with
[`kzalloc()`](#c-kzalloc)).

#### <a id="c-mempool_destroy"></a>`mempool_destroy()`

```c
void mempool_destroy(struct mempool *pool)
```

deallocate a memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool which was allocated via
  `mempool_create()`.

**Description**

Free all reserved elements in **pool** and **pool** itself.  This function
only sleeps if the `free_fn()` function sleeps.

#### <a id="c-mempool_init"></a>`mempool_init()`

```c
int mempool_init(struct mempool *pool, int min_nr, mempool_alloc_t *alloc_fn, mempool_free_t *free_fn, void *pool_data)
```

initialize a memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool that should be initialized
- `int min_nr`: the minimum number of elements guaranteed to be
  allocated for this pool.
- `mempool_alloc_t *alloc_fn`: user-defined element-allocation function.
- `mempool_free_t *free_fn`: user-defined element-freeing function.
- `void *pool_data`: optional private data available to the user-defined functions.

**Description**

Like `mempool_create()`, but initializes the pool in (i.e. embedded in another
structure).

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-mempool_create_node"></a>`mempool_create_node()`

```c
struct mempool * mempool_create_node(int min_nr, mempool_alloc_t *alloc_fn, mempool_free_t *free_fn, void *pool_data, gfp_t gfp_mask, int node_id)
```

create a memory pool

**Parameters**

- `int min_nr`: the minimum number of elements guaranteed to be
  allocated for this pool.
- `mempool_alloc_t *alloc_fn`: user-defined element-allocation function.
- `mempool_free_t *free_fn`: user-defined element-freeing function.
- `void *pool_data`: optional private data available to the user-defined functions.
- `gfp_t gfp_mask`: memory allocation flags
- `int node_id`: numa node to allocate on

**Description**

this function creates and allocates a guaranteed size, preallocated
memory pool. The pool can be used from the [`mempool_alloc()`](#c-mempool_alloc) and [`mempool_free()`](#c-mempool_free)
functions. This function might sleep. Both the `alloc_fn()` and the `free_fn()`
functions might sleep - as long as the [`mempool_alloc()`](#c-mempool_alloc) function is not called
from IRQ contexts.

**Return**

pointer to the created memory pool object or `NULL` on error.

#### <a id="c-mempool_resize"></a>`mempool_resize()`

```c
int mempool_resize(struct mempool *pool, int new_min_nr)
```

resize an existing memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool which was allocated via
  `mempool_create()`.
- `int new_min_nr`: the new minimum number of elements guaranteed to be
  allocated for this pool.

**Description**

This function shrinks/grows the pool. In the case of growing,
it cannot be guaranteed that the pool will be grown to the new
size immediately, but new [`mempool_free()`](#c-mempool_free) calls will refill it.
This function may sleep.

Note, the caller must guarantee that no mempool_destroy is called
while this function is running. [`mempool_alloc()`](#c-mempool_alloc) & [`mempool_free()`](#c-mempool_free)
might be called (eg. from IRQ contexts) while this function executes.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-mempool_alloc_bulk"></a>`mempool_alloc_bulk()`

```c
int mempool_alloc_bulk(struct mempool *pool, void **elems, unsigned int count, unsigned int allocated)
```

allocate multiple elements from a memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool
- `void **elems`: partially or fully populated elements array
- `unsigned int count`: number of entries in **elem** that need to be allocated
- `unsigned int allocated`: number of entries in **elem** already allocated

**Description**

Allocate elements for each slot in **elem** that is non-`NULL`. This is done by
first calling into the alloc_fn supplied at pool initialization time, and
dipping into the reserved pool when alloc_fn fails to allocate an element.

On return all **count** elements in **elems** will be populated.

**Return**

Always 0.  If it wasn't for %$#^$ alloc tags, it would return void.

#### <a id="c-mempool_alloc"></a>`mempool_alloc()`

```c
void * mempool_alloc(struct mempool *pool, gfp_t gfp_mask)
```

allocate an element from a memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool
- `gfp_t gfp_mask`: GFP_* flags.  `__GFP_ZERO` is not supported.

**Description**

Allocate an element from **pool**.  This is done by first calling into the
alloc_fn supplied at pool initialization time, and dipping into the reserved
pool when alloc_fn fails to allocate an element.

This function only sleeps if the alloc_fn callback sleeps, or when waiting
for elements to become available in the pool.

**Return**

pointer to the allocated element or `NULL` when failing to allocate
an element.  Allocation failure can only happen when **gfp_mask** does not
include `__GFP_DIRECT_RECLAIM`.

#### <a id="c-mempool_alloc_preallocated"></a>`mempool_alloc_preallocated()`

```c
void * mempool_alloc_preallocated(struct mempool *pool)
```

allocate an element from preallocated elements belonging to a memory pool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool

**Description**

This function is similar to [`mempool_alloc()`](#c-mempool_alloc), but it only attempts allocating
an element from the preallocated elements. It only takes a single spinlock_t
and immediately returns if no preallocated elements are available.

**Return**

pointer to the allocated element or `NULL` if no elements are
available.

#### <a id="c-mempool_free_bulk"></a>`mempool_free_bulk()`

```c
unsigned int mempool_free_bulk(struct mempool *pool, void **elems, unsigned int count)
```

return elements to a mempool

**Parameters**

- `struct mempool *pool`: pointer to the memory pool
- `void **elems`: elements to return
- `unsigned int count`: number of elements to return

**Description**

Returns a number of elements from the start of **elem** to **pool** if **pool** needs
replenishing and sets their slots in **elem** to NULL.  Other elements are left
in **elem**.

**Return**

number of elements transferred to **pool**.  Elements are always
transferred from the beginning of **elem**, so the return value can be used as
an offset into **elem** for the freeing the remaining elements in the caller.

#### <a id="c-mempool_free"></a>`mempool_free()`

```c
void mempool_free(void *element, struct mempool *pool)
```

return an element to the pool.

**Parameters**

- `void *element`: element to return
- `struct mempool *pool`: pointer to the memory pool

**Description**

Returns **element** to **pool** if it needs replenishing, else frees it using
the free_fn callback in **pool**.

This function only sleeps if the free_fn callback sleeps.


<a id="rst-more-memory-management-functions"></a>

## More Memory Management Functions


#### <a id="c-zap_vma_ptes"></a>`zap_vma_ptes()`

```c
void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size)
```

remove ptes mapping the vma

**Parameters**

- `struct vm_area_struct *vma`: vm_area_struct holding ptes to be zapped
- `unsigned long address`: starting address of pages to zap
- `unsigned long size`: number of bytes to zap

**Description**

This function only unmaps ptes assigned to VM_PFNMAP vmas.

The entire address range must be fully contained within the vma.

#### <a id="c-vm_insert_pages"></a>`vm_insert_pages()`

```c
int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr, struct page **pages, unsigned long *num)
```

insert multiple pages into user vma, batching the pmd lock.

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `unsigned long addr`: target start user address of these pages
- `struct page **pages`: source kernel pages
- `unsigned long *num`: in: number of pages to map. out: number of pages that were *not*
  mapped. (0 means all pages were successfully mapped).

**Description**

Preferred over [`vm_insert_page()`](#c-vm_insert_page) when inserting multiple pages.

In case of error, we may have mapped a subset of the provided
pages. It is the caller's responsibility to account for this case.

The same restrictions apply as in [`vm_insert_page()`](#c-vm_insert_page).

#### <a id="c-vm_insert_page"></a>`vm_insert_page()`

```c
int vm_insert_page(struct vm_area_struct *vma, unsigned long addr, struct page *page)
```

insert single page into user vma

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `unsigned long addr`: target user address of this page
- `struct page *page`: source kernel page

**Description**

This allows drivers to insert individual pages they've allocated
into a user vma. The zeropage is supported in some VMAs,
see `vm_mixed_zeropage_allowed()`.

The page has to be a nice clean _individual_ kernel allocation.
If you allocate a compound page, you need to have marked it as
such (__GFP_COMP), or manually just split the page up yourself
(see `split_page()`).

NOTE! Traditionally this was done with "[`remap_pfn_range()`](#c-remap_pfn_range)" which
took an arbitrary page protection parameter. This doesn't allow
that. Your vma protection will have to be set up correctly, which
means that if you want a shared writable mapping, you'd better
ask for a shared writable mapping!

The page does not need to be reserved.

Usually this function is called from f_op->`mmap()` handler
under mm->mmap_lock write-lock, so it can change vma->vm_flags.
Caller must set VM_MIXEDMAP on vma if it wants to call this
function from other places, for example from page-fault handler.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-vm_map_pages"></a>`vm_map_pages()`

```c
int vm_map_pages(struct vm_area_struct *vma, struct page **pages, unsigned long num)
```

maps range of kernel pages starts with non zero offset

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `struct page **pages`: pointer to array of source kernel pages
- `unsigned long num`: number of pages in page array

**Description**

Maps an object consisting of **num** pages, catering for the user's
requested vm_pgoff

If we fail to insert any page into the vma, the function will return
immediately leaving any previously inserted pages present.  Callers
from the mmap handler may immediately return the error as their caller
will destroy the vma, removing any successfully inserted pages. Other
callers should make their own arrangements for calling `unmap_region()`.

**Context**

Process context. Called by mmap handlers.

**Return**

0 on success and error code otherwise.

#### <a id="c-vm_map_pages_zero"></a>`vm_map_pages_zero()`

```c
int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages, unsigned long num)
```

map range of kernel pages starts with zero offset

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `struct page **pages`: pointer to array of source kernel pages
- `unsigned long num`: number of pages in page array

**Description**

Similar to [`vm_map_pages()`](#c-vm_map_pages), except that it explicitly sets the offset
to 0. This function is intended for the drivers that did not consider
vm_pgoff.

**Context**

Process context. Called by mmap handlers.

**Return**

0 on success and error code otherwise.

#### <a id="c-vmf_insert_pfn_prot"></a>`vmf_insert_pfn_prot()`

```c
vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, pgprot_t pgprot)
```

insert single pfn into user vma with specified pgprot

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `unsigned long addr`: target user address of this page
- `unsigned long pfn`: source kernel pfn
- `pgprot_t pgprot`: pgprot flags for the inserted page

**Description**

This is exactly like [`vmf_insert_pfn()`](#c-vmf_insert_pfn), except that it allows drivers
to override pgprot on a per-page basis.

This only makes sense for IO mappings, and it makes no sense for
COW mappings.  In general, using multiple vmas is preferable;
vmf_insert_pfn_prot should only be used if using multiple VMAs is
impractical.

pgprot typically only differs from **vma->vm_page_prot** when drivers set
caching- and encryption bits different than those of **vma->vm_page_prot**,
because the caching- or encryption mode may not be known at `mmap()` time.

This is ok as long as **vma->vm_page_prot** is not used by the core vm
to set caching and encryption bits for those vmas (except for COW pages).
This is ensured by core vm only modifying these page table entries using
functions that don't touch caching- or encryption bits, using `pte_modify()`
if needed. (See for example `mprotect()`).

Also when new page-table entries are created, this is only done using the
`fault()` callback, and never using the value of vma->vm_page_prot,
except for page-table entries that point to anonymous pages as the result
of COW.

**Context**

Process context.  May allocate using `GFP_KERNEL`.

**Return**

vm_fault_t value.

#### <a id="c-vmf_insert_pfn"></a>`vmf_insert_pfn()`

```c
vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn)
```

insert single pfn into user vma

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `unsigned long addr`: target user address of this page
- `unsigned long pfn`: source kernel pfn

**Description**

Similar to vm_insert_page, this allows drivers to insert individual pages
they've allocated into a user vma. Same comments apply.

This function should only be called from a vm_ops->fault handler, and
in that case the handler should return the result of this function.

vma cannot be a COW mapping.

As this is called only for pages that do not currently exist, we
do not need to flush old virtual caches or the TLB.

**Context**

Process context.  May allocate using `GFP_KERNEL`.

**Return**

vm_fault_t value.

#### <a id="c-remap_pfn_range"></a>`remap_pfn_range()`

```c
int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t prot)
```

remap kernel memory to userspace

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `unsigned long addr`: target page aligned user address to start at
- `unsigned long pfn`: page frame number of kernel physical memory address
- `unsigned long size`: size of mapping area
- `pgprot_t prot`: page protection flags for this mapping

**Note**

this is only safe if the mm semaphore is held when called.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-vm_iomap_memory"></a>`vm_iomap_memory()`

```c
int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
```

remap memory to userspace

**Parameters**

- `struct vm_area_struct *vma`: user vma to map to
- `phys_addr_t start`: start of the physical memory to be mapped
- `unsigned long len`: size of area

**Description**

This is a simplified `io_remap_pfn_range()` for common driver use. The
driver just needs to give us the physical memory range to be mapped,
we'll figure out the rest from the vma information.

NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
whatever write-combining details or similar.

**Return**

`0` on success, negative error code otherwise.

#### <a id="c-unmap_mapping_pages"></a>`unmap_mapping_pages()`

```c
void unmap_mapping_pages(struct address_space *mapping, pgoff_t start, pgoff_t nr, bool even_cows)
```

Unmap pages from processes.

**Parameters**

- `struct address_space *mapping`: The address space containing pages to be unmapped.
- `pgoff_t start`: Index of first page to be unmapped.
- `pgoff_t nr`: Number of pages to be unmapped.  0 to unmap to end of file.
- `bool even_cows`: Whether to unmap even private COWed pages.

**Description**

Unmap the pages in this address space from any userspace process which
has them mmaped.  Generally, you want to remove COWed pages as well when
a file is being truncated, but not when invalidating pages from the page
cache.

#### <a id="c-unmap_mapping_range"></a>`unmap_mapping_range()`

```c
void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows)
```

unmap the portion of all mmaps in the specified address_space corresponding to the specified byte range in the underlying file.

**Parameters**

- `struct address_space *mapping`: the address space containing mmaps to be unmapped.
- `loff_t const holebegin`: byte in first page to unmap, relative to the start of
  the underlying file.  This will be rounded down to a PAGE_SIZE
  boundary.  Note that this is different from [`truncate_pagecache()`](#c-truncate_pagecache), which
  must keep the partial page.  In contrast, we must get rid of
  partial pages.
- `loff_t const holelen`: size of prospective hole in bytes.  This will be rounded
  up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
  end of the file.
- `int even_cows`: 1 when truncating a file, unmap even private COWed pages;
  but 0 when invalidating pagecache, don't throw away private data.

#### <a id="c-follow_pfnmap_start"></a>`follow_pfnmap_start()`

```c
int follow_pfnmap_start(struct follow_pfnmap_args *args)
```

Look up a pfn mapping at a user virtual address

**Parameters**

- `struct follow_pfnmap_args *args`: Pointer to struct **follow_pfnmap_args**

**Description**

The caller needs to setup args->vma and args->address to point to the
virtual address as the target of such lookup.  On a successful return,
the results will be put into other output fields.

After the caller finished using the fields, the caller must invoke
another [`follow_pfnmap_end()`](#c-follow_pfnmap_end) to proper releases the locks and resources
of such look up request.

During the `start()` and `end()` calls, the results in **args** will be valid
as proper locks will be held.  After the `end()` is called, all the fields
in **follow_pfnmap_args** will be invalid to be further accessed.  Further
use of such information after `end()` may require proper synchronizations
by the caller with page table updates, otherwise it can create a
security bug.

If the PTE maps a refcounted page, callers are responsible to protect
against invalidation with MMU notifiers; otherwise access to the PFN at
a later point in time can trigger use-after-free.

Only IO mappings and raw PFN mappings are allowed.  The mmap semaphore
should be taken for read, and the mmap semaphore cannot be released
before the `end()` is invoked.

This function must not be used to modify PTE content.

**Return**

zero on success, negative otherwise.

#### <a id="c-follow_pfnmap_end"></a>`follow_pfnmap_end()`

```c
void follow_pfnmap_end(struct follow_pfnmap_args *args)
```

End a [`follow_pfnmap_start()`](#c-follow_pfnmap_start) process

**Parameters**

- `struct follow_pfnmap_args *args`: Pointer to struct **follow_pfnmap_args**

**Description**

Must be used in pair of [`follow_pfnmap_start()`](#c-follow_pfnmap_start).  See the `start()` function
above for more information.

#### <a id="c-generic_access_phys"></a>`generic_access_phys()`

```c
int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write)
```

generic implementation for iomem mmap access

**Parameters**

- `struct vm_area_struct *vma`: the vma to access
- `unsigned long addr`: userspace address, not relative offset within **vma**
- `void *buf`: buffer to read/write
- `int len`: length of transfer
- `int write`: set to FOLL_WRITE when writing, otherwise reading

**Description**

This is a generic implementation for `vm_operations_struct.access` for an
iomem mapping. This callback is used by `access_process_vm()` when the **vma** is
not page based.

#### <a id="c-copy_remote_vm_str"></a>`copy_remote_vm_str()`

```c
int copy_remote_vm_str(struct task_struct *tsk, unsigned long addr, void *buf, int len, unsigned int gup_flags)
```

copy a string from another process's address space.

**Parameters**

- `struct task_struct *tsk`: the task of the target address space
- `unsigned long addr`: start address to read from
- `void *buf`: destination buffer
- `int len`: number of bytes to copy
- `unsigned int gup_flags`: flags modifying lookup behaviour

**Description**

The caller must hold a reference on **mm**.

**Return**

number of bytes copied from **addr** (source) to **buf** (destination);
not including the trailing NUL. Always guaranteed to leave NUL-terminated
buffer. On any error, return -EFAULT.



#### <a id="c-__get_pfnblock_flags_mask"></a>`__get_pfnblock_flags_mask()`

```c
unsigned long __get_pfnblock_flags_mask(const struct page *page, unsigned long pfn, unsigned long mask)
```

Return the requested group of flags for a pageblock_nr_pages block of pages

**Parameters**

- `const struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number
- `unsigned long mask`: mask of bits that the caller is interested in

**Return**

pageblock_bits flags

#### <a id="c-get_pfnblock_bit"></a>`get_pfnblock_bit()`

```c
bool get_pfnblock_bit(const struct page *page, unsigned long pfn, enum pageblock_bits pb_bit)
```

Check if a standalone bit of a pageblock is set

**Parameters**

- `const struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number
- `enum pageblock_bits pb_bit`: pageblock bit to check

**Return**

true if the bit is set, otherwise false

#### <a id="c-get_pfnblock_migratetype"></a>`get_pfnblock_migratetype()`

```c
enum migratetype get_pfnblock_migratetype(const struct page *page, unsigned long pfn)
```

Return the migratetype of a pageblock

**Parameters**

- `const struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number

**Return**

The migratetype of the pageblock

**Description**

Use [`get_pfnblock_migratetype()`](#c-get_pfnblock_migratetype) if caller already has both **page** and **pfn**
to save a call to `page_to_pfn()`.

#### <a id="c-__set_pfnblock_flags_mask"></a>`__set_pfnblock_flags_mask()`

```c
void __set_pfnblock_flags_mask(struct page *page, unsigned long pfn, unsigned long flags, unsigned long mask)
```

Set the requested group of flags for a pageblock_nr_pages block of pages

**Parameters**

- `struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number
- `unsigned long flags`: The flags to set
- `unsigned long mask`: mask of bits that the caller is interested in

#### <a id="c-set_pfnblock_bit"></a>`set_pfnblock_bit()`

```c
void set_pfnblock_bit(const struct page *page, unsigned long pfn, enum pageblock_bits pb_bit)
```

Set a standalone bit of a pageblock

**Parameters**

- `const struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number
- `enum pageblock_bits pb_bit`: pageblock bit to set

#### <a id="c-clear_pfnblock_bit"></a>`clear_pfnblock_bit()`

```c
void clear_pfnblock_bit(const struct page *page, unsigned long pfn, enum pageblock_bits pb_bit)
```

Clear a standalone bit of a pageblock

**Parameters**

- `const struct page *page`: The page within the block of interest
- `unsigned long pfn`: The target page frame number
- `enum pageblock_bits pb_bit`: pageblock bit to clear

#### <a id="c-set_pageblock_migratetype"></a>`set_pageblock_migratetype()`

```c
void set_pageblock_migratetype(struct page *page, enum migratetype migratetype)
```

Set the migratetype of a pageblock

**Parameters**

- `struct page *page`: The page within the block of interest
- `enum migratetype migratetype`: migratetype to set

#### <a id="c-__move_freepages_block_isolate"></a>`__move_freepages_block_isolate()`

```c
bool __move_freepages_block_isolate(struct zone *zone, struct page *page, bool isolate)
```

move free pages in block for page isolation

**Parameters**

- `struct zone *zone`: the zone
- `struct page *page`: the pageblock page
- `bool isolate`: to isolate the given pageblock or unisolate it

**Description**

This is similar to `move_freepages_block()`, but handles the special
case encountered in page isolation, where the block of interest
might be part of a larger buddy spanning multiple pageblocks.

Unlike the regular page allocator path, which moves pages while
stealing buddies off the freelist, page isolation is interested in
arbitrary pfn ranges that may have overlapping buddies on both ends.

This function handles that. Straddling buddies are split into
individual pageblocks. Only the block of interest is moved.

Returns `true` if pages could be moved, `false` otherwise.

#### <a id="c-__putback_isolated_page"></a>`__putback_isolated_page()`

```c
void __putback_isolated_page(struct page *page, unsigned int order, int mt)
```

Return a now-isolated page back where we got it

**Parameters**

- `struct page *page`: Page that was isolated
- `unsigned int order`: Order of the isolated page
- `int mt`: The page's pageblock's migratetype

**Description**

This function is meant to return a page pulled from the free lists via
__isolate_free_page back to the free lists they were pulled from.

#### <a id="c-__free_pages"></a>`__free_pages()`

```c
void __free_pages(struct page *page, unsigned int order)
```

Free pages allocated with [`alloc_pages()`](#c-alloc_pages).

**Parameters**

- `struct page *page`: The page pointer returned from [`alloc_pages()`](#c-alloc_pages).
- `unsigned int order`: The order of the allocation.

**Description**

This function can free multi-page allocations that are not compound
pages.  It does not check that the **order** passed in matches that of
the allocation, so it is easy to leak memory.  Freeing more memory
than was allocated will probably emit a warning.

If the last reference to this page is speculative, it will be released
by `put_page()` which only frees the first page of a non-compound
allocation.  To prevent the remaining pages from being leaked, we free
the subsequent pages here.  If you want to use the page's reference
count to decide when to free the allocation, you should allocate a
compound page, and use `put_page()` instead of [`__free_pages()`](#c-__free_pages).

**Context**

May be called in interrupt context or while holding a normal
spinlock, but not in NMI context or while holding a raw spinlock.

#### <a id="c-free_pages"></a>`free_pages()`

```c
void free_pages(unsigned long addr, unsigned int order)
```

Free pages allocated with `__get_free_pages()`.

**Parameters**

- `unsigned long addr`: The virtual address tied to a page returned from `__get_free_pages()`.
- `unsigned int order`: The order of the allocation.

**Description**

This function behaves the same as [`__free_pages()`](#c-__free_pages). Use this function
to free pages when you only have a valid virtual address. If you have
the page, call [`__free_pages()`](#c-__free_pages) instead.

#### <a id="c-alloc_pages_exact"></a>`alloc_pages_exact()`

```c
void * alloc_pages_exact(size_t size, gfp_t gfp_mask)
```

allocate an exact number physically-contiguous pages.

**Parameters**

- `size_t size`: the number of bytes to allocate
- `gfp_t gfp_mask`: GFP flags for the allocation, must not contain __GFP_COMP

**Description**

This function is similar to [`alloc_pages()`](#c-alloc_pages), except that it allocates the
minimum number of pages to satisfy the request.  [`alloc_pages()`](#c-alloc_pages) can only
allocate memory in power-of-two pages.

This function is also limited by MAX_PAGE_ORDER.

Memory allocated by this function must be released by [`free_pages_exact()`](#c-free_pages_exact).

**Return**

pointer to the allocated area or `NULL` in case of error.

#### <a id="c-alloc_pages_exact_nid"></a>`alloc_pages_exact_nid()`

```c
void * alloc_pages_exact_nid(int nid, size_t size, gfp_t gfp_mask)
```

allocate an exact number of physically-contiguous pages on a node.

**Parameters**

- `int nid`: the preferred node ID where memory should be allocated
- `size_t size`: the number of bytes to allocate
- `gfp_t gfp_mask`: GFP flags for the allocation, must not contain __GFP_COMP

**Description**

Like [`alloc_pages_exact()`](#c-alloc_pages_exact), but try to allocate on node nid first before falling
back.

**Return**

pointer to the allocated area or `NULL` in case of error.

#### <a id="c-free_pages_exact"></a>`free_pages_exact()`

```c
void free_pages_exact(void *virt, size_t size)
```

release memory allocated via [`alloc_pages_exact()`](#c-alloc_pages_exact)

**Parameters**

- `void *virt`: the value returned by alloc_pages_exact.
- `size_t size`: size of allocation, same value as passed to [`alloc_pages_exact()`](#c-alloc_pages_exact).

**Description**

Release the memory allocated by a previous call to alloc_pages_exact.

#### <a id="c-nr_free_zone_pages"></a>`nr_free_zone_pages()`

```c
unsigned long nr_free_zone_pages(int offset)
```

count number of pages beyond high watermark

**Parameters**

- `int offset`: The zone index of the highest zone

**Description**

[`nr_free_zone_pages()`](#c-nr_free_zone_pages) counts the number of pages which are beyond the
high watermark within all zones at or below a given zone index.  For each
zone, the number of pages is calculated as:

nr_free_zone_pages = managed_pages - high_pages

**Return**

number of pages beyond high watermark.

#### <a id="c-nr_free_buffer_pages"></a>`nr_free_buffer_pages()`

```c
unsigned long nr_free_buffer_pages(void)
```

count number of pages beyond high watermark

**Parameters**

- `void`: no arguments

**Description**

[`nr_free_buffer_pages()`](#c-nr_free_buffer_pages) counts the number of pages which are beyond the high
watermark within ZONE_DMA and ZONE_NORMAL.

**Return**

number of pages beyond high watermark within ZONE_DMA and
ZONE_NORMAL.

#### <a id="c-find_next_best_node"></a>`find_next_best_node()`

```c
int find_next_best_node(int node, nodemask_t *used_node_mask)
```

find the next node that should appear in a given node's fallback list

**Parameters**

- `int node`: node whose fallback list we're appending
- `nodemask_t *used_node_mask`: nodemask_t of already used nodes

**Description**

We use a number of factors to determine which is the next node that should
appear on a given node's fallback list.  The node should not have appeared
already in **node**'s fallback list, and it should be the next closest node
according to the distance array (which contains arbitrary distance values
from each node to each node in the system), and should also prefer nodes
with no CPUs, since presumably they'll have very little allocation pressure
on them otherwise.

**Return**

node id of the found node or `NUMA_NO_NODE` if no node is found.

#### <a id="c-setup_per_zone_wmarks"></a>`setup_per_zone_wmarks()`

```c
void setup_per_zone_wmarks(void)
```

called when min_free_kbytes changes or when memory is hot-{added|removed}

**Parameters**

- `void`: no arguments

**Description**

Ensures that the watermark\[min,low,high\] values for each zone are set
correctly with respect to min_free_kbytes.

#### <a id="c-alloc_contig_frozen_range"></a>`alloc_contig_frozen_range()`

```c
int alloc_contig_frozen_range(unsigned long start, unsigned long end, acr_flags_t alloc_flags, gfp_t gfp_mask)
```

- tries to allocate given range of frozen pages

**Parameters**

- `unsigned long start`: start PFN to allocate
- `unsigned long end`: one-past-the-last PFN to allocate
- `acr_flags_t alloc_flags`: allocation information
- `gfp_t gfp_mask`: GFP mask. Node/zone/placement hints are ignored; only some
  action and reclaim modifiers are supported. Reclaim modifiers
  control allocation behavior during compaction/migration/reclaim.

**Description**

The PFN range does not have to be pageblock aligned. The PFN range must
belong to a single zone.

The first thing this routine does is attempt to MIGRATE_ISOLATE all
pageblocks in the range.  Once isolated, the pageblocks should not
be modified by others.

All frozen pages which PFN is in \[start, end) are allocated for the
caller, and they could be freed with [`free_contig_frozen_range()`](#c-free_contig_frozen_range),
`free_frozen_pages()` also could be used to free compound frozen pages
directly.

**Return**

zero on success or negative error code.

#### <a id="c-alloc_contig_range"></a>`alloc_contig_range()`

```c
int alloc_contig_range(unsigned long start, unsigned long end, acr_flags_t alloc_flags, gfp_t gfp_mask)
```

- tries to allocate given range of pages

**Parameters**

- `unsigned long start`: start PFN to allocate
- `unsigned long end`: one-past-the-last PFN to allocate
- `acr_flags_t alloc_flags`: allocation information
- `gfp_t gfp_mask`: GFP mask.

**Description**

This routine is a wrapper around [`alloc_contig_frozen_range()`](#c-alloc_contig_frozen_range), it can't
be used to allocate compound pages, the refcount of each allocated page
will be set to one.

All pages which PFN is in \[start, end) are allocated for the caller,
and should be freed with [`free_contig_range()`](#c-free_contig_range) or by manually calling
`__free_page()` on each allocated page.

**Return**

zero on success or negative error code.

#### <a id="c-alloc_contig_frozen_pages"></a>`alloc_contig_frozen_pages()`

```c
struct page * alloc_contig_frozen_pages(unsigned long nr_pages, gfp_t gfp_mask, int nid, nodemask_t *nodemask)
```

- tries to find and allocate contiguous range of frozen pages

**Parameters**

- `unsigned long nr_pages`: Number of contiguous pages to allocate
- `gfp_t gfp_mask`: GFP mask. Node/zone/placement hints limit the search; only some
  action and reclaim modifiers are supported. Reclaim modifiers
  control allocation behavior during compaction/migration/reclaim.
- `int nid`: Target node
- `nodemask_t *nodemask`: Mask for other possible nodes

**Description**

This routine is a wrapper around [`alloc_contig_frozen_range()`](#c-alloc_contig_frozen_range). It scans over
zones on an applicable zonelist to find a contiguous pfn range which can then
be tried for allocation with [`alloc_contig_frozen_range()`](#c-alloc_contig_frozen_range). This routine is
intended for allocation requests which can not be fulfilled with the buddy
allocator.

The allocated memory is always aligned to a page boundary. If nr_pages is a
power of two, then allocated range is also guaranteed to be aligned to same
nr_pages (e.g. 1GB request would be aligned to 1GB).

Allocated frozen pages need be freed with [`free_contig_frozen_range()`](#c-free_contig_frozen_range),
or by manually calling `free_frozen_pages()` on each allocated frozen
non-compound page, for compound frozen pages could be freed with
`free_frozen_pages()` directly.

**Return**

pointer to contiguous frozen pages on success, or NULL if not successful.

#### <a id="c-alloc_contig_pages"></a>`alloc_contig_pages()`

```c
struct page * alloc_contig_pages(unsigned long nr_pages, gfp_t gfp_mask, int nid, nodemask_t *nodemask)
```

- tries to find and allocate contiguous range of pages

**Parameters**

- `unsigned long nr_pages`: Number of contiguous pages to allocate
- `gfp_t gfp_mask`: GFP mask.
- `int nid`: Target node
- `nodemask_t *nodemask`: Mask for other possible nodes

**Description**

This routine is a wrapper around [`alloc_contig_frozen_pages()`](#c-alloc_contig_frozen_pages), it can't
be used to allocate compound pages, the refcount of each allocated page
will be set to one.

Allocated pages can be freed with [`free_contig_range()`](#c-free_contig_range) or by manually
calling `__free_page()` on each allocated page.

**Return**

pointer to contiguous pages on success, or NULL if not successful.

#### <a id="c-free_contig_frozen_range"></a>`free_contig_frozen_range()`

```c
void free_contig_frozen_range(unsigned long pfn, unsigned long nr_pages)
```

- free the contiguous range of frozen pages

**Parameters**

- `unsigned long pfn`: start PFN to free
- `unsigned long nr_pages`: Number of contiguous frozen pages to free

**Description**

This can be used to free the allocated compound/non-compound frozen pages.

#### <a id="c-free_contig_range"></a>`free_contig_range()`

```c
void free_contig_range(unsigned long pfn, unsigned long nr_pages)
```

- free the contiguous range of pages

**Parameters**

- `unsigned long pfn`: start PFN to free
- `unsigned long nr_pages`: Number of contiguous pages to free

**Description**

This can be only used to free the allocated non-compound pages.

#### <a id="c-alloc_pages_nolock"></a>`alloc_pages_nolock()`

```c
struct page * alloc_pages_nolock(gfp_t gfp_flags, int nid, unsigned int order)
```

opportunistic reentrant allocation from any context

**Parameters**

- `gfp_t gfp_flags`: GFP flags. Only __GFP_ACCOUNT allowed.
- `int nid`: node to allocate from
- `unsigned int order`: allocation order size

**Description**

Allocates pages of a given order from the given node. This is safe to
call from any context (from atomic, NMI, and also reentrant
allocator -> tracepoint -> alloc_pages_nolock_noprof).
Allocation is best effort and to be expected to fail easily so nobody should
rely on the success. Failures are not reported via `warn_alloc()`.
See always fail conditions below.

**Return**

allocated page or NULL on failure. NULL does not mean EBUSY or EAGAIN.
It means ENOMEM. There is no reason to call it again and expect !NULL.



#### <a id="c-numa_nearest_node"></a>`numa_nearest_node()`

```c
int numa_nearest_node(int node, unsigned int state)
```

Find nearest node by state

**Parameters**

- `int node`: Node id to start the search
- `unsigned int state`: State to filter the search

**Description**

Lookup the closest node by distance if **nid** is not in state.

**Return**

this **node** if it is in state, otherwise the closest node by distance

#### <a id="c-nearest_node_nodemask"></a>`nearest_node_nodemask()`

```c
int nearest_node_nodemask(int node, nodemask_t *mask)
```

Find the node in **mask** at the nearest distance from **node**.

**Parameters**

- `int node`: a valid node ID to start the search from.
- `nodemask_t *mask`: a pointer to a nodemask representing the allowed nodes.

**Description**

This function iterates over all nodes in **mask** and calculates the
distance from the starting **node**, then it returns the node ID that is
the closest to **node**, or MAX_NUMNODES if no node is found.

Note that **node** must be a valid node ID usable with `node_distance()`,
providing an invalid node ID (e.g., NUMA_NO_NODE) may result in crashes
or unexpected behavior.

#### <a id="c-folio_can_map_prot_numa"></a>`folio_can_map_prot_numa()`

```c
bool folio_can_map_prot_numa(struct folio *folio, struct vm_area_struct *vma, bool is_private_single_threaded)
```

check whether the folio can map prot numa

**Parameters**

- `struct folio *folio`: The folio whose mapping considered for being made NUMA hintable
- `struct vm_area_struct *vma`: The VMA that the folio belongs to.
- `bool is_private_single_threaded`: Is this a single-threaded private VMA or not

**Description**

This function checks to see if the folio actually indicates that
we need to make the mapping one which causes a NUMA hinting fault,
as there are cases where it's simply unnecessary, and the folio's
access time is adjusted for memory tiering if prot numa needed.

**Return**

True if the mapping of the folio needs to be changed, false otherwise.

#### <a id="c-alloc_pages_mpol"></a>`alloc_pages_mpol()`

```c
struct page * alloc_pages_mpol(gfp_t gfp, unsigned int order, struct mempolicy *pol, pgoff_t ilx, int nid)
```

Allocate pages according to NUMA mempolicy.

**Parameters**

- `gfp_t gfp`: GFP flags.
- `unsigned int order`: Order of the page allocation.
- `struct mempolicy *pol`: Pointer to the NUMA mempolicy.
- `pgoff_t ilx`: Index for interleave mempolicy (also distinguishes [`alloc_pages()`](#c-alloc_pages)).
- `int nid`: Preferred node (usually `numa_node_id()` but **mpol** may override it).

**Return**

The page on success or NULL if allocation fails.

#### <a id="c-vma_alloc_folio"></a>`vma_alloc_folio()`

```c
struct folio * vma_alloc_folio(gfp_t gfp, int order, struct vm_area_struct *vma, unsigned long addr)
```

Allocate a folio for a VMA.

**Parameters**

- `gfp_t gfp`: GFP flags.
- `int order`: Order of the folio.
- `struct vm_area_struct *vma`: Pointer to VMA.
- `unsigned long addr`: Virtual address of the allocation.  Must be inside **vma**.

**Description**

Allocate a folio for a specific address in **vma**, using the appropriate
NUMA policy.  The caller must hold the mmap_lock of the mm_struct of the
VMA to prevent it from going away.  Should be used for all allocations
for folios that will be mapped into user space, excepting hugetlbfs, and
excepting where direct use of `folio_alloc_mpol()` is more appropriate.

**Return**

The folio on success or NULL if allocation fails.

#### <a id="c-alloc_pages"></a>`alloc_pages()`

```c
struct page * alloc_pages(gfp_t gfp, unsigned int order)
```

Allocate pages.

**Parameters**

- `gfp_t gfp`: GFP flags.
- `unsigned int order`: Power of two of number of pages to allocate.

**Description**

Allocate 1 \<\< **order** contiguous pages.  The physical address of the
first page is naturally aligned (eg an order-3 allocation will be aligned
to a multiple of 8 * PAGE_SIZE bytes).  The NUMA policy of the current
process is honoured when in process context.

**Context**

Can be called from any context, providing the appropriate GFP
flags are used.

**Return**

The page on success or NULL if allocation fails.

#### <a id="c-mpol_misplaced"></a>`mpol_misplaced()`

```c
int mpol_misplaced(struct folio *folio, struct vm_fault *vmf, unsigned long addr)
```

check whether current folio node is valid in policy

**Parameters**

- `struct folio *folio`: folio to be checked
- `struct vm_fault *vmf`: structure describing the fault
- `unsigned long addr`: virtual address in **vma** for shared policy lookup and interleave policy

**Description**

Lookup current policy node id for vma,addr and "compare to" folio's
node id.  Policy determination "mimics" `alloc_page_vma()`.
Called from fault path where we know the vma and faulting address.

**Return**

NUMA_NO_NODE if the page is in a node that is valid for this
policy, or a suitable node ID to allocate a replacement folio from.

#### <a id="c-mpol_shared_policy_init"></a>`mpol_shared_policy_init()`

```c
void mpol_shared_policy_init(struct shared_policy *sp, struct mempolicy *mpol)
```

initialize shared policy for inode

**Parameters**

- `struct shared_policy *sp`: pointer to inode shared policy
- `struct mempolicy *mpol`: struct mempolicy to install

**Description**

Install non-NULL **mpol** in inode's shared policy rb-tree.
On entry, the current task has a reference on a non-NULL **mpol**.
This must be released on exit.
This is called at `get_inode()` calls and we can use GFP_KERNEL.

#### <a id="c-mpol_parse_str"></a>`mpol_parse_str()`

```c
int mpol_parse_str(char *str, struct mempolicy **mpol)
```

parse string to mempolicy, for tmpfs mpol mount option.

**Parameters**

- `char *str`: string containing mempolicy to parse
- `struct mempolicy **mpol`: pointer to struct mempolicy pointer, returned on success.

**Description**

- Format of input:
  \<mode>\[=\<flags>\]\[:\<nodelist>\]

**Return**

`0` on success, else `1`

#### <a id="c-mpol_to_str"></a>`mpol_to_str()`

```c
void mpol_to_str(char *buffer, int maxlen, struct mempolicy *pol)
```

format a mempolicy structure for printing

**Parameters**

- `char *buffer`: to contain formatted mempolicy string
- `int maxlen`: length of **buffer**
- `struct mempolicy *pol`: pointer to mempolicy to be formatted

**Description**

Convert **pol** into a string.  If **buffer** is too short, truncate the string.
Recommend a **maxlen** of at least 51 for the longest mode, "weighted
interleave", plus the longest flag flags, "relative|balancing", and to
display at least a few node ids.



#### <a id="c-softleaf_t"></a>`typedef softleaf_t`

Describes a page table software leaf entry, abstracted from its architecture-specific encoding.

**Description**

Page table leaf entries are those which do not reference any descendent page
tables but rather either reference a data page, are an empty (or 'none'
entry), or contain a non-present entry.

If referencing another page table or a data page then the page table entry is
pertinent to hardware - that is it tells the hardware how to decode the page
table entry.

Otherwise it is a software-defined leaf page table entry, which this type
describes. See leafops.h and specifically **softleaf_type** for a list of all
possible kinds of software leaf entry.

A softleaf_t entry is abstracted from the hardware page table entry, so is
not architecture-specific.

**NOTE**

- While we transition from the confusing swp_entry_t type used for this

  purpose, we simply alias this type. This will be removed once the
  transition is complete.

#### <a id="c-struct-folio"></a>`struct folio`

Represents a contiguous set of bytes.

**Definition**

```c
struct folio {
        memdesc_flags_t flags;
        union {
            struct list_head lru;
            unsigned int mlock_count;
            struct dev_pagemap *pgmap;
        };
        struct address_space *mapping;
        union {
            pgoff_t index;
            unsigned long share;
        };
        union {
            void *private;
            swp_entry_t swap;
        };
        atomic_t _mapcount;
        atomic_t _refcount;
    #ifdef CONFIG_MEMCG;
        unsigned long memcg_data;
    #elif defined(CONFIG_SLAB_OBJ_EXT);
        unsigned long _unused_slab_obj_exts;
    #endif;
    #if defined(WANT_PAGE_VIRTUAL);
        void *virtual;
    #endif;
    #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS;
        int _last_cpupid;
    #endif;
        atomic_t _large_mapcount;
        atomic_t _nr_pages_mapped;
    #ifdef CONFIG_64BIT;
        atomic_t _entire_mapcount;
        atomic_t _pincount;
    #endif;
        mm_id_mapcount_t _mm_id_mapcount[2];
        union {
            mm_id_t _mm_id[2];
            unsigned long _mm_ids;
        };
    #ifdef NR_PAGES_IN_LARGE_FOLIO;
        unsigned int _nr_pages;
    #endif;
        struct list_head _deferred_list;
    #ifndef CONFIG_64BIT;
        atomic_t _entire_mapcount;
        atomic_t _pincount;
    #endif;
        void *_hugetlb_subpool;
        void *_hugetlb_cgroup;
        void *_hugetlb_cgroup_rsvd;
        void *_hugetlb_hwpoison;
};
```

**Members**

- `flags`: Identical to the page flags.
- `{unnamed_union}`: anonymous
- `lru`: Least Recently Used list; tracks how recently this folio was used.
- `mlock_count`: Number of times this folio has been pinned by `mlock()`.
- `pgmap`: Metadata for ZONE_DEVICE mappings
- `mapping`: The file this page belongs to, or refers to the anon_vma for
  anonymous memory.
- `{unnamed_union}`: anonymous
- `index`: Offset within the file, in units of pages.  For anonymous memory,
  this is the index from the beginning of the mmap.
- `share`: number of DAX mappings that reference this folio. See
  dax_associate_entry.
- `{unnamed_union}`: anonymous
- `private`: Filesystem per-folio data (see [`folio_attach_private()`](#c-folio_attach_private)).
- `swap`: Used for swp_entry_t if `folio_test_swapcache()`.
- `_mapcount`: Do not access this member directly.  Use [`folio_mapcount()`](#c-folio_mapcount) to
  find out how many times this folio is mapped by userspace.
- `_refcount`: Do not access this member directly.  Use [`folio_ref_count()`](#c-folio_ref_count)
  to find how many references there are to this folio.
- `memcg_data`: Memory Control Group data.
- `_unused_slab_obj_exts`: Placeholder to match obj_exts in struct slab.
- `virtual`: Virtual address in the kernel direct map.
- `_last_cpupid`: IDs of last CPU and last process that accessed the folio.
- `_large_mapcount`: Do not use directly, call [`folio_mapcount()`](#c-folio_mapcount).
- `_nr_pages_mapped`: Do not use outside of rmap and debug code.
- `_entire_mapcount`: Do not use directly, call `folio_entire_mapcount()`.
- `_pincount`: Do not use directly, call [`folio_maybe_dma_pinned()`](#c-folio_maybe_dma_pinned).
- `_mm_id_mapcount`: Do not use outside of rmap code.
- `{unnamed_union}`: anonymous
- `_mm_id`: Do not use outside of rmap code.
- `_mm_ids`: Do not use outside of rmap code.
- `_nr_pages`: Do not use directly, call [`folio_nr_pages()`](#c-folio_nr_pages).
- `_deferred_list`: Folios to be split under memory pressure.
- `_entire_mapcount`: Do not use directly, call `folio_entire_mapcount()`.
- `_pincount`: Do not use directly, call [`folio_maybe_dma_pinned()`](#c-folio_maybe_dma_pinned).
- `_hugetlb_subpool`: Do not use directly, use accessor in hugetlb.h.
- `_hugetlb_cgroup`: Do not use directly, use accessor in hugetlb_cgroup.h.
- `_hugetlb_cgroup_rsvd`: Do not use directly, use accessor in hugetlb_cgroup.h.
- `_hugetlb_hwpoison`: Do not use directly, call `raw_hwp_list_head()`.

**Description**

A folio is a physically, virtually and logically contiguous set
of bytes.  It is a power-of-two in size, and it is aligned to that
same power-of-two.  It is at least as large as `PAGE_SIZE`.  If it is
in the page cache, it is at a file offset which is a multiple of that
power-of-two.  It may be mapped into userspace at an address which is
at an arbitrary page offset, but its kernel virtual address is aligned
to its size.

#### <a id="c-struct-ptdesc"></a>`struct ptdesc`

Memory descriptor for page tables.

**Definition**

```c
struct ptdesc {
        memdesc_flags_t pt_flags;
        union {
            struct rcu_head pt_rcu_head;
            struct list_head pt_list;
            struct {
                unsigned long _pt_pad_1;
                pgtable_t pmd_huge_pte;
            };
        };
        unsigned long __page_mapping;
        union {
            pgoff_t pt_index;
            struct mm_struct *pt_mm;
            atomic_t pt_frag_refcount;
    #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING;
            atomic_t pt_share_count;
    #endif;
        };
        union {
            unsigned long _pt_pad_2;
    #if ALLOC_SPLIT_PTLOCKS;
            spinlock_t *ptl;
    #else;
            spinlock_t ptl;
    #endif;
        };
        unsigned int __page_type;
        atomic_t __page_refcount;
    #ifdef CONFIG_MEMCG;
        unsigned long pt_memcg_data;
    #endif;
};
```

**Members**

- `pt_flags`: enum pt_flags plus zone/node/section.
- `{unnamed_union}`: anonymous
- `pt_rcu_head`: For freeing page table pages.
- `pt_list`: List of used page tables. Used for s390 gmap shadow pages
  (which are not linked into the user page tables) and x86
  pgds.
- `{unnamed_struct}`: anonymous
- `_pt_pad_1`: Padding that aliases with page's compound head.
- `pmd_huge_pte`: Protected by ptdesc->ptl, used for THPs.
- `__page_mapping`: Aliases with page->mapping. Unused for page tables.
- `{unnamed_union}`: anonymous
- `pt_index`: Used for s390 gmap.
- `pt_mm`: Used for x86 pgds.
- `pt_frag_refcount`: For fragmented page table tracking. Powerpc only.
- `pt_share_count`: Used for HugeTLB PMD page table share count.
- `{unnamed_union}`: anonymous
- `_pt_pad_2`: Padding to ensure proper alignment.
- `ptl`: Lock for the page table.
- `ptl`: Lock for the page table.
- `__page_type`: Same as page->page_type. Unused for page tables.
- `__page_refcount`: Same as page refcount.
- `pt_memcg_data`: Memcg data. Tracked for page tables here.

**Description**

This struct overlays struct page for now. Do not modify without a good
understanding of the issues.

#### <a id="c-vm_fault_t"></a>`typedef vm_fault_t`

Return type for page fault handlers.

**Description**

Page fault handlers return a bitmask of `VM_FAULT` values.

#### <a id="c-enum-vm_fault_reason"></a>`enum vm_fault_reason`

Page fault handlers return a bitmask of these values to tell the core VM what happened when handling the fault. Used to decide whether a process gets delivered SIGBUS or just gets major/minor fault counters bumped up.

**Constants**

- `VM_FAULT_OOM`: Out Of Memory
- `VM_FAULT_SIGBUS`: Bad access
- `VM_FAULT_MAJOR`: Page read from storage
- `VM_FAULT_HWPOISON`: Hit poisoned small page
- `VM_FAULT_HWPOISON_LARGE`: Hit poisoned large page. Index encoded
  in upper bits
- `VM_FAULT_SIGSEGV`: segmentation fault
- `VM_FAULT_NOPAGE`: ->fault installed the pte, not return page
- `VM_FAULT_LOCKED`: ->fault locked the returned page
- `VM_FAULT_RETRY`: ->fault blocked, must retry
- `VM_FAULT_FALLBACK`: huge page fault failed, fall back to small
- `VM_FAULT_DONE_COW`: ->fault has fully handled COW
- `VM_FAULT_NEEDDSYNC`: ->fault did not modify page tables and needs
  `fsync()` to complete (for synchronous page faults
  in DAX)
- `VM_FAULT_COMPLETED`: ->fault completed, meanwhile mmap lock released
- `VM_FAULT_HINDEX_MASK`: mask HINDEX value

#### <a id="c-enum-fault_flag"></a>`enum fault_flag`

Fault flag definitions.

**Constants**

- `FAULT_FLAG_WRITE`: Fault was a write fault.
- `FAULT_FLAG_MKWRITE`: Fault was mkwrite of existing PTE.
- `FAULT_FLAG_ALLOW_RETRY`: Allow to retry the fault if blocked.
- `FAULT_FLAG_RETRY_NOWAIT`: Don't drop mmap_lock and wait when retrying.
- `FAULT_FLAG_KILLABLE`: The fault task is in SIGKILL killable region.
- `FAULT_FLAG_TRIED`: The fault has been tried once.
- `FAULT_FLAG_USER`: The fault originated in userspace.
- `FAULT_FLAG_REMOTE`: The fault is not for current task/mm.
- `FAULT_FLAG_INSTRUCTION`: The fault was during an instruction fetch.
- `FAULT_FLAG_INTERRUPTIBLE`: The fault can be interrupted by non-fatal signals.
- `FAULT_FLAG_UNSHARE`: The fault is an unsharing request to break COW in a
  COW mapping, making sure that an exclusive anon page is
  mapped after the fault.
- `FAULT_FLAG_ORIG_PTE_VALID`: whether the fault has vmf->orig_pte cached.
  We should only access orig_pte if this flag set.
- `FAULT_FLAG_VMA_LOCK`: The fault is handled under VMA lock.

**Description**

About **FAULT_FLAG_ALLOW_RETRY** and **FAULT_FLAG_TRIED**: we can specify
whether we would allow page faults to retry by specifying these two
fault flags correctly.  Currently there can be three legal combinations:

- (a) ALLOW_RETRY and !TRIED:  this means the page fault allows retry, and

  this is the first try

- (b) ALLOW_RETRY and TRIED:   this means the page fault allows retry, and

  we've already tried at least once

(c) !ALLOW_RETRY and !TRIED: this means the page fault does not allow retry

The unlisted combination (!ALLOW_RETRY && TRIED) is illegal and should never
be used.  Note that page faults can be allowed to retry for multiple times,
in which case we'll have an initial fault with flags (a) then later on
continuous faults with flags (b).  We should always try to detect pending
signals before a retry to make sure the continuous page faults can still be
interrupted if necessary.

The combination FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE is illegal.
FAULT_FLAG_UNSHARE is ignored and treated like an ordinary read fault when
applied to mappings that are not COW mappings.



#### <a id="c-folio_is_file_lru"></a>`folio_is_file_lru()`

```c
int folio_is_file_lru(const struct folio *folio)
```

Should the folio be on a file LRU or anon LRU?

**Parameters**

- `const struct folio *folio`: The folio to test.

**Description**

We would like to get this info without a page flag, but the state
needs to survive until the folio is last deleted from the LRU, which
could be as far down as __page_cache_release.

**Return**

An integer (not a boolean!) used to sort a folio onto the
right LRU list and to account folios correctly.
1 if **folio** is a regular filesystem backed page cache folio
or a lazily freed anonymous folio (e.g. via MADV_FREE).
0 if **folio** is a normal anonymous folio, a tmpfs folio or otherwise
ram or swap backed folio.

#### <a id="c-__folio_clear_lru_flags"></a>`__folio_clear_lru_flags()`

```c
void __folio_clear_lru_flags(struct folio *folio)
```

Clear page lru flags before releasing a page.

**Parameters**

- `struct folio *folio`: The folio that was on lru and now has a zero reference.

#### <a id="c-folio_lru_list"></a>`folio_lru_list()`

```c
enum lru_list folio_lru_list(const struct folio *folio)
```

Which LRU list should a folio be on?

**Parameters**

- `const struct folio *folio`: The folio to test.

**Return**

The LRU list a folio should be on, as an index
into the array of LRU lists.

#### <a id="c-num_pages_contiguous"></a>`num_pages_contiguous()`

```c
size_t num_pages_contiguous(struct page **pages, size_t nr_pages)
```

determine the number of contiguous pages that represent contiguous PFNs

**Parameters**

- `struct page **pages`: an array of page pointers
- `size_t nr_pages`: length of the array, at least 1

**Description**

Determine the number of contiguous pages that represent contiguous PFNs
in **pages**, starting from the first page.

In some kernel configs contiguous PFNs will not have contiguous struct
pages. In these configurations [`num_pages_contiguous()`](#c-num_pages_contiguous) will return a num
smaller than ideal number. The caller should continue to check for pfn
contiguity after each call to [`num_pages_contiguous()`](#c-num_pages_contiguous).

Returns the number of contiguous pages.



#### <a id="c-page_folio"></a>`page_folio()`

```c
page_folio(p)
```

Converts from page to folio.

**Parameters**

- `p`: The page.

**Description**

Every page is part of a folio.  This function cannot be called on a
NULL pointer.

**Context**

No reference, nor lock is required on **page**.  If the caller
does not hold a reference, this call may race with a folio split, so
it should re-check the folio still contains this page after gaining
a reference on the folio.

**Return**

The folio which contains this page.

#### <a id="c-folio_page"></a>`folio_page()`

```c
folio_page(folio, n)
```

Return a page from a folio.

**Parameters**

- `folio`: The folio.
- `n`: The page number to return.

**Description**

**n** is relative to the start of the folio.  This function does not
check that the page number lies within **folio**; the caller is presumed
to have a reference to the page.

#### <a id="c-folio_xor_flags_has_waiters"></a>`folio_xor_flags_has_waiters()`

```c
bool folio_xor_flags_has_waiters(struct folio *folio, unsigned long mask)
```

Change some folio flags.

**Parameters**

- `struct folio *folio`: The folio.
- `unsigned long mask`: Bits set in this word will be changed.

**Description**

This must only be used for flags which are changed with the folio
lock held.  For example, it is unsafe to use for PG_dirty as that
can be set without the folio lock held.  It can also only be used
on flags which are in the range 0-6 as some of the implementations
only affect those bits.

**Return**

Whether there are tasks waiting on the folio.

#### <a id="c-folio_test_uptodate"></a>`folio_test_uptodate()`

```c
bool folio_test_uptodate(const struct folio *folio)
```

Is this folio up to date?

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

The uptodate flag is set on a folio when every byte in the folio is
at least as new as the corresponding bytes on storage.  Anonymous
and CoW folios are always uptodate.  If the folio is not uptodate,
some of the bytes in it may be; see the `is_partially_uptodate()`
address_space operation.

#### <a id="c-folio_test_large"></a>`folio_test_large()`

```c
bool folio_test_large(const struct folio *folio)
```

Does this folio contain more than one page?

**Parameters**

- `const struct folio *folio`: The folio to test.

**Return**

True if the folio is larger than one page.

#### <a id="c-PageHuge"></a>`PageHuge()`

```c
bool PageHuge(const struct page *page)
```

Determine if the page belongs to hugetlbfs

**Parameters**

- `const struct page *page`: The page to test.

**Context**

Any context.

**Return**

True for hugetlbfs pages, false for anon pages or pages
belonging to other filesystems.

#### <a id="c-page_has_movable_ops"></a>`page_has_movable_ops()`

```c
bool page_has_movable_ops(const struct page *page)
```

test for a movable_ops page

**Parameters**

- `const struct page *page`: The page to test.

**Description**

Test whether this is a movable_ops page. Such pages will stay that
way until freed.

Returns true if this is a movable_ops page, otherwise false.

#### <a id="c-folio_has_private"></a>`folio_has_private()`

```c
int folio_has_private(const struct folio *folio)
```

Determine if folio has private stuff

**Parameters**

- `const struct folio *folio`: The folio to be checked

**Description**

Determine if a folio has private stuff, indicating that release routines
should be invoked upon it.



#### <a id="c-folio_page_idx"></a>`folio_page_idx()`

```c
unsigned long folio_page_idx(const struct folio *folio, const struct page *page)
```

Return the number of a page in a folio.

**Parameters**

- `const struct folio *folio`: The folio.
- `const struct page *page`: The folio page.

**Description**

This function expects that the page is actually part of the folio.
The returned number is relative to the start of the folio.

#### <a id="c-vma_flag_t"></a>`typedef vma_flag_t`

specifies an individual VMA flag by bit number.

**Description**

This value is made type safe by sparse to avoid passing invalid flag values
around.

#### <a id="c-fault_flag_allow_retry_first"></a>`fault_flag_allow_retry_first()`

```c
bool fault_flag_allow_retry_first(enum fault_flag flags)
```

check ALLOW_RETRY the first time

**Parameters**

- `enum fault_flag flags`: Fault flags.

**Description**

This is mostly used for places where we want to try to avoid taking
the mmap_lock for too long a time when waiting for another condition
to change, in which case we can try to be polite to release the
mmap_lock in the first round to avoid potential starvation of other
processes that would also want the mmap_lock.

**Return**

true if the page fault allows retry and this is the first
attempt of the fault handling; false otherwise.

#### <a id="c-folio_order"></a>`folio_order()`

```c
unsigned int folio_order(const struct folio *folio)
```

The allocation order of a folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

A folio is composed of 2^order pages.  See `get_order()` for the definition
of order.

**Return**

The order of the folio.

#### <a id="c-folio_reset_order"></a>`folio_reset_order()`

```c
void folio_reset_order(struct folio *folio)
```

Reset the folio order and derived _nr_pages

**Parameters**

- `struct folio *folio`: The folio.

**Description**

Reset the order and derived _nr_pages to 0. Must only be used in the
process of splitting large folios.

#### <a id="c-folio_mapcount"></a>`folio_mapcount()`

```c
int folio_mapcount(const struct folio *folio)
```

Number of mappings of this folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

The folio mapcount corresponds to the number of present user page table
entries that reference any part of a folio. Each such present user page
table entry must be paired with exactly on folio reference.

For ordindary folios, each user page table entry (PTE/PMD/PUD/...) counts
exactly once.

For hugetlb folios, each abstracted "hugetlb" user page table entry that
references the entire folio counts exactly once, even when such special
page table entries are comprised of multiple ordinary page table entries.

Will report 0 for pages which cannot be mapped into userspace, such as
slab, page tables and similar.

**Return**

The number of times this folio is mapped.

#### <a id="c-folio_mapped"></a>`folio_mapped()`

```c
bool folio_mapped(const struct folio *folio)
```

Is this folio mapped into userspace?

**Parameters**

- `const struct folio *folio`: The folio.

**Return**

True if any page in this folio is referenced by user page tables.

#### <a id="c-thp_order"></a>`thp_order()`

```c
unsigned int thp_order(struct page *page)
```

Order of a transparent huge page.

**Parameters**

- `struct page *page`: Head page of a transparent huge page.

#### <a id="c-thp_size"></a>`thp_size()`

```c
unsigned long thp_size(struct page *page)
```

Size of a transparent huge page.

**Parameters**

- `struct page *page`: Head page of a transparent huge page.

**Return**

Number of bytes in this page.

#### <a id="c-folio_get"></a>`folio_get()`

```c
void folio_get(struct folio *folio)
```

Increment the reference count on a folio.

**Parameters**

- `struct folio *folio`: The folio.

**Context**

May be called in any context, as long as you know that
you have a refcount on the folio.  If you do not already have one,
[`folio_try_get()`](#c-folio_try_get) may be the right interface for you to use.

#### <a id="c-folio_put"></a>`folio_put()`

```c
void folio_put(struct folio *folio)
```

Decrement the reference count on a folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

If the folio's reference count reaches zero, the memory will be
released back to the page allocator and may be used by another
allocation immediately.  Do not access the memory or the struct folio
after calling [`folio_put()`](#c-folio_put) unless you can be sure that it wasn't the
last reference.

**Context**

May be called in process or interrupt context, but not in NMI
context.  May be called while holding a spinlock.

#### <a id="c-folio_put_refs"></a>`folio_put_refs()`

```c
void folio_put_refs(struct folio *folio, int refs)
```

Reduce the reference count on a folio.

**Parameters**

- `struct folio *folio`: The folio.
- `int refs`: The amount to subtract from the folio's reference count.

**Description**

If the folio's reference count reaches zero, the memory will be
released back to the page allocator and may be used by another
allocation immediately.  Do not access the memory or the struct folio
after calling [`folio_put_refs()`](#c-folio_put_refs) unless you can be sure that these weren't
the last references.

**Context**

May be called in process or interrupt context, but not in NMI
context.  May be called while holding a spinlock.

#### <a id="c-folios_put"></a>`folios_put()`

```c
void folios_put(struct folio_batch *folios)
```

Decrement the reference count on an array of folios.

**Parameters**

- `struct folio_batch *folios`: The folios.

**Description**

Like [`folio_put()`](#c-folio_put), but for a batch of folios.  This is more efficient
than writing the loop yourself as it will optimise the locks which need
to be taken if the folios are freed.  The folios batch is returned
empty and ready to be reused for another batch; there is no need to
reinitialise it.

**Context**

May be called in process or interrupt context, but not in NMI
context.  May be called while holding a spinlock.

#### <a id="c-folio_pfn"></a>`folio_pfn()`

```c
unsigned long folio_pfn(const struct folio *folio)
```

Return the Page Frame Number of a folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

A folio may contain multiple pages.  The pages have consecutive
Page Frame Numbers.

**Return**

The Page Frame Number of the first page in the folio.

#### <a id="c-folio_mk_pte"></a>`folio_mk_pte()`

```c
pte_t folio_mk_pte(const struct folio *folio, pgprot_t pgprot)
```

Create a PTE for this folio

**Parameters**

- `const struct folio *folio`: The folio to create a PTE for
- `pgprot_t pgprot`: The page protection bits to use

**Description**

Create a page table entry for the first page of this folio.
This is suitable for passing to `set_ptes()`.

**Return**

A page table entry suitable for mapping this folio.

#### <a id="c-folio_mk_pmd"></a>`folio_mk_pmd()`

```c
pmd_t folio_mk_pmd(const struct folio *folio, pgprot_t pgprot)
```

Create a PMD for this folio

**Parameters**

- `const struct folio *folio`: The folio to create a PMD for
- `pgprot_t pgprot`: The page protection bits to use

**Description**

Create a page table entry for the first page of this folio.
This is suitable for passing to `set_pmd_at()`.

**Return**

A page table entry suitable for mapping this folio.

#### <a id="c-folio_mk_pud"></a>`folio_mk_pud()`

```c
pud_t folio_mk_pud(const struct folio *folio, pgprot_t pgprot)
```

Create a PUD for this folio

**Parameters**

- `const struct folio *folio`: The folio to create a PUD for
- `pgprot_t pgprot`: The page protection bits to use

**Description**

Create a page table entry for the first page of this folio.
This is suitable for passing to `set_pud_at()`.

**Return**

A page table entry suitable for mapping this folio.

#### <a id="c-folio_maybe_dma_pinned"></a>`folio_maybe_dma_pinned()`

```c
bool folio_maybe_dma_pinned(struct folio *folio)
```

Report if a folio may be pinned for DMA.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

This function checks if a folio has been pinned via a call to
a function in the `pin_user_pages()` family.

For small folios, the return value is partially fuzzy: false is not fuzzy,
because it means "definitely not pinned for DMA", but true means "probably
pinned for DMA, but possibly a false positive due to having at least
GUP_PIN_COUNTING_BIAS worth of normal folio references".

False positives are OK, because: a) it's unlikely for a folio to
get that many refcounts, and b) all the callers of this routine are
expected to be able to deal gracefully with a false positive.

For most large folios, the result will be exactly correct. That's because
we have more tracking data available: the _pincount field is used
instead of the GUP_PIN_COUNTING_BIAS scheme.

For more information, please see Documentation/core-api/pin_user_pages.rst.

**Return**

True, if it is likely that the folio has been "dma-pinned".
False, if the folio is definitely not dma-pinned.

#### <a id="c-is_zero_page"></a>`is_zero_page()`

```c
bool is_zero_page(const struct page *page)
```

Query if a page is a zero page

**Parameters**

- `const struct page *page`: The page to query

**Description**

This returns true if **page** is one of the permanent zero pages.

#### <a id="c-is_zero_folio"></a>`is_zero_folio()`

```c
bool is_zero_folio(const struct folio *folio)
```

Query if a folio is a zero page

**Parameters**

- `const struct folio *folio`: The folio to query

**Description**

This returns true if **folio** is one of the permanent zero pages.

#### <a id="c-folio_nr_pages"></a>`folio_nr_pages()`

```c
unsigned long folio_nr_pages(const struct folio *folio)
```

The number of pages in the folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Return**

A positive power of two.

#### <a id="c-folio_next"></a>`folio_next()`

```c
struct folio * folio_next(struct folio *folio)
```

Move to the next physical folio.

**Parameters**

- `struct folio *folio`: The folio we're currently operating on.

**Description**

If you have physically contiguous memory which may span more than
one folio (eg a `struct bio_vec`), use this function to move from one
folio to the next.  Do not use it if the memory is only virtually
contiguous as the folios are almost certainly not adjacent to each
other.  This is the folio equivalent to writing `page++`.

**Context**

We assume that the folios are refcounted and/or locked at a
higher level and do not adjust the reference counts.

**Return**

The next struct folio.

#### <a id="c-folio_shift"></a>`folio_shift()`

```c
unsigned int folio_shift(const struct folio *folio)
```

The size of the memory described by this folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

A folio represents a number of bytes which is a power-of-two in size.
This function tells you which power-of-two the folio is.  See also
[`folio_size()`](#c-folio_size) and [`folio_order()`](#c-folio_order).

**Context**

The caller should have a reference on the folio to prevent
it from being split.  It is not necessary for the folio to be locked.

**Return**

The base-2 logarithm of the size of this folio.

#### <a id="c-folio_size"></a>`folio_size()`

```c
size_t folio_size(const struct folio *folio)
```

The number of bytes in a folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Context**

The caller should have a reference on the folio to prevent
it from being split.  It is not necessary for the folio to be locked.

**Return**

The number of bytes in this folio.

#### <a id="c-folio_maybe_mapped_shared"></a>`folio_maybe_mapped_shared()`

```c
bool folio_maybe_mapped_shared(struct folio *folio)
```

Whether the folio is mapped into the page tables of more than one MM

**Parameters**

- `struct folio *folio`: The folio.

**Description**

This function checks if the folio maybe currently mapped into more than one
MM ("maybe mapped shared"), or if the folio is certainly mapped into a single
MM ("mapped exclusively").

For KSM folios, this function also returns "mapped shared" when a folio is
mapped multiple times into the same MM, because the individual page mappings
are independent.

For small anonymous folios and anonymous hugetlb folios, the return
value will be exactly correct: non-KSM folios can only be mapped at most once
into an MM, and they cannot be partially mapped. KSM folios are
considered shared even if mapped multiple times into the same MM.

- For other folios, the result can be fuzzy:
  1. For partially-mappable large folios (THP), the return value can wrongly
     indicate "mapped shared" (false positive) if a folio was mapped by
     more than two MMs at one point in time.
  1. For pagecache folios (including hugetlb), the return value can wrongly
     indicate "mapped shared" (false positive) when two VMAs in the same MM
     cover the same file range.

Further, this function only considers current page table mappings that
are tracked using the folio mapcount(s).

- This function does not consider:
  1. If the folio might get mapped in the (near) future (e.g., swapcache,
     pagecache, temporary unmapping for migration).
  1. If the folio is mapped differently (VM_PFNMAP).
  1. If hugetlb page table sharing applies. Callers might want to check
     `hugetlb_pmd_shared()`.

**Return**

Whether the folio is estimated to be mapped into more than one MM.

#### <a id="c-folio_expected_ref_count"></a>`folio_expected_ref_count()`

```c
int folio_expected_ref_count(const struct folio *folio)
```

calculate the expected folio refcount

**Parameters**

- `const struct folio *folio`: the folio

**Description**

Calculate the expected folio refcount, taking references from the pagecache,
swapcache, PG_private and page table mappings into account. Useful in
combination with [`folio_ref_count()`](#c-folio_ref_count) to detect unexpected references (e.g.,
GUP or other temporary references).

Does currently not consider references from the LRU cache. If the folio
was isolated from the LRU (which is the case during migration or split),
the LRU cache does not apply.

Calling this function on an unmapped folio -- \![`folio_mapped()`](#c-folio_mapped) -- that is
locked will return a stable result.

Calling this function on a mapped folio will not result in a stable result,
because nothing stops additional page table mappings from coming (e.g.,
`fork()`) or going (e.g., `munmap()`).

Calling this function without the folio lock will also not result in a
stable result: for example, the folio might get dropped from the swapcache
concurrently.

However, even when called without the folio lock or on a mapped folio,
this function can be used to detect unexpected references early (for example,
if it makes sense to even lock the folio and unmap it).

The caller must add any reference (e.g., from [`folio_try_get()`](#c-folio_try_get)) it might be
holding itself to the result.

Returns the expected folio refcount.

#### <a id="c-ptdesc_address"></a>`ptdesc_address()`

```c
void * ptdesc_address(const struct ptdesc *pt)
```

Virtual address of page table.

**Parameters**

- `const struct ptdesc *pt`: Page table descriptor.

**Return**

The first byte of the page table described by **pt**.

#### <a id="c-ptdesc_set_kernel"></a>`ptdesc_set_kernel()`

```c
void ptdesc_set_kernel(struct ptdesc *ptdesc)
```

Mark a ptdesc used to map the kernel

**Parameters**

- `struct ptdesc *ptdesc`: The ptdesc to be marked

**Description**

Kernel page tables often need special handling. Set a flag so that
the handling code knows this ptdesc will not be used for userspace.

#### <a id="c-ptdesc_clear_kernel"></a>`ptdesc_clear_kernel()`

```c
void ptdesc_clear_kernel(struct ptdesc *ptdesc)
```

Mark a ptdesc as no longer used to map the kernel

**Parameters**

- `struct ptdesc *ptdesc`: The ptdesc to be unmarked

**Description**

Use when the ptdesc is no longer used to map the kernel and no longer
needs special handling.

#### <a id="c-ptdesc_test_kernel"></a>`ptdesc_test_kernel()`

```c
bool ptdesc_test_kernel(const struct ptdesc *ptdesc)
```

Check if a ptdesc is used to map the kernel

**Parameters**

- `const struct ptdesc *ptdesc`: The ptdesc being tested

**Description**

Call to tell if the ptdesc used to map the kernel.

#### <a id="c-pagetable_alloc"></a>`pagetable_alloc()`

```c
struct ptdesc * pagetable_alloc(gfp_t gfp, unsigned int order)
```

Allocate pagetables

**Parameters**

- `gfp_t gfp`: GFP flags
- `unsigned int order`: desired pagetable order

**Description**

pagetable_alloc allocates memory for page tables as well as a page table
descriptor to describe that memory.

**Return**

The ptdesc describing the allocated page tables.

#### <a id="c-pagetable_free"></a>`pagetable_free()`

```c
void pagetable_free(struct ptdesc *pt)
```

Free pagetables

**Parameters**

- `struct ptdesc *pt`: The page table descriptor

**Description**

pagetable_free frees the memory of all page tables described by a page
table descriptor and the memory for the descriptor itself.

#### <a id="c-vma_lookup"></a>`vma_lookup()`

```c
struct vm_area_struct * vma_lookup(struct mm_struct *mm, unsigned long addr)
```

Find a VMA at a specific address

**Parameters**

- `struct mm_struct *mm`: The process address space.
- `unsigned long addr`: The user address.

**Return**

The vm_area_struct at the given address, `NULL` otherwise.

#### <a id="c-mmap_action_remap"></a>`mmap_action_remap()`

```c
void mmap_action_remap(struct vm_area_desc *desc, unsigned long start, unsigned long start_pfn, unsigned long size)
```

helper for mmap_prepare hook to specify that a pure PFN remap is required.

**Parameters**

- `struct vm_area_desc *desc`: The VMA descriptor for the VMA requiring remap.
- `unsigned long start`: The virtual address to start the remap from, must be within the VMA.
- `unsigned long start_pfn`: The first PFN in the range to remap.
- `unsigned long size`: The size of the range to remap, in bytes, at most spanning to the end
  of the VMA.

#### <a id="c-mmap_action_remap_full"></a>`mmap_action_remap_full()`

```c
void mmap_action_remap_full(struct vm_area_desc *desc, unsigned long start_pfn)
```

helper for mmap_prepare hook to specify that the entirety of a VMA should be PFN remapped.

**Parameters**

- `struct vm_area_desc *desc`: The VMA descriptor for the VMA requiring remap.
- `unsigned long start_pfn`: The first PFN in the range to remap.

#### <a id="c-mmap_action_ioremap"></a>`mmap_action_ioremap()`

```c
void mmap_action_ioremap(struct vm_area_desc *desc, unsigned long start, unsigned long start_pfn, unsigned long size)
```

helper for mmap_prepare hook to specify that a pure PFN I/O remap is required.

**Parameters**

- `struct vm_area_desc *desc`: The VMA descriptor for the VMA requiring remap.
- `unsigned long start`: The virtual address to start the remap from, must be within the VMA.
- `unsigned long start_pfn`: The first PFN in the range to remap.
- `unsigned long size`: The size of the range to remap, in bytes, at most spanning to the end
  of the VMA.

#### <a id="c-mmap_action_ioremap_full"></a>`mmap_action_ioremap_full()`

```c
void mmap_action_ioremap_full(struct vm_area_desc *desc, unsigned long start_pfn)
```

helper for mmap_prepare hook to specify that the entirety of a VMA should be PFN I/O remapped.

**Parameters**

- `struct vm_area_desc *desc`: The VMA descriptor for the VMA requiring remap.
- `unsigned long start_pfn`: The first PFN in the range to remap.

#### <a id="c-clear_pages"></a>`clear_pages()`

```c
void clear_pages(void *addr, unsigned int npages)
```

clear a page range for kernel-internal use.

**Parameters**

- `void *addr`: start address
- `unsigned int npages`: number of pages

**Description**

Use [`clear_user_pages()`](/kernel/internals/mm/highmem.md#c-clear_user_pages) instead when clearing a page range to be
mapped to user space.

Does absolutely no exception handling.

Note that even though the clearing operation is preemptible, [`clear_pages()`](#c-clear_pages)
does not (and on architectures where it reduces to a few long-running
instructions, might not be able to) call `cond_resched()` to check if
rescheduling is required.

When running under preemptible models this is not a problem. Under
cooperatively scheduled models, however, the caller is expected to
limit **npages** to no more than PROCESS_PAGES_NON_PREEMPT_BATCH.

#### <a id="c-vma_is_special_huge"></a>`vma_is_special_huge()`

```c
bool vma_is_special_huge(const struct vm_area_struct *vma)
```

Are transhuge page-table entries considered special?

**Parameters**

- `const struct vm_area_struct *vma`: Pointer to the struct vm_area_struct to consider

**Description**

Whether transhuge page-table entries are considered "special" following
the definition in `vm_normal_page()`.

**Return**

true if transhuge page-table entries should be considered special,
false otherwise.



#### <a id="c-folio_ref_count"></a>`folio_ref_count()`

```c
int folio_ref_count(const struct folio *folio)
```

The reference count on this folio.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

The refcount is usually incremented by calls to [`folio_get()`](#c-folio_get) and
decremented by calls to [`folio_put()`](#c-folio_put).  Some typical users of the
folio refcount:

- Each reference from a page table
- The page cache
- Filesystem private data
- The LRU list
- Pipes
- Direct IO which references this page in the process address space

**Return**

The number of references to this folio.

#### <a id="c-folio_try_get"></a>`folio_try_get()`

```c
bool folio_try_get(struct folio *folio)
```

Attempt to increase the refcount on a folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

If you do not already have a reference to a folio, you can attempt to
get one using this function.  It may fail if, for example, the folio
has been freed since you found a pointer to it, or it is frozen for
the purposes of splitting or migration.

**Return**

True if the reference count was successfully incremented.



#### <a id="c-is_highmem"></a>`is_highmem()`

```c
int is_highmem(const struct zone *zone)
```

helper function to quickly check if a struct zone is a highmem zone or not. This is an attempt to keep references to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum.

**Parameters**

- `const struct zone *zone`: pointer to struct zone variable

**Return**

1 for a highmem zone, 0 otherwise

#### <a id="c-for_each_online_pgdat"></a>`for_each_online_pgdat()`

```c
for_each_online_pgdat(pgdat)
```

helper macro to iterate over all online nodes

**Parameters**

- `pgdat`: pointer to a pg_data_t variable

#### <a id="c-for_each_zone"></a>`for_each_zone()`

```c
for_each_zone(zone)
```

helper macro to iterate over all memory zones

**Parameters**

- `zone`: pointer to struct zone variable

**Description**

The user only needs to declare the zone variable, for_each_zone
fills it in.

#### <a id="c-next_zones_zonelist"></a>`next_zones_zonelist()`

```c
struct zoneref * next_zones_zonelist(struct zoneref *z, enum zone_type highest_zoneidx, nodemask_t *nodes)
```

Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point

**Parameters**

- `struct zoneref *z`: The cursor used as a starting point for the search
- `enum zone_type highest_zoneidx`: The zone index of the highest zone to return
- `nodemask_t *nodes`: An optional nodemask to filter the zonelist with

**Description**

This function returns the next zone at or below a given zone index that is
within the allowed nodemask using a cursor as the starting point for the
search. The zoneref returned is a cursor that represents the current zone
being examined. It should be advanced by one before calling
next_zones_zonelist again.

**Return**

the next zone at or below highest_zoneidx within the allowed
nodemask using a cursor within a zonelist as a starting point

#### <a id="c-first_zones_zonelist"></a>`first_zones_zonelist()`

```c
struct zoneref * first_zones_zonelist(struct zonelist *zonelist, enum zone_type highest_zoneidx, nodemask_t *nodes)
```

Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist

**Parameters**

- `struct zonelist *zonelist`: The zonelist to search for a suitable zone
- `enum zone_type highest_zoneidx`: The zone index of the highest zone to return
- `nodemask_t *nodes`: An optional nodemask to filter the zonelist with

**Description**

This function returns the first zone at or below a given zone index that is
within the allowed nodemask. The zoneref returned is a cursor that can be
used to iterate the zonelist with next_zones_zonelist by advancing it by
one before calling.

When no eligible zone is found, zoneref->zone is NULL (zoneref itself is
never NULL). This may happen either genuinely, or due to concurrent nodemask
update due to cpuset modification.

**Return**

Zoneref pointer for the first suitable zone found

#### <a id="c-for_each_zone_zonelist_nodemask"></a>`for_each_zone_zonelist_nodemask()`

```c
for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask)
```

helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask

**Parameters**

- `zone`: The current zone in the iterator
- `z`: The current pointer within zonelist->_zonerefs being iterated
- `zlist`: The zonelist being iterated
- `highidx`: The zone index of the highest zone to return
- `nodemask`: Nodemask allowed by the allocator

**Description**

This iterator iterates though all zones at or below a given zone index and
within a given nodemask

#### <a id="c-for_each_zone_zonelist"></a>`for_each_zone_zonelist()`

```c
for_each_zone_zonelist(zone, z, zlist, highidx)
```

helper macro to iterate over valid zones in a zonelist at or below a given zone index

**Parameters**

- `zone`: The current zone in the iterator
- `z`: The current pointer within zonelist->zones being iterated
- `zlist`: The zonelist being iterated
- `highidx`: The zone index of the highest zone to return

**Description**

This iterator iterates though all zones at or below a given zone index.

#### <a id="c-pfn_valid"></a>`pfn_valid()`

```c
int pfn_valid(unsigned long pfn)
```

check if there is a valid memory map entry for a PFN

**Parameters**

- `unsigned long pfn`: the page frame number to check

**Description**

Check if there is a valid memory map entry aka struct page for the **pfn**.
Note, that availability of the memory map entry does not imply that
there is actual usable memory at that **pfn**. The struct page may
represent a hole or an unusable page frame.

**Return**

1 for PFNs that have memory map entries and 0 otherwise



#### <a id="c-folio_mapping"></a>`folio_mapping()`

```c
struct address_space * folio_mapping(const struct folio *folio)
```

Find the mapping where this folio is stored.

**Parameters**

- `const struct folio *folio`: The folio.

**Description**

For folios which are in the page cache, return the mapping that this
page belongs to.  Folios in the swap cache return the swap mapping
this page is stored in (which is different from the mapping for the
swap file or swap device where the data is stored).

You can call this for folios which aren't in the swap cache or page
cache and it will return NULL.



#### <a id="c-__anon_vma_prepare"></a>`__anon_vma_prepare()`

```c
int __anon_vma_prepare(struct vm_area_struct *vma)
```

attach an anon_vma to a memory region

**Parameters**

- `struct vm_area_struct *vma`: the memory region in question

**Description**

This makes sure the memory mapping described by 'vma' has
an 'anon_vma' attached to it, so that we can associate the
anonymous pages mapped into it with that anon_vma.

The common case will be that we already have one, which
is handled inline by `anon_vma_prepare()`. But if
not we either need to find an adjacent mapping that we
can re-use the anon_vma from (very common when the only
reason for splitting a vma has been `mprotect()`), or we
allocate a new one.

Anon-vma allocations are very subtle, because we may have
optimistically looked up an anon_vma in `folio_lock_anon_vma_read()`
and that may actually touch the rwsem even in the newly
allocated vma (it depends on RCU to make sure that the
anon_vma isn't actually destroyed).

As a result, we need to do proper anon_vma locking even
for the new allocation. At the same time, we do not want
to do any locking for the common case of already having
an anon_vma.

#### <a id="c-anon_vma_clone"></a>`anon_vma_clone()`

```c
int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src, enum vma_operation operation)
```

Establishes new anon_vma_chain objects in **dst** linking to all of the anon_vma objects contained within **src** anon_vma_chain's.

**Parameters**

- `struct vm_area_struct *dst`: The destination VMA with an empty anon_vma_chain.
- `struct vm_area_struct *src`: The source VMA we wish to duplicate.
- `enum vma_operation operation`: The type of operation which resulted in the clone.

**Description**

This is the heart of the VMA side of the anon_vma implementation - we invoke
this function whenever we need to set up a new VMA's anon_vma state.

This is invoked for:

- VMA Merge, but only when **dst** is unfaulted and **src** is faulted - meaning we
  clone **src** into **dst**.
- VMA split.
- VMA (m)remap.
- Fork of faulted VMA.

In all cases other than fork this is simply a duplication. Fork additionally
adds a new active anon_vma.

ONLY in the case of fork do we try to 'reuse' existing anon_vma's in an
anon_vma hierarchy, reusing anon_vma's which have no VMA associated with them
but do have a single child. This is to avoid waste of memory when repeatedly
forking.

**Return**

0 on success, -ENOMEM on failure.

#### <a id="c-unlink_anon_vmas"></a>`unlink_anon_vmas()`

```c
void unlink_anon_vmas(struct vm_area_struct *vma)
```

remove all links between a VMA and anon_vma's, freeing anon_vma_chain objects.

**Parameters**

- `struct vm_area_struct *vma`: The VMA whose links to anon_vma objects is to be severed.

**Description**

As part of the process anon_vma_chain's are freed,
anon_vma->num_children,num_active_vmas is updated as required and, if the
relevant anon_vma references no further VMAs, its reference count is
decremented.

#### <a id="c-page_address_in_vma"></a>`page_address_in_vma()`

```c
unsigned long page_address_in_vma(const struct folio *folio, const struct page *page, const struct vm_area_struct *vma)
```

The virtual address of a page in this VMA.

**Parameters**

- `const struct folio *folio`: The folio containing the page.
- `const struct page *page`: The page within the folio.
- `const struct vm_area_struct *vma`: The VMA we need to know the address in.

**Description**

Calculates the user virtual address of this page in the specified VMA.
It is the caller's responsibility to check the page is actually
within the VMA.  There may not currently be a PTE pointing at this
page, but if a page fault occurs at this address, this is the page
which will be accessed.

**Context**

Caller should hold a reference to the folio.  Caller should
hold a lock (eg the i_mmap_lock or the mmap_lock) which keeps the
VMA from being altered.

**Return**

The virtual address corresponding to this page in the VMA.

#### <a id="c-folio_referenced"></a>`folio_referenced()`

```c
int folio_referenced(struct folio *folio, int is_locked, struct mem_cgroup *memcg, vm_flags_t *vm_flags)
```

Test if the folio was referenced.

**Parameters**

- `struct folio *folio`: The folio to test.
- `int is_locked`: Caller holds lock on the folio.
- `struct mem_cgroup *memcg`: target memory cgroup
- `vm_flags_t *vm_flags`: A combination of all the vma->vm_flags which referenced the folio.

**Description**

Quick test_and_clear_referenced for all mappings of a folio,

**Return**

The number of mappings which referenced the folio. Return -1 if
the function bailed out due to rmap lock contention.

#### <a id="c-mapping_wrprotect_range"></a>`mapping_wrprotect_range()`

```c
int mapping_wrprotect_range(struct address_space *mapping, pgoff_t pgoff, unsigned long pfn, unsigned long nr_pages)
```

Write-protect all mappings in a specified range.

**Parameters**

- `struct address_space *mapping`: The mapping whose reverse mapping should be traversed.
- `pgoff_t pgoff`: The page offset at which **pfn** is mapped within **mapping**.
- `unsigned long pfn`: The PFN of the page mapped in **mapping** at **pgoff**.
- `unsigned long nr_pages`: The number of physically contiguous base pages spanned.

**Description**

Traverses the reverse mapping, finding all VMAs which contain a shared
mapping of the pages in the specified range in **mapping**, and write-protects
them (that is, updates the page tables to mark the mappings read-only such
that a write protection fault arises when the mappings are written to).

The **pfn** value need not refer to a folio, but rather can reference a kernel
allocation which is mapped into userland. We therefore do not require that
the page maps to a folio with a valid mapping or index field, rather the
caller specifies these in **mapping** and **pgoff**.

**Return**

the number of write-protected PTEs, or an error.

#### <a id="c-pfn_mkclean_range"></a>`pfn_mkclean_range()`

```c
int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff, struct vm_area_struct *vma)
```

Cleans the PTEs (including PMDs) mapped with range of \[**pfn**, **pfn** + **nr_pages**) at the specific offset (**pgoff**) within the **vma** of shared mappings. And since clean PTEs should also be readonly, write protects them too.

**Parameters**

- `unsigned long pfn`: start pfn.
- `unsigned long nr_pages`: number of physically contiguous pages srarting with **pfn**.
- `pgoff_t pgoff`: page offset that the **pfn** mapped with.
- `struct vm_area_struct *vma`: vma that **pfn** mapped within.

**Description**

Returns the number of cleaned PTEs (including PMDs).

#### <a id="c-folio_move_anon_rmap"></a>`folio_move_anon_rmap()`

```c
void folio_move_anon_rmap(struct folio *folio, struct vm_area_struct *vma)
```

move a folio to our anon_vma

**Parameters**

- `struct folio *folio`: The folio to move to our anon_vma
- `struct vm_area_struct *vma`: The vma the folio belongs to

**Description**

When a folio belongs exclusively to one process after a COW event,
that folio can be moved into the anon_vma that belongs to just that
process, so the rmap code will not search the parent or sibling processes.

#### <a id="c-__folio_set_anon"></a>`__folio_set_anon()`

```c
void __folio_set_anon(struct folio *folio, struct vm_area_struct *vma, unsigned long address, bool exclusive)
```

set up a new anonymous rmap for a folio

**Parameters**

- `struct folio *folio`: The folio to set up the new anonymous rmap for.
- `struct vm_area_struct *vma`: VM area to add the folio to.
- `unsigned long address`: User virtual address of the mapping
- `bool exclusive`: Whether the folio is exclusive to the process.

#### <a id="c-__page_check_anon_rmap"></a>`__page_check_anon_rmap()`

```c
void __page_check_anon_rmap(const struct folio *folio, const struct page *page, struct vm_area_struct *vma, unsigned long address)
```

sanity check anonymous rmap addition

**Parameters**

- `const struct folio *folio`: The folio containing **page**.
- `const struct page *page`: the page to check the mapping of
- `struct vm_area_struct *vma`: the vm area in which the mapping is added
- `unsigned long address`: the user virtual address mapped

#### <a id="c-folio_add_anon_rmap_ptes"></a>`folio_add_anon_rmap_ptes()`

```c
void folio_add_anon_rmap_ptes(struct folio *folio, struct page *page, int nr_pages, struct vm_area_struct *vma, unsigned long address, rmap_t flags)
```

add PTE mappings to a page range of an anon folio

**Parameters**

- `struct folio *folio`: The folio to add the mappings to
- `struct page *page`: The first page to add
- `int nr_pages`: The number of pages which will be mapped
- `struct vm_area_struct *vma`: The vm area in which the mappings are added
- `unsigned long address`: The user virtual address of the first page to map
- `rmap_t flags`: The rmap flags

**Description**

The page range of folio is defined by \[first_page, first_page + nr_pages)

The caller needs to hold the page table lock, and the page must be locked in
the anon_vma case: to serialize mapping,index checking after setting,
and to ensure that an anon folio is not being upgraded racily to a KSM folio
(but KSM folios are never downgraded).

#### <a id="c-folio_add_anon_rmap_pmd"></a>`folio_add_anon_rmap_pmd()`

```c
void folio_add_anon_rmap_pmd(struct folio *folio, struct page *page, struct vm_area_struct *vma, unsigned long address, rmap_t flags)
```

add a PMD mapping to a page range of an anon folio

**Parameters**

- `struct folio *folio`: The folio to add the mapping to
- `struct page *page`: The first page to add
- `struct vm_area_struct *vma`: The vm area in which the mapping is added
- `unsigned long address`: The user virtual address of the first page to map
- `rmap_t flags`: The rmap flags

**Description**

The page range of folio is defined by \[first_page, first_page + HPAGE_PMD_NR)

The caller needs to hold the page table lock, and the page must be locked in
the anon_vma case: to serialize mapping,index checking after setting.

#### <a id="c-folio_add_new_anon_rmap"></a>`folio_add_new_anon_rmap()`

```c
void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma, unsigned long address, rmap_t flags)
```

Add mapping to a new anonymous folio.

**Parameters**

- `struct folio *folio`: The folio to add the mapping to.
- `struct vm_area_struct *vma`: the vm area in which the mapping is added
- `unsigned long address`: the user virtual address mapped
- `rmap_t flags`: The rmap flags

**Description**

Like folio_add_anon_rmap_*() but must only be called on *new* folios.
This means the inc-and-test can be bypassed.
The folio doesn't necessarily need to be locked while it's exclusive
unless two threads map it concurrently. However, the folio must be
locked if it's shared.

If the folio is pmd-mappable, it is accounted as a THP.

#### <a id="c-folio_add_file_rmap_ptes"></a>`folio_add_file_rmap_ptes()`

```c
void folio_add_file_rmap_ptes(struct folio *folio, struct page *page, int nr_pages, struct vm_area_struct *vma)
```

add PTE mappings to a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to add the mappings to
- `struct page *page`: The first page to add
- `int nr_pages`: The number of pages that will be mapped using PTEs
- `struct vm_area_struct *vma`: The vm area in which the mappings are added

**Description**

The page range of the folio is defined by \[page, page + nr_pages)

The caller needs to hold the page table lock.

#### <a id="c-folio_add_file_rmap_pmd"></a>`folio_add_file_rmap_pmd()`

```c
void folio_add_file_rmap_pmd(struct folio *folio, struct page *page, struct vm_area_struct *vma)
```

add a PMD mapping to a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to add the mapping to
- `struct page *page`: The first page to add
- `struct vm_area_struct *vma`: The vm area in which the mapping is added

**Description**

The page range of the folio is defined by \[page, page + HPAGE_PMD_NR)

The caller needs to hold the page table lock.

#### <a id="c-folio_add_file_rmap_pud"></a>`folio_add_file_rmap_pud()`

```c
void folio_add_file_rmap_pud(struct folio *folio, struct page *page, struct vm_area_struct *vma)
```

add a PUD mapping to a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to add the mapping to
- `struct page *page`: The first page to add
- `struct vm_area_struct *vma`: The vm area in which the mapping is added

**Description**

The page range of the folio is defined by \[page, page + HPAGE_PUD_NR)

The caller needs to hold the page table lock.

#### <a id="c-folio_remove_rmap_ptes"></a>`folio_remove_rmap_ptes()`

```c
void folio_remove_rmap_ptes(struct folio *folio, struct page *page, int nr_pages, struct vm_area_struct *vma)
```

remove PTE mappings from a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to remove the mappings from
- `struct page *page`: The first page to remove
- `int nr_pages`: The number of pages that will be removed from the mapping
- `struct vm_area_struct *vma`: The vm area from which the mappings are removed

**Description**

The page range of the folio is defined by \[page, page + nr_pages)

The caller needs to hold the page table lock.

#### <a id="c-folio_remove_rmap_pmd"></a>`folio_remove_rmap_pmd()`

```c
void folio_remove_rmap_pmd(struct folio *folio, struct page *page, struct vm_area_struct *vma)
```

remove a PMD mapping from a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to remove the mapping from
- `struct page *page`: The first page to remove
- `struct vm_area_struct *vma`: The vm area from which the mapping is removed

**Description**

The page range of the folio is defined by \[page, page + HPAGE_PMD_NR)

The caller needs to hold the page table lock.

#### <a id="c-folio_remove_rmap_pud"></a>`folio_remove_rmap_pud()`

```c
void folio_remove_rmap_pud(struct folio *folio, struct page *page, struct vm_area_struct *vma)
```

remove a PUD mapping from a page range of a folio

**Parameters**

- `struct folio *folio`: The folio to remove the mapping from
- `struct page *page`: The first page to remove
- `struct vm_area_struct *vma`: The vm area from which the mapping is removed

**Description**

The page range of the folio is defined by \[page, page + HPAGE_PUD_NR)

The caller needs to hold the page table lock.

#### <a id="c-try_to_unmap"></a>`try_to_unmap()`

```c
void try_to_unmap(struct folio *folio, enum ttu_flags flags)
```

Try to remove all page table mappings to a folio.

**Parameters**

- `struct folio *folio`: The folio to unmap.
- `enum ttu_flags flags`: action and flags

**Description**

Tries to remove all the page table entries which are mapping this
folio.  It is the caller's responsibility to check if the folio is
still mapped if needed (use TTU_SYNC to prevent accounting races).

**Context**

Caller must hold the folio lock.

#### <a id="c-try_to_migrate"></a>`try_to_migrate()`

```c
void try_to_migrate(struct folio *folio, enum ttu_flags flags)
```

try to replace all page table mappings with swap entries

**Parameters**

- `struct folio *folio`: the folio to replace page table entries for
- `enum ttu_flags flags`: action and flags

**Description**

Tries to remove all the page table entries which are mapping this folio and
replace them with special swap entries. Caller must hold the folio lock.

#### <a id="c-make_device_exclusive"></a>`make_device_exclusive()`

```c
struct page * make_device_exclusive(struct mm_struct *mm, unsigned long addr, void *owner, struct folio **foliop)
```

Mark a page for exclusive use by a device

**Parameters**

- `struct mm_struct *mm`: mm_struct of associated target process
- `unsigned long addr`: the virtual address to mark for exclusive device access
- `void *owner`: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
- `struct folio **foliop`: folio pointer will be stored here on success.

**Description**

This function looks up the page mapped at the given address, grabs a
folio reference, locks the folio and replaces the PTE with special
device-exclusive PFN swap entry, preventing access through the process
page tables. The function will return with the folio locked and referenced.

On fault, the device-exclusive entries are replaced with the original PTE
under folio lock, after calling MMU notifiers.

Only anonymous non-hugetlb folios are supported and the VMA must have
write permissions such that we can fault in the anonymous page writable
in order to mark it exclusive. The caller must hold the mmap_lock in read
mode.

A driver using this to program access from a device must use a mmu notifier
critical section to hold a device specific lock during programming. Once
programming is complete it should drop the folio lock and reference after
which point CPU access to the page will revoke the exclusive access.

**Notes**

1. This function always operates on individual PTEs mapping individual
   pages. PMD-sized THPs are first remapped to be mapped by PTEs before
   the conversion happens on a single PTE corresponding to **addr**.
1. While concurrent access through the process page tables is prevented,
   concurrent access through other page references (e.g., earlier GUP
   invocation) is not handled and not supported.
1. device-exclusive entries are considered "clean" and "old" by core-mm.
   Device drivers must update the folio state when informed by MMU
   notifiers.

**Return**

pointer to mapped page on success, otherwise a negative error.

#### <a id="c-__rmap_walk_file"></a>`__rmap_walk_file()`

```c
void __rmap_walk_file(struct folio *folio, struct address_space *mapping, pgoff_t pgoff_start, unsigned long nr_pages, struct rmap_walk_control *rwc, bool locked)
```

Traverse the reverse mapping for a file-backed mapping of a page mapped within a specified page cache object at a specified offset.

**Parameters**

- `struct folio *folio`: Either the folio whose mappings to traverse, or if NULL,
  the callbacks specified in **rwc** will be configured such
  as to be able to look up mappings correctly.
- `struct address_space *mapping`: The page cache object whose mapping VMAs we intend to
  traverse. If **folio** is non-NULL, this should be equal to
  folio_mapping(folio).
- `pgoff_t pgoff_start`: The offset within **mapping** of the page which we are
  looking up. If **folio** is non-NULL, this should be equal
  to folio_pgoff(folio).
- `unsigned long nr_pages`: The number of pages mapped by the mapping. If **folio** is
  non-NULL, this should be equal to folio_nr_pages(folio).
- `struct rmap_walk_control *rwc`: The reverse mapping walk control object describing how
  the traversal should proceed.
- `bool locked`: Is the **mapping** already locked? If not, we acquire the
  lock.



#### <a id="c-isolate_movable_ops_page"></a>`isolate_movable_ops_page()`

```c
bool isolate_movable_ops_page(struct page *page, isolate_mode_t mode)
```

isolate a movable_ops page for migration

**Parameters**

- `struct page *page`: The page.
- `isolate_mode_t mode`: The isolation mode.

**Description**

Try to isolate a movable_ops page for migration. Will fail if the page is
not a movable_ops page, if the page is already isolated for migration
or if the page was just was released by its owner.

Once isolated, the page cannot get freed until it is either putback
or migrated.

Returns true if isolation succeeded, otherwise false.

#### <a id="c-putback_movable_ops_page"></a>`putback_movable_ops_page()`

```c
void putback_movable_ops_page(struct page *page)
```

putback an isolated movable_ops page

**Parameters**

- `struct page *page`: The isolated page.

**Description**

Putback an isolated movable_ops page.

After the page was putback, it might get freed instantly.

#### <a id="c-migrate_movable_ops_page"></a>`migrate_movable_ops_page()`

```c
int migrate_movable_ops_page(struct page *dst, struct page *src, enum migrate_mode mode)
```

migrate an isolated movable_ops page

**Parameters**

- `struct page *dst`: The destination page.
- `struct page *src`: The source page.
- `enum migrate_mode mode`: The migration mode.

**Description**

Migrate an isolated movable_ops page.

If the src page was already released by its owner, the src page is
un-isolated (putback) and migration succeeds; the migration core will be the
owner of both pages.

If the src page was not released by its owner and the migration was
successful, the owner of the src page and the dst page are swapped and
the src page is un-isolated.

If migration fails, the ownership stays unmodified and the src page
remains isolated: migration may be retried later or the page can be putback.

TODO: migration core will treat both pages as folios and lock them before
this call to unlock them after this call. Further, the folio refcounts on
src and dst are also released by migration core. These pages will not be
folios in the future, so that must be reworked.

Returns 0 on success, otherwise a negative error code.

#### <a id="c-migrate_folio"></a>`migrate_folio()`

```c
int migrate_folio(struct address_space *mapping, struct folio *dst, struct folio *src, enum migrate_mode mode)
```

Simple folio migration.

**Parameters**

- `struct address_space *mapping`: The address_space containing the folio.
- `struct folio *dst`: The folio to migrate the data to.
- `struct folio *src`: The folio containing the current data.
- `enum migrate_mode mode`: How to migrate the page.

**Description**

Common logic to directly migrate a single LRU folio suitable for
folios that do not have private data.

Folios are locked upon entry and exit.

#### <a id="c-buffer_migrate_folio"></a>`buffer_migrate_folio()`

```c
int buffer_migrate_folio(struct address_space *mapping, struct folio *dst, struct folio *src, enum migrate_mode mode)
```

Migration function for folios with buffers.

**Parameters**

- `struct address_space *mapping`: The address space containing **src**.
- `struct folio *dst`: The folio to migrate to.
- `struct folio *src`: The folio to migrate from.
- `enum migrate_mode mode`: How to migrate the folio.

**Description**

This function can only be used if the underlying filesystem guarantees
that no other references to **src** exist. For example attached buffer
heads are accessed only under the folio lock.  If your filesystem cannot
provide this guarantee, [`buffer_migrate_folio_norefs()`](#c-buffer_migrate_folio_norefs) may be more
appropriate.

**Return**

0 on success or a negative errno on failure.

#### <a id="c-buffer_migrate_folio_norefs"></a>`buffer_migrate_folio_norefs()`

```c
int buffer_migrate_folio_norefs(struct address_space *mapping, struct folio *dst, struct folio *src, enum migrate_mode mode)
```

Migration function for folios with buffers.

**Parameters**

- `struct address_space *mapping`: The address space containing **src**.
- `struct folio *dst`: The folio to migrate to.
- `struct folio *src`: The folio to migrate from.
- `enum migrate_mode mode`: How to migrate the folio.

**Description**

Like [`buffer_migrate_folio()`](#c-buffer_migrate_folio) except that this variant is more careful
and checks that there are also no buffer head references. This function
is the right one for mappings where buffer heads are directly looked
up and referenced (such as block device mappings).

**Return**

0 on success or a negative errno on failure.



#### <a id="c-do_mmap"></a>`do_mmap()`

```c
unsigned long do_mmap(struct file *file, unsigned long addr, unsigned long len, unsigned long prot, unsigned long flags, vm_flags_t vm_flags, unsigned long pgoff, unsigned long *populate, struct list_head *uf)
```

Perform a userland memory mapping into the current process address space of length **len** with protection bits **prot**, mmap flags **flags** (from which VMA flags will be inferred), and any additional VMA flags to apply **vm_flags**. If this is a file-backed mapping then the file is specified in **file** and page offset into the file via **pgoff**.

**Parameters**

- `struct file *file`: An optional struct file pointer describing the file which is to be
  mapped, if a file-backed mapping.
- `unsigned long addr`: If non-zero, hints at (or if **flags** has MAP_FIXED set, specifies) the
  address at which to perform this mapping. See mmap (2) for details. Must be
  page-aligned.
- `unsigned long len`: The length of the mapping. Will be page-aligned and must be at least 1
  page in size.
- `unsigned long prot`: Protection bits describing access required to the mapping. See mmap
  (2) for details.
- `unsigned long flags`: Flags specifying how the mapping should be performed, see mmap (2)
  for details.
- `vm_flags_t vm_flags`: VMA flags which should be set by default, or 0 otherwise.
- `unsigned long pgoff`: Page offset into the **file** if file-backed, should be 0 otherwise.
- `unsigned long *populate`: A pointer to a value which will be set to 0 if no population of
  the range is required, or the number of bytes to populate if it is. Must be
  non-NULL. See mmap (2) for details as to under what circumstances population
  of the range occurs.
- `struct list_head *uf`: An optional pointer to a list head to track userfaultfd unmap events
  should unmapping events arise. If provided, it is up to the caller to manage
  this.

**Description**

This function does not perform security checks on the file and assumes, if
**uf** is non-NULL, the caller has provided a list head to track unmap events
for userfaultfd **uf**.

It also simply indicates whether memory population is required by setting
**populate**, which must be non-NULL, expecting the caller to actually perform
this task itself if appropriate.

This function will invoke architecture-specific (and if provided and
relevant, file system-specific) logic to determine the most appropriate
unmapped area in which to place the mapping if not MAP_FIXED.

Callers which require userland `mmap()` behaviour should invoke `vm_mmap()`,
which is also exported for module use.

Those which require this behaviour less security checks, userfaultfd and
populate behaviour, and who handle the mmap write lock themselves, should
call this function.

Note that the returned address may reside within a merged VMA if an
appropriate merge were to take place, so it doesn't necessarily specify the
start of a VMA, rather only the start of a valid mapped range of length
**len** bytes, rounded down to the nearest page size.

The caller must write-lock current->mm->mmap_lock.

**Return**

Either an error, or the address at which the requested mapping has
been performed.

#### <a id="c-find_vma_intersection"></a>`find_vma_intersection()`

```c
struct vm_area_struct * find_vma_intersection(struct mm_struct *mm, unsigned long start_addr, unsigned long end_addr)
```

Look up the first VMA which intersects the interval

**Parameters**

- `struct mm_struct *mm`: The process address space.
- `unsigned long start_addr`: The inclusive start user address.
- `unsigned long end_addr`: The exclusive end user address.

**Return**

The first VMA within the provided range, `NULL` otherwise.  Assumes
start_addr \< end_addr.

#### <a id="c-find_vma"></a>`find_vma()`

```c
struct vm_area_struct * find_vma(struct mm_struct *mm, unsigned long addr)
```

Find the VMA for a given address, or the next VMA.

**Parameters**

- `struct mm_struct *mm`: The mm_struct to check
- `unsigned long addr`: The address

**Return**

The VMA associated with addr, or the next VMA.
May return `NULL` in the case of no VMA at addr or above.

#### <a id="c-find_vma_prev"></a>`find_vma_prev()`

```c
struct vm_area_struct * find_vma_prev(struct mm_struct *mm, unsigned long addr, struct vm_area_struct **pprev)
```

Find the VMA for a given address, or the next vma and set `pprev` to the previous VMA, if any.

**Parameters**

- `struct mm_struct *mm`: The mm_struct to check
- `unsigned long addr`: The address
- `struct vm_area_struct **pprev`: The pointer to set to the previous VMA

**Description**

Note that RCU lock is missing here since the external `mmap_lock()` is used
instead.

**Return**

The VMA associated with **addr**, or the next vma.
May return `NULL` in the case of no vma at addr or above.



#### <a id="c-kmemleak_alloc"></a>`kmemleak_alloc()`

```c
void __ref kmemleak_alloc(const void *ptr, size_t size, int min_count, gfp_t gfp)
```

register a newly allocated object

**Parameters**

- `const void *ptr`: pointer to beginning of the object
- `size_t size`: size of the object
- `int min_count`: minimum number of references to this object. If during memory
  scanning a number of references less than **min_count** is found,
  the object is reported as a memory leak. If **min_count** is 0,
  the object is never reported as a leak. If **min_count** is -1,
  the object is ignored (not scanned and not reported as a leak)
- `gfp_t gfp`: [`kmalloc()`](#c-kmalloc) flags used for kmemleak internal memory allocations

**Description**

This function is called from the kernel allocators when a new object
(memory block) is allocated (kmem_cache_alloc, kmalloc etc.).

#### <a id="c-kmemleak_alloc_percpu"></a>`kmemleak_alloc_percpu()`

```c
void __ref kmemleak_alloc_percpu(const void __percpu *ptr, size_t size, gfp_t gfp)
```

register a newly allocated __percpu object

**Parameters**

- `const void __percpu *ptr`: __percpu pointer to beginning of the object
- `size_t size`: size of the object
- `gfp_t gfp`: flags used for kmemleak internal memory allocations

**Description**

This function is called from the kernel percpu allocator when a new object
(memory block) is allocated (alloc_percpu).

#### <a id="c-kmemleak_vmalloc"></a>`kmemleak_vmalloc()`

```c
void __ref kmemleak_vmalloc(const struct vm_struct *area, size_t size, gfp_t gfp)
```

register a newly vmalloc'ed object

**Parameters**

- `const struct vm_struct *area`: pointer to vm_struct
- `size_t size`: size of the object
- `gfp_t gfp`: `__vmalloc()` flags used for kmemleak internal memory allocations

**Description**

This function is called from the [`vmalloc()`](#c-vmalloc) kernel allocator when a new
object (memory block) is allocated.

#### <a id="c-kmemleak_free"></a>`kmemleak_free()`

```c
void __ref kmemleak_free(const void *ptr)
```

unregister a previously registered object

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

This function is called from the kernel allocators when an object (memory
block) is freed (kmem_cache_free, kfree, vfree etc.).

#### <a id="c-kmemleak_free_part"></a>`kmemleak_free_part()`

```c
void __ref kmemleak_free_part(const void *ptr, size_t size)
```

partially unregister a previously registered object

**Parameters**

- `const void *ptr`: pointer to the beginning or inside the object. This also
  represents the start of the range to be freed
- `size_t size`: size to be unregistered

**Description**

This function is called when only a part of a memory block is freed
(usually from the bootmem allocator).

#### <a id="c-kmemleak_free_percpu"></a>`kmemleak_free_percpu()`

```c
void __ref kmemleak_free_percpu(const void __percpu *ptr)
```

unregister a previously registered __percpu object

**Parameters**

- `const void __percpu *ptr`: __percpu pointer to beginning of the object

**Description**

This function is called from the kernel percpu allocator when an object
(memory block) is freed (free_percpu).

#### <a id="c-kmemleak_update_trace"></a>`kmemleak_update_trace()`

```c
void __ref kmemleak_update_trace(const void *ptr)
```

update object allocation stack trace

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

Override the object allocation stack trace for cases where the actual
allocation place is not always useful.

#### <a id="c-kmemleak_not_leak"></a>`kmemleak_not_leak()`

```c
void __ref kmemleak_not_leak(const void *ptr)
```

mark an allocated object as false positive

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

Calling this function on an object will cause the memory block to no longer
be reported as leak and always be scanned.

#### <a id="c-kmemleak_transient_leak"></a>`kmemleak_transient_leak()`

```c
void __ref kmemleak_transient_leak(const void *ptr)
```

mark an allocated object as transient false positive

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

Calling this function on an object will cause the memory block to not be
reported as a leak temporarily. This may happen, for example, if the object
is part of a singly linked list and the ->next reference to it is changed.

#### <a id="c-kmemleak_ignore_percpu"></a>`kmemleak_ignore_percpu()`

```c
void __ref kmemleak_ignore_percpu(const void __percpu *ptr)
```

similar to kmemleak_ignore but taking a percpu address argument

**Parameters**

- `const void __percpu *ptr`: percpu address of the object

#### <a id="c-kmemleak_ignore"></a>`kmemleak_ignore()`

```c
void __ref kmemleak_ignore(const void *ptr)
```

ignore an allocated object

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

Calling this function on an object will cause the memory block to be
ignored (not scanned and not reported as a leak). This is usually done when
it is known that the corresponding block is not a leak and does not contain
any references to other allocated memory blocks.

#### <a id="c-kmemleak_scan_area"></a>`kmemleak_scan_area()`

```c
void __ref kmemleak_scan_area(const void *ptr, size_t size, gfp_t gfp)
```

limit the range to be scanned in an allocated object

**Parameters**

- `const void *ptr`: pointer to beginning or inside the object. This also
  represents the start of the scan area
- `size_t size`: size of the scan area
- `gfp_t gfp`: [`kmalloc()`](#c-kmalloc) flags used for kmemleak internal memory allocations

**Description**

This function is used when it is known that only certain parts of an object
contain references to other objects. Kmemleak will only scan these areas
reducing the number false negatives.

#### <a id="c-kmemleak_no_scan"></a>`kmemleak_no_scan()`

```c
void __ref kmemleak_no_scan(const void *ptr)
```

do not scan an allocated object

**Parameters**

- `const void *ptr`: pointer to beginning of the object

**Description**

This function notifies kmemleak not to scan the given memory block. Useful
in situations where it is known that the given object does not contain any
references to other objects. Kmemleak will not scan such objects reducing
the number of false negatives.

#### <a id="c-kmemleak_alloc_phys"></a>`kmemleak_alloc_phys()`

```c
void __ref kmemleak_alloc_phys(phys_addr_t phys, size_t size, gfp_t gfp)
```

similar to kmemleak_alloc but taking a physical address argument

**Parameters**

- `phys_addr_t phys`: physical address of the object
- `size_t size`: size of the object
- `gfp_t gfp`: [`kmalloc()`](#c-kmalloc) flags used for kmemleak internal memory allocations

#### <a id="c-kmemleak_free_part_phys"></a>`kmemleak_free_part_phys()`

```c
void __ref kmemleak_free_part_phys(phys_addr_t phys, size_t size)
```

similar to kmemleak_free_part but taking a physical address argument

**Parameters**

- `phys_addr_t phys`: physical address if the beginning or inside an object. This
  also represents the start of the range to be freed
- `size_t size`: size to be unregistered

#### <a id="c-kmemleak_ignore_phys"></a>`kmemleak_ignore_phys()`

```c
void __ref kmemleak_ignore_phys(phys_addr_t phys)
```

similar to kmemleak_ignore but taking a physical address argument

**Parameters**

- `phys_addr_t phys`: physical address of the object


<!-- #kernel-doc:: mm/hmm.c (build warnings) -->


#### <a id="c-devm_memremap_pages"></a>`devm_memremap_pages()`

```c
void * devm_memremap_pages(struct device *dev, struct dev_pagemap *pgmap)
```

remap and provide memmap backing for the given resource

**Parameters**

- `struct device *dev`: hosting device for **res**
- `struct dev_pagemap *pgmap`: pointer to a struct dev_pagemap

**Notes**

- 1/ At a minimum the range and type members of **pgmap** must be initialized

  by the caller before passing it to this function

- 2/ The altmap field may optionally be initialized, in which case

  PGMAP_ALTMAP_VALID must be set in pgmap->flags.

- 3/ The ref field may optionally be provided, in which pgmap->ref must be

  'live' on entry and will be killed and reaped at
  `devm_memremap_pages_release()` time, or if this routine fails.

- 4/ range is expected to be a host memory range that could feasibly be

  treated as a "System RAM" range, i.e. not a device mmio range, but
  this is not enforced.

#### <a id="c-get_dev_pagemap"></a>`get_dev_pagemap()`

```c
struct dev_pagemap * get_dev_pagemap(unsigned long pfn)
```

take a new live reference on the dev_pagemap for **pfn**

**Parameters**

- `unsigned long pfn`: page frame number to lookup page_map



#### <a id="c-vma_kernel_pagesize"></a>`vma_kernel_pagesize()`

```c
unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
```

Page size granularity for this VMA.

**Parameters**

- `struct vm_area_struct *vma`: The user mapping.

**Description**

Folios in this VMA will be aligned to, and at least the size of the
number of bytes returned by this function.

**Return**

The default size of the folios allocated when backing a VMA.

#### <a id="c-huge_pmd_unshare"></a>`huge_pmd_unshare()`

```c
int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
```

Unmap a pmd table if it is shared by multiple users

**Parameters**

- `struct mmu_gather *tlb`: the current mmu_gather.
- `struct vm_area_struct *vma`: the vma covering the pmd table.
- `unsigned long addr`: the address we are trying to unshare.
- `pte_t *ptep`: pointer into the (pmd) page table.

**Description**

Called with the page table lock held, the i_mmap_rwsem held in write mode
and the hugetlb vma lock held in write mode.

**Note**

The caller must call `huge_pmd_unshare_flush()` before dropping the
i_mmap_rwsem.

**Return**

1 if it was a shared PMD table and it got unmapped, or 0 if it
was not a shared PMD table.

#### <a id="c-folio_isolate_hugetlb"></a>`folio_isolate_hugetlb()`

```c
bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list)
```

try to isolate an allocated hugetlb folio

**Parameters**

- `struct folio *folio`: the folio to isolate
- `struct list_head *list`: the list to add the folio to on success

**Description**

Isolate an allocated (refcount > 0) hugetlb folio, marking it as
isolated/non-migratable, and moving it from the active list to the
given list.

Isolation will fail if **folio** is not an allocated hugetlb folio, or if
it is already isolated/non-migratable.

On success, an additional folio reference is taken that must be dropped
using [`folio_putback_hugetlb()`](#c-folio_putback_hugetlb) to undo the isolation.

**Return**

True if isolation worked, otherwise False.

#### <a id="c-folio_putback_hugetlb"></a>`folio_putback_hugetlb()`

```c
void folio_putback_hugetlb(struct folio *folio)
```

unisolate a hugetlb folio

**Parameters**

- `struct folio *folio`: the isolated hugetlb folio

**Description**

Putback/un-isolate the hugetlb folio that was previous isolated using
[`folio_isolate_hugetlb()`](#c-folio_isolate_hugetlb): marking it non-isolated/migratable and putting it
back onto the active list.

Will drop the additional folio reference obtained through
[`folio_isolate_hugetlb()`](#c-folio_isolate_hugetlb).



#### <a id="c-folio_mark_accessed"></a>`folio_mark_accessed()`

```c
void folio_mark_accessed(struct folio *folio)
```

Mark a folio as having seen activity.

**Parameters**

- `struct folio *folio`: The folio to mark.

**Description**

This function will perform one of the following transitions:

* inactive,unreferenced      ->      inactive,referenced
* inactive,referenced        ->      active,unreferenced
* active,unreferenced        ->      active,referenced

When a newly allocated folio is not yet visible, so safe for non-atomic ops,
`__folio_set_referenced()` may be substituted for [`folio_mark_accessed()`](#c-folio_mark_accessed).

#### <a id="c-folio_add_lru"></a>`folio_add_lru()`

```c
void folio_add_lru(struct folio *folio)
```

Add a folio to an LRU list.

**Parameters**

- `struct folio *folio`: The folio to be added to the LRU.

**Description**

Queue the folio for addition to the LRU. The decision on whether
to add the page to the \[in\]active \[file|anon\] list is deferred until the
folio_batch is drained. This gives a chance for the caller of [`folio_add_lru()`](#c-folio_add_lru)
have the folio added to the active list using [`folio_mark_accessed()`](#c-folio_mark_accessed).

#### <a id="c-folio_add_lru_vma"></a>`folio_add_lru_vma()`

```c
void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
```

Add a folio to the appropriate LRU list for this VMA.

**Parameters**

- `struct folio *folio`: The folio to be added to the LRU.
- `struct vm_area_struct *vma`: VMA in which the folio is mapped.

**Description**

If the VMA is mlocked, **folio** is added to the unevictable list.
Otherwise, it is treated the same way as [`folio_add_lru()`](#c-folio_add_lru).

#### <a id="c-deactivate_file_folio"></a>`deactivate_file_folio()`

```c
void deactivate_file_folio(struct folio *folio)
```

Deactivate a file folio.

**Parameters**

- `struct folio *folio`: Folio to deactivate.

**Description**

This function hints to the VM that **folio** is a good reclaim candidate,
for example if its invalidation fails due to the folio being dirty
or under writeback.

**Context**

Caller holds a reference on the folio.

#### <a id="c-folio_mark_lazyfree"></a>`folio_mark_lazyfree()`

```c
void folio_mark_lazyfree(struct folio *folio)
```

make an anon folio lazyfree

**Parameters**

- `struct folio *folio`: folio to deactivate

**Description**

[`folio_mark_lazyfree()`](#c-folio_mark_lazyfree) moves **folio** to the inactive file list.
This is done to accelerate the reclaim of **folio**.

#### <a id="c-folios_put_refs"></a>`folios_put_refs()`

```c
void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
```

Reduce the reference count on a batch of folios.

**Parameters**

- `struct folio_batch *folios`: The folios.
- `unsigned int *refs`: The number of refs to subtract from each folio.

**Description**

Like [`folio_put()`](#c-folio_put), but for a batch of folios.  This is more efficient
than writing the loop yourself as it will optimise the locks which need
to be taken if the folios are freed.  The folios batch is returned
empty and ready to be reused for another batch; there is no need
to reinitialise it.  If **refs** is NULL, we subtract one from each
folio refcount.

**Context**

May be called in process or interrupt context, but not in NMI
context.  May be called while holding a spinlock.

#### <a id="c-release_pages"></a>`release_pages()`

```c
void release_pages(release_pages_arg arg, int nr)
```

batched `put_page()`

**Parameters**

- `release_pages_arg arg`: array of pages to release
- `int nr`: number of pages

**Description**

Decrement the reference count on all the pages in **arg**.  If it
fell to zero, remove the page from the LRU and free it.

Note that the argument can be an array of pages, encoded pages,
or folio pointers. We ignore any encoded bits, and turn any of
them into just a folio that gets free'd.

#### <a id="c-folio_batch_remove_exceptionals"></a>`folio_batch_remove_exceptionals()`

```c
void folio_batch_remove_exceptionals(struct folio_batch *fbatch)
```

Prune non-folios from a batch.

**Parameters**

- `struct folio_batch *fbatch`: The batch to prune

**Description**

`find_get_entries()` fills a batch with both folios and shadow/swap/DAX
entries.  This function prunes all the non-folio entries from **fbatch**
without leaving holes, so that it can be passed on to folio-only batch
operations.



#### <a id="c-mem_cgroup_css_from_folio"></a>`mem_cgroup_css_from_folio()`

```c
struct cgroup_subsys_state * mem_cgroup_css_from_folio(struct folio *folio)
```

css of the memcg associated with a folio

**Parameters**

- `struct folio *folio`: folio of interest

**Description**

If memcg is bound to the default hierarchy, css of the memcg associated
with **folio** is returned.  The returned css remains associated with **folio**
until it is released.

If memcg is bound to a traditional hierarchy, the css of root_mem_cgroup
is returned.

#### <a id="c-page_cgroup_ino"></a>`page_cgroup_ino()`

```c
ino_t page_cgroup_ino(struct page *page)
```

return inode number of the memcg a page is charged to

**Parameters**

- `struct page *page`: the page

**Description**

Look up the closest online ancestor of the memory cgroup **page** is charged to
and return its inode number or 0 if **page** is not charged to any cgroup. It
is safe to call this function without holding a reference to **page**.

Note, this function is inherently racy, because there is nothing to prevent
the cgroup inode from getting torn down and potentially reallocated a moment
after [`page_cgroup_ino()`](#c-page_cgroup_ino) returns, so it only should be used by callers that
do not care (such as procfs interfaces).

#### <a id="c-mod_memcg_state"></a>`mod_memcg_state()`

```c
void mod_memcg_state(struct mem_cgroup *memcg, enum memcg_stat_item idx, int val)
```

update cgroup memory statistics

**Parameters**

- `struct mem_cgroup *memcg`: the memory cgroup
- `enum memcg_stat_item idx`: the stat item - can be enum memcg_stat_item or enum node_stat_item
- `int val`: delta to add to the counter, can be negative

#### <a id="c-mod_lruvec_state"></a>`mod_lruvec_state()`

```c
void mod_lruvec_state(struct lruvec *lruvec, enum node_stat_item idx, int val)
```

update lruvec memory statistics

**Parameters**

- `struct lruvec *lruvec`: the lruvec
- `enum node_stat_item idx`: the stat item
- `int val`: delta to add to the counter, can be negative

**Description**

The lruvec is the intersection of the NUMA node and a cgroup. This
function updates the all three counters that are affected by a
change of state at this level: per-node, per-cgroup, per-lruvec.

#### <a id="c-count_memcg_events"></a>`count_memcg_events()`

```c
void count_memcg_events(struct mem_cgroup *memcg, enum vm_event_item idx, unsigned long count)
```

account VM events in a cgroup

**Parameters**

- `struct mem_cgroup *memcg`: the memory cgroup
- `enum vm_event_item idx`: the event item
- `unsigned long count`: the number of events that occurred

#### <a id="c-get_mem_cgroup_from_mm"></a>`get_mem_cgroup_from_mm()`

```c
struct mem_cgroup * get_mem_cgroup_from_mm(struct mm_struct *mm)
```

Obtain a reference on given mm_struct's memcg.

**Parameters**

- `struct mm_struct *mm`: mm from which memcg should be extracted. It can be NULL.

**Description**

Obtain a reference on mm->memcg and returns it if successful. If mm
is NULL, then the memcg is chosen as follows:
1) The active memcg, if set.
2) current->mm->memcg, if available
3) root memcg
If mem_cgroup is disabled, NULL is returned.

#### <a id="c-get_mem_cgroup_from_current"></a>`get_mem_cgroup_from_current()`

```c
struct mem_cgroup * get_mem_cgroup_from_current(void)
```

Obtain a reference on current task's memcg.

**Parameters**

- `void`: no arguments

#### <a id="c-get_mem_cgroup_from_folio"></a>`get_mem_cgroup_from_folio()`

```c
struct mem_cgroup * get_mem_cgroup_from_folio(struct folio *folio)
```

Obtain a reference on a given folio's memcg.

**Parameters**

- `struct folio *folio`: folio from which memcg should be extracted.

#### <a id="c-mem_cgroup_iter"></a>`mem_cgroup_iter()`

```c
struct mem_cgroup * mem_cgroup_iter(struct mem_cgroup *root, struct mem_cgroup *prev, struct mem_cgroup_reclaim_cookie *reclaim)
```

iterate over memory cgroup hierarchy

**Parameters**

- `struct mem_cgroup *root`: hierarchy root
- `struct mem_cgroup *prev`: previously returned memcg, NULL on first invocation
- `struct mem_cgroup_reclaim_cookie *reclaim`: cookie for shared reclaim walks, NULL for full walks

**Description**

Returns references to children of the hierarchy below **root**, or
**root** itself, or `NULL` after a full round-trip.

Caller must pass the return value in **prev** on subsequent
invocations for reference counting, or use [`mem_cgroup_iter_break()`](#c-mem_cgroup_iter_break)
to cancel a hierarchy walk before the round-trip is complete.

Reclaimers can specify a node in **reclaim** to divide up the memcgs
in the hierarchy among all concurrent reclaimers operating on the
same node.

#### <a id="c-mem_cgroup_iter_break"></a>`mem_cgroup_iter_break()`

```c
void mem_cgroup_iter_break(struct mem_cgroup *root, struct mem_cgroup *prev)
```

abort a hierarchy walk prematurely

**Parameters**

- `struct mem_cgroup *root`: hierarchy root
- `struct mem_cgroup *prev`: last visited hierarchy member as returned by [`mem_cgroup_iter()`](#c-mem_cgroup_iter)

#### <a id="c-mem_cgroup_scan_tasks"></a>`mem_cgroup_scan_tasks()`

```c
void mem_cgroup_scan_tasks(struct mem_cgroup *memcg, int (*fn)(struct task_struct *, void *), void *arg)
```

iterate over tasks of a memory cgroup hierarchy

**Parameters**

- `struct mem_cgroup *memcg`: hierarchy root
- `int (*fn)(struct task_struct *, void *)`: function to call for each task
- `void *arg`: argument passed to **fn**

**Description**

This function iterates over tasks attached to **memcg** or to any of its
descendants and calls **fn** for each task. If **fn** returns a non-zero
value, the function breaks the iteration loop. Otherwise, it will iterate
over all tasks and return 0.

This function must not be called for the root memory cgroup.

#### <a id="c-folio_lruvec_lock"></a>`folio_lruvec_lock()`

```c
struct lruvec * folio_lruvec_lock(struct folio *folio)
```

Lock the lruvec for a folio.

**Parameters**

- `struct folio *folio`: Pointer to the folio.

**Description**

These functions are safe to use under any of the following conditions:
- folio locked
- folio_test_lru false
- folio frozen (refcount of 0)

**Return**

The lruvec this folio is on with its lock held.

#### <a id="c-folio_lruvec_lock_irq"></a>`folio_lruvec_lock_irq()`

```c
struct lruvec * folio_lruvec_lock_irq(struct folio *folio)
```

Lock the lruvec for a folio.

**Parameters**

- `struct folio *folio`: Pointer to the folio.

**Description**

These functions are safe to use under any of the following conditions:
- folio locked
- folio_test_lru false
- folio frozen (refcount of 0)

**Return**

The lruvec this folio is on with its lock held and interrupts
disabled.

#### <a id="c-folio_lruvec_lock_irqsave"></a>`folio_lruvec_lock_irqsave()`

```c
struct lruvec * folio_lruvec_lock_irqsave(struct folio *folio, unsigned long *flags)
```

Lock the lruvec for a folio.

**Parameters**

- `struct folio *folio`: Pointer to the folio.
- `unsigned long *flags`: Pointer to irqsave flags.

**Description**

These functions are safe to use under any of the following conditions:
- folio locked
- folio_test_lru false
- folio frozen (refcount of 0)

**Return**

The lruvec this folio is on with its lock held and interrupts
disabled.

#### <a id="c-mem_cgroup_update_lru_size"></a>`mem_cgroup_update_lru_size()`

```c
void mem_cgroup_update_lru_size(struct lruvec *lruvec, enum lru_list lru, int zid, int nr_pages)
```

account for adding or removing an lru page

**Parameters**

- `struct lruvec *lruvec`: mem_cgroup per zone lru vector
- `enum lru_list lru`: index of lru list the page is sitting on
- `int zid`: zone id of the accounted pages
- `int nr_pages`: positive when adding or negative when removing

**Description**

This function must be called under lru_lock, just before a page is added
to or just after a page is removed from an lru list.

#### <a id="c-mem_cgroup_margin"></a>`mem_cgroup_margin()`

```c
unsigned long mem_cgroup_margin(struct mem_cgroup *memcg)
```

calculate chargeable space of a memory cgroup

**Parameters**

- `struct mem_cgroup *memcg`: the memory cgroup

**Description**

Returns the maximum amount of memory **mem** can be charged with, in
pages.

#### <a id="c-mem_cgroup_print_oom_context"></a>`mem_cgroup_print_oom_context()`

```c
void mem_cgroup_print_oom_context(struct mem_cgroup *memcg, struct task_struct *p)
```

Print OOM information relevant to memory controller.

**Parameters**

- `struct mem_cgroup *memcg`: The memory cgroup that went over limit
- `struct task_struct *p`: Task that is going to be killed

**NOTE**

**memcg** and **p**'s mem_cgroup can be different when hierarchy is
enabled

#### <a id="c-mem_cgroup_print_oom_meminfo"></a>`mem_cgroup_print_oom_meminfo()`

```c
void mem_cgroup_print_oom_meminfo(struct mem_cgroup *memcg)
```

Print OOM memory information relevant to memory controller.

**Parameters**

- `struct mem_cgroup *memcg`: The memory cgroup that went over limit

#### <a id="c-mem_cgroup_get_oom_group"></a>`mem_cgroup_get_oom_group()`

```c
struct mem_cgroup * mem_cgroup_get_oom_group(struct task_struct *victim, struct mem_cgroup *oom_domain)
```

get a memory cgroup to clean up after OOM

**Parameters**

- `struct task_struct *victim`: task to be killed by the OOM killer
- `struct mem_cgroup *oom_domain`: memcg in case of memcg OOM, NULL in case of system-wide OOM

**Description**

Returns a pointer to a memory cgroup, which has to be cleaned up
by killing all belonging OOM-killable tasks.

Caller has to call `mem_cgroup_put()` on the returned non-NULL memcg.

#### <a id="c-consume_stock"></a>`consume_stock()`

```c
bool consume_stock(struct mem_cgroup *memcg, unsigned int nr_pages)
```

Try to consume stocked charge on this cpu.

**Parameters**

- `struct mem_cgroup *memcg`: memcg to consume from.
- `unsigned int nr_pages`: how many pages to charge.

**Description**

Consume the cached charge if enough nr_pages are present otherwise return
failure. Also return failure for charge request larger than
MEMCG_CHARGE_BATCH or if the local lock is already taken.

returns true if successful, false otherwise.

#### <a id="c-__memcg_kmem_charge_page"></a>`__memcg_kmem_charge_page()`

```c
int __memcg_kmem_charge_page(struct page *page, gfp_t gfp, int order)
```

charge a kmem page to the current memory cgroup

**Parameters**

- `struct page *page`: page to charge
- `gfp_t gfp`: reclaim mode
- `int order`: allocation order

**Description**

Returns 0 on success, an error code on failure.

#### <a id="c-__memcg_kmem_uncharge_page"></a>`__memcg_kmem_uncharge_page()`

```c
void __memcg_kmem_uncharge_page(struct page *page, int order)
```

uncharge a kmem page

**Parameters**

- `struct page *page`: page to uncharge
- `int order`: allocation order

#### <a id="c-mem_cgroup_wb_stats"></a>`mem_cgroup_wb_stats()`

```c
void mem_cgroup_wb_stats(struct bdi_writeback *wb, unsigned long *pfilepages, unsigned long *pheadroom, unsigned long *pdirty, unsigned long *pwriteback)
```

retrieve writeback related stats from its memcg

**Parameters**

- `struct bdi_writeback *wb`: bdi_writeback in question
- `unsigned long *pfilepages`: out parameter for number of file pages
- `unsigned long *pheadroom`: out parameter for number of allocatable pages according to memcg
- `unsigned long *pdirty`: out parameter for number of dirty pages
- `unsigned long *pwriteback`: out parameter for number of pages under writeback

**Description**

Determine the numbers of file, headroom, dirty, and writeback pages in
**wb**'s memcg.  File, dirty and writeback are self-explanatory.  Headroom
is a bit more involved.

A memcg's headroom is "min(max, high) - used".  In the hierarchy, the
headroom is calculated as the lowest headroom of itself and the
ancestors.  Note that this doesn't consider the actual amount of
available memory in the system.  The caller should further cap
**\*pheadroom** accordingly.

#### <a id="c-mem_cgroup_from_private_id"></a>`mem_cgroup_from_private_id()`

```c
struct mem_cgroup * mem_cgroup_from_private_id(unsigned short id)
```

look up a memcg from a memcg id

**Parameters**

- `unsigned short id`: the memcg id to look up

**Description**

Caller must hold [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock).

#### <a id="c-mem_cgroup_css_reset"></a>`mem_cgroup_css_reset()`

```c
void mem_cgroup_css_reset(struct cgroup_subsys_state *css)
```

reset the states of a mem_cgroup

**Parameters**

- `struct cgroup_subsys_state *css`: the target css

**Description**

Reset the states of the mem_cgroup associated with **css**.  This is
invoked when the userland requests disabling on the default hierarchy
but the memcg is pinned through dependency.  The memcg should stop
applying policies and should revert to the vanilla state as it may be
made visible again.

The current implementation only resets the essential configurations.
This needs to be expanded to cover all the visible parts.

#### <a id="c-mem_cgroup_calculate_protection"></a>`mem_cgroup_calculate_protection()`

```c
void mem_cgroup_calculate_protection(struct mem_cgroup *root, struct mem_cgroup *memcg)
```

check if memory consumption is in the normal range

**Parameters**

- `struct mem_cgroup *root`: the top ancestor of the sub-tree being checked
- `struct mem_cgroup *memcg`: the memory cgroup to check

**Description**

- WARNING: This function is not stateless! It can only be used as part

  of a top-down tree iteration, not for isolated queries.

#### <a id="c-mem_cgroup_charge_hugetlb"></a>`mem_cgroup_charge_hugetlb()`

```c
int mem_cgroup_charge_hugetlb(struct folio *folio, gfp_t gfp)
```

charge the memcg for a hugetlb folio

**Parameters**

- `struct folio *folio`: folio being charged
- `gfp_t gfp`: reclaim mode

**Description**

This function is called when allocating a huge page folio, after the page has
already been obtained and charged to the appropriate hugetlb cgroup
controller (if it is enabled).

Returns ENOMEM if the memcg is already full.
Returns 0 if either the charge was successful, or if we skip the charging.

#### <a id="c-mem_cgroup_swapin_charge_folio"></a>`mem_cgroup_swapin_charge_folio()`

```c
int mem_cgroup_swapin_charge_folio(struct folio *folio, struct mm_struct *mm, gfp_t gfp, swp_entry_t entry)
```

Charge a newly allocated folio for swapin.

**Parameters**

- `struct folio *folio`: folio to charge.
- `struct mm_struct *mm`: mm context of the victim
- `gfp_t gfp`: reclaim mode
- `swp_entry_t entry`: swap entry for which the folio is allocated

**Description**

This function charges a folio allocated for swapin. Please call this before
adding the folio to the swapcache.

Returns 0 on success. Otherwise, an error code is returned.

#### <a id="c-mem_cgroup_replace_folio"></a>`mem_cgroup_replace_folio()`

```c
void mem_cgroup_replace_folio(struct folio *old, struct folio *new)
```

Charge a folio's replacement.

**Parameters**

- `struct folio *old`: Currently circulating folio.
- `struct folio *new`: Replacement folio.

**Description**

Charge **new** as a replacement folio for **old**. **old** will
be uncharged upon free.

Both folios must be locked, **new->mapping** must be set up.

#### <a id="c-mem_cgroup_migrate"></a>`mem_cgroup_migrate()`

```c
void mem_cgroup_migrate(struct folio *old, struct folio *new)
```

Transfer the memcg data from the old to the new folio.

**Parameters**

- `struct folio *old`: Currently circulating folio.
- `struct folio *new`: Replacement folio.

**Description**

Transfer the memcg data from the old folio to the new folio for migration.
The old folio's data info will be cleared. Note that the memory counters
will remain unchanged throughout the process.

Both folios must be locked, **new->mapping** must be set up.

#### <a id="c-mem_cgroup_sk_charge"></a>`mem_cgroup_sk_charge()`

```c
bool mem_cgroup_sk_charge(const struct sock *sk, unsigned int nr_pages, gfp_t gfp_mask)
```

charge socket memory

**Parameters**

- `const struct sock *sk`: socket in memcg to charge
- `unsigned int nr_pages`: number of pages to charge
- `gfp_t gfp_mask`: reclaim mode

**Description**

Charges **nr_pages** to **memcg**. Returns `true` if the charge fit within
**memcg**'s configured limit, `false` if it doesn't.

#### <a id="c-mem_cgroup_sk_uncharge"></a>`mem_cgroup_sk_uncharge()`

```c
void mem_cgroup_sk_uncharge(const struct sock *sk, unsigned int nr_pages)
```

uncharge socket memory

**Parameters**

- `const struct sock *sk`: socket in memcg to uncharge
- `unsigned int nr_pages`: number of pages to uncharge

#### <a id="c-__mem_cgroup_try_charge_swap"></a>`__mem_cgroup_try_charge_swap()`

```c
int __mem_cgroup_try_charge_swap(struct folio *folio, swp_entry_t entry)
```

try charging swap space for a folio

**Parameters**

- `struct folio *folio`: folio being added to swap
- `swp_entry_t entry`: swap entry to charge

**Description**

Try to charge **folio**'s memcg for the swap space at **entry**.

Returns 0 on success, -ENOMEM on failure.

#### <a id="c-__mem_cgroup_uncharge_swap"></a>`__mem_cgroup_uncharge_swap()`

```c
void __mem_cgroup_uncharge_swap(swp_entry_t entry, unsigned int nr_pages)
```

uncharge swap space

**Parameters**

- `swp_entry_t entry`: swap entry to uncharge
- `unsigned int nr_pages`: the amount of swap space to uncharge

#### <a id="c-obj_cgroup_may_zswap"></a>`obj_cgroup_may_zswap()`

```c
bool obj_cgroup_may_zswap(struct obj_cgroup *objcg)
```

check if this cgroup can zswap

**Parameters**

- `struct obj_cgroup *objcg`: the object cgroup

**Description**

Check if the hierarchical zswap limit has been reached.

This doesn't check for specific headroom, and it is not atomic
either. But with zswap, the size of the allocation is only known
once compression has occurred, and this optimistic pre-check avoids
spending cycles on compression when there is already no room left
or zswap is disabled altogether somewhere in the hierarchy.

#### <a id="c-obj_cgroup_charge_zswap"></a>`obj_cgroup_charge_zswap()`

```c
void obj_cgroup_charge_zswap(struct obj_cgroup *objcg, size_t size)
```

charge compression backend memory

**Parameters**

- `struct obj_cgroup *objcg`: the object cgroup
- `size_t size`: size of compressed object

**Description**

This forces the charge after [`obj_cgroup_may_zswap()`](#c-obj_cgroup_may_zswap) allowed
compression and storage in zswap for this cgroup to go ahead.

#### <a id="c-obj_cgroup_uncharge_zswap"></a>`obj_cgroup_uncharge_zswap()`

```c
void obj_cgroup_uncharge_zswap(struct obj_cgroup *objcg, size_t size)
```

uncharge compression backend memory

**Parameters**

- `struct obj_cgroup *objcg`: the object cgroup
- `size_t size`: size of compressed object

**Description**

Uncharges zswap memory on page in.


<!-- #kernel-doc:: mm/memory-tiers.c (build warnings) -->


#### <a id="c-shmem_recalc_inode"></a>`shmem_recalc_inode()`

```c
bool shmem_recalc_inode(struct inode *inode, long alloced, long swapped)
```

recalculate the block usage of an inode

**Parameters**

- `struct inode *inode`: inode to recalc
- `long alloced`: the change in number of pages allocated to inode
- `long swapped`: the change in number of pages swapped from inode

**Description**

We have to calculate the free blocks since the mm can drop
undirtied hole pages behind our back.

But normally   info->alloced == inode->i_mapping->nrpages + info->swapped
So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)

**Return**

true if swapped was incremented from 0, for [`shmem_writeout()`](#c-shmem_writeout).

#### <a id="c-shmem_writeout"></a>`shmem_writeout()`

```c
int shmem_writeout(struct folio *folio, struct swap_iocb **plug, struct list_head *folio_list)
```

Write the folio to swap

**Parameters**

- `struct folio *folio`: The folio to write
- `struct swap_iocb **plug`: swap plug
- `struct list_head *folio_list`: list to put back folios on split

**Description**

Move the folio from the page cache to the swap cache.

#### <a id="c-shmem_get_folio"></a>`shmem_get_folio()`

```c
int shmem_get_folio(struct inode *inode, pgoff_t index, loff_t write_end, struct folio **foliop, enum sgp_type sgp)
```

find, and lock a shmem folio.

**Parameters**

- `struct inode *inode`: inode to search
- `pgoff_t index`: the page index.
- `loff_t write_end`: end of a write, could extend inode size
- `struct folio **foliop`: pointer to the folio if found
- `enum sgp_type sgp`: SGP_* flags to control behavior

**Description**

Looks up the page cache entry at **inode** & **index**.  If a folio is
present, it is returned locked with an increased refcount.

If the caller modifies data in the folio, it must call [`folio_mark_dirty()`](#c-folio_mark_dirty)
before unlocking the folio to ensure that the folio is not reclaimed.
There is no need to reserve space before calling [`folio_mark_dirty()`](#c-folio_mark_dirty).

- When no folio is found, the behavior depends on **sgp**:
  - for SGP_READ, **\*foliop** is `NULL` and 0 is returned
  - for SGP_NOALLOC, **\*foliop** is `NULL` and -ENOENT is returned
  - for all other flags a new folio is allocated, inserted into the
    page cache and returned locked in **foliop**.

**Context**

May sleep.

**Return**

0 if successful, else a negative error code.

#### <a id="c-shmem_kernel_file_setup"></a>`shmem_kernel_file_setup()`

```c
struct file * shmem_kernel_file_setup(const char *name, loff_t size, vma_flags_t flags)
```

get an unlinked file living in tmpfs which must be kernel internal. There will be NO LSM permission checks against the underlying inode. So users of this interface must do LSM checks at a higher layer. The users are the big_key and shm implementations. LSM checks are provided at the key or shm level rather than the inode.

**Parameters**

- `const char *name`: name for dentry (to be seen in /proc/\<pid>/maps)
- `loff_t size`: size to be set for the file
- `vma_flags_t flags`: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size

#### <a id="c-shmem_file_setup"></a>`shmem_file_setup()`

```c
struct file * shmem_file_setup(const char *name, loff_t size, vma_flags_t flags)
```

get an unlinked file living in tmpfs

**Parameters**

- `const char *name`: name for dentry (to be seen in /proc/\<pid>/maps)
- `loff_t size`: size to be set for the file
- `vma_flags_t flags`: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size

#### <a id="c-shmem_file_setup_with_mnt"></a>`shmem_file_setup_with_mnt()`

```c
struct file * shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name, loff_t size, vma_flags_t flags)
```

get an unlinked file living in tmpfs

**Parameters**

- `struct vfsmount *mnt`: the tmpfs mount where the file will be created
- `const char *name`: name for dentry (to be seen in /proc/\<pid>/maps)
- `loff_t size`: size to be set for the file
- `vma_flags_t flags`: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size

#### <a id="c-shmem_zero_setup"></a>`shmem_zero_setup()`

```c
int shmem_zero_setup(struct vm_area_struct *vma)
```

setup a shared anonymous mapping

**Parameters**

- `struct vm_area_struct *vma`: the vma to be mmapped is prepared by do_mmap

**Return**

0 on success, or error

#### <a id="c-shmem_zero_setup_desc"></a>`shmem_zero_setup_desc()`

```c
int shmem_zero_setup_desc(struct vm_area_desc *desc)
```

same as shmem_zero_setup, but determined by VMA descriptor for convenience.

**Parameters**

- `struct vm_area_desc *desc`: Describes VMA

**Return**

0 on success, or error

#### <a id="c-shmem_read_folio_gfp"></a>`shmem_read_folio_gfp()`

```c
struct folio * shmem_read_folio_gfp(struct address_space *mapping, pgoff_t index, gfp_t gfp)
```

read into page cache, using specified page allocation flags.

**Parameters**

- `struct address_space *mapping`: the folio's address_space
- `pgoff_t index`: the folio index
- `gfp_t gfp`: the page allocator flags to use if allocating

**Description**

This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
with any new page allocations done using the specified allocation flags.
But [`read_cache_page_gfp()`](#c-read_cache_page_gfp) uses the ->`read_folio()` method: which does not
suit tmpfs, since it may have pages in swapcache, and needs to find those
for itself; although drivers/gpu/drm i915 and ttm rely upon this support.

`i915_gem_object_get_pages_gtt()` mixes __GFP_NORETRY | __GFP_NOWARN in
with the `mapping_gfp_mask()`, to avoid OOMing the machine unnecessarily.



#### <a id="c-migrate_vma_split_folio"></a>`migrate_vma_split_folio()`

```c
int migrate_vma_split_folio(struct folio *folio, struct page *fault_page)
```

Helper function to split a THP folio

**Parameters**

- `struct folio *folio`: the folio to split
- `struct page *fault_page`: struct page associated with the fault if any

**Description**

Returns 0 on success

#### <a id="c-migrate_vma_setup"></a>`migrate_vma_setup()`

```c
int migrate_vma_setup(struct migrate_vma *args)
```

prepare to migrate a range of memory

**Parameters**

- `struct migrate_vma *args`: contains the vma, start, and pfns arrays for the migration

**Return**

negative errno on failures, 0 when 0 or more pages were migrated
without an error.

**Description**

Prepare to migrate a range of memory virtual address range by collecting all
the pages backing each virtual address in the range, saving them inside the
src array.  Then lock those pages and unmap them. Once the pages are locked
and unmapped, check whether each page is pinned or not.  Pages that aren't
pinned have the MIGRATE_PFN_MIGRATE flag set (by this function) in the
corresponding src array entry.  Then restores any pages that are pinned, by
remapping and unlocking those pages.

The caller should then allocate destination memory and copy source memory to
it for all those entries (ie with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE
flag set).  Once these are allocated and copied, the caller must update each
corresponding entry in the dst array with the pfn value of the destination
page and with MIGRATE_PFN_VALID. Destination pages must be locked via
[`lock_page()`](#c-lock_page).

Note that the caller does not have to migrate all the pages that are marked
with MIGRATE_PFN_MIGRATE flag in src array unless this is a migration from
device memory to system memory.  If the caller cannot migrate a device page
back to system memory, then it must return VM_FAULT_SIGBUS, which has severe
consequences for the userspace process, so it must be avoided if at all
possible.

For empty entries inside CPU page table (`pte_none()` or `pmd_none()` is true) we
do set MIGRATE_PFN_MIGRATE flag inside the corresponding source array thus
allowing the caller to allocate device memory for those unbacked virtual
addresses.  For this the caller simply has to allocate device memory and
properly set the destination entry like for regular migration.  Note that
this can still fail, and thus inside the device driver you must check if the
migration was successful for those entries after calling [`migrate_vma_pages()`](#c-migrate_vma_pages),
just like for regular migration.

After that, the callers must call [`migrate_vma_pages()`](#c-migrate_vma_pages) to go over each entry
in the src array that has the MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag
set. If the corresponding entry in dst array has MIGRATE_PFN_VALID flag set,
then [`migrate_vma_pages()`](#c-migrate_vma_pages) to migrate struct page information from the source
struct page to the destination struct page.  If it fails to migrate the
struct page information, then it clears the MIGRATE_PFN_MIGRATE flag in the
src array.

At this point all successfully migrated pages have an entry in the src
array with MIGRATE_PFN_VALID and MIGRATE_PFN_MIGRATE flag set and the dst
array entry with MIGRATE_PFN_VALID flag set.

Once [`migrate_vma_pages()`](#c-migrate_vma_pages) returns the caller may inspect which pages were
successfully migrated, and which were not.  Successfully migrated pages will
have the MIGRATE_PFN_MIGRATE flag set for their src array entry.

It is safe to update device page table after [`migrate_vma_pages()`](#c-migrate_vma_pages) because
both destination and source page are still locked, and the mmap_lock is held
in read mode (hence no one can unmap the range being migrated).

Once the caller is done cleaning up things and updating its page table (if it
chose to do so, this is not an obligation) it finally calls
[`migrate_vma_finalize()`](#c-migrate_vma_finalize) to update the CPU page table to point to new pages
for successfully migrated pages or otherwise restore the CPU page table to
point to the original source pages.

#### <a id="c-migrate_vma_insert_huge_pmd_page"></a>`migrate_vma_insert_huge_pmd_page()`

```c
int migrate_vma_insert_huge_pmd_page(struct migrate_vma *migrate, unsigned long addr, struct page *page, unsigned long *src, pmd_t *pmdp)
```

Insert a huge folio into **migrate->vma->vm_mm** at **addr**. folio is already allocated as a part of the migration process with large page.

**Parameters**

- `struct migrate_vma *migrate`: migrate_vma arguments
- `unsigned long addr`: address where the folio will be inserted
- `struct page *page`: page to be inserted at **addr**
- `unsigned long *src`: src pfn which is being migrated
- `pmd_t *pmdp`: pointer to the pmd

**Description**

**page** needs to be initialized and setup after it's allocated. The code bits
here follow closely the code in `__do_huge_pmd_anonymous_page()`. This API does
not support THP zero pages.

#### <a id="c-migrate_device_pages"></a>`migrate_device_pages()`

```c
void migrate_device_pages(unsigned long *src_pfns, unsigned long *dst_pfns, unsigned long npages)
```

migrate meta-data from src page to dst page

**Parameters**

- `unsigned long *src_pfns`: src_pfns returned from [`migrate_device_range()`](#c-migrate_device_range)
- `unsigned long *dst_pfns`: array of pfns allocated by the driver to migrate memory to
- `unsigned long npages`: number of pages in the range

**Description**

Equivalent to [`migrate_vma_pages()`](#c-migrate_vma_pages). This is called to migrate struct page
meta-data from source struct page to destination.

#### <a id="c-migrate_vma_pages"></a>`migrate_vma_pages()`

```c
void migrate_vma_pages(struct migrate_vma *migrate)
```

migrate meta-data from src page to dst page

**Parameters**

- `struct migrate_vma *migrate`: migrate struct containing all migration information

**Description**

This migrates struct page meta-data from source struct page to destination
struct page. This effectively finishes the migration from source page to the
destination page.

#### <a id="c-migrate_vma_finalize"></a>`migrate_vma_finalize()`

```c
void migrate_vma_finalize(struct migrate_vma *migrate)
```

restore CPU page table entry

**Parameters**

- `struct migrate_vma *migrate`: migrate struct containing all migration information

**Description**

This replaces the special migration pte entry with either a mapping to the
new page if migration was successful for that page, or to the original page
otherwise.

This also unlocks the pages and puts them back on the lru, or drops the extra
refcount, for device pages.

#### <a id="c-migrate_device_range"></a>`migrate_device_range()`

```c
int migrate_device_range(unsigned long *src_pfns, unsigned long start, unsigned long npages)
```

migrate device private pfns to normal memory.

**Parameters**

- `unsigned long *src_pfns`: array large enough to hold migrating source device private pfns.
- `unsigned long start`: starting pfn in the range to migrate.
- `unsigned long npages`: number of pages to migrate.

**Description**

[`migrate_vma_setup()`](#c-migrate_vma_setup) is similar in concept to [`migrate_vma_setup()`](#c-migrate_vma_setup) except that
instead of looking up pages based on virtual address mappings a range of
device pfns that should be migrated to system memory is used instead.

This is useful when a driver needs to free device memory but doesn't know the
virtual mappings of every page that may be in device memory. For example this
is often the case when a driver is being unloaded or unbound from a device.

Like [`migrate_vma_setup()`](#c-migrate_vma_setup) this function will take a reference and lock any
migrating pages that aren't free before unmapping them. Drivers may then
allocate destination pages and start copying data from the device to CPU
memory before calling [`migrate_device_pages()`](#c-migrate_device_pages).

#### <a id="c-migrate_device_pfns"></a>`migrate_device_pfns()`

```c
int migrate_device_pfns(unsigned long *src_pfns, unsigned long npages)
```

migrate device private pfns to normal memory.

**Parameters**

- `unsigned long *src_pfns`: pre-populated array of source device private pfns to migrate.
- `unsigned long npages`: number of pages to migrate.

**Description**

Similar to [`migrate_device_range()`](#c-migrate_device_range) but supports non-contiguous pre-populated
array of device pages to migrate.


<!-- #kernel-doc:: mm/nommu.c (duplicates kernel-doc from other files) -->


#### <a id="c-struct-wp_walk"></a>`struct wp_walk`

Private struct for pagetable walk callbacks

**Definition**

```c
struct wp_walk {
    struct mmu_notifier_range range;
    unsigned long tlbflush_start;
    unsigned long tlbflush_end;
    unsigned long total;
};
```

**Members**

- `range`: Range for mmu notifiers
- `tlbflush_start`: Address of first modified pte
- `tlbflush_end`: Address of last modified pte + 1
- `total`: Total number of modified ptes

#### <a id="c-wp_pte"></a>`wp_pte()`

```c
int wp_pte(pte_t *pte, unsigned long addr, unsigned long end, struct mm_walk *walk)
```

Write-protect a pte

**Parameters**

- `pte_t *pte`: Pointer to the pte
- `unsigned long addr`: The start of protecting virtual address
- `unsigned long end`: The end of protecting virtual address
- `struct mm_walk *walk`: pagetable walk callback argument

**Description**

The function write-protects a pte and records the range in
virtual address space of touched ptes for efficient range TLB flushes.

#### <a id="c-struct-clean_walk"></a>`struct clean_walk`

Private struct for the clean_record_pte function.

**Definition**

```c
struct clean_walk {
    struct wp_walk base;
    pgoff_t bitmap_pgoff;
    unsigned long *bitmap;
    pgoff_t start;
    pgoff_t end;
};
```

**Members**

- `base`: struct wp_walk we derive from
- `bitmap_pgoff`: Address_space Page offset of the first bit in **bitmap**
- `bitmap`: Bitmap with one bit for each page offset in the address_space range
  covered.
- `start`: Address_space page offset of first modified pte relative
  to **bitmap_pgoff**
- `end`: Address_space page offset of last modified pte relative
  to **bitmap_pgoff**

#### <a id="c-clean_record_pte"></a>`clean_record_pte()`

```c
int clean_record_pte(pte_t *pte, unsigned long addr, unsigned long end, struct mm_walk *walk)
```

Clean a pte and record its address space offset in a bitmap

**Parameters**

- `pte_t *pte`: Pointer to the pte
- `unsigned long addr`: The start of virtual address to be clean
- `unsigned long end`: The end of virtual address to be clean
- `struct mm_walk *walk`: pagetable walk callback argument

**Description**

The function cleans a pte and records the range in
virtual address space of touched ptes for efficient TLB flushes.
It also records dirty ptes in a bitmap representing page offsets
in the address_space, as well as the first and last of the bits
touched.

#### <a id="c-wp_shared_mapping_range"></a>`wp_shared_mapping_range()`

```c
unsigned long wp_shared_mapping_range(struct address_space *mapping, pgoff_t first_index, pgoff_t nr)
```

Write-protect all ptes in an address space range

**Parameters**

- `struct address_space *mapping`: The address_space we want to write protect
- `pgoff_t first_index`: The first page offset in the range
- `pgoff_t nr`: Number of incremental page offsets to cover

**Note**

This function currently skips transhuge page-table entries, since
it's intended for dirty-tracking on the PTE level. It will warn on
encountering transhuge write-enabled entries, though, and can easily be
extended to handle them as well.

**Return**

The number of ptes actually write-protected. Note that
already write-protected ptes are not counted.

#### <a id="c-clean_record_shared_mapping_range"></a>`clean_record_shared_mapping_range()`

```c
unsigned long clean_record_shared_mapping_range(struct address_space *mapping, pgoff_t first_index, pgoff_t nr, pgoff_t bitmap_pgoff, unsigned long *bitmap, pgoff_t *start, pgoff_t *end)
```

Clean and record all ptes in an address space range

**Parameters**

- `struct address_space *mapping`: The address_space we want to clean
- `pgoff_t first_index`: The first page offset in the range
- `pgoff_t nr`: Number of incremental page offsets to cover
- `pgoff_t bitmap_pgoff`: The page offset of the first bit in **bitmap**
- `unsigned long *bitmap`: Pointer to a bitmap of at least **nr** bits. The bitmap needs to
  cover the whole range **first_index**..**first_index** + **nr**.
- `pgoff_t *start`: Pointer to number of the first set bit in **bitmap**.
  is modified as new bits are set by the function.
- `pgoff_t *end`: Pointer to the number of the last set bit in **bitmap**.
  none set. The value is modified as new bits are set by the function.

**Description**

When this function returns there is no guarantee that a CPU has
not already dirtied new ptes. However it will not clean any ptes not
reported in the bitmap. The guarantees are as follows:

* All ptes dirty when the function starts executing will end up recorded
  in the bitmap.
* All ptes dirtied after that will either remain dirty, be recorded in the
  bitmap or both.

If a caller needs to make sure all dirty ptes are picked up and none
additional are added, it first needs to write-protect the address-space
range and make sure new writers are blocked in `page_mkwrite()` or
`pfn_mkwrite()`. And then after a TLB flush following the write-protection
pick up all dirty bits.

This function currently skips transhuge page-table entries, since
it's intended for dirty-tracking on the PTE level. It will warn on
encountering transhuge dirty entries, though, and can easily be extended
to handle them as well.

**Return**

The number of dirty ptes actually cleaned.


<!-- #kernel-doc:: mm/memory-failure.c (build warnings) -->


#### <a id="c-pcpu_addr_in_chunk"></a>`pcpu_addr_in_chunk()`

```c
bool pcpu_addr_in_chunk(struct pcpu_chunk *chunk, void *addr)
```

check if the address is served from this chunk

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `void *addr`: percpu address

**Return**

True if the address is served from this chunk.

#### <a id="c-pcpu_check_block_hint"></a>`pcpu_check_block_hint()`

```c
bool pcpu_check_block_hint(struct pcpu_block_md *block, int bits, size_t align)
```

check against the contig hint

**Parameters**

- `struct pcpu_block_md *block`: block of interest
- `int bits`: size of allocation
- `size_t align`: alignment of area (max PAGE_SIZE)

**Description**

Check to see if the allocation can fit in the block's contig hint.
Note, a chunk uses the same hints as a block so this can also check against
the chunk's contig hint.

#### <a id="c-pcpu_next_md_free_region"></a>`pcpu_next_md_free_region()`

```c
void pcpu_next_md_free_region(struct pcpu_chunk *chunk, int *bit_off, int *bits)
```

finds the next hint free area

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int *bit_off`: chunk offset
- `int *bits`: size of free area

**Description**

Helper function for pcpu_for_each_md_free_region.  It checks
block->contig_hint and performs aggregation across blocks to find the
next hint.  It modifies bit_off and bits in-place to be consumed in the
loop.

#### <a id="c-pcpu_next_fit_region"></a>`pcpu_next_fit_region()`

```c
void pcpu_next_fit_region(struct pcpu_chunk *chunk, int alloc_bits, int align, int *bit_off, int *bits)
```

finds fit areas for a given allocation request

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int alloc_bits`: size of allocation
- `int align`: alignment of area (max PAGE_SIZE)
- `int *bit_off`: chunk offset
- `int *bits`: size of free area

**Description**

Finds the next free region that is viable for use with a given size and
alignment.  This only returns if there is a valid area to be used for this
allocation.  block->first_free is returned if the allocation request fits
within the block to see if the request can be fulfilled prior to the contig
hint.

#### <a id="c-pcpu_mem_zalloc"></a>`pcpu_mem_zalloc()`

```c
void * pcpu_mem_zalloc(size_t size, gfp_t gfp)
```

allocate memory

**Parameters**

- `size_t size`: bytes to allocate
- `gfp_t gfp`: allocation flags

**Description**

Allocate **size** bytes.  If **size** is smaller than PAGE_SIZE,
[`kzalloc()`](#c-kzalloc) is used; otherwise, the equivalent of [`vzalloc()`](#c-vzalloc) is used.
This is to facilitate passing through whitelisted flags.  The
returned memory is always zeroed.

**Return**

Pointer to the allocated area on success, NULL on failure.

#### <a id="c-pcpu_mem_free"></a>`pcpu_mem_free()`

```c
void pcpu_mem_free(void *ptr)
```

free memory

**Parameters**

- `void *ptr`: memory to free

**Description**

Free **ptr**.  **ptr** should have been allocated using [`pcpu_mem_zalloc()`](#c-pcpu_mem_zalloc).

#### <a id="c-pcpu_chunk_relocate"></a>`pcpu_chunk_relocate()`

```c
void pcpu_chunk_relocate(struct pcpu_chunk *chunk, int oslot)
```

put chunk in the appropriate chunk slot

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int oslot`: the previous slot it was on

**Description**

This function is called after an allocation or free changed **chunk**.
New slot according to the changed state is determined and **chunk** is
moved to the slot.  Note that the reserved chunk is never put on
chunk slots.

**Context**

pcpu_lock.

#### <a id="c-pcpu_block_update"></a>`pcpu_block_update()`

```c
void pcpu_block_update(struct pcpu_block_md *block, int start, int end)
```

updates a block given a free area

**Parameters**

- `struct pcpu_block_md *block`: block of interest
- `int start`: start offset in block
- `int end`: end offset in block

**Description**

Updates a block given a known free area.  The region \[start, end) is
expected to be the entirety of the free area within a block.  Chooses
the best starting offset if the contig hints are equal.

#### <a id="c-pcpu_chunk_refresh_hint"></a>`pcpu_chunk_refresh_hint()`

```c
void pcpu_chunk_refresh_hint(struct pcpu_chunk *chunk, bool full_scan)
```

updates metadata about a chunk

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `bool full_scan`: if we should scan from the beginning

**Description**

Iterates over the metadata blocks to find the largest contig area.
A full scan can be avoided on the allocation path as this is triggered
if we broke the contig_hint.  In doing so, the scan_hint will be before
the contig_hint or after if the scan_hint == contig_hint.  This cannot
be prevented on freeing as we want to find the largest area possibly
spanning blocks.

#### <a id="c-pcpu_block_refresh_hint"></a>`pcpu_block_refresh_hint()`

```c
void pcpu_block_refresh_hint(struct pcpu_chunk *chunk, int index)
```

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int index`: index of the metadata block

**Description**

Scans over the block beginning at first_free and updates the block
metadata accordingly.

#### <a id="c-pcpu_block_update_hint_alloc"></a>`pcpu_block_update_hint_alloc()`

```c
void pcpu_block_update_hint_alloc(struct pcpu_chunk *chunk, int bit_off, int bits)
```

update hint on allocation path

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int bit_off`: chunk offset
- `int bits`: size of request

**Description**

Updates metadata for the allocation path.  The metadata only has to be
refreshed by a full scan iff the chunk's contig hint is broken.  Block level
scans are required if the block's contig hint is broken.

#### <a id="c-pcpu_block_update_hint_free"></a>`pcpu_block_update_hint_free()`

```c
void pcpu_block_update_hint_free(struct pcpu_chunk *chunk, int bit_off, int bits)
```

updates the block hints on the free path

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int bit_off`: chunk offset
- `int bits`: size of request

**Description**

Updates metadata for the allocation path.  This avoids a blind block
refresh by making use of the block contig hints.  If this fails, it scans
forward and backward to determine the extent of the free area.  This is
capped at the boundary of blocks.

A chunk update is triggered if a page becomes free, a block becomes free,
or the free spans across blocks.  This tradeoff is to minimize iterating
over the block metadata to update chunk_md->contig_hint.
chunk_md->contig_hint may be off by up to a page, but it will never be more
than the available space.  If the contig hint is contained in one block, it
will be accurate.

#### <a id="c-pcpu_is_populated"></a>`pcpu_is_populated()`

```c
bool pcpu_is_populated(struct pcpu_chunk *chunk, int bit_off, int bits, int *next_off)
```

determines if the region is populated

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int bit_off`: chunk offset
- `int bits`: size of area
- `int *next_off`: return value for the next offset to start searching

**Description**

For atomic allocations, check if the backing pages are populated.

**Return**

Bool if the backing pages are populated.
next_index is to skip over unpopulated blocks in pcpu_find_block_fit.

#### <a id="c-pcpu_find_block_fit"></a>`pcpu_find_block_fit()`

```c
int pcpu_find_block_fit(struct pcpu_chunk *chunk, int alloc_bits, size_t align, bool pop_only)
```

finds the block index to start searching

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int alloc_bits`: size of request in allocation units
- `size_t align`: alignment of area (max PAGE_SIZE bytes)
- `bool pop_only`: use populated regions only

**Description**

Given a chunk and an allocation spec, find the offset to begin searching
for a free region.  This iterates over the bitmap metadata blocks to
find an offset that will be guaranteed to fit the requirements.  It is
not quite first fit as if the allocation does not fit in the contig hint
of a block or chunk, it is skipped.  This errs on the side of caution
to prevent excess iteration.  Poor alignment can cause the allocator to
skip over blocks and chunks that have valid free areas.

**Return**

The offset in the bitmap to begin searching.
-1 if no offset is found.

#### <a id="c-pcpu_alloc_area"></a>`pcpu_alloc_area()`

```c
int pcpu_alloc_area(struct pcpu_chunk *chunk, int alloc_bits, size_t align, int start)
```

allocates an area from a pcpu_chunk

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int alloc_bits`: size of request in allocation units
- `size_t align`: alignment of area (max PAGE_SIZE)
- `int start`: bit_off to start searching

**Description**

This function takes in a **start** offset to begin searching to fit an
allocation of **alloc_bits** with alignment **align**.  It needs to scan
the allocation map because if it fits within the block's contig hint,
**start** will be block->first_free. This is an attempt to fill the
allocation prior to breaking the contig hint.  The allocation and
boundary maps are updated accordingly if it confirms a valid
free area.

**Return**

Allocated addr offset in **chunk** on success.
-1 if no matching area is found.

#### <a id="c-pcpu_free_area"></a>`pcpu_free_area()`

```c
int pcpu_free_area(struct pcpu_chunk *chunk, int off)
```

frees the corresponding offset

**Parameters**

- `struct pcpu_chunk *chunk`: chunk of interest
- `int off`: addr offset into chunk

**Description**

This function determines the size of an allocation to free using
the boundary bitmap and clears the allocation map.

**Return**

Number of freed bytes.

#### <a id="c-pcpu_alloc_first_chunk"></a>`pcpu_alloc_first_chunk()`

```c
struct pcpu_chunk * pcpu_alloc_first_chunk(unsigned long tmp_addr, int map_size)
```

creates chunks that serve the first chunk

**Parameters**

- `unsigned long tmp_addr`: the start of the region served
- `int map_size`: size of the region served

**Description**

This is responsible for creating the chunks that serve the first chunk.  The
base_addr is page aligned down of **tmp_addr** while the region end is page
aligned up.  Offsets are kept track of to determine the region served. All
this is done to appease the bitmap allocator in avoiding partial blocks.

**Return**

Chunk serving the region at **tmp_addr** of **map_size**.

#### <a id="c-pcpu_chunk_populated"></a>`pcpu_chunk_populated()`

```c
void pcpu_chunk_populated(struct pcpu_chunk *chunk, int page_start, int page_end)
```

post-population bookkeeping

**Parameters**

- `struct pcpu_chunk *chunk`: pcpu_chunk which got populated
- `int page_start`: the start page
- `int page_end`: the end page

**Description**

Pages in \[**page_start**,**page_end**) have been populated to **chunk**.  Update
the bookkeeping information accordingly.  Must be called after each
successful population.

#### <a id="c-pcpu_chunk_depopulated"></a>`pcpu_chunk_depopulated()`

```c
void pcpu_chunk_depopulated(struct pcpu_chunk *chunk, int page_start, int page_end)
```

post-depopulation bookkeeping

**Parameters**

- `struct pcpu_chunk *chunk`: pcpu_chunk which got depopulated
- `int page_start`: the start page
- `int page_end`: the end page

**Description**

Pages in \[**page_start**,**page_end**) have been depopulated from **chunk**.
Update the bookkeeping information accordingly.  Must be called after
each successful depopulation.

#### <a id="c-pcpu_chunk_addr_search"></a>`pcpu_chunk_addr_search()`

```c
struct pcpu_chunk * pcpu_chunk_addr_search(void *addr)
```

determine chunk containing specified address

**Parameters**

- `void *addr`: address for which the chunk needs to be determined.

**Description**

This is an internal function that handles all but static allocations.
Static percpu address values should never be passed into the allocator.

**Return**

The address of the found chunk.

#### <a id="c-pcpu_alloc"></a>`pcpu_alloc()`

```c
void __percpu * pcpu_alloc(size_t size, size_t align, bool reserved, gfp_t gfp)
```

the percpu allocator

**Parameters**

- `size_t size`: size of area to allocate in bytes
- `size_t align`: alignment of area (max PAGE_SIZE)
- `bool reserved`: allocate from the reserved chunk if available
- `gfp_t gfp`: allocation flags

**Description**

Allocate percpu area of **size** bytes aligned at **align**.  If **gfp** doesn't
contain `GFP_KERNEL`, the allocation is atomic. If **gfp** has __GFP_NOWARN
then no warning will be triggered on invalid or failed allocation
requests.

**Return**

Percpu pointer to the allocated area on success, NULL on failure.

#### <a id="c-pcpu_balance_free"></a>`pcpu_balance_free()`

```c
void pcpu_balance_free(bool empty_only)
```

manage the amount of free chunks

**Parameters**

- `bool empty_only`: free chunks only if there are no populated pages

**Description**

If empty_only is `false`, reclaim all fully free chunks regardless of the
number of populated pages.  Otherwise, only reclaim chunks that have no
populated pages.

**Context**

pcpu_lock (can be dropped temporarily)

#### <a id="c-pcpu_balance_populated"></a>`pcpu_balance_populated()`

```c
void pcpu_balance_populated(void)
```

manage the amount of populated pages

**Parameters**

- `void`: no arguments

**Description**

Maintain a certain amount of populated pages to satisfy atomic allocations.
It is possible that this is called when physical memory is scarce causing
OOM killer to be triggered.  We should avoid doing so until an actual
allocation causes the failure as it is possible that requests can be
serviced from already backed regions.

**Context**

pcpu_lock (can be dropped temporarily)

#### <a id="c-pcpu_reclaim_populated"></a>`pcpu_reclaim_populated()`

```c
void pcpu_reclaim_populated(void)
```

scan over to_depopulate chunks and free empty pages

**Parameters**

- `void`: no arguments

**Description**

Scan over chunks in the depopulate list and try to release unused populated
pages back to the system.  Depopulated chunks are sidelined to prevent
repopulating these pages unless required.  Fully free chunks are reintegrated
and freed accordingly (1 is kept around).  If we drop below the empty
populated pages threshold, reintegrate the chunk if it has empty free pages.
Each chunk is scanned in the reverse order to keep populated pages close to
the beginning of the chunk.

**Context**

pcpu_lock (can be dropped temporarily)

#### <a id="c-pcpu_balance_workfn"></a>`pcpu_balance_workfn()`

```c
void pcpu_balance_workfn(struct work_struct *work)
```

manage the amount of free chunks and populated pages

**Parameters**

- `struct work_struct *work`: unused

**Description**

For each chunk type, manage the number of fully free chunks and the number of
populated pages.  An important thing to consider is when pages are freed and
how they contribute to the global counts.

#### <a id="c-free_percpu"></a>`free_percpu()`

```c
void free_percpu(void __percpu *ptr)
```

free percpu area

**Parameters**

- `void __percpu *ptr`: pointer to area to free

**Description**

Free percpu area **ptr**.

**Context**

Can be called from atomic context.

#### <a id="c-is_kernel_percpu_address"></a>`is_kernel_percpu_address()`

```c
bool is_kernel_percpu_address(unsigned long addr)
```

test whether address is from static percpu area

**Parameters**

- `unsigned long addr`: address to test

**Description**

Test whether **addr** belongs to in-kernel static percpu area.  Module
static percpu areas are not considered.  For those, use
`is_module_percpu_address()`.

**Return**

`true` if **addr** is from in-kernel static percpu area, `false` otherwise.

#### <a id="c-per_cpu_ptr_to_phys"></a>`per_cpu_ptr_to_phys()`

```c
phys_addr_t per_cpu_ptr_to_phys(void *addr)
```

convert translated percpu address to physical address

**Parameters**

- `void *addr`: the address to be converted to physical address

**Description**

Given **addr** which is dereferenceable address obtained via one of
percpu access macros, this function translates it into its physical
address.  The caller is responsible for ensuring **addr** stays valid
until this function finishes.

percpu allocator has special setup for the first chunk, which currently
supports either embedding in linear address space or vmalloc mapping,
and, from the second one, the backing allocator (currently either vm or
km) provides translation.

The addr can be translated simply without checking if it falls into the
first chunk. But the current code reflects better how percpu allocator
actually works, and the verification can discover both bugs in percpu
allocator itself and [`per_cpu_ptr_to_phys()`](#c-per_cpu_ptr_to_phys) callers. So we keep current
code.

**Return**

The physical address for **addr**.

#### <a id="c-pcpu_alloc_alloc_info"></a>`pcpu_alloc_alloc_info()`

```c
struct pcpu_alloc_info * pcpu_alloc_alloc_info(int nr_groups, int nr_units)
```

allocate percpu allocation info

**Parameters**

- `int nr_groups`: the number of groups
- `int nr_units`: the number of units

**Description**

Allocate ai which is large enough for **nr_groups** groups containing
**nr_units** units.  The returned ai's groups\[0\].cpu_map points to the
cpu_map array which is long enough for **nr_units** and filled with
NR_CPUS.  It's the caller's responsibility to initialize cpu_map
pointer of other groups.

**Return**

Pointer to the allocated pcpu_alloc_info on success, NULL on
failure.

#### <a id="c-pcpu_free_alloc_info"></a>`pcpu_free_alloc_info()`

```c
void pcpu_free_alloc_info(struct pcpu_alloc_info *ai)
```

free percpu allocation info

**Parameters**

- `struct pcpu_alloc_info *ai`: pcpu_alloc_info to free

**Description**

Free **ai** which was allocated by [`pcpu_alloc_alloc_info()`](#c-pcpu_alloc_alloc_info).

#### <a id="c-pcpu_dump_alloc_info"></a>`pcpu_dump_alloc_info()`

```c
void pcpu_dump_alloc_info(const char *lvl, const struct pcpu_alloc_info *ai)
```

print out information about pcpu_alloc_info

**Parameters**

- `const char *lvl`: loglevel
- `const struct pcpu_alloc_info *ai`: allocation info to dump

**Description**

Print out information about **ai** using loglevel **lvl**.

#### <a id="c-pcpu_setup_first_chunk"></a>`pcpu_setup_first_chunk()`

```c
void pcpu_setup_first_chunk(const struct pcpu_alloc_info *ai, void *base_addr)
```

initialize the first percpu chunk

**Parameters**

- `const struct pcpu_alloc_info *ai`: pcpu_alloc_info describing how to percpu area is shaped
- `void *base_addr`: mapped address

**Description**

Initialize the first percpu chunk which contains the kernel static
percpu area.  This function is to be called from arch percpu area
setup path.

**ai** contains all information necessary to initialize the first
chunk and prime the dynamic percpu allocator.

**ai->static_size** is the size of static percpu area.

**ai->reserved_size**, if non-zero, specifies the amount of bytes to
reserve after the static area in the first chunk.  This reserves
the first chunk such that it's available only through reserved
percpu allocation.  This is primarily used to serve module percpu
static areas on architectures where the addressing model has
limited offset range for symbol relocations to guarantee module
percpu symbols fall inside the relocatable range.

**ai->dyn_size** determines the number of bytes available for dynamic
allocation in the first chunk.  The area between **ai->static_size** +
**ai->reserved_size** + **ai->dyn_size** and **ai->unit_size** is unused.

**ai->unit_size** specifies unit size and must be aligned to PAGE_SIZE
and equal to or larger than **ai->static_size** + **ai->reserved_size** +
**ai->dyn_size**.

**ai->atom_size** is the allocation atom size and used as alignment
for vm areas.

**ai->alloc_size** is the allocation size and always multiple of
**ai->atom_size**.  This is larger than **ai->atom_size** if
**ai->unit_size** is larger than **ai->atom_size**.

**ai->nr_groups** and **ai->groups** describe virtual memory layout of
percpu areas.  Units which should be colocated are put into the
same group.  Dynamic VM areas will be allocated according to these
groupings.  If **ai->nr_groups** is zero, a single group containing
all units is assumed.

The caller should have mapped the first chunk at **base_addr** and
copied static data to each unit.

The first chunk will always contain a static and a dynamic region.
However, the static region is not managed by any chunk.  If the first
chunk also contains a reserved region, it is served by two chunks -
one for the reserved region and one for the dynamic region.  They
share the same vm, but use offset regions in the area allocation map.
The chunk serving the dynamic region is circulated in the chunk slots
and available for dynamic allocation like any other chunk.

#### <a id="c-pcpu_build_alloc_info"></a>`pcpu_build_alloc_info()`

```c
struct pcpu_alloc_info * pcpu_build_alloc_info(size_t reserved_size, size_t dyn_size, size_t atom_size, pcpu_fc_cpu_distance_fn_t cpu_distance_fn)
```

build alloc_info considering distances between CPUs

**Parameters**

- `size_t reserved_size`: the size of reserved percpu area in bytes
- `size_t dyn_size`: minimum free size for dynamic allocation in bytes
- `size_t atom_size`: allocation atom size
- `pcpu_fc_cpu_distance_fn_t cpu_distance_fn`: callback to determine distance between cpus, optional

**Description**

This function determines grouping of units, their mappings to cpus
and other parameters considering needed percpu size, allocation
atom size and distances between CPUs.

Groups are always multiples of atom size and CPUs which are of
LOCAL_DISTANCE both ways are grouped together and share space for
units in the same group.  The returned configuration is guaranteed
to have CPUs on different nodes on different groups and >=75% usage
of allocated virtual address space.

**Return**

On success, pointer to the new allocation_info is returned.  On
failure, ERR_PTR value is returned.

#### <a id="c-pcpu_embed_first_chunk"></a>`pcpu_embed_first_chunk()`

```c
int pcpu_embed_first_chunk(size_t reserved_size, size_t dyn_size, size_t atom_size, pcpu_fc_cpu_distance_fn_t cpu_distance_fn, pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn)
```

embed the first percpu chunk into bootmem

**Parameters**

- `size_t reserved_size`: the size of reserved percpu area in bytes
- `size_t dyn_size`: minimum free size for dynamic allocation in bytes
- `size_t atom_size`: allocation atom size
- `pcpu_fc_cpu_distance_fn_t cpu_distance_fn`: callback to determine distance between cpus, optional
- `pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn`: callback to convert cpu to it's node, optional

**Description**

This is a helper to ease setting up embedded first percpu chunk and
can be called where [`pcpu_setup_first_chunk()`](#c-pcpu_setup_first_chunk) is expected.

If this function is used to setup the first chunk, it is allocated
by calling pcpu_fc_alloc and used as-is without being mapped into
vmalloc area.  Allocations are always whole multiples of **atom_size**
aligned to **atom_size**.

This enables the first chunk to piggy back on the linear physical
mapping which often uses larger page size.  Please note that this
can result in very sparse cpu->unit mapping on NUMA machines thus
requiring large vmalloc address space.  Don't use this allocator if
vmalloc space is not orders of magnitude larger than distances
between node memory addresses (ie. 32bit NUMA machines).

**dyn_size** specifies the minimum dynamic area size.

If the needed size is smaller than the minimum or specified unit
size, the leftover is returned using pcpu_fc_free.

**Return**

0 on success, -errno on failure.

#### <a id="c-pcpu_page_first_chunk"></a>`pcpu_page_first_chunk()`

```c
int pcpu_page_first_chunk(size_t reserved_size, pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn)
```

map the first chunk using PAGE_SIZE pages

**Parameters**

- `size_t reserved_size`: the size of reserved percpu area in bytes
- `pcpu_fc_cpu_to_node_fn_t cpu_to_nd_fn`: callback to convert cpu to it's node, optional

**Description**

This is a helper to ease setting up page-remapped first percpu
chunk and can be called where [`pcpu_setup_first_chunk()`](#c-pcpu_setup_first_chunk) is expected.

This is the basic allocator.  Static percpu area is allocated
page-by-page into vmalloc area.

**Return**

0 on success, -errno on failure.



#### <a id="c-copy_from_user_nofault"></a>`copy_from_user_nofault()`

```c
long copy_from_user_nofault(void *dst, const void __user *src, size_t size)
```

safely attempt to read from a user-space location

**Parameters**

- `void *dst`: pointer to the buffer that shall take the data
- `const void __user *src`: address to read from. This must be a user address.
- `size_t size`: size of the data chunk

**Description**

Safely read from user address **src** to the buffer at **dst**. If a kernel fault
happens, handle that and return -EFAULT.

#### <a id="c-copy_to_user_nofault"></a>`copy_to_user_nofault()`

```c
long copy_to_user_nofault(void __user *dst, const void *src, size_t size)
```

safely attempt to write to a user-space location

**Parameters**

- `void __user *dst`: address to write to
- `const void *src`: pointer to the data that shall be written
- `size_t size`: size of the data chunk

**Description**

Safely write to address **dst** from the buffer at **src**.  If a kernel fault
happens, handle that and return -EFAULT.

#### <a id="c-strncpy_from_user_nofault"></a>`strncpy_from_user_nofault()`

```c
long strncpy_from_user_nofault(char *dst, const void __user *unsafe_addr, long count)
```

- Copy a NUL terminated string from unsafe user address.

**Parameters**

- `char *dst`: Destination address, in kernel space.  This buffer must be at
  least **count** bytes long.
- `const void __user *unsafe_addr`: Unsafe user address.
- `long count`: Maximum number of bytes to copy, including the trailing NUL.

**Description**

Copies a NUL-terminated string from unsafe user address to kernel buffer.

On success, returns the length of the string INCLUDING the trailing NUL.

If access fails, returns -EFAULT (some data may have been copied
and the trailing NUL added).

If **count** is smaller than the length of the string, copies **count**-1 bytes,
sets the last byte of **dst** buffer to NUL and returns **count**.

#### <a id="c-strnlen_user_nofault"></a>`strnlen_user_nofault()`

```c
long strnlen_user_nofault(const void __user *unsafe_addr, long count)
```

- Get the size of a user string INCLUDING final NUL.

**Parameters**

- `const void __user *unsafe_addr`: The string to measure.
- `long count`: Maximum count (including NUL)

**Description**

Get the size of a NUL-terminated string in user space without pagefault.

Returns the size of the string INCLUDING the terminating NUL.

If the string is too long, returns a number larger than **count**. User
has to check the return value against "> count".
On exception (or invalid count), returns 0.

Unlike strnlen_user, this can be used from IRQ handler etc. because
it disables pagefaults.



#### <a id="c-writeback_throttling_sane"></a>`writeback_throttling_sane()`

```c
bool writeback_throttling_sane(struct scan_control *sc)
```

is the usual dirty throttling mechanism available?

**Parameters**

- `struct scan_control *sc`: scan_control in question

**Description**

The normal page dirty throttling mechanism in `balance_dirty_pages()` is
completely broken with the legacy memcg and direct stalling in
`shrink_folio_list()` is used for throttling instead, which lacks all the
niceties such as fairness, adaptive pausing, bandwidth proportional
allocation and configurability.

This function tests whether the vmscan currently in progress can assume
that the normal dirty throttling mechanism is operational.

#### <a id="c-lruvec_lru_size"></a>`lruvec_lru_size()`

```c
unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
```

Returns the number of pages on the given LRU list.

**Parameters**

- `struct lruvec *lruvec`: lru vector
- `enum lru_list lru`: lru to use
- `int zone_idx`: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)

#### <a id="c-remove_mapping"></a>`remove_mapping()`

```c
long remove_mapping(struct address_space *mapping, struct folio *folio)
```

Attempt to remove a folio from its mapping.

**Parameters**

- `struct address_space *mapping`: The address space.
- `struct folio *folio`: The folio to remove.

**Description**

If the folio is dirty, under writeback or if someone else has a ref
on it, removal will fail.

**Return**

The number of pages removed from the mapping.  0 if the folio
could not be removed.

**Context**

The caller should have a single refcount on the folio and
hold its lock.

#### <a id="c-folio_putback_lru"></a>`folio_putback_lru()`

```c
void folio_putback_lru(struct folio *folio)
```

Put previously isolated folio onto appropriate LRU list.

**Parameters**

- `struct folio *folio`: Folio to be returned to an LRU list.

**Description**

Add previously isolated **folio** to appropriate LRU list.
The folio may still be unevictable for other reasons.

**Context**

lru_lock must not be held, interrupts must be enabled.

#### <a id="c-folio_isolate_lru"></a>`folio_isolate_lru()`

```c
bool folio_isolate_lru(struct folio *folio)
```

Try to isolate a folio from its LRU list.

**Parameters**

- `struct folio *folio`: Folio to isolate from its LRU list.

**Description**

Isolate a **folio** from an LRU list and adjust the vmstat statistic
corresponding to whatever LRU list the folio was on.

The folio will have its LRU flag cleared.  If it was found on the
active list, it will have the Active flag set.  If it was found on the
unevictable list, it will have the Unevictable flag set.  These flags
may need to be cleared by the caller before letting the page go.

- (1) Must be called with an elevated refcount on the folio. This is a

  fundamental difference from `isolate_lru_folios()` (which is called
  without a stable reference).
(2) The lru_lock must not be held.
(3) Interrupts must be enabled.

**Context**

**Return**

true if the folio was removed from an LRU list.
false if the folio was not on an LRU list.

#### <a id="c-check_move_unevictable_folios"></a>`check_move_unevictable_folios()`

```c
void check_move_unevictable_folios(struct folio_batch *fbatch)
```

Move evictable folios to appropriate zone lru list

**Parameters**

- `struct folio_batch *fbatch`: Batch of lru folios to check.

**Description**

Checks folios for evictability, if an evictable folio is in the unevictable
lru list, moves it to the appropriate evictable lru list. This function
should be only used for lru folios.



#### <a id="c-__remove_pages"></a>`__remove_pages()`

```c
void __remove_pages(unsigned long pfn, unsigned long nr_pages, struct vmem_altmap *altmap)
```

remove sections of pages

**Parameters**

- `unsigned long pfn`: starting pageframe (must be aligned to start of a section)
- `unsigned long nr_pages`: number of pages to remove (must be multiple of section size)
- `struct vmem_altmap *altmap`: alternative device page map or `NULL` if default memmap is used

**Description**

Generic helper function to remove section mappings and sysfs entries
for the section of the memory we are removing. Caller needs to make
sure that pages are marked reserved and zones are adjust properly by
calling `offline_pages()`.

#### <a id="c-try_offline_node"></a>`try_offline_node()`

```c
void try_offline_node(int nid)
```

**Parameters**

- `int nid`: the node ID

**Description**

Offline a node if all memory sections and cpus of the node are removed.

**NOTE**

The caller must call `lock_device_hotplug()` to serialize hotplug
and online/offline operations before this call.

#### <a id="c-__remove_memory"></a>`__remove_memory()`

```c
void __remove_memory(u64 start, u64 size)
```

Remove memory if every memory block is offline

**Parameters**

- `u64 start`: physical address of the region to remove
- `u64 size`: size of the region to remove

**NOTE**

The caller must call `lock_device_hotplug()` to serialize hotplug
and online/offline operations before this call, as required by
[`try_offline_node()`](#c-try_offline_node).



#### <a id="c-mmu_interval_read_begin"></a>`mmu_interval_read_begin()`

```c
unsigned long mmu_interval_read_begin(struct mmu_interval_notifier *interval_sub)
```

Begin a read side critical section against a VA range

**Parameters**

- `struct mmu_interval_notifier *interval_sub`: The interval subscription

**Description**

`mmu_iterval_read_begin()`/`mmu_iterval_read_retry()` implement a
collision-retry scheme similar to seqcount for the VA range under
subscription. If the mm invokes invalidation during the critical section
then `mmu_interval_read_retry()` will return true.

This is useful to obtain shadow PTEs where teardown or setup of the SPTEs
require a blocking context.  The critical region formed by this can sleep,
and the required 'user_lock' can also be a sleeping lock.

The caller is required to provide a 'user_lock' to serialize both teardown
and setup.

The return value should be passed to `mmu_interval_read_retry()`.

#### <a id="c-mmu_notifier_register"></a>`mmu_notifier_register()`

```c
int mmu_notifier_register(struct mmu_notifier *subscription, struct mm_struct *mm)
```

Register a notifier on a mm

**Parameters**

- `struct mmu_notifier *subscription`: The notifier to attach
- `struct mm_struct *mm`: The mm to attach the notifier to

**Description**

Must not hold mmap_lock nor any other VM related lock when calling
this registration function. Must also ensure mm_users can't go down
to zero while this runs to avoid races with mmu_notifier_release,
so mm has to be current->mm or the mm should be pinned safely such
as with `get_task_mm()`. If the mm is not current->mm, the mm_users
pin should be released by calling mmput after mmu_notifier_register
returns.

`mmu_notifier_unregister()` or [`mmu_notifier_put()`](#c-mmu_notifier_put) must be always called to
unregister the notifier.

While the caller has a mmu_notifier get the subscription->mm pointer will remain
valid, and can be converted to an active mm pointer via `mmget_not_zero()`.

#### <a id="c-mmu_notifier_get_locked"></a>`mmu_notifier_get_locked()`

```c
struct mmu_notifier * mmu_notifier_get_locked(const struct mmu_notifier_ops *ops, struct mm_struct *mm)
```

Return the single struct mmu_notifier for the mm & ops

**Parameters**

- `const struct mmu_notifier_ops *ops`: The operations struct being subscribe with
- `struct mm_struct *mm`: The mm to attach notifiers too

**Description**

This function either allocates a new mmu_notifier via
ops->`alloc_notifier()`, or returns an already existing notifier on the
list. The value of the ops pointer is used to determine when two notifiers
are the same.

Each call to `mmu_notifier_get()` must be paired with a call to
[`mmu_notifier_put()`](#c-mmu_notifier_put). The caller must hold the write side of mm->mmap_lock.

While the caller has a mmu_notifier get the mm pointer will remain valid,
and can be converted to an active mm pointer via `mmget_not_zero()`.

#### <a id="c-mmu_notifier_put"></a>`mmu_notifier_put()`

```c
void mmu_notifier_put(struct mmu_notifier *subscription)
```

Release the reference on the notifier

**Parameters**

- `struct mmu_notifier *subscription`: The notifier to act on

**Description**

This function must be paired with each `mmu_notifier_get()`, it releases the
reference obtained by the get. If this is the last reference then process
to free the notifier will be run asynchronously.

Unlike `mmu_notifier_unregister()` the get/put flow only calls ops->release
when the mm_struct is destroyed. Instead free_notifier is always called to
release any resources held by the user.

As ops->release is not guaranteed to be called, the user must ensure that
all sptes are dropped, and no new sptes can be established before
[`mmu_notifier_put()`](#c-mmu_notifier_put) is called.

This function can be called from the ops->release callback, however the
caller must still ensure it is called pairwise with `mmu_notifier_get()`.

Modules calling this function must call [`mmu_notifier_synchronize()`](#c-mmu_notifier_synchronize) in
their __exit functions to ensure the async work is completed.

#### <a id="c-mmu_interval_notifier_insert"></a>`mmu_interval_notifier_insert()`

```c
int mmu_interval_notifier_insert(struct mmu_interval_notifier *interval_sub, struct mm_struct *mm, unsigned long start, unsigned long length, const struct mmu_interval_notifier_ops *ops)
```

Insert an interval notifier

**Parameters**

- `struct mmu_interval_notifier *interval_sub`: Interval subscription to register
- `struct mm_struct *mm`: mm_struct to attach to
- `unsigned long start`: Starting virtual address to monitor
- `unsigned long length`: Length of the range to monitor
- `const struct mmu_interval_notifier_ops *ops`: Interval notifier operations to be called on matching events

**Description**

This function subscribes the interval notifier for notifications from the
mm.  Upon return the ops related to mmu_interval_notifier will be called
whenever an event that intersects with the given range occurs.

Upon return the range_notifier may not be present in the interval tree yet.
The caller must use the normal interval notifier read flow via
[`mmu_interval_read_begin()`](#c-mmu_interval_read_begin) to establish SPTEs for this range.

#### <a id="c-mmu_interval_notifier_remove"></a>`mmu_interval_notifier_remove()`

```c
void mmu_interval_notifier_remove(struct mmu_interval_notifier *interval_sub)
```

Remove a interval notifier

**Parameters**

- `struct mmu_interval_notifier *interval_sub`: Interval subscription to unregister

**Description**

This function must be paired with [`mmu_interval_notifier_insert()`](#c-mmu_interval_notifier_insert). It cannot
be called from any ops callback.

Once this returns ops callbacks are no longer running on other CPUs and
will not be called in future.

#### <a id="c-mmu_notifier_synchronize"></a>`mmu_notifier_synchronize()`

```c
void mmu_notifier_synchronize(void)
```

Ensure all mmu_notifiers are freed

**Parameters**

- `void`: no arguments

**Description**

This function ensures that all outstanding async SRU work from
[`mmu_notifier_put()`](#c-mmu_notifier_put) is completed. After it returns any mmu_notifier_ops
associated with an unused mmu_notifier will no longer be called.

Before using the caller must ensure that all of its mmu_notifiers have been
fully released via [`mmu_notifier_put()`](#c-mmu_notifier_put).

Modules using the [`mmu_notifier_put()`](#c-mmu_notifier_put) API should call this in their __exit
function to avoid module unloading races.



#### <a id="c-balloon_page_insert"></a>`balloon_page_insert()`

```c
void balloon_page_insert(struct balloon_dev_info *balloon, struct page *page)
```

insert a page into the balloon's page list and make the page->private assignment accordingly.

**Parameters**

- `struct balloon_dev_info *balloon`: pointer to balloon device
- `struct page *page`: page to be assigned as a 'balloon page'

**Description**

Caller must ensure the balloon_pages_lock is held.

#### <a id="c-balloon_page_finalize"></a>`balloon_page_finalize()`

```c
void balloon_page_finalize(struct page *page)
```

prepare a balloon page that was removed from the balloon list for release to the page allocator

**Parameters**

- `struct page *page`: page to be released to the page allocator

**Description**

Caller must ensure the balloon_pages_lock is held.

#### <a id="c-balloon_page_list_enqueue"></a>`balloon_page_list_enqueue()`

```c
size_t balloon_page_list_enqueue(struct balloon_dev_info *b_dev_info, struct list_head *pages)
```

inserts a list of pages into the balloon page list.

**Parameters**

- `struct balloon_dev_info *b_dev_info`: balloon device descriptor where we will insert a new page to
- `struct list_head *pages`: pages to enqueue - allocated using balloon_page_alloc.

**Description**

Driver must call this function to properly enqueue balloon pages before
definitively removing them from the guest system.

**Return**

number of pages that were enqueued.

#### <a id="c-balloon_page_list_dequeue"></a>`balloon_page_list_dequeue()`

```c
size_t balloon_page_list_dequeue(struct balloon_dev_info *b_dev_info, struct list_head *pages, size_t n_req_pages)
```

removes pages from balloon's page list and returns a list of the pages.

**Parameters**

- `struct balloon_dev_info *b_dev_info`: balloon device descriptor where we will grab a page from.
- `struct list_head *pages`: pointer to the list of pages that would be returned to the caller.
- `size_t n_req_pages`: number of requested pages.

**Description**

Driver must call this function to properly de-allocate a previous enlisted
balloon pages before definitively releasing it back to the guest system.
This function tries to remove **n_req_pages** from the ballooned pages and
return them to the caller in the **pages** list.

Note that this function may fail to dequeue some pages even if the balloon
isn't empty - since the page list can be temporarily empty due to compaction
of isolated pages.

**Return**

number of pages that were added to the **pages** list.

#### <a id="c-balloon_page_alloc"></a>`balloon_page_alloc()`

```c
struct page * balloon_page_alloc(void)
```

allocates a new page for insertion into the balloon page list.

**Parameters**

- `void`: no arguments

**Description**

Driver must call this function to properly allocate a new balloon page.
Driver must call balloon_page_enqueue before definitively removing the page
from the guest system.

**Return**

struct page for the allocated page or NULL on allocation failure.

#### <a id="c-balloon_page_enqueue"></a>`balloon_page_enqueue()`

```c
void balloon_page_enqueue(struct balloon_dev_info *b_dev_info, struct page *page)
```

inserts a new page into the balloon page list.

**Parameters**

- `struct balloon_dev_info *b_dev_info`: balloon device descriptor where we will insert a new page
- `struct page *page`: new page to enqueue - allocated using balloon_page_alloc.

**Description**

Drivers must call this function to properly enqueue a new allocated balloon
page before definitively removing the page from the guest system.

Drivers must not enqueue pages while page->lru is still in
use, and must not use page->lru until a page was unqueued again.

#### <a id="c-balloon_page_dequeue"></a>`balloon_page_dequeue()`

```c
struct page * balloon_page_dequeue(struct balloon_dev_info *b_dev_info)
```

removes a page from balloon's page list and returns its address to allow the driver to release the page.

**Parameters**

- `struct balloon_dev_info *b_dev_info`: balloon device descriptor where we will grab a page from.

**Description**

Driver must call this function to properly dequeue a previously enqueued page
before definitively releasing it back to the guest system.

Caller must perform its own accounting to ensure that this
function is called only if some pages are actually enqueued.

Note that this function may fail to dequeue some pages even if there are
some enqueued pages - since the page list can be temporarily empty due to
the compaction of isolated pages.

TODO: remove the caller accounting requirements, and allow caller to wait
until all pages can be dequeued.

**Return**

struct page for the dequeued page, or NULL if no page was dequeued.



#### <a id="c-vmf_insert_pfn_pmd"></a>`vmf_insert_pfn_pmd()`

```c
vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, unsigned long pfn, bool write)
```

insert a pmd size pfn

**Parameters**

- `struct vm_fault *vmf`: Structure describing the fault
- `unsigned long pfn`: pfn to insert
- `bool write`: whether it's a write fault

**Description**

Insert a pmd size pfn. See [`vmf_insert_pfn()`](#c-vmf_insert_pfn) for additional info.

**Return**

vm_fault_t value.

#### <a id="c-vmf_insert_pfn_pud"></a>`vmf_insert_pfn_pud()`

```c
vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, unsigned long pfn, bool write)
```

insert a pud size pfn

**Parameters**

- `struct vm_fault *vmf`: Structure describing the fault
- `unsigned long pfn`: pfn to insert
- `bool write`: whether it's a write fault

**Description**

Insert a pud size pfn. See [`vmf_insert_pfn()`](#c-vmf_insert_pfn) for additional info.

**Return**

vm_fault_t value.

#### <a id="c-vmf_insert_folio_pud"></a>`vmf_insert_folio_pud()`

```c
vm_fault_t vmf_insert_folio_pud(struct vm_fault *vmf, struct folio *folio, bool write)
```

insert a pud size folio mapped by a pud entry

**Parameters**

- `struct vm_fault *vmf`: Structure describing the fault
- `struct folio *folio`: folio to insert
- `bool write`: whether it's a write fault

**Return**

vm_fault_t value.

#### <a id="c-touch_pmd"></a>`touch_pmd()`

```c
bool touch_pmd(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmd, bool write)
```

Mark page table pmd entry as accessed and dirty (for write)

**Parameters**

- `struct vm_area_struct *vma`: The VMA covering **addr**
- `unsigned long addr`: The virtual address
- `pmd_t *pmd`: pmd pointer into the page table mapping **addr**
- `bool write`: Whether it's a write access

**Return**

whether the pmd entry is changed

#### <a id="c-__split_unmapped_folio"></a>`__split_unmapped_folio()`

```c
int __split_unmapped_folio(struct folio *folio, int new_order, struct page *split_at, struct xa_state *xas, struct address_space *mapping, enum split_type split_type)
```

splits an unmapped **folio** to lower order folios in two ways: uniform split or non-uniform split.

**Parameters**

- `struct folio *folio`: the to-be-split folio
- `int new_order`: the smallest order of the after split folios (since buddy
  allocator like split generates folios with orders from **folio**'s
  order - 1 to new_order).
- `struct page *split_at`: in buddy allocator like split, the folio containing **split_at**
  will be split until its order becomes **new_order**.
- `struct xa_state *xas`: xa_state pointing to folio->mapping->i_pages and locked by caller
- `struct address_space *mapping`:

  **folio->mapping**
- `enum split_type split_type`: if the split is uniform or not (buddy allocator like split)

**Description**

1. uniform split: the given **folio** into multiple **new_order** small folios,
   where all small folios have the same order. This is done when
   split_type is SPLIT_TYPE_UNIFORM.
2. buddy allocator like (non-uniform) split: the given **folio** is split into
   half and one of the half (containing the given page) is split into half
   until the given **folio**'s order becomes **new_order**. This is done when
   split_type is SPLIT_TYPE_NON_UNIFORM.

The high level flow for these two methods are:

1. uniform split: **xas** is split with no expectation of failure and a single
   `__split_folio_to_order()` is called to split the **folio** into **new_order**
   along with stats update.
2. non-uniform split: folio_order - **new_order** calls to
   `__split_folio_to_order()` are expected to be made in a for loop to split
   the **folio** to one lower order at a time. The folio containing **split_at**
   is split in each iteration. **xas** is split into half in each iteration and
   can fail. A failed **xas** split leaves split folios as is without merging
   them back.

After splitting, the caller's folio reference will be transferred to the
folio containing **split_at**. The caller needs to unlock and/or free
after-split folios if necessary.

**Return**

0 - successful, \<0 - failed (if -ENOMEM is returned, **folio** might be
split but not to **new_order**, the caller needs to check)

#### <a id="c-folio_check_splittable"></a>`folio_check_splittable()`

```c
int folio_check_splittable(struct folio *folio, unsigned int new_order, enum split_type split_type)
```

check if a folio can be split to a given order

**Parameters**

- `struct folio *folio`: folio to be split
- `unsigned int new_order`: the smallest order of the after split folios (since buddy
  allocator like split generates folios with orders from **folio**'s
  order - 1 to new_order).
- `enum split_type split_type`: uniform or non-uniform split

**Description**

[`folio_check_splittable()`](#c-folio_check_splittable) checks if **folio** can be split to **new_order** using
**split_type** method. The truncated folio check must come first.

**Context**

folio must be locked.

**Return**

0 - **folio** can be split to **new_order**, otherwise an error number is
returned.

#### <a id="c-__folio_split"></a>`__folio_split()`

```c
int __folio_split(struct folio *folio, unsigned int new_order, struct page *split_at, struct page *lock_at, struct list_head *list, enum split_type split_type)
```

split a folio at **split_at** to a **new_order** folio

**Parameters**

- `struct folio *folio`: folio to split
- `unsigned int new_order`: the order of the new folio
- `struct page *split_at`: a page within the new folio
- `struct page *lock_at`: a page within **folio** to be left locked to caller
- `struct list_head *list`: after-split folios will be put on it if non NULL
- `enum split_type split_type`: perform uniform split or not (non-uniform split)

**Description**

It calls [`__split_unmapped_folio()`](#c-__split_unmapped_folio) to perform uniform and non-uniform split.
It is in charge of checking whether the split is supported or not and
preparing **folio** for [`__split_unmapped_folio()`](#c-__split_unmapped_folio).

After splitting, the after-split folio containing **lock_at** remains locked
and others are unlocked:
1. for uniform split, **lock_at** points to one of **folio**'s subpages;
2. for buddy allocator like (non-uniform) split, **lock_at** points to **folio**.

**Return**

0 - successful, \<0 - failed (if -ENOMEM is returned, **folio** might be
split but not to **new_order**, the caller needs to check)

#### <a id="c-folio_split_unmapped"></a>`folio_split_unmapped()`

```c
int folio_split_unmapped(struct folio *folio, unsigned int new_order)
```

split a large anon folio that is already unmapped

**Parameters**

- `struct folio *folio`: folio to split
- `unsigned int new_order`: the order of folios after split

**Description**

This function is a helper for splitting folios that have already been
unmapped. The use case is that the device or the CPU can refuse to migrate
THP pages in the middle of migration, due to allocation issues on either
side.

anon_vma_lock is not required to be held, `mmap_read_lock()` or
`mmap_write_lock()` should be held. **folio** is expected to be locked by the
caller. device-private and non device-private folios are supported along
with folios that are in the swapcache. **folio** should also be unmapped and
isolated from LRU (if applicable)

Upon return, the folio is not remapped, split folios are not added to LRU,
`free_folio_and_swap_cache()` is not called, and new folios remain locked.

**Return**

0 on success, -EAGAIN if the folio cannot be split (e.g., due to
insufficient reference count or extra pins).

#### <a id="c-folio_split"></a>`folio_split()`

```c
int folio_split(struct folio *folio, unsigned int new_order, struct page *split_at, struct list_head *list)
```

split a folio at **split_at** to a **new_order** folio

**Parameters**

- `struct folio *folio`: folio to split
- `unsigned int new_order`: the order of the new folio
- `struct page *split_at`: a page within the new folio
- `struct list_head *list`: after-split folios are added to **list** if not null, otherwise to LRU
  list

**Description**

It has the same prerequisites and returns as
`split_huge_page_to_list_to_order()`.

Split a folio at **split_at** to a new_order folio, leave the
remaining subpages of the original folio as large as possible. For example,
in the case of splitting an order-9 folio at its third order-3 subpages to
an order-3 folio, there are 2^(9-3)=64 order-3 subpages in the order-9 folio.
After the split, there will be a group of folios with different orders and
the new folio containing **split_at** is marked in bracket:
\[order-4, {order-3}, order-3, order-5, order-6, order-7, order-8\].

After split, folio is left locked for caller.

**Return**

0 - successful, \<0 - failed (if -ENOMEM is returned, **folio** might be
split but not to **new_order**, the caller needs to check)

#### <a id="c-min_order_for_split"></a>`min_order_for_split()`

```c
unsigned int min_order_for_split(struct folio *folio)
```

get the minimum order **folio** can be split to

**Parameters**

- `struct folio *folio`: folio to split

**Description**

[`min_order_for_split()`](#c-min_order_for_split) tells the minimum order **folio** can be split to.
If a file-backed folio is truncated, 0 will be returned. Any subsequent
split attempt should get -EBUSY from split checking code.

**Return**

**folio**'s minimum order for split

---

# Netlink notes for kernel developers

_Peios Kernel / Internals / Core APIs_

> Older families often define "null" attributes and commands with value of 0 and named unspec. This is supported (type: unused) but should be avoided in new families. The unspec enum values are not used in practice, so just set the value of…

<a id="rst-netlink-notes-for-kernel-developers"></a>
<a id="rst-kernel-netlink"></a>

<!-- SPDX-License-Identifier: BSD-3-Clause -->

<a id="rst-general-guidance"></a>

## General guidance

<a id="rst-attribute-enums"></a>

### Attribute enums

Older families often define "null" attributes and commands with value of `0` and named `unspec`. This is supported (`type: unused`) but should be avoided in new families. The `unspec` enum values are not used in practice, so just set the value of the first attribute to `1`.

<a id="rst-message-enums"></a>

### Message enums

Use the same command IDs for requests and replies. This makes it easier to match them up, and we have plenty of ID space.

Use separate command IDs for notifications. This makes it easier to sort the notifications from replies (and present them to the user application via a different API than replies).

<a id="rst-answer-requests"></a>

### Answer requests

Older families do not reply to all of the commands, especially NEW / ADD commands. User only gets information whether the operation succeeded or not via the ACK. Try to find useful data to return. Once the command is added whether it replies with a full message or only an ACK is uAPI and cannot be changed. It's better to err on the side of replying.

Specifically NEW and ADD commands should reply with information identifying the created object such as the allocated object's ID (without having to resort to using `NLM_F_ECHO`).

<a id="rst-nlm-f-echo"></a>

### NLM_F_ECHO

Make sure to pass the request info to genl_notify() to allow `NLM_F_ECHO` to take effect.  This is useful for programs that need precise feedback from the kernel (for example for logging purposes).

<a id="rst-support-dump-consistency"></a>

### Support dump consistency

If iterating over objects during dump may skip over objects or repeat them - make sure to report dump inconsistency with `NLM_F_DUMP_INTR`. This is usually implemented by maintaining a generation id for the structure and recording it in the `seq` member of struct netlink_callback.

<a id="rst-netlink-specification"></a>

## Netlink specification

Documentation of the Netlink specification parts which are only relevant to the kernel space.

<a id="rst-globals"></a>

### Globals

<a id="rst-kernel-policy"></a>

#### kernel-policy

Defines whether the kernel validation policy is `global` i.e. the same for all operations of the family, defined for each operation individually - `per-op`, or separately for each operation and operation type (do vs dump) - `split`. New families should use `per-op` (default) to be able to narrow down the attributes accepted by a specific command.

<a id="rst-checks"></a>

### checks

Documentation for the `checks` sub-sections of attribute specs.

<a id="rst-unterminated-ok"></a>

#### unterminated-ok

Accept strings without the null-termination (for legacy families only). Switches from the `NLA_NUL_STRING` to `NLA_STRING` policy type.

<a id="rst-max-len"></a>

#### max-len

Defines max length for a binary or string attribute (corresponding to the `len` member of struct nla_policy). For string attributes terminating null character is not counted towards `max-len`.

The field may either be a literal integer value or a name of a defined constant. String types may reduce the constant by one (i.e. specify `max-len: CONST - 1`) to reserve space for the terminating character so implementations should recognize such pattern.

<a id="rst-min-len"></a>

#### min-len

Similar to `max-len` but defines minimum length.

---

# Generic bitfield packing and unpacking functions

_Peios Kernel / Internals / Core APIs_

> When working with hardware, one has to choose between several approaches of interfacing with it. One can memory-map a pointer to a carefully crafted struct over the hardware device's memory region, and access its fields as struct members…

<a id="rst-generic-bitfield-packing-and-unpacking-functions"></a>

<a id="rst-problem-statement"></a>

## Problem statement

When working with hardware, one has to choose between several approaches of interfacing with it. One can memory-map a pointer to a carefully crafted struct over the hardware device's memory region, and access its fields as struct members (potentially declared as bitfields). But writing code this way would make it less portable, due to potential endianness mismatches between the CPU and the hardware device. Additionally, one has to pay close attention when translating register definitions from the hardware documentation into bit field indices for the structs. Also, some hardware (typically networking equipment) tends to group its register fields in ways that violate any reasonable word boundaries (sometimes even 64 bit ones). This creates the inconvenience of having to define "high" and "low" portions of register fields within the struct. A more robust alternative to struct field definitions would be to extract the required fields by shifting the appropriate number of bits. But this would still not protect from endianness mismatches, except if all memory accesses were performed byte-by-byte. Also the code can easily get cluttered, and the high-level idea might get lost among the many bit shifts required. Many drivers take the bit-shifting approach and then attempt to reduce the clutter with tailored macros, but more often than not these macros take shortcuts that still prevent the code from being truly portable.

<a id="rst-the-solution"></a>

## The solution

This API deals with 2 basic operations:

> - Packing a CPU-usable number into a memory buffer (with hardware constraints/quirks)
>
> - Unpacking a memory buffer (which has hardware constraints/quirks) into a CPU-usable number.

The API offers an abstraction over said hardware constraints and quirks, over CPU endianness and therefore between possible mismatches between the two.

The basic unit of these API functions is the u64. From the CPU's perspective, bit 63 always means bit offset 7 of byte 7, albeit only logically. The question is: where do we lay this bit out in memory?

The following examples cover the memory layout of a packed u64 field. The byte offsets in the packed buffer are always implicitly 0, 1, ... 7. What the examples show is where the logical bytes and bits sit.

1. Normally (no quirks), we would do it like this:



```text
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32
7                       6                       5                        4
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
3                       2                       1                        0
```

That is, the MSByte (7) of the CPU-usable u64 sits at memory offset 0, and the LSByte (0) of the u64 sits at memory offset 7. This corresponds to what most folks would regard to as "big endian", where bit i corresponds to the number 2^i. This is also referred to in the code comments as "logical" notation.

2. If QUIRK_MSB_ON_THE_RIGHT is set, we do it like this:



```text
56 57 58 59 60 61 62 63 48 49 50 51 52 53 54 55 40 41 42 43 44 45 46 47 32 33 34 35 36 37 38 39
7                       6                        5                       4
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23  8  9 10 11 12 13 14 15  0  1  2  3  4  5  6  7
3                       2                        1                       0
```

That is, QUIRK_MSB_ON_THE_RIGHT does not affect byte positioning, but inverts bit offsets inside a byte.

3. If QUIRK_LITTLE_ENDIAN is set, we do it like this:



```text
39 38 37 36 35 34 33 32 47 46 45 44 43 42 41 40 55 54 53 52 51 50 49 48 63 62 61 60 59 58 57 56
4                       5                       6                       7
7  6  5  4  3  2  1  0  15 14 13 12 11 10  9  8 23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24
0                       1                       2                       3
```

Therefore, QUIRK_LITTLE_ENDIAN means that inside the memory region, every byte from each 4-byte word is placed at its mirrored position compared to the boundary of that word.

4. If QUIRK_MSB_ON_THE_RIGHT and QUIRK_LITTLE_ENDIAN are both set, we do it like this:



```text
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
4                       5                       6                       7
0  1  2  3  4  5  6  7  8   9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0                       1                       2                       3
```

5. If just QUIRK_LSW32_IS_FIRST is set, we do it like this:



```text
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
3                       2                       1                        0
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32
7                       6                       5                        4
```

In this case the 8 byte memory region is interpreted as follows: first 4 bytes correspond to the least significant 4-byte word, next 4 bytes to the more significant 4-byte word.

6. If QUIRK_LSW32_IS_FIRST and QUIRK_MSB_ON_THE_RIGHT are set, we do it like this:



```text
24 25 26 27 28 29 30 31 16 17 18 19 20 21 22 23  8  9 10 11 12 13 14 15  0  1  2  3  4  5  6  7
3                       2                        1                       0
56 57 58 59 60 61 62 63 48 49 50 51 52 53 54 55 40 41 42 43 44 45 46 47 32 33 34 35 36 37 38 39
7                       6                        5                       4
```

7. If QUIRK_LSW32_IS_FIRST and QUIRK_LITTLE_ENDIAN are set, it looks like this:



```text
7  6  5  4  3  2  1  0  15 14 13 12 11 10  9  8 23 22 21 20 19 18 17 16 31 30 29 28 27 26 25 24
0                       1                       2                       3
39 38 37 36 35 34 33 32 47 46 45 44 43 42 41 40 55 54 53 52 51 50 49 48 63 62 61 60 59 58 57 56
4                       5                       6                       7
```

8. If QUIRK_LSW32_IS_FIRST, QUIRK_LITTLE_ENDIAN and QUIRK_MSB_ON_THE_RIGHT are set, it looks like this:



```text
0  1  2  3  4  5  6  7  8   9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0                       1                       2                       3
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
4                       5                       6                       7
```

We always think of our offsets as if there were no quirk, and we translate them afterwards, before accessing the memory region.

<a id="rst-note-on-buffer-lengths-not-multiple-of-4"></a>

## Note on buffer lengths not multiple of 4

To deal with memory layout quirks where groups of 4 bytes are laid out "little endian" relative to each other, but "big endian" within the group itself, the concept of groups of 4 bytes is intrinsic to the packing API (not to be confused with the memory access, which is performed byte by byte, though).

With buffer lengths not multiple of 4, this means one group will be incomplete. Depending on the quirks, this may lead to discontinuities in the bit fields accessible through the buffer. The packing API assumes discontinuities were not the intention of the memory layout, so it avoids them by effectively logically shortening the most significant group of 4 octets to the number of octets actually available.

Example with a 31 byte sized buffer given below. Physical buffer offsets are implicit, and increase from left to right within a group, and from top to bottom within a column.

No quirks:



```text
           31         29         28        |   Group 7 (most significant)
27         26         25         24        |   Group 6
23         22         21         20        |   Group 5
19         18         17         16        |   Group 4
15         14         13         12        |   Group 3
11         10          9          8        |   Group 2
 7          6          5          4        |   Group 1
 3          2          1          0        |   Group 0 (least significant)
```

QUIRK_LSW32_IS_FIRST:



```text
 3          2          1          0        |   Group 0 (least significant)
 7          6          5          4        |   Group 1
11         10          9          8        |   Group 2
15         14         13         12        |   Group 3
19         18         17         16        |   Group 4
23         22         21         20        |   Group 5
27         26         25         24        |   Group 6
30         29         28                   |   Group 7 (most significant)
```

QUIRK_LITTLE_ENDIAN:



```text
           30         28         29        |   Group 7 (most significant)
24         25         26         27        |   Group 6
20         21         22         23        |   Group 5
16         17         18         19        |   Group 4
12         13         14         15        |   Group 3
 8          9         10         11        |   Group 2
 4          5          6          7        |   Group 1
 0          1          2          3        |   Group 0 (least significant)
```

QUIRK_LITTLE_ENDIAN \| QUIRK_LSW32_IS_FIRST:



```text
 0          1          2          3        |   Group 0 (least significant)
 4          5          6          7        |   Group 1
 8          9         10         11        |   Group 2
12         13         14         15        |   Group 3
16         17         18         19        |   Group 4
20         21         22         23        |   Group 5
24         25         26         27        |   Group 6
28         29         30                   |   Group 7 (most significant)
```

<a id="rst-intended-use"></a>

## Intended use

Drivers that opt to use this API first need to identify which of the above 3 quirk combinations (for a total of 8) match what the hardware documentation describes.

There are 3 supported usage patterns, detailed below.

<a id="rst-packing"></a>

### packing()

This API function is deprecated.

The packing() function returns an int-encoded error code, which protects the programmer against incorrect API use.  The errors are not expected to occur during runtime, therefore it is reasonable to wrap packing() into a custom function which returns void and swallows those errors. Optionally it can dump stack or print the error description.



```c
void my_packing(void *buf, u64 *val, int startbit, int endbit,
                size_t len, enum packing_op op)
{
        int err;

        /* Adjust quirks accordingly */
        err = packing(buf, val, startbit, endbit, len, op, QUIRK_LSW32_IS_FIRST);
        if (likely(!err))
                return;

        if (err == -EINVAL) {
                pr_err("Start bit (%d) expected to be larger than end (%d)\n",
                       startbit, endbit);
        } else if (err == -ERANGE) {
                if ((startbit - endbit + 1) > 64)
                        pr_err("Field %d-%d too large for 64 bits!\n",
                               startbit, endbit);
                else
                        pr_err("Cannot store %llx inside bits %d-%d (would truncate)\n",
                               *val, startbit, endbit);
        }
        dump_stack();
}
```

<a id="rst-pack-and-unpack"></a>

### pack() and unpack()

These are const-correct variants of packing(), and eliminate the last "enum packing_op op" argument.

Calling pack(...) is equivalent, and preferred, to calling packing(..., PACK).

Calling unpack(...) is equivalent, and preferred, to calling packing(..., UNPACK).

<a id="rst-pack-fields-and-unpack-fields"></a>

### pack_fields() and unpack_fields()

The library exposes optimized functions for the scenario where there are many fields represented in a buffer, and it encourages consumer drivers to avoid repetitive calls to pack() and unpack() for each field, but instead use pack_fields() and unpack_fields(), which reduces the code footprint.

These APIs use field definitions in arrays of `struct packed_field_u8` or `struct packed_field_u16`, allowing consumer drivers to minimize the size of these arrays according to their custom requirements.

The pack_fields() and unpack_fields() API functions are actually macros which automatically select the appropriate function at compile time, based on the type of the fields array passed in.

An additional benefit over pack() and unpack() is that sanity checks on the field definitions are handled at compile time with `BUILD_BUG_ON` rather than only when the offending code is executed. These functions return void and wrapping them to handle unexpected errors is not necessary.

It is recommended, but not required, that you wrap your packed buffer into a structured type with a fixed size. This generally makes it easier for the compiler to enforce that the correct size buffer is used.

Here is an example of how to use the fields APIs:



```c
/* Ordering inside the unpacked structure is flexible and can be different
 * from the packed buffer. Here, it is optimized to reduce padding.
 */
struct data {
     u64 field3;
     u32 field4;
     u16 field1;
     u8 field2;
};

#define SIZE 13

typedef struct __packed { u8 buf[SIZE]; } packed_buf_t;

static const struct packed_field_u8 fields[] = {
        PACKED_FIELD(100, 90, struct data, field1),
        PACKED_FIELD(90, 87, struct data, field2),
        PACKED_FIELD(86, 30, struct data, field3),
        PACKED_FIELD(29, 0, struct data, field4),
};

void unpack_your_data(const packed_buf_t *buf, struct data *unpacked)
{
        BUILD_BUG_ON(sizeof(*buf) != SIZE;

        unpack_fields(buf, sizeof(*buf), unpacked, fields,
                      QUIRK_LITTLE_ENDIAN);
}

void pack_your_data(const struct data *unpacked, packed_buf_t *buf)
{
        BUILD_BUG_ON(sizeof(*buf) != SIZE;

        pack_fields(buf, sizeof(*buf), unpacked, fields,
                    QUIRK_LITTLE_ENDIAN);
}
```

---

# The padata parallel execution mechanism

_Peios Kernel / Internals / Core APIs_

> Padata is a mechanism by which the kernel can farm jobs out to be done in parallel on multiple CPUs while optionally retaining their ordering.

<a id="rst-the-padata-parallel-execution-mechanism"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Date:** May 2020

Padata is a mechanism by which the kernel can farm jobs out to be done in parallel on multiple CPUs while optionally retaining their ordering.

It was originally developed for IPsec, which needs to perform encryption and decryption on large numbers of packets without reordering those packets.  This is currently the sole consumer of padata's serialized job support.

Padata also supports multithreaded jobs, splitting up the job evenly while load balancing and coordinating between threads.

<a id="rst-running-serialized-jobs"></a>

## Running Serialized Jobs

<a id="rst-initializing"></a>

### Initializing

The first step in using padata to run serialized jobs is to set up a padata_instance structure for overall control of how jobs are to be run:



```text
#include <linux/padata.h>

struct padata_instance *padata_alloc(const char *name);
```

'name' simply identifies the instance.

Then, complete padata initialization by allocating a padata_shell:



```text
struct padata_shell *padata_alloc_shell(struct padata_instance *pinst);
```

A padata_shell is used to submit a job to padata and allows a series of such jobs to be serialized independently.  A padata_instance may have one or more padata_shells associated with it, each allowing a separate series of jobs.

<a id="rst-modifying-cpumasks"></a>

### Modifying cpumasks

The CPUs used to run jobs can be changed in two ways, programmatically with padata_set_cpumask() or via sysfs.  The former is defined:



```text
int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type,
                       cpumask_var_t cpumask);
```

Here cpumask_type is one of PADATA_CPU_PARALLEL or PADATA_CPU_SERIAL, where a parallel cpumask describes which processors will be used to execute jobs submitted to this instance in parallel and a serial cpumask defines which processors are allowed to be used as the serialization callback processor. cpumask specifies the new cpumask to use.

There may be sysfs files for an instance's cpumasks.  For example, pcrypt's live in /sys/kernel/pcrypt/&lt;instance-name&gt;.  Within an instance's directory there are two files, parallel_cpumask and serial_cpumask, and either cpumask may be changed by echoing a bitmask into the file, for example:



```text
echo f > /sys/kernel/pcrypt/pencrypt/parallel_cpumask
```

Reading one of these files shows the user-supplied cpumask, which may be different from the 'usable' cpumask.

Padata maintains two pairs of cpumasks internally, the user-supplied cpumasks and the 'usable' cpumasks.  (Each pair consists of a parallel and a serial cpumask.)  The user-supplied cpumasks default to all possible CPUs on instance allocation and may be changed as above.  The usable cpumasks are always a subset of the user-supplied cpumasks and contain only the online CPUs in the user-supplied masks; these are the cpumasks padata actually uses.  So it is legal to supply a cpumask to padata that contains offline CPUs.  Once an offline CPU in the user-supplied cpumask comes online, padata is going to use it.

Changing the CPU masks are expensive operations, so it should not be done with great frequency.

<a id="rst-running-a-job"></a>

### Running A Job

Actually submitting work to the padata instance requires the creation of a padata_priv structure, which represents one job:



```text
struct padata_priv {
    /* Other stuff here... */
    void                    (*parallel)(struct padata_priv *padata);
    void                    (*serial)(struct padata_priv *padata);
};
```

This structure will almost certainly be embedded within some larger structure specific to the work to be done.  Most of its fields are private to padata, but the structure should be zeroed at initialisation time, and the parallel() and serial() functions should be provided.  Those functions will be called in the process of getting the work done as we will see momentarily.

The submission of the job is done with:



```text
int padata_do_parallel(struct padata_shell *ps,
                       struct padata_priv *padata, int *cb_cpu);
```

The ps and padata structures must be set up as described above; cb_cpu points to the preferred CPU to be used for the final callback when the job is done; it must be in the current instance's CPU mask (if not the cb_cpu pointer is updated to point to the CPU actually chosen).  The return value from padata_do_parallel() is zero on success, indicating that the job is in progress. -EBUSY means that somebody, somewhere else is messing with the instance's CPU mask, while -EINVAL is a complaint about cb_cpu not being in the serial cpumask, no online CPUs in the parallel or serial cpumasks, or a stopped instance.

Each job submitted to padata_do_parallel() will, in turn, be passed to exactly one call to the above-mentioned parallel() function, on one CPU, so true parallelism is achieved by submitting multiple jobs.  parallel() runs with software interrupts disabled and thus cannot sleep.  The parallel() function gets the padata_priv structure pointer as its lone parameter; information about the actual work to be done is probably obtained by using container_of() to find the enclosing structure.

Note that parallel() has no return value; the padata subsystem assumes that parallel() will take responsibility for the job from this point.  The job need not be completed during this call, but, if parallel() leaves work outstanding, it should be prepared to be called again with a new job before the previous one completes.

<a id="rst-serializing-jobs"></a>

### Serializing Jobs

When a job does complete, parallel() (or whatever function actually finishes the work) should inform padata of the fact with a call to:



```text
void padata_do_serial(struct padata_priv *padata);
```

At some point in the future, padata_do_serial() will trigger a call to the serial() function in the padata_priv structure.  That call will happen on the CPU requested in the initial call to padata_do_parallel(); it, too, is run with local software interrupts disabled. Note that this call may be deferred for a while since the padata code takes pains to ensure that jobs are completed in the order in which they were submitted.

<a id="rst-destroying"></a>

### Destroying

Cleaning up a padata instance predictably involves calling the two free functions that correspond to the allocation in reverse:



```text
void padata_free_shell(struct padata_shell *ps);
void padata_free(struct padata_instance *pinst);
```

It is the user's responsibility to ensure all outstanding jobs are complete before any of the above are called.

<a id="rst-running-multithreaded-jobs"></a>

## Running Multithreaded Jobs

A multithreaded job has a main thread and zero or more helper threads, with the main thread participating in the job and then waiting until all helpers have finished.  padata splits the job into units called chunks, where a chunk is a piece of the job that one thread completes in one call to the thread function.

A user has to do three things to run a multithreaded job.  First, describe the job by defining a padata_mt_job structure, which is explained in the Interface section.  This includes a pointer to the thread function, which padata will call each time it assigns a job chunk to a thread.  Then, define the thread function, which accepts three arguments, `start`, `end`, and `arg`, where the first two delimit the range that the thread operates on and the last is a pointer to the job's shared state, if any.  Prepare the shared state, which is typically allocated on the main thread's stack.  Last, call padata_do_multithreaded(), which will return once the job is finished.

<a id="rst-interface"></a>

## Interface


#### <a id="c-struct-padata_priv"></a>`struct padata_priv`

Represents one job

**Definition**

```c
struct padata_priv {
    struct list_head        list;
    struct parallel_data    *pd;
    int cb_cpu;
    unsigned int            seq_nr;
    int info;
    void (*parallel)(struct padata_priv *padata);
    void (*serial)(struct padata_priv *padata);
};
```

**Members**

- `list`: List entry, to attach to the padata lists.
- `pd`: Pointer to the internal control structure.
- `cb_cpu`: Callback cpu for serializatioon.
- `seq_nr`: Sequence number of the parallelized data object.
- `info`: Used to pass information from the parallel to the serial function.
- `parallel`: Parallel execution function.
- `serial`: Serial complete function.

#### <a id="c-struct-padata_list"></a>`struct padata_list`

one per work type per CPU

**Definition**

```c
struct padata_list {
    struct list_head        list;
    spinlock_t lock;
};
```

**Members**

- `list`: List head.
- `lock`: List lock.

#### <a id="c-struct-padata_serial_queue"></a>`struct padata_serial_queue`

The percpu padata serial queue

**Definition**

```c
struct padata_serial_queue {
    struct padata_list    serial;
    struct work_struct    work;
    struct parallel_data *pd;
};
```

**Members**

- `serial`: List to wait for serialization after reordering.
- `work`: work struct for serialization.
- `pd`: Backpointer to the internal control structure.

#### <a id="c-struct-padata_cpumask"></a>`struct padata_cpumask`

The cpumasks for the parallel/serial workers

**Definition**

```c
struct padata_cpumask {
    cpumask_var_t pcpu;
    cpumask_var_t cbcpu;
};
```

**Members**

- `pcpu`: cpumask for the parallel workers.
- `cbcpu`: cpumask for the serial (callback) workers.

#### <a id="c-struct-parallel_data"></a>`struct parallel_data`

Internal control structure, covers everything that depends on the cpumask in use.

**Definition**

```c
struct parallel_data {
    struct padata_shell             *ps;
    struct padata_list              __percpu *reorder_list;
    struct padata_serial_queue      __percpu *squeue;
    refcount_t refcnt;
    unsigned int                    seq_nr;
    unsigned int                    processed;
    int cpu;
    struct padata_cpumask           cpumask;
};
```

**Members**

- `ps`: padata_shell object.
- `reorder_list`: percpu reorder lists
- `squeue`: percpu padata queues used for serialuzation.
- `refcnt`: Number of objects holding a reference on this parallel_data.
- `seq_nr`: Sequence number of the parallelized data object.
- `processed`: Number of already processed objects.
- `cpu`: Next CPU to be processed.
- `cpumask`: The cpumasks in use for parallel and serial workers.

#### <a id="c-struct-padata_shell"></a>`struct padata_shell`

Wrapper around struct parallel_data, its purpose is to allow the underlying control structure to be replaced on the fly using RCU.

**Definition**

```c
struct padata_shell {
    struct padata_instance          *pinst;
    struct parallel_data       *pd;
    struct parallel_data            *opd;
    struct list_head                list;
};
```

**Members**

- `pinst`: padat instance.
- `pd`: Actual parallel_data structure which may be substituted on the fly.
- `opd`: Pointer to old pd to be freed by padata_replace.
- `list`: List entry in padata_instance list.

#### <a id="c-struct-padata_mt_job"></a>`struct padata_mt_job`

represents one multithreaded job

**Definition**

```c
struct padata_mt_job {
    void (*thread_fn)(unsigned long start, unsigned long end, void *arg);
    void *fn_arg;
    unsigned long           start;
    unsigned long           size;
    unsigned long           align;
    unsigned long           min_chunk;
    int max_threads;
    bool numa_aware;
};
```

**Members**

- `thread_fn`: Called for each chunk of work that a padata thread does.
- `fn_arg`: The thread function argument.
- `start`: The start of the job (units are job-specific).
- `size`: size of this node's work (units are job-specific).
- `align`: Ranges passed to the thread function fall on this boundary, with the
  possible exceptions of the beginning and end of the job.
- `min_chunk`: The minimum chunk size in job-specific units.  This allows
  the client to communicate the minimum amount of work that's
  appropriate for one worker thread to do at once.
- `max_threads`: Max threads to use for the job, actual number may be less
  depending on task size and minimum chunk size.
- `numa_aware`: Distribute jobs to different nodes with CPU in a round robin fashion.

#### <a id="c-struct-padata_instance"></a>`struct padata_instance`

The overall control structure.

**Definition**

```c
struct padata_instance {
        struct hlist_node               cpu_online_node;
        struct hlist_node               cpu_dead_node;
        struct workqueue_struct         *parallel_wq;
        struct workqueue_struct         *serial_wq;
        struct list_head                pslist;
        struct padata_cpumask           cpumask;
        struct kobject                   kobj;
        struct mutex                     lock;
        u8 flags;
    #define PADATA_INIT     1;
    #define PADATA_RESET    2;
    #define PADATA_INVALID  4;
};
```

**Members**

- `cpu_online_node`: Linkage for CPU online callback.
- `cpu_dead_node`: Linkage for CPU offline callback.
- `parallel_wq`: The workqueue used for parallel work.
- `serial_wq`: The workqueue used for serial work.
- `pslist`: List of padata_shell objects attached to this instance.
- `cpumask`: User supplied cpumasks for parallel and serial works.
- `kobj`: padata instance kernel object.
- `lock`: padata instance lock.
- `flags`: padata flags.



#### <a id="c-padata_do_parallel"></a>`padata_do_parallel()`

```c
int padata_do_parallel(struct padata_shell *ps, struct padata_priv *padata, int *cb_cpu)
```

padata parallelization function

**Parameters**

- `struct padata_shell *ps`: padatashell
- `struct padata_priv *padata`: object to be parallelized
- `int *cb_cpu`: pointer to the CPU that the serialization callback function should
  run on.  If it's not in the serial cpumask of **pinst**
  (i.e. cpumask.cbcpu), this function selects a fallback CPU and if
  none found, returns -EINVAL.

**Description**

The parallelization callback function will run with BHs off.

**Note**

Every object which is parallelized by padata_do_parallel
must be seen by padata_do_serial.

**Return**

0 on success or else negative error code.

#### <a id="c-padata_do_serial"></a>`padata_do_serial()`

```c
void padata_do_serial(struct padata_priv *padata)
```

padata serialization function

**Parameters**

- `struct padata_priv *padata`: object to be serialized.

**Description**

padata_do_serial must be called for every parallelized object.
The serialization callback function will run with BHs off.

#### <a id="c-padata_do_multithreaded"></a>`padata_do_multithreaded()`

```c
void padata_do_multithreaded(struct padata_mt_job *job)
```

run a multithreaded job

**Parameters**

- `struct padata_mt_job *job`: Description of the job.

**Description**

See the definition of struct padata_mt_job for more details.

#### <a id="c-padata_set_cpumask"></a>`padata_set_cpumask()`

```c
int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type, cpumask_var_t cpumask)
```

Sets specified by **cpumask_type** cpumask to the value equivalent to **cpumask**.

**Parameters**

- `struct padata_instance *pinst`: padata instance
- `int cpumask_type`: PADATA_CPU_SERIAL or PADATA_CPU_PARALLEL corresponding
  to parallel and serial cpumasks respectively.
- `cpumask_var_t cpumask`: the cpumask to use

**Return**

0 on success or negative error code

#### <a id="c-padata_alloc"></a>`padata_alloc()`

```c
struct padata_instance * padata_alloc(const char *name)
```

allocate and initialize a padata instance

**Parameters**

- `const char *name`: used to identify the instance

**Return**

new instance on success, NULL on error

#### <a id="c-padata_free"></a>`padata_free()`

```c
void padata_free(struct padata_instance *pinst)
```

free a padata instance

**Parameters**

- `struct padata_instance *pinst`: padata instance to free

#### <a id="c-padata_alloc_shell"></a>`padata_alloc_shell()`

```c
struct padata_shell * padata_alloc_shell(struct padata_instance *pinst)
```

Allocate and initialize padata shell.

**Parameters**

- `struct padata_instance *pinst`: Parent padata_instance object.

**Return**

new shell on success, NULL on error

#### <a id="c-padata_free_shell"></a>`padata_free_shell()`

```c
void padata_free_shell(struct padata_shell *ps)
```

free a padata shell

**Parameters**

- `struct padata_shell *ps`: padata shell to free

---

# Generic parser

_Peios Kernel / Internals / Core APIs_

> The generic parser is a simple parser for parsing mount options, filesystem options, driver options, subsystem options, etc.

<a id="rst-generic-parser"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-overview"></a>

## Overview

The generic parser is a simple parser for parsing mount options, filesystem options, driver options, subsystem options, etc.

<a id="rst-parser-api"></a>

## Parser API


#### <a id="c-match_token"></a>`match_token()`

```c
int match_token(char *s, const match_table_t table, substring_t args[])
```

Find a token (and optional args) in a string

**Parameters**

- `char *s`: the string to examine for token/argument pairs
- `const match_table_t table`: match_table_t describing the set of allowed option tokens and the
  arguments that may be associated with them. Must be terminated with a
  `struct match_token` whose pattern is set to the NULL pointer.
- `substring_t args[]`: array of `MAX_OPT_ARGS` `substring_t` elements. Used to return match
  locations.

**Description**

Detects which if any of a set of token strings has been passed
to it. Tokens can include up to `MAX_OPT_ARGS` instances of basic c-style
format identifiers which will be taken into account when matching the
tokens, and whose locations will be returned in the **args** array.

#### <a id="c-match_int"></a>`match_int()`

```c
int match_int(substring_t *s, int *result)
```

scan a decimal representation of an integer from a substring_t

**Parameters**

- `substring_t *s`: substring_t to be scanned
- `int *result`: resulting integer on success

**Description**

Attempts to parse the `substring_t` **s** as a decimal integer.

**Return**

On success, sets **result** to the integer represented by the string
and returns 0. Returns -EINVAL or -ERANGE on failure.

#### <a id="c-match_uint"></a>`match_uint()`

```c
int match_uint(substring_t *s, unsigned int *result)
```

scan a decimal representation of an integer from a substring_t

**Parameters**

- `substring_t *s`: substring_t to be scanned
- `unsigned int *result`: resulting integer on success

**Description**

Attempts to parse the `substring_t` **s** as a decimal integer.

**Return**

On success, sets **result** to the integer represented by the string
and returns 0. Returns -EINVAL or -ERANGE on failure.

#### <a id="c-match_u64"></a>`match_u64()`

```c
int match_u64(substring_t *s, u64 *result)
```

scan a decimal representation of a u64 from a substring_t

**Parameters**

- `substring_t *s`: substring_t to be scanned
- `u64 *result`: resulting unsigned long long on success

**Description**

Attempts to parse the `substring_t` **s** as a long decimal
integer.

**Return**

On success, sets **result** to the integer represented by the string
and returns 0. Returns -EINVAL or -ERANGE on failure.

#### <a id="c-match_octal"></a>`match_octal()`

```c
int match_octal(substring_t *s, int *result)
```

scan an octal representation of an integer from a substring_t

**Parameters**

- `substring_t *s`: substring_t to be scanned
- `int *result`: resulting integer on success

**Description**

Attempts to parse the `substring_t` **s** as an octal integer.

**Return**

On success, sets **result** to the integer represented by the string
and returns 0. Returns -EINVAL or -ERANGE on failure.

#### <a id="c-match_hex"></a>`match_hex()`

```c
int match_hex(substring_t *s, int *result)
```

scan a hex representation of an integer from a substring_t

**Parameters**

- `substring_t *s`: substring_t to be scanned
- `int *result`: resulting integer on success

**Description**

Attempts to parse the `substring_t` **s** as a hexadecimal integer.

**Return**

On success, sets **result** to the integer represented by the string
and returns 0. Returns -EINVAL or -ERANGE on failure.

#### <a id="c-match_wildcard"></a>`match_wildcard()`

```c
bool match_wildcard(const char *pattern, const char *str)
```

parse if a string matches given wildcard pattern

**Parameters**

- `const char *pattern`: wildcard pattern
- `const char *str`: the string to be parsed

**Description**

Parse the string **str** to check if matches wildcard
pattern **pattern**. The pattern may contain two types of wildcards:

* '*' - matches zero or more characters
* '?' - matches one character

**Return**

If the **str** matches the **pattern**, return true, else return false.

#### <a id="c-match_strlcpy"></a>`match_strlcpy()`

```c
size_t match_strlcpy(char *dest, const substring_t *src, size_t size)
```

Copy the characters from a substring_t to a sized buffer

**Parameters**

- `char *dest`: where to copy to
- `const substring_t *src`: `substring_t` to copy
- `size_t size`: size of destination buffer

**Description**

Copy the characters in `substring_t` **src** to the
c-style string **dest**.  Copy no more than **size** - 1 characters, plus
the terminating NUL.

**Return**

length of **src**.

#### <a id="c-match_strdup"></a>`match_strdup()`

```c
char * match_strdup(const substring_t *s)
```

allocate a new string with the contents of a substring_t

**Parameters**

- `const substring_t *s`: `substring_t` to copy

**Description**

Allocates and returns a string filled with the contents of
the `substring_t` **s**. The caller is responsible for freeing the returned
string with [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

**Return**

the address of the newly allocated NUL-terminated string or
`NULL` on error.

---

# pin_user_pages() and related calls

_Peios Kernel / Internals / Core APIs_

> Overview

<a id="rst-pin-user-pages-and-related-calls"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-overview"></a>

## Overview

This document describes the following functions:



```text
pin_user_pages()
pin_user_pages_fast()
pin_user_pages_remote()
```

<a id="rst-basic-description-of-foll-pin"></a>

## Basic description of FOLL_PIN

FOLL_PIN and FOLL_LONGTERM are flags that can be passed to the get_user_pages\*() ("gup") family of functions. FOLL_PIN has significant interactions and interdependencies with FOLL_LONGTERM, so both are covered here.

FOLL_PIN is internal to gup, meaning that it should not appear at the gup call sites. This allows the associated wrapper functions  (pin_user_pages\*() and others) to set the correct combination of these flags, and to check for problems as well.

FOLL_LONGTERM, on the other hand, *is* allowed to be set at the gup call sites. This is in order to avoid creating a large number of wrapper functions to cover all combinations of get\*(), pin\*(), FOLL_LONGTERM, and more. Also, the pin_user_pages\*() APIs are clearly distinct from the get_user_pages\*() APIs, so that's a natural dividing line, and a good point to make separate wrapper calls. In other words, use pin_user_pages\*() for DMA-pinned pages, and get_user_pages\*() for other cases. There are five cases described later on in this document, to further clarify that concept.

FOLL_PIN and FOLL_GET are mutually exclusive for a given gup call. However, multiple threads and call sites are free to pin the same struct pages, via both FOLL_PIN and FOLL_GET. It's just the call site that needs to choose one or the other, not the struct page(s).

The FOLL_PIN implementation is nearly the same as FOLL_GET, except that FOLL_PIN uses a different reference counting technique.

FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying that is, FOLL_LONGTERM is a specific case, more restrictive case of FOLL_PIN.

<a id="rst-which-flags-are-set-by-each-wrapper"></a>

## Which flags are set by each wrapper

For these pin_user_pages\*() functions, FOLL_PIN is OR'd in with whatever gup flags the caller provides. The caller is required to pass in a non-null struct pages\* array, and the function then pins pages by incrementing each by a special value: GUP_PIN_COUNTING_BIAS.

For large folios, the GUP_PIN_COUNTING_BIAS scheme is not used. Instead, the extra space available in the struct folio is used to store the pincount directly.

This approach for large folios avoids the counting upper limit problems that are discussed below. Those limitations would have been aggravated severely by huge pages, because each tail page adds a refcount to the head page. And in fact, testing revealed that, without a separate pincount field, refcount overflows were seen in some huge page stress tests.

This also means that huge pages and large folios do not suffer from the false positives problem that is mentioned below.:



```text
Function
--------
pin_user_pages          FOLL_PIN is always set internally by this function.
pin_user_pages_fast     FOLL_PIN is always set internally by this function.
pin_user_pages_remote   FOLL_PIN is always set internally by this function.
```

For these get_user_pages\*() functions, FOLL_GET might not even be specified. Behavior is a little more complex than above. If FOLL_GET was *not* specified, but the caller passed in a non-null struct pages\* array, then the function sets FOLL_GET for you, and proceeds to pin pages by incrementing the refcount of each page by +1.:



```text
Function
--------
get_user_pages           FOLL_GET is sometimes set internally by this function.
get_user_pages_fast      FOLL_GET is sometimes set internally by this function.
get_user_pages_remote    FOLL_GET is sometimes set internally by this function.
```

<a id="rst-tracking-dma-pinned-pages"></a>

## Tracking dma-pinned pages

Some of the key design constraints, and solutions, for tracking dma-pinned pages:

- An actual reference count, per struct page, is required. This is because multiple processes may pin and unpin a page.

- False positives (reporting that a page is dma-pinned, when in fact it is not) are acceptable, but false negatives are not.

- struct page may not be increased in size for this, and all fields are already used.

- Given the above, we can overload the page-&gt;\_refcount field by using, sort of, the upper bits in that field for a dma-pinned count. "Sort of", means that, rather than dividing page-&gt;\_refcount into bit fields, we simple add a medium- large value (GUP_PIN_COUNTING_BIAS, initially chosen to be 1024: 10 bits) to page-&gt;\_refcount. This provides fuzzy behavior: if a page has get_page() called on it 1024 times, then it will appear to have a single dma-pinned count. And again, that's acceptable.

This also leads to limitations: there are only 31-10==21 bits available for a counter that increments 10 bits at a time.

- Because of that limitation, special handling is applied to the zero pages when using FOLL_PIN.  We only pretend to pin a zero page - we don't alter its refcount or pincount at all (it is permanent, so there's no need).  The unpinning functions also don't do anything to a zero page.  This is transparent to the caller.

- Callers must specifically request "dma-pinned tracking of pages". In other words, just calling get_user_pages() will not suffice; a new set of functions, pin_user_page() and related, must be used.

<a id="rst-foll-pin-foll-get-foll-longterm-when-to-use-which-flags"></a>

## FOLL_PIN, FOLL_GET, FOLL_LONGTERM: when to use which flags

Thanks to Jan Kara, Vlastimil Babka and several other -mm people, for describing these categories:

<a id="rst-case-1-direct-io-dio"></a>

### CASE 1: Direct IO (DIO)

There are GUP references to pages that are serving as DIO buffers. These buffers are needed for a relatively short time (so they are not "long term"). No special synchronization with folio_mkclean() or munmap() is provided. Therefore, flags to set at the call site are:



```text
FOLL_PIN
```

...but rather than setting FOLL_PIN directly, call sites should use one of the pin_user_pages\*() routines that set FOLL_PIN.

<a id="rst-case-2-rdma"></a>

### CASE 2: RDMA

There are GUP references to pages that are serving as DMA buffers. These buffers are needed for a long time ("long term"). No special synchronization with folio_mkclean() or munmap() is provided. Therefore, flags to set at the call site are:



```text
FOLL_PIN | FOLL_LONGTERM
```

NOTE: Some pages, such as DAX pages, cannot be pinned with longterm pins. That's because DAX pages do not have a separate page cache, and so "pinning" implies locking down file system blocks, which is not (yet) supported in that way.

<a id="rst-case-3-mmu-notifier-registration-with-or-without-page-faulting-hardware"></a>
<a id="rst-mmu-notifier-registration-case"></a>

### CASE 3: MMU notifier registration, with or without page faulting hardware

Device drivers can pin pages via get_user_pages\*(), and register for mmu notifier callbacks for the memory range. Then, upon receiving a notifier "invalidate range" callback , stop the device from using the range, and unpin the pages. There may be other possible schemes, such as for example explicitly synchronizing against pending IO, that accomplish approximately the same thing.

Or, if the hardware supports replayable page faults, then the device driver can avoid pinning entirely (this is ideal), as follows: register for mmu notifier callbacks as above, but instead of stopping the device and unpinning in the callback, simply remove the range from the device's page tables.

Either way, as long as the driver unpins the pages upon mmu notifier callback, then there is proper synchronization with both filesystem and mm (folio_mkclean(), munmap(), etc). Therefore, neither flag needs to be set.

<a id="rst-case-4-pinning-for-struct-page-manipulation-only"></a>

### CASE 4: Pinning for struct page manipulation only

If only struct page data (as opposed to the actual memory contents that a page is tracking) is affected, then normal GUP calls are sufficient, and neither flag needs to be set.

<a id="rst-case-5-pinning-in-order-to-write-to-the-data-within-the-page"></a>

### CASE 5: Pinning in order to write to the data within the page

Even though neither DMA nor Direct IO is involved, just a simple case of "pin, write to a page's data, unpin" can cause a problem. Case 5 may be considered a superset of Case 1, plus Case 2, plus anything that invokes that pattern. In other words, if the code is neither Case 1 nor Case 2, it may still require FOLL_PIN, for patterns like this:

- **Correct (uses FOLL_PIN calls):**

  pin_user_pages() write to the data within the pages unpin_user_pages()

- **INCORRECT (uses FOLL_GET calls):**

  get_user_pages() write to the data within the pages put_page()

<a id="rst-folio-maybe-dma-pinned-the-whole-point-of-pinning"></a>

## folio_maybe_dma_pinned(): the whole point of pinning

The whole point of marking folios as "DMA-pinned" or "gup-pinned" is to be able to query, "is this folio DMA-pinned?" That allows code such as folio_mkclean() (and file system writeback code in general) to make informed decisions about what to do when a folio cannot be unmapped due to such pins.

What to do in those cases is the subject of a years-long series of discussions and debates (see the References at the end of this document). It's a TODO item here: fill in the details once that's worked out. Meanwhile, it's safe to say that having this available:



```text
static inline bool folio_maybe_dma_pinned(struct folio *folio)
```

...is a prerequisite to solving the long-running gup+DMA problem.

<a id="rst-another-way-of-thinking-about-foll-get-foll-pin-and-foll-longterm"></a>

## Another way of thinking about FOLL_GET, FOLL_PIN, and FOLL_LONGTERM

Another way of thinking about these flags is as a progression of restrictions: FOLL_GET is for struct page manipulation, without affecting the data that the struct page refers to. FOLL_PIN is a *replacement* for FOLL_GET, and is for short term pins on pages whose data *will* get accessed. As such, FOLL_PIN is a "more severe" form of pinning. And finally, FOLL_LONGTERM is an even more restrictive case that has FOLL_PIN as a prerequisite: this is for pages that will be pinned longterm, and whose data will be accessed.

<a id="rst-unit-testing"></a>

## Unit testing

This file:



```text
tools/testing/selftests/mm/gup_test.c
```

has the following new calls to exercise the new pin\*() wrapper functions:

- PIN_FAST_BENCHMARK (./gup_test -a)

- PIN_BASIC_TEST (./gup_test -b)

You can monitor how many total dma-pinned pages have been acquired and released since the system was booted, via two new /proc/vmstat entries:



```text
/proc/vmstat/nr_foll_pin_acquired
/proc/vmstat/nr_foll_pin_released
```

Under normal conditions, these two values will be equal unless there are any long-term \[R\]DMA pins in place, or during pin/unpin transitions.

- nr_foll_pin_acquired: This is the number of logical pins that have been acquired since the system was powered on. For huge pages, the head page is pinned once for each page (head page and each tail page) within the huge page. This follows the same sort of behavior that get_user_pages() uses for huge pages: the head page is refcounted once for each tail or head page in the huge page, when get_user_pages() is applied to a huge page.

- nr_foll_pin_released: The number of logical pins that have been released since the system was powered on. Note that pages are released (unpinned) on a PAGE_SIZE granularity, even if the original pin was applied to a huge page. Becaused of the pin count behavior described above in "nr_foll_pin_acquired", the accounting balances out, so that after doing this:



  ```text
  pin_user_pages(huge_page);
  for (each page in huge_page)
      unpin_user_page(page);
  ```

...the following is expected:



```text
nr_foll_pin_released == nr_foll_pin_acquired
```

(...unless it was already out of balance due to a long-term RDMA pin being in place.)

<a id="rst-other-diagnostics"></a>

## Other diagnostics

dump_page() has been enhanced slightly to handle these new counting fields, and to better report on large folios in general.  Specifically, for large folios, the exact pincount is reported.

<a id="rst-references"></a>

## References

- [Some slow progress on get_user_pages() (Apr 2, 2019)](<https://lwn.net/Articles/784574/>)<a id="rst-some-slow-progress-on-get-user-pages-apr-2-2019"></a>

- [DMA and get_user_pages() (LPC: Dec 12, 2018)](<https://lwn.net/Articles/774411/>)<a id="rst-dma-and-get-user-pages-lpc-dec-12-2018"></a>

- [The trouble with get_user_pages() (Apr 30, 2018)](<https://lwn.net/Articles/753027/>)<a id="rst-the-trouble-with-get-user-pages-apr-30-2018"></a>

- [LWN kernel index: get_user_pages()](<https://lwn.net/Kernel/Index/#Memory_management-get_user_pages>)<a id="rst-lwn-kernel-index-get-user-pages"></a>

John Hubbard, October, 2019

---

# Message logging with printk

_Peios Kernel / Internals / Core APIs_

> printk() is one of the most widely known functions in the Linux kernel. It's the standard tool we have for printing messages and usually the most basic way of tracing and debugging. If you're familiar with printf(3) you can tell printk()…

<a id="rst-message-logging-with-printk"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

printk() is one of the most widely known functions in the Linux kernel. It's the standard tool we have for printing messages and usually the most basic way of tracing and debugging. If you're familiar with printf(3) you can tell printk() is based on it, although it has some functional differences:

> - printk() messages can specify a log level.
>
> - the format string, while largely compatible with C99, doesn't follow the exact same specification. It has some extensions and a few limitations (no `%n` or floating point conversion specifiers). See [How to get printk format specifiers right](</kernel/internals/core-api/printk-formats.md#rst-printk-specifiers>).

All printk() messages are printed to the kernel log buffer, which is a ring buffer exported to userspace through /dev/kmsg. The usual way to read it is using `dmesg`.

printk() is typically used like this:



```text
printk(KERN_INFO "Message: %s\n", arg);
```

where `KERN_INFO` is the log level (note that it's concatenated to the format string, the log level is not a separate argument). The available log levels are:


<table>
<thead>
<tr>
<th>


Name

</th>
<th>


String

</th>
<th>


Alias function

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


KERN_EMERG

</td>
<td>


"0"

</td>
<td>


pr_emerg()

</td>
</tr>
<tr>
<td>


KERN_ALERT

</td>
<td>


"1"

</td>
<td>


pr_alert()

</td>
</tr>
<tr>
<td>


KERN_CRIT

</td>
<td>


"2"

</td>
<td>


pr_crit()

</td>
</tr>
<tr>
<td>


KERN_ERR

</td>
<td>


"3"

</td>
<td>


pr_err()

</td>
</tr>
<tr>
<td>


KERN_WARNING

</td>
<td>


"4"

</td>
<td>


pr_warn()

</td>
</tr>
<tr>
<td>


KERN_NOTICE

</td>
<td>


"5"

</td>
<td>


pr_notice()

</td>
</tr>
<tr>
<td>


KERN_INFO

</td>
<td>


"6"

</td>
<td>


pr_info()

</td>
</tr>
<tr>
<td>


KERN_DEBUG

</td>
<td>


"7"

</td>
<td>


pr_debug() and pr_devel() if DEBUG is defined

</td>
</tr>
<tr>
<td>


KERN_DEFAULT

</td>
<td>


""

</td>
<td>




</td>
</tr>
<tr>
<td>


KERN_CONT

</td>
<td>


"c"

</td>
<td>


pr_cont()

</td>
</tr>
</tbody>
</table>

The log level specifies the importance of a message. The kernel decides whether to show the message immediately (printing it to the current console) depending on its log level and the current *console_loglevel* (a kernel variable). If the message priority is higher (lower log level value) than the *console_loglevel* the message will be printed to the console.

If the log level is omitted, the message is printed with `KERN_DEFAULT` level.

You can check the current *console_loglevel* with:



```text
$ cat /proc/sys/kernel/printk
4        4        1        7
```

The result shows the *current*, *default*, *minimum* and *boot-time-default* log levels.

To change the current console_loglevel simply write the desired level to `/proc/sys/kernel/printk`. For example, to print all messages to the console:



```text
# echo 8 > /proc/sys/kernel/printk
```

Another way, using `dmesg`:



```text
# dmesg -n 5
```

sets the console_loglevel to print KERN_WARNING (4) or more severe messages to console. See `dmesg(1)` for more information.

As an alternative to printk() you can use the `pr_*()` aliases for logging. This family of macros embed the log level in the macro names. For example:



```text
pr_info("Info message no. %d\n", msg_num);
```

prints a `KERN_INFO` message.

Besides being more concise than the equivalent printk() calls, they can use a common definition for the format string through the pr_fmt() macro. For instance, defining this at the top of a source file (before any `#include` directive):



```text
#define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__
```

would prefix every pr\_\*() message in that file with the module and function name that originated the message.

For debugging purposes there are also two conditionally-compiled macros: pr_debug() and pr_devel(), which are compiled-out unless `DEBUG` (or also `CONFIG_DYNAMIC_DEBUG` in the case of pr_debug()) is defined.

<a id="rst-function-reference"></a>

## Function reference


#### <a id="c-pr_fmt"></a>`pr_fmt()`

```c
pr_fmt(fmt)
```

used by the pr_*() macros to generate the printk format string

**Parameters**

- `fmt`: format string passed from a pr_*() macro

**Description**

This macro can be used to generate a unified format string for pr_*()
macros. A common use is to prefix all pr_*() messages in a file with a common
string. For example, defining this at the top of a source file:

\#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

would prefix all pr_info, pr_emerg... messages in the file with the module
name.

#### <a id="c-printk"></a>`printk()`

```c
printk(fmt, ...)
```

print a kernel message

**Parameters**

- `fmt`: format string
- `...`: variable arguments

**Description**

This is [`printk()`](#c-printk). It can be called from any context. We want it to work.

If printk indexing is enabled, `_printk()` is called from printk_index_wrap.
Otherwise, printk is simply #defined to _printk.

We try to grab the console_lock. If we succeed, it's easy - we log the
output and call the console drivers.  If we fail to get the semaphore, we
place the output into the log buffer and return. The current holder of
the console_sem will notice the new output in [`console_unlock()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-console_unlock); and will
send it to the consoles before releasing the lock.

One effect of this deferred printing is that code which calls [`printk()`](#c-printk) and
then changes console_loglevel may break. This is because console_loglevel
is inspected when the actual printing occurs.

See also:
printf(3)

See the [`vsnprintf()`](/kernel/internals/core-api/kernel-api.md#c-vsnprintf) documentation for format string extensions over C99.

#### <a id="c-pr_emerg"></a>`pr_emerg()`

```c
pr_emerg(fmt, ...)
```

Print an emergency-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_EMERG loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_alert"></a>`pr_alert()`

```c
pr_alert(fmt, ...)
```

Print an alert-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_ALERT loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_crit"></a>`pr_crit()`

```c
pr_crit(fmt, ...)
```

Print a critical-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_CRIT loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_err"></a>`pr_err()`

```c
pr_err(fmt, ...)
```

Print an error-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_ERR loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_warn"></a>`pr_warn()`

```c
pr_warn(fmt, ...)
```

Print a warning-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_WARNING loglevel. It uses [`pr_fmt()`](#c-pr_fmt)
to generate the format string.

#### <a id="c-pr_notice"></a>`pr_notice()`

```c
pr_notice(fmt, ...)
```

Print a notice-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_NOTICE loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_info"></a>`pr_info()`

```c
pr_info(fmt, ...)
```

Print an info-level message

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_INFO loglevel. It uses [`pr_fmt()`](#c-pr_fmt) to
generate the format string.

#### <a id="c-pr_cont"></a>`pr_cont()`

```c
pr_cont(fmt, ...)
```

Continues a previous log message in the same line.

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_CONT loglevel. It should only be
used when continuing a log message with no newline ('\n') enclosed. Otherwise
it defaults back to KERN_DEFAULT loglevel.

#### <a id="c-pr_devel"></a>`pr_devel()`

```c
pr_devel(fmt, ...)
```

Print a debug-level message conditionally

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to a printk with KERN_DEBUG loglevel if DEBUG is
defined. Otherwise it does nothing.

It uses [`pr_fmt()`](#c-pr_fmt) to generate the format string.

#### <a id="c-pr_debug"></a>`pr_debug()`

```c
pr_debug(fmt, ...)
```

Print a debug-level message conditionally

**Parameters**

- `fmt`: format string
- `...`: arguments for the format string

**Description**

This macro expands to `dynamic_pr_debug()` if CONFIG_DYNAMIC_DEBUG is
set. Otherwise, if DEBUG is defined, it's equivalent to a printk with
KERN_DEBUG loglevel. If DEBUG is not defined it does nothing.

It uses [`pr_fmt()`](#c-pr_fmt) to generate the format string (`dynamic_pr_debug()` uses
[`pr_fmt()`](#c-pr_fmt) internally).

---

# How to get printk format specifiers right

_Peios Kernel / Internals / Core APIs_

> If <type> is architecture-dependent for its size (e.g., cycles_t, tcflag_t) or is dependent on a config option for its size (e.g., blk_status_t), use a format specifier of its largest possible type and explicitly cast to it.

<a id="rst-how-to-get-printk-format-specifiers-right"></a>

<a id="rst-printk-specifiers"></a>

**Author:** Randy Dunlap &lt;[rdunlap@infradead.org](<mailto:rdunlap@infradead.org>)&gt;

**Author:** Andrew Murray &lt;[amurray@mpc-data.co.uk](<mailto:amurray@mpc-data.co.uk>)&gt;

<a id="rst-integer-types"></a>

## Integer types



```text
If variable is of Type,         use printk format specifier:
------------------------------------------------------------
        signed char             %d or %hhx
        unsigned char           %u or %x
        char                    %u or %x
        short int               %d or %hx
        unsigned short int      %u or %x
        int                     %d or %x
        unsigned int            %u or %x
        long                    %ld or %lx
        unsigned long           %lu or %lx
        long long               %lld or %llx
        unsigned long long      %llu or %llx
        size_t                  %zu or %zx
        ssize_t                 %zd or %zx
        s8                      %d or %hhx
        u8                      %u or %x
        s16                     %d or %hx
        u16                     %u or %x
        s32                     %d or %x
        u32                     %u or %x
        s64                     %lld or %llx
        u64                     %llu or %llx
```

If &lt;type&gt; is architecture-dependent for its size (e.g., cycles_t, tcflag_t) or is dependent on a config option for its size (e.g., blk_status_t), use a format specifier of its largest possible type and explicitly cast to it.

Example:



```text
printk("test: latency: %llu cycles\n", (unsigned long long)time);
```

Reminder: sizeof() returns type size_t.

The kernel's printf does not support %n. Floating point formats (%e, %f, %g, %a) are also not recognized, for obvious reasons. Use of any unsupported specifier or length qualifier results in a WARN and early return from vsnprintf().

<a id="rst-pointer-types"></a>

## Pointer types

A raw pointer value may be printed with %p which will hash the address before printing. The kernel also supports extended specifiers for printing pointers of different types.

Some of the extended specifiers print the data on the given address instead of printing the address itself. In this case, the following error messages might be printed instead of the unreachable information:



```text
(null)   data on plain NULL address
(efault) data on invalid address
(einval) invalid data on a valid address
```

<a id="rst-plain-pointers"></a>

### Plain Pointers



```text
%p      abcdef12 or 00000000abcdef12
```

Pointers printed without a specifier extension (i.e unadorned %p) are hashed to prevent leaking information about the kernel memory layout. This has the added benefit of providing a unique identifier. On 64-bit machines the first 32 bits are zeroed. The kernel will print `(ptrval)` until it gathers enough entropy.

When possible, use specialised modifiers such as %pS or %pB (described below) to avoid the need of providing an unhashed address that has to be interpreted post-hoc. If not possible, and the aim of printing the address is to provide more information for debugging, use %p and boot the kernel with the `no_hash_pointers` parameter during debugging, which will print all %p addresses unmodified. If you *really* always want the unmodified address, see %px below.

If (and only if) you are printing addresses as a content of a virtual file in e.g. procfs or sysfs (using e.g. seq_printf(), not printk()) read by a userspace process, use the %pK modifier described below instead of %p or %px.

<a id="rst-error-pointers"></a>

### Error Pointers



```text
%pe     -ENOSPC
```

For printing error pointers (i.e. a pointer for which IS_ERR() is true) as a symbolic error name. Error values for which no symbolic name is known are printed in decimal, while a non-ERR_PTR passed as the argument to %pe gets treated as ordinary %p.

<a id="rst-symbols-function-pointers"></a>

### Symbols/Function Pointers



```text
%pS     versatile_init+0x0/0x110
%ps     versatile_init
%pSR    versatile_init+0x9/0x110
        (with __builtin_extract_return_addr() translation)
%pB     prev_fn_of_versatile_init+0x88/0x88
```

The `S` and `s` specifiers are used for printing a pointer in symbolic format. They result in the symbol name with (S) or without (s) offsets. If KALLSYMS are disabled then the symbol address is printed instead.

The `B` specifier results in the symbol name with offsets and should be used when printing stack backtraces. The specifier takes into consideration the effect of compiler optimisations which may occur when tail-calls are used and marked with the noreturn GCC attribute.

If the pointer is within a module, the module name and optionally build ID is printed after the symbol name with an extra `b` appended to the end of the specifier.



```text
%pS     versatile_init+0x0/0x110 [module_name]
%pSb    versatile_init+0x0/0x110 [module_name ed5019fdf5e53be37cb1ba7899292d7e143b259e]
%pSRb   versatile_init+0x9/0x110 [module_name ed5019fdf5e53be37cb1ba7899292d7e143b259e]
        (with __builtin_extract_return_addr() translation)
%pBb    prev_fn_of_versatile_init+0x88/0x88 [module_name ed5019fdf5e53be37cb1ba7899292d7e143b259e]
```

<a id="rst-probed-pointers-from-bpf-tracing"></a>

### Probed Pointers from BPF / tracing



```text
%pks    kernel string
%pus    user string
```

The `k` and `u` specifiers are used for printing prior probed memory from either kernel memory (k) or user memory (u). The subsequent `s` specifier results in printing a string. For direct use in regular vsnprintf() the (k) and (u) annotation is ignored, however, when used out of BPF's bpf_trace_printk(), for example, it reads the memory it is pointing to without faulting.

<a id="rst-kernel-pointers"></a>

### Kernel Pointers



```text
%pK     01234567 or 0123456789abcdef
```

For printing kernel pointers which should be hidden from unprivileged users. The behaviour of %pK depends on the kptr_restrict sysctl - see [Documentation/admin-guide/sysctl/kernel.rst](/kernel/administration/admin-guide/sysctl/kernel.md) for more details.

This modifier is *only* intended when producing content of a file read by userspace from e.g. procfs or sysfs, not for dmesg. Please refer to the section about %p above for discussion about how to manage hashing pointers in printk().

<a id="rst-unmodified-addresses"></a>

### Unmodified Addresses



```text
%px     01234567 or 0123456789abcdef
```

For printing pointers when you *really* want to print the address. Please consider whether or not you are leaking sensitive information about the kernel memory layout before printing pointers with %px. %px is functionally equivalent to %lx (or %lu). %px is preferred because it is more uniquely grep'able. If in the future we need to modify the way the kernel handles printing pointers we will be better equipped to find the call sites.

Before using %px, consider if using %p is sufficient together with enabling the `no_hash_pointers` kernel parameter during debugging sessions (see the %p description above). One valid scenario for %px might be printing information immediately before a panic, which prevents any sensitive information to be exploited anyway, and with %px there would be no need to reproduce the panic with no_hash_pointers.

<a id="rst-pointer-differences"></a>

### Pointer Differences



```text
%td     2560
%tx     a00
```

For printing the pointer differences, use the %t modifier for ptrdiff_t.

Example:



```text
printk("test: difference between pointers: %td\n", ptr2 - ptr1);
```

<a id="rst-struct-resources"></a>

### Struct Resources



```text
%pr     [mem 0x60000000-0x6fffffff flags 0x2200] or
        [mem 0x60000000 flags 0x2200] or
        [mem 0x0000000060000000-0x000000006fffffff flags 0x2200]
        [mem 0x0000000060000000 flags 0x2200]
%pR     [mem 0x60000000-0x6fffffff pref] or
        [mem 0x60000000 pref] or
        [mem 0x0000000060000000-0x000000006fffffff pref]
        [mem 0x0000000060000000 pref]
```

For printing struct resources. The `R` and `r` specifiers result in a printed resource with (R) or without (r) a decoded flags member.  If start is equal to end only print the start value.

Passed by reference.

<a id="rst-physical-address-types-phys-addr-t"></a>

### Physical address types phys_addr_t



```text
%pa[p]  0x01234567 or 0x0123456789abcdef
```

For printing a phys_addr_t type (and its derivatives, such as resource_size_t) which can vary based on build options, regardless of the width of the CPU data path.

Passed by reference.

<a id="rst-struct-range"></a>

### Struct Range



```text
%pra    [range 0x0000000060000000-0x000000006fffffff] or
        [range 0x0000000060000000]
```

For printing struct range.  struct range holds an arbitrary range of u64 values.  If start is equal to end only print the start value.

Passed by reference.

<a id="rst-dma-address-types-dma-addr-t"></a>

### DMA address types dma_addr_t



```text
%pad    0x01234567 or 0x0123456789abcdef
```

For printing a dma_addr_t type which can vary based on build options, regardless of the width of the CPU data path.

Passed by reference.

<a id="rst-raw-buffer-as-an-escaped-string"></a>

### Raw buffer as an escaped string



```text
%*pE[achnops]
```

For printing raw buffer as an escaped string. For the following buffer:



```text
1b 62 20 5c 43 07 22 90 0d 5d
```

A few examples show how the conversion would be done (excluding surrounding quotes):



```text
%*pE            "\eb \C\a"\220\r]"
%*pEhp          "\x1bb \C\x07"\x90\x0d]"
%*pEa           "\e\142\040\\\103\a\042\220\r\135"
```

The conversion rules are applied according to an optional combination of flags (see `string_escape_mem()` kernel documentation for the details):

> - a - ESCAPE_ANY
>
> - c - ESCAPE_SPECIAL
>
> - h - ESCAPE_HEX
>
> - n - ESCAPE_NULL
>
> - o - ESCAPE_OCTAL
>
> - p - ESCAPE_NP
>
> - s - ESCAPE_SPACE

By default ESCAPE_ANY_NP is used.

ESCAPE_ANY_NP is the sane choice for many cases, in particularly for printing SSIDs.

If field width is omitted then 1 byte only will be escaped.

<a id="rst-raw-buffer-as-a-hex-string"></a>

### Raw buffer as a hex string



```text
%*ph    00 01 02  ...  3f
%*phC   00:01:02: ... :3f
%*phD   00-01-02- ... -3f
%*phN   000102 ... 3f
```

For printing small buffers (up to 64 bytes long) as a hex string with a certain separator. For larger buffers consider using `print_hex_dump()`.

<a id="rst-mac-fddi-addresses"></a>

### MAC/FDDI addresses



```text
%pM     00:01:02:03:04:05
%pMR    05:04:03:02:01:00
%pMF    00-01-02-03-04-05
%pm     000102030405
%pmR    050403020100
```

For printing 6-byte MAC/FDDI addresses in hex notation. The `M` and `m` specifiers result in a printed address with (M) or without (m) byte separators. The default byte separator is the colon (:).

Where FDDI addresses are concerned the `F` specifier can be used after the `M` specifier to use dash (-) separators instead of the default separator.

For Bluetooth addresses the `R` specifier shall be used after the `M` specifier to use reversed byte order suitable for visual interpretation of Bluetooth addresses which are in the little endian order.

Passed by reference.

<a id="rst-ipv4-addresses"></a>

### IPv4 addresses



```text
%pI4    1.2.3.4
%pi4    001.002.003.004
%p[Ii]4[hnbl]
```

For printing IPv4 dot-separated decimal addresses. The `I4` and `i4` specifiers result in a printed address with (i4) or without (I4) leading zeros.

The additional `h`, `n`, `b`, and `l` specifiers are used to specify host, network, big or little endian order addresses respectively. Where no specifier is provided the default network/big endian order is used.

Passed by reference.

<a id="rst-ipv6-addresses"></a>

### IPv6 addresses



```text
%pI6    0001:0002:0003:0004:0005:0006:0007:0008
%pi6    00010002000300040005000600070008
%pI6c   1:2:3:4:5:6:7:8
```

For printing IPv6 network-order 16-bit hex addresses. The `I6` and `i6` specifiers result in a printed address with (I6) or without (i6) colon-separators. Leading zeros are always used.

The additional `c` specifier can be used with the `I` specifier to print a compressed IPv6 address as described by [https://tools.ietf.org/html/rfc5952](<https://tools.ietf.org/html/rfc5952>)

Passed by reference.

<a id="rst-ipv4-ipv6-addresses-generic-with-port-flowinfo-scope"></a>

### IPv4/IPv6 addresses (generic, with port, flowinfo, scope)



```text
%pIS    1.2.3.4         or 0001:0002:0003:0004:0005:0006:0007:0008
%piS    001.002.003.004 or 00010002000300040005000600070008
%pISc   1.2.3.4         or 1:2:3:4:5:6:7:8
%pISpc  1.2.3.4:12345   or [1:2:3:4:5:6:7:8]:12345
%p[Ii]S[pfschnbl]
```

For printing an IP address without the need to distinguish whether it's of type AF_INET or AF_INET6. A pointer to a valid struct sockaddr, specified through `IS` or `iS`, can be passed to this format specifier.

The additional `p`, `f`, and `s` specifiers are used to specify port (IPv4, IPv6), flowinfo (IPv6) and scope (IPv6). Ports have a `:` prefix, flowinfo a `/` and scope a `%`, each followed by the actual value.

In case of an IPv6 address the compressed IPv6 address as described by [https://tools.ietf.org/html/rfc5952](<https://tools.ietf.org/html/rfc5952>) is being used if the additional specifier `c` is given. The IPv6 address is surrounded by `[`, `]` in case of additional specifiers `p`, `f` or `s` as suggested by [https://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-07](<https://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-07>)

In case of IPv4 addresses, the additional `h`, `n`, `b`, and `l` specifiers can be used as well and are ignored in case of an IPv6 address.

Passed by reference.

Further examples:



```text
%pISfc          1.2.3.4         or [1:2:3:4:5:6:7:8]/123456789
%pISsc          1.2.3.4         or [1:2:3:4:5:6:7:8]%1234567890
%pISpfc         1.2.3.4:12345   or [1:2:3:4:5:6:7:8]:12345/123456789
```

<a id="rst-uuid-guid-addresses"></a>

### UUID/GUID addresses



```text
%pUb    00010203-0405-0607-0809-0a0b0c0d0e0f
%pUB    00010203-0405-0607-0809-0A0B0C0D0E0F
%pUl    03020100-0504-0706-0809-0a0b0c0e0e0f
%pUL    03020100-0504-0706-0809-0A0B0C0E0E0F
```

For printing 16-byte UUID/GUIDs addresses. The additional `l`, `L`, `b` and `B` specifiers are used to specify a little endian order in lower (l) or upper case (L) hex notation - and big endian order in lower (b) or upper case (B) hex notation.

Where no additional specifiers are used the default big endian order with lower case hex notation will be printed.

Passed by reference.

<a id="rst-dentry-names"></a>

### dentry names



```text
%pd{,2,3,4}
%pD{,2,3,4}
```

For printing dentry name; if we race with `d_move()`, the name might be a mix of old and new ones, but it won't oops.  %pd dentry is a safer equivalent of %s dentry-&gt;d_name.name we used to use, %pd&lt;n&gt; prints `n` last components.  %pD does the same thing for struct file.

Passed by reference.

<a id="rst-block-device-names"></a>

### block_device names



```text
%pg     sda, sda1 or loop0p1
```

For printing name of block_device pointers.

<a id="rst-struct-va-format"></a>

### struct va_format



```text
%pV
```

For printing struct va_format structures. These contain a format string and va_list as follows:



```text
struct va_format {
        const char *fmt;
        va_list *va;
};
```

Implements a "recursive vsnprintf".

Do not use this feature without some mechanism to verify the correctness of the format string and va_list arguments.

Passed by reference.

<a id="rst-device-tree-nodes"></a>

### Device tree nodes



```text
%pOF[fnpPcCF]
```

For printing device tree node structures. Default behaviour is equivalent to %pOFf.

> - f - device node full_name
>
> - n - device node name
>
> - p - device node phandle
>
> - P - device node path spec (name + @unit)
>
> - F - device node flags
>
> - c - major compatible string
>
> - C - full compatible string

The separator when using multiple arguments is ':'

Examples:



```text
%pOF    /foo/bar@0                      - Node full name
%pOFf   /foo/bar@0                      - Same as above
%pOFfp  /foo/bar@0:10                   - Node full name + phandle
%pOFfcF /foo/bar@0:foo,device:--P-      - Node full name +
                                          major compatible string +
                                          node flags
                                                D - dynamic
                                                d - detached
                                                P - Populated
                                                B - Populated bus
```

Passed by reference.

<a id="rst-fwnode-handles"></a>

### Fwnode handles



```text
%pfw[fP]
```

For printing information on an fwnode_handle. The default is to print the full node name, including the path. The modifiers are functionally equivalent to %pOF above.

> - f - full name of the node, including the path
>
> - P - the name of the node including an address (if there is one)

Examples (ACPI):



```text
%pfwf   \_SB.PCI0.CIO2.port@1.endpoint@0        - Full node name
%pfwP   endpoint@0                              - Node name
```

Examples (OF):



```text
%pfwf   /ocp@68000000/i2c@48072000/camera@10/port/endpoint - Full name
%pfwP   endpoint                                - Node name
```

<a id="rst-time-and-date"></a>

### Time and date



```text
%pt[RT]                 YYYY-mm-ddTHH:MM:SS
%pt[RT]s                YYYY-mm-dd HH:MM:SS
%pt[RT]d                YYYY-mm-dd
%pt[RT]t                HH:MM:SS
%ptSp                   <seconds>.<nanoseconds>
%pt[RST][dt][r][s]
```

For printing date and time as represented by:



```text
R  content of struct rtc_time
S  content of struct timespec64
T  time64_t type
```

in human readable format.

By default year will be incremented by 1900 and month by 1. Use %pt\[RT\]r (raw) to suppress this behaviour.

The %pt\[RT\]s (space) will override ISO 8601 separator by using ' ' (space) instead of 'T' (Capital T) between date and time. It won't have any effect when date or time is omitted.

The %ptSp is equivalent to %lld.%09ld for the content of the struct timespec64. When the other specifiers are given, it becomes the respective equivalent of %ptT\[dt\]\[r\]\[s\].%09ld. In other words, the seconds are being printed in the human readable format followed by a dot and nanoseconds.

Passed by reference.

<a id="rst-struct-clk"></a>

### struct clk



```text
%pC     pll1
```

For printing struct clk structures. %pC prints the name of the clock (Common Clock Framework) or a unique 32-bit ID (legacy clock framework).

Passed by reference.

<a id="rst-bitmap-and-its-derivatives-such-as-cpumask-and-nodemask"></a>

### bitmap and its derivatives such as cpumask and nodemask



```text
%*pb    0779
%*pbl   0,3-6,8-10
```

For printing bitmap and its derivatives such as cpumask and nodemask, %\*pb outputs the bitmap with field width as the number of bits and %\*pbl output the bitmap as range list with field width as the number of bits.

The field width is passed by value, the bitmap is passed by reference. Helper macros cpumask_pr_args() and nodemask_pr_args() are available to ease printing cpumask and nodemask.

<a id="rst-flags-bitfields-such-as-page-flags-and-gfp-flags"></a>

### Flags bitfields such as page flags and gfp_flags



```text
%pGp    0x17ffffc0002036(referenced|uptodate|lru|active|private|node=0|zone=2|lastcpupid=0x1fffff)
%pGg    GFP_USER|GFP_DMA32|GFP_NOWARN
%pGv    read|exec|mayread|maywrite|mayexec|denywrite
```

For printing flags bitfields as a collection of symbolic constants that would construct the value. The type of flags is given by the third character. Currently supported are:

> - p - \[p\]age flags, expects value of type (`unsigned long *`)
>
> - v - \[v\]ma_flags, expects value of type (`unsigned long *`)
>
> - g - \[g\]fp_flags, expects value of type (`gfp_t *`)

The flag names and print order depends on the particular type.

Note that this format should not be used directly in the `TP_printk()` part of a tracepoint. Instead, use the show\_\*\_flags() functions from &lt;trace/events/mmflags.h&gt;.

Passed by reference.

<a id="rst-network-device-features"></a>

### Network device features



```text
%pNF    0x000000000000c000
```

For printing netdev_features_t.

Passed by reference.

<a id="rst-v4l2-and-drm-fourcc-code-pixel-format"></a>

### V4L2 and DRM FourCC code (pixel format)



```text
%p4cc
```

Print a FourCC code used by V4L2 or DRM, including format endianness and its numerical value as hexadecimal.

Passed by reference.

Examples:



```text
%p4cc   BG12 little-endian (0x32314742)
%p4cc   Y10  little-endian (0x20303159)
%p4cc   NV12 big-endian (0xb231564e)
```

<a id="rst-generic-fourcc-code"></a>

### Generic FourCC code

- **::**

  %p4c\[h\[R\]lb\]    gP00 (0x67503030)

Print a generic FourCC code, as both ASCII characters and its numerical value as hexadecimal.

The generic FourCC code is always printed in the big-endian format, the most significant byte first. This is the opposite of V4L/DRM FourCCs.

The additional `h`, `hR`, `l`, and `b` specifiers define what endianness is used to load the stored bytes. The data might be interpreted using the host, reversed host byte order, little-endian, or big-endian.

Passed by reference.

Examples for a little-endian machine, given &amp;(u32)0x67503030:



```text
%p4ch   gP00 (0x67503030)
%p4chR  00Pg (0x30305067)
%p4cl   gP00 (0x67503030)
%p4cb   00Pg (0x30305067)
```

Examples for a big-endian machine, given &amp;(u32)0x67503030:



```text
%p4ch   gP00 (0x67503030)
%p4chR  00Pg (0x30305067)
%p4cl   00Pg (0x30305067)
%p4cb   gP00 (0x67503030)
```

<a id="rst-rust"></a>

### Rust



```text
%pA
```

Only intended to be used from Rust code to format `core::fmt::Arguments`. Do *not* use it from C.

<a id="rst-thanks"></a>

## Thanks

If you add other %p extensions, please extend &lt;lib/tests/printf_kunit.c&gt; with one or more test cases, if at all feasible.

Thank you for your cooperation and attention.

---

# Printk Index

_Peios Kernel / Internals / Core APIs_

> There are many ways to monitor the state of the system. One important source of information is the system log. It provides a lot of information, including more or less important warnings and error messages.

<a id="rst-printk-index"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

There are many ways to monitor the state of the system. One important source of information is the system log. It provides a lot of information, including more or less important warnings and error messages.

There are monitoring tools that filter and take action based on messages logged.

The kernel messages are evolving together with the code. As a result, particular kernel messages are not KABI and never will be\!

It is a huge challenge for maintaining the system log monitors. It requires knowing what messages were updated in a particular kernel version and why. Finding these changes in the sources would require non-trivial parsers. Also it would require matching the sources with the binary kernel which is not always trivial. Various changes might be backported. Various kernel versions might be used on different monitored systems.

This is where the printk index feature might become useful. It provides a dump of printk formats used all over the source code used for the kernel and modules on the running system. It is accessible at runtime via debugfs.

The printk index helps to find changes in the message formats. Also it helps to track the strings back to the kernel sources and the related commit.

<a id="rst-user-interface"></a>

## User Interface

The index of printk formats are split in into separate files. The files are named according to the binaries where the printk formats are built-in. There is always "vmlinux" and optionally also modules, for example:



```text
/sys/kernel/debug/printk/index/vmlinux
/sys/kernel/debug/printk/index/ext4
/sys/kernel/debug/printk/index/scsi_mod
```

Note that only loaded modules are shown. Also printk formats from a module might appear in "vmlinux" when the module is built-in.

The content is inspired by the dynamic debug interface and looks like:



```text
$> head -1 /sys/kernel/debug/printk/index/vmlinux; shuf -n 5 vmlinux
# <level[,flags]> filename:line function "format"
<5> block/blk-settings.c:661 disk_stack_limits "%s: Warning: Device %s is misaligned\n"
<4> kernel/trace/trace.c:8296 trace_create_file "Could not create tracefs '%s' entry\n"
<6> arch/x86/kernel/hpet.c:144 _hpet_print_config "hpet: %s(%d):\n"
<6> init/do_mounts.c:605 prepare_namespace "Waiting for root device %s...\n"
<6> drivers/acpi/osl.c:1410 acpi_no_auto_serialize_setup "ACPI: auto-serialization disabled\n"
```

, where the meaning is:

> - **level:** log level value: 0-7 for particular severity, -1 as default, 'c' as continuous line without an explicit log level
>
> - **flags:** optional flags: currently only 'c' for KERN_CONT
>
> - **filename:line:** source filename and line number of the related printk() call. Note that there are many wrappers, for example, pr_warn(), pr_warn_once(), dev_warn().
>
> - **function:** function name where the printk() call is used.
>
> - **format:** format string

The extra information makes it a bit harder to find differences between various kernels. Especially the line number might change very often. On the other hand, it helps a lot to confirm that it is the same string or find the commit that is responsible for eventual changes.

<a id="rst-printk-is-not-a-stable-kabi"></a>

## printk() Is Not a Stable KABI

Several developers are afraid that exporting all these implementation details into the user space will transform particular printk() calls into KABI.

But it is exactly the opposite. printk() calls must \_not\_ be KABI. And the printk index helps user space tools to deal with this.

<a id="rst-subsystem-specific-printk-wrappers"></a>

## Subsystem specific printk wrappers

The printk index is generated using extra metadata that are stored in a dedicated .elf section ".printk_index". It is achieved using macro wrappers doing \__printk_index_emit() together with the real printk() call. The same technique is used also for the metadata used by the dynamic debug feature.

The metadata are stored for a particular message only when it is printed using these special wrappers. It is implemented for the commonly used printk() calls, including, for example, pr_warn(), or pr_once().

Additional changes are necessary for various subsystem specific wrappers that call the original printk() via a common helper function. These needs their own wrappers adding \__printk_index_emit().

Only few subsystem specific wrappers have been updated so far, for example, dev_printk(). As a result, the printk formats from some subsystems can be missing in the printk index.

<a id="rst-subsystem-specific-prefix"></a>

## Subsystem specific prefix

The macro pr_fmt() macro allows to define a prefix that is printed before the string generated by the related printk() calls.

Subsystem specific wrappers usually add even more complicated prefixes.

These prefixes can be stored into the printk index metadata by an optional parameter of \__printk_index_emit(). The debugfs interface might then show the printk formats including these prefixes. For example, drivers/acpi/osl.c contains:



```text
#define pr_fmt(fmt) "ACPI: OSL: " fmt

static int __init acpi_no_auto_serialize_setup(char *str)
{
      acpi_gbl_auto_serialize_methods = FALSE;
      pr_info("Auto-serialization disabled\n");

      return 1;
}
```

This results in the following printk index entry:



```text
<6> drivers/acpi/osl.c:1410 acpi_no_auto_serialize_setup "ACPI: auto-serialization disabled\n"
```

It helps matching messages from the real log with printk index. Then the source file name, line number, and function name can be used to match the string with the source code.

---

# Memory Protection Keys

_Peios Kernel / Internals / Core APIs_

> Memory Protection Keys provide a mechanism for enforcing page-based protections, but without requiring modification of the page tables when an application changes protection domains.

<a id="rst-memory-protection-keys"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Memory Protection Keys provide a mechanism for enforcing page-based protections, but without requiring modification of the page tables when an application changes protection domains.

- **Pkeys Userspace (PKU) is a feature which can be found on:**

  - Intel server CPUs, Skylake and later

  - Intel client CPUs, Tiger Lake (11th Gen Core) and later

  - Future AMD CPUs

  - arm64 CPUs implementing the Permission Overlay Extension (FEAT_S1POE)

<a id="rst-x86-64"></a>

## x86_64

Pkeys work by dedicating 4 previously Reserved bits in each page table entry to a "protection key", giving 16 possible keys.

Protections for each key are defined with a per-CPU user-accessible register (PKRU).  Each of these is a 32-bit register storing two bits (Access Disable and Write Disable) for each of 16 keys.

Being a CPU register, PKRU is inherently thread-local, potentially giving each thread a different set of protections from every other thread.

There are two instructions (RDPKRU/WRPKRU) for reading and writing to the register.  The feature is only available in 64-bit mode, even though there is theoretically space in the PAE PTEs.  These permissions are enforced on data access only and have no effect on instruction fetches.

<a id="rst-arm64"></a>

## arm64

Pkeys use 3 bits in each page table entry, to encode a "protection key index", giving 8 possible keys.

Protections for each key are defined with a per-CPU user-writable system register (POR_EL0).  This is a 64-bit register encoding read, write and execute overlay permissions for each protection key index.

Being a CPU register, POR_EL0 is inherently thread-local, potentially giving each thread a different set of protections from every other thread.

Unlike x86_64, the protection key permissions also apply to instruction fetches.

<a id="rst-syscalls"></a>

## Syscalls

There are 3 system calls which directly interact with pkeys:



```text
int pkey_alloc(unsigned long flags, unsigned long init_access_rights)
int pkey_free(int pkey);
int pkey_mprotect(unsigned long start, size_t len,
                  unsigned long prot, int pkey);
```

Before a pkey can be used, it must first be allocated with pkey_alloc().  An application writes to the architecture specific CPU register directly in order to change access permissions to memory covered with a key.  In this example this is wrapped by a C function called pkey_set().



```text
int real_prot = PROT_READ|PROT_WRITE;
pkey = pkey_alloc(0, PKEY_DISABLE_WRITE);
ptr = mmap(NULL, PAGE_SIZE, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
ret = pkey_mprotect(ptr, PAGE_SIZE, real_prot, pkey);
... application runs here
```

Now, if the application needs to update the data at 'ptr', it can gain access, do the update, then remove its write access:



```text
pkey_set(pkey, 0); // clear PKEY_DISABLE_WRITE
*ptr = foo; // assign something
pkey_set(pkey, PKEY_DISABLE_WRITE); // set PKEY_DISABLE_WRITE again
```

Now when it frees the memory, it will also free the pkey since it is no longer in use:



```text
munmap(ptr, PAGE_SIZE);
pkey_free(pkey);
```

> [!NOTE]
>
> pkey_set() is a wrapper around writing to the CPU register. Example implementations can be found in tools/testing/selftests/mm/pkey-\{arm64,powerpc,x86\}.h

<a id="rst-behavior"></a>

## Behavior

The kernel attempts to make protection keys consistent with the behavior of a plain mprotect().  For instance if you do this:



```text
mprotect(ptr, size, PROT_NONE);
something(ptr);
```

you can expect the same effects with protection keys when doing this:



```text
pkey = pkey_alloc(0, PKEY_DISABLE_WRITE | PKEY_DISABLE_READ);
pkey_mprotect(ptr, size, PROT_READ|PROT_WRITE, pkey);
something(ptr);
```

That should be true whether something() is a direct access to 'ptr' like:



```text
*ptr = foo;
```

or when the kernel does the access on the application's behalf like with a read():



```text
read(fd, ptr, 1);
```

The kernel will send a SIGSEGV in both cases, but si_code will be set to SEGV_PKERR when violating protection keys versus SEGV_ACCERR when the plain mprotect() permissions are violated.

Note that kernel accesses from a kthread (such as io_uring) will use a default value for the protection key register and so will not be consistent with userspace's value of the register or mprotect().

---

# Red-black Trees (rbtree) in Linux

_Peios Kernel / Internals / Core APIs_

> Red-black trees are a type of self-balancing binary search tree, used for storing sortable key/value data pairs. This differs from radix trees (which are used to efficiently store sparse arrays and thus use long integer indexes to…

<a id="rst-red-black-trees-rbtree-in-linux"></a>

**Date:** January 18, 2007

**Author:** Rob Landley &lt;[rob@landley.net](<mailto:rob@landley.net>)&gt;

<a id="rst-what-are-red-black-trees-and-what-are-they-for"></a>

## What are red-black trees, and what are they for?

Red-black trees are a type of self-balancing binary search tree, used for storing sortable key/value data pairs.  This differs from radix trees (which are used to efficiently store sparse arrays and thus use long integer indexes to insert/access/delete nodes) and hash tables (which are not kept sorted to be easily traversed in order, and must be tuned for a specific size and hash function where rbtrees scale gracefully storing arbitrary keys).

Red-black trees are similar to AVL trees, but provide faster real-time bounded worst case performance for insertion and deletion (at most two rotations and three rotations, respectively, to balance the tree), with slightly slower (but still O(log n)) lookup time.

To quote Linux Weekly News:

> There are a number of red-black trees in use in the kernel. The deadline and CFQ I/O schedulers employ rbtrees to track requests; the packet CD/DVD driver does the same. The high-resolution timer code uses an rbtree to organize outstanding timer requests.  The ext3 filesystem tracks directory entries in a red-black tree.  Virtual memory areas (VMAs) are tracked with red-black trees, as are epoll file descriptors, cryptographic keys, and network packets in the "hierarchical token bucket" scheduler.

This document covers use of the Linux rbtree implementation.  For more information on the nature and implementation of Red Black Trees,  see:

> - **Linux Weekly News article on red-black trees**
>
>   [https://lwn.net/Articles/184495/](<https://lwn.net/Articles/184495/>)
>
> - **Wikipedia entry on red-black trees**
>
>   [https://en.wikipedia.org/wiki/Red-black_tree](<https://en.wikipedia.org/wiki/Red-black_tree>)

<a id="rst-linux-implementation-of-red-black-trees"></a>

## Linux implementation of red-black trees

Linux's rbtree implementation lives in the file "lib/rbtree.c".  To use it, "\#include &lt;linux/rbtree.h&gt;".

The Linux rbtree implementation is optimized for speed, and thus has one less layer of indirection (and better cache locality) than more traditional tree implementations.  Instead of using pointers to separate rb_node and data structures, each instance of struct rb_node is embedded in the data structure it organizes.  And instead of using a comparison callback function pointer, users are expected to write their own tree search and insert functions which call the provided rbtree functions.  Locking is also left up to the user of the rbtree code.

<a id="rst-creating-a-new-rbtree"></a>

## Creating a new rbtree

Data nodes in an rbtree tree are structures containing a struct rb_node member:



```text
struct mytype {
      struct rb_node node;
      char *keystring;
};
```

When dealing with a pointer to the embedded struct rb_node, the containing data structure may be accessed with the standard container_of() macro.  In addition, individual members may be accessed directly via rb_entry(node, type, member).

At the root of each rbtree is an rb_root structure, which is initialized to be empty via:

> struct rb_root mytree = RB_ROOT;

<a id="rst-searching-for-a-value-in-an-rbtree"></a>

## Searching for a value in an rbtree

Writing a search function for your tree is fairly straightforward: start at the root, compare each value, and follow the left or right branch as necessary.

Example:



```text
struct mytype *my_search(struct rb_root *root, char *string)
{
      struct rb_node *node = root->rb_node;

      while (node) {
              struct mytype *data = container_of(node, struct mytype, node);
              int result;

              result = strcmp(string, data->keystring);

              if (result < 0)
                      node = node->rb_left;
              else if (result > 0)
                      node = node->rb_right;
              else
                      return data;
      }
      return NULL;
}
```

<a id="rst-inserting-data-into-an-rbtree"></a>

## Inserting data into an rbtree

Inserting data in the tree involves first searching for the place to insert the new node, then inserting the node and rebalancing ("recoloring") the tree.

The search for insertion differs from the previous search by finding the location of the pointer on which to graft the new node.  The new node also needs a link to its parent node for rebalancing purposes.

Example:



```text
int my_insert(struct rb_root *root, struct mytype *data)
{
      struct rb_node **new = &(root->rb_node), *parent = NULL;

      /* Figure out where to put new node */
      while (*new) {
              struct mytype *this = container_of(*new, struct mytype, node);
              int result = strcmp(data->keystring, this->keystring);

              parent = *new;
              if (result < 0)
                      new = &((*new)->rb_left);
              else if (result > 0)
                      new = &((*new)->rb_right);
              else
                      return FALSE;
      }

      /* Add new node and rebalance tree. */
      rb_link_node(&data->node, parent, new);
      rb_insert_color(&data->node, root);

      return TRUE;
}
```

<a id="rst-removing-or-replacing-existing-data-in-an-rbtree"></a>

## Removing or replacing existing data in an rbtree

To remove an existing node from a tree, call:



```text
void rb_erase(struct rb_node *victim, struct rb_root *tree);
```

Example:



```text
struct mytype *data = mysearch(&mytree, "walrus");

if (data) {
      rb_erase(&data->node, &mytree);
      myfree(data);
}
```

To replace an existing node in a tree with a new one with the same key, call:



```text
void rb_replace_node(struct rb_node *old, struct rb_node *new,
                      struct rb_root *tree);
```

Replacing a node this way does not re-sort the tree: If the new node doesn't have the same key as the old node, the rbtree will probably become corrupted.

<a id="rst-iterating-through-the-elements-stored-in-an-rbtree-in-sort-order"></a>

## Iterating through the elements stored in an rbtree (in sort order)

Four functions are provided for iterating through an rbtree's contents in sorted order.  These work on arbitrary trees, and should not need to be modified or wrapped (except for locking purposes):



```text
struct rb_node *rb_first(struct rb_root *tree);
struct rb_node *rb_last(struct rb_root *tree);
struct rb_node *rb_next(struct rb_node *node);
struct rb_node *rb_prev(struct rb_node *node);
```

To start iterating, call rb_first() or rb_last() with a pointer to the root of the tree, which will return a pointer to the node structure contained in the first or last element in the tree.  To continue, fetch the next or previous node by calling rb_next() or rb_prev() on the current node.  This will return NULL when there are no more nodes left.

The iterator functions return a pointer to the embedded struct rb_node, from which the containing data structure may be accessed with the container_of() macro, and individual members may be accessed directly via rb_entry(node, type, member).

Example:



```text
struct rb_node *node;
for (node = rb_first(&mytree); node; node = rb_next(node))
      printk("key=%s\n", rb_entry(node, struct mytype, node)->keystring);
```

<a id="rst-cached-rbtrees"></a>

## Cached rbtrees

Computing the leftmost (smallest) node is quite a common task for binary search trees, such as for traversals or users relying on the particular order for their own logic. To this end, users can use 'struct rb_root_cached' to optimize O(logN) rb_first() calls to a simple pointer fetch avoiding potentially expensive tree iterations. This is done at negligible runtime overhead for maintenance; albeit larger memory footprint.

Similar to the rb_root structure, cached rbtrees are initialized to be empty via:



```text
struct rb_root_cached mytree = RB_ROOT_CACHED;
```

Cached rbtree is simply a regular rb_root with an extra pointer to cache the leftmost node. This allows rb_root_cached to exist wherever rb_root does, which permits augmented trees to be supported as well as only a few extra interfaces:



```text
struct rb_node *rb_first_cached(struct rb_root_cached *tree);
void rb_insert_color_cached(struct rb_node *, struct rb_root_cached *, bool);
void rb_erase_cached(struct rb_node *node, struct rb_root_cached *);
```

Both insert and erase calls have their respective counterpart of augmented trees:



```text
void rb_insert_augmented_cached(struct rb_node *node, struct rb_root_cached *,
                                bool, struct rb_augment_callbacks *);
void rb_erase_augmented_cached(struct rb_node *, struct rb_root_cached *,
                               struct rb_augment_callbacks *);
```

<a id="rst-support-for-augmented-rbtrees"></a>

## Support for Augmented rbtrees

Augmented rbtree is an rbtree with "some" additional data stored in each node, where the additional data for node N must be a function of the contents of all nodes in the subtree rooted at N. This data can be used to augment some new functionality to rbtree. Augmented rbtree is an optional feature built on top of basic rbtree infrastructure. An rbtree user who wants this feature will have to call the augmentation functions with the user provided augmentation callback when inserting and erasing nodes.

C files implementing augmented rbtree manipulation must include &lt;linux/rbtree_augmented.h&gt; instead of &lt;linux/rbtree.h&gt;. Note that linux/rbtree_augmented.h exposes some rbtree implementations details you are not expected to rely on; please stick to the documented APIs there and do not include &lt;linux/rbtree_augmented.h&gt; from header files either so as to minimize chances of your users accidentally relying on such implementation details.

On insertion, the user must update the augmented information on the path leading to the inserted node, then call rb_link_node() as usual and rb_augment_inserted() instead of the usual rb_insert_color() call. If rb_augment_inserted() rebalances the rbtree, it will callback into a user provided function to update the augmented information on the affected subtrees.

When erasing a node, the user must call rb_erase_augmented() instead of rb_erase(). rb_erase_augmented() calls back into user provided functions to update the augmented information on affected subtrees.

In both cases, the callbacks are provided through struct rb_augment_callbacks. 3 callbacks must be defined:

- A propagation callback, which updates the augmented value for a given node and its ancestors, up to a given stop point (or NULL to update all the way to the root).

- A copy callback, which copies the augmented value for a given subtree to a newly assigned subtree root.

- A tree rotation callback, which copies the augmented value for a given subtree to a newly assigned subtree root AND recomputes the augmented information for the former subtree root.

The compiled code for rb_erase_augmented() may inline the propagation and copy callbacks, which results in a large function, so each augmented rbtree user should have a single rb_erase_augmented() call site in order to limit compiled code size.

<a id="rst-sample-usage"></a>

### Sample usage

Interval tree is an example of augmented rb tree. Reference - "Introduction to Algorithms" by Cormen, Leiserson, Rivest and Stein. More details about interval trees:

Classical rbtree has a single key and it cannot be directly used to store interval ranges like \[lo:hi\] and do a quick lookup for any overlap with a new lo:hi or to find whether there is an exact match for a new lo:hi.

However, rbtree can be augmented to store such interval ranges in a structured way making it possible to do efficient lookup and exact match.

This "extra information" stored in each node is the maximum hi (max_hi) value among all the nodes that are its descendants. This information can be maintained at each node just by looking at the node and its immediate children. And this will be used in O(log n) lookup for lowest match (lowest start address among all possible matches) with something like:



```text
struct interval_tree_node *
interval_tree_first_match(struct rb_root *root,
                          unsigned long start, unsigned long last)
{
      struct interval_tree_node *node;

      if (!root->rb_node)
              return NULL;
      node = rb_entry(root->rb_node, struct interval_tree_node, rb);

      while (true) {
              if (node->rb.rb_left) {
                      struct interval_tree_node *left =
                              rb_entry(node->rb.rb_left,
                                       struct interval_tree_node, rb);
                      if (left->__subtree_last >= start) {
                              /*
                               * Some nodes in left subtree satisfy Cond2.
                               * Iterate to find the leftmost such node N.
                               * If it also satisfies Cond1, that's the match
                               * we are looking for. Otherwise, there is no
                               * matching interval as nodes to the right of N
                               * can't satisfy Cond1 either.
                               */
                              node = left;
                              continue;
                      }
              }
              if (node->start <= last) {              /* Cond1 */
                      if (node->last >= start)        /* Cond2 */
                              return node;    /* node is leftmost match */
                      if (node->rb.rb_right) {
                              node = rb_entry(node->rb.rb_right,
                                      struct interval_tree_node, rb);
                              if (node->__subtree_last >= start)
                                      continue;
                      }
              }
              return NULL;    /* No match */
      }
}
```

Insertion/removal are defined using the following augmented callbacks:



```text
static inline unsigned long
compute_subtree_last(struct interval_tree_node *node)
{
      unsigned long max = node->last, subtree_last;
      if (node->rb.rb_left) {
              subtree_last = rb_entry(node->rb.rb_left,
                      struct interval_tree_node, rb)->__subtree_last;
              if (max < subtree_last)
                      max = subtree_last;
      }
      if (node->rb.rb_right) {
              subtree_last = rb_entry(node->rb.rb_right,
                      struct interval_tree_node, rb)->__subtree_last;
              if (max < subtree_last)
                      max = subtree_last;
      }
      return max;
}

static void augment_propagate(struct rb_node *rb, struct rb_node *stop)
{
      while (rb != stop) {
              struct interval_tree_node *node =
                      rb_entry(rb, struct interval_tree_node, rb);
              unsigned long subtree_last = compute_subtree_last(node);
              if (node->__subtree_last == subtree_last)
                      break;
              node->__subtree_last = subtree_last;
              rb = rb_parent(&node->rb);
      }
}

static void augment_copy(struct rb_node *rb_old, struct rb_node *rb_new)
{
      struct interval_tree_node *old =
              rb_entry(rb_old, struct interval_tree_node, rb);
      struct interval_tree_node *new =
              rb_entry(rb_new, struct interval_tree_node, rb);

      new->__subtree_last = old->__subtree_last;
}

static void augment_rotate(struct rb_node *rb_old, struct rb_node *rb_new)
{
      struct interval_tree_node *old =
              rb_entry(rb_old, struct interval_tree_node, rb);
      struct interval_tree_node *new =
              rb_entry(rb_new, struct interval_tree_node, rb);

      new->__subtree_last = old->__subtree_last;
      old->__subtree_last = compute_subtree_last(old);
}

static const struct rb_augment_callbacks augment_callbacks = {
      augment_propagate, augment_copy, augment_rotate
};

void interval_tree_insert(struct interval_tree_node *node,
                          struct rb_root *root)
{
      struct rb_node **link = &root->rb_node, *rb_parent = NULL;
      unsigned long start = node->start, last = node->last;
      struct interval_tree_node *parent;

      while (*link) {
              rb_parent = *link;
              parent = rb_entry(rb_parent, struct interval_tree_node, rb);
              if (parent->__subtree_last < last)
                      parent->__subtree_last = last;
              if (start < parent->start)
                      link = &parent->rb.rb_left;
              else
                      link = &parent->rb.rb_right;
      }

      node->__subtree_last = last;
      rb_link_node(&node->rb, rb_parent, link);
      rb_insert_augmented(&node->rb, root, &augment_callbacks);
}

void interval_tree_remove(struct interval_tree_node *node,
                          struct rb_root *root)
{
      rb_erase_augmented(&node->rb, root, &augment_callbacks);
}
```

---

# refcount_t API compared to atomic_t

_Peios Kernel / Internals / Core APIs_

> Introduction

<a id="rst-refcount-t-api-compared-to-atomic-t"></a>

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

The goal of refcount_t API is to provide a minimal API for implementing an object's reference counters. While a generic architecture-independent implementation from lib/refcount.c uses atomic operations underneath, there are a number of differences between some of the `refcount_*()` and `atomic_*()` functions with regards to the memory ordering guarantees. This document outlines the differences and provides respective examples in order to help maintainers validate their code against the change in these memory ordering guarantees.

The terms used through this document try to follow the formal LKMM defined in tools/memory-model/Documentation/explanation.txt.

memory-barriers.txt and atomic_t.txt provide more background to the memory ordering in general and for atomic operations specifically.

<a id="rst-relevant-types-of-memory-ordering"></a>

## Relevant types of memory ordering

> [!NOTE]
>
> The following section only covers some of the memory ordering types that are relevant for the atomics and reference counters and used through this document. For a much broader picture please consult memory-barriers.txt document.

In the absence of any memory ordering guarantees (i.e. fully unordered) atomics &amp; refcounters only provide atomicity and program order (po) relation (on the same CPU). It guarantees that each `atomic_*()` and `refcount_*()` operation is atomic and instructions are executed in program order on a single CPU. This is implemented using READ_ONCE()/WRITE_ONCE() and compare-and-swap primitives.

A strong (full) memory ordering guarantees that all prior loads and stores (all po-earlier instructions) on the same CPU are completed before any po-later instruction is executed on the same CPU. It also guarantees that all po-earlier stores on the same CPU and all propagated stores from other CPUs must propagate to all other CPUs before any po-later instruction is executed on the original CPU (A-cumulative property). This is implemented using smp_mb().

A RELEASE memory ordering guarantees that all prior loads and stores (all po-earlier instructions) on the same CPU are completed before the operation. It also guarantees that all po-earlier stores on the same CPU and all propagated stores from other CPUs must propagate to all other CPUs before the release operation (A-cumulative property). This is implemented using smp_store_release().

An ACQUIRE memory ordering guarantees that all post loads and stores (all po-later instructions) on the same CPU are completed after the acquire operation. It also guarantees that all po-later stores on the same CPU must propagate to all other CPUs after the acquire operation executes. This is implemented using smp_acquire__after_ctrl_dep().

A control dependency (on success) for refcounters guarantees that if a reference for an object was successfully obtained (reference counter increment or addition happened, function returned true), then further stores are ordered against this operation. Control dependency on stores are not implemented using any explicit barriers, but rely on CPU not to speculate on stores. This is only a single CPU relation and provides no guarantees for other CPUs.

<a id="rst-comparison-of-functions"></a>

## Comparison of functions

<a id="rst-case-1-non-read-modify-write-rmw-ops"></a>

### case 1) - non-"Read/Modify/Write" (RMW) ops

Function changes:

> - atomic_set() --&gt; refcount_set()
>
> - atomic_read() --&gt; refcount_read()

Memory ordering guarantee changes:

> - none (both fully unordered)

<a id="rst-case-2-non-read-modify-write-rmw-ops-with-release-ordering"></a>

### case 2) - non-"Read/Modify/Write" (RMW) ops with release ordering

Function changes:

> - atomic_set_release() --&gt; refcount_set_release()

Memory ordering guarantee changes:

> - none (both provide RELEASE ordering)

<a id="rst-case-3-increment-based-ops-that-return-no-value"></a>

### case 3) - increment-based ops that return no value

Function changes:

> - atomic_inc() --&gt; refcount_inc()
>
> - atomic_add() --&gt; refcount_add()

Memory ordering guarantee changes:

> - none (both fully unordered)

<a id="rst-case-4-decrement-based-rmw-ops-that-return-no-value"></a>

### case 4) - decrement-based RMW ops that return no value

Function changes:

> - atomic_dec() --&gt; refcount_dec()

Memory ordering guarantee changes:

> - fully unordered --&gt; RELEASE ordering

<a id="rst-case-5-increment-based-rmw-ops-that-return-a-value"></a>

### case 5) - increment-based RMW ops that return a value

Function changes:

> - atomic_inc_not_zero() --&gt; refcount_inc_not_zero()
>
> - no atomic counterpart --&gt; refcount_add_not_zero()

Memory ordering guarantees changes:

> - fully ordered --&gt; control dependency on success for stores

> [!NOTE]
>
> We really assume here that necessary ordering is provided as a result of obtaining pointer to the object\!

<a id="rst-case-6-increment-based-rmw-ops-with-acquire-ordering-that-return-a-value"></a>

### case 6) - increment-based RMW ops with acquire ordering that return a value

Function changes:

> - atomic_inc_not_zero() --&gt; refcount_inc_not_zero_acquire()
>
> - no atomic counterpart --&gt; refcount_add_not_zero_acquire()

Memory ordering guarantees changes:

> - fully ordered --&gt; ACQUIRE ordering on success

<a id="rst-case-7-generic-dec-sub-decrement-based-rmw-ops-that-return-a-value"></a>

### case 7) - generic dec/sub decrement-based RMW ops that return a value

Function changes:

> - atomic_dec_and_test() --&gt; refcount_dec_and_test()
>
> - atomic_sub_and_test() --&gt; refcount_sub_and_test()

Memory ordering guarantees changes:

> - fully ordered --&gt; RELEASE ordering + ACQUIRE ordering on success

<a id="rst-case-8-other-decrement-based-rmw-ops-that-return-a-value"></a>

### case 8) other decrement-based RMW ops that return a value

Function changes:

> - no atomic counterpart --&gt; refcount_dec_if_one()
>
> - `atomic_add_unless(&var, -1, 1)` --&gt; `refcount_dec_not_one(&var)`

Memory ordering guarantees changes:

> - fully ordered --&gt; RELEASE ordering + control dependency

> [!NOTE]
>
> atomic_add_unless() only provides full order on success.

<a id="rst-case-9-lock-based-rmw"></a>

### case 9) - lock-based RMW

Function changes:

> - atomic_dec_and_lock() --&gt; refcount_dec_and_lock()
>
> - atomic_dec_and_mutex_lock() --&gt; refcount_dec_and_mutex_lock()

Memory ordering guarantees changes:

> - fully ordered --&gt; RELEASE ordering + control dependency + hold spin_lock() on success

---

# DMA and swiotlb

_Peios Kernel / Internals / Core APIs_

> swiotlb is a memory buffer allocator used by the Linux kernel DMA layer. It is typically used when a device doing DMA can't directly access the target memory buffer because of hardware limitations or other requirements. In such a case, the…

<a id="rst-dma-and-swiotlb"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

swiotlb is a memory buffer allocator used by the Linux kernel DMA layer. It is typically used when a device doing DMA can't directly access the target memory buffer because of hardware limitations or other requirements. In such a case, the DMA layer calls swiotlb to allocate a temporary memory buffer that conforms to the limitations. The DMA is done to/from this temporary memory buffer, and the CPU copies the data between the temporary buffer and the original target memory buffer. This approach is generically called "bounce buffering", and the temporary memory buffer is called a "bounce buffer".

Device drivers don't interact directly with swiotlb. Instead, drivers inform the DMA layer of the DMA attributes of the devices they are managing, and use the normal DMA map, unmap, and sync APIs when programming a device to do DMA. These APIs use the device DMA attributes and kernel-wide settings to determine if bounce buffering is necessary. If so, the DMA layer manages the allocation, freeing, and sync'ing of bounce buffers. Since the DMA attributes are per device, some devices in a system may use bounce buffering while others do not.

Because the CPU copies data between the bounce buffer and the original target memory buffer, doing bounce buffering is slower than doing DMA directly to the original memory buffer, and it consumes more CPU resources. So it is used only when necessary for providing DMA functionality.

<a id="rst-usage-scenarios"></a>

## Usage Scenarios

swiotlb was originally created to handle DMA for devices with addressing limitations. As physical memory sizes grew beyond 4 GiB, some devices could only provide 32-bit DMA addresses. By allocating bounce buffer memory below the 4 GiB line, these devices with addressing limitations could still work and do DMA.

More recently, Confidential Computing (CoCo) VMs have the guest VM's memory encrypted by default, and the memory is not accessible by the host hypervisor and VMM. For the host to do I/O on behalf of the guest, the I/O must be directed to guest memory that is unencrypted. CoCo VMs set a kernel-wide option to force all DMA I/O to use bounce buffers, and the bounce buffer memory is set up as unencrypted. The host does DMA I/O to/from the bounce buffer memory, and the Linux kernel DMA layer does "sync" operations to cause the CPU to copy the data to/from the original target memory buffer. The CPU copying bridges between the unencrypted and the encrypted memory. This use of bounce buffers allows device drivers to "just work" in a CoCo VM, with no modifications needed to handle the memory encryption complexity.

Other edge case scenarios arise for bounce buffers. For example, when IOMMU mappings are set up for a DMA operation to/from a device that is considered "untrusted", the device should be given access only to the memory containing the data being transferred. But if that memory occupies only part of an IOMMU granule, other parts of the granule may contain unrelated kernel data. Since IOMMU access control is per-granule, the untrusted device can gain access to the unrelated kernel data. This problem is solved by bounce buffering the DMA operation and ensuring that unused portions of the bounce buffers do not contain any unrelated kernel data.

<a id="rst-core-functionality"></a>

## Core Functionality

The primary swiotlb APIs are swiotlb_tbl_map_single() and swiotlb_tbl_unmap_single(). The "map" API allocates a bounce buffer of a specified size in bytes and returns the physical address of the buffer. The buffer memory is physically contiguous. The expectation is that the DMA layer maps the physical memory address to a DMA address, and returns the DMA address to the driver for programming into the device. If a DMA operation specifies multiple memory buffer segments, a separate bounce buffer must be allocated for each segment. swiotlb_tbl_map_single() always does a "sync" operation (i.e., a CPU copy) to initialize the bounce buffer to match the contents of the original buffer.

swiotlb_tbl_unmap_single() does the reverse. If the DMA operation might have updated the bounce buffer memory and DMA_ATTR_SKIP_CPU_SYNC is not set, the unmap does a "sync" operation to cause a CPU copy of the data from the bounce buffer back to the original buffer. Then the bounce buffer memory is freed.

swiotlb also provides "sync" APIs that correspond to the dma_sync\_\*() APIs that a driver may use when control of a buffer transitions between the CPU and the device. The swiotlb "sync" APIs cause a CPU copy of the data between the original buffer and the bounce buffer. Like the dma_sync\_\*() APIs, the swiotlb "sync" APIs support doing a partial sync, where only a subset of the bounce buffer is copied to/from the original buffer.

<a id="rst-core-functionality-constraints"></a>

## Core Functionality Constraints

The swiotlb map/unmap/sync APIs must operate without blocking, as they are called by the corresponding DMA APIs which may run in contexts that cannot block. Hence the default memory pool for swiotlb allocations must be pre-allocated at boot time (but see Dynamic swiotlb below). Because swiotlb allocations must be physically contiguous, the entire default memory pool is allocated as a single contiguous block.

The need to pre-allocate the default swiotlb pool creates a boot-time tradeoff. The pool should be large enough to ensure that bounce buffer requests can always be satisfied, as the non-blocking requirement means requests can't wait for space to become available. But a large pool potentially wastes memory, as this pre-allocated memory is not available for other uses in the system. The tradeoff is particularly acute in CoCo VMs that use bounce buffers for all DMA I/O. These VMs use a heuristic to set the default pool size to \~6% of memory, with a max of 1 GiB, which has the potential to be very wasteful of memory. Conversely, the heuristic might produce a size that is insufficient, depending on the I/O patterns of the workload in the VM. The dynamic swiotlb feature described below can help, but has limitations. Better management of the swiotlb default memory pool size remains an open issue.

A single allocation from swiotlb is limited to IO_TLB_SIZE \* IO_TLB_SEGSIZE bytes, which is 256 KiB with current definitions. When a device's DMA settings are such that the device might use swiotlb, the maximum size of a DMA segment must be limited to that 256 KiB. This value is communicated to higher-level kernel code via dma_map_mapping_size() and swiotlb_max_mapping_size(). If the higher-level code fails to account for this limit, it may make requests that are too large for swiotlb, and get a "swiotlb full" error.

A key device DMA setting is "min_align_mask", which is a power of 2 minus 1 so that some number of low order bits are set, or it may be zero. swiotlb allocations ensure these min_align_mask bits of the physical address of the bounce buffer match the same bits in the address of the original buffer. When min_align_mask is non-zero, it may produce an "alignment offset" in the address of the bounce buffer that slightly reduces the maximum size of an allocation. This potential alignment offset is reflected in the value returned by swiotlb_max_mapping_size(), which can show up in places like /sys/block/&lt;device&gt;/queue/max_sectors_kb. For example, if a device does not use swiotlb, max_sectors_kb might be 512 KiB or larger. If a device might use swiotlb, max_sectors_kb will be 256 KiB. When min_align_mask is non-zero, max_sectors_kb might be even smaller, such as 252 KiB.

swiotlb_tbl_map_single() also takes an "alloc_align_mask" parameter. This parameter specifies the allocation of bounce buffer space must start at a physical address with the alloc_align_mask bits set to zero. But the actual bounce buffer might start at a larger address if min_align_mask is non-zero. Hence there may be pre-padding space that is allocated prior to the start of the bounce buffer. Similarly, the end of the bounce buffer is rounded up to an alloc_align_mask boundary, potentially resulting in post-padding space. Any pre-padding or post-padding space is not initialized by swiotlb code. The "alloc_align_mask" parameter is used by IOMMU code when mapping for untrusted devices. It is set to the granule size - 1 so that the bounce buffer is allocated entirely from granules that are not used for any other purpose.

<a id="rst-data-structures-concepts"></a>

## Data structures concepts

Memory used for swiotlb bounce buffers is allocated from overall system memory as one or more "pools". The default pool is allocated during system boot with a default size of 64 MiB. The default pool size may be modified with the "swiotlb=" kernel boot line parameter. The default size may also be adjusted due to other conditions, such as running in a CoCo VM, as described above. If CONFIG_SWIOTLB_DYNAMIC is enabled, additional pools may be allocated later in the life of the system. Each pool must be a contiguous range of physical memory. The default pool is allocated below the 4 GiB physical address line so it works for devices that can only address 32-bits of physical memory (unless architecture-specific code provides the SWIOTLB_ANY flag). In a CoCo VM, the pool memory must be decrypted before swiotlb is used.

Each pool is divided into "slots" of size IO_TLB_SIZE, which is 2 KiB with current definitions. IO_TLB_SEGSIZE contiguous slots (128 slots) constitute what might be called a "slot set". When a bounce buffer is allocated, it occupies one or more contiguous slots. A slot is never shared by multiple bounce buffers. Furthermore, a bounce buffer must be allocated from a single slot set, which leads to the maximum bounce buffer size being IO_TLB_SIZE \* IO_TLB_SEGSIZE. Multiple smaller bounce buffers may co-exist in a single slot set if the alignment and size constraints can be met.

Slots are also grouped into "areas", with the constraint that a slot set exists entirely in a single area. Each area has its own spin lock that must be held to manipulate the slots in that area. The division into areas avoids contending for a single global spin lock when swiotlb is heavily used, such as in a CoCo VM. The number of areas defaults to the number of CPUs in the system for maximum parallelism, but since an area can't be smaller than IO_TLB_SEGSIZE slots, it might be necessary to assign multiple CPUs to the same area. The number of areas can also be set via the "swiotlb=" kernel boot parameter.

When allocating a bounce buffer, if the area associated with the calling CPU does not have enough free space, areas associated with other CPUs are tried sequentially. For each area tried, the area's spin lock must be obtained before trying an allocation, so contention may occur if swiotlb is relatively busy overall. But an allocation request does not fail unless all areas do not have enough free space.

IO_TLB_SIZE, IO_TLB_SEGSIZE, and the number of areas must all be powers of 2 as the code uses shifting and bit masking to do many of the calculations. The number of areas is rounded up to a power of 2 if necessary to meet this requirement.

The default pool is allocated with PAGE_SIZE alignment. If an alloc_align_mask argument to swiotlb_tbl_map_single() specifies a larger alignment, one or more initial slots in each slot set might not meet the alloc_align_mask criterium. Because a bounce buffer allocation can't cross a slot set boundary, eliminating those initial slots effectively reduces the max size of a bounce buffer. Currently, there's no problem because alloc_align_mask is set based on IOMMU granule size, and granules cannot be larger than PAGE_SIZE. But if that were to change in the future, the initial pool allocation might need to be done with alignment larger than PAGE_SIZE.

<a id="rst-dynamic-swiotlb"></a>

## Dynamic swiotlb

When CONFIG_SWIOTLB_DYNAMIC is enabled, swiotlb can do on-demand expansion of the amount of memory available for allocation as bounce buffers. If a bounce buffer request fails due to lack of available space, an asynchronous background task is kicked off to allocate memory from general system memory and turn it into an swiotlb pool. Creating an additional pool must be done asynchronously because the memory allocation may block, and as noted above, swiotlb requests are not allowed to block. Once the background task is kicked off, the bounce buffer request creates a "transient pool" to avoid returning an "swiotlb full" error. A transient pool has the size of the bounce buffer request, and is deleted when the bounce buffer is freed. Memory for this transient pool comes from the general system memory atomic pool so that creation does not block. Creating a transient pool has relatively high cost, particularly in a CoCo VM where the memory must be decrypted, so it is done only as a stopgap until the background task can add another non-transient pool.

Adding a dynamic pool has limitations. Like with the default pool, the memory must be physically contiguous, so the size is limited to MAX_PAGE_ORDER pages (e.g., 4 MiB on a typical x86 system). Due to memory fragmentation, a max size allocation may not be available. The dynamic pool allocator tries smaller sizes until it succeeds, but with a minimum size of 1 MiB. Given sufficient system memory fragmentation, dynamically adding a pool might not succeed at all.

The number of areas in a dynamic pool may be different from the number of areas in the default pool. Because the new pool size is typically a few MiB at most, the number of areas will likely be smaller. For example, with a new pool size of 4 MiB and the 256 KiB minimum area size, only 16 areas can be created. If the system has more than 16 CPUs, multiple CPUs must share an area, creating more lock contention.

New pools added via dynamic swiotlb are linked together in a linear list. swiotlb code frequently must search for the pool containing a particular swiotlb physical address, so that search is linear and not performant with a large number of dynamic pools. The data structures could be improved for faster searches.

Overall, dynamic swiotlb works best for small configurations with relatively few CPUs. It allows the default swiotlb pool to be smaller so that memory is not wasted, with dynamic pools making more space available if needed (as long as fragmentation isn't an obstacle). It is less useful for large CoCo VMs.

<a id="rst-data-structure-details"></a>

## Data Structure Details

swiotlb is managed with four primary data structures: io_tlb_mem, io_tlb_pool, io_tlb_area, and io_tlb_slot. io_tlb_mem describes a swiotlb memory allocator, which includes the default memory pool and any dynamic or transient pools linked to it. Limited statistics on swiotlb usage are kept per memory allocator and are stored in this data structure. These statistics are available under /sys/kernel/debug/swiotlb when CONFIG_DEBUG_FS is set.

io_tlb_pool describes a memory pool, either the default pool, a dynamic pool, or a transient pool. The description includes the start and end addresses of the memory in the pool, a pointer to an array of io_tlb_area structures, and a pointer to an array of io_tlb_slot structures that are associated with the pool.

io_tlb_area describes an area. The primary field is the spin lock used to serialize access to slots in the area. The io_tlb_area array for a pool has an entry for each area, and is accessed using a 0-based area index derived from the calling processor ID. Areas exist solely to allow parallel access to swiotlb from multiple CPUs.

io_tlb_slot describes an individual memory slot in the pool, with size IO_TLB_SIZE (2 KiB currently). The io_tlb_slot array is indexed by the slot index computed from the bounce buffer address relative to the starting memory address of the pool. The size of struct io_tlb_slot is 24 bytes, so the overhead is about 1% of the slot size.

The io_tlb_slot array is designed to meet several requirements. First, the DMA APIs and the corresponding swiotlb APIs use the bounce buffer address as the identifier for a bounce buffer. This address is returned by swiotlb_tbl_map_single(), and then passed as an argument to swiotlb_tbl_unmap_single() and the swiotlb_sync\_\*() functions.  The original memory buffer address obviously must be passed as an argument to swiotlb_tbl_map_single(), but it is not passed to the other APIs. Consequently, swiotlb data structures must save the original memory buffer address so that it can be used when doing sync operations. This original address is saved in the io_tlb_slot array.

Second, the io_tlb_slot array must handle partial sync requests. In such cases, the argument to swiotlb_sync\_\*() is not the address of the start of the bounce buffer but an address somewhere in the middle of the bounce buffer, and the address of the start of the bounce buffer isn't known to swiotlb code. But swiotlb code must be able to calculate the corresponding original memory buffer address to do the CPU copy dictated by the "sync". So an adjusted original memory buffer address is populated into the struct io_tlb_slot for each slot occupied by the bounce buffer. An adjusted "alloc_size" of the bounce buffer is also recorded in each struct io_tlb_slot so a sanity check can be performed on the size of the "sync" operation. The "alloc_size" field is not used except for the sanity check.

Third, the io_tlb_slot array is used to track available slots. The "list" field in struct io_tlb_slot records how many contiguous available slots exist starting at that slot. A "0" indicates that the slot is occupied. A value of "1" indicates only the current slot is available. A value of "2" indicates the current slot and the next slot are available, etc. The maximum value is IO_TLB_SEGSIZE, which can appear in the first slot in a slot set, and indicates that the entire slot set is available. These values are used when searching for available slots to use for a new bounce buffer. They are updated when allocating a new bounce buffer and when freeing a bounce buffer. At pool creation time, the "list" field is initialized to IO_TLB_SEGSIZE down to 1 for the slots in every slot set.

Fourth, the io_tlb_slot array keeps track of any "padding slots" allocated to meet alloc_align_mask requirements described above. When swiotlb_tbl_map_single() allocates bounce buffer space to meet alloc_align_mask requirements, it may allocate pre-padding space across zero or more slots. But when swiotlb_tbl_unmap_single() is called with the bounce buffer address, the alloc_align_mask value that governed the allocation, and therefore the allocation of any padding slots, is not known. The "pad_slots" field records the number of padding slots so that swiotlb_tbl_unmap_single() can free them. The "pad_slots" value is recorded only in the first non-padding slot allocated to the bounce buffer.

<a id="rst-restricted-pools"></a>

## Restricted pools

The swiotlb machinery is also used for "restricted pools", which are pools of memory separate from the default swiotlb pool, and that are dedicated for DMA use by a particular device. Restricted pools provide a level of DMA memory protection on systems with limited hardware protection capabilities, such as those lacking an IOMMU. Such usage is specified by DeviceTree entries and requires that CONFIG_DMA_RESTRICTED_POOL is set. Each restricted pool is based on its own io_tlb_mem data structure that is independent of the main swiotlb io_tlb_mem.

Restricted pools add swiotlb_alloc() and swiotlb_free() APIs, which are called from the dma_alloc\_\*() and dma_free\_\*() APIs. The swiotlb_alloc/free() APIs allocate/free slots from/to the restricted pool directly and do not go through swiotlb_tbl_map/unmap_single().

---

# Symbol Namespaces

_Peios Kernel / Internals / Core APIs_

> The following document describes how to use Symbol Namespaces to structure the export surface of in-kernel symbols exported through the family of EXPORT_SYMBOL() macros.

<a id="rst-symbol-namespaces"></a>

The following document describes how to use Symbol Namespaces to structure the export surface of in-kernel symbols exported through the family of EXPORT_SYMBOL() macros.

<a id="rst-introduction"></a>

## Introduction

Symbol Namespaces have been introduced as a means to structure the export surface of the in-kernel API. It allows subsystem maintainers to partition their exported symbols into separate namespaces. That is useful for documentation purposes (think of the SUBSYSTEM_DEBUG namespace) as well as for limiting the availability of a set of symbols for use in other parts of the kernel. As of today, modules that make use of symbols exported into namespaces, are required to import the namespace. Otherwise the kernel will, depending on its configuration, reject loading the module or warn about a missing import.

Additionally, it is possible to put symbols into a module namespace, strictly limiting which modules are allowed to use these symbols.

<a id="rst-how-to-define-symbol-namespaces"></a>

## How to define Symbol Namespaces

Symbols can be exported into namespace using different methods. All of them are changing the way EXPORT_SYMBOL and friends are instrumented to create ksymtab entries.

<a id="rst-using-the-export-symbol-macros"></a>

### Using the EXPORT_SYMBOL macros

In addition to the macros EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL(), that allow exporting of kernel symbols to the kernel symbol table, variants of these are available to export symbols into a certain namespace: EXPORT_SYMBOL_NS() and EXPORT_SYMBOL_NS_GPL(). They take one additional argument: the namespace as a string constant. Note that this string must not contain whitespaces. E.g. to export the symbol `usb_stor_suspend` into the namespace `USB_STORAGE`, use:



```text
EXPORT_SYMBOL_NS(usb_stor_suspend, "USB_STORAGE");
```

The corresponding ksymtab entry struct `kernel_symbol` will have the member `namespace` set accordingly. A symbol that is exported without a namespace will refer to `NULL`. There is no default namespace if none is defined. `modpost` and kernel/module/main.c make use the namespace at build time or module load time, respectively.

<a id="rst-using-the-default-symbol-namespace-define"></a>

### Using the DEFAULT_SYMBOL_NAMESPACE define

Defining namespaces for all symbols of a subsystem can be very verbose and may become hard to maintain. Therefore a default define (DEFAULT_SYMBOL_NAMESPACE) is been provided, that, if set, will become the default for all EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL() macro expansions that do not specify a namespace.

There are multiple ways of specifying this define and it depends on the subsystem and the maintainer's preference, which one to use. The first option is to define the default namespace in the `Makefile` of the subsystem. E.g. to export all symbols defined in usb-common into the namespace USB_COMMON, add a line like this to drivers/usb/common/Makefile:



```text
ccflags-y += -DDEFAULT_SYMBOL_NAMESPACE='"USB_COMMON"'
```

That will affect all EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL() statements. A symbol exported with EXPORT_SYMBOL_NS() while this definition is present, will still be exported into the namespace that is passed as the namespace argument as this argument has preference over a default symbol namespace.

A second option to define the default namespace is directly in the compilation unit as preprocessor statement. The above example would then read:



```text
#define DEFAULT_SYMBOL_NAMESPACE "USB_COMMON"
```

within the corresponding compilation unit before the \#include for &lt;linux/export.h&gt;. Typically it's placed before the first \#include statement.

<a id="rst-using-the-export-symbol-for-modules-macro"></a>

### Using the EXPORT_SYMBOL_FOR_MODULES() macro

Symbols exported using this macro are put into a module namespace. This namespace cannot be imported. These exports are GPL-only as they are only intended for in-tree modules.

The macro takes a comma separated list of module names, allowing only those modules to access this symbol. Simple tail-globs are supported.

For example:



```text
EXPORT_SYMBOL_FOR_MODULES(preempt_notifier_inc, "kvm,kvm-*")
```

will limit usage of this symbol to modules whose name matches the given patterns.

<a id="rst-how-to-use-symbols-exported-in-namespaces"></a>

## How to use Symbols exported in Namespaces

In order to use symbols that are exported into namespaces, kernel modules need to explicitly import these namespaces. Otherwise the kernel might reject to load the module. The module code is required to use the macro MODULE_IMPORT_NS for the namespaces it uses symbols from. E.g. a module using the usb_stor_suspend symbol from above, needs to import the namespace USB_STORAGE using a statement like:



```text
MODULE_IMPORT_NS("USB_STORAGE");
```

This will create a `modinfo` tag in the module for each imported namespace. This has the side effect, that the imported namespaces of a module can be inspected with modinfo:



```text
$ modinfo drivers/usb/storage/ums-karma.ko
[...]
import_ns:      USB_STORAGE
[...]
```

It is advisable to add the MODULE_IMPORT_NS() statement close to other module metadata definitions like MODULE_AUTHOR() or MODULE_LICENSE().

<a id="rst-loading-modules-that-use-namespaced-symbols"></a>

## Loading Modules that use namespaced Symbols

At module loading time (e.g. `insmod`), the kernel will check each symbol referenced from the module for its availability and whether the namespace it might be exported to has been imported by the module. The default behaviour of the kernel is to reject loading modules that don't specify sufficient imports. An error will be logged and loading will be failed with EINVAL. In order to allow loading of modules that don't satisfy this precondition, a configuration option is available: Setting MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS=y will enable loading regardless, but will emit a warning.

<a id="rst-automatically-creating-module-import-ns-statements"></a>

## Automatically creating MODULE_IMPORT_NS statements

Missing namespaces imports can easily be detected at build time. In fact, modpost will emit a warning if a module uses a symbol from a namespace without importing it. MODULE_IMPORT_NS() statements will usually be added at a definite location (along with other module meta data). To make the life of module authors (and subsystem maintainers) easier, a script and make target is available to fixup missing imports. Fixing missing imports can be done with:



```text
$ make nsdeps
```

A typical scenario for module authors would be:



```text
- write code that depends on a symbol from a not imported namespace
- ``make``
- notice the warning of modpost telling about a missing import
- run ``make nsdeps`` to add the import to the correct code location
```

For subsystem maintainers introducing a namespace, the steps are very similar. Again, `make nsdeps` will eventually add the missing namespace imports for in-tree modules:



```text
- move or add symbols to a namespace (e.g. with EXPORT_SYMBOL_NS())
- ``make`` (preferably with an allmodconfig to cover all in-kernel
  modules)
- notice the warning of modpost telling about a missing import
- run ``make nsdeps`` to add the import to the correct code location
```

You can also run nsdeps for external module builds. A typical usage is:



```text
$ make -C <path_to_kernel_src> M=$PWD nsdeps
```

Note: it will happily generate an import statement for the module namespace; which will not work and generates build and runtime failures.

---

# this_cpu operations

_Peios Kernel / Internals / Core APIs_

> this_cpu operations are a way of optimizing access to per cpu variables associated with the currently executing processor. This is done through the use of segment registers (or a dedicated register where the cpu permanently stored the…

<a id="rst-this-cpu-operations"></a>

**Author:** Christoph Lameter, August 4th, 2014

**Author:** Pranith Kumar, Aug 2nd, 2014

this_cpu operations are a way of optimizing access to per cpu variables associated with the *currently* executing processor. This is done through the use of segment registers (or a dedicated register where the cpu permanently stored the beginning of the per cpu area for a specific processor).

this_cpu operations add a per cpu variable offset to the processor specific per cpu base and encode that operation in the instruction operating on the per cpu variable.

This means that there are no atomicity issues between the calculation of the offset and the operation on the data. Therefore it is not necessary to disable preemption or interrupts to ensure that the processor is not changed between the calculation of the address and the operation on the data.

Read-modify-write operations are of particular interest. Frequently processors have special lower latency instructions that can operate without the typical synchronization overhead, but still provide some sort of relaxed atomicity guarantees. The x86, for example, can execute RMW (Read Modify Write) instructions like inc/dec/cmpxchg without the lock prefix and the associated latency penalty.

Access to the variable without the lock prefix is not synchronized but synchronization is not necessary since we are dealing with per cpu data specific to the currently executing processor. Only the current processor should be accessing that variable and therefore there are no concurrency issues with other processors in the system.

Please note that accesses by remote processors to a per cpu area are exceptional situations and may impact performance and/or correctness (remote write operations) of local RMW operations via this_cpu\_\*.

The main use of the this_cpu operations has been to optimize counter operations.

The following this_cpu() operations with implied preemption protection are defined. These operations can be used without worrying about preemption and interrupts:



```text
this_cpu_read(pcp)
this_cpu_write(pcp, val)
this_cpu_add(pcp, val)
this_cpu_and(pcp, val)
this_cpu_or(pcp, val)
this_cpu_add_return(pcp, val)
this_cpu_xchg(pcp, nval)
this_cpu_cmpxchg(pcp, oval, nval)
this_cpu_sub(pcp, val)
this_cpu_inc(pcp)
this_cpu_dec(pcp)
this_cpu_sub_return(pcp, val)
this_cpu_inc_return(pcp)
this_cpu_dec_return(pcp)
```

<a id="rst-inner-working-of-this-cpu-operations"></a>

## Inner working of this_cpu operations

On x86 the fs: or the gs: segment registers contain the base of the per cpu area. It is then possible to simply use the segment override to relocate a per cpu relative address to the proper per cpu area for the processor. So the relocation to the per cpu base is encoded in the instruction via a segment register prefix.

For example:



```text
DEFINE_PER_CPU(int, x);
int z;

z = this_cpu_read(x);
```

results in a single instruction:



```text
mov ax, gs:[x]
```

instead of a sequence of calculation of the address and then a fetch from that address which occurs with the per cpu operations. Before this_cpu_ops such sequence also required preempt disable/enable to prevent the kernel from moving the thread to a different processor while the calculation is performed.

Consider the following this_cpu operation:



```text
this_cpu_inc(x)
```

The above results in the following single instruction (no lock prefix\!):



```text
inc gs:[x]
```

instead of the following operations required if there is no segment register:



```text
int *y;
int cpu;

cpu = get_cpu();
y = per_cpu_ptr(&x, cpu);
(*y)++;
put_cpu();
```

Note that these operations can only be used on per cpu data that is reserved for a specific processor. Without disabling preemption in the surrounding code this_cpu_inc() will only guarantee that one of the per cpu counters is correctly incremented. However, there is no guarantee that the OS will not move the process directly before or after the this_cpu instruction is executed. In general this means that the value of the individual counters for each processor are meaningless. The sum of all the per cpu counters is the only value that is of interest.

Per cpu variables are used for performance reasons. Bouncing cache lines can be avoided if multiple processors concurrently go through the same code paths.  Since each processor has its own per cpu variables no concurrent cache line updates take place. The price that has to be paid for this optimization is the need to add up the per cpu counters when the value of a counter is needed.

<a id="rst-special-operations"></a>

## Special operations



```text
y = this_cpu_ptr(&x)
```

Takes the offset of a per cpu variable (&amp;x \!) and returns the address of the per cpu variable that belongs to the currently executing processor.  this_cpu_ptr avoids multiple steps that the common get_cpu/put_cpu sequence requires. No processor number is available. Instead, the offset of the local per cpu area is simply added to the per cpu offset.

Note that this operation can only be used in code segments where smp_processor_id() may be used, for example, where preemption has been disabled. The pointer is then used to access local per cpu data in a critical section. When preemption is re-enabled this pointer is usually no longer useful since it may no longer point to per cpu data of the current processor.

The special cases where it makes sense to obtain a per-CPU pointer in preemptible code are addressed by raw_cpu_ptr(), but such use cases need to handle cases where two different CPUs are accessing the same per cpu variable, which might well be that of a third CPU.  These use cases are typically performance optimizations.  For example, SRCU implements a pair of counters as a pair of per-CPU variables, and rcu_read_lock_nmisafe() uses raw_cpu_ptr() to get a pointer to some CPU's counter, and uses atomic_inc_long() to handle migration between the raw_cpu_ptr() and the atomic_inc_long().

<a id="rst-per-cpu-variables-and-offsets"></a>

## Per cpu variables and offsets

Per cpu variables have *offsets* to the beginning of the per cpu area. They do not have addresses although they look like that in the code. Offsets cannot be directly dereferenced. The offset must be added to a base pointer of a per cpu area of a processor in order to form a valid address.

Therefore the use of x or &amp;x outside of the context of per cpu operations is invalid and will generally be treated like a NULL pointer dereference.



```text
DEFINE_PER_CPU(int, x);
```

In the context of per cpu operations the above implies that x is a per cpu variable. Most this_cpu operations take a cpu variable.



```text
int __percpu *p = &x;
```

&amp;x and hence p is the *offset* of a per cpu variable. this_cpu_ptr() takes the offset of a per cpu variable which makes this look a bit strange.

<a id="rst-operations-on-a-field-of-a-per-cpu-structure"></a>

## Operations on a field of a per cpu structure

Let's say we have a percpu structure:



```text
struct s {
        int n,m;
};

DEFINE_PER_CPU(struct s, p);
```

Operations on these fields are straightforward:



```text
this_cpu_inc(p.m)

z = this_cpu_cmpxchg(p.m, 0, 1);
```

If we have an offset to struct s:



```text
struct s __percpu *ps = &p;

this_cpu_dec(ps->m);

z = this_cpu_inc_return(ps->n);
```

The calculation of the pointer may require the use of this_cpu_ptr() if we do not make use of this_cpu ops later to manipulate fields:



```text
struct s *pp;

pp = this_cpu_ptr(&p);

pp->m--;

z = pp->n++;
```

<a id="rst-variants-of-this-cpu-ops"></a>

## Variants of this_cpu ops

this_cpu ops are interrupt safe. Some architectures do not support these per cpu local operations. In that case the operation must be replaced by code that disables interrupts, then does the operations that are guaranteed to be atomic and then re-enable interrupts. Doing so is expensive. If there are other reasons why the scheduler cannot change the processor we are executing on then there is no reason to disable interrupts. For that purpose the following \__this_cpu operations are provided.

These operations have no guarantee against concurrent interrupts or preemption. If a per cpu variable is not used in an interrupt context and the scheduler cannot preempt, then they are safe. If any interrupts still occur while an operation is in progress and if the interrupt too modifies the variable, then RMW actions can not be guaranteed to be safe:



```text
__this_cpu_read(pcp)
__this_cpu_write(pcp, val)
__this_cpu_add(pcp, val)
__this_cpu_and(pcp, val)
__this_cpu_or(pcp, val)
__this_cpu_add_return(pcp, val)
__this_cpu_xchg(pcp, nval)
__this_cpu_cmpxchg(pcp, oval, nval)
__this_cpu_sub(pcp, val)
__this_cpu_inc(pcp)
__this_cpu_dec(pcp)
__this_cpu_sub_return(pcp, val)
__this_cpu_inc_return(pcp)
__this_cpu_dec_return(pcp)
```

Will increment x and will not fall-back to code that disables interrupts on platforms that cannot accomplish atomicity through address relocation and a Read-Modify-Write operation in the same instruction.

<a id="rst-this-cpu-ptr-pp-n-vs-this-cpu-ptr-pp-n"></a>

## &amp;this_cpu_ptr(pp)-&gt;n vs this_cpu_ptr(&amp;pp-&gt;n)

The first operation takes the offset and forms an address and then adds the offset of the n field. This may result in two add instructions emitted by the compiler.

The second one first adds the two offsets and then does the relocation.  IMHO the second form looks cleaner and has an easier time with (). The second form also is consistent with the way this_cpu_read() and friends are used.

<a id="rst-remote-access-to-per-cpu-data"></a>

## Remote access to per cpu data

Per cpu data structures are designed to be used by one cpu exclusively. If you use the variables as intended, this_cpu_ops() are guaranteed to be "atomic" as no other CPU has access to these data structures.

There are special cases where you might need to access per cpu data structures remotely. It is usually safe to do a remote read access and that is frequently done to summarize counters. Remote write access something which could be problematic because this_cpu ops do not have lock semantics. A remote write may interfere with a this_cpu RMW operation.

Remote write accesses to percpu data structures are highly discouraged unless absolutely necessary. Please consider using an IPI to wake up the remote CPU and perform the update to its per cpu area.

To access per-cpu data structure remotely, typically the per_cpu_ptr() function is used:



```text
DEFINE_PER_CPU(struct data, datap);

struct data *p = per_cpu_ptr(&datap, cpu);
```

This makes it explicit that we are getting ready to access a percpu area remotely.

You can also do the following to convert the datap offset to an address:



```text
struct data *p = this_cpu_ptr(&datap);
```

but, passing of pointers calculated via this_cpu_ptr to other cpus is unusual and should be avoided.

Remote access are typically only for reading the status of another cpus per cpu data. Write accesses can cause unique problems due to the relaxed synchronization requirements for this_cpu operations.

One example that illustrates some concerns with write operations is the following scenario that occurs because two per cpu variables share a cache-line but the relaxed synchronization is applied to only one process updating the cache-line.

Consider the following example:



```text
struct test {
        atomic_t a;
        int b;
};

DEFINE_PER_CPU(struct test, onecacheline);
```

There is some concern about what would happen if the field 'a' is updated remotely from one processor and the local processor would use this_cpu ops to update field b. Care should be taken that such simultaneous accesses to data within the same cache line are avoided. Also costly synchronization may be necessary. IPIs are generally recommended in such scenarios instead of a remote write to the per cpu area of another processor.

Even in cases where the remote writes are rare, please bear in mind that a remote write will evict the cache line from the processor that most likely will access it. If the processor wakes up and finds a missing local cache line of a per cpu area, its performance and hence the wake up times will be affected.

---

# ktime accessors

_Peios Kernel / Internals / Core APIs_

> Device drivers can read the current time using ktime_get() and the many related functions declared in linux/timekeeping.h. As a rule of thumb, using an accessor with a shorter name is preferred over one with a longer name if both are…

<a id="rst-ktime-accessors"></a>

Device drivers can read the current time using ktime_get() and the many related functions declared in linux/timekeeping.h. As a rule of thumb, using an accessor with a shorter name is preferred over one with a longer name if both are equally fit for a particular use case.

<a id="rst-basic-ktime-t-based-interfaces"></a>

## Basic ktime_t based interfaces

The recommended simplest form returns an opaque ktime_t, with variants that return time for different clock references:





<a id="c-ktime_get"></a>

```c
ktime_t ktime_get( void )
```

CLOCK_MONOTONIC

Useful for reliable timestamps and measuring short time intervals accurately. Starts at system boot time but stops during suspend.





<a id="c-ktime_get_boottime"></a>

```c
ktime_t ktime_get_boottime( void )
```

CLOCK_BOOTTIME

Like ktime_get(), but does not stop when suspended. This can be used e.g. for key expiration times that need to be synchronized with other machines across a suspend operation.





<a id="c-ktime_get_real"></a>

```c
ktime_t ktime_get_real( void )
```

CLOCK_REALTIME

Returns the time in relative to the UNIX epoch starting in 1970 using the Coordinated Universal Time (UTC), same as gettimeofday() user space. This is used for all timestamps that need to persist across a reboot, like inode times, but should be avoided for internal uses, since it can jump backwards due to a leap second update, NTP adjustment settimeofday() operation from user space.





<a id="c-ktime_get_clocktai"></a>

```c
ktime_t ktime_get_clocktai( void )
```

> CLOCK_TAI

Like ktime_get_real(), but uses the International Atomic Time (TAI) reference instead of UTC to avoid jumping on leap second updates. This is rarely useful in the kernel.





<a id="c-ktime_get_raw"></a>

```c
ktime_t ktime_get_raw( void )
```

CLOCK_MONOTONIC_RAW

Like ktime_get(), but runs at the same rate as the hardware clocksource without (NTP) adjustments for clock drift. This is also rarely needed in the kernel.

<a id="rst-nanosecond-timespec64-and-second-output"></a>

## nanosecond, timespec64, and second output

For all of the above, there are variants that return the time in a different format depending on what is required by the user:





<a id="c-ktime_get_ns"></a>

```c
u64 ktime_get_ns( void )
        u64 ktime_get_boottime_ns( void )
        u64 ktime_get_real_ns( void )
        u64 ktime_get_clocktai_ns( void )
        u64 ktime_get_raw_ns( void )
```

Same as the plain ktime_get functions, but returning a u64 number of nanoseconds in the respective time reference, which may be more convenient for some callers.





<a id="c-ktime_get_ts64"></a>

```c
void ktime_get_ts64( struct timespec64 * )
        void ktime_get_boottime_ts64( struct timespec64 * )
        void ktime_get_real_ts64( struct timespec64 * )
        void ktime_get_clocktai_ts64( struct timespec64 * )
        void ktime_get_raw_ts64( struct timespec64 * )
```

Same above, but returns the time in a 'struct timespec64', split into seconds and nanoseconds. This can avoid an extra division when printing the time, or when passing it into an external interface that expects a 'timespec' or 'timeval' structure.





<a id="c-ktime_get_seconds"></a>

```c
time64_t ktime_get_seconds( void )
        time64_t ktime_get_boottime_seconds( void )
        time64_t ktime_get_real_seconds( void )
        time64_t ktime_get_clocktai_seconds( void )
        time64_t ktime_get_raw_seconds( void )
```

Return a coarse-grained version of the time as a scalar time64_t. This avoids accessing the clock hardware and rounds down the seconds to the full seconds of the last timer tick using the respective reference.

<a id="rst-coarse-and-fast-ns-access"></a>

## Coarse and fast_ns access

Some additional variants exist for more specialized cases:





<a id="c-ktime_get_coarse"></a>

```c
ktime_t ktime_get_coarse( void )
ktime_t ktime_get_coarse_boottime( void )
ktime_t ktime_get_coarse_real( void )
ktime_t ktime_get_coarse_clocktai( void )
```





<a id="c-ktime_get_coarse_ns"></a>

```c
u64 ktime_get_coarse_ns( void )
u64 ktime_get_coarse_boottime_ns( void )
u64 ktime_get_coarse_real_ns( void )
u64 ktime_get_coarse_clocktai_ns( void )
```





<a id="c-ktime_get_coarse_ts64"></a>

```c
void ktime_get_coarse_ts64( struct timespec64 * )
        void ktime_get_coarse_boottime_ts64( struct timespec64 * )
        void ktime_get_coarse_real_ts64( struct timespec64 * )
        void ktime_get_coarse_clocktai_ts64( struct timespec64 * )
```

These are quicker than the non-coarse versions, but less accurate, corresponding to CLOCK_MONOTONIC_COARSE and CLOCK_REALTIME_COARSE in user space, along with the equivalent boottime/tai/raw timebase not available in user space.

The time returned here corresponds to the last timer tick, which may be as much as 10ms in the past (for CONFIG_HZ=100), same as reading the 'jiffies' variable.  These are only useful when called in a fast path and one still expects better than second accuracy, but can't easily use 'jiffies', e.g. for inode timestamps. Skipping the hardware clock access saves around 100 CPU cycles on most modern machines with a reliable cycle counter, but up to several microseconds on older hardware with an external clocksource.





<a id="c-ktime_get_mono_fast_ns"></a>

```c
u64 ktime_get_mono_fast_ns( void )
        u64 ktime_get_raw_fast_ns( void )
        u64 ktime_get_boot_fast_ns( void )
        u64 ktime_get_tai_fast_ns( void )
        u64 ktime_get_real_fast_ns( void )
```

These variants are safe to call from any context, including from a non-maskable interrupt (NMI) during a timekeeper update, and while we are entering suspend with the clocksource powered down. This is useful in some tracing or debugging code as well as machine check reporting, but most drivers should never call them, since the time is allowed to jump under certain conditions.

<a id="rst-deprecated-time-interfaces"></a>

## Deprecated time interfaces

Older kernels used some other interfaces that are now being phased out but may appear in third-party drivers being ported here. In particular, all interfaces returning a 'struct timeval' or 'struct timespec' have been replaced because the tv_sec member overflows in year 2038 on 32-bit architectures. These are the recommended replacements:





<a id="c-ktime_get_ts"></a>

```c
void ktime_get_ts( struct timespec * )
```

Use ktime_get() or ktime_get_ts64() instead.





<a id="c-do_gettimeofday"></a>

```c
void do_gettimeofday( struct timeval * )
        void getnstimeofday( struct timespec * )
        void getnstimeofday64( struct timespec64 * )
        void ktime_get_real_ts( struct timespec * )
```

ktime_get_real_ts64() is a direct replacement, but consider using monotonic time (ktime_get_ts64()) and/or a ktime_t based interface (ktime_get()/ktime_get_real()).





<a id="c-current_kernel_time"></a>

```c
struct timespec current_kernel_time( void )
        struct timespec64 current_kernel_time64( void )
        struct timespec get_monotonic_coarse( void )
        struct timespec64 get_monotonic_coarse64( void )
```

These are replaced by ktime_get_coarse_real_ts64() and ktime_get_coarse_ts64(). However, A lot of code that wants coarse-grained times can use the simple 'jiffies' instead, while some drivers may actually want the higher resolution accessors these days.





<a id="c-getrawmonotonic"></a>

```c
struct timespec getrawmonotonic( void )
        struct timespec64 getrawmonotonic64( void )
        struct timespec timekeeping_clocktai( void )
        struct timespec64 timekeeping_clocktai64( void )
        struct timespec get_monotonic_boottime( void )
        struct timespec64 get_monotonic_boottime64( void )
```

These are replaced by ktime_get_raw()/ktime_get_raw_ts64(), ktime_get_clocktai()/ktime_get_clocktai_ts64() as well as ktime_get_boottime()/ktime_get_boottime_ts64(). However, if the particular choice of clock source is not important for the user, consider converting to ktime_get()/ktime_get_ts64() instead for consistency.

---

# The Linux Kernel Tracepoint API

_Peios Kernel / Internals / Core APIs_

> Tracepoints are static probe points that are located in strategic points throughout the kernel. 'Probes' register/unregister with tracepoints via a callback mechanism. The 'probes' are strictly typed functions that are passed a unique set…

<a id="rst-the-linux-kernel-tracepoint-api"></a>

**Author:** Jason Baron

**Author:** William Cohen

<a id="rst-introduction"></a>

## Introduction

Tracepoints are static probe points that are located in strategic points throughout the kernel. 'Probes' register/unregister with tracepoints via a callback mechanism. The 'probes' are strictly typed functions that are passed a unique set of parameters defined by each tracepoint.

From this simple callback mechanism, 'probes' can be used to profile, debug, and understand kernel behavior. There are a number of tools that provide a framework for using 'probes'. These tools include Systemtap, ftrace, and LTTng.

Tracepoints are defined in a number of header files via various macros. Thus, the purpose of this document is to provide a clear accounting of the available tracepoints. The intention is to understand not only what tracepoints are available but also to understand where future tracepoints might be added.

The API presented has functions of the form: `trace_tracepointname(function parameters)`. These are the tracepoints callbacks that are found throughout the code. Registering and unregistering probes with these callback sites is covered in the `Documentation/trace/*` directory.

<a id="rst-irq"></a>

## IRQ


#### <a id="c-trace_irq_handler_entry"></a>`trace_irq_handler_entry()`

```c
void trace_irq_handler_entry(int irq, struct irqaction *action)
```

called immediately before the irq action handler

**Parameters**

- `int irq`: irq number
- `struct irqaction *action`: pointer to struct irqaction

**Description**

The struct irqaction pointed to by **action** contains various
information about the handler, including the device name,
**action->name**, and the device id, **action->dev_id**. When used in
conjunction with the irq_handler_exit tracepoint, we can figure
out irq handler latencies.

#### <a id="c-trace_irq_handler_exit"></a>`trace_irq_handler_exit()`

```c
void trace_irq_handler_exit(int irq, struct irqaction *action, int ret)
```

called immediately after the irq action handler returns

**Parameters**

- `int irq`: irq number
- `struct irqaction *action`: pointer to struct irqaction
- `int ret`: return value

**Description**

If the **ret** value is set to IRQ_HANDLED, then we know that the corresponding
**action->handler** successfully handled this irq. Otherwise, the irq might be
a shared irq line, or the irq was not handled successfully. Can be used in
conjunction with the irq_handler_entry to understand irq handler latencies.

#### <a id="c-trace_softirq_entry"></a>`trace_softirq_entry()`

```c
void trace_softirq_entry(unsigned int vec_nr)
```

called immediately before the softirq handler

**Parameters**

- `unsigned int vec_nr`: softirq vector number

**Description**

When used in combination with the softirq_exit tracepoint
we can determine the softirq handler routine.

#### <a id="c-trace_softirq_exit"></a>`trace_softirq_exit()`

```c
void trace_softirq_exit(unsigned int vec_nr)
```

called immediately after the softirq handler returns

**Parameters**

- `unsigned int vec_nr`: softirq vector number

**Description**

When used in combination with the softirq_entry tracepoint
we can determine the softirq handler routine.

#### <a id="c-trace_softirq_raise"></a>`trace_softirq_raise()`

```c
void trace_softirq_raise(unsigned int vec_nr)
```

called immediately when a softirq is raised

**Parameters**

- `unsigned int vec_nr`: softirq vector number

**Description**

When used in combination with the softirq_entry tracepoint
we can determine the softirq raise to run latency.

#### <a id="c-trace_tasklet_entry"></a>`trace_tasklet_entry()`

```c
void trace_tasklet_entry(struct tasklet_struct *t, void *func)
```

called immediately before the tasklet is run

**Parameters**

- `struct tasklet_struct *t`: tasklet pointer
- `void *func`: tasklet callback or function being run

**Description**

Used to find individual tasklet execution time

#### <a id="c-trace_tasklet_exit"></a>`trace_tasklet_exit()`

```c
void trace_tasklet_exit(struct tasklet_struct *t, void *func)
```

called immediately after the tasklet is run

**Parameters**

- `struct tasklet_struct *t`: tasklet pointer
- `void *func`: tasklet callback or function being run

**Description**

Used to find individual tasklet execution time


<a id="rst-signal"></a>

## SIGNAL


#### <a id="c-trace_signal_generate"></a>`trace_signal_generate()`

```c
void trace_signal_generate(int sig, struct kernel_siginfo *info, struct task_struct *task, int group, int result)
```

called when a signal is generated

**Parameters**

- `int sig`: signal number
- `struct kernel_siginfo *info`: pointer to struct siginfo
- `struct task_struct *task`: pointer to struct task_struct
- `int group`: shared or private
- `int result`: TRACE_SIGNAL_*

**Description**

Current process sends a 'sig' signal to 'task' process with
'info' siginfo. If 'info' is SEND_SIG_NOINFO or SEND_SIG_PRIV,
'info' is not a pointer and you can't access its field. Instead,
SEND_SIG_NOINFO means that si_code is SI_USER, and SEND_SIG_PRIV
means that si_code is SI_KERNEL.

#### <a id="c-trace_signal_deliver"></a>`trace_signal_deliver()`

```c
void trace_signal_deliver(int sig, struct kernel_siginfo *info, struct k_sigaction *ka)
```

called when a signal is delivered

**Parameters**

- `int sig`: signal number
- `struct kernel_siginfo *info`: pointer to struct siginfo
- `struct k_sigaction *ka`: pointer to struct k_sigaction

**Description**

A 'sig' signal is delivered to current process with 'info' siginfo,
and it will be handled by 'ka'. ka->sa.sa_handler can be SIG_IGN or
SIG_DFL.
Note that some signals reported by signal_generate tracepoint can be
lost, ignored or modified (by debugger) before hitting this tracepoint.
This means, this can show which signals are actually delivered, but
matching generated signals and delivered signals may not be correct.


<a id="rst-block-io"></a>

## Block IO


#### <a id="c-trace_block_touch_buffer"></a>`trace_block_touch_buffer()`

```c
void trace_block_touch_buffer(struct buffer_head *bh)
```

mark a buffer accessed

**Parameters**

- `struct buffer_head *bh`: buffer_head being touched

**Description**

Called from `touch_buffer()`.

#### <a id="c-trace_block_dirty_buffer"></a>`trace_block_dirty_buffer()`

```c
void trace_block_dirty_buffer(struct buffer_head *bh)
```

mark a buffer dirty

**Parameters**

- `struct buffer_head *bh`: buffer_head being dirtied

**Description**

Called from [`mark_buffer_dirty()`](/kernel/internals/filesystems/buffer.md#c-mark_buffer_dirty).

#### <a id="c-trace_block_rq_requeue"></a>`trace_block_rq_requeue()`

```c
void trace_block_rq_requeue(struct request *rq)
```

place block IO request back on a queue

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

The block operation request **rq** is being placed back into queue
**q**.  For some reason the request was not completed and needs to be
put back in the queue.

#### <a id="c-trace_block_rq_complete"></a>`trace_block_rq_complete()`

```c
void trace_block_rq_complete(struct request *rq, blk_status_t error, unsigned int nr_bytes)
```

block IO operation completed by device driver

**Parameters**

- `struct request *rq`: block operations request
- `blk_status_t error`: status code
- `unsigned int nr_bytes`: number of completed bytes

**Description**

The block_rq_complete tracepoint event indicates that some portion
of operation request has been completed by the device driver.  If
the **rq->bio** is `NULL`, then there is absolutely no additional work to
do for the request. If **rq->bio** is non-NULL then there is
additional work required to complete the request.

#### <a id="c-trace_block_rq_error"></a>`trace_block_rq_error()`

```c
void trace_block_rq_error(struct request *rq, blk_status_t error, unsigned int nr_bytes)
```

block IO operation error reported by device driver

**Parameters**

- `struct request *rq`: block operations request
- `blk_status_t error`: status code
- `unsigned int nr_bytes`: number of completed bytes

**Description**

The block_rq_error tracepoint event indicates that some portion
of operation request has failed as reported by the device driver.

#### <a id="c-trace_block_rq_insert"></a>`trace_block_rq_insert()`

```c
void trace_block_rq_insert(struct request *rq)
```

insert block operation request into queue

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

Called immediately before block operation request **rq** is inserted
into queue **q**.  The fields in the operation request **rq** struct can
be examined to determine which device and sectors the pending
operation would access.

#### <a id="c-trace_block_rq_issue"></a>`trace_block_rq_issue()`

```c
void trace_block_rq_issue(struct request *rq)
```

issue pending block IO request operation to device driver

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

Called when block operation request **rq** from queue **q** is sent to a
device driver for processing.

#### <a id="c-trace_block_rq_merge"></a>`trace_block_rq_merge()`

```c
void trace_block_rq_merge(struct request *rq)
```

merge request with another one in the elevator

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

Called when block operation request **rq** from queue **q** is merged to another
request queued in the elevator.

#### <a id="c-trace_block_io_start"></a>`trace_block_io_start()`

```c
void trace_block_io_start(struct request *rq)
```

insert a request for execution

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

Called when block operation request **rq** is queued for execution

#### <a id="c-trace_block_io_done"></a>`trace_block_io_done()`

```c
void trace_block_io_done(struct request *rq)
```

block IO operation request completed

**Parameters**

- `struct request *rq`: block IO operation request

**Description**

Called when block operation request **rq** is completed

#### <a id="c-trace_block_bio_complete"></a>`trace_block_bio_complete()`

```c
void trace_block_bio_complete(struct request_queue *q, struct bio *bio)
```

completed all work on the block operation

**Parameters**

- `struct request_queue *q`: queue holding the block operation
- `struct bio *bio`: block operation completed

**Description**

This tracepoint indicates there is no further work to do on this
block IO operation **bio**.

#### <a id="c-trace_block_bio_backmerge"></a>`trace_block_bio_backmerge()`

```c
void trace_block_bio_backmerge(struct bio *bio)
```

merging block operation to the end of an existing operation

**Parameters**

- `struct bio *bio`: new block operation to merge

**Description**

Merging block request **bio** to the end of an existing block request.

#### <a id="c-trace_block_bio_frontmerge"></a>`trace_block_bio_frontmerge()`

```c
void trace_block_bio_frontmerge(struct bio *bio)
```

merging block operation to the beginning of an existing operation

**Parameters**

- `struct bio *bio`: new block operation to merge

**Description**

Merging block IO operation **bio** to the beginning of an existing block request.

#### <a id="c-trace_block_bio_queue"></a>`trace_block_bio_queue()`

```c
void trace_block_bio_queue(struct bio *bio)
```

putting new block IO operation in queue

**Parameters**

- `struct bio *bio`: new block operation

**Description**

About to place the block IO operation **bio** into queue **q**.

#### <a id="c-trace_block_getrq"></a>`trace_block_getrq()`

```c
void trace_block_getrq(struct bio *bio)
```

get a free request entry in queue for block IO operations

**Parameters**

- `struct bio *bio`: pending block IO operation (can be `NULL`)

**Description**

A request struct has been allocated to handle the block IO operation **bio**.

#### <a id="c-trace_blk_zone_append_update_request_bio"></a>`trace_blk_zone_append_update_request_bio()`

```c
void trace_blk_zone_append_update_request_bio(struct request *rq)
```

update bio sector after zone append

**Parameters**

- `struct request *rq`: the completed request that sets the bio sector

**Description**

Update the bio's bi_sector after a zone append command has been completed.

#### <a id="c-trace_block_plug"></a>`trace_block_plug()`

```c
void trace_block_plug(struct request_queue *q)
```

keep operations requests in request queue

**Parameters**

- `struct request_queue *q`: request queue to plug

**Description**

Plug the request queue **q**.  Do not allow block operation requests
to be sent to the device driver. Instead, accumulate requests in
the queue to improve throughput performance of the block device.

#### <a id="c-trace_block_unplug"></a>`trace_block_unplug()`

```c
void trace_block_unplug(struct request_queue *q, unsigned int depth, bool explicit)
```

release of operations requests in request queue

**Parameters**

- `struct request_queue *q`: request queue to unplug
- `unsigned int depth`: number of requests just added to the queue
- `bool explicit`: whether this was an explicit unplug, or one from `schedule()`

**Description**

Unplug request queue **q** because device driver is scheduled to work
on elements in the request queue.

#### <a id="c-trace_block_split"></a>`trace_block_split()`

```c
void trace_block_split(struct bio *bio, unsigned int new_sector)
```

split a single bio struct into two bio structs

**Parameters**

- `struct bio *bio`: block operation being split
- `unsigned int new_sector`: The starting sector for the new bio

**Description**

The bio request **bio** needs to be split into two bio requests.  The newly
created **bio** request starts at **new_sector**. This split may be required due to
hardware limitations such as operation crossing device boundaries in a RAID
system.

#### <a id="c-trace_block_bio_remap"></a>`trace_block_bio_remap()`

```c
void trace_block_bio_remap(struct bio *bio, dev_t dev, sector_t from)
```

map request for a logical device to the raw device

**Parameters**

- `struct bio *bio`: revised operation
- `dev_t dev`: original device for the operation
- `sector_t from`: original sector for the operation

**Description**

An operation for a logical device has been mapped to the
raw block device.

#### <a id="c-trace_block_rq_remap"></a>`trace_block_rq_remap()`

```c
void trace_block_rq_remap(struct request *rq, dev_t dev, sector_t from)
```

map request for a block operation request

**Parameters**

- `struct request *rq`: block IO operation request
- `dev_t dev`: device for the operation
- `sector_t from`: original sector for the operation

**Description**

The block operation request **rq** in **q** has been remapped.  The block
operation request **rq** holds the current information and **from** hold
the original sector.

#### <a id="c-trace_blkdev_zone_mgmt"></a>`trace_blkdev_zone_mgmt()`

```c
void trace_blkdev_zone_mgmt(struct bio *bio, sector_t nr_sectors)
```

Execute a zone management operation on a range of zones

**Parameters**

- `struct bio *bio`: The block IO operation sent down to the device
- `sector_t nr_sectors`: The number of sectors affected by this operation

**Description**

Execute a zone management operation on a specified range of zones. This
range is encoded in `nr_sectors`, which has to be a multiple of the zone
size.


<a id="rst-workqueue"></a>

## Workqueue


#### <a id="c-trace_workqueue_queue_work"></a>`trace_workqueue_queue_work()`

```c
void trace_workqueue_queue_work(int req_cpu, struct pool_workqueue *pwq, struct work_struct *work)
```

called when a work gets queued

**Parameters**

- `int req_cpu`: the requested cpu
- `struct pool_workqueue *pwq`: pointer to struct pool_workqueue
- `struct work_struct *work`: pointer to struct work_struct

**Description**

This event occurs when a work is queued immediately or once a
delayed work is actually queued on a workqueue (ie: once the delay
has been reached).

#### <a id="c-trace_workqueue_activate_work"></a>`trace_workqueue_activate_work()`

```c
void trace_workqueue_activate_work(struct work_struct *work)
```

called when a work gets activated

**Parameters**

- `struct work_struct *work`: pointer to struct work_struct

**Description**

This event occurs when a queued work is put on the active queue,
which happens immediately after queueing unless **max_active** limit
is reached.

#### <a id="c-trace_workqueue_execute_start"></a>`trace_workqueue_execute_start()`

```c
void trace_workqueue_execute_start(struct work_struct *work)
```

called immediately before the workqueue callback

**Parameters**

- `struct work_struct *work`: pointer to struct work_struct

**Description**

Allows to track workqueue execution.

#### <a id="c-trace_workqueue_execute_end"></a>`trace_workqueue_execute_end()`

```c
void trace_workqueue_execute_end(struct work_struct *work, work_func_t function)
```

called immediately after the workqueue callback

**Parameters**

- `struct work_struct *work`: pointer to struct work_struct
- `work_func_t function`: pointer to worker function

**Description**

Allows to track workqueue execution.

---

# Unaligned Memory Accesses

_Peios Kernel / Internals / Core APIs_

> Linux runs on a wide variety of architectures which have varying behaviour when it comes to memory access. This document presents some details about unaligned accesses, why you need to write code that doesn't cause them, and how to write…

<a id="rst-unaligned-memory-accesses"></a>

**Author:** Daniel Drake &lt;[dsd@gentoo.org](<mailto:dsd@gentoo.org>)&gt;,

**Author:** Johannes Berg &lt;[johannes@sipsolutions.net](<mailto:johannes@sipsolutions.net>)&gt;

**With help from:** Alan Cox, Avuton Olrich, Heikki Orsila, Jan Engelhardt, Kyle McMartin, Kyle Moffett, Randy Dunlap, Robert Hancock, Uli Kunitz, Vadim Lobanov

Linux runs on a wide variety of architectures which have varying behaviour when it comes to memory access. This document presents some details about unaligned accesses, why you need to write code that doesn't cause them, and how to write such code\!

<a id="rst-the-definition-of-an-unaligned-access"></a>

## The definition of an unaligned access

Unaligned memory accesses occur when you try to read N bytes of data starting from an address that is not evenly divisible by N (i.e. addr % N \!= 0). For example, reading 4 bytes of data from address 0x10004 is fine, but reading 4 bytes of data from address 0x10005 would be an unaligned memory access.

The above may seem a little vague, as memory access can happen in different ways. The context here is at the machine code level: certain instructions read or write a number of bytes to or from memory (e.g. movb, movw, movl in x86 assembly). As will become clear, it is relatively easy to spot C statements which will compile to multiple-byte memory access instructions, namely when dealing with types such as u16, u32 and u64.

<a id="rst-natural-alignment"></a>

## Natural alignment

The rule mentioned above forms what we refer to as natural alignment: When accessing N bytes of memory, the base memory address must be evenly divisible by N, i.e. addr % N == 0.

When writing code, assume the target architecture has natural alignment requirements.

In reality, only a few architectures require natural alignment on all sizes of memory access. However, we must consider ALL supported architectures; writing code that satisfies natural alignment requirements is the easiest way to achieve full portability.

<a id="rst-why-unaligned-access-is-bad"></a>

## Why unaligned access is bad

The effects of performing an unaligned memory access vary from architecture to architecture. It would be easy to write a whole document on the differences here; a summary of the common scenarios is presented below:

> - Some architectures are able to perform unaligned memory accesses transparently, but there is usually a significant performance cost.
>
> - Some architectures raise processor exceptions when unaligned accesses happen. The exception handler is able to correct the unaligned access, at significant cost to performance.
>
> - Some architectures raise processor exceptions when unaligned accesses happen, but the exceptions do not contain enough information for the unaligned access to be corrected.
>
> - Some architectures are not capable of unaligned memory access, but will silently perform a different memory access to the one that was requested, resulting in a subtle code bug that is hard to detect\!

It should be obvious from the above that if your code causes unaligned memory accesses to happen, your code will not work correctly on certain platforms and will cause performance problems on others.

<a id="rst-code-that-does-not-cause-unaligned-access"></a>

## Code that does not cause unaligned access

At first, the concepts above may seem a little hard to relate to actual coding practice. After all, you don't have a great deal of control over memory addresses of certain variables, etc.

Fortunately things are not too complex, as in most cases, the compiler ensures that things will work for you. For example, take the following structure:



```text
struct foo {
        u16 field1;
        u32 field2;
        u8 field3;
};
```

Let us assume that an instance of the above structure resides in memory starting at address 0x10000. With a basic level of understanding, it would not be unreasonable to expect that accessing field2 would cause an unaligned access. You'd be expecting field2 to be located at offset 2 bytes into the structure, i.e. address 0x10002, but that address is not evenly divisible by 4 (remember, we're reading a 4 byte value here).

Fortunately, the compiler understands the alignment constraints, so in the above case it would insert 2 bytes of padding in between field1 and field2. Therefore, for standard structure types you can always rely on the compiler to pad structures so that accesses to fields are suitably aligned (assuming you do not cast the field to a type of different length).

Similarly, you can also rely on the compiler to align variables and function parameters to a naturally aligned scheme, based on the size of the type of the variable.

At this point, it should be clear that accessing a single byte (u8 or char) will never cause an unaligned access, because all memory addresses are evenly divisible by one.

On a related topic, with the above considerations in mind you may observe that you could reorder the fields in the structure in order to place fields where padding would otherwise be inserted, and hence reduce the overall resident memory size of structure instances. The optimal layout of the above example is:



```text
struct foo {
        u32 field2;
        u16 field1;
        u8 field3;
};
```

For a natural alignment scheme, the compiler would only have to add a single byte of padding at the end of the structure. This padding is added in order to satisfy alignment constraints for arrays of these structures.

Another point worth mentioning is the use of \_\_attribute\_\_((packed)) on a structure type. This GCC-specific attribute tells the compiler never to insert any padding within structures, useful when you want to use a C struct to represent some data that comes in a fixed arrangement 'off the wire'.

You might be inclined to believe that usage of this attribute can easily lead to unaligned accesses when accessing fields that do not satisfy architectural alignment requirements. However, again, the compiler is aware of the alignment constraints and will generate extra instructions to perform the memory access in a way that does not cause unaligned access. Of course, the extra instructions obviously cause a loss in performance compared to the non-packed case, so the packed attribute should only be used when avoiding structure padding is of importance.

<a id="rst-code-that-causes-unaligned-access"></a>

## Code that causes unaligned access

With the above in mind, let's move onto a real life example of a function that can cause an unaligned memory access. The following function taken from include/linux/etherdevice.h is an optimized routine to compare two ethernet MAC addresses for equality:



```text
bool ether_addr_equal(const u8 *addr1, const u8 *addr2)
{
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
      u32 fold = ((*(const u32 *)addr1) ^ (*(const u32 *)addr2)) |
                 ((*(const u16 *)(addr1 + 4)) ^ (*(const u16 *)(addr2 + 4)));

      return fold == 0;
#else
      const u16 *a = (const u16 *)addr1;
      const u16 *b = (const u16 *)addr2;
      return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2])) == 0;
#endif
}
```

In the above function, when the hardware has efficient unaligned access capability, there is no issue with this code.  But when the hardware isn't able to access memory on arbitrary boundaries, the reference to a\[0\] causes 2 bytes (16 bits) to be read from memory starting at address addr1.

Think about what would happen if addr1 was an odd address such as 0x10003. (Hint: it'd be an unaligned access.)

Despite the potential unaligned access problems with the above function, it is included in the kernel anyway but is understood to only work normally on 16-bit-aligned addresses. It is up to the caller to ensure this alignment or not use this function at all. This alignment-unsafe function is still useful as it is a decent optimization for the cases when you can ensure alignment, which is true almost all of the time in ethernet networking context.

Here is another example of some code that could cause unaligned accesses:



```text
void myfunc(u8 *data, u32 value)
{
        [...]
        *((u32 *) data) = cpu_to_le32(value);
        [...]
}
```

This code will cause unaligned accesses every time the data parameter points to an address that is not evenly divisible by 4.

In summary, the 2 main scenarios where you may run into unaligned access problems involve:

> 1. Casting variables to types of different lengths
>
> 2. Pointer arithmetic followed by access to at least 2 bytes of data

<a id="rst-avoiding-unaligned-accesses"></a>

## Avoiding unaligned accesses

The easiest way to avoid unaligned access is to use the get\_unaligned() and put\_unaligned() macros provided by the &lt;linux/unaligned.h&gt; header file.

Going back to an earlier example of code that potentially causes unaligned access:



```text
void myfunc(u8 *data, u32 value)
{
        [...]
        *((u32 *) data) = cpu_to_le32(value);
        [...]
}
```

To avoid the unaligned memory access, you would rewrite it as follows:



```text
void myfunc(u8 *data, u32 value)
{
        [...]
        value = cpu_to_le32(value);
        put_unaligned(value, (u32 *) data);
        [...]
}
```

The get\_unaligned() macro works similarly. Assuming 'data' is a pointer to memory and you wish to avoid unaligned access, its usage is as follows:



```text
u32 value = get_unaligned((u32 *) data);
```

These macros work for memory accesses of any length (not just 32 bits as in the examples above). Be aware that when compared to standard access of aligned memory, using these macros to access unaligned memory can be costly in terms of performance.

If use of such macros is not convenient, another option is to use memcpy(), where the source or destination (or both) are of type u8\* or unsigned char\*. Due to the byte-wise nature of this operation, unaligned accesses are avoided.

<a id="rst-alignment-vs-networking"></a>

## Alignment vs. Networking

On architectures that require aligned loads, networking requires that the IP header is aligned on a four-byte boundary to optimise the IP stack. For regular ethernet hardware, the constant NET\_IP\_ALIGN is used. On most architectures this constant has the value 2 because the normal ethernet header is 14 bytes long, so in order to get proper alignment one needs to DMA to an address which can be expressed as 4\*n + 2. One notable exception here is powerpc which defines NET\_IP\_ALIGN to 0 because DMA to unaligned addresses can be very expensive and dwarf the cost of unaligned loads.

For some ethernet hardware that cannot DMA to unaligned addresses like 4\*n+2 or non-ethernet hardware, this can be a problem, and it is then required to copy the incoming frame into an aligned buffer. Because this is unnecessary on architectures that can do unaligned accesses, the code can be made dependent on CONFIG\_HAVE\_EFFICIENT\_UNALIGNED\_ACCESS like so:



```text
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
        skb = original skb
#else
        skb = copy skb
#endif
```

---

# Union-Find in Linux

_Peios Kernel / Internals / Core APIs_

> Union-find is a data structure used to handle the merging and querying of disjoint sets. The primary operations supported by union-find are:

<a id="rst-union-find-in-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Date:** June 21, 2024

**Author:** Xavier &lt;[xavier_qy@163.com](<mailto:xavier_qy@163.com>)&gt;

<a id="rst-what-is-union-find-and-what-is-it-used-for"></a>

## What is union-find, and what is it used for?

Union-find is a data structure used to handle the merging and querying of disjoint sets. The primary operations supported by union-find are:

> - **Initialization: Resetting each element as an individual set, with**
>
>   each set's initial parent node pointing to itself.
>
> - **Find: Determine which set a particular element belongs to, usually by**
>
>   returning a “representative element” of that set. This operation is used to check if two elements are in the same set.
>
> Union: Merge two sets into one.

As a data structure used to maintain sets (groups), union-find is commonly utilized to solve problems related to offline queries, dynamic connectivity, and graph theory. It is also a key component in Kruskal's algorithm for computing the minimum spanning tree, which is crucial in scenarios like network routing. Consequently, union-find is widely referenced. Additionally, union-find has applications in symbolic computation, register allocation, and more.

Space Complexity: O(n), where n is the number of nodes.

Time Complexity: Using path compression can reduce the time complexity of the find operation, and using union by rank can reduce the time complexity of the union operation. These optimizations reduce the average time complexity of each find and union operation to O(α(n)), where α(n) is the inverse Ackermann function. This can be roughly considered a constant time complexity for practical purposes.

This document covers use of the Linux union-find implementation.  For more information on the nature and implementation of union-find,  see:

> - **Wikipedia entry on union-find**
>
>   [https://en.wikipedia.org/wiki/Disjoint-set_data_structure](<https://en.wikipedia.org/wiki/Disjoint-set_data_structure>)

<a id="rst-linux-implementation-of-union-find"></a>

## Linux implementation of union-find

Linux's union-find implementation resides in the file "lib/union_find.c". To use it, "\#include &lt;linux/union_find.h&gt;".

The union-find data structure is defined as follows:



```text
struct uf_node {
        struct uf_node *parent;
        unsigned int rank;
};
```

In this structure, parent points to the parent node of the current node. The rank field represents the height of the current tree. During a union operation, the tree with the smaller rank is attached under the tree with the larger rank to maintain balance.

<a id="rst-initializing-union-find"></a>

## Initializing union-find

You can complete the initialization using either static or initialization interface. Initialize the parent pointer to point to itself and set the rank to 0. Example:



```text
struct uf_node my_node = UF_INIT_NODE(my_node);
```

or

> uf_node_init(&amp;my_node);

<a id="rst-find-the-root-node-of-union-find"></a>

## Find the Root Node of union-find

This operation is mainly used to determine whether two nodes belong to the same set in the union-find. If they have the same root, they are in the same set. During the find operation, path compression is performed to improve the efficiency of subsequent find operations. Example:



```text
int connected;
struct uf_node *root1 = uf_find(&node_1);
struct uf_node *root2 = uf_find(&node_2);
if (root1 == root2)
        connected = 1;
else
        connected = 0;
```

<a id="rst-union-two-sets-in-union-find"></a>

## Union Two Sets in union-find

To union two sets in the union-find, you first find their respective root nodes and then link the smaller node to the larger node based on the rank of the root nodes. Example:



```text
uf_union(&node_1, &node_2);
```

---

# General notification mechanism

_Peios Kernel / Internals / Core APIs_

> The general notification mechanism is built on top of the standard pipe driver whereby it effectively splices notification messages from the kernel into pipes opened by userspace. This can be used in conjunction with:

> **Peios:** The LSM examples here describe upstream interfaces and implementation choices. Peios configures `landlock,lockdown,integrity,pkm`; SELinux, Smack, AppArmor and their attribute/policy interfaces are not the active native access model. Use the native token/SD interfaces for Peios authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-general-notification-mechanism"></a>

The general notification mechanism is built on top of the standard pipe driver whereby it effectively splices notification messages from the kernel into pipes opened by userspace.  This can be used in conjunction with:



```text
* Key/keyring notifications
```

The notifications buffers can be enabled by:

> "General setup"/"General notification queue" (CONFIG_WATCH_QUEUE)

This document has the following sections:

<a id="rst-contents"></a>



<a id="rst-overview"></a>

## Overview

This facility appears as a pipe that is opened in a special mode.  The pipe's internal ring buffer is used to hold messages that are generated by the kernel. These messages are then read out by read().  Splice and similar are disabled on such pipes due to them wanting to, under some circumstances, revert their additions to the ring - which might end up interleaved with notification messages.

The owner of the pipe has to tell the kernel which sources it would like to watch through that pipe.  Only sources that have been connected to a pipe will insert messages into it.  Note that a source may be bound to multiple pipes and insert messages into all of them simultaneously.

Filters may also be emplaced on a pipe so that certain source types and subevents can be ignored if they're not of interest.

A message will be discarded if there isn't a slot available in the ring or if no preallocated message buffer is available.  In both of these cases, read() will insert a WATCH_META_LOSS_NOTIFICATION message into the output buffer after the last message currently in the buffer has been read.

Note that when producing a notification, the kernel does not wait for the consumers to collect it, but rather just continues on.  This means that notifications can be generated whilst spinlocks are held and also protects the kernel from being held up indefinitely by a userspace malfunction.

<a id="rst-message-structure"></a>

## Message Structure

Notification messages begin with a short header:



```text
struct watch_notification {
        __u32   type:24;
        __u32   subtype:8;
        __u32   info;
};
```

"type" indicates the source of the notification record and "subtype" indicates the type of record from that source (see the Watch Sources section below).  The type may also be "WATCH_TYPE_META".  This is a special record type generated internally by the watch queue itself.  There are two subtypes:

> - WATCH_META_REMOVAL_NOTIFICATION
>
> - WATCH_META_LOSS_NOTIFICATION

The first indicates that an object on which a watch was installed was removed or destroyed and the second indicates that some messages have been lost.

"info" indicates a bunch of things, including:

> - The length of the message in bytes, including the header (mask with WATCH_INFO_LENGTH and shift by WATCH_INFO_LENGTH__SHIFT).  This indicates the size of the record, which may be between 8 and 127 bytes.
>
> - The watch ID (mask with WATCH_INFO_ID and shift by WATCH_INFO_ID__SHIFT). This indicates that caller's ID of the watch, which may be between 0 and 255.  Multiple watches may share a queue, and this provides a means to distinguish them.
>
> - A type-specific field (WATCH_INFO_TYPE_INFO).  This is set by the notification producer to indicate some meaning specific to the type and subtype.

Everything in info apart from the length can be used for filtering.

The header can be followed by supplementary information.  The format of this is at the discretion is defined by the type and subtype.

<a id="rst-watch-list-notification-source-api"></a>

## Watch List (Notification Source) API

A "watch list" is a list of watchers that are subscribed to a source of notifications.  A list may be attached to an object (say a key or a superblock) or may be global (say for device events).  From a userspace perspective, a non-global watch list is typically referred to by reference to the object it belongs to (such as using KEYCTL_NOTIFY and giving it a key serial number to watch that specific key).

To manage a watch list, the following functions are provided:

> - 
>
>   ```text
>   void init_watch_list(struct watch_list *wlist,
>                        void (*release_watch)(struct watch *wlist));
>   ```
>
>   Initialise a watch list.  If `release_watch` is not NULL, then this indicates a function that should be called when the watch_list object is destroyed to discard any references the watch list holds on the watched object.
>
> - `void remove_watch_list(struct watch_list *wlist);`
>
>   This removes all of the watches subscribed to a watch_list and frees them and then destroys the watch_list object itself.

<a id="rst-watch-queue-notification-output-api"></a>

## Watch Queue (Notification Output) API

A "watch queue" is the buffer allocated by an application that notification records will be written into.  The workings of this are hidden entirely inside of the pipe device driver, but it is necessary to gain a reference to it to set a watch.  These can be managed with:

> - `struct watch_queue *get_watch_queue(int fd);`
>
>   Since watch queues are indicated to the kernel by the fd of the pipe that implements the buffer, userspace must hand that fd through a system call. This can be used to look up an opaque pointer to the watch queue from the system call.
>
> - `void put_watch_queue(struct watch_queue *wqueue);`
>
>   This discards the reference obtained from `get_watch_queue()`.

<a id="rst-watch-subscription-api"></a>

## Watch Subscription API

A "watch" is a subscription on a watch list, indicating the watch queue, and thus the buffer, into which notification records should be written.  The watch queue object may also carry filtering rules for that object, as set by userspace.  Some parts of the watch struct can be set by the driver:



```text
struct watch {
        union {
                u32             info_id;        /* ID to be OR'd in to info field */
                ...
        };
        void                    *private;       /* Private data for the watched object */
        u64                     id;             /* Internal identifier */
        ...
};
```

The `info_id` value should be an 8-bit number obtained from userspace and shifted by WATCH_INFO_ID__SHIFT.  This is OR'd into the WATCH_INFO_ID field of struct watch_notification::info when and if the notification is written into the associated watch queue buffer.

The `private` field is the driver's data associated with the watch_list and is cleaned up by the `watch_list::release_watch()` method.

The `id` field is the source's ID.  Notifications that are posted with a different ID are ignored.

The following functions are provided to manage watches:

> - `void init_watch(struct watch *watch, struct watch_queue *wqueue);`
>
>   Initialise a watch object, setting its pointer to the watch queue, using appropriate barriering to avoid lockdep complaints.
>
> - `int add_watch_to_object(struct watch *watch, struct watch_list *wlist);`
>
>   Subscribe a watch to a watch list (notification source).  The driver-settable fields in the watch struct must have been set before this is called.
>
> - 
>
>   ```text
>   int remove_watch_from_object(struct watch_list *wlist,
>                                struct watch_queue *wqueue,
>                                u64 id, false);
>   ```
>
>   Remove a watch from a watch list, where the watch must match the specified watch queue (`wqueue`) and object identifier (`id`).  A notification (`WATCH_META_REMOVAL_NOTIFICATION`) is sent to the watch queue to indicate that the watch got removed.
>
> - `int remove_watch_from_object(struct watch_list *wlist, NULL, 0, true);`
>
>   Remove all the watches from a watch list.  It is expected that this will be called preparatory to destruction and that the watch list will be inaccessible to new watches by this point.  A notification (`WATCH_META_REMOVAL_NOTIFICATION`) is sent to the watch queue of each subscribed watch to indicate that the watch got removed.

<a id="rst-notification-posting-api"></a>

## Notification Posting API

To post a notification to watch list so that the subscribed watches can see it, the following function should be used:



```text
void post_watch_notification(struct watch_list *wlist,
                             struct watch_notification *n,
                             const struct cred *cred,
                             u64 id);
```

The notification should be preformatted and a pointer to the header (`n`) should be passed in.  The notification may be larger than this and the size in units of buffer slots is noted in `n->info & WATCH_INFO_LENGTH`.

The `cred` struct indicates the credentials of the source (subject) and is passed to the LSMs, such as SELinux, to allow or suppress the recording of the note in each individual queue according to the credentials of that queue (object).

The `id` is the ID of the source object (such as the serial number on a key). Only watches that have the same ID set in them will see this notification.

<a id="rst-watch-sources"></a>

## Watch Sources

Any particular buffer can be fed from multiple sources.  Sources include:

> - WATCH_TYPE_KEY_NOTIFY
>
>   Notifications of this type indicate changes to keys and keyrings, including the changes of keyring contents or the attributes of keys.
>
>   See [Documentation/security/keys/core.rst](/kernel/internals/security/keys/core.md) for more information.

<a id="rst-event-filtering"></a>

## Event Filtering

Once a watch queue has been created, a set of filters can be applied to limit the events that are received using:



```text
struct watch_notification_filter filter = {
        ...
};
ioctl(fd, IOC_WATCH_QUEUE_SET_FILTER, &filter)
```

The filter description is a variable of type:



```text
struct watch_notification_filter {
        __u32   nr_filters;
        __u32   __reserved;
        struct watch_notification_type_filter filters[];
};
```

Where "nr_filters" is the number of filters in filters\[\] and "\__reserved" should be 0.  The "filters" array has elements of the following type:



```text
struct watch_notification_type_filter {
        __u32   type;
        __u32   info_filter;
        __u32   info_mask;
        __u32   subtype_filter[8];
};
```

Where:

> - `type` is the event type to filter for and should be something like "WATCH_TYPE_KEY_NOTIFY"
>
> - `info_filter` and `info_mask` act as a filter on the info field of the notification record.  The notification is only written into the buffer if:
>
>
>
>   ```text
>   (watch.info & info_mask) == info_filter
>   ```
>
>   This could be used, for example, to ignore events that are not exactly on the watched point in a mount tree.
>
> - `subtype_filter` is a bitmask indicating the subtypes that are of interest.  Bit 0 of subtype_filter\[0\] corresponds to subtype 0, bit 1 to subtype 1, and so on.

If the argument to the ioctl() is NULL, then the filters will be removed and all events from the watched sources will come through.

<a id="rst-userspace-code-example"></a>

## Userspace Code Example

A buffer is created with something like the following:



```text
pipe2(fds, O_TMPFILE);
ioctl(fds[1], IOC_WATCH_QUEUE_SET_SIZE, 256);
```

It can then be set to receive keyring change notifications:



```text
keyctl(KEYCTL_WATCH_KEY, KEY_SPEC_SESSION_KEYRING, fds[1], 0x01);
```

The notifications can then be consumed by something like the following:



```text
static void consumer(int rfd, struct watch_queue_buffer *buf)
{
        unsigned char buffer[128];
        ssize_t buf_len;

        while (buf_len = read(rfd, buffer, sizeof(buffer)),
               buf_len > 0
               ) {
                void *p = buffer;
                void *end = buffer + buf_len;
                while (p < end) {
                        union {
                                struct watch_notification n;
                                unsigned char buf1[128];
                        } n;
                        size_t largest, len;

                        largest = end - p;
                        if (largest > 128)
                                largest = 128;
                        memcpy(&n, p, largest);

                        len = (n->info & WATCH_INFO_LENGTH) >>
                                WATCH_INFO_LENGTH__SHIFT;
                        if (len == 0 || len > largest)
                                return;

                        switch (n.n.type) {
                        case WATCH_TYPE_META:
                                got_meta(&n.n);
                        case WATCH_TYPE_KEY_NOTIFY:
                                saw_key_change(&n.n);
                                break;
                        }

                        p += len;
                }
        }
}
```

---

# Workqueue

_Peios Kernel / Internals / Core APIs_

> There are many cases where an asynchronous process execution context is needed and the workqueue (wq) API is the most commonly used mechanism for such cases.

<a id="rst-workqueue"></a>

**Date:** September, 2010

**Author:** Tejun Heo &lt;[tj@kernel.org](<mailto:tj@kernel.org>)&gt;

**Author:** Florian Mickler &lt;[florian@mickler.org](<mailto:florian@mickler.org>)&gt;

<a id="rst-introduction"></a>

## Introduction

There are many cases where an asynchronous process execution context is needed and the workqueue (wq) API is the most commonly used mechanism for such cases.

When such an asynchronous execution context is needed, a work item describing which function to execute is put on a queue.  An independent thread serves as the asynchronous execution context.  The queue is called workqueue and the thread is called worker.

While there are work items on the workqueue the worker executes the functions associated with the work items one after the other.  When there is no work item left on the workqueue the worker becomes idle. When a new work item gets queued, the worker begins executing again.

<a id="rst-why-concurrency-managed-workqueue"></a>

## Why Concurrency Managed Workqueue?

In the original wq implementation, a multi threaded (MT) wq had one worker thread per CPU and a single threaded (ST) wq had one worker thread system-wide.  A single MT wq needed to keep around the same number of workers as the number of CPUs.  The kernel grew a lot of MT wq users over the years and with the number of CPU cores continuously rising, some systems saturated the default 32k PID space just booting up.

Although MT wq wasted a lot of resource, the level of concurrency provided was unsatisfactory.  The limitation was common to both ST and MT wq albeit less severe on MT.  Each wq maintained its own separate worker pool.  An MT wq could provide only one execution context per CPU while an ST wq one for the whole system.  Work items had to compete for those very limited execution contexts leading to various problems including proneness to deadlocks around the single execution context.

The tension between the provided level of concurrency and resource usage also forced its users to make unnecessary tradeoffs like libata choosing to use ST wq for polling PIOs and accepting an unnecessary limitation that no two polling PIOs can progress at the same time.  As MT wq don't provide much better concurrency, users which require higher level of concurrency, like async or fscache, had to implement their own thread pool.

Concurrency Managed Workqueue (cmwq) is a reimplementation of wq with focus on the following goals.

- Maintain compatibility with the original workqueue API.

- Use per-CPU unified worker pools shared by all wq to provide flexible level of concurrency on demand without wasting a lot of resource.

- Automatically regulate worker pool and level of concurrency so that the API users don't need to worry about such details.

<a id="rst-the-design"></a>

## The Design

In order to ease the asynchronous execution of functions a new abstraction, the work item, is introduced.

A work item is a simple struct that holds a pointer to the function that is to be executed asynchronously.  Whenever a driver or subsystem wants a function to be executed asynchronously it has to set up a work item pointing to that function and queue that work item on a workqueue.

A work item can be executed in either a thread or the BH (softirq) context.

For threaded workqueues, special purpose threads, called \[k\]workers, execute the functions off of the queue, one after the other. If no work is queued, the worker threads become idle. These worker threads are managed in worker-pools.

The cmwq design differentiates between the user-facing workqueues that subsystems and drivers queue work items on and the backend mechanism which manages worker-pools and processes the queued work items.

There are two worker-pools, one for normal work items and the other for high priority ones, for each possible CPU and some extra worker-pools to serve work items queued on unbound workqueues - the number of these backing pools is dynamic.

BH workqueues use the same framework. However, as there can only be one concurrent execution context, there's no need to worry about concurrency. Each per-CPU BH worker pool contains only one pseudo worker which represents the BH execution context. A BH workqueue can be considered a convenience interface to softirq.

Subsystems and drivers can create and queue work items through special workqueue API functions as they see fit. They can influence some aspects of the way the work items are executed by setting flags on the workqueue they are putting the work item on. These flags include things like CPU locality, concurrency limits, priority and more.  To get a detailed overview refer to the API description of `alloc_workqueue()` below.

When a work item is queued to a workqueue, the target worker-pool is determined according to the queue parameters and workqueue attributes and appended on the shared worklist of the worker-pool.  For example, unless specifically overridden, a work item of a bound workqueue will be queued on the worklist of either normal or highpri worker-pool that is associated to the CPU the issuer is running on.

For any thread pool implementation, managing the concurrency level (how many execution contexts are active) is an important issue.  cmwq tries to keep the concurrency at a minimal but sufficient level. Minimal to save resources and sufficient in that the system is used at its full capacity.

Each worker-pool bound to an actual CPU implements concurrency management by hooking into the scheduler.  The worker-pool is notified whenever an active worker wakes up or sleeps and keeps track of the number of the currently runnable workers.  Generally, work items are not expected to hog a CPU and consume many cycles.  That means maintaining just enough concurrency to prevent work processing from stalling should be optimal.  As long as there are one or more runnable workers on the CPU, the worker-pool doesn't start execution of a new work, but, when the last running worker goes to sleep, it immediately schedules a new worker so that the CPU doesn't sit idle while there are pending work items.  This allows using a minimal number of workers without losing execution bandwidth.

Keeping idle workers around doesn't cost other than the memory space for kthreads, so cmwq holds onto idle ones for a while before killing them.

For unbound workqueues, the number of backing pools is dynamic. Unbound workqueue can be assigned custom attributes using `apply_workqueue_attrs()` and workqueue will automatically create backing worker pools matching the attributes.  The responsibility of regulating concurrency level is on the users.  There is also a flag to mark a bound wq to ignore the concurrency management.  Please refer to the API section for details.

Forward progress guarantee relies on that workers can be created when more execution contexts are necessary, which in turn is guaranteed through the use of rescue workers.  All work items which might be used on code paths that handle memory reclaim are required to be queued on wq's that have a rescue-worker reserved for execution under memory pressure.  Else it is possible that the worker-pool deadlocks waiting for execution contexts to free up.

<a id="rst-application-programming-interface-api"></a>

## Application Programming Interface (API)

`alloc_workqueue()` allocates a wq.  The original `create_*workqueue()` functions are deprecated and scheduled for removal.  `alloc_workqueue()` takes three arguments - `@name`, `@flags` and `@max_active`.  `@name` is the name of the wq and also used as the name of the rescuer thread if there is one.

A wq no longer manages execution resources but serves as a domain for forward progress guarantee, flush and work item attributes. `@flags` and `@max_active` control how work items are assigned execution resources, scheduled and executed.

<a id="rst-flags"></a>

### `flags`

- **`WQ_BH`**

  BH workqueues can be considered a convenience interface to softirq. BH workqueues are always per-CPU and all BH work items are executed in the queueing CPU's softirq context in the queueing order.

  All BH workqueues must have 0 `max_active` and `WQ_HIGHPRI` is the only allowed additional flag.

  BH work items cannot sleep. All other features such as delayed queueing, flushing and canceling are supported.

- **`WQ_PERCPU`**

  Work items queued to a per-cpu wq are bound to a specific CPU. This flag is the right choice when cpu locality is important.

  This flag is the complement of `WQ_UNBOUND`.

- **`WQ_UNBOUND`**

  Work items queued to an unbound wq are served by the special worker-pools which host workers which are not bound to any specific CPU.  This makes the wq behave as a simple execution context provider without concurrency management.  The unbound worker-pools try to start execution of work items as soon as possible.  Unbound wq sacrifices locality but is useful for the following cases.

  - Wide fluctuation in the concurrency level requirement is expected and using bound wq may end up creating large number of mostly unused workers across different CPUs as the issuer hops through different CPUs.

  - Long running CPU intensive workloads which can be better managed by the system scheduler.

- **`WQ_FREEZABLE`**

  A freezable wq participates in the freeze phase of the system suspend operations.  Work items on the wq are drained and no new work item starts execution until thawed.

- **`WQ_MEM_RECLAIM`**

  All wq which might be used in the memory reclaim paths **MUST** have this flag set.  The wq is guaranteed to have at least one execution context regardless of memory pressure.

- **`WQ_HIGHPRI`**

  Work items of a highpri wq are queued to the highpri worker-pool of the target cpu.  Highpri worker-pools are served by worker threads with elevated nice level.

  Note that normal and highpri worker-pools don't interact with each other.  Each maintains its separate pool of workers and implements concurrency management among its workers.

- **`WQ_CPU_INTENSIVE`**

  Work items of a CPU intensive wq do not contribute to the concurrency level.  In other words, runnable CPU intensive work items will not prevent other work items in the same worker-pool from starting execution.  This is useful for bound work items which are expected to hog CPU cycles so that their execution is regulated by the system scheduler.

  Although CPU intensive work items don't contribute to the concurrency level, start of their executions is still regulated by the concurrency management and runnable non-CPU-intensive work items can delay execution of CPU intensive work items.

  This flag is meaningless for unbound wq.

<a id="rst-max-active"></a>

### `max_active`

`@max_active` determines the maximum number of execution contexts per CPU which can be assigned to the work items of a wq. For example, with `@max_active` of 16, at most 16 work items of the wq can be executing at the same time per CPU. This is always a per-CPU attribute, even for unbound workqueues.

The maximum limit for `@max_active` is 2048 and the default value used when 0 is specified is 1024. These values are chosen sufficiently high such that they are not the limiting factor while providing protection in runaway cases.

The number of active work items of a wq is usually regulated by the users of the wq, more specifically, by how many work items the users may queue at the same time.  Unless there is a specific need for throttling the number of active work items, specifying '0' is recommended.

Some users depend on strict execution ordering where only one work item is in flight at any given time and the work items are processed in queueing order. While the combination of `@max_active` of 1 and `WQ_UNBOUND` used to achieve this behavior, this is no longer the case. Use alloc_ordered_workqueue() instead.

<a id="rst-example-execution-scenarios"></a>

## Example Execution Scenarios

The following example execution scenarios try to illustrate how cmwq behave under different configurations.

> Work items w0, w1, w2 are queued to a bound wq q0 on the same CPU. w0 burns CPU for 5ms then sleeps for 10ms then burns CPU for 5ms again before finishing.  w1 and w2 burn CPU for 5ms then sleep for 10ms.

Ignoring all other tasks, works and processing overhead, and assuming simple FIFO scheduling, the following is one highly simplified version of possible sequences of events with the original wq.



```text
TIME IN MSECS  EVENT
0              w0 starts and burns CPU
5              w0 sleeps
15             w0 wakes up and burns CPU
20             w0 finishes
20             w1 starts and burns CPU
25             w1 sleeps
35             w1 wakes up and finishes
35             w2 starts and burns CPU
40             w2 sleeps
50             w2 wakes up and finishes
```

And with cmwq with `@max_active` &gt;= 3,



```text
TIME IN MSECS  EVENT
0              w0 starts and burns CPU
5              w0 sleeps
5              w1 starts and burns CPU
10             w1 sleeps
10             w2 starts and burns CPU
15             w2 sleeps
15             w0 wakes up and burns CPU
20             w0 finishes
20             w1 wakes up and finishes
25             w2 wakes up and finishes
```

If `@max_active` == 2,



```text
TIME IN MSECS  EVENT
0              w0 starts and burns CPU
5              w0 sleeps
5              w1 starts and burns CPU
10             w1 sleeps
15             w0 wakes up and burns CPU
20             w0 finishes
20             w1 wakes up and finishes
20             w2 starts and burns CPU
25             w2 sleeps
35             w2 wakes up and finishes
```

Now, let's assume w1 and w2 are queued to a different wq q1 which has `WQ_CPU_INTENSIVE` set,



```text
TIME IN MSECS  EVENT
0              w0 starts and burns CPU
5              w0 sleeps
5              w1 and w2 start and burn CPU
10             w1 sleeps
15             w2 sleeps
15             w0 wakes up and burns CPU
20             w0 finishes
20             w1 wakes up and finishes
25             w2 wakes up and finishes
```

<a id="rst-guidelines"></a>

## Guidelines

- Do not forget to use `WQ_MEM_RECLAIM` if a wq may process work items which are used during memory reclaim.  Each wq with `WQ_MEM_RECLAIM` set has an execution context reserved for it.  If there is dependency among multiple work items used during memory reclaim, they should be queued to separate wq each with `WQ_MEM_RECLAIM`.

- Unless strict ordering is required, there is no need to use ST wq.

- Unless there is a specific need, using 0 for @max_active is recommended.  In most use cases, concurrency level usually stays well under the default limit.

- A wq serves as a domain for forward progress guarantee (`WQ_MEM_RECLAIM`, flush and work item attributes.  Work items which are not involved in memory reclaim and don't need to be flushed as a part of a group of work items, and don't require any special attribute, can use one of the system wq.  There is no difference in execution characteristics between using a dedicated wq and a system wq.

  Note: If something may generate more than @max_active outstanding work items (do stress test your producers), it may saturate a system wq and potentially lead to deadlock. It should utilize its own dedicated workqueue rather than the system wq.

- Unless work items are expected to consume a huge amount of CPU cycles, using a bound wq is usually beneficial due to the increased level of locality in wq operations and work item execution.

<a id="rst-affinity-scopes"></a>

## Affinity Scopes

An unbound workqueue groups CPUs according to its affinity scope to improve cache locality. For example, if a workqueue is using the default affinity scope of "cache", it will group CPUs according to last level cache boundaries. A work item queued on the workqueue will be assigned to a worker on one of the CPUs which share the last level cache with the issuing CPU. Once started, the worker may or may not be allowed to move outside the scope depending on the `affinity_strict` setting of the scope.

Workqueue currently supports the following affinity scopes.

- **`default`**

  Use the scope in module parameter `workqueue.default_affinity_scope` which is always set to one of the scopes below.

- **`cpu`**

  CPUs are not grouped. A work item issued on one CPU is processed by a worker on the same CPU. This makes unbound workqueues behave as per-cpu workqueues without concurrency management.

- **`smt`**

  CPUs are grouped according to SMT boundaries. This usually means that the logical threads of each physical CPU core are grouped together.

- **`cache`**

  CPUs are grouped according to cache boundaries. Which specific cache boundary is used is determined by the arch code. L3 is used in a lot of cases. This is the default affinity scope.

- **`numa`**

  CPUs are grouped according to NUMA boundaries.

- **`system`**

  All CPUs are put in the same group. Workqueue makes no effort to process a work item on a CPU close to the issuing CPU.

The default affinity scope can be changed with the module parameter `workqueue.default_affinity_scope` and a specific workqueue's affinity scope can be changed using `apply_workqueue_attrs()`.

If `WQ_SYSFS` is set, the workqueue will have the following affinity scope related interface files under its `/sys/devices/virtual/workqueue/WQ_NAME/` directory.

- **`affinity_scope`**

  Read to see the current affinity scope. Write to change.

  When default is the current scope, reading this file will also show the current effective scope in parentheses, for example, `default (cache)`.

- **`affinity_strict`**

  0 by default indicating that affinity scopes are not strict. When a work item starts execution, workqueue makes a best-effort attempt to ensure that the worker is inside its affinity scope, which is called repatriation. Once started, the scheduler is free to move the worker anywhere in the system as it sees fit. This enables benefiting from scope locality while still being able to utilize other CPUs if necessary and available.

  If set to 1, all workers of the scope are guaranteed always to be in the scope. This may be useful when crossing affinity scopes has other implications, for example, in terms of power consumption or workload isolation. Strict NUMA scope can also be used to match the workqueue behavior of older kernels.

<a id="rst-affinity-scopes-and-performance"></a>

## Affinity Scopes and Performance

It'd be ideal if an unbound workqueue's behavior is optimal for vast majority of use cases without further tuning. Unfortunately, in the current kernel, there exists a pronounced trade-off between locality and utilization necessitating explicit configurations when workqueues are heavily used.

Higher locality leads to higher efficiency where more work is performed for the same number of consumed CPU cycles. However, higher locality may also cause lower overall system utilization if the work items are not spread enough across the affinity scopes by the issuers. The following performance testing with dm-crypt clearly illustrates this trade-off.

The tests are run on a CPU with 12-cores/24-threads split across four L3 caches (AMD Ryzen 9 3900x). CPU clock boost is turned off for consistency. `/dev/dm-0` is a dm-crypt device created on NVME SSD (Samsung 990 PRO) and opened with `cryptsetup` with default settings.

<a id="rst-scenario-1-enough-issuers-and-work-spread-across-the-machine"></a>

### Scenario 1: Enough issuers and work spread across the machine

The command used:



```text
$ fio --filename=/dev/dm-0 --direct=1 --rw=randrw --bs=32k --ioengine=libaio \
  --iodepth=64 --runtime=60 --numjobs=24 --time_based --group_reporting \
  --name=iops-test-job --verify=sha512
```

There are 24 issuers, each issuing 64 IOs concurrently. `--verify=sha512` makes `fio` generate and read back the content each time which makes execution locality matter between the issuer and `kcryptd`. The following are the read bandwidths and CPU utilizations depending on different affinity scope settings on `kcryptd` measured over five runs. Bandwidths are in MiBps, and CPU util in percents.


<table>
<thead>
<tr>
<th>


Affinity

</th>
<th>


Bandwidth (MiBps)

</th>
<th>


CPU util (%)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


system

</td>
<td>


1159.40 ±1.34

</td>
<td>


99.31 ±0.02

</td>
</tr>
<tr>
<td>


cache

</td>
<td>


1166.40 ±0.89

</td>
<td>


99.34 ±0.01

</td>
</tr>
<tr>
<td>


cache (strict)

</td>
<td>


1166.00 ±0.71

</td>
<td>


99.35 ±0.01

</td>
</tr>
</tbody>
</table>

With enough issuers spread across the system, there is no downside to "cache", strict or otherwise. All three configurations saturate the whole machine but the cache-affine ones outperform by 0.6% thanks to improved locality.

<a id="rst-scenario-2-fewer-issuers-enough-work-for-saturation"></a>

### Scenario 2: Fewer issuers, enough work for saturation

The command used:



```text
$ fio --filename=/dev/dm-0 --direct=1 --rw=randrw --bs=32k \
  --ioengine=libaio --iodepth=64 --runtime=60 --numjobs=8 \
  --time_based --group_reporting --name=iops-test-job --verify=sha512
```

The only difference from the previous scenario is `--numjobs=8`. There are a third of the issuers but is still enough total work to saturate the system.


<table>
<thead>
<tr>
<th>


Affinity

</th>
<th>


Bandwidth (MiBps)

</th>
<th>


CPU util (%)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


system

</td>
<td>


1155.40 ±0.89

</td>
<td>


97.41 ±0.05

</td>
</tr>
<tr>
<td>


cache

</td>
<td>


1154.40 ±1.14

</td>
<td>


96.15 ±0.09

</td>
</tr>
<tr>
<td>


cache (strict)

</td>
<td>


1112.00 ±4.64

</td>
<td>


93.26 ±0.35

</td>
</tr>
</tbody>
</table>

This is more than enough work to saturate the system. Both "system" and "cache" are nearly saturating the machine but not fully. "cache" is using less CPU but the better efficiency puts it at the same bandwidth as "system".

Eight issuers moving around over four L3 cache scope still allow "cache (strict)" to mostly saturate the machine but the loss of work conservation is now starting to hurt with 3.7% bandwidth loss.

<a id="rst-scenario-3-even-fewer-issuers-not-enough-work-to-saturate"></a>

### Scenario 3: Even fewer issuers, not enough work to saturate

The command used:



```text
$ fio --filename=/dev/dm-0 --direct=1 --rw=randrw --bs=32k \
  --ioengine=libaio --iodepth=64 --runtime=60 --numjobs=4 \
  --time_based --group_reporting --name=iops-test-job --verify=sha512
```

Again, the only difference is `--numjobs=4`. With the number of issuers reduced to four, there now isn't enough work to saturate the whole system and the bandwidth becomes dependent on completion latencies.


<table>
<thead>
<tr>
<th>


Affinity

</th>
<th>


Bandwidth (MiBps)

</th>
<th>


CPU util (%)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


system

</td>
<td>


993.60 ±1.82

</td>
<td>


75.49 ±0.06

</td>
</tr>
<tr>
<td>


cache

</td>
<td>


973.40 ±1.52

</td>
<td>


74.90 ±0.07

</td>
</tr>
<tr>
<td>


cache (strict)

</td>
<td>


828.20 ±4.49

</td>
<td>


66.84 ±0.29

</td>
</tr>
</tbody>
</table>

Now, the tradeoff between locality and utilization is clearer. "cache" shows 2% bandwidth loss compared to "system" and "cache (struct)" whopping 20%.

<a id="rst-conclusion-and-recommendations"></a>

### Conclusion and Recommendations

In the above experiments, the efficiency advantage of the "cache" affinity scope over "system" is, while consistent and noticeable, small. However, the impact is dependent on the distances between the scopes and may be more pronounced in processors with more complex topologies.

While the loss of work-conservation in certain scenarios hurts, it is a lot better than "cache (strict)" and maximizing workqueue utilization is unlikely to be the common case anyway. As such, "cache" is the default affinity scope for unbound pools.

- As there is no one option which is great for most cases, workqueue usages that may consume a significant amount of CPU are recommended to configure the workqueues using `apply_workqueue_attrs()` and/or enable `WQ_SYSFS`.

- An unbound workqueue with strict "cpu" affinity scope behaves the same as `WQ_CPU_INTENSIVE` per-cpu workqueue. There is no real advanage to the latter and an unbound workqueue provides a lot more flexibility.

- Affinity scopes are introduced in Linux v6.5. To emulate the previous behavior, use strict "numa" affinity scope.

- The loss of work-conservation in non-strict affinity scopes is likely originating from the scheduler. There is no theoretical reason why the kernel wouldn't be able to do the right thing and maintain work-conservation in most cases. As such, it is possible that future scheduler improvements may make most of these tunables unnecessary.

<a id="rst-examining-configuration"></a>

## Examining Configuration

Use tools/workqueue/wq_dump.py to examine unbound CPU affinity configuration, worker pools and how workqueues map to the pools:



```text
$ tools/workqueue/wq_dump.py
Affinity Scopes
===============
wq_unbound_cpumask=0000000f

CPU
  nr_pods  4
  pod_cpus [0]=00000001 [1]=00000002 [2]=00000004 [3]=00000008
  pod_node [0]=0 [1]=0 [2]=1 [3]=1
  cpu_pod  [0]=0 [1]=1 [2]=2 [3]=3

SMT
  nr_pods  4
  pod_cpus [0]=00000001 [1]=00000002 [2]=00000004 [3]=00000008
  pod_node [0]=0 [1]=0 [2]=1 [3]=1
  cpu_pod  [0]=0 [1]=1 [2]=2 [3]=3

CACHE (default)
  nr_pods  2
  pod_cpus [0]=00000003 [1]=0000000c
  pod_node [0]=0 [1]=1
  cpu_pod  [0]=0 [1]=0 [2]=1 [3]=1

NUMA
  nr_pods  2
  pod_cpus [0]=00000003 [1]=0000000c
  pod_node [0]=0 [1]=1
  cpu_pod  [0]=0 [1]=0 [2]=1 [3]=1

SYSTEM
  nr_pods  1
  pod_cpus [0]=0000000f
  pod_node [0]=-1
  cpu_pod  [0]=0 [1]=0 [2]=0 [3]=0

Worker Pools
============
pool[00] ref= 1 nice=  0 idle/workers=  4/  4 cpu=  0
pool[01] ref= 1 nice=-20 idle/workers=  2/  2 cpu=  0
pool[02] ref= 1 nice=  0 idle/workers=  4/  4 cpu=  1
pool[03] ref= 1 nice=-20 idle/workers=  2/  2 cpu=  1
pool[04] ref= 1 nice=  0 idle/workers=  4/  4 cpu=  2
pool[05] ref= 1 nice=-20 idle/workers=  2/  2 cpu=  2
pool[06] ref= 1 nice=  0 idle/workers=  3/  3 cpu=  3
pool[07] ref= 1 nice=-20 idle/workers=  2/  2 cpu=  3
pool[08] ref=42 nice=  0 idle/workers=  6/  6 cpus=0000000f
pool[09] ref=28 nice=  0 idle/workers=  3/  3 cpus=00000003
pool[10] ref=28 nice=  0 idle/workers= 17/ 17 cpus=0000000c
pool[11] ref= 1 nice=-20 idle/workers=  1/  1 cpus=0000000f
pool[12] ref= 2 nice=-20 idle/workers=  1/  1 cpus=00000003
pool[13] ref= 2 nice=-20 idle/workers=  1/  1 cpus=0000000c

Workqueue CPU -> pool
=====================
[    workqueue \ CPU              0  1  2  3 dfl]
events                   percpu   0  2  4  6
events_highpri           percpu   1  3  5  7
events_long              percpu   0  2  4  6
events_unbound           unbound  9  9 10 10  8
events_freezable         percpu   0  2  4  6
events_power_efficient   percpu   0  2  4  6
events_freezable_pwr_ef  percpu   0  2  4  6
rcu_gp                   percpu   0  2  4  6
rcu_par_gp               percpu   0  2  4  6
slub_flushwq             percpu   0  2  4  6
netns                    ordered  8  8  8  8  8
...
```

See the command's help message for more info.

<a id="rst-monitoring"></a>

## Monitoring

Use tools/workqueue/wq_monitor.py to monitor workqueue operations:



```text
$ tools/workqueue/wq_monitor.py events
                            total  infl  CPUtime  CPUhog CMW/RPR  mayday rescued
events                      18545     0      6.1       0       5       -       -
events_highpri                  8     0      0.0       0       0       -       -
events_long                     3     0      0.0       0       0       -       -
events_unbound              38306     0      0.1       -       7       -       -
events_freezable                0     0      0.0       0       0       -       -
events_power_efficient      29598     0      0.2       0       0       -       -
events_freezable_pwr_ef        10     0      0.0       0       0       -       -
sock_diag_events                0     0      0.0       0       0       -       -

                            total  infl  CPUtime  CPUhog CMW/RPR  mayday rescued
events                      18548     0      6.1       0       5       -       -
events_highpri                  8     0      0.0       0       0       -       -
events_long                     3     0      0.0       0       0       -       -
events_unbound              38322     0      0.1       -       7       -       -
events_freezable                0     0      0.0       0       0       -       -
events_power_efficient      29603     0      0.2       0       0       -       -
events_freezable_pwr_ef        10     0      0.0       0       0       -       -
sock_diag_events                0     0      0.0       0       0       -       -

...
```

See the command's help message for more info.

<a id="rst-debugging"></a>

## Debugging

Because the work functions are executed by generic worker threads there are a few tricks needed to shed some light on misbehaving workqueue users.

Worker threads show up in the process list as:



```text
root      5671  0.0  0.0      0     0 ?        S    12:07   0:00 [kworker/0:1]
root      5672  0.0  0.0      0     0 ?        S    12:07   0:00 [kworker/1:2]
root      5673  0.0  0.0      0     0 ?        S    12:12   0:00 [kworker/0:0]
root      5674  0.0  0.0      0     0 ?        S    12:13   0:00 [kworker/1:0]
```

If kworkers are going crazy (using too much cpu), there are two types of possible problems:

> 1. Something being scheduled in rapid succession
>
> 2. A single work item that consumes lots of cpu cycles

The first one can be tracked using tracing:



```text
$ echo workqueue:workqueue_queue_work > /sys/kernel/tracing/set_event
$ cat /sys/kernel/tracing/trace_pipe > out.txt
(wait a few secs)
^C
```

If something is busy looping on work queueing, it would be dominating the output and the offender can be determined with the work item function.

For the second type of problems it should be possible to just check the stack trace of the offending worker thread.



```text
$ cat /proc/THE_OFFENDING_KWORKER/stack
```

The work item's function should be trivially visible in the stack trace.

<a id="rst-non-reentrance-conditions"></a>

## Non-reentrance Conditions

Workqueue guarantees that a work item cannot be re-entrant if the following conditions hold after a work item gets queued:

> 1. The work function hasn't been changed.
>
> 2. No one queues the work item to another workqueue.
>
> 3. The work item hasn't been reinitiated.

In other words, if the above conditions hold, the work item is guaranteed to be executed by at most one worker system-wide at any given time.

Note that requeuing the work item (to the same queue) in the self function doesn't break these conditions, so it's safe to do. Otherwise, caution is required when breaking the conditions inside a work function.

<a id="rst-kernel-inline-documentations-reference"></a>

## Kernel Inline Documentations Reference


#### <a id="c-struct-workqueue_attrs"></a>`struct workqueue_attrs`

A struct for workqueue attributes.

**Definition**

```c
struct workqueue_attrs {
    int nice;
    cpumask_var_t cpumask;
    cpumask_var_t __pod_cpumask;
    bool affn_strict;
    enum wq_affn_scope affn_scope;
    bool ordered;
};
```

**Members**

- `nice`: nice level
- `cpumask`: allowed CPUs

  Work items in this workqueue are affine to these CPUs and not allowed
  to execute on other CPUs. A pool serving a workqueue must have the
  same **cpumask**.
- `__pod_cpumask`: internal attribute used to create per-pod pools

  Internal use only.

  Per-pod unbound worker pools are used to improve locality. Always a
  subset of ->cpumask. A workqueue can be associated with multiple
  worker pools with disjoint **__pod_cpumask**'s. Whether the enforcement
  of a pool's **__pod_cpumask** is strict depends on **affn_strict**.
- `affn_strict`: affinity scope is strict

  If clear, workqueue will make a best-effort attempt at starting the
  worker inside **__pod_cpumask** but the scheduler is free to migrate it
  outside.

  If set, workers are only allowed to run inside **__pod_cpumask**.
- `affn_scope`: unbound CPU affinity scope

  CPU pods are used to improve execution locality of unbound work
  items. There are multiple pod types, one for each wq_affn_scope, and
  every CPU in the system belongs to one pod in every pod type. CPUs
  that belong to the same pod share the worker pool. For example,
  selecting `WQ_AFFN_NUMA` makes the workqueue use a separate worker
  pool for each NUMA node.
- `ordered`: work items must be executed one by one in queueing order

**Description**

This can be used to change attributes of an unbound workqueue.

#### <a id="c-work_pending"></a>`work_pending()`

```c
work_pending(work)
```

Find out whether a work item is currently pending

**Parameters**

- `work`: The work item in question

#### <a id="c-delayed_work_pending"></a>`delayed_work_pending()`

```c
delayed_work_pending(w)
```

Find out whether a delayable work item is currently pending

**Parameters**

- `w`: The work item in question

#### <a id="c-alloc_workqueue"></a>`alloc_workqueue()`

```c
struct workqueue_struct * alloc_workqueue(const char *fmt, unsigned int flags, int max_active, ...)
```

allocate a workqueue

**Parameters**

- `const char *fmt`: printf format for the name of the workqueue
- `unsigned int flags`: WQ_* flags
- `int max_active`: max in-flight work items, 0 for default
- `...`: args for **fmt**

**Description**

For a per-cpu workqueue, **max_active** limits the number of in-flight work
items for each CPU. e.g. **max_active** of 1 indicates that each CPU can be
executing at most one work item for the workqueue.

For unbound workqueues, **max_active** limits the number of in-flight work items
for the whole system. e.g. **max_active** of 16 indicates that there can be
at most 16 work items executing for the workqueue in the whole system.

As sharing the same active counter for an unbound workqueue across multiple
NUMA nodes can be expensive, **max_active** is distributed to each NUMA node
according to the proportion of the number of online CPUs and enforced
independently.

Depending on online CPU distribution, a node may end up with per-node
max_active which is significantly lower than **max_active**, which can lead to
deadlocks if the per-node concurrency limit is lower than the maximum number
of interdependent work items for the workqueue.

To guarantee forward progress regardless of online CPU distribution, the
concurrency limit on every node is guaranteed to be equal to or greater than
min_active which is set to min(**max_active**, `WQ_DFL_MIN_ACTIVE`). This means
that the sum of per-node max_active's may be larger than **max_active**.

For detailed information on `WQ_`\* flags, please refer to
Documentation/core-api/workqueue.rst.

**Return**

Pointer to the allocated workqueue on success, `NULL` on failure.

#### <a id="c-alloc_workqueue_lockdep_map"></a>`alloc_workqueue_lockdep_map()`

```c
struct workqueue_struct * alloc_workqueue_lockdep_map(const char *fmt, unsigned int flags, int max_active, struct lockdep_map *lockdep_map, ...)
```

allocate a workqueue with user-defined lockdep_map

**Parameters**

- `const char *fmt`: printf format for the name of the workqueue
- `unsigned int flags`: WQ_* flags
- `int max_active`: max in-flight work items, 0 for default
- `struct lockdep_map *lockdep_map`: user-defined lockdep_map
- `...`: args for **fmt**

**Description**

Same as alloc_workqueue but with the a user-define lockdep_map. Useful for
workqueues created with the same purpose and to avoid leaking a lockdep_map
on each workqueue creation.

**Return**

Pointer to the allocated workqueue on success, `NULL` on failure.

#### <a id="c-alloc_ordered_workqueue_lockdep_map"></a>`alloc_ordered_workqueue_lockdep_map()`

```c
alloc_ordered_workqueue_lockdep_map(fmt, flags, lockdep_map, args...)
```

allocate an ordered workqueue with user-defined lockdep_map

**Parameters**

- `fmt`: printf format for the name of the workqueue
- `flags`: WQ_* flags (only WQ_FREEZABLE and WQ_MEM_RECLAIM are meaningful)
- `lockdep_map`: user-defined lockdep_map
- `args...`: args for **fmt**

**Description**

Same as alloc_ordered_workqueue but with the a user-define lockdep_map.
Useful for workqueues created with the same purpose and to avoid leaking a
lockdep_map on each workqueue creation.

**Return**

Pointer to the allocated workqueue on success, `NULL` on failure.

#### <a id="c-alloc_ordered_workqueue"></a>`alloc_ordered_workqueue()`

```c
alloc_ordered_workqueue(fmt, flags, args...)
```

allocate an ordered workqueue

**Parameters**

- `fmt`: printf format for the name of the workqueue
- `flags`: WQ_* flags (only WQ_FREEZABLE and WQ_MEM_RECLAIM are meaningful)
- `args...`: args for **fmt**

**Description**

Allocate an ordered workqueue.  An ordered workqueue executes at
most one work item at any given time in the queued order.  They are
implemented as unbound workqueues with **max_active** of one.

**Return**

Pointer to the allocated workqueue on success, `NULL` on failure.

#### <a id="c-queue_work"></a>`queue_work()`

```c
bool queue_work(struct workqueue_struct *wq, struct work_struct *work)
```

queue work on a workqueue

**Parameters**

- `struct workqueue_struct *wq`: workqueue to use
- `struct work_struct *work`: work to queue

**Description**

Returns `false` if **work** was already on a queue, `true` otherwise.

We queue the work to the CPU on which it was submitted, but if the CPU dies
it can be processed by another CPU.

Memory-ordering properties:  If it returns `true`, guarantees that all stores
preceding the call to [`queue_work()`](#c-queue_work) in the program order will be visible from
the CPU which will execute **work** by the time such work executes, e.g.,

{ x is initially 0 }

CPU0                               CPU1

WRITE_ONCE(x, 1);                  \[ **work** is being executed \]
r0 = queue_work(wq, work);           r1 = READ_ONCE(x);

Forbids: r0 == true && r1 == 0

#### <a id="c-queue_delayed_work"></a>`queue_delayed_work()`

```c
bool queue_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay)
```

queue work on a workqueue after delay

**Parameters**

- `struct workqueue_struct *wq`: workqueue to use
- `struct delayed_work *dwork`: delayable work to queue
- `unsigned long delay`: number of jiffies to wait before queueing

**Description**

Equivalent to [`queue_delayed_work_on()`](#c-queue_delayed_work_on) but tries to use the local CPU.

#### <a id="c-mod_delayed_work"></a>`mod_delayed_work()`

```c
bool mod_delayed_work(struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay)
```

modify delay of or queue a delayed work

**Parameters**

- `struct workqueue_struct *wq`: workqueue to use
- `struct delayed_work *dwork`: work to queue
- `unsigned long delay`: number of jiffies to wait before queueing

**Description**

[`mod_delayed_work_on()`](#c-mod_delayed_work_on) on local CPU.

#### <a id="c-schedule_work_on"></a>`schedule_work_on()`

```c
bool schedule_work_on(int cpu, struct work_struct *work)
```

put work task on a specific cpu

**Parameters**

- `int cpu`: cpu to put the work task on
- `struct work_struct *work`: job to be done

**Description**

This puts a job on a specific cpu

#### <a id="c-schedule_work"></a>`schedule_work()`

```c
bool schedule_work(struct work_struct *work)
```

put work task in global workqueue

**Parameters**

- `struct work_struct *work`: job to be done

**Description**

Returns `false` if **work** was already on the kernel-global workqueue and
`true` otherwise.

This puts a job in the kernel-global workqueue if it was not already
queued and leaves it in the same position on the kernel-global
workqueue otherwise.

Shares the same memory-ordering properties of [`queue_work()`](#c-queue_work), cf. the
DocBook header of [`queue_work()`](#c-queue_work).

#### <a id="c-enable_and_queue_work"></a>`enable_and_queue_work()`

```c
bool enable_and_queue_work(struct workqueue_struct *wq, struct work_struct *work)
```

Enable and queue a work item on a specific workqueue

**Parameters**

- `struct workqueue_struct *wq`: The target workqueue
- `struct work_struct *work`: The work item to be enabled and queued

**Description**

This function combines the operations of [`enable_work()`](#c-enable_work) and [`queue_work()`](#c-queue_work),
providing a convenient way to enable and queue a work item in a single call.
It invokes [`enable_work()`](#c-enable_work) on **work** and then queues it if the disable depth
reached 0. Returns `true` if the disable depth reached 0 and **work** is queued,
and `false` otherwise.

Note that **work** is always queued when disable depth reaches zero. If the
desired behavior is queueing only if certain events took place while **work** is
disabled, the user should implement the necessary state tracking and perform
explicit conditional queueing after [`enable_work()`](#c-enable_work).

#### <a id="c-schedule_delayed_work_on"></a>`schedule_delayed_work_on()`

```c
bool schedule_delayed_work_on(int cpu, struct delayed_work *dwork, unsigned long delay)
```

queue work in global workqueue on CPU after delay

**Parameters**

- `int cpu`: cpu to use
- `struct delayed_work *dwork`: job to be done
- `unsigned long delay`: number of jiffies to wait

**Description**

After waiting for a given time this puts a job in the kernel-global
workqueue on the specified CPU.

#### <a id="c-schedule_delayed_work"></a>`schedule_delayed_work()`

```c
bool schedule_delayed_work(struct delayed_work *dwork, unsigned long delay)
```

put work task in global workqueue after delay

**Parameters**

- `struct delayed_work *dwork`: job to be done
- `unsigned long delay`: number of jiffies to wait or 0 for immediate execution

**Description**

After waiting for a given time this puts a job in the kernel-global
workqueue.



#### <a id="c-for_each_pool"></a>`for_each_pool()`

```c
for_each_pool(pool, pi)
```

iterate through all worker_pools in the system

**Parameters**

- `pool`: iteration cursor
- `pi`: integer used for iteration

**Description**

This must be called either with wq_pool_mutex held or RCU read
locked.  If the pool needs to be used beyond the locking in effect, the
caller is responsible for guaranteeing that the pool stays online.

The if/else clause exists only for the lockdep assertion and can be
ignored.

#### <a id="c-for_each_pool_worker"></a>`for_each_pool_worker()`

```c
for_each_pool_worker(worker, pool)
```

iterate through all workers of a worker_pool

**Parameters**

- `worker`: iteration cursor
- `pool`: worker_pool to iterate workers of

**Description**

This must be called with wq_pool_attach_mutex.

The if/else clause exists only for the lockdep assertion and can be
ignored.

#### <a id="c-for_each_pwq"></a>`for_each_pwq()`

```c
for_each_pwq(pwq, wq)
```

iterate through all pool_workqueues of the specified workqueue

**Parameters**

- `pwq`: iteration cursor
- `wq`: the target workqueue

**Description**

This must be called either with wq->mutex held or RCU read locked.
If the pwq needs to be used beyond the locking in effect, the caller is
responsible for guaranteeing that the pwq stays online.

The if/else clause exists only for the lockdep assertion and can be
ignored.

#### <a id="c-worker_pool_assign_id"></a>`worker_pool_assign_id()`

```c
int worker_pool_assign_id(struct worker_pool *pool)
```

allocate ID and assign it to **pool**

**Parameters**

- `struct worker_pool *pool`: the pool pointer of interest

**Description**

Returns 0 if ID in \[0, WORK_OFFQ_POOL_NONE) is allocated and assigned
successfully, -errno on failure.

#### <a id="c-unbound_effective_cpumask"></a>`unbound_effective_cpumask()`

```c
struct cpumask * unbound_effective_cpumask(struct workqueue_struct *wq)
```

effective cpumask of an unbound workqueue

**Parameters**

- `struct workqueue_struct *wq`: workqueue of interest

**Description**

**wq->unbound_attrs->cpumask** contains the cpumask requested by the user which
is masked with wq_unbound_cpumask to determine the effective cpumask. The
default pwq is always mapped to the pool with the current effective cpumask.

#### <a id="c-get_work_pool"></a>`get_work_pool()`

```c
struct worker_pool * get_work_pool(struct work_struct *work)
```

return the worker_pool a given work was associated with

**Parameters**

- `struct work_struct *work`: the work item of interest

**Description**

Pools are created and destroyed under wq_pool_mutex, and allows read
access under RCU read lock.  As such, this function should be
called under wq_pool_mutex or inside of a [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) region.

All fields of the returned pool are accessible as long as the above
mentioned locking is in effect.  If the returned pool needs to be used
beyond the critical section, the caller is responsible for ensuring the
returned pool is and stays online.

**Return**

The worker_pool **work** was last associated with.  `NULL` if none.

#### <a id="c-worker_set_flags"></a>`worker_set_flags()`

```c
void worker_set_flags(struct worker *worker, unsigned int flags)
```

set worker flags and adjust nr_running accordingly

**Parameters**

- `struct worker *worker`: self
- `unsigned int flags`: flags to set

**Description**

Set **flags** in **worker->flags** and adjust nr_running accordingly.

#### <a id="c-worker_clr_flags"></a>`worker_clr_flags()`

```c
void worker_clr_flags(struct worker *worker, unsigned int flags)
```

clear worker flags and adjust nr_running accordingly

**Parameters**

- `struct worker *worker`: self
- `unsigned int flags`: flags to clear

**Description**

Clear **flags** in **worker->flags** and adjust nr_running accordingly.

#### <a id="c-worker_enter_idle"></a>`worker_enter_idle()`

```c
void worker_enter_idle(struct worker *worker)
```

enter idle state

**Parameters**

- `struct worker *worker`: worker which is entering idle state

**Description**

**worker** is entering idle state.  Update stats and idle timer if
necessary.

LOCKING:
raw_spin_lock_irq(pool->lock).

#### <a id="c-worker_leave_idle"></a>`worker_leave_idle()`

```c
void worker_leave_idle(struct worker *worker)
```

leave idle state

**Parameters**

- `struct worker *worker`: worker which is leaving idle state

**Description**

**worker** is leaving idle state.  Update stats.

LOCKING:
raw_spin_lock_irq(pool->lock).

#### <a id="c-find_worker_executing_work"></a>`find_worker_executing_work()`

```c
struct worker * find_worker_executing_work(struct worker_pool *pool, struct work_struct *work)
```

find worker which is executing a work

**Parameters**

- `struct worker_pool *pool`: pool of interest
- `struct work_struct *work`: work to find worker for

**Description**

Find a worker which is executing **work** on **pool** by searching
**pool->busy_hash** which is keyed by the address of **work**.  For a worker
to match, its current execution should match the address of **work** and
its work function.  This is to avoid unwanted dependency between
unrelated work executions through a work item being recycled while still
being executed.

This is a bit tricky.  A work item may be freed once its execution
starts and nothing prevents the freed area from being recycled for
another work item.  If the same work item address ends up being reused
before the original execution finishes, workqueue will identify the
recycled work item as currently executing and make it wait until the
current execution finishes, introducing an unwanted dependency.

This function checks the work item address and work function to avoid
false positives.  Note that this isn't complete as one may construct a
work function which can introduce dependency onto itself through a
recycled work item.  Well, if somebody wants to shoot oneself in the
foot that badly, there's only so much we can do, and if such deadlock
actually occurs, it should be easy to locate the culprit work function.

**Context**

raw_spin_lock_irq(pool->lock).

**Return**

Pointer to worker which is executing **work** if found, `NULL`
otherwise.

#### <a id="c-move_linked_works"></a>`move_linked_works()`

```c
void move_linked_works(struct work_struct *work, struct list_head *head, struct work_struct **nextp)
```

move linked works to a list

**Parameters**

- `struct work_struct *work`: start of series of works to be scheduled
- `struct list_head *head`: target list to append **work** to
- `struct work_struct **nextp`: out parameter for nested worklist walking

**Description**

Schedule linked works starting from **work** to **head**. Work series to be
scheduled starts at **work** and includes any consecutive work with
WORK_STRUCT_LINKED set in its predecessor. See [`assign_work()`](#c-assign_work) for details on
**nextp**.

**Context**

raw_spin_lock_irq(pool->lock).

#### <a id="c-assign_work"></a>`assign_work()`

```c
bool assign_work(struct work_struct *work, struct worker *worker, struct work_struct **nextp)
```

assign a work item and its linked work items to a worker

**Parameters**

- `struct work_struct *work`: work to assign
- `struct worker *worker`: worker to assign to
- `struct work_struct **nextp`: out parameter for nested worklist walking

**Description**

Assign **work** and its linked work items to **worker**. If **work** is already being
executed by another worker in the same pool, it'll be punted there.

If **nextp** is not NULL, it's updated to point to the next work of the last
scheduled work. This allows [`assign_work()`](#c-assign_work) to be nested inside
[`list_for_each_entry_safe()`](/kernel/internals/core-api/list.md#c-list_for_each_entry_safe).

Returns `true` if **work** was successfully assigned to **worker**. `false` if **work**
was punted to another worker already executing it.

#### <a id="c-kick_pool"></a>`kick_pool()`

```c
bool kick_pool(struct worker_pool *pool)
```

wake up an idle worker if necessary

**Parameters**

- `struct worker_pool *pool`: pool to kick

**Description**

**pool** may have pending work items. Wake up worker if necessary. Returns
whether a worker was woken up.

#### <a id="c-wq_worker_running"></a>`wq_worker_running()`

```c
void wq_worker_running(struct task_struct *task)
```

a worker is running again

**Parameters**

- `struct task_struct *task`: task waking up

**Description**

This function is called when a worker returns from `schedule()`

#### <a id="c-wq_worker_sleeping"></a>`wq_worker_sleeping()`

```c
void wq_worker_sleeping(struct task_struct *task)
```

a worker is going to sleep

**Parameters**

- `struct task_struct *task`: task going to sleep

**Description**

This function is called from `schedule()` when a busy worker is
going to sleep.

#### <a id="c-wq_worker_tick"></a>`wq_worker_tick()`

```c
void wq_worker_tick(struct task_struct *task)
```

a scheduler tick occurred while a kworker is running

**Parameters**

- `struct task_struct *task`: task currently running

**Description**

Called from `sched_tick()`. We're in the IRQ context and the current
worker's fields which follow the 'K' locking rule can be accessed safely.

#### <a id="c-wq_worker_last_func"></a>`wq_worker_last_func()`

```c
work_func_t wq_worker_last_func(struct task_struct *task)
```

retrieve worker's last work function

**Parameters**

- `struct task_struct *task`: Task to retrieve last work function of.

**Description**

Determine the last function a worker executed. This is called from
the scheduler to get a worker's last known identity.

This function is called during `schedule()` when a kworker is going
to sleep. It's used by psi to identify aggregation workers during
dequeuing, to allow periodic aggregation to shut-off when that
worker is the last task in the system or cgroup to go to sleep.

As this function doesn't involve any workqueue-related locking, it
only returns stable values when called from inside the scheduler's
queuing and dequeuing paths, when **task**, which must be a kworker,
is guaranteed to not be processing any works.

**Context**

raw_spin_lock_irq(rq->lock)

**Return**

The last work function `current` executed as a worker, NULL if it
hasn't executed any work yet.

#### <a id="c-wq_node_nr_active"></a>`wq_node_nr_active()`

```c
struct wq_node_nr_active * wq_node_nr_active(struct workqueue_struct *wq, int node)
```

Determine wq_node_nr_active to use

**Parameters**

- `struct workqueue_struct *wq`: workqueue of interest
- `int node`: NUMA node, can be `NUMA_NO_NODE`

**Description**

Determine wq_node_nr_active to use for **wq** on **node**. Returns:

- `NULL` for per-cpu workqueues as they don't need to use shared nr_active.

- node_nr_active\[nr_node_ids\] if **node** is `NUMA_NO_NODE`.

- Otherwise, node_nr_active\[**node**\].

#### <a id="c-wq_update_node_max_active"></a>`wq_update_node_max_active()`

```c
void wq_update_node_max_active(struct workqueue_struct *wq, int off_cpu)
```

Update per-node max_actives to use

**Parameters**

- `struct workqueue_struct *wq`: workqueue to update
- `int off_cpu`: CPU that's going down, -1 if a CPU is not going down

**Description**

Update **wq->node_nr_active**\[\]->max. **wq** must be unbound. max_active is
distributed among nodes according to the proportions of numbers of online
cpus. The result is always between **wq->min_active** and max_active.

#### <a id="c-get_pwq"></a>`get_pwq()`

```c
void get_pwq(struct pool_workqueue *pwq)
```

get an extra reference on the specified pool_workqueue

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue to get

**Description**

Obtain an extra reference on **pwq**.  The caller should guarantee that
**pwq** has positive refcnt and be holding the matching pool->lock.

#### <a id="c-put_pwq"></a>`put_pwq()`

```c
void put_pwq(struct pool_workqueue *pwq)
```

put a pool_workqueue reference

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue to put

**Description**

Drop a reference of **pwq**.  If its refcnt reaches zero, schedule its
destruction.  The caller should be holding the matching pool->lock.

#### <a id="c-put_pwq_unlocked"></a>`put_pwq_unlocked()`

```c
void put_pwq_unlocked(struct pool_workqueue *pwq)
```

[`put_pwq()`](#c-put_pwq) with surrounding pool lock/unlock

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue to put (can be `NULL`)

**Description**

[`put_pwq()`](#c-put_pwq) with locking.  This function also allows `NULL` **pwq**.

#### <a id="c-pwq_tryinc_nr_active"></a>`pwq_tryinc_nr_active()`

```c
bool pwq_tryinc_nr_active(struct pool_workqueue *pwq, bool fill)
```

Try to increment nr_active for a pwq

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue of interest
- `bool fill`: max_active may have increased, try to increase concurrency level

**Description**

Try to increment nr_active for **pwq**. Returns `true` if an nr_active count is
successfully obtained. `false` otherwise.

#### <a id="c-pwq_activate_first_inactive"></a>`pwq_activate_first_inactive()`

```c
bool pwq_activate_first_inactive(struct pool_workqueue *pwq, bool fill)
```

Activate the first inactive work item on a pwq

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue of interest
- `bool fill`: max_active may have increased, try to increase concurrency level

**Description**

Activate the first inactive work item of **pwq** if available and allowed by
max_active limit.

Returns `true` if an inactive work item has been activated. `false` if no
inactive work item is found or max_active limit is reached.

#### <a id="c-unplug_oldest_pwq"></a>`unplug_oldest_pwq()`

```c
void unplug_oldest_pwq(struct workqueue_struct *wq)
```

unplug the oldest pool_workqueue

**Parameters**

- `struct workqueue_struct *wq`: workqueue_struct where its oldest pwq is to be unplugged

**Description**

This function should only be called for ordered workqueues where only the
oldest pwq is unplugged, the others are plugged to suspend execution to
ensure proper work item ordering:

```text
dfl_pwq --------------+     [P] - plugged
                      |
                      v
pwqs -> A -> B [P] -> C [P] (newest)
        |    |        |
        1    3        5
        |    |        |
        2    4        6
```

When the oldest pwq is drained and removed, this function should be called
to unplug the next oldest one to start its work item execution. Note that
pwq's are linked into wq->pwqs with the oldest first, so the first one in
the list is the oldest.

#### <a id="c-node_activate_pending_pwq"></a>`node_activate_pending_pwq()`

```c
void node_activate_pending_pwq(struct wq_node_nr_active *nna, struct worker_pool *caller_pool)
```

Activate a pending pwq on a wq_node_nr_active

**Parameters**

- `struct wq_node_nr_active *nna`: wq_node_nr_active to activate a pending pwq for
- `struct worker_pool *caller_pool`: worker_pool the caller is locking

**Description**

Activate a pwq in **nna->pending_pwqs**. Called with **caller_pool** locked.
**caller_pool** may be unlocked and relocked to lock other worker_pools.

#### <a id="c-pwq_dec_nr_active"></a>`pwq_dec_nr_active()`

```c
void pwq_dec_nr_active(struct pool_workqueue *pwq)
```

Retire an active count

**Parameters**

- `struct pool_workqueue *pwq`: pool_workqueue of interest

**Description**

Decrement **pwq**'s nr_active and try to activate the first inactive work item.
For unbound workqueues, this function may temporarily drop **pwq->pool->lock**.

#### <a id="c-pwq_dec_nr_in_flight"></a>`pwq_dec_nr_in_flight()`

```c
void pwq_dec_nr_in_flight(struct pool_workqueue *pwq, unsigned long work_data)
```

decrement pwq's nr_in_flight

**Parameters**

- `struct pool_workqueue *pwq`: pwq of interest
- `unsigned long work_data`: work_data of work which left the queue

**Description**

A work either has completed or is removed from pending queue,
decrement nr_in_flight of its pwq and handle workqueue flushing.

**NOTE**

For unbound workqueues, this function may temporarily drop **pwq->pool->lock**
and thus should be called after all other state updates for the in-flight
work item is complete.

**Context**

raw_spin_lock_irq(pool->lock).

#### <a id="c-try_to_grab_pending"></a>`try_to_grab_pending()`

```c
int try_to_grab_pending(struct work_struct *work, u32 cflags, unsigned long *irq_flags)
```

steal work item from worklist and disable irq

**Parameters**

- `struct work_struct *work`: work item to steal
- `u32 cflags`: `WORK_CANCEL_` flags
- `unsigned long *irq_flags`: place to store irq state

**Description**

Try to grab PENDING bit of **work**.  This function can handle **work** in any
stable state - idle, on timer or on worklist.

```text
========    ================================================================
1           if @work was pending and we successfully stole PENDING
0           if @work was idle and we claimed PENDING
-EAGAIN     if PENDING couldn't be grabbed at the moment, safe to busy-retry
========    ================================================================
```

**Note**

On >= 0 return, the caller owns **work**'s PENDING bit.  To avoid getting
interrupted while holding PENDING and **work** off queue, irq must be
disabled on entry.  This, combined with delayed_work->timer being
irqsafe, ensures that we return -EAGAIN for finite short period of time.

On successful return, >= 0, irq is disabled and the caller is
responsible for releasing it using local_irq_restore(**\*irq_flags**).

This function is safe to call from any context including IRQ handler.

#### <a id="c-work_grab_pending"></a>`work_grab_pending()`

```c
bool work_grab_pending(struct work_struct *work, u32 cflags, unsigned long *irq_flags)
```

steal work item from worklist and disable irq

**Parameters**

- `struct work_struct *work`: work item to steal
- `u32 cflags`: `WORK_CANCEL_` flags
- `unsigned long *irq_flags`: place to store IRQ state

**Description**

Grab PENDING bit of **work**. **work** can be in any stable state - idle, on timer
or on worklist.

Can be called from any context. IRQ is disabled on return with IRQ state
stored in **\*irq_flags**. The caller is responsible for re-enabling it using
`local_irq_restore()`.

Returns `true` if **work** was pending. `false` if idle.

#### <a id="c-insert_work"></a>`insert_work()`

```c
void insert_work(struct pool_workqueue *pwq, struct work_struct *work, struct list_head *head, unsigned int extra_flags)
```

insert a work into a pool

**Parameters**

- `struct pool_workqueue *pwq`: pwq **work** belongs to
- `struct work_struct *work`: work to insert
- `struct list_head *head`: insertion point
- `unsigned int extra_flags`: extra WORK_STRUCT_* flags to set

**Description**

Insert **work** which belongs to **pwq** after **head**.  **extra_flags** is or'd to
work_struct flags.

**Context**

raw_spin_lock_irq(pool->lock).

#### <a id="c-queue_work_on"></a>`queue_work_on()`

```c
bool queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work)
```

queue work on specific cpu

**Parameters**

- `int cpu`: CPU number to execute work on
- `struct workqueue_struct *wq`: workqueue to use
- `struct work_struct *work`: work to queue

**Description**

We queue the work to a specific CPU, the caller must ensure it
can't go away.  Callers that fail to ensure that the specified
CPU cannot go away will execute on a randomly chosen CPU.
But note well that callers specifying a CPU that never has been
online will get a splat.

**Return**

`false` if **work** was already on a queue, `true` otherwise.

#### <a id="c-select_numa_node_cpu"></a>`select_numa_node_cpu()`

```c
int select_numa_node_cpu(int node)
```

Select a CPU based on NUMA node

**Parameters**

- `int node`: NUMA node ID that we want to select a CPU from

**Description**

This function will attempt to find a "random" cpu available on a given
node. If there are no CPUs available on the given node it will return
WORK_CPU_UNBOUND indicating that we should just schedule to any
available CPU if we need to schedule this work.

#### <a id="c-queue_work_node"></a>`queue_work_node()`

```c
bool queue_work_node(int node, struct workqueue_struct *wq, struct work_struct *work)
```

queue work on a "random" cpu for a given NUMA node

**Parameters**

- `int node`: NUMA node that we are targeting the work for
- `struct workqueue_struct *wq`: workqueue to use
- `struct work_struct *work`: work to queue

**Description**

We queue the work to a "random" CPU within a given NUMA node. The basic
idea here is to provide a way to somehow associate work with a given
NUMA node.

This function will only make a best effort attempt at getting this onto
the right NUMA node. If no node is requested or the requested node is
offline then we just fall back to standard queue_work behavior.

Currently the "random" CPU ends up being the first available CPU in the
intersection of cpu_online_mask and the cpumask of the node, unless we
are running on the node. In that case we just use the current CPU.

**Return**

`false` if **work** was already on a queue, `true` otherwise.

#### <a id="c-queue_delayed_work_on"></a>`queue_delayed_work_on()`

```c
bool queue_delayed_work_on(int cpu, struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay)
```

queue work on specific CPU after delay

**Parameters**

- `int cpu`: CPU number to execute work on
- `struct workqueue_struct *wq`: workqueue to use
- `struct delayed_work *dwork`: work to queue
- `unsigned long delay`: number of jiffies to wait before queueing

**Description**

We queue the delayed_work to a specific CPU, for non-zero delays the
caller must ensure it is online and can't go away. Callers that fail
to ensure this, may get **dwork->timer** queued to an offlined CPU and
this will prevent queueing of **dwork->work** unless the offlined CPU
becomes online again.

**Return**

`false` if **work** was already on a queue, `true` otherwise.  If
**delay** is zero and **dwork** is idle, it will be scheduled for immediate
execution.

#### <a id="c-mod_delayed_work_on"></a>`mod_delayed_work_on()`

```c
bool mod_delayed_work_on(int cpu, struct workqueue_struct *wq, struct delayed_work *dwork, unsigned long delay)
```

modify delay of or queue a delayed work on specific CPU

**Parameters**

- `int cpu`: CPU number to execute work on
- `struct workqueue_struct *wq`: workqueue to use
- `struct delayed_work *dwork`: work to queue
- `unsigned long delay`: number of jiffies to wait before queueing

**Description**

If **dwork** is idle, equivalent to [`queue_delayed_work_on()`](#c-queue_delayed_work_on); otherwise,
modify **dwork**'s timer so that it expires after **delay**.  If **delay** is
zero, **work** is guaranteed to be scheduled immediately regardless of its
current state.

This function is safe to call from any context including IRQ handler.
See [`try_to_grab_pending()`](#c-try_to_grab_pending) for details.

**Return**

`false` if **dwork** was idle and queued, `true` if **dwork** was
pending and its timer was modified.

#### <a id="c-queue_rcu_work"></a>`queue_rcu_work()`

```c
bool queue_rcu_work(struct workqueue_struct *wq, struct rcu_work *rwork)
```

queue work after a RCU grace period

**Parameters**

- `struct workqueue_struct *wq`: workqueue to use
- `struct rcu_work *rwork`: work to queue

**Return**

`false` if **rwork** was already pending, `true` otherwise.  Note
that a full RCU grace period is guaranteed only after a `true` return.
While **rwork** is guaranteed to be executed after a `false` return, the
execution may happen before a full RCU grace period has passed.

#### <a id="c-worker_attach_to_pool"></a>`worker_attach_to_pool()`

```c
void worker_attach_to_pool(struct worker *worker, struct worker_pool *pool)
```

attach a worker to a pool

**Parameters**

- `struct worker *worker`: worker to be attached
- `struct worker_pool *pool`: the target pool

**Description**

Attach **worker** to **pool**.  Once attached, the `WORKER_UNBOUND` flag and
cpu-binding of **worker** are kept coordinated with the pool across
cpu-\[un\]hotplugs.

#### <a id="c-worker_detach_from_pool"></a>`worker_detach_from_pool()`

```c
void worker_detach_from_pool(struct worker *worker)
```

detach a worker from its pool

**Parameters**

- `struct worker *worker`: worker which is attached to its pool

**Description**

Undo the attaching which had been done in [`worker_attach_to_pool()`](#c-worker_attach_to_pool).  The
caller worker shouldn't access to the pool after detached except it has
other reference to the pool.

#### <a id="c-create_worker"></a>`create_worker()`

```c
struct worker * create_worker(struct worker_pool *pool)
```

create a new workqueue worker

**Parameters**

- `struct worker_pool *pool`: pool the new worker will belong to

**Description**

Create and start a new worker which is attached to **pool**.

**Context**

Might sleep.  Does GFP_KERNEL allocations.

**Return**

Pointer to the newly created worker.

#### <a id="c-set_worker_dying"></a>`set_worker_dying()`

```c
void set_worker_dying(struct worker *worker, struct list_head *list)
```

Tag a worker for destruction

**Parameters**

- `struct worker *worker`: worker to be destroyed
- `struct list_head *list`: transfer worker away from its pool->idle_list and into list

**Description**

Tag **worker** for destruction and adjust **pool** stats accordingly.  The worker
should be idle.

**Context**

raw_spin_lock_irq(pool->lock).

#### <a id="c-idle_worker_timeout"></a>`idle_worker_timeout()`

```c
void idle_worker_timeout(struct timer_list *t)
```

check if some idle workers can now be deleted.

**Parameters**

- `struct timer_list *t`: The pool's idle_timer that just expired

**Description**

The timer is armed in [`worker_enter_idle()`](#c-worker_enter_idle). Note that it isn't disarmed in
[`worker_leave_idle()`](#c-worker_leave_idle), as a worker flicking between idle and active while its
pool is at the `too_many_workers()` tipping point would cause too much timer
housekeeping overhead. Since IDLE_WORKER_TIMEOUT is long enough, we just let
it expire and re-evaluate things from there.

#### <a id="c-idle_cull_fn"></a>`idle_cull_fn()`

```c
void idle_cull_fn(struct work_struct *work)
```

cull workers that have been idle for too long.

**Parameters**

- `struct work_struct *work`: the pool's work for handling these idle workers

**Description**

This goes through a pool's idle workers and gets rid of those that have been
idle for at least IDLE_WORKER_TIMEOUT seconds.

We don't want to disturb isolated CPUs because of a pcpu kworker being
culled, so this also resets worker affinity. This requires a sleepable
context, hence the split between timer callback and work item.

#### <a id="c-maybe_create_worker"></a>`maybe_create_worker()`

```c
void maybe_create_worker(struct worker_pool *pool)
```

create a new worker if necessary

**Parameters**

- `struct worker_pool *pool`: pool to create a new worker for

**Description**

Create a new worker for **pool** if necessary.  **pool** is guaranteed to
have at least one idle worker on return from this function.  If
creating a new worker takes longer than MAYDAY_INTERVAL, mayday is
sent to all rescuers with works scheduled on **pool** to resolve
possible allocation deadlock.

On return, `need_to_create_worker()` is guaranteed to be `false` and
`may_start_working()` `true`.

LOCKING:
raw_spin_lock_irq(pool->lock) which may be released and regrabbed
multiple times.  Does GFP_KERNEL allocations.  Called only from
manager.

#### <a id="c-manage_workers"></a>`manage_workers()`

```c
bool manage_workers(struct worker *worker)
```

manage worker pool

**Parameters**

- `struct worker *worker`: self

**Description**

Assume the manager role and manage the worker pool **worker** belongs
to.  At any given time, there can be only zero or one manager per
pool.  The exclusion is handled automatically by this function.

The caller can safely start processing works on false return.  On
true return, it's guaranteed that `need_to_create_worker()` is false
and `may_start_working()` is true.

**Context**

raw_spin_lock_irq(pool->lock) which may be released and regrabbed
multiple times.  Does GFP_KERNEL allocations.

**Return**

`false` if the pool doesn't need management and the caller can safely
start processing works, `true` if management function was performed and
the conditions that the caller verified before calling the function may
no longer be true.

#### <a id="c-process_one_work"></a>`process_one_work()`

```c
void process_one_work(struct worker *worker, struct work_struct *work)
```

process single work

**Parameters**

- `struct worker *worker`: self
- `struct work_struct *work`: work to process

**Description**

Process **work**.  This function contains all the logics necessary to
process a single work including synchronization against and
interaction with other workers on the same cpu, queueing and
flushing.  As long as context requirement is met, any worker can
call this function to process a work.

**Context**

raw_spin_lock_irq(pool->lock) which is released and regrabbed.

#### <a id="c-process_scheduled_works"></a>`process_scheduled_works()`

```c
void process_scheduled_works(struct worker *worker)
```

process scheduled works

**Parameters**

- `struct worker *worker`: self

**Description**

Process all scheduled works.  Please note that the scheduled list
may change while processing a work, so this function repeatedly
fetches a work from the top and executes it.

**Context**

raw_spin_lock_irq(pool->lock) which may be released and regrabbed
multiple times.

#### <a id="c-worker_thread"></a>`worker_thread()`

```c
int worker_thread(void *__worker)
```

the worker thread function

**Parameters**

- `void *__worker`: self

**Description**

The worker thread function.  All workers belong to a worker_pool -
either a per-cpu one or dynamic unbound one.  These workers process all
work items regardless of their specific target workqueue.  The only
exception is work items which belong to workqueues with a rescuer which
will be explained in [`rescuer_thread()`](#c-rescuer_thread).

**Return**

0

#### <a id="c-rescuer_thread"></a>`rescuer_thread()`

```c
int rescuer_thread(void *__rescuer)
```

the rescuer thread function

**Parameters**

- `void *__rescuer`: self

**Description**

Workqueue rescuer thread function.  There's one rescuer for each
workqueue which has WQ_MEM_RECLAIM set.

Regular work processing on a pool may block trying to create a new
worker which uses GFP_KERNEL allocation which has slight chance of
developing into deadlock if some works currently on the same queue
need to be processed to satisfy the GFP_KERNEL allocation.  This is
the problem rescuer solves.

When such condition is possible, the pool summons rescuers of all
workqueues which have works queued on the pool and let them process
those works so that forward progress can be guaranteed.

This should happen rarely.

**Return**

0

#### <a id="c-check_flush_dependency"></a>`check_flush_dependency()`

```c
void check_flush_dependency(struct workqueue_struct *target_wq, struct work_struct *target_work, bool from_cancel)
```

check for flush dependency sanity

**Parameters**

- `struct workqueue_struct *target_wq`: workqueue being flushed
- `struct work_struct *target_work`: work item being flushed (NULL for workqueue flushes)
- `bool from_cancel`: are we called from the work cancel path

**Description**

`current` is trying to flush the whole **target_wq** or **target_work** on it.
If this is not the cancel path (which implies work being flushed is either
already running, or will not be at all), check if **target_wq** doesn't have
`WQ_MEM_RECLAIM` and verify that `current` is not reclaiming memory or running
on a workqueue which doesn't have `WQ_MEM_RECLAIM` as that can break forward-
progress guarantee leading to a deadlock.

#### <a id="c-insert_wq_barrier"></a>`insert_wq_barrier()`

```c
void insert_wq_barrier(struct pool_workqueue *pwq, struct wq_barrier *barr, struct work_struct *target, struct worker *worker)
```

insert a barrier work

**Parameters**

- `struct pool_workqueue *pwq`: pwq to insert barrier into
- `struct wq_barrier *barr`: wq_barrier to insert
- `struct work_struct *target`: target work to attach **barr** to
- `struct worker *worker`: worker currently executing **target**, NULL if **target** is not executing

**Description**

**barr** is linked to **target** such that **barr** is completed only after
**target** finishes execution.  Please note that the ordering
guarantee is observed only with respect to **target** and on the local
cpu.

Currently, a queued barrier can't be canceled.  This is because
[`try_to_grab_pending()`](#c-try_to_grab_pending) can't determine whether the work to be
grabbed is at the head of the queue and thus can't clear LINKED
flag of the previous work while there must be a valid next work
after a work with LINKED flag set.

Note that when **worker** is non-NULL, **target** may be modified
underneath us, so we can't reliably determine pwq from **target**.

**Context**

raw_spin_lock_irq(pool->lock).

#### <a id="c-flush_workqueue_prep_pwqs"></a>`flush_workqueue_prep_pwqs()`

```c
bool flush_workqueue_prep_pwqs(struct workqueue_struct *wq, int flush_color, int work_color)
```

prepare pwqs for workqueue flushing

**Parameters**

- `struct workqueue_struct *wq`: workqueue being flushed
- `int flush_color`: new flush color, \< 0 for no-op
- `int work_color`: new work color, \< 0 for no-op

**Description**

Prepare pwqs for workqueue flushing.

If **flush_color** is non-negative, flush_color on all pwqs should be
-1.  If no pwq has in-flight commands at the specified color, all
pwq->flush_color's stay at -1 and `false` is returned.  If any pwq
has in flight commands, its pwq->flush_color is set to
**flush_color**, **wq->nr_pwqs_to_flush** is updated accordingly, pwq
wakeup logic is armed and `true` is returned.

The caller should have initialized **wq->first_flusher** prior to
calling this function with non-negative **flush_color**.  If
**flush_color** is negative, no flush color update is done and `false`
is returned.

If **work_color** is non-negative, all pwqs should have the same
work_color which is previous to **work_color** and all will be
advanced to **work_color**.

**Context**

mutex_lock(wq->mutex).

**Return**

`true` if **flush_color** >= 0 and there's something to flush.  `false`
otherwise.

#### <a id="c-__flush_workqueue"></a>`__flush_workqueue()`

```c
void __flush_workqueue(struct workqueue_struct *wq)
```

ensure that any scheduled work has run to completion.

**Parameters**

- `struct workqueue_struct *wq`: workqueue to flush

**Description**

This function sleeps until all work items which were queued on entry
have finished execution, but it is not livelocked by new incoming ones.

#### <a id="c-drain_workqueue"></a>`drain_workqueue()`

```c
void drain_workqueue(struct workqueue_struct *wq)
```

drain a workqueue

**Parameters**

- `struct workqueue_struct *wq`: workqueue to drain

**Description**

Wait until the workqueue becomes empty.  While draining is in progress,
only chain queueing is allowed.  IOW, only currently pending or running
work items on **wq** can queue further work items on it.  **wq** is flushed
repeatedly until it becomes empty.  The number of flushing is determined
by the depth of chaining and should be relatively short.  Whine if it
takes too long.

#### <a id="c-flush_work"></a>`flush_work()`

```c
bool flush_work(struct work_struct *work)
```

wait for a work to finish executing the last queueing instance

**Parameters**

- `struct work_struct *work`: the work to flush

**Description**

Wait until **work** has finished execution.  **work** is guaranteed to be idle
on return if it hasn't been requeued since flush started.

**Return**

`true` if [`flush_work()`](#c-flush_work) waited for the work to finish execution,
`false` if it was already idle.

#### <a id="c-flush_delayed_work"></a>`flush_delayed_work()`

```c
bool flush_delayed_work(struct delayed_work *dwork)
```

wait for a dwork to finish executing the last queueing

**Parameters**

- `struct delayed_work *dwork`: the delayed work to flush

**Description**

Delayed timer is cancelled and the pending work is queued for
immediate execution.  Like [`flush_work()`](#c-flush_work), this function only
considers the last queueing instance of **dwork**.

**Return**

`true` if [`flush_work()`](#c-flush_work) waited for the work to finish execution,
`false` if it was already idle.

#### <a id="c-flush_rcu_work"></a>`flush_rcu_work()`

```c
bool flush_rcu_work(struct rcu_work *rwork)
```

wait for a rwork to finish executing the last queueing

**Parameters**

- `struct rcu_work *rwork`: the rcu work to flush

**Return**

`true` if [`flush_rcu_work()`](#c-flush_rcu_work) waited for the work to finish execution,
`false` if it was already idle.

#### <a id="c-cancel_work_sync"></a>`cancel_work_sync()`

```c
bool cancel_work_sync(struct work_struct *work)
```

cancel a work and wait for it to finish

**Parameters**

- `struct work_struct *work`: the work to cancel

**Description**

Cancel **work** and wait for its execution to finish. This function can be used
even if the work re-queues itself or migrates to another workqueue. On return
from this function, **work** is guaranteed to be not pending or executing on any
CPU as long as there aren't racing enqueues.

cancel_work_sync(`delayed_work->work`) must not be used for delayed_work's.
Use [`cancel_delayed_work_sync()`](#c-cancel_delayed_work_sync) instead.

Must be called from a sleepable context if **work** was last queued on a non-BH
workqueue. Can also be called from non-hardirq atomic contexts including BH
if **work** was last queued on a BH workqueue.

Returns `true` if **work** was pending, `false` otherwise.

#### <a id="c-cancel_delayed_work"></a>`cancel_delayed_work()`

```c
bool cancel_delayed_work(struct delayed_work *dwork)
```

cancel a delayed work

**Parameters**

- `struct delayed_work *dwork`: delayed_work to cancel

**Description**

Kill off a pending delayed_work.

**Return**

`true` if **dwork** was pending and canceled; `false` if it wasn't
pending.

**Note**

The work callback function may still be running on return, unless
it returns `true` and the work doesn't re-arm itself.  Explicitly flush or
use [`cancel_delayed_work_sync()`](#c-cancel_delayed_work_sync) to wait on it.

This function is safe to call from any context including IRQ handler.

#### <a id="c-cancel_delayed_work_sync"></a>`cancel_delayed_work_sync()`

```c
bool cancel_delayed_work_sync(struct delayed_work *dwork)
```

cancel a delayed work and wait for it to finish

**Parameters**

- `struct delayed_work *dwork`: the delayed work cancel

**Description**

This is [`cancel_work_sync()`](#c-cancel_work_sync) for delayed works.

**Return**

`true` if **dwork** was pending, `false` otherwise.

#### <a id="c-disable_work"></a>`disable_work()`

```c
bool disable_work(struct work_struct *work)
```

Disable and cancel a work item

**Parameters**

- `struct work_struct *work`: work item to disable

**Description**

Disable **work** by incrementing its disable count and cancel it if currently
pending. As long as the disable count is non-zero, any attempt to queue **work**
will fail and return `false`. The maximum supported disable depth is 2 to the
power of `WORK_OFFQ_DISABLE_BITS`, currently 65536.

Can be called from any context. Returns `true` if **work** was pending, `false`
otherwise.

#### <a id="c-disable_work_sync"></a>`disable_work_sync()`

```c
bool disable_work_sync(struct work_struct *work)
```

Disable, cancel and drain a work item

**Parameters**

- `struct work_struct *work`: work item to disable

**Description**

Similar to [`disable_work()`](#c-disable_work) but also wait for **work** to finish if currently
executing.

Must be called from a sleepable context if **work** was last queued on a non-BH
workqueue. Can also be called from non-hardirq atomic contexts including BH
if **work** was last queued on a BH workqueue.

Returns `true` if **work** was pending, `false` otherwise.

#### <a id="c-enable_work"></a>`enable_work()`

```c
bool enable_work(struct work_struct *work)
```

Enable a work item

**Parameters**

- `struct work_struct *work`: work item to enable

**Description**

Undo disable_work\[_sync\]() by decrementing **work**'s disable count. **work** can
only be queued if its disable count is 0.

Can be called from any context. Returns `true` if the disable count reached 0.
Otherwise, `false`.

#### <a id="c-disable_delayed_work"></a>`disable_delayed_work()`

```c
bool disable_delayed_work(struct delayed_work *dwork)
```

Disable and cancel a delayed work item

**Parameters**

- `struct delayed_work *dwork`: delayed work item to disable

**Description**

[`disable_work()`](#c-disable_work) for delayed work items.

#### <a id="c-disable_delayed_work_sync"></a>`disable_delayed_work_sync()`

```c
bool disable_delayed_work_sync(struct delayed_work *dwork)
```

Disable, cancel and drain a delayed work item

**Parameters**

- `struct delayed_work *dwork`: delayed work item to disable

**Description**

[`disable_work_sync()`](#c-disable_work_sync) for delayed work items.

#### <a id="c-enable_delayed_work"></a>`enable_delayed_work()`

```c
bool enable_delayed_work(struct delayed_work *dwork)
```

Enable a delayed work item

**Parameters**

- `struct delayed_work *dwork`: delayed work item to enable

**Description**

[`enable_work()`](#c-enable_work) for delayed work items.

#### <a id="c-schedule_on_each_cpu"></a>`schedule_on_each_cpu()`

```c
int schedule_on_each_cpu(work_func_t func)
```

execute a function synchronously on each online CPU

**Parameters**

- `work_func_t func`: the function to call

**Description**

[`schedule_on_each_cpu()`](#c-schedule_on_each_cpu) executes **func** on each online CPU using the
system workqueue and blocks until all CPUs have completed.
[`schedule_on_each_cpu()`](#c-schedule_on_each_cpu) is very slow.

**Return**

0 on success, -errno on failure.

#### <a id="c-execute_in_process_context"></a>`execute_in_process_context()`

```c
int execute_in_process_context(work_func_t fn, struct execute_work *ew)
```

reliably execute the routine with user context

**Parameters**

- `work_func_t fn`: the function to execute
- `struct execute_work *ew`: guaranteed storage for the execute work structure (must
  be available when the work executes)

**Description**

Executes the function immediately if process context is available,
otherwise schedules the function for delayed execution.

**Return**

0 - function was executed
1 - function was scheduled for execution

#### <a id="c-free_workqueue_attrs"></a>`free_workqueue_attrs()`

```c
void free_workqueue_attrs(struct workqueue_attrs *attrs)
```

free a workqueue_attrs

**Parameters**

- `struct workqueue_attrs *attrs`: workqueue_attrs to free

**Description**

Undo [`alloc_workqueue_attrs()`](#c-alloc_workqueue_attrs).

#### <a id="c-alloc_workqueue_attrs"></a>`alloc_workqueue_attrs()`

```c
struct workqueue_attrs * alloc_workqueue_attrs(void)
```

allocate a workqueue_attrs

**Parameters**

- `void`: no arguments

**Description**

Allocate a new workqueue_attrs, initialize with default settings and
return it.

**Return**

The allocated new workqueue_attr on success. `NULL` on failure.

#### <a id="c-init_worker_pool"></a>`init_worker_pool()`

```c
int init_worker_pool(struct worker_pool *pool)
```

initialize a newly zalloc'd worker_pool

**Parameters**

- `struct worker_pool *pool`: worker_pool to initialize

**Description**

Initialize a newly zalloc'd **pool**.  It also allocates **pool->attrs**.

**Return**

0 on success, -errno on failure.  Even on failure, all fields
inside **pool** proper are initialized and [`put_unbound_pool()`](#c-put_unbound_pool) can be called
on **pool** safely to release it.

#### <a id="c-put_unbound_pool"></a>`put_unbound_pool()`

```c
void put_unbound_pool(struct worker_pool *pool)
```

put a worker_pool

**Parameters**

- `struct worker_pool *pool`: worker_pool to put

**Description**

Put **pool**.  If its refcnt reaches zero, it gets destroyed in RCU
safe manner.  [`get_unbound_pool()`](#c-get_unbound_pool) calls this function on its failure path
and this function should be able to release pools which went through,
successfully or not, [`init_worker_pool()`](#c-init_worker_pool).

Should be called with wq_pool_mutex held.

#### <a id="c-get_unbound_pool"></a>`get_unbound_pool()`

```c
struct worker_pool * get_unbound_pool(const struct workqueue_attrs *attrs)
```

get a worker_pool with the specified attributes

**Parameters**

- `const struct workqueue_attrs *attrs`: the attributes of the worker_pool to get

**Description**

Obtain a worker_pool which has the same attributes as **attrs**, bump the
reference count and return it.  If there already is a matching
worker_pool, it will be used; otherwise, this function attempts to
create a new one.

Should be called with wq_pool_mutex held.

**Return**

On success, a worker_pool with the same attributes as **attrs**.
On failure, `NULL`.

#### <a id="c-wq_calc_pod_cpumask"></a>`wq_calc_pod_cpumask()`

```c
void wq_calc_pod_cpumask(struct workqueue_attrs *attrs, int cpu)
```

calculate a wq_attrs' cpumask for a pod

**Parameters**

- `struct workqueue_attrs *attrs`: the wq_attrs of the default pwq of the target workqueue
- `int cpu`: the target CPU

**Description**

Calculate the cpumask a workqueue with **attrs** should use on **pod**.
The result is stored in **attrs->__pod_cpumask**.

If pod affinity is not enabled, **attrs->cpumask** is always used. If enabled
and **pod** has online CPUs requested by **attrs**, the returned cpumask is the
intersection of the possible CPUs of **pod** and **attrs->cpumask**.

The caller is responsible for ensuring that the cpumask of **pod** stays stable.

#### <a id="c-apply_workqueue_attrs"></a>`apply_workqueue_attrs()`

```c
int apply_workqueue_attrs(struct workqueue_struct *wq, const struct workqueue_attrs *attrs)
```

apply new workqueue_attrs to an unbound workqueue

**Parameters**

- `struct workqueue_struct *wq`: the target workqueue
- `const struct workqueue_attrs *attrs`: the workqueue_attrs to apply, allocated with [`alloc_workqueue_attrs()`](#c-alloc_workqueue_attrs)

**Description**

Apply **attrs** to an unbound workqueue **wq**. Unless disabled, this function maps
a separate pwq to each CPU pod with possibles CPUs in **attrs->cpumask** so that
work items are affine to the pod it was issued on. Older pwqs are released as
in-flight work items finish. Note that a work item which repeatedly requeues
itself back-to-back will stay on its current pwq.

Performs GFP_KERNEL allocations.

**Return**

0 on success and -errno on failure.

#### <a id="c-unbound_wq_update_pwq"></a>`unbound_wq_update_pwq()`

```c
void unbound_wq_update_pwq(struct workqueue_struct *wq, int cpu)
```

update a pwq slot for CPU hot\[un\]plug

**Parameters**

- `struct workqueue_struct *wq`: the target workqueue
- `int cpu`: the CPU to update the pwq slot for

**Description**

This function is to be called from `CPU_DOWN_PREPARE`, `CPU_ONLINE` and
`CPU_DOWN_FAILED`.  **cpu** is in the same pod of the CPU being hot\[un\]plugged.

If pod affinity can't be adjusted due to memory allocation failure, it falls
back to **wq->dfl_pwq** which may not be optimal but is always correct.

Note that when the last allowed CPU of a pod goes offline for a workqueue
with a cpumask spanning multiple pods, the workers which were already
executing the work items for the workqueue will lose their CPU affinity and
may execute on any CPU. This is similar to how per-cpu workqueues behave on
CPU_DOWN. If a workqueue user wants strict affinity, it's the user's
responsibility to flush the work item from CPU_DOWN_PREPARE.

#### <a id="c-wq_adjust_max_active"></a>`wq_adjust_max_active()`

```c
void wq_adjust_max_active(struct workqueue_struct *wq)
```

update a wq's max_active to the current setting

**Parameters**

- `struct workqueue_struct *wq`: target workqueue

**Description**

If **wq** isn't freezing, set **wq->max_active** to the saved_max_active and
activate inactive work items accordingly. If **wq** is freezing, clear
**wq->max_active** to zero.

#### <a id="c-destroy_workqueue"></a>`destroy_workqueue()`

```c
void destroy_workqueue(struct workqueue_struct *wq)
```

safely terminate a workqueue

**Parameters**

- `struct workqueue_struct *wq`: target workqueue

**Description**

Safely destroy a workqueue. All work currently pending will be done first.

This function does NOT guarantee that non-pending work that has been
submitted with [`queue_delayed_work()`](#c-queue_delayed_work) and similar functions will be done
before destroying the workqueue. The fundamental problem is that, currently,
the workqueue has no way of accessing non-pending delayed_work. delayed_work
is only linked on the timer-side. All delayed_work must, therefore, be
canceled before calling this function.

TODO: It would be better if the problem described above wouldn't exist and
[`destroy_workqueue()`](#c-destroy_workqueue) would cleanly cancel all pending and non-pending
delayed_work.

#### <a id="c-workqueue_set_max_active"></a>`workqueue_set_max_active()`

```c
void workqueue_set_max_active(struct workqueue_struct *wq, int max_active)
```

adjust max_active of a workqueue

**Parameters**

- `struct workqueue_struct *wq`: target workqueue
- `int max_active`: new max_active value.

**Description**

Set max_active of **wq** to **max_active**. See the [`alloc_workqueue()`](#c-alloc_workqueue) function
comment.

**Context**

Don't call from IRQ context.

#### <a id="c-workqueue_set_min_active"></a>`workqueue_set_min_active()`

```c
void workqueue_set_min_active(struct workqueue_struct *wq, int min_active)
```

adjust min_active of an unbound workqueue

**Parameters**

- `struct workqueue_struct *wq`: target unbound workqueue
- `int min_active`: new min_active value

**Description**

Set min_active of an unbound workqueue. Unlike other types of workqueues, an
unbound workqueue is not guaranteed to be able to process max_active
interdependent work items. Instead, an unbound workqueue is guaranteed to be
able to process min_active number of interdependent work items which is
`WQ_DFL_MIN_ACTIVE` by default.

Use this function to adjust the min_active value between 0 and the current
max_active.

#### <a id="c-current_work"></a>`current_work()`

```c
struct work_struct * current_work(void)
```

retrieve `current` task's work struct

**Parameters**

- `void`: no arguments

**Description**

Determine if `current` task is a workqueue worker and what it's working on.
Useful to find out the context that the `current` task is running in.

**Return**

work struct if `current` task is a workqueue worker, `NULL` otherwise.

#### <a id="c-current_is_workqueue_rescuer"></a>`current_is_workqueue_rescuer()`

```c
bool current_is_workqueue_rescuer(void)
```

is `current` workqueue rescuer?

**Parameters**

- `void`: no arguments

**Description**

Determine whether `current` is a workqueue rescuer.  Can be used from
work functions to determine whether it's being run off the rescuer task.

**Return**

`true` if `current` is a workqueue rescuer. `false` otherwise.

#### <a id="c-workqueue_congested"></a>`workqueue_congested()`

```c
bool workqueue_congested(int cpu, struct workqueue_struct *wq)
```

test whether a workqueue is congested

**Parameters**

- `int cpu`: CPU in question
- `struct workqueue_struct *wq`: target workqueue

**Description**

Test whether **wq**'s cpu workqueue for **cpu** is congested.  There is
no synchronization around this function and the test result is
unreliable and only useful as advisory hints or for debugging.

If **cpu** is WORK_CPU_UNBOUND, the test is performed on the local CPU.

With the exception of ordered workqueues, all workqueues have per-cpu
pool_workqueues, each with its own congested state. A workqueue being
congested on one CPU doesn't mean that the workqueue is contested on any
other CPUs.

**Return**

`true` if congested, `false` otherwise.

#### <a id="c-work_busy"></a>`work_busy()`

```c
unsigned int work_busy(struct work_struct *work)
```

test whether a work is currently pending or running

**Parameters**

- `struct work_struct *work`: the work to be tested

**Description**

Test whether **work** is currently pending or running.  There is no
synchronization around this function and the test result is
unreliable and only useful as advisory hints or for debugging.

**Return**

OR'd bitmask of WORK_BUSY_* bits.

#### <a id="c-set_worker_desc"></a>`set_worker_desc()`

```c
void set_worker_desc(const char *fmt, ...)
```

set description for the current work item

**Parameters**

- `const char *fmt`: printf-style format string
- `...`: arguments for the format string

**Description**

This function can be called by a running work function to describe what
the work item is about.  If the worker task gets dumped, this
information will be printed out together to help debugging.  The
description can be at most WORKER_DESC_LEN including the trailing '\0'.

#### <a id="c-print_worker_info"></a>`print_worker_info()`

```c
void print_worker_info(const char *log_lvl, struct task_struct *task)
```

print out worker information and description

**Parameters**

- `const char *log_lvl`: the log level to use when printing
- `struct task_struct *task`: target task

**Description**

If **task** is a worker and currently executing a work item, print out the
name of the workqueue being serviced and worker description set with
[`set_worker_desc()`](#c-set_worker_desc) by the currently executing work item.

This function can be safely called on any task as long as the
task_struct itself is accessible.  While safe, this function isn't
synchronized and may print out mixups or garbages of limited length.

#### <a id="c-show_one_workqueue"></a>`show_one_workqueue()`

```c
void show_one_workqueue(struct workqueue_struct *wq)
```

dump state of specified workqueue

**Parameters**

- `struct workqueue_struct *wq`: workqueue whose state will be printed

#### <a id="c-show_one_worker_pool"></a>`show_one_worker_pool()`

```c
void show_one_worker_pool(struct worker_pool *pool)
```

dump state of specified worker pool

**Parameters**

- `struct worker_pool *pool`: worker pool whose state will be printed

#### <a id="c-show_all_workqueues"></a>`show_all_workqueues()`

```c
void show_all_workqueues(void)
```

dump workqueue state

**Parameters**

- `void`: no arguments

**Description**

Called from a sysrq handler and prints out all busy workqueues and pools.

#### <a id="c-show_freezable_workqueues"></a>`show_freezable_workqueues()`

```c
void show_freezable_workqueues(void)
```

dump freezable workqueue state

**Parameters**

- `void`: no arguments

**Description**

Called from `try_to_freeze_tasks()` and prints out all freezable workqueues
still busy.

#### <a id="c-rebind_workers"></a>`rebind_workers()`

```c
void rebind_workers(struct worker_pool *pool)
```

rebind all workers of a pool to the associated CPU

**Parameters**

- `struct worker_pool *pool`: pool of interest

**Description**

**pool->cpu** is coming online.  Rebind all workers to the CPU.

#### <a id="c-restore_unbound_workers_cpumask"></a>`restore_unbound_workers_cpumask()`

```c
void restore_unbound_workers_cpumask(struct worker_pool *pool, int cpu)
```

restore cpumask of unbound workers

**Parameters**

- `struct worker_pool *pool`: unbound pool of interest
- `int cpu`: the CPU which is coming up

**Description**

An unbound pool may end up with a cpumask which doesn't have any online
CPUs.  When a worker of such pool get scheduled, the scheduler resets
its cpus_allowed.  If **cpu** is in **pool**'s cpumask which didn't have any
online CPU before, cpus_allowed of all its workers should be restored.

#### <a id="c-work_on_cpu_key"></a>`work_on_cpu_key()`

```c
long work_on_cpu_key(int cpu, long (*fn)(void *), void *arg, struct lock_class_key *key)
```

run a function in thread context on a particular cpu

**Parameters**

- `int cpu`: the cpu to run on
- `long (*fn)(void *)`: the function to run
- `void *arg`: the function arg
- `struct lock_class_key *key`: The lock class key for lock debugging purposes

**Description**

It is up to the caller to ensure that the cpu doesn't go offline.
The caller must not hold any locks which would prevent **fn** from completing.

**Return**

The value **fn** returns.

#### <a id="c-freeze_workqueues_begin"></a>`freeze_workqueues_begin()`

```c
void freeze_workqueues_begin(void)
```

begin freezing workqueues

**Parameters**

- `void`: no arguments

**Description**

Start freezing workqueues.  After this function returns, all freezable
workqueues will queue new works to their inactive_works list instead of
pool->worklist.

**Context**

Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.

#### <a id="c-freeze_workqueues_busy"></a>`freeze_workqueues_busy()`

```c
bool freeze_workqueues_busy(void)
```

are freezable workqueues still busy?

**Parameters**

- `void`: no arguments

**Description**

Check whether freezing is complete.  This function must be called
between [`freeze_workqueues_begin()`](#c-freeze_workqueues_begin) and [`thaw_workqueues()`](#c-thaw_workqueues).

**Context**

Grabs and releases wq_pool_mutex.

**Return**

`true` if some freezable workqueues are still busy.  `false` if freezing
is complete.

#### <a id="c-thaw_workqueues"></a>`thaw_workqueues()`

```c
void thaw_workqueues(void)
```

thaw workqueues

**Parameters**

- `void`: no arguments

**Description**

Thaw workqueues.  Normal queueing is restored and all collected
frozen works are transferred to their respective pool worklists.

**Context**

Grabs and releases wq_pool_mutex, wq->mutex and pool->lock's.

#### <a id="c-workqueue_unbound_housekeeping_update"></a>`workqueue_unbound_housekeeping_update()`

```c
int workqueue_unbound_housekeeping_update(const struct cpumask *hk)
```

Propagate housekeeping cpumask update

**Parameters**

- `const struct cpumask *hk`: the new housekeeping cpumask

**Description**

Update the unbound workqueue cpumask on top of the new housekeeping cpumask such
that the effective unbound affinity is the intersection of the new housekeeping
with the requested affinity set via nohz_full=/isolcpus= or sysfs.

**Return**

0 on success and -errno on failure.

#### <a id="c-workqueue_set_unbound_cpumask"></a>`workqueue_set_unbound_cpumask()`

```c
int workqueue_set_unbound_cpumask(cpumask_var_t cpumask)
```

Set the low-level unbound cpumask

**Parameters**

- `cpumask_var_t cpumask`: the cpumask to set

**Description**

The low-level workqueues cpumask is a global cpumask that limits
the affinity of all unbound workqueues.  This function check the **cpumask**
and apply it to all unbound workqueues and updates all pwqs of them.

**Return**

0       - Success
-EINVAL - Invalid **cpumask**
-ENOMEM - Failed to allocate memory for attrs or pwqs.

#### <a id="c-workqueue_sysfs_register"></a>`workqueue_sysfs_register()`

```c
int workqueue_sysfs_register(struct workqueue_struct *wq)
```

make a workqueue visible in sysfs

**Parameters**

- `struct workqueue_struct *wq`: the workqueue to register

**Description**

Expose **wq** in sysfs under /sys/bus/workqueue/devices.
alloc_workqueue*() automatically calls this function if WQ_SYSFS is set
which is the preferred method.

Workqueue user should use this function directly iff it wants to apply
workqueue_attrs before making the workqueue visible in sysfs; otherwise,
[`apply_workqueue_attrs()`](#c-apply_workqueue_attrs) may race against userland updating the
attributes.

**Return**

0 on success, -errno on failure.

#### <a id="c-workqueue_sysfs_unregister"></a>`workqueue_sysfs_unregister()`

```c
void workqueue_sysfs_unregister(struct workqueue_struct *wq)
```

undo [`workqueue_sysfs_register()`](#c-workqueue_sysfs_register)

**Parameters**

- `struct workqueue_struct *wq`: the workqueue to unregister

**Description**

If **wq** is registered to sysfs by [`workqueue_sysfs_register()`](#c-workqueue_sysfs_register), unregister.

#### <a id="c-workqueue_init_early"></a>`workqueue_init_early()`

```c
void workqueue_init_early(void)
```

early init for workqueue subsystem

**Parameters**

- `void`: no arguments

**Description**

This is the first step of three-staged workqueue subsystem initialization and
invoked as soon as the bare basics - memory allocation, cpumasks and idr are
up. It sets up all the data structures and system workqueues and allows early
boot code to create workqueues and queue/cancel work items. Actual work item
execution starts only after kthreads can be created and scheduled right
before early initcalls.

#### <a id="c-workqueue_init"></a>`workqueue_init()`

```c
void workqueue_init(void)
```

bring workqueue subsystem fully online

**Parameters**

- `void`: no arguments

**Description**

This is the second step of three-staged workqueue subsystem initialization
and invoked as soon as kthreads can be created and scheduled. Workqueues have
been created and work items queued on them, but there are no kworkers
executing the work items yet. Populate the worker pools with the initial
workers and enable future kworker creations.

#### <a id="c-workqueue_init_topology"></a>`workqueue_init_topology()`

```c
void workqueue_init_topology(void)
```

initialize CPU pods for unbound workqueues

**Parameters**

- `void`: no arguments

**Description**

This is the third step of three-staged workqueue subsystem initialization and
invoked after SMP and topology information are fully initialized. It
initializes the unbound CPU pods accordingly.

---

# XArray

_Peios Kernel / Internals / Core APIs_

> The XArray is an abstract data type which behaves like a very large array of pointers. It meets many of the same needs as a hash or a conventional resizable array. Unlike a hash, it allows you to sensibly go to the next or previous entry…

<a id="rst-xarray"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

**Author:** Matthew Wilcox

<a id="rst-overview"></a>

## Overview

The XArray is an abstract data type which behaves like a very large array of pointers.  It meets many of the same needs as a hash or a conventional resizable array.  Unlike a hash, it allows you to sensibly go to the next or previous entry in a cache-efficient manner.  In contrast to a resizable array, there is no need to copy data or change MMU mappings in order to grow the array.  It is more memory-efficient, parallelisable and cache friendly than a doubly-linked list.  It takes advantage of RCU to perform lookups without locking.

The XArray implementation is efficient when the indices used are densely clustered; hashing the object and using the hash as the index will not perform well.  The XArray is optimised for small indices, but still has good performance with large indices.  If your index can be larger than `ULONG_MAX` then the XArray is not the data type for you.  The most important user of the XArray is the page cache.

Normal pointers may be stored in the XArray directly.  They must be 4-byte aligned, which is true for any pointer returned from kmalloc() and alloc_page().  It isn't true for arbitrary user-space pointers, nor for function pointers.  You can store pointers to statically allocated objects, as long as those objects have an alignment of at least 4.

You can also store integers between 0 and `LONG_MAX` in the XArray. You must first convert it into an entry using xa_mk_value(). When you retrieve an entry from the XArray, you can check whether it is a value entry by calling xa_is_value(), and convert it back to an integer by calling xa_to_value().

Some users want to tag the pointers they store in the XArray.  You can call xa_tag_pointer() to create an entry with a tag, xa_untag_pointer() to turn a tagged entry back into an untagged pointer and xa_pointer_tag() to retrieve the tag of an entry.  Tagged pointers use the same bits that are used to distinguish value entries from normal pointers, so you must decide whether you want to store value entries or tagged pointers in any particular XArray.

The XArray does not support storing IS_ERR() pointers as some conflict with value entries or internal entries.

An unusual feature of the XArray is the ability to create entries which occupy a range of indices.  Once stored to, looking up any index in the range will return the same entry as looking up any other index in the range.  Storing to any index will store to all of them.  Multi-index entries can be explicitly split into smaller entries. Unsetting (using xa_erase() or xa_store() with `NULL`) any entry will cause the XArray to forget about the range.

<a id="rst-normal-api"></a>

## Normal API

Start by initialising an XArray, either with DEFINE_XARRAY() for statically allocated XArrays or xa_init() for dynamically allocated ones.  A freshly-initialised XArray contains a `NULL` pointer at every index.

You can then set entries using xa_store() and get entries using xa_load().  xa_store() will overwrite any entry with the new entry and return the previous entry stored at that index.  You can unset entries using xa_erase() or by setting the entry to `NULL` using xa_store(). There is no difference between an entry that has never been stored to and one that has been erased with xa_erase(); an entry that has most recently had `NULL` stored to it is also equivalent except if the XArray was initialized with `XA_FLAGS_ALLOC`.

You can conditionally replace an entry at an index by using xa_cmpxchg().  Like cmpxchg(), it will only succeed if the entry at that index has the 'old' value.  It also returns the entry which was at that index; if it returns the same entry which was passed as 'old', then xa_cmpxchg() succeeded.

If you want to only store a new entry to an index if the current entry at that index is `NULL`, you can use xa_insert() which returns `-EBUSY` if the entry is not empty.

You can copy entries out of the XArray into a plain array by calling xa_extract().  Or you can iterate over the present entries in the XArray by calling xa_for_each(), xa_for_each_start() or xa_for_each_range(). You may prefer to use xa_find() or xa_find_after() to move to the next present entry in the XArray.

Calling xa_store_range() stores the same entry in a range of indices.  If you do this, some of the other operations will behave in a slightly odd way.  For example, marking the entry at one index may result in the entry being marked at some, but not all of the other indices.  Storing into one index may result in the entry retrieved by some, but not all of the other indices changing.

Sometimes you need to ensure that a subsequent call to xa_store() will not need to allocate memory.  The xa_reserve() function will store a reserved entry at the indicated index.  Users of the normal API will see this entry as containing `NULL`.  If you do not need to use the reserved entry, you can call xa_release() to remove the unused entry.  If another user has stored to the entry in the meantime, xa_release() will do nothing; if instead you want the entry to become `NULL`, you should use xa_erase(). Using xa_insert() on a reserved entry will fail.

If all entries in the array are `NULL`, the xa_empty() function will return `true`.

Finally, you can remove all entries from an XArray by calling xa_destroy().  If the XArray entries are pointers, you may wish to free the entries first.  You can do this by iterating over all present entries in the XArray using the xa_for_each() iterator.

<a id="rst-search-marks"></a>

### Search Marks

Each entry in the array has three bits associated with it called marks. Each mark may be set or cleared independently of the others.  You can iterate over marked entries by using the xa_for_each_marked() iterator.

You can enquire whether a mark is set on an entry by using xa_get_mark().  If the entry is not `NULL`, you can set a mark on it by using xa_set_mark() and remove the mark from an entry by calling xa_clear_mark().  You can ask whether any entry in the XArray has a particular mark set by calling xa_marked().  Erasing an entry from the XArray causes all marks associated with that entry to be cleared.

Setting or clearing a mark on any index of a multi-index entry will affect all indices covered by that entry.  Querying the mark on any index will return the same result.

There is no way to iterate over entries which are not marked; the data structure does not allow this to be implemented efficiently.  There are not currently iterators to search for logical combinations of bits (eg iterate over all entries which have both `XA_MARK_1` and `XA_MARK_2` set, or iterate over all entries which have `XA_MARK_0` or `XA_MARK_2` set).  It would be possible to add these if a user arises.

<a id="rst-allocating-xarrays"></a>

### Allocating XArrays

If you use DEFINE_XARRAY_ALLOC() to define the XArray, or initialise it by passing `XA_FLAGS_ALLOC` to xa_init_flags(), the XArray changes to track whether entries are in use or not.

You can call xa_alloc() to store the entry at an unused index in the XArray.  If you need to modify the array from interrupt context, you can use xa_alloc_bh() or xa_alloc_irq() to disable interrupts while allocating the ID.

Using xa_store(), xa_cmpxchg() or xa_insert() will also mark the entry as being allocated.  Unlike a normal XArray, storing `NULL` will mark the entry as being in use, like xa_reserve(). To free an entry, use xa_erase() (or xa_release() if you only want to free the entry if it's `NULL`).

By default, the lowest free entry is allocated starting from 0.  If you want to allocate entries starting at 1, it is more efficient to use DEFINE_XARRAY_ALLOC1() or `XA_FLAGS_ALLOC1`.  If you want to allocate IDs up to a maximum, then wrap back around to the lowest free ID, you can use xa_alloc_cyclic().

You cannot use `XA_MARK_0` with an allocating XArray as this mark is used to track whether an entry is free or not.  The other marks are available for your use.

<a id="rst-memory-allocation"></a>

### Memory allocation

The xa_store(), xa_cmpxchg(), xa_alloc(), xa_reserve() and xa_insert() functions take a gfp_t parameter in case the XArray needs to allocate memory to store this entry. If the entry is being deleted, no memory allocation needs to be performed, and the GFP flags specified will be ignored.

It is possible for no memory to be allocatable, particularly if you pass a restrictive set of GFP flags.  In that case, the functions return a special value which can be turned into an errno using xa_err(). If you don't need to know exactly which error occurred, using xa_is_err() is slightly more efficient.

<a id="rst-locking"></a>

### Locking

When using the Normal API, you do not have to worry about locking. The XArray uses RCU and an internal spinlock to synchronise access:

- **No lock needed:**

  - xa_empty()

  - xa_marked()

- **Takes RCU read lock:**

  - xa_load()

  - xa_for_each()

  - xa_for_each_start()

  - xa_for_each_range()

  - xa_find()

  - xa_find_after()

  - xa_extract()

  - xa_get_mark()

- **Takes xa_lock internally:**

  - xa_store()

  - xa_store_bh()

  - xa_store_irq()

  - xa_insert()

  - xa_insert_bh()

  - xa_insert_irq()

  - xa_erase()

  - xa_erase_bh()

  - xa_erase_irq()

  - xa_cmpxchg()

  - xa_cmpxchg_bh()

  - xa_cmpxchg_irq()

  - xa_store_range()

  - xa_alloc()

  - xa_alloc_bh()

  - xa_alloc_irq()

  - xa_reserve()

  - xa_reserve_bh()

  - xa_reserve_irq()

  - xa_destroy()

  - xa_set_mark()

  - xa_clear_mark()

- **Assumes xa_lock held on entry:**

  - \__xa_store()

  - \__xa_insert()

  - \__xa_erase()

  - \__xa_cmpxchg()

  - \__xa_alloc()

  - \__xa_set_mark()

  - \__xa_clear_mark()

If you want to take advantage of the lock to protect the data structures that you are storing in the XArray, you can call xa_lock() before calling xa_load(), then take a reference count on the object you have found before calling xa_unlock().  This will prevent stores from removing the object from the array between looking up the object and incrementing the refcount.  You can also use RCU to avoid dereferencing freed memory, but an explanation of that is beyond the scope of this document.

The XArray does not disable interrupts or softirqs while modifying the array.  It is safe to read the XArray from interrupt or softirq context as the RCU lock provides enough protection.

If, for example, you want to store entries in the XArray in process context and then erase them in softirq context, you can do that this way:



```text
void foo_init(struct foo *foo)
{
    xa_init_flags(&foo->array, XA_FLAGS_LOCK_BH);
}

int foo_store(struct foo *foo, unsigned long index, void *entry)
{
    int err;

    xa_lock_bh(&foo->array);
    err = xa_err(__xa_store(&foo->array, index, entry, GFP_KERNEL));
    if (!err)
        foo->count++;
    xa_unlock_bh(&foo->array);
    return err;
}

/* foo_erase() is only called from softirq context */
void foo_erase(struct foo *foo, unsigned long index)
{
    xa_lock(&foo->array);
    __xa_erase(&foo->array, index);
    foo->count--;
    xa_unlock(&foo->array);
}
```

If you are going to modify the XArray from interrupt or softirq context, you need to initialise the array using xa_init_flags(), passing `XA_FLAGS_LOCK_IRQ` or `XA_FLAGS_LOCK_BH`.

The above example also shows a common pattern of wanting to extend the coverage of the xa_lock on the store side to protect some statistics associated with the array.

Sharing the XArray with interrupt context is also possible, either using xa_lock_irqsave() in both the interrupt handler and process context, or xa_lock_irq() in process context and xa_lock() in the interrupt handler.  Some of the more common patterns have helper functions such as xa_store_bh(), xa_store_irq(), xa_erase_bh(), xa_erase_irq(), xa_cmpxchg_bh() and xa_cmpxchg_irq().

Sometimes you need to protect access to the XArray with a mutex because that lock sits above another mutex in the locking hierarchy.  That does not entitle you to use functions like \__xa_erase() without taking the xa_lock; the xa_lock is used for lockdep validation and will be used for other purposes in the future.

The \__xa_set_mark() and \__xa_clear_mark() functions are also available for situations where you look up an entry and want to atomically set or clear a mark.  It may be more efficient to use the advanced API in this case, as it will save you from walking the tree twice.

<a id="rst-advanced-api"></a>

## Advanced API

The advanced API offers more flexibility and better performance at the cost of an interface which can be harder to use and has fewer safeguards. No locking is done for you by the advanced API, and you are required to use the xa_lock while modifying the array.  You can choose whether to use the xa_lock or the RCU lock while doing read-only operations on the array.  You can mix advanced and normal operations on the same array; indeed the normal API is implemented in terms of the advanced API.  The advanced API is only available to modules with a GPL-compatible license.

The advanced API is based around the xa_state.  This is an opaque data structure which you declare on the stack using the XA_STATE() macro. This macro initialises the xa_state ready to start walking around the XArray.  It is used as a cursor to maintain the position in the XArray and let you compose various operations together without having to restart from the top every time.  The contents of the xa_state are protected by the rcu_read_lock() or the xas_lock().  If you need to drop whichever of those locks is protecting your state and tree, you must call xas_pause() so that future calls do not rely on the parts of the state which were left unprotected.

The xa_state is also used to store errors.  You can call xas_error() to retrieve the error.  All operations check whether the xa_state is in an error state before proceeding, so there's no need for you to check for an error after each call; you can make multiple calls in succession and only check at a convenient point.  The only errors currently generated by the XArray code itself are `ENOMEM` and `EINVAL`, but it supports arbitrary errors in case you want to call xas_set_err() yourself.

If the xa_state is holding an `ENOMEM` error, calling xas_nomem() will attempt to allocate more memory using the specified gfp flags and cache it in the xa_state for the next attempt.  The idea is that you take the xa_lock, attempt the operation and drop the lock.  The operation attempts to allocate memory while holding the lock, but it is more likely to fail.  Once you have dropped the lock, xas_nomem() can try harder to allocate more memory.  It will return `true` if it is worth retrying the operation (i.e. that there was a memory error *and* more memory was allocated).  If it has previously allocated memory, and that memory wasn't used, and there is no error (or some error that isn't `ENOMEM`), then it will free the memory previously allocated.

<a id="rst-internal-entries"></a>

### Internal Entries

The XArray reserves some entries for its own purposes.  These are never exposed through the normal API, but when using the advanced API, it's possible to see them.  Usually the best way to handle them is to pass them to xas_retry(), and retry the operation if it returns `true`.


<table>
<tbody>
<tr>
<td>


Name

</td>
<td>


Test

</td>
<td>


Usage

</td>
</tr>
<tr>
<td>


Node

</td>
<td>


xa_is_node()

</td>
<td>


An XArray node.  May be visible when using a multi-index xa_state.

</td>
</tr>
<tr>
<td>


Sibling

</td>
<td>


xa_is_sibling()

</td>
<td>


A non-canonical entry for a multi-index entry.  The value indicates which slot in this node has the canonical entry.

</td>
</tr>
<tr>
<td>


Retry

</td>
<td>


xa_is_retry()

</td>
<td>


This entry is currently being modified by a thread which has the xa_lock.  The node containing this entry may be freed at the end of this RCU period.  You should restart the lookup from the head of the array.

</td>
</tr>
<tr>
<td>


Zero

</td>
<td>


xa_is_zero()

</td>
<td>


Zero entries appear as `NULL` through the Normal API, but occupy an entry in the XArray which can be used to reserve the index for future use.  This is used by allocating XArrays for allocated entries which are `NULL`.

</td>
</tr>
</tbody>
</table>

Other internal entries may be added in the future.  As far as possible, they will be handled by xas_retry().

<a id="rst-additional-functionality"></a>

### Additional functionality

The xas_create_range() function allocates all the necessary memory to store every entry in a range.  It will set ENOMEM in the xa_state if it cannot allocate memory.

You can use xas_init_marks() to reset the marks on an entry to their default state.  This is usually all marks clear, unless the XArray is marked with `XA_FLAGS_TRACK_FREE`, in which case mark 0 is set and all other marks are clear.  Replacing one entry with another using xas_store() will not reset the marks on that entry; if you want the marks reset, you should do that explicitly.

The xas_load() will walk the xa_state as close to the entry as it can.  If you know the xa_state has already been walked to the entry and need to check that the entry hasn't changed, you can use xas_reload() to save a function call.

If you need to move to a different index in the XArray, call xas_set().  This resets the cursor to the top of the tree, which will generally make the next operation walk the cursor to the desired spot in the tree.  If you want to move to the next or previous index, call xas_next() or xas_prev().  Setting the index does not walk the cursor around the array so does not require a lock to be held, while moving to the next or previous index does.

You can search for the next present entry using xas_find().  This is the equivalent of both xa_find() and xa_find_after(); if the cursor has been walked to an entry, then it will find the next entry after the one currently referenced.  If not, it will return the entry at the index of the xa_state.  Using xas_next_entry() to move to the next present entry instead of xas_find() will save a function call in the majority of cases at the expense of emitting more inline code.

The xas_find_marked() function is similar.  If the xa_state has not been walked, it will return the entry at the index of the xa_state, if it is marked.  Otherwise, it will return the first marked entry after the entry referenced by the xa_state.  The xas_next_marked() function is the equivalent of xas_next_entry().

When iterating over a range of the XArray using xas_for_each() or xas_for_each_marked(), it may be necessary to temporarily stop the iteration.  The xas_pause() function exists for this purpose. After you have done the necessary work and wish to resume, the xa_state is in an appropriate state to continue the iteration after the entry you last processed.  If you have interrupts disabled while iterating, then it is good manners to pause the iteration and reenable interrupts every `XA_CHECK_SCHED` entries.

The xas_get_mark(), xas_set_mark() and xas_clear_mark() functions require the xa_state cursor to have been moved to the appropriate location in the XArray; they will do nothing if you have called xas_pause() or xas_set() immediately before.

You can call xas_set_update() to have a callback function called each time the XArray updates a node.  This is used by the page cache workingset code to maintain its list of nodes which contain only shadow entries.

<a id="rst-multi-index-entries"></a>

### Multi-Index Entries

The XArray has the ability to tie multiple indices together so that operations on one index affect all indices.  For example, storing into any index will change the value of the entry retrieved from any index. Setting or clearing a mark on any index will set or clear the mark on every index that is tied together.  The current implementation only allows tying ranges which are aligned powers of two together; eg indices 64-127 may be tied together, but 2-6 may not be.  This may save substantial quantities of memory; for example tying 512 entries together will save over 4kB.

You can create a multi-index entry by using XA_STATE_ORDER() or xas_set_order() followed by a call to xas_store(). Calling xas_load() with a multi-index xa_state will walk the xa_state to the right location in the tree, but the return value is not meaningful, potentially being an internal entry or `NULL` even when there is an entry stored within the range.  Calling xas_find_conflict() will return the first entry within the range or `NULL` if there are no entries in the range.  The xas_for_each_conflict() iterator will iterate over every entry which overlaps the specified range.

If xas_load() encounters a multi-index entry, the xa_index in the xa_state will not be changed.  When iterating over an XArray or calling xas_find(), if the initial index is in the middle of a multi-index entry, it will not be altered.  Subsequent calls or iterations will move the index to the first index in the range. Each entry will only be returned once, no matter how many indices it occupies.

Using xas_next() or xas_prev() with a multi-index xa_state is not supported.  Using either of these functions on a multi-index entry will reveal sibling entries; these should be skipped over by the caller.

Storing `NULL` into any index of a multi-index entry will set the entry at every index to `NULL` and dissolve the tie.  A multi-index entry can be split into entries occupying smaller ranges by calling xas_split_alloc() without the xa_lock held, followed by taking the lock and calling xas_split() or calling xas_try_split() with xa_lock. The difference between xas_split_alloc()+xas_split() and xas_try_alloc() is that xas_split_alloc() + xas_split() split the entry from the original order to the new order in one shot uniformly, whereas xas_try_split() iteratively splits the entry containing the index non-uniformly. For example, to split an order-9 entry, which takes 2^(9-6)=8 slots, assuming `XA_CHUNK_SHIFT` is 6, xas_split_alloc() + xas_split() need 8 xa_node. xas_try_split() splits the order-9 entry into 2 order-8 entries, then split one order-8 entry, based on the given index, to 2 order-7 entries, ..., and split one order-1 entry to 2 order-0 entries. When splitting the order-6 entry and a new xa_node is needed, xas_try_split() will try to allocate one if possible. As a result, xas_try_split() would only need 1 xa_node instead of 8.

<a id="rst-functions-and-structures"></a>

## Functions and structures


#### <a id="c-xa_mk_value"></a>`xa_mk_value()`

```c
void * xa_mk_value(unsigned long v)
```

Create an XArray entry from an integer.

**Parameters**

- `unsigned long v`: Value to store in XArray.

**Context**

Any context.

**Return**

An entry suitable for storing in the XArray.

#### <a id="c-xa_to_value"></a>`xa_to_value()`

```c
unsigned long xa_to_value(const void *entry)
```

Get value stored in an XArray entry.

**Parameters**

- `const void *entry`: XArray entry.

**Context**

Any context.

**Return**

The value stored in the XArray entry.

#### <a id="c-xa_is_value"></a>`xa_is_value()`

```c
bool xa_is_value(const void *entry)
```

Determine if an entry is a value.

**Parameters**

- `const void *entry`: XArray entry.

**Context**

Any context.

**Return**

True if the entry is a value, false if it is a pointer.

#### <a id="c-xa_tag_pointer"></a>`xa_tag_pointer()`

```c
void * xa_tag_pointer(void *p, unsigned long tag)
```

Create an XArray entry for a tagged pointer.

**Parameters**

- `void *p`: Plain pointer.
- `unsigned long tag`: Tag value (0, 1 or 3).

**Description**

If the user of the XArray prefers, they can tag their pointers instead
of storing value entries.  Three tags are available (0, 1 and 3).
These are distinct from the xa_mark_t as they are not replicated up
through the array and cannot be searched for.

**Context**

Any context.

**Return**

An XArray entry.

#### <a id="c-xa_untag_pointer"></a>`xa_untag_pointer()`

```c
void * xa_untag_pointer(void *entry)
```

Turn an XArray entry into a plain pointer.

**Parameters**

- `void *entry`: XArray entry.

**Description**

If you have stored a tagged pointer in the XArray, call this function
to get the untagged version of the pointer.

**Context**

Any context.

**Return**

A pointer.

#### <a id="c-xa_pointer_tag"></a>`xa_pointer_tag()`

```c
unsigned int xa_pointer_tag(void *entry)
```

Get the tag stored in an XArray entry.

**Parameters**

- `void *entry`: XArray entry.

**Description**

If you have stored a tagged pointer in the XArray, call this function
to get the tag of that pointer.

**Context**

Any context.

**Return**

A tag.

#### <a id="c-xa_is_zero"></a>`xa_is_zero()`

```c
bool xa_is_zero(const void *entry)
```

Is the entry a zero entry?

**Parameters**

- `const void *entry`: Entry retrieved from the XArray

**Description**

The normal API will return NULL as the contents of a slot containing
a zero entry.  You can only see zero entries by using the advanced API.

**Return**

`true` if the entry is a zero entry.

#### <a id="c-xa_is_err"></a>`xa_is_err()`

```c
bool xa_is_err(const void *entry)
```

Report whether an XArray operation returned an error

**Parameters**

- `const void *entry`: Result from calling an XArray function

**Description**

If an XArray operation cannot complete an operation, it will return
a special value indicating an error.  This function tells you
whether an error occurred; [`xa_err()`](#c-xa_err) tells you which error occurred.

**Context**

Any context.

**Return**

`true` if the entry indicates an error.

#### <a id="c-xa_err"></a>`xa_err()`

```c
int xa_err(void *entry)
```

Turn an XArray result into an errno.

**Parameters**

- `void *entry`: Result from calling an XArray function.

**Description**

If an XArray operation cannot complete an operation, it will return
a special pointer value which encodes an errno.  This function extracts
the errno from the pointer value, or returns 0 if the pointer does not
represent an errno.

**Context**

Any context.

**Return**

A negative errno or 0.

#### <a id="c-struct-xa_limit"></a>`struct xa_limit`

Represents a range of IDs.

**Definition**

```c
struct xa_limit {
    u32 max;
    u32 min;
};
```

**Members**

- `max`: The maximum ID to allocate (inclusive).
- `min`: The lowest ID to allocate (inclusive).

**Description**

This structure is used either directly or via the `XA_LIMIT()` macro
to communicate the range of IDs that are valid for allocation.
Three common ranges are predefined for you:
* xa_limit_32b       - \[0 - UINT_MAX\]
* xa_limit_31b       - \[0 - INT_MAX\]
* xa_limit_16b       - \[0 - USHRT_MAX\]

#### <a id="c-struct-xarray"></a>`struct xarray`

The anchor of the XArray.

**Definition**

```c
struct xarray {
    spinlock_t xa_lock;
};
```

**Members**

- `xa_lock`: Lock that protects the contents of the XArray.

**Description**

To use the xarray, define it statically or embed it in your data structure.
It is a very small data structure, so it does not usually make sense to
allocate it separately and keep a pointer to it in your data structure.

You may use the xa_lock to protect your own data structures as well.

#### <a id="c-DEFINE_XARRAY_FLAGS"></a>`DEFINE_XARRAY_FLAGS()`

```c
DEFINE_XARRAY_FLAGS(name, flags)
```

Define an XArray with custom flags.

**Parameters**

- `name`: A string that names your XArray.
- `flags`: XA_FLAG values.

**Description**

This is intended for file scope definitions of XArrays.  It declares
and initialises an empty XArray with the chosen name and flags.  It is
equivalent to calling [`xa_init_flags()`](#c-xa_init_flags) on the array, but it does the
initialisation at compiletime instead of runtime.

#### <a id="c-DEFINE_XARRAY"></a>`DEFINE_XARRAY()`

```c
DEFINE_XARRAY(name)
```

Define an XArray.

**Parameters**

- `name`: A string that names your XArray.

**Description**

This is intended for file scope definitions of XArrays.  It declares
and initialises an empty XArray with the chosen name.  It is equivalent
to calling [`xa_init()`](#c-xa_init) on the array, but it does the initialisation at
compiletime instead of runtime.

#### <a id="c-DEFINE_XARRAY_ALLOC"></a>`DEFINE_XARRAY_ALLOC()`

```c
DEFINE_XARRAY_ALLOC(name)
```

Define an XArray which allocates IDs starting at 0.

**Parameters**

- `name`: A string that names your XArray.

**Description**

This is intended for file scope definitions of allocating XArrays.
See also [`DEFINE_XARRAY()`](#c-DEFINE_XARRAY).

#### <a id="c-DEFINE_XARRAY_ALLOC1"></a>`DEFINE_XARRAY_ALLOC1()`

```c
DEFINE_XARRAY_ALLOC1(name)
```

Define an XArray which allocates IDs starting at 1.

**Parameters**

- `name`: A string that names your XArray.

**Description**

This is intended for file scope definitions of allocating XArrays.
See also [`DEFINE_XARRAY()`](#c-DEFINE_XARRAY).

#### <a id="c-xa_init_flags"></a>`xa_init_flags()`

```c
void xa_init_flags(struct xarray *xa, gfp_t flags)
```

Initialise an empty XArray with flags.

**Parameters**

- `struct xarray *xa`: XArray.
- `gfp_t flags`: XA_FLAG values.

**Description**

If you need to initialise an XArray with special flags (eg you need
to take the lock from interrupt context), use this function instead
of [`xa_init()`](#c-xa_init).

**Context**

Any context.

#### <a id="c-xa_init"></a>`xa_init()`

```c
void xa_init(struct xarray *xa)
```

Initialise an empty XArray.

**Parameters**

- `struct xarray *xa`: XArray.

**Description**

An empty XArray is full of NULL entries.

**Context**

Any context.

#### <a id="c-xa_empty"></a>`xa_empty()`

```c
bool xa_empty(const struct xarray *xa)
```

Determine if an array has any present entries.

**Parameters**

- `const struct xarray *xa`: XArray.

**Context**

Any context.

**Return**

`true` if the array contains only NULL pointers.

#### <a id="c-xa_marked"></a>`xa_marked()`

```c
bool xa_marked(const struct xarray *xa, xa_mark_t mark)
```

Inquire whether any entry in this array has a mark set

**Parameters**

- `const struct xarray *xa`: Array
- `xa_mark_t mark`: Mark value

**Context**

Any context.

**Return**

`true` if any entry has this mark set.

#### <a id="c-xa_for_each_range"></a>`xa_for_each_range()`

```c
xa_for_each_range(xa, index, entry, start, last)
```

Iterate over a portion of an XArray.

**Parameters**

- `xa`: XArray.
- `index`: Index of **entry**.
- `entry`: Entry retrieved from array.
- `start`: First index to retrieve from array.
- `last`: Last index to retrieve from array.

**Description**

During the iteration, **entry** will have the value of the entry stored
in **xa** at **index**.  You may modify **index** during the iteration if you
want to skip or reprocess indices.  It is safe to modify the array
during the iteration.  At the end of the iteration, **entry** will be set
to NULL and **index** will have a value less than or equal to max.

[`xa_for_each_range()`](#c-xa_for_each_range) is O(n.log(n)) while [`xas_for_each()`](#c-xas_for_each) is O(n).  You have
to handle your own locking with [`xas_for_each()`](#c-xas_for_each), and if you have to unlock
after each iteration, it will also end up being O(n.log(n)).
[`xa_for_each_range()`](#c-xa_for_each_range) will spin if it hits a retry entry; if you intend to
see retry entries, you should use the [`xas_for_each()`](#c-xas_for_each) iterator instead.
The [`xas_for_each()`](#c-xas_for_each) iterator will expand into more inline code than
[`xa_for_each_range()`](#c-xa_for_each_range).

**Context**

Any context.  Takes and releases the RCU lock.

#### <a id="c-xa_for_each_start"></a>`xa_for_each_start()`

```c
xa_for_each_start(xa, index, entry, start)
```

Iterate over a portion of an XArray.

**Parameters**

- `xa`: XArray.
- `index`: Index of **entry**.
- `entry`: Entry retrieved from array.
- `start`: First index to retrieve from array.

**Description**

During the iteration, **entry** will have the value of the entry stored
in **xa** at **index**.  You may modify **index** during the iteration if you
want to skip or reprocess indices.  It is safe to modify the array
during the iteration.  At the end of the iteration, **entry** will be set
to NULL and **index** will have a value less than or equal to max.

[`xa_for_each_start()`](#c-xa_for_each_start) is O(n.log(n)) while [`xas_for_each()`](#c-xas_for_each) is O(n).  You have
to handle your own locking with [`xas_for_each()`](#c-xas_for_each), and if you have to unlock
after each iteration, it will also end up being O(n.log(n)).
[`xa_for_each_start()`](#c-xa_for_each_start) will spin if it hits a retry entry; if you intend to
see retry entries, you should use the [`xas_for_each()`](#c-xas_for_each) iterator instead.
The [`xas_for_each()`](#c-xas_for_each) iterator will expand into more inline code than
[`xa_for_each_start()`](#c-xa_for_each_start).

**Context**

Any context.  Takes and releases the RCU lock.

#### <a id="c-xa_for_each"></a>`xa_for_each()`

```c
xa_for_each(xa, index, entry)
```

Iterate over present entries in an XArray.

**Parameters**

- `xa`: XArray.
- `index`: Index of **entry**.
- `entry`: Entry retrieved from array.

**Description**

During the iteration, **entry** will have the value of the entry stored
in **xa** at **index**.  You may modify **index** during the iteration if you want
to skip or reprocess indices.  It is safe to modify the array during the
iteration.  At the end of the iteration, **entry** will be set to NULL and
**index** will have a value less than or equal to max.

[`xa_for_each()`](#c-xa_for_each) is O(n.log(n)) while [`xas_for_each()`](#c-xas_for_each) is O(n).  You have
to handle your own locking with [`xas_for_each()`](#c-xas_for_each), and if you have to unlock
after each iteration, it will also end up being O(n.log(n)).  [`xa_for_each()`](#c-xa_for_each)
will spin if it hits a retry entry; if you intend to see retry entries,
you should use the [`xas_for_each()`](#c-xas_for_each) iterator instead.  The [`xas_for_each()`](#c-xas_for_each)
iterator will expand into more inline code than [`xa_for_each()`](#c-xa_for_each).

**Context**

Any context.  Takes and releases the RCU lock.

#### <a id="c-xa_for_each_marked"></a>`xa_for_each_marked()`

```c
xa_for_each_marked(xa, index, entry, filter)
```

Iterate over marked entries in an XArray.

**Parameters**

- `xa`: XArray.
- `index`: Index of **entry**.
- `entry`: Entry retrieved from array.
- `filter`: Selection criterion.

**Description**

During the iteration, **entry** will have the value of the entry stored
in **xa** at **index**.  The iteration will skip all entries in the array
which do not match **filter**.  You may modify **index** during the iteration
if you want to skip or reprocess indices.  It is safe to modify the array
during the iteration.  At the end of the iteration, **entry** will be set to
NULL and **index** will have a value less than or equal to max.

[`xa_for_each_marked()`](#c-xa_for_each_marked) is O(n.log(n)) while [`xas_for_each_marked()`](#c-xas_for_each_marked) is O(n).
You have to handle your own locking with [`xas_for_each()`](#c-xas_for_each), and if you have
to unlock after each iteration, it will also end up being O(n.log(n)).
[`xa_for_each_marked()`](#c-xa_for_each_marked) will spin if it hits a retry entry; if you intend to
see retry entries, you should use the [`xas_for_each_marked()`](#c-xas_for_each_marked) iterator
instead.  The [`xas_for_each_marked()`](#c-xas_for_each_marked) iterator will expand into more inline
code than [`xa_for_each_marked()`](#c-xa_for_each_marked).

**Context**

Any context.  Takes and releases the RCU lock.

#### <a id="c-xa_store_bh"></a>`xa_store_bh()`

```c
void * xa_store_bh(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

This function is like calling [`xa_store()`](#c-xa_store) except it disables softirqs
while holding the array lock.

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.

**Return**

The old entry at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_store_irq"></a>`xa_store_irq()`

```c
void * xa_store_irq(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

This function is like calling [`xa_store()`](#c-xa_store) except it disables interrupts
while holding the array lock.

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.

**Return**

The old entry at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_erase_bh"></a>`xa_erase_bh()`

```c
void * xa_erase_bh(struct xarray *xa, unsigned long index)
```

Erase this entry from the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.

**Description**

After this function returns, loading from **index** will return `NULL`.
If the index is part of a multi-index entry, all indices will be erased
and none of the entries will be part of a multi-index entry.

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.

**Return**

The entry which used to be at this index.

#### <a id="c-xa_erase_irq"></a>`xa_erase_irq()`

```c
void * xa_erase_irq(struct xarray *xa, unsigned long index)
```

Erase this entry from the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.

**Description**

After this function returns, loading from **index** will return `NULL`.
If the index is part of a multi-index entry, all indices will be erased
and none of the entries will be part of a multi-index entry.

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.

**Return**

The entry which used to be at this index.

#### <a id="c-xa_cmpxchg"></a>`xa_cmpxchg()`

```c
void * xa_cmpxchg(struct xarray *xa, unsigned long index, void *old, void *entry, gfp_t gfp)
```

Conditionally replace an entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *old`: Old value to test against.
- `void *entry`: New value to place in array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

If the entry at **index** is the same as **old**, replace it with **entry**.
If the return value is equal to **old**, then the exchange was successful.

**Context**

Any context.  Takes and releases the xa_lock.  May sleep
if the **gfp** flags permit.

**Return**

The old value at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_cmpxchg_bh"></a>`xa_cmpxchg_bh()`

```c
void * xa_cmpxchg_bh(struct xarray *xa, unsigned long index, void *old, void *entry, gfp_t gfp)
```

Conditionally replace an entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *old`: Old value to test against.
- `void *entry`: New value to place in array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

This function is like calling [`xa_cmpxchg()`](#c-xa_cmpxchg) except it disables softirqs
while holding the array lock.

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.  May sleep if the **gfp** flags permit.

**Return**

The old value at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_cmpxchg_irq"></a>`xa_cmpxchg_irq()`

```c
void * xa_cmpxchg_irq(struct xarray *xa, unsigned long index, void *old, void *entry, gfp_t gfp)
```

Conditionally replace an entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *old`: Old value to test against.
- `void *entry`: New value to place in array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

This function is like calling [`xa_cmpxchg()`](#c-xa_cmpxchg) except it disables interrupts
while holding the array lock.

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.  May sleep if the **gfp** flags permit.

**Return**

The old value at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_insert"></a>`xa_insert()`

```c
int xa_insert(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray unless another entry is already present.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Inserting a NULL entry will store a reserved entry (like [`xa_reserve()`](#c-xa_reserve))
if no entry is present.  Inserting will fail if a reserved entry is
present, even though loading from this index will return NULL.

**Context**

Any context.  Takes and releases the xa_lock.  May sleep if
the **gfp** flags permit.

**Return**

0 if the store succeeded.  -EBUSY if another entry was present.
-ENOMEM if memory could not be allocated.

#### <a id="c-xa_insert_bh"></a>`xa_insert_bh()`

```c
int xa_insert_bh(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray unless another entry is already present.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Inserting a NULL entry will store a reserved entry (like [`xa_reserve()`](#c-xa_reserve))
if no entry is present.  Inserting will fail if a reserved entry is
present, even though loading from this index will return NULL.

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.  May sleep if the **gfp** flags permit.

**Return**

0 if the store succeeded.  -EBUSY if another entry was present.
-ENOMEM if memory could not be allocated.

#### <a id="c-xa_insert_irq"></a>`xa_insert_irq()`

```c
int xa_insert_irq(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray unless another entry is already present.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Inserting a NULL entry will store a reserved entry (like [`xa_reserve()`](#c-xa_reserve))
if no entry is present.  Inserting will fail if a reserved entry is
present, even though loading from this index will return NULL.

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.  May sleep if the **gfp** flags permit.

**Return**

0 if the store succeeded.  -EBUSY if another entry was present.
-ENOMEM if memory could not be allocated.

#### <a id="c-xa_alloc"></a>`xa_alloc()`

```c
int xa_alloc(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

**Context**

Any context.  Takes and releases the xa_lock.  May sleep if
the **gfp** flags permit.

**Return**

0 on success, -ENOMEM if memory could not be allocated or
-EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_alloc_bh"></a>`xa_alloc_bh()`

```c
int xa_alloc_bh(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.  May sleep if the **gfp** flags permit.

**Return**

0 on success, -ENOMEM if memory could not be allocated or
-EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_alloc_irq"></a>`xa_alloc_irq()`

```c
int xa_alloc_irq(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.  May sleep if the **gfp** flags permit.

**Return**

0 on success, -ENOMEM if memory could not be allocated or
-EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_alloc_cyclic"></a>`xa_alloc_cyclic()`

```c
int xa_alloc_cyclic(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, u32 *next, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of allocated ID.
- `u32 *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.
The search for an empty entry will start at **next** and will wrap
around if necessary.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

Note that callers interested in whether wrapping has occurred should
use [`__xa_alloc_cyclic()`](#c-__xa_alloc_cyclic) instead.

**Context**

Any context.  Takes and releases the xa_lock.  May sleep if
the **gfp** flags permit.

**Return**

0 if the allocation succeeded, -ENOMEM if memory could not be
allocated or -EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_alloc_cyclic_bh"></a>`xa_alloc_cyclic_bh()`

```c
int xa_alloc_cyclic_bh(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, u32 *next, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of allocated ID.
- `u32 *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.
The search for an empty entry will start at **next** and will wrap
around if necessary.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

Note that callers interested in whether wrapping has occurred should
use [`__xa_alloc_cyclic()`](#c-__xa_alloc_cyclic) instead.

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.  May sleep if the **gfp** flags permit.

**Return**

0 if the allocation succeeded, -ENOMEM if memory could not be
allocated or -EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_alloc_cyclic_irq"></a>`xa_alloc_cyclic_irq()`

```c
int xa_alloc_cyclic_irq(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, u32 *next, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of allocated ID.
- `u32 *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.
The search for an empty entry will start at **next** and will wrap
around if necessary.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

Note that callers interested in whether wrapping has occurred should
use [`__xa_alloc_cyclic()`](#c-__xa_alloc_cyclic) instead.

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.  May sleep if the **gfp** flags permit.

**Return**

0 if the allocation succeeded, -ENOMEM if memory could not be
allocated or -EBUSY if there are no free entries in **limit**.

#### <a id="c-xa_reserve"></a>`xa_reserve()`

```c
int xa_reserve(struct xarray *xa, unsigned long index, gfp_t gfp)
```

Reserve this index in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Ensures there is somewhere to store an entry at **index** in the array.
If there is already something stored at **index**, this function does
nothing.  If there was nothing there, the entry is marked as reserved.
Loading from a reserved entry returns a `NULL` pointer.

If you do not use the entry that you have reserved, call [`xa_release()`](#c-xa_release)
or [`xa_erase()`](#c-xa_erase) to free any unnecessary memory.

**Context**

Any context.  Takes and releases the xa_lock.
May sleep if the **gfp** flags permit.

**Return**

0 if the reservation succeeded or -ENOMEM if it failed.

#### <a id="c-xa_reserve_bh"></a>`xa_reserve_bh()`

```c
int xa_reserve_bh(struct xarray *xa, unsigned long index, gfp_t gfp)
```

Reserve this index in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

A softirq-disabling version of [`xa_reserve()`](#c-xa_reserve).

**Context**

Any context.  Takes and releases the xa_lock while
disabling softirqs.

**Return**

0 if the reservation succeeded or -ENOMEM if it failed.

#### <a id="c-xa_reserve_irq"></a>`xa_reserve_irq()`

```c
int xa_reserve_irq(struct xarray *xa, unsigned long index, gfp_t gfp)
```

Reserve this index in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

An interrupt-disabling version of [`xa_reserve()`](#c-xa_reserve).

**Context**

Process context.  Takes and releases the xa_lock while
disabling interrupts.

**Return**

0 if the reservation succeeded or -ENOMEM if it failed.

#### <a id="c-xa_release"></a>`xa_release()`

```c
void xa_release(struct xarray *xa, unsigned long index)
```

Release a reserved entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.

**Description**

After calling [`xa_reserve()`](#c-xa_reserve), you can call this function to release the
reservation.  If the entry at **index** has been stored to, this function
will do nothing.

#### <a id="c-xa_is_sibling"></a>`xa_is_sibling()`

```c
bool xa_is_sibling(const void *entry)
```

Is the entry a sibling entry?

**Parameters**

- `const void *entry`: Entry retrieved from the XArray

**Return**

`true` if the entry is a sibling entry.

#### <a id="c-xa_is_retry"></a>`xa_is_retry()`

```c
bool xa_is_retry(const void *entry)
```

Is the entry a retry entry?

**Parameters**

- `const void *entry`: Entry retrieved from the XArray

**Return**

`true` if the entry is a retry entry.

#### <a id="c-xa_is_advanced"></a>`xa_is_advanced()`

```c
bool xa_is_advanced(const void *entry)
```

Is the entry only permitted for the advanced API?

**Parameters**

- `const void *entry`: Entry to be stored in the XArray.

**Return**

`true` if the entry cannot be stored by the normal API.

#### <a id="c-xa_update_node_t"></a>`xa_update_node_t()`

```c
typedef void xa_update_node_t(struct xa_node *node)
```

A callback function from the XArray.

**Parameters**

- `struct xa_node *node`: The node which is being processed

**Description**

This function is called every time the XArray updates the count of
present and value entries in a node.  It allows advanced users to
maintain the private_list in the node.

**Context**

The xa_lock is held and interrupts may be disabled.
Implementations should not drop the xa_lock, nor re-enable
interrupts.

#### <a id="c-XA_STATE"></a>`XA_STATE()`

```c
XA_STATE(name, array, index)
```

Declare an XArray operation state.

**Parameters**

- `name`: Name of this operation state (usually xas).
- `array`: Array to operate on.
- `index`: Initial index of interest.

**Description**

Declare and initialise an xa_state on the stack.

#### <a id="c-XA_STATE_ORDER"></a>`XA_STATE_ORDER()`

```c
XA_STATE_ORDER(name, array, index, order)
```

Declare an XArray operation state.

**Parameters**

- `name`: Name of this operation state (usually xas).
- `array`: Array to operate on.
- `index`: Initial index of interest.
- `order`: Order of entry.

**Description**

Declare and initialise an xa_state on the stack.  This variant of
[`XA_STATE()`](#c-XA_STATE) allows you to specify the 'order' of the element you
want to operate on.`

#### <a id="c-xas_error"></a>`xas_error()`

```c
int xas_error(const struct xa_state *xas)
```

Return an errno stored in the xa_state.

**Parameters**

- `const struct xa_state *xas`: XArray operation state.

**Return**

0 if no error has been noted.  A negative errno if one has.

#### <a id="c-xas_set_err"></a>`xas_set_err()`

```c
void xas_set_err(struct xa_state *xas, long err)
```

Note an error in the xa_state.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `long err`: Negative error number.

**Description**

Only call this function with a negative **err**; zero or positive errors
will probably not behave the way you think they should.  If you want
to clear the error from an xa_state, use [`xas_reset()`](#c-xas_reset).

#### <a id="c-xas_invalid"></a>`xas_invalid()`

```c
bool xas_invalid(const struct xa_state *xas)
```

Is the xas in a retry or error state?

**Parameters**

- `const struct xa_state *xas`: XArray operation state.

**Return**

`true` if the xas cannot be used for operations.

#### <a id="c-xas_valid"></a>`xas_valid()`

```c
bool xas_valid(const struct xa_state *xas)
```

Is the xas a valid cursor into the array?

**Parameters**

- `const struct xa_state *xas`: XArray operation state.

**Return**

`true` if the xas can be used for operations.

#### <a id="c-xas_is_node"></a>`xas_is_node()`

```c
bool xas_is_node(const struct xa_state *xas)
```

Does the xas point to a node?

**Parameters**

- `const struct xa_state *xas`: XArray operation state.

**Return**

`true` if the xas currently references a node.

#### <a id="c-xas_reset"></a>`xas_reset()`

```c
void xas_reset(struct xa_state *xas)
```

Reset an XArray operation state.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Resets the error or walk state of the **xas** so future walks of the
array will start from the root.  Use this if you have dropped the
xarray lock and want to reuse the xa_state.

**Context**

Any context.

#### <a id="c-xas_retry"></a>`xas_retry()`

```c
bool xas_retry(struct xa_state *xas, const void *entry)
```

Retry the operation if appropriate.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `const void *entry`: Entry from xarray.

**Description**

The advanced functions may sometimes return an internal entry, such as
a retry entry or a zero entry.  This function sets up the **xas** to restart
the walk from the head of the array if needed.

**Context**

Any context.

**Return**

true if the operation needs to be retried.

#### <a id="c-xas_reload"></a>`xas_reload()`

```c
void * xas_reload(struct xa_state *xas)
```

Refetch an entry from the xarray.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Use this function to check that a previously loaded entry still has
the same value.  This is useful for the lockless pagecache lookup where
we walk the array with only the RCU lock to protect us, lock the page,
then check that the page hasn't moved since we looked it up.

The caller guarantees that **xas** is still valid.  If it may be in an
error or restart state, call [`xas_load()`](#c-xas_load) instead.

**Return**

The entry at this location in the xarray.

#### <a id="c-xas_set"></a>`xas_set()`

```c
void xas_set(struct xa_state *xas, unsigned long index)
```

Set up XArray operation state for a different index.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long index`: New index into the XArray.

**Description**

Move the operation state to refer to a different index.  This will
have the effect of starting a walk from the top; see [`xas_next()`](#c-xas_next)
to move to an adjacent index.

#### <a id="c-xas_advance"></a>`xas_advance()`

```c
void xas_advance(struct xa_state *xas, unsigned long index)
```

Skip over sibling entries.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long index`: Index of last sibling entry.

**Description**

Move the operation state to refer to the last sibling entry.
This is useful for loops that normally want to see sibling
entries but sometimes want to skip them.  Use [`xas_set()`](#c-xas_set) if you
want to move to an index which is not part of this entry.

#### <a id="c-xas_set_order"></a>`xas_set_order()`

```c
void xas_set_order(struct xa_state *xas, unsigned long index, unsigned int order)
```

Set up XArray operation state for a multislot entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long index`: Target of the operation.
- `unsigned int order`: Entry occupies 2^**order** indices.

#### <a id="c-xas_set_update"></a>`xas_set_update()`

```c
void xas_set_update(struct xa_state *xas, xa_update_node_t update)
```

Set up XArray operation state for a callback.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `xa_update_node_t update`: Function to call when updating a node.

**Description**

The XArray can notify a caller after it has updated an xa_node.
This is advanced functionality and is only needed by the page
cache and swap cache.

#### <a id="c-xas_next_entry"></a>`xas_next_entry()`

```c
void * xas_next_entry(struct xa_state *xas, unsigned long max)
```

Advance iterator to next present entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long max`: Highest index to return.

**Description**

[`xas_next_entry()`](#c-xas_next_entry) is an inline function to optimise xarray traversal for
speed.  It is equivalent to calling [`xas_find()`](#c-xas_find), and will call [`xas_find()`](#c-xas_find)
for all the hard cases.

**Return**

The next present entry after the one currently referred to by **xas**.

#### <a id="c-xas_next_marked"></a>`xas_next_marked()`

```c
void * xas_next_marked(struct xa_state *xas, unsigned long max, xa_mark_t mark)
```

Advance iterator to next marked entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long max`: Highest index to return.
- `xa_mark_t mark`: Mark to search for.

**Description**

[`xas_next_marked()`](#c-xas_next_marked) is an inline function to optimise xarray traversal for
speed.  It is equivalent to calling [`xas_find_marked()`](#c-xas_find_marked), and will call
[`xas_find_marked()`](#c-xas_find_marked) for all the hard cases.

**Return**

The next marked entry after the one currently referred to by **xas**.

#### <a id="c-xas_for_each"></a>`xas_for_each()`

```c
xas_for_each(xas, entry, max)
```

Iterate over a range of an XArray.

**Parameters**

- `xas`: XArray operation state.
- `entry`: Entry retrieved from the array.
- `max`: Maximum index to retrieve from array.

**Description**

The loop body will be executed for each entry present in the xarray
between the current xas position and **max**.  **entry** will be set to
the entry retrieved from the xarray.  It is safe to delete entries
from the array in the loop body.  You should hold either the RCU lock
or the xa_lock while iterating.  If you need to drop the lock, call
[`xas_pause()`](#c-xas_pause) first.

#### <a id="c-xas_for_each_marked"></a>`xas_for_each_marked()`

```c
xas_for_each_marked(xas, entry, max, mark)
```

Iterate over a range of an XArray.

**Parameters**

- `xas`: XArray operation state.
- `entry`: Entry retrieved from the array.
- `max`: Maximum index to retrieve from array.
- `mark`: Mark to search for.

**Description**

The loop body will be executed for each marked entry in the xarray
between the current xas position and **max**.  **entry** will be set to
the entry retrieved from the xarray.  It is safe to delete entries
from the array in the loop body.  You should hold either the RCU lock
or the xa_lock while iterating.  If you need to drop the lock, call
[`xas_pause()`](#c-xas_pause) first.

#### <a id="c-xas_for_each_conflict"></a>`xas_for_each_conflict()`

```c
xas_for_each_conflict(xas, entry)
```

Iterate over a range of an XArray.

**Parameters**

- `xas`: XArray operation state.
- `entry`: Entry retrieved from the array.

**Description**

The loop body will be executed for each entry in the XArray that
lies within the range specified by **xas**.  If the loop terminates
normally, **entry** will be `NULL`.  The user may break out of the loop,
which will leave **entry** set to the conflicting entry.  The caller
may also call `xa_set_err()` to exit the loop while setting an error
to record the reason.

#### <a id="c-xas_prev"></a>`xas_prev()`

```c
void * xas_prev(struct xa_state *xas)
```

Move iterator to previous index.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

If the **xas** was in an error state, it will remain in an error state
and this function will return `NULL`.  If the **xas** has never been walked,
it will have the effect of calling [`xas_load()`](#c-xas_load).  Otherwise one will be
subtracted from the index and the state will be walked to the correct
location in the array for the next operation.

If the iterator was referencing index 0, this function wraps
around to `ULONG_MAX`.

**Return**

The entry at the new index.  This may be `NULL` or an internal
entry.

#### <a id="c-xas_next"></a>`xas_next()`

```c
void * xas_next(struct xa_state *xas)
```

Move state to next index.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

If the **xas** was in an error state, it will remain in an error state
and this function will return `NULL`.  If the **xas** has never been walked,
it will have the effect of calling [`xas_load()`](#c-xas_load).  Otherwise one will be
added to the index and the state will be walked to the correct
location in the array for the next operation.

If the iterator was referencing index `ULONG_MAX`, this function wraps
around to 0.

**Return**

The entry at the new index.  This may be `NULL` or an internal
entry.



#### <a id="c-xas_load"></a>`xas_load()`

```c
void * xas_load(struct xa_state *xas)
```

Load an entry from the XArray (advanced).

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Usually walks the **xas** to the appropriate state to load the entry
stored at xa_index.  However, it will do nothing and return `NULL` if
**xas** is in an error state.  [`xas_load()`](#c-xas_load) will never expand the tree.

If the xa_state is set up to operate on a multi-index entry, [`xas_load()`](#c-xas_load)
may return `NULL` or an internal entry, even if there are entries
present within the range specified by **xas**.

**Context**

Any context.  The caller should hold the xa_lock or the RCU lock.

**Return**

Usually an entry in the XArray, but see description for exceptions.

#### <a id="c-xas_nomem"></a>`xas_nomem()`

```c
bool xas_nomem(struct xa_state *xas, gfp_t gfp)
```

Allocate memory if needed.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `gfp_t gfp`: Memory allocation flags.

**Description**

If we need to add new nodes to the XArray, we try to allocate memory
with GFP_NOWAIT while holding the lock, which will usually succeed.
If it fails, **xas** is flagged as needing memory to continue.  The caller
should drop the lock and call [`xas_nomem()`](#c-xas_nomem).  If [`xas_nomem()`](#c-xas_nomem) succeeds,
the caller should retry the operation.

Forward progress is guaranteed as one node is allocated here and
stored in the xa_state where it will be found by `xas_alloc()`.  More
nodes will likely be found in the slab allocator, but we do not tie
them up here.

**Return**

true if memory was needed, and was successfully allocated.

#### <a id="c-xas_free_nodes"></a>`xas_free_nodes()`

```c
void xas_free_nodes(struct xa_state *xas, struct xa_node *top)
```

Free this node and all nodes that it references

**Parameters**

- `struct xa_state *xas`: Array operation state.
- `struct xa_node *top`: Node to free

**Description**

This node has been removed from the tree.  We must now free it and all
of its subnodes.  There may be RCU walkers with references into the tree,
so we must replace all entries with retry markers.

#### <a id="c-xas_create_range"></a>`xas_create_range()`

```c
void xas_create_range(struct xa_state *xas)
```

Ensure that stores to this range will succeed

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Creates all of the slots in the range covered by **xas**.  Sets **xas** to
create single-index entries and positions it at the beginning of the
range.  This is for the benefit of users which have not yet been
converted to use multi-index entries.

#### <a id="c-xas_store"></a>`xas_store()`

```c
void * xas_store(struct xa_state *xas, void *entry)
```

Store this entry in the XArray.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `void *entry`: New entry.

**Description**

If **xas** is operating on a multi-index entry, the entry returned by this
function is essentially meaningless (it may be an internal entry or it
may be `NULL`, even if there are non-NULL entries at some of the indices
covered by the range).  This is not a problem for any current users,
and can be changed if needed.

**Return**

The old entry at this index.

#### <a id="c-xas_get_mark"></a>`xas_get_mark()`

```c
bool xas_get_mark(const struct xa_state *xas, xa_mark_t mark)
```

Returns the state of this mark.

**Parameters**

- `const struct xa_state *xas`: XArray operation state.
- `xa_mark_t mark`: Mark number.

**Return**

true if the mark is set, false if the mark is clear or **xas**
is in an error state.

#### <a id="c-xas_set_mark"></a>`xas_set_mark()`

```c
void xas_set_mark(const struct xa_state *xas, xa_mark_t mark)
```

Sets the mark on this entry and its parents.

**Parameters**

- `const struct xa_state *xas`: XArray operation state.
- `xa_mark_t mark`: Mark number.

**Description**

Sets the specified mark on this entry, and walks up the tree setting it
on all the ancestor entries.  Does nothing if **xas** has not been walked to
an entry, or is in an error state.

#### <a id="c-xas_clear_mark"></a>`xas_clear_mark()`

```c
void xas_clear_mark(const struct xa_state *xas, xa_mark_t mark)
```

Clears the mark on this entry and its parents.

**Parameters**

- `const struct xa_state *xas`: XArray operation state.
- `xa_mark_t mark`: Mark number.

**Description**

Clears the specified mark on this entry, and walks back to the head
attempting to clear it on all the ancestor entries.  Does nothing if
**xas** has not been walked to an entry, or is in an error state.

#### <a id="c-xas_init_marks"></a>`xas_init_marks()`

```c
void xas_init_marks(const struct xa_state *xas)
```

Initialise all marks for the entry

**Parameters**

- `const struct xa_state *xas`: Array operations state.

**Description**

Initialise all marks for the entry specified by **xas**.  If we're tracking
free entries with a mark, we need to set it on all entries.  All other
marks are cleared.

This implementation is not as efficient as it could be; we may walk
up the tree multiple times.

#### <a id="c-xas_split_alloc"></a>`xas_split_alloc()`

```c
void xas_split_alloc(struct xa_state *xas, void *entry, unsigned int order, gfp_t gfp)
```

Allocate memory for splitting an entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `void *entry`: New entry which will be stored in the array.
- `unsigned int order`: Current entry order.
- `gfp_t gfp`: Memory allocation flags.

**Description**

This function should be called before calling [`xas_split()`](#c-xas_split).
If necessary, it will allocate new nodes (and fill them with **entry**)
to prepare for the upcoming split of an entry of **order** size into
entries of the order stored in the **xas**.

**Context**

May sleep if **gfp** flags permit.

#### <a id="c-xas_split"></a>`xas_split()`

```c
void xas_split(struct xa_state *xas, void *entry, unsigned int order)
```

Split a multi-index entry into smaller entries.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `void *entry`: New entry to store in the array.
- `unsigned int order`: Current entry order.

**Description**

The size of the new entries is set in **xas**.  The value in **entry** is
copied to all the replacement entries.

**Context**

Any context.  The caller should hold the xa_lock.

#### <a id="c-xas_try_split_min_order"></a>`xas_try_split_min_order()`

```c
unsigned int xas_try_split_min_order(unsigned int order)
```

Minimal split order [`xas_try_split()`](#c-xas_try_split) can accept

**Parameters**

- `unsigned int order`: Current entry order.

**Description**

[`xas_try_split()`](#c-xas_try_split) can split a multi-index entry to smaller than **order** - 1 if
no new xa_node is needed. This function provides the minimal order
[`xas_try_split()`](#c-xas_try_split) supports.

**Return**

the minimal order [`xas_try_split()`](#c-xas_try_split) supports

**Context**

Any context.

#### <a id="c-xas_try_split"></a>`xas_try_split()`

```c
void xas_try_split(struct xa_state *xas, void *entry, unsigned int order)
```

Try to split a multi-index entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `void *entry`: New entry to store in the array.
- `unsigned int order`: Current entry order.

**Description**

The size of the new entries is set in **xas**.  The value in **entry** is
copied to all the replacement entries. If and only if one new xa_node is
needed, the function will use GFP_NOWAIT to get one if xas->xa_alloc is
NULL. If more new xa_node are needed, the function gives EINVAL error.

**NOTE**

use [`xas_try_split_min_order()`](#c-xas_try_split_min_order) to get next split order instead of
**order** - 1 if you want to minmize [`xas_try_split()`](#c-xas_try_split) calls.

**Context**

Any context.  The caller should hold the xa_lock.

#### <a id="c-xas_pause"></a>`xas_pause()`

```c
void xas_pause(struct xa_state *xas)
```

Pause a walk to drop a lock.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Some users need to pause a walk and drop the lock they're holding in
order to yield to a higher priority thread or carry out an operation
on an entry.  Those users should call this function before they drop
the lock.  It resets the **xas** to be suitable for the next iteration
of the loop after the user has reacquired the lock.  If most entries
found during a walk require you to call [`xas_pause()`](#c-xas_pause), the [`xa_for_each()`](#c-xa_for_each)
iterator may be more appropriate.

Note that [`xas_pause()`](#c-xas_pause) only works for forward iteration.  If a user needs
to pause a reverse iteration, we will need a `xas_pause_rev()`.

#### <a id="c-xas_find"></a>`xas_find()`

```c
void * xas_find(struct xa_state *xas, unsigned long max)
```

Find the next present entry in the XArray.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long max`: Highest index to return.

**Description**

If the **xas** has not yet been walked to an entry, return the entry
which has an index >= xas.xa_index.  If it has been walked, the entry
currently being pointed at has been processed, and so we move to the
next entry.

If no entry is found and the array is smaller than **max**, the iterator
is set to the smallest index not yet in the array.  This allows **xas**
to be immediately passed to [`xas_store()`](#c-xas_store).

**Return**

The entry, if found, otherwise `NULL`.

#### <a id="c-xas_find_marked"></a>`xas_find_marked()`

```c
void * xas_find_marked(struct xa_state *xas, unsigned long max, xa_mark_t mark)
```

Find the next marked entry in the XArray.

**Parameters**

- `struct xa_state *xas`: XArray operation state.
- `unsigned long max`: Highest index to return.
- `xa_mark_t mark`: Mark number to search for.

**Description**

If the **xas** has not yet been walked to an entry, return the marked entry
which has an index >= xas.xa_index.  If it has been walked, the entry
currently being pointed at has been processed, and so we return the
first marked entry with an index > xas.xa_index.

If no marked entry is found and the array is smaller than **max**, **xas** is
set to the bounds state and xas->xa_index is set to the smallest index
not yet in the array.  This allows **xas** to be immediately passed to
[`xas_store()`](#c-xas_store).

If no entry is found before **max** is reached, **xas** is set to the restart
state.

**Return**

The entry, if found, otherwise `NULL`.

#### <a id="c-xas_find_conflict"></a>`xas_find_conflict()`

```c
void * xas_find_conflict(struct xa_state *xas)
```

Find the next present entry in a range.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

The **xas** describes both a range and a position within that range.

**Context**

Any context.  Expects xa_lock to be held.

**Return**

The next entry in the range covered by **xas** or `NULL`.

#### <a id="c-xa_load"></a>`xa_load()`

```c
void * xa_load(struct xarray *xa, unsigned long index)
```

Load an entry from an XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: index into array.

**Context**

Any context.  Takes and releases the RCU lock.

**Return**

The entry at **index** in **xa**.

#### <a id="c-__xa_erase"></a>`__xa_erase()`

```c
void * __xa_erase(struct xarray *xa, unsigned long index)
```

Erase this entry from the XArray while locked.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.

**Description**

After this function returns, loading from **index** will return `NULL`.
If the index is part of a multi-index entry, all indices will be erased
and none of the entries will be part of a multi-index entry.

**Context**

Any context.  Expects xa_lock to be held on entry.

**Return**

The entry which used to be at this index.

#### <a id="c-xa_erase"></a>`xa_erase()`

```c
void * xa_erase(struct xarray *xa, unsigned long index)
```

Erase this entry from the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.

**Description**

After this function returns, loading from **index** will return `NULL`.
If the index is part of a multi-index entry, all indices will be erased
and none of the entries will be part of a multi-index entry.

**Context**

Any context.  Takes and releases the xa_lock.

**Return**

The entry which used to be at this index.

#### <a id="c-__xa_store"></a>`__xa_store()`

```c
void * __xa_store(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

You must already be holding the xa_lock when calling this function.
It will drop the lock if needed to allocate memory, and then reacquire
it afterwards.

**Context**

Any context.  Expects xa_lock to be held on entry.  May
release and reacquire xa_lock if **gfp** flags permit.

**Return**

The old entry at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-xa_store"></a>`xa_store()`

```c
void * xa_store(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

After this function returns, loads from this index will return **entry**.
Storing into an existing multi-index entry updates the entry of every index.
The marks associated with **index** are unaffected unless **entry** is `NULL`.

**Context**

Any context.  Takes and releases the xa_lock.
May sleep if the **gfp** flags permit.

**Return**

The old entry at this index on success, xa_err(-EINVAL) if **entry**
cannot be stored in an XArray, or xa_err(-ENOMEM) if memory allocation
failed.

#### <a id="c-__xa_cmpxchg"></a>`__xa_cmpxchg()`

```c
void * __xa_cmpxchg(struct xarray *xa, unsigned long index, void *old, void *entry, gfp_t gfp)
```

Conditionally replace an entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *old`: Old value to test against.
- `void *entry`: New value to place in array.
- `gfp_t gfp`: Memory allocation flags.

**Description**

You must already be holding the xa_lock when calling this function.
It will drop the lock if needed to allocate memory, and then reacquire
it afterwards.

If the entry at **index** is the same as **old**, replace it with **entry**.
If the return value is equal to **old**, then the exchange was successful.

**Context**

Any context.  Expects xa_lock to be held on entry.  May
release and reacquire xa_lock if **gfp** flags permit.

**Return**

The old value at this index or [`xa_err()`](#c-xa_err) if an error happened.

#### <a id="c-__xa_insert"></a>`__xa_insert()`

```c
int __xa_insert(struct xarray *xa, unsigned long index, void *entry, gfp_t gfp)
```

Store this entry in the XArray if no entry is present.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index into array.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Inserting a NULL entry will store a reserved entry (like [`xa_reserve()`](#c-xa_reserve))
if no entry is present.  Inserting will fail if a reserved entry is
present, even though loading from this index will return NULL.

**Context**

Any context.  Expects xa_lock to be held on entry.  May
release and reacquire xa_lock if **gfp** flags permit.

**Return**

0 if the store succeeded.  -EBUSY if another entry was present.
-ENOMEM if memory could not be allocated.

#### <a id="c-xa_store_range"></a>`xa_store_range()`

```c
void * xa_store_range(struct xarray *xa, unsigned long first, unsigned long last, void *entry, gfp_t gfp)
```

Store this entry at a range of indices in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long first`: First index to affect.
- `unsigned long last`: Last index to affect.
- `void *entry`: New entry.
- `gfp_t gfp`: Memory allocation flags.

**Description**

After this function returns, loads from any index between **first** and **last**,
inclusive will return **entry**.
Storing into an existing multi-index entry updates the entry of every index.
The marks associated with **index** are unaffected unless **entry** is `NULL`.

**Context**

Process context.  Takes and releases the xa_lock.  May sleep
if the **gfp** flags permit.

**Return**

`NULL` on success, xa_err(-EINVAL) if **entry** cannot be stored in
an XArray, or xa_err(-ENOMEM) if memory allocation failed.

#### <a id="c-xas_get_order"></a>`xas_get_order()`

```c
int xas_get_order(struct xa_state *xas)
```

Get the order of an entry.

**Parameters**

- `struct xa_state *xas`: XArray operation state.

**Description**

Called after xas_load, the xas should not be in an error state.
The xas should not be pointing to a sibling entry.

**Return**

A number between 0 and 63 indicating the order of the entry.

#### <a id="c-xa_get_order"></a>`xa_get_order()`

```c
int xa_get_order(struct xarray *xa, unsigned long index)
```

Get the order of an entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of the entry.

**Return**

A number between 0 and 63 indicating the order of the entry.

#### <a id="c-__xa_alloc"></a>`__xa_alloc()`

```c
int __xa_alloc(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range for allocated ID.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

**Context**

Any context.  Expects xa_lock to be held on entry.  May
release and reacquire xa_lock if **gfp** flags permit.

**Return**

0 on success, -ENOMEM if memory could not be allocated or
-EBUSY if there are no free entries in **limit**.

#### <a id="c-__xa_alloc_cyclic"></a>`__xa_alloc_cyclic()`

```c
int __xa_alloc_cyclic(struct xarray *xa, u32 *id, void *entry, struct xa_limit limit, u32 *next, gfp_t gfp)
```

Find somewhere to store this entry in the XArray.

**Parameters**

- `struct xarray *xa`: XArray.
- `u32 *id`: Pointer to ID.
- `void *entry`: New entry.
- `struct xa_limit limit`: Range of allocated ID.
- `u32 *next`: Pointer to next ID to allocate.
- `gfp_t gfp`: Memory allocation flags.

**Description**

Finds an empty entry in **xa** between **limit.min** and **limit.max**,
stores the index into the **id** pointer, then stores the entry at
that index.  A concurrent lookup will not see an uninitialised **id**.
The search for an empty entry will start at **next** and will wrap
around if necessary.

Must only be operated on an xarray initialized with flag XA_FLAGS_ALLOC set
in [`xa_init_flags()`](#c-xa_init_flags).

**Context**

Any context.  Expects xa_lock to be held on entry.  May
release and reacquire xa_lock if **gfp** flags permit.

**Return**

0 if the allocation succeeded without wrapping.  1 if the
allocation succeeded after wrapping, -ENOMEM if memory could not be
allocated or -EBUSY if there are no free entries in **limit**.

#### <a id="c-__xa_set_mark"></a>`__xa_set_mark()`

```c
void __xa_set_mark(struct xarray *xa, unsigned long index, xa_mark_t mark)
```

Set this mark on this entry while locked.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.
- `xa_mark_t mark`: Mark number.

**Description**

Attempting to set a mark on a `NULL` entry does not succeed.

**Context**

Any context.  Expects xa_lock to be held on entry.

#### <a id="c-__xa_clear_mark"></a>`__xa_clear_mark()`

```c
void __xa_clear_mark(struct xarray *xa, unsigned long index, xa_mark_t mark)
```

Clear this mark on this entry while locked.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.
- `xa_mark_t mark`: Mark number.

**Context**

Any context.  Expects xa_lock to be held on entry.

#### <a id="c-xa_get_mark"></a>`xa_get_mark()`

```c
bool xa_get_mark(struct xarray *xa, unsigned long index, xa_mark_t mark)
```

Inquire whether this mark is set on this entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.
- `xa_mark_t mark`: Mark number.

**Description**

This function uses the RCU read lock, so the result may be out of date
by the time it returns.  If you need the result to be stable, use a lock.

**Context**

Any context.  Takes and releases the RCU lock.

**Return**

True if the entry at **index** has this mark set, false if it doesn't.

#### <a id="c-xa_set_mark"></a>`xa_set_mark()`

```c
void xa_set_mark(struct xarray *xa, unsigned long index, xa_mark_t mark)
```

Set this mark on this entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.
- `xa_mark_t mark`: Mark number.

**Description**

Attempting to set a mark on a `NULL` entry does not succeed.

**Context**

Process context.  Takes and releases the xa_lock.

#### <a id="c-xa_clear_mark"></a>`xa_clear_mark()`

```c
void xa_clear_mark(struct xarray *xa, unsigned long index, xa_mark_t mark)
```

Clear this mark on this entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long index`: Index of entry.
- `xa_mark_t mark`: Mark number.

**Description**

Clearing a mark always succeeds.

**Context**

Process context.  Takes and releases the xa_lock.

#### <a id="c-xa_find"></a>`xa_find()`

```c
void * xa_find(struct xarray *xa, unsigned long *indexp, unsigned long max, xa_mark_t filter)
```

Search the XArray for an entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long *indexp`: Pointer to an index.
- `unsigned long max`: Maximum index to search to.
- `xa_mark_t filter`: Selection criterion.

**Description**

Finds the entry in **xa** which matches the **filter**, and has the lowest
index that is at least **indexp** and no more than **max**.
If an entry is found, **indexp** is updated to be the index of the entry.
This function is protected by the RCU read lock, so it may not find
entries which are being simultaneously added.  It will not return an
`XA_RETRY_ENTRY`; if you need to see retry entries, use [`xas_find()`](#c-xas_find).

**Context**

Any context.  Takes and releases the RCU lock.

**Return**

The entry, if found, otherwise `NULL`.

#### <a id="c-xa_find_after"></a>`xa_find_after()`

```c
void * xa_find_after(struct xarray *xa, unsigned long *indexp, unsigned long max, xa_mark_t filter)
```

Search the XArray for a present entry.

**Parameters**

- `struct xarray *xa`: XArray.
- `unsigned long *indexp`: Pointer to an index.
- `unsigned long max`: Maximum index to search to.
- `xa_mark_t filter`: Selection criterion.

**Description**

Finds the entry in **xa** which matches the **filter** and has the lowest
index that is above **indexp** and no more than **max**.
If an entry is found, **indexp** is updated to be the index of the entry.
This function is protected by the RCU read lock, so it may miss entries
which are being simultaneously added.  It will not return an
`XA_RETRY_ENTRY`; if you need to see retry entries, use [`xas_find()`](#c-xas_find).

**Context**

Any context.  Takes and releases the RCU lock.

**Return**

The pointer, if found, otherwise `NULL`.

#### <a id="c-xa_extract"></a>`xa_extract()`

```c
unsigned int xa_extract(struct xarray *xa, void **dst, unsigned long start, unsigned long max, unsigned int n, xa_mark_t filter)
```

Copy selected entries from the XArray into a normal array.

**Parameters**

- `struct xarray *xa`: The source XArray to copy from.
- `void **dst`: The buffer to copy entries into.
- `unsigned long start`: The first index in the XArray eligible to be selected.
- `unsigned long max`: The last index in the XArray eligible to be selected.
- `unsigned int n`: The maximum number of entries to copy.
- `xa_mark_t filter`: Selection criterion.

**Description**

Copies up to **n** entries that match **filter** from the XArray.  The
copied entries will have indices between **start** and **max**, inclusive.

The **filter** may be an XArray mark value, in which case entries which are
marked with that mark will be copied.  It may also be `XA_PRESENT`, in
which case all entries which are not `NULL` will be copied.

The entries returned may not represent a snapshot of the XArray at a
moment in time.  For example, if another thread stores to index 5, then
index 10, calling [`xa_extract()`](#c-xa_extract) may return the old contents of index 5
and the new contents of index 10.  Indices not modified while this
function is running will not be skipped.

If you need stronger guarantees, holding the xa_lock across calls to this
function will prevent concurrent modification.

**Context**

Any context.  Takes and releases the RCU lock.

**Return**

The number of entries copied.

#### <a id="c-xa_delete_node"></a>`xa_delete_node()`

```c
void xa_delete_node(struct xa_node *node, xa_update_node_t update)
```

Private interface for workingset code.

**Parameters**

- `struct xa_node *node`: Node to be removed from the tree.
- `xa_update_node_t update`: Function to call to update ancestor nodes.

**Context**

xa_lock must be held on entry and will not be released.

#### <a id="c-xa_destroy"></a>`xa_destroy()`

```c
void xa_destroy(struct xarray *xa)
```

Free all internal data structures.

**Parameters**

- `struct xarray *xa`: XArray.

**Description**

After calling this function, the XArray is empty and has freed all memory
allocated for its internal data structures.  You are responsible for
freeing the objects referenced by the XArray.

**Context**

Any context.  Takes and releases the xa_lock, interrupt-safe.

---

# IRQs

_Peios Kernel / Internals / Core APIs / irq_

> Reference for IRQs.

<a id="rst-irqs"></a>

- [What is an IRQ?](</kernel/internals/core-api/irq/concepts.md>)
- [SMP IRQ affinity](</kernel/internals/core-api/irq/irq-affinity.md>)
- [The irq_domain Interrupt Number Mapping Library](</kernel/internals/core-api/irq/irq-domain.md>)
- [IRQ-flags state tracing](</kernel/internals/core-api/irq/irqflags-tracing.md>)

---

# What is an IRQ?

_Peios Kernel / Internals / Core APIs / irq_

> An IRQ is an interrupt request from a device. Currently, they can come in over a pin, or over a packet. Several devices may be connected to the same pin thus sharing an IRQ. Such as on legacy PCI bus: All devices typically share 4…

<a id="rst-what-is-an-irq"></a>

An IRQ is an interrupt request from a device. Currently, they can come in over a pin, or over a packet. Several devices may be connected to the same pin thus sharing an IRQ. Such as on legacy PCI bus: All devices typically share 4 lanes/pins. Note that each device can request an interrupt on each of the lanes.

An IRQ number is a kernel identifier used to talk about a hardware interrupt source. Typically, this is an index into the global irq_desc array or sparse_irqs tree. But except for what linux/interrupt.h implements, the details are architecture specific.

An IRQ number is an enumeration of the possible interrupt sources on a machine. Typically, what is enumerated is the number of input pins on all of the interrupt controllers in the system. In the case of ISA, what is enumerated are the 8 input pins on each of the two i8259 interrupt controllers.

Architectures can assign additional meaning to the IRQ numbers, and are encouraged to in the case where there is any manual configuration of the hardware involved. The ISA IRQs are a classic example of assigning this kind of additional meaning.

---

# SMP IRQ affinity

_Peios Kernel / Internals / Core APIs / irq_

> Started by Ingo Molnar <mingo@redhat.com>

<a id="rst-smp-irq-affinity"></a>

- **ChangeLog:**

  - Started by Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;

  - Update by Max Krasnyansky &lt;[maxk@qualcomm.com](<mailto:maxk@qualcomm.com>)&gt;

/proc/irq/IRQ\#/smp_affinity and /proc/irq/IRQ\#/smp_affinity_list specify which target CPUs are permitted for a given IRQ source.  It's a bitmask (smp_affinity) or CPU list (smp_affinity_list) of allowed CPUs.  It's not allowed to turn off all CPUs, and if an IRQ controller does not support IRQ affinity then the value will not change from the default of all CPUs.

/proc/irq/default_smp_affinity specifies default affinity mask that applies to all non-active IRQs. Once IRQ is allocated/activated its affinity bitmask will be set to the default mask. It can then be changed as described above. Default mask is 0xffffffff.

Here is an example of restricting IRQ44 (eth1) to CPU0-3 then restricting it to CPU4-7 (this is an 8-CPU SMP box):



```text
[root@moon 44]# cd /proc/irq/44
[root@moon 44]# cat smp_affinity
ffffffff

[root@moon 44]# echo 0f > smp_affinity
[root@moon 44]# cat smp_affinity
0000000f
[root@moon 44]# ping -f h
PING hell (195.4.7.3): 56 data bytes
...
--- hell ping statistics ---
6029 packets transmitted, 6027 packets received, 0% packet loss
round-trip min/avg/max = 0.1/0.1/0.4 ms
[root@moon 44]# cat /proc/interrupts | grep 'CPU\|44:'
        CPU0       CPU1       CPU2       CPU3      CPU4       CPU5        CPU6       CPU7
44:       1068       1785       1785       1783         0          0           0         0    IO-APIC-level  eth1
```

As can be seen from the line above IRQ44 was delivered only to the first four processors (0-3). Now lets restrict that IRQ to CPU(4-7).



```text
[root@moon 44]# echo f0 > smp_affinity
[root@moon 44]# cat smp_affinity
000000f0
[root@moon 44]# ping -f h
PING hell (195.4.7.3): 56 data bytes
..
--- hell ping statistics ---
2779 packets transmitted, 2777 packets received, 0% packet loss
round-trip min/avg/max = 0.1/0.5/585.4 ms
[root@moon 44]# cat /proc/interrupts |  'CPU\|44:'
        CPU0       CPU1       CPU2       CPU3      CPU4       CPU5        CPU6       CPU7
44:       1068       1785       1785       1783      1784       1069        1070       1069   IO-APIC-level  eth1
```

This time around IRQ44 was delivered only to the last four processors. i.e counters for the CPU0-3 did not change.

Here is an example of limiting that same IRQ (44) to CPUs 1024 to 1031:



```text
[root@moon 44]# echo 1024-1031 > smp_affinity_list
[root@moon 44]# cat smp_affinity_list
1024-1031
```

Note that to do this with a bitmask would require 32 bitmasks of zero to follow the pertinent one.

---

# The irq_domain Interrupt Number Mapping Library

_Peios Kernel / Internals / Core APIs / irq_

> The current design of the Linux kernel uses a single large number space where each separate IRQ source is assigned a unique number. This is simple when there is only one interrupt controller. But in systems with multiple interrupt…

<a id="rst-the-irq-domain-interrupt-number-mapping-library"></a>

The current design of the Linux kernel uses a single large number space where each separate IRQ source is assigned a unique number. This is simple when there is only one interrupt controller. But in systems with multiple interrupt controllers, the kernel must ensure that each one gets assigned non-overlapping allocations of Linux IRQ numbers.

The number of interrupt controllers registered as unique irqchips shows a rising tendency. For example, subdrivers of different kinds such as GPIO controllers avoid reimplementing identical callback mechanisms as the IRQ core system by modelling their interrupt handlers as irqchips. I.e. in effect cascading interrupt controllers.

So in the past, IRQ numbers could be chosen so that they match the hardware IRQ line into the root interrupt controller (i.e. the component actually firing the interrupt line to the CPU). Nowadays, this number is just a number and the number has no relationship to hardware interrupt numbers.

For this reason, we need a mechanism to separate controller-local interrupt numbers, called hardware IRQs, from Linux IRQ numbers.

The irq_alloc_desc\*() and irq_free_desc\*() APIs provide allocation of IRQ numbers, but they don't provide any support for reverse mapping of the controller-local IRQ (hwirq) number into the Linux IRQ number space.

The irq_domain library adds a mapping between hwirq and IRQ numbers on top of the irq_alloc_desc\*() API. An irq_domain to manage the mapping is preferred over interrupt controller drivers open coding their own reverse mapping scheme.

irq_domain also implements a translation from an abstract struct irq_fwspec to hwirq numbers (Device Tree, non-DT firmware node, ACPI GSI, and software node so far), and can be easily extended to support other IRQ topology data sources. The implementation is performed without any extra platform support code.

<a id="rst-irq-domain-usage"></a>

## irq_domain Usage

struct irq_domain could be defined as an irq domain controller. That is, it handles the mapping between hardware and virtual interrupt numbers for a given interrupt domain. The domain structure is generally created by the PIC code for a given PIC instance (though a domain can cover more than one PIC if they have a flat number model). It is the domain callbacks that are responsible for setting the irq_chip on a given irq_desc after it has been mapped.

The host code and data structures use a fwnode_handle pointer to identify the domain. In some cases, and in order to preserve source code compatibility, this fwnode pointer is "upgraded" to a DT device_node. For those firmware infrastructures that do not provide a unique identifier for an interrupt controller, the irq_domain code offers a fwnode allocator.

An interrupt controller driver creates and registers a struct irq_domain by calling one of the irq_domain_create\_\*() functions (each mapping method has a different allocator function, more on that later). The function will return a pointer to the struct irq_domain on success. The caller must provide the allocator function with a struct irq_domain_ops pointer.

In most cases, the irq_domain will begin empty without any mappings between hwirq and IRQ numbers.  Mappings are added to the irq_domain by calling irq_create_mapping() which accepts the irq_domain and a hwirq number as arguments. If a mapping for the hwirq doesn't already exist, irq_create_mapping() allocates a new Linux irq_desc, associates it with the hwirq, and calls the `irq_domain_ops.map()` callback. In there, the driver can perform any required hardware setup.

Once a mapping has been established, it can be retrieved or used via a variety of methods:

- irq_resolve_mapping() returns a pointer to the irq_desc structure for a given domain and hwirq number, or NULL if there was no mapping.

- irq_find_mapping() returns a Linux IRQ number for a given domain and hwirq number, or 0 if there was no mapping

- generic_handle_domain_irq() handles an interrupt described by a domain and a hwirq number

Note that irq_domain lookups must happen in contexts that are compatible with an RCU read-side critical section.

The irq_create_mapping() function must be called *at least once* before any call to irq_find_mapping(), lest the descriptor will not be allocated.

If the driver has the Linux IRQ number or the irq_data pointer, and needs to know the associated hwirq number (such as in the irq_chip callbacks) then it can be directly obtained from `irq_data.hwirq`.

<a id="rst-types-of-irq-domain-mappings"></a>

## Types of irq_domain Mappings

There are several mechanisms available for reverse mapping from hwirq to Linux IRQ, and each mechanism uses a different allocation function. Which reverse map type should be used depends on the use case.  Each of the reverse map types are described below:

<a id="rst-linear"></a>

### Linear



```text
irq_domain_create_linear()
```

The linear reverse map maintains a fixed-size table indexed by the hwirq number.  When a hwirq is mapped, an irq_desc is allocated for the hwirq, and the IRQ number is stored in the table.

The Linear map is a good choice when the maximum number of hwirqs is fixed and a relatively small number (\~ &lt; 256).  The advantages of this map are fixed-time lookup for IRQ numbers, and irq_descs are only allocated for in-use IRQs.  The disadvantage is that the table must be as large as the largest possible hwirq number.

The majority of drivers should use the Linear map.

<a id="rst-tree"></a>

### Tree



```text
irq_domain_create_tree()
```

The irq_domain maintains a radix tree map from hwirq numbers to Linux IRQs.  When an hwirq is mapped, an irq_desc is allocated and the hwirq is used as the lookup key for the radix tree.

The Tree map is a good choice if the hwirq number can be very large since it doesn't need to allocate a table as large as the largest hwirq number.  The disadvantage is that hwirq to IRQ number lookup is dependent on how many entries are in the table.

Very few drivers should need this mapping.

<a id="rst-no-map"></a>

### No Map



```text
irq_domain_create_nomap()
```

The No Map mapping is to be used when the hwirq number is programmable in the hardware.  In this case it is best to program the Linux IRQ number into the hardware itself so that no mapping is required.  Calling irq_create_direct_mapping() will allocate a Linux IRQ number and call the .map() callback so that driver can program the Linux IRQ number into the hardware.

Most drivers cannot use this mapping, and it is now gated on the CONFIG_IRQ_DOMAIN_NOMAP option. Please refrain from introducing new users of this API.

<a id="rst-legacy"></a>

### Legacy



```text
irq_domain_create_simple()
irq_domain_create_legacy()
```

The Legacy mapping is a special case for drivers that already have a range of irq_descs allocated for the hwirqs.  It is used when the driver cannot be immediately converted to use the Linear mapping.  For example, many embedded system board support files use a set of \#defines for IRQ numbers that are passed to struct device registrations.  In that case the Linux IRQ numbers cannot be dynamically assigned and the Legacy mapping should be used.

As the name implies, the \*\_legacy() functions are deprecated and only exist to ease the support of ancient platforms. No new users should be added. Same goes for the \*\_simple() functions when their use results in the legacy behaviour.

The Legacy map assumes a contiguous range of IRQ numbers has already been allocated for the controller and that the IRQ number can be calculated by adding a fixed offset to the hwirq number, and visa-versa.  The disadvantage is that it requires the interrupt controller to manage IRQ allocations and it requires an irq_desc to be allocated for every hwirq, even if it is unused.

The Legacy map should only be used if fixed IRQ mappings must be supported.  For example, ISA controllers would use the Legacy map for mapping Linux IRQs 0-15 so that existing ISA drivers get the correct IRQ numbers.

Most users of legacy mappings should use irq_domain_create_simple() which will use a legacy domain only if an IRQ range is supplied by the system and will otherwise use a linear domain mapping. The semantics of this call are such that if an IRQ range is specified then descriptors will be allocated on-the-fly for it, and if no range is specified it will fall through to irq_domain_create_linear() which means *no* IRQ descriptors will be allocated.

A typical use case for simple domains is where an irqchip provider is supporting both dynamic and static IRQ assignments.

In order to avoid ending up in a situation where a linear domain is used and no descriptor gets allocated it is very important to make sure that the driver using the simple domain call irq_create_mapping() before any irq_find_mapping() since the latter will actually work for the static IRQ assignment case.

<a id="rst-hierarchy-irq-domain"></a>

### Hierarchy IRQ Domain

On some architectures, there may be multiple interrupt controllers involved in delivering an interrupt from the device to the target CPU. Let's look at a typical interrupt delivery path on x86 platforms:



```text
Device --> IOAPIC -> Interrupt remapping Controller -> Local APIC -> CPU
```

There are three interrupt controllers involved:

1. IOAPIC controller

2. Interrupt remapping controller

3. Local APIC controller

To support such a hardware topology and make software architecture match hardware architecture, an irq_domain data structure is built for each interrupt controller and those irq_domains are organized into hierarchy. When building irq_domain hierarchy, the irq_domain nearest the device is child and the irq_domain nearest the CPU is parent. So a hierarchy structure as below will be built for the example above:



```text
CPU Vector irq_domain (root irq_domain to manage CPU vectors)
        ^
        |
Interrupt Remapping irq_domain (manage irq_remapping entries)
        ^
        |
IOAPIC irq_domain (manage IOAPIC delivery entries/pins)
```

There are four major interfaces to use hierarchy irq_domain:

1. irq_domain_alloc_irqs(): allocate IRQ descriptors and interrupt controller related resources to deliver these interrupts.

2. irq_domain_free_irqs(): free IRQ descriptors and interrupt controller related resources associated with these interrupts.

3. irq_domain_activate_irq(): activate interrupt controller hardware to deliver the interrupt.

4. irq_domain_deactivate_irq(): deactivate interrupt controller hardware to stop delivering the interrupt.

The following is needed to support hierarchy irq_domain:

1. The `parent` field in struct irq_domain is used to maintain irq_domain hierarchy information.

2. The `parent_data` field in struct irq_data is used to build hierarchy irq_data to match hierarchy irq_domains. The irq_data is used to store irq_domain pointer and hardware irq number.

3. The `alloc()`, `free()`, and other callbacks in struct irq_domain_ops to support hierarchy irq_domain operations.

With the support of hierarchy irq_domain and hierarchy irq_data ready, an irq_domain structure is built for each interrupt controller, and an irq_data structure is allocated for each irq_domain associated with an IRQ.

For an interrupt controller driver to support hierarchy irq_domain, it needs to:

1. Implement irq_domain_ops.alloc() and irq_domain_ops.free()

2. Optionally, implement irq_domain_ops.activate() and irq_domain_ops.deactivate().

3. Optionally, implement an irq_chip to manage the interrupt controller hardware.

4. There is no need to implement irq_domain_ops.map() and irq_domain_ops.unmap(). They are unused with hierarchy irq_domain.

Note the hierarchy irq_domain is in no way x86-specific, and is heavily used to support other architectures, such as ARM, ARM64 etc.

<a id="rst-stacked-irq-chip"></a>

#### Stacked irq_chip

Now, we could go one step further to support stacked (hierarchy) irq_chip. That is, an irq_chip is associated with each irq_data along the hierarchy. A child irq_chip may implement a required action by itself or by cooperating with its parent irq_chip.

With stacked irq_chip, interrupt controller driver only needs to deal with the hardware managed by itself and may ask for services from its parent irq_chip when needed. So we could achieve a much cleaner software architecture.

<a id="rst-debugging"></a>

## Debugging

Most of the internals of the IRQ subsystem are exposed in debugfs by turning CONFIG_GENERIC_IRQ_DEBUGFS on.

<a id="rst-structures-and-public-functions-provided"></a>

## Structures and Public Functions Provided

This chapter contains the autogenerated documentation of the structures and exported kernel API functions which are used for IRQ domains.


#### <a id="c-struct-irq_fwspec"></a>`struct irq_fwspec`

generic IRQ specifier structure

**Definition**

```c
struct irq_fwspec {
    struct fwnode_handle    *fwnode;
    int param_count;
    u32 param[IRQ_DOMAIN_IRQ_SPEC_PARAMS];
};
```

**Members**

- `fwnode`: Pointer to a firmware-specific descriptor
- `param_count`: Number of device-specific parameters
- `param`: Device-specific parameters

**Description**

This structure, directly modeled after of_phandle_args, is used to
pass a device-specific description of an interrupt.

#### <a id="c-struct-irq_fwspec_info"></a>`struct irq_fwspec_info`

firmware provided IRQ information structure

**Definition**

```c
struct irq_fwspec_info {
    unsigned long           flags;
    const struct cpumask    *affinity;
};
```

**Members**

- `flags`: Information validity flags
- `affinity`: Affinity mask for this interrupt

**Description**

This structure reports firmware-specific information about an
interrupt. The only significant information is the affinity of a
per-CPU interrupt, but this is designed to be extended as required.

#### <a id="c-struct-irq_domain_ops"></a>`struct irq_domain_ops`

Methods for irq_domain objects

**Definition**

```c
struct irq_domain_ops {
        int (*match)(struct irq_domain *d, struct device_node *node, enum irq_domain_bus_token bus_token);
        int (*select)(struct irq_domain *d, struct irq_fwspec *fwspec, enum irq_domain_bus_token bus_token);
        int (*map)(struct irq_domain *d, unsigned int virq, irq_hw_number_t hw);
        void (*unmap)(struct irq_domain *d, unsigned int virq);
        int (*xlate)(struct irq_domain *d, struct device_node *node, const u32 *intspec, unsigned int intsize, unsigned long *out_hwirq, unsigned int *out_type);
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        int (*alloc)(struct irq_domain *d, unsigned int virq, unsigned int nr_irqs, void *arg);
        void (*free)(struct irq_domain *d, unsigned int virq, unsigned int nr_irqs);
        int (*activate)(struct irq_domain *d, struct irq_data *irqd, bool reserve);
        void (*deactivate)(struct irq_domain *d, struct irq_data *irq_data);
        int (*translate)(struct irq_domain *d, struct irq_fwspec *fwspec, unsigned long *out_hwirq, unsigned int *out_type);
        int (*get_fwspec_info)(struct irq_fwspec *fwspec, struct irq_fwspec_info *info);
    #endif;
    #ifdef CONFIG_GENERIC_IRQ_DEBUGFS;
        void (*debug_show)(struct seq_file *m, struct irq_domain *d, struct irq_data *irqd, int ind);
    #endif;
};
```

**Members**

- `match`: Match an interrupt controller device node to a domain, returns
  1 on a match
- `select`: Match an interrupt controller fw specification. It is more generic
  than **match** as it receives a complete struct irq_fwspec. Therefore,
  **select** is preferred if provided. Returns 1 on a match.
- `map`: Create or update a mapping between a virtual irq number and a hw
  irq number. This is called only once for a given mapping.
- `unmap`: Dispose of such a mapping
- `xlate`: Given a device tree node and interrupt specifier, decode
  the hardware irq number and linux irq type value.
- `alloc`: Allocate **nr_irqs** interrupts starting from **virq**.
- `free`: Free **nr_irqs** interrupts starting from **virq**.
- `activate`: Activate one interrupt in HW (**irqd**). If **reserve** is set, only
  reserve the vector. If unset, assign the vector (called from
  [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq)).
- `deactivate`: Disarm one interrupt (**irqd**).
- `translate`: Given **fwspec**, decode the hardware irq number (**out_hwirq**) and
  linux irq type value (**out_type**). This is a generalised **xlate**
  (over struct irq_fwspec) and is preferred if provided.
- `get_fwspec_info`: Given **fwspec**, report additional firmware-provided information in
  **info**. Optional.
- `debug_show`: For domains to show specific data for an interrupt in debugfs.

**Description**

Functions below are provided by the driver and called whenever a new mapping
is created or an old mapping is disposed. The driver can then proceed to
whatever internal data structures management is required. It also needs
to setup the irq_desc when returning from `map()`.

#### <a id="c-struct-irq_domain"></a>`struct irq_domain`

Hardware interrupt number translation object

**Definition**

```c
struct irq_domain {
        struct list_head                link;
        const char                      *name;
        const struct irq_domain_ops     *ops;
        void *host_data;
        unsigned int                    flags;
        unsigned int                    mapcount;
        struct mutex                    mutex;
        struct irq_domain               *root;
        struct fwnode_handle            *fwnode;
        enum irq_domain_bus_token       bus_token;
        struct irq_domain_chip_generic  *gc;
        struct device                   *dev;
        struct device                   *pm_dev;
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        struct irq_domain               *parent;
    #endif;
    #ifdef CONFIG_GENERIC_MSI_IRQ;
        const struct msi_parent_ops     *msi_parent_ops;
    #endif;
        void (*exit)(struct irq_domain *d);
        irq_hw_number_t hwirq_max;
        unsigned int                    revmap_size;
        struct radix_tree_root          revmap_tree;
        struct irq_data            *revmap[] ;
};
```

**Members**

- `link`: Element in global irq_domain list.
- `name`: Name of interrupt domain
- `ops`: Pointer to irq_domain methods
- `host_data`: Private data pointer for use by owner.  Not touched by irq_domain
  core code.
- `flags`: Per irq_domain flags
- `mapcount`: The number of mapped interrupts
- `mutex`: Domain lock, hierarchical domains use root domain's lock
- `root`: Pointer to root domain, or containing structure if non-hierarchical
- `fwnode`: Pointer to firmware node associated with the irq_domain. Pretty easy
  to swap it for the of_node via the irq_domain_get_of_node accessor
- `bus_token`:

  **fwnode**'s device_node might be used for several irq domains. But
  in connection with **bus_token**, the pair shall be unique in a
  system.
- `gc`: Pointer to a list of generic chips. There is a helper function for
  setting up one or more generic chips for interrupt controllers
  drivers using the generic chip library which uses this pointer.
- `dev`: Pointer to the device which instantiated the irqdomain
  With per device irq domains this is not necessarily the same
  as **pm_dev**.
- `pm_dev`: Pointer to a device that can be utilized for power management
  purposes related to the irq domain.
- `parent`: Pointer to parent irq_domain to support hierarchy irq_domains
- `msi_parent_ops`: Pointer to MSI parent domain methods for per device domain init
- `exit`: Function called when the domain is destroyed
- `hwirq_max`: Top limit for the HW irq number. Especially to avoid
  conflicts/failures with reserved HW irqs. Can be ~0.
- `revmap_size`: Size of the linear map table **revmap**
- `revmap_tree`: Radix map tree for hwirqs that don't fit in the linear map
- `revmap`: Linear table of irq_data pointers

**Description**

Optional elements:

Revmap data, used internally by the irq domain code:

#### <a id="c-struct-irq_domain_info"></a>`struct irq_domain_info`

Domain information structure

**Definition**

```c
struct irq_domain_info {
        struct fwnode_handle                    *fwnode;
        unsigned int                            domain_flags;
        unsigned int                            size;
        irq_hw_number_t hwirq_max;
        int direct_max;
        unsigned int                            hwirq_base;
        unsigned int                            virq_base;
        enum irq_domain_bus_token               bus_token;
        const char                              *name_suffix;
        const struct irq_domain_ops             *ops;
        void *host_data;
        struct device                           *dev;
    #ifdef CONFIG_IRQ_DOMAIN_HIERARCHY;
        struct irq_domain                       *parent;
    #endif;
        struct irq_domain_chip_generic_info     *dgc_info;
        int (*init)(struct irq_domain *d);
        void (*exit)(struct irq_domain *d);
};
```

**Members**

- `fwnode`: firmware node for the interrupt controller
- `domain_flags`: Additional flags to add to the domain flags
- `size`: Size of linear map; 0 for radix mapping only
- `hwirq_max`: Maximum number of interrupts supported by controller
- `direct_max`: Maximum value of direct maps;
  Use ~0 for no limit; 0 for no direct mapping
- `hwirq_base`: The first hardware interrupt number (legacy domains only)
- `virq_base`: The first Linux interrupt number for legacy domains to
  immediately associate the interrupts after domain creation
- `bus_token`: Domain bus token
- `name_suffix`: Optional name suffix to avoid collisions when multiple
  domains are added using same fwnode
- `ops`: Domain operation callbacks
- `host_data`: Controller private data pointer
- `dev`: Device which creates the domain
- `parent`: Pointer to the parent irq domain used in a hierarchy domain
- `dgc_info`: Geneneric chip information structure pointer used to
  create generic chips for the domain if not NULL.
- `init`: Function called when the domain is created.
  Allow to do some additional domain initialisation.
- `exit`: Function called when the domain is destroyed.
  Allow to do some additional cleanup operation.

#### <a id="c-irq_domain_create_linear"></a>`irq_domain_create_linear()`

```c
struct irq_domain * irq_domain_create_linear(struct fwnode_handle *fwnode, unsigned int size, const struct irq_domain_ops *ops, void *host_data)
```

Allocate and register a linear revmap irq_domain.

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to interrupt controller's FW node.
- `unsigned int size`: Number of interrupts in the domain.
- `const struct irq_domain_ops *ops`: map/unmap domain callbacks
- `void *host_data`: Controller private data pointer

**Return**

Newly created irq_domain

#### <a id="c-irq_create_mapping"></a>`irq_create_mapping()`

```c
unsigned int irq_create_mapping(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Map a hardware interrupt into linux irq space

**Parameters**

- `struct irq_domain *domain`: domain owning this hardware interrupt or NULL for default domain
- `irq_hw_number_t hwirq`: hardware irq number in that domain space

**Description**

Only one mapping per hardware interrupt is permitted.

If the sense/trigger is to be specified, `set_irq_type()` should be called
on the number returned from that call.

**Return**

Linux irq number or 0 on error

#### <a id="c-irq_resolve_mapping"></a>`irq_resolve_mapping()`

```c
struct irq_desc * irq_resolve_mapping(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Find a linux irq from a hw irq number.

**Parameters**

- `struct irq_domain *domain`: domain owning this hardware interrupt
- `irq_hw_number_t hwirq`: hardware irq number in that domain space

**Return**

Interrupt descriptor

#### <a id="c-irq_find_mapping"></a>`irq_find_mapping()`

```c
unsigned int irq_find_mapping(struct irq_domain *domain, irq_hw_number_t hwirq)
```

Find a linux irq from a hw irq number.

**Parameters**

- `struct irq_domain *domain`: domain owning this hardware interrupt
- `irq_hw_number_t hwirq`: hardware irq number in that domain space

**Return**

Linux irq number or 0 if not found

#### <a id="c-irq_domain_create_hierarchy"></a>`irq_domain_create_hierarchy()`

```c
struct irq_domain * irq_domain_create_hierarchy(struct irq_domain *parent, unsigned int flags, unsigned int size, struct fwnode_handle *fwnode, const struct irq_domain_ops *ops, void *host_data)
```

Add a irqdomain into the hierarchy

**Parameters**

- `struct irq_domain *parent`: Parent irq domain to associate with the new domain
- `unsigned int flags`: Irq domain flags associated to the domain
- `unsigned int size`: Size of the domain. See below
- `struct fwnode_handle *fwnode`: Optional fwnode of the interrupt controller
- `const struct irq_domain_ops *ops`: Pointer to the interrupt domain callbacks
- `void *host_data`: Controller private data pointer

**Description**

If **size** is 0 a tree domain is created, otherwise a linear domain.

If successful the parent is associated to the new domain and the
domain flags are set.

**Return**

A pointer to IRQ domain, or `NULL` on failure.

#### <a id="c-irq_domain_alloc_irqs"></a>`irq_domain_alloc_irqs()`

```c
int irq_domain_alloc_irqs(struct irq_domain *domain, unsigned int nr_irqs, int node, void *arg)
```

Allocate IRQs from domain

**Parameters**

- `struct irq_domain *domain`: domain to allocate from
- `unsigned int nr_irqs`: number of IRQs to allocate
- `int node`: NUMA node id for memory allocation
- `void *arg`: domain specific argument

**Description**

See [`__irq_domain_alloc_irqs()`](#c-__irq_domain_alloc_irqs)' documentation.



#### <a id="c-__irq_domain_alloc_fwnode"></a>`__irq_domain_alloc_fwnode()`

```c
struct fwnode_handle * __irq_domain_alloc_fwnode(unsigned int type, int id, const char *name, phys_addr_t *pa, struct fwnode_handle *parent)
```

Allocate a fwnode_handle suitable for identifying an irq domain

**Parameters**

- `unsigned int type`: Type of irqchip_fwnode. See linux/irqdomain.h
- `int id`: Optional user provided id if name != NULL
- `const char *name`: Optional user provided domain name
- `phys_addr_t *pa`: Optional user-provided physical address
- `struct fwnode_handle *parent`: Optional parent fwnode_handle

**Description**

Allocate a struct irqchip_fwid, and return a pointer to the embedded
fwnode_handle (or NULL on failure).

**Note**

The types IRQCHIP_FWNODE_NAMED and IRQCHIP_FWNODE_NAMED_ID are
solely to transport name information to irqdomain creation code. The
node is not stored. For other types the pointer is kept in the irq
domain struct.

#### <a id="c-irq_domain_free_fwnode"></a>`irq_domain_free_fwnode()`

```c
void irq_domain_free_fwnode(struct fwnode_handle *fwnode)
```

Free a non-OF-backed fwnode_handle

**Parameters**

- `struct fwnode_handle *fwnode`: fwnode_handle to free

**Description**

Free a fwnode_handle allocated with irq_domain_alloc_fwnode.

#### <a id="c-irq_domain_instantiate"></a>`irq_domain_instantiate()`

```c
struct irq_domain * irq_domain_instantiate(const struct irq_domain_info *info)
```

Instantiate a new irq domain data structure

**Parameters**

- `const struct irq_domain_info *info`: Domain information pointer pointing to the information for this domain

**Return**

A pointer to the instantiated irq domain or an ERR_PTR value.

#### <a id="c-irq_domain_remove"></a>`irq_domain_remove()`

```c
void irq_domain_remove(struct irq_domain *domain)
```

Remove an irq domain.

**Parameters**

- `struct irq_domain *domain`: domain to remove

**Description**

This routine is used to remove an irq domain. The caller must ensure
that all mappings within the domain have been disposed of prior to
use, depending on the revmap type.

#### <a id="c-irq_domain_create_simple"></a>`irq_domain_create_simple()`

```c
struct irq_domain * irq_domain_create_simple(struct fwnode_handle *fwnode, unsigned int size, unsigned int first_irq, const struct irq_domain_ops *ops, void *host_data)
```

Register an irq_domain and optionally map a range of irqs

**Parameters**

- `struct fwnode_handle *fwnode`: firmware node for the interrupt controller
- `unsigned int size`: total number of irqs in mapping
- `unsigned int first_irq`: first number of irq block assigned to the domain,
  pass zero to assign irqs on-the-fly. If first_irq is non-zero, then
  pre-map all of the irqs in the domain to virqs starting at first_irq.
- `const struct irq_domain_ops *ops`: domain callbacks
- `void *host_data`: Controller private data pointer

**Description**

Allocates an irq_domain, and optionally if first_irq is positive then also
allocate irq_descs and map all of the hwirqs to virqs starting at first_irq.

This is intended to implement the expected behaviour for most
interrupt controllers. If device tree is used, then first_irq will be 0 and
irqs get mapped dynamically on the fly. However, if the controller requires
static virq assignments (non-DT boot) then it will set that up correctly.

#### <a id="c-irq_find_matching_fwspec"></a>`irq_find_matching_fwspec()`

```c
struct irq_domain * irq_find_matching_fwspec(struct irq_fwspec *fwspec, enum irq_domain_bus_token bus_token)
```

Locates a domain for a given fwspec

**Parameters**

- `struct irq_fwspec *fwspec`: FW specifier for an interrupt
- `enum irq_domain_bus_token bus_token`: domain-specific data

#### <a id="c-irq_set_default_domain"></a>`irq_set_default_domain()`

```c
void irq_set_default_domain(struct irq_domain *domain)
```

Set a "default" irq domain

**Parameters**

- `struct irq_domain *domain`: default domain pointer

**Description**

For convenience, it's possible to set a "default" domain that will be used
whenever NULL is passed to [`irq_create_mapping()`](#c-irq_create_mapping). It makes life easier for
platforms that want to manipulate a few hard coded interrupt numbers that
aren't properly represented in the device-tree.

#### <a id="c-irq_get_default_domain"></a>`irq_get_default_domain()`

```c
struct irq_domain * irq_get_default_domain(void)
```

Retrieve the "default" irq domain

**Parameters**

- `void`: no arguments

**Return**

the default domain, if any.

**Description**

Modern code should never use this. This should only be used on
systems that cannot implement a firmware->fwnode mapping (which
both DT and ACPI provide).

#### <a id="c-irq_create_direct_mapping"></a>`irq_create_direct_mapping()`

```c
unsigned int irq_create_direct_mapping(struct irq_domain *domain)
```

Allocate an irq for direct mapping

**Parameters**

- `struct irq_domain *domain`: domain to allocate the irq for or NULL for default domain

**Description**

This routine is used for irq controllers which can choose the hardware
interrupt numbers they generate. In such a case it's simplest to use
the linux irq as the hardware interrupt number. It still uses the linear
or radix tree to store the mapping, but the irq controller can optimize
the revmap path by using the hwirq directly.

#### <a id="c-irq_create_mapping_affinity"></a>`irq_create_mapping_affinity()`

```c
unsigned int irq_create_mapping_affinity(struct irq_domain *domain, irq_hw_number_t hwirq, const struct irq_affinity_desc *affinity)
```

Map a hardware interrupt into linux irq space

**Parameters**

- `struct irq_domain *domain`: domain owning this hardware interrupt or NULL for default domain
- `irq_hw_number_t hwirq`: hardware irq number in that domain space
- `const struct irq_affinity_desc *affinity`: irq affinity

**Description**

Only one mapping per hardware interrupt is permitted. Returns a linux
irq number.
If the sense/trigger is to be specified, `set_irq_type()` should be called
on the number returned from that call.

#### <a id="c-irq_dispose_mapping"></a>`irq_dispose_mapping()`

```c
void irq_dispose_mapping(unsigned int virq)
```

Unmap an interrupt

**Parameters**

- `unsigned int virq`: linux irq number of the interrupt to unmap

#### <a id="c-__irq_resolve_mapping"></a>`__irq_resolve_mapping()`

```c
struct irq_desc * __irq_resolve_mapping(struct irq_domain *domain, irq_hw_number_t hwirq, unsigned int *irq)
```

Find a linux irq from a hw irq number.

**Parameters**

- `struct irq_domain *domain`: domain owning this hardware interrupt
- `irq_hw_number_t hwirq`: hardware irq number in that domain space
- `unsigned int *irq`: optional pointer to return the Linux irq if required

**Description**

Returns the interrupt descriptor.

#### <a id="c-irq_domain_xlate_onecell"></a>`irq_domain_xlate_onecell()`

```c
int irq_domain_xlate_onecell(struct irq_domain *d, struct device_node *ctrlr, const u32 *intspec, unsigned int intsize, unsigned long *out_hwirq, unsigned int *out_type)
```

Generic xlate for direct one cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct device_node *ctrlr`: The device tree node for the device whose interrupt is translated
- `const u32 *intspec`: The interrupt specifier data from the device tree
- `unsigned int intsize`: The number of entries in **intspec**
- `unsigned long *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Device Tree IRQ specifier translation function which works with one cell
bindings where the cell value maps directly to the hwirq number.

#### <a id="c-irq_domain_xlate_twocell"></a>`irq_domain_xlate_twocell()`

```c
int irq_domain_xlate_twocell(struct irq_domain *d, struct device_node *ctrlr, const u32 *intspec, unsigned int intsize, irq_hw_number_t *out_hwirq, unsigned int *out_type)
```

Generic xlate for direct two cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct device_node *ctrlr`: The device tree node for the device whose interrupt is translated
- `const u32 *intspec`: The interrupt specifier data from the device tree
- `unsigned int intsize`: The number of entries in **intspec**
- `irq_hw_number_t *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Device Tree IRQ specifier translation function which works with two cell
bindings where the cell values map directly to the hwirq number
and linux irq flags.

#### <a id="c-irq_domain_xlate_twothreecell"></a>`irq_domain_xlate_twothreecell()`

```c
int irq_domain_xlate_twothreecell(struct irq_domain *d, struct device_node *ctrlr, const u32 *intspec, unsigned int intsize, irq_hw_number_t *out_hwirq, unsigned int *out_type)
```

Generic xlate for direct two or three cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct device_node *ctrlr`: The device tree node for the device whose interrupt is translated
- `const u32 *intspec`: The interrupt specifier data from the device tree
- `unsigned int intsize`: The number of entries in **intspec**
- `irq_hw_number_t *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Device Tree interrupt specifier translation function for two or three
cell bindings, where the cell values map directly to the hardware
interrupt number and the type specifier.

#### <a id="c-irq_domain_xlate_onetwocell"></a>`irq_domain_xlate_onetwocell()`

```c
int irq_domain_xlate_onetwocell(struct irq_domain *d, struct device_node *ctrlr, const u32 *intspec, unsigned int intsize, unsigned long *out_hwirq, unsigned int *out_type)
```

Generic xlate for one or two cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct device_node *ctrlr`: The device tree node for the device whose interrupt is translated
- `const u32 *intspec`: The interrupt specifier data from the device tree
- `unsigned int intsize`: The number of entries in **intspec**
- `unsigned long *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Device Tree IRQ specifier translation function which works with either one
or two cell bindings where the cell values map directly to the hwirq number
and linux irq flags.

**Note**

don't use this function unless your interrupt controller explicitly
supports both one and two cell bindings.  For the majority of controllers
the `_onecell()` or `_twocell()` variants above should be used.

#### <a id="c-irq_domain_translate_onecell"></a>`irq_domain_translate_onecell()`

```c
int irq_domain_translate_onecell(struct irq_domain *d, struct irq_fwspec *fwspec, unsigned long *out_hwirq, unsigned int *out_type)
```

Generic translate for direct one cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct irq_fwspec *fwspec`: The firmware interrupt specifier to translate
- `unsigned long *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

#### <a id="c-irq_domain_translate_twocell"></a>`irq_domain_translate_twocell()`

```c
int irq_domain_translate_twocell(struct irq_domain *d, struct irq_fwspec *fwspec, unsigned long *out_hwirq, unsigned int *out_type)
```

Generic translate for direct two cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct irq_fwspec *fwspec`: The firmware interrupt specifier to translate
- `unsigned long *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Device Tree IRQ specifier translation function which works with two cell
bindings where the cell values map directly to the hwirq number
and linux irq flags.

#### <a id="c-irq_domain_translate_twothreecell"></a>`irq_domain_translate_twothreecell()`

```c
int irq_domain_translate_twothreecell(struct irq_domain *d, struct irq_fwspec *fwspec, unsigned long *out_hwirq, unsigned int *out_type)
```

Generic translate for direct two or three cell bindings

**Parameters**

- `struct irq_domain *d`: Interrupt domain involved in the translation
- `struct irq_fwspec *fwspec`: The firmware interrupt specifier to translate
- `unsigned long *out_hwirq`: Pointer to storage for the hardware interrupt number
- `unsigned int *out_type`: Pointer to storage for the interrupt type

**Description**

Firmware interrupt specifier translation function for two or three cell
specifications, where the parameter values map directly to the hardware
interrupt number and the type specifier.

#### <a id="c-irq_domain_reset_irq_data"></a>`irq_domain_reset_irq_data()`

```c
void irq_domain_reset_irq_data(struct irq_data *irq_data)
```

Clear hwirq, chip and chip_data in **irq_data**

**Parameters**

- `struct irq_data *irq_data`: The pointer to irq_data

#### <a id="c-irq_domain_disconnect_hierarchy"></a>`irq_domain_disconnect_hierarchy()`

```c
int irq_domain_disconnect_hierarchy(struct irq_domain *domain, unsigned int virq)
```

Mark the first unused level of a hierarchy

**Parameters**

- `struct irq_domain *domain`: IRQ domain from which the hierarchy is to be disconnected
- `unsigned int virq`: IRQ number where the hierarchy is to be trimmed

**Description**

Marks the **virq** level belonging to **domain** as disconnected.
Returns -EINVAL if **virq** doesn't have a valid irq_data pointing
to **domain**.

Its only use is to be able to trim levels of hierarchy that do not
have any real meaning for this interrupt, and that the driver marks
as such from its .`alloc()` callback.

#### <a id="c-irq_domain_get_irq_data"></a>`irq_domain_get_irq_data()`

```c
struct irq_data * irq_domain_get_irq_data(struct irq_domain *domain, unsigned int virq)
```

Get irq_data associated with **virq** and **domain**

**Parameters**

- `struct irq_domain *domain`: domain to match
- `unsigned int virq`: IRQ number to get irq_data

#### <a id="c-irq_domain_set_hwirq_and_chip"></a>`irq_domain_set_hwirq_and_chip()`

```c
int irq_domain_set_hwirq_and_chip(struct irq_domain *domain, unsigned int virq, irq_hw_number_t hwirq, const struct irq_chip *chip, void *chip_data)
```

Set hwirq and irqchip of **virq** at **domain**

**Parameters**

- `struct irq_domain *domain`: Interrupt domain to match
- `unsigned int virq`: IRQ number
- `irq_hw_number_t hwirq`: The hwirq number
- `const struct irq_chip *chip`: The associated interrupt chip
- `void *chip_data`: The associated chip data

#### <a id="c-irq_domain_set_info"></a>`irq_domain_set_info()`

```c
void irq_domain_set_info(struct irq_domain *domain, unsigned int virq, irq_hw_number_t hwirq, const struct irq_chip *chip, void *chip_data, irq_flow_handler_t handler, void *handler_data, const char *handler_name)
```

Set the complete data for a **virq** in **domain**

**Parameters**

- `struct irq_domain *domain`: Interrupt domain to match
- `unsigned int virq`: IRQ number
- `irq_hw_number_t hwirq`: The hardware interrupt number
- `const struct irq_chip *chip`: The associated interrupt chip
- `void *chip_data`: The associated interrupt chip data
- `irq_flow_handler_t handler`: The interrupt flow handler
- `void *handler_data`: The interrupt flow handler data
- `const char *handler_name`: The interrupt handler name

#### <a id="c-irq_domain_free_irqs_common"></a>`irq_domain_free_irqs_common()`

```c
void irq_domain_free_irqs_common(struct irq_domain *domain, unsigned int virq, unsigned int nr_irqs)
```

Clear irq_data and free the parent

**Parameters**

- `struct irq_domain *domain`: Interrupt domain to match
- `unsigned int virq`: IRQ number to start with
- `unsigned int nr_irqs`: The number of irqs to free

#### <a id="c-irq_domain_free_irqs_top"></a>`irq_domain_free_irqs_top()`

```c
void irq_domain_free_irqs_top(struct irq_domain *domain, unsigned int virq, unsigned int nr_irqs)
```

Clear handler and handler data, clear irqdata and free parent

**Parameters**

- `struct irq_domain *domain`: Interrupt domain to match
- `unsigned int virq`: IRQ number to start with
- `unsigned int nr_irqs`: The number of irqs to free

#### <a id="c-__irq_domain_alloc_irqs"></a>`__irq_domain_alloc_irqs()`

```c
int __irq_domain_alloc_irqs(struct irq_domain *domain, int irq_base, unsigned int nr_irqs, int node, void *arg, bool realloc, const struct irq_affinity_desc *affinity)
```

Allocate IRQs from domain

**Parameters**

- `struct irq_domain *domain`: domain to allocate from
- `int irq_base`: allocate specified IRQ number if irq_base >= 0
- `unsigned int nr_irqs`: number of IRQs to allocate
- `int node`: NUMA node id for memory allocation
- `void *arg`: domain specific argument
- `bool realloc`: IRQ descriptors have already been allocated if true
- `const struct irq_affinity_desc *affinity`: Optional irq affinity mask for multiqueue devices

**Description**

Allocate IRQ numbers and initialized all data structures to support
hierarchy IRQ domains.
Parameter **realloc** is mainly to support legacy IRQs.
Returns error code or allocated IRQ number

The whole process to setup an IRQ has been split into two steps.
The first step, [`__irq_domain_alloc_irqs()`](#c-__irq_domain_alloc_irqs), is to allocate IRQ
descriptor and required hardware resources. The second step,
[`irq_domain_activate_irq()`](#c-irq_domain_activate_irq), is to program the hardware with preallocated
resources. In this way, it's easier to rollback when failing to
allocate resources.

#### <a id="c-irq_domain_push_irq"></a>`irq_domain_push_irq()`

```c
int irq_domain_push_irq(struct irq_domain *domain, int virq, void *arg)
```

Push a domain in to the top of a hierarchy.

**Parameters**

- `struct irq_domain *domain`: Domain to push.
- `int virq`: Irq to push the domain in to.
- `void *arg`: Passed to the irq_domain_ops `alloc()` function.

**Description**

For an already existing irqdomain hierarchy, as might be obtained
via a call to `pci_enable_msix()`, add an additional domain to the
head of the processing chain.  Must be called before [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq)
has been called.

#### <a id="c-irq_domain_pop_irq"></a>`irq_domain_pop_irq()`

```c
int irq_domain_pop_irq(struct irq_domain *domain, int virq)
```

Remove a domain from the top of a hierarchy.

**Parameters**

- `struct irq_domain *domain`: Domain to remove.
- `int virq`: Irq to remove the domain from.

**Description**

Undo the effects of a call to [`irq_domain_push_irq()`](#c-irq_domain_push_irq).  Must be
called either before [`request_irq()`](/kernel/internals/core-api/genericirq.md#c-request_irq) or after [`free_irq()`](/kernel/internals/core-api/genericirq.md#c-free_irq).

#### <a id="c-irq_domain_free_irqs"></a>`irq_domain_free_irqs()`

```c
void irq_domain_free_irqs(unsigned int virq, unsigned int nr_irqs)
```

Free IRQ number and associated data structures

**Parameters**

- `unsigned int virq`: base IRQ number
- `unsigned int nr_irqs`: number of IRQs to free

#### <a id="c-irq_domain_alloc_irqs_parent"></a>`irq_domain_alloc_irqs_parent()`

```c
int irq_domain_alloc_irqs_parent(struct irq_domain *domain, unsigned int irq_base, unsigned int nr_irqs, void *arg)
```

Allocate interrupts from parent domain

**Parameters**

- `struct irq_domain *domain`: Domain below which interrupts must be allocated
- `unsigned int irq_base`: Base IRQ number
- `unsigned int nr_irqs`: Number of IRQs to allocate
- `void *arg`: Allocation data (arch/domain specific)

#### <a id="c-irq_domain_free_irqs_parent"></a>`irq_domain_free_irqs_parent()`

```c
void irq_domain_free_irqs_parent(struct irq_domain *domain, unsigned int irq_base, unsigned int nr_irqs)
```

Free interrupts from parent domain

**Parameters**

- `struct irq_domain *domain`: Domain below which interrupts must be freed
- `unsigned int irq_base`: Base IRQ number
- `unsigned int nr_irqs`: Number of IRQs to free


<a id="rst-internal-functions-provided"></a>

## Internal Functions Provided

This chapter contains the autogenerated documentation of the internal functions.


#### <a id="c-irq_domain_activate_irq"></a>`irq_domain_activate_irq()`

```c
int irq_domain_activate_irq(struct irq_data *irq_data, bool reserve)
```

Call domain_ops->activate recursively to activate interrupt

**Parameters**

- `struct irq_data *irq_data`: Outermost irq_data associated with interrupt
- `bool reserve`: If set only reserve an interrupt vector instead of assigning one

**Description**

This is the second step to call domain_ops->activate to program interrupt
controllers, so the interrupt could actually get delivered.

#### <a id="c-irq_domain_deactivate_irq"></a>`irq_domain_deactivate_irq()`

```c
void irq_domain_deactivate_irq(struct irq_data *irq_data)
```

Call domain_ops->deactivate recursively to deactivate interrupt

**Parameters**

- `struct irq_data *irq_data`: outermost irq_data associated with interrupt

**Description**

It calls domain_ops->deactivate to program interrupt controllers to disable
interrupt delivery.

---

# IRQ-flags state tracing

_Peios Kernel / Internals / Core APIs / irq_

> The "irq-flags tracing" feature "traces" hardirq and softirq state, in that it gives interested subsystems an opportunity to be notified of every hardirqs-off/hardirqs-on, softirqs-off/softirqs-on event that happens in the kernel.

<a id="rst-irq-flags-state-tracing"></a>

**Author:** started by Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;

The "irq-flags tracing" feature "traces" hardirq and softirq state, in that it gives interested subsystems an opportunity to be notified of every hardirqs-off/hardirqs-on, softirqs-off/softirqs-on event that happens in the kernel.

CONFIG_TRACE_IRQFLAGS_SUPPORT is needed for CONFIG_PROVE_SPIN_LOCKING and CONFIG_PROVE_RW_LOCKING to be offered by the generic lock debugging code. Otherwise only CONFIG_PROVE_MUTEX_LOCKING and CONFIG_PROVE_RWSEM_LOCKING will be offered on an architecture - these are locking APIs that are not used in IRQ context. (the one exception for rwsems is worked around)

Architecture support for this is certainly not in the "trivial" category, because lots of lowlevel assembly code deal with irq-flags state changes. But an architecture can be irq-flags-tracing enabled in a rather straightforward and risk-free manner.

Architectures that want to support this need to do a couple of code-organizational changes first:

- add and enable TRACE_IRQFLAGS_SUPPORT in their arch level Kconfig file

and then a couple of functional changes are needed as well to implement irq-flags-tracing support:

- in lowlevel entry code add (build-conditional) calls to the trace_hardirqs_off()/trace_hardirqs_on() functions. The lock validator closely guards whether the 'real' irq-flags matches the 'virtual' irq-flags state, and complains loudly (and turns itself off) if the two do not match. Usually most of the time for arch support for irq-flags-tracing is spent in this state: look at the lockdep complaint, try to figure out the assembly code we did not cover yet, fix and repeat. Once the system has booted up and works without a lockdep complaint in the irq-flags-tracing functions arch support is complete.

- if the architecture has non-maskable interrupts then those need to be excluded from the irq-tracing \[and lock validation\] mechanism via lockdep_off()/lockdep_on().

In general there is no risk from having an incomplete irq-flags-tracing implementation in an architecture: lockdep will detect that and will turn itself off. I.e. the lock validator will still be reliable. There should be no crashes due to irq-tracing bugs. (except if the assembly changes break other code by modifying conditions or registers that shouldn't be)

---

# Kexec Handover Subsystem

_Peios Kernel / Internals / Core APIs / kho_

> Kexec HandOver (KHO) is a mechanism that allows Linux to preserve memory regions, which could contain serialized system states, across kexec.

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-kexec-handover-subsystem"></a>
<a id="rst-kho-concepts"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

<a id="rst-overview"></a>

## Overview

Kexec HandOver (KHO) is a mechanism that allows Linux to preserve memory regions, which could contain serialized system states, across kexec.

KHO uses [flattened device tree (FDT)](<#rst-kho-fdt>) to pass information about the preserved state from pre-exec kernel to post-kexec kernel and [scratch memory regions](<#rst-kho-scratch>) to ensure integrity of the preserved memory.

<a id="rst-kho-fdt-1"></a>
<a id="rst-kho-fdt"></a>

## KHO FDT

Every KHO kexec carries a KHO specific flattened device tree (FDT) blob that describes the preserved state. The FDT includes properties describing preserved memory regions and nodes that hold subsystem specific state.

The preserved memory regions contain either serialized subsystem states, or in-memory data that shall not be touched across kexec. After KHO, subsystems can retrieve and restore the preserved state from KHO FDT.

Subsystems participating in KHO can define their own format for state serialization and preservation.

KHO FDT and structures defined by the subsystems form an ABI between pre-kexec and post-kexec kernels. This ABI is defined by header files in `include/linux/kho/abi` directory.

- [Kexec Handover ABI](</kernel/internals/core-api/kho/abi.md>)

<a id="rst-scratch-regions"></a>
<a id="rst-kho-scratch"></a>

## Scratch Regions

To boot into kexec, we need to have a physically contiguous memory range that contains no handed over memory. Kexec then places the target kernel and initrd into that region. The new kernel exclusively uses this region for memory allocations before during boot up to the initialization of the page allocator.

We guarantee that we always have such regions through the scratch regions: On first boot KHO allocates several physically contiguous memory regions. Since after kexec these regions will be used by early memory allocations, there is a scratch region per NUMA node plus a scratch region to satisfy allocations requests that do not require particular NUMA node assignment. By default, size of the scratch region is calculated based on amount of memory allocated during boot. The `kho_scratch` kernel command line option may be used to explicitly define size of the scratch regions. The scratch regions are declared as CMA when page allocator is initialized so that their memory can be used during system lifetime. CMA gives us the guarantee that no handover pages land in that region, because handover pages must be at a static physical memory location and CMA enforces that only movable pages can be located inside.

After KHO kexec, we ignore the `kho_scratch` kernel command line option and instead reuse the exact same region that was originally allocated. This allows us to recursively execute any amount of KHO kexecs. Because we used this region for boot memory allocations and as target memory for kexec blobs, some parts of that memory region may be reserved. These reservations are irrelevant for the next KHO, because kexec can overwrite even the original kernel.

<a id="rst-kho-finalization-phase-1"></a>
<a id="rst-kho-finalization-phase"></a>

## KHO finalization phase

To enable user space based kexec file loader, the kernel needs to be able to provide the FDT that describes the current kernel's state before performing the actual kexec. The process of generating that FDT is called serialization. When the FDT is generated, some properties of the system may become immutable because they are already written down in the FDT. That state is called the KHO finalization phase.

<a id="rst-see-also"></a>

## See Also

- [Kexec Handover Usage](</kernel/administration/admin-guide/mm/kho.md>)

---

# Kexec Handover ABI

_Peios Kernel / Internals / Core APIs / kho_

> /admin-guide/mm/kho

<a id="rst-kexec-handover-abi"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

<a id="rst-core-kexec-handover-abi"></a>

## Core Kexec Handover ABI


Kexec Handover uses the ABI defined below for passing preserved data from
one kernel to the next.
The ABI uses Flattened Device Tree (FDT) format. The first kernel creates an
FDT which is then passed to the next kernel during a kexec handover.

This interface is a contract. Any modification to the FDT structure, node
properties, compatible string, or the layout of the data structures
referenced here constitutes a breaking change. Such changes require
incrementing the version number in KHO_FDT_COMPATIBLE to prevent a new kernel
from misinterpreting data from an older kernel. Changes are allowed provided
the compatibility version is incremented. However, backward/forward
compatibility is only guaranteed for kernels supporting the same ABI version.

- FDT Structure Overview:
  The FDT serves as a central registry for physical
  addresses of preserved data structures and sub-FDTs. The first kernel
  populates this FDT with references to memory regions and other FDTs that
  need to persist across the kexec transition. The subsequent kernel then
  parses this FDT to locate and restore the preserved data.:

```text
/ {
    compatible = "kho-v1";

    preserved-memory-map = <0x...>;

    <subnode-name-1> {
        fdt = <0x...>;
    };

    <subnode-name-2> {
        fdt = <0x...>;
    };
          ... ...
    <subnode-name-N> {
        fdt = <0x...>;
    };
};
```

- Root KHO Node (/):
  - compatible: "kho-v1"

    Indentifies the overall KHO ABI version.

  - preserved-memory-map: u64

    Physical memory address pointing to the root of the
    preserved memory map data structure.

  - Subnodes (\<subnode-name-N>):
    Subnodes can also be added to the root node to
    describe other preserved data blobs. The \<subnode-name-N>
    is provided by the subsystem that uses KHO for preserving its
    data.

    - fdt: u64

      Physical address pointing to a subnode FDT blob that is also
      being preserved.


<a id="rst-vmalloc-preservation-abi"></a>

## vmalloc preservation ABI


The Kexec Handover ABI for preserving vmalloc'ed memory is defined by
a set of structures and helper macros. The layout of these structures is a
stable contract between kernels and is versioned by the KHO_FDT_COMPATIBLE
string.

The preservation is managed through a main descriptor `struct kho_vmalloc`,
which points to a linked list of `struct kho_vmalloc_chunk` structures. These
chunks contain the physical addresses of the preserved pages, allowing the
next kernel to reconstruct the vmalloc area with the same content and layout.
Helper macros are also defined for storing and loading pointers within
these structures.


<a id="rst-memblock-preservation-abi"></a>

## memblock preservation ABI


Memblock can serialize its current memory reservations created with
reserve_mem command line option across kexec through KHO.
The post-KHO kernel can then consume these reservations and they are
guaranteed to have the same physical address.

The state is serialized using Flattened Device Tree (FDT) format. Any
modification to the FDT structure, node properties, or the compatible
strings constitutes a breaking change. Such changes require incrementing the
version number in the relevant `_COMPATIBLE` string to prevent a new kernel
from misinterpreting data from an old kernel.

Changes are allowed provided the compatibility version is incremented.
However, backward/forward compatibility is only guaranteed for kernels
supporting the same ABI version.

- FDT Structure Overview:
  The entire memblock state is encapsulated within a single KHO entry named
  "memblock".
  This entry contains an FDT with the following layout:

```none
/ {
        compatible = "memblock-v1";

        n1 {
                compatible = "reserve-mem-v1";
                start = <0xc06b 0x4000000>;
                size = <0x04 0x00>;
        };
};
```

Main memblock node (/):

- compatible: "memblock-v1"
  Identifies the overall memblock ABI version.

reserved_mem node:
These nodes describe all reserve_mem regions. The node name is the name
defined by the user for a reserve_mem region.

- compatible: "reserve-mem-v1"

  Identifies the ABI version of reserve_mem descriptions

- start: u64

  Physical address of the reserved memory region.

- size: u64

  size in bytes of the reserved memory region.


<a id="rst-see-also"></a>

## See Also

- [Kexec Handover Usage](</kernel/administration/admin-guide/mm/kho.md>)

---

# Real-time preemption

_Peios Kernel / Internals / Core APIs / real-time_

> This documentation is intended for Linux kernel developers and contributors interested in the inner workings of PREEMPT_RT. It explains key concepts and the required changes compared to a non-PREEMPT_RT configuration.

<a id="rst-real-time-preemption"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This documentation is intended for Linux kernel developers and contributors interested in the inner workings of PREEMPT_RT. It explains key concepts and the required changes compared to a non-PREEMPT_RT configuration.

- [Theory of operation](</kernel/internals/core-api/real-time/theory.md>)
- [How realtime kernels differ](</kernel/internals/core-api/real-time/differences.md>)
- [Considering hardware](</kernel/internals/core-api/real-time/hardware.md>)
- [Porting an architecture to support PREEMPT_RT](</kernel/internals/core-api/real-time/architecture-porting.md>)

---

# Porting an architecture to support PREEMPT_RT

_Peios Kernel / Internals / Core APIs / real-time_

> This list outlines the architecture specific requirements that must be implemented in order to enable PREEMPT_RT. Once all required features are implemented, ARCH_SUPPORTS_RT can be selected in architecture’s Kconfig to make PREEMPT_RT…

<a id="rst-porting-an-architecture-to-support-preempt-rt"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Sebastian Andrzej Siewior &lt;[bigeasy@linutronix.de](<mailto:bigeasy@linutronix.de>)&gt;

This list outlines the architecture specific requirements that must be implemented in order to enable PREEMPT_RT. Once all required features are implemented, ARCH_SUPPORTS_RT can be selected in architecture’s Kconfig to make PREEMPT_RT selectable. Many prerequisites (genirq support for example) are enforced by the common code and are omitted here.

The optional features are not strictly required but it is worth to consider them.

<a id="rst-requirements"></a>

## Requirements

- **Forced threaded interrupts**

  CONFIG_IRQ_FORCED_THREADING must be selected. Any interrupts that must remain in hard-IRQ context must be marked with IRQF_NO_THREAD. This requirement applies for instance to clocksource event interrupts, perf interrupts and cascading interrupt-controller handlers.

- **PREEMPTION support**

  Kernel preemption must be supported and requires that CONFIG_ARCH_NO_PREEMPT remain unselected. Scheduling requests, such as those issued from an interrupt or other exception handler, must be processed immediately.

- **POSIX CPU timers and KVM**

  POSIX CPU timers must expire from thread context rather than directly within the timer interrupt. This behavior is enabled by setting the configuration option CONFIG_HAVE_POSIX_CPU_TIMERS_TASK_WORK. When virtualization support, such as KVM, is enabled, CONFIG_VIRT_XFER_TO_GUEST_WORK must also be set to ensure that any pending work, such as POSIX timer expiration, is handled before transitioning into guest mode.

- **Hard-IRQ and Soft-IRQ stacks**

  Soft interrupts are handled in the thread context in which they are raised. If a soft interrupt is triggered from hard-IRQ context, its execution is deferred to the ksoftirqd thread. Preemption is never disabled during soft interrupt handling, which makes soft interrupts preemptible. If an architecture provides a custom \__do_softirq() implementation that uses a separate stack, it must select CONFIG_HAVE_SOFTIRQ_ON_OWN_STACK. The functionality should only be enabled when CONFIG_SOFTIRQ_ON_OWN_STACK is set.

- **FPU and SIMD access in kernel mode**

  FPU and SIMD registers are typically not used in kernel mode and are therefore not saved during kernel preemption. As a result, any kernel code that uses these registers must be enclosed within a kernel_fpu_begin() and kernel_fpu_end() section. The kernel_fpu_begin() function usually invokes local_bh_disable() to prevent interruptions from softirqs and to disable regular preemption. This allows the protected code to run safely in both thread and softirq contexts. On PREEMPT_RT kernels, however, kernel_fpu_begin() must not call local_bh_disable(). Instead, it should use preempt_disable(), since softirqs are always handled in thread context under PREEMPT_RT. In this case, disabling preemption alone is sufficient. The crypto subsystem operates on memory pages and requires users to "walk and map" these pages while processing a request. This operation must occur outside the kernel_fpu_begin()/ kernel_fpu_end() section because it requires preemption to be enabled. These preemption points are generally sufficient to avoid excessive scheduling latency.

- **Exception handlers**

  Exception handlers, such as the page fault handler, typically enable interrupts early, before invoking any generic code to process the exception. This is necessary because handling a page fault may involve operations that can sleep. Enabling interrupts is especially important on PREEMPT_RT, where certain locks, such as spinlock_t, become sleepable. For example, handling an invalid opcode may result in sending a SIGILL signal to the user task. A debug excpetion will send a SIGTRAP signal. In both cases, if the exception occurred in user space, it is safe to enable interrupts early. Sending a signal requires both interrupts and kernel preemption to be enabled.

<a id="rst-optional-features"></a>

## Optional features

- **Timer and clocksource**

  A high-resolution clocksource and clockevents device are recommended. The clockevents device should support the CLOCK_EVT_FEAT_ONESHOT feature for optimal timer behavior. In most cases, microsecond-level accuracy is sufficient

- **Lazy preemption**

  This mechanism allows an in-kernel scheduling request for non-real-time tasks to be delayed until the task is about to return to user space. It helps avoid preempting a task that holds a sleeping lock at the time of the scheduling request. With CONFIG_GENERIC_IRQ_ENTRY enabled, supporting this feature requires defining a bit for TIF_NEED_RESCHED_LAZY, preferably near TIF_NEED_RESCHED.

- **Serial console with NBCON**

  With PREEMPT_RT enabled, all console output is handled by a dedicated thread rather than directly from the context in which printk() is invoked. This design allows printk() to be safely used in atomic contexts. However, this also means that if the kernel crashes and cannot switch to the printing thread, no output will be visible preventing the system from printing its final messages. There are exceptions for immediate output, such as during panic() handling. To support this, the console driver must implement new-style lock handling. This involves setting the CON_NBCON flag in console::flags and providing implementations for the write_atomic, write_thread, device_lock, and device_unlock callbacks.

---

# How realtime kernels differ

_Peios Kernel / Internals / Core APIs / real-time_

> With forced-threaded interrupts and sleeping spin locks, code paths that previously caused long scheduling latencies have been made preemptible and moved into process context. This allows the scheduler to manage them more effectively and…

<a id="rst-how-realtime-kernels-differ"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Sebastian Andrzej Siewior &lt;[bigeasy@linutronix.de](<mailto:bigeasy@linutronix.de>)&gt;

<a id="rst-preface"></a>

## Preface

With forced-threaded interrupts and sleeping spin locks, code paths that previously caused long scheduling latencies have been made preemptible and moved into process context. This allows the scheduler to manage them more effectively and respond to higher-priority tasks with reduced latency.

The following chapters provide an overview of key differences between a PREEMPT_RT kernel and a standard, non-PREEMPT_RT kernel.

<a id="rst-locking"></a>

## Locking

Spinning locks such as spinlock_t are used to provide synchronization for data structures accessed from both interrupt context and process context. For this reason, locking functions are also available with the \_irq() or \_irqsave() suffixes, which disable interrupts before acquiring the lock. This ensures that the lock can be safely acquired in process context when interrupts are enabled.

However, on a PREEMPT_RT system, interrupts are forced-threaded and no longer run in hard IRQ context. As a result, there is no need to disable interrupts as part of the locking procedure when using spinlock_t.

For low-level core components such as interrupt handling, the scheduler, or the timer subsystem the kernel uses raw_spinlock_t. This lock type preserves traditional semantics: it disables preemption and, when used with \_irq() or \_irqsave(), also disables interrupts. This ensures proper synchronization in critical sections that must remain non-preemptible or with interrupts disabled.

<a id="rst-execution-context"></a>

## Execution context

Interrupt handling in a PREEMPT_RT system is invoked in process context through the use of threaded interrupts. Other parts of the kernel also shift their execution into threaded context by different mechanisms. The goal is to keep execution paths preemptible, allowing the scheduler to interrupt them when a higher-priority task needs to run.

Below is an overview of the kernel subsystems involved in this transition to threaded, preemptible execution.

<a id="rst-interrupt-handling"></a>

### Interrupt handling

All interrupts are forced-threaded in a PREEMPT_RT system. The exceptions are interrupts that are requested with the IRQF_NO_THREAD, IRQF_PERCPU, or IRQF_ONESHOT flags.

The IRQF_ONESHOT flag is used together with threaded interrupts, meaning those registered using request_threaded_irq() and providing only a threaded handler. Its purpose is to keep the interrupt line masked until the threaded handler has completed.

If a primary handler is also provided in this case, it is essential that the handler does not acquire any sleeping locks, as it will not be threaded. The handler should be minimal and must avoid introducing delays, such as busy-waiting on hardware registers.

<a id="rst-soft-interrupts-bottom-half-handling"></a>

### Soft interrupts, bottom half handling

Soft interrupts are raised by the interrupt handler and are executed after the handler returns. Since they run in thread context, they can be preempted by other threads. Do not assume that softirq context runs with preemption disabled. This means you must not rely on mechanisms like local_bh_disable() in process context to protect per-CPU variables. Because softirq handlers are preemptible under PREEMPT_RT, this approach does not provide reliable synchronization.

If this kind of protection is required for performance reasons, consider using local_lock_nested_bh(). On non-PREEMPT_RT kernels, this allows lockdep to verify that bottom halves are disabled. On PREEMPT_RT systems, it adds the necessary locking to ensure proper protection.

Using local_lock_nested_bh() also makes the locking scope explicit and easier for readers and maintainers to understand.

<a id="rst-per-cpu-variables"></a>

### per-CPU variables

Protecting access to per-CPU variables solely by using preempt_disable() should be avoided, especially if the critical section has unbounded runtime or may call APIs that can sleep.

If using a spinlock_t is considered too costly for performance reasons, consider using local_lock_t. On non-PREEMPT_RT configurations, this introduces no runtime overhead when lockdep is disabled. With lockdep enabled, it verifies that the lock is only acquired in process context and never from softirq or hard IRQ context.

On a PREEMPT_RT kernel, local_lock_t is implemented using a per-CPU spinlock_t, which provides safe local protection for per-CPU data while keeping the system preemptible.

Because spinlock_t on PREEMPT_RT does not disable preemption, it cannot be used to protect per-CPU data by relying on implicit preemption disabling. If this inherited preemption disabling is essential and if local_lock_t cannot be used due to performance constraints, brevity of the code, or abstraction boundaries within an API then preempt_disable_nested() may be a suitable alternative. On non-PREEMPT_RT kernels, it verifies with lockdep that preemption is already disabled. On PREEMPT_RT, it explicitly disables preemption.

<a id="rst-timers"></a>

### Timers

By default, an hrtimer is executed in hard interrupt context. The exception is timers initialized with the HRTIMER_MODE_SOFT flag, which are executed in softirq context.

On a PREEMPT_RT kernel, this behavior is reversed: hrtimers are executed in softirq context by default, typically within the ktimersd thread. This thread runs at the lowest real-time priority, ensuring it executes before any SCHED_OTHER tasks but does not interfere with higher-priority real-time threads. To explicitly request execution in hard interrupt context on PREEMPT_RT, the timer must be marked with the HRTIMER_MODE_HARD flag.

<a id="rst-memory-allocation"></a>

### Memory allocation

The memory allocation APIs, such as kmalloc() and alloc_pages(), require a gfp_t flag to indicate the allocation context. On non-PREEMPT_RT kernels, it is necessary to use GFP_ATOMIC when allocating memory from interrupt context or from sections where preemption is disabled. This is because the allocator must not sleep in these contexts waiting for memory to become available.

However, this approach does not work on PREEMPT_RT kernels. The memory allocator in PREEMPT_RT uses sleeping locks internally, which cannot be acquired when preemption is disabled. Fortunately, this is generally not a problem, because PREEMPT_RT moves most contexts that would traditionally run with preemption or interrupts disabled into threaded context, where sleeping is allowed.

What remains problematic is code that explicitly disables preemption or interrupts. In such cases, memory allocation must be performed outside the critical section.

This restriction also applies to memory deallocation routines such as kfree() and free_pages(), which may also involve internal locking and must not be called from non-preemptible contexts.

<a id="rst-irq-work"></a>

### IRQ work

The irq_work API provides a mechanism to schedule a callback in interrupt context. It is designed for use in contexts where traditional scheduling is not possible, such as from within NMI handlers or from inside the scheduler, where using a workqueue would be unsafe.

On non-PREEMPT_RT systems, all irq_work items are executed immediately in interrupt context. Items marked with IRQ_WORK_LAZY are deferred until the next timer tick but are still executed in interrupt context.

On PREEMPT_RT systems, the execution model changes. Because irq_work callbacks may acquire sleeping locks or have unbounded execution time, they are handled in thread context by a per-CPU irq_work kernel thread. This thread runs at the lowest real-time priority, ensuring it executes before any SCHED_OTHER tasks but does not interfere with higher-priority real-time threads.

The exception are work items marked with IRQ_WORK_HARD_IRQ, which are still executed in hard interrupt context. Lazy items (IRQ_WORK_LAZY) continue to be deferred until the next timer tick and are also executed by the irq_work/ thread.

<a id="rst-rcu-callbacks"></a>

### RCU callbacks

RCU callbacks are invoked by default in softirq context. Their execution is important because, depending on the use case, they either free memory or ensure progress in state transitions. Running these callbacks as part of the softirq chain can lead to undesired situations, such as contention for CPU resources with other SCHED_OTHER tasks when executed within ksoftirqd.

To avoid running callbacks in softirq context, the RCU subsystem provides a mechanism to execute them in process context instead. This behavior can be enabled by setting the boot command-line parameter rcutree.use_softirq=0. This setting is enforced in kernels configured with PREEMPT_RT.

<a id="rst-spin-until-ready"></a>

## Spin until ready

The "spin until ready" pattern involves repeatedly checking (spinning on) the state of a data structure until it becomes available. This pattern assumes that preemption, soft interrupts, or interrupts are disabled. If the data structure is marked busy, it is presumed to be in use by another CPU, and spinning should eventually succeed as that CPU makes progress.

Some examples are hrtimer_cancel() or timer_delete_sync(). These functions cancel timers that execute with interrupts or soft interrupts disabled. If a thread attempts to cancel a timer and finds it active, spinning until the callback completes is safe because the callback can only run on another CPU and will eventually finish.

On PREEMPT_RT kernels, however, timer callbacks run in thread context. This introduces a challenge: a higher-priority thread attempting to cancel the timer may preempt the timer callback thread. Since the scheduler cannot migrate the callback thread to another CPU due to affinity constraints, spinning can result in livelock even on multiprocessor systems.

To avoid this, both the canceling and callback sides must use a handshake mechanism that supports priority inheritance. This allows the canceling thread to suspend until the callback completes, ensuring forward progress without risking livelock.

In order to solve the problem at the API level, the sequence locks were extended to allow a proper handover between the the spinning reader and the maybe blocked writer.

<a id="rst-sequence-locks"></a>

### Sequence locks

Sequence counters and sequential locks are documented in [Documentation/locking/seqlock.rst](/kernel/internals/locking/seqlock.md).

The interface has been extended to ensure proper preemption states for the writer and spinning reader contexts. This is achieved by embedding the writer serialization lock directly into the sequence counter type, resulting in composite types such as seqcount_spinlock_t or seqcount_mutex_t.

These composite types allow readers to detect an ongoing write and actively boost the writer’s priority to help it complete its update instead of spinning and waiting for its completion.

If the plain seqcount_t is used, extra care must be taken to synchronize the reader with the writer during updates. The writer must ensure its update is serialized and non-preemptible relative to the reader. This cannot be achieved using a regular spinlock_t because spinlock_t on PREEMPT_RT does not disable preemption. In such cases, using seqcount_spinlock_t is the preferred solution.

However, if there is no spinning involved i.e., if the reader only needs to detect whether a write has started and not serialize against it then using seqcount_t is reasonable.

---

# Considering hardware

_Peios Kernel / Internals / Core APIs / real-time_

> The way a workload is handled can be influenced by the hardware it runs on. Key components include the CPU, memory, and the buses that connect them. These resources are shared among all applications on the system. As a result, heavy…

<a id="rst-considering-hardware"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Sebastian Andrzej Siewior &lt;[bigeasy@linutronix.de](<mailto:bigeasy@linutronix.de>)&gt;

The way a workload is handled can be influenced by the hardware it runs on. Key components include the CPU, memory, and the buses that connect them. These resources are shared among all applications on the system. As a result, heavy utilization of one resource by a single application can affect the deterministic handling of workloads in other applications.

Below is a brief overview.

<a id="rst-system-memory-and-cache"></a>

## System memory and cache

Main memory and the associated caches are the most common shared resources among tasks in a system. One task can dominate the available caches, forcing another task to wait until a cache line is written back to main memory before it can proceed. The impact of this contention varies based on write patterns and the size of the caches available. Larger caches may reduce stalls because more lines can be buffered before being written back. Conversely, certain write patterns may trigger the cache controller to flush many lines at once, causing applications to stall until the operation completes.

This issue can be partly mitigated if applications do not share the same CPU cache. The kernel is aware of the cache topology and exports this information to user space. Tools such as **lstopo** from the Portable Hardware Locality (hwloc) project ([https://www.open-mpi.org/projects/hwloc/](<https://www.open-mpi.org/projects/hwloc/>)) can visualize the hierarchy.

Avoiding shared L2 or L3 caches is not always possible. Even when cache sharing is minimized, bottlenecks can still occur when accessing system memory. Memory is used not only by the CPU but also by peripheral devices via DMA, such as graphics cards or network adapters.

In some cases, cache and memory bottlenecks can be controlled if the hardware provides the necessary support. On x86 systems, Intel offers Cache Allocation Technology (CAT), which enables cache partitioning among applications and provides control over the interconnect. AMD provides similar functionality under Platform Quality of Service (PQoS). On Arm64, the equivalent is Memory System Resource Partitioning and Monitoring (MPAM).

These features can be configured through the Linux Resource Control interface. For details, see [Documentation/filesystems/resctrl.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/resctrl.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92).

The perf tool can be used to monitor cache behavior. It can analyze cache misses of an application and compare how they change under different workloads on a neighboring CPU. Even more powerful, the perf c2c tool can help identify cache-to-cache issues, where multiple CPU cores repeatedly access and modify data on the same cache line.

<a id="rst-hardware-buses"></a>

## Hardware buses

Real-time systems often need to access hardware directly to perform their work. Any latency in this process is undesirable, as it can affect the outcome of the task. For example, on an I/O bus, a changed output may not become immediately visible but instead appear with variable delay depending on the latency of the bus used for communication.

A bus such as PCI is relatively simple because register accesses are routed directly to the connected device. In the worst case, a read operation stalls the CPU until the device responds.

A bus such as USB is more complex, involving multiple layers. A register read or write is wrapped in a USB Request Block (URB), which is then sent by the USB host controller to the device. Timing and latency are influenced by the underlying USB bus. Requests cannot be sent immediately; they must align with the next frame boundary according to the endpoint type and the host controller's scheduling rules. This can introduce delays and additional latency. For example, a network device connected via USB may still deliver sufficient throughput, but the added latency when sending or receiving packets may fail to meet the requirements of certain real-time use cases.

Additional restrictions on bus latency can arise from power management. For instance, PCIe with Active State Power Management (ASPM) enabled can suspend the link between the device and the host. While this behavior is beneficial for power savings, it delays device access and adds latency to responses. This issue is not limited to PCIe; internal buses within a System-on-Chip (SoC) can also be affected by power management mechanisms.

<a id="rst-virtualization"></a>

## Virtualization

In a virtualized environment such as KVM, each guest CPU is represented as a thread on the host. If such a thread runs with real-time priority, the system should be tested to confirm it can sustain this behavior over extended periods. Because of its priority, the thread will not be preempted by lower-priority threads (such as SCHED_OTHER), which may then receive no CPU time. This can cause problems if a lower-priority thread is pinned to a CPU already occupied by a real-time task and unable to make progress. Even if a CPU has been isolated, the system may still (accidentally) start a per‑CPU thread on that CPU. Ensuring that a guest CPU goes idle is difficult, as it requires avoiding both task scheduling and interrupt handling. Furthermore, if the guest CPU does go idle but the guest system is booted with the option **idle=poll**, the guest CPU will never enter an idle state and will instead spin until an event arrives.

Device handling introduces additional considerations. Emulated PCI devices or VirtIO devices require a counterpart on the host to complete requests. This adds latency because the host must intercept and either process the request directly or schedule a thread for its completion. These delays can be avoided if the required PCI device is passed directly through to the guest. Some devices, such as networking or storage controllers, support the PCIe SR-IOV feature. SR-IOV allows a single PCIe device to be divided into multiple virtual functions, which can then be assigned to different guests.

<a id="rst-networking"></a>

## Networking

For low-latency networking, the full networking stack may be undesirable, as it can introduce additional sources of delay. In this context, XDP can be used as a shortcut to bypass much of the stack while still relying on the kernel's network driver.

The requirements are that the network driver must support XDP- preferably using an "skb pool" and that the application must use an XDP socket. Additional configuration may involve BPF filters, tuning networking queues, or configuring qdiscs for time-based transmission. These techniques are often applied in Time-Sensitive Networking (TSN) environments.

Documenting all required steps exceeds the scope of this text. For detailed guidance, see the TSN documentation at [https://tsn.readthedocs.io](<https://tsn.readthedocs.io>).

Another useful resource is the Linux Real-Time Communication Testbench [https://github.com/Linutronix/RTC-Testbench](<https://github.com/Linutronix/RTC-Testbench>). The goal of this project is to validate real-time network communication. It can be thought of as a "cyclictest" for networking and also serves as a starting point for application development.

---

# Theory of operation

_Peios Kernel / Internals / Core APIs / real-time_

> PREEMPT_RT transforms the Linux kernel into a real-time kernel. It achieves this by replacing locking primitives, such as spinlock_t, with a preemptible and priority-inheritance aware implementation known as rtmutex, and by enforcing the…

<a id="rst-theory-of-operation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Sebastian Andrzej Siewior &lt;[bigeasy@linutronix.de](<mailto:bigeasy@linutronix.de>)&gt;

<a id="rst-preface"></a>

## Preface

PREEMPT_RT transforms the Linux kernel into a real-time kernel. It achieves this by replacing locking primitives, such as spinlock_t, with a preemptible and priority-inheritance aware implementation known as rtmutex, and by enforcing the use of threaded interrupts. As a result, the kernel becomes fully preemptible, with the exception of a few critical code paths, including entry code, the scheduler, and low-level interrupt handling routines.

This transformation places the majority of kernel execution contexts under the control of the scheduler and significantly increasing the number of preemption points. Consequently, it reduces the latency between a high-priority task becoming runnable and its actual execution on the CPU.

<a id="rst-scheduling"></a>

## Scheduling

The core principles of Linux scheduling and the associated user-space API are documented in the man page sched(7) [sched(7)](<https://man7.org/linux/man-pages/man7/sched.7.html>)<a id="rst-sched-7"></a>. By default, the Linux kernel uses the SCHED_OTHER scheduling policy. Under this policy, a task is preempted when the scheduler determines that it has consumed a fair share of CPU time relative to other runnable tasks. However, the policy does not guarantee immediate preemption when a new SCHED_OTHER task becomes runnable. The currently running task may continue executing.

This behavior differs from that of real-time scheduling policies such as SCHED_FIFO. When a task with a real-time policy becomes runnable, the scheduler immediately selects it for execution if it has a higher priority than the currently running task. The task continues to run until it voluntarily yields the CPU, typically by blocking on an event.

<a id="rst-sleeping-spin-locks"></a>

## Sleeping spin locks

The various lock types and their behavior under real-time configurations are described in detail in [Documentation/locking/locktypes.rst](/kernel/internals/locking/locktypes.md). In a non-PREEMPT_RT configuration, a spinlock_t is acquired by first disabling preemption and then actively spinning until the lock becomes available. Once the lock is released, preemption is enabled. From a real-time perspective, this approach is undesirable because disabling preemption prevents the scheduler from switching to a higher-priority task, potentially increasing latency.

To address this, PREEMPT_RT replaces spinning locks with sleeping spin locks that do not disable preemption. On PREEMPT_RT, spinlock_t is implemented using rtmutex. Instead of spinning, a task attempting to acquire a contended lock disables CPU migration, donates its priority to the lock owner (priority inheritance), and voluntarily schedules out while waiting for the lock to become available.

Disabling CPU migration provides the same effect as disabling preemption, while still allowing preemption and ensuring that the task continues to run on the same CPU while holding a sleeping lock.

<a id="rst-priority-inheritance"></a>

## Priority inheritance

Lock types such as spinlock_t and mutex_t in a PREEMPT_RT enabled kernel are implemented on top of rtmutex, which provides support for priority inheritance (PI). When a task blocks on such a lock, the PI mechanism temporarily propagates the blocked task’s scheduling parameters to the lock owner.

For example, if a SCHED_FIFO task A blocks on a lock currently held by a SCHED_OTHER task B, task A’s scheduling policy and priority are temporarily inherited by task B. After this inheritance, task A is put to sleep while waiting for the lock, and task B effectively becomes the highest-priority task in the system. This allows B to continue executing, make progress, and eventually release the lock.

Once B releases the lock, it reverts to its original scheduling parameters, and task A can resume execution.

<a id="rst-threaded-interrupts"></a>

## Threaded interrupts

Interrupt handlers are another source of code that executes with preemption disabled and outside the control of the scheduler. To bring interrupt handling under scheduler control, PREEMPT_RT enforces threaded interrupt handlers.

With forced threading, interrupt handling is split into two stages. The first stage, the primary handler, is executed in IRQ context with interrupts disabled. Its sole responsibility is to wake the associated threaded handler. The second stage, the threaded handler, is the function passed to request_irq() as the interrupt handler. It runs in process context, scheduled by the kernel.

From waking the interrupt thread until threaded handling is completed, the interrupt source is masked in the interrupt controller. This ensures that the device interrupt remains pending but does not retrigger the CPU, allowing the system to exit IRQ context and handle the interrupt in a scheduled thread.

By default, the threaded handler executes with the SCHED_FIFO scheduling policy and a priority of 50 (MAX_RT_PRIO / 2), which is midway between the minimum and maximum real-time priorities.

If the threaded interrupt handler raises any soft interrupts during its execution, those soft interrupt routines are invoked after the threaded handler completes, within the same thread. Preemption remains enabled during the execution of the soft interrupt handler.

<a id="rst-summary"></a>

## Summary

By using sleeping locks and forced-threaded interrupts, PREEMPT_RT significantly reduces sections of code where interrupts or preemption is disabled, allowing the scheduler to preempt the current execution context and switch to a higher-priority task.

---

# Atomic bitops

_Peios Kernel / Internals / Core APIs / wrappers_

> Reference for Atomic bitops.

<a id="rst-atomic-bitops"></a>

<!-- SPDX-License-Identifier: GPL-2.0
This is a simple wrapper to bring atomic_bitops.txt into the RST world
until such a time as that file can be converted directly. -->

<!-- Source LaTeX layout: \footnotesize -->




```text
=============
Atomic bitops
=============

While our bitmap_{}() functions are non-atomic, we have a number of operations
operating on single bits in a bitmap that are atomic.


API
---

The single bit operations are:

Non-RMW ops:

  test_bit()

RMW atomic operations without return value:

  {set,clear,change}_bit()
  clear_bit_unlock()

RMW atomic operations with return value:

  test_and_{set,clear,change}_bit()
  test_and_set_bit_lock()

Barriers:

  smp_mb__{before,after}_atomic()


All RMW atomic operations have a '__' prefixed variant which is non-atomic.


SEMANTICS
---------

Non-atomic ops:

In particular __clear_bit_unlock() suffers the same issue as atomic_set(),
which is why the generic version maps to clear_bit_unlock(), see atomic_t.txt.


RMW ops:

The test_and_{}_bit() operations return the original value of the bit.


ORDERING
--------

Like with atomic_t, the rule of thumb is:

 - non-RMW operations are unordered;

 - RMW operations that have no return value are unordered;

 - RMW operations that have a return value are fully ordered.

 - RMW operations that are conditional are fully ordered.

Except for a successful test_and_set_bit_lock() which has ACQUIRE semantics,
clear_bit_unlock() which has RELEASE semantics and test_bit_acquire which has
ACQUIRE semantics.

Since a platform only has a single means of achieving atomic operations
the same barriers as for atomic_t are used, see atomic_t.txt.


```


<!-- Source LaTeX layout: \normalsize -->

---

# Atomic types

_Peios Kernel / Internals / Core APIs / wrappers_

> Reference for Atomic types.

<a id="rst-atomic-types"></a>

<!-- SPDX-License-Identifier: GPL-2.0
This is a simple wrapper to bring atomic_t.txt into the RST world
until such a time as that file can be converted directly. -->

<!-- Source LaTeX layout: \footnotesize -->




```text

On atomic types (atomic_t atomic64_t and atomic_long_t).

The atomic type provides an interface to the architecture's means of atomic
RMW operations between CPUs (atomic operations on MMIO are not supported and
can lead to fatal traps on some platforms).

API
---

The 'full' API consists of (atomic64_ and atomic_long_ prefixes omitted for
brevity):

Non-RMW ops:

  atomic_read(), atomic_set()
  atomic_read_acquire(), atomic_set_release()


RMW atomic operations:

Arithmetic:

  atomic_{add,sub,inc,dec}()
  atomic_{add,sub,inc,dec}_return{,_relaxed,_acquire,_release}()
  atomic_fetch_{add,sub,inc,dec}{,_relaxed,_acquire,_release}()


Bitwise:

  atomic_{and,or,xor,andnot}()
  atomic_fetch_{and,or,xor,andnot}{,_relaxed,_acquire,_release}()


Swap:

  atomic_xchg{,_relaxed,_acquire,_release}()
  atomic_cmpxchg{,_relaxed,_acquire,_release}()
  atomic_try_cmpxchg{,_relaxed,_acquire,_release}()


Reference count (but please see refcount_t):

  atomic_add_unless(), atomic_inc_not_zero()
  atomic_sub_and_test(), atomic_dec_and_test()


Misc:

  atomic_inc_and_test(), atomic_add_negative()
  atomic_dec_unless_positive(), atomic_inc_unless_negative()


Barriers:

  smp_mb__{before,after}_atomic()


TYPES (signed vs unsigned)
-----

While atomic_t, atomic_long_t and atomic64_t use int, long and s64
respectively (for hysterical raisins), the kernel uses -fno-strict-overflow
(which implies -fwrapv) and defines signed overflow to behave like
2s-complement.

Therefore, an explicitly unsigned variant of the atomic ops is strictly
unnecessary and we can simply cast, there is no UB.

There was a bug in UBSAN prior to GCC-8 that would generate UB warnings for
signed types.

With this we also conform to the C/C++ _Atomic behaviour and things like
P1236R1.


SEMANTICS
---------

Non-RMW ops:

The non-RMW ops are (typically) regular LOADs and STOREs and are canonically
implemented using READ_ONCE(), WRITE_ONCE(), smp_load_acquire() and
smp_store_release() respectively. Therefore, if you find yourself only using
the Non-RMW operations of atomic_t, you do not in fact need atomic_t at all
and are doing it wrong.

A note for the implementation of atomic_set{}() is that it must not break the
atomicity of the RMW ops. That is:

  C Atomic-RMW-ops-are-atomic-WRT-atomic_set

  {
    atomic_t v = ATOMIC_INIT(1);
  }

  P0(atomic_t *v)
  {
    (void)atomic_add_unless(v, 1, 0);
  }

  P1(atomic_t *v)
  {
    atomic_set(v, 0);
  }

  exists
  (v=2)

In this case we would expect the atomic_set() from CPU1 to either happen
before the atomic_add_unless(), in which case that latter one would no-op, or
_after_ in which case we'd overwrite its result. In no case is "2" a valid
outcome.

This is typically true on 'normal' platforms, where a regular competing STORE
will invalidate a LL/SC or fail a CMPXCHG.

The obvious case where this is not so is when we need to implement atomic ops
with a lock:

  CPU0                                          CPU1

  atomic_add_unless(v, 1, 0);
    lock();
    ret = READ_ONCE(v->counter); // == 1
                                                atomic_set(v, 0);
    if (ret != u)                                 WRITE_ONCE(v->counter, 0);
      WRITE_ONCE(v->counter, ret + 1);
    unlock();

the typical solution is to then implement atomic_set{}() with atomic_xchg().


RMW ops:

These come in various forms:

 - plain operations without return value: atomic_{}()

 - operations which return the modified value: atomic_{}_return()

   these are limited to the arithmetic operations because those are
   reversible. Bitops are irreversible and therefore the modified value
   is of dubious utility.

 - operations which return the original value: atomic_fetch_{}()

 - swap operations: xchg(), cmpxchg() and try_cmpxchg()

 - misc; the special purpose operations that are commonly used and would,
   given the interface, normally be implemented using (try_)cmpxchg loops but
   are time critical and can, (typically) on LL/SC architectures, be more
   efficiently implemented.

All these operations are SMP atomic; that is, the operations (for a single
atomic variable) can be fully ordered and no intermediate state is lost or
visible.


ORDERING  (go read memory-barriers.txt first)
--------

The rule of thumb:

 - non-RMW operations are unordered;

 - RMW operations that have no return value are unordered;

 - RMW operations that have a return value are fully ordered;

 - RMW operations that are conditional are unordered on FAILURE,
   otherwise the above rules apply.

Except of course when a successful operation has an explicit ordering like:

 {}_relaxed: unordered
 {}_acquire: the R of the RMW (or atomic_read) is an ACQUIRE
 {}_release: the W of the RMW (or atomic_set)  is a  RELEASE

Where 'unordered' is against other memory locations. Address dependencies are
not defeated.  Conditional operations are still unordered on FAILURE.

Fully ordered primitives are ordered against everything prior and everything
subsequent. Therefore a fully ordered primitive is like having an smp_mb()
before and an smp_mb() after the primitive.


The barriers:

  smp_mb__{before,after}_atomic()

only apply to the RMW atomic ops and can be used to augment/upgrade the
ordering inherent to the op. These barriers act almost like a full smp_mb():
smp_mb__before_atomic() orders all earlier accesses against the RMW op
itself and all accesses following it, and smp_mb__after_atomic() orders all
later accesses against the RMW op and all accesses preceding it. However,
accesses between the smp_mb__{before,after}_atomic() and the RMW op are not
ordered, so it is advisable to place the barrier right next to the RMW atomic
op whenever possible.

These helper barriers exist because architectures have varying implicit
ordering on their SMP atomic primitives. For example our TSO architectures
provide full ordered atomics and these barriers are no-ops.

NOTE: when the atomic RmW ops are fully ordered, they should also imply a
compiler barrier.

Thus:

  atomic_fetch_add();

is equivalent to:

  smp_mb__before_atomic();
  atomic_fetch_add_relaxed();
  smp_mb__after_atomic();

However the atomic_fetch_add() might be implemented more efficiently.

Further, while something like:

  smp_mb__before_atomic();
  atomic_dec(&X);

is a 'typical' RELEASE pattern, the barrier is strictly stronger than
a RELEASE because it orders preceding instructions against both the read
and write parts of the atomic_dec(), and against all following instructions
as well. Similarly, something like:

  atomic_inc(&X);
  smp_mb__after_atomic();

is an ACQUIRE pattern (though very much not typical), but again the barrier is
strictly stronger than ACQUIRE. As illustrated:

  C Atomic-RMW+mb__after_atomic-is-stronger-than-acquire

  {
  }

  P0(int *x, atomic_t *y)
  {
    r0 = READ_ONCE(*x);
    smp_rmb();
    r1 = atomic_read(y);
  }

  P1(int *x, atomic_t *y)
  {
    atomic_inc(y);
    smp_mb__after_atomic();
    WRITE_ONCE(*x, 1);
  }

  exists
  (0:r0=1 /\ 0:r1=0)

This should not happen; but a hypothetical atomic_inc_acquire() --
(void)atomic_fetch_inc_acquire() for instance -- would allow the outcome,
because it would not order the W part of the RMW against the following
WRITE_ONCE.  Thus:

  P0                    P1

                        t = LL.acq *y (0)
                        t++;
                        *x = 1;
  r0 = *x (1)
  RMB
  r1 = *y (0)
                        SC *y, t;

is allowed.


CMPXCHG vs TRY_CMPXCHG
----------------------

  int atomic_cmpxchg(atomic_t *ptr, int old, int new);
  bool atomic_try_cmpxchg(atomic_t *ptr, int *oldp, int new);

Both provide the same functionality, but try_cmpxchg() can lead to more
compact code. The functions relate like:

  bool atomic_try_cmpxchg(atomic_t *ptr, int *oldp, int new)
  {
    int ret, old = *oldp;
    ret = atomic_cmpxchg(ptr, old, new);
    if (ret != old)
      *oldp = ret;
    return ret == old;
  }

and:

  int atomic_cmpxchg(atomic_t *ptr, int old, int new)
  {
    (void)atomic_try_cmpxchg(ptr, &old, new);
    return old;
  }

Usage:

  old = atomic_read(&v);                        old = atomic_read(&v);
  for (;;) {                                    do {
    new = func(old);                              new = func(old);
    tmp = atomic_cmpxchg(&v, old, new);         } while (!atomic_try_cmpxchg(&v, &old, new));
    if (tmp == old)
      break;
    old = tmp;
  }

NB. try_cmpxchg() also generates better code on some platforms (notably x86)
where the function more closely matches the hardware instruction.


FORWARD PROGRESS
----------------

In general strong forward progress is expected of all unconditional atomic
operations -- those in the Arithmetic and Bitwise classes and xchg(). However
a fair amount of code also requires forward progress from the conditional
atomic operations.

Specifically 'simple' cmpxchg() loops are expected to not starve one another
indefinitely. However, this is not evident on LL/SC architectures, because
while an LL/SC architecture 'can/should/must' provide forward progress
guarantees between competing LL/SC sections, such a guarantee does not
transfer to cmpxchg() implemented using LL/SC. Consider:

  old = atomic_read(&v);
  do {
    new = func(old);
  } while (!atomic_try_cmpxchg(&v, &old, new));

which on LL/SC becomes something like:

  old = atomic_read(&v);
  do {
    new = func(old);
  } while (!({
    volatile asm ("1: LL  %[oldval], %[v]\n"
                  "   CMP %[oldval], %[old]\n"
                  "   BNE 2f\n"
                  "   SC  %[new], %[v]\n"
                  "   BNE 1b\n"
                  "2:\n"
                  : [oldval] "=&r" (oldval), [v] "m" (v)
                  : [old] "r" (old), [new] "r" (new)
                  : "memory");
    success = (oldval == old);
    if (!success)
      old = oldval;
    success; }));

However, even the forward branch from the failed compare can cause the LL/SC
to fail on some architectures, let alone whatever the compiler makes of the C
loop body. As a result there is no guarantee what so ever the cacheline
containing @v will stay on the local CPU and progress is made.

Even native CAS architectures can fail to provide forward progress for their
primitive (See Sparc64 for an example).

Such implementations are strongly encouraged to add exponential backoff loops
to a failed CAS in order to ensure some progress. Affected architectures are
also strongly encouraged to inspect/audit the atomic fallbacks, refcount_t and
their locking primitives.

```


<!-- Source LaTeX layout: \normalsize -->

---

# Linux kernel memory barriers

_Peios Kernel / Internals / Core APIs / wrappers_

> Reference for Linux kernel memory barriers.

<a id="rst-linux-kernel-memory-barriers"></a>

<!-- SPDX-License-Identifier: GPL-2.0
This is a simple wrapper to bring memory-barriers.txt into the RST world
until such a time as that file can be converted directly. -->

<!-- Source LaTeX layout: \footnotesize -->




```text
                         ============================
                         LINUX KERNEL MEMORY BARRIERS
                         ============================

By: David Howells <dhowells@redhat.com>
    Paul E. McKenney <paulmck@linux.ibm.com>
    Will Deacon <will.deacon@arm.com>
    Peter Zijlstra <peterz@infradead.org>

==========
DISCLAIMER
==========

This document is not a specification; it is intentionally (for the sake of
brevity) and unintentionally (due to being human) incomplete. This document is
meant as a guide to using the various memory barriers provided by Linux, but
in case of any doubt (and there are many) please ask.  Some doubts may be
resolved by referring to the formal memory consistency model and related
documentation at tools/memory-model/.  Nevertheless, even this memory
model should be viewed as the collective opinion of its maintainers rather
than as an infallible oracle.

To repeat, this document is not a specification of what Linux expects from
hardware.

The purpose of this document is twofold:

 (1) to specify the minimum functionality that one can rely on for any
     particular barrier, and

 (2) to provide a guide as to how to use the barriers that are available.

Note that an architecture can provide more than the minimum requirement
for any particular barrier, but if the architecture provides less than
that, that architecture is incorrect.

Note also that it is possible that a barrier may be a no-op for an
architecture because the way that arch works renders an explicit barrier
unnecessary in that case.


========
CONTENTS
========

 (*) Abstract memory access model.

     - Device operations.
     - Guarantees.

 (*) What are memory barriers?

     - Varieties of memory barrier.
     - What may not be assumed about memory barriers?
     - Address-dependency barriers (historical).
     - Control dependencies.
     - SMP barrier pairing.
     - Examples of memory barrier sequences.
     - Read memory barriers vs load speculation.
     - Multicopy atomicity.

 (*) Explicit kernel barriers.

     - Compiler barrier.
     - CPU memory barriers.

 (*) Implicit kernel memory barriers.

     - Lock acquisition functions.
     - Interrupt disabling functions.
     - Sleep and wake-up functions.
     - Miscellaneous functions.

 (*) Inter-CPU acquiring barrier effects.

     - Acquires vs memory accesses.

 (*) Where are memory barriers needed?

     - Interprocessor interaction.
     - Atomic operations.
     - Accessing devices.
     - Interrupts.

 (*) Kernel I/O barrier effects.

 (*) Assumed minimum execution ordering model.

 (*) The effects of the cpu cache.

     - Cache coherency vs DMA.
     - Cache coherency vs MMIO.

 (*) The things CPUs get up to.

     - And then there's the Alpha.
     - Virtual Machine Guests.

 (*) Example uses.

     - Circular buffers.

 (*) References.


============================
ABSTRACT MEMORY ACCESS MODEL
============================

Consider the following abstract model of the system:

                            :                :
                            :                :
                            :                :
                +-------+   :   +--------+   :   +-------+
                |       |   :   |        |   :   |       |
                |       |   :   |        |   :   |       |
                | CPU 1 |<----->| Memory |<----->| CPU 2 |
                |       |   :   |        |   :   |       |
                |       |   :   |        |   :   |       |
                +-------+   :   +--------+   :   +-------+
                    ^       :       ^        :       ^
                    |       :       |        :       |
                    |       :       |        :       |
                    |       :       v        :       |
                    |       :   +--------+   :       |
                    |       :   |        |   :       |
                    |       :   |        |   :       |
                    +---------->| Device |<----------+
                            :   |        |   :
                            :   |        |   :
                            :   +--------+   :
                            :                :

Each CPU executes a program that generates memory access operations.  In the
abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
perform the memory operations in any order it likes, provided program causality
appears to be maintained.  Similarly, the compiler may also arrange the
instructions it emits in any order it likes, provided it doesn't affect the
apparent operation of the program.

So in the above diagram, the effects of the memory operations performed by a
CPU are perceived by the rest of the system as the operations cross the
interface between the CPU and rest of the system (the dotted lines).


For example, consider the following sequence of events:

        CPU 1           CPU 2
        =============== ===============
        { A == 1; B == 2 }
        A = 3;          x = B;
        B = 4;          y = A;

The set of accesses as seen by the memory system in the middle can be arranged
in 24 different combinations:

        STORE A=3,      STORE B=4,      y=LOAD A->3,    x=LOAD B->4
        STORE A=3,      STORE B=4,      x=LOAD B->4,    y=LOAD A->3
        STORE A=3,      y=LOAD A->3,    STORE B=4,      x=LOAD B->4
        STORE A=3,      y=LOAD A->3,    x=LOAD B->2,    STORE B=4
        STORE A=3,      x=LOAD B->2,    STORE B=4,      y=LOAD A->3
        STORE A=3,      x=LOAD B->2,    y=LOAD A->3,    STORE B=4
        STORE B=4,      STORE A=3,      y=LOAD A->3,    x=LOAD B->4
        STORE B=4, ...
        ...

and can thus result in four different combinations of values:

        x == 2, y == 1
        x == 2, y == 3
        x == 4, y == 1
        x == 4, y == 3


Furthermore, the stores committed by a CPU to the memory system may not be
perceived by the loads made by another CPU in the same order as the stores were
committed.


As a further example, consider this sequence of events:

        CPU 1           CPU 2
        =============== ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;          Q = P;
        P = &B;         D = *Q;

There is an obvious address dependency here, as the value loaded into D depends
on the address retrieved from P by CPU 2.  At the end of the sequence, any of
the following results are possible:

        (Q == &A) and (D == 1)
        (Q == &B) and (D == 2)
        (Q == &B) and (D == 4)

Note that CPU 2 will never try and load C into D because the CPU will load P
into Q before issuing the load of *Q.


DEVICE OPERATIONS
-----------------

Some devices present their control interfaces as collections of memory
locations, but the order in which the control registers are accessed is very
important.  For instance, imagine an ethernet card with a set of internal
registers that are accessed through an address port register (A) and a data
port register (D).  To read internal register 5, the following code might then
be used:

        *A = 5;
        x = *D;

but this might show up as either of the following two sequences:

        STORE *A = 5, x = LOAD *D
        x = LOAD *D, STORE *A = 5

the second of which will almost certainly result in a malfunction, since it set
the address _after_ attempting to read the register.


GUARANTEES
----------

There are some minimal guarantees that may be expected of a CPU:

 (*) On any given CPU, dependent memory accesses will be issued in order, with
     respect to itself.  This means that for:

        Q = READ_ONCE(P); D = READ_ONCE(*Q);

     the CPU will issue the following memory operations:

        Q = LOAD P, D = LOAD *Q

     and always in that order.  However, on DEC Alpha, READ_ONCE() also
     emits a memory-barrier instruction, so that a DEC Alpha CPU will
     instead issue the following memory operations:

        Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER

     Whether on DEC Alpha or not, the READ_ONCE() also prevents compiler
     mischief.

 (*) Overlapping loads and stores within a particular CPU will appear to be
     ordered within that CPU.  This means that for:

        a = READ_ONCE(*X); WRITE_ONCE(*X, b);

     the CPU will only issue the following sequence of memory operations:

        a = LOAD *X, STORE *X = b

     And for:

        WRITE_ONCE(*X, c); d = READ_ONCE(*X);

     the CPU will only issue:

        STORE *X = c, d = LOAD *X

     (Loads and stores overlap if they are targeted at overlapping pieces of
     memory).

And there are a number of things that _must_ or _must_not_ be assumed:

 (*) It _must_not_ be assumed that the compiler will do what you want
     with memory references that are not protected by READ_ONCE() and
     WRITE_ONCE().  Without them, the compiler is within its rights to
     do all sorts of "creative" transformations, which are covered in
     the COMPILER BARRIER section.

 (*) It _must_not_ be assumed that independent loads and stores will be issued
     in the order given.  This means that for:

        X = *A; Y = *B; *D = Z;

     we may get any of the following sequences:

        X = LOAD *A,  Y = LOAD *B,  STORE *D = Z
        X = LOAD *A,  STORE *D = Z, Y = LOAD *B
        Y = LOAD *B,  X = LOAD *A,  STORE *D = Z
        Y = LOAD *B,  STORE *D = Z, X = LOAD *A
        STORE *D = Z, X = LOAD *A,  Y = LOAD *B
        STORE *D = Z, Y = LOAD *B,  X = LOAD *A

 (*) It _must_ be assumed that overlapping memory accesses may be merged or
     discarded.  This means that for:

        X = *A; Y = *(A + 4);

     we may get any one of the following sequences:

        X = LOAD *A; Y = LOAD *(A + 4);
        Y = LOAD *(A + 4); X = LOAD *A;
        {X, Y} = LOAD {*A, *(A + 4) };

     And for:

        *A = X; *(A + 4) = Y;

     we may get any of:

        STORE *A = X; STORE *(A + 4) = Y;
        STORE *(A + 4) = Y; STORE *A = X;
        STORE {*A, *(A + 4) } = {X, Y};

And there are anti-guarantees:

 (*) These guarantees do not apply to bitfields, because compilers often
     generate code to modify these using non-atomic read-modify-write
     sequences.  Do not attempt to use bitfields to synchronize parallel
     algorithms.

 (*) Even in cases where bitfields are protected by locks, all fields
     in a given bitfield must be protected by one lock.  If two fields
     in a given bitfield are protected by different locks, the compiler's
     non-atomic read-modify-write sequences can cause an update to one
     field to corrupt the value of an adjacent field.

 (*) These guarantees apply only to properly aligned and sized scalar
     variables.  "Properly sized" currently means variables that are
     the same size as "char", "short", "int" and "long".  "Properly
     aligned" means the natural alignment, thus no constraints for
     "char", two-byte alignment for "short", four-byte alignment for
     "int", and either four-byte or eight-byte alignment for "long",
     on 32-bit and 64-bit systems, respectively.  Note that these
     guarantees were introduced into the C11 standard, so beware when
     using older pre-C11 compilers (for example, gcc 4.6).  The portion
     of the standard containing this guarantee is Section 3.14, which
     defines "memory location" as follows:

        memory location
                either an object of scalar type, or a maximal sequence
                of adjacent bit-fields all having nonzero width

                NOTE 1: Two threads of execution can update and access
                separate memory locations without interfering with
                each other.

                NOTE 2: A bit-field and an adjacent non-bit-field member
                are in separate memory locations. The same applies
                to two bit-fields, if one is declared inside a nested
                structure declaration and the other is not, or if the two
                are separated by a zero-length bit-field declaration,
                or if they are separated by a non-bit-field member
                declaration. It is not safe to concurrently update two
                bit-fields in the same structure if all members declared
                between them are also bit-fields, no matter what the
                sizes of those intervening bit-fields happen to be.


=========================
WHAT ARE MEMORY BARRIERS?
=========================

As can be seen above, independent memory operations are effectively performed
in random order, but this can be a problem for CPU-CPU interaction and for I/O.
What is required is some way of intervening to instruct the compiler and the
CPU to restrict the order.

Memory barriers are such interventions.  They impose a perceived partial
ordering over the memory operations on either side of the barrier.

Such enforcement is important because the CPUs and other devices in a system
can use a variety of tricks to improve performance, including reordering,
deferral and combination of memory operations; speculative loads; speculative
branch prediction and various types of caching.  Memory barriers are used to
override or suppress these tricks, allowing the code to sanely control the
interaction of multiple CPUs and/or devices.


VARIETIES OF MEMORY BARRIER
---------------------------

Memory barriers come in four basic varieties:

 (1) Write (or store) memory barriers.

     A write memory barrier gives a guarantee that all the STORE operations
     specified before the barrier will appear to happen before all the STORE
     operations specified after the barrier with respect to the other
     components of the system.

     A write barrier is a partial ordering on stores only; it is not required
     to have any effect on loads.

     A CPU can be viewed as committing a sequence of store operations to the
     memory system as time progresses.  All stores _before_ a write barrier
     will occur _before_ all the stores after the write barrier.

     [!] Note that write barriers should normally be paired with read or
     address-dependency barriers; see the "SMP barrier pairing" subsection.


 (2) Address-dependency barriers (historical).
     [!] This section is marked as HISTORICAL: it covers the long-obsolete
     smp_read_barrier_depends() macro, the semantics of which are now
     implicit in all marked accesses.  For more up-to-date information,
     including how compiler transformations can sometimes break address
     dependencies, see Documentation/RCU/rcu_dereference.rst.

     An address-dependency barrier is a weaker form of read barrier.  In the
     case where two loads are performed such that the second depends on the
     result of the first (eg: the first load retrieves the address to which
     the second load will be directed), an address-dependency barrier would
     be required to make sure that the target of the second load is updated
     after the address obtained by the first load is accessed.

     An address-dependency barrier is a partial ordering on interdependent
     loads only; it is not required to have any effect on stores, independent
     loads or overlapping loads.

     As mentioned in (1), the other CPUs in the system can be viewed as
     committing sequences of stores to the memory system that the CPU being
     considered can then perceive.  An address-dependency barrier issued by
     the CPU under consideration guarantees that for any load preceding it,
     if that load touches one of a sequence of stores from another CPU, then
     by the time the barrier completes, the effects of all the stores prior to
     that touched by the load will be perceptible to any loads issued after
     the address-dependency barrier.

     See the "Examples of memory barrier sequences" subsection for diagrams
     showing the ordering constraints.

     [!] Note that the first load really has to have an _address_ dependency and
     not a control dependency.  If the address for the second load is dependent
     on the first load, but the dependency is through a conditional rather than
     actually loading the address itself, then it's a _control_ dependency and
     a full read barrier or better is required.  See the "Control dependencies"
     subsection for more information.

     [!] Note that address-dependency barriers should normally be paired with
     write barriers; see the "SMP barrier pairing" subsection.

     [!] Kernel release v5.9 removed kernel APIs for explicit address-
     dependency barriers.  Nowadays, APIs for marking loads from shared
     variables such as READ_ONCE() and rcu_dereference() provide implicit
     address-dependency barriers.

 (3) Read (or load) memory barriers.

     A read barrier is an address-dependency barrier plus a guarantee that all
     the LOAD operations specified before the barrier will appear to happen
     before all the LOAD operations specified after the barrier with respect to
     the other components of the system.

     A read barrier is a partial ordering on loads only; it is not required to
     have any effect on stores.

     Read memory barriers imply address-dependency barriers, and so can
     substitute for them.

     [!] Note that read barriers should normally be paired with write barriers;
     see the "SMP barrier pairing" subsection.


 (4) General memory barriers.

     A general memory barrier gives a guarantee that all the LOAD and STORE
     operations specified before the barrier will appear to happen before all
     the LOAD and STORE operations specified after the barrier with respect to
     the other components of the system.

     A general memory barrier is a partial ordering over both loads and stores.

     General memory barriers imply both read and write memory barriers, and so
     can substitute for either.


And a couple of implicit varieties:

 (5) ACQUIRE operations.

     This acts as a one-way permeable barrier.  It guarantees that all memory
     operations after the ACQUIRE operation will appear to happen after the
     ACQUIRE operation with respect to the other components of the system.
     ACQUIRE operations include LOCK operations and both smp_load_acquire()
     and smp_cond_load_acquire() operations.

     Memory operations that occur before an ACQUIRE operation may appear to
     happen after it completes.

     An ACQUIRE operation should almost always be paired with a RELEASE
     operation.


 (6) RELEASE operations.

     This also acts as a one-way permeable barrier.  It guarantees that all
     memory operations before the RELEASE operation will appear to happen
     before the RELEASE operation with respect to the other components of the
     system. RELEASE operations include UNLOCK operations and
     smp_store_release() operations.

     Memory operations that occur after a RELEASE operation may appear to
     happen before it completes.

     The use of ACQUIRE and RELEASE operations generally precludes the need
     for other sorts of memory barrier.  In addition, a RELEASE+ACQUIRE pair is
     -not- guaranteed to act as a full memory barrier.  However, after an
     ACQUIRE on a given variable, all memory accesses preceding any prior
     RELEASE on that same variable are guaranteed to be visible.  In other
     words, within a given variable's critical section, all accesses of all
     previous critical sections for that variable are guaranteed to have
     completed.

     This means that ACQUIRE acts as a minimal "acquire" operation and
     RELEASE acts as a minimal "release" operation.

A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
RELEASE variants in addition to fully-ordered and relaxed (no barrier
semantics) definitions.  For compound atomics performing both a load and a
store, ACQUIRE semantics apply only to the load and RELEASE semantics apply
only to the store portion of the operation.

Memory barriers are only required where there's a possibility of interaction
between two CPUs or between a CPU and a device.  If it can be guaranteed that
there won't be any such interaction in any particular piece of code, then
memory barriers are unnecessary in that piece of code.


Note that these are the _minimum_ guarantees.  Different architectures may give
more substantial guarantees, but they may _not_ be relied upon outside of arch
specific code.


WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
----------------------------------------------

There are certain things that the Linux kernel memory barriers do not guarantee:

 (*) There is no guarantee that any of the memory accesses specified before a
     memory barrier will be _complete_ by the completion of a memory barrier
     instruction; the barrier can be considered to draw a line in that CPU's
     access queue that accesses of the appropriate type may not cross.

 (*) There is no guarantee that issuing a memory barrier on one CPU will have
     any direct effect on another CPU or any other hardware in the system.  The
     indirect effect will be the order in which the second CPU sees the effects
     of the first CPU's accesses occur, but see the next point:

 (*) There is no guarantee that a CPU will see the correct order of effects
     from a second CPU's accesses, even _if_ the second CPU uses a memory
     barrier, unless the first CPU _also_ uses a matching memory barrier (see
     the subsection on "SMP Barrier Pairing").

 (*) There is no guarantee that some intervening piece of off-the-CPU
     hardware[*] will not reorder the memory accesses.  CPU cache coherency
     mechanisms should propagate the indirect effects of a memory barrier
     between CPUs, but might not do so in order.

        [*] For information on bus mastering DMA and coherency please read:

            Documentation/driver-api/pci/pci.rst
            Documentation/core-api/dma-api-howto.rst
            Documentation/core-api/dma-api.rst


ADDRESS-DEPENDENCY BARRIERS (HISTORICAL)
----------------------------------------
[!] This section is marked as HISTORICAL: it covers the long-obsolete
smp_read_barrier_depends() macro, the semantics of which are now implicit
in all marked accesses.  For more up-to-date information, including
how compiler transformations can sometimes break address dependencies,
see Documentation/RCU/rcu_dereference.rst.

As of v4.15 of the Linux kernel, an smp_mb() was added to READ_ONCE() for
DEC Alpha, which means that about the only people who need to pay attention
to this section are those working on DEC Alpha architecture-specific code
and those working on READ_ONCE() itself.  For those who need it, and for
those who are interested in the history, here is the story of
address-dependency barriers.

[!] While address dependencies are observed in both load-to-load and
load-to-store relations, address-dependency barriers are not necessary
for load-to-store situations.

The requirement of address-dependency barriers is a little subtle, and
it's not always obvious that they're needed.  To illustrate, consider the
following sequence of events:

        CPU 1                 CPU 2
        ===============       ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE_OLD(P);
                              D = *Q;

[!] READ_ONCE_OLD() corresponds to READ_ONCE() of pre-4.15 kernel, which
doesn't imply an address-dependency barrier.

There's a clear address dependency here, and it would seem that by the end of
the sequence, Q must be either &A or &B, and that:

        (Q == &A) implies (D == 1)
        (Q == &B) implies (D == 4)

But!  CPU 2's perception of P may be updated _before_ its perception of B, thus
leading to the following situation:

        (Q == &B) and (D == 2) ????

While this may seem like a failure of coherency or causality maintenance, it
isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
Alpha).

To deal with this, READ_ONCE() provides an implicit address-dependency barrier
since kernel release v4.15:

        CPU 1                 CPU 2
        ===============       ===============
        { A == 1, B == 2, C == 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE(P);
                              <implicit address-dependency barrier>
                              D = *Q;

This enforces the occurrence of one of the two implications, and prevents the
third possibility from arising.


[!] Note that this extremely counterintuitive situation arises most easily on
machines with split caches, so that, for example, one cache bank processes
even-numbered cache lines and the other bank processes odd-numbered cache
lines.  The pointer P might be stored in an odd-numbered cache line, and the
variable B might be stored in an even-numbered cache line.  Then, if the
even-numbered bank of the reading CPU's cache is extremely busy while the
odd-numbered bank is idle, one can see the new value of the pointer P (&B),
but the old value of the variable B (2).


An address-dependency barrier is not required to order dependent writes
because the CPUs that the Linux kernel supports don't do writes until they
are certain (1) that the write will actually happen, (2) of the location of
the write, and (3) of the value to be written.
But please carefully read the "CONTROL DEPENDENCIES" section and the
Documentation/RCU/rcu_dereference.rst file:  The compiler can and does break
dependencies in a great many highly creative ways.

        CPU 1                 CPU 2
        ===============       ===============
        { A == 1, B == 2, C = 3, P == &A, Q == &C }
        B = 4;
        <write barrier>
        WRITE_ONCE(P, &B);
                              Q = READ_ONCE_OLD(P);
                              WRITE_ONCE(*Q, 5);

Therefore, no address-dependency barrier is required to order the read into
Q with the store into *Q.  In other words, this outcome is prohibited,
even without an implicit address-dependency barrier of modern READ_ONCE():

        (Q == &B) && (B == 4)

Please note that this pattern should be rare.  After all, the whole point
of dependency ordering is to -prevent- writes to the data structure, along
with the expensive cache misses associated with those writes.  This pattern
can be used to record rare error conditions and the like, and the CPUs'
naturally occurring ordering prevents such records from being lost.


Note well that the ordering provided by an address dependency is local to
the CPU containing it.  See the section on "Multicopy atomicity" for
more information.


The address-dependency barrier is very important to the RCU system,
for example.  See rcu_assign_pointer() and rcu_dereference() in
include/linux/rcupdate.h.  This permits the current target of an RCU'd
pointer to be replaced with a new modified target, without the replacement
target appearing to be incompletely initialised.


CONTROL DEPENDENCIES
--------------------

Control dependencies can be a bit tricky because current compilers do
not understand them.  The purpose of this section is to help you prevent
the compiler's ignorance from breaking your code.

A load-load control dependency requires a full read memory barrier, not
simply an (implicit) address-dependency barrier to make it work correctly.
Consider the following bit of code:

        q = READ_ONCE(a);
        <implicit address-dependency barrier>
        if (q) {
                /* BUG: No address dependency!!! */
                p = READ_ONCE(b);
        }

This will not have the desired effect because there is no actual address
dependency, but rather a control dependency that the CPU may short-circuit
by attempting to predict the outcome in advance, so that other CPUs see
the load from b as having happened before the load from a.  In such a case
what's actually required is:

        q = READ_ONCE(a);
        if (q) {
                <read barrier>
                p = READ_ONCE(b);
        }

However, stores are not speculated.  This means that ordering -is- provided
for load-store control dependencies, as in the following example:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
        }

Control dependencies pair normally with other types of barriers.
That said, please note that neither READ_ONCE() nor WRITE_ONCE()
are optional! Without the READ_ONCE(), the compiler might combine the
load from 'a' with other loads from 'a'.  Without the WRITE_ONCE(),
the compiler might combine the store to 'b' with other stores to 'b'.
Either can result in highly counterintuitive effects on ordering.

Worse yet, if the compiler is able to prove (say) that the value of
variable 'a' is always non-zero, it would be well within its rights
to optimize the original example by eliminating the "if" statement
as follows:

        q = a;
        b = 1;  /* BUG: Compiler and CPU can both reorder!!! */

So don't leave out the READ_ONCE().

It is tempting to try to enforce ordering on identical stores on both
branches of the "if" statement as follows:

        q = READ_ONCE(a);
        if (q) {
                barrier();
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                barrier();
                WRITE_ONCE(b, 1);
                do_something_else();
        }

Unfortunately, current compilers will transform this as follows at high
optimization levels:

        q = READ_ONCE(a);
        barrier();
        WRITE_ONCE(b, 1);  /* BUG: No ordering vs. load from a!!! */
        if (q) {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something();
        } else {
                /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
                do_something_else();
        }

Now there is no conditional between the load from 'a' and the store to
'b', which means that the CPU is within its rights to reorder them:
The conditional is absolutely required, and must be present in the
assembly code even after all compiler optimizations have been applied.
Therefore, if you need ordering in this example, you need explicit
memory barriers, for example, smp_store_release():

        q = READ_ONCE(a);
        if (q) {
                smp_store_release(&b, 1);
                do_something();
        } else {
                smp_store_release(&b, 1);
                do_something_else();
        }

In contrast, without explicit memory barriers, two-legged-if control
ordering is guaranteed only when the stores differ, for example:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

The initial READ_ONCE() is still required to prevent the compiler from
proving the value of 'a'.

In addition, you need to be careful what you do with the local variable 'q',
otherwise the compiler might be able to guess the value and again remove
the needed conditional.  For example:

        q = READ_ONCE(a);
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

If MAX is defined to be 1, then the compiler knows that (q % MAX) is
equal to zero, in which case the compiler is within its rights to
transform the above code into the following:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 2);
        do_something_else();

Given this transformation, the CPU is not required to respect the ordering
between the load from variable 'a' and the store to variable 'b'.  It is
tempting to add a barrier(), but this does not help.  The conditional
is gone, and the barrier won't bring it back.  Therefore, if you are
relying on this ordering, you should make sure that MAX is greater than
one, perhaps as follows:

        q = READ_ONCE(a);
        BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
        if (q % MAX) {
                WRITE_ONCE(b, 1);
                do_something();
        } else {
                WRITE_ONCE(b, 2);
                do_something_else();
        }

Please note once again that the stores to 'b' differ.  If they were
identical, as noted earlier, the compiler could pull this store outside
of the 'if' statement.

You must also be careful not to rely too much on boolean short-circuit
evaluation.  Consider this example:

        q = READ_ONCE(a);
        if (q || 1 > 0)
                WRITE_ONCE(b, 1);

Because the first condition cannot fault and the second condition is
always true, the compiler can transform this example as following,
defeating control dependency:

        q = READ_ONCE(a);
        WRITE_ONCE(b, 1);

This example underscores the need to ensure that the compiler cannot
out-guess your code.  More generally, although READ_ONCE() does force
the compiler to actually emit code for a given load, it does not force
the compiler to use the results.

In addition, control dependencies apply only to the then-clause and
else-clause of the if-statement in question.  In particular, it does
not necessarily apply to code following the if-statement:

        q = READ_ONCE(a);
        if (q) {
                WRITE_ONCE(b, 1);
        } else {
                WRITE_ONCE(b, 2);
        }
        WRITE_ONCE(c, 1);  /* BUG: No ordering against the read from 'a'. */

It is tempting to argue that there in fact is ordering because the
compiler cannot reorder volatile accesses and also cannot reorder
the writes to 'b' with the condition.  Unfortunately for this line
of reasoning, the compiler might compile the two writes to 'b' as
conditional-move instructions, as in this fanciful pseudo-assembly
language:

        ld r1,a
        cmp r1,$0
        cmov,ne r4,$1
        cmov,eq r4,$2
        st r4,b
        st $1,c

A weakly ordered CPU would have no dependency of any sort between the load
from 'a' and the store to 'c'.  The control dependencies would extend
only to the pair of cmov instructions and the store depending on them.
In short, control dependencies apply only to the stores in the then-clause
and else-clause of the if-statement in question (including functions
invoked by those two clauses), not to code following that if-statement.


Note well that the ordering provided by a control dependency is local
to the CPU containing it.  See the section on "Multicopy atomicity"
for more information.


In summary:

  (*) Control dependencies can order prior loads against later stores.
      However, they do -not- guarantee any other sort of ordering:
      Not prior loads against later loads, nor prior stores against
      later anything.  If you need these other forms of ordering,
      use smp_rmb(), smp_wmb(), or, in the case of prior stores and
      later loads, smp_mb().

  (*) If both legs of the "if" statement begin with identical stores to
      the same variable, then those stores must be ordered, either by
      preceding both of them with smp_mb() or by using smp_store_release()
      to carry out the stores.  Please note that it is -not- sufficient
      to use barrier() at beginning of each leg of the "if" statement
      because, as shown by the example above, optimizing compilers can
      destroy the control dependency while respecting the letter of the
      barrier() law.

  (*) Control dependencies require at least one run-time conditional
      between the prior load and the subsequent store, and this
      conditional must involve the prior load.  If the compiler is able
      to optimize the conditional away, it will have also optimized
      away the ordering.  Careful use of READ_ONCE() and WRITE_ONCE()
      can help to preserve the needed conditional.

  (*) Control dependencies require that the compiler avoid reordering the
      dependency into nonexistence.  Careful use of READ_ONCE() or
      atomic{,64}_read() can help to preserve your control dependency.
      Please see the COMPILER BARRIER section for more information.

  (*) Control dependencies apply only to the then-clause and else-clause
      of the if-statement containing the control dependency, including
      any functions that these two clauses call.  Control dependencies
      do -not- apply to code following the if-statement containing the
      control dependency.

  (*) Control dependencies pair normally with other types of barriers.

  (*) Control dependencies do -not- provide multicopy atomicity.  If you
      need all the CPUs to see a given store at the same time, use smp_mb().

  (*) Compilers do not understand control dependencies.  It is therefore
      your job to ensure that they do not break your code.


SMP BARRIER PAIRING
-------------------

When dealing with CPU-CPU interactions, certain types of memory barrier should
always be paired.  A lack of appropriate pairing is almost certainly an error.

General barriers pair with each other, though they also pair with most
other types of barriers, albeit without multicopy atomicity.  An acquire
barrier pairs with a release barrier, but both may also pair with other
barriers, including of course general barriers.  A write barrier pairs
with an address-dependency barrier, a control dependency, an acquire barrier,
a release barrier, a read barrier, or a general barrier.  Similarly a
read barrier, control dependency, or an address-dependency barrier pairs
with a write barrier, an acquire barrier, a release barrier, or a
general barrier:

        CPU 1                 CPU 2
        ===============       ===============
        WRITE_ONCE(a, 1);
        <write barrier>
        WRITE_ONCE(b, 2);     x = READ_ONCE(b);
                              <read barrier>
                              y = READ_ONCE(a);

Or:

        CPU 1                 CPU 2
        ===============       ===============================
        a = 1;
        <write barrier>
        WRITE_ONCE(b, &a);    x = READ_ONCE(b);
                              <implicit address-dependency barrier>
                              y = *x;

Or even:

        CPU 1                 CPU 2
        ===============       ===============================
        r1 = READ_ONCE(y);
        <general barrier>
        WRITE_ONCE(x, 1);     if (r2 = READ_ONCE(x)) {
                                 <implicit control dependency>
                                 WRITE_ONCE(y, 1);
                              }

        assert(r1 == 0 || r2 == 0);

Basically, the read barrier always has to be there, even though it can be of
the "weaker" type.

[!] Note that the stores before the write barrier would normally be expected to
match the loads after the read barrier or the address-dependency barrier, and
vice versa:

        CPU 1                               CPU 2
        ===================                 ===================
        WRITE_ONCE(a, 1);    }----   --->{  v = READ_ONCE(c);
        WRITE_ONCE(b, 2);    }    \ /    {  w = READ_ONCE(d);
        <write barrier>            \        <read barrier>
        WRITE_ONCE(c, 3);    }    / \    {  x = READ_ONCE(a);
        WRITE_ONCE(d, 4);    }----   --->{  y = READ_ONCE(b);


EXAMPLES OF MEMORY BARRIER SEQUENCES
------------------------------------

Firstly, write barriers act as partial orderings on store operations.
Consider the following sequence of events:

        CPU 1
        =======================
        STORE A = 1
        STORE B = 2
        STORE C = 3
        <write barrier>
        STORE D = 4
        STORE E = 5

This sequence of events is committed to the memory coherence system in an order
that the rest of the system might perceive as the unordered set of { STORE A,
STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
}:

        +-------+       :      :
        |       |       +------+
        |       |------>| C=3  |     }     /\
        |       |  :    +------+     }-----  \  -----> Events perceptible to
        |       |  :    | A=1  |     }        \/       the rest of the system
        |       |  :    +------+     }
        | CPU 1 |  :    | B=2  |     }
        |       |       +------+     }
        |       |   wwwwwwwwwwwwwwww }   <--- At this point the write barrier
        |       |       +------+     }        requires all stores prior to the
        |       |  :    | E=5  |     }        barrier to be committed before
        |       |  :    +------+     }        further stores may take place
        |       |------>| D=4  |     }
        |       |       +------+
        +-------+       :      :
                           |
                           | Sequence in which stores are committed to the
                           | memory system by CPU 1
                           V


Secondly, address-dependency barriers act as partial orderings on address-
dependent loads.  Consider the following sequence of events:

        CPU 1                   CPU 2
        ======================= =======================
                { B = 7; X = 9; Y = 8; C = &Y }
        STORE A = 1
        STORE B = 2
        <write barrier>
        STORE C = &B            LOAD X
        STORE D = 4             LOAD C (gets &B)
                                LOAD *C (reads B)

Without intervention, CPU 2 may perceive the events on CPU 1 in some
effectively random order, despite the write barrier issued by CPU 1:

        +-------+       :      :                :       :
        |       |       +------+                +-------+  | Sequence of update
        |       |------>| B=2  |-----       --->| Y->8  |  | of perception on
        |       |  :    +------+     \          +-------+  | CPU 2
        | CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
        |       |       +------+       |        +-------+
        |       |   wwwwwwwwwwwwwwww   |        :       :
        |       |       +------+       |        :       :
        |       |  :    | C=&B |---    |        :       :       +-------+
        |       |  :    +------+   \   |        +-------+       |       |
        |       |------>| D=4  |    ----------->| C->&B |------>|       |
        |       |       +------+       |        +-------+       |       |
        +-------+       :      :       |        :       :       |       |
                                       |        :       :       |       |
                                       |        :       :       | CPU 2 |
                                       |        +-------+       |       |
            Apparently incorrect --->  |        | B->7  |------>|       |
            perception of B (!)        |        +-------+       |       |
                                       |        :       :       |       |
                                       |        +-------+       |       |
            The load of X holds --->    \       | X->9  |------>|       |
            up the maintenance           \      +-------+       |       |
            of coherence of B             ----->| B->2  |       +-------+
                                                +-------+
                                                :       :


In the above example, CPU 2 perceives that B is 7, despite the load of *C
(which would be B) coming after the LOAD of C.

If, however, an address-dependency barrier were to be placed between the load
of C and the load of *C (ie: B) on CPU 2:

        CPU 1                   CPU 2
        ======================= =======================
                { B = 7; X = 9; Y = 8; C = &Y }
        STORE A = 1
        STORE B = 2
        <write barrier>
        STORE C = &B            LOAD X
        STORE D = 4             LOAD C (gets &B)
                                <address-dependency barrier>
                                LOAD *C (reads B)

then the following will occur:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| B=2  |-----       --->| Y->8  |
        |       |  :    +------+     \          +-------+
        | CPU 1 |  :    | A=1  |      \     --->| C->&Y |
        |       |       +------+       |        +-------+
        |       |   wwwwwwwwwwwwwwww   |        :       :
        |       |       +------+       |        :       :
        |       |  :    | C=&B |---    |        :       :       +-------+
        |       |  :    +------+   \   |        +-------+       |       |
        |       |------>| D=4  |    ----------->| C->&B |------>|       |
        |       |       +------+       |        +-------+       |       |
        +-------+       :      :       |        :       :       |       |
                                       |        :       :       |       |
                                       |        :       :       | CPU 2 |
                                       |        +-------+       |       |
                                       |        | X->9  |------>|       |
                                       |        +-------+       |       |
          Makes sure all effects --->   \   aaaaaaaaaaaaaaaaa   |       |
          prior to the store of C        \      +-------+       |       |
          are perceptible to              ----->| B->2  |------>|       |
          subsequent loads                      +-------+       |       |
                                                :       :       +-------+


And thirdly, a read barrier acts as a partial order on loads.  Consider the
following sequence of events:

        CPU 1                   CPU 2
        ======================= =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                LOAD A

Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
some effectively random order, despite the write barrier issued by CPU 1:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       | A->0  |------>|       |
                                        |       +-------+       |       |
                                        |       :       :       +-------+
                                         \      :       :
                                          \     +-------+
                                           ---->| A->1  |
                                                +-------+
                                                :       :


If, however, a read barrier were to be placed between the load of B and the
load of A on CPU 2:

        CPU 1                   CPU 2
        ======================= =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                <read barrier>
                                LOAD A

then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
2:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                        |       :       :       |       |
          At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
          barrier causes all effects      \     +-------+       |       |
          prior to the storage of B        ---->| A->1  |------>|       |
          to be perceptible to CPU 2            +-------+       |       |
                                                :       :       +-------+


To illustrate this more completely, consider what could happen if the code
contained a load of A either side of the read barrier:

        CPU 1                   CPU 2
        ======================= =======================
                { A = 0, B = 9 }
        STORE A=1
        <write barrier>
        STORE B=2
                                LOAD B
                                LOAD A [first load of A]
                                <read barrier>
                                LOAD A [second load of A]

Even though the two loads of A both occur after the load of B, they may both
come up with different values:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                        |       :       :       |       |
                                        |       +-------+       |       |
                                        |       | A->0  |------>| 1st   |
                                        |       +-------+       |       |
          At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
          barrier causes all effects      \     +-------+       |       |
          prior to the storage of B        ---->| A->1  |------>| 2nd   |
          to be perceptible to CPU 2            +-------+       |       |
                                                :       :       +-------+


But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
before the read barrier completes anyway:

        +-------+       :      :                :       :
        |       |       +------+                +-------+
        |       |------>| A=1  |------      --->| A->0  |
        |       |       +------+      \         +-------+
        | CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
        |       |       +------+        |       +-------+
        |       |------>| B=2  |---     |       :       :
        |       |       +------+   \    |       :       :       +-------+
        +-------+       :      :    \   |       +-------+       |       |
                                     ---------->| B->2  |------>|       |
                                        |       +-------+       | CPU 2 |
                                        |       :       :       |       |
                                         \      :       :       |       |
                                          \     +-------+       |       |
                                           ---->| A->1  |------>| 1st   |
                                                +-------+       |       |
                                            rrrrrrrrrrrrrrrrr   |       |
                                                +-------+       |       |
                                                | A->1  |------>| 2nd   |
                                                +-------+       |       |
                                                :       :       +-------+


The guarantee is that the second load will always come up with A == 1 if the
load of B came up with B == 2.  No such guarantee exists for the first load of
A; that may come up with either A == 0 or A == 1.


READ MEMORY BARRIERS VS LOAD SPECULATION
----------------------------------------

Many CPUs speculate with loads: that is they see that they will need to load an
item from memory, and they find a time where they're not using the bus for any
other loads, and so do the load in advance - even though they haven't actually
got to that point in the instruction execution flow yet.  This permits the
actual load instruction to potentially complete immediately because the CPU
already has the value to hand.

It may turn out that the CPU didn't actually need the value - perhaps because a
branch circumvented the load - in which case it can discard the value or just
cache it for later use.

Consider:

        CPU 1                   CPU 2
        ======================= =======================
                                LOAD B
                                DIVIDE          } Divide instructions generally
                                DIVIDE          } take a long time to perform
                                LOAD A

Which might appear as this:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
        Once the divisions are complete -->     :       :   ~-->|       |
        the CPU can then perform the            :       :       |       |
        LOAD with immediate effect              :       :       +-------+


Placing a read barrier or an address-dependency barrier just before the second
load:

        CPU 1                   CPU 2
        ======================= =======================
                                LOAD B
                                DIVIDE
                                DIVIDE
                                <read barrier>
                                LOAD A

will force any value speculatively obtained to be reconsidered to an extent
dependent on the type of barrier used.  If there was no change made to the
speculated memory location, then the speculated value will just be used:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
                                                :       :   ~   |       |
                                            rrrrrrrrrrrrrrrr~   |       |
                                                :       :   ~   |       |
                                                :       :   ~-->|       |
                                                :       :       |       |
                                                :       :       +-------+


but if there was an update or an invalidation from another CPU pending, then
the speculation will be cancelled and the value reloaded:

                                                :       :       +-------+
                                                +-------+       |       |
                                            --->| B->2  |------>|       |
                                                +-------+       | CPU 2 |
                                                :       :DIVIDE |       |
                                                +-------+       |       |
        The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
        division speculates on the              +-------+   ~   |       |
        LOAD of A                               :       :   ~   |       |
                                                :       :DIVIDE |       |
                                                :       :   ~   |       |
                                                :       :   ~   |       |
                                            rrrrrrrrrrrrrrrrr   |       |
                                                +-------+       |       |
        The speculation is discarded --->   --->| A->1  |------>|       |
        and an updated value is                 +-------+       |       |
        retrieved                               :       :       +-------+


MULTICOPY ATOMICITY
--------------------

Multicopy atomicity is a deeply intuitive notion about ordering that is
not always provided by real computer systems, namely that a given store
becomes visible at the same time to all CPUs, or, alternatively, that all
CPUs agree on the order in which all stores become visible.  However,
support of full multicopy atomicity would rule out valuable hardware
optimizations, so a weaker form called ``other multicopy atomicity''
instead guarantees only that a given store becomes visible at the same
time to all -other- CPUs.  The remainder of this document discusses this
weaker form, but for brevity will call it simply ``multicopy atomicity''.

The following example demonstrates multicopy atomicity:

        CPU 1                   CPU 2                   CPU 3
        ======================= ======================= =======================
                { X = 0, Y = 0 }
        STORE X=1               r1=LOAD X (reads 1)     LOAD Y (reads 1)
                                <general barrier>       <read barrier>
                                STORE Y=r1              LOAD X

Suppose that CPU 2's load from X returns 1, which it then stores to Y,
and CPU 3's load from Y returns 1.  This indicates that CPU 1's store
to X precedes CPU 2's load from X and that CPU 2's store to Y precedes
CPU 3's load from Y.  In addition, the memory barriers guarantee that
CPU 2 executes its load before its store, and CPU 3 loads from Y before
it loads from X.  The question is then "Can CPU 3's load from X return 0?"

Because CPU 3's load from X in some sense comes after CPU 2's load, it
is natural to expect that CPU 3's load from X must therefore return 1.
This expectation follows from multicopy atomicity: if a load executing
on CPU B follows a load from the same variable executing on CPU A (and
CPU A did not originally store the value which it read), then on
multicopy-atomic systems, CPU B's load must return either the same value
that CPU A's load did or some later value.  However, the Linux kernel
does not require systems to be multicopy atomic.

The use of a general memory barrier in the example above compensates
for any lack of multicopy atomicity.  In the example, if CPU 2's load
from X returns 1 and CPU 3's load from Y returns 1, then CPU 3's load
from X must indeed also return 1.

However, dependencies, read barriers, and write barriers are not always
able to compensate for non-multicopy atomicity.  For example, suppose
that CPU 2's general barrier is removed from the above example, leaving
only the data dependency shown below:

        CPU 1                   CPU 2                   CPU 3
        ======================= ======================= =======================
                { X = 0, Y = 0 }
        STORE X=1               r1=LOAD X (reads 1)     LOAD Y (reads 1)
                                <data dependency>       <read barrier>
                                STORE Y=r1              LOAD X (reads 0)

This substitution allows non-multicopy atomicity to run rampant: in
this example, it is perfectly legal for CPU 2's load from X to return 1,
CPU 3's load from Y to return 1, and its load from X to return 0.

The key point is that although CPU 2's data dependency orders its load
and store, it does not guarantee to order CPU 1's store.  Thus, if this
example runs on a non-multicopy-atomic system where CPUs 1 and 2 share a
store buffer or a level of cache, CPU 2 might have early access to CPU 1's
writes.  General barriers are therefore required to ensure that all CPUs
agree on the combined order of multiple accesses.

General barriers can compensate not only for non-multicopy atomicity,
but can also generate additional ordering that can ensure that -all-
CPUs will perceive the same order of -all- operations.  In contrast, a
chain of release-acquire pairs do not provide this additional ordering,
which means that only those CPUs on the chain are guaranteed to agree
on the combined order of the accesses.  For example, switching to C code
in deference to the ghost of Herman Hollerith:

        int u, v, x, y, z;

        void cpu0(void)
        {
                r0 = smp_load_acquire(&x);
                WRITE_ONCE(u, 1);
                smp_store_release(&y, 1);
        }

        void cpu1(void)
        {
                r1 = smp_load_acquire(&y);
                r4 = READ_ONCE(v);
                r5 = READ_ONCE(u);
                smp_store_release(&z, 1);
        }

        void cpu2(void)
        {
                r2 = smp_load_acquire(&z);
                smp_store_release(&x, 1);
        }

        void cpu3(void)
        {
                WRITE_ONCE(v, 1);
                smp_mb();
                r3 = READ_ONCE(u);
        }

Because cpu0(), cpu1(), and cpu2() participate in a chain of
smp_store_release()/smp_load_acquire() pairs, the following outcome
is prohibited:

        r0 == 1 && r1 == 1 && r2 == 1

Furthermore, because of the release-acquire relationship between cpu0()
and cpu1(), cpu1() must see cpu0()'s writes, so that the following
outcome is prohibited:

        r1 == 1 && r5 == 0

However, the ordering provided by a release-acquire chain is local
to the CPUs participating in that chain and does not apply to cpu3(),
at least aside from stores.  Therefore, the following outcome is possible:

        r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0

As an aside, the following outcome is also possible:

        r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1

Although cpu0(), cpu1(), and cpu2() will see their respective reads and
writes in order, CPUs not involved in the release-acquire chain might
well disagree on the order.  This disagreement stems from the fact that
the weak memory-barrier instructions used to implement smp_load_acquire()
and smp_store_release() are not required to order prior stores against
subsequent loads in all cases.  This means that cpu3() can see cpu0()'s
store to u as happening -after- cpu1()'s load from v, even though
both cpu0() and cpu1() agree that these two operations occurred in the
intended order.

However, please keep in mind that smp_load_acquire() is not magic.
In particular, it simply reads from its argument with ordering.  It does
-not- ensure that any particular value will be read.  Therefore, the
following outcome is possible:

        r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0

Note that this outcome can happen even on a mythical sequentially
consistent system where nothing is ever reordered.

To reiterate, if your code requires full ordering of all operations,
use general barriers throughout.


========================
EXPLICIT KERNEL BARRIERS
========================

The Linux kernel has a variety of different barriers that act at different
levels:

  (*) Compiler barrier.

  (*) CPU memory barriers.


COMPILER BARRIER
----------------

The Linux kernel has an explicit compiler barrier function that prevents the
compiler from moving the memory accesses either side of it to the other side:

        barrier();

This is a general barrier -- there are no read-read or write-write
variants of barrier().  However, READ_ONCE() and WRITE_ONCE() can be
thought of as weak forms of barrier() that affect only the specific
accesses flagged by the READ_ONCE() or WRITE_ONCE().

The barrier() function has the following effects:

 (*) Prevents the compiler from reordering accesses following the
     barrier() to precede any accesses preceding the barrier().
     One example use for this property is to ease communication between
     interrupt-handler code and the code that was interrupted.

 (*) Within a loop, forces the compiler to load the variables used
     in that loop's conditional on each pass through that loop.

The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
optimizations that, while perfectly safe in single-threaded code, can
be fatal in concurrent code.  Here are some examples of these sorts
of optimizations:

 (*) The compiler is within its rights to reorder loads and stores
     to the same variable, and in some cases, the CPU is within its
     rights to reorder loads to the same variable.  This means that
     the following code:

        a[0] = x;
        a[1] = x;

     Might result in an older value of x stored in a[1] than in a[0].
     Prevent both the compiler and the CPU from doing this as follows:

        a[0] = READ_ONCE(x);
        a[1] = READ_ONCE(x);

     In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
     accesses from multiple CPUs to a single variable.

 (*) The compiler is within its rights to merge successive loads from
     the same variable.  Such merging can cause the compiler to "optimize"
     the following code:

        while (tmp = a)
                do_something_with(tmp);

     into the following code, which, although in some sense legitimate
     for single-threaded code, is almost certainly not what the developer
     intended:

        if (tmp = a)
                for (;;)
                        do_something_with(tmp);

     Use READ_ONCE() to prevent the compiler from doing this to you:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

 (*) The compiler is within its rights to reload a variable, for example,
     in cases where high register pressure prevents the compiler from
     keeping all data of interest in registers.  The compiler might
     therefore optimize the variable 'tmp' out of our previous example:

        while (tmp = a)
                do_something_with(tmp);

     This could result in the following code, which is perfectly safe in
     single-threaded code, but can be fatal in concurrent code:

        while (a)
                do_something_with(a);

     For example, the optimized version of this code could result in
     passing a zero to do_something_with() in the case where the variable
     a was modified by some other CPU between the "while" statement and
     the call to do_something_with().

     Again, use READ_ONCE() to prevent the compiler from doing this:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

     Note that if the compiler runs short of registers, it might save
     tmp onto the stack.  The overhead of this saving and later restoring
     is why compilers reload variables.  Doing so is perfectly safe for
     single-threaded code, so you need to tell the compiler about cases
     where it is not safe.

 (*) The compiler is within its rights to omit a load entirely if it knows
     what the value will be.  For example, if the compiler can prove that
     the value of variable 'a' is always zero, it can optimize this code:

        while (tmp = a)
                do_something_with(tmp);

     Into this:

        do { } while (0);

     This transformation is a win for single-threaded code because it
     gets rid of a load and a branch.  The problem is that the compiler
     will carry out its proof assuming that the current CPU is the only
     one updating variable 'a'.  If variable 'a' is shared, then the
     compiler's proof will be erroneous.  Use READ_ONCE() to tell the
     compiler that it doesn't know as much as it thinks it does:

        while (tmp = READ_ONCE(a))
                do_something_with(tmp);

     But please note that the compiler is also closely watching what you
     do with the value after the READ_ONCE().  For example, suppose you
     do the following and MAX is a preprocessor macro with the value 1:

        while ((tmp = READ_ONCE(a)) % MAX)
                do_something_with(tmp);

     Then the compiler knows that the result of the "%" operator applied
     to MAX will always be zero, again allowing the compiler to optimize
     the code into near-nonexistence.  (It will still load from the
     variable 'a'.)

 (*) Similarly, the compiler is within its rights to omit a store entirely
     if it knows that the variable already has the value being stored.
     Again, the compiler assumes that the current CPU is the only one
     storing into the variable, which can cause the compiler to do the
     wrong thing for shared variables.  For example, suppose you have
     the following:

        a = 0;
        ... Code that does not store to variable a ...
        a = 0;

     The compiler sees that the value of variable 'a' is already zero, so
     it might well omit the second store.  This would come as a fatal
     surprise if some other CPU might have stored to variable 'a' in the
     meantime.

     Use WRITE_ONCE() to prevent the compiler from making this sort of
     wrong guess:

        WRITE_ONCE(a, 0);
        ... Code that does not store to variable a ...
        WRITE_ONCE(a, 0);

 (*) The compiler is within its rights to reorder memory accesses unless
     you tell it not to.  For example, consider the following interaction
     between process-level code and an interrupt handler:

        void process_level(void)
        {
                msg = get_message();
                flag = true;
        }

        void interrupt_handler(void)
        {
                if (flag)
                        process_message(msg);
        }

     There is nothing to prevent the compiler from transforming
     process_level() to the following, in fact, this might well be a
     win for single-threaded code:

        void process_level(void)
        {
                flag = true;
                msg = get_message();
        }

     If the interrupt occurs between these two statement, then
     interrupt_handler() might be passed a garbled msg.  Use WRITE_ONCE()
     to prevent this as follows:

        void process_level(void)
        {
                WRITE_ONCE(msg, get_message());
                WRITE_ONCE(flag, true);
        }

        void interrupt_handler(void)
        {
                if (READ_ONCE(flag))
                        process_message(READ_ONCE(msg));
        }

     Note that the READ_ONCE() and WRITE_ONCE() wrappers in
     interrupt_handler() are needed if this interrupt handler can itself
     be interrupted by something that also accesses 'flag' and 'msg',
     for example, a nested interrupt or an NMI.  Otherwise, READ_ONCE()
     and WRITE_ONCE() are not needed in interrupt_handler() other than
     for documentation purposes.  (Note also that nested interrupts
     do not typically occur in modern Linux kernels, in fact, if an
     interrupt handler returns with interrupts enabled, you will get a
     WARN_ONCE() splat.)

     You should assume that the compiler can move READ_ONCE() and
     WRITE_ONCE() past code not containing READ_ONCE(), WRITE_ONCE(),
     barrier(), or similar primitives.

     This effect could also be achieved using barrier(), but READ_ONCE()
     and WRITE_ONCE() are more selective:  With READ_ONCE() and
     WRITE_ONCE(), the compiler need only forget the contents of the
     indicated memory locations, while with barrier() the compiler must
     discard the value of all memory locations that it has currently
     cached in any machine registers.  Of course, the compiler must also
     respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
     though the CPU of course need not do so.

 (*) The compiler is within its rights to invent stores to a variable,
     as in the following example:

        if (a)
                b = a;
        else
                b = 42;

     The compiler might save a branch by optimizing this as follows:

        b = 42;
        if (a)
                b = a;

     In single-threaded code, this is not only safe, but also saves
     a branch.  Unfortunately, in concurrent code, this optimization
     could cause some other CPU to see a spurious value of 42 -- even
     if variable 'a' was never zero -- when loading variable 'b'.
     Use WRITE_ONCE() to prevent this as follows:

        if (a)
                WRITE_ONCE(b, a);
        else
                WRITE_ONCE(b, 42);

     The compiler can also invent loads.  These are usually less
     damaging, but they can result in cache-line bouncing and thus in
     poor performance and scalability.  Use READ_ONCE() to prevent
     invented loads.

 (*) For aligned memory locations whose size allows them to be accessed
     with a single memory-reference instruction, prevents "load tearing"
     and "store tearing," in which a single large access is replaced by
     multiple smaller accesses.  For example, given an architecture having
     16-bit store instructions with 7-bit immediate fields, the compiler
     might be tempted to use two 16-bit store-immediate instructions to
     implement the following 32-bit store:

        p = 0x00010002;

     Please note that GCC really does use this sort of optimization,
     which is not surprising given that it would likely take more
     than two instructions to build the constant and then store it.
     This optimization can therefore be a win in single-threaded code.
     In fact, a recent bug (since fixed) caused GCC to incorrectly use
     this optimization in a volatile store.  In the absence of such bugs,
     use of WRITE_ONCE() prevents store tearing in the following example:

        WRITE_ONCE(p, 0x00010002);

     Use of packed structures can also result in load and store tearing,
     as in this example:

        struct __attribute__((__packed__)) foo {
                short a;
                int b;
                short c;
        };
        struct foo foo1, foo2;
        ...

        foo2.a = foo1.a;
        foo2.b = foo1.b;
        foo2.c = foo1.c;

     Because there are no READ_ONCE() or WRITE_ONCE() wrappers and no
     volatile markings, the compiler would be well within its rights to
     implement these three assignment statements as a pair of 32-bit
     loads followed by a pair of 32-bit stores.  This would result in
     load tearing on 'foo1.b' and store tearing on 'foo2.b'.  READ_ONCE()
     and WRITE_ONCE() again prevent tearing in this example:

        foo2.a = foo1.a;
        WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
        foo2.c = foo1.c;

All that aside, it is never necessary to use READ_ONCE() and
WRITE_ONCE() on a variable that has been marked volatile.  For example,
because 'jiffies' is marked volatile, it is never necessary to
say READ_ONCE(jiffies).  The reason for this is that READ_ONCE() and
WRITE_ONCE() are implemented as volatile casts, which has no effect when
its argument is already marked volatile.

Please note that these compiler barriers have no direct effect on the CPU,
which may then reorder things however it wishes.


CPU MEMORY BARRIERS
-------------------

The Linux kernel has seven basic CPU memory barriers:

        TYPE                    MANDATORY       SMP CONDITIONAL
        ======================= =============== ===============
        GENERAL                 mb()            smp_mb()
        WRITE                   wmb()           smp_wmb()
        READ                    rmb()           smp_rmb()
        ADDRESS DEPENDENCY                      READ_ONCE()


All memory barriers except the address-dependency barriers imply a compiler
barrier.  Address dependencies do not impose any additional compiler ordering.

Aside: In the case of address dependencies, the compiler would be expected
to issue the loads in the correct order (eg. `a[b]` would have to load
the value of b before loading a[b]), however there is no guarantee in
the C specification that the compiler may not speculate the value of b
(eg. is equal to 1) and load a[b] before b (eg. tmp = a[1]; if (b != 1)
tmp = a[b]; ).  There is also the problem of a compiler reloading b after
having loaded a[b], thus having a newer copy of b than a[b].  A consensus
has not yet been reached about these problems, however the READ_ONCE()
macro is a good place to start looking.

SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
systems because it is assumed that a CPU will appear to be self-consistent,
and will order overlapping accesses correctly with respect to itself.
However, see the subsection on "Virtual Machine Guests" below.

[!] Note that SMP memory barriers _must_ be used to control the ordering of
references to shared memory on SMP systems, though the use of locking instead
is sufficient.

Mandatory barriers should not be used to control SMP effects, since mandatory
barriers impose unnecessary overhead on both SMP and UP systems. They may,
however, be used to control MMIO effects on accesses through relaxed memory I/O
windows.  These barriers are required even on non-SMP systems as they affect
the order in which memory operations appear to a device by prohibiting both the
compiler and the CPU from reordering them.


There are some more advanced barrier functions:

 (*) smp_store_mb(var, value)

     This assigns the value to the variable and then inserts a full memory
     barrier after it.  It isn't guaranteed to insert anything more than a
     compiler barrier in a UP compilation.


 (*) smp_mb__before_atomic();
 (*) smp_mb__after_atomic();

     These are for use with atomic RMW functions that do not imply memory
     barriers, but where the code needs a memory barrier. Examples for atomic
     RMW functions that do not imply a memory barrier are e.g. add,
     subtract, (failed) conditional operations, _relaxed functions,
     but not atomic_read or atomic_set. A common example where a memory
     barrier may be required is when atomic ops are used for reference
     counting.

     These are also used for atomic RMW bitop functions that do not imply a
     memory barrier (such as set_bit and clear_bit).

     As an example, consider a piece of code that marks an object as being dead
     and then decrements the object's reference count:

        obj->dead = 1;
        smp_mb__before_atomic();
        atomic_dec(&obj->ref_count);

     This makes sure that the death mark on the object is perceived to be set
     *before* the reference counter is decremented.

     See Documentation/atomic_{t,bitops}.txt for more information.


 (*) dma_wmb();
 (*) dma_rmb();
 (*) dma_mb();

     These are for use with consistent memory to guarantee the ordering
     of writes or reads of shared memory accessible to both the CPU and a
     DMA capable device. See Documentation/core-api/dma-api.rst file for more
     information about consistent memory.

     For example, consider a device driver that shares memory with a device
     and uses a descriptor status value to indicate if the descriptor belongs
     to the device or the CPU, and a doorbell to notify it when new
     descriptors are available:

        if (desc->status != DEVICE_OWN) {
                /* do not read data until we own descriptor */
                dma_rmb();

                /* read/modify data */
                read_data = desc->data;
                desc->data = write_data;

                /* flush modifications before status update */
                dma_wmb();

                /* assign ownership */
                desc->status = DEVICE_OWN;

                /* Make descriptor status visible to the device followed by
                 * notify device of new descriptor
                 */
                writel(DESC_NOTIFY, doorbell);
        }

     The dma_rmb() allows us to guarantee that the device has released ownership
     before we read the data from the descriptor, and the dma_wmb() allows
     us to guarantee the data is written to the descriptor before the device
     can see it now has ownership.  The dma_mb() implies both a dma_rmb() and
     a dma_wmb().

     Note that the dma_*() barriers do not provide any ordering guarantees for
     accesses to MMIO regions.  See the later "KERNEL I/O BARRIER EFFECTS"
     subsection for more information about I/O accessors and MMIO ordering.

 (*) pmem_wmb();

     This is for use with persistent memory to ensure that stores for which
     modifications are written to persistent storage reached a platform
     durability domain.

     For example, after a non-temporal write to pmem region, we use pmem_wmb()
     to ensure that stores have reached a platform durability domain. This ensures
     that stores have updated persistent storage before any data access or
     data transfer caused by subsequent instructions is initiated. This is
     in addition to the ordering done by wmb().

     For load from persistent memory, existing read memory barriers are sufficient
     to ensure read ordering.

 (*) io_stop_wc();

     For memory accesses with write-combining attributes (e.g. those returned
     by ioremap_wc()), the CPU may wait for prior accesses to be merged with
     subsequent ones. io_stop_wc() can be used to prevent the merging of
     write-combining memory accesses before this macro with those after it when
     such wait has performance implications.

===============================
IMPLICIT KERNEL MEMORY BARRIERS
===============================

Some of the other functions in the linux kernel imply memory barriers, amongst
which are locking and scheduling functions.

This specification is a _minimum_ guarantee; any particular architecture may
provide more substantial guarantees, but these may not be relied upon outside
of arch specific code.


LOCK ACQUISITION FUNCTIONS
--------------------------

The Linux kernel has a number of locking constructs:

 (*) spin locks
 (*) R/W spin locks
 (*) mutexes
 (*) semaphores
 (*) R/W semaphores

In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
for each construct.  These operations all imply certain barriers:

 (1) ACQUIRE operation implication:

     Memory operations issued after the ACQUIRE will be completed after the
     ACQUIRE operation has completed.

     Memory operations issued before the ACQUIRE may be completed after
     the ACQUIRE operation has completed.

 (2) RELEASE operation implication:

     Memory operations issued before the RELEASE will be completed before the
     RELEASE operation has completed.

     Memory operations issued after the RELEASE may be completed before the
     RELEASE operation has completed.

 (3) ACQUIRE vs ACQUIRE implication:

     All ACQUIRE operations issued before another ACQUIRE operation will be
     completed before that ACQUIRE operation.

 (4) ACQUIRE vs RELEASE implication:

     All ACQUIRE operations issued before a RELEASE operation will be
     completed before the RELEASE operation.

 (5) Failed conditional ACQUIRE implication:

     Certain locking variants of the ACQUIRE operation may fail, either due to
     being unable to get the lock immediately, or due to receiving an unblocked
     signal while asleep waiting for the lock to become available.  Failed
     locks do not imply any sort of barrier.

[!] Note: one of the consequences of lock ACQUIREs and RELEASEs being only
one-way barriers is that the effects of instructions outside of a critical
section may seep into the inside of the critical section.

An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
because it is possible for an access preceding the ACQUIRE to happen after the
ACQUIRE, and an access following the RELEASE to happen before the RELEASE, and
the two accesses can themselves then cross:

        *A = a;
        ACQUIRE M
        RELEASE M
        *B = b;

may occur as:

        ACQUIRE M, STORE *B, STORE *A, RELEASE M

When the ACQUIRE and RELEASE are a lock acquisition and release,
respectively, this same reordering can occur if the lock's ACQUIRE and
RELEASE are to the same lock variable, but only from the perspective of
another CPU not holding that lock.  In short, a ACQUIRE followed by an
RELEASE may -not- be assumed to be a full memory barrier.

Similarly, the reverse case of a RELEASE followed by an ACQUIRE does
not imply a full memory barrier.  Therefore, the CPU's execution of the
critical sections corresponding to the RELEASE and the ACQUIRE can cross,
so that:

        *A = a;
        RELEASE M
        ACQUIRE N
        *B = b;

could occur as:

        ACQUIRE N, STORE *B, STORE *A, RELEASE M

It might appear that this reordering could introduce a deadlock.
However, this cannot happen because if such a deadlock threatened,
the RELEASE would simply complete, thereby avoiding the deadlock.

        Why does this work?

        One key point is that we are only talking about the CPU doing
        the reordering, not the compiler.  If the compiler (or, for
        that matter, the developer) switched the operations, deadlock
        -could- occur.

        But suppose the CPU reordered the operations.  In this case,
        the unlock precedes the lock in the assembly code.  The CPU
        simply elected to try executing the later lock operation first.
        If there is a deadlock, this lock operation will simply spin (or
        try to sleep, but more on that later).  The CPU will eventually
        execute the unlock operation (which preceded the lock operation
        in the assembly code), which will unravel the potential deadlock,
        allowing the lock operation to succeed.

        But what if the lock is a sleeplock?  In that case, the code will
        try to enter the scheduler, where it will eventually encounter
        a memory barrier, which will force the earlier unlock operation
        to complete, again unraveling the deadlock.  There might be
        a sleep-unlock race, but the locking primitive needs to resolve
        such races properly in any case.

Locks and semaphores may not provide any guarantee of ordering on UP compiled
systems, and so cannot be counted on in such a situation to actually achieve
anything at all - especially with respect to I/O accesses - unless combined
with interrupt disabling operations.

See also the section on "Inter-CPU acquiring barrier effects".


As an example, consider the following:

        *A = a;
        *B = b;
        ACQUIRE
        *C = c;
        *D = d;
        RELEASE
        *E = e;
        *F = f;

The following sequence of events is acceptable:

        ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE

        [+] Note that {*F,*A} indicates a combined access.

But none of the following are:

        {*F,*A}, *B,    ACQUIRE, *C, *D,        RELEASE, *E
        *A, *B, *C,     ACQUIRE, *D,            RELEASE, *E, *F
        *A, *B,         ACQUIRE, *C,            RELEASE, *D, *E, *F
        *B,             ACQUIRE, *C, *D,        RELEASE, {*F,*A}, *E



INTERRUPT DISABLING FUNCTIONS
-----------------------------

Functions that disable interrupts (ACQUIRE equivalent) and enable interrupts
(RELEASE equivalent) will act as compiler barriers only.  So if memory or I/O
barriers are required in such a situation, they must be provided from some
other means.


SLEEP AND WAKE-UP FUNCTIONS
---------------------------

Sleeping and waking on an event flagged in global data can be viewed as an
interaction between two pieces of data: the task state of the task waiting for
the event and the global data used to indicate the event.  To make sure that
these appear to happen in the right order, the primitives to begin the process
of going to sleep, and the primitives to initiate a wake up imply certain
barriers.

Firstly, the sleeper normally follows something like this sequence of events:

        for (;;) {
                set_current_state(TASK_UNINTERRUPTIBLE);
                if (event_indicated)
                        break;
                schedule();
        }

A general memory barrier is interpolated automatically by set_current_state()
after it has altered the task state:

        CPU 1
        ===============================
        set_current_state();
          smp_store_mb();
            STORE current->state
            <general barrier>
        LOAD event_indicated

set_current_state() may be wrapped by:

        prepare_to_wait();
        prepare_to_wait_exclusive();

which therefore also imply a general memory barrier after setting the state.
The whole sequence above is available in various canned forms, all of which
interpolate the memory barrier in the right place, for example:

        wait_event();
        wait_event_cmd();
        wait_event_exclusive_cmd();
        wait_event_interruptible();
        wait_event_interruptible_exclusive();
        wait_event_interruptible_timeout();
        wait_event_killable();
        wait_event_timeout();
        wait_on_bit();
        wait_on_bit_lock();


Secondly, code that performs a wake up normally follows something like this:

        event_indicated = 1;
        wake_up(&event_wait_queue);

or:

        event_indicated = 1;
        wake_up_process(event_daemon);

A general memory barrier is executed by wake_up() if it wakes something up.
If it doesn't wake anything up then a memory barrier may or may not be
executed; you must not rely on it.  The barrier occurs before the task state
is accessed, in particular, it sits between the STORE to indicate the event
and the STORE to set TASK_RUNNING:

        CPU 1 (Sleeper)                 CPU 2 (Waker)
        =============================== ===============================
        set_current_state();            STORE event_indicated
          smp_store_mb();               wake_up();
            STORE current->state          ...
            <general barrier>             <general barrier>
        LOAD event_indicated              if ((LOAD task->state) & TASK_NORMAL)
                                            STORE task->state

where "task" is the thread being woken up and it equals CPU 1's "current".

To repeat, a general memory barrier is guaranteed to be executed by wake_up()
if something is actually awakened, but otherwise there is no such guarantee.
To see this, consider the following sequence of events, where X and Y are both
initially zero:

        CPU 1                           CPU 2
        =============================== ===============================
        X = 1;                          Y = 1;
        smp_mb();                       wake_up();
        LOAD Y                          LOAD X

If a wakeup does occur, one (at least) of the two loads must see 1.  If, on
the other hand, a wakeup does not occur, both loads might see 0.

wake_up_process() always executes a general memory barrier.  The barrier again
occurs before the task state is accessed.  In particular, if the wake_up() in
the previous snippet were replaced by a call to wake_up_process() then one of
the two loads would be guaranteed to see 1.

The available waker functions include:

        complete();
        wake_up();
        wake_up_all();
        wake_up_bit();
        wake_up_interruptible();
        wake_up_interruptible_all();
        wake_up_interruptible_nr();
        wake_up_interruptible_poll();
        wake_up_interruptible_sync();
        wake_up_interruptible_sync_poll();
        wake_up_locked();
        wake_up_locked_poll();
        wake_up_nr();
        wake_up_poll();
        wake_up_process();

In terms of memory ordering, these functions all provide the same guarantees of
a wake_up() (or stronger).

[!] Note that the memory barriers implied by the sleeper and the waker do _not_
order multiple stores before the wake-up with respect to loads of those stored
values after the sleeper has called set_current_state().  For instance, if the
sleeper does:

        set_current_state(TASK_INTERRUPTIBLE);
        if (event_indicated)
                break;
        __set_current_state(TASK_RUNNING);
        do_something(my_data);

and the waker does:

        my_data = value;
        event_indicated = 1;
        wake_up(&event_wait_queue);

there's no guarantee that the change to event_indicated will be perceived by
the sleeper as coming after the change to my_data.  In such a circumstance, the
code on both sides must interpolate its own memory barriers between the
separate data accesses.  Thus the above sleeper ought to do:

        set_current_state(TASK_INTERRUPTIBLE);
        if (event_indicated) {
                smp_rmb();
                do_something(my_data);
        }

and the waker should do:

        my_data = value;
        smp_wmb();
        event_indicated = 1;
        wake_up(&event_wait_queue);


MISCELLANEOUS FUNCTIONS
-----------------------

Other functions that imply barriers:

 (*) schedule() and similar imply full memory barriers.


===================================
INTER-CPU ACQUIRING BARRIER EFFECTS
===================================

On SMP systems locking primitives give a more substantial form of barrier: one
that does affect memory access ordering on other CPUs, within the context of
conflict on any particular lock.


ACQUIRES VS MEMORY ACCESSES
---------------------------

Consider the following: the system has a pair of spinlocks (M) and (Q), and
three CPUs; then should the following sequence of events occur:

        CPU 1                           CPU 2
        =============================== ===============================
        WRITE_ONCE(*A, a);              WRITE_ONCE(*E, e);
        ACQUIRE M                       ACQUIRE Q
        WRITE_ONCE(*B, b);              WRITE_ONCE(*F, f);
        WRITE_ONCE(*C, c);              WRITE_ONCE(*G, g);
        RELEASE M                       RELEASE Q
        WRITE_ONCE(*D, d);              WRITE_ONCE(*H, h);

Then there is no guarantee as to what order CPU 3 will see the accesses to *A
through *H occur in, other than the constraints imposed by the separate locks
on the separate CPUs.  It might, for example, see:

        *E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M

But it won't see any of:

        *B, *C or *D preceding ACQUIRE M
        *A, *B or *C following RELEASE M
        *F, *G or *H preceding ACQUIRE Q
        *E, *F or *G following RELEASE Q


=================================
WHERE ARE MEMORY BARRIERS NEEDED?
=================================

Under normal operation, memory operation reordering is generally not going to
be a problem as a single-threaded linear piece of code will still appear to
work correctly, even if it's in an SMP kernel.  There are, however, four
circumstances in which reordering definitely _could_ be a problem:

 (*) Interprocessor interaction.

 (*) Atomic operations.

 (*) Accessing devices.

 (*) Interrupts.


INTERPROCESSOR INTERACTION
--------------------------

When there's a system with more than one processor, more than one CPU in the
system may be working on the same data set at the same time.  This can cause
synchronisation problems, and the usual way of dealing with them is to use
locks.  Locks, however, are quite expensive, and so it may be preferable to
operate without the use of a lock if at all possible.  In such a case
operations that affect both CPUs may have to be carefully ordered to prevent
a malfunction.

Consider, for example, the R/W semaphore slow path.  Here a waiting process is
queued on the semaphore, by virtue of it having a piece of its stack linked to
the semaphore's list of waiting processes:

        struct rw_semaphore {
                ...
                spinlock_t lock;
                struct list_head waiters;
        };

        struct rwsem_waiter {
                struct list_head list;
                struct task_struct *task;
        };

To wake up a particular waiter, the up_read() or up_write() functions have to:

 (1) read the next pointer from this waiter's record to know as to where the
     next waiter record is;

 (2) read the pointer to the waiter's task structure;

 (3) clear the task pointer to tell the waiter it has been given the semaphore;

 (4) call wake_up_process() on the task; and

 (5) release the reference held on the waiter's task struct.

In other words, it has to perform this sequence of events:

        LOAD waiter->list.next;
        LOAD waiter->task;
        STORE waiter->task;
        CALL wakeup
        RELEASE task

and if any of these steps occur out of order, then the whole thing may
malfunction.

Once it has queued itself and dropped the semaphore lock, the waiter does not
get the lock again; it instead just waits for its task pointer to be cleared
before proceeding.  Since the record is on the waiter's stack, this means that
if the task pointer is cleared _before_ the next pointer in the list is read,
another CPU might start processing the waiter and might clobber the waiter's
stack before the up*() function has a chance to read the next pointer.

Consider then what might happen to the above sequence of events:

        CPU 1                           CPU 2
        =============================== ===============================
                                        down_xxx()
                                        Queue waiter
                                        Sleep
        up_yyy()
        LOAD waiter->task;
        STORE waiter->task;
                                        Woken up by other event
        <preempt>
                                        Resume processing
                                        down_xxx() returns
                                        call foo()
                                        foo() clobbers *waiter
        </preempt>
        LOAD waiter->list.next;
        --- OOPS ---

This could be dealt with using the semaphore lock, but then the down_xxx()
function has to needlessly get the spinlock again after being woken up.

The way to deal with this is to insert a general SMP memory barrier:

        LOAD waiter->list.next;
        LOAD waiter->task;
        smp_mb();
        STORE waiter->task;
        CALL wakeup
        RELEASE task

In this case, the barrier makes a guarantee that all memory accesses before the
barrier will appear to happen before all the memory accesses after the barrier
with respect to the other CPUs on the system.  It does _not_ guarantee that all
the memory accesses before the barrier will be complete by the time the barrier
instruction itself is complete.

On a UP system - where this wouldn't be a problem - the smp_mb() is just a
compiler barrier, thus making sure the compiler emits the instructions in the
right order without actually intervening in the CPU.  Since there's only one
CPU, that CPU's dependency ordering logic will take care of everything else.


ATOMIC OPERATIONS
-----------------

While they are technically interprocessor interaction considerations, atomic
operations are noted specially as some of them imply full memory barriers and
some don't, but they're very heavily relied on as a group throughout the
kernel.

See Documentation/atomic_t.txt for more information.


ACCESSING DEVICES
-----------------

Many devices can be memory mapped, and so appear to the CPU as if they're just
a set of memory locations.  To control such a device, the driver usually has to
make the right memory accesses in exactly the right order.

However, having a clever CPU or a clever compiler creates a potential problem
in that the carefully sequenced accesses in the driver code won't reach the
device in the requisite order if the CPU or the compiler thinks it is more
efficient to reorder, combine or merge accesses - something that would cause
the device to malfunction.

Inside of the Linux kernel, I/O should be done through the appropriate accessor
routines - such as inb() or writel() - which know how to make such accesses
appropriately sequential.  While this, for the most part, renders the explicit
use of memory barriers unnecessary, if the accessor functions are used to refer
to an I/O memory window with relaxed memory access properties, then _mandatory_
memory barriers are required to enforce ordering.

See Documentation/driver-api/device-io.rst for more information.


INTERRUPTS
----------

A driver may be interrupted by its own interrupt service routine, and thus the
two parts of the driver may interfere with each other's attempts to control or
access the device.

This may be alleviated - at least in part - by disabling local interrupts (a
form of locking), such that the critical operations are all contained within
the interrupt-disabled section in the driver.  While the driver's interrupt
routine is executing, the driver's core may not run on the same CPU, and its
interrupt is not permitted to happen again until the current interrupt has been
handled, thus the interrupt handler does not need to lock against that.

However, consider a driver that was talking to an ethernet card that sports an
address register and a data register.  If that driver's core talks to the card
under interrupt-disablement and then the driver's interrupt handler is invoked:

        LOCAL IRQ DISABLE
        writew(ADDR, 3);
        writew(DATA, y);
        LOCAL IRQ ENABLE
        <interrupt>
        writew(ADDR, 4);
        q = readw(DATA);
        </interrupt>

The store to the data register might happen after the second store to the
address register if ordering rules are sufficiently relaxed:

        STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA


If ordering rules are relaxed, it must be assumed that accesses done inside an
interrupt disabled section may leak outside of it and may interleave with
accesses performed in an interrupt - and vice versa - unless implicit or
explicit barriers are used.

Normally this won't be a problem because the I/O accesses done inside such
sections will include synchronous load operations on strictly ordered I/O
registers that form implicit I/O barriers.


A similar situation may occur between an interrupt routine and two routines
running on separate CPUs that communicate with each other.  If such a case is
likely, then interrupt-disabling locks should be used to guarantee ordering.


==========================
KERNEL I/O BARRIER EFFECTS
==========================

Interfacing with peripherals via I/O accesses is deeply architecture and device
specific. Therefore, drivers which are inherently non-portable may rely on
specific behaviours of their target systems in order to achieve synchronization
in the most lightweight manner possible. For drivers intending to be portable
between multiple architectures and bus implementations, the kernel offers a
series of accessor functions that provide various degrees of ordering
guarantees:

 (*) readX(), writeX():

        The readX() and writeX() MMIO accessors take a pointer to the
        peripheral being accessed as an __iomem * parameter. For pointers
        mapped with the default I/O attributes (e.g. those returned by
        ioremap()), the ordering guarantees are as follows:

        1. All readX() and writeX() accesses to the same peripheral are ordered
           with respect to each other. This ensures that MMIO register accesses
           by the same CPU thread to a particular device will arrive in program
           order.

        2. A writeX() issued by a CPU thread holding a spinlock is ordered
           before a writeX() to the same peripheral from another CPU thread
           issued after a later acquisition of the same spinlock. This ensures
           that MMIO register writes to a particular device issued while holding
           a spinlock will arrive in an order consistent with acquisitions of
           the lock.

        3. A writeX() by a CPU thread to the peripheral will first wait for the
           completion of all prior writes to memory either issued by, or
           propagated to, the same thread. This ensures that writes by the CPU
           to an outbound DMA buffer allocated by dma_alloc_coherent() will be
           visible to a DMA engine when the CPU writes to its MMIO control
           register to trigger the transfer.

        4. A readX() by a CPU thread from the peripheral will complete before
           any subsequent reads from memory by the same thread can begin. This
           ensures that reads by the CPU from an incoming DMA buffer allocated
           by dma_alloc_coherent() will not see stale data after reading from
           the DMA engine's MMIO status register to establish that the DMA
           transfer has completed.

        5. A readX() by a CPU thread from the peripheral will complete before
           any subsequent delay() loop can begin execution on the same thread.
           This ensures that two MMIO register writes by the CPU to a peripheral
           will arrive at least 1us apart if the first write is immediately read
           back with readX() and udelay(1) is called prior to the second
           writeX():

                writel(42, DEVICE_REGISTER_0); // Arrives at the device...
                readl(DEVICE_REGISTER_0);
                udelay(1);
                writel(42, DEVICE_REGISTER_1); // ...at least 1us before this.

        The ordering properties of __iomem pointers obtained with non-default
        attributes (e.g. those returned by ioremap_wc()) are specific to the
        underlying architecture and therefore the guarantees listed above cannot
        generally be relied upon for accesses to these types of mappings.

 (*) readX_relaxed(), writeX_relaxed():

        These are similar to readX() and writeX(), but provide weaker memory
        ordering guarantees. Specifically, they do not guarantee ordering with
        respect to locking, normal memory accesses or delay() loops (i.e.
        bullets 2-5 above) but they are still guaranteed to be ordered with
        respect to other accesses from the same CPU thread to the same
        peripheral when operating on __iomem pointers mapped with the default
        I/O attributes.

 (*) readsX(), writesX():

        The readsX() and writesX() MMIO accessors are designed for accessing
        register-based, memory-mapped FIFOs residing on peripherals that are not
        capable of performing DMA. Consequently, they provide only the ordering
        guarantees of readX_relaxed() and writeX_relaxed(), as documented above.

 (*) inX(), outX():

        The inX() and outX() accessors are intended to access legacy port-mapped
        I/O peripherals, which may require special instructions on some
        architectures (notably x86). The port number of the peripheral being
        accessed is passed as an argument.

        Since many CPU architectures ultimately access these peripherals via an
        internal virtual memory mapping, the portable ordering guarantees
        provided by inX() and outX() are the same as those provided by readX()
        and writeX() respectively when accessing a mapping with the default I/O
        attributes.

        Device drivers may expect outX() to emit a non-posted write transaction
        that waits for a completion response from the I/O peripheral before
        returning. This is not guaranteed by all architectures and is therefore
        not part of the portable ordering semantics.

 (*) insX(), outsX():

        As above, the insX() and outsX() accessors provide the same ordering
        guarantees as readsX() and writesX() respectively when accessing a
        mapping with the default I/O attributes.

 (*) ioreadX(), iowriteX():

        These will perform appropriately for the type of access they're actually
        doing, be it inX()/outX() or readX()/writeX().

With the exception of the string accessors (insX(), outsX(), readsX() and
writesX()), all of the above assume that the underlying peripheral is
little-endian and will therefore perform byte-swapping operations on big-endian
architectures.


========================================
ASSUMED MINIMUM EXECUTION ORDERING MODEL
========================================

It has to be assumed that the conceptual CPU is weakly-ordered but that it will
maintain the appearance of program causality with respect to itself.  Some CPUs
(such as i386 or x86_64) are more constrained than others (such as powerpc or
frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
of arch-specific code.

This means that it must be considered that the CPU will execute its instruction
stream in any order it feels like - or even in parallel - provided that if an
instruction in the stream depends on an earlier instruction, then that
earlier instruction must be sufficiently complete[*] before the later
instruction may proceed; in other words: provided that the appearance of
causality is maintained.

 [*] Some instructions have more than one effect - such as changing the
     condition codes, changing registers or changing memory - and different
     instructions may depend on different effects.

A CPU may also discard any instruction sequence that winds up having no
ultimate effect.  For example, if two adjacent instructions both load an
immediate value into the same register, the first may be discarded.


Similarly, it has to be assumed that compiler might reorder the instruction
stream in any way it sees fit, again provided the appearance of causality is
maintained.


============================
THE EFFECTS OF THE CPU CACHE
============================

The way cached memory operations are perceived across the system is affected to
a certain extent by the caches that lie between CPUs and memory, and by the
memory coherence system that maintains the consistency of state in the system.

As far as the way a CPU interacts with another part of the system through the
caches goes, the memory system has to include the CPU's caches, and memory
barriers for the most part act at the interface between the CPU and its cache
(memory barriers logically act on the dotted line in the following diagram):

            <--- CPU --->         :       <----------- Memory ----------->
                                  :
        +--------+    +--------+  :   +--------+    +-----------+
        |        |    |        |  :   |        |    |           |    +--------+
        |  CPU   |    | Memory |  :   | CPU    |    |           |    |        |
        |  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
        |        |    | Queue  |  :   |        |    |           |--->| Memory |
        |        |    |        |  :   |        |    |           |    |        |
        +--------+    +--------+  :   +--------+    |           |    |        |
                                  :                 | Cache     |    +--------+
                                  :                 | Coherency |
                                  :                 | Mechanism |    +--------+
        +--------+    +--------+  :   +--------+    |           |    |        |
        |        |    |        |  :   |        |    |           |    |        |
        |  CPU   |    | Memory |  :   | CPU    |    |           |--->| Device |
        |  Core  |--->| Access |----->| Cache  |<-->|           |    |        |
        |        |    | Queue  |  :   |        |    |           |    |        |
        |        |    |        |  :   |        |    |           |    +--------+
        +--------+    +--------+  :   +--------+    +-----------+
                                  :
                                  :

Although any particular load or store may not actually appear outside of the
CPU that issued it since it may have been satisfied within the CPU's own cache,
it will still appear as if the full memory access had taken place as far as the
other CPUs are concerned since the cache coherency mechanisms will migrate the
cacheline over to the accessing CPU and propagate the effects upon conflict.

The CPU core may execute instructions in any order it deems fit, provided the
expected program causality appears to be maintained.  Some of the instructions
generate load and store operations which then go into the queue of memory
accesses to be performed.  The core may place these in the queue in any order
it wishes, and continue execution until it is forced to wait for an instruction
to complete.

What memory barriers are concerned with is controlling the order in which
accesses cross from the CPU side of things to the memory side of things, and
the order in which the effects are perceived to happen by the other observers
in the system.

[!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
their own loads and stores as if they had happened in program order.

[!] MMIO or other device accesses may bypass the cache system.  This depends on
the properties of the memory window through which devices are accessed and/or
the use of any special device communication instructions the CPU may have.


CACHE COHERENCY VS DMA
----------------------

Not all systems maintain cache coherency with respect to devices doing DMA.  In
such cases, a device attempting DMA may obtain stale data from RAM because
dirty cache lines may be resident in the caches of various CPUs, and may not
have been written back to RAM yet.  To deal with this, the appropriate part of
the kernel must flush the overlapping bits of cache on each CPU (and maybe
invalidate them as well).

In addition, the data DMA'd to RAM by a device may be overwritten by dirty
cache lines being written back to RAM from a CPU's cache after the device has
installed its own data, or cache lines present in the CPU's cache may simply
obscure the fact that RAM has been updated, until at such time as the cacheline
is discarded from the CPU's cache and reloaded.  To deal with this, the
appropriate part of the kernel must invalidate the overlapping bits of the
cache on each CPU.

See Documentation/core-api/cachetlb.rst for more information on cache
management.


CACHE COHERENCY VS MMIO
-----------------------

Memory mapped I/O usually takes place through memory locations that are part of
a window in the CPU's memory space that has different properties assigned than
the usual RAM directed window.

Amongst these properties is usually the fact that such accesses bypass the
caching entirely and go directly to the device buses.  This means MMIO accesses
may, in effect, overtake accesses to cached memory that were emitted earlier.
A memory barrier isn't sufficient in such a case, but rather the cache must be
flushed between the cached memory write and the MMIO access if the two are in
any way dependent.


=========================
THE THINGS CPUS GET UP TO
=========================

A programmer might take it for granted that the CPU will perform memory
operations in exactly the order specified, so that if the CPU is, for example,
given the following piece of code to execute:

        a = READ_ONCE(*A);
        WRITE_ONCE(*B, b);
        c = READ_ONCE(*C);
        d = READ_ONCE(*D);
        WRITE_ONCE(*E, e);

they would then expect that the CPU will complete the memory operation for each
instruction before moving on to the next one, leading to a definite sequence of
operations as seen by external observers in the system:

        LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.


Reality is, of course, much messier.  With many CPUs and compilers, the above
assumption doesn't hold because:

 (*) loads are more likely to need to be completed immediately to permit
     execution progress, whereas stores can often be deferred without a
     problem;

 (*) loads may be done speculatively, and the result discarded should it prove
     to have been unnecessary;

 (*) loads may be done speculatively, leading to the result having been fetched
     at the wrong time in the expected sequence of events;

 (*) the order of the memory accesses may be rearranged to promote better use
     of the CPU buses and caches;

 (*) loads and stores may be combined to improve performance when talking to
     memory or I/O hardware that can do batched accesses of adjacent locations,
     thus cutting down on transaction setup costs (memory and PCI devices may
     both be able to do this); and

 (*) the CPU's data cache may affect the ordering, and while cache-coherency
     mechanisms may alleviate this - once the store has actually hit the cache
     - there's no guarantee that the coherency management will be propagated in
     order to other CPUs.

So what another CPU, say, might actually observe from the above piece of code
is:

        LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B

        (Where "LOAD {*C,*D}" is a combined load)


However, it is guaranteed that a CPU will be self-consistent: it will see its
_own_ accesses appear to be correctly ordered, without the need for a memory
barrier.  For instance with the following code:

        U = READ_ONCE(*A);
        WRITE_ONCE(*A, V);
        WRITE_ONCE(*A, W);
        X = READ_ONCE(*A);
        WRITE_ONCE(*A, Y);
        Z = READ_ONCE(*A);

and assuming no intervention by an external influence, it can be assumed that
the final result will appear to be:

        U == the original value of *A
        X == W
        Z == Y
        *A == Y

The code above may cause the CPU to generate the full sequence of memory
accesses:

        U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A

in that order, but, without intervention, the sequence may have almost any
combination of elements combined or discarded, provided the program's view
of the world remains consistent.  Note that READ_ONCE() and WRITE_ONCE()
are -not- optional in the above example, as there are architectures
where a given CPU might reorder successive loads to the same location.
On such architectures, READ_ONCE() and WRITE_ONCE() do whatever is
necessary to prevent this, for example, on Itanium the volatile casts
used by READ_ONCE() and WRITE_ONCE() cause GCC to emit the special ld.acq
and st.rel instructions (respectively) that prevent such reordering.

The compiler may also combine, discard or defer elements of the sequence before
the CPU even sees them.

For instance:

        *A = V;
        *A = W;

may be reduced to:

        *A = W;

since, without either a write barrier or an WRITE_ONCE(), it can be
assumed that the effect of the storage of V to *A is lost.  Similarly:

        *A = Y;
        Z = *A;

may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
reduced to:

        *A = Y;
        Z = Y;

and the LOAD operation never appear outside of the CPU.


AND THEN THERE'S THE ALPHA
--------------------------

The DEC Alpha CPU is one of the most relaxed CPUs there is.  Not only that,
some versions of the Alpha CPU have a split data cache, permitting them to have
two semantically-related cache lines updated at separate times.  This is where
the address-dependency barrier really becomes necessary as this synchronises
both caches with the memory coherence system, thus making it seem like pointer
changes vs new data occur in the right order.

The Alpha defines the Linux kernel's memory model, although as of v4.15
the Linux kernel's addition of smp_mb() to READ_ONCE() on Alpha greatly
reduced its impact on the memory model.


VIRTUAL MACHINE GUESTS
----------------------

Guests running within virtual machines might be affected by SMP effects even if
the guest itself is compiled without SMP support.  This is an artifact of
interfacing with an SMP host while running an UP kernel.  Using mandatory
barriers for this use-case would be possible but is often suboptimal.

To handle this case optimally, low-level virt_mb() etc macros are available.
These have the same effect as smp_mb() etc when SMP is enabled, but generate
identical code for SMP and non-SMP systems.  For example, virtual machine guests
should use virt_mb() rather than smp_mb() when synchronizing against a
(possibly SMP) host.

These are equivalent to smp_mb() etc counterparts in all other respects,
in particular, they do not control MMIO effects: to control
MMIO effects, use mandatory barriers.


============
EXAMPLE USES
============

CIRCULAR BUFFERS
----------------

Memory barriers can be used to implement circular buffering without the need
of a lock to serialise the producer with the consumer.  See:

        Documentation/core-api/circular-buffers.rst

for details.


==========
REFERENCES
==========

Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
Digital Press)
        Chapter 5.2: Physical Address Space Characteristics
        Chapter 5.4: Caches and Write Buffers
        Chapter 5.5: Data Sharing
        Chapter 5.6: Read/Write Ordering

AMD64 Architecture Programmer's Manual Volume 2: System Programming
        Chapter 7.1: Memory-Access Ordering
        Chapter 7.4: Buffering and Combining Memory Writes

ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
        Chapter B2: The AArch64 Application Level Memory Model

IA-32 Intel Architecture Software Developer's Manual, Volume 3:
System Programming Guide
        Chapter 7.1: Locked Atomic Operations
        Chapter 7.2: Memory Ordering
        Chapter 7.4: Serializing Instructions

The SPARC Architecture Manual, Version 9
        Chapter 8: Memory Models
        Appendix D: Formal Specification of the Memory Models
        Appendix J: Programming with the Memory Models

Storage in the PowerPC (Stone and Fitzgerald)

UltraSPARC Programmer Reference Manual
        Chapter 5: Memory Accesses and Cacheability
        Chapter 15: Sparc-V9 Memory Models

UltraSPARC III Cu User's Manual
        Chapter 9: Memory Models

UltraSPARC IIIi Processor User's Manual
        Chapter 8: Memory Models

UltraSPARC Architecture 2005
        Chapter 9: Memory
        Appendix D: Formal Specifications of the Memory Models

UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
        Chapter 8: Memory Models
        Appendix F: Caches and Cache Coherency

Solaris Internals, Core Kernel Architecture, p63-68:
        Chapter 3.3: Hardware Considerations for Locks and
                        Synchronization

Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
for Kernel Programmers:
        Chapter 13: Other Memory Models

Intel Itanium Architecture Software Developer's Manual: Volume 1:
        Section 2.6: Speculation
        Section 4.4: Memory Access

```


<!-- Source LaTeX layout: \normalsize -->

---

# Memory Management Documentation

_Peios Kernel / Internals / Memory management_

> This is a guide to understanding the memory management subsystem of Linux. If you are looking for advice on simply allocating memory, see the memory_allocation. For controlling and tuning guides, see the admin guide…

<a id="rst-memory-management-documentation"></a>

This is a guide to understanding the memory management subsystem of Linux.  If you are looking for advice on simply allocating memory, see the [Memory Allocation Guide](</kernel/internals/core-api/memory-allocation.md#rst-memory-allocation>).  For controlling and tuning guides, see the [admin guide](</kernel/administration/admin-guide/mm/index.md>).

- [Physical Memory](</kernel/internals/mm/physical-memory.md>)
- [Page Tables](</kernel/internals/mm/page-tables.md>)
- [Process Addresses](</kernel/internals/mm/process-addrs.md>)
- [Boot Memory](</kernel/internals/mm/bootmem.md>)
- [Page Allocation](</kernel/internals/mm/page-allocation.md>)
- [Virtually Contiguous Memory Allocation](</kernel/internals/mm/vmalloc.md>)
- [Slab Allocation](</kernel/internals/mm/slab.md>)
- [High Memory Handling](</kernel/internals/mm/highmem.md>)
- [Page Reclaim](</kernel/internals/mm/page-reclaim.md>)
- [Swap](</kernel/internals/mm/swap.md>)
- [Swap Table](</kernel/internals/mm/swap-table.md>)
- [Page Cache](</kernel/internals/mm/page-cache.md>)
- [Shared Memory Filesystem](</kernel/internals/mm/shmfs.md>)
- [Out Of Memory Handling](</kernel/internals/mm/oom.md>)

<a id="rst-unsorted-documentation"></a>

## Unsorted Documentation

This is a collection of unsorted documents about the Linux memory management (MM) subsystem internals with different level of details ranging from notes and mailing list responses for elaborating descriptions of data structures and algorithms.  It should all be integrated nicely into the above structured documentation, or deleted if it has served its purpose.

- [Active MM](</kernel/internals/mm/active-mm.md>)
- [MEMORY ALLOCATION PROFILING](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/mm/allocation-profiling.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Architecture Page Table Helpers](</kernel/internals/mm/arch-pgtable-helpers.md>)
- [Memory Balancing](</kernel/internals/mm/balance.md>)
- [DAMON: Data Access MONitoring and Access-aware System Operations](</kernel/internals/mm/damon/index.md>)
- [Free Page Reporting](</kernel/internals/mm/free-page-reporting.md>)
- [Heterogeneous Memory Management (HMM)](</kernel/internals/mm/hmm.md>)
- [hwpoison](</kernel/internals/mm/hwpoison.md>)
- [Hugetlbfs Reservation](</kernel/internals/mm/hugetlbfs-reserv.md>)
- [Kernel Samepage Merging](</kernel/internals/mm/ksm.md>)
- [Physical Memory Model](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/mm/memory-model.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Memfd Preservation via LUO](</kernel/internals/mm/memfd-preservation.md>)
- [When do you need to notify inside page table lock ?](</kernel/internals/mm/mmu-notifier.md>)
- [Multi-Gen LRU](</kernel/internals/mm/multigen-lru.md>)
- [What is NUMA?](</kernel/internals/mm/numa.md>)
- [Overcommit Accounting](</kernel/internals/mm/overcommit-accounting.md>)
- [Page migration](</kernel/internals/mm/page-migration.md>)
- [Page fragments](</kernel/internals/mm/page-frags.md>)
- [page owner: Tracking about who allocated each page](</kernel/internals/mm/page-owner.md>)
- [Page Table Check](</kernel/internals/mm/page-table-check.md>)
- [remap_file_pages() system call](</kernel/internals/mm/remap-file-pages.md>)
- [Split page table lock](</kernel/internals/mm/split-page-table-lock.md>)
- [Transparent Hugepage Support](</kernel/internals/mm/transhuge.md>)
- [Unevictable LRU Infrastructure](</kernel/internals/mm/unevictable-lru.md>)
- [Virtually Mapped Kernel Stack Support](</kernel/internals/mm/vmalloced-kernel-stacks.md>)
- [A vmemmap diet for HugeTLB and Device DAX](</kernel/internals/mm/vmemmap-dedup.md>)
- [zsmalloc](</kernel/internals/mm/zsmalloc.md>)

---

# Active MM

_Peios Kernel / Internals / Memory management_

> Note, the mm_count refcount may no longer include the "lazy" users (running tasks with ->active_mm == mm && ->mm == NULL) on kernels with CONFIG_MMU_LAZY_TLB_REFCOUNT=n. Taking and releasing these lazy references must be done with…

<a id="rst-active-mm"></a>

Note, the mm_count refcount may no longer include the "lazy" users (running tasks with -&gt;active_mm == mm &amp;&amp; -&gt;mm == NULL) on kernels with CONFIG_MMU_LAZY_TLB_REFCOUNT=n. Taking and releasing these lazy references must be done with mmgrab_lazy_tlb() and mmdrop_lazy_tlb() helpers, which abstract this config option.



```text
List:       linux-kernel
Subject:    Re: active_mm
From:       Linus Torvalds <torvalds () transmeta ! com>
Date:       1999-07-30 21:36:24

Cc'd to linux-kernel, because I don't write explanations all that often,
and when I do I feel better about more people reading them.

On Fri, 30 Jul 1999, David Mosberger wrote:
>
> Is there a brief description someplace on how "mm" vs. "active_mm" in
> the task_struct are supposed to be used?  (My apologies if this was
> discussed on the mailing lists---I just returned from vacation and
> wasn't able to follow linux-kernel for a while).

Basically, the new setup is:

 - we have "real address spaces" and "anonymous address spaces". The
   difference is that an anonymous address space doesn't care about the
   user-level page tables at all, so when we do a context switch into an
   anonymous address space we just leave the previous address space
   active.

   The obvious use for a "anonymous address space" is any thread that
   doesn't need any user mappings - all kernel threads basically fall into
   this category, but even "real" threads can temporarily say that for
   some amount of time they are not going to be interested in user space,
   and that the scheduler might as well try to avoid wasting time on
   switching the VM state around. Currently only the old-style bdflush
   sync does that.

 - "tsk->mm" points to the "real address space". For an anonymous process,
   tsk->mm will be NULL, for the logical reason that an anonymous process
   really doesn't _have_ a real address space at all.

 - however, we obviously need to keep track of which address space we
   "stole" for such an anonymous user. For that, we have "tsk->active_mm",
   which shows what the currently active address space is.

   The rule is that for a process with a real address space (ie tsk->mm is
   non-NULL) the active_mm obviously always has to be the same as the real
   one.

   For a anonymous process, tsk->mm == NULL, and tsk->active_mm is the
   "borrowed" mm while the anonymous process is running. When the
   anonymous process gets scheduled away, the borrowed address space is
   returned and cleared.

To support all that, the "struct mm_struct" now has two counters: a
"mm_users" counter that is how many "real address space users" there are,
and a "mm_count" counter that is the number of "lazy" users (ie anonymous
users) plus one if there are any real users.

Usually there is at least one real user, but it could be that the real
user exited on another CPU while a lazy user was still active, so you do
actually get cases where you have a address space that is _only_ used by
lazy users. That is often a short-lived state, because once that thread
gets scheduled away in favour of a real thread, the "zombie" mm gets
released because "mm_count" becomes zero.

Also, a new rule is that _nobody_ ever has "init_mm" as a real MM any
more. "init_mm" should be considered just a "lazy context when no other
context is available", and in fact it is mainly used just at bootup when
no real VM has yet been created. So code that used to check

       if (current->mm == &init_mm)

should generally just do

       if (!current->mm)

instead (which makes more sense anyway - the test is basically one of "do
we have a user context", and is generally done by the page fault handler
and things like that).

Anyway, I put a pre-patch-2.3.13-1 on ftp.kernel.org just a moment ago,
because it slightly changes the interfaces to accommodate the alpha (who
would have thought it, but the alpha actually ends up having one of the
ugliest context switch codes - unlike the other architectures where the MM
and register state is separate, the alpha PALcode joins the two, and you
need to switch both together).

(From https://lore.kernel.org/lkml/Pine.LNX.4.10.9907301410280.752-100000@penguin.transmeta.com/)
```

---

# MEMORY ALLOCATION PROFILING

_Peios Kernel / Internals / Memory management_

> Low overhead (suitable for production) accounting of all memory allocations, tracked by file and line number.

<a id="rst-memory-allocation-profiling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Low overhead (suitable for production) accounting of all memory allocations, tracked by file and line number.

Usage: kconfig options: - CONFIG\_MEM\_ALLOC\_PROFILING

- CONFIG\_MEM\_ALLOC\_PROFILING\_ENABLED\_BY\_DEFAULT

- CONFIG\_MEM\_ALLOC\_PROFILING\_DEBUG adds warnings for allocations that weren't accounted because of a missing annotation

- **Boot parameter:**

  sysctl.vm.mem\_profiling=\{0\|1\|never\}\[,compressed\]

  When set to "never", memory allocation profiling overhead is minimized and it cannot be enabled at runtime (sysctl becomes read-only). When CONFIG\_MEM\_ALLOC\_PROFILING\_ENABLED\_BY\_DEFAULT=y, default value is "1". When CONFIG\_MEM\_ALLOC\_PROFILING\_ENABLED\_BY\_DEFAULT=n, default value is "never". "compressed" optional parameter will try to store page tag references in a compact format, avoiding page extensions. This results in improved performance and memory consumption, however it might fail depending on system configuration. If compression fails, a warning is issued and memory allocation profiling gets disabled.

- **sysctl:**

  /proc/sys/vm/mem\_profiling

  1: Enable memory profiling.

  0: Disable memory profiling.

  The default value depends on CONFIG\_MEM\_ALLOC\_PROFILING\_ENABLED\_BY\_DEFAULT.

  When CONFIG\_MEM\_ALLOC\_PROFILING\_DEBUG=y, this control is read-only to avoid warnings produced by allocations made while profiling is disabled and freed when it's enabled.

- **Runtime info:**

  /proc/allocinfo

Example output:



```text
root@moria-kvm:~# sort -g /proc/allocinfo|tail|numfmt --to=iec
      2.8M    22648 fs/kernfs/dir.c:615 func:__kernfs_new_node
      3.8M      953 mm/memory.c:4214 func:alloc_anon_folio
      4.0M     1010 drivers/staging/ctagmod/ctagmod.c:20 [ctagmod] func:ctagmod_start
      4.1M        4 net/netfilter/nf_conntrack_core.c:2567 func:nf_ct_alloc_hashtable
      6.0M     1532 mm/filemap.c:1919 func:__filemap_get_folio
      8.8M     2785 kernel/fork.c:307 func:alloc_thread_stack_node
       13M      234 block/blk-mq.c:3421 func:blk_mq_alloc_rqs
       14M     3520 mm/mm_init.c:2530 func:alloc_large_system_hash
       15M     3656 mm/readahead.c:247 func:page_cache_ra_unbounded
       55M     4887 mm/slub.c:2259 func:alloc_slab_page
      122M    31168 mm/page_ext.c:270 func:alloc_page_ext
```

<a id="rst-theory-of-operation"></a>

## Theory of operation

Memory allocation profiling builds off of code tagging, which is a library for declaring static structs (that typically describe a file and line number in some way, hence code tagging) and then finding and operating on them at runtime, - i.e. iterating over them to print them in debugfs/procfs.

To add accounting for an allocation call, we replace it with a macro invocation, alloc\_hooks(), that - declares a code tag - stashes a pointer to it in task\_struct - calls the real allocation function - and finally, restores the task\_struct alloc tag pointer to its previous value.

This allows for alloc\_hooks() calls to be nested, with the most recent one taking effect. This is important for allocations internal to the mm/ code that do not properly belong to the outer allocation context and should be counted separately: for example, slab object extension vectors, or when the slab allocates pages from the page allocator.

Thus, proper usage requires determining which function in an allocation call stack should be tagged. There are many helper functions that essentially wrap e.g. kmalloc() and do a little more work, then are called in multiple places; we'll generally want the accounting to happen in the callers of these helpers, not in the helpers themselves.

To fix up a given helper, for example foo(), do the following: - switch its allocation call to the \_noprof() version, e.g. kmalloc\_noprof()

- rename it to foo\_noprof()

- define a macro version of foo() like so:

  \#define foo(...) alloc\_hooks(foo\_noprof(\_\_VA\_ARGS\_\_))

It's also possible to stash a pointer to an alloc tag in your own data structures.

Do this when you're implementing a generic data structure that does allocations "on behalf of" some other code - for example, the rhashtable code. This way, instead of seeing a large line in /proc/allocinfo for rhashtable.c, we can break it out by rhashtable type.

To do so: - Hook your data structure's init function, like any other allocation function.

- Within your init function, use the convenience macro alloc\_tag\_record() to record alloc tag in your data structure.

- Then, use the following form for your allocations: alloc\_hooks\_tag(ht-&gt;your\_saved\_tag, kmalloc\_noprof(...))

---

# Architecture Page Table Helpers

_Peios Kernel / Internals / Memory management_

> Generic MM expects architectures (with MMU) to provide helpers to create, access and modify page table entries at various level for different memory functions. These page table helpers need to conform to a common semantics across…

<a id="rst-architecture-page-table-helpers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Generic MM expects architectures (with MMU) to provide helpers to create, access and modify page table entries at various level for different memory functions. These page table helpers need to conform to a common semantics across platforms. Following tables describe the expected semantics which can also be tested during boot via CONFIG_DEBUG_VM_PGTABLE option. All future changes in here or the debug test need to be in sync.

<a id="rst-pte-page-table-helpers"></a>

## PTE Page Table Helpers


<table>
<tbody>
<tr>
<td>


pte_same

</td>
<td>


Tests whether both PTE entries are the same

</td>
</tr>
<tr>
<td>


pte_present

</td>
<td>


Tests a valid mapped PTE

</td>
</tr>
<tr>
<td>


pte_young

</td>
<td>


Tests a young PTE

</td>
</tr>
<tr>
<td>


pte_dirty

</td>
<td>


Tests a dirty PTE

</td>
</tr>
<tr>
<td>


pte_write

</td>
<td>


Tests a writable PTE

</td>
</tr>
<tr>
<td>


pte_special

</td>
<td>


Tests a special PTE

</td>
</tr>
<tr>
<td>


pte_protnone

</td>
<td>


Tests a PROT_NONE PTE

</td>
</tr>
<tr>
<td>


pte_soft_dirty

</td>
<td>


Tests a soft dirty PTE

</td>
</tr>
<tr>
<td>


pte_swp_soft_dirty

</td>
<td>


Tests a soft dirty swapped PTE

</td>
</tr>
<tr>
<td>


pte_mkyoung

</td>
<td>


Creates a young PTE

</td>
</tr>
<tr>
<td>


pte_mkold

</td>
<td>


Creates an old PTE

</td>
</tr>
<tr>
<td>


pte_mkdirty

</td>
<td>


Creates a dirty PTE

</td>
</tr>
<tr>
<td>


pte_mkclean

</td>
<td>


Creates a clean PTE

</td>
</tr>
<tr>
<td>


pte_mkwrite

</td>
<td>


Creates a writable PTE of the type specified by the VMA.

</td>
</tr>
<tr>
<td>


pte_mkwrite_novma

</td>
<td>


Creates a writable PTE, of the conventional type of writable.

</td>
</tr>
<tr>
<td>


pte_wrprotect

</td>
<td>


Creates a write protected PTE

</td>
</tr>
<tr>
<td>


pte_mkspecial

</td>
<td>


Creates a special PTE

</td>
</tr>
<tr>
<td>


pte_mksoft_dirty

</td>
<td>


Creates a soft dirty PTE

</td>
</tr>
<tr>
<td>


pte_clear_soft_dirty

</td>
<td>


Clears a soft dirty PTE

</td>
</tr>
<tr>
<td>


pte_swp_mksoft_dirty

</td>
<td>


Creates a soft dirty swapped PTE

</td>
</tr>
<tr>
<td>


pte_swp_clear_soft_dirty

</td>
<td>


Clears a soft dirty swapped PTE

</td>
</tr>
<tr>
<td>


pte_mknotpresent

</td>
<td>


Invalidates a mapped PTE

</td>
</tr>
<tr>
<td>


ptep_clear

</td>
<td>


Clears a PTE

</td>
</tr>
<tr>
<td>


ptep_get_and_clear

</td>
<td>


Clears and returns PTE

</td>
</tr>
<tr>
<td>


ptep_get_and_clear_full

</td>
<td>


Clears and returns PTE (batched PTE unmap)

</td>
</tr>
<tr>
<td>


ptep_test_and_clear_young

</td>
<td>


Clears young from a PTE

</td>
</tr>
<tr>
<td>


ptep_set_wrprotect

</td>
<td>


Converts into a write protected PTE

</td>
</tr>
<tr>
<td>


ptep_set_access_flags

</td>
<td>


Converts into a more permissive PTE

</td>
</tr>
</tbody>
</table>

<a id="rst-pmd-page-table-helpers"></a>

## PMD Page Table Helpers


<table>
<tbody>
<tr>
<td>


pmd_same

</td>
<td>


Tests whether both PMD entries are the same

</td>
</tr>
<tr>
<td>


pmd_bad

</td>
<td>


Tests a non-table mapped PMD

</td>
</tr>
<tr>
<td>


pmd_leaf

</td>
<td>


Tests a leaf mapped PMD

</td>
</tr>
<tr>
<td>


pmd_trans_huge

</td>
<td>


Tests a Transparent Huge Page (THP) at PMD

</td>
</tr>
<tr>
<td>


pmd_present

</td>
<td>


Tests whether pmd_page() points to valid memory

</td>
</tr>
<tr>
<td>


pmd_young

</td>
<td>


Tests a young PMD

</td>
</tr>
<tr>
<td>


pmd_dirty

</td>
<td>


Tests a dirty PMD

</td>
</tr>
<tr>
<td>


pmd_write

</td>
<td>


Tests a writable PMD

</td>
</tr>
<tr>
<td>


pmd_special

</td>
<td>


Tests a special PMD

</td>
</tr>
<tr>
<td>


pmd_protnone

</td>
<td>


Tests a PROT_NONE PMD

</td>
</tr>
<tr>
<td>


pmd_soft_dirty

</td>
<td>


Tests a soft dirty PMD

</td>
</tr>
<tr>
<td>


pmd_swp_soft_dirty

</td>
<td>


Tests a soft dirty swapped PMD

</td>
</tr>
<tr>
<td>


pmd_mkyoung

</td>
<td>


Creates a young PMD

</td>
</tr>
<tr>
<td>


pmd_mkold

</td>
<td>


Creates an old PMD

</td>
</tr>
<tr>
<td>


pmd_mkdirty

</td>
<td>


Creates a dirty PMD

</td>
</tr>
<tr>
<td>


pmd_mkclean

</td>
<td>


Creates a clean PMD

</td>
</tr>
<tr>
<td>


pmd_mkwrite

</td>
<td>


Creates a writable PMD of the type specified by the VMA.

</td>
</tr>
<tr>
<td>


pmd_mkwrite_novma

</td>
<td>


Creates a writable PMD, of the conventional type of writable.

</td>
</tr>
<tr>
<td>


pmd_wrprotect

</td>
<td>


Creates a write protected PMD

</td>
</tr>
<tr>
<td>


pmd_mkspecial

</td>
<td>


Creates a special PMD

</td>
</tr>
<tr>
<td>


pmd_mksoft_dirty

</td>
<td>


Creates a soft dirty PMD

</td>
</tr>
<tr>
<td>


pmd_clear_soft_dirty

</td>
<td>


Clears a soft dirty PMD

</td>
</tr>
<tr>
<td>


pmd_swp_mksoft_dirty

</td>
<td>


Creates a soft dirty swapped PMD

</td>
</tr>
<tr>
<td>


pmd_swp_clear_soft_dirty

</td>
<td>


Clears a soft dirty swapped PMD

</td>
</tr>
<tr>
<td>


pmd_mkinvalid

</td>
<td>


Invalidates a present PMD; do not call for non-present PMD \[1\]

</td>
</tr>
<tr>
<td>


pmd_set_huge

</td>
<td>


Creates a PMD huge mapping

</td>
</tr>
<tr>
<td>


pmd_clear_huge

</td>
<td>


Clears a PMD huge mapping

</td>
</tr>
<tr>
<td>


pmdp_get_and_clear

</td>
<td>


Clears a PMD

</td>
</tr>
<tr>
<td>


pmdp_get_and_clear_full

</td>
<td>


Clears a PMD

</td>
</tr>
<tr>
<td>


pmdp_test_and_clear_young

</td>
<td>


Clears young from a PMD

</td>
</tr>
<tr>
<td>


pmdp_set_wrprotect

</td>
<td>


Converts into a write protected PMD

</td>
</tr>
<tr>
<td>


pmdp_set_access_flags

</td>
<td>


Converts into a more permissive PMD

</td>
</tr>
</tbody>
</table>

<a id="rst-pud-page-table-helpers"></a>

## PUD Page Table Helpers


<table>
<tbody>
<tr>
<td>


pud_same

</td>
<td>


Tests whether both PUD entries are the same

</td>
</tr>
<tr>
<td>


pud_bad

</td>
<td>


Tests a non-table mapped PUD

</td>
</tr>
<tr>
<td>


pud_leaf

</td>
<td>


Tests a leaf mapped PUD

</td>
</tr>
<tr>
<td>


pud_trans_huge

</td>
<td>


Tests a Transparent Huge Page (THP) at PUD

</td>
</tr>
<tr>
<td>


pud_present

</td>
<td>


Tests a valid mapped PUD

</td>
</tr>
<tr>
<td>


pud_young

</td>
<td>


Tests a young PUD

</td>
</tr>
<tr>
<td>


pud_dirty

</td>
<td>


Tests a dirty PUD

</td>
</tr>
<tr>
<td>


pud_write

</td>
<td>


Tests a writable PUD

</td>
</tr>
<tr>
<td>


pud_mkyoung

</td>
<td>


Creates a young PUD

</td>
</tr>
<tr>
<td>


pud_mkold

</td>
<td>


Creates an old PUD

</td>
</tr>
<tr>
<td>


pud_mkdirty

</td>
<td>


Creates a dirty PUD

</td>
</tr>
<tr>
<td>


pud_mkclean

</td>
<td>


Creates a clean PUD

</td>
</tr>
<tr>
<td>


pud_mkwrite

</td>
<td>


Creates a writable PUD

</td>
</tr>
<tr>
<td>


pud_wrprotect

</td>
<td>


Creates a write protected PUD

</td>
</tr>
<tr>
<td>


pud_mkinvalid

</td>
<td>


Invalidates a present PUD; do not call for non-present PUD \[1\]

</td>
</tr>
<tr>
<td>


pud_set_huge

</td>
<td>


Creates a PUD huge mapping

</td>
</tr>
<tr>
<td>


pud_clear_huge

</td>
<td>


Clears a PUD huge mapping

</td>
</tr>
<tr>
<td>


pudp_get_and_clear

</td>
<td>


Clears a PUD

</td>
</tr>
<tr>
<td>


pudp_get_and_clear_full

</td>
<td>


Clears a PUD

</td>
</tr>
<tr>
<td>


pudp_test_and_clear_young

</td>
<td>


Clears young from a PUD

</td>
</tr>
<tr>
<td>


pudp_set_wrprotect

</td>
<td>


Converts into a write protected PUD

</td>
</tr>
<tr>
<td>


pudp_set_access_flags

</td>
<td>


Converts into a more permissive PUD

</td>
</tr>
</tbody>
</table>

<a id="rst-hugetlb-page-table-helpers"></a>

## HugeTLB Page Table Helpers


<table>
<tbody>
<tr>
<td>


pte_huge

</td>
<td>


Tests a HugeTLB

</td>
</tr>
<tr>
<td>


arch_make_huge_pte

</td>
<td>


Creates a HugeTLB

</td>
</tr>
<tr>
<td>


huge_pte_dirty

</td>
<td>


Tests a dirty HugeTLB

</td>
</tr>
<tr>
<td>


huge_pte_write

</td>
<td>


Tests a writable HugeTLB

</td>
</tr>
<tr>
<td>


huge_pte_mkdirty

</td>
<td>


Creates a dirty HugeTLB

</td>
</tr>
<tr>
<td>


huge_pte_mkwrite

</td>
<td>


Creates a writable HugeTLB

</td>
</tr>
<tr>
<td>


huge_pte_wrprotect

</td>
<td>


Creates a write protected HugeTLB

</td>
</tr>
<tr>
<td>


huge_ptep_get_and_clear

</td>
<td>


Clears a HugeTLB

</td>
</tr>
<tr>
<td>


huge_ptep_set_wrprotect

</td>
<td>


Converts into a write protected HugeTLB

</td>
</tr>
<tr>
<td colspan="2">


huge_ptep_set_access_flags  \| Converts into a more permissive HugeTLB

</td>
</tr>
</tbody>
</table>

<a id="rst-swap-page-table-helpers"></a>

## SWAP Page Table Helpers


<table>
<tbody>
<tr>
<td>


\__pte_to_swp_entry

</td>
<td colspan="2">


Creates a swp_entry_t (arch) from a swap PTE

</td>
</tr>
<tr>
<td>


\__swp_entry_to_pte

</td>
<td colspan="2">


Creates a swap PTE from a swp_entry_t (arch)

</td>
</tr>
<tr>
<td>


\__pmd_to_swp_entry

</td>
<td colspan="2">


Creates a swp_entry_t (arch) from a swap PMD

</td>
</tr>
<tr>
<td>


\__swp_entry_to_pmd

</td>
<td colspan="2">


Creates a swap PMD from a swp_entry_t (arch)

</td>
</tr>
<tr>
<td colspan="3">


is_migration_entry        \| Tests a migration (read or write) swapped entry

</td>
</tr>
<tr>
<td colspan="2">


is_writable_migration_entry

</td>
<td>


Tests a write migration swapped entry

</td>
</tr>
<tr>
<td colspan="2">


make_readable_migration_entry

</td>
<td>


Creates a read migration swapped entry

</td>
</tr>
<tr>
<td colspan="2">


make_writable_migration_entry

</td>
<td>


Creates a write migration swapped entry

</td>
</tr>
</tbody>
</table>

\[1\] [https://lore.kernel.org/linux-mm/20181017020930.GN30832@redhat.com/](<https://lore.kernel.org/linux-mm/20181017020930.GN30832@redhat.com/>)

---

# Memory Balancing

_Peios Kernel / Internals / Memory management_

> Started Jan 2000 by Kanoj Sarcar <kanoj@sgi.com>

<a id="rst-memory-balancing"></a>

Started Jan 2000 by Kanoj Sarcar &lt;[kanoj@sgi.com](<mailto:kanoj@sgi.com>)&gt;

Memory balancing is needed for \!\__GFP_HIGH and \!\__GFP_KSWAPD_RECLAIM as well as for non \__GFP_IO allocations.

The first reason why a caller may avoid reclaim is that the caller can not sleep due to holding a spinlock or is in interrupt context. The second may be that the caller is willing to fail the allocation without incurring the overhead of page reclaim. This may happen for opportunistic high-order allocation requests that have order-0 fallback options. In such cases, the caller may also wish to avoid waking kswapd.

\__GFP_IO allocation requests are made to prevent file system deadlocks.

In the absence of non sleepable allocation requests, it seems detrimental to be doing balancing. Page reclamation can be kicked off lazily, that is, only when needed (aka zone free memory is 0), instead of making it a proactive process.

That being said, the kernel should try to fulfill requests for direct mapped pages from the direct mapped pool, instead of falling back on the dma pool, so as to keep the dma pool filled for dma requests (atomic or not). A similar argument applies to highmem and direct mapped pages. OTOH, if there is a lot of free dma pages, it is preferable to satisfy regular memory requests by allocating one from the dma pool, instead of incurring the overhead of regular zone balancing.

In 2.2, memory balancing/page reclamation would kick off only when the \_total\_ number of free pages fell below 1/64 th of total memory. With the right ratio of dma and regular memory, it is quite possible that balancing would not be done even when the dma zone was completely empty. 2.2 has been running production machines of varying memory sizes, and seems to be doing fine even with the presence of this problem. In 2.3, due to HIGHMEM, this problem is aggravated.

In 2.3, zone balancing can be done in one of two ways: depending on the zone size (and possibly of the size of lower class zones), we can decide at init time how many free pages we should aim for while balancing any zone. The good part is, while balancing, we do not need to look at sizes of lower class zones, the bad part is, we might do too frequent balancing due to ignoring possibly lower usage in the lower class zones. Also, with a slight change in the allocation routine, it is possible to reduce the memclass() macro to be a simple equality.

Another possible solution is that we balance only when the free memory of a zone \_and\_ all its lower class zones falls below 1/64th of the total memory in the zone and its lower class zones. This fixes the 2.2 balancing problem, and stays as close to 2.2 behavior as possible. Also, the balancing algorithm works the same way on the various architectures, which have different numbers and types of zones. If we wanted to get fancy, we could assign different weights to free pages in different zones in the future.

Note that if the size of the regular zone is huge compared to dma zone, it becomes less significant to consider the free dma pages while deciding whether to balance the regular zone. The first solution becomes more attractive then.

The appended patch implements the second solution. It also "fixes" two problems: first, kswapd is woken up as in 2.2 on low memory conditions for non-sleepable allocations. Second, the HIGHMEM zone is also balanced, so as to give a fighting chance for replace_with_highmem() to get a HIGHMEM page, as well as to ensure that HIGHMEM allocations do not fall back into regular zone. This also makes sure that HIGHMEM pages are not leaked (for example, in situations where a HIGHMEM page is in the swapcache but is not being used by anyone)

kswapd also needs to know about the zones it should balance. kswapd is primarily needed in a situation where balancing can not be done, probably because all allocation requests are coming from intr context and all process contexts are sleeping. For 2.3, kswapd does not really need to balance the highmem zone, since intr context does not request highmem pages. kswapd looks at the zone_wake_kswapd field in the zone structure to decide whether a zone needs balancing.

Page stealing from process memory and shm is done if stealing the page would alleviate memory pressure on any zone in the page's node that has fallen below its watermark.

watermark\[WMARK_MIN/WMARK_LOW/WMARK_HIGH\]/low_on_memory/zone_wake_kswapd: These are per-zone fields, used to determine when a zone needs to be balanced. When the number of pages falls below watermark\[WMARK_MIN\], the hysteric field low_on_memory gets set. This stays set till the number of free pages becomes watermark\[WMARK_HIGH\]. When low_on_memory is set, page allocation requests will try to free some pages in the zone (providing GFP_WAIT is set in the request). Orthogonal to this, is the decision to poke kswapd to free some zone pages. That decision is not hysteresis based, and is done when the number of free pages is below watermark\[WMARK_LOW\]; in which case zone_wake_kswapd is also set.

(Good) Ideas that I have heard:

1. Dynamic experience should influence balancing: number of failed requests for a zone can be tracked and fed into the balancing scheme ([jalvo@mbay.net](<mailto:jalvo@mbay.net>))

2. Implement a replace_with_highmem()-like replace_with_regular() to preserve dma pages. ([lkd@tantalophile.demon.co.uk](<mailto:lkd@tantalophile.demon.co.uk>))

---

# Boot Memory

_Peios Kernel / Internals / Memory management_

> Reference for Boot Memory.

<a id="rst-boot-memory"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Free Page Reporting

_Peios Kernel / Internals / Memory management_

> Free page reporting is an API by which a device can register to receive lists of pages that are currently unused by the system. This is useful in the case of virtualization where a guest is then able to use this data to notify the…

<a id="rst-free-page-reporting"></a>

Free page reporting is an API by which a device can register to receive lists of pages that are currently unused by the system. This is useful in the case of virtualization where a guest is then able to use this data to notify the hypervisor that it is no longer using certain pages in memory.

For the driver, typically a balloon driver, to use of this functionality it will allocate and initialize a page_reporting_dev_info structure. The field within the structure it will populate is the "report" function pointer used to process the scatterlist. It must also guarantee that it can handle at least PAGE_REPORTING_CAPACITY worth of scatterlist entries per call to the function. A call to page_reporting_register will register the page reporting interface with the reporting framework assuming no other page reporting devices are already registered.

Once registered the page reporting API will begin reporting batches of pages to the driver. The API will start reporting pages 2 seconds after the interface is registered and will continue to do so 2 seconds after any page of a sufficiently high order is freed.

Pages reported will be stored in the scatterlist passed to the reporting function with the final entry having the end bit set in entry nent - 1. While pages are being processed by the report function they will not be accessible to the allocator. Once the report function has been completed the pages will be returned to the free area from which they were obtained.

Prior to removing a driver that is making use of free page reporting it is necessary to call page_reporting_unregister to have the page_reporting_dev_info structure that is currently in use by free page reporting removed. Doing this will prevent further reports from being issued via the interface. If another driver or the same driver is registered it is possible for it to resume where the previous driver had left off in terms of reporting free pages.

Alexander Duyck, Dec 04, 2019

---

# High Memory Handling

_Peios Kernel / Internals / Memory management_

> By: Peter Zijlstra <a.p.zijlstra@chello.nl>

<a id="rst-high-memory-handling"></a>

By: Peter Zijlstra &lt;[a.p.zijlstra@chello.nl](<mailto:a.p.zijlstra@chello.nl>)&gt;

<a id="rst-contents"></a>



<a id="rst-what-is-high-memory"></a>

## What Is High Memory?

High memory (highmem) is used when the size of physical memory approaches or exceeds the maximum size of virtual memory.  At that point it becomes impossible for the kernel to keep all of the available physical memory mapped at all times.  This means the kernel needs to start using temporary mappings of the pieces of physical memory that it wants to access.

The part of (physical) memory not covered by a permanent mapping is what we refer to as 'highmem'.  There are various architecture dependent constraints on where exactly that border lies.

In the i386 arch, for example, we choose to map the kernel into every process's VM space so that we don't have to pay the full TLB invalidation costs for kernel entry/exit.  This means the available virtual memory space (4GiB on i386) has to be divided between user and kernel space.

The traditional split for architectures using this approach is 3:1, 3GiB for userspace and the top 1GiB for kernel space:



```text
+--------+ 0xffffffff
| Kernel |
+--------+ 0xc0000000
|        |
| User   |
|        |
+--------+ 0x00000000
```

This means that the kernel can at most map 1GiB of physical memory at any one time, but because we need virtual address space for other things - including temporary maps to access the rest of the physical memory - the actual direct map will typically be less (usually around \~896MiB).

Other architectures that have mm context tagged TLBs can have separate kernel and user maps.  Some hardware (like some ARMs), however, have limited virtual space when they use mm context tags.

<a id="rst-temporary-virtual-mappings"></a>

## Temporary Virtual Mappings

The kernel contains several ways of creating temporary mappings. The following list shows them in order of preference of use.

- kmap_local_page(), kmap_local_folio() - These functions are used to create short term mappings. They can be invoked from any context (including interrupts) but the mappings can only be used in the context which acquired them. The only differences between them consist in the first taking a pointer to a struct page and the second taking a pointer to struct folio and the byte offset within the folio which identifies the page.

  These functions should always be used, whereas kmap_atomic() and kmap() have been deprecated.

  These mappings are thread-local and CPU-local, meaning that the mapping can only be accessed from within this thread and the thread is bound to the CPU while the mapping is active. Although preemption is never disabled by this function, the CPU can not be unplugged from the system via CPU-hotplug until the mapping is disposed.

  It's valid to take pagefaults in a local kmap region, unless the context in which the local mapping is acquired does not allow it for other reasons.

  As said, pagefaults and preemption are never disabled. There is no need to disable preemption because, when context switches to a different task, the maps of the outgoing task are saved and those of the incoming one are restored.

  kmap_local_page(), as well as kmap_local_folio() always returns valid virtual kernel addresses and it is assumed that kunmap_local() will never fail.

  On CONFIG_HIGHMEM=n kernels and for low memory pages they return the virtual address of the direct mapping. Only real highmem pages are temporarily mapped. Therefore, users may call a plain page_address() for pages which are known to not come from ZONE_HIGHMEM. However, it is always safe to use kmap_local\_\{page,folio\}() / kunmap_local().

  While they are significantly faster than kmap(), for the highmem case they come with restrictions about the pointers validity. Contrary to kmap() mappings, the local mappings are only valid in the context of the caller and cannot be handed to other contexts. This implies that users must be absolutely sure to keep the use of the return address local to the thread which mapped it.

  Most code can be designed to use thread local mappings. User should therefore try to design their code to avoid the use of kmap() by mapping pages in the same thread the address will be used and prefer kmap_local_page() or kmap_local_folio().

  Nesting kmap_local_page() and kmap_atomic() mappings is allowed to a certain extent (up to KMAP_TYPE_NR) but their invocations have to be strictly ordered because the map implementation is stack based. See kmap_local_page() kdocs (included in the "Functions" section) for details on how to manage nested mappings.

- kmap_atomic(). This function has been deprecated; use kmap_local_page().

  NOTE: Conversions to kmap_local_page() must take care to follow the mapping restrictions imposed on kmap_local_page(). Furthermore, the code between calls to kmap_atomic() and kunmap_atomic() may implicitly depend on the side effects of atomic mappings, i.e. disabling page faults or preemption, or both. In that case, explicit calls to pagefault_disable() or preempt_disable() or both must be made in conjunction with the use of kmap_local_page().

  \[Legacy documentation\]

  This permits a very short duration mapping of a single page.  Since the mapping is restricted to the CPU that issued it, it performs well, but the issuing task is therefore required to stay on that CPU until it has finished, lest some other task displace its mappings.

  kmap_atomic() may also be used by interrupt contexts, since it does not sleep and the callers too may not sleep until after kunmap_atomic() is called.

  Each call of kmap_atomic() in the kernel creates a non-preemptible section and disable pagefaults. This could be a source of unwanted latency. Therefore users should prefer kmap_local_page() instead of kmap_atomic().

  It is assumed that k\[un\]map_atomic() won't fail.

- kmap(). This function has been deprecated; use kmap_local_page().

  NOTE: Conversions to kmap_local_page() must take care to follow the mapping restrictions imposed on kmap_local_page(). In particular, it is necessary to make sure that the kernel virtual memory pointer is only valid in the thread that obtained it.

  \[Legacy documentation\]

  This should be used to make short duration mapping of a single page with no restrictions on preemption or migration. It comes with an overhead as mapping space is restricted and protected by a global lock for synchronization. When mapping is no longer needed, the address that the page was mapped to must be released with kunmap().

  Mapping changes must be propagated across all the CPUs. kmap() also requires global TLB invalidation when the kmap's pool wraps and it might block when the mapping space is fully utilized until a slot becomes available. Therefore, kmap() is only callable from preemptible context.

  All the above work is necessary if a mapping must last for a relatively long time but the bulk of high-memory mappings in the kernel are short-lived and only used in one place. This means that the cost of kmap() is mostly wasted in such cases. kmap() was not intended for long term mappings but it has morphed in that direction and its use is strongly discouraged in newer code and the set of the preceding functions should be preferred.

  On 64-bit systems, calls to kmap_local_page(), kmap_atomic() and kmap() have no real work to do because a 64-bit address space is more than sufficient to address all the physical memory whose pages are permanently mapped.

- vmap().  This can be used to make a long duration mapping of multiple physical pages into a contiguous virtual space.  It needs global synchronization to unmap.

<a id="rst-cost-of-temporary-mappings"></a>

## Cost of Temporary Mappings

The cost of creating temporary mappings can be quite high.  The arch has to manipulate the kernel's page tables, the data TLB and/or the MMU's registers.

If CONFIG_HIGHMEM is not set, then the kernel will try and create a mapping simply with a bit of arithmetic that will convert the page struct address into a pointer to the page contents rather than juggling mappings about.  In such a case, the unmap operation may be a null operation.

If CONFIG_MMU is not set, then there can be no temporary mappings and no highmem.  In such a case, the arithmetic approach will also be used.

<a id="rst-i386-pae"></a>

## i386 PAE

The i386 arch, under some circumstances, will permit you to stick up to 64GiB of RAM into your 32-bit machine.  This has a number of consequences:

- Linux needs a page-frame structure for each page in the system and the pageframes need to live in the permanent mapping, which means:

- you can have 896M/sizeof(struct page) page-frames at most; with struct page being 32-bytes that would end up being something in the order of 112G worth of pages; the kernel, however, needs to store more than just page-frames in that memory...

- PAE makes your page tables larger - which slows the system down as more data has to be accessed to traverse in TLB fills and the like.  One advantage is that PAE has more PTE bits and can provide advanced features like NX and PAT.

The general recommendation is that you don't use more than 8GiB on a 32-bit machine - although more might work for you and your workload, you're pretty much on your own - don't expect kernel developers to really care much if things come apart.

<a id="rst-functions"></a>

## Functions


#### <a id="c-kmap"></a>`kmap()`

```c
void * kmap(struct page *page)
```

Map a page for long term usage

**Parameters**

- `struct page *page`: Pointer to the page to be mapped

**Return**

The virtual address of the mapping

**Description**

Can only be invoked from preemptible task context because on 32bit
systems with CONFIG_HIGHMEM enabled this function might sleep.

For systems with CONFIG_HIGHMEM=n and for pages in the low memory area
this returns the virtual address of the direct kernel mapping.

The returned virtual address is globally visible and valid up to the
point where it is unmapped via [`kunmap()`](#c-kunmap). The pointer can be handed to
other contexts.

For highmem pages on 32bit systems this can be slow as the mapping space
is limited and protected by a global lock. In case that there is no
mapping slot available the function blocks until a slot is released via
[`kunmap()`](#c-kunmap).

#### <a id="c-kunmap"></a>`kunmap()`

```c
void kunmap(const struct page *page)
```

Unmap the virtual address mapped by [`kmap()`](#c-kmap)

**Parameters**

- `const struct page *page`: Pointer to the page which was mapped by [`kmap()`](#c-kmap)

**Description**

Counterpart to [`kmap()`](#c-kmap). A NOOP for CONFIG_HIGHMEM=n and for mappings of
pages in the low memory area.

#### <a id="c-kmap_to_page"></a>`kmap_to_page()`

```c
struct page * kmap_to_page(void *addr)
```

Get the page for a kmap'ed address

**Parameters**

- `void *addr`: The address to look up

**Return**

The page which is mapped to **addr**.

#### <a id="c-kmap_flush_unused"></a>`kmap_flush_unused()`

```c
void kmap_flush_unused(void)
```

Flush all unused kmap mappings in order to remove stray mappings

**Parameters**

- `void`: no arguments

#### <a id="c-kmap_local_page"></a>`kmap_local_page()`

```c
void * kmap_local_page(const struct page *page)
```

Map a page for temporary usage

**Parameters**

- `const struct page *page`: Pointer to the page to be mapped

**Return**

The virtual address of the mapping

**Description**

Can be invoked from any context, including interrupts.

Requires careful handling when nesting multiple mappings because the map
management is stack based. The unmap has to be in the reverse order of
the map operation:

addr1 = kmap_local_page(page1);
addr2 = kmap_local_page(page2);
\...
kunmap_local(addr2);
kunmap_local(addr1);

Unmapping addr1 before addr2 is invalid and causes malfunction.

Contrary to [`kmap()`](#c-kmap) mappings the mapping is only valid in the context of
the caller and cannot be handed to other contexts.

On CONFIG_HIGHMEM=n kernels and for low memory pages this returns the
virtual address of the direct mapping. Only real highmem pages are
temporarily mapped.

While [`kmap_local_page()`](#c-kmap_local_page) is significantly faster than [`kmap()`](#c-kmap) for the highmem
case it comes with restrictions about the pointer validity.

On HIGHMEM enabled systems mapping a highmem page has the side effect of
disabling migration in order to keep the virtual address stable across
preemption. No caller of [`kmap_local_page()`](#c-kmap_local_page) can rely on this side effect.

#### <a id="c-kmap_local_folio"></a>`kmap_local_folio()`

```c
void * kmap_local_folio(const struct folio *folio, size_t offset)
```

Map a page in this folio for temporary usage

**Parameters**

- `const struct folio *folio`: The folio containing the page.
- `size_t offset`: The byte offset within the folio which identifies the page.

**Description**

Requires careful handling when nesting multiple mappings because the map
management is stack based. The unmap has to be in the reverse order of
the map operation:

```text
addr1 = kmap_local_folio(folio1, offset1);
addr2 = kmap_local_folio(folio2, offset2);
...
kunmap_local(addr2);
kunmap_local(addr1);
```

Unmapping addr1 before addr2 is invalid and causes malfunction.

Contrary to [`kmap()`](#c-kmap) mappings the mapping is only valid in the context of
the caller and cannot be handed to other contexts.

On CONFIG_HIGHMEM=n kernels and for low memory pages this returns the
virtual address of the direct mapping. Only real highmem pages are
temporarily mapped.

While it is significantly faster than [`kmap()`](#c-kmap) for the highmem case it
comes with restrictions about the pointer validity.

On HIGHMEM enabled systems mapping a highmem page has the side effect of
disabling migration in order to keep the virtual address stable across
preemption. No caller of [`kmap_local_folio()`](#c-kmap_local_folio) can rely on this side effect.

**Context**

Can be invoked from any context.

**Return**

The virtual address of **offset**.

#### <a id="c-kmap_atomic"></a>`kmap_atomic()`

```c
void * kmap_atomic(const struct page *page)
```

Atomically map a page for temporary usage - Deprecated!

**Parameters**

- `const struct page *page`: Pointer to the page to be mapped

**Return**

The virtual address of the mapping

**Description**

In fact a wrapper around [`kmap_local_page()`](#c-kmap_local_page) which also disables pagefaults
and, depending on PREEMPT_RT configuration, also CPU migration and
preemption. Therefore users should not count on the latter two side effects.

Mappings should always be released by [`kunmap_atomic()`](#c-kunmap_atomic).

Do not use in new code. Use [`kmap_local_page()`](#c-kmap_local_page) instead.

It is used in atomic context when code wants to access the contents of a
page that might be allocated from high memory (see __GFP_HIGHMEM), for
example a page in the pagecache.  The API has two functions, and they
can be used in a manner similar to the following:

```text
// Find the page of interest.
struct page *page = find_get_page(mapping, offset);

// Gain access to the contents of that page.
void *vaddr = kmap_atomic(page);

// Do something to the contents of that page.
memset(vaddr, 0, PAGE_SIZE);

// Unmap that page.
kunmap_atomic(vaddr);
```

Note that the [`kunmap_atomic()`](#c-kunmap_atomic) call takes the result of the [`kmap_atomic()`](#c-kmap_atomic)
call, not the argument.

If you need to map two pages because you want to copy from one page to
another you need to keep the kmap_atomic calls strictly nested, like:

vaddr1 = kmap_atomic(page1);
vaddr2 = kmap_atomic(page2);

memcpy(vaddr1, vaddr2, PAGE_SIZE);

kunmap_atomic(vaddr2);
kunmap_atomic(vaddr1);

#### <a id="c-clear_user_page"></a>`clear_user_page()`

```c
void clear_user_page(void *addr, unsigned long vaddr, struct page *page)
```

clear a page to be mapped to user space

**Parameters**

- `void *addr`: the address of the page
- `unsigned long vaddr`: the address of the user mapping
- `struct page *page`: the page

**Description**

We condition the definition of [`clear_user_page()`](#c-clear_user_page) on the architecture
not having a custom [`clear_user_highpage()`](#c-clear_user_highpage). That's because if there
is some special flushing needed for [`clear_user_highpage()`](#c-clear_user_highpage) then it
is likely that [`clear_user_page()`](#c-clear_user_page) also needs some magic. And, since
our only caller is the generic [`clear_user_highpage()`](#c-clear_user_highpage), not defining
is not much of a loss.

#### <a id="c-clear_user_pages"></a>`clear_user_pages()`

```c
void clear_user_pages(void *addr, unsigned long vaddr, struct page *page, unsigned int npages)
```

clear a page range to be mapped to user space

**Parameters**

- `void *addr`: start address
- `unsigned long vaddr`: start address of the user mapping
- `struct page *page`: start page
- `unsigned int npages`: number of pages

**Description**

Assumes that the region (**addr**, +**npages**) has been validated
already so this does no exception handling.

If the architecture provides a [`clear_user_page()`](#c-clear_user_page), use that;
otherwise, we can safely use [`clear_pages()`](/kernel/internals/core-api/mm-api.md#c-clear_pages).

#### <a id="c-clear_user_highpage"></a>`clear_user_highpage()`

```c
void clear_user_highpage(struct page *page, unsigned long vaddr)
```

clear a page to be mapped to user space

**Parameters**

- `struct page *page`: start page
- `unsigned long vaddr`: start address of the user mapping

**Description**

With !CONFIG_HIGHMEM this (and the `copy_user_highpage()` below) will
be plain [`clear_user_page()`](#c-clear_user_page) (and `copy_user_page()`).

#### <a id="c-clear_user_highpages"></a>`clear_user_highpages()`

```c
void clear_user_highpages(struct page *page, unsigned long vaddr, unsigned int npages)
```

clear a page range to be mapped to user space

**Parameters**

- `struct page *page`: start page
- `unsigned long vaddr`: start address of the user mapping
- `unsigned int npages`: number of pages

**Description**

Assumes that all the pages in the region (**page**, +**npages**) are valid
so this does no exception handling.

#### <a id="c-vma_alloc_zeroed_movable_folio"></a>`vma_alloc_zeroed_movable_folio()`

```c
struct folio * vma_alloc_zeroed_movable_folio(struct vm_area_struct *vma, unsigned long vaddr)
```

Allocate a zeroed page for a VMA.

**Parameters**

- `struct vm_area_struct *vma`: The VMA the page is to be allocated for.
- `unsigned long vaddr`: The virtual address the page will be inserted into.

**Description**

This function will allocate a page suitable for inserting into this
VMA at this virtual address.  It may be allocated from highmem or
the movable zone.  An architecture may provide its own implementation.

**Return**

A folio containing one allocated and zeroed page or NULL if
we are out of memory.

#### <a id="c-memcpy_from_folio"></a>`memcpy_from_folio()`

```c
void memcpy_from_folio(char *to, struct folio *folio, size_t offset, size_t len)
```

Copy a range of bytes from a folio.

**Parameters**

- `char *to`: The memory to copy to.
- `struct folio *folio`: The folio to read from.
- `size_t offset`: The first byte in the folio to read.
- `size_t len`: The number of bytes to copy.

#### <a id="c-memcpy_to_folio"></a>`memcpy_to_folio()`

```c
void memcpy_to_folio(struct folio *folio, size_t offset, const char *from, size_t len)
```

Copy a range of bytes to a folio.

**Parameters**

- `struct folio *folio`: The folio to write to.
- `size_t offset`: The first byte in the folio to store to.
- `const char *from`: The memory to copy from.
- `size_t len`: The number of bytes to copy.

#### <a id="c-folio_zero_tail"></a>`folio_zero_tail()`

```c
void * folio_zero_tail(struct folio *folio, size_t offset, void *kaddr)
```

Zero the tail of a folio.

**Parameters**

- `struct folio *folio`: The folio to zero.
- `size_t offset`: The byte offset in the folio to start zeroing at.
- `void *kaddr`: The address the folio is currently mapped to.

**Description**

If you have already used [`kmap_local_folio()`](#c-kmap_local_folio) to map a folio, written
some data to it and now need to zero the end of the folio (and flush
the dcache), you can use this function.  If you do not have the
folio kmapped (eg the folio has been partially populated by DMA),
use [`folio_zero_range()`](#c-folio_zero_range) or [`folio_zero_segment()`](#c-folio_zero_segment) instead.

**Return**

An address which can be passed to [`kunmap_local()`](#c-kunmap_local).

#### <a id="c-folio_fill_tail"></a>`folio_fill_tail()`

```c
void folio_fill_tail(struct folio *folio, size_t offset, const char *from, size_t len)
```

Copy some data to a folio and pad with zeroes.

**Parameters**

- `struct folio *folio`: The destination folio.
- `size_t offset`: The offset into **folio** at which to start copying.
- `const char *from`: The data to copy.
- `size_t len`: How many bytes of data to copy.

**Description**

This function is most useful for filesystems which support inline data.
When they want to copy data from the inode into the page cache, this
function does everything for them.  It supports large folios even on
HIGHMEM configurations.

#### <a id="c-memcpy_from_file_folio"></a>`memcpy_from_file_folio()`

```c
size_t memcpy_from_file_folio(char *to, struct folio *folio, loff_t pos, size_t len)
```

Copy some bytes from a file folio.

**Parameters**

- `char *to`: The destination buffer.
- `struct folio *folio`: The folio to copy from.
- `loff_t pos`: The position in the file.
- `size_t len`: The maximum number of bytes to copy.

**Description**

Copy up to **len** bytes from this folio.  This may be limited by PAGE_SIZE
if the folio comes from HIGHMEM, and by the size of the folio.

**Return**

The number of bytes copied from the folio.

#### <a id="c-folio_zero_segments"></a>`folio_zero_segments()`

```c
void folio_zero_segments(struct folio *folio, size_t start1, size_t xend1, size_t start2, size_t xend2)
```

Zero two byte ranges in a folio.

**Parameters**

- `struct folio *folio`: The folio to write to.
- `size_t start1`: The first byte to zero.
- `size_t xend1`: One more than the last byte in the first range.
- `size_t start2`: The first byte to zero in the second range.
- `size_t xend2`: One more than the last byte in the second range.

#### <a id="c-folio_zero_segment"></a>`folio_zero_segment()`

```c
void folio_zero_segment(struct folio *folio, size_t start, size_t xend)
```

Zero a byte range in a folio.

**Parameters**

- `struct folio *folio`: The folio to write to.
- `size_t start`: The first byte to zero.
- `size_t xend`: One more than the last byte to zero.

#### <a id="c-folio_zero_range"></a>`folio_zero_range()`

```c
void folio_zero_range(struct folio *folio, size_t start, size_t length)
```

Zero a byte range in a folio.

**Parameters**

- `struct folio *folio`: The folio to write to.
- `size_t start`: The first byte to zero.
- `size_t length`: The number of bytes to zero.

#### <a id="c-folio_release_kmap"></a>`folio_release_kmap()`

```c
void folio_release_kmap(struct folio *folio, void *addr)
```

Unmap a folio and drop a refcount.

**Parameters**

- `struct folio *folio`: The folio to release.
- `void *addr`: The address previously returned by a call to [`kmap_local_folio()`](#c-kmap_local_folio).

**Description**

It is common, eg in directory handling to kmap a folio.  This function
unmaps the folio and drops the refcount that was being held to keep the
folio alive while we accessed it.



#### <a id="c-kmap_high"></a>`kmap_high()`

```c
void * kmap_high(struct page *page)
```

map a highmem page into memory

**Parameters**

- `struct page *page`: `struct page` to map

**Description**

Returns the page's virtual memory address.

We cannot call this from interrupts, as it may block.

#### <a id="c-kmap_high_get"></a>`kmap_high_get()`

```c
void * kmap_high_get(const struct page *page)
```

pin a highmem page into memory

**Parameters**

- `const struct page *page`: `struct page` to pin

**Description**

Returns the page's current virtual memory address, or NULL if no mapping
exists.  If and only if a non null address is returned then a
matching call to [`kunmap_high()`](#c-kunmap_high) is necessary.

This can be called from any context.

#### <a id="c-kunmap_high"></a>`kunmap_high()`

```c
void kunmap_high(const struct page *page)
```

unmap a highmem page into memory

**Parameters**

- `const struct page *page`: `struct page` to unmap

**Description**

If ARCH_NEEDS_KMAP_HIGH_GET is not defined then this may be called
only from user context.

#### <a id="c-page_address"></a>`page_address()`

```c
void * page_address(const struct page *page)
```

get the mapped virtual address of a page

**Parameters**

- `const struct page *page`: `struct page` to get the virtual address of

**Description**

Returns the page's virtual address.

#### <a id="c-set_page_address"></a>`set_page_address()`

```c
void set_page_address(struct page *page, void *virtual)
```

set a page's virtual address

**Parameters**

- `struct page *page`: `struct page` to set
- `void *virtual`: virtual address to use



#### <a id="c-kunmap_atomic"></a>`kunmap_atomic()`

```c
kunmap_atomic(__addr)
```

Unmap the virtual address mapped by [`kmap_atomic()`](#c-kmap_atomic) - deprecated!

**Parameters**

- `__addr`: Virtual address to be unmapped

**Description**

Unmaps an address previously mapped by [`kmap_atomic()`](#c-kmap_atomic) and re-enables
pagefaults. Depending on PREEMP_RT configuration, re-enables also
migration and preemption. Users should not count on these side effects.

Mappings should be unmapped in the reverse order that they were mapped.
See [`kmap_local_page()`](#c-kmap_local_page) for details on nesting.

**__addr** can be any address within the mapped page, so there is no need
to subtract any offset that has been added. In contrast to [`kunmap()`](#c-kunmap),
this function takes the address returned from [`kmap_atomic()`](#c-kmap_atomic), not the
page passed to it. The compiler will warn you if you pass the page.

#### <a id="c-kunmap_local"></a>`kunmap_local()`

```c
kunmap_local(__addr)
```

Unmap a page mapped via [`kmap_local_page()`](#c-kmap_local_page).

**Parameters**

- `__addr`: An address within the page mapped

**Description**

**__addr** can be any address within the mapped page.  Commonly it is the
address return from [`kmap_local_page()`](#c-kmap_local_page), but it can also include offsets.

Unmapping should be done in the reverse order of the mapping.  See
[`kmap_local_page()`](#c-kmap_local_page) for details.

---

# Heterogeneous Memory Management (HMM)

_Peios Kernel / Internals / Memory management_

> Provide infrastructure and helpers to integrate non-conventional memory (device memory like GPU on board memory) into regular kernel path, with the cornerstone of this being specialized struct page for such memory (see sections 5 to 7 of…

<a id="rst-heterogeneous-memory-management-hmm"></a>

Provide infrastructure and helpers to integrate non-conventional memory (device memory like GPU on board memory) into regular kernel path, with the cornerstone of this being specialized struct page for such memory (see sections 5 to 7 of this document).

HMM also provides optional helpers for SVM (Share Virtual Memory), i.e., allowing a device to transparently access program addresses coherently with the CPU meaning that any valid pointer on the CPU is also a valid pointer for the device. This is becoming mandatory to simplify the use of advanced heterogeneous computing where GPU, DSP, or FPGA are used to perform various computations on behalf of a process.

This document is divided as follows: in the first section I expose the problems related to using device specific memory allocators. In the second section, I expose the hardware limitations that are inherent to many platforms. The third section gives an overview of the HMM design. The fourth section explains how CPU page-table mirroring works and the purpose of HMM in this context. The fifth section deals with how device memory is represented inside the kernel. Finally, the last section presents a new migration helper that allows leveraging the device DMA engine.

<a id="rst-contents"></a>



<a id="rst-problems-of-using-a-device-specific-memory-allocator"></a>

## Problems of using a device specific memory allocator

Devices with a large amount of on board memory (several gigabytes) like GPUs have historically managed their memory through dedicated driver specific APIs. This creates a disconnect between memory allocated and managed by a device driver and regular application memory (private anonymous, shared memory, or regular file backed memory). From here on I will refer to this aspect as split address space. I use shared address space to refer to the opposite situation: i.e., one in which any application memory region can be used by a device transparently.

Split address space happens because devices can only access memory allocated through a device specific API. This implies that all memory objects in a program are not equal from the device point of view which complicates large programs that rely on a wide set of libraries.

Concretely, this means that code that wants to leverage devices like GPUs needs to copy objects between generically allocated memory (malloc, mmap private, mmap share) and memory allocated through the device driver API (this still ends up with an mmap but of the device file).

For flat data sets (array, grid, image, ...) this isn't too hard to achieve but for complex data sets (list, tree, ...) it's hard to get right. Duplicating a complex data set needs to re-map all the pointer relations between each of its elements. This is error prone and programs get harder to debug because of the duplicate data set and addresses.

Split address space also means that libraries cannot transparently use data they are getting from the core program or another library and thus each library might have to duplicate its input data set using the device specific memory allocator. Large projects suffer from this and waste resources because of the various memory copies.

Duplicating each library API to accept as input or output memory allocated by each device specific allocator is not a viable option. It would lead to a combinatorial explosion in the library entry points.

Finally, with the advance of high level language constructs (in C++ but in other languages too) it is now possible for the compiler to leverage GPUs and other devices without programmer knowledge. Some compiler identified patterns are only doable with a shared address space. It is also more reasonable to use a shared address space for all other patterns.

<a id="rst-i-o-bus-device-memory-characteristics"></a>

## I/O bus, device memory characteristics

I/O buses cripple shared address spaces due to a few limitations. Most I/O buses only allow basic memory access from device to main memory; even cache coherency is often optional. Access to device memory from a CPU is even more limited. More often than not, it is not cache coherent.

If we only consider the PCIE bus, then a device can access main memory (often through an IOMMU) and be cache coherent with the CPUs. However, it only allows a limited set of atomic operations from the device on main memory. This is worse in the other direction: the CPU can only access a limited range of the device memory and cannot perform atomic operations on it. Thus device memory cannot be considered the same as regular memory from the kernel point of view.

Another crippling factor is the limited bandwidth (\~32GBytes/s with PCIE 4.0 and 16 lanes). This is 33 times less than the fastest GPU memory (1 TBytes/s). The final limitation is latency. Access to main memory from the device has an order of magnitude higher latency than when the device accesses its own memory.

Some platforms are developing new I/O buses or additions/modifications to PCIE to address some of these limitations (OpenCAPI, CCIX). They mainly allow two-way cache coherency between CPU and device and allow all atomic operations the architecture supports. Sadly, not all platforms are following this trend and some major architectures are left without hardware solutions to these problems.

So for shared address space to make sense, not only must we allow devices to access any memory but we must also permit any memory to be migrated to device memory while the device is using it (blocking CPU access while it happens).

<a id="rst-shared-address-space-and-migration"></a>

## Shared address space and migration

HMM intends to provide two main features. The first one is to share the address space by duplicating the CPU page table in the device page table so the same address points to the same physical memory for any valid main memory address in the process address space.

To achieve this, HMM offers a set of helpers to populate the device page table while keeping track of CPU page table updates. Device page table updates are not as easy as CPU page table updates. To update the device page table, you must allocate a buffer (or use a pool of pre-allocated buffers) and write GPU specific commands in it to perform the update (unmap, cache invalidations, and flush, ...). This cannot be done through common code for all devices. Hence why HMM provides helpers to factor out everything that can be while leaving the hardware specific details to the device driver.

The second mechanism HMM provides is a new kind of ZONE_DEVICE memory that allows allocating a struct page for each page of device memory. Those pages are special because the CPU cannot map them. However, they allow migrating main memory to device memory using existing migration mechanisms and everything looks like a page that is swapped out to disk from the CPU point of view. Using a struct page gives the easiest and cleanest integration with existing mm mechanisms. Here again, HMM only provides helpers, first to hotplug new ZONE_DEVICE memory for the device memory and second to perform migration. Policy decisions of what and when to migrate is left to the device driver.

Note that any CPU access to a device page triggers a page fault and a migration back to main memory. For example, when a page backing a given CPU address A is migrated from a main memory page to a device page, then any CPU access to address A triggers a page fault and initiates a migration back to main memory.

With these two features, HMM not only allows a device to mirror process address space and keeps both CPU and device page tables synchronized, but also leverages device memory by migrating the part of the data set that is actively being used by the device.

<a id="rst-address-space-mirroring-implementation-and-api"></a>

## Address space mirroring implementation and API

Address space mirroring's main objective is to allow duplication of a range of CPU page table into a device page table; HMM helps keep both synchronized. A device driver that wants to mirror a process address space must start with the registration of a mmu_interval_notifier:



```text
int mmu_interval_notifier_insert(struct mmu_interval_notifier *interval_sub,
                                 struct mm_struct *mm, unsigned long start,
                                 unsigned long length,
                                 const struct mmu_interval_notifier_ops *ops);
```

During the ops-&gt;invalidate() callback the device driver must perform the update action to the range (mark range read only, or fully unmap, etc.). The device must complete the update before the driver callback returns.

When the device driver wants to populate a range of virtual addresses, it can use:



```text
int hmm_range_fault(struct hmm_range *range);
```

It will trigger a page fault on missing or read-only entries if write access is requested (see below). Page faults use the generic mm page fault code path just like a CPU page fault. The usage pattern is:



```text
int driver_populate_range(...)
{
     struct hmm_range range;
     ...

     range.notifier = &interval_sub;
     range.start = ...;
     range.end = ...;
     range.hmm_pfns = ...;

     if (!mmget_not_zero(interval_sub->notifier.mm))
         return -EFAULT;

again:
     range.notifier_seq = mmu_interval_read_begin(&interval_sub);
     mmap_read_lock(mm);
     ret = hmm_range_fault(&range);
     if (ret) {
         mmap_read_unlock(mm);
         if (ret == -EBUSY)
                goto again;
         return ret;
     }
     mmap_read_unlock(mm);

     take_lock(driver->update);
     if (mmu_interval_read_retry(&ni, range.notifier_seq) {
         release_lock(driver->update);
         goto again;
     }

     /* Use pfns array content to update device page table,
      * under the update lock */

     release_lock(driver->update);
     return 0;
}
```

The driver-&gt;update lock is the same lock that the driver takes inside its invalidate() callback. That lock must be held before calling mmu_interval_read_retry() to avoid any race with a concurrent CPU page table update.

<a id="rst-leverage-default-flags-and-pfn-flags-mask"></a>

## Leverage default_flags and pfn_flags_mask

The hmm_range struct has 2 fields, default_flags and pfn_flags_mask, that specify fault or snapshot policy for the whole range instead of having to set them for each entry in the pfns array.

For instance if the device driver wants pages for a range with at least read permission, it sets:



```text
range->default_flags = HMM_PFN_REQ_FAULT;
range->pfn_flags_mask = 0;
```

and calls hmm_range_fault() as described above. This will fill fault all pages in the range with at least read permission.

Now let's say the driver wants to do the same except for one page in the range for which it wants to have write permission. Now driver set:



```text
range->default_flags = HMM_PFN_REQ_FAULT;
range->pfn_flags_mask = HMM_PFN_REQ_WRITE;
range->pfns[index_of_write] = HMM_PFN_REQ_WRITE;
```

With this, HMM will fault in all pages with at least read (i.e., valid) and for the address == range-&gt;start + (index_of_write &lt;&lt; PAGE_SHIFT) it will fault with write permission i.e., if the CPU pte does not have write permission set then HMM will call handle_mm_fault().

After hmm_range_fault completes the flag bits are set to the current state of the page tables, ie HMM_PFN_VALID \| HMM_PFN_WRITE will be set if the page is writable.

<a id="rst-represent-and-manage-device-memory-from-core-kernel-point-of-view"></a>

## Represent and manage device memory from core kernel point of view

Several different designs were tried to support device memory. The first one used a device specific data structure to keep information about migrated memory and HMM hooked itself in various places of mm code to handle any access to addresses that were backed by device memory. It turns out that this ended up replicating most of the fields of struct page and also needed many kernel code paths to be updated to understand this new kind of memory.

Most kernel code paths never try to access the memory behind a page but only care about struct page contents. Because of this, HMM switched to directly using struct page for device memory which left most kernel code paths unaware of the difference. We only need to make sure that no one ever tries to map those pages from the CPU side.

<a id="rst-migration-to-and-from-device-memory"></a>

## Migration to and from device memory

Because the CPU cannot access device memory directly, the device driver must use hardware DMA or device specific load/store instructions to migrate data. The migrate_vma_setup(), migrate_vma_pages(), and migrate_vma_finalize() functions are designed to make drivers easier to write and to centralize common code across drivers.

Before migrating pages to device private memory, special device private `struct page` needs to be created. These will be used as special "swap" page table entries so that a CPU process will fault if it tries to access a page that has been migrated to device private memory.

These can be allocated and freed with:



```text
struct resource *res;
struct dev_pagemap pagemap;

res = request_free_mem_region(&iomem_resource, /* number of bytes */,
                              "name of driver resource");
pagemap.type = MEMORY_DEVICE_PRIVATE;
pagemap.range.start = res->start;
pagemap.range.end = res->end;
pagemap.nr_range = 1;
pagemap.ops = &device_devmem_ops;
memremap_pages(&pagemap, numa_node_id());

memunmap_pages(&pagemap);
release_mem_region(pagemap.range.start, range_len(&pagemap.range));
```

There are also devm_request_free_mem_region(), devm_memremap_pages(), devm_memunmap_pages(), and devm_release_mem_region() when the resources can be tied to a `struct device`.

The overall migration steps are similar to migrating NUMA pages within system memory (see [Documentation/mm/page_migration.rst](/kernel/internals/mm/page-migration.md)) but the steps are split between device driver specific code and shared common code:

1. `mmap_read_lock()`

   The device driver has to pass a `struct vm_area_struct` to migrate_vma_setup() so the mmap_read_lock() or mmap_write_lock() needs to be held for the duration of the migration.

2. `migrate_vma_setup(struct migrate_vma *args)`

   The device driver initializes the `struct migrate_vma` fields and passes the pointer to migrate_vma_setup(). The `args->flags` field is used to filter which source pages should be migrated. For example, setting `MIGRATE_VMA_SELECT_SYSTEM` will only migrate system memory and `MIGRATE_VMA_SELECT_DEVICE_PRIVATE` will only migrate pages residing in device private memory. If the latter flag is set, the `args->pgmap_owner` field is used to identify device private pages owned by the driver. This avoids trying to migrate device private pages residing in other devices. Currently only anonymous private VMA ranges can be migrated to or from system memory and device private memory.

   One of the first steps migrate_vma_setup() does is to invalidate other device's MMUs with the `mmu_notifier_invalidate_range_start(()` and `mmu_notifier_invalidate_range_end()` calls around the page table walks to fill in the `args->src` array with PFNs to be migrated. The `invalidate_range_start()` callback is passed a `struct mmu_notifier_range` with the `event` field set to `MMU_NOTIFY_MIGRATE` and the `owner` field set to the `args->pgmap_owner` field passed to migrate_vma_setup(). This allows the device driver to skip the invalidation callback and only invalidate device private MMU mappings that are actually migrating. This is explained more in the next section.

   While walking the page tables, a `pte_none()` or `is_zero_pfn()` entry results in a valid "zero" PFN stored in the `args->src` array. This lets the driver allocate device private memory and clear it instead of copying a page of zeros. Valid PTE entries to system memory or device private struct pages will be locked with `lock_page()`, isolated from the LRU (if system memory since device private pages are not on the LRU), unmapped from the process, and a special migration PTE is inserted in place of the original PTE. migrate_vma_setup() also clears the `args->dst` array.

3. The device driver allocates destination pages and copies source pages to destination pages.

   The driver checks each `src` entry to see if the `MIGRATE_PFN_MIGRATE` bit is set and skips entries that are not migrating. The device driver can also choose to skip migrating a page by not filling in the `dst` array for that page.

   The driver then allocates either a device private struct page or a system memory page, locks the page with `lock_page()`, and fills in the `dst` array entry with:



   ```text
   dst[i] = migrate_pfn(page_to_pfn(dpage));
   ```

   Now that the driver knows that this page is being migrated, it can invalidate device private MMU mappings and copy device private memory to system memory or another device private page. The core Linux kernel handles CPU page table invalidations so the device driver only has to invalidate its own MMU mappings.

   The driver can use `migrate_pfn_to_page(src[i])` to get the `struct page` of the source and either copy the source page to the destination or clear the destination device private memory if the pointer is `NULL` meaning the source page was not populated in system memory.

4. `migrate_vma_pages()`

   This step is where the migration is actually "committed".

   If the source page was a `pte_none()` or `is_zero_pfn()` page, this is where the newly allocated page is inserted into the CPU's page table. This can fail if a CPU thread faults on the same page. However, the page table is locked and only one of the new pages will be inserted. The device driver will see that the `MIGRATE_PFN_MIGRATE` bit is cleared if it loses the race.

   If the source page was locked, isolated, etc. the source `struct page` information is now copied to destination `struct page` finalizing the migration on the CPU side.

5. Device driver updates device MMU page tables for pages still migrating, rolling back pages not migrating.

   If the `src` entry still has `MIGRATE_PFN_MIGRATE` bit set, the device driver can update the device MMU and set the write enable bit if the `MIGRATE_PFN_WRITE` bit is set.

6. `migrate_vma_finalize()`

   This step replaces the special migration page table entry with the new page's page table entry and releases the reference to the source and destination `struct page`.

7. `mmap_read_unlock()`

   The lock can now be released.

<a id="rst-exclusive-access-memory"></a>

## Exclusive access memory

Some devices have features such as atomic PTE bits that can be used to implement atomic access to system memory. To support atomic operations to a shared virtual memory page such a device needs access to that page which is exclusive of any userspace access from the CPU. The `make_device_exclusive()` function can be used to make a memory range inaccessible from userspace.

This replaces all mappings for pages in the given range with special swap entries. Any attempt to access the swap entry results in a fault which is resolved by replacing the entry with the original mapping. A driver gets notified that the mapping has been changed by MMU notifiers, after which point it will no longer have exclusive access to the page. Exclusive access is guaranteed to last until the driver drops the page lock and page reference, at which point any CPU faults on the page may proceed as described.

<a id="rst-memory-cgroup-memcg-and-rss-accounting"></a>

## Memory cgroup (memcg) and rss accounting

For now, device memory is accounted as any regular page in rss counters (either anonymous if device page is used for anonymous, file if device page is used for file backed page, or shmem if device page is used for shared memory). This is a deliberate choice to keep existing applications, that might start using device memory without knowing about it, running unimpacted.

A drawback is that the OOM killer might kill an application using a lot of device memory and not a lot of regular system memory and thus not freeing much system memory. We want to gather more real world experience on how applications and system react under memory pressure in the presence of device memory before deciding to account device memory differently.

Same decision was made for memory cgroup. Device memory pages are accounted against same memory cgroup a regular page would be accounted to. This does simplify migration to and from device memory. This also means that migration back from device memory to regular memory cannot fail because it would go above memory cgroup limit. We might revisit this choice later on once we get more experience in how device memory is used and its impact on memory resource control.

Note that device memory can never be pinned by a device driver nor through GUP and thus such memory is always free upon process exit. Or when last reference is dropped in case of shared memory or file backed memory.

---

# Hugetlbfs Reservation

_Peios Kernel / Internals / Memory management_

> Huge pages as described at Documentation/admin-guide/mm/hugetlbpage.rst are typically preallocated for application use. These huge pages are instantiated in a task's address space at page fault time if the VMA indicates huge pages are to…

<a id="rst-hugetlbfs-reservation"></a>

<a id="rst-overview"></a>

## Overview

Huge pages as described at [Documentation/admin-guide/mm/hugetlbpage.rst](/kernel/administration/admin-guide/mm/hugetlbpage.md) are typically preallocated for application use.  These huge pages are instantiated in a task's address space at page fault time if the VMA indicates huge pages are to be used.  If no huge page exists at page fault time, the task is sent a SIGBUS and often dies an unhappy death.  Shortly after huge page support was added, it was determined that it would be better to detect a shortage of huge pages at mmap() time.  The idea is that if there were not enough huge pages to cover the mapping, the mmap() would fail.  This was first done with a simple check in the code at mmap() time to determine if there were enough free huge pages to cover the mapping.  Like most things in the kernel, the code has evolved over time.  However, the basic idea was to 'reserve' huge pages at mmap() time to ensure that huge pages would be available for page faults in that mapping.  The description below attempts to describe how huge page reserve processing is done in the v4.10 kernel.

<a id="rst-audience"></a>

## Audience

This description is primarily targeted at kernel developers who are modifying hugetlbfs code.

<a id="rst-the-data-structures"></a>

## The Data Structures

- **resv_huge_pages**

  This is a global (per-hstate) count of reserved huge pages.  Reserved huge pages are only available to the task which reserved them. Therefore, the number of huge pages generally available is computed as (`free_huge_pages - resv_huge_pages`).

- **Reserve Map**

  A reserve map is described by the structure:



  ```text
  struct resv_map {
          struct kref refs;
          spinlock_t lock;
          struct list_head regions;
          long adds_in_progress;
          struct list_head region_cache;
          long region_cache_count;
  };
  ```

  There is one reserve map for each huge page mapping in the system. The regions list within the resv_map describes the regions within the mapping.  A region is described as:



  ```text
  struct file_region {
          struct list_head link;
          long from;
          long to;
  };
  ```

  The 'from' and 'to' fields of the file region structure are huge page indices into the mapping.  Depending on the type of mapping, a region in the reserv_map may indicate reservations exist for the range, or reservations do not exist.

- **Flags for MAP_PRIVATE Reservations**

  These are stored in the bottom bits of the reservation map pointer.

  - **`#define HPAGE_RESV_OWNER    (1UL << 0)`**

    Indicates this task is the owner of the reservations associated with the mapping.

  - **`#define HPAGE_RESV_UNMAPPED (1UL << 1)`**

    Indicates task originally mapping this range (and creating reserves) has unmapped a page from this task (the child) due to a failed COW.

- **Page Flags**

  The PagePrivate page flag is used to indicate that a huge page reservation must be restored when the huge page is freed.  More details will be discussed in the "Freeing huge pages" section.

<a id="rst-reservation-map-location-private-or-shared"></a>

## Reservation Map Location (Private or Shared)

A huge page mapping or segment is either private or shared.  If private, it is typically only available to a single address space (task).  If shared, it can be mapped into multiple address spaces (tasks).  The location and semantics of the reservation map is significantly different for the two types of mappings.  Location differences are:

- For private mappings, the reservation map hangs off the VMA structure. Specifically, vma-&gt;vm_private_data.  This reserve map is created at the time the mapping (mmap(MAP_PRIVATE)) is created.

- For shared mappings, the reservation map hangs off the inode.  Specifically, inode-&gt;i_mapping-&gt;private_data.  Since shared mappings are always backed by files in the hugetlbfs filesystem, the hugetlbfs code ensures each inode contains a reservation map.  As a result, the reservation map is allocated when the inode is created.

<a id="rst-creating-reservations"></a>

## Creating Reservations

Reservations are created when a huge page backed shared memory segment is created (shmget(SHM_HUGETLB)) or a mapping is created via mmap(MAP_HUGETLB). These operations result in a call to the routine hugetlb_reserve_pages():



```text
int hugetlb_reserve_pages(struct inode *inode,
                          long from, long to,
                          struct vm_area_struct *vma,
                          vm_flags_t vm_flags)
```

The first thing hugetlb_reserve_pages() does is check if the NORESERVE flag was specified in either the shmget() or mmap() call.  If NORESERVE was specified, then this routine returns immediately as no reservations are desired.

The arguments 'from' and 'to' are huge page indices into the mapping or underlying file.  For shmget(), 'from' is always 0 and 'to' corresponds to the length of the segment/mapping.  For mmap(), the offset argument could be used to specify the offset into the underlying file.  In such a case, the 'from' and 'to' arguments have been adjusted by this offset.

One of the big differences between PRIVATE and SHARED mappings is the way in which reservations are represented in the reservation map.

- For shared mappings, an entry in the reservation map indicates a reservation exists or did exist for the corresponding page.  As reservations are consumed, the reservation map is not modified.

- For private mappings, the lack of an entry in the reservation map indicates a reservation exists for the corresponding page.  As reservations are consumed, entries are added to the reservation map.  Therefore, the reservation map can also be used to determine which reservations have been consumed.

For private mappings, hugetlb_reserve_pages() creates the reservation map and hangs it off the VMA structure.  In addition, the HPAGE_RESV_OWNER flag is set to indicate this VMA owns the reservations.

The reservation map is consulted to determine how many huge page reservations are needed for the current mapping/segment.  For private mappings, this is always the value (to - from).  However, for shared mappings it is possible that some reservations may already exist within the range (to - from).  See the section [Reservation Map Modifications](<#rst-resv-map-modifications>) for details on how this is accomplished.

The mapping may be associated with a subpool.  If so, the subpool is consulted to ensure there is sufficient space for the mapping.  It is possible that the subpool has set aside reservations that can be used for the mapping.  See the section [Subpool Reservations](<#rst-sub-pool-resv>) for more details.

After consulting the reservation map and subpool, the number of needed new reservations is known.  The routine hugetlb_acct_memory() is called to check for and take the requested number of reservations.  hugetlb_acct_memory() calls into routines that potentially allocate and adjust surplus page counts. However, within those routines the code is simply checking to ensure there are enough free huge pages to accommodate the reservation.  If there are, the global reservation count resv_huge_pages is adjusted something like the following:



```text
if (resv_needed <= (resv_huge_pages - free_huge_pages))
        resv_huge_pages += resv_needed;
```

Note that the global lock hugetlb_lock is held when checking and adjusting these counters.

If there were enough free huge pages and the global count resv_huge_pages was adjusted, then the reservation map associated with the mapping is modified to reflect the reservations.  In the case of a shared mapping, a file_region will exist that includes the range 'from' - 'to'.  For private mappings, no modifications are made to the reservation map as lack of an entry indicates a reservation exists.

If hugetlb_reserve_pages() was successful, the global reservation count and reservation map associated with the mapping will be modified as required to ensure reservations exist for the range 'from' - 'to'.

<a id="rst-consuming-reservations-allocating-a-huge-page"></a>
<a id="rst-consume-resv"></a>

## Consuming Reservations/Allocating a Huge Page

Reservations are consumed when huge pages associated with the reservations are allocated and instantiated in the corresponding mapping.  The allocation is performed within the routine alloc_hugetlb_folio():



```text
struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
                             unsigned long addr, int avoid_reserve)
```

alloc_hugetlb_folio is passed a VMA pointer and a virtual address, so it can consult the reservation map to determine if a reservation exists.  In addition, alloc_hugetlb_folio takes the argument avoid_reserve which indicates reserves should not be used even if it appears they have been set aside for the specified address.  The avoid_reserve argument is most often used in the case of Copy on Write and Page Migration where additional copies of an existing page are being allocated.

The helper routine vma_needs_reservation() is called to determine if a reservation exists for the address within the mapping(vma).  See the section [Reservation Map Helper Routines](<#rst-resv-map-helpers>) for detailed information on what this routine does. The value returned from vma_needs_reservation() is generally 0 or 1.  0 if a reservation exists for the address, 1 if no reservation exists. If a reservation does not exist, and there is a subpool associated with the mapping the subpool is consulted to determine if it contains reservations. If the subpool contains reservations, one can be used for this allocation. However, in every case the avoid_reserve argument overrides the use of a reservation for the allocation.  After determining whether a reservation exists and can be used for the allocation, the routine dequeue_huge_page_vma() is called.  This routine takes two arguments related to reservations:

- avoid_reserve, this is the same value/argument passed to alloc_hugetlb_folio().

- chg, even though this argument is of type long only the values 0 or 1 are passed to dequeue_huge_page_vma.  If the value is 0, it indicates a reservation exists (see the section "Memory Policy and Reservations" for possible issues).  If the value is 1, it indicates a reservation does not exist and the page must be taken from the global free pool if possible.

The free lists associated with the memory policy of the VMA are searched for a free page.  If a page is found, the value free_huge_pages is decremented when the page is removed from the free list.  If there was a reservation associated with the page, the following adjustments are made:



```text
SetPagePrivate(page);   /* Indicates allocating this page consumed
                         * a reservation, and if an error is
                         * encountered such that the page must be
                         * freed, the reservation will be restored. */
resv_huge_pages--;      /* Decrement the global reservation count */
```

Note, if no huge page can be found that satisfies the VMA's memory policy an attempt will be made to allocate one using the buddy allocator.  This brings up the issue of surplus huge pages and overcommit which is beyond the scope reservations.  Even if a surplus page is allocated, the same reservation based adjustments as above will be made: SetPagePrivate(page) and resv_huge_pages--.

After obtaining a new hugetlb folio, (folio)-&gt;\_hugetlb_subpool is set to the value of the subpool associated with the page if it exists.  This will be used for subpool accounting when the folio is freed.

The routine vma_commit_reservation() is then called to adjust the reserve map based on the consumption of the reservation.  In general, this involves ensuring the page is represented within a file_region structure of the region map.  For shared mappings where the reservation was present, an entry in the reserve map already existed so no change is made.  However, if there was no reservation in a shared mapping or this was a private mapping a new entry must be created.

It is possible that the reserve map could have been changed between the call to vma_needs_reservation() at the beginning of alloc_hugetlb_folio() and the call to vma_commit_reservation() after the folio was allocated.  This would be possible if hugetlb_reserve_pages was called for the same page in a shared mapping.  In such cases, the reservation count and subpool free page count will be off by one.  This rare condition can be identified by comparing the return value from vma_needs_reservation and vma_commit_reservation.  If such a race is detected, the subpool and global reserve counts are adjusted to compensate.  See the section [Reservation Map Helper Routines](<#rst-resv-map-helpers>) for more information on these routines.

<a id="rst-instantiate-huge-pages"></a>

## Instantiate Huge Pages

After huge page allocation, the page is typically added to the page tables of the allocating task.  Before this, pages in a shared mapping are added to the page cache and pages in private mappings are added to an anonymous reverse mapping.  In both cases, the PagePrivate flag is cleared.  Therefore, when a huge page that has been instantiated is freed no adjustment is made to the global reservation count (resv_huge_pages).

<a id="rst-freeing-huge-pages"></a>

## Freeing Huge Pages

Huge pages are freed by free_huge_folio().  It is only passed a pointer to the folio as it is called from the generic MM code.  When a huge page is freed, reservation accounting may need to be performed.  This would be the case if the page was associated with a subpool that contained reserves, or the page is being freed on an error path where a global reserve count must be restored.

The page-&gt;private field points to any subpool associated with the page. If the PagePrivate flag is set, it indicates the global reserve count should be adjusted (see the section [Consuming Reservations/Allocating a Huge Page](<#rst-consume-resv>) for information on how these are set).

The routine first calls hugepage_subpool_put_pages() for the page.  If this routine returns a value of 0 (which does not equal the value passed 1) it indicates reserves are associated with the subpool, and this newly free page must be used to keep the number of subpool reserves above the minimum size. Therefore, the global resv_huge_pages counter is incremented in this case.

If the PagePrivate flag was set in the page, the global resv_huge_pages counter will always be incremented.

<a id="rst-subpool-reservations"></a>
<a id="rst-sub-pool-resv"></a>

## Subpool Reservations

There is a struct hstate associated with each huge page size.  The hstate tracks all huge pages of the specified size.  A subpool represents a subset of pages within a hstate that is associated with a mounted hugetlbfs filesystem.

When a hugetlbfs filesystem is mounted a min_size option can be specified which indicates the minimum number of huge pages required by the filesystem. If this option is specified, the number of huge pages corresponding to min_size are reserved for use by the filesystem.  This number is tracked in the min_hpages field of a struct hugepage_subpool.  At mount time, hugetlb_acct_memory(min_hpages) is called to reserve the specified number of huge pages.  If they can not be reserved, the mount fails.

The routines hugepage_subpool_get/put_pages() are called when pages are obtained from or released back to a subpool.  They perform all subpool accounting, and track any reservations associated with the subpool. hugepage_subpool_get/put_pages are passed the number of huge pages by which to adjust the subpool 'used page' count (down for get, up for put).  Normally, they return the same value that was passed or an error if not enough pages exist in the subpool.

However, if reserves are associated with the subpool a return value less than the passed value may be returned.  This return value indicates the number of additional global pool adjustments which must be made.  For example, suppose a subpool contains 3 reserved huge pages and someone asks for 5. The 3 reserved pages associated with the subpool can be used to satisfy part of the request.  But, 2 pages must be obtained from the global pools.  To relay this information to the caller, the value 2 is returned.  The caller is then responsible for attempting to obtain the additional two pages from the global pools.

<a id="rst-cow-and-reservations"></a>

## COW and Reservations

Since shared mappings all point to and use the same underlying pages, the biggest reservation concern for COW is private mappings.  In this case, two tasks can be pointing at the same previously allocated page.  One task attempts to write to the page, so a new page must be allocated so that each task points to its own page.

When the page was originally allocated, the reservation for that page was consumed.  When an attempt to allocate a new page is made as a result of COW, it is possible that no free huge pages are free and the allocation will fail.

When the private mapping was originally created, the owner of the mapping was noted by setting the HPAGE_RESV_OWNER bit in the pointer to the reservation map of the owner.  Since the owner created the mapping, the owner owns all the reservations associated with the mapping.  Therefore, when a write fault occurs and there is no page available, different action is taken for the owner and non-owner of the reservation.

In the case where the faulting task is not the owner, the fault will fail and the task will typically receive a SIGBUS.

If the owner is the faulting task, we want it to succeed since it owned the original reservation.  To accomplish this, the page is unmapped from the non-owning task.  In this way, the only reference is from the owning task. In addition, the HPAGE_RESV_UNMAPPED bit is set in the reservation map pointer of the non-owning task.  The non-owning task may receive a SIGBUS if it later faults on a non-present page.  But, the original owner of the mapping/reservation will behave as expected.

<a id="rst-reservation-map-modifications"></a>
<a id="rst-resv-map-modifications"></a>

## Reservation Map Modifications

The following low level routines are used to make modifications to a reservation map.  Typically, these routines are not called directly.  Rather, a reservation map helper routine is called which calls one of these low level routines.  These low level routines are fairly well documented in the source code (mm/hugetlb.c).  These routines are:



```text
long region_chg(struct resv_map *resv, long f, long t);
long region_add(struct resv_map *resv, long f, long t);
void region_abort(struct resv_map *resv, long f, long t);
long region_count(struct resv_map *resv, long f, long t);
```

Operations on the reservation map typically involve two operations:

1. region_chg() is called to examine the reserve map and determine how many pages in the specified range \[f, t) are NOT currently represented.

   The calling code performs global checks and allocations to determine if there are enough huge pages for the operation to succeed.

2. - **a)** If the operation can succeed, region_add() is called to actually modify the reservation map for the same range \[f, t) previously passed to region_chg().

   - **b)** If the operation can not succeed, region_abort is called for the same range \[f, t) to abort the operation.

Note that this is a two step process where region_add() and region_abort() are guaranteed to succeed after a prior call to region_chg() for the same range.  region_chg() is responsible for pre-allocating any data structures necessary to ensure the subsequent operations (specifically region_add())) will succeed.

As mentioned above, region_chg() determines the number of pages in the range which are NOT currently represented in the map.  This number is returned to the caller.  region_add() returns the number of pages in the range added to the map.  In most cases, the return value of region_add() is the same as the return value of region_chg().  However, in the case of shared mappings it is possible for changes to the reservation map to be made between the calls to region_chg() and region_add().  In this case, the return value of region_add() will not match the return value of region_chg().  It is likely that in such cases global counts and subpool accounting will be incorrect and in need of adjustment.  It is the responsibility of the caller to check for this condition and make the appropriate adjustments.

The routine region_del() is called to remove regions from a reservation map. It is typically called in the following situations:

- When a file in the hugetlbfs filesystem is being removed, the inode will be released and the reservation map freed.  Before freeing the reservation map, all the individual file_region structures must be freed.  In this case region_del is passed the range \[0, LONG_MAX).

- When a hugetlbfs file is being truncated.  In this case, all allocated pages after the new file size must be freed.  In addition, any file_region entries in the reservation map past the new end of file must be deleted.  In this case, region_del is passed the range \[new_end_of_file, LONG_MAX).

- When a hole is being punched in a hugetlbfs file.  In this case, huge pages are removed from the middle of the file one at a time.  As the pages are removed, region_del() is called to remove the corresponding entry from the reservation map.  In this case, region_del is passed the range \[page_idx, page_idx + 1).

In every case, region_del() will return the number of pages removed from the reservation map.  In VERY rare cases, region_del() can fail.  This can only happen in the hole punch case where it has to split an existing file_region entry and can not allocate a new structure.  In this error case, region_del() will return -ENOMEM.  The problem here is that the reservation map will indicate that there is a reservation for the page.  However, the subpool and global reservation counts will not reflect the reservation.  To handle this situation, the routine hugetlb_fix_reserve_counts() is called to adjust the counters so that they correspond with the reservation map entry that could not be deleted.

region_count() is called when unmapping a private huge page mapping.  In private mappings, the lack of a entry in the reservation map indicates that a reservation exists.  Therefore, by counting the number of entries in the reservation map we know how many reservations were consumed and how many are outstanding (outstanding = (end - start) - region_count(resv, start, end)). Since the mapping is going away, the subpool and global reservation counts are decremented by the number of outstanding reservations.

<a id="rst-reservation-map-helper-routines"></a>
<a id="rst-resv-map-helpers"></a>

## Reservation Map Helper Routines

Several helper routines exist to query and modify the reservation maps. These routines are only interested with reservations for a specific huge page, so they just pass in an address instead of a range.  In addition, they pass in the associated VMA.  From the VMA, the type of mapping (private or shared) and the location of the reservation map (inode or VMA) can be determined.  These routines simply call the underlying routines described in the section "Reservation Map Modifications".  However, they do take into account the 'opposite' meaning of reservation map entries for private and shared mappings and hide this detail from the caller:



```text
long vma_needs_reservation(struct hstate *h,
                           struct vm_area_struct *vma,
                           unsigned long addr)
```

This routine calls region_chg() for the specified page.  If no reservation exists, 1 is returned.  If a reservation exists, 0 is returned:



```text
long vma_commit_reservation(struct hstate *h,
                            struct vm_area_struct *vma,
                            unsigned long addr)
```

This calls region_add() for the specified page.  As in the case of region_chg and region_add, this routine is to be called after a previous call to vma_needs_reservation.  It will add a reservation entry for the page.  It returns 1 if the reservation was added and 0 if not.  The return value should be compared with the return value of the previous call to vma_needs_reservation.  An unexpected difference indicates the reservation map was modified between calls:



```text
void vma_end_reservation(struct hstate *h,
                         struct vm_area_struct *vma,
                         unsigned long addr)
```

This calls region_abort() for the specified page.  As in the case of region_chg and region_abort, this routine is to be called after a previous call to vma_needs_reservation.  It will abort/end the in progress reservation add operation:



```text
long vma_add_reservation(struct hstate *h,
                         struct vm_area_struct *vma,
                         unsigned long addr)
```

This is a special wrapper routine to help facilitate reservation cleanup on error paths.  It is only called from the routine restore_reserve_on_error(). This routine is used in conjunction with vma_needs_reservation in an attempt to add a reservation to the reservation map.  It takes into account the different reservation map semantics for private and shared mappings.  Hence, region_add is called for shared mappings (as an entry present in the map indicates a reservation), and region_del is called for private mappings (as the absence of an entry in the map indicates a reservation).  See the section "Reservation cleanup in error paths" for more information on what needs to be done on error paths.

<a id="rst-reservation-cleanup-in-error-paths"></a>

## Reservation Cleanup in Error Paths

As mentioned in the section [Reservation Map Helper Routines](<#rst-resv-map-helpers>), reservation map modifications are performed in two steps.  First vma_needs_reservation is called before a page is allocated.  If the allocation is successful, then vma_commit_reservation is called.  If not, vma_end_reservation is called. Global and subpool reservation counts are adjusted based on success or failure of the operation and all is well.

Additionally, after a huge page is instantiated the PagePrivate flag is cleared so that accounting when the page is ultimately freed is correct.

However, there are several instances where errors are encountered after a huge page is allocated but before it is instantiated.  In this case, the page allocation has consumed the reservation and made the appropriate subpool, reservation map and global count adjustments.  If the page is freed at this time (before instantiation and clearing of PagePrivate), then free_huge_folio will increment the global reservation count.  However, the reservation map indicates the reservation was consumed.  This resulting inconsistent state will cause the 'leak' of a reserved huge page.  The global reserve count will be  higher than it should and prevent allocation of a pre-allocated page.

The routine restore_reserve_on_error() attempts to handle this situation.  It is fairly well documented.  The intention of this routine is to restore the reservation map to the way it was before the page allocation.   In this way, the state of the reservation map will correspond to the global reservation count after the page is freed.

The routine restore_reserve_on_error itself may encounter errors while attempting to restore the reservation map entry.  In this case, it will simply clear the PagePrivate flag of the page.  In this way, the global reserve count will not be incremented when the page is freed.  However, the reservation map will continue to look as though the reservation was consumed. A page can still be allocated for the address, but it will not use a reserved page as originally intended.

There is some code (most notably userfaultfd) which can not call restore_reserve_on_error.  In this case, it simply modifies the PagePrivate so that a reservation will not be leaked when the huge page is freed.

<a id="rst-reservations-and-memory-policy"></a>

## Reservations and Memory Policy

Per-node huge page lists existed in struct hstate when git was first used to manage Linux code.  The concept of reservations was added some time later. When reservations were added, no attempt was made to take memory policy into account.  While cpusets are not exactly the same as memory policy, this comment in hugetlb_acct_memory sums up the interaction between reservations and cpusets/memory policy:



```text
/*
 * When cpuset is configured, it breaks the strict hugetlb page
 * reservation as the accounting is done on a global variable. Such
 * reservation is completely rubbish in the presence of cpuset because
 * the reservation is not checked against page availability for the
 * current cpuset. Application can still potentially OOM'ed by kernel
 * with lack of free htlb page in cpuset that the task is in.
 * Attempt to enforce strict accounting with cpuset is almost
 * impossible (or too ugly) because cpuset is too fluid that
 * task or memory node can be dynamically moved between cpusets.
 *
 * The change of semantics for shared hugetlb mapping with cpuset is
 * undesirable. However, in order to preserve some of the semantics,
 * we fall back to check against current free page availability as
 * a best attempt and hopefully to minimize the impact of changing
 * semantics that cpuset has.
 */
```

Huge page reservations were added to prevent unexpected page allocation failures (OOM) at page fault time.  However, if an application makes use of cpusets or memory policy there is no guarantee that huge pages will be available on the required nodes.  This is true even if there are a sufficient number of global reservations.

<a id="rst-hugetlbfs-regression-testing"></a>

## Hugetlbfs regression testing

The most complete set of hugetlb tests are in the libhugetlbfs repository. If you modify any hugetlb related code, use the libhugetlbfs test suite to check for regressions.  In addition, if you add any new hugetlb functionality, please add appropriate tests to libhugetlbfs.

-- Mike Kravetz, 7 April 2017

---

# hwpoison

_Peios Kernel / Internals / Memory management_

> Upcoming Intel CPUs have support for recovering from some memory errors (MCA recovery). This requires the OS to declare a page "poisoned", kill the processes associated with it and avoid using it in the future.

<a id="rst-hwpoison"></a>

<a id="rst-what-is-hwpoison"></a>

## What is hwpoison?

Upcoming Intel CPUs have support for recovering from some memory errors (`MCA recovery`). This requires the OS to declare a page "poisoned", kill the processes associated with it and avoid using it in the future.

This patchkit implements the necessary infrastructure in the VM.

To quote the overview comment:



```text
High level machine check handler. Handles pages reported by the
hardware as being corrupted usually due to a 2bit ECC memory or cache
failure.

This focusses on pages detected as corrupted in the background.
When the current CPU tries to consume corruption the currently
running process can just be killed directly instead. This implies
that if the error cannot be handled for some reason it's safe to
just ignore it because no corruption has been consumed yet. Instead
when that happens another machine check will happen.

Handles page cache pages in various states. The tricky part
here is that we can access any page asynchronous to other VM
users, because memory failures could happen anytime and anywhere,
possibly violating some of their assumptions. This is why this code
has to be extremely careful. Generally it tries to use normal locking
rules, as in get the standard locks, even if that means the
error handling takes potentially a long time.

Some of the operations here are somewhat inefficient and have non
linear algorithmic complexity, because the data structures have not
been optimized for this case. This is in particular the case
for the mapping from a vma to a process. Since this case is expected
to be rare we hope we can get away with this.
```

The code consists of a the high level handler in mm/memory-failure.c, a new page poison bit and various checks in the VM to handle poisoned pages.

The main target right now is KVM guests, but it works for all kinds of applications. KVM support requires a recent qemu-kvm release.

For the KVM use there was need for a new signal type so that KVM can inject the machine check into the guest with the proper address. This in theory allows other applications to handle memory failures too. The expectation is that most applications won't do that, but some very specialized ones might.

<a id="rst-failure-recovery-modes"></a>

## Failure recovery modes

There are two (actually three) modes memory failure recovery can be in:

- **vm.memory_failure_recovery sysctl set to zero:**

  All memory failures cause a panic. Do not attempt recovery.

- **early kill**

  (can be controlled globally and per process) Send SIGBUS to the application as soon as the error is detected This allows applications who can process memory errors in a gentle way (e.g. drop affected object) This is the mode used by KVM qemu.

- **late kill**

  Send SIGBUS when the application runs into the corrupted page. This is best for memory error unaware applications and default Note some pages are always handled as late kill.

<a id="rst-user-control"></a>

## User control

- **vm.memory_failure_recovery**

  See sysctl.txt

- **vm.memory_failure_early_kill**

  Enable early kill mode globally

- **PR_MCE_KILL**

  Set early/late kill mode/revert to system default

  - **arg1: PR_MCE_KILL_CLEAR:**

    Revert to system default

  - **arg1: PR_MCE_KILL_SET:**

    arg2 defines thread specific mode

    - **PR_MCE_KILL_EARLY:**

      Early kill

    - **PR_MCE_KILL_LATE:**

      Late kill

    - **PR_MCE_KILL_DEFAULT**

      Use system global default

  Note that if you want to have a dedicated thread which handles the SIGBUS(BUS_MCEERR_AO) on behalf of the process, you should call prctl(PR_MCE_KILL_EARLY) on the designated thread. Otherwise, the SIGBUS is sent to the main thread.

- **PR_MCE_KILL_GET**

  return current mode

<a id="rst-testing"></a>

## Testing

- madvise(MADV_HWPOISON, ....) (as root) - Poison a page in the process for testing

- hwpoison-inject module through debugfs `/sys/kernel/debug/hwpoison/`

  - **corrupt-pfn**

    Inject hwpoison fault at PFN echoed into this file. This does some early filtering to avoid corrupted unintended pages in test suites.

  - **unpoison-pfn**

    Software-unpoison page at PFN echoed into this file. This way a page can be reused again.  This only works for Linux injected failures, not for real memory failures. Once any hardware memory failure happens, this feature is disabled.

  Note these injection interfaces are not stable and might change between kernel versions

  - **corrupt-filter-dev-major, corrupt-filter-dev-minor**

    Only handle memory failures to pages associated with the file system defined by block device major/minor.  -1U is the wildcard value.  This should be only used for testing with artificial injection.

  - **corrupt-filter-memcg**

    Limit injection to pages owned by memgroup. Specified by inode number of the memcg.

    Example:



    ```text
    mkdir /sys/fs/cgroup/mem/hwpoison

    usemem -m 100 -s 1000 &
    echo `jobs -p` > /sys/fs/cgroup/mem/hwpoison/tasks

    memcg_ino=$(ls -id /sys/fs/cgroup/mem/hwpoison | cut -f1 -d' ')
    echo $memcg_ino > /debug/hwpoison/corrupt-filter-memcg

    page-types -p `pidof init`   --hwpoison  # shall do nothing
    page-types -p `pidof usemem` --hwpoison  # poison its pages
    ```

  - **corrupt-filter-flags-mask, corrupt-filter-flags-value**

    When specified, only poison pages if ((page_flags &amp; mask) == value).  This allows stress testing of many kinds of pages. The page_flags are the same as in /proc/kpageflags. The flag bits are defined in include/linux/kernel-page-flags.h and documented in [Documentation/admin-guide/mm/pagemap.rst](/kernel/administration/admin-guide/mm/pagemap.md)

- Architecture specific MCE injector

  x86 has mce-inject, mce-test

  Some portable hwpoison test programs in mce-test, see below.

<a id="rst-references"></a>

## References

- **[http://halobates.de/mce-lc09-2.pdf](<http://halobates.de/mce-lc09-2.pdf>)**

  Overview presentation from LinuxCon 09

- **git://git.kernel.org/pub/scm/utils/cpu/mce/mce-test.git**

  Test suite (hwpoison specific portable tests in tsrc)

- **git://git.kernel.org/pub/scm/utils/cpu/mce/mce-inject.git**

  x86 specific injector

<a id="rst-limitations"></a>

## Limitations

- Not all page types are supported and never will. Most kernel internal objects cannot be recovered, only LRU pages for now.

--- Andi Kleen, Oct 2009

---

# Kernel Samepage Merging

_Peios Kernel / Internals / Memory management_

> KSM is a memory-saving de-duplication feature, enabled by CONFIG_KSM=y, added to the Linux kernel in 2.6.32. See mm/ksm.c for its implementation, and http://lwn.net/Articles/306704/ and https://lwn.net/Articles/330589/

<a id="rst-kernel-samepage-merging"></a>

KSM is a memory-saving de-duplication feature, enabled by CONFIG_KSM=y, added to the Linux kernel in 2.6.32.  See `mm/ksm.c` for its implementation, and [http://lwn.net/Articles/306704/](<http://lwn.net/Articles/306704/>) and [https://lwn.net/Articles/330589/](<https://lwn.net/Articles/330589/>)

The userspace interface of KSM is described in [Documentation/admin-guide/mm/ksm.rst](/kernel/administration/admin-guide/mm/ksm.md)

<a id="rst-design"></a>

## Design

<a id="rst-overview"></a>

### Overview


A few notes about the KSM scanning process,
to make it easier to understand the data structures below:

In order to reduce excessive scanning, KSM sorts the memory pages by their
contents into a data structure that holds pointers to the pages' locations.

Since the contents of the pages may change at any moment, KSM cannot just
insert the pages into a normal sorted tree and expect it to find anything.
Therefore KSM uses two data structures - the stable and the unstable tree.

The stable tree holds pointers to all the merged pages (ksm pages), sorted
by their contents.  Because each such page is write-protected, searching on
this tree is fully assured to be working (except when pages are unmapped),
and therefore this tree is called the stable tree.

The stable tree node includes information required for reverse
mapping from a KSM page to virtual addresses that map this page.

In order to avoid large latencies of the rmap walks on KSM pages,
KSM maintains two types of nodes in the stable tree:

* the regular nodes that keep the reverse mapping structures in a
  linked list
* the "chains" that link nodes ("dups") that represent the same
  write protected memory content, but each "dup" corresponds to a
  different KSM page copy of that content

Internally, the regular nodes, "dups" and "chains" are represented
using the same struct ksm_stable_node structure.

In addition to the stable tree, KSM uses a second data structure called the
unstable tree: this tree holds pointers to pages which have been found to
be "unchanged for a period of time".  The unstable tree sorts these pages
by their contents, but since they are not write-protected, KSM cannot rely
upon the unstable tree to work correctly - the unstable tree is liable to
be corrupted as its contents are modified, and so it is called unstable.

KSM solves this problem by several techniques:

1) The unstable tree is flushed every time KSM completes scanning all
   memory areas, and then the tree is rebuilt again from the beginning.
2) KSM will only insert into the unstable tree, pages whose hash value
   has not changed since the previous scan of all memory areas.
3) The unstable tree is a RedBlack Tree - so its balancing is based on the
   colors of the nodes and not on their contents, assuring that even when
   the tree gets "corrupted" it won't get out of balance, so scanning time
   remains the same (also, searching and inserting nodes in an rbtree uses
   the same algorithm, so we have no overhead when we flush and rebuild).
4) KSM never flushes the stable tree, which means that even if it were to
   take 10 attempts to find a page in the unstable tree, once it is found,
   it is secured in the stable tree.  (When we scan a new page, we first
   compare it against the stable tree, and then against the unstable tree.)

If the merge_across_nodes tunable is unset, then KSM maintains multiple
stable trees and multiple unstable trees: one of each for each NUMA node.


<a id="rst-reverse-mapping"></a>

### Reverse mapping

KSM maintains reverse mapping information for KSM pages in the stable tree.

If a KSM page is shared between less than `max_page_sharing` VMAs, the node of the stable tree that represents such KSM page points to a list of struct ksm_rmap_item and the `page->mapping` of the KSM page points to the stable tree node.

When the sharing passes this threshold, KSM adds a second dimension to the stable tree. The tree node becomes a "chain" that links one or more "dups". Each "dup" keeps reverse mapping information for a KSM page with `page->mapping` pointing to that "dup".

Every "chain" and all "dups" linked into a "chain" enforce the invariant that they represent the same write protected memory content, even if each "dup" will be pointed by a different KSM page copy of that content.

This way the stable tree lookup computational complexity is unaffected if compared to an unlimited list of reverse mappings. It is still enforced that there cannot be KSM page content duplicates in the stable tree itself.

The deduplication limit enforced by `max_page_sharing` is required to avoid the virtual memory rmap lists to grow too large. The rmap walk has O(N) complexity where N is the number of rmap_items (i.e. virtual mappings) that are sharing the page, which is in turn capped by `max_page_sharing`. So this effectively spreads the linear O(N) computational complexity from rmap walk context over different KSM pages. The ksmd walk over the stable_node "chains" is also O(N), but N is the number of stable_node "dups", not the number of rmap_items, so it has not a significant impact on ksmd performance. In practice the best stable_node "dup" candidate will be kept and found at the head of the "dups" list.

High values of `max_page_sharing` result in faster memory merging (because there will be fewer stable_node dups queued into the stable_node chain-&gt;hlist to check for pruning) and higher deduplication factor at the expense of slower worst case for rmap walks for any KSM page which can happen during swapping, compaction, NUMA balancing and page migration.

The `stable_node_dups/stable_node_chains` ratio is also affected by the `max_page_sharing` tunable, and an high ratio may indicate fragmentation in the stable_node dups, which could be solved by introducing fragmentation algorithms in ksmd which would refile rmap_items from one stable_node dup to another stable_node dup, in order to free up stable_node "dups" with few rmap_items in them, but that may increase the ksmd CPU usage and possibly slowdown the readonly computations on the KSM pages of the applications.

The whole list of stable_node "dups" linked in the stable_node "chains" is scanned periodically in order to prune stale stable_nodes. The frequency of such scans is defined by `stable_node_chains_prune_millisecs` sysfs tunable.

<a id="rst-reference"></a>

### Reference


#### <a id="c-struct-ksm_scan"></a>`struct ksm_scan`

cursor for scanning

**Definition**

```c
struct ksm_scan {
    struct ksm_mm_slot *mm_slot;
    unsigned long address;
    struct ksm_rmap_item **rmap_list;
    unsigned long seqnr;
};
```

**Members**

- `mm_slot`: the current mm_slot we are scanning
- `address`: the next address inside that to be scanned
- `rmap_list`: link to the next rmap to be scanned in the rmap_list
- `seqnr`: count of completed full scans (needed when removing unstable node)

**Description**

There is only the one ksm_scan instance of this cursor structure.


-- Izik Eidus, Hugh Dickins, 17 Nov 2009

---

# Memfd Preservation via LUO

_Peios Kernel / Internals / Memory management_

> /core-api/liveupdate

<a id="rst-memfd-preservation-via-luo"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->


**Overview**

Memory file descriptors (memfd) can be preserved over a kexec using the Live
Update Orchestrator (LUO) file preservation. This allows userspace to
transfer its memory contents to the next kernel after a kexec.

The preservation is not intended to be transparent. Only select properties of
the file are preserved. All others are reset to default. The preserved
properties are described below.

> [!NOTE]
> The LUO API is not stabilized yet, so the preserved properties of a memfd
> are also not stable and are subject to backwards incompatible changes.

> [!NOTE]
> Currently a memfd backed by Hugetlb is not supported. Memfds created
> with `MFD_HUGETLB` will be rejected.

**Preserved Properties**

The following properties of the memfd are preserved across kexec:

- File Contents

  All data stored in the file is preserved.

- File Size

  The size of the file is preserved. Holes in the file are filled by
  allocating pages for them during preservation.

- File Position

  The current file position is preserved, allowing applications to continue
  reading/writing from their last position.

- File Status Flags

  memfds are always opened with `O_RDWR` and `O_LARGEFILE`. This property
  is maintained.

**Non-Preserved Properties**

All properties which are not preserved must be assumed to be reset to
default. This section describes some of those properties which may be more of
note.

- `FD_CLOEXEC` flag

  A memfd can be created with the `MFD_CLOEXEC` flag that sets the
  `FD_CLOEXEC` on the file. This flag is not preserved and must be set
  again after restore via `fcntl()`.

- Seals:
  File seals are not preserved. The file is unsealed on restore and if
  needed, must be sealed again via `fcntl()`.


<a id="rst-memfd-preservation-abi"></a>

## Memfd Preservation ABI





#### <a id="c-MEMFD_LUO_FOLIO_DIRTY"></a>`MEMFD_LUO_FOLIO_DIRTY`

```c
MEMFD_LUO_FOLIO_DIRTY
```

The folio is dirty.

**Description**

This flag indicates the folio contains data from user. A non-dirty folio is
one that was allocated (say using fallocate(2)) but not written to.

#### <a id="c-MEMFD_LUO_FOLIO_UPTODATE"></a>`MEMFD_LUO_FOLIO_UPTODATE`

```c
MEMFD_LUO_FOLIO_UPTODATE
```

The folio is up-to-date.

**Description**

An up-to-date folio has been zeroed out. shmem zeroes out folios on first
use. This flag tracks which folios need zeroing.

#### <a id="c-struct-memfd_luo_folio_ser"></a>`struct memfd_luo_folio_ser`

Serialized state of a single folio.

**Definition**

```c
struct memfd_luo_folio_ser {
    u64 pfn:52;
    u64 flags:12;
    u64 index;
};
```

**Members**

- `pfn`: The page frame number of the folio.
- `flags`: Flags to describe the state of the folio.
- `index`: The page offset (pgoff_t) of the folio within the original file.

#### <a id="c-struct-memfd_luo_ser"></a>`struct memfd_luo_ser`

Main serialization structure for a memfd.

**Definition**

```c
struct memfd_luo_ser {
    u64 pos;
    u64 size;
    u64 nr_folios;
    struct kho_vmalloc folios;
};
```

**Members**

- `pos`: The file's current position (f_pos).
- `size`: The total size of the file in bytes (i_size).
- `nr_folios`: Number of folios in the folios array.
- `folios`: KHO vmalloc descriptor pointing to the array of
  struct memfd_luo_folio_ser.


<a id="rst-see-also"></a>

## See Also

- [Live Update Orchestrator](</kernel/internals/core-api/liveupdate.md>)

- [Kexec Handover Subsystem](</kernel/internals/core-api/kho/index.md>)

---

# Physical Memory Model

_Peios Kernel / Internals / Memory management_

> Physical memory in a system may be addressed in different ways. The simplest case is when the physical memory starts at address 0 and spans a contiguous range up to the maximal address. It could be, however, that this range contains small…

<a id="rst-physical-memory-model"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Physical memory in a system may be addressed in different ways. The simplest case is when the physical memory starts at address 0 and spans a contiguous range up to the maximal address. It could be, however, that this range contains small holes that are not accessible for the CPU. Then there could be several contiguous ranges at completely distinct addresses. And, don't forget about NUMA, where different memory banks are attached to different CPUs.

Linux abstracts this diversity using one of the two memory models: FLATMEM and SPARSEMEM. Each architecture defines what memory models it supports, what the default memory model is and whether it is possible to manually override that default.

All the memory models track the status of physical page frames using struct page arranged in one or more arrays.

Regardless of the selected memory model, there exists one-to-one mapping between the physical page frame number (PFN) and the corresponding `struct page`.

Each memory model defines `pfn_to_page()` and `page_to_pfn()` helpers that allow the conversion from PFN to `struct page` and vice versa.

<a id="rst-flatmem"></a>

## FLATMEM

The simplest memory model is FLATMEM. This model is suitable for non-NUMA systems with contiguous, or mostly contiguous, physical memory.

In the FLATMEM memory model, there is a global `mem_map` array that maps the entire physical memory. For most architectures, the holes have entries in the `mem_map` array. The `struct page` objects corresponding to the holes are never fully initialized.

To allocate the `mem_map` array, architecture specific setup code should call `free_area_init()` function. Yet, the mappings array is not usable until the call to `memblock_free_all()` that hands all the memory to the page allocator.

An architecture may free parts of the `mem_map` array that do not cover the actual physical pages. In such case, the architecture specific `pfn_valid()` implementation should take the holes in the `mem_map` into account.

With FLATMEM, the conversion between a PFN and the `struct page` is straightforward: `PFN - ARCH_PFN_OFFSET` is an index to the `mem_map` array.

The `ARCH_PFN_OFFSET` defines the first page frame number for systems with physical memory starting at address different from 0.

<a id="rst-sparsemem"></a>

## SPARSEMEM

SPARSEMEM is the most versatile memory model available in Linux and it is the only memory model that supports several advanced features such as hot-plug and hot-remove of the physical memory, alternative memory maps for non-volatile memory devices and deferred initialization of the memory map for larger systems.

The SPARSEMEM model presents the physical memory as a collection of sections. A section is represented with struct mem\_section that contains `section_mem_map` that is, logically, a pointer to an array of struct pages. However, it is stored with some other magic that aids the sections management. The section size and maximal number of section is specified using `SECTION_SIZE_BITS` and `MAX_PHYSMEM_BITS` constants defined by each architecture that supports SPARSEMEM. While `MAX_PHYSMEM_BITS` is an actual width of a physical address that an architecture supports, the `SECTION_SIZE_BITS` is an arbitrary value.

The maximal number of sections is denoted `NR_MEM_SECTIONS` and defined as

```math
NR\_MEM\_SECTIONS = 2 ^ {(MAX\_PHYSMEM\_BITS - SECTION\_SIZE\_BITS)}
```

The `mem_section` objects are arranged in a two-dimensional array called `mem_sections`. The size and placement of this array depend on `CONFIG_SPARSEMEM_EXTREME` and the maximal possible number of sections:

- When `CONFIG_SPARSEMEM_EXTREME` is disabled, the `mem_sections` array is static and has `NR_MEM_SECTIONS` rows. Each row holds a single `mem_section` object.

- When `CONFIG_SPARSEMEM_EXTREME` is enabled, the `mem_sections` array is dynamically allocated. Each row contains PAGE\_SIZE worth of `mem_section` objects and the number of rows is calculated to fit all the memory sections.

With SPARSEMEM there are two possible ways to convert a PFN to the corresponding `struct page` - a "classic sparse" and "sparse vmemmap". The selection is made at build time and it is determined by the value of `CONFIG_SPARSEMEM_VMEMMAP`.

The classic sparse encodes the section number of a page in page-&gt;flags and uses high bits of a PFN to access the section that maps that page frame. Inside a section, the PFN is the index to the array of pages.

The sparse vmemmap uses a virtually mapped memory map to optimize pfn\_to\_page and page\_to\_pfn operations. There is a global `struct page *vmemmap` pointer that points to a virtually contiguous array of `struct page` objects. A PFN is an index to that array and the offset of the `struct page` from `vmemmap` is the PFN of that page.

To use vmemmap, an architecture has to reserve a range of virtual addresses that will map the physical pages containing the memory map and make sure that `vmemmap` points to that range. In addition, the architecture should implement `vmemmap_populate()` method that will allocate the physical memory and create page tables for the virtual memory map. If an architecture does not have any special requirements for the vmemmap mappings, it can use default `vmemmap_populate_basepages()` provided by the generic memory management.

The virtually mapped memory map allows storing `struct page` objects for persistent memory devices in pre-allocated storage on those devices. This storage is represented with struct vmem\_altmap that is eventually passed to vmemmap\_populate() through a long chain of function calls. The vmemmap\_populate() implementation may use the `vmem_altmap` along with `vmemmap_alloc_block_buf()` helper to allocate memory map on the persistent memory device.

<a id="rst-zone-device"></a>

## ZONE\_DEVICE

The `ZONE_DEVICE` facility builds upon `SPARSEMEM_VMEMMAP` to offer `struct page` `mem_map` services for device driver identified physical address ranges. The "device" aspect of `ZONE_DEVICE` relates to the fact that the page objects for these address ranges are never marked online, and that a reference must be taken against the device, not just the page to keep the memory pinned for active use. `ZONE_DEVICE`, via `devm_memremap_pages()`, performs just enough memory hotplug to turn on `pfn_to_page()`, `page_to_pfn()`, and `get_user_pages()` service for the given range of pfns. Since the page reference count never drops below 1 the page is never tracked as free memory and the page's `struct list_head lru` space is repurposed for back referencing to the host device / driver that mapped the memory.

While `SPARSEMEM` presents memory as a collection of sections, optionally collected into memory blocks, `ZONE_DEVICE` users have a need for smaller granularity of populating the `mem_map`. Given that `ZONE_DEVICE` memory is never marked online it is subsequently never subject to its memory ranges being exposed through the sysfs memory hotplug api on memory block boundaries. The implementation relies on this lack of user-api constraint to allow sub-section sized memory ranges to be specified to `arch_add_memory()`, the top-half of memory hotplug. Sub-section support allows for 2MB as the cross-arch common alignment granularity for `devm_memremap_pages()`.

The users of `ZONE_DEVICE` are:

- pmem: Map platform persistent memory to be used as a direct-I/O target via DAX mappings.

- hmm: Extend `ZONE_DEVICE` with `->page_fault()` and `->folio_free()` event callbacks to allow a device-driver to coordinate memory management events related to device-memory, typically GPU memory. See [Documentation/mm/hmm.rst](/kernel/internals/mm/hmm.md).

- p2pdma: Create `struct page` objects to allow peer devices in a PCI/-E topology to coordinate direct-DMA operations between themselves, i.e. bypass host memory.

---

# When do you need to notify inside page table lock ?

_Peios Kernel / Internals / Memory management_

> When clearing a pte/pmd we are given a choice to notify the event through (notify version of *_clear_flush call mmu_notifier_invalidate_range) under the page table lock. But that notification is not necessary in all cases.

<a id="rst-when-do-you-need-to-notify-inside-page-table-lock"></a>

When clearing a pte/pmd we are given a choice to notify the event through (notify version of \*\_clear_flush call mmu_notifier_invalidate_range) under the page table lock. But that notification is not necessary in all cases.

For secondary TLB (non CPU TLB) like IOMMU TLB or device TLB (when device use thing like ATS/PASID to get the IOMMU to walk the CPU page table to access a process virtual address space). There is only 2 cases when you need to notify those secondary TLB while holding page table lock when clearing a pte/pmd:

> - **A)** page backing address is free before mmu_notifier_invalidate_range_end()
>
> - **B)** a page table entry is updated to point to a new page (COW, write fault on zero page, \__replace_page(), ...)

Case A is obvious you do not want to take the risk for the device to write to a page that might now be used by some completely different task.

Case B is more subtle. For correctness it requires the following sequence to happen:

> - take page table lock
>
> - clear page table entry and notify (\[pmd/pte\]p_huge_clear_flush_notify())
>
> - set page table entry to point to new page

If clearing the page table entry is not followed by a notify before setting the new pte/pmd value then you can break memory model like C11 or C++11 for the device.

Consider the following scenario (device use a feature similar to ATS/PASID):

Two address addrA and addrB such that \|addrA - addrB\| &gt;= PAGE_SIZE we assume they are write protected for COW (other case of B apply too).



```text
[Time N] --------------------------------------------------------------------
CPU-thread-0  {try to write to addrA}
CPU-thread-1  {try to write to addrB}
CPU-thread-2  {}
CPU-thread-3  {}
DEV-thread-0  {read addrA and populate device TLB}
DEV-thread-2  {read addrB and populate device TLB}
[Time N+1] ------------------------------------------------------------------
CPU-thread-0  {COW_step0: {mmu_notifier_invalidate_range_start(addrA)}}
CPU-thread-1  {COW_step0: {mmu_notifier_invalidate_range_start(addrB)}}
CPU-thread-2  {}
CPU-thread-3  {}
DEV-thread-0  {}
DEV-thread-2  {}
[Time N+2] ------------------------------------------------------------------
CPU-thread-0  {COW_step1: {update page table to point to new page for addrA}}
CPU-thread-1  {COW_step1: {update page table to point to new page for addrB}}
CPU-thread-2  {}
CPU-thread-3  {}
DEV-thread-0  {}
DEV-thread-2  {}
[Time N+3] ------------------------------------------------------------------
CPU-thread-0  {preempted}
CPU-thread-1  {preempted}
CPU-thread-2  {write to addrA which is a write to new page}
CPU-thread-3  {}
DEV-thread-0  {}
DEV-thread-2  {}
[Time N+3] ------------------------------------------------------------------
CPU-thread-0  {preempted}
CPU-thread-1  {preempted}
CPU-thread-2  {}
CPU-thread-3  {write to addrB which is a write to new page}
DEV-thread-0  {}
DEV-thread-2  {}
[Time N+4] ------------------------------------------------------------------
CPU-thread-0  {preempted}
CPU-thread-1  {COW_step3: {mmu_notifier_invalidate_range_end(addrB)}}
CPU-thread-2  {}
CPU-thread-3  {}
DEV-thread-0  {}
DEV-thread-2  {}
[Time N+5] ------------------------------------------------------------------
CPU-thread-0  {preempted}
CPU-thread-1  {}
CPU-thread-2  {}
CPU-thread-3  {}
DEV-thread-0  {read addrA from old page}
DEV-thread-2  {read addrB from new page}
```

So here because at time N+2 the clear page table entry was not pair with a notification to invalidate the secondary TLB, the device see the new value for addrB before seeing the new value for addrA. This break total memory ordering for the device.

When changing a pte to write protect or to point to a new write protected page with same content (KSM) it is fine to delay the mmu_notifier_invalidate_range call to mmu_notifier_invalidate_range_end() outside the page table lock. This is true even if the thread doing the page table update is preempted right after releasing page table lock but before call mmu_notifier_invalidate_range_end().

---

# Multi-Gen LRU

_Peios Kernel / Internals / Memory management_

> The multi-gen LRU is an alternative LRU implementation that optimizes page reclaim and improves performance under memory pressure. Page reclaim decides the kernel's caching policy and ability to overcommit memory. It directly impacts the…

<a id="rst-multi-gen-lru"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The multi-gen LRU is an alternative LRU implementation that optimizes page reclaim and improves performance under memory pressure. Page reclaim decides the kernel's caching policy and ability to overcommit memory. It directly impacts the kswapd CPU usage and RAM efficiency.

<a id="rst-design-overview"></a>

## Design overview

<a id="rst-objectives"></a>

### Objectives

The design objectives are:

- Good representation of access recency

- Try to profit from spatial locality

- Fast paths to make obvious choices

- Simple self-correcting heuristics

The representation of access recency is at the core of all LRU implementations. In the multi-gen LRU, each generation represents a group of pages with similar access recency. Generations establish a (time-based) common frame of reference and therefore help make better choices, e.g., between different memcgs on a computer or different computers in a data center (for job scheduling).

Exploiting spatial locality improves efficiency when gathering the accessed bit. A rmap walk targets a single page and does not try to profit from discovering a young PTE. A page table walk can sweep all the young PTEs in an address space, but the address space can be too sparse to make a profit. The key is to optimize both methods and use them in combination.

Fast paths reduce code complexity and runtime overhead. Unmapped pages do not require TLB flushes; clean pages do not require writeback. These facts are only helpful when other conditions, e.g., access recency, are similar. With generations as a common frame of reference, additional factors stand out. But obvious choices might not be good choices; thus self-correction is necessary.

The benefits of simple self-correcting heuristics are self-evident. Again, with generations as a common frame of reference, this becomes attainable. Specifically, pages in the same generation can be categorized based on additional factors, and a feedback loop can statistically compare the refault percentages across those categories and infer which of them are better choices.

<a id="rst-assumptions"></a>

### Assumptions

The protection of hot pages and the selection of cold pages are based on page access channels and patterns. There are two access channels:

- Accesses through page tables

- Accesses through file descriptors

The protection of the former channel is by design stronger because:

1. The uncertainty in determining the access patterns of the former channel is higher due to the approximation of the accessed bit.

2. The cost of evicting the former channel is higher due to the TLB flushes required and the likelihood of encountering the dirty bit.

3. The penalty of underprotecting the former channel is higher because applications usually do not prepare themselves for major page faults like they do for blocked I/O. E.g., GUI applications commonly use dedicated I/O threads to avoid blocking rendering threads.

There are also two access patterns:

- Accesses exhibiting temporal locality

- Accesses not exhibiting temporal locality

For the reasons listed above, the former channel is assumed to follow the former pattern unless `VM_SEQ_READ` or `VM_RAND_READ` is present, and the latter channel is assumed to follow the latter pattern unless outlying refaults have been observed.

<a id="rst-workflow-overview"></a>

## Workflow overview

Evictable pages are divided into multiple generations for each `lruvec`. The youngest generation number is stored in `lrugen->max_seq` for both anon and file types as they are aged on an equal footing. The oldest generation numbers are stored in `lrugen->min_seq[]` separately for anon and file types as clean file pages can be evicted regardless of swap constraints. These three variables are monotonically increasing.

Generation numbers are truncated into `order_base_2(MAX_NR_GENS+1)` bits in order to fit into the gen counter in `folio->flags`. Each truncated generation number is an index to `lrugen->folios[]`. The sliding window technique is used to track at least `MIN_NR_GENS` and at most `MAX_NR_GENS` generations. The gen counter stores a value within `[1, MAX_NR_GENS]` while a page is on one of `lrugen->folios[]`; otherwise it stores zero.

Each generation is divided into multiple tiers. A page accessed `N` times through file descriptors is in tier `order_base_2(N)`. Unlike generations, tiers do not have dedicated `lrugen->folios[]`. In contrast to moving across generations, which requires the LRU lock, moving across tiers only involves atomic operations on `folio->flags` and therefore has a negligible cost. A feedback loop modeled after the PID controller monitors refaults over all the tiers from anon and file types and decides which tiers from which types to evict or protect. The desired effect is to balance refault percentages between anon and file types proportional to the swappiness level.

There are two conceptually independent procedures: the aging and the eviction. They form a closed-loop system, i.e., the page reclaim.

<a id="rst-aging"></a>

### Aging

The aging produces young generations. Given an `lruvec`, it increments `max_seq` when `max_seq-min_seq+1` approaches `MIN_NR_GENS`. The aging promotes hot pages to the youngest generation when it finds them accessed through page tables; the demotion of cold pages happens consequently when it increments `max_seq`. The aging uses page table walks and rmap walks to find young PTEs. For the former, it iterates `lruvec_memcg()->mm_list` and calls `walk_page_range()` with each `mm_struct` on this list to scan PTEs, and after each iteration, it increments `max_seq`. For the latter, when the eviction walks the rmap and finds a young PTE, the aging scans the adjacent PTEs. For both, on finding a young PTE, the aging clears the accessed bit and updates the gen counter of the page mapped by this PTE to `(max_seq%MAX_NR_GENS)+1`.

<a id="rst-eviction"></a>

### Eviction

The eviction consumes old generations. Given an `lruvec`, it increments `min_seq` when `lrugen->folios[]` indexed by `min_seq%MAX_NR_GENS` becomes empty. To select a type and a tier to evict from, it first compares `min_seq[]` to select the older type. If both types are equally old, it selects the one whose first tier has a lower refault percentage. The first tier contains single-use unmapped clean pages, which are the best bet. The eviction sorts a page according to its gen counter if the aging has found this page accessed through page tables and updated its gen counter. It also moves a page to the next generation, i.e., `min_seq+1`, if this page was accessed multiple times through file descriptors and the feedback loop has detected outlying refaults from the tier this page is in. To this end, the feedback loop uses the first tier as the baseline, for the reason stated earlier.

<a id="rst-working-set-protection"></a>

### Working set protection

Each generation is timestamped at birth. If `lru_gen_min_ttl` is set, an `lruvec` is protected from the eviction when its oldest generation was born within `lru_gen_min_ttl` milliseconds. In other words, it prevents the working set of `lru_gen_min_ttl` milliseconds from getting evicted. The OOM killer is triggered if this working set cannot be kept in memory.

This time-based approach has the following advantages:

1. It is easier to configure because it is agnostic to applications and memory sizes.

2. It is more reliable because it is directly wired to the OOM killer.

<a id="rst-mm-struct-list"></a>

### `mm_struct` list

An `mm_struct` list is maintained for each memcg, and an `mm_struct` follows its owner task to the new memcg when this task is migrated.

A page table walker iterates `lruvec_memcg()->mm_list` and calls `walk_page_range()` with each `mm_struct` on this list to scan PTEs. When multiple page table walkers iterate the same list, each of them gets a unique `mm_struct`, and therefore they can run in parallel.

Page table walkers ignore any misplaced pages, e.g., if an `mm_struct` was migrated, pages left in the previous memcg will be ignored when the current memcg is under reclaim. Similarly, page table walkers will ignore pages from nodes other than the one under reclaim.

This infrastructure also tracks the usage of `mm_struct` between context switches so that page table walkers can skip processes that have been sleeping since the last iteration.

<a id="rst-rmap-pt-walk-feedback"></a>

### Rmap/PT walk feedback

Searching the rmap for PTEs mapping each page on an LRU list (to test and clear the accessed bit) can be expensive because pages from different VMAs (PA space) are not cache friendly to the rmap (VA space). For workloads mostly using mapped pages, searching the rmap can incur the highest CPU cost in the reclaim path.

`lru_gen_look_around()` exploits spatial locality to reduce the trips into the rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If the scan was done cacheline efficiently, it adds the PMD entry pointing to the PTE table to the Bloom filter. This forms a feedback loop between the eviction and the aging.

<a id="rst-bloom-filters"></a>

### Bloom filters

Bloom filters are a space and memory efficient data structure for set membership test, i.e., test if an element is not in the set or may be in the set.

In the eviction path, specifically, in `lru_gen_look_around()`, if a PMD has a sufficient number of hot pages, its address is placed in the filter. In the aging path, set membership means that the PTE range will be scanned for young pages.

Note that Bloom filters are probabilistic on set membership. If a test is false positive, the cost is an additional scan of a range of PTEs, which may yield hot pages anyway. Parameters of the filter itself can control the false positive rate in the limit.

<a id="rst-pid-controller"></a>

### PID controller

A feedback loop modeled after the Proportional-Integral-Derivative (PID) controller monitors refaults over anon and file types and decides which type to evict when both types are available from the same generation.

The PID controller uses generations rather than the wall clock as the time domain because a CPU can scan pages at different rates under varying memory pressure. It calculates a moving average for each new generation to avoid being permanently locked in a suboptimal state.

<a id="rst-memcg-lru"></a>

### Memcg LRU

An memcg LRU is a per-node LRU of memcgs. It is also an LRU of LRUs, since each node and memcg combination has an LRU of folios (see `mem_cgroup_lruvec()`). Its goal is to improve the scalability of global reclaim, which is critical to system-wide memory overcommit in data centers. Note that memcg LRU only applies to global reclaim.

The basic structure of an memcg LRU can be understood by an analogy to the active/inactive LRU (of folios):

1. It has the young and the old (generations), i.e., the counterparts to the active and the inactive;

2. The increment of `max_seq` triggers promotion, i.e., the counterpart to activation;

3. Other events trigger similar operations, e.g., offlining an memcg triggers demotion, i.e., the counterpart to deactivation.

In terms of global reclaim, it has two distinct features:

1. Sharding, which allows each thread to start at a random memcg (in the old generation) and improves parallelism;

2. Eventual fairness, which allows direct reclaim to bail out at will and reduces latency without affecting fairness over some time.

In terms of traversing memcgs during global reclaim, it improves the best-case complexity from O(n) to O(1) and does not affect the worst-case complexity O(n). Therefore, on average, it has a sublinear complexity.

<a id="rst-summary"></a>

### Summary

The multi-gen LRU (of folios) can be disassembled into the following parts:

- Generations

- Rmap walks

- Page table walks via `mm_struct` list

- Bloom filters for rmap/PT walk feedback

- PID controller for refault feedback

The aging and the eviction form a producer-consumer model; specifically, the latter drives the former by the sliding window over generations. Within the aging, rmap walks drive page table walks by inserting hot densely populated page tables to the Bloom filters. Within the eviction, the PID controller uses refaults as the feedback to select types to evict and tiers to protect.

---

# What is NUMA?

_Peios Kernel / Internals / Memory management_

> Started Nov 1999 by Kanoj Sarcar <kanoj@sgi.com>

Started Nov 1999 by Kanoj Sarcar &lt;[kanoj@sgi.com](<mailto:kanoj@sgi.com>)&gt;

<a id="rst-what-is-numa"></a>

## What is NUMA?

This question can be answered from a couple of perspectives:  the hardware view and the Linux software view.

From the hardware perspective, a NUMA system is a computer platform that comprises multiple components or assemblies each of which may contain 0 or more CPUs, local memory, and/or IO buses.  For brevity and to disambiguate the hardware view of these physical components/assemblies from the software abstraction thereof, we'll call the components/assemblies 'cells' in this document.

Each of the 'cells' may be viewed as an SMP \[symmetric multi-processor\] subset of the system--although some components necessary for a stand-alone SMP system may not be populated on any given cell.   The cells of the NUMA system are connected together with some sort of system interconnect--e.g., a crossbar or point-to-point link are common types of NUMA system interconnects.  Both of these types of interconnects can be aggregated to create NUMA platforms with cells at multiple distances from other cells.

For Linux, the NUMA platforms of interest are primarily what is known as Cache Coherent NUMA or ccNUMA systems.   With ccNUMA systems, all memory is visible to and accessible from any CPU attached to any cell and cache coherency is handled in hardware by the processor caches and/or the system interconnect.

Memory access time and effective memory bandwidth varies depending on how far away the cell containing the CPU or IO bus making the memory access is from the cell containing the target memory.  For example, access to memory by CPUs attached to the same cell will experience faster access times and higher bandwidths than accesses to memory on other, remote cells.  NUMA platforms can have cells at multiple remote distances from any given cell.

Platform vendors don't build NUMA systems just to make software developers' lives interesting.  Rather, this architecture is a means to provide scalable memory bandwidth.  However, to achieve scalable memory bandwidth, system and application software must arrange for a large majority of the memory references \[cache misses\] to be to "local" memory--memory on the same cell, if any--or to the closest cell with memory.

This leads to the Linux software view of a NUMA system:

Linux divides the system's hardware resources into multiple software abstractions called "nodes".  Linux maps the nodes onto the physical cells of the hardware platform, abstracting away some of the details for some architectures.  As with physical cells, software nodes may contain 0 or more CPUs, memory and/or IO buses.  And, again, memory accesses to memory on "closer" nodes--nodes that map to closer cells--will generally experience faster access times and higher effective bandwidth than accesses to more remote cells.

For some architectures, such as x86, Linux will "hide" any node representing a physical cell that has no memory attached, and reassign any CPUs attached to that cell to a node representing a cell that does have memory.  Thus, on these architectures, one cannot assume that all CPUs that Linux associates with a given node will see the same local memory access times and bandwidth.

In addition, for some architectures, again x86 is an example, Linux supports the emulation of additional nodes.  For NUMA emulation, linux will carve up the existing nodes--or the system memory for non-NUMA platforms--into multiple nodes.  Each emulated node will manage a fraction of the underlying cells' physical memory.  NUMA emulation is useful for testing NUMA kernel and application features on non-NUMA platforms, and as a sort of memory resource management mechanism when used together with cpusets. \[see [Documentation/admin-guide/cgroup-v1/cpusets.rst](/kernel/administration/admin-guide/cgroup-v1/cpusets.md)\]

For each node with memory, Linux constructs an independent memory management subsystem, complete with its own free page lists, in-use page lists, usage statistics and locks to mediate access.  In addition, Linux constructs for each memory zone \[one or more of DMA, DMA32, NORMAL, HIGH_MEMORY, MOVABLE\], an ordered "zonelist".  A zonelist specifies the zones/nodes to visit when a selected zone/node cannot satisfy the allocation request.  This situation, when a zone has no available memory to satisfy a request, is called "overflow" or "fallback".

Because some nodes contain multiple zones containing different types of memory, Linux must decide whether to order the zonelists such that allocations fall back to the same zone type on a different node, or to a different zone type on the same node.  This is an important consideration because some zones, such as DMA or DMA32, represent relatively scarce resources.  Linux chooses a default Node ordered zonelist. This means it tries to fallback to other zones from the same node before using remote nodes which are ordered by NUMA distance.

By default, Linux will attempt to satisfy memory allocation requests from the node to which the CPU that executes the request is assigned.  Specifically, Linux will attempt to allocate from the first node in the appropriate zonelist for the node where the request originates.  This is called "local allocation." If the "local" node cannot satisfy the request, the kernel will examine other nodes' zones in the selected zonelist looking for the first zone in the list that can satisfy the request.

Local allocation will tend to keep subsequent access to the allocated memory "local" to the underlying physical resources and off the system interconnect-- as long as the task on whose behalf the kernel allocated some memory does not later migrate away from that memory.  The Linux scheduler is aware of the NUMA topology of the platform--embodied in the "scheduling domains" data structures \[see [Documentation/scheduler/sched-domains.rst](/kernel/internals/scheduler/sched-domains.md)\]--and the scheduler attempts to minimize task migration to distant scheduling domains.  However, the scheduler does not take a task's NUMA footprint into account directly. Thus, under sufficient imbalance, tasks can migrate between nodes, remote from their initial node and kernel data structures.

System administrators and application designers can restrict a task's migration to improve NUMA locality using various CPU affinity command line interfaces, such as taskset(1) and numactl(1), and program interfaces such as sched_setaffinity(2).  Further, one can modify the kernel's default local allocation behavior using Linux NUMA memory policy. \[see [Documentation/admin-guide/mm/numa_memory_policy.rst](/kernel/administration/admin-guide/mm/numa-memory-policy.md)\].

System administrators can restrict the CPUs and nodes' memories that a non- privileged user can specify in the scheduling or NUMA commands and functions using control groups and CPUsets.  \[see [Documentation/admin-guide/cgroup-v1/cpusets.rst](/kernel/administration/admin-guide/cgroup-v1/cpusets.md)\]

On architectures that do not hide memoryless nodes, Linux will include only zones \[nodes\] with memory in the zonelists.  This means that for a memoryless node the "local memory node"--the node of the first zone in CPU's node's zonelist--will not be the node itself.  Rather, it will be the node that the kernel selected as the nearest node with memory when it built the zonelists. So, default, local allocations will succeed with the kernel supplying the closest available memory.  This is a consequence of the same mechanism that allows such allocations to fallback to other nearby nodes when a node that does contain memory overflows.

Some kernel allocations do not want or cannot tolerate this allocation fallback behavior.  Rather they want to be sure they get memory from the specified node or get notified that the node has no free memory.  This is usually the case when a subsystem allocates per CPU memory resources, for example.

A typical model for making such an allocation is to obtain the node id of the node to which the "current CPU" is attached using one of the kernel's numa_node_id() or CPU_to_node() functions and then request memory from only the node id returned.  When such an allocation fails, the requesting subsystem may revert to its own fallback path.  The slab kernel memory allocator is an example of this.  Or, the subsystem may choose to disable or not to enable itself on allocation failure.  The kernel profiling subsystem is an example of this.

If the architecture supports--does not hide--memoryless nodes, then CPUs attached to memoryless nodes would always incur the fallback path overhead or some subsystems would fail to initialize if they attempted to allocated memory exclusively from a node without memory.  To support such architectures transparently, kernel subsystems can use the numa_mem_id() or cpu_to_mem() function to locate the "local memory node" for the calling or specified CPU.  Again, this is the same node from which default, local page allocations will be attempted.

---

# Out Of Memory Handling

_Peios Kernel / Internals / Memory management_

> Reference for Out Of Memory Handling.

<a id="rst-out-of-memory-handling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Overcommit Accounting

_Peios Kernel / Internals / Memory management_

> The Linux kernel supports the following overcommit handling modes

<a id="rst-overcommit-accounting"></a>

The Linux kernel supports the following overcommit handling modes

- **0**

  Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. This is the default.

- **1**

  Always overcommit. Appropriate for some scientific applications. Classic example is code using sparse arrays and just relying on the virtual memory consisting almost entirely of zero pages.

- **2**

  Don't overcommit. The total address space commit for the system is not permitted to exceed swap + a configurable amount (default is 50%) of physical RAM.  Depending on the amount you use, in most situations this means a process will not be killed while accessing pages but will receive errors on memory allocation as appropriate.

  Useful for applications that want to guarantee their memory allocations will be available in the future without having to initialize every page.

The overcommit policy is set via the sysctl `vm.overcommit_memory`.

The overcommit amount can be set via `vm.overcommit_ratio` (percentage) or `vm.overcommit_kbytes` (absolute value). These only have an effect when `vm.overcommit_memory` is set to 2.

The current overcommit limit and amount committed are viewable in `/proc/meminfo` as CommitLimit and Committed_AS respectively.

<a id="rst-gotchas"></a>

## Gotchas

The C language stack growth does an implicit mremap. If you want absolute guarantees and run close to the edge you MUST mmap your stack for the largest size you think you will need. For typical stack usage this does not matter much but it's a corner case if you really really care

In mode 2 the MAP_NORESERVE flag is ignored.

<a id="rst-how-it-works"></a>

## How It Works

The overcommit is based on the following rules

- **For a file backed map**

  SHARED or READ-only   -       0 cost (the file is the map not swap)  
  PRIVATE WRITABLE      -       size of mapping per instance

- **For an anonymous or `/dev/zero` map**

  SHARED                        -       size of mapping  
  PRIVATE READ-only     -       0 cost (but of little use)  
  PRIVATE WRITABLE      -       size of mapping per instance

- **Additional accounting**

  Pages made writable copies by mmap  
  shmfs memory drawn from the same pool

<a id="rst-status"></a>

## Status

- We account mmap memory mappings

- We account mprotect changes in commit

- We account mremap changes in size

- We account brk

- We account munmap

- We report the commit status in /proc

- Account and check on fork

- Review stack handling/building on exec

- SHMfs accounting

- Implement actual limit enforcement

<a id="rst-to-do"></a>

## To Do

- Account ptrace pages (this is hard)

---

# Page Allocation

_Peios Kernel / Internals / Memory management_

> Reference for Page Allocation.

<a id="rst-page-allocation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Page Cache

_Peios Kernel / Internals / Memory management_

> The page cache is the primary way that the user and the rest of the kernel interact with filesystems. It can be bypassed (e.g. with O_DIRECT), but normal reads, writes and mmaps go through the page cache.

<a id="rst-page-cache"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The page cache is the primary way that the user and the rest of the kernel interact with filesystems.  It can be bypassed (e.g. with O_DIRECT), but normal reads, writes and mmaps go through the page cache.

<a id="rst-folios"></a>

## Folios

The folio is the unit of memory management within the page cache. Operations

---

# Page fragments

_Peios Kernel / Internals / Memory management_

> A page fragment is an arbitrary-length arbitrary-offset area of memory which resides within a 0 or higher order compound page. Multiple fragments within that page are individually refcounted, in the page's reference counter.

<a id="rst-page-fragments"></a>

A page fragment is an arbitrary-length arbitrary-offset area of memory which resides within a 0 or higher order compound page.  Multiple fragments within that page are individually refcounted, in the page's reference counter.

The page_frag functions, page_frag_alloc and page_frag_free, provide a simple allocation framework for page fragments.  This is used by the network stack and network device drivers to provide a backing region of memory for use as either an sk_buff-&gt;head, or to be used in the "frags" portion of skb_shared_info.

In order to make use of the page fragment APIs a backing page fragment cache is needed.  This provides a central point for the fragment allocation and tracks allows multiple calls to make use of a cached page.  The advantage to doing this is that multiple calls to get_page can be avoided which can be expensive at allocation time.  However due to the nature of this caching it is required that any calls to the cache be protected by either a per-cpu limitation, or a per-cpu limitation and forcing interrupts to be disabled when executing the fragment allocation.

The network stack uses two separate caches per CPU to handle fragment allocation.  The netdev_alloc_cache is used by callers making use of the netdev_alloc_frag and \__netdev_alloc_skb calls.  The napi_alloc_cache is used by callers of the \__napi_alloc_frag and napi_alloc_skb calls.  The main difference between these two calls is the context in which they may be called.  The "netdev" prefixed functions are usable in any context as these functions will disable interrupts, while the "napi" prefixed functions are only usable within the softirq context.

Many network device drivers use a similar methodology for allocating page fragments, but the page fragments are cached at the ring or descriptor level.  In order to enable these cases it is necessary to provide a generic way of tearing down a page cache.  For this reason \__page_frag_cache_drain was implemented.  It allows for freeing multiple references from a single page via a single call.  The advantage to doing this is that it allows for cleaning up the multiple references that were added to a page in order to avoid calling get_page per allocation.

Alexander Duyck, Nov 29, 2016.

---

# Page migration

_Peios Kernel / Internals / Memory management_

> Page migration allows moving the physical location of pages between nodes in a NUMA system while the process is running. This means that the virtual addresses that the process sees do not change. However, the system rearranges the physical…

<a id="rst-page-migration"></a>

Page migration allows moving the physical location of pages between nodes in a NUMA system while the process is running. This means that the virtual addresses that the process sees do not change. However, the system rearranges the physical location of those pages.

Also see [Documentation/mm/hmm.rst](/kernel/internals/mm/hmm.md) for migrating pages to or from device private memory.

The main intent of page migration is to reduce the latency of memory accesses by moving pages near to the processor where the process accessing that memory is running.

Page migration allows a process to manually relocate the node on which its pages are located through the MF_MOVE and MF_MOVE_ALL options while setting a new memory policy via mbind(). The pages of a process can also be relocated from another process using the sys_migrate_pages() function call. The migrate_pages() function call takes two sets of nodes and moves pages of a process that are located on the from nodes to the destination nodes. Page migration functions are provided by the numactl package by Andi Kleen (a version later than 0.9.3 is required. Get it from [https://github.com/numactl/numactl.git](<https://github.com/numactl/numactl.git>)). numactl provides libnuma which provides an interface similar to other NUMA functionality for page migration.  cat `/proc/<pid>/numa_maps` allows an easy review of where the pages of a process are located. See also the numa_maps documentation in the proc(5) man page.

Manual migration is useful if for example the scheduler has relocated a process to a processor on a distant node. A batch scheduler or an administrator may detect the situation and move the pages of the process nearer to the new processor. The kernel itself only provides manual page migration support. Automatic page migration may be implemented through user space processes that move pages. A special function call "move_pages" allows the moving of individual pages within a process. For example, A NUMA profiler may obtain a log showing frequent off-node accesses and may use the result to move pages to more advantageous locations.

Larger installations usually partition the system using cpusets into sections of nodes. Paul Jackson has equipped cpusets with the ability to move pages when a task is moved to another cpuset (See [CPUSETS](</kernel/administration/admin-guide/cgroup-v1/cpusets.md#rst-cpusets-1>)). Cpusets allow the automation of process locality. If a task is moved to a new cpuset then also all its pages are moved with it so that the performance of the process does not sink dramatically. Also the pages of processes in a cpuset are moved if the allowed memory nodes of a cpuset are changed.

Page migration allows the preservation of the relative location of pages within a group of nodes for all migration techniques which will preserve a particular memory allocation pattern generated even after migrating a process. This is necessary in order to preserve the memory latencies. Processes will run with similar performance after migration.

Page migration occurs in several steps. First a high level description for those trying to use migrate_pages() from the kernel (for userspace usage see the Andi Kleen's numactl package mentioned above) and then a low level description of how the low level details work.

<a id="rst-in-kernel-use-of-migrate-pages"></a>

## In kernel use of migrate_pages()

1. Remove folios from the LRU.

   Lists of folios to be migrated are generated by scanning over folios and moving them into lists. This is done by calling folio_isolate_lru(). Calling folio_isolate_lru() increases the references to the folio so that it cannot vanish while the folio migration occurs. It also prevents the swapper or other scans from encountering the folio.

2. We need to have a function of type new_folio_t that can be passed to migrate_pages(). This function should figure out how to allocate the correct new folio given the old folio.

3. The migrate_pages() function is called which attempts to do the migration. It will call the function to allocate the new folio for each folio that is considered for moving.

<a id="rst-how-migrate-pages-works"></a>

## How migrate_pages() works

migrate_pages() does several passes over its list of folios. A folio is moved if all references to a folio are removable at the time. The folio has already been removed from the LRU via folio_isolate_lru() and the refcount is increased so that the folio cannot be freed while folio migration occurs.

Steps:

1. Lock the page to be migrated.

2. Ensure that writeback is complete.

3. Lock the new page that we want to move to. It is locked so that accesses to this (not yet up-to-date) page immediately block while the move is in progress.

4. All the page table references to the page are converted to migration entries. This decreases the mapcount of a page. If the resulting mapcount is not zero then we do not migrate the page. All user space processes that attempt to access the page will now wait on the page lock or wait for the migration page table entry to be removed.

5. The i_pages lock is taken. This will cause all processes trying to access the page via the mapping to block on the spinlock.

6. The refcount of the page is examined and we back out if references remain. Otherwise, we know that we are the only one referencing this page.

7. The radix tree is checked and if it does not contain the pointer to this page then we back out because someone else modified the radix tree.

8. The new page is prepped with some settings from the old page so that accesses to the new page will discover a page with the correct settings.

9. The radix tree is changed to point to the new page.

10. The reference count of the old page is dropped because the address space reference is gone. A reference to the new page is established because the new page is referenced by the address space.

11. The i_pages lock is dropped. With that lookups in the mapping become possible again. Processes will move from spinning on the lock to sleeping on the locked new page.

12. The page contents are copied to the new page.

13. The remaining page flags are copied to the new page.

14. The old page flags are cleared to indicate that the page does not provide any information anymore.

15. Queued up writeback on the new page is triggered.

16. If migration entries were inserted into the page table, then replace them with real ptes. Doing so will enable access for user space processes not already waiting for the page lock.

17. The page locks are dropped from the old and new page. Processes waiting on the page lock will redo their page faults and will reach the new page.

18. The new page is moved to the LRU and can be scanned by the swapper, etc. again.

<a id="rst-movable-ops-page-migration"></a>

## movable_ops page migration

Selected typed, non-folio pages (e.g., pages inflated in a memory balloon, zsmalloc pages) can be migrated using the movable_ops migration framework.

The "struct movable_operations" provide callbacks specific to a page type for isolating, migrating and un-isolating (putback) these pages.

Once a page is indicated as having movable_ops, that condition must not change until the page was freed back to the buddy. This includes not changing/clearing the page type and not changing/clearing the PG_movable_ops page flag.

Arbitrary drivers cannot currently make use of this framework, as it requires:

- **(a)** a page type

- **(b)** indicating them as possibly having movable_ops in page_has_movable_ops() based on the page type

- **(c)** returning the movable_ops from page_movable_ops() based on the page type

- **(d)** not reusing the PG_movable_ops and PG_movable_ops_isolated page flags for other purposes

For example, balloon drivers can make use of this framework through the balloon-compaction infrastructure residing in the core kernel.

<a id="rst-monitoring-migration"></a>

## Monitoring Migration

The following events (counters) can be used to monitor page migration.

1. PGMIGRATE_SUCCESS: Normal page migration success. Each count means that a page was migrated. If the page was a non-THP and non-hugetlb page, then this counter is increased by one. If the page was a THP or hugetlb, then this counter is increased by the number of THP or hugetlb subpages. For example, migration of a single 2MB THP that has 4KB-size base pages (subpages) will cause this counter to increase by 512.

2. PGMIGRATE_FAIL: Normal page migration failure. Same counting rules as for PGMIGRATE_SUCCESS, above: this will be increased by the number of subpages, if it was a THP or hugetlb.

3. THP_MIGRATION_SUCCESS: A THP was migrated without being split.

4. THP_MIGRATION_FAIL: A THP could not be migrated nor it could be split.

5. THP_MIGRATION_SPLIT: A THP was migrated, but not as such: first, the THP had to be split. After splitting, a migration retry was used for its sub-pages.

THP_MIGRATION\_\* events also update the appropriate PGMIGRATE_SUCCESS or PGMIGRATE_FAIL events. For example, a THP migration failure will cause both THP_MIGRATION_FAIL and PGMIGRATE_FAIL to increase.

Christoph Lameter, May 8, 2006. Minchan Kim, Mar 28, 2016.


#### <a id="c-struct-movable_operations"></a>`struct movable_operations`

Driver page migration

**Definition**

```c
struct movable_operations {
    bool (*isolate_page)(struct page *, isolate_mode_t);
    int (*migrate_page)(struct page *dst, struct page *src, enum migrate_mode);
    void (*putback_page)(struct page *);
};
```

**Members**

- `isolate_page`: The VM calls this function to prepare the page to be moved.  The page
  is locked and the driver should not unlock it.  The driver should
  return `true` if the page is movable and `false` if it is not
  currently movable.  After this function returns, the VM uses the
  page->lru field, so the driver must preserve any information which
  is usually stored here.
- `migrate_page`: After isolation, the VM calls this function with the isolated
  **src** page.  The driver should copy the contents of the
  **src** page to the **dst** page and set up the fields of **dst** page.
  Both pages are locked.
  If page migration is successful, the driver should return 0.
  If the driver cannot migrate the page at the moment, it can return
  -EAGAIN.  The VM interprets this as a temporary migration failure and
  will retry it later.  Any other error value is a permanent migration
  failure and migration will not be retried.
  The driver shouldn't touch the **src->lru** field while in the
  `migrate_page()` function.  It may write to **dst->lru**.
- `putback_page`: If migration fails on the isolated page, the VM informs the driver
  that the page is no longer a candidate for migration by calling
  this function.  The driver should put the isolated page back into
  its own data structure.

---

# page owner: Tracking about who allocated each page

_Peios Kernel / Internals / Memory management_

> page owner is for the tracking about who allocated each page. It can be used to debug memory leak or to find a memory hogger. When allocation happens, information about allocation such as call stack and order of pages is stored into…

<a id="rst-page-owner-tracking-about-who-allocated-each-page"></a>

<a id="rst-introduction"></a>

## Introduction

page owner is for the tracking about who allocated each page. It can be used to debug memory leak or to find a memory hogger. When allocation happens, information about allocation such as call stack and order of pages is stored into certain storage for each page. When we need to know about status of all pages, we can get and analyze this information.

Although we already have tracepoint for tracing page allocation/free, using it for analyzing who allocate each page is rather complex. We need to enlarge the trace buffer for preventing overlapping until userspace program launched. And, launched program continually dump out the trace buffer for later analysis and it would change system behaviour with more possibility rather than just keeping it in memory, so bad for debugging.

page owner can also be used for various purposes. For example, accurate fragmentation statistics can be obtained through gfp flag information of each page. It is already implemented and activated if page owner is enabled. Other usages are more than welcome.

It can also be used to show all the stacks and their current number of allocated base pages, which gives us a quick overview of where the memory is going without the need to screen through all the pages and match the allocation and free operation. It's also possible to show only a numeric identifier of all the stacks (without stack traces) and their number of allocated base pages (faster to read and parse, eg, for monitoring) that can be matched with stacks later (show_handles and show_stacks_handles).

page owner is disabled by default. So, if you'd like to use it, you need to add "page_owner=on" to your boot cmdline. If the kernel is built with page owner and page owner is disabled in runtime due to not enabling boot option, runtime overhead is marginal. If disabled in runtime, it doesn't require memory to store owner information, so there is no runtime memory overhead. And, page owner inserts just two unlikely branches into the page allocator hotpath and if not enabled, then allocation is done like as the kernel without page owner. These two unlikely branches should not affect to allocation performance, especially if the static keys jump label patching functionality is available. Following is the kernel's code size change due to this facility.

Although enabling page owner increases kernel size by several kilobytes, most of this code is outside page allocator and its hot path. Building the kernel with page owner and turning it on if needed would be great option to debug kernel memory problem.

There is one notice that is caused by implementation detail. page owner stores information into the memory from struct page extension. This memory is initialized some time later than that page allocator starts in sparse memory system, so, until initialization, many pages can be allocated and they would have no owner information. To fix it up, these early allocated pages are investigated and marked as allocated in initialization phase. Although it doesn't mean that they have the right owner information, at least, we can tell whether the page is allocated or not, more accurately. On 2GB memory x86-64 VM box, 13343 early allocated pages are caught and marked, although they are mostly allocated from struct page extension feature. Anyway, after that, no page is left in un-tracking state.

<a id="rst-usage"></a>

## Usage

1. Build user-space helper:



   ```text
   cd tools/mm
   make page_owner_sort
   ```

2. Enable page owner: add "page_owner=on" to boot cmdline.

3. Do the job that you want to debug.

4. Analyze information from page owner:



   ```text
   cat /sys/kernel/debug/page_owner_stacks/show_stacks > stacks.txt
   cat stacks.txt
    post_alloc_hook+0x177/0x1a0
    get_page_from_freelist+0xd01/0xd80
    __alloc_pages+0x39e/0x7e0
    allocate_slab+0xbc/0x3f0
    ___slab_alloc+0x528/0x8a0
    kmem_cache_alloc+0x224/0x3b0
    sk_prot_alloc+0x58/0x1a0
    sk_alloc+0x32/0x4f0
    inet_create+0x427/0xb50
    __sock_create+0x2e4/0x650
    inet_ctl_sock_create+0x30/0x180
    igmp_net_init+0xc1/0x130
    ops_init+0x167/0x410
    setup_net+0x304/0xa60
    copy_net_ns+0x29b/0x4a0
    create_new_namespaces+0x4a1/0x820
   nr_base_pages: 16
   ...
   ...
   echo 7000 > /sys/kernel/debug/page_owner_stacks/count_threshold
   cat /sys/kernel/debug/page_owner_stacks/show_stacks> stacks_7000.txt
   cat stacks_7000.txt
    post_alloc_hook+0x177/0x1a0
    get_page_from_freelist+0xd01/0xd80
    __alloc_pages+0x39e/0x7e0
    alloc_pages_mpol+0x22e/0x490
    folio_alloc+0xd5/0x110
    filemap_alloc_folio+0x78/0x230
    page_cache_ra_order+0x287/0x6f0
    filemap_get_pages+0x517/0x1160
    filemap_read+0x304/0x9f0
    xfs_file_buffered_read+0xe6/0x1d0 [xfs]
    xfs_file_read_iter+0x1f0/0x380 [xfs]
    __kernel_read+0x3b9/0x730
    kernel_read_file+0x309/0x4d0
    __do_sys_finit_module+0x381/0x730
    do_syscall_64+0x8d/0x150
    entry_SYSCALL_64_after_hwframe+0x62/0x6a
   nr_base_pages: 20824
   ...

   cat /sys/kernel/debug/page_owner_stacks/show_handles > handles_7000.txt
   cat handles_7000.txt
   handle: 42
   nr_base_pages: 20824
   ...

   cat /sys/kernel/debug/page_owner_stacks/show_stacks_handles > stacks_handles.txt
   cat stacks_handles.txt
    post_alloc_hook+0x177/0x1a0
    get_page_from_freelist+0xd01/0xd80
    __alloc_pages+0x39e/0x7e0
    alloc_pages_mpol+0x22e/0x490
    folio_alloc+0xd5/0x110
    filemap_alloc_folio+0x78/0x230
    page_cache_ra_order+0x287/0x6f0
    filemap_get_pages+0x517/0x1160
    filemap_read+0x304/0x9f0
    xfs_file_buffered_read+0xe6/0x1d0 [xfs]
    xfs_file_read_iter+0x1f0/0x380 [xfs]
    __kernel_read+0x3b9/0x730
    kernel_read_file+0x309/0x4d0
    __do_sys_finit_module+0x381/0x730
    do_syscall_64+0x8d/0x150
    entry_SYSCALL_64_after_hwframe+0x62/0x6a
   handle: 42
   ...

   cat /sys/kernel/debug/page_owner > page_owner_full.txt
   ./page_owner_sort page_owner_full.txt sorted_page_owner.txt
   ```

   The general output of `page_owner_full.txt` is as follows:



   ```text
       Page allocated via order XXX, ...
       PFN XXX ...
       // Detailed stack

       Page allocated via order XXX, ...
       PFN XXX ...
       // Detailed stack
   By default, it will do full pfn dump, to start with a given pfn,
   page_owner supports fseek.

   FILE *fp = fopen("/sys/kernel/debug/page_owner", "r");
   fseek(fp, pfn_start, SEEK_SET);
   ```

   The `page_owner_sort` tool ignores `PFN` rows, puts the remaining rows in buf, uses regexp to extract the page order value, counts the times and pages of buf, and finally sorts them according to the parameter(s).

   See the result about who allocated each page in the `sorted_page_owner.txt`. General output:



   ```text
   XXX times, XXX pages:
   Page allocated via order XXX, ...
   // Detailed stack
   ```

   By default, `page_owner_sort` is sorted according to the times of buf. If you want to sort by the page nums of buf, use the `-m` parameter. The detailed parameters are:

   fundamental function:



   ```text
   Sort:
           -a              Sort by memory allocation time.
           -m              Sort by total memory.
           -p              Sort by pid.
           -P              Sort by tgid.
           -n              Sort by task command name.
           -r              Sort by memory release time.
           -s              Sort by stack trace.
           -t              Sort by times (default).
           --sort <order>  Specify sorting order.  Sorting syntax is [+|-]key[,[+|-]key[,...]].
                           Choose a key from the **STANDARD FORMAT SPECIFIERS** section. The "+" is
                           optional since default direction is increasing numerical or lexicographic
                           order. Mixed use of abbreviated and complete-form of keys is allowed.

           Examples:
                           ./page_owner_sort <input> <output> --sort=n,+pid,-tgid
                           ./page_owner_sort <input> <output> --sort=at
   ```

   additional function:



   ```text
   Cull:
           --cull <rules>
                           Specify culling rules.Culling syntax is key[,key[,...]].Choose a
                           multi-letter key from the **STANDARD FORMAT SPECIFIERS** section.

           <rules> is a single argument in the form of a comma-separated list,
           which offers a way to specify individual culling rules.  The recognized
           keywords are described in the **STANDARD FORMAT SPECIFIERS** section below.
           <rules> can be specified by the sequence of keys k1,k2, ..., as described in
           the STANDARD SORT KEYS section below. Mixed use of abbreviated and
           complete-form of keys is allowed.

           Examples:
                           ./page_owner_sort <input> <output> --cull=stacktrace
                           ./page_owner_sort <input> <output> --cull=st,pid,name
                           ./page_owner_sort <input> <output> --cull=n,f

   Filter:
           -f              Filter out the information of blocks whose memory has been released.

   Select:
           --pid <pidlist>         Select by pid. This selects the blocks whose process ID
                                   numbers appear in <pidlist>.
           --tgid <tgidlist>       Select by tgid. This selects the blocks whose thread
                                   group ID numbers appear in <tgidlist>.
           --name <cmdlist>        Select by task command name. This selects the blocks whose
                                   task command name appear in <cmdlist>.

           <pidlist>, <tgidlist>, <cmdlist> are single arguments in the form of a comma-separated list,
           which offers a way to specify individual selecting rules.


           Examples:
                           ./page_owner_sort <input> <output> --pid=1
                           ./page_owner_sort <input> <output> --tgid=1,2,3
                           ./page_owner_sort <input> <output> --name name1,name2
   ```

<a id="rst-standard-format-specifiers"></a>

## STANDARD FORMAT SPECIFIERS



```text
For --sort option:

      KEY             LONG            DESCRIPTION
      p               pid             process ID
      tg              tgid            thread group ID
      n               name            task command name
      st              stacktrace      stack trace of the page allocation
      T               txt             full text of block
      ft              free_ts         timestamp of the page when it was released
      at              alloc_ts        timestamp of the page when it was allocated
      ator            allocator       memory allocator for pages

For --cull option:

      KEY             LONG            DESCRIPTION
      p               pid             process ID
      tg              tgid            thread group ID
      n               name            task command name
      f               free            whether the page has been released or not
      st              stacktrace      stack trace of the page allocation
      ator            allocator       memory allocator for pages
```

---

# Page Reclaim

_Peios Kernel / Internals / Memory management_

> Reference for Page Reclaim.

<a id="rst-page-reclaim"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Page Table Check

_Peios Kernel / Internals / Memory management_

> Page table check allows to harden the kernel by ensuring that some types of the memory corruptions are prevented.

<a id="rst-page-table-check"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Page table check allows to harden the kernel by ensuring that some types of the memory corruptions are prevented.

Page table check performs extra verifications at the time when new pages become accessible from the userspace by getting their page table entries (PTEs PMDs etc.) added into the table.

In case of most detected corruption, the kernel is crashed. There is a small performance and memory overhead associated with the page table check. Therefore, it is disabled by default, but can be optionally enabled on systems where the extra hardening outweighs the performance costs. Also, because page table check is synchronous, it can help with debugging double map memory corruption issues, by crashing kernel at the time wrong mapping occurs instead of later which is often the case with memory corruptions bugs.

It can also be used to do page table entry checks over various flags, dump warnings when illegal combinations of entry flags are detected.  Currently, userfaultfd is the only user of such to sanity check wr-protect bit against any writable flags.  Illegal flag combinations will not directly cause data corruption in this case immediately, but that will cause read-only data to be writable, leading to corrupt when the page content is later modified.

<a id="rst-double-mapping-detection-logic"></a>

## Double mapping detection logic


<table>
<thead>
<tr>
<th>


Current Mapping

</th>
<th>


New mapping

</th>
<th>


Permissions

</th>
<th>


Rule

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Anonymous

</td>
<td>


Anonymous

</td>
<td>


Read

</td>
<td>


Allow

</td>
</tr>
<tr>
<td>


Anonymous

</td>
<td>


Anonymous

</td>
<td>


Read / Write

</td>
<td>


Prohibit

</td>
</tr>
<tr>
<td>


Anonymous

</td>
<td>


Named

</td>
<td>


Any

</td>
<td>


Prohibit

</td>
</tr>
<tr>
<td>


Named

</td>
<td>


Anonymous

</td>
<td>


Any

</td>
<td>


Prohibit

</td>
</tr>
<tr>
<td>


Named

</td>
<td>


Named

</td>
<td>


Any

</td>
<td>


Allow

</td>
</tr>
</tbody>
</table>

<a id="rst-enabling-page-table-check"></a>

## Enabling Page Table Check

Build kernel with:

- PAGE_TABLE_CHECK=y Note, it can only be enabled on platforms where ARCH_SUPPORTS_PAGE_TABLE_CHECK is available.

- Boot with 'page_table_check=on' kernel parameter.

Optionally, build kernel with PAGE_TABLE_CHECK_ENFORCED in order to have page table support without extra kernel parameter.

<a id="rst-implementation-notes"></a>

## Implementation notes

We specifically decided not to use VMA information in order to avoid relying on MM states (except for limited "struct page" info). The page table check is a separate from Linux-MM state machine that verifies that the user accessible pages are not falsely shared.

PAGE_TABLE_CHECK depends on EXCLUSIVE_SYSTEM_RAM. The reason is that without EXCLUSIVE_SYSTEM_RAM, users are allowed to map arbitrary physical memory regions into the userspace via /dev/mem. At the same time, pages may change their properties (e.g., from anonymous pages to named pages) while they are still being mapped in the userspace, leading to "corruption" detected by the page table check.

Even with EXCLUSIVE_SYSTEM_RAM, I/O pages may be still allowed to be mapped via /dev/mem. However, these pages are always considered as named pages, so they won't break the logic used in the page table check.

---

# Page Tables

_Peios Kernel / Internals / Memory management_

> Paged virtual memory was invented along with virtual memory as a concept in 1962 on the Ferranti Atlas Computer which was the first computer with paged virtual memory. The feature migrated to newer computers and became a de facto feature…

<a id="rst-page-tables"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Paged virtual memory was invented along with virtual memory as a concept in 1962 on the Ferranti Atlas Computer which was the first computer with paged virtual memory. The feature migrated to newer computers and became a de facto feature of all Unix-like systems as time went by. In 1985 the feature was included in the Intel 80386, which was the CPU Linux 1.0 was developed on.

Page tables map virtual addresses as seen by the CPU into physical addresses as seen on the external memory bus.

Linux defines page tables as a hierarchy which is currently five levels in height. The architecture code for each supported architecture will then map this to the restrictions of the hardware.

The physical address corresponding to the virtual address is often referenced by the underlying physical page frame. The **page frame number** or **pfn** is the physical address of the page (as seen on the external memory bus) divided by `PAGE_SIZE`.

Physical memory address 0 will be *pfn 0* and the highest pfn will be the last page of physical memory the external address bus of the CPU can address.

With a page granularity of 4KB and an address range of 32 bits, pfn 0 is at address 0x00000000, pfn 1 is at address 0x00001000, pfn 2 is at 0x00002000 and so on until we reach pfn 0xfffff at 0xfffff000. With 16KB pages pfns are at 0x00004000, 0x00008000 ... 0xffffc000 and pfn goes from 0 to 0x3ffff.

As you can see, with 4KB pages the page base address uses bits 12-31 of the address, and this is why `PAGE_SHIFT` in this case is defined as 12 and `PAGE_SIZE` is usually defined in terms of the page shift as `(1 << PAGE_SHIFT)`

Over time a deeper hierarchy has been developed in response to increasing memory sizes. When Linux was created, 4KB pages and a single page table called `swapper_pg_dir` with 1024 entries was used, covering 4MB which coincided with the fact that Torvalds's first computer had 4MB of physical memory. Entries in this single table were referred to as *PTEs* - page table entries.

The software page table hierarchy reflects the fact that page table hardware has become hierarchical and that in turn is done to save page table memory and speed up mapping.

One could of course imagine a single, linear page table with enormous amounts of entries, breaking down the whole memory into single pages. Such a page table would be very sparse, because large portions of the virtual memory usually remains unused. By using hierarchical page tables large holes in the virtual address space does not waste valuable page table memory, because it will suffice to mark large areas as unmapped at a higher level in the page table hierarchy.

Additionally, on modern CPUs, a higher level page table entry can point directly to a physical memory range, which allows mapping a contiguous range of several megabytes or even gigabytes in a single high-level page table entry, taking shortcuts in mapping virtual memory to physical memory: there is no need to traverse deeper in the hierarchy when you find a large mapped range like this.

The page table hierarchy has now developed into this:



```text
+-----+
| PGD |
+-----+
   |
   |   +-----+
   +-->| P4D |
       +-----+
          |
          |   +-----+
          +-->| PUD |
              +-----+
                 |
                 |   +-----+
                 +-->| PMD |
                     +-----+
                        |
                        |   +-----+
                        +-->| PTE |
                            +-----+
```

Symbols on the different levels of the page table hierarchy have the following meaning beginning from the bottom:

- **pte**, `pte_t`, `pteval_t` = **Page Table Entry** - mentioned earlier. The *pte* is an array of `PTRS_PER_PTE` elements of the `pteval_t` type, each mapping a single page of virtual memory to a single page of physical memory. The architecture defines the size and contents of `pteval_t`.

  A typical example is that the `pteval_t` is a 32- or 64-bit value with the upper bits being a **pfn** (page frame number), and the lower bits being some architecture-specific bits such as memory protection.

  The **entry** part of the name is a bit confusing because while in Linux 1.0 this did refer to a single page table entry in the single top level page table, it was retrofitted to be an array of mapping elements when two-level page tables were first introduced, so the *pte* is the lowermost page *table*, not a page table *entry*.

- **pmd**, `pmd_t`, `pmdval_t` = **Page Middle Directory**, the hierarchy right above the *pte*, with `PTRS_PER_PMD` references to the *pte*:s.

- **pud**, `pud_t`, `pudval_t` = **Page Upper Directory** was introduced after the other levels to handle 4-level page tables. It is potentially unused, or *folded* as we will discuss later.

- **p4d**, `p4d_t`, `p4dval_t` = **Page Level 4 Directory** was introduced to handle 5-level page tables after the *pud* was introduced. Now it was clear that we needed to replace *pgd*, *pmd*, *pud* etc with a figure indicating the directory level and that we cannot go on with ad hoc names any more. This is only used on systems which actually have 5 levels of page tables, otherwise it is folded.

- **pgd**, `pgd_t`, `pgdval_t` = **Page Global Directory** - the Linux kernel main page table handling the PGD for the kernel memory is still found in `swapper_pg_dir`, but each userspace process in the system also has its own memory context and thus its own *pgd*, found in `struct mm_struct` which in turn is referenced to in each `struct task_struct`. So tasks have memory context in the form of a `struct mm_struct` and this in turn has a `struct pgt_t *pgd` pointer to the corresponding page global directory.

To repeat: each level in the page table hierarchy is a *array of pointers*, so the **pgd** contains `PTRS_PER_PGD` pointers to the next level below, **p4d** contains `PTRS_PER_P4D` pointers to **pud** items and so on. The number of pointers on each level is architecture-defined.:



```text
      PMD
--> +-----+           PTE
    | ptr |-------> +-----+
    | ptr |-        | ptr |-------> PAGE
    | ptr | \       | ptr |
    | ptr |  \        ...
    | ... |   \
    | ptr |    \         PTE
    +-----+     +----> +-----+
                       | ptr |-------> PAGE
                       | ptr |
                         ...
```

<a id="rst-page-table-folding"></a>

## Page Table Folding

If the architecture does not use all the page table levels, they can be *folded* which means skipped, and all operations performed on page tables will be compile-time augmented to just skip a level when accessing the next lower level.

Page table handling code that wishes to be architecture-neutral, such as the virtual memory manager, will need to be written so that it traverses all of the currently five levels. This style should also be preferred for architecture-specific code, so as to be robust to future changes.

<a id="rst-mmu-tlb-and-page-faults"></a>

## MMU, TLB, and Page Faults

The `Memory Management Unit (MMU)` is a hardware component that handles virtual to physical address translations. It may use relatively small caches in hardware called `Translation Lookaside Buffers (TLBs)` and `Page Walk Caches` to speed up these translations.

When CPU accesses a memory location, it provides a virtual address to the MMU, which checks if there is the existing translation in the TLB or in the Page Walk Caches (on architectures that support them). If no translation is found, MMU uses the page walks to determine the physical address and create the map.

The dirty bit for a page is set (i.e., turned on) when the page is written to. Each page of memory has associated permission and dirty bits. The latter indicate that the page has been modified since it was loaded into memory.

If nothing prevents it, eventually the physical memory can be accessed and the requested operation on the physical frame is performed.

There are several reasons why the MMU can't find certain translations. It could happen because the CPU is trying to access memory that the current task is not permitted to, or because the data is not present into physical memory.

When these conditions happen, the MMU triggers page faults, which are types of exceptions that signal the CPU to pause the current execution and run a special function to handle the mentioned exceptions.

There are common and expected causes of page faults. These are triggered by process management optimization techniques called "Lazy Allocation" and "Copy-on-Write". Page faults may also happen when frames have been swapped out to persistent storage (swap partition or file) and evicted from their physical locations.

These techniques improve memory efficiency, reduce latency, and minimize space occupation. This document won't go deeper into the details of "Lazy Allocation" and "Copy-on-Write" because these subjects are out of scope as they belong to Process Address Management.

Swapping differentiates itself from the other mentioned techniques because it's undesirable since it's performed as a means to reduce memory under heavy pressure.

Swapping can't work for memory mapped by kernel logical addresses. These are a subset of the kernel virtual space that directly maps a contiguous range of physical memory. Given any logical address, its physical address is determined with simple arithmetic on an offset. Accesses to logical addresses are fast because they avoid the need for complex page table lookups at the expenses of frames not being evictable and pageable out.

If the kernel fails to make room for the data that must be present in the physical frames, the kernel invokes the out-of-memory (OOM) killer to make room by terminating lower priority processes until pressure reduces under a safe threshold.

Additionally, page faults may be also caused by code bugs or by maliciously crafted addresses that the CPU is instructed to access. A thread of a process could use instructions to address (non-shared) memory which does not belong to its own address space, or could try to execute an instruction that wants to write to a read-only location.

If the above-mentioned conditions happen in user-space, the kernel sends a `Segmentation Fault` (SIGSEGV) signal to the current thread. That signal usually causes the termination of the thread and of the process it belongs to.

This document is going to simplify and show an high altitude view of how the Linux kernel handles these page faults, creates tables and tables' entries, check if memory is present and, if not, requests to load data from persistent storage or from other devices, and updates the MMU and its caches.

The first steps are architecture dependent. Most architectures jump to `do_page_fault()`, whereas the x86 interrupt handler is defined by the `DEFINE_IDTENTRY_RAW_ERRORCODE()` macro which calls `handle_page_fault()`.

Whatever the routes, all architectures end up to the invocation of `handle_mm_fault()` which, in turn, (likely) ends up calling `__handle_mm_fault()` to carry out the actual work of allocating the page tables.

The unfortunate case of not being able to call `__handle_mm_fault()` means that the virtual address is pointing to areas of physical memory which are not permitted to be accessed (at least from the current context). This condition resolves to the kernel sending the above-mentioned SIGSEGV signal to the process and leads to the consequences already explained.

`__handle_mm_fault()` carries out its work by calling several functions to find the entry's offsets of the upper layers of the page tables and allocate the tables that it may need.

The functions that look for the offset have names like `*_offset()`, where the "\*" is for pgd, p4d, pud, pmd, pte; instead the functions to allocate the corresponding tables, layer by layer, are called `*_alloc`, using the above-mentioned convention to name them after the corresponding types of tables in the hierarchy.

The page table walk may end at one of the middle or upper layers (PMD, PUD).

Linux supports larger page sizes than the usual 4KB (i.e., the so called `huge pages`). When using these kinds of larger pages, higher level pages can directly map them, with no need to use lower level page entries (PTE). Huge pages contain large contiguous physical regions that usually span from 2MB to 1GB. They are respectively mapped by the PMD and PUD page entries.

The huge pages bring with them several benefits like reduced TLB pressure, reduced page table overhead, memory allocation efficiency, and performance improvement for certain workloads. However, these benefits come with trade-offs, like wasted memory and allocation challenges.

At the very end of the walk with allocations, if it didn't return errors, `__handle_mm_fault()` finally calls `handle_pte_fault()`, which via `do_fault()` performs one of `do_read_fault()`, `do_cow_fault()`, `do_shared_fault()`. "read", "cow", "shared" give hints about the reasons and the kind of fault it's handling.

The actual implementation of the workflow is very complex. Its design allows Linux to handle page faults in a way that is tailored to the specific characteristics of each architecture, while still sharing a common overall structure.

To conclude this high altitude view of how Linux handles page faults, let's add that the page faults handler can be disabled and enabled respectively with `pagefault_disable()` and `pagefault_enable()`.

Several code paths make use of the latter two functions because they need to disable traps into the page faults handler, mostly to prevent deadlocks.

---

# Physical Memory

_Peios Kernel / Internals / Memory management_

> Linux is available for a wide range of architectures so there is a need for an architecture-independent abstraction to represent the physical memory. This chapter describes the structures used to manage physical memory in a running system.

<a id="rst-physical-memory"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Linux is available for a wide range of architectures so there is a need for an architecture-independent abstraction to represent the physical memory. This chapter describes the structures used to manage physical memory in a running system.

The first principal concept prevalent in the memory management is [Non-Uniform Memory Access (NUMA)](<https://en.wikipedia.org/wiki/Non-uniform_memory_access>)<a id="rst-non-uniform-memory-access-numa"></a>. With multi-core and multi-socket machines, memory may be arranged into banks that incur a different cost to access depending on the “distance” from the processor. For example, there might be a bank of memory assigned to each CPU or a bank of memory very suitable for DMA near peripheral devices.

Each bank is called a node and the concept is represented under Linux by a `struct pglist_data` even if the architecture is UMA. This structure is always referenced by its typedef `pg_data_t`. A `pg_data_t` structure for a particular node can be referenced by `NODE_DATA(nid)` macro where `nid` is the ID of that node.

For NUMA architectures, the node structures are allocated by the architecture specific code early during boot. Usually, these structures are allocated locally on the memory bank they represent. For UMA architectures, only one static `pg_data_t` structure called `contig_page_data` is used. Nodes will be discussed further in Section [Nodes](<#rst-nodes-1>)

The entire physical address space is partitioned into one or more blocks called zones which represent ranges within memory. These ranges are usually determined by architectural constraints for accessing the physical memory. The memory range within a node that corresponds to a particular zone is described by a `struct zone`. Each zone has one of the types described below.

- `ZONE_DMA` and `ZONE_DMA32` historically represented memory suitable for DMA by peripheral devices that cannot access all of the addressable memory. For many years there are better more and robust interfaces to get memory with DMA specific requirements ([Documentation/core-api/dma-api.rst](/kernel/internals/core-api/dma-api.md)), but `ZONE_DMA` and `ZONE_DMA32` still represent memory ranges that have restrictions on how they can be accessed. Depending on the architecture, either of these zone types or even they both can be disabled at build time using `CONFIG_ZONE_DMA` and `CONFIG_ZONE_DMA32` configuration options. Some 64-bit platforms may need both zones as they support peripherals with different DMA addressing limitations.

- `ZONE_NORMAL` is for normal memory that can be accessed by the kernel all the time. DMA operations can be performed on pages in this zone if the DMA devices support transfers to all addressable memory. `ZONE_NORMAL` is always enabled.

- `ZONE_HIGHMEM` is the part of the physical memory that is not covered by a permanent mapping in the kernel page tables. The memory in this zone is only accessible to the kernel using temporary mappings. This zone is available only on some 32-bit architectures and is enabled with `CONFIG_HIGHMEM`.

- `ZONE_MOVABLE` is for normal accessible memory, just like `ZONE_NORMAL`. The difference is that the contents of most pages in `ZONE_MOVABLE` is movable. That means that while virtual addresses of these pages do not change, their content may move between different physical pages. Often `ZONE_MOVABLE` is populated during memory hotplug, but it may be also populated on boot using one of `kernelcore`, `movablecore` and `movable_node` kernel command line parameters. See [Documentation/mm/page_migration.rst](/kernel/internals/mm/page-migration.md) and [Documentation/admin-guide/mm/memory-hotplug.rst](/kernel/administration/admin-guide/mm/memory-hotplug.md) for additional details.

- `ZONE_DEVICE` represents memory residing on devices such as PMEM and GPU. It has different characteristics than RAM zone types and it exists to provide [struct page](<#rst-pages-1>) and memory map services for device driver identified physical address ranges. `ZONE_DEVICE` is enabled with configuration option `CONFIG_ZONE_DEVICE`.

It is important to note that many kernel operations can only take place using `ZONE_NORMAL` so it is the most performance critical zone. Zones are discussed further in Section [Zones](<#rst-zones-1>).

The relation between node and zone extents is determined by the physical memory map reported by the firmware, architectural constraints for memory addressing and certain parameters in the kernel command line.

For example, with 32-bit kernel on an x86 UMA machine with 2 Gbytes of RAM the entire memory will be on node 0 and there will be three zones: `ZONE_DMA`, `ZONE_NORMAL` and `ZONE_HIGHMEM`:



```text
0                                                            2G
+-------------------------------------------------------------+
|                            node 0                           |
+-------------------------------------------------------------+

0         16M                    896M                        2G
+----------+-----------------------+--------------------------+
| ZONE_DMA |      ZONE_NORMAL      |       ZONE_HIGHMEM       |
+----------+-----------------------+--------------------------+
```

With a kernel built with `ZONE_DMA` disabled and `ZONE_DMA32` enabled and booted with `movablecore=80%` parameter on an arm64 machine with 16 Gbytes of RAM equally split between two nodes, there will be `ZONE_DMA32`, `ZONE_NORMAL` and `ZONE_MOVABLE` on node 0, and `ZONE_NORMAL` and `ZONE_MOVABLE` on node 1:



```text
1G                                9G                         17G
+--------------------------------+ +--------------------------+
|              node 0            | |          node 1          |
+--------------------------------+ +--------------------------+

1G       4G        4200M          9G          9320M          17G
+---------+----------+-----------+ +------------+-------------+
|  DMA32  |  NORMAL  |  MOVABLE  | |   NORMAL   |   MOVABLE   |
+---------+----------+-----------+ +------------+-------------+
```

Memory banks may belong to interleaving nodes. In the example below an x86 machine has 16 Gbytes of RAM in 4 memory banks, even banks belong to node 0 and odd banks belong to node 1:



```text
0              4G              8G             12G            16G
+-------------+ +-------------+ +-------------+ +-------------+
|    node 0   | |    node 1   | |    node 0   | |    node 1   |
+-------------+ +-------------+ +-------------+ +-------------+

0   16M      4G
+-----+-------+ +-------------+ +-------------+ +-------------+
| DMA | DMA32 | |    NORMAL   | |    NORMAL   | |    NORMAL   |
+-----+-------+ +-------------+ +-------------+ +-------------+
```

In this case node 0 will span from 0 to 12 Gbytes and node 1 will span from 4 to 16 Gbytes.

<a id="rst-nodes-1"></a>
<a id="rst-nodes"></a>

## Nodes

As we have mentioned, each node in memory is described by a `pg_data_t` which is a typedef for a `struct pglist_data`. When allocating a page, by default Linux uses a node-local allocation policy to allocate memory from the node closest to the running CPU. As processes tend to run on the same CPU, it is likely the memory from the current node will be used. The allocation policy can be controlled by users as described in [Documentation/admin-guide/mm/numa_memory_policy.rst](/kernel/administration/admin-guide/mm/numa-memory-policy.md).

Most NUMA architectures maintain an array of pointers to the node structures. The actual structures are allocated early during boot when architecture specific code parses the physical memory map reported by the firmware. The bulk of the node initialization happens slightly later in the boot process by free_area_init() function, described later in Section [Initialization](<#rst-initialization-1>).

Along with the node structures, kernel maintains an array of `nodemask_t` bitmasks called `node_states`. Each bitmask in this array represents a set of nodes with particular properties as defined by `enum node_states`:

- **`N_POSSIBLE`**

  The node could become online at some point.

- **`N_ONLINE`**

  The node is online.

- **`N_NORMAL_MEMORY`**

  The node has regular memory.

- **`N_HIGH_MEMORY`**

  The node has regular or high memory. When `CONFIG_HIGHMEM` is disabled aliased to `N_NORMAL_MEMORY`.

- **`N_MEMORY`**

  The node has memory(regular, high, movable)

- **`N_CPU`**

  The node has one or more CPUs

- **`N_GENERIC_INITIATOR`**

  The node has one or more Generic Initiators

For each node that has a property described above, the bit corresponding to the node ID in the `node_states[<property>]` bitmask is set.

For example, for node 2 with normal memory and CPUs, bit 2 will be set in



```text
node_states[N_POSSIBLE]
node_states[N_ONLINE]
node_states[N_NORMAL_MEMORY]
node_states[N_HIGH_MEMORY]
node_states[N_MEMORY]
node_states[N_CPU]
```

For various operations possible with nodemasks please refer to `include/linux/nodemask.h`.

Among other things, nodemasks are used to provide macros for node traversal, namely `for_each_node()` and `for_each_online_node()`.

For instance, to call a function foo() for each online node:



```text
for_each_online_node(nid) {
        pg_data_t *pgdat = NODE_DATA(nid);

        foo(pgdat);
}
```

<a id="rst-node-structure"></a>

### Node structure

The nodes structure `struct pglist_data` is declared in `include/linux/mmzone.h`. Here we briefly describe fields of this structure:

<a id="rst-general"></a>

#### General

- **`node_zones`**

  The zones for this node.  Not all of the zones may be populated, but it is the full list. It is referenced by this node's node_zonelists as well as other node's node_zonelists.

- **`node_zonelists`**

  The list of all zones in all nodes. This list defines the order of zones that allocations are preferred from. The `node_zonelists` is set up by `build_zonelists()` in `mm/page_alloc.c` during the initialization of core memory management structures.

- **`nr_zones`**

  Number of populated zones in this node.

- **`node_mem_map`**

  For UMA systems that use FLATMEM memory model the 0's node `node_mem_map` is array of struct pages representing each physical frame.

- **`node_page_ext`**

  For UMA systems that use FLATMEM memory model the 0's node `node_page_ext` is array of extensions of struct pages. Available only in the kernels built with `CONFIG_PAGE_EXTENSION` enabled.

- **`node_start_pfn`**

  The page frame number of the starting page frame in this node.

- **`node_present_pages`**

  Total number of physical pages present in this node.

- **`node_spanned_pages`**

  Total size of physical page range, including holes.

- **`node_size_lock`**

  A lock that protects the fields defining the node extents. Only defined when at least one of `CONFIG_MEMORY_HOTPLUG` or `CONFIG_DEFERRED_STRUCT_PAGE_INIT` configuration options are enabled. `pgdat_resize_lock()` and `pgdat_resize_unlock()` are provided to manipulate `node_size_lock` without checking for `CONFIG_MEMORY_HOTPLUG` or `CONFIG_DEFERRED_STRUCT_PAGE_INIT`.

- **`node_id`**

  The Node ID (NID) of the node, starts at 0.

- **`totalreserve_pages`**

  This is a per-node reserve of pages that are not available to userspace allocations.

- **`first_deferred_pfn`**

  If memory initialization on large machines is deferred then this is the first PFN that needs to be initialized. Defined only when `CONFIG_DEFERRED_STRUCT_PAGE_INIT` is enabled

- **`deferred_split_queue`**

  Per-node queue of huge pages that their split was deferred. Defined only when `CONFIG_TRANSPARENT_HUGEPAGE` is enabled.

- **`__lruvec`**

  Per-node lruvec holding LRU lists and related parameters. Used only when memory cgroups are disabled. It should not be accessed directly, use `mem_cgroup_lruvec()` to look up lruvecs instead.

<a id="rst-reclaim-control"></a>

#### Reclaim control

See also [Documentation/mm/page_reclaim.rst](/kernel/internals/mm/page-reclaim.md).

- **`kswapd`**

  Per-node instance of kswapd kernel thread.

- **`kswapd_wait`, `pfmemalloc_wait`, `reclaim_wait`**

  Workqueues used to synchronize memory reclaim tasks

- **`nr_writeback_throttled`**

  Number of tasks that are throttled waiting on dirty pages to clean.

- **`nr_reclaim_start`**

  Number of pages written while reclaim is throttled waiting for writeback.

- **`kswapd_order`**

  Controls the order kswapd tries to reclaim

- **`kswapd_highest_zoneidx`**

  The highest zone index to be reclaimed by kswapd

- **`kswapd_failures`**

  Number of runs kswapd was unable to reclaim any pages

- **`min_unmapped_pages`**

  Minimal number of unmapped file backed pages that cannot be reclaimed. Determined by `vm.min_unmapped_ratio` sysctl. Only defined when `CONFIG_NUMA` is enabled.

- **`min_slab_pages`**

  Minimal number of SLAB pages that cannot be reclaimed. Determined by `vm.min_slab_ratio sysctl`. Only defined when `CONFIG_NUMA` is enabled

- **`flags`**

  Flags controlling reclaim behavior.

<a id="rst-compaction-control"></a>

#### Compaction control

- **`kcompactd_max_order`**

  Page order that kcompactd should try to achieve.

- **`kcompactd_highest_zoneidx`**

  The highest zone index to be compacted by kcompactd.

- **`kcompactd_wait`**

  Workqueue used to synchronize memory compaction tasks.

- **`kcompactd`**

  Per-node instance of kcompactd kernel thread.

- **`proactive_compact_trigger`**

  Determines if proactive compaction is enabled. Controlled by `vm.compaction_proactiveness` sysctl.

<a id="rst-statistics"></a>

#### Statistics

- **`per_cpu_nodestats`**

  Per-CPU VM statistics for the node

- **`vm_stat`**

  VM statistics for the node.

<a id="rst-zones-1"></a>
<a id="rst-zones"></a>

## Zones

As we have mentioned, each zone in memory is described by a `struct zone` which is an element of the `node_zones` array of the node it belongs to. `struct zone` is the core data structure of the page allocator. A zone represents a range of physical memory and may have holes.

The page allocator uses the GFP flags, see [Memory Allocation Controls](</kernel/internals/core-api/mm-api.md#rst-mm-api-gfp-flags>), specified by a memory allocation to determine the highest zone in a node from which the memory allocation can allocate memory. The page allocator first allocates memory from that zone, if the page allocator can't allocate the requested amount of memory from the zone, it will allocate memory from the next lower zone in the node, the process continues up to and including the lowest zone. For example, if a node contains `ZONE_DMA32`, `ZONE_NORMAL` and `ZONE_MOVABLE` and the highest zone of a memory allocation is `ZONE_MOVABLE`, the order of the zones from which the page allocator allocates memory is `ZONE_MOVABLE` &gt; `ZONE_NORMAL` &gt; `ZONE_DMA32`.

At runtime, free pages in a zone are in the Per-CPU Pagesets (PCP) or free areas of the zone. The Per-CPU Pagesets are a vital mechanism in the kernel's memory management system. By handling most frequent allocations and frees locally on each CPU, the Per-CPU Pagesets improve performance and scalability, especially on systems with many cores. The page allocator in the kernel employs a two-step strategy for memory allocation, starting with the Per-CPU Pagesets before falling back to the buddy allocator. Pages are transferred between the Per-CPU Pagesets and the global free areas (managed by the buddy allocator) in batches. This minimizes the overhead of frequent interactions with the global buddy allocator.

Architecture specific code calls free_area_init() to initializes zones.

<a id="rst-zone-structure"></a>

### Zone structure

The zones structure `struct zone` is defined in `include/linux/mmzone.h`. Here we briefly describe fields of this structure:

<a id="rst-general-1"></a>

#### General

- **`_watermark`**

  The watermarks for this zone. When the amount of free pages in a zone is below the min watermark, boosting is ignored, an allocation may trigger direct reclaim and direct compaction, it is also used to throttle direct reclaim. When the amount of free pages in a zone is below the low watermark, kswapd is woken up. When the amount of free pages in a zone is above the high watermark, kswapd stops reclaiming (a zone is balanced) when the `NUMA_BALANCING_MEMORY_TIERING` bit of `sysctl_numa_balancing_mode` is not set. The promo watermark is used for memory tiering and NUMA balancing. When the amount of free pages in a zone is above the promo watermark, kswapd stops reclaiming when the `NUMA_BALANCING_MEMORY_TIERING` bit of `sysctl_numa_balancing_mode` is set. The watermarks are set by `__setup_per_zone_wmarks()`. The min watermark is calculated according to `vm.min_free_kbytes` sysctl. The other three watermarks are set according to the distance between two watermarks. The distance itself is calculated taking `vm.watermark_scale_factor` sysctl into account.

- **`watermark_boost`**

  The number of pages which are used to boost watermarks to increase reclaim pressure to reduce the likelihood of future fallbacks and wake kswapd now as the node may be balanced overall and kswapd will not wake naturally.

- **`nr_reserved_highatomic`**

  The number of pages which are reserved for high-order atomic allocations.

- **`nr_free_highatomic`**

  The number of free pages in reserved highatomic pageblocks

- **`lowmem_reserve`**

  The array of the amounts of the memory reserved in this zone for memory allocations. For example, if the highest zone a memory allocation can allocate memory from is `ZONE_MOVABLE`, the amount of memory reserved in this zone for this allocation is `lowmem_reserve[ZONE_MOVABLE]` when attempting to allocate memory from this zone. This is a mechanism the page allocator uses to prevent allocations which could use `highmem` from using too much `lowmem`. For some specialised workloads on `highmem` machines, it is dangerous for the kernel to allow process memory to be allocated from the `lowmem` zone. This is because that memory could then be pinned via the `mlock()` system call, or by unavailability of swapspace. `vm.lowmem_reserve_ratio` sysctl determines how aggressive the kernel is in defending these lower zones. This array is recalculated by `setup_per_zone_lowmem_reserve()` at runtime if `vm.lowmem_reserve_ratio` sysctl changes.

- **`node`**

  The index of the node this zone belongs to. Available only when `CONFIG_NUMA` is enabled because there is only one zone in a UMA system.

- **`zone_pgdat`**

  Pointer to the `struct pglist_data` of the node this zone belongs to.

- **`per_cpu_pageset`**

  Pointer to the Per-CPU Pagesets (PCP) allocated and initialized by `setup_zone_pageset()`. By handling most frequent allocations and frees locally on each CPU, PCP improves performance and scalability on systems with many cores.

- **`pageset_high_min`**

  Copied to the `high_min` of the Per-CPU Pagesets for faster access.

- **`pageset_high_max`**

  Copied to the `high_max` of the Per-CPU Pagesets for faster access.

- **`pageset_batch`**

  Copied to the `batch` of the Per-CPU Pagesets for faster access. The `batch`, `high_min` and `high_max` of the Per-CPU Pagesets are used to calculate the number of elements the Per-CPU Pagesets obtain from the buddy allocator under a single hold of the lock for efficiency. They are also used to decide if the Per-CPU Pagesets return pages to the buddy allocator in page free process.

- **`pageblock_flags`**

  The pointer to the flags for the pageblocks in the zone (see `include/linux/pageblock-flags.h` for flags list). The memory is allocated in `setup_usemap()`. Each pageblock occupies `NR_PAGEBLOCK_BITS` bits. Defined only when `CONFIG_FLATMEM` is enabled. The flags is stored in `mem_section` when `CONFIG_SPARSEMEM` is enabled.

- **`zone_start_pfn`**

  The start pfn of the zone. It is initialized by `calculate_node_totalpages()`.

- **`managed_pages`**

  The present pages managed by the buddy system, which is calculated as: `managed_pages` = `present_pages` - `reserved_pages`, `reserved_pages` includes pages allocated by the memblock allocator. It should be used by page allocator and vm scanner to calculate all kinds of watermarks and thresholds. It is accessed using `atomic_long_xxx()` functions. It is initialized in `free_area_init_core()` and then is reinitialized when memblock allocator frees pages into buddy system.

- **`spanned_pages`**

  The total pages spanned by the zone, including holes, which is calculated as: `spanned_pages` = `zone_end_pfn` - `zone_start_pfn`. It is initialized by `calculate_node_totalpages()`.

- **`present_pages`**

  The physical pages existing within the zone, which is calculated as: `present_pages` = `spanned_pages` - `absent_pages` (pages in holes). It may be used by memory hotplug or memory power management logic to figure out unmanaged pages by checking (`present_pages` - `managed_pages`). Write access to `present_pages` at runtime should be protected by `mem_hotplug_begin/done()`. Any reader who can't tolerant drift of `present_pages` should use `get_online_mems()` to get a stable value. It is initialized by `calculate_node_totalpages()`.

- **`present_early_pages`**

  The present pages existing within the zone located on memory available since early boot, excluding hotplugged memory. Defined only when `CONFIG_MEMORY_HOTPLUG` is enabled and initialized by `calculate_node_totalpages()`.

- **`cma_pages`**

  The pages reserved for CMA use. These pages behave like `ZONE_MOVABLE` when they are not used for CMA. Defined only when `CONFIG_CMA` is enabled.

- **`name`**

  The name of the zone. It is a pointer to the corresponding element of the `zone_names` array.

- **`nr_isolate_pageblock`**

  Number of isolated pageblocks. It is used to solve incorrect freepage counting problem due to racy retrieving migratetype of pageblock. Protected by `zone->lock`. Defined only when `CONFIG_MEMORY_ISOLATION` is enabled.

- **`span_seqlock`**

  The seqlock to protect `zone_start_pfn` and `spanned_pages`. It is a seqlock because it has to be read outside of `zone->lock`, and it is done in the main allocator path. However, the seqlock is written quite infrequently. Defined only when `CONFIG_MEMORY_HOTPLUG` is enabled.

- **`initialized`**

  The flag indicating if the zone is initialized. Set by `init_currently_empty_zone()` during boot.

- **`free_area`**

  The array of free areas, where each element corresponds to a specific order which is a power of two. The buddy allocator uses this structure to manage free memory efficiently. When allocating, it tries to find the smallest sufficient block, if the smallest sufficient block is larger than the requested size, it will be recursively split into the next smaller blocks until the required size is reached. When a page is freed, it may be merged with its buddy to form a larger block. It is initialized by `zone_init_free_lists()`.

- **`unaccepted_pages`**

  The list of pages to be accepted. All pages on the list are `MAX_PAGE_ORDER`. Defined only when `CONFIG_UNACCEPTED_MEMORY` is enabled.

- **`flags`**

  The zone flags. The least three bits are used and defined by `enum zone_flags`. `ZONE_BOOSTED_WATERMARK` (bit 0): zone recently boosted watermarks. Cleared when kswapd is woken. `ZONE_RECLAIM_ACTIVE` (bit 1): kswapd may be scanning the zone. `ZONE_BELOW_HIGH` (bit 2): zone is below high watermark.

- **`lock`**

  The main lock that protects the internal data structures of the page allocator specific to the zone, especially protects `free_area`.

- **`percpu_drift_mark`**

  When free pages are below this point, additional steps are taken when reading the number of free pages to avoid per-cpu counter drift allowing watermarks to be breached. It is updated in `refresh_zone_stat_thresholds()`.

<a id="rst-compaction-control-1"></a>

#### Compaction control

- **`compact_cached_free_pfn`**

  The PFN where compaction free scanner should start in the next scan.

- **`compact_cached_migrate_pfn`**

  The PFNs where compaction migration scanner should start in the next scan. This array has two elements: the first one is used in `MIGRATE_ASYNC` mode, and the other one is used in `MIGRATE_SYNC` mode.

- **`compact_init_migrate_pfn`**

  The initial migration PFN which is initialized to 0 at boot time, and to the first pageblock with migratable pages in the zone after a full compaction finishes. It is used to check if a scan is a whole zone scan or not.

- **`compact_init_free_pfn`**

  The initial free PFN which is initialized to 0 at boot time and to the last pageblock with free `MIGRATE_MOVABLE` pages in the zone. It is used to check if it is the start of a scan.

- **`compact_considered`**

  The number of compactions attempted since last failure. It is reset in `defer_compaction()` when a compaction fails to result in a page allocation success. It is increased by 1 in `compaction_deferred()` when a compaction should be skipped. `compaction_deferred()` is called before `compact_zone()` is called, `compaction_defer_reset()` is called when `compact_zone()` returns `COMPACT_SUCCESS`, `defer_compaction()` is called when `compact_zone()` returns `COMPACT_PARTIAL_SKIPPED` or `COMPACT_COMPLETE`.

- **`compact_defer_shift`**

  The number of compactions skipped before trying again is `1<<compact_defer_shift`. It is increased by 1 in `defer_compaction()`. It is reset in `compaction_defer_reset()` when a direct compaction results in a page allocation success. Its maximum value is `COMPACT_MAX_DEFER_SHIFT`.

- **`compact_order_failed`**

  The minimum compaction failed order. It is set in `compaction_defer_reset()` when a compaction succeeds and in `defer_compaction()` when a compaction fails to result in a page allocation success.

- **`compact_blockskip_flush`**

  Set to true when compaction migration scanner and free scanner meet, which means the `PB_compact_skip` bits should be cleared.

- **`contiguous`**

  Set to true when the zone is contiguous (in other words, no hole).

<a id="rst-statistics-1"></a>

#### Statistics

- **`vm_stat`**

  VM statistics for the zone. The items tracked are defined by `enum zone_stat_item`.

- **`vm_numa_event`**

  VM NUMA event statistics for the zone. The items tracked are defined by `enum numa_stat_item`.

- **`per_cpu_zonestats`**

  Per-CPU VM statistics for the zone. It records VM statistics and VM NUMA event statistics on a per-CPU basis. It reduces updates to the global `vm_stat` and `vm_numa_event` fields of the zone to improve performance.

<a id="rst-pages-1"></a>
<a id="rst-pages"></a>

## Pages

> [!NOTE]
>
> **Stub**
>
> This section is incomplete. Please list and describe the appropriate fields.

<a id="rst-folios-1"></a>
<a id="rst-folios"></a>

## Folios

> [!NOTE]
>
> **Stub**
>
> This section is incomplete. Please list and describe the appropriate fields.

<a id="rst-initialization-1"></a>
<a id="rst-initialization"></a>

## Initialization

> [!NOTE]
>
> **Stub**
>
> This section is incomplete. Please list and describe the appropriate fields.

---

# Process Addresses

_Peios Kernel / Internals / Memory management_

> Userland memory ranges are tracked by the kernel via Virtual Memory Areas or 'VMA's of type !struct vm_area_struct.

<a id="rst-process-addresses"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Userland memory ranges are tracked by the kernel via Virtual Memory Areas or 'VMA's of type `!struct vm_area_struct`.

Each VMA describes a virtually contiguous memory range with identical attributes, each described by a `!struct vm_area_struct` object. Userland access outside of VMAs is invalid except in the case where an adjacent stack VMA could be extended to contain the accessed address.

All VMAs are contained within one and only one virtual address space, described by a `!struct mm_struct` object which is referenced by all tasks (that is, threads) which share the virtual address space. We refer to this as the `!mm`.

Each mm object contains a maple tree data structure which describes all VMAs within the virtual address space.

> [!NOTE]
>
> An exception to this is the 'gate' VMA which is provided by architectures which use `!vsyscall` and is a global static object which does not belong to any specific mm.

<a id="rst-locking"></a>

## Locking

The kernel is designed to be highly scalable against concurrent read operations on VMA **metadata** so a complicated set of locks are required to ensure memory corruption does not occur.

> [!NOTE]
>
> Locking VMAs for their metadata does not have any impact on the memory they describe nor the page tables that map them.

<a id="rst-terminology"></a>

### Terminology

- **mmap locks** - Each MM has a read/write semaphore `!mmap_lock` which locks at a process address space granularity which can be acquired via `!mmap_read_lock()`, `!mmap_write_lock()` and variants.

- **VMA locks** - The VMA lock is at VMA granularity (of course) which behaves as a read/write semaphore in practice. A VMA read lock is obtained via `!lock_vma_under_rcu()` (and unlocked via `!vma_end_read()`) and a write lock via vma_start_write() or vma_start_write_killable() (all VMA write locks are unlocked automatically when the mmap write lock is released). To take a VMA write lock you **must** have already acquired an `!mmap_write_lock()`.

- **rmap locks** - When trying to access VMAs through the reverse mapping via a `!struct address_space` or `!struct anon_vma` object (reachable from a folio via `!folio->mapping`). VMAs must be stabilised via `!anon_vma_[try]lock_read()` or `!anon_vma_[try]lock_write()` for anonymous memory and `!i_mmap_[try]lock_read()` or `!i_mmap_[try]lock_write()` for file-backed memory. We refer to these locks as the reverse mapping locks, or 'rmap locks' for brevity.

We discuss page table locks separately in the dedicated section below.

The first thing **any** of these locks achieve is to **stabilise** the VMA within the MM tree. That is, guaranteeing that the VMA object will not be deleted from under you nor modified (except for some specific fields described below).

Stabilising a VMA also keeps the address space described by it around.

<a id="rst-lock-usage"></a>

### Lock usage

If you want to **read** VMA metadata fields or just keep the VMA stable, you must do one of the following:

- Obtain an mmap read lock at the MM granularity via `!mmap_read_lock()` (or a suitable variant), unlocking it with a matching `!mmap_read_unlock()` when you're done with the VMA, *or*

- Try to obtain a VMA read lock via `!lock_vma_under_rcu()`. This tries to acquire the lock atomically so might fail, in which case fall-back logic is required to instead obtain an mmap read lock if this returns `!NULL`, *or*

- Acquire an rmap lock before traversing the locked interval tree (whether anonymous or file-backed) to obtain the required VMA.

If you want to **write** VMA metadata fields, then things vary depending on the field (we explore each VMA field in detail below). For the majority you must:

- Obtain an mmap write lock at the MM granularity via `!mmap_write_lock()` (or a suitable variant), unlocking it with a matching `!mmap_write_unlock()` when you're done with the VMA, *and*

- Obtain a VMA write lock via `!vma_start_write()` for each VMA you wish to modify, which will be released automatically when `!mmap_write_unlock()` is called.

- If you want to be able to write to **any** field, you must also hide the VMA from the reverse mapping by obtaining an **rmap write lock**.

VMA locks are special in that you must obtain an mmap **write** lock **first** in order to obtain a VMA **write** lock. A VMA **read** lock however can be obtained without any other lock (`!lock_vma_under_rcu()` will acquire then release an RCU lock to lookup the VMA for you).

This constrains the impact of writers on readers, as a writer can interact with one VMA while a reader interacts with another simultaneously.

> [!NOTE]
>
> The primary users of VMA read locks are page fault handlers, which means that without a VMA write lock, page faults will run concurrent with whatever you are doing.

Examining all valid lock states:


<table>
<thead>
<tr>
<th>


mmap lock

</th>
<th>


VMA lock

</th>
<th>


rmap lock

</th>
<th>


Stable?

</th>
<th>


Read?

</th>
<th>


Write most?

</th>
<th>


Write all?

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


-

</td>
<td>


-

</td>
<td>


-

</td>
<td>


N

</td>
<td>


N

</td>
<td>


N

</td>
<td>


N

</td>
</tr>
<tr>
<td>


-

</td>
<td>


R

</td>
<td>


-

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


N

</td>
</tr>
<tr>
<td>


-

</td>
<td>


-

</td>
<td>


R/W

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


N

</td>
</tr>
<tr>
<td>


R/W

</td>
<td>


-/R

</td>
<td>


-/R/W

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


N

</td>
</tr>
<tr>
<td>


W

</td>
<td>


W

</td>
<td>


-/R

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


N

</td>
</tr>
<tr>
<td>


W

</td>
<td>


W

</td>
<td>


W

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
</tr>
</tbody>
</table>

> [!WARNING]
>
> While it's possible to obtain a VMA lock while holding an mmap read lock, attempting to do the reverse is invalid as it can result in deadlock - if another task already holds an mmap write lock and attempts to acquire a VMA write lock that will deadlock on the VMA read lock.

All of these locks behave as read/write semaphores in practice, so you can obtain either a read or a write lock for each of these.

> [!NOTE]
>
> Generally speaking, a read/write semaphore is a class of lock which permits concurrent readers. However a write lock can only be obtained once all readers have left the critical region (and pending readers made to wait).
>
> This renders read locks on a read/write semaphore concurrent with other readers and write locks exclusive against all others holding the semaphore.

<a id="rst-vma-fields"></a>

#### VMA fields

We can subdivide `!struct vm_area_struct` fields by their purpose, which makes it easier to explore their locking characteristics:

> [!NOTE]
>
> We exclude VMA lock-specific fields here to avoid confusion, as these are in effect an internal implementation detail.


<table>
<caption>Virtual layout fields</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Description

</th>
<th>


Write lock

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`!vm_start`

</td>
<td>


Inclusive start virtual address of range VMA describes.

</td>
<td>


mmap write, VMA write, rmap write.

</td>
</tr>
<tr>
<td>


`!vm_end`

</td>
<td>


Exclusive end virtual address of range VMA describes.

</td>
<td>


mmap write, VMA write, rmap write.

</td>
</tr>
<tr>
<td>


`!vm_pgoff`

</td>
<td>


Describes the page offset into the file, the original page offset within the virtual address space (prior to any `!mremap()`), or PFN if a PFN map and the architecture does not support `!CONFIG_ARCH_HAS_PTE_SPECIAL`.

</td>
<td>


mmap write, VMA write, rmap write.

</td>
</tr>
</tbody>
</table>

These fields describes the size, start and end of the VMA, and as such cannot be modified without first being hidden from the reverse mapping since these fields are used to locate VMAs within the reverse mapping interval trees.


<table>
<caption>Core fields</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Description

</th>
<th>


Write lock

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`!vm_mm`

</td>
<td>


Containing mm_struct.

</td>
<td>


None - written once on initial map.

</td>
</tr>
<tr>
<td>


`!vm_page_prot`

</td>
<td>


Architecture-specific page table protection bits determined from VMA flags.

</td>
<td>


mmap write, VMA write.

</td>
</tr>
<tr>
<td>


`!vm_flags`

</td>
<td>


Read-only access to VMA flags describing attributes of the VMA, in union with private writable `!__vm_flags`.

</td>
<td>


N/A

</td>
</tr>
<tr>
<td>


`!__vm_flags`

</td>
<td>


Private, writable access to VMA flags field, updated by `!vm_flags_*()` functions.

</td>
<td>


mmap write, VMA write.

</td>
</tr>
<tr>
<td>


`!vm_file`

</td>
<td>


If the VMA is file-backed, points to a struct file object describing the underlying file, if anonymous then `!NULL`.

</td>
<td>


None - written once on initial map.

</td>
</tr>
<tr>
<td>


`!vm_ops`

</td>
<td>


If the VMA is file-backed, then either the driver or file-system provides a `!struct vm_operations_struct` object describing callbacks to be invoked on VMA lifetime events.

</td>
<td>


None - Written once on initial map by `!f_ops->mmap()`.

</td>
</tr>
<tr>
<td>


`!vm_private_data`

</td>
<td>


A `!void *` field for driver-specific metadata.

</td>
<td>


Handled by driver.

</td>
</tr>
</tbody>
</table>

These are the core fields which describe the MM the VMA belongs to and its attributes.


<table>
<caption>Config-specific fields</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Configuration option

</th>
<th>


Description

</th>
<th>


Write lock

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`!anon_name`

</td>
<td>


CONFIG_ANON_VMA_NAME

</td>
<td>


A field for storing a `!struct anon_vma_name` object providing a name for anonymous mappings, or `!NULL` if none is set or the VMA is file-backed. The underlying object is reference counted and can be shared across multiple VMAs for scalability.

</td>
<td>


mmap write, VMA write.

</td>
</tr>
<tr>
<td>


`!swap_readahead_info`

</td>
<td>


CONFIG_SWAP

</td>
<td>


Metadata used by the swap mechanism to perform readahead. This field is accessed atomically.

</td>
<td>


mmap read, swap-specific lock.

</td>
</tr>
<tr>
<td>


`!vm_policy`

</td>
<td>


CONFIG_NUMA

</td>
<td>


`!mempolicy` object which describes the NUMA behaviour of the VMA. The underlying object is reference counted.

</td>
<td>


mmap write, VMA write.

</td>
</tr>
<tr>
<td>


`!numab_state`

</td>
<td>


CONFIG_NUMA_BALANCING

</td>
<td>


`!vma_numab_state` object which describes the current state of NUMA balancing in relation to this VMA. Updated under mmap read lock by `!task_numa_work()`.

</td>
<td>


mmap read, numab-specific lock.

</td>
</tr>
<tr>
<td>


`!vm_userfaultfd_ctx`

</td>
<td>


CONFIG_USERFAULTFD

</td>
<td>


Userfaultfd context wrapper object of type `!vm_userfaultfd_ctx`, either of zero size if userfaultfd is disabled, or containing a pointer to an underlying `!userfaultfd_ctx` object which describes userfaultfd metadata.

</td>
<td>


mmap write, VMA write.

</td>
</tr>
</tbody>
</table>

These fields are present or not depending on whether the relevant kernel configuration option is set.


<table>
<caption>Reverse mapping fields</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Description

</th>
<th>


Write lock

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`!shared.rb`

</td>
<td>


A red/black tree node used, if the mapping is file-backed, to place the VMA in the `!struct address_space->i_mmap` red/black interval tree.

</td>
<td>


mmap write, VMA write, i_mmap write.

</td>
</tr>
<tr>
<td>


`!shared.rb_subtree_last`

</td>
<td>


Metadata used for management of the interval tree if the VMA is file-backed.

</td>
<td>


mmap write, VMA write, i_mmap write.

</td>
</tr>
<tr>
<td>


`!anon_vma_chain`

</td>
<td>


List of pointers to both forked/CoW’d `!anon_vma` objects and `!vma->anon_vma` if it is non-`!NULL`.

</td>
<td>


mmap read, anon_vma write.

</td>
</tr>
<tr>
<td>


`!anon_vma`

</td>
<td>


`!anon_vma` object used by anonymous folios mapped exclusively to this VMA. Initially set by `!anon_vma_prepare()` serialised by the `!page_table_lock`. This is set as soon as any page is faulted in.

</td>
<td>


When `NULL` and setting non-`NULL`: mmap read, page_table_lock.

When non-`NULL` and setting `NULL`: mmap write, VMA write, anon_vma write.

</td>
</tr>
</tbody>
</table>

These fields are used to both place the VMA within the reverse mapping, and for anonymous mappings, to be able to access both related `!struct anon_vma` objects and the `!struct anon_vma` in which folios mapped exclusively to this VMA should reside.

> [!NOTE]
>
> If a file-backed mapping is mapped with `!MAP_PRIVATE` set then it can be in both the `!anon_vma` and `!i_mmap` trees at the same time, so all of these fields might be utilised at once.

<a id="rst-page-tables"></a>

### Page tables

We won't speak exhaustively on the subject but broadly speaking, page tables map virtual addresses to physical ones through a series of page tables, each of which contain entries with physical addresses for the next page table level (along with flags), and at the leaf level the physical addresses of the underlying physical data pages or a special entry such as a swap entry, migration entry or other special marker. Offsets into these pages are provided by the virtual address itself.

In Linux these are divided into five levels - PGD, P4D, PUD, PMD and PTE. Huge pages might eliminate one or two of these levels, but when this is the case we typically refer to the leaf level as the PTE level regardless.

> [!NOTE]
>
> In instances where the architecture supports fewer page tables than five the kernel cleverly 'folds' page table levels, that is stubbing out functions related to the skipped levels. This allows us to conceptually act as if there were always five levels, even if the compiler might, in practice, eliminate any code relating to missing ones.

There are four key operations typically performed on page tables:

1. **Traversing** page tables - Simply reading page tables in order to traverse them. This only requires that the VMA is kept stable, so a lock which establishes this suffices for traversal (there are also lockless variants which eliminate even this requirement, such as `!gup_fast()`). There is also a special case of page table traversal for non-VMA regions which we consider separately below.

2. **Installing** page table mappings - Whether creating a new mapping or modifying an existing one in such a way as to change its identity. This requires that the VMA is kept stable via an mmap or VMA lock (explicitly not rmap locks).

3. **Zapping/unmapping** page table entries - This is what the kernel calls clearing page table mappings at the leaf level only, whilst leaving all page tables in place. This is a very common operation in the kernel performed on file truncation, the `!MADV_DONTNEED` operation via `!madvise()`, and others. This is performed by a number of functions including `!unmap_mapping_range()` and `!unmap_mapping_pages()`. The VMA need only be kept stable for this operation.

4. **Freeing** page tables - When finally the kernel removes page tables from a userland process (typically via `!free_pgtables()`) extreme care must be taken to ensure this is done safely, as this logic finally frees all page tables in the specified range, ignoring existing leaf entries (it assumes the caller has both zapped the range and prevented any further faults or modifications within it).

> [!NOTE]
>
> Modifying mappings for reclaim or migration is performed under rmap lock as it, like zapping, does not fundamentally modify the identity of what is being mapped.

**Traversing** and **zapping** ranges can be performed holding any one of the locks described in the terminology section above - that is the mmap lock, the VMA lock or either of the reverse mapping locks.

That is - as long as you keep the relevant VMA **stable** - you are good to go ahead and perform these operations on page tables (though internally, kernel operations that perform writes also acquire internal page table locks to serialise - see the page table implementation detail section for more details).

> [!NOTE]
>
> We free empty PTE tables on zap under the RCU lock - this does not change the aforementioned locking requirements around zapping.

When **installing** page table entries, the mmap or VMA lock must be held to keep the VMA stable. We explore why this is in the page table locking details section below.

**Freeing** page tables is an entirely internal memory management operation and has special requirements (see the page freeing section below for more details).

> [!WARNING]
>
> When **freeing** page tables, it must not be possible for VMAs containing the ranges those page tables map to be accessible via the reverse mapping.
>
> The `!free_pgtables()` function removes the relevant VMAs from the reverse mappings, but no other VMAs can be permitted to be accessible and span the specified range.

<a id="rst-traversing-non-vma-page-tables"></a>

### Traversing non-VMA page tables

We've focused above on traversal of page tables belonging to VMAs. It is also possible to traverse page tables which are not represented by VMAs.

Kernel page table mappings themselves are generally managed but whatever part of the kernel established them and the aforementioned locking rules do not apply - for instance vmalloc has its own set of locks which are utilised for establishing and tearing down page its page tables.

However, for convenience we provide the `!walk_kernel_page_table_range()` function which is synchronised via the mmap lock on the `!init_mm` kernel instantiation of the `!struct mm_struct` metadata object.

If an operation requires exclusive access, a write lock is used, but if not, a read lock suffices - we assert only that at least a read lock has been acquired.

Since, aside from vmalloc and memory hot plug, kernel page tables are not torn down all that often - this usually suffices, however any caller of this functionality must ensure that any additionally required locks are acquired in advance.

We also permit a truly unusual case is the traversal of non-VMA ranges in **userland** ranges, as provided for by `!walk_page_range_debug()`.

This has only one user - the general page table dumping logic (implemented in `!mm/ptdump.c`) - which seeks to expose all mappings for debug purposes even if they are highly unusual (possibly architecture-specific) and are not backed by a VMA.

We must take great care in this case, as the `!munmap()` implementation detaches VMAs under an mmap write lock before tearing down page tables under a downgraded mmap read lock.

This means such an operation could race with this, and thus an mmap **write** lock is required.

<a id="rst-lock-ordering"></a>

### Lock ordering

As we have multiple locks across the kernel which may or may not be taken at the same time as explicit mm or VMA locks, we have to be wary of lock inversion, and the **order** in which locks are acquired and released becomes very important.

> [!NOTE]
>
> Lock inversion occurs when two threads need to acquire multiple locks, but in doing so inadvertently cause a mutual deadlock.
>
> For example, consider thread 1 which holds lock A and tries to acquire lock B, while thread 2 holds lock B and tries to acquire lock A.
>
> Both threads are now deadlocked on each other. However, had they attempted to acquire locks in the same order, one would have waited for the other to complete its work and no deadlock would have occurred.

The opening comment in `!mm/rmap.c` describes in detail the required ordering of locks within memory management code:



```text
inode->i_rwsem        (while writing or truncating, not reading or faulting)
  mm->mmap_lock
    mapping->invalidate_lock (in filemap_fault)
      folio_lock
        hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share, see hugetlbfs below)
          vma_start_write
            mapping->i_mmap_rwsem
              anon_vma->rwsem
                mm->page_table_lock or pte_lock
                  swap_lock (in swap_duplicate, swap_info_get)
                    mmlist_lock (in mmput, drain_mmlist and others)
                    mapping->private_lock (in block_dirty_folio)
                        i_pages lock (widely used)
                          lruvec->lru_lock (in folio_lruvec_lock_irq)
                    inode->i_lock (in set_page_dirty's __mark_inode_dirty)
                    bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
                      sb_lock (within inode_lock in fs/fs-writeback.c)
                      i_pages lock (widely used, in set_page_dirty,
                                in arch-dependent flush_dcache_mmap_lock,
                                within bdi.wb->list_lock in __sync_single_inode)
```

There is also a file-system specific lock ordering comment located at the top of `!mm/filemap.c`:



```text
->i_mmap_rwsem                        (truncate_pagecache)
  ->private_lock                      (__free_pte->block_dirty_folio)
    ->swap_lock                       (exclusive_swap_page, others)
      ->i_pages lock

->i_rwsem
  ->invalidate_lock                   (acquired by fs in truncate path)
    ->i_mmap_rwsem                    (truncate->unmap_mapping_range)

->mmap_lock
  ->i_mmap_rwsem
    ->page_table_lock or pte_lock     (various, mainly in memory.c)
      ->i_pages lock                  (arch-dependent flush_dcache_mmap_lock)

->mmap_lock
  ->invalidate_lock                   (filemap_fault)
    ->lock_page                       (filemap_fault, access_process_vm)

->i_rwsem                             (generic_perform_write)
  ->mmap_lock                         (fault_in_readable->do_page_fault)

bdi->wb.list_lock
  sb_lock                             (fs/fs-writeback.c)
  ->i_pages lock                      (__sync_single_inode)

->i_mmap_rwsem
  ->anon_vma.lock                     (vma_merge)

->anon_vma.lock
  ->page_table_lock or pte_lock       (anon_vma_prepare and various)

->page_table_lock or pte_lock
  ->swap_lock                         (try_to_unmap_one)
  ->private_lock                      (try_to_unmap_one)
  ->i_pages lock                      (try_to_unmap_one)
  ->lruvec->lru_lock                  (follow_page_mask->mark_page_accessed)
  ->lruvec->lru_lock                  (check_pte_range->folio_isolate_lru)
  ->private_lock                      (folio_remove_rmap_pte->set_page_dirty)
  ->i_pages lock                      (folio_remove_rmap_pte->set_page_dirty)
  bdi.wb->list_lock                   (folio_remove_rmap_pte->set_page_dirty)
  ->inode->i_lock                     (folio_remove_rmap_pte->set_page_dirty)
  bdi.wb->list_lock                   (zap_pte_range->set_page_dirty)
  ->inode->i_lock                     (zap_pte_range->set_page_dirty)
  ->private_lock                      (zap_pte_range->block_dirty_folio)
```

Please check the current state of these comments which may have changed since the time of writing of this document.

<a id="rst-locking-implementation-details"></a>

## Locking Implementation Details

> [!WARNING]
>
> Locking rules for PTE-level page tables are very different from locking rules for page tables at other levels.

<a id="rst-page-table-locking-details"></a>

### Page table locking details

> [!NOTE]
>
> This section explores page table locking requirements for page tables encompassed by a VMA. See the above section on non-VMA page table traversal for details on how we handle that case.

In addition to the locks described in the terminology section above, we have additional locks dedicated to page tables:

- **Higher level page table locks** - Higher level page tables, that is PGD, P4D and PUD each make use of the process address space granularity `!mm->page_table_lock` lock when modified.

- **Fine-grained page table locks** - PMDs and PTEs each have fine-grained locks either kept within the folios describing the page tables or allocated separated and pointed at by the folios if `!ALLOC_SPLIT_PTLOCKS` is set. The PMD spin lock is obtained via `!pmd_lock()`, however PTEs are mapped into higher memory (if a 32-bit system) and carefully locked via `!pte_offset_map_lock()`.

These locks represent the minimum required to interact with each page table level, but there are further requirements.

Importantly, note that on a **traversal** of page tables, sometimes no such locks are taken. However, at the PTE level, at least concurrent page table deletion must be prevented (using RCU) and the page table must be mapped into high memory, see below.

Whether care is taken on reading the page table entries depends on the architecture, see the section on atomicity below.

<a id="rst-locking-rules"></a>

#### Locking rules

We establish basic locking rules when interacting with page tables:

- When changing a page table entry the page table lock for that page table **must** be held, except if you can safely assume nobody can access the page tables concurrently (such as on invocation of `!free_pgtables()`).

- Reads from and writes to page table entries must be *appropriately* atomic. See the section on atomicity below for details.

- Populating previously empty entries requires that the mmap or VMA locks are held (read or write), doing so with only rmap locks would be dangerous (see the warning below).

- As mentioned previously, zapping can be performed while simply keeping the VMA stable, that is holding any one of the mmap, VMA or rmap locks.

> [!WARNING]
>
> Populating previously empty entries is dangerous as, when unmapping VMAs, `!vms_clear_ptes()` has a window of time between zapping (via `!unmap_vmas()`) and freeing page tables (via `!free_pgtables()`), where the VMA is still visible in the rmap tree. `!free_pgtables()` assumes that the zap has already been performed and removes PTEs unconditionally (along with all other page tables in the freed range), so installing new PTE entries could leak memory and also cause other unexpected and dangerous behaviour.

There are additional rules applicable when moving page tables, which we discuss in the section on this topic below.

PTE-level page tables are different from page tables at other levels, and there are extra requirements for accessing them:

- On 32-bit architectures, they may be in high memory (meaning they need to be mapped into kernel memory to be accessible).

- When empty, they can be unlinked and RCU-freed while holding an mmap lock or rmap lock for reading in combination with the PTE and PMD page table locks. In particular, this happens in `!retract_page_tables()` when handling `!MADV_COLLAPSE`. So accessing PTE-level page tables requires at least holding an RCU read lock; but that only suffices for readers that can tolerate racing with concurrent page table updates such that an empty PTE is observed (in a page table that has actually already been detached and marked for RCU freeing) while another new page table has been installed in the same location and filled with entries. Writers normally need to take the PTE lock and revalidate that the PMD entry still refers to the same PTE-level page table. If the writer does not care whether it is the same PTE-level page table, it can take the PMD lock and revalidate that the contents of pmd entry still meet the requirements. In particular, this also happens in `!retract_page_tables()` when handling `!MADV_COLLAPSE`.

To access PTE-level page tables, a helper like `!pte_offset_map_lock()` or `!pte_offset_map()` can be used depending on stability requirements. These map the page table into kernel memory if required, take the RCU lock, and depending on variant, may also look up or acquire the PTE lock. See the comment on `!pte_offset_map_lock()`.

<a id="rst-atomicity"></a>

#### Atomicity

Regardless of page table locks, the MMU hardware concurrently updates accessed and dirty bits (perhaps more, depending on architecture). Additionally, page table traversal operations in parallel (though holding the VMA stable) and functionality like GUP-fast locklessly traverses (that is reads) page tables, without even keeping the VMA stable at all.

When performing a page table traversal and keeping the VMA stable, whether a read must be performed once and only once or not depends on the architecture (for instance x86-64 does not require any special precautions).

If a write is being performed, or if a read informs whether a write takes place (on an installation of a page table entry say, for instance in `!__pud_install()`), special care must always be taken. In these cases we can never assume that page table locks give us entirely exclusive access, and must retrieve page table entries once and only once.

If we are reading page table entries, then we need only ensure that the compiler does not rearrange our loads. This is achieved via `!pXXp_get()` functions - `!pgdp_get()`, `!p4dp_get()`, `!pudp_get()`, `!pmdp_get()`, and `!ptep_get()`.

Each of these uses `!READ_ONCE()` to guarantee that the compiler reads the page table entry only once.

However, if we wish to manipulate an existing page table entry and care about the previously stored data, we must go further and use an hardware atomic operation as, for example, in `!ptep_get_and_clear()`.

Equally, operations that do not rely on the VMA being held stable, such as GUP-fast (see `!gup_fast()` and its various page table level handlers like `!gup_fast_pte_range()`), must very carefully interact with page table entries, using functions such as `!ptep_get_lockless()` and equivalent for higher level page table levels.

Writes to page table entries must also be appropriately atomic, as established by `!set_pXX()` functions - `!set_pgd()`, `!set_p4d()`, `!set_pud()`, `!set_pmd()`, and `!set_pte()`.

Equally functions which clear page table entries must be appropriately atomic, as in `!pXX_clear()` functions - `!pgd_clear()`, `!p4d_clear()`, `!pud_clear()`, `!pmd_clear()`, and `!pte_clear()`.

<a id="rst-page-table-installation"></a>

#### Page table installation

Page table installation is performed with the VMA held stable explicitly by an mmap or VMA lock in read or write mode (see the warning in the locking rules section for details as to why).

When allocating a P4D, PUD or PMD and setting the relevant entry in the above PGD, P4D or PUD, the `!mm->page_table_lock` must be held. This is acquired in `!__p4d_alloc()`, `!__pud_alloc()` and `!__pmd_alloc()` respectively.

> [!NOTE]
>
> `!__pmd_alloc()` actually invokes `!pud_lock()` and `!pud_lockptr()` in turn, however at the time of writing it ultimately references the `!mm->page_table_lock`.

Allocating a PTE will either use the `!mm->page_table_lock` or, if `!USE_SPLIT_PMD_PTLOCKS` is defined, a lock embedded in the PMD physical page metadata in the form of a `!struct ptdesc`, acquired by `!pmd_ptdesc()` called from `!pmd_lock()` and ultimately `!__pte_alloc()`.

Finally, modifying the contents of the PTE requires special treatment, as the PTE page table lock must be acquired whenever we want stable and exclusive access to entries contained within a PTE, especially when we wish to modify them.

This is performed via `!pte_offset_map_lock()` which carefully checks to ensure that the PTE hasn't changed from under us, ultimately invoking `!pte_lockptr()` to obtain a spin lock at PTE granularity contained within the `!struct ptdesc` associated with the physical PTE page. The lock must be released via `!pte_unmap_unlock()`.

> [!NOTE]
>
> There are some variants on this, such as `!pte_offset_map_rw_nolock()` when we know we hold the PTE stable but for brevity we do not explore this.  See the comment for `!pte_offset_map_lock()` for more details.

When modifying data in ranges we typically only wish to allocate higher page tables as necessary, using these locks to avoid races or overwriting anything, and set/clear data at the PTE level as required (for instance when page faulting or zapping).

A typical pattern taken when traversing page table entries to install a new mapping is to optimistically determine whether the page table entry in the table above is empty, if so, only then acquiring the page table lock and checking again to see if it was allocated underneath us.

This allows for a traversal with page table locks only being taken when required. An example of this is `!__pud_alloc()`.

At the leaf page table, that is the PTE, we can't entirely rely on this pattern as we have separate PMD and PTE locks and a THP collapse for instance might have eliminated the PMD entry as well as the PTE from under us.

This is why `!pte_offset_map_lock()` locklessly retrieves the PMD entry for the PTE, carefully checking it is as expected, before acquiring the PTE-specific lock, and then *again* checking that the PMD entry is as expected.

If a THP collapse (or similar) were to occur then the lock on both pages would be acquired, so we can ensure this is prevented while the PTE lock is held.

Installing entries this way ensures mutual exclusion on write.

<a id="rst-page-table-freeing"></a>

#### Page table freeing

Tearing down page tables themselves is something that requires significant care. There must be no way that page tables designated for removal can be traversed or referenced by concurrent tasks.

It is insufficient to simply hold an mmap write lock and VMA lock (which will prevent racing faults, and rmap operations), as a file-backed mapping can be truncated under the `!struct address_space->i_mmap_rwsem` alone.

As a result, no VMA which can be accessed via the reverse mapping (either through the `!struct anon_vma->rb_root` or the `!struct address_space->i_mmap` interval trees) can have its page tables torn down.

The operation is typically performed via `!free_pgtables()`, which assumes either the mmap write lock has been taken (as specified by its `!mm_wr_locked` parameter), or that the VMA is already unreachable.

It carefully removes the VMA from all reverse mappings, however it's important that no new ones overlap these or any route remain to permit access to addresses within the range whose page tables are being torn down.

Additionally, it assumes that a zap has already been performed and steps have been taken to ensure that no further page table entries can be installed between the zap and the invocation of `!free_pgtables()`.

Since it is assumed that all such steps have been taken, page table entries are cleared without page table locks (in the `!pgd_clear()`, `!p4d_clear()`, `!pud_clear()`, and `!pmd_clear()` functions.

> [!NOTE]
>
> It is possible for leaf page tables to be torn down independent of the page tables above it as is done by `!retract_page_tables()`, which is performed under the i_mmap read lock, PMD, and PTE page table locks, without this level of care.

<a id="rst-page-table-moving"></a>

#### Page table moving

Some functions manipulate page table levels above PMD (that is PUD, P4D and PGD page tables). Most notable of these is `!mremap()`, which is capable of moving higher level page tables.

In these instances, it is required that **all** locks are taken, that is the mmap lock, the VMA lock and the relevant rmap locks.

You can observe this in the `!mremap()` implementation in the functions `!take_rmap_locks()` and `!drop_rmap_locks()` which perform the rmap side of lock acquisition, invoked ultimately by `!move_page_tables()`.

<a id="rst-vma-lock-internals"></a>

### VMA lock internals

<a id="rst-overview"></a>

#### Overview

VMA read locking is entirely optimistic - if the lock is contended or a competing write has started, then we do not obtain a read lock.

A VMA **read** lock is obtained by `!lock_vma_under_rcu()`, which first calls `!rcu_read_lock()` to ensure that the VMA is looked up in an RCU critical section, then attempts to VMA lock it via `!vma_start_read()`, before releasing the RCU lock via `!rcu_read_unlock()`.

In cases when the user already holds mmap read lock, `!vma_start_read_locked()` and `!vma_start_read_locked_nested()` can be used. These functions do not fail due to lock contention but the caller should still check their return values in case they fail for other reasons.

VMA read locks increment `!vma.vm_refcnt` reference counter for their duration and the caller of `!lock_vma_under_rcu()` must drop it via `!vma_end_read()`.

VMA **write** locks are acquired via `!vma_start_write()` in instances where a VMA is about to be modified, unlike `!vma_start_read()` the lock is always acquired. An mmap write lock **must** be held for the duration of the VMA write lock, releasing or downgrading the mmap write lock also releases the VMA write lock so there is no `!vma_end_write()` function.

Note that when write-locking a VMA lock, the `!vma.vm_refcnt` is temporarily modified so that readers can detect the presense of a writer. The reference counter is restored once the vma sequence number used for serialisation is updated.

This ensures the semantics we require - VMA write locks provide exclusive write access to the VMA.

<a id="rst-implementation-details"></a>

#### Implementation details

The VMA lock mechanism is designed to be a lightweight means of avoiding the use of the heavily contended mmap lock. It is implemented using a combination of a reference counter and sequence numbers belonging to the containing `!struct mm_struct` and the VMA.

Read locks are acquired via `!vma_start_read()`, which is an optimistic operation, i.e. it tries to acquire a read lock but returns false if it is unable to do so. At the end of the read operation, `!vma_end_read()` is called to release the VMA read lock.

Invoking `!vma_start_read()` requires that `!rcu_read_lock()` has been called first, establishing that we are in an RCU critical section upon VMA read lock acquisition. Once acquired, the RCU lock can be released as it is only required for lookup. This is abstracted by `!lock_vma_under_rcu()` which is the interface a user should use.

Writing requires the mmap to be write-locked and the VMA lock to be acquired via `!vma_start_write()`, however the write lock is released by the termination or downgrade of the mmap write lock so no `!vma_end_write()` is required.

All this is achieved by the use of per-mm and per-VMA sequence counts, which are used in order to reduce complexity, especially for operations which write-lock multiple VMAs at once.

If the mm sequence count, `!mm->mm_lock_seq` is equal to the VMA sequence count `!vma->vm_lock_seq` then the VMA is write-locked. If they differ, then it is not.

Each time the mmap write lock is released in `!mmap_write_unlock()` or `!mmap_write_downgrade()`, `!vma_end_write_all()` is invoked which also increments `!mm->mm_lock_seq` via `!mm_lock_seqcount_end()`.

This way, we ensure that, regardless of the VMA's sequence number, a write lock is never incorrectly indicated and that when we release an mmap write lock we efficiently release **all** VMA write locks contained within the mmap at the same time.

Since the mmap write lock is exclusive against others who hold it, the automatic release of any VMA locks on its release makes sense, as you would never want to keep VMAs locked across entirely separate write operations. It also maintains correct lock ordering.

Each time a VMA read lock is acquired, we increment `!vma.vm_refcnt` reference counter and check that the sequence count of the VMA does not match that of the mm.

If it does, the read lock fails and `!vma.vm_refcnt` is dropped. If it does not, we keep the reference counter raised, excluding writers, but permitting other readers, who can also obtain this lock under RCU.

Importantly, maple tree operations performed in `!lock_vma_under_rcu()` are also RCU safe, so the whole read lock operation is guaranteed to function correctly.

On the write side, we set a bit in `!vma.vm_refcnt` which can't be modified by readers and wait for all readers to drop their reference count. Once there are no readers, the VMA's sequence number is set to match that of the mm. During this entire operation mmap write lock is held.

This way, if any read locks are in effect, `!vma_start_write()` will sleep until these are finished and mutual exclusion is achieved.

After setting the VMA's sequence number, the bit in `!vma.vm_refcnt` indicating a writer is cleared. From this point on, VMA's sequence number will indicate VMA's write-locked state until mmap write lock is dropped or downgraded.

This clever combination of a reference counter and sequence count allows for fast RCU-based per-VMA lock acquisition (especially on page fault, though utilised elsewhere) with minimal complexity around lock ordering.

<a id="rst-mmap-write-lock-downgrading"></a>

### mmap write lock downgrading

When an mmap write lock is held one has exclusive access to resources within the mmap (with the usual caveats about requiring VMA write locks to avoid races with tasks holding VMA read locks).

It is then possible to **downgrade** from a write lock to a read lock via `!mmap_write_downgrade()` which, similar to `!mmap_write_unlock()`, implicitly terminates all VMA write locks via `!vma_end_write_all()`, but importantly does not relinquish the mmap lock while downgrading, therefore keeping the locked virtual address space stable.

An interesting consequence of this is that downgraded locks are exclusive against any other task possessing a downgraded lock (since a racing task would have to acquire a write lock first to downgrade it, and the downgraded lock prevents a new write lock from being obtained until the original lock is released).

For clarity, we map read (R)/downgraded write (D)/write (W) locks against one another showing which locks exclude the others:


<table>
<caption>Lock exclusivity</caption>
<thead>
<tr>
<th>




</th>
<th>


R

</th>
<th>


D

</th>
<th>


W

</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">


R

</th>
<td>


N

</td>
<td>


N

</td>
<td>


Y

</td>
</tr>
<tr>
<th scope="row">


D

</th>
<td>


N

</td>
<td>


Y

</td>
<td>


Y

</td>
</tr>
<tr>
<th scope="row">


W

</th>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
</tr>
</tbody>
</table>

Here a Y indicates the locks in the matching row/column are mutually exclusive, and N indicates that they are not.

<a id="rst-stack-expansion"></a>

### Stack expansion

Stack expansion throws up additional complexities in that we cannot permit there to be racing page faults, as a result we invoke `!vma_start_write()` to prevent this in `!expand_downwards()` or `!expand_upwards()`.

<a id="rst-functions-and-structures"></a>

## Functions and structures


#### <a id="c-vma_refcount_put"></a>`vma_refcount_put()`

```c
void vma_refcount_put(struct vm_area_struct *vma)
```

Drop reference count in VMA vm_refcnt field due to a read-lock being dropped.

**Parameters**

- `struct vm_area_struct *vma`: The VMA whose reference count we wish to decrement.

**Description**

If we were the last reader, wake up threads waiting to obtain an exclusive
lock.

#### <a id="c-vma_start_write_killable"></a>`vma_start_write_killable()`

```c
int vma_start_write_killable(struct vm_area_struct *vma)
```

Begin writing to a VMA.

**Parameters**

- `struct vm_area_struct *vma`: The VMA we are going to modify.

**Description**

Exclude concurrent readers under the per-VMA lock until the currently
write-locked mmap_lock is dropped or downgraded.

**Context**

May sleep while waiting for readers to drop the vma read lock.
Caller must already hold the mmap_lock for write.

**Return**

0 for a successful acquisition.  -EINTR if a fatal signal was
received.

#### <a id="c-vma_assert_write_locked"></a>`vma_assert_write_locked()`

```c
void vma_assert_write_locked(struct vm_area_struct *vma)
```

assert that **vma** holds a VMA write lock.

**Parameters**

- `struct vm_area_struct *vma`: The VMA to assert.

#### <a id="c-vma_assert_locked"></a>`vma_assert_locked()`

```c
void vma_assert_locked(struct vm_area_struct *vma)
```

assert that **vma** holds either a VMA read or a VMA write lock and is not detached.

**Parameters**

- `struct vm_area_struct *vma`: The VMA to assert.

#### <a id="c-vma_assert_stabilised"></a>`vma_assert_stabilised()`

```c
void vma_assert_stabilised(struct vm_area_struct *vma)
```

assert that this VMA cannot be changed from underneath us either by having a VMA or mmap lock held.

**Parameters**

- `struct vm_area_struct *vma`: The VMA whose stability we wish to assess.

**Description**

If lockdep is enabled we can precisely ensure stability via either an mmap
lock owned by us or a specific VMA lock.

With lockdep disabled we may sometimes race with other threads acquiring the
mmap read lock simultaneous with our VMA read lock.

---

# remap_file_pages() system call

_Peios Kernel / Internals / Memory management_

> The remap_file_pages() system call is used to create a nonlinear mapping, that is, a mapping in which the pages of the file are mapped into a nonsequential order in memory. The advantage of using remap_file_pages() over using repeated…

<a id="rst-remap-file-pages-system-call"></a>

The remap_file_pages() system call is used to create a nonlinear mapping, that is, a mapping in which the pages of the file are mapped into a nonsequential order in memory. The advantage of using remap_file_pages() over using repeated calls to mmap(2) is that the former approach does not require the kernel to create additional VMA (Virtual Memory Area) data structures.

Supporting of nonlinear mapping requires significant amount of non-trivial code in kernel virtual memory subsystem including hot paths. Also to get nonlinear mapping work kernel need a way to distinguish normal page table entries from entries with file offset (pte_file). Kernel reserves flag in PTE for this purpose. PTE flags are scarce resource especially on some CPU architectures. It would be nice to free up the flag for other usage.

Fortunately, there are not many users of remap_file_pages() in the wild. It's only known that one enterprise RDBMS implementation uses the syscall on 32-bit systems to map files bigger than can linearly fit into 32-bit virtual address space. This use-case is not critical anymore since 64-bit systems are widely available.

The syscall is deprecated and replaced it with an emulation now. The emulation creates new VMAs instead of nonlinear mappings. It's going to work slower for rare users of remap_file_pages() but ABI is preserved.

One side effect of emulation (apart from performance) is that user can hit vm.max_map_count limit more easily due to additional VMAs. See comment for DEFAULT_MAX_MAP_COUNT for more details on the limit.

---

# Shared Memory Filesystem

_Peios Kernel / Internals / Memory management_

> Reference for Shared Memory Filesystem.

<a id="rst-shared-memory-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Slab Allocation

_Peios Kernel / Internals / Memory management_

> Reference for Slab Allocation.

<a id="rst-slab-allocation"></a>

<a id="rst-functions-and-structures"></a>

## Functions and structures

<!-- SPDX-License-Identifier: GPL-2.0 -->


#### <a id="c-slab_folio"></a>`slab_folio()`

```c
slab_folio(s)
```

The folio allocated for a slab

**Parameters**

- `s`: The slab.

**Description**

Slabs are allocated as folios that contain the individual objects and are
using some fields in the first struct page of the folio - those fields are
now accessed by struct slab. It is occasionally necessary to convert back to
a folio in order to communicate with the rest of the mm.  Please use this
helper function instead of casting yourself, as the implementation may change
in the future.

#### <a id="c-page_slab"></a>`page_slab()`

```c
struct slab * page_slab(const struct page *page)
```

Converts from struct page to its slab.

**Parameters**

- `const struct page *page`: A page which may or may not belong to a slab.

**Return**

The slab which contains this page or NULL if the page does
not belong to a slab.  This includes pages returned from large kmalloc.

#### <a id="c-slab_page"></a>`slab_page()`

```c
slab_page(s)
```

The first struct page allocated for a slab

**Parameters**

- `s`: The slab.

**Description**

A convenience wrapper for converting slab to the first struct page of the
underlying folio, to communicate with code not yet converted to folio or
struct slab.



#### <a id="c-enum-slab_flags"></a>`enum slab_flags`

How the slab flags bits are used.

**Constants**

- `SL_locked`: Is locked with `slab_lock()`
- `SL_partial`: On the per-node partial list
- `SL_pfmemalloc`: Was allocated from PF_MEMALLOC reserves

**Description**

The slab flags share space with the page flags but some bits have
different interpretations.  The high bits are used for information
like zone/node/section.

---

# Split page table lock

_Peios Kernel / Internals / Memory management_

> Originally, mm->page_table_lock spinlock protected all page tables of the mm_struct. But this approach leads to poor page fault scalability of multi-threaded applications due to high contention on the lock. To improve scalability, split…

<a id="rst-split-page-table-lock"></a>

Originally, mm-&gt;page_table_lock spinlock protected all page tables of the mm_struct. But this approach leads to poor page fault scalability of multi-threaded applications due to high contention on the lock. To improve scalability, split page table lock was introduced.

With split page table lock we have separate per-table lock to serialize access to the table. At the moment we use split lock for PTE and PMD tables. Access to higher level tables protected by mm-&gt;page_table_lock.

There are helpers to lock/unlock a table and other accessor functions:

> - - **pte_offset_map_lock()**
>
>     maps PTE and takes PTE table lock, returns pointer to PTE with pointer to its PTE table lock, or returns NULL if no PTE table;
>
> - - **pte_offset_map_ro_nolock()**
>
>     maps PTE, returns pointer to PTE with pointer to its PTE table lock (not taken), or returns NULL if no PTE table;
>
> - - **pte_offset_map_rw_nolock()**
>
>     maps PTE, returns pointer to PTE with pointer to its PTE table lock (not taken) and the value of its pmd entry, or returns NULL if no PTE table;
>
> - - **pte_offset_map()**
>
>     maps PTE, returns pointer to PTE, or returns NULL if no PTE table;
>
> - - **pte_unmap()**
>
>     unmaps PTE table;
>
> - - **pte_unmap_unlock()**
>
>     unlocks and unmaps PTE table;
>
> - - **pte_alloc_map_lock()**
>
>     allocates PTE table if needed and takes its lock, returns pointer to PTE with pointer to its lock, or returns NULL if allocation failed;
>
> - - **pmd_lock()**
>
>     takes PMD table lock, returns pointer to taken lock;
>
> - - **pmd_lockptr()**
>
>     returns pointer to PMD table lock;

Split page table lock for PTE tables is enabled compile-time if CONFIG_SPLIT_PTLOCK_CPUS (usually 4) is less or equal to NR_CPUS. If split lock is disabled, all tables are guarded by mm-&gt;page_table_lock.

Split page table lock for PMD tables is enabled, if it's enabled for PTE tables and the architecture supports it (see below).

<a id="rst-hugetlb-and-split-page-table-lock"></a>

## Hugetlb and split page table lock

Hugetlb can support several page sizes. We use split lock only for PMD level, but not for PUD.

Hugetlb-specific helpers:

> - - **huge_pte_lock()**
>
>     takes pmd split lock for PMD_SIZE page, mm-&gt;page_table_lock otherwise;
>
> - - **huge_pte_lockptr()**
>
>     returns pointer to table lock;

<a id="rst-support-of-split-page-table-lock-by-an-architecture"></a>

## Support of split page table lock by an architecture

There's no need in special enabling of PTE split page table lock: everything required is done by pagetable_pte_ctor() and pagetable_dtor(), which must be called on PTE table allocation / freeing.

Make sure the architecture doesn't use slab allocator for page table allocation: slab uses page-&gt;slab_cache for its pages. This field shares storage with page-&gt;ptl.

PMD split lock only makes sense if you have more than two page table levels.

PMD split lock enabling requires pagetable_pmd_ctor() call on PMD table allocation and pagetable_dtor() on freeing.

Allocation usually happens in pmd_alloc_one(), freeing in pmd_free() and pmd_free_tlb(), but make sure you cover all PMD table allocation / freeing paths: i.e X86_PAE preallocate few PMDs on pgd_alloc().

With everything in place you can set CONFIG_ARCH_ENABLE_SPLIT_PMD_PTLOCK.

NOTE: pagetable_pte_ctor() and pagetable_pmd_ctor() can fail -- it must be handled properly.

<a id="rst-page-ptl"></a>

## page-&gt;ptl

page-&gt;ptl is used to access split page table lock, where 'page' is struct page of page containing the table. It shares storage with page-&gt;private (and few other fields in union).

To avoid increasing size of struct page and have best performance, we use a trick:

> - if spinlock_t fits into long, we use page-&gt;ptr as spinlock, so we can avoid indirect access and save a cache line.
>
> - if size of spinlock_t is bigger then size of long, we use page-&gt;ptl as pointer to spinlock_t and allocate it dynamically. This allows to use split lock with enabled DEBUG_SPINLOCK or DEBUG_LOCK_ALLOC, but costs one more cache line for indirect access;

The spinlock_t allocated in pagetable_pte_ctor() for PTE table and in pagetable_pmd_ctor() for PMD table.

Please, never access page-&gt;ptl directly -- use appropriate helper.

---

# Swap Table

_Peios Kernel / Internals / Memory management_

> Swap table implements swap cache as a per-cluster swap cache value array.

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Chris Li &lt;[chrisl@kernel.org](<mailto:chrisl@kernel.org>)&gt;, Kairui Song &lt;[kasong@tencent.com](<mailto:kasong@tencent.com>)&gt;

<a id="rst-swap-table"></a>

## Swap Table

Swap table implements swap cache as a per-cluster swap cache value array.

<a id="rst-swap-entry"></a>

### Swap Entry

A swap entry contains the information required to serve the anonymous page fault.

Swap entry is encoded as two parts: swap type and swap offset.

The swap type indicates which swap device to use. The swap offset is the offset of the swap file to read the page data from.

<a id="rst-swap-cache"></a>

### Swap Cache

Swap cache is a map to look up folios using swap entry as the key. The result value can have three possible types depending on which stage of this swap entry was in.

1. NULL: This swap entry is not used.

2. folio: A folio has been allocated and bound to this swap entry. This is the transient state of swap out or swap in. The folio data can be in the folio or swap file, or both.

3. shadow: The shadow contains the working set information of the swapped out folio. This is the normal state for a swapped out page.

<a id="rst-swap-table-internals"></a>

### Swap Table Internals

The previous swap cache is implemented by XArray. The XArray is a tree structure. Each lookup will go through multiple nodes. Can we do better?

Notice that most of the time when we look up the swap cache, we are either in a swap in or swap out path. We should already have the swap cluster, which contains the swap entry.

If we have a per-cluster array to store swap cache value in the cluster. Swap cache lookup within the cluster can be a very simple array lookup.

We give such a per-cluster swap cache value array a name: the swap table.

A swap table is an array of pointers. Each pointer is the same size as a PTE. The size of a swap table for one swap cluster typically matches a PTE page table, which is one page on modern 64-bit systems.

With swap table, swap cache lookup can achieve great locality, simpler, and faster.

<a id="rst-locking"></a>

### Locking

Swap table modification requires taking the cluster lock. If a folio is being added to or removed from the swap table, the folio must be locked prior to the cluster lock. After adding or removing is done, the folio shall be unlocked.

Swap table lookup is protected by RCU and atomic read. If the lookup returns a folio, the user must lock the folio before use.

---

# Swap

_Peios Kernel / Internals / Memory management_

> Reference for Swap.

<a id="rst-swap"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Transparent Hugepage Support

_Peios Kernel / Internals / Memory management_

> This document describes design principles for Transparent Hugepage (THP) support and its interaction with other parts of the memory management system.

<a id="rst-transparent-hugepage-support"></a>

This document describes design principles for Transparent Hugepage (THP) support and its interaction with other parts of the memory management system.

<a id="rst-design-principles"></a>

## Design principles

- "graceful fallback": mm components which don't have transparent hugepage knowledge fall back to breaking huge pmd mapping into table of ptes and, if necessary, split a transparent hugepage. Therefore these components can continue working on the regular pages or regular pte mappings.

- if a hugepage allocation fails because of memory fragmentation, regular pages should be gracefully allocated instead and mixed in the same vma without any failure or significant delay and without userland noticing

- if some task quits and more hugepages become available (either immediately in the buddy or through the VM), guest physical memory backed by regular pages should be relocated on hugepages automatically (with khugepaged)

- it doesn't require memory reservation and in turn it uses hugepages whenever possible (the only possible reservation here is kernelcore= to avoid unmovable pages to fragment all the memory but such a tweak is not specific to transparent hugepage support and it's a generic feature that applies to all dynamic high order allocations in the kernel)

<a id="rst-get-user-pages-and-pin-user-pages"></a>

## get_user_pages and pin_user_pages

get_user_pages and pin_user_pages if run on a hugepage, will return the head or tail pages as usual (exactly as they would do on hugetlbfs). Most GUP users will only care about the actual physical address of the page and its temporary pinning to release after the I/O is complete, so they won't ever notice the fact the page is huge. But if any driver is going to mangle over the page structure of the tail page (like for checking page-&gt;mapping or other bits that are relevant for the head page and not the tail page), it should be updated to jump to check head page instead. Taking a reference on any head/tail page would prevent the page from being split by anyone.

> [!NOTE]
>
> these aren't new constraints to the GUP API, and they match the same constraints that apply to hugetlbfs too, so any driver capable of handling GUP on hugetlbfs will also work fine on transparent hugepage backed mappings.

<a id="rst-graceful-fallback"></a>

## Graceful fallback

Code walking pagetables but unaware about huge pmds can simply call split_huge_pmd(vma, pmd, addr) where the pmd is the one returned by pmd_offset. It's trivial to make the code transparent hugepage aware by just grepping for "pmd_offset" and adding split_huge_pmd where missing after pmd_offset returns the pmd. Thanks to the graceful fallback design, with a one liner change, you can avoid to write hundreds if not thousands of lines of complex code to make your code hugepage aware.

If you're not walking pagetables but you run into a physical hugepage that you can't handle natively in your code, you can split it by calling split_huge_page(page). This is what the Linux VM does before it tries to swapout the hugepage for example. split_huge_page() can fail if the page is pinned and you must handle this correctly.

Example to make mremap.c transparent hugepage aware with a one liner change:



```text
diff --git a/mm/mremap.c b/mm/mremap.c
--- a/mm/mremap.c
+++ b/mm/mremap.c
@@ -41,6 +41,7 @@ static pmd_t *get_old_pmd(struct mm_stru
                return NULL;

        pmd = pmd_offset(pud, addr);
+       split_huge_pmd(vma, pmd, addr);
        if (pmd_none_or_clear_bad(pmd))
                return NULL;
```

<a id="rst-locking-in-hugepage-aware-code"></a>

## Locking in hugepage aware code

We want as much code as possible hugepage aware, as calling split_huge_page() or split_huge_pmd() has a cost.

To make pagetable walks huge pmd aware, all you need to do is to call pmd_trans_huge() on the pmd returned by pmd_offset. You must hold the mmap_lock in read (or write) mode to be sure a huge pmd cannot be created from under you by khugepaged (khugepaged collapse_huge_page takes the mmap_lock in write mode in addition to the anon_vma lock). If pmd_trans_huge returns false, you just fallback in the old code paths. If instead pmd_trans_huge returns true, you have to take the page table lock (pmd_lock()) and re-run pmd_trans_huge. Taking the page table lock will prevent the huge pmd being converted into a regular pmd from under you (split_huge_pmd can run in parallel to the pagetable walk). If the second pmd_trans_huge returns false, you should just drop the page table lock and fallback to the old code as before. Otherwise, you can proceed to process the huge pmd and the hugepage natively. Once finished, you can drop the page table lock.

<a id="rst-refcounts-and-transparent-huge-pages"></a>

## Refcounts and transparent huge pages

Refcounting on THP is mostly consistent with refcounting on other compound pages:

> - get_page()/put_page() and GUP operate on the folio-&gt;\_refcount.
>
> - -&gt;\_refcount in tail pages is always zero: get_page_unless_zero() never succeeds on tail pages.
>
> - map/unmap of a PMD entry for the whole THP increment/decrement folio-&gt;\_entire_mapcount and folio-&gt;\_large_mapcount.
>
>   We also maintain the two slots for tracking MM owners (MM ID and corresponding mapcount), and the current status ("maybe mapped shared" vs. "mapped exclusively").
>
>   With CONFIG_PAGE_MAPCOUNT, we also increment/decrement folio-&gt;\_nr_pages_mapped by ENTIRELY_MAPPED when \_entire_mapcount goes from -1 to 0 or 0 to -1.
>
> - map/unmap of individual pages with PTE entry increment/decrement folio-&gt;\_large_mapcount.
>
>   We also maintain the two slots for tracking MM owners (MM ID and corresponding mapcount), and the current status ("maybe mapped shared" vs. "mapped exclusively").
>
>   With CONFIG_PAGE_MAPCOUNT, we also increment/decrement page-&gt;\_mapcount and increment/decrement folio-&gt;\_nr_pages_mapped when page-&gt;\_mapcount goes from -1 to 0 or 0 to -1 as this counts the number of pages mapped by PTE.

split_huge_page internally has to distribute the refcounts in the head page to the tail pages before clearing all PG_head/tail bits from the page structures. It can be done easily for refcounts taken by page table entries, but we don't have enough information on how to distribute any additional pins (i.e. from get_user_pages). split_huge_page() fails any requests to split pinned huge pages: it expects page count to be equal to the sum of mapcount of all sub-pages plus one (split_huge_page caller must have a reference to the head page).

split_huge_page uses migration entries to stabilize page-&gt;\_refcount and page-&gt;\_mapcount of anonymous pages. File pages just get unmapped.

We are safe against physical memory scanners too: the only legitimate way a scanner can get a reference to a page is get_page_unless_zero().

All tail pages have zero -&gt;\_refcount until atomic_add(). This prevents the scanner from getting a reference to the tail page up to that point. After the atomic_add() we don't care about the -&gt;\_refcount value. We already know how many references should be uncharged from the head page.

For head page get_page_unless_zero() will succeed and we don't mind. It's clear where references should go after split: it will stay on the head page.

Note that split_huge_pmd() doesn't have any limitations on refcounting: pmd can be split at any point and never fails.

<a id="rst-partial-unmap-and-deferred-split-folio-anon-thp-only"></a>

## Partial unmap and deferred_split_folio() (anon THP only)

Unmapping part of THP (with munmap() or other way) is not going to free memory immediately. Instead, we detect that a subpage of THP is not in use in folio_remove_rmap\_\*() and queue the THP for splitting if memory pressure comes. Splitting will free up unused subpages.

Splitting the page right away is not an option due to locking context in the place where we can detect partial unmap. It also might be counterproductive since in many cases partial unmap happens during exit(2) if a THP crosses a VMA boundary.

The function deferred_split_folio() is used to queue a folio for splitting. The splitting itself will happen when we get memory pressure via shrinker interface.

With CONFIG_PAGE_MAPCOUNT, we reliably detect partial mappings based on folio-&gt;\_nr_pages_mapped.

With CONFIG_NO_PAGE_MAPCOUNT, we detect partial mappings based on the average per-page mapcount in a THP: if the average is &lt; 1, an anon THP is certainly partially mapped. As long as only a single process maps a THP, this detection is reliable. With long-running child processes, there can be scenarios where partial mappings can currently not be detected, and might need asynchronous detection during memory reclaim in the future.

---

# Unevictable LRU Infrastructure

_Peios Kernel / Internals / Memory management_

> Introduction

<a id="rst-unevictable-lru-infrastructure"></a>

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

This document describes the Linux memory manager's "Unevictable LRU" infrastructure and the use of this to manage several types of "unevictable" folios.

The document attempts to provide the overall rationale behind this mechanism and the rationale for some of the design decisions that drove the implementation.  The latter design rationale is discussed in the context of an implementation description.  Admittedly, one can obtain the implementation details - the "what does it do?" - by reading the code.  One hopes that the descriptions below add value by provide the answer to "why does it do that?".

<a id="rst-the-unevictable-lru"></a>

## The Unevictable LRU

The Unevictable LRU facility adds an additional LRU list to track unevictable folios and to hide these folios from vmscan.  This mechanism is based on a patch by Larry Woodman of Red Hat to address several scalability problems with folio reclaim in Linux.  The problems have been observed at customer sites on large memory x86_64 systems.

To illustrate this with an example, a non-NUMA x86_64 platform with 128GB of main memory will have over 32 million 4k pages in a single node.  When a large fraction of these pages are not evictable for any reason \[see below\], vmscan will spend a lot of time scanning the LRU lists looking for the small fraction of pages that are evictable.  This can result in a situation where all CPUs are spending 100% of their time in vmscan for hours or days on end, with the system completely unresponsive.

The unevictable list addresses the following classes of unevictable pages:

> - Those owned by ramfs.
>
> - Those owned by tmpfs with the noswap mount option.
>
> - Those mapped into SHM_LOCK'd shared memory regions.
>
> - Those mapped into VM_LOCKED \[mlock()ed\] VMAs.

The infrastructure may also be able to handle other conditions that make pages unevictable, either by definition or by circumstance, in the future.

<a id="rst-the-unevictable-lru-folio-list"></a>

### The Unevictable LRU Folio List

The Unevictable LRU folio list is a lie.  It was never an LRU-ordered list, but a companion to the LRU-ordered anonymous and file, active and inactive folio lists; and now it is not even a folio list.  But following familiar convention, here in this document and in the source, we often imagine it as a fifth LRU folio list.

The Unevictable LRU infrastructure consists of an additional, per-node, LRU list called the "unevictable" list and an associated folio flag, PG_unevictable, to indicate that the folio is being managed on the unevictable list.

The PG_unevictable flag is analogous to, and mutually exclusive with, the PG_active flag in that it indicates on which LRU list a folio resides when PG_lru is set.

The Unevictable LRU infrastructure maintains unevictable folios as if they were on an additional LRU list for a few reasons:

> 1. We get to "treat unevictable folios just like we treat other folios in the system - which means we get to use the same code to manipulate them, the same code to isolate them (for migrate, etc.), the same code to keep track of the statistics, etc..." \[Rik van Riel\]
>
> 2. We want to be able to migrate unevictable folios between nodes for memory defragmentation, workload management and memory hotplug.  The Linux kernel can only migrate folios that it can successfully isolate from the LRU lists (or "Movable" folios: outside of consideration here).  If we were to maintain folios elsewhere than on an LRU-like list, where they can be detected by folio_isolate_lru(), we would prevent their migration.

The unevictable list does not differentiate between file-backed and anonymous, swap-backed folios.  This differentiation is only important while the folios are, in fact, evictable.

The unevictable list benefits from the "arrayification" of the per-node LRU lists and statistics originally proposed and posted by Christoph Lameter.

<a id="rst-memory-control-group-interaction"></a>

### Memory Control Group Interaction

The unevictable LRU facility interacts with the memory control group \[aka memory controller; see [Documentation/admin-guide/cgroup-v1/memory.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/admin-guide/cgroup-v1/memory.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)\] by extending the lru_list enum.

The memory controller data structure automatically gets a per-node unevictable list as a result of the "arrayification" of the per-node LRU lists (one per lru_list enum element).  The memory controller tracks the movement of pages to and from the unevictable list.

When a memory control group comes under memory pressure, the controller will not attempt to reclaim pages on the unevictable list.  This has a couple of effects:

> 1. Because the pages are "hidden" from reclaim on the unevictable list, the reclaim process can be more efficient, dealing only with pages that have a chance of being reclaimed.
>
> 2. On the other hand, if too many of the pages charged to the control group are unevictable, the evictable portion of the working set of the tasks in the control group may not fit into the available memory.  This can cause the control group to thrash or to OOM-kill tasks.

<a id="rst-marking-address-spaces-unevictable"></a>
<a id="rst-mark-addr-space-unevict"></a>

### Marking Address Spaces Unevictable

For facilities such as ramfs none of the pages attached to the address space may be evicted.  To prevent eviction of any such pages, the AS_UNEVICTABLE address space flag is provided, and this can be manipulated by a filesystem using a number of wrapper functions:

> - `void mapping_set_unevictable(struct address_space *mapping);`
>
>   > Mark the address space as being completely unevictable.
>
> - `void mapping_clear_unevictable(struct address_space *mapping);`
>
>   > Mark the address space as being evictable.
>
> - `int mapping_unevictable(struct address_space *mapping);`
>
>   > Query the address space, and return true if it is completely unevictable.

These are currently used in three places in the kernel:

> 1. By ramfs to mark the address spaces of its inodes when they are created, and this mark remains for the life of the inode.
>
> 2. By SYSV SHM to mark SHM_LOCK'd address spaces until SHM_UNLOCK is called. Note that SHM_LOCK is not required to page in the locked pages if they're swapped out; the application must touch the pages manually if it wants to ensure they're in memory.
>
> 3. By the i915 driver to mark pinned address space until it's unpinned. The amount of unevictable memory marked by i915 driver is roughly the bounded object size in debugfs/dri/0/i915_gem_objects.

<a id="rst-detecting-unevictable-pages"></a>

### Detecting Unevictable Pages

The function folio_evictable() in mm/internal.h determines whether a folio is evictable or not using the query function outlined above \[see section [Marking address spaces unevictable](<#rst-mark-addr-space-unevict>)\] to check the AS_UNEVICTABLE flag.

For address spaces that are so marked after being populated (as SHM regions might be), the lock action (e.g. SHM_LOCK) can be lazy, and need not populate the page tables for the region as does, for example, mlock(), nor need it make any special effort to push any pages in the SHM_LOCK'd area to the unevictable list.  Instead, vmscan will do this if and when it encounters the folios during a reclamation scan.

On an unlock action (such as SHM_UNLOCK), the unlocker (e.g. shmctl()) must scan the pages in the region and "rescue" them from the unevictable list if no other condition is keeping them unevictable.  If an unevictable region is destroyed, the pages are also "rescued" from the unevictable list in the process of freeing them.

folio_evictable() also checks for mlocked folios by calling folio_test_mlocked(), which is set when a folio is faulted into a VM_LOCKED VMA, or found in a VMA being VM_LOCKED.

<a id="rst-vmscan-s-handling-of-unevictable-folios"></a>

### Vmscan's Handling of Unevictable Folios

If unevictable folios are culled in the fault path, or moved to the unevictable list at mlock() or mmap() time, vmscan will not encounter the folios until they have become evictable again (via munlock() for example) and have been "rescued" from the unevictable list.  However, there may be situations where we decide, for the sake of expediency, to leave an unevictable folio on one of the regular active/inactive LRU lists for vmscan to deal with.  vmscan checks for such folios in all of the shrink\_\{active\|inactive\|folio\}\_list() functions and will "cull" such folios that it encounters: that is, it diverts those folios to the unevictable list for the memory cgroup and node being scanned.

There may be situations where a folio is mapped into a VM_LOCKED VMA, but the folio does not have the mlocked flag set.  Such folios will make it all the way to shrink_active_list() or shrink_folio_list() where they will be detected when vmscan walks the reverse map in folio_referenced() or try_to_unmap().  The folio is culled to the unevictable list when it is released by the shrinker.

To "cull" an unevictable folio, vmscan simply puts the folio back on the LRU list using folio_putback_lru() - the inverse operation to folio_isolate_lru() - after dropping the folio lock.  Because the condition which makes the folio unevictable may change once the folio is unlocked, \__pagevec_lru_add_fn() will recheck the unevictable state of a folio before placing it on the unevictable list.

<a id="rst-mlocked-pages"></a>

## MLOCKED Pages

The unevictable folio list is also useful for mlock(), in addition to ramfs and SYSV SHM.  Note that mlock() is only available in CONFIG_MMU=y situations; in NOMMU situations, all mappings are effectively mlocked.

<a id="rst-history"></a>

### History

The "Unevictable mlocked Pages" infrastructure is based on work originally posted by Nick Piggin in an RFC patch entitled "mm: mlocked pages off LRU". Nick posted his patch as an alternative to a patch posted by Christoph Lameter to achieve the same objective: hiding mlocked pages from vmscan.

In Nick's patch, he used one of the struct page LRU list link fields as a count of VM_LOCKED VMAs that map the page (Rik van Riel had the same idea three years earlier).  But this use of the link field for a count prevented the management of the pages on an LRU list, and thus mlocked pages were not migratable as folio_isolate_lru() could not detect them, and the LRU list link field was not available to the migration subsystem.

Nick resolved this by putting mlocked pages back on the LRU list before attempting to isolate them, thus abandoning the count of VM_LOCKED VMAs.  When Nick's patch was integrated with the Unevictable LRU work, the count was replaced by walking the reverse map when munlocking, to determine whether any other VM_LOCKED VMAs still mapped the page.

However, walking the reverse map for each page when munlocking was ugly and inefficient, and could lead to catastrophic contention on a file's rmap lock, when many processes which had it mlocked were trying to exit.  In 5.18, the idea of keeping mlock_count in Unevictable LRU list link field was revived and put to work, without preventing the migration of mlocked pages.  This is why the "Unevictable LRU list" cannot be a linked list of pages now; but there was no use for that linked list anyway - though its size is maintained for meminfo.

<a id="rst-basic-management"></a>

### Basic Management

mlocked pages - pages mapped into a VM_LOCKED VMA - are a class of unevictable pages.  When such a page has been "noticed" by the memory management subsystem, the folio is marked with the PG_mlocked flag.  This can be manipulated using folio_set_mlocked() and folio_clear_mlocked() functions.

A PG_mlocked page will be placed on the unevictable list when it is added to the LRU.  Such pages can be "noticed" by memory management in several places:

> 1. in the mlock()/mlock2()/mlockall() system call handlers;
>
> 2. in the mmap() system call handler when mmapping a region with the MAP_LOCKED flag;
>
> 3. mmapping a region in a task that has called mlockall() with the MCL_FUTURE flag;
>
> 4. in the fault path and when a VM_LOCKED stack segment is expanded; or
>
> 5. as mentioned above, in vmscan:shrink_folio_list() when attempting to reclaim a page in a VM_LOCKED VMA by folio_referenced() or try_to_unmap().

mlocked pages become unlocked and rescued from the unevictable list when:

> 1. mapped in a range unlocked via the munlock()/munlockall() system calls;
>
> 2. munmap()'d out of the last VM_LOCKED VMA that maps the page, including unmapping at task exit;
>
> 3. when the page is truncated from the last VM_LOCKED VMA of an mmapped file; or
>
> 4. before a page is COW'd in a VM_LOCKED VMA.

<a id="rst-mlock-mlock2-mlockall-system-call-handling"></a>

### mlock()/mlock2()/mlockall() System Call Handling

mlock(), mlock2() and mlockall() system call handlers proceed to mlock_fixup() for each VMA in the range specified by the call.  In the case of mlockall(), this is the entire active address space of the task.  Note that mlock_fixup() is used for both mlocking and munlocking a range of memory.  A call to mlock() an already VM_LOCKED VMA, or to munlock() a VMA that is not VM_LOCKED, is treated as a no-op and mlock_fixup() simply returns.

If the VMA passes some filtering as described in "Filtering Special VMAs" below, mlock_fixup() will attempt to merge the VMA with its neighbors or split off a subset of the VMA if the range does not cover the entire VMA.  Any pages already present in the VMA are then marked as mlocked by mlock_folio() via mlock_pte_range() via walk_page_range() via mlock_vma_pages_range().

Before returning from the system call, do_mlock() or mlockall() will call \__mm_populate() to fault in the remaining pages via get_user_pages() and to mark those pages as mlocked as they are faulted.

Note that the VMA being mlocked might be mapped with PROT_NONE.  In this case, get_user_pages() will be unable to fault in the pages.  That's okay.  If pages do end up getting faulted into this VM_LOCKED VMA, they will be handled in the fault path - which is also how mlock2()'s MLOCK_ONFAULT areas are handled.

For each PTE (or PMD) being faulted into a VMA, the page add rmap function calls mlock_vma_folio(), which calls mlock_folio() when the VMA is VM_LOCKED (unless it is a PTE mapping of a part of a transparent huge page).  Or when it is a newly allocated anonymous page, folio_add_lru_vma() calls mlock_new_folio() instead: similar to mlock_folio(), but can make better judgments, since this page is held exclusively and known not to be on LRU yet.

mlock_folio() sets PG_mlocked immediately, then places the page on the CPU's mlock folio batch, to batch up the rest of the work to be done under lru_lock by \__mlock_folio().  \__mlock_folio() sets PG_unevictable, initializes mlock_count and moves the page to unevictable state ("the unevictable LRU", but with mlock_count in place of LRU threading).  Or if the page was already PG_lru and PG_unevictable and PG_mlocked, it simply increments the mlock_count.

But in practice that may not work ideally: the page may not yet be on an LRU, or it may have been temporarily isolated from LRU.  In such cases the mlock_count field cannot be touched, but will be set to 0 later when \__munlock_folio() returns the page to "LRU".  Races prohibit mlock_count from being set to 1 then: rather than risk stranding a page indefinitely as unevictable, always err with mlock_count on the low side, so that when munlocked the page will be rescued to an evictable LRU, then perhaps be mlocked again later if vmscan finds it in a VM_LOCKED VMA.

<a id="rst-filtering-special-vmas"></a>

### Filtering Special VMAs

mlock_fixup() filters several classes of "special" VMAs:

1. VMAs with VM_IO or VM_PFNMAP set are skipped entirely.  The pages behind these mappings are inherently pinned, so we don't need to mark them as mlocked.  In any case, most of the pages have no struct page in which to so mark the page.  Because of this, get_user_pages() will fail for these VMAs, so there is no sense in attempting to visit them.

2. VMAs mapping hugetlbfs page are already effectively pinned into memory.  We neither need nor want to mlock() these pages.  But \__mm_populate() includes hugetlbfs ranges, allocating the huge pages and populating the PTEs.

3. VMAs with VM_DONTEXPAND are generally userspace mappings of kernel pages, such as the VDSO page, relay channel pages, etc.  These pages are inherently unevictable and are not managed on the LRU lists.  \__mm_populate() includes these ranges, populating the PTEs if not already populated.

4. VMAs with VM_MIXEDMAP set are not marked VM_LOCKED, but \__mm_populate() includes these ranges, populating the PTEs if not already populated.

Note that for all of these special VMAs, mlock_fixup() does not set the VM_LOCKED flag.  Therefore, we won't have to deal with them later during munlock(), munmap() or task exit.  Neither does mlock_fixup() account these VMAs against the task's "locked_vm".

<a id="rst-munlock-munlockall-system-call-handling"></a>

### munlock()/munlockall() System Call Handling

The munlock() and munlockall() system calls are handled by the same mlock_fixup() function as mlock(), mlock2() and mlockall() system calls are. If called to munlock an already munlocked VMA, mlock_fixup() simply returns. Because of the VMA filtering discussed above, VM_LOCKED will not be set in any "special" VMAs.  So, those VMAs will be ignored for munlock.

If the VMA is VM_LOCKED, mlock_fixup() again attempts to merge or split off the specified range.  All pages in the VMA are then munlocked by munlock_folio() via mlock_pte_range() via walk_page_range() via mlock_vma_pages_range() - the same function used when mlocking a VMA range, with new flags for the VMA indicating that it is munlock() being performed.

munlock_folio() uses the mlock pagevec to batch up work to be done under lru_lock by  \__munlock_folio().  \__munlock_folio() decrements the folio's mlock_count, and when that reaches 0 it clears the mlocked flag and clears the unevictable flag, moving the folio from unevictable state to the inactive LRU.

But in practice that may not work ideally: the folio may not yet have reached "the unevictable LRU", or it may have been temporarily isolated from it.  In those cases its mlock_count field is unusable and must be assumed to be 0: so that the folio will be rescued to an evictable LRU, then perhaps be mlocked again later if vmscan finds it in a VM_LOCKED VMA.

<a id="rst-migrating-mlocked-pages"></a>

### Migrating MLOCKED Pages

A page that is being migrated has been isolated from the LRU lists and is held locked across unmapping of the page, updating the page's address space entry and copying the contents and state, until the page table entry has been replaced with an entry that refers to the new page.  Linux supports migration of mlocked pages and other unevictable pages.  PG_mlocked is cleared from the the old page when it is unmapped from the last VM_LOCKED VMA, and set when the new page is mapped in place of migration entry in a VM_LOCKED VMA.  If the page was unevictable because mlocked, PG_unevictable follows PG_mlocked; but if the page was unevictable for other reasons, PG_unevictable is copied explicitly.

Note that page migration can race with mlocking or munlocking of the same page. There is mostly no problem since page migration requires unmapping all PTEs of the old page (including munlock where VM_LOCKED), then mapping in the new page (including mlock where VM_LOCKED).  The page table locks provide sufficient synchronization.

However, since mlock_vma_pages_range() starts by setting VM_LOCKED on a VMA, before mlocking any pages already present, if one of those pages were migrated before mlock_pte_range() reached it, it would get counted twice in mlock_count. To prevent that, mlock_vma_pages_range() temporarily marks the VMA as VM_IO, so that mlock_vma_folio() will skip it.

To complete page migration, we place the old and new pages back onto the LRU afterwards.  The "unneeded" page - old page on success, new page on failure - is freed when the reference count held by the migration process is released.

<a id="rst-compacting-mlocked-pages"></a>

### Compacting MLOCKED Pages

The memory map can be scanned for compactable regions and the default behavior is to let unevictable pages be moved.  /proc/sys/vm/compact_unevictable_allowed controls this behavior (see [Documentation/admin-guide/sysctl/vm.rst](/kernel/administration/admin-guide/sysctl/vm.md)).  The work of compaction is mostly handled by the page migration code and the same work flow as described in Migrating MLOCKED Pages will apply.

<a id="rst-mlocking-transparent-huge-pages"></a>

### MLOCKING Transparent Huge Pages

A transparent huge page is represented by a single entry on an LRU list. Therefore, we can only make unevictable an entire compound page, not individual subpages.

If a user tries to mlock() part of a huge page, and no user mlock()s the whole of the huge page, we want the rest of the page to be reclaimable.

We cannot just split the page on partial mlock() as split_huge_page() can fail and a new intermittent failure mode for the syscall is undesirable.

We handle this by keeping PTE-mlocked huge pages on evictable LRU lists: the PMD on the border of a VM_LOCKED VMA will be split into a PTE table.

This way the huge page is accessible for vmscan.  Under memory pressure the page will be split, subpages which belong to VM_LOCKED VMAs will be moved to the unevictable LRU and the rest can be reclaimed.

/proc/meminfo's Unevictable and Mlocked amounts do not include those parts of a transparent huge page which are mapped only by PTEs in VM_LOCKED VMAs.

<a id="rst-mmap-map-locked-system-call-handling"></a>

### mmap(MAP_LOCKED) System Call Handling

In addition to the mlock(), mlock2() and mlockall() system calls, an application can request that a region of memory be mlocked by supplying the MAP_LOCKED flag to the mmap() call.  There is one important and subtle difference here, though. mmap() + mlock() will fail if the range cannot be faulted in (e.g. because mm_populate fails) and returns with ENOMEM while mmap(MAP_LOCKED) will not fail. The mmapped area will still have properties of the locked area - pages will not get swapped out - but major page faults to fault memory in might still happen.

Furthermore, any mmap() call or brk() call that expands the heap by a task that has previously called mlockall() with the MCL_FUTURE flag will result in the newly mapped memory being mlocked.  Before the unevictable/mlock changes, the kernel simply called make_pages_present() to allocate pages and populate the page table.

To mlock a range of memory under the unevictable/mlock infrastructure, the mmap() handler and task address space expansion functions call populate_vma_page_range() specifying the vma and the address range to mlock.

<a id="rst-munmap-exit-exec-system-call-handling"></a>

### munmap()/exit()/exec() System Call Handling

When unmapping an mlocked region of memory, whether by an explicit call to munmap() or via an internal unmap from exit() or exec() processing, we must munlock the pages if we're removing the last VM_LOCKED VMA that maps the pages. Before the unevictable/mlock changes, mlocking did not mark the pages in any way, so unmapping them required no processing.

For each PTE (or PMD) being unmapped from a VMA, folio_remove_rmap\_\*() calls munlock_vma_folio(), which calls munlock_folio() when the VMA is VM_LOCKED (unless it was a PTE mapping of a part of a transparent huge page).

munlock_folio() uses the mlock pagevec to batch up work to be done under lru_lock by  \__munlock_folio().  \__munlock_folio() decrements the folio's mlock_count, and when that reaches 0 it clears the mlocked flag and clears the unevictable flag, moving the folio from unevictable state to the inactive LRU.

But in practice that may not work ideally: the folio may not yet have reached "the unevictable LRU", or it may have been temporarily isolated from it.  In those cases its mlock_count field is unusable and must be assumed to be 0: so that the folio will be rescued to an evictable LRU, then perhaps be mlocked again later if vmscan finds it in a VM_LOCKED VMA.

<a id="rst-truncating-mlocked-pages"></a>

### Truncating MLOCKED Pages

File truncation or hole punching forcibly unmaps the deleted pages from userspace; truncation even unmaps and deletes any private anonymous pages which had been Copied-On-Write from the file pages now being truncated.

Mlocked pages can be munlocked and deleted in this way: like with munmap(), for each PTE (or PMD) being unmapped from a VMA, folio_remove_rmap\_\*() calls munlock_vma_folio(), which calls munlock_folio() when the VMA is VM_LOCKED (unless it was a PTE mapping of a part of a transparent huge page).

However, if there is a racing munlock(), since mlock_vma_pages_range() starts munlocking by clearing VM_LOCKED from a VMA, before munlocking all the pages present, if one of those pages were unmapped by truncation or hole punch before mlock_pte_range() reached it, it would not be recognized as mlocked by this VMA, and would not be counted out of mlock_count.  In this rare case, a page may still appear as PG_mlocked after it has been fully unmapped: and it is left to release_pages() (or \__page_cache_release()) to clear it and update statistics before freeing (this event is counted in /proc/vmstat unevictable_pgs_cleared, which is usually 0).

<a id="rst-page-reclaim-in-shrink-list"></a>

### Page Reclaim in shrink\_\*\_list()

vmscan's shrink_active_list() culls any obviously unevictable pages - i.e. \!page_evictable(page) pages - diverting those to the unevictable list. However, shrink_active_list() only sees unevictable pages that made it onto the active/inactive LRU lists.  Note that these pages do not have PG_unevictable set - otherwise they would be on the unevictable list and shrink_active_list() would never see them.

Some examples of these unevictable pages on the LRU lists are:

> 1. ramfs pages that have been placed on the LRU lists when first allocated.
>
> 2. SHM_LOCK'd shared memory pages.  shmctl(SHM_LOCK) does not attempt to allocate or fault in the pages in the shared memory region.  This happens when an application accesses the page the first time after SHM_LOCK'ing the segment.
>
> 3. pages still mapped into VM_LOCKED VMAs, which should be marked mlocked, but events left mlock_count too low, so they were munlocked too early.

vmscan's shrink_inactive_list() and shrink_folio_list() also divert obviously unevictable pages found on the inactive lists to the appropriate memory cgroup and node unevictable list.

rmap's folio_referenced_one(), called via vmscan's shrink_active_list() or shrink_folio_list(), and rmap's try_to_unmap_one() called via shrink_folio_list(), check for (3) pages still mapped into VM_LOCKED VMAs, and call mlock_vma_folio() to correct them.  Such pages are culled to the unevictable list when released by the shrinker.

---

# Virtually Contiguous Memory Allocation

_Peios Kernel / Internals / Memory management_

> Reference for Virtually Contiguous Memory Allocation.

<a id="rst-virtually-contiguous-memory-allocation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

---

# Virtually Mapped Kernel Stack Support

_Peios Kernel / Internals / Memory management_

> Overview

<a id="rst-virtually-mapped-kernel-stack-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Shuah Khan &lt;[skhan@linuxfoundation.org](<mailto:skhan@linuxfoundation.org>)&gt;

<a id="rst-contents"></a>



<a id="rst-overview"></a>

## Overview

This is a compilation of information from the code and original patch series that introduced the `Virtually Mapped Kernel Stacks feature <https://lwn.net/Articles/694348/>`

<a id="rst-introduction"></a>

## Introduction

Kernel stack overflows are often hard to debug and make the kernel susceptible to exploits. Problems could show up at a later time making it difficult to isolate and root-cause.

Virtually mapped kernel stacks with guard pages cause kernel stack overflows to be caught immediately rather than causing difficult to diagnose corruptions.

HAVE_ARCH_VMAP_STACK and VMAP_STACK configuration options enable support for virtually mapped stacks with guard pages. This feature causes reliable faults when the stack overflows. The usability of the stack trace after overflow and response to the overflow itself is architecture dependent.

> [!NOTE]
>
> As of this writing, arm64, powerpc, riscv, s390, um, and x86 have support for VMAP_STACK.

<a id="rst-have-arch-vmap-stack"></a>

## HAVE_ARCH_VMAP_STACK

Architectures that can support Virtually Mapped Kernel Stacks should enable this bool configuration option. The requirements are:

- vmalloc space must be large enough to hold many kernel stacks. This may rule out many 32-bit architectures.

- Stacks in vmalloc space need to work reliably.  For example, if vmap page tables are created on demand, either this mechanism needs to work while the stack points to a virtual address with unpopulated page tables or arch code (switch_to() and switch_mm(), most likely) needs to ensure that the stack's page table entries are populated before running on a possibly unpopulated stack.

- If the stack overflows into a guard page, something reasonable should happen. The definition of "reasonable" is flexible, but instantly rebooting without logging anything would be unfriendly.

<a id="rst-vmap-stack"></a>

## VMAP_STACK

When enabled, the VMAP_STACK bool configuration option allocates virtually mapped task stacks. This option depends on HAVE_ARCH_VMAP_STACK.

- Enable this if you want the use virtually-mapped kernel stacks with guard pages. This causes kernel stack overflows to be caught immediately rather than causing difficult-to-diagnose corruption.

> [!NOTE]
>
> Using this feature with KASAN requires architecture support for backing virtual mappings with real shadow memory, and KASAN_VMALLOC must be enabled.

> [!NOTE]
>
> VMAP_STACK is enabled, it is not possible to run DMA on stack allocated data.

Kernel configuration options and dependencies keep changing. Refer to the latest code base:

`Kconfig <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/Kconfig>`

<a id="rst-allocation"></a>

## Allocation

When a new kernel thread is created, a thread stack is allocated from virtually contiguous memory pages from the page level allocator. These pages are mapped into contiguous kernel virtual space with PAGE_KERNEL protections.

alloc_thread_stack_node() calls \__vmalloc_node_range() to allocate stack with PAGE_KERNEL protections.

- Allocated stacks are cached and later reused by new threads, so memcg accounting is performed manually on assigning/releasing stacks to tasks. Hence, \__vmalloc_node_range is called without \__GFP_ACCOUNT.

- vm_struct is cached to be able to find when thread free is initiated in interrupt context. free_thread_stack() can be called in interrupt context.

- On arm64, all VMAP's stacks need to have the same alignment to ensure that VMAP'd stack overflow detection works correctly. Arch specific vmap stack allocator takes care of this detail.

- This does not address interrupt stacks - according to the original patch

Thread stack allocation is initiated from clone(), fork(), vfork(), kernel_thread() via kernel_clone(). These are a few hints for searching the code base to understand when and how a thread stack is allocated.

Bulk of the code is in: `kernel/fork.c <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/kernel/fork.c>`.

stack_vm_area pointer in task_struct keeps track of the virtually allocated stack and a non-null stack_vm_area pointer serves as an indication that the virtually mapped kernel stacks are enabled.



```text
struct vm_struct *stack_vm_area;
```

<a id="rst-stack-overflow-handling"></a>

## Stack overflow handling

Leading and trailing guard pages help detect stack overflows. When the stack overflows into the guard pages, handlers have to be careful not to overflow the stack again. When handlers are called, it is likely that very little stack space is left.

On x86, this is done by handling the page fault indicating the kernel stack overflow on the double-fault stack.

<a id="rst-testing-vmap-allocation-with-guard-pages"></a>

## Testing VMAP allocation with guard pages

How do we ensure that VMAP_STACK is actually allocating with a leading and trailing guard page? The following lkdtm tests can help detect any regressions.



```text
void lkdtm_STACK_GUARD_PAGE_LEADING()
void lkdtm_STACK_GUARD_PAGE_TRAILING()
```

<a id="rst-conclusions"></a>

## Conclusions

- A percpu cache of vmalloced stacks appears to be a bit faster than a high-order stack allocation, at least when the cache hits.

- THREAD_INFO_IN_TASK gets rid of arch-specific thread_info entirely and simply embed the thread_info (containing only flags) and 'int cpu' into task_struct.

- The thread stack can be freed as soon as the task is dead (without waiting for RCU) and then, if vmapped stacks are in use, cache the entire stack for reuse on the same cpu.

---

# A vmemmap diet for HugeTLB and Device DAX

_Peios Kernel / Internals / Memory management_

> This section is to explain how HugeTLB Vmemmap Optimization (HVO) works.

<a id="rst-a-vmemmap-diet-for-hugetlb-and-device-dax"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-hugetlb"></a>

## HugeTLB

This section is to explain how HugeTLB Vmemmap Optimization (HVO) works.

The `struct page` structures are used to describe a physical page frame. By default, there is a one-to-one mapping from a page frame to its corresponding `struct page`.

HugeTLB pages consist of multiple base page size pages and is supported by many architectures. See [Documentation/admin-guide/mm/hugetlbpage.rst](/kernel/administration/admin-guide/mm/hugetlbpage.md) for more details. On the x86-64 architecture, HugeTLB pages of size 2MB and 1GB are currently supported. Since the base page size on x86 is 4KB, a 2MB HugeTLB page consists of 512 base pages and a 1GB HugeTLB page consists of 262144 base pages. For each base page, there is a corresponding `struct page`.

Within the HugeTLB subsystem, only the first 4 `struct page` are used to contain unique information about a HugeTLB page. `__NR_USED_SUBPAGE` provides this upper limit. The only 'useful' information in the remaining `struct page` is the compound_head field, and this field is the same for all tail pages.

By removing redundant `struct page` for HugeTLB pages, memory can be returned to the buddy allocator for other uses.

Different architectures support different HugeTLB pages. For example, the following table is the HugeTLB page size supported by x86 and arm64 architectures. Because arm64 supports 4k, 16k, and 64k base pages and supports contiguous entries, so it supports many kinds of sizes of HugeTLB page.


<table>
<tbody>
<tr>
<td>


Architecture

</td>
<td>


Page Size

</td>
<td colspan="4">


HugeTLB Page Size

</td>
</tr>
<tr>
<td>


x86-64

</td>
<td>


4KB

</td>
<td>


2MB

</td>
<td>


1GB

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td rowspan="3">


arm64

</td>
<td>


4KB

</td>
<td>


64KB

</td>
<td>


2MB

</td>
<td>


32MB

</td>
<td>


1GB

</td>
</tr>
<tr>
<td>


16KB

</td>
<td>


2MB

</td>
<td>


32MB

</td>
<td>


1GB

</td>
<td>




</td>
</tr>
<tr>
<td>


64KB

</td>
<td>


2MB

</td>
<td>


512MB

</td>
<td>


16GB

</td>
<td>




</td>
</tr>
</tbody>
</table>

When the system boot up, every HugeTLB page has more than one `struct page` structs which size is (unit: pages):



```text
struct_size = HugeTLB_Size / PAGE_SIZE * sizeof(struct page) / PAGE_SIZE
```

Where HugeTLB_Size is the size of the HugeTLB page. We know that the size of the HugeTLB page is always n times PAGE_SIZE. So we can get the following relationship:



```text
HugeTLB_Size = n * PAGE_SIZE
```

Then:



```text
struct_size = n * PAGE_SIZE / PAGE_SIZE * sizeof(struct page) / PAGE_SIZE
            = n * sizeof(struct page) / PAGE_SIZE
```

We can use huge mapping at the pud/pmd level for the HugeTLB page.

For the HugeTLB page of the pmd level mapping, then:



```text
struct_size = n * sizeof(struct page) / PAGE_SIZE
            = PAGE_SIZE / sizeof(pte_t) * sizeof(struct page) / PAGE_SIZE
            = sizeof(struct page) / sizeof(pte_t)
            = 64 / 8
            = 8 (pages)
```

Where n is how many pte entries which one page can contains. So the value of n is (PAGE_SIZE / sizeof(pte_t)).

This optimization only supports 64-bit system, so the value of sizeof(pte_t) is 8. And this optimization also applicable only when the size of `struct page` is a power of two. In most cases, the size of `struct page` is 64 bytes (e.g. x86-64 and arm64). So if we use pmd level mapping for a HugeTLB page, the size of `struct page` structs of it is 8 page frames which size depends on the size of the base page.

For the HugeTLB page of the pud level mapping, then:



```text
struct_size = PAGE_SIZE / sizeof(pmd_t) * struct_size(pmd)
            = PAGE_SIZE / 8 * 8 (pages)
            = PAGE_SIZE (pages)
```

Where the struct_size(pmd) is the size of the `struct page` structs of a HugeTLB page of the pmd level mapping.

E.g.: A 2MB HugeTLB page on x86_64 consists in 8 page frames while 1GB HugeTLB page consists in 4096.

Next, we take the pmd level mapping of the HugeTLB page as an example to show the internal implementation of this optimization. There are 8 pages `struct page` structs associated with a HugeTLB page which is pmd mapped.

Here is how things look before optimization:



```text
   HugeTLB                  struct pages(8 pages)         page frame(8 pages)
+-----------+ ---virt_to_page---> +-----------+   mapping to   +-----------+
|           |                     |     0     | -------------> |     0     |
|           |                     +-----------+                +-----------+
|           |                     |     1     | -------------> |     1     |
|           |                     +-----------+                +-----------+
|           |                     |     2     | -------------> |     2     |
|           |                     +-----------+                +-----------+
|           |                     |     3     | -------------> |     3     |
|           |                     +-----------+                +-----------+
|           |                     |     4     | -------------> |     4     |
|    PMD    |                     +-----------+                +-----------+
|   level   |                     |     5     | -------------> |     5     |
|  mapping  |                     +-----------+                +-----------+
|           |                     |     6     | -------------> |     6     |
|           |                     +-----------+                +-----------+
|           |                     |     7     | -------------> |     7     |
|           |                     +-----------+                +-----------+
|           |
|           |
|           |
+-----------+
```

The value of page-&gt;compound_head is the same for all tail pages. The first page of `struct page` (page 0) associated with the HugeTLB page contains the 4 `struct page` necessary to describe the HugeTLB. The only use of the remaining pages of `struct page` (page 1 to page 7) is to point to page-&gt;compound_head. Therefore, we can remap pages 1 to 7 to page 0. Only 1 page of `struct page` will be used for each HugeTLB page. This will allow us to free the remaining 7 pages to the buddy allocator.

Here is how things look after remapping:



```text
   HugeTLB                  struct pages(8 pages)         page frame(8 pages)
+-----------+ ---virt_to_page---> +-----------+   mapping to   +-----------+
|           |                     |     0     | -------------> |     0     |
|           |                     +-----------+                +-----------+
|           |                     |     1     | ---------------^ ^ ^ ^ ^ ^ ^
|           |                     +-----------+                  | | | | | |
|           |                     |     2     | -----------------+ | | | | |
|           |                     +-----------+                    | | | | |
|           |                     |     3     | -------------------+ | | | |
|           |                     +-----------+                      | | | |
|           |                     |     4     | ---------------------+ | | |
|    PMD    |                     +-----------+                        | | |
|   level   |                     |     5     | -----------------------+ | |
|  mapping  |                     +-----------+                          | |
|           |                     |     6     | -------------------------+ |
|           |                     +-----------+                            |
|           |                     |     7     | ---------------------------+
|           |                     +-----------+
|           |
|           |
|           |
+-----------+
```

When a HugeTLB is freed to the buddy system, we should allocate 7 pages for vmemmap pages and restore the previous mapping relationship.

For the HugeTLB page of the pud level mapping. It is similar to the former. We also can use this approach to free (PAGE_SIZE - 1) vmemmap pages.

Apart from the HugeTLB page of the pmd/pud level mapping, some architectures (e.g. aarch64) provides a contiguous bit in the translation table entries that hints to the MMU to indicate that it is one of a contiguous set of entries that can be cached in a single TLB entry.

The contiguous bit is used to increase the mapping size at the pmd and pte (last) level. So this type of HugeTLB page can be optimized only when its size of the `struct page` structs is greater than **1** page.

Notice: The head vmemmap page is not freed to the buddy allocator and all tail vmemmap pages are mapped to the head vmemmap page frame. So we can see more than one `struct page` struct with `PG_head` (e.g. 8 per 2 MB HugeTLB page) associated with each HugeTLB page. The `compound_head()` can handle this correctly. There is only **one** head `struct page`, the tail `struct page` with `PG_head` are fake head `struct page`.  We need an approach to distinguish between those two different types of `struct page` so that `compound_head()` can return the real head `struct page` when the parameter is the tail `struct page` but with `PG_head`.

<a id="rst-device-dax"></a>

## Device DAX

The device-dax interface uses the same tail deduplication technique explained in the previous chapter, except when used with the vmemmap in the device (altmap).

The following page sizes are supported in DAX: PAGE_SIZE (4K on x86_64), PMD_SIZE (2M on x86_64) and PUD_SIZE (1G on x86_64). For powerpc equivalent details see [Documentation/arch/powerpc/vmemmap_dedup.rst](/kernel/hardware/arch/powerpc/vmemmap-dedup.md)

The differences with HugeTLB are relatively minor.

It only use 3 `struct page` for storing all information as opposed to 4 on HugeTLB pages.

There's no remapping of vmemmap given that device-dax memory is not part of System RAM ranges initialized at boot. Thus the tail page deduplication happens at a later stage when we populate the sections. HugeTLB reuses the the head vmemmap page representing, whereas device-dax reuses the tail vmemmap page. This results in only half of the savings compared to HugeTLB.

Deduplicated tail pages are not mapped read-only.

Here's how things look like on device-dax after the sections are populated:



```text
+-----------+ ---virt_to_page---> +-----------+   mapping to   +-----------+
|           |                     |     0     | -------------> |     0     |
|           |                     +-----------+                +-----------+
|           |                     |     1     | -------------> |     1     |
|           |                     +-----------+                +-----------+
|           |                     |     2     | ----------------^ ^ ^ ^ ^ ^
|           |                     +-----------+                   | | | | |
|           |                     |     3     | ------------------+ | | | |
|           |                     +-----------+                     | | | |
|           |                     |     4     | --------------------+ | | |
|    PMD    |                     +-----------+                       | | |
|   level   |                     |     5     | ----------------------+ | |
|  mapping  |                     +-----------+                         | |
|           |                     |     6     | ------------------------+ |
|           |                     +-----------+                           |
|           |                     |     7     | --------------------------+
|           |                     +-----------+
|           |
|           |
|           |
+-----------+
```

---

# zsmalloc

_Peios Kernel / Internals / Memory management_

> This allocator is designed for use with zram. Thus, the allocator is supposed to work well under low memory conditions. In particular, it never attempts higher order page allocation which is very likely to fail under memory pressure. On…

<a id="rst-zsmalloc"></a>

This allocator is designed for use with zram. Thus, the allocator is supposed to work well under low memory conditions. In particular, it never attempts higher order page allocation which is very likely to fail under memory pressure. On the other hand, if we just use single (0-order) pages, it would suffer from very high fragmentation -- any object of size PAGE_SIZE/2 or larger would occupy an entire page. This was one of the major issues with its predecessor (xvmalloc).

To overcome these issues, zsmalloc allocates a bunch of 0-order pages and links them together using various 'struct page' fields. These linked pages act as a single higher-order page i.e. an object can span 0-order page boundaries. The code refers to these linked pages as a single entity called zspage.

For simplicity, zsmalloc can only allocate objects of size up to PAGE_SIZE since this satisfies the requirements of all its current users (in the worst case, page is incompressible and is thus stored "as-is" i.e. in uncompressed form). For allocation requests larger than this size, failure is returned (see zs_malloc).

Additionally, zs_malloc() does not return a dereferenceable pointer. Instead, it returns an opaque handle (unsigned long) which encodes actual location of the allocated object. The reason for this indirection is that zsmalloc does not keep zspages permanently mapped since that would cause issues on 32-bit systems where the VA region for kernel space mappings is very small. So, using the allocated memory should be done through the proper handle-based APIs.

<a id="rst-stat"></a>

## stat

With CONFIG_ZSMALLOC_STAT, we could see zsmalloc internal information via `/sys/kernel/debug/zsmalloc/<user name>`. Here is a sample of stat output:



```text
# cat /sys/kernel/debug/zsmalloc/zram0/classes

class  size       10%       20%       30%       40%       50%       60%       70%       80%       90%       99%      100% obj_allocated   obj_used pages_used pages_per_zspage freeable
   ...
   ...
   30   512         0        12         4         1         0         1         0         0         1         0       414          3464       3346        433                1       14
   31   528         2         7         2         2         1         0         1         0         0         2       117          4154       3793        536                4       44
   32   544         6         3         4         1         2         1         0         0         0         1       260          4170       3965        556                2       26
   ...
   ...
```

- **class**

  index

- **size**

  object size zspage stores

- **10%**

  the number of zspages with usage ratio less than 10% (see below)

- **20%**

  the number of zspages with usage ratio between 10% and 20%

- **30%**

  the number of zspages with usage ratio between 20% and 30%

- **40%**

  the number of zspages with usage ratio between 30% and 40%

- **50%**

  the number of zspages with usage ratio between 40% and 50%

- **60%**

  the number of zspages with usage ratio between 50% and 60%

- **70%**

  the number of zspages with usage ratio between 60% and 70%

- **80%**

  the number of zspages with usage ratio between 70% and 80%

- **90%**

  the number of zspages with usage ratio between 80% and 90%

- **99%**

  the number of zspages with usage ratio between 90% and 99%

- **100%**

  the number of zspages with usage ratio 100%

- **obj_allocated**

  the number of objects allocated

- **obj_used**

  the number of objects allocated to the user

- **pages_used**

  the number of pages allocated for the class

- **pages_per_zspage**

  the number of 0-order pages to make a zspage

- **freeable**

  the approximate number of pages class compaction can free

Each zspage maintains inuse counter which keeps track of the number of objects stored in the zspage.  The inuse counter determines the zspage's "fullness group" which is calculated as the ratio of the "inuse" objects to the total number of objects the zspage can hold (objs_per_zspage). The closer the inuse counter is to objs_per_zspage, the better.

<a id="rst-internals"></a>

## Internals

zsmalloc has 255 size classes, each of which can hold a number of zspages. Each zspage can contain up to ZSMALLOC_CHAIN_SIZE physical (0-order) pages. The optimal zspage chain size for each size class is calculated during the creation of the zsmalloc pool (see calculate_zspage_chain_size()).

As an optimization, zsmalloc merges size classes that have similar characteristics in terms of the number of pages per zspage and the number of objects that each zspage can store.

For instance, consider the following size classes::



```text
class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable
...
   94  1536        0    ....       0             0          0          0                3        0
  100  1632        0    ....       0             0          0          0                2        0
...
```

Size classes \#95-99 are merged with size class \#100. This means that when we need to store an object of size, say, 1568 bytes, we end up using size class \#100 instead of size class \#96. Size class \#100 is meant for objects of size 1632 bytes, so each object of size 1568 bytes wastes 1632-1568=64 bytes.

Size class \#100 consists of zspages with 2 physical pages each, which can hold a total of 5 objects. If we need to store 13 objects of size 1568, we end up allocating three zspages, or 6 physical pages.

However, if we take a closer look at size class \#96 (which is meant for objects of size 1568 bytes) and trace `calculate_zspage_chain_size()`, we find that the most optimal zspage configuration for this class is a chain of 5 physical pages::



```text
pages per zspage      wasted bytes     used%
       1                  960           76
       2                  352           95
       3                 1312           89
       4                  704           95
       5                   96           99
```

This means that a class \#96 configuration with 5 physical pages can store 13 objects of size 1568 in a single zspage, using a total of 5 physical pages. This is more efficient than the class \#100 configuration, which would use 6 physical pages to store the same number of objects.

As the zspage chain size for class \#96 increases, its key characteristics such as pages per-zspage and objects per-zspage also change. This leads to dewer class mergers, resulting in a more compact grouping of classes, which reduces memory wastage.

Let's take a closer look at the bottom of `/sys/kernel/debug/zsmalloc/zramX/classes`::



```text
class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable

...
  202  3264         0   ..         0             0          0          0                4        0
  254  4096         0   ..         0             0          0          0                1        0
...
```

Size class \#202 stores objects of size 3264 bytes and has a maximum of 4 pages per zspage. Any object larger than 3264 bytes is considered huge and belongs to size class \#254, which stores each object in its own physical page (objects in huge classes do not share pages).

Increasing the size of the chain of zspages also results in a higher watermark for the huge size class and fewer huge classes overall. This allows for more efficient storage of large objects.

For zspage chain size of 8, huge class watermark becomes 3632 bytes::



```text
class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable

...
  202  3264         0   ..         0             0          0          0                4        0
  211  3408         0   ..         0             0          0          0                5        0
  217  3504         0   ..         0             0          0          0                6        0
  222  3584         0   ..         0             0          0          0                7        0
  225  3632         0   ..         0             0          0          0                8        0
  254  4096         0   ..         0             0          0          0                1        0
...
```

For zspage chain size of 16, huge class watermark becomes 3840 bytes::



```text
class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable

...
  202  3264         0   ..         0             0          0          0                4        0
  206  3328         0   ..         0             0          0          0               13        0
  207  3344         0   ..         0             0          0          0                9        0
  208  3360         0   ..         0             0          0          0               14        0
  211  3408         0   ..         0             0          0          0                5        0
  212  3424         0   ..         0             0          0          0               16        0
  214  3456         0   ..         0             0          0          0               11        0
  217  3504         0   ..         0             0          0          0                6        0
  219  3536         0   ..         0             0          0          0               13        0
  222  3584         0   ..         0             0          0          0                7        0
  223  3600         0   ..         0             0          0          0               15        0
  225  3632         0   ..         0             0          0          0                8        0
  228  3680         0   ..         0             0          0          0                9        0
  230  3712         0   ..         0             0          0          0               10        0
  232  3744         0   ..         0             0          0          0               11        0
  234  3776         0   ..         0             0          0          0               12        0
  235  3792         0   ..         0             0          0          0               13        0
  236  3808         0   ..         0             0          0          0               14        0
  238  3840         0   ..         0             0          0          0               15        0
  254  4096         0   ..         0             0          0          0                1        0
...
```

Overall the combined zspage chain size effect on zsmalloc pool configuration::



```text
pages per zspage   number of size classes (clusters)   huge size class watermark
       4                        69                               3264
       5                        86                               3408
       6                        93                               3504
       7                       112                               3584
       8                       123                               3632
       9                       140                               3680
      10                       143                               3712
      11                       159                               3744
      12                       164                               3776
      13                       180                               3792
      14                       183                               3808
      15                       188                               3840
      16                       191                               3840
```

<a id="rst-a-synthetic-test"></a>

### A synthetic test

zram as a build artifacts storage (Linux kernel compilation).

- `CONFIG_ZSMALLOC_CHAIN_SIZE=4`

  zsmalloc classes stats::



  ```text
  class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable

  ...
  Total              13   ..        51        413836     412973     159955                         3
  ```

  zram mm_stat::



  ```text
  1691783168 628083717 655175680        0 655175680       60        0    34048    34049
  ```

- `CONFIG_ZSMALLOC_CHAIN_SIZE=8`

  zsmalloc classes stats::



  ```text
  class  size       10%   ....    100% obj_allocated   obj_used pages_used pages_per_zspage freeable

  ...
  Total              18   ..        87        414852     412978     156666                         0
  ```

  zram mm_stat::



  ```text
  1691803648 627793930 641703936        0 641703936       60        0    33591    33591
  ```

Using larger zspage chains may result in using fewer physical pages, as seen in the example where the number of physical pages used decreased from 159955 to 156666, at the same time maximum zsmalloc pool memory usage went down from 655175680 to 641703936 bytes.

However, this advantage may be offset by the potential for increased system memory pressure (as some zspages have larger chain sizes) in cases where there is heavy internal fragmentation and zspool compaction is unable to relocate objects and release zspages. In these cases, it is recommended to decrease the limit on the size of the zspage chains (as specified by the CONFIG_ZSMALLOC_CHAIN_SIZE option).

<a id="rst-functions"></a>

## Functions


#### <a id="c-obj_to_location"></a>`obj_to_location()`

```c
void obj_to_location(unsigned long obj, struct zpdesc **zpdesc, unsigned int *obj_idx)
```

get (\<zpdesc>, \<obj_idx>) from encoded object value

**Parameters**

- `unsigned long obj`: the encoded object value
- `struct zpdesc **zpdesc`: zpdesc object resides in zspage
- `unsigned int *obj_idx`: object index

#### <a id="c-location_to_obj"></a>`location_to_obj()`

```c
unsigned long location_to_obj(struct zpdesc *zpdesc, unsigned int obj_idx)
```

get obj value encoded from (\<zpdesc>, \<obj_idx>)

**Parameters**

- `struct zpdesc *zpdesc`: zpdesc object resides in zspage
- `unsigned int obj_idx`: object index

#### <a id="c-zs_lookup_class_index"></a>`zs_lookup_class_index()`

```c
unsigned int zs_lookup_class_index(struct zs_pool *pool, unsigned int size)
```

Returns index of the zsmalloc `size_class` that hold objects of the provided size.

**Parameters**

- `struct zs_pool *pool`: zsmalloc pool to use
- `unsigned int size`: object size

**Context**

Any context.

**Return**

the index of the zsmalloc `size_class` that hold objects of the
provided size.

#### <a id="c-zs_huge_class_size"></a>`zs_huge_class_size()`

```c
size_t zs_huge_class_size(struct zs_pool *pool)
```

Returns the size (in bytes) of the first huge zsmalloc `size_class`.

**Parameters**

- `struct zs_pool *pool`: zsmalloc pool to use

**Description**

The function returns the size of the first huge class - any object of equal
or bigger size will be stored in zspage consisting of a single physical
page.

**Context**

Any context.

**Return**

the size (in bytes) of the first huge zsmalloc `size_class`.

#### <a id="c-zs_malloc"></a>`zs_malloc()`

```c
unsigned long zs_malloc(struct zs_pool *pool, size_t size, gfp_t gfp, const int nid)
```

Allocate block of given size from pool.

**Parameters**

- `struct zs_pool *pool`: pool to allocate from
- `size_t size`: size of block to allocate
- `gfp_t gfp`: gfp flags when allocating object
- `const int nid`: The preferred node id to allocate new zspage (if needed)

**Description**

On success, handle to the allocated object is returned,
otherwise an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR).
Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.

#### <a id="c-zs_create_pool"></a>`zs_create_pool()`

```c
struct zs_pool * zs_create_pool(const char *name)
```

Creates an allocation pool to work from.

**Parameters**

- `const char *name`: pool name to be created

**Description**

This function must be called before anything when using
the zsmalloc allocator.

On success, a pointer to the newly created pool is returned,
otherwise NULL.

---

# DAMON: Data Access MONitoring and Access-aware System Operations

_Peios Kernel / Internals / Memory management / damon_

> DAMON is a Linux kernel subsystem for efficient data access monitoring <damon_design_monitoring> and access-aware system operations <damon_design_damos>. It is designed for being

<a id="rst-damon-data-access-monitoring-and-access-aware-system-operations"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

DAMON is a Linux kernel subsystem for efficient [data access monitoring](</kernel/internals/mm/damon/design.md#rst-damon-design-monitoring>) and [access-aware system operations](</kernel/internals/mm/damon/design.md#rst-damon-design-damos>).  It is designed for being

> - *accurate* (for DRAM level memory management),
>
> - *light-weight* (for production online usages),
>
> - *scalable* (in terms of memory size),
>
> - *tunable* (for flexible usages), and
>
> - *autoamted* (for production operation without manual tunings).

- [Frequently Asked Questions](</kernel/internals/mm/damon/faq.md>)
- [Design](</kernel/internals/mm/damon/design.md>)
- [API Reference](</kernel/internals/mm/damon/api.md>)
- [DAMON Maintainer Entry Profile](</kernel/internals/mm/damon/maintainer-profile.md>)

To utilize and control DAMON from the user-space, please refer to the administration [guide](</kernel/administration/admin-guide/mm-damon/index.md>).

If you prefer academic papers for reading and citations, please use the papers from [HPDC'22](<https://dl.acm.org/doi/abs/10.1145/3502181.3531466>)<a id="rst-hpdc-22"></a> and [Middleware19 Industry](<https://dl.acm.org/doi/abs/10.1145/3366626.3368125>)<a id="rst-middleware19-industry"></a> . Note that those cover DAMON implementations in Linux v5.16 and v5.15, respectively.

---

# API Reference

_Peios Kernel / Internals / Memory management / damon_

> Kernel space programs can use every feature of DAMON using below APIs. All you need to do is including damon.h, which is located in include/linux/ of the source tree.

<a id="rst-api-reference"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Kernel space programs can use every feature of DAMON using below APIs.  All you need to do is including `damon.h`, which is located in `include/linux/` of the source tree.

<a id="rst-structures"></a>

## Structures


#### <a id="c-struct-damon_addr_range"></a>`struct damon_addr_range`

Represents an address region of \[**start**, **end**).

**Definition**

```c
struct damon_addr_range {
    unsigned long start;
    unsigned long end;
};
```

**Members**

- `start`: Start address of the region (inclusive).
- `end`: End address of the region (exclusive).

#### <a id="c-struct-damon_size_range"></a>`struct damon_size_range`

Represents size for filter to operate on \[**min**, **max**\].

**Definition**

```c
struct damon_size_range {
    unsigned long min;
    unsigned long max;
};
```

**Members**

- `min`: Min size (inclusive).
- `max`: Max size (inclusive).

#### <a id="c-struct-damon_region"></a>`struct damon_region`

Represents a monitoring target region.

**Definition**

```c
struct damon_region {
    struct damon_addr_range ar;
    unsigned long sampling_addr;
    unsigned int nr_accesses;
    unsigned int nr_accesses_bp;
    struct list_head list;
    unsigned int age;
};
```

**Members**

- `ar`: The address range of the region.
- `sampling_addr`: Address of the sample for the next access check.
- `nr_accesses`: Access frequency of this region.
- `nr_accesses_bp`:

  **nr_accesses** in basis point (0.01%) that updated for
  each sampling interval.
- `list`: List head for siblings.
- `age`: Age of this region.

**Description**

**nr_accesses** is reset to zero for every [`damon_attrs->aggr_interval`](#c-struct-damon_attrs) and be
increased for every [`damon_attrs->sample_interval`](#c-struct-damon_attrs) if an access to the region
during the last sampling interval is found.  The update of this field should
not be done with direct access but with the helper function,
[`damon_update_region_access_rate()`](#c-damon_update_region_access_rate).

**nr_accesses_bp** is another representation of **nr_accesses** in basis point
(1 in 10,000) that updated for every [`damon_attrs->sample_interval`](#c-struct-damon_attrs) in a
manner similar to moving sum.  By the algorithm, this value becomes
**nr_accesses** * 10000 for every [`struct damon_attrs`](#c-struct-damon_attrs)->aggr_interval.  This can
be used when the aggregation interval is too huge and therefore cannot wait
for it before getting the access monitoring results.

**age** is initially zero, increased for each aggregation interval, and reset
to zero again if the access frequency is significantly changed.  If two
regions are merged into a new region, both **nr_accesses** and **age** of the new
region are set as region size-weighted average of those of the two regions.

#### <a id="c-struct-damon_target"></a>`struct damon_target`

Represents a monitoring target.

**Definition**

```c
struct damon_target {
    struct pid *pid;
    unsigned int nr_regions;
    struct list_head regions_list;
    struct list_head list;
    bool obsolete;
};
```

**Members**

- `pid`: The PID of the virtual address space to monitor.
- `nr_regions`: Number of monitoring target regions of this target.
- `regions_list`: Head of the monitoring target regions of this target.
- `list`: List head for siblings.
- `obsolete`: Whether the commit destination target is obsolete.

**Description**

Each monitoring context could have multiple targets.  For example, a context
for virtual memory address spaces could have multiple target processes.  The
**pid** should be set for appropriate [`struct damon_operations`](#c-struct-damon_operations) including the
virtual address spaces monitoring operations.

**obsolete** is used only for `damon_commit_targets()` source targets, to specify
the matching destination targets are obsolete.  Read `damon_commit_targets()`
to see how it is handled.

#### <a id="c-enum-damos_action"></a>`enum damos_action`

Represents an action of a Data Access Monitoring-based Operation Scheme.

**Constants**

- `DAMOS_WILLNEED`: Call `madvise()` for the region with MADV_WILLNEED.
- `DAMOS_COLD`: Call `madvise()` for the region with MADV_COLD.
- `DAMOS_PAGEOUT`: Reclaim the region.
- `DAMOS_HUGEPAGE`: Call `madvise()` for the region with MADV_HUGEPAGE.
- `DAMOS_NOHUGEPAGE`: Call `madvise()` for the region with MADV_NOHUGEPAGE.
- `DAMOS_LRU_PRIO`: Prioritize the region on its LRU lists.
- `DAMOS_LRU_DEPRIO`: Deprioritize the region on its LRU lists.
- `DAMOS_MIGRATE_HOT`: Migrate the regions prioritizing warmer regions.
- `DAMOS_MIGRATE_COLD`: Migrate the regions prioritizing colder regions.
- `DAMOS_STAT`: Do nothing but count the stat.
- `NR_DAMOS_ACTIONS`: Total number of DAMOS actions

**Description**

The support of each action is up to running [`struct damon_operations`](#c-struct-damon_operations).
Refer to 'Operation Action' section of Documentation/mm/damon/design.rst for
status of the supports.

Note that DAMOS_PAGEOUT doesn't trigger demotions.

#### <a id="c-enum-damos_quota_goal_metric"></a>`enum damos_quota_goal_metric`

Represents the metric to be used as the goal

**Constants**

- `DAMOS_QUOTA_USER_INPUT`: User-input value.
- `DAMOS_QUOTA_SOME_MEM_PSI_US`: System level some memory PSI in us.
- `DAMOS_QUOTA_NODE_MEM_USED_BP`: MemUsed ratio of a node.
- `DAMOS_QUOTA_NODE_MEM_FREE_BP`: MemFree ratio of a node.
- `DAMOS_QUOTA_NODE_MEMCG_USED_BP`: MemUsed ratio of a node for a cgroup.
- `DAMOS_QUOTA_NODE_MEMCG_FREE_BP`: MemFree ratio of a node for a cgroup.
- `DAMOS_QUOTA_ACTIVE_MEM_BP`: Active to total LRU memory ratio.
- `DAMOS_QUOTA_INACTIVE_MEM_BP`: Inactive to total LRU memory ratio.
- `NR_DAMOS_QUOTA_GOAL_METRICS`: Number of DAMOS quota goal metrics.

**Description**

Metrics equal to larger than **NR_DAMOS_QUOTA_GOAL_METRICS** are unsupported.

#### <a id="c-struct-damos_quota_goal"></a>`struct damos_quota_goal`

DAMOS scheme quota auto-tuning goal.

**Definition**

```c
struct damos_quota_goal {
    enum damos_quota_goal_metric metric;
    unsigned long target_value;
    unsigned long current_value;
    union {
        u64 last_psi_total;
        struct {
            int nid;
            u64 memcg_id;
        };
    };
    struct list_head list;
};
```

**Members**

- `metric`: Metric to be used for representing the goal.
- `target_value`: Target value of **metric** to achieve with the tuning.
- `current_value`: Current value of **metric**.
- `{unnamed_union}`: anonymous
- `last_psi_total`: Last measured total PSI
- `{unnamed_struct}`: anonymous
- `nid`: Node id.
- `memcg_id`: Memcg id.
- `list`: List head for siblings.

**Description**

Data structure for getting the current score of the quota tuning goal.  The
score is calculated by how close **current_value** and **target_value** are.  Then
the score is entered to DAMON's internal feedback loop mechanism to get the
auto-tuned quota.

If **metric** is DAMOS_QUOTA_USER_INPUT, **current_value** should be manually
entered by the user, probably inside the kdamond callbacks.  Otherwise,
DAMON sets **current_value** with self-measured value of **metric**.

If **metric** is DAMOS_QUOTA_NODE_MEM_{USED,FREE}_BP, **nid** represents the node
id of the target node to account the used/free memory.

If **metric** is DAMOS_QUOTA_NODE_MEMCG_{USED,FREE}_BP, **nid** and **memcg_id**
represents the node id and the cgroup to account the used memory for.

#### <a id="c-struct-damos_quota"></a>`struct damos_quota`

Controls the aggressiveness of the given scheme.

**Definition**

```c
struct damos_quota {
    unsigned long reset_interval;
    unsigned long ms;
    unsigned long sz;
    struct list_head goals;
    unsigned long esz;
    unsigned int weight_sz;
    unsigned int weight_nr_accesses;
    unsigned int weight_age;
};
```

**Members**

- `reset_interval`: Charge reset interval in milliseconds.
- `ms`: Maximum milliseconds that the scheme can use.
- `sz`: Maximum bytes of memory that the action can be applied.
- `goals`: Head of quota tuning goals ([`damos_quota_goal`](#c-struct-damos_quota_goal)) list.
- `esz`: Effective size quota in bytes.
- `weight_sz`: Weight of the region's size for prioritization.
- `weight_nr_accesses`: Weight of the region's nr_accesses for prioritization.
- `weight_age`: Weight of the region's age for prioritization.

**Description**

To avoid consuming too much CPU time or IO resources for applying the
[`struct damos`](#c-struct-damos)->action to large memory, DAMON allows users to set time and/or
size quotas.  The quotas can be set by writing non-zero values to `ms` and
`sz`, respectively.  If the time quota is set, DAMON tries to use only up to
`ms` milliseconds within `reset_interval` for applying the action.  If the
size quota is set, DAMON tries to apply the action only up to `sz` bytes
within `reset_interval`.

To convince the different types of quotas and goals, DAMON internally
converts those into one single size quota called "effective quota".  DAMON
internally uses it as the only one real quota.  The conversion is made as
follows.

The time quota is transformed to a size quota using estimated throughput of
the scheme's action.  DAMON then compares it against `sz` and uses smaller
one as the effective quota.

If **goals** is not empty, DAMON calculates yet another size quota based on the
goals using its internal feedback loop algorithm, for every **reset_interval**.
Then, if the new size quota is smaller than the effective quota, it uses the
new size quota as the effective quota.

The resulting effective size quota in bytes is set to **esz**.

For selecting regions within the quota, DAMON prioritizes current scheme's
target memory regions using the [`struct damon_operations`](#c-struct-damon_operations)->get_scheme_score.
You could customize the prioritization logic by setting `weight_sz`,
`weight_nr_accesses`, and `weight_age`, because monitoring operations are
encouraged to respect those.

#### <a id="c-enum-damos_wmark_metric"></a>`enum damos_wmark_metric`

Represents the watermark metric.

**Constants**

- `DAMOS_WMARK_NONE`: Ignore the watermarks of the given scheme.
- `DAMOS_WMARK_FREE_MEM_RATE`: Free memory rate of the system in \[0,1000\].
- `NR_DAMOS_WMARK_METRICS`: Total number of DAMOS watermark metrics

#### <a id="c-struct-damos_watermarks"></a>`struct damos_watermarks`

Controls when a given scheme should be activated.

**Definition**

```c
struct damos_watermarks {
    enum damos_wmark_metric metric;
    unsigned long interval;
    unsigned long high;
    unsigned long mid;
    unsigned long low;
};
```

**Members**

- `metric`: Metric for the watermarks.
- `interval`: Watermarks check time interval in microseconds.
- `high`: High watermark.
- `mid`: Middle watermark.
- `low`: Low watermark.

**Description**

If `metric` is `DAMOS_WMARK_NONE`, the scheme is always active.  Being active
means DAMON does monitoring and applying the action of the scheme to
appropriate memory regions.  Else, DAMON checks `metric` of the system for at
least every `interval` microseconds and works as below.

If `metric` is higher than `high`, the scheme is inactivated.  If `metric` is
between `mid` and `low`, the scheme is activated.  If `metric` is lower than
`low`, the scheme is inactivated.

#### <a id="c-struct-damos_stat"></a>`struct damos_stat`

Statistics on a given scheme.

**Definition**

```c
struct damos_stat {
    unsigned long nr_tried;
    unsigned long sz_tried;
    unsigned long nr_applied;
    unsigned long sz_applied;
    unsigned long sz_ops_filter_passed;
    unsigned long qt_exceeds;
    unsigned long nr_snapshots;
};
```

**Members**

- `nr_tried`: Total number of regions that the scheme is tried to be applied.
- `sz_tried`: Total size of regions that the scheme is tried to be applied.
- `nr_applied`: Total number of regions that the scheme is applied.
- `sz_applied`: Total size of regions that the scheme is applied.
- `sz_ops_filter_passed`: Total bytes that passed ops layer-handled DAMOS filters.
- `qt_exceeds`: Total number of times the quota of the scheme has exceeded.
- `nr_snapshots`: Total number of DAMON snapshots that the scheme has tried.

**Description**

"Tried an action to a region" in this context means the DAMOS core logic
determined the region as eligible to apply the action.  The access pattern
([`struct damos_access_pattern`](#c-struct-damos_access_pattern)), quotas ([`struct damos_quota`](#c-struct-damos_quota)), watermarks
([`struct damos_watermarks`](#c-struct-damos_watermarks)) and filters ([`struct damos_filter`](#c-struct-damos_filter)) that handled
on core logic can affect this.  The core logic asks the operation set
([`struct damon_operations`](#c-struct-damon_operations)) to apply the action to the region.

"Applied an action to a region" in this context means the operation set
([`struct damon_operations`](#c-struct-damon_operations)) successfully applied the action to the region, at
least to a part of the region.  The filters ([`struct damos_filter`](#c-struct-damos_filter)) that
handled on operation set layer and type of the action and pages of the
region can affect this.  For example, if a filter is set to exclude
anonymous pages and the region has only anonymous pages, the region will be
failed at applying the action.  If the action is `DAMOS_PAGEOUT` and all
pages of the region are already paged out, the region will be failed at
applying the action.

#### <a id="c-enum-damos_filter_type"></a>`enum damos_filter_type`

Type of memory for [`struct damos_filter`](#c-struct-damos_filter)

**Constants**

- `DAMOS_FILTER_TYPE_ANON`: Anonymous pages.
- `DAMOS_FILTER_TYPE_ACTIVE`: Active pages.
- `DAMOS_FILTER_TYPE_MEMCG`: Specific memcg's pages.
- `DAMOS_FILTER_TYPE_YOUNG`: Recently accessed pages.
- `DAMOS_FILTER_TYPE_HUGEPAGE_SIZE`: Page is part of a hugepage.
- `DAMOS_FILTER_TYPE_UNMAPPED`: Unmapped pages.
- `DAMOS_FILTER_TYPE_ADDR`: Address range.
- `DAMOS_FILTER_TYPE_TARGET`: Data Access Monitoring target.
- `NR_DAMOS_FILTER_TYPES`: Number of filter types.

**Description**

The anon pages type and memcg type filters are handled by underlying
[`struct damon_operations`](#c-struct-damon_operations) as a part of scheme action trying, and therefore
accounted as 'tried'.  In contrast, other types are handled by core layer
before trying of the action and therefore not accounted as 'tried'.

The support of the filters that handled by [`struct damon_operations`](#c-struct-damon_operations) depend
on the running [`struct damon_operations`](#c-struct-damon_operations).
`enum DAMON_OPS_PADDR` supports both anon pages type and memcg type filters,
while `enum DAMON_OPS_VADDR` and `enum DAMON_OPS_FVADDR` don't support any of
the two types.

#### <a id="c-struct-damos_filter"></a>`struct damos_filter`

DAMOS action target memory filter.

**Definition**

```c
struct damos_filter {
    enum damos_filter_type type;
    bool matching;
    bool allow;
    union {
        u64 memcg_id;
        struct damon_addr_range addr_range;
        int target_idx;
        struct damon_size_range sz_range;
    };
    struct list_head list;
};
```

**Members**

- `type`: Type of the target memory.
- `matching`: Whether this is for **type**-matching memory.
- `allow`: Whether to include or exclude the **matching** memory.
- `{unnamed_union}`: anonymous
- `memcg_id`: Memcg id of the question if **type** is DAMOS_FILTER_MEMCG.
- `addr_range`: Address range if **type** is DAMOS_FILTER_TYPE_ADDR.
- `target_idx`: Index of the [`struct damon_target`](#c-struct-damon_target) of
  [`damon_ctx->adaptive_targets`](#c-struct-damon_ctx) if **type** is
  DAMOS_FILTER_TYPE_TARGET.
- `sz_range`: Size range if **type** is DAMOS_FILTER_TYPE_HUGEPAGE_SIZE.
- `list`: List head for siblings.

**Description**

Before applying the [`damos->action`](#c-struct-damos) to a memory region, DAMOS checks if each
byte of the region matches to this given condition and avoid applying the
action if so.  Support of each filter type depends on the running [`struct damon_operations`](#c-struct-damon_operations) and the type.  Refer to [`enum damos_filter_type`](#c-enum-damos_filter_type) for more
details.

#### <a id="c-struct-damos_walk_control"></a>`struct damos_walk_control`

Control [`damos_walk()`](#c-damos_walk).

**Definition**

```c
struct damos_walk_control {
    void (*walk_fn)(void *data, struct damon_ctx *ctx, struct damon_target *t, struct damon_region *r, struct damos *s, unsigned long sz_filter_passed);
    void *data;
};
```

**Members**

- `walk_fn`: Function to be called back for each region.
- `data`: Data that will be passed to walk functions.

**Description**

Control [`damos_walk()`](#c-damos_walk), which requests specific kdamond to invoke the given
function to each region that eligible to apply actions of the kdamond's
schemes.  Refer to [`damos_walk()`](#c-damos_walk) for more details.

#### <a id="c-struct-damos_access_pattern"></a>`struct damos_access_pattern`

Target access pattern of the given scheme.

**Definition**

```c
struct damos_access_pattern {
    unsigned long min_sz_region;
    unsigned long max_sz_region;
    unsigned int min_nr_accesses;
    unsigned int max_nr_accesses;
    unsigned int min_age_region;
    unsigned int max_age_region;
};
```

**Members**

- `min_sz_region`: Minimum size of target regions.
- `max_sz_region`: Maximum size of target regions.
- `min_nr_accesses`: Minimum `->nr_accesses` of target regions.
- `max_nr_accesses`: Maximum `->nr_accesses` of target regions.
- `min_age_region`: Minimum age of target regions.
- `max_age_region`: Maximum age of target regions.

#### <a id="c-struct-damos_migrate_dests"></a>`struct damos_migrate_dests`

Migration destination nodes and their weights.

**Definition**

```c
struct damos_migrate_dests {
    unsigned int *node_id_arr;
    unsigned int *weight_arr;
    size_t nr_dests;
};
```

**Members**

- `node_id_arr`: Array of migration destination node ids.
- `weight_arr`: Array of migration weights for **node_id_arr**.
- `nr_dests`: Length of the **node_id_arr** and **weight_arr** arrays.

**Description**

**node_id_arr** is an array of the ids of migration destination nodes.
**weight_arr** is an array of the weights for those.  The weights in
**weight_arr** are for nodes in **node_id_arr** of same array index.

#### <a id="c-struct-damos"></a>`struct damos`

Represents a Data Access Monitoring-based Operation Scheme.

**Definition**

```c
struct damos {
    struct damos_access_pattern pattern;
    enum damos_action action;
    unsigned long apply_interval_us;
    struct damos_quota quota;
    struct damos_watermarks wmarks;
    union {
        struct {
            int target_nid;
            struct damos_migrate_dests migrate_dests;
        };
    };
    struct list_head core_filters;
    struct list_head ops_filters;
    void *last_applied;
    struct damos_stat stat;
    unsigned long max_nr_snapshots;
    struct list_head list;
};
```

**Members**

- `pattern`: Access pattern of target regions.
- `action`: [`damos_action`](#c-enum-damos_action) to be applied to the target regions.
- `apply_interval_us`: The time between applying the **action**.
- `quota`: Control the aggressiveness of this scheme.
- `wmarks`: Watermarks for automated (in)activation of this scheme.
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `target_nid`: Destination node if **action** is "migrate_{hot,cold}".
- `migrate_dests`: Destination nodes if **action** is "migrate_{hot,cold}".
- `core_filters`: Additional set of [`struct damos_filter`](#c-struct-damos_filter) for `action`.
- `ops_filters`: ops layer handling [`struct damos_filter`](#c-struct-damos_filter) objects list.
- `last_applied`: Last **action** applied ops-managing entity.
- `stat`: Statistics of this scheme.
- `max_nr_snapshots`: Upper limit of nr_snapshots stat.
- `list`: List head for siblings.

**Description**

For each **apply_interval_us**, DAMON finds regions which fit in the
`pattern` and applies `action` to those. To avoid consuming too much
CPU time or IO resources for the `action`, `quota` is used.

If **apply_interval_us** is zero, [`damon_attrs->aggr_interval`](#c-struct-damon_attrs) is used instead.

To do the work only when needed, schemes can be activated for specific
system situations using `wmarks`.  If all schemes that registered to the
monitoring context are inactive, DAMON stops monitoring either, and just
repeatedly checks the watermarks.

**migrate_dests** specifies multiple migration target nodes with different
weights for migrate_hot or migrate_cold actions.  **target_nid** is ignored if
this is set.

**target_nid** is used to set the migration target node for migrate_hot or
migrate_cold actions, and **migrate_dests** is unset.

Before applying the `action` to a memory region, [`struct damon_operations`](#c-struct-damon_operations)
implementation could check pages of the region and skip `action` to respect
`core_filters`

The minimum entity that **action** can be applied depends on the underlying
[`struct damon_operations`](#c-struct-damon_operations).  Since it may not be aligned with the core layer
abstract, namely [`struct damon_region`](#c-struct-damon_region), [`struct damon_operations`](#c-struct-damon_operations) could apply
**action** to same entity multiple times.  Large folios that underlying on
multiple `struct damon` region objects could be such examples.  The [`struct damon_operations`](#c-struct-damon_operations) can use **last_applied** to avoid that.  DAMOS core logic
unsets **last_applied** when each regions walking for applying the scheme is
finished.

After applying the `action` to each region, `stat` is updated.

If `max_nr_snapshots` is set as non-zero and `stat.nr_snapshots` be same to or
greater than it, the scheme is deactivated.

#### <a id="c-enum-damon_ops_id"></a>`enum damon_ops_id`

Identifier for each monitoring operations implementation

**Constants**

- `DAMON_OPS_VADDR`: Monitoring operations for virtual address spaces
- `DAMON_OPS_FVADDR`: Monitoring operations for only fixed ranges of virtual
  address spaces
- `DAMON_OPS_PADDR`: Monitoring operations for the physical address space
- `NR_DAMON_OPS`: Number of monitoring operations implementations

#### <a id="c-struct-damon_operations"></a>`struct damon_operations`

Monitoring operations for given use cases.

**Definition**

```c
struct damon_operations {
    enum damon_ops_id id;
    void (*init)(struct damon_ctx *context);
    void (*update)(struct damon_ctx *context);
    void (*prepare_access_checks)(struct damon_ctx *context);
    unsigned int (*check_accesses)(struct damon_ctx *context);
    int (*get_scheme_score)(struct damon_ctx *context, struct damon_target *t, struct damon_region *r, struct damos *scheme);
    unsigned long (*apply_scheme)(struct damon_ctx *context, struct damon_target *t, struct damon_region *r, struct damos *scheme, unsigned long *sz_filter_passed);
    bool (*target_valid)(struct damon_target *t);
    void (*cleanup_target)(struct damon_target *t);
};
```

**Members**

- `id`: Identifier of this operations set.
- `init`: Initialize operations-related data structures.
- `update`: Update operations-related data structures.
- `prepare_access_checks`: Prepare next access check of target regions.
- `check_accesses`: Check the accesses to target regions.
- `get_scheme_score`: Get the score of a region for a scheme.
- `apply_scheme`: Apply a DAMON-based operation scheme.
- `target_valid`: Determine if the target is valid.
- `cleanup_target`: Clean up each target before deallocation.

**Description**

DAMON can be extended for various address spaces and usages.  For this,
users should register the low level operations for their target address
space and usecase via the [`damon_ctx.ops`](#c-struct-damon_ctx).  Then, the monitoring thread
([`damon_ctx.kdamond`](#c-struct-damon_ctx)) calls **init** and **prepare_access_checks** before starting
the monitoring, **update** after each [`damon_attrs.ops_update_interval`](#c-struct-damon_attrs), and
**check_accesses**, **target_valid** and **prepare_access_checks** after each
[`damon_attrs.sample_interval`](#c-struct-damon_attrs).

Each [`struct damon_operations`](#c-struct-damon_operations) instance having valid **id** can be registered
via [`damon_register_ops()`](#c-damon_register_ops) and selected by [`damon_select_ops()`](#c-damon_select_ops) later.
**init** should initialize operations-related data structures.  For example,
this could be used to construct proper monitoring target regions and link
those to **damon_ctx.adaptive_targets**.
**update** should update the operations-related data structures.  For example,
this could be used to update monitoring target regions for current status.
**prepare_access_checks** should manipulate the monitoring regions to be
prepared for the next access check.
**check_accesses** should check the accesses to each region that made after the
last preparation and update the number of observed accesses of each region.
It should also return max number of observed accesses that made as a result
of its update.  The value will be used for regions adjustment threshold.
**get_scheme_score** should return the priority score of a region for a scheme
as an integer in \[0, `DAMOS_MAX_SCORE`\].
**apply_scheme** is called from **kdamond** when a region for user provided
DAMON-based operation scheme is found.  It should apply the scheme's action
to the region and return bytes of the region that the action is successfully
applied.  It should also report how many bytes of the region has passed
filters ([`struct damos_filter`](#c-struct-damos_filter)) that handled by itself.
**target_valid** should check whether the target is still valid for the
monitoring.
**cleanup_target** is called before the target will be deallocated.

#### <a id="c-struct-damon_intervals_goal"></a>`struct damon_intervals_goal`

Monitoring intervals auto-tuning goal.

**Definition**

```c
struct damon_intervals_goal {
    unsigned long access_bp;
    unsigned long aggrs;
    unsigned long min_sample_us;
    unsigned long max_sample_us;
};
```

**Members**

- `access_bp`: Access events observation ratio to achieve in bp.
- `aggrs`: Number of aggregations to achieve **access_bp** within.
- `min_sample_us`: Minimum resulting sampling interval in microseconds.
- `max_sample_us`: Maximum resulting sampling interval in microseconds.

**Description**

DAMON automatically tunes [`damon_attrs->sample_interval`](#c-struct-damon_attrs) and
[`damon_attrs->aggr_interval`](#c-struct-damon_attrs) aiming the ratio in bp (1/10,000) of
DAMON-observed access events to theoretical maximum amount within **aggrs**
aggregations be same to **access_bp**.  The logic increases
[`damon_attrs->aggr_interval`](#c-struct-damon_attrs) and [`damon_attrs->sampling_interval`](#c-struct-damon_attrs) in same
ratio if the current access events observation ratio is lower than the
target for each **aggrs** aggregations, and vice versa.

If **aggrs** is zero, the tuning is disabled and hence this struct is ignored.

#### <a id="c-struct-damon_attrs"></a>`struct damon_attrs`

Monitoring attributes for accuracy/overhead control.

**Definition**

```c
struct damon_attrs {
    unsigned long sample_interval;
    unsigned long aggr_interval;
    unsigned long ops_update_interval;
    struct damon_intervals_goal intervals_goal;
    unsigned long min_nr_regions;
    unsigned long max_nr_regions;
};
```

**Members**

- `sample_interval`: The time between access samplings.
- `aggr_interval`: The time between monitor results aggregations.
- `ops_update_interval`: The time between monitoring operations updates.
- `intervals_goal`: Intervals auto-tuning goal.
- `min_nr_regions`: The minimum number of adaptive monitoring
  regions.
- `max_nr_regions`: The maximum number of adaptive monitoring
  regions.

**Description**

For each **sample_interval**, DAMON checks whether each region is accessed or
not during the last **sample_interval**.  If such access is found, DAMON
aggregates the information by increasing [`damon_region->nr_accesses`](#c-struct-damon_region) for
**aggr_interval** time.  For each **aggr_interval**, the count is reset.  DAMON
also checks whether the target memory regions need update (e.g., by
`mmap()` calls from the application, in case of virtual memory monitoring)
and applies the changes for each **ops_update_interval**.  All time intervals
are in micro-seconds.  Please refer to [`struct damon_operations`](#c-struct-damon_operations) and `struct damon_call_control` for more detail.

#### <a id="c-struct-damon_ctx"></a>`struct damon_ctx`

Represents a context for each monitoring. This is the main interface that allows users to set the attributes and get the results of the monitoring.

**Definition**

```c
struct damon_ctx {
    struct damon_attrs attrs;
    struct damon_operations ops;
    unsigned long addr_unit;
    unsigned long min_region_sz;
    struct list_head adaptive_targets;
    struct list_head schemes;
};
```

**Members**

- `attrs`: Monitoring attributes for accuracy/overhead control.
- `ops`: Set of monitoring operations for given use cases.
- `addr_unit`: Scale factor for core to ops address conversion.
- `min_region_sz`: Minimum region size.
- `adaptive_targets`: Head of monitoring targets ([`damon_target`](#c-struct-damon_target)) list.
- `schemes`: Head of schemes ([`damos`](#c-struct-damos)) list.

**Description**

For each monitoring context, one kernel thread for the monitoring, namely
kdamond, is created.  The pid of kdamond can be retrieved using
[`damon_kdamond_pid()`](#c-damon_kdamond_pid).

Once started, kdamond runs until explicitly required to be terminated or
every monitoring target is invalid.  The validity of the targets is checked
via the [`damon_operations.target_valid`](#c-struct-damon_operations) of **ops**.  The termination can also be
explicitly requested by calling [`damon_stop()`](#c-damon_stop).  To know if a kdamond is
running, [`damon_is_running()`](#c-damon_is_running) can be used.

While the kdamond is running, all accesses to [`struct damon_ctx`](#c-struct-damon_ctx) from a
thread other than the kdamond should be made using safe DAMON APIs,
including [`damon_call()`](#c-damon_call) and [`damos_walk()`](#c-damos_walk).


<a id="rst-functions"></a>

## Functions


#### <a id="c-damon_is_registered_ops"></a>`damon_is_registered_ops()`

```c
bool damon_is_registered_ops(enum damon_ops_id id)
```

Check if a given damon_operations is registered.

**Parameters**

- `enum damon_ops_id id`: Id of the damon_operations to check if registered.

**Return**

true if the ops is set, false otherwise.

#### <a id="c-damon_register_ops"></a>`damon_register_ops()`

```c
int damon_register_ops(struct damon_operations *ops)
```

Register a monitoring operations set to DAMON.

**Parameters**

- `struct damon_operations *ops`: monitoring operations set to register.

**Description**

This function registers a monitoring operations set of valid [`struct damon_operations`](#c-struct-damon_operations)->id so that others can find and use them later.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_select_ops"></a>`damon_select_ops()`

```c
int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
```

Select a monitoring operations to use with the context.

**Parameters**

- `struct damon_ctx *ctx`: monitoring context to use the operations.
- `enum damon_ops_id id`: id of the registered monitoring operations to select.

**Description**

This function finds registered monitoring operations set of **id** and make
**ctx** to use it.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damos_filter_for_ops"></a>`damos_filter_for_ops()`

```c
bool damos_filter_for_ops(enum damos_filter_type type)
```

Return if the filter is ops-handled one.

**Parameters**

- `enum damos_filter_type type`: type of the filter.

**Return**

true if the filter of **type** needs to be handled by ops layer, false
otherwise.

#### <a id="c-damon_set_attrs"></a>`damon_set_attrs()`

```c
int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
```

Set attributes for the monitoring.

**Parameters**

- `struct damon_ctx *ctx`: monitoring context
- `struct damon_attrs *attrs`: monitoring attributes

**Description**

This function should be called while the kdamond is not running, an access
check results aggregation is not ongoing (e.g., from [`damon_call()`](#c-damon_call).

Every time interval is in micro-seconds.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_set_schemes"></a>`damon_set_schemes()`

```c
void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes, ssize_t nr_schemes)
```

Set data access monitoring based operation schemes.

**Parameters**

- `struct damon_ctx *ctx`: monitoring context
- `struct damos **schemes`: array of the schemes
- `ssize_t nr_schemes`: number of entries in **schemes**

**Description**

This function should not be called while the kdamond of the context is
running.

#### <a id="c-damos_commit_quota_goals"></a>`damos_commit_quota_goals()`

```c
int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src)
```

Commit DAMOS quota goals to another quota.

**Parameters**

- `struct damos_quota *dst`: The commit destination DAMOS quota.
- `struct damos_quota *src`: The commit source DAMOS quota.

**Description**

Copies user-specified parameters for quota goals from **src** to **dst**.  Users
should use this function for quota goals-level parameters update of running
DAMON contexts, instead of manual in-place updates.

This function should be called from parameters-update safe context, like
[`damon_call()`](#c-damon_call).

#### <a id="c-damos_filters_default_reject"></a>`damos_filters_default_reject()`

```c
bool damos_filters_default_reject(struct list_head *filters)
```

decide whether to reject memory that didn't match with any given filter.

**Parameters**

- `struct list_head *filters`: Given DAMOS filters of a group.

#### <a id="c-damon_commit_ctx"></a>`damon_commit_ctx()`

```c
int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
```

Commit parameters of a DAMON context to another.

**Parameters**

- `struct damon_ctx *dst`: The commit destination DAMON context.
- `struct damon_ctx *src`: The commit source DAMON context.

**Description**

This function copies user-specified parameters from **src** to **dst** and update
the internal status and results accordingly.  Users should use this function
for context-level parameters update of running context, instead of manual
in-place updates.

This function should be called from parameters-update safe context, like
[`damon_call()`](#c-damon_call).

#### <a id="c-damon_nr_running_ctxs"></a>`damon_nr_running_ctxs()`

```c
int damon_nr_running_ctxs(void)
```

Return number of currently running contexts.

**Parameters**

- `void`: no arguments

#### <a id="c-damon_start"></a>`damon_start()`

```c
int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
```

Starts the monitorings for a given group of contexts.

**Parameters**

- `struct damon_ctx **ctxs`: an array of the pointers for contexts to start monitoring
- `int nr_ctxs`: size of **ctxs**
- `bool exclusive`: exclusiveness of this contexts group

**Description**

This function starts a group of monitoring threads for a group of monitoring
contexts.  One thread per each context is created and run in parallel.  The
caller should handle synchronization between the threads by itself.  If
**exclusive** is true and a group of threads that created by other
'[`damon_start()`](#c-damon_start)' call is currently running, this function does nothing but
returns -EBUSY.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_stop"></a>`damon_stop()`

```c
int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
```

Stops the monitorings for a given group of contexts.

**Parameters**

- `struct damon_ctx **ctxs`: an array of the pointers for contexts to stop monitoring
- `int nr_ctxs`: size of **ctxs**

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_is_running"></a>`damon_is_running()`

```c
bool damon_is_running(struct damon_ctx *ctx)
```

Returns if a given DAMON context is running.

**Parameters**

- `struct damon_ctx *ctx`: The DAMON context to see if running.

**Return**

true if **ctx** is running, false otherwise.

#### <a id="c-damon_kdamond_pid"></a>`damon_kdamond_pid()`

```c
int damon_kdamond_pid(struct damon_ctx *ctx)
```

Return pid of a given DAMON context's worker thread.

**Parameters**

- `struct damon_ctx *ctx`: The DAMON context of the question.

**Return**

pid if **ctx** is running, negative error code otherwise.

#### <a id="c-damon_call"></a>`damon_call()`

```c
int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
```

Invoke a given function on DAMON worker thread (kdamond).

**Parameters**

- `struct damon_ctx *ctx`: DAMON context to call the function for.
- `struct damon_call_control *control`: Control variable of the call request.

**Description**

Ask DAMON worker thread (kdamond) of **ctx** to call a function with an
argument data that respectively passed via `damon_call_control->fn` and
`damon_call_control->data` of **control**.  If `damon_call_control->repeat` of
**control** is unset, further wait until the kdamond finishes handling of the
request.  Otherwise, return as soon as the request is made.

The kdamond executes the function with the argument in the main loop, just
after a sampling of the iteration is finished.  The function can hence
safely access the internal data of the [`struct damon_ctx`](#c-struct-damon_ctx) without additional
synchronization.  The return value of the function will be saved in
`damon_call_control->return_code`.

Note that this function should be called only after [`damon_start()`](#c-damon_start) with the
**ctx** has succeeded.  Otherwise, this function could fall into an indefinite
wait.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damos_walk"></a>`damos_walk()`

```c
int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
```

Invoke a given functions while DAMOS walk regions.

**Parameters**

- `struct damon_ctx *ctx`: DAMON context to call the functions for.
- `struct damos_walk_control *control`: Control variable of the walk request.

**Description**

Ask DAMON worker thread (kdamond) of **ctx** to call a function for each region
that the kdamond will apply DAMOS action to, and wait until the kdamond
finishes handling of the request.

The kdamond executes the given function in the main loop, for each region
just after it applied any DAMOS actions of **ctx** to it.  The invocation is
made only within one [`damos->apply_interval_us`](#c-struct-damos) since [`damos_walk()`](#c-damos_walk)
invocation, for each scheme.  The given callback function can hence safely
access the internal data of [`struct damon_ctx`](#c-struct-damon_ctx) and [`struct damon_region`](#c-struct-damon_region) that
each of the scheme will apply the action for next interval, without
additional synchronizations against the kdamond.  If every scheme of **ctx**
passed at least one [`damos->apply_interval_us`](#c-struct-damos), kdamond marks the request as
completed so that [`damos_walk()`](#c-damos_walk) can wakeup and return.

Note that this function should be called only after [`damon_start()`](#c-damon_start) with the
**ctx** has succeeded.  Otherwise, this function could fall into an indefinite
wait.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_set_region_biggest_system_ram_default"></a>`damon_set_region_biggest_system_ram_default()`

```c
int damon_set_region_biggest_system_ram_default(struct damon_target *t, unsigned long *start, unsigned long *end, unsigned long min_region_sz)
```

Set the region of the given monitoring target as requested, or biggest 'System RAM'.

**Parameters**

- `struct damon_target *t`: The monitoring target to set the region.
- `unsigned long *start`: The pointer to the start address of the region.
- `unsigned long *end`: The pointer to the end address of the region.
- `unsigned long min_region_sz`: Minimum region size.

**Description**

This function sets the region of **t** as requested by **start** and **end**.  If the
values of **start** and **end** are zero, however, this function finds the biggest
'System RAM' resource and sets the region to cover the resource.  In the
latter case, this function saves the start and end addresses of the resource
in **start** and **end**, respectively.

**Return**

0 on success, negative error code otherwise.

#### <a id="c-damon_update_region_access_rate"></a>`damon_update_region_access_rate()`

```c
void damon_update_region_access_rate(struct damon_region *r, bool accessed, struct damon_attrs *attrs)
```

Update the access rate of a region.

**Parameters**

- `struct damon_region *r`: The DAMON region to update for its access check result.
- `bool accessed`: Whether the region has accessed during last sampling interval.
- `struct damon_attrs *attrs`: The damon_attrs of the DAMON context.

**Description**

Update the access rate of a region with the region's last sampling interval
access check result.

Usually this will be called by [`damon_operations->check_accesses`](#c-struct-damon_operations) callback.

#### <a id="c-damon_initialized"></a>`damon_initialized()`

```c
bool damon_initialized(void)
```

Return if DAMON is ready to be used.

**Parameters**

- `void`: no arguments

**Return**

true if DAMON is ready to be used, false otherwise.

---

# Design

_Peios Kernel / Internals / Memory management / damon_

> The monitoring-related information including the monitoring request specification and DAMON-based operation schemes are stored in a data structure called DAMON context. DAMON executes each context with a kernel thread called kdamond.…

<a id="rst-design"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-execution-model-and-data-structures"></a>
<a id="rst-damon-design-execution-model-and-data-structures"></a>

## Execution Model and Data Structures

The monitoring-related information including the monitoring request specification and DAMON-based operation schemes are stored in a data structure called DAMON `context`.  DAMON executes each context with a kernel thread called `kdamond`.  Multiple kdamonds could run in parallel, for different types of monitoring.

To know how user-space can do the configurations and start/stop DAMON, refer to [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>) documentation.

<a id="rst-overall-architecture"></a>

## Overall Architecture

DAMON subsystem is configured with three layers including

- [Operations Set](<#rst-damon-operations-set>): Implements fundamental operations for DAMON that depends on the given monitoring target address-space and available set of software/hardware primitives,

- [Core](<#rst-damon-core-logic>): Implements core logics including monitoring overhead/accuracy control and access-aware system operations on top of the operations set layer, and

- [Modules](<#rst-damon-modules>): Implements kernel modules for various purposes that provides interfaces for the user space, on top of the core layer.

<a id="rst-operations-set-layer"></a>
<a id="rst-damon-operations-set"></a>

## Operations Set Layer

<a id="rst-damon-design-configurable-operations-set"></a>

For data access monitoring and additional low level work, DAMON needs a set of implementations for specific operations that are dependent on and optimized for the given target address space.  For example, below two operations for access monitoring are address-space dependent.

1. Identification of the monitoring target address range for the address space.

2. Access check of specific address range in the target space.

DAMON consolidates these implementations in a layer called DAMON Operations Set, and defines the interface between it and the upper layer.  The upper layer is dedicated for DAMON's core logics including the mechanism for control of the monitoring accuracy and the overhead.

Hence, DAMON can easily be extended for any address space and/or available hardware features by configuring the core logic to use the appropriate operations set.  If there is no available operations set for a given purpose, a new operations set can be implemented following the interface between the layers.

For example, physical memory, virtual memory, swap space, those for specific processes, NUMA nodes, files, and backing memory devices would be supportable. Also, if some architectures or devices support special optimized access check features, those will be easily configurable.

DAMON currently provides below three operation sets.  Below three subsections describe how those work.

> - vaddr: Monitor virtual address spaces of specific processes
>
> - fvaddr: Monitor fixed virtual address ranges
>
> - paddr: Monitor the physical address space of the system

To know how user-space can do the configuration via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [operations](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-context>) file part of the documentation.

<a id="rst-vma-based-target-address-range-construction"></a>
<a id="rst-damon-design-vaddr-target-regions-construction"></a>

### VMA-based Target Address Range Construction

A mechanism of `vaddr` DAMON operations set that automatically initializes and updates the monitoring target address regions so that entire memory mappings of the target processes can be covered.

This mechanism is only for the `vaddr` operations set.  In cases of `fvaddr` and `paddr` operation sets, users are asked to manually set the monitoring target address ranges.

Only small parts in the super-huge virtual address space of the processes are mapped to the physical memory and accessed.  Thus, tracking the unmapped address regions is just wasteful.  However, because DAMON can deal with some level of noise using the adaptive regions adjustment mechanism, tracking every mapping is not strictly required but could even incur a high overhead in some cases.  That said, too huge unmapped areas inside the monitoring target should be removed to not take the time for the adaptive mechanism.

For the reason, this implementation converts the complex mappings to three distinct regions that cover every mapped area of the address space.  The two gaps between the three regions are the two biggest unmapped areas in the given address space.  The two biggest unmapped areas would be the gap between the heap and the uppermost mmap()-ed region, and the gap between the lowermost mmap()-ed region and the stack in most of the cases.  Because these gaps are exceptionally huge in usual address spaces, excluding these will be sufficient to make a reasonable trade-off.  Below shows this in detail:



```text
<heap>
<BIG UNMAPPED REGION 1>
<uppermost mmap()-ed region>
(small mmap()-ed regions and munmap()-ed regions)
<lowermost mmap()-ed region>
<BIG UNMAPPED REGION 2>
<stack>
```

<a id="rst-pte-accessed-bit-based-access-check"></a>

### PTE Accessed-bit Based Access Check

Both of the implementations for physical and virtual address spaces use PTE Accessed-bit for basic access checks.  Only one difference is the way of finding the relevant PTE Accessed bit(s) from the address.  While the implementation for the virtual address walks the page table for the target task of the address, the implementation for the physical address walks every page table having a mapping to the address.  In this way, the implementations find and clear the bit(s) for next sampling target address and checks whether the bit(s) set again after one sampling period.  This could disturb other kernel subsystems using the Accessed bits, namely Idle page tracking and the reclaim logic.  DAMON does nothing to avoid disturbing Idle page tracking, so handling the interference is the responsibility of sysadmins.  However, it solves the conflict with the reclaim logic using `PG_idle` and `PG_young` page flags, as Idle page tracking does.

<a id="rst-address-unit"></a>
<a id="rst-damon-design-addr-unit"></a>

### Address Unit

DAMON core layer uses `unsinged long` type for monitoring target address ranges.  In some cases, the address space for a given operations set could be too large to be handled with the type.  ARM (32-bit) with large physical address extension is an example.  For such cases, a per-operations set parameter called `address unit` is provided.  It represents the scale factor that need to be multiplied to the core layer's address for calculating real address on the given address space.  Support of `address unit` parameter is up to each operations set implementation.  `paddr` is the only operations set implementation that supports the parameter.

<a id="rst-core-logics"></a>
<a id="rst-damon-core-logic"></a>

## Core Logics

<a id="rst-monitoring"></a>
<a id="rst-damon-design-monitoring"></a>

### Monitoring

Below four sections describe each of the DAMON core mechanisms and the five monitoring attributes, `sampling interval`, `aggregation interval`, `update interval`, `minimum number of regions`, and `maximum number of regions`.

To know how user-space can set the attributes via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [monitoring_attrs](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-monitoring-attrs>) part of the documentation.

<a id="rst-access-frequency-monitoring"></a>

#### Access Frequency Monitoring

The output of DAMON says what pages are how frequently accessed for a given duration.  The resolution of the access frequency is controlled by setting `sampling interval` and `aggregation interval`.  In detail, DAMON checks access to each page per `sampling interval` and aggregates the results.  In other words, counts the number of the accesses to each page.  After each `aggregation interval` passes, DAMON calls callback functions that previously registered by users so that users can read the aggregated results and then clears the results.  This can be described in below simple pseudo-code:



```text
while monitoring_on:
    for page in monitoring_target:
        if accessed(page):
            nr_accesses[page] += 1
    if time() % aggregation_interval == 0:
        for callback in user_registered_callbacks:
            callback(monitoring_target, nr_accesses)
        for page in monitoring_target:
            nr_accesses[page] = 0
    sleep(sampling interval)
```

The monitoring overhead of this mechanism will arbitrarily increase as the size of the target workload grows.

<a id="rst-region-based-sampling"></a>
<a id="rst-damon-design-region-based-sampling"></a>

#### Region Based Sampling

To avoid the unbounded increase of the overhead, DAMON groups adjacent pages that assumed to have the same access frequencies into a region.  As long as the assumption (pages in a region have the same access frequencies) is kept, only one page in the region is required to be checked.  Thus, for each `sampling interval`, DAMON randomly picks one page in each region, waits for one `sampling interval`, checks whether the page is accessed meanwhile, and increases the access frequency counter of the region if so.  The counter is called `nr_accesses` of the region.  Therefore, the monitoring overhead is controllable by setting the number of regions.  DAMON allows users to set the minimum and the maximum number of regions for the trade-off.

This scheme, however, cannot preserve the quality of the output if the assumption is not guaranteed.

<a id="rst-adaptive-regions-adjustment"></a>
<a id="rst-damon-design-adaptive-regions-adjustment"></a>

#### Adaptive Regions Adjustment

Even somehow the initial monitoring target regions are well constructed to fulfill the assumption (pages in same region have similar access frequencies), the data access pattern can be dynamically changed.  This will result in low monitoring quality.  To keep the assumption as much as possible, DAMON adaptively merges and splits each region based on their access frequency.

For each `aggregation interval`, it compares the access frequencies (`nr_accesses`) of adjacent regions.  If the difference is small, and if the sum of the two regions' sizes is smaller than the size of total regions divided by the `minimum number of regions`, DAMON merges the two regions.  If the resulting number of total regions is still higher than `maximum number of regions`, it repeats the merging with increasing access frequenceis difference threshold until the upper-limit of the number of regions is met, or the threshold becomes higher than possible maximum value (`aggregation interval` divided by `sampling interval`).   Then, after it reports and clears the aggregated access frequency of each region, it splits each region into two or three regions if the total number of regions will not exceed the user-specified maximum number of regions after the split.

In this way, DAMON provides its best-effort quality and minimal overhead while keeping the bounds users set for their trade-off.

<a id="rst-age-tracking"></a>
<a id="rst-damon-design-age-tracking"></a>

#### Age Tracking

By analyzing the monitoring results, users can also find how long the current access pattern of a region has maintained.  That could be used for good understanding of the access pattern.  For example, page placement algorithm utilizing both the frequency and the recency could be implemented using that. To make such access pattern maintained period analysis easier, DAMON maintains yet another counter called `age` in each region.  For each `aggregation interval`, DAMON checks if the region's size and access frequency (`nr_accesses`) has significantly changed.  If so, the counter is reset to zero.  Otherwise, the counter is increased.

<a id="rst-dynamic-target-space-updates-handling"></a>

#### Dynamic Target Space Updates Handling

The monitoring target address range could dynamically changed.  For example, virtual memory could be dynamically mapped and unmapped.  Physical memory could be hot-plugged.

As the changes could be quite frequent in some cases, DAMON allows the monitoring operations to check dynamic changes including memory mapping changes and applies it to monitoring operations-related data structures such as the abstracted monitoring target memory area only for each of a user-specified time interval (`update interval`).

User-space can get the monitoring results via DAMON sysfs interface and/or tracepoints.  For more details, please refer to the documentations for [DAMOS tried regions](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-schemes-tried-regions>) and [Tracepoints for Monitoring Results](</kernel/administration/admin-guide/mm-damon/usage.md#rst-tracepoint>), respectively.

<a id="rst-monitoring-parameters-tuning-guide"></a>
<a id="rst-damon-design-monitoring-params-tuning-guide"></a>

#### Monitoring Parameters Tuning Guide

In short, set `aggregation interval` to capture meaningful amount of accesses for the purpose.  The amount of accesses can be measured using `nr_accesses` and `age` of regions in the aggregated monitoring results snapshot.  The default value of the interval, `100ms`, turns out to be too short in many cases.  Set `sampling interval` proportional to `aggregation interval`.  By default, `1/20` is recommended as the ratio.

`Aggregation interval` should be set as the time interval that the workload can make an amount of accesses for the monitoring purpose, within the interval. If the interval is too short, only small number of accesses are captured.  As a result, the monitoring results look everything is samely accessed only rarely. For many purposes, that would be useless.  If it is too long, however, the time to converge regions with the [regions adjustment mechanism](<#rst-damon-design-adaptive-regions-adjustment>) can be too long, depending on the time scale of the given purpose.  This could happen if the workload is actually making only rare accesses but the user thinks the amount of accesses for the monitoring purpose too high.  For such cases, the target amount of access to capture per `aggregation interval` should carefully reconsidered.  Also, note that the captured amount of accesses is represented with not only `nr_accesses`, but also `age`.  For example, even if every region on the monitoring results show zero `nr_accesses`, regions could still be distinguished using `age` values as the recency information.

Hence the optimum value of `aggregation interval` depends on the access intensiveness of the workload.  The user should tune the interval based on the amount of access that captured on each aggregated snapshot of the monitoring results.

Note that the default value of the interval is 100 milliseconds, which is too short in many cases, especially on large systems.

`Sampling interval` defines the resolution of each aggregation.  If it is set too large, monitoring results will look like every region was samely rarely accessed, or samely frequently accessed.  That is, regions become undistinguishable based on access pattern, and therefore the results will be useless in many use cases.  If `sampling interval` is too small, it will not degrade the resolution, but will increase the monitoring overhead.  If it is appropriate enough to provide a resolution of the monitoring results that sufficient for the given purpose, it shouldn't be unnecessarily further lowered.  It is recommended to be set proportional to `aggregation interval`. By default, the ratio is set as `1/20`, and it is still recommended.

Based on the manual tuning guide, DAMON provides more intuitive knob-based intervals auto tuning mechanism.  Please refer to [the design document of the feature](<#rst-damon-design-monitoring-intervals-autotuning>) for detail.

Refer to below documents for an example tuning based on the above guide.

- [DAMON Moniting Interval Parameters Tuning Example](</kernel/internals/mm/damon/monitoring-intervals-tuning-example.md>)

<a id="rst-monitoring-intervals-auto-tuning"></a>
<a id="rst-damon-design-monitoring-intervals-autotuning"></a>

#### Monitoring Intervals Auto-tuning

DAMON provides automatic tuning of the `sampling interval` and `aggregation interval` based on the [the tuning guide idea](<#rst-damon-design-monitoring-params-tuning-guide>).  The tuning mechanism allows users to set the aimed amount of access events to observe via DAMON within given time interval.  The target can be specified by the user as a ratio of DAMON-observed access events to the theoretical maximum amount of the events (`access_bp`) that measured within a given number of aggregations (`aggrs`).

The DAMON-observed access events are calculated in byte granularity based on DAMON [region assumption](<#rst-damon-design-region-based-sampling>).  For example, if a region of size `X` bytes of `Y` `nr_accesses` is found, it means `X * Y` access events are observed by DAMON.  Theoretical maximum access events for the region is calculated in same way, but replacing `Y` with theoretical maximum `nr_accesses`, which can be calculated as `aggregation interval / sampling interval`.

The mechanism calculates the ratio of access events for `aggrs` aggregations, and increases or decrease the `sampleing interval` and `aggregation interval` in same ratio, if the observed access ratio is lower or higher than the target, respectively.  The ratio of the intervals change is decided in proportion to the distance between current samples ratio and the target ratio.

The user can further set the minimum and maximum `sampling interval` that can be set by the tuning mechanism using two parameters (`min_sample_us` and `max_sample_us`).  Because the tuning mechanism changes `sampling interval` and `aggregation interval` in same ratio always, the minimum and maximum `aggregation interval` after each of the tuning changes can automatically set together.

The tuning is turned off by default, and need to be set explicitly by the user. As a rule of thumbs and the Parreto principle, 4% access samples ratio target is recommended.  Note that Parreto principle (80/20 rule) has applied twice. That is, assumes 4% (20% of 20%) DAMON-observed access events ratio (source) to capture 64% (80% multipled by 80%) real access events (outcomes).

To know how user-space can use this feature via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [intervals_goal](</kernel/administration/admin-guide/mm-damon/usage.md#rst-damon-usage-sysfs-monitoring-intervals-goal>) part of the documentation.

<a id="rst-operation-schemes"></a>
<a id="rst-damon-design-damos"></a>

### Operation Schemes

One common purpose of data access monitoring is access-aware system efficiency optimizations.  For example,

> paging out memory regions that are not accessed for more than two minutes

or

> using THP for memory regions that are larger than 2 MiB and showing a high access frequency for more than one minute.

One straightforward approach for such schemes would be profile-guided optimizations.  That is, getting data access monitoring results of the workloads or the system using DAMON, finding memory regions of special characteristics by profiling the monitoring results, and making system operation changes for the regions.  The changes could be made by modifying or providing advice to the software (the application and/or the kernel), or reconfiguring the hardware.  Both offline and online approaches could be available.

Among those, providing advice to the kernel at runtime would be flexible and effective, and therefore widely be used.   However, implementing such schemes could impose unnecessary redundancy and inefficiency.  The profiling could be redundant if the type of interest is common.  Exchanging the information including monitoring results and operation advice between kernel and user spaces could be inefficient.

To allow users to reduce such redundancy and inefficiencies by offloading the works, DAMON provides a feature called Data Access Monitoring-based Operation Schemes (DAMOS).  It lets users specify their desired schemes at a high level.  For such specifications, DAMON starts monitoring, finds regions having the access pattern of interest, and applies the user-desired operation actions to the regions, for every user-specified time interval called `apply_interval`.

To know how user-space can set `apply_interval` via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [apply_interval_us](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-scheme>) part of the documentation.

<a id="rst-operation-action"></a>
<a id="rst-damon-design-damos-action"></a>

#### Operation Action

The management action that the users desire to apply to the regions of their interest.  For example, paging out, prioritizing for next reclamation victim selection, advising `khugepaged` to collapse or split, or doing nothing but collecting statistics of the regions.

The list of supported actions is defined in DAMOS, but the implementation of each action is in the DAMON operations set layer because the implementation normally depends on the monitoring target address space.  For example, the code for paging specific virtual address ranges out would be different from that for physical address ranges.  And the monitoring operations implementation sets are not mandated to support all actions of the list.  Hence, the availability of specific DAMOS action depends on what operations set is selected to be used together.

The list of the supported actions, their meaning, and DAMON operations sets that supports each action are as below.

> - `willneed`: Call `madvise()` for the region with `MADV_WILLNEED`. Supported by `vaddr` and `fvaddr` operations set.
>
> - `cold`: Call `madvise()` for the region with `MADV_COLD`. Supported by `vaddr` and `fvaddr` operations set.
>
> - `pageout`: Reclaim the region. Supported by `vaddr`, `fvaddr` and `paddr` operations set.
>
> - `hugepage`: Call `madvise()` for the region with `MADV_HUGEPAGE`. Supported by `vaddr` and `fvaddr` operations set.
>
> - `nohugepage`: Call `madvise()` for the region with `MADV_NOHUGEPAGE`. Supported by `vaddr` and `fvaddr` operations set.
>
> - `lru_prio`: Prioritize the region on its LRU lists. Supported by `paddr` operations set.
>
> - `lru_deprio`: Deprioritize the region on its LRU lists. Supported by `paddr` operations set.
>
> - `migrate_hot`: Migrate the regions prioritizing warmer regions. Supported by `vaddr`, `fvaddr` and `paddr` operations set.
>
> - `migrate_cold`: Migrate the regions prioritizing colder regions. Supported by `vaddr`, `fvaddr` and `paddr` operations set.
>
> - `stat`: Do nothing but count the statistics. Supported by all operations sets.

Applying the actions except `stat` to a region is considered as changing the region's characteristics.  Hence, DAMOS resets the age of regions when any such actions are applied to those.

To know how user-space can set the action via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [action](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-scheme>) part of the documentation.

<a id="rst-target-access-pattern"></a>
<a id="rst-damon-design-damos-access-pattern"></a>

#### Target Access Pattern

The access pattern of the schemes' interest.  The patterns are constructed with the properties that DAMON's monitoring results provide, specifically the size, the access frequency, and the age.  Users can describe their access pattern of interest by setting minimum and maximum values of the three properties.  If a region's three properties are in the ranges, DAMOS classifies it as one of the regions that the scheme is having an interest in.

To know how user-space can set the access pattern via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [access_pattern](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-access-pattern>) part of the documentation.

<a id="rst-quotas"></a>
<a id="rst-damon-design-damos-quotas"></a>

#### Quotas

DAMOS upper-bound overhead control feature.  DAMOS could incur high overhead if the target access pattern is not properly tuned.  For example, if a huge memory region having the access pattern of interest is found, applying the scheme's action to all pages of the huge region could consume unacceptably large system resources.  Preventing such issues by tuning the access pattern could be challenging, especially if the access patterns of the workloads are highly dynamic.

To mitigate that situation, DAMOS provides an upper-bound overhead control feature called quotas.  It lets users specify an upper limit of time that DAMOS can use for applying the action, and/or a maximum bytes of memory regions that the action can be applied within a user-specified time duration.

To know how user-space can set the basic quotas via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [quotas](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-quotas>) part of the documentation.

<a id="rst-prioritization"></a>
<a id="rst-damon-design-damos-quotas-prioritization"></a>

##### Prioritization

A mechanism for making a good decision under the quotas.  When the action cannot be applied to all regions of interest due to the quotas, DAMOS prioritizes regions and applies the action to only regions having high enough priorities so that it will not exceed the quotas.

The prioritization mechanism should be different for each action.  For example, rarely accessed (colder) memory regions would be prioritized for page-out scheme action.  In contrast, the colder regions would be deprioritized for huge page collapse scheme action.  Hence, the prioritization mechanisms for each action are implemented in each DAMON operations set, together with the actions.

Though the implementation is up to the DAMON operations set, it would be common to calculate the priority using the access pattern properties of the regions. Some users would want the mechanisms to be personalized for their specific case.  For example, some users would want the mechanism to weigh the recency (`age`) more than the access frequency (`nr_accesses`).  DAMOS allows users to specify the weight of each access pattern property and passes the information to the underlying mechanism.  Nevertheless, how and even whether the weight will be respected are up to the underlying prioritization mechanism implementation.

To know how user-space can set the prioritization weights via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [weights](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-quotas>) part of the documentation.

<a id="rst-aim-oriented-feedback-driven-auto-tuning"></a>
<a id="rst-damon-design-damos-quotas-auto-tuning"></a>

##### Aim-oriented Feedback-driven Auto-tuning

Automatic feedback-driven quota tuning.  Instead of setting the absolute quota value, users can specify the metric of their interest, and what target value they want the metric value to be.  DAMOS then automatically tunes the aggressiveness (the quota) of the corresponding scheme.  For example, if DAMOS is under achieving the goal, DAMOS automatically increases the quota.  If DAMOS is over achieving the goal, it decreases the quota.

The goal can be specified with five parameters, namely `target_metric`, `target_value`, `current_value`, `nid` and `path`.  The auto-tuning mechanism tries to make `current_value` of `target_metric` be same to `target_value`.

- `user_input`: User-provided value.  Users could use any metric that they has interest in for the value.  Use space main workload's latency or throughput, system metrics like free memory ratio or memory pressure stall time (PSI) could be examples.  Note that users should explicitly set `current_value` on their own in this case.  In other words, users should repeatedly provide the feedback.

- `some_mem_psi_us`: System-wide `some` memory pressure stall information in microseconds that measured from last quota reset to next quota reset. DAMOS does the measurement on its own, so only `target_value` need to be set by users at the initial time.  In other words, DAMOS does self-feedback.

- `node_mem_used_bp`: Specific NUMA node's used memory ratio in bp (1/10,000).

- `node_mem_free_bp`: Specific NUMA node's free memory ratio in bp (1/10,000).

- `node_memcg_used_bp`: Specific cgroup's node used memory ratio for a specific NUMA node, in bp (1/10,000).

- `node_memcg_free_bp`: Specific cgroup's node unused memory ratio for a specific NUMA node, in bp (1/10,000).

- `active_mem_bp`: Active to active + inactive (LRU) memory size ratio in bp (1/10,000).

- `inactive_mem_bp`: Inactive to active + inactive (LRU) memory size ratio in bp (1/10,000).

`nid` is optionally required for only `node_mem_used_bp`, `node_mem_free_bp`, `node_memcg_used_bp` and `node_memcg_free_bp` to point the specific NUMA node.

`path` is optionally required for only `node_memcg_used_bp` and `node_memcg_free_bp` to point the path to the cgroup.  The value should be the path of the memory cgroup from the cgroups mount point.

To know how user-space can set the tuning goal metric, the target value, and/or the current value via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [quota goals](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-schemes-quota-goals>) part of the documentation.

<a id="rst-watermarks"></a>
<a id="rst-damon-design-damos-watermarks"></a>

#### Watermarks

Conditional DAMOS (de)activation automation.  Users might want DAMOS to run only under certain situations.  For example, when a sufficient amount of free memory is guaranteed, running a scheme for proactive reclamation would only consume unnecessary system resources.  To avoid such consumption, the user would need to manually monitor some metrics such as free memory ratio, and turn DAMON/DAMOS on or off.

DAMOS allows users to offload such works using three watermarks.  It allows the users to configure the metric of their interest, and three watermark values, namely high, middle, and low.  If the value of the metric becomes above the high watermark or below the low watermark, the scheme is deactivated.  If the metric becomes below the mid watermark but above the low watermark, the scheme is activated.  If all schemes are deactivated by the watermarks, the monitoring is also deactivated.  In this case, the DAMON worker thread only periodically checks the watermarks and therefore incurs nearly zero overhead.

To know how user-space can set the watermarks via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [watermarks](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-watermarks>) part of the documentation.

<a id="rst-filters"></a>
<a id="rst-damon-design-damos-filters"></a>

#### Filters

Non-access pattern-based target memory regions filtering.  If users run self-written programs or have good profiling tools, they could know something more than the kernel, such as future access patterns or some special requirements for specific types of memory. For example, some users may know only anonymous pages can impact their program's performance.  They can also have a list of latency-critical processes.

To let users optimize DAMOS schemes with such special knowledge, DAMOS provides a feature called DAMOS filters.  The feature allows users to set an arbitrary number of filters for each scheme.  Each filter specifies

- a type of memory (`type`),

- whether it is for the memory of the type or all except the type (`matching`), and

- whether it is to allow (include) or reject (exclude) applying the scheme's action to the memory (`allow`).

For efficient handling of filters, some types of filters are handled by the core layer, while others are handled by operations set.  In the latter case, hence, support of the filter types depends on the DAMON operations set.  In case of the core layer-handled filters, the memory regions that excluded by the filter are not counted as the scheme has tried to the region.  In contrast, if a memory regions is filtered by an operations set layer-handled filter, it is counted as the scheme has tried.  This difference affects the statistics.

When multiple filters are installed, the group of filters that handled by the core layer are evaluated first.  After that, the group of filters that handled by the operations layer are evaluated.  Filters in each of the groups are evaluated in the installed order.  If a part of memory is matched to one of the filter, next filters are ignored.  If the part passes through the filters evaluation stage because it is not matched to any of the filters, applying the scheme's action to it depends on the last filter's allowance type.  If the last filter was for allowing, the part of memory will be rejected, and vice versa.

For example, let's assume 1) a filter for allowing anonymous pages and 2) another filter for rejecting young pages are installed in the order.  If a page of a region that eligible to apply the scheme's action is an anonymous page, the scheme's action will be applied to the page regardless of whether it is young or not, since it matches with the first allow-filter.  If the page is not anonymous but young, the scheme's action will not be applied, since the second reject-filter blocks it.  If the page is neither anonymous nor young, the page will pass through the filters evaluation stage since there is no matching filter, and the action will be applied to the page.

Below `type` of filters are currently supported.

- - **Core layer handled**

    - - **addr**

        - Applied to pages that belonging to a given address range.

    - - **target**

        - Applied to pages that belonging to a given DAMON monitoring target.

- - **Operations layer handled, supported by only `paddr` operations set.**

    - - **anon**

        - Applied to pages that containing data that not stored in files.

    - - **active**

        - Applied to active pages.

    - - **memcg**

        - Applied to pages that belonging to a given cgroup.

    - - **young**

        - Applied to pages that are accessed after the last access check from the scheme.

    - - **hugepage_size**

        - Applied to pages that managed in a given size range.

    - - **unmapped**

        - Applied to pages that unmapped.

To know how user-space can set the filters via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to [filters](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-filters>) part of the documentation.

<a id="rst-statistics"></a>
<a id="rst-damon-design-damos-stat"></a>

#### Statistics

The statistics of DAMOS behaviors that designed to help monitoring, tuning and debugging of DAMOS.

DAMOS accounts below statistics for each scheme, from the beginning of the scheme's execution.

- `nr_tried`: Total number of regions that the scheme is tried to be applied.

- `sz_tried`: Total size of regions that the scheme is tried to be applied.

- `sz_ops_filter_passed`: Total bytes that passed operations set layer-handled DAMOS filters.

- `nr_applied`: Total number of regions that the scheme is applied.

- `sz_applied`: Total size of regions that the scheme is applied.

- `qt_exceeds`: Total number of times the quota of the scheme has exceeded.

- `nr_snapshots`: Total number of DAMON snapshots that the scheme is tried to be applied.

- `max_nr_snapshots`: Upper limit of `nr_snapshots`.

"A scheme is tried to be applied to a region" means DAMOS core logic determined the region is eligible to apply the scheme's [action](<#rst-damon-design-damos-action>).  The [access pattern](<#rst-damon-design-damos-access-pattern>), [quotas](<#rst-damon-design-damos-quotas>), [watermarks](<#rst-damon-design-damos-watermarks>), and [filters](<#rst-damon-design-damos-filters>) that handled on core logic could affect this. The core logic will only ask the underlying [operation set](<#rst-damon-operations-set>) to do apply the action to the region, so whether the action is really applied or not is unclear.  That's why it is called "tried".

"A scheme is applied to a region" means the [operation set](<#rst-damon-operations-set>) has applied the action to at least a part of the region.  The [filters](<#rst-damon-design-damos-filters>) that handled by the operation set, and the types of the [action](<#rst-damon-design-damos-action>) and the pages of the region can affect this.  For example, if a filter is set to exclude anonymous pages and the region has only anonymous pages, or if the action is `pageout` while all pages of the region are unreclaimable, applying the action to the region will fail.

Unlike normal stats, `max_nr_snapshots` is set by users.  If it is set as non-zero and `nr_snapshots` be same to or greater than `nr_snapshots`, the scheme is deactivated.

To know how user-space can read the stats via [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>), refer to :ref:s\`stats &lt;sysfs_stats&gt;\` part of the documentation.

<a id="rst-regions-walking"></a>

#### Regions Walking

DAMOS feature allowing users access each region that a DAMOS action has just applied.  Using this feature, DAMON [API](<#rst-damon-design-api>) allows users access full properties of the regions including the access monitoring results and amount of the region's internal memory that passed the DAMOS filters. [DAMON sysfs interface](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>) also allows users read the data via special [files](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-schemes-tried-regions>).

<a id="rst-application-programming-interface"></a>
<a id="rst-damon-design-api"></a>

### Application Programming Interface

The programming interface for kernel space data access-aware applications. DAMON is a framework, so it does nothing by itself.  Instead, it only helps other kernel components such as subsystems and modules building their data access-aware applications using DAMON's core features.  For this, DAMON exposes its all features to other kernel components via its application programming interface, namely `include/linux/damon.h`.  Please refer to the API [document](</kernel/internals/mm/damon/api.md>) for details of the interface.

<a id="rst-modules"></a>
<a id="rst-damon-modules"></a>

## Modules

Because the core of DAMON is a framework for kernel components, it doesn't provide any direct interface for the user space.  Such interfaces should be implemented by each DAMON API user kernel components, instead.  DAMON subsystem itself implements such DAMON API user modules, which are supposed to be used for general purpose DAMON control and special purpose data access-aware system operations, and provides stable application binary interfaces (ABI) for the user space.  The user space can build their efficient data access-aware applications using the interfaces.

<a id="rst-general-purpose-user-interface-modules"></a>

### General Purpose User Interface Modules

DAMON modules that provide user space ABIs for general purpose DAMON usage in runtime.

Like many other ABIs, the modules create files on pseudo file systems like 'sysfs', allow users to specify their requests to and get the answers from DAMON by writing to and reading from the files.  As a response to such I/O, DAMON user interface modules control DAMON and retrieve the results as user requested via the DAMON API, and return the results to the user-space.

The ABIs are designed to be used for user space applications development, rather than human beings' fingers.  Human users are recommended to use such user space tools.  One such Python-written user space tool is available at Github ([https://github.com/damonitor/damo](<https://github.com/damonitor/damo>)), Pypi ([https://pypistats.org/packages/damo](<https://pypistats.org/packages/damo>)), and multiple distros ([https://repology.org/project/damo/versions](<https://repology.org/project/damo/versions>)).

Currently, one module for this type, namely 'DAMON sysfs interface' is available.  Please refer to the ABI [doc](</kernel/administration/admin-guide/mm-damon/usage.md#rst-sysfs-interface>) for details of the interfaces.

<a id="rst-special-purpose-access-aware-kernel-modules"></a>
<a id="rst-damon-modules-special-purpose"></a>

### Special-Purpose Access-aware Kernel Modules

DAMON modules that provide user space ABI for specific purpose DAMON usage.

DAMON user interface modules are for full control of all DAMON features in runtime.  For each special-purpose system-wide data access-aware system operations such as proactive reclamation or LRU lists balancing, the interfaces could be simplified by removing unnecessary knobs for the specific purpose, and extended for boot-time and even compile time control.  Default values of DAMON control parameters for the usage would also need to be optimized for the purpose.

To support such cases, yet more DAMON API user kernel modules that provide more simple and optimized user space interfaces are available.  Currently, two modules for proactive reclamation and LRU lists manipulation are provided.  For more detail, please read the usage documents for those ([Data Access Monitoring Results Stat](</kernel/administration/admin-guide/mm-damon/stat.md>), [DAMON-based Reclamation](</kernel/administration/admin-guide/mm-damon/reclaim.md>) and [DAMON-based LRU-lists Sorting](</kernel/administration/admin-guide/mm-damon/lru-sort.md>)).

<a id="rst-sample-damon-modules"></a>

### Sample DAMON Modules

DAMON modules that provides example DAMON kernel API usages.

kernel programmers can build their own special or general purpose DAMON modules using DAMON kernel API.  To help them easily understand how DAMON kernel API can be used, a few sample modules are provided under `samples/damon/` of the linux source tree.  Please note that these modules are not developed for being used on real products, but only for showing how DAMON kernel API can be used in simple ways.

---

# Frequently Asked Questions

_Peios Kernel / Internals / Memory management / damon_

> No. The core of the DAMON is address space independent. The address space specific monitoring operations including monitoring target regions constructions and actual access checks can be implemented and configured on the DAMON core by the…

<a id="rst-frequently-asked-questions"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-does-damon-support-virtual-memory-only"></a>

## Does DAMON support virtual memory only?

No.  The core of the DAMON is address space independent.  The address space specific monitoring operations including monitoring target regions constructions and actual access checks can be implemented and configured on the DAMON core by the users.  In this way, DAMON users can monitor any address space with any access check technique.

Nonetheless, DAMON provides vma/rmap tracking and PTE Accessed bit check based implementations of the address space dependent functions for the virtual memory and the physical memory by default, for a reference and convenient use.

<a id="rst-can-i-simply-monitor-page-granularity"></a>

## Can I simply monitor page granularity?

Yes.  You can do so by setting the `min_nr_regions` attribute higher than the working set size divided by the page size.  Because the monitoring target regions size is forced to be `>=page size`, the region split will make no effect.

---

# DAMON Maintainer Entry Profile

_Peios Kernel / Internals / Memory management / damon_

> The DAMON subsystem covers the files that are listed in 'DAMON' section of 'MAINTAINERS' file.

<a id="rst-damon-maintainer-entry-profile"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The DAMON subsystem covers the files that are listed in 'DAMON' section of 'MAINTAINERS' file.

The mailing lists for the subsystem are [damon@lists.linux.dev](<mailto:damon@lists.linux.dev>) and [linux-mm@kvack.org](<mailto:linux-mm@kvack.org>).  Patches should be made against the [mm-new tree](<https://git.kernel.org/akpm/mm/h/mm-new>)<a id="rst-mm-new-tree"></a> whenever possible and posted to the mailing lists.

<a id="rst-scm-trees"></a>

## SCM Trees

There are multiple Linux trees for DAMON development.  Patches under development or testing are queued in [damon/next](<https://git.kernel.org/sj/h/damon/next>)<a id="rst-damon-next"></a> by the DAMON maintainer. Sufficiently reviewed patches will be queued in [mm-new](<https://git.kernel.org/akpm/mm/h/mm-new>)<a id="rst-mm-new"></a> by the memory management subsystem maintainer.  As more sufficient tests are done, the patches will move to [mm-unstable](<https://git.kernel.org/akpm/mm/h/mm-unstable>)<a id="rst-mm-unstable"></a> and then to [mm-stable](<https://git.kernel.org/akpm/mm/h/mm-stable>)<a id="rst-mm-stable"></a>.  And finally those will be pull-requested to the mainline by the memory management subsystem maintainer.

Note again the patches for [mm-new tree](<https://git.kernel.org/akpm/mm/h/mm-new>)<a id="rst-mm-new-tree-1"></a> are queued by the memory management subsystem maintainer.  If the patches require some patches in [damon/next tree](<https://git.kernel.org/sj/h/damon/next>)<a id="rst-damon-next-tree"></a> which have not yet merged in mm-new, please make sure the requirement is clearly specified.

<a id="rst-submit-checklist-addendum"></a>

## Submit checklist addendum

When making DAMON changes, you should do below.

- Build changes related outputs including kernel and documents.

- Ensure the builds introduce no new errors or warnings.

- Run and ensure no new failures for DAMON [selftests](<https://github.com/damonitor/damon-tests/blob/master/corr/run.sh#L49>)<a id="rst-selftests"></a> and [kunittests](<https://github.com/damonitor/damon-tests/blob/master/corr/tests/kunit.sh>)<a id="rst-kunittests"></a>.

Further doing below and putting the results will be helpful.

- Run [damon-tests/corr](<https://github.com/damonitor/damon-tests/tree/master/corr>)<a id="rst-damon-tests-corr"></a> for normal changes.

- Measure impacts on benchmarks or real world workloads for performance changes.

<a id="rst-key-cycle-dates"></a>

## Key cycle dates

Patches can be sent anytime.  Key cycle dates of the [mm-new](<https://git.kernel.org/akpm/mm/h/mm-new>)<a id="rst-mm-new-1"></a>, [mm-unstable](<https://git.kernel.org/akpm/mm/h/mm-unstable>)<a id="rst-mm-unstable-1"></a> and [mm-stable](<https://git.kernel.org/akpm/mm/h/mm-stable>)<a id="rst-mm-stable-1"></a> trees depend on the memory management subsystem maintainer.

<a id="rst-review-cadence"></a>

## Review cadence

The DAMON maintainer does the work on the usual work hour (09:00 to 17:00, Mon-Fri) in PT (Pacific Time).  The response to patches will occasionally be slow.  Do not hesitate to send a ping if you have not heard back within a week of sending a patch.

<a id="rst-mailing-tool"></a>

## Mailing tool

Like many other Linux kernel subsystems, DAMON uses the mailing lists ([damon@lists.linux.dev](<mailto:damon@lists.linux.dev>) and [linux-mm@kvack.org](<mailto:linux-mm@kvack.org>)) as the major communication channel.  There is a simple tool called [HacKerMaiL](<https://github.com/damonitor/hackermail>)<a id="rst-hackermail"></a> (`hkml`), which is for people who are not very familiar with the mailing lists based communication.  The tool could be particularly helpful for DAMON community members since it is developed and maintained by DAMON maintainer.  The tool is also officially announced to support DAMON and general Linux kernel development workflow.

In other words, [hkml](<https://github.com/damonitor/hackermail>)<a id="rst-hkml"></a> is a mailing tool for DAMON community, which DAMON maintainer is committed to support. Please feel free to try and report issues or feature requests for the tool to the maintainer.

<a id="rst-community-meetup"></a>

## Community meetup

DAMON community has a bi-weekly meetup series for members who prefer synchronous conversations over mails.  It is for discussions on specific topics between a group of members including the maintainer.  The maintainer shares the available time slots, and attendees should reserve one of those at least 24 hours before the time slot, by reaching out to the maintainer.

Schedules and reservation status are available at the Google [doc](<https://docs.google.com/document/d/1v43Kcj3ly4CYqmAkMaZzLiM2GEnWfgdGbZAH3mi2vpM/edit?usp=sharing>)<a id="rst-doc"></a>. There is also a public Google [calendar](<https://calendar.google.com/calendar/u/0?cid=ZDIwOTA4YTMxNjc2MDQ3NTIyMmUzYTM5ZmQyM2U4NDA0ZGIwZjBiYmJlZGQxNDM0MmY4ZTRjOTE0NjdhZDRiY0Bncm91cC5jYWxlbmRhci5nb29nbGUuY29t>)<a id="rst-calendar"></a> that has the events.  Anyone can subscribe to it.  DAMON maintainer will also provide periodic reminders to the mailing list ([damon@lists.linux.dev](<mailto:damon@lists.linux.dev>)).

---

# DAMON Moniting Interval Parameters Tuning Example

_Peios Kernel / Internals / Memory management / damon_

> DAMON's monitoring parameters need tuning based on given workload and the monitoring purpose. There is a tuning guide <damon_design_monitoring_params_tuning_guide> for that. This document provides an example tuning based on the guide.

<a id="rst-damon-moniting-interval-parameters-tuning-example"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

DAMON's monitoring parameters need tuning based on given workload and the monitoring purpose.  There is a [tuning guide](</kernel/internals/mm/damon/design.md#rst-damon-design-monitoring-params-tuning-guide>) for that.  This document provides an example tuning based on the guide.

<a id="rst-setup"></a>

## Setup

For below example, DAMON of Linux kernel v6.11 and [damo](<https://github.com/damonitor/damo>)<a id="rst-damo"></a> (DAMON user-space tool) v2.5.9 was used to monitor and visualize access patterns on the physical address space of a system running a real-world server workload.

<a id="rst-ms-100ms-intervals-too-short-interval"></a>

## 5ms/100ms intervals: Too Short Interval

Let's start by capturing the access pattern snapshot on the physical address space of the system using DAMON, with the default interval parameters (5 milliseconds and 100 milliseconds for the sampling and the aggregation intervals, respectively).  Wait ten minutes between the start of DAMON and the capturing of the snapshot, to show a meaningful time-wise access patterns.



```text
# damo start
# sleep 600
# damo record --snapshot 0 1
# damo stop
```

Then, list the DAMON-found regions of different access patterns, sorted by the "access temperature".  "Access temperature" is a metric representing the access-hotness of a region.  It is calculated as a weighted sum of the access frequency and the age of the region.  If the access frequency is 0 %, the temperature is multiplied by minus one.  That is, if a region is not accessed, it gets minus temperature and it gets lower as not accessed for longer time. The sorting is in temperature-ascendint order, so the region at the top of the list is the coldest, and the one at the bottom is the hottest one.



```text
# damo report access --sort_regions_by temperature
0   addr 16.052 GiB   size 5.985 GiB   access 0 %   age 5.900 s    # coldest
1   addr 22.037 GiB   size 6.029 GiB   access 0 %   age 5.300 s
2   addr 28.065 GiB   size 6.045 GiB   access 0 %   age 5.200 s
3   addr 10.069 GiB   size 5.983 GiB   access 0 %   age 4.500 s
4   addr 4.000 GiB    size 6.069 GiB   access 0 %   age 4.400 s
5   addr 62.008 GiB   size 3.992 GiB   access 0 %   age 3.700 s
6   addr 56.795 GiB   size 5.213 GiB   access 0 %   age 3.300 s
7   addr 39.393 GiB   size 6.096 GiB   access 0 %   age 2.800 s
8   addr 50.782 GiB   size 6.012 GiB   access 0 %   age 2.800 s
9   addr 34.111 GiB   size 5.282 GiB   access 0 %   age 2.300 s
10  addr 45.489 GiB   size 5.293 GiB   access 0 %   age 1.800 s    # hottest
total size: 62.000 GiB
```

The list shows not seemingly hot regions, and only minimum access pattern diversity.  Every region has zero access frequency.  The number of region is 10, which is the default `min_nr_regions value`.  Size of each region is also nearly identical.  We can suspect this is because “adaptive regions adjustment” mechanism was not well working.  As the guide suggested, we can get relative hotness of regions using `age` as the recency information.  That would be better than nothing, but given the fact that the longest age is only about 6 seconds while we waited about ten minutes, it is unclear how useful this will be.

The temperature ranges to total size of regions of each range histogram visualization of the results also shows no interesting distribution pattern.



```text
# damo report access --style temperature-sz-hist
<temperature> <total size>
[-,590,000,000, -,549,000,000) 5.985 GiB  |**********          |
[-,549,000,000, -,508,000,000) 12.074 GiB |********************|
[-,508,000,000, -,467,000,000) 0 B        |                    |
[-,467,000,000, -,426,000,000) 12.052 GiB |********************|
[-,426,000,000, -,385,000,000) 0 B        |                    |
[-,385,000,000, -,344,000,000) 3.992 GiB  |*******             |
[-,344,000,000, -,303,000,000) 5.213 GiB  |*********           |
[-,303,000,000, -,262,000,000) 12.109 GiB |********************|
[-,262,000,000, -,221,000,000) 5.282 GiB  |*********           |
[-,221,000,000, -,180,000,000) 0 B        |                    |
[-,180,000,000, -,139,000,000) 5.293 GiB  |*********           |
total size: 62.000 GiB
```

In short, the parameters provide poor quality monitoring results for hot regions detection. According to the [guide](</kernel/internals/mm/damon/design.md#rst-damon-design-monitoring-params-tuning-guide>), this is due to the too short aggregation interval.

<a id="rst-ms-2s-intervals-starts-showing-small-hot-regions"></a>

## 100ms/2s intervals: Starts Showing Small Hot Regions

Following the guide, increase the interval 20 times (100 milliseocnds and 2 seconds for sampling and aggregation intervals, respectively).



```text
# damo start -s 100ms -a 2s
# sleep 600
# damo record --snapshot 0 1
# damo stop
# damo report access --sort_regions_by temperature
0   addr 10.180 GiB   size 6.117 GiB   access 0 %   age 7 m 8 s    # coldest
1   addr 49.275 GiB   size 6.195 GiB   access 0 %   age 6 m 14 s
2   addr 62.421 GiB   size 3.579 GiB   access 0 %   age 6 m 4 s
3   addr 40.154 GiB   size 6.127 GiB   access 0 %   age 5 m 40 s
4   addr 16.296 GiB   size 6.182 GiB   access 0 %   age 5 m 32 s
5   addr 34.254 GiB   size 5.899 GiB   access 0 %   age 5 m 24 s
6   addr 46.281 GiB   size 2.995 GiB   access 0 %   age 5 m 20 s
7   addr 28.420 GiB   size 5.835 GiB   access 0 %   age 5 m 6 s
8   addr 4.000 GiB    size 6.180 GiB   access 0 %   age 4 m 16 s
9   addr 22.478 GiB   size 5.942 GiB   access 0 %   age 3 m 58 s
10  addr 55.470 GiB   size 915.645 MiB access 0 %   age 3 m 6 s
11  addr 56.364 GiB   size 6.056 GiB   access 0 %   age 2 m 8 s
12  addr 56.364 GiB   size 4.000 KiB   access 95 %  age 16 s
13  addr 49.275 GiB   size 4.000 KiB   access 100 % age 8 m 24 s   # hottest
total size: 62.000 GiB
# damo report access --style temperature-sz-hist
<temperature> <total size>
[-42,800,000,000, -33,479,999,000) 22.018 GiB |*****************   |
[-33,479,999,000, -24,159,998,000) 27.090 GiB |********************|
[-24,159,998,000, -14,839,997,000) 6.836 GiB  |******              |
[-14,839,997,000, -5,519,996,000)  6.056 GiB  |*****               |
[-5,519,996,000, 3,800,005,000)    4.000 KiB  |*                   |
[3,800,005,000, 13,120,006,000)    0 B        |                    |
[13,120,006,000, 22,440,007,000)   0 B        |                    |
[22,440,007,000, 31,760,008,000)   0 B        |                    |
[31,760,008,000, 41,080,009,000)   0 B        |                    |
[41,080,009,000, 50,400,010,000)   0 B        |                    |
[50,400,010,000, 59,720,011,000)   4.000 KiB  |*                   |
total size: 62.000 GiB
```

DAMON found two distinct 4 KiB regions that pretty hot.  The regions are also well aged.  The hottest 4 KiB region was keeping the access frequency for about 8 minutes, and the coldest region was keeping no access for about 7 minutes. The distribution on the histogram also looks like having a pattern.

Especially, the finding of the 4 KiB regions among the 62 GiB total memory shows DAMON’s adaptive regions adjustment is working as designed.

Still the number of regions is close to the `min_nr_regions`, and sizes of cold regions are similar, though.  Apparently it is improved, but it still has rooms to improve.

<a id="rst-ms-8s-intervals-pretty-improved-results"></a>

## 400ms/8s intervals: Pretty Improved Results

Increase the intervals four times (400 milliseconds and 8 seconds for sampling and aggregation intervals, respectively).



```text
# damo start -s 400ms -a 8s
# sleep 600
# damo record --snapshot 0 1
# damo stop
# damo report access --sort_regions_by temperature
0   addr 64.492 GiB   size 1.508 GiB   access 0 %   age 6 m 48 s    # coldest
1   addr 21.749 GiB   size 5.674 GiB   access 0 %   age 6 m 8 s
2   addr 27.422 GiB   size 5.801 GiB   access 0 %   age 6 m
3   addr 49.431 GiB   size 8.675 GiB   access 0 %   age 5 m 28 s
4   addr 33.223 GiB   size 5.645 GiB   access 0 %   age 5 m 12 s
5   addr 58.321 GiB   size 6.170 GiB   access 0 %   age 5 m 4 s
[...]
25  addr 6.615 GiB    size 297.531 MiB access 15 %  age 0 ns
26  addr 9.513 GiB    size 12.000 KiB  access 20 %  age 0 ns
27  addr 9.511 GiB    size 108.000 KiB access 25 %  age 0 ns
28  addr 9.513 GiB    size 20.000 KiB  access 25 %  age 0 ns
29  addr 9.511 GiB    size 12.000 KiB  access 30 %  age 0 ns
30  addr 9.520 GiB    size 4.000 KiB   access 40 %  age 0 ns
[...]
41  addr 9.520 GiB    size 4.000 KiB   access 80 %  age 56 s
42  addr 9.511 GiB    size 12.000 KiB  access 100 % age 6 m 16 s
43  addr 58.321 GiB   size 4.000 KiB   access 100 % age 6 m 24 s
44  addr 9.512 GiB    size 4.000 KiB   access 100 % age 6 m 48 s
45  addr 58.106 GiB   size 4.000 KiB   access 100 % age 6 m 48 s    # hottest
total size: 62.000 GiB
# damo report access --style temperature-sz-hist
<temperature> <total size>
[-40,800,000,000, -32,639,999,000) 21.657 GiB  |********************|
[-32,639,999,000, -24,479,998,000) 17.938 GiB  |*****************   |
[-24,479,998,000, -16,319,997,000) 16.885 GiB  |****************    |
[-16,319,997,000, -8,159,996,000)  586.879 MiB |*                   |
[-8,159,996,000, 5,000)            4.946 GiB   |*****               |
[5,000, 8,160,006,000)             260.000 KiB |*                   |
[8,160,006,000, 16,320,007,000)    0 B         |                    |
[16,320,007,000, 24,480,008,000)   0 B         |                    |
[24,480,008,000, 32,640,009,000)   0 B         |                    |
[32,640,009,000, 40,800,010,000)   16.000 KiB  |*                   |
[40,800,010,000, 48,960,011,000)   8.000 KiB   |*                   |
total size: 62.000 GiB
```

The number of regions having different access patterns has significantly increased.  Size of each region is also more varied. Total size of non-zero access frequency regions is also significantly increased. Maybe this is already good enough to make some meaningful memory management efficiency changes.

<a id="rst-ms-16s-intervals-another-bias"></a>

## 800ms/16s intervals: Another bias

Further double the intervals (800 milliseconds and 16 seconds for sampling and aggregation intervals, respectively).  The results is more improved for the hot regions detection, but starts looking degrading cold regions detection.



```text
# damo start -s 800ms -a 16s
# sleep 600
# damo record --snapshot 0 1
# damo stop
# damo report access --sort_regions_by temperature
0   addr 64.781 GiB   size 1.219 GiB   access 0 %   age 4 m 48 s
1   addr 24.505 GiB   size 2.475 GiB   access 0 %   age 4 m 16 s
2   addr 26.980 GiB   size 504.273 MiB access 0 %   age 4 m
3   addr 29.443 GiB   size 2.462 GiB   access 0 %   age 4 m
4   addr 37.264 GiB   size 5.645 GiB   access 0 %   age 4 m
5   addr 31.905 GiB   size 5.359 GiB   access 0 %   age 3 m 44 s
[...]
20  addr 8.711 GiB    size 40.000 KiB  access 5 %   age 2 m 40 s
21  addr 27.473 GiB   size 1.970 GiB   access 5 %   age 4 m
22  addr 48.185 GiB   size 4.625 GiB   access 5 %   age 4 m
23  addr 47.304 GiB   size 902.117 MiB access 10 %  age 4 m
24  addr 8.711 GiB    size 4.000 KiB   access 100 % age 4 m
25  addr 20.793 GiB   size 3.713 GiB   access 5 %   age 4 m 16 s
26  addr 8.773 GiB    size 4.000 KiB   access 100 % age 4 m 16 s
total size: 62.000 GiB
# damo report access --style temperature-sz-hist
<temperature> <total size>
[-28,800,000,000, -23,359,999,000) 12.294 GiB  |*****************   |
[-23,359,999,000, -17,919,998,000) 9.753 GiB   |*************       |
[-17,919,998,000, -12,479,997,000) 15.131 GiB  |********************|
[-12,479,997,000, -7,039,996,000)  0 B         |                    |
[-7,039,996,000, -1,599,995,000)   7.506 GiB   |**********          |
[-1,599,995,000, 3,840,006,000)    6.127 GiB   |*********           |
[3,840,006,000, 9,280,007,000)     0 B         |                    |
[9,280,007,000, 14,720,008,000)    136.000 KiB |*                   |
[14,720,008,000, 20,160,009,000)   40.000 KiB  |*                   |
[20,160,009,000, 25,600,010,000)   11.188 GiB  |***************     |
[25,600,010,000, 31,040,011,000)   4.000 KiB   |*                   |
total size: 62.000 GiB
```

It found more non-zero access frequency regions. The number of regions is still much higher than the `min_nr_regions`, but it is reduced from that of the previous setup. And apparently the distribution seems bit biased to hot regions.

<a id="rst-conclusion"></a>

## Conclusion

With the above experimental tuning results, we can conclude the theory and the guide makes sense to at least this workload, and could be applied to similar cases.

---

# Unsorted Documentation

_Peios Kernel / Internals / Staging_

> Reference for Unsorted Documentation.

<a id="rst-unsorted-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Brief tutorial on CRC computation](</kernel/internals/staging/crc32.md>)
- [LZO stream format as understood by Linux's LZO decompressor](</kernel/internals/staging/lzo.md>)
- [Linux magic numbers](</kernel/internals/staging/magic-number.md>)
- [Remote Processor Framework](</kernel/internals/staging/remoteproc.md>)
- [Remote Processor Messaging (rpmsg) Framework](</kernel/internals/staging/rpmsg.md>)
- [Speculation](</kernel/internals/staging/speculation.md>)
- [Static Keys](</kernel/internals/staging/static-keys.md>)
- [XZ data compression in Linux](</kernel/internals/staging/xz.md>)

---

# Brief tutorial on CRC computation

_Peios Kernel / Internals / Staging_

> A CRC is a long-division remainder. You add the CRC to the message, and the whole thing (message+CRC) is a multiple of the given CRC polynomial. To check the CRC, you can either check that the CRC matches the recomputed value, or you can…

<a id="rst-brief-tutorial-on-crc-computation"></a>

A CRC is a long-division remainder.  You add the CRC to the message, and the whole thing (message+CRC) is a multiple of the given CRC polynomial.  To check the CRC, you can either check that the CRC matches the recomputed value, <em>or</em> you can check that the remainder computed on the message+CRC is 0.  This latter approach is used by a lot of hardware implementations, and is why so many protocols put the end-of-frame flag after the CRC.

It's actually the same long division you learned in school, except that:

- We're working in binary, so the digits are only 0 and 1, and

- When dividing polynomials, there are no carries.  Rather than add and subtract, we just xor.  Thus, we tend to get a bit sloppy about the difference between adding and subtracting.

Like all division, the remainder is always smaller than the divisor. To produce a 32-bit CRC, the divisor is actually a 33-bit CRC polynomial. Since it's 33 bits long, bit 32 is always going to be set, so usually the CRC is written in hex with the most significant bit omitted.  (If you're familiar with the IEEE 754 floating-point format, it's the same idea.)

Note that a CRC is computed over a string of <em>bits</em>, so you have to decide on the endianness of the bits within each byte.  To get the best error-detecting properties, this should correspond to the order they're actually sent.  For example, standard RS-232 serial is little-endian; the most significant bit (sometimes used for parity) is sent last.  And when appending a CRC word to a message, you should do it in the right order, matching the endianness.

Just like with ordinary division, you proceed one digit (bit) at a time. Each step of the division you take one more digit (bit) of the dividend and append it to the current remainder.  Then you figure out the appropriate multiple of the divisor to subtract to bring the remainder back into range.  In binary, this is easy - it has to be either 0 or 1, and to make the XOR cancel, it's just a copy of bit 32 of the remainder.

When computing a CRC, we don't care about the quotient, so we can throw the quotient bit away, but subtract the appropriate multiple of the polynomial from the remainder and we're back to where we started, ready to process the next bit.

A big-endian CRC written this way would be coded like:



```text
for (i = 0; i < input_bits; i++) {
        multiple = remainder & 0x80000000 ? CRCPOLY : 0;
        remainder = (remainder << 1 | next_input_bit()) ^ multiple;
}
```

Notice how, to get at bit 32 of the shifted remainder, we look at bit 31 of the remainder <em>before</em> shifting it.

But also notice how the next\_input\_bit() bits we're shifting into the remainder don't actually affect any decision-making until 32 bits later.  Thus, the first 32 cycles of this are pretty boring. Also, to add the CRC to a message, we need a 32-bit-long hole for it at the end, so we have to add 32 extra cycles shifting in zeros at the end of every message.

These details lead to a standard trick: rearrange merging in the next\_input\_bit() until the moment it's needed.  Then the first 32 cycles can be precomputed, and merging in the final 32 zero bits to make room for the CRC can be skipped entirely.  This changes the code to:



```text
for (i = 0; i < input_bits; i++) {
        remainder ^= next_input_bit() << 31;
        multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
        remainder = (remainder << 1) ^ multiple;
}
```

With this optimization, the little-endian code is particularly simple:



```text
for (i = 0; i < input_bits; i++) {
        remainder ^= next_input_bit();
        multiple = (remainder & 1) ? CRCPOLY : 0;
        remainder = (remainder >> 1) ^ multiple;
}
```

The most significant coefficient of the remainder polynomial is stored in the least significant bit of the binary "remainder" variable. The other details of endianness have been hidden in CRCPOLY (which must be bit-reversed) and next\_input\_bit().

As long as next\_input\_bit is returning the bits in a sensible order, we don't <em>have</em> to wait until the last possible moment to merge in additional bits. We can do it 8 bits at a time rather than 1 bit at a time:



```text
for (i = 0; i < input_bytes; i++) {
        remainder ^= next_input_byte() << 24;
        for (j = 0; j < 8; j++) {
                multiple = (remainder & 0x80000000) ? CRCPOLY : 0;
                remainder = (remainder << 1) ^ multiple;
        }
}
```

Or in little-endian:



```text
for (i = 0; i < input_bytes; i++) {
        remainder ^= next_input_byte();
        for (j = 0; j < 8; j++) {
                multiple = (remainder & 1) ? CRCPOLY : 0;
                remainder = (remainder >> 1) ^ multiple;
        }
}
```

If the input is a multiple of 32 bits, you can even XOR in a 32-bit word at a time and increase the inner loop count to 32.

You can also mix and match the two loop styles, for example doing the bulk of a message byte-at-a-time and adding bit-at-a-time processing for any fractional bytes at the end.

To reduce the number of conditional branches, software commonly uses the byte-at-a-time table method, popularized by Dilip V. Sarwate, "Computation of Cyclic Redundancy Checks via Table Look-Up", Comm. ACM v.31 no.8 (August 1988) p. 1008-1013.

Here, rather than just shifting one bit of the remainder to decide in the correct multiple to subtract, we can shift a byte at a time. This produces a 40-bit (rather than a 33-bit) intermediate remainder, and the correct multiple of the polynomial to subtract is found using a 256-entry lookup table indexed by the high 8 bits.

(The table entries are simply the CRC-32 of the given one-byte messages.)

When space is more constrained, smaller tables can be used, e.g. two 4-bit shifts followed by a lookup in a 16-entry table.

It is not practical to process much more than 8 bits at a time using this technique, because tables larger than 256 entries use too much memory and, more importantly, too much of the L1 cache.

To get higher software performance, a "slicing" technique can be used. See "High Octane CRC Generation with the Intel Slicing-by-8 Algorithm", [ftp://download.intel.com/technology/comms/perfnet/download/slicing-by-8.pdf](<ftp://download.intel.com/technology/comms/perfnet/download/slicing-by-8.pdf>)

This does not change the number of table lookups, but does increase the parallelism.  With the classic Sarwate algorithm, each table lookup must be completed before the index of the next can be computed.

A "slicing by 2" technique would shift the remainder 16 bits at a time, producing a 48-bit intermediate remainder.  Rather than doing a single lookup in a 65536-entry table, the two high bytes are looked up in two different 256-entry tables.  Each contains the remainder required to cancel out the corresponding byte.  The tables are different because the polynomials to cancel are different.  One has non-zero coefficients from x^32 to x^39, while the other goes from x^40 to x^47.

Since modern processors can handle many parallel memory operations, this takes barely longer than a single table look-up and thus performs almost twice as fast as the basic Sarwate algorithm.

This can be extended to "slicing by 4" using 4 256-entry tables. Each step, 32 bits of data is fetched, XORed with the CRC, and the result broken into bytes and looked up in the tables.  Because the 32-bit shift leaves the low-order bits of the intermediate remainder zero, the final CRC is simply the XOR of the 4 table look-ups.

But this still enforces sequential execution: a second group of table look-ups cannot begin until the previous groups 4 table look-ups have all been completed.  Thus, the processor's load/store unit is sometimes idle.

To make maximum use of the processor, "slicing by 8" performs 8 look-ups in parallel.  Each step, the 32-bit CRC is shifted 64 bits and XORed with 64 bits of input data.  What is important to note is that 4 of those 8 bytes are simply copies of the input data; they do not depend on the previous CRC at all.  Thus, those 4 table look-ups may commence immediately, without waiting for the previous loop iteration.

By always having 4 loads in flight, a modern superscalar processor can be kept busy and make full use of its L1 cache.

Two more details about CRC implementation in the real world:

Normally, appending zero bits to a message which is already a multiple of a polynomial produces a larger multiple of that polynomial.  Thus, a basic CRC will not detect appended zero bits (or bytes).  To enable a CRC to detect this condition, it's common to invert the CRC before appending it.  This makes the remainder of the message+crc come out not as zero, but some fixed non-zero value.  (The CRC of the inversion pattern, 0xffffffff.)

The same problem applies to zero bits prepended to the message, and a similar solution is used.  Instead of starting the CRC computation with a remainder of 0, an initial remainder of all ones is used.  As long as you start the same way on decoding, it doesn't make a difference.

---

# LZO stream format as understood by Linux's LZO decompressor

_Peios Kernel / Internals / Staging_

> This is not a specification. No specification seems to be publicly available for the LZO stream format. This document describes what input format the LZO decompressor as implemented in the Linux kernel understands. The file subject of this…

<a id="rst-lzo-stream-format-as-understood-by-linux-s-lzo-decompressor"></a>

<a id="rst-introduction"></a>

## Introduction

> This is not a specification. No specification seems to be publicly available for the LZO stream format. This document describes what input format the LZO decompressor as implemented in the Linux kernel understands. The file subject of this analysis is lib/lzo/lzo1x\_decompress\_safe.c. No analysis was made on the compressor nor on any other implementations though it seems likely that the format matches the standard one. The purpose of this document is to better understand what the code does in order to propose more efficient fixes for future bug reports.

<a id="rst-description"></a>

## Description

> The stream is composed of a series of instructions, operands, and data. The instructions consist in a few bits representing an opcode, and bits forming the operands for the instruction, whose size and position depend on the opcode and on the number of literals copied by previous instruction. The operands are used to indicate:
>
> > - a distance when copying data from the dictionary (past output buffer)
> >
> > - a length (number of bytes to copy from dictionary)
> >
> > - the number of literals to copy, which is retained in variable "state" as a piece of information for next instructions.
>
> Optionally depending on the opcode and operands, extra data may follow. These extra data can be a complement for the operand (eg: a length or a distance encoded on larger values), or a literal to be copied to the output buffer.
>
> The first byte of the block follows a different encoding from other bytes, it seems to be optimized for literal use only, since there is no dictionary yet prior to that byte.
>
> Lengths are always encoded on a variable size starting with a small number of bits in the operand. If the number of bits isn't enough to represent the length, up to 255 may be added in increments by consuming more bytes with a rate of at most 255 per extra byte (thus the compression ratio cannot exceed around 255:1). The variable length encoding using \#bits is always the same:
>
>
>
> ```text
> length = byte & ((1 << #bits) - 1)
> if (!length) {
>         length = ((1 << #bits) - 1)
>         length += 255*(number of zero bytes)
>         length += first-non-zero-byte
> }
> length += constant (generally 2 or 3)
> ```
>
> For references to the dictionary, distances are relative to the output pointer. Distances are encoded using very few bits belonging to certain ranges, resulting in multiple copy instructions using different encodings. Certain encodings involve one extra byte, others involve two extra bytes forming a little-endian 16-bit quantity (marked LE16 below).
>
> After any instruction except the large literal copy, 0, 1, 2 or 3 literals are copied before starting the next instruction. The number of literals that were copied may change the meaning and behaviour of the next instruction. In practice, only one instruction needs to know whether 0, less than 4, or more literals were copied. This is the information stored in the &lt;state&gt; variable in this implementation. This number of immediate literals to be copied is generally encoded in the last two bits of the instruction but may also be taken from the last two bits of an extra operand (eg: distance).
>
> End of stream is declared when a block copy of distance 0 is seen. Only one instruction may encode this distance (0001HLLL), it takes one LE16 operand for the distance, thus requiring 3 bytes.
>
> > [!IMPORTANT]
> >
> > In the code some length checks are missing because certain instructions are called under the assumption that a certain number of bytes follow because it has already been guaranteed before parsing the instructions. They just have to "refill" this credit if they consume extra bytes. This is an implementation design choice independent on the algorithm or encoding.

Versions

0: Original version 1: LZO-RLE

Version 1 of LZO implements an extension to encode runs of zeros using run length encoding. This improves speed for data with many zeros, which is a common case for zram. This modifies the bitstream in a backwards compatible way (v1 can correctly decompress v0 compressed data, but v0 cannot read v1 data).

For maximum compatibility, both versions are available under different names (lzo and lzo-rle). Differences in the encoding are noted in this document with e.g.: version 1 only.

<a id="rst-byte-sequences"></a>

## Byte sequences

> First byte encoding:
>
>
>
> ```text
> 0..16   : follow regular instruction encoding, see below. It is worth
>           noting that code 16 will represent a block copy from the
>           dictionary which is empty, and that it will always be
>           invalid at this place.
>
> 17      : bitstream version. If the first byte is 17, and compressed
>           stream length is at least 5 bytes (length of shortest possible
>           versioned bitstream), the next byte gives the bitstream version
>           (version 1 only).
>           Otherwise, the bitstream version is 0.
>
> 18..21  : copy 0..3 literals
>           state = (byte - 17) = 0..3  [ copy <state> literals ]
>           skip byte
>
> 22..255 : copy literal string
>           length = (byte - 17) = 4..238
>           state = 4 [ don't copy extra literals ]
>           skip byte
> ```
>
> Instruction encoding:
>
>
>
> ```text
> 0 0 0 0 X X X X  (0..15)
>   Depends on the number of literals copied by the last instruction.
>   If last instruction did not copy any literal (state == 0), this
>   encoding will be a copy of 4 or more literal, and must be interpreted
>   like this :
>
>      0 0 0 0 L L L L  (0..15)  : copy long literal string
>      length = 3 + (L ?: 15 + (zero_bytes * 255) + non_zero_byte)
>      state = 4  (no extra literals are copied)
>
>   If last instruction used to copy between 1 to 3 literals (encoded in
>   the instruction's opcode or distance), the instruction is a copy of a
>   2-byte block from the dictionary within a 1kB distance. It is worth
>   noting that this instruction provides little savings since it uses 2
>   bytes to encode a copy of 2 other bytes but it encodes the number of
>   following literals for free. It must be interpreted like this :
>
>      0 0 0 0 D D S S  (0..15)  : copy 2 bytes from <= 1kB distance
>      length = 2
>      state = S (copy S literals after this block)
>    Always followed by exactly one byte : H H H H H H H H
>      distance = (H << 2) + D + 1
>
>   If last instruction used to copy 4 or more literals (as detected by
>   state == 4), the instruction becomes a copy of a 3-byte block from the
>   dictionary from a 2..3kB distance, and must be interpreted like this :
>
>      0 0 0 0 D D S S  (0..15)  : copy 3 bytes from 2..3 kB distance
>      length = 3
>      state = S (copy S literals after this block)
>    Always followed by exactly one byte : H H H H H H H H
>      distance = (H << 2) + D + 2049
>
> 0 0 0 1 H L L L  (16..31)
>      Copy of a block within 16..48kB distance (preferably less than 10B)
>      length = 2 + (L ?: 7 + (zero_bytes * 255) + non_zero_byte)
>   Always followed by exactly one LE16 :  D D D D D D D D : D D D D D D S S
>      distance = 16384 + (H << 14) + D
>      state = S (copy S literals after this block)
>      End of stream is reached if distance == 16384
>      In version 1 only, to prevent ambiguity with the RLE case when
>      ((distance & 0x803f) == 0x803f) && (261 <= length <= 264), the
>      compressor must not emit block copies where distance and length
>      meet these conditions.
>
>   In version 1 only, this instruction is also used to encode a run of
>      zeros if distance = 0xbfff, i.e. H = 1 and the D bits are all 1.
>      In this case, it is followed by a fourth byte, X.
>      run length = ((X << 3) | (0 0 0 0 0 L L L)) + 4
>
> 0 0 1 L L L L L  (32..63)
>      Copy of small block within 16kB distance (preferably less than 34B)
>      length = 2 + (L ?: 31 + (zero_bytes * 255) + non_zero_byte)
>   Always followed by exactly one LE16 :  D D D D D D D D : D D D D D D S S
>      distance = D + 1
>      state = S (copy S literals after this block)
>
> 0 1 L D D D S S  (64..127)
>      Copy 3-4 bytes from block within 2kB distance
>      state = S (copy S literals after this block)
>      length = 3 + L
>    Always followed by exactly one byte : H H H H H H H H
>      distance = (H << 3) + D + 1
>
> 1 L L D D D S S  (128..255)
>      Copy 5-8 bytes from block within 2kB distance
>      state = S (copy S literals after this block)
>      length = 5 + L
>    Always followed by exactly one byte : H H H H H H H H
>      distance = (H << 3) + D + 1
> ```

<a id="rst-authors"></a>

## Authors

> This document was written by Willy Tarreau &lt;[w@1wt.eu](<mailto:w@1wt.eu>)&gt; on 2014/07/19 during an analysis of the decompression code available in Linux 3.16-rc5, and updated by Dave Rodgman &lt;[dave.rodgman@arm.com](<mailto:dave.rodgman@arm.com>)&gt; on 2018/10/30 to introduce run-length encoding. The code is tricky, it is possible that this document contains mistakes or that a few corner cases were overlooked. In any case, please report any doubt, fix, or proposed updates to the author(s) so that the document can be updated.

---

# Linux magic numbers

_Peios Kernel / Internals / Staging_

> This file is a registry of magic numbers which are in use. When you add a magic number to a structure, you should also add it to this file, since it is best if the magic numbers used by various structures are unique.

<a id="rst-linux-magic-numbers"></a>
<a id="rst-magicnumbers"></a>

This file is a registry of magic numbers which are in use.  When you add a magic number to a structure, you should also add it to this file, since it is best if the magic numbers used by various structures are unique.

It is a <strong>very</strong> good idea to protect kernel data structures with magic numbers.  This allows you to check at run time whether (a) a structure has been clobbered, or (b) you've passed the wrong structure to a routine.  This last is especially useful --- particularly when you are passing pointers to structures via a void \* pointer.  The tty code, for example, does this frequently to pass driver-specific and line discipline-specific structures back and forth.

The way to use magic numbers is to declare them at the beginning of the structure, like so:



```text
struct tty_ldisc {
        int     magic;
        ...
};
```

Please follow this discipline when you are adding future enhancements to the kernel\!  It has saved me countless hours of debugging, especially in the screwy cases where an array has been overrun and structures following the array have been overwritten.  Using this discipline, these cases get detected quickly and safely.

Changelog:



```text
                                      Theodore Ts'o
                                      31 Mar 94

The magic table is current to Linux 2.1.55.

                                      Michael Chastain
                                      <mailto:mec@shout.net>
                                      22 Sep 1997

Now it should be up to date with Linux 2.1.112. Because
we are in feature freeze time it is very unlikely that
something will change before 2.2.x. The entries are
sorted by number field.

                                      Krzysztof G. Baranowski
                                      <mailto: kgb@knm.org.pl>
                                      29 Jul 1998

Updated the magic table to Linux 2.5.45. Right over the feature freeze,
but it is possible that some new magic numbers will sneak into the
kernel before 2.6.x yet.

                                      Petr Baudis
                                      <pasky@ucw.cz>
                                      03 Nov 2002

Updated the magic table to Linux 2.5.74.

                                      Fabian Frederick
                                      <ffrederick@users.sourceforge.net>
                                      09 Jul 2003
```


<table>
<thead>
<tr>
<th>



Magic Name

</th>
<th>



Number

</th>
<th>



Structure

</th>
<th>



File

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



PG\_MAGIC

</td>
<td>



'P'

</td>
<td>



pg\_\{read,write\}\_hdr

</td>
<td>



`include/uapi/linux/pg.h`

</td>
</tr>
<tr>
<td>



APM\_BIOS\_MAGIC

</td>
<td>



0x4101

</td>
<td>



apm\_user

</td>
<td>



`arch/x86/kernel/apm_32.c`

</td>
</tr>
<tr>
<td>



FASYNC\_MAGIC

</td>
<td>



0x4601

</td>
<td>



fasync\_struct

</td>
<td>



`include/linux/fs.h`

</td>
</tr>
<tr>
<td>



SLIP\_MAGIC

</td>
<td>



0x5302

</td>
<td>



slip

</td>
<td>



`drivers/net/slip/slip.h`

</td>
</tr>
<tr>
<td>



BAYCOM\_MAGIC

</td>
<td>



19730510

</td>
<td>



baycom\_state

</td>
<td>



`drivers/net/hamradio/baycom_epp.c`

</td>
</tr>
<tr>
<td>



HDLCDRV\_MAGIC

</td>
<td>



0x5ac6e778

</td>
<td>



hdlcdrv\_state

</td>
<td>



`include/linux/hdlcdrv.h`

</td>
</tr>
<tr>
<td>



KV\_MAGIC

</td>
<td>



0x5f4b565f

</td>
<td>



kernel\_vars\_s

</td>
<td>



`arch/mips/include/asm/sn/klkernvars.h`

</td>
</tr>
<tr>
<td>



CODA\_MAGIC

</td>
<td>



0xC0DAC0DA

</td>
<td>



coda\_file\_info

</td>
<td>



`fs/coda/coda_fs_i.h`

</td>
</tr>
<tr>
<td>



YAM\_MAGIC

</td>
<td>



0xF10A7654

</td>
<td>



yam\_port

</td>
<td>



`drivers/net/hamradio/yam.c`

</td>
</tr>
<tr>
<td>



CCB\_MAGIC

</td>
<td>



0xf2691ad2

</td>
<td>



ccb

</td>
<td>



`drivers/scsi/ncr53c8xx.c`

</td>
</tr>
<tr>
<td>



QUEUE\_MAGIC\_FREE

</td>
<td>



0xf7e1c9a3

</td>
<td>



queue\_entry

</td>
<td>



`drivers/scsi/arm/queue.c`

</td>
</tr>
<tr>
<td>



QUEUE\_MAGIC\_USED

</td>
<td>



0xf7e1cc33

</td>
<td>



queue\_entry

</td>
<td>



`drivers/scsi/arm/queue.c`

</td>
</tr>
<tr>
<td>



NMI\_MAGIC

</td>
<td>



0x48414d4d455201

</td>
<td>



nmi\_s

</td>
<td>



`arch/mips/include/asm/sn/nmi.h`

</td>
</tr>
</tbody>
</table>

---

# Remote Processor Framework

_Peios Kernel / Internals / Staging_

> Modern SoCs typically have heterogeneous remote processor devices in asymmetric multiprocessing (AMP) configurations, which may be running different instances of operating system, whether it's Linux or any other flavor of real-time OS.

<a id="rst-remote-processor-framework"></a>

<a id="rst-introduction"></a>

## Introduction

Modern SoCs typically have heterogeneous remote processor devices in asymmetric multiprocessing (AMP) configurations, which may be running different instances of operating system, whether it's Linux or any other flavor of real-time OS.

OMAP4, for example, has dual Cortex-A9, dual Cortex-M3 and a C64x+ DSP. In a typical configuration, the dual cortex-A9 is running Linux in a SMP configuration, and each of the other three cores (two M3 cores and a DSP) is running its own instance of RTOS in an AMP configuration.

The remoteproc framework allows different platforms/architectures to control (power on, load firmware, power off) those remote processors while abstracting the hardware differences, so the entire driver doesn't need to be duplicated. In addition, this framework also adds rpmsg virtio devices for remote processors that supports this kind of communication. This way, platform-specific remoteproc drivers only need to provide a few low-level handlers, and then all rpmsg drivers will then just work (for more information about the virtio-based rpmsg bus and its drivers, please read [Documentation/staging/rpmsg.rst](/kernel/internals/staging/rpmsg.md)). Registration of other types of virtio devices is now also possible. Firmwares just need to publish what kind of virtio devices do they support, and then remoteproc will add those devices. This makes it possible to reuse the existing virtio drivers with remote processor backends at a minimal development cost.

<a id="rst-user-api"></a>

## User API



```text
int rproc_boot(struct rproc *rproc)
```

Boot a remote processor (i.e. load its firmware, power it on, ...).

If the remote processor is already powered on, this function immediately returns (successfully).

Returns 0 on success, and an appropriate error value otherwise. Note: to use this function you should already have a valid rproc handle. There are several ways to achieve that cleanly (devres, pdata, the way remoteproc\_rpmsg.c does this, or, if this becomes prevalent, we might also consider using dev\_archdata for this).



```text
int rproc_shutdown(struct rproc *rproc)
```

Power off a remote processor (previously booted with rproc\_boot()). In case @rproc is still being used by an additional user(s), then this function will just decrement the power refcount and exit, without really powering off the device.

Returns 0 on success, and an appropriate error value otherwise. Every call to rproc\_boot() must (eventually) be accompanied by a call to rproc\_shutdown(). Calling rproc\_shutdown() redundantly is a bug.

> [!NOTE]
>
> we're not decrementing the rproc's refcount, only the power refcount. which means that the @rproc handle stays valid even after rproc\_shutdown() returns, and users can still use it with a subsequent rproc\_boot(), if needed.



```text
struct rproc *rproc_get_by_phandle(phandle phandle)
```

Find an rproc handle using a device tree phandle. Returns the rproc handle on success, and NULL on failure. This function increments the remote processor's refcount, so always use rproc\_put() to decrement it back once rproc isn't needed anymore.

<a id="rst-typical-usage"></a>

## Typical usage



```text
#include <linux/remoteproc.h>

/* in case we were given a valid 'rproc' handle */
int dummy_rproc_example(struct rproc *my_rproc)
{
      int ret;

      /* let's power on and boot our remote processor */
      ret = rproc_boot(my_rproc);
      if (ret) {
              /*
               * something went wrong. handle it and leave.
               */
      }

      /*
       * our remote processor is now powered on... give it some work
       */

      /* let's shut it down now */
      rproc_shutdown(my_rproc);
}
```

<a id="rst-api-for-implementers"></a>

## API for implementers



```text
struct rproc *rproc_alloc(struct device *dev, const char *name,
                              const struct rproc_ops *ops,
                              const char *firmware, int len)
```

Allocate a new remote processor handle, but don't register it yet. Required parameters are the underlying device, the name of this remote processor, platform-specific ops handlers, the name of the firmware to boot this rproc with, and the length of private data needed by the allocating rproc driver (in bytes).

This function should be used by rproc implementations during initialization of the remote processor.

After creating an rproc handle using this function, and when ready, implementations should then call rproc\_add() to complete the registration of the remote processor.

On success, the new rproc is returned, and on failure, NULL.

> [!NOTE]
>
> <strong>never</strong> directly deallocate @rproc, even if it was not registered yet. Instead, when you need to unroll rproc\_alloc(), use rproc\_free().



```text
void rproc_free(struct rproc *rproc)
```

Free an rproc handle that was allocated by rproc\_alloc.

This function essentially unrolls rproc\_alloc(), by decrementing the rproc's refcount. It doesn't directly free rproc; that would happen only if there are no other references to rproc and its refcount now dropped to zero.



```text
int rproc_add(struct rproc *rproc)
```

Register @rproc with the remoteproc framework, after it has been allocated with rproc\_alloc().

This is called by the platform-specific rproc implementation, whenever a new remote processor device is probed.

Returns 0 on success and an appropriate error code otherwise. Note: this function initiates an asynchronous firmware loading context, which will look for virtio devices supported by the rproc's firmware.

If found, those virtio devices will be created and added, so as a result of registering this remote processor, additional virtio drivers might get probed.



```text
int rproc_del(struct rproc *rproc)
```

Unroll rproc\_add().

This function should be called when the platform specific rproc implementation decides to remove the rproc device. it should \_only\_ be called if a previous invocation of rproc\_add() has completed successfully.

After rproc\_del() returns, @rproc is still valid, and its last refcount should be decremented by calling rproc\_free().

Returns 0 on success and -EINVAL if @rproc isn't valid.



```text
void rproc_report_crash(struct rproc *rproc, enum rproc_crash_type type)
```

Report a crash in a remoteproc

This function must be called every time a crash is detected by the platform specific rproc implementation. This should not be called from a non-remoteproc driver. This function can be called from atomic/interrupt context.

<a id="rst-implementation-callbacks"></a>

## Implementation callbacks

These callbacks should be provided by platform-specific remoteproc drivers:



```text
/**
 * struct rproc_ops - platform-specific device handlers
 * @start:    power on the device and boot it
 * @stop:     power off the device
 * @kick:     kick a virtqueue (virtqueue id given as a parameter)
 */
struct rproc_ops {
      int (*start)(struct rproc *rproc);
      int (*stop)(struct rproc *rproc);
      void (*kick)(struct rproc *rproc, int vqid);
};
```

Every remoteproc implementation should at least provide the -&gt;start and -&gt;stop handlers. If rpmsg/virtio functionality is also desired, then the -&gt;kick handler should be provided as well.

The -&gt;start() handler takes an rproc handle and should then power on the device and boot it (use rproc-&gt;priv to access platform-specific private data). The boot address, in case needed, can be found in rproc-&gt;bootaddr (remoteproc core puts there the ELF entry point). On success, 0 should be returned, and on failure, an appropriate error code.

The -&gt;stop() handler takes an rproc handle and powers the device down. On success, 0 is returned, and on failure, an appropriate error code.

The -&gt;kick() handler takes an rproc handle, and an index of a virtqueue where new message was placed in. Implementations should interrupt the remote processor and let it know it has pending messages. Notifying remote processors the exact virtqueue index to look in is optional: it is easy (and not too expensive) to go through the existing virtqueues and look for new buffers in the used rings.

<a id="rst-binary-firmware-structure"></a>

## Binary Firmware Structure

At this point remoteproc supports ELF32 and ELF64 firmware binaries. However, it is quite expected that other platforms/devices which we'd want to support with this framework will be based on different binary formats.

When those use cases show up, we will have to decouple the binary format from the framework core, so we can support several binary formats without duplicating common code.

When the firmware is parsed, its various segments are loaded to memory according to the specified device address (might be a physical address if the remote processor is accessing memory directly).

In addition to the standard ELF segments, most remote processors would also include a special section which we call "the resource table".

The resource table contains system resources that the remote processor requires before it should be powered on, such as allocation of physically contiguous memory, or iommu mapping of certain on-chip peripherals. Remotecore will only power up the device after all the resource table's requirement are met.

In addition to system resources, the resource table may also contain resource entries that publish the existence of supported features or configurations by the remote processor, such as trace buffers and supported virtio devices (and their configurations).

The resource table begins with this header:



```text
/**
 * struct resource_table - firmware resource table header
 * @ver: version number
 * @num: number of resource entries
 * @reserved: reserved (must be zero)
 * @offset: array of offsets pointing at the various resource entries
 *
 * The header of the resource table, as expressed by this structure,
 * contains a version number (should we need to change this format in the
 * future), the number of available resource entries, and their offsets
 * in the table.
 */
struct resource_table {
      u32 ver;
      u32 num;
      u32 reserved[2];
      u32 offset[0];
} __packed;
```

Immediately following this header are the resource entries themselves, each of which begins with the following resource entry header:



```text
/**
 * struct fw_rsc_hdr - firmware resource entry header
 * @type: resource type
 * @data: resource data
 *
 * Every resource entry begins with a 'struct fw_rsc_hdr' header providing
 * its @type. The content of the entry itself will immediately follow
 * this header, and it should be parsed according to the resource type.
 */
struct fw_rsc_hdr {
      u32 type;
      u8 data[0];
} __packed;
```

Some resources entries are mere announcements, where the host is informed of specific remoteproc configuration. Other entries require the host to do something (e.g. allocate a system resource). Sometimes a negotiation is expected, where the firmware requests a resource, and once allocated, the host should provide back its details (e.g. address of an allocated memory region).

Here are the various resource types that are currently supported:



```text
/**
 * enum fw_resource_type - types of resource entries
 *
 * @RSC_CARVEOUT:   request for allocation of a physically contiguous
 *                memory region.
 * @RSC_DEVMEM:     request to iommu_map a memory-based peripheral.
 * @RSC_TRACE:            announces the availability of a trace buffer into which
 *                the remote processor will be writing logs.
 * @RSC_VDEV:       declare support for a virtio device, and serve as its
 *                virtio header.
 * @RSC_LAST:       just keep this one at the end
 * @RSC_VENDOR_START: start of the vendor specific resource types range
 * @RSC_VENDOR_END:   end of the vendor specific resource types range
 *
 * Please note that these values are used as indices to the rproc_handle_rsc
 * lookup table, so please keep them sane. Moreover, @RSC_LAST is used to
 * check the validity of an index before the lookup table is accessed, so
 * please update it as needed.
 */
enum fw_resource_type {
      RSC_CARVEOUT            = 0,
      RSC_DEVMEM              = 1,
      RSC_TRACE               = 2,
      RSC_VDEV                = 3,
      RSC_LAST                = 4,
      RSC_VENDOR_START        = 128,
      RSC_VENDOR_END          = 512,
};
```

For more details regarding a specific resource type, please see its dedicated structure in include/linux/remoteproc.h.

We also expect that platform-specific resource entries will show up at some point. When that happens, we could easily add a new RSC\_PLATFORM type, and hand those resources to the platform-specific rproc driver to handle.

<a id="rst-virtio-and-remoteproc"></a>

## Virtio and remoteproc

The firmware should provide remoteproc information about virtio devices that it supports, and their configurations: a RSC\_VDEV resource entry should specify the virtio device id (as in virtio\_ids.h), virtio features, virtio config space, vrings information, etc.

When a new remote processor is registered, the remoteproc framework will look for its resource table and will register the virtio devices it supports. A firmware may support any number of virtio devices, and of any type (a single remote processor can also easily support several rpmsg virtio devices this way, if desired).

Of course, RSC\_VDEV resource entries are only good enough for static allocation of virtio devices. Dynamic allocations will also be made possible using the rpmsg bus (similar to how we already do dynamic allocations of rpmsg channels; read more about it in rpmsg.txt).

---

# Remote Processor Messaging (rpmsg) Framework

_Peios Kernel / Internals / Staging_

> Modern SoCs typically employ heterogeneous remote processor devices in asymmetric multiprocessing (AMP) configurations, which may be running different instances of operating system, whether it's Linux or any other flavor of real-time OS.

<a id="rst-remote-processor-messaging-rpmsg-framework"></a>

> [!NOTE]
>
> This document describes the rpmsg bus and how to write rpmsg drivers. To learn how to add rpmsg support for new platforms, check out remoteproc.txt (also a resident of Documentation/).

<a id="rst-introduction"></a>

## Introduction

Modern SoCs typically employ heterogeneous remote processor devices in asymmetric multiprocessing (AMP) configurations, which may be running different instances of operating system, whether it's Linux or any other flavor of real-time OS.

OMAP4, for example, has dual Cortex-A9, dual Cortex-M3 and a C64x+ DSP. Typically, the dual cortex-A9 is running Linux in a SMP configuration, and each of the other three cores (two M3 cores and a DSP) is running its own instance of RTOS in an AMP configuration.

Typically AMP remote processors employ dedicated DSP codecs and multimedia hardware accelerators, and therefore are often used to offload CPU-intensive multimedia tasks from the main application processor.

These remote processors could also be used to control latency-sensitive sensors, drive random hardware blocks, or just perform background tasks while the main CPU is idling.

Users of those remote processors can either be userland apps (e.g. multimedia frameworks talking with remote OMX components) or kernel drivers (controlling hardware accessible only by the remote processor, reserving kernel-controlled resources on behalf of the remote processor, etc..).

Rpmsg is a virtio-based messaging bus that allows kernel drivers to communicate with remote processors available on the system. In turn, drivers could then expose appropriate user space interfaces, if needed.

When writing a driver that exposes rpmsg communication to userland, please keep in mind that remote processors might have direct access to the system's physical memory and other sensitive hardware resources (e.g. on OMAP4, remote cores and hardware accelerators may have direct access to the physical memory, gpio banks, dma controllers, i2c bus, gptimers, mailbox devices, hwspinlocks, etc..). Moreover, those remote processors might be running RTOS where every task can access the entire memory/devices exposed to the processor. To minimize the risks of rogue (or buggy) userland code exploiting remote bugs, and by that taking over the system, it is often desired to limit userland to specific rpmsg channels (see definition below) it can send messages on, and if possible, minimize how much control it has over the content of the messages.

Every rpmsg device is a communication channel with a remote processor (thus rpmsg devices are called channels). Channels are identified by a textual name and have a local ("source") rpmsg address, and remote ("destination") rpmsg address.

When a driver starts listening on a channel, its rx callback is bound with a unique rpmsg local address (a 32-bit integer). This way when inbound messages arrive, the rpmsg core dispatches them to the appropriate driver according to their destination address (this is done by invoking the driver's rx handler with the payload of the inbound message).

<a id="rst-user-api"></a>

## User API



```text
int rpmsg_send(struct rpmsg_endpoint *ept, void *data, int len);
```

sends a message across to the remote processor from the given endpoint. The caller should specify the endpoint, the data it wants to send, and its length (in bytes). The message will be sent on the specified endpoint's channel, i.e. its source and destination address fields will be respectively set to the endpoint's src address and its parent channel dst addresses.

In case there are no TX buffers available, the function will block until one becomes available (i.e. until the remote processor consumes a tx buffer and puts it back on virtio's used descriptor ring), or a timeout of 15 seconds elapses. When the latter happens, -ERESTARTSYS is returned.

The function can only be called from a process context (for now). Returns 0 on success and an appropriate error value on failure.



```text
int rpmsg_sendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst);
```

sends a message across to the remote processor from a given endpoint, to a destination address provided by the caller.

The caller should specify the endpoint, the data it wants to send, its length (in bytes), and an explicit destination address.

The message will then be sent to the remote processor to which the endpoints's channel belongs, using the endpoints's src address, and the user-provided dst address (thus the channel's dst address will be ignored).

In case there are no TX buffers available, the function will block until one becomes available (i.e. until the remote processor consumes a tx buffer and puts it back on virtio's used descriptor ring), or a timeout of 15 seconds elapses. When the latter happens, -ERESTARTSYS is returned.

The function can only be called from a process context (for now). Returns 0 on success and an appropriate error value on failure.



```text
int rpmsg_trysend(struct rpmsg_endpoint *ept, void *data, int len);
```

sends a message across to the remote processor from a given endpoint. The caller should specify the endpoint, the data it wants to send, and its length (in bytes). The message will be sent on the specified endpoint's channel, i.e. its source and destination address fields will be respectively set to the endpoint's src address and its parent channel dst addresses.

In case there are no TX buffers available, the function will immediately return -ENOMEM without waiting until one becomes available.

The function can only be called from a process context (for now). Returns 0 on success and an appropriate error value on failure.



```text
int rpmsg_trysendto(struct rpmsg_endpoint *ept, void *data, int len, u32 dst)
```

sends a message across to the remote processor from a given endpoint, to a destination address provided by the user.

The user should specify the channel, the data it wants to send, its length (in bytes), and an explicit destination address.

The message will then be sent to the remote processor to which the channel belongs, using the channel's src address, and the user-provided dst address (thus the channel's dst address will be ignored).

In case there are no TX buffers available, the function will immediately return -ENOMEM without waiting until one becomes available.

The function can only be called from a process context (for now). Returns 0 on success and an appropriate error value on failure.



```text
struct rpmsg_endpoint *rpmsg_create_ept(struct rpmsg_device *rpdev,
                                        rpmsg_rx_cb_t cb, void *priv,
                                        struct rpmsg_channel_info chinfo);
```

every rpmsg address in the system is bound to an rx callback (so when inbound messages arrive, they are dispatched by the rpmsg bus using the appropriate callback handler) by means of an rpmsg\_endpoint struct.

This function allows drivers to create such an endpoint, and by that, bind a callback, and possibly some private data too, to an rpmsg address (either one that is known in advance, or one that will be dynamically assigned for them).

Simple rpmsg drivers need not call rpmsg\_create\_ept, because an endpoint is already created for them when they are probed by the rpmsg bus (using the rx callback they provide when they registered to the rpmsg bus).

So things should just work for simple drivers: they already have an endpoint, their rx callback is bound to their rpmsg address, and when relevant inbound messages arrive (i.e. messages which their dst address equals to the src address of their rpmsg channel), the driver's handler is invoked to process it.

That said, more complicated drivers might do need to allocate additional rpmsg addresses, and bind them to different rx callbacks. To accomplish that, those drivers need to call this function. Drivers should provide their channel (so the new endpoint would bind to the same remote processor their channel belongs to), an rx callback function, an optional private data (which is provided back when the rx callback is invoked), and an address they want to bind with the callback. If addr is RPMSG\_ADDR\_ANY, then rpmsg\_create\_ept will dynamically assign them an available rpmsg address (drivers should have a very good reason why not to always use RPMSG\_ADDR\_ANY here).

Returns a pointer to the endpoint on success, or NULL on error.



```text
void rpmsg_destroy_ept(struct rpmsg_endpoint *ept);
```

destroys an existing rpmsg endpoint. user should provide a pointer to an rpmsg endpoint that was previously created with rpmsg\_create\_ept().



```text
int register_rpmsg_driver(struct rpmsg_driver *rpdrv);
```

registers an rpmsg driver with the rpmsg bus. user should provide a pointer to an rpmsg\_driver struct, which contains the driver's -&gt;probe() and -&gt;remove() functions, an rx callback, and an id\_table specifying the names of the channels this driver is interested to be probed with.



```text
void unregister_rpmsg_driver(struct rpmsg_driver *rpdrv);
```

unregisters an rpmsg driver from the rpmsg bus. user should provide a pointer to a previously-registered rpmsg\_driver struct. Returns 0 on success, and an appropriate error value on failure.

<a id="rst-typical-usage"></a>

## Typical usage

The following is a simple rpmsg driver, that sends an "hello\!" message on probe(), and whenever it receives an incoming message, it dumps its content to the console.



```text
#include <linux/dev_printk.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/printk.h>
#include <linux/rpmsg.h>
#include <linux/types.h>

static void rpmsg_sample_cb(struct rpmsg_channel *rpdev, void *data, int len,
                                              void *priv, u32 src)
{
      print_hex_dump(KERN_INFO, "incoming message:", DUMP_PREFIX_NONE,
                                              16, 1, data, len, true);
}

static int rpmsg_sample_probe(struct rpmsg_channel *rpdev)
{
      int err;

      dev_info(&rpdev->dev, "chnl: 0x%x -> 0x%x\n", rpdev->src, rpdev->dst);

      /* send a message on our channel */
      err = rpmsg_send(rpdev->ept, "hello!", 6);
      if (err) {
              dev_err(&rpdev->dev, "rpmsg_send failed: %d\n", err);
              return err;
      }

      return 0;
}

static void rpmsg_sample_remove(struct rpmsg_channel *rpdev)
{
      dev_info(&rpdev->dev, "rpmsg sample client driver is removed\n");
}

static struct rpmsg_device_id rpmsg_driver_sample_id_table[] = {
      { .name = "rpmsg-client-sample" },
      { },
};
MODULE_DEVICE_TABLE(rpmsg, rpmsg_driver_sample_id_table);

static struct rpmsg_driver rpmsg_sample_client = {
      .drv.name       = KBUILD_MODNAME,
      .id_table       = rpmsg_driver_sample_id_table,
      .probe          = rpmsg_sample_probe,
      .callback       = rpmsg_sample_cb,
      .remove         = rpmsg_sample_remove,
};
module_rpmsg_driver(rpmsg_sample_client);
```

> [!NOTE]
>
> a similar sample which can be built and loaded can be found in samples/rpmsg/.

<a id="rst-allocations-of-rpmsg-channels"></a>

## Allocations of rpmsg channels

At this point we only support dynamic allocations of rpmsg channels.

This is possible only with remote processors that have the VIRTIO\_RPMSG\_F\_NS virtio device feature set. This feature bit means that the remote processor supports dynamic name service announcement messages.

When this feature is enabled, creation of rpmsg devices (i.e. channels) is completely dynamic: the remote processor announces the existence of a remote rpmsg service by sending a name service message (which contains the name and rpmsg addr of the remote service, see struct rpmsg\_ns\_msg).

This message is then handled by the rpmsg bus, which in turn dynamically creates and registers an rpmsg channel (which represents the remote service). If/when a relevant rpmsg driver is registered, it will be immediately probed by the bus, and can then start sending messages to the remote service.

The plan is also to add static creation of rpmsg channels via the virtio config space, but it's not implemented yet.

---

# Speculation

_Peios Kernel / Internals / Staging_

> This document explains potential effects of speculation, and how undesirable effects can be mitigated portably using common APIs.

<a id="rst-speculation"></a>

This document explains potential effects of speculation, and how undesirable effects can be mitigated portably using common APIs.

---

To improve performance and minimize average latencies, many contemporary CPUs employ speculative execution techniques such as branch prediction, performing work which may be discarded at a later stage.

Typically speculative execution cannot be observed from architectural state, such as the contents of registers. However, in some cases it is possible to observe its impact on microarchitectural state, such as the presence or absence of data in caches. Such state may form side-channels which can be observed to extract secret information.

For example, in the presence of branch prediction, it is possible for bounds checks to be ignored by code which is speculatively executed. Consider the following code:



```text
int load_array(int *array, unsigned int index)
{
        if (index >= MAX_ARRAY_ELEMS)
                return 0;
        else
                return array[index];
}
```

Which, on arm64, may be compiled to an assembly sequence such as:



```text
      CMP     <index>, #MAX_ARRAY_ELEMS
      B.LT    less
      MOV     <returnval>, #0
      RET
less:
      LDR     <returnval>, [<array>, <index>]
      RET
```

It is possible that a CPU mis-predicts the conditional branch, and speculatively loads array\[index\], even if index &gt;= MAX\_ARRAY\_ELEMS. This value will subsequently be discarded, but the speculated load may affect microarchitectural state which can be subsequently measured.

More complex sequences involving multiple dependent memory accesses may result in sensitive information being leaked. Consider the following code, building on the prior example:



```text
int load_dependent_arrays(int *arr1, int *arr2, int index)
{
        int val1, val2,

        val1 = load_array(arr1, index);
        val2 = load_array(arr2, val1);

        return val2;
}
```

Under speculation, the first call to load\_array() may return the value of an out-of-bounds address, while the second call will influence microarchitectural state dependent on this value. This may provide an arbitrary read primitive.

<a id="rst-mitigating-speculation-side-channels"></a>

## Mitigating speculation side-channels

The kernel provides a generic API to ensure that bounds checks are respected even under speculation. Architectures which are affected by speculation-based side-channels are expected to implement these primitives.

The array\_index\_nospec() helper in &lt;linux/nospec.h&gt; can be used to prevent information from being leaked via side-channels.

A call to array\_index\_nospec(index, size) returns a sanitized index value that is bounded to \[0, size) even under cpu speculation conditions.

This can be used to protect the earlier load\_array() example:



```text
int load_array(int *array, unsigned int index)
{
        if (index >= MAX_ARRAY_ELEMS)
                return 0;
        else {
                index = array_index_nospec(index, MAX_ARRAY_ELEMS);
                return array[index];
        }
}
```

---

# Static Keys

_Peios Kernel / Internals / Staging_

> Static keys allows the inclusion of seldom used features in performance-sensitive fast-path kernel code, via a GCC feature and a code patching technique. A quick example:

<a id="rst-static-keys"></a>

> [!WARNING]
>
> DEPRECATED API:
>
> The use of 'struct static\_key' directly, is now DEPRECATED. In addition static\_key\_\{true,false\}() is also DEPRECATED. IE DO NOT use the following:
>
>
>
> ```text
> struct static_key false = STATIC_KEY_INIT_FALSE;
> struct static_key true = STATIC_KEY_INIT_TRUE;
> static_key_true()
> static_key_false()
> ```
>
> The updated API replacements are:
>
>
>
> ```text
> DEFINE_STATIC_KEY_TRUE(key);
> DEFINE_STATIC_KEY_FALSE(key);
> DEFINE_STATIC_KEY_ARRAY_TRUE(keys, count);
> DEFINE_STATIC_KEY_ARRAY_FALSE(keys, count);
> static_branch_likely()
> static_branch_unlikely()
> ```

<a id="rst-abstract"></a>

## Abstract

Static keys allows the inclusion of seldom used features in performance-sensitive fast-path kernel code, via a GCC feature and a code patching technique. A quick example:



```text
DEFINE_STATIC_KEY_FALSE(key);

...

if (static_branch_unlikely(&key))
        do unlikely code
else
        do likely code

...
static_branch_enable(&key);
...
static_branch_disable(&key);
...
```

The static\_branch\_unlikely() branch will be generated into the code with as little impact to the likely code path as possible.

<a id="rst-motivation"></a>

## Motivation

Currently, tracepoints are implemented using a conditional branch. The conditional check requires checking a global variable for each tracepoint. Although the overhead of this check is small, it increases when the memory cache comes under pressure (memory cache lines for these global variables may be shared with other memory accesses). As we increase the number of tracepoints in the kernel this overhead may become more of an issue. In addition, tracepoints are often dormant (disabled) and provide no direct kernel functionality. Thus, it is highly desirable to reduce their impact as much as possible. Although tracepoints are the original motivation for this work, other kernel code paths should be able to make use of the static keys facility.

<a id="rst-solution"></a>

## Solution

gcc (v4.5) adds a new 'asm goto' statement that allows branching to a label:

[https://gcc.gnu.org/ml/gcc-patches/2009-07/msg01556.html](<https://gcc.gnu.org/ml/gcc-patches/2009-07/msg01556.html>)

Using the 'asm goto', we can create branches that are either taken or not taken by default, without the need to check memory. Then, at run-time, we can patch the branch site to change the branch direction.

For example, if we have a simple branch that is disabled by default:



```text
if (static_branch_unlikely(&key))
        printk("I am the true branch\n");
```

Thus, by default the 'printk' will not be emitted. And the code generated will consist of a single atomic 'no-op' instruction (5 bytes on x86), in the straight-line code path. When the branch is 'flipped', we will patch the 'no-op' in the straight-line codepath with a 'jump' instruction to the out-of-line true branch. Thus, changing branch direction is expensive but branch selection is basically 'free'. That is the basic tradeoff of this optimization.

This lowlevel patching mechanism is called 'jump label patching', and it gives the basis for the static keys facility.

<a id="rst-static-key-label-api-usage-and-examples"></a>

## Static key label API, usage and examples

In order to make use of this optimization you must first define a key:



```text
DEFINE_STATIC_KEY_TRUE(key);
```

or:



```text
DEFINE_STATIC_KEY_FALSE(key);
```

The key must be global, that is, it can't be allocated on the stack or dynamically allocated at run-time.

The key is then used in code as:



```text
if (static_branch_unlikely(&key))
        do unlikely code
else
        do likely code
```

Or:



```text
if (static_branch_likely(&key))
        do likely code
else
        do unlikely code
```

Keys defined via DEFINE\_STATIC\_KEY\_TRUE(), or DEFINE\_STATIC\_KEY\_FALSE, may be used in either static\_branch\_likely() or static\_branch\_unlikely() statements.

Branch(es) can be set true via:



```text
static_branch_enable(&key);
```

or false via:



```text
static_branch_disable(&key);
```

The branch(es) can then be switched via reference counts:



```text
static_branch_inc(&key);
...
static_branch_dec(&key);
```

Thus, 'static\_branch\_inc()' means 'make the branch true', and 'static\_branch\_dec()' means 'make the branch false' with appropriate reference counting. For example, if the key is initialized true, a static\_branch\_dec(), will switch the branch to false. And a subsequent static\_branch\_inc(), will change the branch back to true. Likewise, if the key is initialized false, a 'static\_branch\_inc()', will change the branch to true. And then a 'static\_branch\_dec()', will again make the branch false.

The state and the reference count can be retrieved with 'static\_key\_enabled()' and 'static\_key\_count()'.  In general, if you use these functions, they should be protected with the same mutex used around the enable/disable or increment/decrement function.

Note that switching branches results in some locks being taken, particularly the CPU hotplug lock (in order to avoid races against CPUs being brought in the kernel while the kernel is getting patched). Calling the static key API from within a hotplug notifier is thus a sure deadlock recipe. In order to still allow use of the functionality, the following functions are provided:

> static\_key\_enable\_cpuslocked() static\_key\_disable\_cpuslocked() static\_branch\_enable\_cpuslocked() static\_branch\_disable\_cpuslocked()

These functions are <em>not</em> general purpose, and must only be used when you really know that you're in the above context, and no other.

Where an array of keys is required, it can be defined as:



```text
DEFINE_STATIC_KEY_ARRAY_TRUE(keys, count);
```

or:



```text
DEFINE_STATIC_KEY_ARRAY_FALSE(keys, count);
```

4. Architecture level code patching interface, 'jump labels'

There are a few functions and macros that architectures must implement in order to take advantage of this optimization. If there is no architecture support, we simply fall back to a traditional, load, test, and jump sequence. Also, the struct jump\_entry table must be at least 4-byte aligned because the static\_key-&gt;entry field makes use of the two least significant bits.

- - **`select HAVE_ARCH_JUMP_LABEL`,**

    see: arch/x86/Kconfig

- - **`#define JUMP_LABEL_NOP_SIZE`,**

    see: arch/x86/include/asm/jump\_label.h

- - **`__always_inline bool arch_static_branch(struct static_key *key, bool branch)`,**

    see: arch/x86/include/asm/jump\_label.h

- - **`__always_inline bool arch_static_branch_jump(struct static_key *key, bool branch)`,**

    see: arch/x86/include/asm/jump\_label.h

- - **`void arch_jump_label_transform(struct jump_entry *entry, enum jump_label_type type)`,**

    see: arch/x86/kernel/jump\_label.c

- - **`struct jump_entry`,**

    see: arch/x86/include/asm/jump\_label.h

5. Static keys / jump label analysis, results (x86\_64):

As an example, let's add the following branch to 'getppid()', such that the system call now looks like:



```text
SYSCALL_DEFINE0(getppid)
{
      int pid;

+     if (static_branch_unlikely(&key))
+             printk("I am the true branch\n");

      rcu_read_lock();
      pid = task_tgid_vnr(rcu_dereference(current->real_parent));
      rcu_read_unlock();

      return pid;
}
```

The resulting instructions with jump labels generated by GCC is:



```text
ffffffff81044290 <sys_getppid>:
ffffffff81044290:       55                      push   %rbp
ffffffff81044291:       48 89 e5                mov    %rsp,%rbp
ffffffff81044294:       e9 00 00 00 00          jmpq   ffffffff81044299 <sys_getppid+0x9>
ffffffff81044299:       65 48 8b 04 25 c0 b6    mov    %gs:0xb6c0,%rax
ffffffff810442a0:       00 00
ffffffff810442a2:       48 8b 80 80 02 00 00    mov    0x280(%rax),%rax
ffffffff810442a9:       48 8b 80 b0 02 00 00    mov    0x2b0(%rax),%rax
ffffffff810442b0:       48 8b b8 e8 02 00 00    mov    0x2e8(%rax),%rdi
ffffffff810442b7:       e8 f4 d9 00 00          callq  ffffffff81051cb0 <pid_vnr>
ffffffff810442bc:       5d                      pop    %rbp
ffffffff810442bd:       48 98                   cltq
ffffffff810442bf:       c3                      retq
ffffffff810442c0:       48 c7 c7 e3 54 98 81    mov    $0xffffffff819854e3,%rdi
ffffffff810442c7:       31 c0                   xor    %eax,%eax
ffffffff810442c9:       e8 71 13 6d 00          callq  ffffffff8171563f <printk>
ffffffff810442ce:       eb c9                   jmp    ffffffff81044299 <sys_getppid+0x9>
```

Without the jump label optimization it looks like:



```text
ffffffff810441f0 <sys_getppid>:
ffffffff810441f0:       8b 05 8a 52 d8 00       mov    0xd8528a(%rip),%eax        # ffffffff81dc9480 <key>
ffffffff810441f6:       55                      push   %rbp
ffffffff810441f7:       48 89 e5                mov    %rsp,%rbp
ffffffff810441fa:       85 c0                   test   %eax,%eax
ffffffff810441fc:       75 27                   jne    ffffffff81044225 <sys_getppid+0x35>
ffffffff810441fe:       65 48 8b 04 25 c0 b6    mov    %gs:0xb6c0,%rax
ffffffff81044205:       00 00
ffffffff81044207:       48 8b 80 80 02 00 00    mov    0x280(%rax),%rax
ffffffff8104420e:       48 8b 80 b0 02 00 00    mov    0x2b0(%rax),%rax
ffffffff81044215:       48 8b b8 e8 02 00 00    mov    0x2e8(%rax),%rdi
ffffffff8104421c:       e8 2f da 00 00          callq  ffffffff81051c50 <pid_vnr>
ffffffff81044221:       5d                      pop    %rbp
ffffffff81044222:       48 98                   cltq
ffffffff81044224:       c3                      retq
ffffffff81044225:       48 c7 c7 13 53 98 81    mov    $0xffffffff81985313,%rdi
ffffffff8104422c:       31 c0                   xor    %eax,%eax
ffffffff8104422e:       e8 60 0f 6d 00          callq  ffffffff81715193 <printk>
ffffffff81044233:       eb c9                   jmp    ffffffff810441fe <sys_getppid+0xe>
ffffffff81044235:       66 66 2e 0f 1f 84 00    data32 nopw %cs:0x0(%rax,%rax,1)
ffffffff8104423c:       00 00 00 00
```

Thus, the disable jump label case adds a 'mov', 'test' and 'jne' instruction vs. the jump label case just has a 'no-op' or 'jmp 0'. (The jmp 0, is patched to a 5 byte atomic no-op instruction at boot-time.) Thus, the disabled jump label case adds:



```text
6 (mov) + 2 (test) + 2 (jne) = 10 - 5 (5 byte jump 0) = 5 addition bytes.
```

If we then include the padding bytes, the jump label code saves, 16 total bytes of instruction memory for this small function. In this case the non-jump label function is 80 bytes long. Thus, we have saved 20% of the instruction footprint. We can in fact improve this even further, since the 5-byte no-op really can be a 2-byte no-op since we can reach the branch with a 2-byte jmp. However, we have not yet implemented optimal no-op sizes (they are currently hard-coded).

Since there are a number of static key API uses in the scheduler paths, 'pipe-test' (also known as 'perf bench sched pipe') can be used to show the performance improvement. Testing done on 3.3.0-rc2:

jump label disabled:



```text
Performance counter stats for 'bash -c /tmp/pipe-test' (50 runs):

       855.700314 task-clock                #    0.534 CPUs utilized            ( +-  0.11% )
          200,003 context-switches          #    0.234 M/sec                    ( +-  0.00% )
                0 CPU-migrations            #    0.000 M/sec                    ( +- 39.58% )
              487 page-faults               #    0.001 M/sec                    ( +-  0.02% )
    1,474,374,262 cycles                    #    1.723 GHz                      ( +-  0.17% )
  <not supported> stalled-cycles-frontend
  <not supported> stalled-cycles-backend
    1,178,049,567 instructions              #    0.80  insns per cycle          ( +-  0.06% )
      208,368,926 branches                  #  243.507 M/sec                    ( +-  0.06% )
        5,569,188 branch-misses             #    2.67% of all branches          ( +-  0.54% )

      1.601607384 seconds time elapsed                                          ( +-  0.07% )
```

jump label enabled:



```text
Performance counter stats for 'bash -c /tmp/pipe-test' (50 runs):

       841.043185 task-clock                #    0.533 CPUs utilized            ( +-  0.12% )
          200,004 context-switches          #    0.238 M/sec                    ( +-  0.00% )
                0 CPU-migrations            #    0.000 M/sec                    ( +- 40.87% )
              487 page-faults               #    0.001 M/sec                    ( +-  0.05% )
    1,432,559,428 cycles                    #    1.703 GHz                      ( +-  0.18% )
  <not supported> stalled-cycles-frontend
  <not supported> stalled-cycles-backend
    1,175,363,994 instructions              #    0.82  insns per cycle          ( +-  0.04% )
      206,859,359 branches                  #  245.956 M/sec                    ( +-  0.04% )
        4,884,119 branch-misses             #    2.36% of all branches          ( +-  0.85% )

      1.579384366 seconds time elapsed
```

The percentage of saved branches is .7%, and we've saved 12% on 'branch-misses'. This is where we would expect to get the most savings, since this optimization is about reducing the number of branches. In addition, we've saved .2% on instructions, and 2.8% on cycles and 1.4% on elapsed time.

---

# XZ data compression in Linux

_Peios Kernel / Internals / Staging_

> XZ is a general purpose data compression format with high compression ratio. The XZ decompressor in Linux is called XZ Embedded. It supports the LZMA2 filter and optionally also Branch/Call/Jump (BCJ) filters for executable code. CRC32 is…

<a id="rst-xz-data-compression-in-linux"></a>

<!-- SPDX-License-Identifier: 0BSD -->

<a id="rst-introduction"></a>

## Introduction

XZ is a general purpose data compression format with high compression ratio. The XZ decompressor in Linux is called XZ Embedded. It supports the LZMA2 filter and optionally also Branch/Call/Jump (BCJ) filters for executable code. CRC32 is supported for integrity checking.

See the [XZ Embedded](<https://tukaani.org/xz/embedded.html>) home page for the latest version which includes a few optional extra features that aren't required in the Linux kernel and information about using the code outside the Linux kernel.

For userspace, [XZ Utils](<https://tukaani.org/xz/>) provide a zlib-like compression library and a gzip-like command line tool.

<a id="rst-xz-embedded"></a>



<a id="rst-xz-utils"></a>



<a id="rst-xz-related-components-in-the-kernel"></a>

## XZ related components in the kernel

The xz\_dec module provides XZ decompressor with single-call (buffer to buffer) and multi-call (stateful) APIs in include/linux/xz.h.

For decompressing the kernel image, initramfs, and initrd, there is a wrapper function in lib/decompress\_unxz.c. Its API is the same as in other decompress\_\*.c files, which is defined in include/linux/decompress/generic.h.

For kernel makefiles, three commands are provided for use with `$(call if_changed)`. They require the xz tool from XZ Utils.

- `$(call if_changed,xzkern)` is for compressing the kernel image. It runs the script scripts/xz\_wrap.sh which uses arch-optimized options and a big LZMA2 dictionary.

- `$(call if_changed,xzkern_with_size)` is like `xzkern` above but this also appends a four-byte trailer containing the uncompressed size of the file. The trailer is needed by the boot code on some archs.

- Other things can be compressed with `$(call if_needed,xzmisc)` which will use no BCJ filter and 1 MiB LZMA2 dictionary.

<a id="rst-notes-on-compression-options"></a>

## Notes on compression options

Since the XZ Embedded supports only streams with CRC32 or no integrity check, make sure that you don't use some other integrity check type when encoding files that are supposed to be decoded by the kernel. With liblzma from XZ Utils, you need to use either `LZMA_CHECK_CRC32` or `LZMA_CHECK_NONE` when encoding. With the `xz` command line tool, use `--check=crc32` or `--check=none` to override the default `--check=crc64`.

Using CRC32 is strongly recommended unless there is some other layer which will verify the integrity of the uncompressed data anyway. Double checking the integrity would probably be waste of CPU cycles. Note that the headers will always have a CRC32 which will be validated by the decoder; you can only change the integrity check type (or disable it) for the actual uncompressed data.

In userspace, LZMA2 is typically used with dictionary sizes of several megabytes. The decoder needs to have the dictionary in RAM:

- In multi-call mode the dictionary is allocated as part of the decoder state. The reasonable maximum dictionary size for in-kernel use will depend on the target hardware: a few megabytes is fine for desktop systems while 64 KiB to 1 MiB might be more appropriate on some embedded systems.

- In single-call mode the output buffer is used as the dictionary buffer. That is, the size of the dictionary doesn't affect the decompressor memory usage at all. Only the base data structures are allocated which take a little less than 30 KiB of memory. For the best compression, the dictionary should be at least as big as the uncompressed data. A notable example of single-call mode is decompressing the kernel itself (except on PowerPC).

The compression presets in XZ Utils may not be optimal when creating files for the kernel, so don't hesitate to use custom settings to, for example, set the dictionary size. Also, xz may produce a smaller file in single-threaded mode so setting that explicitly is recommended. Example:



```text
xz --threads=1 --check=crc32 --lzma2=dict=512KiB inputfile
```

<a id="rst-xz-dec-api"></a>

## xz\_dec API

This is available with `#include <linux/xz.h>`.


#### <a id="c-enum-xz_mode"></a>`enum xz_mode`

Operation mode

**Constants**

- `XZ_SINGLE`: Single-call mode. This uses less RAM than
  multi-call modes, because the LZMA2
  dictionary doesn't need to be allocated as
  part of the decoder state. All required data
  structures are allocated at initialization,
  so [`xz_dec_run()`](#c-xz_dec_run) cannot return XZ_MEM_ERROR.
- `XZ_PREALLOC`: Multi-call mode with preallocated LZMA2
  dictionary buffer. All data structures are
  allocated at initialization, so [`xz_dec_run()`](#c-xz_dec_run)
  cannot return XZ_MEM_ERROR.
- `XZ_DYNALLOC`: Multi-call mode. The LZMA2 dictionary is
  allocated once the required size has been
  parsed from the stream headers. If the
  allocation fails, [`xz_dec_run()`](#c-xz_dec_run) will return
  XZ_MEM_ERROR.

**Description**

It is possible to enable support only for a subset of the above
modes at compile time by defining XZ_DEC_SINGLE, XZ_DEC_PREALLOC,
or XZ_DEC_DYNALLOC. The xz_dec kernel module is always compiled
with support for all operation modes, but the preboot code may
be built with fewer features to minimize code size.

#### <a id="c-enum-xz_ret"></a>`enum xz_ret`

Return codes

**Constants**

- `XZ_OK`: Everything is OK so far. More input or more
  output space is required to continue. This
  return code is possible only in multi-call mode
  (XZ_PREALLOC or XZ_DYNALLOC).
- `XZ_STREAM_END`: Operation finished successfully.
- `XZ_UNSUPPORTED_CHECK`: Integrity check type is not supported. Decoding
  is still possible in multi-call mode by simply
  calling [`xz_dec_run()`](#c-xz_dec_run) again.
  Note that this return value is used only if
  XZ_DEC_ANY_CHECK was defined at build time,
  which is not used in the kernel. Unsupported
  check types return XZ_OPTIONS_ERROR if
  XZ_DEC_ANY_CHECK was not defined at build time.
- `XZ_MEM_ERROR`: Allocating memory failed. This return code is
  possible only if the decoder was initialized
  with XZ_DYNALLOC. The amount of memory that was
  tried to be allocated was no more than the
  dict_max argument given to [`xz_dec_init()`](#c-xz_dec_init).
- `XZ_MEMLIMIT_ERROR`: A bigger LZMA2 dictionary would be needed than
  allowed by the dict_max argument given to
  [`xz_dec_init()`](#c-xz_dec_init). This return value is possible
  only in multi-call mode (XZ_PREALLOC or
  XZ_DYNALLOC); the single-call mode (XZ_SINGLE)
  ignores the dict_max argument.
- `XZ_FORMAT_ERROR`: File format was not recognized (wrong magic
  bytes).
- `XZ_OPTIONS_ERROR`: This implementation doesn't support the requested
  compression options. In the decoder this means
  that the header CRC32 matches, but the header
  itself specifies something that we don't support.
- `XZ_DATA_ERROR`: Compressed data is corrupt.
- `XZ_BUF_ERROR`: Cannot make any progress. Details are slightly
  different between multi-call and single-call
  mode; more information below.

**Description**

In multi-call mode, XZ_BUF_ERROR is returned when two consecutive calls
to XZ code cannot consume any input and cannot produce any new output.
This happens when there is no new input available, or the output buffer
is full while at least one output byte is still pending. Assuming your
code is not buggy, you can get this error only when decoding a compressed
stream that is truncated or otherwise corrupt.

In single-call mode, XZ_BUF_ERROR is returned only when the output buffer
is too small or the compressed input is corrupt in a way that makes the
decoder produce more output than the caller expected. When it is
(relatively) clear that the compressed input is truncated, XZ_DATA_ERROR
is used instead of XZ_BUF_ERROR.

#### <a id="c-struct-xz_buf"></a>`struct xz_buf`

Passing input and output buffers to XZ code

**Definition**

```c
struct xz_buf {
    const uint8_t *in;
    size_t in_pos;
    size_t in_size;
    uint8_t *out;
    size_t out_pos;
    size_t out_size;
};
```

**Members**

- `in`: Beginning of the input buffer. This may be NULL if and only
  if in_pos is equal to in_size.
- `in_pos`: Current position in the input buffer. This must not exceed
  in_size.
- `in_size`: Size of the input buffer
- `out`: Beginning of the output buffer. This may be NULL if and only
  if out_pos is equal to out_size.
- `out_pos`: Current position in the output buffer. This must not exceed
  out_size.
- `out_size`: Size of the output buffer

**Description**

Only the contents of the output buffer from out\[out_pos\] onward, and
the variables in_pos and out_pos are modified by the XZ code.

#### <a id="c-xz_dec_init"></a>`xz_dec_init()`

```c
struct xz_dec * xz_dec_init(enum xz_mode mode, uint32_t dict_max)
```

Allocate and initialize a XZ decoder state

**Parameters**

- `enum xz_mode mode`: Operation mode
- `uint32_t dict_max`: Maximum size of the LZMA2 dictionary (history buffer) for
  multi-call decoding. This is ignored in single-call mode
  (mode == XZ_SINGLE). LZMA2 dictionary is always 2^n bytes
  or 2^n + 2^(n-1) bytes (the latter sizes are less common
  in practice), so other values for dict_max don't make sense.
  In the kernel, dictionary sizes of 64 KiB, 128 KiB, 256 KiB,
  512 KiB, and 1 MiB are probably the only reasonable values,
  except for kernel and initramfs images where a bigger
  dictionary can be fine and useful.

**Description**

Single-call mode (XZ_SINGLE): [`xz_dec_run()`](#c-xz_dec_run) decodes the whole stream at
once. The caller must provide enough output space or the decoding will
fail. The output space is used as the dictionary buffer, which is why
there is no need to allocate the dictionary as part of the decoder's
internal state.

Because the output buffer is used as the workspace, streams encoded using
a big dictionary are not a problem in single-call mode. It is enough that
the output buffer is big enough to hold the actual uncompressed data; it
can be smaller than the dictionary size stored in the stream headers.

Multi-call mode with preallocated dictionary (XZ_PREALLOC): dict_max bytes
of memory is preallocated for the LZMA2 dictionary. This way there is no
risk that [`xz_dec_run()`](#c-xz_dec_run) could run out of memory, since [`xz_dec_run()`](#c-xz_dec_run) will
never allocate any memory. Instead, if the preallocated dictionary is too
small for decoding the given input stream, [`xz_dec_run()`](#c-xz_dec_run) will return
XZ_MEMLIMIT_ERROR. Thus, it is important to know what kind of data will be
decoded to avoid allocating excessive amount of memory for the dictionary.

Multi-call mode with dynamically allocated dictionary (XZ_DYNALLOC):
dict_max specifies the maximum allowed dictionary size that [`xz_dec_run()`](#c-xz_dec_run)
may allocate once it has parsed the dictionary size from the stream
headers. This way excessive allocations can be avoided while still
limiting the maximum memory usage to a sane value to prevent running the
system out of memory when decompressing streams from untrusted sources.

On success, [`xz_dec_init()`](#c-xz_dec_init) returns a pointer to struct xz_dec, which is
ready to be used with [`xz_dec_run()`](#c-xz_dec_run). If memory allocation fails,
[`xz_dec_init()`](#c-xz_dec_init) returns NULL.

#### <a id="c-xz_dec_run"></a>`xz_dec_run()`

```c
enum xz_ret xz_dec_run(struct xz_dec *s, struct xz_buf *b)
```

Run the XZ decoder

**Parameters**

- `struct xz_dec *s`: Decoder state allocated using [`xz_dec_init()`](#c-xz_dec_init)
- `struct xz_buf *b`: Input and output buffers

**Description**

The possible return values depend on build options and operation mode.
See enum xz_ret for details.

Note that if an error occurs in single-call mode (return value is not
XZ_STREAM_END), b->in_pos and b->out_pos are not modified and the
contents of the output buffer from b->out\[b->out_pos\] onward are
undefined. This is true even after XZ_BUF_ERROR, because with some filter
chains, there may be a second pass over the output buffer, and this pass
cannot be properly done if the output buffer is truncated. Thus, you
cannot give the single-call decoder a too small buffer and then expect to
get that amount valid data from the beginning of the stream. You must use
the multi-call decoder if you don't want to uncompress the whole stream.

#### <a id="c-xz_dec_reset"></a>`xz_dec_reset()`

```c
void xz_dec_reset(struct xz_dec *s)
```

Reset an already allocated decoder state

**Parameters**

- `struct xz_dec *s`: Decoder state allocated using [`xz_dec_init()`](#c-xz_dec_init)

**Description**

This function can be used to reset the multi-call decoder state without
freeing and reallocating memory with [`xz_dec_end()`](#c-xz_dec_end) and [`xz_dec_init()`](#c-xz_dec_init).

In single-call mode, [`xz_dec_reset()`](#c-xz_dec_reset) is always called in the beginning of
[`xz_dec_run()`](#c-xz_dec_run). Thus, explicit call to [`xz_dec_reset()`](#c-xz_dec_reset) is useful only in
multi-call mode.

#### <a id="c-xz_dec_end"></a>`xz_dec_end()`

```c
void xz_dec_end(struct xz_dec *s)
```

Free the memory allocated for the decoder state

**Parameters**

- `struct xz_dec *s`: Decoder state allocated using [`xz_dec_init()`](#c-xz_dec_init). If s is NULL,
  this function does nothing.

**MicroLZMA decompressor**

This MicroLZMA header format was created for use in EROFS but may be used
by others too. **In most cases one needs the XZ APIs above instead.**

The compressed format supported by this decoder is a raw LZMA stream
whose first byte (always 0x00) has been replaced with bitwise-negation
of the LZMA properties (lc/lp/pb) byte. For example, if lc/lp/pb is
3/0/2, the first byte is 0xA2. This way the first byte can never be 0x00.
Just like with LZMA2, lc + lp \<= 4 must be true. The LZMA end-of-stream
marker must not be used. The unused values are reserved for future use.

#### <a id="c-xz_dec_microlzma_alloc"></a>`xz_dec_microlzma_alloc()`

```c
struct xz_dec_microlzma * xz_dec_microlzma_alloc(enum xz_mode mode, uint32_t dict_size)
```

Allocate memory for the MicroLZMA decoder

**Parameters**

- `enum xz_mode mode`: XZ_SINGLE or XZ_PREALLOC
- `uint32_t dict_size`: LZMA dictionary size. This must be at least 4 KiB and
  at most 3 GiB.

**Description**

In contrast to [`xz_dec_init()`](#c-xz_dec_init), this function only allocates the memory
and remembers the dictionary size. [`xz_dec_microlzma_reset()`](#c-xz_dec_microlzma_reset) must be used
before calling [`xz_dec_microlzma_run()`](#c-xz_dec_microlzma_run).

The amount of allocated memory is a little less than 30 KiB with XZ_SINGLE.
With XZ_PREALLOC also a dictionary buffer of dict_size bytes is allocated.

On success, [`xz_dec_microlzma_alloc()`](#c-xz_dec_microlzma_alloc) returns a pointer to
struct xz_dec_microlzma. If memory allocation fails or
dict_size is invalid, NULL is returned.

#### <a id="c-xz_dec_microlzma_reset"></a>`xz_dec_microlzma_reset()`

```c
void xz_dec_microlzma_reset(struct xz_dec_microlzma *s, uint32_t comp_size, uint32_t uncomp_size, int uncomp_size_is_exact)
```

Reset the MicroLZMA decoder state

**Parameters**

- `struct xz_dec_microlzma *s`: Decoder state allocated using [`xz_dec_microlzma_alloc()`](#c-xz_dec_microlzma_alloc)
- `uint32_t comp_size`: Compressed size of the input stream
- `uint32_t uncomp_size`: Uncompressed size of the input stream. A value smaller
  than the real uncompressed size of the input stream can
  be specified if uncomp_size_is_exact is set to false.
  uncomp_size can never be set to a value larger than the
  expected real uncompressed size because it would eventually
  result in XZ_DATA_ERROR.
- `int uncomp_size_is_exact`: This is an int instead of bool to avoid
  requiring stdbool.h. This should normally be set to true.
  When this is set to false, error detection is weaker.

#### <a id="c-xz_dec_microlzma_run"></a>`xz_dec_microlzma_run()`

```c
enum xz_ret xz_dec_microlzma_run(struct xz_dec_microlzma *s, struct xz_buf *b)
```

Run the MicroLZMA decoder

**Parameters**

- `struct xz_dec_microlzma *s`: Decoder state initialized using [`xz_dec_microlzma_reset()`](#c-xz_dec_microlzma_reset)
- `struct xz_buf *b`: Input and output buffers

**Description**

This works similarly to [`xz_dec_run()`](#c-xz_dec_run) with a few important differences.
Only the differences are documented here.

The only possible return values are XZ_OK, XZ_STREAM_END, and
XZ_DATA_ERROR. This function cannot return XZ_BUF_ERROR: if no progress
is possible due to lack of input data or output space, this function will
keep returning XZ_OK. Thus, the calling code must be written so that it
will eventually provide input and output space matching (or exceeding)
comp_size and uncomp_size arguments given to [`xz_dec_microlzma_reset()`](#c-xz_dec_microlzma_reset).
If the caller cannot do this (for example, if the input file is truncated
or otherwise corrupt), the caller must detect this error by itself to
avoid an infinite loop.

If the compressed data seems to be corrupt, XZ_DATA_ERROR is returned.
This can happen also when incorrect dictionary, uncompressed, or
compressed sizes have been specified.

With XZ_PREALLOC only: As an extra feature, b->out may be NULL to skip over
uncompressed data. This way the caller doesn't need to provide a temporary
output buffer for the bytes that will be ignored.

With XZ_SINGLE only: In contrast to [`xz_dec_run()`](#c-xz_dec_run), the return value XZ_OK
is also possible and thus XZ_SINGLE is actually a limited multi-call mode.
After XZ_OK the bytes decoded so far may be read from the output buffer.
It is possible to continue decoding but the variables b->out and b->out_pos
MUST NOT be changed by the caller. Increasing the value of b->out_size is
allowed to make more output space available; one doesn't need to provide
space for the whole uncompressed data on the first call. The input buffer
may be changed normally like with XZ_PREALLOC. This way input data can be
provided from non-contiguous memory.

#### <a id="c-xz_dec_microlzma_end"></a>`xz_dec_microlzma_end()`

```c
void xz_dec_microlzma_end(struct xz_dec_microlzma *s)
```

Free the memory allocated for the decoder state

**Parameters**

- `struct xz_dec_microlzma *s`: Decoder state allocated using [`xz_dec_microlzma_alloc()`](#c-xz_dec_microlzma_alloc).
  If s is NULL, this function does nothing.

---

# Overview

_Peios Kernel / Internals / StrataFS / Start here_

> stratafs presents an ordered set of existing directories as one tree — where it sits, the model it follows, and what it delegates.

<a id="trm-4-1"></a>

stratafs presents an ordered set of existing directories — its
**strata**, or layers, which give it its name — as one merged
directory tree. Each stratum is an ordinary
directory on an ordinary filesystem, owned and written by whatever
agent owns it, with no coordination with stratafs and no notification
to it. The merged view reflects changes to any stratum without a
remount. <a id="cite-mount.reflects-stratum-changes"></a>

It is a stacking filesystem in the strict sense: it stores no file
data, no directory entries, and no security descriptors. Every object
reachable through a stratafs mount is a real object on a real stratum,
and every data and metadata operation is performed against that object. <a id="cite-model.every-object-is-real"></a>
stratafs inodes carry no address-space operations, so there is no
second page cache to keep coherent; reads, writes, mappings and splices
are forwarded to a backing file opened on the provider.

Unlike overlayfs, stratafs has **no whiteouts and no opaque-directory
markers**. There is no mechanism anywhere in the filesystem for
recording that a name should be absent. That single omission accounts
for most of what is unusual about it: removing a name can leave the
name visible, some names cannot be removed at all, and several
operations that succeed on an ordinary filesystem are refused here
rather than faked. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) collects the consequences.

<a id="trm-4-1-1"></a>

## Where it sits <a id="cite-mount.superblock-identity"></a>

stratafs lives in `fs/stratafs`, alongside PKM. It is built by `CONFIG_STRATAFS_FS` — a boolean option, so it
is linked into `vmlinux` — and registered by an `fs_initcall`. The
option depends on `CONFIG_SECURITY_PKM`, because stratafs reaches KACS
for every access decision and for the whole of the copy-up context.
That reach is through `<linux/kacs_stratafs.h>`, a kernel-private
header in `include/linux` whose symbols are deliberately not exported
to modules. This is a private in-kernel integration interface, not a
userspace API.

The filesystem type registers under the name `stratafs`, with the
superblock magic `0x53545241` — ASCII `STRA` — and the flags
`FS_USERNS_MOUNT` and `FS_RENAME_DOES_D_MOVE`. It takes no device;
superblocks come from `get_tree_nodev`, so the device identifier
reported for every object in a mount is an anonymous one belonging to
the mount rather than to any stratum.

A small part of the filesystem is written in Rust. The crate
`stratafs-core` compiles the sources in `security/pkm/stratafs_core`
and holds three pure, allocation-free decisions: validating the
stack-wide flag rules, selecting the provider from a presence bitmap,
and routing one modifying operation. Everything else — the VFS glue,
resolution, enumeration, copy-up — is C.

<a id="trm-4-1-2"></a>

## The model <a id="cite-strata.identified-by-path"></a>

A mount is defined by its **stratum stack**: an ordered list of strata,
highest-precedence first, fixed for the life of the mount. A stratum is
identified by its **path**, not by the directory that path resolved to
at mount time, which is what allows a package transaction to replace a
whole stratum by renaming trees around underneath a live mount.

For a given name in a given directory, the **provider** is the
highest-precedence stratum that holds it. A name whose provider is a
directory, and which lower strata also hold as a directory, resolves to
a **merged directory** whose entries are the union of theirs. A name
whose provider is anything else masks every lower entry of that name
completely, subtree and all.

At most one stratum carries the `create` flag. That **create stratum**
receives newly created objects and is the destination of **copy-up** —
the replication of an object into the create stratum so that a
modification can be applied without touching the stratum that provides
it. A stack may have no create stratum, in which case nothing can be
created and nothing copied up.

Routing a modification is a decision about strata alone. It happens
when the modifying operation is performed, never at open, and it never
consults the caller: by the time an operation reaches stratafs, KACS
has already decided the caller was entitled to perform it. [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) sets
out why no other formulation is implementable.

<a id="trm-4-1-3"></a>

## What it delegates

stratafs holds no security descriptors, so it makes no access
decisions of its own about the objects it presents. The descriptor
evaluated for an operation is the one on the object the operation will
be performed against, and KACS reads it through the ordinary
extended-attribute path, which the stacking layer forwards down to the
provider. A stratafs mount cannot grant access its provider stratum
would refuse.

A merged directory is the exception, because it stands for several
real directories with several descriptors and forwarding yields only
the provider's. Those checks stratafs performs itself, against every
participating directory, requiring all of them to succeed ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)).

Copy-up is the other exception, in the opposite direction. It is
machinery serving an operation that was already authorised, not an
operation a caller requests, so it must introduce no new checks against
whichever task happens to execute it. KACS provides a kernel-internal
copy-up context for exactly this, described in full at [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>); [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)
covers the stratafs half.

<a id="trm-4-1-4"></a>

## This chapter

[The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>) covers the stack, the mount options that define it, what a
mounter must be entitled to, and absent strata. [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>) covers resolution:
providers, merging, type conflicts, and enumeration. [The Coherency Model](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-1>) covers
coherency — how uncoordinated change is observed, and the inode
identity presented over it. [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) covers mutation: routing, copy-up,
creation, removal, rename, links, locking and durability. [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>) covers
the security seam with KACS, and [The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>) the one interface stratafs
synthesises for userspace. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) collects the failure modes, including
the divergences from ordinary filesystem behaviour that follow from
having no whiteouts, and [Constants](</kernel/internals/stratafs/start-here/generated-constants.md#trm-4-a>) the constants.

## Mounting and testing

See [StrataFS mount options](</kernel/administration/stratafs/mount-options.md>) for operation, and [StrataFS test hooks](</kernel/development/native-subsystems/stratafs-test-hooks.md>) for development.

## Topics

- [Security](</kernel/internals/stratafs/security/overview.md>)
- [Mutation](</kernel/internals/stratafs/mutation/overview.md>)
- [Strata and mounting](</kernel/internals/stratafs/strata-and-mounting/overview.md>)
- [Name resolution](</kernel/internals/stratafs/name-resolution/overview.md>)
- [Coherency](</kernel/internals/stratafs/coherency/overview.md>)

---

# The Origin Attribute

_Peios Kernel / Internals / StrataFS / Start here_

> The one synthetic extended attribute that reveals which stratum provided a merged path — its value, constraints and access rules.

<a id="trm-4-7"></a>

A merged path does not reveal which stratum provided it. stratafs
exposes that through one synthetic extended attribute,
`system.stratafs.origin`, and deliberately through nothing else — a
tool that instead re-implemented [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>)'s resolution rules against the
strata would be a second implementation of them, and would eventually
disagree with the first.

Together with the mount table ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)), which gives the stratum stack,
it is enough to explain any path in a mount without privilege beyond
what reading the path itself requires.

<a id="trm-4-7-1"></a>

## The value

Reading the attribute returns the absolute path of the object that
provides it:

- For a **non-directory**, the provider's path in its stratum. <a id="cite-origin.value.non-directory"></a>
- For a **merged directory**, the paths of every participating
  directory in precedence order, separated by newlines. <a id="cite-origin.value.merged-directory"></a>

Each element is the stratum's own path, then a `/` where the relative
part is non-empty and the base does not already end in one, then the
relative path. <a id="cite-origin.value.element-format"></a> Within a path, a newline or a backslash is escaped by a
preceding backslash; those two are the whole escape set, and the `/`
stratafs itself inserts is not escaped. <a id="cite-origin.value.escaping"></a> Stratum paths are absolute
because the mount parser required them to be ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)).

There is no trailing newline and no trailing NUL. <a id="cite-origin.value.no-trailing-terminator"></a> A null buffer returns
the length required; an undersized one returns `ERANGE`. <a id="cite-origin.value.sizing"></a>

The value is synthesised at each read from the current resolution. It
is not stored, and it is not the value of any attribute on any stratum. <a id="cite-origin.value.synthesised-per-read"></a>
Because non-root dentries are always invalidated ([Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>)), a read by
path always reflects a fresh resolution.

<a id="trm-4-7-2"></a>

## Constraints

The attribute is not settable. Any set or removal in the reserved
namespace fails with `EPERM`, before the provider is reached at all. <a id="cite-origin.not-settable"></a>

It is not reported by an attribute listing. The listing handler filters
reserved names out of both its sizing pass and its copy pass, and the
synthetic name is never added to any listing. <a id="cite-origin.hidden-from-listing"></a> Hiding it keeps
archivers, copy tools and backup software from discovering it,
attempting to preserve it, and failing.

The whole `system.stratafs.` namespace is reserved. No read, write or
removal of any name in it is forwarded to the provider: a read of any
name other than `origin` returns `ENODATA`, and a write or removal
returns `EPERM`. <a id="cite-origin.namespace-reserved"></a> Where a provider object carries a real attribute of
one of these names, it is masked — the synthesised value is returned
instead, and the provider's attribute is absent from listings through
the mount. <a id="cite-origin.masks-provider-attribute"></a>

Two details of the implementation are worth stating exactly. The
namespace test is a fixed-length prefix comparison against
`system.stratafs.` including the trailing dot, so the bare name
`system.stratafs` is *not* reserved and would be forwarded to the
provider. <a id="cite-origin.bare-name-not-reserved"></a> And the reserved set is one name wider than the namespace
suggests: the staging marker attribute,
`security.peios.stratafs_staging`, receives the same treatment —
`EPERM` to write, `ENODATA` to read, hidden from listings, masked from
providers — despite lying outside the `system.stratafs.` namespace. <a id="cite-origin.staging-marker-reserved"></a>

<a id="trm-4-7-3"></a>

## Access

Reading the attribute requires the access that reading an extended
attribute of the object requires, and is refused where that would be
refused. <a id="cite-origin.requires-read-ea"></a> The right to read the object's stat attributes is not
sufficient: the request is for the read-EA right, which KACS's
`getxattr` hook demands on the stratafs dentry before stratafs's own
handler runs.

For a merged directory the value names every participating directory,
so it discloses more than any one of them. Reading it requires that
access on **every** participating directory and is refused where any
refuses — the same intersection [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) applies to enumeration, and for
the same reason: a caller who may not know a restricted directory
participates must not learn it from this attribute. <a id="cite-origin.merged-requires-all-participants"></a>

Where the attribute is read **through a directory descriptor**, the
participating set is the one settled when that descriptor was opened
([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)), and the value names that set rather than the current one. <a id="cite-origin.fd.settled-participant-set"></a> The
access decision was likewise made at open and is recorded on the
dentry, so the read consults a stored verdict rather than re-checking. <a id="cite-origin.fd.access-decided-at-open"></a>
A stratum that has joined since is not disclosed, because the check
that would have covered it was never run; a settled participant that
has since ceased to hold the directory is still named, for the same
reason.

Where it is read **by path**, the participating set is the current one,
resolved afresh, and the read-EA right is required against each of its
members at that moment. <a id="cite-origin.by-path.current-participant-set"></a>

---

# Failure Modes

_Peios Kernel / Internals / StrataFS / Start here_

> Every condition under which a stratafs operation fails and the error it produces, from mount time through resolution and mutation.

<a id="trm-4-8"></a>

This section consolidates the conditions under which a stratafs
operation fails and the error each produces. The sections above remain
authoritative for the conditions themselves.

<a id="trm-4-8-1"></a>

## Mount-time

| Condition | Error |
|---|---|
| Caller lacks the access to resolve a stratum path or read its attributes | `EACCES` |
| Empty stratum stack, or `strata=` absent | `EINVAL` |
| Stack longer than 16 strata | `EINVAL` |
| More than one stratum carries `create` | `EINVAL` |
| A stratum carries both `create` and `ro` | `EINVAL` |
| The same directory appears twice in the stack | `EINVAL` |
| Any malformed `strata=` value ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` |
| A remount's `strata=` differs from the mounted stack ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` |
| An allocation failure while parsing | `ENOMEM` |
| A create-bearing stack established outside the initial user namespace, or without `CAP_SYS_ADMIN` there | `EPERM` |
| A stratum path names a non-directory | `ENOTDIR` |
| A stratum is absent without `am` | `ENOENT` |
| A stratum lies within the mount point, or within another stratafs mount whose strata include this mount point | `ELOOP` |
| The composed stack reaches the kernel's maximum stacking depth | `ELOOP` |
| Sixteen consecutive collisions allocating a mount cookie | `EAGAIN` |

The option-only conditions are decided before any path is touched, and
the `EPERM` admission test before any path is resolved. <a id="cite-failure.mount.option-checks-precede-path-checks"></a> The per-path
conditions follow. [Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>) records the one place the specified ordering
is not achieved.

<a id="trm-4-8-2"></a>

## Resolution

| Condition | Error |
|---|---|
| No participating stratum holds the name | `ENOENT` |
| An ancestor of the path is masked by a non-directory provider | `ENOTDIR` |
| Operation requires a non-directory; provider is a directory | `EISDIR` |
| Traverse or list refused on any participating directory | `EACCES` |
| A stratum walk fails for a reason other than absence | that error |
| A joined stratum path or child relative path exceeds `PATH_MAX` | `ENAMETOOLONG` |
| A task re-enters the same superblock while resolving | `ELOOP` |

<a id="trm-4-8-3"></a>

## Mutation

| Condition | Error |
|---|---|
| Provider will not accept modification, and no create stratum has higher precedence | `EROFS` |
| Any mutation on a read-only-mounted stratafs | `EROFS` |
| Creation, unnamed-file creation, or unnamed-file link with no create stratum, or it absent | `EROFS` |
| Create stratum holds a path component as a non-directory | `ENOTDIR` |
| Exclusive creation where any stratum holds the name | `EEXIST` |
| Copy-up cannot preserve an extended attribute | `EIO` |
| Copy-up cannot preserve the descriptor | `EACCES`, `EOPNOTSUPP`, `EINVAL`, `ESTALE` or `ENOMEM`, as KACS reported it |
| Copy-up for a descriptor whose object is no longer the provider, or whose target name is taken at publication | `ESTALE` |
| Copy-up of a device node, FIFO or socket | `EROFS` |
| Unlink where the provider will not accept modification | `EROFS`, or `EPERM` where the provider inode is immutable |
| Rmdir where another stratum holds entries within | `ENOTEMPTY` |
| Rmdir or directory rename where list is refused on a participant | `EACCES` |
| Modifying a special file's mode, descriptor or extended attributes where its provider will not accept modification | `EROFS` |
| Establishing a shared write-capable mapping where routing yields read-only | `EROFS` |
| A route change after shared mapping preparation could require another copy-up | `EAGAIN`; retry the whole `mmap` call |
| StrataFS or FUSE passthrough layers exceed the supported stacking depth during shared mapping preparation | `ELOOP` |
| Replacing disposition where [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) would refuse the removal, or where a stratum above the create stratum would still hold the name | `EROFS` |
| Replacing disposition on anything but a regular file | `EOPNOTSUPP` |
| Rename where the source's provider will not accept modification | `EROFS` |
| Rename where a stratum above the source's provider provides the destination | `EROFS` |
| Rename where the source's provider does not hold the destination's directory | `EXDEV` |
| Rename of a directory containing entries from other strata | `EXDEV` |
| Rename of a non-directory onto a directory provider | `EISDIR` |
| Rename of a directory onto a non-directory provider | `ENOTDIR` |
| Rename onto a destination directory not empty across every stratum | `ENOTEMPTY` |
| `RENAME_NOREPLACE` where any stratum holds the destination | `EEXIST` |
| `RENAME_EXCHANGE` where the two names are not provided by one stratum that accepts modification | `EROFS` |
| `RENAME_EXCHANGE` where another stratum holds entries under either directory name | `EXDEV` |
| `RENAME_WHITEOUT` | `EINVAL` |
| Hard link whose source's provider will not accept modification, or does not hold the destination's directory | `EXDEV` |
| Hard link where any stratum holds the destination | `EEXIST` |
| Linking an unnamed file into a different mount | `EXDEV` |
| A dentry whose private state is missing, or whose provider identity no longer matches | `ESTALE` |
| `ioctl` on a regular file | `ENOTTY`, or `ENOIOCTLCMD` for the compat form |
| `remap_file_range` with flags outside dedupe and advisory | `EINVAL` |

Shared mapping preparation can publish a copy-up before a later mapping
check fails. That copy remains published; the mapping failure does not
restore the earlier provider. Copies completed by earlier layers also
remain if preparation fails deeper in the backing chain.

<a id="trm-4-8-4"></a>

## Interface

| Condition | Error |
|---|---|
| Set or remove of any reserved attribute | `EPERM` |
| Read of a reserved attribute other than `origin` | `ENODATA` |
| Origin read where read-EA is refused on any participant | `EACCES` |
| Origin read into an undersized buffer | `ERANGE` |
| Freezing the filesystem | `EOPNOTSUPP` |
| Reading a mount's policy without TCB privilege | refused by KACS |

<a id="trm-4-8-5"></a>

## Intended divergences

None of the following is a defect. Each is described above, and each
follows from stratafs having no way to record that a name should be
absent, or from a merged path standing for objects in more than one
stratum.

- **Removing a name may not remove it from the view.** Where a lower
  stratum also holds the name, it becomes the provider and the name
  remains, now resolving to different content ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)).
- **A name may be unremovable.** Where the provider will not accept
  modification, removal fails however the caller is privileged
  ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)).
- **Rename may be refused for an unmodified file.** Where the source's
  provider will not accept modification, rename fails rather than
  silently copying ([Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>)).
- **Hard links may be refused within one directory.** Where the
  source's provider will not accept modification, linking fails with
  `EXDEV` ([Links](</kernel/internals/stratafs/mutation/links.md#trm-4-5-6>)).
- **An object's inode number may change.** Where the provider for a
  path changes, a new inode is presented ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **Two callers may hold non-contending locks on one path.** Locks are
  held on the object a descriptor resolved to, so callers who opened
  either side of a change of provider — including one caused by a
  copy-up neither of them performed — have locked different objects
  ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).
- **Copy-up severs hard links.** Two names that shared an object in a
  lower stratum, and compared equal by inode number, refer to different
  objects once one of them is written through the mount; only the
  written one is copied up ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
- **An open may succeed where the first write then fails.** Routing
  happens when a modifying operation is performed, not at open, so an
  open for writing against a provider that will not accept modification
  succeeds and the `EROFS` arrives at the write, the truncate, or the
  attempt to establish a shared writable mapping ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).
- **A copy-up moves an object out from under descriptors already open
  on it.** Only the descriptor whose operation caused the copy-up refers
  to the copy; others continue to refer to the original, and locks held
  on it stay there ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>), [Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).
- **A write may fail `ESTALE` on a descriptor that was valid when
  opened.** Where another descriptor, another mount, or a direct writer
  has since caused that name to be provided by a different object, a
  copy-up cannot proceed and the caller must reopen ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
- **`fstat` and `stat` may report different inode numbers for one
  file.** After a copy-up, the descriptor that caused it keeps the inode
  it was opened against while a fresh resolution of the path yields a
  new one, so the two disagree for as long as that descriptor lives —
  though both name the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **A directory's link count is always 1.** The true count of
  subdirectories spans strata and cannot be maintained ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)).
- **Directory positions do not survive a reopen.** A `readdir` offset
  is an ordinal into a per-descriptor capture, carrying no provider
  cookie ([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)).

Every one of the first four is the result of refusing to invent a
hidden record — a whiteout — that would make an entry in someone else's
directory unreachable without their knowledge. The alternative buys
POSIX fidelity at the cost of a stratum no longer meaning what its
owner wrote in it, which is the property [The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>) exists to protect.

---

# Generated constants

_Peios Kernel / Internals / StrataFS / Start here_

> Every stratafs constant — filesystem identity, stratum flags, extended attributes, copy-up and staging markers — generated from the source.

<a id="trm-4-a"></a>

Every value below is generated from the source by
`tools/docs/peios-reference/generators/gen-stratafs-constants.py`. Nothing here is transcribed by
hand, and the generator's `--check` mode fails if the two drift apart. <a id="cite-const.generated-from-source"></a>

<a id="trm-4-a-1"></a>

## Filesystem identity <a id="cite-const.magic-alias-shared-with-kacs"></a>

| Constant              | Value        | Meaning                                         |
|-----------------------|--------------|-------------------------------------------------|
| `STRATAFS_MAGIC`      | `0x53545241` | Superblock magic, reported by `statfs` ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) |
| `STRATAFS_NAME`       | `"stratafs"` | The name the filesystem registers under         |
| `STRATAFS_MAX_STRATA` | `16`         | Longest stratum stack accepted ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>))         |

`STRATAFS_MAGIC` is an alias for `STRATAFS_SUPER_MAGIC`, which is
declared in the header stratafs shares with KACS so that the mount
policy class keyed on it cannot drift ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)).

<a id="trm-4-a-2"></a>

## Stratum flags

| Constant            | Value | Meaning                    |
|---------------------|-------|----------------------------|
| `STRATAFS_F_CREATE` | `0x1` | The `create` flag ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)) |
| `STRATAFS_F_RO`     | `0x2` | The `ro` flag              |
| `STRATAFS_F_AM`     | `0x4` | The `am` flag              |

<a id="trm-4-a-3"></a>

## Extended attributes

| Constant                 | Value                               | Meaning                                                  |
|--------------------------|-------------------------------------|----------------------------------------------------------|
| `STRATAFS_XATTR_PREFIX`  | `"system.stratafs."`                | Reserved namespace; never forwarded to a provider ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) |
| `STRATAFS_XATTR_ORIGIN`  | `"system.stratafs.origin"`          | Synthetic, read-only, hidden from listings ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>))        |
| `STRATAFS_XATTR_STAGING` | `"security.peios.stratafs_staging"` | Copy-up staging marker; also reserved ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>))           |

`STRATAFS_XATTR_STAGING` is an alias for `STRATAFS_STAGING_XATTR`,
declared in the shared header. Note the name it resolves to lies
outside the reserved `system.stratafs.` namespace, yet receives the
same treatment ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)).

The canonical security-descriptor attribute is KACS's, not
stratafs's; stratafs only detects it in order to exclude it from
copy-up replication ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)).

<a id="trm-4-a-4"></a>

## Copy-up and staging

| Constant                        | Value                | Meaning                                     |
|---------------------------------|----------------------|---------------------------------------------|
| `STRATAFS_STAGE_MARKER_MAGIC`   | `0x53544731`         | Marker magic                                |
| `STRATAFS_STAGE_MARKER_VERSION` | `1`                  | Marker version                              |
| `STRATAFS_COPY_BUFFER_SIZE`     | `65536`              | Copy-up read/write chunk, in bytes ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)) |
| `STRATAFS_STAGE_PREFIX`         | `".stratafs-stage-"` | Staged-name prefix                          |
| `STRATAFS_RECOVERY_BATCH`       | `128`                | Names scanned per staging-recovery pass     |

<a id="trm-4-a-4-1"></a>

### The staging marker <a id="cite-const.stage-marker-layout"></a>

`struct stratafs_stage_marker` is packed and 24 bytes, all fields
little-endian. It is the value of the staging attribute above.

| Offset | Size | Field          | Type     |
|--------|------|----------------|----------|
| 0      | 4    | `magic`        | `__le32` |
| 4      | 2    | `version`      | `__le16` |
| 6      | 2    | `size`         | `__le16` |
| 8      | 8    | `boot_cookie`  | `__le64` |
| 16     | 8    | `mount_cookie` | `__le64` |

<a id="trm-4-a-5"></a>

## Routing <a id="cite-const.route-discriminants-match-rust"></a>

The value `route_existing` returns ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), as the Rust decision
core names it and as the C glue mirrors it. The discriminants match.

| C enumerator               | Value | Rust       |
|----------------------------|-------|------------|
| `STRATAFS_ROUTE_IN_PLACE`  | `0`   | `InPlace`  |
| `STRATAFS_ROUTE_COPY_UP`   | `1`   | `CopyUp`   |
| `STRATAFS_ROUTE_READ_ONLY` | `2`   | `ReadOnly` |

<a id="trm-4-a-6"></a>

## The decision core

`stratafs-core` holds the stack-wide flag rules, provider selection,
and routing. Its flag bits match the C ones above exactly. <a id="cite-const.core-flag-bits-match-c"></a>

| Constant          | Value |
|-------------------|-------|
| `MAX_STRATA`      | `16`  |
| `FLAG_CREATE`     | `0x1` |
| `FLAG_READ_ONLY`  | `0x2` |
| `FLAG_ABSENT_MAY` | `0x4` |
| `FLAG_MASK`       | `0x7` |

The crate distinguishes these configuration errors. The C boundary
collapses all of them to `EINVAL`, so the distinction is not
observable to a caller ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)). <a id="cite-const.config-errors-collapse-to-einval"></a>

| Error            | Discriminant |
|------------------|--------------|
| `Empty`          | `1`          |
| `TooMany`        | `2`          |
| `UnknownFlag`    | `3`          |
| `RepeatedCreate` | `4`          |
| `CreateReadOnly` | `5`          |

<a id="trm-4-a-7"></a>

## Build configuration <a id="cite-const.build-kconfig-option"></a>

stratafs is built by `CONFIG_STRATAFS_FS`, a boolean option, so what it
builds is linked into `vmlinux` rather than loaded. It depends on
`CONFIG_SECURITY_PKM` and selects `FS_STACK`. Its sources are staged
into the kernel tree as `fs/stratafs`, separate from PKM's own
`security/pkm`. `CONFIG_STRATAFS_FS_TEST_HOOKS` compiles the test rendezvous and fail points ([Stratum flags](</kernel/internals/stratafs/start-here/generated-constants.md#trm-4-a-2>)),
inert unless the kernel is booted with `stratafs.test_hooks=1`. `CONFIG_STRATAFS_KUNIT_TEST` builds the in-kernel unit tests.

The translation units are:

- `super.o`
- `lookup.o`
- `inode.o`
- `file.o`
- `dir.o`
- `dir_cache.o`
- `xattr.o`
- `copy_up.o`

---

# Security

_Peios Kernel / Internals / StrataFS / Security_

> Find the Peios kernel articles about security.

Use these articles to understand security in the Peios kernel.

- [KACS admission and object phases](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md>)
- [Copy-up descriptors](</kernel/internals/stratafs/security/copy-up-descriptors.md>)
- [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md>)
- [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md>)
- [Mount Policy](</kernel/internals/stratafs/security/mount-policy.md>)
- [Audit](</kernel/internals/stratafs/security/audit.md>)

---

# KACS admission and object phases

_Peios Kernel / Internals / StrataFS / Security_

> KACS admission and object phases: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7"></a>

StrataFS copy-up is the internal realisation of an operation already
authorized against a StrataFS handle — not a second caller-requested
operation. KACS therefore provides a kernel-internal context so that
the mechanics of copy-up introduce no new rights checks against the
task that happens to execute them.

The context exempts **KACS caller authorization only**. It does not
replace credentials, borrow an identity, grant a privilege, bypass
another LSM, neutralise an underlying filesystem check, make a
read-only mount writable, or suppress immutable, append-only, quota,
space, I/O or format errors. <a id="cite-facs.stratafs-copy-up.exempts-kacs-only"></a> Every exemption is a return before the
authorize call, and every mutation still goes through the ordinary
`vfs_*` path under `mnt_want_write()`. <a id="cite-facs.stratafs-copy-up.mutations-via-vfs"></a>

<a id="trm-3-9-7-1"></a>

## Admission and lifetime

Only the in-kernel StrataFS implementation can create or enter a
context. There is no userspace surface of any kind — no ABI, file
descriptor, token, ioctl, syscall or securityfs control — and the
copy-up API is declared in a kernel-private header with no exported
symbols. <a id="cite-facs.stratafs-copy-up.no-userspace-surface"></a>

A context is created only after the StrataFS operation requiring
copy-up has passed its complete outer authorization. KACS does not
verify that: the context creation call performs no check, and the
ordering is satisfied by StrataFS calling in the right order. <a id="cite-facs.stratafs-copy-up.creation-performs-no-check"></a> The
context is not itself an alternative authorization path.

The exemption covers namespace creation the outer handle authorises
without an add-entry right on the create stratum, so the context is
reachable only from a create-enabled mount established by a caller
holding `CAP_SYS_ADMIN` in the **initial** user namespace. That
closure rests on an explicit test of the mounter's user namespace at
stack establishment — the capability half contributes nothing to it,
because the KACS switchboard discards the target namespace and answers
from `SeTcbPrivilege` alone ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)). The check is made when the
immutable stack is established rather than when a copy-up runs, so
descriptor delegation cannot reintroduce acting-task authorization.
Reconfiguration cannot re-supply the strata list.

A context attaches to at most one task, and a task carries at most
one. <a id="cite-facs.stratafs-copy-up.one-context-per-task"></a> It is not inherited by `fork()`, `clone()` or `execve()` — exec
explicitly clears it. <a id="cite-facs.stratafs-copy-up.not-inherited"></a> A refcounted context can be transferred to a
kernel worker, but the originating task leaves it first. <a id="cite-facs.stratafs-copy-up.worker-transfer"></a> Leaving,
task exit, every error path, and completion all remove the attachment
and clear any armed phase. <a id="cite-facs.stratafs-copy-up.detach-clears-phase"></a>

The interface fails closed on nesting, concurrent attachment, a stale
phase, or an object mismatch. <a id="cite-facs.stratafs-copy-up.fails-closed-on-misuse"></a> A mismatched operation is evaluated
normally and neither consumes nor broadens the armed exemption. <a id="cite-facs.stratafs-copy-up.mismatch-evaluated-normally"></a>

<a id="trm-3-9-7-2"></a>

## Object and phase binding

Creation pins the exact provider path, its current inode, a complete
validated copy of its effective descriptor, and the provider-visible
`security.capability` value or its absence. <a id="cite-facs.stratafs-copy-up.creation-pins-provider"></a> Every later positive path
is paired with a pinned inode as well — retaining a dentry alone is
insufficient, because an unlink followed by recreation can
reinstantiate it over a different inode. <a id="cite-facs.stratafs-copy-up.paths-paired-with-inode"></a>

One phase is armed at a time: <a id="cite-facs.stratafs-copy-up.one-phase-armed"></a>

| Phase | Objects admitted |
|---|---|
| Source read | The pinned provider only. |
| Create | One pinned provider, one destination parent, and either one named negative dentry or one anonymous creation in that parent. Used for both parent materialisation and the staged object. |
| Populate | The pinned provider and the one staged object bound to the context. |
| Publish by link | The bound staged object, one destination parent, one absent destination dentry. |
| Publish by rename | The bound staged object and its parent, one destination parent, one absent destination dentry. |
| Cleanup | One bound staging or materialisation dentry and its exact parent. |
| Orphan cleanup | One positive provider dentry carrying an authenticated stale staging marker, and its exact parent. |
| Orphan-marker cleanup | The exact positive provider dentry whose authenticated stale marker is being removed after publication. |

Path, dentry, inode, parent, object type and operation kind are all
compared wherever the hook supplies them — and path comparison
includes the mount, so the same dentry reached through a different
mount of the same superblock does not match. <a id="cite-facs.stratafs-copy-up.match-includes-mount"></a> An inode-only hook can
match the pinned inode, but that does not authorize a pathname
operation on another dentry, and a phase never acts as a wildcard for
other objects of the same filesystem or directory. <a id="cite-facs.stratafs-copy-up.no-wildcard-matching"></a>

The staged binding stays valid only while its dentry names the pinned
inode under the pinned staging parent, and that parent still names its
own pinned inode. A rename or parent substitution invalidates the
populate, protected-metadata and publish exemptions even when the
staged dentry and inode are themselves unchanged. <a id="cite-facs.stratafs-copy-up.rename-invalidates-binding"></a>

Named creation is bound to the exact final component. <a id="cite-facs.stratafs-copy-up.named-creation-exact-component"></a> Anonymous
creation is bound to its parent, expected object type, the attached
task, and the single armed create phase — and once created, the
anonymous object has to be bound as the staged object before populate,
publish or cleanup can use it. <a id="cite-facs.stratafs-copy-up.anonymous-must-be-bound"></a>

Where the destination is a stacking filesystem creating a real inode
below the armed destination dentry, the transition is authenticated at
the exact outer dentry, and only the one subsequent real-inode
security initialisation of the expected type receives the pinned
provider descriptor. <a id="cite-facs.stratafs-copy-up.stacking-transition-authenticated"></a> The real inode is not the staged binding: the
outer inode is separately anchored, through the matching post-create
event for an anonymous object or an explicit confirmation of the exact
positive outer dentry for a named one. A missing, repeated, mismatched
or out-of-order transition fails closed, and an inner post-create
event from the real filesystem is rejected as the outer anchor by
superblock comparison. <a id="cite-facs.stratafs-copy-up.transition-out-of-order-fails"></a>

KACS retains the exact path, inode, parent path and parent inode of
every named object whose creation it admits. Cleanup can be armed only
for one of those or for the exact bound staging object; an unrelated
positive dentry fails with `ESTALE`. <a id="cite-facs.stratafs-copy-up.cleanup-victim-restricted"></a> The cleanup setup call is not
itself authority to choose a deletion victim.

After an atomic rename or link publishes the staged inode, the staging
identity can be rebound to the published path, but only while mount,
inode, parent dentry and pinned parent inode all still match. <a id="cite-facs.stratafs-copy-up.rebind-conditions"></a> The
rebind API exists and is **not called** by StrataFS: the link case is
rebound internally by the publish path, and the rename case relies on
publish preserving the dentry. <a id="cite-facs.stratafs-copy-up.rebind-unused"></a> That holds because publication always
renames within a single parent. A cross-directory publish rename would
silently invalidate the staging binding, since the rename-publish
entry point does not require the destination parent to equal the
staging parent — currently unreachable, but the guard is the caller's
discipline rather than the interface's.

Named staging entries carry `security.peios.stratafs_staging`.
Caller-originated writes and removals of it are denied. <a id="cite-facs.stratafs-copy-up.staging-marker-writes-denied"></a> A write or
removal is admitted only on the exact bound staging inode during
populate, or on the exact orphan-marker object during authenticated
recovery — where the predicate admits a *write* as well as a removal,
being shared between the setxattr and removexattr hooks. <a id="cite-facs.stratafs-copy-up.staging-marker-admission"></a> Probing the
marker for recovery is a kernel-only raw read conveying no caller
authority, and orphan deletion is bound to the exact dentry, inode,
parent dentry and parent inode supplied when the phase was armed, so
an arbitrary name sharing the staging prefix never matches. <a id="cite-facs.stratafs-copy-up.orphan-deletion-exact-binding"></a> Recovery
processes at most 128 entries per batch.

<a id="trm-3-9-7-3"></a>

## Exempt operations <a id="cite-facs.stratafs-copy-up.exempt-operations"></a>

For a matching object in a matching phase, the ordinary AccessCheck,
cached-grant check, privilege check and caller-access audit decision
are omitted at these points:

| Copy-up action | Enforcement points |
|---|---|
| Open and read provider data or a symlink target | `security_inode_permission`, `security_file_open`, `security_file_permission`, `security_inode_readlink` |
| Read provider attributes and extended attributes | the inode and file getattr, setattr-preflight, getxattr and listxattr paths as applicable |
| Create a staged file, directory or symlink, and materialise parents | `security_inode_permission`, `security_inode_create`, `security_inode_mkdir`, `security_inode_symlink`, `security_inode_init_security`; for a stacking destination also `security_dentry_create_files_as` and, for an anonymous object, `security_inode_post_create_tmpfile` |
| Populate staged data, attributes and eligible non-descriptor xattrs | `security_inode_permission`, `security_file_open`, `security_file_permission`, the inode and file setattr paths, setxattr and removexattr. `security.capability` uses only the dedicated clone call below. |
| Publish | `security_inode_permission` on the exact staged object or destination parent, then `security_inode_link` or `security_inode_rename` |
| Remove staging or roll back materialised entries | `security_inode_permission` on the exact parent, then `security_inode_unlink` or `security_inode_rmdir` |

A `security_inode_permission` or `security_file_permission` match also
matches the requested mask. <a id="cite-facs.stratafs-copy-up.mask-must-match"></a> Provider access is
read-only — write, append and non-directory execute requests never
match it. <a id="cite-facs.stratafs-copy-up.provider-read-only"></a> Staging access is limited to the read, write and append
masks population needs, plus execute and chdir for directories, and
namespace parents to the write and traverse masks the one armed action
needs, plus open and chdir. <a id="cite-facs.stratafs-copy-up.staging-mask-limits"></a> Unknown mask bits fail closed. <a id="cite-facs.stratafs-copy-up.unknown-mask-fails-closed"></a>

The list is exhaustive. The context does not exempt execution, memory
mapping, ioctl, locking, arbitrary `fcntl`, device access, process
access, socket access, mount operations, or operations on a descriptor
installed into a userspace file table — each verified by the absence
of any copy-up branch on those paths. <a id="cite-facs.stratafs-copy-up.list-exhaustive"></a> Internal copy-up files are
additionally denied `statfs`, `truncate`, `fsync` and `fallocate`. <a id="cite-facs.stratafs-copy-up.internal-file-denied-ops"></a>

A file opened internally under the exemption is marked
copy-up-internal in its blob and carries a granted mask of zero. <a id="cite-facs.stratafs-copy-up.internal-file-zero-mask"></a> It is
usable without a cached caller grant only while the same context is
attached and its phase admits that exact file. Use after phase
completion, from another task, or after transfer through `SCM_RIGHTS`
fails closed. <a id="cite-facs.stratafs-copy-up.internal-file-scope"></a> Each armed phase has a distinct monotonically increasing
generation — overflowing it fails closed — and an internal file is
sealed to the generation it was opened in, so a later phase of the
same kind after a worker transfer cannot reactivate an older file. <a id="cite-facs.stratafs-copy-up.generation-seal"></a>
Final release drops the context reference.

The one exception is the read-only provider-directory cursor used by
bounded staging recovery. StrataFS may retain that file while it
leaves the context to clean one captured batch, then resume it after
re-entering the same context and arming a new source-read phase. Only
a directory file already marked internal for that exact context, still
naming the pinned provider path and inode, opened for read without
write, execute or path-only mode, and inside that attached
source-read phase, resumes; it is then resealed to the new generation. <a id="cite-facs.stratafs-copy-up.directory-cursor-resume"></a>
Between phases it is unusable and conveys no deletion authority.

<a id="trm-3-9-7-4"></a>

## Backing-file adoption <a id="cite-facs.stratafs-copy-up.backing-adoption"></a>

Before a regular-file copy is published, one exact copy-up-internal
backing file can become the backing file for the outer StrataFS open
description. The staging binding is verified, and the backing file's
recorded user path is confirmed to be that same outer description;
the outer description's immutable granted and continuous-audit
snapshot is then copied across and the internal marker removed. <a id="cite-facs.stratafs-copy-up.adoption-copies-snapshot"></a> This
is a transfer of authority already attached to the descriptor, not a
new AccessCheck against the task that caused the copy-up, which is
what preserves descriptor delegation when that task is not the opener.
It is one-shot, and requires the backing file mode. <a id="cite-facs.stratafs-copy-up.adoption-one-shot"></a>

StrataFS performs adoption after opening the staged file and **before**
publishing the anonymous staged object. KACS verifies the still-bound
staging object while the owned context has no armed phase.
<a id="cite-facs.stratafs-copy-up.adoption-before-publish"></a>

If the staged file belongs to OverlayFS, adoption also follows its exact
private backing files. Each child must be the parent's stored real file,
name that parent's upper object on its upper mount, and record the parent
as its user path. Matching a path alone does not establish this relationship.
The child must have an ordinary managed grant, no copy-up context or phase
generation, and no inherited backing grant.

KACS pins and validates the entire bounded chain before changing any file's
snapshot. A stale association, repeated file, or excessive depth rejects the
handoff without changing those snapshots. Once validation succeeds, every
admitted file receives the original outer description's granted and
continuous-audit masks in both security blobs. This preserves delegated
authority without consulting the task's credentials or weakening phase
precedence.

<a id="trm-3-9-7-7"></a>

## Auditing <a id="cite-facs.stratafs-copy-up.auditing"></a>

The outer authorized handle operation remains subject to ordinary
audit. No second caller AccessCheck or privilege-use audit is emitted
for an exempt internal sub-operation, since that would attribute
StrataFS mechanics to a caller decision that never happened — and
internal files carry a continuous-audit mask of zero, so they generate
no per-operation events either. <a id="cite-facs.stratafs-copy-up.no-second-audit"></a> The `CAP_SETFCAP` satisfaction path
returns before the capability check that would record privilege use.

StrataFS decides when its own copy-up lifecycle and failure events —
`stratafs.file.copied-up` and `stratafs.mutation.refused` ([Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>)) —
occur; KACS supplies the kernel-only emitter, so KMES stamps each
event with the effective token of the task whose operation caused it
([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)). Two of those emissions are best-effort: an allocation failure,
or an operation string that is empty or over 64 bytes, drops the event
silently. <a id="cite-facs.stratafs-copy-up.emission-best-effort"></a>

Denied mismatches, and operations performed with no active matching
context, follow the ordinary authorization and audit paths.

## Related explanations

- [Deferred deletion](</kernel/internals/stratafs/mutation/deferred-deletion.md>)
- [Copy-up descriptors](</kernel/internals/stratafs/security/copy-up-descriptors.md>)

---

# Copy-up descriptors

_Peios Kernel / Internals / StrataFS / Security_

> Copy-up descriptors: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7-6"></a>

## Exact protected-metadata cloning <a id="cite-facs.stratafs-copy-up.descriptor-cloning"></a>

KACS owns descriptor cloning rather than StrataFS raw-xattr code.
Before a create phase is armed, the provider's complete effective
descriptor is resolved and pinned using the ordinary mount-policy and
corrupt-descriptor rules ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). A missing, corrupt, unresolvable,
oversized or unsupported descriptor fails the phase before the
destination is created. <a id="cite-facs.stratafs-copy-up.unresolvable-descriptor-fails-phase"></a>

For a matching inode security initialisation, an exact byte-for-byte
copy of the pinned descriptor is installed instead of inheritance
running. <a id="cite-facs.stratafs-copy-up.exact-copy-not-inheritance"></a> The canonical xattr is installed as part of inode creation
and the inode's validated parsed cache is seeded from identical bytes
before the inode becomes usable. <a id="cite-facs.stratafs-copy-up.xattr-and-cache-seeded"></a> Failure to allocate, validate or
install either representation fails creation — there is no window in
which a named staging inode carries an inherited or otherwise weaker
descriptor. <a id="cite-facs.stratafs-copy-up.no-weak-window"></a>

On a stacking destination the same applies to the real inode created
below the outer dentry, with the authenticated outer transition as the
only authority to redirect installation there. The pinned bytes are
installed and cached during the real inode's creation, before the
outer object is confirmed or bound; inheriting the parent's descriptor
and repairing it afterwards would not be conforming. <a id="cite-facs.stratafs-copy-up.stacking-real-inode-install"></a>

The canonical descriptor is not copied by ordinary xattr enumeration —
it is reported as cancelled so a stacking filesystem discards it — and
raw canonical getxattr and setxattr stay denied even inside the
context, with the hook-side denial evaluated before any phase match. <a id="cite-facs.stratafs-copy-up.canonical-xattr-cancelled"></a>
The context does not override the unconditional denial of POSIX ACL
mutation either. <a id="cite-facs.stratafs-copy-up.posix-acl-still-denied"></a>

Raw setxattr, including through an internal copy-up file, remains
unable to install `security.capability`. <a id="cite-facs.stratafs-copy-up.raw-setcap-denied"></a> Where the provider has one,
StrataFS calls the dedicated clone entry point during populate, after
any operation that might clear file capabilities. That call accepts
only a kernel buffer exactly matching the pinned value, under the same
user namespace it was pinned in, for the still-bound staged inode. <a id="cite-facs.stratafs-copy-up.clone-call-preconditions"></a> It
re-reads the provider immediately before installing and fails with
`ESTALE` if the value or its presence changed. <a id="cite-facs.stratafs-copy-up.clone-estale-on-change"></a>

The call copies the caller's buffer before comparing, and installs
with `XATTR_CREATE` through the ordinary VFS path, so mount-idmap
conversion, xattr validation, filesystem permission and format checks
and other LSM checks all still apply. <a id="cite-facs.stratafs-copy-up.clone-through-vfs"></a> The otherwise-dead
`CAP_SETFCAP` gate is satisfied only synchronously inside that
validated call, and the corresponding setxattr re-entry is admitted
only after the first hook matches the exact staged inode. <a id="cite-facs.stratafs-copy-up.setfcap-synchronous-only"></a> The
capability answer targets only the pinned caller namespace or the
staged inode's filesystem namespace, and the condition is cleared on
every return. Nothing is installed when the provider had no attribute,
a different one, or an unreadable or invalid one. <a id="cite-facs.stratafs-copy-up.no-install-on-mismatch"></a> The exception does
not revive exec-time file-capability grants.

There is one asymmetry here: the removal path does not reject
`security.capability` the way the set path does, so an internal
copy-up descriptor can remove it from the staged object during
populate. <a id="cite-facs.stratafs-copy-up.removal-path-asymmetry"></a>

Other eligible provider xattrs follow StrataFS's replication rules
while KACS's caller checks on their source and staging objects are
exempted as above. An ineligible xattr that cannot be replicated
triggers StrataFS's ordinary copy-up failure rule rather than being
silently omitted.

<a id="trm-4-6-3"></a>

Copy-up produces a second instance of an existing object. Its security
descriptor is the source's — owner, group, discretionary list, system
list and integrity label alike — and it is KACS that carries it, not
stratafs. <a id="cite-security.copy-up-descriptor-preserved"></a>

<a id="trm-4-6-3-1"></a>

## How it is carried <a id="cite-security.copy-up-never-inherits-descriptor"></a>

When a copy-up context is created, the provider's complete effective
descriptor is resolved and pinned as a byte string on the context. Each
create phase copies those bytes into the phase, and the inode security
initialisation for the created object installs them verbatim instead of
running inheritance. Nothing is reconstructed field by field: it is a
copy of the source bytes, so all five components are preserved together.

The canonical descriptor attribute is deliberately excluded from
stratafs's own extended-attribute replication, precisely so that the
two mechanisms cannot disagree.

The separation inside KACS is clean and explicit. The inode security
initialisation takes the copy-up branch first, and taking it
short-circuits the inheritance builder entirely. Ordinary creation in a
create stratum inherits from its parent ([Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>)); copy-up preserves.
There is no path on which a copied-up object receives an inherited
descriptor.

<a id="trm-4-6-3-1-1"></a>

### Descriptors of materialised parents <a id="cite-security.materialised-parents-use-provider-descriptor"></a>

Directories materialised in the create stratum to hold a copied-up
object are handled the same way, each carrying the descriptor of the
corresponding **provider** directory — the merged provider of that same
relative path, which is what the pre-check of [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) evaluated against.

<a id="trm-4-6-3-2"></a>

## Failure <a id="cite-security.copy-up-descriptor-failure-fails-operation"></a>

Where the source descriptor cannot be replicated, the copy-up fails and
the operation that required it fails. A missing, corrupt, unresolvable,
oversized or unsupported descriptor fails the phase before the
destination is created, and an absent pinned descriptor at install time
fails the create.

<a id="trm-4-6-3-2-1"></a>

### Protection precedes publication <a id="cite-security.descriptor-installed-before-publication"></a>

Nothing publishes a copied-up object carrying any
other descriptor: the descriptor is installed at inode creation, before
any content, and publication is a link or rename of an object already
stamped, so there is no window in which a differently-protected object
is reachable.

The failure errno is not the specified one. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>)'s table pairs
descriptor failure with `EIO` alongside extended-attribute failure, and
the extended-attribute half does report `EIO`. The descriptor half is
carried by KACS, whose failures surface as `EACCES`, `EOPNOTSUPP`,
`EINVAL`, `ESTALE` or `ENOMEM`; there is no `EIO` anywhere on that
path. This is tracked as a defect.

<a id="trm-4-6-3-3"></a>

## Why preservation rather than inheritance

Copy-up is reachable by any caller with the right to modify the source
object. That right does not include the right to modify the source's
descriptor, which is a separate right.

Were a copied-up object to receive an inherited descriptor, a caller
holding only write access to a restrictively protected object could
cause a copy of it to exist carrying the create stratum directory's
inheritable entries — and that copy, having higher precedence, would
become what the merged path resolves to. The object's confinement would
have been replaced by the directory's, through an operation the caller
was entitled to perform, without their ever holding the right to alter
a descriptor.

Preserving the source descriptor closes that: a copy is exactly as
reachable as its original, and copy-up changes which stratum holds an
object without changing who may reach it.

<a id="trm-4-6-3-4"></a>

## Provenance <a id="cite-security.copy-up-descriptor-owner-is-source"></a>

Because the descriptor is preserved, the copy's descriptor-level owner
is the owner of the object it was copied from, not the caller who
caused the copy. Ownership therefore does not record who created the
copy and cannot be relied on to; the audit record of [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) is where
that is available.

Setting the copying caller as the descriptor owner would have preserved
provenance, and was rejected: an owner holds implicit rights over an
object's descriptor, so making the caller the owner would reintroduce
the escalation this section exists to prevent by a slightly longer
route.

The POSIX owner is preserved separately and for a different reason —
[Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>) covers the chown and [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md#trm-4-5-8>) what it means for accounting.

<a id="trm-4-6-3-5"></a>

## What "the source's descriptor" means <a id="cite-security.copy-up-pins-effective-descriptor"></a>

The descriptor pinned at the start of a copy-up is the provider's
**effective** descriptor rather than its raw stored attribute. On a
provider mount whose own policy class synthesises, that would be the
synthesised value. In practice that case is unreachable: reaching the
object through the stratafs mount at all requires a real descriptor,
under stratafs's own deny-missing class ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)). A provider on an
unmanaged mount is refused outright.

---

# Access Check Delegation

_Peios Kernel / Internals / StrataFS / Security_

> stratafs stores no descriptors and allocates its inodes bare — who performs which access check, and when.

<a id="trm-4-6-1"></a>

stratafs stores no security descriptors. It allocates its outer inodes
bare and never runs the inode security initialisation over them, and
neither its inode state nor its superblock state has anywhere to put a
descriptor. Every object reachable through a mount has its descriptor
on its own stratum, and that descriptor is what governs access to it. <a id="cite-security.descriptor-on-provider-stratum"></a>

<a id="trm-4-6-1-1"></a>

## The rule <a id="cite-security.check-evaluates-target-descriptor"></a>

An access check for an operation on an object reachable through a
stratafs mount evaluates the security descriptor of the object the
operation will be performed against. For an operation on a
non-directory, that is the provider's object; for a merged directory,
[Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) defines which participants' descriptors apply.

stratafs synthesises no descriptor, supplies none of its own, and
applies no mount-level template. It could not: constructing one would
require a synthesising mount policy class, and stratafs is pinned to
the class that denies where a descriptor is missing ([Mount Policy](</kernel/internals/stratafs/security/mount-policy.md#trm-4-6-4>)).

Because the descriptor evaluated is the provider's own, a stratafs
mount cannot grant access that the provider's stratum would refuse.
That property is structural rather than a matter of care in
implementation: there is no descriptor for stratafs to get wrong,
because it holds none.

The guarantee is one-directional, which is the direction that matters.
Where the provider carries no descriptor there is nothing to evaluate
and the mount's own policy decides, which is to refuse — so such an
object is unreachable through the mount even where its own filesystem's
policy would have admitted it.

<a id="trm-4-6-1-2"></a>

## Who performs which check <a id="cite-security.merged-checks-are-stratafs-own"></a>

For an object with a single provider, the descriptor comes back through
ordinary forwarding. KACS reads the canonical descriptor attribute the
same way it does for any file, the stacking layer forwards the
`getxattr` down to the provider, and the descriptor that comes back is
the provider's. For metadata and extended-attribute operations, stratafs
re-targets the pending one-shot KACS decision onto the provider inode,
so the check is made against the object the operation will reach.

A merged directory is not that case. It stands for several directories
with several descriptors, and forwarding yields only the provider's.
Those checks are **stratafs's own**: it walks every present
participating directory and evaluates each one's descriptor, failing on
the first refusal.

KACS cooperates by standing down on stratafs inodes entirely. Its
`inode_permission` hook, and its create, mkdir, mknod, symlink, link,
unlink, rmdir and rename hooks, all return success immediately for a
superblock carrying the stratafs magic. The checks that matter are made
by stratafs against the real objects, or by KACS against the real
objects once stratafs has resolved them.

<a id="trm-4-6-1-3"></a>

## Timing <a id="cite-security.open-grant-frozen"></a>

The descriptor evaluated is the provider's at the time the check runs,
and the open-time grant is frozen into the file's KACS state — the
check-at-open principle applies unchanged, and copy-up transfers that
immutable snapshot to the new backing file rather than deciding again.

For merged-directory checks, stratafs reads each participant's descriptor
attribute on every check. KACS also refreshes an outer stratafs inode's
parsed descriptor whenever a check or descriptor query needs it. A writer
using the stratum directly therefore needs no invalidation protocol with
the merged view. Missing and corrupt descriptors are re-read too, so a
subsequent repair can take effect.

This refresh applies to retained handles as well as new pathname operations.
An `O_PATH` handle performs its live access check against the refreshed
descriptor. An ordinary file handle retains its granted access, but a
permitted descriptor query returns the provider's current descriptor, not
the one present when the file opened.

When copy-up rebinds a file's inode to the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), stratafs explicitly
invalidates the parsed descriptor. Subsequent descriptor queries follow the
new provider. The file's frozen grant remains unchanged; invalidating the
inode cache does not authorise or revoke access on an already-open file.

---

# Checks on Merged Directories

_Peios Kernel / Internals / StrataFS / Security_

> An operation on a merged directory is checked against every participating directory — including where the create stratum's directory does not exist.

<a id="trm-4-6-2"></a>

A merged directory stands for several real directories, each with its
own security descriptor. An operation on one is checked against every
participating directory whose contents it depends on, and against the
directory it modifies. Where more than one applies, **all** must
succeed: the check walks participants in order and returns on the first
refusal, and nothing degrades an operation to the subset of strata the
caller may reach.

Two composite rights recur:

- **Search** — traverse on every participating directory, since every
  one is searched to resolve a name. The permission hook maps the
  kernel's execute intent onto it. <a id="cite-security.merged-search-right"></a>
- **Enumerate** — Search plus list on every participating directory.
  The permission hook maps the read intent onto the list right, and
  directory open demands both together. <a id="cite-security.merged-enumerate-right"></a>

| Operation | Checked against |
|---|---|
| Resolving a name | Search <a id="cite-security.rights.resolve"></a> |
| Enumerating | Enumerate, before the listing is captured <a id="cite-security.rights.enumerate"></a> |
| Reading an object's attributes | Search, plus whatever the object's own descriptor requires <a id="cite-security.rights.read-attributes"></a> |
| Reading the origin attribute on a merged directory | Search, plus read-EA on **every** participant ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) <a id="cite-security.rights.read-origin"></a> |
| Creating a name | Search, plus add-file or add-subdirectory on the **create stratum's** directory <a id="cite-security.rights.create"></a> |
| Copy-up | Nothing beyond what the operation it serves already required <a id="cite-security.rights.copy-up"></a> |
| Removing a name | Search, plus delete-child on the **provider's** directory <a id="cite-security.rights.remove"></a> |
| Removing a directory | Enumerate — emptiness is judged across every participant — plus delete-child on the provider's directory <a id="cite-security.rights.rmdir"></a> |
| Rename, source | Search, plus delete-child on the source **provider's** directory <a id="cite-security.rights.rename-source"></a> |
| Rename, destination | Search, plus add-entry on the source provider's directory, which [Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>) requires to hold the destination, plus delete-child where that directory already holds the name <a id="cite-security.rights.rename-destination"></a> |
| Rename of a directory | Both of the above, plus Enumerate on the object being renamed, and Enumerate on the destination where its provider is a directory <a id="cite-security.rights.rename-directory"></a> |
| `RENAME_EXCHANGE` | Search on both, plus add-entry and delete-child on the directory of the stratum providing both names <a id="cite-security.rights.rename-exchange"></a> |
| Link | Search on both, plus add-file on the source provider's directory <a id="cite-security.rights.link"></a> |
| Creating or linking an unnamed file | Search, plus add-file on the **create stratum's** directory <a id="cite-security.rights.unnamed-file"></a> |

The mutating rights land on the directory that actually changes, which
follows from [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>): an entry appears in the create stratum's directory
and disappears from the provider's, so in each case it is that
directory's descriptor that decides. The two coincide whenever the
create stratum is also the provider. <a id="cite-security.mutating-right-on-modified-directory"></a>

One right the table does not name is required anyway: the underlying
`vfs_link` makes KACS demand write-attributes on the **source object**,
which is an object-descriptor right outside the directory scope this
section covers. <a id="cite-security.link-requires-write-attributes-on-source"></a> Linking an unnamed file is exempt, since stratafs marks
the source for that purpose. <a id="cite-security.unnamed-link-exempt-from-source-check"></a>

The effective rights on a merged directory are therefore the
intersection of the rights on its participants, with mutating rights
additionally required on the directory that is actually modified.
Requiring the intersection is fail-closed and admits no partial
results: the alternative would let the names held by a restrictively
protected directory be enumerated by a caller who could not enumerate
it directly, because a permissive directory of higher precedence
happened to provide the merged path.

One consequence is worth stating plainly. Because creation is governed
by the create stratum's directory descriptor, and a created name
shadows the same name in every lower stratum, the right to create in
the create stratum's directory is the right to determine what every
lower stratum's entry of that name resolves to.

<a id="trm-4-6-2-1"></a>

## Where the create stratum's directory does not exist <a id="cite-security.create-check-falls-back-to-provider-directory"></a>

A merged directory has a create stratum whether or not that
subdirectory exists ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)), so a check naming "the create stratum's
directory" has to be evaluated against a directory that is not there
yet.

Every such check is performed before any part of the operation is
carried out, and in particular before any directory is materialised:
the authorisation call strictly precedes parent materialisation in
creation, in tmpfile creation, and in the unnamed-link path. Where the
checks fail, nothing has been created, so the create stratum is left
exactly as it was.

Where the create stratum does not hold the path, the check falls back
to the **corresponding provider directory** — the merged provider of
that same relative path — which is the descriptor the directory will
carry once materialised ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)). It is never skipped, and never
substituted with an ancestor's descriptor. Where no provider exists
either, the result is `EROFS`.

Materialising the intervening directories is part of the operation, not
a separate one. No per-ancestor authorisation is taken; the mkdirs are
exempted by the copy-up context. Checking against the descriptor the
directory will have keeps the answer independent of how much of the
create stratum happens to have been materialised already: the first
caller to write into a deep path and the hundredth face the same check,
against the same descriptor.

A create that fails *after* materialisation for a reason other than a
check — `EEXIST`, `ENOSPC` — does leave the intervening directories in
place.

<a id="trm-4-6-2-2"></a>

## Copy-up carries no separate authority <a id="cite-security.copy-up-requires-no-extra-right"></a>

A copy-up requires no right beyond those the operation that provoked it
already required. In particular it does not require the caller to hold
the right to read the provider's object, nor the right to add an entry
to the create stratum's directory. Neither copy-up path takes any
authorisation at all.

Copy-up is the mechanism by which an authorised modification is
realised, not an operation a caller requests. The read of the provider
is stratafs's own, and the copy carries the source's descriptor
unchanged ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so the caller obtains nothing they did not already
have: the same content, under the same descriptor, at the same path.

The alternative cannot be expressed. Routing happens when a
modification is performed ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), and by then the authority that
governed the open is a mask cached on the descriptor, immutable and
carrying no token — so there is nothing to evaluate a fresh right
against. Checking the *acting* token instead would break descriptor
delegation, since a descriptor passed to another process would stop
working there.

What remains is a resource consideration rather than an access one: a
caller entitled to write a file in a stratum that will not accept
modification can cause an entry to appear in the create stratum without
holding rights over that directory. They gain neither access nor space
by it: [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md#trm-4-5-8>) records that the copy is accounted to the preserved owner
rather than to them.

That exemption is only enforceable because KACS provides a copy-up
context; without it the access-control layer would check the caller
against the create stratum's directory at exactly the point where the
authority to check no longer exists. [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>) describes the context, its
phase binding and its exhaustive list of exempt operations. What
matters here is what stratafs must hold up its end of: the context
exempts caller authorisation only, so every mutation still goes through
the ordinary VFS path under write access on the target mount, a
read-only filesystem still refuses, and filesystem errors still
propagate. Nothing is performed under a borrowed or elevated identity —
every copy-up mutation runs with the calling task's own credentials.

<a id="trm-4-6-2-2-1"></a>

### Recovery retains the mounter’s file credentials <a id="cite-security.staging-recovery-uses-mounter"></a>

The stale-staging recovery scan passes the **mounter's** credentials
to the internal directory open, which retains them as the file’s
credentials. That does not switch the calling task’s current
credentials or select a different KACS token. The scan runs in a
source-read copy-up context bound to that exact directory, so the
context admits its read before an ordinary token access check.

Consequently, neither the caller nor the mounter needs a directory-list
grant for that scoped recovery read. An ordinary open requesting list
access remains subject to the directory’s descriptor. Path resolution
separately uses the captured mounter credentials; the file-credential
argument is not itself an authority switch.

---

# Mount Policy

_Peios Kernel / Internals / StrataFS / Security_

> Every stratafs mount carries the FACS policy class that denies access to an object with no readable descriptor, and what follows from that.

<a id="trm-4-6-4"></a>

A stratafs mount carries the FACS mount policy class that denies access
to an object with no readable security descriptor. The class is derived
from the filesystem magic, not from an administrative choice: the
policy resolver maps the stratafs magic to the deny-missing class, and
falls back to that mapping whenever a cached policy value is not one of
the valid ones. <a id="cite-security.mount-policy-is-deny-missing"></a>

<a id="trm-4-6-4-1"></a>

## Policy changes are refused before validation <a id="cite-security.mount-policy-cannot-be-set"></a>

It cannot be set to anything else. The set path rejects a superblock
carrying the stratafs magic with `EOPNOTSUPP` **before** it validates
its arguments or checks privilege, and there is no mount option to
choose one — stratafs's parameter table holds exactly one entry, and
anything else is refused. Reading a mount's policy is itself privileged,
requiring TCB privilege, though for stratafs the answer is fixed.

Two classes are excluded for distinct reasons.

**The unmanaged class** declares that FACS does not apply to a mount and
that the kernel governs it by rules particular to that filesystem.
stratafs has no such rules: it delegates every decision to the provider
([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)). An unmanaged stratafs mount would therefore have no access
control at all — not delegated control, but none — for every object
reachable through it. That is not theoretical: enforcement points
consult the mount policy of the superblock an object belongs to before
performing their check, and treat an unmanaged mount as requiring none.
For a mount established over a directory of executables, that would
place every program on the system beyond the execute check.

**The synthesising classes** would have stratafs supply a descriptor of
its own for an object whose provider has none. Either consequence is
disqualifying: the mount would grant access to an object that is
unreachable through its own stratum, falsifying the guarantee the whole
of [Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>) rests on; and the class that persists a synthesised descriptor
would write it back onto the provider's object, which stratafs may not
do to any stratum and certainly not to one carrying `ro`.

<a id="trm-4-6-4-2"></a>

## Missing descriptors <a id="cite-security.missing-descriptor-denied"></a>

Where a provider object has no descriptor, access through the stratafs
mount is denied under the mount's own policy, and the provider
filesystem's policy is not consulted. Both paths implement this:
stratafs's own merged-directory check turns `ENODATA` or `EOPNOTSUPP`
straight into `EACCES` rather than asking the provider's superblock to
synthesise, and an object open resolves the missing-descriptor policy
against the **stratafs** superblock, yielding a missing-descriptor
cache entry and then `EACCES`.

<a id="trm-4-6-4-2-1"></a>

### Corrupt is not missing <a id="cite-security.corrupt-descriptor-does-not-use-mount-policy"></a>

A descriptor that is present but cannot be interpreted is a distinct
case and is not routed to mount policy. It takes the ordinary
corrupt-descriptor outcome: a corrupt cache entry and an emitted event
on the open path, and a validation failure on the merged-directory
path. The two produce the same errno by different routes, and mount
policy is consulted in neither.

<a id="trm-4-6-4-3"></a>

## Consequence <a id="cite-security.merge-never-widens-access"></a>

A stratafs mount is uniform in the sense a mount policy requires: every
object reached through it is subject to the same policy, which is the
mount's own. What varies between objects is the descriptor evaluated,
which is a property of the object rather than of the policy.

Because the policy denies where a descriptor is absent, the divergence
from direct access is always in the refusing direction. An object with
no descriptor on a stratum whose own filesystem would synthesise one is
refused through the stratafs mount while remaining reachable through
its stratum path. An object reachable through its stratum path is never
made *more* reachable by being merged. The same holds for a stratum on
an unmanaged filesystem, whose objects carry no descriptors at all:
merging one is permitted but yields nothing readable, and is not a
useful arrangement.

---

# Audit

_Peios Kernel / Internals / StrataFS / Security_

> The two stratafs events recorded because the information cannot be recovered afterwards — plus two gaps and what is not audited at all.

<a id="trm-4-6-5"></a>

Two classes of stratafs event carry information that cannot be
recovered from the filesystem afterwards, and are recorded when they
happen. Both are emitted through KACS's kernel-only emitter, so KMES
stamps each with the effective token of the task whose operation caused
it. <a id="cite-audit.events-stamped-with-effective-token"></a>

<a id="trm-4-6-5-1"></a>

## Copy-up <a id="cite-audit.copy-up-always-emitted"></a>

Every copy-up emits a `stratafs.file.copied-up` record, successful or
not. Its payload carries these fields, each a path of nested maps:

| Field | |
|---|---|
| `object.file.path-relative` | The relative path within the mount, `/`-prefixed |
| `source.stratum.index` | The stratum the object was copied from |
| `source.stratum.path` | That stratum's path |
| `destination.stratum.index` | The stratum it was copied into |
| `destination.stratum.path` | That stratum's path |
| `outcome.success` | Whether the copy-up succeeded |
| `outcome.errno` | The failure, as a negative errno; absent on success |

The caller's identity is not in this payload. It does not need to be:
KMES stamps the effective, true and process token GUIDs onto every event
header at ring-write time, and because copy-up runs in the caller's own
context those are the caller's. The identity is carried in the
**envelope**, once, for every event — duplicating it into the payload
would give a reader a second copy that could disagree with the first.

Recording it matters because [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>) preserves the source's descriptor,
so nothing about the resulting object records who caused it to exist.
A reader of these records must take the identity from the event header,
not look for it among the fields.

The `ENOTDIR` of parent materialisation is reported through this event
in its `outcome.errno` rather than through the refusal event below;
the required fields are all present, under a different event type.

<a id="trm-4-6-5-2"></a>

## Refused mutation <a id="cite-audit.arrangement-refusal-emitted"></a>

A mutation refused because of how the mount is arranged emits a
`stratafs.mutation.refused` record carrying the relative path
(`object.file.path-relative`), the operation (`operation.name`), the
providing stratum (`source.stratum.index` and `source.stratum.path`),
the error (`outcome.errno`, negative) and whether the refusal was
deferred (`outcome.deferred`). The `source.stratum` fields are present
only where a provider is known; see below.

What counts as an arrangement refusal is one explicit list — `EROFS`,
`EXDEV`, `ENOTDIR`, `EISDIR`, `ENOTEMPTY`, `EEXIST`, `EINVAL`. Call
sites cover
every mutating path: writes, mappings, truncation, `fallocate`, splice,
`copy_file_range`, `remap_file_range`, `setattr`, `setxattr` and
`removexattr`, creation, tmpfile, unlink and rmdir, link, supersede,
and rename.

`EACCES` is deliberately absent from that list. A refusal produced by an
access check is audited by the mechanism that performed it, and
stratafs does not duplicate those records.

These refusals report a mismatch between what a caller attempted and
how the mount is arranged — software writing where it cannot, or an
arrangement that does not admit an operation someone expected. That is
diagnostic information about the system's configuration, and it is
otherwise visible only as an error returned to a caller that may
discard it.

Rollbacks are audited under the same event with the deferred flag set:
a create or link whose outer bookkeeping failed and whose lower object
could not be removed again, and a failed publication rollback after a
copy-up.

A refusal raised before a provider is known — creation, tmpfile, the
heads of link and rename — has no stratum to name. Its record has no
`source` map at all: `source.stratum.index` and `source.stratum.path`
are both absent, never `-1`, nil or an empty string, so a reader can
tell "no provider was involved" from "the provider's path is empty".

<a id="trm-4-6-5-2-1"></a>

### One exception <a id="cite-audit.deferred-deletion-audited-on-any-error"></a>

A refused **deferred deletion** is audited on *any* non-zero result, not
only the arrangement errors, so one refused by an access check does get
a stratafs record. That is the right resolution of the two rules, since
the requirement to audit a deferred deletion is unconditional — nobody
is left to receive the error — but it is a deliberate exception to the
`EACCES` exclusion above.

The record is stratafs's whether or not stratafs was entered. The
delete-child check on the merged parent runs before `->unlink`, so a
directory whose descriptor tightened between the arm and the close
refuses the deletion before the filesystem sees it; KACS then raises
the stratafs record itself, with no `source.stratum` fields, since no
stratum was consulted.

<a id="trm-4-6-5-3"></a>

## What is not audited <a id="cite-audit.lookup-not-audited"></a>

Resolution, revalidation and enumeration emit no records of their own.
They occur on every path operation, they reveal nothing the resulting
access check does not, and recording them would produce volume out of
all proportion to their significance. There is no audit call anywhere
in the lookup path.

Access checks performed against provider objects are audited by KACS,
under its own rules.

---

# Mutation

_Peios Kernel / Internals / StrataFS / Mutation_

> Find the Peios kernel articles about mutation.

Use these articles to understand mutation in the Peios kernel.

- [Deferred deletion](</kernel/internals/stratafs/mutation/deferred-deletion.md>)
- [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md>)
- [Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md>)
- [Creation](</kernel/internals/stratafs/mutation/creation.md>)
- [Removal](</kernel/internals/stratafs/mutation/removal.md>)
- [Rename](</kernel/internals/stratafs/mutation/rename.md>)
- [Links](</kernel/internals/stratafs/mutation/links.md>)
- [Locking](</kernel/internals/stratafs/mutation/locking.md>)
- [Durability and Accounting](</kernel/internals/stratafs/mutation/durability-and-accounting.md>)

---

# Deferred deletion

_Peios Kernel / Internals / StrataFS / Mutation_

> Deferred deletion: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-7-5"></a>

## Deferred deletion <a id="cite-facs.stratafs-copy-up.deferred-deletion"></a>

A delete-pending mark is authorized when it is set, and the setting
open's token is recorded with it ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-3>)). At the
last close there is no re-authorization against the closing task. <a id="cite-facs.stratafs-copy-up.close-no-reauth"></a> Instead a synchronous, non-nesting internal
deletion scope is armed for the outer path the marking open named, captured
when the mark was set, and StrataFS binds
it once to the exact provider parent, dentry and inode selected from
the descriptor's settled provider. <a id="cite-facs.stratafs-copy-up.deletion-scope-binding"></a> Only the corresponding outer and
lower unlink calls match, and the scope is cleared on every return.

The mechanism never turns an ordinary close into deletion authority,
never admits a different provider entry, and never permits unlinking
an entry that no longer names the descriptor's inode. <a id="cite-facs.stratafs-copy-up.deletion-identity-check"></a> If the original
entry has disappeared or changed identity, the deletion is already
complete and no exemption is used.

<a id="trm-4-5-3-3"></a>

## Deferred deletion <a id="cite-create.deferred-delete-targets-resolved-object"></a>

A request to delete an object when the last descriptor to it is closed
applies to the object the descriptor resolved to, not to whatever
provides that name at close time. Because removal ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)) is defined
over the current provider of a name, the deferred case has its own
path.

<a id="trm-4-5-3-3-1"></a>

### An entry already gone <a id="cite-create.deferred-delete-already-gone-succeeds"></a>

When the deletion is attempted, stratafs locates the entry at the path
the descriptor was opened against, in the stratum that provided it at
that time — the descriptor's private dentry carries both — and resolves
the parent in that same stratum. Four conditions end the attempt
quietly, reporting success because the deletion is already complete:
the parent is gone, the name is gone, the name now identifies a
different inode, or the unlink raced.

The merged parent can disappear or become a non-directory before the
VFS reaches stratafs’s unlink handler. An `ENOENT` or `ENOTDIR` from
that earlier check is also a successful no-op, but only after a lookup
in the descriptor’s original providing stratum confirms that its
recorded name is absent or identifies a different inode. A higher
stratum masking a still-live backing target does not satisfy that
condition: the deletion still fails and is audited. Other errors keep
their ordinary failure and audit behavior.

<a id="trm-4-5-3-3-2"></a>

### The original stratum must accept removal <a id="cite-create.deferred-delete-requires-writable-stratum"></a>

That stratum must accept modification, or the deletion fails with
`EROFS`. Then the entry is removed, and no other. In particular, where
another caller's copy-up has published a new object at that name in a
higher stratum, that object is not the one being deleted and is left
alone.

<a id="trm-4-5-3-3-3"></a>

### Failures are audited <a id="cite-create.deferred-delete-audits-failure"></a>

Because the attempt has no caller to report to, any failure is audited
— and for a deferred deletion, *every* non-zero result is audited, not
only the arrangement errors [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) covers for ordinary refusals. The
object is left in place.

<a id="trm-4-5-3-3-4"></a>

### Authority at deletion time <a id="cite-create.deferred-delete-checked-against-the-providing-stratum"></a>

The right to delete the entry is checked against the directory of the
**stratum where the entry lives**, not against the merged parent, and
it is checked at deletion time rather than only at arm.

Arm time could not do it. The authorizer there holds a `struct file`,
and which stratum provides the entry is stratafs-internal — the
provider index and the parent's relative path are not visible to KACS.
stratafs computes that directory before removing anything, so the check
happens there, where the answer exists.

<a id="trm-4-5-3-3-5"></a>

### The requesting token outlives the arm <a id="cite-create.deferred-delete-token-outlives-the-arm"></a>

The token is the one that requested the deferred deletion, not the
credentials of whoever closes the descriptor. That requires it to
outlive the arm: the file's blob takes a reference when armed and
releases it in `->file_release`, on both the armed and unarmed exits.
The file is the thing that was armed, so its lifetime is the right
one — arm and close may be far apart and in different tasks.

<a id="trm-4-5-3-3-6"></a>

### Supported object types <a id="cite-create.deferred-delete-non-directories"></a>

Deferred deletion is restricted to non-directories, and at arm time to
regular files on a managed mount.

## Related explanations

- [Creation](</kernel/internals/stratafs/mutation/creation.md>)

---

# Write Routing

_Peios Kernel / Internals / StrataFS / Mutation_

> Which single stratum a modification is performed against, when that decision is made, and what shared writable mappings do to it.

<a id="trm-4-5-1"></a>

An operation that modifies an existing object is performed against
exactly one stratum. This section covers which, and when the decision
is made.

<a id="trm-4-5-1-1"></a>

## Accepting modification <a id="cite-write.accepts-modification"></a>

A stratum **accepts modification** of an object it provides when all
three of the following hold:

- the stratum does not carry `ro`;
- the provider's mount is not read-only;
- the provider's inode is not marked immutable.

<a id="trm-4-5-1-1-1"></a>

### Independence from the caller’s rights <a id="cite-write.routing-does-not-use-caller-rights"></a>

The predicate is a property of the stratum and the object alone. It
takes the superblock, the stratum index and the provider path, and
nothing else — no credentials, no security descriptor, no access
check.

That restriction is load-bearing. Were the predicate to take the
caller's rights into account, a caller *refused* write access by the
provider's descriptor could still provoke a copy-up: the write would
fail, but the copy would have been published, and from then on the
merged path would resolve to a snapshot the provider's legitimate
writer could no longer update. A caller with no write access at all
could freeze any file in the mount.

Note the third term is the immutable inode flag specifically, not
unwritability in general. A file that is unwritable by its mode bits is
routed in place and refused by the underlying filesystem.

<a id="trm-4-5-1-2"></a>

## The rule

The decision itself is `route_existing` in `stratafs-core`, which takes
the provider index, whether it accepts modification, the create index
and whether the create stratum is present, whether the object is of a
copyable type, and whether the stratafs mount itself is read-only. It
selects in-place modification, copy-up, or read-only through the following
ordered checks.

1. If the **mount** is read-only, the route is read-only. This term
   short-circuits everything else. <a id="cite-write.read-only-mount-short-circuits"></a>
2. If the provider accepts modification, the operation is performed
   against the provider's object. <a id="cite-write.in-place-when-provider-accepts"></a>
3. Otherwise, if the object is copyable, a create stratum exists, is
   present, and has **strictly higher precedence than the provider**,
   the object is copied up and the operation performed against the
   copy. <a id="cite-write.copy-up-when-create-outranks"></a>
4. Otherwise the route is read-only and the operation fails with
   `EROFS`. <a id="cite-write.erofs-when-no-writable-stratum"></a>

The strict `create_index < provider` comparison is what stops a
modification being placed where something already present would shadow
it. Where a high-precedence stratum provides a name it will not accept
a write for, there is no lower stratum that can take the write without
the result vanishing behind the provider, so `EROFS` is the honest
answer — reported at the moment of the write rather than discovered
later.

Where the name is held by no stratum, the operation is a creation and
[Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) applies instead.

<a id="trm-4-5-1-3"></a>

## When the decision is made

Routing happens as part of a modifying operation, not an ordinary open.
Most mutating entry points call `route_existing` afresh against their
selected provider. Shared write-capable mappings prepare the route before
the memory mapping lock is taken and recheck the selected provider in the
mapping callback. Opening a descriptor does not reserve a writable route.
<a id="cite-write.routed-per-operation"></a>

| Operation | Routes |
|---|---|
| Writing or appending | Yes <a id="cite-write.routes.write"></a> |
| Truncating, or any other `setattr` | Yes <a id="cite-write.routes.setattr"></a> |
| Changing mode, owner, timestamps, or the security descriptor | Yes <a id="cite-write.routes.metadata"></a> |
| Setting or removing an extended attribute | Yes <a id="cite-write.routes.xattr"></a> |
| `fallocate` | Yes <a id="cite-write.routes.fallocate"></a> |
| `splice` into the file | Yes <a id="cite-write.routes.splice"></a> |
| `copy_file_range` and `remap_file_range` | Yes <a id="cite-write.routes.copy-range"></a> |
| Establishing a shared writable mapping | Yes <a id="cite-write.routes.shared-mapping"></a> |
| Reading contents, attributes, or extended attributes | No <a id="cite-write.routes.read-does-not"></a> |
| Opening, for any access | No <a id="cite-write.routes.open-does-not"></a> |
| Taking or releasing a lock, or a lease | No <a id="cite-write.routes.lock-does-not"></a> |

The security descriptor and the system access control list are both
reached as extended attributes, so both route through the `setxattr`
path like any other attribute; there is no descriptor-specific code in
stratafs at all. <a id="cite-write.descriptor-routes-as-xattr"></a>

An open is not itself a routing trigger. `open` computes a route, but
uses it only to decide the flags of the backing open — a non-in-place
route downgrades the provider open to read-only and strips `O_TRUNC`,
deferring rather than deciding. <a id="cite-write.open-defers-routing"></a> The one case in which an open acts is
`O_TRUNC` on a regular file: that is a modification, so it routes, and
copies up or fails with `EROFS` there and then. The truncation itself
is applied afterwards by the VFS through `setattr`, which routes again
and lands on the copy. <a id="cite-write.o-trunc-routes-at-open"></a>

Writes to regular files use the open file description's current
`O_APPEND` setting, including changes made with `F_SETFL` after open or
copy-up. Clearing the flag restores writes at the selected offset and
allows `splice` and range-copy operations to use their explicit offsets.
The provider's append-only restrictions and flag checks still apply.

Routing at operation time rather than at open is what makes the rule
implementable. A filesystem cannot see what an open asked for in
access-mask terms — the caller's descriptor is stamped by KACS before
the filesystem's own open method runs, and its mask lives in a private
blob a filesystem cannot reach. Nor does it need to: the access check
has already happened by the time an operation reaches stratafs, so a
modifying operation arriving here is one its caller was entitled to
perform, and routing it is a decision about strata alone.

<a id="trm-4-5-1-4"></a>

## Shared writable mappings <a id="cite-write.mmap-routes-on-maywrite"></a>

Establishing a shared mapping that can become writable routes before any
bytes are written. Stores through the mapping can then modify its backing
object without another filesystem operation that could perform copy-up.

Preparation applies to regular files mapped with `MAP_SHARED` or
`MAP_SHARED_VALIDATE` through a readable, writable open file description.
This includes `PROT_READ`: the shared mapping retains `VM_MAYWRITE` and can
later gain write access through `mprotect`. Private mappings and shared
mappings that cannot gain write access do not trigger preparation.
Ordinary writable opens remain lazy; opening alone does not copy up a file.

The existing KACS mapping checks run before preparation. Preparation
follows direct StrataFS providers and the selected backing file of FUSE
passthrough mappings. It completes routing and any required copy-up for
each StrataFS layer before the VFS acquires `mmap_lock`. It grants no
additional access, and the backing file's mapping checks still apply.

The mapping callback pins the selected provider and forwards only an
in-place route. If a route change after preparation could require another
copy-up, the mapping fails with `EAGAIN`. Retry the whole `mmap`
call so that preparation runs again. Definitive read-only conditions still
fail with `EROFS`.

A completed copy-up remains published if a later mapping check or provider
callback fails. The same applies if an earlier layer completes copy-up
before preparation fails in a deeper layer. Preparation does not roll back
copies that another operation could already have observed.

<a id="trm-4-5-1-5"></a>

## What a copy-up does to an open descriptor <a id="cite-write.copying-descriptor-follows-copy"></a>

A copy-up performed for one descriptor changes which object provides
the name. That descriptor refers to the copy from then on: it keeps the
inode it was opened against while the inode's backing object becomes
the copy ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), and its backing file is replaced.

Every other descriptor already open against the original continues to
refer to the original, and any fresh resolution of the path yields a
new inode standing for the copy. The pre-copy-up file is not closed —
it is retained so that locks and leases taken before the copy-up keep
working ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)).

<a id="trm-4-5-1-6"></a>

## Special files <a id="cite-write.special-files-never-copied-up"></a>

A FIFO, socket, or device node is opened and written without the
filesystem object being modified: what is written passes to a pipe, a
socket, or a driver, not to the object's contents. Writing to such an
object therefore does not route, and such an object is never copied up
— every routing site gates on the object being a regular file, and the
copyable flag excludes anything that is not a regular file, directory
or symlink.

Copying up a FIFO would sever it: a reader holding the original and a
writer that arrived after the copy would hold two unrelated pipes. A
device node survives copying only by the accident that the copy names
the same device.

Opens, reads and writes are forwarded to the provider whether or not it
accepts modification, since the write-mode downgrade and the `O_TRUNC`
refusal both apply to regular files only. Operations that modify the
object itself — its mode, its descriptor, its extended attributes — do
route, and where the provider does not accept modification they fail
with `EROFS`, because the copy-up branch cannot apply to an object that
is never copied up.

<a id="trm-4-5-1-7"></a>

## `ioctl` <a id="cite-write.ioctl-regular-file-refused"></a>

`ioctl` on a regular file is refused unconditionally with `ENOTTY`, and
its compat form with `ENOIOCTLCMD`. Stored-file `ioctl`s can mutate
data and would need command-by-command routing, which is not
implemented; refusing is the conservative stand-in. `ioctl` on a
non-regular file is forwarded to the provider.

---

# Copy-Up

_Peios Kernel / Internals / StrataFS / Mutation_

> Replicating an object from its provider into the create stratum — parents, what is replicated, staging and atomicity.

<a id="trm-4-5-2"></a>

Copy-up replicates an object from its provider stratum into the create
stratum, at the same path relative to the mount root, so that a
modification can be applied without modifying the provider. <a id="cite-copy-up.replicates-into-create-stratum"></a>

Every step runs inside a KACS copy-up context, which exempts the
mechanics from caller authorisation without granting anything. [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)
describes that context in full; [Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>) covers the stratafs side of the
bargain.

<a id="trm-4-5-2-1"></a>

## Parents <a id="cite-copy-up.materialises-missing-parents"></a>

Where the create stratum does not hold the directories containing the
object's path, they are created first, walking the relative path
component by component from the create-stratum root downwards. Each is
created as an empty directory with the mode of the corresponding
**merged provider** directory, and with that directory's security
descriptor, installed by KACS during the create phase rather than
inherited.

Contents are not copied. The directories exist to hold the copied
object; the entries they hold in lower strata continue to be reached by
merging.

Where the create stratum holds one of those components as something
other than a directory, the copy-up fails with `ENOTDIR` and the
operation requiring it fails. The blocking entry is not removed or
replaced — there is no `unlink`, `rmdir` or `rename` anywhere on the
parent-materialisation path.

Materialised parents receive a mode and a descriptor, and nothing else:
no extended attributes and no timestamp preservation.

<a id="trm-4-5-2-2"></a>

## What is replicated

| Provider type | Result in the create stratum |
|---|---|
| Regular file | A regular file with the same contents and mode <a id="cite-copy-up.result.regular-file"></a> |
| Symbolic link | A symbolic link with the same target <a id="cite-copy-up.result.symlink"></a> |
| Directory | An empty directory with the same mode; contents are not copied <a id="cite-copy-up.result.directory"></a> |

A device node, FIFO, or socket is never copied up. Anything that is not
a regular file, directory or symlink is refused with `EROFS` before a
copy-up begins. <a id="cite-copy-up.non-copyable-refused"></a>

The security descriptor is carried by KACS rather than replicated as an
attribute ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)). Every other extended attribute is copied, with
three exclusions: the canonical descriptor attribute, anything in the
`system.stratafs.` namespace, and the staging marker attribute. Each
is copied with `XATTR_CREATE`, and `security.capability` goes through a
dedicated KACS entry point rather than a raw write. <a id="cite-copy-up.xattrs-copied-with-exclusions"></a>

No attribute is silently discarded. Any per-attribute failure aborts
the copy-up, as does a listing that fails or exceeds `XATTR_LIST_MAX`;
in every case the error reported is `EIO`, whatever the underlying one
was. <a id="cite-copy-up.xattr-failure-aborts-with-eio"></a>

Modification timestamps are preserved for every type, symbolic links
included. <a id="cite-copy-up.mtime-preserved"></a> The mode is carried across too, except for a symbolic
link, whose mode is fixed by the VFS and not the caller's to set. <a id="cite-copy-up.mode-preserved-except-symlinks"></a>
Access and change times are not preserved for any type. <a id="cite-copy-up.atime-ctime-not-preserved"></a>

**Ownership is preserved.** The staged object is created with the
calling task's credentials, so it begins owned by the caller; where
that differs from the source's uid or gid, a second `notify_change`
sets both to the source's. <a id="cite-copy-up.posix-ownership-preserved"></a> The KACS security descriptor, including
its owner SID, is preserved as well ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so both notions of owner
name the object's owner rather than whoever provoked the copy.

The chown runs under the **mount's own credential** — the same
resolution context stratafs uses to reach providers the caller cannot
([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)) — because setting another uid needs authority the caller does
not have. <a id="cite-copy-up.ownership-chown-runs-under-resolution-credential"></a> It is a separate change from the mode and timestamp
above, which are the caller's to set and stay that way.

Because disk quota keys on the POSIX owner, a copy is accounted to the
owner of the object it was copied from and not to the caller. <a id="cite-copy-up.accounted-to-preserved-owner"></a> That is
what makes [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)'s exemption sound: a caller who may write a file in a
stratum that will not accept modification can cause an entry to appear
in the create stratum without holding rights over it, gaining neither
access nor space.

Hard links are not preserved: an object with several links in its
stratum is copied up as a single independent object, and the other
links continue to refer to the original. <a id="cite-copy-up.hard-links-not-preserved"></a>

Contents are copied through a 64 KiB buffer, one read and one write per
iteration, with the inner write loop retrying short writes. Where the
copy-up was provoked by a path rather than a descriptor, the source is
reopened for each chunk; the staged file is reopened for each chunk
either way.

<a id="trm-4-5-2-3"></a>

## The source must still be the provider <a id="cite-copy-up.source-must-still-be-provider"></a>

Before beginning a copy-up on behalf of a descriptor, the object the
descriptor refers to is verified still to be the provider of that name,
comparing both the path and the provider inode. Where it is not, the
copy-up is not performed and the operation fails with `ESTALE`.

The verification is repeated immediately before publication, under the
create directory's lock, and publication itself uses an operation that
fails if the target name already exists: linking an anonymous object
into place, or a `RENAME_NOREPLACE`. Both additionally test the target
dentry explicitly, and an `EEXIST` from either is normalised to
`ESTALE`.

That is decisive for the case that matters. A competing copy-up
publishes into the same create-stratum directory, where the
filesystem's own atomicity applies, so exactly one of two racing
copy-ups succeeds and the other fails `ESTALE`.

It cannot extend further, and nothing tries to. Strata may be on
different filesystems, and stratafs can neither lock them together nor
inspect them at one instant. A change in some *other* stratum after the
second verification — a direct writer creating the name in a
higher-precedence stratum, say — is an ordinary concurrent structural
change, visible to the next resolution, and is neither an error nor
detected.

This is not a rare case. Every descriptor other than the one that
caused a copy-up still refers to the original object, so a second
descriptor opened before the copy-up meets this rule the first time it
writes. A caller therefore has to be prepared for a write to fail
`ESTALE` on a descriptor that was valid when it was opened and has done
nothing wrong. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records it.

<a id="trm-4-5-2-4"></a>

## Staging and atomicity <a id="cite-copy-up.never-partially-observable"></a>

A copy-up is never observable in a partial state. All content,
attribute and metadata work happens on an object that is not reachable
through the mount, and publication is a single step.

Two arrangements are used, chosen by type:

- A **regular file** is staged as an anonymous object on the create
  stratum's filesystem — a kernel tmpfile — and linked into place when
  complete. No reader can reach it.
- A **directory or symlink** is staged under a name in the create
  stratum, since neither has an anonymous form, and published by a
  no-replace rename.

A staged name is `.stratafs-stage-` followed by the mount cookie and a
per-stage identifier, in a 64-byte buffer, with up to eight retries on
collision. It is excluded from resolution and from enumeration for the
mount that owns it, and removed if the copy-up fails. The exclusion is
local: a second stratafs mount sharing the create stratum, and every
direct reader of that directory, sees an ordinary entry containing a
partial copy.

<a id="trm-4-5-2-4-1"></a>

### Identifying staging entries <a id="cite-copy-up.orphan-recovery-checks-marker"></a>

A staged name alone is not proof of ownership, so each staged object
also carries a marker in the extended attribute
`security.peios.stratafs_staging`. The marker is a 24-byte
little-endian structure: a magic of `0x53544731` — ASCII `STG1` — a
version, its own size, a per-boot cookie, and the cookie of the mount
that created it.

Recovery of an orphan is therefore precise. A staged entry whose marker
is valid and whose owning mount is not live is removed; one belonging to
a live mount is left alone, and so is one whose marker is missing,
short, or carries the wrong magic, version or size. That matters
because two mounts may share a create stratum, and an unqualified
cleanup would have each new mount destroy the other's copy-up in
flight.

The scan runs in batches of 128 names, with resume, and is triggered
from five places: mounting, opening a directory, looking up a name
beginning with the staging prefix, copying up into a directory, and the
emptiness test of [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) before it scans the create stratum's participating
directory, after the caller's traverse/list access has been checked.

The fifth exists because the other four only reach directories somebody
visits. An orphan in a directory that is never opened, looked up, or
copied into would otherwise block `rmdir`: a dead mount's stages are not
in the current mount's in-flight list and would be counted as ordinary
entries. Recovery before that scan reaches the affected directory
without recursively visiting every directory at mount time. It also
means the create directory is scanned for recovery when its merged
emptiness is tested, even if it ultimately proves nonempty.

The marker is removed after publication. A failure to remove it is only
warned about, leaving the marker on the published copy until a later
lookup cleans it.

<a id="trm-4-5-2-5"></a>

## Failed copy-up and rollback <a id="cite-copy-up.failure-leaves-no-entry"></a>

Where a copy-up fails for any reason, the create stratum is left with
no new entry at the target path and the operation fails. Nothing falls
back to a weaker replication: an object whose descriptor or extended
attributes could not be preserved is never published. A published copy
whose descriptor handoff then fails is rolled back.

<a id="trm-4-5-2-6"></a>

## Concurrent modification <a id="cite-copy-up.no-source-snapshot"></a>

The provider may be modified while it is being copied, by a writer that
does not know stratafs exists.

Copy-up reads the provider as any reader would, with no locking of the
source and no snapshot, and offers no stronger consistency than an
ordinary read of that object. Where the provider is modified during the
copy, the copy may contain bytes from more than one state of the
source, exactly as a concurrent `read` of the same object may.

Nothing detects that and restarts — there is no retry loop, no
generation check. Equally, nothing blocks waiting for a quiescent
source, and nothing fails a copy-up merely because the source is being
written.

What *is* guaranteed is that the published object never appears in a
partial state, because staging and publication are properties of the
create stratum's filesystem, which stratafs does control.

<a id="trm-4-5-2-6-1"></a>

### Independence after publication <a id="cite-copy-up.published-copy-independent"></a>

Once published, the copy is independent of its source. Subsequent
modifications to the object it was copied from are not reflected in it,
and are not visible through the mount for as long as the copy provides
the name.

---

# Creation

_Peios Kernel / Internals / StrataFS / Mutation_

> Creation: behaviour and implementation of the Peios kernel.

<a id="trm-4-5-3"></a>

Creating a name held by no participating stratum places it in the
create stratum. <a id="cite-create.lands-in-create-stratum"></a>

1. If there is no create stratum, or it is absent, the operation fails
   with `EROFS`. <a id="cite-create.erofs-without-create-stratum"></a>
2. Any directories of the create stratum containing the name's path
   that do not exist are materialised as [Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>) requires for copy-up
   parents. Where the create stratum holds one of those components as
   something other than a directory, the operation fails with
   `ENOTDIR`; the blocking entry is not removed or replaced. <a id="cite-create.parent-conflict-enotdir"></a>
3. The name is created there.

All six kinds of creation — regular file, directory, symbolic link,
device node, FIFO, socket — go through one helper and one path.

The `ENOTDIR` case arises because creation routes positionally, into
the create stratum's subdirectory at the same path whether or not it
exists ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)). Where the create stratum holds that path as a file,
and a higher-precedence stratum provides it as a directory, the merged
directory exists and is reachable while its create-stratum counterpart
is blocked.

<a id="trm-4-5-3-1"></a>

## The security descriptor <a id="cite-create.descriptor-inherited-from-parent"></a>

A created object has no provider to inherit from, so its descriptor is
established by the ordinary creation semantics of the create stratum's
filesystem — by inheritance from the directory it is created in,
exactly as if it had been created there directly. The create is an
ordinary `vfs_create`, `vfs_mkdir`, `vfs_symlink` or `vfs_mknod`
against the real create-stratum parent, with the KACS creation decision
bound to that same parent.

This is cleanly separated from copy-up inside KACS: the copy-up branch
of the inode security initialisation is taken first and short-circuits
the inheritance builder entirely. Ordinary creation in a create stratum
inherits; copy-up preserves.

Where the creating interface lets the caller supply a descriptor — the
native open path does — it is honoured rather than replaced by an
inherited one. That is entirely KACS's doing; stratafs has no
descriptor parameter and cannot express it. All stratafs contributes is
re-anchoring the pending native create request onto the create-stratum
parent.

<a id="trm-4-5-3-2"></a>

## Dispositions that delete <a id="cite-create.supersede-is-removal-then-creation"></a>

A creating interface may offer a disposition that replaces an existing
object rather than opening it. In Peios that is the supersede
disposition of the native open path: KACS creates a temporary file
through the mount, opens it, and renames it onto the target, at which
point stratafs diverts the rename into a dedicated supersede path.

Such a disposition requires both removal and creation authority. This
does not prescribe their publication order. Before anything is created,
the removal is validated: the
target's provider must accept modification, or the operation fails with
`EROFS`. Before anything is removed, the replacement is checked for
reachability: if any stratum strictly above the create stratum, other
than the provider being removed, holds the name, the operation fails
with `EROFS`.

Without that guard the disposition could report success while leaving
the caller's new object invisible. The removal takes the name out of
the stratum that provided it; the creation puts the replacement in the
create stratum; and if some stratum between the two also holds the
name, it now outranks the replacement.

The creation half is treated as a creation throughout. It is never
reclassified as a modification of a newly-surfaced provider and never
copies one up: the caller asked for a new object, and its descriptor is
derived as above.

<a id="trm-4-5-3-2-1"></a>

### Implementation restrictions

Three restrictions are implementation choices rather than consequences
of the model:

1. Supersede applies to regular files only, and anything else is refused
   with `EOPNOTSUPP`. <a id="cite-create.supersede-regular-files-only"></a>
2. The source must be in the create stratum, and source and destination
   must share a parent. <a id="cite-create.supersede-source-and-parent-restrictions"></a>
3. Across distinct strata the two halves are **not** atomic. The staged
   file is renamed into place in the create stratum **before** the old
   provider is unlinked. Between those operations both backing names
   exist: ordinary precedence selects the replacement if the create
   stratum is higher, or retains the original until its removal if it is
   higher. A failure to publish leaves the original untouched, rather
   than exposing a still-lower provider. <a id="cite-create.supersede-is-not-atomic"></a>

   Write access to the original provider is probed before publication,
   then released while the replacement is published. It is reacquired
   for removal; a provider remounted read-only in between therefore fails
   with `EROFS` after publication. The two backing mounts never have
   simultaneous freeze-protection holds, even when they share a superblock.

   A later removal failure is returned to the caller and recorded as
   `supersede-removal`. Native-open cleanup then attempts to remove the
   newly published object, following its final name rather than its old
   temporary name. If the original still has its name, successful
   cleanup restores its visibility; concurrent provider changes are
   preserved. Cleanup is itself a filesystem operation and can fail;
   in that case both entries can remain, with ordinary precedence
   deciding which is visible. A crash between publication and removal
   can likewise leave both. This ordering narrows the destructive
   failure window; it does not promise a transaction or crash recovery.

   When both objects are in the create stratum, replacement uses one
   backing-filesystem rename and needs no separate provider unlink.

<a id="trm-4-5-3-4"></a>

## Exclusive creation <a id="cite-create.exclusive-eexist-from-any-stratum"></a>

Where creation is requested exclusively, the name must not exist in
**any** participating stratum, and a name provided by a lower stratum
causes `EEXIST` even though the create stratum does not hold it.

Nothing in stratafs implements this, and nothing needs to. The merged
lookup instantiates a positive dentry whenever any stratum holds the
name, and the VFS refuses `O_EXCL` on a dentry it did not create. The
`excl` argument stratafs receives is ignored. There is a race backstop
in the create path — a positive dentry appearing in the create stratum
yields `EEXIST` — but it sees only that one stratum.

Exclusive creation asks whether the name is free, and through this
mount it is not: a caller that created it anyway would find their
object shadowing a file they did not know was there, or masking a whole
subtree.

<a id="trm-4-5-3-5"></a>

## Non-exclusive creation over a shadowed name <a id="cite-create.shadowed-non-exclusive-is-open"></a>

Where creation is not exclusive and a lower stratum provides the name,
the merged dentry is positive, so the VFS never calls the create path
at all. The operation is an open, and [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>) routes it.

Where the provider is a regular file that does not accept modification
and the create stratum has higher precedence, the result is a copy-up
followed by the requested modification, including truncation where
`O_TRUNC` was requested. `O_TRUNC` is stripped from the backing open on
a non-in-place route precisely so that the copy-up source is not
destroyed before it is read.

Where the provider is a FIFO, socket, or device node, no copy-up occurs
and the open is forwarded to the provider. Such an open succeeds
whether or not the provider accepts modification: opening a special
file does not modify it.

<a id="trm-4-5-3-6"></a>

## Unnamed files <a id="cite-create.unnamed-file-in-create-stratum"></a>

A file may be created without a name, for later linking into place. In
a merged directory this is supported, and the file is created on the
create stratum's filesystem, recorded with the create stratum's index
and marked unnamed.

Where the mount has no create stratum, or it is absent, the operation
fails with `EROFS`. Parent materialisation applies as for a named
creation: the create stratum's counterpart of the directory the
operation named is materialised, and the new file's descriptor is
derived by inheritance from it, because that directory is what the
descriptor must come from. Linking such a file into the mount is
governed by [Links](</kernel/internals/stratafs/mutation/links.md#trm-4-5-6>).

---

# Removal

_Peios Kernel / Internals / StrataFS / Mutation_

> stratafs has no whiteouts, so removal can only remove an entry that is really there — and what removal therefore never does.

<a id="trm-4-5-4"></a>

stratafs has no whiteouts and cannot record that a name should be
absent. Removal can therefore only remove an entry that is actually
there, in a stratum it may write to.

<a id="trm-4-5-4-1"></a>

## Unlinking <a id="cite-remove.unlink-in-provider"></a>

To remove a non-directory name from a merged directory: if the provider
accepts modification ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)), the entry is removed from the provider;
otherwise the operation fails with `EROFS`. The parent is resolved in
the provider's stratum, and the unlink is performed there.

The provider need not be the create stratum. Any stratum that accepts
modification may have an entry removed from it, by the same rule that
allows an object it provides to be modified in place.

Where a lower-precedence stratum also holds the name, that entry
becomes the provider once the higher one is removed, and the name
remains visible, now resolving to the lower stratum's object. That is
not an error and is not reported as one: the removal succeeded, and the
entry it removed is gone. The dentry is dropped on success, so the next
lookup finds the lower entry.

Removing an object that a lower stratum also provides is how a
modification is undone. Where a file was copied up in order to be
edited, removing it through the mount discards the edit and restores
the original, which remained untouched in its own stratum throughout.
Callers expecting POSIX removal will find the name still present
afterwards; [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records this as an intended divergence.

Refusal because the provider does not accept modification is `EROFS`,
with one exception: where the provider's inode is immutable it is
`EPERM`. The outer inode carries the provider's inode flags, so the VFS
refuses the removal before stratafs's own `EROFS` test is reached — and
`EPERM` is what every filesystem returns for an immutable file, so the
distinction is the useful one rather than an accident worth papering
over. The `ro` flag and a read-only provider mount both still produce
`EROFS`.

<a id="trm-4-5-4-2"></a>

## Removing directories <a id="cite-remove.rmdir-merged-emptiness"></a>

The same rule applies, with one additional condition: the **merged**
directory must be empty. A directory is empty for this purpose only if
no participating stratum holds any entry within it, so a directory that
is empty in the provider but not in another participant fails with
`ENOTEMPTY`.

<a id="trm-4-5-4-2-1"></a>

### Access checks precede the emptiness scan <a id="cite-remove.access-before-emptiness"></a>

Because determining this reads the contents of every participating
stratum, the caller must hold traverse and list rights on each of them.
That check completes over all participants before any of them is
enumerated, so a refusal yields `EACCES` without disclosing whether the
directory was empty. Without that ordering the emptiness test would be
a disclosure channel: a caller who may not enumerate a protected
participant could learn whether it contains anything by attempting
`rmdir` and distinguishing `ENOTEMPTY` from success.

The emptiness scan filters this mount's in-flight staging entries, as
enumeration does. That does not authorise removing a live stage: the
provider can still refuse the physical removal with `ENOTEMPTY`.

<a id="trm-4-5-4-2-2"></a>

### Orphan recovery before inspection <a id="cite-remove.rmdir-staging-recovery"></a>

After the traverse/list checks complete, the emptiness test runs orphan
recovery on the create stratum's participating directory **before**
enumerating its contents ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)). A dead mount's entries are not in the
current mount's in-flight list, so waiting until that list has filtered
them would reject the directory before recovery could run. A directory
containing only recoverable orphan files or empty orphan directories can
therefore be removed without first opening or listing it.

Recovery requires the staging prefix, a valid marker, and an owner that
is no longer live. Missing or malformed markers, ordinary published
names, and stages belonging to a live mount remain untouched; they can
still make removal fail with `ENOTEMPTY`. The scan is local to the
participating create directory, not a recursive walk of the stratum.

Where the directory is removed and lower strata hold the same name as a
directory, the name remains visible as a merged directory of the
remaining strata — which, by the emptiness condition, is empty.

<a id="trm-4-5-4-3"></a>

## What removal never does <a id="cite-remove.touches-only-the-provider"></a>

Removal touches exactly one stratum, the provider's. The other strata
are opened read-only for the emptiness scan and nothing else. No entry,
marker, or object is created in any stratum to suppress a lower entry;
no whiteout machinery exists anywhere in the filesystem.

Success is never reported for a name whose provider entry was not
removed. The one place zero is returned without a removal is the
deferred path of [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>), where the entry the descriptor named is
already gone and the deletion is genuinely complete.

---

# Rename

_Peios Kernel / Internals / StrataFS / Mutation_

> Rename both removes and creates, so the source is bound by the removal constraint — atomic replacement, flags and RENAME_NOREPLACE ordering.

<a id="trm-4-5-5"></a>

Rename both removes a name and creates one. Because stratafs cannot
make a name disappear ([Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>)), the constraint on the source is the
same as for removal, and the constraint on the destination follows from
the read-after-write direction of [Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>).

For a rename of a source to a destination within one mount, letting `P`
be the source's provider:

1. `P` must accept modification. Otherwise `EROFS` — the source cannot
   be removed, so the rename would leave it still visible and amount to
   a copy. <a id="cite-rename.source-provider-must-be-writable"></a>
2. The destination must not be provided by a stratum of **higher**
   precedence than `P`. Otherwise `EROFS` — the renamed object would be
   shadowed at its destination and unreadable through the path it was
   renamed to. <a id="cite-rename.destination-not-higher-precedence"></a>
3. `P` must hold the directory containing the destination. Otherwise
   `EXDEV`. That directory is not created to satisfy the condition,
   whether or not `P` is the create stratum: parent materialisation
   exists to receive a copy-up, and a rename is not one. <a id="cite-rename.destination-parent-in-provider"></a>
4. Where the source is a directory, the merged directory must contain
   no entries provided by a stratum other than `P`. Otherwise `EXDEV`,
   since those entries cannot move with it. Determining this reads
   every participating stratum, so traverse and list rights are
   required on each, checked before any enumeration begins; where that
   is refused the rename fails with `EACCES` without disclosing whether
   other strata contributed. <a id="cite-rename.directory-source-must-not-strand-entries"></a>
5. Where the destination is provided, its type must match the source's.
   A non-directory onto a directory provider fails with `EISDIR`; a
   directory onto anything else fails with `ENOTDIR`. Only the
   provider's type is compared, since a lower stratum's entry of a
   different type is masked and contributes no inode. <a id="cite-rename.destination-type-must-match"></a>
6. Where the destination's provider is a directory, that merged
   directory must contain no entries at all — the same merged-emptiness
   test `rmdir` uses, with the same access requirement. Otherwise
   `ENOTEMPTY`. <a id="cite-rename.destination-directory-must-be-empty"></a>
7. The rename is performed within `P`: both parents are resolved at the
   provider's index, and a single `vfs_rename` is issued there. <a id="cite-rename.performed-within-the-provider"></a>

Where the destination is provided by a stratum of lower precedence than
`P` and both are non-directories, the rename succeeds and the renamed
object shadows it. Where the destination is held by `P` itself, it is
replaced, as on any filesystem. <a id="cite-rename.lower-destination-is-shadowed"></a>

Where the renamed object and the destination are both directories, the
result is not a shadowing: by [Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>) the renamed directory merges with
the lower strata's directories of that name. <a id="cite-rename.directory-destination-merges"></a> Condition 6 is what keeps
that tolerable — those directories are empty, so the merged result is
the renamed directory's own contents.

`P` need not be the create stratum. A rename is performed in whichever
stratum provides the source, provided that stratum accepts
modification. A rename whose source and destination are in different
mounts fails with `EXDEV`, refused by the VFS before stratafs is
consulted, and stratafs additionally refuses one spanning two mounts
inside the provider stratum. <a id="cite-rename.cross-mount-exdev"></a>

The immutable-provider caveat of [Removal](</kernel/internals/stratafs/mutation/removal.md#trm-4-5-4>) applies to condition 1 as well:
an immutable source yields `EPERM` from the VFS rather than `EROFS`. <a id="cite-rename.immutable-source-eperm"></a>

<a id="trm-4-5-5-1"></a>

## Replacing atomically <a id="cite-rename.replace-is-atomic"></a>

A rename onto an existing destination is the operation by which most
software replaces a file safely, and it works through a stratafs mount
for a destination provided by a lower stratum. That case is permitted
by condition 2: the destination is shadowed by the renamed object
rather than removed, so no whiteout is required, and the replacement is
a single `vfs_rename` within one directory pair of one stratum — atomic
on the filesystem holding `P`.

Where the source of such a rename is a temporary file the caller
created in the same directory, [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) placed it in the create stratum,
which never carries `ro`. Conditions 1 and 3 are then satisfied.

The contrast with the supersede disposition ([Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>)) is worth noticing:
that spans two strata and is not atomic.

<a id="trm-4-5-5-2"></a>

## Flags

Conditions 1 and 4 concern whether the source can be moved at all, and
apply under every flag. Conditions 2, 3, 5 and 6 concern the
destination.

| Flag | Behaviour |
|---|---|
| `RENAME_NOREPLACE` | The destination must not be held by **any** participating stratum, not merely by `P`. Conditions 2, 5 and 6 are not evaluated, since each presupposes a destination that exists; where any stratum holds the destination the rename fails with `EEXIST`. <a id="cite-rename.noreplace-checks-every-stratum"></a> |
| `RENAME_EXCHANGE` | Both names must be provided by the **same** stratum, and that stratum must accept modification; otherwise `EROFS`. Conditions 1 and 4 apply to both names. Conditions 2, 5 and 6 are not evaluated: an exchange swaps two names that both already exist, so neither type matching nor emptiness is required of either, exactly as on any filesystem. Condition 3 is subsumed. Where either name is a directory, no stratum other than the providing one may hold entries under either name; otherwise `EXDEV`. <a id="cite-rename.exchange-needs-one-stratum"></a> |
| `RENAME_WHITEOUT` | Fails with `EINVAL`, checked before everything else. stratafs has no whiteouts and cannot represent one. <a id="cite-rename.whiteout-flag-einval"></a> |

Exempting `RENAME_EXCHANGE` from conditions 5 and 6 is what leaves the
flag usable. Its ordinary purpose is to swap two populated directories
atomically, which condition 6 would refuse outright and condition 5
would refuse whenever the two differ in type. The stranded-entries
condition is the only destination constraint an exchange genuinely
needs, because it is the only one that arises from the names spanning
strata rather than from what the names hold.

<a id="trm-4-5-5-2-1"></a>

### The `RENAME_NOREPLACE` ordering <a id="cite-rename.noreplace-eexist-takes-precedence"></a>

A `RENAME_NOREPLACE` whose destination is held by any participating
stratum fails with `EEXIST`, and that `EEXIST` takes precedence over
conditions 1, 3 and 4. It is not stratafs that decides this. For
`RENAME_NOREPLACE` the VFS looks the destination up with `LOOKUP_EXCL`
and returns `EEXIST` for a positive dentry before `vfs_rename` runs at
all, and stratafs's merged lookup makes the dentry positive whenever any
stratum holds the name. `namei.c` is unpatched, so there is no point
inside `->rename` from which the order could be changed.

stratafs nonetheless evaluates conditions 1, 3 and 4 first, and the code
says so. That ordering is reachable only as a race backstop — where the
destination appeared between the VFS lookup and the rename — so a caller
should not expect `EROFS`, `EXDEV` or `EACCES` from a `RENAME_NOREPLACE`
whose destination already existed.

<a id="trm-4-5-5-3"></a>

## Other behaviour

Unknown `flags` bits are neither rejected nor masked; they pass through
to the VFS. <a id="cite-rename.unknown-flags-pass-through"></a> Where the two provider-level names resolve to one inode the
rename is a no-op returning success. <a id="cite-rename.same-inode-is-a-noop"></a> A dentry whose private state is
missing, or whose provider identity no longer matches, yields `ESTALE`. <a id="cite-rename.stale-dentry-estale"></a>
That refusal is per attempt, and the VFS heals it: `ESTALE` from a
rename makes the syscall retry once with a fresh walk, whose rebuilt
dentry carries the current provider identity, so the caller usually
observes the retry's outcome — a rename of the object now at the name —
rather than the errno. The refusal itself is recorded at the
`stratafs:stratafs_rename_stale` tracepoint, with the walk-time and
found inode numbers.
Because the filesystem sets `FS_RENAME_DOES_D_MOVE`, stratafs performs
the `d_move` or `d_exchange` itself, together with swapping the
dentries' recorded relative paths.

---

# Links

_Peios Kernel / Internals / StrataFS / Mutation_

> Hard links within one mount, linking an unnamed file, and how symbolic links are created.

<a id="trm-4-5-6"></a>

<a id="trm-4-5-6-1"></a>

## Hard links

To create a hard link from an existing name to a new name within one
mount, letting `P` be the source's provider:

1. `P` must accept modification. Otherwise `EXDEV`. <a id="cite-link.source-provider-must-be-writable"></a>
2. The destination must not be held by any participating stratum.
   Otherwise `EEXIST`. <a id="cite-link.destination-must-not-be-held"></a>
3. `P` must hold the directory containing the destination. Otherwise
   `EXDEV`. That directory is not created to satisfy the condition,
   whether or not `P` is the create stratum. <a id="cite-link.destination-parent-in-provider"></a>
4. The link is created in `P`. <a id="cite-link.created-in-the-provider"></a>

`P` need not be the create stratum: a link is made in whichever stratum
provides the source, since that is the only stratum in which the two
names can share an object. Condition 2 ensures the new link is not
shadowed at its destination, since no stratum — above `P` or below it —
holds that name.

Condition 2 is enforced by the VFS rather than by stratafs for a named
source: the link path looks the destination up with `LOOKUP_EXCL`, and
stratafs's merged lookup makes the dentry positive whenever any stratum
holds the name. stratafs's own test covers only the provider stratum
and is a race backstop. For an unnamed source it does check every
stratum explicitly.

A link request is never satisfied by copying the source up. <a id="cite-link.never-copies-up"></a> The result
would be a link to the copy rather than to the object named by the
source, so the two names would not share an object — which is the whole
of what a hard link is for. Refusing is the only correct answer.

`EXDEV` is used rather than `EROFS` because it is the error callers
already handle when a link cannot be made between two locations, and
because it is accurate: the link would have to span two strata, which
through this mount are two filesystems.

Where installing the outer inode fails after the lower link succeeded,
the link is rolled back; a failed rollback is audited. <a id="cite-link.rolled-back-on-install-failure"></a>

<a id="trm-4-5-6-2"></a>

## Linking an unnamed file <a id="cite-link.unnamed-goes-to-create-stratum"></a>

An unnamed file created under [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) is linked into the mount by the
rules for creation, not by those above: it has no provider, so
conditions 1 and 3 have no subject.

The link is created in the create stratum — a source recorded with any
other index is refused with `EXDEV` — and the operation follows [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>):
the name must not be held by any participating stratum, parent
directories are materialised in the create stratum, and a create
stratum that is absent or does not exist fails with `EROFS`.

<a id="trm-4-5-6-2-1"></a>

### Unnamed files cannot cross mounts <a id="cite-link.unnamed-cross-mount-exdev"></a>

Linking an unnamed file into a different mount fails with `EXDEV`,
checked both by superblock and by mount, and by the VFS as well.

<a id="trm-4-5-6-3"></a>

## Symbolic links <a id="cite-link.symlink-target-verbatim"></a>

Creating a symbolic link is an ordinary creation and follows [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>):
the link is created in the create stratum, with a security descriptor
established by inheritance there.

A symbolic link's target is stored and returned verbatim. The target
string is passed through untouched on creation, and on read the outer
inode's `get_link` calls the provider inode's own and returns its
result unmodified. No rewriting exists anywhere: a target naming a path
inside a stratum is not rewritten to name the corresponding path inside
the mount, nor the reverse.

Resolution of a symbolic link found in a stratum follows [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>). The
raw string goes back to the VFS, which interprets it as any filesystem's
target is interpreted, so an absolute target resolves from the process's
root and may re-enter this mount, a different stratafs mount, or none.
A link created directly in a stratum by that stratum's owner is
followed as written; the rule constrains only what stratafs itself
does, which is nothing.

---

# Locking

_Peios Kernel / Internals / StrataFS / Mutation_

> Advisory locks across a stack of independently writable directories — the rule, a changing provider, the retired provider, and leases.

<a id="trm-4-5-7"></a>

Advisory file locks — whole-file and record locks alike — exist so that
several writers of one file can coordinate. A stratafs mount is
established over directories that have their own writers, so a lock
taken through the mount and a lock taken directly on the same object
must be the same lock.

<a id="trm-4-5-7-1"></a>

## The rule <a id="cite-lock.taken-on-the-provider-object"></a>

A lock taken through a stratafs mount is held on the provider's object,
in the same lock space as a lock taken on that object by any other
path. Both the POSIX and the `flock` paths retarget the request onto
the descriptor's provider file, so the lock lands on the provider
inode's own lock context.

stratafs maintains no lock space of its own. There is no lock list, no
fallback onto the outer inode, and no per-inode lock state. Two callers
that lock the same provider object — one through the mount, one through
the stratum directly, or two through different stratafs mounts sharing
that stratum — contend with each other. Open-file-description locks are
re-owned onto the provider file so that their per-description semantics
are preserved.

<a id="trm-4-5-7-1-1"></a>

### Locking does not copy up <a id="cite-lock.no-copy-up-and-facs-rights-still-apply"></a>

Taking a lock does not modify an object, so it does not route ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>))
and cannot itself cause a copy-up. FACS still checks the descriptor's
granted rights ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)): a shared lock requires `FILE_READ_DATA`, and an
exclusive lock requires `FILE_WRITE_DATA` or `FILE_APPEND_DATA`. A
read-only descriptor can therefore carry a shared lock, but not an
exclusive lock without a write grant.

<a id="trm-4-5-7-2"></a>

## Locks and a changing provider <a id="cite-lock.not-transferred-on-provider-change"></a>

A lock is held on the object a descriptor resolved to. That object may
cease to be the provider afterwards — because a higher-precedence
stratum gains the name, because the object is removed from its stratum,
or because a copy-up produced a new object.

In every such case the lock remains held on the object it was taken on.
It is not transferred, and it does not begin to guard the new provider.

**Two callers may therefore hold exclusive locks on one merged path
without contending**, whenever they opened it either side of a change of
provider. Neither is wrong about the object it locked; they locked
different objects, and each lock is honoured by everything else holding
that object. The merged path is what stopped naming one thing. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>)
records it.

A caller that must be sure it holds a lock on the current provider has
to reopen and re-take it, which is the same discipline required of
anything that locks a path another process may replace by rename. The
exposure here is that a copy-up is a replacement the caller did not
perform and cannot see.

<a id="trm-4-5-7-3"></a>

## The retired provider

Copy-up does not close the file it copied from. The pre-copy-up
provider file is moved aside into the descriptor's private state
specifically to keep locks and leases taken before the copy-up alive,
and the fan-out that follows is invisible to the specification but
visible in behaviour:

- A POSIX or `flock` **unlock** is applied to both the retired file and
  the copy; a non-unlock request goes only to the copy. <a id="cite-lock.unlock-reaches-the-retired-file"></a>
- A lease release is applied to both. A lease *acquisition* is
  redirected to the retired file when that file already holds a lease
  of the same flavour. <a id="cite-lock.lease-acquisition-redirected"></a>
- Querying a lease returns the stronger of the two files' lease types,
  ordering write above read above none. <a id="cite-lock.lease-query-returns-the-stronger"></a>
- Closing the descriptor runs the underlying flush and removes POSIX
  locks on both files, and releasing it breaks leases on both, using
  the outer file as the owner identity. <a id="cite-lock.close-clears-both-files"></a>

All of it is serialised by the descriptor's mutation lock.

<a id="trm-4-5-7-4"></a>

## Leases and mandatory locking <a id="cite-lock.leases-are-the-providers"></a>

Leases are established on the provider's object, in that object's own
lock space, and every result is the provider's own, returned unchanged.
stratafs neither adds to nor removes from whatever semantics the
provider's filesystem gives them, and never reports a lock as
established where the provider's filesystem refused it.

Mandatory locking has no subject here: the platform does not offer it,
and stratafs contains nothing that would obstruct it. The outer inode
copies the provider's inode flags wholesale.

<a id="trm-4-5-7-5"></a>

## Internal locks

The specification names no internal lock and fixes no acquisition
order. The implementation's hierarchy, outermost first:

1. The per-open-file **mutation lock**, taken by every operation that
   may copy up.
2. The per-outer-inode **rebind lock**, taken inside it whenever an
   inode's provider is swapped.
3. The dentry lock or the inode lock, taken inside the rebind lock and
   never overlapping each other.

The superblock's identity lock and staging lock are each taken alone.
`copy_file_range` and `remap_file_range` deliberately do not nest the
two files' mutation locks: the input file's is taken, a reference
grabbed, and released before the output file's is taken.

StrataFS assigns inode and per-file lockdep classes during initialization,
before publication. The inode's `i_rwsem` and the file's mutation lock use
classes based on the mount's admitted stacking depth. Directory and
non-directory inodes use separate classes.

Dynamic path resolution can reach a different depth, so these classes do
not guarantee descending acquisition order. Lockdep still records
dependencies and detects reverse-order cycles across depths.

Reads and writes select and retain a reference to their backing file
under the mutation lock. Writes finish routing, any copy-up, and append
flag synchronization before releasing it. The data transfer runs without
the mutation lock because faults on user buffers can acquire the memory
mapping lock. An operation finishes against its selected provider even if a
concurrent operation copies up the descriptor. Writes that complete
successfully before forwarding returns refresh the outer inode from its
current provider under the mutation lock.

Shared write-capable mapping preparation follows the backing chain through
StrataFS and FUSE passthrough. It takes each StrataFS layer's mutation lock
before the VFS acquires `mmap_lock`, then releases it before preparing the
next layer. Each forwarding step uses the credentials that its backing
mapping would use.

StrataFS does not take the mutation lock, resolve paths, perform copy-up,
or acquire provider freeze protection in its mapping callback.

A separate leaf spinlock protects the backing file and matching provider
index. Copy-up publishes this pair while holding the mutation lock. The
mapping callback takes a reference to the selected file under the leaf
lock, then releases the lock before checking the route, auditing a refusal,
or forwarding to the backing filesystem. The reference preserves identity
and lifetime, not the provider's read-only or immutable state. A changed
route can require the caller to retry the whole mapping operation.

For mutations the ordering is: the KACS decision, then parent
materialisation, then write access on the target mount, then the
parent's directory lock through the VFS's create, remove or rename
helpers. Refusal auditing takes the dentry lock with an atomic
allocation first and falls back to the rebind lock only if that fails,
so the two are never nested.

Backing-filesystem freeze protection is held for one mutation stage at a
time. Regular-file copy-up releases its creation-stage mount write hold
while copying contents: reads and writes keep their ordinary permission
and pre-content notification checks, and each write acquires its own
freeze protection. It reacquires the mount write hold before copying
metadata or publishing the anonymous stage; failure to reacquire aborts
the copy without publishing it. This permits a pending filesystem freeze
to complete between stages without a writer waiting on itself.
<a id="cite-lock.copy-up-content-without-outer-writer"></a>

Supersede releases the create mount's write hold before acquiring
the original provider's hold for removal. Rename's merged-destination
emptiness scan, which can recover orphan staging objects, runs without a
backing write hold retained by rename; recovery acquires its own. An early
write-access probe preserves the read-only refusal, and the mutation
reacquires write access before taking its backing directory locks.

---

# Durability and Accounting

_Peios Kernel / Internals / StrataFS / Mutation_

> stratafs holds no storage, so durability and accounting belong to the providers — except where a merged directory needs a rule of its own.

<a id="trm-4-5-8"></a>

stratafs holds no storage, so durability is the providers' and the
accounting is theirs too. Two operations nonetheless need a rule,
because a merged directory has no single provider to forward to.

<a id="trm-4-5-8-1"></a>

## Synchronising an object <a id="cite-durability.fsync-follows-the-descriptor"></a>

Synchronising a non-directory is forwarded to the object the descriptor
resolved to — the descriptor's own provider file — and reports what
that object's filesystem reports. No path re-resolution happens, so it
is never forwarded to whichever object currently provides the path.
Where the two differ, the data the caller wrote is on the object it
opened, and synchronising anything else would report success while
leaving that data unsynchronised.

Where a copy-up has occurred through this descriptor, the descriptor's
object is the copy, and it is the copy that is synchronised. The
retired pre-copy-up file ([Locking](</kernel/internals/stratafs/mutation/locking.md#trm-4-5-7>)) is not.

<a id="trm-4-5-8-2"></a>

## Synchronising a merged directory <a id="cite-durability.dirsync-covers-every-stratum-at-call-time"></a>

Synchronising a merged directory synchronises the corresponding
directory in **every** stratum of the mount that holds it at the time
of the call, and fails if any of them fails. The loop continues past a
failure, so every stratum is still attempted, and the first error is
what is returned.

The set is evaluated when the operation runs, not when the descriptor
was opened: the directory is re-resolved across all strata rather than
read from the participant set settled at open ([Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md#trm-4-3-4>)). Both halves of
that matter:

- Evaluating at call time catches a directory the create stratum did
  not hold when the descriptor was opened and does now — which is
  exactly what happens when a file is created through that descriptor
  and [Creation](</kernel/internals/stratafs/mutation/creation.md#trm-4-5-3>) materialises its parent.
- Covering every stratum rather than the provider alone is required by
  the atomic-replace pattern of [Rename](</kernel/internals/stratafs/mutation/rename.md#trm-4-5-5>), whose rename is performed in
  the stratum that provided the *source*, which need not be the stratum
  providing the merged directory.

Durability is a question about what is on disk now, which is why this
is the one place a merged directory is treated as its current set of
real directories rather than as the thing a descriptor was opened
against.

<a id="trm-4-5-8-3"></a>

## Freezing <a id="cite-durability.freeze-eopnotsupp"></a>

A stratafs mount has no storage to quiesce. Freezing returns
`EOPNOTSUPP` and propagates nothing to any stratum's filesystem; no
unfreeze, freeze-super or thaw-super operation is registered at all.
Freezing the filesystem a stratum lives on is done through that
filesystem, and affects the merged view as it affects any other reader
of that stratum.

<a id="trm-4-5-8-4"></a>

## Storage accounting

Storage consumed by an object created through the mount, or copied up
into the create stratum, is consumed on the create stratum's filesystem
and accounted there. <a id="cite-durability.storage-charged-to-create-stratum"></a>

<a id="trm-4-5-8-4-1"></a>

### The principal charged by quota <a id="cite-durability.copy-up-accounted-to-preserved-owner"></a>

Disk quota keys on the POSIX owner, and copy-up preserves it ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)):
the staged object is created with the calling task's credentials, and
the ownership is then set to the source's under the mount's own
credential. <a id="cite-durability.copy-up-preserves-posix-owner"></a> A copy is therefore accounted to the owner of the object
it was copied from, not to the caller who caused it.

The KACS security descriptor, including its owner SID ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), is
preserved alongside it. <a id="cite-durability.copy-up-preserves-owner-sid"></a> The two notions of owner agree, and both
name the object rather than whoever provoked the copy — which is what
[Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) relies on when it permits a caller to cause a copy into a
directory they hold no rights over.

Ownership is what accounting follows; the caller who caused the copy is
recorded in the audit record of [Audit](</kernel/internals/stratafs/security/audit.md#trm-4-6-5>) instead.

---

# Strata and mounting

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> Find the Peios kernel articles about strata and mounting.

Use these articles to understand strata and mounting in the Peios kernel.

- [The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md>)
- [Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md>)
- [Absent Strata](</kernel/internals/stratafs/strata-and-mounting/absent-strata.md>)

---

# The Stratum Stack

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> A mount is its stratum stack — an ordered, non-empty list fixed for the mount's life — plus the resolution context and the create stratum.

<a id="trm-4-2-1"></a>

A mount is defined by its stratum stack: an ordered, non-empty list of
strata, highest-precedence first. The stack is fixed for the life of
the mount. Nothing reorders it, and precedence never varies by path, by
caller, or by operation. <a id="cite-strata.stack-fixed-and-ordered"></a>

Index 0 is the highest-precedence stratum. That convention runs all the
way through: strata are stored in a fixed array in mount-option order,
presence across the stack is a `u64` bitmap indexed by the same
position, and selecting the provider is the trailing-zero count of that
bitmap — the lowest set index, which is the highest-precedence stratum
that holds the name.

The array is `STRATAFS_MAX_STRATA` entries, which is **16**. A stack
longer than that is refused at parse time. <a id="cite-strata.max-sixteen"></a> Absence never renumbers
anything: an absent stratum simply has its bit clear, keeping its slot
and its precedence.

<a id="trm-4-2-1-1"></a>

## A stratum is a path <a id="cite-strata.no-cached-resolution"></a>

What is stored for each stratum is a string and a flag word — nothing
else. No reference is held on a stratum's directory, and no resolution
result is retained across operations. Every time a name is resolved,
the stratum's path string is joined with the relative path of the name
and walked from scratch.

This is what makes a stratum follow a wholesale replacement. A package
transaction that renames the old tree aside and the new tree into place
leaves the original directory object intact and referenced by anything
that held it; a stratum defined as that object would go on serving the
replaced tree. Defined as a path, it follows.

The cost is that every lookup does the walk. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers what that
means in practice, because the implementation does not cache
resolutions at all.

<a id="trm-4-2-1-2"></a>

## The resolution context <a id="cite-mount.resolution-context-pinned"></a>

Stratum paths are joined absolute and walked from a root captured when
the mount was created — the creating process's own filesystem root —
under credentials captured at the same moment. Both are pinned for the
life of the mount and released only when the superblock is freed.

The credential override matters as much as the root. A stratum path is
resolved with the mounter's credentials, not with those of whatever
process later touches the mount, so a caller in a different mount
namespace cannot shift what a stratum denotes, and the paths reported
by the origin attribute ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)) always name the same things.

Symbolic links and mounts along a stratum's path are followed as they
stand at the moment of resolution, since the walk is an ordinary
`filename_lookup` with no restricting flags. A mount established inside
a stratum is therefore part of that stratum's tree, and one stratum can
span several filesystems — which [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>) has to account for when
deriving inode numbers.

<a id="trm-4-2-1-3"></a>

## What a stratum's filesystem must provide <a id="cite-strata.mount-time-checks"></a>

Nothing beyond ordinary directory and file operations. stratafs probes
no capability at mount time: it checks only that each stratum path
resolves, names a directory, is not a duplicate of another stratum, and
does not push the composed stack past the kernel's maximum stacking
depth. There is no test for a usable directory version value, because
nothing in the implementation would use one.

<a id="trm-4-2-1-4"></a>

## Flags <a id="cite-strata.stack-errors-are-einval"></a>

Each stratum carries zero or more flags, declared with it in the mount
options and stored as a bit field.

| Flag | Bit | Meaning |
|---|---|---|
| `create` | `STRATAFS_F_CREATE` | This stratum receives newly created objects and is the destination of copy-up. |
| `ro` | `STRATAFS_F_RO` | stratafs does not modify this stratum. |
| `am` | `STRATAFS_F_AM` | This stratum's directory may be absent. |

The stack-wide rules are decided in Rust, in `stratafs-core`: the stack
must be non-empty, must not exceed 16 strata, must contain no
unrecognised flag bit, must not carry `create` twice, and must not
carry `create` and `ro` on one stratum. The crate distinguishes five
error cases, but the C boundary collapses all of them to `EINVAL`, so
the distinction is not observable to a caller.

<a id="trm-4-2-1-4-1"></a>

### `create` <a id="cite-strata.create-designates-creation-and-copy-up-destination"></a>

At most one stratum carries `create`, and a stack may carry none, in
which case `create_index` is `-1` and every creation and every copy-up
is refused with `EROFS`. Modification of an object provided by a
stratum that accepts modification is unaffected, because routing tests
the provider before it consults the create stratum at all ([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).

`create` does not mean "writable", and it is not the only stratum
stratafs writes to. It designates where objects that do not yet exist
in any stratum are created, and where an object is copied when its
provider will not accept a modification. A stratum carrying neither
`create` nor `ro` is modified in place, and any number of such strata
may sit above the create stratum, below it, or both.

<a id="trm-4-2-1-4-2"></a>

### `ro` <a id="cite-strata.ro-is-independent-of-filesystem"></a>

`ro` is a stratafs-level assertion, independent of whether the
stratum's filesystem is itself read-only. It is one of three terms in
the predicate that decides whether a stratum **accepts modification**
of an object it provides:

- the stratum does not carry `ro`;
- the provider's mount is not read-only;
- the provider's inode is not marked immutable.

The predicate takes only the superblock, the stratum index, and the
provider path. It reads no credentials, consults no security
descriptor, and calls into KACS not at all — which is what stops a
caller who has been *refused* write access from provoking a copy-up
([Write Routing](</kernel/internals/stratafs/mutation/write-routing.md#trm-4-5-1>)).

Note the third term is specifically the immutable inode flag. A file
that is unwritable by its mode bits is not excluded by this predicate;
the write is routed in place and the underlying filesystem refuses it.

<a id="trm-4-2-1-4-3"></a>

### `am` <a id="cite-strata.am-governs-mount-time-only"></a>

Without `am`, a stratum's directory must exist when the mount is
created, and a mount whose stratum directory is absent fails with
`ENOENT`. With `am`, an absent directory is accepted at mount time.

The flag governs mount time only. At runtime the resolver never
consults it: a stratum whose directory has gone is skipped exactly the
same way whether or not it carries `am`. [Absent Strata](</kernel/internals/stratafs/strata-and-mounting/absent-strata.md#trm-4-2-4>) covers what absence
means once the mount is live.

---

# Mount Admission

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> What a caller must be entitled to and what a configuration must satisfy — evaluation order, loop detection, and mount immutability.

<a id="trm-4-2-3"></a>

A stratafs mount is configured entirely at mount time. This section
covers what the caller must be entitled to, the conditions a
configuration has to satisfy, and the order in which those conditions
are evaluated.

<a id="trm-4-2-3-1"></a>

## Entitlement <a id="cite-mount.create-requires-init-userns-cap"></a>

Establishing a mount with no create stratum takes no privilege of its
own. The filesystem type carries `FS_USERNS_MOUNT`, and stratafs is on
the allowlist of types a mount namespace's descriptor may admit
([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)), so a caller may establish one in a mount namespace it created
without the mount privilege; what the caller needs beyond that is only
the access that resolving the stratum paths already requires, which
falls out of the resolution itself. A user namespace by itself confers
nothing here, as everywhere under KACS.

A stack that carries `create` is different. Copy-up is authorised by
the outer handle and deliberately requires no add-entry right on the
create stratum ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)), so the mount configuration carries authority
to materialise names in a real directory outside the mount. The caller
establishing such a stack must be operating in the **initial** user
namespace and hold `CAP_SYS_ADMIN` there; anything else fails with
`EPERM`.

The test is made in `get_tree`, before the tree is built and therefore
before any stratum path is resolved, and it is stricter than requiring
the capability alone: the credential's own user namespace must *be* the
initial one, not merely a namespace in which the capability resolves.
This is the closure the KACS copy-up context depends on. The check is
made once, when the immutable stack is established, rather than at each
copy-up, so descriptor delegation cannot reintroduce authorisation
against the acting task, and no reconfiguration can re-supply the
strata list.

There is no explicit per-stratum entitlement check in the mount path.
Both halves come out of the ordinary machinery: traverse rights are
enforced by the path walk, which runs under the mounting caller's
credentials, and the right to read a stratum directory's attributes is
enforced by using the security-checking `vfs_getattr` rather than its
unchecked variant, which reaches KACS's `getattr` hook and demands
`FILE_READ_ATTRIBUTES`.

One seam is worth recording: the path walk uses the credentials
captured on the filesystem context, while `vfs_getattr` runs outside
that override and so uses the acting task's. For a mount established
the ordinary way the two are the same task. For one established with
`fsopen` and `fsconfig` from different tasks they need not be.

Nothing re-checks entitlement if a stratum directory later appears.
That is sound because every access through the mount is checked against
the providing object in any case ([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)), so a caller who mounts a
stratum they cannot read still cannot read it.

<a id="trm-4-2-3-2"></a>

## Validity

| Condition | Error |
|---|---|
| The stratum stack is empty | `EINVAL` <a id="cite-mount.admit.empty-stack-einval"></a> |
| The stack exceeds 16 strata | `EINVAL` <a id="cite-mount.admit.too-many-strata-einval"></a> |
| More than one stratum carries `create` | `EINVAL` <a id="cite-mount.admit.multiple-create-einval"></a> |
| A stratum carries both `create` and `ro` | `EINVAL` <a id="cite-mount.admit.create-with-ro-einval"></a> |
| The same directory appears as more than one stratum | `EINVAL` <a id="cite-mount.admit.duplicate-stratum-einval"></a> |
| A malformed `strata=` value ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)) | `EINVAL` <a id="cite-mount.admit.malformed-value-einval"></a> |
| A create-bearing stack from outside the initial user namespace, or without `CAP_SYS_ADMIN` there | `EPERM` <a id="cite-mount.admit.create-requires-privilege-eperm"></a> |
| A stratum's path names something other than a directory | `ENOTDIR` <a id="cite-mount.admit.not-a-directory-enotdir"></a> |
| A stratum's directory is absent and the stratum does not carry `am` | `ENOENT` <a id="cite-mount.admit.absent-without-am-enoent"></a> |
| The composed stack reaches the kernel's maximum stacking depth | `ELOOP` <a id="cite-mount.admit.stacking-depth-eloop"></a> |
| A stratum lies within the mount point, or within another stratafs mount whose strata include this mount point | `ELOOP` <a id="cite-mount.admit.recursive-stratum-eloop"></a> |
| Sixteen consecutive collisions allocating a mount cookie | `EAGAIN` <a id="cite-mount.admit.cookie-exhaustion-eagain"></a> |

Two strata are the same directory when they resolve to the same
directory object, not merely when their paths are equal as strings: the
comparison is on resolved inodes, so two paths reaching one directory
through different symbolic links or bind mounts are caught. Absent
strata are skipped and never compared. <a id="cite-mount.duplicate-strata-by-inode"></a>

<a id="trm-4-2-3-3"></a>

## Evaluation order <a id="cite-mount.admission-evaluation-order"></a>

The conditions that depend on nothing but the option string are decided
first, during parsing and stack-wide validation, and are reported
whatever the caller's access. The `EPERM` admission test comes next, in
`get_tree`, still before any path is touched. Only then are the strata
resolved.

The purpose of that ordering is to stop the validity conditions being
an oracle: a caller with no right to traverse a directory should not be
able to name it as a stratum and learn from the errno whether it exists
and whether it is a directory.

The path walk and the attribute read both run under the caller's
credentials, so a path the caller cannot resolve returns `EACCES` from
the walk itself, and the `EACCES` is propagated unchanged.

The check is stack-wide because it runs in two passes. The first
resolves and stats every stratum; an `EACCES` from any of them is the
answer, whatever an earlier stratum reported. Only when every stratum
has passed entitlement does the second pass apply the type, duplicate
and depth conditions. A caller who names a readable non-directory first
and an unreadable path second is told `EACCES`, not `ENOTDIR`.
<a id="cite-mount.entitlement-is-decided-in-two-passes"></a>

The mount-point loop condition is evaluated in a different call
entirely, after the tree has been built, and so always follows every
entitlement check.

<a id="trm-4-2-3-4"></a>

## Loops <a id="cite-mount.loop-detected-at-mount"></a>

A stratum inside the mount point is detected directly. The indirect
case — a stratum inside *another* stratafs mount whose own strata
include this mount point — is detected by recursing into any stratum
whose superblock carries the stratafs magic, bounded by a visited-
superblock set and by the kernel's maximum stacking depth. This runs
through a Peios-added `super_operations` hook, `validate_mountpoint`,
wired into the new-mount, bind and move-mount paths by the patch series;
it is not an upstream interface.

That check cannot bind after the fact: a mount established within a
stratum, or a bind mount of this mount into one of its own strata, can
create a cycle later. Resolution is guarded separately, and differently
— not by a depth counter but by a per-task, per-superblock re-entrancy
list. A task that is already resolving in a superblock and re-enters it
gets `ELOOP` immediately, so a cycle spanning any number of stratafs
mounts terminates the moment it returns to one it is already inside.

<a id="trm-4-2-3-5"></a>

## Immutability and mount identity <a id="cite-mount.strata-shared-between-mounts"></a>

The stack is fixed for the life of the mount; changing one is expressed
by unmounting and mounting again ([Mount Options](</kernel/administration/stratafs/mount-options.md#trm-4-2-2>)).

Two stratafs mounts may name the same directory as a stratum. Each
resolves independently and neither is aware of the other; where both
have a create stratum in common they mutate the same objects, with the
same result as any two writers of one directory. There is no registry
of stratum paths to make them aware of each other.

There is a registry of *mounts*, but it exists for a different purpose.
Each mount draws a random non-zero cookie and inserts itself into a
global table, retrying up to sixteen times on collision; a second
random non-zero cookie is drawn once per boot. The pair identifies
which live mount owns a staging entry, so that a mount sharing a create
stratum can distinguish another mount's copy-up in flight from an
orphan left by a crash ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).

<a id="trm-4-2-3-6"></a>

## An all-absent stack <a id="cite-mount.all-absent-stack-is-legal"></a>

A mount succeeds even when no stratum root is present at all — a stack
whose only strata are absent `am` strata is legal. The root inode is
constructed with no provider, and reports mode `S_IFDIR` with no
permission bits.

Such a root still carries a security descriptor, since an object with
none would refuse every access check made on the mount root and the
provider-less root could never be observed. stratafs synthesises it:
owned by the mounter, with read and traverse for everyone, and nothing
more — there is nothing beneath such a root to write. The moment a
stratum root appears the root's descriptor is that root's own, and
when it goes again the synthesised one returns; KACS never caches a
StrataFS root's descriptor, so no access is decided against a root that
has since gained or lost its provider. <a id="cite-mount.all-absent-root-serves-a-synthesised-descriptor"></a>

---

# Absent Strata

_Peios Kernel / Internals / StrataFS / Strata and mounting_

> A stratum's directory may not exist — what happens while it is absent, and what appearing, disappearing and reappearing do.

<a id="trm-4-2-4"></a>

A stratum's directory may not exist. It may be absent when the mount is
created — which requires `am` ([Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>)) — or exist at mount time and be
removed while the mount is live, which nothing prevents for any
stratum.

<a id="trm-4-2-4-1"></a>

## While absent <a id="cite-strata.absent-contributes-nothing"></a>

An absent stratum holds no names, participates in no merged directory,
and contributes no entries to any enumeration. It keeps its position
and its precedence; only its presence bit is clear.

The mechanism is a single test in the resolver. Resolving one stratum
either succeeds, or fails with `ENOENT` or `ENOTDIR`, in which case the
stratum is skipped and its bit is left clear. Any other error —
`EACCES`, `EIO`, `ELOOP`, `ENAMETOOLONG`, `ESTALE` — is not treated as
absence and fails the whole resolution instead. So a stratum that is
unreadable for a reason other than not being there masks the name for
every stratum, rather than being passed over.

An absent create stratum additionally causes every operation that would
create or copy up to fail with `EROFS`. The create stratum's root is
re-resolved at the point of use and its `ENOENT` is mapped to `EROFS`
by each of the paths that needs it — the copy-up parent walk, the
creation authorisation pre-check, and the routing decision, which
computes create-stratum presence live and requires the result to be a
directory. stratafs does not create the stratum's own directory to
satisfy such an operation: establishing that directory, with the
security descriptor it should have, belongs to whatever provisions the
system, and a mount that minted it would be choosing that descriptor.

<a id="trm-4-2-4-2"></a>

## Appearing and disappearing <a id="cite-strata.appearance-observed-on-next-lookup"></a>

Neither event is detected. Both are simply observed, because there is
nothing to invalidate.

A stratum's directory is never held; only its path string is. Every
resolution walks that string afresh, so a directory that comes into
existence is picked up by the very next lookup, and one that is
removed, renamed away, or replaced by another directory is picked up
just as immediately — the walk finds nothing, or finds the replacement.

The specification describes this in terms of a version tuple recorded
over the nearest existing ancestor of an absent stratum's path, and an
identity comparison for a stratum that disappears. Neither exists in
the implementation, and neither is needed: they are the machinery for
knowing when a *cached* resolution has gone stale, and nothing is
cached. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers the trade that represents.

The `am` flag is not consulted at runtime at all. It governs whether
the mount is allowed to be established with the directory missing, and
nothing more; a stratum without it that vanishes afterwards behaves
exactly like one with it.

<a id="trm-4-2-4-3"></a>

## Reappearance <a id="cite-strata.reappearance-preserves-inode-number"></a>

A stratum that disappears and reappears is the same stratum in the same
stack position, and nothing about the old directory is remembered.
Resolutions are recomputed against whatever the new directory holds.

Provider identity does survive the gap, though it is not resolution
memory. The derived inode number ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)) identifies the provider's
filesystem and inode number. If the same underlying object is reached
again — because the directory was renamed away and back rather than
replaced — it receives the same number it had before, without a
mount-lifetime pin on ordinary provider inodes. Only identities that
cannot be derived use the pinned fallback map. That is exactly what
the identity rule requires: equal numbers for one provider object,
whatever path reached it.

---

# Name resolution

_Peios Kernel / Internals / StrataFS / Name resolution_

> Find the Peios kernel articles about name resolution.

Use these articles to understand name resolution in the Peios kernel.

- [Lookup and type conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md>)
- [Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md>)
- [Enumeration](</kernel/internals/stratafs/name-resolution/enumeration.md>)

---

# Lookup and type conflicts

_Peios Kernel / Internals / StrataFS / Name resolution_

> Resolving one name in one directory — the provider, ancestors, independence from the caller, and staging entries.

<a id="trm-4-3-1"></a>

Resolution is defined for one name in one directory. Every path
operation is a sequence of such resolutions, each independent of the
last.

<a id="trm-4-3-1-1"></a>

## The provider <a id="cite-resolution.provider-is-highest-stratum"></a>

To resolve a name in a stratafs directory, the corresponding directory
of each stratum is examined in precedence order, and the first stratum
holding an entry of that name is its **provider**. If no stratum holds
it, the resolution produces a negative dentry and the VFS reports
`ENOENT`.

Mechanically, each stratum's path string is joined with the relative
path of the name and walked in full, once per stratum. A walk that
succeeds sets that stratum's bit in a presence bitmap; a walk that
fails with `ENOENT` or `ENOTDIR` leaves it clear and the stratum is
skipped. Selecting the provider is then the trailing-zero count of the
bitmap, computed in `stratafs-core`.

Any other error from a stratum's walk — `EACCES`, `EIO`, `ELOOP`,
`ENAMETOOLONG`, `ESTALE` — is not treated as absence. It fails the
whole resolution, so a stratum that is unreadable for a reason other
than not being there masks the name entirely rather than being passed
over.

A joined stratum path, or a child relative path, that would exceed
`PATH_MAX` fails with `ENAMETOOLONG`.

<a id="trm-4-3-1-2"></a>

## Ancestors <a id="cite-resolution.provider-chosen-per-component"></a>

Resolution does not consult a parent's provider to find a child's. A
name's provider is chosen afresh across all strata, so if `/a` is
provided by stratum 2, `/a/b` may still be provided by stratum 1 —
provided stratum 1 also holds `/a` as a directory and the two therefore
merge ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)).

What resolution does consult is whether any ancestor of the path is
masked. Before resolving the final component, every proper prefix of
the relative path is resolved across all strata and its merged provider
computed; a prefix whose provider is not a directory aborts the whole
resolution with `ENOTDIR`. That is what makes masking total ([Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>)),
and it is why a lookup costs one full walk per stratum for the name
itself plus one merged resolution per path component above it.

<a id="trm-4-3-1-3"></a>

## Independence from the caller <a id="cite-resolution.independent-of-caller"></a>

Resolution runs under the credentials captured at mount, against the
root captured at mount, and takes no operation argument. It does not
depend on the calling token, on what the caller is trying to do, or on
whether the operation will ultimately be permitted.

A name whose provider the caller may not access therefore resolves
normally and is then refused. It does not fall through to a lower
stratum — which would let a caller's rights change which file they
read, a considerably worse property than a denial.

<a id="trm-4-3-1-4"></a>

## Reaching the object <a id="cite-resolution.non-directory-forwarded"></a>

Once a name resolves to a non-directory provider, the object is the
provider's object and stratafs does not interpose on its contents. The
outer inode takes the provider's mode and, from it, the operations
tables for a regular file, symlink or special file; reads, writes,
mappings, splices, locks and `ioctl`s are forwarded to a backing file
opened on the provider.

Symbolic links are forwarded rather than followed. The outer inode's
`get_link` calls the provider inode's own and returns the raw target
verbatim; stratafs deliberately does not use `vfs_get_link`, which
would demand a read right the caller need not hold to traverse a link.
The VFS then interprets the target in the caller's own namespace, so an
absolute target resolves from the process's root and may re-enter this
mount, another stratafs mount, or none.

Where a mount is established at a path within a stratum, stratafs
follows it: the stratum walk is an ordinary `filename_lookup` with no
flag restricting it to one filesystem, and everything downstream
operates on the inner mount it returns.

<a id="trm-4-3-1-5"></a>

## Staging entries <a id="cite-resolution.staged-names-hidden"></a>

One class of name is invisible to resolution. While a copy-up is in
flight, its staged object may exist under a name in the create stratum;
that name is dropped from resolution for the mount that owns it, so an
incomplete copy is never reachable through the merged view ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)).
The suppression applies only to the create stratum, and only within the
owning mount — a second stratafs mount sharing that directory, and any
direct reader of it, sees an ordinary entry.

<a id="trm-4-3-1-5-1"></a>

### Recovery triggered by lookup <a id="cite-resolution.staging-prefix-triggers-recovery"></a>

Staged names begin with `.stratafs-stage-`, and a lookup of any name
with that prefix triggers a recovery scan of the create-stratum parent
before resolving. A resolution can therefore have the side effect of
removing orphaned staging entries from the create stratum.

<a id="trm-4-3-1-6"></a>

## Recursion <a id="cite-resolution.reentrant-superblock-eloop"></a>

A task that is already resolving inside a superblock and re-enters the
same superblock fails immediately with `ELOOP`. The guard is a global
list of task-and-superblock pairs, not a depth counter, so a cycle
formed after mount — a stratafs mount established inside one of its own
strata, or bind-mounted into one — terminates the moment resolution
returns to a mount it is already inside.

<a id="trm-4-3-3"></a>

Two strata may hold the same name with different types — a directory in
one, a regular file in another. The provider's type is the type of the
resolved object, and the outer inode is given the provider's mode and
the operations tables that follow from it. <a id="cite-resolution.conflict-provider-type-wins"></a>

- Where the provider is a **directory**, lower-precedence strata that
  hold the name as a directory participate in a merged directory
  ([Directory Merge](</kernel/internals/stratafs/name-resolution/directory-merge.md#trm-4-3-2>)). Lower-precedence strata that hold the name as anything else
  are masked. <a id="cite-resolution.conflict-directory-merges-only-directories"></a>
- Where the provider is **not** a directory, every lower-precedence
  entry of that name is masked, whatever its type. <a id="cite-resolution.non-directory-masks-lower"></a> Only the provider's
  path is retained on the dentry; the other strata's references are
  released as soon as the provider is chosen.

<a id="trm-4-3-3-1"></a>

## Masking is total <a id="cite-resolution.masking-hides-whole-subtree"></a>

A masked entry is unreachable through the mount. Where the masked entry
is a directory, its entire subtree is unreachable: no path beneath the
masked name resolves, regardless of what the masked directory contains
and regardless of whether some other stratum holds part of that
subtree.

This is enforced by the ancestor pass described in [Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>). Each proper
prefix of a relative path is resolved across every stratum and its
merged provider computed; a prefix whose merged provider is not a
directory returns `ENOTDIR` before the final component is considered.
Because the test uses the merged answer rather than a per-stratum one,
another stratum holding the subtree cannot rescue it.

A regular file at `/x` in a high-precedence stratum therefore hides a
whole `/x/…` tree in a lower one. That is severe, and deliberate: the
alternative — resolving `/x` as a file but `/x/y` through the masked
directory — would make a path's meaning depend on how far along it the
caller looked.

<a id="trm-4-3-3-1-1"></a>

### Masking leaves the strata unchanged <a id="cite-resolution.masking-does-not-modify-strata"></a>

Masking modifies nothing. Resolution and enumeration are read-only
throughout, no marker is written to any stratum, and the masked entry
remains present and unchanged in its own stratum, reachable by any path
that does not traverse the mount.

<a id="trm-4-3-3-2"></a>

## Stability <a id="cite-resolution.conflict-operation-fails-against-provider"></a>

Type conflicts resolve identically for every caller and every
operation, because provider selection is a pure function of the
presence bitmap and consults neither.

An operation that would only be valid against the masked type does not
cause the masked entry to be selected. It fails against the provider
instead, with whatever error that type produces — typically `ENOTDIR`
from the ancestor pass, or `EISDIR` raised by the generic VFS against
an outer inode carrying the provider's mode.

---

# Directory Merge

_Peios Kernel / Internals / StrataFS / Name resolution_

> When lower strata hold the same name as a directory the result is a merged directory — participation, its create stratum, and symlinks.

<a id="trm-4-3-2"></a>

Where a name's provider is a directory, and lower-precedence strata
hold the same name as a directory, the resolved object is a **merged
directory**.

<a id="trm-4-3-2-1"></a>

## Participation <a id="cite-resolution.merge-participants"></a>

The strata participating in a merged directory are, in precedence
order, those whose corresponding directory both exists and is a
directory. A stratum holding the name as a non-directory does not
participate and is masked entirely ([Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>)); a stratum not holding the
name simply does not participate.

Every consumer of a merged directory applies the same two-part filter —
the presence bit is set, and the resolved dentry is a directory — in a
single ascending loop over stratum indices with a `continue` for
non-participants. Nothing compacts or re-sorts, so relative precedence
within a merged directory is always the relative precedence in the
stack.

Merging is recursive, and it is recomputed rather than cached: there is
no merged-directory object anywhere. Each lookup and each directory
open rebuilds the full per-stratum path set from the relative path
string, so any child that is a directory in more than one stratum
merges at its own level by the same rule.

<a id="trm-4-3-2-1-1"></a>

### Participation at the mount root <a id="cite-resolution.root-participation"></a>

The root of a mount is a merged directory whose participants are the
mount's strata. The root has one special case: where the ordinary
provider rule would pick a stratum root that is present but not a
directory, the root instead takes the first stratum that is both
present and a directory, so an absent or non-directory stratum root
cannot change the synthetic root's type. A mount whose stratum roots
are all absent still has a root inode, with no provider and no
permission bits.

<a id="trm-4-3-2-2"></a>

## The create stratum of a merged directory <a id="cite-resolution.merge-create-stratum-is-positional"></a>

A merged directory's create stratum is the correspondingly-named
subdirectory of the mount's create stratum, at the same path relative
to the mount root — whether or not that subdirectory currently exists.
It follows that a merged directory has a create stratum even when the
mount's create stratum holds no part of that path, and creation still
routes there.

The derivation is positional and mount-wide: `create_index` is a single
integer on the superblock, fixed at mount, and every creation and
copy-up site reads it directly. Nothing re-derives it from which strata
happen to participate.

That matters because the alternative — taking the create stratum to be
the highest-precedence participating writable directory — would make
the destination of a write depend on which directories happened to
exist, so creating a file in a subdirectory could land in a different
stratum from creating one beside it.

Where the create stratum's counterpart of a merged directory does not
exist, the path is materialised on demand, from the mount root
downwards, at the point an operation first needs it ([Copy-Up](</kernel/internals/stratafs/mutation/copy-up.md#trm-4-5-2>)). The
authorisation for creating into it is evaluated against the descriptor
that directory will carry once materialised, which is the corresponding
provider directory's ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)).

<a id="trm-4-3-2-3"></a>

## Symbolic links and participation <a id="cite-resolution.merge-participant-set-resolves-like-lookup"></a>

Two resolution entry points disagree about the final component of a
stratum path, and the difference is visible.

Ordinary lookup resolves without following the final component, so a
symbolic link at a name resolves to the link itself and the VFS follows
it. Every site that builds the participant set resolves the same way —
the set itself, the emptiness scan, the foreign-entry scan, the
permission check and directory `fsync`.

A symlink is a non-directory, so a stratum holding a name as one is
masked entirely, exactly as [Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>) has it: it does not participate,
contributes no entries to the merged listing or to emptiness tests, and
masks whatever the strata below hold at that name. A dangling symlink
is the same, and for the same reason. <a id="cite-resolution.symlink-masks-like-any-non-directory"></a>

The two views agreeing is what closes a confused-deputy shape. Were the
participant set to follow the final component while lookup did not, a
stratum owner who replaced a directory with a symlink would change
which real directory contributed entries to another stratum's merged
view, and the permission check would run against a target the mounter
never named.

---

# Enumeration

_Peios Kernel / Internals / StrataFS / Name resolution_

> The union of names across participating strata, each appearing once — captured at open, with consistency and position rules.

<a id="trm-4-3-4"></a>

Enumerating a merged directory yields the union of the names held by
its participating strata, with each distinct name appearing exactly
once. <a id="cite-resolution.merged-directory-is-union"></a>

<a id="trm-4-3-4-1"></a>

## Capture at open

The whole listing is built when the directory is opened, and the
enumeration is served from that capture for the life of the descriptor.
Each participant is opened and iterated in ascending stratum order, and
its entries are appended to one list. <a id="cite-enumerate.captured-at-open"></a>

Deduplication is global rather than per-stratum: before an entry is
recorded, the whole accumulated list is scanned for the same name, and
a match causes the entry to be dropped. Because participants are
visited highest-precedence first, the entry that survives is always the
provider's. <a id="cite-enumerate.duplicate-name-resolves-to-provider"></a> `.` and `..` are dropped from every participant and
synthesised once. <a id="cite-enumerate.dot-entries-synthesised-once"></a>

Each surviving entry carries the name, its length, the directory entry
type reported by the providing participant, and an inode number
obtained by looking the child up in that same participant and deriving
its identity, with allocation only as a fallback ([Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)), so `getdents` and
`stat` agree. <a id="cite-enumerate.entry-inode-matches-stat"></a> The final component is not followed during that lookup,
so a symlink entry reports its own identity rather than its target's. <a id="cite-enumerate.symlink-entry-reports-itself"></a>

Two details of that: an entry that vanishes between the participant's
own `readdir` and the follow-up lookup is silently dropped, which is
ordinary provider behaviour; and a participant filesystem that reports
`DT_UNKNOWN` has that propagated unchanged, even though the child path
is in hand and the real type could be derived. <a id="cite-enumerate.dt-unknown-propagated"></a>

Shadowed entries are neither reported nor otherwise detectable. No
second record is ever allocated, so nothing about them survives into
the listing, and the entry count reflects distinct names only. <a id="cite-enumerate.shadowed-entries-invisible"></a>

The order in which names are reported is stratum-ascending and then
each stratum's own `readdir` order — deterministic for one capture, and
not otherwise specified. <a id="cite-enumerate.order-stratum-then-readdir"></a>

The implementation uses a temporary, per-open name hash while capturing
entries, then an immutable position index for enumeration. Growing the
hash does not reorder entries or change which provider wins a duplicate.
The hash buckets are released before the open succeeds. Capture remains
eager under the opener's authority; the index does not defer any part of
that authorisation to a later reader or descriptor recipient.

Deduplication takes expected linear work in the number of names offered
by the participants. Resuming enumeration or seeking to an ordinal does
not scan earlier entries again. Provider enumeration, child lookup and
access checks still contribute their own costs. Each independent open
retains its own names and position index, so memory use still grows with
the number of distinct captured names and simultaneously open file
descriptions. These are implementation properties, not time or memory
limits promised to callers.

<a id="trm-4-3-4-2"></a>

## Consistency <a id="cite-enumerate.changes-after-open-invisible"></a>

There is exactly one capture per descriptor. Nothing appends to the
list after the directory is opened, and nothing re-captures — a
rewind replays the original capture, since the directory uses the
generic `llseek`. A change to any participating stratum after the open
is therefore invisible to that descriptor for its lifetime.

What that bounds is only what stratafs itself contributes. Each
participating directory is enumerated by its own filesystem, with
whatever consistency that filesystem offers its own callers, and
participants are read sequentially with no cross-stratum lock or
barrier. A merged listing is no better than the listings it is
assembled from, and nothing claims otherwise.

<a id="trm-4-3-4-3"></a>

## The settled participant set <a id="cite-enumerate.participant-set-settled-at-open"></a>

For the purpose of enumeration, the participating set is settled when
the directory is opened and does not change for the life of the
descriptor. What is settled is the set of participating **directory
objects**, not the set of stratum positions: the descriptor holds a
`struct path` reference on each participant, pinned until release, and
nothing re-resolves those positions by path. A participant that has
since been removed and replaced by another directory at the same path
is a different object and contributes nothing.

The settled set has exactly three consumers: the enumeration itself,
the access check performed when the directory is opened ([Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>)), and
the origin attribute read through that descriptor ([The Origin Attribute](</kernel/internals/stratafs/start-here/the-origin-attribute.md#trm-4-7>)). It extends to
nothing else. Resolving a name relative to the descriptor — opening,
removing, renaming, linking — is an ordinary live resolution under
[Lookup](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-1>), performed against the strata as they are at that moment.

So a descriptor opened before a stratum began to hold the directory
will not list that stratum's names, but `openat` through the same
descriptor will resolve them. The two answers differ deliberately:
enumeration is a bulk disclosure whose authorisation was decided once,
when the descriptor was opened; a resolution is a fresh operation that
carries its own check.

Freezing the participant set is what keeps that open-time check
meaningful. Were a later re-read free to admit a stratum that joined
afterwards, its names would reach the caller without its directory's
descriptor ever having been consulted — and a stratum owner could make
a directory participate precisely to expose it. A caller that wants the
current participant set reopens.

<a id="trm-4-3-4-4"></a>

## Positions <a id="cite-enumerate.offsets-are-plain-ordinals"></a>

Offsets 0 and 1 are `.` and `..`. Offset `2 + k` is the k-th element of
the captured list — a plain ordinal. The offset each participant
filesystem supplies is discarded: no provider cookie, no stratum index,
and no name hash is encoded.

A position is therefore meaningful only within one open file
description. On close and reopen — and so across a remount or a reboot —
the capture is rebuilt from each stratum's current contents and current
`readdir` order, and ordinal `2 + k` may name a different entry or
none. `telldir` and `seekdir` across descriptors are unreliable on a
stratafs directory, as is NFS re-export of one.

<a id="trm-4-3-4-5"></a>

## Access <a id="cite-enumerate.requires-rights-on-every-participant"></a>

Enumeration requires traverse and list rights on **every** participating
directory, checked before the capture is built. The check returns on
the first refusal, and a refusal aborts the open entirely, so no
partial listing covering only the readable strata can be produced.

---

# Coherency

_Peios Kernel / Internals / StrataFS / Coherency_

> Find the Peios kernel articles about coherency.

Use these articles to understand coherency in the Peios kernel.

- [Model and revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md>)
- [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md>)

---

# Model and revalidation

_Peios Kernel / Internals / StrataFS / Coherency_

> Strata change underneath stratafs without telling it — what can change a resolution, and the guarantee that survives it.

<a id="trm-4-4-1"></a>

Every stratum of a mount may be modified at any time by an agent that
does not know stratafs exists. stratafs observes such changes without
being told of them.

<a id="trm-4-4-1-1"></a>

## No coordination <a id="cite-coherency.no-notification-protocol"></a>

There is no notification machinery anywhere in the filesystem — no
`fsnotify` registration, no `inotify`, nothing a stratum's filesystem
is expected to report. No writer announces a change, quiesces, or
participates in any protocol. Every resolution is performed from
scratch by re-walking the stratum path string, so nothing has to be
told anything.

<a id="trm-4-4-1-2"></a>

## What can change a resolution <a id="cite-coherency.resolution-depends-on-names-not-contents"></a>

A resolution depends only on which names each participating stratum
directory holds and what type each entry has. It does not depend on the
contents of any file.

A change to an object's **contents** therefore requires no action at
all. stratafs inodes carry no address-space operations; there is no
second page cache, and every data operation is forwarded to a backing
file opened on the provider. A change to that object is observed
through the mount immediately and by construction, because there is
nothing to invalidate.

A change to the **structure** of a participating stratum directory — an
entry created, removed, renamed, or replaced by one of another type —
may change which stratum provides a name. [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) covers how that is
handled, which is by not caching anything.

<a id="trm-4-4-1-3"></a>

## The guarantee <a id="cite-coherency.structural-change-visible-to-next-resolution"></a>

A structural change in a stratum becomes visible to any resolution
begun after the stratum's own filesystem exposes that change to an
ordinary lookup. stratafs adds no delay of its own: there is no
timeout, no jiffies comparison, no generation counter, and no
resolution cache to serve a stale answer from.

It cannot anticipate a change the underlying filesystem is not yet
reporting. A network filesystem holding an attribute cache does not
show a change to stratafs any sooner than to any other caller, and
nothing claims otherwise.

Resolutions already completed are not revisited. Every regular-file
open is detached onto a descriptor-private dentry and inode holding
their own reference to the provider, and I/O runs against the file
opened at that time, so later masking or removal in any stratum cannot
reach that descriptor. It is not re-pointed and it does not fail. A
process holding a configuration file open across a package upgrade
continues to read the file it opened.

The one exception is copy-up, which [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>) covers: a descriptor whose
own write caused a copy-up keeps its inode while that inode's backing
object becomes the copy.

The open file description retains its sequential file position across
copy-up. `read` and `write` advance that position, and `lseek` with
`SEEK_CUR` uses it even after the backing file changes. Positioned I/O
through `pread` or `pwrite` leaves it unchanged.

<a id="trm-4-4-1-4"></a>

## Live strata <a id="cite-coherency.stratum-replaceable-while-mounted"></a>

Because resolutions are made against current state, and because a
stratum is a path rather than a directory object ([The Stratum Stack](</kernel/internals/stratafs/strata-and-mounting/the-stratum-stack.md#trm-4-2-1>)), a stratum's
directory may be replaced wholesale — by a package transaction, by a
reconciler, by an administrator — while the mount is live, with no
remount and no interruption to callers. That is the requirement the
filesystem exists to satisfy, and [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) is the whole of its cost.

<a id="trm-4-4-2"></a>

The specification permits an implementation to cache resolutions,
subject to a version tuple recorded per stratum and an identity
comparison on reuse. This implementation caches nothing, and so
implements neither.

<a id="trm-4-4-2-1"></a>

## Always invalidate <a id="cite-coherency.revalidate.always-invalidates"></a>

`d_revalidate` returns 0 for every dentry except the mount root. The
VFS therefore discards the dentry and re-enters `lookup` on every path
walk, and the lookup re-resolves the parent and the child from their
relative path strings across every stratum.

Nothing is memoised. No version value is recorded, no directory
identity is retained for comparison, no nearest-existing-ancestor walk
happens, and no `i_version` is read anywhere in the filesystem. The
per-dentry provider path that is retained is not a cache of a
resolution: it is dropped when the dentry is released, and the dentry
is released on the next walk.

The specification's machinery exists to know when a cached resolution
has gone stale. With no cached resolution, the questions it answers do
not arise:

| What the tuple would detect | Why it is unnecessary here |
|---|---|
| A stratum gaining or losing a name | The next walk resolves the name afresh |
| A stratum's directory appearing | The next walk finds it |
| A stratum's directory removed, renamed away, or renamed over | The next walk finds nothing, or finds the replacement |

The result is strictly stronger than the specification requires, in the
safe direction. The internal filesystem-domain, fallback-inode and
staging-name counters do not validate cached resolutions.

<a id="trm-4-4-2-2"></a>

## What it costs <a id="cite-coherency.revalidate.rcu-walk-refused"></a>

The cost is real and lands on the hottest path in the kernel.

`d_revalidate` refuses RCU-walk unconditionally: a lookup in RCU mode
returns `ECHILD` and the walk is retried in ref-walk mode, and the
directory permission check does the same. RCU-walk is therefore never
used on a stratafs mount, and the fallback is taken always rather than
only where it genuinely cannot proceed.

The refusal, invisible to the caller by design, is visible at two
tracepoints. `stratafs:stratafs_rcu_walk_refused` marks the directory
permission check turning a walk back under `MAY_NOT_BLOCK` — in
practice the first stratafs directory a walk must traverse does this,
so it is the point that actually takes every walk out of RCU mode.
`stratafs:stratafs_d_revalidate` records each revalidation verdict —
mount cookie, merged inode number (zero for a negative entry), whether
the call was in RCU mode, and the return value — and because the
permission check fires first, every recorded call arrives already in
ref-walk mode; its `-ECHILD` branch is the backstop. Like every PKM
tracepoint, neither records a pathname.

What replaces it, per path component, is one full `filename_lookup` per
stratum — up to sixteen — plus one merged resolution per proper prefix
of the path, for the ancestor-masking test of [Type Conflicts](</kernel/internals/stratafs/name-resolution/lookup-and-type-conflicts.md#trm-4-3-3>). Where a mount is
established over a directory of executables, that lies on the path of
every program execution, and there is no dentry cache hit to avoid it.

This is the one part of the filesystem whose cost is worth measuring
rather than assuming, and closing the gap — recording enough per
resolution to reuse one safely, and making the comparison RCU-safe — is
tracked as work in its own right.

---

# Inode Identity and Lifecycle

_Peios Kernel / Internals / StrataFS / Coherency_

> stratafs allocates its own inodes standing for provider objects — the identity it reports, the mount root, and what a provider change does.

<a id="trm-4-4-3"></a>

stratafs presents its own inodes, allocated from its own superblock.
Each stands for a provider object and forwards operations to it; none
holds file data, directory entries, or a security descriptor.

<a id="trm-4-4-3-1"></a>

## Reported identity <a id="cite-inode.number-derived-from-provider"></a>

The device identifier reported for any object in a mount is the
stratafs superblock's own anonymous device, not the provider's.
`getattr` calls the provider's directly and then overrides `dev`, `ino`
and, for directories, `nlink`; all four inode-operations tables install
that same `getattr`.

The inode number is derived from the provider filesystem's reported
inode number and a small mount-local identifier for its reported device.
The device identifier distinguishes filesystem domains, not stratum
positions: a stratum can cross mount points. The reported device also
distinguishes Btrfs subvolumes, which can share a kernel superblock and
inode numbers. Two paths to the same provider identity, including hard
links and bind-mounted aliases, therefore report the same number.

Derivation reserves the high bit for allocated fallback numbers. A
self-delimiting tag in the low bits identifies the filesystem domain;
the provider inode number occupies the remaining bits. Small provider
numbers stay small enough to derive again through nested stratafs views.
Neither the bit layout nor the mount-local domain assignment is a
persistent identifier or an ABI that callers should decode. Numbers
may differ between mounts; within a mount, reloading the same provider
identity after cache eviction produces the same number.

Only identities that cannot fit, or providers that do not report a
usable inode number, use the fallback map. It allocates a distinct
number and holds a reference on the provider inode until unmount to
prevent address reuse. Repeated encounters with that provider reuse its
allocation. Synthetic provider-less roots use the same allocated number
space without a provider reference. Exhaustion returns `EOVERFLOW`
rather than wrapping, including on 32-bit builds. An attribute lookup
error is returned to the caller instead of silently assigning a new
identity.

<a id="trm-4-4-3-1-1"></a>

### The mount root <a id="cite-inode.root.follows-live-provider"></a>

The root inode is created once, when the superblock is filled, and the
root dentry is never replaced — `d_revalidate` returns 1 for it. Its
provider is nevertheless re-resolved live on every use, and the number
follows: resolving the root's provider derives or looks up its identity
and writes the result to the root inode's number.
Mode, owner, timestamps and number are therefore all current.

That the number follows is what keeps [Inode Identity and Lifecycle](</kernel/internals/stratafs/coherency/inode-identity-and-lifecycle.md#trm-4-4-3>)'s identity rule true at
the root. Identity belongs to the provider, so the number the root
reports is the number every other merged path to that same provider
reports; without it, a root whose provider is also reachable elsewhere
would report a different number from that other path — two paths naming
one object, unequal. <a id="cite-inode.root.agrees-with-other-paths-to-its-provider"></a> That is the false-inequality direction, the one
that breaks hard-link detection.

Where no stratum root exists at mount time, the root receives a stable
synthetic number, distinct from derived provider numbers. If a provider
later appears, the root's number follows that provider.
<a id="cite-inode.root.synthetic-without-a-provider"></a>

<a id="trm-4-4-3-2"></a>

## Attributes of merged directories <a id="cite-inode.merged-dir.attributes-from-provider"></a>

A merged directory's owner, group, mode and timestamps are its
provider's — the highest-precedence participating directory — taken
straight from a `getattr` on the provider path, so what is reported is
a real directory's attributes rather than a composite.

The security descriptor of a merged directory is not a single
descriptor; [Checks on Merged Directories](</kernel/internals/stratafs/security/checks-on-merged-directories.md#trm-4-6-2>) defines which participating directory's descriptor
governs each operation.

<a id="trm-4-4-3-2-1"></a>

### The synthetic link count <a id="cite-inode.merged-dir.nlink-forced-to-1"></a>

Its link count is forced to 1, both in the cached inode and in the
reported `stat`. The true count of subdirectories spans strata and
cannot be maintained, so the value carries no meaning beyond indicating
that the object is a directory. Nothing should infer a subdirectory
count from it.

<a id="trm-4-4-3-3"></a>

## Provider change <a id="cite-inode.never-rebound-by-resolution"></a>

When the provider for a path changes — because a higher-precedence
stratum gained the name, because the previous provider's entry was
removed, or because copy-up produced a new object — a **resolution** of
that path yields a new inode. An inode reached by resolution is never
re-associated with a different provider.

That is required because per-inode state is populated from the provider
the inode was resolved against and is not in general re-derivable. In
particular KACS caches a security descriptor against the outer stratafs
inode; applying it to a different provider's object would govern access
to one object by another object's descriptor.

The implementation enforces this bluntly. The one function that
re-associates an inode with a new provider is reachable from exactly
one call site, on the descriptor-private dentry created at open, and
never on a hashed dentry reached by resolution. A copy-up performed for
a path rather than a descriptor drops the dentry instead of rebinding
it. Provider change by masking or removal needs no special handling at
all, because the unconditional invalidation of [Revalidation](</kernel/internals/stratafs/coherency/model-and-revalidation.md#trm-4-4-2>) forces a fresh
lookup and a fresh inode.

An object's reported inode number therefore changes when its provider
changes. That is expected: it is the same change a caller would observe
if the file had been replaced, which is what has happened.

<a id="trm-4-4-3-3-1"></a>

### Descriptors already open <a id="cite-inode.copy-up.descriptor-keeps-inode"></a>

A descriptor open at the moment its own operation copies its object up
is not re-pointed. It keeps the inode it was opened against, and that
inode's backing object becomes the copy: the provider path and provider
inode are swapped in place under a per-inode lock, the attributes are
refreshed, and the backing file is replaced, so subsequent operations
through the descriptor reach the copy.

This is the one case in which an inode's backing object changes, and it
is safe for the reason the general rule exists: copy-up preserves the
source's security descriptor exactly ([Descriptors on Copy-Up](</kernel/internals/stratafs/security/copy-up-descriptors.md#trm-4-6-3>)), so the descriptor cached
on that inode remains correct for the copy.

At open, the descriptor-private inode is deliberately given the path
inode's number, so before any copy-up `fstat` and `stat` agree. After
one they do not: the descriptor keeps the number assigned to the
pre-copy-up provider, while a fresh resolution of the path derives or
allocates a number for the copy. Both name the copy; the numbers disagree for as
long as that descriptor lives. [Failure Modes](</kernel/internals/stratafs/start-here/failure-modes.md#trm-4-8>) records it.

<a id="trm-4-4-3-4"></a>

## Lifetime <a id="cite-inode.provider-reclaim-with-live-mount"></a>

A stratafs inode holds a reference on its provider inode for as long as
it lives, released on eviction. The dentry additionally holds a full
path reference. Ordinary derived identities add no provider reference
and no per-inode entry to the identity map. Walking a persistent-backed
view and dropping caches can therefore reclaim the provider inodes while
the stratafs mount remains live. The per-mount device-domain table stays
until unmount; its size tracks encountered filesystem domains rather
than the number of files walked.

The fallback alone adds a provider reference held until unmount. That
cost applies only to identities that could not be derived.

Renaming a provider out of the view and back, or evicting and reloading
its cached inode, preserves its derived identity. <a id="cite-inode.stable-across-cache-reclaim"></a>
Ordinary inode-number reuse by the provider after deletion remains
possible, just as it is when accessing that filesystem directly.

Releasing the last reference to a stratafs inode modifies nothing:
eviction truncates its own empty mapping, clears the inode, drops the
provider reference, and frees its private state.

---

# Block

_Peios Kernel / Internals / Block_

> Reference for Block.

<a id="rst-block"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [BFQ (Budget Fair Queueing)](</kernel/internals/block/bfq-iosched.md>)
- [Immutable biovecs and biovec iterators](</kernel/internals/block/biovecs.md>)
- [Multi-Queue Block IO Queueing Mechanism (blk-mq)](</kernel/internals/block/blk-mq.md>)
- [Embedded device command line partition parsing](</kernel/internals/block/cmdline-partition.md>)
- [Data Integrity](</kernel/internals/block/data-integrity.md>)
- [Deadline IO scheduler tunables](</kernel/internals/block/deadline-iosched.md>)
- [Inline Encryption](</kernel/internals/block/inline-encryption.md>)
- [Block io priorities](</kernel/internals/block/ioprio.md>)
- [Kyber I/O scheduler tunables](</kernel/internals/block/kyber-iosched.md>)
- [Null block device driver](</kernel/internals/block/null-blk.md>)
- [Block layer support for Persistent Reservations](</kernel/internals/block/pr.md>)
- [Block layer statistics in /sys/block/&lt;dev&gt;/stat](</kernel/internals/block/stat.md>)
- [Switching Scheduler](</kernel/internals/block/switching-sched.md>)
- [Explicit volatile write back cache control](</kernel/internals/block/writeback-cache-control.md>)
- [Userspace block device driver (ublk driver)](</kernel/internals/block/ublk.md>)

---

# BFQ (Budget Fair Queueing)

_Peios Kernel / Internals / Block_

> BFQ is a proportional-share I/O scheduler, with some extra low-latency capabilities. In addition to cgroups support (blkio or io controllers), BFQ's main features are:

<a id="rst-bfq-budget-fair-queueing"></a>

BFQ is a proportional-share I/O scheduler, with some extra low-latency capabilities. In addition to cgroups support (blkio or io controllers), BFQ's main features are:

- BFQ guarantees a high system and application responsiveness, and a low latency for time-sensitive applications, such as audio or video players;

- BFQ distributes bandwidth, not just time, among processes or groups (switching back to time distribution when needed to keep throughput high).

In its default configuration, BFQ privileges latency over throughput. So, when needed for achieving a lower latency, BFQ builds schedules that may lead to a lower throughput. If your main or only goal, for a given device, is to achieve the maximum-possible throughput at all times, then do switch off all low-latency heuristics for that device, by setting low_latency to 0. See Section 3 for details on how to configure BFQ for the desired tradeoff between latency and throughput, or on how to maximize throughput.

As every I/O scheduler, BFQ adds some overhead to per-I/O-request processing. To give an idea of this overhead, the total, single-lock-protected, per-request processing time of BFQ---i.e., the sum of the execution times of the request insertion, dispatch and completion hooks---is, e.g., 1.9 us on an Intel Core [i7-2760QM@2.40GHz](<mailto:i7-2760QM@2.40GHz>) (dated CPU for notebooks; time measured with simple code instrumentation, and using the throughput-sync.sh script of the S suite \[1\], in performance-profiling mode). To put this result into context, the total, single-lock-protected, per-request execution time of the lightest I/O scheduler available in blk-mq, mq-deadline, is 0.7 us (mq-deadline is \~800 LOC, against \~10500 LOC for BFQ).

Scheduling overhead further limits the maximum IOPS that a CPU can process (already limited by the execution of the rest of the I/O stack). To give an idea of the limits with BFQ, on slow or average CPUs, here are, first, the limits of BFQ for three different CPUs, on, respectively, an average laptop, an old desktop, and a cheap embedded system, in case full hierarchical support is enabled (i.e., CONFIG_BFQ_GROUP_IOSCHED is set), but CONFIG_BFQ_CGROUP_DEBUG is not set (Section 4-2): - Intel i7-4850HQ: 400 KIOPS - AMD A8-3850: 250 KIOPS - ARM CortexTM-A53 Octa-core: 80 KIOPS

If CONFIG_BFQ_CGROUP_DEBUG is set (and of course full hierarchical support is enabled), then the sustainable throughput with BFQ decreases, because all blkio.bfq\* statistics are created and updated (Section 4-2). For BFQ, this leads to the following maximum sustainable throughputs, on the same systems as above: - Intel i7-4850HQ: 310 KIOPS - AMD A8-3850: 200 KIOPS - ARM CortexTM-A53 Octa-core: 56 KIOPS

BFQ works for multi-queue devices too.

<!-- The table of contents follow. Impatients can just jump to Section 3. -->

<!-- CONTENTS

1. When may BFQ be useful?
 1-1 Personal systems
 1-2 Server systems
2. How does BFQ work?
3. What are BFQ's tunables and how to properly configure BFQ?
4. BFQ group scheduling
 4-1 Service guarantees provided
 4-2 Interface -->

<a id="rst-when-may-bfq-be-useful"></a>

## 1. When may BFQ be useful?

BFQ provides the following benefits on personal and server systems.

<a id="rst-personal-systems"></a>

### 1-1 Personal systems

<a id="rst-low-latency-for-interactive-applications"></a>

#### Low latency for interactive applications

Regardless of the actual background workload, BFQ guarantees that, for interactive tasks, the storage device is virtually as responsive as if it was idle. For example, even if one or more of the following background workloads are being executed:

- one or more large files are being read, written or copied,

- a tree of source files is being compiled,

- one or more virtual machines are performing I/O,

- a software update is in progress,

- indexing daemons are scanning filesystems and updating their databases,

starting an application or loading a file from within an application takes about the same time as if the storage device was idle. As a comparison, with CFQ, NOOP or DEADLINE, and in the same conditions, applications experience high latencies, or even become unresponsive until the background workload terminates (also on SSDs).

<a id="rst-low-latency-for-soft-real-time-applications"></a>

#### Low latency for soft real-time applications

Also soft real-time applications, such as audio and video players/streamers, enjoy a low latency and a low drop rate, regardless of the background I/O workload. As a consequence, these applications do not suffer from almost any glitch due to the background workload.

<a id="rst-higher-speed-for-code-development-tasks"></a>

#### Higher speed for code-development tasks

If some additional workload happens to be executed in parallel, then BFQ executes the I/O-related components of typical code-development tasks (compilation, checkout, merge, etc.) much more quickly than CFQ, NOOP or DEADLINE.

<a id="rst-high-throughput"></a>

#### High throughput

On hard disks, BFQ achieves up to 30% higher throughput than CFQ, and up to 150% higher throughput than DEADLINE and NOOP, with all the sequential workloads considered in our tests. With random workloads, and with all the workloads on flash-based devices, BFQ achieves, instead, about the same throughput as the other schedulers.

<a id="rst-strong-fairness-bandwidth-and-delay-guarantees"></a>

#### Strong fairness, bandwidth and delay guarantees

BFQ distributes the device throughput, and not just the device time, among I/O-bound applications in proportion to their weights, with any workload and regardless of the device parameters. From these bandwidth guarantees, it is possible to compute a tight per-I/O-request delay guarantees by a simple formula. If not configured for strict service guarantees, BFQ switches to time-based resource sharing (only) for applications that would otherwise cause a throughput loss.

<a id="rst-server-systems"></a>

### 1-2 Server systems

Most benefits for server systems follow from the same service properties as above. In particular, regardless of whether additional, possibly heavy workloads are being served, BFQ guarantees:

- audio and video-streaming with zero or very low jitter and drop rate;

- fast retrieval of WEB pages and embedded objects;

- real-time recording of data in live-dumping applications (e.g., packet logging);

- responsiveness in local and remote access to a server.

<a id="rst-how-does-bfq-work"></a>

## 2. How does BFQ work?

BFQ is a proportional-share I/O scheduler, whose general structure, plus a lot of code, are borrowed from CFQ.

- Each process doing I/O on a device is associated with a weight and a `(bfq_)queue`.

- BFQ grants exclusive access to the device, for a while, to one queue (process) at a time, and implements this service model by associating every queue with a budget, measured in number of sectors.

  - After a queue is granted access to the device, the budget of the queue is decremented, on each request dispatch, by the size of the request.

  - The in-service queue is expired, i.e., its service is suspended, only if one of the following events occurs: 1) the queue finishes its budget, 2) the queue empties, 3) a "budget timeout" fires.

    - The budget timeout prevents processes doing random I/O from holding the device for too long and dramatically reducing throughput.

    - Actually, as in CFQ, a queue associated with a process issuing sync requests may not be expired immediately when it empties. In contrast, BFQ may idle the device for a short time interval, giving the process the chance to go on being served if it issues a new request in time. Device idling typically boosts the throughput on rotational devices and on non-queueing flash-based devices, if processes do synchronous and sequential I/O. In addition, under BFQ, device idling is also instrumental in guaranteeing the desired throughput fraction to processes issuing sync requests (see the description of the slice_idle tunable in this document, or \[1, 2\], for more details).

      - With respect to idling for service guarantees, if several processes are competing for the device at the same time, but all processes and groups have the same weight, then BFQ guarantees the expected throughput distribution without ever idling the device. Throughput is thus as high as possible in this common scenario.

    > - On flash-based storage with internal queueing of commands (typically NCQ), device idling happens to be always detrimental to throughput. So, with these devices, BFQ performs idling only when strictly needed for service guarantees, i.e., for guaranteeing low latency or fairness. In these cases, overall throughput may be sub-optimal. No solution currently exists to provide both strong service guarantees and optimal throughput on devices with internal queueing.

  - If low-latency mode is enabled (default configuration), BFQ executes some special heuristics to detect interactive and soft real-time applications (e.g., video or audio players/streamers), and to reduce their latency. The most important action taken to achieve this goal is to give to the queues associated with these applications more than their fair share of the device throughput. For brevity, we call it just "weight-raising" the whole sets of actions taken by BFQ to privilege these queues. In particular, BFQ provides a milder form of weight-raising for interactive applications, and a stronger form for soft real-time applications.

  - BFQ automatically deactivates idling for queues born in a burst of queue creations. In fact, these queues are usually associated with the processes of applications and services that benefit mostly from a high throughput. Examples are systemd during boot, or git grep.

  - As CFQ, BFQ merges queues performing interleaved I/O, i.e., performing random I/O that becomes mostly sequential if merged. Differently from CFQ, BFQ achieves this goal with a more reactive mechanism, called Early Queue Merge (EQM). EQM is so responsive in detecting interleaved I/O (cooperating processes), that it enables BFQ to achieve a high throughput, by queue merging, even for queues for which CFQ needs a different mechanism, preemption, to get a high throughput. As such, EQM is a unified mechanism to achieve a high throughput with interleaved I/O.

  - Queues are scheduled according to a variant of WF2Q+, named B-WF2Q+, and implemented using an augmented rb-tree to preserve an O(log N) overall complexity.  See \[2\] for more details. B-WF2Q+ is also ready for hierarchical scheduling, details in Section 4.

  - B-WF2Q+ guarantees a tight deviation with respect to an ideal, perfectly fair, and smooth service. In particular, B-WF2Q+ guarantees that each queue receives a fraction of the device throughput proportional to its weight, even if the throughput fluctuates, and regardless of: the device parameters, the current workload and the budgets assigned to the queue.

  - The last, budget-independence, property (although probably counterintuitive in the first place) is definitely beneficial, for the following reasons:

    - First, with any proportional-share scheduler, the maximum deviation with respect to an ideal service is proportional to the maximum budget (slice) assigned to queues. As a consequence, BFQ can keep this deviation tight, not only because of the accurate service of B-WF2Q+, but also because BFQ *does not* need to assign a larger budget to a queue to let the queue receive a higher fraction of the device throughput.

    - Second, BFQ is free to choose, for every process (queue), the budget that best fits the needs of the process, or best leverages the I/O pattern of the process. In particular, BFQ updates queue budgets with a simple feedback-loop algorithm that allows a high throughput to be achieved, while still providing tight latency guarantees to time-sensitive applications. When the in-service queue expires, this algorithm computes the next budget of the queue so as to:

      - Let large budgets be eventually assigned to the queues associated with I/O-bound applications performing sequential I/O: in fact, the longer these applications are served once got access to the device, the higher the throughput is.

      - Let small budgets be eventually assigned to the queues associated with time-sensitive applications (which typically perform sporadic and short I/O), because, the smaller the budget assigned to a queue waiting for service is, the sooner B-WF2Q+ will serve that queue (Subsec 3.3 in \[2\]).

- If several processes are competing for the device at the same time, but all processes and groups have the same weight, then BFQ guarantees the expected throughput distribution without ever idling the device. It uses preemption instead. Throughput is then much higher in this common scenario.

- ioprio classes are served in strict priority order, i.e., lower-priority queues are not served as long as there are higher-priority queues.  Among queues in the same class, the bandwidth is distributed in proportion to the weight of each queue. A very thin extra bandwidth is however guaranteed to the Idle class, to prevent it from starving.

<a id="rst-what-are-bfq-s-tunables-and-how-to-properly-configure-bfq"></a>

## 3. What are BFQ's tunables and how to properly configure BFQ?

Most BFQ tunables affect service guarantees (basically latency and fairness) and throughput. For full details on how to choose the desired tradeoff between service guarantees and throughput, see the parameters slice_idle, strict_guarantees and low_latency. For details on how to maximise throughput, see slice_idle, timeout_sync and max_budget. The other performance-related parameters have been inherited from, and have been preserved mostly for compatibility with CFQ. So far, no performance improvement has been reported after changing the latter parameters in BFQ.

In particular, the tunables back_seek-max, back_seek_penalty, fifo_expire_async and fifo_expire_sync below are the same as in CFQ. Their description is just copied from that for CFQ. Some considerations in the description of slice_idle are copied from CFQ too.

<a id="rst-per-process-ioprio-and-weight"></a>

### per-process ioprio and weight

Unless the cgroups interface is used (see "4. BFQ group scheduling"), weights can be assigned to processes only indirectly, through I/O priorities, and according to the relation: weight = (IOPRIO_BE_NR - ioprio) \* 10.

Beware that, if low-latency is set, then BFQ automatically raises the weight of the queues associated with interactive and soft real-time applications. Unset this tunable if you need/want to control weights.

<a id="rst-slice-idle"></a>

### slice_idle

This parameter specifies how long BFQ should idle for the next I/O request, when certain sync BFQ queues become empty. By default slice_idle is a non-zero value. Idling has a double purpose: boosting throughput and making sure that the desired throughput distribution is respected (see the description of how BFQ works, and, if needed, the papers referred there).

As for throughput, idling can be very helpful on highly seeky media like single spindle SATA/SAS disks where we can cut down on overall number of seeks and see improved throughput.

Setting slice_idle to 0 will remove all the idling on queues and one should see an overall improved throughput on faster storage devices like multiple SATA/SAS disks in hardware RAID configuration, as well as flash-based storage with internal command queueing (and parallelism).

So depending on storage and workload, it might be useful to set slice_idle=0.  In general for SATA/SAS disks and software RAID of SATA/SAS disks keeping slice_idle enabled should be useful. For any configurations where there are multiple spindles behind single LUN (Host based hardware RAID controller or for storage arrays), or with flash-based fast storage, setting slice_idle=0 might end up in better throughput and acceptable latencies.

Idling is however necessary to have service guarantees enforced in case of differentiated weights or differentiated I/O-request lengths. To see why, suppose that a given BFQ queue A must get several I/O requests served for each request served for another queue B. Idling ensures that, if A makes a new I/O request slightly after becoming empty, then no request of B is dispatched in the middle, and thus A does not lose the possibility to get more than one request dispatched before the next request of B is dispatched. Note that idling guarantees the desired differentiated treatment of queues only in terms of I/O-request dispatches. To guarantee that the actual service order then corresponds to the dispatch order, the strict_guarantees tunable must be set too.

There is an important flip side to idling: apart from the above cases where it is beneficial also for throughput, idling can severely impact throughput. One important case is random workload. Because of this issue, BFQ tends to avoid idling as much as possible, when it is not beneficial also for throughput (as detailed in Section 2). As a consequence of this behavior, and of further issues described for the strict_guarantees tunable, short-term service guarantees may be occasionally violated. And, in some cases, these guarantees may be more important than guaranteeing maximum throughput. For example, in video playing/streaming, a very low drop rate may be more important than maximum throughput. In these cases, consider setting the strict_guarantees parameter.

<a id="rst-slice-idle-us"></a>

### slice_idle_us

Controls the same tuning parameter as slice_idle, but in microseconds. Either tunable can be used to set idling behavior.  Afterwards, the other tunable will reflect the newly set value in sysfs.

<a id="rst-strict-guarantees"></a>

### strict_guarantees

If this parameter is set (default: unset), then BFQ

- always performs idling when the in-service queue becomes empty;

- forces the device to serve one I/O request at a time, by dispatching a new request only if there is no outstanding request.

In the presence of differentiated weights or I/O-request sizes, both the above conditions are needed to guarantee that every BFQ queue receives its allotted share of the bandwidth. The first condition is needed for the reasons explained in the description of the slice_idle tunable.  The second condition is needed because all modern storage devices reorder internally-queued requests, which may trivially break the service guarantees enforced by the I/O scheduler.

Setting strict_guarantees may evidently affect throughput.

<a id="rst-back-seek-max"></a>

### back_seek_max

This specifies, given in Kbytes, the maximum "distance" for backward seeking. The distance is the amount of space from the current head location to the sectors that are backward in terms of distance.

This parameter allows the scheduler to anticipate requests in the "backward" direction and consider them as being the "next" if they are within this distance from the current head location.

<a id="rst-back-seek-penalty"></a>

### back_seek_penalty

This parameter is used to compute the cost of backward seeking. If the backward distance of request is just 1/back_seek_penalty from a "front" request, then the seeking cost of two requests is considered equivalent.

So scheduler will not bias toward one or the other request (otherwise scheduler will bias toward front request). Default value of back_seek_penalty is 2.

<a id="rst-fifo-expire-async"></a>

### fifo_expire_async

This parameter is used to set the timeout of asynchronous requests. Default value of this is 250ms.

<a id="rst-fifo-expire-sync"></a>

### fifo_expire_sync

This parameter is used to set the timeout of synchronous requests. Default value of this is 125ms. In case to favor synchronous requests over asynchronous one, this value should be decreased relative to fifo_expire_async.

<a id="rst-low-latency"></a>

### low_latency

This parameter is used to enable/disable BFQ's low latency mode. By default, low latency mode is enabled. If enabled, interactive and soft real-time applications are privileged and experience a lower latency, as explained in more detail in the description of how BFQ works.

DISABLE this mode if you need full control on bandwidth distribution. In fact, if it is enabled, then BFQ automatically increases the bandwidth share of privileged applications, as the main means to guarantee a lower latency to them.

In addition, as already highlighted at the beginning of this document, DISABLE this mode if your only goal is to achieve a high throughput. In fact, privileging the I/O of some application over the rest may entail a lower throughput. To achieve the highest-possible throughput on a non-rotational device, setting slice_idle to 0 may be needed too (at the cost of giving up any strong guarantee on fairness and low latency).

<a id="rst-timeout-sync"></a>

### timeout_sync

Maximum amount of device time that can be given to a task (queue) once it has been selected for service. On devices with costly seeks, increasing this time usually increases maximum throughput. On the opposite end, increasing this time coarsens the granularity of the short-term bandwidth and latency guarantees, especially if the following parameter is set to zero.

<a id="rst-max-budget"></a>

### max_budget

Maximum amount of service, measured in sectors, that can be provided to a BFQ queue once it is set in service (of course within the limits of the above timeout). According to what was said in the description of the algorithm, larger values increase the throughput in proportion to the percentage of sequential I/O requests issued. The price of larger values is that they coarsen the granularity of short-term bandwidth and latency guarantees.

The default value is 0, which enables auto-tuning: BFQ sets max_budget to the maximum number of sectors that can be served during timeout_sync, according to the estimated peak rate.

For specific devices, some users have occasionally reported to have reached a higher throughput by setting max_budget explicitly, i.e., by setting max_budget to a higher value than 0. In particular, they have set max_budget to higher values than those to which BFQ would have set it with auto-tuning. An alternative way to achieve this goal is to just increase the value of timeout_sync, leaving max_budget equal to 0.

<a id="rst-group-scheduling-with-bfq"></a>

## 4. Group scheduling with BFQ

BFQ supports both cgroups-v1 and cgroups-v2 io controllers, namely blkio and io. In particular, BFQ supports weight-based proportional share. To activate cgroups support, set BFQ_GROUP_IOSCHED.

<a id="rst-service-guarantees-provided"></a>

### 4-1 Service guarantees provided

With BFQ, proportional share means true proportional share of the device bandwidth, according to group weights. For example, a group with weight 200 gets twice the bandwidth, and not just twice the time, of a group with weight 100.

BFQ supports hierarchies (group trees) of any depth. Bandwidth is distributed among groups and processes in the expected way: for each group, the children of the group share the whole bandwidth of the group in proportion to their weights. In particular, this implies that, for each leaf group, every process of the group receives the same share of the whole group bandwidth, unless the ioprio of the process is modified.

The resource-sharing guarantee for a group may partially or totally switch from bandwidth to time, if providing bandwidth guarantees to the group lowers the throughput too much. This switch occurs on a per-process basis: if a process of a leaf group causes throughput loss if served in such a way to receive its share of the bandwidth, then BFQ switches back to just time-based proportional share for that process.

<a id="rst-interface"></a>

### 4-2 Interface

To get proportional sharing of bandwidth with BFQ for a given device, BFQ must of course be the active scheduler for that device.

Within each group directory, the names of the files associated with BFQ-specific cgroup parameters and stats begin with the "bfq." prefix. So, with cgroups-v1 or cgroups-v2, the full prefix for BFQ-specific files is "blkio.bfq." or "io.bfq." For example, the group parameter to set the weight of a group with BFQ is blkio.bfq.weight or io.bfq.weight.

As for cgroups-v1 (blkio controller), the exact set of stat files created, and kept up-to-date by bfq, depends on whether CONFIG_BFQ_CGROUP_DEBUG is set. If it is set, then bfq creates all the stat files documented in [Documentation/admin-guide/cgroup-v1/blkio-controller.rst](/kernel/administration/admin-guide/cgroup-v1/blkio-controller.md). If, instead, CONFIG_BFQ_CGROUP_DEBUG is not set, then bfq creates only the files:



```text
blkio.bfq.io_service_bytes
blkio.bfq.io_service_bytes_recursive
blkio.bfq.io_serviced
blkio.bfq.io_serviced_recursive
```

The value of CONFIG_BFQ_CGROUP_DEBUG greatly influences the maximum throughput sustainable with bfq, because updating the blkio.bfq.\* stats is rather costly, especially for some of the stats enabled by CONFIG_BFQ_CGROUP_DEBUG.

<a id="rst-parameters"></a>

### Parameters

For each group, the following parameters can be set:

> - **weight**
>
>   This specifies the default weight for the cgroup inside its parent. Available values: 1..1000 (default: 100).
>
>   For cgroup v1, it is set by writing the value to `blkio.bfq.weight`.
>
>   For cgroup v2, it is set by writing the value to `io.bfq.weight`. (with an optional prefix of `default` and a space).
>
>   The linear mapping between ioprio and weights, described at the beginning of the tunable section, is still valid, but all weights higher than IOPRIO_BE_NR\*10 are mapped to ioprio 0.
>
>   Recall that, if low-latency is set, then BFQ automatically raises the weight of the queues associated with interactive and soft real-time applications. Unset this tunable if you need/want to control weights.
>
> - **weight_device**
>
>   This specifies a per-device weight for the cgroup. The syntax is `minor:major weight`. A weight of `0` may be used to reset to the default weight.
>
>   For cgroup v1, it is set by writing the value to `blkio.bfq.weight_device`.
>
>   For cgroup v2, the file name is `io.bfq.weight`.

- **\[1\]**

  P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O Scheduler", Proceedings of the First Workshop on Mobile System Technologies (MST-2015), May 2015.

  [http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf](<http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf>)

- **\[2\]**

  P. Valente and M. Andreolini, "Improving Application Responsiveness with the BFQ Disk I/O Scheduler", Proceedings of the 5th Annual International Systems and Storage Conference (SYSTOR '12), June 2012.

  Slightly extended version:

  [http://algogroup.unimore.it/people/paolo/disk_sched/bfq-v1-suite-results.pdf](<http://algogroup.unimore.it/people/paolo/disk_sched/bfq-v1-suite-results.pdf>)

- **\[3\]**

  [https://github.com/Algodev-github/S](<https://github.com/Algodev-github/S>)

---

# Immutable biovecs and biovec iterators

_Peios Kernel / Internals / Block_

> Kent Overstreet <kmo@daterainc.com>

<a id="rst-immutable-biovecs-and-biovec-iterators"></a>

Kent Overstreet &lt;[kmo@daterainc.com](<mailto:kmo@daterainc.com>)&gt;

As of 3.13, biovecs should never be modified after a bio has been submitted. Instead, we have a new struct bvec_iter which represents a range of a biovec - the iterator will be modified as the bio is completed, not the biovec.

More specifically, old code that needed to partially complete a bio would update bi_sector and bi_size, and advance bi_idx to the next biovec. If it ended up partway through a biovec, it would increment bv_offset and decrement bv_len by the number of bytes completed in that biovec.

In the new scheme of things, everything that must be mutated in order to partially complete a bio is segregated into struct bvec_iter: bi_sector, bi_size and bi_idx have been moved there; and instead of modifying bv_offset and bv_len, struct bvec_iter has bi_bvec_done, which represents the number of bytes completed in the current bvec.

There are a bunch of new helper macros for hiding the gory details - in particular, presenting the illusion of partially completed biovecs so that normal code doesn't have to deal with bi_bvec_done.

> - Driver code should no longer refer to biovecs directly; we now have bio_iovec() and bio_iter_iovec() macros that return literal struct biovecs, constructed from the raw biovecs but taking into account bi_bvec_done and bi_size.
>
>   bio_for_each_segment() has been updated to take a bvec_iter argument instead of an integer (that corresponded to bi_idx); for a lot of code the conversion just required changing the types of the arguments to bio_for_each_segment().
>
> - Advancing a bvec_iter is done with bio_advance_iter(); bio_advance() is a wrapper around bio_advance_iter() that operates on bio-&gt;bi_iter, and also advances the bio integrity's iter if present.
>
>   There is a lower level advance function - bvec_iter_advance() - which takes a pointer to a biovec, not a bio; this is used by the bio integrity code.

As of 5.12 bvec segments with zero bv_len are not supported.

<a id="rst-what-s-all-this-get-us"></a>

## What's all this get us?

Having a real iterator, and making biovecs immutable, has a number of advantages:

> - Before, iterating over bios was very awkward when you weren't processing exactly one bvec at a time - for example, bio_copy_data() in block/bio.c, which copies the contents of one bio into another. Because the biovecs wouldn't necessarily be the same size, the old code was tricky convoluted - it had to walk two different bios at the same time, keeping both bi_idx and and offset into the current biovec for each.
>
>   The new code is much more straightforward - have a look. This sort of pattern comes up in a lot of places; a lot of drivers were essentially open coding bvec iterators before, and having common implementation considerably simplifies a lot of code.
>
> - Before, any code that might need to use the biovec after the bio had been completed (perhaps to copy the data somewhere else, or perhaps to resubmit it somewhere else if there was an error) had to save the entire bvec array - again, this was being done in a fair number of places.
>
> - Biovecs can be shared between multiple bios - a bvec iter can represent an arbitrary range of an existing biovec, both starting and ending midway through biovecs. This is what enables efficient splitting of arbitrary bios. Note that this means we \_only\_ use bi_size to determine when we've reached the end of a bio, not bi_vcnt - and the bio_iovec() macro takes bi_size into account when constructing biovecs.
>
> - Splitting bios is now much simpler. The old bio_split() didn't even work on bios with more than a single bvec\! Now, we can efficiently split arbitrary size bios - because the new bio can share the old bio's biovec.
>
>   Care must be taken to ensure the biovec isn't freed while the split bio is still using it, in case the original bio completes first, though. Using bio_chain() when splitting bios helps with this.
>
> - Submitting partially completed bios is now perfectly fine - this comes up occasionally in stacking block drivers and various code (e.g. md and bcache) had some ugly workarounds for this.
>
>   It used to be the case that submitting a partially completed bio would work fine to \_most\_ devices, but since accessing the raw bvec array was the norm, not all drivers would respect bi_idx and those would break. Now, since all drivers \_must\_ go through the bvec iterator - and have been audited to make sure they are - submitting partially completed bios is perfectly fine.

<a id="rst-other-implications"></a>

## Other implications:

> - Almost all usage of bi_idx is now incorrect and has been removed; instead, where previously you would have used bi_idx you'd now use a bvec_iter, probably passing it to one of the helper macros.
>
>   I.e. instead of using bio_iovec_idx() (or bio-&gt;bi_iovec\[bio-&gt;bi_idx\]), you now use bio_iter_iovec(), which takes a bvec_iter and returns a literal struct bio_vec - constructed on the fly from the raw biovec but taking into account bi_bvec_done (and bi_size).
>
> - bi_vcnt can't be trusted or relied upon by driver code - i.e. anything that doesn't actually own the bio. The reason is twofold: firstly, it's not actually needed for iterating over the bio anymore - we only use bi_size. Secondly, when cloning a bio and reusing (a portion of) the original bio's biovec, in order to calculate bi_vcnt for the new bio we'd have to iterate over all the biovecs in the new bio - which is silly as it's not needed.
>
>   So, don't use bi_vcnt anymore.
>
> - The current interface allows the block layer to split bios as needed, so we could eliminate a lot of complexity particularly in stacked drivers. Code that creates bios can then create whatever size bios are convenient, and more importantly stacked drivers don't have to deal with both their own bio size limitations and the limitations of the underlying devices. Thus there's no need to define -&gt;merge_bvec_fn() callbacks for individual block drivers.

<a id="rst-usage-of-helpers"></a>

## Usage of helpers:

- The following helpers whose names have the suffix of `_all` can only be used on non-BIO_CLONED bio. They are usually used by filesystem code. Drivers shouldn't use them because the bio may have been split before it reached the driver.



```text
bio_for_each_segment_all()
bio_for_each_bvec_all()
bio_first_bvec_all()
bio_first_page_all()
bio_first_folio_all()
```

- The following helpers iterate over single-page segment. The passed 'struct bio_vec' will contain a single-page IO vector during the iteration:



  ```text
  bio_for_each_segment()
  bio_for_each_segment_all()
  ```

- The following helpers iterate over multi-page bvec. The passed 'struct bio_vec' will contain a multi-page IO vector during the iteration:



  ```text
  bio_for_each_bvec()
  bio_for_each_bvec_all()
  rq_for_each_bvec()
  ```

---

# Multi-Queue Block IO Queueing Mechanism (blk-mq)

_Peios Kernel / Internals / Block_

> The Multi-Queue Block IO Queueing Mechanism is an API to enable fast storage devices to achieve a huge number of input/output operations per second (IOPS) through queueing and submitting IO requests to block devices simultaneously,…

<a id="rst-multi-queue-block-io-queueing-mechanism-blk-mq"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Multi-Queue Block IO Queueing Mechanism is an API to enable fast storage devices to achieve a huge number of input/output operations per second (IOPS) through queueing and submitting IO requests to block devices simultaneously, benefiting from the parallelism offered by modern storage devices.

<a id="rst-introduction"></a>

## Introduction

<a id="rst-background"></a>

### Background

Magnetic hard disks have been the de facto standard from the beginning of the development of the kernel. The Block IO subsystem aimed to achieve the best performance possible for those devices with a high penalty when doing random access, and the bottleneck was the mechanical moving parts, a lot slower than any layer on the storage stack. One example of such optimization technique involves ordering read/write requests according to the current position of the hard disk head.

However, with the development of Solid State Drives and Non-Volatile Memories without mechanical parts nor random access penalty and capable of performing high parallel access, the bottleneck of the stack had moved from the storage device to the operating system. In order to take advantage of the parallelism in those devices' design, the multi-queue mechanism was introduced.

The former design had a single queue to store block IO requests with a single lock. That did not scale well in SMP systems due to dirty data in cache and the bottleneck of having a single lock for multiple processors. This setup also suffered with congestion when different processes (or the same process, moving to different CPUs) wanted to perform block IO. Instead of this, the blk-mq API spawns multiple queues with individual entry points local to the CPU, removing the need for a lock. A deeper explanation on how this works is covered in the following section ([Operation](<#rst-operation>)).

<a id="rst-operation"></a>

### Operation

When the userspace performs IO to a block device (reading or writing a file, for instance), blk-mq takes action: it will store and manage IO requests to the block device, acting as middleware between the userspace (and a file system, if present) and the block device driver.

blk-mq has two group of queues: software staging queues and hardware dispatch queues. When the request arrives at the block layer, it will try the shortest path possible: send it directly to the hardware queue. However, there are two cases that it might not do that: if there's an IO scheduler attached at the layer or if we want to try to merge requests. In both cases, requests will be sent to the software queue.

Then, after the requests are processed by software queues, they will be placed at the hardware queue, a second stage queue where the hardware has direct access to process those requests. However, if the hardware does not have enough resources to accept more requests, blk-mq will place requests on a temporary queue, to be sent in the future, when the hardware is able.

<a id="rst-software-staging-queues"></a>

#### Software staging queues

The block IO subsystem adds requests in the software staging queues (represented by struct blk_mq_ctx) in case that they weren't sent directly to the driver. A request is one or more BIOs. They arrived at the block layer through the data structure struct bio. The block layer will then build a new structure from it, the struct request that will be used to communicate with the device driver. Each queue has its own lock and the number of queues is defined by a per-CPU or per-node basis.

The staging queue can be used to merge requests for adjacent sectors. For instance, requests for sector 3-6, 6-7, 7-9 can become one request for 3-9. Even if random access to SSDs and NVMs have the same time of response compared to sequential access, grouped requests for sequential access decreases the number of individual requests. This technique of merging requests is called plugging.

Along with that, the requests can be reordered to ensure fairness of system resources (e.g. to ensure that no application suffers from starvation) and/or to improve IO performance, by an IO scheduler.

<a id="rst-io-schedulers"></a>

##### IO Schedulers

There are several schedulers implemented by the block layer, each one following a heuristic to improve the IO performance. They are "pluggable" (as in plug and play), in the sense of they can be selected at run time using sysfs. You can read more about Linux's IO schedulers [here](<https://www.kernel.org/doc/html/latest/block/index.html>)<a id="rst-here"></a>. The scheduling happens only between requests in the same queue, so it is not possible to merge requests from different queues, otherwise there would be cache trashing and a need to have a lock for each queue. After the scheduling, the requests are eligible to be sent to the hardware. One of the possible schedulers to be selected is the NONE scheduler, the most straightforward one. It will just place requests on whatever software queue the process is running on, without any reordering. When the device starts processing requests in the hardware queue (a.k.a. run the hardware queue), the software queues mapped to that hardware queue will be drained in sequence according to their mapping.

<a id="rst-hardware-dispatch-queues"></a>

#### Hardware dispatch queues

The hardware queue (represented by struct blk_mq_hw_ctx) is a struct used by device drivers to map the device submission queues (or device DMA ring buffer), and are the last step of the block layer submission code before the low level device driver taking ownership of the request. To run this queue, the block layer removes requests from the associated software queues and tries to dispatch to the hardware.

If it's not possible to send the requests directly to hardware, they will be added to a linked list (`hctx->dispatch`) of requests. Then, next time the block layer runs a queue, it will send the requests laying at the `dispatch` list first, to ensure a fairness dispatch with those requests that were ready to be sent first. The number of hardware queues depends on the number of hardware contexts supported by the hardware and its device driver, but it will not be more than the number of cores of the system. There is no reordering at this stage, and each software queue has a set of hardware queues to send requests for.

> [!NOTE]
>
> Neither the block layer nor the device protocols guarantee the order of completion of requests. This must be handled by higher layers, like the filesystem.

<a id="rst-tag-based-completion"></a>

#### Tag-based completion

In order to indicate which request has been completed, every request is identified by an integer, ranging from 0 to the dispatch queue size. This tag is generated by the block layer and later reused by the device driver, removing the need to create a redundant identifier. When a request is completed in the driver, the tag is sent back to the block layer to notify it of the finalization. This removes the need to do a linear search to find out which IO has been completed.

<a id="rst-further-reading"></a>

### Further reading

- [Linux Block IO: Introducing Multi-queue SSD Access on Multi-core Systems](<http://kernel.dk/blk-mq.pdf>)<a id="rst-linux-block-io-introducing-multi-queue-ssd-access-on-multi-core-systems"></a>

- [NOOP scheduler](<https://en.wikipedia.org/wiki/Noop_scheduler>)<a id="rst-noop-scheduler"></a>

- [Null block device driver](<https://www.kernel.org/doc/html/latest/block/null_blk.html>)<a id="rst-null-block-device-driver"></a>

<a id="rst-source-code-documentation"></a>

## Source code documentation


#### <a id="c-enum-blk_eh_timer_return"></a>`enum blk_eh_timer_return`

How the timeout handler should proceed

**Constants**

- `BLK_EH_DONE`: The block driver completed the command or will complete it at
  a later time.
- `BLK_EH_RESET_TIMER`: Reset the request timer and continue waiting for the
  request to complete.

#### <a id="c-struct-blk_mq_hw_ctx"></a>`struct blk_mq_hw_ctx`

State for a hardware queue facing the hardware block device

**Definition**

```c
struct blk_mq_hw_ctx {
        struct {
            spinlock_t lock;
            struct list_head        dispatch;
            unsigned long           state;
        };
        struct delayed_work     run_work;
        cpumask_var_t cpumask;
        int next_cpu;
        int next_cpu_batch;
        unsigned long           flags;
        void *sched_data;
        struct request_queue    *queue;
        struct blk_flush_queue  *fq;
        void *driver_data;
        struct sbitmap          ctx_map;
        struct blk_mq_ctx       *dispatch_from;
        unsigned int            dispatch_busy;
        unsigned short          type;
        unsigned short          nr_ctx;
        struct blk_mq_ctx       **ctxs;
        spinlock_t dispatch_wait_lock;
        wait_queue_entry_t dispatch_wait;
        atomic_t wait_index;
        struct blk_mq_tags      *tags;
        struct blk_mq_tags      *sched_tags;
        unsigned int            numa_node;
        unsigned int            queue_num;
        atomic_t nr_active;
        struct hlist_node       cpuhp_online;
        struct hlist_node       cpuhp_dead;
        struct kobject          kobj;
    #ifdef CONFIG_BLK_DEBUG_FS;
        struct dentry           *debugfs_dir;
        struct dentry           *sched_debugfs_dir;
    #endif;
        struct list_head        hctx_list;
};
```

**Members**

- `{unnamed_struct}`: anonymous
- `lock`: Protects the dispatch list.
- `dispatch`: Used for requests that are ready to be
  dispatched to the hardware but for some reason (e.g. lack of
  resources) could not be sent to the hardware. As soon as the
  driver can send new requests, requests at this list will
  be sent first for a fairer dispatch.
- `state`: BLK_MQ_S_* flags. Defines the state of the hw
  queue (active, scheduled to restart, stopped).
- `run_work`: Used for scheduling a hardware queue run at a later time.
- `cpumask`: Map of available CPUs where this hctx can run.
- `next_cpu`: Used by `blk_mq_hctx_next_cpu()` for round-robin CPU
  selection from **cpumask**.
- `next_cpu_batch`: Counter of how many works left in the batch before
  changing to the next CPU.
- `flags`: BLK_MQ_F_* flags. Defines the behaviour of the queue.
- `sched_data`: Pointer owned by the IO scheduler attached to a request
  queue. It's up to the IO scheduler how to use this pointer.
- `queue`: Pointer to the request queue that owns this hardware context.
- `fq`: Queue of requests that need to perform a flush operation.
- `driver_data`: Pointer to data owned by the block driver that created
  this hctx
- `ctx_map`: Bitmap for each software queue. If bit is on, there is a
  pending request in that software queue.
- `dispatch_from`: Software queue to be used when no scheduler was
  selected.
- `dispatch_busy`: Number used by `blk_mq_update_dispatch_busy()` to
  decide if the hw_queue is busy using Exponential Weighted Moving
  Average algorithm.
- `type`: HCTX_TYPE_* flags. Type of hardware queue.
- `nr_ctx`: Number of software queues.
- `ctxs`: Array of software queues.
- `dispatch_wait_lock`: Lock for dispatch_wait queue.
- `dispatch_wait`: Waitqueue to put requests when there is no tag
  available at the moment, to wait for another try in the future.
- `wait_index`: Index of next available dispatch_wait queue to insert
  requests.
- `tags`: Tags owned by the block driver. A tag at this set is only
  assigned when a request is dispatched from a hardware queue.
- `sched_tags`: Tags owned by I/O scheduler. If there is an I/O
  scheduler associated with a request queue, a tag is assigned when
  that request is allocated. Else, this member is not used.
- `numa_node`: NUMA node the storage adapter has been connected to.
- `queue_num`: Index of this hardware queue.
- `nr_active`: Number of active requests. Only used when a tag set is
  shared across request queues.
- `cpuhp_online`: List to store request if CPU is going to die
- `cpuhp_dead`: List to store request if some CPU die.
- `kobj`: Kernel object for sysfs.
- `debugfs_dir`: debugfs directory for this hardware queue. Named
  as cpu\<cpu_number>.
- `sched_debugfs_dir`: debugfs directory for the scheduler.
- `hctx_list`: if this hctx is not in use, this is an entry in
  q->unused_hctx_list.

#### <a id="c-struct-blk_mq_queue_map"></a>`struct blk_mq_queue_map`

Map software queues to hardware queues

**Definition**

```c
struct blk_mq_queue_map {
    unsigned int *mq_map;
    unsigned int nr_queues;
    unsigned int queue_offset;
};
```

**Members**

- `mq_map`: CPU ID to hardware queue index map. This is an array
  with nr_cpu_ids elements. Each element has a value in the range
  \[**queue_offset**, **queue_offset** + **nr_queues**).
- `nr_queues`: Number of hardware queues to map CPU IDs onto.
- `queue_offset`: First hardware queue to map onto. Used by the PCIe NVMe
  driver to map each hardware queue type (enum hctx_type) onto a distinct
  set of hardware queues.

#### <a id="c-enum-hctx_type"></a>`enum hctx_type`

Type of hardware queue

**Constants**

- `HCTX_TYPE_DEFAULT`: All I/O not otherwise accounted for.
- `HCTX_TYPE_READ`: Just for READ I/O.
- `HCTX_TYPE_POLL`: Polled I/O of any kind.
- `HCTX_MAX_TYPES`: Number of types of hctx.

#### <a id="c-struct-blk_mq_tag_set"></a>`struct blk_mq_tag_set`

tag set that can be shared between request queues

**Definition**

```c
struct blk_mq_tag_set {
    const struct blk_mq_ops *ops;
    struct blk_mq_queue_map map[HCTX_MAX_TYPES];
    unsigned int            nr_maps;
    unsigned int            nr_hw_queues;
    unsigned int            queue_depth;
    unsigned int            reserved_tags;
    unsigned int            cmd_size;
    int numa_node;
    unsigned int            timeout;
    unsigned int            flags;
    void *driver_data;
    struct blk_mq_tags      **tags;
    struct blk_mq_tags      *shared_tags;
    struct mutex            tag_list_lock;
    struct list_head        tag_list;
    struct srcu_struct      *srcu;
    struct srcu_struct      tags_srcu;
    struct rw_semaphore     update_nr_hwq_lock;
};
```

**Members**

- `ops`: Pointers to functions that implement block driver behavior.
- `map`: One or more ctx -> hctx mappings. One map exists for each
  hardware queue type (enum hctx_type) that the driver wishes
  to support. There are no restrictions on maps being of the
  same size, and it's perfectly legal to share maps between
  types.
- `nr_maps`: Number of elements in the **map** array. A number in the range
  \[1, HCTX_MAX_TYPES\].
- `nr_hw_queues`: Number of hardware queues supported by the block driver that
  owns this data structure.
- `queue_depth`: Number of tags per hardware queue, reserved tags included.
- `reserved_tags`: Number of tags to set aside for BLK_MQ_REQ_RESERVED tag
  allocations.
- `cmd_size`: Number of additional bytes to allocate per request. The block
  driver owns these additional bytes.
- `numa_node`: NUMA node the storage adapter has been connected to.
- `timeout`: Request processing timeout in jiffies.
- `flags`: Zero or more BLK_MQ_F_* flags.
- `driver_data`: Pointer to data owned by the block driver that created this
  tag set.
- `tags`: Tag sets. One tag set per hardware queue. Has **nr_hw_queues**
  elements.
- `shared_tags`: Shared set of tags. Has **nr_hw_queues** elements. If set,
  shared by all **tags**.
- `tag_list_lock`: Serializes tag_list accesses.
- `tag_list`: List of the request queues that use this tag set. See also
  request_queue.tag_set_list.
- `srcu`: Use as lock when type of the request queue is blocking
  (BLK_MQ_F_BLOCKING).
- `tags_srcu`: SRCU used to defer freeing of tags page_list to prevent
  use-after-free when iterating tags.
- `update_nr_hwq_lock`: Synchronize updating nr_hw_queues with add/del disk &
  switching elevator.

#### <a id="c-struct-blk_mq_queue_data"></a>`struct blk_mq_queue_data`

Data about a request inserted in a queue

**Definition**

```c
struct blk_mq_queue_data {
    struct request *rq;
    bool last;
};
```

**Members**

- `rq`: Request pointer.
- `last`: If it is the last request in the queue.

#### <a id="c-struct-blk_mq_ops"></a>`struct blk_mq_ops`

Callback functions that implements block driver behaviour.

**Definition**

```c
struct blk_mq_ops {
        blk_status_t (*queue_rq)(struct blk_mq_hw_ctx *, const struct blk_mq_queue_data *);
        void (*commit_rqs)(struct blk_mq_hw_ctx *);
        void (*queue_rqs)(struct rq_list *rqlist);
        int (*get_budget)(struct request_queue *);
        void (*put_budget)(struct request_queue *, int);
        void (*set_rq_budget_token)(struct request *, int);
        int (*get_rq_budget_token)(struct request *);
        enum blk_eh_timer_return (*timeout)(struct request *);
        int (*poll)(struct blk_mq_hw_ctx *, struct io_comp_batch *);
        void (*complete)(struct request *);
        int (*init_hctx)(struct blk_mq_hw_ctx *, void *, unsigned int);
        void (*exit_hctx)(struct blk_mq_hw_ctx *, unsigned int);
        int (*init_request)(struct blk_mq_tag_set *set, struct request *, unsigned int, unsigned int);
        void (*exit_request)(struct blk_mq_tag_set *set, struct request *, unsigned int);
        void (*cleanup_rq)(struct request *);
        bool (*busy)(struct request_queue *);
        void (*map_queues)(struct blk_mq_tag_set *set);
    #ifdef CONFIG_BLK_DEBUG_FS;
        void (*show_rq)(struct seq_file *m, struct request *rq);
    #endif;
};
```

**Members**

- `queue_rq`: Queue a new request from block IO.
- `commit_rqs`: If a driver uses bd->last to judge when to submit
  requests to hardware, it must define this function. In case of errors
  that make us stop issuing further requests, this hook serves the
  purpose of kicking the hardware (which the last request otherwise
  would have done).
- `queue_rqs`: Queue a list of new requests. Driver is guaranteed
  that each request belongs to the same queue. If the driver doesn't
  empty the **rqlist** completely, then the rest will be queued
  individually by the block layer upon return.
- `get_budget`: Reserve budget before queue request, once .queue_rq is
  run, it is driver's responsibility to release the
  reserved budget. Also we have to handle failure case
  of .get_budget for avoiding I/O deadlock.
- `put_budget`: Release the reserved budget.
- `set_rq_budget_token`: store rq's budget token
- `get_rq_budget_token`: retrieve rq's budget token
- `timeout`: Called on request timeout.
- `poll`: Called to poll for completion of a specific tag.
- `complete`: Mark the request as complete.
- `init_hctx`: Called when the block layer side of a hardware queue has
  been set up, allowing the driver to allocate/init matching
  structures.
- `exit_hctx`: Ditto for exit/teardown.
- `init_request`: Called for every command allocated by the block layer
  to allow the driver to set up driver specific data.

  Tag greater than or equal to queue_depth is for setting up
  flush request.
- `exit_request`: Ditto for exit/teardown.
- `cleanup_rq`: Called before freeing one request which isn't completed
  yet, and usually for freeing the driver private data.
- `busy`: If set, returns whether or not this queue currently is busy.
- `map_queues`: This allows drivers specify their own queue mapping by
  overriding the setup-time function that builds the mq_map.
- `show_rq`: Used by the debugfs implementation to show driver-specific
  information about a request.

#### <a id="c-blk_mq_rq_state"></a>`blk_mq_rq_state()`

```c
enum mq_rq_state blk_mq_rq_state(struct request *rq)
```

read the current MQ_RQ_* state of a request

**Parameters**

- `struct request *rq`: target request.

#### <a id="c-blk_mq_add_to_batch"></a>`blk_mq_add_to_batch()`

```c
bool blk_mq_add_to_batch(struct request *req, struct io_comp_batch *iob, bool is_error, void (*complete)(struct io_comp_batch *))
```

add a request to the completion batch

**Parameters**

- `struct request *req`: The request to add to batch
- `struct io_comp_batch *iob`: The batch to add the request
- `bool is_error`: Specify true if the request failed with an error
- `void (*complete)(struct io_comp_batch *)`: The completaion handler for the request

**Description**

Batched completions only work when there is no I/O error and no special
->end_io handler.

**Return**

true when the request was added to the batch, otherwise false

#### <a id="c-blk_mq_rq_from_pdu"></a>`blk_mq_rq_from_pdu()`

```c
struct request * blk_mq_rq_from_pdu(void *pdu)
```

cast a PDU to a request

**Parameters**

- `void *pdu`: the PDU (Protocol Data Unit) to be casted

**Return**

request

**Description**

Driver command data is immediately after the request. So subtract request
size to get back to the original request.

#### <a id="c-blk_mq_rq_to_pdu"></a>`blk_mq_rq_to_pdu()`

```c
void * blk_mq_rq_to_pdu(struct request *rq)
```

cast a request to a PDU

**Parameters**

- `struct request *rq`: the request to be casted

**Return**

pointer to the PDU

**Description**

Driver command data is immediately after the request. So add request to get
the PDU.

#### <a id="c-blk_rq_nr_bvec"></a>`blk_rq_nr_bvec()`

```c
unsigned int blk_rq_nr_bvec(struct request *rq)
```

return number of bvecs in a request

**Parameters**

- `struct request *rq`: request to calculate bvecs for

**Description**

Returns the number of bvecs.



#### <a id="c-blk_mq_wait_quiesce_done"></a>`blk_mq_wait_quiesce_done()`

```c
void blk_mq_wait_quiesce_done(struct blk_mq_tag_set *set)
```

wait until in-progress quiesce is done

**Parameters**

- `struct blk_mq_tag_set *set`: tag_set to wait on

**Note**

it is driver's responsibility for making sure that quiesce has
been started on or more of the request_queues of the tag_set.  This
function only waits for the quiesce on those request_queues that had
the quiesce flag set using blk_mq_quiesce_queue_nowait.

#### <a id="c-blk_mq_quiesce_queue"></a>`blk_mq_quiesce_queue()`

```c
void blk_mq_quiesce_queue(struct request_queue *q)
```

wait until all ongoing dispatches have finished

**Parameters**

- `struct request_queue *q`: request queue.

**Note**

this function does not prevent that the struct request `end_io()`
callback function is invoked. Once this function is returned, we make
sure no dispatch can happen until the queue is unquiesced via
`blk_mq_unquiesce_queue()`.

#### <a id="c-blk_update_request"></a>`blk_update_request()`

```c
bool blk_update_request(struct request *req, blk_status_t error, unsigned int nr_bytes)
```

Complete multiple bytes without completing the request

**Parameters**

- `struct request *req`: the request being processed
- `blk_status_t error`: block status code
- `unsigned int nr_bytes`: number of bytes to complete for **req**

**Description**

Ends I/O on a number of bytes attached to **req**, but doesn't complete
the request structure even if **req** doesn't have leftover.
If **req** has leftover, sets it up for the next range of segments.

Passing the result of `blk_rq_bytes()` as **nr_bytes** guarantees
`false` return from this function.

**Note**

The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
except in the consistency check at the end of this function.

**Return**

`false` - this request doesn't have any more data
`true`  - this request has more data

#### <a id="c-blk_mq_complete_request"></a>`blk_mq_complete_request()`

```c
void blk_mq_complete_request(struct request *rq)
```

end I/O on a request

**Parameters**

- `struct request *rq`: the request being processed

**Description**

Complete a request by scheduling the ->complete_rq operation.

#### <a id="c-blk_mq_start_request"></a>`blk_mq_start_request()`

```c
void blk_mq_start_request(struct request *rq)
```

Start processing a request

**Parameters**

- `struct request *rq`: Pointer to request to be started

**Description**

Function used by device drivers to notify the block layer that a request
is going to be processed now, so blk layer can do proper initializations
such as starting the timeout timer.

#### <a id="c-blk_execute_rq_nowait"></a>`blk_execute_rq_nowait()`

```c
void blk_execute_rq_nowait(struct request *rq, bool at_head)
```

insert a request to I/O scheduler for execution

**Parameters**

- `struct request *rq`: request to insert
- `bool at_head`: insert request at head or tail of queue

**Description**

Insert a fully prepared request at the back of the I/O scheduler queue
for execution.  Don't wait for completion.

**Note**

This function will invoke **done** directly if the queue is dead.

#### <a id="c-blk_execute_rq"></a>`blk_execute_rq()`

```c
blk_status_t blk_execute_rq(struct request *rq, bool at_head)
```

insert a request into queue for execution

**Parameters**

- `struct request *rq`: request to insert
- `bool at_head`: insert request at head or tail of queue

**Description**

Insert a fully prepared request at the back of the I/O scheduler queue
for execution and wait for completion.

**Return**

The blk_status_t result provided to `blk_mq_end_request()`.

#### <a id="c-blk_mq_delay_run_hw_queue"></a>`blk_mq_delay_run_hw_queue()`

```c
void blk_mq_delay_run_hw_queue(struct blk_mq_hw_ctx *hctx, unsigned long msecs)
```

Run a hardware queue asynchronously.

**Parameters**

- `struct blk_mq_hw_ctx *hctx`: Pointer to the hardware queue to run.
- `unsigned long msecs`: Milliseconds of delay to wait before running the queue.

**Description**

Run a hardware queue asynchronously with a delay of **msecs**.

#### <a id="c-blk_mq_run_hw_queue"></a>`blk_mq_run_hw_queue()`

```c
void blk_mq_run_hw_queue(struct blk_mq_hw_ctx *hctx, bool async)
```

Start to run a hardware queue.

**Parameters**

- `struct blk_mq_hw_ctx *hctx`: Pointer to the hardware queue to run.
- `bool async`: If we want to run the queue asynchronously.

**Description**

Check if the request queue is not in a quiesced state and if there are
pending requests to be sent. If this is true, run the queue to send requests
to hardware.

#### <a id="c-blk_mq_run_hw_queues"></a>`blk_mq_run_hw_queues()`

```c
void blk_mq_run_hw_queues(struct request_queue *q, bool async)
```

Run all hardware queues in a request queue.

**Parameters**

- `struct request_queue *q`: Pointer to the request queue to run.
- `bool async`: If we want to run the queue asynchronously.

#### <a id="c-blk_mq_delay_run_hw_queues"></a>`blk_mq_delay_run_hw_queues()`

```c
void blk_mq_delay_run_hw_queues(struct request_queue *q, unsigned long msecs)
```

Run all hardware queues asynchronously.

**Parameters**

- `struct request_queue *q`: Pointer to the request queue to run.
- `unsigned long msecs`: Milliseconds of delay to wait before running the queues.

#### <a id="c-blk_mq_request_bypass_insert"></a>`blk_mq_request_bypass_insert()`

```c
void blk_mq_request_bypass_insert(struct request *rq, blk_insert_t flags)
```

Insert a request at dispatch list.

**Parameters**

- `struct request *rq`: Pointer to request to be inserted.
- `blk_insert_t flags`: BLK_MQ_INSERT_*

**Description**

Should only be used carefully, when the caller knows we want to
bypass a potential IO scheduler on the target device.

#### <a id="c-blk_mq_try_issue_directly"></a>`blk_mq_try_issue_directly()`

```c
void blk_mq_try_issue_directly(struct blk_mq_hw_ctx *hctx, struct request *rq)
```

Try to send a request directly to device driver.

**Parameters**

- `struct blk_mq_hw_ctx *hctx`: Pointer of the associated hardware queue.
- `struct request *rq`: Pointer to request to be sent.

**Description**

If the device has enough resources to accept a new request now, send the
request directly to device driver. Else, insert at hctx->dispatch queue, so
we can try send it another time in the future. Requests inserted at this
queue have higher priority.

#### <a id="c-blk_mq_submit_bio"></a>`blk_mq_submit_bio()`

```c
void blk_mq_submit_bio(struct bio *bio)
```

Create and send a request to block device.

**Parameters**

- `struct bio *bio`: Bio pointer.

**Description**

Builds up a request structure from **q** and **bio** and send to the device. The
request may not be queued directly to hardware if:
* This request can be merged with another one
* We want to place request at plug queue for possible future merging
* There is an IO scheduler active at this queue

It will not queue the request if there is an error with the bio, or at the
request creation.

#### <a id="c-blk_insert_cloned_request"></a>`blk_insert_cloned_request()`

```c
blk_status_t blk_insert_cloned_request(struct request *rq)
```

Helper for stacking drivers to submit a request

**Parameters**

- `struct request *rq`: the request being queued

#### <a id="c-blk_rq_unprep_clone"></a>`blk_rq_unprep_clone()`

```c
void blk_rq_unprep_clone(struct request *rq)
```

Helper function to free all bios in a cloned request

**Parameters**

- `struct request *rq`: the clone request to be cleaned up

**Description**

Free all bios in **rq** for a cloned request.

#### <a id="c-blk_rq_prep_clone"></a>`blk_rq_prep_clone()`

```c
int blk_rq_prep_clone(struct request *rq, struct request *rq_src, struct bio_set *bs, gfp_t gfp_mask, int (*bio_ctr)(struct bio *, struct bio *, void *), void *data)
```

Helper function to setup clone request

**Parameters**

- `struct request *rq`: the request to be setup
- `struct request *rq_src`: original request to be cloned
- `struct bio_set *bs`: bio_set that bios for clone are allocated from
- `gfp_t gfp_mask`: memory allocation mask for bio
- `int (*bio_ctr)(struct bio *, struct bio *, void *)`: setup function to be called for each clone bio.
  Returns `0` for success, non `0` for failure.
- `void *data`: private data to be passed to **bio_ctr**

**Description**

Clones bios in **rq_src** to **rq**, and copies attributes of **rq_src** to **rq**.
Also, pages which the original bios are pointing to are not copied
and the cloned bios just point same pages.
So cloned bios must be completed before original bios, which means
the caller must complete **rq** before **rq_src**.

#### <a id="c-blk_mq_destroy_queue"></a>`blk_mq_destroy_queue()`

```c
void blk_mq_destroy_queue(struct request_queue *q)
```

shutdown a request queue

**Parameters**

- `struct request_queue *q`: request queue to shutdown

**Description**

This shuts down a request queue allocated by `blk_mq_alloc_queue()`. All future
requests will be failed with -ENODEV. The caller is responsible for dropping
the reference from `blk_mq_alloc_queue()` by calling [`blk_put_queue()`](/kernel/internals/core-api/kernel-api.md#c-blk_put_queue).

**Context**

can sleep

---

# Embedded device command line partition parsing

_Peios Kernel / Internals / Block_

> The "blkdevparts" command line option adds support for reading the block device partition table from the kernel command line.

<a id="rst-embedded-device-command-line-partition-parsing"></a>

The "blkdevparts" command line option adds support for reading the block device partition table from the kernel command line.

It is typically used for fixed block (eMMC) embedded devices. It has no MBR, so saves storage space. Bootloader can be easily accessed by absolute address of data on the block device. Users can easily change the partition.

The format for the command line is just like mtdparts:

- **blkdevparts=&lt;blkdev-def&gt;\[;&lt;blkdev-def&gt;\]**

  - **&lt;blkdev-def&gt; := &lt;blkdev-id&gt;:&lt;partdef&gt;\[,&lt;partdef&gt;\]**

    &lt;partdef&gt; := &lt;size&gt;\[@&lt;offset&gt;\](part-name)

- **&lt;blkdev-id&gt;**

  block device disk name. Embedded device uses fixed block device. Its disk name is also fixed, such as: mmcblk0, mmcblk1, mmcblk0boot0.

- **&lt;size&gt;**

  partition size, in bytes, such as: 512, 1m, 1G. size may contain an optional suffix of (upper or lower case):

  > K, M, G, T, P, E.

  "-" is used to denote all remaining space.

- **&lt;offset&gt;**

  partition start address, in bytes. offset may contain an optional suffix of (upper or lower case):

  > K, M, G, T, P, E.

- **(part-name)**

  partition name. Kernel sends uevent with "PARTNAME". Application can create a link to block device partition with the name "PARTNAME". User space application can access partition by partition name.

- **ro**

  read-only. Flag the partition as read-only.

Example:

> > eMMC disk names are "mmcblk0" and "mmcblk0boot0".
>
> bootargs:
>
>
>
> ```text
> 'blkdevparts=mmcblk0:1G(data0),1G(data1),-;mmcblk0boot0:1m(boot)ro,-(kernel)'
> ```
>
> dmesg:
>
>
>
> ```text
> mmcblk0: p1(data0) p2(data1) p3()
> mmcblk0boot0: p1(boot) p2(kernel)
> ```

---

# Data Integrity

_Peios Kernel / Internals / Block_

> Modern filesystems feature checksumming of data and metadata to protect against data corruption. However, the detection of the corruption is done at read time which could potentially be months after the data was written. At that point the…

<a id="rst-data-integrity"></a>

<a id="rst-introduction"></a>

## 1. Introduction

Modern filesystems feature checksumming of data and metadata to protect against data corruption.  However, the detection of the corruption is done at read time which could potentially be months after the data was written.  At that point the original data that the application tried to write is most likely lost.

The solution is to ensure that the disk is actually storing what the application meant it to.  Recent additions to both the SCSI family protocols (SBC Data Integrity Field, SCC protection proposal) as well as SATA/T13 (External Path Protection) try to remedy this by adding support for appending integrity metadata to an I/O.  The integrity metadata (or protection information in SCSI terminology) includes a checksum for each sector as well as an incrementing counter that ensures the individual sectors are written in the right order.  And for some protection schemes also that the I/O is written to the right place on disk.

Current storage controllers and devices implement various protective measures, for instance checksumming and scrubbing.  But these technologies are working in their own isolated domains or at best between adjacent nodes in the I/O path.  The interesting thing about DIF and the other integrity extensions is that the protection format is well defined and every node in the I/O path can verify the integrity of the I/O and reject it if corruption is detected.  This allows not only corruption prevention but also isolation of the point of failure.

<a id="rst-the-data-integrity-extensions"></a>

## 2. The Data Integrity Extensions

As written, the protocol extensions only protect the path between controller and storage device.  However, many controllers actually allow the operating system to interact with the integrity metadata (IMD).  We have been working with several FC/SAS HBA vendors to enable the protection information to be transferred to and from their controllers.

The SCSI Data Integrity Field works by appending 8 bytes of protection information to each sector.  The data + integrity metadata is stored in 520 byte sectors on disk.  Data + IMD are interleaved when transferred between the controller and target.  The T13 proposal is similar.

Because it is highly inconvenient for operating systems to deal with 520 (and 4104) byte sectors, we approached several HBA vendors and encouraged them to allow separation of the data and integrity metadata scatter-gather lists.

The controller will interleave the buffers on write and split them on read.  This means that Linux can DMA the data buffers to and from host memory without changes to the page cache.

Also, the 16-bit CRC checksum mandated by both the SCSI and SATA specs is somewhat heavy to compute in software.  Benchmarks found that calculating this checksum had a significant impact on system performance for a number of workloads.  Some controllers allow a lighter-weight checksum to be used when interfacing with the operating system.  Emulex, for instance, supports the TCP/IP checksum instead. The IP checksum received from the OS is converted to the 16-bit CRC when writing and vice versa.  This allows the integrity metadata to be generated by Linux or the application at very low cost (comparable to software RAID5).

The IP checksum is weaker than the CRC in terms of detecting bit errors.  However, the strength is really in the separation of the data buffers and the integrity metadata.  These two distinct buffers must match up for an I/O to complete.

The separation of the data and integrity metadata buffers as well as the choice in checksums is referred to as the Data Integrity Extensions.  As these extensions are outside the scope of the protocol bodies (T10, T13), Oracle and its partners are trying to standardize them within the Storage Networking Industry Association.

<a id="rst-kernel-changes"></a>

## 3. Kernel Changes

The data integrity framework in Linux enables protection information to be pinned to I/Os and sent to/received from controllers that support it.

The advantage to the integrity extensions in SCSI and SATA is that they enable us to protect the entire path from application to storage device.  However, at the same time this is also the biggest disadvantage. It means that the protection information must be in a format that can be understood by the disk.

Generally Linux/POSIX applications are agnostic to the intricacies of the storage devices they are accessing.  The virtual filesystem switch and the block layer make things like hardware sector size and transport protocols completely transparent to the application.

However, this level of detail is required when preparing the protection information to send to a disk.  Consequently, the very concept of an end-to-end protection scheme is a layering violation. It is completely unreasonable for an application to be aware whether it is accessing a SCSI or SATA disk.

The data integrity support implemented in Linux attempts to hide this from the application.  As far as the application (and to some extent the kernel) is concerned, the integrity metadata is opaque information that's attached to the I/O.

The current implementation allows the block layer to automatically generate the protection information for any I/O.  Eventually the intent is to move the integrity metadata calculation to userspace for user data.  Metadata and other I/O that originates within the kernel will still use the automatic generation interface.

Some storage devices allow each hardware sector to be tagged with a 16-bit value.  The owner of this tag space is the owner of the block device.  I.e. the filesystem in most cases.  The filesystem can use this extra space to tag sectors as they see fit.  Because the tag space is limited, the block interface allows tagging bigger chunks by way of interleaving.  This way, 8\*16 bits of information can be attached to a typical 4KB filesystem block.

This also means that applications such as fsck and mkfs will need access to manipulate the tags from user space.  A passthrough interface for this is being worked on.

<a id="rst-block-layer-implementation-details"></a>

## 4. Block Layer Implementation Details

<a id="rst-bio"></a>

### 4.1 Bio

The data integrity patches add a new field to struct bio when CONFIG_BLK_DEV_INTEGRITY is enabled.  bio_integrity(bio) returns a pointer to a struct bip which contains the bio integrity payload. Essentially a bip is a trimmed down struct bio which holds a bio_vec containing the integrity metadata and the required housekeeping information (bvec pool, vector count, etc.)

A kernel subsystem can enable data integrity protection on a bio by calling bio_integrity_alloc(bio).  This will allocate and attach the bip to the bio.

Individual pages containing integrity metadata can subsequently be attached using bio_integrity_add_page().

bio_free() will automatically free the bip.

<a id="rst-block-device"></a>

### 4.2 Block Device

Block devices can set up the integrity information in the integrity sub-struture of the queue_limits structure.

Layered block devices will need to pick a profile that's appropriate for all subdevices.  queue_limits_stack_integrity() can help with that.  DM and MD linear, RAID0 and RAID1 are currently supported.  RAID4/5/6 will require extra work due to the application tag.

<a id="rst-block-layer-integrity-api"></a>

## 5.0 Block Layer Integrity API

<a id="rst-normal-filesystem"></a>

### 5.1 Normal Filesystem

> The normal filesystem is unaware that the underlying block device is capable of sending/receiving integrity metadata.  The IMD will be automatically generated by the block layer at submit_bio() time in case of a WRITE.  A READ request will cause the I/O integrity to be verified upon completion.
>
> IMD generation and verification can be toggled using the:
>
>
>
> ```text
> /sys/block/<bdev>/integrity/write_generate
> ```
>
> and:
>
>
>
> ```text
> /sys/block/<bdev>/integrity/read_verify
> ```
>
> flags.

<a id="rst-integrity-aware-filesystem"></a>

### 5.2 Integrity-Aware Filesystem

> A filesystem that is integrity-aware can prepare I/Os with IMD attached.  It can also use the application tag space if this is supported by the block device.
>
> `bool bio_integrity_prep(bio);`
>
> > To generate IMD for WRITE and to set up buffers for READ, the filesystem must call bio_integrity_prep(bio).
> >
> > Prior to calling this function, the bio data direction and start sector must be set, and the bio should have all data pages added.  It is up to the caller to ensure that the bio does not change while I/O is in progress. Complete bio with error if prepare failed for some reason.

<a id="rst-passing-existing-integrity-metadata"></a>

### 5.3 Passing Existing Integrity Metadata

> Filesystems that either generate their own integrity metadata or are capable of transferring IMD from user space can use the following calls:
>
> `struct bip * bio_integrity_alloc(bio, gfp_mask, nr_pages);`
>
> > Allocates the bio integrity payload and hangs it off of the bio. nr_pages indicate how many pages of protection data need to be stored in the integrity bio_vec list (similar to bio_alloc()).
> >
> > The integrity payload will be freed at bio_free() time.
>
> `int bio_integrity_add_page(bio, page, len, offset);`
>
> > Attaches a page containing integrity metadata to an existing bio.  The bio must have an existing bip, i.e. bio_integrity_alloc() must have been called.  For a WRITE, the integrity metadata in the pages must be in a format understood by the target device with the notable exception that the sector numbers will be remapped as the request traverses the I/O stack.  This implies that the pages added using this call will be modified during I/O\!  The first reference tag in the integrity metadata must have a value of bip-&gt;bip_sector.
> >
> > Pages can be added using bio_integrity_add_page() as long as there is room in the bip bio_vec array (nr_pages).
> >
> > Upon completion of a READ operation, the attached pages will contain the integrity metadata received from the storage device. It is up to the receiver to process them and verify data integrity upon completion.

---

2007-12-24 Martin K. Petersen &lt;[martin.petersen@oracle.com](<mailto:martin.petersen@oracle.com>)&gt;

---

# Deadline IO scheduler tunables

_Peios Kernel / Internals / Block_

> This little file attempts to document how the deadline io scheduler works. In particular, it will clarify the meaning of the exposed tunables that may be of interest to power users.

<a id="rst-deadline-io-scheduler-tunables"></a>

This little file attempts to document how the deadline io scheduler works. In particular, it will clarify the meaning of the exposed tunables that may be of interest to power users.

<a id="rst-selecting-io-schedulers"></a>

## Selecting IO schedulers

Refer to [Documentation/block/switching-sched.rst](/kernel/internals/block/switching-sched.md) for information on selecting an io scheduler on a per-device basis.

---

<a id="rst-read-expire-in-ms"></a>

## read_expire     (in ms)

The goal of the deadline io scheduler is to attempt to guarantee a start service time for a request. As we focus mainly on read latencies, this is tunable. When a read request first enters the io scheduler, it is assigned a deadline that is the current time + the read_expire value in units of milliseconds.

<a id="rst-write-expire-in-ms"></a>

## write_expire    (in ms)

Similar to read_expire mentioned above, but for writes.

<a id="rst-fifo-batch-number-of-requests"></a>

## fifo_batch      (number of requests)

Requests are grouped into `batches` of a particular data direction (read or write) which are serviced in increasing sector order.  To limit extra seeking, deadline expiries are only checked between batches.  fifo_batch controls the maximum number of requests per batch.

This parameter tunes the balance between per-request latency and aggregate throughput.  When low latency is the primary concern, smaller is better (where a value of 1 yields first-come first-served behaviour).  Increasing fifo_batch generally improves throughput, at the cost of latency variation.

<a id="rst-writes-starved-number-of-dispatches"></a>

## writes_starved  (number of dispatches)

When we have to move requests from the io scheduler queue to the block device dispatch queue, we always give a preference to reads. However, we don't want to starve writes indefinitely either. So writes_starved controls how many times we give preference to reads over writes. When that has been done writes_starved number of times, we dispatch some writes based on the same criteria as reads.

<a id="rst-front-merges-bool"></a>

## front_merges    (bool)

Sometimes it happens that a request enters the io scheduler that is contiguous with a request that is already on the queue. Either it fits in the back of that request, or it fits at the front. That is called either a back merge candidate or a front merge candidate. Due to the way files are typically laid out, back merges are much more common than front merges. For some work loads, you may even know that it is a waste of time to spend any time attempting to front merge requests. Setting front_merges to 0 disables this functionality. Front merges may still occur due to the cached last_merge hint, but since that comes at basically 0 cost we leave that on. We simply disable the rbtree front sector lookup when the io scheduler merge function is called.

Nov 11 2002, Jens Axboe &lt;[jens.axboe@oracle.com](<mailto:jens.axboe@oracle.com>)&gt;

---

# Inline Encryption

_Peios Kernel / Internals / Block_

> Inline encryption hardware sits logically between memory and disk, and can en/decrypt data as it goes in/out of the disk. For each I/O request, software can control exactly how the inline encryption hardware will en/decrypt the data in…

<a id="rst-inline-encryption-1"></a>
<a id="rst-inline-encryption"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

Inline encryption hardware sits logically between memory and disk, and can en/decrypt data as it goes in/out of the disk.  For each I/O request, software can control exactly how the inline encryption hardware will en/decrypt the data in terms of key, algorithm, data unit size (the granularity of en/decryption), and data unit number (a value that determines the initialization vector(s)).

Some inline encryption hardware accepts all encryption parameters including raw keys directly in low-level I/O requests.  However, most inline encryption hardware instead has a fixed number of "keyslots" and requires that the key, algorithm, and data unit size first be programmed into a keyslot.  Each low-level I/O request then just contains a keyslot index and data unit number.

Note that inline encryption hardware is very different from traditional crypto accelerators, which are supported through the kernel crypto API.  Traditional crypto accelerators operate on memory regions, whereas inline encryption hardware operates on I/O requests.  Thus, inline encryption hardware needs to be managed by the block layer, not the kernel crypto API.

Inline encryption hardware is also very different from "self-encrypting drives", such as those based on the TCG Opal or ATA Security standards.  Self-encrypting drives don't provide fine-grained control of encryption and provide no way to verify the correctness of the resulting ciphertext.  Inline encryption hardware provides fine-grained control of encryption, including the choice of key and initialization vector for each sector, and can be tested for correctness.

<a id="rst-objective"></a>

## Objective

We want to support inline encryption in the kernel.  To make testing easier, we also want support for falling back to the kernel crypto API when actual inline encryption hardware is absent.  We also want inline encryption to work with layered devices like device-mapper and loopback (i.e. we want to be able to use the inline encryption hardware of the underlying devices if present, or else fall back to crypto API en/decryption).

<a id="rst-constraints-and-notes"></a>

## Constraints and notes

- We need a way for upper layers (e.g. filesystems) to specify an encryption context to use for en/decrypting a bio, and device drivers (e.g. UFSHCD) need to be able to use that encryption context when they process the request. Encryption contexts also introduce constraints on bio merging; the block layer needs to be aware of these constraints.

- Different inline encryption hardware has different supported algorithms, supported data unit sizes, maximum data unit numbers, etc.  We call these properties the "crypto capabilities".  We need a way for device drivers to advertise crypto capabilities to upper layers in a generic way.

- Inline encryption hardware usually (but not always) requires that keys be programmed into keyslots before being used.  Since programming keyslots may be slow and there may not be very many keyslots, we shouldn't just program the key for every I/O request, but rather keep track of which keys are in the keyslots and reuse an already-programmed keyslot when possible.

- Upper layers typically define a specific end-of-life for crypto keys, e.g. when an encrypted directory is locked or when a crypto mapping is torn down. At these times, keys are wiped from memory.  We must provide a way for upper layers to also evict keys from any keyslots they are present in.

- When possible, device-mapper devices must be able to pass through the inline encryption support of their underlying devices.  However, it doesn't make sense for device-mapper devices to have keyslots themselves.

<a id="rst-basic-design"></a>

## Basic design

We introduce `struct blk_crypto_key` to represent an inline encryption key and how it will be used.  This includes the type of the key (raw or hardware-wrapped); the actual bytes of the key; the size of the key; the algorithm and data unit size the key will be used with; and the number of bytes needed to represent the maximum data unit number the key will be used with.

We introduce `struct bio_crypt_ctx` to represent an encryption context.  It contains a data unit number and a pointer to a blk_crypto_key.  We add pointers to a bio_crypt_ctx to `struct bio` and `struct request`; this allows users of the block layer (e.g. filesystems) to provide an encryption context when creating a bio and have it be passed down the stack for processing by the block layer and device drivers.  Note that the encryption context doesn't explicitly say whether to encrypt or decrypt, as that is implicit from the direction of the bio; WRITE means encrypt, and READ means decrypt.

We also introduce `struct blk_crypto_profile` to contain all generic inline encryption-related state for a particular inline encryption device.  The blk_crypto_profile serves as the way that drivers for inline encryption hardware advertise their crypto capabilities and provide certain functions (e.g., functions to program and evict keys) to upper layers.  Each device driver that wants to support inline encryption will construct a blk_crypto_profile, then associate it with the disk's request_queue.

The blk_crypto_profile also manages the hardware's keyslots, when applicable. This happens in the block layer, so that users of the block layer can just specify encryption contexts and don't need to know about keyslots at all, nor do device drivers need to care about most details of keyslot management.

Specifically, for each keyslot, the block layer (via the blk_crypto_profile) keeps track of which blk_crypto_key that keyslot contains (if any), and how many in-flight I/O requests are using it.  When the block layer creates a `struct request` for a bio that has an encryption context, it grabs a keyslot that already contains the key if possible.  Otherwise it waits for an idle keyslot (a keyslot that isn't in-use by any I/O), then programs the key into the least-recently-used idle keyslot using the function the device driver provided. In both cases, the resulting keyslot is stored in the `crypt_keyslot` field of the request, where it is then accessible to device drivers and is released after the request completes.

`struct request` also contains a pointer to the original bio_crypt_ctx. Requests can be built from multiple bios, and the block layer must take the encryption context into account when trying to merge bios and requests.  For two bios/requests to be merged, they must have compatible encryption contexts: both unencrypted, or both encrypted with the same key and contiguous data unit numbers.  Only the encryption context for the first bio in a request is retained, since the remaining bios have been verified to be merge-compatible with the first bio.

To make it possible for inline encryption to work with request_queue based layered devices, when a request is cloned, its encryption context is cloned as well.  When the cloned request is submitted, it is then processed as usual; this includes getting a keyslot from the clone's target device if needed.

<a id="rst-blk-crypto-fallback"></a>

## blk-crypto-fallback

It is desirable for the inline encryption support of upper layers (e.g. filesystems) to be testable without real inline encryption hardware, and likewise for the block layer's keyslot management logic.  It is also desirable to allow upper layers to just always use inline encryption rather than have to implement encryption in multiple ways.

Therefore, we also introduce *blk-crypto-fallback*, which is an implementation of inline encryption using the kernel crypto API.  blk-crypto-fallback is built into the block layer, so it works on any block device without any special setup. Essentially, when a bio with an encryption context is submitted to a block_device that doesn't support that encryption context, the block layer will handle en/decryption of the bio using blk-crypto-fallback.

For encryption, the data cannot be encrypted in-place, as callers usually rely on it being unmodified.  Instead, blk-crypto-fallback allocates bounce pages, fills a new bio with those bounce pages, encrypts the data into those bounce pages, and submits that "bounce" bio.  When the bounce bio completes, blk-crypto-fallback completes the original bio.  If the original bio is too large, multiple bounce bios may be required; see the code for details.

For decryption, blk-crypto-fallback "wraps" the bio's completion callback (`bi_complete`) and private data (`bi_private`) with its own, unsets the bio's encryption context, then submits the bio.  If the read completes successfully, blk-crypto-fallback restores the bio's original completion callback and private data, then decrypts the bio's data in-place using the kernel crypto API.  Decryption happens from a workqueue, as it may sleep. Afterwards, blk-crypto-fallback completes the bio.

In both cases, the bios that blk-crypto-fallback submits no longer have an encryption context.  Therefore, lower layers only see standard unencrypted I/O.

blk-crypto-fallback also defines its own blk_crypto_profile and has its own "keyslots"; its keyslots contain `struct crypto_skcipher` objects.  The reason for this is twofold.  First, it allows the keyslot management logic to be tested without actual inline encryption hardware.  Second, similar to actual inline encryption hardware, the crypto API doesn't accept keys directly in requests but rather requires that keys be set ahead of time, and setting keys can be expensive; moreover, allocating a crypto_skcipher can't happen on the I/O path at all due to the locks it takes.  Therefore, the concept of keyslots still makes sense for blk-crypto-fallback.

Note that regardless of whether real inline encryption hardware or blk-crypto-fallback is used, the ciphertext written to disk (and hence the on-disk format of data) will be the same (assuming that both the inline encryption hardware's implementation and the kernel crypto API's implementation of the algorithm being used adhere to spec and function correctly).

blk-crypto-fallback is optional and is controlled by the `CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK` kernel configuration option.

<a id="rst-api-presented-to-users-of-the-block-layer"></a>

## API presented to users of the block layer

`blk_crypto_config_supported()` allows users to check ahead of time whether inline encryption with particular crypto settings will work on a particular block_device -- either via hardware or via blk-crypto-fallback.  This function takes in a `struct blk_crypto_config` which is like blk_crypto_key, but omits the actual bytes of the key and instead just contains the algorithm, data unit size, etc.  This function can be useful if blk-crypto-fallback is disabled.

`blk_crypto_init_key()` allows users to initialize a blk_crypto_key.

Users must call `blk_crypto_start_using_key()` before actually starting to use a blk_crypto_key on a block_device (even if `blk_crypto_config_supported()` was called earlier).  This is needed to initialize blk-crypto-fallback if it will be needed.  This must not be called from the data path, as this may have to allocate resources, which may deadlock in that case.

Next, to attach an encryption context to a bio, users should call `bio_crypt_set_ctx()`.  This function allocates a bio_crypt_ctx and attaches it to a bio, given the blk_crypto_key and the data unit number that will be used for en/decryption.  Users don't need to worry about freeing the bio_crypt_ctx later, as that happens automatically when the bio is freed or reset.

To submit a bio that uses inline encryption, users must call `blk_crypto_submit_bio()` instead of the usual `submit_bio()`.  This will submit the bio to the underlying driver if it supports inline crypto, or else call the blk-crypto fallback routines before submitting normal bios to the underlying drivers.

Finally, when done using inline encryption with a blk_crypto_key on a block_device, users must call `blk_crypto_evict_key()`.  This ensures that the key is evicted from all keyslots it may be programmed into and unlinked from any kernel data structures it may be linked into.

In summary, for users of the block layer, the lifecycle of a blk_crypto_key is as follows:

1. `blk_crypto_config_supported()` (optional)

2. `blk_crypto_init_key()`

3. `blk_crypto_start_using_key()`

4. `bio_crypt_set_ctx()` (potentially many times)

5. `blk_crypto_evict_key()` (after all I/O has completed)

6. Zeroize the blk_crypto_key (this has no dedicated function)

If a blk_crypto_key is being used on multiple block_devices, then `blk_crypto_config_supported()` (if used), `blk_crypto_start_using_key()`, and `blk_crypto_evict_key()` must be called on each block_device.

<a id="rst-api-presented-to-device-drivers"></a>

## API presented to device drivers

A device driver that wants to support inline encryption must set up a blk_crypto_profile in the request_queue of its device.  To do this, it first must call `blk_crypto_profile_init()` (or its resource-managed variant `devm_blk_crypto_profile_init()`), providing the number of keyslots.

Next, it must advertise its crypto capabilities by setting fields in the blk_crypto_profile, e.g. `modes_supported` and `max_dun_bytes_supported`.

It then must set function pointers in the `ll_ops` field of the blk_crypto_profile to tell upper layers how to control the inline encryption hardware, e.g. how to program and evict keyslots.  Most drivers will need to implement `keyslot_program` and `keyslot_evict`.  For details, see the comments for `struct blk_crypto_ll_ops`.

Once the driver registers a blk_crypto_profile with a request_queue, I/O requests the driver receives via that queue may have an encryption context.  All encryption contexts will be compatible with the crypto capabilities declared in the blk_crypto_profile, so drivers don't need to worry about handling unsupported requests.  Also, if a nonzero number of keyslots was declared in the blk_crypto_profile, then all I/O requests that have an encryption context will also have a keyslot which was already programmed with the appropriate key.

If the driver implements runtime suspend and its blk_crypto_ll_ops don't work while the device is runtime-suspended, then the driver must also set the `dev` field of the blk_crypto_profile to point to the `struct device` that will be resumed before any of the low-level operations are called.

If there are situations where the inline encryption hardware loses the contents of its keyslots, e.g. device resets, the driver must handle reprogramming the keyslots.  To do this, the driver may call `blk_crypto_reprogram_all_keys()`.

Finally, if the driver used `blk_crypto_profile_init()` instead of `devm_blk_crypto_profile_init()`, then it is responsible for calling `blk_crypto_profile_destroy()` when the crypto profile is no longer needed.

<a id="rst-layered-devices"></a>

## Layered Devices

Request queue based layered devices like dm-rq that wish to support inline encryption need to create their own blk_crypto_profile for their request_queue, and expose whatever functionality they choose. When a layered device wants to pass a clone of that request to another request_queue, blk-crypto will initialize and prepare the clone as necessary.

<a id="rst-interaction-between-inline-encryption-and-blk-integrity"></a>

## Interaction between inline encryption and blk integrity

At the time of this patch, there is no real hardware that supports both these features. However, these features do interact with each other, and it's not completely trivial to make them both work together properly. In particular, when a WRITE bio wants to use inline encryption on a device that supports both features, the bio will have an encryption context specified, after which its integrity information is calculated (using the plaintext data, since the encryption will happen while data is being written), and the data and integrity info is sent to the device. Obviously, the integrity info must be verified before the data is encrypted. After the data is encrypted, the device must not store the integrity info that it received with the plaintext data since that might reveal information about the plaintext data. As such, it must re-generate the integrity info from the ciphertext data and store that on disk instead. Another issue with storing the integrity info of the plaintext data is that it changes the on disk format depending on whether hardware inline encryption support is present or the kernel crypto API fallback is used (since if the fallback is used, the device will receive the integrity info of the ciphertext, not that of the plaintext).

Because there isn't any real hardware yet, it seems prudent to assume that hardware implementations might not implement both features together correctly, and disallow the combination for now. Whenever a device supports integrity, the kernel will pretend that the device does not support hardware inline encryption (by setting the blk_crypto_profile in the request_queue of the device to NULL). When the crypto API fallback is enabled, this means that all bios with and encryption context will use the fallback, and IO will complete as usual.  When the fallback is disabled, a bio with an encryption context will be failed.

<a id="rst-hardware-wrapped-keys-1"></a>
<a id="rst-hardware-wrapped-keys"></a>

## Hardware-wrapped keys

<a id="rst-motivation-and-threat-model"></a>

### Motivation and threat model

Linux storage encryption (dm-crypt, fscrypt, eCryptfs, etc.) traditionally relies on the raw encryption key(s) being present in kernel memory so that the encryption can be performed.  This traditionally isn't seen as a problem because the key(s) won't be present during an offline attack, which is the main type of attack that storage encryption is intended to protect from.

However, there is an increasing desire to also protect users' data from other types of attacks (to the extent possible), including:

- Cold boot attacks, where an attacker with physical access to a system suddenly powers it off, then immediately dumps the system memory to extract recently in-use encryption keys, then uses these keys to decrypt user data on-disk.

- Online attacks where the attacker is able to read kernel memory without fully compromising the system, followed by an offline attack where any extracted keys can be used to decrypt user data on-disk.  An example of such an online attack would be if the attacker is able to run some code on the system that exploits a Meltdown-like vulnerability but is unable to escalate privileges.

- Online attacks where the attacker fully compromises the system, but their data exfiltration is significantly time-limited and/or bandwidth-limited, so in order to completely exfiltrate the data they need to extract the encryption keys to use in a later offline attack.

Hardware-wrapped keys are a feature of inline encryption hardware that is designed to protect users' data from the above attacks (to the extent possible), without introducing limitations such as a maximum number of keys.

Note that it is impossible to **fully** protect users' data from these attacks. Even in the attacks where the attacker "just" gets read access to kernel memory, they can still extract any user data that is present in memory, including plaintext pagecache pages of encrypted files.  The focus here is just on protecting the encryption keys, as those instantly give access to **all** user data in any following offline attack, rather than just some of it (where which data is included in that "some" might not be controlled by the attacker).

<a id="rst-solution-overview"></a>

### Solution overview

Inline encryption hardware typically has "keyslots" into which software can program keys for the hardware to use; the contents of keyslots typically can't be read back by software.  As such, the above security goals could be achieved if the kernel simply erased its copy of the key(s) after programming them into keyslot(s) and thereafter only referred to them via keyslot number.

However, that naive approach runs into a couple problems:

- It limits the number of unlocked keys to the number of keyslots, which typically is a small number.  In cases where there is only one encryption key system-wide (e.g., a full-disk encryption key), that can be tolerable. However, in general there can be many logged-in users with many different keys, and/or many running applications with application-specific encrypted storage areas.  This is especially true if file-based encryption (e.g. fscrypt) is being used.

- Inline crypto engines typically lose the contents of their keyslots if the storage controller (usually UFS or eMMC) is reset.  Resetting the storage controller is a standard error recovery procedure that is executed if certain types of storage errors occur, and such errors can occur at any time. Therefore, when inline crypto is being used, the operating system must always be ready to reprogram the keyslots without user intervention.

Thus, it is important for the kernel to still have a way to "remind" the hardware about a key, without actually having the raw key itself.

Somewhat less importantly, it is also desirable that the raw keys are never visible to software at all, even while being initially unlocked.  This would ensure that a read-only compromise of system memory will never allow a key to be extracted to be used off-system, even if it occurs when a key is being unlocked.

To solve all these problems, some vendors of inline encryption hardware have made their hardware support *hardware-wrapped keys*.  Hardware-wrapped keys are encrypted keys that can only be unwrapped (decrypted) and used by hardware -- either by the inline encryption hardware itself, or by a dedicated hardware block that can directly provision keys to the inline encryption hardware.

(We refer to them as "hardware-wrapped keys" rather than simply "wrapped keys" to add some clarity in cases where there could be other types of wrapped keys, such as in file-based encryption.  Key wrapping is a commonly used technique.)

The key which wraps (encrypts) hardware-wrapped keys is a hardware-internal key that is never exposed to software; it is either a persistent key (a "long-term wrapping key") or a per-boot key (an "ephemeral wrapping key").  The long-term wrapped form of the key is what is initially unlocked, but it is erased from memory as soon as it is converted into an ephemerally-wrapped key.  In-use hardware-wrapped keys are always ephemerally-wrapped, not long-term wrapped.

As inline encryption hardware can only be used to encrypt/decrypt data on-disk, the hardware also includes a level of indirection; it doesn't use the unwrapped key directly for inline encryption, but rather derives both an inline encryption key and a "software secret" from it.  Software can use the "software secret" for tasks that can't use the inline encryption hardware, such as filenames encryption.  The software secret is not protected from memory compromise.

<a id="rst-key-hierarchy"></a>

### Key hierarchy

Here is the key hierarchy for a hardware-wrapped key:



```text
               Hardware-wrapped key
                        |
                        |
                  <Hardware KDF>
                        |
          -----------------------------
          |                           |
Inline encryption key           Software secret
```

The components are:

- *Hardware-wrapped key*: a key for the hardware's KDF (Key Derivation Function), in ephemerally-wrapped form.  The key wrapping algorithm is a hardware implementation detail that doesn't impact kernel operation, but a strong authenticated encryption algorithm such as AES-256-GCM is recommended.

- *Hardware KDF*: a KDF (Key Derivation Function) which the hardware uses to derive subkeys after unwrapping the wrapped key.  The hardware's choice of KDF doesn't impact kernel operation, but it does need to be known for testing purposes, and it's also assumed to have at least a 256-bit security strength. All known hardware uses the SP800-108 KDF in Counter Mode with AES-256-CMAC, with a particular choice of labels and contexts; new hardware should use this already-vetted KDF.

- *Inline encryption key*: a derived key which the hardware directly provisions to a keyslot of the inline encryption hardware, without exposing it to software.  In all known hardware, this will always be an AES-256-XTS key. However, in principle other encryption algorithms could be supported too. Hardware must derive distinct subkeys for each supported encryption algorithm.

- *Software secret*: a derived key which the hardware returns to software so that software can use it for cryptographic tasks that can't use inline encryption.  This value is cryptographically isolated from the inline encryption key, i.e. knowing one doesn't reveal the other.  (The KDF ensures this.)  Currently, the software secret is always 32 bytes and thus is suitable for cryptographic applications that require up to a 256-bit security strength. Some use cases (e.g. full-disk encryption) won't require the software secret.

Example: in the case of fscrypt, the fscrypt master key (the key that protects a particular set of encrypted directories) is made hardware-wrapped.  The inline encryption key is used as the file contents encryption key, while the software secret (rather than the master key directly) is used to key fscrypt's KDF (HKDF-SHA512) to derive other subkeys such as filenames encryption keys.

Note that currently this design assumes a single inline encryption key per hardware-wrapped key, without any further key derivation.  Thus, in the case of fscrypt, currently hardware-wrapped keys are only compatible with the "inline encryption optimized" settings, which use one file contents encryption key per encryption policy rather than one per file.  This design could be extended to make the hardware derive per-file keys using per-file nonces passed down the storage stack, and in fact some hardware already supports this; future work is planned to remove this limitation by adding the corresponding kernel support.

<a id="rst-kernel-support"></a>

### Kernel support

The inline encryption support of the kernel's block layer ("blk-crypto") has been extended to support hardware-wrapped keys as an alternative to raw keys, when hardware support is available.  This works in the following way:

- A `key_types_supported` field is added to the crypto capabilities in `struct blk_crypto_profile`.  This allows device drivers to declare that they support raw keys, hardware-wrapped keys, or both.

- `struct blk_crypto_key` can now contain a hardware-wrapped key as an alternative to a raw key; a `key_type` field is added to `struct blk_crypto_config` to distinguish between the different key types. This allows users of blk-crypto to en/decrypt data using a hardware-wrapped key in a way very similar to using a raw key.

- A new method `blk_crypto_ll_ops::derive_sw_secret` is added.  Device drivers that support hardware-wrapped keys must implement this method.  Users of blk-crypto can call `blk_crypto_derive_sw_secret()` to access this method.

- The programming and eviction of hardware-wrapped keys happens via `blk_crypto_ll_ops::keyslot_program` and `blk_crypto_ll_ops::keyslot_evict`, just like it does for raw keys.  If a driver supports hardware-wrapped keys, then it must handle hardware-wrapped keys being passed to these methods.

blk-crypto-fallback doesn't support hardware-wrapped keys.  Therefore, hardware-wrapped keys can only be used with actual inline encryption hardware.

All the above deals with hardware-wrapped keys in ephemerally-wrapped form only. To get such keys in the first place, new block device ioctls have been added to provide a generic interface to creating and preparing such keys:

- `BLKCRYPTOIMPORTKEY` converts a raw key to long-term wrapped form.  It takes in a pointer to a `struct blk_crypto_import_key_arg`.  The caller must set `raw_key_ptr` and `raw_key_size` to the pointer and size (in bytes) of the raw key to import.  On success, `BLKCRYPTOIMPORTKEY` returns 0 and writes the resulting long-term wrapped key blob to the buffer pointed to by `lt_key_ptr`, which is of maximum size `lt_key_size`.  It also updates `lt_key_size` to be the actual size of the key.  On failure, it returns -1 and sets errno.  An errno of `EOPNOTSUPP` indicates that the block device does not support hardware-wrapped keys.  An errno of `EOVERFLOW` indicates that the output buffer did not have enough space for the key blob.

- `BLKCRYPTOGENERATEKEY` is like `BLKCRYPTOIMPORTKEY`, but it has the hardware generate the key instead of importing one.  It takes in a pointer to a `struct blk_crypto_generate_key_arg`.

- `BLKCRYPTOPREPAREKEY` converts a key from long-term wrapped form to ephemerally-wrapped form.  It takes in a pointer to a `struct blk_crypto_prepare_key_arg`.  The caller must set `lt_key_ptr` and `lt_key_size` to the pointer and size (in bytes) of the long-term wrapped key blob to convert.  On success, `BLKCRYPTOPREPAREKEY` returns 0 and writes the resulting ephemerally-wrapped key blob to the buffer pointed to by `eph_key_ptr`, which is of maximum size `eph_key_size`.  It also updates `eph_key_size` to be the actual size of the key.  On failure, it returns -1 and sets errno.  Errno values of `EOPNOTSUPP` and `EOVERFLOW` mean the same as they do for `BLKCRYPTOIMPORTKEY`.  An errno of `EBADMSG` indicates that the long-term wrapped key is invalid.

Userspace needs to use either `BLKCRYPTOIMPORTKEY` or `BLKCRYPTOGENERATEKEY` once to create a key, and then `BLKCRYPTOPREPAREKEY` each time the key is unlocked and added to the kernel.  Note that these ioctls have no relevance for raw keys; they are only for hardware-wrapped keys.

<a id="rst-testability"></a>

### Testability

Both the hardware KDF and the inline encryption itself are well-defined algorithms that don't depend on any secrets other than the unwrapped key. Therefore, if the unwrapped key is known to software, these algorithms can be reproduced in software in order to verify the ciphertext that is written to disk by the inline encryption hardware.

However, the unwrapped key will only be known to software for testing if the "import" functionality is used.  Proper testing is not possible in the "generate" case where the hardware generates the key itself.  The correct operation of the "generate" mode thus relies on the security and correctness of the hardware RNG and its use to generate the key, as well as the testing of the "import" mode as that should cover all parts other than the key generation.

For an example of a test that verifies the ciphertext written to disk in the "import" mode, see the fscrypt hardware-wrapped key tests in xfstests, or [Android's vts_kernel_encryption_test](<https://android.googlesource.com/platform/test/vts-testcase/kernel/+/refs/heads/main/encryption/>)<a id="rst-android-s-vts-kernel-encryption-test"></a>.

---

# Block io priorities

_Peios Kernel / Internals / Block_

> The io priority feature enables users to io nice processes or process groups, similar to what has been possible with cpu scheduling for ages. Support for io priorities is io scheduler dependent and currently supported by bfq and…

<a id="rst-block-io-priorities"></a>

<a id="rst-intro"></a>

## Intro

The io priority feature enables users to io nice processes or process groups, similar to what has been possible with cpu scheduling for ages. Support for io priorities is io scheduler dependent and currently supported by bfq and mq-deadline.

<a id="rst-scheduling-classes"></a>

## Scheduling classes

Three generic scheduling classes are implemented for io priorities that determine how io is served for a process.

IOPRIO_CLASS_RT: This is the realtime io class. This scheduling class is given higher priority than any other in the system, processes from this class are given first access to the disk every time. Thus it needs to be used with some care, one io RT process can starve the entire system. Within the RT class, there are 8 levels of class data that determine exactly how much time this process needs the disk for on each service. In the future this might change to be more directly mappable to performance, by passing in a wanted data rate instead.

IOPRIO_CLASS_BE: This is the best-effort scheduling class, which is the default for any process that hasn't set a specific io priority. The class data determines how much io bandwidth the process will get, it's directly mappable to the cpu nice levels just more coarsely implemented. 0 is the highest BE prio level, 7 is the lowest. The mapping between cpu nice level and io nice level is determined as: io_nice = (cpu_nice + 20) / 5.

IOPRIO_CLASS_IDLE: This is the idle scheduling class, processes running at this level only get io time when no one else needs the disk. The idle class has no class data, since it doesn't really apply here.

<a id="rst-tools"></a>

## Tools

See below for a sample ionice tool. Usage:



```text
# ionice -c<class> -n<level> -p<pid>
```

If pid isn't given, the current process is assumed. IO priority settings are inherited on fork, so you can use ionice to start the process at a given level:



```text
# ionice -c2 -n0 /bin/ls
```

will run ls at the best-effort scheduling class at the highest priority. For a running process, you can give the pid instead:



```text
# ionice -c1 -n2 -p100
```

will change pid 100 to run at the realtime scheduling class, at priority 2.

ionice.c tool:



```text
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <asm/unistd.h>

extern int sys_ioprio_set(int, int, int);
extern int sys_ioprio_get(int, int);

#if defined(__i386__)
#define __NR_ioprio_set               289
#define __NR_ioprio_get               290
#elif defined(__ppc__)
#define __NR_ioprio_set               273
#define __NR_ioprio_get               274
#elif defined(__x86_64__)
#define __NR_ioprio_set               251
#define __NR_ioprio_get               252
#else
#error "Unsupported arch"
#endif

static inline int ioprio_set(int which, int who, int ioprio)
{
      return syscall(__NR_ioprio_set, which, who, ioprio);
}

static inline int ioprio_get(int which, int who)
{
      return syscall(__NR_ioprio_get, which, who);
}

enum {
      IOPRIO_CLASS_NONE,
      IOPRIO_CLASS_RT,
      IOPRIO_CLASS_BE,
      IOPRIO_CLASS_IDLE,
};

enum {
      IOPRIO_WHO_PROCESS = 1,
      IOPRIO_WHO_PGRP,
      IOPRIO_WHO_USER,
};

#define IOPRIO_CLASS_SHIFT    13

const char *to_prio[] = { "none", "realtime", "best-effort", "idle", };

int main(int argc, char *argv[])
{
      int ioprio = 4, set = 0, ioprio_class = IOPRIO_CLASS_BE;
      int c, pid = 0;

      while ((c = getopt(argc, argv, "+n:c:p:")) != EOF) {
              switch (c) {
              case 'n':
                      ioprio = strtol(optarg, NULL, 10);
                      set = 1;
                      break;
              case 'c':
                      ioprio_class = strtol(optarg, NULL, 10);
                      set = 1;
                      break;
              case 'p':
                      pid = strtol(optarg, NULL, 10);
                      break;
              }
      }

      switch (ioprio_class) {
              case IOPRIO_CLASS_NONE:
                      ioprio_class = IOPRIO_CLASS_BE;
                      break;
              case IOPRIO_CLASS_RT:
              case IOPRIO_CLASS_BE:
                      break;
              case IOPRIO_CLASS_IDLE:
                      ioprio = 7;
                      break;
              default:
                      printf("bad prio class %d\n", ioprio_class);
                      return 1;
      }

      if (!set) {
              if (!pid && argv[optind])
                      pid = strtol(argv[optind], NULL, 10);

              ioprio = ioprio_get(IOPRIO_WHO_PROCESS, pid);

              printf("pid=%d, %d\n", pid, ioprio);

              if (ioprio == -1)
                      perror("ioprio_get");
              else {
                      ioprio_class = ioprio >> IOPRIO_CLASS_SHIFT;
                      ioprio = ioprio & 0xff;
                      printf("%s: prio %d\n", to_prio[ioprio_class], ioprio);
              }
      } else {
              if (ioprio_set(IOPRIO_WHO_PROCESS, pid, ioprio | ioprio_class << IOPRIO_CLASS_SHIFT) == -1) {
                      perror("ioprio_set");
                      return 1;
              }

              if (argv[optind])
                      execvp(argv[optind], &argv[optind]);
      }

      return 0;
}
```

March 11 2005, Jens Axboe &lt;[jens.axboe@oracle.com](<mailto:jens.axboe@oracle.com>)&gt;

---

# Kyber I/O scheduler tunables

_Peios Kernel / Internals / Block_

> The only two tunables for the Kyber scheduler are the target latencies for reads and synchronous writes. Kyber will throttle requests in order to meet these target latencies.

<a id="rst-kyber-i-o-scheduler-tunables"></a>

The only two tunables for the Kyber scheduler are the target latencies for reads and synchronous writes. Kyber will throttle requests in order to meet these target latencies.

<a id="rst-read-lat-nsec"></a>

## read_lat_nsec

Target latency for reads (in nanoseconds).

<a id="rst-write-lat-nsec"></a>

## write_lat_nsec

Target latency for synchronous writes (in nanoseconds).

---

# Null block device driver

_Peios Kernel / Internals / Block_

> The null block device (/dev/nullb*) is used for benchmarking the various block-layer implementations. It emulates a block device of X gigabytes in size. It does not execute any read/write operation, just mark them as complete in the…

<a id="rst-null-block-device-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The null block device (`/dev/nullb*`) is used for benchmarking the various block-layer implementations. It emulates a block device of X gigabytes in size. It does not execute any read/write operation, just mark them as complete in the request queue. The following instances are possible:

> Multi-queue block-layer
>
> > - Request-based.
> >
> > - Configurable submission queues per device.
>
> No block-layer (Known as bio-based)
>
> > - Bio-based. IO requests are submitted directly to the device driver.
> >
> > - Directly accepts bio data structure and returns them.

All of them have a completion queue for each core in the system.

<a id="rst-module-parameters"></a>

## Module parameters

- **queue_mode=\[0-2\]: Default: 2-Multi-queue**

  Selects which block-layer the module should instantiate with.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Bio-based

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Single-queue (deprecated)

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  Multi-queue

  </td>
  </tr>
  </tbody>
  </table>

- **home_node=\[0--nr_nodes\]: Default: NUMA_NO_NODE**

  Selects what CPU node the data structures are allocated from.

- **gb=\[Size in GB\]: Default: 250GB**

  The size of the device reported to the system.

- **bs=\[Block size (in bytes)\]: Default: 512 bytes**

  The block size reported to the system.

- **nr_devices=\[Number of devices\]: Default: 1**

  Number of block devices instantiated. They are instantiated as /dev/nullb0, etc.

- **irqmode=\[0-2\]: Default: 1-Soft-irq**

  The completion mode used for completing IOs to the block-layer.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  None.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Soft-irq. Uses IPI to complete IOs across CPU nodes. Simulates the overhead when IOs are issued from another CPU node than the home the device is connected to.

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  Timer: Waits a specific period (completion_nsec) for each IO before completion.

  </td>
  </tr>
  </tbody>
  </table>

- **completion_nsec=\[ns\]: Default: 10,000ns**

  Combined with irqmode=2 (timer). The time each completion event must wait.

- **submit_queues=\[1..nr_cpus\]: Default: 1**

  The number of submission queues attached to the device driver. If unset, it defaults to 1. For multi-queue, it is ignored when use_per_node_hctx module parameter is 1.

- **hw_queue_depth=\[0..qdepth\]: Default: 64**

  The hardware queue depth of the device.

- **memory_backed=\[0/1\]: Default: 0**

  Whether or not to use a memory buffer to respond to IO requests


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Transfer no data in response to IO requests

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Use a memory buffer to respond to IO requests

  </td>
  </tr>
  </tbody>
  </table>

- **discard=\[0/1\]: Default: 0**

  Support discard operations (requires memory-backed null_blk device).


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Do not support discard operations

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Enable support for discard operations

  </td>
  </tr>
  </tbody>
  </table>

- **cache_size=\[Size in MB\]: Default: 0**

  Cache size in MB for memory-backed device.

- **mbps=\[Maximum bandwidth in MB/s\]: Default: 0 (no limit)**

  Bandwidth limit for device performance.

<a id="rst-multi-queue-specific-parameters"></a>

### Multi-queue specific parameters

- **use_per_node_hctx=\[0/1\]: Default: 0**

  Number of hardware context queues.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  The number of submit queues are set to the value of the submit_queues parameter.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  The multi-queue block layer is instantiated with a hardware dispatch queue for each CPU node in the system.

  </td>
  </tr>
  </tbody>
  </table>

- **no_sched=\[0/1\]: Default: 0**

  Enable/disable the io scheduler.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  nullb\* use default blk-mq io scheduler

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  nullb\* doesn't use io scheduler

  </td>
  </tr>
  </tbody>
  </table>

- **blocking=\[0/1\]: Default: 0**

  Blocking behavior of the request queue.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Register as a non-blocking blk-mq driver device.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Register as a blocking blk-mq driver device, null_blk will set the BLK_MQ_F_BLOCKING flag, indicating that it sometimes/always needs to block in its -&gt;queue_rq() function.

  </td>
  </tr>
  </tbody>
  </table>

- **shared_tags=\[0/1\]: Default: 0**

  Sharing tags between devices.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Tag set is not shared.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Tag set shared between devices for blk-mq. Only makes sense with nr_devices &gt; 1, otherwise there's no tag set to share.

  </td>
  </tr>
  </tbody>
  </table>

- **zoned=\[0/1\]: Default: 0**

  Device is a random-access or a zoned block device.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Block device is exposed as a random-access block device.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Block device is exposed as a host-managed zoned block device. Requires CONFIG_BLK_DEV_ZONED.

  </td>
  </tr>
  </tbody>
  </table>

- **zone_size=\[MB\]: Default: 256**

  Per zone size when exposed as a zoned block device. Must be a power of two.

- **zone_nr_conv=\[nr_conv\]: Default: 0**

  The number of conventional zones to create when block device is zoned.  If zone_nr_conv &gt;= nr_zones, it will be reduced to nr_zones - 1.

---

# Block layer support for Persistent Reservations

_Peios Kernel / Internals / Block_

> The Linux kernel supports a user space interface for simplified Persistent Reservations which map to block devices that support these (like SCSI). Persistent Reservations allow restricting access to block devices to specific initiators in…

<a id="rst-block-layer-support-for-persistent-reservations"></a>

The Linux kernel supports a user space interface for simplified Persistent Reservations which map to block devices that support these (like SCSI). Persistent Reservations allow restricting access to block devices to specific initiators in a shared storage setup.

This document gives a general overview of the support ioctl commands. For a more detailed reference please refer to the SCSI Primary Commands standard, specifically the section on Reservations and the "PERSISTENT RESERVE IN" and "PERSISTENT RESERVE OUT" commands.

All implementations are expected to ensure the reservations survive a power loss and cover all connections in a multi path environment. These behaviors are optional in SPC but will be automatically applied by Linux.

<a id="rst-the-following-types-of-reservations-are-supported"></a>

## The following types of reservations are supported:

> - - **PR_WRITE_EXCLUSIVE**
>
>     Only the initiator that owns the reservation can write to the device.  Any initiator can read from the device.
>
> - - **PR_EXCLUSIVE_ACCESS**
>
>     Only the initiator that owns the reservation can access the device.
>
> - - **PR_WRITE_EXCLUSIVE_REG_ONLY**
>
>     Only initiators with a registered key can write to the device, Any initiator can read from the device.
>
> - - **PR_EXCLUSIVE_ACCESS_REG_ONLY**
>
>     Only initiators with a registered key can access the device.
>
> - PR_WRITE_EXCLUSIVE_ALL_REGS
>
>   > Only initiators with a registered key can write to the device, Any initiator can read from the device. All initiators with a registered key are considered reservation holders. Please reference the SPC spec on the meaning of a reservation holder if you want to use this type.
>
> - - **PR_EXCLUSIVE_ACCESS_ALL_REGS**
>
>     Only initiators with a registered key can access the device. All initiators with a registered key are considered reservation holders. Please reference the SPC spec on the meaning of a reservation holder if you want to use this type.

<a id="rst-the-following-ioctl-are-supported"></a>

## The following ioctl are supported:

<a id="rst-ioc-pr-register"></a>

### 1. IOC_PR_REGISTER

This ioctl command registers a new reservation if the new_key argument is non-null.  If no existing reservation exists old_key must be zero, if an existing reservation should be replaced old_key must contain the old reservation key.

If the new_key argument is 0 it unregisters the existing reservation passed in old_key.

<a id="rst-ioc-pr-reserve"></a>

### 2. IOC_PR_RESERVE

This ioctl command reserves the device and thus restricts access for other devices based on the type argument.  The key argument must be the existing reservation key for the device as acquired by the IOC_PR_REGISTER, IOC_PR_REGISTER_IGNORE, IOC_PR_PREEMPT or IOC_PR_PREEMPT_ABORT commands.

<a id="rst-ioc-pr-release"></a>

### 3. IOC_PR_RELEASE

This ioctl command releases the reservation specified by key and flags and thus removes any access restriction implied by it.

<a id="rst-ioc-pr-preempt"></a>

### 4. IOC_PR_PREEMPT

This ioctl command releases the existing reservation referred to by old_key and replaces it with a new reservation of type for the reservation key new_key.

<a id="rst-ioc-pr-preempt-abort"></a>

### 5. IOC_PR_PREEMPT_ABORT

This ioctl command works like IOC_PR_PREEMPT except that it also aborts any outstanding command sent over a connection identified by old_key.

<a id="rst-ioc-pr-clear"></a>

### 6. IOC_PR_CLEAR

This ioctl command unregisters both key and any other reservation key registered with the device and drops any existing reservation.

<a id="rst-flags"></a>

## Flags

All the ioctls have a flag field.  Currently only one flag is supported:

> - - **PR_FL_IGNORE_KEY**
>
>     Ignore the existing reservation key.  This is commonly supported for IOC_PR_REGISTER, and some implementation may support the flag for IOC_PR_RESERVE.

For all unknown flags the kernel will return -EOPNOTSUPP.

---

# Block layer statistics in /sys/block/<dev>/stat

_Peios Kernel / Internals / Block_

> This file documents the contents of the /sys/block/<dev>/stat file.

<a id="rst-block-layer-statistics-in-sys-block-dev-stat"></a>

This file documents the contents of the /sys/block/&lt;dev&gt;/stat file.

The stat file provides several statistics about the state of block device &lt;dev&gt;.

- **Q.** Why are there multiple statistics in a single file?  Doesn't sysfs normally contain a single value per file?

- **A.** By having a single file, the kernel can guarantee that the statistics represent a consistent snapshot of the state of the device.  If the statistics were exported as multiple files containing one statistic each, it would be impossible to guarantee that a set of readings represent a single point in time.

The stat file consists of a single line of text containing 17 decimal values separated by whitespace.  The fields are summarized in the following table, and described in more detail below.


<table>
<thead>
<tr>
<th>


Name

</th>
<th>


units

</th>
<th>


description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


read I/Os

</td>
<td>


requests

</td>
<td>


number of read I/Os processed

</td>
</tr>
<tr>
<td>


read merges

</td>
<td>


requests

</td>
<td>


number of read I/Os merged with in-queue I/O

</td>
</tr>
<tr>
<td>


read sectors

</td>
<td>


sectors

</td>
<td>


number of sectors read

</td>
</tr>
<tr>
<td>


read ticks

</td>
<td>


milliseconds

</td>
<td>


total wait time for read requests

</td>
</tr>
<tr>
<td>


write I/Os

</td>
<td>


requests

</td>
<td>


number of write I/Os processed

</td>
</tr>
<tr>
<td>


write merges

</td>
<td>


requests

</td>
<td>


number of write I/Os merged with in-queue I/O

</td>
</tr>
<tr>
<td>


write sectors

</td>
<td>


sectors

</td>
<td>


number of sectors written

</td>
</tr>
<tr>
<td>


write ticks

</td>
<td>


milliseconds

</td>
<td>


total wait time for write requests

</td>
</tr>
<tr>
<td>


in_flight

</td>
<td>


requests

</td>
<td>


number of I/Os currently in flight

</td>
</tr>
<tr>
<td>


io_ticks

</td>
<td>


milliseconds

</td>
<td>


total time this block device has been active

</td>
</tr>
<tr>
<td>


time_in_queue

</td>
<td>


milliseconds

</td>
<td>


total wait time for all requests

</td>
</tr>
<tr>
<td>


discard I/Os

</td>
<td>


requests

</td>
<td>


number of discard I/Os processed

</td>
</tr>
<tr>
<td>


discard merges

</td>
<td>


requests

</td>
<td>


number of discard I/Os merged with in-queue I/O

</td>
</tr>
<tr>
<td>


discard sectors

</td>
<td>


sectors

</td>
<td>


number of sectors discarded

</td>
</tr>
<tr>
<td>


discard ticks

</td>
<td>


milliseconds

</td>
<td>


total wait time for discard requests

</td>
</tr>
<tr>
<td>


flush I/Os

</td>
<td>


requests

</td>
<td>


number of flush I/Os processed

</td>
</tr>
<tr>
<td>


flush ticks

</td>
<td>


milliseconds

</td>
<td>


total wait time for flush requests

</td>
</tr>
</tbody>
</table>

<a id="rst-read-i-os-write-i-os-discard-i-0s"></a>

## read I/Os, write I/Os, discard I/0s

These values increment when an I/O request completes.

<a id="rst-flush-i-os"></a>

## flush I/Os

These values increment when an flush I/O request completes.

Block layer combines flush requests and executes at most one at a time. This counts flush requests executed by disk. Not tracked for partitions.

<a id="rst-read-merges-write-merges-discard-merges"></a>

## read merges, write merges, discard merges

These values increment when an I/O request is merged with an already-queued I/O request.

<a id="rst-read-sectors-write-sectors-discard-sectors"></a>

## read sectors, write sectors, discard_sectors

These values count the number of sectors read from, written to, or discarded from this block device.  The "sectors" in question are the standard UNIX 512-byte sectors, not any device- or filesystem-specific block size.  The counters are incremented when the I/O completes.

<a id="rst-read-ticks-write-ticks-discard-ticks-flush-ticks"></a>

## read ticks, write ticks, discard ticks, flush ticks

These values count the number of milliseconds that I/O requests have waited on this block device.  If there are multiple I/O requests waiting, these values will increase at a rate greater than 1000/second; for example, if 60 read requests wait for an average of 30 ms, the read_ticks field will increase by 60\*30 = 1800.

<a id="rst-in-flight"></a>

## in_flight

This value counts the number of I/O requests that have been issued to the device driver but have not yet completed.  It does not include I/O requests that are in the queue but not yet issued to the device driver.

<a id="rst-io-ticks"></a>

## io_ticks

This value counts the number of milliseconds during which the device has had I/O requests queued.

<a id="rst-time-in-queue"></a>

## time_in_queue

This value counts the number of milliseconds that I/O requests have waited on this block device.  If there are multiple I/O requests waiting, this value will increase as the product of the number of milliseconds times the number of requests waiting (see "read ticks" above for an example).

---

# Switching Scheduler

_Peios Kernel / Internals / Block_

> Each io queue has a set of io scheduler tunables associated with it. These tunables control how the io scheduler works. You can find these entries in:

<a id="rst-switching-scheduler"></a>

Each io queue has a set of io scheduler tunables associated with it. These tunables control how the io scheduler works. You can find these entries in:



```text
/sys/block/<device>/queue/iosched
```

assuming that you have sysfs mounted on /sys. If you don't have sysfs mounted, you can do so by typing:



```text
# mount none /sys -t sysfs
```

It is possible to change the IO scheduler for a given block device on the fly to select one of mq-deadline, none, bfq, or kyber schedulers - which can improve that device's throughput.

To set a specific scheduler, simply do this:



```text
echo SCHEDNAME > /sys/block/DEV/queue/scheduler
```

where SCHEDNAME is the name of a defined IO scheduler, and DEV is the device name (hda, hdb, sga, or whatever you happen to have).

The list of defined schedulers can be found by simply doing a "cat /sys/block/DEV/queue/scheduler" - the list of valid names will be displayed, with the currently selected scheduler in brackets:



```text
# cat /sys/block/sda/queue/scheduler
[mq-deadline] kyber bfq none
# echo none >/sys/block/sda/queue/scheduler
# cat /sys/block/sda/queue/scheduler
[none] mq-deadline kyber bfq
```

---

# Userspace block device driver (ublk driver)

_Peios Kernel / Internals / Block_

> ublk is a generic framework for implementing block device logic from userspace. The motivation behind it is that moving virtual block drivers into userspace, such as loop, nbd and similar can be very helpful. It can help to implement new…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-userspace-block-device-driver-ublk-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

ublk is a generic framework for implementing block device logic from userspace. The motivation behind it is that moving virtual block drivers into userspace, such as loop, nbd and similar can be very helpful. It can help to implement new virtual block device such as ublk-qcow2 (there are several attempts of implementing qcow2 driver in kernel).

Userspace block devices are attractive because:

- They can be written many programming languages.

- They can use libraries that are not available in the kernel.

- They can be debugged with tools familiar to application developers.

- Crashes do not kernel panic the machine.

- Bugs are likely to have a lower security impact than bugs in kernel code.

- They can be installed and updated independently of the kernel.

- They can be used to simulate block device easily with user specified parameters/setting for test/debug purpose

ublk block device (`/dev/ublkb*`) is added by ublk driver. Any IO request on the device will be forwarded to ublk userspace program. For convenience, in this document, `ublk server` refers to generic ublk userspace program. `ublksrv` <a id="rst-footnote-reference-1"></a>[1](#rst-userspace) is one of such implementation. It provides `libublksrv` <a id="rst-footnote-reference-2"></a>[2](#rst-userspace-lib) library for developing specific user block device conveniently, while also generic type block device is included, such as loop and null. Richard W.M. Jones wrote userspace nbd device `nbdublk` <a id="rst-footnote-reference-3"></a>[3](#rst-userspace-nbdublk)  based on `libublksrv` <a id="rst-footnote-reference-4"></a>[2](#rst-userspace-lib).

After the IO is handled by userspace, the result is committed back to the driver, thus completing the request cycle. This way, any specific IO handling logic is totally done by userspace, such as loop's IO handling, NBD's IO communication, or qcow2's IO mapping.

`/dev/ublkb*` is driven by blk-mq request-based driver. Each request is assigned by one queue wide unique tag. ublk server assigns unique tag to each IO too, which is 1:1 mapped with IO of `/dev/ublkb*`.

Both the IO request forward and IO handling result committing are done via `io_uring` passthrough command; that is why ublk is also one io_uring based block driver. It has been observed that using io_uring passthrough command can give better IOPS than block IO; which is why ublk is one of high performance implementation of userspace block device: not only IO request communication is done by io_uring, but also the preferred IO handling in ublk server is io_uring based approach too.

ublk provides control interface to set/get ublk block device parameters. The interface is extendable and kabi compatible: basically any ublk request queue's parameter or ublk generic feature parameters can be set/get via the interface. Thus, ublk is generic userspace block device framework. For example, it is easy to setup a ublk device with specified block parameters from userspace.

<a id="rst-using-ublk"></a>

## Using ublk

ublk requires userspace ublk server to handle real block device logic.

Below is example of using `ublksrv` to provide ublk-based loop device.

- add a device:



  ```text
  ublk add -t loop -f ublk-loop.img
  ```

- format with xfs, then use it:



  ```text
  mkfs.xfs /dev/ublkb0
  mount /dev/ublkb0 /mnt
  # do anything. all IOs are handled by io_uring
  ...
  umount /mnt
  ```

- list the devices with their info:



  ```text
  ublk list
  ```

- delete the device:



  ```text
  ublk del -a
  ublk del -n $ublk_dev_id
  ```

See usage details in README of `ublksrv` <a id="rst-footnote-reference-5"></a>[4](#rst-userspace-readme).

<a id="rst-design"></a>

## Design

<a id="rst-control-plane"></a>

### Control plane

ublk driver provides global misc device node (`/dev/ublk-control`) for managing and controlling ublk devices with help of several control commands:

- `UBLK_CMD_ADD_DEV`

  Add a ublk char device (`/dev/ublkc*`) which is talked with ublk server WRT IO command communication. Basic device info is sent together with this command. It sets UAPI structure of `ublksrv_ctrl_dev_info`, such as `nr_hw_queues`, `queue_depth`, and max IO request buffer size, for which the info is negotiated with the driver and sent back to the server. When this command is completed, the basic device info is immutable.

- `UBLK_CMD_SET_PARAMS` / `UBLK_CMD_GET_PARAMS`

  Set or get parameters of the device, which can be either generic feature related, or request queue limit related, but can't be IO logic specific, because the driver does not handle any IO logic. This command has to be sent before sending `UBLK_CMD_START_DEV`.

- `UBLK_CMD_START_DEV`

  After the server prepares userspace resources (such as creating I/O handler threads &amp; io_uring for handling ublk IO), this command is sent to the driver for allocating &amp; exposing `/dev/ublkb*`. Parameters set via `UBLK_CMD_SET_PARAMS` are applied for creating the device.

- `UBLK_CMD_STOP_DEV`

  Halt IO on `/dev/ublkb*` and remove the device. When this command returns, ublk server will release resources (such as destroying I/O handler threads &amp; io_uring).

- `UBLK_CMD_DEL_DEV`

  Remove `/dev/ublkc*`. When this command returns, the allocated ublk device number can be reused.

- `UBLK_CMD_GET_QUEUE_AFFINITY`

  When `/dev/ublkc` is added, the driver creates block layer tagset, so that each queue's affinity info is available. The server sends `UBLK_CMD_GET_QUEUE_AFFINITY` to retrieve queue affinity info. It can set up the per-queue context efficiently, such as bind affine CPUs with IO pthread and try to allocate buffers in IO thread context.

- `UBLK_CMD_GET_DEV_INFO`

  For retrieving device info via `ublksrv_ctrl_dev_info`. It is the server's responsibility to save IO target specific info in userspace.

- `UBLK_CMD_GET_DEV_INFO2` Same purpose with `UBLK_CMD_GET_DEV_INFO`, but ublk server has to provide path of the char device of `/dev/ublkc*` for kernel to run permission check, and this command is added for supporting unprivileged ublk device, and introduced with `UBLK_F_UNPRIVILEGED_DEV` together. Only the user owning the requested device can retrieve the device info.

  How to deal with userspace/kernel compatibility:

  1. if kernel is capable of handling `UBLK_F_UNPRIVILEGED_DEV`

  > If ublk server supports `UBLK_F_UNPRIVILEGED_DEV`:
  >
  > ublk server should send `UBLK_CMD_GET_DEV_INFO2`, given anytime unprivileged application needs to query devices the current user owns, when the application has no idea if `UBLK_F_UNPRIVILEGED_DEV` is set given the capability info is stateless, and application should always retrieve it via `UBLK_CMD_GET_DEV_INFO2`
  >
  > If ublk server doesn't support `UBLK_F_UNPRIVILEGED_DEV`:
  >
  > `UBLK_CMD_GET_DEV_INFO` is always sent to kernel, and the feature of UBLK_F_UNPRIVILEGED_DEV isn't available for user

  2. if kernel isn't capable of handling `UBLK_F_UNPRIVILEGED_DEV`

  > If ublk server supports `UBLK_F_UNPRIVILEGED_DEV`:
  >
  > `UBLK_CMD_GET_DEV_INFO2` is tried first, and will be failed, then `UBLK_CMD_GET_DEV_INFO` needs to be retried given `UBLK_F_UNPRIVILEGED_DEV` can't be set
  >
  > If ublk server doesn't support `UBLK_F_UNPRIVILEGED_DEV`:
  >
  > `UBLK_CMD_GET_DEV_INFO` is always sent to kernel, and the feature of `UBLK_F_UNPRIVILEGED_DEV` isn't available for user

- `UBLK_CMD_START_USER_RECOVERY`

  This command is valid if `UBLK_F_USER_RECOVERY` feature is enabled. This command is accepted after the old process has exited, ublk device is quiesced and `/dev/ublkc*` is released. User should send this command before he starts a new process which re-opens `/dev/ublkc*`. When this command returns, the ublk device is ready for the new process.

- `UBLK_CMD_END_USER_RECOVERY`

  This command is valid if `UBLK_F_USER_RECOVERY` feature is enabled. This command is accepted after ublk device is quiesced and a new process has opened `/dev/ublkc*` and get all ublk queues be ready. When this command returns, ublk device is unquiesced and new I/O requests are passed to the new process.

- user recovery feature description

  Three new features are added for user recovery: `UBLK_F_USER_RECOVERY`, `UBLK_F_USER_RECOVERY_REISSUE`, and `UBLK_F_USER_RECOVERY_FAIL_IO`. To enable recovery of ublk devices after the ublk server exits, the ublk server should specify the `UBLK_F_USER_RECOVERY` flag when creating the device. The ublk server may additionally specify at most one of `UBLK_F_USER_RECOVERY_REISSUE` and `UBLK_F_USER_RECOVERY_FAIL_IO` to modify how I/O is handled while the ublk server is dying/dead (this is called the `nosrv` case in the driver code).

  With just `UBLK_F_USER_RECOVERY` set, after the ublk server exits, ublk does not delete `/dev/ublkb*` during the whole recovery stage and ublk device ID is kept. It is ublk server's responsibility to recover the device context by its own knowledge. Requests which have not been issued to userspace are requeued. Requests which have been issued to userspace are aborted.

  With `UBLK_F_USER_RECOVERY_REISSUE` additionally set, after the ublk server exits, contrary to `UBLK_F_USER_RECOVERY`, requests which have been issued to userspace are requeued and will be re-issued to the new process after handling `UBLK_CMD_END_USER_RECOVERY`. `UBLK_F_USER_RECOVERY_REISSUE` is designed for backends who tolerate double-write since the driver may issue the same I/O request twice. It might be useful to a read-only FS or a VM backend.

  With `UBLK_F_USER_RECOVERY_FAIL_IO` additionally set, after the ublk server exits, requests which have issued to userspace are failed, as are any subsequently issued requests. Applications continuously issuing I/O against devices with this flag set will see a stream of I/O errors until a new ublk server recovers the device.

Unprivileged ublk device is supported by passing `UBLK_F_UNPRIVILEGED_DEV`. Once the flag is set, all control commands can be sent by unprivileged user. Except for command of `UBLK_CMD_ADD_DEV`, permission check on the specified char device(`/dev/ublkc*`) is done for all other control commands by ublk driver, for doing that, path of the char device has to be provided in these commands' payload from ublk server. With this way, ublk device becomes container-ware, and device created in one container can be controlled/accessed just inside this container.

<a id="rst-data-plane"></a>

### Data plane

The ublk server should create dedicated threads for handling I/O. Each thread should have its own io_uring through which it is notified of new I/O, and through which it can complete I/O. These dedicated threads should focus on IO handling and shouldn't handle any control &amp; management tasks.

The's IO is assigned by a unique tag, which is 1:1 mapping with IO request of `/dev/ublkb*`.

UAPI structure of `ublksrv_io_desc` is defined for describing each IO from the driver. A fixed mmapped area (array) on `/dev/ublkc*` is provided for exporting IO info to the server; such as IO offset, length, OP/flags and buffer address. Each `ublksrv_io_desc` instance can be indexed via queue id and IO tag directly.

The following IO commands are communicated via io_uring passthrough command, and each command is only for forwarding the IO and committing the result with specified IO tag in the command data:

<a id="rst-traditional-per-i-o-commands"></a>

#### Traditional Per-I/O Commands

- `UBLK_U_IO_FETCH_REQ`

  Sent from the server I/O pthread for fetching future incoming I/O requests destined to `/dev/ublkb*`. This command is sent only once from the server IO pthread for ublk driver to setup IO forward environment.

  Once a thread issues this command against a given (qid,tag) pair, the thread registers itself as that I/O's daemon. In the future, only that I/O's daemon is allowed to issue commands against the I/O. If any other thread attempts to issue a command against a (qid,tag) pair for which the thread is not the daemon, the command will fail. Daemons can be reset only be going through recovery.

  The ability for every (qid,tag) pair to have its own independent daemon task is indicated by the `UBLK_F_PER_IO_DAEMON` feature. If this feature is not supported by the driver, daemons must be per-queue instead - i.e. all I/Os associated to a single qid must be handled by the same task.

- `UBLK_U_IO_COMMIT_AND_FETCH_REQ`

  When an IO request is destined to `/dev/ublkb*`, the driver stores the IO's `ublksrv_io_desc` to the specified mapped area; then the previous received IO command of this IO tag (either `UBLK_IO_FETCH_REQ` or `UBLK_IO_COMMIT_AND_FETCH_REQ)` is completed, so the server gets the IO notification via io_uring.

  After the server handles the IO, its result is committed back to the driver by sending `UBLK_IO_COMMIT_AND_FETCH_REQ` back. Once ublkdrv received this command, it parses the result and complete the request to `/dev/ublkb*`. In the meantime setup environment for fetching future requests with the same IO tag. That is, `UBLK_IO_COMMIT_AND_FETCH_REQ` is reused for both fetching request and committing back IO result.

- `UBLK_U_IO_NEED_GET_DATA`

  With `UBLK_F_NEED_GET_DATA` enabled, the WRITE request will be firstly issued to ublk server without data copy. Then, IO backend of ublk server receives the request and it can allocate data buffer and embed its addr inside this new io command. After the kernel driver gets the command, data copy is done from request pages to this backend's buffer. Finally, backend receives the request again with data to be written and it can truly handle the request.

  `UBLK_IO_NEED_GET_DATA` adds one additional round-trip and one io_uring_enter() syscall. Any user thinks that it may lower performance should not enable UBLK_F_NEED_GET_DATA. ublk server pre-allocates IO buffer for each IO by default. Any new project should try to use this buffer to communicate with ublk driver. However, existing project may break or not able to consume the new buffer interface; that's why this command is added for backwards compatibility so that existing projects can still consume existing buffers.

- data copy between ublk server IO buffer and ublk block IO request

  The driver needs to copy the block IO request pages into the server buffer (pages) first for WRITE before notifying the server of the coming IO, so that the server can handle WRITE request.

  When the server handles READ request and sends `UBLK_IO_COMMIT_AND_FETCH_REQ` to the server, ublkdrv needs to copy the server buffer (pages) read to the IO request pages.

<a id="rst-batch-i-o-commands-ublk-f-batch-io"></a>

#### Batch I/O Commands (UBLK_F_BATCH_IO)

The `UBLK_F_BATCH_IO` feature provides an alternative high-performance I/O handling model that replaces the traditional per-I/O commands with per-queue batch commands. This significantly reduces communication overhead and enables better load balancing across multiple server tasks.

Key differences from traditional mode:

- **Per-queue vs Per-I/O**: Commands operate on queues rather than individual I/Os

- **Batch processing**: Multiple I/Os are handled in single operations

- **Multishot commands**: Use io_uring multishot for reduced submission overhead

- **Flexible task assignment**: Any task can handle any I/O (no per-I/O daemons)

- **Better load balancing**: Tasks can adjust their workload dynamically

Batch I/O Commands:

- `UBLK_U_IO_PREP_IO_CMDS`

  Prepares multiple I/O commands in batch. The server provides a buffer containing multiple I/O descriptors that will be processed together. This reduces the number of individual command submissions required.

- `UBLK_U_IO_COMMIT_IO_CMDS`

  Commits results for multiple I/O operations in batch, and prepares the I/O descriptors to accept new requests. The server provides a buffer containing the results of multiple completed I/Os, allowing efficient bulk completion of requests.

- `UBLK_U_IO_FETCH_IO_CMDS`

  **Multishot command** for fetching I/O commands in batch. This is the key command that enables high-performance batch processing:

  - Uses io_uring multishot capability for reduced submission overhead

  - Single command can fetch multiple I/O requests over time

  - Buffer size determines maximum batch size per operation

  - Multiple fetch commands can be submitted for load balancing

  - Only one fetch command is active at any time per queue

  - Supports dynamic load balancing across multiple server tasks

  It is one typical multishot io_uring request with provided buffer, and it won't be completed until any failure is triggered.

  Each task can submit `UBLK_U_IO_FETCH_IO_CMDS` with different buffer sizes to control how much work it handles. This enables sophisticated load balancing strategies in multi-threaded servers.

Migration: Applications using traditional commands (`UBLK_U_IO_FETCH_REQ`, `UBLK_U_IO_COMMIT_AND_FETCH_REQ`) cannot use batch mode simultaneously.

<a id="rst-zero-copy"></a>

### Zero copy

ublk zero copy relies on io_uring's fixed kernel buffer, which provides two APIs: `io_buffer_register_bvec()` and `io_buffer_unregister_bvec`.

ublk adds IO command of `UBLK_IO_REGISTER_IO_BUF` to call `io_buffer_register_bvec()` for ublk server to register client request buffer into io_uring buffer table, then ublk server can submit io_uring IOs with the registered buffer index. IO command of `UBLK_IO_UNREGISTER_IO_BUF` calls `io_buffer_unregister_bvec()` to unregister the buffer, which is guaranteed to be live between calling `io_buffer_register_bvec()` and `io_buffer_unregister_bvec()`. Any io_uring operation which supports this kind of kernel buffer will grab one reference of the buffer until the operation is completed.

ublk server implementing zero copy or user copy has to be CAP_SYS_ADMIN and be trusted, because it is ublk server's responsibility to make sure IO buffer filled with data for handling read command, and ublk server has to return correct result to ublk driver when handling READ command, and the result has to match with how many bytes filled to the IO buffer. Otherwise, uninitialized kernel IO buffer will be exposed to client application.

ublk server needs to align the parameter of `struct ublk_param_dma_align` with backend for zero copy to work correctly.

For reaching best IO performance, ublk server should align its segment parameter of `struct ublk_param_segment` with backend for avoiding unnecessary IO split, which usually hurts io_uring performance.

<a id="rst-auto-buffer-registration"></a>

### Auto Buffer Registration

The `UBLK_F_AUTO_BUF_REG` feature automatically handles buffer registration and unregistration for I/O requests, which simplifies the buffer management process and reduces overhead in the ublk server implementation.

This is another feature flag for using zero copy, and it is compatible with `UBLK_F_SUPPORT_ZERO_COPY`.

<a id="rst-feature-overview"></a>

#### Feature Overview

This feature automatically registers request buffers to the io_uring context before delivering I/O commands to the ublk server and unregisters them when completing I/O commands. This eliminates the need for manual buffer registration/unregistration via `UBLK_IO_REGISTER_IO_BUF` and `UBLK_IO_UNREGISTER_IO_BUF` commands, then IO handling in ublk server can avoid dependency on the two uring_cmd operations.

IOs can't be issued concurrently to io_uring if there is any dependency among these IOs. So this way not only simplifies ublk server implementation, but also makes concurrent IO handling becomes possible by removing the dependency on buffer registration &amp; unregistration commands.

<a id="rst-usage-requirements"></a>

#### Usage Requirements

1. The ublk server must create a sparse buffer table on the same `io_ring_ctx` used for `UBLK_IO_FETCH_REQ` and `UBLK_IO_COMMIT_AND_FETCH_REQ`. If uring_cmd is issued on a different `io_ring_ctx`, manual buffer unregistration is required.

2. Buffer registration data must be passed via uring_cmd's `sqe->addr` with the following structure:



   ```text
   struct ublk_auto_buf_reg {
       __u16 index;      /* Buffer index for registration */
       __u8 flags;       /* Registration flags */
       __u8 reserved0;   /* Reserved for future use */
       __u32 reserved1;  /* Reserved for future use */
   };
   ```

   ublk_auto_buf_reg_to_sqe_addr() is for converting the above structure into `sqe->addr`.

3. All reserved fields in `ublk_auto_buf_reg` must be zeroed.

4. Optional flags can be passed via `ublk_auto_buf_reg.flags`.

<a id="rst-fallback-behavior"></a>

#### Fallback Behavior

If auto buffer registration fails:

1. When `UBLK_AUTO_BUF_REG_FALLBACK` is enabled:

   - The uring_cmd is completed

   - `UBLK_IO_F_NEED_REG_BUF` is set in `ublksrv_io_desc.op_flags`

   - The ublk server must manually deal with the failure, such as, register the buffer manually, or using user copy feature for retrieving the data for handling ublk IO

2. If fallback is not enabled:

   - The ublk I/O request fails silently

   - The uring_cmd won't be completed

<a id="rst-limitations"></a>

#### Limitations

- Requires same `io_ring_ctx` for all operations

- May require manual buffer management in fallback cases

- io_ring_ctx buffer table has a max size of 16K, which may not be enough in case that too many ublk devices are handled by this single io_ring_ctx and each one has very large queue depth

<a id="rst-references"></a>

## References

<a id="rst-userspace"></a>



**[1]** [https://github.com/ming1/ubdsrv](<https://github.com/ming1/ubdsrv>)

<a id="rst-userspace-lib"></a>



**[2]** [https://github.com/ming1/ubdsrv/tree/master/lib](<https://github.com/ming1/ubdsrv/tree/master/lib>)

<a id="rst-userspace-nbdublk"></a>



**[3]** [https://gitlab.com/rwmjones/libnbd/-/tree/nbdublk](<https://gitlab.com/rwmjones/libnbd/-/tree/nbdublk>)

<a id="rst-userspace-readme"></a>



**[4]** [https://github.com/ming1/ubdsrv/blob/master/README](<https://github.com/ming1/ubdsrv/blob/master/README>)

---

# Explicit volatile write back cache control

_Peios Kernel / Internals / Block_

> Many storage devices, especially in the consumer market, come with volatile write back caches. That means the devices signal I/O completion to the operating system before data actually has hit the non-volatile storage. This behavior…

<a id="rst-explicit-volatile-write-back-cache-control"></a>

<a id="rst-introduction"></a>

## Introduction

Many storage devices, especially in the consumer market, come with volatile write back caches.  That means the devices signal I/O completion to the operating system before data actually has hit the non-volatile storage.  This behavior obviously speeds up various workloads, but it means the operating system needs to force data out to the non-volatile storage when it performs a data integrity operation like fsync, sync or an unmount.

The Linux block layer provides two simple mechanisms that let filesystems control the caching behavior of the storage device.  These mechanisms are a forced cache flush, and the Force Unit Access (FUA) flag for requests.

<a id="rst-explicit-cache-flushes"></a>

## Explicit cache flushes

The REQ_PREFLUSH flag can be OR ed into the r/w flags of a bio submitted from the filesystem and will make sure the volatile cache of the storage device has been flushed before the actual I/O operation is started.  This explicitly guarantees that previously completed write requests are on non-volatile storage before the flagged bio starts. In addition the REQ_PREFLUSH flag can be set on an otherwise empty bio structure, which causes only an explicit cache flush without any dependent I/O.  It is recommend to use the blkdev_issue_flush() helper for a pure cache flush.

<a id="rst-forced-unit-access"></a>

## Forced Unit Access

The REQ_FUA flag can be OR ed into the r/w flags of a bio submitted from the filesystem and will make sure that I/O completion for this request is only signaled after the data has been committed to non-volatile storage.

<a id="rst-implementation-details-for-filesystems"></a>

## Implementation details for filesystems

Filesystems can simply set the REQ_PREFLUSH and REQ_FUA bits and do not have to worry if the underlying devices need any explicit cache flushing and how the Forced Unit Access is implemented.  The REQ_PREFLUSH and REQ_FUA flags may both be set on a single bio.

<a id="rst-feature-settings-for-block-drivers"></a>

## Feature settings for block drivers

For devices that do not support volatile write caches there is no driver support required, the block layer completes empty REQ_PREFLUSH requests before entering the driver and strips off the REQ_PREFLUSH and REQ_FUA bits from requests that have a payload.

For devices with volatile write caches the driver needs to tell the block layer that it supports flushing caches by setting the

> BLK_FEAT_WRITE_CACHE

flag in the queue_limits feature field.  For devices that also support the FUA bit the block layer needs to be told to pass on the REQ_FUA bit by also setting the

> BLK_FEAT_FUA

flag in the features field of the queue_limits structure.

<a id="rst-implementation-details-for-bio-based-block-drivers"></a>

## Implementation details for bio based block drivers

For bio based drivers the REQ_PREFLUSH and REQ_FUA bit are simply passed on to the driver if the driver sets the BLK_FEAT_WRITE_CACHE flag and the driver needs to handle them.

*NOTE*: The REQ_FUA bit also gets passed on when the BLK_FEAT_FUA flags is \_not\_ set.  Any bio based driver that sets BLK_FEAT_WRITE_CACHE also needs to handle REQ_FUA.

For remapping drivers the REQ_FUA bits need to be propagated to underlying devices, and a global flush needs to be implemented for bios with the REQ_PREFLUSH bit set.

<a id="rst-implementation-details-for-blk-mq-drivers"></a>

## Implementation details for blk-mq drivers

When the BLK_FEAT_WRITE_CACHE flag is set, REQ_OP_WRITE \| REQ_PREFLUSH requests with a payload are automatically turned into a sequence of a REQ_OP_FLUSH request followed by the actual write by the block layer.

When the BLK_FEAT_FUA flags is set, the REQ_FUA bit is simply passed on for the REQ_OP_WRITE request, else a REQ_OP_FLUSH request is sent by the block layer after the completion of the write request for bio submissions with the REQ_FUA bit set.

---

# Filesystems in the Linux kernel

_Peios Kernel / Internals / Filesystems_

> This under-development manual will, some glorious day, provide comprehensive information on how the Linux virtual filesystem (VFS) layer works, along with the filesystems that sit below it. For now, what we have can be found below.

<a id="rst-filesystems-in-the-linux-kernel"></a>
<a id="rst-filesystems-index"></a>

This under-development manual will, some glorious day, provide comprehensive information on how the Linux virtual filesystem (VFS) layer works, along with the filesystems that sit below it.  For now, what we have can be found below.

<a id="rst-core-vfs-documentation"></a>

## Core VFS documentation

See these manuals for documentation about the VFS layer itself and how its algorithms work.

- [Overview of the Linux Virtual File System](</kernel/internals/filesystems/vfs.md>)
- [Pathname lookup](</kernel/internals/filesystems/path-lookup.md>)
- [Linux Filesystems API summary](</kernel/internals/filesystems/api-summary.md>)
- [splice and pipes](</kernel/internals/filesystems/splice.md>)
- [Locking](</kernel/internals/filesystems/locking.md>)
- [Directory Locking](</kernel/internals/filesystems/directory-locking.md>)
- [The Devpts Filesystem](</kernel/internals/filesystems/devpts.md>)
- [Linux Directory Notification](</kernel/internals/filesystems/dnotify.md>)
- [Fiemap Ioctl](</kernel/internals/filesystems/fiemap.md>)
- [File management in the Linux kernel](</kernel/internals/filesystems/files.md>)
- [File Locking Release Notes](</kernel/internals/filesystems/locks.md>)
- [Multigrain Timestamps](</kernel/internals/filesystems/multigrain-ts.md>)
- [Filesystem Mount API](</kernel/internals/filesystems/mount-api.md>)
- [Quota subsystem](</kernel/internals/filesystems/quota.md>)
- [The seq_file Interface](</kernel/internals/filesystems/seq-file.md>)
- [Shared Subtrees](</kernel/internals/filesystems/sharedsubtree.md>)
- [Idmappings](</kernel/internals/filesystems/idmappings.md>)
- [VFS iomap Documentation](</kernel/internals/filesystems/iomap/index.md>)
- [Automount Support](</kernel/internals/filesystems/automount-support.md>)
- [Filesystem Caching](</kernel/internals/filesystems/caching/index.md>)
- [Changes since 2.5.0:](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/porting.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

<a id="rst-filesystem-support-layers"></a>

## Filesystem support layers

Documentation for the support code within the filesystem layer for use in filesystem implementations.

- [Buffer Heads](</kernel/internals/filesystems/buffer.md>)
- [The Linux Journalling API](</kernel/internals/filesystems/journalling.md>)
- [Filesystem-level encryption (fscrypt)](</kernel/internals/filesystems/fscrypt.md>)
- [fs-verity: read-only file-based authenticity protection](</kernel/internals/filesystems/fsverity.md>)
- [Network Filesystem Services Library](</kernel/internals/filesystems/netfs-library.md>)

<a id="rst-filesystems"></a>

## Filesystems

Documentation for filesystem implementations.

- [v9fs: Plan 9 Resource Sharing for Linux](</kernel/internals/filesystems/9p.md>)
- [Acorn Disc Filing System - ADFS](</kernel/internals/filesystems/adfs.md>)
- [Overview of Amiga Filesystems](</kernel/internals/filesystems/affs.md>)
- [kAFS: AFS FILESYSTEM](</kernel/internals/filesystems/afs.md>)
- [autofs - how it works](</kernel/internals/filesystems/autofs.md>)
- [Miscellaneous Device control operations for the autofs kernel module](</kernel/internals/filesystems/autofs-mount-control.md>)
- [BeOS filesystem for Linux](</kernel/internals/filesystems/befs.md>)
- [BFS Filesystem for Linux](</kernel/internals/filesystems/bfs.md>)
- [BTRFS](</kernel/internals/filesystems/btrfs.md>)
- [Ceph Distributed File System](</kernel/internals/filesystems/ceph.md>)
- [Coda Kernel-Venus Interface](</kernel/internals/filesystems/coda.md>)
- [Configfs - Userspace-driven Kernel Object Configuration](</kernel/internals/filesystems/configfs.md>)
- [Cramfs - cram a filesystem onto a small ROM](</kernel/internals/filesystems/cramfs.md>)
- [Direct Access for files](</kernel/internals/filesystems/dax.md>)
- [DebugFS](</kernel/internals/filesystems/debugfs.md>)
- [DLMFS](</kernel/internals/filesystems/dlmfs.md>)
- [eCryptfs: A stacked cryptographic filesystem for Linux](</kernel/internals/filesystems/ecryptfs.md>)
- [efivarfs - a (U)EFI variable filesystem](</kernel/internals/filesystems/efivarfs.md>)
- [EROFS - Enhanced Read-Only File System](</kernel/internals/filesystems/erofs.md>)
- [The Second Extended Filesystem](</kernel/internals/filesystems/ext2.md>)
- [Ext3 Filesystem](</kernel/internals/filesystems/ext3.md>)
- [ext4 Data Structures and Algorithms](</kernel/internals/filesystems/ext4/index.md>)
- [Flash-Friendly File System (F2FS)](</kernel/internals/filesystems/f2fs.md>)
- [Global File System 2](</kernel/internals/filesystems/gfs2/index.md>)
- [Macintosh HFS Filesystem for Linux](</kernel/internals/filesystems/hfs.md>)
- [Macintosh HFSPlus Filesystem for Linux](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/hfsplus.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Read/Write HPFS 2.09](</kernel/internals/filesystems/hpfs.md>)
- [FUSE (Filesystem in Userspace) Technical Documentation](</kernel/internals/filesystems/fuse/index.md>)
- [Inotify - A Powerful yet Simple File Change Notification System](</kernel/internals/filesystems/inotify.md>)
- [ISO9660 Filesystem](</kernel/internals/filesystems/isofs.md>)
- [NILFS2](</kernel/internals/filesystems/nilfs2.md>)
- [NFS](</kernel/internals/filesystems/nfs/index.md>)
- [NTFS3](</kernel/internals/filesystems/ntfs3.md>)
- [OCFS2 filesystem](</kernel/internals/filesystems/ocfs2.md>)
- [OCFS2 file system - online file check](</kernel/internals/filesystems/ocfs2-online-filecheck.md>)
- [Optimized MPEG Filesystem (OMFS)](</kernel/internals/filesystems/omfs.md>)
- [ORANGEFS](</kernel/internals/filesystems/orangefs.md>)
- [Overlay Filesystem](</kernel/internals/filesystems/overlayfs.md>)
- [The /proc Filesystem](</kernel/internals/filesystems/proc.md>)
- [The QNX6 Filesystem](</kernel/internals/filesystems/qnx6.md>)
- [Ramfs, rootfs and initramfs](</kernel/internals/filesystems/ramfs-rootfs-initramfs.md>)
- [relay interface (formerly relayfs)](</kernel/internals/filesystems/relay.md>)
- [User Interface for Resource Control feature (resctrl)](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/resctrl.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [ROMFS - ROM File System](</kernel/internals/filesystems/romfs.md>)
- [CIFS](</kernel/internals/filesystems/smb/index.md>)
- [SPU Filesystem](</kernel/internals/filesystems/spufs/index.md>)
- [Squashfs 4.0 Filesystem](</kernel/internals/filesystems/squashfs.md>)
- [sysfs - \_The\_ filesystem for exporting kernel objects](</kernel/internals/filesystems/sysfs.md>)
- [Tmpfs](</kernel/internals/filesystems/tmpfs.md>)
- [UBI File System](</kernel/internals/filesystems/ubifs.md>)
- [UBIFS Authentication Support](</kernel/internals/filesystems/ubifs-authentication.md>)
- [UDF file system](</kernel/internals/filesystems/udf.md>)
- [virtiofs: virtio-fs host&lt;-&gt;guest shared file system](</kernel/internals/filesystems/virtiofs.md>)
- [VFAT](</kernel/internals/filesystems/vfat.md>)
- [XFS Filesystem Documentation](</kernel/internals/filesystems/xfs/index.md>)
- [ZoneFS - Zone filesystem for Zoned block devices](</kernel/internals/filesystems/zonefs.md>)

---

# v9fs: Plan 9 Resource Sharing for Linux

_Peios Kernel / Internals / Filesystems_

> v9fs is a Unix implementation of the Plan 9 9p remote filesystem protocol.

<a id="rst-v9fs-plan-9-resource-sharing-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-about"></a>

## About

v9fs is a Unix implementation of the Plan 9 9p remote filesystem protocol.

This software was originally developed by Ron Minnich &lt;[rminnich@sandia.gov](<mailto:rminnich@sandia.gov>)&gt; and Maya Gokhale.  Additional development by Greg Watson &lt;[gwatson@lanl.gov](<mailto:gwatson@lanl.gov>)&gt; and most recently Eric Van Hensbergen &lt;[ericvh@gmail.com](<mailto:ericvh@gmail.com>)&gt;, Latchesar Ionkov &lt;[lucho@ionkov.net](<mailto:lucho@ionkov.net>)&gt; and Russ Cox &lt;[rsc@swtch.com](<mailto:rsc@swtch.com>)&gt;.

The best detailed explanation of the Linux implementation and applications of the 9p client is available in the form of a USENIX paper:

> [https://www.usenix.org/events/usenix05/tech/freenix/hensbergen.html](<https://www.usenix.org/events/usenix05/tech/freenix/hensbergen.html>)

Other applications are described in the following papers:

> - XCPU &amp; Clustering [http://xcpu.org/papers/xcpu-talk.pdf](<http://xcpu.org/papers/xcpu-talk.pdf>)
>
> - KVMFS: control file system for KVM [http://xcpu.org/papers/kvmfs.pdf](<http://xcpu.org/papers/kvmfs.pdf>)
>
> - CellFS: A New Programming Model for the Cell BE [http://xcpu.org/papers/cellfs-talk.pdf](<http://xcpu.org/papers/cellfs-talk.pdf>)
>
> - PROSE I/O: Using 9p to enable Application Partitions [http://plan9.escet.urjc.es/iwp9/cready/PROSE_iwp9_2006.pdf](<http://plan9.escet.urjc.es/iwp9/cready/PROSE_iwp9_2006.pdf>)
>
> - VirtFS: A Virtualization Aware File System pass-through [https://kernel.org/doc/ols/2010/ols2010-pages-109-120.pdf](<https://kernel.org/doc/ols/2010/ols2010-pages-109-120.pdf>)

<a id="rst-usage"></a>

## Usage

For remote file server:



```text
mount -t 9p 10.10.1.2 /mnt/9
```

For Plan 9 From User Space applications ([https://9fans.github.io/plan9port/](<https://9fans.github.io/plan9port/>)):



```text
mount -t 9p `namespace`/acme /mnt/9 -o trans=unix,uname=$USER
```

For server running on QEMU host with virtio transport:



```text
mount -t 9p -o trans=virtio <mount_tag> /mnt/9
```

where mount_tag is the tag generated by the server to each of the exported mount points. Each 9P export is seen by the client as a virtio device with an associated "mount_tag" property. Available mount tags can be seen by reading /sys/bus/virtio/drivers/9pnet_virtio/virtio&lt;n&gt;/mount_tag files.

<a id="rst-usbg-usage"></a>

## USBG Usage

To mount a 9p FS on a USB Host accessible via the gadget at runtime:



```text
mount -t 9p -o trans=usbg,aname=/path/to/fs <device> /mnt/9
```

To mount a 9p FS on a USB Host accessible via the gadget as root filesystem:



```text
root=<device> rootfstype=9p rootflags=trans=usbg,cache=loose,uname=root,access=0,dfltuid=0,dfltgid=0,aname=/path/to/rootfs
```

where &lt;device&gt; is the tag associated by the usb gadget transport. It is defined by the configfs instance name.

<a id="rst-usbg-example"></a>

## USBG Example

The USB host exports a filesystem, while the gadget on the USB device side makes it mountable.

Diod (9pfs server) and the forwarder are on the development host, where the root filesystem is actually stored. The gadget is initialized during boot (or later) on the embedded board. Then the forwarder will find it on the USB bus and start forwarding requests.

In this case the 9p requests come from the device and are handled by the host. The reason is that USB device ports are normally not available on PCs, so a connection in the other direction would not work.

When using the usbg transport, for now there is no native usb host service capable to handle the requests from the gadget driver. For this we have to use the extra python tool p9_fwd.py from tools/usb.

Just start the 9pfs capable network server like diod/nfs-ganesha e.g.:



```text
$ diod -f -n -d 0 -S -l 0.0.0.0:9999 -e $PWD
```

Optionally scan your bus if there are more then one usbg gadgets to find their path:



```text
$ python $kernel_dir/tools/usb/p9_fwd.py list

Bus | Addr | Manufacturer     | Product          | ID        | Path
--- | ---- | ---------------- | ---------------- | --------- | ----
  2 |   67 | unknown          | unknown          | 1d6b:0109 | 2-1.1.2
  2 |   68 | unknown          | unknown          | 1d6b:0109 | 2-1.1.3
```

Then start the python transport:



```text
$ python $kernel_dir/tools/usb/p9_fwd.py --path 2-1.1.2 connect -p 9999
```

After that the gadget driver can be used as described above.

One use-case is to use it as an alternative to NFS root booting during the development of embedded Linux devices.

<a id="rst-options"></a>

## Options

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> trans=name
>
> </td>
> <td>
>
>
> select an alternative transport.  Valid options are currently:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > unix
> >
> > </td>
> > <td>
> >
> >
> > specifying a named pipe mount point
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > tcp
> >
> > </td>
> > <td>
> >
> >
> > specifying a normal TCP/IP connection
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > fd
> >
> > </td>
> > <td>
> >
> >
> > used passed file descriptors for connection (see rfdno and wfdno)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > virtio
> >
> > </td>
> > <td>
> >
> >
> > connect to the next virtio channel available (from QEMU with trans_virtio module)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > rdma
> >
> > </td>
> > <td>
> >
> >
> > connect to a specified RDMA channel
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > usbg
> >
> > </td>
> > <td>
> >
> >
> > connect to a specified usb gadget channel
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> uname=name
>
> </td>
> <td>
>
>
> user name to attempt mount as on the remote server.  The server may override or ignore this value.  Certain user names may require authentication.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> aname=name
>
> </td>
> <td>
>
>
> aname specifies the file tree to access when the server is offering several exported file systems.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cache=mode
>
> </td>
> <td>
>
>
> specifies a caching policy.  By default, no caches are used. The mode can be specified as a bitmask or by using one of the preexisting common 'shortcuts'. The bitmask is described below: (unspecified bits are reserved)
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 0b00000000
> >
> > </td>
> > <td>
> >
> >
> > all caches disabled, mmap disabled
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0b00000001
> >
> > </td>
> > <td>
> >
> >
> > file caches enabled
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0b00000010
> >
> > </td>
> > <td>
> >
> >
> > meta-data caches enabled
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0b00000100
> >
> > </td>
> > <td>
> >
> >
> > writeback behavior (as opposed to writethrough)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0b00001000
> >
> > </td>
> > <td>
> >
> >
> > loose caches (no explicit consistency with server)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0b10000000
> >
> > </td>
> > <td>
> >
> >
> > fscache enabled for persistent caching
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> The current shortcuts and their associated bitmask are:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > none
> >
> > </td>
> > <td>
> >
> >
> > 0b00000000 (no caching)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > readahead
> >
> > </td>
> > <td>
> >
> >
> > 0b00000001 (only read-ahead file caching)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > mmap
> >
> > </td>
> > <td>
> >
> >
> > 0b00000101 (read-ahead + writeback file cache)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > loose
> >
> > </td>
> > <td>
> >
> >
> > 0b00001111 (non-coherent file and meta-data caches)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > fscache
> >
> > </td>
> > <td>
> >
> >
> > 0b10001111 (persistent loose cache)
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> NOTE: only these shortcuts are tested modes of operation at the moment, so using other combinations of bit-patterns is not known to work.  Work on better cache support is in progress.
>
> IMPORTANT: loose caches (and by extension at the moment fscache) do not necessarily validate cached values on the server.  In other words changes on the server are not guaranteed to be reflected on the client system.  Only use this mode of operation if you have an exclusive mount and the server will not modify the filesystem underneath you.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> debug=n
>
> </td>
> <td>
>
>
> specifies debug level.  The debug level is a bitmask.
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 0x01
> >
> > </td>
> > <td>
> >
> >
> > display verbose error messages
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x02
> >
> > </td>
> > <td>
> >
> >
> > developer debug (DEBUG_CURRENT)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x04
> >
> > </td>
> > <td>
> >
> >
> > display 9p trace
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x08
> >
> > </td>
> > <td>
> >
> >
> > display VFS trace
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x10
> >
> > </td>
> > <td>
> >
> >
> > display Marshalling debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x20
> >
> > </td>
> > <td>
> >
> >
> > display RPC debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x40
> >
> > </td>
> > <td>
> >
> >
> > display transport debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x80
> >
> > </td>
> > <td>
> >
> >
> > display allocation debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x100
> >
> > </td>
> > <td>
> >
> >
> > display protocol message debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x200
> >
> > </td>
> > <td>
> >
> >
> > display Fid debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x400
> >
> > </td>
> > <td>
> >
> >
> > display packet debug
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 0x800
> >
> > </td>
> > <td>
> >
> >
> > display fscache tracing debug
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rfdno=n
>
> </td>
> <td>
>
>
> the file descriptor for reading with trans=fd
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> wfdno=n
>
> </td>
> <td>
>
>
> the file descriptor for writing with trans=fd
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> msize=n
>
> </td>
> <td>
>
>
> the number of bytes to use for 9p packet payload
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> port=n
>
> </td>
> <td>
>
>
> port to connect to on the remote server
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> noextend
>
> </td>
> <td>
>
>
> force legacy mode (no 9p2000.u or 9p2000.L semantics)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> version=name
>
> </td>
> <td>
>
>
> Select 9P protocol version. Valid options are:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 9p2000
> >
> > </td>
> > <td>
> >
> >
> > Legacy mode (same as noextend)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 9p2000.u
> >
> > </td>
> > <td>
> >
> >
> > Use 9P2000.u protocol
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 9p2000.L
> >
> > </td>
> > <td>
> >
> >
> > Use 9P2000.L protocol
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dfltuid
>
> </td>
> <td>
>
>
> attempt to mount as a particular uid
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dfltgid
>
> </td>
> <td>
>
>
> attempt to mount with a particular gid
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> afid
>
> </td>
> <td>
>
>
> security channel - used by Plan 9 authentication protocols
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nodevmap
>
> </td>
> <td>
>
>
> do not map special files - represent them as normal files. This can be used to share devices/named pipes/sockets between hosts.  This functionality will be expanded in later versions.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> directio
>
> </td>
> <td>
>
>
> bypass page cache on all read/write operations
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ignoreqv
>
> </td>
> <td>
>
>
> ignore qid.version==0 as a marker to ignore cache
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> noxattr
>
> </td>
> <td>
>
>
> do not offer xattr functions on this mount.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> access
>
> </td>
> <td>
>
>
> - **there are four access modes.**
>
>   - **user**
>
>     if a user tries to access a file on v9fs filesystem for the first time, v9fs sends an attach command (Tattach) for that user. This is the default mode.
>
>   - **&lt;uid&gt;**
>
>     allows only user with uid=&lt;uid&gt; to access the files on the mounted filesystem
>
>   - **any**
>
>     v9fs does single attach and performs all operations as one user
>
>   - **clien**
>
>     ACL based access check on the 9p client side for access validation
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cachetag
>
> </td>
> <td>
>
>
> cache tag to use the specified persistent cache. cache tags for existing cache sessions can be listed at /sys/fs/9p/caches. (applies only to cache=fscache)
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-behavior"></a>

## Behavior

This section aims at describing 9p 'quirks' that can be different from a local filesystem behaviors.

> - Setting O_NONBLOCK on a file will make client reads return as early as the server returns some data instead of trying to fill the read buffer with the requested amount of bytes or end of file is reached.

<a id="rst-resources"></a>

## Resources

Protocol specifications are maintained on github: [http://ericvh.github.com/9p-rfc/](<http://ericvh.github.com/9p-rfc/>)

9p client and server implementations are listed on [http://9p.cat-v.org/implementations](<http://9p.cat-v.org/implementations>)

A 9p2000.L server is being developed by LLNL and can be found at [http://code.google.com/p/diod/](<http://code.google.com/p/diod/>)

There are user and developer mailing lists available through the v9fs project on sourceforge ([http://sourceforge.net/projects/v9fs](<http://sourceforge.net/projects/v9fs>)).

News and other information is maintained on a Wiki. ([http://sf.net/apps/mediawiki/v9fs/index.php](<http://sf.net/apps/mediawiki/v9fs/index.php>)).

Bug reports are best issued via the mailing list.

For more information on the Plan 9 Operating System check out [http://plan9.bell-labs.com/plan9](<http://plan9.bell-labs.com/plan9>)

For information on Plan 9 from User Space (Plan 9 applications and libraries ported to Linux/BSD/OSX/etc) check out [https://9fans.github.io/plan9port/](<https://9fans.github.io/plan9port/>)

---

# Acorn Disc Filing System - ADFS

_Peios Kernel / Internals / Filesystems_

> The ADFS module supports the following Filecore formats which have:

<a id="rst-acorn-disc-filing-system-adfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-filesystems-supported-by-adfs"></a>

## Filesystems supported by ADFS

The ADFS module supports the following Filecore formats which have:

- new maps

- new directories or big directories

In terms of the named formats, this means we support:

- E and E+, with or without boot block

- F and F+

We fully support reading files from these filesystems, and writing to existing files within their existing allocation.  Essentially, we do not support changing any of the filesystem metadata.

This is intended to support loopback mounted Linux native filesystems on a RISC OS Filecore filesystem, but will allow the data within files to be changed.

If write support (ADFS_FS_RW) is configured, we allow rudimentary directory updates, specifically updating the access mode and timestamp.

<a id="rst-mount-options-for-adfs"></a>

## Mount options for ADFS

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> uid=nnn
>
> </td>
> <td>
>
>
> All files in the partition will be owned by user id nnn.  Default 0 (root).
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gid=nnn
>
> </td>
> <td>
>
>
> All files in the partition will be in group nnn.  Default 0 (root).
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ownmask=nnn
>
> </td>
> <td>
>
>
> The permission mask for ADFS 'owner' permissions will be nnn.  Default 0700.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> othmask=nnn
>
> </td>
> <td>
>
>
> The permission mask for ADFS 'other' permissions will be nnn.  Default 0077.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ftsuffix=n
>
> </td>
> <td>
>
>
> When ftsuffix=0, no file type suffix will be applied. When ftsuffix=1, a hexadecimal suffix corresponding to the RISC OS file type will be added.  Default 0.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-mapping-of-adfs-permissions-to-linux-permissions"></a>

## Mapping of ADFS permissions to Linux permissions

> ADFS permissions consist of the following:
>
> > - Owner read
> >
> > - Owner write
> >
> > - Other read
> >
> > - Other write
>
> (In older versions, an 'execute' permission did exist, but this does not hold the same meaning as the Linux 'execute' permission and is now obsolete).
>
> The mapping is performed as follows:
>
>
>
> ```text
>     Owner read                              -> -r--r--r--
>     Owner write                             -> --w--w---w
>     Owner read and filetype UnixExec        -> ---x--x--x
> These are then masked by ownmask, eg 700    -> -rwx------
>     Possible owner mode permissions         -> -rwx------
>
>     Other read                              -> -r--r--r--
>     Other write                             -> --w--w--w-
>     Other read and filetype UnixExec        -> ---x--x--x
> These are then masked by othmask, eg 077    -> ----rwxrwx
>     Possible other mode permissions         -> ----rwxrwx
> ```
>
> Hence, with the default masks, if a file is owner read/write, and not a UnixExec filetype, then the permissions will be:
>
>
>
> ```text
> -rw-------
> ```
>
> However, if the masks were ownmask=0770,othmask=0007, then this would be modified to:
>
>
>
> ```text
> -rw-rw----
> ```
>
> There is no restriction on what you can do with these masks.  You may wish that either read bits give read access to the file for all, but keep the default write protection (ownmask=0755,othmask=0577):
>
>
>
> ```text
> -rw-r--r--
> ```
>
> You can therefore tailor the permission translation to whatever you desire the permissions should be under Linux.

<a id="rst-risc-os-file-type-suffix"></a>

## RISC OS file type suffix

> RISC OS file types are stored in bits 19..8 of the file load address.
>
> To enable non-RISC OS systems to be used to store files without losing file type information, a file naming convention was devised (initially for use with NFS) such that a hexadecimal suffix of the form ,xyz denoted the file type: e.g. BasicFile,ffb is a BASIC (0xffb) file.  This naming convention is now also used by RISC OS emulators such as RPCEmu.
>
> Mounting an ADFS disc with option ftsuffix=1 will cause appropriate file type suffixes to be appended to file names read from a directory.  If the ftsuffix option is zero or omitted, no file type suffixes will be added.

---

# Overview of Amiga Filesystems

_Peios Kernel / Internals / Filesystems_

> Not all varieties of the Amiga filesystems are supported for reading and writing. The Amiga currently knows six different filesystems:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-overview-of-amiga-filesystems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Not all varieties of the Amiga filesystems are supported for reading and writing. The Amiga currently knows six different filesystems:


<table>
<tbody>
<tr>
<td>


DOS0

</td>
<td>


The old or original filesystem, not really suited for hard disks and normally not used on them, either. Supported read/write.

</td>
</tr>
<tr>
<td>


DOS1

</td>
<td>


The original Fast File System. Supported read/write.

</td>
</tr>
<tr>
<td>


DOS2

</td>
<td>


The old "international" filesystem. International means that a bug has been fixed so that accented ("international") letters in file names are case-insensitive, as they ought to be. Supported read/write.

</td>
</tr>
<tr>
<td>


DOS3

</td>
<td>


The "international" Fast File System.  Supported read/write.

</td>
</tr>
<tr>
<td>


DOS4

</td>
<td>


The original filesystem with directory cache. The directory cache speeds up directory accesses on floppies considerably, but slows down file creation/deletion. Doesn't make much sense on hard disks. Supported read only.

</td>
</tr>
<tr>
<td>


DOS5

</td>
<td>


The Fast File System with directory cache. Supported read only.

</td>
</tr>
</tbody>
</table>

All of the above filesystems allow block sizes from 512 to 32K bytes. Supported block sizes are: 512, 1024, 2048 and 4096 bytes. Larger blocks speed up almost everything at the expense of wasted disk space. The speed gain above 4K seems not really worth the price, so you don't lose too much here, either.

The muFS (multi user File System) equivalents of the above file systems are supported, too.

<a id="rst-mount-options-for-the-affs"></a>

## Mount options for the AFFS

- **protect**

  If this option is set, the protection bits cannot be altered.

- **setuid\[=uid\]**

  This sets the owner of all files and directories in the file system to uid or the uid of the current user, respectively.

- **setgid\[=gid\]**

  Same as above, but for gid.

- **mode=mode**

  Sets the mode flags to the given (octal) value, regardless of the original permissions. Directories will get an x permission if the corresponding r bit is set. This is useful since most of the plain AmigaOS files will map to 600.

- **nofilenametruncate**

  The file system will return an error when filename exceeds standard maximum filename length (30 characters).

- **reserved=num**

  Sets the number of reserved blocks at the start of the partition to num. You should never need this option. Default is 2.

- **root=block**

  Sets the block number of the root block. This should never be necessary.

- **bs=blksize**

  Sets the blocksize to blksize. Valid block sizes are 512, 1024, 2048 and 4096. Like the root option, this should never be necessary, as the affs can figure it out itself.

- **quiet**

  The file system will not return an error for disallowed mode changes.

- **verbose**

  The volume name, file system type and block size will be written to the syslog when the filesystem is mounted.

- **mufs**

  The filesystem is really a muFS, also it doesn't identify itself as one. This option is necessary if the filesystem wasn't formatted as muFS, but is used as one.

- **prefix=path**

  Path will be prefixed to every absolute path name of symbolic links on an AFFS partition. Default = "/". (See below.)

- **volume=name**

  When symbolic links with an absolute path are created on an AFFS partition, name will be prepended as the volume name. Default = "" (empty string). (See below.)

<a id="rst-handling-of-the-users-groups-and-protection-flags"></a>

## Handling of the Users/Groups and protection flags

Amiga -&gt; Linux:

The Amiga protection flags RWEDRWEDHSPARWED are handled as follows:

> - R maps to r for user, group and others. On directories, R implies x.
>
> - W maps to w.
>
> - E maps to x.
>
> - D is ignored.
>
> - H, S and P are always retained and ignored under Linux.
>
> - A is cleared when a file is written to.

User id and group id will be used unless set\[gu\]id are given as mount options. Since most of the Amiga file systems are single user systems they will be owned by root. The root directory (the mount point) of the Amiga filesystem will be owned by the user who actually mounts the filesystem (the root directory doesn't have uid/gid fields).

Linux -&gt; Amiga:

The Linux rwxrwxrwx file mode is handled as follows:

> - r permission will allow R for user, group and others.
>
> - w permission will allow W for user, group and others.
>
> - x permission of the user will allow E for plain files.
>
> - D will be allowed for user, group and others.
>
> - All other flags (suid, sgid, ...) are ignored and will not be retained.

Newly created files and directories will get the user and group ID of the current user and a mode according to the umask.

<a id="rst-symbolic-links"></a>

## Symbolic links

Although the Amiga and Linux file systems resemble each other, there are some, not always subtle, differences. One of them becomes apparent with symbolic links. While Linux has a file system with exactly one root directory, the Amiga has a separate root directory for each file system (for example, partition, floppy disk, ...). With the Amiga, these entities are called "volumes". They have symbolic names which can be used to access them. Thus, symbolic links can point to a different volume. AFFS turns the volume name into a directory name and prepends the prefix path (see prefix option) to it.

Example: You mount all your Amiga partitions under /amiga/&lt;volume&gt; (where &lt;volume&gt; is the name of the volume), and you give the option "prefix=/amiga/" when mounting all your AFFS partitions. (They might be "User", "WB" and "Graphics", the mount points /amiga/User, /amiga/WB and /amiga/Graphics). A symbolic link referring to "User:sc/include/dos/dos.h" will be followed to "/amiga/User/sc/include/dos/dos.h".

<a id="rst-examples"></a>

## Examples

Command line:



```text
mount  Archive/Amiga/Workbench3.1.adf /mnt -t affs -o loop,verbose
mount  /dev/sda3 /Amiga -t affs
```

/etc/fstab entry:



```text
/dev/sdb5   /amiga/Workbench    affs    noauto,user,exec,verbose 0 0
```

<a id="rst-important-note"></a>

## IMPORTANT NOTE

If you boot Windows 95 (don't know about 3.x, 98 and NT) while you have an Amiga harddisk connected to your PC, it will overwrite the bytes 0x00dc..0x00df of block 0 with garbage, thus invalidating the Rigid Disk Block. Sheer luck has it that this is an unused area of the RDB, so only the checksum doesn't match anymore. Linux will ignore this garbage and recognize the RDB anyway, but before you connect that drive to your Amiga again, you must restore or repair your RDB. So please do make a backup copy of it before booting Windows\!

If the damage is already done, the following should fix the RDB (where &lt;disk&gt; is the device name).

DO AT YOUR OWN RISK:



```text
dd if=/dev/<disk> of=rdb.tmp count=1
cp rdb.tmp rdb.fixed
dd if=/dev/zero of=rdb.fixed bs=1 seek=220 count=4
dd if=rdb.fixed of=/dev/<disk>
```

<a id="rst-bugs-restrictions-caveats"></a>

## Bugs, Restrictions, Caveats

Quite a few things may not work as advertised. Not everything is tested, though several hundred MB have been read and written using this fs. For a most up-to-date list of bugs please consult fs/affs/Changes.

By default, filenames are truncated to 30 characters without warning. 'nofilenametruncate' mount option can change that behavior.

Case is ignored by the affs in filename matching, but Linux shells do care about the case. Example (with /wb being an affs mounted fs):



```text
rm /wb/WRONGCASE
```

will remove /mnt/wrongcase, but:



```text
rm /wb/WR*
```

will not since the names are matched by the shell.

The block allocation is designed for hard disk partitions. If more than 1 process writes to a (small) diskette, the blocks are allocated in an ugly way (but the real AFFS doesn't do much better). This is also true when space gets tight.

You cannot execute programs on an OFS (Old File System), since the program files cannot be memory mapped due to the 488 byte blocks. For the same reason you cannot mount an image on such a filesystem via the loopback device.

The bitmap valid flag in the root block may not be accurate when the system crashes while an affs partition is mounted. There's currently no way to fix a garbled filesystem without an Amiga (disk validator) or manually (who would do this?). Maybe later.

If you mount affs partitions on system startup, you may want to tell fsck that the fs should not be checked (place a '0' in the sixth field of /etc/fstab).

It's not possible to read floppy disks with a normal PC or workstation due to an incompatibility with the Amiga floppy controller.

If you are interested in an Amiga Emulator for Linux, look at

[http://web.archive.org/web/%2E/http://www.freiburg.linux.de/\~uae/](<http://web.archive.org/web/%2E/http://www.freiburg.linux.de/~uae/>)

---

# kAFS: AFS FILESYSTEM

_Peios Kernel / Internals / Filesystems_

> This filesystem provides a fairly simple secure AFS filesystem driver. It is under development and does not yet provide the full feature set. The features it does support include:

<a id="rst-kafs-afs-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

- Overview.
- Usage.
- Mountpoints.
- Dynamic root.
- Proc filesystem.
- The cell database.
- Security.
- The @sys substitution. -->

<a id="rst-overview"></a>

## Overview

This filesystem provides a fairly simple secure AFS filesystem driver. It is under development and does not yet provide the full feature set.  The features it does support include:

> (\*) Security (currently only AFS kaserver and KerberosIV tickets).
>
> (\*) File reading and writing.
>
> (\*) Automounting.
>
> (\*) Local caching (via fscache).

It does not yet support the following AFS features:

> (\*) pioctl() system call.

<a id="rst-compilation"></a>

## Compilation

The filesystem should be enabled by turning on the kernel configuration options:



```text
CONFIG_AF_RXRPC         - The RxRPC protocol transport
CONFIG_RXKAD            - The RxRPC Kerberos security handler
CONFIG_AFS_FS           - The AFS filesystem
```

Additionally, the following can be turned on to aid debugging:



```text
CONFIG_AF_RXRPC_DEBUG   - Permit AF_RXRPC debugging to be enabled
CONFIG_AFS_DEBUG        - Permit AFS debugging to be enabled
```

They permit the debugging messages to be turned on dynamically by manipulating the masks in the following files:



```text
/sys/module/af_rxrpc/parameters/debug
/sys/module/kafs/parameters/debug
```

<a id="rst-usage"></a>

## Usage

When inserting the driver modules the root cell must be specified along with a list of volume location server IP addresses:



```text
modprobe rxrpc
modprobe kafs rootcell=cambridge.redhat.com:172.16.18.73:172.16.18.91
```

The first module is the AF_RXRPC network protocol driver.  This provides the RxRPC remote operation protocol and may also be accessed from userspace.  See:

> [Documentation/networking/rxrpc.rst](/kernel/internals/networking/rxrpc.md)

The second module is the kerberos RxRPC security driver, and the third module is the actual filesystem driver for the AFS filesystem.

Once the module has been loaded, more modules can be added by the following procedure:



```text
echo add grand.central.org 18.9.48.14:128.2.203.61:130.237.48.87 >/proc/fs/afs/cells
```

Where the parameters to the "add" command are the name of a cell and a list of volume location servers within that cell, with the latter separated by colons.

Filesystems can be mounted anywhere by commands similar to the following:



```text
mount -t afs "%cambridge.redhat.com:root.afs." /afs
mount -t afs "#cambridge.redhat.com:root.cell." /afs/cambridge
mount -t afs "#root.afs." /afs
mount -t afs "#root.cell." /afs/cambridge
```

Where the initial character is either a hash or a percent symbol depending on whether you definitely want a R/W volume (percent) or whether you'd prefer a R/O volume, but are willing to use a R/W volume instead (hash).

The name of the volume can be suffixes with ".backup" or ".readonly" to specify connection to only volumes of those types.

The name of the cell is optional, and if not given during a mount, then the named volume will be looked up in the cell specified during modprobe.

Additional cells can be added through /proc (see later section).

<a id="rst-mountpoints"></a>

## Mountpoints

AFS has a concept of mountpoints. In AFS terms, these are specially formatted symbolic links (of the same form as the "device name" passed to mount).  kAFS presents these to the user as directories that have a follow-link capability (i.e.: symbolic link semantics).  If anyone attempts to access them, they will automatically cause the target volume to be mounted (if possible) on that site.

Automatically mounted filesystems will be automatically unmounted approximately twenty minutes after they were last used.  Alternatively they can be unmounted directly with the umount() system call.

Manually unmounting an AFS volume will cause any idle submounts upon it to be culled first.  If all are culled, then the requested volume will also be unmounted, otherwise error EBUSY will be returned.

This can be used by the administrator to attempt to unmount the whole AFS tree mounted on /afs in one go by doing:



```text
umount /afs
```

<a id="rst-dynamic-root"></a>

## Dynamic Root

A mount option is available to create a serverless mount that is only usable for dynamic lookup.  Creating such a mount can be done by, for example:



```text
mount -t afs none /afs -o dyn
```

This creates a mount that just has an empty directory at the root.  Attempting to look up a name in this directory will cause a mountpoint to be created that looks up a cell of the same name, for example:



```text
ls /afs/grand.central.org/
```

<a id="rst-proc-filesystem"></a>

## Proc Filesystem

The AFS module creates a "/proc/fs/afs/" directory and populates it:

> - **(\*) A "cells" file that lists cells currently known to the afs module and**
>
>   their usage counts:
>
>
>
>   ```text
>   [root@andromeda ~]# cat /proc/fs/afs/cells
>   USE NAME
>     3 cambridge.redhat.com
>   ```
>
> - **(\*) A directory per cell that contains files that list volume location**
>
>   servers, volumes, and active servers known within that cell:
>
>
>
>   ```text
>   [root@andromeda ~]# cat /proc/fs/afs/cambridge.redhat.com/servers
>   USE ADDR            STATE
>     4 172.16.18.91        0
>   [root@andromeda ~]# cat /proc/fs/afs/cambridge.redhat.com/vlservers
>   ADDRESS
>   172.16.18.91
>   [root@andromeda ~]# cat /proc/fs/afs/cambridge.redhat.com/volumes
>   USE STT VLID[0]  VLID[1]  VLID[2]  NAME
>     1 Val 20000000 20000001 20000002 root.afs
>   ```

<a id="rst-the-cell-database"></a>

## The Cell Database

The filesystem maintains an internal database of all the cells it knows and the IP addresses of the volume location servers for those cells.  The cell to which the system belongs is added to the database when modprobe is performed by the "rootcell=" argument or, if compiled in, using a "kafs.rootcell=" argument on the kernel command line.

Further cells can be added by commands similar to the following:



```text
echo add CELLNAME VLADDR[:VLADDR][:VLADDR]... >/proc/fs/afs/cells
echo add grand.central.org 18.9.48.14:128.2.203.61:130.237.48.87 >/proc/fs/afs/cells
```

No other cell database operations are available at this time.

<a id="rst-security"></a>

## Security

Secure operations are initiated by acquiring a key using the klog program.  A very primitive klog program is available at:

> [https://people.redhat.com/\~dhowells/rxrpc/klog.c](<https://people.redhat.com/~dhowells/rxrpc/klog.c>)

This should be compiled by:



```text
make klog LDLIBS="-lcrypto -lcrypt -lkrb4 -lkeyutils"
```

And then run as:



```text
./klog
```

Assuming it's successful, this adds a key of type RxRPC, named for the service and cell, e.g.: "afs@&lt;cellname&gt;".  This can be viewed with the keyctl program or by cat'ing /proc/keys:



```text
[root@andromeda ~]# keyctl show
Session Keyring
       -3 --alswrv      0     0  keyring: _ses.3268
        2 --alswrv      0     0   \_ keyring: _uid.0
111416553 --als--v      0     0   \_ rxrpc: afs@CAMBRIDGE.REDHAT.COM
```

Currently the username, realm, password and proposed ticket lifetime are compiled into the program.

It is not required to acquire a key before using AFS facilities, but if one is not acquired then all operations will be governed by the anonymous user parts of the ACLs.

If a key is acquired, then all AFS operations, including mounts and automounts, made by a possessor of that key will be secured with that key.

If a file is opened with a particular key and then the file descriptor is passed to a process that doesn't have that key (perhaps over an AF_UNIX socket), then the operations on the file will be made with key that was used to open the file.

<a id="rst-the-sys-substitution"></a>

## The @sys Substitution

The list of up to 16 @sys substitutions for the current network namespace can be configured by writing a list to /proc/fs/afs/sysname:



```text
[root@andromeda ~]# echo foo amd64_linux_26 >/proc/fs/afs/sysname
```

or cleared entirely by writing an empty list:



```text
[root@andromeda ~]# echo >/proc/fs/afs/sysname
```

The current list for current network namespace can be retrieved by:



```text
[root@andromeda ~]# cat /proc/fs/afs/sysname
foo
amd64_linux_26
```

When @sys is being substituted for, each element of the list is tried in the order given.

By default, the list will contain one item that conforms to the pattern "&lt;arch&gt;\_linux_26", amd64 being the name for x86_64.

---

# Linux Filesystems API summary

_Peios Kernel / Internals / Filesystems_

> This section contains API-level documentation, mostly taken from the source code itself.

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-linux-filesystems-api-summary"></a>

This section contains API-level documentation, mostly taken from the source code itself.

<a id="rst-the-linux-vfs"></a>

## The Linux VFS

<a id="rst-the-filesystem-types"></a>

### The Filesystem types


#### <a id="c-enum-positive_aop_returns"></a>`enum positive_aop_returns`

aop return codes with specific semantics

**Constants**

- `AOP_WRITEPAGE_ACTIVATE`: Informs the caller that page writeback has
  completed, that the page is still locked, and
  should be considered active.  The VM uses this hint
  to return the page to the active list -- it won't
  be a candidate for writeback again in the near
  future.  Other callers must be careful to unlock
  the page if they get this return.  Returned by
  `writepage()`;
- `AOP_TRUNCATED_PAGE`: The AOP method that was handed a locked page has
  unlocked it and the page might have been truncated.
  The caller should back up to acquiring a new page and
  trying again.  The aop will be taking reasonable
  precautions not to livelock.  If the caller held a page
  reference, it should drop it before retrying.  Returned
  by `read_folio()`.

**Description**

address_space_operation functions return these large constants to indicate
special semantics to the caller.  These are much larger than the bytes in a
page to allow for functions that return the number of bytes operated on in a
given page.

#### <a id="c-struct-address_space"></a>`struct address_space`

Contents of a cacheable, mappable object.

**Definition**

```c
struct address_space {
        struct inode            *host;
        struct xarray           i_pages;
        struct rw_semaphore     invalidate_lock;
        gfp_t gfp_mask;
        atomic_t i_mmap_writable;
    #ifdef CONFIG_READ_ONLY_THP_FOR_FS;
        atomic_t nr_thps;
    #endif;
        struct rb_root_cached   i_mmap;
        unsigned long           nrpages;
        pgoff_t writeback_index;
        const struct address_space_operations *a_ops;
        unsigned long           flags;
        errseq_t wb_err;
        spinlock_t i_private_lock;
        struct list_head        i_private_list;
        struct rw_semaphore     i_mmap_rwsem;
        void *                  i_private_data;
};
```

**Members**

- `host`: Owner, either the inode or the block_device.
- `i_pages`: Cached pages.
- `invalidate_lock`: Guards coherency between page cache contents and
  file offset->disk block mappings in the filesystem during invalidates.
  It is also used to block modification of page cache contents through
  memory mappings.
- `gfp_mask`: Memory allocation flags to use for allocating pages.
- `i_mmap_writable`: Number of VM_SHARED, VM_MAYWRITE mappings.
- `nr_thps`: Number of THPs in the pagecache (non-shmem only).
- `i_mmap`: Tree of private and shared mappings.
- `nrpages`: Number of page entries, protected by the i_pages lock.
- `writeback_index`: Writeback starts here.
- `a_ops`: Methods.
- `flags`: Error bits and flags (AS_*).
- `wb_err`: The most recent error which has occurred.
- `i_private_lock`: For use by the owner of the address_space.
- `i_private_list`: For use by the owner of the address_space.
- `i_mmap_rwsem`: Protects **i_mmap** and **i_mmap_writable**.
- `i_private_data`: For use by the owner of the address_space.

#### <a id="c-struct-file_ra_state"></a>`struct file_ra_state`

Track a file's readahead state.

**Definition**

```c
struct file_ra_state {
    pgoff_t start;
    unsigned int size;
    unsigned int async_size;
    unsigned int ra_pages;
    unsigned short order;
    unsigned short mmap_miss;
    loff_t prev_pos;
};
```

**Members**

- `start`: Where the most recent readahead started.
- `size`: Number of pages read in the most recent readahead.
- `async_size`: Numer of pages that were/are not needed immediately
  and so were/are genuinely "ahead".  Start next readahead when
  the first of these pages is accessed.
- `ra_pages`: Maximum size of a readahead request, copied from the bdi.
- `order`: Preferred folio order used for most recent readahead.
- `mmap_miss`: How many mmap accesses missed in the page cache.
- `prev_pos`: The last byte in the most recent read request.

**Description**

When this structure is passed to ->`readahead()`, the "most recent"
readahead means the current readahead.

#### <a id="c-struct-file"></a>`struct file`

Represents a file

**Definition**

```c
struct file {
        spinlock_t f_lock;
        fmode_t f_mode;
        const struct file_operations    *f_op;
        struct address_space            *f_mapping;
        void *private_data;
        struct inode                    *f_inode;
        unsigned int                    f_flags;
        unsigned int                    f_iocb_flags;
        const struct cred               *f_cred;
        struct fown_struct              *f_owner;
        union {
            const struct path       f_path;
            struct path             __f_path;
        };
        union {
            struct mutex            f_pos_lock;
            u64 f_pipe;
        };
        loff_t f_pos;
    #ifdef CONFIG_SECURITY;
        void *f_security;
    #endif;
        errseq_t f_wb_err;
        errseq_t f_sb_err;
    #ifdef CONFIG_EPOLL;
        struct hlist_head               *f_ep;
    #endif;
        union {
            struct callback_head    f_task_work;
            struct llist_node       f_llist;
            struct file_ra_state    f_ra;
            freeptr_t f_freeptr;
        };
        file_ref_t f_ref;
};
```

**Members**

- `f_lock`: Protects f_ep, f_flags. Must not be taken from IRQ context.
- `f_mode`: FMODE_* flags often used in hotpaths
- `f_op`: file operations
- `f_mapping`: Contents of a cacheable, mappable object.
- `private_data`: filesystem or driver specific data
- `f_inode`: cached inode
- `f_flags`: file flags
- `f_iocb_flags`: iocb flags
- `f_cred`: stashed credentials of creator/opener
- `f_owner`: file owner
- `{unnamed_union}`: anonymous
- `f_path`: path of the file
- `__f_path`: writable alias for **f_path**; *ONLY* for core VFS and only before
  the file gets open
- `{unnamed_union}`: anonymous
- `f_pos_lock`: lock protecting file position
- `f_pipe`: specific to pipes
- `f_pos`: file position
- `f_security`: LSM security context of this file
- `f_wb_err`: writeback error
- `f_sb_err`: per sb writeback errors
- `f_ep`: link of all epoll hooks for this file
- `{unnamed_union}`: anonymous
- `f_task_work`: task work entry point
- `f_llist`: work queue entrypoint
- `f_ra`: file's readahead state
- `f_freeptr`: Pointer used by SLAB_TYPESAFE_BY_RCU file cache (don't touch.)
- `f_ref`: reference count

#### <a id="c-i_uid_into_vfsuid"></a>`i_uid_into_vfsuid()`

```c
vfsuid_t i_uid_into_vfsuid(struct mnt_idmap *idmap, const struct inode *inode)
```

map an inode's i_uid down according to an idmapping

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct inode *inode`: inode to map

**Return**

whe inode's i_uid mapped down according to **idmap**.
If the inode's i_uid has no mapping INVALID_VFSUID is returned.

#### <a id="c-i_uid_needs_update"></a>`i_uid_needs_update()`

```c
bool i_uid_needs_update(struct mnt_idmap *idmap, const struct iattr *attr, const struct inode *inode)
```

check whether inode's i_uid needs to be updated

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct iattr *attr`: the new attributes of **inode**
- `const struct inode *inode`: the inode to update

**Description**

Check whether the $inode's i_uid field needs to be updated taking idmapped
mounts into account if the filesystem supports it.

**Return**

true if **inode**'s i_uid field needs to be updated, false if not.

#### <a id="c-i_uid_update"></a>`i_uid_update()`

```c
void i_uid_update(struct mnt_idmap *idmap, const struct iattr *attr, struct inode *inode)
```

update **inode**'s i_uid field

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct iattr *attr`: the new attributes of **inode**
- `struct inode *inode`: the inode to update

**Description**

Safely update **inode**'s i_uid field translating the vfsuid of any idmapped
mount into the filesystem kuid.

#### <a id="c-i_gid_into_vfsgid"></a>`i_gid_into_vfsgid()`

```c
vfsgid_t i_gid_into_vfsgid(struct mnt_idmap *idmap, const struct inode *inode)
```

map an inode's i_gid down according to an idmapping

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct inode *inode`: inode to map

**Return**

the inode's i_gid mapped down according to **idmap**.
If the inode's i_gid has no mapping INVALID_VFSGID is returned.

#### <a id="c-i_gid_needs_update"></a>`i_gid_needs_update()`

```c
bool i_gid_needs_update(struct mnt_idmap *idmap, const struct iattr *attr, const struct inode *inode)
```

check whether inode's i_gid needs to be updated

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct iattr *attr`: the new attributes of **inode**
- `const struct inode *inode`: the inode to update

**Description**

Check whether the $inode's i_gid field needs to be updated taking idmapped
mounts into account if the filesystem supports it.

**Return**

true if **inode**'s i_gid field needs to be updated, false if not.

#### <a id="c-i_gid_update"></a>`i_gid_update()`

```c
void i_gid_update(struct mnt_idmap *idmap, const struct iattr *attr, struct inode *inode)
```

update **inode**'s i_gid field

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct iattr *attr`: the new attributes of **inode**
- `struct inode *inode`: the inode to update

**Description**

Safely update **inode**'s i_gid field translating the vfsgid of any idmapped
mount into the filesystem kgid.

#### <a id="c-inode_fsuid_set"></a>`inode_fsuid_set()`

```c
void inode_fsuid_set(struct inode *inode, struct mnt_idmap *idmap)
```

initialize inode's i_uid field with callers fsuid

**Parameters**

- `struct inode *inode`: inode to initialize
- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from

**Description**

Initialize the i_uid field of **inode**. If the inode was found/created via
an idmapped mount map the caller's fsuid according to **idmap**.

#### <a id="c-inode_fsgid_set"></a>`inode_fsgid_set()`

```c
void inode_fsgid_set(struct inode *inode, struct mnt_idmap *idmap)
```

initialize inode's i_gid field with callers fsgid

**Parameters**

- `struct inode *inode`: inode to initialize
- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from

**Description**

Initialize the i_gid field of **inode**. If the inode was found/created via
an idmapped mount map the caller's fsgid according to **idmap**.

#### <a id="c-fsuidgid_has_mapping"></a>`fsuidgid_has_mapping()`

```c
bool fsuidgid_has_mapping(struct super_block *sb, struct mnt_idmap *idmap)
```

check whether caller's fsuid/fsgid is mapped

**Parameters**

- `struct super_block *sb`: the superblock we want a mapping in
- `struct mnt_idmap *idmap`: idmap of the relevant mount

**Description**

Check whether the caller's fsuid and fsgid have a valid mapping in the
s_user_ns of the superblock **sb**. If the caller is on an idmapped mount map
the caller's fsuid and fsgid according to the **idmap** first.

**Return**

true if fsuid and fsgid is mapped, false if not.

#### <a id="c-inode_set_ctime"></a>`inode_set_ctime()`

```c
struct timespec64 inode_set_ctime(struct inode *inode, time64_t sec, long nsec)
```

set the ctime in the inode

**Parameters**

- `struct inode *inode`: inode in which to set the ctime
- `time64_t sec`: tv_sec value to set
- `long nsec`: tv_nsec value to set

**Description**

Set the ctime in **inode** to { **sec**, **nsec** }

#### <a id="c-file_write_started"></a>`file_write_started()`

```c
bool file_write_started(const struct file *file)
```

check if SB_FREEZE_WRITE is held

**Parameters**

- `const struct file *file`: the file we write to

**Description**

May be false positive with !CONFIG_LOCKDEP/LOCK_STATE_UNKNOWN.
May be false positive with !S_ISREG, because [`file_start_write()`](#c-file_start_write) has
no effect on !S_ISREG.

#### <a id="c-file_write_not_started"></a>`file_write_not_started()`

```c
bool file_write_not_started(const struct file *file)
```

check if SB_FREEZE_WRITE is not held

**Parameters**

- `const struct file *file`: the file we write to

**Description**

May be false positive with !CONFIG_LOCKDEP/LOCK_STATE_UNKNOWN.
May be false positive with !S_ISREG, because [`file_start_write()`](#c-file_start_write) has
no effect on !S_ISREG.

#### <a id="c-struct-renamedata"></a>`struct renamedata`

contains all information required for renaming

**Definition**

```c
struct renamedata {
    struct mnt_idmap *mnt_idmap;
    struct dentry *old_parent;
    struct dentry *old_dentry;
    struct dentry *new_parent;
    struct dentry *new_dentry;
    struct delegated_inode *delegated_inode;
    unsigned int flags;
};
```

**Members**

- `mnt_idmap`: idmap of the mount in which the rename is happening.
- `old_parent`: parent of source
- `old_dentry`: source
- `new_parent`: parent of destination
- `new_dentry`: destination
- `delegated_inode`: returns an inode needing a delegation break
- `flags`: rename flags

#### <a id="c-is_mgtime"></a>`is_mgtime()`

```c
bool is_mgtime(const struct inode *inode)
```

is this inode using multigrain timestamps

**Parameters**

- `const struct inode *inode`: inode to test for multigrain timestamps

**Description**

Return true if the inode uses multigrain timestamps, false otherwise.

#### <a id="c-is_idmapped_mnt"></a>`is_idmapped_mnt()`

```c
bool is_idmapped_mnt(const struct vfsmount *mnt)
```

check whether a mount is mapped

**Parameters**

- `const struct vfsmount *mnt`: the mount to check

**Description**

If **mnt** has an non **nop_mnt_idmap** attached to it then **mnt** is mapped.

**Return**

true if mount is mapped, false if not.

#### <a id="c-file_start_write"></a>`file_start_write()`

```c
void file_start_write(struct file *file)
```

get write access to a superblock for regular file io

**Parameters**

- `struct file *file`: the file we want to write to

**Description**

This is a variant of `sb_start_write()` which is a noop on non-regular file.
Should be matched with a call to [`file_end_write()`](#c-file_end_write).

#### <a id="c-file_end_write"></a>`file_end_write()`

```c
void file_end_write(struct file *file)
```

drop write access to a superblock of a regular file

**Parameters**

- `struct file *file`: the file we wrote to

**Description**

Should be matched with a call to [`file_start_write()`](#c-file_start_write).

#### <a id="c-kiocb_start_write"></a>`kiocb_start_write()`

```c
void kiocb_start_write(struct kiocb *iocb)
```

get write access to a superblock for async file io

**Parameters**

- `struct kiocb *iocb`: the io context we want to submit the write with

**Description**

This is a variant of `sb_start_write()` for async io submission.
Should be matched with a call to [`kiocb_end_write()`](#c-kiocb_end_write).

#### <a id="c-kiocb_end_write"></a>`kiocb_end_write()`

```c
void kiocb_end_write(struct kiocb *iocb)
```

drop write access to a superblock after async file io

**Parameters**

- `struct kiocb *iocb`: the io context we sumbitted the write with

**Description**

Should be matched with a call to [`kiocb_start_write()`](#c-kiocb_start_write).

#### <a id="c-name_is_dot_dotdot"></a>`name_is_dot_dotdot()`

```c
bool name_is_dot_dotdot(const char *name, size_t len)
```

returns true only if **name** is "." or ".."

**Parameters**

- `const char *name`: file name to check
- `size_t len`: length of file name, in bytes

#### <a id="c-name_contains_dotdot"></a>`name_contains_dotdot()`

```c
bool name_contains_dotdot(const char *name)
```

check if a file name contains ".." path components

**Parameters**

- `const char *name`: File path string to check
  Search for ".." surrounded by either '/' or start/end of string.

#### <a id="c-inode_dio_begin"></a>`inode_dio_begin()`

```c
void inode_dio_begin(struct inode *inode)
```

signal start of a direct I/O requests

**Parameters**

- `struct inode *inode`: inode the direct I/O happens on

**Description**

This is called once we've finished processing a direct I/O request,
and is used to wake up callers waiting for direct I/O to be quiesced.

#### <a id="c-inode_dio_end"></a>`inode_dio_end()`

```c
void inode_dio_end(struct inode *inode)
```

signal finish of a direct I/O requests

**Parameters**

- `struct inode *inode`: inode the direct I/O happens on

**Description**

This is called once we've finished processing a direct I/O request,
and is used to wake up callers waiting for direct I/O to be quiesced.

#### <a id="c-generic_ci_validate_strict_name"></a>`generic_ci_validate_strict_name()`

```c
bool generic_ci_validate_strict_name(struct inode *dir, const struct qstr *name)
```

Check if a given name is suitable for a directory

**Parameters**

- `struct inode *dir`: inode of the directory where the new file will be created
- `const struct qstr *name`: name of the new file

**Description**

This functions checks if the proposed filename is valid for the
parent directory. That means that only valid UTF-8 filenames will be
accepted for casefold directories from filesystems created with the
strict encoding flag.  That also means that any name will be
accepted for directories that doesn't have casefold enabled, or
aren't being strict with the encoding.

**Return**

* True: if the filename is suitable for this directory. It can be
  true if a given name is not suitable for a strict encoding
  directory, but the directory being used isn't strict
* False if the filename isn't suitable for this directory. This only
  happens when a directory is casefolded and the filesystem is strict
  about its encoding.


<a id="rst-the-directory-cache"></a>

### The Directory Cache


#### <a id="c-d_drop"></a>`d_drop()`

```c
void d_drop(struct dentry *dentry)
```

drop a dentry

**Parameters**

- `struct dentry *dentry`: dentry to drop

**Description**

[`d_drop()`](#c-d_drop) unhashes the entry from the parent dentry hashes, so that it won't
be found through a VFS lookup any more. Note that this is different from
deleting the dentry - d_delete will try to mark the dentry negative if
possible, giving a successful _negative_ lookup, while d_drop will
just make the cache lookup fail.

[`d_drop()`](#c-d_drop) is used mainly for stuff that wants to invalidate a dentry for some
reason (NFS timeouts or autofs deletes).

__d_drop requires dentry->d_lock

___d_drop doesn't mark dentry as "unhashed"
(dentry->d_hash.pprev will be LIST_POISON2, not NULL).

#### <a id="c-d_find_any_alias"></a>`d_find_any_alias()`

```c
struct dentry * d_find_any_alias(struct inode *inode)
```

find any alias for a given inode

**Parameters**

- `struct inode *inode`: inode to find an alias for

**Description**

If any aliases exist for the given inode, take and return a
reference for one of them.  If no aliases exist, return `NULL`.

#### <a id="c-d_find_alias"></a>`d_find_alias()`

```c
struct dentry * d_find_alias(struct inode *inode)
```

grab a hashed alias of inode

**Parameters**

- `struct inode *inode`: inode in question

**Description**

If inode has a hashed alias, or is a directory and has any alias,
acquire the reference to alias and return it. Otherwise return NULL.
Notice that if inode is a directory there can be only one alias and
it can be unhashed only if it has no children, or if it is the root
of a filesystem, or if the directory was renamed and d_revalidate
was the first vfs operation to notice.

If the inode has an IS_ROOT, DCACHE_DISCONNECTED alias, then prefer
any other hashed alias over that one.

#### <a id="c-d_dispose_if_unused"></a>`d_dispose_if_unused()`

```c
void d_dispose_if_unused(struct dentry *dentry, struct list_head *dispose)
```

move unreferenced dentries to shrink list

**Parameters**

- `struct dentry *dentry`: dentry in question
- `struct list_head *dispose`: head of shrink list

**Description**

If dentry has no external references, move it to shrink list.

NOTE!!! The caller is responsible for preventing eviction of the dentry by
holding dentry->d_inode->i_lock or equivalent.

#### <a id="c-shrink_dcache_sb"></a>`shrink_dcache_sb()`

```c
void shrink_dcache_sb(struct super_block *sb)
```

shrink dcache for a superblock

**Parameters**

- `struct super_block *sb`: superblock

**Description**

Shrink the dcache for the specified super block. This is used to free
the dcache before unmounting a file system.

#### <a id="c-path_has_submounts"></a>`path_has_submounts()`

```c
int path_has_submounts(const struct path *parent)
```

check for mounts over a dentry in the current namespace.

**Parameters**

- `const struct path *parent`: path to check.

**Description**

Return true if the parent or its subdirectories contain
a mount point in the current namespace.

#### <a id="c-d_invalidate"></a>`d_invalidate()`

```c
void d_invalidate(struct dentry *dentry)
```

detach submounts, prune dcache, and drop

**Parameters**

- `struct dentry *dentry`: dentry to invalidate (aka detach, prune and drop)

#### <a id="c-d_alloc"></a>`d_alloc()`

```c
struct dentry * d_alloc(struct dentry * parent, const struct qstr *name)
```

allocate a dcache entry

**Parameters**

- `struct dentry * parent`: parent of entry to allocate
- `const struct qstr *name`: qstr of the name

**Description**

Allocates a dentry. It returns `NULL` if there is insufficient memory
available. On a success the dentry is returned. The name passed in is
copied and the copy passed in may be reused after this call.

#### <a id="c-d_instantiate"></a>`d_instantiate()`

```c
void d_instantiate(struct dentry *entry, struct inode * inode)
```

fill in inode information for a dentry

**Parameters**

- `struct dentry *entry`: dentry to complete
- `struct inode * inode`: inode to attach to this dentry

**Description**

Fill in inode information in the entry.

This turns negative dentries into productive full members
of society.

NOTE! This assumes that the inode count has been incremented
(or otherwise set) by the caller to indicate that it is now
in use by the dcache.

#### <a id="c-d_obtain_alias"></a>`d_obtain_alias()`

```c
struct dentry * d_obtain_alias(struct inode *inode)
```

find or allocate a DISCONNECTED dentry for a given inode

**Parameters**

- `struct inode *inode`: inode to allocate the dentry for

**Description**

Obtain a dentry for an inode resulting from NFS filehandle conversion or
similar open by handle operations.  The returned dentry may be anonymous,
or may have a full name (if the inode was already in the cache).

When called on a directory inode, we must ensure that the inode only ever
has one dentry.  If a dentry is found, that is returned instead of
allocating a new one.

On successful return, the reference to the inode has been transferred
to the dentry.  In case of an error the reference on the inode is released.
To make it easier to use in export operations a `NULL` or IS_ERR inode may
be passed in and the error will be propagated to the return value,
with a `NULL` **inode** replaced by ERR_PTR(-ESTALE).

#### <a id="c-d_obtain_root"></a>`d_obtain_root()`

```c
struct dentry * d_obtain_root(struct inode *inode)
```

find or allocate a dentry for a given inode

**Parameters**

- `struct inode *inode`: inode to allocate the dentry for

**Description**

Obtain an IS_ROOT dentry for the root of a filesystem.

We must ensure that directory inodes only ever have one dentry.  If a
dentry is found, that is returned instead of allocating a new one.

On successful return, the reference to the inode has been transferred
to the dentry.  In case of an error the reference on the inode is
released.  A `NULL` or IS_ERR inode may be passed in and will be the
error will be propagate to the return value, with a `NULL` **inode**
replaced by ERR_PTR(-ESTALE).

#### <a id="c-d_add_ci"></a>`d_add_ci()`

```c
struct dentry * d_add_ci(struct dentry *dentry, struct inode *inode, struct qstr *name)
```

lookup or allocate new dentry with case-exact name

**Parameters**

- `struct dentry *dentry`: the negative dentry that was passed to the parent's lookup func
- `struct inode *inode`: the inode case-insensitive lookup has found
- `struct qstr *name`: the case-exact name to be associated with the returned dentry

**Description**

This is to avoid filling the dcache with case-insensitive names to the
same inode, only the actual correct case is stored in the dcache for
case-insensitive filesystems.

For a case-insensitive lookup match and if the case-exact dentry
already exists in the dcache, use it and return it.

If no entry exists with the exact case name, allocate new dentry with
the exact case, and return the spliced entry.

#### <a id="c-d_same_name"></a>`d_same_name()`

```c
bool d_same_name(const struct dentry *dentry, const struct dentry *parent, const struct qstr *name)
```

compare dentry name with case-exact name

**Parameters**

- `const struct dentry *dentry`: the negative dentry that was passed to the parent's lookup func
- `const struct dentry *parent`: parent dentry
- `const struct qstr *name`: the case-exact name to be associated with the returned dentry

**Return**

true if names are same, or false

#### <a id="c-d_lookup"></a>`d_lookup()`

```c
struct dentry * d_lookup(const struct dentry *parent, const struct qstr *name)
```

search for a dentry

**Parameters**

- `const struct dentry *parent`: parent dentry
- `const struct qstr *name`: qstr of name we wish to find

**Return**

dentry, or NULL

**Description**

d_lookup searches the children of the parent dentry for the name in
question. If the dentry is found its reference count is incremented and the
dentry is returned. The caller must use dput to free the entry when it has
finished using it. `NULL` is returned if the dentry does not exist.

#### <a id="c-d_delete"></a>`d_delete()`

```c
void d_delete(struct dentry * dentry)
```

delete a dentry

**Parameters**

- `struct dentry * dentry`: The dentry to delete

**Description**

Turn the dentry into a negative dentry if possible, otherwise
remove it from the hash queues so it can be deleted later

#### <a id="c-d_rehash"></a>`d_rehash()`

```c
void d_rehash(struct dentry * entry)
```

add an entry back to the hash

**Parameters**

- `struct dentry * entry`: dentry to add to the hash

**Description**

Adds a dentry to the hash according to its name.

#### <a id="c-d_add"></a>`d_add()`

```c
void d_add(struct dentry *entry, struct inode *inode)
```

add dentry to hash queues

**Parameters**

- `struct dentry *entry`: dentry to add
- `struct inode *inode`: The inode to attach to this dentry

**Description**

This adds the entry to the hash queues and initializes **inode**.
The entry was actually filled in earlier during [`d_alloc()`](#c-d_alloc).

#### <a id="c-d_splice_alias"></a>`d_splice_alias()`

```c
struct dentry * d_splice_alias(struct inode *inode, struct dentry *dentry)
```

splice a disconnected dentry into the tree if one exists

**Parameters**

- `struct inode *inode`: the inode which may have a disconnected dentry
- `struct dentry *dentry`: a negative dentry which we want to point to the inode.

**Description**

If inode is a directory and has an IS_ROOT alias, then d_move that in
place of the given dentry and return it, else simply d_add the inode
to the dentry and return NULL.

If a non-IS_ROOT directory is found, the filesystem is corrupt, and
we should error out: directories can't have multiple aliases.

This is needed in the lookup routine of any filesystem that is exportable
(via knfsd) so that we can build dcache paths to directories effectively.

If a dentry was found and moved, then it is returned.  Otherwise NULL
is returned.  This matches the expected return value of ->lookup.

Cluster filesystems may call this function with a negative, hashed dentry.
In that case, we know that the inode will be a regular file, and also this
will only occur during atomic_open. So we need to check for the dentry
being already hashed only in the final case.

#### <a id="c-is_subdir"></a>`is_subdir()`

```c
bool is_subdir(struct dentry *new_dentry, struct dentry *old_dentry)
```

is new dentry a subdirectory of old_dentry

**Parameters**

- `struct dentry *new_dentry`: new dentry
- `struct dentry *old_dentry`: old dentry

**Description**

Returns true if new_dentry is a subdirectory of the parent (at any depth).
Returns false otherwise.
Caller must ensure that "new_dentry" is pinned before calling [`is_subdir()`](#c-is_subdir)



#### <a id="c-dget_dlock"></a>`dget_dlock()`

```c
struct dentry * dget_dlock(struct dentry *dentry)
```

get a reference to a dentry

**Parameters**

- `struct dentry *dentry`: dentry to get a reference to

**Description**

Given a live dentry, increment the reference count and return the dentry.
Caller must hold **dentry->d_lock**.  Making sure that dentry is alive is
caller's resonsibility.  There are many conditions sufficient to guarantee
that; e.g. anything with non-negative refcount is alive, so's anything
hashed, anything positive, anyone's parent, etc.

#### <a id="c-dget"></a>`dget()`

```c
struct dentry * dget(struct dentry *dentry)
```

get a reference to a dentry

**Parameters**

- `struct dentry *dentry`: dentry to get a reference to

**Description**

Given a dentry or `NULL` pointer increment the reference count
if appropriate and return the dentry.  A dentry will not be
destroyed when it has references.  Conversely, a dentry with
no references can disappear for any number of reasons, starting
with memory pressure.  In other words, that primitive is
used to clone an existing reference; using it on something with
zero refcount is a bug.

**NOTE**

it will spin if **dentry->d_lock** is held.  From the deadlock
avoidance point of view it is equivalent to `spin_lock()`/increment
refcount/`spin_unlock()`, so calling it under **dentry->d_lock** is
always a bug; so's calling it under ->d_lock on any of its descendents.

#### <a id="c-d_unhashed"></a>`d_unhashed()`

```c
int d_unhashed(const struct dentry *dentry)
```

is dentry hashed

**Parameters**

- `const struct dentry *dentry`: entry to check

**Description**

Returns true if the dentry passed is not currently hashed.

#### <a id="c-d_really_is_negative"></a>`d_really_is_negative()`

```c
bool d_really_is_negative(const struct dentry *dentry)
```

Determine if a dentry is really negative (ignoring fallthroughs)

**Parameters**

- `const struct dentry *dentry`: The dentry in question

**Description**

Returns true if the dentry represents either an absent name or a name that
doesn't map to an inode (ie. ->d_inode is NULL).  The dentry could represent
a true miss, a whiteout that isn't represented by a 0,0 chardev or a
fallthrough marker in an opaque directory.

Note!  (1) This should be used *only* by a filesystem to examine its own
dentries.  It should not be used to look at some other filesystem's
dentries.  (2) It should also be used in combination with [`d_inode()`](#c-d_inode) to get
the inode.  (3) The dentry may have something attached to ->d_lower and the
type field of the flags may be set to something other than miss or whiteout.

#### <a id="c-d_really_is_positive"></a>`d_really_is_positive()`

```c
bool d_really_is_positive(const struct dentry *dentry)
```

Determine if a dentry is really positive (ignoring fallthroughs)

**Parameters**

- `const struct dentry *dentry`: The dentry in question

**Description**

Returns true if the dentry represents a name that maps to an inode
(ie. ->d_inode is not NULL).  The dentry might still represent a whiteout if
that is represented on medium as a 0,0 chardev.

Note!  (1) This should be used *only* by a filesystem to examine its own
dentries.  It should not be used to look at some other filesystem's
dentries.  (2) It should also be used in combination with [`d_inode()`](#c-d_inode) to get
the inode.

#### <a id="c-d_inode"></a>`d_inode()`

```c
struct inode * d_inode(const struct dentry *dentry)
```

Get the actual inode of this dentry

**Parameters**

- `const struct dentry *dentry`: The dentry to query

**Description**

This is the helper normal filesystems should use to get at their own inodes
in their own dentries and ignore the layering superimposed upon them.

#### <a id="c-d_inode_rcu"></a>`d_inode_rcu()`

```c
struct inode * d_inode_rcu(const struct dentry *dentry)
```

Get the actual inode of this dentry with `READ_ONCE()`

**Parameters**

- `const struct dentry *dentry`: The dentry to query

**Description**

This is the helper normal filesystems should use to get at their own inodes
in their own dentries and ignore the layering superimposed upon them.

#### <a id="c-d_backing_inode"></a>`d_backing_inode()`

```c
struct inode * d_backing_inode(const struct dentry *upper)
```

Get upper or lower inode we should be using

**Parameters**

- `const struct dentry *upper`: The upper layer

**Description**

This is the helper that should be used to get at the inode that will be used
if this dentry were to be opened as a file.  The inode may be on the upper
dentry or it may be on a lower dentry pinned by the upper.

Normal filesystems should not use this to access their own inodes.

#### <a id="c-d_real"></a>`d_real()`

```c
struct dentry * d_real(struct dentry *dentry, enum d_real_type type)
```

Return the real dentry

**Parameters**

- `struct dentry *dentry`: the dentry to query
- `enum d_real_type type`: the type of real dentry (data or metadata)

**Description**

If dentry is on a union/overlay, then return the underlying, real dentry.
Otherwise return the dentry itself.

See also: Documentation/filesystems/vfs.rst

#### <a id="c-d_real_inode"></a>`d_real_inode()`

```c
struct inode * d_real_inode(const struct dentry *dentry)
```

Return the real inode hosting the data

**Parameters**

- `const struct dentry *dentry`: The dentry to query

**Description**

If dentry is on a union/overlay, then return the underlying, real inode.
Otherwise return [`d_inode()`](#c-d_inode).


<a id="rst-inode-handling"></a>

### Inode Handling


#### <a id="c-inode_init_always_gfp"></a>`inode_init_always_gfp()`

```c
int inode_init_always_gfp(struct super_block *sb, struct inode *inode, gfp_t gfp)
```

perform inode structure initialisation

**Parameters**

- `struct super_block *sb`: superblock inode belongs to
- `struct inode *inode`: inode to initialise
- `gfp_t gfp`: allocation flags

**Description**

These are initializations that need to be done on every inode
allocation as the fields are not initialised by slab allocation.
If there are additional allocations required **gfp** is used.

#### <a id="c-drop_nlink"></a>`drop_nlink()`

```c
void drop_nlink(struct inode *inode)
```

directly drop an inode's link count

**Parameters**

- `struct inode *inode`: inode

**Description**

This is a low-level filesystem helper to replace any
direct filesystem manipulation of i_nlink.  In cases
where we are attempting to track writes to the
filesystem, a decrement to zero means an imminent
write when the file is truncated and actually unlinked
on the filesystem.

#### <a id="c-clear_nlink"></a>`clear_nlink()`

```c
void clear_nlink(struct inode *inode)
```

directly zero an inode's link count

**Parameters**

- `struct inode *inode`: inode

**Description**

This is a low-level filesystem helper to replace any
direct filesystem manipulation of i_nlink.  See
[`drop_nlink()`](#c-drop_nlink) for why we care about i_nlink hitting zero.

#### <a id="c-set_nlink"></a>`set_nlink()`

```c
void set_nlink(struct inode *inode, unsigned int nlink)
```

directly set an inode's link count

**Parameters**

- `struct inode *inode`: inode
- `unsigned int nlink`: new nlink (should be non-zero)

**Description**

This is a low-level filesystem helper to replace any
direct filesystem manipulation of i_nlink.

#### <a id="c-inc_nlink"></a>`inc_nlink()`

```c
void inc_nlink(struct inode *inode)
```

directly increment an inode's link count

**Parameters**

- `struct inode *inode`: inode

**Description**

This is a low-level filesystem helper to replace any
direct filesystem manipulation of i_nlink.  Currently,
it is only here for parity with `dec_nlink()`.

#### <a id="c-inode_sb_list_add"></a>`inode_sb_list_add()`

```c
void inode_sb_list_add(struct inode *inode)
```

add inode to the superblock list of inodes

**Parameters**

- `struct inode *inode`: inode to add

#### <a id="c-__insert_inode_hash"></a>`__insert_inode_hash()`

```c
void __insert_inode_hash(struct inode *inode, unsigned long hashval)
```

hash an inode

**Parameters**

- `struct inode *inode`: unhashed inode
- `unsigned long hashval`: unsigned long value used to locate this object in the
  inode_hashtable.

**Description**

Add an inode to the inode hash for this superblock.

#### <a id="c-__remove_inode_hash"></a>`__remove_inode_hash()`

```c
void __remove_inode_hash(struct inode *inode)
```

remove an inode from the hash

**Parameters**

- `struct inode *inode`: inode to unhash

**Description**

Remove an inode from the superblock.

#### <a id="c-evict_inodes"></a>`evict_inodes()`

```c
void evict_inodes(struct super_block *sb)
```

evict all evictable inodes for a superblock

**Parameters**

- `struct super_block *sb`: superblock to operate on

**Description**

Make sure that no inodes with zero refcount are retained.  This is
called by superblock shutdown after having SB_ACTIVE flag removed,
so any inode reaching zero refcount during or after that call will
be immediately evicted.

#### <a id="c-new_inode"></a>`new_inode()`

```c
struct inode * new_inode(struct super_block *sb)
```

obtain an inode

**Parameters**

- `struct super_block *sb`: superblock

**Description**

Allocates a new inode for given superblock. The default gfp_mask
for allocations related to inode->i_mapping is GFP_HIGHUSER_MOVABLE.
If HIGHMEM pages are unsuitable or it is known that pages allocated
for the page cache are not reclaimable or migratable,
`mapping_set_gfp_mask()` must be called with suitable flags on the
newly created inode's mapping

#### <a id="c-unlock_new_inode"></a>`unlock_new_inode()`

```c
void unlock_new_inode(struct inode *inode)
```

clear the I_NEW state and wake up any waiters

**Parameters**

- `struct inode *inode`: new inode to unlock

**Description**

Called when the inode is fully initialised to clear the new state of the
inode and wake up anyone waiting for the inode to finish initialisation.

#### <a id="c-lock_two_nondirectories"></a>`lock_two_nondirectories()`

```c
void lock_two_nondirectories(struct inode *inode1, struct inode *inode2)
```

take two i_mutexes on non-directory objects

**Parameters**

- `struct inode *inode1`: first inode to lock
- `struct inode *inode2`: second inode to lock

**Description**

Lock any non-NULL argument. Passed objects must not be directories.
Zero, one or two objects may be locked by this function.

#### <a id="c-unlock_two_nondirectories"></a>`unlock_two_nondirectories()`

```c
void unlock_two_nondirectories(struct inode *inode1, struct inode *inode2)
```

release locks from [`lock_two_nondirectories()`](#c-lock_two_nondirectories)

**Parameters**

- `struct inode *inode1`: first inode to unlock
- `struct inode *inode2`: second inode to unlock

#### <a id="c-inode_insert5"></a>`inode_insert5()`

```c
struct inode * inode_insert5(struct inode *inode, unsigned long hashval, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *data)
```

obtain an inode from a mounted file system

**Parameters**

- `struct inode *inode`: pre-allocated inode to use for insert to cache
- `unsigned long hashval`: hash value (usually inode number) to get
- `int (*test)(struct inode *, void *)`: callback used for comparisons between inodes
- `int (*set)(struct inode *, void *)`: callback used to initialize a new struct inode
- `void *data`: opaque data pointer to pass to **test** and **set**

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache,
and if present return it with an increased reference count. This is a
variant of [`iget5_locked()`](#c-iget5_locked) that doesn't allocate an inode.

If the inode is not present in the cache, insert the pre-allocated inode and
return it locked, hashed, and with the I_NEW flag set. The file system gets
to fill it in before unlocking it via [`unlock_new_inode()`](#c-unlock_new_inode).

Note that both **test** and **set** are called with the inode_hash_lock held, so
they can't sleep.

#### <a id="c-iget5_locked"></a>`iget5_locked()`

```c
struct inode * iget5_locked(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *data)
```

obtain an inode from a mounted file system

**Parameters**

- `struct super_block *sb`: super block of file system
- `unsigned long hashval`: hash value (usually inode number) to get
- `int (*test)(struct inode *, void *)`: callback used for comparisons between inodes
- `int (*set)(struct inode *, void *)`: callback used to initialize a new struct inode
- `void *data`: opaque data pointer to pass to **test** and **set**

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache,
and if present return it with an increased reference count. This is a
generalized version of [`iget_locked()`](#c-iget_locked) for file systems where the inode
number is not sufficient for unique identification of an inode.

If the inode is not present in the cache, allocate and insert a new inode
and return it locked, hashed, and with the I_NEW flag set. The file system
gets to fill it in before unlocking it via [`unlock_new_inode()`](#c-unlock_new_inode).

Note that both **test** and **set** are called with the inode_hash_lock held, so
they can't sleep.

#### <a id="c-iget5_locked_rcu"></a>`iget5_locked_rcu()`

```c
struct inode * iget5_locked_rcu(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *data)
```

obtain an inode from a mounted file system

**Parameters**

- `struct super_block *sb`: super block of file system
- `unsigned long hashval`: hash value (usually inode number) to get
- `int (*test)(struct inode *, void *)`: callback used for comparisons between inodes
- `int (*set)(struct inode *, void *)`: callback used to initialize a new struct inode
- `void *data`: opaque data pointer to pass to **test** and **set**

**Description**

This is equivalent to iget5_locked, except the **test** callback must
tolerate the inode not being stable, including being mid-teardown.

#### <a id="c-iget_locked"></a>`iget_locked()`

```c
struct inode * iget_locked(struct super_block *sb, unsigned long ino)
```

obtain an inode from a mounted file system

**Parameters**

- `struct super_block *sb`: super block of file system
- `unsigned long ino`: inode number to get

**Description**

Search for the inode specified by **ino** in the inode cache and if present
return it with an increased reference count. This is for file systems
where the inode number is sufficient for unique identification of an inode.

If the inode is not in cache, allocate a new inode and return it locked,
hashed, and with the I_NEW flag set.  The file system gets to fill it in
before unlocking it via [`unlock_new_inode()`](#c-unlock_new_inode).

#### <a id="c-iunique"></a>`iunique()`

```c
ino_t iunique(struct super_block *sb, ino_t max_reserved)
```

get a unique inode number

**Parameters**

- `struct super_block *sb`: superblock
- `ino_t max_reserved`: highest reserved inode number

**Description**

Obtain an inode number that is unique on the system for a given
superblock. This is used by file systems that have no natural
permanent inode numbering system. An inode number is returned that
is higher than the reserved limit but unique.

BUGS:
With a large number of inodes live on the file system this function
currently becomes quite slow.

#### <a id="c-ilookup5_nowait"></a>`ilookup5_nowait()`

```c
struct inode * ilookup5_nowait(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data, bool *isnew)
```

search for an inode in the inode cache

**Parameters**

- `struct super_block *sb`: super block of file system to search
- `unsigned long hashval`: hash value (usually inode number) to search for
- `int (*test)(struct inode *, void *)`: callback used for comparisons between inodes
- `void *data`: opaque data pointer to pass to **test**
- `bool *isnew`: return argument telling whether I_NEW was set when
  the inode was found in hash (the caller needs to
  wait for I_NEW to clear)

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache.
If the inode is in the cache, the inode is returned with an incremented
reference count.

**Note**

I_NEW is not waited upon so you have to be very careful what you do
with the returned inode.  You probably should be using [`ilookup5()`](#c-ilookup5) instead.

Note2: **test** is called with the inode_hash_lock held, so can't sleep.

#### <a id="c-ilookup5"></a>`ilookup5()`

```c
struct inode * ilookup5(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data)
```

search for an inode in the inode cache

**Parameters**

- `struct super_block *sb`: super block of file system to search
- `unsigned long hashval`: hash value (usually inode number) to search for
- `int (*test)(struct inode *, void *)`: callback used for comparisons between inodes
- `void *data`: opaque data pointer to pass to **test**

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache,
and if the inode is in the cache, return the inode with an incremented
reference count.  Waits on I_NEW before returning the inode.
returned with an incremented reference count.

This is a generalized version of [`ilookup()`](#c-ilookup) for file systems where the
inode number is not sufficient for unique identification of an inode.

**Note**

**test** is called with the inode_hash_lock held, so can't sleep.

#### <a id="c-ilookup"></a>`ilookup()`

```c
struct inode * ilookup(struct super_block *sb, unsigned long ino)
```

search for an inode in the inode cache

**Parameters**

- `struct super_block *sb`: super block of file system to search
- `unsigned long ino`: inode number to search for

**Description**

Search for the inode **ino** in the inode cache, and if the inode is in the
cache, the inode is returned with an incremented reference count.

#### <a id="c-find_inode_nowait"></a>`find_inode_nowait()`

```c
struct inode * find_inode_nowait(struct super_block *sb, unsigned long hashval, int (*match)(struct inode *, unsigned long, void *), void *data)
```

find an inode in the inode cache

**Parameters**

- `struct super_block *sb`: super block of file system to search
- `unsigned long hashval`: hash value (usually inode number) to search for
- `int (*match)(struct inode *, unsigned long, void *)`: callback used for comparisons between inodes
- `void *data`: opaque data pointer to pass to **match**

**Description**

Search for the inode specified by **hashval** and **data** in the inode
cache, where the helper function **match** will return 0 if the inode
does not match, 1 if the inode does match, and -1 if the search
should be stopped.  The **match** function must be responsible for
taking the i_lock spin_lock and checking i_state for an inode being
freed or being initialized, and incrementing the reference count
before returning 1.  It also must not sleep, since it is called with
the inode_hash_lock spinlock held.

This is a even more generalized version of [`ilookup5()`](#c-ilookup5) when the
function must never block --- `find_inode()` can block in
`__wait_on_freeing_inode()` --- or when the caller can not increment
the reference count because the resulting [`iput()`](#c-iput) might cause an
inode eviction.  The tradeoff is that the **match** funtion must be
very carefully implemented.

#### <a id="c-find_inode_rcu"></a>`find_inode_rcu()`

```c
struct inode * find_inode_rcu(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data)
```

find an inode in the inode cache

**Parameters**

- `struct super_block *sb`: Super block of file system to search
- `unsigned long hashval`: Key to hash
- `int (*test)(struct inode *, void *)`: Function to test match on an inode
- `void *data`: Data for test function

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache,
where the helper function **test** will return 0 if the inode does not match
and 1 if it does.  The **test** function must be responsible for taking the
i_lock spin_lock and checking i_state for an inode being freed or being
initialized.

If successful, this will return the inode for which the **test** function
returned 1 and NULL otherwise.

The **test** function is not permitted to take a ref on any inode presented.
It is also not permitted to sleep.

The caller must hold the RCU read lock.

#### <a id="c-find_inode_by_ino_rcu"></a>`find_inode_by_ino_rcu()`

```c
struct inode * find_inode_by_ino_rcu(struct super_block *sb, unsigned long ino)
```

Find an inode in the inode cache

**Parameters**

- `struct super_block *sb`: Super block of file system to search
- `unsigned long ino`: The inode number to match

**Description**

Search for the inode specified by **hashval** and **data** in the inode cache,
where the helper function **test** will return 0 if the inode does not match
and 1 if it does.  The **test** function must be responsible for taking the
i_lock spin_lock and checking i_state for an inode being freed or being
initialized.

If successful, this will return the inode for which the **test** function
returned 1 and NULL otherwise.

The **test** function is not permitted to take a ref on any inode presented.
It is also not permitted to sleep.

The caller must hold the RCU read lock.

#### <a id="c-iput"></a>`iput()`

```c
void iput(struct inode *inode)
```

put an inode

**Parameters**

- `struct inode *inode`: inode to put

**Description**

Puts an inode, dropping its usage count. If the inode use count hits
zero, the inode is then freed and may also be destroyed.

Consequently, [`iput()`](#c-iput) can sleep.

#### <a id="c-iput_not_last"></a>`iput_not_last()`

```c
void iput_not_last(struct inode *inode)
```

put an inode assuming this is not the last reference

**Parameters**

- `struct inode *inode`: inode to put

#### <a id="c-bmap"></a>`bmap()`

```c
int bmap(struct inode *inode, sector_t *block)
```

find a block number in a file

**Parameters**

- `struct inode *inode`: inode owning the block number being requested
- `sector_t *block`: pointer containing the block to find

**Description**

Replaces the value in `*block` with the block number on the device holding
corresponding to the requested block number in the file.
That is, asked for block 4 of inode 1 the function will replace the
4 in `*block`, with disk block relative to the disk start that holds that
block of the file.

Returns -EINVAL in case of error, 0 otherwise. If mapping falls into a
hole, returns 0 and `*block` is also set to 0.

#### <a id="c-inode_update_time"></a>`inode_update_time()`

```c
int inode_update_time(struct inode *inode, enum fs_update_time type, unsigned int flags)
```

update either atime or c/mtime and i_version on the inode

**Parameters**

- `struct inode *inode`: inode to be updated
- `enum fs_update_time type`: timestamp to be updated
- `unsigned int flags`: flags for the update

**Description**

Update either atime or c/mtime and version in a inode if needed for a file
access or modification.  It is up to the caller to mark the inode dirty
appropriately.

Returns the positive I_DIRTY_* flags for [`__mark_inode_dirty()`](#c-__mark_inode_dirty) if the inode
needs to be marked dirty, 0 if it did not, or a negative errno if an error
happened.

#### <a id="c-generic_update_time"></a>`generic_update_time()`

```c
int generic_update_time(struct inode *inode, enum fs_update_time type, unsigned int flags)
```

update the timestamps on the inode

**Parameters**

- `struct inode *inode`: inode to be updated
- `enum fs_update_time type`: timestamp to be updated
- `unsigned int flags`: flags for the update

**Description**

Returns a negative error value on error, else 0.

#### <a id="c-file_remove_privs"></a>`file_remove_privs()`

```c
int file_remove_privs(struct file *file)
```

remove special file privileges (suid, capabilities)

**Parameters**

- `struct file *file`: file to remove privileges from

**Description**

When file is modified by a write or truncation ensure that special
file privileges are removed.

**Return**

0 on success, negative errno on failure.

#### <a id="c-current_time"></a>`current_time()`

```c
struct timespec64 current_time(struct inode *inode)
```

Return FS time (possibly fine-grained)

**Parameters**

- `struct inode *inode`: inode.

**Description**

Return the current time truncated to the time granularity supported by
the fs, as suitable for a ctime/mtime change. If the ctime is flagged
as having been QUERIED, get a fine-grained timestamp, but don't update
the floor.

For a multigrain inode, this is effectively an estimate of the timestamp
that a file would receive. An actual update must go through
[`inode_set_ctime_current()`](#c-inode_set_ctime_current).

#### <a id="c-file_update_time"></a>`file_update_time()`

```c
int file_update_time(struct file *file)
```

update mtime and ctime time

**Parameters**

- `struct file *file`: file accessed

**Description**

Update the mtime and ctime members of an inode and mark the inode for
writeback. Note that this function is meant exclusively for usage in
the file write path of filesystems, and filesystems may choose to
explicitly ignore updates via this function with the _NOCMTIME inode
flag, e.g. for network filesystem where these imestamps are handled
by the server. This can return an error for file systems who need to
allocate space in order to update an inode.

**Return**

0 on success, negative errno on failure.

#### <a id="c-file_modified"></a>`file_modified()`

```c
int file_modified(struct file *file)
```

handle mandated vfs changes when modifying a file

**Parameters**

- `struct file *file`: file that was modified

**Description**

When file has been modified ensure that special
file privileges are removed and time settings are updated.

**Context**

Caller must hold the file's inode lock.

**Return**

0 on success, negative errno on failure.

#### <a id="c-kiocb_modified"></a>`kiocb_modified()`

```c
int kiocb_modified(struct kiocb *iocb)
```

handle mandated vfs changes when modifying a file

**Parameters**

- `struct kiocb *iocb`: iocb that was modified

**Description**

When file has been modified ensure that special
file privileges are removed and time settings are updated.

**Context**

Caller must hold the file's inode lock.

**Return**

0 on success, negative errno on failure.

#### <a id="c-inode_init_owner"></a>`inode_init_owner()`

```c
void inode_init_owner(struct mnt_idmap *idmap, struct inode *inode, const struct inode *dir, umode_t mode)
```

Init uid,gid,mode for new inode according to posix standards

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was created from
- `struct inode *inode`: New inode
- `const struct inode *dir`: Directory inode
- `umode_t mode`: mode of the new inode

**Description**

If the inode has been created through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions
and initializing i_uid and i_gid. On non-idmapped mounts or if permission
checking is to be performed on the raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-inode_owner_or_capable"></a>`inode_owner_or_capable()`

```c
bool inode_owner_or_capable(struct mnt_idmap *idmap, const struct inode *inode)
```

check current task permissions to inode

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct inode *inode`: inode being checked

**Description**

Return true if current either has CAP_FOWNER in a namespace with the
inode owner uid mapped, or owns the file.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-inode_dio_wait"></a>`inode_dio_wait()`

```c
void inode_dio_wait(struct inode *inode)
```

wait for outstanding DIO requests to finish

**Parameters**

- `struct inode *inode`: inode to wait for

**Description**

Waits for all pending direct I/O requests to finish so that we can
proceed with a truncate or equivalent operation.

Must be called under a lock that serializes taking new references
to i_dio_count, usually by inode->i_rwsem.

#### <a id="c-timestamp_truncate"></a>`timestamp_truncate()`

```c
struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode)
```

Truncate timespec to a granularity

**Parameters**

- `struct timespec64 t`: Timespec
- `struct inode *inode`: inode being updated

**Description**

Truncate a timespec to the granularity supported by the fs
containing the inode. Always rounds down. gran must
not be 0 nor greater than a second (NSEC_PER_SEC, or 10^9 ns).

#### <a id="c-inode_set_ctime_current"></a>`inode_set_ctime_current()`

```c
struct timespec64 inode_set_ctime_current(struct inode *inode)
```

set the ctime to current_time

**Parameters**

- `struct inode *inode`: inode

**Description**

Set the inode's ctime to the current value for the inode. Returns the
current value that was assigned. If this is not a multigrain inode, then we
set it to the later of the coarse time and floor value.

If it is multigrain, then we first see if the coarse-grained timestamp is
distinct from what is already there. If so, then use that. Otherwise, get a
fine-grained timestamp.

After that, try to swap the new value into i_ctime_nsec. Accept the
resulting ctime, regardless of the outcome of the swap. If it has
already been replaced, then that timestamp is later than the earlier
unacceptable one, and is thus acceptable.

#### <a id="c-inode_set_ctime_deleg"></a>`inode_set_ctime_deleg()`

```c
struct timespec64 inode_set_ctime_deleg(struct inode *inode, struct timespec64 update)
```

try to update the ctime on a delegated inode

**Parameters**

- `struct inode *inode`: inode to update
- `struct timespec64 update`: timespec64 to set the ctime

**Description**

Attempt to atomically update the ctime on behalf of a delegation holder.

The nfs server can call back the holder of a delegation to get updated
inode attributes, including the mtime. When updating the mtime, update
the ctime to a value at least equal to that.

This can race with concurrent updates to the inode, in which
case the update is skipped.

Note that this works even when multigrain timestamps are not enabled,
so it is used in either case.

#### <a id="c-in_group_or_capable"></a>`in_group_or_capable()`

```c
bool in_group_or_capable(struct mnt_idmap *idmap, const struct inode *inode, vfsgid_t vfsgid)
```

check whether caller is CAP_FSETID privileged

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount **inode** was found from
- `const struct inode *inode`: inode to check
- `vfsgid_t vfsgid`: the new/current vfsgid of **inode**

**Description**

Check whether **vfsgid** is in the caller's group list or if the caller is
privileged with CAP_FSETID over **inode**. This can be used to determine
whether the setgid bit can be kept or must be dropped.

**Return**

true if the caller is sufficiently privileged, false if not.

#### <a id="c-mode_strip_sgid"></a>`mode_strip_sgid()`

```c
umode_t mode_strip_sgid(struct mnt_idmap *idmap, const struct inode *dir, umode_t mode)
```

handle the sgid bit for non-directories

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was created from
- `const struct inode *dir`: parent directory inode
- `umode_t mode`: mode of the file to be created in **dir**

**Description**

If the **mode** of the new file has both the S_ISGID and S_IXGRP bit
raised and **dir** has the S_ISGID bit raised ensure that the caller is
either in the group of the parent directory or they have CAP_FSETID
in their user namespace and are privileged over the parent directory.
In all other cases, strip the S_ISGID bit from **mode**.

**Return**

the new mode to use for the file

#### <a id="c-dump_inode"></a>`dump_inode()`

```c
void dump_inode(struct inode *inode, const char *reason)
```

dump an inode.

**Parameters**

- `struct inode *inode`: inode to dump
- `const char *reason`: reason for dumping

**Description**

If inode is an invalid pointer, we don't want to crash accessing it,
so probe everything depending on it carefully with `get_kernel_nofault()`.



#### <a id="c-make_bad_inode"></a>`make_bad_inode()`

```c
void make_bad_inode(struct inode *inode)
```

mark an inode bad due to an I/O error

**Parameters**

- `struct inode *inode`: Inode to mark bad

**Description**

When an inode cannot be read due to a media or remote network
failure this function makes the inode "bad" and causes I/O operations
on it to fail from this point on.

#### <a id="c-is_bad_inode"></a>`is_bad_inode()`

```c
bool is_bad_inode(struct inode *inode)
```

is an inode errored

**Parameters**

- `struct inode *inode`: inode to test

**Description**

Returns true if the inode in question has been marked as bad.

#### <a id="c-iget_failed"></a>`iget_failed()`

```c
void iget_failed(struct inode *inode)
```

Mark an under-construction inode as dead and release it

**Parameters**

- `struct inode *inode`: The inode to discard

**Description**

Mark an under-construction inode as dead and release it.


<a id="rst-registration-and-superblocks"></a>

### Registration and Superblocks


#### <a id="c-deactivate_locked_super"></a>`deactivate_locked_super()`

```c
void deactivate_locked_super(struct super_block *s)
```

drop an active reference to superblock

**Parameters**

- `struct super_block *s`: superblock to deactivate

**Description**

Drops an active reference to superblock, converting it into a temporary
one if there is no other active references left.  In that case we
tell fs driver to shut it down and drop the temporary reference we
had just acquired.

Caller holds exclusive lock on superblock; that lock is released.

#### <a id="c-deactivate_super"></a>`deactivate_super()`

```c
void deactivate_super(struct super_block *s)
```

drop an active reference to superblock

**Parameters**

- `struct super_block *s`: superblock to deactivate

**Description**

Variant of [`deactivate_locked_super()`](#c-deactivate_locked_super), except that superblock is *not*
locked by caller.  If we are going to drop the final active reference,
lock will be acquired prior to that.

#### <a id="c-retire_super"></a>`retire_super()`

```c
void retire_super(struct super_block *sb)
```

prevents superblock from being reused

**Parameters**

- `struct super_block *sb`: superblock to retire

**Description**

The function marks superblock to be ignored in superblock test, which
prevents it from being reused for any new mounts.  If the superblock has
a private bdi, it also unregisters it, but doesn't reduce the refcount
of the superblock to prevent potential races.  The refcount is reduced
by [`generic_shutdown_super()`](#c-generic_shutdown_super).  The function can not be called
concurrently with [`generic_shutdown_super()`](#c-generic_shutdown_super).  It is safe to call the
function multiple times, subsequent calls have no effect.

The marker will affect the re-use only for block-device-based
superblocks.  Other superblocks will still get marked if this function
is used, but that will not affect their reusability.

#### <a id="c-generic_shutdown_super"></a>`generic_shutdown_super()`

```c
void generic_shutdown_super(struct super_block *sb)
```

common helper for ->`kill_sb()`

**Parameters**

- `struct super_block *sb`: superblock to kill

**Description**

[`generic_shutdown_super()`](#c-generic_shutdown_super) does all fs-independent work on superblock
shutdown.  Typical ->`kill_sb()` should pick all fs-specific objects
that need destruction out of superblock, call [`generic_shutdown_super()`](#c-generic_shutdown_super)
and release aforementioned objects.  Note: dentries and inodes _are_
taken care of and do not need specific handling.

Upon calling this function, the filesystem may no longer alter or
rearrange the set of dentries belonging to this super_block, nor may it
change the attachments of dentries to inodes.

#### <a id="c-sget_fc"></a>`sget_fc()`

```c
struct super_block * sget_fc(struct fs_context *fc, int (*test)(struct super_block *, struct fs_context *), int (*set)(struct super_block *, struct fs_context *))
```

Find or create a superblock

**Parameters**

- `struct fs_context *fc`: Filesystem context.
- `int (*test)(struct super_block *, struct fs_context *)`: Comparison callback
- `int (*set)(struct super_block *, struct fs_context *)`: Setup callback

**Description**

Create a new superblock or find an existing one.

The **test** callback is used to find a matching existing superblock.
Whether or not the requested parameters in **fc** are taken into account
is specific to the **test** callback that is used. They may even be
completely ignored.

If an extant superblock is matched, it will be returned unless:

- (1) the namespace the filesystem context **fc** and the extant

  superblock's namespace differ

- (2) the filesystem context **fc** has requested that reusing an extant

  superblock is not allowed

In both cases EBUSY will be returned.

If no match is made, a new superblock will be allocated and basic
initialisation will be performed (s_type, s_fs_info and s_id will be
set and the **set** callback will be invoked), the superblock will be
published and it will be returned in a partially constructed state
with SB_BORN and SB_ACTIVE as yet unset.

**Return**

On success, an extant or newly created superblock is
returned. On failure an error pointer is returned.

#### <a id="c-sget"></a>`sget()`

```c
struct super_block * sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), int flags, void *data)
```

find or create a superblock

**Parameters**

- `struct file_system_type *type`: filesystem type superblock should belong to
- `int (*test)(struct super_block *,void *)`: comparison callback
- `int (*set)(struct super_block *,void *)`: setup callback
- `int flags`: mount flags
- `void *data`: argument to each of them

#### <a id="c-iterate_supers_type"></a>`iterate_supers_type()`

```c
void iterate_supers_type(struct file_system_type *type, void (*f)(struct super_block *, void *), void *arg)
```

call function for superblocks of given type

**Parameters**

- `struct file_system_type *type`: fs type
- `void (*f)(struct super_block *, void *)`: function to call
- `void *arg`: argument to pass to it

**Description**

Scans the superblock list and calls given function, passing it
locked superblock and given argument.

#### <a id="c-get_anon_bdev"></a>`get_anon_bdev()`

```c
int get_anon_bdev(dev_t *p)
```

Allocate a block device for filesystems which don't have one.

**Parameters**

- `dev_t *p`: Pointer to a dev_t.

**Description**

Filesystems which don't use real block devices can call this function
to allocate a virtual block device.

**Context**

Any context.  Frequently called while holding sb_lock.

**Return**

0 on success, -EMFILE if there are no anonymous bdevs left
or -ENOMEM if memory allocation failed.

#### <a id="c-sget_dev"></a>`sget_dev()`

```c
struct super_block * sget_dev(struct fs_context *fc, dev_t dev)
```

Find or create a superblock by device number

**Parameters**

- `struct fs_context *fc`: Filesystem context.
- `dev_t dev`: device number

**Description**

Find or create a superblock using the provided device number that
will be stored in fc->sget_key.

If an extant superblock is matched, then that will be returned with
an elevated reference count that the caller must transfer or discard.

If no match is made, a new superblock will be allocated and basic
initialisation will be performed (s_type, s_fs_info, s_id, s_dev will
be set). The superblock will be published and it will be returned in
a partially constructed state with SB_BORN and SB_ACTIVE as yet
unset.

**Return**

an existing or newly created superblock on success, an error
pointer on failure.

#### <a id="c-get_tree_bdev_flags"></a>`get_tree_bdev_flags()`

```c
int get_tree_bdev_flags(struct fs_context *fc, int (*fill_super)(struct super_block *sb, struct fs_context *fc), unsigned int flags)
```

Get a superblock based on a single block device

**Parameters**

- `struct fs_context *fc`: The filesystem context holding the parameters
- `int (*fill_super)(struct super_block *sb, struct fs_context *fc)`: Helper to initialise a new superblock
- `unsigned int flags`: GET_TREE_BDEV_* flags

#### <a id="c-get_tree_bdev"></a>`get_tree_bdev()`

```c
int get_tree_bdev(struct fs_context *fc, int (*fill_super)(struct super_block *, struct fs_context *))
```

Get a superblock based on a single block device

**Parameters**

- `struct fs_context *fc`: The filesystem context holding the parameters
- `int (*fill_super)(struct super_block *, struct fs_context *)`: Helper to initialise a new superblock

#### <a id="c-vfs_get_tree"></a>`vfs_get_tree()`

```c
int vfs_get_tree(struct fs_context *fc)
```

Get the mountable root

**Parameters**

- `struct fs_context *fc`: The superblock configuration context.

**Description**

The filesystem is invoked to get or create a superblock which can then later
be used for mounting.  The filesystem places a pointer to the root to be
used for mounting in **fc->root**.

#### <a id="c-freeze_super"></a>`freeze_super()`

```c
int freeze_super(struct super_block *sb, enum freeze_holder who, const void *freeze_owner)
```

lock the filesystem and force it into a consistent state

**Parameters**

- `struct super_block *sb`: the super to lock
- `enum freeze_holder who`: context that wants to freeze
- `const void *freeze_owner`: owner of the freeze

**Description**

Syncs the super to make sure the filesystem is consistent and calls the fs's
freeze_fs.  Subsequent calls to this without first thawing the fs may return
-EBUSY.

**who** should be:
* `FREEZE_HOLDER_USERSPACE` if userspace wants to freeze the fs;
* `FREEZE_HOLDER_KERNEL` if the kernel wants to freeze the fs.
* `FREEZE_MAY_NEST` whether nesting freeze and thaw requests is allowed.

The **who** argument distinguishes between the kernel and userspace trying to
freeze the filesystem.  Although there cannot be multiple kernel freezes or
multiple userspace freezes in effect at any given time, the kernel and
userspace can both hold a filesystem frozen.  The filesystem remains frozen
until there are no kernel or userspace freezes in effect.

A filesystem may hold multiple devices and thus a filesystems may be
frozen through the block layer via multiple block devices. In this
case the request is marked as being allowed to nest by passing
FREEZE_MAY_NEST. The filesystem remains frozen until all block
devices are unfrozen. If multiple freezes are attempted without
FREEZE_MAY_NEST -EBUSY will be returned.

During this function, sb->s_writers.frozen goes through these values:

SB_UNFROZEN: File system is normal, all writes progress as usual.

SB_FREEZE_WRITE: The file system is in the process of being frozen.  New
writes should be blocked, though page faults are still allowed. We wait for
all writes to complete and then proceed to the next stage.

SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked
but internal fs threads can still modify the filesystem (although they
should not dirty new pages or inodes), writeback can run etc. After waiting
for all running page faults we sync the filesystem which will clean all
dirty pages and inodes (no new dirty pages or inodes can be created when
sync is running).

SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs
modification are blocked (e.g. XFS preallocation truncation on inode
reclaim). This is usually implemented by blocking new transactions for
filesystems that have them and need this additional guard. After all
internal writers are finished we call ->`freeze_fs()` to finish filesystem
freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is
mostly auxiliary for filesystems to verify they do not modify frozen fs.

sb->s_writers.frozen is protected by sb->s_umount.

**Return**

If the freeze was successful zero is returned. If the freeze
failed a negative error code is returned.

#### <a id="c-thaw_super"></a>`thaw_super()`

```c
int thaw_super(struct super_block *sb, enum freeze_holder who, const void *freeze_owner)
```

- unlock filesystem

**Parameters**

- `struct super_block *sb`: the super to thaw
- `enum freeze_holder who`: context that wants to freeze
- `const void *freeze_owner`: owner of the freeze

**Description**

Unlocks the filesystem and marks it writeable again after [`freeze_super()`](#c-freeze_super)
if there are no remaining freezes on the filesystem.

**who** should be:
* `FREEZE_HOLDER_USERSPACE` if userspace wants to thaw the fs;
* `FREEZE_HOLDER_KERNEL` if the kernel wants to thaw the fs.
* `FREEZE_MAY_NEST` whether nesting freeze and thaw requests is allowed

A filesystem may hold multiple devices and thus a filesystems may
have been frozen through the block layer via multiple block devices.
The filesystem remains frozen until all block devices are unfrozen.


<a id="rst-file-locks"></a>

### File Locks


#### <a id="c-locks_owner_has_blockers"></a>`locks_owner_has_blockers()`

```c
bool locks_owner_has_blockers(struct file_lock_context *flctx, fl_owner_t owner)
```

Check for blocking lock requests

**Parameters**

- `struct file_lock_context *flctx`: file lock context
- `fl_owner_t owner`: lock owner

**Description**

- Return values:
  `true`: **owner** has at least one blocker
  `false`: **owner** has no blockers

#### <a id="c-locks_delete_block"></a>`locks_delete_block()`

```c
int locks_delete_block(struct file_lock *waiter)
```

stop waiting for a file lock

**Parameters**

- `struct file_lock *waiter`: the lock which was waiting

**Description**

lockd/nfsd need to disconnect the lock while working on it.

#### <a id="c-posix_lock_file"></a>`posix_lock_file()`

```c
int posix_lock_file(struct file *filp, struct file_lock *fl, struct file_lock *conflock)
```

Apply a POSIX-style lock to a file

**Parameters**

- `struct file *filp`: The file to apply the lock to
- `struct file_lock *fl`: The lock to be applied
- `struct file_lock *conflock`: Place to return a copy of the conflicting lock, if found.

**Description**

Add a POSIX style lock to a file.
We merge adjacent & overlapping locks whenever possible.
POSIX locks are sorted by owner task, then by starting address

Note that if called with an FL_EXISTS argument, the caller may determine
whether or not a lock was successfully freed by testing the return
value for -ENOENT.

#### <a id="c-__break_lease"></a>`__break_lease()`

```c
int __break_lease(struct inode *inode, unsigned int flags)
```

revoke all outstanding leases on file

**Parameters**

- `struct inode *inode`: the inode of the file to return
- `unsigned int flags`: LEASE_BREAK_* flags

**Description**

break_lease (inlined for speed) has checked there already is at least
some kind of lock (maybe a lease) on this file.  Leases are broken on
a call to `open()` or `truncate()`.  This function can block waiting for the
lease break unless you specify LEASE_BREAK_NONBLOCK.

#### <a id="c-lease_get_mtime"></a>`lease_get_mtime()`

```c
void lease_get_mtime(struct inode *inode, struct timespec64 *time)
```

update modified time of an inode with exclusive lease

**Parameters**

- `struct inode *inode`: the inode
- `struct timespec64 *time`: pointer to a timespec which contains the last modified time

**Description**

This is to force NFS clients to flush their caches for files with
exclusive leases.  The justification is that if someone has an
exclusive lease, then they could be modifying it.

#### <a id="c-kernel_getlease"></a>`kernel_getlease()`

```c
int kernel_getlease(struct file *filp, struct file *lease_file, unsigned int flavor)
```

Query a file lease or delegation through its filesystem

**Parameters**

- `struct file *filp`: the file whose lease state is queried
- `struct file *lease_file`: the original lease owner, or NULL to use **filp**
- `unsigned int flavor`: FL_LEASE or FL_DELEG

**Description**

Dispatch to the filesystem getlease method when present, otherwise query
the generic inode lease state. Layered filesystems preserve **lease_file**
while forwarding the query to a backing file.

**Return**

F_RDLCK, F_WRLCK or F_UNLCK, or a negative error from the filesystem.

#### <a id="c-generic_setlease"></a>`generic_setlease()`

```c
int generic_setlease(struct file *filp, int arg, struct file_lease **flp, void **priv)
```

sets a lease on an open file

**Parameters**

- `struct file *filp`: file pointer
- `int arg`: type of lease to obtain
- `struct file_lease **flp`: input - file_lock to use, output - file_lock inserted
- `void **priv`: private data for lm_setup (may be NULL if lm_setup
  doesn't require it)

**Description**

The (input) flp->fl_lmops->lm_break function is required
by `break_lease()`.

#### <a id="c-vfs_setlease"></a>`vfs_setlease()`

```c
int vfs_setlease(struct file *filp, int arg, struct file_lease **lease, void **priv)
```

sets a lease on an open file

**Parameters**

- `struct file *filp`: file pointer
- `int arg`: type of lease to obtain
- `struct file_lease **lease`: file_lock to use when adding a lease
- `void **priv`: private info for lm_setup when adding a lease (may be
  NULL if lm_setup doesn't require it)

**Description**

Call this to establish a lease on the file. The "lease" argument is not
used for F_UNLCK requests and may be NULL. For commands that set or alter
an existing lease, the `(*lease)->fl_lmops->lm_break` operation must be
set; if not, this function will return -ENOLCK (and generate a scary-looking
stack trace).

The "priv" pointer is passed directly to the lm_setup function as-is. It
may be NULL if the lm_setup operation doesn't require it.

#### <a id="c-locks_lock_inode_wait"></a>`locks_lock_inode_wait()`

```c
int locks_lock_inode_wait(struct inode *inode, struct file_lock *fl)
```

Apply a lock to an inode

**Parameters**

- `struct inode *inode`: inode of the file to apply to
- `struct file_lock *fl`: The lock to be applied

**Description**

Apply a POSIX or FLOCK style lock request to an inode.

#### <a id="c-vfs_test_lock"></a>`vfs_test_lock()`

```c
int vfs_test_lock(struct file *filp, struct file_lock *fl)
```

test file byte range lock

**Parameters**

- `struct file *filp`: The file to test lock for
- `struct file_lock *fl`: The byte-range in the file to test; also used to hold result

**Description**

On entry, **fl** does not contain a lock, but identifies a range (fl_start, fl_end)
in the file (c.flc_file), and an owner (c.flc_owner) for whom existing locks
should be ignored.  c.flc_type and c.flc_flags are ignored.
Both fl_lmops and fl_ops in **fl** must be NULL.
Returns -ERRNO on failure.  Indicates presence of conflicting lock by
setting fl->fl_type to something other than F_UNLCK.

If [`vfs_test_lock()`](#c-vfs_test_lock) does find a lock and return it, the caller must
use `locks_free_lock()` or `locks_release_private()` on the returned lock.

#### <a id="c-vfs_lock_file"></a>`vfs_lock_file()`

```c
int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf)
```

file byte range lock

**Parameters**

- `struct file *filp`: The file to apply the lock to
- `unsigned int cmd`: type of locking operation (F_SETLK, F_GETLK, etc.)
- `struct file_lock *fl`: The lock to be applied
- `struct file_lock *conf`: Place to return a copy of the conflicting lock, if found.

**Description**

A caller that doesn't care about the conflicting lock may pass NULL
as the final argument.

If the filesystem defines a private ->`lock()` method, then **conf** will
be left unchanged; so a caller that cares should initialize it to
some acceptable default.

To avoid blocking kernel daemons, such as lockd, that need to acquire POSIX
locks, the ->`lock()` interface may return asynchronously, before the lock has
been granted or denied by the underlying filesystem, if (and only if)
lm_grant is set. Additionally FOP_ASYNC_LOCK in file_operations fop_flags
need to be set.

Callers expecting ->`lock()` to return asynchronously will only use F_SETLK,
not F_SETLKW; they will set FL_SLEEP if (and only if) the request is for a
blocking lock. When ->`lock()` does return asynchronously, it must return
FILE_LOCK_DEFERRED, and call ->`lm_grant()` when the lock request completes.
If the request is for non-blocking lock the file system should return
FILE_LOCK_DEFERRED then try to get the lock and call the callback routine
with the result. If the request timed out the callback routine will return a
nonzero return code and the file system should release the lock. The file
system is also responsible to keep a corresponding posix lock when it
grants a lock so the VFS can find out which locks are locally held and do
the correct lock cleanup when required.
The underlying filesystem must not drop the kernel lock or call
->`lm_grant()` before returning to the caller with a FILE_LOCK_DEFERRED
return code.

#### <a id="c-vfs_cancel_lock"></a>`vfs_cancel_lock()`

```c
int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
```

file byte range unblock lock

**Parameters**

- `struct file *filp`: The file to apply the unblock to
- `struct file_lock *fl`: The lock to be unblocked

**Description**

Used by lock managers to cancel blocked requests

#### <a id="c-vfs_inode_has_locks"></a>`vfs_inode_has_locks()`

```c
bool vfs_inode_has_locks(struct inode *inode)
```

are any file locks held on **inode**?

**Parameters**

- `struct inode *inode`: inode to check for locks

**Description**

Return true if there are any FL_POSIX or FL_FLOCK locks currently
set on **inode**.



#### <a id="c-lease_open_conflict"></a>`lease_open_conflict()`

```c
int lease_open_conflict(struct file *filp, const int arg)
```

see if the given file points to an inode that has an existing open that would conflict with the desired lease.

**Parameters**

- `struct file *filp`: file to check
- `const int arg`: type of lease that we're trying to acquire

**Description**

Check to see if there's an existing open fd on this file that would
conflict with the lease we're trying to set.

#### <a id="c-posix_lock_inode_wait"></a>`posix_lock_inode_wait()`

```c
int posix_lock_inode_wait(struct inode *inode, struct file_lock *fl)
```

Apply a POSIX-style lock to a file

**Parameters**

- `struct inode *inode`: inode of file to which lock request should be applied
- `struct file_lock *fl`: The lock to be applied

**Description**

Apply a POSIX style lock request to an inode.

#### <a id="c-generic_getlease"></a>`generic_getlease()`

```c
int generic_getlease(struct file *filp, struct file *lease_file, unsigned int flavor)
```

Enquire what lease is currently active

**Parameters**

- `struct file *filp`: the backing file whose inode stores the lease
- `struct file *lease_file`: the file identifying the lease owner
- `unsigned int flavor`: type of lease flags to check

**Description**

The value returned by this function will be one of
(if no lease break is pending):

`F_RDLCK` to indicate a shared lease is held.

`F_WRLCK` to indicate an exclusive lease is held.

`F_UNLCK` to indicate no lease is held.

(if a lease break is pending):

- `F_RDLCK` to indicate an exclusive lease needs to be

  changed to a shared lease (or removed).

`F_UNLCK` to indicate the lease needs to be removed.

XXX: sfr & willy disagree over whether F_INPROGRESS
should be returned to userspace.

#### <a id="c-fcntl_setlease"></a>`fcntl_setlease()`

```c
int fcntl_setlease(unsigned int fd, struct file *filp, int arg)
```

sets a lease on an open file

**Parameters**

- `unsigned int fd`: open file descriptor
- `struct file *filp`: file pointer
- `int arg`: type of lease to obtain

**Description**

Call this fcntl to establish a lease on the file.
Note that you also need to call `F_SETSIG` to
receive a signal when the lease is broken.

#### <a id="c-fcntl_setdeleg"></a>`fcntl_setdeleg()`

```c
int fcntl_setdeleg(unsigned int fd, struct file *filp, struct delegation *deleg)
```

sets a delegation on an open file

**Parameters**

- `unsigned int fd`: open file descriptor
- `struct file *filp`: file pointer
- `struct delegation *deleg`: delegation request from userland

**Description**

Call this fcntl to establish a delegation on the file.
Note that you also need to call `F_SETSIG` to
receive a signal when the lease is broken.

#### <a id="c-flock_lock_inode_wait"></a>`flock_lock_inode_wait()`

```c
int flock_lock_inode_wait(struct inode *inode, struct file_lock *fl)
```

Apply a FLOCK-style lock to a file

**Parameters**

- `struct inode *inode`: inode of the file to apply to
- `struct file_lock *fl`: The lock to be applied

**Description**

Apply a FLOCK style lock request to an inode.

#### <a id="c-sys_flock"></a>`sys_flock()`

```c
long sys_flock(unsigned int fd, unsigned int cmd)
```

- `flock()` system call.

**Parameters**

- `unsigned int fd`: the file descriptor to lock.
- `unsigned int cmd`: the type of lock to apply.

**Description**

Apply a `FL_FLOCK` style lock to an open file descriptor.
The **cmd** can be one of:

- `LOCK_SH` -- a shared lock.
- `LOCK_EX` -- an exclusive lock.
- `LOCK_UN` -- remove an existing lock.
- `LOCK_MAND` -- a 'mandatory' flock. (DEPRECATED)

`LOCK_MAND` support has been removed from the kernel.

#### <a id="c-locks_translate_pid"></a>`locks_translate_pid()`

```c
pid_t locks_translate_pid(struct file_lock_core *fl, struct pid_namespace *ns)
```

translate a file_lock's fl_pid number into a namespace

**Parameters**

- `struct file_lock_core *fl`: The file_lock who's fl_pid should be translated
- `struct pid_namespace *ns`: The namespace into which the pid should be translated

**Description**

Used to translate a fl_pid into a namespace virtual pid number


<a id="rst-other-functions"></a>

### Other Functions


#### <a id="c-mpage_readahead"></a>`mpage_readahead()`

```c
void mpage_readahead(struct readahead_control *rac, get_block_t get_block)
```

start reads against pages

**Parameters**

- `struct readahead_control *rac`: Describes which pages to read.
- `get_block_t get_block`: The filesystem's block mapper function.

**Description**

This function walks the pages and the blocks within each page, building and
emitting large BIOs.

If anything unusual happens, such as:

- encountering a page which has buffers
- encountering a page which has a non-hole after a hole
- encountering a page with non-contiguous blocks

then this code just gives up and calls the buffer_head-based read function.
It does handle a page which has holes at the end - that is a common case:
the end-of-file on blocksize \< PAGE_SIZE setups.

BH_Boundary explanation:

There is a problem.  The mpage read code assembles several pages, gets all
their disk mappings, and then submits them all.  That's fine, but obtaining
the disk mappings may require I/O.  Reads of indirect blocks, for example.

So an mpage read of the first 16 blocks of an ext2 file will cause I/O to be
submitted in the following order:

12 0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16

because the indirect block has to be read to get the mappings of blocks
13,14,15,16.  Obviously, this impacts performance.

So what we do it to allow the filesystem's `get_block()` function to set
BH_Boundary when it maps block 11.  BH_Boundary says: mapping of the block
after this one will require I/O against a block which is probably close to
this one.  So you should push what I/O you have currently accumulated.

This all causes the disk requests to be issued in the correct order.

#### <a id="c-__mpage_writepages"></a>`__mpage_writepages()`

```c
int __mpage_writepages(struct address_space *mapping, struct writeback_control *wbc, get_block_t get_block, int (*write_folio)(struct folio *folio, struct writeback_control *wbc))
```

walk the list of dirty pages of the given address space & `writepage()` all of them

**Parameters**

- `struct address_space *mapping`: address space structure to write
- `struct writeback_control *wbc`: subtract the number of written pages from **\*wbc->nr_to_write**
- `get_block_t get_block`: the filesystem's block mapper function.
- `int (*write_folio)(struct folio *folio, struct writeback_control *wbc)`: handler to call for each folio before calling
  `mpage_write_folio()`

**Description**

This is a library function, which implements the `writepages()`
address_space_operation. It calls **write_folio** handler for each folio. If
the handler returns value > 0, it calls `mpage_write_folio()` to do the
folio writeback.



#### <a id="c-generic_permission"></a>`generic_permission()`

```c
int generic_permission(struct mnt_idmap *idmap, struct inode *inode, int mask)
```

check for access rights on a Posix-like filesystem

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *inode`: inode to check access rights for
- `int mask`: right to check for (`MAY_READ`, `MAY_WRITE`, `MAY_EXEC`,
  `MAY_NOT_BLOCK` ...)

**Description**

Used to check for read/write/execute permissions on a file.
We use "fsuid" for this, letting us set arbitrary permissions
for filesystem access without changing the "normal" uids which
are used for other things.

generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk
request cannot be satisfied (eg. requires blocking or too much complexity).
It would then be called again in ref-walk mode.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-inode_permission"></a>`inode_permission()`

```c
int inode_permission(struct mnt_idmap *idmap, struct inode *inode, int mask)
```

Check for access rights to a given inode

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *inode`: Inode to check permission on
- `int mask`: Right to check for (`MAY_READ`, `MAY_WRITE`, `MAY_EXEC`)

**Description**

Check for read/write/execute permissions on an inode.  We use fs\[ug\]id for
this, letting us set arbitrary permissions for filesystem access without
changing the "normal" UIDs which are used for other things.

When checking for MAY_APPEND, MAY_WRITE must also be set in **mask**.

#### <a id="c-path_get"></a>`path_get()`

```c
void path_get(const struct path *path)
```

get a reference to a path

**Parameters**

- `const struct path *path`: path to get the reference to

**Description**

Given a path increment the reference count to the dentry and the vfsmount.

#### <a id="c-path_put"></a>`path_put()`

```c
void path_put(const struct path *path)
```

put a reference to a path

**Parameters**

- `const struct path *path`: path to put the reference to

**Description**

Given a path decrement the reference count to the dentry and the vfsmount.

#### <a id="c-end_dirop"></a>`end_dirop()`

```c
void end_dirop(struct dentry *de)
```

signal completion of a dirop

**Parameters**

- `struct dentry *de`: the dentry which was returned by start_dirop or similar.

**Description**

If the de is an error, nothing happens. Otherwise any lock taken to
protect the dentry is dropped and the dentry itself is release (`dput()`).

#### <a id="c-vfs_path_lookup"></a>`vfs_path_lookup()`

```c
int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path)
```

lookup a file path relative to a dentry-vfsmount pair

**Parameters**

- `struct dentry *dentry`: pointer to dentry of the base directory
- `struct vfsmount *mnt`: pointer to vfs mount of the base directory
- `const char *name`: pointer to file name
- `unsigned int flags`: lookup flags
- `struct path *path`: pointer to struct path to fill

#### <a id="c-try_lookup_noperm"></a>`try_lookup_noperm()`

```c
struct dentry * try_lookup_noperm(struct qstr *name, struct dentry *base)
```

filesystem helper to lookup single pathname component

**Parameters**

- `struct qstr *name`: qstr storing pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

Look up a dentry by name in the dcache, returning NULL if it does not
currently exist.  The function does not try to create a dentry and if one
is found it doesn't try to revalidate it.

Note that this routine is purely a helper for filesystem usage and should
not be called by generic code.  It does no permission checking.

No locks need be held - only a counted reference to **base** is needed.

#### <a id="c-lookup_noperm"></a>`lookup_noperm()`

```c
struct dentry * lookup_noperm(struct qstr *name, struct dentry *base)
```

filesystem helper to lookup single pathname component

**Parameters**

- `struct qstr *name`: qstr storing pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

Note that this routine is purely a helper for filesystem usage and should
not be called by generic code.  It does no permission checking.

The caller must hold base->i_rwsem.

#### <a id="c-lookup_one"></a>`lookup_one()`

```c
struct dentry * lookup_one(struct mnt_idmap *idmap, struct qstr *name, struct dentry *base)
```

lookup single pathname component

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the lookup is performed from
- `struct qstr *name`: qstr holding pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

This can be used for in-kernel filesystem clients such as file servers.

The caller must hold base->i_rwsem.

#### <a id="c-lookup_one_unlocked"></a>`lookup_one_unlocked()`

```c
struct dentry * lookup_one_unlocked(struct mnt_idmap *idmap, struct qstr *name, struct dentry *base)
```

lookup single pathname component

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the lookup is performed from
- `struct qstr *name`: qstr olding pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

This can be used for in-kernel filesystem clients such as file servers.

Unlike lookup_one, it should be called without the parent
i_rwsem held, and will take the i_rwsem itself if necessary.

#### <a id="c-lookup_one_positive_killable"></a>`lookup_one_positive_killable()`

```c
struct dentry * lookup_one_positive_killable(struct mnt_idmap *idmap, struct qstr *name, struct dentry *base)
```

lookup single pathname component

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the lookup is performed from
- `struct qstr *name`: qstr olding pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
known positive or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). This is what most of the users want.

Note that pinned negative with unlocked parent _can_ become positive at any
time, so callers of [`lookup_one_unlocked()`](#c-lookup_one_unlocked) need to be very careful; pinned
positives have >d_inode stable, so this one avoids such problems.

This can be used for in-kernel filesystem clients such as file servers.

It should be called without the parent i_rwsem held, and will take
the i_rwsem itself if necessary.  If a fatal signal is pending or
delivered, it will return `-EINTR` if the lock is needed.

#### <a id="c-lookup_one_positive_unlocked"></a>`lookup_one_positive_unlocked()`

```c
struct dentry * lookup_one_positive_unlocked(struct mnt_idmap *idmap, struct qstr *name, struct dentry *base)
```

lookup single pathname component

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the lookup is performed from
- `struct qstr *name`: qstr holding pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

This helper will yield ERR_PTR(-ENOENT) on negatives. The helper returns
known positive or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR). This is what most of the users want.

Note that pinned negative with unlocked parent _can_ become positive at any
time, so callers of [`lookup_one_unlocked()`](#c-lookup_one_unlocked) need to be very careful; pinned
positives have >d_inode stable, so this one avoids such problems.

This can be used for in-kernel filesystem clients such as file servers.

The helper should be called without i_rwsem held.

#### <a id="c-lookup_noperm_unlocked"></a>`lookup_noperm_unlocked()`

```c
struct dentry * lookup_noperm_unlocked(struct qstr *name, struct dentry *base)
```

filesystem helper to lookup single pathname component

**Parameters**

- `struct qstr *name`: pathname component to lookup
- `struct dentry *base`: base directory to lookup from

**Description**

Note that this routine is purely a helper for filesystem usage and should
not be called by generic code. It does no permission checking.

Unlike [`lookup_noperm()`](#c-lookup_noperm), it should be called without the parent
i_rwsem held, and will take the i_rwsem itself if necessary.

Unlike [`try_lookup_noperm()`](#c-try_lookup_noperm) it *does* revalidate the dentry if it already
existed.

#### <a id="c-start_creating"></a>`start_creating()`

```c
struct dentry * start_creating(struct mnt_idmap *idmap, struct dentry *parent, struct qstr *name)
```

prepare to create a given name with permission checking

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *parent`: directory in which to prepare to create the name
- `struct qstr *name`: the name to be created

**Description**

Locks are taken and a lookup is performed prior to creating
an object in a directory.  Permission checking (MAY_EXEC) is performed
against **idmap**.

If the name already exists, a positive dentry is returned, so
behaviour is similar to O_CREAT without O_EXCL, which doesn't fail
with -EEXIST.

**Return**

a negative or positive dentry, or an error.

#### <a id="c-start_removing"></a>`start_removing()`

```c
struct dentry * start_removing(struct mnt_idmap *idmap, struct dentry *parent, struct qstr *name)
```

prepare to remove a given name with permission checking

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *parent`: directory in which to find the name
- `struct qstr *name`: the name to be removed

**Description**

Locks are taken and a lookup in performed prior to removing
an object from a directory.  Permission checking (MAY_EXEC) is performed
against **idmap**.

If the name doesn't exist, an error is returned.

`end_removing()` should be called when removal is complete, or aborted.

**Return**

a positive dentry, or an error.

#### <a id="c-start_creating_killable"></a>`start_creating_killable()`

```c
struct dentry * start_creating_killable(struct mnt_idmap *idmap, struct dentry *parent, struct qstr *name)
```

prepare to create a given name with permission checking

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *parent`: directory in which to prepare to create the name
- `struct qstr *name`: the name to be created

**Description**

Locks are taken and a lookup in performed prior to creating
an object in a directory.  Permission checking (MAY_EXEC) is performed
against **idmap**.

If the name already exists, a positive dentry is returned.

If a signal is received or was already pending, the function aborts
with -EINTR;

**Return**

a negative or positive dentry, or an error.

#### <a id="c-start_removing_killable"></a>`start_removing_killable()`

```c
struct dentry * start_removing_killable(struct mnt_idmap *idmap, struct dentry *parent, struct qstr *name)
```

prepare to remove a given name with permission checking

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *parent`: directory in which to find the name
- `struct qstr *name`: the name to be removed

**Description**

Locks are taken and a lookup in performed prior to removing
an object from a directory.  Permission checking (MAY_EXEC) is performed
against **idmap**.

If the name doesn't exist, an error is returned.

`end_removing()` should be called when removal is complete, or aborted.

If a signal is received or was already pending, the function aborts
with -EINTR;

**Return**

a positive dentry, or an error.

#### <a id="c-start_creating_noperm"></a>`start_creating_noperm()`

```c
struct dentry * start_creating_noperm(struct dentry *parent, struct qstr *name)
```

prepare to create a given name without permission checking

**Parameters**

- `struct dentry *parent`: directory in which to prepare to create the name
- `struct qstr *name`: the name to be created

**Description**

Locks are taken and a lookup in performed prior to creating
an object in a directory.

If the name already exists, a positive dentry is returned.

**Return**

a negative or positive dentry, or an error.

#### <a id="c-start_removing_noperm"></a>`start_removing_noperm()`

```c
struct dentry * start_removing_noperm(struct dentry *parent, struct qstr *name)
```

prepare to remove a given name without permission checking

**Parameters**

- `struct dentry *parent`: directory in which to find the name
- `struct qstr *name`: the name to be removed

**Description**

Locks are taken and a lookup in performed prior to removing
an object from a directory.

If the name doesn't exist, an error is returned.

`end_removing()` should be called when removal is complete, or aborted.

**Return**

a positive dentry, or an error.

#### <a id="c-start_creating_dentry"></a>`start_creating_dentry()`

```c
struct dentry * start_creating_dentry(struct dentry *parent, struct dentry *child)
```

prepare to create a given dentry

**Parameters**

- `struct dentry *parent`: directory from which dentry should be removed
- `struct dentry *child`: the dentry to be removed

**Description**

A lock is taken to protect the dentry again other dirops and
the validity of the dentry is checked: correct parent and still hashed.

If the dentry is valid and negative a reference is taken and
returned.  If not an error is returned.

`end_creating()` should be called when creation is complete, or aborted.

**Return**

the valid dentry, or an error.

#### <a id="c-start_removing_dentry"></a>`start_removing_dentry()`

```c
struct dentry * start_removing_dentry(struct dentry *parent, struct dentry *child)
```

prepare to remove a given dentry

**Parameters**

- `struct dentry *parent`: directory from which dentry should be removed
- `struct dentry *child`: the dentry to be removed

**Description**

A lock is taken to protect the dentry again other dirops and
the validity of the dentry is checked: correct parent and still hashed.

If the dentry is valid and positive, a reference is taken and
returned.  If not an error is returned.

`end_removing()` should be called when removal is complete, or aborted.

**Return**

the valid dentry, or an error.

#### <a id="c-start_renaming"></a>`start_renaming()`

```c
int start_renaming(struct renamedata *rd, int lookup_flags, struct qstr *old_last, struct qstr *new_last)
```

lookup and lock names for rename with permission checking

**Parameters**

- `struct renamedata *rd`: rename data containing parents and flags, and
  for receiving found dentries
- `int lookup_flags`: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
  LOOKUP_NO_SYMLINKS etc).
- `struct qstr *old_last`: name of object in **rd.old_parent**
- `struct qstr *new_last`: name of object in **rd.new_parent**

**Description**

Look up two names and ensure locks are in place for
rename.

On success the found dentries are stored in **rd.old_dentry**,
**rd.new_dentry**.  Also the refcount on **rd->old_parent** is increased.
These references and the lock are dropped by `end_renaming()`.

The passed in qstrs need not have the hash calculated, and basic
eXecute permission checking is performed against **rd.mnt_idmap**.

**Return**

zero or an error.

#### <a id="c-start_renaming_dentry"></a>`start_renaming_dentry()`

```c
int start_renaming_dentry(struct renamedata *rd, int lookup_flags, struct dentry *old_dentry, struct qstr *new_last)
```

lookup and lock name for rename with permission checking

**Parameters**

- `struct renamedata *rd`: rename data containing parents and flags, and
  for receiving found dentries
- `int lookup_flags`: extra flags to pass to ->lookup (e.g. LOOKUP_REVAL,
  LOOKUP_NO_SYMLINKS etc).
- `struct dentry *old_dentry`: dentry of name to move
- `struct qstr *new_last`: name of target in **rd.new_parent**

**Description**

Look up target name and ensure locks are in place for
rename.

On success the found dentry is stored in **rd.new_dentry** and
**rd.old_parent** is confirmed to be the parent of **old_dentry**.  If it
was originally `NULL`, it is set.  In either case a reference is taken
so that `end_renaming()` can have a stable reference to unlock.

References and the lock can be dropped with `end_renaming()`

The passed in qstr need not have the hash calculated, and basic
eXecute permission checking is performed against **rd.mnt_idmap**.

**Return**

zero or an error.

#### <a id="c-start_renaming_two_dentries"></a>`start_renaming_two_dentries()`

```c
int start_renaming_two_dentries(struct renamedata *rd, struct dentry *old_dentry, struct dentry *new_dentry)
```

Lock to dentries in given parents for rename

**Parameters**

- `struct renamedata *rd`: rename data containing parent
- `struct dentry *old_dentry`: dentry of name to move
- `struct dentry *new_dentry`: dentry to move to

**Description**

Ensure locks are in place for rename and check parentage is still correct.

On success the two dentries are stored in **rd.old_dentry** and
**rd.new_dentry** and **rd.old_parent** and **rd.new_parent** are confirmed to
be the parents of the dentries.

References and the lock can be dropped with `end_renaming()`

**Return**

zero or an error.

#### <a id="c-vfs_create"></a>`vfs_create()`

```c
int vfs_create(struct mnt_idmap *idmap, struct dentry *dentry, umode_t mode, struct delegated_inode *di)
```

create new file

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct dentry *dentry`: dentry of the child file
- `umode_t mode`: mode of the child file
- `struct delegated_inode *di`: returns parent inode, if the inode is delegated.

**Description**

Create a new file.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-kernel_tmpfile_open"></a>`kernel_tmpfile_open()`

```c
struct file * kernel_tmpfile_open(struct mnt_idmap *idmap, const struct path *parentpath, umode_t mode, int open_flag, const struct cred *cred)
```

open a tmpfile for kernel internal use

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `const struct path *parentpath`: path of the base directory
- `umode_t mode`: mode of the new tmpfile
- `int open_flag`: flags
- `const struct cred *cred`: credentials for open

**Description**

Create and open a temporary file.  The file is not accounted in nr_files,
hence this is only for kernel internal use, and must not be installed into
file tables or such.

#### <a id="c-end_creating_path"></a>`end_creating_path()`

```c
void end_creating_path(const struct path *path, struct dentry *dentry)
```

finish a code section started by `start_creating_path()`

**Parameters**

- `const struct path *path`: the path instantiated by `start_creating_path()`
- `struct dentry *dentry`: the dentry returned by `start_creating_path()`

**Description**

[`end_creating_path()`](#c-end_creating_path) will unlock and locks taken by `start_creating_path()`
and drop an references that were taken.  It should only be called
if `start_creating_path()` returned a non-error.
If [`vfs_mkdir()`](#c-vfs_mkdir) was called and it returned an error, that error *should*
be passed to [`end_creating_path()`](#c-end_creating_path) together with the path.

#### <a id="c-dentry_create"></a>`dentry_create()`

```c
struct file * dentry_create(struct path *path, int flags, umode_t mode, const struct cred *cred)
```

Create and open a file

**Parameters**

- `struct path *path`: path to create
- `int flags`: O\_ flags
- `umode_t mode`: mode bits for new file
- `const struct cred *cred`: credentials to use

**Description**

Caller must hold the parent directory's lock, and have prepared
a negative dentry, placed in **path->dentry**, for the new file.

Caller sets **path->mnt** to the vfsmount of the filesystem where
the new file is to be created. The parent directory and the
negative dentry must reside on the same filesystem instance.

On success, returns a `struct file *`. Otherwise an ERR_PTR
is returned.

#### <a id="c-vfs_mknod"></a>`vfs_mknod()`

```c
int vfs_mknod(struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev, struct delegated_inode *delegated_inode)
```

create device node or file

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *dir`: inode of the parent directory
- `struct dentry *dentry`: dentry of the child device node
- `umode_t mode`: mode of the child device node
- `dev_t dev`: device number of device to create
- `struct delegated_inode *delegated_inode`: returns parent inode, if the inode is delegated.

**Description**

Create a device node or file.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-vfs_mkdir"></a>`vfs_mkdir()`

```c
struct dentry * vfs_mkdir(struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, umode_t mode, struct delegated_inode *delegated_inode)
```

create directory returning correct dentry if possible

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *dir`: inode of the parent directory
- `struct dentry *dentry`: dentry of the child directory
- `umode_t mode`: mode of the child directory
- `struct delegated_inode *delegated_inode`: returns parent inode, if the inode is delegated.

**Description**

Create a directory.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

In the event that the filesystem does not use the **\*dentry** but leaves it
negative or unhashes it and possibly splices a different one returning it,
the original dentry is `dput()` and the alternate is returned.

In case of an error the dentry is `dput()` and an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) is returned.

#### <a id="c-vfs_rmdir"></a>`vfs_rmdir()`

```c
int vfs_rmdir(struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, struct delegated_inode *delegated_inode)
```

remove directory

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *dir`: inode of the parent directory
- `struct dentry *dentry`: dentry of the child directory
- `struct delegated_inode *delegated_inode`: returns parent inode, if it's delegated.

**Description**

Remove a directory.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-vfs_unlink"></a>`vfs_unlink()`

```c
int vfs_unlink(struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, struct delegated_inode *delegated_inode)
```

unlink a filesystem object

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *dir`: parent directory
- `struct dentry *dentry`: victim
- `struct delegated_inode *delegated_inode`: returns victim inode, if the inode is delegated.

**Description**

The caller must hold dir->i_rwsem exclusively.

If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and
return a reference to the inode in delegated_inode.  The caller
should then break the delegation on that inode and retry.  Because
breaking a delegation may take a long time, the caller should drop
dir->i_rwsem before doing so.

Alternatively, a caller may pass NULL for delegated_inode.  This may
be appropriate for callers that expect the underlying filesystem not
to be NFS exported.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-vfs_symlink"></a>`vfs_symlink()`

```c
int vfs_symlink(struct mnt_idmap *idmap, struct inode *dir, struct dentry *dentry, const char *oldname, struct delegated_inode *delegated_inode)
```

create symlink

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *dir`: inode of the parent directory
- `struct dentry *dentry`: dentry of the child symlink file
- `const char *oldname`: name of the file to link to
- `struct delegated_inode *delegated_inode`: returns victim inode, if the inode is delegated.

**Description**

Create a symlink.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-vfs_link"></a>`vfs_link()`

```c
int vfs_link(struct dentry *old_dentry, struct mnt_idmap *idmap, struct inode *dir, struct dentry *new_dentry, struct delegated_inode *delegated_inode)
```

create a new link

**Parameters**

- `struct dentry *old_dentry`: object to be linked
- `struct mnt_idmap *idmap`: idmap of the mount
- `struct inode *dir`: new parent
- `struct dentry *new_dentry`: where to create the new link
- `struct delegated_inode *delegated_inode`: returns inode needing a delegation break

**Description**

The caller must hold dir->i_rwsem exclusively.

If vfs_link discovers a delegation on the to-be-linked file in need
of breaking, it will return -EWOULDBLOCK and return a reference to the
inode in delegated_inode.  The caller should then break the delegation
and retry.  Because breaking a delegation may take a long time, the
caller should drop the i_rwsem before doing so.

Alternatively, a caller may pass NULL for delegated_inode.  This may
be appropriate for callers that expect the underlying filesystem not
to be NFS exported.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then take
care to map the inode according to **idmap** before checking permissions.
On non-idmapped mounts or if permission checking is to be performed on the
raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-vfs_rename"></a>`vfs_rename()`

```c
int vfs_rename(struct renamedata *rd)
```

rename a filesystem object

**Parameters**

- `struct renamedata *rd`: pointer to [`struct renamedata`](#c-struct-renamedata) info

**Description**

The caller must hold multiple mutexes--see `lock_rename()`).

If vfs_rename discovers a delegation in need of breaking at either
the source or destination, it will return -EWOULDBLOCK and return a
reference to the inode in delegated_inode.  The caller should then
break the delegation and retry.  Because breaking a delegation may
take a long time, the caller should drop all locks before doing
so.

Alternatively, a caller may pass NULL for delegated_inode.  This may
be appropriate for callers that expect the underlying filesystem not
to be NFS exported.

The worst of all namespace operations - renaming directory. "Perverted"
doesn't even start to describe it. Somebody in UCB had a heck of a trip...
Problems:

a) we can get into loop creation.
b) race potential - two innocent renames can create a loop together.
That's where 4.4BSD screws up. Current fix: serialization on
sb->s_vfs_rename_mutex. We might be more accurate, but that's another
story.
c) we may have to lock up to _four_ objects - parents and victim (if it exists),
and source (if it's a non-directory or a subdirectory that moves to
different parent).
And that - after we got ->i_rwsem on parents (until then we don't know
whether the target exists).  Solution: try to be smart with locking
order for inodes.  We rely on the fact that tree topology may change
only under ->s_vfs_rename_mutex _and_ that parent of the object we
move will be locked.  Thus we can rank directories by the tree
(ancestors first) and rank all non-directories after them.
That works since everybody except rename does "lock parent, lookup,
lock child" and rename is under ->s_vfs_rename_mutex.
HOWEVER, it relies on the assumption that any object with ->`lookup()`
has no more than 1 dentry.  If "hybrid" objects will ever appear,
we'd better make sure that there's no link(2) for them.
d) conversion from fhandle to dentry may come in the wrong moment - when
we are removing the target. Solution: we will have to grab ->i_rwsem
in the fhandle_to_dentry code. \[FIXME - current nfsfh.c relies on
->i_rwsem on parents, which works but leads to some truly excessive
locking\].

#### <a id="c-vfs_readlink"></a>`vfs_readlink()`

```c
int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen)
```

copy symlink body into userspace buffer

**Parameters**

- `struct dentry *dentry`: dentry on which to get symbolic link
- `char __user *buffer`: user memory pointer
- `int buflen`: size of buffer

**Description**

Does not touch atime.  That's up to the caller if necessary

Does not call security hook.

#### <a id="c-vfs_get_link"></a>`vfs_get_link()`

```c
const char * vfs_get_link(struct dentry *dentry, struct delayed_call *done)
```

get symlink body

**Parameters**

- `struct dentry *dentry`: dentry on which to get symbolic link
- `struct delayed_call *done`: caller needs to free returned data with this

**Description**

Calls security hook and i_op->`get_link()` on the supplied inode.

It does not touch atime.  That's up to the caller if necessary.

Does not work on "special" symlinks like /proc/$$/fd/N

#### <a id="c-page_get_link"></a>`page_get_link()`

```c
const char * page_get_link(struct dentry *dentry, struct inode *inode, struct delayed_call *callback)
```

An implementation of the get_link inode_operation.

**Parameters**

- `struct dentry *dentry`: The directory entry which is the symlink.
- `struct inode *inode`: The inode for the symlink.
- `struct delayed_call *callback`: Used to drop the reference to the symlink.

**Description**

Filesystems which store their symlinks in the page cache should use
this to implement the `get_link()` member of their inode_operations.

**Return**

A pointer to the NUL-terminated symlink.

#### <a id="c-page_put_link"></a>`page_put_link()`

```c
void page_put_link(void *arg)
```

Drop the reference to the symlink.

**Parameters**

- `void *arg`: The folio which contains the symlink.

**Description**

This is used internally by [`page_get_link()`](#c-page_get_link).  It is exported for use
by filesystems which need to implement a variant of [`page_get_link()`](#c-page_get_link)
themselves.  Despite the apparent symmetry, filesystems which use
[`page_get_link()`](#c-page_get_link) do not need to call [`page_put_link()`](#c-page_put_link).

The argument, while it has a void pointer type, must be a pointer to
the folio which was retrieved from the page cache.  The delayed_call
infrastructure is used to drop the reference count once the caller
is done with the symlink.



#### <a id="c-finish_open"></a>`finish_open()`

```c
int finish_open(struct file *file, struct dentry *dentry, int (*open)(struct inode *, struct file *))
```

finish opening a file

**Parameters**

- `struct file *file`: file pointer
- `struct dentry *dentry`: pointer to dentry
- `int (*open)(struct inode *, struct file *)`: open callback

**Description**

This can be used to finish opening a file passed to i_op->`atomic_open()`.

If the open callback is set to NULL, then the standard f_op->`open()`
filesystem callback is substituted.

NB: the dentry reference is _not_ consumed.  If, for example, the dentry is
the return value of [`d_splice_alias()`](#c-d_splice_alias), then the caller needs to perform `dput()`
on it after [`finish_open()`](#c-finish_open).

Returns zero on success or -errno if the open failed.

#### <a id="c-finish_no_open"></a>`finish_no_open()`

```c
int finish_no_open(struct file *file, struct dentry *dentry)
```

finish ->`atomic_open()` without opening the file

**Parameters**

- `struct file *file`: file pointer
- `struct dentry *dentry`: dentry, ERR_PTR(-E...) or NULL (as returned from ->`lookup()`)

**Description**

This can be used to set the result of a lookup in ->`atomic_open()`.

NB: unlike [`finish_open()`](#c-finish_open) this function does consume the dentry reference and
the caller need not `dput()` it.

Returns 0 or -E..., which must be the return value of ->`atomic_open()` after
having called this function.

#### <a id="c-kernel_file_open"></a>`kernel_file_open()`

```c
struct file * kernel_file_open(const struct path *path, int flags, const struct cred *cred)
```

open a file for kernel internal use

**Parameters**

- `const struct path *path`: path of the file to open
- `int flags`: open flags
- `const struct cred *cred`: credentials for open

**Description**

Open a file for use by in-kernel consumers. The file is not accounted
against nr_files and must not be installed into the file descriptor
table.

**Return**

Opened file on success, an error pointer on failure.

#### <a id="c-filp_open"></a>`filp_open()`

```c
struct file * filp_open(const char *filename, int flags, umode_t mode)
```

open file and return file pointer

**Parameters**

- `const char *filename`: path to open
- `int flags`: open flags as per the open(2) second argument
- `umode_t mode`: mode for the new file if O_CREAT is set, else ignored

**Description**

This is the helper to open a file from kernelspace if you really
have to.  But in generally you should not do this, so please move
along, nothing to see here..



#### <a id="c-bio_reset"></a>`bio_reset()`

```c
void bio_reset(struct bio *bio, struct block_device *bdev, blk_opf_t opf)
```

reinitialize a bio

**Parameters**

- `struct bio *bio`: bio to reset
- `struct block_device *bdev`: block device to use the bio for
- `blk_opf_t opf`: operation and flags for bio

**Description**

After calling [`bio_reset()`](#c-bio_reset), **bio** will be in the same state as a freshly
allocated bio returned bio [`bio_alloc_bioset()`](#c-bio_alloc_bioset) - the only fields that are
preserved are the ones that are initialized by [`bio_alloc_bioset()`](#c-bio_alloc_bioset). See
comment in struct bio.

#### <a id="c-bio_reuse"></a>`bio_reuse()`

```c
void bio_reuse(struct bio *bio, blk_opf_t opf)
```

reuse a bio with the payload left intact

**Parameters**

- `struct bio *bio`: bio to reuse
- `blk_opf_t opf`: operation and flags for the next I/O

**Description**

Allow reusing an existing bio for another operation with all set up
fields including the payload, device and end_io handler left intact.

Typically used when **bio** is first used to read data which is then written
to another location without modification.  **bio** must not be in-flight and
owned by the caller.  Can't be used for cloned bios.

**Note**

Can't be used when **bio** has integrity or blk-crypto contexts for now.
Feel free to add that support when you need it, though.

#### <a id="c-bio_chain"></a>`bio_chain()`

```c
void bio_chain(struct bio *bio, struct bio *parent)
```

chain bio completions

**Parameters**

- `struct bio *bio`: the target bio
- `struct bio *parent`: the parent bio of **bio**

**Description**

The caller won't have a bi_end_io called when **bio** completes - instead,
**parent**'s bi_end_io won't be called until both **parent** and **bio** have
completed; the chained bio will also be freed when it completes.

The caller must not set bi_private or bi_end_io in **bio**.

#### <a id="c-bio_alloc_bioset"></a>`bio_alloc_bioset()`

```c
struct bio * bio_alloc_bioset(struct block_device *bdev, unsigned short nr_vecs, blk_opf_t opf, gfp_t gfp_mask, struct bio_set *bs)
```

allocate a bio for I/O

**Parameters**

- `struct block_device *bdev`: block device to allocate the bio for (can be `NULL`)
- `unsigned short nr_vecs`: number of bvecs to pre-allocate
- `blk_opf_t opf`: operation and flags for bio
- `gfp_t gfp_mask`: the GFP_* mask given to the slab allocator
- `struct bio_set *bs`: the bio_set to allocate from.

**Description**

Allocate a bio from the mempools in **bs**.

If `__GFP_DIRECT_RECLAIM` is set then bio_alloc will always be able to
allocate a bio.  This is due to the mempool guarantees.  To make this work,
callers must never allocate more than 1 bio at a time from the general pool.
Callers that need to allocate more than 1 bio must always submit the
previously allocated bio for IO before attempting to allocate a new one.
Failure to do so can cause deadlocks under memory pressure.

Note that when running under [`submit_bio_noacct()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio_noacct) (i.e. any block driver),
bios are not submitted until after you return - see the code in
[`submit_bio_noacct()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio_noacct) that converts recursion into iteration, to prevent
stack overflows.

This would normally mean allocating multiple bios under [`submit_bio_noacct()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio_noacct)
would be susceptible to deadlocks, but we have
deadlock avoidance code that resubmits any blocked bios from a rescuer
thread.

However, we do not guarantee forward progress for allocations from other
mempools. Doing multiple allocations from the same mempool under
[`submit_bio_noacct()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio_noacct) should be avoided - instead, use bio_set's front_pad
for per bio allocations.

**Return**

Pointer to new bio on success, NULL on failure.

#### <a id="c-bio_kmalloc"></a>`bio_kmalloc()`

```c
struct bio * bio_kmalloc(unsigned short nr_vecs, gfp_t gfp_mask)
```

kmalloc a bio

**Parameters**

- `unsigned short nr_vecs`: number of bio_vecs to allocate
- `gfp_t gfp_mask`: the GFP_* mask given to the slab allocator

**Description**

Use kmalloc to allocate a bio (including bvecs).  The bio must be initialized
using `bio_init()` before use.  To free a bio returned from this function use
[`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree) after calling `bio_uninit()`.  A bio returned from this function can
be reused by calling `bio_uninit()` before calling `bio_init()` again.

Note that unlike `bio_alloc()` or [`bio_alloc_bioset()`](#c-bio_alloc_bioset) allocations from this
function are not backed by a mempool can fail.  Do not use this function
for allocations in the file system I/O path.

**Return**

Pointer to new bio on success, NULL on failure.

#### <a id="c-bio_put"></a>`bio_put()`

```c
void bio_put(struct bio *bio)
```

release a reference to a bio

**Parameters**

- `struct bio *bio`: bio to release reference to

**Description**

Put a reference to a `struct bio`, either one you have gotten with
bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it.

#### <a id="c-bio_alloc_clone"></a>`bio_alloc_clone()`

```c
struct bio * bio_alloc_clone(struct block_device *bdev, struct bio *bio_src, gfp_t gfp, struct bio_set *bs)
```

clone a bio that shares the original bio's biovec

**Parameters**

- `struct block_device *bdev`: block_device to clone onto
- `struct bio *bio_src`: bio to clone from
- `gfp_t gfp`: allocation priority
- `struct bio_set *bs`: bio_set to allocate from

**Description**

Allocate a new bio that is a clone of **bio_src**. The caller owns the returned
bio, but not the actual data it points to.

The caller must ensure that the return bio is not freed before **bio_src**.

#### <a id="c-bio_init_clone"></a>`bio_init_clone()`

```c
int bio_init_clone(struct block_device *bdev, struct bio *bio, struct bio *bio_src, gfp_t gfp)
```

clone a bio that shares the original bio's biovec

**Parameters**

- `struct block_device *bdev`: block_device to clone onto
- `struct bio *bio`: bio to clone into
- `struct bio *bio_src`: bio to clone from
- `gfp_t gfp`: allocation priority

**Description**

Initialize a new bio in caller provided memory that is a clone of **bio_src**.
The caller owns the returned bio, but not the actual data it points to.

The caller must ensure that **bio_src** is not freed before **bio**.

#### <a id="c-__bio_add_page"></a>`__bio_add_page()`

```c
void __bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int off)
```

add page(s) to a bio in a new segment

**Parameters**

- `struct bio *bio`: destination bio
- `struct page *page`: start page to add
- `unsigned int len`: length of the data to add, may cross pages
- `unsigned int off`: offset of the data relative to **page**, may cross pages

**Description**

Add the data at **page** + **off** to **bio** as a new bvec.  The caller must ensure
that **bio** has space for another bvec.

#### <a id="c-bio_add_virt_nofail"></a>`bio_add_virt_nofail()`

```c
void bio_add_virt_nofail(struct bio *bio, void *vaddr, unsigned len)
```

add data in the direct kernel mapping to a bio

**Parameters**

- `struct bio *bio`: destination bio
- `void *vaddr`: data to add
- `unsigned len`: length of the data to add, may cross pages

**Description**

Add the data at **vaddr** to **bio**.  The caller must have ensure a segment
is available for the added data.  No merging into an existing segment
will be performed.

#### <a id="c-bio_add_page"></a>`bio_add_page()`

```c
int bio_add_page(struct bio *bio, struct page *page, unsigned int len, unsigned int offset)
```

attempt to add page(s) to bio

**Parameters**

- `struct bio *bio`: destination bio
- `struct page *page`: start page to add
- `unsigned int len`: vec entry length, may cross pages
- `unsigned int offset`: vec entry offset relative to **page**, may cross pages

**Description**

Attempt to add page(s) to the bio_vec maplist. This will only fail
if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio.

#### <a id="c-bio_add_folio"></a>`bio_add_folio()`

```c
bool bio_add_folio(struct bio *bio, struct folio *folio, size_t len, size_t off)
```

Attempt to add part of a folio to a bio.

**Parameters**

- `struct bio *bio`: BIO to add to.
- `struct folio *folio`: Folio to add.
- `size_t len`: How many bytes from the folio to add.
- `size_t off`: First byte in this folio to add.

**Description**

Filesystems that use folios can call this function instead of calling
[`bio_add_page()`](#c-bio_add_page) for each page in the folio.  If **off** is bigger than
PAGE_SIZE, this function can create a bio_vec that starts in a page
after the bv_page.  BIOs do not support folios that are 4GiB or larger.

**Return**

Whether the addition was successful.

#### <a id="c-bio_add_vmalloc_chunk"></a>`bio_add_vmalloc_chunk()`

```c
unsigned int bio_add_vmalloc_chunk(struct bio *bio, void *vaddr, unsigned len)
```

add a vmalloc chunk to a bio

**Parameters**

- `struct bio *bio`: destination bio
- `void *vaddr`: vmalloc address to add
- `unsigned len`: total length in bytes of the data to add

**Description**

Add data starting at **vaddr** to **bio** and return how many bytes were added.
This may be less than the amount originally asked.  Returns 0 if no data
could be added to **bio**.

This helper calls `flush_kernel_vmap_range()` for the range added.  For reads
the caller still needs to manually call `invalidate_kernel_vmap_range()` in
the completion handler.

#### <a id="c-bio_add_vmalloc"></a>`bio_add_vmalloc()`

```c
bool bio_add_vmalloc(struct bio *bio, void *vaddr, unsigned int len)
```

add a vmalloc region to a bio

**Parameters**

- `struct bio *bio`: destination bio
- `void *vaddr`: vmalloc address to add
- `unsigned int len`: total length in bytes of the data to add

**Description**

Add data starting at **vaddr** to **bio**.  Return `true` on success or `false` if
**bio** does not have enough space for the payload.

This helper calls `flush_kernel_vmap_range()` for the range added.  For reads
the caller still needs to manually call `invalidate_kernel_vmap_range()` in
the completion handler.

#### <a id="c-submit_bio_wait"></a>`submit_bio_wait()`

```c
int submit_bio_wait(struct bio *bio)
```

submit a bio, and wait until it completes

**Parameters**

- `struct bio *bio`: The `struct bio` which describes the I/O

**Description**

Simple wrapper around [`submit_bio()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio). Returns 0 on success, or the error from
[`bio_endio()`](#c-bio_endio) on failure.

WARNING: Unlike to how [`submit_bio()`](/kernel/internals/core-api/kernel-api.md#c-submit_bio) is usually used, this function does not
result in bio reference to be consumed. The caller must drop the reference
on his own.

#### <a id="c-bdev_rw_virt"></a>`bdev_rw_virt()`

```c
int bdev_rw_virt(struct block_device *bdev, sector_t sector, void *data, size_t len, enum req_op op)
```

synchronously read into / write from kernel mapping

**Parameters**

- `struct block_device *bdev`: block device to access
- `sector_t sector`: sector to access
- `void *data`: data to read/write
- `size_t len`: length in byte to read/write
- `enum req_op op`: operation (e.g. REQ_OP_READ/REQ_OP_WRITE)

**Description**

Performs synchronous I/O to **bdev** for **data**/**len**.  **data** must be in
the kernel direct mapping and not a vmalloc address.

#### <a id="c-bio_copy_data"></a>`bio_copy_data()`

```c
void bio_copy_data(struct bio *dst, struct bio *src)
```

copy contents of data buffers from one bio to another

**Parameters**

- `struct bio *dst`: destination bio
- `struct bio *src`: source bio

**Description**

Stops when it reaches the end of either **src** or **dst** - that is, copies
min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios).

#### <a id="c-bio_endio"></a>`bio_endio()`

```c
void bio_endio(struct bio *bio)
```

end I/O on a bio

**Parameters**

- `struct bio *bio`: bio

**Description**

[`bio_endio()`](#c-bio_endio) will end I/O on the whole bio. [`bio_endio()`](#c-bio_endio) is the preferred
way to end I/O on a bio. No one should call `bi_end_io()` directly on a
bio unless they own it and thus know that it has an end_io function.

[`bio_endio()`](#c-bio_endio) can be called several times on a bio that has been chained
using [`bio_chain()`](#c-bio_chain).  The ->`bi_end_io()` function will only be called the
last time.

#### <a id="c-bio_split"></a>`bio_split()`

```c
struct bio * bio_split(struct bio *bio, int sectors, gfp_t gfp, struct bio_set *bs)
```

split a bio

**Parameters**

- `struct bio *bio`: bio to split
- `int sectors`: number of sectors to split from the front of **bio**
- `gfp_t gfp`: gfp mask
- `struct bio_set *bs`: bio set to allocate from

**Description**

Allocates and returns a new bio which represents **sectors** from the start of
**bio**, and updates **bio** to represent the remaining sectors.

Unless this is a discard request the newly allocated bio will point
to **bio**'s bi_io_vec. It is the caller's responsibility to ensure that
neither **bio** nor **bs** are freed before the split bio.

#### <a id="c-bio_trim"></a>`bio_trim()`

```c
void bio_trim(struct bio *bio, sector_t offset, sector_t size)
```

trim a bio

**Parameters**

- `struct bio *bio`: bio to trim
- `sector_t offset`: number of sectors to trim from the front of **bio**
- `sector_t size`: size we want to trim **bio** to, in sectors

**Description**

This function is typically used for bios that are cloned and submitted
to the underlying device in parts.

#### <a id="c-bioset_init"></a>`bioset_init()`

```c
int bioset_init(struct bio_set *bs, unsigned int pool_size, unsigned int front_pad, int flags)
```

Initialize a bio_set

**Parameters**

- `struct bio_set *bs`: pool to initialize
- `unsigned int pool_size`: Number of bio and bio_vecs to cache in the mempool
- `unsigned int front_pad`: Number of bytes to allocate in front of the returned bio
- `int flags`: Flags to modify behavior, currently `BIOSET_NEED_BVECS`
  and `BIOSET_NEED_RESCUER`

**Description**

Set up a bio_set to be used with **bio_alloc_bioset**. Allows the caller
to ask for a number of bytes to be allocated in front of the bio.
Front pad allocation is useful for embedding the bio inside
another structure, to avoid allocating extra data to go with the bio.
Note that the bio must be embedded at the END of that structure always,
or things will break badly.
If `BIOSET_NEED_BVECS` is set in **flags**, a separate pool will be allocated
for allocating iovecs.  This pool is not needed e.g. for [`bio_init_clone()`](#c-bio_init_clone).
If `BIOSET_NEED_RESCUER` is set, a workqueue is created which can be used
to dispatch queued requests when the mempool runs out of space.



#### <a id="c-seq_open"></a>`seq_open()`

```c
int seq_open(struct file *file, const struct seq_operations *op)
```

initialize sequential file

**Parameters**

- `struct file *file`: file we initialize
- `const struct seq_operations *op`: method table describing the sequence

**Description**

[`seq_open()`](#c-seq_open) sets **file**, associating it with a sequence described
by **op**.  **op->start()** sets the iterator up and returns the first
element of sequence. **op->stop()** shuts it down.  **op->next()**
returns the next element of sequence.  **op->show()** prints element
into the buffer.  In case of error ->`start()` and ->`next()` return
ERR_PTR(error).  In the end of sequence they return `NULL`. ->`show()`
returns 0 in case of success and negative number in case of error.
Returning SEQ_SKIP means "discard this element and move on".

**Note**

- [`seq_open()`](#c-seq_open) will allocate a struct seq_file and store its

  pointer in **file->private_data**. This pointer should not be modified.

#### <a id="c-seq_read"></a>`seq_read()`

```c
ssize_t seq_read(struct file *file, char __user *buf, size_t size, loff_t *ppos)
```

->`read()` method for sequential files.

**Parameters**

- `struct file *file`: the file to read from
- `char __user *buf`: the buffer to read to
- `size_t size`: the maximum number of bytes to read
- `loff_t *ppos`: the current position in the file

**Description**

Ready-made ->f_op->`read()`

#### <a id="c-seq_lseek"></a>`seq_lseek()`

```c
loff_t seq_lseek(struct file *file, loff_t offset, int whence)
```

->`llseek()` method for sequential files.

**Parameters**

- `struct file *file`: the file in question
- `loff_t offset`: new position
- `int whence`: 0 for absolute, 1 for relative position

**Description**

Ready-made ->f_op->`llseek()`

#### <a id="c-seq_release"></a>`seq_release()`

```c
int seq_release(struct inode *inode, struct file *file)
```

free the structures associated with sequential file.

**Parameters**

- `struct inode *inode`: its inode
- `struct file *file`: file in question

**Description**

Frees the structures associated with sequential file; can be used
as ->f_op->`release()` if you don't have private data to destroy.

#### <a id="c-seq_escape_mem"></a>`seq_escape_mem()`

```c
void seq_escape_mem(struct seq_file *m, const char *src, size_t len, unsigned int flags, const char *esc)
```

print data into buffer, escaping some characters

**Parameters**

- `struct seq_file *m`: target buffer
- `const char *src`: source buffer
- `size_t len`: size of source buffer
- `unsigned int flags`: flags to pass to [`string_escape_mem()`](/kernel/internals/core-api/kernel-api.md#c-string_escape_mem)
- `const char *esc`: set of characters that need escaping

**Description**

Puts data into buffer, replacing each occurrence of character from
given class (defined by **flags** and **esc**) with printable escaped sequence.

Use `seq_has_overflowed()` to check for errors.

#### <a id="c-mangle_path"></a>`mangle_path()`

```c
char * mangle_path(char *s, const char *p, const char *esc)
```

mangle and copy path to buffer beginning

**Parameters**

- `char *s`: buffer start
- `const char *p`: beginning of path in above buffer
- `const char *esc`: set of characters that need escaping

**Description**

Copy the path from **p** to **s**, replacing each occurrence of character from
**esc** with usual octal escape.
Returns pointer past last written character in **s**, or NULL in case of
failure.

#### <a id="c-seq_path"></a>`seq_path()`

```c
int seq_path(struct seq_file *m, const struct path *path, const char *esc)
```

seq_file interface to print a pathname

**Parameters**

- `struct seq_file *m`: the seq_file handle
- `const struct path *path`: the struct path to print
- `const char *esc`: set of characters to escape in the output

**Description**

return the absolute path of 'path', as represented by the
dentry / mnt pair in the path parameter.

#### <a id="c-seq_file_path"></a>`seq_file_path()`

```c
int seq_file_path(struct seq_file *m, struct file *file, const char *esc)
```

seq_file interface to print a pathname of a file

**Parameters**

- `struct seq_file *m`: the seq_file handle
- `struct file *file`: the struct file to print
- `const char *esc`: set of characters to escape in the output

**Description**

return the absolute path to the file.

#### <a id="c-seq_write"></a>`seq_write()`

```c
int seq_write(struct seq_file *seq, const void *data, size_t len)
```

write arbitrary data to buffer

**Parameters**

- `struct seq_file *seq`: seq_file identifying the buffer to which data should be written
- `const void *data`: data address
- `size_t len`: number of bytes

**Description**

Return 0 on success, non-zero otherwise.

#### <a id="c-seq_pad"></a>`seq_pad()`

```c
void seq_pad(struct seq_file *m, char c)
```

write padding spaces to buffer

**Parameters**

- `struct seq_file *m`: seq_file identifying the buffer to which data should be written
- `char c`: the byte to append after padding if non-zero

#### <a id="c-seq_hlist_start"></a>`seq_hlist_start()`

```c
struct hlist_node * seq_hlist_start(struct hlist_head *head, loff_t pos)
```

start an iteration of a hlist

**Parameters**

- `struct hlist_head *head`: the head of the hlist
- `loff_t pos`: the start position of the sequence

**Description**

Called at seq_file->op->`start()`.

#### <a id="c-seq_hlist_start_head"></a>`seq_hlist_start_head()`

```c
struct hlist_node * seq_hlist_start_head(struct hlist_head *head, loff_t pos)
```

start an iteration of a hlist

**Parameters**

- `struct hlist_head *head`: the head of the hlist
- `loff_t pos`: the start position of the sequence

**Description**

Called at seq_file->op->`start()`. Call this function if you want to
print a header at the top of the output.

#### <a id="c-seq_hlist_next"></a>`seq_hlist_next()`

```c
struct hlist_node * seq_hlist_next(void *v, struct hlist_head *head, loff_t *ppos)
```

move to the next position of the hlist

**Parameters**

- `void *v`: the current iterator
- `struct hlist_head *head`: the head of the hlist
- `loff_t *ppos`: the current position

**Description**

Called at seq_file->op->`next()`.

#### <a id="c-seq_hlist_start_rcu"></a>`seq_hlist_start_rcu()`

```c
struct hlist_node * seq_hlist_start_rcu(struct hlist_head *head, loff_t pos)
```

start an iteration of a hlist protected by RCU

**Parameters**

- `struct hlist_head *head`: the head of the hlist
- `loff_t pos`: the start position of the sequence

**Description**

Called at seq_file->op->`start()`.

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](/kernel/internals/core-api/kernel-api.md#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock).

#### <a id="c-seq_hlist_start_head_rcu"></a>`seq_hlist_start_head_rcu()`

```c
struct hlist_node * seq_hlist_start_head_rcu(struct hlist_head *head, loff_t pos)
```

start an iteration of a hlist protected by RCU

**Parameters**

- `struct hlist_head *head`: the head of the hlist
- `loff_t pos`: the start position of the sequence

**Description**

Called at seq_file->op->`start()`. Call this function if you want to
print a header at the top of the output.

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](/kernel/internals/core-api/kernel-api.md#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock).

#### <a id="c-seq_hlist_next_rcu"></a>`seq_hlist_next_rcu()`

```c
struct hlist_node * seq_hlist_next_rcu(void *v, struct hlist_head *head, loff_t *ppos)
```

move to the next position of the hlist protected by RCU

**Parameters**

- `void *v`: the current iterator
- `struct hlist_head *head`: the head of the hlist
- `loff_t *ppos`: the current position

**Description**

Called at seq_file->op->`next()`.

This list-traversal primitive may safely run concurrently with
the _rcu list-mutation primitives such as [`hlist_add_head_rcu()`](/kernel/internals/core-api/kernel-api.md#c-hlist_add_head_rcu)
as long as the traversal is guarded by [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock).

#### <a id="c-seq_hlist_start_percpu"></a>`seq_hlist_start_percpu()`

```c
struct hlist_node * seq_hlist_start_percpu(struct hlist_head __percpu *head, int *cpu, loff_t pos)
```

start an iteration of a percpu hlist array

**Parameters**

- `struct hlist_head __percpu *head`: pointer to percpu array of struct hlist_heads
- `int *cpu`: pointer to cpu "cursor"
- `loff_t pos`: start position of sequence

**Description**

Called at seq_file->op->`start()`.

#### <a id="c-seq_hlist_next_percpu"></a>`seq_hlist_next_percpu()`

```c
struct hlist_node * seq_hlist_next_percpu(void *v, struct hlist_head __percpu *head, int *cpu, loff_t *pos)
```

move to the next position of the percpu hlist array

**Parameters**

- `void *v`: pointer to current hlist_node
- `struct hlist_head __percpu *head`: pointer to percpu array of struct hlist_heads
- `int *cpu`: pointer to cpu "cursor"
- `loff_t *pos`: start position of sequence

**Description**

Called at seq_file->op->`next()`.



#### <a id="c-register_filesystem"></a>`register_filesystem()`

```c
int register_filesystem(struct file_system_type * fs)
```

register a new filesystem

**Parameters**

- `struct file_system_type * fs`: the file system structure

**Description**

Adds the file system passed to the list of file systems the kernel
is aware of for mount and other syscalls. Returns 0 on success,
or a negative errno code on an error.

The `struct file_system_type` that is passed is linked into the kernel
structures and must not be freed until the file system has been
unregistered.

#### <a id="c-unregister_filesystem"></a>`unregister_filesystem()`

```c
int unregister_filesystem(struct file_system_type * fs)
```

unregister a file system

**Parameters**

- `struct file_system_type * fs`: filesystem to unregister

**Description**

Remove a file system that was previously successfully registered
with the kernel. An error is returned if the file system is not found.
Zero is returned on a success.

Once this function has returned the `struct file_system_type` structure
may be freed or reused.



#### <a id="c-wbc_attach_fdatawrite_inode"></a>`wbc_attach_fdatawrite_inode()`

```c
void wbc_attach_fdatawrite_inode(struct writeback_control *wbc, struct inode *inode)
```

associate wbc and inode for fdatawrite

**Parameters**

- `struct writeback_control *wbc`: writeback_control of interest
- `struct inode *inode`: target inode

**Description**

This function is to be used by `filemap_writeback()`, which is an alternative
entry point into writeback code, and first ensures **inode** is associated with
a bdi_writeback and attaches it to **wbc**.

#### <a id="c-wbc_detach_inode"></a>`wbc_detach_inode()`

```c
void wbc_detach_inode(struct writeback_control *wbc)
```

disassociate wbc from inode and perform foreign detection

**Parameters**

- `struct writeback_control *wbc`: writeback_control of the just finished writeback

**Description**

To be called after a writeback attempt of an inode finishes and undoes
`wbc_attach_and_unlock_inode()`.  Can be called under any context.

As concurrent write sharing of an inode is expected to be very rare and
memcg only tracks page ownership on first-use basis severely confining
the usefulness of such sharing, cgroup writeback tracks ownership
per-inode.  While the support for concurrent write sharing of an inode
is deemed unnecessary, an inode being written to by different cgroups at
different points in time is a lot more common, and, more importantly,
charging only by first-use can too readily lead to grossly incorrect
behaviors (single foreign page can lead to gigabytes of writeback to be
incorrectly attributed).

To resolve this issue, cgroup writeback detects the majority dirtier of
an inode and transfers the ownership to it.  To avoid unnecessary
oscillation, the detection mechanism keeps track of history and gives
out the switch verdict only if the foreign usage pattern is stable over
a certain amount of time and/or writeback attempts.

On each writeback attempt, **wbc** tries to detect the majority writer
using Boyer-Moore majority vote algorithm.  In addition to the byte
count from the majority voting, it also counts the bytes written for the
current wb and the last round's winner wb (max of last round's current
wb, the winner from two rounds ago, and the last round's majority
candidate).  Keeping track of the historical winner helps the algorithm
to semi-reliably detect the most active writer even when it's not the
absolute majority.

Once the winner of the round is determined, whether the winner is
foreign or not and how much IO time the round consumed is recorded in
inode->i_wb_frn_history.  If the amount of recorded foreign IO time is
over a certain threshold, the switch verdict is given.

#### <a id="c-wbc_account_cgroup_owner"></a>`wbc_account_cgroup_owner()`

```c
void wbc_account_cgroup_owner(struct writeback_control *wbc, struct folio *folio, size_t bytes)
```

account writeback to update inode cgroup ownership

**Parameters**

- `struct writeback_control *wbc`: writeback_control of the writeback in progress
- `struct folio *folio`: folio being written out
- `size_t bytes`: number of bytes being written out

**Description**

**bytes** from **folio** are about to written out during the writeback
controlled by **wbc**.  Keep the book for foreign inode detection.  See
[`wbc_detach_inode()`](#c-wbc_detach_inode).

#### <a id="c-__mark_inode_dirty"></a>`__mark_inode_dirty()`

```c
void __mark_inode_dirty(struct inode *inode, int flags)
```

internal function to mark an inode dirty

**Parameters**

- `struct inode *inode`: inode to mark
- `int flags`: what kind of dirty, e.g. I_DIRTY_SYNC.  This can be a combination of
  multiple I_DIRTY_* flags, except that I_DIRTY_TIME can't be combined
  with I_DIRTY_PAGES.

**Description**

Mark an inode as dirty.  We notify the filesystem, then update the inode's
dirty flags.  Then, if needed we add the inode to the appropriate dirty list.

Most callers should use `mark_inode_dirty()` or `mark_inode_dirty_sync()`
instead of calling this directly.

CAREFUL!  We only add the inode to the dirty list if it is hashed or if it
refers to a blockdev.  Unhashed inodes will never be added to the dirty list
even if they are later hashed, as they will have been marked dirty already.

In short, ensure you hash any inodes _before_ you start marking them dirty.

Note that for blockdevs, inode->dirtied_when represents the dirtying time of
the block-special inode (/dev/hda1) itself.  And the ->dirtied_when field of
the kernel-internal blockdev inode represents the dirtying time of the
blockdev's pages.  This is why for I_DIRTY_PAGES we always use
page->mapping->host, so the page-dirtying time is recorded in the internal
blockdev inode.

#### <a id="c-writeback_inodes_sb_nr"></a>`writeback_inodes_sb_nr()`

```c
void writeback_inodes_sb_nr(struct super_block *sb, unsigned long nr, enum wb_reason reason)
```

writeback dirty inodes from given super_block

**Parameters**

- `struct super_block *sb`: the superblock
- `unsigned long nr`: the number of pages to write
- `enum wb_reason reason`: reason why some writeback work initiated

**Description**

Start writeback on some inodes on this super_block. No guarantees are made
on how many (if any) will be written, and this function does not wait
for IO completion of submitted IO.

#### <a id="c-writeback_inodes_sb"></a>`writeback_inodes_sb()`

```c
void writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
```

writeback dirty inodes from given super_block

**Parameters**

- `struct super_block *sb`: the superblock
- `enum wb_reason reason`: reason why some writeback work was initiated

**Description**

Start writeback on some inodes on this super_block. No guarantees are made
on how many (if any) will be written, and this function does not wait
for IO completion of submitted IO.

#### <a id="c-try_to_writeback_inodes_sb"></a>`try_to_writeback_inodes_sb()`

```c
void try_to_writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
```

try to start writeback if none underway

**Parameters**

- `struct super_block *sb`: the superblock
- `enum wb_reason reason`: reason why some writeback work was initiated

**Description**

Invoke __writeback_inodes_sb_nr if no writeback is currently underway.

#### <a id="c-sync_inodes_sb"></a>`sync_inodes_sb()`

```c
void sync_inodes_sb(struct super_block *sb)
```

sync sb inode pages

**Parameters**

- `struct super_block *sb`: the superblock

**Description**

This function writes and waits on any dirty inode belonging to this
super_block.

#### <a id="c-write_inode_now"></a>`write_inode_now()`

```c
int write_inode_now(struct inode *inode, int sync)
```

write an inode to disk

**Parameters**

- `struct inode *inode`: inode to write to disk
- `int sync`: whether the write should be synchronous or not

**Description**

This function commits an inode to disk immediately if it is dirty. This is
primarily needed by knfsd.

The caller must either have a ref on the inode or must have set I_WILL_FREE.

#### <a id="c-sync_inode_metadata"></a>`sync_inode_metadata()`

```c
int sync_inode_metadata(struct inode *inode, int wait)
```

write an inode to disk

**Parameters**

- `struct inode *inode`: the inode to sync
- `int wait`: wait for I/O to complete.

**Description**

Write an inode to disk and adjust its dirty state after completion.

**Note**

only writes the actual inode, no associated data or other metadata.



#### <a id="c-anon_inode_getfile"></a>`anon_inode_getfile()`

```c
struct file * anon_inode_getfile(const char *name, const struct file_operations *fops, void *priv, int flags)
```

creates a new file instance by hooking it up to an anonymous inode, and a dentry that describe the "class" of the file

**Parameters**

- `const char *name`: \[in\]    name of the "class" of the new file
- `const struct file_operations *fops`: \[in\]    file operations for the new file
- `void *priv`: \[in\]    private data for the new file (will be file's private_data)
- `int flags`: \[in\]    flags

**Description**

Creates a new file by hooking it on a single inode. This is useful for files
that do not need to have a full-fledged inode in order to operate correctly.
All the files created with [`anon_inode_getfile()`](#c-anon_inode_getfile) will share a single inode,
hence saving memory and avoiding code duplication for the file/inode/dentry
setup.  Returns the newly created file* or an error pointer.

#### <a id="c-anon_inode_getfile_fmode"></a>`anon_inode_getfile_fmode()`

```c
struct file * anon_inode_getfile_fmode(const char *name, const struct file_operations *fops, void *priv, int flags, fmode_t f_mode)
```

creates a new file instance by hooking it up to an anonymous inode, and a dentry that describe the "class" of the file

**Parameters**

- `const char *name`: \[in\]    name of the "class" of the new file
- `const struct file_operations *fops`: \[in\]    file operations for the new file
- `void *priv`: \[in\]    private data for the new file (will be file's private_data)
- `int flags`: \[in\]    flags
- `fmode_t f_mode`: \[in\]    fmode

**Description**

Creates a new file by hooking it on a single inode. This is useful for files
that do not need to have a full-fledged inode in order to operate correctly.
All the files created with [`anon_inode_getfile()`](#c-anon_inode_getfile) will share a single inode,
hence saving memory and avoiding code duplication for the file/inode/dentry
setup. Allows setting the fmode. Returns the newly created file* or an error
pointer.

#### <a id="c-anon_inode_create_getfile"></a>`anon_inode_create_getfile()`

```c
struct file * anon_inode_create_getfile(const char *name, const struct file_operations *fops, void *priv, int flags, const struct inode *context_inode)
```

Like [`anon_inode_getfile()`](#c-anon_inode_getfile), but creates a new !S_PRIVATE anon inode rather than reuse the singleton anon inode and calls the `inode_init_security_anon()` LSM hook.

**Parameters**

- `const char *name`: \[in\]    name of the "class" of the new file
- `const struct file_operations *fops`: \[in\]    file operations for the new file
- `void *priv`: \[in\]    private data for the new file (will be file's private_data)
- `int flags`: \[in\]    flags
- `const struct inode *context_inode`: \[in\]    the logical relationship with the new inode (optional)

**Description**

Create a new anonymous inode and file pair.  This can be done for two
reasons:

- for the inode to have its own security context, so that LSMs can enforce
  policy on the inode's creation;

- if the caller needs a unique inode, for example in order to customize
  the size returned by `fstat()`

The LSM may use **context_inode** in `inode_init_security_anon()`, but a
reference to it is not held.

Returns the newly created file* or an error pointer.

#### <a id="c-anon_inode_getfd"></a>`anon_inode_getfd()`

```c
int anon_inode_getfd(const char *name, const struct file_operations *fops, void *priv, int flags)
```

creates a new file instance by hooking it up to an anonymous inode and a dentry that describe the "class" of the file

**Parameters**

- `const char *name`: \[in\]    name of the "class" of the new file
- `const struct file_operations *fops`: \[in\]    file operations for the new file
- `void *priv`: \[in\]    private data for the new file (will be file's private_data)
- `int flags`: \[in\]    flags

**Description**

Creates a new file by hooking it on a single inode. This is
useful for files that do not need to have a full-fledged inode in
order to operate correctly.  All the files created with
[`anon_inode_getfd()`](#c-anon_inode_getfd) will use the same singleton inode, reducing
memory use and avoiding code duplication for the file/inode/dentry
setup.  Returns a newly created file descriptor or an error code.



#### <a id="c-setattr_should_drop_sgid"></a>`setattr_should_drop_sgid()`

```c
int setattr_should_drop_sgid(struct mnt_idmap *idmap, const struct inode *inode)
```

determine whether the setgid bit needs to be removed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount **inode** was found from
- `const struct inode *inode`: inode to check

**Description**

This function determines whether the setgid bit needs to be removed.
We retain backwards compatibility and require setgid bit to be removed
unconditionally if S_IXGRP is set. Otherwise we have the exact same
requirements as [`setattr_prepare()`](#c-setattr_prepare) and [`setattr_copy()`](#c-setattr_copy).

**Return**

ATTR_KILL_SGID if setgid bit needs to be removed, 0 otherwise.

#### <a id="c-setattr_should_drop_suidgid"></a>`setattr_should_drop_suidgid()`

```c
int setattr_should_drop_suidgid(struct mnt_idmap *idmap, struct inode *inode)
```

determine whether the set{g,u}id bit needs to be dropped

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount **inode** was found from
- `struct inode *inode`: inode to check

**Description**

This function determines whether the set{g,u}id bits need to be removed.
If the setuid bit needs to be removed ATTR_KILL_SUID is returned. If the
setgid bit needs to be removed ATTR_KILL_SGID is returned. If both
set{g,u}id bits need to be removed the corresponding mask of both flags is
returned.

**Return**

A mask of ATTR_KILL_S{G,U}ID indicating which - if any - setid bits
to remove, 0 otherwise.

#### <a id="c-setattr_prepare"></a>`setattr_prepare()`

```c
int setattr_prepare(struct mnt_idmap *idmap, struct dentry *dentry, struct iattr *attr)
```

check if attribute changes to a dentry are allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct dentry *dentry`: dentry to check
- `struct iattr *attr`: attributes to change

**Description**

Check if we are allowed to change the attributes contained in **attr**
in the given dentry.  This includes the normal unix access permission
checks, as well as checks for rlimits and others. The function also clears
SGID bit from mode if user is not allowed to set it. Also file capabilities
and IMA extended attributes are cleared if ATTR_KILL_PRIV is set.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before checking
permissions. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.

Should be called as the first thing in ->setattr implementations,
possibly after taking additional locks.

#### <a id="c-inode_newsize_ok"></a>`inode_newsize_ok()`

```c
int inode_newsize_ok(const struct inode *inode, loff_t offset)
```

may this inode be truncated to a given size

**Parameters**

- `const struct inode *inode`: the inode to be truncated
- `loff_t offset`: the new size to assign to the inode

**Description**

inode_newsize_ok must be called with i_rwsem held exclusively.

inode_newsize_ok will check filesystem limits and ulimits to check that the
new inode size is within limits. inode_newsize_ok will also send SIGXFSZ
when necessary. Caller must not proceed with inode size change if failure is
returned. **inode** must be a file (not directory), with appropriate
permissions to allow truncate (inode_newsize_ok does NOT check these
conditions).

**Return**

0 on success, -ve errno on failure

#### <a id="c-setattr_copy"></a>`setattr_copy()`

```c
void setattr_copy(struct mnt_idmap *idmap, struct inode *inode, const struct iattr *attr)
```

copy simple metadata updates into the generic inode

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct inode *inode`: the inode to be updated
- `const struct iattr *attr`: the new attributes

**Description**

setattr_copy must be called with i_rwsem held exclusively.

setattr_copy updates the inode's metadata with that specified
in attr on idmapped mounts. Necessary permission checks to determine
whether or not the S_ISGID property needs to be removed are performed with
the correct idmapped mount permission helpers.
Noticeably missing is inode size update, which is more complex
as it requires pagecache updates.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before checking
permissions. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.

The inode is not marked as dirty after this operation. The rationale is
that for "simple" filesystems, the struct inode is the inode storage.
The caller is free to mark the inode dirty afterwards if needed.

#### <a id="c-notify_change"></a>`notify_change()`

```c
int notify_change(struct mnt_idmap *idmap, struct dentry *dentry, struct iattr *attr, struct delegated_inode *delegated_inode)
```

modify attributes of a filesystem object

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `struct dentry *dentry`: object affected
- `struct iattr *attr`: new attributes
- `struct delegated_inode *delegated_inode`: returns inode, if the inode is delegated

**Description**

The caller must hold the i_rwsem exclusively on the affected object.

If notify_change discovers a delegation in need of breaking,
it will return -EWOULDBLOCK and return a reference to the inode in
delegated_inode.  The caller should then break the delegation and
retry.  Because breaking a delegation may take a long time, the
caller should drop the i_rwsem before doing so.

Alternatively, a caller may pass NULL for delegated_inode.  This may
be appropriate for callers that expect the underlying filesystem not
to be NFS exported.  Also, passing NULL is fine for callers holding
the file open for write, as there can be no conflicting delegation in
that case.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before checking
permissions. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.



#### <a id="c-d_path"></a>`d_path()`

```c
char * d_path(const struct path *path, char *buf, int buflen)
```

return the path of a dentry

**Parameters**

- `const struct path *path`: path to report
- `char *buf`: buffer to return value in
- `int buflen`: buffer length

**Description**

Convert a dentry into an ASCII path name. If the entry has been deleted
the string " (deleted)" is appended. Note that this is ambiguous.

Returns a pointer into the buffer or an error code if the path was
too long. Note: Callers should use the returned pointer, not the passed
in buffer, to use the name! The implementation often starts at an offset
into the buffer, and may leave 0 bytes at the start.

"buflen" should be positive.



#### <a id="c-dax_layout_busy_page_range"></a>`dax_layout_busy_page_range()`

```c
struct page * dax_layout_busy_page_range(struct address_space *mapping, loff_t start, loff_t end)
```

find first pinned page in **mapping**

**Parameters**

- `struct address_space *mapping`: address space to scan for a page with ref count > 1
- `loff_t start`: Starting offset. Page containing 'start' is included.
- `loff_t end`: End offset. Page containing 'end' is included. If 'end' is LLONG_MAX,
  pages from 'start' till the end of file are included.

**Description**

DAX requires ZONE_DEVICE mapped pages. These pages are never
'onlined' to the page allocator so they are considered idle when
page->count == 1. A filesystem uses this interface to determine if
any page in the mapping is busy, i.e. for DMA, or other
`get_user_pages()` usages.

It is expected that the filesystem is holding locks to block the
establishment of new mappings in this address_space. I.e. it expects
to be able to run [`unmap_mapping_range()`](/kernel/internals/core-api/mm-api.md#c-unmap_mapping_range) and subsequently not race
`mapping_mapped()` becoming true.

#### <a id="c-dax_iomap_rw"></a>`dax_iomap_rw()`

```c
ssize_t dax_iomap_rw(struct kiocb *iocb, struct iov_iter *iter, const struct iomap_ops *ops)
```

Perform I/O to a DAX file

**Parameters**

- `struct kiocb *iocb`: The control block for this I/O
- `struct iov_iter *iter`: The addresses to do I/O from or to
- `const struct iomap_ops *ops`: iomap ops passed from the file system

**Description**

This function performs read and write operations to directly mapped
persistent memory.  The callers needs to take care of read/write exclusion
and evicting any page cache pages in the region under I/O.

#### <a id="c-dax_iomap_fault"></a>`dax_iomap_fault()`

```c
vm_fault_t dax_iomap_fault(struct vm_fault *vmf, unsigned int order, unsigned long *pfnp, int *iomap_errp, const struct iomap_ops *ops)
```

handle a page fault on a DAX file

**Parameters**

- `struct vm_fault *vmf`: The description of the fault
- `unsigned int order`: Order of the page to fault in
- `unsigned long *pfnp`: PFN to insert for synchronous faults if fsync is required
- `int *iomap_errp`: Storage for detailed error code in case of error
- `const struct iomap_ops *ops`: Iomap ops passed from the file system

**Description**

When a page fault occurs, filesystems may call this helper in
their fault handler for DAX files. [`dax_iomap_fault()`](#c-dax_iomap_fault) assumes the caller
has done all the necessary locking for page fault to proceed
successfully.

#### <a id="c-dax_finish_sync_fault"></a>`dax_finish_sync_fault()`

```c
vm_fault_t dax_finish_sync_fault(struct vm_fault *vmf, unsigned int order, unsigned long pfn)
```

finish synchronous page fault

**Parameters**

- `struct vm_fault *vmf`: The description of the fault
- `unsigned int order`: Order of entry to be inserted
- `unsigned long pfn`: PFN to insert

**Description**

This function ensures that the file range touched by the page fault is
stored persistently on the media and handles inserting of appropriate page
table entry.



#### <a id="c-simple_rename_timestamp"></a>`simple_rename_timestamp()`

```c
void simple_rename_timestamp(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry)
```

update the various inode timestamps for rename

**Parameters**

- `struct inode *old_dir`: old parent directory
- `struct dentry *old_dentry`: dentry that is being renamed
- `struct inode *new_dir`: new parent directory
- `struct dentry *new_dentry`: target for rename

**Description**

POSIX mandates that the old and new parent directories have their ctime and
mtime updated, and that inodes of **old_dentry** and **new_dentry** (if any), have
their ctime updated.

#### <a id="c-simple_setattr"></a>`simple_setattr()`

```c
int simple_setattr(struct mnt_idmap *idmap, struct dentry *dentry, struct iattr *iattr)
```

setattr for simple filesystem

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the target mount
- `struct dentry *dentry`: dentry
- `struct iattr *iattr`: iattr structure

**Description**

Returns 0 on success, -error on failure.

simple_setattr is a simple ->setattr implementation without a proper
implementation of size changes.

It can either be used for in-memory filesystems or special files
on simple regular filesystems.  Anything that needs to change on-disk
or wire state on size changes needs its own setattr method.

#### <a id="c-simple_read_from_buffer"></a>`simple_read_from_buffer()`

```c
ssize_t simple_read_from_buffer(void __user *to, size_t count, loff_t *ppos, const void *from, size_t available)
```

copy data from the buffer to user space

**Parameters**

- `void __user *to`: the user space buffer to read to
- `size_t count`: the maximum number of bytes to read
- `loff_t *ppos`: the current position in the buffer
- `const void *from`: the buffer to read from
- `size_t available`: the size of the buffer

**Description**

The [`simple_read_from_buffer()`](#c-simple_read_from_buffer) function reads up to **count** bytes from the
buffer **from** at offset **ppos** into the user space address starting at **to**.

On success, the number of bytes read is returned and the offset **ppos** is
advanced by this number, or negative value is returned on error.

#### <a id="c-simple_write_to_buffer"></a>`simple_write_to_buffer()`

```c
ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos, const void __user *from, size_t count)
```

copy data from user space to the buffer

**Parameters**

- `void *to`: the buffer to write to
- `size_t available`: the size of the buffer
- `loff_t *ppos`: the current position in the buffer
- `const void __user *from`: the user space buffer to read from
- `size_t count`: the maximum number of bytes to read

**Description**

The [`simple_write_to_buffer()`](#c-simple_write_to_buffer) function reads up to **count** bytes from the user
space address starting at **from** into the buffer **to** at offset **ppos**.

On success, the number of bytes written is returned and the offset **ppos** is
advanced by this number, or negative value is returned on error.

#### <a id="c-memory_read_from_buffer"></a>`memory_read_from_buffer()`

```c
ssize_t memory_read_from_buffer(void *to, size_t count, loff_t *ppos, const void *from, size_t available)
```

copy data from the buffer

**Parameters**

- `void *to`: the kernel space buffer to read to
- `size_t count`: the maximum number of bytes to read
- `loff_t *ppos`: the current position in the buffer
- `const void *from`: the buffer to read from
- `size_t available`: the size of the buffer

**Description**

The [`memory_read_from_buffer()`](#c-memory_read_from_buffer) function reads up to **count** bytes from the
buffer **from** at offset **ppos** into the kernel space address starting at **to**.

On success, the number of bytes read is returned and the offset **ppos** is
advanced by this number, or negative value is returned on error.

#### <a id="c-generic_encode_ino32_fh"></a>`generic_encode_ino32_fh()`

```c
int generic_encode_ino32_fh(struct inode *inode, __u32 *fh, int *max_len, struct inode *parent)
```

generic export_operations->encode_fh function

**Parameters**

- `struct inode *inode`: the object to encode
- `__u32 *fh`: where to store the file handle fragment
- `int *max_len`: maximum length to store there (in 4 byte units)
- `struct inode *parent`: parent directory inode, if wanted

**Description**

This generic encode_fh function assumes that the 32 inode number
is suitable for locating an inode, and that the generation number
can be used to check that it is still valid.  It places them in the
filehandle fragment where export_decode_fh expects to find them.

#### <a id="c-generic_fh_to_dentry"></a>`generic_fh_to_dentry()`

```c
struct dentry * generic_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type, struct inode *(*get_inode) (struct super_block *sb, u64 ino, u32 gen))
```

generic helper for the fh_to_dentry export operation

**Parameters**

- `struct super_block *sb`: filesystem to do the file handle conversion on
- `struct fid *fid`: file handle to convert
- `int fh_len`: length of the file handle in bytes
- `int fh_type`: type of file handle
- `struct inode *(*get_inode) (struct super_block *sb, u64 ino, u32 gen)`: filesystem callback to retrieve inode

**Description**

This function decodes **fid** as long as it has one of the well-known
Linux filehandle types and calls **get_inode** on it to retrieve the
inode for the object specified in the file handle.

#### <a id="c-generic_fh_to_parent"></a>`generic_fh_to_parent()`

```c
struct dentry * generic_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type, struct inode *(*get_inode) (struct super_block *sb, u64 ino, u32 gen))
```

generic helper for the fh_to_parent export operation

**Parameters**

- `struct super_block *sb`: filesystem to do the file handle conversion on
- `struct fid *fid`: file handle to convert
- `int fh_len`: length of the file handle in bytes
- `int fh_type`: type of file handle
- `struct inode *(*get_inode) (struct super_block *sb, u64 ino, u32 gen)`: filesystem callback to retrieve inode

**Description**

This function decodes **fid** as long as it has one of the well-known
Linux filehandle types and calls **get_inode** on it to retrieve the
inode for the _parent_ object specified in the file handle if it
is specified in the file handle, or NULL otherwise.

#### <a id="c-__generic_file_fsync"></a>`__generic_file_fsync()`

```c
int __generic_file_fsync(struct file *file, loff_t start, loff_t end, int datasync)
```

generic fsync implementation for simple filesystems

**Parameters**

- `struct file *file`: file to synchronize
- `loff_t start`: start offset in bytes
- `loff_t end`: end offset in bytes (inclusive)
- `int datasync`: only synchronize essential metadata if true

**Description**

This is a generic implementation of the fsync method for simple
filesystems which track all non-inode metadata in the buffers list
hanging off the address_space structure.

#### <a id="c-generic_file_fsync"></a>`generic_file_fsync()`

```c
int generic_file_fsync(struct file *file, loff_t start, loff_t end, int datasync)
```

generic fsync implementation for simple filesystems with flush

**Parameters**

- `struct file *file`: file to synchronize
- `loff_t start`: start offset in bytes
- `loff_t end`: end offset in bytes (inclusive)
- `int datasync`: only synchronize essential metadata if true

#### <a id="c-generic_check_addressable"></a>`generic_check_addressable()`

```c
int generic_check_addressable(unsigned blocksize_bits, u64 num_blocks)
```

Check addressability of file system

**Parameters**

- `unsigned blocksize_bits`: log of file system block size
- `u64 num_blocks`: number of blocks in file system

**Description**

Determine whether a file system with **num_blocks** blocks (and a
block size of 2***\*blocksize_bits**) is addressable by the sector_t
and page cache of the system.  Return 0 if so and -EFBIG otherwise.

#### <a id="c-simple_get_link"></a>`simple_get_link()`

```c
const char * simple_get_link(struct dentry *dentry, struct inode *inode, struct delayed_call *done)
```

generic helper to get the target of "fast" symlinks

**Parameters**

- `struct dentry *dentry`: not used here
- `struct inode *inode`: the symlink inode
- `struct delayed_call *done`: not used here

**Description**

Generic helper for filesystems to use for symlink inodes where a pointer to
the symlink target is stored in ->i_link.  NOTE: this isn't normally called,
since as an optimization the path lookup code uses any non-NULL ->i_link
directly, without calling ->`get_link()`.  But ->`get_link()` still must be set,
to mark the inode_operations as being for a symlink.

**Return**

the symlink target

#### <a id="c-generic_ci_d_compare"></a>`generic_ci_d_compare()`

```c
int generic_ci_d_compare(const struct dentry *dentry, unsigned int len, const char *str, const struct qstr *name)
```

generic d_compare implementation for casefolding filesystems

**Parameters**

- `const struct dentry *dentry`: dentry whose name we are checking against
- `unsigned int len`: len of name of dentry
- `const char *str`: str pointer to name of dentry
- `const struct qstr *name`: Name to compare against

**Return**

0 if names match, 1 if mismatch, or -ERRNO

#### <a id="c-generic_ci_d_hash"></a>`generic_ci_d_hash()`

```c
int generic_ci_d_hash(const struct dentry *dentry, struct qstr *str)
```

generic d_hash implementation for casefolding filesystems

**Parameters**

- `const struct dentry *dentry`: dentry of the parent directory
- `struct qstr *str`: qstr of name whose hash we should fill in

**Return**

0 if hash was successful or unchanged, and -EINVAL on error

#### <a id="c-generic_ci_match"></a>`generic_ci_match()`

```c
int generic_ci_match(const struct inode *parent, const struct qstr *name, const struct qstr *folded_name, const u8 *de_name, u32 de_name_len)
```

Match a name (case-insensitively) with a dirent. This is a filesystem helper for comparison with directory entries. generic_ci_d_compare should be used in VFS' ->d_compare instead.

**Parameters**

- `const struct inode *parent`: Inode of the parent of the dirent under comparison
- `const struct qstr *name`: name under lookup.
- `const struct qstr *folded_name`: Optional pre-folded name under lookup
- `const u8 *de_name`: Dirent name.
- `u32 de_name_len`: dirent name length.

**Description**

Test whether a case-insensitive directory entry matches the filename
being searched.  If **folded_name** is provided, it is used instead of
recalculating the casefold of **name**.

**Return**

\> 0 if the directory entry matches, 0 if it doesn't match, or
\< 0 on error.

#### <a id="c-generic_set_sb_d_ops"></a>`generic_set_sb_d_ops()`

```c
void generic_set_sb_d_ops(struct super_block *sb)
```

helper for choosing the set of filesystem-wide dentry operations for the enabled features

**Parameters**

- `struct super_block *sb`: superblock to be configured

**Description**

Filesystems supporting casefolding and/or fscrypt can call this
helper at mount-time to configure default dentry_operations to the
best set of dentry operations required for the enabled features.
The helper must be called after these have been configured, but
before the root dentry is created.

#### <a id="c-inode_maybe_inc_iversion"></a>`inode_maybe_inc_iversion()`

```c
bool inode_maybe_inc_iversion(struct inode *inode, bool force)
```

increments i_version

**Parameters**

- `struct inode *inode`: inode with the i_version that should be updated
- `bool force`: increment the counter even if it's not necessary?

**Description**

Every time the inode is modified, the i_version field must be seen to have
changed by any observer.

If "force" is set or the QUERIED flag is set, then ensure that we increment
the value, and clear the queried flag.

In the common case where neither is set, then we can return "false" without
updating i_version.

If this function returns false, and no other metadata has changed, then we
can avoid logging the metadata.

#### <a id="c-inode_query_iversion"></a>`inode_query_iversion()`

```c
u64 inode_query_iversion(struct inode *inode)
```

read i_version for later use

**Parameters**

- `struct inode *inode`: inode from which i_version should be read

**Description**

Read the inode i_version counter. This should be used by callers that wish
to store the returned i_version for later comparison. This will guarantee
that a later query of the i_version will result in a different value if
anything has changed.

In this implementation, we fetch the current value, set the QUERIED flag and
then try to swap it into place with a cmpxchg, if it wasn't already set. If
that fails, we try again with the newly fetched value from the cmpxchg.

#### <a id="c-simple_inode_init_ts"></a>`simple_inode_init_ts()`

```c
struct timespec64 simple_inode_init_ts(struct inode *inode)
```

initialize the timestamps for a new inode

**Parameters**

- `struct inode *inode`: inode to be initialized

**Description**

When a new inode is created, most filesystems set the timestamps to the
current time. Add a helper to do this.

#### <a id="c-simple_start_creating"></a>`simple_start_creating()`

```c
struct dentry * simple_start_creating(struct dentry *parent, const char *name)
```

prepare to create a given name

**Parameters**

- `struct dentry *parent`: directory in which to prepare to create the name
- `const char *name`: the name to be created

**Description**

Required lock is taken and a lookup in performed prior to creating an
object in a directory.  No permission checking is performed.

**Return**

a negative dentry on which [`vfs_create()`](#c-vfs_create) or similar may
be attempted, or an error.



#### <a id="c-posix_acl_chmod"></a>`posix_acl_chmod()`

```c
int  posix_acl_chmod(struct mnt_idmap *idmap, struct dentry *dentry, umode_t mode)
```

chmod a posix acl

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount **inode** was found from
- `struct dentry *dentry`: dentry to check permissions on
- `umode_t mode`: the new mode of **inode**

**Description**

If the dentry has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before checking
permissions. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-posix_acl_update_mode"></a>`posix_acl_update_mode()`

```c
int posix_acl_update_mode(struct mnt_idmap *idmap, struct inode *inode, umode_t *mode_p, struct posix_acl **acl)
```

update mode in set_acl

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount **inode** was found from
- `struct inode *inode`: target inode
- `umode_t *mode_p`: mode (pointer) for update
- `struct posix_acl **acl`: acl pointer

**Description**

Update the file mode when setting an ACL: compute the new file permission
bits based on the ACL.  In addition, if the ACL is equivalent to the new
file mode, set **\*acl** to NULL to indicate that no ACL should be set.

As with chmod, clear the setgid bit if the caller is not in the owning group
or capable of CAP_FSETID (see inode_change_ok).

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before checking
permissions. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.

Called from set_acl inode operations.

#### <a id="c-posix_acl_from_xattr"></a>`posix_acl_from_xattr()`

```c
struct posix_acl * posix_acl_from_xattr(struct user_namespace *userns, const void *value, size_t size)
```

convert POSIX ACLs from backing store to VFS format

**Parameters**

- `struct user_namespace *userns`: the filesystem's idmapping
- `const void *value`: the uapi representation of POSIX ACLs
- `size_t size`: the size of **void**

**Description**

Filesystems that store POSIX ACLs in the unaltered uapi format should use
[`posix_acl_from_xattr()`](#c-posix_acl_from_xattr) when reading them from the backing store and
converting them into the struct posix_acl VFS format. The helper is
specifically intended to be called from the acl inode operation.

The [`posix_acl_from_xattr()`](#c-posix_acl_from_xattr) function will map the raw {g,u}id values stored
in ACL_{GROUP,USER} entries into idmapping in **userns**.

Note that [`posix_acl_from_xattr()`](#c-posix_acl_from_xattr) does not take idmapped mounts into account.
If it did it calling it from the get acl inode operation would return POSIX
ACLs mapped according to an idmapped mount which would mean that the value
couldn't be cached for the filesystem. Idmapped mounts are taken into
account on the fly during permission checking or right at the VFS -
userspace boundary before reporting them to the user.

**Return**

Allocated struct posix_acl on success, NULL for a valid header but
without actual POSIX ACL entries, or [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) encoded error code.

#### <a id="c-vfs_set_acl"></a>`vfs_set_acl()`

```c
int vfs_set_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name, struct posix_acl *kacl)
```

set posix acls

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: the dentry based on which to set the posix acls
- `const char *acl_name`: the name of the posix acl
- `struct posix_acl *kacl`: the posix acls in the appropriate VFS format

**Description**

This function sets **kacl**. The caller must all `posix_acl_release()` on **kacl**
afterwards.

**Return**

On success 0, on error negative errno.

#### <a id="c-vfs_get_acl"></a>`vfs_get_acl()`

```c
struct posix_acl * vfs_get_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name)
```

get posix acls

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: the dentry based on which to retrieve the posix acls
- `const char *acl_name`: the name of the posix acl

**Description**

This function retrieves **kacl** from the filesystem. The caller must all
`posix_acl_release()` on **kacl**.

**Return**

On success POSIX ACLs in VFS format, on error negative errno.

#### <a id="c-vfs_remove_acl"></a>`vfs_remove_acl()`

```c
int vfs_remove_acl(struct mnt_idmap *idmap, struct dentry *dentry, const char *acl_name)
```

remove posix acls

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: the dentry based on which to retrieve the posix acls
- `const char *acl_name`: the name of the posix acl

**Description**

This function removes posix acls.

**Return**

On success 0, on error negative errno.



#### <a id="c-fill_mg_cmtime"></a>`fill_mg_cmtime()`

```c
void fill_mg_cmtime(struct kstat *stat, u32 request_mask, struct inode *inode)
```

Fill in the mtime and ctime and flag ctime as QUERIED

**Parameters**

- `struct kstat *stat`: where to store the resulting values
- `u32 request_mask`: STATX_* values requested
- `struct inode *inode`: inode from which to grab the c/mtime

**Description**

Given **inode**, grab the ctime and mtime out if it and store the result
in **stat**. When fetching the value, flag it as QUERIED (if not already)
so the next write will record a distinct timestamp.

NB: The QUERIED flag is tracked in the ctime, but we set it there even
if only the mtime was requested, as that ensures that the next mtime
change will be distinct.

#### <a id="c-generic_fillattr"></a>`generic_fillattr()`

```c
void generic_fillattr(struct mnt_idmap *idmap, u32 request_mask, struct inode *inode, struct kstat *stat)
```

Fill in the basic attributes from the inode struct

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount the inode was found from
- `u32 request_mask`: statx request_mask
- `struct inode *inode`: Inode to use as the source
- `struct kstat *stat`: Where to fill in the attributes

**Description**

Fill in the basic attributes in the kstat structure from data that's to be
found on the VFS inode structure.  This is the default if no getattr inode
operation is supplied.

If the inode has been found through an idmapped mount the idmap of
the vfsmount must be passed through **idmap**. This function will then
take care to map the inode according to **idmap** before filling in the
uid and gid filds. On non-idmapped mounts or if permission checking is to be
performed on the raw inode simply pass **nop_mnt_idmap**.

#### <a id="c-generic_fill_statx_attr"></a>`generic_fill_statx_attr()`

```c
void generic_fill_statx_attr(struct inode *inode, struct kstat *stat)
```

Fill in the statx attributes from the inode flags

**Parameters**

- `struct inode *inode`: Inode to use as the source
- `struct kstat *stat`: Where to fill in the attribute flags

**Description**

Fill in the STATX_ATTR_* flags in the kstat structure for properties of the
inode that are published on i_flags and enforced by the VFS.

#### <a id="c-generic_fill_statx_atomic_writes"></a>`generic_fill_statx_atomic_writes()`

```c
void generic_fill_statx_atomic_writes(struct kstat *stat, unsigned int unit_min, unsigned int unit_max, unsigned int unit_max_opt)
```

Fill in atomic writes statx attributes

**Parameters**

- `struct kstat *stat`: Where to fill in the attribute flags
- `unsigned int unit_min`: Minimum supported atomic write length in bytes
- `unsigned int unit_max`: Maximum supported atomic write length in bytes
- `unsigned int unit_max_opt`: Optimised maximum supported atomic write length in bytes

**Description**

Fill in the STATX{_ATTR}_WRITE_ATOMIC flags in the kstat structure from
atomic write unit_min and unit_max values.

#### <a id="c-vfs_getattr_nosec"></a>`vfs_getattr_nosec()`

```c
int vfs_getattr_nosec(const struct path *path, struct kstat *stat, u32 request_mask, unsigned int query_flags)
```

getattr without security checks

**Parameters**

- `const struct path *path`: file to get attributes from
- `struct kstat *stat`: structure to return attributes in
- `u32 request_mask`: STATX_xxx flags indicating what the caller wants
- `unsigned int query_flags`: Query mode (AT_STATX_SYNC_TYPE)

**Description**

Get attributes without calling security_inode_getattr.

Currently the only caller other than vfs_getattr is internal to the
filehandle lookup code, which uses only the inode number and returns no
attributes to any user.  Any other code probably wants vfs_getattr.



#### <a id="c-vfs_fsync_range"></a>`vfs_fsync_range()`

```c
int vfs_fsync_range(struct file *file, loff_t start, loff_t end, int datasync)
```

helper to sync a range of data & metadata to disk

**Parameters**

- `struct file *file`: file to sync
- `loff_t start`: offset in bytes of the beginning of data range to sync
- `loff_t end`: offset in bytes of the end of data range (inclusive)
- `int datasync`: perform only datasync

**Description**

Write back data in range **start**..**end** and metadata for **file** to disk.  If
**datasync** is set only metadata needed to access modified file data is
written.

#### <a id="c-vfs_fsync"></a>`vfs_fsync()`

```c
int vfs_fsync(struct file *file, int datasync)
```

perform a fsync or fdatasync on a file

**Parameters**

- `struct file *file`: file to sync
- `int datasync`: only perform a fdatasync operation

**Description**

Write back data and metadata for **file** to disk.  If **datasync** is
set only metadata needed to access modified file data is written.



#### <a id="c-__vfs_setxattr_locked"></a>`__vfs_setxattr_locked()`

```c
int __vfs_setxattr_locked(struct mnt_idmap *idmap, struct dentry *dentry, const char *name, const void *value, size_t size, int flags, struct delegated_inode *delegated_inode)
```

set an extended attribute while holding the inode lock

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount of the target inode
- `struct dentry *dentry`: object to perform setxattr on
- `const char *name`: xattr name to set
- `const void *value`: value to set **name** to
- `size_t size`: size of **value**
- `int flags`: flags to pass into filesystem operations
- `struct delegated_inode *delegated_inode`: on return, will contain an inode pointer that
  a delegation was broken on, NULL if none.

#### <a id="c-vfs_listxattr"></a>`vfs_listxattr()`

```c
ssize_t vfs_listxattr(struct dentry *dentry, char *list, size_t size)
```

retrieve \0 separated list of xattr names

**Parameters**

- `struct dentry *dentry`: the dentry from whose inode the xattr names are retrieved
- `char *list`: buffer to store xattr names into
- `size_t size`: size of the buffer

**Description**

This function returns the names of all xattrs associated with the
inode of **dentry**.

Note, for legacy reasons the [`vfs_listxattr()`](#c-vfs_listxattr) function lists POSIX
ACLs as well. Since POSIX ACLs are decoupled from IOP_XATTR the
[`vfs_listxattr()`](#c-vfs_listxattr) function doesn't check for this flag since a
filesystem could implement POSIX ACLs without implementing any other
xattrs.

However, since all codepaths that remove IOP_XATTR also assign of
inode operations that either don't implement or implement a stub
->`listxattr()` operation.

**Return**

On success, the size of the buffer that was used. On error a
negative error code.

#### <a id="c-__vfs_removexattr_locked"></a>`__vfs_removexattr_locked()`

```c
int __vfs_removexattr_locked(struct mnt_idmap *idmap, struct dentry *dentry, const char *name, struct delegated_inode *delegated_inode)
```

set an extended attribute while holding the inode lock

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount of the target inode
- `struct dentry *dentry`: object to perform setxattr on
- `const char *name`: name of xattr to remove
- `struct delegated_inode *delegated_inode`: on return, will contain an inode pointer that
  a delegation was broken on, NULL if none.

#### <a id="c-generic_listxattr"></a>`generic_listxattr()`

```c
ssize_t generic_listxattr(struct dentry *dentry, char *buffer, size_t buffer_size)
```

run through a dentry's xattr `list()` operations

**Parameters**

- `struct dentry *dentry`: dentry to list the xattrs
- `char *buffer`: result buffer
- `size_t buffer_size`: size of **buffer**

**Description**

Combine the results of the `list()` operation from every xattr_handler in the
xattr_handler stack.

Note that this will not include the entries for POSIX ACLs.

#### <a id="c-xattr_full_name"></a>`xattr_full_name()`

```c
const char * xattr_full_name(const struct xattr_handler *handler, const char *name)
```

Compute full attribute name from suffix

**Parameters**

- `const struct xattr_handler *handler`: handler of the xattr_handler operation
- `const char *name`: name passed to the xattr_handler operation

**Description**

The get and set xattr handler operations are called with the remainder of
the attribute name after skipping the handler's prefix: for example, "foo"
is passed to the get operation of a handler with prefix "user." to get
attribute "user.foo".  The full name is still "there" in the name though.

**Note**

the list xattr handler operation when called from the vfs is passed a
NULL name; some file systems use this operation internally, with varying
semantics.



#### <a id="c-mnt_get_write_access"></a>`mnt_get_write_access()`

```c
int mnt_get_write_access(struct vfsmount *m)
```

get write access to a mount without freeze protection

**Parameters**

- `struct vfsmount *m`: the mount on which to take a write

**Description**

This tells the low-level filesystem that a write is about to be performed to
it, and makes sure that writes are allowed (mnt it read-write) before
returning success. This operation does not protect against filesystem being
frozen. When the write operation is finished, [`mnt_put_write_access()`](#c-mnt_put_write_access) must be
called. This is effectively a refcount.

#### <a id="c-mnt_want_write"></a>`mnt_want_write()`

```c
int mnt_want_write(struct vfsmount *m)
```

get write access to a mount

**Parameters**

- `struct vfsmount *m`: the mount on which to take a write

**Description**

This tells the low-level filesystem that a write is about to be performed to
it, and makes sure that writes are allowed (mount is read-write, filesystem
is not frozen) before returning success.  When the write operation is
finished, [`mnt_drop_write()`](#c-mnt_drop_write) must be called.  This is effectively a refcount.

#### <a id="c-mnt_want_write_file"></a>`mnt_want_write_file()`

```c
int mnt_want_write_file(struct file *file)
```

get write access to a file's mount

**Parameters**

- `struct file *file`: the file who's mount on which to take a write

**Description**

This is like mnt_want_write, but if the file is already open for writing it
skips incrementing mnt_writers (since the open file already has a reference)
and instead only does the freeze protection and the check for emergency r/o
remounts.  This must be paired with mnt_drop_write_file.

#### <a id="c-mnt_put_write_access"></a>`mnt_put_write_access()`

```c
void mnt_put_write_access(struct vfsmount *mnt)
```

give up write access to a mount

**Parameters**

- `struct vfsmount *mnt`: the mount on which to give up write access

**Description**

Tells the low-level filesystem that we are done
performing writes to it.  Must be matched with
[`mnt_get_write_access()`](#c-mnt_get_write_access) call above.

#### <a id="c-mnt_drop_write"></a>`mnt_drop_write()`

```c
void mnt_drop_write(struct vfsmount *mnt)
```

give up write access to a mount

**Parameters**

- `struct vfsmount *mnt`: the mount on which to give up write access

**Description**

Tells the low-level filesystem that we are done performing writes to it and
also allows filesystem to be frozen again.  Must be matched with
[`mnt_want_write()`](#c-mnt_want_write) call above.

#### <a id="c-vfs_create_mount"></a>`vfs_create_mount()`

```c
struct vfsmount * vfs_create_mount(struct fs_context *fc)
```

Create a mount for a configured superblock

**Parameters**

- `struct fs_context *fc`: The configuration context with the superblock attached

**Description**

Create a mount to an already configured superblock.  If necessary, the
caller should invoke [`vfs_get_tree()`](#c-vfs_get_tree) before calling this.

Note that this does not attach the mount to anything.

#### <a id="c-path_is_mountpoint"></a>`path_is_mountpoint()`

```c
bool path_is_mountpoint(const struct path *path)
```

Check if path is a mount in the current namespace.

**Parameters**

- `const struct path *path`: path to check

**Description**

`d_mountpoint()` can only be used reliably to establish if a dentry is
not mounted in any namespace and that common case is handled inline.
`d_mountpoint()` isn't aware of the possibility there may be multiple
mounts using a given dentry in a different namespace. This function
checks if the passed in path is a mountpoint rather than the dentry
alone.

#### <a id="c-may_umount_tree"></a>`may_umount_tree()`

```c
int may_umount_tree(struct vfsmount *m)
```

check if a mount tree is busy

**Parameters**

- `struct vfsmount *m`: root of mount tree

**Description**

This is called to check if a tree of mounts has any
open files, pwds, chroots or sub mounts that are
busy.

#### <a id="c-may_umount"></a>`may_umount()`

```c
int may_umount(struct vfsmount *mnt)
```

check if a mount point is busy

**Parameters**

- `struct vfsmount *mnt`: root of mount

**Description**

This is called to check if a mount point has any
open files, pwds, chroots or sub mounts. If the
mount has sub mounts this will return busy
regardless of whether the sub mounts are busy.

Doesn't take quota and stuff into account. IOW, in some cases it will
give false negatives. The main reason why it's here is that we need
a non-destructive way to look for easily umountable filesystems.

#### <a id="c-clone_private_mount"></a>`clone_private_mount()`

```c
struct vfsmount * clone_private_mount(const struct path *path)
```

create a private clone of a path

**Parameters**

- `const struct path *path`: path to clone

**Description**

This creates a new vfsmount, which will be the clone of **path**.  The new mount
will not be attached anywhere in the namespace and will be private (i.e.
changes to the originating mount won't be propagated into this).

This assumes caller has called or done the equivalent of `may_mount()`.

Release with `mntput()`.

#### <a id="c-mnt_set_expiry"></a>`mnt_set_expiry()`

```c
void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list)
```

Put a mount on an expiration list

**Parameters**

- `struct vfsmount *mnt`: The mount to list.
- `struct list_head *expiry_list`: The list to add the mount to.


<a id="rst-the-proc-filesystem"></a>

## The proc filesystem

<a id="rst-sysctl-interface"></a>

### sysctl interface


#### <a id="c-proc_dostring"></a>`proc_dostring()`

```c
int proc_dostring(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a string sysctl

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes a string from/to the user buffer. If the kernel
buffer provided is not large enough to hold the string, the
string is truncated. The copied string is `NULL-terminated`.
If the string is being read by the user process, it is copied
and a newline '\n' is added. It is truncated if the buffer is
not large enough.

Returns 0 on success.

#### <a id="c-proc_dobool"></a>`proc_dobool()`

```c
int proc_dobool(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read/write a bool

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes one integer value from/to the user buffer,
treated as an ASCII string.

table->data must point to a bool variable and table->maxlen must
be sizeof(bool).

Returns 0 on success.

#### <a id="c-proc_dointvec"></a>`proc_dointvec()`

```c
int proc_dointvec(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of integers

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(unsigned int) integer
values from/to the user buffer, treated as an ASCII string.

Returns 0 on success.

#### <a id="c-proc_douintvec"></a>`proc_douintvec()`

```c
int proc_douintvec(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of unsigned integers

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(unsigned int) unsigned integer
values from/to the user buffer, treated as an ASCII string.

Returns 0 on success.

#### <a id="c-proc_dointvec_minmax"></a>`proc_dointvec_minmax()`

```c
int proc_dointvec_minmax(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of integers with min/max values

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(unsigned int) integer
values from/to the user buffer, treated as an ASCII string.

This routine will ensure the values are within the range specified by
table->extra1 (min) and table->extra2 (max).

Returns 0 on success or -EINVAL when the range check fails and
SYSCTL_USER_TO_KERN(dir) == true

#### <a id="c-proc_douintvec_minmax"></a>`proc_douintvec_minmax()`

```c
int proc_douintvec_minmax(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of unsigned ints with min/max values

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(unsigned int) unsigned integer
values from/to the user buffer, treated as an ASCII string. Negative
strings are not allowed.

When changing the kernel variable, this routine will ensure the values
are within the range specified by table->extra1 (min) and table->extra2
(max). And Check that the values are less than UINT_MAX to avoid having to
support wrap around uses from userspace.

Returns 0 on success or -ERANGE when range check failes and
SYSCTL_USER_TO_KERN(dir) == true

#### <a id="c-proc_dou8vec_minmax"></a>`proc_dou8vec_minmax()`

```c
int proc_dou8vec_minmax(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of unsigned chars with min/max values

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(u8) unsigned chars
values from/to the user buffer, treated as an ASCII string. Negative
strings are not allowed.

This routine will ensure the values are within the range specified by
table->extra1 (min) and table->extra2 (max).

Returns 0 on success or an error on SYSCTL_USER_TO_KERN(dir) == true
and the range check fails.

#### <a id="c-proc_doulongvec_minmax"></a>`proc_doulongvec_minmax()`

```c
int proc_doulongvec_minmax(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read a vector of long integers with min/max values

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

Reads/writes up to table->maxlen/sizeof(unsigned long) unsigned long
values from/to the user buffer, treated as an ASCII string.

This routine will ensure the values are within the range specified by
table->extra1 (min) and table->extra2 (max).

Returns 0 on success.

#### <a id="c-proc_do_large_bitmap"></a>`proc_do_large_bitmap()`

```c
int proc_do_large_bitmap(const struct ctl_table *table, int dir, void *buffer, size_t *lenp, loff_t *ppos)
```

read/write from/to a large bitmap

**Parameters**

- `const struct ctl_table *table`: the sysctl table
- `int dir`: `TRUE` if this is a write to the sysctl file
- `void *buffer`: the user buffer
- `size_t *lenp`: the size of the user buffer
- `loff_t *ppos`: file position

**Description**

The bitmap is stored at table->data and the bitmap length (in bits)
in table->maxlen.

We use a range comma separated format (e.g. 1,3-4,10-10) so that
large bitmaps may be represented in a compact manner. Writing into
the file will clear the bitmap then update it with the given input.

Returns 0 on success.


<a id="rst-proc-filesystem-interface"></a>

### proc filesystem interface


#### <a id="c-proc_flush_pid"></a>`proc_flush_pid()`

```c
void proc_flush_pid(struct pid *pid)
```

Remove dcache entries for **pid** from the /proc dcache.

**Parameters**

- `struct pid *pid`: pid that should be flushed.

**Description**

This function walks a list of inodes (that belong to any proc
filesystem) that are attached to the pid and flushes them from
the dentry cache.

It is safe and reasonable to cache /proc entries for a task until
that task exits.  After that they just clog up the dcache with
useless entries, possibly causing useful dcache entries to be
flushed instead.  This routine is provided to flush those useless
dcache entries when a process is reaped.

**NOTE**

- This routine is just an optimization so it does not guarantee

  that no dcache entries will exist after a process is reaped
  it just makes it very unlikely that any will persist.


<a id="rst-events-based-on-file-descriptors"></a>

## Events based on file descriptors


#### <a id="c-eventfd_signal_mask"></a>`eventfd_signal_mask()`

```c
void eventfd_signal_mask(struct eventfd_ctx *ctx, __poll_t mask)
```

Increment the event counter

**Parameters**

- `struct eventfd_ctx *ctx`: \[in\] Pointer to the eventfd context.
- `__poll_t mask`: \[in\] poll mask

**Description**

This function is supposed to be called by the kernel in paths that do not
allow sleeping. In this function we allow the counter to reach the ULLONG_MAX
value, and we signal this as overflow condition by returning a EPOLLERR
to poll(2).

#### <a id="c-eventfd_ctx_put"></a>`eventfd_ctx_put()`

```c
void eventfd_ctx_put(struct eventfd_ctx *ctx)
```

Releases a reference to the internal eventfd context.

**Parameters**

- `struct eventfd_ctx *ctx`: \[in\] Pointer to eventfd context.

**Description**

The eventfd context reference must have been previously acquired either
with [`eventfd_ctx_fdget()`](#c-eventfd_ctx_fdget) or [`eventfd_ctx_fileget()`](#c-eventfd_ctx_fileget).

#### <a id="c-eventfd_ctx_remove_wait_queue"></a>`eventfd_ctx_remove_wait_queue()`

```c
int eventfd_ctx_remove_wait_queue(struct eventfd_ctx *ctx, wait_queue_entry_t *wait, __u64 *cnt)
```

Read the current counter and removes wait queue.

**Parameters**

- `struct eventfd_ctx *ctx`: \[in\] Pointer to eventfd context.
- `wait_queue_entry_t *wait`: \[in\] Wait queue to be removed.
- `__u64 *cnt`: \[out\] Pointer to the 64-bit counter value.

**Description**

Returns `0` if successful, or the following error codes:

-EAGAIN      : The operation would have blocked.

This is used to atomically remove a wait queue entry from the eventfd wait
queue head, and read/reset the counter value.

#### <a id="c-eventfd_fget"></a>`eventfd_fget()`

```c
struct file * eventfd_fget(int fd)
```

Acquire a reference of an eventfd file descriptor.

**Parameters**

- `int fd`: \[in\] Eventfd file descriptor.

**Description**

Returns a pointer to the eventfd file structure in case of success, or the
following error pointer:

-EBADF    : Invalid **fd** file descriptor.
-EINVAL   : The **fd** file descriptor is not an eventfd file.

#### <a id="c-eventfd_ctx_fdget"></a>`eventfd_ctx_fdget()`

```c
struct eventfd_ctx * eventfd_ctx_fdget(int fd)
```

Acquires a reference to the internal eventfd context.

**Parameters**

- `int fd`: \[in\] Eventfd file descriptor.

**Description**

Returns a pointer to the internal eventfd context, otherwise the error
pointers returned by the following functions:

eventfd_fget

#### <a id="c-eventfd_ctx_fileget"></a>`eventfd_ctx_fileget()`

```c
struct eventfd_ctx * eventfd_ctx_fileget(struct file *file)
```

Acquires a reference to the internal eventfd context.

**Parameters**

- `struct file *file`: \[in\] Eventfd file pointer.

**Description**

Returns a pointer to the internal eventfd context, otherwise the error
pointer:

-EINVAL   : The **fd** file descriptor is not an eventfd file.


<a id="rst-eventpoll-epoll-interfaces"></a>

## eventpoll (epoll) interfaces


#### <a id="c-ep_events_available"></a>`ep_events_available()`

```c
int ep_events_available(struct eventpoll *ep)
```

Checks if ready events might be available.

**Parameters**

- `struct eventpoll *ep`: Pointer to the eventpoll context.

**Return**

a value different than `zero` if ready events are available,
or `zero` otherwise.

#### <a id="c-busy_loop_ep_timeout"></a>`busy_loop_ep_timeout()`

```c
bool busy_loop_ep_timeout(unsigned long start_time, struct eventpoll *ep)
```

check if busy poll has timed out. The timeout value from the epoll instance ep is preferred, but if it is not set fallback to the system-wide global via busy_loop_timeout.

**Parameters**

- `unsigned long start_time`: The start time used to compute the remaining time until timeout.
- `struct eventpoll *ep`: Pointer to the eventpoll context.

**Return**

true if the timeout has expired, false otherwise.

#### <a id="c-reverse_path_check"></a>`reverse_path_check()`

```c
int reverse_path_check(void)
```

The tfile_check_list is list of epitem_head, which have links that are proposed to be newly added. We need to make sure that those added links don't add too many paths such that we will spend all our time waking up eventpoll objects.

**Parameters**

- `void`: no arguments

**Return**

`zero` if the proposed links don't create too many paths,
`-1` otherwise.

#### <a id="c-ep_poll"></a>`ep_poll()`

```c
int ep_poll(struct eventpoll *ep, struct epoll_event __user *events, int maxevents, struct timespec64 *timeout)
```

Retrieves ready events, and delivers them to the caller-supplied event buffer.

**Parameters**

- `struct eventpoll *ep`: Pointer to the eventpoll context.
- `struct epoll_event __user *events`: Pointer to the userspace buffer where the ready events should be
  stored.
- `int maxevents`: Size (in terms of number of events) of the caller event buffer.
- `struct timespec64 *timeout`: Maximum timeout for the ready events fetch operation, in
  timespec. If the timeout is zero, the function will not block,
  while if the **timeout** ptr is NULL, the function will block
  until at least one event has been retrieved (or an error
  occurred).

**Return**

the number of ready events which have been fetched, or an
error code, in case of error.

#### <a id="c-ep_loop_check_proc"></a>`ep_loop_check_proc()`

```c
int ep_loop_check_proc(struct eventpoll *ep, int depth)
```

verify that adding an epoll file **ep** inside another epoll file does not create closed loops, and determine the depth of the subtree starting at **ep**

**Parameters**

- `struct eventpoll *ep`: the `struct eventpoll` to be currently checked.
- `int depth`: Current depth of the path being checked.

**Return**

depth of the subtree, or a value bigger than EP_MAX_NESTS if we found
a loop or went too deep.

#### <a id="c-ep_loop_check"></a>`ep_loop_check()`

```c
int ep_loop_check(struct eventpoll *ep, struct eventpoll *to)
```

Performs a check to verify that adding an epoll file (**to**) into another epoll file (represented by **ep**) does not create closed loops or too deep chains.

**Parameters**

- `struct eventpoll *ep`: Pointer to the epoll we are inserting into.
- `struct eventpoll *to`: Pointer to the epoll to be inserted.

**Return**

`zero` if adding the epoll **to** inside the epoll **from**
does not violate the constraints, or `-1` otherwise.


<a id="rst-the-filesystem-for-exporting-kernel-objects"></a>

## The Filesystem for Exporting Kernel Objects


#### <a id="c-sysfs_create_file_ns"></a>`sysfs_create_file_ns()`

```c
int sysfs_create_file_ns(struct kobject *kobj, const struct attribute *attr, const struct ns_common *ns)
```

create an attribute file for an object with custom ns

**Parameters**

- `struct kobject *kobj`: object we're creating for
- `const struct attribute *attr`: attribute descriptor
- `const struct ns_common *ns`: namespace the new file should belong to

#### <a id="c-sysfs_add_file_to_group"></a>`sysfs_add_file_to_group()`

```c
int sysfs_add_file_to_group(struct kobject *kobj, const struct attribute *attr, const char *group)
```

add an attribute file to a pre-existing group.

**Parameters**

- `struct kobject *kobj`: object we're acting for.
- `const struct attribute *attr`: attribute descriptor.
- `const char *group`: group name.

#### <a id="c-sysfs_chmod_file"></a>`sysfs_chmod_file()`

```c
int sysfs_chmod_file(struct kobject *kobj, const struct attribute *attr, umode_t mode)
```

update the modified mode value on an object attribute.

**Parameters**

- `struct kobject *kobj`: object we're acting for.
- `const struct attribute *attr`: attribute descriptor.
- `umode_t mode`: file permissions.

#### <a id="c-sysfs_break_active_protection"></a>`sysfs_break_active_protection()`

```c
struct kernfs_node * sysfs_break_active_protection(struct kobject *kobj, const struct attribute *attr)
```

break "active" protection

**Parameters**

- `struct kobject *kobj`: The kernel object **attr** is associated with.
- `const struct attribute *attr`: The attribute to break the "active" protection for.

**Description**

With sysfs, just like kernfs, deletion of an attribute is postponed until
all active .`show()` and .`store()` callbacks have finished unless this function
is called. Hence this function is useful in methods that implement self
deletion.

#### <a id="c-sysfs_unbreak_active_protection"></a>`sysfs_unbreak_active_protection()`

```c
void sysfs_unbreak_active_protection(struct kernfs_node *kn)
```

restore "active" protection

**Parameters**

- `struct kernfs_node *kn`: Pointer returned by [`sysfs_break_active_protection()`](#c-sysfs_break_active_protection).

**Description**

Undo the effects of [`sysfs_break_active_protection()`](#c-sysfs_break_active_protection). Since this function
calls `kernfs_put()` on the kernfs node that corresponds to the 'attr'
argument passed to [`sysfs_break_active_protection()`](#c-sysfs_break_active_protection) that attribute may have
been removed between the [`sysfs_break_active_protection()`](#c-sysfs_break_active_protection) and
[`sysfs_unbreak_active_protection()`](#c-sysfs_unbreak_active_protection) calls, it is not safe to access **kn** after
this function has returned.

#### <a id="c-sysfs_remove_file_ns"></a>`sysfs_remove_file_ns()`

```c
void sysfs_remove_file_ns(struct kobject *kobj, const struct attribute *attr, const struct ns_common *ns)
```

remove an object attribute with a custom ns tag

**Parameters**

- `struct kobject *kobj`: object we're acting for
- `const struct attribute *attr`: attribute descriptor
- `const struct ns_common *ns`: namespace tag of the file to remove

**Description**

Hash the attribute name and namespace tag and kill the victim.

#### <a id="c-sysfs_remove_file_self"></a>`sysfs_remove_file_self()`

```c
bool sysfs_remove_file_self(struct kobject *kobj, const struct attribute *attr)
```

remove an object attribute from its own method

**Parameters**

- `struct kobject *kobj`: object we're acting for
- `const struct attribute *attr`: attribute descriptor

**Description**

See `kernfs_remove_self()` for details.

#### <a id="c-sysfs_remove_file_from_group"></a>`sysfs_remove_file_from_group()`

```c
void sysfs_remove_file_from_group(struct kobject *kobj, const struct attribute *attr, const char *group)
```

remove an attribute file from a group.

**Parameters**

- `struct kobject *kobj`: object we're acting for.
- `const struct attribute *attr`: attribute descriptor.
- `const char *group`: group name.

#### <a id="c-sysfs_create_bin_file"></a>`sysfs_create_bin_file()`

```c
int sysfs_create_bin_file(struct kobject *kobj, const struct bin_attribute *attr)
```

create binary file for object.

**Parameters**

- `struct kobject *kobj`: object.
- `const struct bin_attribute *attr`: attribute descriptor.

#### <a id="c-sysfs_remove_bin_file"></a>`sysfs_remove_bin_file()`

```c
void sysfs_remove_bin_file(struct kobject *kobj, const struct bin_attribute *attr)
```

remove binary file for object.

**Parameters**

- `struct kobject *kobj`: object.
- `const struct bin_attribute *attr`: attribute descriptor.

#### <a id="c-sysfs_emit"></a>`sysfs_emit()`

```c
int sysfs_emit(char *buf, const char *fmt, ...)
```

scnprintf equivalent, aware of PAGE_SIZE buffer.

**Parameters**

- `char *buf`: start of PAGE_SIZE buffer.
- `const char *fmt`: format
- `...`: optional arguments to **format**

**Description**

Returns number of characters written to **buf**.

#### <a id="c-sysfs_emit_at"></a>`sysfs_emit_at()`

```c
int sysfs_emit_at(char *buf, int at, const char *fmt, ...)
```

scnprintf equivalent, aware of PAGE_SIZE buffer.

**Parameters**

- `char *buf`: start of PAGE_SIZE buffer.
- `int at`: offset in **buf** to start write in bytes
  **at** must be >= 0 && \< PAGE_SIZE
- `const char *fmt`: format
- `...`: optional arguments to **fmt**

**Description**

Returns number of characters written starting at &**buf**\[**at**\].

#### <a id="c-sysfs_bin_attr_simple_read"></a>`sysfs_bin_attr_simple_read()`

```c
ssize_t sysfs_bin_attr_simple_read(struct file *file, struct kobject *kobj, const struct bin_attribute *attr, char *buf, loff_t off, size_t count)
```

read callback to simply copy from memory.

**Parameters**

- `struct file *file`: attribute file which is being read.
- `struct kobject *kobj`: object to which the attribute belongs.
- `const struct bin_attribute *attr`: attribute descriptor.
- `char *buf`: destination buffer.
- `loff_t off`: offset in bytes from which to read.
- `size_t count`: maximum number of bytes to read.

**Description**

Simple ->`read()` callback for bin_attributes backed by a buffer in memory.
The **private** and **size** members in struct bin_attribute must be set to the
buffer's location and size before the bin_attribute is created in sysfs.

Bounds check for **off** and **count** is done in `sysfs_kf_bin_read()`.
Negative value check for **off** is done in `vfs_setpos()` and `default_llseek()`.

Returns number of bytes written to **buf**.



#### <a id="c-sysfs_create_link"></a>`sysfs_create_link()`

```c
int sysfs_create_link(struct kobject *kobj, struct kobject *target, const char *name)
```

create symlink between two objects.

**Parameters**

- `struct kobject *kobj`: object whose directory we're creating the link in.
- `struct kobject *target`: object we're pointing to.
- `const char *name`: name of the symlink.

#### <a id="c-sysfs_create_link_nowarn"></a>`sysfs_create_link_nowarn()`

```c
int sysfs_create_link_nowarn(struct kobject *kobj, struct kobject *target, const char *name)
```

create symlink between two objects.

**Parameters**

- `struct kobject *kobj`: object whose directory we're creating the link in.
- `struct kobject *target`: object we're pointing to.
- `const char *name`: name of the symlink.

**Description**

This function does the same as [`sysfs_create_link()`](#c-sysfs_create_link), but it
doesn't warn if the link already exists.

#### <a id="c-sysfs_remove_link"></a>`sysfs_remove_link()`

```c
void sysfs_remove_link(struct kobject *kobj, const char *name)
```

remove symlink in object's directory.

**Parameters**

- `struct kobject *kobj`: object we're acting for.
- `const char *name`: name of the symlink to remove.

#### <a id="c-sysfs_rename_link_ns"></a>`sysfs_rename_link_ns()`

```c
int sysfs_rename_link_ns(struct kobject *kobj, struct kobject *targ, const char *old, const char *new, const struct ns_common *new_ns)
```

rename symlink in object's directory.

**Parameters**

- `struct kobject *kobj`: object we're acting for.
- `struct kobject *targ`: object we're pointing to.
- `const char *old`: previous name of the symlink.
- `const char *new`: new name of the symlink.
- `const struct ns_common *new_ns`: new namespace of the symlink.

**Description**

A helper function for the common rename symlink idiom.


<a id="rst-the-debugfs-filesystem"></a>

## The debugfs filesystem

<a id="rst-debugfs-interface"></a>

### debugfs interface


#### <a id="c-debugfs_lookup"></a>`debugfs_lookup()`

```c
struct dentry * debugfs_lookup(const char *name, struct dentry *parent)
```

look up an existing debugfs file

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to look up.
- `struct dentry *parent`: a pointer to the parent dentry of the file.

**Description**

This function will return a pointer to a dentry if it succeeds.  If the file
doesn't exist or an error occurs, `NULL` will be returned.  The returned
dentry must be passed to `dput()` when it is no longer needed.

If debugfs is not enabled in the kernel, the value -`ENODEV` will be
returned.

#### <a id="c-debugfs_create_file_unsafe"></a>`debugfs_create_file_unsafe()`

```c
struct dentry * debugfs_create_file_unsafe(const char *name, umode_t mode, struct dentry *parent, void *data, const struct file_operations *fops)
```

create a file in the debugfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is NULL, then the
  file will be created in the root of the debugfs filesystem.
- `void *data`: a pointer to something that the caller will want to get to later
  on.  The inode.i_private pointer will point to this value on
  the `open()` call.
- `const struct file_operations *fops`: a pointer to a struct file_operations that should be used for
  this file.

**Description**

[`debugfs_create_file_unsafe()`](#c-debugfs_create_file_unsafe) is completely analogous to
`debugfs_create_file()`, the only difference being that the fops
handed it will not get protected against file removals by the
debugfs core.

It is your responsibility to protect your struct file_operation
methods against file removals by means of [`debugfs_file_get()`](#c-debugfs_file_get)
and [`debugfs_file_put()`](#c-debugfs_file_put). ->`open()` is still protected by
debugfs though.

Any struct file_operations defined by means of
`DEFINE_DEBUGFS_ATTRIBUTE()` is protected against file removals and
thus, may be used here.

#### <a id="c-debugfs_create_file_size"></a>`debugfs_create_file_size()`

```c
void debugfs_create_file_size(const char *name, umode_t mode, struct dentry *parent, void *data, const struct file_operations *fops, loff_t file_size)
```

create a file in the debugfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is NULL, then the
  file will be created in the root of the debugfs filesystem.
- `void *data`: a pointer to something that the caller will want to get to later
  on.  The inode.i_private pointer will point to this value on
  the `open()` call.
- `const struct file_operations *fops`: a pointer to a struct file_operations that should be used for
  this file.
- `loff_t file_size`: initial file size

**Description**

This is the basic "create a file" function for debugfs.  It allows for a
wide range of flexibility in creating a file, or a directory (if you want
to create a directory, the [`debugfs_create_dir()`](#c-debugfs_create_dir) function is
recommended to be used instead.)

#### <a id="c-debugfs_create_dir"></a>`debugfs_create_dir()`

```c
struct dentry * debugfs_create_dir(const char *name, struct dentry *parent)
```

create a directory in the debugfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the directory to
  create.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is NULL, then the
  directory will be created in the root of the debugfs filesystem.

**Description**

This function creates a directory in debugfs with the given name.

This function will return a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`debugfs_remove()`](#c-debugfs_remove) function when the file is
to be removed (no automatic cleanup happens if your module is unloaded,
you are responsible here.)  If an error occurs, ERR_PTR(-ERROR) will be
returned.

If debugfs is not enabled in the kernel, the value -`ENODEV` will be
returned.

**NOTE**

it's expected that most callers should _ignore_ the errors returned
by this function. Other debugfs functions handle the fact that the "dentry"
passed to them could be an error and they don't crash in that case.
Drivers should generally work fine even if debugfs fails to init anyway.

#### <a id="c-debugfs_create_automount"></a>`debugfs_create_automount()`

```c
struct dentry * debugfs_create_automount(const char *name, struct dentry *parent, debugfs_automount_t f, void *data)
```

create automount point in the debugfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is NULL, then the
  file will be created in the root of the debugfs filesystem.
- `debugfs_automount_t f`: function to be called when pathname resolution steps on that one.
- `void *data`: opaque argument to pass to `f()`.

**Description**

**f** should return what ->`d_automount()` would.

#### <a id="c-debugfs_create_symlink"></a>`debugfs_create_symlink()`

```c
struct dentry * debugfs_create_symlink(const char *name, struct dentry *parent, const char *target)
```

create a symbolic link in the debugfs filesystem

**Parameters**

- `const char *name`: a pointer to a string containing the name of the symbolic link to
  create.
- `struct dentry *parent`: a pointer to the parent dentry for this symbolic link.  This
  should be a directory dentry if set.  If this parameter is NULL,
  then the symbolic link will be created in the root of the debugfs
  filesystem.
- `const char *target`: a pointer to a string containing the path to the target of the
  symbolic link.

**Description**

This function creates a symbolic link with the given name in debugfs that
links to the given target path.

This function will return a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`debugfs_remove()`](#c-debugfs_remove) function when the symbolic
link is to be removed (no automatic cleanup happens if your module is
unloaded, you are responsible here.)  If an error occurs, ERR_PTR(-ERROR)
will be returned.

If debugfs is not enabled in the kernel, the value -`ENODEV` will be
returned.

#### <a id="c-debugfs_remove"></a>`debugfs_remove()`

```c
void debugfs_remove(struct dentry *dentry)
```

recursively removes a directory

**Parameters**

- `struct dentry *dentry`: a pointer to a the dentry of the directory to be removed.  If this
  parameter is NULL or an error value, nothing will be done.

**Description**

This function recursively removes a directory tree in debugfs that
was previously created with a call to another debugfs function
(like `debugfs_create_file()` or variants thereof.)

This function is required to be called in order for the file to be
removed, no automatic cleanup of files will happen when a module is
removed, you are responsible here.

#### <a id="c-debugfs_lookup_and_remove"></a>`debugfs_lookup_and_remove()`

```c
void debugfs_lookup_and_remove(const char *name, struct dentry *parent)
```

lookup a directory or file and recursively remove it

**Parameters**

- `const char *name`: a pointer to a string containing the name of the item to look up.
- `struct dentry *parent`: a pointer to the parent dentry of the item.

**Description**

This is the equlivant of doing something like
debugfs_remove(debugfs_lookup(..)) but with the proper reference counting
handled for the directory being looked up.

#### <a id="c-debugfs_change_name"></a>`debugfs_change_name()`

```c
int debugfs_change_name(struct dentry *dentry, const char *fmt, ...)
```

rename a file/directory in the debugfs filesystem

**Parameters**

- `struct dentry *dentry`: dentry of an object to be renamed.
- `const char *fmt`: format for new name
- `...`: variable arguments

**Description**

This function renames a file/directory in debugfs.  The target must not
exist for rename to succeed.

This function will return 0 on success and -E... on failure.

If debugfs is not enabled in the kernel, the value -`ENODEV` will be
returned.

#### <a id="c-debugfs_initialized"></a>`debugfs_initialized()`

```c
bool debugfs_initialized(void)
```

Tells whether debugfs has been registered

**Parameters**

- `void`: no arguments



#### <a id="c-debugfs_file_get"></a>`debugfs_file_get()`

```c
int debugfs_file_get(struct dentry *dentry)
```

mark the beginning of file data access

**Parameters**

- `struct dentry *dentry`: the dentry object whose data is being accessed.

**Description**

Up to a matching call to [`debugfs_file_put()`](#c-debugfs_file_put), any successive call
into the file removing functions [`debugfs_remove()`](#c-debugfs_remove) and
`debugfs_remove_recursive()` will block. Since associated private
file data may only get freed after a successful return of any of
the removal functions, you may safely access it after a successful
call to [`debugfs_file_get()`](#c-debugfs_file_get) without worrying about lifetime issues.

If -`EIO` is returned, the file has already been removed and thus,
it is not safe to access any of its data. If, on the other hand,
it is allowed to access the file data, zero is returned.

#### <a id="c-debugfs_file_put"></a>`debugfs_file_put()`

```c
void debugfs_file_put(struct dentry *dentry)
```

mark the end of file data access

**Parameters**

- `struct dentry *dentry`: the dentry object formerly passed to
  [`debugfs_file_get()`](#c-debugfs_file_get).

**Description**

Allow any ongoing concurrent call into [`debugfs_remove()`](#c-debugfs_remove) or
`debugfs_remove_recursive()` blocked by a former call to
[`debugfs_file_get()`](#c-debugfs_file_get) to proceed and return to its caller.

#### <a id="c-debugfs_enter_cancellation"></a>`debugfs_enter_cancellation()`

```c
void debugfs_enter_cancellation(struct file *file, struct debugfs_cancellation *cancellation)
```

enter a debugfs cancellation

**Parameters**

- `struct file *file`: the file being accessed
- `struct debugfs_cancellation *cancellation`: the cancellation object, the cancel callback
  inside of it must be initialized

**Description**

When a debugfs file is removed it needs to wait for all active
operations to complete. However, the operation itself may need
to wait for hardware or completion of some asynchronous process
or similar. As such, it may need to be cancelled to avoid long
waits or even deadlocks.

This function can be used inside a debugfs handler that may
need to be cancelled. As soon as this function is called, the
cancellation's 'cancel' callback may be called, at which point
the caller should proceed to call [`debugfs_leave_cancellation()`](#c-debugfs_leave_cancellation)
and leave the debugfs handler function as soon as possible.
Note that the 'cancel' callback is only ever called in the
context of some kind of [`debugfs_remove()`](#c-debugfs_remove).

This function must be paired with [`debugfs_leave_cancellation()`](#c-debugfs_leave_cancellation).

#### <a id="c-debugfs_leave_cancellation"></a>`debugfs_leave_cancellation()`

```c
void debugfs_leave_cancellation(struct file *file, struct debugfs_cancellation *cancellation)
```

leave cancellation section

**Parameters**

- `struct file *file`: the file being accessed
- `struct debugfs_cancellation *cancellation`: the cancellation previously registered with
  [`debugfs_enter_cancellation()`](#c-debugfs_enter_cancellation)

**Description**

See the documentation of [`debugfs_enter_cancellation()`](#c-debugfs_enter_cancellation).

#### <a id="c-debugfs_create_u8"></a>`debugfs_create_u8()`

```c
void debugfs_create_u8(const char *name, umode_t mode, struct dentry *parent, u8 *value)
```

create a debugfs file that is used to read and write an unsigned 8-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u8 *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_u16"></a>`debugfs_create_u16()`

```c
void debugfs_create_u16(const char *name, umode_t mode, struct dentry *parent, u16 *value)
```

create a debugfs file that is used to read and write an unsigned 16-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u16 *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_u32"></a>`debugfs_create_u32()`

```c
void debugfs_create_u32(const char *name, umode_t mode, struct dentry *parent, u32 *value)
```

create a debugfs file that is used to read and write an unsigned 32-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u32 *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_u64"></a>`debugfs_create_u64()`

```c
void debugfs_create_u64(const char *name, umode_t mode, struct dentry *parent, u64 *value)
```

create a debugfs file that is used to read and write an unsigned 64-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u64 *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_ulong"></a>`debugfs_create_ulong()`

```c
void debugfs_create_ulong(const char *name, umode_t mode, struct dentry *parent, unsigned long *value)
```

create a debugfs file that is used to read and write an unsigned long value.

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `unsigned long *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_x8"></a>`debugfs_create_x8()`

```c
void debugfs_create_x8(const char *name, umode_t mode, struct dentry *parent, u8 *value)
```

create a debugfs file that is used to read and write an unsigned 8-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u8 *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_x16"></a>`debugfs_create_x16()`

```c
void debugfs_create_x16(const char *name, umode_t mode, struct dentry *parent, u16 *value)
```

create a debugfs file that is used to read and write an unsigned 16-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u16 *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_x32"></a>`debugfs_create_x32()`

```c
void debugfs_create_x32(const char *name, umode_t mode, struct dentry *parent, u32 *value)
```

create a debugfs file that is used to read and write an unsigned 32-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u32 *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_x64"></a>`debugfs_create_x64()`

```c
void debugfs_create_x64(const char *name, umode_t mode, struct dentry *parent, u64 *value)
```

create a debugfs file that is used to read and write an unsigned 64-bit value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `u64 *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_size_t"></a>`debugfs_create_size_t()`

```c
void debugfs_create_size_t(const char *name, umode_t mode, struct dentry *parent, size_t *value)
```

create a debugfs file that is used to read and write an size_t value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `size_t *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_atomic_t"></a>`debugfs_create_atomic_t()`

```c
void debugfs_create_atomic_t(const char *name, umode_t mode, struct dentry *parent, atomic_t *value)
```

create a debugfs file that is used to read and write an atomic_t value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `atomic_t *value`: a pointer to the variable that the file should read to and write
  from.

#### <a id="c-debugfs_create_bool"></a>`debugfs_create_bool()`

```c
void debugfs_create_bool(const char *name, umode_t mode, struct dentry *parent, bool *value)
```

create a debugfs file that is used to read and write a boolean value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `bool *value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_str"></a>`debugfs_create_str()`

```c
void debugfs_create_str(const char *name, umode_t mode, struct dentry *parent, char **value)
```

create a debugfs file that is used to read and write a string value

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `char **value`: a pointer to the variable that the file should read to and write
  from.

**Description**

This function creates a file in debugfs with the given name that
contains the value of the variable **value**.  If the **mode** variable is so
set, it can be read from, and written to.

#### <a id="c-debugfs_create_blob"></a>`debugfs_create_blob()`

```c
struct dentry * debugfs_create_blob(const char *name, umode_t mode, struct dentry *parent, struct debugfs_blob_wrapper *blob)
```

create a debugfs file that is used to read and write a binary blob

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `struct debugfs_blob_wrapper *blob`: a pointer to a struct debugfs_blob_wrapper which contains a pointer
  to the blob data and the size of the data.

**Description**

This function creates a file in debugfs with the given name that exports
**blob->data** as a binary blob. If the **mode** variable is so set it can be
read from and written to.

This function will return a pointer to a dentry if it succeeds.  This
pointer must be passed to the [`debugfs_remove()`](#c-debugfs_remove) function when the file is
to be removed (no automatic cleanup happens if your module is unloaded,
you are responsible here.)  If an error occurs, ERR_PTR(-ERROR) will be
returned.

If debugfs is not enabled in the kernel, the value ERR_PTR(-ENODEV) will
be returned.

#### <a id="c-debugfs_create_u32_array"></a>`debugfs_create_u32_array()`

```c
void debugfs_create_u32_array(const char *name, umode_t mode, struct dentry *parent, struct debugfs_u32_array *array)
```

create a debugfs file that is used to read u32 array.

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `struct debugfs_u32_array *array`: wrapper struct containing data pointer and size of the array.

**Description**

This function creates a file in debugfs with the given name that exports
**array** as data. If the **mode** variable is so set it can be read from.
Writing is not supported. Seek within the file is also not supported.
Once array is created its size can not be changed.

#### <a id="c-debugfs_print_regs32"></a>`debugfs_print_regs32()`

```c
void debugfs_print_regs32(struct seq_file *s, const struct debugfs_reg32 *regs, int nregs, void __iomem *base, char *prefix)
```

use seq_print to describe a set of registers

**Parameters**

- `struct seq_file *s`: the seq_file structure being used to generate output
- `const struct debugfs_reg32 *regs`: an array if struct debugfs_reg32 structures
- `int nregs`: the length of the above array
- `void __iomem *base`: the base address to be used in reading the registers
- `char *prefix`: a string to be prefixed to every output line

**Description**

This function outputs a text block describing the current values of
some 32-bit hardware registers. It is meant to be used within debugfs
files based on seq_file that need to show registers, intermixed with other
information. The prefix argument may be used to specify a leading string,
because some peripherals have several blocks of identical registers,
for example configuration of dma channels

#### <a id="c-debugfs_create_regset32"></a>`debugfs_create_regset32()`

```c
void debugfs_create_regset32(const char *name, umode_t mode, struct dentry *parent, struct debugfs_regset32 *regset)
```

create a debugfs file that returns register values

**Parameters**

- `const char *name`: a pointer to a string containing the name of the file to create.
- `umode_t mode`: the permission that the file should have
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `struct debugfs_regset32 *regset`: a pointer to a struct debugfs_regset32, which contains a pointer
  to an array of register definitions, the array size and the base
  address where the register bank is to be found.

**Description**

This function creates a file in debugfs with the given name that reports
the names and values of a set of 32-bit registers. If the **mode** variable
is so set it can be read from. Writing is not supported.

#### <a id="c-debugfs_create_devm_seqfile"></a>`debugfs_create_devm_seqfile()`

```c
void debugfs_create_devm_seqfile(struct device *dev, const char *name, struct dentry *parent, int (*read_fn)(struct seq_file *s, void *data))
```

create a debugfs file that is bound to device.

**Parameters**

- `struct device *dev`: device related to this debugfs file.
- `const char *name`: name of the debugfs file.
- `struct dentry *parent`: a pointer to the parent dentry for this file.  This should be a
  directory dentry if set.  If this parameter is `NULL`, then the
  file will be created in the root of the debugfs filesystem.
- `int (*read_fn)(struct seq_file *s, void *data)`: function pointer called to print the seq_file content.

---

# Miscellaneous Device control operations for the autofs kernel module

_Peios Kernel / Internals / Filesystems_

> There is a problem with active restarts in autofs (that is to say restarting autofs when there are busy mounts).

<a id="rst-miscellaneous-device-control-operations-for-the-autofs-kernel-module"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-the-problem"></a>

## The problem

There is a problem with active restarts in autofs (that is to say restarting autofs when there are busy mounts).

During normal operation autofs uses a file descriptor opened on the directory that is being managed in order to be able to issue control operations. Using a file descriptor gives ioctl operations access to autofs specific information stored in the super block. The operations are things such as setting an autofs mount catatonic, setting the expire timeout and requesting expire checks. As is explained below, certain types of autofs triggered mounts can end up covering an autofs mount itself which prevents us being able to use open(2) to obtain a file descriptor for these operations if we don't already have one open.

Currently autofs uses "umount -l" (lazy umount) to clear active mounts at restart. While using lazy umount works for most cases, anything that needs to walk back up the mount tree to construct a path, such as getcwd(2) and the proc file system /proc/&lt;pid&gt;/cwd, no longer works because the point from which the path is constructed has been detached from the mount tree.

The actual problem with autofs is that it can't reconnect to existing mounts. Immediately one thinks of just adding the ability to remount autofs file systems would solve it, but alas, that can't work. This is because autofs direct mounts and the implementation of "on demand mount and expire" of nested mount trees have the file system mounted directly on top of the mount trigger directory dentry.

For example, there are two types of automount maps, direct (in the kernel module source you will see a third type called an offset, which is just a direct mount in disguise) and indirect.

Here is a master map with direct and indirect map entries:



```text
/-      /etc/auto.direct
/test   /etc/auto.indirect
```

and the corresponding map files:



```text
/etc/auto.direct:

/automount/dparse/g6  budgie:/autofs/export1
/automount/dparse/g1  shark:/autofs/export1
and so on.
```

/etc/auto.indirect:



```text
g1    shark:/autofs/export1
g6    budgie:/autofs/export1
and so on.
```

For the above indirect map an autofs file system is mounted on /test and mounts are triggered for each sub-directory key by the inode lookup operation. So we see a mount of shark:/autofs/export1 on /test/g1, for example.

The way that direct mounts are handled is by making an autofs mount on each full path, such as /automount/dparse/g1, and using it as a mount trigger. So when we walk on the path we mount shark:/autofs/export1 "on top of this mount point". Since these are always directories we can use the follow_link inode operation to trigger the mount.

But, each entry in direct and indirect maps can have offsets (making them multi-mount map entries).

For example, an indirect mount map entry could also be:



```text
g1  \
/        shark:/autofs/export5/testing/test \
/s1      shark:/autofs/export/testing/test/s1 \
/s2      shark:/autofs/export5/testing/test/s2 \
/s1/ss1  shark:/autofs/export1 \
/s2/ss2  shark:/autofs/export2
```

and a similarly a direct mount map entry could also be:



```text
/automount/dparse/g1 \
    /       shark:/autofs/export5/testing/test \
    /s1     shark:/autofs/export/testing/test/s1 \
    /s2     shark:/autofs/export5/testing/test/s2 \
    /s1/ss1 shark:/autofs/export2 \
    /s2/ss2 shark:/autofs/export2
```

One of the issues with version 4 of autofs was that, when mounting an entry with a large number of offsets, possibly with nesting, we needed to mount and umount all of the offsets as a single unit. Not really a problem, except for people with a large number of offsets in map entries. This mechanism is used for the well known "hosts" map and we have seen cases (in 2.4) where the available number of mounts are exhausted or where the number of privileged ports available is exhausted.

In version 5 we mount only as we go down the tree of offsets and similarly for expiring them which resolves the above problem. There is somewhat more detail to the implementation but it isn't needed for the sake of the problem explanation. The one important detail is that these offsets are implemented using the same mechanism as the direct mounts above and so the mount points can be covered by a mount.

The current autofs implementation uses an ioctl file descriptor opened on the mount point for control operations. The references held by the descriptor are accounted for in checks made to determine if a mount is in use and is also used to access autofs file system information held in the mount super block. So the use of a file handle needs to be retained.

<a id="rst-the-solution"></a>

## The Solution

To be able to restart autofs leaving existing direct, indirect and offset mounts in place we need to be able to obtain a file handle for these potentially covered autofs mount points. Rather than just implement an isolated operation it was decided to re-implement the existing ioctl interface and add new operations to provide this functionality.

In addition, to be able to reconstruct a mount tree that has busy mounts, the uid and gid of the last user that triggered the mount needs to be available because these can be used as macro substitution variables in autofs maps. They are recorded at mount request time and an operation has been added to retrieve them.

Since we're re-implementing the control interface, a couple of other problems with the existing interface have been addressed. First, when a mount or expire operation completes a status is returned to the kernel by either a "send ready" or a "send fail" operation. The "send fail" operation of the ioctl interface could only ever send ENOENT so the re-implementation allows user space to send an actual status. Another expensive operation in user space, for those using very large maps, is discovering if a mount is present. Usually this involves scanning /proc/mounts and since it needs to be done quite often it can introduce significant overhead when there are many entries in the mount table. An operation to lookup the mount status of a mount point dentry (covered or not) has also been added.

Current kernel development policy recommends avoiding the use of the ioctl mechanism in favor of systems such as Netlink. An implementation using this system was attempted to evaluate its suitability and it was found to be inadequate, in this case. The Generic Netlink system was used for this as raw Netlink would lead to a significant increase in complexity. There's no question that the Generic Netlink system is an elegant solution for common case ioctl functions but it's not a complete replacement probably because its primary purpose in life is to be a message bus implementation rather than specifically an ioctl replacement. While it would be possible to work around this there is one concern that lead to the decision to not use it. This is that the autofs expire in the daemon has become far to complex because umount candidates are enumerated, almost for no other reason than to "count" the number of times to call the expire ioctl. This involves scanning the mount table which has proved to be a big overhead for users with large maps. The best way to improve this is try and get back to the way the expire was done long ago. That is, when an expire request is issued for a mount (file handle) we should continually call back to the daemon until we can't umount any more mounts, then return the appropriate status to the daemon. At the moment we just expire one mount at a time. A Generic Netlink implementation would exclude this possibility for future development due to the requirements of the message bus architecture.

<a id="rst-autofs-miscellaneous-device-mount-control-interface"></a>

## autofs Miscellaneous Device mount control interface

The control interface is opening a device node, typically /dev/autofs.

All the ioctls use a common structure to pass the needed parameter information and return operation results:



```text
struct autofs_dev_ioctl {
        __u32 ver_major;
        __u32 ver_minor;
        __u32 size;             /* total size of data passed in
                                * including this struct */
        __s32 ioctlfd;          /* automount command fd */

        /* Command parameters */
        union {
                struct args_protover                protover;
                struct args_protosubver             protosubver;
                struct args_openmount               openmount;
                struct args_ready           ready;
                struct args_fail            fail;
                struct args_setpipefd               setpipefd;
                struct args_timeout         timeout;
                struct args_requester               requester;
                struct args_expire          expire;
                struct args_askumount               askumount;
                struct args_ismountpoint    ismountpoint;
        };

        char path[];
};
```

The ioctlfd field is a mount point file descriptor of an autofs mount point. It is returned by the open call and is used by all calls except the check for whether a given path is a mount point, where it may optionally be used to check a specific mount corresponding to a given mount point file descriptor, and when requesting the uid and gid of the last successful mount on a directory within the autofs file system.

The union is used to communicate parameters and results of calls made as described below.

The path field is used to pass a path where it is needed and the size field is used account for the increased structure length when translating the structure sent from user space.

This structure can be initialized before setting specific fields by using the void function call init_autofs_dev_ioctl(`struct autofs_dev_ioctl *`).

All of the ioctls perform a copy of this structure from user space to kernel space and return -EINVAL if the size parameter is smaller than the structure size itself, -ENOMEM if the kernel memory allocation fails or -EFAULT if the copy itself fails. Other checks include a version check of the compiled in user space version against the module version and a mismatch results in a -EINVAL return. If the size field is greater than the structure size then a path is assumed to be present and is checked to ensure it begins with a "/" and is NULL terminated, otherwise -EINVAL is returned. Following these checks, for all ioctl commands except AUTOFS_DEV_IOCTL_VERSION_CMD, AUTOFS_DEV_IOCTL_OPENMOUNT_CMD and AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD the ioctlfd is validated and if it is not a valid descriptor or doesn't correspond to an autofs mount point an error of -EBADF, -ENOTTY or -EINVAL (not an autofs descriptor) is returned.

<a id="rst-the-ioctls"></a>

## The ioctls

An example of an implementation which uses this interface can be seen in autofs version 5.0.4 and later in file lib/dev-ioctl-lib.c of the distribution tar available for download from kernel.org in directory /pub/linux/daemons/autofs/v5.

The device node ioctl operations implemented by this interface are:

<a id="rst-autofs-dev-ioctl-version"></a>

### AUTOFS_DEV_IOCTL_VERSION

Get the major and minor version of the autofs device ioctl kernel module implementation. It requires an initialized struct autofs_dev_ioctl as an input parameter and sets the version information in the passed in structure. It returns 0 on success or the error -EINVAL if a version mismatch is detected.

<a id="rst-autofs-dev-ioctl-protover-cmd-and-autofs-dev-ioctl-protosubver-cmd"></a>

### AUTOFS_DEV_IOCTL_PROTOVER_CMD and AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD

Get the major and minor version of the autofs protocol version understood by loaded module. This call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to a valid autofs mount point descriptor and sets the requested version number in version field of struct args_protover or sub_version field of struct args_protosubver. These commands return 0 on success or one of the negative error codes if validation fails.

<a id="rst-autofs-dev-ioctl-openmount-and-autofs-dev-ioctl-closemount"></a>

### AUTOFS_DEV_IOCTL_OPENMOUNT and AUTOFS_DEV_IOCTL_CLOSEMOUNT

Obtain and release a file descriptor for an autofs managed mount point path. The open call requires an initialized struct autofs_dev_ioctl with the path field set and the size field adjusted appropriately as well as the devid field of struct args_openmount set to the device number of the autofs mount. The device number can be obtained from the mount options shown in /proc/mounts. The close call requires an initialized struct autofs_dev_ioct with the ioctlfd field set to the descriptor obtained from the open call. The release of the file descriptor can also be done with close(2) so any open descriptors will also be closed at process exit. The close call is included in the implemented operations largely for completeness and to provide for a consistent user space implementation.

<a id="rst-autofs-dev-ioctl-ready-cmd-and-autofs-dev-ioctl-fail-cmd"></a>

### AUTOFS_DEV_IOCTL_READY_CMD and AUTOFS_DEV_IOCTL_FAIL_CMD

Return mount and expire result status from user space to the kernel. Both of these calls require an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call and the token field of struct args_ready or struct args_fail set to the wait queue token number, received by user space in the foregoing mount or expire request. The status field of struct args_fail is set to the errno of the operation. It is set to 0 on success.

<a id="rst-autofs-dev-ioctl-setpipefd-cmd"></a>

### AUTOFS_DEV_IOCTL_SETPIPEFD_CMD

Set the pipe file descriptor used for kernel communication to the daemon. Normally this is set at mount time using an option but when reconnecting to a existing mount we need to use this to tell the autofs mount about the new kernel pipe descriptor. In order to protect mounts against incorrectly setting the pipe descriptor we also require that the autofs mount be catatonic (see next call).

The call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call and the pipefd field of struct args_setpipefd set to descriptor of the pipe. On success the call also sets the process group id used to identify the controlling process (eg. the owning automount(8) daemon) to the process group of the caller.

<a id="rst-autofs-dev-ioctl-catatonic-cmd"></a>

### AUTOFS_DEV_IOCTL_CATATONIC_CMD

Make the autofs mount point catatonic. The autofs mount will no longer issue mount requests, the kernel communication pipe descriptor is released and any remaining waits in the queue released.

The call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call.

<a id="rst-autofs-dev-ioctl-timeout-cmd"></a>

### AUTOFS_DEV_IOCTL_TIMEOUT_CMD

Set the expire timeout for mounts within an autofs mount point.

The call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call.

<a id="rst-autofs-dev-ioctl-requester-cmd"></a>

### AUTOFS_DEV_IOCTL_REQUESTER_CMD

Return the uid and gid of the last process to successfully trigger a the mount on the given path dentry.

The call requires an initialized struct autofs_dev_ioctl with the path field set to the mount point in question and the size field adjusted appropriately. Upon return the uid field of struct args_requester contains the uid and gid field the gid.

When reconstructing an autofs mount tree with active mounts we need to re-connect to mounts that may have used the original process uid and gid (or string variations of them) for mount lookups within the map entry. This call provides the ability to obtain this uid and gid so they may be used by user space for the mount map lookups.

<a id="rst-autofs-dev-ioctl-expire-cmd"></a>

### AUTOFS_DEV_IOCTL_EXPIRE_CMD

Issue an expire request to the kernel for an autofs mount. Typically this ioctl is called until no further expire candidates are found.

The call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call. In addition an immediate expire that's independent of the mount timeout, and a forced expire that's independent of whether the mount is busy, can be requested by setting the how field of struct args_expire to AUTOFS_EXP_IMMEDIATE or AUTOFS_EXP_FORCED, respectively . If no expire candidates can be found the ioctl returns -1 with errno set to EAGAIN.

This call causes the kernel module to check the mount corresponding to the given ioctlfd for mounts that can be expired, issues an expire request back to the daemon and waits for completion.

<a id="rst-autofs-dev-ioctl-askumount-cmd"></a>

### AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD

Checks if an autofs mount point is in use.

The call requires an initialized struct autofs_dev_ioctl with the ioctlfd field set to the descriptor obtained from the open call and it returns the result in the may_umount field of struct args_askumount, 1 for busy and 0 otherwise.

<a id="rst-autofs-dev-ioctl-ismountpoint-cmd"></a>

### AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD

Check if the given path is a mountpoint.

The call requires an initialized struct autofs_dev_ioctl. There are two possible variations. Both use the path field set to the path of the mount point to check and the size field adjusted appropriately. One uses the ioctlfd field to identify a specific mount point to check while the other variation uses the path and optionally in.type field of struct args_ismountpoint set to an autofs mount type. The call returns 1 if this is a mount point and sets out.devid field to the device number of the mount and out.magic field to the relevant super block magic number (described below) or 0 if it isn't a mountpoint. In both cases the device number (as returned by new_encode_dev()) is returned in out.devid field.

If supplied with a file descriptor we're looking for a specific mount, not necessarily at the top of the mounted stack. In this case the path the descriptor corresponds to is considered a mountpoint if it is itself a mountpoint or contains a mount, such as a multi-mount without a root mount. In this case we return 1 if the descriptor corresponds to a mount point and also returns the super magic of the covering mount if there is one or 0 if it isn't a mountpoint.

If a path is supplied (and the ioctlfd field is set to -1) then the path is looked up and is checked to see if it is the root of a mount. If a type is also given we are looking for a particular autofs mount and if a match isn't found a fail is returned. If the located path is the root of a mount 1 is returned along with the super magic of the mount or 0 otherwise.

---

# autofs - how it works

_Peios Kernel / Internals / Filesystems_

> The goal of autofs is to provide on-demand mounting and race free automatic unmounting of various other filesystems. This provides two key advantages:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-autofs-how-it-works"></a>

<a id="rst-purpose"></a>

## Purpose

The goal of autofs is to provide on-demand mounting and race free automatic unmounting of various other filesystems.  This provides two key advantages:

1. There is no need to delay boot until all filesystems that might be needed are mounted.  Processes that try to access those slow filesystems might be delayed but other processes can continue freely.  This is particularly important for network filesystems (e.g. NFS) or filesystems stored on media with a media-changing robot.

2. The names and locations of filesystems can be stored in a remote database and can change at any time.  The content in that database at the time of access will be used to provide a target for the access.  The interpretation of names in the filesystem can even be programmatic rather than database-backed, allowing wildcards for example, and can vary based on the user who first accessed a name.

<a id="rst-context"></a>

## Context

The "autofs" filesystem module is only one part of an autofs system. There also needs to be a user-space program which looks up names and mounts filesystems.  This will often be the "automount" program, though other tools including "systemd" can make use of "autofs". This document describes only the kernel module and the interactions required with any user-space program.  Subsequent text refers to this as the "automount daemon" or simply "the daemon".

"autofs" is a Linux kernel module which provides the "autofs" filesystem type.  Several "autofs" filesystems can be mounted and they can each be managed separately, or all managed by the same daemon.

<a id="rst-content"></a>

## Content

An autofs filesystem can contain 3 sorts of objects: directories, symbolic links and mount traps.  Mount traps are directories with extra properties as described in the next section.

Objects can only be created by the automount daemon: symlinks are created with a regular `symlink` system call, while directories and mount traps are created with `mkdir`.  The determination of whether a directory should be a mount trap is based on a master map. This master map is consulted by autofs to determine which directories are mount points. Mount points can be *direct*/*indirect*/*offset*. On most systems, the default master map is located at */etc/auto.master*.

If neither the *direct* or *offset* mount options are given (so the mount is considered to be *indirect*), then the root directory is always a regular directory, otherwise it is a mount trap when it is empty and a regular directory when not empty.  Note that *direct* and *offset* are treated identically so a concise summary is that the root directory is a mount trap only if the filesystem is mounted *direct* and the root is empty.

Directories created in the root directory are mount traps only if the filesystem is mounted *indirect* and they are empty.

Directories further down the tree depend on the *maxproto* mount option and particularly whether it is less than five or not. When *maxproto* is five, no directories further down the tree are ever mount traps, they are always regular directories.  When the *maxproto* is four (or three), these directories are mount traps precisely when they are empty.

So: non-empty (i.e. non-leaf) directories are never mount traps. Empty directories are sometimes mount traps, and sometimes not depending on where in the tree they are (root, top level, or lower), the *maxproto*, and whether the mount was *indirect* or not.

<a id="rst-mount-traps"></a>

## Mount Traps

A core element of the implementation of autofs is the Mount Traps which are provided by the Linux VFS.  Any directory provided by a filesystem can be designated as a trap.  This involves two separate features that work together to allow autofs to do its job.

**DCACHE_NEED_AUTOMOUNT**

If a dentry has the DCACHE_NEED_AUTOMOUNT flag set (which gets set if the inode has S_AUTOMOUNT set, or can be set directly) then it is (potentially) a mount trap.  Any access to this directory beyond a "`stat`" will (normally) cause the `d_op->d_automount()` dentry operation to be called. The task of this method is to find the filesystem that should be mounted on the directory and to return it.  The VFS is responsible for actually mounting the root of this filesystem on the directory.

autofs doesn't find the filesystem itself but sends a message to the automount daemon asking it to find and mount the filesystem.  The autofs `d_automount` method then waits for the daemon to report that everything is ready.  It will then return "`NULL`" indicating that the mount has already happened.  The VFS doesn't try to mount anything but follows down the mount that is already there.

This functionality is sufficient for some users of mount traps such as NFS which creates traps so that mountpoints on the server can be reflected on the client.  However it is not sufficient for autofs.  As mounting onto a directory is considered to be "beyond a `stat`", the automount daemon would not be able to mount a filesystem on the 'trap' directory without some way to avoid getting caught in the trap.  For that purpose there is another flag.

**DCACHE_MANAGE_TRANSIT**

If a dentry has DCACHE_MANAGE_TRANSIT set then two very different but related behaviours are invoked, both using the `d_op->d_manage()` dentry operation.

Firstly, before checking to see if any filesystem is mounted on the directory, d_manage() will be called with the `rcu_walk` parameter set to `false`.  It may return one of three things:

- A return value of zero indicates that there is nothing special about this dentry and normal checks for mounts and automounts should proceed.

  autofs normally returns zero, but first waits for any expiry (automatic unmounting of the mounted filesystem) to complete.  This avoids races.

- A return value of `-EISDIR` tells the VFS to ignore any mounts on the directory and to not consider calling `->d_automount()`. This effectively disables the **DCACHE_NEED_AUTOMOUNT** flag causing the directory not be a mount trap after all.

  autofs returns this if it detects that the process performing the lookup is the automount daemon and that the mount has been requested but has not yet completed.  How it determines this is discussed later.  This allows the automount daemon not to get caught in the mount trap.

  There is a subtlety here.  It is possible that a second autofs filesystem can be mounted below the first and for both of them to be managed by the same daemon.  For the daemon to be able to mount something on the second it must be able to "walk" down past the first.  This means that d_manage cannot *always* return -EISDIR for the automount daemon.  It must only return it when a mount has been requested, but has not yet completed.

  `d_manage` also returns `-EISDIR` if the dentry shouldn't be a mount trap, either because it is a symbolic link or because it is not empty.

- Any other negative value is treated as an error and returned to the caller.

  autofs can return

  - -ENOENT if the automount daemon failed to mount anything,

  - -ENOMEM if it ran out of memory,

  - -EINTR if a signal arrived while waiting for expiry to complete

  - or any other error sent down by the automount daemon.

The second use case only occurs during an "RCU-walk" and so `rcu_walk` will be set.

An RCU-walk is a fast and lightweight process for walking down a filename path (i.e. it is like running on tip-toes).  RCU-walk cannot cope with all situations so when it finds a difficulty it falls back to "REF-walk", which is slower but more robust.

RCU-walk will never call `->d_automount`; the filesystems must already be mounted or RCU-walk cannot handle the path. To determine if a mount-trap is safe for RCU-walk mode it calls `->d_manage()` with `rcu_walk` set to `true`.

In this case `d_manage()` must avoid blocking and should avoid taking spinlocks if at all possible.  Its sole purpose is to determine if it would be safe to follow down into any mounted directory and the only reason that it might not be is if an expiry of the mount is underway.

In the `rcu_walk` case, `d_manage()` cannot return -EISDIR to tell the VFS that this is a directory that doesn't require d_automount.  If `rcu_walk` sees a dentry with DCACHE_NEED_AUTOMOUNT set but nothing mounted, it *will* fall back to REF-walk.  `d_manage()` cannot make the VFS remain in RCU-walk mode, but can only tell it to get out of RCU-walk mode by returning `-ECHILD`.

So `d_manage()`, when called with `rcu_walk` set, should either return -ECHILD if there is any reason to believe it is unsafe to enter the mounted filesystem, otherwise it should return 0.

autofs will return `-ECHILD` if an expiry of the filesystem has been initiated or is being considered, otherwise it returns 0.

<a id="rst-mountpoint-expiry"></a>

## Mountpoint expiry

The VFS has a mechanism for automatically expiring unused mounts, much as it can expire any unused dentry information from the dcache. This is guided by the MNT_SHRINKABLE flag.  This only applies to mounts that were created by `d_automount()` returning a filesystem to be mounted.  As autofs doesn't return such a filesystem but leaves the mounting to the automount daemon, it must involve the automount daemon in unmounting as well.  This also means that autofs has more control over expiry.

The VFS also supports "expiry" of mounts using the MNT_EXPIRE flag to the `umount` system call.  Unmounting with MNT_EXPIRE will fail unless a previous attempt had been made, and the filesystem has been inactive and untouched since that previous attempt.  autofs does not depend on this but has its own internal tracking of whether filesystems were recently used.  This allows individual names in the autofs directory to expire separately.

With version 4 of the protocol, the automount daemon can try to unmount any filesystems mounted on the autofs filesystem or remove any symbolic links or empty directories any time it likes.  If the unmount or removal is successful the filesystem will be returned to the state it was before the mount or creation, so that any access of the name will trigger normal auto-mount processing.  In particular, `rmdir` and `unlink` do not leave negative entries in the dcache as a normal filesystem would, so an attempt to access a recently-removed object is passed to autofs for handling.

With version 5, this is not safe except for unmounting from top-level directories.  As lower-level directories are never mount traps, other processes will see an empty directory as soon as the filesystem is unmounted.  So it is generally safest to use the autofs expiry protocol described below.

Normally the daemon only wants to remove entries which haven't been used for a while.  For this purpose autofs maintains a "`last_used`" time stamp on each directory or symlink.  For symlinks it genuinely does record the last time the symlink was "used" or followed to find out where it points to.  For directories the field is used slightly differently.  The field is updated at mount time and during expire checks if it is found to be in use (ie. open file descriptor or process working directory) and during path walks. The update done during path walks prevents frequent expire and immediate mount of frequently accessed automounts. But in the case where a GUI continually access or an application frequently scans an autofs directory tree there can be an accumulation of mounts that aren't actually being used. To cater for this case the "`strictexpire`" autofs mount option can be used to avoid the "`last_used`" update on path walk thereby preventing this apparent inability to expire mounts that aren't really in use.

The daemon is able to ask autofs if anything is due to be expired, using an `ioctl` as discussed later.  For a *direct* mount, autofs considers if the entire mount-tree can be unmounted or not.  For an *indirect* mount, autofs considers each of the names in the top level directory to determine if any of those can be unmounted and cleaned up.

There is an option with indirect mounts to consider each of the leaves that has been mounted on instead of considering the top-level names. This was originally intended for compatibility with version 4 of autofs and should be considered as deprecated for Sun Format automount maps. However, it may be used again for amd format mount maps (which are generally indirect maps) because the amd automounter allows for the setting of an expire timeout for individual mounts. But there are some difficulties in making the needed changes for this.

When autofs considers a directory it checks the `last_used` time and compares it with the "timeout" value set when the filesystem was mounted, though this check is ignored in some cases. It also checks if the directory or anything below it is in use.  For symbolic links, only the `last_used` time is ever considered.

If both appear to support expiring the directory or symlink, an action is taken.

There are two ways to ask autofs to consider expiry.  The first is to use the **AUTOFS_IOC_EXPIRE** ioctl.  This only works for indirect mounts.  If it finds something in the root directory to expire it will return the name of that thing.  Once a name has been returned the automount daemon needs to unmount any filesystems mounted below the name normally.  As described above, this is unsafe for non-toplevel mounts in a version-5 autofs.  For this reason the current `automount(8)` does not use this ioctl.

The second mechanism uses either the **AUTOFS_DEV_IOCTL_EXPIRE_CMD** or the **AUTOFS_IOC_EXPIRE_MULTI** ioctl.  This will work for both direct and indirect mounts.  If it selects an object to expire, it will notify the daemon using the notification mechanism described below.  This will block until the daemon acknowledges the expiry notification. This implies that the "`EXPIRE`" ioctl must be sent from a different thread than the one which handles notification.

While the ioctl is blocking, the entry is marked as "expiring" and `d_manage` will block until the daemon affirms that the unmount has completed (together with removing any directories that might have been necessary), or has been aborted.

<a id="rst-communicating-with-autofs-detecting-the-daemon"></a>

## Communicating with autofs: detecting the daemon

There are several forms of communication between the automount daemon and the filesystem.  As we have already seen, the daemon can create and remove directories and symlinks using normal filesystem operations. autofs knows whether a process requesting some operation is the daemon or not based on its process-group id number (see getpgid(1)).

When an autofs filesystem is mounted the pgid of the mounting processes is recorded unless the "pgrp=" option is given, in which case that number is recorded instead.  Any request arriving from a process in that process group is considered to come from the daemon. If the daemon ever has to be stopped and restarted a new pgid can be provided through an ioctl as will be described below.

<a id="rst-communicating-with-autofs-the-event-pipe"></a>

## Communicating with autofs: the event pipe

When an autofs filesystem is mounted, the 'write' end of a pipe must be passed using the 'fd=' mount option.  autofs will write notification messages to this pipe for the daemon to respond to. For version 5, the format of the message is:



```text
struct autofs_v5_packet {
        struct autofs_packet_hdr hdr;
        autofs_wqt_t wait_queue_token;
        __u32 dev;
        __u64 ino;
        __u32 uid;
        __u32 gid;
        __u32 pid;
        __u32 tgid;
        __u32 len;
        char name[NAME_MAX+1];
};
```

And the format of the header is:



```text
struct autofs_packet_hdr {
        int proto_version;              /* Protocol version */
        int type;                       /* Type of packet */
};
```

where the type is one of



```text
autofs_ptype_missing_indirect
autofs_ptype_expire_indirect
autofs_ptype_missing_direct
autofs_ptype_expire_direct
```

so messages can indicate that a name is missing (something tried to access it but it isn't there) or that it has been selected for expiry.

The pipe will be set to "packet mode" (equivalent to passing `O_DIRECT`) to \_pipe2(2)\_ so that a read from the pipe will return at most one packet, and any unread portion of a packet will be discarded.

The `wait_queue_token` is a unique number which can identify a particular request to be acknowledged.  When a message is sent over the pipe the affected dentry is marked as either "active" or "expiring" and other accesses to it block until the message is acknowledged using one of the ioctls below with the relevant `wait_queue_token`.

<a id="rst-communicating-with-autofs-root-directory-ioctls"></a>

## Communicating with autofs: root directory ioctls

The root directory of an autofs filesystem will respond to a number of ioctls.  The process issuing the ioctl must have the CAP_SYS_ADMIN capability, or must be the automount daemon.

The available ioctl commands are:

- - ****AUTOFS_IOC_READY**:**

    a notification has been handled.  The argument to the ioctl command is the "wait_queue_token" number corresponding to the notification being acknowledged.

- - ****AUTOFS_IOC_FAIL**:**

    similar to above, but indicates failure with the error code `ENOENT`.

- - ****AUTOFS_IOC_CATATONIC**:**

    Causes the autofs to enter "catatonic" mode meaning that it stops sending notifications to the daemon. This mode is also entered if a write to the pipe fails.

- - ****AUTOFS_IOC_PROTOVER**:**

    This returns the protocol version in use.

- - ****AUTOFS_IOC_PROTOSUBVER**:**

    Returns the protocol sub-version which is really a version number for the implementation.

- - ****AUTOFS_IOC_SETTIMEOUT**:**

    This passes a pointer to an unsigned long.  The value is used to set the timeout for expiry, and the current timeout value is stored back through the pointer.

- - ****AUTOFS_IOC_ASKUMOUNT**:**

    Returns, in the pointed-to `int`, 1 if the filesystem could be unmounted.  This is only a hint as the situation could change at any instant.  This call can be used to avoid a more expensive full unmount attempt.

- - ****AUTOFS_IOC_EXPIRE**:**

    as described above, this asks if there is anything suitable to expire.  A pointer to a packet:



    ```text
    struct autofs_packet_expire_multi {
            struct autofs_packet_hdr hdr;
            autofs_wqt_t wait_queue_token;
            int len;
            char name[NAME_MAX+1];
    };
    ```

    is required.  This is filled in with the name of something that can be unmounted or removed.  If nothing can be expired, `errno` is set to `EAGAIN`.  Even though a `wait_queue_token` is present in the structure, no "wait queue" is established and no acknowledgment is needed.

- - ****AUTOFS_IOC_EXPIRE_MULTI**:**

    This is similar to **AUTOFS_IOC_EXPIRE** except that it causes notification to be sent to the daemon, and it blocks until the daemon acknowledges. The argument is an integer which can contain two different flags.

    **AUTOFS_EXP_IMMEDIATE** causes `last_used` time to be ignored and objects are expired if the are not in use.

    **AUTOFS_EXP_FORCED** causes the in use status to be ignored and objects are expired even if they are in use. This assumes that the daemon has requested this because it is capable of performing the umount.

    **AUTOFS_EXP_LEAVES** will select a leaf rather than a top-level name to expire.  This is only safe when *maxproto* is 4.

<a id="rst-communicating-with-autofs-char-device-ioctls"></a>

## Communicating with autofs: char-device ioctls

It is not always possible to open the root of an autofs filesystem, particularly a *direct* mounted filesystem.  If the automount daemon is restarted there is no way for it to regain control of existing mounts using any of the above communication channels.  To address this need there is a "miscellaneous" character device (major 10, minor 235) which can be used to communicate directly with the autofs filesystem. It requires CAP_SYS_ADMIN for access.

The 'ioctl's that can be used on this device are described in a separate document `autofs-mount-control.rst`, and are summarised briefly here. Each ioctl is passed a pointer to an `autofs_dev_ioctl` structure:



```text
struct autofs_dev_ioctl {
        __u32 ver_major;
        __u32 ver_minor;
        __u32 size;             /* total size of data passed in
                                 * including this struct */
        __s32 ioctlfd;          /* automount command fd */

        /* Command parameters */
        union {
                struct args_protover            protover;
                struct args_protosubver         protosubver;
                struct args_openmount           openmount;
                struct args_ready               ready;
                struct args_fail                fail;
                struct args_setpipefd           setpipefd;
                struct args_timeout             timeout;
                struct args_requester           requester;
                struct args_expire              expire;
                struct args_askumount           askumount;
                struct args_ismountpoint        ismountpoint;
        };

        char path[];
};
```

For the **OPEN_MOUNT** and **IS_MOUNTPOINT** commands, the target filesystem is identified by the `path`.  All other commands identify the filesystem by the `ioctlfd` which is a file descriptor open on the root, and which can be returned by **OPEN_MOUNT**.

The `ver_major` and `ver_minor` are in/out parameters which check that the requested version is supported, and report the maximum version that the kernel module can support.

Commands are:

- - ****AUTOFS_DEV_IOCTL_VERSION_CMD**:**

    does nothing, except validate and set version numbers.

- - ****AUTOFS_DEV_IOCTL_OPENMOUNT_CMD**:**

    return an open file descriptor on the root of an autofs filesystem.  The filesystem is identified by name and device number, which is stored in `openmount.devid`. Device numbers for existing filesystems can be found in `/proc/self/mountinfo`.

- - ****AUTOFS_DEV_IOCTL_CLOSEMOUNT_CMD**:**

    same as `close(ioctlfd)`.

- - ****AUTOFS_DEV_IOCTL_SETPIPEFD_CMD**:**

    if the filesystem is in catatonic mode, this can provide the write end of a new pipe in `setpipefd.pipefd` to re-establish communication with a daemon. The process group of the calling process is used to identify the daemon.

- - ****AUTOFS_DEV_IOCTL_REQUESTER_CMD**:**

    `path` should be a name within the filesystem that has been auto-mounted on. On successful return, `requester.uid` and `requester.gid` will be the UID and GID of the process which triggered that mount.

- - ****AUTOFS_DEV_IOCTL_ISMOUNTPOINT_CMD**:**

    Check if path is a mountpoint of a particular type - see separate documentation for details.

- **AUTOFS_DEV_IOCTL_PROTOVER_CMD**

- **AUTOFS_DEV_IOCTL_PROTOSUBVER_CMD**

- **AUTOFS_DEV_IOCTL_READY_CMD**

- **AUTOFS_DEV_IOCTL_FAIL_CMD**

- **AUTOFS_DEV_IOCTL_CATATONIC_CMD**

- **AUTOFS_DEV_IOCTL_TIMEOUT_CMD**

- **AUTOFS_DEV_IOCTL_EXPIRE_CMD**

- **AUTOFS_DEV_IOCTL_ASKUMOUNT_CMD**

These all have the same function as the similarly named **AUTOFS_IOC** ioctls, except that **FAIL** can be given an explicit error number in `fail.status` instead of assuming `ENOENT`, and this **EXPIRE** command corresponds to **AUTOFS_IOC_EXPIRE_MULTI**.

<a id="rst-catatonic-mode"></a>

## Catatonic mode

As mentioned, an autofs mount can enter "catatonic" mode.  This happens if a write to the notification pipe fails, or if it is explicitly requested by an `ioctl`.

When entering catatonic mode, the pipe is closed and any pending notifications are acknowledged with the error `ENOENT`.

Once in catatonic mode attempts to access non-existing names will result in `ENOENT` while attempts to access existing directories will be treated in the same way as if they came from the daemon, so mount traps will not fire.

When the filesystem is mounted a \_uid\_ and \_gid\_ can be given which set the ownership of directories and symbolic links.  When the filesystem is in catatonic mode, any process with a matching UID can create directories or symlinks in the root directory, but not in other directories.

Catatonic mode can only be left via the **AUTOFS_DEV_IOCTL_OPENMOUNT_CMD** ioctl on the `/dev/autofs`.

<a id="rst-the-ignore-mount-option"></a>

## The "ignore" mount option

The "ignore" mount option can be used to provide a generic indicator to applications that the mount entry should be ignored when displaying mount information.

In other OSes that provide autofs and that provide a mount list to user space based on the kernel mount list a no-op mount option ("ignore" is the one use on the most common OSes) is allowed so that autofs file system users can optionally use it.

This is intended to be used by user space programs to exclude autofs mounts from consideration when reading the mounts list.

<a id="rst-autofs-name-spaces-and-shared-mounts"></a>

## autofs, name spaces, and shared mounts

With bind mounts and name spaces it is possible for an autofs filesystem to appear at multiple places in one or more filesystem name spaces.  For this to work sensibly, the autofs filesystem should always be mounted "shared". e.g.



```text
mount --make-shared /autofs/mount/point
```

The automount daemon is only able to manage a single mount location for an autofs filesystem and if mounts on that are not 'shared', other locations will not behave as expected.  In particular access to those other locations will likely result in the `ELOOP` error



```text
Too many levels of symbolic links
```

---

# Automount Support

_Peios Kernel / Internals / Filesystems_

> Support is available for filesystems that wish to do automounting support (such as kAFS which can be found in fs/afs/ and NFS in fs/nfs/). This facility includes allowing in-kernel mounts to be performed and mountpoint degradation to be…

<a id="rst-automount-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Support is available for filesystems that wish to do automounting support (such as kAFS which can be found in fs/afs/ and NFS in fs/nfs/). This facility includes allowing in-kernel mounts to be performed and mountpoint degradation to be requested. The latter can also be requested by userspace.

<a id="rst-in-kernel-automounting"></a>

## In-Kernel Automounting

See section "Mount Traps" of  [Documentation/filesystems/autofs.rst](/kernel/internals/filesystems/autofs.md)

Then from userspace, you can just do something like:



```text
[root@andromeda root]# mount -t afs \#root.afs. /afs
[root@andromeda root]# ls /afs
asd  cambridge  cambridge.redhat.com  grand.central.org
[root@andromeda root]# ls /afs/cambridge
afsdoc
[root@andromeda root]# ls /afs/cambridge/afsdoc/
ChangeLog  html  LICENSE  pdf  RELNOTES-1.2.2
```

And then if you look in the mountpoint catalogue, you'll see something like:



```text
[root@andromeda root]# cat /proc/mounts
...
#root.afs. /afs afs rw 0 0
#root.cell. /afs/cambridge.redhat.com afs rw 0 0
#afsdoc. /afs/cambridge.redhat.com/afsdoc afs rw 0 0
```

<a id="rst-automatic-mountpoint-expiry"></a>

## Automatic Mountpoint Expiry

Automatic expiration of mountpoints is easy, provided you've mounted the mountpoint to be expired in the automounting procedure outlined separately.

To do expiration, you need to follow these steps:

> 1. Create at least one list off which the vfsmounts to be expired can be hung.
>
> 2. When a new mountpoint is created in the -&gt;d_automount method, add the mnt to the list using mnt_set_expiry():
>
>
>
>    ```text
>    mnt_set_expiry(newmnt, &afs_vfsmounts);
>    ```
>
> 3. When you want mountpoints to be expired, call mark_mounts_for_expiry() with a pointer to this list. This will process the list, marking every vfsmount thereon for potential expiry on the next call.
>
>    If a vfsmount was already flagged for expiry, and if its usage count is 1 (it's only referenced by its parent vfsmount), then it will be deleted from the namespace and thrown away (effectively unmounted).
>
>    It may prove simplest to simply call this at regular intervals, using some sort of timed event to drive it.

The expiration flag is cleared by calls to mntput. This means that expiration will only happen on the second expiration request after the last time the mountpoint was accessed.

If a mountpoint is moved, it gets removed from the expiration list. If a bind mount is made on an expirable mount, the new vfsmount will not be on the expiration list and will not expire.

If a namespace is copied, all mountpoints contained therein will be copied, and the copies of those that are on an expiration list will be added to the same expiration list.

<a id="rst-userspace-driven-expiry"></a>

## Userspace Driven Expiry

As an alternative, it is possible for userspace to request expiry of any mountpoint (though some will be rejected - the current process's idea of the rootfs for example). It does this by passing the MNT_EXPIRE flag to umount(). This flag is considered incompatible with MNT_FORCE and MNT_DETACH.

If the mountpoint in question is in referenced by something other than umount() or its parent mountpoint, an EBUSY error will be returned and the mountpoint will not be marked for expiration or unmounted.

If the mountpoint was not already marked for expiry at that time, an EAGAIN error will be given and it won't be unmounted.

Otherwise if it was already marked and it wasn't referenced, unmounting will take place as usual.

Again, the expiration flag is cleared every time anything other than umount() looks at a mountpoint.

---

# BeOS filesystem for Linux

_Peios Kernel / Internals / Filesystems_

> Document last updated: Dec 6, 2001

<a id="rst-beos-filesystem-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Document last updated: Dec 6, 2001

<a id="rst-warning"></a>

## Warning

Make sure you understand that this is alpha software.  This means that the implementation is neither complete nor well-tested.

I DISCLAIM ALL RESPONSIBILITY FOR ANY POSSIBLE BAD EFFECTS OF THIS CODE\!

<a id="rst-license"></a>

## License

This software is covered by the GNU General Public License. See the file COPYING for the complete text of the license. Or the GNU website: &lt;[http://www.gnu.org/licenses/licenses.html](<http://www.gnu.org/licenses/licenses.html>)&gt;

<a id="rst-author"></a>

## Author

The largest part of the code written by Will Dyson &lt;[will_dyson@pobox.com](<mailto:will_dyson@pobox.com>)&gt; He has been working on the code since Aug 13, 2001. See the changelog for details.

Original Author: Makoto Kato &lt;[m_kato@ga2.so-net.ne.jp](<mailto:m_kato@ga2.so-net.ne.jp>)&gt;

His original code can still be found at: &lt;[http://hp.vector.co.jp/authors/VA008030/bfs/](<http://hp.vector.co.jp/authors/VA008030/bfs/>)&gt;

Does anyone know of a more current email address for Makoto? He doesn't respond to the address given above...

This filesystem doesn't have a maintainer.

<a id="rst-what-is-this-driver"></a>

## What is this Driver?

This module implements the native filesystem of BeOS [http://www.beincorporated.com/](<http://www.beincorporated.com/>) for the linux 2.4.1 and later kernels. Currently it is a read-only implementation.

<a id="rst-which-is-it-bfs-or-befs"></a>

## Which is it, BFS or BEFS?

Be, Inc said, "BeOS Filesystem is officially called BFS, not BeFS". But Unixware Boot Filesystem is called bfs, too. And they are already in the kernel. Because of this naming conflict, on Linux the BeOS filesystem is called befs.

<a id="rst-how-to-install"></a>

## How to Install

step 1.  Install the BeFS  patch into the source code tree of linux.

Apply the patchfile to your kernel source tree. Assuming that your kernel source is in /foo/bar/linux and the patchfile is called patch-befs-xxx, you would do the following:

> cd /foo/bar/linux patch -p1 &lt; /path/to/patch-befs-xxx

if the patching step fails (i.e. there are rejected hunks), you can try to figure it out yourself (it shouldn't be hard), or mail the maintainer (Will Dyson &lt;[will_dyson@pobox.com](<mailto:will_dyson@pobox.com>)&gt;) for help.

step 2.  Configuration &amp; make kernel

The linux kernel has many compile-time options. Most of them are beyond the scope of this document. I suggest the Kernel-HOWTO document as a good general reference on this topic. [http://www.linuxdocs.org/HOWTOs/Kernel-HOWTO-4.html](<http://www.linuxdocs.org/HOWTOs/Kernel-HOWTO-4.html>)

However, to use the BeFS module, you must enable it at configure time:



```text
cd /foo/bar/linux
make menuconfig (or xconfig)
```

The BeFS module is not a standard part of the linux kernel, so you must first enable support for experimental code under the "Code maturity level" menu.

Then, under the "Filesystems" menu will be an option called "BeFS filesystem (experimental)", or something like that. Enable that option (it is fine to make it a module).

Save your kernel configuration and then build your kernel.

step 3.  Install

See the kernel howto &lt;[http://www.linux.com/howto/Kernel-HOWTO.html](<http://www.linux.com/howto/Kernel-HOWTO.html>)&gt; for instructions on this critical step.

<a id="rst-using-bfs"></a>

## Using BFS

To use the BeOS filesystem, use filesystem type 'befs'.

ex:



```text
mount -t befs /dev/fd0 /beos
```

<a id="rst-mount-options"></a>

## Mount Options


<table>
<tbody>
<tr>
<td>


uid=nnn

</td>
<td>


All files in the partition will be owned by user id nnn.

</td>
</tr>
<tr>
<td>


gid=nnn

</td>
<td>


All files in the partition will be in group nnn.

</td>
</tr>
<tr>
<td>


iocharset=xxx

</td>
<td>


Use xxx as the name of the NLS translation table.

</td>
</tr>
<tr>
<td>


debug

</td>
<td>


The driver will output debugging information to the syslog.

</td>
</tr>
</tbody>
</table>

<a id="rst-how-to-get-latest-version"></a>

## How to Get Latest Version

The latest version is currently available at: &lt;[http://befs-driver.sourceforge.net/](<http://befs-driver.sourceforge.net/>)&gt;

<a id="rst-any-known-bugs"></a>

## Any Known Bugs?

As of Jan 20, 2002:

> None

<a id="rst-special-thanks"></a>

## Special Thanks

Dominic Giampalo ... Writing "Practical file system design with Be filesystem"

Hiroyuki Yamada  ... Testing LinuxPPC.

---

# BFS Filesystem for Linux

_Peios Kernel / Internals / Filesystems_

> The BFS filesystem is used by SCO UnixWare OS for the /stand slice, which usually contains the kernel image and a few other files required for the boot process.

<a id="rst-bfs-filesystem-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The BFS filesystem is used by SCO UnixWare OS for the /stand slice, which usually contains the kernel image and a few other files required for the boot process.

In order to access /stand partition under Linux you obviously need to know the partition number and the kernel must support UnixWare disk slices (CONFIG_UNIXWARE_DISKLABEL config option). However BFS support does not depend on having UnixWare disklabel support because one can also mount BFS filesystem via loopback:



```text
# losetup /dev/loop0 stand.img
# mount -t bfs /dev/loop0 /mnt/stand
```

where stand.img is a file containing the image of BFS filesystem. When you have finished using it and umounted you need to also deallocate /dev/loop0 device by:



```text
# losetup -d /dev/loop0
```

You can simplify mounting by just typing:



```text
# mount -t bfs -o loop stand.img /mnt/stand
```

this will allocate the first available loopback device (and load loop.o kernel module if necessary) automatically. If the loopback driver is not loaded automatically, make sure that you have compiled the module and that modprobe is functioning. Beware that umount will not deallocate /dev/loopN device if /etc/mtab file on your system is a symbolic link to /proc/mounts. You will need to do it manually using "-d" switch of losetup(8). Read losetup(8) manpage for more info.

To create the BFS image under UnixWare you need to find out first which slice contains it. The command prtvtoc(1M) is your friend:



```text
# prtvtoc /dev/rdsk/c0b0t0d0s0
```

(assuming your root disk is on target=0, lun=0, bus=0, controller=0). Then you look for the slice with tag "STAND", which is usually slice 10. With this information you can use dd(1) to create the BFS image:



```text
# umount /stand
# dd if=/dev/rdsk/c0b0t0d0sa of=stand.img bs=512
```

Just in case, you can verify that you have done the right thing by checking the magic number:



```text
# od -Ad -tx4 stand.img | more
```

The first 4 bytes should be 0x1badface.

If you have any patches, questions or suggestions regarding this BFS implementation please contact the author:

Tigran Aivazian &lt;[aivazian.tigran@gmail.com](<mailto:aivazian.tigran@gmail.com>)&gt;

---

# BTRFS

_Peios Kernel / Internals / Filesystems_

> Btrfs is a copy on write filesystem for Linux aimed at implementing advanced features while focusing on fault tolerance, repair and easy administration. Jointly developed by several companies, licensed under the GPL and open for…

<a id="rst-btrfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Btrfs is a copy on write filesystem for Linux aimed at implementing advanced features while focusing on fault tolerance, repair and easy administration. Jointly developed by several companies, licensed under the GPL and open for contribution from anyone.

The main Btrfs features include:

> - Extent based file storage (2^64 max file size)
>
> - Space efficient packing of small files
>
> - Space efficient indexed directories
>
> - Dynamic inode allocation
>
> - Writable snapshots
>
> - Subvolumes (separate internal filesystem roots)
>
> - Object level mirroring and striping
>
> - Checksums on data and metadata (multiple algorithms available)
>
> - Compression (multiple algorithms available)
>
> - Reflink, deduplication
>
> - Scrub (on-line checksum verification)
>
> - Hierarchical quota groups (subvolume and snapshot support)
>
> - Integrated multiple device support, with several raid algorithms
>
> - Offline filesystem check
>
> - Efficient incremental backup and FS mirroring (send/receive)
>
> - Trim/discard
>
> - Online filesystem defragmentation
>
> - Swapfile support
>
> - Zoned mode
>
> - Read/write metadata verification
>
> - Online resize (shrink, grow)

For more information please refer to the documentation site or wiki

> [https://btrfs.readthedocs.io](<https://btrfs.readthedocs.io>)

that maintains information about administration tasks, frequently asked questions, use cases, mount options, comprehensible changelogs, features, manual pages, source code repositories, contacts etc.

---

# Buffer Heads

_Peios Kernel / Internals / Filesystems_

> Linux uses buffer heads to maintain state about individual filesystem blocks. Buffer heads are deprecated and new filesystems should use iomap instead.

<a id="rst-buffer-heads"></a>

Linux uses buffer heads to maintain state about individual filesystem blocks. Buffer heads are deprecated and new filesystems should use iomap instead.

<a id="rst-functions"></a>

## Functions


#### <a id="c-brelse"></a>`brelse()`

```c
void brelse(struct buffer_head *bh)
```

Release a buffer.

**Parameters**

- `struct buffer_head *bh`: The buffer to release.

**Description**

Decrement a buffer_head's reference count.  If **bh** is NULL, this
function is a no-op.

If all buffers on a folio have zero reference count, are clean
and unlocked, and if the folio is unlocked and not under writeback
then [`try_to_free_buffers()`](#c-try_to_free_buffers) may strip the buffers from the folio in
preparation for freeing it (sometimes, rarely, buffers are removed
from a folio but it ends up not being freed, and buffers may later
be reattached).

**Context**

Any context.

#### <a id="c-bforget"></a>`bforget()`

```c
void bforget(struct buffer_head *bh)
```

Discard any dirty data in a buffer.

**Parameters**

- `struct buffer_head *bh`: The buffer to forget.

**Description**

Call this function instead of [`brelse()`](#c-brelse) if the data written to a buffer
no longer needs to be written back.  It will clear the buffer's dirty
flag so writeback of this buffer will be skipped.

**Context**

Any context.

#### <a id="c-__bread"></a>`__bread()`

```c
struct buffer_head * __bread(struct block_device *bdev, sector_t block, unsigned size)
```

Read a block.

**Parameters**

- `struct block_device *bdev`: The block device to read from.
- `sector_t block`: Block number in units of block size.
- `unsigned size`: The block size of this device in bytes.

**Description**

Read a specified block, and return the buffer head that refers
to it.  The memory is allocated from the movable area so that it can
be migrated.  The returned buffer head has its refcount increased.
The caller should call [`brelse()`](#c-brelse) when it has finished with the buffer.

**Context**

May sleep waiting for I/O.

**Return**

NULL if the block was unreadable.

#### <a id="c-get_nth_bh"></a>`get_nth_bh()`

```c
struct buffer_head * get_nth_bh(struct buffer_head *bh, unsigned int count)
```

Get a reference on the n'th buffer after this one.

**Parameters**

- `struct buffer_head *bh`: The buffer to start counting from.
- `unsigned int count`: How many buffers to skip.

**Description**

This is primarily useful for finding the nth buffer in a folio; in
that case you pass the head buffer and the byte offset in the folio
divided by the block size.  It can be used for other purposes, but
it will wrap at the end of the folio rather than returning NULL or
proceeding to the next folio for you.

**Return**

The requested buffer with an elevated refcount.



#### <a id="c-sync_mapping_buffers"></a>`sync_mapping_buffers()`

```c
int sync_mapping_buffers(struct address_space *mapping)
```

write out & wait upon a mapping's "associated" buffers

**Parameters**

- `struct address_space *mapping`: the mapping which wants those buffers written

**Description**

Starts I/O against the buffers at mapping->i_private_list, and waits upon
that I/O.

Basically, this is a convenience function for `fsync()`.
**mapping** is a file or directory which needs those buffers to be written for
a successful `fsync()`.

#### <a id="c-generic_buffers_fsync_noflush"></a>`generic_buffers_fsync_noflush()`

```c
int generic_buffers_fsync_noflush(struct file *file, loff_t start, loff_t end, bool datasync)
```

generic buffer fsync implementation for simple filesystems with no inode lock

**Parameters**

- `struct file *file`: file to synchronize
- `loff_t start`: start offset in bytes
- `loff_t end`: end offset in bytes (inclusive)
- `bool datasync`: only synchronize essential metadata if true

**Description**

This is a generic implementation of the fsync method for simple
filesystems which track all non-inode metadata in the buffers list
hanging off the address_space structure.

#### <a id="c-generic_buffers_fsync"></a>`generic_buffers_fsync()`

```c
int generic_buffers_fsync(struct file *file, loff_t start, loff_t end, bool datasync)
```

generic buffer fsync implementation for simple filesystems with no inode lock

**Parameters**

- `struct file *file`: file to synchronize
- `loff_t start`: start offset in bytes
- `loff_t end`: end offset in bytes (inclusive)
- `bool datasync`: only synchronize essential metadata if true

**Description**

This is a generic implementation of the fsync method for simple
filesystems which track all non-inode metadata in the buffers list
hanging off the address_space structure. This also makes sure that
a device cache flush operation is called at the end.

#### <a id="c-block_dirty_folio"></a>`block_dirty_folio()`

```c
bool block_dirty_folio(struct address_space *mapping, struct folio *folio)
```

Mark a folio as dirty.

**Parameters**

- `struct address_space *mapping`: The address space containing this folio.
- `struct folio *folio`: The folio to mark dirty.

**Description**

Filesystems which use buffer_heads can use this function as their
->dirty_folio implementation.  Some filesystems need to do a little
work before calling this function.  Filesystems which do not use
buffer_heads should call [`filemap_dirty_folio()`](/kernel/internals/core-api/mm-api.md#c-filemap_dirty_folio) instead.

If the folio has buffers, the uptodate buffers are set dirty, to
preserve dirty-state coherency between the folio and the buffers.
Buffers added to a dirty folio are created dirty.

The buffers are dirtied before the folio is dirtied.  There's a small
race window in which writeback may see the folio cleanness but not the
buffer dirtiness.  That's fine.  If this code were to set the folio
dirty before the buffers, writeback could clear the folio dirty flag,
see a bunch of clean buffers and we'd end up with dirty buffers/clean
folio on the dirty folio list.

We use i_private_lock to lock against [`try_to_free_buffers()`](#c-try_to_free_buffers) while
using the folio's buffer list.  This also prevents clean buffers
being added to the folio after it was set dirty.

**Context**

May only be called from process context.  Does not sleep.
Caller must ensure that **folio** cannot be truncated during this call,
typically by holding the folio lock or having a page in the folio
mapped and holding the page table lock.

**Return**

True if the folio was dirtied; false if it was already dirtied.

#### <a id="c-mark_buffer_dirty"></a>`mark_buffer_dirty()`

```c
void mark_buffer_dirty(struct buffer_head *bh)
```

mark a buffer_head as needing writeout

**Parameters**

- `struct buffer_head *bh`: the buffer_head to mark dirty

**Description**

[`mark_buffer_dirty()`](#c-mark_buffer_dirty) will set the dirty bit against the buffer, then set
its backing page dirty, then tag the page as dirty in the page cache
and then attach the address_space's inode to its superblock's dirty
inode list.

[`mark_buffer_dirty()`](#c-mark_buffer_dirty) is atomic.  It takes bh->b_folio->mapping->i_private_lock,
i_pages lock and mapping->host->i_lock.

#### <a id="c-__brelse"></a>`__brelse()`

```c
void __brelse(struct buffer_head *bh)
```

Release a buffer.

**Parameters**

- `struct buffer_head *bh`: The buffer to release.

**Description**

This variant of [`brelse()`](#c-brelse) can be called if **bh** is guaranteed to not be NULL.

#### <a id="c-__bforget"></a>`__bforget()`

```c
void __bforget(struct buffer_head *bh)
```

Discard any dirty data in a buffer.

**Parameters**

- `struct buffer_head *bh`: The buffer to forget.

**Description**

This variant of [`bforget()`](#c-bforget) can be called if **bh** is guaranteed to not
be NULL.

#### <a id="c-bdev_getblk"></a>`bdev_getblk()`

```c
struct buffer_head * bdev_getblk(struct block_device *bdev, sector_t block, unsigned size, gfp_t gfp)
```

Get a buffer_head in a block device's buffer cache.

**Parameters**

- `struct block_device *bdev`: The block device.
- `sector_t block`: The block number.
- `unsigned size`: The size of buffer_heads for this **bdev**.
- `gfp_t gfp`: The memory allocation flags to use.

**Description**

The returned buffer head has its reference count incremented, but is
not locked.  The caller should call [`brelse()`](#c-brelse) when it has finished
with the buffer.  The buffer may not be uptodate.  If needed, the
caller can bring it uptodate either by reading it or overwriting it.

**Return**

The buffer head, or NULL if memory could not be allocated.

#### <a id="c-__bread_gfp"></a>`__bread_gfp()`

```c
struct buffer_head * __bread_gfp(struct block_device *bdev, sector_t block, unsigned size, gfp_t gfp)
```

Read a block.

**Parameters**

- `struct block_device *bdev`: The block device to read from.
- `sector_t block`: Block number in units of block size.
- `unsigned size`: The block size of this device in bytes.
- `gfp_t gfp`: Not page allocation flags; see below.

**Description**

You are not expected to call this function.  You should use one of
`sb_bread()`, `sb_bread_unmovable()` or [`__bread()`](#c-__bread).

Read a specified block, and return the buffer head that refers to it.
If **gfp** is 0, the memory will be allocated using the block device's
default GFP flags.  If **gfp** is __GFP_MOVABLE, the memory may be
allocated from a movable area.  Do not pass in a complete set of
GFP flags.

The returned buffer head has its refcount increased.  The caller should
call [`brelse()`](#c-brelse) when it has finished with the buffer.

**Context**

May sleep waiting for I/O.

**Return**

NULL if the block was unreadable.

#### <a id="c-block_invalidate_folio"></a>`block_invalidate_folio()`

```c
void block_invalidate_folio(struct folio *folio, size_t offset, size_t length)
```

Invalidate part or all of a buffer-backed folio.

**Parameters**

- `struct folio *folio`: The folio which is affected.
- `size_t offset`: start of the range to invalidate
- `size_t length`: length of the range to invalidate

**Description**

[`block_invalidate_folio()`](#c-block_invalidate_folio) is called when all or part of the folio has been
invalidated by a truncate operation.

[`block_invalidate_folio()`](#c-block_invalidate_folio) does not have to release all buffers, but it must
ensure that no dirty buffer is left outside **offset** and that no I/O
is underway against any of the blocks which are outside the truncation
point.  Because the caller is about to free (and possibly reuse) those
blocks on-disk.

#### <a id="c-clean_bdev_aliases"></a>`clean_bdev_aliases()`

```c
void clean_bdev_aliases(struct block_device *bdev, sector_t block, sector_t len)
```

clean a range of buffers in block device

**Parameters**

- `struct block_device *bdev`: Block device to clean buffers in
- `sector_t block`: Start of a range of blocks to clean
- `sector_t len`: Number of blocks to clean

**Description**

We are taking a range of blocks for data and we don't want writeback of any
buffer-cache aliases starting from return from this function and until the
moment when something will explicitly mark the buffer dirty (hopefully that
will not happen until we will free that block ;-) We don't even need to mark
it not-uptodate - nobody can expect anything from a newly allocated buffer
anyway. We used to use `unmap_buffer()` for such invalidation, but that was
wrong. We definitely don't want to mark the alias unmapped, for example - it
would confuse anyone who might pick it with `bread()` afterwards...

Also..  Note that [`bforget()`](#c-bforget) doesn't lock the buffer.  So there can be
writeout I/O going on against recently-freed buffers.  We don't wait on that
I/O in [`bforget()`](#c-bforget) - it's more efficient to wait on the I/O only if we really
need to.  That happens here.

#### <a id="c-try_to_free_buffers"></a>`try_to_free_buffers()`

```c
bool try_to_free_buffers(struct folio *folio)
```

Release buffers attached to this folio.

**Parameters**

- `struct folio *folio`: The folio.

**Description**

If any buffers are in use (dirty, under writeback, elevated refcount),
no buffers will be freed.

If the folio is dirty but all the buffers are clean then we need to
be sure to mark the folio clean as well.  This is because the folio
may be against a block device, and a later reattachment of buffers
to a dirty folio will set *all* buffers dirty.  Which would corrupt
filesystem data on the same device.

The same applies to regular filesystem folios: if all the buffers are
clean then we set the folio clean and proceed.  To do that, we require
total exclusion from [`block_dirty_folio()`](#c-block_dirty_folio).  That is obtained with
i_private_lock.

Exclusion against try_to_free_buffers may be obtained by either
locking the folio or by holding its mapping's i_private_lock.

**Context**

Process context.  **folio** must be locked.  Will not sleep.

**Return**

true if all buffers attached to this folio were freed.

#### <a id="c-bh_uptodate_or_lock"></a>`bh_uptodate_or_lock()`

```c
int bh_uptodate_or_lock(struct buffer_head *bh)
```

Test whether the buffer is uptodate

**Parameters**

- `struct buffer_head *bh`: struct buffer_head

**Description**

Return true if the buffer is up-to-date and false,
with the buffer locked, if not.

#### <a id="c-__bh_read"></a>`__bh_read()`

```c
int __bh_read(struct buffer_head *bh, blk_opf_t op_flags, bool wait)
```

Submit read for a locked buffer

**Parameters**

- `struct buffer_head *bh`: struct buffer_head
- `blk_opf_t op_flags`: appending REQ_OP_* flags besides REQ_OP_READ
- `bool wait`: wait until reading finish

**Description**

Returns zero on success or don't wait, and -EIO on error.

#### <a id="c-__bh_read_batch"></a>`__bh_read_batch()`

```c
void __bh_read_batch(int nr, struct buffer_head *bhs[], blk_opf_t op_flags, bool force_lock)
```

Submit read for a batch of unlocked buffers

**Parameters**

- `int nr`: entry number of the buffer batch
- `struct buffer_head *bhs[]`: a batch of struct buffer_head
- `blk_opf_t op_flags`: appending REQ_OP_* flags besides REQ_OP_READ
- `bool force_lock`: force to get a lock on the buffer if set, otherwise drops any
  buffer that cannot lock.

**Description**

Returns zero on success or don't wait, and -EIO on error.

---

# Ceph Distributed File System

_Peios Kernel / Internals / Filesystems_

> Ceph is a distributed network file system designed to provide good performance, reliability, and scalability.

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-ceph-distributed-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Ceph is a distributed network file system designed to provide good performance, reliability, and scalability.

Basic features include:

> - POSIX semantics
>
> - Seamless scaling from 1 to many thousands of nodes
>
> - High availability and reliability.  No single point of failure.
>
> - N-way replication of data across storage nodes
>
> - Fast recovery from node failures
>
> - Automatic rebalancing of data on node addition/removal
>
> - Easy deployment: most FS components are userspace daemons

Also,

> - Flexible snapshots (on any directory)
>
> - Recursive accounting (nested files, directories, bytes)

In contrast to cluster filesystems like GFS, OCFS2, and GPFS that rely on symmetric access by all clients to shared block devices, Ceph separates data and metadata management into independent server clusters, similar to Lustre.  Unlike Lustre, however, metadata and storage nodes run entirely as user space daemons.  File data is striped across storage nodes in large chunks to distribute workload and facilitate high throughputs.  When storage nodes fail, data is re-replicated in a distributed fashion by the storage nodes themselves (with some minimal coordination from a cluster monitor), making the system extremely efficient and scalable.

Metadata servers effectively form a large, consistent, distributed in-memory cache above the file namespace that is extremely scalable, dynamically redistributes metadata in response to workload changes, and can tolerate arbitrary (well, non-Byzantine) node failures.  The metadata server takes a somewhat unconventional approach to metadata storage to significantly improve performance for common workloads.  In particular, inodes with only a single link are embedded in directories, allowing entire directories of dentries and inodes to be loaded into its cache with a single I/O operation.  The contents of extremely large directories can be fragmented and managed by independent metadata servers, allowing scalable concurrent access.

The system offers automatic data rebalancing/migration when scaling from a small cluster of just a few nodes to many hundreds, without requiring an administrator carve the data set into static volumes or go through the tedious process of migrating data between servers. When the file system approaches full, new nodes can be easily added and things will "just work."

Ceph includes flexible snapshot mechanism that allows a user to create a snapshot on any subdirectory (and its nested contents) in the system.  Snapshot creation and deletion are as simple as 'mkdir .snap/foo' and 'rmdir .snap/foo'.

Snapshot names have two limitations:

- They can not start with an underscore ('\_'), as these names are reserved for internal usage by the MDS.

- They can not exceed 240 characters in size.  This is because the MDS makes use of long snapshot names internally, which follow the format: `_<SNAPSHOT-NAME>_<INODE-NUMBER>`.  Since filenames in general can't have more than 255 characters, and `<node-id>` takes 13 characters, the long snapshot names can take as much as 255 - 1 - 1 - 13 = 240.

Ceph also provides some recursive accounting on directories for nested files and bytes.  You can run the commands:



```text
getfattr -n ceph.dir.rfiles /some/dir
getfattr -n ceph.dir.rbytes /some/dir
```

to get the total number of nested files and their combined size, respectively. This makes the identification of large disk space consumers relatively quick, as no 'du' or similar recursive scan of the file system is required.

Finally, Ceph also allows quotas to be set on any directory in the system. The quota can restrict the number of bytes or the number of files stored beneath that point in the directory hierarchy.  Quotas can be set using extended attributes 'ceph.quota.max_files' and 'ceph.quota.max_bytes', eg:



```text
setfattr -n ceph.quota.max_bytes -v 100000000 /some/dir
getfattr -n ceph.quota.max_bytes /some/dir
```

A limitation of the current quotas implementation is that it relies on the cooperation of the client mounting the file system to stop writers when a limit is reached.  A modified or adversarial client cannot be prevented from writing as much data as it needs.

<a id="rst-mount-syntax"></a>

## Mount Syntax

The basic mount syntax is:



```text
# mount -t ceph user@fsid.fs_name=/[subdir] mnt -o mon_addr=monip1[:port][/monip2[:port]]
```

You only need to specify a single monitor, as the client will get the full list when it connects.  (However, if the monitor you specify happens to be down, the mount won't succeed.)  The port can be left off if the monitor is using the default.  So if the monitor is at 1.2.3.4:



```text
# mount -t ceph cephuser@07fe3187-00d9-42a3-814b-72a4d5e7d5be.cephfs=/ /mnt/ceph -o mon_addr=1.2.3.4
```

is sufficient.  If /sbin/mount.ceph is installed, a hostname can be used instead of an IP address and the cluster FSID can be left out (as the mount helper will fill it in by reading the ceph configuration file):



```text
# mount -t ceph cephuser@cephfs=/ /mnt/ceph -o mon_addr=mon-addr
```

Multiple monitor addresses can be passed by separating each address with a slash (`/`):



```text
# mount -t ceph cephuser@cephfs=/ /mnt/ceph -o mon_addr=192.168.1.100/192.168.1.101
```

When using the mount helper, monitor address can be read from ceph configuration file if available. Note that, the cluster FSID (passed as part of the device string) is validated by checking it with the FSID reported by the monitor.

<a id="rst-mount-options"></a>

## Mount Options

> - **mon_addr=ip_address\[:port\]\[/ip_address\[:port\]\]**
>
>   Monitor address to the cluster. This is used to bootstrap the connection to the cluster. Once connection is established, the monitor addresses in the monitor map are followed.
>
> - **fsid=cluster-id**
>
>   FSID of the cluster (from `ceph fsid` command).
>
> - **ip=A.B.C.D\[:N\]**
>
>   Specify the IP and/or port the client should bind to locally. There is normally not much reason to do this.  If the IP is not specified, the client's IP address is determined by looking at the address its connection to the monitor originates from.
>
> - **wsize=X**
>
>   Specify the maximum write size in bytes.  Default: 64 MB.
>
> - **rsize=X**
>
>   Specify the maximum read size in bytes.  Default: 64 MB.
>
> - **rasize=X**
>
>   Specify the maximum readahead size in bytes.  Default: 8 MB.
>
> - **mount_timeout=X**
>
>   Specify the timeout value for mount (in seconds), in the case of a non-responsive Ceph file system.  The default is 60 seconds.
>
> - **caps_max=X**
>
>   Specify the maximum number of caps to hold. Unused caps are released when number of caps exceeds the limit. The default is 0 (no limit)
>
> - **rbytes**
>
>   When stat() is called on a directory, set st_size to 'rbytes', the summation of file sizes over all files nested beneath that directory.  This is the default.
>
> - **norbytes**
>
>   When stat() is called on a directory, set st_size to the number of entries in that directory.
>
> - **nocrc**
>
>   Disable CRC32C calculation for data writes.  If set, the storage node must rely on TCP's error correction to detect data corruption in the data payload.
>
> - **dcache**
>
>   Use the dcache contents to perform negative lookups and readdir when the client has the entire directory contents in its cache.  (This does not change correctness; the client uses cached metadata only when a lease or capability ensures it is valid.)
>
> - **nodcache**
>
>   Do not use the dcache as above.  This avoids a significant amount of complex code, sacrificing performance without affecting correctness, and is useful for tracking down bugs.
>
> - **noasyncreaddir**
>
>   Do not use the dcache as above for readdir.
>
> - **noquotadf**
>
>   Report overall filesystem usage in statfs instead of using the root directory quota.
>
> - **nocopyfrom**
>
>   Don't use the RADOS 'copy-from' operation to perform remote object copies.  Currently, it's only used in copy_file_range, which will revert to the default VFS implementation if this option is used.
>
> - **recover_session=&lt;no\|clean&gt;**
>
>   Set auto reconnect mode in the case where the client is blocklisted. The available modes are "no" and "clean". The default is "no".
>
>   - no: never attempt to reconnect when client detects that it has been blocklisted. Operations will generally fail after being blocklisted.
>
>   - clean: client reconnects to the ceph cluster automatically when it detects that it has been blocklisted. During reconnect, client drops dirty data/metadata, invalidates page caches and writable file handles. After reconnect, file locks become stale because the MDS loses track of them. If an inode contains any stale file locks, read/write on the inode is not allowed until applications release all stale file locks.

<a id="rst-more-information"></a>

## More Information

- **For more information on Ceph, see the home page at**

  [https://ceph.com/](<https://ceph.com/>)

- **The Linux kernel client source tree is available at**

  - [https://github.com/ceph/ceph-client.git](<https://github.com/ceph/ceph-client.git>)

- **and the source for the full system is at**

  [https://github.com/ceph/ceph.git](<https://github.com/ceph/ceph.git>)

---

# Coda Kernel-Venus Interface

_Peios Kernel / Internals / Filesystems_

> For more information:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-coda-kernel-venus-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> This is one of the technical documents describing a component of Coda -- this document describes the client kernel-Venus interface.

For more information:

> [http://www.coda.cs.cmu.edu](<http://www.coda.cs.cmu.edu>)

For user level software needed to run Coda:

> [ftp://ftp.coda.cs.cmu.edu](<ftp://ftp.coda.cs.cmu.edu>)

To run Coda you need to get a user level cache manager for the client, named Venus, as well as tools to manipulate ACLs, to log in, etc.  The client needs to have the Coda filesystem selected in the kernel configuration.

The server needs a user level server and at present does not depend on kernel support.

> The Venus kernel interface
>
> Peter J. Braam
>
> v1.0, Nov 9, 1997
>
> This document describes the communication between Venus and kernel level filesystem code needed for the operation of the Coda file sys- tem.  This document version is meant to describe the current interface (version 1.0) as well as improvements we envisage.

<!-- Table of Contents

1. Introduction

2. Servicing Coda filesystem calls

3. The message layer

   3.1 Implementation details

4. The interface at the call level

   4.1 Data structures shared by the kernel and Venus
   4.2 The pioctl interface
   4.3 root
   4.4 lookup
   4.5 getattr
   4.6 setattr
   4.7 access
   4.8 create
   4.9 mkdir
   4.10 link
   4.11 symlink
   4.12 remove
   4.13 rmdir
   4.14 readlink
   4.15 open
   4.16 close
   4.17 ioctl
   4.18 rename
   4.19 readdir
   4.20 vget
   4.21 fsync
   4.22 inactive
   4.23 rdwr
   4.24 odymount
   4.25 ody_lookup
   4.26 ody_expand
   4.27 prefetch
   4.28 signal

5. The minicache and downcalls

   5.1 INVALIDATE
   5.2 FLUSH
   5.3 PURGEUSER
   5.4 ZAPFILE
   5.5 ZAPDIR
   5.6 ZAPVNODE
   5.7 PURGEFID
   5.8 REPLACE

6. Initialization and cleanup

   6.1 Requirements -->

<a id="rst-introduction"></a>

## 1. Introduction

> A key component in the Coda Distributed File System is the cache manager, Venus.
>
> When processes on a Coda enabled system access files in the Coda filesystem, requests are directed at the filesystem layer in the operating system. The operating system will communicate with Venus to service the request for the process.  Venus manages a persistent client cache and makes remote procedure calls to Coda file servers and related servers (such as authentication servers) to service these requests it receives from the operating system.  When Venus has serviced a request it replies to the operating system with appropriate return codes, and other data related to the request.  Optionally the kernel support for Coda may maintain a minicache of recently processed requests to limit the number of interactions with Venus.  Venus possesses the facility to inform the kernel when elements from its minicache are no longer valid.
>
> This document describes precisely this communication between the kernel and Venus.  The definitions of so called upcalls and downcalls will be given with the format of the data they handle. We shall also describe the semantic invariants resulting from the calls.
>
> Historically Coda was implemented in a BSD file system in Mach 2.6. The interface between the kernel and Venus is very similar to the BSD VFS interface.  Similar functionality is provided, and the format of the parameters and returned data is very similar to the BSD VFS.  This leads to an almost natural environment for implementing a kernel-level filesystem driver for Coda in a BSD system.  However, other operating systems such as Linux and Windows 95 and NT have virtual filesystem with different interfaces.
>
> To implement Coda on these systems some reverse engineering of the Venus/Kernel protocol is necessary.  Also it came to light that other systems could profit significantly from certain small optimizations and modifications to the protocol. To facilitate this work as well as to make future ports easier, communication between Venus and the kernel should be documented in great detail.  This is the aim of this document.

<a id="rst-servicing-coda-filesystem-calls"></a>

## 2.  Servicing Coda filesystem calls

> The service of a request for a Coda file system service originates in a process P which accessing a Coda file. It makes a system call which traps to the OS kernel. Examples of such calls trapping to the kernel are `read`, `write`, `open`, `close`, `create`, `mkdir`, `rmdir`, `chmod` in a Unix context.  Similar calls exist in the Win32 environment, and are named `CreateFile`.
>
> Generally the operating system handles the request in a virtual filesystem (VFS) layer, which is named I/O Manager in NT and IFS manager in Windows 95.  The VFS is responsible for partial processing of the request and for locating the specific filesystem(s) which will service parts of the request.  Usually the information in the path assists in locating the correct FS drivers.  Sometimes after extensive pre-processing, the VFS starts invoking exported routines in the FS driver.  This is the point where the FS specific processing of the request starts, and here the Coda specific kernel code comes into play.
>
> The FS layer for Coda must expose and implement several interfaces. First and foremost the VFS must be able to make all necessary calls to the Coda FS layer, so the Coda FS driver must expose the VFS interface as applicable in the operating system. These differ very significantly among operating systems, but share features such as facilities to read/write and create and remove objects.  The Coda FS layer services such VFS requests by invoking one or more well defined services offered by the cache manager Venus.  When the replies from Venus have come back to the FS driver, servicing of the VFS call continues and finishes with a reply to the kernel's VFS. Finally the VFS layer returns to the process.
>
> As a result of this design a basic interface exposed by the FS driver must allow Venus to manage message traffic.  In particular Venus must be able to retrieve and place messages and to be notified of the arrival of a new message. The notification must be through a mechanism which does not block Venus since Venus must attend to other tasks even when no messages are waiting or being processed.
>
> **Interfaces of the Coda FS Driver**
>
> Furthermore the FS layer provides for a special path of communication between a user process and Venus, called the pioctl interface. The pioctl interface is used for Coda specific services, such as requesting detailed information about the persistent cache managed by Venus. Here the involvement of the kernel is minimal.  It identifies the calling process and passes the information on to Venus.  When Venus replies the response is passed back to the caller in unmodified form.
>
> Finally Venus allows the kernel FS driver to cache the results from certain services.  This is done to avoid excessive context switches and results in an efficient system.  However, Venus may acquire information, for example from the network which implies that cached information must be flushed or replaced. Venus then makes a downcall to the Coda FS layer to request flushes or updates in the cache.  The kernel FS driver handles such requests synchronously.
>
> Among these interfaces the VFS interface and the facility to place, receive and be notified of messages are platform specific.  We will not go into the calls exported to the VFS layer but we will state the requirements of the message exchange mechanism.

<a id="rst-the-message-layer"></a>

## 3.  The message layer

> At the lowest level the communication between Venus and the FS driver proceeds through messages.  The synchronization between processes requesting Coda file service and Venus relies on blocking and waking up processes.  The Coda FS driver processes VFS- and pioctl-requests on behalf of a process P, creates messages for Venus, awaits replies and finally returns to the caller.  The implementation of the exchange of messages is platform specific, but the semantics have (so far) appeared to be generally applicable.  Data buffers are created by the FS Driver in kernel memory on behalf of P and copied to user memory in Venus.
>
> The FS Driver while servicing P makes upcalls to Venus.  Such an upcall is dispatched to Venus by creating a message structure.  The structure contains the identification of P, the message sequence number, the size of the request and a pointer to the data in kernel memory for the request.  Since the data buffer is re-used to hold the reply from Venus, there is a field for the size of the reply.  A flags field is used in the message to precisely record the status of the message.  Additional platform dependent structures involve pointers to determine the position of the message on queues and pointers to synchronization objects.  In the upcall routine the message structure is filled in, flags are set to 0, and it is placed on the *pending* queue.  The routine calling upcall is responsible for allocating the data buffer; its structure will be described in the next section.
>
> A facility must exist to notify Venus that the message has been created, and implemented using available synchronization objects in the OS. This notification is done in the upcall context of the process P. When the message is on the pending queue, process P cannot proceed in upcall.  The (kernel mode) processing of P in the filesystem request routine must be suspended until Venus has replied.  Therefore the calling thread in P is blocked in upcall.  A pointer in the message structure will locate the synchronization object on which P is sleeping.
>
> Venus detects the notification that a message has arrived, and the FS driver allow Venus to retrieve the message with a getmsg_from_kernel call. This action finishes in the kernel by putting the message on the queue of processing messages and setting flags to READ.  Venus is passed the contents of the data buffer. The getmsg_from_kernel call now returns and Venus processes the request.
>
> At some later point the FS driver receives a message from Venus, namely when Venus calls sendmsg_to_kernel.  At this moment the Coda FS driver looks at the contents of the message and decides if:
>
> - the message is a reply for a suspended thread P.  If so it removes the message from the processing queue and marks the message as WRITTEN.  Finally, the FS driver unblocks P (still in the kernel mode context of Venus) and the sendmsg_to_kernel call returns to Venus.  The process P will be scheduled at some point and continues processing its upcall with the data buffer replaced with the reply from Venus.
>
> - The message is a `downcall`.  A downcall is a request from Venus to the FS Driver. The FS driver processes the request immediately (usually a cache eviction or replacement) and when it finishes sendmsg_to_kernel returns.
>
> Now P awakes and continues processing upcall.  There are some subtleties to take account of. First P will determine if it was woken up in upcall by a signal from some other source (for example an attempt to terminate P) or as is normally the case by Venus in its sendmsg_to_kernel call.  In the normal case, the upcall routine will deallocate the message structure and return.  The FS routine can proceed with its processing.
>
> **Sleeping and IPC arrangements**
>
> In case P is woken up by a signal and not by Venus, it will first look at the flags field.  If the message is not yet READ, the process P can handle its signal without notifying Venus.  If Venus has READ, and the request should not be processed, P can send Venus a signal message to indicate that it should disregard the previous message.  Such signals are put in the queue at the head, and read first by Venus.  If the message is already marked as WRITTEN it is too late to stop the processing.  The VFS routine will now continue.  (-- If a VFS request involves more than one upcall, this can lead to complicated state, an extra field "handle_signals" could be added in the message structure to indicate points of no return have been passed.--)

<a id="rst-implementation-details"></a>

### 3.1.  Implementation details

> The Unix implementation of this mechanism has been through the implementation of a character device associated with Coda.  Venus retrieves messages by doing a read on the device, replies are sent with a write and notification is through the select system call on the file descriptor for the device.  The process P is kept waiting on an interruptible wait queue object.
>
> In Windows NT and the DPMI Windows 95 implementation a DeviceIoControl call is used.  The DeviceIoControl call is designed to copy buffers from user memory to kernel memory with OPCODES. The sendmsg_to_kernel is issued as a synchronous call, while the getmsg_from_kernel call is asynchronous.  Windows EventObjects are used for notification of message arrival.  The process P is kept waiting on a KernelEvent object in NT and a semaphore in Windows 95.

<a id="rst-the-interface-at-the-call-level"></a>

## 4.  The interface at the call level

> This section describes the upcalls a Coda FS driver can make to Venus. Each of these upcalls make use of two structures: inputArgs and outputArgs.   In pseudo BNF form the structures take the following form:
>
>
>
> ```text
> struct inputArgs {
>     u_long opcode;
>     u_long unique;     /* Keep multiple outstanding msgs distinct */
>     u_short pid;                 /* Common to all */
>     u_short pgid;                /* Common to all */
>     struct CodaCred cred;        /* Common to all */
>
>     <union "in" of call dependent parts of inputArgs>
> };
>
> struct outputArgs {
>     u_long opcode;
>     u_long unique;       /* Keep multiple outstanding msgs distinct */
>     u_long result;
>
>     <union "out" of call dependent parts of inputArgs>
> };
> ```
>
> Before going on let us elucidate the role of the various fields. The inputArgs start with the opcode which defines the type of service requested from Venus. There are approximately 30 upcalls at present which we will discuss.   The unique field labels the inputArg with a unique number which will identify the message uniquely.  A process and process group id are passed.  Finally the credentials of the caller are included.
>
> Before delving into the specific calls we need to discuss a variety of data structures shared by the kernel and Venus.

<a id="rst-data-structures-shared-by-the-kernel-and-venus"></a>

### 4.1.  Data structures shared by the kernel and Venus

> The CodaCred structure defines a variety of user and group ids as they are set for the calling process. The vuid_t and vgid_t are 32 bit unsigned integers.  It also defines group membership in an array.  On Unix the CodaCred has proven sufficient to implement good security semantics for Coda but the structure may have to undergo modification for the Windows environment when these mature:
>
>
>
> ```text
> struct CodaCred {
>     vuid_t cr_uid, cr_euid, cr_suid, cr_fsuid; /* Real, effective, set, fs uid */
>     vgid_t cr_gid, cr_egid, cr_sgid, cr_fsgid; /* same for groups */
>     vgid_t cr_groups[NGROUPS];        /* Group membership for caller */
> };
> ```
>
> > [!NOTE]
> >
> > It is questionable if we need CodaCreds in Venus. Finally Venus doesn't know about groups, although it does create files with the default uid/gid.  Perhaps the list of group membership is superfluous.
>
> The next item is the fundamental identifier used to identify Coda files, the ViceFid.  A fid of a file uniquely defines a file or directory in the Coda filesystem within a cell <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1):
>
>
>
> ```text
> typedef struct ViceFid {
>     VolumeId Volume;
>     VnodeId Vnode;
>     Unique_t Unique;
> } ViceFid;
> ```
>
> <a id="rst-footnote-1"></a>
>
>
>
> **[1]** A cell is agroup of Coda servers acting under the aegis of a single system control machine or SCM. See the Coda Administration manual for a detailed description of the role of the SCM.
>
> Each of the constituent fields: VolumeId, VnodeId and Unique_t are unsigned 32 bit integers.  We envisage that a further field will need to be prefixed to identify the Coda cell; this will probably take the form of a Ipv6 size IP address naming the Coda cell through DNS.
>
> The next important structure shared between Venus and the kernel is the attributes of the file.  The following structure is used to exchange information.  It has room for future extensions such as support for device files (currently not present in Coda):
>
>
>
> ```text
> struct coda_timespec {
>         int64_t         tv_sec;         /* seconds */
>         long            tv_nsec;        /* nanoseconds */
> };
>
> struct coda_vattr {
>         enum coda_vtype va_type;        /* vnode type (for create) */
>         u_short         va_mode;        /* files access mode and type */
>         short           va_nlink;       /* number of references to file */
>         vuid_t          va_uid;         /* owner user id */
>         vgid_t          va_gid;         /* owner group id */
>         long            va_fsid;        /* file system id (dev for now) */
>         long            va_fileid;      /* file id */
>         u_quad_t        va_size;        /* file size in bytes */
>         long            va_blocksize;   /* blocksize preferred for i/o */
>         struct coda_timespec va_atime;  /* time of last access */
>         struct coda_timespec va_mtime;  /* time of last modification */
>         struct coda_timespec va_ctime;  /* time file changed */
>         u_long          va_gen;         /* generation number of file */
>         u_long          va_flags;       /* flags defined for file */
>         dev_t           va_rdev;        /* device special file represents */
>         u_quad_t        va_bytes;       /* bytes of disk space held by file */
>         u_quad_t        va_filerev;     /* file modification number */
>         u_int           va_vaflags;     /* operations flags, see below */
>         long            va_spare;       /* remain quad aligned */
> };
> ```

<a id="rst-the-pioctl-interface"></a>

### 4.2.  The pioctl interface

> Coda specific requests can be made by application through the pioctl interface. The pioctl is implemented as an ordinary ioctl on a fictitious file /coda/.CONTROL.  The pioctl call opens this file, gets a file handle and makes the ioctl call. Finally it closes the file.
>
> The kernel involvement in this is limited to providing the facility to open and close and pass the ioctl message and to verify that a path in the pioctl data buffers is a file in a Coda filesystem.
>
> The kernel is handed a data packet of the form:
>
>
>
> ```text
> struct {
>     const char *path;
>     struct ViceIoctl vidata;
>     int follow;
> } data;
> ```
>
> where:
>
>
>
> ```text
> struct ViceIoctl {
>         caddr_t in, out;        /* Data to be transferred in, or out */
>         short in_size;          /* Size of input buffer <= 2K */
>         short out_size;         /* Maximum size of output buffer, <= 2K */
> };
> ```
>
> The path must be a Coda file, otherwise the ioctl upcall will not be made.
>
> > [!NOTE]
> >
> > The data structures and code are a mess.  We need to clean this up.

**We now proceed to document the individual calls**:

<a id="rst-root"></a>

### 4.3.  root

> - **Arguments**
>
>   in
>
>   > empty
>
>   out:
>
>
>
>   ```text
>   struct cfs_root_out {
>       ViceFid VFid;
>   } cfs_root;
>   ```
>
> - **Description**
>
>   This call is made to Venus during the initialization of the Coda filesystem. If the result is zero, the cfs_root structure contains the ViceFid of the root of the Coda filesystem. If a non-zero result is generated, its value is a platform dependent error code indicating the difficulty Venus encountered in locating the root of the Coda filesystem.

<a id="rst-lookup"></a>

### 4.4.  lookup

> - **Summary**
>
>   Find the ViceFid and type of an object in a directory if it exists.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct  cfs_lookup_in {
>       ViceFid     VFid;
>       char        *name;          /* Place holder for data. */
>   } cfs_lookup;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_lookup_out {
>       ViceFid VFid;
>       int vtype;
>   } cfs_lookup;
>   ```
>
> - **Description**
>
>   This call is made to determine the ViceFid and filetype of a directory entry.  The directory entry requested carries name 'name' and Venus will search the directory identified by cfs_lookup_in.VFid. The result may indicate that the name does not exist, or that difficulty was encountered in finding it (e.g. due to disconnection). If the result is zero, the field cfs_lookup_out.VFid contains the targets ViceFid and cfs_lookup_out.vtype the coda_vtype giving the type of object the name designates.
>
> The name of the object is an 8 bit character string of maximum length CFS_MAXNAMLEN, currently set to 256 (including a 0 terminator.)
>
> It is extremely important to realize that Venus bitwise ors the field cfs_lookup.vtype with CFS_NOCACHE to indicate that the object should not be put in the kernel name cache.
>
> > [!NOTE]
> >
> > The type of the vtype is currently wrong.  It should be coda_vtype. Linux does not take note of CFS_NOCACHE.  It should.

<a id="rst-getattr"></a>

### 4.5.  getattr

> Summary Get the attributes of a file.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_getattr_in {
>       ViceFid VFid;
>       struct coda_vattr attr; /* XXXXX */
>   } cfs_getattr;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_getattr_out {
>       struct coda_vattr attr;
>   } cfs_getattr;
>   ```
>
> - **Description**
>
>   This call returns the attributes of the file identified by fid.
>
> - **Errors**
>
>   Errors can occur if the object with fid does not exist, is unaccessible or if the caller does not have permission to fetch attributes.
>
> > [!NOTE]
> >
> > Many kernel FS drivers (Linux, NT and Windows 95) need to acquire the attributes as well as the Fid for the instantiation of an internal "inode" or "FileHandle".  A significant improvement in performance on such systems could be made by combining the lookup and getattr calls both at the Venus/kernel interaction level and at the RPC level.
>
> The vattr structure included in the input arguments is superfluous and should be removed.

<a id="rst-setattr"></a>

### 4.6.  setattr

> - **Summary**
>
>   Set the attributes of a file.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_setattr_in {
>       ViceFid VFid;
>       struct coda_vattr attr;
>   } cfs_setattr;
>   ```
>
>   out
>
>   > empty
>
> - **Description**
>
>   The structure attr is filled with attributes to be changed in BSD style.  Attributes not to be changed are set to -1, apart from vtype which is set to VNON. Other are set to the value to be assigned. The only attributes which the FS driver may request to change are the mode, owner, groupid, atime, mtime and ctime.  The return value indicates success or failure.
>
> - **Errors**
>
>   A variety of errors can occur.  The object may not exist, may be inaccessible, or permission may not be granted by Venus.

<a id="rst-access"></a>

### 4.7.  access

> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_access_in {
>       ViceFid     VFid;
>       int flags;
>   } cfs_access;
>   ```
>
>   out
>
>   > empty
>
> - **Description**
>
>   Verify if access to the object identified by VFid for operations described by flags is permitted.  The result indicates if access will be granted.  It is important to remember that Coda uses ACLs to enforce protection and that ultimately the servers, not the clients enforce the security of the system.  The result of this call will depend on whether a token is held by the user.
>
> - **Errors**
>
>   The object may not exist, or the ACL describing the protection may not be accessible.

<a id="rst-create"></a>

### 4.8.  create

> - **Summary**
>
>   Invoked to create a file
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_create_in {
>       ViceFid VFid;
>       struct coda_vattr attr;
>       int excl;
>       int mode;
>       char        *name;          /* Place holder for data. */
>   } cfs_create;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_create_out {
>       ViceFid VFid;
>       struct coda_vattr attr;
>   } cfs_create;
>   ```
>
> - **Description**
>
>   This upcall is invoked to request creation of a file. The file will be created in the directory identified by VFid, its name will be name, and the mode will be mode.  If excl is set an error will be returned if the file already exists.  If the size field in attr is set to zero the file will be truncated.  The uid and gid of the file are set by converting the CodaCred to a uid using a macro CRTOUID (this macro is platform dependent).  Upon success the VFid and attributes of the file are returned.  The Coda FS Driver will normally instantiate a vnode, inode or file handle at kernel level for the new object.
>
> - **Errors**
>
>   A variety of errors can occur. Permissions may be insufficient. If the object exists and is not a file the error EISDIR is returned under Unix.
>
> > [!NOTE]
> >
> > The packing of parameters is very inefficient and appears to indicate confusion between the system call creat and the VFS operation create. The VFS operation create is only called to create new objects. This create call differs from the Unix one in that it is not invoked to return a file descriptor. The truncate and exclusive options, together with the mode, could simply be part of the mode as it is under Unix.  There should be no flags argument; this is used in open (2) to return a file descriptor for READ or WRITE mode.
>
> The attributes of the directory should be returned too, since the size and mtime changed.

<a id="rst-mkdir"></a>

### 4.9.  mkdir

> - **Summary**
>
>   Create a new directory.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_mkdir_in {
>       ViceFid     VFid;
>       struct coda_vattr attr;
>       char        *name;          /* Place holder for data. */
>   } cfs_mkdir;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_mkdir_out {
>       ViceFid VFid;
>       struct coda_vattr attr;
>   } cfs_mkdir;
>   ```
>
> - **Description**
>
>   This call is similar to create but creates a directory. Only the mode field in the input parameters is used for creation. Upon successful creation, the attr returned contains the attributes of the new directory.
>
> - **Errors**
>
>   As for create.
>
> > [!NOTE]
> >
> > The input parameter should be changed to mode instead of attributes.
>
> The attributes of the parent should be returned since the size and mtime changes.

<a id="rst-link"></a>

### 4.10.  link

> - **Summary**
>
>   Create a link to an existing file.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_link_in {
>       ViceFid sourceFid;          /* cnode to link *to* */
>       ViceFid destFid;            /* Directory in which to place link */
>       char        *tname;         /* Place holder for data. */
>   } cfs_link;
>   ```
>
>   out
>
>   > empty
>
> - **Description**
>
>   This call creates a link to the sourceFid in the directory identified by destFid with name tname.  The source must reside in the target's parent, i.e. the source must be have parent destFid, i.e. Coda does not support cross directory hard links.  Only the return value is relevant.  It indicates success or the type of failure.
>
> - **Errors**
>
>   The usual errors can occur.

<a id="rst-symlink"></a>

### 4.11.  symlink

> - **Summary**
>
>   create a symbolic link
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_symlink_in {
>       ViceFid     VFid;          /* Directory to put symlink in */
>       char        *srcname;
>       struct coda_vattr attr;
>       char        *tname;
>   } cfs_symlink;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Create a symbolic link. The link is to be placed in the directory identified by VFid and named tname.  It should point to the pathname srcname.  The attributes of the newly created object are to be set to attr.
>
> > [!NOTE]
> >
> > The attributes of the target directory should be returned since its size changed.

<a id="rst-remove"></a>

### 4.12.  remove

> - **Summary**
>
>   Remove a file
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_remove_in {
>       ViceFid     VFid;
>       char        *name;          /* Place holder for data. */
>   } cfs_remove;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Remove file named cfs_remove_in.name in directory identified by   VFid.
>
> > [!NOTE]
> >
> > The attributes of the directory should be returned since its mtime and size may change.

<a id="rst-rmdir"></a>

### 4.13.  rmdir

> - **Summary**
>
>   Remove a directory
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_rmdir_in {
>       ViceFid     VFid;
>       char        *name;          /* Place holder for data. */
>   } cfs_rmdir;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Remove the directory with name 'name' from the directory identified by VFid.
>
> > [!NOTE]
> >
> > The attributes of the parent directory should be returned since its mtime and size may change.

<a id="rst-readlink"></a>

### 4.14.  readlink

> - **Summary**
>
>   Read the value of a symbolic link.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_readlink_in {
>       ViceFid VFid;
>   } cfs_readlink;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_readlink_out {
>       int count;
>       caddr_t     data;           /* Place holder for data. */
>   } cfs_readlink;
>   ```
>
> - **Description**
>
>   This routine reads the contents of symbolic link identified by VFid into the buffer data.  The buffer data must be able to hold any name up to CFS_MAXNAMLEN (PATH or NAM??).
>
> - **Errors**
>
>   No unusual errors.

<a id="rst-open"></a>

### 4.15.  open

> - **Summary**
>
>   Open a file.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_open_in {
>       ViceFid     VFid;
>       int flags;
>   } cfs_open;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_open_out {
>       dev_t       dev;
>       ino_t       inode;
>   } cfs_open;
>   ```
>
> - **Description**
>
>   This request asks Venus to place the file identified by VFid in its cache and to note that the calling process wishes to open it with flags as in open(2).  The return value to the kernel differs for Unix and Windows systems.  For Unix systems the Coda FS Driver is informed of the device and inode number of the container file in the fields dev and inode.  For Windows the path of the container file is returned to the kernel.
>
> > [!NOTE]
> >
> > Currently the cfs_open_out structure is not properly adapted to deal with the Windows case.  It might be best to implement two upcalls, one to open aiming at a container file name, the other at a container file inode.

<a id="rst-close"></a>

### 4.16.  close

> - **Summary**
>
>   Close a file, update it on the servers.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_close_in {
>       ViceFid     VFid;
>       int flags;
>   } cfs_close;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Close the file identified by VFid.
>
> > [!NOTE]
> >
> > The flags argument is bogus and not used.  However, Venus' code has room to deal with an execp input field, probably this field should be used to inform Venus that the file was closed but is still memory mapped for execution.  There are comments about fetching versus not fetching the data in Venus vproc_vfscalls.  This seems silly.  If a file is being closed, the data in the container file is to be the new data.  Here again the execp flag might be in play to create confusion: currently Venus might think a file can be flushed from the cache when it is still memory mapped.  This needs to be understood.

<a id="rst-ioctl"></a>

### 4.17.  ioctl

> - **Summary**
>
>   Do an ioctl on a file. This includes the pioctl interface.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_ioctl_in {
>       ViceFid VFid;
>       int cmd;
>       int len;
>       int rwflag;
>       char *data;                 /* Place holder for data. */
>   } cfs_ioctl;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_ioctl_out {
>       int len;
>       caddr_t     data;           /* Place holder for data. */
>   } cfs_ioctl;
>   ```
>
> - **Description**
>
>   Do an ioctl operation on a file.  The command, len and data arguments are filled as usual.  flags is not used by Venus.
>
> > [!NOTE]
> >
> > Another bogus parameter.  flags is not used.  What is the business about PREFETCHING in the Venus code?

<a id="rst-rename"></a>

### 4.18.  rename

> - **Summary**
>
>   Rename a fid.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_rename_in {
>       ViceFid     sourceFid;
>       char        *srcname;
>       ViceFid destFid;
>       char        *destname;
>   } cfs_rename;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Rename the object with name srcname in directory sourceFid to destname in destFid.   It is important that the names srcname and destname are 0 terminated strings.  Strings in Unix kernels are not always null terminated.

<a id="rst-readdir"></a>

### 4.19.  readdir

> - **Summary**
>
>   Read directory entries.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_readdir_in {
>       ViceFid     VFid;
>       int count;
>       int offset;
>   } cfs_readdir;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_readdir_out {
>       int size;
>       caddr_t     data;           /* Place holder for data. */
>   } cfs_readdir;
>   ```
>
> - **Description**
>
>   Read directory entries from VFid starting at offset and read at most count bytes.  Returns the data in data and returns the size in size.
>
> > [!NOTE]
> >
> > This call is not used.  Readdir operations exploit container files.  We will re-evaluate this during the directory revamp which is about to take place.

<a id="rst-vget"></a>

### 4.20.  vget

> - **Summary**
>
>   instructs Venus to do an FSDB-&gt;Get.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_vget_in {
>       ViceFid VFid;
>   } cfs_vget;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_vget_out {
>       ViceFid VFid;
>       int vtype;
>   } cfs_vget;
>   ```
>
> - **Description**
>
>   This upcall asks Venus to do a get operation on an fsobj labelled by VFid.
>
> > [!NOTE]
> >
> > This operation is not used.  However, it is extremely useful since it can be used to deal with read/write memory mapped files. These can be "pinned" in the Venus cache using vget and released with inactive.

<a id="rst-fsync"></a>

### 4.21.  fsync

> - **Summary**
>
>   Tell Venus to update the RVM attributes of a file.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_fsync_in {
>       ViceFid VFid;
>   } cfs_fsync;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   Ask Venus to update RVM attributes of object VFid. This should be called as part of kernel level fsync type calls.  The result indicates if the syncing was successful.
>
> > [!NOTE]
> >
> > Linux does not implement this call. It should.

<a id="rst-inactive"></a>

### 4.22.  inactive

> - **Summary**
>
>   Tell Venus a vnode is no longer in use.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_inactive_in {
>       ViceFid VFid;
>   } cfs_inactive;
>   ```
>
>   out
>
>   > none
>
> - **Description**
>
>   This operation returns EOPNOTSUPP.
>
> > [!NOTE]
> >
> > This should perhaps be removed.

<a id="rst-rdwr"></a>

### 4.23.  rdwr

> - **Summary**
>
>   Read or write from a file
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct cfs_rdwr_in {
>       ViceFid     VFid;
>       int rwflag;
>       int count;
>       int offset;
>       int ioflag;
>       caddr_t     data;           /* Place holder for data. */
>   } cfs_rdwr;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct cfs_rdwr_out {
>       int rwflag;
>       int count;
>       caddr_t     data;   /* Place holder for data. */
>   } cfs_rdwr;
>   ```
>
> - **Description**
>
>   This upcall asks Venus to read or write from a file.
>
> > [!NOTE]
> >
> > It should be removed since it is against the Coda philosophy that read/write operations never reach Venus.  I have been told the operation does not work.  It is not currently used.

<a id="rst-odymount"></a>

### 4.24.  odymount

> - **Summary**
>
>   Allows mounting multiple Coda "filesystems" on one Unix mount point.
>
> - **Arguments**
>
>   in:
>
>
>
>   ```text
>   struct ody_mount_in {
>       char        *name;          /* Place holder for data. */
>   } ody_mount;
>   ```
>
>   out:
>
>
>
>   ```text
>   struct ody_mount_out {
>       ViceFid VFid;
>   } ody_mount;
>   ```
>
> - **Description**
>
>   Asks Venus to return the rootfid of a Coda system named name.  The fid is returned in VFid.
>
> > [!NOTE]
> >
> > This call was used by David for dynamic sets.  It should be removed since it causes a jungle of pointers in the VFS mounting area. It is not used by Coda proper.  Call is not implemented by Venus.

<a id="rst-ody-lookup"></a>

### 4.25.  ody_lookup

> - **Summary**
>
>   Looks up something.
>
> - **Arguments**
>
>   in
>
>   > irrelevant
>
>   out
>
>   > irrelevant
>
> > [!NOTE]
> >
> > Gut it. Call is not implemented by Venus.

<a id="rst-ody-expand"></a>

### 4.26.  ody_expand

> - **Summary**
>
>   expands something in a dynamic set.
>
> - **Arguments**
>
>   in
>
>   > irrelevant
>
>   out
>
>   > irrelevant
>
> > [!NOTE]
> >
> > Gut it. Call is not implemented by Venus.

<a id="rst-prefetch"></a>

### 4.27.  prefetch

> - **Summary**
>
>   Prefetch a dynamic set.
>
> Arguments
>
> > in
> >
> > > Not documented.
> >
> > out
> >
> > > Not documented.
>
> - **Description**
>
>   Venus worker.cc has support for this call, although it is noted that it doesn't work.  Not surprising, since the kernel does not have support for it. (ODY_PREFETCH is not a defined operation).
>
> > [!NOTE]
> >
> > Gut it. It isn't working and isn't used by Coda.

<a id="rst-signal"></a>

### 4.28.  signal

> - **Summary**
>
>   Send Venus a signal about an upcall.
>
> - **Arguments**
>
>   in
>
>   > none
>
>   out
>
>   > not applicable.
>
> - **Description**
>
>   This is an out-of-band upcall to Venus to inform Venus that the calling process received a signal after Venus read the message from the input queue.  Venus is supposed to clean up the operation.
>
> - **Errors**
>
>   No reply is given.
>
> > [!NOTE]
> >
> > We need to better understand what Venus needs to clean up and if it is doing this correctly.  Also we need to handle multiple upcall per system call situations correctly.  It would be important to know what state changes in Venus take place after an upcall for which the kernel is responsible for notifying Venus to clean up (e.g. open definitely is such a state change, but many others are maybe not).

<a id="rst-the-minicache-and-downcalls"></a>

## 5.  The minicache and downcalls

> The Coda FS Driver can cache results of lookup and access upcalls, to limit the frequency of upcalls.  Upcalls carry a price since a process context switch needs to take place.  The counterpart of caching the information is that Venus will notify the FS Driver that cached entries must be flushed or renamed.
>
> The kernel code generally has to maintain a structure which links the internal file handles (called vnodes in BSD, inodes in Linux and FileHandles in Windows) with the ViceFid's which Venus maintains.  The reason is that frequent translations back and forth are needed in order to make upcalls and use the results of upcalls.  Such linking objects are called cnodes.
>
> The current minicache implementations have cache entries which record the following:
>
> 1. the name of the file
>
> 2. the cnode of the directory containing the object
>
> 3. a list of CodaCred's for which the lookup is permitted.
>
> 4. the cnode of the object
>
> The lookup call in the Coda FS Driver may request the cnode of the desired object from the cache, by passing its name, directory and the CodaCred's of the caller.  The cache will return the cnode or indicate that it cannot be found.  The Coda FS Driver must be careful to invalidate cache entries when it modifies or removes objects.
>
> When Venus obtains information that indicates that cache entries are no longer valid, it will make a downcall to the kernel.  Downcalls are intercepted by the Coda FS Driver and lead to cache invalidations of the kind described below.  The Coda FS Driver does not return an error unless the downcall data could not be read into kernel memory.

<a id="rst-invalidate"></a>

### 5.1.  INVALIDATE

> No information is available on this call.

<a id="rst-flush"></a>

### 5.2.  FLUSH

> - **Arguments**
>
>   None
>
> - **Summary**
>
>   Flush the name cache entirely.
>
> - **Description**
>
>   Venus issues this call upon startup and when it dies. This is to prevent stale cache information being held.  Some operating systems allow the kernel name cache to be switched off dynamically. When this is done, this downcall is made.

<a id="rst-purgeuser"></a>

### 5.3.  PURGEUSER

> - **Arguments**
>
>
>
>   ```text
>   struct cfs_purgeuser_out {/* CFS_PURGEUSER is a venus->kernel call */
>       struct CodaCred cred;
>   } cfs_purgeuser;
>   ```
>
> - **Description**
>
>   Remove all entries in the cache carrying the Cred.  This call is issued when tokens for a user expire or are flushed.

<a id="rst-zapfile"></a>

### 5.4.  ZAPFILE

> - **Arguments**
>
>
>
>   ```text
>   struct cfs_zapfile_out {  /* CFS_ZAPFILE is a venus->kernel call */
>       ViceFid CodaFid;
>   } cfs_zapfile;
>   ```
>
> - **Description**
>
>   Remove all entries which have the (dir vnode, name) pair. This is issued as a result of an invalidation of cached attributes of a vnode.
>
> > [!NOTE]
> >
> > Call is not named correctly in NetBSD and Mach.  The minicache zapfile routine takes different arguments. Linux does not implement the invalidation of attributes correctly.

<a id="rst-zapdir"></a>

### 5.5.  ZAPDIR

> - **Arguments**
>
>
>
>   ```text
>   struct cfs_zapdir_out {   /* CFS_ZAPDIR is a venus->kernel call */
>       ViceFid CodaFid;
>   } cfs_zapdir;
>   ```
>
> - **Description**
>
>   Remove all entries in the cache lying in a directory CodaFid, and all children of this directory. This call is issued when Venus receives a callback on the directory.

<a id="rst-zapvnode"></a>

### 5.6.  ZAPVNODE

> - **Arguments**
>
>
>
>   ```text
>   struct cfs_zapvnode_out { /* CFS_ZAPVNODE is a venus->kernel call */
>       struct CodaCred cred;
>       ViceFid VFid;
>   } cfs_zapvnode;
>   ```
>
> - **Description**
>
>   Remove all entries in the cache carrying the cred and VFid as in the arguments. This downcall is probably never issued.

<a id="rst-purgefid"></a>

### 5.7.  PURGEFID

> - **Arguments**
>
>
>
>   ```text
>   struct cfs_purgefid_out { /* CFS_PURGEFID is a venus->kernel call */
>       ViceFid CodaFid;
>   } cfs_purgefid;
>   ```
>
> - **Description**
>
>   Flush the attribute for the file. If it is a dir (odd vnode), purge its children from the namecache and remove the file from the namecache.

<a id="rst-replace"></a>

### 5.8.  REPLACE

> - **Summary**
>
>   Replace the Fid's for a collection of names.
>
> - **Arguments**
>
>
>
>   ```text
>   struct cfs_replace_out { /* cfs_replace is a venus->kernel call */
>       ViceFid NewFid;
>       ViceFid OldFid;
>   } cfs_replace;
>   ```
>
> - **Description**
>
>   This routine replaces a ViceFid in the name cache with another.  It is added to allow Venus during reintegration to replace locally allocated temp fids while disconnected with global fids even when the reference counts on those fids are not zero.

<a id="rst-initialization-and-cleanup"></a>

## 6.  Initialization and cleanup

> This section gives brief hints as to desirable features for the Coda FS Driver at startup and upon shutdown or Venus failures.  Before entering the discussion it is useful to repeat that the Coda FS Driver maintains the following data:
>
> 1. message queues
>
> 2. cnodes
>
> 3. name cache entries
>
>    The name cache entries are entirely private to the driver, so they can easily be manipulated.   The message queues will generally have clear points of initialization and destruction.  The cnodes are much more delicate.  User processes hold reference counts in Coda filesystems and it can be difficult to clean up the cnodes.
>
> It can expect requests through:
>
> 1. the message subsystem
>
> 2. the VFS layer
>
> 3. pioctl interface
>
>    Currently the pioctl passes through the VFS for Coda so we can treat these similarly.

<a id="rst-requirements"></a>

### 6.1.  Requirements

> The following requirements should be accommodated:
>
> 1. The message queues should have open and close routines.  On Unix the opening of the character devices are such routines.
>
> > - Before opening, no messages can be placed.
> >
> > - Opening will remove any old messages still pending.
> >
> > - Close will notify any sleeping processes that their upcall cannot be completed.
> >
> > - Close will free all memory allocated by the message queues.
>
> 2. At open the namecache shall be initialized to empty state.
>
> 3. Before the message queues are open, all VFS operations will fail. Fortunately this can be achieved by making sure than mounting the Coda filesystem cannot succeed before opening.
>
> 4. After closing of the queues, no VFS operations can succeed.  Here one needs to be careful, since a few operations (lookup, read/write, readdir) can proceed without upcalls.  These must be explicitly blocked.
>
> 5. Upon closing the namecache shall be flushed and disabled.
>
> 6. All memory held by cnodes can be freed without relying on upcalls.
>
> 7. Unmounting the file system can be done without relying on upcalls.
>
> 8. Mounting the Coda filesystem should fail gracefully if Venus cannot get the rootfid or the attributes of the rootfid.  The latter is best implemented by Venus fetching these objects before attempting to mount.
>
> > [!NOTE]
> >
> > NetBSD in particular but also Linux have not implemented the above requirements fully.  For smooth operation this needs to be corrected.

---

# Configfs - Userspace-driven Kernel Object Configuration

_Peios Kernel / Internals / Filesystems_

> Joel Becker <joel.becker@oracle.com>

<a id="rst-configfs-userspace-driven-kernel-object-configuration"></a>

Joel Becker &lt;[joel.becker@oracle.com](<mailto:joel.becker@oracle.com>)&gt;

Updated: 31 March 2005

- **Copyright (c) 2005 Oracle Corporation,**

  Joel Becker &lt;[joel.becker@oracle.com](<mailto:joel.becker@oracle.com>)&gt;

<a id="rst-what-is-configfs"></a>

## What is configfs?

configfs is a ram-based filesystem that provides the converse of sysfs's functionality.  Where sysfs is a filesystem-based view of kernel objects, configfs is a filesystem-based manager of kernel objects, or config_items.

With sysfs, an object is created in kernel (for example, when a device is discovered) and it is registered with sysfs.  Its attributes then appear in sysfs, allowing userspace to read the attributes via readdir(3)/read(2).  It may allow some attributes to be modified via write(2).  The important point is that the object is created and destroyed in kernel, the kernel controls the lifecycle of the sysfs representation, and sysfs is merely a window on all this.

A configfs config_item is created via an explicit userspace operation: mkdir(2).  It is destroyed via rmdir(2).  The attributes appear at mkdir(2) time, and can be read or modified via read(2) and write(2). As with sysfs, readdir(3) queries the list of items and/or attributes. symlink(2) can be used to group items together.  Unlike sysfs, the lifetime of the representation is completely driven by userspace.  The kernel modules backing the items must respond to this.

Both sysfs and configfs can and should exist together on the same system.  One is not a replacement for the other.

<a id="rst-using-configfs"></a>

## Using configfs

configfs can be compiled as a module or into the kernel.  You can access it by doing:



```text
mount -t configfs none /config
```

The configfs tree will be empty unless client modules are also loaded. These are modules that register their item types with configfs as subsystems.  Once a client subsystem is loaded, it will appear as a subdirectory (or more than one) under /config.  Like sysfs, the configfs tree is always there, whether mounted on /config or not.

An item is created via mkdir(2).  The item's attributes will also appear at this time.  readdir(3) can determine what the attributes are, read(2) can query their default values, and write(2) can store new values.  Don't mix more than one attribute in one attribute file.

There are two types of configfs attributes:

- Normal attributes, which similar to sysfs attributes, are small ASCII text files, with a maximum size of one page (PAGE_SIZE, 4096 on i386).  Preferably only one value per file should be used, and the same caveats from sysfs apply. Configfs expects write(2) to store the entire buffer at once.  When writing to normal configfs attributes, userspace processes should first read the entire file, modify the portions they wish to change, and then write the entire buffer back.

- Binary attributes, which are somewhat similar to sysfs binary attributes, but with a few slight changes to semantics.  The PAGE_SIZE limitation does not apply, but the whole binary item must fit in single kernel vmalloc'ed buffer. The write(2) calls from user space are buffered, and the attributes' write_bin_attribute method will be invoked on the final close, therefore it is imperative for user-space to check the return code of close(2) in order to verify that the operation finished successfully. To avoid a malicious user OOMing the kernel, there's a per-binary attribute maximum buffer value.

When an item needs to be destroyed, remove it with rmdir(2).  An item cannot be destroyed if any other item has a link to it (via symlink(2)).  Links can be removed via unlink(2).

<a id="rst-configuring-fakenbd-an-example"></a>

## Configuring FakeNBD: an Example

Imagine there's a Network Block Device (NBD) driver that allows you to access remote block devices.  Call it FakeNBD.  FakeNBD uses configfs for its configuration.  Obviously, there will be a nice program that sysadmins use to configure FakeNBD, but somehow that program has to tell the driver about it.  Here's where configfs comes in.

When the FakeNBD driver is loaded, it registers itself with configfs. readdir(3) sees this just fine:



```text
# ls /config
fakenbd
```

A fakenbd connection can be created with mkdir(2).  The name is arbitrary, but likely the tool will make some use of the name.  Perhaps it is a uuid or a disk name:



```text
# mkdir /config/fakenbd/disk1
# ls /config/fakenbd/disk1
target device rw
```

The target attribute contains the IP address of the server FakeNBD will connect to.  The device attribute is the device on the server. Predictably, the rw attribute determines whether the connection is read-only or read-write:



```text
# echo 10.0.0.1 > /config/fakenbd/disk1/target
# echo /dev/sda1 > /config/fakenbd/disk1/device
# echo 1 > /config/fakenbd/disk1/rw
```

That's it.  That's all there is.  Now the device is configured, via the shell no less.

<a id="rst-coding-with-configfs"></a>

## Coding With configfs

Every object in configfs is a config_item.  A config_item reflects an object in the subsystem.  It has attributes that match values on that object.  configfs handles the filesystem representation of that object and its attributes, allowing the subsystem to ignore all but the basic show/store interaction.

Items are created and destroyed inside a config_group.  A group is a collection of items that share the same attributes and operations. Items are created by mkdir(2) and removed by rmdir(2), but configfs handles that.  The group has a set of operations to perform these tasks

A subsystem is the top level of a client module.  During initialization, the client module registers the subsystem with configfs, the subsystem appears as a directory at the top of the configfs filesystem.  A subsystem is also a config_group, and can do everything a config_group can.

<a id="rst-struct-config-item"></a>

## struct config_item



```text
struct config_item {
        char                    *ci_name;
        char                    ci_namebuf[UOBJ_NAME_LEN];
        struct kref             ci_kref;
        struct list_head        ci_entry;
        struct config_item      *ci_parent;
        struct config_group     *ci_group;
        struct config_item_type *ci_type;
        struct dentry           *ci_dentry;
};

void config_item_init(struct config_item *);
void config_item_init_type_name(struct config_item *,
                                const char *name,
                                struct config_item_type *type);
struct config_item *config_item_get(struct config_item *);
void config_item_put(struct config_item *);
```

Generally, struct config_item is embedded in a container structure, a structure that actually represents what the subsystem is doing.  The config_item portion of that structure is how the object interacts with configfs.

Whether statically defined in a source file or created by a parent config_group, a config_item must have one of the \_init() functions called on it.  This initializes the reference count and sets up the appropriate fields.

All users of a config_item should have a reference on it via config_item_get(), and drop the reference when they are done via config_item_put().

By itself, a config_item cannot do much more than appear in configfs. Usually a subsystem wants the item to display and/or store attributes, among other things.  For that, it needs a type.

<a id="rst-struct-config-item-type"></a>

## struct config_item_type



```text
struct configfs_item_operations {
        void (*release)(struct config_item *);
        int (*allow_link)(struct config_item *src,
                          struct config_item *target);
        void (*drop_link)(struct config_item *src,
                         struct config_item *target);
};

struct config_item_type {
        struct module                           *ct_owner;
        struct configfs_item_operations         *ct_item_ops;
        struct configfs_group_operations        *ct_group_ops;
        struct configfs_attribute               **ct_attrs;
        struct configfs_bin_attribute           **ct_bin_attrs;
};
```

The most basic function of a config_item_type is to define what operations can be performed on a config_item.  All items that have been allocated dynamically will need to provide the ct_item_ops-&gt;release() method.  This method is called when the config_item's reference count reaches zero.

<a id="rst-struct-configfs-attribute"></a>

## struct configfs_attribute



```text
struct configfs_attribute {
        char                    *ca_name;
        struct module           *ca_owner;
        umode_t                  ca_mode;
        ssize_t (*show)(struct config_item *, char *);
        ssize_t (*store)(struct config_item *, const char *, size_t);
};
```

When a config_item wants an attribute to appear as a file in the item's configfs directory, it must define a configfs_attribute describing it. It then adds the attribute to the NULL-terminated array config_item_type-&gt;ct_attrs.  When the item appears in configfs, the attribute file will appear with the configfs_attribute-&gt;ca_name filename.  configfs_attribute-&gt;ca_mode specifies the file permissions.

If an attribute is readable and provides a -&gt;show method, that method will be called whenever userspace asks for a read(2) on the attribute.  If an attribute is writable and provides a -&gt;store  method, that method will be called whenever userspace asks for a write(2) on the attribute.

<a id="rst-struct-configfs-bin-attribute"></a>

## struct configfs_bin_attribute



```text
struct configfs_bin_attribute {
        struct configfs_attribute       cb_attr;
        void                            *cb_private;
        size_t                          cb_max_size;
};
```

The binary attribute is used when the one needs to use binary blob to appear as the contents of a file in the item's configfs directory. To do so add the binary attribute to the NULL-terminated array config_item_type-&gt;ct_bin_attrs, and the item appears in configfs, the attribute file will appear with the configfs_bin_attribute-&gt;cb_attr.ca_name filename.  configfs_bin_attribute-&gt;cb_attr.ca_mode specifies the file permissions. The cb_private member is provided for use by the driver, while the cb_max_size member specifies the maximum amount of vmalloc buffer to be used.

If binary attribute is readable and the config_item provides a ct_item_ops-&gt;read_bin_attribute() method, that method will be called whenever userspace asks for a read(2) on the attribute.  The converse will happen for write(2). The reads/writes are buffered so only a single read/write will occur; the attributes' need not concern itself with it.

<a id="rst-struct-config-group"></a>

## struct config_group

A config_item cannot live in a vacuum.  The only way one can be created is via mkdir(2) on a config_group.  This will trigger creation of a child item:



```text
struct config_group {
        struct config_item              cg_item;
        struct list_head                cg_children;
        struct configfs_subsystem       *cg_subsys;
        struct list_head                default_groups;
        struct list_head                group_entry;
};

void config_group_init(struct config_group *group);
void config_group_init_type_name(struct config_group *group,
                                 const char *name,
                                 struct config_item_type *type);
```

The config_group structure contains a config_item.  Properly configuring that item means that a group can behave as an item in its own right. However, it can do more: it can create child items or groups.  This is accomplished via the group operations specified on the group's config_item_type:



```text
struct configfs_group_operations {
        struct config_item *(*make_item)(struct config_group *group,
                                         const char *name);
        struct config_group *(*make_group)(struct config_group *group,
                                           const char *name);
        void (*disconnect_notify)(struct config_group *group,
                                  struct config_item *item);
        void (*drop_item)(struct config_group *group,
                          struct config_item *item);
};
```

A group creates child items by providing the ct_group_ops-&gt;make_item() method.  If provided, this method is called from mkdir(2) in the group's directory.  The subsystem allocates a new config_item (or more likely, its container structure), initializes it, and returns it to configfs.  Configfs will then populate the filesystem tree to reflect the new item.

If the subsystem wants the child to be a group itself, the subsystem provides ct_group_ops-&gt;make_group().  Everything else behaves the same, using the group \_init() functions on the group.

Finally, when userspace calls rmdir(2) on the item or group, ct_group_ops-&gt;drop_item() is called.  As a config_group is also a config_item, it is not necessary for a separate drop_group() method. The subsystem must config_item_put() the reference that was initialized upon item allocation.  If a subsystem has no work to do, it may omit the ct_group_ops-&gt;drop_item() method, and configfs will call config_item_put() on the item on behalf of the subsystem.

- **Important:**

  drop_item() is void, and as such cannot fail.  When rmdir(2) is called, configfs WILL remove the item from the filesystem tree (assuming that it has no children to keep it busy).  The subsystem is responsible for responding to this.  If the subsystem has references to the item in other threads, the memory is safe.  It may take some time for the item to actually disappear from the subsystem's usage.  But it is gone from configfs.

When drop_item() is called, the item's linkage has already been torn down.  It no longer has a reference on its parent and has no place in the item hierarchy.  If a client needs to do some cleanup before this teardown happens, the subsystem can implement the ct_group_ops-&gt;disconnect_notify() method.  The method is called after configfs has removed the item from the filesystem view but before the item is removed from its parent group.  Like drop_item(), disconnect_notify() is void and cannot fail.  Client subsystems should not drop any references here, as they still must do it in drop_item().

A config_group cannot be removed while it still has child items.  This is implemented in the configfs rmdir(2) code.  -&gt;drop_item() will not be called, as the item has not been dropped.  rmdir(2) will fail, as the directory is not empty.

<a id="rst-struct-configfs-subsystem"></a>

## struct configfs_subsystem

A subsystem must register itself, usually at module_init time.  This tells configfs to make the subsystem appear in the file tree:



```text
struct configfs_subsystem {
        struct config_group     su_group;
        struct mutex            su_mutex;
};

int configfs_register_subsystem(struct configfs_subsystem *subsys);
void configfs_unregister_subsystem(struct configfs_subsystem *subsys);
```

A subsystem consists of a toplevel config_group and a mutex. The group is where child config_items are created.  For a subsystem, this group is usually defined statically.  Before calling configfs_register_subsystem(), the subsystem must have initialized the group via the usual group \_init() functions, and it must also have initialized the mutex.

When the register call returns, the subsystem is live, and it will be visible via configfs.  At that point, mkdir(2) can be called and the subsystem must be ready for it.

<a id="rst-an-example"></a>

## An Example

The best example of these basic concepts is the simple_children subsystem/group and the simple_child item in samples/configfs/configfs_sample.c. It shows a trivial object displaying and storing an attribute, and a simple group creating and destroying these children.

<a id="rst-hierarchy-navigation-and-the-subsystem-mutex"></a>

## Hierarchy Navigation and the Subsystem Mutex

There is an extra bonus that configfs provides.  The config_groups and config_items are arranged in a hierarchy due to the fact that they appear in a filesystem.  A subsystem is NEVER to touch the filesystem parts, but the subsystem might be interested in this hierarchy.  For this reason, the hierarchy is mirrored via the config_group-&gt;cg_children and config_item-&gt;ci_parent structure members.

A subsystem can navigate the cg_children list and the ci_parent pointer to see the tree created by the subsystem.  This can race with configfs' management of the hierarchy, so configfs uses the subsystem mutex to protect modifications.  Whenever a subsystem wants to navigate the hierarchy, it must do so under the protection of the subsystem mutex.

A subsystem will be prevented from acquiring the mutex while a newly allocated item has not been linked into this hierarchy.   Similarly, it will not be able to acquire the mutex while a dropping item has not yet been unlinked.  This means that an item's ci_parent pointer will never be NULL while the item is in configfs, and that an item will only be in its parent's cg_children list for the same duration.  This allows a subsystem to trust ci_parent and cg_children while they hold the mutex.

<a id="rst-item-aggregation-via-symlink-2"></a>

## Item Aggregation Via symlink(2)

configfs provides a simple group via the group-&gt;item parent/child relationship.  Often, however, a larger environment requires aggregation outside of the parent/child connection.  This is implemented via symlink(2).

A config_item may provide the ct_item_ops-&gt;allow_link() and ct_item_ops-&gt;drop_link() methods.  If the -&gt;allow_link() method exists, symlink(2) may be called with the config_item as the source of the link. These links are only allowed between configfs config_items.  Any symlink(2) attempt outside the configfs filesystem will be denied.

When symlink(2) is called, the source config_item's -&gt;allow_link() method is called with itself and a target item.  If the source item allows linking to target item, it returns 0.  A source item may wish to reject a link if it only wants links to a certain type of object (say, in its own subsystem).

When unlink(2) is called on the symbolic link, the source item is notified via the -&gt;drop_link() method.  Like the -&gt;drop_item() method, this is a void function and cannot return failure.  The subsystem is responsible for responding to the change.

A config_item cannot be removed while it links to any other item, nor can it be removed while an item links to it.  Dangling symlinks are not allowed in configfs.

<a id="rst-automatically-created-subgroups"></a>

## Automatically Created Subgroups

A new config_group may want to have two types of child config_items. While this could be codified by magic names in -&gt;make_item(), it is much more explicit to have a method whereby userspace sees this divergence.

Rather than have a group where some items behave differently than others, configfs provides a method whereby one or many subgroups are automatically created inside the parent at its creation.  Thus, mkdir("parent") results in "parent", "parent/subgroup1", up through "parent/subgroupN".  Items of type 1 can now be created in "parent/subgroup1", and items of type N can be created in "parent/subgroupN".

These automatic subgroups, or default groups, do not preclude other children of the parent group.  If ct_group_ops-&gt;make_group() exists, other child groups can be created on the parent group directly.

A configfs subsystem specifies default groups by adding them using the configfs_add_default_group() function to the parent config_group structure.  Each added group is populated in the configfs tree at the same time as the parent group.  Similarly, they are removed at the same time as the parent.  No extra notification is provided.  When a -&gt;drop_item() method call notifies the subsystem the parent group is going away, it also means every default group child associated with that parent group.

As a consequence of this, default groups cannot be removed directly via rmdir(2).  They also are not considered when rmdir(2) on the parent group is checking for children.

<a id="rst-dependent-subsystems"></a>

## Dependent Subsystems

Sometimes other drivers depend on particular configfs items.  For example, ocfs2 mounts depend on a heartbeat region item.  If that region item is removed with rmdir(2), the ocfs2 mount must BUG or go readonly.  Not happy.

configfs provides two additional API calls: configfs_depend_item() and configfs_undepend_item().  A client driver can call configfs_depend_item() on an existing item to tell configfs that it is depended on.  configfs will then return -EBUSY from rmdir(2) for that item.  When the item is no longer depended on, the client driver calls configfs_undepend_item() on it.

These API cannot be called underneath any configfs callbacks, as they will conflict.  They can block and allocate.  A client driver probably shouldn't calling them of its own gumption.  Rather it should be providing an API that external subsystems call.

How does this work?  Imagine the ocfs2 mount process.  When it mounts, it asks for a heartbeat region item.  This is done via a call into the heartbeat code.  Inside the heartbeat code, the region item is looked up.  Here, the heartbeat code calls configfs_depend_item().  If it succeeds, then heartbeat knows the region is safe to give to ocfs2. If it fails, it was being torn down anyway, and heartbeat can gracefully pass up an error.

---

# Cramfs - cram a filesystem onto a small ROM

_Peios Kernel / Internals / Filesystems_

> cramfs is designed to be simple and small, and to compress things well.

<a id="rst-cramfs-cram-a-filesystem-onto-a-small-rom"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

cramfs is designed to be simple and small, and to compress things well.

It uses the zlib routines to compress a file one page at a time, and allows random page access.  The meta-data is not compressed, but is expressed in a very terse representation to make it use much less diskspace than traditional filesystems.

You can't write to a cramfs filesystem (making it compressible and compact also makes it \_very\_ hard to update on-the-fly), so you have to create the disk image with the "mkcramfs" utility.

<a id="rst-usage-notes"></a>

## Usage Notes

File sizes are limited to less than 16MB.

Maximum filesystem size is a little over 256MB.  (The last file on the filesystem is allowed to extend past 256MB.)

Only the low 8 bits of gid are stored.  The current version of mkcramfs simply truncates to 8 bits, which is a potential security issue.

Hard links are supported, but hard linked files will still have a link count of 1 in the cramfs image.

Cramfs directories have no `.` or `..` entries.  Directories (like every other file on cramfs) always have a link count of 1.  (There's no need to use -noleaf in `find`, btw.)

No timestamps are stored in a cramfs, so these default to the epoch (1970 GMT).  Recently-accessed files may have updated timestamps, but the update lasts only as long as the inode is cached in memory, after which the timestamp reverts to 1970, i.e. moves backwards in time.

Currently, cramfs must be written and read with architectures of the same endianness, and can be read only by kernels with PAGE_SIZE == 4096.  At least the latter of these is a bug, but it hasn't been decided what the best fix is.  For the moment if you have larger pages you can just change the \#define in mkcramfs.c, so long as you don't mind the filesystem becoming unreadable to future kernels.

<a id="rst-memory-mapped-cramfs-image"></a>

## Memory Mapped cramfs image

The CRAMFS_MTD Kconfig option adds support for loading data directly from a physical linear memory range (usually non volatile memory like Flash) instead of going through the block device layer. This saves some memory since no intermediate buffering is necessary to hold the data before decompressing.

And when data blocks are kept uncompressed and properly aligned, they will automatically be mapped directly into user space whenever possible providing eXecute-In-Place (XIP) from ROM of read-only segments. Data segments mapped read-write (hence they have to be copied to RAM) may still be compressed in the cramfs image in the same file along with non compressed read-only segments. Both MMU and no-MMU systems are supported. This is particularly handy for tiny embedded systems with very tight memory constraints.

The location of the cramfs image in memory is system dependent. You must know the proper physical address where the cramfs image is located and configure an MTD device for it. Also, that MTD device must be supported by a map driver that implements the "point" method. Examples of such MTD drivers are cfi_cmdset_0001 (Intel/Sharp CFI flash) or physmap (Flash device in physical memory map). MTD partitions based on such devices are fine too. Then that device should be specified with the "mtd:" prefix as the mount device argument. For example, to mount the MTD device named "fs_partition" on the /mnt directory:



```text
$ mount -t cramfs mtd:fs_partition /mnt
```

To boot a kernel with this as root filesystem, suffice to specify something like "root=mtd:fs_partition" on the kernel command line.

<a id="rst-tools"></a>

## Tools

A version of mkcramfs that can take advantage of the latest capabilities described above can be found here:

[https://github.com/npitre/cramfs-tools](<https://github.com/npitre/cramfs-tools>)

<a id="rst-for-usr-share-magic"></a>

## For /usr/share/magic


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


ulelong 0x28cd3d45

</td>
<td>


Linux cramfs offset 0

</td>
</tr>
<tr>
<td>


&gt;4

</td>
<td>


ulelong x

</td>
<td>


size %d

</td>
</tr>
<tr>
<td>


&gt;8

</td>
<td>


ulelong x

</td>
<td>


flags 0x%x

</td>
</tr>
<tr>
<td>


&gt;12

</td>
<td>


ulelong x

</td>
<td>


future 0x%x

</td>
</tr>
<tr>
<td>


&gt;16

</td>
<td>


string  &gt;0

</td>
<td>


signature "%.16s"

</td>
</tr>
<tr>
<td>


&gt;32

</td>
<td>


ulelong x

</td>
<td>


fsid.crc 0x%x

</td>
</tr>
<tr>
<td>


&gt;36

</td>
<td>


ulelong x

</td>
<td>


fsid.edition %d

</td>
</tr>
<tr>
<td>


&gt;40

</td>
<td>


ulelong x

</td>
<td>


fsid.blocks %d

</td>
</tr>
<tr>
<td>


&gt;44

</td>
<td>


ulelong x

</td>
<td>


fsid.files %d

</td>
</tr>
<tr>
<td>


&gt;48

</td>
<td>


string  &gt;0

</td>
<td>


name "%.16s"

</td>
</tr>
<tr>
<td>


512

</td>
<td>


ulelong 0x28cd3d45

</td>
<td>


Linux cramfs offset 512

</td>
</tr>
<tr>
<td>


&gt;516

</td>
<td>


ulelong x

</td>
<td>


size %d

</td>
</tr>
<tr>
<td>


&gt;520

</td>
<td>


ulelong x

</td>
<td>


flags 0x%x

</td>
</tr>
<tr>
<td>


&gt;524

</td>
<td>


ulelong x

</td>
<td>


future 0x%x

</td>
</tr>
<tr>
<td>


&gt;528

</td>
<td>


string  &gt;0

</td>
<td>


signature "%.16s"

</td>
</tr>
<tr>
<td>


&gt;544

</td>
<td>


ulelong x

</td>
<td>


fsid.crc 0x%x

</td>
</tr>
<tr>
<td>


&gt;548

</td>
<td>


ulelong x

</td>
<td>


fsid.edition %d

</td>
</tr>
<tr>
<td>


&gt;552

</td>
<td>


ulelong x

</td>
<td>


fsid.blocks %d

</td>
</tr>
<tr>
<td>


&gt;556

</td>
<td>


ulelong x

</td>
<td>


fsid.files %d

</td>
</tr>
<tr>
<td>


&gt;560

</td>
<td>


string  &gt;0

</td>
<td>


name "%.16s"

</td>
</tr>
</tbody>
</table>

<a id="rst-hacker-notes"></a>

## Hacker Notes

See fs/cramfs/README for filesystem layout and implementation notes.

---

# Direct Access for files

_Peios Kernel / Internals / Filesystems_

> The page cache is usually used to buffer reads and writes to files. It is also used to provide the pages which are mapped into userspace by a call to mmap.

<a id="rst-direct-access-for-files"></a>

<a id="rst-motivation"></a>

## Motivation

The page cache is usually used to buffer reads and writes to files. It is also used to provide the pages which are mapped into userspace by a call to mmap.

For block devices that are memory-like, the page cache pages would be unnecessary copies of the original storage.  The `DAX` code removes the extra copy by performing reads and writes directly to the storage device. For file mappings, the storage device is mapped directly into userspace.

<a id="rst-usage"></a>

## Usage

If you have a block device which supports `DAX`, you can make a filesystem on it as usual.  The `DAX` code currently only supports files with a block size equal to your kernel's `PAGE_SIZE`, so you may need to specify a block size when creating the filesystem.

Currently 5 filesystems support `DAX`: ext2, ext4, xfs, virtiofs and erofs. Enabling `DAX` on them is different.

<a id="rst-enabling-dax-on-ext2-and-erofs"></a>

## Enabling DAX on ext2 and erofs

When mounting the filesystem, use the `-o dax` option on the command line or add 'dax' to the options in `/etc/fstab`.  This works to enable `DAX` on all files within the filesystem.  It is equivalent to the `-o dax=always` behavior below.

<a id="rst-enabling-dax-on-xfs-and-ext4"></a>

## Enabling DAX on xfs and ext4

<a id="rst-summary"></a>

## Summary

> 1. There exists an in-kernel file access mode flag `S_DAX` that corresponds to the statx flag `STATX_ATTR_DAX`.  See the manpage for statx(2) for details about this access mode.
>
> 2. There exists a persistent flag `FS_XFLAG_DAX` that can be applied to regular files and directories. This advisory flag can be set or cleared at any time, but doing so does not immediately affect the `S_DAX` state.
>
> 3. If the persistent `FS_XFLAG_DAX` flag is set on a directory, this flag will be inherited by all regular files and subdirectories that are subsequently created in this directory. Files and subdirectories that exist at the time this flag is set or cleared on the parent directory are not modified by this modification of the parent directory.
>
> 4. There exist dax mount options which can override `FS_XFLAG_DAX` in the setting of the `S_DAX` flag.  Given underlying storage which supports `DAX` the following hold:
>
>    `-o dax=inode`  means "follow `FS_XFLAG_DAX`" and is the default.
>
>    `-o dax=never`  means "never set `S_DAX`, ignore `FS_XFLAG_DAX`."
>
>    `-o dax=always` means "always set `S_DAX` ignore `FS_XFLAG_DAX`."
>
>    `-o dax`      is a legacy option which is an alias for `dax=always`.
>
>    > [!WARNING]
>    >
>    > The option `-o dax` may be removed in the future so `-o dax=always` is the preferred method for specifying this behavior.
>
>    > [!NOTE]
>    >
>    > Modifications to and the inheritance behavior of `FS_XFLAG_DAX` remain the same even when the filesystem is mounted with a dax option.  However, in-core inode state (`S_DAX`) will be overridden until the filesystem is remounted with dax=inode and the inode is evicted from kernel memory.
>
> 5. The `S_DAX` policy can be changed via:
>
>    - **a)** Setting the parent directory `FS_XFLAG_DAX` as needed before files are created
>
>    - **b)** Setting the appropriate dax="foo" mount option
>
>    - **c)** Changing the `FS_XFLAG_DAX` flag on existing regular files and directories.  This has runtime constraints and limitations that are described in 6) below.
>
> 6. When changing the `S_DAX` policy via toggling the persistent `FS_XFLAG_DAX` flag, the change to existing regular files won't take effect until the files are closed by all processes.

<a id="rst-details"></a>

## Details

There are 2 per-file dax flags.  One is a persistent inode setting (`FS_XFLAG_DAX`) and the other is a volatile flag indicating the active state of the feature (`S_DAX`).

`FS_XFLAG_DAX` is preserved within the filesystem.  This persistent config setting can be set, cleared and/or queried using the ``FS_IOC_FS`[`GS``\]\`ETXATTR\` ioctl (see ioctl_xfs_fsgetxattr(2)) or an utility such as 'xfs_io'.

New files and directories automatically inherit `FS_XFLAG_DAX` from their parent directory **when created**.  Therefore, setting `FS_XFLAG_DAX` at directory creation time can be used to set a default behavior for an entire sub-tree.

To clarify inheritance, here are 3 examples:

Example A:



```shell
mkdir -p a/b/c
xfs_io -c 'chattr +x' a
mkdir a/b/c/d
mkdir a/e

------[outcome]------

dax: a,e
no dax: b,c,d
```

Example B:



```shell
mkdir a
xfs_io -c 'chattr +x' a
mkdir -p a/b/c/d

------[outcome]------

dax: a,b,c,d
no dax:
```

Example C:



```shell
mkdir -p a/b/c
xfs_io -c 'chattr +x' c
mkdir a/b/c/d

------[outcome]------

dax: c,d
no dax: a,b
```

The current enabled state (`S_DAX`) is set when a file inode is instantiated in memory by the kernel.  It is set based on the underlying media support, the value of `FS_XFLAG_DAX` and the filesystem's dax mount option.

statx can be used to query `S_DAX`.

> [!NOTE]
>
> That only regular files will ever have `S_DAX` set and therefore statx will never indicate that `S_DAX` is set on directories.

Setting the `FS_XFLAG_DAX` flag (specifically or through inheritance) occurs even if the underlying media does not support dax and/or the filesystem is overridden with a mount option.

<a id="rst-enabling-dax-on-virtiofs"></a>

## Enabling DAX on virtiofs

The semantic of DAX on virtiofs is basically equal to that on ext4 and xfs, except that when '-o dax=inode' is specified, virtiofs client derives the hint whether DAX shall be enabled or not from virtiofs server through FUSE protocol, rather than the persistent `FS_XFLAG_DAX` flag. That is, whether DAX shall be enabled or not is completely determined by virtiofs server, while virtiofs server itself may deploy various algorithm making this decision, e.g. depending on the persistent `FS_XFLAG_DAX` flag on the host.

It is still supported to set or clear persistent `FS_XFLAG_DAX` flag inside guest, but it is not guaranteed that DAX will be enabled or disabled for corresponding file then. Users inside guest still need to call statx(2) and check the statx flag `STATX_ATTR_DAX` to see if DAX is enabled for this file.

<a id="rst-implementation-tips-for-block-driver-writers"></a>

## Implementation Tips for Block Driver Writers

To support `DAX` in your block driver, implement the 'direct_access' block device operation.  It is used to translate the sector number (expressed in units of 512-byte sectors) to a page frame number (pfn) that identifies the physical page for the memory.  It also returns a kernel virtual address that can be used to access the memory.

The direct_access method takes a 'size' parameter that indicates the number of bytes being requested.  The function should return the number of bytes that can be contiguously accessed at that offset.  It may also return a negative errno if an error occurs.

In order to support this method, the storage must be byte-accessible by the CPU at all times.  If your device uses paging techniques to expose a large amount of memory through a smaller window, then you cannot implement direct_access.  Equally, if your device can occasionally stall the CPU for an extended period, you should also not attempt to implement direct_access.

These block devices may be used for inspiration: - pmem: NVDIMM persistent memory driver

<a id="rst-implementation-tips-for-filesystem-writers"></a>

## Implementation Tips for Filesystem Writers

Filesystem support consists of:

- Adding support to mark inodes as being `DAX` by setting the `S_DAX` flag in i_flags

- Implementing -&gt;read_iter and -&gt;write_iter operations which use `dax_iomap_rw()` when inode has `S_DAX` flag set

- Implementing an mmap file operation for `DAX` files which sets the `VM_MIXEDMAP` and `VM_HUGEPAGE` flags on the `VMA`, and setting the vm_ops to include handlers for fault, pmd_fault, page_mkwrite, pfn_mkwrite. These handlers should probably call `dax_iomap_fault()` passing the appropriate fault size and iomap operations.

- Calling `iomap_zero_range()` passing appropriate iomap operations instead of `block_truncate_page()` for `DAX` files

- Ensuring that there is sufficient locking between reads, writes, truncates and page faults

The iomap handlers for allocating blocks must make sure that allocated blocks are zeroed out and converted to written extents before being returned to avoid exposure of uninitialized data through mmap.

These filesystems may be used for inspiration:

> [!NOTE]
>
> **See also**
>
> ext2: see [Documentation/filesystems/ext2.rst](/kernel/internals/filesystems/ext2.md)

> [!NOTE]
>
> **See also**
>
> xfs:  see [Documentation/admin-guide/xfs.rst](/kernel/administration/admin-guide/filesystems/xfs.md)

> [!NOTE]
>
> **See also**
>
> ext4: see Documentation/filesystems/ext4/

<a id="rst-handling-media-errors"></a>

## Handling Media Errors

The libnvdimm subsystem stores a record of known media error locations for each pmem block device (in gendisk-&gt;badblocks). If we fault at such location, or one with a latent error not yet discovered, the application can expect to receive a `SIGBUS`. Libnvdimm also allows clearing of these errors by simply writing the affected sectors (through the pmem driver, and if the underlying NVDIMM supports the clear_poison DSM defined by ACPI).

Since `DAX` IO normally doesn't go through the `driver/bio` path, applications or sysadmins have an option to restore the lost data from a prior `backup/inbuilt` redundancy in the following ways:

1. Delete the affected file, and restore from a backup (sysadmin route): This will free the filesystem blocks that were being used by the file, and the next time they're allocated, they will be zeroed first, which happens through the driver, and will clear bad sectors.

2. Truncate or hole-punch the part of the file that has a bad-block (at least an entire aligned sector has to be hole-punched, but not necessarily an entire filesystem block).

These are the two basic paths that allow `DAX` filesystems to continue operating in the presence of media errors. More robust error recovery mechanisms can be built on top of this in the future, for example, involving redundancy/mirroring provided at the block layer through DM, or additionally, at the filesystem level. These would have to rely on the above two tenets, that error clearing can happen either by sending an IO through the driver, or zeroing (also through the driver).

<a id="rst-shortcomings"></a>

## Shortcomings

Even if the kernel or its modules are stored on a filesystem that supports `DAX` on a block device that supports `DAX`, they will still be copied into RAM.

The DAX code does not work correctly on architectures which have virtually mapped caches such as ARM, MIPS and SPARC.

Calling `get_user_pages()` on a range of user memory that has been mmapped from a `DAX` file will fail when there are no 'struct page' to describe those pages.  This problem has been addressed in some device drivers by adding optional struct page support for pages under the control of the driver (see `CONFIG_NVDIMM_PFN` in `drivers/nvdimm` for an example of how to do this). In the non struct page cases `O_DIRECT` reads/writes to those memory ranges from a non-`DAX` file will fail

> [!NOTE]
>
> `O_DIRECT` reads/writes \_of a `DAX` file do work, it is the memory that is being accessed that is key here).  Other things that will not work in the non struct page case include RDMA, `sendfile()` and `splice()`.

---

# DebugFS

_Peios Kernel / Internals / Filesystems_

> Copyright © 2009 Jonathan Corbet <corbet@lwn.net>

> **Peios:** Integrity lockdown restricts debugfs access. Read-only files passing its safety checks can remain accessible, but writable or ioctl/mmap-capable debugfs interfaces can fail with `EPERM`. Native authority does not bypass lockdown. These upstream diagnostic recipes therefore depend on interface availability in the configured kernel. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-debugfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © 2009 Jonathan Corbet &lt;[corbet@lwn.net](<mailto:corbet@lwn.net>)&gt;

Debugfs exists as a simple way for kernel developers to make information available to user space.  Unlike /proc, which is only meant for information about a process, or sysfs, which has strict one-value-per-file rules, debugfs has no rules at all.  Developers can put any information they want there.  The debugfs filesystem is also intended to not serve as a stable ABI to user space; in theory, there are no stability constraints placed on files exported there.  The real world is not always so simple, though <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1); even debugfs interfaces are best designed with the idea that they will need to be maintained forever.

Debugfs is typically mounted with a command like:



```text
mount -t debugfs none /sys/kernel/debug
```

(Or an equivalent /etc/fstab line). The debugfs root directory is accessible only to the root user by default. To change access to the tree the "uid", "gid" and "mode" mount options can be used.

Note that the debugfs API is exported GPL-only to modules.

Code using debugfs should include &lt;linux/debugfs.h&gt;.  Then, the first order of business will be to create at least one directory to hold a set of debugfs files:



```text
struct dentry *debugfs_create_dir(const char *name, struct dentry *parent);
```

This call, if successful, will make a directory called name underneath the indicated parent directory.  If parent is NULL, the directory will be created in the debugfs root.  On success, the return value is a struct dentry pointer which can be used to create files in the directory (and to clean it up at the end).  An ERR_PTR(-ERROR) return value indicates that something went wrong.  If ERR_PTR(-ENODEV) is returned, that is an indication that the kernel has been built without debugfs support and none of the functions described below will work.

The most general way to create a file within a debugfs directory is with:



```text
struct dentry *debugfs_create_file(const char *name, umode_t mode,
                                   struct dentry *parent, void *data,
                                   const struct file_operations *fops);
```

Here, name is the name of the file to create, mode describes the access permissions the file should have, parent indicates the directory which should hold the file, data will be stored in the i_private field of the resulting inode structure, and fops is a set of file operations which implement the file's behavior.  At a minimum, the read() and/or write() operations should be provided; others can be included as needed.  Again, the return value will be a dentry pointer to the created file, ERR_PTR(-ERROR) on error, or ERR_PTR(-ENODEV) if debugfs support is missing.

Create a file with an initial size, the following function can be used instead:



```text
void debugfs_create_file_size(const char *name, umode_t mode,
                              struct dentry *parent, void *data,
                              const struct file_operations *fops,
                              loff_t file_size);
```

file_size is the initial file size. The other parameters are the same as the function debugfs_create_file.

In a number of cases, the creation of a set of file operations is not actually necessary; the debugfs code provides a number of helper functions for simple situations.  Files containing a single integer value can be created with any of:



```text
void debugfs_create_u8(const char *name, umode_t mode,
                       struct dentry *parent, u8 *value);
void debugfs_create_u16(const char *name, umode_t mode,
                        struct dentry *parent, u16 *value);
void debugfs_create_u32(const char *name, umode_t mode,
                        struct dentry *parent, u32 *value);
void debugfs_create_u64(const char *name, umode_t mode,
                        struct dentry *parent, u64 *value);
```

These files support both reading and writing the given value; if a specific file should not be written to, simply set the mode bits accordingly.  The values in these files are in decimal; if hexadecimal is more appropriate, the following functions can be used instead:



```text
void debugfs_create_x8(const char *name, umode_t mode,
                       struct dentry *parent, u8 *value);
void debugfs_create_x16(const char *name, umode_t mode,
                        struct dentry *parent, u16 *value);
void debugfs_create_x32(const char *name, umode_t mode,
                        struct dentry *parent, u32 *value);
void debugfs_create_x64(const char *name, umode_t mode,
                        struct dentry *parent, u64 *value);
```

These functions are useful as long as the developer knows the size of the value to be exported.  Some types can have different widths on different architectures, though, complicating the situation somewhat.  There are functions meant to help out in such special cases:



```text
void debugfs_create_size_t(const char *name, umode_t mode,
                           struct dentry *parent, size_t *value);
```

As might be expected, this function will create a debugfs file to represent a variable of type size_t.

Similarly, there are helpers for variables of type unsigned long, in decimal and hexadecimal:



```text
struct dentry *debugfs_create_ulong(const char *name, umode_t mode,
                                    struct dentry *parent,
                                    unsigned long *value);
void debugfs_create_xul(const char *name, umode_t mode,
                        struct dentry *parent, unsigned long *value);
```

Boolean values can be placed in debugfs with:



```text
void debugfs_create_bool(const char *name, umode_t mode,
                         struct dentry *parent, bool *value);
```

A read on the resulting file will yield either Y (for non-zero values) or N, followed by a newline.  If written to, it will accept either upper- or lower-case values, or 1 or 0.  Any other input will be silently ignored.

Also, atomic_t values can be placed in debugfs with:



```text
void debugfs_create_atomic_t(const char *name, umode_t mode,
                             struct dentry *parent, atomic_t *value)
```

A read of this file will get atomic_t values, and a write of this file will set atomic_t values.

Another option is exporting a block of arbitrary binary data, with this structure and function:



```text
struct debugfs_blob_wrapper {
    void *data;
    unsigned long size;
};

struct dentry *debugfs_create_blob(const char *name, umode_t mode,
                                   struct dentry *parent,
                                   struct debugfs_blob_wrapper *blob);
```

A read of this file will return the data pointed to by the debugfs_blob_wrapper structure.  Some drivers use "blobs" as a simple way to return several lines of (static) formatted text output.  This function can be used to export binary information, but there does not appear to be any code which does so in the mainline.  Note that all files created with debugfs_create_blob() are read-only.

If you want to dump a block of registers (something that happens quite often during development, even if little such code reaches mainline), debugfs offers two functions: one to make a registers-only file, and another to insert a register block in the middle of another sequential file:



```text
struct debugfs_reg32 {
    char *name;
    unsigned long offset;
};

struct debugfs_regset32 {
    const struct debugfs_reg32 *regs;
    int nregs;
    void __iomem *base;
    struct device *dev;     /* Optional device for Runtime PM */
};

debugfs_create_regset32(const char *name, umode_t mode,
                        struct dentry *parent,
                        struct debugfs_regset32 *regset);

void debugfs_print_regs32(struct seq_file *s, const struct debugfs_reg32 *regs,
                     int nregs, void __iomem *base, char *prefix);
```

The "base" argument may be 0, but you may want to build the reg32 array using \__stringify, and a number of register names (macros) are actually byte offsets over a base for the register block.

If you want to dump a u32 array in debugfs, you can create a file with:



```text
struct debugfs_u32_array {
    u32 *array;
    u32 n_elements;
};

void debugfs_create_u32_array(const char *name, umode_t mode,
                    struct dentry *parent,
                    struct debugfs_u32_array *array);
```

The "array" argument wraps a pointer to the array's data and the number of its elements. Note: Once array is created its size can not be changed.

There is a helper function to create a device-related seq_file:



```text
void debugfs_create_devm_seqfile(struct device *dev,
                             const char *name,
                             struct dentry *parent,
                             int (*read_fn)(struct seq_file *s,
                                     void *data));
```

The "dev" argument is the device related to this debugfs file, and the "read_fn" is a function pointer which to be called to print the seq_file content.

There are a couple of other directory-oriented helper functions:



```text
struct dentry *debugfs_change_name(struct dentry *dentry,
                                      const char *fmt, ...);

struct dentry *debugfs_create_symlink(const char *name,
                                      struct dentry *parent,
                                      const char *target);
```

A call to debugfs_change_name() will give a new name to an existing debugfs file, always in the same directory.  The new_name must not exist prior to the call; the return value is 0 on success and -E... on failure. Symbolic links can be created with debugfs_create_symlink().

There is one important thing that all debugfs users must take into account: there is no automatic cleanup of any directories created in debugfs.  If a module is unloaded without explicitly removing debugfs entries, the result will be a lot of stale pointers and no end of highly antisocial behavior. So all debugfs users - at least those which can be built as modules - must be prepared to remove all files and directories they create there.  A file or directory can be removed with:



```text
void debugfs_remove(struct dentry *dentry);
```

The dentry value can be NULL or an error value, in which case nothing will be removed.  Note that this function will recursively remove all files and directories underneath it.  Previously, debugfs_remove_recursive() was used to perform that task, but this function is now just an alias to debugfs_remove().  debugfs_remove_recursive() should be considered deprecated.

<a id="rst-footnote-1"></a>



**[1]** [http://lwn.net/Articles/309298/](<http://lwn.net/Articles/309298/>)

---

# The Devpts Filesystem

_Peios Kernel / Internals / Filesystems_

> Each mount of the devpts filesystem is now distinct such that ptys and their indices allocated in one mount are independent from ptys and their indices in all other mounts.

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-the-devpts-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Each mount of the devpts filesystem is now distinct such that ptys and their indices allocated in one mount are independent from ptys and their indices in all other mounts.

A devpts instance creates its `ptmx` node with default mode `0000`; the `ptmxmode` mount option can select a different mode. These are Unix metadata values, not a native Peios access grant.

To retain backwards compatibility a ptmx device node (aka any node created with `mknod name c 5 2`) when opened will look for an instance of devpts under the name `pts` in the same directory as the ptmx device node.

Instead of a separate `/dev/ptmx` device node, `/dev/ptmx` can be a symlink or bind mount to `/dev/pts/ptmx`. The conventional Unix setup uses `ptmxmode=0666` or changes that node's mode after mounting. In Peios, mode changes alone do not authorize access: the mount and native descriptor policy must also permit the caller's operations. Do not use `chmod 0666` as evidence that PTY access has been delegated.

Total count of pty pairs in all instances is limited by sysctls:



```text
kernel.pty.max = 4096       - global limit
kernel.pty.reserve = 1024   - reserved for filesystems mounted from the initial mount namespace
kernel.pty.nr               - current count of ptys
```

Per-instance limit could be set by adding mount option `max=<count>`.

This feature was added in kernel 3.4 together with `sysctl kernel.pty.reserve`.

In kernels older than 3.4 sysctl `kernel.pty.max` works as per-instance limit.

---

# Directory Locking

_Peios Kernel / Internals / Filesystems_

> Locking scheme used for directory operations is based on two kinds of locks - per-inode (->i_rwsem) and per-filesystem (->s_vfs_rename_mutex).

<a id="rst-directory-locking"></a>

Locking scheme used for directory operations is based on two kinds of locks - per-inode (-&gt;i_rwsem) and per-filesystem (-&gt;s_vfs_rename_mutex).

When taking the i_rwsem on multiple non-directory objects, we always acquire the locks in order by increasing address.  We'll call that "inode pointer" order in the following.

<a id="rst-primitives"></a>

## Primitives

For our purposes all operations fall in 6 classes:

1. read access.  Locking rules:

   > - lock the directory we are accessing (shared)

2. object creation.  Locking rules:

   > - lock the directory we are accessing (exclusive)

3. object removal.  Locking rules:

   > - lock the parent (exclusive)
   >
   > - find the victim
   >
   > - lock the victim (exclusive)

4. link creation.  Locking rules:

   > - lock the parent (exclusive)
   >
   > - check that the source is not a directory
   >
   > - lock the source (exclusive; probably could be weakened to shared)

5. rename that is \_not\_ cross-directory.  Locking rules:

   > - lock the parent (exclusive)
   >
   > - find the source and target
   >
   > - decide which of the source and target need to be locked. The source needs to be locked if it's a non-directory, target - if it's a non-directory or about to be removed.
   >
   > - take the locks that need to be taken (exclusive), in inode pointer order if need to take both (that can happen only when both source and target are non-directories - the source because it wouldn't need to be locked otherwise and the target because mixing directory and non-directory is allowed only with RENAME_EXCHANGE, and that won't be removing the target).

6. cross-directory rename.  The trickiest in the whole bunch.  Locking rules:

   > - lock the filesystem
   >
   > - if the parents don't have a common ancestor, fail the operation.
   >
   > - lock the parents in "ancestors first" order (exclusive). If neither is an ancestor of the other, lock the parent of source first.
   >
   > - find the source and target.
   >
   > - verify that the source is not a descendent of the target and target is not a descendent of source; fail the operation otherwise.
   >
   > - lock the subdirectories involved (exclusive), source before target.
   >
   > - lock the non-directories involved (exclusive), in inode pointer order.

The rules above obviously guarantee that all directories that are going to be read, modified or removed by method will be locked by the caller.

<a id="rst-splicing"></a>

## Splicing

There is one more thing to consider - splicing.  It's not an operation in its own right; it may happen as part of lookup.  We speak of the operations on directory trees, but we obviously do not have the full picture of those - especially for network filesystems.  What we have is a bunch of subtrees visible in dcache and locking happens on those. Trees grow as we do operations; memory pressure prunes them.  Normally that's not a problem, but there is a nasty twist - what should we do when one growing tree reaches the root of another?  That can happen in several scenarios, starting from "somebody mounted two nested subtrees from the same NFS4 server and doing lookups in one of them has reached the root of another"; there's also open-by-fhandle stuff, and there's a possibility that directory we see in one place gets moved by the server to another and we run into it when we do a lookup.

For a lot of reasons we want to have the same directory present in dcache only once.  Multiple aliases are not allowed.  So when lookup runs into a subdirectory that already has an alias, something needs to be done with dcache trees.  Lookup is already holding the parent locked.  If alias is a root of separate tree, it gets attached to the directory we are doing a lookup in, under the name we'd been looking for.  If the alias is already a child of the directory we are looking in, it changes name to the one we'd been looking for.  No extra locking is involved in these two cases. However, if it's a child of some other directory, the things get trickier. First of all, we verify that it is *not* an ancestor of our directory and fail the lookup if it is.  Then we try to lock the filesystem and the current parent of the alias.  If either trylock fails, we fail the lookup. If trylocks succeed, we detach the alias from its current parent and attach to our directory, under the name we are looking for.

Note that splicing does *not* involve any modification of the filesystem; all we change is the view in dcache.  Moreover, holding a directory locked exclusive prevents such changes involving its children and holding the filesystem lock prevents any changes of tree topology, other than having a root of one tree becoming a child of directory in another.  In particular, if two dentries have been found to have a common ancestor after taking the filesystem lock, their relationship will remain unchanged until the lock is dropped.  So from the directory operations' point of view splicing is almost irrelevant - the only place where it matters is one step in cross-directory renames; we need to be careful when checking if parents have a common ancestor.

<a id="rst-multiple-filesystem-stuff"></a>

## Multiple-filesystem stuff

For some filesystems a method can involve a directory operation on another filesystem; it may be ecryptfs doing operation in the underlying filesystem, overlayfs doing something to the layers, network filesystem using a local one as a cache, etc.  In all such cases the operations on other filesystems must follow the same locking rules.  Moreover, "a directory operation on this filesystem might involve directory operations on that filesystem" should be an asymmetric relation (or, if you will, it should be possible to rank the filesystems so that directory operation on a filesystem could trigger directory operations only on higher-ranked ones - in these terms overlayfs ranks lower than its layers, network filesystem ranks lower than whatever it caches on, etc.)

<a id="rst-deadlock-avoidance"></a>

## Deadlock avoidance

If no directory is its own ancestor, the scheme above is deadlock-free.

Proof:

There is a ranking on the locks, such that all primitives take them in order of non-decreasing rank.  Namely,

> - rank -&gt;i_rwsem of non-directories on given filesystem in inode pointer order.
>
> - put -&gt;i_rwsem of all directories on a filesystem at the same rank, lower than -&gt;i_rwsem of any non-directory on the same filesystem.
>
> - put -&gt;s_vfs_rename_mutex at rank lower than that of any -&gt;i_rwsem on the same filesystem.
>
> - among the locks on different filesystems use the relative rank of those filesystems.

For example, if we have NFS filesystem caching on a local one, we have

> 1. -&gt;s_vfs_rename_mutex of NFS filesystem
>
> 2. -&gt;i_rwsem of directories on that NFS filesystem, same rank for all
>
> 3. -&gt;i_rwsem of non-directories on that filesystem, in order of increasing address of inode
>
> 4. -&gt;s_vfs_rename_mutex of local filesystem
>
> 5. -&gt;i_rwsem of directories on the local filesystem, same rank for all
>
> 6. -&gt;i_rwsem of non-directories on local filesystem, in order of increasing address of inode.

It's easy to verify that operations never take a lock with rank lower than that of an already held lock.

Suppose deadlocks are possible.  Consider the minimal deadlocked set of threads.  It is a cycle of several threads, each blocked on a lock held by the next thread in the cycle.

Since the locking order is consistent with the ranking, all contended locks in the minimal deadlock will be of the same rank, i.e. they all will be -&gt;i_rwsem of directories on the same filesystem. Moreover, without loss of generality we can assume that all operations are done directly to that filesystem and none of them has actually reached the method call.

In other words, we have a cycle of threads, T1,..., Tn, and the same number of directories (D1,...,Dn) such that

> T1 is blocked on D1 which is held by T2
>
> T2 is blocked on D2 which is held by T3
>
> ...
>
> Tn is blocked on Dn which is held by T1.

Each operation in the minimal cycle must have locked at least one directory and blocked on attempt to lock another.  That leaves only 3 possible operations: directory removal (locks parent, then child), same-directory rename killing a subdirectory (ditto) and cross-directory rename of some sort.

There must be a cross-directory rename in the set; indeed, if all operations had been of the "lock parent, then child" sort we would have Dn a parent of D1, which is a parent of D2, which is a parent of D3, ..., which is a parent of Dn.  Relationships couldn't have changed since the moment directory locks had been acquired, so they would all hold simultaneously at the deadlock time and we would have a loop.

Since all operations are on the same filesystem, there can't be more than one cross-directory rename among them.  Without loss of generality we can assume that T1 is the one doing a cross-directory rename and everything else is of the "lock parent, then child" sort.

In other words, we have a cross-directory rename that locked Dn and blocked on attempt to lock D1, which is a parent of D2, which is a parent of D3, ..., which is a parent of Dn.  Relationships between D1,...,Dn all hold simultaneously at the deadlock time.  Moreover, cross-directory rename does not get to locking any directories until it has acquired filesystem lock and verified that directories involved have a common ancestor, which guarantees that ancestry relationships between all of them had been stable.

Consider the order in which directories are locked by the cross-directory rename; parents first, then possibly their children. Dn and D1 would have to be among those, with Dn locked before D1. Which pair could it be?

It can't be the parents - indeed, since D1 is an ancestor of Dn, it would be the first parent to be locked.  Therefore at least one of the children must be involved and thus neither of them could be a descendent of another - otherwise the operation would not have progressed past locking the parents.

It can't be a parent and its child; otherwise we would've had a loop, since the parents are locked before the children, so the parent would have to be a descendent of its child.

It can't be a parent and a child of another parent either. Otherwise the child of the parent in question would've been a descendent of another child.

That leaves only one possibility - namely, both Dn and D1 are among the children, in some order.  But that is also impossible, since neither of the children is a descendent of another.

That concludes the proof, since the set of operations with the properties required for a minimal deadlock can not exist.

Note that the check for having a common ancestor in cross-directory rename is crucial - without it a deadlock would be possible.  Indeed, suppose the parents are initially in different trees; we would lock the parent of source, then try to lock the parent of target, only to have an unrelated lookup splice a distant ancestor of source to some distant descendent of the parent of target.   At that point we have cross-directory rename holding the lock on parent of source and trying to lock its distant ancestor.  Add a bunch of rmdir() attempts on all directories in between (all of those would fail with -ENOTEMPTY, had they ever gotten the locks) and voila - we have a deadlock.

<a id="rst-loop-avoidance"></a>

## Loop avoidance

These operations are guaranteed to avoid loop creation.  Indeed, the only operation that could introduce loops is cross-directory rename. Suppose after the operation there is a loop; since there hadn't been such loops before the operation, at least on of the nodes in that loop must've had its parent changed.  In other words, the loop must be passing through the source or, in case of exchange, possibly the target.

Since the operation has succeeded, neither source nor target could have been ancestors of each other.  Therefore the chain of ancestors starting in the parent of source could not have passed through the target and vice versa.  On the other hand, the chain of ancestors of any node could not have passed through the node itself, or we would've had a loop before the operation.  But everything other than source and target has kept the parent after the operation, so the operation does not change the chains of ancestors of (ex-)parents of source and target.  In particular, those chains must end after a finite number of steps.

Now consider the loop created by the operation.  It passes through either source or target; the next node in the loop would be the ex-parent of target or source resp.  After that the loop would follow the chain of ancestors of that parent.  But as we have just shown, that chain must end after a finite number of steps, which means that it can't be a part of any loop.  Q.E.D.

While this locking scheme works for arbitrary DAGs, it relies on ability to check that directory is a descendent of another object.  Current implementation assumes that directory graph is a tree.  This assumption is also preserved by all operations (cross-directory rename on a tree that would not introduce a cycle will leave it a tree and link() fails for directories).

Notice that "directory" in the above == "anything that might have children", so if we are going to introduce hybrid objects we will need either to make sure that link(2) doesn't work for them or to make changes in is_subdir() that would make it work even in presence of such beasts.

---

# DLMFS

_Peios Kernel / Internals / Filesystems_

> A minimal DLM userspace interface implemented via a virtual file system.

<a id="rst-dlmfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

A minimal DLM userspace interface implemented via a virtual file system.

dlmfs is built with OCFS2 as it requires most of its infrastructure.

**Project web page:** [http://ocfs2.wiki.kernel.org](<http://ocfs2.wiki.kernel.org>)

**Tools web page:** [https://github.com/markfasheh/ocfs2-tools](<https://github.com/markfasheh/ocfs2-tools>)

**OCFS2 mailing lists:** [https://subspace.kernel.org/lists.linux.dev.html](<https://subspace.kernel.org/lists.linux.dev.html>)

All code copyright 2005 Oracle except when otherwise noted.

<a id="rst-credits"></a>

## Credits

Some code taken from ramfs which is Copyright © 2000 Linus Torvalds and Transmeta Corp.

Mark Fasheh &lt;[mark.fasheh@oracle.com](<mailto:mark.fasheh@oracle.com>)&gt;

<a id="rst-caveats"></a>

## Caveats

- Right now it only works with the OCFS2 DLM, though support for other DLM implementations should not be a major issue.

<a id="rst-mount-options"></a>

## Mount options

None

<a id="rst-usage"></a>

## Usage

If you're just interested in OCFS2, then please see [ocfs2.rst](/kernel/internals/filesystems/ocfs2.md). The rest of this document will be geared towards those who want to use dlmfs for easy to setup and easy to use clustered locking in userspace.

<a id="rst-setup"></a>

## Setup

dlmfs requires that the OCFS2 cluster infrastructure be in place. Please download ocfs2-tools from the above url and configure a cluster.

You'll want to start heartbeating on a volume which all the nodes in your lockspace can access. The easiest way to do this is via ocfs2_hb_ctl (distributed with ocfs2-tools). Right now it requires that an OCFS2 file system be in place so that it can automatically find its heartbeat area, though it will eventually support heartbeat against raw disks.

Please see the ocfs2_hb_ctl and mkfs.ocfs2 manual pages distributed with ocfs2-tools.

Once you're heartbeating, DLM lock 'domains' can be easily created / destroyed and locks within them accessed.

<a id="rst-locking"></a>

## Locking

Users may access dlmfs via standard file system calls, or they can use 'libo2dlm' (distributed with ocfs2-tools) which abstracts the file system calls and presents a more traditional locking api.

dlmfs handles lock caching automatically for the user, so a lock request for an already acquired lock will not generate another DLM call. Userspace programs are assumed to handle their own local locking.

Two levels of locks are supported - Shared Read, and Exclusive. Also supported is a Trylock operation.

For information on the libo2dlm interface, please see o2dlm.h, distributed with ocfs2-tools.

Lock value blocks can be read and written to a resource via read(2) and write(2) against the fd obtained via your open(2) call. The maximum currently supported LVB length is 64 bytes (though that is an OCFS2 DLM limitation). Through this mechanism, users of dlmfs can share small amounts of data amongst their nodes.

mkdir(2) signals dlmfs to join a domain (which will have the same name as the resulting directory)

rmdir(2) signals dlmfs to leave the domain

Locks for a given domain are represented by regular inodes inside the domain directory.  Locking against them is done via the open(2) system call.

The open(2) call will not return until your lock has been granted or an error has occurred, unless it has been instructed to do a trylock operation. If the lock succeeds, you'll get an fd.

open(2) with O_CREAT to ensure the resource inode is created - dlmfs does not automatically create inodes for existing lock resources.


<table>
<thead>
<tr>
<th>


Open Flag

</th>
<th>


Lock Request Type

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


O_RDONLY

</td>
<td>


Shared Read

</td>
</tr>
<tr>
<td>


O_RDWR

</td>
<td>


Exclusive

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>


Open Flag

</th>
<th>


Resulting Locking Behavior

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


O_NONBLOCK

</td>
<td>


Trylock operation

</td>
</tr>
</tbody>
</table>

You must provide exactly one of O_RDONLY or O_RDWR.

If O_NONBLOCK is also provided and the trylock operation was valid but could not lock the resource then open(2) will return ETXTBUSY.

close(2) drops the lock associated with your fd.

Modes passed to mkdir(2) or open(2) are adhered to locally. Chown is supported locally as well. This means you can use them to restrict access to the resources via dlmfs on your local node only.

The resource LVB may be read from the fd in either Shared Read or Exclusive modes via the read(2) system call. It can be written via write(2) only when open in Exclusive mode.

Once written, an LVB will be visible to other nodes who obtain Read Only or higher level locks on the resource.

<a id="rst-see-also"></a>

## See Also

[http://opendlm.sourceforge.net/cvsmirror/opendlm/docs/dlmbook_final.pdf](<http://opendlm.sourceforge.net/cvsmirror/opendlm/docs/dlmbook_final.pdf>)

For more information on the VMS distributed locking API.

---

# Linux Directory Notification

_Peios Kernel / Internals / Filesystems_

> Stephen Rothwell <sfr@canb.auug.org.au>

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-linux-directory-notification"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Stephen Rothwell &lt;[sfr@canb.auug.org.au](<mailto:sfr@canb.auug.org.au>)&gt;

The intention of directory notification is to allow user applications to be notified when a directory, or any of the files in it, are changed. The basic mechanism involves the application registering for notification on a directory using a fcntl(2) call and the notifications themselves being delivered using signals.

The application decides which "events" it wants to be notified about. The currently defined events are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> DN_ACCESS
>
> </td>
> <td>
>
>
> A file in the directory was accessed (read)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DN_MODIFY
>
> </td>
> <td>
>
>
> A file in the directory was modified (write,truncate)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DN_CREATE
>
> </td>
> <td>
>
>
> A file was created in the directory
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DN_DELETE
>
> </td>
> <td>
>
>
> A file was unlinked from directory
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DN_RENAME
>
> </td>
> <td>
>
>
> A file in the directory was renamed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DN_ATTRIB
>
> </td>
> <td>
>
>
> A file in the directory had its attributes changed (chmod,chown)
>
> </td>
> </tr>
> </tbody>
> </table>

Usually, the application must reregister after each notification, but if DN_MULTISHOT is or'ed with the event mask, then the registration will remain until explicitly removed (by registering for no events).

By default, SIGIO will be delivered to the process and no other useful information.  However, if the F_SETSIG fcntl(2) call is used to let the kernel know which signal to deliver, a siginfo structure will be passed to the signal handler and the si_fd member of that structure will contain the file descriptor associated with the directory in which the event occurred.

Preferably the application will choose one of the real time signals (SIGRTMIN + &lt;n&gt;) so that the notifications may be queued.  This is especially important if DN_MULTISHOT is specified.  Note that SIGRTMIN is often blocked, so it is better to use (at least) SIGRTMIN + 1.

<a id="rst-implementation-expectations-features-and-bugs"></a>

## Implementation expectations (features and bugs :-))

The notification should work for any local access to files even if the actual file system is on a remote server.  This implies that remote access to files served by local user mode servers should be notified. Also, remote accesses to files served by a local kernel NFS server should be notified.

In order to make the impact on the file system code as small as possible, the problem of hard links to files has been ignored.  So if a file (x) exists in two directories (a and b) then a change to the file using the name "a/x" should be notified to a program expecting notifications on directory "a", but will not be notified to one expecting notifications on directory "b".

Also, files that are unlinked, will still cause notifications in the last directory that they were linked to.

<a id="rst-configuration"></a>

## Configuration

Dnotify is controlled via the CONFIG_DNOTIFY configuration option.  When disabled, fcntl(fd, F_NOTIFY, ...) will return -EINVAL.

<a id="rst-example"></a>

## Example

See tools/testing/selftests/filesystems/dnotify_test.c for an example.

<a id="rst-note"></a>

## NOTE

Beginning with Linux 2.6.13, dnotify has been replaced by inotify. See [Documentation/filesystems/inotify.rst](/kernel/internals/filesystems/inotify.md) for more information on it.

---

# eCryptfs: A stacked cryptographic filesystem for Linux

_Peios Kernel / Internals / Filesystems_

> eCryptfs is free software. Please see the file COPYING for details. For documentation, please see the files in the doc/ subdirectory. For building and installation instructions please see the INSTALL file.

<a id="rst-ecryptfs-a-stacked-cryptographic-filesystem-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

eCryptfs is free software. Please see the file COPYING for details. For documentation, please see the files in the doc/ subdirectory.  For building and installation instructions please see the INSTALL file.

**Maintainer:** Phillip Hellewell

**Lead developer:** Michael A. Halcrow &lt;[mhalcrow@us.ibm.com](<mailto:mhalcrow@us.ibm.com>)&gt;

**Developers:** Michael C. Thompson Kent Yoder

**Web Site:** [http://ecryptfs.sf.net](<http://ecryptfs.sf.net>)

This software is currently undergoing development. Make sure to maintain a backup copy of any data you write into eCryptfs.

eCryptfs requires the userspace tools downloadable from the SourceForge site:

[http://sourceforge.net/projects/ecryptfs/](<http://sourceforge.net/projects/ecryptfs/>)

Userspace requirements include:

- David Howells' userspace keyring headers and libraries (version 1.0 or higher), obtainable from [http://people.redhat.com/\~dhowells/keyutils/](<http://people.redhat.com/~dhowells/keyutils/>)

- Libgcrypt

> [!NOTE]
>
> In the beta/experimental releases of eCryptfs, when you upgrade eCryptfs, you should copy the files to an unencrypted location and then copy the files back into the new eCryptfs mount to migrate the files.

<a id="rst-mount-wide-passphrase"></a>

## Mount-wide Passphrase

Create a new directory into which eCryptfs will write its encrypted files (i.e., /root/crypt).  Then, create the mount point directory (i.e., /mnt/crypt).  Now it's time to mount eCryptfs:



```text
mount -t ecryptfs /root/crypt /mnt/crypt
```

You should be prompted for a passphrase and a salt (the salt may be blank).

Try writing a new file:



```text
echo "Hello, World" > /mnt/crypt/hello.txt
```

The operation will complete.  Notice that there is a new file in /root/crypt that is at least 12288 bytes in size (depending on your host page size).  This is the encrypted underlying file for what you just wrote.  To test reading, from start to finish, you need to clear the user session keyring:

keyctl clear @u

Then umount /mnt/crypt and mount again per the instructions given above.



```text
cat /mnt/crypt/hello.txt
```

<a id="rst-notes"></a>

## Notes

eCryptfs version 0.1 should only be mounted on (1) empty directories or (2) directories containing files only created by eCryptfs. If you mount a directory that has pre-existing files not created by eCryptfs, then behavior is undefined. Do not run eCryptfs in higher verbosity levels unless you are doing so for the sole purpose of debugging or development, since secret values will be written out to the system log in that case.

Mike Halcrow [mhalcrow@us.ibm.com](<mailto:mhalcrow@us.ibm.com>)

---

# efivarfs - a (U)EFI variable filesystem

_Peios Kernel / Internals / Filesystems_

> The efivarfs filesystem was created to address the shortcomings of using entries in sysfs to maintain EFI variables. The old sysfs EFI variables code only supported variables of up to 1024 bytes. This limitation existed in version 0.99 of…

<a id="rst-efivarfs-a-u-efi-variable-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The efivarfs filesystem was created to address the shortcomings of using entries in sysfs to maintain EFI variables. The old sysfs EFI variables code only supported variables of up to 1024 bytes. This limitation existed in version 0.99 of the EFI specification, but was removed before any full releases. Since variables can now be larger than a single page, sysfs isn't the best interface for this.

Variables can be created, deleted and modified with the efivarfs filesystem.

efivarfs is typically mounted like this:



```text
mount -t efivarfs none /sys/firmware/efi/efivars
```

Due to the presence of numerous firmware bugs where removing non-standard UEFI variables causes the system firmware to fail to POST, efivarfs files that are not well-known standardized variables are created as immutable files.  This doesn't prevent removal - "chattr -i" will work - but it does prevent this kind of failure from being accomplished accidentally.

> [!WARNING]
>
> When a content of an UEFI variable in /sys/firmware/efi/efivars is displayed, for example using "hexdump", pay attention that the first 4 bytes of the output represent the UEFI variable attributes, in little-endian format.
>
> Practically the output of each efivar is composed of:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 4_bytes_of_attributes + efivar_data
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

*See also:*

- [Documentation/admin-guide/acpi/ssdt-overlays.rst](/kernel/administration/admin-guide/acpi/ssdt-overlays.md)

- Documentation/ABI/removed/sysfs-firmware-efi-vars

---

# EROFS - Enhanced Read-Only File System

_Peios Kernel / Internals / Filesystems_

> EROFS filesystem stands for Enhanced Read-Only File System. It aims to form a generic read-only filesystem solution for various read-only use cases instead of just focusing on storage space saving without considering any side effects of…

<a id="rst-erofs-enhanced-read-only-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

EROFS filesystem stands for Enhanced Read-Only File System.  It aims to form a generic read-only filesystem solution for various read-only use cases instead of just focusing on storage space saving without considering any side effects of runtime performance.

It is designed to meet the needs of flexibility, feature extendability and user payload friendly, etc.  Apart from those, it is still kept as a simple random-access friendly high-performance filesystem to get rid of unneeded I/O amplification and memory-resident overhead compared to similar approaches.

It is implemented to be a better choice for the following scenarios:

> - read-only storage media or
>
> - part of a fully trusted read-only solution, which means it needs to be immutable and bit-for-bit identical to the official golden image for their releases due to security or other considerations and
>
> - hope to minimize extra storage space with guaranteed end-to-end performance by using compact layout, transparent file compression and direct access, especially for those embedded devices with limited memory and high-density hosts with numerous containers.

Here are the main features of EROFS:

> - Little endian on-disk design;
>
> - Block-based distribution and file-based distribution over fscache are supported;
>
> - Support multiple devices to refer to external blobs, which can be used for container images;
>
> - 32-bit block addresses for each device, therefore 16TiB address space at most with 4KiB block size for now;
>
> - Two inode layouts for different requirements:
>
>
>   <table>
>   <thead>
>   <tr>
>   <th>
>
>
>
>
>   </th>
>   <th>
>
>
>
>
>   </th>
>   <th>
>
>
>
>
>   </th>
>   </tr>
>   </thead>
>   <tbody>
>   <tr>
>   <td>
>
>
>   Inode metadata size
>
>   </td>
>   <td>
>
>
>   32 bytes
>
>   </td>
>   <td>
>
>
>   64 bytes
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   Max file size
>
>   </td>
>   <td>
>
>
>   4 GiB
>
>   </td>
>   <td>
>
>
>   16 EiB (also limited by max. vol size)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   Max uids/gids
>
>   </td>
>   <td>
>
>
>   65536
>
>   </td>
>   <td>
>
>
>   4294967296
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   Per-inode timestamp
>
>   </td>
>   <td>
>
>
>   no
>
>   </td>
>   <td>
>
>
>   yes (64 + 32-bit timestamp)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   Max hardlinks
>
>   </td>
>   <td>
>
>
>   65536
>
>   </td>
>   <td>
>
>
>   4294967296
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   Metadata reserved
>
>   </td>
>   <td>
>
>
>   8 bytes
>
>   </td>
>   <td>
>
>
>   18 bytes
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
> - Support extended attributes as an option;
>
> - Support a bloom filter that speeds up negative extended attribute lookups;
>
> - Support POSIX.1e ACLs by using extended attributes;
>
> - Support transparent data compression as an option: LZ4, MicroLZMA, DEFLATE and Zstandard algorithms can be used on a per-file basis; In addition, inplace decompression is also supported to avoid bounce compressed buffers and unnecessary page cache thrashing.
>
> - Support chunk-based data deduplication and rolling-hash compressed data deduplication;
>
> - Support tailpacking inline compared to byte-addressed unaligned metadata or smaller block size alternatives;
>
> - Support merging tail-end data into a special inode as fragments.
>
> - Support large folios to make use of THPs (Transparent Hugepages);
>
> - Support direct I/O on uncompressed files to avoid double caching for loop devices;
>
> - Support FSDAX on uncompressed images for secure containers and ramdisks in order to get rid of unnecessary page cache.
>
> - Support file-based on-demand loading with the Fscache infrastructure.

The following git tree provides the file system user-space tools under development, such as a formatting tool (mkfs.erofs), an on-disk consistency &amp; compatibility checking tool (fsck.erofs), and a debugging tool (dump.erofs):

- git://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs-utils.git

For more information, please also refer to the documentation site:

- [https://erofs.docs.kernel.org](<https://erofs.docs.kernel.org>)

Bugs and patches are welcome, please kindly help us and send to the following linux-erofs mailing list:

- linux-erofs mailing list   &lt;[linux-erofs@lists.ozlabs.org](<mailto:linux-erofs@lists.ozlabs.org>)&gt;

<a id="rst-mount-options"></a>

## Mount options


<table>
<tbody>
<tr>
<td>


(no)user_xattr

</td>
<td>


Setup Extended User Attributes. Note: xattr is enabled by default if CONFIG_EROFS_FS_XATTR is selected.

</td>
</tr>
<tr>
<td>


(no)acl

</td>
<td>


Setup POSIX Access Control List. Note: acl is enabled by default if CONFIG_EROFS_FS_POSIX_ACL is selected.

</td>
</tr>
<tr>
<td>


cache_strategy=%s

</td>
<td>


Select a strategy for cached decompression from now on:


<table>
<tbody>
<tr>
<td>


disabled

</td>
<td>


In-place I/O decompression only;

</td>
</tr>
<tr>
<td>


readahead

</td>
<td>


Cache the last incomplete compressed physical cluster for further reading. It still does in-place I/O decompression for the rest compressed physical clusters;

</td>
</tr>
<tr>
<td>


readaround

</td>
<td>


Cache both ends of incomplete compressed physical clusters for further reading. It still does in-place I/O decompression for the rest compressed physical clusters.

</td>
</tr>
</tbody>
</table>

</td>
</tr>
<tr>
<td>


dax=\{always,never\}

</td>
<td>


Use direct access (no page cache).  See [Documentation/filesystems/dax.rst](/kernel/internals/filesystems/dax.md).

</td>
</tr>
<tr>
<td>


dax

</td>
<td>


A legacy option which is an alias for `dax=always`.

</td>
</tr>
<tr>
<td>


device=%s

</td>
<td>


Specify a path to an extra device to be used together.

</td>
</tr>
<tr>
<td>


directio

</td>
<td>


(For file-backed mounts) Use direct I/O to access backing files, and asynchronous I/O will be enabled if supported.

</td>
</tr>
<tr>
<td>


fsid=%s

</td>
<td>


Specify a filesystem image ID for Fscache back-end.

</td>
</tr>
<tr>
<td>


domain_id=%s

</td>
<td>


Specify a trusted domain ID for fscache mode so that different images with the same blobs, identified by blob IDs, can share storage within the same trusted domain. Also used for different filesystems with inode page sharing enabled to share page cache within the trusted domain.

</td>
</tr>
<tr>
<td>


fsoffset=%llu

</td>
<td>


Specify block-aligned filesystem offset for the primary device.

</td>
</tr>
<tr>
<td>


inode_share

</td>
<td>


Enable inode page sharing for this filesystem.  Inodes with identical content within the same domain ID can share the page cache.

</td>
</tr>
</tbody>
</table>

<a id="rst-sysfs-entries"></a>

## Sysfs Entries

Information about mounted erofs file systems can be found in /sys/fs/erofs. Each mounted filesystem will have a directory in /sys/fs/erofs based on its device name (i.e., /sys/fs/erofs/sda). (see also Documentation/ABI/testing/sysfs-fs-erofs)

<a id="rst-on-disk-details"></a>

## On-disk details

<a id="rst-summary"></a>

### Summary

Different from other read-only file systems, an EROFS volume is designed to be as simple as possible:



```text
                              |-> aligned with the block size
 ____________________________________________________________
| |SB| | ... | Metadata | ... | Data | Metadata | ... | Data |
|_|__|_|_____|__________|_____|______|__________|_____|______|
0 +1K
```

All data areas should be aligned with the block size, but metadata areas may not. All metadata can be now observed in two different spaces (views):

> 1. Inode metadata space
>
>    Each valid inode should be aligned with an inode slot, which is a fixed value (32 bytes) and designed to be kept in line with compact inode size.
>
>    - **Each inode can be directly found with the following formula:**
>
>      inode offset = meta_blkaddr \* block_size + 32 \* nid
>
>
>
>    ```text
>                                |-> aligned with 8B
>                                           |-> followed closely
>    + meta_blkaddr blocks                                      |-> another slot
>      _____________________________________________________________________
>    |  ...   | inode |  xattrs  | extents  | data inline | ... | inode ...
>    |________|_______|(optional)|(optional)|__(optional)_|_____|__________
>             |-> aligned with the inode slot size
>                  .                   .
>                .                         .
>              .                              .
>            .                                    .
>          .                                         .
>        .                                              .
>      .____________________________________________________|-> aligned with 4B
>      | xattr_ibody_header | shared xattrs | inline xattrs |
>      |____________________|_______________|_______________|
>      |->    12 bytes    <-|->x * 4 bytes<-|               .
>                          .                .                 .
>                    .                      .                   .
>               .                           .                     .
>           ._______________________________.______________________.
>           | id | id | id | id |  ... | id | ent | ... | ent| ... |
>           |____|____|____|____|______|____|_____|_____|____|_____|
>                                           |-> aligned with 4B
>                                                       |-> aligned with 4B
>    ```
>
>    Inode could be 32 or 64 bytes, which can be distinguished from a common field which all inode versions have -- i_format:
>
>
>
>    ```text
>     __________________               __________________
>    |     i_format     |             |     i_format     |
>    |__________________|             |__________________|
>    |        ...       |             |        ...       |
>    |                  |             |                  |
>    |__________________| 32 bytes    |                  |
>                                     |                  |
>                                     |__________________| 64 bytes
>    ```
>
>    Xattrs, extents, data inline are placed after the corresponding inode with proper alignment, and they could be optional for different data mappings. \_currently\_ total 5 data layouts are supported:
>
>
>    <table>
>    <tbody>
>    <tr>
>    <td>
>
>
>    0
>
>    </td>
>    <td>
>
>
>    flat file data without data inline (no extent);
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    1
>
>    </td>
>    <td>
>
>
>    fixed-sized output data compression (with non-compacted indexes);
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    2
>
>    </td>
>    <td>
>
>
>    flat file data with tail packing data inline (no extent);
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    3
>
>    </td>
>    <td>
>
>
>    fixed-sized output data compression (with compacted indexes, v5.3+);
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    4
>
>    </td>
>    <td>
>
>
>    chunk-based file (v5.15+).
>
>    </td>
>    </tr>
>    </tbody>
>    </table>
>
>    The size of the optional xattrs is indicated by i_xattr_count in inode header. Large xattrs or xattrs shared by many different files can be stored in shared xattrs metadata rather than inlined right after inode.
>
> 2. Shared xattrs metadata space
>
>    Shared xattrs space is similar to the above inode space, started with a specific block indicated by xattr_blkaddr, organized one by one with proper align.
>
>    - **Each share xattr can also be directly found by the following formula:**
>
>      xattr offset = xattr_blkaddr \* block_size + 4 \* xattr_id



```text
                       |-> aligned by  4 bytes
+ xattr_blkaddr blocks                     |-> aligned with 4 bytes
 _________________________________________________________________________
|  ...   | xattr_entry |  xattr data | ... |  xattr_entry | xattr data  ...
|________|_____________|_____________|_____|______________|_______________
```

<a id="rst-directories"></a>

### Directories

All directories are now organized in a compact on-disk format. Note that each directory block is divided into index and name areas in order to support random file lookup, and all directory entries are \_strictly\_ recorded in alphabetical order in order to support improved prefix binary search algorithm (could refer to the related source code).



```text
                 ___________________________
                /                           |
               /              ______________|________________
              /              /              | nameoff1       | nameoffN-1
 ____________.______________._______________v________________v__________
| dirent | dirent | ... | dirent | filename | filename | ... | filename |
|___.0___|____1___|_____|___N-1__|____0_____|____1_____|_____|___N-1____|
     \                           ^
      \                          |                           * could have
       \                         |                             trailing '\0'
        \________________________| nameoff0
                            Directory block
```

Note that apart from the offset of the first filename, nameoff0 also indicates the total number of directory entries in this block since it is no need to introduce another on-disk field at all.

<a id="rst-chunk-based-files"></a>

### Chunk-based files

In order to support chunk-based data deduplication, a new inode data layout has been supported since Linux v5.15: Files are split in equal-sized data chunks with `extents` area of the inode metadata indicating how to get the chunk data: these can be simply as a 4-byte block address array or in the 8-byte chunk index form (see struct erofs_inode_chunk_index in erofs_fs.h for more details.)

By the way, chunk-based files are all uncompressed for now.

<a id="rst-long-extended-attribute-name-prefixes"></a>

### Long extended attribute name prefixes

There are use cases where extended attributes with different values can have only a few common prefixes (such as overlayfs xattrs).  The predefined prefixes work inefficiently in both image size and runtime performance in such cases.

The long xattr name prefixes feature is introduced to address this issue.  The overall idea is that, apart from the existing predefined prefixes, the xattr entry could also refer to user-specified long xattr name prefixes, e.g. "trusted.overlay.".

When referring to a long xattr name prefix, the highest bit (bit 7) of erofs_xattr_entry.e_name_index is set, while the lower bits (bit 0-6) as a whole represent the index of the referred long name prefix among all long name prefixes.  Therefore, only the trailing part of the name apart from the long xattr name prefix is stored in erofs_xattr_entry.e_name, which could be empty if the full xattr name matches exactly as its long xattr name prefix.

All long xattr prefixes are stored one by one in the packed inode as long as the packed inode is valid, or in the meta inode otherwise.  The xattr_prefix_count (of the on-disk superblock) indicates the total number of long xattr name prefixes, while (xattr_prefix_start \* 4) indicates the start offset of long name prefixes in the packed/meta inode.  Note that, long extended attribute name prefixes are disabled if xattr_prefix_count is 0.

Each long name prefix is stored in the format: ALIGN(\{\__le16 len, data\}, 4), where len represents the total size of the data part.  The data part is actually represented by 'struct erofs_xattr_long_prefix', where base_index represents the index of the predefined xattr name prefix, e.g. EROFS_XATTR_INDEX_TRUSTED for "trusted.overlay." long name prefix, while the infix string keeps the string after stripping the short prefix, e.g. "overlay." for the example above.

<a id="rst-data-compression"></a>

### Data compression

EROFS implements fixed-sized output compression which generates fixed-sized compressed data blocks from variable-sized input in contrast to other existing fixed-sized input solutions. Relatively higher compression ratios can be gotten by using fixed-sized output compression since nowadays popular data compression algorithms are mostly LZ77-based and such fixed-sized output approach can be benefited from the historical dictionary (aka. sliding window).

In details, original (uncompressed) data is turned into several variable-sized extents and in the meanwhile, compressed into physical clusters (pclusters). In order to record each variable-sized extent, logical clusters (lclusters) are introduced as the basic unit of compress indexes to indicate whether a new extent is generated within the range (HEAD) or not (NONHEAD). Lclusters are now fixed in block size, as illustrated below:



```text
         |<-    variable-sized extent    ->|<-       VLE         ->|
       clusterofs                        clusterofs              clusterofs
         |                                 |                       |
_________v_________________________________v_______________________v________
... |    .         |              |        .     |              |  .   ...
____|____._________|______________|________.___ _|______________|__.________
    |-> lcluster <-|-> lcluster <-|-> lcluster <-|-> lcluster <-|
         (HEAD)        (NONHEAD)       (HEAD)        (NONHEAD)    .
          .             CBLKCNT            .                    .
           .                               .                  .
            .                              .                .
      _______._____________________________.______________._________________
         ... |              |              |              | ...
      _______|______________|______________|______________|_________________
             |->      big pcluster       <-|-> pcluster <-|
```

A physical cluster can be seen as a container of physical compressed blocks which contains compressed data. Previously, only lcluster-sized (4KB) pclusters were supported. After big pcluster feature is introduced (available since Linux v5.13), pcluster can be a multiple of lcluster size.

For each HEAD lcluster, clusterofs is recorded to indicate where a new extent starts and blkaddr is used to seek the compressed data. For each NONHEAD lcluster, delta0 and delta1 are available instead of blkaddr to indicate the distance to its HEAD lcluster and the next HEAD lcluster. A PLAIN lcluster is also a HEAD lcluster except that its data is uncompressed. See the comments around "struct z_erofs_vle_decompressed_index" in erofs_fs.h for more details.

If big pcluster is enabled, pcluster size in lclusters needs to be recorded as well. Let the delta0 of the first NONHEAD lcluster store the compressed block count with a special flag as a new called CBLKCNT NONHEAD lcluster. It's easy to understand its delta0 is constantly 1, as illustrated below:



```text
 __________________________________________________________
| HEAD |  NONHEAD  | NONHEAD | ... | NONHEAD | HEAD | HEAD |
|__:___|_(CBLKCNT)_|_________|_____|_________|__:___|____:_|
   |<----- a big pcluster (with CBLKCNT) ------>|<--  -->|
         a lcluster-sized pcluster (without CBLKCNT) ^
```

If another HEAD follows a HEAD lcluster, there is no room to record CBLKCNT, but it's easy to know the size of such pcluster is 1 lcluster as well.

Since Linux v6.1, each pcluster can be used for multiple variable-sized extents, therefore it can be used for compressed data deduplication.

---

# The Second Extended Filesystem

_Peios Kernel / Internals / Filesystems_

> ext2 was originally released in January 1993. Written by R'emy Card, Theodore Ts'o and Stephen Tweedie, it was a major rewrite of the Extended Filesystem. It is currently still (April 2001) the predominant filesystem in use by Linux. There…

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-the-second-extended-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ext2 was originally released in January 1993.  Written by R'emy Card, Theodore Ts'o and Stephen Tweedie, it was a major rewrite of the Extended Filesystem.  It is currently still (April 2001) the predominant filesystem in use by Linux.  There are also implementations available for NetBSD, FreeBSD, the GNU HURD, Windows 95/98/NT, OS/2 and RISC OS.

<a id="rst-options"></a>

## Options

Most defaults are determined by the filesystem superblock, and can be set using tune2fs(8). Kernel-determined defaults are indicated by (\*).


<table>
<tbody>
<tr>
<td>


bsddf

</td>
<td>


(\*)

</td>
<td>


Makes `df` act like BSD.

</td>
</tr>
<tr>
<td>


minixdf

</td>
<td>




</td>
<td>


Makes `df` act like Minix.

</td>
</tr>
<tr>
<td>


check=none, nocheck

</td>
<td>


(\*)

</td>
<td>


Don't do extra checking of bitmaps on mount (check=normal and check=strict options removed)

</td>
</tr>
<tr>
<td>


dax

</td>
<td>




</td>
<td>


Use direct access (no page cache).  See [Documentation/filesystems/dax.rst](/kernel/internals/filesystems/dax.md).

</td>
</tr>
<tr>
<td>


debug

</td>
<td>




</td>
<td>


Extra debugging information is sent to the kernel syslog.  Useful for developers.

</td>
</tr>
<tr>
<td>


errors=continue

</td>
<td>




</td>
<td>


Keep going on a filesystem error.

</td>
</tr>
<tr>
<td>


errors=remount-ro

</td>
<td>




</td>
<td>


Remount the filesystem read-only on an error.

</td>
</tr>
<tr>
<td>


errors=panic

</td>
<td>




</td>
<td>


Panic and halt the machine if an error occurs.

</td>
</tr>
<tr>
<td>


grpid, bsdgroups

</td>
<td>




</td>
<td>


Give objects the same group ID as their parent.

</td>
</tr>
<tr>
<td>


nogrpid, sysvgroups

</td>
<td>




</td>
<td>


New objects have the group ID of their creator.

</td>
</tr>
<tr>
<td>


nouid32

</td>
<td>




</td>
<td>


Use 16-bit UIDs and GIDs.

</td>
</tr>
<tr>
<td>


oldalloc

</td>
<td>




</td>
<td>


Enable the old block allocator. Orlov should have better performance, we'd like to get some feedback if it's the contrary for you.

</td>
</tr>
<tr>
<td>


orlov

</td>
<td>


(\*)

</td>
<td>


Use the Orlov block allocator. (See [http://lwn.net/Articles/14633/](<http://lwn.net/Articles/14633/>) and [http://lwn.net/Articles/14446/](<http://lwn.net/Articles/14446/>).)

</td>
</tr>
<tr>
<td>


resuid=n

</td>
<td>




</td>
<td>


The user ID which may use the reserved blocks.

</td>
</tr>
<tr>
<td>


resgid=n

</td>
<td>




</td>
<td>


The group ID which may use the reserved blocks.

</td>
</tr>
<tr>
<td>


sb=n

</td>
<td>




</td>
<td>


Use alternate superblock at this location.

</td>
</tr>
<tr>
<td>


user_xattr

</td>
<td>




</td>
<td>


Enable "user." POSIX Extended Attributes (requires CONFIG_EXT2_FS_XATTR).

</td>
</tr>
<tr>
<td>


nouser_xattr

</td>
<td>




</td>
<td>


Don't support "user." extended attributes.

</td>
</tr>
<tr>
<td>


acl

</td>
<td>




</td>
<td>


Enable POSIX Access Control Lists support (requires CONFIG_EXT2_FS_POSIX_ACL).

</td>
</tr>
<tr>
<td>


noacl

</td>
<td>




</td>
<td>


Don't support POSIX ACLs.

</td>
</tr>
<tr>
<td>


quota, usrquota

</td>
<td>




</td>
<td>


Enable user disk quota support (requires CONFIG_QUOTA).

</td>
</tr>
<tr>
<td>


grpquota

</td>
<td>




</td>
<td>


Enable group disk quota support (requires CONFIG_QUOTA).

</td>
</tr>
</tbody>
</table>

noquota option ls silently ignored by ext2.

<a id="rst-specification"></a>

## Specification

ext2 shares many properties with traditional Unix filesystems.  It has the concepts of blocks, inodes and directories.  It has space in the specification for Access Control Lists (ACLs), fragments, undeletion and compression though these are not yet implemented (some are available as separate patches).  There is also a versioning mechanism to allow new features (such as journalling) to be added in a maximally compatible manner.

<a id="rst-blocks"></a>

### Blocks

The space in the device or file is split up into blocks.  These are a fixed size, of 1024, 2048 or 4096 bytes (8192 bytes on Alpha systems), which is decided when the filesystem is created.  Smaller blocks mean less wasted space per file, but require slightly more accounting overhead, and also impose other limits on the size of files and the filesystem.

<a id="rst-block-groups"></a>

### Block Groups

Blocks are clustered into block groups in order to reduce fragmentation and minimise the amount of head seeking when reading a large amount of consecutive data.  Information about each block group is kept in a descriptor table stored in the block(s) immediately after the superblock. Two blocks near the start of each group are reserved for the block usage bitmap and the inode usage bitmap which show which blocks and inodes are in use.  Since each bitmap is limited to a single block, this means that the maximum size of a block group is 8 times the size of a block.

The block(s) following the bitmaps in each block group are designated as the inode table for that block group and the remainder are the data blocks.  The block allocation algorithm attempts to allocate data blocks in the same block group as the inode which contains them.

<a id="rst-the-superblock"></a>

### The Superblock

The superblock contains all the information about the configuration of the filing system.  The primary copy of the superblock is stored at an offset of 1024 bytes from the start of the device, and it is essential to mounting the filesystem.  Since it is so important, backup copies of the superblock are stored in block groups throughout the filesystem. The first version of ext2 (revision 0) stores a copy at the start of every block group, along with backups of the group descriptor block(s). Because this can consume a considerable amount of space for large filesystems, later revisions can optionally reduce the number of backup copies by only putting backups in specific groups (this is the sparse superblock feature).  The groups chosen are 0, 1 and powers of 3, 5 and 7.

The information in the superblock contains fields such as the total number of inodes and blocks in the filesystem and how many are free, how many inodes and blocks are in each block group, when the filesystem was mounted (and if it was cleanly unmounted), when it was modified, what version of the filesystem it is (see the Revisions section below) and which OS created it.

If the filesystem is revision 1 or higher, then there are extra fields, such as a volume name, a unique identification number, the inode size, and space for optional filesystem features to store configuration info.

All fields in the superblock (as in all other ext2 structures) are stored on the disc in little endian format, so a filesystem is portable between machines without having to know what machine it was created on.

<a id="rst-inodes"></a>

### Inodes

The inode (index node) is a fundamental concept in the ext2 filesystem. Each object in the filesystem is represented by an inode.  The inode structure contains pointers to the filesystem blocks which contain the data held in the object and all of the metadata about an object except its name.  The metadata about an object includes the permissions, owner, group, flags, size, number of blocks used, access time, change time, modification time, deletion time, number of links, fragments, version (for NFS) and extended attributes (EAs) and/or Access Control Lists (ACLs).

There are some reserved fields which are currently unused in the inode structure and several which are overloaded.  One field is reserved for the directory ACL if the inode is a directory and alternately for the top 32 bits of the file size if the inode is a regular file (allowing file sizes larger than 2GB).  The translator field is unused under Linux, but is used by the HURD to reference the inode of a program which will be used to interpret this object.  Most of the remaining reserved fields have been used up for both Linux and the HURD for larger owner and group fields, The HURD also has a larger mode field so it uses another of the remaining fields to store the extra more bits.

There are pointers to the first 12 blocks which contain the file's data in the inode.  There is a pointer to an indirect block (which contains pointers to the next set of blocks), a pointer to a doubly-indirect block (which contains pointers to indirect blocks) and a pointer to a trebly-indirect block (which contains pointers to doubly-indirect blocks).

The flags field contains some ext2-specific flags which aren't catered for by the standard chmod flags.  These flags can be listed with lsattr and changed with the chattr command, and allow specific filesystem behaviour on a per-file basis.  There are flags for secure deletion, undeletable, compression, synchronous updates, immutability, append-only, dumpable, no-atime, indexed directories, and data-journaling.  Not all of these are supported yet.

<a id="rst-directories"></a>

### Directories

A directory is a filesystem object and has an inode just like a file. It is a specially formatted file containing records which associate each name with an inode number.  Later revisions of the filesystem also encode the type of the object (file, directory, symlink, device, fifo, socket) to avoid the need to check the inode itself for this information (support for taking advantage of this feature does not yet exist in Glibc 2.2).

The inode allocation code tries to assign inodes which are in the same block group as the directory in which they are first created.

The current implementation of ext2 uses a singly-linked list to store the filenames in the directory; a pending enhancement uses hashing of the filenames to allow lookup without the need to scan the entire directory.

The current implementation never removes empty directory blocks once they have been allocated to hold more files.

<a id="rst-special-files"></a>

### Special files

Symbolic links are also filesystem objects with inodes.  They deserve special mention because the data for them is stored within the inode itself if the symlink is less than 60 bytes long.  It uses the fields which would normally be used to store the pointers to data blocks. This is a worthwhile optimisation as it we avoid allocating a full block for the symlink, and most symlinks are less than 60 characters long.

Character and block special devices never have data blocks assigned to them.  Instead, their device number is stored in the inode, again reusing the fields which would be used to point to the data blocks.

<a id="rst-reserved-space"></a>

### Reserved Space

In ext2, there is a mechanism for reserving a certain number of blocks for a particular user (normally the super-user).  This is intended to allow for the system to continue functioning even if non-privileged users fill up all the space available to them (this is independent of filesystem quotas).  It also keeps the filesystem from filling up entirely which helps combat fragmentation.

<a id="rst-filesystem-check"></a>

### Filesystem check

At boot time, most systems run a consistency check (e2fsck) on their filesystems.  The superblock of the ext2 filesystem contains several fields which indicate whether fsck should actually run (since checking the filesystem at boot can take a long time if it is large).  fsck will run if the filesystem was not cleanly unmounted, if the maximum mount count has been exceeded or if the maximum time between checks has been exceeded.

<a id="rst-feature-compatibility"></a>

### Feature Compatibility

The compatibility feature mechanism used in ext2 is sophisticated. It safely allows features to be added to the filesystem, without unnecessarily sacrificing compatibility with older versions of the filesystem code.  The feature compatibility mechanism is not supported by the original revision 0 (EXT2_GOOD_OLD_REV) of ext2, but was introduced in revision 1.  There are three 32-bit fields, one for compatible features (COMPAT), one for read-only compatible (RO_COMPAT) features and one for incompatible (INCOMPAT) features.

These feature flags have specific meanings for the kernel as follows:

A COMPAT flag indicates that a feature is present in the filesystem, but the on-disk format is 100% compatible with older on-disk formats, so a kernel which didn't know anything about this feature could read/write the filesystem without any chance of corrupting the filesystem (or even making it inconsistent).  This is essentially just a flag which says "this filesystem has a (hidden) feature" that the kernel or e2fsck may want to be aware of (more on e2fsck and feature flags later).  The ext3 HAS_JOURNAL feature is a COMPAT flag because the ext3 journal is simply a regular file with data blocks in it so the kernel does not need to take any special notice of it if it doesn't understand ext3 journaling.

An RO_COMPAT flag indicates that the on-disk format is 100% compatible with older on-disk formats for reading (i.e. the feature does not change the visible on-disk format).  However, an old kernel writing to such a filesystem would/could corrupt the filesystem, so this is prevented. The most common such feature, SPARSE_SUPER, is an RO_COMPAT feature because sparse groups allow file data blocks where superblock/group descriptor backups used to live, and ext2_free_blocks() refuses to free these blocks, which would leading to inconsistent bitmaps.  An old kernel would also get an error if it tried to free a series of blocks which crossed a group boundary, but this is a legitimate layout in a SPARSE_SUPER filesystem.

An INCOMPAT flag indicates the on-disk format has changed in some way that makes it unreadable by older kernels, or would otherwise cause a problem if an old kernel tried to mount it.  FILETYPE is an INCOMPAT flag because older kernels would think a filename was longer than 256 characters, which would lead to corrupt directory listings. The COMPRESSION flag is an obvious INCOMPAT flag - if the kernel doesn't understand compression, you would just get garbage back from read() instead of it automatically decompressing your data.  The ext3 RECOVER flag is needed to prevent a kernel which does not understand the ext3 journal from mounting the filesystem without replaying the journal.

For e2fsck, it needs to be more strict with the handling of these flags than the kernel.  If it doesn't understand ANY of the COMPAT, RO_COMPAT, or INCOMPAT flags it will refuse to check the filesystem, because it has no way of verifying whether a given feature is valid or not.  Allowing e2fsck to succeed on a filesystem with an unknown feature is a false sense of security for the user.  Refusing to check a filesystem with unknown features is a good incentive for the user to update to the latest e2fsck.  This also means that anyone adding feature flags to ext2 also needs to update e2fsck to verify these features.

<a id="rst-metadata"></a>

### Metadata

It is frequently claimed that the ext2 implementation of writing asynchronous metadata is faster than the ffs synchronous metadata scheme but less reliable.  Both methods are equally resolvable by their respective fsck programs.

If you're exceptionally paranoid, there are 3 ways of making metadata writes synchronous on ext2:

- per-file if you have the program source: use the O_SYNC flag to open()

- per-file if you don't have the source: use "chattr +S" on the file

- per-filesystem: add the "sync" option to mount (or in /etc/fstab)

the first and last are not ext2 specific but do force the metadata to be written synchronously.  See also Journaling below.

<a id="rst-limitations"></a>

### Limitations

There are various limits imposed by the on-disk layout of ext2.  Other limits are imposed by the current implementation of the kernel code. Many of the limits are determined at the time the filesystem is first created, and depend upon the block size chosen.  The ratio of inodes to data blocks is fixed at filesystem creation time, so the only way to increase the number of inodes is to increase the size of the filesystem. No tools currently exist which can change the ratio of inodes to blocks.

Most of these limits could be overcome with slight changes in the on-disk format and using a compatibility flag to signal the format change (at the expense of some compatibility).


<table>
<thead>
<tr>
<th>


Filesystem block size

</th>
<th>


1kB

</th>
<th>


2kB

</th>
<th>


4kB

</th>
<th>


8kB

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


File size limit

</td>
<td>


16GB

</td>
<td>


256GB

</td>
<td>


2048GB

</td>
<td>


2048GB

</td>
</tr>
<tr>
<td>


Filesystem size limit

</td>
<td>


2047GB

</td>
<td>


8192GB

</td>
<td>


16384GB

</td>
<td>


32768GB

</td>
</tr>
</tbody>
</table>

There is a 2.4 kernel limit of 2048GB for a single block device, so no filesystem larger than that can be created at this time.  There is also an upper limit on the block size imposed by the page size of the kernel, so 8kB blocks are only allowed on Alpha systems (and other architectures which support larger pages).

There is an upper limit of 32000 subdirectories in a single directory.

There is a "soft" upper limit of about 10-15k files in a single directory with the current linear linked-list directory implementation.  This limit stems from performance problems when creating and deleting (and also finding) files in such large directories.  Using a hashed directory index (under development) allows 100k-1M+ files in a single directory without performance problems (although RAM size becomes an issue at this point).

The (meaningless) absolute upper limit of files in a single directory (imposed by the file size, the realistic limit is obviously much less) is over 130 trillion files.  It would be higher except there are not enough 4-character names to make up unique directory entries, so they have to be 8 character filenames, even then we are fairly close to running out of unique filenames.

<a id="rst-journaling"></a>

### Journaling

A journaling extension to the ext2 code has been developed by Stephen Tweedie.  It avoids the risks of metadata corruption and the need to wait for e2fsck to complete after a crash, without requiring a change to the on-disk ext2 layout.  In a nutshell, the journal is a regular file which stores whole metadata (and optionally data) blocks that have been modified, prior to writing them into the filesystem.  This means it is possible to add a journal to an existing ext2 filesystem without the need for data conversion.

When changes to the filesystem (e.g. a file is renamed) they are stored in a transaction in the journal and can either be complete or incomplete at the time of a crash.  If a transaction is complete at the time of a crash (or in the normal case where the system does not crash), then any blocks in that transaction are guaranteed to represent a valid filesystem state, and are copied into the filesystem.  If a transaction is incomplete at the time of the crash, then there is no guarantee of consistency for the blocks in that transaction so they are discarded (which means any filesystem changes they represent are also lost). Check Documentation/filesystems/ext4/ if you want to read more about ext4 and journaling.

<a id="rst-references"></a>

## References


<table>
<tbody>
<tr>
<td>


The kernel source

</td>
<td>


[file:/usr/src/linux/fs/ext2/](<file:/usr/src/linux/fs/ext2/>)

</td>
</tr>
<tr>
<td>


e2fsprogs (e2fsck)

</td>
<td>


[http://e2fsprogs.sourceforge.net/](<http://e2fsprogs.sourceforge.net/>)

</td>
</tr>
<tr>
<td>


Design &amp; Implementation

</td>
<td>


[http://e2fsprogs.sourceforge.net/ext2intro.html](<http://e2fsprogs.sourceforge.net/ext2intro.html>)

</td>
</tr>
<tr>
<td>


Journaling (ext3)

</td>
<td>


[ftp://ftp.uk.linux.org/pub/linux/sct/fs/jfs/](<ftp://ftp.uk.linux.org/pub/linux/sct/fs/jfs/>)

</td>
</tr>
<tr>
<td>


Filesystem Resizing

</td>
<td>


[http://ext2resize.sourceforge.net/](<http://ext2resize.sourceforge.net/>)

</td>
</tr>
<tr>
<td>


Compression <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

</td>
<td>


[http://e2compr.sourceforge.net/](<http://e2compr.sourceforge.net/>)

</td>
</tr>
</tbody>
</table>

Implementations for:


<table>
<tbody>
<tr>
<td>


Windows 95/98/NT/2000

</td>
<td>


[http://www.chrysocome.net/explore2fs](<http://www.chrysocome.net/explore2fs>)

</td>
</tr>
<tr>
<td>


Windows 95 <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1)

</td>
<td>


[http://www.yipton.net/content/fsdext2/](<http://www.yipton.net/content/fsdext2/>)

</td>
</tr>
<tr>
<td>


DOS client <a id="rst-footnote-reference-3"></a>[1](#rst-footnote-1)

</td>
<td>


[ftp://metalab.unc.edu/pub/Linux/system/filesystems/ext2/](<ftp://metalab.unc.edu/pub/Linux/system/filesystems/ext2/>)

</td>
</tr>
<tr>
<td>


OS/2 <a id="rst-footnote-reference-4"></a>[2](#rst-footnote-2)

</td>
<td>


[ftp://metalab.unc.edu/pub/Linux/system/filesystems/ext2/](<ftp://metalab.unc.edu/pub/Linux/system/filesystems/ext2/>)

</td>
</tr>
<tr>
<td>


RISC OS client

</td>
<td>


[http://www.esw-heim.tu-clausthal.de/\~marco/smorbrod/IscaFS/](<http://www.esw-heim.tu-clausthal.de/~marco/smorbrod/IscaFS/>)

</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-1"></a>



**[1]** no longer actively developed/supported (as of Apr 2001)

<a id="rst-footnote-2"></a>



**[2]** no longer actively developed/supported (as of Mar 2009)

---

# Ext3 Filesystem

_Peios Kernel / Internals / Filesystems_

> Ext3 was originally released in September 1999. Written by Stephen Tweedie for the 2.2 branch, and ported to 2.4 kernels by Peter Braam, Andreas Dilger, Andrew Morton, Alexander Viro, Ted Ts'o and Stephen Tweedie.

<a id="rst-ext3-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Ext3 was originally released in September 1999. Written by Stephen Tweedie for the 2.2 branch, and ported to 2.4 kernels by Peter Braam, Andreas Dilger, Andrew Morton, Alexander Viro, Ted Ts'o and Stephen Tweedie.

Ext3 is the ext2 filesystem enhanced with journalling capabilities. The filesystem is a subset of ext4 filesystem so use ext4 driver for accessing ext3 filesystems.

---

# Flash-Friendly File System (F2FS)

_Peios Kernel / Internals / Filesystems_

> NAND flash memory-based storage devices, such as SSD, eMMC, and SD cards, have been equipped on a variety systems ranging from mobile to server systems. Since they are known to have different characteristics from the conventional rotating…

<a id="rst-flash-friendly-file-system-f2fs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

NAND flash memory-based storage devices, such as SSD, eMMC, and SD cards, have been equipped on a variety systems ranging from mobile to server systems. Since they are known to have different characteristics from the conventional rotating disks, a file system, an upper layer to the storage device, should adapt to the changes from the sketch in the design level.

F2FS is a file system exploiting NAND flash memory-based storage devices, which is based on Log-structured File System (LFS). The design has been focused on addressing the fundamental issues in LFS, which are snowball effect of wandering tree and high cleaning overhead.

Since a NAND flash memory-based storage device shows different characteristic according to its internal geometry or flash memory management scheme, namely FTL, F2FS and its tools support various parameters not only for configuring on-disk layout, but also for selecting allocation and cleaning algorithms.

The following git tree provides the file system formatting tool (mkfs.f2fs), a consistency checking tool (fsck.f2fs), and a debugging tool (dump.f2fs).

- git://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git

For sending patches, please use the following mailing list:

- [linux-f2fs-devel@lists.sourceforge.net](<mailto:linux-f2fs-devel@lists.sourceforge.net>)

For reporting bugs, please use the following f2fs bug tracker link:

- [https://bugzilla.kernel.org/enter_bug.cgi?product=File%20System&amp;component=f2fs](<https://bugzilla.kernel.org/enter_bug.cgi?product=File%20System&component=f2fs>)

<a id="rst-background-and-design-issues"></a>

## Background and Design issues

<a id="rst-log-structured-file-system-lfs"></a>

### Log-structured File System (LFS)

"A log-structured file system writes all modifications to disk sequentially in a log-like structure, thereby speeding up  both file writing and crash recovery. The log is the only structure on disk; it contains indexing information so that files can be read back from the log efficiently. In order to maintain large free areas on disk for fast writing, we divide  the log into segments and use a segment cleaner to compress the live information from heavily fragmented segments." from Rosenblum, M. and Ousterhout, J. K., 1992, "The design and implementation of a log-structured file system", ACM Trans. Computer Systems 10, 1, 26–52.

<a id="rst-wandering-tree-problem"></a>

### Wandering Tree Problem

In LFS, when a file data is updated and written to the end of log, its direct pointer block is updated due to the changed location. Then the indirect pointer block is also updated due to the direct pointer block update. In this manner, the upper index structures such as inode, inode map, and checkpoint block are also updated recursively. This problem is called as wandering tree problem \[1\], and in order to enhance the performance, it should eliminate or relax the update propagation as much as possible.

\[1\] Bityutskiy, A. 2005. JFFS3 design issues. [http://www.linux-mtd.infradead.org/](<http://www.linux-mtd.infradead.org/>)

<a id="rst-cleaning-overhead"></a>

### Cleaning Overhead

Since LFS is based on out-of-place writes, it produces so many obsolete blocks scattered across the whole storage. In order to serve new empty log space, it needs to reclaim these obsolete blocks seamlessly to users. This job is called as a cleaning process.

The process consists of three operations as follows.

1. A victim segment is selected through referencing segment usage table.

2. It loads parent index structures of all the data in the victim identified by segment summary blocks.

3. It checks the cross-reference between the data and its parent index structure.

4. It moves valid data selectively.

This cleaning job may cause unexpected long delays, so the most important goal is to hide the latencies to users. And also definitely, it should reduce the amount of valid data to be moved, and move them quickly as well.

<a id="rst-key-features"></a>

## Key Features

<a id="rst-flash-awareness"></a>

### Flash Awareness

- Enlarge the random write area for better performance, but provide the high spatial locality

- Align FS data structures to the operational units in FTL as best efforts

<a id="rst-wandering-tree-problem-1"></a>

### Wandering Tree Problem

- Use a term, “node”, that represents inodes as well as various pointer blocks

- Introduce Node Address Table (NAT) containing the locations of all the “node” blocks; this will cut off the update propagation.

<a id="rst-cleaning-overhead-1"></a>

### Cleaning Overhead

- Support a background cleaning process

- Support greedy and cost-benefit algorithms for victim selection policies

- Support multi-head logs for static/dynamic hot and cold data separation

- Introduce adaptive logging for efficient block allocation

<a id="rst-mount-options"></a>

## Mount Options


<table>
<tbody>
<tr>
<td>


background_gc=%s

</td>
<td>


Turn on/off cleaning operations, namely garbage collection, triggered in background when I/O subsystem is idle. If background_gc=on, it will turn on the garbage collection and if background_gc=off, garbage collection will be turned off. If background_gc=sync, it will turn on synchronous garbage collection running in background. Default value for this option is on. So garbage collection is on by default.

</td>
</tr>
<tr>
<td>


gc_merge

</td>
<td>


When background_gc is on, this option can be enabled to let background GC thread to handle foreground GC requests, it can eliminate the sluggish issue caused by slow foreground GC operation when GC is triggered from a process with limited I/O and CPU resources.

</td>
</tr>
<tr>
<td>


nogc_merge

</td>
<td>


Disable GC merge feature.

</td>
</tr>
<tr>
<td>


disable_roll_forward

</td>
<td>


Disable the roll-forward recovery routine

</td>
</tr>
<tr>
<td>


norecovery

</td>
<td>


Disable the roll-forward recovery routine, mounted read- only (i.e., -o ro,disable_roll_forward)

</td>
</tr>
<tr>
<td>


discard/nodiscard

</td>
<td>


Enable/disable real-time discard in f2fs, if discard is enabled, f2fs will issue discard/TRIM commands when a segment is cleaned.

</td>
</tr>
<tr>
<td>


heap/no_heap

</td>
<td>


Deprecated.

</td>
</tr>
<tr>
<td>


nouser_xattr

</td>
<td>


Disable Extended User Attributes. Note: xattr is enabled by default if CONFIG_F2FS_FS_XATTR is selected.

</td>
</tr>
<tr>
<td>


noacl

</td>
<td>


Disable POSIX Access Control List. Note: acl is enabled by default if CONFIG_F2FS_FS_POSIX_ACL is selected.

</td>
</tr>
<tr>
<td>


active_logs=%u

</td>
<td>


Support configuring the number of active logs. In the current design, f2fs supports only 2, 4, and 6 logs. Default number is 6.

</td>
</tr>
<tr>
<td>


disable_ext_identify

</td>
<td>


Disable the extension list configured by mkfs, so f2fs is not aware of cold files such as media files.

</td>
</tr>
<tr>
<td>


inline_xattr

</td>
<td>


Enable the inline xattrs feature.

</td>
</tr>
<tr>
<td>


noinline_xattr

</td>
<td>


Disable the inline xattrs feature.

</td>
</tr>
<tr>
<td>


inline_xattr_size=%u

</td>
<td>


Support configuring inline xattr size, it depends on flexible inline xattr feature.

</td>
</tr>
<tr>
<td>


inline_data

</td>
<td>


Enable the inline data feature: Newly created small (&lt;\~3.4k) files can be written into inode block.

</td>
</tr>
<tr>
<td>


inline_dentry

</td>
<td>


Enable the inline dir feature: data in newly created directory entries can be written into inode block. The space of inode block which is used to store inline dentries is limited to \~3.4k.

</td>
</tr>
<tr>
<td>


noinline_dentry

</td>
<td>


Disable the inline dentry feature.

</td>
</tr>
<tr>
<td>


flush_merge

</td>
<td>


Merge concurrent cache_flush commands as much as possible to eliminate redundant command issues. If the underlying device handles the cache_flush command relatively slowly, recommend to enable this option.

</td>
</tr>
<tr>
<td>


nobarrier

</td>
<td>


This option can be used if underlying storage guarantees its cached data should be written to the novolatile area. If this option is set, no cache_flush commands are issued but f2fs still guarantees the write ordering of all the data writes.

</td>
</tr>
<tr>
<td>


barrier

</td>
<td>


If this option is set, cache_flush commands are allowed to be issued.

</td>
</tr>
<tr>
<td>


fastboot

</td>
<td>


This option is used when a system wants to reduce mount time as much as possible, even though normal performance can be sacrificed.

</td>
</tr>
<tr>
<td>


extent_cache

</td>
<td>


Enable an extent cache based on rb-tree, it can cache as many as extent which map between contiguous logical address and physical address per inode, resulting in increasing the cache hit ratio. Set by default.

</td>
</tr>
<tr>
<td>


noextent_cache

</td>
<td>


Disable an extent cache based on rb-tree explicitly, see the above extent_cache mount option.

</td>
</tr>
<tr>
<td>


noinline_data

</td>
<td>


Disable the inline data feature, inline data feature is enabled by default.

</td>
</tr>
<tr>
<td>


data_flush

</td>
<td>


Enable data flushing before checkpoint in order to persist data of regular and symlink.

</td>
</tr>
<tr>
<td>


reserve_root=%d

</td>
<td>


Support configuring reserved space which is used for allocation from a privileged user with specified uid or gid, unit: 4KB, the default limit is 12.5% of user blocks.

</td>
</tr>
<tr>
<td>


reserve_node=%d

</td>
<td>


Support configuring reserved nodes which are used for allocation from a privileged user with specified uid or gid, the default limit is 12.5% of all nodes.

</td>
</tr>
<tr>
<td>


resuid=%d

</td>
<td>


The user ID which may use the reserved blocks and nodes.

</td>
</tr>
<tr>
<td>


resgid=%d

</td>
<td>


The group ID which may use the reserved blocks and nodes.

</td>
</tr>
<tr>
<td>


fault_injection=%d

</td>
<td>


Enable fault injection in all supported types with specified injection rate.

</td>
</tr>
<tr>
<td>


fault_type=%d

</td>
<td>


Support configuring fault injection type, should be enabled with fault_injection option, fault type value is shown below, it supports single or combined type.



```none
===========================      ==========
Type_Name                        Type_Value
===========================      ==========
FAULT_KMALLOC                    0x00000001
FAULT_KVMALLOC                   0x00000002
FAULT_PAGE_ALLOC                 0x00000004
FAULT_PAGE_GET                   0x00000008
FAULT_ALLOC_BIO                  0x00000010 (obsolete)
FAULT_ALLOC_NID                  0x00000020
FAULT_ORPHAN                     0x00000040
FAULT_BLOCK                      0x00000080
FAULT_DIR_DEPTH                  0x00000100
FAULT_EVICT_INODE                0x00000200
FAULT_TRUNCATE                   0x00000400
FAULT_READ_IO                    0x00000800
FAULT_CHECKPOINT                 0x00001000
FAULT_DISCARD                    0x00002000 (obsolete)
FAULT_WRITE_IO                   0x00004000
FAULT_SLAB_ALLOC                 0x00008000
FAULT_DQUOT_INIT                 0x00010000
FAULT_LOCK_OP                    0x00020000
FAULT_BLKADDR_VALIDITY           0x00040000
FAULT_BLKADDR_CONSISTENCE        0x00080000
FAULT_NO_SEGMENT                 0x00100000
FAULT_INCONSISTENT_FOOTER        0x00200000
FAULT_ATOMIC_TIMEOUT             0x00400000 (1000ms)
FAULT_VMALLOC                    0x00800000
FAULT_LOCK_TIMEOUT               0x01000000 (1000ms)
FAULT_SKIP_WRITE                 0x02000000
===========================      ==========
```

</td>
</tr>
<tr>
<td>


mode=%s

</td>
<td>


Control block allocation mode which supports "adaptive" and "lfs". In "lfs" mode, there should be no random writes towards main area. "fragment:segment" and "fragment:block" are newly added here. These are developer options for experiments to simulate filesystem fragmentation/after-GC situation itself. The developers use these modes to understand filesystem fragmentation/after-GC condition well, and eventually get some insights to handle them better. In "fragment:segment", f2fs allocates a new segment in random position. With this, we can simulate the after-GC condition. In "fragment:block", we can scatter block allocation with "max_fragment_chunk" and "max_fragment_hole" sysfs nodes. We added some randomness to both chunk and hole size to make it close to realistic IO pattern. So, in this mode, f2fs will allocate 1..&lt;max_fragment_chunk&gt; blocks in a chunk and make a hole in the length of 1..&lt;max_fragment_hole&gt; by turns. With this, the newly allocated blocks will be scattered throughout the whole partition. Note that "fragment:block" implicitly enables "fragment:segment" option for more randomness. Please, use these options for your experiments and we strongly recommend to re-format the filesystem after using these options.

</td>
</tr>
<tr>
<td>


usrquota

</td>
<td>


Enable plain user disk quota accounting.

</td>
</tr>
<tr>
<td>


grpquota

</td>
<td>


Enable plain group disk quota accounting.

</td>
</tr>
<tr>
<td>


prjquota

</td>
<td>


Enable plain project quota accounting.

</td>
</tr>
<tr>
<td>


usrjquota=&lt;file&gt;

</td>
<td>


Appoint specified file and type during mount, so that quota

</td>
</tr>
<tr>
<td>


grpjquota=&lt;file&gt;

</td>
<td>


information can be properly updated during recovery flow,

</td>
</tr>
<tr>
<td>


prjjquota=&lt;file&gt;

</td>
<td>


&lt;quota file&gt;: must be in root directory;

</td>
</tr>
<tr>
<td>


jqfmt=&lt;quota type&gt;

</td>
<td>


&lt;quota type&gt;: \[vfsold,vfsv0,vfsv1\].

</td>
</tr>
<tr>
<td>


usrjquota=

</td>
<td>


Turn off user journalled quota.

</td>
</tr>
<tr>
<td>


grpjquota=

</td>
<td>


Turn off group journalled quota.

</td>
</tr>
<tr>
<td>


prjjquota=

</td>
<td>


Turn off project journalled quota.

</td>
</tr>
<tr>
<td>


quota

</td>
<td>


Enable plain user disk quota accounting.

</td>
</tr>
<tr>
<td>


noquota

</td>
<td>


Disable all plain disk quota option.

</td>
</tr>
<tr>
<td>


alloc_mode=%s

</td>
<td>


Adjust block allocation policy, which supports "reuse" and "default".

</td>
</tr>
<tr>
<td>


fsync_mode=%s

</td>
<td>


Control the policy of fsync. Currently supports "posix", "strict", and "nobarrier". In "posix" mode, which is default, fsync will follow POSIX semantics and does a light operation to improve the filesystem performance. In "strict" mode, fsync will be heavy and behaves in line with xfs, ext4 and btrfs, where xfstest generic/342 will pass, but the performance will regress. "nobarrier" is based on "posix", but doesn't issue flush command for non-atomic files likewise "nobarrier" mount option.

</td>
</tr>
<tr>
<td>


test_dummy_encryption

</td>
<td>




</td>
</tr>
<tr>
<td>


test_dummy_encryption=%s

</td>
<td>


Enable dummy encryption, which provides a fake fscrypt context. The fake fscrypt context is used by xfstests. The argument may be either "v1" or "v2", in order to select the corresponding fscrypt policy version.

</td>
</tr>
<tr>
<td>


checkpoint=%s\[:%u\[%\]\]

</td>
<td>


Set to "disable" to turn off checkpointing. Set to "enable" to re-enable checkpointing. Is enabled by default. While disabled, any unmounting or unexpected shutdowns will cause the filesystem contents to appear as they did when the filesystem was mounted with that option. While mounting with checkpoint=disable, the filesystem must run garbage collection to ensure that all available space can be used. If this takes too much time, the mount may return EAGAIN. You may optionally add a value to indicate how much of the disk you would be willing to temporarily give up to avoid additional garbage collection. This can be given as a number of blocks, or as a percent. For instance, mounting with checkpoint=disable:100% would always succeed, but it may hide up to all remaining free space. The actual space that would be unusable can be viewed at /sys/fs/f2fs/&lt;disk&gt;/unusable This space is reclaimed once checkpoint=enable.

</td>
</tr>
<tr>
<td>


checkpoint_merge

</td>
<td>


When checkpoint is enabled, this can be used to create a kernel daemon and make it to merge concurrent checkpoint requests as much as possible to eliminate redundant checkpoint issues. Plus, we can eliminate the sluggish issue caused by slow checkpoint operation when the checkpoint is done in a process context in a cgroup having low i/o budget and cpu shares. To make this do better, we set the default i/o priority of the kernel daemon to "3", to give one higher priority than other kernel threads. This is the same way to give a I/O priority to the jbd2 journaling thread of ext4 filesystem.

</td>
</tr>
<tr>
<td>


nocheckpoint_merge

</td>
<td>


Disable checkpoint merge feature.

</td>
</tr>
<tr>
<td>


compress_algorithm=%s

</td>
<td>


Control compress algorithm, currently f2fs supports "lzo", "lz4", "zstd" and "lzo-rle" algorithm.

</td>
</tr>
<tr>
<td>


compress_algorithm=%s:%d

</td>
<td>


Control compress algorithm and its compress level, now, only "lz4" and "zstd" support compress level config:



```text
=========      ===========
algorithm      level range
=========      ===========
lz4            3 - 16
zstd           1 - 22
=========      ===========
```

</td>
</tr>
<tr>
<td>


compress_log_size=%u

</td>
<td>


Support configuring compress cluster size. The size will be 4KB \* (1 &lt;&lt; %u). The default and minimum sizes are 16KB.

</td>
</tr>
<tr>
<td>


compress_extension=%s

</td>
<td>


Support adding specified extension, so that f2fs can enable compression on those corresponding files, e.g. if all files with '.ext' has high compression rate, we can set the '.ext' on compression extension list and enable compression on these file by default rather than to enable it via ioctl. For other files, we can still enable compression via ioctl. Note that, there is one reserved special extension '\*', it can be set to enable compression for all files.

</td>
</tr>
<tr>
<td>


nocompress_extension=%s

</td>
<td>


Support adding specified extension, so that f2fs can disable compression on those corresponding files, just contrary to compression extension. If you know exactly which files cannot be compressed, you can use this. The same extension name can't appear in both compress and nocompress extension at the same time. If the compress extension specifies all files, the types specified by the nocompress extension will be treated as special cases and will not be compressed. Don't allow use '\*' to specifie all file in nocompress extension. After add nocompress_extension, the priority should be: dir_flag &lt; comp_extention,nocompress_extension &lt; comp_file_flag,no_comp_file_flag. See more in compression sections.

</td>
</tr>
<tr>
<td>


compress_chksum

</td>
<td>


Support verifying chksum of raw data in compressed cluster.

</td>
</tr>
<tr>
<td>


compress_mode=%s

</td>
<td>


Control file compression mode. This supports "fs" and "user" modes. In "fs" mode (default), f2fs does automatic compression on the compression enabled files. In "user" mode, f2fs disables the automaic compression and gives the user discretion of choosing the target file and the timing. The user can do manual compression/decompression on the compression enabled files using ioctls.

</td>
</tr>
<tr>
<td>


compress_cache

</td>
<td>


Support to use address space of a filesystem managed inode to cache compressed block, in order to improve cache hit ratio of random read.

</td>
</tr>
<tr>
<td>


inlinecrypt

</td>
<td>


When possible, encrypt/decrypt the contents of encrypted files using the blk-crypto framework rather than filesystem-layer encryption. This allows the use of inline encryption hardware. The on-disk format is unaffected. For more details, see [Documentation/block/inline-encryption.rst](/kernel/internals/block/inline-encryption.md).

</td>
</tr>
<tr>
<td>


atgc

</td>
<td>


Enable age-threshold garbage collection, it provides high effectiveness and efficiency on background GC.

</td>
</tr>
<tr>
<td>


discard_unit=%s

</td>
<td>


Control discard unit, the argument can be "block", "segment" and "section", issued discard command's offset/size will be aligned to the unit, by default, "discard_unit=block" is set, so that small discard functionality is enabled. For blkzoned device, "discard_unit=section" will be set by default, it is helpful for large sized SMR or ZNS devices to reduce memory cost by getting rid of fs metadata supports small discard.

</td>
</tr>
<tr>
<td>


memory=%s

</td>
<td>


Control memory mode. This supports "normal" and "low" modes. "low" mode is introduced to support low memory devices. Because of the nature of low memory devices, in this mode, f2fs will try to save memory sometimes by sacrificing performance. "normal" mode is the default mode and same as before.

</td>
</tr>
<tr>
<td>


age_extent_cache

</td>
<td>


Enable an age extent cache based on rb-tree. It records data block update frequency of the extent per inode, in order to provide better temperature hints for data block allocation.

</td>
</tr>
<tr>
<td>


errors=%s

</td>
<td>


Specify f2fs behavior on critical errors. This supports modes: "panic", "continue" and "remount-ro", respectively, trigger panic immediately, continue without doing anything, and remount the partition in read-only mode. By default it uses "continue" mode.



```none
====================== =============== =============== ========
mode                   continue        remount-ro      panic
====================== =============== =============== ========
access ops             normal          normal          N/A
syscall errors         -EIO            -EROFS          N/A
mount option           rw              ro              N/A
pending dir write      keep            keep            N/A
pending non-dir write  drop            keep            N/A
pending node write     drop            keep            N/A
pending meta write     keep            keep            N/A
====================== =============== =============== ========
```

</td>
</tr>
<tr>
<td>


nat_bits

</td>
<td>


Enable nat_bits feature to enhance full/empty nat blocks access, by default it's disabled.

</td>
</tr>
<tr>
<td>


lookup_mode=%s

</td>
<td>


Control the directory lookup behavior for casefolded directories. This option has no effect on directories that do not have the casefold feature enabled.



```none
================== ========================================
Value              Description
================== ========================================
perf               (Default) Enforces a hash-only lookup.
                   The linear search fallback is always
                   disabled, ignoring the on-disk flag.
compat             Enables the linear search fallback for
                   compatibility with directory entries
                   created by older kernel that used a
                   different case-folding algorithm.
                   This mode ignores the on-disk flag.
auto               F2FS determines the mode based on the
                   on-disk `SB_ENC_NO_COMPAT_FALLBACK_FL`
                   flag.
================== ========================================
```

</td>
</tr>
</tbody>
</table>

<a id="rst-debugfs-entries"></a>

## Debugfs Entries

/sys/kernel/debug/f2fs/ contains information about all the partitions mounted as f2fs. Each file shows the whole f2fs information.

/sys/kernel/debug/f2fs/status includes:

> - major file system information managed by f2fs currently
>
> - average SIT information about whole segments
>
> - current memory footprint consumed by f2fs.

<a id="rst-sysfs-entries"></a>

## Sysfs Entries

Information about mounted f2fs file systems can be found in /sys/fs/f2fs.  Each mounted filesystem will have a directory in /sys/fs/f2fs based on its device name (i.e., /sys/fs/f2fs/sda). The files in each per-device directory are shown in table below.

Files in /sys/fs/f2fs/&lt;devname&gt; (see also Documentation/ABI/testing/sysfs-fs-f2fs)

<a id="rst-usage"></a>

## Usage

1. Download userland tools and compile them.

2. Skip, if f2fs was compiled statically inside kernel. Otherwise, insert the f2fs.ko module:



   ```text
   # insmod f2fs.ko
   ```

3. Create a directory to use when mounting:



   ```text
   # mkdir /mnt/f2fs
   ```

4. Format the block device, and then mount as f2fs:



   ```text
   # mkfs.f2fs -l label /dev/block_device
   # mount -t f2fs /dev/block_device /mnt/f2fs
   ```

<a id="rst-mkfs-f2fs"></a>

### mkfs.f2fs

The mkfs.f2fs is for the use of formatting a partition as the f2fs filesystem, which builds a basic on-disk layout.

The quick options consist of:


<table>
<tbody>
<tr>
<td>


`-l [label]`

</td>
<td>


Give a volume label, up to 512 unicode name.

</td>
</tr>
<tr>
<td>


`-a [0 or 1]`

</td>
<td>


Split start location of each area for heap-based allocation.

1 is set by default, which performs this.

</td>
</tr>
<tr>
<td>


`-o [int]`

</td>
<td>


Set overprovision ratio in percent over volume size.

5 is set by default.

</td>
</tr>
<tr>
<td>


`-s [int]`

</td>
<td>


Set the number of segments per section.

1 is set by default.

</td>
</tr>
<tr>
<td>


`-z [int]`

</td>
<td>


Set the number of sections per zone.

1 is set by default.

</td>
</tr>
<tr>
<td>


`-e [str]`

</td>
<td>


Set basic extension list. e.g. "mp3,gif,mov"

</td>
</tr>
<tr>
<td>


`-t [0 or 1]`

</td>
<td>


Disable discard command or not.

1 is set by default, which conducts discard.

</td>
</tr>
</tbody>
</table>

Note: please refer to the manpage of mkfs.f2fs(8) to get full option list.

<a id="rst-fsck-f2fs"></a>

### fsck.f2fs

The fsck.f2fs is a tool to check the consistency of an f2fs-formatted partition, which examines whether the filesystem metadata and user-made data are cross-referenced correctly or not. Note that, initial version of the tool does not fix any inconsistency.

The quick options consist of:



```text
-d debug level [default:0]
```

Note: please refer to the manpage of fsck.f2fs(8) to get full option list.

<a id="rst-dump-f2fs"></a>

### dump.f2fs

The dump.f2fs shows the information of specific inode and dumps SSA and SIT to file. Each file is dump_ssa and dump_sit.

The dump.f2fs is used to debug on-disk data structures of the f2fs filesystem. It shows on-disk inode information recognized by a given inode number, and is able to dump all the SSA and SIT entries into predefined files, ./dump_ssa and ./dump_sit respectively.

The options consist of:



```text
-d debug level [default:0]
-i inode no (hex)
-s [SIT dump segno from #1~#2 (decimal), for all 0~-1]
-a [SSA dump segno from #1~#2 (decimal), for all 0~-1]
```

Examples:



```text
# dump.f2fs -i [ino] /dev/sdx
# dump.f2fs -s 0~-1 /dev/sdx (SIT dump)
# dump.f2fs -a 0~-1 /dev/sdx (SSA dump)
```

Note: please refer to the manpage of dump.f2fs(8) to get full option list.

<a id="rst-sload-f2fs"></a>

### sload.f2fs

The sload.f2fs gives a way to insert files and directories in the existing disk image. This tool is useful when building f2fs images given compiled files.

Note: please refer to the manpage of sload.f2fs(8) to get full option list.

<a id="rst-resize-f2fs"></a>

### resize.f2fs

The resize.f2fs lets a user resize the f2fs-formatted disk image, while preserving all the files and directories stored in the image.

Note: please refer to the manpage of resize.f2fs(8) to get full option list.

<a id="rst-defrag-f2fs"></a>

### defrag.f2fs

The defrag.f2fs can be used to defragment scattered written data as well as filesystem metadata across the disk. This can improve the write speed by giving more free consecutive space.

Note: please refer to the manpage of defrag.f2fs(8) to get full option list.

<a id="rst-f2fs-io"></a>

### f2fs_io

The f2fs_io is a simple tool to issue various filesystem APIs as well as f2fs-specific ones, which is very useful for QA tests.

Note: please refer to the manpage of f2fs_io(8) to get full option list.

<a id="rst-design"></a>

## Design

<a id="rst-on-disk-layout"></a>

### On-disk Layout

F2FS divides the whole volume into a number of segments, each of which is fixed to 2MB in size. A section is composed of consecutive segments, and a zone consists of a set of sections. By default, section and zone sizes are set to one segment size identically, but users can easily modify the sizes by mkfs.

F2FS splits the entire volume into six areas, and all the areas except superblock consist of multiple segments as described below:



```text
                                        align with the zone size <-|
             |-> align with the segment size
 _________________________________________________________________________
|            |            |   Segment   |    Node     |   Segment  |      |
| Superblock | Checkpoint |    Info.    |   Address   |   Summary  | Main |
|    (SB)    |   (CP)     | Table (SIT) | Table (NAT) | Area (SSA) |      |
|____________|_____2______|______N______|______N______|______N_____|__N___|
                                                                   .      .
                                                         .                .
                                             .                            .
                                ._________________________________________.
                                |_Segment_|_..._|_Segment_|_..._|_Segment_|
                                .           .
                                ._________._________
                                |_section_|__...__|_
                                .            .
                                .________.
                                |__zone__|
```

- - **Superblock (SB)**

    It is located at the beginning of the partition, and there exist two copies to avoid file system crash. It contains basic partition information and some default parameters of f2fs.

- - **Checkpoint (CP)**

    It contains file system information, bitmaps for valid NAT/SIT sets, orphan inode lists, and summary entries of current active segments.

- - **Segment Information Table (SIT)**

    It contains segment information such as valid block count and bitmap for the validity of all the blocks.

- - **Node Address Table (NAT)**

    It is composed of a block address table for all the node blocks stored in Main area.

- - **Segment Summary Area (SSA)**

    It contains summary entries which contains the owner information of all the data and node blocks stored in Main area.

- - **Main Area**

    It contains file and directory data including their indices.

In order to avoid misalignment between file system and flash-based storage, F2FS aligns the start block address of CP with the segment size. Also, it aligns the start block address of Main area with the zone size by reserving some segments in SSA area.

Reference the following survey for additional technical details. [https://wiki.linaro.org/WorkingGroups/Kernel/Projects/FlashCardSurvey](<https://wiki.linaro.org/WorkingGroups/Kernel/Projects/FlashCardSurvey>)

<a id="rst-file-system-metadata-structure"></a>

### File System Metadata Structure

F2FS adopts the checkpointing scheme to maintain file system consistency. At mount time, F2FS first tries to find the last valid checkpoint data by scanning CP area. In order to reduce the scanning time, F2FS uses only two copies of CP. One of them always indicates the last valid data, which is called as shadow copy mechanism. In addition to CP, NAT and SIT also adopt the shadow copy mechanism.

For file system consistency, each CP points to which NAT and SIT copies are valid, as shown as below:



```text
+--------+----------+---------+
|   CP   |    SIT   |   NAT   |
+--------+----------+---------+
.         .          .          .
.            .              .              .
.               .                 .                 .
+-------+-------+--------+--------+--------+--------+
| CP #0 | CP #1 | SIT #0 | SIT #1 | NAT #0 | NAT #1 |
+-------+-------+--------+--------+--------+--------+
   |             ^                          ^
   |             |                          |
   `----------------------------------------'
```

<a id="rst-index-structure"></a>

### Index Structure

The key data structure to manage the data locations is a "node". Similar to traditional file structures, F2FS has three types of node: inode, direct node, indirect node. F2FS assigns 4KB to an inode block which contains 923 data block indices, two direct node pointers, two indirect node pointers, and one double indirect node pointer as described below. One direct node block contains 1018 data blocks, and one indirect node block contains also 1018 node blocks. Thus, one inode block (i.e., a file) covers:



```text
4KB * (923 + 2 * 1018 + 2 * 1018 * 1018 + 1018 * 1018 * 1018) := 3.94TB.

 Inode block (4KB)
   |- data (923)
   |- direct node (2)
   |          `- data (1018)
   |- indirect node (2)
   |            `- direct node (1018)
   |                       `- data (1018)
   `- double indirect node (1)
                       `- indirect node (1018)
                                    `- direct node (1018)
                                               `- data (1018)
```

Note that all the node blocks are mapped by NAT which means the location of each node is translated by the NAT table. In the consideration of the wandering tree problem, F2FS is able to cut off the propagation of node updates caused by leaf data writes.

<a id="rst-directory-structure"></a>

### Directory Structure

A directory entry occupies 11 bytes, which consists of the following attributes.

- hash          hash value of the file name

- ino           inode number

- len           the length of file name

- type          file type such as directory, symlink, etc

A dentry block consists of 214 dentry slots and file names. Therein a bitmap is used to represent whether each dentry is valid or not. A dentry block occupies 4KB with the following composition.



```text
Dentry Block(4 K) = bitmap (27 bytes) + reserved (3 bytes) +
                    dentries(11 * 214 bytes) + file name (8 * 214 bytes)

                       [Bucket]
           +--------------------------------+
           |dentry block 1 | dentry block 2 |
           +--------------------------------+
           .               .
     .                             .
.       [Dentry Block Structure: 4KB]       .
+--------+----------+----------+------------+
| bitmap | reserved | dentries | file names |
+--------+----------+----------+------------+
[Dentry Block: 4KB] .   .
               .               .
          .                          .
          +------+------+-----+------+
          | hash | ino  | len | type |
          +------+------+-----+------+
          [Dentry Structure: 11 bytes]
```

F2FS implements multi-level hash tables for directory structure. Each level has a hash table with dedicated number of hash buckets as shown below. Note that "A(2B)" means a bucket includes 2 data blocks.



```text
----------------------
A : bucket
B : block
N : MAX_DIR_HASH_DEPTH
----------------------

level #0   | A(2B)
        |
level #1   | A(2B) - A(2B)
        |
level #2   | A(2B) - A(2B) - A(2B) - A(2B)
    .     |   .       .       .       .
level #N/2 | A(2B) - A(2B) - A(2B) - A(2B) - A(2B) - ... - A(2B)
    .     |   .       .       .       .
level #N   | A(4B) - A(4B) - A(4B) - A(4B) - A(4B) - ... - A(4B)
```

The number of blocks and buckets are determined by:



```text
                          ,- 2, if n < MAX_DIR_HASH_DEPTH / 2,
# of blocks in level #n = |
                          `- 4, Otherwise

                           ,- 2^(n + dir_level),
                           |        if n + dir_level < MAX_DIR_HASH_DEPTH / 2,
# of buckets in level #n = |
                           `- 2^((MAX_DIR_HASH_DEPTH / 2) - 1),
                                    Otherwise
```

When F2FS finds a file name in a directory, at first a hash value of the file name is calculated. Then, F2FS scans the hash table in level \#0 to find the dentry consisting of the file name and its inode number. If not found, F2FS scans the next hash table in level \#1. In this way, F2FS scans hash tables in each levels incrementally from 1 to N. In each level F2FS needs to scan only one bucket determined by the following equation, which shows O(log(\# of files)) complexity:



```text
bucket number to scan in level #n = (hash value) % (# of buckets in level #n)
```

In the case of file creation, F2FS finds empty consecutive slots that cover the file name. F2FS searches the empty slots in the hash tables of whole levels from 1 to N in the same way as the lookup operation.

The following figure shows an example of two cases holding children:



```text
    --------------> Dir <--------------
    |                                 |
 child                             child

 child - child                     [hole] - child

 child - child - child             [hole] - [hole] - child

Case 1:                           Case 2:
Number of children = 6,           Number of children = 3,
File size = 7                     File size = 7
```

<a id="rst-default-block-allocation"></a>

### Default Block Allocation

At runtime, F2FS manages six active logs inside "Main" area: Hot/Warm/Cold node and Hot/Warm/Cold data.

- Hot node      contains direct node blocks of directories.

- Warm node     contains direct node blocks except hot node blocks.

- Cold node     contains indirect node blocks

- Hot data      contains dentry blocks

- Warm data     contains data blocks except hot and cold data blocks

- Cold data     contains multimedia data or migrated data blocks

LFS has two schemes for free space management: threaded log and copy-and-compac- tion. The copy-and-compaction scheme which is known as cleaning, is well-suited for devices showing very good sequential write performance, since free segments are served all the time for writing new data. However, it suffers from cleaning overhead under high utilization. Contrarily, the threaded log scheme suffers from random writes, but no cleaning process is needed. F2FS adopts a hybrid scheme where the copy-and-compaction scheme is adopted by default, but the policy is dynamically changed to the threaded log scheme according to the file system status.

In order to align F2FS with underlying flash-based storage, F2FS allocates a segment in a unit of section. F2FS expects that the section size would be the same as the unit size of garbage collection in FTL. Furthermore, with respect to the mapping granularity in FTL, F2FS allocates each section of the active logs from different zones as much as possible, since FTL can write the data in the active logs into one allocation unit according to its mapping granularity.

<a id="rst-cleaning-process"></a>

### Cleaning process

F2FS does cleaning both on demand and in the background. On-demand cleaning is triggered when there are not enough free segments to serve VFS calls. Background cleaner is operated by a kernel thread, and triggers the cleaning job when the system is idle.

F2FS supports two victim selection policies: greedy and cost-benefit algorithms. In the greedy algorithm, F2FS selects a victim segment having the smallest number of valid blocks. In the cost-benefit algorithm, F2FS selects a victim segment according to the segment age and the number of valid blocks in order to address log block thrashing problem in the greedy algorithm. F2FS adopts the greedy algorithm for on-demand cleaner, while background cleaner adopts cost-benefit algorithm.

In order to identify whether the data in the victim segment are valid or not, F2FS manages a bitmap. Each bit represents the validity of a block, and the bitmap is composed of a bit stream covering whole blocks in main area.

<a id="rst-write-hint-policy"></a>

### Write-hint Policy

F2FS sets the whint all the time with the below policy.


<table>
<thead>
<tr>
<th>


User

</th>
<th>


F2FS

</th>
<th>


Block

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


N/A

</td>
<td>


META

</td>
<td>


WRITE_LIFE_NONE\|REQ_META

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


HOT_NODE

</td>
<td>


WRITE_LIFE_NONE

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


WARM_NODE

</td>
<td>


WRITE_LIFE_MEDIUM

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


COLD_NODE

</td>
<td>


WRITE_LIFE_LONG

</td>
</tr>
<tr>
<td>


ioctl(COLD)

</td>
<td>


COLD_DATA

</td>
<td>


WRITE_LIFE_EXTREME

</td>
</tr>
<tr>
<td>


extension list

</td>
<td>


"

</td>
<td>


"

</td>
</tr>
<tr>
<td colspan="3">


-- buffered io

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


COLD_DATA

</td>
<td>


WRITE_LIFE_EXTREME

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


HOT_DATA

</td>
<td>


WRITE_LIFE_SHORT

</td>
</tr>
<tr>
<td>


N/A

</td>
<td>


WARM_DATA

</td>
<td>


WRITE_LIFE_NOT_SET

</td>
</tr>
<tr>
<td colspan="3">


-- direct io

</td>
</tr>
<tr>
<td>


WRITE_LIFE_EXTREME

</td>
<td>


COLD_DATA

</td>
<td>


WRITE_LIFE_EXTREME

</td>
</tr>
<tr>
<td>


WRITE_LIFE_SHORT

</td>
<td>


HOT_DATA

</td>
<td>


WRITE_LIFE_SHORT

</td>
</tr>
<tr>
<td>


WRITE_LIFE_NOT_SET

</td>
<td>


WARM_DATA

</td>
<td>


WRITE_LIFE_NOT_SET

</td>
</tr>
<tr>
<td>


WRITE_LIFE_NONE

</td>
<td>


"

</td>
<td>


WRITE_LIFE_NONE

</td>
</tr>
<tr>
<td>


WRITE_LIFE_MEDIUM

</td>
<td>


"

</td>
<td>


WRITE_LIFE_MEDIUM

</td>
</tr>
<tr>
<td>


WRITE_LIFE_LONG

</td>
<td>


"

</td>
<td>


WRITE_LIFE_LONG

</td>
</tr>
</tbody>
</table>

<a id="rst-fallocate-2-policy"></a>

### Fallocate(2) Policy

The default policy follows the below POSIX rule.

- **Allocating disk space**

  The default operation (i.e., mode is zero) of fallocate() allocates the disk space within the range specified by offset and len.  The file size (as reported by stat(2)) will be changed if offset+len is greater than the file size.  Any subregion within the range specified by offset and len that did not contain data before the call will be initialized to zero.  This default behavior closely resembles the behavior of the posix_fallocate(3) library function, and is intended as a method of optimally implementing that function.

However, once F2FS receives ioctl(fd, F2FS_IOC_SET_PIN_FILE) in prior to fallocate(fd, DEFAULT_MODE), it allocates on-disk block addresses having zero or random data, which is useful to the below scenario where:

> 1. create(fd)
>
> 2. ioctl(fd, F2FS_IOC_SET_PIN_FILE)
>
> 3. fallocate(fd, 0, 0, size)
>
> 4. address = fibmap(fd, offset)
>
> 5. open(blkdev)
>
> 6. write(blkdev, address)

<a id="rst-compression-implementation"></a>

### Compression implementation

- New term named cluster is defined as basic unit of compression, file can be divided into multiple clusters logically. One cluster includes 4 &lt;&lt; n (n &gt;= 0) logical pages, compression size is also cluster size, each of cluster can be compressed or not.

- In cluster metadata layout, one special block address is used to indicate a cluster is a compressed one or normal one; for compressed cluster, following metadata maps cluster to \[1, 4 &lt;&lt; n - 1\] physical blocks, in where f2fs stores data including compress header and compressed data.

- In order to eliminate write amplification during overwrite, F2FS only support compression on write-once file, data can be compressed only when all logical blocks in cluster contain valid data and compress ratio of cluster data is lower than specified threshold.

- To enable compression on regular inode, there are four ways:

  - chattr +c file

  - chattr +c dir; touch dir/file

  - mount w/ -o compress_extension=ext; touch file.ext

  - mount w/ -o compress_extension=\*; touch any_file

- To disable compression on regular inode, there are two ways:

  - chattr -c file

  - mount w/ -o nocompress_extension=ext; touch file.ext

- Priority in between FS_COMPR_FL, FS_NOCOMP_FS, extensions:

  - compress_extension=so; nocompress_extension=zip; chattr +c dir; touch dir/foo.so; touch dir/bar.zip; touch dir/baz.txt; then foo.so and baz.txt should be compresse, bar.zip should be non-compressed. chattr +c dir/bar.zip can enable compress on bar.zip.

  - compress_extension=so; nocompress_extension=zip; chattr -c dir; touch dir/foo.so; touch dir/bar.zip; touch dir/baz.txt; then foo.so should be compresse, bar.zip and baz.txt should be non-compressed. chattr+c dir/bar.zip; chattr+c dir/baz.txt; can enable compress on bar.zip and baz.txt.

- At this point, compression feature doesn't expose compressed space to user directly in order to guarantee potential data updates later to the space. Instead, the main goal is to reduce data writes to flash disk as much as possible, resulting in extending disk life time as well as relaxing IO congestion. Alternatively, we've added ioctl(F2FS_IOC_RELEASE_COMPRESS_BLOCKS) interface to reclaim compressed space and show it to user after setting a special flag to the inode. Once the compressed space is released, the flag will block writing data to the file until either the compressed space is reserved via ioctl(F2FS_IOC_RESERVE_COMPRESS_BLOCKS) or the file size is truncated to zero.

Compress metadata layout:



```text
                            [Dnode Structure]
            +-----------------------------------------------+
            | cluster 1 | cluster 2 | ......... | cluster N |
            +-----------------------------------------------+
            .           .                       .           .
      .                      .                .                      .
.         Compressed Cluster       .        .        Normal Cluster            .
+----------+---------+---------+---------+  +---------+---------+---------+---------+
|compr flag| block 1 | block 2 | block 3 |  | block 1 | block 2 | block 3 | block 4 |
+----------+---------+---------+---------+  +---------+---------+---------+---------+
           .                             .
        .                                           .
    .                                                           .
    +-------------+-------------+----------+----------------------------+
    | data length | data chksum | reserved |      compressed data       |
    +-------------+-------------+----------+----------------------------+
```

<a id="rst-compression-mode"></a>

### Compression mode

f2fs supports "fs" and "user" compression modes with "compression_mode" mount option. With this option, f2fs provides a choice to select the way how to compress the compression enabled files (refer to "Compression implementation" section for how to enable compression on a regular inode).

1. compress_mode=fs

   This is the default option. f2fs does automatic compression in the writeback of the compression enabled files.

2. compress_mode=user

   This disables the automatic compression and gives the user discretion of choosing the target file and the timing. The user can do manual compression/decompression on the compression enabled files using F2FS_IOC_DECOMPRESS_FILE and F2FS_IOC_COMPRESS_FILE ioctls like the below.

To decompress a file:



```text
fd = open(filename, O_WRONLY, 0);
ret = ioctl(fd, F2FS_IOC_DECOMPRESS_FILE);
```

To compress a file:



```text
fd = open(filename, O_WRONLY, 0);
ret = ioctl(fd, F2FS_IOC_COMPRESS_FILE);
```

<a id="rst-nvme-zoned-namespace-devices"></a>

### NVMe Zoned Namespace devices

- ZNS defines a per-zone capacity which can be equal or less than the zone-size. Zone-capacity is the number of usable blocks in the zone. F2FS checks if zone-capacity is less than zone-size, if it is, then any segment which starts after the zone-capacity is marked as not-free in the free segment bitmap at initial mount time. These segments are marked as permanently used so they are not allocated for writes and consequently are not needed to be garbage collected. In case the zone-capacity is not aligned to default segment size(2MB), then a segment can start before the zone-capacity and span across zone-capacity boundary. Such spanning segments are also considered as usable segments. All blocks past the zone-capacity are considered unusable in these segments.

<a id="rst-device-aliasing-feature"></a>

### Device aliasing feature

f2fs can utilize a special file called a "device aliasing file." This file allows the entire storage device to be mapped with a single, large extent, not using the usual f2fs node structures. This mapped area is pinned and primarily intended for holding the space.

Essentially, this mechanism allows a portion of the f2fs area to be temporarily reserved and used by another filesystem or for different purposes. Once that external usage is complete, the device aliasing file can be deleted, releasing the reserved space back to F2FS for its own use.



```text
# ls /dev/vd*
/dev/vdb (32GB) /dev/vdc (32GB)
# mkfs.ext4 /dev/vdc
# mkfs.f2fs -c /dev/vdc@vdc.file /dev/vdb
# mount /dev/vdb /mnt/f2fs
# ls -l /mnt/f2fs
vdc.file
# df -h
/dev/vdb                            64G   33G   32G  52% /mnt/f2fs

# mount -o loop /dev/vdc /mnt/ext4
# df -h
/dev/vdb                            64G   33G   32G  52% /mnt/f2fs
/dev/loop7                          32G   24K   30G   1% /mnt/ext4
# umount /mnt/ext4

# f2fs_io getflags /mnt/f2fs/vdc.file
get a flag on /mnt/f2fs/vdc.file ret=0, flags=nocow(pinned),immutable
# f2fs_io setflags noimmutable /mnt/f2fs/vdc.file
get a flag on noimmutable ret=0, flags=800010
set a flag on /mnt/f2fs/vdc.file ret=0, flags=noimmutable
# rm /mnt/f2fs/vdc.file
# df -h
/dev/vdb                            64G  753M   64G   2% /mnt/f2fs
```

So, the key idea is, user can do any file operations on /dev/vdc, and reclaim the space after the use, while the space is counted as /data. That doesn't require modifying partition size and filesystem format.

<a id="rst-per-file-read-only-large-folio-support"></a>

### Per-file Read-Only Large Folio Support

F2FS implements large folio support on the read path to leverage high-order page allocation for significant performance gains. To minimize code complexity, this support is currently excluded from the write path, which requires handling complex optimizations such as compression and block allocation modes.

This optional feature is triggered only when a file's immutable bit is set. Consequently, F2FS will return EOPNOTSUPP if a user attempts to open a cached file with write permissions, even immediately after clearing the bit. Write access is only restored once the cached inode is dropped. The usage flow is demonstrated below:



```text
# f2fs_io setflags immutable /data/testfile_read_seq

/* flush and reload the inode to enable the large folio */
# sync && echo 3 > /proc/sys/vm/drop_caches

/* mmap(MAP_POPULATE) + mlock() */
# f2fs_io read 128 0 1024 mmap 1 0 /data/testfile_read_seq

/* mmap() + fadvise(POSIX_FADV_WILLNEED) + mlock() */
# f2fs_io read 128 0 1024 fadvise 1 0 /data/testfile_read_seq

/* mmap() + mlock2(MLOCK_ONFAULT) + madvise(MADV_POPULATE_READ) */
# f2fs_io read 128 0 1024 madvise 1 0 /data/testfile_read_seq

# f2fs_io clearflags immutable /data/testfile_read_seq

# f2fs_io write 1 0 1 zero buffered /data/testfile_read_seq
Failed to open /mnt/test/test: Operation not supported

/* flush and reload the inode to disable the large folio */
# sync && echo 3 > /proc/sys/vm/drop_caches

# f2fs_io write 1 0 1 zero buffered /data/testfile_read_seq
Written 4096 bytes with pattern = zero, total_time = 29 us, max_latency = 28 us

# rm /data/testfile_read_seq
```

---

# Fiemap Ioctl

_Peios Kernel / Internals / Filesystems_

> The fiemap ioctl is an efficient method for userspace to get file extent mappings. Instead of block-by-block mapping (such as bmap), fiemap returns a list of extents.

<a id="rst-fiemap-ioctl"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The fiemap ioctl is an efficient method for userspace to get file extent mappings. Instead of block-by-block mapping (such as bmap), fiemap returns a list of extents.

<a id="rst-request-basics"></a>

## Request Basics

A fiemap request is encoded within struct fiemap:


#### <a id="c-struct-fiemap"></a>`struct fiemap`

file extent mappings

**Definition**

```c
struct fiemap {
    __u64 fm_start;
    __u64 fm_length;
    __u32 fm_flags;
    __u32 fm_mapped_extents;
    __u32 fm_extent_count;
    struct fiemap_extent fm_extents[];
};
```

**Members**

- `fm_start`: byte offset (inclusive) at which to start mapping (in)
- `fm_length`: logical length of mapping which userspace wants (in)
- `fm_flags`: FIEMAP_FLAG_* flags for request (in/out)
- `fm_mapped_extents`: number of extents that were mapped (out)
- `fm_extent_count`: size of fm_extents array (in)
- `fm_extents`: array of mapped extents (out)


fm_start, and fm_length specify the logical range within the file which the process would like mappings for. Extents returned mirror those on disk - that is, the logical offset of the 1st returned extent may start before fm_start, and the range covered by the last returned extent may end after fm_length. All offsets and lengths are in bytes.

Certain flags to modify the way in which mappings are looked up can be set in fm_flags. If the kernel doesn't understand some particular flags, it will return EBADR and the contents of fm_flags will contain the set of flags which caused the error. If the kernel is compatible with all flags passed, the contents of fm_flags will be unmodified. It is up to userspace to determine whether rejection of a particular flag is fatal to its operation. This scheme is intended to allow the fiemap interface to grow in the future but without losing compatibility with old software.

fm_extent_count specifies the number of elements in the fm_extents\[\] array that can be used to return extents.  If fm_extent_count is zero, then the fm_extents\[\] array is ignored (no extents will be returned), and the fm_mapped_extents count will hold the number of extents needed in fm_extents\[\] to hold the file's current mapping.  Note that there is nothing to prevent the file from changing between calls to FIEMAP.

The following flags can be set in fm_flags:

- **FIEMAP_FLAG_SYNC**

  If this flag is set, the kernel will sync the file before mapping extents.

- **FIEMAP_FLAG_XATTR**

  If this flag is set, the extents returned will describe the inodes extended attribute lookup tree, instead of its data tree.

- **FIEMAP_FLAG_CACHE**

  This flag requests caching of the extents.

<a id="rst-extent-mapping"></a>

## Extent Mapping

Extent information is returned within the embedded fm_extents array which userspace must allocate along with the fiemap structure. The number of elements in the fiemap_extents\[\] array should be passed via fm_extent_count. The number of extents mapped by kernel will be returned via fm_mapped_extents. If the number of fiemap_extents allocated is less than would be required to map the requested range, the maximum number of extents that can be mapped in the fm_extent\[\] array will be returned and fm_mapped_extents will be equal to fm_extent_count. In that case, the last extent in the array will not complete the requested range and will not have the FIEMAP_EXTENT_LAST flag set (see the next section on extent flags).

Each extent is described by a single fiemap_extent structure as returned in fm_extents:


#### <a id="c-struct-fiemap_extent"></a>`struct fiemap_extent`

description of one fiemap extent

**Definition**

```c
struct fiemap_extent {
    __u64 fe_logical;
    __u64 fe_physical;
    __u64 fe_length;
    __u32 fe_flags;
};
```

**Members**

- `fe_logical`: byte offset of the extent in the file
- `fe_physical`: byte offset of extent on disk
- `fe_length`: length in bytes for this extent
- `fe_flags`: FIEMAP_EXTENT_* flags for this extent


All offsets and lengths are in bytes and mirror those on disk.  It is valid for an extents logical offset to start before the request or its logical length to extend past the request.  Unless FIEMAP_EXTENT_NOT_ALIGNED is returned, fe_logical, fe_physical, and fe_length will be aligned to the block size of the file system.  With the exception of extents flagged as FIEMAP_EXTENT_MERGED, adjacent extents will not be merged.

The fe_flags field contains flags which describe the extent returned. A special flag, FIEMAP_EXTENT_LAST is always set on the last extent in the file so that the process making fiemap calls can determine when no more extents are available, without having to call the ioctl again.

Some flags are intentionally vague and will always be set in the presence of other more specific flags. This way a program looking for a general property does not have to know all existing and future flags which imply that property.

For example, if FIEMAP_EXTENT_DATA_INLINE or FIEMAP_EXTENT_DATA_TAIL are set, FIEMAP_EXTENT_NOT_ALIGNED will also be set. A program looking for inline or tail-packed data can key on the specific flag. Software which simply cares not to try operating on non-aligned extents however, can just key on FIEMAP_EXTENT_NOT_ALIGNED, and not have to worry about all present and future flags which might imply unaligned data. Note that the opposite is not true - it would be valid for FIEMAP_EXTENT_NOT_ALIGNED to appear alone.

- **FIEMAP_EXTENT_LAST**

  This is generally the last extent in the file. A mapping attempt past this extent may return nothing. Some implementations set this flag to indicate this extent is the last one in the range queried by the user (via fiemap-&gt;fm_length).

- **FIEMAP_EXTENT_UNKNOWN**

  The location of this extent is currently unknown. This may indicate the data is stored on an inaccessible volume or that no storage has been allocated for the file yet.

- **FIEMAP_EXTENT_DELALLOC**

  This will also set FIEMAP_EXTENT_UNKNOWN.

  Delayed allocation - while there is data for this extent, its physical location has not been allocated yet.

- **FIEMAP_EXTENT_ENCODED**

  This extent does not consist of plain filesystem blocks but is encoded (e.g. encrypted or compressed).  Reading the data in this extent via I/O to the block device will have undefined results.

Note that it is *always* undefined to try to update the data in-place by writing to the indicated location without the assistance of the filesystem, or to access the data using the information returned by the FIEMAP interface while the filesystem is mounted.  In other words, user applications may only read the extent data via I/O to the block device while the filesystem is unmounted, and then only if the FIEMAP_EXTENT_ENCODED flag is clear; user applications must not try reading or writing to the filesystem via the block device under any other circumstances.

- **FIEMAP_EXTENT_DATA_ENCRYPTED**

  This will also set FIEMAP_EXTENT_ENCODED The data in this extent has been encrypted by the file system.

- **FIEMAP_EXTENT_NOT_ALIGNED**

  Extent offsets and length are not guaranteed to be block aligned.

- **FIEMAP_EXTENT_DATA_INLINE**

  This will also set FIEMAP_EXTENT_NOT_ALIGNED Data is located within a meta data block.

- **FIEMAP_EXTENT_DATA_TAIL**

  This will also set FIEMAP_EXTENT_NOT_ALIGNED Data is packed into a block with data from other files.

- **FIEMAP_EXTENT_UNWRITTEN**

  Unwritten extent - the extent is allocated but its data has not been initialized.  This indicates the extent's data will be all zero if read through the filesystem but the contents are undefined if read directly from the device.

- **FIEMAP_EXTENT_MERGED**

  This will be set when a file does not support extents, i.e., it uses a block based addressing scheme.  Since returning an extent for each block back to userspace would be highly inefficient, the kernel will try to merge most adjacent blocks into 'extents'.

- **FIEMAP_EXTENT_SHARED**

  This flag is set to request that space be shared with other files.

<a id="rst-vfs-file-system-implementation"></a>

## VFS -&gt; File System Implementation

File systems wishing to support fiemap must implement a -&gt;fiemap callback on their inode_operations structure. The fs -&gt;fiemap call is responsible for defining its set of supported fiemap flags, and calling a helper function on each discovered extent:



```text
struct inode_operations {
     ...

     int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start,
                   u64 len);
```

-&gt;fiemap is passed struct fiemap_extent_info which describes the fiemap request:


#### <a id="c-struct-fiemap_extent_info"></a>`struct fiemap_extent_info`

fiemap request to a filesystem

**Definition**

```c
struct fiemap_extent_info {
    unsigned int fi_flags;
    unsigned int fi_extents_mapped;
    unsigned int fi_extents_max;
    struct fiemap_extent __user *fi_extents_start;
};
```

**Members**

- `fi_flags`: Flags as passed from user
- `fi_extents_mapped`: Number of mapped extents
- `fi_extents_max`: Size of fiemap_extent array
- `fi_extents_start`: Start of fiemap_extent array


It is intended that the file system should not need to access any of this structure directly. Filesystem handlers should be tolerant to signals and return EINTR once fatal signal received.

Flag checking should be done at the beginning of the -&gt;fiemap callback via the fiemap_prep() helper:



```text
int fiemap_prep(struct inode *inode, struct fiemap_extent_info *fieinfo,
                u64 start, u64 *len, u32 supported_flags);
```

The struct fieinfo should be passed in as received from ioctl_fiemap(). The set of fiemap flags which the fs understands should be passed via fs_flags. If fiemap_prep finds invalid user flags, it will place the bad values in fieinfo-&gt;fi_flags and return -EBADR. If the file system gets -EBADR, from fiemap_prep(), it should immediately exit, returning that error back to ioctl_fiemap().  Additionally the range is validate against the supported maximum file size.

For each extent in the request range, the file system should call the helper function, fiemap_fill_next_extent():



```text
int fiemap_fill_next_extent(struct fiemap_extent_info *info, u64 logical,
                            u64 phys, u64 len, u32 flags, u32 dev);
```

fiemap_fill_next_extent() will use the passed values to populate the next free extent in the fm_extents array. 'General' extent flags will automatically be set from specific flags on behalf of the calling file system so that the userspace API is not broken.

fiemap_fill_next_extent() returns 0 on success, and 1 when the user-supplied fm_extents array is full. If an error is encountered while copying the extent to user memory, -EFAULT will be returned.

---

# File management in the Linux kernel

_Peios Kernel / Internals / Filesystems_

> This document describes how locking for files (struct file) and file descriptor table (struct files) works.

<a id="rst-file-management-in-the-linux-kernel"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes how locking for files (struct file) and file descriptor table (struct files) works.

Up until 2.6.12, the file descriptor table has been protected with a lock (files-&gt;file_lock) and reference count (files-&gt;count). -&gt;file_lock protected accesses to all the file related fields of the table. -&gt;count was used for sharing the file descriptor table between tasks cloned with CLONE_FILES flag. Typically this would be the case for posix threads. As with the common refcounting model in the kernel, the last task doing a put_files_struct() frees the file descriptor (fd) table. The files (struct file) themselves are protected using reference count (-&gt;f_count).

In the new lock-free model of file descriptor management, the reference counting is similar, but the locking is based on RCU. The file descriptor table contains multiple elements - the fd sets (open_fds and close_on_exec, the array of file pointers, the sizes of the sets and the array etc.). In order for the updates to appear atomic to a lock-free reader, all the elements of the file descriptor table are in a separate structure - struct fdtable. files_struct contains a pointer to struct fdtable through which the actual fd table is accessed. Initially the fdtable is embedded in files_struct itself. On a subsequent expansion of fdtable, a new fdtable structure is allocated and files-&gt;fdtab points to the new structure. The fdtable structure is freed with RCU and lock-free readers either see the old fdtable or the new fdtable making the update appear atomic. Here are the locking rules for the fdtable structure -

1. All references to the fdtable must be done through the files_fdtable() macro:



   ```text
   struct fdtable *fdt;

   rcu_read_lock();

   fdt = files_fdtable(files);
   ....
   if (n <= fdt->max_fds)
           ....
   ...
   rcu_read_unlock();
   ```

   files_fdtable() uses rcu_dereference() macro which takes care of the memory barrier requirements for lock-free dereference. The fdtable pointer must be read within the read-side critical section.

2. Reading of the fdtable as described above must be protected by rcu_read_lock()/rcu_read_unlock().

3. For any update to the fd table, files-&gt;file_lock must be held.

4. To look up the file structure given an fd, a reader must use either lookup_fdget_rcu() or files_lookup_fdget_rcu() APIs. These take care of barrier requirements due to lock-free lookup.

   An example:



   ```text
   struct file *file;

   rcu_read_lock();
   file = lookup_fdget_rcu(fd);
   rcu_read_unlock();
   if (file) {
           ...
           fput(file);
   }
   ....
   ```

5. Since both fdtable and file structures can be looked up lock-free, they must be installed using rcu_assign_pointer() API. If they are looked up lock-free, rcu_dereference() must be used. However it is advisable to use files_fdtable() and lookup_fdget_rcu()/files_lookup_fdget_rcu() which take care of these issues.

6. While updating, the fdtable pointer must be looked up while holding files-&gt;file_lock. If -&gt;file_lock is dropped, then another thread expand the files thereby creating a new fdtable and making the earlier fdtable pointer stale.

   For example:



   ```text
   spin_lock(&files->file_lock);
   fd = locate_fd(files, file, start);
   if (fd >= 0) {
           /* locate_fd() may have expanded fdtable, load the ptr */
           fdt = files_fdtable(files);
           __set_open_fd(fd, fdt);
           __clear_close_on_exec(fd, fdt);
           spin_unlock(&files->file_lock);
   .....
   ```

   Since locate_fd() can drop -&gt;file_lock (and reacquire -&gt;file_lock), the fdtable pointer (fdt) must be loaded after locate_fd().

On newer kernels rcu based file lookup has been switched to rely on SLAB_TYPESAFE_BY_RCU instead of call_rcu(). It isn't sufficient anymore to just acquire a reference to the file in question under rcu using atomic_long_inc_not_zero() since the file might have already been recycled and someone else might have bumped the reference. In other words, callers might see reference count bumps from newer users. For this is reason it is necessary to verify that the pointer is the same before and after the reference count increment. This pattern can be seen in get_file_rcu() and \__files_get_rcu().

In addition, it isn't possible to access or check fields in struct file without first acquiring a reference on it under rcu lookup. Not doing that was always very dodgy and it was only usable for non-pointer data in struct file. With SLAB_TYPESAFE_BY_RCU it is necessary that callers either first acquire a reference or they must hold the files_lock of the fdtable.

---

# Filesystem-level encryption (fscrypt)

_Peios Kernel / Internals / Filesystems_

> fscrypt is a library which filesystems can hook into to support transparent encryption of files and directories.

> **Peios:** Filesystem encryption remains distinct from native access control. References to root or Linux capabilities below describe the inherited threat model and compatibility checks. UID 0 is not a KACS bypass; `CAP_FOWNER` is a compatibility pass, and descriptor, handle and ioctl checks still apply. An fscrypt key is not a native file-access grant. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-filesystem-level-encryption-fscrypt"></a>

<a id="rst-introduction"></a>

## Introduction

fscrypt is a library which filesystems can hook into to support transparent encryption of files and directories.

Note: "fscrypt" in this document refers to the kernel-level portion, implemented in `fs/crypto/`, as opposed to the userspace tool [fscrypt](<https://github.com/google/fscrypt>)<a id="rst-fscrypt"></a>.  This document only covers the kernel-level portion.  For command-line examples of how to use encryption, see the documentation for the userspace tool [fscrypt](<https://github.com/google/fscrypt>)<a id="rst-fscrypt-1"></a>.  Also, it is recommended to use the fscrypt userspace tool, or other existing userspace tools such as [fscryptctl](<https://github.com/google/fscryptctl>)<a id="rst-fscryptctl"></a> or [Android's key management system](<https://source.android.com/security/encryption/file-based>)<a id="rst-android-s-key-management-system"></a>, over using the kernel's API directly.  Using existing tools reduces the chance of introducing your own security bugs.  (Nevertheless, for completeness this documentation covers the kernel's API anyway.)

Unlike dm-crypt, fscrypt operates at the filesystem level rather than at the block device level.  This allows it to encrypt different files with different keys and to have unencrypted files on the same filesystem.  This is useful for multi-user systems where each user's data-at-rest needs to be cryptographically isolated from the others. However, except for filenames, fscrypt does not encrypt filesystem metadata.

Unlike eCryptfs, which is a stacked filesystem, fscrypt is integrated directly into supported filesystems --- currently ext4, F2FS, UBIFS, and CephFS.  This allows encrypted files to be read and written without caching both the decrypted and encrypted pages in the pagecache, thereby nearly halving the memory used and bringing it in line with unencrypted files.  Similarly, half as many dentries and inodes are needed.  eCryptfs also limits encrypted filenames to 143 bytes, causing application compatibility issues; fscrypt allows the full 255 bytes (NAME_MAX).  Finally, unlike eCryptfs, the fscrypt API can be used by unprivileged users, with no need to mount anything.

fscrypt does not support encrypting files in-place.  Instead, it supports marking an empty directory as encrypted.  Then, after userspace provides the key, all regular files, directories, and symbolic links created in that directory tree are transparently encrypted.

<a id="rst-threat-model"></a>

## Threat model

<a id="rst-offline-attacks"></a>

### Offline attacks

Provided that userspace chooses a strong encryption key, fscrypt protects the confidentiality of file contents and filenames in the event of a single point-in-time permanent offline compromise of the block device content.  fscrypt does not protect the confidentiality of non-filename metadata, e.g. file sizes, file permissions, file timestamps, and extended attributes.  Also, the existence and location of holes (unallocated blocks which logically contain all zeroes) in files is not protected.

fscrypt is not guaranteed to protect confidentiality or authenticity if an attacker is able to manipulate the filesystem offline prior to an authorized user later accessing the filesystem.

<a id="rst-online-attacks"></a>

### Online attacks

fscrypt (and storage encryption in general) can only provide limited protection against online attacks.  In detail:

<a id="rst-side-channel-attacks"></a>

#### Side-channel attacks

fscrypt is only resistant to side-channel attacks, such as timing or electromagnetic attacks, to the extent that the underlying Linux Cryptographic API algorithms or inline encryption hardware are.  If a vulnerable algorithm is used, such as a table-based implementation of AES, it may be possible for an attacker to mount a side channel attack against the online system.  Side channel attacks may also be mounted against applications consuming decrypted data.

<a id="rst-unauthorized-file-access"></a>

#### Unauthorized file access

After an encryption key has been added, fscrypt does not hide the plaintext file contents or filenames from other users on the same system.  Instead, existing access control mechanisms such as file mode bits, POSIX ACLs, LSMs, or namespaces should be used for this purpose.

(For the reasoning behind this, understand that while the key is added, the confidentiality of the data, from the perspective of the system itself, is *not* protected by the mathematical properties of encryption but rather only by the correctness of the kernel. Therefore, any encryption-specific access control checks would merely be enforced by kernel *code* and therefore would be largely redundant with the wide variety of access control mechanisms already available.)

<a id="rst-read-only-kernel-memory-compromise"></a>

#### Read-only kernel memory compromise

Unless [hardware-wrapped keys](<#rst-hardware-wrapped-keys>) are used, an attacker who gains the ability to read from arbitrary kernel memory, e.g. by mounting a physical attack or by exploiting a kernel security vulnerability, can compromise all fscrypt keys that are currently in-use.  This also extends to cold boot attacks; if the system is suddenly powered off, keys the system was using may remain in memory for a short time.

However, if hardware-wrapped keys are used, then the fscrypt master keys and file contents encryption keys (but not other types of fscrypt subkeys such as filenames encryption keys) are protected from compromises of arbitrary kernel memory.

In addition, fscrypt allows encryption keys to be removed from the kernel, which may protect them from later compromise.

In more detail, the FS_IOC_REMOVE_ENCRYPTION_KEY ioctl (or the FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS ioctl) can wipe a master encryption key from kernel memory.  If it does so, it will also try to evict all cached inodes which had been "unlocked" using the key, thereby wiping their per-file keys and making them once again appear "locked", i.e. in ciphertext or encrypted form.

However, these ioctls have some limitations:

- Per-file keys for in-use files will *not* be removed or wiped. Therefore, for maximum effect, userspace should close the relevant encrypted files and directories before removing a master key, as well as kill any processes whose working directory is in an affected encrypted directory.

- The kernel cannot magically wipe copies of the master key(s) that userspace might have as well.  Therefore, userspace must wipe all copies of the master key(s) it makes as well; normally this should be done immediately after FS_IOC_ADD_ENCRYPTION_KEY, without waiting for FS_IOC_REMOVE_ENCRYPTION_KEY.  Naturally, the same also applies to all higher levels in the key hierarchy.  Userspace should also follow other security precautions such as mlock()ing memory containing keys to prevent it from being swapped out.

- In general, decrypted contents and filenames in the kernel VFS caches are freed but not wiped.  Therefore, portions thereof may be recoverable from freed memory, even after the corresponding key(s) were wiped.  To partially solve this, you can add init_on_free=1 to your kernel command line.  However, this has a performance cost.

- Secret keys might still exist in CPU registers or in other places not explicitly considered here.

<a id="rst-full-system-compromise"></a>

#### Full system compromise

An attacker able to execute arbitrary kernel code can exfiltrate data protected by in-use fscrypt keys. In Peios, Unix UID 0 alone is not equivalent to this compromise: native authorization still governs managed file and process access. An attacker with sufficient native authority to read unlocked files can obtain their plaintext without breaking the encryption.  Thus, usually fscrypt provides no meaningful protection in this scenario.  (Data that is protected by a key that is absent throughout the entire attack remains protected, modulo the limitations of key removal mentioned above in the case where the key was removed prior to the attack.)

However, if [hardware-wrapped keys](<#rst-hardware-wrapped-keys>) are used, such attackers will be unable to exfiltrate the master keys or file contents keys in a form that will be usable after the system is powered off.  This may be useful if the attacker is significantly time-limited and/or bandwidth-limited, so they can only exfiltrate some data and need to rely on a later offline attack to exfiltrate the rest of it.

<a id="rst-limitations-of-v1-policies"></a>

#### Limitations of v1 policies

v1 encryption policies have some weaknesses with respect to online attacks:

- There is no verification that the provided master key is correct. Therefore, a malicious user can temporarily associate the wrong key with another user's encrypted files to which they have read-only access.  Because of filesystem caching, the wrong key will then be used by the other user's accesses to those files, even if the other user has the correct key in their own keyring.  This violates the meaning of "read-only access".

- A compromise of a per-file key also compromises the master key from which it was derived.

- Removing v1 keys through the filesystem keyring API requires `CAP_SYS_ADMIN`, mapped to enabled `SeTcbPrivilege` in Peios. The legacy process-keyring mechanism has separate removal limitations.

All the above problems are fixed with v2 encryption policies.  For this reason among others, it is recommended to use v2 encryption policies on all new encrypted directories.

<a id="rst-key-hierarchy"></a>

## Key hierarchy

Note: this section assumes the use of raw keys rather than hardware-wrapped keys.  The use of hardware-wrapped keys modifies the key hierarchy slightly.  For details, see [Hardware-wrapped keys](<#rst-hardware-wrapped-keys>).

<a id="rst-master-keys"></a>

### Master Keys

Each encrypted directory tree is protected by a *master key*.  Master keys can be up to 64 bytes long, and must be at least as long as the greater of the security strength of the contents and filenames encryption modes being used.  For example, if any AES-256 mode is used, the master key must be at least 256 bits, i.e. 32 bytes.  A stricter requirement applies if the key is used by a v1 encryption policy and AES-256-XTS is used; such keys must be 64 bytes.

To "unlock" an encrypted directory tree, userspace must provide the appropriate master key.  There can be any number of master keys, each of which protects any number of directory trees on any number of filesystems.

Master keys must be real cryptographic keys, i.e. indistinguishable from random bytestrings of the same length.  This implies that users **must not** directly use a password as a master key, zero-pad a shorter key, or repeat a shorter key.  Security cannot be guaranteed if userspace makes any such error, as the cryptographic proofs and analysis would no longer apply.

Instead, users should generate master keys either using a cryptographically secure random number generator, or by using a KDF (Key Derivation Function).  The kernel does not do any key stretching; therefore, if userspace derives the key from a low-entropy secret such as a passphrase, it is critical that a KDF designed for this purpose be used, such as scrypt, PBKDF2, or Argon2.

<a id="rst-key-derivation-function"></a>

### Key derivation function

With one exception, fscrypt never uses the master key(s) for encryption directly.  Instead, they are only used as input to a KDF (Key Derivation Function) to derive the actual keys.

The KDF used for a particular master key differs depending on whether the key is used for v1 encryption policies or for v2 encryption policies.  Users **must not** use the same key for both v1 and v2 encryption policies.  (No real-world attack is currently known on this specific case of key reuse, but its security cannot be guaranteed since the cryptographic proofs and analysis would no longer apply.)

For v1 encryption policies, the KDF only supports deriving per-file encryption keys.  It works by encrypting the master key with AES-128-ECB, using the file's 16-byte nonce as the AES key.  The resulting ciphertext is used as the derived key.  If the ciphertext is longer than needed, then it is truncated to the needed length.

For v2 encryption policies, the KDF is HKDF-SHA512.  The master key is passed as the "input keying material", no salt is used, and a distinct "application-specific information string" is used for each distinct key to be derived.  For example, when a per-file encryption key is derived, the application-specific information string is the file's nonce prefixed with "fscrypt\\0" and a context byte.  Different context bytes are used for other types of derived keys.

HKDF-SHA512 is preferred to the original AES-128-ECB based KDF because HKDF is more flexible, is nonreversible, and evenly distributes entropy from the master key.  HKDF is also standardized and widely used by other software, whereas the AES-128-ECB based KDF is ad-hoc.

<a id="rst-per-file-encryption-keys"></a>

### Per-file encryption keys

Since each master key can protect many files, it is necessary to "tweak" the encryption of each file so that the same plaintext in two files doesn't map to the same ciphertext, or vice versa.  In most cases, fscrypt does this by deriving per-file keys.  When a new encrypted inode (regular file, directory, or symlink) is created, fscrypt randomly generates a 16-byte nonce and stores it in the inode's encryption xattr.  Then, it uses a KDF (as described in [Key derivation function](<#rst-key-derivation-function>)) to derive the file's key from the master key and nonce.

Key derivation was chosen over key wrapping because wrapped keys would require larger xattrs which would be less likely to fit in-line in the filesystem's inode table, and there didn't appear to be any significant advantages to key wrapping.  In particular, currently there is no requirement to support unlocking a file with multiple alternative master keys or to support rotating master keys.  Instead, the master keys may be wrapped in userspace, e.g. as is done by the [fscrypt](<https://github.com/google/fscrypt>)<a id="rst-fscrypt-2"></a> tool.

<a id="rst-direct-key-policies"></a>

### DIRECT_KEY policies

The Adiantum encryption mode (see [Encryption modes and usage](<#rst-encryption-modes-and-usage>)) is suitable for both contents and filenames encryption, and it accepts long IVs --- long enough to hold both an 8-byte data unit index and a 16-byte per-file nonce.  Also, the overhead of each Adiantum key is greater than that of an AES-256-XTS key.

Therefore, to improve performance and save memory, for Adiantum a "direct key" configuration is supported.  When the user has enabled this by setting FSCRYPT_POLICY_FLAG_DIRECT_KEY in the fscrypt policy, per-file encryption keys are not used.  Instead, whenever any data (contents or filenames) is encrypted, the file's 16-byte nonce is included in the IV.  Moreover:

- For v1 encryption policies, the encryption is done directly with the master key.  Because of this, users **must not** use the same master key for any other purpose, even for other v1 policies.

- For v2 encryption policies, the encryption is done with a per-mode key derived using the KDF.  Users may use the same master key for other v2 encryption policies.

<a id="rst-iv-ino-lblk-64-policies"></a>

### IV_INO_LBLK_64 policies

When FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64 is set in the fscrypt policy, the encryption keys are derived from the master key, encryption mode number, and filesystem UUID.  This normally results in all files protected by the same master key sharing a single contents encryption key and a single filenames encryption key.  To still encrypt different files' data differently, inode numbers are included in the IVs. Consequently, shrinking the filesystem may not be allowed.

This format is optimized for use with inline encryption hardware compliant with the UFS standard, which supports only 64 IV bits per I/O request and may have only a small number of keyslots.

<a id="rst-iv-ino-lblk-32-policies"></a>

### IV_INO_LBLK_32 policies

IV_INO_LBLK_32 policies work like IV_INO_LBLK_64, except that for IV_INO_LBLK_32, the inode number is hashed with SipHash-2-4 (where the SipHash key is derived from the master key) and added to the file data unit index mod 2^32 to produce a 32-bit IV.

This format is optimized for use with inline encryption hardware compliant with the eMMC v5.2 standard, which supports only 32 IV bits per I/O request and may have only a small number of keyslots.  This format results in some level of IV reuse, so it should only be used when necessary due to hardware limitations.

<a id="rst-key-identifiers"></a>

### Key identifiers

For master keys used for v2 encryption policies, a unique 16-byte "key identifier" is also derived using the KDF.  This value is stored in the clear, since it is needed to reliably identify the key itself.

<a id="rst-dirhash-keys"></a>

### Dirhash keys

For directories that are indexed using a secret-keyed dirhash over the plaintext filenames, the KDF is also used to derive a 128-bit SipHash-2-4 key per directory in order to hash filenames.  This works just like deriving a per-file encryption key, except that a different KDF context is used.  Currently, only casefolded ("case-insensitive") encrypted directories use this style of hashing.

<a id="rst-encryption-modes-and-usage"></a>

## Encryption modes and usage

fscrypt allows one encryption mode to be specified for file contents and one encryption mode to be specified for filenames.  Different directory trees are permitted to use different encryption modes.

<a id="rst-supported-modes"></a>

### Supported modes

Currently, the following pairs of encryption modes are supported:

- AES-256-XTS for contents and AES-256-CBC-CTS for filenames

- AES-256-XTS for contents and AES-256-HCTR2 for filenames

- Adiantum for both contents and filenames

- AES-128-CBC-ESSIV for contents and AES-128-CBC-CTS for filenames

- SM4-XTS for contents and SM4-CBC-CTS for filenames

Note: in the API, "CBC" means CBC-ESSIV, and "CTS" means CBC-CTS. So, for example, FSCRYPT_MODE_AES_256_CTS means AES-256-CBC-CTS.

Authenticated encryption modes are not currently supported because of the difficulty of dealing with ciphertext expansion.  Therefore, contents encryption uses a block cipher in [XTS mode](<https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS>)<a id="rst-xts-mode"></a> or [CBC-ESSIV mode](<https://en.wikipedia.org/wiki/Disk_encryption_theory#Encrypted_salt-sector_initialization_vector_(ESSIV)>)<a id="rst-cbc-essiv-mode"></a>, or a wide-block cipher.  Filenames encryption uses a block cipher in [CBC-CTS mode](<https://en.wikipedia.org/wiki/Ciphertext_stealing>)<a id="rst-cbc-cts-mode"></a> or a wide-block cipher.

The (AES-256-XTS, AES-256-CBC-CTS) pair is the recommended default. It is also the only option that is *guaranteed* to always be supported if the kernel supports fscrypt at all; see [Kernel config options](<#rst-kernel-config-options>).

The (AES-256-XTS, AES-256-HCTR2) pair is also a good choice that upgrades the filenames encryption to use a wide-block cipher.  (A *wide-block cipher*, also called a tweakable super-pseudorandom permutation, has the property that changing one bit scrambles the entire result.)  As described in [Filenames encryption](<#rst-filenames-encryption>), a wide-block cipher is the ideal mode for the problem domain, though CBC-CTS is the "least bad" choice among the alternatives.  For more information about HCTR2, see [the HCTR2 paper](<https://eprint.iacr.org/2021/1441.pdf>)<a id="rst-the-hctr2-paper"></a>.

Adiantum is recommended on systems where AES is too slow due to lack of hardware acceleration for AES.  Adiantum is a wide-block cipher that uses XChaCha12 and AES-256 as its underlying components.  Most of the work is done by XChaCha12, which is much faster than AES when AES acceleration is unavailable.  For more information about Adiantum, see [the Adiantum paper](<https://eprint.iacr.org/2018/720.pdf>)<a id="rst-the-adiantum-paper"></a>.

The (AES-128-CBC-ESSIV, AES-128-CBC-CTS) pair was added to try to provide a more efficient option for systems that lack AES instructions in the CPU but do have a non-inline crypto engine such as CAAM or CESA that supports AES-CBC (and not AES-XTS).  This is deprecated.  It has been shown that just doing AES on the CPU is actually faster. Moreover, Adiantum is faster still and is recommended on such systems.

The remaining mode pairs are the "national pride ciphers":

- (SM4-XTS, SM4-CBC-CTS)

Generally speaking, these ciphers aren't "bad" per se, but they receive limited security review compared to the usual choices such as AES and ChaCha.  They also don't bring much new to the table.  It is suggested to only use these ciphers where their use is mandated.

<a id="rst-kernel-config-options"></a>

### Kernel config options

Enabling fscrypt support (CONFIG_FS_ENCRYPTION) automatically pulls in only the basic support from the crypto API needed to use AES-256-XTS and AES-256-CBC-CTS encryption.  For optimal performance, it is strongly recommended to also enable any available platform-specific kconfig options that provide acceleration for the algorithm(s) you wish to use.  Support for any "non-default" encryption modes typically requires extra kconfig options as well.

Below, some relevant options are listed by encryption mode.  Note, acceleration options not listed below may be available for your platform; refer to the kconfig menus.  File contents encryption can also be configured to use inline encryption hardware instead of the kernel crypto API (see [Inline encryption support](<#rst-inline-encryption-support>)); in that case, the file contents mode doesn't need to supported in the kernel crypto API, but the filenames mode still does.

- - **AES-256-XTS and AES-256-CBC-CTS**

    - - **Recommended:**

        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK

        - x86: CONFIG_CRYPTO_AES_NI_INTEL

- - **AES-256-HCTR2**

    - - **Mandatory:**

        - CONFIG_CRYPTO_HCTR2

    - - **Recommended:**

        - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK

        - x86: CONFIG_CRYPTO_AES_NI_INTEL

- - **Adiantum**

    - - **Mandatory:**

        - CONFIG_CRYPTO_ADIANTUM

- - **AES-128-CBC-ESSIV and AES-128-CBC-CTS:**

    - - **Mandatory:**

        - CONFIG_CRYPTO_ESSIV

        - CONFIG_CRYPTO_SHA256 or another SHA-256 implementation

    - - **Recommended:**

        - AES-CBC acceleration

<a id="rst-contents-encryption"></a>

### Contents encryption

For contents encryption, each file's contents is divided into "data units".  Each data unit is encrypted independently.  The IV for each data unit incorporates the zero-based index of the data unit within the file.  This ensures that each data unit within a file is encrypted differently, which is essential to prevent leaking information.

Note: the encryption depending on the offset into the file means that operations like "collapse range" and "insert range" that rearrange the extent mapping of files are not supported on encrypted files.

There are two cases for the sizes of the data units:

- Fixed-size data units.  This is how all filesystems other than UBIFS work.  A file's data units are all the same size; the last data unit is zero-padded if needed.  By default, the data unit size is equal to the filesystem block size.  On some filesystems, users can select a sub-block data unit size via the `log2_data_unit_size` field of the encryption policy; see [FS_IOC_SET_ENCRYPTION_POLICY](<#rst-fs-ioc-set-encryption-policy>).

- Variable-size data units.  This is what UBIFS does.  Each "UBIFS data node" is treated as a crypto data unit.  Each contains variable length, possibly compressed data, zero-padded to the next 16-byte boundary.  Users cannot select a sub-block data unit size on UBIFS.

In the case of compression + encryption, the compressed data is encrypted.  UBIFS compression works as described above.  f2fs compression works a bit differently; it compresses a number of filesystem blocks into a smaller number of filesystem blocks. Therefore a f2fs-compressed file still uses fixed-size data units, and it is encrypted in a similar way to a file containing holes.

As mentioned in [Key hierarchy](<#rst-key-hierarchy>), the default encryption setting uses per-file keys.  In this case, the IV for each data unit is simply the index of the data unit in the file.  However, users can select an encryption setting that does not use per-file keys.  For these, some kind of file identifier is incorporated into the IVs as follows:

- With [DIRECT_KEY policies](<#rst-direct-key-policies>), the data unit index is placed in bits 0-63 of the IV, and the file's nonce is placed in bits 64-191.

- With [IV_INO_LBLK_64 policies](<#rst-iv-ino-lblk-64-policies>), the data unit index is placed in bits 0-31 of the IV, and the file's inode number is placed in bits 32-63.  This setting is only allowed when data unit indices and inode numbers fit in 32 bits.

- With [IV_INO_LBLK_32 policies](<#rst-iv-ino-lblk-32-policies>), the file's inode number is hashed and added to the data unit index.  The resulting value is truncated to 32 bits and placed in bits 0-31 of the IV.  This setting is only allowed when data unit indices and inode numbers fit in 32 bits.

The byte order of the IV is always little endian.

If the user selects FSCRYPT_MODE_AES_128_CBC for the contents mode, an ESSIV layer is automatically included.  In this case, before the IV is passed to AES-128-CBC, it is encrypted with AES-256 where the AES-256 key is the SHA-256 hash of the file's contents encryption key.

<a id="rst-filenames-encryption"></a>

### Filenames encryption

For filenames, each full filename is encrypted at once.  Because of the requirements to retain support for efficient directory lookups and filenames of up to 255 bytes, the same IV is used for every filename in a directory.

However, each encrypted directory still uses a unique key, or alternatively has the file's nonce (for [DIRECT_KEY policies](<#rst-direct-key-policies>)) or inode number (for [IV_INO_LBLK_64 policies](<#rst-iv-ino-lblk-64-policies>)) included in the IVs. Thus, IV reuse is limited to within a single directory.

With CBC-CTS, the IV reuse means that when the plaintext filenames share a common prefix at least as long as the cipher block size (16 bytes for AES), the corresponding encrypted filenames will also share a common prefix.  This is undesirable.  Adiantum and HCTR2 do not have this weakness, as they are wide-block encryption modes.

All supported filenames encryption modes accept any plaintext length &gt;= 16 bytes; cipher block alignment is not required.  However, filenames shorter than 16 bytes are NUL-padded to 16 bytes before being encrypted.  In addition, to reduce leakage of filename lengths via their ciphertexts, all filenames are NUL-padded to the next 4, 8, 16, or 32-byte boundary (configurable).  32 is recommended since this provides the best confidentiality, at the cost of making directory entries consume slightly more space.  Note that since NUL (`\0`) is not otherwise a valid character in filenames, the padding will never produce duplicate plaintexts.

Symbolic link targets are considered a type of filename and are encrypted in the same way as filenames in directory entries, except that IV reuse is not a problem as each symlink has its own inode.

<a id="rst-user-api"></a>

## User API

<a id="rst-setting-an-encryption-policy"></a>

### Setting an encryption policy

<a id="rst-fs-ioc-set-encryption-policy"></a>

#### FS_IOC_SET_ENCRYPTION_POLICY

The FS_IOC_SET_ENCRYPTION_POLICY ioctl sets an encryption policy on an empty directory or verifies that a directory or regular file already has the specified encryption policy.  It takes in a pointer to struct fscrypt_policy_v1 or struct fscrypt_policy_v2, defined as follows:



```text
#define FSCRYPT_POLICY_V1               0
#define FSCRYPT_KEY_DESCRIPTOR_SIZE     8
struct fscrypt_policy_v1 {
        __u8 version;
        __u8 contents_encryption_mode;
        __u8 filenames_encryption_mode;
        __u8 flags;
        __u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
};
#define fscrypt_policy  fscrypt_policy_v1

#define FSCRYPT_POLICY_V2               2
#define FSCRYPT_KEY_IDENTIFIER_SIZE     16
struct fscrypt_policy_v2 {
        __u8 version;
        __u8 contents_encryption_mode;
        __u8 filenames_encryption_mode;
        __u8 flags;
        __u8 log2_data_unit_size;
        __u8 __reserved[3];
        __u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
};
```

This structure must be initialized as follows:

- `version` must be FSCRYPT_POLICY_V1 (0) if struct fscrypt_policy_v1 is used or FSCRYPT_POLICY_V2 (2) if struct fscrypt_policy_v2 is used. (Note: we refer to the original policy version as "v1", though its version code is really 0.) For new encrypted directories, use v2 policies.

- `contents_encryption_mode` and `filenames_encryption_mode` must be set to constants from `<linux/fscrypt.h>` which identify the encryption modes to use.  If unsure, use FSCRYPT_MODE_AES_256_XTS (1) for `contents_encryption_mode` and FSCRYPT_MODE_AES_256_CTS (4) for `filenames_encryption_mode`.  For details, see [Encryption modes and usage](<#rst-encryption-modes-and-usage>).

  v1 encryption policies only support three combinations of modes: (FSCRYPT_MODE_AES_256_XTS, FSCRYPT_MODE_AES_256_CTS), (FSCRYPT_MODE_AES_128_CBC, FSCRYPT_MODE_AES_128_CTS), and (FSCRYPT_MODE_ADIANTUM, FSCRYPT_MODE_ADIANTUM).  v2 policies support all combinations documented in [Supported modes](<#rst-supported-modes>).

- `flags` contains optional flags from `<linux/fscrypt.h>`:

  - FSCRYPT_POLICY_FLAGS_PAD\_\*: The amount of NUL padding to use when encrypting filenames.  If unsure, use FSCRYPT_POLICY_FLAGS_PAD_32 (0x3).

  - FSCRYPT_POLICY_FLAG_DIRECT_KEY: See [DIRECT_KEY policies](<#rst-direct-key-policies>).

  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_64: See [IV_INO_LBLK_64 policies](<#rst-iv-ino-lblk-64-policies>).

  - FSCRYPT_POLICY_FLAG_IV_INO_LBLK_32: See [IV_INO_LBLK_32 policies](<#rst-iv-ino-lblk-32-policies>).

  v1 encryption policies only support the PAD\_\* and DIRECT_KEY flags. The other flags are only supported by v2 encryption policies.

  The DIRECT_KEY, IV_INO_LBLK_64, and IV_INO_LBLK_32 flags are mutually exclusive.

- `log2_data_unit_size` is the log2 of the data unit size in bytes, or 0 to select the default data unit size.  The data unit size is the granularity of file contents encryption.  For example, setting `log2_data_unit_size` to 12 causes file contents be passed to the underlying encryption algorithm (such as AES-256-XTS) in 4096-byte data units, each with its own IV.

  Not all filesystems support setting `log2_data_unit_size`.  ext4 and f2fs support it since Linux v6.7.  On filesystems that support it, the supported nonzero values are 9 through the log2 of the filesystem block size, inclusively.  The default value of 0 selects the filesystem block size.

  The main use case for `log2_data_unit_size` is for selecting a data unit size smaller than the filesystem block size for compatibility with inline encryption hardware that only supports smaller data unit sizes.  `/sys/block/$disk/queue/crypto/` may be useful for checking which data unit sizes are supported by a particular system's inline encryption hardware.

  Leave this field zeroed unless you are certain you need it.  Using an unnecessarily small data unit size reduces performance.

- For v2 encryption policies, `__reserved` must be zeroed.

- For v1 encryption policies, `master_key_descriptor` specifies how to find the master key in a keyring; see [Adding keys](<#rst-adding-keys>).  It is up to userspace to choose a unique `master_key_descriptor` for each master key.  The e4crypt and fscrypt tools use the first 8 bytes of `SHA-512(SHA-512(master_key))`, but this particular scheme is not required.  Also, the master key need not be in the keyring yet when FS_IOC_SET_ENCRYPTION_POLICY is executed.  However, it must be added before any files can be created in the encrypted directory.

  For v2 encryption policies, `master_key_descriptor` has been replaced with `master_key_identifier`, which is longer and cannot be arbitrarily chosen.  Instead, the key must first be added using [FS_IOC_ADD_ENCRYPTION_KEY](<#rst-fs-ioc-add-encryption-key>).  Then, the `key_spec.u.identifier` the kernel returned in the struct fscrypt_add_key_arg must be used as the `master_key_identifier` in struct fscrypt_policy_v2.

If the file is not yet encrypted, then FS_IOC_SET_ENCRYPTION_POLICY verifies that the file is an empty directory.  If so, the specified encryption policy is assigned to the directory, turning it into an encrypted directory.  After that, and after providing the corresponding master key as described in [Adding keys](<#rst-adding-keys>), all regular files, directories (recursively), and symlinks created in the directory will be encrypted, inheriting the same encryption policy. The filenames in the directory's entries will be encrypted as well.

Alternatively, if the file is already encrypted, then FS_IOC_SET_ENCRYPTION_POLICY validates that the specified encryption policy exactly matches the actual one.  If they match, then the ioctl returns 0.  Otherwise, it fails with EEXIST.  This works on both regular files and directories, including nonempty directories.

The inherited v2 key-claim check accepts either a key added by the current user or `CAP_FOWNER`. Peios treats `CAP_FOWNER` as a compatibility pass, so this is not an independent guarantee that the caller supplied or owns the key; the check can also accept a policy whose key is not yet present. A matching key is still needed to access encrypted content. Native handle rights and the remaining filesystem policy checks apply independently.

Note that the ext4 filesystem does not allow the root directory to be encrypted, even if it is empty.  Users who want to encrypt an entire filesystem with one key should consider using dm-crypt instead.

FS_IOC_SET_ENCRYPTION_POLICY can fail with the following errors:

- `EACCES`: the file is not owned by the process's uid, nor does the process have the CAP_FOWNER capability in a namespace with the file owner's uid mapped

- `EEXIST`: the file is already encrypted with an encryption policy different from the one specified

- `EINVAL`: an invalid encryption policy was specified (invalid version, mode(s), or flags; or reserved bits were set); or a v1 encryption policy was specified but the directory has the casefold flag enabled (casefolding is incompatible with v1 policies).

- `ENOKEY`: a v2 encryption policy was specified, but the key with the specified `master_key_identifier` has not been added, nor does the process have the CAP_FOWNER capability in the initial user namespace

- `ENOTDIR`: the file is unencrypted and is a regular file, not a directory

- `ENOTEMPTY`: the file is unencrypted and is a nonempty directory

- `ENOTTY`: this type of filesystem does not implement encryption

- `EOPNOTSUPP`: the kernel was not configured with encryption support for filesystems, or the filesystem superblock has not had encryption enabled on it.  (For example, to use encryption on an ext4 filesystem, CONFIG_FS_ENCRYPTION must be enabled in the kernel config, and the superblock must have had the "encrypt" feature flag enabled using `tune2fs -O encrypt` or `mkfs.ext4 -O encrypt`.)

- `EPERM`: this directory may not be encrypted, e.g. because it is the root directory of an ext4 filesystem

- `EROFS`: the filesystem is readonly

<a id="rst-getting-an-encryption-policy"></a>

### Getting an encryption policy

Two ioctls are available to get a file's encryption policy:

- [FS_IOC_GET_ENCRYPTION_POLICY_EX](<#rst-fs-ioc-get-encryption-policy-ex>)

- [FS_IOC_GET_ENCRYPTION_POLICY](<#rst-fs-ioc-get-encryption-policy>)

The extended (\_EX) version of the ioctl is more general and is recommended to use when possible.  However, on older kernels only the original ioctl is available.  Applications should try the extended version, and if it fails with ENOTTY fall back to the original version.

<a id="rst-fs-ioc-get-encryption-policy-ex"></a>

#### FS_IOC_GET_ENCRYPTION_POLICY_EX

The FS_IOC_GET_ENCRYPTION_POLICY_EX ioctl retrieves the encryption policy, if any, for a directory or regular file.  On a managed Peios handle, KACS additionally requires `FILE_READ_ATTRIBUTES` for this ioctl; opening the file with an unrelated grant is not enough.  It takes in a pointer to struct fscrypt_get_policy_ex_arg, defined as follows:



```text
struct fscrypt_get_policy_ex_arg {
        __u64 policy_size; /* input/output */
        union {
                __u8 version;
                struct fscrypt_policy_v1 v1;
                struct fscrypt_policy_v2 v2;
        } policy; /* output */
};
```

The caller must initialize `policy_size` to the size available for the policy struct, i.e. `sizeof(arg.policy)`.

On success, the policy struct is returned in `policy`, and its actual size is returned in `policy_size`.  `policy.version` should be checked to determine the version of policy returned.  Note that the version code for the "v1" policy is actually 0 (FSCRYPT_POLICY_V1).

FS_IOC_GET_ENCRYPTION_POLICY_EX can fail with the following errors:

- `EINVAL`: the file is encrypted, but it uses an unrecognized encryption policy version

- `ENODATA`: the file is not encrypted

- `ENOTTY`: this type of filesystem does not implement encryption, or this kernel is too old to support FS_IOC_GET_ENCRYPTION_POLICY_EX (try FS_IOC_GET_ENCRYPTION_POLICY instead)

- `EOPNOTSUPP`: the kernel was not configured with encryption support for this filesystem, or the filesystem superblock has not had encryption enabled on it

- `EOVERFLOW`: the file is encrypted and uses a recognized encryption policy version, but the policy struct does not fit into the provided buffer

Note: if you only need to know whether a file is encrypted or not, on most filesystems it is also possible to use the FS_IOC_GETFLAGS ioctl and check for FS_ENCRYPT_FL, or to use the statx() system call and check for STATX_ATTR_ENCRYPTED in stx_attributes.

<a id="rst-fs-ioc-get-encryption-policy"></a>

#### FS_IOC_GET_ENCRYPTION_POLICY

The FS_IOC_GET_ENCRYPTION_POLICY ioctl can also retrieve the encryption policy, if any, for a directory or regular file.  However, unlike [FS_IOC_GET_ENCRYPTION_POLICY_EX](<#rst-fs-ioc-get-encryption-policy-ex>), FS_IOC_GET_ENCRYPTION_POLICY only supports the original policy version.  It takes in a pointer directly to struct fscrypt_policy_v1 rather than struct fscrypt_get_policy_ex_arg.

The error codes for FS_IOC_GET_ENCRYPTION_POLICY are the same as those for FS_IOC_GET_ENCRYPTION_POLICY_EX, except that FS_IOC_GET_ENCRYPTION_POLICY also returns `EINVAL` if the file is encrypted using a newer encryption policy version.

<a id="rst-getting-the-per-filesystem-salt"></a>

### Getting the per-filesystem salt

Some filesystems, such as ext4 and F2FS, also support the deprecated ioctl FS_IOC_GET_ENCRYPTION_PWSALT.  This ioctl retrieves a randomly generated 16-byte value stored in the filesystem superblock.  This value is intended to used as a salt when deriving an encryption key from a passphrase or other low-entropy user credential.

FS_IOC_GET_ENCRYPTION_PWSALT is deprecated.  Instead, prefer to generate and manage any needed salt(s) in userspace.

<a id="rst-getting-a-file-s-encryption-nonce"></a>

### Getting a file's encryption nonce

Since Linux v5.7, the ioctl FS_IOC_GET_ENCRYPTION_NONCE is supported. On encrypted files and directories it gets the inode's 16-byte nonce. On unencrypted files and directories, it fails with ENODATA.

This ioctl can be useful for automated tests which verify that the encryption is being done correctly.  It is not needed for normal use of fscrypt.

Native ioctl authorization applies before the filesystem handles these requests.
On managed Peios handles, encryption-policy/key-status queries require
`FILE_READ_ATTRIBUTES`; setting a policy or adding/removing a key requires
`FILE_WRITE_ATTRIBUTES`. The v1 key operations and remove-all-users operation
also retain `CAP_SYS_ADMIN`, mapped to enabled `SeTcbPrivilege`. Supplying a
key makes decryption possible but does not grant file access. UID-based key
claims and keyring quotas remain inherited bookkeeping, not native SD grants.

<a id="rst-adding-keys"></a>

### Adding keys

<a id="rst-fs-ioc-add-encryption-key"></a>

#### FS_IOC_ADD_ENCRYPTION_KEY

The FS_IOC_ADD_ENCRYPTION_KEY ioctl adds a master encryption key to the filesystem, making all files on the filesystem which were encrypted using that key appear "unlocked", i.e. in plaintext form. It can be executed on any file or directory on the target filesystem, but using the filesystem's root directory is recommended.  It takes in a pointer to struct fscrypt_add_key_arg, defined as follows:



```text
struct fscrypt_add_key_arg {
        struct fscrypt_key_specifier key_spec;
        __u32 raw_size;
        __u32 key_id;
#define FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED 0x00000001
        __u32 flags;
        __u32 __reserved[7];
        __u8 raw[];
};

#define FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR        1
#define FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER        2

struct fscrypt_key_specifier {
        __u32 type;     /* one of FSCRYPT_KEY_SPEC_TYPE_* */
        __u32 __reserved;
        union {
                __u8 __reserved[32]; /* reserve some extra space */
                __u8 descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
                __u8 identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
        } u;
};

struct fscrypt_provisioning_key_payload {
        __u32 type;
        __u32 flags;
        __u8 raw[];
};
```

struct fscrypt_add_key_arg must be zeroed, then initialized as follows:

- If the key is being added for use by v1 encryption policies, then `key_spec.type` must contain FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR, and `key_spec.u.descriptor` must contain the descriptor of the key being added, corresponding to the value in the `master_key_descriptor` field of struct fscrypt_policy_v1. To add this type of key, the calling process must have the CAP_SYS_ADMIN capability in the initial user namespace.

  Alternatively, if the key is being added for use by v2 encryption policies, then `key_spec.type` must contain FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER, and `key_spec.u.identifier` is an *output* field which the kernel fills in with a cryptographic hash of the key.  This v2 add operation has no additional fscrypt capability requirement, but Peios still requires the native handle rights described above.  However, the number of keys that can be added is limited by the user's quota for the keyrings service (see `Documentation/security/keys/core.rst`).

- `raw_size` must be the size of the `raw` key provided, in bytes. Alternatively, if `key_id` is nonzero, this field must be 0, since in that case the size is implied by the specified Linux keyring key.

- `key_id` is 0 if the key is given directly in the `raw` field. Otherwise `key_id` is the ID of a Linux keyring key of type "fscrypt-provisioning" whose payload is struct fscrypt_provisioning_key_payload whose `raw` field contains the key, whose `type` field matches `key_spec.type`, and whose `flags` field matches `flags`.  Since `raw` is variable-length, the total size of this key's payload must be `sizeof(struct fscrypt_provisioning_key_payload)` plus the number of key bytes.  The process must have Search permission on this key.

  Most users should leave this 0 and specify the key directly.  The support for specifying a Linux keyring key is intended mainly to allow re-adding keys after a filesystem is unmounted and re-mounted, without having to store the keys in userspace memory.

- `flags` contains optional flags from `<linux/fscrypt.h>`:

  - FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED: This denotes that the key is a hardware-wrapped key.  See [Hardware-wrapped keys](<#rst-hardware-wrapped-keys>).  This flag can't be used if FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR is used.

- `raw` is a variable-length field which must contain the actual key, `raw_size` bytes long.  Alternatively, if `key_id` is nonzero, then this field is unused.  Note that despite being named `raw`, if FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED is specified then it will contain a wrapped key, not a raw key.

For v2 policy keys, the kernel keeps track of which user (identified by effective user ID) added the key, and only allows the key to be removed by that user --- or by "root", if they use [FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS](<#rst-fs-ioc-remove-encryption-key-all-users>).

However, if another user has added the key, it may be desirable to prevent that other user from unexpectedly removing it.  Therefore, FS_IOC_ADD_ENCRYPTION_KEY may also be used to add a v2 policy key *again*, even if it's already added by other user(s).  In this case, FS_IOC_ADD_ENCRYPTION_KEY will just install a claim to the key for the current user, rather than actually add the key again (but the key must still be provided, as a proof of knowledge).

FS_IOC_ADD_ENCRYPTION_KEY returns 0 if either the key or a claim to the key was either added or already exists.

FS_IOC_ADD_ENCRYPTION_KEY can fail with the following errors:

- `EACCES`: FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR was specified, but the caller does not have the CAP_SYS_ADMIN capability in the initial user namespace; or the key was specified by Linux key ID but the process lacks Search permission on the key.

- `EBADMSG`: invalid hardware-wrapped key

- `EDQUOT`: the key quota for this user would be exceeded by adding the key

- `EINVAL`: invalid key size or key specifier type, or reserved bits were set

- `EKEYREJECTED`: the key was specified by Linux key ID, but the key has the wrong type

- `ENOKEY`: the key was specified by Linux key ID, but no key exists with that ID

- `ENOTTY`: this type of filesystem does not implement encryption

- `EOPNOTSUPP`: the kernel was not configured with encryption support for this filesystem, or the filesystem superblock has not had encryption enabled on it; or a hardware wrapped key was specified but the filesystem does not support inline encryption or the hardware does not support hardware-wrapped keys

<a id="rst-legacy-method"></a>

#### Legacy method

For v1 encryption policies, a master encryption key can also be provided by adding it to a process-subscribed keyring, e.g. to a session keyring, or to a user keyring if the user keyring is linked into the session keyring.

This method is deprecated (and not supported for v2 encryption policies) for several reasons.  First, it cannot be used in combination with FS_IOC_REMOVE_ENCRYPTION_KEY (see [Removing keys](<#rst-removing-keys>)), so for removing a key a workaround such as keyctl_unlink() in combination with `sync; echo 2 > /proc/sys/vm/drop_caches` would have to be used.  Second, it doesn't match the fact that the locked/unlocked status of encrypted files (i.e. whether they appear to be in plaintext form or in ciphertext form) is global.  This mismatch has caused much confusion as well as real problems when processes running under different UIDs, such as a `sudo` command, need to access encrypted files.

Nevertheless, to add a key to one of the process-subscribed keyrings, the add_key() system call can be used (see: `Documentation/security/keys/core.rst`).  The key type must be "logon"; keys of this type are kept in kernel memory and cannot be read back by userspace.  The key description must be "fscrypt:" followed by the 16-character lower case hex representation of the `master_key_descriptor` that was set in the encryption policy.  The key payload must conform to the following structure:



```text
#define FSCRYPT_MAX_KEY_SIZE            64

struct fscrypt_key {
        __u32 mode;
        __u8 raw[FSCRYPT_MAX_KEY_SIZE];
        __u32 size;
};
```

`mode` is ignored; just set it to 0.  The actual key is provided in `raw` with `size` indicating its size in bytes.  That is, the bytes `raw[0..size-1]` (inclusive) are the actual key.

The key description prefix "fscrypt:" may alternatively be replaced with a filesystem-specific prefix such as "ext4:".  However, the filesystem-specific prefixes are deprecated and should not be used in new programs.

<a id="rst-removing-keys"></a>

### Removing keys

Two ioctls are available for removing a key that was added by [FS_IOC_ADD_ENCRYPTION_KEY](<#rst-fs-ioc-add-encryption-key>):

- [FS_IOC_REMOVE_ENCRYPTION_KEY](<#rst-fs-ioc-remove-encryption-key>)

- [FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS](<#rst-fs-ioc-remove-encryption-key-all-users>)

For v2 policy keys, the ordinary removal ioctl releases the current UID's claim; the all-users variant removes all claims and additionally requires `CAP_SYS_ADMIN` (enabled `SeTcbPrivilege` in Peios). Native handle checks apply to both.

These ioctls don't work on keys that were added via the legacy process-subscribed keyrings mechanism.

Before using these ioctls, read the [Online attacks](<#rst-online-attacks>) section for a discussion of the security goals and limitations of these ioctls.

<a id="rst-fs-ioc-remove-encryption-key"></a>

#### FS_IOC_REMOVE_ENCRYPTION_KEY

The FS_IOC_REMOVE_ENCRYPTION_KEY ioctl removes a claim to a master encryption key from the filesystem, and possibly removes the key itself.  It can be executed on any file or directory on the target filesystem, but using the filesystem's root directory is recommended. It takes in a pointer to struct fscrypt_remove_key_arg, defined as follows:



```text
struct fscrypt_remove_key_arg {
        struct fscrypt_key_specifier key_spec;
#define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY      0x00000001
#define FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS     0x00000002
        __u32 removal_status_flags;     /* output */
        __u32 __reserved[5];
};
```

This structure must be zeroed, then initialized as follows:

- The key to remove is specified by `key_spec`:

  > - To remove a key used by v1 encryption policies, set `key_spec.type` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill in `key_spec.u.descriptor`.  To remove this type of key, the calling process must have the CAP_SYS_ADMIN capability in the initial user namespace.
  >
  > - To remove a key used by v2 encryption policies, set `key_spec.type` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill in `key_spec.u.identifier`.

For v2 policy keys, this ioctl is usable by non-root users.  However, to make this possible, it actually just removes the current user's claim to the key, undoing a single call to FS_IOC_ADD_ENCRYPTION_KEY. Only after all claims are removed is the key really removed.

For example, if FS_IOC_ADD_ENCRYPTION_KEY was called with uid 1000, then the key will be "claimed" by uid 1000, and FS_IOC_REMOVE_ENCRYPTION_KEY will only succeed as uid 1000.  Or, if both uids 1000 and 2000 added the key, then for each uid FS_IOC_REMOVE_ENCRYPTION_KEY will only remove their own claim.  Only once *both* are removed is the key really removed.  (Think of it like unlinking a file that may have hard links.)

If FS_IOC_REMOVE_ENCRYPTION_KEY really removes the key, it will also try to "lock" all files that had been unlocked with the key.  It won't lock files that are still in-use, so this ioctl is expected to be used in cooperation with userspace ensuring that none of the files are still open.  However, if necessary, this ioctl can be executed again later to retry locking any remaining files.

FS_IOC_REMOVE_ENCRYPTION_KEY returns 0 if either the key was removed (but may still have files remaining to be locked), the user's claim to the key was removed, or the key was already removed but had files remaining to be the locked so the ioctl retried locking them.  In any of these cases, `removal_status_flags` is filled in with the following informational status flags:

- `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY`: set if some file(s) are still in-use.  Not guaranteed to be set in the case where only the user's claim to the key was removed.

- `FSCRYPT_KEY_REMOVAL_STATUS_FLAG_OTHER_USERS`: set if only the user's claim to the key was removed, not the key itself

FS_IOC_REMOVE_ENCRYPTION_KEY can fail with the following errors:

- `EACCES`: The FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR key specifier type was specified, but the caller does not have the CAP_SYS_ADMIN capability in the initial user namespace

- `EINVAL`: invalid key specifier type, or reserved bits were set

- `ENOKEY`: the key object was not found at all, i.e. it was never added in the first place or was already fully removed including all files locked; or, the user does not have a claim to the key (but someone else does).

- `ENOTTY`: this type of filesystem does not implement encryption

- `EOPNOTSUPP`: the kernel was not configured with encryption support for this filesystem, or the filesystem superblock has not had encryption enabled on it

<a id="rst-fs-ioc-remove-encryption-key-all-users"></a>

#### FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS

FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS is exactly the same as [FS_IOC_REMOVE_ENCRYPTION_KEY](<#rst-fs-ioc-remove-encryption-key>), except that for v2 policy keys, the ALL_USERS version of the ioctl will remove all users' claims to the key, not just the current user's.  I.e., the key itself will always be removed, no matter how many users have added it.  This difference is only meaningful if non-root users are adding and removing keys.

Because of this, FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS also requires "root", namely the CAP_SYS_ADMIN capability in the initial user namespace.  Otherwise it will fail with EACCES.

<a id="rst-getting-key-status"></a>

### Getting key status

<a id="rst-fs-ioc-get-encryption-key-status"></a>

#### FS_IOC_GET_ENCRYPTION_KEY_STATUS

The FS_IOC_GET_ENCRYPTION_KEY_STATUS ioctl retrieves the status of a master encryption key.  It can be executed on any file or directory on the target filesystem, but using the filesystem's root directory is recommended.  It takes in a pointer to struct fscrypt_get_key_status_arg, defined as follows:



```text
struct fscrypt_get_key_status_arg {
        /* input */
        struct fscrypt_key_specifier key_spec;
        __u32 __reserved[6];

        /* output */
#define FSCRYPT_KEY_STATUS_ABSENT               1
#define FSCRYPT_KEY_STATUS_PRESENT              2
#define FSCRYPT_KEY_STATUS_INCOMPLETELY_REMOVED 3
        __u32 status;
#define FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF   0x00000001
        __u32 status_flags;
        __u32 user_count;
        __u32 __out_reserved[13];
};
```

The caller must zero all input fields, then fill in `key_spec`:

> - To get the status of a key for v1 encryption policies, set `key_spec.type` to FSCRYPT_KEY_SPEC_TYPE_DESCRIPTOR and fill in `key_spec.u.descriptor`.
>
> - To get the status of a key for v2 encryption policies, set `key_spec.type` to FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER and fill in `key_spec.u.identifier`.

On success, 0 is returned and the kernel fills in the output fields:

- `status` indicates whether the key is absent, present, or incompletely removed.  Incompletely removed means that removal has been initiated, but some files are still in use; i.e., [FS_IOC_REMOVE_ENCRYPTION_KEY](<#rst-fs-ioc-remove-encryption-key>) returned 0 but set the informational status flag FSCRYPT_KEY_REMOVAL_STATUS_FLAG_FILES_BUSY.

- `status_flags` can contain the following flags:

  > - `FSCRYPT_KEY_STATUS_FLAG_ADDED_BY_SELF` indicates that the key has added by the current user.  This is only set for keys identified by `identifier` rather than by `descriptor`.

- `user_count` specifies the number of users who have added the key. This is only set for keys identified by `identifier` rather than by `descriptor`.

FS_IOC_GET_ENCRYPTION_KEY_STATUS can fail with the following errors:

- `EINVAL`: invalid key specifier type, or reserved bits were set

- `ENOTTY`: this type of filesystem does not implement encryption

- `EOPNOTSUPP`: the kernel was not configured with encryption support for this filesystem, or the filesystem superblock has not had encryption enabled on it

Among other use cases, FS_IOC_GET_ENCRYPTION_KEY_STATUS can be useful for determining whether the key for a given encrypted directory needs to be added before prompting the user for the passphrase needed to derive the key.

FS_IOC_GET_ENCRYPTION_KEY_STATUS can only get the status of keys in the filesystem-level keyring, i.e. the keyring managed by [FS_IOC_ADD_ENCRYPTION_KEY](<#rst-fs-ioc-add-encryption-key>) and [FS_IOC_REMOVE_ENCRYPTION_KEY](<#rst-fs-ioc-remove-encryption-key>).  It cannot get the status of a key that has only been added for use by v1 encryption policies using the legacy mechanism involving process-subscribed keyrings.

<a id="rst-access-semantics"></a>

## Access semantics

<a id="rst-with-the-key"></a>

### With the key

With the encryption key, encrypted regular files, directories, and symlinks behave very similarly to their unencrypted counterparts --- after all, the encryption is intended to be transparent.  However, astute users may notice some differences in behavior:

- Unencrypted files, or files encrypted with a different encryption policy (i.e. different key, modes, or flags), cannot be renamed or linked into an encrypted directory; see [Encryption policy enforcement](<#rst-encryption-policy-enforcement>).  Attempts to do so will fail with EXDEV.  However, encrypted files can be renamed within an encrypted directory, or into an unencrypted directory.

  Note: "moving" an unencrypted file into an encrypted directory, e.g. with the `mv` program, is implemented in userspace by a copy followed by a delete.  Be aware that the original unencrypted data may remain recoverable from free space on the disk; prefer to keep all files encrypted from the very beginning.  The `shred` program may be used to overwrite the source files but isn't guaranteed to be effective on all filesystems and storage devices.

- Direct I/O is supported on encrypted files only under some circumstances.  For details, see [Direct I/O support](<#rst-direct-i-o-support>).

- The fallocate operations FALLOC_FL_COLLAPSE_RANGE and FALLOC_FL_INSERT_RANGE are not supported on encrypted files and will fail with EOPNOTSUPP.

- Online defragmentation of encrypted files is not supported.  The EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE ioctls will fail with EOPNOTSUPP.

- The ext4 filesystem does not support data journaling with encrypted regular files.  It will fall back to ordered data mode instead.

- DAX (Direct Access) is not supported on encrypted files.

- The maximum length of an encrypted symlink is 2 bytes shorter than the maximum length of an unencrypted symlink.  For example, on an EXT4 filesystem with a 4K block size, unencrypted symlinks can be up to 4095 bytes long, while encrypted symlinks can only be up to 4093 bytes long (both lengths excluding the terminating null).

Note that mmap *is* supported.  This is possible because the pagecache for an encrypted file contains the plaintext, not the ciphertext.

<a id="rst-without-the-key"></a>

### Without the key

Some filesystem operations may be performed on encrypted regular files, directories, and symlinks even before their encryption key has been added, or after their encryption key has been removed:

- File metadata may be read, e.g. using stat().

- Directories may be listed, in which case the filenames will be listed in an encoded form derived from their ciphertext.  The current encoding algorithm is described in [Filename hashing and encoding](<#rst-filename-hashing-and-encoding>).  The algorithm is subject to change, but it is guaranteed that the presented filenames will be no longer than NAME_MAX bytes, will not contain the `/` or `\0` characters, and will uniquely identify directory entries.

  The `.` and `..` directory entries are special.  They are always present and are not encrypted or encoded.

- Files may be deleted.  That is, nondirectory files may be deleted with unlink() as usual, and empty directories may be deleted with rmdir() as usual.  Therefore, `rm` and `rm -r` will work as expected.

- Symlink targets may be read and followed, but they will be presented in encrypted form, similar to filenames in directories.  Hence, they are unlikely to point to anywhere useful.

Without the key, regular files cannot be opened or truncated. Attempts to do so will fail with ENOKEY.  This implies that any regular file operations that require a file descriptor, such as read(), write(), mmap(), fallocate(), and ioctl(), are also forbidden.

Also without the key, files of any type (including directories) cannot be created or linked into an encrypted directory, nor can a name in an encrypted directory be the source or target of a rename, nor can an O_TMPFILE temporary file be created in an encrypted directory.  All such operations will fail with ENOKEY.

It is not currently possible to backup and restore encrypted files without the encryption key.  This would require special APIs which have not yet been implemented.

<a id="rst-encryption-policy-enforcement"></a>

## Encryption policy enforcement

After an encryption policy has been set on a directory, all regular files, directories, and symbolic links created in that directory (recursively) will inherit that encryption policy.  Special files --- that is, named pipes, device nodes, and UNIX domain sockets --- will not be encrypted.

Except for those special files, it is forbidden to have unencrypted files, or files encrypted with a different encryption policy, in an encrypted directory tree.  Attempts to link or rename such a file into an encrypted directory will fail with EXDEV.  This is also enforced during -&gt;lookup() to provide limited protection against offline attacks that try to disable or downgrade encryption in known locations where applications may later write sensitive data.  It is recommended that systems implementing a form of "verified boot" take advantage of this by validating all top-level encryption policies prior to access.

<a id="rst-inline-encryption-support"></a>

## Inline encryption support

Many newer systems (especially mobile SoCs) have *inline encryption hardware* that can encrypt/decrypt data while it is on its way to/from the storage device.  Linux supports inline encryption through a set of extensions to the block layer called *blk-crypto*.  blk-crypto allows filesystems to attach encryption contexts to bios (I/O requests) to specify how the data will be encrypted or decrypted in-line.  For more information about blk-crypto, see [Documentation/block/inline-encryption.rst](</kernel/internals/block/inline-encryption.md#rst-inline-encryption>).

On supported filesystems (currently ext4 and f2fs), fscrypt can use blk-crypto instead of the kernel crypto API to encrypt/decrypt file contents.  To enable this, set CONFIG_FS_ENCRYPTION_INLINE_CRYPT=y in the kernel configuration, and specify the "inlinecrypt" mount option when mounting the filesystem.

Note that the "inlinecrypt" mount option just specifies to use inline encryption when possible; it doesn't force its use.  fscrypt will still fall back to using the kernel crypto API on files where the inline encryption hardware doesn't have the needed crypto capabilities (e.g. support for the needed encryption algorithm and data unit size) and where blk-crypto-fallback is unusable.  (For blk-crypto-fallback to be usable, it must be enabled in the kernel configuration with CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK=y, and the file must be protected by a raw key rather than a hardware-wrapped key.)

Currently fscrypt always uses the filesystem block size (which is usually 4096 bytes) as the data unit size.  Therefore, it can only use inline encryption hardware that supports that data unit size.

Inline encryption doesn't affect the ciphertext or other aspects of the on-disk format, so users may freely switch back and forth between using "inlinecrypt" and not using "inlinecrypt".  An exception is that files that are protected by a hardware-wrapped key can only be encrypted/decrypted by the inline encryption hardware and therefore can only be accessed when the "inlinecrypt" mount option is used.  For more information about hardware-wrapped keys, see below.

<a id="rst-hardware-wrapped-keys"></a>

### Hardware-wrapped keys

fscrypt supports using *hardware-wrapped keys* when the inline encryption hardware supports it.  Such keys are only present in kernel memory in wrapped (encrypted) form; they can only be unwrapped (decrypted) by the inline encryption hardware and are temporally bound to the current boot.  This prevents the keys from being compromised if kernel memory is leaked.  This is done without limiting the number of keys that can be used and while still allowing the execution of cryptographic tasks that are tied to the same key but can't use inline encryption hardware, e.g. filenames encryption.

Note that hardware-wrapped keys aren't specific to fscrypt; they are a block layer feature (part of *blk-crypto*).  For more details about hardware-wrapped keys, see the block layer documentation at [Documentation/block/inline-encryption.rst](</kernel/internals/block/inline-encryption.md#rst-hardware-wrapped-keys>).  The rest of this section just focuses on the details of how fscrypt can use hardware-wrapped keys.

fscrypt supports hardware-wrapped keys by allowing the fscrypt master keys to be hardware-wrapped keys as an alternative to raw keys.  To add a hardware-wrapped key with [FS_IOC_ADD_ENCRYPTION_KEY](<#rst-fs-ioc-add-encryption-key>), userspace must specify FSCRYPT_ADD_KEY_FLAG_HW_WRAPPED in the `flags` field of struct fscrypt_add_key_arg and also in the `flags` field of struct fscrypt_provisioning_key_payload when applicable.  The key must be in ephemerally-wrapped form, not long-term wrapped form.

Some limitations apply.  First, files protected by a hardware-wrapped key are tied to the system's inline encryption hardware.  Therefore they can only be accessed when the "inlinecrypt" mount option is used, and they can't be included in portable filesystem images.  Second, currently the hardware-wrapped key support is only compatible with [IV_INO_LBLK_64 policies](<#rst-iv-ino-lblk-64-policies>) and [IV_INO_LBLK_32 policies](<#rst-iv-ino-lblk-32-policies>), as it assumes that there is just one file contents encryption key per fscrypt master key rather than one per file.  Future work may address this limitation by passing per-file nonces down the storage stack to allow the hardware to derive per-file keys.

Implementation-wise, to encrypt/decrypt the contents of files that are protected by a hardware-wrapped key, fscrypt uses blk-crypto, attaching the hardware-wrapped key to the bio crypt contexts.  As is the case with raw keys, the block layer will program the key into a keyslot when it isn't already in one.  However, when programming a hardware-wrapped key, the hardware doesn't program the given key directly into a keyslot but rather unwraps it (using the hardware's ephemeral wrapping key) and derives the inline encryption key from it. The inline encryption key is the key that actually gets programmed into a keyslot, and it is never exposed to software.

However, fscrypt doesn't just do file contents encryption; it also uses its master keys to derive filenames encryption keys, key identifiers, and sometimes some more obscure types of subkeys such as dirhash keys.  So even with file contents encryption out of the picture, fscrypt still needs a raw key to work with.  To get such a key from a hardware-wrapped key, fscrypt asks the inline encryption hardware to derive a cryptographically isolated "software secret" from the hardware-wrapped key.  fscrypt uses this "software secret" to key its KDF to derive all subkeys other than file contents keys.

Note that this implies that the hardware-wrapped key feature only protects the file contents encryption keys.  It doesn't protect other fscrypt subkeys such as filenames encryption keys.

<a id="rst-direct-i-o-support"></a>

## Direct I/O support

For direct I/O on an encrypted file to work, the following conditions must be met (in addition to the conditions for direct I/O on an unencrypted file):

- The file must be using inline encryption.  Usually this means that the filesystem must be mounted with `-o inlinecrypt` and inline encryption hardware must be present.  However, a software fallback is also available.  For details, see [Inline encryption support](<#rst-inline-encryption-support>).

- The I/O request must be fully aligned to the filesystem block size. This means that the file position the I/O is targeting, the lengths of all I/O segments, and the memory addresses of all I/O buffers must be multiples of this value.  Note that the filesystem block size may be greater than the logical block size of the block device.

If either of the above conditions is not met, then direct I/O on the encrypted file will fall back to buffered I/O.

<a id="rst-implementation-details"></a>

## Implementation details

<a id="rst-encryption-context"></a>

### Encryption context

An encryption policy is represented on-disk by struct fscrypt_context_v1 or struct fscrypt_context_v2.  It is up to individual filesystems to decide where to store it, but normally it would be stored in a hidden extended attribute.  It should *not* be exposed by the xattr-related system calls such as getxattr() and setxattr() because of the special semantics of the encryption xattr. (In particular, there would be much confusion if an encryption policy were to be added to or removed from anything other than an empty directory.)  These structs are defined as follows:



```text
#define FSCRYPT_FILE_NONCE_SIZE 16

#define FSCRYPT_KEY_DESCRIPTOR_SIZE  8
struct fscrypt_context_v1 {
        u8 version;
        u8 contents_encryption_mode;
        u8 filenames_encryption_mode;
        u8 flags;
        u8 master_key_descriptor[FSCRYPT_KEY_DESCRIPTOR_SIZE];
        u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
};

#define FSCRYPT_KEY_IDENTIFIER_SIZE  16
struct fscrypt_context_v2 {
        u8 version;
        u8 contents_encryption_mode;
        u8 filenames_encryption_mode;
        u8 flags;
        u8 log2_data_unit_size;
        u8 __reserved[3];
        u8 master_key_identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
        u8 nonce[FSCRYPT_FILE_NONCE_SIZE];
};
```

The context structs contain the same information as the corresponding policy structs (see [Setting an encryption policy](<#rst-setting-an-encryption-policy>)), except that the context structs also contain a nonce.  The nonce is randomly generated by the kernel and is used as KDF input or as a tweak to cause different files to be encrypted differently; see [Per-file encryption keys](<#rst-per-file-encryption-keys>) and [DIRECT_KEY policies](<#rst-direct-key-policies>).

<a id="rst-data-path-changes"></a>

### Data path changes

When inline encryption is used, filesystems just need to associate encryption contexts with bios to specify how the block layer or the inline encryption hardware will encrypt/decrypt the file contents.

When inline encryption isn't used, filesystems must encrypt/decrypt the file contents themselves, as described below:

For the read path (-&gt;read_folio()) of regular files, filesystems can read the ciphertext into the page cache and decrypt it in-place.  The folio lock must be held until decryption has finished, to prevent the folio from becoming visible to userspace prematurely.

For the write path (-&gt;writepages()) of regular files, filesystems cannot encrypt data in-place in the page cache, since the cached plaintext must be preserved.  Instead, filesystems must encrypt into a temporary buffer or "bounce page", then write out the temporary buffer.  Some filesystems, such as UBIFS, already use temporary buffers regardless of encryption.  Other filesystems, such as ext4 and F2FS, have to allocate bounce pages specially for encryption.

<a id="rst-filename-hashing-and-encoding"></a>

### Filename hashing and encoding

Modern filesystems accelerate directory lookups by using indexed directories.  An indexed directory is organized as a tree keyed by filename hashes.  When a -&gt;lookup() is requested, the filesystem normally hashes the filename being looked up so that it can quickly find the corresponding directory entry, if any.

With encryption, lookups must be supported and efficient both with and without the encryption key.  Clearly, it would not work to hash the plaintext filenames, since the plaintext filenames are unavailable without the key.  (Hashing the plaintext filenames would also make it impossible for the filesystem's fsck tool to optimize encrypted directories.)  Instead, filesystems hash the ciphertext filenames, i.e. the bytes actually stored on-disk in the directory entries.  When asked to do a -&gt;lookup() with the key, the filesystem just encrypts the user-supplied name to get the ciphertext.

Lookups without the key are more complicated.  The raw ciphertext may contain the `\0` and `/` characters, which are illegal in filenames.  Therefore, readdir() must base64url-encode the ciphertext for presentation.  For most filenames, this works fine; on -&gt;lookup(), the filesystem just base64url-decodes the user-supplied name to get back to the raw ciphertext.

However, for very long filenames, base64url encoding would cause the filename length to exceed NAME_MAX.  To prevent this, readdir() actually presents long filenames in an abbreviated form which encodes a strong "hash" of the ciphertext filename, along with the optional filesystem-specific hash(es) needed for directory lookups.  This allows the filesystem to still, with a high degree of confidence, map the filename given in -&gt;lookup() back to a particular directory entry that was previously listed by readdir().  See struct fscrypt_nokey_name in the source for more details.

Note that the precise way that filenames are presented to userspace without the key is subject to change in the future.  It is only meant as a way to temporarily present valid filenames so that commands like `rm -r` work as expected on encrypted directories.

<a id="rst-tests"></a>

## Tests

To test fscrypt, use xfstests, which is Linux's de facto standard filesystem test suite.  First, run all the tests in the "encrypt" group on the relevant filesystem(s).  One can also run the tests with the 'inlinecrypt' mount option to test the implementation for inline encryption support.  For example, to test ext4 and f2fs encryption using [kvm-xfstests](<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>)<a id="rst-kvm-xfstests"></a>:



```text
kvm-xfstests -c ext4,f2fs -g encrypt
kvm-xfstests -c ext4,f2fs -g encrypt -m inlinecrypt
```

UBIFS encryption can also be tested this way, but it should be done in a separate command, and it takes some time for kvm-xfstests to set up emulated UBI volumes:



```text
kvm-xfstests -c ubifs -g encrypt
```

No tests should fail.  However, tests that use non-default encryption modes (e.g. generic/549 and generic/550) will be skipped if the needed algorithms were not built into the kernel's crypto API.  Also, tests that access the raw block device (e.g. generic/399, generic/548, generic/549, generic/550) will be skipped on UBIFS.

Besides running the "encrypt" group tests, for ext4 and f2fs it's also possible to run most xfstests with the "test_dummy_encryption" mount option.  This option causes all new files to be automatically encrypted with a dummy key, without having to make any API calls. This tests the encrypted I/O paths more thoroughly.  To do this with kvm-xfstests, use the "encrypt" filesystem configuration:



```text
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
kvm-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
```

Because this runs many more tests than "-g encrypt" does, it takes much longer to run; so also consider using [gce-xfstests](<https://github.com/tytso/xfstests-bld/blob/master/Documentation/gce-xfstests.md>)<a id="rst-gce-xfstests"></a> instead of kvm-xfstests:



```text
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto
gce-xfstests -c ext4/encrypt,f2fs/encrypt -g auto -m inlinecrypt
```

---

# fs-verity: read-only file-based authenticity protection

_Peios Kernel / Internals / Filesystems_

> fs-verity (fs/verity/) is a support layer that filesystems can hook into to support transparent integrity and authenticity protection of read-only files. Currently, it is supported by the ext4, f2fs, and btrfs filesystems. Like fscrypt,…

<a id="rst-fs-verity-read-only-file-based-authenticity-protection"></a>
<a id="rst-fsverity"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

fs-verity (`fs/verity/`) is a support layer that filesystems can hook into to support transparent integrity and authenticity protection of read-only files.  Currently, it is supported by the ext4, f2fs, and btrfs filesystems.  Like fscrypt, not too much filesystem-specific code is needed to support fs-verity.

fs-verity is similar to [dm-verity](<https://www.kernel.org/doc/Documentation/admin-guide/device-mapper/verity.rst>)<a id="rst-dm-verity"></a> but works on files rather than block devices.  On regular files on filesystems supporting fs-verity, userspace can execute an ioctl that causes the filesystem to build a Merkle tree for the file and persist it to a filesystem-specific location associated with the file.

After this, the file is made readonly, and all reads from the file are automatically verified against the file's Merkle tree.  Reads of any corrupted data, including mmap reads, will fail.

Userspace can use another ioctl to retrieve the root hash (actually the "fs-verity file digest", which is a hash that includes the Merkle tree root hash) that fs-verity is enforcing for the file.  This ioctl executes in constant time, regardless of the file size.

fs-verity is essentially a way to hash a file in constant time, subject to the caveat that reads which would violate the hash will fail at runtime.

<a id="rst-use-cases"></a>

## Use cases

By itself, fs-verity only provides integrity protection, i.e. detection of accidental (non-malicious) corruption.

However, because fs-verity makes retrieving the file hash extremely efficient, it's primarily meant to be used as a tool to support authentication (detection of malicious modifications) or auditing (logging file hashes before use).

A standard file hash could be used instead of fs-verity.  However, this is inefficient if the file is large and only a small portion may be accessed.  This is often the case for Android application package (APK) files, for example.  These typically contain many translations, classes, and other resources that are infrequently or even never accessed on a particular device.  It would be slow and wasteful to read and hash the entire file before starting the application.

Unlike an ahead-of-time hash, fs-verity also re-verifies data each time it's paged in.  This ensures that malicious disk firmware can't undetectably change the contents of the file at runtime.

fs-verity does not replace or obsolete dm-verity.  dm-verity should still be used on read-only filesystems.  fs-verity is for files that must live on a read-write filesystem because they are independently updated and potentially user-installed, so dm-verity cannot be used.

fs-verity does not mandate a particular scheme for authenticating its file hashes.  (Similarly, dm-verity does not mandate a particular scheme for authenticating its block device root hashes.)  Options for authenticating fs-verity file hashes include:

- Trusted userspace code.  Often, the userspace code that accesses files can be trusted to authenticate them.  Consider e.g. an application that wants to authenticate data files before using them, or an application loader that is part of the operating system (which is already authenticated in a different way, such as by being loaded from a read-only partition that uses dm-verity) and that wants to authenticate applications before loading them.  In these cases, this trusted userspace code can authenticate a file's contents by retrieving its fs-verity digest using [FS_IOC_MEASURE_VERITY](<#rst-fs-ioc-measure-verity>), then verifying a signature of it using any userspace cryptographic library that supports digital signatures.

- Integrity Measurement Architecture (IMA).  IMA supports fs-verity file digests as an alternative to its traditional full file digests. "IMA appraisal" enforces that files contain a valid, matching signature in their "security.ima" extended attribute, as controlled by the IMA policy.  For more information, see the IMA documentation.

- Integrity Policy Enforcement (IPE).  IPE supports enforcing access control decisions based on immutable security properties of files, including those protected by fs-verity's built-in signatures. "IPE policy" specifically allows for the authorization of fs-verity files using properties `fsverity_digest` for identifying files by their verity digest, and `fsverity_signature` to authorize files with a verified fs-verity's built-in signature. For details on configuring IPE policies and understanding its operational modes, please refer to [IPE admin guide](</kernel/administration/admin-guide/lsm/ipe.md>).

- Trusted userspace code in combination with [Built-in signature verification](<#rst-built-in-signature-verification>).  This approach should be used only with great care.

<a id="rst-user-api"></a>

## User API

<a id="rst-fs-ioc-enable-verity"></a>

### FS_IOC_ENABLE_VERITY

The FS_IOC_ENABLE_VERITY ioctl enables fs-verity on a file.  It takes in a pointer to a struct fsverity_enable_arg, defined as follows:



```text
struct fsverity_enable_arg {
        __u32 version;
        __u32 hash_algorithm;
        __u32 block_size;
        __u32 salt_size;
        __u64 salt_ptr;
        __u32 sig_size;
        __u32 __reserved1;
        __u64 sig_ptr;
        __u64 __reserved2[11];
};
```

This structure contains the parameters of the Merkle tree to build for the file.  It must be initialized as follows:

- `version` must be 1.

- `hash_algorithm` must be the identifier for the hash algorithm to use for the Merkle tree, such as FS_VERITY_HASH_ALG_SHA256.  See `include/uapi/linux/fsverity.h` for the list of possible values.

- `block_size` is the Merkle tree block size, in bytes.  In Linux v6.3 and later, this can be any power of 2 between (inclusively) 1024 and the minimum of the system page size and the filesystem block size.  In earlier versions, the page size was the only allowed value.

- `salt_size` is the size of the salt in bytes, or 0 if no salt is provided.  The salt is a value that is prepended to every hashed block; it can be used to personalize the hashing for a particular file or device.  Currently the maximum salt size is 32 bytes.

- `salt_ptr` is the pointer to the salt, or NULL if no salt is provided.

- `sig_size` is the size of the builtin signature in bytes, or 0 if no builtin signature is provided.  Currently the builtin signature is (somewhat arbitrarily) limited to 16128 bytes.

- `sig_ptr`  is the pointer to the builtin signature, or NULL if no builtin signature is provided.  A builtin signature is only needed if the [Built-in signature verification](<#rst-built-in-signature-verification>) feature is being used.  It is not needed for IMA appraisal, and it is not needed if the file signature is being handled entirely in userspace.

- All reserved fields must be zeroed.

FS_IOC_ENABLE_VERITY causes the filesystem to build a Merkle tree for the file and persist it to a filesystem-specific location associated with the file, then mark the file as a verity file.  This ioctl may take a long time to execute on large files, and it is interruptible by fatal signals.

FS_IOC_ENABLE_VERITY checks for write access to the inode.  However, it must be executed on an O_RDONLY file descriptor and no processes can have the file open for writing.  Attempts to open the file for writing while this ioctl is executing will fail with ETXTBSY.  (This is necessary to guarantee that no writable file descriptors will exist after verity is enabled, and to guarantee that the file's contents are stable while the Merkle tree is being built over it.)

On success, FS_IOC_ENABLE_VERITY returns 0, and the file becomes a verity file.  On failure (including the case of interruption by a fatal signal), no changes are made to the file.

FS_IOC_ENABLE_VERITY can fail with the following errors:

- `EACCES`: the process does not have write access to the file

- `EBADMSG`: the builtin signature is malformed

- `EBUSY`: this ioctl is already running on the file

- `EEXIST`: the file already has verity enabled

- `EFAULT`: the caller provided inaccessible memory

- `EFBIG`: the file is too large to enable verity on

- `EINTR`: the operation was interrupted by a fatal signal

- `EINVAL`: unsupported version, hash algorithm, or block size; or reserved bits are set; or the file descriptor refers to neither a regular file nor a directory.

- `EISDIR`: the file descriptor refers to a directory

- `EKEYREJECTED`: the builtin signature doesn't match the file

- `EMSGSIZE`: the salt or builtin signature is too long

- `ENOKEY`: the ".fs-verity" keyring doesn't contain the certificate needed to verify the builtin signature

- `ENOPKG`: fs-verity recognizes the hash algorithm, but it's not available in the kernel as currently configured

- `ENOTTY`: this type of filesystem does not implement fs-verity

- `EOPNOTSUPP`: the kernel was not configured with fs-verity support; or the filesystem superblock has not had the 'verity' feature enabled on it; or the filesystem does not support fs-verity on this file.  (See [Filesystem support](<#rst-filesystem-support>).)

- `EPERM`: the file is append-only; or, a builtin signature is required and one was not provided.

- `EROFS`: the filesystem is read-only

- `ETXTBSY`: someone has the file open for writing.  This can be the caller's file descriptor, another open file descriptor, or the file reference held by a writable memory map.

<a id="rst-fs-ioc-measure-verity"></a>

### FS_IOC_MEASURE_VERITY

The FS_IOC_MEASURE_VERITY ioctl retrieves the digest of a verity file. The fs-verity file digest is a cryptographic digest that identifies the file contents that are being enforced on reads; it is computed via a Merkle tree and is different from a traditional full-file digest.

This ioctl takes in a pointer to a variable-length structure:



```text
struct fsverity_digest {
        __u16 digest_algorithm;
        __u16 digest_size; /* input/output */
        __u8 digest[];
};
```

`digest_size` is an input/output field.  On input, it must be initialized to the number of bytes allocated for the variable-length `digest` field.

On success, 0 is returned and the kernel fills in the structure as follows:

- `digest_algorithm` will be the hash algorithm used for the file digest.  It will match `fsverity_enable_arg::hash_algorithm`.

- `digest_size` will be the size of the digest in bytes, e.g. 32 for SHA-256.  (This can be redundant with `digest_algorithm`.)

- `digest` will be the actual bytes of the digest.

FS_IOC_MEASURE_VERITY is guaranteed to execute in constant time, regardless of the size of the file.

FS_IOC_MEASURE_VERITY can fail with the following errors:

- `EFAULT`: the caller provided inaccessible memory

- `ENODATA`: the file is not a verity file

- `ENOTTY`: this type of filesystem does not implement fs-verity

- `EOPNOTSUPP`: the kernel was not configured with fs-verity support, or the filesystem superblock has not had the 'verity' feature enabled on it.  (See [Filesystem support](<#rst-filesystem-support>).)

- `EOVERFLOW`: the digest is longer than the specified `digest_size` bytes.  Try providing a larger buffer.

<a id="rst-fs-ioc-read-verity-metadata"></a>

### FS_IOC_READ_VERITY_METADATA

The FS_IOC_READ_VERITY_METADATA ioctl reads verity metadata from a verity file.  This ioctl is available since Linux v5.12.

This ioctl is useful for cases where the verity verification should be performed somewhere other than the currently running kernel.

One example is a server program that takes a verity file and serves it to a client program, such that the client can do its own fs-verity compatible verification of the file.  This only makes sense if the client doesn't trust the server and if the server needs to provide the storage for the client.

Another example is copying verity metadata when creating filesystem images in userspace (such as with `mkfs.ext4 -d`).

This is a fairly specialized use case, and most fs-verity users won't need this ioctl.

This ioctl takes in a pointer to the following structure:



```text
#define FS_VERITY_METADATA_TYPE_MERKLE_TREE     1
#define FS_VERITY_METADATA_TYPE_DESCRIPTOR      2
#define FS_VERITY_METADATA_TYPE_SIGNATURE       3

struct fsverity_read_metadata_arg {
        __u64 metadata_type;
        __u64 offset;
        __u64 length;
        __u64 buf_ptr;
        __u64 __reserved;
};
```

`metadata_type` specifies the type of metadata to read:

- `FS_VERITY_METADATA_TYPE_MERKLE_TREE` reads the blocks of the Merkle tree.  The blocks are returned in order from the root level to the leaf level.  Within each level, the blocks are returned in the same order that their hashes are themselves hashed. See [Merkle tree](<#rst-merkle-tree>) for more information.

- `FS_VERITY_METADATA_TYPE_DESCRIPTOR` reads the fs-verity descriptor.  See [fs-verity descriptor](<#rst-fs-verity-descriptor>).

- `FS_VERITY_METADATA_TYPE_SIGNATURE` reads the builtin signature which was passed to FS_IOC_ENABLE_VERITY, if any.  See [Built-in signature verification](<#rst-built-in-signature-verification>).

The semantics are similar to those of `pread()`.  `offset` specifies the offset in bytes into the metadata item to read from, and `length` specifies the maximum number of bytes to read from the metadata item.  `buf_ptr` is the pointer to the buffer to read into, cast to a 64-bit integer.  `__reserved` must be 0.  On success, the number of bytes read is returned.  0 is returned at the end of the metadata item.  The returned length may be less than `length`, for example if the ioctl is interrupted.

The metadata returned by FS_IOC_READ_VERITY_METADATA isn't guaranteed to be authenticated against the file digest that would be returned by [FS_IOC_MEASURE_VERITY](<#rst-fs-ioc-measure-verity>), as the metadata is expected to be used to implement fs-verity compatible verification anyway (though absent a malicious disk, the metadata will indeed match).  E.g. to implement this ioctl, the filesystem is allowed to just read the Merkle tree blocks from disk without actually verifying the path to the root node.

FS_IOC_READ_VERITY_METADATA can fail with the following errors:

- `EFAULT`: the caller provided inaccessible memory

- `EINTR`: the ioctl was interrupted before any data was read

- `EINVAL`: reserved fields were set, or `offset + length` overflowed

- `ENODATA`: the file is not a verity file, or FS_VERITY_METADATA_TYPE_SIGNATURE was requested but the file doesn't have a builtin signature

- `ENOTTY`: this type of filesystem does not implement fs-verity, or this ioctl is not yet implemented on it

- `EOPNOTSUPP`: the kernel was not configured with fs-verity support, or the filesystem superblock has not had the 'verity' feature enabled on it.  (See [Filesystem support](<#rst-filesystem-support>).)

<a id="rst-fs-ioc-getflags"></a>

### FS_IOC_GETFLAGS

The existing ioctl FS_IOC_GETFLAGS (which isn't specific to fs-verity) can also be used to check whether a file has fs-verity enabled or not. To do so, check for FS_VERITY_FL (0x00100000) in the returned flags.

The verity flag is not settable via FS_IOC_SETFLAGS.  You must use FS_IOC_ENABLE_VERITY instead, since parameters must be provided.

<a id="rst-statx"></a>

### statx

Since Linux v5.5, the statx() system call sets STATX_ATTR_VERITY if the file has fs-verity enabled.  This can perform better than FS_IOC_GETFLAGS and FS_IOC_MEASURE_VERITY because it doesn't require opening the file, and opening verity files can be expensive.

<a id="rst-fs-ioc-fsgetxattr"></a>

### FS_IOC_FSGETXATTR

Since Linux v7.0, the FS_IOC_FSGETXATTR ioctl sets FS_XFLAG_VERITY (0x00020000) in the returned flags when the file has verity enabled. Note that this attribute cannot be set with FS_IOC_FSSETXATTR as enabling verity requires input parameters. See FS_IOC_ENABLE_VERITY.

<a id="rst-file-getattr"></a>

### file_getattr

Since Linux v7.0, the file_getattr() syscall sets FS_XFLAG_VERITY (0x00020000) in the returned flags when the file has verity enabled. Note that this attribute cannot be set with file_setattr() as enabling verity requires input parameters. See FS_IOC_ENABLE_VERITY.

<a id="rst-accessing-verity-files-1"></a>
<a id="rst-accessing-verity-files"></a>

## Accessing verity files

Applications can transparently access a verity file just like a non-verity one, with the following exceptions:

- Verity files are readonly.  They cannot be opened for writing or truncate()d, even if the file mode bits allow it.  Attempts to do one of these things will fail with EPERM.  However, changes to metadata such as owner, mode, timestamps, and xattrs are still allowed, since these are not measured by fs-verity.  Verity files can also still be renamed, deleted, and linked to.

- Direct I/O is not supported on verity files.  Attempts to use direct I/O on such files will fall back to buffered I/O.

- DAX (Direct Access) is not supported on verity files, because this would circumvent the data verification.

- Reads of data that doesn't match the verity Merkle tree will fail with EIO (for read()) or SIGBUS (for mmap() reads).

- If the sysctl "fs.verity.require_signatures" is set to 1 and the file is not signed by a key in the ".fs-verity" keyring, then opening the file will fail.  See [Built-in signature verification](<#rst-built-in-signature-verification>).

Direct access to the Merkle tree is not supported.  Therefore, if a verity file is copied, or is backed up and restored, then it will lose its "verity"-ness.  fs-verity is primarily meant for files like executables that are managed by a package manager.

<a id="rst-file-digest-computation"></a>

## File digest computation

This section describes how fs-verity hashes the file contents using a Merkle tree to produce the digest which cryptographically identifies the file contents.  This algorithm is the same for all filesystems that support fs-verity.

Userspace only needs to be aware of this algorithm if it needs to compute fs-verity file digests itself, e.g. in order to sign files.

<a id="rst-merkle-tree"></a>
<a id="rst-fsverity-merkle-tree"></a>

### Merkle tree

The file contents is divided into blocks, where the block size is configurable but is usually 4096 bytes.  The end of the last block is zero-padded if needed.  Each block is then hashed, producing the first level of hashes.  Then, the hashes in this first level are grouped into 'blocksize'-byte blocks (zero-padding the ends as needed) and these blocks are hashed, producing the second level of hashes.  This proceeds up the tree until only a single block remains.  The hash of this block is the "Merkle tree root hash".

If the file fits in one block and is nonempty, then the "Merkle tree root hash" is simply the hash of the single data block.  If the file is empty, then the "Merkle tree root hash" is all zeroes.

The "blocks" here are not necessarily the same as "filesystem blocks".

If a salt was specified, then it's zero-padded to the closest multiple of the input size of the hash algorithm's compression function, e.g. 64 bytes for SHA-256 or 128 bytes for SHA-512.  The padded salt is prepended to every data or Merkle tree block that is hashed.

The purpose of the block padding is to cause every hash to be taken over the same amount of data, which simplifies the implementation and keeps open more possibilities for hardware acceleration.  The purpose of the salt padding is to make the salting "free" when the salted hash state is precomputed, then imported for each hash.

Example: in the recommended configuration of SHA-256 and 4K blocks, 128 hash values fit in each block.  Thus, each level of the Merkle tree is approximately 128 times smaller than the previous, and for large files the Merkle tree's size converges to approximately 1/127 of the original file size.  However, for small files, the padding is significant, making the space overhead proportionally more.

<a id="rst-fs-verity-descriptor"></a>
<a id="rst-fsverity-descriptor"></a>

### fs-verity descriptor

By itself, the Merkle tree root hash is ambiguous.  For example, it can't a distinguish a large file from a small second file whose data is exactly the top-level hash block of the first file.  Ambiguities also arise from the convention of padding to the next block boundary.

To solve this problem, the fs-verity file digest is actually computed as a hash of the following structure, which contains the Merkle tree root hash as well as other fields such as the file size:



```text
struct fsverity_descriptor {
        __u8 version;           /* must be 1 */
        __u8 hash_algorithm;    /* Merkle tree hash algorithm */
        __u8 log_blocksize;     /* log2 of size of data and tree blocks */
        __u8 salt_size;         /* size of salt in bytes; 0 if none */
        __le32 __reserved_0x04; /* must be 0 */
        __le64 data_size;       /* size of file the Merkle tree is built over */
        __u8 root_hash[64];     /* Merkle tree root hash */
        __u8 salt[32];          /* salt prepended to each hashed block */
        __u8 __reserved[144];   /* must be 0's */
};
```

<a id="rst-built-in-signature-verification"></a>

## Built-in signature verification

CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y adds supports for in-kernel verification of fs-verity builtin signatures.

**IMPORTANT**\!  Please take great care before using this feature. It is not the only way to do signatures with fs-verity, and the alternatives (such as userspace signature verification, and IMA appraisal) can be much better.  It's also easy to fall into a trap of thinking this feature solves more problems than it actually does.

Enabling this option adds the following:

1. At boot time, the kernel creates a keyring named ".fs-verity".  The root user can add trusted X.509 certificates to this keyring using the add_key() system call.

2. [FS_IOC_ENABLE_VERITY](<#rst-fs-ioc-enable-verity>) accepts a pointer to a PKCS\#7 formatted detached signature in DER format of the file's fs-verity digest. On success, the ioctl persists the signature alongside the Merkle tree.  Then, any time the file is opened, the kernel verifies the file's actual digest against this signature, using the certificates in the ".fs-verity" keyring. This verification happens as long as the file's signature exists, regardless of the state of the sysctl variable "fs.verity.require_signatures" described in the next item. The IPE LSM relies on this behavior to recognize and label fsverity files that contain a verified built-in fsverity signature.

3. A new sysctl "fs.verity.require_signatures" is made available. When set to 1, the kernel requires that all verity files have a correctly signed digest as described in (2).

The data that the signature as described in (2) must be a signature of is the fs-verity file digest in the following format:



```text
struct fsverity_formatted_digest {
        char magic[8];                  /* must be "FSVerity" */
        __le16 digest_algorithm;
        __le16 digest_size;
        __u8 digest[];
};
```

That's it.  It should be emphasized again that fs-verity builtin signatures are not the only way to do signatures with fs-verity.  See [Use cases](<#rst-use-cases>) for an overview of ways in which fs-verity can be used. fs-verity builtin signatures have some major limitations that should be carefully considered before using them:

- Builtin signature verification does *not* make the kernel enforce that any files actually have fs-verity enabled.  Thus, it is not a complete authentication policy.  Currently, if it is used, one way to complete the authentication policy is for trusted userspace code to explicitly check whether files have fs-verity enabled with a signature before they are accessed.  (With fs.verity.require_signatures=1, just checking whether fs-verity is enabled suffices.)  But, in this case the trusted userspace code could just store the signature alongside the file and verify it itself using a cryptographic library, instead of using this feature.

- Another approach is to utilize fs-verity builtin signature verification in conjunction with the IPE LSM, which supports defining a kernel-enforced, system-wide authentication policy that allows only files with a verified fs-verity builtin signature to perform certain operations, such as execution. Note that IPE doesn't require fs.verity.require_signatures=1. Please refer to [IPE admin guide](</kernel/administration/admin-guide/lsm/ipe.md>) for more details.

- A file's builtin signature can only be set at the same time that fs-verity is being enabled on the file.  Changing or deleting the builtin signature later requires re-creating the file.

- Builtin signature verification uses the same set of public keys for all fs-verity enabled files on the system.  Different keys cannot be trusted for different files; each key is all or nothing.

- The sysctl fs.verity.require_signatures applies system-wide. Setting it to 1 only works when all users of fs-verity on the system agree that it should be set to 1.  This limitation can prevent fs-verity from being used in cases where it would be helpful.

- Builtin signature verification can only use signature algorithms that are supported by the kernel.  For example, the kernel does not yet support Ed25519, even though this is often the signature algorithm that is recommended for new cryptographic designs.

- fs-verity builtin signatures are in PKCS\#7 format, and the public keys are in X.509 format.  These formats are commonly used, including by some other kernel features (which is why the fs-verity builtin signatures use them), and are very feature rich. Unfortunately, history has shown that code that parses and handles these formats (which are from the 1990s and are based on ASN.1) often has vulnerabilities as a result of their complexity.  This complexity is not inherent to the cryptography itself.

  fs-verity users who do not need advanced features of X.509 and PKCS\#7 should strongly consider using simpler formats, such as plain Ed25519 keys and signatures, and verifying signatures in userspace.

  fs-verity users who choose to use X.509 and PKCS\#7 anyway should still consider that verifying those signatures in userspace is more flexible (for other reasons mentioned earlier in this document) and eliminates the need to enable CONFIG_FS_VERITY_BUILTIN_SIGNATURES and its associated increase in kernel attack surface.  In some cases it can even be necessary, since advanced X.509 and PKCS\#7 features do not always work as intended with the kernel.  For example, the kernel does not check X.509 certificate validity times.

  Note: IMA appraisal, which supports fs-verity, does not use PKCS\#7 for its signatures, so it partially avoids the issues discussed here.  IMA appraisal does use X.509.

<a id="rst-filesystem-support"></a>

## Filesystem support

fs-verity is supported by several filesystems, described below.  The CONFIG_FS_VERITY kconfig option must be enabled to use fs-verity on any of these filesystems.

`include/linux/fsverity.h` declares the interface between the `fs/verity/` support layer and filesystems.  Briefly, filesystems must provide an `fsverity_operations` structure that provides methods to read and write the verity metadata to a filesystem-specific location, including the Merkle tree blocks and `fsverity_descriptor`.  Filesystems must also call functions in `fs/verity/` at certain times, such as when a file is opened or when pages have been read into the pagecache.  (See [Verifying data](<#rst-verifying-data>).)

<a id="rst-ext4"></a>

### ext4

ext4 supports fs-verity since Linux v5.4 and e2fsprogs v1.45.2.

To create verity files on an ext4 filesystem, the filesystem must have been formatted with `-O verity` or had `tune2fs -O verity` run on it.  "verity" is an RO_COMPAT filesystem feature, so once set, old kernels will only be able to mount the filesystem readonly, and old versions of e2fsck will be unable to check the filesystem.

Originally, an ext4 filesystem with the "verity" feature could only be mounted when its block size was equal to the system page size (typically 4096 bytes).  In Linux v6.3, this limitation was removed.

ext4 sets the EXT4_VERITY_FL on-disk inode flag on verity files.  It can only be set by [FS_IOC_ENABLE_VERITY](<#rst-fs-ioc-enable-verity>), and it cannot be cleared.

ext4 also supports encryption, which can be used simultaneously with fs-verity.  In this case, the plaintext data is verified rather than the ciphertext.  This is necessary in order to make the fs-verity file digest meaningful, since every file is encrypted differently.

ext4 stores the verity metadata (Merkle tree and fsverity_descriptor) past the end of the file, starting at the first 64K boundary beyond i_size.  This approach works because (a) verity files are readonly, and (b) pages fully beyond i_size aren't visible to userspace but can be read/written internally by ext4 with only some relatively small changes to ext4.  This approach avoids having to depend on the EA_INODE feature and on rearchitecturing ext4's xattr support to support paging multi-gigabyte xattrs into memory, and to support encrypting xattrs.  Note that the verity metadata *must* be encrypted when the file is, since it contains hashes of the plaintext data.

ext4 only allows verity on extent-based files.

<a id="rst-f2fs"></a>

### f2fs

f2fs supports fs-verity since Linux v5.4 and f2fs-tools v1.11.0.

To create verity files on an f2fs filesystem, the filesystem must have been formatted with `-O verity`.

f2fs sets the FADVISE_VERITY_BIT on-disk inode flag on verity files. It can only be set by [FS_IOC_ENABLE_VERITY](<#rst-fs-ioc-enable-verity>), and it cannot be cleared.

Like ext4, f2fs stores the verity metadata (Merkle tree and fsverity_descriptor) past the end of the file, starting at the first 64K boundary beyond i_size.  See explanation for ext4 above. Moreover, f2fs supports at most 4096 bytes of xattr entries per inode which usually wouldn't be enough for even a single Merkle tree block.

f2fs doesn't support enabling verity on files that currently have atomic or volatile writes pending.

<a id="rst-btrfs"></a>

### btrfs

btrfs supports fs-verity since Linux v5.15.  Verity-enabled inodes are marked with a RO_COMPAT inode flag, and the verity metadata is stored in separate btree items.

<a id="rst-implementation-details"></a>

## Implementation details

<a id="rst-verifying-data"></a>

### Verifying data

fs-verity ensures that all reads of a verity file's data are verified, regardless of which syscall is used to do the read (e.g. mmap(), read(), pread()) and regardless of whether it's the first read or a later read (unless the later read can return cached data that was already verified).  Below, we describe how filesystems implement this.

<a id="rst-pagecache"></a>

#### Pagecache

For filesystems using Linux's pagecache, the `->read_folio()` and `->readahead()` methods must be modified to verify folios before they are marked Uptodate.  Merely hooking `->read_iter()` would be insufficient, since `->read_iter()` is not used for memory maps.

Therefore, fs/verity/ provides the function fsverity_verify_blocks() which verifies data that has been read into the pagecache of a verity inode.  The containing folio must still be locked and not Uptodate, so it's not yet readable by userspace.  As needed to do the verification, fsverity_verify_blocks() will call back into the filesystem to read hash blocks via fsverity_operations::read_merkle_tree_page().

fsverity_verify_blocks() returns false if verification failed; in this case, the filesystem must not set the folio Uptodate.  Following this, as per the usual Linux pagecache behavior, attempts by userspace to read() from the part of the file containing the folio will fail with EIO, and accesses to the folio within a memory map will raise SIGBUS.

In principle, verifying a data block requires verifying the entire path in the Merkle tree from the data block to the root hash. However, for efficiency the filesystem may cache the hash blocks. Therefore, fsverity_verify_blocks() only ascends the tree reading hash blocks until an already-verified hash block is seen.  It then verifies the path to that block.

This optimization, which is also used by dm-verity, results in excellent sequential read performance.  This is because usually (e.g. 127 in 128 times for 4K blocks and SHA-256) the hash block from the bottom level of the tree will already be cached and checked from reading a previous data block.  However, random reads perform worse.

<a id="rst-block-device-based-filesystems"></a>

#### Block device based filesystems

Block device based filesystems (e.g. ext4 and f2fs) in Linux also use the pagecache, so the above subsection applies too.  However, they also usually read many data blocks from a file at once, grouped into a structure called a "bio".  To make it easier for these types of filesystems to support fs-verity, fs/verity/ also provides a function fsverity_verify_bio() which verifies all data blocks in a bio.

ext4 and f2fs also support encryption.  If a verity file is also encrypted, the data must be decrypted before being verified.  To support this, these filesystems allocate a "post-read context" for each bio and store it in `->bi_private`:



```text
struct bio_post_read_ctx {
       struct bio *bio;
       struct work_struct work;
       unsigned int cur_step;
       unsigned int enabled_steps;
};
```

`enabled_steps` is a bitmask that specifies whether decryption, verity, or both is enabled.  After the bio completes, for each needed postprocessing step the filesystem enqueues the bio_post_read_ctx on a workqueue, and then the workqueue work does the decryption or verification.  Finally, folios where no decryption or verity error occurred are marked Uptodate, and the folios are unlocked.

On many filesystems, files can contain holes.  Normally, `->readahead()` simply zeroes hole blocks and considers the corresponding data to be up-to-date; no bios are issued.  To prevent this case from bypassing fs-verity, filesystems use fsverity_verify_blocks() to verify hole blocks.

Filesystems also disable direct I/O on verity files, since otherwise direct I/O would bypass fs-verity.

<a id="rst-userspace-utility"></a>

## Userspace utility

This document focuses on the kernel, but a userspace utility for fs-verity can be found at:

> [https://git.kernel.org/pub/scm/fs/fsverity/fsverity-utils.git](<https://git.kernel.org/pub/scm/fs/fsverity/fsverity-utils.git>)

See the README.md file in the fsverity-utils source tree for details, including examples of setting up fs-verity protected files.

<a id="rst-tests"></a>

## Tests

To test fs-verity, use xfstests.  For example, using [kvm-xfstests](<https://github.com/tytso/xfstests-bld/blob/master/Documentation/kvm-quickstart.md>)<a id="rst-kvm-xfstests"></a>:



```text
kvm-xfstests -c ext4,f2fs,btrfs -g verity
```

<a id="rst-faq"></a>

## FAQ

This section answers frequently asked questions about fs-verity that weren't already directly answered in other parts of this document.

**Q:** Why isn't fs-verity part of IMA?

**A:** fs-verity and IMA (Integrity Measurement Architecture) have different focuses.  fs-verity is a filesystem-level mechanism for hashing individual files using a Merkle tree.  In contrast, IMA specifies a system-wide policy that specifies which files are hashed and what to do with those hashes, such as log them, authenticate them, or add them to a measurement list.

IMA supports the fs-verity hashing mechanism as an alternative to full file hashes, for those who want the performance and security benefits of the Merkle tree based hash.  However, it doesn't make sense to force all uses of fs-verity to be through IMA.  fs-verity already meets many users' needs even as a standalone filesystem feature, and it's testable like other filesystem features e.g. with xfstests.

**Q:** Isn't fs-verity useless because the attacker can just modify the hashes in the Merkle tree, which is stored on-disk?

**A:** To verify the authenticity of an fs-verity file you must verify the authenticity of the "fs-verity file digest", which incorporates the root hash of the Merkle tree.  See [Use cases](<#rst-use-cases>).

**Q:** Isn't fs-verity useless because the attacker can just replace a verity file with a non-verity one?

**A:** See [Use cases](<#rst-use-cases>).  In the initial use case, it's really trusted userspace code that authenticates the files; fs-verity is just a tool to do this job efficiently and securely.  The trusted userspace code will consider non-verity files to be inauthentic.

**Q:** Why does the Merkle tree need to be stored on-disk?  Couldn't you store just the root hash?

**A:** If the Merkle tree wasn't stored on-disk, then you'd have to compute the entire tree when the file is first accessed, even if just one byte is being read.  This is a fundamental consequence of how Merkle tree hashing works.  To verify a leaf node, you need to verify the whole path to the root hash, including the root node (the thing which the root hash is a hash of).  But if the root node isn't stored on-disk, you have to compute it by hashing its children, and so on until you've actually hashed the entire file.

That defeats most of the point of doing a Merkle tree-based hash, since if you have to hash the whole file ahead of time anyway, then you could simply do sha256(file) instead.  That would be much simpler, and a bit faster too.

It's true that an in-memory Merkle tree could still provide the advantage of verification on every read rather than just on the first read.  However, it would be inefficient because every time a hash page gets evicted (you can't pin the entire Merkle tree into memory, since it may be very large), in order to restore it you again need to hash everything below it in the tree.  This again defeats most of the point of doing a Merkle tree-based hash, since a single block read could trigger re-hashing gigabytes of data.

**Q:** But couldn't you store just the leaf nodes and compute the rest?

**A:** See previous answer; this really just moves up one level, since one could alternatively interpret the data blocks as being the leaf nodes of the Merkle tree.  It's true that the tree can be computed much faster if the leaf level is stored rather than just the data, but that's only because each level is less than 1% the size of the level below (assuming the recommended settings of SHA-256 and 4K blocks).  For the exact same reason, by storing "just the leaf nodes" you'd already be storing over 99% of the tree, so you might as well simply store the whole tree.

**Q:** Can the Merkle tree be built ahead of time, e.g. distributed as part of a package that is installed to many computers?

**A:** This isn't currently supported.  It was part of the original design, but was removed to simplify the kernel UAPI and because it wasn't a critical use case.  Files are usually installed once and used many times, and cryptographic hashing is somewhat fast on most modern processors.

**Q:** Why doesn't fs-verity support writes?

**A:** Write support would be very difficult and would require a completely different design, so it's well outside the scope of fs-verity.  Write support would require:

- A way to maintain consistency between the data and hashes, including all levels of hashes, since corruption after a crash (especially of potentially the entire file\!) is unacceptable. The main options for solving this are data journalling, copy-on-write, and log-structured volume.  But it's very hard to retrofit existing filesystems with new consistency mechanisms. Data journalling is available on ext4, but is very slow.

- Rebuilding the Merkle tree after every write, which would be extremely inefficient.  Alternatively, a different authenticated dictionary structure such as an "authenticated skiplist" could be used.  However, this would be far more complex.

Compare it to dm-verity vs. dm-integrity.  dm-verity is very simple: the kernel just verifies read-only data against a read-only Merkle tree.  In contrast, dm-integrity supports writes but is slow, is much more complex, and doesn't actually support full-device authentication since it authenticates each sector independently, i.e. there is no "root hash".  It doesn't really make sense for the same device-mapper target to support these two very different cases; the same applies to fs-verity.

**Q:** Since verity files are immutable, why isn't the immutable bit set?

**A:** The existing "immutable" bit (FS_IMMUTABLE_FL) already has a specific set of semantics which not only make the file contents read-only, but also prevent the file from being deleted, renamed, linked to, or having its owner or mode changed.  These extra properties are unwanted for fs-verity, so reusing the immutable bit isn't appropriate.

**Q:** Why does the API use ioctls instead of setxattr() and getxattr()?

**A:** Abusing the xattr interface for basically arbitrary syscalls is heavily frowned upon by most of the Linux filesystem developers. An xattr should really just be an xattr on-disk, not an API to e.g. magically trigger construction of a Merkle tree.

**Q:** Does fs-verity support remote filesystems?

**A:** So far all filesystems that have implemented fs-verity support are local filesystems, but in principle any filesystem that can store per-file verity metadata can support fs-verity, regardless of whether it's local or remote.  Some filesystems may have fewer options of where to store the verity metadata; one possibility is to store it past the end of the file and "hide" it from userspace by manipulating i_size.  The data verification functions provided by `fs/verity/` also assume that the filesystem uses the Linux pagecache, but both local and remote filesystems normally do so.

**Q:** Why is anything filesystem-specific at all?  Shouldn't fs-verity be implemented entirely at the VFS level?

**A:** There are many reasons why this is not possible or would be very difficult, including the following:

- To prevent bypassing verification, folios must not be marked Uptodate until they've been verified.  Currently, each filesystem is responsible for marking folios Uptodate via `->readahead()`.  Therefore, currently it's not possible for the VFS to do the verification on its own.  Changing this would require significant changes to the VFS and all filesystems.

- It would require defining a filesystem-independent way to store the verity metadata.  Extended attributes don't work for this because (a) the Merkle tree may be gigabytes, but many filesystems assume that all xattrs fit into a single 4K filesystem block, and (b) ext4 and f2fs encryption doesn't encrypt xattrs, yet the Merkle tree *must* be encrypted when the file contents are, because it stores hashes of the plaintext file contents.

  So the verity metadata would have to be stored in an actual file.  Using a separate file would be very ugly, since the metadata is fundamentally part of the file to be protected, and it could cause problems where users could delete the real file but not the metadata file or vice versa.  On the other hand, having it be in the same file would break applications unless filesystems' notion of i_size were divorced from the VFS's, which would be complex and require changes to all filesystems.

- It's desirable that FS_IOC_ENABLE_VERITY uses the filesystem's transaction mechanism so that either the file ends up with verity enabled, or no changes were made.  Allowing intermediate states to occur after a crash may cause problems.

---

# Macintosh HFS Filesystem for Linux

_Peios Kernel / Internals / Filesystems_

> HFS stands for Hierarchical File System and is the filesystem used by the Mac Plus and all later Macintosh models. Earlier Macintosh models used MFS (Macintosh File System), which is not supported, MacOS 8.1 and newer support a filesystem…

<a id="rst-macintosh-hfs-filesystem-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> This filesystem doesn't have a maintainer.

HFS stands for `Hierarchical File System` and is the filesystem used by the Mac Plus and all later Macintosh models.  Earlier Macintosh models used MFS (`Macintosh File System`), which is not supported, MacOS 8.1 and newer support a filesystem called HFS+ that's similar to HFS but is extended in various areas.  Use the hfsplus filesystem driver to access such filesystems from Linux.

<a id="rst-mount-options"></a>

## Mount options

When mounting an HFS filesystem, the following options are accepted:

> - **creator=cccc, type=cccc**
>
>   Specifies the creator/type values as shown by the MacOS finder used for creating new files.  Default values: '????'.
>
> - **uid=n, gid=n**
>
>   Specifies the user/group that owns all files on the filesystems. Default:  user/group id of the mounting process.
>
> - **dir_umask=n, file_umask=n, umask=n**
>
>   Specifies the umask used for all files , all directories or all files and directories.  Defaults to the umask of the mounting process.
>
> - **session=n**
>
>   Select the CDROM session to mount as HFS filesystem.  Defaults to leaving that decision to the CDROM driver.  This option will fail with anything but a CDROM as underlying devices.
>
> - **part=n**
>
>   Select partition number n from the devices.  Does only makes sense for CDROMS because they can't be partitioned under Linux. For disk devices the generic partition parsing code does this for us.  Defaults to not parsing the partition table at all.
>
> - **quiet**
>
>   Ignore invalid mount options instead of complaining.

<a id="rst-writing-to-hfs-filesystems"></a>

## Writing to HFS Filesystems

HFS is not a UNIX filesystem, thus it does not have the usual features you'd expect:

> - You can't modify the set-uid, set-gid, sticky or executable bits or the uid and gid of files.
>
> - You can't create hard- or symlinks, device files, sockets or FIFOs.

HFS does on the other have the concepts of multiple forks per file.  These non-standard forks are represented as hidden additional files in the normal filesystems namespace which is kind of a cludge and makes the semantics for the a little strange:

> - You can't create, delete or rename resource forks of files or the Finder's metadata.
>
> - They are however created (with default values), deleted and renamed along with the corresponding data fork or directory.
>
> - Copying files to a different filesystem will loose those attributes that are essential for MacOS to work.

<a id="rst-creating-hfs-filesystems"></a>

## Creating HFS filesystems

The hfsutils package from Robert Leslie contains a program called hformat that can be used to create HFS filesystem. See &lt;[https://www.mars.org/home/rob/proj/hfs/](<https://www.mars.org/home/rob/proj/hfs/>)&gt; for details.

<a id="rst-credits"></a>

## Credits

The HFS drivers was written by Paul H. Hargrovea ([hargrove@sccm.Stanford.EDU](<mailto:hargrove@sccm.Stanford.EDU>)). Roman Zippel ([roman@ardistech.com](<mailto:roman@ardistech.com>)) rewrote large parts of the code and brought in btree routines derived from Brad Boyer's hfsplus driver.

---

# Macintosh HFSPlus Filesystem for Linux

_Peios Kernel / Internals / Filesystems_

> HFSPlus is a filesystem first introduced in MacOS 8.1. HFSPlus has several extensions to HFS, including 32-bit allocation blocks, 255-character unicode filenames, and file sizes of 2^63 bytes.

<a id="rst-macintosh-hfsplus-filesystem-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

HFSPlus is a filesystem first introduced in MacOS 8.1. HFSPlus has several extensions to HFS, including 32-bit allocation blocks, 255-character unicode filenames, and file sizes of 2^63 bytes.

<a id="rst-mount-options"></a>

## Mount options

When mounting an HFSPlus filesystem, the following options are accepted:

> - **creator=cccc, type=cccc**
>
>   Specifies the creator/type values as shown by the MacOS finder used for creating new files.  Default values: '????'.
>
> - **uid=n, gid=n**
>
>   Specifies the user/group that owns all files on the filesystem that have uninitialized permissions structures. Default:  user/group id of the mounting process.
>
> - **umask=n**
>
>   Specifies the umask (in octal) used for files and directories that have uninitialized permissions structures. Default:  umask of the mounting process.
>
> - **session=n**
>
>   Select the CDROM session to mount as HFSPlus filesystem.  Defaults to leaving that decision to the CDROM driver.  This option will fail with anything but a CDROM as underlying devices.
>
> - **part=n**
>
>   Select partition number n from the devices.  This option only makes sense for CDROMs because they can't be partitioned under Linux. For disk devices the generic partition parsing code does this for us.  Defaults to not parsing the partition table at all.
>
> - **decompose**
>
>   Decompose file name characters.
>
> - **nodecompose**
>
>   Do not decompose file name characters.
>
> - **force**
>
>   Used to force write access to volumes that are marked as journalled or locked.  Use at your own risk.
>
> - **nls=cccc**
>
>   Encoding to use when presenting file names.

<a id="rst-references"></a>

## References

kernel source:          &lt;[file:fs/hfsplus](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/fs/hfsplus?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)&gt;

Apple Technote 1150     [https://developer.apple.com/legacy/library/technotes/tn/tn1150.html](<https://developer.apple.com/legacy/library/technotes/tn/tn1150.html>)

---

# Read/Write HPFS 2.09

_Peios Kernel / Internals / Filesystems_

> 1998-2004, Mikulas Patocka

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-read-write-hpfs-2-09"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1998-2004, Mikulas Patocka

**email:** [mikulas@artax.karlin.mff.cuni.cz](<mailto:mikulas@artax.karlin.mff.cuni.cz>)

**homepage:** [https://artax.karlin.mff.cuni.cz/\~mikulas/vyplody/hpfs/index-e.cgi](<https://artax.karlin.mff.cuni.cz/~mikulas/vyplody/hpfs/index-e.cgi>)

<a id="rst-credits"></a>

## Credits

- **Chris Smith, 1993, original read-only HPFS, some code and hpfs structures file**

  is taken from it

Jacques Gelinas, MSDos mmap, Inspired by fs/nfs/mmap.c (Jon Tombs 15 Aug 1993)

Werner Almesberger, 1992, 1993, MSDos option parser &amp; CR/LF conversion

Mount options

- **uid=xxx,gid=xxx,umask=xxx (default uid=gid=0 umask=default_system_umask)**

  Set owner/group/mode for files that do not have it specified in extended attributes. Mode is inverted umask - for example umask 027 gives owner all permission, group read permission and anybody else no access. Note that for files mode is anded with 0666. If you want files to have 'x' rights, you must use extended attributes.

- **case=lower,asis (default asis)**

  File name lowercasing in readdir.

- **conv=binary,text,auto (default binary)**

  CR/LF -&gt; LF conversion, if auto, decision is made according to extension - there is a list of text extensions (I thing it's better to not convert text file than to damage binary file). If you want to change that list, change it in the source. Original readonly HPFS contained some strange heuristic algorithm that I removed. I thing it's danger to let the computer decide whether file is text or binary. For example, DJGPP binaries contain small text message at the beginning and they could be misidentified and damaged under some circumstances.

- **check=none,normal,strict (default normal)**

  Check level. Selecting none will cause only little speedup and big danger. I tried to write it so that it won't crash if check=normal on corrupted filesystems. check=strict means many superfluous checks - used for debugging (for example it checks if file is allocated in bitmaps when accessing it).

- **errors=continue,remount-ro,panic (default remount-ro)**

  Behaviour when filesystem errors found.

- **chkdsk=no,errors,always (default errors)**

  When to mark filesystem dirty so that OS/2 checks it.

- **eas=no,ro,rw (default rw)**

  What to do with extended attributes. 'no' - ignore them and use always values specified in uid/gid/mode options. 'ro' - read extended attributes but do not create them. 'rw' - create extended attributes when you use chmod/chown/chgrp/mknod/ln -s on the filesystem.

- **timeshift=(-)nnn (default 0)**

  Shifts the time by nnn seconds. For example, if you see under linux one hour more, than under os/2, use timeshift=-3600.

<a id="rst-file-names"></a>

## File names

As in OS/2, filenames are case insensitive. However, shell thinks that names are case sensitive, so for example when you create a file FOO, you can use 'cat FOO', 'cat Foo', 'cat foo' or 'cat F\*' but not 'cat f\*'. Note, that you also won't be able to compile linux kernel (and maybe other things) on HPFS because kernel creates different files with names like bootsect.S and bootsect.s. When searching for file whose name has characters &gt;= 128, codepages are used - see below. OS/2 ignores dots and spaces at the end of file name, so this driver does as well. If you create 'a. ...', the file 'a' will be created, but you can still access it under names 'a.', 'a..', 'a .  . . ' etc.

<a id="rst-extended-attributes"></a>

## Extended attributes

On HPFS partitions, OS/2 can associate to each file a special information called extended attributes. Extended attributes are pairs of (key,value) where key is an ascii string identifying that attribute and value is any string of bytes of variable length. OS/2 stores window and icon positions and file types there. So why not use it for unix-specific info like file owner or access rights? This driver can do it. If you chown/chgrp/chmod on a hpfs partition, extended attributes with keys "UID", "GID" or "MODE" and 2-byte values are created. Only that extended attributes those value differs from defaults specified in mount options are created. Once created, the extended attributes are never deleted, they're just changed. It means that when your default uid=0 and you type something like 'chown luser file; chown root file' the file will contain extended attribute UID=0. And when you umount the fs and mount it again with uid=luser_uid, the file will be still owned by root\! If you chmod file to 444, extended attribute "MODE" will not be set, this special case is done by setting read-only flag. When you mknod a block or char device, besides "MODE", the special 4-byte extended attribute "DEV" will be created containing the device number. Currently this driver cannot resize extended attributes - it means that if somebody (I don't know who?) has set "UID", "GID", "MODE" or "DEV" attributes with different sizes, they won't be rewritten and changing these values doesn't work.

<a id="rst-symlinks"></a>

## Symlinks

You can do symlinks on HPFS partition, symlinks are achieved by setting extended attribute named "SYMLINK" with symlink value. Like on ext2, you can chown and chgrp symlinks but I don't know what is it good for. chmoding symlink results in chmoding file where symlink points. These symlinks are just for Linux use and incompatible with OS/2. OS/2 PmShell symlinks are not supported because they are stored in very crazy way. They tried to do it so that link changes when file is moved ... sometimes it works. But the link is partly stored in directory extended attributes and partly in OS2SYS.INI. I don't want (and don't know how) to analyze or change OS2SYS.INI.

<a id="rst-codepages"></a>

## Codepages

HPFS can contain several uppercasing tables for several codepages and each file has a pointer to codepage its name is in. However OS/2 was created in America where people don't care much about codepages and so multiple codepages support is quite buggy. I have Czech OS/2 working in codepage 852 on my disk. Once I booted English OS/2 working in cp 850 and I created a file on my 852 partition. It marked file name codepage as 850 - good. But when I again booted Czech OS/2, the file was completely inaccessible under any name. It seems that OS/2 uppercases the search pattern with its system code page (852) and file name it's comparing to with its code page (850). These could never match. Is it really what IBM developers wanted? But problems continued. When I created in Czech OS/2 another file in that directory, that file was inaccessible too. OS/2 probably uses different uppercasing method when searching where to place a file (note, that files in HPFS directory must be sorted) and when searching for a file. Finally when I opened this directory in PmShell, PmShell crashed (the funny thing was that, when rebooted, PmShell tried to reopen this directory again :-). chkdsk happily ignores these errors and only low-level disk modification saved me.  Never mix different language versions of OS/2 on one system although HPFS was designed to allow that. OK, I could implement complex codepage support to this driver but I think it would cause more problems than benefit with such buggy implementation in OS/2. So this driver simply uses first codepage it finds for uppercasing and lowercasing no matter what's file codepage index. Usually all file names are in this codepage - if you don't try to do what I described above :-)

<a id="rst-known-bugs"></a>

## Known bugs

HPFS386 on OS/2 server is not supported. HPFS386 installed on normal OS/2 client should work. If you have OS/2 server, use only read-only mode. I don't know how to handle some HPFS386 structures like access control list or extended perm list, I don't know how to delete them when file is deleted and how to not overwrite them with extended attributes. Send me some info on these structures and I'll make it. However, this driver should detect presence of HPFS386 structures, remount read-only and not destroy them (I hope).

When there's not enough space for extended attributes, they will be truncated and no error is returned.

OS/2 can't access files if the path is longer than about 256 chars but this driver allows you to do it. chkdsk ignores such errors.

Sometimes you won't be able to delete some files on a very full filesystem (returning error ENOSPC). That's because file in non-leaf node in directory tree (one directory, if it's large, has dirents in tree on HPFS) must be replaced with another node when deleted. And that new file might have larger name than the old one so the new name doesn't fit in directory node (dnode). And that would result in directory tree splitting, that takes disk space. Workaround is to delete other files that are leaf (probability that the file is non-leaf is about 1/50) or to truncate file first to make some space. You encounter this problem only if you have many directories so that preallocated directory band is full i.e.:



```text
number_of_directories / size_of_filesystem_in_mb > 4.
```

You can't delete open directories.

You can't rename over directories (what is it good for?).

Renaming files so that only case changes doesn't work. This driver supports it but vfs doesn't. Something like 'mv file FILE' won't work.

All atimes and directory mtimes are not updated. That's because of performance reasons. If you extremely wish to update them, let me know, I'll write it (but it will be slow).

When the system is out of memory and swap, it may slightly corrupt filesystem (lost files, unbalanced directories). (I guess all filesystem may do it).

When compiled, you get warning: function declaration isn't a prototype. Does anybody know what does it mean?

<a id="rst-what-does-unbalanced-tree-message-mean"></a>

## What does "unbalanced tree" message mean?

Old versions of this driver created sometimes unbalanced dnode trees. OS/2 chkdsk doesn't scream if the tree is unbalanced (and sometimes creates unbalanced trees too :-) but both HPFS and HPFS386 contain bug that it rarely crashes when the tree is not balanced. This driver handles unbalanced trees correctly and writes warning if it finds them. If you see this message, this is probably because of directories created with old version of this driver. Workaround is to move all files from that directory to another and then back again. Do it in Linux, not OS/2\! If you see this message in directory that is whole created by this driver, it is BUG - let me know about it.

<a id="rst-bugs-in-os-2"></a>

## Bugs in OS/2

When you have two (or more) lost directories pointing each to other, chkdsk locks up when repairing filesystem.

Sometimes (I think it's random) when you create a file with one-char name under OS/2, OS/2 marks it as 'long'. chkdsk then removes this flag saying "Minor fs error corrected".

File names like "a .b" are marked as 'long' by OS/2 but chkdsk "corrects" it and marks them as short (and writes "minor fs error corrected"). This bug is not in HPFS386.

<a id="rst-codepage-bugs-described-above"></a>

## Codepage bugs described above

If you don't install fixpacks, there are many, many more...

<a id="rst-history"></a>

## History


<table>
<tbody>
<tr>
<td>


0.90

</td>
<td>


First public release

</td>
</tr>
<tr>
<td>


0.91

</td>
<td>


Fixed bug that caused shooting to memory when write_inode was called on open inode (rarely happened)

</td>
</tr>
<tr>
<td>


0.92

</td>
<td>


Fixed a little memory leak in freeing directory inodes

</td>
</tr>
<tr>
<td>


0.93

</td>
<td>


Fixed bug that locked up the machine when there were too many filenames with first 15 characters same Fixed write_file to zero file when writing behind file end

</td>
</tr>
<tr>
<td>


0.94

</td>
<td>


Fixed a little memory leak when trying to delete busy file or directory

</td>
</tr>
<tr>
<td>


0.95

</td>
<td>


Fixed a bug that i_hpfs_parent_dir was not updated when moving files

</td>
</tr>
<tr>
<td>


1.90

</td>
<td>


First version for 2.1.1xx kernels

</td>
</tr>
<tr>
<td>


1.91

</td>
<td>


Fixed a bug that chk_sectors failed when sectors were at the end of disk Fixed a race-condition when write_inode is called while deleting file Fixed a bug that could possibly happen (with very low probability) when using 0xff in filenames.

Rewritten locking to avoid race-conditions

Mount option 'eas' now works

Fsync no longer returns error

Files beginning with '.' are marked hidden

Remount support added

Alloc is not so slow when filesystem becomes full

Atimes are no more updated because it slows down operation

Code cleanup (removed all commented debug prints)

</td>
</tr>
<tr>
<td>


1.92

</td>
<td>


Corrected a bug when sync was called just before closing file

</td>
</tr>
<tr>
<td>


1.93

</td>
<td>


Modified, so that it works with kernels &gt;= 2.1.131, I don't know if it works with previous versions

Fixed a possible problem with disks &gt; 64G (but I don't have one, so I can't test it)

Fixed a file overflow at 2G

Added new option 'timeshift'

Changed behaviour on HPFS386: It is now possible to operate on HPFS386 in read-only mode

Fixed a bug that slowed down alloc and prevented allocating 100% space (this bug was not destructive)

</td>
</tr>
<tr>
<td>


1.94

</td>
<td>


Added workaround for one bug in Linux

Fixed one buffer leak

Fixed some incompatibilities with large extended attributes (but it's still not 100% ok, I have no info on it and OS/2 doesn't want to create them)

Rewritten allocation

Fixed a bug with i_blocks (du sometimes didn't display correct values)

Directories have no longer archive attribute set (some programs don't like it)

Fixed a bug that it set badly one flag in large anode tree (it was not destructive)

</td>
</tr>
<tr>
<td>


1.95

</td>
<td>


Fixed one buffer leak, that could happen on corrupted filesystem

Fixed one bug in allocation in 1.94

</td>
</tr>
<tr>
<td>


1.96

</td>
<td>


Added workaround for one bug in OS/2 (HPFS locked up, HPFS386 reported error sometimes when opening directories in PMSHELL)

Fixed a possible bitmap race

Fixed possible problem on large disks

You can now delete open files

Fixed a nondestructive race in rename

</td>
</tr>
<tr>
<td>


1.97

</td>
<td>


Support for HPFS v3 (on large partitions)

ZFixed a bug that it didn't allow creation of files &gt; 128M (it should be 2G)

</td>
</tr>
<tr>
<td>


1.97.1

</td>
<td>


Changed names of global symbols

Fixed a bug when chmoding or chowning root directory

</td>
</tr>
<tr>
<td>


1.98

</td>
<td>


Fixed a deadlock when using old_readdir Better directory handling; workaround for "unbalanced tree" bug in OS/2

</td>
</tr>
<tr>
<td>


1.99

</td>
<td>


Corrected a possible problem when there's not enough space while deleting file

Now it tries to truncate the file if there's not enough space when deleting

Removed a lot of redundant code

</td>
</tr>
<tr>
<td>


2.00

</td>
<td>


Fixed a bug in rename (it was there since 1.96) Better anti-fragmentation strategy

</td>
</tr>
<tr>
<td>


2.01

</td>
<td>


Fixed problem with directory listing over NFS

Directory lseek now checks for proper parameters

Fixed race-condition in buffer code - it is in all filesystems in Linux; when reading device (cat /dev/hda) while creating files on it, files could be damaged

</td>
</tr>
<tr>
<td>


2.02

</td>
<td>


Workaround for bug in breada in Linux. breada could cause accesses beyond end of partition

</td>
</tr>
<tr>
<td>


2.03

</td>
<td>


Char, block devices and pipes are correctly created

Fixed non-crashing race in unlink (Alexander Viro)

Now it works with Japanese version of OS/2

</td>
</tr>
<tr>
<td>


2.04

</td>
<td>


Fixed error when ftruncate used to extend file

</td>
</tr>
<tr>
<td>


2.05

</td>
<td>


Fixed crash when got mount parameters without =

Fixed crash when allocation of anode failed due to full disk

Fixed some crashes when block io or inode allocation failed

</td>
</tr>
<tr>
<td>


2.06

</td>
<td>


Fixed some crash on corrupted disk structures

Better allocation strategy

Reschedule points added so that it doesn't lock CPU long time

It should work in read-only mode on Warp Server

</td>
</tr>
<tr>
<td>


2.07

</td>
<td>


More fixes for Warp Server. Now it really works

</td>
</tr>
<tr>
<td>


2.08

</td>
<td>


Creating new files is not so slow on large disks

An attempt to sync deleted file does not generate filesystem error

</td>
</tr>
<tr>
<td>


2.09

</td>
<td>


Fixed error on extremely fragmented files

</td>
</tr>
</tbody>
</table>

---

# Idmappings

_Peios Kernel / Internals / Filesystems_

> Most filesystem developers will have encountered idmappings. They are used when reading from or writing ownership to disk, reporting ownership to userspace, or for permission checking. This document is aimed at filesystem developers that…

> **Peios:** Idmapped mounts translate Unix ownership metadata. They do not remap native token identities or security-descriptor principals, and creating a user namespace does not grant native privileges. Treat the Unix ownership examples below as metadata examples; KACS file and mount checks still apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-idmappings"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Most filesystem developers will have encountered idmappings. They are used when reading from or writing ownership to disk, reporting ownership to userspace, or for permission checking. This document is aimed at filesystem developers that want to know how idmappings work.

<a id="rst-formal-notes"></a>

## Formal notes

An idmapping is essentially a translation of a range of ids into another or the same range of ids. The notational convention for idmappings that is widely used in userspace is:



```text
u:k:r
```

`u` indicates the first element in the upper idmapset `U` and `k` indicates the first element in the lower idmapset `K`. The `r` parameter indicates the range of the idmapping, i.e. how many ids are mapped. From now on, we will always prefix ids with `u` or `k` to make it clear whether we're talking about an id in the upper or lower idmapset.

To see what this looks like in practice, let's take the following idmapping:



```text
u22:k10000:r3
```

and write down the mappings it will generate:



```text
u22 -> k10000
u23 -> k10001
u24 -> k10002
```

From a mathematical viewpoint `U` and `K` are well-ordered sets and an idmapping is an order isomorphism from `U` into `K`. So `U` and `K` are order isomorphic. In fact, `U` and `K` are always well-ordered subsets of the set of all possible ids usable on a given system.

Looking at this mathematically briefly will help us highlight some properties that make it easier to understand how we can translate between idmappings. For example, we know that the inverse idmapping is an order isomorphism as well:



```text
k10000 -> u22
k10001 -> u23
k10002 -> u24
```

Given that we are dealing with order isomorphisms plus the fact that we're dealing with subsets we can embed idmappings into each other, i.e. we can sensibly translate between different idmappings. For example, assume we've been given the three idmappings:



```text
1. u0:k10000:r10000
2. u0:k20000:r10000
3. u0:k30000:r10000
```

and id `k11000` which has been generated by the first idmapping by mapping `u1000` from the upper idmapset down to `k11000` in the lower idmapset.

Because we're dealing with order isomorphic subsets it is meaningful to ask what id `k11000` corresponds to in the second or third idmapping. The straightforward algorithm to use is to apply the inverse of the first idmapping, mapping `k11000` up to `u1000`. Afterwards, we can map `u1000` down using either the second idmapping mapping or third idmapping mapping. The second idmapping would map `u1000` down to `k21000`. The third idmapping would map `u1000` down to `k31000`.

If we were given the same task for the following three idmappings:



```text
1. u0:k10000:r10000
2. u0:k20000:r200
3. u0:k30000:r300
```

we would fail to translate as the sets aren't order isomorphic over the full range of the first idmapping anymore (However they are order isomorphic over the full range of the second idmapping.). Neither the second or third idmapping contain `u1000` in the upper idmapset `U`. This is equivalent to not having an id mapped. We can simply say that `u1000` is unmapped in the second and third idmapping. The kernel will report unmapped ids as the overflowuid `(uid_t)-1` or overflowgid `(gid_t)-1` to userspace.

The algorithm to calculate what a given id maps to is pretty simple. First, we need to verify that the range can contain our target id. We will skip this step for simplicity. After that if we want to know what `id` maps to we can do simple calculations:

- If we want to map from left to right:



  ```text
  u:k:r
  id - u + k = n
  ```

- If we want to map from right to left:



  ```text
  u:k:r
  id - k + u = n
  ```

Instead of "left to right" we can also say "down" and instead of "right to left" we can also say "up". Obviously mapping down and up invert each other.

To see whether the simple formulas above work, consider the following two idmappings:



```text
1. u0:k20000:r10000
2. u500:k30000:r10000
```

Assume we are given `k21000` in the lower idmapset of the first idmapping. We want to know what id this was mapped from in the upper idmapset of the first idmapping. So we're mapping up in the first idmapping:



```text
id     - k      + u  = n
k21000 - k20000 + u0 = u1000
```

Now assume we are given the id `u1100` in the upper idmapset of the second idmapping and we want to know what this id maps down to in the lower idmapset of the second idmapping. This means we're mapping down in the second idmapping:



```text
id    - u    + k      = n
u1100 - u500 + k30000 = k30600
```

<a id="rst-general-notes"></a>

## General notes

In the context of the kernel an idmapping can be interpreted as mapping a range of userspace ids into a range of kernel ids:



```text
userspace-id:kernel-id:range
```

A userspace id is always an element in the upper idmapset of an idmapping of type `uid_t` or `gid_t` and a kernel id is always an element in the lower idmapset of an idmapping of type `kuid_t` or `kgid_t`. From now on "userspace id" will be used to refer to the well known `uid_t` and `gid_t` types and "kernel id" will be used to refer to `kuid_t` and `kgid_t`.

The kernel is mostly concerned with kernel ids. They are used when performing permission checks and are stored in an inode's `i_uid` and `i_gid` field. A userspace id on the other hand is an id that is reported to userspace by the kernel, or is passed by userspace to the kernel, or a raw device id that is written or read from disk.

Note that we are only concerned with idmappings as the kernel stores them not how userspace would specify them.

For the rest of this document we will prefix all userspace ids with `u` and all kernel ids with `k`. Ranges of idmappings will be prefixed with `r`. So an idmapping will be written as `u0:k10000:r10000`.

For example, within this idmapping, the id `u1000` is an id in the upper idmapset or "userspace idmapset" starting with `u0`. And it is mapped to `k11000` which is a kernel id in the lower idmapset or "kernel idmapset" starting with `k10000`.

A kernel id is always created by an idmapping. Such idmappings are associated with user namespaces. Since we mainly care about how idmappings work we're not going to be concerned with how idmappings are created nor how they are used outside of the filesystem context. This is best left to an explanation of user namespaces.

The initial user namespace is special. It always has an idmapping of the following form:



```text
u0:k0:r4294967295
```

which is an identity idmapping over the full range of ids available on this system.

Other user namespaces usually have non-identity idmappings such as:



```text
u0:k10000:r10000
```

When a process creates or wants to change ownership of a file, or when the ownership of a file is read from disk by a filesystem, the userspace id is immediately translated into a kernel id according to the idmapping associated with the relevant user namespace.

For instance, consider a file that is stored on disk by a filesystem as being owned by `u1000`:

- If a filesystem were to be mounted in the initial user namespaces (as most filesystems are) then the initial idmapping will be used. As we saw this is simply the identity idmapping. This would mean id `u1000` read from disk would be mapped to id `k1000`. So an inode's `i_uid` and `i_gid` field would contain `k1000`.

- If a filesystem were to be mounted with an idmapping of `u0:k10000:r10000` then `u1000` read from disk would be mapped to `k11000`. So an inode's `i_uid` and `i_gid` would contain `k11000`.

<a id="rst-translation-algorithms"></a>

## Translation algorithms

We've already seen briefly that it is possible to translate between different idmappings. We'll now take a closer look how that works.

<a id="rst-crossmapping"></a>

### Crossmapping

This translation algorithm is used by the kernel in quite a few places. For example, it is used when reporting back the ownership of a file to userspace via the `stat()` system call family.

If we've been given `k11000` from one idmapping we can map that id up in another idmapping. In order for this to work both idmappings need to contain the same kernel id in their kernel idmapsets. For example, consider the following idmappings:



```text
1. u0:k10000:r10000
2. u20000:k10000:r10000
```

and we are mapping `u1000` down to `k11000` in the first idmapping . We can then translate `k11000` into a userspace id in the second idmapping using the kernel idmapset of the second idmapping:



```text
/* Map the kernel id up into a userspace id in the second idmapping. */
from_kuid(u20000:k10000:r10000, k11000) = u21000
```

Note, how we can get back to the kernel id in the first idmapping by inverting the algorithm:



```text
/* Map the userspace id down into a kernel id in the second idmapping. */
make_kuid(u20000:k10000:r10000, u21000) = k11000

/* Map the kernel id up into a userspace id in the first idmapping. */
from_kuid(u0:k10000:r10000, k11000) = u1000
```

This algorithm allows us to answer the question what userspace id a given kernel id corresponds to in a given idmapping. In order to be able to answer this question both idmappings need to contain the same kernel id in their respective kernel idmapsets.

For example, when the kernel reads a raw userspace id from disk it maps it down into a kernel id according to the idmapping associated with the filesystem. Let's assume the filesystem was mounted with an idmapping of `u0:k20000:r10000` and it reads a file owned by `u1000` from disk. This means `u1000` will be mapped to `k21000` which is what will be stored in the inode's `i_uid` and `i_gid` field.

When someone in userspace calls `stat()` or a related function to get ownership information about the file the kernel can't simply map the id back up according to the filesystem's idmapping as this would give the wrong owner if the caller is using an idmapping.

So the kernel will map the id back up in the idmapping of the caller. Let's assume the caller has the somewhat unconventional idmapping `u3000:k20000:r10000` then `k21000` would map back up to `u4000`. Consequently the user would see that this file is owned by `u4000`.

<a id="rst-remapping"></a>

### Remapping

It is possible to translate a kernel id from one idmapping to another one via the userspace idmapset of the two idmappings. This is equivalent to remapping a kernel id.

Let's look at an example. We are given the following two idmappings:



```text
1. u0:k10000:r10000
2. u0:k20000:r10000
```

and we are given `k11000` in the first idmapping. In order to translate this kernel id in the first idmapping into a kernel id in the second idmapping we need to perform two steps:

1. Map the kernel id up into a userspace id in the first idmapping:



   ```text
   /* Map the kernel id up into a userspace id in the first idmapping. */
   from_kuid(u0:k10000:r10000, k11000) = u1000
   ```

2. Map the userspace id down into a kernel id in the second idmapping:



   ```text
   /* Map the userspace id down into a kernel id in the second idmapping. */
   make_kuid(u0:k20000:r10000, u1000) = k21000
   ```

As you can see we used the userspace idmapset in both idmappings to translate the kernel id in one idmapping to a kernel id in another idmapping.

This allows us to answer the question what kernel id we would need to use to get the same userspace id in another idmapping. In order to be able to answer this question both idmappings need to contain the same userspace id in their respective userspace idmapsets.

Note, how we can easily get back to the kernel id in the first idmapping by inverting the algorithm:

1. Map the kernel id up into a userspace id in the second idmapping:



   ```text
   /* Map the kernel id up into a userspace id in the second idmapping. */
   from_kuid(u0:k20000:r10000, k21000) = u1000
   ```

2. Map the userspace id down into a kernel id in the first idmapping:



   ```text
   /* Map the userspace id down into a kernel id in the first idmapping. */
   make_kuid(u0:k10000:r10000, u1000) = k11000
   ```

Another way to look at this translation is to treat it as inverting one idmapping and applying another idmapping if both idmappings have the relevant userspace id mapped. This will come in handy when working with idmapped mounts.

<a id="rst-invalid-translations"></a>

### Invalid translations

It is never valid to use an id in the kernel idmapset of one idmapping as the id in the userspace idmapset of another or the same idmapping. While the kernel idmapset always indicates an idmapset in the kernel id space the userspace idmapset indicates a userspace id. So the following translations are forbidden:



```text
/* Map the userspace id down into a kernel id in the first idmapping. */
make_kuid(u0:k10000:r10000, u1000) = k11000

/* INVALID: Map the kernel id down into a kernel id in the second idmapping. */
make_kuid(u10000:k20000:r10000, k110000) = k21000
                                ~~~~~~~
```

and equally wrong:



```text
/* Map the kernel id up into a userspace id in the first idmapping. */
from_kuid(u0:k10000:r10000, k11000) = u1000

/* INVALID: Map the userspace id up into a userspace id in the second idmapping. */
from_kuid(u20000:k0:r10000, u1000) = k21000
                            ~~~~~
```

Since userspace ids have type `uid_t` and `gid_t` and kernel ids have type `kuid_t` and `kgid_t` the compiler will throw an error when they are conflated. So the two examples above would cause a compilation failure.

<a id="rst-idmappings-when-creating-filesystem-objects"></a>

## Idmappings when creating filesystem objects

The concepts of mapping an id down or mapping an id up are expressed in the two kernel functions filesystem developers are rather familiar with and which we've already used in this document:



```text
/* Map the userspace id down into a kernel id. */
make_kuid(idmapping, uid)

/* Map the kernel id up into a userspace id. */
from_kuid(idmapping, kuid)
```

We will take an abbreviated look into how idmappings figure into creating filesystem objects. For simplicity we will only look at what happens when the VFS has already completed path lookup right before it calls into the filesystem itself. So we're concerned with what happens when e.g. `vfs_mkdir()` is called. We will also assume that the directory we're creating filesystem objects in is readable and writable for everyone.

When creating a filesystem object the caller will look at the caller's filesystem ids. These are just regular `uid_t` and `gid_t` userspace ids but they are exclusively used when determining file ownership which is why they are called "filesystem ids". They are usually identical to the uid and gid of the caller but can differ. We will just assume they are always identical to not get lost in too many details.

When the caller enters the kernel two things happen:

1. Map the caller's userspace ids down into kernel ids in the caller's idmapping. (To be precise, the kernel will simply look at the kernel ids stashed in the credentials of the current task but for our education we'll pretend this translation happens just in time.)

2. Verify that the caller's kernel ids can be mapped up to userspace ids in the filesystem's idmapping.

The second step is important as regular filesystem will ultimately need to map the kernel id back up into a userspace id when writing to disk. So with the second step the kernel guarantees that a valid userspace id can be written to disk. If it can't the kernel will refuse the creation request to not even remotely risk filesystem corruption.

The astute reader will have realized that this is simply a variation of the crossmapping algorithm we mentioned above in a previous section. First, the kernel maps the caller's userspace id down into a kernel id according to the caller's idmapping and then maps that kernel id up according to the filesystem's idmapping.

From the implementation point it's worth mentioning how idmappings are represented. All idmappings are taken from the corresponding user namespace.

> - caller's idmapping (usually taken from `current_user_ns()`)
>
> - filesystem's idmapping (`sb->s_user_ns`)
>
> - mount's idmapping (`mnt_idmap(vfsmnt)`)

Let's see some examples with caller/filesystem idmapping but without mount idmappings. This will exhibit some problems we can hit. After that we will revisit/reconsider these examples, this time using mount idmappings, to see how they can solve the problems we observed before.

<a id="rst-example-1"></a>

### Example 1



```text
caller id:            u1000
caller idmapping:     u0:k0:r4294967295
filesystem idmapping: u0:k0:r4294967295
```

Both the caller and the filesystem use the identity idmapping:

1. Map the caller's userspace ids into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

2. Verify that the caller's kernel ids can be mapped to userspace ids in the filesystem's idmapping.

   For this second step the kernel will call the function `fsuidgid_has_mapping()` which ultimately boils down to calling `from_kuid()`:



   ```text
   from_kuid(u0:k0:r4294967295, k1000) = u1000
   ```

In this example both idmappings are the same so there's nothing exciting going on. Ultimately the userspace id that lands on disk will be `u1000`.

<a id="rst-example-2"></a>

### Example 2



```text
caller id:            u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k20000:r10000
```

1. Map the caller's userspace ids down into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k10000:r10000, u1000) = k11000
   ```

2. Verify that the caller's kernel ids can be mapped up to userspace ids in the filesystem's idmapping:



   ```text
   from_kuid(u0:k20000:r10000, k11000) = u-1
   ```

It's immediately clear that while the caller's userspace id could be successfully mapped down into kernel ids in the caller's idmapping the kernel ids could not be mapped up according to the filesystem's idmapping. So the kernel will deny this creation request.

Note that while this example is less common, because most filesystem can't be mounted with non-initial idmappings this is a general problem as we can see in the next examples.

<a id="rst-example-3"></a>

### Example 3



```text
caller id:            u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k0:r4294967295
```

1. Map the caller's userspace ids down into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k10000:r10000, u1000) = k11000
   ```

2. Verify that the caller's kernel ids can be mapped up to userspace ids in the filesystem's idmapping:



   ```text
   from_kuid(u0:k0:r4294967295, k11000) = u11000
   ```

We can see that the translation always succeeds. The userspace id that the filesystem will ultimately put to disk will always be identical to the value of the kernel id that was created in the caller's idmapping. This has mainly two consequences.

First, that we can't allow a caller to ultimately write to disk with another userspace id. We could only do this if we were to mount the whole filesystem with the caller's or another idmapping. But that solution is limited to a few filesystems and not very flexible. But this is a use-case that is pretty important in containerized workloads.

Second, the caller will usually not be able to create any files or access directories that have stricter permissions because none of the filesystem's kernel ids map up into valid userspace ids in the caller's idmapping

1. Map raw userspace ids down to kernel ids in the filesystem's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

2. Map kernel ids up to userspace ids in the caller's idmapping:



   ```text
   from_kuid(u0:k10000:r10000, k1000) = u-1
   ```

<a id="rst-example-4"></a>

### Example 4



```text
file id:              u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k0:r4294967295
```

In order to report ownership to userspace the kernel uses the crossmapping algorithm introduced in a previous section:

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

2. Map the kernel id up into a userspace id in the caller's idmapping:



   ```text
   from_kuid(u0:k10000:r10000, k1000) = u-1
   ```

The crossmapping algorithm fails in this case because the kernel id in the filesystem idmapping cannot be mapped up to a userspace id in the caller's idmapping. Thus, the kernel will report the ownership of this file as the overflowid.

<a id="rst-example-5"></a>

### Example 5



```text
file id:              u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k20000:r10000
```

In order to report ownership to userspace the kernel uses the crossmapping algorithm introduced in a previous section:

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k20000:r10000, u1000) = k21000
   ```

2. Map the kernel id up into a userspace id in the caller's idmapping:



   ```text
   from_kuid(u0:k10000:r10000, k21000) = u-1
   ```

Again, the crossmapping algorithm fails in this case because the kernel id in the filesystem idmapping cannot be mapped to a userspace id in the caller's idmapping. Thus, the kernel will report the ownership of this file as the overflowid.

Note how in the last two examples things would be simple if the caller would be using the initial idmapping. For a filesystem mounted with the initial idmapping it would be trivial. So we only consider a filesystem with an idmapping of `u0:k20000:r10000`:

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k20000:r10000, u1000) = k21000
   ```

2. Map the kernel id up into a userspace id in the caller's idmapping:



   ```text
   from_kuid(u0:k0:r4294967295, k21000) = u21000
   ```

<a id="rst-idmappings-on-idmapped-mounts"></a>

## Idmappings on idmapped mounts

The examples we've seen in the previous section where the caller's idmapping and the filesystem's idmapping are incompatible causes various issues for workloads. For a more complex but common example, consider two containers started on the host. To completely prevent the two containers from affecting each other, an administrator may often use different non-overlapping idmappings for the two containers:



```text
container1 idmapping:  u0:k10000:r10000
container2 idmapping:  u0:k20000:r10000
filesystem idmapping:  u0:k30000:r10000
```

An administrator wanting to provide easy read-write access to the following set of files:



```text
dir id:       u0
dir/file1 id: u1000
dir/file2 id: u2000
```

to both containers currently can't.

Of course the administrator has the option to recursively change ownership via `chown()`. For example, they could change ownership so that `dir` and all files below it can be crossmapped from the filesystem's into the container's idmapping. Let's assume they change ownership so it is compatible with the first container's idmapping:



```text
dir id:       u10000
dir/file1 id: u11000
dir/file2 id: u12000
```

This would still leave `dir` rather useless to the second container. In fact, `dir` and all files below it would continue to appear owned by the overflowid for the second container.

Or consider another increasingly popular example. Some service managers such as systemd implement a concept called "portable home directories". A user may want to use their home directories on different machines where they are assigned different login userspace ids. Most users will have `u1000` as the login id on their machine at home and all files in their home directory will usually be owned by `u1000`. At uni or at work they may have another login id such as `u1125`. This makes it rather difficult to interact with their home directory on their work machine.

In both cases changing ownership recursively has grave implications. The most obvious one is that ownership is changed globally and permanently. In the home directory case this change in ownership would even need to happen every time the user switches from their home to their work machine. For really large sets of files this becomes increasingly costly.

If the user is lucky, they are dealing with a filesystem that is mountable inside user namespaces. But this would also change ownership globally and the change in ownership is tied to the lifetime of the filesystem mount, i.e. the superblock. The only way to change ownership is to completely unmount the filesystem and mount it again in another user namespace. This is usually impossible because it would mean that all users currently accessing the filesystem can't anymore. And it means that `dir` still can't be shared between two containers with different idmappings. But usually the user doesn't even have this option since most filesystems aren't mountable inside containers. And not having them mountable might be desirable as it doesn't require the filesystem to deal with malicious filesystem images.

But the usecases mentioned above and more can be handled by idmapped mounts. They allow to expose the same set of dentries with different ownership at different mounts. This is achieved by marking the mounts with a user namespace through the `mount_setattr()` system call. The idmapping associated with it is then used to translate from the caller's idmapping to the filesystem's idmapping and vica versa using the remapping algorithm we introduced above.

Idmapped mounts make it possible to change ownership in a temporary and localized way. The ownership changes are restricted to a specific mount and the ownership changes are tied to the lifetime of the mount. All other users and locations where the filesystem is exposed are unaffected.

Filesystems that support idmapped mounts don't have any real reason to support being mountable inside user namespaces. A filesystem could be exposed completely under an idmapped mount to get the same effect. This has the advantage that filesystems can leave the creation of the superblock to privileged users in the initial user namespace.

However, it is perfectly possible to combine idmapped mounts with filesystems mountable inside user namespaces. We will touch on this further below.

<a id="rst-filesystem-types-vs-idmapped-mount-types"></a>

### Filesystem types vs idmapped mount types

With the introduction of idmapped mounts we need to distinguish between filesystem ownership and mount ownership of a VFS object such as an inode. The owner of a inode might be different when looked at from a filesystem perspective than when looked at from an idmapped mount. Such fundamental conceptual distinctions should almost always be clearly expressed in the code. So, to distinguish idmapped mount ownership from filesystem ownership separate types have been introduced.

If a uid or gid has been generated using the filesystem or caller's idmapping then we will use the `kuid_t` and `kgid_t` types. However, if a uid or gid has been generated using a mount idmapping then we will be using the dedicated `vfsuid_t` and `vfsgid_t` types.

All VFS helpers that generate or take uids and gids as arguments use the `vfsuid_t` and `vfsgid_t` types and we will be able to rely on the compiler to catch errors that originate from conflating filesystem and VFS uids and gids.

The `vfsuid_t` and `vfsgid_t` types are often mapped from and to `kuid_t` and `kgid_t` types similar how `kuid_t` and `kgid_t` types are mapped from and to `uid_t` and `gid_t` types:



```text
uid_t <--> kuid_t <--> vfsuid_t
gid_t <--> kgid_t <--> vfsgid_t
```

Whenever we report ownership based on a `vfsuid_t` or `vfsgid_t` type, e.g., during `stat()`, or store ownership information in a shared VFS object based on a `vfsuid_t` or `vfsgid_t` type, e.g., during `chown()` we can use the `vfsuid_into_kuid()` and `vfsgid_into_kgid()` helpers.

To illustrate why this helper currently exists, consider what happens when we change ownership of an inode from an idmapped mount. After we generated a `vfsuid_t` or `vfsgid_t` based on the mount idmapping we later commit to this `vfsuid_t` or `vfsgid_t` to become the new filesystem wide ownership. Thus, we are turning the `vfsuid_t` or `vfsgid_t` into a global `kuid_t` or `kgid_t`. And this can be done by using `vfsuid_into_kuid()` and `vfsgid_into_kgid()`.

Note, whenever a shared VFS object, e.g., a cached `struct inode` or a cached `struct posix_acl`, stores ownership information a filesystem or "global" `kuid_t` and `kgid_t` must be used. Ownership expressed via `vfsuid_t` and `vfsgid_t` is specific to an idmapped mount.

We already noted that `vfsuid_t` and `vfsgid_t` types are generated based on mount idmappings whereas `kuid_t` and `kgid_t` types are generated based on filesystem idmappings. To prevent abusing filesystem idmappings to generate `vfsuid_t` or `vfsgid_t` types or mount idmappings to generate `kuid_t` or `kgid_t` types filesystem idmappings and mount idmappings are different types as well.

All helpers that map to or from `vfsuid_t` and `vfsgid_t` types require a mount idmapping to be passed which is of type `struct mnt_idmap`. Passing a filesystem or caller idmapping will cause a compilation error.

Similar to how we prefix all userspace ids in this document with `u` and all kernel ids with `k` we will prefix all VFS ids with `v`. So a mount idmapping will be written as: `u0:v10000:r10000`.

<a id="rst-remapping-helpers"></a>

### Remapping helpers

Idmapping functions were added that translate between idmappings. They make use of the remapping algorithm we've introduced earlier. We're going to look at:

- `i_uid_into_vfsuid()` and `i_gid_into_vfsgid()`

  The `i_*id_into_vfs*id()` functions translate filesystem's kernel ids into VFS ids in the mount's idmapping:



  ```text
  /* Map the filesystem's kernel id up into a userspace id in the filesystem's idmapping. */
  from_kuid(filesystem, kid) = uid

  /* Map the filesystem's userspace id down ito a VFS id in the mount's idmapping. */
  make_kuid(mount, uid) = kuid
  ```

- `mapped_fsuid()` and `mapped_fsgid()`

  The `mapped_fs*id()` functions translate the caller's kernel ids into kernel ids in the filesystem's idmapping. This translation is achieved by remapping the caller's VFS ids using the mount's idmapping:



  ```text
  /* Map the caller's VFS id up into a userspace id in the mount's idmapping. */
  from_kuid(mount, kid) = uid

  /* Map the mount's userspace id down into a kernel id in the filesystem's idmapping. */
  make_kuid(filesystem, uid) = kuid
  ```

- `vfsuid_into_kuid()` and `vfsgid_into_kgid()`

  > Whenever

Note that these two functions invert each other. Consider the following idmappings:



```text
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k20000:r10000
mount idmapping:      u0:v10000:r10000
```

Assume a file owned by `u1000` is read from disk. The filesystem maps this id to `k21000` according to its idmapping. This is what is stored in the inode's `i_uid` and `i_gid` fields.

When the caller queries the ownership of this file via `stat()` the kernel would usually simply use the crossmapping algorithm and map the filesystem's kernel id up to a userspace id in the caller's idmapping.

But when the caller is accessing the file on an idmapped mount the kernel will first call `i_uid_into_vfsuid()` thereby translating the filesystem's kernel id into a VFS id in the mount's idmapping:



```text
i_uid_into_vfsuid(k21000):
  /* Map the filesystem's kernel id up into a userspace id. */
  from_kuid(u0:k20000:r10000, k21000) = u1000

  /* Map the filesystem's userspace id down into a VFS id in the mount's idmapping. */
  make_kuid(u0:v10000:r10000, u1000) = v11000
```

Finally, when the kernel reports the owner to the caller it will turn the VFS id in the mount's idmapping into a userspace id in the caller's idmapping:



```text
k11000 = vfsuid_into_kuid(v11000)
from_kuid(u0:k10000:r10000, k11000) = u1000
```

We can test whether this algorithm really works by verifying what happens when we create a new file. Let's say the user is creating a file with `u1000`.

The kernel maps this to `k11000` in the caller's idmapping. Usually the kernel would now apply the crossmapping, verifying that `k11000` can be mapped to a userspace id in the filesystem's idmapping. Since `k11000` can't be mapped up in the filesystem's idmapping directly this creation request fails.

But when the caller is accessing the file on an idmapped mount the kernel will first call `mapped_fs*id()` thereby translating the caller's kernel id into a VFS id according to the mount's idmapping:



```text
mapped_fsuid(k11000):
   /* Map the caller's kernel id up into a userspace id in the mount's idmapping. */
   from_kuid(u0:k10000:r10000, k11000) = u1000

   /* Map the mount's userspace id down into a kernel id in the filesystem's idmapping. */
   make_kuid(u0:v20000:r10000, u1000) = v21000
```

When finally writing to disk the kernel will then map `v21000` up into a userspace id in the filesystem's idmapping:



```text
k21000 = vfsuid_into_kuid(v21000)
from_kuid(u0:k20000:r10000, k21000) = u1000
```

As we can see, we end up with an invertible and therefore information preserving algorithm. A file created from `u1000` on an idmapped mount will also be reported as being owned by `u1000` and vica versa.

Let's now briefly reconsider the failing examples from earlier in the context of idmapped mounts.

<a id="rst-example-2-reconsidered"></a>

### Example 2 reconsidered



```text
caller id:            u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k20000:r10000
mount idmapping:      u0:v10000:r10000
```

When the caller is using a non-initial idmapping the common case is to attach the same idmapping to the mount. We now perform three steps:

1. Map the caller's userspace ids into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k10000:r10000, u1000) = k11000
   ```

2. Translate the caller's VFS id into a kernel id in the filesystem's idmapping:



   ```text
   mapped_fsuid(v11000):
     /* Map the VFS id up into a userspace id in the mount's idmapping. */
     from_kuid(u0:v10000:r10000, v11000) = u1000

     /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
     make_kuid(u0:k20000:r10000, u1000) = k21000
   ```

3. Verify that the caller's kernel ids can be mapped to userspace ids in the filesystem's idmapping:



   ```text
   from_kuid(u0:k20000:r10000, k21000) = u1000
   ```

So the ownership that lands on disk will be `u1000`.

<a id="rst-example-3-reconsidered"></a>

### Example 3 reconsidered



```text
caller id:            u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k0:r4294967295
mount idmapping:      u0:v10000:r10000
```

The same translation algorithm works with the third example.

1. Map the caller's userspace ids into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k10000:r10000, u1000) = k11000
   ```

2. Translate the caller's VFS id into a kernel id in the filesystem's idmapping:



   ```text
   mapped_fsuid(v11000):
      /* Map the VFS id up into a userspace id in the mount's idmapping. */
      from_kuid(u0:v10000:r10000, v11000) = u1000

      /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
      make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

3. Verify that the caller's kernel ids can be mapped to userspace ids in the filesystem's idmapping:



   ```text
   from_kuid(u0:k0:r4294967295, k1000) = u1000
   ```

So the ownership that lands on disk will be `u1000`.

<a id="rst-example-4-reconsidered"></a>

### Example 4 reconsidered



```text
file id:              u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k0:r4294967295
mount idmapping:      u0:v10000:r10000
```

In order to report ownership to userspace the kernel now does three steps using the translation algorithm we introduced earlier:

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

2. Translate the kernel id into a VFS id in the mount's idmapping:



   ```text
   i_uid_into_vfsuid(k1000):
     /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
     from_kuid(u0:k0:r4294967295, k1000) = u1000

     /* Map the userspace id down into a VFS id in the mounts's idmapping. */
     make_kuid(u0:v10000:r10000, u1000) = v11000
   ```

3. Map the VFS id up into a userspace id in the caller's idmapping:



   ```text
   k11000 = vfsuid_into_kuid(v11000)
   from_kuid(u0:k10000:r10000, k11000) = u1000
   ```

Earlier, the caller's kernel id couldn't be crossmapped in the filesystems's idmapping. With the idmapped mount in place it now can be crossmapped into the filesystem's idmapping via the mount's idmapping. The file will now be created with `u1000` according to the mount's idmapping.

<a id="rst-example-5-reconsidered"></a>

### Example 5 reconsidered



```text
file id:              u1000
caller idmapping:     u0:k10000:r10000
filesystem idmapping: u0:k20000:r10000
mount idmapping:      u0:v10000:r10000
```

Again, in order to report ownership to userspace the kernel now does three steps using the translation algorithm we introduced earlier:

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k20000:r10000, u1000) = k21000
   ```

2. Translate the kernel id into a VFS id in the mount's idmapping:



   ```text
   i_uid_into_vfsuid(k21000):
     /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
     from_kuid(u0:k20000:r10000, k21000) = u1000

     /* Map the userspace id down into a VFS id in the mounts's idmapping. */
     make_kuid(u0:v10000:r10000, u1000) = v11000
   ```

3. Map the VFS id up into a userspace id in the caller's idmapping:



   ```text
   k11000 = vfsuid_into_kuid(v11000)
   from_kuid(u0:k10000:r10000, k11000) = u1000
   ```

Earlier, the file's kernel id couldn't be crossmapped in the filesystems's idmapping. With the idmapped mount in place it now can be crossmapped into the filesystem's idmapping via the mount's idmapping. The file is now owned by `u1000` according to the mount's idmapping.

<a id="rst-changing-ownership-on-a-home-directory"></a>

### Changing ownership on a home directory

We've seen above how idmapped mounts can be used to translate between idmappings when either the caller, the filesystem or both uses a non-initial idmapping. A wide range of usecases exist when the caller is using a non-initial idmapping. This mostly happens in the context of containerized workloads. The consequence is as we have seen that for both, filesystem's mounted with the initial idmapping and filesystems mounted with non-initial idmappings, access to the filesystem isn't working because the kernel ids can't be crossmapped between the caller's and the filesystem's idmapping.

As we've seen above idmapped mounts provide a solution to this by remapping the caller's or filesystem's idmapping according to the mount's idmapping.

Aside from containerized workloads, idmapped mounts have the advantage that they also work when both the caller and the filesystem use the initial idmapping which means users on the host can change the ownership of directories and files on a per-mount basis.

Consider our previous example where a user has their home directory on portable storage. At home they have id `u1000` and all files in their home directory are owned by `u1000` whereas at uni or work they have login id `u1125`.

Taking their home directory with them becomes problematic. They can't easily access their files, they might not be able to write to disk without applying lax permissions or ACLs and even if they can, they will end up with an annoying mix of files and directories owned by `u1000` and `u1125`.

Idmapped mounts allow to solve this problem. A user can create an idmapped mount for their home directory on their work computer or their computer at home depending on what ownership they would prefer to end up on the portable storage itself.

Let's assume they want all files on disk to belong to `u1000`. When the user plugs in their portable storage at their work station they can setup a job that creates an idmapped mount with the minimal idmapping `u1000:k1125:r1`. So now when they create a file the kernel performs the following steps we already know from above::



```text
caller id:            u1125
caller idmapping:     u0:k0:r4294967295
filesystem idmapping: u0:k0:r4294967295
mount idmapping:      u1000:v1125:r1
```

1. Map the caller's userspace ids into kernel ids in the caller's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1125) = k1125
   ```

2. Translate the caller's VFS id into a kernel id in the filesystem's idmapping:



   ```text
   mapped_fsuid(v1125):
     /* Map the VFS id up into a userspace id in the mount's idmapping. */
     from_kuid(u1000:v1125:r1, v1125) = u1000

     /* Map the userspace id down into a kernel id in the filesystem's idmapping. */
     make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

3. Verify that the caller's filesystem ids can be mapped to userspace ids in the filesystem's idmapping:



   ```text
   from_kuid(u0:k0:r4294967295, k1000) = u1000
   ```

So ultimately the file will be created with `u1000` on disk.

Now let's briefly look at what ownership the caller with id `u1125` will see on their work computer:



```text
file id:              u1000
caller idmapping:     u0:k0:r4294967295
filesystem idmapping: u0:k0:r4294967295
mount idmapping:      u1000:v1125:r1
```

1. Map the userspace id on disk down into a kernel id in the filesystem's idmapping:



   ```text
   make_kuid(u0:k0:r4294967295, u1000) = k1000
   ```

2. Translate the kernel id into a VFS id in the mount's idmapping:



   ```text
   i_uid_into_vfsuid(k1000):
     /* Map the kernel id up into a userspace id in the filesystem's idmapping. */
     from_kuid(u0:k0:r4294967295, k1000) = u1000

     /* Map the userspace id down into a VFS id in the mounts's idmapping. */
     make_kuid(u1000:v1125:r1, u1000) = v1125
   ```

3. Map the VFS id up into a userspace id in the caller's idmapping:



   ```text
   k1125 = vfsuid_into_kuid(v1125)
   from_kuid(u0:k0:r4294967295, k1125) = u1125
   ```

So ultimately the caller will be reported that the file belongs to `u1125` which is the caller's userspace id on their workstation in our example.

The raw userspace id that is put on disk is `u1000` so when the user takes their home directory back to their home computer where they are assigned `u1000` using the initial idmapping and mount the filesystem with the initial idmapping they will see all those files owned by `u1000`.

---

# Inotify - A Powerful yet Simple File Change Notification System

_Peios Kernel / Internals / Filesystems_

> Document started 15 Mar 2005 by Robert Love <rml@novell.com>

<a id="rst-inotify-a-powerful-yet-simple-file-change-notification-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Document started 15 Mar 2005 by Robert Love &lt;[rml@novell.com](<mailto:rml@novell.com>)&gt;

Document updated 4 Jan 2015 by Zhang Zhen &lt;[zhenzhang.zhang@huawei.com](<mailto:zhenzhang.zhang@huawei.com>)&gt;

> - Deleted obsoleted interface, just refer to manpages for user interface.

- **(i)** Rationale

- **Q:**

  What is the design decision behind not tying the watch to the open fd of the watched object?

- **A:**

  Watches are associated with an open inotify device, not an open file. This solves the primary problem with dnotify: keeping the file open pins the file and thus, worse, pins the mount.  Dnotify is therefore infeasible for use on a desktop system with removable media as the media cannot be unmounted.  Watching a file should not require that it be open.

- **Q:**

  What is the design decision behind using an-fd-per-instance as opposed to an fd-per-watch?

- **A:**

  An fd-per-watch quickly consumes more file descriptors than are allowed, more fd's than are feasible to manage, and more fd's than are optimally select()-able.  Yes, root can bump the per-process fd limit and yes, users can use epoll, but requiring both is a silly and extraneous requirement. A watch consumes less memory than an open file, separating the number spaces is thus sensible.  The current design is what user-space developers want: Users initialize inotify, once, and add n watches, requiring but one fd and no twiddling with fd limits.  Initializing an inotify instance two thousand times is silly.  If we can implement user-space's preferences cleanly--and we can, the idr layer makes stuff like this trivial--then we should.

  There are other good arguments.  With a single fd, there is a single item to block on, which is mapped to a single queue of events.  The single fd returns all watch events and also any potential out-of-band data.  If every fd was a separate watch,

  - There would be no way to get event ordering.  Events on file foo and file bar would pop poll() on both fd's, but there would be no way to tell which happened first.  A single queue trivially gives you ordering.  Such ordering is crucial to existing applications such as Beagle.  Imagine "mv a b ; mv b a" events without ordering.

  - We'd have to maintain n fd's and n internal queues with state, versus just one.  It is a lot messier in the kernel.  A single, linear queue is the data structure that makes sense.

  - User-space developers prefer the current API.  The Beagle guys, for example, love it.  Trust me, I asked.  It is not a surprise: Who'd want to manage and block on 1000 fd's via select?

  - No way to get out of band data.

  - 1024 is still too low.  ;-)

  When you talk about designing a file change notification system that scales to 1000s of directories, juggling 1000s of fd's just does not seem the right interface.  It is too heavy.

  Additionally, it \_is\_ possible to  more than one instance  and juggle more than one queue and thus more than one associated fd.  There need not be a one-fd-per-process mapping; it is one-fd-per-queue and a process can easily want more than one queue.

- **Q:**

  Why the system call approach?

- **A:**

  The poor user-space interface is the second biggest problem with dnotify. Signals are a terrible, terrible interface for file notification.  Or for anything, for that matter.  The ideal solution, from all perspectives, is a file descriptor-based one that allows basic file I/O and poll/select. Obtaining the fd and managing the watches could have been done either via a device file or a family of new system calls.  We decided to implement a family of system calls because that is the preferred approach for new kernel interfaces.  The only real difference was whether we wanted to use open(2) and ioctl(2) or a couple of new system calls.  System calls beat ioctls.

---

# ISO9660 Filesystem

_Peios Kernel / Internals / Filesystems_

> Mount options that are the same as for msdos and vfat partitions.

<a id="rst-iso9660-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Mount options that are the same as for msdos and vfat partitions.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> gid=nnn
>
> </td>
> <td>
>
>
> All files in the partition will be in group nnn.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> uid=nnn
>
> </td>
> <td>
>
>
> All files in the partition will be owned by user id nnn.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> umask=nnn
>
> </td>
> <td>
>
>
> The permission mask (see umask(1)) for the partition.
>
> </td>
> </tr>
> </tbody>
> </table>

Mount options that are the same as vfat partitions. These are only useful when using discs encoded using Microsoft's Joliet extensions.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> iocharset=name
>
> </td>
> <td>
>
>
> Character set to use for converting from Unicode to ASCII.  Joliet filenames are stored in Unicode format, but Unix for the most part doesn't know how to deal with Unicode. There is also an option of doing UTF-8 translations with the utf8 option.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> utf8
>
> </td>
> <td>
>
>
> Encode Unicode names in UTF-8 format. Default is no.
>
> </td>
> </tr>
> </tbody>
> </table>

Mount options unique to the isofs filesystem.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> block=512
>
> </td>
> <td>
>
>
> Set the block size for the disk to 512 bytes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> block=1024
>
> </td>
> <td>
>
>
> Set the block size for the disk to 1024 bytes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> block=2048
>
> </td>
> <td>
>
>
> Set the block size for the disk to 2048 bytes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> check=relaxed
>
> </td>
> <td>
>
>
> Matches filenames with different cases
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> check=strict
>
> </td>
> <td>
>
>
> Matches only filenames with the exact same case
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cruft
>
> </td>
> <td>
>
>
> Try to handle badly formatted CDs.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> map=off
>
> </td>
> <td>
>
>
> Do not map non-Rock Ridge filenames to lower case
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> map=normal
>
> </td>
> <td>
>
>
> Map non-Rock Ridge filenames to lower case
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> map=acorn
>
> </td>
> <td>
>
>
> As map=normal but also apply Acorn extensions if present
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mode=xxx
>
> </td>
> <td>
>
>
> Sets the permissions on files to xxx unless Rock Ridge extensions set the permissions otherwise
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dmode=xxx
>
> </td>
> <td>
>
>
> Sets the permissions on directories to xxx unless Rock Ridge extensions set the permissions otherwise
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> overriderockperm
>
> </td>
> <td>
>
>
> Set permissions on files and directories according to 'mode' and 'dmode' even though Rock Ridge extensions are present.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nojoliet
>
> </td>
> <td>
>
>
> Ignore Joliet extensions if they are present.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> norock
>
> </td>
> <td>
>
>
> Ignore Rock Ridge extensions if they are present.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> hide
>
> </td>
> <td>
>
>
> Completely strip hidden files from the file system.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> showassoc
>
> </td>
> <td>
>
>
> Show files marked with the 'associated' bit
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> unhide
>
> </td>
> <td>
>
>
> Deprecated; showing hidden files is now default; If given, it is a synonym for 'showassoc' which will recreate previous unhide behavior
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> session=x
>
> </td>
> <td>
>
>
> Select number of session on multisession CD
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sbsector=xxx
>
> </td>
> <td>
>
>
> Session begins from sector xxx
>
> </td>
> </tr>
> </tbody>
> </table>

Recommended documents about ISO 9660 standard are located at:

- [http://www.y-adagio.com/](<http://www.y-adagio.com/>)

- [ftp://ftp.ecma.ch/ecma-st/Ecma-119.pdf](<ftp://ftp.ecma.ch/ecma-st/Ecma-119.pdf>)

Quoting from the PDF "This 2nd Edition of Standard ECMA-119 is technically identical with ISO 9660.", so it is a valid and gratis substitute of the official ISO specification.

---

# The Linux Journalling API

_Peios Kernel / Internals / Filesystems_

> The journalling layer is easy to use. You need to first of all create a journal_t data structure. There are two calls to do this dependent on how you decide to allocate the physical media on which the journal resides. The…

<a id="rst-the-linux-journalling-api"></a>

<a id="rst-overview"></a>

## Overview

<a id="rst-details"></a>

### Details

The journalling layer is easy to use. You need to first of all create a journal_t data structure. There are two calls to do this dependent on how you decide to allocate the physical media on which the journal resides. The jbd2_journal_init_inode() call is for journals stored in filesystem inodes, or the jbd2_journal_init_dev() call can be used for journal stored on a raw device (in a continuous range of blocks). A journal_t is a typedef for a struct pointer, so when you are finally finished make sure you call jbd2_journal_destroy() on it to free up any used kernel memory.

Once you have got your journal_t object you need to 'mount' or load the journal file. The journalling layer expects the space for the journal was already allocated and initialized properly by the userspace tools. When loading the journal you must call jbd2_journal_load() to process journal contents. If the client file system detects the journal contents does not need to be processed (or even need not have valid contents), it may call jbd2_journal_wipe() to clear the journal contents before calling jbd2_journal_load().

Note that jbd2_journal_wipe(..,0) calls jbd2_journal_skip_recovery() for you if it detects any outstanding transactions in the journal and similarly jbd2_journal_load() will call jbd2_journal_recover() if necessary. I would advise reading ext4_load_journal() in fs/ext4/super.c for examples on this stage.

Now you can go ahead and start modifying the underlying filesystem. Almost.

You still need to actually journal your filesystem changes, this is done by wrapping them into transactions. Additionally you also need to wrap the modification of each of the buffers with calls to the journal layer, so it knows what the modifications you are actually making are. To do this use jbd2_journal_start() which returns a transaction handle.

jbd2_journal_start() and its counterpart jbd2_journal_stop(), which indicates the end of a transaction are nestable calls, so you can reenter a transaction if necessary, but remember you must call jbd2_journal_stop() the same number of times as jbd2_journal_start() before the transaction is completed (or more accurately leaves the update phase). Ext4/VFS makes use of this feature to simplify handling of inode dirtying, quota support, etc.

Inside each transaction you need to wrap the modifications to the individual buffers (blocks). Before you start to modify a buffer you need to call jbd2_journal_get_create_access() / jbd2_journal_get_write_access() / jbd2_journal_get_undo_access() as appropriate, this allows the journalling layer to copy the unmodified data if it needs to. After all the buffer may be part of a previously uncommitted transaction. At this point you are at last ready to modify a buffer, and once you are have done so you need to call jbd2_journal_dirty_metadata(). Or if you've asked for access to a buffer you now know is now longer required to be pushed back on the device you can call jbd2_journal_forget() in much the same way as you might have used bforget() in the past.

A jbd2_journal_flush() may be called at any time to commit and checkpoint all your transactions.

Then at umount time , in your put_super() you can then call jbd2_journal_destroy() to clean up your in-core journal object.

Unfortunately there a couple of ways the journal layer can cause a deadlock. The first thing to note is that each task can only have a single outstanding transaction at any one time, remember nothing commits until the outermost jbd2_journal_stop(). This means you must complete the transaction at the end of each file/inode/address etc. operation you perform, so that the journalling system isn't re-entered on another journal. Since transactions can't be nested/batched across differing journals, and another filesystem other than yours (say ext4) may be modified in a later syscall.

The second case to bear in mind is that jbd2_journal_start() can block if there isn't enough space in the journal for your transaction (based on the passed nblocks param) - when it blocks it merely(\!) needs to wait for transactions to complete and be committed from other tasks, so essentially we are waiting for jbd2_journal_stop(). So to avoid deadlocks you must treat jbd2_journal_start() / jbd2_journal_stop() as if they were semaphores and include them in your semaphore ordering rules to prevent deadlocks. Note that jbd2_journal_extend() has similar blocking behaviour to jbd2_journal_start() so you can deadlock here just as easily as on jbd2_journal_start().

Try to reserve the right number of blocks the first time. ;-). This will be the maximum number of blocks you are going to touch in this transaction. I advise having a look at at least ext4_jbd.h to see the basis on which ext4 uses to make these decisions.

Another wriggle to watch out for is your on-disk block allocation strategy. Why? Because, if you do a delete, you need to ensure you haven't reused any of the freed blocks until the transaction freeing these blocks commits. If you reused these blocks and crash happens, there is no way to restore the contents of the reallocated blocks at the end of the last fully committed transaction. One simple way of doing this is to mark blocks as free in internal in-memory block allocation structures only after the transaction freeing them commits. Ext4 uses journal commit callback for this purpose.

With journal commit callbacks you can ask the journalling layer to call a callback function when the transaction is finally committed to disk, so that you can do some of your own management. You ask the journalling layer for calling the callback by simply setting `journal->j_commit_callback` function pointer and that function is called after each transaction commit.

JBD2 also provides a way to block all transaction updates via jbd2_journal_lock_updates() / jbd2_journal_unlock_updates(). Ext4 uses this when it wants a window with a clean and stable fs for a moment. E.g.



```text
jbd2_journal_lock_updates() //stop new stuff happening..
jbd2_journal_flush()        // checkpoint everything.
..do stuff on stable fs
jbd2_journal_unlock_updates() // carry on with filesystem use.
```

The opportunities for abuse and DOS attacks with this should be obvious, if you allow unprivileged userspace to trigger codepaths containing these calls.

<a id="rst-fast-commits"></a>

### Fast commits

JBD2 to also allows you to perform file-system specific delta commits known as fast commits. In order to use fast commits, you will need to set following callbacks that perform corresponding work:

`journal->j_fc_cleanup_cb`: Cleanup function called after every full commit and fast commit.

`journal->j_fc_replay_cb`: Replay function called for replay of fast commit blocks.

File system is free to perform fast commits as and when it wants as long as it gets permission from JBD2 to do so by calling the function `jbd2_fc_begin_commit()`. Once a fast commit is done, the client file  system should tell JBD2 about it by calling `jbd2_fc_end_commit()`. If the file system wants JBD2 to perform a full commit immediately after stopping the fast commit it can do so by calling `jbd2_fc_end_commit_fallback()`. This is useful if fast commit operation fails for some reason and the only way to guarantee consistency is for JBD2 to perform the full traditional commit.

JBD2 helper functions to manage fast commit buffers. File system can use `jbd2_fc_get_buf()` and `jbd2_fc_wait_bufs()` to allocate and wait on IO completion of fast commit buffers.

Currently, only Ext4 implements fast commits. For details of its implementation of fast commits, please refer to the top level comments in fs/ext4/fast_commit.c.

<a id="rst-summary"></a>

### Summary

Using the journal is a matter of wrapping the different context changes, being each mount, each modification (transaction) and each changed buffer to tell the journalling layer about them.

<a id="rst-data-types"></a>

## Data Types

The journalling layer uses typedefs to 'hide' the concrete definitions of the structures used. As a client of the JBD2 layer you can just rely on the using the pointer as a magic cookie of some sort. Obviously the hiding is not enforced as this is 'C'.

<a id="rst-structures"></a>

### Structures


#### <a id="c-handle_t"></a>`typedef handle_t`

The handle_t type represents a single atomic update being performed by some process.

**Description**

All filesystem modifications made by the process go
through this handle.  Recursive operations (such as quota operations)
are gathered into a single update.

The buffer credits field is used to account for journaled buffers
being modified by the running process.  To ensure that there is
enough log space for all outstanding operations, we need to limit the
number of outstanding buffers possible at any time.  When the
operation completes, any buffer credits not used are credited back to
the transaction, so that at all times we know how many buffers the
outstanding updates on a transaction might possibly touch.

This is an opaque datatype.

#### <a id="c-journal_t"></a>`typedef journal_t`

The journal_t maintains all of the journaling state information for a single filesystem.

**Description**

journal_t is linked to from the fs superblock structure.

We use the journal_t to keep track of all outstanding transaction
activity on the filesystem, and to manage the state of the log
writing process.

This is an opaque datatype.

#### <a id="c-struct-jbd2_inode"></a>`struct jbd2_inode`

The jbd_inode type is the structure linking inodes in ordered mode present in a transaction so that we can sync them during commit.

**Definition**

```c
struct jbd2_inode {
    transaction_t *i_transaction;
    transaction_t *i_next_transaction;
    struct list_head i_list;
    struct inode *i_vfs_inode;
    unsigned long i_flags;
    loff_t i_dirty_start;
    loff_t i_dirty_end;
};
```

**Members**

- `i_transaction`: Which transaction does this inode belong to? Either the running
  transaction or the committing one. \[j_list_lock\]
- `i_next_transaction`: Pointer to the running transaction modifying inode's data in case
  there is already a committing transaction touching it. \[j_list_lock\]
- `i_list`: List of inodes in the i_transaction \[j_list_lock\]
- `i_vfs_inode`: VFS inode this inode belongs to \[constant for lifetime of structure\]
- `i_flags`: Flags of inode \[j_list_lock\]
- `i_dirty_start`: Offset in bytes where the dirty range for this inode starts.
  \[j_list_lock\]
- `i_dirty_end`: Inclusive offset in bytes where the dirty range for this inode
  ends. \[j_list_lock\]

#### <a id="c-struct-jbd2_journal_handle"></a>`struct jbd2_journal_handle`

The jbd2_journal_handle type is the concrete type associated with handle_t.

**Definition**

```c
struct jbd2_journal_handle {
    union {
        transaction_t *h_transaction;
        journal_t *h_journal;
    };
    handle_t *h_rsv_handle;
    int h_total_credits;
    int h_revoke_credits;
    int h_revoke_credits_requested;
    int h_ref;
    int h_err;
    unsigned int    h_sync:         1;
    unsigned int    h_reserved:     1;
    unsigned int    h_aborted:      1;
    unsigned int    h_type:         8;
    unsigned int    h_line_no:      16;
    unsigned long           h_start_jiffies;
    unsigned int            h_requested_credits;
    unsigned int            saved_alloc_context;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `h_transaction`: Which compound transaction is this update a part of?
- `h_journal`: Which journal handle belongs to - used iff h_reserved set.
- `h_rsv_handle`: Handle reserved for finishing the logical operation.
- `h_total_credits`: Number of remaining buffers we are allowed to add to
  journal. These are dirty buffers and revoke descriptor blocks.
- `h_revoke_credits`: Number of remaining revoke records available for handle
- `h_revoke_credits_requested`: Holds **h_revoke_credits** after handle is started.
- `h_ref`: Reference count on this handle.
- `h_err`: Field for caller's use to track errors through large fs operations.
- `h_sync`: Flag for sync-on-close.
- `h_reserved`: Flag for handle for reserved credits.
- `h_aborted`: Flag indicating fatal error on handle.
- `h_type`: For handle statistics.
- `h_line_no`: For handle statistics.
- `h_start_jiffies`: Handle Start time.
- `h_requested_credits`: Holds **h_total_credits** after handle is started.
- `saved_alloc_context`: Saved context while transaction is open.

#### <a id="c-struct-journal_s"></a>`struct journal_s`

The journal_s type is the concrete type associated with journal_t.

**Definition**

```c
struct journal_s {
        unsigned long           j_flags;
        int j_errno;
        struct mutex            j_abort_mutex;
        struct buffer_head      *j_sb_buffer;
        journal_superblock_t *j_superblock;
        rwlock_t j_state_lock;
        int j_barrier_count;
        struct mutex            j_barrier;
        transaction_t *j_running_transaction;
        transaction_t *j_committing_transaction;
        transaction_t *j_checkpoint_transactions;
        wait_queue_head_t j_wait_transaction_locked;
        wait_queue_head_t j_wait_done_commit;
        wait_queue_head_t j_wait_commit;
        wait_queue_head_t j_wait_updates;
        wait_queue_head_t j_wait_reserved;
        wait_queue_head_t j_fc_wait;
        struct mutex            j_checkpoint_mutex;
        struct buffer_head      *j_chkpt_bhs[JBD2_NR_BATCH];
        struct shrinker         *j_shrinker;
        struct percpu_counter   j_checkpoint_jh_count;
        transaction_t *j_shrink_transaction;
        unsigned long           j_head;
        unsigned long           j_tail;
        unsigned long           j_free;
        unsigned long           j_first;
        unsigned long           j_last;
        unsigned long           j_fc_first;
        unsigned long           j_fc_off;
        unsigned long           j_fc_last;
        struct block_device     *j_dev;
        int j_blocksize;
        unsigned long long      j_blk_offset;
        char j_devname[BDEVNAME_SIZE+24];
        struct block_device     *j_fs_dev;
        errseq_t j_fs_dev_wb_err;
        unsigned int            j_total_len;
        atomic_t j_reserved_credits;
        spinlock_t j_list_lock;
        struct inode            *j_inode;
        tid_t j_tail_sequence;
        tid_t j_transaction_sequence;
        tid_t j_commit_sequence;
        tid_t j_commit_request;
        __u8 j_uuid[16];
        struct task_struct      *j_task;
        int j_max_transaction_buffers;
        int j_revoke_records_per_block;
        int j_transaction_overhead_buffers;
        unsigned long           j_commit_interval;
        struct timer_list       j_commit_timer;
        spinlock_t j_revoke_lock;
        struct jbd2_revoke_table_s *j_revoke;
        struct jbd2_revoke_table_s *j_revoke_table[2];
        struct buffer_head      **j_wbuf;
        struct buffer_head      **j_fc_wbuf;
        int j_wbufsize;
        int j_fc_wbufsize;
        pid_t j_last_sync_writer;
        u64 j_average_commit_time;
        u32 j_min_batch_time;
        u32 j_max_batch_time;
        void (*j_commit_callback)(journal_t *, transaction_t *);
        int (*j_submit_inode_data_buffers) (struct jbd2_inode *);
        int (*j_finish_inode_data_buffers) (struct jbd2_inode *);
        spinlock_t j_history_lock;
        struct proc_dir_entry   *j_proc_entry;
        struct transaction_stats_s j_stats;
        unsigned int            j_failed_commit;
        void *j_private;
        __u32 j_csum_seed;
    #ifdef CONFIG_DEBUG_LOCK_ALLOC;
        struct lockdep_map      j_trans_commit_map;
    #endif;
        struct lock_class_key   jbd2_trans_commit_key;
        void (*j_fc_cleanup_callback)(struct journal_s *journal, int full, tid_t tid);
        int (*j_fc_replay_callback)(struct journal_s *journal, struct buffer_head *bh, enum passtype pass, int off, tid_t expected_commit_id);
        int (*j_bmap)(struct journal_s *journal, sector_t *block);
};
```

**Members**

- `j_flags`: General journaling state flags \[j_state_lock,
  no lock for quick racy checks\]
- `j_errno`: Is there an outstanding uncleared error on the journal (from a prior
  abort)? \[j_state_lock\]
- `j_abort_mutex`: Lock the whole aborting procedure.
- `j_sb_buffer`: The first part of the superblock buffer.
- `j_superblock`: The second part of the superblock buffer.
- `j_state_lock`: Protect the various scalars in the journal.
- `j_barrier_count`: Number of processes waiting to create a barrier lock \[j_state_lock,
  no lock for quick racy checks\]
- `j_barrier`: The barrier lock itself.
- `j_running_transaction`: Transactions: The current running transaction...
  \[j_state_lock, no lock for quick racy checks\] \[caller holding
  open handle\]
- `j_committing_transaction`: the transaction we are pushing to disk
  \[j_state_lock\] \[caller holding open handle\]
- `j_checkpoint_transactions`: ... and a linked circular list of all transactions waiting for
  checkpointing. \[j_list_lock\]
- `j_wait_transaction_locked`: Wait queue for waiting for a locked transaction to start committing,
  or for a barrier lock to be released.
- `j_wait_done_commit`: Wait queue for waiting for commit to complete.
- `j_wait_commit`: Wait queue to trigger commit.
- `j_wait_updates`: Wait queue to wait for updates to complete.
- `j_wait_reserved`: Wait queue to wait for reserved buffer credits to drop.
- `j_fc_wait`: Wait queue to wait for completion of async fast commits.
- `j_checkpoint_mutex`: Semaphore for locking against concurrent checkpoints.
- `j_chkpt_bhs`: List of buffer heads used by the checkpoint routine.  This
  was moved from `jbd2_log_do_checkpoint()` to reduce stack
  usage.  Access to this array is controlled by the
  **j_checkpoint_mutex**.  \[j_checkpoint_mutex\]
- `j_shrinker`: Journal head shrinker, reclaim buffer's journal head which
  has been written back.
- `j_checkpoint_jh_count`: Number of journal buffers on the checkpoint list. \[j_list_lock\]
- `j_shrink_transaction`: Record next transaction will shrink on the checkpoint list.
  \[j_list_lock\]
- `j_head`: Journal head: identifies the first unused block in the journal.
  \[j_state_lock\]
- `j_tail`: Journal tail: identifies the oldest still-used block in the journal.
  \[j_state_lock\]
- `j_free`: Journal free: how many free blocks are there in the journal?
  \[j_state_lock\]
- `j_first`: The block number of the first usable block in the journal
  \[j_state_lock\].
- `j_last`: The block number one beyond the last usable block in the journal
  \[j_state_lock\].
- `j_fc_first`: The block number of the first fast commit block in the journal
  \[j_state_lock\].
- `j_fc_off`: Number of fast commit blocks currently allocated. Accessed only
  during fast commit. Currently only process can do fast commit, so
  this field is not protected by any lock.
- `j_fc_last`: The block number one beyond the last fast commit block in the journal
  \[j_state_lock\].
- `j_dev`: Device where we store the journal.
- `j_blocksize`: Block size for the location where we store the journal.
- `j_blk_offset`: Starting block offset into the device where we store the journal.
- `j_devname`: Journal device name.
- `j_fs_dev`: Device which holds the client fs.  For internal journal this will be
  equal to j_dev.
- `j_fs_dev_wb_err`: Records the errseq of the client fs's backing block device.
- `j_total_len`: Total maximum capacity of the journal region on disk.
- `j_reserved_credits`: Number of buffers reserved from the running transaction.
- `j_list_lock`: Protects the buffer lists and internal buffer state.
- `j_inode`: Optional inode where we store the journal.  If present, all
  journal block numbers are mapped into this inode via [`bmap()`](/kernel/internals/filesystems/api-summary.md#c-bmap).
- `j_tail_sequence`: Sequence number of the oldest transaction in the log \[j_state_lock\]
- `j_transaction_sequence`: Sequence number of the next transaction to grant \[j_state_lock\]
- `j_commit_sequence`: Sequence number of the most recently committed transaction
  \[j_state_lock, no lock for quick racy checks\]
- `j_commit_request`: Sequence number of the most recent transaction wanting commit
  \[j_state_lock, no lock for quick racy checks\]
- `j_uuid`: Journal uuid: identifies the object (filesystem, LVM volume etc)
  backed by this journal.  This will eventually be replaced by an array
  of uuids, allowing us to index multiple devices within a single
  journal and to perform atomic updates across them.
- `j_task`: Pointer to the current commit thread for this journal.
- `j_max_transaction_buffers`: Maximum number of metadata buffers to allow in a single compound
  commit transaction.
- `j_revoke_records_per_block`: Number of revoke records that fit in one descriptor block.
- `j_transaction_overhead_buffers`: Number of blocks each transaction needs for its own bookkeeping
- `j_commit_interval`: What is the maximum transaction lifetime before we begin a commit?
- `j_commit_timer`: The timer used to wakeup the commit thread.
- `j_revoke_lock`: Protect the revoke table.
- `j_revoke`: The revoke table - maintains the list of revoked blocks in the
  current transaction.
- `j_revoke_table`: Alternate revoke tables for j_revoke.
- `j_wbuf`: Array of bhs for jbd2_journal_commit_transaction.
- `j_fc_wbuf`: Array of fast commit bhs for fast commit. Accessed only
  during a fast commit. Currently only process can do fast commit, so
  this field is not protected by any lock.
- `j_wbufsize`: Size of **j_wbuf** array.
- `j_fc_wbufsize`: Size of **j_fc_wbuf** array.
- `j_last_sync_writer`: The pid of the last person to run a synchronous operation
  through the journal.
- `j_average_commit_time`: The average amount of time in nanoseconds it takes to commit a
  transaction to disk. \[j_state_lock\]
- `j_min_batch_time`: Minimum time that we should wait for additional filesystem operations
  to get batched into a synchronous handle in microseconds.
- `j_max_batch_time`: Maximum time that we should wait for additional filesystem operations
  to get batched into a synchronous handle in microseconds.
- `j_commit_callback`: This function is called when a transaction is closed.
- `j_submit_inode_data_buffers`: This function is called for all inodes associated with the
  committing transaction marked with JI_WRITE_DATA flag
  before we start to write out the transaction to the journal.
- `j_finish_inode_data_buffers`: This function is called for all inodes associated with the
  committing transaction marked with JI_WAIT_DATA flag
  after we have written the transaction to the journal
  but before we write out the commit block.
- `j_history_lock`: Protect the transactions statistics history.
- `j_proc_entry`: procfs entry for the jbd statistics directory.
- `j_stats`: Overall statistics.
- `j_failed_commit`: Failed journal commit ID.
- `j_private`: An opaque pointer to fs-private information.  ext3 puts its
  superblock pointer here.
- `j_csum_seed`: Precomputed journal UUID checksum for seeding other checksums.
- `j_trans_commit_map`: Lockdep entity to track transaction commit dependencies. Handles
  hold this "lock" for read, when we wait for commit, we acquire the
  "lock" for writing. This matches the properties of jbd2 journalling
  where the running transaction has to wait for all handles to be
  dropped to commit that transaction and also acquiring a handle may
  require transaction commit to finish.
- `jbd2_trans_commit_key`: "struct lock_class_key" for **j_trans_commit_map**
- `j_fc_cleanup_callback`: Clean-up after fast commit or full commit. JBD2 calls this function
  after every commit operation.
- `j_fc_replay_callback`: File-system specific function that performs replay of a fast
  commit. JBD2 calls this function for each fast commit block found in
  the journal. This function should return JBD2_FC_REPLAY_CONTINUE
  to indicate that the block was processed correctly and more fast
  commit replay should continue. Return value of JBD2_FC_REPLAY_STOP
  indicates the end of replay (no more blocks remaining). A negative
  return value indicates error.
- `j_bmap`: Bmap function that should be used instead of the generic
  VFS bmap function.


<a id="rst-functions"></a>

## Functions

The functions here are split into two groups those that affect a journal as a whole, and those which are used to manage transactions

<a id="rst-journal-level"></a>

### Journal Level


#### <a id="c-jbd2_journal_force_commit_nested"></a>`jbd2_journal_force_commit_nested()`

```c
int jbd2_journal_force_commit_nested(journal_t *journal)
```

Force and wait upon a commit if the calling process is not within transaction.

**Parameters**

- `journal_t *journal`: journal to force
  Returns true if progress was made.

**Description**

This is used for forcing out undo-protected data which contains
bitmaps, when the fs is running out of space.

#### <a id="c-jbd2_journal_force_commit"></a>`jbd2_journal_force_commit()`

```c
int jbd2_journal_force_commit(journal_t *journal)
```

force any uncommitted transactions

**Parameters**

- `journal_t *journal`: journal to force

**Description**

Caller want unconditional commit. We can only force the running transaction
if we don't have an active handle, otherwise, we will deadlock.

#### <a id="c-jbd2_journal_init_dev"></a>`jbd2_journal_init_dev()`

```c
journal_t * jbd2_journal_init_dev(struct block_device *bdev, struct block_device *fs_dev, unsigned long long start, int len, int blocksize)
```

creates and initialises a journal structure

**Parameters**

- `struct block_device *bdev`: Block device on which to create the journal
- `struct block_device *fs_dev`: Device which hold journalled filesystem for this journal.
- `unsigned long long start`: Block nr Start of journal.
- `int len`: Length of the journal in blocks.
- `int blocksize`: blocksize of journalling device

**Return**

a newly created journal_t *

**Description**

jbd2_journal_init_dev creates a journal which maps a fixed contiguous
range of blocks on an arbitrary block device.

#### <a id="c-jbd2_journal_init_inode"></a>`jbd2_journal_init_inode()`

```c
journal_t * jbd2_journal_init_inode(struct inode *inode)
```

creates a journal which maps to a inode.

**Parameters**

- `struct inode *inode`: An inode to create the journal in

**Description**

jbd2_journal_init_inode creates a journal which maps an on-disk inode as
the journal.  The inode must exist already, must support [`bmap()`](/kernel/internals/filesystems/api-summary.md#c-bmap) and
must have all data blocks preallocated.

#### <a id="c-jbd2_journal_update_sb_errno"></a>`jbd2_journal_update_sb_errno()`

```c
void jbd2_journal_update_sb_errno(journal_t *journal)
```

Update error in the journal.

**Parameters**

- `journal_t *journal`: The journal to update.

**Description**

Update a journal's errno.  Write updated superblock to disk waiting for IO
to complete.

#### <a id="c-jbd2_journal_load"></a>`jbd2_journal_load()`

```c
int jbd2_journal_load(journal_t *journal)
```

Read journal from disk.

**Parameters**

- `journal_t *journal`: Journal to act on.

**Description**

Given a journal_t structure which tells us which disk blocks contain
a journal, read the journal from disk to initialise the in-memory
structures.

#### <a id="c-jbd2_journal_destroy"></a>`jbd2_journal_destroy()`

```c
int jbd2_journal_destroy(journal_t *journal)
```

Release a journal_t structure.

**Parameters**

- `journal_t *journal`: Journal to act on.

**Description**

Release a journal_t structure once it is no longer in use by the
journaled object.
Return \<0 if we couldn't clean up the journal.

#### <a id="c-jbd2_journal_check_used_features"></a>`jbd2_journal_check_used_features()`

```c
int jbd2_journal_check_used_features(journal_t *journal, unsigned long compat, unsigned long ro, unsigned long incompat)
```

Check if features specified are used.

**Parameters**

- `journal_t *journal`: Journal to check.
- `unsigned long compat`: bitmask of compatible features
- `unsigned long ro`: bitmask of features that force read-only mount
- `unsigned long incompat`: bitmask of incompatible features

**Description**

Check whether the journal uses all of a given set of
features.  Return true (non-zero) if it does.

#### <a id="c-jbd2_journal_check_available_features"></a>`jbd2_journal_check_available_features()`

```c
int jbd2_journal_check_available_features(journal_t *journal, unsigned long compat, unsigned long ro, unsigned long incompat)
```

Check feature set in journalling layer

**Parameters**

- `journal_t *journal`: Journal to check.
- `unsigned long compat`: bitmask of compatible features
- `unsigned long ro`: bitmask of features that force read-only mount
- `unsigned long incompat`: bitmask of incompatible features

**Description**

Check whether the journaling code supports the use of
all of a given set of features on this journal.  Return true

#### <a id="c-jbd2_journal_set_features"></a>`jbd2_journal_set_features()`

```c
int jbd2_journal_set_features(journal_t *journal, unsigned long compat, unsigned long ro, unsigned long incompat)
```

Mark a given journal feature in the superblock

**Parameters**

- `journal_t *journal`: Journal to act on.
- `unsigned long compat`: bitmask of compatible features
- `unsigned long ro`: bitmask of features that force read-only mount
- `unsigned long incompat`: bitmask of incompatible features

**Description**

Mark a given journal feature as present on the
superblock.  Returns true if the requested features could be set.

#### <a id="c-jbd2_journal_flush"></a>`jbd2_journal_flush()`

```c
int jbd2_journal_flush(journal_t *journal, unsigned int flags)
```

Flush journal

**Parameters**

- `journal_t *journal`: Journal to act on.
- `unsigned int flags`: optional operation on the journal blocks after the flush (see below)

**Description**

Flush all data for a given journal to disk and empty the journal.
Filesystems can use this when remounting readonly to ensure that
recovery does not need to happen on remount. Optionally, a discard or zeroout
can be issued on the journal blocks after flushing.

- flags:
  JBD2_JOURNAL_FLUSH_DISCARD: issues discards for the journal blocks
  JBD2_JOURNAL_FLUSH_ZEROOUT: issues zeroouts for the journal blocks

#### <a id="c-jbd2_journal_wipe"></a>`jbd2_journal_wipe()`

```c
int jbd2_journal_wipe(journal_t *journal, int write)
```

Wipe journal contents

**Parameters**

- `journal_t *journal`: Journal to act on.
- `int write`: flag (see below)

**Description**

Wipe out all of the contents of a journal, safely.  This will produce
a warning if the journal contains any valid recovery information.
Must be called between journal_init_*() and [`jbd2_journal_load()`](#c-jbd2_journal_load).

If 'write' is non-zero, then we wipe out the journal on disk; otherwise
we merely suppress recovery.

#### <a id="c-jbd2_journal_abort"></a>`jbd2_journal_abort()`

```c
void jbd2_journal_abort(journal_t *journal, int errno)
```

Shutdown the journal immediately.

**Parameters**

- `journal_t *journal`: the journal to shutdown.
- `int errno`: an error number to record in the journal indicating
  the reason for the shutdown.

**Description**

Perform a complete, immediate shutdown of the ENTIRE
journal (not of a single transaction).  This operation cannot be
undone without closing and reopening the journal.

The jbd2_journal_abort function is intended to support higher level error
recovery mechanisms such as the ext2/ext3 remount-readonly error
mode.

Journal abort has very specific semantics.  Any existing dirty,
unjournaled buffers in the main filesystem will still be written to
disk by bdflush, but the journaling mechanism will be suspended
immediately and no further transaction commits will be honoured.

Any dirty, journaled buffers will be written back to disk without
hitting the journal.  Atomicity cannot be guaranteed on an aborted
filesystem, but we _do_ attempt to leave as much data as possible
behind for fsck to use for cleanup.

Any attempt to get a new transaction handle on a journal which is in
ABORT state will just result in an -EROFS error return.  A
jbd2_journal_stop on an existing handle will return -EIO if we have
entered abort state during the update.

Recursive transactions are not disturbed by journal abort until the
final jbd2_journal_stop, which will receive the -EIO error.

Finally, the jbd2_journal_abort call allows the caller to supply an errno
which will be recorded (if possible) in the journal superblock.  This
allows a client to record failure conditions in the middle of a
transaction without having to complete the transaction to record the
failure to disk.  ext3_error, for example, now uses this
functionality.

#### <a id="c-jbd2_journal_errno"></a>`jbd2_journal_errno()`

```c
int jbd2_journal_errno(journal_t *journal)
```

returns the journal's error state.

**Parameters**

- `journal_t *journal`: journal to examine.

**Description**

This is the errno number set with [`jbd2_journal_abort()`](#c-jbd2_journal_abort), the last
time the journal was mounted - if the journal was stopped
without calling abort this will be 0.

If the journal has been aborted on this mount time -EROFS will
be returned.

#### <a id="c-jbd2_journal_clear_err"></a>`jbd2_journal_clear_err()`

```c
int jbd2_journal_clear_err(journal_t *journal)
```

clears the journal's error state

**Parameters**

- `journal_t *journal`: journal to act on.

**Description**

An error must be cleared or acked to take a FS out of readonly
mode.

#### <a id="c-jbd2_journal_ack_err"></a>`jbd2_journal_ack_err()`

```c
void jbd2_journal_ack_err(journal_t *journal)
```

Ack journal err.

**Parameters**

- `journal_t *journal`: journal to act on.

**Description**

An error must be cleared or acked to take a FS out of readonly
mode.



#### <a id="c-jbd2_journal_recover"></a>`jbd2_journal_recover()`

```c
int jbd2_journal_recover(journal_t *journal)
```

recovers a on-disk journal

**Parameters**

- `journal_t *journal`: the journal to recover

**Description**

The primary function for recovering the log contents when mounting a
journaled device.

Recovery is done in three passes.  In the first pass, we look for the
end of the log.  In the second, we assemble the list of revoke
blocks.  In the third and final pass, we replay any un-revoked blocks
in the log.

#### <a id="c-jbd2_journal_skip_recovery"></a>`jbd2_journal_skip_recovery()`

```c
int jbd2_journal_skip_recovery(journal_t *journal)
```

Start journal and wipe exiting records

**Parameters**

- `journal_t *journal`: journal to startup

**Description**

Locate any valid recovery information from the journal and set up the
journal structures in memory to ignore it (presumably because the
caller has evidence that it is out of date).
This function doesn't appear to be exported..

We perform one pass over the journal to allow us to tell the user how
much recovery information is being erased, and to let us initialise
the journal transaction sequence numbers to the next unused ID.


<a id="rst-transaction-level"></a>

### Transaction Level


#### <a id="c-jbd2_journal_start"></a>`jbd2_journal_start()`

```c
handle_t * jbd2_journal_start(journal_t *journal, int nblocks)
```

Obtain a new handle.

**Parameters**

- `journal_t *journal`: Journal to start transaction on.
- `int nblocks`: number of block buffer we might modify

**Description**

We make sure that the transaction can guarantee at least nblocks of
modified buffers in the log.  We block until the log can guarantee
that much space. Additionally, if rsv_blocks > 0, we also create another
handle with rsv_blocks reserved blocks in the journal. This handle is
stored in h_rsv_handle. It is not attached to any particular transaction
and thus doesn't block transaction commit. If the caller uses this reserved
handle, it has to set h_rsv_handle to NULL as otherwise [`jbd2_journal_stop()`](#c-jbd2_journal_stop)
on the parent handle will dispose the reserved one. Reserved handle has to
be converted to a normal handle using [`jbd2_journal_start_reserved()`](#c-jbd2_journal_start_reserved) before
it can be used.

Return a pointer to a newly allocated handle, or an [`ERR_PTR()`](/kernel/internals/core-api/kernel-api.md#c-ERR_PTR) value
on failure.

#### <a id="c-jbd2_journal_start_reserved"></a>`jbd2_journal_start_reserved()`

```c
int jbd2_journal_start_reserved(handle_t *handle, unsigned int type, unsigned int line_no)
```

start reserved handle

**Parameters**

- `handle_t *handle`: handle to start
- `unsigned int type`: for handle statistics
- `unsigned int line_no`: for handle statistics

**Description**

Start handle that has been previously reserved with `jbd2_journal_reserve()`.
This attaches **handle** to the running transaction (or creates one if there's
not transaction running). Unlike [`jbd2_journal_start()`](#c-jbd2_journal_start) this function cannot
block on journal commit, checkpointing, or similar stuff. It can block on
memory allocation or frozen journal though.

Return 0 on success, non-zero on error - handle is freed in that case.

#### <a id="c-jbd2_journal_extend"></a>`jbd2_journal_extend()`

```c
int jbd2_journal_extend(handle_t *handle, int nblocks, int revoke_records)
```

extend buffer credits.

**Parameters**

- `handle_t *handle`: handle to 'extend'
- `int nblocks`: nr blocks to try to extend by.
- `int revoke_records`: number of revoke records to try to extend by.

**Description**

Some transactions, such as large extends and truncates, can be done
atomically all at once or in several stages.  The operation requests
a credit for a number of buffer modifications in advance, but can
extend its credit if it needs more.

jbd2_journal_extend tries to give the running handle more buffer credits.
It does not guarantee that allocation - this is a best-effort only.
The calling process MUST be able to deal cleanly with a failure to
extend here.

Return 0 on success, non-zero on failure.

return code \< 0 implies an error
return code > 0 implies normal transaction-full status.

#### <a id="c-jbd2__journal_restart"></a>`jbd2__journal_restart()`

```c
int jbd2__journal_restart(handle_t *handle, int nblocks, int revoke_records, gfp_t gfp_mask)
```

restart a handle .

**Parameters**

- `handle_t *handle`: handle to restart
- `int nblocks`: nr credits requested
- `int revoke_records`: number of revoke record credits requested
- `gfp_t gfp_mask`: memory allocation flags (for start_this_handle)

**Description**

Restart a handle for a multi-transaction filesystem
operation.

If the [`jbd2_journal_extend()`](#c-jbd2_journal_extend) call above fails to grant new buffer credits
to a running handle, a call to jbd2_journal_restart will commit the
handle's transaction so far and reattach the handle to a new
transaction capable of guaranteeing the requested number of
credits. We preserve reserved handle if there's any attached to the
passed in handle.

#### <a id="c-jbd2_journal_lock_updates"></a>`jbd2_journal_lock_updates()`

```c
void jbd2_journal_lock_updates(journal_t *journal)
```

establish a transaction barrier.

**Parameters**

- `journal_t *journal`: Journal to establish a barrier on.

**Description**

This locks out any further updates from being started, and blocks
until all existing updates have completed, returning only once the
journal is in a quiescent state with no updates running.

The journal lock should not be held on entry.

#### <a id="c-jbd2_journal_unlock_updates"></a>`jbd2_journal_unlock_updates()`

```c
void jbd2_journal_unlock_updates(journal_t *journal)
```

release barrier

**Parameters**

- `journal_t *journal`: Journal to release the barrier on.

**Description**

Release a transaction barrier obtained with [`jbd2_journal_lock_updates()`](#c-jbd2_journal_lock_updates).

Should be called without the journal lock held.

#### <a id="c-jbd2_journal_get_write_access"></a>`jbd2_journal_get_write_access()`

```c
int jbd2_journal_get_write_access(handle_t *handle, struct buffer_head *bh)
```

notify intent to modify a buffer for metadata (not data) update.

**Parameters**

- `handle_t *handle`: transaction to add buffer modifications to
- `struct buffer_head *bh`: bh to be used for metadata writes

**Return**

error code or 0 on success.

**Description**

In full data journalling mode the buffer may be of type BJ_AsyncData,
because we're `write()ing` a buffer which is also part of a shared mapping.

#### <a id="c-jbd2_journal_get_create_access"></a>`jbd2_journal_get_create_access()`

```c
int jbd2_journal_get_create_access(handle_t *handle, struct buffer_head *bh)
```

notify intent to use newly created bh

**Parameters**

- `handle_t *handle`: transaction to new buffer to
- `struct buffer_head *bh`: new buffer.

**Description**

Call this if you create a new bh.

#### <a id="c-jbd2_journal_get_undo_access"></a>`jbd2_journal_get_undo_access()`

```c
int jbd2_journal_get_undo_access(handle_t *handle, struct buffer_head *bh)
```

Notify intent to modify metadata with non-rewindable consequences

**Parameters**

- `handle_t *handle`: transaction
- `struct buffer_head *bh`: buffer to undo

**Description**

Sometimes there is a need to distinguish between metadata which has
been committed to disk and that which has not.  The ext3fs code uses
this for freeing and allocating space, we have to make sure that we
do not reuse freed space until the deallocation has been committed,
since if we overwrote that space we would make the delete
un-rewindable in case of a crash.

To deal with that, jbd2_journal_get_undo_access requests write access to a
buffer for parts of non-rewindable operations such as delete
operations on the bitmaps.  The journaling code must keep a copy of
the buffer's contents prior to the undo_access call until such time
as we know that the buffer has definitely been committed to disk.

We never need to know which transaction the committed data is part
of, buffers touched here are guaranteed to be dirtied later and so
will be committed to a new transaction in due course, at which point
we can discard the old committed data pointer.

Returns error number or 0 on success.

#### <a id="c-jbd2_journal_set_triggers"></a>`jbd2_journal_set_triggers()`

```c
void jbd2_journal_set_triggers(struct buffer_head *bh, struct jbd2_buffer_trigger_type *type)
```

Add triggers for commit writeout

**Parameters**

- `struct buffer_head *bh`: buffer to trigger on
- `struct jbd2_buffer_trigger_type *type`: struct jbd2_buffer_trigger_type containing the trigger(s).

**Description**

Set any triggers on this journal_head.  This is always safe, because
triggers for a committing buffer will be saved off, and triggers for
a running transaction will match the buffer in that transaction.

Call with NULL to clear the triggers.

#### <a id="c-jbd2_journal_dirty_metadata"></a>`jbd2_journal_dirty_metadata()`

```c
int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
```

mark a buffer as containing dirty metadata

**Parameters**

- `handle_t *handle`: transaction to add buffer to.
- `struct buffer_head *bh`: buffer to mark

**Description**

mark dirty metadata which needs to be journaled as part of the current
transaction.

The buffer must have previously had [`jbd2_journal_get_write_access()`](#c-jbd2_journal_get_write_access)
called so that it has a valid journal_head attached to the buffer
head.

The buffer is placed on the transaction's metadata list and is marked
as belonging to the transaction.

Returns error number or 0 on success.

Special care needs to be taken if the buffer already belongs to the
current committing transaction (in which case we should have frozen
data present for that commit).  In that case, we don't relink the
buffer: that only gets done when the old transaction finally
completes its commit.

#### <a id="c-jbd2_journal_forget"></a>`jbd2_journal_forget()`

```c
int jbd2_journal_forget(handle_t *handle, struct buffer_head *bh)
```

[`bforget()`](/kernel/internals/filesystems/buffer.md#c-bforget) for potentially-journaled buffers.

**Parameters**

- `handle_t *handle`: transaction handle
- `struct buffer_head *bh`: bh to 'forget'

**Description**

We can only do the bforget if there are no commits pending against the
buffer.  If the buffer is dirty in the current running transaction we
can safely unlink it.

bh may not be a journalled buffer at all - it may be a non-JBD
buffer which came off the hashtable.  Check for this.

Decrements bh->b_count by one.

Allow this call even if the handle has aborted --- it may be part of
the caller's cleanup after an abort.

#### <a id="c-jbd2_journal_stop"></a>`jbd2_journal_stop()`

```c
int jbd2_journal_stop(handle_t *handle)
```

complete a transaction

**Parameters**

- `handle_t *handle`: transaction to complete.

**Description**

All done for a particular handle.

There is not much action needed here.  We just return any remaining
buffer credits to the transaction and remove the handle.  The only
complication is that we need to start a commit operation if the
filesystem is marked for synchronous update.

jbd2_journal_stop itself will not usually return an error, but it may
do so in unusual circumstances.  In particular, expect it to
return -EIO if a jbd2_journal_abort has been executed since the
transaction began.

#### <a id="c-jbd2_journal_try_to_free_buffers"></a>`jbd2_journal_try_to_free_buffers()`

```c
bool jbd2_journal_try_to_free_buffers(journal_t *journal, struct folio *folio)
```

try to free page buffers.

**Parameters**

- `journal_t *journal`: journal for operation
- `struct folio *folio`: Folio to detach data from.

**Description**

For all the buffers on this page,
if they are fully written out ordered data, move them onto BUF_CLEAN
so [`try_to_free_buffers()`](/kernel/internals/filesystems/buffer.md#c-try_to_free_buffers) can reap them.

This function returns non-zero if we wish [`try_to_free_buffers()`](/kernel/internals/filesystems/buffer.md#c-try_to_free_buffers)
to be called. We do this if the page is releasable by [`try_to_free_buffers()`](/kernel/internals/filesystems/buffer.md#c-try_to_free_buffers).
We also do it if the page has locked or dirty buffers and the caller wants
us to perform sync or async writeout.

This complicates JBD locking somewhat.  We aren't protected by the
BKL here.  We wish to remove the buffer from its committing or
running transaction's ->t_datalist via __jbd2_journal_unfile_buffer.

This may *change* the value of transaction_t->t_datalist, so anyone
who looks at t_datalist needs to lock against this function.

Even worse, someone may be doing a jbd2_journal_dirty_data on this
buffer.  So we need to lock against that.  `jbd2_journal_dirty_data()`
will come out of the lock with the buffer dirty, which makes it
ineligible for release here.

Who else is affected by this?  hmm...  Really the only contender
is `do_get_write_access()` - it could be looking at the buffer while
`journal_try_to_free_buffer()` is changing its state.  But that
cannot happen because we never reallocate freed data as metadata
while the data is part of a transaction.  Yes?

Return false on failure, true on success

#### <a id="c-jbd2_journal_invalidate_folio"></a>`jbd2_journal_invalidate_folio()`

```c
int jbd2_journal_invalidate_folio(journal_t *journal, struct folio *folio, size_t offset, size_t length)
```

**Parameters**

- `journal_t *journal`: journal to use for flush...
- `struct folio *folio`: folio to flush
- `size_t offset`: start of the range to invalidate
- `size_t length`: length of the range to invalidate

**Description**

Reap page buffers containing data after in the specified range in page.
Can return -EBUSY if buffers are part of the committing transaction and
the page is straddling i_size. Caller then has to wait for current commit
and try again.


<a id="rst-see-also"></a>

## See also

[Journaling the Linux ext2fs Filesystem, LinuxExpo 98, Stephen Tweedie](<http://kernel.org/pub/linux/kernel/people/sct/ext3/journal-design.ps.gz>)

[Ext3 Journalling FileSystem, OLS 2000, Dr. Stephen Tweedie](<http://olstrans.sourceforge.net/release/OLS2000-ext3/OLS2000-ext3.html>)

---

# Locking

_Peios Kernel / Internals / Filesystems_

> The text below describes the locking rules for VFS-related methods. It is (believed to be) up-to-date. Please, if you change anything in prototypes or locking protocols - update this file. And update the relevant instances in the tree,…

> **Peios:** The VFS also has Peios `validate_mountpoint` and `getlease` callbacks. See the [VFS reference](</kernel/internals/filesystems/vfs.md>) for their contracts. Layered lease queries must preserve the outer `lease_file` identity when forwarding to a backing file.


<a id="rst-locking"></a>

The text below describes the locking rules for VFS-related methods. It is (believed to be) up-to-date. *Please*, if you change anything in prototypes or locking protocols - update this file. And update the relevant instances in the tree, don't leave that to maintainers of filesystems/devices/ etc. At the very least, put the list of dubious cases in the end of this file. Don't turn it into log - maintainers of out-of-the-tree code are supposed to be able to use diff(1).

Thing currently missing here: socket operations. Alexey?

<a id="rst-dentry-operations"></a>

## dentry_operations

prototypes:



```text
int (*d_revalidate)(struct inode *, const struct qstr *,
                    struct dentry *, unsigned int);
int (*d_weak_revalidate)(struct dentry *, unsigned int);
int (*d_hash)(const struct dentry *, struct qstr *);
int (*d_compare)(const struct dentry *,
                unsigned int, const char *, const struct qstr *);
int (*d_delete)(struct dentry *);
int (*d_init)(struct dentry *);
void (*d_release)(struct dentry *);
void (*d_iput)(struct dentry *, struct inode *);
char *(*d_dname)((struct dentry *dentry, char *buffer, int buflen);
struct vfsmount *(*d_automount)(struct path *path);
int (*d_manage)(const struct path *, bool);
struct dentry *(*d_real)(struct dentry *, enum d_real_type type);
bool (*d_unalias_trylock)(const struct dentry *);
void (*d_unalias_unlock)(const struct dentry *);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


rename_lock

</th>
<th>


-&gt;d_lock

</th>
<th>


may block

</th>
<th>


rcu-walk

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


d_revalidate:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes (ref-walk)

</td>
<td>


maybe

</td>
</tr>
<tr>
<td>


d_weak_revalidate:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_hash

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
<td>


maybe

</td>
</tr>
<tr>
<td>


d_compare:

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
<td>


maybe

</td>
</tr>
<tr>
<td>


d_delete:

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_init:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_release:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_prune:

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_iput:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_dname:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_automount:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_manage:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes (ref-walk)

</td>
<td>


maybe

</td>
</tr>
<tr>
<td>


d_real

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_unalias_trylock

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


d_unalias_unlock

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
</tbody>
</table>

<a id="rst-inode-operations"></a>

## inode_operations

prototypes:



```text
int (*create) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t, bool);
struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
int (*link) (struct dentry *,struct inode *,struct dentry *);
int (*unlink) (struct inode *,struct dentry *);
int (*symlink) (struct mnt_idmap *, struct inode *,struct dentry *,const char *);
struct dentry *(*mkdir) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t);
int (*rmdir) (struct inode *,struct dentry *);
int (*mknod) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t,dev_t);
int (*rename) (struct mnt_idmap *, struct inode *, struct dentry *,
                struct inode *, struct dentry *, unsigned int);
int (*readlink) (struct dentry *, char __user *,int);
const char *(*get_link) (struct dentry *, struct inode *, struct delayed_call *);
void (*truncate) (struct inode *);
int (*permission) (struct mnt_idmap *, struct inode *, int, unsigned int);
struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
int (*setattr) (struct mnt_idmap *, struct dentry *, struct iattr *);
int (*getattr) (struct mnt_idmap *, const struct path *, struct kstat *, u32, unsigned int);
ssize_t (*listxattr) (struct dentry *, char *, size_t);
int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start, u64 len);
void (*update_time)(struct inode *inode, enum fs_update_time type,
                    int flags);
void (*sync_lazytime)(struct inode *inode);
int (*atomic_open)(struct inode *, struct dentry *,
                        struct file *, unsigned open_flag,
                        umode_t create_mode);
int (*tmpfile) (struct mnt_idmap *, struct inode *,
                struct file *, umode_t);
int (*fileattr_set)(struct mnt_idmap *idmap,
                    struct dentry *dentry, struct file_kattr *fa);
int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
struct posix_acl * (*get_acl)(struct mnt_idmap *, struct dentry *, int);
struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
```

- **locking rules:**

  all may block


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


i_rwsem(inode)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


lookup:

</td>
<td>


shared

</td>
</tr>
<tr>
<td>


create:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


link:

</td>
<td>


exclusive (both)

</td>
</tr>
<tr>
<td>


mknod:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


symlink:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


mkdir:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


unlink:

</td>
<td>


exclusive (both)

</td>
</tr>
<tr>
<td>


rmdir:

</td>
<td>


exclusive (both)(see below)

</td>
</tr>
<tr>
<td>


rename:

</td>
<td>


exclusive (both parents, some children) (see below)

</td>
</tr>
<tr>
<td>


readlink:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


get_link:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


setattr:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


permission:

</td>
<td>


no (may not block if called in rcu-walk mode)

</td>
</tr>
<tr>
<td>


get_inode_acl:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


get_acl:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


getattr:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


listxattr:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


fiemap:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


update_time:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


sync_lazytime:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


atomic_open:

</td>
<td>


shared (exclusive if O_CREAT is set in open flags)

</td>
</tr>
<tr>
<td>


tmpfile:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


fileattr_get:

</td>
<td>


no or exclusive

</td>
</tr>
<tr>
<td>


fileattr_set:

</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


get_offset_ctx

</td>
<td>


no

</td>
</tr>
</tbody>
</table>

> Additionally, -&gt;rmdir(), -&gt;unlink() and -&gt;rename() have -&gt;i_rwsem exclusive on victim. cross-directory -&gt;rename() has (per-superblock) -&gt;s_vfs_rename_sem. -&gt;unlink() and -&gt;rename() have -&gt;i_rwsem exclusive on all non-directories involved. -&gt;rename() has -&gt;i_rwsem exclusive on any subdirectory that changes parent.

See [Documentation/filesystems/directory-locking.rst](/kernel/internals/filesystems/directory-locking.md) for more detailed discussion of the locking scheme for directory operations.

<a id="rst-xattr-handler-operations"></a>

## xattr_handler operations

prototypes:



```text
bool (*list)(struct dentry *dentry);
int (*get)(const struct xattr_handler *handler, struct dentry *dentry,
           struct inode *inode, const char *name, void *buffer,
           size_t size);
int (*set)(const struct xattr_handler *handler,
           struct mnt_idmap *idmap,
           struct dentry *dentry, struct inode *inode, const char *name,
           const void *buffer, size_t size, int flags);
```

- **locking rules:**

  all may block


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


i_rwsem(inode)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


list:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


get:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


set:

</td>
<td>


exclusive

</td>
</tr>
</tbody>
</table>

<a id="rst-super-operations"></a>

## super_operations

prototypes:



```text
struct inode *(*alloc_inode)(struct super_block *sb);
void (*free_inode)(struct inode *);
void (*destroy_inode)(struct inode *);
void (*dirty_inode) (struct inode *, int flags);
int (*write_inode) (struct inode *, struct writeback_control *wbc);
int (*drop_inode) (struct inode *);
void (*evict_inode) (struct inode *);
void (*put_super) (struct super_block *);
int (*sync_fs)(struct super_block *sb, int wait);
int (*freeze_fs) (struct super_block *);
int (*unfreeze_fs) (struct super_block *);
int (*statfs) (struct dentry *, struct kstatfs *);
void (*umount_begin) (struct super_block *);
int (*show_options)(struct seq_file *, struct dentry *);
ssize_t (*quota_read)(struct super_block *, int, char *, size_t, loff_t);
ssize_t (*quota_write)(struct super_block *, int, const char *, size_t, loff_t);
```

- **locking rules:**

  All may block \[not true, see below\]


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


s_umount

</th>
<th>


note

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


alloc_inode:

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


free_inode:

</td>
<td>




</td>
<td>


called from RCU callback

</td>
</tr>
<tr>
<td>


destroy_inode:

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


dirty_inode:

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


write_inode:

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


drop_inode:

</td>
<td>




</td>
<td>


\!\!\!inode-&gt;i_lock\!\!\!

</td>
</tr>
<tr>
<td>


evict_inode:

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


put_super:

</td>
<td>


write

</td>
<td>




</td>
</tr>
<tr>
<td>


sync_fs:

</td>
<td>


read

</td>
<td>




</td>
</tr>
<tr>
<td>


freeze_fs:

</td>
<td>


write

</td>
<td>




</td>
</tr>
<tr>
<td>


unfreeze_fs:

</td>
<td>


write

</td>
<td>




</td>
</tr>
<tr>
<td>


statfs:

</td>
<td>


maybe(read)

</td>
<td>


(see below)

</td>
</tr>
<tr>
<td>


umount_begin:

</td>
<td>


no

</td>
<td>




</td>
</tr>
<tr>
<td>


show_options:

</td>
<td>


no

</td>
<td>


(namespace_sem)

</td>
</tr>
<tr>
<td>


quota_read:

</td>
<td>


no

</td>
<td>


(see below)

</td>
</tr>
<tr>
<td>


quota_write:

</td>
<td>


no

</td>
<td>


(see below)

</td>
</tr>
</tbody>
</table>

-&gt;statfs() has s_umount (shared) when called by ustat(2) (native or compat), but that's an accident of bad API; s_umount is used to pin the superblock down when we only have dev_t given us by userland to identify the superblock.  Everything else (statfs(), fstatfs(), etc.) doesn't hold it when calling -&gt;statfs() - superblock is pinned down by resolving the pathname passed to syscall.

-&gt;quota_read() and -&gt;quota_write() functions are both guaranteed to be the only ones operating on the quota file by the quota code (via dqio_sem) (unless an admin really wants to screw up something and writes to quota files with quotas on). For other details about locking see also dquot_operations section.

<a id="rst-file-system-type"></a>

## file_system_type

prototypes:



```text
void (*kill_sb) (struct super_block *);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


may block

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


kill_sb

</td>
<td>


yes

</td>
</tr>
</tbody>
</table>

-&gt;kill_sb() takes a write-locked superblock, does all shutdown work on it, unlocks and drops the reference.

<a id="rst-address-space-operations"></a>

## address_space_operations

prototypes:



```text
int (*read_folio)(struct file *, struct folio *);
int (*writepages)(struct address_space *, struct writeback_control *);
bool (*dirty_folio)(struct address_space *, struct folio *folio);
void (*readahead)(struct readahead_control *);
int (*write_begin)(const struct kiocb *, struct address_space *mapping,
                        loff_t pos, unsigned len,
                        struct folio **foliop, void **fsdata);
int (*write_end)(const struct kiocb *, struct address_space *mapping,
                        loff_t pos, unsigned len, unsigned copied,
                        struct folio *folio, void *fsdata);
sector_t (*bmap)(struct address_space *, sector_t);
void (*invalidate_folio) (struct folio *, size_t start, size_t len);
bool (*release_folio)(struct folio *, gfp_t);
void (*free_folio)(struct folio *);
int (*direct_IO)(struct kiocb *, struct iov_iter *iter);
int (*migrate_folio)(struct address_space *, struct folio *dst,
                struct folio *src, enum migrate_mode);
int (*launder_folio)(struct folio *);
bool (*is_partially_uptodate)(struct folio *, size_t from, size_t count);
int (*error_remove_folio)(struct address_space *, struct folio *);
int (*swap_activate)(struct swap_info_struct *sis, struct file *f, sector_t *span)
int (*swap_deactivate)(struct file *);
int (*swap_rw)(struct kiocb *iocb, struct iov_iter *iter);
```

- **locking rules:**

  All except dirty_folio and free_folio may block


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


folio locked

</th>
<th>


i_rwsem

</th>
<th>


invalidate_lock

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


read_folio:

</td>
<td>


yes, unlocks

</td>
<td>




</td>
<td>


shared

</td>
</tr>
<tr>
<td>


writepages:

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


dirty_folio:

</td>
<td>


maybe

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


readahead:

</td>
<td>


yes, unlocks

</td>
<td>




</td>
<td>


shared

</td>
</tr>
<tr>
<td>


write_begin:

</td>
<td>


locks the folio

</td>
<td>


exclusive

</td>
<td>




</td>
</tr>
<tr>
<td>


write_end:

</td>
<td>


yes, unlocks

</td>
<td>


exclusive

</td>
<td>




</td>
</tr>
<tr>
<td>


bmap:

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


invalidate_folio:

</td>
<td>


yes

</td>
<td>




</td>
<td>


exclusive

</td>
</tr>
<tr>
<td>


release_folio:

</td>
<td>


yes

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


free_folio:

</td>
<td>


yes

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


direct_IO:

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


migrate_folio:

</td>
<td>


yes (both)

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


launder_folio:

</td>
<td>


yes

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


is_partially_uptodate:

</td>
<td>


yes

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


error_remove_folio:

</td>
<td>


yes

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


swap_activate:

</td>
<td>


no

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


swap_deactivate:

</td>
<td>


no

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


swap_rw:

</td>
<td>


yes, unlocks

</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

-&gt;write_begin(), -&gt;write_end() and -&gt;read_folio() may be called from the request handler (/dev/loop).

-&gt;read_folio() unlocks the folio, either synchronously or via I/O completion.

-&gt;readahead() unlocks the folios that I/O is attempted on like -&gt;read_folio().

-&gt;writepages() is used for periodic writeback and for syscall-initiated sync operations.  The address_space should start I/O against at least `*nr_to_write` pages.  `*nr_to_write` must be decremented for each page which is written.  The address_space implementation may write more (or less) pages than `*nr_to_write` asks for, but it should try to be reasonably close. If nr_to_write is NULL, all dirty pages must be written.

writepages should \_only\_ write pages which are present in mapping-&gt;i_pages.

-&gt;dirty_folio() is called from various places in the kernel when the target folio is marked as needing writeback.  The folio cannot be truncated because either the caller holds the folio lock, or the caller has found the folio while holding the page table lock which will block truncation.

-&gt;bmap() is currently used by legacy ioctl() (FIBMAP) provided by some filesystems and by the swapper. The latter will eventually go away.  Please, keep it that way and don't breed new callers.

-&gt;invalidate_folio() is called when the filesystem must attempt to drop some or all of the buffers from the page when it is being truncated. It returns zero on success.  The filesystem must exclusively acquire invalidate_lock before invalidating page cache in truncate / hole punch path (and thus calling into -&gt;invalidate_folio) to block races between page cache invalidation and page cache filling functions (fault, read, ...).

-&gt;release_folio() is called when the MM wants to make a change to the folio that would invalidate the filesystem's private data.  For example, it may be about to be removed from the address_space or split.  The folio is locked and not under writeback.  It may be dirty.  The gfp parameter is not usually used for allocation, but rather to indicate what the filesystem may do to attempt to free the private data.  The filesystem may return false to indicate that the folio's private data cannot be freed. If it returns true, it should have already removed the private data from the folio.  If a filesystem does not provide a -&gt;release_folio method, the pagecache will assume that private data is buffer_heads and call try_to_free_buffers().

-&gt;free_folio() is called when the kernel has dropped the folio from the page cache.

-&gt;launder_folio() may be called prior to releasing a folio if it is still found to be dirty. It returns zero if the folio was successfully cleaned, or an error value if not. Note that in order to prevent the folio getting mapped back in and redirtied, it needs to be kept locked across the entire operation.

-&gt;swap_activate() will be called to prepare the given file for swap.  It should perform any validation and preparation necessary to ensure that writes can be performed with minimal memory allocation.  It should call add_swap_extent(), or the helper iomap_swapfile_activate(), and return the number of extents added.  If IO should be submitted through -&gt;swap_rw(), it should set SWP_FS_OPS, otherwise IO will be submitted directly to the block device `sis->bdev`.

-&gt;swap_deactivate() will be called in the sys_swapoff() path after -&gt;swap_activate() returned success.

-&gt;swap_rw will be called for swap IO if SWP_FS_OPS was set by -&gt;swap_activate().

<a id="rst-file-lock-operations"></a>

## file_lock_operations

prototypes:



```text
void (*fl_copy_lock)(struct file_lock *, struct file_lock *);
void (*fl_release_private)(struct file_lock *);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


inode-&gt;i_lock

</th>
<th>


may block

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


fl_copy_lock:

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


fl_release_private:

</td>
<td>


maybe

</td>
<td>


maybe\[1\]\_

</td>
</tr>
</tbody>
</table>

<!-- [1]:
->fl_release_private for flock or POSIX locks is currently allowed
to block. Leases however can still be freed while the i_lock is held and
so fl_release_private called on a lease should not block. -->

<a id="rst-lock-manager-operations"></a>

## lock_manager_operations

prototypes:



```text
void (*lm_notify)(struct file_lock *);  /* unblock callback */
int (*lm_grant)(struct file_lock *, struct file_lock *, int);
void (*lm_break)(struct file_lock *); /* break_lease callback */
int (*lm_change)(struct file_lock **, int);
bool (*lm_breaker_owns_lease)(struct file_lock *);
bool (*lm_lock_expirable)(struct file_lock *);
void (*lm_expire_lock)(void);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


flc_lock

</th>
<th>


blocked_lock_lock

</th>
<th>


may block

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


lm_notify:

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_grant:

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_break:

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_change

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_breaker_owns_lease:

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_lock_expirable

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


lm_expire_lock

</td>
<td>


no

</td>
<td>


no

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


lm_open_conflict

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
</tbody>
</table>

<a id="rst-buffer-head"></a>

## buffer_head

prototypes:



```text
void (*b_end_io)(struct buffer_head *bh, int uptodate);
```

locking rules:

called from interrupts. In other words, extreme care is needed here. bh is locked, but that's all warranties we have here. Currently only RAID1, highmem, fs/buffer.c, and fs/ntfs/aops.c are providing these. Block devices call this method upon the IO completion.

<a id="rst-block-device-operations"></a>

## block_device_operations

prototypes:



```text
int (*open) (struct block_device *, fmode_t);
int (*release) (struct gendisk *, fmode_t);
int (*ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
int (*compat_ioctl) (struct block_device *, fmode_t, unsigned, unsigned long);
int (*direct_access) (struct block_device *, sector_t, void **,
                        unsigned long *);
void (*unlock_native_capacity) (struct gendisk *);
int (*getgeo)(struct gendisk *, struct hd_geometry *);
void (*swap_slot_free_notify) (struct block_device *, unsigned long);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


open_mutex

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


open:

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


release:

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


ioctl:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


compat_ioctl:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


direct_access:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


unlock_native_capacity:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


getgeo:

</td>
<td>


no

</td>
</tr>
<tr>
<td>


swap_slot_free_notify:

</td>
<td>


no      (see below)

</td>
</tr>
</tbody>
</table>

swap_slot_free_notify is called with swap_lock and sometimes the page lock held.

<a id="rst-file-operations"></a>

## file_operations

prototypes:



```text
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
int (*iopoll) (struct kiocb *kiocb, bool spin);
int (*iterate_shared) (struct file *, struct dir_context *);
__poll_t (*poll) (struct file *, struct poll_table_struct *);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, loff_t start, loff_t end, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
unsigned long (*get_unmapped_area)(struct file *, unsigned long,
                unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *,
                size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *,
                size_t, unsigned int);
int (*setlease)(struct file *, int, struct file_lease **, void **);
int (*getlease)(struct file *, struct file *lease_file, unsigned int flavor);
long (*fallocate)(struct file *, int, loff_t, loff_t);
void (*show_fdinfo)(struct seq_file *m, struct file *f);
unsigned (*mmap_capabilities)(struct file *);
ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
                loff_t, size_t, unsigned int);
loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
                struct file *file_out, loff_t pos_out,
                loff_t len, unsigned int remap_flags);
int (*fadvise)(struct file *, loff_t, loff_t, int);
```

- **locking rules:**

  All may block.

-&gt;llseek() locking has moved from llseek to the individual llseek implementations.  If your fs is not using generic_file_llseek, you need to acquire and release the appropriate locks in your -&gt;llseek(). For many filesystems, it is probably safe to acquire the inode mutex or just to use i_size_read() instead. Note: this does not protect the file-&gt;f_pos against concurrent modifications since this is something the userspace has to take care about.

-&gt;iterate_shared() is called with i_rwsem held for reading, and with the file f_pos_lock held exclusively

-&gt;fasync() is responsible for maintaining the FASYNC bit in filp-&gt;f_flags. Most instances call fasync_helper(), which does that maintenance, so it's not normally something one needs to worry about.  Return values &gt; 0 will be mapped to zero in the VFS layer.

-&gt;readdir() and -&gt;ioctl() on directories must be changed. Ideally we would move -&gt;readdir() to inode_operations and use a separate method for directory -&gt;ioctl() or kill the latter completely. One of the problems is that for anything that resembles union-mount we won't have a struct file for all components. And there are other reasons why the current interface is a mess...

-&gt;read on directories probably must go away - we should just enforce -EISDIR in sys_read() and friends.

-&gt;setlease operations should call generic_setlease() before or after setting the lease within the individual filesystem to record the result of the operation

-&gt;fallocate implementation must be really careful to maintain page cache consistency when punching holes or performing other operations that invalidate page cache contents. Usually the filesystem needs to call truncate_inode_pages_range() to invalidate relevant range of the page cache. However the filesystem usually also needs to update its internal (and on disk) view of file offset -&gt; disk block mapping. Until this update is finished, the filesystem needs to block page faults and reads from reloading now-stale page cache contents from the disk. Since VFS acquires mapping-&gt;invalidate_lock in shared mode when loading pages from disk (filemap_fault(), filemap_read(), readahead paths), the fallocate implementation must take the invalidate_lock to prevent reloading.

-&gt;copy_file_range and -&gt;remap_file_range implementations need to serialize against modifications of file data while the operation is running. For blocking changes through write(2) and similar operations inode-&gt;i_rwsem can be used. To block changes to file contents via a memory mapping during the operation, the filesystem must take mapping-&gt;invalidate_lock to coordinate with -&gt;page_mkwrite.

<a id="rst-dquot-operations"></a>

## dquot_operations

prototypes:



```text
int (*write_dquot) (struct dquot *);
int (*acquire_dquot) (struct dquot *);
int (*release_dquot) (struct dquot *);
int (*mark_dirty) (struct dquot *);
int (*write_info) (struct super_block *, int);
```

These operations are intended to be more or less wrapping functions that ensure a proper locking wrt the filesystem and call the generic quota operations.

What filesystem should expect from the generic quota functions:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


FS recursion

</th>
<th>


Held locks when called

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


write_dquot:

</td>
<td>


yes

</td>
<td>


dqonoff_sem or dqptr_sem

</td>
</tr>
<tr>
<td>


acquire_dquot:

</td>
<td>


yes

</td>
<td>


dqonoff_sem or dqptr_sem

</td>
</tr>
<tr>
<td>


release_dquot:

</td>
<td>


yes

</td>
<td>


dqonoff_sem or dqptr_sem

</td>
</tr>
<tr>
<td>


mark_dirty:

</td>
<td>


no

</td>
<td>


- <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


write_info:

</td>
<td>


yes

</td>
<td>


dqonoff_sem

</td>
</tr>
</tbody>
</table>

FS recursion means calling -&gt;quota_read() and -&gt;quota_write() from superblock operations.

More details about quota locking can be found in fs/dquot.c.

<a id="rst-vm-operations-struct"></a>

## vm_operations_struct

prototypes:



```text
void (*open)(struct vm_area_struct *);
void (*close)(struct vm_area_struct *);
vm_fault_t (*fault)(struct vm_fault *);
vm_fault_t (*huge_fault)(struct vm_fault *, unsigned int order);
vm_fault_t (*map_pages)(struct vm_fault *, pgoff_t start, pgoff_t end);
vm_fault_t (*page_mkwrite)(struct vm_area_struct *, struct vm_fault *);
vm_fault_t (*pfn_mkwrite)(struct vm_area_struct *, struct vm_fault *);
int (*access)(struct vm_area_struct *, unsigned long, void*, int, int);
```

locking rules:


<table>
<thead>
<tr>
<th>


ops

</th>
<th>


mmap_lock

</th>
<th>


PageLocked(page)

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


open:

</td>
<td>


write

</td>
<td>




</td>
</tr>
<tr>
<td>


close:

</td>
<td>


read/write

</td>
<td>




</td>
</tr>
<tr>
<td>


fault:

</td>
<td>


read

</td>
<td>


can return with page locked

</td>
</tr>
<tr>
<td>


huge_fault:

</td>
<td>


maybe-read

</td>
<td>




</td>
</tr>
<tr>
<td>


map_pages:

</td>
<td>


maybe-read

</td>
<td>




</td>
</tr>
<tr>
<td>


page_mkwrite:

</td>
<td>


read

</td>
<td>


can return with page locked

</td>
</tr>
<tr>
<td>


pfn_mkwrite:

</td>
<td>


read

</td>
<td>




</td>
</tr>
<tr>
<td>


access:

</td>
<td>


read

</td>
<td>




</td>
</tr>
</tbody>
</table>

-&gt;fault() is called when a previously not present pte is about to be faulted in. The filesystem must find and return the page associated with the passed in "pgoff" in the vm_fault structure. If it is possible that the page may be truncated and/or invalidated, then the filesystem must lock invalidate_lock, then ensure the page is not already truncated (invalidate_lock will block subsequent truncate), and then return with VM_FAULT_LOCKED, and the page locked. The VM will unlock the page.

-&gt;huge_fault() is called when there is no PUD or PMD entry present.  This gives the filesystem the opportunity to install a PUD or PMD sized page. Filesystems can also use the -&gt;fault method to return a PMD sized page, so implementing this function may not be necessary.  In particular, filesystems should not call filemap_fault() from -&gt;huge_fault(). The mmap_lock may not be held when this method is called.

-&gt;map_pages() is called when VM asks to map easy accessible pages. Filesystem should find and map pages associated with offsets from "start_pgoff" till "end_pgoff". -&gt;map_pages() is called with the RCU lock held and must not block.  If it's not possible to reach a page without blocking, filesystem should skip it. Filesystem should use set_pte_range() to setup page table entry. Pointer to entry associated with the page is passed in "pte" field in vm_fault structure. Pointers to entries for other offsets should be calculated relative to "pte".

-&gt;page_mkwrite() is called when a previously read-only pte is about to become writeable. The filesystem again must ensure that there are no truncate/invalidate races or races with operations such as -&gt;remap_file_range or -&gt;copy_file_range, and then return with the page locked. Usually mapping-&gt;invalidate_lock is suitable for proper serialization. If the page has been truncated, the filesystem should not look up a new page like the -&gt;fault() handler, but simply return with VM_FAULT_NOPAGE, which will cause the VM to retry the fault.

-&gt;pfn_mkwrite() is the same as page_mkwrite but when the pte is VM_PFNMAP or VM_MIXEDMAP with a page-less entry. Expected return is VM_FAULT_NOPAGE. Or one of the VM_FAULT_ERROR types. The default behavior after this call is to make the pte read-write, unless pfn_mkwrite returns an error.

-&gt;access() is called when get_user_pages() fails in access_process_vm(), typically used to debug a process through /proc/pid/mem or ptrace.  This function is needed only for VM_IO \| VM_PFNMAP VMAs.

---

> Dubious stuff

(if you break something or notice that it is broken and do not fix it yourself - at least put it here)

---

# File Locking Release Notes

_Peios Kernel / Internals / Filesystems_

> Andy Walker <andy@lysaker.kvaerner.no>

<a id="rst-file-locking-release-notes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Andy Walker &lt;[andy@lysaker.kvaerner.no](<mailto:andy@lysaker.kvaerner.no>)&gt;
>
> > 12 May 1997

<a id="rst-what-s-new"></a>

## 1. What's New?

<a id="rst-broken-flock-emulation"></a>

### 1.1 Broken Flock Emulation

The old flock(2) emulation in the kernel was swapped for proper BSD compatible flock(2) support in the 1.3.x series of kernels. With the release of the 2.1.x kernel series, support for the old emulation has been totally removed, so that we don't need to carry this baggage forever.

This should not cause problems for anybody, since everybody using a 2.1.x kernel should have updated their C library to a suitable version anyway (see the file "[Documentation/process/changes.rst](/kernel/development/process/changes.md)".)

<a id="rst-allow-mixed-locks-again"></a>

### 1.2 Allow Mixed Locks Again

<a id="rst-typical-problems-sendmail"></a>

#### 1.2.1 Typical Problems - Sendmail

Because sendmail was unable to use the old flock() emulation, many sendmail installations use fcntl() instead of flock(). This is true of Slackware 3.0 for example. This gave rise to some other subtle problems if sendmail was configured to rebuild the alias file. Sendmail tried to lock the aliases.dir file with fcntl() at the same time as the GDBM routines tried to lock this file with flock(). With pre 1.3.96 kernels this could result in deadlocks that, over time, or under a very heavy mail load, would eventually cause the kernel to lock solid with deadlocked processes.

<a id="rst-the-solution"></a>

#### 1.2.2 The Solution

The solution I have chosen, after much experimentation and discussion, is to make flock() and fcntl() locks oblivious to each other. Both can exists, and neither will have any effect on the other.

I wanted the two lock styles to be cooperative, but there were so many race and deadlock conditions that the current solution was the only practical one. It puts us in the same position as, for example, SunOS 4.1.x and several other commercial Unices. The only OS's that support cooperative flock()/fcntl() are those that emulate flock() using fcntl(), with all the problems that implies.

<a id="rst-mandatory-locking-as-a-mount-option"></a>

### 1.3 Mandatory Locking As A Mount Option

Mandatory locking was prior to this release a general configuration option that was valid for all mounted filesystems.  This had a number of inherent dangers, not the least of which was the ability to freeze an NFS server by asking it to read a file for which a mandatory lock existed.

Such option was dropped in Kernel v5.14.

---

# Filesystem Mount API

_Peios Kernel / Internals / Filesystems_

> The creation of new mounts is now to be done in a multistep process:

<a id="rst-filesystem-mount-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- CONTENTS

(1) Overview.

(2) The filesystem context.

(3) The filesystem context operations.

(4) Filesystem context security.

(5) VFS filesystem context API.

(6) Superblock creation helpers.

(7) Parameter description.

(8) Parameter helper functions. -->

<a id="rst-overview"></a>

## Overview

The creation of new mounts is now to be done in a multistep process:

> 1. Create a filesystem context.
>
> 2. Parse the parameters and attach them to the context.  Parameters are expected to be passed individually from userspace, though legacy binary parameters can also be handled.
>
> 3. Validate and pre-process the context.
>
> 4. Get or create a superblock and mountable root.
>
> 5. Perform the mount.
>
> 6. Return an error message attached to the context.
>
> 7. Destroy the context.

To support this, the file_system_type struct gains two new fields:



```text
int (*init_fs_context)(struct fs_context *fc);
const struct fs_parameter_description *parameters;
```

The first is invoked to set up the filesystem-specific parts of a filesystem context, including the additional space, and the second points to the parameter description for validation at registration time and querying by a future system call.

Note that security initialisation is done *after* the filesystem is called so that the namespaces may be adjusted first.

<a id="rst-the-filesystem-context"></a>

## The Filesystem context

The creation and reconfiguration of a superblock is governed by a filesystem context.  This is represented by the fs_context structure:



```text
struct fs_context {
        const struct fs_context_operations *ops;
        struct file_system_type *fs_type;
        void                    *fs_private;
        struct dentry           *root;
        struct user_namespace   *user_ns;
        struct net              *net_ns;
        const struct cred       *cred;
        char                    *source;
        char                    *subtype;
        void                    *security;
        void                    *s_fs_info;
        unsigned int            sb_flags;
        unsigned int            sb_flags_mask;
        unsigned int            s_iflags;
        enum fs_context_purpose purpose:8;
        ...
};
```

The fs_context fields are as follows:

> - 
>
>   ```text
>   const struct fs_context_operations *ops
>   ```
>
>   These are operations that can be done on a filesystem context (see below).  This must be set by the -&gt;init_fs_context() file_system_type operation.
>
> - 
>
>   ```text
>   struct file_system_type *fs_type
>   ```
>
>   A pointer to the file_system_type of the filesystem that is being constructed or reconfigured.  This retains a reference on the type owner.
>
> - 
>
>   ```text
>   void *fs_private
>   ```
>
>   A pointer to the file system's private data.  This is where the filesystem will need to store any options it parses.
>
> - 
>
>   ```text
>   struct dentry *root
>   ```
>
>   A pointer to the root of the mountable tree (and indirectly, the superblock thereof).  This is filled in by the -&gt;get_tree() op.  If this is set, an active reference on root-&gt;d_sb must also be held.
>
> - 
>
>   ```text
>   struct user_namespace *user_ns
>   struct net *net_ns
>   ```
>
>   There are a subset of the namespaces in use by the invoking process.  They retain references on each namespace.  The subscribed namespaces may be replaced by the filesystem to reflect other sources, such as the parent mount superblock on an automount.
>
> - 
>
>   ```text
>   const struct cred *cred
>   ```
>
>   The mounter's credentials.  This retains a reference on the credentials.
>
> - 
>
>   ```text
>   char *source
>   ```
>
>   This specifies the source.  It may be a block device (e.g. /dev/sda1) or something more exotic, such as the "host:/path" that NFS desires.
>
> - 
>
>   ```text
>   char *subtype
>   ```
>
>   This is a string to be added to the type displayed in /proc/mounts to qualify it (used by FUSE).  This is available for the filesystem to set if desired.
>
> - 
>
>   ```text
>   void *security
>   ```
>
>   A place for the LSMs to hang their security data for the superblock.  The relevant security operations are described below.
>
> - 
>
>   ```text
>   void *s_fs_info
>   ```
>
>   The proposed s_fs_info for a new superblock, set in the superblock by sget_fc().  This can be used to distinguish superblocks.
>
> - 
>
>   ```text
>   unsigned int sb_flags
>   unsigned int sb_flags_mask
>   ```
>
>   Which bits SB\_\* flags are to be set/cleared in super_block::s_flags.
>
> - 
>
>   ```text
>   unsigned int s_iflags
>   ```
>
>   These will be bitwise-OR'd with s-&gt;s_iflags when a superblock is created.
>
> - 
>
>   ```text
>   enum fs_context_purpose
>   ```
>
>   This indicates the purpose for which the context is intended.  The available values are:
>
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > FS_CONTEXT_FOR_MOUNT,
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > New superblock for explicit mount
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > FS_CONTEXT_FOR_SUBMOUNT
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > New automatic submount of extant mount
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > FS_CONTEXT_FOR_RECONFIGURE
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Change an existing mount
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>

The mount context is created by calling vfs_new_fs_context() or vfs_dup_fs_context() and is destroyed with put_fs_context().  Note that the structure is not refcounted.

VFS, security and filesystem mount options are set individually with vfs_parse_mount_option().  Options provided by the old mount(2) system call as a page of data can be parsed with generic_parse_monolithic().

When mounting, the filesystem is allowed to take data from any of the pointers and attach it to the superblock (or whatever), provided it clears the pointer in the mount context.

The filesystem is also allowed to allocate resources and pin them with the mount context.  For instance, NFS might pin the appropriate protocol version module.

<a id="rst-the-filesystem-context-operations"></a>

## The Filesystem Context Operations

The filesystem context points to a table of operations:



```text
struct fs_context_operations {
        void (*free)(struct fs_context *fc);
        int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
        int (*parse_param)(struct fs_context *fc,
                           struct fs_parameter *param);
        int (*parse_monolithic)(struct fs_context *fc, void *data);
        int (*get_tree)(struct fs_context *fc);
        int (*reconfigure)(struct fs_context *fc);
};
```

These operations are invoked by the various stages of the mount procedure to manage the filesystem context.  They are as follows:

> - 
>
>   ```text
>   void (*free)(struct fs_context *fc);
>   ```
>
>   Called to clean up the filesystem-specific part of the filesystem context when the context is destroyed.  It should be aware that parts of the context may have been removed and NULL'd out by -&gt;get_tree().
>
> - 
>
>   ```text
>   int (*dup)(struct fs_context *fc, struct fs_context *src_fc);
>   ```
>
>   Called when a filesystem context has been duplicated to duplicate the filesystem-private data.  An error may be returned to indicate failure to do this.
>
>   > [!WARNING]
>   >
>   > Note that even if this fails, put_fs_context() will be called immediately thereafter, so -&gt;dup() *must* make the filesystem-private data safe for -&gt;free().
>
> - 
>
>   ```text
>   int (*parse_param)(struct fs_context *fc,
>                      struct fs_parameter *param);
>   ```
>
>   Called when a parameter is being added to the filesystem context.  param points to the key name and maybe a value object.  VFS-specific options will have been weeded out and fc-&gt;sb_flags updated in the context. Security options will also have been weeded out and fc-&gt;security updated.
>
>   The parameter can be parsed with fs_parse() and fs_lookup_param().  Note that the source(s) are presented as parameters named "source".
>
>   If successful, 0 should be returned or a negative error code otherwise.
>
> - 
>
>   ```text
>   int (*parse_monolithic)(struct fs_context *fc, void *data);
>   ```
>
>   Called when the mount(2) system call is invoked to pass the entire data page in one go.  If this is expected to be just a list of "key\[=val\]" items separated by commas, then this may be set to NULL.
>
>   The return value is as for -&gt;parse_param().
>
>   If the filesystem (e.g. NFS) needs to examine the data first and then finds it's the standard key-val list then it may pass it off to generic_parse_monolithic().
>
> - 
>
>   ```text
>   int (*get_tree)(struct fs_context *fc);
>   ```
>
>   Called to get or create the mountable root and superblock, using the information stored in the filesystem context (reconfiguration goes via a different vector).  It may detach any resources it desires from the filesystem context and transfer them to the superblock it creates.
>
>   On success it should set fc-&gt;root to the mountable root and return 0.  In the case of an error, it should return a negative error code.
>
>   The phase on a userspace-driven context will be set to only allow this to be called once on any particular context.
>
> - 
>
>   ```text
>   int (*reconfigure)(struct fs_context *fc);
>   ```
>
>   Called to effect reconfiguration of a superblock using information stored in the filesystem context.  It may detach any resources it desires from the filesystem context and transfer them to the superblock.  The superblock can be found from fc-&gt;root-&gt;d_sb.
>
>   On success it should return 0.  In the case of an error, it should return a negative error code.

<a id="rst-filesystem-context-security"></a>

## Filesystem context Security

The filesystem context contains a security pointer that the LSMs can use for building up a security context for the superblock to be mounted.  There are a number of operations used by the new mount code for this purpose:

> - 
>
>   ```text
>   int security_fs_context_alloc(struct fs_context *fc,
>                                 struct dentry *reference);
>   ```
>
>   Called to initialise fc-&gt;security (which is preset to NULL) and allocate any resources needed.  It should return 0 on success or a negative error code on failure.
>
>   reference will be non-NULL if the context is being created for superblock reconfiguration (FS_CONTEXT_FOR_RECONFIGURE) in which case it indicates the root dentry of the superblock to be reconfigured.  It will also be non-NULL in the case of a submount (FS_CONTEXT_FOR_SUBMOUNT) in which case it indicates the automount point.
>
> - 
>
>   ```text
>   int security_fs_context_dup(struct fs_context *fc,
>                               struct fs_context *src_fc);
>   ```
>
>   Called to initialise fc-&gt;security (which is preset to NULL) and allocate any resources needed.  The original filesystem context is pointed to by src_fc and may be used for reference.  It should return 0 on success or a negative error code on failure.
>
> - 
>
>   ```text
>   void security_fs_context_free(struct fs_context *fc);
>   ```
>
>   Called to clean up anything attached to fc-&gt;security.  Note that the contents may have been transferred to a superblock and the pointer cleared during get_tree.
>
> - 
>
>   ```text
>   int security_fs_context_parse_param(struct fs_context *fc,
>                                       struct fs_parameter *param);
>   ```
>
>   Called for each mount parameter, including the source.  The arguments are as for the -&gt;parse_param() method.  It should return 0 to indicate that the parameter should be passed on to the filesystem, 1 to indicate that the parameter should be discarded or an error to indicate that the parameter should be rejected.
>
>   The value pointed to by param may be modified (if a string) or stolen (provided the value pointer is NULL'd out).  If it is stolen, 1 must be returned to prevent it being passed to the filesystem.
>
> - 
>
>   ```text
>   int security_fs_context_validate(struct fs_context *fc);
>   ```
>
>   Called after all the options have been parsed to validate the collection as a whole and to do any necessary allocation so that security_sb_get_tree() and security_sb_reconfigure() are less likely to fail.  It should return 0 or a negative error code.
>
>   In the case of reconfiguration, the target superblock will be accessible via fc-&gt;root.
>
> - 
>
>   ```text
>   int security_sb_get_tree(struct fs_context *fc);
>   ```
>
>   Called during the mount procedure to verify that the specified superblock is allowed to be mounted and to transfer the security data there.  It should return 0 or a negative error code.
>
> - 
>
>   ```text
>   void security_sb_reconfigure(struct fs_context *fc);
>   ```
>
>   Called to apply any reconfiguration to an LSM's context.  It must not fail.  Error checking and resource allocation must be done in advance by the parameter parsing and validation hooks.
>
> - 
>
>   ```text
>   int security_sb_mountpoint(struct fs_context *fc,
>                              struct path *mountpoint,
>                              unsigned int mnt_flags);
>   ```
>
>   Called during the mount procedure to verify that the root dentry attached to the context is permitted to be attached to the specified mountpoint. It should return 0 on success or a negative error code on failure.

<a id="rst-vfs-filesystem-context-api"></a>

## VFS Filesystem context API

There are four operations for creating a filesystem context and one for destroying a context:

> - 
>
>   ```text
>   struct fs_context *fs_context_for_mount(struct file_system_type *fs_type,
>                                           unsigned int sb_flags);
>   ```
>
>   Allocate a filesystem context for the purpose of setting up a new mount, whether that be with a new superblock or sharing an existing one.  This sets the superblock flags, initialises the security and calls fs_type-&gt;init_fs_context() to initialise the filesystem private data.
>
>   fs_type specifies the filesystem type that will manage the context and sb_flags presets the superblock flags stored therein.
>
> - 
>
>   ```text
>   struct fs_context *fs_context_for_reconfigure(
>            struct dentry *dentry,
>            unsigned int sb_flags,
>            unsigned int sb_flags_mask);
>   ```
>
>   Allocate a filesystem context for the purpose of reconfiguring an existing superblock.  dentry provides a reference to the superblock to be configured.  sb_flags and sb_flags_mask indicate which superblock flags need changing and to what.
>
> - 
>
>   ```text
>   struct fs_context *fs_context_for_submount(
>            struct file_system_type *fs_type,
>            struct dentry *reference);
>   ```
>
>   Allocate a filesystem context for the purpose of creating a new mount for an automount point or other derived superblock.  fs_type specifies the filesystem type that will manage the context and the reference dentry supplies the parameters.  Namespaces are propagated from the reference dentry's superblock also.
>
>   Note that it's not a requirement that the reference dentry be of the same filesystem type as fs_type.
>
> - 
>
>   ```text
>   struct fs_context *vfs_dup_fs_context(struct fs_context *src_fc);
>   ```
>
>   Duplicate a filesystem context, copying any options noted and duplicating or additionally referencing any resources held therein.  This is available for use where a filesystem has to get a mount within a mount, such as NFS4 does by internally mounting the root of the target server and then doing a private pathwalk to the target directory.
>
>   The purpose in the new context is inherited from the old one.
>
> - 
>
>   ```text
>   void put_fs_context(struct fs_context *fc);
>   ```
>
>   Destroy a filesystem context, releasing any resources it holds.  This calls the -&gt;free() operation.  This is intended to be called by anyone who created a filesystem context.
>
>   > [!WARNING]
>   >
>   > filesystem contexts are not refcounted, so this causes unconditional destruction.

In all the above operations, apart from the put op, the return is a mount context pointer or a negative error code.

For the remaining operations, if an error occurs, a negative error code will be returned.

> - 
>
>   ```text
>   int vfs_parse_fs_param(struct fs_context *fc,
>                          struct fs_parameter *param);
>   ```
>
>   Supply a single mount parameter to the filesystem context.  This includes the specification of the source/device which is specified as the "source" parameter (which may be specified multiple times if the filesystem supports that).
>
>   param specifies the parameter key name and the value.  The parameter is first checked to see if it corresponds to a standard mount flag (in which case it is used to set an SB_xxx flag and consumed) or a security option (in which case the LSM consumes it) before it is passed on to the filesystem.
>
>   The parameter value is typed and can be one of:
>
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > fs_value_is_flag
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Parameter not given a value
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > fs_value_is_string
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Value is a string
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > fs_value_is_blob
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Value is a binary blob
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > fs_value_is_filename
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Value is a filename\* + dirfd
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > fs_value_is_file
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Value is an open file (file\*)
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>
>
>   If there is a value, that value is stored in a union in the struct in one of param-&gt;\{string,blob,name,file\}.  Note that the function may steal and clear the pointer, but then becomes responsible for disposing of the object.
>
> - 
>
>   ```text
>   int vfs_parse_fs_qstr(struct fs_context *fc, const char *key,
>                           const struct qstr *value);
>   ```
>
>   A wrapper around vfs_parse_fs_param() that copies the value string it is passed.
>
> - 
>
>   ```text
>   int vfs_parse_fs_string(struct fs_context *fc, const char *key,
>                           const char *value);
>   ```
>
>   A wrapper around vfs_parse_fs_param() that copies the value string it is passed.
>
> - 
>
>   ```text
>   int generic_parse_monolithic(struct fs_context *fc, void *data);
>   ```
>
>   Parse a sys_mount() data page, assuming the form to be a text list consisting of key\[=val\] options separated by commas.  Each item in the list is passed to vfs_mount_option().  This is the default when the -&gt;parse_monolithic() method is NULL.
>
> - 
>
>   ```text
>   int vfs_get_tree(struct fs_context *fc);
>   ```
>
>   Get or create the mountable root and superblock, using the parameters in the filesystem context to select/configure the superblock.  This invokes the -&gt;get_tree() method.
>
> - 
>
>   ```text
>   struct vfsmount *vfs_create_mount(struct fs_context *fc);
>   ```
>
>   Create a mount given the parameters in the specified filesystem context. Note that this does not attach the mount to anything.

<a id="rst-superblock-creation-helpers"></a>

## Superblock Creation Helpers

A number of VFS helpers are available for use by filesystems for the creation or looking up of superblocks.

> - 
>
>   ```text
>   struct super_block *
>   sget_fc(struct fs_context *fc,
>           int (*test)(struct super_block *sb, struct fs_context *fc),
>           int (*set)(struct super_block *sb, struct fs_context *fc));
>   ```
>
>   This is the core routine.  If test is non-NULL, it searches for an existing superblock matching the criteria held in the fs_context, using the test function to match them.  If no match is found, a new superblock is created and the set function is called to set it up.
>
>   Prior to the set function being called, fc-&gt;s_fs_info will be transferred to sb-&gt;s_fs_info - and fc-&gt;s_fs_info will be cleared if set returns success (ie. 0).

The following helpers all wrap sget_fc():

> 1. vfs_get_single_super
>
>    Only one such superblock may exist in the system.  Any further attempt to get a new superblock gets this one (and any parameter differences are ignored).
>
> 2. vfs_get_keyed_super
>
>    Multiple superblocks of this type may exist and they're keyed on their s_fs_info pointer (for example this may refer to a namespace).
>
> 3. vfs_get_independent_super
>
>    Multiple independent superblocks of this type may exist.  This function never matches an existing one and always creates a new one.

<a id="rst-parameter-description"></a>

## Parameter Description

Parameters are described using structures defined in linux/fs_parser.h. There's a core description struct that links everything together:



```text
struct fs_parameter_description {
        const struct fs_parameter_spec *specs;
        const struct fs_parameter_enum *enums;
};
```

For example:



```text
enum {
        Opt_autocell,
        Opt_bar,
        Opt_dyn,
        Opt_foo,
        Opt_source,
};

static const struct fs_parameter_description afs_fs_parameters = {
        .specs          = afs_param_specs,
        .enums          = afs_param_enums,
};
```

The members are as follows:

> 1. 
>
>    ```text
>    const struct fs_parameter_specification *specs;
>    ```
>
>    Table of parameter specifications, terminated with a null entry, where the entries are of type:
>
>
>
>    ```text
>    struct fs_parameter_spec {
>            const char              *name;
>            u8                      opt;
>            enum fs_parameter_type  type:8;
>            unsigned short          flags;
>    };
>    ```
>
>    The 'name' field is a string to match exactly to the parameter key (no wildcards, patterns and no case-independence) and 'opt' is the value that will be returned by the fs_parser() function in the case of a successful match.
>
>    The 'type' field indicates the desired value type and must be one of:
>
>    >
>    > <table>
>    > <thead>
>    > <tr>
>    > <th>
>    >
>    >
>    > TYPE NAME
>    >
>    > </th>
>    > <th>
>    >
>    >
>    > EXPECTED VALUE
>    >
>    > </th>
>    > <th>
>    >
>    >
>    > RESULT IN
>    >
>    > </th>
>    > </tr>
>    > </thead>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_flag
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > No value
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > n/a
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_bool
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Boolean value
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;boolean
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_u32
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > 32-bit unsigned int
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uint_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_u32_octal
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > 32-bit octal int
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uint_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_u32_hex
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > 32-bit hex int
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uint_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_s32
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > 32-bit signed int
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;int_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_u64
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > 64-bit unsigned int
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uint_64
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_enum
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Enum value name
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uint_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_string
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Arbitrary string
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > param-&gt;string
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_blob
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Binary blob
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > param-&gt;blob
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_blockdev
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Blockdev path
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > - Needs lookup
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_path
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Path
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > - Needs lookup
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_fd
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > File descriptor
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;int_32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_uid
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > User ID (u32)
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;uid
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_is_gid
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Group ID (u32)
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;gid
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    Note that if the value is of fs_param_is_bool type, fs_parse() will try to match any string value against "0", "1", "no", "yes", "false", "true".
>
>    Each parameter can also be qualified with 'flags':
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_v_optional
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > The value is optional
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_neg_with_no
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;negated set if key is prefixed with "no"
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_neg_with_empty
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > result-&gt;negated set if value is ""
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fs_param_deprecated
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > The parameter is deprecated.
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    These are wrapped with a number of convenience wrappers:
>
>    >
>    > <table>
>    > <thead>
>    > <tr>
>    > <th>
>    >
>    >
>    > MACRO
>    >
>    > </th>
>    > <th>
>    >
>    >
>    > SPECIFIES
>    >
>    > </th>
>    > </tr>
>    > </thead>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_flag()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_flag
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_flag_no()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_flag, fs_param_neg_with_no
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_bool()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_bool
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_u32()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_u32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_u32oct()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_u32_octal
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_s32()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_s32
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_u64()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_u64
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_enum()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_enum
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_string()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_string
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_blob()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_blob
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_bdev()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_blockdev
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_path()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_path
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_fd()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_fd
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_uid()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_uid
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > fsparam_gid()
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > fs_param_is_gid
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    all of which take two arguments, name string and option number - for example:
>
>
>
>    ```text
>    static const struct fs_parameter_spec afs_param_specs[] = {
>            fsparam_flag    ("autocell",    Opt_autocell),
>            fsparam_flag    ("dyn",         Opt_dyn),
>            fsparam_string  ("source",      Opt_source),
>            fsparam_flag_no ("foo",         Opt_foo),
>            {}
>    };
>    ```
>
>    An addition macro, \__fsparam() is provided that takes an additional pair of arguments to specify the type and the flags for anything that doesn't match one of the above macros.
>
> 2. 
>
>    ```text
>    const struct fs_parameter_enum *enums;
>    ```
>
>    Table of enum value names to integer mappings, terminated with a null entry.  This is of type:
>
>
>
>    ```text
>    struct fs_parameter_enum {
>            u8              opt;
>            char            name[14];
>            u8              value;
>    };
>    ```
>
>    Where the array is an unsorted list of \{ parameter ID, name \}-keyed elements that indicate the value to map to, e.g.:
>
>
>
>    ```text
>    static const struct fs_parameter_enum afs_param_enums[] = {
>            { Opt_bar,   "x",      1},
>            { Opt_bar,   "y",      23},
>            { Opt_bar,   "z",      42},
>    };
>    ```
>
>    If a parameter of type fs_param_is_enum is encountered, fs_parse() will try to look the value up in the enum table and the result will be stored in the parse result.

The parser should be pointed to by the parser pointer in the file_system_type struct as this will provide validation on registration (if CONFIG_VALIDATE_FS_PARSER=y) and will allow the description to be queried from userspace using the fsinfo() syscall.

<a id="rst-parameter-helper-functions"></a>

## Parameter Helper Functions

A number of helper functions are provided to help a filesystem or an LSM process the parameters it is given.

> - 
>
>   ```text
>   int lookup_constant(const struct constant_table tbl[],
>                       const char *name, int not_found);
>   ```
>
>   Look up a constant by name in a table of name -&gt; integer mappings.  The table is an array of elements of the following type:
>
>
>
>   ```text
>   struct constant_table {
>           const char      *name;
>           int             value;
>   };
>   ```
>
>   If a match is found, the corresponding value is returned.  If a match isn't found, the not_found value is returned instead.
>
> - 
>
>   ```text
>   bool fs_validate_description(const char *name,
>                                const struct fs_parameter_description *desc);
>   ```
>
>   This performs some validation checks on a parameter description.  It returns true if the description is good and false if it is not.  It will log errors to the kernel log buffer if validation fails.
>
> - 
>
>   ```text
>   int fs_parse(struct fs_context *fc,
>                const struct fs_parameter_description *desc,
>                struct fs_parameter *param,
>                struct fs_parse_result *result);
>   ```
>
>   This is the main interpreter of parameters.  It uses the parameter description to look up a parameter by key name and to convert that to an option number (which it returns).
>
>   If successful, and if the parameter type indicates the result is a boolean, integer, enum, uid, or gid type, the value is converted by this function and the result stored in result-&gt;\{boolean,int_32,uint_32,uint_64,uid,gid\}.
>
>   If a match isn't initially made, the key is prefixed with "no" and no value is present then an attempt will be made to look up the key with the prefix removed.  If this matches a parameter for which the type has flag fs_param_neg_with_no set, then a match will be made and result-&gt;negated will be set to true.
>
>   If the parameter isn't matched, -ENOPARAM will be returned; if the parameter is matched, but the value is erroneous, -EINVAL will be returned; otherwise the parameter's option number will be returned.
>
> - 
>
>   ```text
>   int fs_lookup_param(struct fs_context *fc,
>                       struct fs_parameter *value,
>                       bool want_bdev,
>                       unsigned int flags,
>                       struct path *_path);
>   ```
>
>   This takes a parameter that carries a string or filename type and attempts to do a path lookup on it.  If the parameter expects a blockdev, a check is made that the inode actually represents one.
>
>   Returns 0 if successful and `*_path` will be set; returns a negative error code if not.

---

# Multigrain Timestamps

_Peios Kernel / Internals / Filesystems_

> Historically, the kernel has always used coarse time values to stamp inodes. This value is updated every jiffy, so any change that happens within that jiffy will end up with the same timestamp.

<a id="rst-multigrain-timestamps"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Historically, the kernel has always used coarse time values to stamp inodes. This value is updated every jiffy, so any change that happens within that jiffy will end up with the same timestamp.

When the kernel goes to stamp an inode (due to a read or write), it first gets the current time and then compares it to the existing timestamp(s) to see whether anything will change. If nothing changed, then it can avoid updating the inode's metadata.

Coarse timestamps are therefore good from a performance standpoint, since they reduce the need for metadata updates, but bad from the standpoint of determining whether anything has changed, since a lot of things can happen in a jiffy.

They are particularly troublesome with NFSv3, where unchanging timestamps can make it difficult to tell whether to invalidate caches. NFSv4 provides a dedicated change attribute that should always show a visible change, but not all filesystems implement this properly, causing the NFS server to substitute the ctime in many cases.

Multigrain timestamps aim to remedy this by selectively using fine-grained timestamps when a file has had its timestamps queried recently, and the current coarse-grained time does not cause a change.

<a id="rst-inode-timestamps"></a>

## Inode Timestamps

There are currently 3 timestamps in the inode that are updated to the current wallclock time on different activity:

- **ctime:**

  The inode change time. This is stamped with the current time whenever the inode's metadata is changed. Note that this value is not settable from userland.

- **mtime:**

  The inode modification time. This is stamped with the current time any time a file's contents change.

- **atime:**

  The inode access time. This is stamped whenever an inode's contents are read. Widely considered to be a terrible mistake. Usually avoided with options like noatime or relatime.

Updating the mtime always implies a change to the ctime, but updating the atime due to a read request does not.

Multigrain timestamps are only tracked for the ctime and the mtime. atimes are not affected and always use the coarse-grained value (subject to the floor).

<a id="rst-inode-timestamp-ordering"></a>

## Inode Timestamp Ordering

In addition to just providing info about changes to individual files, file timestamps also serve an important purpose in applications like "make". These programs measure timestamps in order to determine whether source files might be newer than cached objects.

Userland applications like make can only determine ordering based on operational boundaries. For a syscall those are the syscall entry and exit points. For io_uring or nfsd operations, that's the request submission and response. In the case of concurrent operations, userland can make no determination about the order in which things will occur.

For instance, if a single thread modifies one file, and then another file in sequence, the second file must show an equal or later mtime than the first. The same is true if two threads are issuing similar operations that do not overlap in time.

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

Note that the above assumes that the system doesn't experience a backward jump of the realtime clock. If that occurs at an inopportune time, then timestamps can appear to go backward, even on a properly functioning system.

<a id="rst-multigrain-timestamp-implementation"></a>

## Multigrain Timestamp Implementation

Multigrain timestamps are aimed at ensuring that changes to a single file are always recognizable, without violating the ordering guarantees when multiple different files are modified. This affects the mtime and the ctime, but the atime will always use coarse-grained timestamps.

It uses an unused bit in the i_ctime_nsec field to indicate whether the mtime or ctime has been queried. If either or both have, then the kernel takes special care to ensure the next timestamp update will display a visible change. This ensures tight cache coherency for use-cases like NFS, without sacrificing the benefits of reduced metadata updates when files aren't being watched.

<a id="rst-the-ctime-floor-value"></a>

## The Ctime Floor Value

It's not sufficient to simply use fine or coarse-grained timestamps based on whether the mtime or ctime has been queried. A file could get a fine grained timestamp, and then a second file modified later could get a coarse-grained one that appears earlier than the first, which would break the kernel's timestamp ordering guarantees.

To mitigate this problem, maintain a global floor value that ensures that this can't happen. The two files in the above example may appear to have been modified at the same time in such a case, but they will never show the reverse order. To avoid problems with realtime clock jumps, the floor is managed as a monotonic ktime_t, and the values are converted to realtime clock values as needed.

<a id="rst-implementation-notes"></a>

## Implementation Notes

Multigrain timestamps are intended for use by local filesystems that get ctime values from the local clock. This is in contrast to network filesystems and the like that just mirror timestamp values from a server.

For most filesystems, it's sufficient to just set the FS_MGTIME flag in the fstype-&gt;fs_flags in order to opt-in, providing the ctime is only ever set via inode_set_ctime_current(). If the filesystem has a -&gt;getattr routine that doesn't call generic_fillattr, then it should call fill_mg_cmtime() to fill those values. For setattr, it should use setattr_copy() to update the timestamps, or otherwise mimic its behavior.

---

# Network Filesystem Services Library

_Peios Kernel / Internals / Filesystems_

> The network filesystem services library, netfslib, is a set of functions designed to aid a network filesystem in implementing VM/VFS API operations. It takes over the normal buffered read, readahead, write and writeback and also handles…

<a id="rst-network-filesystem-services-library"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

- Overview.
  - Requests and streams.
  - Subrequests.
  - Result collection and retry.
  - Local caching.
  - Content encryption (fscrypt).
- Per-inode context.
  - Inode context helper functions.
  - Inode locking.
  - Inode writeback.
- High-level VFS API.
  - Unlocked read/write iter.
  - Pre-locked read/write iter.
  - Monolithic files API.
  - Memory-mapped I/O API.
- High-level VM API.
  - Deprecated PG_private2 API.
- I/O request API.
  - Request structure.
  - Stream structure.
  - Subrequest structure.
  - Filesystem methods.
  - Terminating a subrequest.
  - Local cache API.
- API function reference. -->

<a id="rst-overview"></a>

## Overview

The network filesystem services library, netfslib, is a set of functions designed to aid a network filesystem in implementing VM/VFS API operations.  It takes over the normal buffered read, readahead, write and writeback and also handles unbuffered and direct I/O.

The library provides support for (re-)negotiation of I/O sizes and retrying failed I/O as well as local caching and will, in the future, provide content encryption.

It insulates the filesystem from VM interface changes as much as possible and handles VM features such as large multipage folios.  The filesystem basically just has to provide a way to perform read and write RPC calls.

The way I/O is organised inside netfslib consists of a number of objects:

> - A *request*.  A request is used to track the progress of the I/O overall and to hold on to resources.  The collection of results is done at the request level.  The I/O within a request is divided into a number of parallel streams of subrequests.
>
> - A *stream*.  A non-overlapping series of subrequests.  The subrequests within a stream do not have to be contiguous.
>
> - A *subrequest*.  This is the basic unit of I/O.  It represents a single RPC call or a single cache I/O operation.  The library passes these to the filesystem and the cache to perform.

<a id="rst-requests-and-streams"></a>

### Requests and Streams

When actually performing I/O (as opposed to just copying into the pagecache), netfslib will create one or more requests to track the progress of the I/O and to hold resources.

A read operation will have a single stream and the subrequests within that stream may be of mixed origins, for instance mixing RPC subrequests and cache subrequests.

On the other hand, a write operation may have multiple streams, where each stream targets a different destination.  For instance, there may be one stream writing to the local cache and one to the server.  Currently, only two streams are allowed, but this could be increased if parallel writes to multiple servers is desired.

The subrequests within a write stream do not need to match alignment or size with the subrequests in another write stream and netfslib performs the tiling of subrequests in each stream over the source buffer independently.  Further, each stream may contain holes that don't correspond to holes in the other stream.

In addition, the subrequests do not need to correspond to the boundaries of the folios or vectors in the source/destination buffer.  The library handles the collection of results and the wrangling of folio flags and references.

<a id="rst-subrequests"></a>

### Subrequests

Subrequests are at the heart of the interaction between netfslib and the filesystem using it.  Each subrequest is expected to correspond to a single read or write RPC or cache operation.  The library will stitch together the results from a set of subrequests to provide a higher level operation.

Netfslib has two interactions with the filesystem or the cache when setting up a subrequest.  First, there's an optional preparatory step that allows the filesystem to negotiate the limits on the subrequest, both in terms of maximum number of bytes and maximum number of vectors (e.g. for RDMA).  This may involve negotiating with the server (e.g. cifs needing to acquire credits).

And, secondly, there's the issuing step in which the subrequest is handed off to the filesystem to perform.

Note that these two steps are done slightly differently between read and write:

> - For reads, the VM/VFS tells us how much is being requested up front, so the library can preset maximum values that the cache and then the filesystem can then reduce.  The cache also gets consulted first on whether it wants to do a read before the filesystem is consulted.
>
> - For writeback, it is unknown how much there will be to write until the pagecache is walked, so no limit is set by the library.

Once a subrequest is completed, the filesystem or cache informs the library of the completion and then collection is invoked.  Depending on whether the request is synchronous or asynchronous, the collection of results will be done in either the application thread or in a work queue.

<a id="rst-result-collection-and-retry"></a>

### Result Collection and Retry

As subrequests complete, the results are collected and collated by the library and folio unlocking is performed progressively (if appropriate).  Once the request is complete, async completion will be invoked (again, if appropriate). It is possible for the filesystem to provide interim progress reports to the library to cause folio unlocking to happen earlier if possible.

If any subrequests fail, netfslib can retry them.  It will wait until all subrequests are completed, offer the filesystem the opportunity to fiddle with the resources/state held by the request and poke at the subrequests before re-preparing and re-issuing the subrequests.

This allows the tiling of contiguous sets of failed subrequest within a stream to be changed, adding more subrequests or ditching excess as necessary (for instance, if the network sizes change or the server decides it wants smaller chunks).

Further, if one or more contiguous cache-read subrequests fail, the library will pass them to the filesystem to perform instead, renegotiating and retiling them as necessary to fit with the filesystem's parameters rather than those of the cache.

<a id="rst-local-caching"></a>

### Local Caching

One of the services netfslib provides, via `fscache`, is the option to cache on local disk a copy of the data obtained from/written to a network filesystem. The library will manage the storing, retrieval and some invalidation of data automatically on behalf of the filesystem if a cookie is attached to the `netfs_inode`.

Note that local caching used to use the PG_private_2 (aliased as PG_fscache) to keep track of a page that was being written to the cache, but this is now deprecated as PG_private_2 will be removed.

Instead, folios that are read from the server for which there was no data in the cache will be marked as dirty and will have `folio->private` set to a special value (`NETFS_FOLIO_COPY_TO_CACHE`) and left to writeback to write. If the folio is modified before that happened, the special value will be cleared and the write will become normally dirty.

When writeback occurs, folios that are so marked will only be written to the cache and not to the server.  Writeback handles mixed cache-only writes and server-and-cache writes by using two streams, sending one to the cache and one to the server.  The server stream will have gaps in it corresponding to those folios.

<a id="rst-content-encryption-fscrypt"></a>

### Content Encryption (fscrypt)

Though it does not do so yet, at some point netfslib will acquire the ability to do client-side content encryption on behalf of the network filesystem (Ceph, for example).  fscrypt can be used for this if appropriate (it may not be - cifs, for example).

The data will be stored encrypted in the local cache using the same manner of encryption as the data written to the server and the library will impose bounce buffering and RMW cycles as necessary.

<a id="rst-per-inode-context"></a>

## Per-Inode Context

The network filesystem helper library needs a place to store a bit of state for its use on each netfs inode it is helping to manage.  To this end, a context structure is defined:



```text
struct netfs_inode {
        struct inode inode;
        const struct netfs_request_ops *ops;
        struct fscache_cookie * cache;
        loff_t remote_i_size;
        unsigned long flags;
        ...
};
```

A network filesystem that wants to use netfslib must place one of these in its inode wrapper struct instead of the VFS `struct inode`.  This can be done in a way similar to the following:



```text
struct my_inode {
        struct netfs_inode netfs; /* Netfslib context and vfs inode */
        ...
};
```

This allows netfslib to find its state by using `container_of()` from the inode pointer, thereby allowing the netfslib helper functions to be pointed to directly by the VFS/VM operation tables.

The structure contains the following fields that are of interest to the filesystem:

> - `inode`
>
>   The VFS inode structure.
>
> - `ops`
>
>   The set of operations provided by the network filesystem to netfslib.
>
> - `cache`
>
>   Local caching cookie, or NULL if no caching is enabled.  This field does not exist if fscache is disabled.
>
> - `remote_i_size`
>
>   The size of the file on the server.  This differs from inode-&gt;i_size if local modifications have been made but not yet written back.
>
> - `flags`
>
>   A set of flags, some of which the filesystem might be interested in:
>
>   - `NETFS_ICTX_MODIFIED_ATTR`
>
>     Set if netfslib modifies mtime/ctime.  The filesystem is free to ignore this or clear it.
>
>   - `NETFS_ICTX_UNBUFFERED`
>
>     Do unbuffered I/O upon the file.  Like direct I/O but without the alignment limitations.  RMW will be performed if necessary.  The pagecache will not be used unless mmap() is also used.
>
>   - `NETFS_ICTX_WRITETHROUGH`
>
>     Do writethrough caching upon the file.  I/O will be set up and dispatched as buffered writes are made to the page cache.  mmap() does the normal writeback thing.
>
>   - `NETFS_ICTX_SINGLE_NO_UPLOAD`
>
>     Set if the file has a monolithic content that must be read entirely in a single go and must not be written back to the server, though it can be cached (e.g. AFS directories).

<a id="rst-inode-context-helper-functions"></a>

### Inode Context Helper Functions

To help deal with the per-inode context, a number helper functions are provided.  Firstly, a function to perform basic initialisation on a context and set the operations table pointer:



```text
void netfs_inode_init(struct netfs_inode *ctx,
                      const struct netfs_request_ops *ops);
```

then a function to cast from the VFS inode structure to the netfs context:



```text
struct netfs_inode *netfs_inode(struct inode *inode);
```

and finally, a function to get the cache cookie pointer from the context attached to an inode (or NULL if fscache is disabled):



```text
struct fscache_cookie *netfs_i_cookie(struct netfs_inode *ctx);
```

<a id="rst-inode-locking"></a>

### Inode Locking

A number of functions are provided to manage the locking of i_rwsem for I/O and to effectively extend it to provide more separate classes of exclusion:



```text
int netfs_start_io_read(struct inode *inode);
void netfs_end_io_read(struct inode *inode);
int netfs_start_io_write(struct inode *inode);
void netfs_end_io_write(struct inode *inode);
int netfs_start_io_direct(struct inode *inode);
void netfs_end_io_direct(struct inode *inode);
```

The exclusion breaks down into four separate classes:

> 1. Buffered reads and writes.
>
>    Buffered reads can run concurrently each other and with buffered writes, but buffered writes cannot run concurrently with each other.
>
> 2. Direct reads and writes.
>
>    Direct (and unbuffered) reads and writes can run concurrently since they do not share local buffering (i.e. the pagecache) and, in a network filesystem, are expected to have exclusion managed on the server (though this may not be the case for, say, Ceph).
>
> 3. Other major inode modifying operations (e.g. truncate, fallocate).
>
>    These should just access i_rwsem directly.
>
> 4. mmap().
>
>    mmap'd accesses might operate concurrently with any of the other classes. They might form the buffer for an intra-file loopback DIO read/write.  They might be permitted on unbuffered files.

<a id="rst-inode-writeback"></a>

### Inode Writeback

Netfslib will pin resources on an inode for future writeback (such as pinning use of an fscache cookie) when an inode is dirtied.  However, this pinning needs careful management.  To manage the pinning, the following sequence occurs:

> 1. An inode state flag `I_PINNING_NETFS_WB` is set by netfslib when the pinning begins (when a folio is dirtied, for example) if the cache is active to stop the cache structures from being discarded and the cache space from being culled.  This also prevents re-getting of cache resources if the flag is already set.
>
> 2. This flag then cleared inside the inode lock during inode writeback in the VM - and the fact that it was set is transferred to `->unpinned_netfs_wb` in `struct writeback_control`.
>
> 3. If `->unpinned_netfs_wb` is now set, the write_inode procedure is forced.
>
> 4. The filesystem's `->write_inode()` function is invoked to do the cleanup.
>
> 5. The filesystem invokes netfs to do its cleanup.

To do the cleanup, netfslib provides a function to do the resource unpinning:



```text
int netfs_unpin_writeback(struct inode *inode, struct writeback_control *wbc);
```

If the filesystem doesn't need to do anything else, this may be set as a its `.write_inode` method.

Further, if an inode is deleted, the filesystem's write_inode method may not get called, so:



```text
void netfs_clear_inode_writeback(struct inode *inode, const void *aux);
```

must be called from `->evict_inode()` *before* `clear_inode()` is called.

<a id="rst-high-level-vfs-api"></a>

## High-Level VFS API

Netfslib provides a number of sets of API calls for the filesystem to delegate VFS operations to.  Netfslib, in turn, will call out to the filesystem and the cache to negotiate I/O sizes, issue RPCs and provide places for it to intervene at various times.

<a id="rst-unlocked-read-write-iter"></a>

### Unlocked Read/Write Iter

The first API set is for the delegation of operations to netfslib when the filesystem is called through the standard VFS read/write_iter methods:



```text
ssize_t netfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter);
ssize_t netfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from);
ssize_t netfs_buffered_read_iter(struct kiocb *iocb, struct iov_iter *iter);
ssize_t netfs_unbuffered_read_iter(struct kiocb *iocb, struct iov_iter *iter);
ssize_t netfs_unbuffered_write_iter(struct kiocb *iocb, struct iov_iter *from);
```

They can be assigned directly to `.read_iter` and `.write_iter`.  They perform the inode locking themselves and the first two will switch between buffered I/O and DIO as appropriate.

<a id="rst-pre-locked-read-write-iter"></a>

### Pre-Locked Read/Write Iter

The second API set is for the delegation of operations to netfslib when the filesystem is called through the standard VFS methods, but needs to do some other stuff before or after calling netfslib whilst still inside locked section (e.g. Ceph negotiating caps).  The unbuffered read function is:



```text
ssize_t netfs_unbuffered_read_iter_locked(struct kiocb *iocb, struct iov_iter *iter);
```

This must not be assigned directly to `.read_iter` and the filesystem is responsible for performing the inode locking before calling it.  In the case of buffered read, the filesystem should use `filemap_read()`.

There are three functions for writes:



```text
ssize_t netfs_buffered_write_iter_locked(struct kiocb *iocb, struct iov_iter *from,
                                         struct netfs_group *netfs_group);
ssize_t netfs_perform_write(struct kiocb *iocb, struct iov_iter *iter,
                            struct netfs_group *netfs_group);
ssize_t netfs_unbuffered_write_iter_locked(struct kiocb *iocb, struct iov_iter *iter,
                                           struct netfs_group *netfs_group);
```

These must not be assigned directly to `.write_iter` and the filesystem is responsible for performing the inode locking before calling them.

The first two functions are for buffered writes; the first just adds some standard write checks and jumps to the second, but if the filesystem wants to do the checks itself, it can use the second directly.  The third function is for unbuffered or DIO writes.

On all three write functions, there is a writeback group pointer (which should be NULL if the filesystem doesn't use this).  Writeback groups are set on folios when they're modified.  If a folio to-be-modified is already marked with a different group, it is flushed first.  The writeback API allows writing back of a specific group.

<a id="rst-memory-mapped-i-o-api"></a>

### Memory-Mapped I/O API

An API for support of mmap()'d I/O is provided:



```text
vm_fault_t netfs_page_mkwrite(struct vm_fault *vmf, struct netfs_group *netfs_group);
```

This allows the filesystem to delegate `.page_mkwrite` to netfslib.  The filesystem should not take the inode lock before calling it, but, as with the locked write functions above, this does take a writeback group pointer.  If the page to be made writable is in a different group, it will be flushed first.

<a id="rst-monolithic-files-api"></a>

### Monolithic Files API

There is also a special API set for files for which the content must be read in a single RPC (and not written back) and is maintained as a monolithic blob (e.g. an AFS directory), though it can be stored and updated in the local cache:



```text
ssize_t netfs_read_single(struct inode *inode, struct file *file, struct iov_iter *iter);
void netfs_single_mark_inode_dirty(struct inode *inode);
int netfs_writeback_single(struct address_space *mapping,
                           struct writeback_control *wbc,
                           struct iov_iter *iter);
```

The first function reads from a file into the given buffer, reading from the cache in preference if the data is cached there; the second function allows the inode to be marked dirty, causing a later writeback; and the third function can be called from the writeback code to write the data to the cache, if there is one.

The inode should be marked `NETFS_ICTX_SINGLE_NO_UPLOAD` if this API is to be used.  The writeback function requires the buffer to be of ITER_FOLIOQ type.

<a id="rst-high-level-vm-api"></a>

## High-Level VM API

Netfslib also provides a number of sets of API calls for the filesystem to delegate VM operations to.  Again, netfslib, in turn, will call out to the filesystem and the cache to negotiate I/O sizes, issue RPCs and provide places for it to intervene at various times:



```text
void netfs_readahead(struct readahead_control *);
int netfs_read_folio(struct file *, struct folio *);
int netfs_writepages(struct address_space *mapping,
                     struct writeback_control *wbc);
bool netfs_dirty_folio(struct address_space *mapping, struct folio *folio);
void netfs_invalidate_folio(struct folio *folio, size_t offset, size_t length);
bool netfs_release_folio(struct folio *folio, gfp_t gfp);
```

These are `address_space_operations` methods and can be set directly in the operations table.

<a id="rst-deprecated-pg-private-2-api"></a>

### Deprecated PG_private_2 API

There is also a deprecated function for filesystems that still use the `->write_begin` method:



```text
int netfs_write_begin(struct netfs_inode *inode, struct file *file,
                      struct address_space *mapping, loff_t pos, unsigned int len,
                      struct folio **_folio, void **_fsdata);
```

It uses the deprecated PG_private_2 flag and so should not be used.

<a id="rst-i-o-request-api"></a>

## I/O Request API

The I/O request API comprises a number of structures and a number of functions that the filesystem may need to use.

<a id="rst-request-structure"></a>

### Request Structure

The request structure manages the request as a whole, holding some resources and state on behalf of the filesystem and tracking the collection of results:



```text
struct netfs_io_request {
        enum netfs_io_origin    origin;
        struct inode            *inode;
        struct address_space    *mapping;
        struct netfs_group      *group;
        struct netfs_io_stream  io_streams[];
        void                    *netfs_priv;
        void                    *netfs_priv2;
        unsigned long long      start;
        unsigned long long      len;
        unsigned long long      i_size;
        unsigned int            debug_id;
        unsigned long           flags;
        ...
};
```

Many of the fields are for internal use, but the fields shown here are of interest to the filesystem:

> - `origin`
>
>   The origin of the request (readahead, read_folio, DIO read, writeback, ...).
>
> - `inode`
>
> - `mapping`
>
>   The inode and the address space of the file being read from.  The mapping may or may not point to inode-&gt;i_data.
>
> - `group`
>
>   The writeback group this request is dealing with or NULL.  This holds a ref on the group.
>
> - `io_streams`
>
>   The parallel streams of subrequests available to the request.  Currently two are available, but this may be made extensible in future.  `NR_IO_STREAMS` indicates the size of the array.
>
> - `netfs_priv`
>
> - `netfs_priv2`
>
>   The network filesystem's private data.  The value for this can be passed in to the helper functions or set during the request.
>
> - `start`
>
> - `len`
>
>   The file position of the start of the read request and the length.  These may be altered by the -&gt;expand_readahead() op.
>
> - `i_size`
>
>   The size of the file at the start of the request.
>
> - `debug_id`
>
>   A number allocated to this operation that can be displayed in trace lines for reference.
>
> - `flags`
>
>   Flags for managing and controlling the operation of the request.  Some of these may be of interest to the filesystem:
>
>   - `NETFS_RREQ_RETRYING`
>
>     Netfslib sets this when generating retries.
>
>   - `NETFS_RREQ_PAUSE`
>
>     The filesystem can set this to request to pause the library's subrequest issuing loop - but care needs to be taken as netfslib may also set it.
>
>   - `NETFS_RREQ_NONBLOCK`
>
>   - `NETFS_RREQ_BLOCKED`
>
>     Netfslib sets the first to indicate that non-blocking mode was set by the caller and the filesystem can set the second to indicate that it would have had to block.
>
>   - `NETFS_RREQ_USE_PGPRIV2`
>
>     The filesystem can set this if it wants to use PG_private_2 to track whether a folio is being written to the cache.  This is deprecated as PG_private_2 is going to go away.

If the filesystem wants more private data than is afforded by this structure, then it should wrap it and provide its own allocator.

<a id="rst-stream-structure"></a>

### Stream Structure

A request is comprised of one or more parallel streams and each stream may be aimed at a different target.

For read requests, only stream 0 is used.  This can contain a mixture of subrequests aimed at different sources.  For write requests, stream 0 is used for the server and stream 1 is used for the cache.  For buffered writeback, stream 0 is not enabled unless a normal dirty folio is encountered, at which point -&gt;begin_writeback() will be invoked and the filesystem can mark the stream available.

The stream struct looks like:



```text
struct netfs_io_stream {
        unsigned char           stream_nr;
        bool                    avail;
        size_t                  sreq_max_len;
        unsigned int            sreq_max_segs;
        unsigned int            submit_extendable_to;
        ...
};
```

A number of members are available for access/use by the filesystem:

> - `stream_nr`
>
>   The number of the stream within the request.
>
> - `avail`
>
>   True if the stream is available for use.  The filesystem should set this on stream zero if in -&gt;begin_writeback().
>
> - `sreq_max_len`
>
> - `sreq_max_segs`
>
>   These are set by the filesystem or the cache in -&gt;prepare_read() or -&gt;prepare_write() for each subrequest to indicate the maximum number of bytes and, optionally, the maximum number of segments (if not 0) that that subrequest can support.
>
> - `submit_extendable_to`
>
>   The size that a subrequest can be rounded up to beyond the EOF, given the available buffer.  This allows the cache to work out if it can do a DIO read or write that straddles the EOF marker.

<a id="rst-subrequest-structure"></a>

### Subrequest Structure

Individual units of I/O are managed by the subrequest structure.  These represent slices of the overall request and run independently:



```text
struct netfs_io_subrequest {
        struct netfs_io_request *rreq;
        struct iov_iter         io_iter;
        unsigned long long      start;
        size_t                  len;
        size_t                  transferred;
        unsigned long           flags;
        short                   error;
        unsigned short          debug_index;
        unsigned char           stream_nr;
        ...
};
```

Each subrequest is expected to access a single source, though the library will handle falling back from one source type to another.  The members are:

> - `rreq`
>
>   A pointer to the read request.
>
> - `io_iter`
>
>   An I/O iterator representing a slice of the buffer to be read into or written from.
>
> - `start`
>
> - `len`
>
>   The file position of the start of this slice of the read request and the length.
>
> - `transferred`
>
>   The amount of data transferred so far for this subrequest.  This should be added to with the length of the transfer made by this issuance of the subrequest.  If this is less than `len` then the subrequest may be reissued to continue.
>
> - `flags`
>
>   Flags for managing the subrequest.  There are a number of interest to the filesystem or cache:
>
>   - `NETFS_SREQ_MADE_PROGRESS`
>
>     Set by the filesystem to indicates that at least one byte of data was read or written.
>
>   - `NETFS_SREQ_HIT_EOF`
>
>     The filesystem should set this if a read hit the EOF on the file (in which case `transferred` should stop at the EOF).  Netfslib may expand the subrequest out to the size of the folio containing the EOF on the off chance that a third party change happened or a DIO read may have asked for more than is available.  The library will clear any excess pagecache.
>
>   - `NETFS_SREQ_CLEAR_TAIL`
>
>     The filesystem can set this to indicate that the remainder of the slice, from transferred to len, should be cleared.  Do not set if HIT_EOF is set.
>
>   - `NETFS_SREQ_NEED_RETRY`
>
>     The filesystem can set this to tell netfslib to retry the subrequest.
>
>   - `NETFS_SREQ_BOUNDARY`
>
>     This can be set by the filesystem on a subrequest to indicate that it ends at a boundary with the filesystem structure (e.g. at the end of a Ceph object).  It tells netfslib not to retile subrequests across it.
>
> - `error`
>
>   This is for the filesystem to store result of the subrequest.  It should be set to 0 if successful and a negative error code otherwise.
>
> - `debug_index`
>
> - `stream_nr`
>
>   A number allocated to this slice that can be displayed in trace lines for reference and the number of the request stream that it belongs to.

If necessary, the filesystem can get and put extra refs on the subrequest it is given:



```text
void netfs_get_subrequest(struct netfs_io_subrequest *subreq,
                          enum netfs_sreq_ref_trace what);
void netfs_put_subrequest(struct netfs_io_subrequest *subreq,
                          enum netfs_sreq_ref_trace what);
```

using netfs trace codes to indicate the reason.  Care must be taken, however, as once control of the subrequest is returned to netfslib, the same subrequest can be reissued/retried.

<a id="rst-filesystem-methods"></a>

### Filesystem Methods

The filesystem sets a table of operations in `netfs_inode` for netfslib to use:



```text
struct netfs_request_ops {
        mempool_t *request_pool;
        mempool_t *subrequest_pool;
        int (*init_request)(struct netfs_io_request *rreq, struct file *file);
        void (*free_request)(struct netfs_io_request *rreq);
        void (*free_subrequest)(struct netfs_io_subrequest *rreq);
        void (*expand_readahead)(struct netfs_io_request *rreq);
        int (*prepare_read)(struct netfs_io_subrequest *subreq);
        void (*issue_read)(struct netfs_io_subrequest *subreq);
        void (*done)(struct netfs_io_request *rreq);
        void (*update_i_size)(struct inode *inode, loff_t i_size);
        void (*post_modify)(struct inode *inode);
        void (*begin_writeback)(struct netfs_io_request *wreq);
        void (*prepare_write)(struct netfs_io_subrequest *subreq);
        void (*issue_write)(struct netfs_io_subrequest *subreq);
        void (*retry_request)(struct netfs_io_request *wreq,
                              struct netfs_io_stream *stream);
        void (*invalidate_cache)(struct netfs_io_request *wreq);
};
```

The table starts with a pair of optional pointers to memory pools from which requests and subrequests can be allocated.  If these are not given, netfslib has default pools that it will use instead.  If the filesystem wraps the netfs structs in its own larger structs, then it will need to use its own pools. Netfslib will allocate directly from the pools.

The methods defined in the table are:

> - `init_request()`
>
> - `free_request()`
>
> - `free_subrequest()`
>
>   \[Optional\] A filesystem may implement these to initialise or clean up any resources that it attaches to the request or subrequest.
>
> - `expand_readahead()`
>
>   \[Optional\] This is called to allow the filesystem to expand the size of a readahead request.  The filesystem gets to expand the request in both directions, though it must retain the initial region as that may represent an allocation already made.  If local caching is enabled, it gets to expand the request first.
>
>   Expansion is communicated by changing -&gt;start and -&gt;len in the request structure.  Note that if any change is made, -&gt;len must be increased by at least as much as -&gt;start is reduced.
>
> - `prepare_read()`
>
>   \[Optional\] This is called to allow the filesystem to limit the size of a subrequest.  It may also limit the number of individual regions in iterator, such as required by RDMA.  This information should be set on stream zero in:
>
>
>
>   ```text
>   rreq->io_streams[0].sreq_max_len
>   rreq->io_streams[0].sreq_max_segs
>   ```
>
>   The filesystem can use this, for example, to chop up a request that has to be split across multiple servers or to put multiple reads in flight.
>
>   Zero should be returned on success and an error code otherwise.
>
> - `issue_read()`
>
>   \[Required\] Netfslib calls this to dispatch a subrequest to the server for reading.  In the subrequest, -&gt;start, -&gt;len and -&gt;transferred indicate what data should be read from the server and -&gt;io_iter indicates the buffer to be used.
>
>   There is no return value; the `netfs_read_subreq_terminated()` function should be called to indicate that the subrequest completed either way. -&gt;error, -&gt;transferred and -&gt;flags should be updated before completing.  The termination can be done asynchronously.
>
>   Note: the filesystem must not deal with setting folios uptodate, unlocking them or dropping their refs - the library deals with this as it may have to stitch together the results of multiple subrequests that variously overlap the set of folios.
>
> - `done()`
>
>   \[Optional\] This is called after the folios in a read request have all been unlocked (and marked uptodate if applicable).
>
> - `update_i_size()`
>
>   \[Optional\] This is invoked by netfslib at various points during the write paths to ask the filesystem to update its idea of the file size.  If not given, netfslib will set i_size and i_blocks and update the local cache cookie.
>
> - `post_modify()`
>
>   \[Optional\] This is called after netfslib writes to the pagecache or when it allows an mmap'd page to be marked as writable.
>
> - `begin_writeback()`
>
>   \[Optional\] Netfslib calls this when processing a writeback request if it finds a dirty page that isn't simply marked NETFS_FOLIO_COPY_TO_CACHE, indicating it must be written to the server.  This allows the filesystem to only set up writeback resources when it knows it's going to have to perform a write.
>
> - `prepare_write()`
>
>   \[Optional\] This is called to allow the filesystem to limit the size of a subrequest.  It may also limit the number of individual regions in iterator, such as required by RDMA.  This information should be set on stream to which the subrequest belongs:
>
>
>
>   ```text
>   rreq->io_streams[subreq->stream_nr].sreq_max_len
>   rreq->io_streams[subreq->stream_nr].sreq_max_segs
>   ```
>
>   The filesystem can use this, for example, to chop up a request that has to be split across multiple servers or to put multiple writes in flight.
>
>   This is not permitted to return an error.  Instead, in the event of failure, `netfs_prepare_write_failed()` must be called.
>
> - `issue_write()`
>
>   \[Required\] This is used to dispatch a subrequest to the server for writing. In the subrequest, -&gt;start, -&gt;len and -&gt;transferred indicate what data should be written to the server and -&gt;io_iter indicates the buffer to be used.
>
>   There is no return value; the `netfs_write_subreq_terminated()` function should be called to indicate that the subrequest completed either way. -&gt;error, -&gt;transferred and -&gt;flags should be updated before completing.  The termination can be done asynchronously.
>
>   Note: the filesystem must not deal with removing the dirty or writeback marks on folios involved in the operation and should not take refs or pins on them, but should leave retention to netfslib.
>
> - `retry_request()`
>
>   \[Optional\] Netfslib calls this at the beginning of a retry cycle.  This allows the filesystem to examine the state of the request, the subrequests in the indicated stream and of its own data and make adjustments or renegotiate resources.
>
> - `invalidate_cache()`
>
>   \[Optional\] This is called by netfslib to invalidate data stored in the local cache in the event that writing to the local cache fails, providing updated coherency data that netfs can't provide.

<a id="rst-terminating-a-subrequest"></a>

### Terminating a subrequest

When a subrequest completes, there are a number of functions that the cache or subrequest can call to inform netfslib of the status change.  One function is provided to terminate a write subrequest at the preparation stage and acts synchronously:

> - `void netfs_prepare_write_failed(struct netfs_io_subrequest *subreq);`
>
>   Indicate that the -&gt;prepare_write() call failed.  The `error` field should have been updated.

Note that -&gt;prepare_read() can return an error as a read can simply be aborted. Dealing with writeback failure is trickier.

The other functions are used for subrequests that got as far as being issued:

> - `void netfs_read_subreq_terminated(struct netfs_io_subrequest *subreq);`
>
>   Tell netfslib that a read subrequest has terminated.  The `error`, `flags` and `transferred` fields should have been updated.
>
> - `void netfs_write_subrequest_terminated(void *_op, ssize_t transferred_or_error);`
>
>   Tell netfslib that a write subrequest has terminated.  Either the amount of data processed or the negative error code can be passed in.  This is can be used as a kiocb completion function.
>
> - `void netfs_read_subreq_progress(struct netfs_io_subrequest *subreq);`
>
>   This is provided to optionally update netfslib on the incremental progress of a read, allowing some folios to be unlocked early and does not actually terminate the subrequest.  The `transferred` field should have been updated.

<a id="rst-local-cache-api"></a>

### Local Cache API

Netfslib provides a separate API for a local cache to implement, though it provides some somewhat similar routines to the filesystem request API.

Firstly, the netfs_io_request object contains a place for the cache to hang its state:



```text
struct netfs_cache_resources {
        const struct netfs_cache_ops    *ops;
        void                            *cache_priv;
        void                            *cache_priv2;
        unsigned int                    debug_id;
        unsigned int                    inval_counter;
};
```

This contains an operations table pointer and two private pointers plus the debug ID of the fscache cookie for tracing purposes and an invalidation counter that is cranked by calls to `fscache_invalidate()` allowing cache subrequests to be invalidated after completion.

The cache operation table looks like the following:



```text
struct netfs_cache_ops {
        void (*end_operation)(struct netfs_cache_resources *cres);
        void (*expand_readahead)(struct netfs_cache_resources *cres,
                                 loff_t *_start, size_t *_len, loff_t i_size);
        enum netfs_io_source (*prepare_read)(struct netfs_io_subrequest *subreq,
                                             loff_t i_size);
        int (*read)(struct netfs_cache_resources *cres,
                    loff_t start_pos,
                    struct iov_iter *iter,
                    bool seek_data,
                    netfs_io_terminated_t term_func,
                    void *term_func_priv);
        void (*prepare_write_subreq)(struct netfs_io_subrequest *subreq);
        void (*issue_write)(struct netfs_io_subrequest *subreq);
};
```

With a termination handler function pointer:



```text
typedef void (*netfs_io_terminated_t)(void *priv,
                                      ssize_t transferred_or_error,
                                      bool was_async);
```

The methods defined in the table are:

> - `end_operation()`
>
>   \[Required\] Called to clean up the resources at the end of the read request.
>
> - `expand_readahead()`
>
>   \[Optional\] Called at the beginning of a readahead operation to allow the cache to expand a request in either direction.  This allows the cache to size the request appropriately for the cache granularity.
>
> - `prepare_read()`
>
>   \[Required\] Called to configure the next slice of a request.  -&gt;start and -&gt;len in the subrequest indicate where and how big the next slice can be; the cache gets to reduce the length to match its granularity requirements.
>
>   The function is passed pointers to the start and length in its parameters, plus the size of the file for reference, and adjusts the start and length appropriately.  It should return one of:
>
>   - `NETFS_FILL_WITH_ZEROES`
>
>   - `NETFS_DOWNLOAD_FROM_SERVER`
>
>   - `NETFS_READ_FROM_CACHE`
>
>   - `NETFS_INVALID_READ`
>
>   to indicate whether the slice should just be cleared or whether it should be downloaded from the server or read from the cache - or whether slicing should be given up at the current point.
>
> - `read()`
>
>   \[Required\] Called to read from the cache.  The start file offset is given along with an iterator to read to, which gives the length also.  It can be given a hint requesting that it seek forward from that start position for data.
>
>   Also provided is a pointer to a termination handler function and private data to pass to that function.  The termination function should be called with the number of bytes transferred or an error code, plus a flag indicating whether the termination is definitely happening in the caller's context.
>
> - `prepare_write_subreq()`
>
>   \[Required\] This is called to allow the cache to limit the size of a subrequest.  It may also limit the number of individual regions in iterator, such as required by DIO/DMA.  This information should be set on stream to which the subrequest belongs:
>
>
>
>   ```text
>   rreq->io_streams[subreq->stream_nr].sreq_max_len
>   rreq->io_streams[subreq->stream_nr].sreq_max_segs
>   ```
>
>   The filesystem can use this, for example, to chop up a request that has to be split across multiple servers or to put multiple writes in flight.
>
>   This is not permitted to return an error.  In the event of failure, `netfs_prepare_write_failed()` must be called.
>
> - `issue_write()`
>
>   \[Required\] This is used to dispatch a subrequest to the cache for writing. In the subrequest, -&gt;start, -&gt;len and -&gt;transferred indicate what data should be written to the cache and -&gt;io_iter indicates the buffer to be used.
>
>   There is no return value; the `netfs_write_subreq_terminated()` function should be called to indicate that the subrequest completed either way. -&gt;error, -&gt;transferred and -&gt;flags should be updated before completing.  The termination can be done asynchronously.

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-folio_start_private_2"></a>`folio_start_private_2()`

```c
void folio_start_private_2(struct folio *folio)
```

Start an fscache write on a folio. \[DEPRECATED\]

**Parameters**

- `struct folio *folio`: The folio.

**Description**

Call this function before writing a folio to a local cache.  Starting a
second write before the first one finishes is not allowed.

Note that this should no longer be used.

#### <a id="c-netfs_inode"></a>`netfs_inode()`

```c
struct netfs_inode * netfs_inode(struct inode *inode)
```

Get the netfs inode context from the inode

**Parameters**

- `struct inode *inode`: The inode to query

**Description**

Get the netfs lib inode context from the network filesystem's inode.  The
context struct is expected to directly follow on from the VFS inode struct.

#### <a id="c-netfs_inode_init"></a>`netfs_inode_init()`

```c
void netfs_inode_init(struct netfs_inode *ctx, const struct netfs_request_ops *ops, bool use_zero_point)
```

Initialise a netfslib inode context

**Parameters**

- `struct netfs_inode *ctx`: The netfs inode to initialise
- `const struct netfs_request_ops *ops`: The netfs's operations list
- `bool use_zero_point`: True to use the zero_point read optimisation

**Description**

Initialise the netfs library context struct.  This is expected to follow on
directly from the VFS inode struct.

#### <a id="c-netfs_resize_file"></a>`netfs_resize_file()`

```c
void netfs_resize_file(struct netfs_inode *ctx, loff_t new_i_size, bool changed_on_server)
```

Note that a file got resized

**Parameters**

- `struct netfs_inode *ctx`: The netfs inode being resized
- `loff_t new_i_size`: The new file size
- `bool changed_on_server`: The change was applied to the server

**Description**

Inform the netfs lib that a file got resized so that it can adjust its state.

#### <a id="c-netfs_i_cookie"></a>`netfs_i_cookie()`

```c
struct fscache_cookie * netfs_i_cookie(struct netfs_inode *ctx)
```

Get the cache cookie from the inode

**Parameters**

- `struct netfs_inode *ctx`: The netfs inode to query

**Description**

Get the caching cookie (if enabled) from the network filesystem's inode.

#### <a id="c-netfs_wait_for_outstanding_io"></a>`netfs_wait_for_outstanding_io()`

```c
void netfs_wait_for_outstanding_io(struct inode *inode)
```

Wait for outstanding I/O to complete

**Parameters**

- `struct inode *inode`: The netfs inode to wait on

**Description**

Wait for outstanding I/O requests of any type to complete.  This is intended
to be called from inode eviction routines.  This makes sure that any
resources held by those requests are cleaned up before we let the inode get
cleaned up.



#### <a id="c-netfs_readahead"></a>`netfs_readahead()`

```c
void netfs_readahead(struct readahead_control *ractl)
```

Helper to manage a read request

**Parameters**

- `struct readahead_control *ractl`: The description of the readahead request

**Description**

Fulfil a readahead request by drawing data from the cache if possible, or
the netfs if not.  Space beyond the EOF is zero-filled.  Multiple I/O
requests from different sources will get munged together.  If necessary, the
readahead window can be expanded in either direction to a more convenient
alighment for RPC efficiency or to make storage in the cache feasible.

The calling netfs must initialise a netfs context contiguous to the vfs
inode before calling this.

This is usable whether or not caching is enabled.

#### <a id="c-netfs_read_folio"></a>`netfs_read_folio()`

```c
int netfs_read_folio(struct file *file, struct folio *folio)
```

Helper to manage a read_folio request

**Parameters**

- `struct file *file`: The file to read from
- `struct folio *folio`: The folio to read

**Description**

Fulfil a read_folio request by drawing data from the cache if
possible, or the netfs if not.  Space beyond the EOF is zero-filled.
Multiple I/O requests from different sources will get munged together.

The calling netfs must initialise a netfs context contiguous to the vfs
inode before calling this.

This is usable whether or not caching is enabled.

#### <a id="c-netfs_write_begin"></a>`netfs_write_begin()`

```c
int netfs_write_begin(struct netfs_inode *ctx, struct file *file, struct address_space *mapping, loff_t pos, unsigned int len, struct folio **_folio, void **_fsdata)
```

Helper to prepare for writing \[DEPRECATED\]

**Parameters**

- `struct netfs_inode *ctx`: The netfs context
- `struct file *file`: The file to read from
- `struct address_space *mapping`: The mapping to read from
- `loff_t pos`: File position at which the write will begin
- `unsigned int len`: The length of the write (may extend beyond the end of the folio chosen)
- `struct folio **_folio`: Where to put the resultant folio
- `void **_fsdata`: Place for the netfs to store a cookie

**Description**

Pre-read data for a write-begin request by drawing data from the cache if
possible, or the netfs if not.  Space beyond the EOF is zero-filled.
Multiple I/O requests from different sources will get munged together.

The calling netfs must provide a table of operations, only one of which,
issue_read, is mandatory.

The `check_write_begin()` operation can be provided to check for and flush
conflicting writes once the folio is grabbed and locked.  It is passed a
pointer to the fsdata cookie that gets returned to the VM to be passed to
write_end.  It is permitted to sleep.  It should return 0 if the request
should go ahead or it may return an error.  It may also unlock and put the
folio, provided it sets `*foliop` to NULL, in which case a return of 0
will cause the folio to be re-got and the process to be retried.

The calling netfs must initialise a netfs context contiguous to the vfs
inode before calling this.

This is usable whether or not caching is enabled.

Note that this should be considered deprecated and `netfs_perform_write()`
used instead.

#### <a id="c-netfs_buffered_read_iter"></a>`netfs_buffered_read_iter()`

```c
ssize_t netfs_buffered_read_iter(struct kiocb *iocb, struct iov_iter *iter)
```

Filesystem buffered I/O read routine

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct iov_iter *iter`: destination for the data read

**Description**

This is the ->`read_iter()` routine for all filesystems that can use the page
cache directly.

The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall be
returned when no data can be read without waiting for I/O requests to
complete; it doesn't prevent readahead.

The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O requests
shall be made for the read or for readahead.  When no data can be read,
-EAGAIN shall be returned.  When readahead would be triggered, a partial,
possibly empty read shall be returned.

**Return**

* number of bytes copied, even for partial reads
* negative error code (or 0 if IOCB_NOIO) if nothing was read

#### <a id="c-netfs_file_read_iter"></a>`netfs_file_read_iter()`

```c
ssize_t netfs_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
```

Generic filesystem read routine

**Parameters**

- `struct kiocb *iocb`: kernel I/O control block
- `struct iov_iter *iter`: destination for the data read

**Description**

This is the ->`read_iter()` routine for all filesystems that can use the page
cache directly.

The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall be
returned when no data can be read without waiting for I/O requests to
complete; it doesn't prevent readahead.

The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O requests
shall be made for the read or for readahead.  When no data can be read,
-EAGAIN shall be returned.  When readahead would be triggered, a partial,
possibly empty read shall be returned.

**Return**

* number of bytes copied, even for partial reads
* negative error code (or 0 if IOCB_NOIO) if nothing was read

---

# NILFS2

_Peios Kernel / Internals / Filesystems_

> NILFS2 is a log-structured file system (LFS) supporting continuous snapshotting. In addition to versioning capability of the entire file system, users can even restore files mistakenly overwritten or destroyed just a few seconds ago. Since…

<a id="rst-nilfs2"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

NILFS2 is a log-structured file system (LFS) supporting continuous snapshotting.  In addition to versioning capability of the entire file system, users can even restore files mistakenly overwritten or destroyed just a few seconds ago.  Since NILFS2 can keep consistency like conventional LFS, it achieves quick recovery after system crashes.

NILFS2 creates a number of checkpoints every few seconds or per synchronous write basis (unless there is no change).  Users can select significant versions among continuously created checkpoints, and can change them into snapshots which will be preserved until they are changed back to checkpoints.

There is no limit on the number of snapshots until the volume gets full.  Each snapshot is mountable as a read-only file system concurrently with its writable mount, and this feature is convenient for online backup.

The userland tools are included in nilfs-utils package, which is available from the following download page.  At least "mkfs.nilfs2", "mount.nilfs2", "umount.nilfs2", and "nilfs_cleanerd" (so called cleaner or garbage collector) are required.  Details on the tools are described in the man pages included in the package.

**Project web page:** [https://nilfs.sourceforge.io/](<https://nilfs.sourceforge.io/>)

**Download page:** [https://nilfs.sourceforge.io/en/download.html](<https://nilfs.sourceforge.io/en/download.html>)

**List info:** [http://vger.kernel.org/vger-lists.html\#linux-nilfs](<http://vger.kernel.org/vger-lists.html#linux-nilfs>)

<a id="rst-caveats"></a>

## Caveats

Features which NILFS2 does not support yet:

> - atime
>
> - extended attributes
>
> - POSIX ACLs
>
> - quotas
>
> - fsck
>
> - defragmentation

<a id="rst-mount-options"></a>

## Mount options

NILFS2 supports the following mount options: (\*) == default


<table>
<tbody>
<tr>
<td>


barrier(\*)

</td>
<td>


This enables/disables the use of write barriers.  This

</td>
</tr>
<tr>
<td>


nobarrier

</td>
<td>


requires an IO stack which can support barriers, and if nilfs gets an error on a barrier write, it will disable again with a warning.

</td>
</tr>
<tr>
<td>


errors=continue

</td>
<td>


Keep going on a filesystem error.

</td>
</tr>
<tr>
<td>


errors=remount-ro(\*)

</td>
<td>


Remount the filesystem read-only on an error.

</td>
</tr>
<tr>
<td>


errors=panic

</td>
<td>


Panic and halt the machine if an error occurs.

</td>
</tr>
<tr>
<td>


cp=n

</td>
<td>


Specify the checkpoint-number of the snapshot to be mounted.  Checkpoints and snapshots are listed by lscp user command.  Only the checkpoints marked as snapshot are mountable with this option.  Snapshot is read-only, so a read-only mount option must be specified together.

</td>
</tr>
<tr>
<td>


order=relaxed(\*)

</td>
<td>


Apply relaxed order semantics that allows modified data blocks to be written to disk without making a checkpoint if no metadata update is going.  This mode is equivalent to the ordered data mode of the ext3 filesystem except for the updates on data blocks still conserve atomicity.  This will improve synchronous write performance for overwriting.

</td>
</tr>
<tr>
<td>


order=strict

</td>
<td>


Apply strict in-order semantics that preserves sequence of all file operations including overwriting of data blocks.  That means, it is guaranteed that no overtaking of events occurs in the recovered file system after a crash.

</td>
</tr>
<tr>
<td>


norecovery

</td>
<td>


Disable recovery of the filesystem on mount. This disables every write access on the device for read-only mounts or snapshots.  This option will fail for r/w mounts on an unclean volume.

</td>
</tr>
<tr>
<td>


discard

</td>
<td>


This enables/disables the use of discard/TRIM commands.

</td>
</tr>
<tr>
<td>


nodiscard(\*)

</td>
<td>


The discard/TRIM commands are sent to the underlying block device when blocks are freed.  This is useful for SSD devices and sparse/thinly-provisioned LUNs.

</td>
</tr>
</tbody>
</table>

<a id="rst-ioctls"></a>

## Ioctls

There is some NILFS2 specific functionality which can be accessed by applications through the system call interfaces. The list of all NILFS2 specific ioctls are shown in the table below.

Table of NILFS2 specific ioctls:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Ioctl
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> NILFS_IOCTL_CHANGE_CPMODE
>
> </td>
> <td>
>
>
> Change mode of given checkpoint between checkpoint and snapshot state. This ioctl is used in chcp and mkcp utilities.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_DELETE_CHECKPOINT
>
> </td>
> <td>
>
>
> Remove checkpoint from NILFS2 file system. This ioctl is used in rmcp utility.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_CPINFO
>
> </td>
> <td>
>
>
> Return info about requested checkpoints. This ioctl is used in lscp utility and by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_CPSTAT
>
> </td>
> <td>
>
>
> Return checkpoints statistics. This ioctl is used by lscp, rmcp utilities and by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_SUINFO
>
> </td>
> <td>
>
>
> Return segment usage info about requested segments. This ioctl is used in lssu, nilfs_resize utilities and by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_SET_SUINFO
>
> </td>
> <td>
>
>
> Modify segment usage info of requested segments. This ioctl is used by nilfs_cleanerd daemon to skip unnecessary cleaning operation of segments and reduce performance penalty or wear of flash device due to redundant move of in-use blocks.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_SUSTAT
>
> </td>
> <td>
>
>
> Return segment usage statistics. This ioctl is used in lssu, nilfs_resize utilities and by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_VINFO
>
> </td>
> <td>
>
>
> Return information on virtual block addresses. This ioctl is used by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_GET_BDESCS
>
> </td>
> <td>
>
>
> Return information about descriptors of disk block numbers. This ioctl is used by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_CLEAN_SEGMENTS
>
> </td>
> <td>
>
>
> Do garbage collection operation in the environment of requested parameters from userspace. This ioctl is used by nilfs_cleanerd daemon.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_SYNC
>
> </td>
> <td>
>
>
> Make a checkpoint. This ioctl is used in mkcp utility.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_RESIZE
>
> </td>
> <td>
>
>
> Resize NILFS2 volume. This ioctl is used by nilfs_resize utility.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NILFS_IOCTL_SET_ALLOC_RANGE
>
> </td>
> <td>
>
>
> Define lower limit of segments in bytes and upper limit of segments in bytes. This ioctl is used by nilfs_resize utility.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-nilfs2-usage"></a>

## NILFS2 usage

To use nilfs2 as a local file system, simply:



```text
# mkfs -t nilfs2 /dev/block_device
# mount -t nilfs2 /dev/block_device /dir
```

This will also invoke the cleaner through the mount helper program (mount.nilfs2).

Checkpoints and snapshots are managed by the following commands. Their manpages are included in the nilfs-utils package above.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> lscp
>
> </td>
> <td>
>
>
> list checkpoints or snapshots.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mkcp
>
> </td>
> <td>
>
>
> make a checkpoint or a snapshot.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> chcp
>
> </td>
> <td>
>
>
> change an existing checkpoint to a snapshot or vice versa.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rmcp
>
> </td>
> <td>
>
>
> invalidate specified checkpoint(s).
>
> </td>
> </tr>
> </tbody>
> </table>

To mount a snapshot:



```text
# mount -t nilfs2 -r -o cp=<cno> /dev/block_device /snap_dir
```

where &lt;cno&gt; is the checkpoint number of the snapshot.

To unmount the NILFS2 mount point or snapshot, simply:



```text
# umount /dir
```

Then, the cleaner daemon is automatically shut down by the umount helper program (umount.nilfs2).

<a id="rst-disk-format"></a>

## Disk format

A nilfs2 volume is equally divided into a number of segments except for the super block (SB) and segment \#0.  A segment is the container of logs.  Each log is composed of summary information blocks, payload blocks, and an optional super root block (SR):



```text
 ______________________________________________________
| |SB| | Segment | Segment | Segment | ... | Segment | |
|_|__|_|____0____|____1____|____2____|_____|____N____|_|
0 +1K +4K       +8M       +16M      +24M  +(8MB x N)
     .             .            (Typical offsets for 4KB-block)
  .                  .
.______________________.
| log | log |... | log |
|__1__|__2__|____|__m__|
      .       .
    .               .
  .                       .
.______________________________.
| Summary | Payload blocks  |SR|
|_blocks__|_________________|__|
```

The payload blocks are organized per file, and each file consists of data blocks and B-tree node blocks:



```text
 |<---       File-A        --->|<---       File-B        --->|
_______________________________________________________________
 | Data blocks | B-tree blocks | Data blocks | B-tree blocks | ...
_|_____________|_______________|_____________|_______________|_
```

Since only the modified blocks are written in the log, it may have files without data blocks or B-tree node blocks.

The organization of the blocks is recorded in the summary information blocks, which contains a header structure (nilfs_segment_summary), per file structures (nilfs_finfo), and per block structures (nilfs_binfo):



```text
 _________________________________________________________________________
| Summary | finfo | binfo | ... | binfo | finfo | binfo | ... | binfo |...
|_blocks__|___A___|_(A,1)_|_____|(A,Na)_|___B___|_(B,1)_|_____|(B,Nb)_|___
```

The logs include regular files, directory files, symbolic link files and several meta data files.  The meta data files are the files used to maintain file system meta data.  The current version of NILFS2 uses the following meta data files:



```text
1) Inode file (ifile)             -- Stores on-disk inodes
2) Checkpoint file (cpfile)       -- Stores checkpoints
3) Segment usage file (sufile)    -- Stores allocation state of segments
4) Data address translation file  -- Maps virtual block numbers to usual
   (DAT)                             block numbers.  This file serves to
                                     make on-disk blocks relocatable.
```

The following figure shows a typical organization of the logs:



```text
 _________________________________________________________________________
| Summary | regular file | file  | ... | ifile | cpfile | sufile | DAT |SR|
|_blocks__|_or_directory_|_______|_____|_______|________|________|_____|__|
```

To stride over segment boundaries, this sequence of files may be split into multiple logs.  The sequence of logs that should be treated as logically one log, is delimited with flags marked in the segment summary.  The recovery code of nilfs2 looks this boundary information to ensure atomicity of updates.

The super root block is inserted for every checkpoints.  It includes three special inodes, inodes for the DAT, cpfile, and sufile.  Inodes of regular files, directories, symlinks and other special files, are included in the ifile.  The inode of ifile itself is included in the corresponding checkpoint entry in the cpfile.  Thus, the hierarchy among NILFS2 files can be depicted as follows:



```text
Super block (SB)
     |
     v
Super root block (the latest cno=xx)
     |-- DAT
     |-- sufile
     `-- cpfile
            |-- ifile (cno=c1)
            |-- ifile (cno=c2) ---- file (ino=i1)
            :        :          |-- file (ino=i2)
            `-- ifile (cno=xx)  |-- file (ino=i3)
                                :        :
                                `-- file (ino=yy)
                                  ( regular file, directory, or symlink )
```

For detail on the format of each file, please see nilfs2_ondisk.h located at include/uapi/linux directory.

There are no patents or other intellectual property that we protect with regard to the design of NILFS2.  It is allowed to replicate the design in hopes that other operating systems could share (mount, read, write, etc.) data stored in this format.

---

# NTFS3

_Peios Kernel / Internals / Filesystems_

> NTFS3 is fully functional NTFS Read-Write driver. The driver works with NTFS versions up to 3.1. File system type to use on mount is ntfs3.

<a id="rst-ntfs3"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary-and-features"></a>

## Summary and Features

NTFS3 is fully functional NTFS Read-Write driver. The driver works with NTFS versions up to 3.1. File system type to use on mount is *ntfs3*.

- This driver implements NTFS read/write support for normal, sparse and compressed files.

- Supports native journal replaying.

- Supports NFS export of mounted NTFS volumes.

- Supports extended attributes. Predefined extended attributes:

  > - *system.ntfs_security* gets/sets security
  >
  >   > Descriptor: SECURITY_DESCRIPTOR_RELATIVE
  >
  > - *system.ntfs_attrib* gets/sets ntfs file/dir attributes.
  >
  >   Note: Applied to empty files, this allows to switch type between sparse(0x200), compressed(0x800) and normal.
  >
  > - *system.ntfs_attrib_be* gets/sets ntfs file/dir attributes.
  >
  >   Same value as system.ntfs_attrib but always represent as big-endian (endianness of system.ntfs_attrib is the same as of the CPU).

<a id="rst-mount-options"></a>

## Mount Options

The list below describes mount options supported by NTFS3 driver in addition to generic ones. You can use every mount option with **no** option. If it is in this table marked with no it means default is without **no**.


<table>
<tbody>
<tr>
<td>


iocharset=name

</td>
<td>


This option informs the driver how to interpret path strings and translate them to Unicode and back. If this option is not set, the default codepage will be used (CONFIG_NLS_DEFAULT).

Example: iocharset=utf8

</td>
</tr>
<tr>
<td>


uid=

</td>
<td rowspan="2">




</td>
</tr>
<tr>
<td>


gid=

</td>
</tr>
<tr>
<td>


umask=

</td>
<td>


Controls the default permissions for files/directories created after the NTFS volume is mounted.

</td>
</tr>
<tr>
<td>


dmask=

</td>
<td rowspan="2">


 Instead of specifying umask which applies both to files and directories, fmask applies only to files and dmask only to directories.

</td>
</tr>
<tr>
<td>


fmask=

</td>
</tr>
<tr>
<td>


nohidden

</td>
<td>


Files with the Windows-specific HIDDEN (FILE_ATTRIBUTE_HIDDEN) attribute will not be shown under Linux.

</td>
</tr>
<tr>
<td>


sys_immutable

</td>
<td>


Files with the Windows-specific SYSTEM (FILE_ATTRIBUTE_SYSTEM) attribute will be marked as system immutable files.

</td>
</tr>
<tr>
<td>


hide_dot_files

</td>
<td>


Updates the Windows-specific HIDDEN (FILE_ATTRIBUTE_HIDDEN) attribute when creating and moving or renaming files. Files whose names start with a dot will have the HIDDEN attribute set and files whose names do not start with a dot will have it unset.

</td>
</tr>
<tr>
<td>


windows_names

</td>
<td>


Prevents the creation of files and directories with a name not allowed by Windows, either because it contains some not allowed character (which are the characters " \* / : &lt; &gt; ? \\ \| and those whose code is less than 0x20), because the name (with or without extension) is a reserved file name (CON, AUX, NUL, PRN, LPT1-9, COM1-9) or because the last character is a space or a dot. Existing such files can still be read and renamed.

</td>
</tr>
<tr>
<td>


discard

</td>
<td>


Enable support of the TRIM command for improved performance on delete operations, which is recommended for use with the solid-state drives (SSD).

</td>
</tr>
<tr>
<td>


force

</td>
<td>


Forces the driver to mount partitions even if volume is marked dirty. Not recommended for use.

</td>
</tr>
<tr>
<td>


sparse

</td>
<td>


Create new files as sparse.

</td>
</tr>
<tr>
<td>


showmeta

</td>
<td>


Use this parameter to show all meta-files (System Files) on a mounted NTFS partition. By default, all meta-files are hidden.

</td>
</tr>
<tr>
<td>


prealloc

</td>
<td>


Preallocate space for files excessively when file size is increasing on writes. Decreases fragmentation in case of parallel write operations to different files.

</td>
</tr>
<tr>
<td>


acl

</td>
<td>


Support POSIX ACLs (Access Control Lists). Effective if supported by Kernel. Not to be confused with NTFS ACLs. The option specified as acl enables support for POSIX ACLs.

</td>
</tr>
</tbody>
</table>

<a id="rst-todo-list"></a>

## Todo list

- Full journaling support over JBD. Currently journal replaying is supported which is not necessarily as effective as JBD would be.

<a id="rst-references"></a>

## References

- - **Commercial version of the NTFS driver for Linux.**

    [https://www.paragon-software.com/home/ntfs-linux-professional/](<https://www.paragon-software.com/home/ntfs-linux-professional/>)

- - **Direct e-mail address for feedback and requests on the NTFS3 implementation.**

    [almaz.alexandrovich@paragon-software.com](<mailto:almaz.alexandrovich@paragon-software.com>)

---

# OCFS2 file system - online file check

_Peios Kernel / Internals / Filesystems_

> This document will describe OCFS2 online file check feature.

<a id="rst-ocfs2-file-system-online-file-check"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document will describe OCFS2 online file check feature.

<a id="rst-introduction"></a>

## Introduction

OCFS2 is often used in high-availability systems. However, OCFS2 usually converts the filesystem to read-only when encounters an error. This may not be necessary, since turning the filesystem read-only would affect other running processes as well, decreasing availability. Then, a mount option (errors=continue) is introduced, which would return the -EIO errno to the calling process and terminate further processing so that the filesystem is not corrupted further. The filesystem is not converted to read-only, and the problematic file's inode number is reported in the kernel log. The user can try to check/fix this file via online filecheck feature.

<a id="rst-scope"></a>

## Scope

This effort is to check/fix small issues which may hinder day-to-day operations of a cluster filesystem by turning the filesystem read-only. The scope of checking/fixing is at the file level, initially for regular files and eventually to all files (including system files) of the filesystem.

In case of directory to file links is incorrect, the directory inode is reported as erroneous.

This feature is not suited for extravagant checks which involve dependency of other components of the filesystem, such as but not limited to, checking if the bits for file blocks in the allocation has been set. In case of such an error, the offline fsck should/would be recommended.

Finally, such an operation/feature should not be automated lest the filesystem may end up with more damage than before the repair attempt. So, this has to be performed using user interaction and consent.

<a id="rst-user-interface"></a>

## User interface

When there are errors in the OCFS2 filesystem, they are usually accompanied by the inode number which caused the error. This inode number would be the input to check/fix the file.

There is a sysfs directory for each OCFS2 file system mounting:



```text
/sys/fs/ocfs2/<devname>/filecheck
```

Here, &lt;devname&gt; indicates the name of OCFS2 volume device which has been already mounted. The file above would accept inode numbers. This could be used to communicate with kernel space, tell which file(inode number) will be checked or fixed. Currently, three operations are supported, which includes checking inode, fixing inode and setting the size of result record history.

1. If you want to know what error exactly happened to &lt;inode&gt; before fixing, do:



   ```text
   # echo "<inode>" > /sys/fs/ocfs2/<devname>/filecheck/check
   # cat /sys/fs/ocfs2/<devname>/filecheck/check
   ```

   The output is like this:



   ```text
   INO         DONE    ERROR
   39502               1       GENERATION
   ```

   &lt;INO&gt; lists the inode numbers. &lt;DONE&gt; indicates whether the operation has been finished. &lt;ERROR&gt; says what kind of errors was found. For the detailed error numbers, please refer to the file linux/fs/ocfs2/filecheck.h.

2. If you determine to fix this inode, do:



   ```text
   # echo "<inode>" > /sys/fs/ocfs2/<devname>/filecheck/fix
   # cat /sys/fs/ocfs2/<devname>/filecheck/fix
   ```

   The output is like this:



   ```text
   INO         DONE    ERROR
   39502               1       SUCCESS
   ```

   This time, the &lt;ERROR&gt; column indicates whether this fix is successful or not.

3. The record cache is used to store the history of check/fix results. It's default size is 10, and can be adjust between the range of 10 \~ 100. You can adjust the size like this:



   ```text
   # echo "<size>" > /sys/fs/ocfs2/<devname>/filecheck/set
   ```

<a id="rst-fixing-stuff"></a>

## Fixing stuff

On receiving the inode, the filesystem would read the inode and the file metadata. In case of errors, the filesystem would fix the errors and report the problems it fixed in the kernel log. As a precautionary measure, the inode must first be checked for errors before performing a final fix.

The inode and the result history will be maintained temporarily in a small linked list buffer which would contain the last (N) inodes fixed/checked, the detailed errors which were fixed/checked are printed in the kernel log.

---

# OCFS2 filesystem

_Peios Kernel / Internals / Filesystems_

> OCFS2 is a general purpose extent based shared disk cluster file system with many similarities to ext3. It supports 64 bit inode numbers, and has automatically extending metadata groups which may also make it attractive for non-clustered…

<a id="rst-ocfs2-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

OCFS2 is a general purpose extent based shared disk cluster file system with many similarities to ext3. It supports 64 bit inode numbers, and has automatically extending metadata groups which may also make it attractive for non-clustered use.

You'll want to install the ocfs2-tools package in order to at least get "mount.ocfs2" and "ocfs2_hb_ctl".

Project web page:    [http://ocfs2.wiki.kernel.org](<http://ocfs2.wiki.kernel.org>) Tools git tree:      [https://github.com/markfasheh/ocfs2-tools](<https://github.com/markfasheh/ocfs2-tools>) OCFS2 mailing lists: [https://subspace.kernel.org/lists.linux.dev.html](<https://subspace.kernel.org/lists.linux.dev.html>)

All code copyright 2005 Oracle except when otherwise noted.

<a id="rst-credits"></a>

## Credits

Lots of code taken from ext3 and other projects.

Authors in alphabetical order:

- Joel Becker   &lt;[joel.becker@oracle.com](<mailto:joel.becker@oracle.com>)&gt;

- Zach Brown    &lt;[zach.brown@oracle.com](<mailto:zach.brown@oracle.com>)&gt;

- Mark Fasheh   &lt;[mfasheh@suse.com](<mailto:mfasheh@suse.com>)&gt;

- Kurt Hackel   &lt;[kurt.hackel@oracle.com](<mailto:kurt.hackel@oracle.com>)&gt;

- Tao Ma        &lt;[tao.ma@oracle.com](<mailto:tao.ma@oracle.com>)&gt;

- Sunil Mushran &lt;[sunil.mushran@oracle.com](<mailto:sunil.mushran@oracle.com>)&gt;

- Manish Singh  &lt;[manish.singh@oracle.com](<mailto:manish.singh@oracle.com>)&gt;

- Tiger Yang    &lt;[tiger.yang@oracle.com](<mailto:tiger.yang@oracle.com>)&gt;

<a id="rst-caveats"></a>

## Caveats

Features which OCFS2 does not support yet:

> - Directory change notification (F_NOTIFY)
>
> - Distributed Caching (F_SETLEASE/F_GETLEASE/break_lease)

<a id="rst-mount-options"></a>

## Mount options

OCFS2 supports the following mount options:

(\*) == default


<table>
<tbody>
<tr>
<td>


barrier=1

</td>
<td>


This enables/disables barriers. barrier=0 disables it, barrier=1 enables it.

</td>
</tr>
<tr>
<td>


errors=remount-ro(\*)

</td>
<td>


Remount the filesystem read-only on an error.

</td>
</tr>
<tr>
<td>


errors=panic

</td>
<td>


Panic and halt the machine if an error occurs.

</td>
</tr>
<tr>
<td>


intr            (\*)

</td>
<td>


Allow signals to interrupt cluster operations.

</td>
</tr>
<tr>
<td>


nointr

</td>
<td>


Do not allow signals to interrupt cluster operations.

</td>
</tr>
<tr>
<td>


noatime

</td>
<td>


Do not update access time.

</td>
</tr>
<tr>
<td>


relatime(\*)

</td>
<td>


Update atime if the previous atime is older than mtime or ctime

</td>
</tr>
<tr>
<td>


strictatime

</td>
<td>


Always update atime, but the minimum update interval is specified by atime_quantum.

</td>
</tr>
<tr>
<td>


atime_quantum=60(\*)

</td>
<td>


OCFS2 will not update atime unless this number of seconds has passed since the last update. Set to zero to always update atime. This option need work with strictatime.

</td>
</tr>
<tr>
<td>


data=ordered    (\*)

</td>
<td>


All data are forced directly out to the main file system prior to its metadata being committed to the journal.

</td>
</tr>
<tr>
<td>


data=writeback

</td>
<td>


Data ordering is not preserved, data may be written into the main file system after its metadata has been committed to the journal.

</td>
</tr>
<tr>
<td>


preferred_slot=0(\*)

</td>
<td>


During mount, try to use this filesystem slot first. If it is in use by another node, the first empty one found will be chosen. Invalid values will be ignored.

</td>
</tr>
<tr>
<td>


commit=nrsec    (\*)

</td>
<td>


Ocfs2 can be told to sync all its data and metadata every 'nrsec' seconds. The default value is 5 seconds. This means that if you lose your power, you will lose as much as the latest 5 seconds of work (your filesystem will not be damaged though, thanks to the journaling).  This default value (or any low value) will hurt performance, but it's good for data-safety. Setting it to 0 will have the same effect as leaving it at the default (5 seconds). Setting it to very large values will improve performance.

</td>
</tr>
<tr>
<td>


localalloc=8(\*)

</td>
<td>


Allows custom localalloc size in MB. If the value is too large, the fs will silently revert it to the default.

</td>
</tr>
<tr>
<td>


localflocks

</td>
<td>


This disables cluster aware flock.

</td>
</tr>
<tr>
<td>


inode64

</td>
<td>


Indicates that Ocfs2 is allowed to create inodes at any location in the filesystem, including those which will result in inode numbers occupying more than 32 bits of significance.

</td>
</tr>
<tr>
<td>


user_xattr      (\*)

</td>
<td>


Enables Extended User Attributes.

</td>
</tr>
<tr>
<td>


nouser_xattr

</td>
<td>


Disables Extended User Attributes.

</td>
</tr>
<tr>
<td>


acl

</td>
<td>


Enables POSIX Access Control Lists support.

</td>
</tr>
<tr>
<td>


noacl           (\*)

</td>
<td>


Disables POSIX Access Control Lists support.

</td>
</tr>
<tr>
<td>


resv_level=2    (\*)

</td>
<td>


Set how aggressive allocation reservations will be. Valid values are between 0 (reservations off) to 8 (maximum space for reservations).

</td>
</tr>
<tr>
<td>


dir_resv_level= (\*)

</td>
<td>


By default, directory reservations will scale with file reservations - users should rarely need to change this value. If allocation reservations are turned off, this option will have no effect.

</td>
</tr>
<tr>
<td>


coherency=full  (\*)

</td>
<td>


Disallow concurrent O_DIRECT writes, cluster inode lock will be taken to force other nodes drop cache, therefore full cluster coherency is guaranteed even for O_DIRECT writes.

</td>
</tr>
<tr>
<td>


coherency=buffered

</td>
<td>


Allow concurrent O_DIRECT writes without EX lock among nodes, which gains high performance at risk of getting stale data on other nodes.

</td>
</tr>
<tr>
<td>


journal_async_commit

</td>
<td>


Commit block can be written to disk without waiting for descriptor blocks. If enabled older kernels cannot mount the device. This will enable 'journal_checksum' internally.

</td>
</tr>
</tbody>
</table>

---

# Optimized MPEG Filesystem (OMFS)

_Peios Kernel / Internals / Filesystems_

> OMFS is a filesystem created by SonicBlue for use in the ReplayTV DVR and Rio Karma MP3 player. The filesystem is extent-based, utilizing block sizes from 2k to 8k, with hash-based directories. This filesystem driver may be used to read…

<a id="rst-optimized-mpeg-filesystem-omfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

OMFS is a filesystem created by SonicBlue for use in the ReplayTV DVR and Rio Karma MP3 player.  The filesystem is extent-based, utilizing block sizes from 2k to 8k, with hash-based directories.  This filesystem driver may be used to read and write disks from these devices.

Note, it is not recommended that this FS be used in place of a general filesystem for your own streaming media device.  Native Linux filesystems will likely perform better.

More information is available at:

> [http://linux-karma.sf.net/](<http://linux-karma.sf.net/>)

Various utilities, including mkomfs and omfsck, are included with omfsprogs, available at:

> [https://bobcopeland.com/karma/](<https://bobcopeland.com/karma/>)

Instructions are included in its README.

<a id="rst-options"></a>

## Options

OMFS supports the following mount-time options:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> uid=n
>
> </td>
> <td>
>
>
> make all files owned by specified user
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gid=n
>
> </td>
> <td>
>
>
> make all files owned by specified group
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> umask=xxx
>
> </td>
> <td>
>
>
> set permission umask to xxx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> fmask=xxx
>
> </td>
> <td>
>
>
> set umask to xxx for files
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dmask=xxx
>
> </td>
> <td>
>
>
> set umask to xxx for directories
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-disk-format"></a>

## Disk format

OMFS discriminates between "sysblocks" and normal data blocks.  The sysblock group consists of super block information, file metadata, directory structures, and extents.  Each sysblock has a header containing CRCs of the entire sysblock, and may be mirrored in successive blocks on the disk.  A sysblock may have a smaller size than a data block, but since they are both addressed by the same 64-bit block number, any remaining space in the smaller sysblock is unused.

Sysblock header information:



```text
struct omfs_header {
        __be64 h_self;                  /* FS block where this is located */
        __be32 h_body_size;             /* size of useful data after header */
        __be16 h_crc;                   /* crc-ccitt of body_size bytes */
        char h_fill1[2];
        u8 h_version;                   /* version, always 1 */
        char h_type;                    /* OMFS_INODE_X */
        u8 h_magic;                     /* OMFS_IMAGIC */
        u8 h_check_xor;                 /* XOR of header bytes before this */
        __be32 h_fill2;
};
```

Files and directories are both represented by omfs_inode:



```text
struct omfs_inode {
        struct omfs_header i_head;      /* header */
        __be64 i_parent;                /* parent containing this inode */
        __be64 i_sibling;               /* next inode in hash bucket */
        __be64 i_ctime;                 /* ctime, in milliseconds */
        char i_fill1[35];
        char i_type;                    /* OMFS_[DIR,FILE] */
        __be32 i_fill2;
        char i_fill3[64];
        char i_name[OMFS_NAMELEN];      /* filename */
        __be64 i_size;                  /* size of file, in bytes */
};
```

Directories in OMFS are implemented as a large hash table.  Filenames are hashed then prepended into the bucket list beginning at OMFS_DIR_START. Lookup requires hashing the filename, then seeking across i_sibling pointers until a match is found on i_name.  Empty buckets are represented by block pointers with all-1s (\~0).

A file is an omfs_inode structure followed by an extent table beginning at OMFS_EXTENT_START:



```text
struct omfs_extent_entry {
        __be64 e_cluster;               /* start location of a set of blocks */
        __be64 e_blocks;                /* number of blocks after e_cluster */
};

struct omfs_extent {
        __be64 e_next;                  /* next extent table location */
        __be32 e_extent_count;          /* total # extents in this table */
        __be32 e_fill;
        struct omfs_extent_entry e_entry;       /* start of extent entries */
};
```

Each extent holds the block offset followed by number of blocks allocated to the extent.  The final extent in each table is a terminator with e_cluster being \~0 and e_blocks being ones'-complement of the total number of blocks in the table.

If this table overflows, a continuation inode is written and pointed to by e_next.  These have a header but lack the rest of the inode structure.

---

# ORANGEFS

_Peios Kernel / Internals / Filesystems_

> OrangeFS is an LGPL userspace scale-out parallel storage system. It is ideal for large storage problems faced by HPC, BigData, Streaming Video, Genomics, Bioinformatics.

<a id="rst-orangefs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

OrangeFS is an LGPL userspace scale-out parallel storage system. It is ideal for large storage problems faced by HPC, BigData, Streaming Video, Genomics, Bioinformatics.

Orangefs, originally called PVFS, was first developed in 1993 by Walt Ligon and Eric Blumer as a parallel file system for Parallel Virtual Machine (PVM) as part of a NASA grant to study the I/O patterns of parallel programs.

Orangefs features include:

> - Distributes file data among multiple file servers
>
> - Supports simultaneous access by multiple clients
>
> - Stores file data and metadata on servers using local file system and access methods
>
> - Userspace implementation is easy to install and maintain
>
> - Direct MPI support
>
> - Stateless

<a id="rst-mailing-list-archives"></a>

## Mailing List Archives

[http://lists.orangefs.org/pipermail/devel_lists.orangefs.org/](<http://lists.orangefs.org/pipermail/devel_lists.orangefs.org/>)

<a id="rst-mailing-list-submissions"></a>

## Mailing List Submissions

[devel@lists.orangefs.org](<mailto:devel@lists.orangefs.org>)

<a id="rst-documentation"></a>

## Documentation

[http://www.orangefs.org/documentation/](<http://www.orangefs.org/documentation/>)

<a id="rst-running-orangefs-on-a-single-server"></a>

## Running ORANGEFS On a Single Server

OrangeFS is usually run in large installations with multiple servers and clients, but a complete filesystem can be run on a single machine for development and testing.

On Fedora, install orangefs and orangefs-server:



```text
dnf -y install orangefs orangefs-server
```

There is an example server configuration file in /etc/orangefs/orangefs.conf.  Change localhost to your hostname if necessary.

To generate a filesystem to run xfstests against, see below.

There is an example client configuration file in /etc/pvfs2tab.  It is a single line.  Uncomment it and change the hostname if necessary.  This controls clients which use libpvfs2.  This does not control the pvfs2-client-core.

Create the filesystem:



```text
pvfs2-server -f /etc/orangefs/orangefs.conf
```

Start the server:



```text
systemctl start orangefs-server
```

Test the server:



```text
pvfs2-ping -m /pvfsmnt
```

Start the client.  The module must be compiled in or loaded before this point:



```text
systemctl start orangefs-client
```

Mount the filesystem:



```text
mount -t pvfs2 tcp://localhost:3334/orangefs /pvfsmnt
```

<a id="rst-userspace-filesystem-source"></a>

## Userspace Filesystem Source

[http://www.orangefs.org/download](<http://www.orangefs.org/download>)

Orangefs versions prior to 2.9.3 would not be compatible with the upstream version of the kernel client.

<a id="rst-building-orangefs-on-a-single-server"></a>

## Building ORANGEFS on a Single Server

Where OrangeFS cannot be installed from distribution packages, it may be built from source.

You can omit --prefix if you don't care that things are sprinkled around in /usr/local.  As of version 2.9.6, OrangeFS uses Berkeley DB by default, we will probably be changing the default to LMDB soon.



```text
./configure --prefix=/opt/ofs --with-db-backend=lmdb --disable-usrint

make

make install
```

Create an orangefs config file by running pvfs2-genconfig and specifying a target config file. Pvfs2-genconfig will prompt you through. Generally it works fine to take the defaults, but you should use your server's hostname, rather than "localhost" when it comes to that question:



```text
/opt/ofs/bin/pvfs2-genconfig /etc/pvfs2.conf
```

Create an /etc/pvfs2tab file (localhost is fine):



```text
echo tcp://localhost:3334/orangefs /pvfsmnt pvfs2 defaults,noauto 0 0 > \
    /etc/pvfs2tab
```

Create the mount point you specified in the tab file if needed:



```text
mkdir /pvfsmnt
```

Bootstrap the server:



```text
/opt/ofs/sbin/pvfs2-server -f /etc/pvfs2.conf
```

Start the server:



```text
/opt/ofs/sbin/pvfs2-server /etc/pvfs2.conf
```

Now the server should be running. Pvfs2-ls is a simple test to verify that the server is running:



```text
/opt/ofs/bin/pvfs2-ls /pvfsmnt
```

If stuff seems to be working, load the kernel module and turn on the client core:



```text
/opt/ofs/sbin/pvfs2-client -p /opt/ofs/sbin/pvfs2-client-core
```

Mount your filesystem:



```text
mount -t pvfs2 tcp://`hostname`:3334/orangefs /pvfsmnt
```

<a id="rst-running-xfstests"></a>

## Running xfstests

It is useful to use a scratch filesystem with xfstests.  This can be done with only one server.

Make a second copy of the FileSystem section in the server configuration file, which is /etc/orangefs/orangefs.conf.  Change the Name to scratch. Change the ID to something other than the ID of the first FileSystem section (2 is usually a good choice).

Then there are two FileSystem sections: orangefs and scratch.

This change should be made before creating the filesystem.



```text
pvfs2-server -f /etc/orangefs/orangefs.conf
```

To run xfstests, create /etc/xfsqa.config:



```text
TEST_DIR=/orangefs
TEST_DEV=tcp://localhost:3334/orangefs
SCRATCH_MNT=/scratch
SCRATCH_DEV=tcp://localhost:3334/scratch
```

Then xfstests can be run:



```text
./check -pvfs2
```

<a id="rst-options"></a>

## Options

The following mount options are accepted:

> - **acl**
>
>   Allow the use of Access Control Lists on files and directories.
>
> - **intr**
>
>   Some operations between the kernel client and the user space filesystem can be interruptible, such as changes in debug levels and the setting of tunable parameters.
>
> - **local_lock**
>
>   Enable posix locking from the perspective of "this" kernel. The default file_operations lock action is to return ENOSYS. Posix locking kicks in if the filesystem is mounted with -o local_lock. Distributed locking is being worked on for the future.

<a id="rst-debugging"></a>

## Debugging

If you want the debug (GOSSIP) statements in a particular source file (inode.c for example) go to syslog:



```text
echo inode > /sys/kernel/debug/orangefs/kernel-debug
```

No debugging (the default):



```text
echo none > /sys/kernel/debug/orangefs/kernel-debug
```

Debugging from several source files:



```text
echo inode,dir > /sys/kernel/debug/orangefs/kernel-debug
```

All debugging:



```text
echo all > /sys/kernel/debug/orangefs/kernel-debug
```

Get a list of all debugging keywords:



```text
cat /sys/kernel/debug/orangefs/debug-help
```

<a id="rst-protocol-between-kernel-module-and-userspace"></a>

## Protocol between Kernel Module and Userspace

Orangefs is a user space filesystem and an associated kernel module. We'll just refer to the user space part of Orangefs as "userspace" from here on out. Orangefs descends from PVFS, and userspace code still uses PVFS for function and variable names. Userspace typedefs many of the important structures. Function and variable names in the kernel module have been transitioned to "orangefs", and The Linux Coding Style avoids typedefs, so kernel module structures that correspond to userspace structures are not typedefed.

The kernel module implements a pseudo device that userspace can read from and write to. Userspace can also manipulate the kernel module through the pseudo device with ioctl.

<a id="rst-the-bufmap"></a>

### The Bufmap

At startup userspace allocates two page-size-aligned (posix_memalign) mlocked memory buffers, one is used for IO and one is used for readdir operations. The IO buffer is 41943040 bytes and the readdir buffer is 4194304 bytes. Each buffer contains logical chunks, or partitions, and a pointer to each buffer is added to its own PVFS_dev_map_desc structure which also describes its total size, as well as the size and number of the partitions.

A pointer to the IO buffer's PVFS_dev_map_desc structure is sent to a mapping routine in the kernel module with an ioctl. The structure is copied from user space to kernel space with copy_from_user and is used to initialize the kernel module's "bufmap" (struct orangefs_bufmap), which then contains:

> - refcnt - a reference counter
>
> - desc_size - PVFS2_BUFMAP_DEFAULT_DESC_SIZE (4194304) - the IO buffer's partition size, which represents the filesystem's block size and is used for s_blocksize in super blocks.
>
> - desc_count - PVFS2_BUFMAP_DEFAULT_DESC_COUNT (10) - the number of partitions in the IO buffer.
>
> - desc_shift - log2(desc_size), used for s_blocksize_bits in super blocks.
>
> - total_size - the total size of the IO buffer.
>
> - page_count - the number of 4096 byte pages in the IO buffer.
>
> - page_array - a pointer to `page_count * (sizeof(struct page*))` bytes of kcalloced memory. This memory is used as an array of pointers to each of the pages in the IO buffer through a call to get_user_pages.
>
> - desc_array - a pointer to `desc_count * (sizeof(struct orangefs_bufmap_desc))` bytes of kcalloced memory. This memory is further initialized:
>
>   > user_desc is the kernel's copy of the IO buffer's ORANGEFS_dev_map_desc structure. user_desc-&gt;ptr points to the IO buffer.
>   >
>   >
>   >
>   > ```text
>   > pages_per_desc = bufmap->desc_size / PAGE_SIZE
>   > offset = 0
>   >
>   > bufmap->desc_array[0].page_array = &bufmap->page_array[offset]
>   > bufmap->desc_array[0].array_count = pages_per_desc = 1024
>   > bufmap->desc_array[0].uaddr = (user_desc->ptr) + (0 * 1024 * 4096)
>   > offset += 1024
>   >                    .
>   >                    .
>   >                    .
>   > bufmap->desc_array[9].page_array = &bufmap->page_array[offset]
>   > bufmap->desc_array[9].array_count = pages_per_desc = 1024
>   > bufmap->desc_array[9].uaddr = (user_desc->ptr) +
>   >                                        (9 * 1024 * 4096)
>   > offset += 1024
>   > ```
>
> - buffer_index_array - a desc_count sized array of ints, used to indicate which of the IO buffer's partitions are available to use.
>
> - buffer_index_lock - a spinlock to protect buffer_index_array during update.
>
> - readdir_index_array - a five (ORANGEFS_READDIR_DEFAULT_DESC_COUNT) element int array used to indicate which of the readdir buffer's partitions are available to use.
>
> - readdir_index_lock - a spinlock to protect readdir_index_array during update.

<a id="rst-operations"></a>

### Operations

The kernel module builds an "op" (struct orangefs_kernel_op_s) when it needs to communicate with userspace. Part of the op contains the "upcall" which expresses the request to userspace. Part of the op eventually contains the "downcall" which expresses the results of the request.

The slab allocator is used to keep a cache of op structures handy.

At init time the kernel module defines and initializes a request list and an in_progress hash table to keep track of all the ops that are in flight at any given time.

Ops are stateful:

> - - **unknown**
>
>     - op was just initialized
>
> - - **waiting**
>
>     - op is on request_list (upward bound)
>
> - - **inprogr**
>
>     - op is in progress (waiting for downcall)
>
> - - **serviced**
>
>     - op has matching downcall; ok
>
> - - **purged**
>
>     - op has to start a timer since client-core exited uncleanly before servicing op
>
> - - **given up**
>
>     - submitter has given up waiting for it

When some arbitrary userspace program needs to perform a filesystem operation on Orangefs (readdir, I/O, create, whatever) an op structure is initialized and tagged with a distinguishing ID number. The upcall part of the op is filled out, and the op is passed to the "service_operation" function.

Service_operation changes the op's state to "waiting", puts it on the request list, and signals the Orangefs file_operations.poll function through a wait queue. Userspace is polling the pseudo-device and thus becomes aware of the upcall request that needs to be read.

When the Orangefs file_operations.read function is triggered, the request list is searched for an op that seems ready-to-process. The op is removed from the request list. The tag from the op and the filled-out upcall struct are copy_to_user'ed back to userspace.

If any of these (and some additional protocol) copy_to_users fail, the op's state is set to "waiting" and the op is added back to the request list. Otherwise, the op's state is changed to "in progress", and the op is hashed on its tag and put onto the end of a list in the in_progress hash table at the index the tag hashed to.

When userspace has assembled the response to the upcall, it writes the response, which includes the distinguishing tag, back to the pseudo device in a series of io_vecs. This triggers the Orangefs file_operations.write_iter function to find the op with the associated tag and remove it from the in_progress hash table. As long as the op's state is not "canceled" or "given up", its state is set to "serviced". The file_operations.write_iter function returns to the waiting vfs, and back to service_operation through wait_for_matching_downcall.

Service operation returns to its caller with the op's downcall part (the response to the upcall) filled out.

The "client-core" is the bridge between the kernel module and userspace. The client-core is a daemon. The client-core has an associated watchdog daemon. If the client-core is ever signaled to die, the watchdog daemon restarts the client-core. Even though the client-core is restarted "right away", there is a period of time during such an event that the client-core is dead. A dead client-core can't be triggered by the Orangefs file_operations.poll function. Ops that pass through service_operation during a "dead spell" can timeout on the wait queue and one attempt is made to recycle them. Obviously, if the client-core stays dead too long, the arbitrary userspace processes trying to use Orangefs will be negatively affected. Waiting ops that can't be serviced will be removed from the request list and have their states set to "given up". In-progress ops that can't be serviced will be removed from the in_progress hash table and have their states set to "given up".

Readdir and I/O ops are atypical with respect to their payloads.

> - readdir ops use the smaller of the two pre-allocated pre-partitioned memory buffers. The readdir buffer is only available to userspace. The kernel module obtains an index to a free partition before launching a readdir op. Userspace deposits the results into the indexed partition and then writes them to back to the pvfs device.
>
> - io (read and write) ops use the larger of the two pre-allocated pre-partitioned memory buffers. The IO buffer is accessible from both userspace and the kernel module. The kernel module obtains an index to a free partition before launching an io op. The kernel module deposits write data into the indexed partition, to be consumed directly by userspace. Userspace deposits the results of read requests into the indexed partition, to be consumed directly by the kernel module.

Responses to kernel requests are all packaged in pvfs2_downcall_t structs. Besides a few other members, pvfs2_downcall_t contains a union of structs, each of which is associated with a particular response type.

The several members outside of the union are:

> - **`int32_t type`**
>
>   - type of operation.
>
> - **`int32_t status`**
>
>   - return code for the operation.
>
> - **`int64_t trailer_size`**
>
>   - 0 unless readdir operation.
>
> - **`char *trailer_buf`**
>
>   - initialized to NULL, used during readdir operations.

The appropriate member inside the union is filled out for any particular response.

> - **PVFS2_VFS_OP_FILE_IO**
>
>   fill a pvfs2_io_response_t
>
> - **PVFS2_VFS_OP_LOOKUP**
>
>   fill a PVFS_object_kref
>
> - **PVFS2_VFS_OP_CREATE**
>
>   fill a PVFS_object_kref
>
> - **PVFS2_VFS_OP_SYMLINK**
>
>   fill a PVFS_object_kref
>
> - **PVFS2_VFS_OP_GETATTR**
>
>   fill in a PVFS_sys_attr_s (tons of stuff the kernel doesn't need) fill in a string with the link target when the object is a symlink.
>
> - **PVFS2_VFS_OP_MKDIR**
>
>   fill a PVFS_object_kref
>
> - **PVFS2_VFS_OP_STATFS**
>
>   fill a pvfs2_statfs_response_t with useless info &lt;g&gt;. It is hard for us to know, in a timely fashion, these statistics about our distributed network filesystem.
>
> - **PVFS2_VFS_OP_FS_MOUNT**
>
>   fill a pvfs2_fs_mount_response_t which is just like a PVFS_object_kref except its members are in a different order and "\__pad1" is replaced with "id".
>
> - **PVFS2_VFS_OP_GETXATTR**
>
>   fill a pvfs2_getxattr_response_t
>
> - **PVFS2_VFS_OP_LISTXATTR**
>
>   fill a pvfs2_listxattr_response_t
>
> - **PVFS2_VFS_OP_PARAM**
>
>   fill a pvfs2_param_response_t
>
> - **PVFS2_VFS_OP_PERF_COUNT**
>
>   fill a pvfs2_perf_count_response_t
>
> - **PVFS2_VFS_OP_FSKEY**
>
>   file a pvfs2_fs_key_response_t
>
> - **PVFS2_VFS_OP_READDIR**
>
>   jamb everything needed to represent a pvfs2_readdir_response_t into the readdir buffer descriptor specified in the upcall.

Userspace uses writev() on /dev/pvfs2-req to pass responses to the requests made by the kernel side.

A buffer_list containing:

> - a pointer to the prepared response to the request from the kernel (struct pvfs2_downcall_t).
>
> - and also, in the case of a readdir request, a pointer to a buffer containing descriptors for the objects in the target directory.

... is sent to the function (PINT_dev_write_list) which performs the writev.

PINT_dev_write_list has a local iovec array: struct iovec io_array\[10\];

The first four elements of io_array are initialized like this for all responses:



```text
io_array[0].iov_base = address of local variable "proto_ver" (int32_t)
io_array[0].iov_len = sizeof(int32_t)

io_array[1].iov_base = address of global variable "pdev_magic" (int32_t)
io_array[1].iov_len = sizeof(int32_t)

io_array[2].iov_base = address of parameter "tag" (PVFS_id_gen_t)
io_array[2].iov_len = sizeof(int64_t)

io_array[3].iov_base = address of out_downcall member (pvfs2_downcall_t)
                       of global variable vfs_request (vfs_request_t)
io_array[3].iov_len = sizeof(pvfs2_downcall_t)
```

Readdir responses initialize the fifth element io_array like this:



```text
io_array[4].iov_base = contents of member trailer_buf (char *)
                       from out_downcall member of global variable
                       vfs_request
io_array[4].iov_len = contents of member trailer_size (PVFS_size)
                      from out_downcall member of global variable
                      vfs_request
```

Orangefs exploits the dcache in order to avoid sending redundant requests to userspace. We keep object inode attributes up-to-date with orangefs_inode_getattr. Orangefs_inode_getattr uses two arguments to help it decide whether or not to update an inode: "new" and "bypass". Orangefs keeps private data in an object's inode that includes a short timeout value, getattr_time, which allows any iteration of orangefs_inode_getattr to know how long it has been since the inode was updated. When the object is not new (new == 0) and the bypass flag is not set (bypass == 0) orangefs_inode_getattr returns without updating the inode if getattr_time has not timed out. Getattr_time is updated each time the inode is updated.

Creation of a new object (file, dir, sym-link) includes the evaluation of its pathname, resulting in a negative directory entry for the object. A new inode is allocated and associated with the dentry, turning it from a negative dentry into a "productive full member of society". Orangefs obtains the new inode from Linux with new_inode() and associates the inode with the dentry by sending the pair back to Linux with d_instantiate().

The evaluation of a pathname for an object resolves to its corresponding dentry. If there is no corresponding dentry, one is created for it in the dcache. Whenever a dentry is modified or verified Orangefs stores a short timeout value in the dentry's d_time, and the dentry will be trusted for that amount of time. Orangefs is a network filesystem, and objects can potentially change out-of-band with any particular Orangefs kernel module instance, so trusting a dentry is risky. The alternative to trusting dentries is to always obtain the needed information from userspace - at least a trip to the client-core, maybe to the servers. Obtaining information from a dentry is cheap, obtaining it from userspace is relatively expensive, hence the motivation to use the dentry when possible.

The timeout values d_time and getattr_time are jiffy based, and the code is designed to avoid the jiffy-wrap problem:



```text
"In general, if the clock may have wrapped around more than once, there
is no way to tell how much time has elapsed. However, if the times t1
and t2 are known to be fairly close, we can reliably compute the
difference in a way that takes into account the possibility that the
clock may have wrapped between times."
```

from course notes by instructor Andy Wang

---

# Overlay Filesystem

_Peios Kernel / Internals / Filesystems_

> OverlayFS layering, copy-up and native descriptor handling in Peios.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<!-- SPDX-License-Identifier: GPL-2.0 -->

Written by: Neil Brown Please see MAINTAINERS file for where to send questions.

<a id="rst-overlay-filesystem"></a>

## Overlay Filesystem

This document describes a prototype for a new approach to providing overlay-filesystem functionality in Linux (sometimes referred to as union-filesystems).  An overlay-filesystem tries to present a filesystem which is the result of overlaying one filesystem on top of the other.

<a id="rst-overlay-objects"></a>

### Overlay objects

The overlay filesystem approach is 'hybrid', because the objects that appear in the filesystem do not always appear to belong to that filesystem. In many cases, an object accessed in the union will be indistinguishable from accessing the corresponding object from the original filesystem. This is most obvious from the 'st_dev' field returned by stat(2).

While directories will report an st_dev from the overlay-filesystem, non-directory objects may report an st_dev from the lower filesystem or upper filesystem that is providing the object.  Similarly st_ino will only be unique when combined with st_dev, and both of these can change over the lifetime of a non-directory object.  Many applications and tools ignore these values and will not be affected.

In the special case of all overlay layers on the same underlying filesystem, all objects will report an st_dev from the overlay filesystem and st_ino from the underlying filesystem.  This will make the overlay mount more compliant with filesystem scanners and overlay objects will be distinguishable from the corresponding objects in the original filesystem.

On 64bit systems, even if all overlay layers are not on the same underlying filesystem, the same compliant behavior could be achieved with the "xino" feature.  The "xino" feature composes a unique object identifier from the real object st_ino and an underlying fsid number. The "xino" feature uses the high inode number bits for fsid, because the underlying filesystems rarely use the high inode number bits.  In case the underlying inode number does overflow into the high xino bits, overlay filesystem will fall back to the non xino behavior for that inode.

The "xino" feature can be enabled with the "-o xino=on" overlay mount option. If all underlying filesystems support NFS file handles, the value of st_ino for overlay filesystem objects is not only unique, but also persistent over the lifetime of the filesystem.  The "-o xino=auto" overlay mount option enables the "xino" feature only if the persistent st_ino requirement is met.

The following table summarizes what can be expected in different overlay configurations.

<a id="rst-inode-properties"></a>

#### Inode properties


<table>
<thead>
<tr>
<th>


Configuration

</th>
<th colspan="2">


Persistent st_ino

</th>
<th colspan="2">


Uniform st_dev

</th>
<th colspan="2">


st_ino == d_ino

</th>
<th colspan="2">


d_ino == i_ino \[\*\]

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>


dir

</td>
<td>


\!dir

</td>
<td>


dir

</td>
<td>


\!dir

</td>
<td>


dir

</td>
<td>


\!dir

</td>
<td>


dir

</td>
<td>


\!dir

</td>
</tr>
<tr>
<td>


All layers on same fs

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
</tr>
<tr>
<td>


Layers not on same fs, xino=off

</td>
<td>


N

</td>
<td>


N

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


N

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


Y

</td>
</tr>
<tr>
<td>


xino=on/auto

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
<td>


Y

</td>
</tr>
<tr>
<td>


xino=on/auto, ino overflow

</td>
<td>


N

</td>
<td>


N

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


N

</td>
<td>


Y

</td>
<td>


N

</td>
<td>


Y

</td>
</tr>
</tbody>
</table>

\[\*\] nfsd v3 readdirplus verifies d_ino == i_ino. i_ino is exposed via several /proc files, such as /proc/locks and /proc/self/fdinfo/&lt;fd&gt; of an inotify file descriptor.

<a id="rst-upper-and-lower"></a>

### Upper and Lower

An overlay filesystem combines two filesystems - an 'upper' filesystem and a 'lower' filesystem.  When a name exists in both filesystems, the object in the 'upper' filesystem is visible while the object in the 'lower' filesystem is either hidden or, in the case of directories, merged with the 'upper' object.

It would be more correct to refer to an upper and lower 'directory tree' rather than 'filesystem' as it is quite possible for both directory trees to be in the same filesystem and there is no requirement that the root of a filesystem be given for either upper or lower.

A wide range of filesystems supported by Linux can be the lower filesystem, but not all filesystems that are mountable by Linux have the features needed for OverlayFS to work.  The lower filesystem does not need to be writable.  The lower filesystem can even be another overlayfs.  The upper filesystem will normally be writable and if it is it must support the creation of trusted.\* and/or user.\* extended attributes, and must provide valid d_type in readdir responses, so NFS is not suitable.

A read-only overlay of two read-only filesystems may use any filesystem type.

<a id="rst-directories"></a>

### Directories

Overlaying mainly involves directories.  If a given name appears in both upper and lower filesystems and refers to a non-directory in either, then the lower object is hidden - the name refers only to the upper object.

Where both upper and lower objects are directories, a merged directory is formed.

At mount time, the two directories given as mount options "lowerdir" and "upperdir" are combined into a merged directory:



```text
mount -t overlay overlay -olowerdir=/lower,upperdir=/upper,\
workdir=/work /merged
```

The "workdir" needs to be an empty directory on the same filesystem as upperdir.

Then whenever a lookup is requested in such a merged directory, the lookup is performed in each actual directory and the combined result is cached in the dentry belonging to the overlay filesystem.  If both actual lookups find directories, both are stored and a merged directory is created, otherwise only one is stored: the upper if it exists, else the lower.

Only the lists of names from directories are merged.  Other content such as metadata and extended attributes are reported for the upper directory only.  These attributes of the lower directory are hidden.

<a id="rst-whiteouts-and-opaque-directories"></a>

### whiteouts and opaque directories

In order to support rm and rmdir without changing the lower filesystem, an overlay filesystem needs to record in the upper filesystem that files have been removed.  This is done using whiteouts and opaque directories (non-directories are always opaque).

A whiteout is created as a character device with 0/0 device number or as a zero-size regular file with the xattr "trusted.overlay.whiteout".

When a whiteout is found in the upper level of a merged directory, any matching name in the lower level is ignored, and the whiteout itself is also hidden.

A directory is made opaque by setting the xattr "trusted.overlay.opaque" to "y".  Where the upper filesystem contains an opaque directory, any directory in the lower filesystem with the same name is ignored.

An opaque directory should not contain any whiteouts, because they do not serve any purpose.  A merge directory containing regular files with the xattr "trusted.overlay.whiteout", should be additionally marked by setting the xattr "trusted.overlay.opaque" to "x" on the merge directory itself. This is needed to avoid the overhead of checking the "trusted.overlay.whiteout" on all entries during readdir in the common case.

<a id="rst-readdir"></a>

### readdir

When a 'readdir' request is made on a merged directory, the upper and lower directories are each read and the name lists merged in the obvious way (upper is read first, then lower - entries that already exist are not re-added).  This merged name list is cached in the 'struct file' and so remains as long as the file is kept open.  If the directory is opened and read by two processes at the same time, they will each have separate caches.  A seekdir to the start of the directory (offset 0) followed by a readdir will cause the cache to be discarded and rebuilt.

This means that changes to the merged directory do not appear while a directory is being read.  This is unlikely to be noticed by many programs.

seek offsets are assigned sequentially when the directories are read. Thus if:

> - read part of a directory
>
> - remember an offset, and close the directory
>
> - re-open the directory some time later
>
> - seek to the remembered offset

there may be little correlation between the old and new locations in the list of filenames, particularly if anything has changed in the directory.

Readdir on directories that are not merged is simply handled by the underlying directory (upper or lower).

<a id="rst-renaming-directories"></a>

### renaming directories

When renaming a directory that is on the lower layer or merged (i.e. the directory was not created on the upper layer to start with) overlayfs can handle it in two different ways:

1. return EXDEV error: this error is returned by rename(2) when trying to move a file or directory across filesystem boundaries.  Hence applications are usually prepared to handle this error (mv(1) for example recursively copies the directory tree).  This is the default behavior.

2. If the "redirect_dir" feature is enabled, then the directory will be copied up (but not the contents).  Then the "trusted.overlay.redirect" extended attribute is set to the path of the original location from the root of the overlay.  Finally the directory is moved to the new location.

There are several ways to tune the "redirect_dir" feature.

Kernel config options:

- - **OVERLAY_FS_REDIRECT_DIR:**

    If this is enabled, then redirect_dir is turned on by  default.

- - **OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW:**

    If this is enabled, then redirects are always followed by default. Enabling this results in a less secure configuration.  Enable this option only when worried about backward compatibility with kernels that have the redirect_dir feature and follow redirects even if turned off.

Module options (can also be changed through /sys/module/overlay/parameters/):

- - **"redirect_dir=BOOL":**

    See OVERLAY_FS_REDIRECT_DIR kernel config option above.

- - **"redirect_always_follow=BOOL":**

    See OVERLAY_FS_REDIRECT_ALWAYS_FOLLOW kernel config option above.

- - **"redirect_max=NUM":**

    The maximum number of bytes in an absolute redirect (default is 256).

Mount options:

- - **"redirect_dir=on":**

    Redirects are enabled.

- - **"redirect_dir=follow":**

    Redirects are not created, but followed.

- - **"redirect_dir=nofollow":**

    Redirects are not created and not followed.

- - **"redirect_dir=off":**

    If "redirect_always_follow" is enabled in the kernel/module config, this "off" translates to "follow", otherwise it translates to "nofollow".

When the NFS export feature is enabled, every copied up directory is indexed by the file handle of the lower inode and a file handle of the upper directory is stored in a "trusted.overlay.upper" extended attribute on the index entry.  On lookup of a merged directory, if the upper directory does not match the file handle stores in the index, that is an indication that multiple upper directories may be redirected to the same lower directory.  In that case, lookup returns an error and warns about a possible inconsistency.

Because lower layer redirects cannot be verified with the index, enabling NFS export support on an overlay filesystem with no upper layer requires turning off redirect follow (e.g. "redirect_dir=nofollow").

<a id="rst-non-directories"></a>

### Non-directories

Objects that are not directories (files, symlinks, device-special files etc.) are presented either from the upper or lower filesystem as appropriate.  When a file in the lower filesystem is accessed in a way that requires write-access, such as opening for write access, changing some metadata etc., the file is first copied from the lower filesystem to the upper filesystem (copy_up).  Note that creating a hard-link also requires copy_up, though of course creation of a symlink does not.

The copy_up may turn out to be unnecessary, for example if the file is opened for read-write but the data is not modified.

The copy_up process first makes sure that the containing directory exists in the upper filesystem - creating it and any parents as necessary.  It then creates the object with the same metadata (owner, mode, mtime, symlink-target etc.) and then if the object is a file, the data is copied from the lower to the upper filesystem.  Finally any extended attributes are copied up.

Once the copy_up is complete, the overlay filesystem simply provides direct access to the newly created file in the upper filesystem - future operations on the file are barely noticed by the overlay filesystem (though an operation on the name of the file such as rename or unlink will of course be noticed and handled).

<a id="rst-permission-model"></a>

### Permission model

OverlayFS stashes credentials for operations on its backing layers. The old
mount API records the mounting task's credentials. With the new API, superblock
creation normally records the `FSCONFIG_CMD_CREATE` caller; setting
`override_creds` records the caller supplying that option instead. These credentials include
the KACS subject, not just Unix IDs.

Access involves checks on the overlay object for the caller and on backing
objects under the saved operation context. In Peios, copying Unix owner, group,
mode and POSIX ACL data is not sufficient to preserve access. KACS explicitly
preserves native descriptors during copy-up: `pkm_kacs_inode_copy_up()` captures
the source SD and carries it on the prepared credential for the upper inode's
creation. The canonical SD xattr is excluded from the ordinary xattr-copy loop;
it is not discarded without replacement. An unmanaged source has no managed
descriptor to preserve.

For an ordinary creation through an overlay, the KACS create hook derives the
new descriptor using the calling subject and the overlay parent rather than
silently substituting the mounter as the creator. It also carries the caller's
projected IDs to the backing creation. Native file-handle grants and subsequent
operation checks continue to apply.

Consequently, `cp -a` followed by a bind mount is not a general access-policy
equivalent of an OverlayFS mount. Generic userspace xattr copying cannot write
the canonical Peios SD, and server-side checks on remote backing filesystems
remain distinct. A setup must provide appropriate descriptors, mount policy
and backing credentials; enabling OverlayFS does not qualify every layer
combination.

Creating an OverlayFS mount requires enabled `SeManageVolumePrivilege` or
`SeTcbPrivilege`: OverlayFS is outside the new-mount descriptor-only allowlist.
The `userxattr` option does not remove that native mount requirement.

<a id="rst-multiple-lower-layers"></a>

### Multiple lower layers

Multiple lower layers can now be given using the colon (":") as a separator character between the directory names.  For example:



```text
mount -t overlay overlay -olowerdir=/lower1:/lower2:/lower3 /merged
```

As the example shows, "upperdir=" and "workdir=" may be omitted.  In that case the overlay will be read-only.

The specified lower directories will be stacked beginning from the rightmost one and going left.  In the above example lower1 will be the top, lower2 the middle and lower3 the bottom layer.

Note: directory names containing colons can be provided as lower layer by escaping the colons with a single backslash.  For example:



```text
mount -t overlay overlay -olowerdir=/a\:lower\:\:dir /merged
```

Since kernel version v6.8, directory names containing colons can also be configured as lower layer using the "lowerdir+" mount options and the fsconfig syscall from new mount api.  For example:



```text
fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/a:lower::dir", 0);
```

In the latter case, colons in lower layer directory names will be escaped as an octal characters (072) when displayed in /proc/self/mountinfo.

<a id="rst-metadata-only-copy-up"></a>

### Metadata only copy up

When the "metacopy" feature is enabled, overlayfs will only copy up metadata (as opposed to whole file), when a metadata specific operation like chown/chmod is performed. An upper file in this state is marked with "trusted.overlayfs.metacopy" xattr which indicates that the upper file contains no data.  The data will be copied up later when file is opened for WRITE operation.  After the lower file's data is copied up, the "trusted.overlayfs.metacopy" xattr is removed from the upper file.

In other words, this is delayed data copy up operation and data is copied up when there is a need to actually modify data.

There are multiple ways to enable/disable this feature. A config option CONFIG_OVERLAY_FS_METACOPY can be set/unset to enable/disable this feature by default. Or one can enable/disable it at module load time with module parameter metacopy=on/off. Lastly, there is also a per mount option metacopy=on/off to enable/disable this feature per mount.

Do not use metacopy=on with untrusted upper/lower directories. Otherwise it is possible that an attacker can create a handcrafted file with appropriate REDIRECT and METACOPY xattrs, and gain access to file on lower pointed by REDIRECT. This should not be possible on local system as setting "trusted." xattrs will require CAP_SYS_ADMIN. But it should be possible for untrusted layers like from a pen drive.

Note: redirect_dir=\{off\|nofollow\|follow\[\*\]\} and nfs_export=on mount options conflict with metacopy=on, and will result in an error.

\[\*\] redirect_dir=follow only conflicts with metacopy=on if upperdir=... is given.

<a id="rst-data-only-lower-layers"></a>

### Data-only lower layers

With "metacopy" feature enabled, an overlayfs regular file may be a composition of information from up to three different layers:

> 1. metadata from a file in the upper layer
>
> 2. st_ino and st_dev object identifier from a file in a lower layer
>
> 3. data from a file in another lower layer (further below)

The "lower data" file can be on any lower layer, except from the top most lower layer.

Below the topmost lower layer, any number of lowermost layers may be defined as "data-only" lower layers, using double colon ("::") separators. A normal lower layer is not allowed to be below a data-only layer, so single colon separators are not allowed to the right of double colon ("::") separators.

For example:



```text
mount -t overlay overlay -olowerdir=/l1:/l2:/l3::/do1::/do2 /merged
```

The paths of files in the "data-only" lower layers are not visible in the merged overlayfs directories and the metadata and st_ino/st_dev of files in the "data-only" lower layers are not visible in overlayfs inodes.

Only the data of the files in the "data-only" lower layers may be visible when a "metacopy" file in one of the lower layers above it, has a "redirect" to the absolute path of the "lower data" file in the "data-only" lower layer.

Instead of explicitly enabling "metacopy=on" it is sufficient to specify at least one data-only layer to enable redirection of data to a data-only layer. In this case other forms of metacopy are rejected.  Note: this way, data-only layers may be used together with "userxattr", in which case careful attention must be given to privileges needed to change the "user.overlay.redirect" xattr to prevent misuse.

Since kernel version v6.8, "data-only" lower layers can also be added using the "datadir+" mount options and the fsconfig syscall from new mount api. For example:



```text
fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l1", 0);
fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l2", 0);
fsconfig(fs_fd, FSCONFIG_SET_STRING, "lowerdir+", "/l3", 0);
fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do1", 0);
fsconfig(fs_fd, FSCONFIG_SET_STRING, "datadir+", "/do2", 0);
```

<a id="rst-specifying-layers-via-file-descriptors"></a>

### Specifying layers via file descriptors

Since kernel v6.13, overlayfs supports specifying layers via file descriptors in addition to specifying them as paths. This feature is available for the "datadir+", "lowerdir+", "upperdir", and "workdir+" mount options with the fsconfig syscall from the new mount api:



```text
fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower1);
fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower2);
fsconfig(fs_fd, FSCONFIG_SET_FD, "lowerdir+", NULL, fd_lower3);
fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data1);
fsconfig(fs_fd, FSCONFIG_SET_FD, "datadir+", NULL, fd_data2);
fsconfig(fs_fd, FSCONFIG_SET_FD, "workdir", NULL, fd_work);
fsconfig(fs_fd, FSCONFIG_SET_FD, "upperdir", NULL, fd_upper);
```

<a id="rst-fs-verity-support"></a>

### fs-verity support

During metadata copy up of a lower file, if the source file has fs-verity enabled and overlay verity support is enabled, then the digest of the lower file is added to the "trusted.overlay.metacopy" xattr. This is then used to verify the content of the lower file each the time the metacopy file is opened.

When a layer containing verity xattrs is used, it means that any such metacopy file in the upper layer is guaranteed to match the content that was in the lower at the time of the copy-up. If at any time (during a mount, after a remount, etc) such a file in the lower is replaced or modified in any way, access to the corresponding file in overlayfs will result in EIO errors (either on open, due to overlayfs digest check, or from a later read due to fs-verity) and a detailed error is printed to the kernel logs. For more details of how fs-verity file access works, see [Documentation/filesystems/fsverity.rst](</kernel/internals/filesystems/fsverity.md#rst-accessing-verity-files>).

Verity can be used as a general robustness check to detect accidental changes in the overlayfs directories in use. But, with additional care it can also give more powerful guarantees. For example, if the upper layer is fully trusted (by using dm-verity or something similar), then an untrusted lower layer can be used to supply validated file content for all metacopy files.  If additionally the untrusted lower directories are specified as "Data-only", then they can only supply such file content, and the entire mount can be trusted to match the upper layer.

This feature is controlled by the "verity" mount option, which supports these values:

- - **"off":**

    The metacopy digest is never generated or used. This is the default if verity option is not specified.

- - **"on":**

    Whenever a metacopy file specifies an expected digest, the corresponding data file must match the specified digest. When generating a metacopy file the verity digest will be set in it based on the source file (if it has one).

- - **"require":**

    Same as "on", but additionally all metacopy files must specify a digest (or EIO is returned on open). This means metadata copy up will only be used if the data file has fs-verity enabled, otherwise a full copy-up is used.

<a id="rst-sharing-and-copying-layers"></a>

### Sharing and copying layers

Lower layers may be shared among several overlay mounts and that is indeed a very common practice.  An overlay mount may use the same lower layer path as another overlay mount and it may use a lower layer path that is beneath or above the path of another overlay lower layer path.

Using an upper layer path and/or a workdir path that are already used by another overlay mount is not allowed and may fail with EBUSY.  Using partially overlapping paths is not allowed and may fail with EBUSY. If files are accessed from two overlayfs mounts which share or overlap the upper layer and/or workdir path, the behavior of the overlay is undefined, though it will not result in a crash or deadlock.

Mounting an overlay using an upper layer path, where the upper layer path was previously used by another mounted overlay in combination with a different lower layer path, is allowed, unless the "index" or "metacopy" features are enabled.

With the "index" feature, on the first time mount, an NFS file handle of the lower layer root directory, along with the UUID of the lower filesystem, are encoded and stored in the "trusted.overlay.origin" extended attribute on the upper layer root directory.  On subsequent mount attempts, the lower root directory file handle and lower filesystem UUID are compared to the stored origin in upper root directory.  On failure to verify the lower root origin, mount will fail with ESTALE.  An overlayfs mount with "index" enabled will fail with EOPNOTSUPP if the lower filesystem does not support NFS export, lower filesystem does not have a valid UUID or if the upper filesystem does not support extended attributes.

For the "metacopy" feature, there is no verification mechanism at mount time. So if same upper is mounted with different set of lower, mount probably will succeed but expect the unexpected later on. So don't do it.

It is quite a common practice to copy overlay layers to a different directory tree on the same or different underlying filesystem, and even to a different machine.  With the "index" feature, trying to mount the copied layers will fail the verification of the lower root file handle.

<a id="rst-nesting-overlayfs-mounts"></a>

### Nesting overlayfs mounts

It is possible to use a lower directory that is stored on an overlayfs mount. For regular files this does not need any special care. However, files that have overlayfs attributes, such as whiteouts or "overlay.\*" xattrs, will be interpreted by the underlying overlayfs mount and stripped out. In order to allow the second overlayfs mount to see the attributes they must be escaped.

Overlayfs specific xattrs are escaped by using a special prefix of "overlay.overlay.". So, a file with a "trusted.overlay.overlay.metacopy" xattr in the lower dir will be exposed as a regular file with a "trusted.overlay.metacopy" xattr in the overlayfs mount. This can be nested by repeating the prefix multiple time, as each instance only removes one prefix.

A lower dir with a regular whiteout will always be handled by the overlayfs mount, so to support storing an effective whiteout file in an overlayfs mount an alternative form of whiteout is supported. This form is a regular, zero-size file with the "overlay.whiteout" xattr set, inside a directory with the "overlay.opaque" xattr set to "x" (see [whiteouts and opaque directories](<#rst-whiteouts-and-opaque-directories>)). These alternative whiteouts are never created by overlayfs, but can be used by userspace tools (like containers) that generate lower layers. These alternative whiteouts can be escaped using the standard xattr escape mechanism in order to properly nest to any depth.

<a id="rst-non-standard-behavior"></a>

### Non-standard behavior

Current version of overlayfs can act as a mostly POSIX compliant filesystem.

This is the list of cases that overlayfs doesn't currently handle:

> - **a)** POSIX mandates updating st_atime for reads.  This is currently not done in the case when the file resides on a lower layer.
>
> - **b)** If a file residing on a lower layer is opened for read-only and then memory mapped with MAP_SHARED, then subsequent changes to the file are not reflected in the memory mapping.
>
> - **c)** If a file residing on a lower layer is being executed, then opening that file for write or truncating the file will not be denied with ETXTBSY.

The following options allow overlayfs to act more like a standards compliant filesystem:

<a id="rst-redirect-dir"></a>

#### redirect_dir

Enabled with the mount option or module option: "redirect_dir=on" or with the kernel config option CONFIG_OVERLAY_FS_REDIRECT_DIR=y.

If this feature is disabled, then rename(2) on a lower or merged directory will fail with EXDEV ("Invalid cross-device link").

<a id="rst-index"></a>

#### index

Enabled with the mount option or module option "index=on" or with the kernel config option CONFIG_OVERLAY_FS_INDEX=y.

If this feature is disabled and a file with multiple hard links is copied up, then this will "break" the link.  Changes will not be propagated to other names referring to the same inode.

<a id="rst-xino"></a>

#### xino

Enabled with the mount option "xino=auto" or "xino=on", with the module option "xino_auto=on" or with the kernel config option CONFIG_OVERLAY_FS_XINO_AUTO=y.  Also implicitly enabled by using the same underlying filesystem for all layers making up the overlay.

If this feature is disabled or the underlying filesystem doesn't have enough free bits in the inode number, then overlayfs will not be able to guarantee that the values of st_ino and st_dev returned by stat(2) and the value of d_ino returned by readdir(3) will act like on a normal filesystem. E.g. the value of st_dev may be different for two objects in the same overlay filesystem and the value of st_ino for filesystem objects may not be persistent and could change even while the overlay filesystem is mounted, as summarized in the [Inode properties](<#rst-inode-properties>) table above.

<a id="rst-changes-to-underlying-filesystems"></a>

### Changes to underlying filesystems

Changes to the underlying filesystems while part of a mounted overlay filesystem are not allowed.  If the underlying filesystem is changed, the behavior of the overlay is undefined, though it will not result in a crash or deadlock.

Offline changes, when the overlay is not mounted, are allowed to the upper tree.  Offline changes to the lower tree are only allowed if the "metacopy", "index", "xino" and "redirect_dir" features have not been used.  If the lower tree is modified and any of these features has been used, the behavior of the overlay is undefined, though it will not result in a crash or deadlock.

When the overlay NFS export feature is enabled, overlay filesystems behavior on offline changes of the underlying lower layer is different than the behavior when NFS export is disabled.

On every copy_up, an NFS file handle of the lower inode, along with the UUID of the lower filesystem, are encoded and stored in an extended attribute "trusted.overlay.origin" on the upper inode.

When the NFS export feature is enabled, a lookup of a merged directory, that found a lower directory at the lookup path or at the path pointed to by the "trusted.overlay.redirect" extended attribute, will verify that the found lower directory file handle and lower filesystem UUID match the origin file handle that was stored at copy_up time.  If a found lower directory does not match the stored origin, that directory will not be merged with the upper directory.

<a id="rst-nfs-export"></a>

### NFS export

When the underlying filesystems supports NFS export and the "nfs_export" feature is enabled, an overlay filesystem may be exported to NFS.

With the "nfs_export" feature, on copy_up of any lower object, an index entry is created under the index directory.  The index entry name is the hexadecimal representation of the copy up origin file handle.  For a non-directory object, the index entry is a hard link to the upper inode. For a directory object, the index entry has an extended attribute "trusted.overlay.upper" with an encoded file handle of the upper directory inode.

When encoding a file handle from an overlay filesystem object, the following rules apply:

> 1. For a non-upper object, encode a lower file handle from lower inode
>
> 2. For an indexed object, encode a lower file handle from copy_up origin
>
> 3. For a pure-upper object and for an existing non-indexed upper object, encode an upper file handle from upper inode

The encoded overlay file handle includes:

> - Header including path type information (e.g. lower/upper)
>
> - UUID of the underlying filesystem
>
> - Underlying filesystem encoding of underlying inode

This encoding format is identical to the encoding format file handles that are stored in extended attribute "trusted.overlay.origin".

When decoding an overlay file handle, the following steps are followed:

> 1. Find underlying layer by UUID and path type information.
>
> 2. Decode the underlying filesystem file handle to underlying dentry.
>
> 3. For a lower file handle, lookup the handle in index directory by name.
>
> 4. If a whiteout is found in index, return ESTALE. This represents an overlay object that was deleted after its file handle was encoded.
>
> 5. For a non-directory, instantiate a disconnected overlay dentry from the decoded underlying dentry, the path type and index inode, if found.
>
> 6. For a directory, use the connected underlying decoded dentry, path type and index, to lookup a connected overlay dentry.

Decoding a non-directory file handle may return a disconnected dentry. copy_up of that disconnected dentry will create an upper index entry with no upper alias.

When overlay filesystem has multiple lower layers, a middle layer directory may have a "redirect" to lower directory.  Because middle layer "redirects" are not indexed, a lower file handle that was encoded from the "redirect" origin directory, cannot be used to find the middle or upper layer directory.  Similarly, a lower file handle that was encoded from a descendant of the "redirect" origin directory, cannot be used to reconstruct a connected overlay path.  To mitigate the cases of directories that cannot be decoded from a lower file handle, these directories are copied up on encode and encoded as an upper file handle. On an overlay filesystem with no upper layer this mitigation cannot be used NFS export in this setup requires turning off redirect follow (e.g. "redirect_dir=nofollow").

The overlay filesystem does not support non-directory connectable file handles, so exporting with the 'subtree_check' exportfs configuration will cause failures to lookup files over NFS.

When the NFS export feature is enabled, all directory index entries are verified on mount time to check that upper file handles are not stale. This verification may cause significant overhead in some cases.

Note: the mount options index=off,nfs_export=on are conflicting for a read-write mount and will result in an error.

Note: the mount option uuid=off can be used to replace UUID of the underlying filesystem in file handles with null, in order to relax the UUID checks. This can be useful in case the underlying disk is copied and the UUID of this copy is changed. This is only applicable if all lower directories are on the same filesystem, otherwise it will fallback to normal behaviour.

<a id="rst-uuid-and-fsid"></a>

### UUID and fsid

The UUID of overlayfs instance itself and the fsid reported by statfs(2) are controlled by the "uuid" mount option, which supports these values:

- - **"null":**

    UUID of overlayfs is null. fsid is taken from upper most filesystem.

- - **"off":**

    UUID of overlayfs is null. fsid is taken from upper most filesystem. UUID of underlying layers is ignored and null used instead.

- - **"on":**

    UUID of overlayfs is generated and used to report a unique fsid. UUID is stored in xattr "trusted.overlay.uuid", making overlayfs fsid unique and persistent.  This option requires an overlayfs with upper filesystem that supports xattrs.

- - **"auto": (default)**

    UUID is taken from xattr "trusted.overlay.uuid" if it exists. Upgrade to "uuid=on" on first time mount of new overlay filesystem that meets the prerequisites. Downgrade to "uuid=null" for existing overlay filesystems that were never mounted with "uuid=on".

<a id="rst-durability-and-copy-up"></a>

### Durability and copy up

The fsync(2) system call ensures that the data and metadata of a file are safely written to the backing storage, which is expected to guarantee the existence of the information post system crash.

Without an fsync(2) call, there is no guarantee that the observed data after a system crash will be either the old or the new data, but in practice, the observed data after crash is often the old or new data or a mix of both.

When an overlayfs file is modified for the first time, copy up will create a copy of the lower file and its parent directories in the upper layer.  Since the Linux filesystem API does not enforce any particular ordering on storing changes without explicit fsync(2) calls, in case of a system crash, the upper file could end up with no data at all (i.e. zeros), which would be an unusual outcome.  To avoid this experience, overlayfs calls fsync(2) on the upper file before completing data copy up with rename(2) or link(2) to make the copy up "atomic".

By default, overlayfs does not explicitly call fsync(2) on copied up directories or on metadata-only copy up, so it provides no guarantee to persist the user's modification unless the user calls fsync(2). The fsync during copy up only guarantees that if a copy up is observed after a crash, the observed data is not zeroes or intermediate values from the copy up staging area.

On traditional local filesystems with a single journal (e.g. ext4, xfs), fsync on a file also persists the parent directory changes, because they are usually modified in the same transaction, so metadata durability during data copy up effectively comes for free.  Overlayfs further limits risk by disallowing network filesystems as upper layer.

Overlayfs can be tuned to prefer performance or durability when storing to the underlying upper layer.  This is controlled by the "fsync" mount option, which supports these values:

- - **"auto": (default)**

    Call fsync(2) on upper file before completion of data copy up. No explicit fsync(2) on directory or metadata-only copy up.

- - **"strict":**

    Call fsync(2) on upper file and directories before completion of any copy up.

- - **"volatile": \[\*\]**

    Prefer performance over durability (see [Volatile mount](<#rst-volatile-mount>))

\[\*\] The mount option "volatile" is an alias to "fsync=volatile".

<a id="rst-volatile-mount"></a>

### Volatile mount

This is enabled with the "volatile" mount option.  Volatile mounts are not guaranteed to survive a crash.  It is strongly recommended that volatile mounts are only used if data written to the overlay can be recreated without significant effort.

The advantage of mounting with the "volatile" option is that all forms of sync calls to the upper filesystem are omitted.

In order to avoid giving a false sense of safety, the syncfs (and fsync) semantics of volatile mounts are slightly different than that of the rest of VFS.  If any writeback error occurs on the upperdir's filesystem after a volatile mount takes place, all sync functions will return an error.  Once this condition is reached, the filesystem will not recover, and every subsequent sync call will return an error, even if the upperdir has not experienced a new error since the last sync call.

When overlay is mounted with "volatile" option, the directory "$workdir/work/incompat/volatile" is created.  During next mount, overlay checks for this directory and refuses to mount if present. This is a strong indicator that the user should discard upper and work directories and create fresh ones. In very limited cases where the user knows that the system has not crashed and contents of upperdir are intact, the "volatile" directory can be removed.

<a id="rst-user-xattr"></a>

### User xattr

The "-o userxattr" mount option forces overlayfs to use the "user.overlay." xattr namespace instead of "trusted.overlay.".  This selects the xattr namespace; it does not grant unprivileged OverlayFS mounting in Peios.

<a id="rst-testsuite"></a>

### Testsuite

There's a testsuite originally developed by David Howells and currently maintained by Amir Goldstein at:

[https://github.com/amir73il/unionmount-testsuite.git](<https://github.com/amir73il/unionmount-testsuite.git>)

Run in a native context authorized for the mounts and file operations used by the test:



```text
# cd unionmount-testsuite
# ./run --ov --verify
```

## Peios implementation details

<a id="trm-3-9-8"></a>

Overlayfs is a different problem from the StrataFS context of [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>).
Nothing here needs an authorization exemption: the caller has already
been authorized against the merged inode. What has to be corrected is
the **descriptor** the new object ends up wearing.

Both of the inputs the inheritance algorithm needs ([PCDS inheritance](https://learn.peios.org/specifications/pcds/security-descriptor/inheritance)) are
wrong by the time the real create runs:

- **The parent is wrong.** Overlayfs creates on the upper filesystem, in
  the upper directory or — for a copy-up, or a create over a whiteout —
  in the overlay's **workdir**. Neither is the directory the caller
  named. A backing directory is also a distinct inode with its own
  descriptor cache, so a descriptor set at runtime through the overlay
  is not the one a create sees.
- **The subject is wrong.** Overlayfs performs upper-layer work under
  the mounter's credentials. The subject the inheritance algorithm sees
  is therefore the principal that mounted the filesystem, not the one
  making the object.

Left alone, the second is the more damaging: on a live image the root
is an overlay mounted by the system, so every object created anywhere
on it came out owned by SYSTEM, and every inherited `CREATOR OWNER` ACE
resolved to SYSTEM rather than to the principal that created the object.

KACS resolves the descriptor **before** the create, while both inputs
are still right, and hands the answer down. <a id="cite-facs.ovl-copy-up.resolve-before-create"></a>

<a id="trm-3-9-8-1"></a>

## The descriptor rides on a credential <a id="cite-facs.ovl-copy-up.descriptor-on-credential"></a>

The kernel offers two hooks for this, and both work the same way: they
hand the LSM a credential to fill in, and overlayfs then performs the
creation under it.

| Hook | Fires for | KACS resolves |
|---|---|---|
| `security_inode_copy_up` | A lower object being materialised in the upper layer | The source object's own effective descriptor <a id="cite-facs.ovl-copy-up.copy-up-hook-resolves-source"></a> |
| `security_dentry_create_files_as` | An ordinary create, mkdir, mknod, symlink or tmpfile | Inheritance from the overlay parent, for the calling principal <a id="cite-facs.ovl-copy-up.create-hook-resolves-inheritance"></a> |

Either way the result is attached to that credential, and the inode
creation path prefers it over computing inheritance itself. <a id="cite-facs.ovl-copy-up.creation-prefers-attached"></a>

The credential is what makes the lifetime sound, and it is the reason
this needs no context of its own:

- Overlayfs installs the credential with `override_creds()` and reverts
  it through a scope guard, on every exit path including errors. <a id="cite-facs.ovl-copy-up.credential-reverted-on-every-path"></a>
- Each scope wraps exactly one creation and nothing else. <a id="cite-facs.ovl-copy-up.one-creation-per-scope"></a> A create over
  a whiteout makes one temporary object and then *renames* it over the
  whiteout, rather than creating a second.
- Releasing the credential releases the descriptor. <a id="cite-facs.ovl-copy-up.release-frees-descriptor"></a>

So there is nothing to arm and nothing to disarm. Outside that scope the
credential is simply not current.

A credential *derived* from one carrying a pending descriptor does not
inherit it. <a id="cite-facs.ovl-copy-up.derived-credential-does-not-inherit"></a> Without that rule the descriptor would escape its create and
be stamped on the next unrelated object the task made.

<a id="trm-3-9-8-2"></a>

## A copied-up object keeps its own descriptor <a id="cite-facs.ovl-copy-up.copy-up-preserves-descriptor"></a>

A copy-up is not a new object, and inheritance is the wrong answer for
it even from the right parent: the object already had a descriptor.
KACS carries the source's across, whether that descriptor was stored on
the lower inode or synthesized for it under a mount policy ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). <a id="cite-facs.ovl-copy-up.source-descriptor-may-be-synthesised"></a>

Without this the defect runs in both directions. An object with a
deliberately narrow descriptor is widened by the act of writing to it,
and a deliberately permissive one is narrowed — in both cases changing
what *other* principals may do to it as a side effect of somebody
else's write. The principal doing the writing already held write access;
nothing about that should re-decide the object's policy for everyone
else.

<a id="trm-3-9-8-3"></a>

## An ordinary create inherits from the overlay <a id="cite-facs.ovl-copy-up.create-inherits-from-overlay"></a>

A genuinely new object has nothing to preserve, so it inherits — but
from the merged directory the caller named and as the caller, which is
what it would have got had overlayfs not been in the way. The parent's
descriptor is read through the overlay inode, so a descriptor set at
runtime governs the children created after it, and `CREATOR OWNER`
resolves to the principal making the object. <a id="cite-facs.ovl-copy-up.creator-owner-resolves-to-caller"></a>

A creator descriptor supplied explicitly to a native create ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2>)) is
picked up here for the same reason. <a id="cite-facs.ovl-copy-up.supplied-descriptor-honoured"></a> The request records the parent the
caller resolved — an overlay inode — so a match attempted at inode
creation time, where only the backing inode is visible, could never
fire, and the descriptor the caller asked for would be silently replaced
by inheritance.

A caller with no token is left alone rather than denied here, so the
inode creation path reaches its own denial. <a id="cite-facs.ovl-copy-up.no-token-passes-through"></a> Two places must not decide
the same thing differently.

<a id="trm-3-9-8-4"></a>

## The descriptor xattr is not copied <a id="cite-facs.ovl-copy-up.canonical-xattr-discarded"></a>

On copy-up the canonical descriptor xattr is discarded during the xattr
copy rather than replicated, because the credential above already
carries it; copying it as well would overwrite the descriptor with the
same answer. It could not be copied through that path in any case — the
canonical xattr is not readable or writable as an ordinary xattr, since
descriptor mutation is the dedicated interface's job ([The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md#trm-3-9-6>)).

<a id="trm-3-9-8-5"></a>

## Failure <a id="cite-facs.ovl-copy-up.resolve-failure-fails-create"></a>

Failing to resolve a descriptor fails the create. That holds for both
hooks: a source whose descriptor cannot be read fails the copy-up, and a
parent whose descriptor cannot be resolved — or which does not grant the
caller the right to add the object — fails the create.

The alternative in each case is to fall back to inheritance from a
backing directory as the mounter, which is the outcome this exists to
prevent, and which leaves nothing behind to find later.

An object on an unmanaged mount is the one case that passes through
untouched: there is nothing there to preserve or to inherit. <a id="cite-facs.ovl-copy-up.unmanaged-untouched"></a>

---

# Pathname lookup

_Peios Kernel / Internals / Filesystems_

> This write-up is based on three articles published at lwn.net:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-pathname-lookup"></a>

This write-up is based on three articles published at lwn.net:

- &lt;[https://lwn.net/Articles/649115/](<https://lwn.net/Articles/649115/>)&gt; Pathname lookup in Linux

- &lt;[https://lwn.net/Articles/649729/](<https://lwn.net/Articles/649729/>)&gt; RCU-walk: faster pathname lookup in Linux

- &lt;[https://lwn.net/Articles/650786/](<https://lwn.net/Articles/650786/>)&gt; A walk among the symlinks

Written by Neil Brown with help from Al Viro and Jon Corbet. It has subsequently been updated to reflect changes in the kernel including:

- per-directory parallel name lookup.

- `openat2()` resolution restriction flags.

<a id="rst-introduction-to-pathname-lookup"></a>

## Introduction to pathname lookup

The most obvious aspect of pathname lookup, which very little exploration is needed to discover, is that it is complex.  There are many rules, special cases, and implementation alternatives that all combine to confuse the unwary reader.  Computer science has long been acquainted with such complexity and has tools to help manage it.  One tool that we will make extensive use of is "divide and conquer".  For the early parts of the analysis we will divide off symlinks - leaving them until the final part.  Well before we get to symlinks we have another major division based on the VFS's approach to locking which will allow us to review "REF-walk" and "RCU-walk" separately.  But we are getting ahead of ourselves.  There are some important low level distinctions we need to clarify first.

<a id="rst-there-are-two-sorts-of"></a>

### There are two sorts of ...

<a id="rst-openat"></a>



Pathnames (sometimes "file names"), used to identify objects in the filesystem, will be familiar to most readers.  They contain two sorts of elements: "slashes" that are sequences of one or more "`/`" characters, and "components" that are sequences of one or more non-"`/`" characters.  These form two kinds of paths.  Those that start with slashes are "absolute" and start from the filesystem root. The others are "relative" and start from the current directory, or from some other location specified by a file descriptor given to "`*at()`" system calls such as [openat()](<http://man7.org/linux/man-pages/man2/openat.2.html>)<a id="rst-openat-1"></a>.

<a id="rst-execveat"></a>



It is tempting to describe the second kind as starting with a component, but that isn't always accurate: a pathname can lack both slashes and components, it can be empty, in other words.  This is generally forbidden in POSIX, but some of those "`*at()`" system calls in Linux permit it when the `AT_EMPTY_PATH` flag is given.  For example, if you have an open file descriptor on an executable file you can execute it by calling [execveat()](<http://man7.org/linux/man-pages/man2/execveat.2.html>)<a id="rst-execveat-1"></a> passing the file descriptor, an empty path, and the `AT_EMPTY_PATH` flag.

These paths can be divided into two sections: the final component and everything else.  The "everything else" is the easy bit.  In all cases it must identify a directory that already exists, otherwise an error such as `ENOENT` or `ENOTDIR` will be reported.

The final component is not so simple.  Not only do different system calls interpret it quite differently (e.g. some create it, some do not), but it might not even exist: neither the empty pathname nor the pathname that is just slashes have a final component.  If it does exist, it could be "`.`" or "`..`" which are handled quite differently from other components.

<a id="rst-posix"></a>



If a pathname ends with a slash, such as "`/tmp/foo/`" it might be tempting to consider that to have an empty final component.  In many ways that would lead to correct results, but not always.  In particular, `mkdir()` and `rmdir()` each create or remove a directory named by the final component, and they are required to work with pathnames ending in "`/`".  According to [POSIX](<https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12>):

> A pathname that contains at least one non-&lt;slash&gt; character and that ends with one or more trailing &lt;slash&gt; characters shall not be resolved successfully unless the last pathname component before the trailing &lt;slash&gt; characters names an existing directory or a directory entry that is to be created for a directory immediately after the pathname is resolved.

The Linux pathname walking code (mostly in `fs/namei.c`) deals with all of these issues: breaking the path into components, handling the "everything else" quite separately from the final component, and checking that the trailing slash is not used where it isn't permitted.  It also addresses the important issue of concurrent access.

While one process is looking up a pathname, another might be making changes that affect that lookup.  One fairly extreme case is that if "a/b" were renamed to "a/c/b" while another process were looking up "a/b/..", that process might successfully resolve on "a/c". Most races are much more subtle, and a big part of the task of pathname lookup is to prevent them from having damaging effects.  Many of the possible races are seen most clearly in the context of the "dcache" and an understanding of that is central to understanding pathname lookup.

<a id="rst-more-than-just-a-cache"></a>

### More than just a cache

The "dcache" caches information about names in each filesystem to make them quickly available for lookup.  Each entry (known as a "dentry") contains three significant fields: a component name, a pointer to a parent dentry, and a pointer to the "inode" which contains further information about the object in that parent with the given name.  The inode pointer can be `NULL` indicating that the name doesn't exist in the parent.  While there can be linkage in the dentry of a directory to the dentries of the children, that linkage is not used for pathname lookup, and so will not be considered here.

The dcache has a number of uses apart from accelerating lookup.  One that will be particularly relevant is that it is closely integrated with the mount table that records which filesystem is mounted where. What the mount table actually stores is which dentry is mounted on top of which other dentry.

When considering the dcache, we have another of our "two types" distinctions: there are two types of filesystems.

Some filesystems ensure that the information in the dcache is always completely accurate (though not necessarily complete).  This can allow the VFS to determine if a particular file does or doesn't exist without checking with the filesystem, and means that the VFS can protect the filesystem against certain races and other problems. These are typically "local" filesystems such as ext3, XFS, and Btrfs.

Other filesystems don't provide that guarantee because they cannot. These are typically filesystems that are shared across a network, whether remote filesystems like NFS and 9P, or cluster filesystems like ocfs2 or cephfs.  These filesystems allow the VFS to revalidate cached information, and must provide their own protection against awkward races.  The VFS can detect these filesystems by the `DCACHE_OP_REVALIDATE` flag being set in the dentry.

<a id="rst-ref-walk-simple-concurrency-management-with-refcounts-and-spinlocks"></a>

### REF-walk: simple concurrency management with refcounts and spinlocks

With all of those divisions carefully classified, we can now start looking at the actual process of walking along a path.  In particular we will start with the handling of the "everything else" part of a pathname, and focus on the "REF-walk" approach to concurrency management.  This code is found in the `link_path_walk()` function, if you ignore all the places that only run when "`LOOKUP_RCU`" (indicating the use of RCU-walk) is set.

<a id="rst-meet-the-lockers"></a>



REF-walk is fairly heavy-handed with locks and reference counts.  Not as heavy-handed as in the old "big kernel lock" days, but certainly not afraid of taking a lock when one is needed.  It uses a variety of different concurrency controls.  A background understanding of the various primitives is assumed, or can be gleaned from elsewhere such as in [Meet the Lockers](<https://lwn.net/Articles/453685/>).

The locking mechanisms used by REF-walk include:

<a id="rst-dentry-d-lockref"></a>

#### dentry-&gt;d_lockref

This uses the lockref primitive to provide both a spinlock and a reference count.  The special-sauce of this primitive is that the conceptual sequence "lock; inc_ref; unlock;" can often be performed with a single atomic memory operation.

Holding a reference on a dentry ensures that the dentry won't suddenly be freed and used for something else, so the values in various fields will behave as expected.  It also protects the `->d_inode` reference to the inode to some extent.

The association between a dentry and its inode is fairly permanent. For example, when a file is renamed, the dentry and inode move together to the new location.  When a file is created the dentry will initially be negative (i.e. `d_inode` is `NULL`), and will be assigned to the new inode as part of the act of creation.

When a file is deleted, this can be reflected in the cache either by setting `d_inode` to `NULL`, or by removing it from the hash table (described shortly) used to look up the name in the parent directory. If the dentry is still in use the second option is used as it is perfectly legal to keep using an open file after it has been deleted and having the dentry around helps.  If the dentry is not otherwise in use (i.e. if the refcount in `d_lockref` is one), only then will `d_inode` be set to `NULL`.  Doing it this way is more efficient for a very common case.

So as long as a counted reference is held to a dentry, a non-`NULL` `->d_inode` value will never be changed.

<a id="rst-dentry-d-lock"></a>

#### dentry-&gt;d_lock

`d_lock` is a synonym for the spinlock that is part of `d_lockref` above. For our purposes, holding this lock protects against the dentry being renamed or unlinked.  In particular, its parent (`d_parent`), and its name (`d_name`) cannot be changed, and it cannot be removed from the dentry hash table.

When looking for a name in a directory, REF-walk takes `d_lock` on each candidate dentry that it finds in the hash table and then checks that the parent and name are correct.  So it doesn't lock the parent while searching in the cache; it only locks children.

When looking for the parent for a given name (to handle "`..`"), REF-walk can take `d_lock` to get a stable reference to `d_parent`, but it first tries a more lightweight approach.  As seen in `dget_parent()`, if a reference can be claimed on the parent, and if subsequently `d_parent` can be seen to have not changed, then there is no need to actually take the lock on the child.

<a id="rst-rename-lock"></a>

#### rename_lock

Looking up a given name in a given directory involves computing a hash from the two values (the name and the dentry of the directory), accessing that slot in a hash table, and searching the linked list that is found there.

When a dentry is renamed, the name and the parent dentry can both change so the hash will almost certainly change too.  This would move the dentry to a different chain in the hash table.  If a filename search happened to be looking at a dentry that was moved in this way, it might end up continuing the search down the wrong chain, and so miss out on part of the correct chain.

The name-lookup process (`d_lookup()`) does *not* try to prevent this from happening, but only to detect when it happens. `rename_lock` is a seqlock that is updated whenever any dentry is renamed.  If `d_lookup` finds that a rename happened while it unsuccessfully scanned a chain in the hash table, it simply tries again.

`rename_lock` is also used to detect and defend against potential attacks against `LOOKUP_BENEATH` and `LOOKUP_IN_ROOT` when resolving ".." (where the parent directory is moved outside the root, bypassing the `path_equal()` check). If `rename_lock` is updated during the lookup and the path encounters a "..", a potential attack occurred and `handle_dots()` will bail out with `-EAGAIN`.

<a id="rst-inode-i-rwsem"></a>

#### inode-&gt;i_rwsem

`i_rwsem` is a read/write semaphore that serializes all changes to a particular directory.  This ensures that, for example, an `unlink()` and a `rename()` cannot both happen at the same time.  It also keeps the directory stable while the filesystem is asked to look up a name that is not currently in the dcache or, optionally, when the list of entries in a directory is being retrieved with `readdir()`.

This has a complementary role to that of `d_lock`: `i_rwsem` on a directory protects all of the names in that directory, while `d_lock` on a name protects just one name in a directory.  Most changes to the dcache hold `i_rwsem` on the relevant directory inode and briefly take `d_lock` on one or more the dentries while the change happens.  One exception is when idle dentries are removed from the dcache due to memory pressure.  This uses `d_lock`, but `i_rwsem` plays no role.

The semaphore affects pathname lookup in two distinct ways.  Firstly it prevents changes during lookup of a name in a directory.  `walk_component()` uses `lookup_fast()` first which, in turn, checks to see if the name is in the cache, using only `d_lock` locking.  If the name isn't found, then `walk_component()` falls back to `lookup_slow()` which takes a shared lock on `i_rwsem`, checks again that the name isn't in the cache, and then calls in to the filesystem to get a definitive answer.  A new dentry will be added to the cache regardless of the result.

Secondly, when pathname lookup reaches the final component, it will sometimes need to take an exclusive lock on `i_rwsem` before performing the last lookup so that the required exclusion can be achieved.  How path lookup chooses to take, or not take, `i_rwsem` is one of the issues addressed in a subsequent section.

If two threads attempt to look up the same name at the same time - a name that is not yet in the dcache - the shared lock on `i_rwsem` will not prevent them both adding new dentries with the same name.  As this would result in confusion an extra level of interlocking is used, based around a secondary hash table (`in_lookup_hashtable`) and a per-dentry flag bit (`DCACHE_PAR_LOOKUP`).

To add a new dentry to the cache while only holding a shared lock on `i_rwsem`, a thread must call `d_alloc_parallel()`.  This allocates a dentry, stores the required name and parent in it, checks if there is already a matching dentry in the primary or secondary hash tables, and if not, stores the newly allocated dentry in the secondary hash table, with `DCACHE_PAR_LOOKUP` set.

If a matching dentry was found in the primary hash table then that is returned and the caller can know that it lost a race with some other thread adding the entry.  If no matching dentry is found in either cache, the newly allocated dentry is returned and the caller can detect this from the presence of `DCACHE_PAR_LOOKUP`.  In this case it knows that it has won any race and now is responsible for asking the filesystem to perform the lookup and find the matching inode.  When the lookup is complete, it must call `d_lookup_done()` which clears the flag and does some other house keeping, including removing the dentry from the secondary hash table - it will normally have been added to the primary hash table already.  Note that a `struct waitqueue_head` is passed to `d_alloc_parallel()`, and `d_lookup_done()` must be called while this `waitqueue_head` is still in scope.

If a matching dentry is found in the secondary hash table, `d_alloc_parallel()` has a little more work to do. It first waits for `DCACHE_PAR_LOOKUP` to be cleared, using a wait_queue that was passed to the instance of `d_alloc_parallel()` that won the race and that will be woken by the call to `d_lookup_done()`.  It then checks to see if the dentry has now been added to the primary hash table.  If it has, the dentry is returned and the caller just sees that it lost any race.  If it hasn't been added to the primary hash table, the most likely explanation is that some other dentry was added instead using `d_splice_alias()`.  In any case, `d_alloc_parallel()` repeats all the look ups from the start and will normally return something from the primary hash table.

<a id="rst-mnt-mnt-count"></a>

#### mnt-&gt;mnt_count

`mnt_count` is a per-CPU reference counter on "`mount`" structures. Per-CPU here means that incrementing the count is cheap as it only uses CPU-local memory, but checking if the count is zero is expensive as it needs to check with every CPU.  Taking a `mnt_count` reference prevents the mount structure from disappearing as the result of regular unmount operations, but does not prevent a "lazy" unmount.  So holding `mnt_count` doesn't ensure that the mount remains in the namespace and, in particular, doesn't stabilize the link to the mounted-on dentry.  It does, however, ensure that the `mount` data structure remains coherent, and it provides a reference to the root dentry of the mounted filesystem.  So a reference through `->mnt_count` provides a stable reference to the mounted dentry, but not the mounted-on dentry.

<a id="rst-mount-lock"></a>

#### mount_lock

`mount_lock` is a global seqlock, a bit like `rename_lock`.  It can be used to check if any change has been made to any mount points.

While walking down the tree (away from the root) this lock is used when crossing a mount point to check that the crossing was safe.  That is, the value in the seqlock is read, then the code finds the mount that is mounted on the current directory, if there is one, and increments the `mnt_count`.  Finally the value in `mount_lock` is checked against the old value.  If there is no change, then the crossing was safe.  If there was a change, the `mnt_count` is decremented and the whole process is retried.

When walking up the tree (towards the root) by following a ".." link, a little more care is needed.  In this case the seqlock (which contains both a counter and a spinlock) is fully locked to prevent any changes to any mount points while stepping up.  This locking is needed to stabilize the link to the mounted-on dentry, which the refcount on the mount itself doesn't ensure.

`mount_lock` is also used to detect and defend against potential attacks against `LOOKUP_BENEATH` and `LOOKUP_IN_ROOT` when resolving ".." (where the parent directory is moved outside the root, bypassing the `path_equal()` check). If `mount_lock` is updated during the lookup and the path encounters a "..", a potential attack occurred and `handle_dots()` will bail out with `-EAGAIN`.

<a id="rst-rcu"></a>

#### RCU

Finally the global (but extremely lightweight) RCU read lock is held from time to time to ensure certain data structures don't get freed unexpectedly.

In particular it is held while scanning chains in the dcache hash table, and the mount point hash table.

<a id="rst-bringing-it-together-with-struct-nameidata"></a>

### Bringing it together with `struct nameidata`

<a id="rst-first-edition-unix"></a>



Throughout the process of walking a path, the current status is stored in a `struct nameidata`, "namei" being the traditional name - dating all the way back to [First Edition Unix](<https://minnie.tuhs.org/cgi-bin/utree.pl?file=V1/u2.s>) - of the function that converts a "name" to an "inode".  `struct nameidata` contains (among other fields):

<a id="rst-struct-path-path"></a>

#### `struct path path`

A `path` contains a `struct vfsmount` (which is embedded in a `struct mount`) and a `struct dentry`.  Together these record the current status of the walk.  They start out referring to the starting point (the current working directory, the root directory, or some other directory identified by a file descriptor), and are updated on each step.  A reference through `d_lockref` and `mnt_count` is always held.

<a id="rst-struct-qstr-last"></a>

#### `struct qstr last`

This is a string together with a length (i.e. *not* `nul` terminated) that is the "next" component in the pathname.

<a id="rst-int-last-type"></a>

#### `int last_type`

This is one of `LAST_NORM`, `LAST_ROOT`, `LAST_DOT` or `LAST_DOTDOT`. The `last` field is only valid if the type is `LAST_NORM`.

<a id="rst-struct-path-root"></a>

#### `struct path root`

This is used to hold a reference to the effective root of the filesystem.  Often that reference won't be needed, so this field is only assigned the first time it is used, or when a non-standard root is requested.  Keeping a reference in the `nameidata` ensures that only one root is in effect for the entire path walk, even if it races with a `chroot()` system call.

It should be noted that in the case of `LOOKUP_IN_ROOT` or `LOOKUP_BENEATH`, the effective root becomes the directory file descriptor passed to `openat2()` (which exposes these `LOOKUP_` flags).

The root is needed when either of two conditions holds: (1) either the pathname or a symbolic link starts with a "'/'", or (2) a "`..`" component is being handled, since "`..`" from the root must always stay at the root.  The value used is usually the current root directory of the calling process.  An alternate root can be provided as when `sysctl()` calls `file_open_root()`, and when NFSv4 or Btrfs call `mount_subtree()`.  In each case a pathname is being looked up in a very specific part of the filesystem, and the lookup must not be allowed to escape that subtree.  It works a bit like a local `chroot()`.

Ignoring the handling of symbolic links, we can now describe the "`link_path_walk()`" function, which handles the lookup of everything except the final component as:

> Given a path (`name`) and a nameidata structure (`nd`), check that the current directory has execute permission and then advance `name` over one component while updating `last_type` and `last`.  If that was the final component, then return, otherwise call `walk_component()` and repeat from the top.

`walk_component()` is even easier.  If the component is `LAST_DOTS`, it calls `handle_dots()` which does the necessary locking as already described.  If it finds a `LAST_NORM` component it first calls "`lookup_fast()`" which only looks in the dcache, but will ask the filesystem to revalidate the result if it is that sort of filesystem. If that doesn't get a good result, it calls "`lookup_slow()`" which takes `i_rwsem`, rechecks the cache, and then asks the filesystem to find a definitive answer.

As the last step of walk_component(), step_into() will be called either directly from walk_component() or from handle_dots().  It calls handle_mounts(), to check and handle mount points, in which a new `struct path` is created containing a counted reference to the new dentry and a reference to the new `vfsmount` which is only counted if it is different from the previous `vfsmount`. Then if there is a symbolic link, step_into() calls pick_link() to deal with it, otherwise it installs the new `struct path` in the `struct nameidata`, and drops the unneeded references.

This "hand-over-hand" sequencing of getting a reference to the new dentry before dropping the reference to the previous dentry may seem obvious, but is worth pointing out so that we will recognize its analogue in the "RCU-walk" version.

<a id="rst-handling-the-final-component"></a>

### Handling the final component

`link_path_walk()` only walks as far as setting `nd->last` and `nd->last_type` to refer to the final component of the path.  It does not call `walk_component()` that last time.  Handling that final component remains for the caller to sort out. Those callers are path_lookupat(), path_parentat() and path_openat() each of which handles the differing requirements of different system calls.

`path_parentat()` is clearly the simplest - it just wraps a little bit of housekeeping around `link_path_walk()` and returns the parent directory and final component to the caller.  The caller will be either aiming to create a name (via `filename_create()`) or remove or rename a name (in which case `user_path_parent()` is used).  They will use `i_rwsem` to exclude other changes while they validate and then perform their operation.

`path_lookupat()` is nearly as simple - it is used when an existing object is wanted such as by `stat()` or `chmod()`.  It essentially just calls `walk_component()` on the final component through a call to `lookup_last()`.  `path_lookupat()` returns just the final dentry. It is worth noting that when flag `LOOKUP_MOUNTPOINT` is set, path_lookupat() will unset LOOKUP_JUMPED in nameidata so that in the subsequent path traversal d_weak_revalidate() won't be called. This is important when unmounting a filesystem that is inaccessible, such as one provided by a dead NFS server.

Finally `path_openat()` is used for the `open()` system call; it contains, in support functions starting with "open_last_lookups()", all the complexity needed to handle the different subtleties of O_CREAT (with or without O_EXCL), final "`/`" characters, and trailing symbolic links.  We will revisit this in the final part of this series, which focuses on those symbolic links.  "open_last_lookups()" will sometimes, but not always, take `i_rwsem`, depending on what it finds.

Each of these, or the functions which call them, need to be alert to the possibility that the final component is not `LAST_NORM`.  If the goal of the lookup is to create something, then any value for `last_type` other than `LAST_NORM` will result in an error.  For example if `path_parentat()` reports `LAST_DOTDOT`, then the caller won't try to create that name.  They also check for trailing slashes by testing `last.name[last.len]`.  If there is any character beyond the final component, it must be a trailing slash.

<a id="rst-revalidation-and-automounts"></a>

### Revalidation and automounts

Apart from symbolic links, there are only two parts of the "REF-walk" process not yet covered.  One is the handling of stale cache entries and the other is automounts.

On filesystems that require it, the lookup routines will call the `->d_revalidate()` dentry method to ensure that the cached information is current.  This will often confirm validity or update a few details from a server.  In some cases it may find that there has been change further up the path and that something that was thought to be valid previously isn't really.  When this happens the lookup of the whole path is aborted and retried with the "`LOOKUP_REVAL`" flag set.  This forces revalidation to be more thorough.  We will see more details of this retry process in the next article.

Automount points are locations in the filesystem where an attempt to lookup a name can trigger changes to how that lookup should be handled, in particular by mounting a filesystem there.  These are covered in greater detail in [autofs.rst](/kernel/internals/filesystems/autofs.md) in the Linux documentation tree, but a few notes specifically related to path lookup are in order here.

The Linux VFS has a concept of "managed" dentries.  There are three potentially interesting things about these dentries corresponding to three different flags that might be set in `dentry->d_flags`:

<a id="rst-dcache-manage-transit"></a>

#### `DCACHE_MANAGE_TRANSIT`

If this flag has been set, then the filesystem has requested that the `d_manage()` dentry operation be called before handling any possible mount point.  This can perform two particular services:

It can block to avoid races.  If an automount point is being unmounted, the `d_manage()` function will usually wait for that process to complete before letting the new lookup proceed and possibly trigger a new automount.

It can selectively allow only some processes to transit through a mount point.  When a server process is managing automounts, it may need to access a directory without triggering normal automount processing.  That server process can identify itself to the `autofs` filesystem, which will then give it a special pass through `d_manage()` by returning `-EISDIR`.

<a id="rst-dcache-mounted"></a>

#### `DCACHE_MOUNTED`

This flag is set on every dentry that is mounted on.  As Linux supports multiple filesystem namespaces, it is possible that the dentry may not be mounted on in *this* namespace, just in some other.  So this flag is seen as a hint, not a promise.

If this flag is set, and `d_manage()` didn't return `-EISDIR`, `lookup_mnt()` is called to examine the mount hash table (honoring the `mount_lock` described earlier) and possibly return a new `vfsmount` and a new `dentry` (both with counted references).

<a id="rst-dcache-need-automount"></a>

#### `DCACHE_NEED_AUTOMOUNT`

If `d_manage()` allowed us to get this far, and `lookup_mnt()` didn't find a mount point, then this flag causes the `d_automount()` dentry operation to be called.

The `d_automount()` operation can be arbitrarily complex and may communicate with server processes etc. but it should ultimately either report that there was an error, that there was nothing to mount, or should provide an updated `struct path` with new `dentry` and `vfsmount`.

In the latter case, `finish_automount()` will be called to safely install the new mount point into the mount table.

There is no new locking of import here and it is important that no locks (only counted references) are held over this processing due to the very real possibility of extended delays. This will become more important next time when we examine RCU-walk which is particularly sensitive to delays.

<a id="rst-rcu-walk-faster-pathname-lookup-in-linux"></a>

## RCU-walk - faster pathname lookup in Linux

RCU-walk is another algorithm for performing pathname lookup in Linux. It is in many ways similar to REF-walk and the two share quite a bit of code.  The significant difference in RCU-walk is how it allows for the possibility of concurrent access.

We noted that REF-walk is complex because there are numerous details and special cases.  RCU-walk reduces this complexity by simply refusing to handle a number of cases -- it instead falls back to REF-walk.  The difficulty with RCU-walk comes from a different direction: unfamiliarity.  The locking rules when depending on RCU are quite different from traditional locking, so we will spend a little extra time when we come to those.

<a id="rst-clear-demarcation-of-roles"></a>

### Clear demarcation of roles

The easiest way to manage concurrency is to forcibly stop any other thread from changing the data structures that a given thread is looking at.  In cases where no other thread would even think of changing the data and lots of different threads want to read at the same time, this can be very costly.  Even when using locks that permit multiple concurrent readers, the simple act of updating the count of the number of current readers can impose an unwanted cost.  So the goal when reading a shared data structure that no other process is changing is to avoid writing anything to memory at all.  Take no locks, increment no counts, leave no footprints.

The REF-walk mechanism already described certainly doesn't follow this principle, but then it is really designed to work when there may well be other threads modifying the data.  RCU-walk, in contrast, is designed for the common situation where there are lots of frequent readers and only occasional writers.  This may not be common in all parts of the filesystem tree, but in many parts it will be.  For the other parts it is important that RCU-walk can quickly fall back to using REF-walk.

Pathname lookup always starts in RCU-walk mode but only remains there as long as what it is looking for is in the cache and is stable.  It dances lightly down the cached filesystem image, leaving no footprints and carefully watching where it is, to be sure it doesn't trip.  If it notices that something has changed or is changing, or if something isn't in the cache, then it tries to stop gracefully and switch to REF-walk.

This stopping requires getting a counted reference on the current `vfsmount` and `dentry`, and ensuring that these are still valid - that a path walk with REF-walk would have found the same entries. This is an invariant that RCU-walk must guarantee.  It can only make decisions, such as selecting the next step, that are decisions which REF-walk could also have made if it were walking down the tree at the same time.  If the graceful stop succeeds, the rest of the path is processed with the reliable, if slightly sluggish, REF-walk.  If RCU-walk finds it cannot stop gracefully, it simply gives up and restarts from the top with REF-walk.

This pattern of "try RCU-walk, if that fails try REF-walk" can be clearly seen in functions like filename_lookup(), filename_parentat(), do_filp_open(), and do_file_open_root().  These four correspond roughly to the three `path_*()` functions we met earlier, each of which calls `link_path_walk()`.  The `path_*()` functions are called using different mode flags until a mode is found which works. They are first called with `LOOKUP_RCU` set to request "RCU-walk".  If that fails with the error `ECHILD` they are called again with no special flag to request "REF-walk".  If either of those report the error `ESTALE` a final attempt is made with `LOOKUP_REVAL` set (and no `LOOKUP_RCU`) to ensure that entries found in the cache are forcibly revalidated - normally entries are only revalidated if the filesystem determines that they are too old to trust.

The `LOOKUP_RCU` attempt may drop that flag internally and switch to REF-walk, but will never then try to switch back to RCU-walk.  Places that trip up RCU-walk are much more likely to be near the leaves and so it is very unlikely that there will be much, if any, benefit from switching back.

<a id="rst-rcu-and-seqlocks-fast-and-light"></a>

### RCU and seqlocks: fast and light

RCU is, unsurprisingly, critical to RCU-walk mode.  The `rcu_read_lock()` is held for the entire time that RCU-walk is walking down a path.  The particular guarantee it provides is that the key data structures - dentries, inodes, super_blocks, and mounts - will not be freed while the lock is held.  They might be unlinked or invalidated in one way or another, but the memory will not be repurposed so values in various fields will still be meaningful.  This is the only guarantee that RCU provides; everything else is done using seqlocks.

As we saw above, REF-walk holds a counted reference to the current dentry and the current vfsmount, and does not release those references before taking references to the "next" dentry or vfsmount.  It also sometimes takes the `d_lock` spinlock.  These references and locks are taken to prevent certain changes from happening.  RCU-walk must not take those references or locks and so cannot prevent such changes. Instead, it checks to see if a change has been made, and aborts or retries if it has.

To preserve the invariant mentioned above (that RCU-walk may only make decisions that REF-walk could have made), it must make the checks at or near the same places that REF-walk holds the references.  So, when REF-walk increments a reference count or takes a spinlock, RCU-walk samples the status of a seqlock using `read_seqcount_begin()` or a similar function.  When REF-walk decrements the count or drops the lock, RCU-walk checks if the sampled status is still valid using `read_seqcount_retry()` or similar.

However, there is a little bit more to seqlocks than that.  If RCU-walk accesses two different fields in a seqlock-protected structure, or accesses the same field twice, there is no a priori guarantee of any consistency between those accesses.  When consistency is needed - which it usually is - RCU-walk must take a copy and then use `read_seqcount_retry()` to validate that copy.

`read_seqcount_retry()` not only checks the sequence number, but also imposes a memory barrier so that no memory-read instruction from *before* the call can be delayed until *after* the call, either by the CPU or by the compiler.  A simple example of this can be seen in `slow_dentry_cmp()` which, for filesystems which do not use simple byte-wise name equality, calls into the filesystem to compare a name against a dentry.  The length and name pointer are copied into local variables, then `read_seqcount_retry()` is called to confirm the two are consistent, and only then is `->d_compare()` called.  When standard filename comparison is used, `dentry_cmp()` is called instead.  Notably it does *not* use `read_seqcount_retry()`, but instead has a large comment explaining why the consistency guarantee isn't necessary.  A subsequent `read_seqcount_retry()` will be sufficient to catch any problem that could occur at this point.

With that little refresher on seqlocks out of the way we can look at the bigger picture of how RCU-walk uses seqlocks.

<a id="rst-mount-lock-and-nd-m-seq"></a>

#### `mount_lock` and `nd->m_seq`

We already met the `mount_lock` seqlock when REF-walk used it to ensure that crossing a mount point is performed safely.  RCU-walk uses it for that too, but for quite a bit more.

Instead of taking a counted reference to each `vfsmount` as it descends the tree, RCU-walk samples the state of `mount_lock` at the start of the walk and stores this initial sequence number in the `struct nameidata` in the `m_seq` field.  This one lock and one sequence number are used to validate all accesses to all `vfsmounts`, and all mount point crossings.  As changes to the mount table are relatively rare, it is reasonable to fall back on REF-walk any time that any "mount" or "unmount" happens.

`m_seq` is checked (using `read_seqretry()`) at the end of an RCU-walk sequence, whether switching to REF-walk for the rest of the path or when the end of the path is reached.  It is also checked when stepping down over a mount point (in `__follow_mount_rcu()`) or up (in `follow_dotdot_rcu()`).  If it is ever found to have changed, the whole RCU-walk sequence is aborted and the path is processed again by REF-walk.

If RCU-walk finds that `mount_lock` hasn't changed then it can be sure that, had REF-walk taken counted references on each vfsmount, the results would have been the same.  This ensures the invariant holds, at least for vfsmount structures.

<a id="rst-dentry-d-seq-and-nd-seq"></a>

#### `dentry->d_seq` and `nd->seq`

In place of taking a count or lock on `d_reflock`, RCU-walk samples the per-dentry `d_seq` seqlock, and stores the sequence number in the `seq` field of the nameidata structure, so `nd->seq` should always be the current sequence number of `nd->dentry`.  This number needs to be revalidated after copying, and before using, the name, parent, or inode of the dentry.

The handling of the name we have already looked at, and the parent is only accessed in `follow_dotdot_rcu()` which fairly trivially follows the required pattern, though it does so for three different cases.

When not at a mount point, `d_parent` is followed and its `d_seq` is collected.  When we are at a mount point, we instead follow the `mnt->mnt_mountpoint` link to get a new dentry and collect its `d_seq`.  Then, after finally finding a `d_parent` to follow, we must check if we have landed on a mount point and, if so, must find that mount point and follow the `mnt->mnt_root` link.  This would imply a somewhat unusual, but certainly possible, circumstance where the starting point of the path lookup was in part of the filesystem that was mounted on, and so not visible from the root.

The inode pointer, stored in `->d_inode`, is a little more interesting.  The inode will always need to be accessed at least twice, once to determine if it is NULL and once to verify access permissions.  Symlink handling requires a validated inode pointer too. Rather than revalidating on each access, a copy is made on the first access and it is stored in the `inode` field of `nameidata` from where it can be safely accessed without further validation.

`lookup_fast()` is the only lookup routine that is used in RCU-mode, `lookup_slow()` being too slow and requiring locks.  It is in `lookup_fast()` that we find the important "hand over hand" tracking of the current dentry.

The current `dentry` and current `seq` number are passed to `__d_lookup_rcu()` which, on success, returns a new `dentry` and a new `seq` number.  `lookup_fast()` then copies the inode pointer and revalidates the new `seq` number.  It then validates the old `dentry` with the old `seq` number one last time and only then continues.  This process of getting the `seq` number of the new dentry and then checking the `seq` number of the old exactly mirrors the process of getting a counted reference to the new dentry before dropping that for the old dentry which we saw in REF-walk.

<a id="rst-no-inode-i-rwsem-or-even-rename-lock"></a>

#### No `inode->i_rwsem` or even `rename_lock`

A semaphore is a fairly heavyweight lock that can only be taken when it is permissible to sleep.  As `rcu_read_lock()` forbids sleeping, `inode->i_rwsem` plays no role in RCU-walk.  If some other thread does take `i_rwsem` and modifies the directory in a way that RCU-walk needs to notice, the result will be either that RCU-walk fails to find the dentry that it is looking for, or it will find a dentry which `read_seqretry()` won't validate.  In either case it will drop down to REF-walk mode which can take whatever locks are needed.

Though `rename_lock` could be used by RCU-walk as it doesn't require any sleeping, RCU-walk doesn't bother.  REF-walk uses `rename_lock` to protect against the possibility of hash chains in the dcache changing while they are being searched.  This can result in failing to find something that actually is there.  When RCU-walk fails to find something in the dentry cache, whether it is really there or not, it already drops down to REF-walk and tries again with appropriate locking.  This neatly handles all cases, so adding extra checks on rename_lock would bring no significant value.

<a id="rst-unlazy-walk-and-complete-walk"></a>

### `unlazy walk()` and `complete_walk()`

That "dropping down to REF-walk" typically involves a call to `unlazy_walk()`, so named because "RCU-walk" is also sometimes referred to as "lazy walk".  `unlazy_walk()` is called when following the path down to the current vfsmount/dentry pair seems to have proceeded successfully, but the next step is problematic.  This can happen if the next name cannot be found in the dcache, if permission checking or name revalidation couldn't be achieved while the `rcu_read_lock()` is held (which forbids sleeping), if an automount point is found, or in a couple of cases involving symlinks. It is also called from `complete_walk()` when the lookup has reached the final component, or the very end of the path, depending on which particular flavor of lookup is used.

Other reasons for dropping out of RCU-walk that do not trigger a call to `unlazy_walk()` are when some inconsistency is found that cannot be handled immediately, such as `mount_lock` or one of the `d_seq` seqlocks reporting a change.  In these cases the relevant function will return `-ECHILD` which will percolate up until it triggers a new attempt from the top using REF-walk.

For those cases where `unlazy_walk()` is an option, it essentially takes a reference on each of the pointers that it holds (vfsmount, dentry, and possibly some symbolic links) and then verifies that the relevant seqlocks have not been changed.  If there have been changes, it, too, aborts with `-ECHILD`, otherwise the transition to REF-walk has been a success and the lookup process continues.

Taking a reference on those pointers is not quite as simple as just incrementing a counter.  That works to take a second reference if you already have one (often indirectly through another object), but it isn't sufficient if you don't actually have a counted reference at all.  For `dentry->d_lockref`, it is safe to increment the reference counter to get a reference unless it has been explicitly marked as "dead" which involves setting the counter to `-128`. `lockref_get_not_dead()` achieves this.

For `mnt->mnt_count` it is safe to take a reference as long as `mount_lock` is then used to validate the reference.  If that validation fails, it may *not* be safe to just drop that reference in the standard way of calling `mnt_put()` - an unmount may have progressed too far.  So the code in `legitimize_mnt()`, when it finds that the reference it got might not be safe, checks the `MNT_SYNC_UMOUNT` flag to determine if a simple `mnt_put()` is correct, or if it should just decrement the count and pretend none of this ever happened.

<a id="rst-taking-care-in-filesystems"></a>

### Taking care in filesystems

RCU-walk depends almost entirely on cached information and often will not call into the filesystem at all.  However there are two places, besides the already-mentioned component-name comparison, where the file system might be included in RCU-walk, and it must know to be careful.

If the filesystem has non-standard permission-checking requirements - such as a networked filesystem which may need to check with the server - the `i_op->permission` interface might be called during RCU-walk. In this case an extra "`MAY_NOT_BLOCK`" flag is passed so that it knows not to sleep, but to return `-ECHILD` if it cannot complete promptly.  `i_op->permission` is given the inode pointer, not the dentry, so it doesn't need to worry about further consistency checks. However if it accesses any other filesystem data structures, it must ensure they are safe to be accessed with only the `rcu_read_lock()` held.  This typically means they must be freed using `kfree_rcu()` or similar.

<a id="rst-read-once"></a>



If the filesystem may need to revalidate dcache entries, then `d_op->d_revalidate` may be called in RCU-walk too.  This interface *is* passed the dentry but does not have access to the `inode` or the `seq` number from the `nameidata`, so it needs to be extra careful when accessing fields in the dentry.  This "extra care" typically involves using  [READ_ONCE()](<https://lwn.net/Articles/624126/>)<a id="rst-read-once-1"></a> to access fields, and verifying the result is not NULL before using it.  This pattern can be seen in `nfs_lookup_revalidate()`.

<a id="rst-a-pair-of-patterns"></a>

### A pair of patterns

In various places in the details of REF-walk and RCU-walk, and also in the big picture, there are a couple of related patterns that are worth being aware of.

The first is "try quickly and check, if that fails try slowly".  We can see that in the high-level approach of first trying RCU-walk and then trying REF-walk, and in places where `unlazy_walk()` is used to switch to REF-walk for the rest of the path.  We also saw it earlier in `dget_parent()` when following a "`..`" link.  It tries a quick way to get a reference, then falls back to taking locks if needed.

The second pattern is "try quickly and check, if that fails try again - repeatedly".  This is seen with the use of `rename_lock` and `mount_lock` in REF-walk.  RCU-walk doesn't make use of this pattern - if anything goes wrong it is much safer to just abort and try a more sedate approach.

The emphasis here is "try quickly and check".  It should probably be "try quickly *and carefully*, then check".  The fact that checking is needed is a reminder that the system is dynamic and only a limited number of things are safe at all.  The most likely cause of errors in this whole process is assuming something is safe when in reality it isn't.  Careful consideration of what exactly guarantees the safety of each access is sometimes necessary.

<a id="rst-a-walk-among-the-symlinks"></a>

## A walk among the symlinks

There are several basic issues that we will examine to understand the handling of symbolic links:  the symlink stack, together with cache lifetimes, will help us understand the overall recursive handling of symlinks and lead to the special care needed for the final component. Then a consideration of access-time updates and summary of the various flags controlling lookup will finish the story.

<a id="rst-the-symlink-stack"></a>

### The symlink stack

There are only two sorts of filesystem objects that can usefully appear in a path prior to the final component: directories and symlinks. Handling directories is quite straightforward: the new directory simply becomes the starting point at which to interpret the next component on the path.  Handling symbolic links requires a bit more work.

Conceptually, symbolic links could be handled by editing the path.  If a component name refers to a symbolic link, then that component is replaced by the body of the link and, if that body starts with a '/', then all preceding parts of the path are discarded.  This is what the "`readlink -f`" command does, though it also edits out "`.`" and "`..`" components.

Directly editing the path string is not really necessary when looking up a path, and discarding early components is pointless as they aren't looked at anyway.  Keeping track of all remaining components is important, but they can of course be kept separately; there is no need to concatenate them.  As one symlink may easily refer to another, which in turn can refer to a third, we may need to keep the remaining components of several paths, each to be processed when the preceding ones are completed.  These path remnants are kept on a stack of limited size.

There are two reasons for placing limits on how many symlinks can occur in a single path lookup.  The most obvious is to avoid loops. If a symlink referred to itself either directly or through intermediaries, then following the symlink can never complete successfully - the error `ELOOP` must be returned.  Loops can be detected without imposing limits, but limits are the simplest solution and, given the second reason for restriction, quite sufficient.

<a id="rst-outlined-recently"></a>



The second reason was [outlined recently](<http://thread.gmane.org/gmane.linux.kernel/1934390/focus=1934550>) by Linus:

> Because it's a latency and DoS issue too. We need to react well to true loops, but also to "very deep" non-loops. It's not about memory use, it's about users triggering unreasonable CPU resources.

Linux imposes a limit on the length of any pathname: `PATH_MAX`, which is 4096.  There are a number of reasons for this limit; not letting the kernel spend too much time on just one path is one of them.  With symbolic links you can effectively generate much longer paths so some sort of limit is needed for the same reason.  Linux imposes a limit of at most 40 (MAXSYMLINKS) symlinks in any one path lookup.  It previously imposed a further limit of eight on the maximum depth of recursion, but that was raised to 40 when a separate stack was implemented, so there is now just the one limit.

The `nameidata` structure that we met in an earlier article contains a small stack that can be used to store the remaining part of up to two symlinks.  In many cases this will be sufficient.  If it isn't, a separate stack is allocated with room for 40 symlinks.  Pathname lookup will never exceed that stack as, once the 40th symlink is detected, an error is returned.

It might seem that the name remnants are all that needs to be stored on this stack, but we need a bit more.  To see that, we need to move on to cache lifetimes.

<a id="rst-storage-and-lifetime-of-cached-symlinks"></a>

### Storage and lifetime of cached symlinks

Like other filesystem resources, such as inodes and directory entries, symlinks are cached by Linux to avoid repeated costly access to external storage.  It is particularly important for RCU-walk to be able to find and temporarily hold onto these cached entries, so that it doesn't need to drop down into REF-walk.

<a id="rst-object-oriented-design-pattern"></a>



While each filesystem is free to make its own choice, symlinks are typically stored in one of two places.  Short symlinks are often stored directly in the inode.  When a filesystem allocates a `struct inode` it typically allocates extra space to store private data (a common [object-oriented design pattern](<https://lwn.net/Articles/446317/>) in the kernel).  This will sometimes include space for a symlink.  The other common location is in the page cache, which normally stores the content of files.  The pathname in a symlink can be seen as the content of that symlink and can easily be stored in the page cache just like file content.

When neither of these is suitable, the next most likely scenario is that the filesystem will allocate some temporary memory and copy or construct the symlink content into that memory whenever it is needed.

When the symlink is stored in the inode, it has the same lifetime as the inode which, itself, is protected by RCU or by a counted reference on the dentry.  This means that the mechanisms that pathname lookup uses to access the dcache and icache (inode cache) safely are quite sufficient for accessing some cached symlinks safely.  In these cases, the `i_link` pointer in the inode is set to point to wherever the symlink is stored and it can be accessed directly whenever needed.

When the symlink is stored in the page cache or elsewhere, the situation is not so straightforward.  A reference on a dentry or even on an inode does not imply any reference on cached pages of that inode, and even an `rcu_read_lock()` is not sufficient to ensure that a page will not disappear.  So for these symlinks the pathname lookup code needs to ask the filesystem to provide a stable reference and, significantly, needs to release that reference when it is finished with it.

Taking a reference to a cache page is often possible even in RCU-walk mode.  It does require making changes to memory, which is best avoided, but that isn't necessarily a big cost and it is better than dropping out of RCU-walk mode completely.  Even filesystems that allocate space to copy the symlink into can use `GFP_ATOMIC` to often successfully allocate memory without the need to drop out of RCU-walk.  If a filesystem cannot successfully get a reference in RCU-walk mode, it must return `-ECHILD` and `unlazy_walk()` will be called to return to REF-walk mode in which the filesystem is allowed to sleep.

The place for all this to happen is the `i_op->get_link()` inode method. This is called both in RCU-walk and REF-walk. In RCU-walk the `dentry*` argument is NULL, `->get_link()` can return -ECHILD to drop out of RCU-walk.  Much like the `i_op->permission()` method we looked at previously, `->get_link()` would need to be careful that all the data structures it references are safe to be accessed while holding no counted reference, only the RCU lock. A callback `struct delayed_called` will be passed to `->get_link()`: file systems can set their own put_link function and argument through set_delayed_call(). Later on, when VFS wants to put link, it will call do_delayed_call() to invoke that callback function with the argument.

In order for the reference to each symlink to be dropped when the walk completes, whether in RCU-walk or REF-walk, the symlink stack needs to contain, along with the path remnants:

- the `struct path` to provide a reference to the previous path

- the `const char *` to provide a reference to the to previous name

- the `seq` to allow the path to be safely switched from RCU-walk to REF-walk

- the `struct delayed_call` for later invocation.

This means that each entry in the symlink stack needs to hold five pointers and an integer instead of just one pointer (the path remnant).  On a 64-bit system, this is about 40 bytes per entry; with 40 entries it adds up to 1600 bytes total, which is less than half a page.  So it might seem like a lot, but is by no means excessive.

Note that, in a given stack frame, the path remnant (`name`) is not part of the symlink that the other fields refer to.  It is the remnant to be followed once that symlink has been fully parsed.

<a id="rst-following-the-symlink"></a>

### Following the symlink

The main loop in `link_path_walk()` iterates seamlessly over all components in the path and all of the non-final symlinks.  As symlinks are processed, the `name` pointer is adjusted to point to a new symlink, or is restored from the stack, so that much of the loop doesn't need to notice.  Getting this `name` variable on and off the stack is very straightforward; pushing and popping the references is a little more complex.

When a symlink is found, walk_component() calls pick_link() via step_into() which returns the link from the filesystem. Providing that operation is successful, the old path `name` is placed on the stack, and the new value is used as the `name` for a while.  When the end of the path is found (i.e. `*name` is `'\0'`) the old `name` is restored off the stack and path walking continues.

Pushing and popping the reference pointers (inode, cookie, etc.) is more complex in part because of the desire to handle tail recursion.  When the last component of a symlink itself points to a symlink, we want to pop the symlink-just-completed off the stack before pushing the symlink-just-found to avoid leaving empty path remnants that would just get in the way.

It is most convenient to push the new symlink references onto the stack in `walk_component()` immediately when the symlink is found; `walk_component()` is also the last piece of code that needs to look at the old symlink as it walks that last component.  So it is quite convenient for `walk_component()` to release the old symlink and pop the references just before pushing the reference information for the new symlink.  It is guided in this by three flags: `WALK_NOFOLLOW` which forbids it from following a symlink if it finds one, `WALK_MORE` which indicates that it is yet too early to release the current symlink, and `WALK_TRAILING` which indicates that it is on the final component of the lookup, so we will check userspace flag `LOOKUP_FOLLOW` to decide whether follow it when it is a symlink and call `may_follow_link()` to check if we have privilege to follow it.

<a id="rst-symlinks-with-no-final-component"></a>

#### Symlinks with no final component

A pair of special-case symlinks deserve a little further explanation. Both result in a new `struct path` (with mount and dentry) being set up in the `nameidata`, and result in pick_link() returning `NULL`.

The more obvious case is a symlink to "`/`".  All symlinks starting with "`/`" are detected in pick_link() which resets the `nameidata` to point to the effective filesystem root.  If the symlink only contains "`/`" then there is nothing more to do, no components at all, so `NULL` is returned to indicate that the symlink can be released and the stack frame discarded.

The other case involves things in `/proc` that look like symlinks but aren't really (and are therefore commonly referred to as "magic-links"):



```text
$ ls -l /proc/self/fd/1
lrwx------ 1 neilb neilb 64 Jun 13 10:19 /proc/self/fd/1 -> /dev/pts/4
```

Every open file descriptor in any process is represented in `/proc` by something that looks like a symlink.  It is really a reference to the target file, not just the name of it.  When you `readlink` these objects you get a name that might refer to the same file - unless it has been unlinked or mounted over.  When `walk_component()` follows one of these, the `->get_link()` method in "procfs" doesn't return a string name, but instead calls nd_jump_link() which updates the `nameidata` in place to point to that target.  `->get_link()` then returns `NULL`.  Again there is no final component and pick_link() returns `NULL`.

<a id="rst-following-the-symlink-in-the-final-component"></a>

### Following the symlink in the final component

All this leads to `link_path_walk()` walking down every component, and following all symbolic links it finds, until it reaches the final component.  This is just returned in the `last` field of `nameidata`. For some callers, this is all they need; they want to create that `last` name if it doesn't exist or give an error if it does.  Other callers will want to follow a symlink if one is found, and possibly apply special handling to the last component of that symlink, rather than just the last component of the original file name.  These callers potentially need to call `link_path_walk()` again and again on successive symlinks until one is found that doesn't point to another symlink.

This case is handled by relevant callers of link_path_walk(), such as path_lookupat(), path_openat() using a loop that calls link_path_walk(), and then handles the final component by calling open_last_lookups() or lookup_last(). If it is a symlink that needs to be followed, open_last_lookups() or lookup_last() will set things up properly and return the path so that the loop repeats, calling link_path_walk() again.  This could loop as many as 40 times if the last component of each symlink is another symlink.

Of the various functions that examine the final component, open_last_lookups() is the most interesting as it works in tandem with do_open() for opening a file.  Part of open_last_lookups() runs with `i_rwsem` held and this part is in a separate function: lookup_open().

Explaining open_last_lookups() and do_open() completely is beyond the scope of this article, but a few highlights should help those interested in exploring the code.

1. Rather than just finding the target file, do_open() is used after open_last_lookup() to open it.  If the file was found in the dcache, then `vfs_open()` is used for this.  If not, then `lookup_open()` will either call `atomic_open()` (if the filesystem provides it) to combine the final lookup with the open, or will perform the separate `i_op->lookup()` and `i_op->create()` steps directly.  In the later case the actual "open" of this newly found or created file will be performed by vfs_open(), just as if the name were found in the dcache.

2. vfs_open() can fail with `-EOPENSTALE` if the cached information wasn't quite current enough.  If it's in RCU-walk `-ECHILD` will be returned otherwise `-ESTALE` is returned.  When `-ESTALE` is returned, the caller may retry with `LOOKUP_REVAL` flag set.

3. An open with O_CREAT **does** follow a symlink in the final component, unlike other creation system calls (like `mkdir`).  So the sequence:



   ```text
   ln -s bar /tmp/foo
   echo hello > /tmp/foo
   ```

   will create a file called `/tmp/bar`.  This is not permitted if `O_EXCL` is set but otherwise is handled for an O_CREAT open much like for a non-creating open: lookup_last() or open_last_lookup() returns a non `NULL` value, and link_path_walk() gets called and the open process continues on the symlink that was found.

<a id="rst-updating-the-access-time"></a>

### Updating the access time

We previously said of RCU-walk that it would "take no locks, increment no counts, leave no footprints."  We have since seen that some "footprints" can be needed when handling symlinks as a counted reference (or even a memory allocation) may be needed.  But these footprints are best kept to a minimum.

One other place where walking down a symlink can involve leaving footprints in a way that doesn't affect directories is in updating access times. In Unix (and Linux) every filesystem object has a "last accessed time", or "`atime`".  Passing through a directory to access a file within is not considered to be an access for the purposes of `atime`; only listing the contents of a directory can update its `atime`. Symlinks are different it seems.  Both reading a symlink (with `readlink()`) and looking up a symlink on the way to some other destination can update the atime on that symlink.

<a id="rst-clearest-statement"></a>



It is not clear why this is the case; POSIX has little to say on the subject.  The [clearest statement](<https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08>) is that, if a particular implementation updates a timestamp in a place not specified by POSIX, this must be documented "except that any changes caused by pathname resolution need not be documented".  This seems to imply that POSIX doesn't really care about access-time updates during pathname lookup.

<a id="rst-linux-1-3-87"></a>



An examination of history shows that prior to [Linux 1.3.87](<https://git.kernel.org/cgit/linux/kernel/git/history/history.git/diff/fs/ext2/symlink.c?id=f806c6db77b8eaa6e00dcfb6b567706feae8dbb8>), the ext2 filesystem, at least, didn't update atime when following a link. Unfortunately we have no record of why that behavior was changed.

In any case, access time must now be updated and that operation can be quite complex.  Trying to stay in RCU-walk while doing it is best avoided.  Fortunately it is often permitted to skip the `atime` update.  Because `atime` updates cause performance problems in various areas, Linux supports the `relatime` mount option, which generally limits the updates of `atime` to once per day on files that aren't being changed (and symlinks never change once created).  Even without `relatime`, many filesystems record `atime` with a one-second granularity, so only one update per second is required.

It is easy to test if an `atime` update is needed while in RCU-walk mode and, if it isn't, the update can be skipped and RCU-walk mode continues.  Only when an `atime` update is actually required does the path walk drop down to REF-walk.  All of this is handled in the `get_link()` function.

<a id="rst-a-few-flags"></a>

### A few flags

A suitable way to wrap up this tour of pathname walking is to list the various flags that can be stored in the `nameidata` to guide the lookup process.  Many of these are only meaningful on the final component, others reflect the current state of the pathname lookup, and some apply restrictions to all path components encountered in the path lookup.

And then there is `LOOKUP_EMPTY`, which doesn't fit conceptually with the others.  If this is not set, an empty pathname causes an error very early on.  If it is set, empty pathnames are not considered to be an error.

<a id="rst-global-state-flags"></a>

#### Global state flags

We have already met two global state flags: `LOOKUP_RCU` and `LOOKUP_REVAL`.  These select between one of three overall approaches to lookup: RCU-walk, REF-walk, and REF-walk with forced revalidation.

`LOOKUP_PARENT` indicates that the final component hasn't been reached yet.  This is primarily used to tell the audit subsystem the full context of a particular access being audited.

`ND_ROOT_PRESET` indicates that the `root` field in the `nameidata` was provided by the caller, so it shouldn't be released when it is no longer needed.

`ND_JUMPED` means that the current dentry was chosen not because it had the right name but for some other reason.  This happens when following "`..`", following a symlink to `/`, crossing a mount point or accessing a "`/proc/$PID/fd/$FD`" symlink (also known as a "magic link"). In this case the filesystem has not been asked to revalidate the name (with `d_revalidate()`).  In such cases the inode may still need to be revalidated, so `d_op->d_weak_revalidate()` is called if `ND_JUMPED` is set when the look completes - which may be at the final component or, when creating, unlinking, or renaming, at the penultimate component.

<a id="rst-resolution-restriction-flags"></a>

#### Resolution-restriction flags

In order to allow userspace to protect itself against certain race conditions and attack scenarios involving changing path components, a series of flags are available which apply restrictions to all path components encountered during path lookup. These flags are exposed through `openat2()`'s `resolve` field.

`LOOKUP_NO_SYMLINKS` blocks all symlink traversals (including magic-links). This is distinctly different from `LOOKUP_FOLLOW`, because the latter only relates to restricting the following of trailing symlinks.

`LOOKUP_NO_MAGICLINKS` blocks all magic-link traversals. Filesystems must ensure that they return errors from `nd_jump_link()`, because that is how `LOOKUP_NO_MAGICLINKS` and other magic-link restrictions are implemented.

`LOOKUP_NO_XDEV` blocks all `vfsmount` traversals (this includes both bind-mounts and ordinary mounts). Note that the `vfsmount` which contains the lookup is determined by the first mountpoint the path lookup reaches -- absolute paths start with the `vfsmount` of `/`, and relative paths start with the `dfd`'s `vfsmount`. Magic-links are only permitted if the `vfsmount` of the path is unchanged.

`LOOKUP_BENEATH` blocks any path components which resolve outside the starting point of the resolution. This is done by blocking `nd_jump_root()` as well as blocking ".." if it would jump outside the starting point. `rename_lock` and `mount_lock` are used to detect attacks against the resolution of "..". Magic-links are also blocked.

`LOOKUP_IN_ROOT` resolves all path components as though the starting point were the filesystem root. `nd_jump_root()` brings the resolution back to the starting point, and ".." at the starting point will act as a no-op. As with `LOOKUP_BENEATH`, `rename_lock` and `mount_lock` are used to detect attacks against ".." resolution. Magic-links are also blocked.

<a id="rst-final-component-flags"></a>

#### Final-component flags

Some of these flags are only set when the final component is being considered.  Others are only checked for when considering that final component.

`LOOKUP_AUTOMOUNT` ensures that, if the final component is an automount point, then the mount is triggered.  Some operations would trigger it anyway, but operations like `stat()` deliberately don't.  `statfs()` needs to trigger the mount but otherwise behaves a lot like `stat()`, so it sets `LOOKUP_AUTOMOUNT`, as does "`quotactl()`" and the handling of "`mount --bind`".

`LOOKUP_FOLLOW` has a similar function to `LOOKUP_AUTOMOUNT` but for symlinks.  Some system calls set or clear it implicitly, while others have API flags such as `AT_SYMLINK_FOLLOW` and `UMOUNT_NOFOLLOW` to control it.  Its effect is similar to `WALK_GET` that we already met, but it is used in a different way.

`LOOKUP_DIRECTORY` insists that the final component is a directory. Various callers set this and it is also set when the final component is found to be followed by a slash.

Finally `LOOKUP_OPEN`, `LOOKUP_CREATE`, `LOOKUP_EXCL`, and `LOOKUP_RENAME_TARGET` are not used directly by the VFS but are made available to the filesystem and particularly the `->d_revalidate()` method.  A filesystem can choose not to bother revalidating too hard if it knows that it will be asked to open or create the file soon. These flags were previously useful for `->lookup()` too but with the introduction of `->atomic_open()` they are less relevant there.

<a id="rst-end-of-the-road"></a>

### End of the road

Despite its complexity, all this pathname lookup code appears to be in good shape - various parts are certainly easier to understand now than even a couple of releases ago.  But that doesn't mean it is "finished".   As already mentioned, RCU-walk currently only follows symlinks that are stored in the inode so, while it handles many ext4 symlinks, it doesn't help with NFS, XFS, or Btrfs.  That support is not likely to be long delayed.

---

# Changes since 2.5.0:

_Peios Kernel / Internals / Filesystems_

> ---

<a id="rst-changes-since-2-5-0"></a>

\---

<strong>recommended</strong>

New helpers: sb\_bread(), sb\_getblk(), sb\_find\_get\_block(), set\_bh(), sb\_set\_blocksize() and sb\_min\_blocksize().

Use them.

(sb\_find\_get\_block() replaces 2.4's get\_hash\_table())

\---

<strong>recommended</strong>

New methods: -&gt;alloc\_inode() and -&gt;destroy\_inode().

Remove inode-&gt;u.foo\_inode\_i

Declare:



```text
struct foo_inode_info {
        /* fs-private stuff */
        struct inode vfs_inode;
};
static inline struct foo_inode_info *FOO_I(struct inode *inode)
{
        return list_entry(inode, struct foo_inode_info, vfs_inode);
}
```

Use FOO\_I(inode) instead of &amp;inode-&gt;u.foo\_inode\_i;

Add foo\_alloc\_inode() and foo\_destroy\_inode() - the former should allocate foo\_inode\_info and return the address of -&gt;vfs\_inode, the latter should free FOO\_I(inode) (see in-tree filesystems for examples).

Make them -&gt;alloc\_inode and -&gt;destroy\_inode in your super\_operations.

Keep in mind that now you need explicit initialization of private data typically between calling iget\_locked() and unlocking the inode.

At some point that will become mandatory.

<strong>mandatory</strong>

The foo\_inode\_info should always be allocated through alloc\_inode\_sb() rather than kmem\_cache\_alloc() or kmalloc() related to set up the inode reclaim context correctly.

\---

<strong>mandatory</strong>

Change of file\_system\_type method (-&gt;read\_super to -&gt;get\_sb)

-&gt;read\_super() is no more.  Ditto for DECLARE\_FSTYPE and DECLARE\_FSTYPE\_DEV.

Turn your foo\_read\_super() into a function that would return 0 in case of success and negative number in case of error (-EINVAL unless you have more informative error value to report).  Call it foo\_fill\_super().  Now declare:



```text
int foo_get_sb(struct file_system_type *fs_type,
      int flags, const char *dev_name, void *data, struct vfsmount *mnt)
{
      return get_sb_bdev(fs_type, flags, dev_name, data, foo_fill_super,
                         mnt);
}
```

(or similar with s/bdev/nodev/ or s/bdev/single/, depending on the kind of filesystem).

Replace DECLARE\_FSTYPE... with explicit initializer and have -&gt;get\_sb set as foo\_get\_sb.

\---

<strong>mandatory</strong>

Locking change: -&gt;s\_vfs\_rename\_sem is taken only by cross-directory renames. Most likely there is no need to change anything, but if you relied on global exclusion between renames for some internal purpose - you need to change your internal locking.  Otherwise exclusion warranties remain the same (i.e. parents and victim are locked, etc.).

\---

<strong>informational</strong>

Now we have the exclusion between -&gt;lookup() and directory removal (by -&gt;rmdir() and -&gt;rename()).  If you used to need that exclusion and do it by internal locking (most of filesystems couldn't care less) - you can relax your locking.

\---

<strong>mandatory</strong>

-&gt;lookup(), -&gt;truncate(), -&gt;create(), -&gt;unlink(), -&gt;mknod(), -&gt;mkdir(), -&gt;rmdir(), -&gt;link(), -&gt;lseek(), -&gt;symlink(), -&gt;rename() and -&gt;readdir() are called without BKL now.  Grab it on entry, drop upon return - that will guarantee the same locking you used to have.  If your method or its parts do not need BKL - better yet, now you can shift lock\_kernel() and unlock\_kernel() so that they would protect exactly what needs to be protected.

\---

<strong>mandatory</strong>

BKL is also moved from around sb operations. BKL should have been shifted into individual fs sb\_op functions.  If you don't need it, remove it.

\---

<strong>informational</strong>

check for -&gt;link() target not being a directory is done by callers.  Feel free to drop it...

\---

<strong>informational</strong>

-&gt;link() callers hold -&gt;i\_mutex on the object we are linking to.  Some of your problems might be over...

\---

<strong>mandatory</strong>

new file\_system\_type method - kill\_sb(superblock).  If you are converting an existing filesystem, set it according to -&gt;fs\_flags:



```text
FS_REQUIRES_DEV         -       kill_block_super
FS_LITTER               -       kill_litter_super
neither                 -       kill_anon_super
```

FS\_LITTER is gone - just remove it from fs\_flags.

\---

<strong>mandatory</strong>

FS\_SINGLE is gone (actually, that had happened back when -&gt;get\_sb() went in - and hadn't been documented ;-/).  Just remove it from fs\_flags (and see -&gt;get\_sb() entry for other actions).

\---

<strong>mandatory</strong>

-&gt;setattr() is called without BKL now.  Caller \_always\_ holds -&gt;i\_mutex, so watch for -&gt;i\_mutex-grabbing code that might be used by your -&gt;setattr(). Callers of notify\_change() need -&gt;i\_mutex now.

\---

<strong>recommended</strong>

New super\_block field `struct export_operations *s_export_op` for explicit support for exporting, e.g. via NFS.  The structure is fully documented at its declaration in include/linux/fs.h, and in [Documentation/filesystems/nfs/exporting.rst](/kernel/internals/filesystems/nfs/exporting.md).

Briefly it allows for the definition of decode\_fh and encode\_fh operations to encode and decode filehandles, and allows the filesystem to use a standard helper function for decode\_fh, and provide file-system specific support for this helper, particularly get\_parent.

It is planned that this will be required for exporting once the code settles down a bit.

<strong>mandatory</strong>

s\_export\_op is now required for exporting a filesystem. isofs, ext2, ext3, fat can be used as examples of very different filesystems.

\---

<strong>mandatory</strong>

iget4() and the read\_inode2 callback have been superseded by iget5\_locked() which has the following prototype:



```text
struct inode *iget5_locked(struct super_block *sb, unsigned long ino,
                            int (*test)(struct inode *, void *),
                            int (*set)(struct inode *, void *),
                            void *data);
```

'test' is an additional function that can be used when the inode number is not sufficient to identify the actual file object. 'set' should be a non-blocking function that initializes those parts of a newly created inode to allow the test function to succeed. 'data' is passed as an opaque value to both test and set functions.

When the inode has been created by iget5\_locked(), it will be returned with the I\_NEW flag set and will still be locked.  The filesystem then needs to finalize the initialization. Once the inode is initialized it must be unlocked by calling unlock\_new\_inode().

The filesystem is responsible for setting (and possibly testing) i\_ino when appropriate. There is also a simpler iget\_locked function that just takes the superblock and inode number as arguments and does the test and set for you.

e.g.:



```text
inode = iget_locked(sb, ino);
if (inode_state_read_once(inode) & I_NEW) {
        err = read_inode_from_disk(inode);
        if (err < 0) {
                iget_failed(inode);
                return err;
        }
        unlock_new_inode(inode);
}
```

Note that if the process of setting up a new inode fails, then iget\_failed() should be called on the inode to render it dead, and an appropriate error should be passed back to the caller.

\---

<strong>recommended</strong>

-&gt;getattr() finally getting used.  See instances in nfs, minix, etc.

\---

<strong>mandatory</strong>

-&gt;revalidate() is gone.  If your filesystem had it - provide -&gt;getattr() and let it call whatever you had as -&gt;revlidate() + (for symlinks that had -&gt;revalidate()) add calls in -&gt;follow\_link()/-&gt;readlink().

\---

<strong>mandatory</strong>

-&gt;d\_parent changes are not protected by BKL anymore.  Read access is safe if at least one of the following is true:

> - filesystem has no cross-directory rename()
>
> - we know that parent had been locked (e.g. we are looking at -&gt;d\_parent of -&gt;lookup() argument).
>
> - we are called from -&gt;rename().
>
> - the child's -&gt;d\_lock is held

Audit your code and add locking if needed.  Notice that any place that is not protected by the conditions above is risky even in the old tree - you had been relying on BKL and that's prone to screwups.  Old tree had quite a few holes of that kind - unprotected access to -&gt;d\_parent leading to anything from oops to silent memory corruption.

\---

<strong>mandatory</strong>

FS\_NOMOUNT is gone.  If you use it - just set SB\_NOUSER in flags (see rootfs for one kind of solution and bdev/socket/pipe for another).

\---

<strong>recommended</strong>

Use bdev\_read\_only(bdev) instead of is\_read\_only(kdev).  The latter is still alive, but only because of the mess in drivers/s390/block/dasd.c. As soon as it gets fixed is\_read\_only() will die.

\---

<strong>mandatory</strong>

-&gt;permission() is called without BKL now. Grab it on entry, drop upon return - that will guarantee the same locking you used to have.  If your method or its parts do not need BKL - better yet, now you can shift lock\_kernel() and unlock\_kernel() so that they would protect exactly what needs to be protected.

\---

<strong>mandatory</strong>

-&gt;statfs() is now called without BKL held.  BKL should have been shifted into individual fs sb\_op functions where it's not clear that it's safe to remove it.  If you don't need it, remove it.

\---

<strong>mandatory</strong>

is\_read\_only() is gone; use bdev\_read\_only() instead.

\---

<strong>mandatory</strong>

destroy\_buffers() is gone; use invalidate\_bdev().

\---

<strong>mandatory</strong>

fsync\_dev() is gone; use fsync\_bdev().  NOTE: lvm breakage is deliberate; as soon as struct block\_device \* is propagated in a reasonable way by that code fixing will become trivial; until then nothing can be done.

<strong>mandatory</strong>

block truncation on error exit from -&gt;write\_begin, and -&gt;direct\_IO moved from generic methods (block\_write\_begin, cont\_write\_begin, nobh\_write\_begin, blockdev\_direct\_IO\*) to callers.  Take a look at ext2\_write\_failed and callers for an example.

<strong>mandatory</strong>

-&gt;truncate is gone.  The whole truncate sequence needs to be implemented in -&gt;setattr, which is now mandatory for filesystems implementing on-disk size changes.  Start with a copy of the old inode\_setattr and vmtruncate, and the reorder the vmtruncate + foofs\_vmtruncate sequence to be in order of zeroing blocks using block\_truncate\_page or similar helpers, size update and on finally on-disk truncation which should not fail. setattr\_prepare (which used to be inode\_change\_ok) now includes the size checks for ATTR\_SIZE and must be called in the beginning of -&gt;setattr unconditionally.

<strong>mandatory</strong>

-&gt;clear\_inode() and -&gt;delete\_inode() are gone; -&gt;evict\_inode() should be used instead.  It gets called whenever the inode is evicted, whether it has remaining links or not.  Caller does <em>not</em> evict the pagecache or inode-associated metadata buffers; the method has to use truncate\_inode\_pages\_final() to get rid of those. Caller makes sure async writeback cannot be running for the inode while (or after) -&gt;evict\_inode() is called.

-&gt;drop\_inode() returns int now; it's called on final iput() with inode-&gt;i\_lock held and it returns true if filesystems wants the inode to be dropped.  As before, inode\_generic\_drop() is still the default and it's been updated appropriately.  inode\_just\_drop() is also alive and it consists simply of return 1.  Note that all actual eviction work is done by caller after -&gt;drop\_inode() returns.

As before, clear\_inode() must be called exactly once on each call of -&gt;evict\_inode() (as it used to be for each call of -&gt;delete\_inode()).  Unlike before, if you are using inode-associated metadata buffers (i.e. mark\_buffer\_dirty\_inode()), it's your responsibility to call invalidate\_inode\_buffers() before clear\_inode().

NOTE: checking i\_nlink in the beginning of -&gt;write\_inode() and bailing out if it's zero is not <em>and</em> <em>never</em> <em>had</em> <em>been</em> enough.  Final unlink() and iput() may happen while the inode is in the middle of -&gt;write\_inode(); e.g. if you blindly free the on-disk inode, you may end up doing that while -&gt;write\_inode() is writing to it.

\---

<strong>mandatory</strong>

.d\_delete() now only advises the dcache as to whether or not to cache unreferenced dentries, and is now only called when the dentry refcount goes to 0. Even on 0 refcount transition, it must be able to tolerate being called 0, 1, or more times (eg. constant, idempotent).

\---

<strong>mandatory</strong>

.d\_compare() calling convention and locking rules are significantly changed. Read updated documentation in [Documentation/filesystems/vfs.rst](/kernel/internals/filesystems/vfs.md) (and look at examples of other filesystems) for guidance.

\---

<strong>mandatory</strong>

.d\_hash() calling convention and locking rules are significantly changed. Read updated documentation in [Documentation/filesystems/vfs.rst](/kernel/internals/filesystems/vfs.md) (and look at examples of other filesystems) for guidance.

\---

<strong>mandatory</strong>

dcache\_lock is gone, replaced by fine grained locks. See fs/dcache.c for details of what locks to replace dcache\_lock with in order to protect particular things. Most of the time, a filesystem only needs -&gt;d\_lock, which protects <em>all</em> the dcache state of a given dentry.

\---

<strong>mandatory</strong>

Filesystems must RCU-free their inodes, if they can have been accessed via rcu-walk path walk (basically, if the file can have had a path name in the vfs namespace).

Even though i\_dentry and i\_rcu share storage in a union, we will initialize the former in inode\_init\_always(), so just leave it alone in the callback.  It used to be necessary to clean it there, but not anymore (starting at 3.2).

\---

<strong>recommended</strong>

vfs now tries to do path walking in "rcu-walk mode", which avoids atomic operations and scalability hazards on dentries and inodes (see [Documentation/filesystems/path-lookup.txt](/kernel/internals/filesystems/path-lookup-legacy.md)). d\_hash and d\_compare changes (above) are examples of the changes required to support this. For more complex filesystem callbacks, the vfs drops out of rcu-walk mode before the fs call, so no changes are required to the filesystem. However, this is costly and loses the benefits of rcu-walk mode. We will begin to add filesystem callbacks that are rcu-walk aware, shown below. Filesystems should take advantage of this where possible.

\---

<strong>mandatory</strong>

d\_revalidate is a callback that is made on every path element (if the filesystem provides it), which requires dropping out of rcu-walk mode. This may now be called in rcu-walk mode (nd-&gt;flags &amp; LOOKUP\_RCU). -ECHILD should be returned if the filesystem cannot handle rcu-walk. See [Documentation/filesystems/vfs.rst](/kernel/internals/filesystems/vfs.md) for more details.

permission is an inode permission check that is called on many or all directory inodes on the way down a path walk (to check for exec permission). It must now be rcu-walk aware (mask &amp; MAY\_NOT\_BLOCK).  See [Documentation/filesystems/vfs.rst](/kernel/internals/filesystems/vfs.md) for more details.

\---

<strong>mandatory</strong>

In -&gt;fallocate() you must check the mode option passed in.  If your filesystem does not support hole punching (deallocating space in the middle of a file) you must return -EOPNOTSUPP if FALLOC\_FL\_PUNCH\_HOLE is set in mode. Currently you can only have FALLOC\_FL\_PUNCH\_HOLE with FALLOC\_FL\_KEEP\_SIZE set, so the i\_size should not change when hole punching, even when puching the end of a file off.

\---

<strong>mandatory</strong>

-&gt;get\_sb() and -&gt;mount() are gone. Switch to using the new mount API. See [Documentation/filesystems/mount\_api.rst](/kernel/internals/filesystems/mount-api.md) for more details.

\---

<strong>mandatory</strong>

-&gt;permission() and generic\_permission()have lost flags argument; instead of passing IPERM\_FLAG\_RCU we add MAY\_NOT\_BLOCK into mask.

generic\_permission() has also lost the check\_acl argument; ACL checking has been taken to VFS and filesystems need to provide a non-NULL -&gt;i\_op-&gt;get\_inode\_acl to read an ACL from disk.

\---

<strong>mandatory</strong>

If you implement your own -&gt;llseek() you must handle SEEK\_HOLE and SEEK\_DATA.  You can handle this by returning -EINVAL, but it would be nicer to support it in some way.  The generic handler assumes that the entire file is data and there is a virtual hole at the end of the file.  So if the provided offset is less than i\_size and SEEK\_DATA is specified, return the same offset. If the above is true for the offset and you are given SEEK\_HOLE, return the end of the file.  If the offset is i\_size or greater return -ENXIO in either case.

<strong>mandatory</strong>

If you have your own -&gt;fsync() you must make sure to call filemap\_write\_and\_wait\_range() so that all dirty pages are synced out properly. You must also keep in mind that -&gt;fsync() is not called with i\_mutex held anymore, so if you require i\_mutex locking you must make sure to take it and release it yourself.

\---

<strong>mandatory</strong>

d\_alloc\_root() is gone, along with a lot of bugs caused by code misusing it.  Replacement: d\_make\_root(inode).  On success d\_make\_root(inode) allocates and returns a new dentry instantiated with the passed in inode. On failure NULL is returned and the passed in inode is dropped so the reference to inode is consumed in all cases and failure handling need not do any cleanup for the inode.  If d\_make\_root(inode) is passed a NULL inode it returns NULL and also requires no further error handling. Typical usage is:



```text
inode = foofs_new_inode(....);
s->s_root = d_make_root(inode);
if (!s->s_root)
        /* Nothing needed for the inode cleanup */
        return -ENOMEM;
...
```

\---

<strong>mandatory</strong>

The witch is dead\!  Well, 2/3 of it, anyway.  -&gt;d\_revalidate() and -&gt;lookup() do <em>not</em> take struct nameidata anymore; just the flags.

\---

<strong>mandatory</strong>

-&gt;create() doesn't take `struct nameidata *`; unlike the previous two, it gets "is it an O\_EXCL or equivalent?" boolean argument.  Note that local filesystems can ignore this argument - they are guaranteed that the object doesn't exist.  It's remote/distributed ones that might care...

\---

<strong>mandatory</strong>

FS\_REVAL\_DOT is gone; if you used to have it, add -&gt;d\_weak\_revalidate() in your dentry operations instead.

\---

<strong>mandatory</strong>

vfs\_readdir() is gone; switch to iterate\_dir() instead

\---

<strong>mandatory</strong>

-&gt;readdir() is gone now; switch to -&gt;iterate\_shared()

<strong>mandatory</strong>

vfs\_follow\_link has been removed.  Filesystems must use nd\_set\_link from -&gt;follow\_link for normal symlinks, or nd\_jump\_link for magic /proc/&lt;pid&gt; style links.

\---

<strong>mandatory</strong>

iget5\_locked()/ilookup5()/ilookup5\_nowait() test() callback used to be called with both -&gt;i\_lock and inode\_hash\_lock held; the former is <em>not</em> taken anymore, so verify that your callbacks do not rely on it (none of the in-tree instances did).  inode\_hash\_lock is still held, of course, so they are still serialized wrt removal from inode hash, as well as wrt set() callback of iget5\_locked().

\---

<strong>mandatory</strong>

d\_materialise\_unique() is gone; d\_splice\_alias() does everything you need now.  Remember that they have opposite orders of arguments ;-/

\---

<strong>mandatory</strong>

f\_dentry is gone; use f\_path.dentry, or, better yet, see if you can avoid it entirely.

\---

<strong>mandatory</strong>

never call -&gt;read() and -&gt;write() directly; use \_\_vfs\_\{read,write\} or wrappers; instead of checking for -&gt;write or -&gt;read being NULL, look for FMODE\_CAN\_\{WRITE,READ\} in file-&gt;f\_mode.

\---

<strong>mandatory</strong>

do \_not\_ use new\_sync\_\{read,write\} for -&gt;read/-&gt;write; leave it NULL instead.

\---

- **<strong>mandatory</strong>**

  -&gt;aio\_read/-&gt;aio\_write are gone.  Use -&gt;read\_iter/-&gt;write\_iter.

\---

<strong>recommended</strong>

for embedded ("fast") symlinks just set inode-&gt;i\_link to wherever the symlink body is and use simple\_follow\_link() as -&gt;follow\_link().

\---

<strong>mandatory</strong>

calling conventions for -&gt;follow\_link() have changed.  Instead of returning cookie and using nd\_set\_link() to store the body to traverse, we return the body to traverse and store the cookie using explicit void \*\* argument. nameidata isn't passed at all - nd\_jump\_link() doesn't need it and nd\_\[gs\]et\_link() is gone.

\---

<strong>mandatory</strong>

calling conventions for -&gt;put\_link() have changed.  It gets inode instead of dentry,  it does not get nameidata at all and it gets called only when cookie is non-NULL.  Note that link body isn't available anymore, so if you need it, store it as cookie.

\---

<strong>mandatory</strong>

any symlink that might use page\_follow\_link\_light/page\_put\_link() must have inode\_nohighmem(inode) called before anything might start playing with its pagecache.  No highmem pages should end up in the pagecache of such symlinks.  That includes any preseeding that might be done during symlink creation.  page\_symlink() will honour the mapping gfp flags, so once you've done inode\_nohighmem() it's safe to use, but if you allocate and insert the page manually, make sure to use the right gfp flags.

\---

<strong>mandatory</strong>

-&gt;follow\_link() is replaced with -&gt;get\_link(); same API, except that

> - -&gt;get\_link() gets inode as a separate argument
>
> - -&gt;get\_link() may be called in RCU mode - in that case NULL dentry is passed

\---

<strong>mandatory</strong>

-&gt;get\_link() gets struct delayed\_call `*done` now, and should do set\_delayed\_call() where it used to set `*cookie`.

-&gt;put\_link() is gone - just give the destructor to set\_delayed\_call() in -&gt;get\_link().

\---

<strong>mandatory</strong>

-&gt;getxattr() and xattr\_handler.get() get dentry and inode passed separately. dentry might be yet to be attached to inode, so do \_not\_ use its -&gt;d\_inode in the instances.  Rationale: \!@\#\!@\# security\_d\_instantiate() needs to be called before we attach dentry to inode.

\---

<strong>mandatory</strong>

symlinks are no longer the only inodes that do <em>not</em> have i\_bdev/i\_cdev/ i\_pipe/i\_link union zeroed out at inode eviction.  As the result, you can't assume that non-NULL value in -&gt;i\_nlink at -&gt;destroy\_inode() implies that it's a symlink.  Checking -&gt;i\_mode is really needed now.  In-tree we had to fix shmem\_destroy\_callback() that used to take that kind of shortcut; watch out, since that shortcut is no longer valid.

\---

<strong>mandatory</strong>

-&gt;i\_mutex is replaced with -&gt;i\_rwsem now.  inode\_lock() et.al. work as they used to - they just take it exclusive.  However, -&gt;lookup() may be called with parent locked shared.  Its instances must not

> - use d\_instantiate) and d\_rehash() separately - use d\_add() or d\_splice\_alias() instead.
>
> - use d\_rehash() alone - call d\_add(new\_dentry, NULL) instead.
>
> - in the unlikely case when (read-only) access to filesystem data structures needs exclusion for some reason, arrange it yourself.  None of the in-tree filesystems needed that.
>
> - rely on -&gt;d\_parent and -&gt;d\_name not changing after dentry has been fed to d\_add() or d\_splice\_alias().  Again, none of the in-tree instances relied upon that.

We are guaranteed that lookups of the same name in the same directory will not happen in parallel ("same" in the sense of your -&gt;d\_compare()). Lookups on different names in the same directory can and do happen in parallel now.

\---

<strong>mandatory</strong>

-&gt;iterate\_shared() is added. Exclusion on struct file level is still provided (as well as that between it and lseek on the same struct file), but if your directory has been opened several times, you can get these called in parallel. Exclusion between that method and all directory-modifying ones is still provided, of course.

If you have any per-inode or per-dentry in-core data structures modified by -&gt;iterate\_shared(), you might need something to serialize the access to them.  If you do dcache pre-seeding, you'll need to switch to d\_alloc\_parallel() for that; look for in-tree examples.

\---

<strong>mandatory</strong>

-&gt;atomic\_open() calls without O\_CREAT may happen in parallel.

\---

<strong>mandatory</strong>

-&gt;setxattr() and xattr\_handler.set() get dentry and inode passed separately. The xattr\_handler.set() gets passed the user namespace of the mount the inode is seen from so filesystems can idmap the i\_uid and i\_gid accordingly. dentry might be yet to be attached to inode, so do \_not\_ use its -&gt;d\_inode in the instances.  Rationale: \!@\#\!@\# security\_d\_instantiate() needs to be called before we attach dentry to inode and \!@\#\!@\#\#\!@$\!$\#\!@\#$\!@$\!@$ smack -&gt;d\_instantiate() uses not just -&gt;getxattr() but -&gt;setxattr() as well.

\---

<strong>mandatory</strong>

-&gt;d\_compare() doesn't get parent as a separate argument anymore.  If you used it for finding the struct super\_block involved, dentry-&gt;d\_sb will work just as well; if it's something more complicated, use dentry-&gt;d\_parent. Just be careful not to assume that fetching it more than once will yield the same value - in RCU mode it could change under you.

\---

<strong>mandatory</strong>

-&gt;rename() has an added flags argument.  Any flags not handled by the filesystem should result in EINVAL being returned.

\---

<strong>recommended</strong>

-&gt;readlink is optional for symlinks.  Don't set, unless filesystem needs to fake something for readlink(2).

\---

<strong>mandatory</strong>

-&gt;getattr() is now passed a struct path rather than a vfsmount and dentry separately, and it now has request\_mask and query\_flags arguments to specify the fields and sync type requested by statx.  Filesystems not supporting any statx-specific features may ignore the new arguments.

\---

<strong>mandatory</strong>

-&gt;atomic\_open() calling conventions have changed.  Gone is `int *opened`, along with FILE\_OPENED/FILE\_CREATED.  In place of those we have FMODE\_OPENED/FMODE\_CREATED, set in file-&gt;f\_mode.  Additionally, return value for 'called finish\_no\_open(), open it yourself' case has become 0, not 1.  Since finish\_no\_open() itself is returning 0 now, that part does not need any changes in -&gt;atomic\_open() instances.

\---

<strong>mandatory</strong>

alloc\_file() has become static now; two wrappers are to be used instead. alloc\_file\_pseudo(inode, vfsmount, name, flags, ops) is for the cases when dentry needs to be created; that's the majority of old alloc\_file() users.  Calling conventions: on success a reference to new struct file is returned and callers reference to inode is subsumed by that.  On failure, ERR\_PTR() is returned and no caller's references are affected, so the caller needs to drop the inode reference it held. alloc\_file\_clone(file, flags, ops) does not affect any caller's references. On success you get a new struct file sharing the mount/dentry with the original, on failure - ERR\_PTR().

\---

<strong>mandatory</strong>

-&gt;clone\_file\_range() and -&gt;dedupe\_file\_range have been replaced with -&gt;remap\_file\_range().  See [Documentation/filesystems/vfs.rst](/kernel/internals/filesystems/vfs.md) for more information.

\---

<strong>recommended</strong>

-&gt;lookup() instances doing an equivalent of:



```text
if (IS_ERR(inode))
        return ERR_CAST(inode);
return d_splice_alias(inode, dentry);
```

don't need to bother with the check - d\_splice\_alias() will do the right thing when given ERR\_PTR(...) as inode.  Moreover, passing NULL inode to d\_splice\_alias() will also do the right thing (equivalent of d\_add(dentry, NULL); return NULL;), so that kind of special cases also doesn't need a separate treatment.

\---

<strong>strongly recommended</strong>

take the RCU-delayed parts of -&gt;destroy\_inode() into a new method - -&gt;free\_inode().  If -&gt;destroy\_inode() becomes empty - all the better, just get rid of it.  Synchronous work (e.g. the stuff that can't be done from an RCU callback, or any WARN\_ON() where we want the stack trace) <em>might</em> be movable to -&gt;evict\_inode(); however, that goes only for the things that are not needed to balance something done by -&gt;alloc\_inode().  IOW, if it's cleaning up the stuff that might have accumulated over the life of in-core inode, -&gt;evict\_inode() might be a fit.

Rules for inode destruction:

> - if -&gt;destroy\_inode() is non-NULL, it gets called
>
> - if -&gt;free\_inode() is non-NULL, it gets scheduled by call\_rcu()
>
> - combination of NULL -&gt;destroy\_inode and NULL -&gt;free\_inode is treated as NULL/free\_inode\_nonrcu, to preserve the compatibility.

Note that the callback (be it via -&gt;free\_inode() or explicit call\_rcu() in -&gt;destroy\_inode()) is <em>NOT</em> ordered wrt superblock destruction; as the matter of fact, the superblock and all associated structures might be already gone.  The filesystem driver is guaranteed to be still there, but that's it.  Freeing memory in the callback is fine; doing more than that is possible, but requires a lot of care and is best avoided.

\---

<strong>mandatory</strong>

DCACHE\_RCUACCESS is gone; having an RCU delay on dentry freeing is the default.  DCACHE\_NORCU opts out, and only d\_alloc\_pseudo() has any business doing so.

\---

<strong>mandatory</strong>

d\_alloc\_pseudo() is internal-only; uses outside of alloc\_file\_pseudo() are very suspect (and won't work in modules).  Such uses are very likely to be misspelled d\_alloc\_anon().

\---

<strong>mandatory</strong>

\[should've been added in 2016\] stale comment in finish\_open() notwithstanding, failure exits in -&gt;atomic\_open() instances should <em>NOT</em> fput() the file, no matter what.  Everything is handled by the caller.

\---

<strong>mandatory</strong>

clone\_private\_mount() returns a longterm mount now, so the proper destructor of its result is kern\_unmount() or kern\_unmount\_array().

\---

<strong>mandatory</strong>

zero-length bvec segments are disallowed, they must be filtered out before passed on to an iterator.

\---

<strong>mandatory</strong>

For bvec based itererators bio\_iov\_iter\_get\_pages() now doesn't copy bvecs but uses the one provided. Anyone issuing kiocb-I/O should ensure that the bvec and page references stay until I/O has completed, i.e. until -&gt;ki\_complete() has been called or returned with non -EIOCBQUEUED code.

\---

<strong>mandatory</strong>

mnt\_want\_write\_file() can now only be paired with mnt\_drop\_write\_file(), whereas previously it could be paired with mnt\_drop\_write() as well.

\---

<strong>mandatory</strong>

iov\_iter\_copy\_from\_user\_atomic() is gone; use copy\_page\_from\_iter\_atomic(). The difference is copy\_page\_from\_iter\_atomic() advances the iterator and you don't need iov\_iter\_advance() after it.  However, if you decide to use only a part of obtained data, you should do iov\_iter\_revert().

\---

<strong>mandatory</strong>

Calling conventions for file\_open\_root() changed; now it takes struct path \* instead of passing mount and dentry separately.  For callers that used to pass &lt;mnt, mnt-&gt;mnt\_root&gt; pair (i.e. the root of given mount), a new helper is provided - file\_open\_root\_mnt().  In-tree users adjusted.

\---

<strong>mandatory</strong>

no\_llseek is gone; don't set .llseek to that - just leave it NULL instead. Checks for "does that file have llseek(2), or should it fail with ESPIPE" should be done by looking at FMODE\_LSEEK in file-&gt;f\_mode.

\---

<em>mandatory</em>

filldir\_t (readdir callbacks) calling conventions have changed.  Instead of returning 0 or -E... it returns bool now.  false means "no more" (as -E... used to) and true - "keep going" (as 0 in old calling conventions).  Rationale: callers never looked at specific -E... values anyway. -&gt; iterate\_shared() instances require no changes at all, all filldir\_t ones in the tree converted.

\---

<strong>mandatory</strong>

Calling conventions for -&gt;tmpfile() have changed.  It now takes a struct file pointer instead of struct dentry pointer.  d\_tmpfile() is similarly changed to simplify callers.  The passed file is in a non-open state and on success must be opened before returning (e.g. by calling finish\_open\_simple()).

\---

<strong>mandatory</strong>

Calling convention for -&gt;huge\_fault has changed.  It now takes a page order instead of an enum page\_entry\_size, and it may be called without the mmap\_lock held.  All in-tree users have been audited and do not seem to depend on the mmap\_lock being held, but out of tree users should verify for themselves.  If they do need it, they can return VM\_FAULT\_RETRY to be called with the mmap\_lock held.

\---

<strong>mandatory</strong>

The order of opening block devices and matching or creating superblocks has changed.

The old logic opened block devices first and then tried to find a suitable superblock to reuse based on the block device pointer.

The new logic tries to find a suitable superblock first based on the device number, and opening the block device afterwards.

Since opening block devices cannot happen under s\_umount because of lock ordering requirements s\_umount is now dropped while opening block devices and reacquired before calling fill\_super().

In the old logic concurrent mounters would find the superblock on the list of superblocks for the filesystem type. Since the first opener of the block device would hold s\_umount they would wait until the superblock became either born or was discarded due to initialization failure.

Since the new logic drops s\_umount concurrent mounters could grab s\_umount and would spin. Instead they are now made to wait using an explicit wait-wake mechanism without having to hold s\_umount.

\---

<strong>mandatory</strong>

The holder of a block device is now the superblock.

The holder of a block device used to be the file\_system\_type which wasn't particularly useful. It wasn't possible to go from block device to owning superblock without matching on the device pointer stored in the superblock. This mechanism would only work for a single device so the block layer couldn't find the owning superblock of any additional devices.

In the old mechanism reusing or creating a superblock for a racing mount(2) and umount(2) relied on the file\_system\_type as the holder. This was severely underdocumented however:

1. Any concurrent mounter that managed to grab an active reference on an existing superblock was made to wait until the superblock either became ready or until the superblock was removed from the list of superblocks of the filesystem type. If the superblock is ready the caller would simple reuse it.

2. If the mounter came after deactivate\_locked\_super() but before the superblock had been removed from the list of superblocks of the filesystem type the mounter would wait until the superblock was shutdown, reuse the block device and allocate a new superblock.

3. If the mounter came after deactivate\_locked\_super() and after the superblock had been removed from the list of superblocks of the filesystem type the mounter would reuse the block device and allocate a new superblock (the bd\_holder point may still be set to the filesystem type).

Because the holder of the block device was the file\_system\_type any concurrent mounter could open the block devices of any superblock of the same file\_system\_type without risking seeing EBUSY because the block device was still in use by another superblock.

Making the superblock the owner of the block device changes this as the holder is now a unique superblock and thus block devices associated with it cannot be reused by concurrent mounters. So a concurrent mounter in (2) could suddenly see EBUSY when trying to open a block device whose holder was a different superblock.

The new logic thus waits until the superblock and the devices are shutdown in -&gt;kill\_sb(). Removal of the superblock from the list of superblocks of the filesystem type is now moved to a later point when the devices are closed:

1. Any concurrent mounter managing to grab an active reference on an existing superblock is made to wait until the superblock is either ready or until the superblock and all devices are shutdown in -&gt;kill\_sb(). If the superblock is ready the caller will simply reuse it.

2. If the mounter comes after deactivate\_locked\_super() but before the superblock has been removed from the list of superblocks of the filesystem type the mounter is made to wait until the superblock and the devices are shut down in -&gt;kill\_sb() and the superblock is removed from the list of superblocks of the filesystem type. The mounter will allocate a new superblock and grab ownership of the block device (the bd\_holder pointer of the block device will be set to the newly allocated superblock).

3. This case is now collapsed into (2) as the superblock is left on the list of superblocks of the filesystem type until all devices are shutdown in -&gt;kill\_sb(). In other words, if the superblock isn't on the list of superblock of the filesystem type anymore then it has given up ownership of all associated block devices (the bd\_holder pointer is NULL).

As this is a VFS level change it has no practical consequences for filesystems other than that all of them must use one of the provided kill\_litter\_super(), kill\_anon\_super(), or kill\_block\_super() helpers.

\---

<strong>mandatory</strong>

Lock ordering has been changed so that s\_umount ranks above open\_mutex again. All places where s\_umount was taken under open\_mutex have been fixed up.

\---

<strong>mandatory</strong>

export\_operations -&gt;encode\_fh() no longer has a default implementation to encode FILEID\_INO32\_GEN\* file handles. Filesystems that used the default implementation may use the generic helper generic\_encode\_ino32\_fh() explicitly.

\---

<strong>mandatory</strong>

If -&gt;rename() update of .. on cross-directory move needs an exclusion with directory modifications, do <em>not</em> lock the subdirectory in question in your -&gt;rename() - it's done by the caller now \[that item should've been added in 28eceeda130f "fs: Lock moved directories"\].

\---

<strong>mandatory</strong>

On same-directory -&gt;rename() the (tautological) update of .. is not protected by any locks; just don't do it if the old parent is the same as the new one. We really can't lock two subdirectories in same-directory rename - not without deadlocks.

\---

<strong>mandatory</strong>

lock\_rename() and lock\_rename\_child() may fail in cross-directory case, if their arguments do not have a common ancestor.  In that case ERR\_PTR(-EXDEV) is returned, with no locks taken.  In-tree users updated; out-of-tree ones would need to do so.

\---

<strong>mandatory</strong>

The list of children anchored in parent dentry got turned into hlist now. Field names got changed (-&gt;d\_children/-&gt;d\_sib instead of -&gt;d\_subdirs/-&gt;d\_child for anchor/entries resp.), so any affected places will be immediately caught by compiler.

\---

<strong>mandatory</strong>

-&gt;d\_delete() instances are now called for dentries with -&gt;d\_lock held and refcount equal to 0.  They are not permitted to drop/regain -&gt;d\_lock. None of in-tree instances did anything of that sort.  Make sure yours do not...

\---

<strong>mandatory</strong>

-&gt;d\_prune() instances are now called without -&gt;d\_lock held on the parent. -&gt;d\_lock on dentry itself is still held; if you need per-parent exclusions (none of the in-tree instances did), use your own spinlock.

-&gt;d\_iput() and -&gt;d\_release() are called with victim dentry still in the list of parent's children.  It is still unhashed, marked killed, etc., just not removed from parent's -&gt;d\_children yet.

Anyone iterating through the list of children needs to be aware of the half-killed dentries that might be seen there; taking -&gt;d\_lock on those will see them negative, unhashed and with negative refcount, which means that most of the in-kernel users would've done the right thing anyway without any adjustment.

\---

<strong>recommended</strong>

Block device freezing and thawing have been moved to holder operations.

Before this change, get\_active\_super() would only be able to find the superblock of the main block device, i.e., the one stored in sb-&gt;s\_bdev. Block device freezing now works for any block device owned by a given superblock, not just the main block device. The get\_active\_super() helper and bd\_fsfreeze\_sb pointer are gone.

\---

<strong>mandatory</strong>

set\_blocksize() takes opened struct file instead of struct block\_device now and it <em>must</em> be opened exclusive.

\---

<strong>mandatory</strong>

-&gt;d\_revalidate() gets two extra arguments - inode of parent directory and name our dentry is expected to have.  Both are stable (dir is pinned in non-RCU case and will stay around during the call in RCU case, and name is guaranteed to stay unchanging).  Your instance doesn't have to use either, but it often helps to avoid a lot of painful boilerplate. Note that while name-&gt;name is stable and NUL-terminated, it may (and often will) have name-&gt;name\[name-&gt;len\] equal to '/' rather than '0' - in normal case it points into the pathname being looked up. NOTE: if you need something like full path from the root of filesystem, you are still on your own - this assists with simple cases, but it's not magic.

\---

<strong>recommended</strong>

kern\_path\_locked() and user\_path\_locked() no longer return a negative dentry so this doesn't need to be checked.  If the name cannot be found, ERR\_PTR(-ENOENT) is returned.

\---

<strong>recommended</strong>

lookup\_one\_qstr\_excl() is changed to return errors in more cases, so these conditions don't require explicit checks:

> - if LOOKUP\_CREATE is NOT given, then the dentry won't be negative, ERR\_PTR(-ENOENT) is returned instead
>
> - if LOOKUP\_EXCL IS given, then the dentry won't be positive, ERR\_PTR(-EEXIST) is rreturned instread

LOOKUP\_EXCL now means "target must not exist".  It can be combined with LOOK\_CREATE or LOOKUP\_RENAME\_TARGET.

\---

<strong>mandatory</strong> invalidate\_inodes() is gone use evict\_inodes() instead.

\---

<strong>mandatory</strong>

-&gt;mkdir() now returns a dentry.  If the created inode is found to already be in cache and have a dentry (often IS\_ROOT()), it will need to be spliced into the given name in place of the given dentry. That dentry now needs to be returned.  If the original dentry is used, NULL should be returned.  Any error should be returned with ERR\_PTR().

In general, filesystems which use d\_instantiate\_new() to install the new inode can safely return NULL.  Filesystems which may not have an I\_NEW inode should use d\_drop();d\_splice\_alias() and return the result of the latter.

If a positive dentry cannot be returned for some reason, in-kernel clients such as cachefiles, nfsd, smb/server may not perform ideally but will fail-safe.

\---

\*\* mandatory\*\*

lookup\_one(), lookup\_one\_unlocked(), lookup\_one\_positive\_unlocked() now take a qstr instead of a name and len.  These, not the "one\_len" versions, should be used whenever accessing a filesystem from outside that filesysmtem, through a mount point - which will have a mnt\_idmap.

\---

\*\* mandatory\*\*

Functions try\_lookup\_one\_len(), lookup\_one\_len(), lookup\_one\_len\_unlocked() and lookup\_positive\_unlocked() have been renamed to try\_lookup\_noperm(), lookup\_noperm(), lookup\_noperm\_unlocked(), lookup\_noperm\_positive\_unlocked().  They now take a qstr instead of separate name and length.  QSTR() can be used when strlen() is needed for the length.

These function no longer do any permission checking - they previously checked that the caller has 'X' permission on the parent.  They must ONLY be used internally by a filesystem on itself when it knows that permissions are irrelevant or in a context where permission checks have already been performed such as after vfs\_path\_parent\_lookup()

\---

\*\* mandatory\*\*

d\_hash\_and\_lookup() is no longer exported or available outside the VFS. Use try\_lookup\_noperm() instead.  This adds name validation and takes arguments in the opposite order but is otherwise identical.

Using try\_lookup\_noperm() will require linux/namei.h to be included.

\---

<strong>mandatory</strong>

Calling conventions for -&gt;d\_automount() have changed; we should <em>not</em> grab an extra reference to new mount - it should be returned with refcount 1.

\---

collect\_mounts()/drop\_collected\_mounts()/iterate\_mounts() are gone now. Replacement is collect\_paths()/drop\_collected\_path(), with no special iterator needed.  Instead of a cloned mount tree, the new interface returns an array of struct path, one for each mount collect\_mounts() would've created.  These struct path point to locations in the caller's namespace that would be roots of the cloned mounts.

\---

<strong>mandatory</strong>

If your filesystem sets the default dentry\_operations, use set\_default\_d\_op() rather than manually setting sb-&gt;s\_d\_op.

\---

<strong>mandatory</strong>

d\_set\_d\_op() is no longer exported (or public, for that matter); \_if\_ your filesystem really needed that, make use of d\_splice\_alias\_ops() to have them set.  Better yet, think hard whether you need different -&gt;d\_op for different dentries - if not, just use set\_default\_d\_op() at mount time and be done with that.  Currently procfs is the only thing that really needs -&gt;d\_op varying between dentries.

\---

<strong>highly recommended</strong>

The file operations mmap() callback is deprecated in favour of mmap\_prepare(). This passes a pointer to a vm\_area\_desc to the callback rather than a VMA, as the VMA at this stage is not yet valid.

The vm\_area\_desc provides the minimum required information for a filesystem to initialise state upon memory mapping of a file-backed region, and output parameters for the file system to set this state.

In nearly all cases, this is all that is required for a filesystem. However, if a filesystem needs to perform an operation such a pre-population of page tables, then that action can be specified in the vm\_area\_desc-&gt;action field, which can be configured using the mmap\_action\_\*() helpers.

\---

<strong>mandatory</strong>

Several functions are renamed:

- kern\_path\_locked -&gt; start\_removing\_path

- kern\_path\_create -&gt; start\_creating\_path

- user\_path\_create -&gt; start\_creating\_user\_path

- user\_path\_locked\_at -&gt; start\_removing\_user\_path\_at

- done\_path\_create -&gt; end\_creating\_path

\---

<strong>mandatory</strong>

Calling conventions for vfs\_parse\_fs\_string() have changed; it does <em>not</em> take length anymore (value ? strlen(value) : 0 is used).  If you want a different length, use

> vfs\_parse\_fs\_qstr(fc, key, &amp;QSTR\_LEN(value, len))

instead.

\---

<strong>mandatory</strong>

vfs\_mkdir() now returns a dentry - the one returned by -&gt;mkdir().  If that dentry is different from the dentry passed in, including if it is an IS\_ERR() dentry pointer, the original dentry is dput().

When vfs\_mkdir() returns an error, and so both dputs() the original dentry and doesn't provide a replacement, it also unlocks the parent. Consequently the return value from vfs\_mkdir() can be passed to end\_creating() and the parent will be unlocked precisely when necessary.

\---

<strong>mandatory</strong>

kill\_litter\_super() is gone; convert to DCACHE\_PERSISTENT use (as all in-tree filesystems have done).

\---

<strong>mandatory</strong>

The -&gt;setlease() file\_operation must now be explicitly set in order to provide support for leases. When set to NULL, the kernel will now return -EINVAL to attempts to set a lease. Filesystems that wish to use the kernel-internal lease implementation should set it to generic\_setlease().

\---

<strong>mandatory</strong>

fs/namei.c primitives that consume filesystem references (do\_renameat2(), do\_linkat(), do\_symlinkat(), do\_mkdirat(), do\_mknodat(), do\_unlinkat() and do\_rmdir()) are gone; they are replaced with non-consuming analogues (filename\_renameat2(), etc.) Callers are adjusted - responsibility for dropping the filenames belongs to them now.

\---

<strong>mandatory</strong>

readlink\_copy() now requires link length as the 4th argument. Said length needs to match what strlen() would return if it was ran on the string.

However, if the string is freely accessible for the duration of inode's lifetime, consider using inode\_set\_cached\_link() instead.

---

# The /proc Filesystem

_Peios Kernel / Internals / Filesystems_

> Process information, native access checks and retained procfs interfaces.

<a id="rst-the-proc-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


<table>
<tbody>
<tr>
<td>


/proc/sys

</td>
<td>


Terrehon Bowden &lt;[terrehon@pacbell.net](<mailto:terrehon@pacbell.net>)&gt;, Bodo Bauer &lt;[bb@ricochet.net](<mailto:bb@ricochet.net>)&gt;

</td>
<td>


October 7 1999

</td>
</tr>
<tr>
<td>


2.4.x update

</td>
<td>


Jorge Nerin &lt;[comandante@zaralinux.com](<mailto:comandante@zaralinux.com>)&gt;

</td>
<td>


November 14 2000

</td>
</tr>
<tr>
<td>


move /proc/sys

</td>
<td>


Shen Feng &lt;[shen@cn.fujitsu.com](<mailto:shen@cn.fujitsu.com>)&gt;

</td>
<td>


April 1 2009

</td>
</tr>
<tr>
<td>


fixes/update part 1.1

</td>
<td>


Stefani Seibold &lt;[stefani@seibold.net](<mailto:stefani@seibold.net>)&gt;

</td>
<td>


June 9 2009

</td>
</tr>
</tbody>
</table>

<!-- Table of Contents

0     Preface
0.1   Introduction/Credits
0.2   Legal Stuff

1     Collecting System Information
1.1   Process-Specific Subdirectories
1.2   Kernel data
1.3   IDE devices in /proc/ide
1.4   Networking info in /proc/net
1.5   SCSI info
1.6   Parallel port info in /proc/parport
1.7   TTY info in /proc/tty
1.8   Miscellaneous kernel statistics in /proc/stat
1.9   Ext4 file system parameters

2     Modifying System Parameters

3     Per-Process Parameters
3.1   /proc/<pid>/oom_adj & /proc/<pid>/oom_score_adj - Adjust the oom-killer
                                                              score
3.2   /proc/<pid>/oom_score - Display current oom-killer score
3.3   /proc/<pid>/io - Display the IO accounting fields
3.4   /proc/<pid>/coredump_filter - Core dump filtering settings
3.5   /proc/<pid>/mountinfo - Information about mounts
3.6   /proc/<pid>/comm  & /proc/<pid>/task/<tid>/comm
3.7   /proc/<pid>/task/<tid>/children - Information about task children
3.8   /proc/<pid>/fdinfo/<fd> - Information about opened file
3.9   /proc/<pid>/map_files - Information about memory mapped files
3.10  /proc/<pid>/timerslack_ns - Task timerslack value
3.11  /proc/<pid>/patch_state - Livepatch patch operation state
3.12  /proc/<pid>/arch_status - Task architecture specific information
3.13  /proc/<pid>/fd - List of symlinks to open files
3.14  /proc/<pid>/ksm_stat - Information about the process's ksm status.

4     Configuring procfs
4.1   Mount options

5     Filesystem behavior -->

<a id="rst-preface"></a>

## Preface

<a id="rst-introduction-credits"></a>

### 0.1 Introduction/Credits

We'd like  to  thank Alan Cox, Rik van Riel, and Alexey Kuznetsov and a lot of other people for help compiling this documentation. We'd also like to extend a special thank  you to Andi Kleen for documentation, which we relied on heavily to create  this  document,  as well as the additional information he provided. Thanks to  everybody  else  who contributed source or docs to the Linux kernel and helped create a great piece of software... :)

The   latest   version    of   this   document   is    available   online   at [https://www.kernel.org/doc/html/latest/filesystems/proc.html](<https://www.kernel.org/doc/html/latest/filesystems/proc.html>)

<a id="rst-legal-stuff"></a>

### 0.2 Legal Stuff

We don't  guarantee  the  correctness  of this document, and if you come to us complaining about  how  you  screwed  up  your  system  because  of  incorrect documentation, we won't feel responsible...

<a id="rst-chapter-1-collecting-system-information"></a>

## Chapter 1: Collecting System Information

<a id="rst-in-this-chapter"></a>

### In This Chapter

- Investigating  the  properties  of  the  pseudo  file  system  /proc and its ability to provide information on the running Linux system

- Examining /proc's structure

- Uncovering  various  information  about the kernel and the processes running on the system

---

The proc  file  system acts as an interface to internal data structures in the kernel. It  can  be  used to obtain information about the system and to change certain kernel parameters at runtime (sysctl).

First, we'll  take  a  look  at the read-only parts of /proc. In Chapter 2, we show you how you can use /proc/sys to change settings.

<a id="rst-process-specific-subdirectories"></a>

### 1.1 Process-Specific Subdirectories

The directory  /proc  contains  (among other things) one subdirectory for each process running on the system, which is named after the process ID (PID).

The link  'self'  points to  the process reading the file system. Each process subdirectory has the entries listed in Table 1-1.

Peios checks cross-process proc access using native process rights and PIP dominance. Basic metadata such as `stat`, `statm` and `comm` requires `PROCESS_QUERY_LIMITED_INFORMATION`; `status`, `cmdline`, `io` and `limits` require `PROCESS_QUERY_INFORMATION`. Memory-oriented entries such as `maps`, `environ` and `pagemap` use process-read authorization. Read-only `/proc/PID/mem` requires `PROCESS_VM_READ`; writable access requires `PROCESS_VM_WRITE`. There is no `CAP_PERFMON` fallback after a KACS denial. Equal UIDs do not grant access. Same-process access has explicit exceptions, while individual entries can impose additional checks.

Peios also exposes `/proc/PID/token`, `/proc/PID/task/TID/token` and `/proc/PID/psb` for native security state. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the access model. Proc visibility settings such as `hidepid` do not bypass these native checks.

Note that an open file descriptor to /proc/&lt;pid&gt; or to any of its contained files or subdirectories does not prevent &lt;pid&gt; being reused for some other process in the event that &lt;pid&gt; exits. Operations on open /proc/&lt;pid&gt; file descriptors corresponding to dead processes never act on any new process that the kernel may, through chance, have also assigned the process ID &lt;pid&gt;. Instead, operations on these FDs usually fail with ESRCH.


<table>
<caption>Table 1-1: Process specific entries in /proc</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


clear_refs

</td>
<td>


Clears page referenced bits shown in smaps output

</td>
</tr>
<tr>
<td>


cmdline

</td>
<td>


Command line arguments

</td>
</tr>
<tr>
<td>


cpu

</td>
<td>


Current and last cpu in which it was executed   (2.4)(smp)

</td>
</tr>
<tr>
<td>


cwd

</td>
<td>


Link to the current working directory

</td>
</tr>
<tr>
<td>


environ

</td>
<td>


Values of environment variables

</td>
</tr>
<tr>
<td>


exe

</td>
<td>


Link to the executable of this process

</td>
</tr>
<tr>
<td>


fd

</td>
<td>


Directory, which contains all file descriptors

</td>
</tr>
<tr>
<td>


maps

</td>
<td>


Memory maps to executables and library files    (2.4)

</td>
</tr>
<tr>
<td>


mem

</td>
<td>


Memory held by this process

</td>
</tr>
<tr>
<td>


root

</td>
<td>


Link to the root directory of this process

</td>
</tr>
<tr>
<td>


stat

</td>
<td>


Process status

</td>
</tr>
<tr>
<td>


statm

</td>
<td>


Process memory status information

</td>
</tr>
<tr>
<td>


status

</td>
<td>


Process status in human readable form

</td>
</tr>
<tr>
<td>


wchan

</td>
<td>


Present with CONFIG_KALLSYMS=y: it shows the kernel function symbol the task is blocked in - or "0" if not blocked.

</td>
</tr>
<tr>
<td>


pagemap

</td>
<td>


Page table

</td>
</tr>
<tr>
<td>


stack

</td>
<td>


Report full stack trace, enable via CONFIG_STACKTRACE

</td>
</tr>
<tr>
<td>


smaps

</td>
<td>


An extension based on maps, showing the memory consumption of each mapping and flags associated with it

</td>
</tr>
<tr>
<td>


smaps_rollup

</td>
<td>


Accumulated smaps stats for all mappings of the process.  This can be derived from smaps, but is faster and more convenient

</td>
</tr>
<tr>
<td>


numa_maps

</td>
<td>


An extension based on maps, showing the memory locality and binding policy as well as mem usage (in pages) of each mapping.

</td>
</tr>
</tbody>
</table>

For example, to get the status information of a process, all you have to do is read the file /proc/PID/status:



```text
>cat /proc/self/status
Name:   cat
State:  R (running)
Tgid:   5452
Pid:    5452
PPid:   743
TracerPid:      0                                             (2.4)
Uid:    501     501     501     501
Gid:    100     100     100     100
FDSize: 256
Groups: 100 14 16
Kthread:    0
VmPeak:     5004 kB
VmSize:     5004 kB
VmLck:         0 kB
VmHWM:       476 kB
VmRSS:       476 kB
RssAnon:             352 kB
RssFile:             120 kB
RssShmem:              4 kB
VmData:      156 kB
VmStk:        88 kB
VmExe:        68 kB
VmLib:      1412 kB
VmPTE:        20 kb
VmSwap:        0 kB
HugetlbPages:          0 kB
CoreDumping:    0
THP_enabled:    1
Threads:        1
SigQ:   0/28578
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 00000000fffffeff
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
CapAmb: 0000000000000000
NoNewPrivs:     0
Seccomp:        0
Speculation_Store_Bypass:       thread vulnerable
SpeculationIndirectBranch:      conditional enabled
voluntary_ctxt_switches:        0
nonvoluntary_ctxt_switches:     1
```

This shows you nearly the same information you would get if you viewed it with the ps  command.  In  fact,  ps  uses  the  proc  file  system  to  obtain its information.  But you get a more detailed  view of the  process by reading the file /proc/PID/status. It fields are described in table 1-2.

The  statm  file  contains  more  detailed  information about the process memory usage. Its seven fields are explained in Table 1-3.  The stat file contains detailed information about the process itself.  Its fields are explained in Table 1-4.

(for SMP CONFIG users)

For making accounting scalable, RSS related information are handled in an asynchronous manner and the value may not be very precise. To see a precise snapshot of a moment, you can see /proc/&lt;pid&gt;/smaps file and scan page table. It's slow but very precise.


<table>
<caption>Table 1-2: Contents of the status fields (as of 4.19)</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Name

</td>
<td>


filename of the executable

</td>
</tr>
<tr>
<td>


Umask

</td>
<td>


file mode creation mask

</td>
</tr>
<tr>
<td>


State

</td>
<td>


state (R is running, S is sleeping, D is sleeping in an uninterruptible wait, Z is zombie, T is traced or stopped)

</td>
</tr>
<tr>
<td>


Tgid

</td>
<td>


thread group ID

</td>
</tr>
<tr>
<td>


Ngid

</td>
<td>


NUMA group ID (0 if none)

</td>
</tr>
<tr>
<td>


Pid

</td>
<td>


process id

</td>
</tr>
<tr>
<td>


PPid

</td>
<td>


process id of the parent process

</td>
</tr>
<tr>
<td>


TracerPid

</td>
<td>


PID of process tracing this process (0 if not, or the tracer is outside of the current pid namespace)

</td>
</tr>
<tr>
<td>


Uid

</td>
<td>


Real, effective, saved set, and  file system UIDs

</td>
</tr>
<tr>
<td>


Gid

</td>
<td>


Real, effective, saved set, and  file system GIDs

</td>
</tr>
<tr>
<td>


FDSize

</td>
<td>


number of file descriptor slots currently allocated

</td>
</tr>
<tr>
<td>


Groups

</td>
<td>


supplementary group list

</td>
</tr>
<tr>
<td>


NStgid

</td>
<td>


descendant namespace thread group ID hierarchy

</td>
</tr>
<tr>
<td>


NSpid

</td>
<td>


descendant namespace process ID hierarchy

</td>
</tr>
<tr>
<td>


NSpgid

</td>
<td>


descendant namespace process group ID hierarchy

</td>
</tr>
<tr>
<td>


NSsid

</td>
<td>


descendant namespace session ID hierarchy

</td>
</tr>
<tr>
<td>


Kthread

</td>
<td>


kernel thread flag, 1 is yes, 0 is no

</td>
</tr>
<tr>
<td>


VmPeak

</td>
<td>


peak virtual memory size

</td>
</tr>
<tr>
<td>


VmSize

</td>
<td>


total program size

</td>
</tr>
<tr>
<td>


VmLck

</td>
<td>


locked memory size

</td>
</tr>
<tr>
<td>


VmPin

</td>
<td>


pinned memory size

</td>
</tr>
<tr>
<td>


VmHWM

</td>
<td>


peak resident set size ("high water mark")

</td>
</tr>
<tr>
<td>


VmRSS

</td>
<td>


size of memory portions. It contains the three following parts (VmRSS = RssAnon + RssFile + RssShmem)

</td>
</tr>
<tr>
<td>


RssAnon

</td>
<td>


size of resident anonymous memory

</td>
</tr>
<tr>
<td>


RssFile

</td>
<td>


size of resident file mappings

</td>
</tr>
<tr>
<td>


RssShmem

</td>
<td>


size of resident shmem memory (includes SysV shm, mapping of tmpfs and shared anonymous mappings)

</td>
</tr>
<tr>
<td>


VmData

</td>
<td>


size of private data segments

</td>
</tr>
<tr>
<td>


VmStk

</td>
<td>


size of stack segments

</td>
</tr>
<tr>
<td>


VmExe

</td>
<td>


size of text segment

</td>
</tr>
<tr>
<td>


VmLib

</td>
<td>


size of shared library code

</td>
</tr>
<tr>
<td>


VmPTE

</td>
<td>


size of page table entries

</td>
</tr>
<tr>
<td>


VmSwap

</td>
<td>


amount of swap used by anonymous private data (shmem swap usage is not included)

</td>
</tr>
<tr>
<td>


HugetlbPages

</td>
<td>


size of hugetlb memory portions

</td>
</tr>
<tr>
<td>


CoreDumping

</td>
<td>


process's memory is currently being dumped (killing the process may lead to a corrupted core)

</td>
</tr>
<tr>
<td>


THP_enabled

</td>
<td>


process is allowed to use THP (returns 0 when PR_SET_THP_DISABLE is set on the process to disable THP completely, not just partially)

</td>
</tr>
<tr>
<td>


Threads

</td>
<td>


number of threads

</td>
</tr>
<tr>
<td>


SigQ

</td>
<td>


number of signals queued/max. number for queue

</td>
</tr>
<tr>
<td>


SigPnd

</td>
<td>


bitmap of pending signals for the thread

</td>
</tr>
<tr>
<td>


ShdPnd

</td>
<td>


bitmap of shared pending signals for the process

</td>
</tr>
<tr>
<td>


SigBlk

</td>
<td>


bitmap of blocked signals

</td>
</tr>
<tr>
<td>


SigIgn

</td>
<td>


bitmap of ignored signals

</td>
</tr>
<tr>
<td>


SigCgt

</td>
<td>


bitmap of caught signals

</td>
</tr>
<tr>
<td>


CapInh

</td>
<td>


bitmap of inheritable capabilities

</td>
</tr>
<tr>
<td>


CapPrm

</td>
<td>


bitmap of permitted capabilities

</td>
</tr>
<tr>
<td>


CapEff

</td>
<td>


bitmap of effective capabilities

</td>
</tr>
<tr>
<td>


CapBnd

</td>
<td>


bitmap of capabilities bounding set

</td>
</tr>
<tr>
<td>


CapAmb

</td>
<td>


bitmap of ambient capabilities

</td>
</tr>
<tr>
<td>


NoNewPrivs

</td>
<td>


no_new_privs, like prctl(PR_GET_NO_NEW_PRIV, ...)

</td>
</tr>
<tr>
<td>


Seccomp

</td>
<td>


seccomp mode, like prctl(PR_GET_SECCOMP, ...)

</td>
</tr>
<tr>
<td>


Speculation_Store_Bypass

</td>
<td>


speculative store bypass mitigation status

</td>
</tr>
<tr>
<td>


SpeculationIndirectBranch

</td>
<td>


indirect branch speculation mode

</td>
</tr>
<tr>
<td>


Cpus_allowed

</td>
<td>


mask of CPUs on which this process may run

</td>
</tr>
<tr>
<td>


Cpus_allowed_list

</td>
<td>


Same as previous, but in "list format"

</td>
</tr>
<tr>
<td>


Mems_allowed

</td>
<td>


mask of memory nodes allowed to this process

</td>
</tr>
<tr>
<td>


Mems_allowed_list

</td>
<td>


Same as previous, but in "list format"

</td>
</tr>
<tr>
<td>


voluntary_ctxt_switches

</td>
<td>


number of voluntary context switches

</td>
</tr>
<tr>
<td>


nonvoluntary_ctxt_switches

</td>
<td>


number of non voluntary context switches

</td>
</tr>
</tbody>
</table>


<table>
<caption>Table 1-3: Contents of the statm fields (as of 2.6.8-rc3)</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Content

</th>
<th>




</th>
</tr>
</thead>
<tbody>
<tr>
<td>


size

</td>
<td>


total program size (pages)

</td>
<td>


(same as VmSize in status)

</td>
</tr>
<tr>
<td>


resident

</td>
<td>


size of memory portions (pages)

</td>
<td>


(same as VmRSS in status)

</td>
</tr>
<tr>
<td>


shared

</td>
<td>


number of pages that are shared

</td>
<td>


(i.e. backed by a file, same as RssFile+RssShmem in status)

</td>
</tr>
<tr>
<td>


trs

</td>
<td>


number of pages that are 'code'

</td>
<td>


(not including libs; broken, includes data segment)

</td>
</tr>
<tr>
<td>


lrs

</td>
<td>


number of pages of library

</td>
<td>


(always 0 on 2.6)

</td>
</tr>
<tr>
<td>


drs

</td>
<td>


number of pages of data/stack

</td>
<td>


(including libs; broken, includes library text)

</td>
</tr>
<tr>
<td>


dt

</td>
<td>


number of dirty pages

</td>
<td>


(always 0 on 2.6)

</td>
</tr>
</tbody>
</table>


<table>
<caption>Table 1-4: Contents of the stat fields (as of 2.6.30-rc7)</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


pid

</td>
<td>


process id

</td>
</tr>
<tr>
<td>


tcomm

</td>
<td>


filename of the executable

</td>
</tr>
<tr>
<td>


state

</td>
<td>


state (R is running, S is sleeping, D is sleeping in an uninterruptible wait, Z is zombie, T is traced or stopped)

</td>
</tr>
<tr>
<td>


ppid

</td>
<td>


process id of the parent process

</td>
</tr>
<tr>
<td>


pgrp

</td>
<td>


pgrp of the process

</td>
</tr>
<tr>
<td>


sid

</td>
<td>


session id

</td>
</tr>
<tr>
<td>


tty_nr

</td>
<td>


tty the process uses

</td>
</tr>
<tr>
<td>


tty_pgrp

</td>
<td>


pgrp of the tty

</td>
</tr>
<tr>
<td>


flags

</td>
<td>


task flags

</td>
</tr>
<tr>
<td>


min_flt

</td>
<td>


number of minor faults

</td>
</tr>
<tr>
<td>


cmin_flt

</td>
<td>


number of minor faults with child's

</td>
</tr>
<tr>
<td>


maj_flt

</td>
<td>


number of major faults

</td>
</tr>
<tr>
<td>


cmaj_flt

</td>
<td>


number of major faults with child's

</td>
</tr>
<tr>
<td>


utime

</td>
<td>


user mode jiffies

</td>
</tr>
<tr>
<td>


stime

</td>
<td>


kernel mode jiffies

</td>
</tr>
<tr>
<td>


cutime

</td>
<td>


user mode jiffies with child's

</td>
</tr>
<tr>
<td>


cstime

</td>
<td>


kernel mode jiffies with child's

</td>
</tr>
<tr>
<td>


priority

</td>
<td>


priority level

</td>
</tr>
<tr>
<td>


nice

</td>
<td>


nice level

</td>
</tr>
<tr>
<td>


num_threads

</td>
<td>


number of threads

</td>
</tr>
<tr>
<td>


it_real_value

</td>
<td>


(obsolete, always 0)

</td>
</tr>
<tr>
<td>


start_time

</td>
<td>


time the process started after system boot

</td>
</tr>
<tr>
<td>


vsize

</td>
<td>


virtual memory size

</td>
</tr>
<tr>
<td>


rss

</td>
<td>


resident set memory size

</td>
</tr>
<tr>
<td>


rsslim

</td>
<td>


current limit in bytes on the rss

</td>
</tr>
<tr>
<td>


start_code

</td>
<td>


address above which program text can run

</td>
</tr>
<tr>
<td>


end_code

</td>
<td>


address below which program text can run

</td>
</tr>
<tr>
<td>


start_stack

</td>
<td>


address of the start of the main process stack

</td>
</tr>
<tr>
<td>


esp

</td>
<td>


current value of ESP

</td>
</tr>
<tr>
<td>


eip

</td>
<td>


current value of EIP

</td>
</tr>
<tr>
<td>


pending

</td>
<td>


bitmap of pending signals

</td>
</tr>
<tr>
<td>


blocked

</td>
<td>


bitmap of blocked signals

</td>
</tr>
<tr>
<td>


sigign

</td>
<td>


bitmap of ignored signals

</td>
</tr>
<tr>
<td>


sigcatch

</td>
<td>


bitmap of caught signals

</td>
</tr>
<tr>
<td>


0

</td>
<td>


(place holder, used to be the wchan address, use /proc/PID/wchan instead)

</td>
</tr>
<tr>
<td>


0

</td>
<td>


(place holder)

</td>
</tr>
<tr>
<td>


0

</td>
<td>


(place holder)

</td>
</tr>
<tr>
<td>


exit_signal

</td>
<td>


signal to send to parent thread on exit

</td>
</tr>
<tr>
<td>


task_cpu

</td>
<td>


which CPU the task is scheduled on

</td>
</tr>
<tr>
<td>


rt_priority

</td>
<td>


realtime priority

</td>
</tr>
<tr>
<td>


policy

</td>
<td>


scheduling policy (man sched_setscheduler)

</td>
</tr>
<tr>
<td>


blkio_ticks

</td>
<td>


time spent waiting for block IO

</td>
</tr>
<tr>
<td>


gtime

</td>
<td>


guest time of the task in jiffies

</td>
</tr>
<tr>
<td>


cgtime

</td>
<td>


guest time of the task children in jiffies

</td>
</tr>
<tr>
<td>


start_data

</td>
<td>


address above which program data+bss is placed

</td>
</tr>
<tr>
<td>


end_data

</td>
<td>


address below which program data+bss is placed

</td>
</tr>
<tr>
<td>


start_brk

</td>
<td>


address above which program heap can be expanded with brk()

</td>
</tr>
<tr>
<td>


arg_start

</td>
<td>


address above which program command line is placed

</td>
</tr>
<tr>
<td>


arg_end

</td>
<td>


address below which program command line is placed

</td>
</tr>
<tr>
<td>


env_start

</td>
<td>


address above which program environment is placed

</td>
</tr>
<tr>
<td>


env_end

</td>
<td>


address below which program environment is placed

</td>
</tr>
<tr>
<td>


exit_code

</td>
<td>


the thread's exit_code in the form reported by the waitpid system call

</td>
</tr>
</tbody>
</table>

The /proc/PID/maps file contains the currently mapped memory regions and their access permissions.

The format is:



```text
address           perms offset  dev   inode      pathname

08048000-08049000 r-xp 00000000 03:00 8312       /opt/test
08049000-0804a000 rw-p 00001000 03:00 8312       /opt/test
0804a000-0806b000 rw-p 00000000 00:00 0          [heap]
a7cb1000-a7cb2000 ---p 00000000 00:00 0
a7cb2000-a7eb2000 rw-p 00000000 00:00 0
a7eb2000-a7eb3000 ---p 00000000 00:00 0
a7eb3000-a7ed5000 rw-p 00000000 00:00 0
a7ed5000-a8008000 r-xp 00000000 03:00 4222       /lib/libc.so.6
a8008000-a800a000 r--p 00133000 03:00 4222       /lib/libc.so.6
a800a000-a800b000 rw-p 00135000 03:00 4222       /lib/libc.so.6
a800b000-a800e000 rw-p 00000000 00:00 0
a800e000-a8022000 r-xp 00000000 03:00 14462      /lib/libpthread.so.0
a8022000-a8023000 r--p 00013000 03:00 14462      /lib/libpthread.so.0
a8023000-a8024000 rw-p 00014000 03:00 14462      /lib/libpthread.so.0
a8024000-a8027000 rw-p 00000000 00:00 0
a8027000-a8043000 r-xp 00000000 03:00 8317       /lib/ld-linux.so.2
a8043000-a8044000 r--p 0001b000 03:00 8317       /lib/ld-linux.so.2
a8044000-a8045000 rw-p 0001c000 03:00 8317       /lib/ld-linux.so.2
aff35000-aff4a000 rw-p 00000000 00:00 0          [stack]
ffffe000-fffff000 r-xp 00000000 00:00 0          [vdso]
```

where "address" is the address space in the process that it occupies, "perms" is a set of permissions:



```text
r = read
w = write
x = execute
s = shared
p = private (copy on write)
```

"offset" is the offset into the mapping, "dev" is the device (major:minor), and "inode" is the inode  on that device.  0 indicates that  no inode is associated with the memory region, as the case would be with BSS (uninitialized data). The "pathname" shows the name associated file for this mapping.  If the mapping is not associated with a file:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> \[heap\]
>
> </td>
> <td>
>
>
> the heap of the program
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> \[stack\]
>
> </td>
> <td>
>
>
> the stack of the main process
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> \[vdso\]
>
> </td>
> <td>
>
>
> the "virtual dynamic shared object", the kernel system call handler
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> \[anon:&lt;name&gt;\]
>
> </td>
> <td>
>
>
> a private anonymous mapping that has been named by userspace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> \[anon_shmem:&lt;name&gt;\]
>
> </td>
> <td>
>
>
> an anonymous shared memory mapping that has been named by userspace
>
> </td>
> </tr>
> </tbody>
> </table>
>
> or if empty, the mapping is anonymous.

Starting with 6.11 kernel, /proc/PID/maps provides an alternative ioctl()-based API that gives ability to flexibly and efficiently query and filter individual VMAs. This interface is binary and is meant for more efficient and easy programmatic use. `struct procmap_query`, defined in linux/fs.h UAPI header, serves as an input/output argument to the `PROCMAP_QUERY` ioctl() command. See comments in linus/fs.h UAPI header for details on query semantics, supported flags, data returned, and general API usage information.

The /proc/PID/smaps is an extension based on maps, showing the memory consumption for each of the process's mappings. For each mapping (aka Virtual Memory Area, or VMA) there is a series of lines such as the following:



```text
08048000-080bc000 r-xp 00000000 03:02 13130      /bin/bash

Size:               1084 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Rss:                 892 kB
Pss:                 374 kB
Pss_Dirty:             0 kB
Shared_Clean:        892 kB
Shared_Dirty:          0 kB
Private_Clean:         0 kB
Private_Dirty:         0 kB
Referenced:          892 kB
Anonymous:             0 kB
KSM:                   0 kB
LazyFree:              0 kB
AnonHugePages:         0 kB
ShmemPmdMapped:        0 kB
Shared_Hugetlb:        0 kB
Private_Hugetlb:       0 kB
Swap:                  0 kB
SwapPss:               0 kB
KernelPageSize:        4 kB
MMUPageSize:           4 kB
Locked:                0 kB
THPeligible:           0
VmFlags: rd ex mr mw me dw
```

The first of these lines shows the same information as is displayed for the mapping in /proc/PID/maps.  Following lines show the size of the mapping (size); the size of each page allocated when backing a VMA (KernelPageSize), which is usually the same as the size in the page table entries; the page size used by the MMU when backing a VMA (in most cases, the same as KernelPageSize); the amount of the mapping that is currently resident in RAM (RSS); the process's proportional share of this mapping (PSS); and the number of clean and dirty shared and private pages in the mapping.

The "proportional set size" (PSS) of a process is the count of pages it has in memory, where each page is divided by the number of processes sharing it. So if a process has 1000 pages all to itself, and 1000 shared with one other process, its PSS will be 1500.  "Pss_Dirty" is the portion of PSS which consists of dirty pages.  ("Pss_Clean" is not included, but it can be calculated by subtracting "Pss_Dirty" from "Pss".)

Traditionally, a page is accounted as "private" if it is mapped exactly once, and a page is accounted as "shared" when mapped multiple times, even when mapped in the same process multiple times. Note that this accounting is independent of MAP_SHARED.

In some kernel configurations, the semantics of pages part of a larger allocation (e.g., THP) can differ: a page is accounted as "private" if all pages part of the corresponding large allocation are *certainly* mapped in the same process, even if the page is mapped multiple times in that process. A page is accounted as "shared" if any page page of the larger allocation is *maybe* mapped in a different process. In some cases, a large allocation might be treated as "maybe mapped by multiple processes" even though this is no longer the case.

Some kernel configurations do not track the precise number of times a page part of a larger allocation is mapped. In this case, when calculating the PSS, the average number of mappings per page in this larger allocation might be used as an approximation for the number of mappings of a page. The PSS calculation will be imprecise in this case.

"Referenced" indicates the amount of memory currently marked as referenced or accessed.

"Anonymous" shows the amount of memory that does not belong to any file.  Even a mapping associated with a file may contain anonymous pages: when MAP_PRIVATE and a page is modified, the file page is replaced by a private anonymous copy.

"KSM" reports how many of the pages are KSM pages. Note that KSM-placed zeropages are not included, only actual KSM pages.

"LazyFree" shows the amount of memory which is marked by madvise(MADV_FREE). The memory isn't freed immediately with madvise(). It's freed in memory pressure if the memory is clean. Please note that the printed value might be lower than the real value due to optimizations used in the current implementation. If this is not desirable please file a bug report.

"AnonHugePages" shows the amount of memory backed by transparent hugepage.

"ShmemPmdMapped" shows the amount of shared (shmem/tmpfs) memory backed by huge pages.

"Shared_Hugetlb" and "Private_Hugetlb" show the amounts of memory backed by hugetlbfs page which is *not* counted in "RSS" or "PSS" field for historical reasons. And these are not included in \{Shared,Private\}\_\{Clean,Dirty\} field.

"Swap" shows how much would-be-anonymous memory is also used, but out on swap.

For shmem mappings, "Swap" includes also the size of the mapped (and not replaced by copy-on-write) part of the underlying shmem object out on swap. "SwapPss" shows proportional swap share of this mapping. Unlike "Swap", this does not take into account swapped out page of underlying shmem objects. "Locked" indicates whether the mapping is locked in memory or not.

"THPeligible" indicates whether the mapping is eligible for allocating naturally aligned THP pages of any currently enabled size. 1 if true, 0 otherwise.

"VmFlags" field deserves a separate description. This member represents the kernel flags associated with the particular virtual memory area in two letter encoded manner. The codes are the following:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> rd
>
> </td>
> <td>
>
>
> readable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> wr
>
> </td>
> <td>
>
>
> writeable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ex
>
> </td>
> <td>
>
>
> executable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sh
>
> </td>
> <td>
>
>
> shared
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mr
>
> </td>
> <td>
>
>
> may read
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mw
>
> </td>
> <td>
>
>
> may write
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> me
>
> </td>
> <td>
>
>
> may execute
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ms
>
> </td>
> <td>
>
>
> may share
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gd
>
> </td>
> <td>
>
>
> stack segment growns down
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> pf
>
> </td>
> <td>
>
>
> pure PFN range
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> lo
>
> </td>
> <td>
>
>
> pages are locked in memory
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> io
>
> </td>
> <td>
>
>
> memory mapped I/O area
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sr
>
> </td>
> <td>
>
>
> sequential read advise provided
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rr
>
> </td>
> <td>
>
>
> random read advise provided
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dc
>
> </td>
> <td>
>
>
> do not copy area on fork
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> de
>
> </td>
> <td>
>
>
> do not expand area on remapping
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ac
>
> </td>
> <td>
>
>
> area is accountable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nr
>
> </td>
> <td>
>
>
> swap space is not reserved for the area
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ht
>
> </td>
> <td>
>
>
> area uses huge tlb pages
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sf
>
> </td>
> <td>
>
>
> synchronous page fault
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ar
>
> </td>
> <td>
>
>
> architecture specific flag
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> wf
>
> </td>
> <td>
>
>
> wipe on fork
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dd
>
> </td>
> <td>
>
>
> do not include area into core dump
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sd
>
> </td>
> <td>
>
>
> soft dirty flag
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mm
>
> </td>
> <td>
>
>
> mixed map area
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> hg
>
> </td>
> <td>
>
>
> huge page advise flag
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nh
>
> </td>
> <td>
>
>
> no huge page advise flag
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mg
>
> </td>
> <td>
>
>
> mergeable advise flag
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> bt
>
> </td>
> <td>
>
>
> arm64 BTI guarded page
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mt
>
> </td>
> <td>
>
>
> arm64 MTE allocation tags are enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> um
>
> </td>
> <td>
>
>
> userfaultfd missing tracking
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> uw
>
> </td>
> <td>
>
>
> userfaultfd wr-protect tracking
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ui
>
> </td>
> <td>
>
>
> userfaultfd minor fault
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ss
>
> </td>
> <td>
>
>
> shadow/guarded control stack page
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sl
>
> </td>
> <td>
>
>
> sealed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> lf
>
> </td>
> <td>
>
>
> lock on fault pages
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dp
>
> </td>
> <td>
>
>
> always lazily freeable mapping
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gu
>
> </td>
> <td>
>
>
> maybe contains guard regions (if not set, definitely doesn't)
>
> </td>
> </tr>
> </tbody>
> </table>

Note that there is no guarantee that every flag and associated mnemonic will be present in all further kernel releases. Things get changed, the flags may be vanished or the reverse -- new added. Interpretation of their meaning might change in future as well. So each consumer of these flags has to follow each specific kernel version for the exact semantic.

This file is only present if the CONFIG_MMU kernel configuration option is enabled.

Note: reading /proc/PID/maps or /proc/PID/smaps is inherently racy (consistent output can be achieved only in the single read call).

This typically manifests when doing partial reads of these files while the memory map is being modified.  Despite the races, we do provide the following guarantees:

1. The mapped addresses never go backwards, which implies no two regions will ever overlap.

2. If there is something at a given vaddr during the entirety of the life of the smaps/maps walk, there will be some output for it.

The /proc/PID/smaps_rollup file includes the same fields as /proc/PID/smaps, but their values are the sums of the corresponding values for all mappings of the process.  Additionally, it contains these fields:

- Pss_Anon

- Pss_File

- Pss_Shmem

They represent the proportional shares of anonymous, file, and shmem pages, as described for smaps above.  These fields are omitted in smaps since each mapping identifies the type (anon, file, or shmem) of all pages it contains. Thus all information in smaps_rollup can be derived from smaps, but at a significantly higher cost.

The /proc/PID/clear_refs is used to reset the PG_Referenced and ACCESSED/YOUNG bits on both physical and virtual pages associated with a process, and the soft-dirty bit on pte (see [Documentation/admin-guide/mm/soft-dirty.rst](/kernel/administration/admin-guide/mm/soft-dirty.md) for details). To clear the bits for all the pages associated with the process:



```text
> echo 1 > /proc/PID/clear_refs
```

To clear the bits for the anonymous pages associated with the process:



```text
> echo 2 > /proc/PID/clear_refs
```

To clear the bits for the file mapped pages associated with the process:



```text
> echo 3 > /proc/PID/clear_refs
```

To clear the soft-dirty bit:



```text
> echo 4 > /proc/PID/clear_refs
```

To reset the peak resident set size ("high water mark") to the process's current value:



```text
> echo 5 > /proc/PID/clear_refs
```

Any other value written to /proc/PID/clear_refs will have no effect.

The /proc/pid/pagemap gives the PFN, which can be used to find the pageflags using /proc/kpageflags and number of times a page is mapped using /proc/kpagecount. For detailed explanation, see [Documentation/admin-guide/mm/pagemap.rst](/kernel/administration/admin-guide/mm/pagemap.md).

The /proc/pid/numa_maps is an extension based on maps, showing the memory locality and binding policy, as well as the memory usage (in pages) of each mapping. The output follows a general format where mapping details get summarized separated by blank spaces, one mapping per each file line:



```text
address   policy    mapping details

00400000 default file=/usr/local/bin/app mapped=1 active=0 N3=1 kernelpagesize_kB=4
00600000 default file=/usr/local/bin/app anon=1 dirty=1 N3=1 kernelpagesize_kB=4
3206000000 default file=/lib64/ld-2.12.so mapped=26 mapmax=6 N0=24 N3=2 kernelpagesize_kB=4
320621f000 default file=/lib64/ld-2.12.so anon=1 dirty=1 N3=1 kernelpagesize_kB=4
3206220000 default file=/lib64/ld-2.12.so anon=1 dirty=1 N3=1 kernelpagesize_kB=4
3206221000 default anon=1 dirty=1 N3=1 kernelpagesize_kB=4
3206800000 default file=/lib64/libc-2.12.so mapped=59 mapmax=21 active=55 N0=41 N3=18 kernelpagesize_kB=4
320698b000 default file=/lib64/libc-2.12.so
3206b8a000 default file=/lib64/libc-2.12.so anon=2 dirty=2 N3=2 kernelpagesize_kB=4
3206b8e000 default file=/lib64/libc-2.12.so anon=1 dirty=1 N3=1 kernelpagesize_kB=4
3206b8f000 default anon=3 dirty=3 active=1 N3=3 kernelpagesize_kB=4
7f4dc10a2000 default anon=3 dirty=3 N3=3 kernelpagesize_kB=4
7f4dc10b4000 default anon=2 dirty=2 active=1 N3=2 kernelpagesize_kB=4
7f4dc1200000 default file=/anon_hugepage\040(deleted) huge anon=1 dirty=1 N3=1 kernelpagesize_kB=2048
7fff335f0000 default stack anon=3 dirty=3 N3=3 kernelpagesize_kB=4
7fff3369d000 default mapped=1 mapmax=35 active=0 N3=1 kernelpagesize_kB=4
```

Where:

"address" is the starting address for the mapping;

"policy" reports the NUMA memory policy set for the mapping (see [Documentation/admin-guide/mm/numa_memory_policy.rst](/kernel/administration/admin-guide/mm/numa-memory-policy.md));

"mapping details" summarizes mapping data such as mapping type, page usage counters, node locality page counters (N0 == node0, N1 == node1, ...) and the kernel page size, in KB, that is backing the mapping up.

Note that some kernel configurations do not track the precise number of times a page part of a larger allocation (e.g., THP) is mapped. In these configurations, "mapmax" might corresponds to the average number of mappings per page in such a larger allocation instead.

<a id="rst-kernel-data"></a>

### 1.2 Kernel data

Similar to  the  process entries, the kernel data files give information about the running kernel. The files used to obtain this information are contained in /proc and  are  listed  in Table 1-5. Not all of these will be present in your system. It  depends  on the kernel configuration and the loaded modules, which files are there, and which are missing.


<table>
<caption>Table 1-5: Kernel info in /proc</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


allocinfo

</td>
<td>


Memory allocations profiling information

</td>
</tr>
<tr>
<td>


apm

</td>
<td>


Advanced power management info

</td>
</tr>
<tr>
<td>


bootconfig

</td>
<td>


Kernel command line obtained from boot config, and, if there were kernel parameters from the boot loader, a "\# Parameters from bootloader:" line followed by a line containing those parameters prefixed by "\# ".                      (5.5)

</td>
</tr>
<tr>
<td>


buddyinfo

</td>
<td>


Kernel memory allocator information (see text)    (2.5)

</td>
</tr>
<tr>
<td>


bus

</td>
<td>


Directory containing bus specific information

</td>
</tr>
<tr>
<td>


cmdline

</td>
<td>


Kernel command line, both from bootloader and embedded in the kernel image

</td>
</tr>
<tr>
<td>


cpuinfo

</td>
<td>


Info about the CPU

</td>
</tr>
<tr>
<td>


devices

</td>
<td>


Available devices (block and character)

</td>
</tr>
<tr>
<td>


dma

</td>
<td>


Used DMS channels

</td>
</tr>
<tr>
<td>


filesystems

</td>
<td>


Supported filesystems

</td>
</tr>
<tr>
<td>


driver

</td>
<td>


Various drivers grouped here, currently rtc       (2.4)

</td>
</tr>
<tr>
<td>


execdomains

</td>
<td>


Execdomains, related to security                  (2.4)

</td>
</tr>
<tr>
<td>


fb

</td>
<td>


Frame Buffer devices                              (2.4)

</td>
</tr>
<tr>
<td>


fs

</td>
<td>


File system parameters, currently nfs/exports     (2.4)

</td>
</tr>
<tr>
<td>


ide

</td>
<td>


Directory containing info about the IDE subsystem

</td>
</tr>
<tr>
<td>


interrupts

</td>
<td>


Interrupt usage

</td>
</tr>
<tr>
<td>


iomem

</td>
<td>


Memory map                                        (2.4)

</td>
</tr>
<tr>
<td>


ioports

</td>
<td>


I/O port usage

</td>
</tr>
<tr>
<td>


irq

</td>
<td>


Masks for irq to cpu affinity                     (2.4)(smp?)

</td>
</tr>
<tr>
<td>


isapnp

</td>
<td>


ISA PnP (Plug&amp;Play) Info                          (2.4)

</td>
</tr>
<tr>
<td>


kcore

</td>
<td>


Kernel core image (can be ELF or A.OUT(deprecated in 2.4))

</td>
</tr>
<tr>
<td>


kmsg

</td>
<td>


Kernel messages

</td>
</tr>
<tr>
<td>


ksyms

</td>
<td>


Kernel symbol table

</td>
</tr>
<tr>
<td>


loadavg

</td>
<td>


- **Load average of last 1, 5 &amp; 15 minutes;**

  number of processes currently runnable (running or on ready queue); total number of processes in system; last pid created. All fields are separated by one space except "number of processes currently runnable" and "total number of processes in system", which are separated by a slash ('/'). Example: 0.61 0.61 0.55 3/828 22084

</td>
</tr>
<tr>
<td>


locks

</td>
<td>


Kernel locks

</td>
</tr>
<tr>
<td>


meminfo

</td>
<td>


Memory info

</td>
</tr>
<tr>
<td>


misc

</td>
<td>


Miscellaneous

</td>
</tr>
<tr>
<td>


modules

</td>
<td>


List of loaded modules

</td>
</tr>
<tr>
<td>


mounts

</td>
<td>


Mounted filesystems

</td>
</tr>
<tr>
<td>


net

</td>
<td>


Networking info (see text)

</td>
</tr>
<tr>
<td>


pagetypeinfo

</td>
<td>


Additional page allocator information (see text)  (2.5)

</td>
</tr>
<tr>
<td>


partitions

</td>
<td>


Table of partitions known to the system

</td>
</tr>
<tr>
<td>


pci

</td>
<td>


Deprecated info of PCI bus (new way -&gt; /proc/bus/pci/, decoupled by lspci                                (2.4)

</td>
</tr>
<tr>
<td>


rtc

</td>
<td>


Real time clock

</td>
</tr>
<tr>
<td>


scsi

</td>
<td>


SCSI info (see text)

</td>
</tr>
<tr>
<td>


slabinfo

</td>
<td>


Slab pool info

</td>
</tr>
<tr>
<td>


softirqs

</td>
<td>


softirq usage

</td>
</tr>
<tr>
<td>


stat

</td>
<td>


Overall statistics

</td>
</tr>
<tr>
<td>


swaps

</td>
<td>


Swap space utilization

</td>
</tr>
<tr>
<td>


sys

</td>
<td>


See chapter 2

</td>
</tr>
<tr>
<td>


sysvipc

</td>
<td>


Info of SysVIPC Resources (msg, sem, shm)         (2.4)

</td>
</tr>
<tr>
<td>


tty

</td>
<td>


Info of tty drivers

</td>
</tr>
<tr>
<td>


uptime

</td>
<td>


Wall clock since boot, combined idle time of all cpus

</td>
</tr>
<tr>
<td>


version

</td>
<td>


Kernel version

</td>
</tr>
<tr>
<td>


video

</td>
<td>


bttv info of video resources                      (2.4)

</td>
</tr>
<tr>
<td>


vmallocinfo

</td>
<td>


Show vmalloced areas

</td>
</tr>
</tbody>
</table>

You can,  for  example,  check  which interrupts are currently in use and what they are used for by looking in the file /proc/interrupts:



```text
> cat /proc/interrupts
           CPU0
  0:    8728810          XT-PIC  timer
  1:        895          XT-PIC  keyboard
  2:          0          XT-PIC  cascade
  3:     531695          XT-PIC  aha152x
  4:    2014133          XT-PIC  serial
  5:      44401          XT-PIC  pcnet_cs
  8:          2          XT-PIC  rtc
 11:          8          XT-PIC  i82365
 12:     182918          XT-PIC  PS/2 Mouse
 13:          1          XT-PIC  fpu
 14:    1232265          XT-PIC  ide0
 15:          7          XT-PIC  ide1
NMI:          0
```

In 2.4.\* a couple of lines where added to this file LOC &amp; ERR (this time is the output of a SMP machine):



```text
> cat /proc/interrupts

           CPU0       CPU1
  0:    1243498    1214548    IO-APIC-edge  timer
  1:       8949       8958    IO-APIC-edge  keyboard
  2:          0          0          XT-PIC  cascade
  5:      11286      10161    IO-APIC-edge  soundblaster
  8:          1          0    IO-APIC-edge  rtc
  9:      27422      27407    IO-APIC-edge  3c503
 12:     113645     113873    IO-APIC-edge  PS/2 Mouse
 13:          0          0          XT-PIC  fpu
 14:      22491      24012    IO-APIC-edge  ide0
 15:       2183       2415    IO-APIC-edge  ide1
 17:      30564      30414   IO-APIC-level  eth0
 18:        177        164   IO-APIC-level  bttv
NMI:    2457961    2457959
LOC:    2457882    2457881
ERR:       2155
```

NMI is incremented in this case because every timer interrupt generates a NMI (Non Maskable Interrupt) which is used by the NMI Watchdog to detect lockups.

LOC is the local interrupt counter of the internal APIC of every CPU.

ERR is incremented in the case of errors in the IO-APIC bus (the bus that connects the CPUs in a SMP system. This means that an error has been detected, the IO-APIC automatically retry the transmission, so it should not be a big problem, but you should read the SMP-FAQ.

In 2.6.2\* /proc/interrupts was expanded again.  This time the goal was for /proc/interrupts to display every IRQ vector in use by the system, not just those considered 'most important'.  The new vectors are:

- **THR**

  interrupt raised when a machine check threshold counter (typically counting ECC corrected errors of memory or cache) exceeds a configurable threshold.  Only available on some systems.

- **TRM**

  a thermal event interrupt occurs when a temperature threshold has been exceeded for the CPU.  This interrupt may also be generated when the temperature drops back to normal.

- **SPU**

  a spurious interrupt is some interrupt that was raised then lowered by some IO device before it could be fully processed by the APIC.  Hence the APIC sees the interrupt but does not know what device it came from. For this case the APIC will generate the interrupt with a IRQ vector of 0xff. This might also be generated by chipset bugs.

- **RES, CAL, TLB**

  rescheduling, call and TLB flush interrupts are sent from one CPU to another per the needs of the OS.  Typically, their statistics are used by kernel developers and interested users to determine the occurrence of interrupts of the given type.

The above IRQ vectors are displayed only when relevant.  For example, the threshold vector does not exist on x86_64 platforms.  Others are suppressed when the system is a uniprocessor.  As of this writing, only i386 and x86_64 platforms support the new IRQ vector displays.

Of some interest is the introduction of the /proc/irq directory to 2.4. It could be used to set IRQ to CPU affinity. This means that you can "hook" an IRQ to only one CPU, or to exclude a CPU of handling IRQs. The contents of the irq subdir is one subdir for each IRQ, and two files; default_smp_affinity and prof_cpu_mask.

For example:



```text
> ls /proc/irq/
0  10  12  14  16  18  2  4  6  8  prof_cpu_mask
1  11  13  15  17  19  3  5  7  9  default_smp_affinity
> ls /proc/irq/0/
smp_affinity
```

smp_affinity is a bitmask, in which you can specify which CPUs can handle the IRQ. You can set it by doing:



```text
> echo 1 > /proc/irq/10/smp_affinity
```

This means that only the first CPU will handle the IRQ, but you can also echo 5 which means that only the first and third CPU can handle the IRQ.

The contents of each smp_affinity file is the same by default:



```text
> cat /proc/irq/0/smp_affinity
ffffffff
```

There is an alternate interface, smp_affinity_list which allows specifying a CPU range instead of a bitmask:



```text
> cat /proc/irq/0/smp_affinity_list
1024-1031
```

The default_smp_affinity mask applies to all non-active IRQs, which are the IRQs which have not yet been allocated/activated, and hence which lack a /proc/irq/\[0-9\]\* directory.

The node file on an SMP system shows the node to which the device using the IRQ reports itself as being attached. This hardware locality information does not include information about any possible driver locality preference.

prof_cpu_mask specifies which CPUs are to be profiled by the system wide profiler. Default value is ffffffff (all CPUs if there are only 32 of them).

The way IRQs are routed is handled by the IO-APIC, and it's Round Robin between all the CPUs which are allowed to handle it. As usual the kernel has more info than you and does a better job than you, so the defaults are the best choice for almost everyone.  \[Note this applies only to those IO-APIC's that support "Round Robin" interrupt distribution.\]

There are  three  more  important subdirectories in /proc: net, scsi, and sys. The general  rule  is  that  the  contents,  or  even  the  existence of these directories, depend  on your kernel configuration. If SCSI is not enabled, the directory scsi  may  not  exist. The same is true with the net, which is there only when networking support is present in the running kernel.

The slabinfo  file  gives  information  about  memory usage at the slab level. Linux uses  slab  pools for memory management above page level in version 2.2. Commonly used  objects  have  their  own  slab  pool (such as network buffers, directory cache, and so on).



```text
> cat /proc/buddyinfo

Node 0, zone      DMA      0      4      5      4      4      3 ...
Node 0, zone   Normal      1      0      0      1    101      8 ...
Node 0, zone  HighMem      2      0      0      1      1      0 ...
```

External fragmentation is a problem under some workloads, and buddyinfo is a useful tool for helping diagnose these problems.  Buddyinfo will give you a clue as to how big an area you can safely allocate, or why a previous allocation failed.

Each column represents the number of pages of a certain order which are available.  In this case, there are 0 chunks of 2^0\*PAGE_SIZE available in ZONE_DMA, 4 chunks of 2^1\*PAGE_SIZE in ZONE_DMA, 101 chunks of 2^4\*PAGE_SIZE available in ZONE_NORMAL, etc...

More information relevant to external fragmentation can be found in pagetypeinfo:



```text
> cat /proc/pagetypeinfo
Page block order: 9
Pages per block:  512

Free pages count per migrate type at order       0      1      2      3      4      5      6      7      8      9     10
Node    0, zone      DMA, type    Unmovable      0      0      0      1      1      1      1      1      1      1      0
Node    0, zone      DMA, type  Reclaimable      0      0      0      0      0      0      0      0      0      0      0
Node    0, zone      DMA, type      Movable      1      1      2      1      2      1      1      0      1      0      2
Node    0, zone      DMA, type      Reserve      0      0      0      0      0      0      0      0      0      1      0
Node    0, zone      DMA, type      Isolate      0      0      0      0      0      0      0      0      0      0      0
Node    0, zone    DMA32, type    Unmovable    103     54     77      1      1      1     11      8      7      1      9
Node    0, zone    DMA32, type  Reclaimable      0      0      2      1      0      0      0      0      1      0      0
Node    0, zone    DMA32, type      Movable    169    152    113     91     77     54     39     13      6      1    452
Node    0, zone    DMA32, type      Reserve      1      2      2      2      2      0      1      1      1      1      0
Node    0, zone    DMA32, type      Isolate      0      0      0      0      0      0      0      0      0      0      0

Number of blocks type     Unmovable  Reclaimable      Movable      Reserve      Isolate
Node 0, zone      DMA            2            0            5            1            0
Node 0, zone    DMA32           41            6          967            2            0
```

Fragmentation avoidance in the kernel works by grouping pages of different migrate types into the same contiguous regions of memory called page blocks. A page block is typically the size of the default hugepage size, e.g. 2MB on X86-64. By keeping pages grouped based on their ability to move, the kernel can reclaim pages within a page block to satisfy a high-order allocation.

The pagetypinfo begins with information on the size of a page block. It then gives the same type of information as buddyinfo except broken down by migrate-type and finishes with details on how many page blocks of each type exist.

If min_free_kbytes has been tuned correctly (recommendations made by hugeadm from libhugetlbfs [https://github.com/libhugetlbfs/libhugetlbfs/](<https://github.com/libhugetlbfs/libhugetlbfs/>)), one can make an estimate of the likely number of huge pages that can be allocated at a given point in time. All the "Movable" blocks should be allocatable unless memory has been mlock()'d. Some of the Reclaimable blocks should also be allocatable although a lot of filesystem metadata may have to be reclaimed to achieve this.

<a id="rst-allocinfo"></a>

#### allocinfo

Provides information about memory allocations at all locations in the code base. Each allocation in the code is identified by its source file, line number, module (if originates from a loadable module) and the function calling the allocation. The number of bytes allocated and number of calls at each location are reported. The first line indicates the version of the file, the second line is the header listing fields in the file. If file version is 2.0 or higher then each line may contain additional &lt;key&gt;:&lt;value&gt; pairs representing extra information about the call site. For example if the counters are not accurate, the line will be appended with "accurate:no" pair.

Supported markers in v2: accurate:no

> Absolute values of the counters in this line are not accurate because of the failure to allocate memory to track some of the allocations made at this location.  Deltas in these counters are accurate, therefore counters can be used to track allocation size and count changes.

Example output.



```text
 > tail -n +3 /proc/allocinfo | sort -rn
127664128    31168 mm/page_ext.c:270 func:alloc_page_ext
 56373248     4737 mm/slub.c:2259 func:alloc_slab_page
 14880768     3633 mm/readahead.c:247 func:page_cache_ra_unbounded
 14417920     3520 mm/mm_init.c:2530 func:alloc_large_system_hash
 13377536      234 block/blk-mq.c:3421 func:blk_mq_alloc_rqs
 11718656     2861 mm/filemap.c:1919 func:__filemap_get_folio
  9192960     2800 kernel/fork.c:307 func:alloc_thread_stack_node
  4206592        4 net/netfilter/nf_conntrack_core.c:2567 func:nf_ct_alloc_hashtable
  4136960     1010 drivers/staging/ctagmod/ctagmod.c:20 [ctagmod] func:ctagmod_start
  3940352      962 mm/memory.c:4214 func:alloc_anon_folio
  2894464    22613 fs/kernfs/dir.c:615 func:__kernfs_new_node
  ...
```

<a id="rst-meminfo"></a>

#### meminfo

Provides information about distribution and utilization of memory.  This varies by architecture and compile options.  Some of the counters reported here overlap.  The memory reported by the non overlapping counters may not add up to the overall memory usage and the difference for some workloads can be substantial.  In many cases there are other means to find out additional memory using subsystem specific interfaces, for instance /proc/net/sockstat for TCP memory allocations.

Example output. You may not have all of these fields.



```text
> cat /proc/meminfo

MemTotal:       32858820 kB
MemFree:        21001236 kB
MemAvailable:   27214312 kB
Buffers:          581092 kB
Cached:          5587612 kB
SwapCached:            0 kB
Active:          3237152 kB
Inactive:        7586256 kB
Active(anon):      94064 kB
Inactive(anon):  4570616 kB
Active(file):    3143088 kB
Inactive(file):  3015640 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Zswap:              1904 kB
Zswapped:           7792 kB
Dirty:                12 kB
Writeback:             0 kB
AnonPages:       4654780 kB
Mapped:           266244 kB
Shmem:              9976 kB
KReclaimable:     517708 kB
Slab:             660044 kB
SReclaimable:     517708 kB
SUnreclaim:       142336 kB
KernelStack:       11168 kB
PageTables:        20540 kB
SecPageTables:         0 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    16429408 kB
Committed_AS:    7715148 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       40444 kB
VmallocChunk:          0 kB
Percpu:            29312 kB
EarlyMemtestBad:       0 kB
HardwareCorrupted:     0 kB
AnonHugePages:   4149248 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
CmaTotal:              0 kB
CmaFree:               0 kB
Unaccepted:            0 kB
Balloon:               0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      401152 kB
DirectMap2M:    10008576 kB
DirectMap1G:    24117248 kB
```

- **MemTotal**

  Total usable RAM (i.e. physical RAM minus a few reserved bits and the kernel binary code)

- **MemFree**

  Total free RAM. On highmem systems, the sum of LowFree+HighFree

- **MemAvailable**

  An estimate of how much memory is available for starting new applications, without swapping. Calculated from MemFree, SReclaimable, the size of the file LRU lists, and the low watermarks in each zone. The estimate takes into account that the system needs some page cache to function well, and that not all reclaimable slab will be reclaimable, due to items being in use. The impact of those factors will vary from system to system.

- **Buffers**

  Relatively temporary storage for raw disk blocks shouldn't get tremendously large (20MB or so)

- **Cached**

  In-memory cache for files read from the disk (the pagecache) as well as tmpfs &amp; shmem. Doesn't include SwapCached.

- **SwapCached**

  Memory that once was swapped out, is swapped back in but still also is in the swapfile (if memory is needed it doesn't need to be swapped out AGAIN because it is already in the swapfile. This saves I/O)

- **Active**

  Memory that has been used more recently and usually not reclaimed unless absolutely necessary.

- **Inactive**

  Memory which has been less recently used.  It is more eligible to be reclaimed for other purposes

- **Unevictable**

  Memory allocated for userspace which cannot be reclaimed, such as mlocked pages, ramfs backing pages, secret memfd pages etc.

- **Mlocked**

  Memory locked with mlock().

- **HighTotal, HighFree**

  Highmem is all memory above \~860MB of physical memory. Highmem areas are for use by userspace programs, or for the pagecache.  The kernel must use tricks to access this memory, making it slower to access than lowmem.

- **LowTotal, LowFree**

  Lowmem is memory which can be used for everything that highmem can be used for, but it is also available for the kernel's use for its own data structures.  Among many other things, it is where everything from the Slab is allocated.  Bad things happen when you're out of lowmem.

- **SwapTotal**

  total amount of swap space available

- **SwapFree**

  Memory which has been evicted from RAM, and is temporarily on the disk

- **Zswap**

  Memory consumed by the zswap backend (compressed size)

- **Zswapped**

  Amount of anonymous memory stored in zswap (original size)

- **Dirty**

  Memory which is waiting to get written back to the disk

- **Writeback**

  Memory which is actively being written back to the disk

- **AnonPages**

  Non-file backed pages mapped into userspace page tables. Note that some kernel configurations might consider all pages part of a larger allocation (e.g., THP) as "mapped", as soon as a single page is mapped.

- **Mapped**

  files which have been mmapped, such as libraries. Note that some kernel configurations might consider all pages part of a larger allocation (e.g., THP) as "mapped", as soon as a single page is mapped.

- **Shmem**

  Total memory used by shared memory (shmem) and tmpfs

- **KReclaimable**

  Kernel allocations that the kernel will attempt to reclaim under memory pressure. Includes SReclaimable (below), and other direct allocations with a shrinker.

- **Slab**

  in-kernel data structures cache

- **SReclaimable**

  Part of Slab, that might be reclaimed, such as caches

- **SUnreclaim**

  Part of Slab, that cannot be reclaimed on memory pressure

- **KernelStack**

  Memory consumed by the kernel stacks of all tasks

- **PageTables**

  Memory consumed by userspace page tables

- **SecPageTables**

  Memory consumed by secondary page tables, this currently includes KVM mmu and IOMMU allocations on x86 and arm64.

- **NFS_Unstable**

  Always zero. Previously counted pages which had been written to the server, but has not been committed to stable storage.

- **Bounce**

  Always zero. Previously memory used for block device "bounce buffers".

- **WritebackTmp**

  Always zero. Previously memory used by FUSE for temporary writeback buffers.

- **CommitLimit**

  Based on the overcommit ratio ('vm.overcommit_ratio'), this is the total amount of  memory currently available to be allocated on the system. This limit is only adhered to if strict overcommit accounting is enabled (mode 2 in 'vm.overcommit_memory').

  The CommitLimit is calculated with the following formula:



  ```text
  CommitLimit = ([total RAM pages] - [total huge TLB pages]) *
                 overcommit_ratio / 100 + [total swap pages]
  ```

  For example, on a system with 1G of physical RAM and 7G of swap with a `vm.overcommit_ratio` of 30 it would yield a CommitLimit of 7.3G.

  For more details, see the memory overcommit documentation in mm/overcommit-accounting.

- **Committed_AS**

  The amount of memory presently allocated on the system. The committed memory is a sum of all of the memory which has been allocated by processes, even if it has not been "used" by them as of yet. A process which malloc()'s 1G of memory, but only touches 300M of it will show up as using 1G. This 1G is memory which has been "committed" to by the VM and can be used at any time by the allocating application. With strict overcommit enabled on the system (mode 2 in 'vm.overcommit_memory'), allocations which would exceed the CommitLimit (detailed above) will not be permitted. This is useful if one needs to guarantee that processes will not fail due to lack of memory once that memory has been successfully allocated.

- **VmallocTotal**

  total size of vmalloc virtual address space

- **VmallocUsed**

  amount of vmalloc area which is used

- **VmallocChunk**

  largest contiguous block of vmalloc area which is free

- **Percpu**

  Memory allocated to the percpu allocator used to back percpu allocations. This stat excludes the cost of metadata.

- **EarlyMemtestBad**

  The amount of RAM/memory in kB, that was identified as corrupted by early memtest. If memtest was not run, this field will not be displayed at all. Size is never rounded down to 0 kB. That means if 0 kB is reported, you can safely assume there was at least one pass of memtest and none of the passes found a single faulty byte of RAM.

- **HardwareCorrupted**

  The amount of RAM/memory in KB, the kernel identifies as corrupted.

- **AnonHugePages**

  Non-file backed huge pages mapped into userspace page tables

- **ShmemHugePages**

  Memory used by shared memory (shmem) and tmpfs allocated with huge pages

- **ShmemPmdMapped**

  Shared memory mapped into userspace with huge pages

- **FileHugePages**

  Memory used for filesystem data (page cache) allocated with huge pages

- **FilePmdMapped**

  Page cache mapped into userspace with huge pages

- **CmaTotal**

  Memory reserved for the Contiguous Memory Allocator (CMA)

- **CmaFree**

  Free remaining memory in the CMA reserves

- **Unaccepted**

  Memory that has not been accepted by the guest

- **Balloon**

  Memory returned to Host by VM Balloon Drivers

- **HugePages_Total, HugePages_Free, HugePages_Rsvd, HugePages_Surp, Hugepagesize, Hugetlb**

  See [Documentation/admin-guide/mm/hugetlbpage.rst](/kernel/administration/admin-guide/mm/hugetlbpage.md).

- **DirectMap4k, DirectMap2M, DirectMap1G**

  Breakdown of page table sizes used in the kernel's identity mapping of RAM

<a id="rst-vmallocinfo"></a>

#### vmallocinfo

Provides information about vmalloced/vmaped areas. One line per area, containing the virtual address range of the area, size in bytes, caller information of the creator, and optional information depending on the kind of area:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> pages=nr
>
> </td>
> <td>
>
>
> number of pages
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> phys=addr
>
> </td>
> <td>
>
>
> if a physical address was specified
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ioremap
>
> </td>
> <td>
>
>
> I/O mapping (ioremap() and friends)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vmalloc
>
> </td>
> <td>
>
>
> vmalloc() area
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vmap
>
> </td>
> <td>
>
>
> vmap()ed pages
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> user
>
> </td>
> <td>
>
>
> VM_USERMAP area
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vpages
>
> </td>
> <td>
>
>
> buffer for pages pointers was vmalloced (huge area)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> N&lt;node&gt;=nr
>
> </td>
> <td>
>
>
> (Only on NUMA kernels) Number of pages allocated on memory node &lt;node&gt;
>
> </td>
> </tr>
> </tbody>
> </table>



```text
> cat /proc/vmallocinfo
0xffffc20000000000-0xffffc20000201000 2101248 alloc_large_system_hash+0x204 ...
/0x2c0 pages=512 vmalloc N0=128 N1=128 N2=128 N3=128
0xffffc20000201000-0xffffc20000302000 1052672 alloc_large_system_hash+0x204 ...
/0x2c0 pages=256 vmalloc N0=64 N1=64 N2=64 N3=64
0xffffc20000302000-0xffffc20000304000    8192 acpi_tb_verify_table+0x21/0x4f...
phys=7fee8000 ioremap
0xffffc20000304000-0xffffc20000307000   12288 acpi_tb_verify_table+0x21/0x4f...
phys=7fee7000 ioremap
0xffffc2000031d000-0xffffc2000031f000    8192 init_vdso_vars+0x112/0x210
0xffffc2000031f000-0xffffc2000032b000   49152 cramfs_uncompress_init+0x2e ...
/0x80 pages=11 vmalloc N0=3 N1=3 N2=2 N3=3
0xffffc2000033a000-0xffffc2000033d000   12288 sys_swapon+0x640/0xac0      ...
pages=2 vmalloc N1=2
0xffffc20000347000-0xffffc2000034c000   20480 xt_alloc_table_info+0xfe ...
/0x130 [x_tables] pages=4 vmalloc N0=4
0xffffffffa0000000-0xffffffffa000f000   61440 sys_init_module+0xc27/0x1d00 ...
pages=14 vmalloc N2=14
0xffffffffa000f000-0xffffffffa0014000   20480 sys_init_module+0xc27/0x1d00 ...
pages=4 vmalloc N1=4
0xffffffffa0014000-0xffffffffa0017000   12288 sys_init_module+0xc27/0x1d00 ...
pages=2 vmalloc N1=2
0xffffffffa0017000-0xffffffffa0022000   45056 sys_init_module+0xc27/0x1d00 ...
pages=10 vmalloc N0=10
```

<a id="rst-softirqs"></a>

#### softirqs

Provides counts of softirq handlers serviced since boot time, for each CPU.



```text
> cat /proc/softirqs
              CPU0       CPU1       CPU2       CPU3
    HI:          0          0          0          0
TIMER:       27166      27120      27097      27034
NET_TX:          0          0          0         17
NET_RX:         42          0          0         39
BLOCK:           0          0        107       1121
TASKLET:         0          0          0        290
SCHED:       27035      26983      26971      26746
HRTIMER:         0          0          0          0
    RCU:      1678       1769       2178       2250
```

<a id="rst-networking-info-in-proc-net"></a>

### 1.3 Networking info in /proc/net

The subdirectory  /proc/net  follows  the  usual  pattern. Table 1-8 shows the additional values  you  get  for  IP  version 6 if you configure the kernel to support this. Table 1-9 lists the files and their meaning.


<table>
<caption>Table 1-8: IPv6 info in /proc/net</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


udp6

</td>
<td>


UDP sockets (IPv6)

</td>
</tr>
<tr>
<td>


tcp6

</td>
<td>


TCP sockets (IPv6)

</td>
</tr>
<tr>
<td>


raw6

</td>
<td>


Raw device statistics (IPv6)

</td>
</tr>
<tr>
<td>


igmp6

</td>
<td>


IP multicast addresses, which this host joined (IPv6)

</td>
</tr>
<tr>
<td>


if_inet6

</td>
<td>


List of IPv6 interface addresses

</td>
</tr>
<tr>
<td>


ipv6_route

</td>
<td>


Kernel routing table for IPv6

</td>
</tr>
<tr>
<td>


rt6_stats

</td>
<td>


Global IPv6 routing tables statistics

</td>
</tr>
<tr>
<td>


sockstat6

</td>
<td>


Socket statistics (IPv6)

</td>
</tr>
<tr>
<td>


snmp6

</td>
<td>


Snmp data (IPv6)

</td>
</tr>
</tbody>
</table>


<table>
<caption>Table 1-9: Network info in /proc/net</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


arp

</td>
<td>


Kernel  ARP table

</td>
</tr>
<tr>
<td>


dev

</td>
<td>


network devices with statistics

</td>
</tr>
<tr>
<td>


dev_mcast

</td>
<td>


the Layer2 multicast groups a device is listening too (interface index, label, number of references, number of bound addresses).

</td>
</tr>
<tr>
<td>


dev_stat

</td>
<td>


network device status

</td>
</tr>
<tr>
<td>


ip_fwchains

</td>
<td>


Firewall chain linkage

</td>
</tr>
<tr>
<td>


ip_fwnames

</td>
<td>


Firewall chain names

</td>
</tr>
<tr>
<td>


ip_masq

</td>
<td>


Directory containing the masquerading tables

</td>
</tr>
<tr>
<td>


ip_masquerade

</td>
<td>


Major masquerading table

</td>
</tr>
<tr>
<td>


netstat

</td>
<td>


Network statistics

</td>
</tr>
<tr>
<td>


raw

</td>
<td>


raw device statistics

</td>
</tr>
<tr>
<td>


route

</td>
<td>


Kernel routing table

</td>
</tr>
<tr>
<td>


rpc

</td>
<td>


Directory containing rpc info

</td>
</tr>
<tr>
<td>


rt_cache

</td>
<td>


Routing cache

</td>
</tr>
<tr>
<td>


snmp

</td>
<td>


SNMP data

</td>
</tr>
<tr>
<td>


sockstat

</td>
<td>


Socket statistics

</td>
</tr>
<tr>
<td>


softnet_stat

</td>
<td>


Per-CPU incoming packets queues statistics of online CPUs

</td>
</tr>
<tr>
<td>


tcp

</td>
<td>


TCP  sockets

</td>
</tr>
<tr>
<td>


udp

</td>
<td>


UDP sockets

</td>
</tr>
<tr>
<td>


unix

</td>
<td>


UNIX domain sockets

</td>
</tr>
<tr>
<td>


wireless

</td>
<td>


Wireless interface data (Wavelan etc)

</td>
</tr>
<tr>
<td>


igmp

</td>
<td>


IP multicast addresses, which this host joined

</td>
</tr>
<tr>
<td>


psched

</td>
<td>


Global packet scheduler parameters.

</td>
</tr>
<tr>
<td>


netlink

</td>
<td>


List of PF_NETLINK sockets

</td>
</tr>
<tr>
<td>


ip_mr_vifs

</td>
<td>


List of multicast virtual interfaces

</td>
</tr>
<tr>
<td>


ip_mr_cache

</td>
<td>


List of multicast routing cache

</td>
</tr>
</tbody>
</table>

You can  use  this  information  to see which network devices are available in your system and how much traffic was routed over those devices:



```text
> cat /proc/net/dev
Inter-|Receive                                                   |[...
 face |bytes    packets errs drop fifo frame compressed multicast|[...
    lo:  908188   5596     0    0    0     0          0         0 [...
  ppp0:15475140  20721   410    0    0   410          0         0 [...
  eth0:  614530   7085     0    0    0     0          0         1 [...

...] Transmit
...] bytes    packets errs drop fifo colls carrier compressed
...]  908188     5596    0    0    0     0       0          0
...] 1375103    17405    0    0    0     0       0          0
...] 1703981     5535    0    0    0     3       0          0
```

In addition, each Channel Bond interface has its own directory.  For example, the bond0 device will have a directory called /proc/net/bond0/. It will contain information that is specific to that bond, such as the current slaves of the bond, the link status of the slaves, and how many times the slaves link has failed.

<a id="rst-scsi-info"></a>

### 1.4 SCSI info

If you have a SCSI or ATA host adapter in your system, you'll find a subdirectory named after the driver for this adapter in /proc/scsi. You'll also see a list of all recognized SCSI devices in /proc/scsi:



```text
>cat /proc/scsi/scsi
Attached devices:
Host: scsi0 Channel: 00 Id: 00 Lun: 00
  Vendor: IBM      Model: DGHS09U          Rev: 03E0
  Type:   Direct-Access                    ANSI SCSI revision: 03
Host: scsi0 Channel: 00 Id: 06 Lun: 00
  Vendor: PIONEER  Model: CD-ROM DR-U06S   Rev: 1.04
  Type:   CD-ROM                           ANSI SCSI revision: 02
```

The directory  named  after  the driver has one file for each adapter found in the system.  These  files  contain information about the controller, including the used  IRQ  and  the  IO  address range. The amount of information shown is dependent on  the adapter you use. The example shows the output for an Adaptec AHA-2940 SCSI adapter:



```text
> cat /proc/scsi/aic7xxx/0

Adaptec AIC7xxx driver version: 5.1.19/3.2.4
Compile Options:
  TCQ Enabled By Default : Disabled
  AIC7XXX_PROC_STATS     : Disabled
  AIC7XXX_RESET_DELAY    : 5
Adapter Configuration:
           SCSI Adapter: Adaptec AHA-294X Ultra SCSI host adapter
                           Ultra Wide Controller
    PCI MMAPed I/O Base: 0xeb001000
 Adapter SEEPROM Config: SEEPROM found and used.
      Adaptec SCSI BIOS: Enabled
                    IRQ: 10
                   SCBs: Active 0, Max Active 2,
                         Allocated 15, HW 16, Page 255
             Interrupts: 160328
      BIOS Control Word: 0x18b6
   Adapter Control Word: 0x005b
   Extended Translation: Enabled
Disconnect Enable Flags: 0xffff
     Ultra Enable Flags: 0x0001
 Tag Queue Enable Flags: 0x0000
Ordered Queue Tag Flags: 0x0000
Default Tag Queue Depth: 8
    Tagged Queue By Device array for aic7xxx host instance 0:
      {255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255}
    Actual queue depth per device for aic7xxx host instance 0:
      {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
Statistics:
(scsi0:0:0:0)
  Device using Wide/Sync transfers at 40.0 MByte/sec, offset 8
  Transinfo settings: current(12/8/1/0), goal(12/8/1/0), user(12/15/1/0)
  Total transfers 160151 (74577 reads and 85574 writes)
(scsi0:0:6:0)
  Device using Narrow/Sync transfers at 5.0 MByte/sec, offset 15
  Transinfo settings: current(50/15/0/0), goal(50/15/0/0), user(50/15/0/0)
  Total transfers 0 (0 reads and 0 writes)
```

<a id="rst-parallel-port-info-in-proc-parport"></a>

### 1.5 Parallel port info in /proc/parport

The directory  /proc/parport  contains information about the parallel ports of your system.  It  has  one  subdirectory  for  each port, named after the port number (0,1,2,...).

These directories contain the four files shown in Table 1-10.


<table>
<caption>Table 1-10: Files in /proc/parport</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


autoprobe

</td>
<td>


Any IEEE-1284 device ID information that has been acquired.

</td>
</tr>
<tr>
<td>


devices

</td>
<td>


list of the device drivers using that port. A + will appear by the name of the device currently using the port (it might not appear against any).

</td>
</tr>
<tr>
<td>


hardware

</td>
<td>


Parallel port's base address, IRQ line and DMA channel.

</td>
</tr>
<tr>
<td>


irq

</td>
<td>


IRQ that parport is using for that port. This is in a separate file to allow you to alter it by writing a new value in (IRQ number or none).

</td>
</tr>
</tbody>
</table>

<a id="rst-tty-info-in-proc-tty"></a>

### 1.6 TTY info in /proc/tty

Information about  the  available  and actually used tty's can be found in the directory /proc/tty. You'll find  entries  for drivers and line disciplines in this directory, as shown in Table 1-11.


<table>
<caption>Table 1-11: Files in /proc/tty</caption>
<thead>
<tr>
<th>


File

</th>
<th>


Content

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


drivers

</td>
<td>


list of drivers and their usage

</td>
</tr>
<tr>
<td>


ldiscs

</td>
<td>


registered line disciplines

</td>
</tr>
<tr>
<td>


driver/serial

</td>
<td>


usage statistic and status of single tty lines

</td>
</tr>
</tbody>
</table>

To see  which  tty's  are  currently in use, you can simply look into the file /proc/tty/drivers:



```text
> cat /proc/tty/drivers
pty_slave            /dev/pts      136   0-255 pty:slave
pty_master           /dev/ptm      128   0-255 pty:master
pty_slave            /dev/ttyp       3   0-255 pty:slave
pty_master           /dev/pty        2   0-255 pty:master
serial               /dev/cua        5   64-67 serial:callout
serial               /dev/ttyS       4   64-67 serial
/dev/tty0            /dev/tty0       4       0 system:vtmaster
/dev/ptmx            /dev/ptmx       5       2 system
/dev/console         /dev/console    5       1 system:console
/dev/tty             /dev/tty        5       0 system:/dev/tty
unknown              /dev/tty        4    1-63 console
```

<a id="rst-miscellaneous-kernel-statistics-in-proc-stat"></a>

### 1.7 Miscellaneous kernel statistics in /proc/stat

Various pieces   of  information about  kernel activity  are  available in the /proc/stat file.  All  of  the numbers reported  in  this file are  aggregates since the system first booted.  For a quick look, simply cat the file:



```text
> cat /proc/stat
cpu  237902850 368826709 106375398 1873517540 1135548 0 14507935 0 0 0
cpu0 60045249 91891769 26331539 468411416 495718 0 5739640 0 0 0
cpu1 59746288 91759249 26609887 468860630 312281 0 4384817 0 0 0
cpu2 59489247 92985423 26904446 467808813 171668 0 2268998 0 0 0
cpu3 58622065 92190267 26529524 468436680 155879 0 2114478 0 0 0
intr 8688370575 8 3373 0 0 0 0 0 0 1 40791 0 0 353317 0 0 0 0 224789828 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 190974333 41958554 123983334 43 0 224593 0 0 0 <more 0's deleted>
ctxt 22848221062
btime 1605316999
processes 746787147
procs_running 2
procs_blocked 0
softirq 12121874454 100099120 3938138295 127375644 2795979 187870761 0 173808342 3072582055 52608 224184354
```

The very first  "cpu" line aggregates the  numbers in all  of the other "cpuN" lines.  These numbers identify the amount of time the CPU has spent performing different kinds of work.  Time units are in USER_HZ (typically hundredths of a second).  The meanings of the columns are as follows, from left to right:

- user: normal processes executing in user mode

- nice: niced processes executing in user mode

- system: processes executing in kernel mode

- idle: twiddling thumbs

- iowait: In a word, iowait stands for waiting for I/O to complete. But there are several problems:

  1. CPU will not wait for I/O to complete, iowait is the time that a task is waiting for I/O to complete. When CPU goes into idle state for outstanding task I/O, another task will be scheduled on this CPU.

  2. In a multi-core CPU, the task waiting for I/O to complete is not running on any CPU, so the iowait of each CPU is difficult to calculate.

  3. The value of iowait field in /proc/stat will decrease in certain conditions.

  So, the iowait is not reliable by reading from /proc/stat.

- irq: servicing interrupts

- softirq: servicing softirqs

- steal: involuntary wait

- guest: running a normal guest

- guest_nice: running a niced guest

The "intr" line gives counts of interrupts  serviced since boot time, for each of the  possible system interrupts.   The first  column  is the  total of  all interrupts serviced  including  unnumbered  architecture specific  interrupts; each  subsequent column is the  total for that particular numbered interrupt. Unnumbered interrupts are not shown, only summed into the total.

The "ctxt" line gives the total number of context switches across all CPUs.

The "btime" line gives  the time at which the  system booted, in seconds since the Unix epoch.

The "processes" line gives the number  of processes and threads created, which includes (but  is not limited  to) those  created by  calls to the  fork() and clone() system calls.

The "procs_running" line gives the total number of threads that are running or ready to run (i.e., the total number of runnable threads).

The   "procs_blocked" line gives  the  number of  processes currently blocked, waiting for I/O to complete.

The "softirq" line gives counts of softirqs serviced since boot time, for each of the possible system softirqs. The first column is the total of all softirqs serviced; each subsequent column is the total for that particular softirq.

<a id="rst-ext4-file-system-parameters"></a>

### 1.8 Ext4 file system parameters

Information about mounted ext4 file systems can be found in /proc/fs/ext4.  Each mounted filesystem will have a directory in /proc/fs/ext4 based on its device name (i.e., /proc/fs/ext4/hdc or /proc/fs/ext4/sda9 or /proc/fs/ext4/dm-0).   The files in each per-device directory are shown in Table 1-12, below.


<table>
<caption>Table 1-12: Files in /proc/fs/ext4/&lt;devname&gt;</caption>
<tbody>
<tr>
<td>


File

</td>
<td>


Content

</td>
</tr>
<tr>
<td>


mb_groups

</td>
<td>


details of multiblock allocator buddy cache of free blocks

</td>
</tr>
</tbody>
</table>

<a id="rst-proc-consoles"></a>

### 1.9 /proc/consoles

Shows registered system console lines.

To see which character device lines are currently used for the system console /dev/console, you may simply look into the file /proc/consoles:



```text
> cat /proc/consoles
tty0                 -WU (ECp)       4:7
ttyS0                -W- (Ep)        4:64
```

The columns are:


<table>
<thead>
<tr>
<th>


device

</th>
<th>


name of the device

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


operations

</td>
<td>


- R = can do read operations

- W = can do write operations

- U = can do unblank

</td>
</tr>
<tr>
<td>


flags

</td>
<td>


- E = it is enabled

- C = it is preferred console

- B = it is primary boot console

- p = it is used for printk buffer

- b = it is not a TTY but a Braille device

- a = it is safe to use when cpu is offline

</td>
</tr>
<tr>
<td>


major:minor

</td>
<td>


major and minor number of the device separated by a colon

</td>
</tr>
</tbody>
</table>

<a id="rst-summary"></a>

### Summary

The /proc file system serves information about the running system. It not only allows access to process data but also allows you to request the kernel status by reading files in the hierarchy.

The directory  structure  of /proc reflects the types of information and makes it easy, if not obvious, where to look for specific data.

<a id="rst-chapter-2-modifying-system-parameters"></a>

## Chapter 2: Modifying System Parameters

<a id="rst-in-this-chapter-1"></a>

### In This Chapter

- Modifying kernel parameters by writing into files found in /proc/sys

- Exploring the files which modify certain parameters

- Review of the /proc/sys file tree

---

A very  interesting part of /proc is the directory /proc/sys. This is not only a source  of  information,  it also allows you to change parameters within the kernel. Be  very  careful  when attempting this. You can optimize your system, but you  can  also  cause  it  to  crash.  Never  alter kernel parameters on a production system.  Set  up  a  development machine and test to make sure that everything works  the  way  you want it to. You may have no alternative but to reboot the machine once an error has been made.

Writable `/proc/sys` entries accept values through their handler. The inherited `sysctl_perm()` path still selects mode bits using the current effective UID and groups, or a subsystem permission callback; read-only entries remain read-only. Handlers can impose additional capability checks, interpreted through KACS. There is no universal rule that every sysctl write is authorized by a native SD or by `SeTcbPrivilege` alone. Use the entry's documented handler and authorization requirements.

The files  in /proc/sys can be used to fine tune and monitor miscellaneous and general things  in  the operation of the Linux kernel. Since some of the files can inadvertently  disrupt  your  system,  it  is  advisable  to  read  both documentation and  source  before actually making adjustments. In any case, be very careful  when  writing  to  any  of these files. The entries in /proc may change slightly between the 2.1.\* and the 2.2 kernel, so if there is any doubt review the kernel documentation in the directory linux/Documentation. This chapter  is  heavily  based  on the documentation included in the pre 2.2 kernels, and became part of it in version 2.2.1 of the Linux kernel.

Please see: Documentation/admin-guide/sysctl/ directory for descriptions of these entries.

<a id="rst-summary-1"></a>

### Summary

Certain aspects  of  kernel  behavior  can be modified at runtime, without the need to  recompile  the kernel, or even to reboot the system. The files in the /proc/sys tree  can  not only be read, but also modified. You can use the echo command to write value into these files, thereby changing the default settings of the kernel.

<a id="rst-chapter-3-per-process-parameters"></a>

## Chapter 3: Per-process Parameters

<a id="rst-proc-pid-oom-adj-proc-pid-oom-score-adj-adjust-the-oom-killer-score"></a>

### 3.1 /proc/&lt;pid&gt;/oom_adj &amp; /proc/&lt;pid&gt;/oom_score_adj- Adjust the oom-killer score

These files can be used to adjust the badness heuristic used to select which process gets killed in out of memory (oom) conditions.

The badness heuristic assigns a value to each candidate task ranging from 0 (never kill) to 1000 (always kill) to determine which process is targeted.  The units are roughly a proportion along that range of allowed memory the process may allocate from based on an estimation of its current memory and swap use. For example, if a task is using all allowed memory, its badness score will be 1000.  If it is using half of its allowed memory, its score will be 500.

The amount of "allowed" memory depends on the context in which the oom killer was called.  If it is due to the memory assigned to the allocating task's cpuset being exhausted, the allowed memory represents the set of mems assigned to that cpuset.  If it is due to a mempolicy's node(s) being exhausted, the allowed memory represents the set of mempolicy nodes.  If it is due to a memory limit (or swap limit) being reached, the allowed memory is that configured limit.  Finally, if it is due to the entire system being out of memory, the allowed memory represents all allocatable resources.

The value of /proc/&lt;pid&gt;/oom_score_adj is added to the badness score before it is used to determine which task to kill.  Acceptable values range from -1000 (OOM_SCORE_ADJ_MIN) to +1000 (OOM_SCORE_ADJ_MAX).  This allows userspace to polarize the preference for oom killing either by always preferring a certain task or completely disabling it.  The lowest possible value, -1000, is equivalent to disabling oom killing entirely for that task since it will always report a badness score of 0.

Consequently, it is very simple for userspace to define the amount of memory to consider for each task.  Setting a /proc/&lt;pid&gt;/oom_score_adj value of +500, for example, is roughly equivalent to allowing the remainder of tasks sharing the same system, cpuset, mempolicy, or memory controller resources to use at least 50% more memory.  A value of -500, on the other hand, would be roughly equivalent to discounting 50% of the task's allowed memory from being considered as scoring against the task.

For backwards compatibility with previous kernels, /proc/&lt;pid&gt;/oom_adj may also be used to tune the badness score.  Its acceptable values range from -16 (OOM_ADJUST_MIN) to +15 (OOM_ADJUST_MAX) and a special value of -17 (OOM_DISABLE) to disable oom killing entirely for that task.  Its value is scaled linearly with /proc/&lt;pid&gt;/oom_score_adj.

The value of /proc/&lt;pid&gt;/oom_score_adj may be reduced no lower than the last value set by a CAP_SYS_RESOURCE process. To reduce the value any lower requires CAP_SYS_RESOURCE, which maps to enabled `SeIncreaseQuotaPrivilege` in Peios. The write also needs native process set-information authorization. If an update would affect other processes sharing the memory map, Peios checks those targets too and can reject the update with `EACCES`.

<a id="rst-proc-pid-oom-score-display-current-oom-killer-score"></a>

### 3.2 /proc/&lt;pid&gt;/oom_score - Display current oom-killer score

This file can be used to check the current score used by the oom-killer for any given &lt;pid&gt;. Use it together with /proc/&lt;pid&gt;/oom_score_adj to tune which process should be killed in an out-of-memory situation.

Please note that the exported value includes oom_score_adj so it is effectively in range \[0,2000\].

<a id="rst-proc-pid-io-display-the-io-accounting-fields"></a>

### 3.3  /proc/&lt;pid&gt;/io - Display the IO accounting fields

This file contains IO statistics for each running process.

<a id="rst-example"></a>

#### Example



```text
test:/tmp # dd if=/dev/zero of=/tmp/test.dat &
[1] 3828

test:/tmp # cat /proc/3828/io
rchar: 323934931
wchar: 323929600
syscr: 632687
syscw: 632675
read_bytes: 0
write_bytes: 323932160
cancelled_write_bytes: 0
```

<a id="rst-description"></a>

#### Description

<a id="rst-rchar"></a>

##### rchar

I/O counter: chars read The number of bytes which this task has caused to be read from storage. This is simply the sum of bytes which this process passed to read() and pread(). It includes things like tty IO and it is unaffected by whether or not actual physical disk IO was required (the read might have been satisfied from pagecache).

<a id="rst-wchar"></a>

##### wchar

I/O counter: chars written The number of bytes which this task has caused, or shall cause to be written to disk. Similar caveats apply here as with rchar.

<a id="rst-syscr"></a>

##### syscr

I/O counter: read syscalls Attempt to count the number of read I/O operations, i.e. syscalls like read() and pread().

<a id="rst-syscw"></a>

##### syscw

I/O counter: write syscalls Attempt to count the number of write I/O operations, i.e. syscalls like write() and pwrite().

<a id="rst-read-bytes"></a>

##### read_bytes

I/O counter: bytes read Attempt to count the number of bytes which this process really did cause to be fetched from the storage layer. Done at the submit_bio() level, so it is accurate for block-backed filesystems. &lt;please add status regarding NFS and CIFS at a later time&gt;

<a id="rst-write-bytes"></a>

##### write_bytes

I/O counter: bytes written Attempt to count the number of bytes which this process caused to be sent to the storage layer. This is done at page-dirtying time.

<a id="rst-cancelled-write-bytes"></a>

##### cancelled_write_bytes

The big inaccuracy here is truncate. If a process writes 1MB to a file and then deletes the file, it will in fact perform no writeout. But it will have been accounted as having caused 1MB of write. In other words: The number of bytes which this process caused to not happen, by truncating pagecache. A task can cause "negative" IO too. If this task truncates some dirty pagecache, some IO which another task has been accounted for (in its write_bytes) will not be happening. We \_could\_ just subtract that from the truncating task's write_bytes, but there is information loss in doing that.

> [!NOTE]
>
> At its current implementation state, this is a bit racy on 32-bit machines: if process A reads process B's /proc/pid/io while process B is updating one of those 64-bit counters, process A could see an intermediate result.

More information about this can be found within the taskstats documentation in Documentation/accounting.

<a id="rst-proc-pid-coredump-filter-core-dump-filtering-settings"></a>

### 3.4 /proc/&lt;pid&gt;/coredump_filter - Core dump filtering settings

When a process is dumped, all anonymous memory is written to a core file as long as the size of the core file isn't limited. But sometimes we don't want to dump some memory segments, for example, huge shared memory or DAX. Conversely, sometimes we want to save file-backed memory segments into a core file, not only the individual files.

/proc/&lt;pid&gt;/coredump_filter allows you to customize which memory segments will be dumped when the &lt;pid&gt; process is dumped. coredump_filter is a bitmask of memory types. If a bit of the bitmask is set, memory segments of the corresponding memory type are dumped, otherwise they are not dumped.

The following 9 memory types are supported:

> - (bit 0) anonymous private memory
>
> - (bit 1) anonymous shared memory
>
> - (bit 2) file-backed private memory
>
> - (bit 3) file-backed shared memory
>
> - (bit 4) ELF header pages in file-backed private memory areas (it is effective only if the bit 2 is cleared)
>
> - (bit 5) hugetlb private memory
>
> - (bit 6) hugetlb shared memory
>
> - (bit 7) DAX private memory
>
> - (bit 8) DAX shared memory
>
> Note that MMIO pages such as frame buffer are never dumped and vDSO pages are always dumped regardless of the bitmask status.
>
> Note that bits 0-4 don't affect hugetlb or DAX memory. hugetlb memory is only affected by bit 5-6, and DAX is only affected by bits 7-8.

The default value of coredump_filter is 0x33; this means all anonymous memory segments, ELF header pages and hugetlb private memory are dumped.

If you don't want to dump all shared memory segments attached to pid 1234, write 0x31 to the process's proc file:



```text
$ echo 0x31 > /proc/1234/coredump_filter
```

When a new process is created, the process inherits the bitmask status from its parent. It is useful to set up coredump_filter before the program runs. For example:



```text
$ echo 0x7 > /proc/self/coredump_filter
$ ./some_program
```

<a id="rst-proc-pid-mountinfo-information-about-mounts"></a>

### 3.5     /proc/&lt;pid&gt;/mountinfo - Information about mounts

This file contains lines of the form:



```text
36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
(1)(2)(3)   (4)   (5)      (6)     (n…m) (m+1)(m+2) (m+3)         (m+4)

(1)   mount ID:        unique identifier of the mount (may be reused after umount)
(2)   parent ID:       ID of parent (or of self for the top of the mount tree)
(3)   major:minor:     value of st_dev for files on filesystem
(4)   root:            root of the mount within the filesystem
(5)   mount point:     mount point relative to the process's root
(6)   mount options:   per mount options
(n…m) optional fields: zero or more fields of the form "tag[:value]"
(m+1) separator:       marks the end of the optional fields
(m+2) filesystem type: name of filesystem of the form "type[.subtype]"
(m+3) mount source:    filesystem specific information or "none"
(m+4) super options:   per super block options
```

Parsers should ignore all unrecognised optional fields.  Currently the possible optional fields are:


<table>
<tbody>
<tr>
<td>


shared:X

</td>
<td>


mount is shared in peer group X

</td>
</tr>
<tr>
<td>


master:X

</td>
<td>


mount is slave to peer group X

</td>
</tr>
<tr>
<td>


propagate_from:X

</td>
<td>


mount is slave and receives propagation from peer group X <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

</td>
</tr>
<tr>
<td>


unbindable

</td>
<td>


mount is unbindable

</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-1"></a>



**[1]** X is the closest dominant peer group under the process's root.  If X is the immediate master of the mount, or if there's no dominant peer group under the same root, then only the "master:X" field is present and not the "propagate_from:X" field.

For more information on mount propagation see:

> [Documentation/filesystems/sharedsubtree.rst](/kernel/internals/filesystems/sharedsubtree.md)

<a id="rst-proc-pid-comm-proc-pid-task-tid-comm"></a>

### 3.6     /proc/&lt;pid&gt;/comm  &amp; /proc/&lt;pid&gt;/task/&lt;tid&gt;/comm

These files provide a method to access a task's comm value. It also allows for a task to set its own or one of its thread siblings comm value. The comm value is limited in size compared to the cmdline value, so writing anything longer then the kernel's TASK_COMM_LEN (currently 16 chars, including the NUL terminator) will result in a truncated comm value.

<a id="rst-proc-pid-task-tid-children-information-about-task-children"></a>

### 3.7     /proc/&lt;pid&gt;/task/&lt;tid&gt;/children - Information about task children

This file provides a fast way to retrieve first level children pids of a task pointed by &lt;pid&gt;/&lt;tid&gt; pair. The format is a space separated stream of pids.

Note the "first level" here -- if a child has its own children they will not be listed here; one needs to read /proc/&lt;children-pid&gt;/task/&lt;tid&gt;/children to obtain the descendants.

Since this interface is intended to be fast and cheap it doesn't guarantee to provide precise results and some children might be skipped, especially if they've exited right after we printed their pids, so one needs to either stop or freeze processes being inspected if precise results are needed.

<a id="rst-proc-pid-fdinfo-fd-information-about-opened-file"></a>

### 3.8     /proc/&lt;pid&gt;/fdinfo/&lt;fd&gt; - Information about opened file

This file provides information associated with an opened file. The regular files have at least four fields -- 'pos', 'flags', 'mnt_id' and 'ino'. The 'pos' represents the current offset of the opened file in decimal form \[see lseek(2) for details\], 'flags' denotes the octal O_xxx mask the file has been created with \[see open(2) for details\] and 'mnt_id' represents mount ID of the file system containing the opened file \[see 3.5 /proc/&lt;pid&gt;/mountinfo for details\]. 'ino' represents the inode number of the file.

A typical output is:



```text
pos:    0
flags:  0100002
mnt_id: 19
ino:    63107
```

All locks associated with a file descriptor are shown in its fdinfo too:



```text
lock:       1: FLOCK  ADVISORY  WRITE 359 00:13:11691 0 EOF
```

The files such as eventfd, fsnotify, signalfd, epoll among the regular pos/flags pair provide additional information particular to the objects they represent.

<a id="rst-eventfd-files"></a>

#### Eventfd files



```text
pos:    0
flags:  04002
mnt_id: 9
ino:    63107
eventfd-count:  5a
```

where 'eventfd-count' is hex value of a counter.

<a id="rst-signalfd-files"></a>

#### Signalfd files



```text
pos:    0
flags:  04002
mnt_id: 9
ino:    63107
sigmask:        0000000000000200
```

where 'sigmask' is hex value of the signal mask associated with a file.

<a id="rst-epoll-files"></a>

#### Epoll files



```text
pos:    0
flags:  02
mnt_id: 9
ino:    63107
tfd:        5 events:       1d data: ffffffffffffffff pos:0 ino:61af sdev:7
```

where 'tfd' is a target file descriptor number in decimal form, 'events' is events mask being watched and the 'data' is data associated with a target \[see epoll(7) for more details\].

The 'pos' is current offset of the target file in decimal form \[see lseek(2)\], 'ino' and 'sdev' are inode and device numbers where target file resides, all in hex format.

<a id="rst-fsnotify-files"></a>

#### Fsnotify files

For inotify files the format is the following:



```text
pos:    0
flags:  02000000
mnt_id: 9
ino:    63107
inotify wd:3 ino:9e7e sdev:800013 mask:800afce ignored_mask:0 fhandle-bytes:8 fhandle-type:1 f_handle:7e9e0000640d1b6d
```

where 'wd' is a watch descriptor in decimal form, i.e. a target file descriptor number, 'ino' and 'sdev' are inode and device where the target file resides and the 'mask' is the mask of events, all in hex form \[see inotify(7) for more details\].

If the kernel was built with exportfs support, the path to the target file is encoded as a file handle.  The file handle is provided by three fields 'fhandle-bytes', 'fhandle-type' and 'f_handle', all in hex format.

If the kernel is built without exportfs support the file handle won't be printed out.

If there is no inotify mark attached yet the 'inotify' line will be omitted.

For fanotify files the format is:



```text
pos:    0
flags:  02
mnt_id: 9
ino:    63107
fanotify flags:10 event-flags:0
fanotify mnt_id:12 mflags:40 mask:38 ignored_mask:40000003
fanotify ino:4f969 sdev:800013 mflags:0 mask:3b ignored_mask:40000000 fhandle-bytes:8 fhandle-type:1 f_handle:69f90400c275b5b4
```

where fanotify 'flags' and 'event-flags' are values used in fanotify_init call, 'mnt_id' is the mount point identifier, 'mflags' is the value of flags associated with mark which are tracked separately from events mask. 'ino' and 'sdev' are target inode and device, 'mask' is the events mask and 'ignored_mask' is the mask of events which are to be ignored. All are in hex format. Incorporation of 'mflags', 'mask' and 'ignored_mask' provide information about flags and mask used in fanotify_mark call \[see fsnotify manpage for details\].

While the first three lines are mandatory and always printed, the rest is optional and may be omitted if no marks created yet.

<a id="rst-timerfd-files"></a>

#### Timerfd files



```text
pos:    0
flags:  02
mnt_id: 9
ino:    63107
clockid: 0
ticks: 0
settime flags: 01
it_value: (0, 49406829)
it_interval: (1, 0)
```

where 'clockid' is the clock type and 'ticks' is the number of the timer expirations that have occurred \[see timerfd_create(2) for details\]. 'settime flags' are flags in octal form been used to setup the timer \[see timerfd_settime(2) for details\]. 'it_value' is remaining time until the timer expiration. 'it_interval' is the interval for the timer. Note the timer might be set up with TIMER_ABSTIME option which will be shown in 'settime flags', but 'it_value' still exhibits timer's remaining time.

<a id="rst-dma-buffer-files"></a>

#### DMA Buffer files



```text
pos:    0
flags:  04002
mnt_id: 9
ino:    63107
size:   32768
count:  2
exp_name:  system-heap
```

where 'size' is the size of the DMA buffer in bytes. 'count' is the file count of the DMA buffer file. 'exp_name' is the name of the DMA buffer exporter.

<a id="rst-vfio-device-files"></a>

#### VFIO Device files



```text
pos:    0
flags:  02000002
mnt_id: 17
ino:    5122
vfio-device-syspath: /sys/devices/pci0000:e0/0000:e0:01.1/0000:e1:00.0/0000:e2:05.0/0000:e8:00.0
```

where 'vfio-device-syspath' is the sysfs path corresponding to the VFIO device file.

<a id="rst-proc-pid-map-files-information-about-memory-mapped-files"></a>

### 3.9     /proc/&lt;pid&gt;/map_files - Information about memory mapped files

This directory contains symbolic links which represent memory mapped files the process is maintaining.  Example output:



```text
| lr-------- 1 root root 64 Jan 27 11:24 333c600000-333c620000 -> /usr/lib64/ld-2.18.so
| lr-------- 1 root root 64 Jan 27 11:24 333c81f000-333c820000 -> /usr/lib64/ld-2.18.so
| lr-------- 1 root root 64 Jan 27 11:24 333c820000-333c821000 -> /usr/lib64/ld-2.18.so
| ...
| lr-------- 1 root root 64 Jan 27 11:24 35d0421000-35d0422000 -> /usr/lib64/libselinux.so.1
| lr-------- 1 root root 64 Jan 27 11:24 400000-41a000 -> /usr/bin/ls
```

The name of a link represents the virtual memory bounds of a mapping, i.e. vm_area_struct::vm_start-vm_area_struct::vm_end.

The main purpose of the map_files is to retrieve a set of memory mapped files in a fast way instead of parsing /proc/&lt;pid&gt;/maps or /proc/&lt;pid&gt;/smaps, both of which contain many more records.  At the same time one can open(2) mappings from the listings of two processes and comparing their inode numbers to figure out which anonymous memory areas are actually shared.

<a id="rst-proc-pid-timerslack-ns-task-timerslack-value"></a>

### 3.10    /proc/&lt;pid&gt;/timerslack_ns - Task timerslack value

This file provides the value of the task's timerslack value in nanoseconds. This value specifies an amount of time that normal timers may be deferred in order to coalesce timers and avoid unnecessary wakeups.

This allows a task's interactivity vs power consumption tradeoff to be adjusted.

Writing 0 to the file will set the task's timerslack to the default value.

Valid values are from 0 - ULLONG_MAX

An application setting the value must have PTRACE_MODE_ATTACH_FSCREDS level permissions on the task specified to change its timerslack_ns value.

<a id="rst-proc-pid-patch-state-livepatch-patch-operation-state"></a>

### 3.11    /proc/&lt;pid&gt;/patch_state - Livepatch patch operation state

When CONFIG_LIVEPATCH is enabled, this file displays the value of the patch state for the task.

A value of '-1' indicates that no patch is in transition.

A value of '0' indicates that a patch is in transition and the task is unpatched.  If the patch is being enabled, then the task hasn't been patched yet.  If the patch is being disabled, then the task has already been unpatched.

A value of '1' indicates that a patch is in transition and the task is patched.  If the patch is being enabled, then the task has already been patched.  If the patch is being disabled, then the task hasn't been unpatched yet.

<a id="rst-proc-pid-arch-status-task-architecture-specific-status"></a>

### 3.12 /proc/&lt;pid&gt;/arch_status - task architecture specific status

When CONFIG_PROC_PID_ARCH_STATUS is enabled, this file displays the architecture specific status of the task.

<a id="rst-example-1"></a>

#### Example



```text
$ cat /proc/6753/arch_status
AVX512_elapsed_ms:      8
```

<a id="rst-description-1"></a>

#### Description

<a id="rst-x86-specific-entries"></a>

#### x86 specific entries

<a id="rst-avx512-elapsed-ms"></a>

##### AVX512_elapsed_ms

> If AVX512 is supported on the machine, this entry shows the milliseconds elapsed since the last time AVX512 usage was recorded. The recording happens on a best effort basis when a task is scheduled out. This means that the value depends on two factors:
>
> > 1. The time which the task spent on the CPU without being scheduled out. With CPU isolation and a single runnable task this can take several seconds.
> >
> > 2. The time since the task was scheduled out last. Depending on the reason for being scheduled out (time slice exhausted, syscall ...) this can be arbitrary long time.
>
> As a consequence the value cannot be considered precise and authoritative information. The application which uses this information has to be aware of the overall scenario on the system in order to determine whether a task is a real AVX512 user or not. Precise information can be obtained with performance counters.
>
> A special value of '-1' indicates that no AVX512 usage was recorded, thus the task is unlikely an AVX512 user, but depends on the workload and the scheduling scenario, it also could be a false negative mentioned above.

<a id="rst-proc-pid-fd-list-of-symlinks-to-open-files"></a>

### 3.13 /proc/&lt;pid&gt;/fd - List of symlinks to open files

This directory contains symbolic links which represent open files the process is maintaining.  Example output:



```text
lr-x------ 1 root root 64 Sep 20 17:53 0 -> /dev/null
l-wx------ 1 root root 64 Sep 20 17:53 1 -> /dev/null
lrwx------ 1 root root 64 Sep 20 17:53 10 -> 'socket:[12539]'
lrwx------ 1 root root 64 Sep 20 17:53 11 -> 'socket:[12540]'
lrwx------ 1 root root 64 Sep 20 17:53 12 -> 'socket:[12542]'
```

The number of open files for the process is stored in 'size' member of stat() output for /proc/&lt;pid&gt;/fd for fast access. -------------------------------------------------------

<a id="rst-proc-pid-ksm-stat-information-about-the-process-s-ksm-status"></a>

### 3.14 /proc/&lt;pid&gt;/ksm_stat - Information about the process's ksm status

When CONFIG_KSM is enabled, each process has this file which displays the information of ksm merging status.

<a id="rst-example-2"></a>

#### Example



```text
/ # cat /proc/self/ksm_stat
ksm_rmap_items 0
ksm_zero_pages 0
ksm_merging_pages 0
ksm_process_profit 0
ksm_merge_any: no
ksm_mergeable: no
```

<a id="rst-description-2"></a>

#### Description

<a id="rst-ksm-rmap-items"></a>

##### ksm_rmap_items

The number of ksm_rmap_item structures in use.  The structure ksm_rmap_item stores the reverse mapping information for virtual addresses.  KSM will generate a ksm_rmap_item for each ksm-scanned page of the process.

<a id="rst-ksm-zero-pages"></a>

##### ksm_zero_pages

When /sys/kernel/mm/ksm/use_zero_pages is enabled, it represent how many empty pages are merged with kernel zero pages by KSM.

<a id="rst-ksm-merging-pages"></a>

##### ksm_merging_pages

It represents how many pages of this process are involved in KSM merging (not including ksm_zero_pages). It is the same with what /proc/&lt;pid&gt;/ksm_merging_pages shows.

<a id="rst-ksm-process-profit"></a>

##### ksm_process_profit

The profit that KSM brings (Saved bytes). KSM can save memory by merging identical pages, but also can consume additional memory, because it needs to generate a number of rmap_items to save each scanned page's brief rmap information. Some of these pages may be merged, but some may not be abled to be merged after being checked several times, which are unprofitable memory consumed.

<a id="rst-ksm-merge-any"></a>

##### ksm_merge_any

It specifies whether the process's 'mm is added by prctl() into the candidate list of KSM or not, and if KSM scanning is fully enabled at process level.

<a id="rst-ksm-mergeable"></a>

##### ksm_mergeable

It specifies whether any VMAs of the process''s mms are currently applicable to KSM.

More information about KSM can be found in [Documentation/admin-guide/mm/ksm.rst](/kernel/administration/admin-guide/mm/ksm.md).

<a id="rst-chapter-4-configuring-procfs"></a>

## Chapter 4: Configuring procfs

<a id="rst-mount-options"></a>

### 4.1     Mount options

The following mount options are supported:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> hidepid=
>
> </td>
> <td>
>
>
> Set /proc/&lt;pid&gt;/ access mode.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gid=
>
> </td>
> <td>
>
>
> Set the group authorized to learn processes information.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> subset=
>
> </td>
> <td>
>
>
> Show only the specified subset of procfs.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> pidns=
>
> </td>
> <td>
>
>
> Specify a the namespace used by this procfs.
>
> </td>
> </tr>
> </tbody>
> </table>

`hidepid=off` or `hidepid=0` disables the hidepid visibility restriction
(the default). It does not disable per-entry native process-access checks.

`hidepid=noaccess` or `hidepid=1` restricts access to process directories;
`hidepid=invisible` or `hidepid=2` also hides denied directories from enumeration
and reports them as absent. For these modes, membership in the configured
`gid` group bypasses the hidepid filter; otherwise the filter calls
`ptrace_may_access(..., PTRACE_MODE_READ_FSCREDS)`. In Peios that path uses native
process-read authorization and PIP, not simply equal Unix ownership.

`hidepid=ptraceable` or `hidepid=4` always uses that read-mode ptrace check,
including for members of the configured group. It does not test whether a
write-mode ptrace attachment would be allowed.

`gid=` selects an exception to the hidepid filter, not a grant of the native
rights required by individual proc entries. Changing supplementary Unix groups
is not a native token-delegation operation. These options also do not guarantee
that a process's existence cannot be inferred through other interfaces.

subset=pid hides all top level files and directories in the procfs that are not related to tasks.

pidns= specifies a pid namespace (either as a string path to something like `/proc/$pid/ns/pid`, or a file descriptor when using `FSCONFIG_SET_FD`) that will be used by the procfs instance when translating pids. By default, procfs will use the calling process's active pid namespace. Note that the pid namespace of an existing procfs instance cannot be modified (attempting to do so will give an `-EBUSY` error).

<a id="rst-chapter-5-filesystem-behavior"></a>

## Chapter 5: Filesystem behavior

Originally, before the advent of pid namespace, procfs was a global file system. It means that there was only one procfs instance in the system.

When pid namespace was added, a separate procfs instance was mounted in each pid namespace. So, procfs mount options are global among all mountpoints within the same namespace:



```text
# grep ^proc /proc/mounts
proc /proc proc rw,relatime,hidepid=2 0 0

# strace -e mount mount -o hidepid=1 -t proc proc /tmp/proc
mount("proc", "/tmp/proc", "proc", 0, "hidepid=1") = 0
+++ exited with 0 +++

# grep ^proc /proc/mounts
proc /proc proc rw,relatime,hidepid=2 0 0
proc /tmp/proc proc rw,relatime,hidepid=2 0 0
```

and only after remounting procfs mount options will change at all mountpoints:



```text
# mount -o remount,hidepid=1 -t proc proc /tmp/proc

# grep ^proc /proc/mounts
proc /proc proc rw,relatime,hidepid=1 0 0
proc /tmp/proc proc rw,relatime,hidepid=1 0 0
```

This behavior is different from the behavior of other filesystems.

The new procfs behavior is more like other filesystems. Each procfs mount creates a new procfs instance. Mount options affect own procfs instance. It means that it became possible to have several procfs instances displaying tasks with different filtering options in one pid namespace:



```text
# mount -o hidepid=invisible -t proc proc /proc
# mount -o hidepid=noaccess -t proc proc /tmp/proc
# grep ^proc /proc/mounts
proc /proc proc rw,relatime,hidepid=invisible 0 0
proc /tmp/proc proc rw,relatime,hidepid=noaccess 0 0
```

---

# The QNX6 Filesystem

_Peios Kernel / Internals / Filesystems_

> The qnx6fs is used by newer QNX operating system versions. (e.g. Neutrino) It got introduced in QNX 6.4.0 and is used default since 6.4.1.

<a id="rst-the-qnx6-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The qnx6fs is used by newer QNX operating system versions. (e.g. Neutrino) It got introduced in QNX 6.4.0 and is used default since 6.4.1.

<a id="rst-option"></a>

## Option

mmi_fs          Mount filesystem as used for example by Audi MMI 3G system

<a id="rst-specification"></a>

## Specification

qnx6fs shares many properties with traditional Unix filesystems. It has the concepts of blocks, inodes and directories.

On QNX it is possible to create little endian and big endian qnx6 filesystems. This feature makes it possible to create and use a different endianness fs for the target (QNX is used on quite a range of embedded systems) platform running on a different endianness.

The Linux driver handles endianness transparently. (LE and BE)

<a id="rst-blocks"></a>

### Blocks

The space in the device or file is split up into blocks. These are a fixed size of 512, 1024, 2048 or 4096, which is decided when the filesystem is created.

Blockpointers are 32bit, so the maximum space that can be addressed is 2^32 \* 4096 bytes or 16TB

<a id="rst-the-superblocks"></a>

### The superblocks

The superblock contains all global information about the filesystem. Each qnx6fs got two superblocks, each one having a 64bit serial number. That serial number is used to identify the "active" superblock. In write mode with reach new snapshot (after each synchronous write), the serial of the new master superblock is increased (old superblock serial + 1)

So basically the snapshot functionality is realized by an atomic final update of the serial number. Before updating that serial, all modifications are done by copying all modified blocks during that specific write request (or period) and building up a new (stable) filesystem structure under the inactive superblock.

Each superblock holds a set of root inodes for the different filesystem parts. (Inode, Bitmap and Longfilenames) Each of these root nodes holds information like total size of the stored data and the addressing levels in that specific tree. If the level value is 0, up to 16 direct blocks can be addressed by each node.

Level 1 adds an additional indirect addressing level where each indirect addressing block holds up to blocksize / 4 bytes pointers to data blocks. Level 2 adds an additional indirect addressing block level (so, already up to 16 \* 256 \* 256 = 1048576 blocks that can be addressed by such a tree).

Unused block pointers are always set to \~0 - regardless of root node, indirect addressing blocks or inodes.

Data leaves are always on the lowest level. So no data is stored on upper tree levels.

The first Superblock is located at 0x2000. (0x2000 is the bootblock size) The Audi MMI 3G first superblock directly starts at byte 0.

Second superblock position can either be calculated from the superblock information (total number of filesystem blocks) or by taking the highest device address, zeroing the last 3 bytes and then subtracting 0x1000 from that address.

0x1000 is the size reserved for each superblock - regardless of the blocksize of the filesystem.

<a id="rst-inodes"></a>

### Inodes

Each object in the filesystem is represented by an inode. (index node) The inode structure contains pointers to the filesystem blocks which contain the data held in the object and all of the metadata about an object except its longname. (filenames longer than 27 characters) The metadata about an object includes the permissions, owner, group, flags, size, number of blocks used, access time, change time and modification time.

Object mode field is POSIX format. (which makes things easier)

There are also pointers to the first 16 blocks, if the object data can be addressed with 16 direct blocks.

For more than 16 blocks an indirect addressing in form of another tree is used. (scheme is the same as the one used for the superblock root nodes)

The filesize is stored 64bit. Inode counting starts with 1. (while long filename inodes start with 0)

<a id="rst-directories"></a>

### Directories

A directory is a filesystem object and has an inode just like a file. It is a specially formatted file containing records which associate each name with an inode number.

'.' inode number points to the directory inode

'..' inode number points to the parent directory inode

Eeach filename record additionally got a filename length field.

One special case are long filenames or subdirectory names.

These got set a filename length field of 0xff in the corresponding directory record plus the longfile inode number also stored in that record.

With that longfilename inode number, the longfilename tree can be walked starting with the superblock longfilename root node pointers.

<a id="rst-special-files"></a>

### Special files

Symbolic links are also filesystem objects with inodes. They got a specific bit in the inode mode field identifying them as symbolic link.

The directory entry file inode pointer points to the target file inode.

Hard links got an inode, a directory entry, but a specific mode bit set, no block pointers and the directory file record pointing to the target file inode.

Character and block special devices do not exist in QNX as those files are handled by the QNX kernel/drivers and created in /dev independent of the underlying filesystem.

<a id="rst-long-filenames"></a>

### Long filenames

Long filenames are stored in a separate addressing tree. The staring point is the longfilename root node in the active superblock.

Each data block (tree leaves) holds one long filename. That filename is limited to 510 bytes. The first two starting bytes are used as length field for the actual filename.

If that structure shall fit for all allowed blocksizes, it is clear why there is a limit of 510 bytes for the actual filename stored.

<a id="rst-bitmap"></a>

### Bitmap

The qnx6fs filesystem allocation bitmap is stored in a tree under bitmap root node in the superblock and each bit in the bitmap represents one filesystem block.

The first block is block 0, which starts 0x1000 after superblock start. So for a normal qnx6fs 0x3000 (bootblock + superblock) is the physical address at which block 0 is located.

Bits at the end of the last bitmap block are set to 1, if the device is smaller than addressing space in the bitmap.

<a id="rst-bitmap-system-area"></a>

### Bitmap system area

The bitmap itself is divided into three parts.

First the system area, that is split into two halves.

Then userspace.

The requirement for a static, fixed preallocated system area comes from how qnx6fs deals with writes.

Each superblock got its own half of the system area. So superblock \#1 always uses blocks from the lower half while superblock \#2 just writes to blocks represented by the upper half bitmap system area bits.

Bitmap blocks, Inode blocks and indirect addressing blocks for those two tree structures are treated as system blocks.

The rational behind that is that a write request can work on a new snapshot (system area of the inactive - resp. lower serial numbered superblock) while at the same time there is still a complete stable filesystem structure in the other half of the system area.

When finished with writing (a sync write is completed, the maximum sync leap time or a filesystem sync is requested), serial of the previously inactive superblock atomically is increased and the fs switches over to that - then stable declared - superblock.

For all data outside the system area, blocks are just copied while writing.

---

# Quota subsystem

_Peios Kernel / Internals / Filesystems_

> Quota subsystem allows system administrator to set limits on used space and number of used inodes (inode is a filesystem structure which is associated with each file or directory) for users and/or groups. For both used space and number of…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-quota-subsystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Quota subsystem allows system administrator to set limits on used space and number of used inodes (inode is a filesystem structure which is associated with each file or directory) for users and/or groups. For both used space and number of used inodes there are actually two limits. The first one is called softlimit and the second one hardlimit.  A user can never exceed a hardlimit for any resource (unless he has CAP_SYS_RESOURCE capability). User is allowed to exceed softlimit but only for limited period of time. This period is called "grace period" or "grace time". When grace time is over, user is not able to allocate more space/inodes until he frees enough of them to get below softlimit.

Quota limits (and amount of grace time) are set independently for each filesystem.

For more details about quota design, see the documentation in quota-tools package ([https://sourceforge.net/projects/linuxquota](<https://sourceforge.net/projects/linuxquota>)).

<a id="rst-quota-netlink-interface"></a>

## Quota netlink interface

When user exceeds a softlimit, runs out of grace time or reaches hardlimit, quota subsystem traditionally printed a message to the controlling terminal of the process which caused the excess. This method has the disadvantage that when user is using a graphical desktop he usually cannot see the message. Thus quota netlink interface has been designed to pass information about the above events to userspace. There they can be captured by an application and processed accordingly.

The interface uses generic netlink framework (see [https://lwn.net/Articles/208755/](<https://lwn.net/Articles/208755/>) and [http://www.infradead.org/\~tgr/libnl/](<http://www.infradead.org/~tgr/libnl/>) for more details about this layer). The name of the quota generic netlink interface is "VFS_DQUOT". Definitions of constants below are in &lt;linux/quota.h&gt;.  Since the quota netlink protocol is not namespace aware, quota netlink messages are sent only in initial network namespace.

Currently, the interface supports only one message type QUOTA_NL_C_WARNING. This command is used to send a notification about any of the above mentioned events. Each message has six attributes. These are (type of the argument is in parentheses):

> - **QUOTA_NL_A_QTYPE (u32)**
>
>   - type of quota being exceeded (one of USRQUOTA, GRPQUOTA)
>
> - **QUOTA_NL_A_EXCESS_ID (u64)**
>
>   - UID/GID (depends on quota type) of user / group whose limit is being exceeded.
>
> - **QUOTA_NL_A_CAUSED_ID (u64)**
>
>   - UID of a user who caused the event
>
> - **QUOTA_NL_A_WARNING (u32)**
>
>   - what kind of limit is exceeded:
>
>     > - **QUOTA_NL_IHARDWARN**
>     >
>     >   inode hardlimit
>     >
>     > - **QUOTA_NL_ISOFTLONGWARN**
>     >
>     >   inode softlimit is exceeded longer than given grace period
>     >
>     > - **QUOTA_NL_ISOFTWARN**
>     >
>     >   inode softlimit
>     >
>     > - **QUOTA_NL_BHARDWARN**
>     >
>     >   space (block) hardlimit
>     >
>     > - **QUOTA_NL_BSOFTLONGWARN**
>     >
>     >   space (block) softlimit is exceeded longer than given grace period.
>     >
>     > - **QUOTA_NL_BSOFTWARN**
>     >
>     >   space (block) softlimit
>
>   - four warnings are also defined for the event when user stops exceeding some limit:
>
>     > - **QUOTA_NL_IHARDBELOW**
>     >
>     >   inode hardlimit
>     >
>     > - **QUOTA_NL_ISOFTBELOW**
>     >
>     >   inode softlimit
>     >
>     > - **QUOTA_NL_BHARDBELOW**
>     >
>     >   space (block) hardlimit
>     >
>     > - **QUOTA_NL_BSOFTBELOW**
>     >
>     >   space (block) softlimit
>
> - **QUOTA_NL_A_DEV_MAJOR (u32)**
>
>   - major number of a device with the affected filesystem
>
> - **QUOTA_NL_A_DEV_MINOR (u32)**
>
>   - minor number of a device with the affected filesystem

---

# Ramfs, rootfs and initramfs

_Peios Kernel / Internals / Filesystems_

> October 17, 2005

<a id="rst-ramfs-rootfs-and-initramfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

October 17, 2005

**Author:** Rob Landley &lt;[rob@landley.net](<mailto:rob@landley.net>)&gt;

<a id="rst-what-is-ramfs"></a>

## What is ramfs?

Ramfs is a very simple filesystem that exports Linux's disk caching mechanisms (the page cache and dentry cache) as a dynamically resizable RAM-based filesystem.

Normally all files are cached in memory by Linux.  Pages of data read from backing store (usually the block device the filesystem is mounted on) are kept around in case it's needed again, but marked as clean (freeable) in case the Virtual Memory system needs the memory for something else.  Similarly, data written to files is marked clean as soon as it has been written to backing store, but kept around for caching purposes until the VM reallocates the memory.  A similar mechanism (the dentry cache) greatly speeds up access to directories.

With ramfs, there is no backing store.  Files written into ramfs allocate dentries and page cache as usual, but there's nowhere to write them to. This means the pages are never marked clean, so they can't be freed by the VM when it's looking to recycle memory.

The amount of code required to implement ramfs is tiny, because all the work is done by the existing Linux caching infrastructure.  Basically, you're mounting the disk cache as a filesystem.  Because of this, ramfs is not an optional component removable via menuconfig, since there would be negligible space savings.

<a id="rst-ramfs-and-ramdisk"></a>

## ramfs and ramdisk:

The older "ram disk" mechanism created a synthetic block device out of an area of RAM and used it as backing store for a filesystem.  This block device was of fixed size, so the filesystem mounted on it was of fixed size.  Using a ram disk also required unnecessarily copying memory from the fake block device into the page cache (and copying changes back out), as well as creating and destroying dentries.  Plus it needed a filesystem driver (such as ext2) to format and interpret this data.

Compared to ramfs, this wastes memory (and memory bus bandwidth), creates unnecessary work for the CPU, and pollutes the CPU caches.  (There are tricks to avoid this copying by playing with the page tables, but they're unpleasantly complicated and turn out to be about as expensive as the copying anyway.) More to the point, all the work ramfs is doing has to happen \_anyway\_, since all file access goes through the page and dentry caches.  The RAM disk is simply unnecessary; ramfs is internally much simpler.

Another reason ramdisks are semi-obsolete is that the introduction of loopback devices offered a more flexible and convenient way to create synthetic block devices, now from files instead of from chunks of memory. See losetup (8) for details.

<a id="rst-ramfs-and-tmpfs"></a>

## ramfs and tmpfs:

One downside of ramfs is you can keep writing data into it until you fill up all memory, and the VM can't free it because the VM thinks that files should get written to backing store (rather than swap space), but ramfs hasn't got any backing store.  Because of this, only root (or a trusted user) should be allowed write access to a ramfs mount.

A ramfs derivative called tmpfs was created to add size limits, and the ability to write the data to swap space.  Normal users can be allowed write access to tmpfs mounts.  See [Documentation/filesystems/tmpfs.rst](/kernel/internals/filesystems/tmpfs.md) for more information.

<a id="rst-what-is-rootfs"></a>

## What is rootfs?

Rootfs is a special instance of ramfs (or tmpfs, if that's enabled), which is always present in Linux systems.  The kernel uses an immutable empty filesystem called nullfs as the true root of the VFS hierarchy, with the mutable rootfs (tmpfs/ramfs) mounted on top of it.  This allows pivot_root() and unmounting of the initramfs to work normally.

Most systems just mount another filesystem over rootfs and ignore it.  The amount of space an empty instance of ramfs takes up is tiny.

With Peios PKM and `CONFIG_TMPFS` enabled, rootfs always uses tmpfs, including when `root=` or `rootfstype=ramfs` is present. The tmpfs xattr support stores native security descriptors. Peios seeds the root descriptor before initramfs contents inherit from it. The upstream command-line method of forcing a ramfs rootfs does not apply to this configuration.

<a id="rst-what-is-initramfs"></a>

## What is initramfs?

All 2.6 Linux kernels contain a gzipped "cpio" format archive, which is extracted into rootfs when the kernel boots up.  After extracting, the kernel checks to see if rootfs contains a file "init", and if so it executes it as PID 1.  If found, this init process is responsible for bringing the system the rest of the way up, including locating and mounting the real root device (if any).  If rootfs does not contain an init program after the embedded cpio archive is extracted into it, the kernel will fall through to the older code to locate and mount a root partition, then exec some variant of /sbin/init out of that.

All this differs from the old initrd in several ways:

> - The old initrd was always a separate file, while the initramfs archive is linked into the linux kernel image.  (The directory `linux-*/usr` is devoted to generating this archive during the build.)
>
> - The old initrd file was a gzipped filesystem image (in some file format, such as ext2, that needed a driver built into the kernel), while the new initramfs archive is a gzipped cpio archive (like tar only simpler, see cpio(1) and [Documentation/driver-api/early-userspace/buffer-format.rst](/kernel/hardware/driver-api/early-userspace/buffer-format.md)). The kernel's cpio extraction code is not only extremely small, it's also \__init text and data that can be discarded during the boot process.
>
> - The program run by the old initrd (which was called /initrd, not /init) did some setup and then returned to the kernel, while the init program from initramfs is not expected to return to the kernel.  (If /init needs to hand off control it can overmount / with a new root device and exec another init program.  See the switch_root utility, below.)
>
> - When switching another root device, initrd would pivot_root and then umount the ramdisk.  With nullfs as the true root, pivot_root() works normally from the initramfs.  Userspace can simply do:
>
>
>
>   ```text
>   chdir(new_root);
>   pivot_root(".", ".");
>   umount2(".", MNT_DETACH);
>   ```
>
>   This is the preferred method for switching root filesystems.

<a id="rst-populating-initramfs"></a>

## Populating initramfs:

The 2.6 kernel build process always creates a gzipped cpio format initramfs archive and links it into the resulting kernel binary.  By default, this archive is empty (consuming 134 bytes on x86).

The config option CONFIG_INITRAMFS_SOURCE (in General Setup in menuconfig, and living in usr/Kconfig) can be used to specify a source for the initramfs archive, which will automatically be incorporated into the resulting binary.  This option can point to an existing gzipped cpio archive, a directory containing files to be archived, or a text file specification such as the following example:



```text
dir /dev 755 0 0
nod /dev/console 644 0 0 c 5 1
nod /dev/loop0 644 0 0 b 7 0
dir /bin 755 1000 1000
slink /bin/sh busybox 777 0 0
file /bin/busybox initramfs/busybox 755 0 0
dir /proc 755 0 0
dir /sys 755 0 0
dir /mnt 755 0 0
file /init initramfs/init.sh 755 0 0
```

Run "usr/gen_init_cpio" (after the kernel build) to get a usage message documenting the above file format.

One advantage of the configuration file is that root access is not required to set permissions or create device nodes in the new archive.  (Note that those two example "file" entries expect to find files named "init.sh" and "busybox" in a directory called "initramfs", under the linux-2.6.\* directory.  See [Documentation/driver-api/early-userspace/early_userspace_support.rst](/kernel/hardware/driver-api/early-userspace/early-userspace-support.md) for more details.)

The kernel does not depend on external cpio tools.  If you specify a directory instead of a configuration file, the kernel's build infrastructure creates a configuration file from that directory (usr/Makefile calls usr/gen_initramfs.sh), and proceeds to package up that directory using the config file (by feeding it to usr/gen_init_cpio, which is created from usr/gen_init_cpio.c).  The kernel's build-time cpio creation code is entirely self-contained, and the kernel's boot-time extractor is also (obviously) self-contained.

The one thing you might need external cpio utilities installed for is creating or extracting your own preprepared cpio files to feed to the kernel build (instead of a config file or directory).

The following command line can extract a cpio image (either by the above script or by the kernel build) back into its component files:



```text
cpio -i -d -H newc -F initramfs_data.cpio --no-absolute-filenames
```

The following shell script can create a prebuilt cpio archive you can use in place of the above config file:



```text
#!/bin/sh

# Copyright 2006 Rob Landley <rob@landley.net> and TimeSys Corporation.
# Licensed under GPL version 2

if [ $# -ne 2 ]
then
  echo "usage: mkinitramfs directory imagename.cpio.gz"
  exit 1
fi

if [ -d "$1" ]
then
  echo "creating $2 from $1"
  (cd "$1"; find . | cpio -o -H newc | gzip) > "$2"
else
  echo "First argument must be a directory"
  exit 1
fi
```

> [!NOTE]
>
> The cpio man page contains some bad advice that will break your initramfs archive if you follow it.  It says "A typical way to generate the list of filenames is with the find command; you should give find the -depth option to minimize problems with permissions on directories that are unwritable or not searchable."  Don't do this when creating initramfs.cpio.gz images, it won't work.  The Linux kernel cpio extractor won't create files in a directory that doesn't exist, so the directory entries must go before the files that go in those directories. The above script gets them in the right order.

<a id="rst-external-initramfs-images"></a>

## External initramfs images:

If the kernel has initrd support enabled, an external cpio.gz archive can also be passed into a 2.6 kernel in place of an initrd.  In this case, the kernel will autodetect the type (initramfs, not initrd) and extract the external cpio archive into rootfs before trying to run /init.

This has the memory efficiency advantages of initramfs (no ramdisk block device) but the separate packaging of initrd (which is nice if you have non-GPL code you'd like to run from initramfs, without conflating it with the GPL licensed Linux kernel binary).

It can also be used to supplement the kernel's built-in initramfs image.  The files in the external archive will overwrite any conflicting files in the built-in initramfs archive.  Some distributors also prefer to customize a single kernel image with task-specific initramfs images, without recompiling.

<a id="rst-contents-of-initramfs"></a>

## Contents of initramfs:

An initramfs archive is a complete self-contained root filesystem for Linux. If you don't already understand what shared libraries, devices, and paths you need to get a minimal root filesystem up and running, here are some references:

- [https://www.tldp.org/HOWTO/Bootdisk-HOWTO/](<https://www.tldp.org/HOWTO/Bootdisk-HOWTO/>)

- [https://www.tldp.org/HOWTO/From-PowerUp-To-Bash-Prompt-HOWTO.html](<https://www.tldp.org/HOWTO/From-PowerUp-To-Bash-Prompt-HOWTO.html>)

- [http://www.linuxfromscratch.org/lfs/view/stable/](<http://www.linuxfromscratch.org/lfs/view/stable/>)

The "klibc" package ([https://www.kernel.org/pub/linux/libs/klibc](<https://www.kernel.org/pub/linux/libs/klibc>)) is designed to be a tiny C library to statically link early userspace code against, along with some related utilities.  It is BSD licensed.

I use uClibc ([https://www.uclibc.org](<https://www.uclibc.org>)) and busybox ([https://www.busybox.net](<https://www.busybox.net>)) myself.  These are LGPL and GPL, respectively.  (A self-contained initramfs package is planned for the busybox 1.3 release.)

In theory you could use glibc, but that's not well suited for small embedded uses like this.  (A "hello world" program statically linked against glibc is over 400k.  With uClibc it's 7k.  Also note that glibc dlopens libnss to do name lookups, even when otherwise statically linked.)

A good first step is to get initramfs to run a statically linked "hello world" program as init, and test it under an emulator like qemu (www.qemu.org) or User Mode Linux, like so:



```text
cat > hello.c << EOF
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  printf("Hello world!\n");
  sleep(999999999);
}
EOF
gcc -static hello.c -o init
echo init | cpio -o -H newc | gzip > test.cpio.gz
# Testing external initramfs using the initrd loading mechanism.
qemu -kernel /boot/vmlinuz -initrd test.cpio.gz /dev/zero
```

When debugging a normal root filesystem, it's nice to be able to boot with "init=/bin/sh".  The initramfs equivalent is "rdinit=/bin/sh", and it's just as useful.

<a id="rst-why-cpio-rather-than-tar"></a>

## Why cpio rather than tar?

This decision was made back in December, 2001.  The discussion started here:

- [https://lore.kernel.org/lkml/a03cke$640$1@cesium.transmeta.com/](<https://lore.kernel.org/lkml/a03cke$640$1@cesium.transmeta.com/>)

And spawned a second thread (specifically on tar vs cpio), starting here:

- [https://lore.kernel.org/lkml/3C25A06D.7030408@zytor.com/](<https://lore.kernel.org/lkml/3C25A06D.7030408@zytor.com/>)

The quick and dirty summary version (which is no substitute for reading the above threads) is:

1. cpio is a standard.  It's decades old (from the AT&amp;T days), and already widely used on Linux (inside RPM, Red Hat's device driver disks).  Here's a Linux Journal article about it from 1996:

   > [http://www.linuxjournal.com/article/1213](<http://www.linuxjournal.com/article/1213>)

   It's not as popular as tar because the traditional cpio command line tools require \_truly_hideous\_ command line arguments.  But that says nothing either way about the archive format, and there are alternative tools, such as:

   > [https://linux.die.net/man/1/afio](<https://linux.die.net/man/1/afio>)

2. The cpio archive format chosen by the kernel is simpler and cleaner (and thus easier to create and parse) than any of the (literally dozens of) various tar archive formats.  The complete initramfs archive format is explained in buffer-format.rst, created in usr/gen_init_cpio.c, and extracted in init/initramfs.c.  All three together come to less than 26k total of human-readable text.

3. The GNU project standardizing on tar is approximately as relevant as Windows standardizing on zip.  Linux is not part of either, and is free to make its own technical decisions.

4. Since this is a kernel internal format, it could easily have been something brand new.  The kernel provides its own tools to create and extract this format anyway.  Using an existing standard was preferable, but not essential.

5. Al Viro made the decision (quote: "tar is ugly as hell and not going to be supported on the kernel side"):

   > - [https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222109050.21702-100000@weyl.math.psu.edu/](<https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222109050.21702-100000@weyl.math.psu.edu/>)

   explained his reasoning:

   > - [https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222240530.21702-100000@weyl.math.psu.edu/](<https://lore.kernel.org/lkml/Pine.GSO.4.21.0112222240530.21702-100000@weyl.math.psu.edu/>)
   >
   > - [https://lore.kernel.org/lkml/Pine.GSO.4.21.0112230849550.23300-100000@weyl.math.psu.edu/](<https://lore.kernel.org/lkml/Pine.GSO.4.21.0112230849550.23300-100000@weyl.math.psu.edu/>)

   and, most importantly, designed and implemented the initramfs code.

<a id="rst-future-directions"></a>

## Future directions:

Today (2.6.16), initramfs is always compiled in, but not always used.  The kernel falls back to legacy boot code that is reached only if initramfs does not contain an /init program.  The fallback is legacy code, there to ensure a smooth transition and allowing early boot functionality to gradually move to "early userspace" (I.E. initramfs).

The move to early userspace is necessary because finding and mounting the real root device is complex.  Root partitions can span multiple devices (raid or separate journal).  They can be out on the network (requiring dhcp, setting a specific MAC address, logging into a server, etc).  They can live on removable media, with dynamically allocated major/minor numbers and persistent naming issues requiring a full udev implementation to sort out.  They can be compressed, encrypted, copy-on-write, loopback mounted, strangely partitioned, and so on.

This kind of complexity (which inevitably includes policy) is rightly handled in userspace.  Both klibc and busybox/uClibc are working on simple initramfs packages to drop into a kernel build.

The klibc package has now been accepted into Andrew Morton's 2.6.17-mm tree. The kernel's current early boot code (partition detection, etc) will probably be migrated into a default initramfs, automatically created and used by the kernel build.

---

# relay interface (formerly relayfs)

_Peios Kernel / Internals / Filesystems_

> The relay interface provides a means for kernel applications to efficiently log and transfer large quantities of data from the kernel to userspace via user-defined 'relay channels'.

<a id="rst-relay-interface-formerly-relayfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The relay interface provides a means for kernel applications to efficiently log and transfer large quantities of data from the kernel to userspace via user-defined 'relay channels'.

A 'relay channel' is a kernel-&gt;user data relay mechanism implemented as a set of per-cpu kernel buffers ('channel buffers'), each represented as a regular file ('relay file') in user space.  Kernel clients write into the channel buffers using efficient write functions; these automatically log into the current cpu's channel buffer.  User space applications mmap() or read() from the relay files and retrieve the data as it becomes available.  The relay files themselves are files created in a host filesystem, e.g. debugfs, and are associated with the channel buffers using the API described below.

The format of the data logged into the channel buffers is completely up to the kernel client; the relay interface does however provide hooks which allow kernel clients to impose some structure on the buffer data.  The relay interface doesn't implement any form of data filtering - this also is left to the kernel client.  The purpose is to keep things as simple as possible.

This document provides an overview of the relay interface API.  The details of the function parameters are documented along with the functions in the relay interface code - please see that for details.

<a id="rst-semantics"></a>

## Semantics

Each relay channel has one buffer per CPU; each buffer has one or more sub-buffers.  Messages are written to the first sub-buffer until it is too full to contain a new message, in which case it is written to the next (if available).  Messages are never split across sub-buffers. At this point, userspace can be notified so it empties the first sub-buffer, while the kernel continues writing to the next.

When notified that a sub-buffer is full, the kernel knows how many bytes of it are padding, i.e., unused space occurring because a complete message couldn't fit into a sub-buffer.  Userspace can use this knowledge to copy only valid data.

After copying it, userspace can notify the kernel that a sub-buffer has been consumed.

A relay channel can operate in a mode where it will overwrite data not yet collected by userspace, and not wait for it to be consumed.

The relay channel itself does not provide for communication of such data between userspace and kernel, allowing the kernel side to remain simple and not impose a single interface on userspace.  It does provide a set of examples and a separate helper though, described below.

The read() interface both removes padding and internally consumes the read sub-buffers; thus in cases where read(2) is being used to drain the channel buffers, special-purpose communication between kernel and user isn't necessary for basic operation.

One of the major goals of the relay interface is to provide a low overhead mechanism for conveying kernel data to userspace.  While the read() interface is easy to use, it's not as efficient as the mmap() approach; the example code attempts to make the tradeoff between the two approaches as small as possible.

<a id="rst-klog-and-relay-apps-example-code"></a>

## klog and relay-apps example code

The relay interface itself is ready to use, but to make things easier, a couple of simple utility functions and a set of examples are provided.

The relay-apps example tarball, available on the relay sourceforge site, contains a set of self-contained examples, each consisting of a pair of .c files containing boilerplate code for each of the user and kernel sides of a relay application.  When combined these two sets of boilerplate code provide glue to easily stream data to disk, without having to bother with mundane housekeeping chores.

The 'klog debugging functions' patch (klog.patch in the relay-apps tarball) provides a couple of high-level logging functions to the kernel which allow writing formatted text or raw data to a channel, regardless of whether a channel to write into exists or not, or even whether the relay interface is compiled into the kernel or not.  These functions allow you to put unconditional 'trace' statements anywhere in the kernel or kernel modules; only when there is a 'klog handler' registered will data actually be logged (see the klog and kleak examples for details).

It is of course possible to use the relay interface from scratch, i.e., without using any of the relay-apps example code or klog, but you'll have to implement communication between userspace and kernel, allowing both to convey the state of buffers (full, empty, amount of padding).  The read() interface both removes padding and internally consumes the read sub-buffers; thus in cases where read(2) is being used to drain the channel buffers, special-purpose communication between kernel and user isn't necessary for basic operation.  Things such as buffer-full conditions would still need to be communicated via some channel though.

klog and the relay-apps examples can be found in the relay-apps tarball on [http://relayfs.sourceforge.net](<http://relayfs.sourceforge.net>)

<a id="rst-the-relay-interface-user-space-api"></a>

## The relay interface user space API

The relay interface implements basic file operations for user space access to relay channel buffer data.  Here are the file operations that are available and some comments regarding their behavior:


<table>
<tbody>
<tr>
<td>


open()

</td>
<td>


enables user to open an \_existing\_ channel buffer.

</td>
</tr>
<tr>
<td>


mmap()

</td>
<td>


results in channel buffer being mapped into the caller's memory space. Note that you can't do a partial mmap - you must map the entire file, which is NRBUF \* SUBBUFSIZE.

</td>
</tr>
<tr>
<td>


read()

</td>
<td>


read the contents of a channel buffer.  The bytes read are 'consumed' by the reader, i.e., they won't be available again to subsequent reads.  If the channel is being used in no-overwrite mode (the default), it can be read at any time even if there's an active kernel writer.  If the channel is being used in overwrite mode and there are active channel writers, results may be unpredictable - users should make sure that all logging to the channel has ended before using read() with overwrite mode.  Sub-buffer padding is automatically removed and will not be seen by the reader.

</td>
</tr>
<tr>
<td>


sendfile()

</td>
<td>


transfer data from a channel buffer to an output file descriptor. Sub-buffer padding is automatically removed and will not be seen by the reader.

</td>
</tr>
<tr>
<td>


poll()

</td>
<td>


POLLIN/POLLRDNORM/POLLERR supported.  User applications are notified when sub-buffer boundaries are crossed.

</td>
</tr>
<tr>
<td>


close()

</td>
<td>


decrements the channel buffer's refcount.  When the refcount reaches 0, i.e., when no process or kernel client has the buffer open, the channel buffer is freed.

</td>
</tr>
</tbody>
</table>

In order for a user application to make use of relay files, the host filesystem must be mounted.  For example:



```text
mount -t debugfs debugfs /sys/kernel/debug
```

> [!NOTE]
>
> The host filesystem doesn't need to be mounted for kernel clients to create or use channels - it only needs to be mounted when user space applications need access to the buffer data.

<a id="rst-the-relay-interface-kernel-api"></a>

## The relay interface kernel API

Here's a summary of the API the relay interface provides to in-kernel clients:

- **TBD(curr. line MT:/API/)**

  channel management functions:



  ```text
  relay_open(base_filename, parent, subbuf_size, n_subbufs,
             callbacks, private_data)
  relay_close(chan)
  relay_flush(chan)
  relay_reset(chan)
  ```

  channel management typically called on instigation of userspace:



  ```text
  relay_subbufs_consumed(chan, cpu, subbufs_consumed)
  ```

  write functions:



  ```text
  relay_write(chan, data, length)
  __relay_write(chan, data, length)
  relay_reserve(chan, length)
  ```

  callbacks:



  ```text
  subbuf_start(buf, subbuf, prev_subbuf, prev_padding)
  buf_mapped(buf, filp)
  buf_unmapped(buf, filp)
  create_buf_file(filename, parent, mode, buf, is_global)
  remove_buf_file(dentry)
  ```

  helper functions:



  ```text
  relay_buf_full(buf)
  subbuf_start_reserve(buf, length)
  ```

<a id="rst-creating-a-channel"></a>

### Creating a channel

relay_open() is used to create a channel, along with its per-cpu channel buffers.  Each channel buffer will have an associated file created for it in the host filesystem, which can be and mmapped or read from in user space.  The files are named basename0...basenameN-1 where N is the number of online cpus, and by default will be created in the root of the filesystem (if the parent param is NULL).  If you want a directory structure to contain your relay files, you should create it using the host filesystem's directory creation function, e.g. debugfs_create_dir(), and pass the parent directory to relay_open().  Users are responsible for cleaning up any directory structure they create, when the channel is closed - again the host filesystem's directory removal functions should be used for that, e.g. debugfs_remove().

In order for a channel to be created and the host filesystem's files associated with its channel buffers, the user must provide definitions for two callback functions, create_buf_file() and remove_buf_file(). create_buf_file() is called once for each per-cpu buffer from relay_open() and allows the user to create the file which will be used to represent the corresponding channel buffer.  The callback should return the dentry of the file created to represent the channel buffer. remove_buf_file() must also be defined; it's responsible for deleting the file(s) created in create_buf_file() and is called during relay_close().

Here are some typical definitions for these callbacks, in this case using debugfs:



```text
/*
* create_buf_file() callback.  Creates relay file in debugfs.
*/
static struct dentry *create_buf_file_handler(const char *filename,
                                            struct dentry *parent,
                                            umode_t mode,
                                            struct rchan_buf *buf,
                                            int *is_global)
{
        return debugfs_create_file(filename, mode, parent, buf,
                                &relay_file_operations);
}

/*
* remove_buf_file() callback.  Removes relay file from debugfs.
*/
static int remove_buf_file_handler(struct dentry *dentry)
{
        debugfs_remove(dentry);

        return 0;
}

/*
* relay interface callbacks
*/
static struct rchan_callbacks relay_callbacks =
{
        .create_buf_file = create_buf_file_handler,
        .remove_buf_file = remove_buf_file_handler,
};
```

And an example relay_open() invocation using them:



```text
chan = relay_open("cpu", NULL, SUBBUF_SIZE, N_SUBBUFS, &relay_callbacks, NULL);
```

If the create_buf_file() callback fails, or isn't defined, channel creation and thus relay_open() will fail.

The total size of each per-cpu buffer is calculated by multiplying the number of sub-buffers by the sub-buffer size passed into relay_open(). The idea behind sub-buffers is that they're basically an extension of double-buffering to N buffers, and they also allow applications to easily implement random-access-on-buffer-boundary schemes, which can be important for some high-volume applications.  The number and size of sub-buffers is completely dependent on the application and even for the same application, different conditions will warrant different values for these parameters at different times.  Typically, the right values to use are best decided after some experimentation; in general, though, it's safe to assume that having only 1 sub-buffer is a bad idea - you're guaranteed to either overwrite data or lose events depending on the channel mode being used.

The create_buf_file() implementation can also be defined in such a way as to allow the creation of a single 'global' buffer instead of the default per-cpu set.  This can be useful for applications interested mainly in seeing the relative ordering of system-wide events without the need to bother with saving explicit timestamps for the purpose of merging/sorting per-cpu files in a postprocessing step.

To have relay_open() create a global buffer, the create_buf_file() implementation should set the value of the is_global outparam to a non-zero value in addition to creating the file that will be used to represent the single buffer.  In the case of a global buffer, create_buf_file() and remove_buf_file() will be called only once.  The normal channel-writing functions, e.g. relay_write(), can still be used - writes from any cpu will transparently end up in the global buffer - but since it is a global buffer, callers should make sure they use the proper locking for such a buffer, either by wrapping writes in a spinlock, or by copying a write function from relay.h and creating a local version that internally does the proper locking.

The private_data passed into relay_open() allows clients to associate user-defined data with a channel, and is immediately available (including in create_buf_file()) via chan-&gt;private_data or buf-&gt;chan-&gt;private_data.

<a id="rst-channel-modes"></a>

### Channel 'modes'

relay channels can be used in either of two modes - 'overwrite' or 'no-overwrite'.  The mode is entirely determined by the implementation of the subbuf_start() callback, as described below.  The default if no subbuf_start() callback is defined is 'no-overwrite' mode.  If the default mode suits your needs, and you plan to use the read() interface to retrieve channel data, you can ignore the details of this section, as it pertains mainly to mmap() implementations.

In 'overwrite' mode, also known as 'flight recorder' mode, writes continuously cycle around the buffer and will never fail, but will unconditionally overwrite old data regardless of whether it's actually been consumed.  In no-overwrite mode, writes will fail, i.e., data will be lost, if the number of unconsumed sub-buffers equals the total number of sub-buffers in the channel.  It should be clear that if there is no consumer or if the consumer can't consume sub-buffers fast enough, data will be lost in either case; the only difference is whether data is lost from the beginning or the end of a buffer.

As explained above, a relay channel is made of up one or more per-cpu channel buffers, each implemented as a circular buffer subdivided into one or more sub-buffers.  Messages are written into the current sub-buffer of the channel's current per-cpu buffer via the write functions described below.  Whenever a message can't fit into the current sub-buffer, because there's no room left for it, the client is notified via the subbuf_start() callback that a switch to a new sub-buffer is about to occur.  The client uses this callback to 1) initialize the next sub-buffer if appropriate 2) finalize the previous sub-buffer if appropriate and 3) return a boolean value indicating whether or not to actually move on to the next sub-buffer.

To implement 'no-overwrite' mode, the userspace client provides an implementation of the subbuf_start() callback something like the following:



```text
static int subbuf_start(struct rchan_buf *buf,
                        void *subbuf,
                        void *prev_subbuf,
                        unsigned int prev_padding)
{
        if (prev_subbuf)
                *((unsigned *)prev_subbuf) = prev_padding;

        if (relay_buf_full(buf))
                return 0;

        subbuf_start_reserve(buf, sizeof(unsigned int));

        return 1;
}
```

If the current buffer is full, i.e., all sub-buffers remain unconsumed, the callback returns 0 to indicate that the buffer switch should not occur yet, i.e., until the consumer has had a chance to read the current set of ready sub-buffers.  For the relay_buf_full() function to make sense, the consumer is responsible for notifying the relay interface when sub-buffers have been consumed via relay_subbufs_consumed().  Any subsequent attempts to write into the buffer will again invoke the subbuf_start() callback with the same parameters; only when the consumer has consumed one or more of the ready sub-buffers will relay_buf_full() return 0, in which case the buffer switch can continue.

The implementation of the subbuf_start() callback for 'overwrite' mode would be very similar:



```text
static int subbuf_start(struct rchan_buf *buf,
                        void *subbuf,
                        void *prev_subbuf,
                        size_t prev_padding)
{
        if (prev_subbuf)
                *((unsigned *)prev_subbuf) = prev_padding;

        subbuf_start_reserve(buf, sizeof(unsigned int));

        return 1;
}
```

In this case, the relay_buf_full() check is meaningless and the callback always returns 1, causing the buffer switch to occur unconditionally.  It's also meaningless for the client to use the relay_subbufs_consumed() function in this mode, as it's never consulted.

The default subbuf_start() implementation, used if the client doesn't define any callbacks, or doesn't define the subbuf_start() callback, implements the simplest possible 'no-overwrite' mode, i.e., it does nothing but return 0.

Header information can be reserved at the beginning of each sub-buffer by calling the subbuf_start_reserve() helper function from within the subbuf_start() callback.  This reserved area can be used to store whatever information the client wants.  In the example above, room is reserved in each sub-buffer to store the padding count for that sub-buffer.  This is filled in for the previous sub-buffer in the subbuf_start() implementation; the padding value for the previous sub-buffer is passed into the subbuf_start() callback along with a pointer to the previous sub-buffer, since the padding value isn't known until a sub-buffer is filled.  The subbuf_start() callback is also called for the first sub-buffer when the channel is opened, to give the client a chance to reserve space in it.  In this case the previous sub-buffer pointer passed into the callback will be NULL, so the client should check the value of the prev_subbuf pointer before writing into the previous sub-buffer.

<a id="rst-writing-to-a-channel"></a>

### Writing to a channel

Kernel clients write data into the current cpu's channel buffer using relay_write() or \__relay_write().  relay_write() is the main logging function - it uses local_irqsave() to protect the buffer and should be used if you might be logging from interrupt context.  If you know you'll never be logging from interrupt context, you can use \__relay_write(), which only disables preemption.  These functions don't return a value, so you can't determine whether or not they failed - the assumption is that you wouldn't want to check a return value in the fast logging path anyway, and that they'll always succeed unless the buffer is full and no-overwrite mode is being used, in which case you can detect a failed write in the subbuf_start() callback by calling the relay_buf_full() helper function.

relay_reserve() is used to reserve a slot in a channel buffer which can be written to later.  This would typically be used in applications that need to write directly into a channel buffer without having to stage data in a temporary buffer beforehand.  Because the actual write may not happen immediately after the slot is reserved, applications using relay_reserve() can keep a count of the number of bytes actually written, either in space reserved in the sub-buffers themselves or as a separate array.  See the 'reserve' example in the relay-apps tarball at [http://relayfs.sourceforge.net](<http://relayfs.sourceforge.net>) for an example of how this can be done.  Because the write is under control of the client and is separated from the reserve, relay_reserve() doesn't protect the buffer at all - it's up to the client to provide the appropriate synchronization when using relay_reserve().

<a id="rst-closing-a-channel"></a>

### Closing a channel

The client calls relay_close() when it's finished using the channel. The channel and its associated buffers are destroyed when there are no longer any references to any of the channel buffers.  relay_flush() forces a sub-buffer switch on all the channel buffers, and can be used to finalize and process the last sub-buffers before the channel is closed.

<a id="rst-misc"></a>

### Misc

Some applications may want to keep a channel around and reuse it rather than open and close a new channel for each use.  relay_reset() can be used for this purpose - it resets a channel to its initial state without reallocating channel buffer memory or destroying existing mappings.  It should however only be called when it's safe to do so, i.e., when the channel isn't currently being written to.

Finally, there are a couple of utility callbacks that can be used for different purposes.  buf_mapped() is called whenever a channel buffer is mmapped from user space and buf_unmapped() is called when it's unmapped.  The client can use this notification to trigger actions within the kernel application, such as enabling/disabling logging to the channel.

<a id="rst-resources"></a>

## Resources

For news, example code, mailing list, etc. see the relay interface homepage:

> [http://relayfs.sourceforge.net](<http://relayfs.sourceforge.net>)

<a id="rst-credits"></a>

## Credits

The ideas and specs for the relay interface came about as a result of discussions on tracing involving the following:

Michel Dagenais         &lt;[michel.dagenais@polymtl.ca](<mailto:michel.dagenais@polymtl.ca>)&gt; Richard Moore           &lt;[richardj_moore@uk.ibm.com](<mailto:richardj_moore@uk.ibm.com>)&gt; Bob Wisniewski          &lt;[bob@watson.ibm.com](<mailto:bob@watson.ibm.com>)&gt; Karim Yaghmour          &lt;[karim@opersys.com](<mailto:karim@opersys.com>)&gt; Tom Zanussi             &lt;[zanussi@us.ibm.com](<mailto:zanussi@us.ibm.com>)&gt;

Also thanks to Hubertus Franke for a lot of useful suggestions and bug reports.

---

# User Interface for Resource Control feature (resctrl)

_Peios Kernel / Internals / Filesystems_

> Intel refers to this feature as Intel Resource Director Technology(Intel(R) RDT). AMD refers to this feature as AMD Platform Quality of Service(AMD QoS).

<a id="rst-user-interface-for-resource-control-feature-resctrl"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2016 Intel Corporation

**Authors:** - Fenghua Yu &lt;[fenghua.yu@intel.com](<mailto:fenghua.yu@intel.com>)&gt;

- Tony Luck &lt;[tony.luck@intel.com](<mailto:tony.luck@intel.com>)&gt;

- Vikas Shivappa &lt;[vikas.shivappa@intel.com](<mailto:vikas.shivappa@intel.com>)&gt;

Intel refers to this feature as Intel Resource Director Technology(Intel(R) RDT). AMD refers to this feature as AMD Platform Quality of Service(AMD QoS).

This feature is enabled by the CONFIG\_X86\_CPU\_RESCTRL and the x86 /proc/cpuinfo flag bits:


<table>
<tbody>
<tr>
<td>


RDT (Resource Director Technology) Allocation

</td>
<td>


"rdt\_a"

</td>
</tr>
<tr>
<td>


CAT (Cache Allocation Technology)

</td>
<td>


"cat\_l3", "cat\_l2"

</td>
</tr>
<tr>
<td>


CDP (Code and Data Prioritization)

</td>
<td>


"cdp\_l3", "cdp\_l2"

</td>
</tr>
<tr>
<td>


CQM (Cache QoS Monitoring)

</td>
<td>


"cqm\_llc", "cqm\_occup\_llc"

</td>
</tr>
<tr>
<td>


MBM (Memory Bandwidth Monitoring)

</td>
<td>


"cqm\_mbm\_total", "cqm\_mbm\_local"

</td>
</tr>
<tr>
<td>


MBA (Memory Bandwidth Allocation)

</td>
<td>


"mba"

</td>
</tr>
<tr>
<td>


SMBA (Slow Memory Bandwidth Allocation)

</td>
<td>


""

</td>
</tr>
<tr>
<td>


BMEC (Bandwidth Monitoring Event Configuration)

</td>
<td>


""

</td>
</tr>
<tr>
<td>


ABMC (Assignable Bandwidth Monitoring Counters)

</td>
<td>


""

</td>
</tr>
<tr>
<td>


SDCIAE (Smart Data Cache Injection Allocation Enforcement)

</td>
<td>


""

</td>
</tr>
</tbody>
</table>

Historically, new features were made visible by default in /proc/cpuinfo. This resulted in the feature flags becoming hard to parse by humans. Adding a new flag to /proc/cpuinfo should be avoided if user space can obtain information about the feature from resctrl's info directory.

To use the feature mount the file system:



```text
# mount -t resctrl resctrl [-o cdp[,cdpl2][,mba_MBps][,debug]] /sys/fs/resctrl
```

mount options are:

- **"cdp":**

  Enable code/data prioritization in L3 cache allocations.

- **"cdpl2":**

  Enable code/data prioritization in L2 cache allocations.

- **"mba\_MBps":**

  Enable the MBA Software Controller(mba\_sc) to specify MBA bandwidth in MiBps

- **"debug":**

  Make debug files accessible. Available debug files are annotated with "Available only with debug option".

L2 and L3 CDP are controlled separately.

RDT features are orthogonal. A particular system may support only monitoring, only control, or both monitoring and control.  Cache pseudo-locking is a unique way of using cache control to "pin" or "lock" data in the cache. Details can be found in "Cache Pseudo-Locking".

The mount succeeds if either of allocation or monitoring is present, but only those files and directories supported by the system will be created. For more details on the behavior of the interface during monitoring and allocation, see the "Resource alloc and monitor groups" section.

<a id="rst-info-directory"></a>

## Info directory

The 'info' directory contains information about the enabled resources. Each resource has its own subdirectory. The subdirectory names reflect the resource names.

Most of the files in the resource's subdirectory are read-only, and describe properties of the resource. Resources that support global configuration options also include writable files that can be used to modify those settings.

Each subdirectory contains the following files with respect to allocation:

Cache resource(L3/L2)  subdirectory contains the following files related to allocation:

- **"num\_closids":**

  The number of CLOSIDs which are valid for this resource. The kernel uses the smallest number of CLOSIDs of all enabled resources as limit.

- **"cbm\_mask":**

  The bitmask which is valid for this resource. This mask is equivalent to 100%.

- **"min\_cbm\_bits":**

  The minimum number of consecutive bits which must be set when writing a mask.

- **"shareable\_bits":**

  Bitmask of shareable resource with other executing entities (e.g. I/O). Applies to all instances of this resource. User can use this when setting up exclusive cache partitions. Note that some platforms support devices that have their own settings for cache use which can over-ride these bits.

  When "io\_alloc" is enabled, a portion of each cache instance can be configured for shared use between hardware and software. "bit\_usage" should be used to see which portions of each cache instance is configured for hardware use via "io\_alloc" feature because every cache instance can have its "io\_alloc" bitmask configured independently via "io\_alloc\_cbm".

- **"bit\_usage":**

  Annotated capacity bitmasks showing how all instances of the resource are used. The legend is:

  > - **"0":**
  >
  >   Corresponding region is unused. When the system's resources have been allocated and a "0" is found in "bit\_usage" it is a sign that resources are wasted.
  >
  > - **"H":**
  >
  >   Corresponding region is used by hardware only but available for software use. If a resource has bits set in "shareable\_bits" or "io\_alloc\_cbm" but not all of these bits appear in the resource groups' schemata then the bits appearing in "shareable\_bits" or "io\_alloc\_cbm" but no resource group will be marked as "H".
  >
  > - **"X":**
  >
  >   Corresponding region is available for sharing and used by hardware and software. These are the bits that appear in "shareable\_bits" or "io\_alloc\_cbm" as well as a resource group's allocation.
  >
  > - **"S":**
  >
  >   Corresponding region is used by software and available for sharing.
  >
  > - **"E":**
  >
  >   Corresponding region is used exclusively by one resource group. No sharing allowed.
  >
  > - **"P":**
  >
  >   Corresponding region is pseudo-locked. No sharing allowed.

- **"sparse\_masks":**

  Indicates if non-contiguous 1s value in CBM is supported.

  > - **"0":**
  >
  >   Only contiguous 1s value in CBM is supported.
  >
  > - **"1":**
  >
  >   Non-contiguous 1s value in CBM is supported.

- **"io\_alloc":**

  "io\_alloc" enables system software to configure the portion of the cache allocated for I/O traffic. File may only exist if the system supports this feature on some of its cache resources.

  > - **"disabled":**
  >
  >   Resource supports "io\_alloc" but the feature is disabled. Portions of cache used for allocation of I/O traffic cannot be configured.
  >
  > - **"enabled":**
  >
  >   Portions of cache used for allocation of I/O traffic can be configured using "io\_alloc\_cbm".
  >
  > - **"not supported":**
  >
  >   Support not available for this resource.

  The feature can be modified by writing to the interface, for example:

  To enable:



  ```text
  # echo 1 > /sys/fs/resctrl/info/L3/io_alloc
  ```

  To disable:



  ```text
  # echo 0 > /sys/fs/resctrl/info/L3/io_alloc
  ```

  The underlying implementation may reduce resources available to general (CPU) cache allocation. See architecture specific notes below. Depending on usage requirements the feature can be enabled or disabled.

  On AMD systems, io\_alloc feature is supported by the L3 Smart Data Cache Injection Allocation Enforcement (SDCIAE). The CLOSID for io\_alloc is the highest CLOSID supported by the resource. When io\_alloc is enabled, the highest CLOSID is dedicated to io\_alloc and no longer available for general (CPU) cache allocation. When CDP is enabled, io\_alloc routes I/O traffic using the highest CLOSID allocated for the instruction cache (CDP\_CODE), making this CLOSID no longer available for general (CPU) cache allocation for both the CDP\_CODE and CDP\_DATA resources.

- **"io\_alloc\_cbm":**

  Capacity bitmasks that describe the portions of cache instances to which I/O traffic from supported I/O devices are routed when "io\_alloc" is enabled.

  CBMs are displayed in the following format:

  > &lt;cache\_id0&gt;=&lt;cbm&gt;;&lt;cache\_id1&gt;=&lt;cbm&gt;;...

  Example:



  ```text
  # cat /sys/fs/resctrl/info/L3/io_alloc_cbm
  0=ffff;1=ffff
  ```

  CBMs can be configured by writing to the interface.

  Example:



  ```text
  # echo 1=ff > /sys/fs/resctrl/info/L3/io_alloc_cbm
  # cat /sys/fs/resctrl/info/L3/io_alloc_cbm
  0=ffff;1=00ff

  # echo "0=ff;1=f" > /sys/fs/resctrl/info/L3/io_alloc_cbm
  # cat /sys/fs/resctrl/info/L3/io_alloc_cbm
  0=00ff;1=000f
  ```

  When CDP is enabled "io\_alloc\_cbm" associated with the CDP\_DATA and CDP\_CODE resources may reflect the same values. For example, values read from and written to /sys/fs/resctrl/info/L3DATA/io\_alloc\_cbm may be reflected by /sys/fs/resctrl/info/L3CODE/io\_alloc\_cbm and vice versa.

Memory bandwidth(MB) subdirectory contains the following files with respect to allocation:

- **"min\_bandwidth":**

  The minimum memory bandwidth percentage which user can request.

- **"bandwidth\_gran":**

  The granularity in which the memory bandwidth percentage is allocated. The allocated b/w percentage is rounded off to the next control step available on the hardware. The available bandwidth control steps are: min\_bandwidth + N \* bandwidth\_gran.

- **"delay\_linear":**

  Indicates if the delay scale is linear or non-linear. This field is purely informational only.

- **"thread\_throttle\_mode":**

  Indicator on Intel systems of how tasks running on threads of a physical core are throttled in cases where they request different memory bandwidth percentages:

  - **"max":**

    the smallest percentage is applied to all threads

  - **"per-thread":**

    bandwidth percentages are directly applied to the threads running on the core

If L3 monitoring is available there will be an "L3\_MON" directory with the following files:

- **"num\_rmids":**

  The number of RMIDs supported by hardware for L3 monitoring events.

- **"mon\_features":**

  Lists the monitoring events if monitoring is enabled for the resource. Example:



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/mon_features
  llc_occupancy
  mbm_total_bytes
  mbm_local_bytes
  ```

  If the system supports Bandwidth Monitoring Event Configuration (BMEC), then the bandwidth events will be configurable. The output will be:



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/mon_features
  llc_occupancy
  mbm_total_bytes
  mbm_total_bytes_config
  mbm_local_bytes
  mbm_local_bytes_config
  ```

- **"mbm\_total\_bytes\_config", "mbm\_local\_bytes\_config":**

  Read/write files containing the configuration for the mbm\_total\_bytes and mbm\_local\_bytes events, respectively, when the Bandwidth Monitoring Event Configuration (BMEC) feature is supported. The event configuration settings are domain specific and affect all the CPUs in the domain. When either event configuration is changed, the bandwidth counters for all RMIDs of both events (mbm\_total\_bytes as well as mbm\_local\_bytes) are cleared for that domain. The next read for every RMID will report "Unavailable" and subsequent reads will report the valid value.

  Following are the types of events supported:


  <table>
  <thead>
  <tr>
  <th>


  Bits

  </th>
  <th>


  Description

  </th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>


  6

  </td>
  <td>


  Dirty Victims from the QOS domain to all types of memory

  </td>
  </tr>
  <tr>
  <td>


  5

  </td>
  <td>


  Reads to slow memory in the non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  4

  </td>
  <td>


  Reads to slow memory in the local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  3

  </td>
  <td>


  Non-temporal writes to non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  Non-temporal writes to local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Reads to memory in the non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  0

  </td>
  <td>


  Reads to memory in the local NUMA domain

  </td>
  </tr>
  </tbody>
  </table>

  By default, the mbm\_total\_bytes configuration is set to 0x7f to count all the event types and the mbm\_local\_bytes configuration is set to 0x15 to count all the local memory events.

  Examples:

  - To view the current configuration::



    ```text
    # cat /sys/fs/resctrl/info/L3_MON/mbm_total_bytes_config
    0=0x7f;1=0x7f;2=0x7f;3=0x7f

    # cat /sys/fs/resctrl/info/L3_MON/mbm_local_bytes_config
    0=0x15;1=0x15;3=0x15;4=0x15
    ```

  - To change the mbm\_total\_bytes to count only reads on domain 0, the bits 0, 1, 4 and 5 needs to be set, which is 110011b in binary (in hexadecimal 0x33):



    ```text
    # echo  "0=0x33" > /sys/fs/resctrl/info/L3_MON/mbm_total_bytes_config

    # cat /sys/fs/resctrl/info/L3_MON/mbm_total_bytes_config
    0=0x33;1=0x7f;2=0x7f;3=0x7f
    ```

  - To change the mbm\_local\_bytes to count all the slow memory reads on domain 0 and 1, the bits 4 and 5 needs to be set, which is 110000b in binary (in hexadecimal 0x30):



    ```text
    # echo  "0=0x30;1=0x30" > /sys/fs/resctrl/info/L3_MON/mbm_local_bytes_config

    # cat /sys/fs/resctrl/info/L3_MON/mbm_local_bytes_config
    0=0x30;1=0x30;3=0x15;4=0x15
    ```

- **"mbm\_assign\_mode":**

  The supported counter assignment modes. The enclosed brackets indicate which mode is enabled. The MBM events associated with counters may reset when "mbm\_assign\_mode" is changed.



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
  [mbm_event]
  default
  ```

  "mbm\_event":

  mbm\_event mode allows users to assign a hardware counter to an RMID, event pair and monitor the bandwidth usage as long as it is assigned. The hardware continues to track the assigned counter until it is explicitly unassigned by the user. Each event within a resctrl group can be assigned independently.

  In this mode, a monitoring event can only accumulate data while it is backed by a hardware counter. Use "mbm\_L3\_assignments" found in each CTRL\_MON and MON group to specify which of the events should have a counter assigned. The number of counters available is described in the "num\_mbm\_cntrs" file. Changing the mode may cause all counters on the resource to reset.

  Moving to mbm\_event counter assignment mode requires users to assign the counters to the events. Otherwise, the MBM event counters will return 'Unassigned' when read.

  The mode is beneficial for AMD platforms that support more CTRL\_MON and MON groups than available hardware counters. By default, this feature is enabled on AMD platforms with the ABMC (Assignable Bandwidth Monitoring Counters) capability, ensuring counters remain assigned even when the corresponding RMID is not actively used by any processor.

  "default":

  In default mode, resctrl assumes there is a hardware counter for each event within every CTRL\_MON and MON group. On AMD platforms, it is recommended to use the mbm\_event mode, if supported, to prevent reset of MBM events between reads resulting from hardware re-allocating counters. This can result in misleading values or display "Unavailable" if no counter is assigned to the event.

  - To enable "mbm\_event" counter assignment mode:



    ```text
    # echo "mbm_event" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
    ```

  - To enable "default" monitoring mode:



    ```text
    # echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
    ```

- **"num\_mbm\_cntrs":**

  The maximum number of counters (total of available and assigned counters) in each domain when the system supports mbm\_event mode.

  For example, on a system with maximum of 32 memory bandwidth monitoring counters in each of its L3 domains:



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/num_mbm_cntrs
  0=32;1=32
  ```

- **"available\_mbm\_cntrs":**

  The number of counters available for assignment in each domain when mbm\_event mode is enabled on the system.

  For example, on a system with 30 available \[hardware\] assignable counters in each of its L3 domains:



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/available_mbm_cntrs
  0=30;1=30
  ```

- **"event\_configs":**

  Directory that exists when "mbm\_event" counter assignment mode is supported. Contains a sub-directory for each MBM event that can be assigned to a counter.

  Two MBM events are supported by default: mbm\_local\_bytes and mbm\_total\_bytes. Each MBM event's sub-directory contains a file named "event\_filter" that is used to view and modify which memory transactions the MBM event is configured with. The file is accessible only when "mbm\_event" counter assignment mode is enabled.

  List of memory transaction types supported:


  <table>
  <thead>
  <tr>
  <th>


  Name

  </th>
  <th>


  Description

  </th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>


  dirty\_victim\_writes\_all

  </td>
  <td>


  Dirty Victims from the QOS domain to all types of memory

  </td>
  </tr>
  <tr>
  <td>


  remote\_reads\_slow\_memory

  </td>
  <td>


  Reads to slow memory in the non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  local\_reads\_slow\_memory

  </td>
  <td>


  Reads to slow memory in the local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  remote\_non\_temporal\_writes

  </td>
  <td>


  Non-temporal writes to non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  local\_non\_temporal\_writes

  </td>
  <td>


  Non-temporal writes to local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  remote\_reads

  </td>
  <td>


  Reads to memory in the non-local NUMA domain

  </td>
  </tr>
  <tr>
  <td>


  local\_reads

  </td>
  <td>


  Reads to memory in the local NUMA domain

  </td>
  </tr>
  </tbody>
  </table>

  For example:



  ```text
  # cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_total_bytes/event_filter
  local_reads,remote_reads,local_non_temporal_writes,remote_non_temporal_writes,
  local_reads_slow_memory,remote_reads_slow_memory,dirty_victim_writes_all

  # cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_local_bytes/event_filter
  local_reads,local_non_temporal_writes,local_reads_slow_memory
  ```

  Modify the event configuration by writing to the "event\_filter" file within the "event\_configs" directory. The read/write "event\_filter" file contains the configuration of the event that reflects which memory transactions are counted by it.

  For example:



  ```text
  # echo "local_reads, local_non_temporal_writes" >
    /sys/fs/resctrl/info/L3_MON/event_configs/mbm_total_bytes/event_filter

  # cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_total_bytes/event_filter
   local_reads,local_non_temporal_writes
  ```

- **"mbm\_assign\_on\_mkdir":**

  Exists when "mbm\_event" counter assignment mode is supported. Accessible only when "mbm\_event" counter assignment mode is enabled.

  Determines if a counter will automatically be assigned to an RMID, MBM event pair when its associated monitor group is created via mkdir. Enabled by default on boot, also when switched from "default" mode to "mbm\_event" counter assignment mode. Users can disable this capability by writing to the interface.

  - **"0":**

    Auto assignment is disabled.

  - **"1":**

    Auto assignment is enabled.

  Example:



  ```text
  # echo 0 > /sys/fs/resctrl/info/L3_MON/mbm_assign_on_mkdir
  # cat /sys/fs/resctrl/info/L3_MON/mbm_assign_on_mkdir
  0
  ```

- **"max\_threshold\_occupancy":**

  Read/write file provides the largest value (in bytes) at which a previously used LLC\_occupancy counter can be considered for reuse.

If telemetry monitoring is available there will be a "PERF\_PKG\_MON" directory with the following files:

- **"num\_rmids":**

  The number of RMIDs for telemetry monitoring events.

  On Intel resctrl will not enable telemetry events if the number of RMIDs that can be tracked concurrently is lower than the total number of RMIDs supported. Telemetry events can be force-enabled with the "rdt=" kernel parameter, but this may reduce the number of monitoring groups that can be created.

- **"mon\_features":**

  Lists the telemetry monitoring events that are enabled on this system.

The upper bound for how many "CTRL\_MON" + "MON" can be created is the smaller of the L3\_MON and PERF\_PKG\_MON "num\_rmids" values.

Finally, in the top level of the "info" directory there is a file named "last\_cmd\_status". This is reset with every "command" issued via the file system (making new directories or writing to any of the control files). If the command was successful, it will read as "ok". If the command failed, it will provide more information that can be conveyed in the error returns from file operations. E.g.



```text
# echo L3:0=f7 > schemata
bash: echo: write error: Invalid argument
# cat info/last_cmd_status
mask f7 has non-consecutive 1-bits
```

<a id="rst-resource-alloc-and-monitor-groups"></a>

## Resource alloc and monitor groups

Resource groups are represented as directories in the resctrl file system.  The default group is the root directory which, immediately after mounting, owns all the tasks and cpus in the system and can make full use of all resources.

On a system with RDT control features additional directories can be created in the root directory that specify different amounts of each resource (see "schemata" below). The root and these additional top level directories are referred to as "CTRL\_MON" groups below.

On a system with RDT monitoring the root directory and other top level directories contain a directory named "mon\_groups" in which additional directories can be created to monitor subsets of tasks in the CTRL\_MON group that is their ancestor. These are called "MON" groups in the rest of this document.

Removing a directory will move all tasks and cpus owned by the group it represents to the parent. Removing one of the created CTRL\_MON groups will automatically remove all MON groups below it.

Moving MON group directories to a new parent CTRL\_MON group is supported for the purpose of changing the resource allocations of a MON group without impacting its monitoring data or assigned tasks. This operation is not allowed for MON groups which monitor CPUs. No other move operation is currently allowed other than simply renaming a CTRL\_MON or MON group.

All groups contain the following files:

- **"tasks":**

  Reading this file shows the list of all tasks that belong to this group. Writing a task id to the file will add a task to the group. Multiple tasks can be added by separating the task ids with commas. Tasks will be assigned sequentially. Multiple failures are not supported. A single failure encountered while attempting to assign a task will cause the operation to abort and already added tasks before the failure will remain in the group. Failures will be logged to /sys/fs/resctrl/info/last\_cmd\_status.

  If the group is a CTRL\_MON group the task is removed from whichever previous CTRL\_MON group owned the task and also from any MON group that owned the task. If the group is a MON group, then the task must already belong to the CTRL\_MON parent of this group. The task is removed from any previous MON group.

- **"cpus":**

  Reading this file shows a bitmask of the logical CPUs owned by this group. Writing a mask to this file will add and remove CPUs to/from this group. As with the tasks file a hierarchy is maintained where MON groups may only include CPUs owned by the parent CTRL\_MON group. When the resource group is in pseudo-locked mode this file will only be readable, reflecting the CPUs associated with the pseudo-locked region.

- **"cpus\_list":**

  Just like "cpus", only using ranges of CPUs instead of bitmasks.

When control is enabled all CTRL\_MON groups will also contain:

- **"schemata":**

  A list of all the resources available to this group. Each resource has its own line and format - see below for details.

- **"size":**

  Mirrors the display of the "schemata" file to display the size in bytes of each allocation instead of the bits representing the allocation.

- **"mode":**

  The "mode" of the resource group dictates the sharing of its allocations. A "shareable" resource group allows sharing of its allocations while an "exclusive" resource group does not. A cache pseudo-locked region is created by first writing "pseudo-locksetup" to the "mode" file before writing the cache pseudo-locked region's schemata to the resource group's "schemata" file. On successful pseudo-locked region creation the mode will automatically change to "pseudo-locked".

- **"ctrl\_hw\_id":**

  Available only with debug option. The identifier used by hardware for the control group. On x86 this is the CLOSID.

When monitoring is enabled all MON groups will also contain:

- **"mon\_data":**

  This contains directories for each monitor domain.

  If L3 monitoring is enabled, there will be a "mon\_L3\_XX" directory for each instance of an L3 cache. Each directory contains files for the enabled L3 events (e.g. "llc\_occupancy", "mbm\_total\_bytes", and "mbm\_local\_bytes").

  If telemetry monitoring is enabled, there will be a "mon\_PERF\_PKG\_YY" directory for each physical processor package. Each directory contains files for the enabled telemetry events (e.g. "core\_energy". "activity", "uops\_retired", etc.)

  The info/`*`/mon\_features files provide the full list of enabled event/file names.

  "core energy" reports a floating point number for the energy (in Joules) consumed by cores (registers, arithmetic units, TLB and L1/L2 caches) during execution of instructions summed across all logical CPUs on a package for the current monitoring group.

  "activity" also reports a floating point value (in Farads).  This provides an estimate of work done independent of the frequency that the CPUs used for execution.

  Note that "core energy" and "activity" only measure energy/activity in the "core" of the CPU (arithmetic units, TLB, L1 and L2 caches, etc.). They do not include L3 cache, memory, I/O devices etc.

  All other events report decimal integer values.

  In a MON group these files provide a read out of the current value of the event for all tasks in the group. In CTRL\_MON groups these files provide the sum for all tasks in the CTRL\_MON group and all tasks in MON groups. Please see example section for more details on usage.

  On systems with Sub-NUMA Cluster (SNC) enabled there are extra directories for each node (located within the "mon\_L3\_XX" directory for the L3 cache they occupy). These are named "mon\_sub\_L3\_YY" where "YY" is the node number.

  When the 'mbm\_event' counter assignment mode is enabled, reading an MBM event of a MON group returns 'Unassigned' if no hardware counter is assigned to it. For CTRL\_MON groups, 'Unassigned' is returned if the MBM event does not have an assigned counter in the CTRL\_MON group nor in any of its associated MON groups.

- **"mon\_hw\_id":**

  Available only with debug option. The identifier used by hardware for the monitor group. On x86 this is the RMID.

When monitoring is enabled all MON groups may also contain:

- **"mbm\_L3\_assignments":**

  Exists when "mbm\_event" counter assignment mode is supported and lists the counter assignment states of the group.

  The assignment list is displayed in the following format:

  &lt;Event&gt;:&lt;Domain ID&gt;=&lt;Assignment state&gt;;&lt;Domain ID&gt;=&lt;Assignment state&gt;

  - **Event: A valid MBM event in the**

    /sys/fs/resctrl/info/L3\_MON/event\_configs directory.

  - **Domain ID: A valid domain ID. When writing, '\*' applies the changes**

    to all the domains.

  Assignment states:

  \_ : No counter assigned.

  e : Counter assigned exclusively.

  Example:

  To display the counter assignment states for the default group.



  ```text
  # cd /sys/fs/resctrl
  # cat /sys/fs/resctrl/mbm_L3_assignments
    mbm_total_bytes:0=e;1=e
    mbm_local_bytes:0=e;1=e
  ```

  Assignments can be modified by writing to the interface.

  Examples:

  To unassign the counter associated with the mbm\_total\_bytes event on domain 0:



  ```text
  # echo "mbm_total_bytes:0=_" > /sys/fs/resctrl/mbm_L3_assignments
  # cat /sys/fs/resctrl/mbm_L3_assignments
    mbm_total_bytes:0=_;1=e
    mbm_local_bytes:0=e;1=e
  ```

  To unassign the counter associated with the mbm\_total\_bytes event on all the domains:



  ```text
  # echo "mbm_total_bytes:*=_" > /sys/fs/resctrl/mbm_L3_assignments
  # cat /sys/fs/resctrl/mbm_L3_assignments
    mbm_total_bytes:0=_;1=_
    mbm_local_bytes:0=e;1=e
  ```

  To assign a counter associated with the mbm\_total\_bytes event on all domains in exclusive mode:



  ```text
  # echo "mbm_total_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments
  # cat /sys/fs/resctrl/mbm_L3_assignments
    mbm_total_bytes:0=e;1=e
    mbm_local_bytes:0=e;1=e
  ```

When the "mba\_MBps" mount option is used all CTRL\_MON groups will also contain:

- **"mba\_MBps\_event":**

  Reading this file shows which memory bandwidth event is used as input to the software feedback loop that keeps memory bandwidth below the value specified in the schemata file. Writing the name of one of the supported memory bandwidth events found in /sys/fs/resctrl/info/L3\_MON/mon\_features changes the input event.

<a id="rst-resource-allocation-rules"></a>

### Resource allocation rules

When a task is running the following rules define which resources are available to it:

1. If the task is a member of a non-default group, then the schemata for that group is used.

2. Else if the task belongs to the default group, but is running on a CPU that is assigned to some specific group, then the schemata for the CPU's group is used.

3. Otherwise the schemata for the default group is used.

<a id="rst-resource-monitoring-rules"></a>

### Resource monitoring rules

1. If a task is a member of a MON group, or non-default CTRL\_MON group then RDT events for the task will be reported in that group.

2. If a task is a member of the default CTRL\_MON group, but is running on a CPU that is assigned to some specific group, then the RDT events for the task will be reported in that group.

3. Otherwise RDT events for the task will be reported in the root level "mon\_data" group.

<a id="rst-notes-on-cache-occupancy-monitoring-and-control"></a>

## Notes on cache occupancy monitoring and control

When moving a task from one group to another you should remember that this only affects <em>new</em> cache allocations by the task. E.g. you may have a task in a monitor group showing 3 MB of cache occupancy. If you move to a new group and immediately check the occupancy of the old and new groups you will likely see that the old group is still showing 3 MB and the new group zero. When the task accesses locations still in cache from before the move, the h/w does not update any counters. On a busy system you will likely see the occupancy in the old group go down as cache lines are evicted and re-used while the occupancy in the new group rises as the task accesses memory and loads into the cache are counted based on membership in the new group.

The same applies to cache allocation control. Moving a task to a group with a smaller cache partition will not evict any cache lines. The process may continue to use them from the old partition.

Hardware uses CLOSid(Class of service ID) and an RMID(Resource monitoring ID) to identify a control group and a monitoring group respectively. Each of the resource groups are mapped to these IDs based on the kind of group. The number of CLOSid and RMID are limited by the hardware and hence the creation of a "CTRL\_MON" directory may fail if we run out of either CLOSID or RMID and creation of "MON" group may fail if we run out of RMIDs.

<a id="rst-max-threshold-occupancy-generic-concepts"></a>

### max\_threshold\_occupancy - generic concepts

Note that an RMID once freed may not be immediately available for use as the RMID is still tagged the cache lines of the previous user of RMID. Hence such RMIDs are placed on limbo list and checked back if the cache occupancy has gone down. If there is a time when system has a lot of limbo RMIDs but which are not ready to be used, user may see an -EBUSY during mkdir.

max\_threshold\_occupancy is a user configurable value to determine the occupancy at which an RMID can be freed.

The mon\_llc\_occupancy\_limbo tracepoint gives the precise occupancy in bytes for a subset of RMID that are not immediately available for allocation. This can't be relied on to produce output every second, it may be necessary to attempt to create an empty monitor group to force an update. Output may only be produced if creation of a control or monitor group fails.

<a id="rst-schemata-files-general-concepts"></a>

### Schemata files - general concepts

Each line in the file describes one resource. The line starts with the name of the resource, followed by specific values to be applied in each of the instances of that resource on the system.

<a id="rst-cache-ids"></a>

### Cache IDs

On current generation systems there is one L3 cache per socket and L2 caches are generally just shared by the hyperthreads on a core, but this isn't an architectural requirement. We could have multiple separate L3 caches on a socket, multiple cores could share an L2 cache. So instead of using "socket" or "core" to define the set of logical cpus sharing a resource we use a "Cache ID". At a given cache level this will be a unique number across the whole system (but it isn't guaranteed to be a contiguous sequence, there may be gaps).  To find the ID for each logical CPU look in /sys/devices/system/cpu/cpu\*/cache/index\*/id

<a id="rst-cache-bit-masks-cbm"></a>

### Cache Bit Masks (CBM)

For cache resources we describe the portion of the cache that is available for allocation using a bitmask. The maximum value of the mask is defined by each cpu model (and may be different for different cache levels). It is found using CPUID, but is also provided in the "info" directory of the resctrl file system in "info/\{resource\}/cbm\_mask". Some Intel hardware requires that these masks have all the '1' bits in a contiguous block. So 0x3, 0x6 and 0xC are legal 4-bit masks with two bits set, but 0x5, 0x9 and 0xA are not. Check /sys/fs/resctrl/info/\{resource\}/sparse\_masks if non-contiguous 1s value is supported. On a system with a 20-bit mask each bit represents 5% of the capacity of the cache. You could partition the cache into four equal parts with masks: 0x1f, 0x3e0, 0x7c00, 0xf8000.

<a id="rst-notes-on-sub-numa-cluster-mode"></a>

## Notes on Sub-NUMA Cluster mode

When SNC mode is enabled, Linux may load balance tasks between Sub-NUMA nodes much more readily than between regular NUMA nodes since the CPUs on Sub-NUMA nodes share the same L3 cache and the system may report the NUMA distance between Sub-NUMA nodes with a lower value than used for regular NUMA nodes.

The top-level monitoring files in each "mon\_L3\_XX" directory provide the sum of data across all SNC nodes sharing an L3 cache instance. Users who bind tasks to the CPUs of a specific Sub-NUMA node can read the "llc\_occupancy", "mbm\_total\_bytes", and "mbm\_local\_bytes" in the "mon\_sub\_L3\_YY" directories to get node local data.

Memory bandwidth allocation is still performed at the L3 cache level. I.e. throttling controls are applied to all SNC nodes.

L3 cache allocation bitmaps also apply to all SNC nodes. But note that the amount of L3 cache represented by each bit is divided by the number of SNC nodes per L3 cache. E.g. with a 100MB cache on a system with 10-bit allocation masks each bit normally represents 10MB. With SNC mode enabled with two SNC nodes per L3 cache, each bit only represents 5MB.

<a id="rst-memory-bandwidth-allocation-and-monitoring"></a>

## Memory bandwidth Allocation and monitoring

For Memory bandwidth resource, by default the user controls the resource by indicating the percentage of total memory bandwidth.

The minimum bandwidth percentage value for each cpu model is predefined and can be looked up through "info/MB/min\_bandwidth". The bandwidth granularity that is allocated is also dependent on the cpu model and can be looked up at "info/MB/bandwidth\_gran". The available bandwidth control steps are: min\_bw + N \* bw\_gran. Intermediate values are rounded to the next control step available on the hardware.

The bandwidth throttling is a core specific mechanism on some of Intel SKUs. Using a high bandwidth and a low bandwidth setting on two threads sharing a core may result in both threads being throttled to use the low bandwidth (see "thread\_throttle\_mode").

The fact that Memory bandwidth allocation(MBA) may be a core specific mechanism where as memory bandwidth monitoring(MBM) is done at the package level may lead to confusion when users try to apply control via the MBA and then monitor the bandwidth to see if the controls are effective. Below are such scenarios:

1. User may <em>not</em> see increase in actual bandwidth when percentage values are increased:

This can occur when aggregate L2 external bandwidth is more than L3 external bandwidth. Consider an SKL SKU with 24 cores on a package and where L2 external  is 10GBps (hence aggregate L2 external bandwidth is 240GBps) and L3 external bandwidth is 100GBps. Now a workload with '20 threads, having 50% bandwidth, each consuming 5GBps' consumes the max L3 bandwidth of 100GBps although the percentage value specified is only 50% &lt;&lt; 100%. Hence increasing the bandwidth percentage will not yield any more bandwidth. This is because although the L2 external bandwidth still has capacity, the L3 external bandwidth is fully used. Also note that this would be dependent on number of cores the benchmark is run on.

2. Same bandwidth percentage may mean different actual bandwidth depending on \# of threads:

For the same SKU in \#1, a 'single thread, with 10% bandwidth' and '4 thread, with 10% bandwidth' can consume up to 10GBps and 40GBps although they have same percentage bandwidth of 10%. This is simply because as threads start using more cores in an rdtgroup, the actual bandwidth may increase or vary although user specified bandwidth percentage is same.

In order to mitigate this and make the interface more user friendly, resctrl added support for specifying the bandwidth in MiBps as well.  The kernel underneath would use a software feedback mechanism or a "Software Controller(mba\_sc)" which reads the actual bandwidth using MBM counters and adjust the memory bandwidth percentages to ensure:



```text
"actual bandwidth < user specified bandwidth".
```

By default, the schemata would take the bandwidth percentage values where as user can switch to the "MBA software controller" mode using a mount option 'mba\_MBps'. The schemata format is specified in the below sections.

<a id="rst-l3-schemata-file-details-code-and-data-prioritization-disabled"></a>

### L3 schemata file details (code and data prioritization disabled)

With CDP disabled the L3 schemata format is:



```text
L3:<cache_id0>=<cbm>;<cache_id1>=<cbm>;...
```

<a id="rst-l3-schemata-file-details-cdp-enabled-via-mount-option-to-resctrl"></a>

### L3 schemata file details (CDP enabled via mount option to resctrl)

When CDP is enabled L3 control is split into two separate resources so you can specify independent masks for code and data like this:



```text
L3DATA:<cache_id0>=<cbm>;<cache_id1>=<cbm>;...
L3CODE:<cache_id0>=<cbm>;<cache_id1>=<cbm>;...
```

<a id="rst-l2-schemata-file-details"></a>

### L2 schemata file details

CDP is supported at L2 using the 'cdpl2' mount option. The schemata format is either:



```text
L2:<cache_id0>=<cbm>;<cache_id1>=<cbm>;...
```

or

> L2DATA:&lt;cache\_id0&gt;=&lt;cbm&gt;;&lt;cache\_id1&gt;=&lt;cbm&gt;;... L2CODE:&lt;cache\_id0&gt;=&lt;cbm&gt;;&lt;cache\_id1&gt;=&lt;cbm&gt;;...

<a id="rst-memory-bandwidth-allocation-default-mode"></a>

### Memory bandwidth Allocation (default mode)

Memory b/w domain is L3 cache.



```text
MB:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;...
```

<a id="rst-memory-bandwidth-allocation-specified-in-mibps"></a>

### Memory bandwidth Allocation specified in MiBps

Memory bandwidth domain is L3 cache.



```text
MB:<cache_id0>=bw_MiBps0;<cache_id1>=bw_MiBps1;...
```

<a id="rst-slow-memory-bandwidth-allocation-smba"></a>

### Slow Memory Bandwidth Allocation (SMBA)

AMD hardware supports Slow Memory Bandwidth Allocation (SMBA). CXL.memory is the only supported "slow" memory device. With the support of SMBA, the hardware enables bandwidth allocation on the slow memory devices. If there are multiple such devices in the system, the throttling logic groups all the slow sources together and applies the limit on them as a whole.

The presence of SMBA (with CXL.memory) is independent of slow memory devices presence. If there are no such devices on the system, then configuring SMBA will have no impact on the performance of the system.

The bandwidth domain for slow memory is L3 cache. Its schemata file is formatted as:



```text
SMBA:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;...
```

<a id="rst-reading-writing-the-schemata-file"></a>

### Reading/writing the schemata file

Reading the schemata file will show the state of all resources on all domains. When writing you only need to specify those values which you wish to change.  E.g.



```text
# cat schemata
L3DATA:0=fffff;1=fffff;2=fffff;3=fffff
L3CODE:0=fffff;1=fffff;2=fffff;3=fffff
# echo "L3DATA:2=3c0;" > schemata
# cat schemata
L3DATA:0=fffff;1=fffff;2=3c0;3=fffff
L3CODE:0=fffff;1=fffff;2=fffff;3=fffff
```

<a id="rst-reading-writing-the-schemata-file-on-amd-systems"></a>

### Reading/writing the schemata file (on AMD systems)

Reading the schemata file will show the current bandwidth limit on all domains. The allocated resources are in multiples of one eighth GB/s. When writing to the file, you need to specify what cache id you wish to configure the bandwidth limit.

For example, to allocate 2GB/s limit on the first cache id:



```text
# cat schemata
  MB:0=2048;1=2048;2=2048;3=2048
  L3:0=ffff;1=ffff;2=ffff;3=ffff

# echo "MB:1=16" > schemata
# cat schemata
  MB:0=2048;1=  16;2=2048;3=2048
  L3:0=ffff;1=ffff;2=ffff;3=ffff
```

<a id="rst-reading-writing-the-schemata-file-on-amd-systems-with-smba-feature"></a>

### Reading/writing the schemata file (on AMD systems) with SMBA feature

Reading and writing the schemata file is the same as without SMBA in above section.

For example, to allocate 8GB/s limit on the first cache id:



```text
# cat schemata
  SMBA:0=2048;1=2048;2=2048;3=2048
    MB:0=2048;1=2048;2=2048;3=2048
    L3:0=ffff;1=ffff;2=ffff;3=ffff

# echo "SMBA:1=64" > schemata
# cat schemata
  SMBA:0=2048;1=  64;2=2048;3=2048
    MB:0=2048;1=2048;2=2048;3=2048
    L3:0=ffff;1=ffff;2=ffff;3=ffff
```

<a id="rst-cache-pseudo-locking"></a>

## Cache Pseudo-Locking

CAT enables a user to specify the amount of cache space that an application can fill. Cache pseudo-locking builds on the fact that a CPU can still read and write data pre-allocated outside its current allocated area on a cache hit. With cache pseudo-locking, data can be preloaded into a reserved portion of cache that no application can fill, and from that point on will only serve cache hits. The cache pseudo-locked memory is made accessible to user space where an application can map it into its virtual address space and thus have a region of memory with reduced average read latency.

The creation of a cache pseudo-locked region is triggered by a request from the user to do so that is accompanied by a schemata of the region to be pseudo-locked. The cache pseudo-locked region is created as follows:

- Create a CAT allocation CLOSNEW with a CBM matching the schemata from the user of the cache region that will contain the pseudo-locked memory. This region must not overlap with any current CAT allocation/CLOS on the system and no future overlap with this cache region is allowed while the pseudo-locked region exists.

- Create a contiguous region of memory of the same size as the cache region.

- Flush the cache, disable hardware prefetchers, disable preemption.

- Make CLOSNEW the active CLOS and touch the allocated memory to load it into the cache.

- Set the previous CLOS as active.

- At this point the closid CLOSNEW can be released - the cache pseudo-locked region is protected as long as its CBM does not appear in any CAT allocation. Even though the cache pseudo-locked region will from this point on not appear in any CBM of any CLOS an application running with any CLOS will be able to access the memory in the pseudo-locked region since the region continues to serve cache hits.

- The contiguous region of memory loaded into the cache is exposed to user-space as a character device.

Cache pseudo-locking increases the probability that data will remain in the cache via carefully configuring the CAT feature and controlling application behavior. There is no guarantee that data is placed in cache. Instructions like INVD, WBINVD, CLFLUSH, etc. can still evict “locked” data from cache. Power management C-states may shrink or power off cache. Deeper C-states will automatically be restricted on pseudo-locked region creation.

It is required that an application using a pseudo-locked region runs with affinity to the cores (or a subset of the cores) associated with the cache on which the pseudo-locked region resides. A sanity check within the code will not allow an application to map pseudo-locked memory unless it runs with affinity to cores associated with the cache on which the pseudo-locked region resides. The sanity check is only done during the initial mmap() handling, there is no enforcement afterwards and the application self needs to ensure it remains affine to the correct cores.

Pseudo-locking is accomplished in two stages:

1. During the first stage the system administrator allocates a portion of cache that should be dedicated to pseudo-locking. At this time an equivalent portion of memory is allocated, loaded into allocated cache portion, and exposed as a character device.

2. During the second stage a user-space application maps (mmap()) the pseudo-locked memory into its address space.

<a id="rst-cache-pseudo-locking-interface"></a>

### Cache Pseudo-Locking Interface

A pseudo-locked region is created using the resctrl interface as follows:

1. Create a new resource group by creating a new directory in /sys/fs/resctrl.

2. Change the new resource group's mode to "pseudo-locksetup" by writing "pseudo-locksetup" to the "mode" file.

3. Write the schemata of the pseudo-locked region to the "schemata" file. All bits within the schemata should be "unused" according to the "bit\_usage" file.

On successful pseudo-locked region creation the "mode" file will contain "pseudo-locked" and a new character device with the same name as the resource group will exist in /dev/pseudo\_lock. This character device can be mmap()'ed by user space in order to obtain access to the pseudo-locked memory region.

An example of cache pseudo-locked region creation and usage can be found below.

<a id="rst-cache-pseudo-locking-debugging-interface"></a>

### Cache Pseudo-Locking Debugging Interface

The pseudo-locking debugging interface is enabled by default (if CONFIG\_DEBUG\_FS is enabled) and can be found in /sys/kernel/debug/resctrl.

There is no explicit way for the kernel to test if a provided memory location is present in the cache. The pseudo-locking debugging interface uses the tracing infrastructure to provide two ways to measure cache residency of the pseudo-locked region:

1. Memory access latency using the pseudo\_lock\_mem\_latency tracepoint. Data from these measurements are best visualized using a hist trigger (see example below). In this test the pseudo-locked region is traversed at a stride of 32 bytes while hardware prefetchers and preemption are disabled. This also provides a substitute visualization of cache hits and misses.

2. Cache hit and miss measurements using model specific precision counters if available. Depending on the levels of cache on the system the pseudo\_lock\_l2 and pseudo\_lock\_l3 tracepoints are available.

When a pseudo-locked region is created a new debugfs directory is created for it in debugfs as /sys/kernel/debug/resctrl/&lt;newdir&gt;. A single write-only file, pseudo\_lock\_measure, is present in this directory. The measurement of the pseudo-locked region depends on the number written to this debugfs file:

- **1:**

  writing "1" to the pseudo\_lock\_measure file will trigger the latency measurement captured in the pseudo\_lock\_mem\_latency tracepoint. See example below.

- **2:**

  writing "2" to the pseudo\_lock\_measure file will trigger the L2 cache residency (cache hits and misses) measurement captured in the pseudo\_lock\_l2 tracepoint. See example below.

- **3:**

  writing "3" to the pseudo\_lock\_measure file will trigger the L3 cache residency (cache hits and misses) measurement captured in the pseudo\_lock\_l3 tracepoint.

All measurements are recorded with the tracing infrastructure. This requires the relevant tracepoints to be enabled before the measurement is triggered.

<a id="rst-example-of-latency-debugging-interface"></a>

#### Example of latency debugging interface

In this example a pseudo-locked region named "newlock" was created. Here is how we can measure the latency in cycles of reading from this region and visualize this data with a histogram that is available if CONFIG\_HIST\_TRIGGERS is set:



```text
# :> /sys/kernel/tracing/trace
# echo 'hist:keys=latency' > /sys/kernel/tracing/events/resctrl/pseudo_lock_mem_latency/trigger
# echo 1 > /sys/kernel/tracing/events/resctrl/pseudo_lock_mem_latency/enable
# echo 1 > /sys/kernel/debug/resctrl/newlock/pseudo_lock_measure
# echo 0 > /sys/kernel/tracing/events/resctrl/pseudo_lock_mem_latency/enable
# cat /sys/kernel/tracing/events/resctrl/pseudo_lock_mem_latency/hist

# event histogram
#
# trigger info: hist:keys=latency:vals=hitcount:sort=hitcount:size=2048 [active]
#

{ latency:        456 } hitcount:          1
{ latency:         50 } hitcount:         83
{ latency:         36 } hitcount:         96
{ latency:         44 } hitcount:        174
{ latency:         48 } hitcount:        195
{ latency:         46 } hitcount:        262
{ latency:         42 } hitcount:        693
{ latency:         40 } hitcount:       3204
{ latency:         38 } hitcount:       3484

Totals:
    Hits: 8192
    Entries: 9
  Dropped: 0
```

<a id="rst-example-of-cache-hits-misses-debugging"></a>

#### Example of cache hits/misses debugging

In this example a pseudo-locked region named "newlock" was created on the L2 cache of a platform. Here is how we can obtain details of the cache hits and misses using the platform's precision counters.



```text
# :> /sys/kernel/tracing/trace
# echo 1 > /sys/kernel/tracing/events/resctrl/pseudo_lock_l2/enable
# echo 2 > /sys/kernel/debug/resctrl/newlock/pseudo_lock_measure
# echo 0 > /sys/kernel/tracing/events/resctrl/pseudo_lock_l2/enable
# cat /sys/kernel/tracing/trace

# tracer: nop
#
#                              _-----=> irqs-off
#                             / _----=> need-resched
#                            | / _---=> hardirq/softirq
#                            || / _--=> preempt-depth
#                            ||| /     delay
#           TASK-PID   CPU#  ||||    TIMESTAMP  FUNCTION
#              | |       |   ||||       |         |
pseudo_lock_mea-1672  [002] ....  3132.860500: pseudo_lock_l2: hits=4097 miss=0
```

<a id="rst-examples-for-rdt-allocation-usage"></a>

#### Examples for RDT allocation usage

1. Example 1

On a two socket machine (one L3 cache per socket) with just four bits for cache bit masks, minimum b/w of 10% with a memory bandwidth granularity of 10%.



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
# mkdir p0 p1
# echo "L3:0=3;1=c\nMB:0=50;1=50" > /sys/fs/resctrl/p0/schemata
# echo "L3:0=3;1=3\nMB:0=50;1=50" > /sys/fs/resctrl/p1/schemata
```

The default resource group is unmodified, so we have access to all parts of all caches (its schemata file reads "L3:0=f;1=f").

Tasks that are under the control of group "p0" may only allocate from the "lower" 50% on cache ID 0, and the "upper" 50% of cache ID 1. Tasks in group "p1" use the "lower" 50% of cache on both sockets.

Similarly, tasks that are under the control of group "p0" may use a maximum memory b/w of 50% on socket0 and 50% on socket 1. Tasks in group "p1" may also use 50% memory b/w on both sockets. Note that unlike cache masks, memory b/w cannot specify whether these allocations can overlap or not. The allocations specifies the maximum b/w that the group may be able to use and the system admin can configure the b/w accordingly.

If resctrl is using the software controller (mba\_sc) then user can enter the max b/w in MB rather than the percentage values.



```text
# echo "L3:0=3;1=c\nMB:0=1024;1=500" > /sys/fs/resctrl/p0/schemata
# echo "L3:0=3;1=3\nMB:0=1024;1=500" > /sys/fs/resctrl/p1/schemata
```

In the above example the tasks in "p1" and "p0" on socket 0 would use a max b/w of 1024MB where as on socket 1 they would use 500MB.

2. Example 2

Again two sockets, but this time with a more realistic 20-bit mask.

Two real time tasks pid=1234 running on processor 0 and pid=5678 running on processor 1 on socket 0 on a 2-socket and dual core machine. To avoid noisy neighbors, each of the two real-time tasks exclusively occupies one quarter of L3 cache on socket 0.



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
```

First we reset the schemata for the default group so that the "upper" 50% of the L3 cache on socket 0 and 50% of memory b/w cannot be used by ordinary tasks:



```text
# echo "L3:0=3ff;1=fffff\nMB:0=50;1=100" > schemata
```

Next we make a resource group for our first real time task and give it access to the "top" 25% of the cache on socket 0.



```text
# mkdir p0
# echo "L3:0=f8000;1=fffff" > p0/schemata
```

Finally we move our first real time task into this resource group. We also use taskset(1) to ensure the task always runs on a dedicated CPU on socket 0. Most uses of resource groups will also constrain which processors tasks run on.



```text
# echo 1234 > p0/tasks
# taskset -cp 1 1234
```

Ditto for the second real time task (with the remaining 25% of cache):



```text
# mkdir p1
# echo "L3:0=7c00;1=fffff" > p1/schemata
# echo 5678 > p1/tasks
# taskset -cp 2 5678
```

For the same 2 socket system with memory b/w resource and CAT L3 the schemata would look like(Assume min\_bandwidth 10 and bandwidth\_gran is 10):

For our first real time task this would request 20% memory b/w on socket 0.



```text
# echo -e "L3:0=f8000;1=fffff\nMB:0=20;1=100" > p0/schemata
```

For our second real time task this would request an other 20% memory b/w on socket 0.



```text
# echo -e "L3:0=f8000;1=fffff\nMB:0=20;1=100" > p0/schemata
```

3. Example 3

A single socket system which has real-time tasks running on core 4-7 and non real-time workload assigned to core 0-3. The real-time tasks share text and data, so a per task association is not required and due to interaction with the kernel it's desired that the kernel on these cores shares L3 with the tasks.



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
```

First we reset the schemata for the default group so that the "upper" 50% of the L3 cache on socket 0, and 50% of memory bandwidth on socket 0 cannot be used by ordinary tasks:



```text
# echo "L3:0=3ff\nMB:0=50" > schemata
```

Next we make a resource group for our real time cores and give it access to the "top" 50% of the cache on socket 0 and 50% of memory bandwidth on socket 0.



```text
# mkdir p0
# echo "L3:0=ffc00\nMB:0=50" > p0/schemata
```

Finally we move core 4-7 over to the new group and make sure that the kernel and the tasks running there get 50% of the cache. They should also get 50% of memory bandwidth assuming that the cores 4-7 are SMT siblings and only the real time threads are scheduled on the cores 4-7.



```text
# echo F0 > p0/cpus
```

4. Example 4

The resource groups in previous examples were all in the default "shareable" mode allowing sharing of their cache allocations. If one resource group configures a cache allocation then nothing prevents another resource group to overlap with that allocation.

In this example a new exclusive resource group will be created on a L2 CAT system with two L2 cache instances that can be configured with an 8-bit capacity bitmask. The new exclusive resource group will be configured to use 25% of each cache instance.



```text
# mount -t resctrl resctrl /sys/fs/resctrl/
# cd /sys/fs/resctrl
```

First, we observe that the default group is configured to allocate to all L2 cache:



```text
# cat schemata
L2:0=ff;1=ff
```

We could attempt to create the new resource group at this point, but it will fail because of the overlap with the schemata of the default group:



```text
# mkdir p0
# echo 'L2:0=0x3;1=0x3' > p0/schemata
# cat p0/mode
shareable
# echo exclusive > p0/mode
-sh: echo: write error: Invalid argument
# cat info/last_cmd_status
schemata overlaps
```

To ensure that there is no overlap with another resource group the default resource group's schemata has to change, making it possible for the new resource group to become exclusive.



```text
# echo 'L2:0=0xfc;1=0xfc' > schemata
# echo exclusive > p0/mode
# grep . p0/*
p0/cpus:0
p0/mode:exclusive
p0/schemata:L2:0=03;1=03
p0/size:L2:0=262144;1=262144
```

A new resource group will on creation not overlap with an exclusive resource group:



```text
# mkdir p1
# grep . p1/*
p1/cpus:0
p1/mode:shareable
p1/schemata:L2:0=fc;1=fc
p1/size:L2:0=786432;1=786432
```

The bit\_usage will reflect how the cache is used:



```text
# cat info/L2/bit_usage
0=SSSSSSEE;1=SSSSSSEE
```

A resource group cannot be forced to overlap with an exclusive resource group:



```text
# echo 'L2:0=0x1;1=0x1' > p1/schemata
-sh: echo: write error: Invalid argument
# cat info/last_cmd_status
overlaps with exclusive group
```

<a id="rst-example-of-cache-pseudo-locking"></a>

#### Example of Cache Pseudo-Locking

Lock portion of L2 cache from cache id 1 using CBM 0x3. Pseudo-locked region is exposed at /dev/pseudo\_lock/newlock that can be provided to application for argument to mmap().



```text
# mount -t resctrl resctrl /sys/fs/resctrl/
# cd /sys/fs/resctrl
```

Ensure that there are bits available that can be pseudo-locked, since only unused bits can be pseudo-locked the bits to be pseudo-locked needs to be removed from the default resource group's schemata:



```text
# cat info/L2/bit_usage
0=SSSSSSSS;1=SSSSSSSS
# echo 'L2:1=0xfc' > schemata
# cat info/L2/bit_usage
0=SSSSSSSS;1=SSSSSS00
```

Create a new resource group that will be associated with the pseudo-locked region, indicate that it will be used for a pseudo-locked region, and configure the requested pseudo-locked region capacity bitmask:



```text
# mkdir newlock
# echo pseudo-locksetup > newlock/mode
# echo 'L2:1=0x3' > newlock/schemata
```

On success the resource group's mode will change to pseudo-locked, the bit\_usage will reflect the pseudo-locked region, and the character device exposing the pseudo-locked region will exist:



```text
# cat newlock/mode
pseudo-locked
# cat info/L2/bit_usage
0=SSSSSSSS;1=SSSSSSPP
# ls -l /dev/pseudo_lock/newlock
crw------- 1 root root 243, 0 Apr  3 05:01 /dev/pseudo_lock/newlock
```



```text
/*
* Example code to access one page of pseudo-locked cache region
* from user space.
*/
#define _GNU_SOURCE
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

/*
* It is required that the application runs with affinity to only
* cores associated with the pseudo-locked region. Here the cpu
* is hardcoded for convenience of example.
*/
static int cpuid = 2;

int main(int argc, char *argv[])
{
  cpu_set_t cpuset;
  long page_size;
  void *mapping;
  int dev_fd;
  int ret;

  page_size = sysconf(_SC_PAGESIZE);

  CPU_ZERO(&cpuset);
  CPU_SET(cpuid, &cpuset);
  ret = sched_setaffinity(0, sizeof(cpuset), &cpuset);
  if (ret < 0) {
    perror("sched_setaffinity");
    exit(EXIT_FAILURE);
  }

  dev_fd = open("/dev/pseudo_lock/newlock", O_RDWR);
  if (dev_fd < 0) {
    perror("open");
    exit(EXIT_FAILURE);
  }

  mapping = mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_SHARED,
          dev_fd, 0);
  if (mapping == MAP_FAILED) {
    perror("mmap");
    close(dev_fd);
    exit(EXIT_FAILURE);
  }

  /* Application interacts with pseudo-locked memory @mapping */

  ret = munmap(mapping, page_size);
  if (ret < 0) {
    perror("munmap");
    close(dev_fd);
    exit(EXIT_FAILURE);
  }

  close(dev_fd);
  exit(EXIT_SUCCESS);
}
```

<a id="rst-locking-between-applications"></a>

### Locking between applications

Certain operations on the resctrl filesystem, composed of read/writes to/from multiple files, must be atomic.

As an example, the allocation of an exclusive reservation of L3 cache involves:

> 1. Read the cbmmasks from each directory or the per-resource "bit\_usage"
>
> 2. Find a contiguous set of bits in the global CBM bitmask that is clear in any of the directory cbmmasks
>
> 3. Create a new directory
>
> 4. Set the bits found in step 2 to the new directory "schemata" file

If two applications attempt to allocate space concurrently then they can end up allocating the same bits so the reservations are shared instead of exclusive.

To coordinate atomic operations on the resctrlfs and to avoid the problem above, the following locking procedure is recommended:

Locking is based on flock, which is available in libc and also as a shell script command

Write lock:

> - **A)** Take flock(LOCK\_EX) on /sys/fs/resctrl
>
> - **B)** Read/write the directory structure.
>
> - **C)** funlock

Read lock:

> - **A)** Take flock(LOCK\_SH) on /sys/fs/resctrl
>
> - **B)** If success read the directory structure.
>
> - **C)** funlock

Example with bash:



```text
# Atomically read directory structure
$ flock -s /sys/fs/resctrl/ find /sys/fs/resctrl

# Read directory contents and create new subdirectory

$ cat create-dir.sh
find /sys/fs/resctrl/ > output.txt
mask = function-of(output.txt)
mkdir /sys/fs/resctrl/newres/
echo mask > /sys/fs/resctrl/newres/schemata

$ flock /sys/fs/resctrl/ ./create-dir.sh
```

Example with C:



```text
/*
* Example code do take advisory locks
* before accessing resctrl filesystem
*/
#include <sys/file.h>
#include <stdlib.h>

void resctrl_take_shared_lock(int fd)
{
  int ret;

  /* take shared lock on resctrl filesystem */
  ret = flock(fd, LOCK_SH);
  if (ret) {
    perror("flock");
    exit(-1);
  }
}

void resctrl_take_exclusive_lock(int fd)
{
  int ret;

  /* release lock on resctrl filesystem */
  ret = flock(fd, LOCK_EX);
  if (ret) {
    perror("flock");
    exit(-1);
  }
}

void resctrl_release_lock(int fd)
{
  int ret;

  /* take shared lock on resctrl filesystem */
  ret = flock(fd, LOCK_UN);
  if (ret) {
    perror("flock");
    exit(-1);
  }
}

void main(void)
{
  int fd, ret;

  fd = open("/sys/fs/resctrl", O_DIRECTORY);
  if (fd == -1) {
    perror("open");
    exit(-1);
  }
  resctrl_take_shared_lock(fd);
  /* code to read directory contents */
  resctrl_release_lock(fd);

  resctrl_take_exclusive_lock(fd);
  /* code to read and write directory contents */
  resctrl_release_lock(fd);
}
```

<a id="rst-examples-for-rdt-monitoring-along-with-allocation-usage"></a>

## Examples for RDT Monitoring along with allocation usage

<a id="rst-reading-monitored-data"></a>

### Reading monitored data

Reading an event file (for ex: mon\_data/mon\_L3\_00/llc\_occupancy) would show the current snapshot of LLC occupancy of the corresponding MON group or CTRL\_MON group.

<a id="rst-example-1-monitor-ctrl-mon-group-and-subset-of-tasks-in-ctrl-mon-group"></a>

### Example 1 (Monitor CTRL\_MON group and subset of tasks in CTRL\_MON group)

On a two socket machine (one L3 cache per socket) with just four bits for cache bit masks:



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
# mkdir p0 p1
# echo "L3:0=3;1=c" > /sys/fs/resctrl/p0/schemata
# echo "L3:0=3;1=3" > /sys/fs/resctrl/p1/schemata
# echo 5678 > p1/tasks
# echo 5679 > p1/tasks
```

The default resource group is unmodified, so we have access to all parts of all caches (its schemata file reads "L3:0=f;1=f").

Tasks that are under the control of group "p0" may only allocate from the "lower" 50% on cache ID 0, and the "upper" 50% of cache ID 1. Tasks in group "p1" use the "lower" 50% of cache on both sockets.

Create monitor groups and assign a subset of tasks to each monitor group.



```text
# cd /sys/fs/resctrl/p1/mon_groups
# mkdir m11 m12
# echo 5678 > m11/tasks
# echo 5679 > m12/tasks
```

fetch data (data shown in bytes)



```text
# cat m11/mon_data/mon_L3_00/llc_occupancy
16234000
# cat m11/mon_data/mon_L3_01/llc_occupancy
14789000
# cat m12/mon_data/mon_L3_00/llc_occupancy
16789000
```

The parent ctrl\_mon group shows the aggregated data.



```text
# cat /sys/fs/resctrl/p1/mon_data/mon_l3_00/llc_occupancy
31234000
```

<a id="rst-example-2-monitor-a-task-from-its-creation"></a>

### Example 2 (Monitor a task from its creation)

On a two socket machine (one L3 cache per socket):



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
# mkdir p0 p1
```

An RMID is allocated to the group once its created and hence the &lt;cmd&gt; below is monitored from its creation.



```text
# echo $$ > /sys/fs/resctrl/p1/tasks
# <cmd>
```

Fetch the data:



```text
# cat /sys/fs/resctrl/p1/mon_data/mon_l3_00/llc_occupancy
31789000
```

<a id="rst-example-3-monitor-without-cat-support-or-before-creating-cat-groups"></a>

### Example 3 (Monitor without CAT support or before creating CAT groups)

Assume a system like HSW has only CQM and no CAT support. In this case the resctrl will still mount but cannot create CTRL\_MON directories. But user can create different MON groups within the root group thereby able to monitor all tasks including kernel threads.

This can also be used to profile jobs cache size footprint before being able to allocate them to different allocation groups.



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
# mkdir mon_groups/m01
# mkdir mon_groups/m02

# echo 3478 > /sys/fs/resctrl/mon_groups/m01/tasks
# echo 2467 > /sys/fs/resctrl/mon_groups/m02/tasks
```

Monitor the groups separately and also get per domain data. From the below its apparent that the tasks are mostly doing work on domain(socket) 0.



```text
# cat /sys/fs/resctrl/mon_groups/m01/mon_L3_00/llc_occupancy
31234000
# cat /sys/fs/resctrl/mon_groups/m01/mon_L3_01/llc_occupancy
34555
# cat /sys/fs/resctrl/mon_groups/m02/mon_L3_00/llc_occupancy
31234000
# cat /sys/fs/resctrl/mon_groups/m02/mon_L3_01/llc_occupancy
32789
```

<a id="rst-example-4-monitor-real-time-tasks"></a>

### Example 4 (Monitor real time tasks)

A single socket system which has real time tasks running on cores 4-7 and non real time tasks on other cpus. We want to monitor the cache occupancy of the real time threads on these cores.



```text
# mount -t resctrl resctrl /sys/fs/resctrl
# cd /sys/fs/resctrl
# mkdir p1
```

Move the cpus 4-7 over to p1:



```text
# echo f0 > p1/cpus
```

View the llc occupancy snapshot:



```text
# cat /sys/fs/resctrl/p1/mon_data/mon_L3_00/llc_occupancy
11234000
```

<a id="rst-examples-on-working-with-mbm-assign-mode"></a>

## Examples on working with mbm\_assign\_mode

a. Check if MBM counter assignment mode is supported.



```text
# mount -t resctrl resctrl /sys/fs/resctrl/

# cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
[mbm_event]
default
```

The "mbm\_event" mode is detected and enabled.

b. Check how many assignable counters are supported.



```text
# cat /sys/fs/resctrl/info/L3_MON/num_mbm_cntrs
0=32;1=32
```

c. Check how many assignable counters are available for assignment in each domain.



```text
# cat /sys/fs/resctrl/info/L3_MON/available_mbm_cntrs
0=30;1=30
```

d. To list the default group's assign states.



```text
# cat /sys/fs/resctrl/mbm_L3_assignments
mbm_total_bytes:0=e;1=e
mbm_local_bytes:0=e;1=e
```

e.  To unassign the counter associated with the mbm\_total\_bytes event on domain 0.



```text
# echo "mbm_total_bytes:0=_" > /sys/fs/resctrl/mbm_L3_assignments
# cat /sys/fs/resctrl/mbm_L3_assignments
mbm_total_bytes:0=_;1=e
mbm_local_bytes:0=e;1=e
```

f. To unassign the counter associated with the mbm\_total\_bytes event on all domains.



```text
# echo "mbm_total_bytes:*=_" > /sys/fs/resctrl/mbm_L3_assignments
# cat /sys/fs/resctrl/mbm_L3_assignment
mbm_total_bytes:0=_;1=_
mbm_local_bytes:0=e;1=e
```

g. To assign a counter associated with the mbm\_total\_bytes event on all domains in exclusive mode.



```text
# echo "mbm_total_bytes:*=e" > /sys/fs/resctrl/mbm_L3_assignments
# cat /sys/fs/resctrl/mbm_L3_assignments
mbm_total_bytes:0=e;1=e
mbm_local_bytes:0=e;1=e
```

h. Read the events mbm\_total\_bytes and mbm\_local\_bytes of the default group. There is no change in reading the events with the assignment.



```text
# cat /sys/fs/resctrl/mon_data/mon_L3_00/mbm_total_bytes
779247936
# cat /sys/fs/resctrl/mon_data/mon_L3_01/mbm_total_bytes
562324232
# cat /sys/fs/resctrl/mon_data/mon_L3_00/mbm_local_bytes
212122123
# cat /sys/fs/resctrl/mon_data/mon_L3_01/mbm_local_bytes
121212144
```

i. Check the event configurations.



```text
# cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_total_bytes/event_filter
local_reads,remote_reads,local_non_temporal_writes,remote_non_temporal_writes,
local_reads_slow_memory,remote_reads_slow_memory,dirty_victim_writes_all

# cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_local_bytes/event_filter
local_reads,local_non_temporal_writes,local_reads_slow_memory
```

j. Change the event configuration for mbm\_local\_bytes.



```text
# echo "local_reads, local_non_temporal_writes, local_reads_slow_memory, remote_reads" >
/sys/fs/resctrl/info/L3_MON/event_configs/mbm_local_bytes/event_filter

# cat /sys/fs/resctrl/info/L3_MON/event_configs/mbm_local_bytes/event_filter
local_reads,local_non_temporal_writes,local_reads_slow_memory,remote_reads
```

k. Now read the local events again. The first read may come back with "Unavailable" status. The subsequent read of mbm\_local\_bytes will display the current value.



```text
# cat /sys/fs/resctrl/mon_data/mon_L3_00/mbm_local_bytes
Unavailable
# cat /sys/fs/resctrl/mon_data/mon_L3_00/mbm_local_bytes
2252323
# cat /sys/fs/resctrl/mon_data/mon_L3_01/mbm_local_bytes
Unavailable
# cat /sys/fs/resctrl/mon_data/mon_L3_01/mbm_local_bytes
1566565
```

l. Users have the option to go back to 'default' mbm\_assign\_mode if required. This can be done using the following command. Note that switching the mbm\_assign\_mode may reset all the MBM counters (and thus all MBM events) of all the resctrl groups.



```text
# echo "default" > /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
# cat /sys/fs/resctrl/info/L3_MON/mbm_assign_mode
mbm_event
[default]
```

m. Unmount the resctrl filesystem.



```text
# umount /sys/fs/resctrl/
```

<a id="rst-intel-rdt-errata"></a>

## Intel RDT Errata

<a id="rst-intel-mbm-counters-may-report-system-memory-bandwidth-incorrectly"></a>

### Intel MBM Counters May Report System Memory Bandwidth Incorrectly

Errata SKX99 for Skylake server and BDF102 for Broadwell server.

Problem: Intel Memory Bandwidth Monitoring (MBM) counters track metrics according to the assigned Resource Monitor ID (RMID) for that logical core. The IA32\_QM\_CTR register (MSR 0xC8E), used to report these metrics, may report incorrect system bandwidth for certain RMID values.

Implication: Due to the errata, system memory bandwidth may not match what is reported.

Workaround: MBM total and local readings are corrected according to the following correction factor table:


<table>
<tbody>
<tr>
<td>


core count

</td>
<td>


rmid count

</td>
<td>


rmid threshold

</td>
<td>


correction factor

</td>
</tr>
<tr>
<td>


1

</td>
<td>


8

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


2

</td>
<td>


16

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


3

</td>
<td>


24

</td>
<td>


15

</td>
<td>


0.969650

</td>
</tr>
<tr>
<td>


4

</td>
<td>


32

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


6

</td>
<td>


48

</td>
<td>


31

</td>
<td>


0.969650

</td>
</tr>
<tr>
<td>


7

</td>
<td>


56

</td>
<td>


47

</td>
<td>


1.142857

</td>
</tr>
<tr>
<td>


8

</td>
<td>


64

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


9

</td>
<td>


72

</td>
<td>


63

</td>
<td>


1.185115

</td>
</tr>
<tr>
<td>


10

</td>
<td>


80

</td>
<td>


63

</td>
<td>


1.066553

</td>
</tr>
<tr>
<td>


11

</td>
<td>


88

</td>
<td>


79

</td>
<td>


1.454545

</td>
</tr>
<tr>
<td>


12

</td>
<td>


96

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


13

</td>
<td>


104

</td>
<td>


95

</td>
<td>


1.230769

</td>
</tr>
<tr>
<td>


14

</td>
<td>


112

</td>
<td>


95

</td>
<td>


1.142857

</td>
</tr>
<tr>
<td>


15

</td>
<td>


120

</td>
<td>


95

</td>
<td>


1.066667

</td>
</tr>
<tr>
<td>


16

</td>
<td>


128

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


17

</td>
<td>


136

</td>
<td>


127

</td>
<td>


1.254863

</td>
</tr>
<tr>
<td>


18

</td>
<td>


144

</td>
<td>


127

</td>
<td>


1.185255

</td>
</tr>
<tr>
<td>


19

</td>
<td>


152

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


20

</td>
<td>


160

</td>
<td>


127

</td>
<td>


1.066667

</td>
</tr>
<tr>
<td>


21

</td>
<td>


168

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


22

</td>
<td>


176

</td>
<td>


159

</td>
<td>


1.454334

</td>
</tr>
<tr>
<td>


23

</td>
<td>


184

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


24

</td>
<td>


192

</td>
<td>


127

</td>
<td>


0.969744

</td>
</tr>
<tr>
<td>


25

</td>
<td>


200

</td>
<td>


191

</td>
<td>


1.280246

</td>
</tr>
<tr>
<td>


26

</td>
<td>


208

</td>
<td>


191

</td>
<td>


1.230921

</td>
</tr>
<tr>
<td>


27

</td>
<td>


216

</td>
<td>


0

</td>
<td>


1.000000

</td>
</tr>
<tr>
<td>


28

</td>
<td>


224

</td>
<td>


191

</td>
<td>


1.143118

</td>
</tr>
</tbody>
</table>

If rmid &gt; rmid threshold, MBM total and local values should be multiplied by the correction factor.

See:

1\. Erratum SKX99 in Intel Xeon Processor Scalable Family Specification Update: [http://web.archive.org/web/20200716124958/https://www.intel.com/content/www/us/en/processors/xeon/scalable/xeon-scalable-spec-update.html](<http://web.archive.org/web/20200716124958/https://www.intel.com/content/www/us/en/processors/xeon/scalable/xeon-scalable-spec-update.html>)

2\. Erratum BDF102 in Intel Xeon E5-2600 v4 Processor Product Family Specification Update: [http://web.archive.org/web/20191125200531/https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/xeon-e5-v4-spec-update.pdf](<http://web.archive.org/web/20191125200531/https://www.intel.com/content/dam/www/public/us/en/documents/specification-updates/xeon-e5-v4-spec-update.pdf>)

3\. The errata in Intel Resource Director Technology (Intel RDT) on 2nd Generation Intel Xeon Scalable Processors Reference Manual: [https://software.intel.com/content/www/us/en/develop/articles/intel-resource-director-technology-rdt-reference-manual.html](<https://software.intel.com/content/www/us/en/develop/articles/intel-resource-director-technology-rdt-reference-manual.html>)

for further information.

---

# ROMFS - ROM File System

_Peios Kernel / Internals / Filesystems_

> This is a quite dumb, read only filesystem, mainly for initial RAM disks of installation disks. It has grown up by the need of having modules linked at boot time. Using this filesystem, you get a very similar feature, and even the…

<a id="rst-romfs-rom-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This is a quite dumb, read only filesystem, mainly for initial RAM disks of installation disks.  It has grown up by the need of having modules linked at boot time.  Using this filesystem, you get a very similar feature, and even the possibility of a small kernel, with a file system which doesn't take up useful memory from the router functions in the basement of your office.

For comparison, both the older minix and xiafs (the latter is now defunct) filesystems, compiled as module need more than 20000 bytes, while romfs is less than a page, about 4000 bytes (assuming i586 code).  Under the same conditions, the msdos filesystem would need about 30K (and does not support device nodes or symlinks), while the nfs module with nfsroot is about 57K.  Furthermore, as a bit unfair comparison, an actual rescue disk used up 3202 blocks with ext2, while with romfs, it needed 3079 blocks.

To create such a file system, you'll need a user program named genromfs. It is available on [http://romfs.sourceforge.net/](<http://romfs.sourceforge.net/>)

As the name suggests, romfs could be also used (space-efficiently) on various read-only media, like (E)EPROM disks if someone will have the motivation.. :)

However, the main purpose of romfs is to have a very small kernel, which has only this filesystem linked in, and then can load any module later, with the current module utilities.  It can also be used to run some program to decide if you need SCSI devices, and even IDE or floppy drives can be loaded later if you use the "initrd"--initial RAM disk--feature of the kernel.  This would not be really news flash, but with romfs, you can even spare off your ext2 or minix or maybe even affs filesystem until you really know that you need it.

For example, a distribution boot disk can contain only the cd disk drivers (and possibly the SCSI drivers), and the ISO 9660 filesystem module.  The kernel can be small enough, since it doesn't have other filesystems, like the quite large ext2fs module, which can then be loaded off the CD at a later stage of the installation.  Another use would be for a recovery disk, when you are reinstalling a workstation from the network, and you will have all the tools/modules available from a nearby server, so you don't want to carry two disks for this purpose, just because it won't fit into ext2.

romfs operates on block devices as you can expect, and the underlying structure is very simple.  Every accessible structure begins on 16 byte boundaries for fast access.  The minimum space a file will take is 32 bytes (this is an empty file, with a less than 16 character name).  The maximum overhead for any non-empty file is the header, and the 16 byte padding for the name and the contents, also 16+14+15 = 45 bytes.  This is quite rare however, since most file names are longer than 3 bytes, and shorter than 15 bytes.

The layout of the filesystem is the following:



```text
offset     content

       +---+---+---+---+
 0     | - | r | o | m |  \
       +---+---+---+---+       The ASCII representation of those bytes
 4     | 1 | f | s | - |  /    (i.e. "-rom1fs-")
       +---+---+---+---+
 8     |   full size   |       The number of accessible bytes in this fs.
       +---+---+---+---+
12     |    checksum   |       The checksum of the FIRST 512 BYTES.
       +---+---+---+---+
16     | volume name   |       The zero terminated name of the volume,
       :               :       padded to 16 byte boundary.
       +---+---+---+---+
xx     |     file      |
       :    headers    :
```

Every multi byte value (32 bit words, I'll use the longwords term from now on) must be in big endian order.

The first eight bytes identify the filesystem, even for the casual inspector.  After that, in the 3rd longword, it contains the number of bytes accessible from the start of this filesystem.  The 4th longword is the checksum of the first 512 bytes (or the number of bytes accessible, whichever is smaller).  The applied algorithm is the same as in the AFFS filesystem, namely a simple sum of the longwords (assuming bigendian quantities again).  For details, please consult the source.  This algorithm was chosen because although it's not quite reliable, it does not require any tables, and it is very simple.

The following bytes are now part of the file system; each file header must begin on a 16 byte boundary:



```text
offset     content

       +---+---+---+---+
 0     | next filehdr|X|       The offset of the next file header
       +---+---+---+---+         (zero if no more files)
 4     |   spec.info   |       Info for directories/hard links/devices
       +---+---+---+---+
 8     |     size      |       The size of this file in bytes
       +---+---+---+---+
12     |   checksum    |       Covering the meta data, including the file
       +---+---+---+---+         name, and padding
16     | file name     |       The zero terminated name of the file,
       :               :       padded to 16 byte boundary
       +---+---+---+---+
xx     | file data     |
       :               :
```

Since the file headers begin always at a 16 byte boundary, the lowest 4 bits would be always zero in the next filehdr pointer.  These four bits are used for the mode information.  Bits 0..2 specify the type of the file; while bit 4 shows if the file is executable or not.  The permissions are assumed to be world readable, if this bit is not set, and world executable if it is; except the character and block devices, they are never accessible for other than owner.  The owner of every file is user and group 0, this should never be a problem for the intended use.  The mapping of the 8 possible values to file types is the following:


<table>
<thead>
<tr>
<th>




</th>
<th>




</th>
<th>




</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


hard link

</td>
<td>


link destination \[file header\]

</td>
</tr>
<tr>
<td>


1

</td>
<td>


directory

</td>
<td>


first file's header

</td>
</tr>
<tr>
<td>


2

</td>
<td>


regular file

</td>
<td>


unused, must be zero \[MBZ\]

</td>
</tr>
<tr>
<td>


3

</td>
<td>


symbolic link

</td>
<td>


unused, MBZ (file data is the link content)

</td>
</tr>
<tr>
<td>


4

</td>
<td>


block device

</td>
<td>


16/16 bits major/minor number

</td>
</tr>
<tr>
<td>


5

</td>
<td>


char device

</td>
<td>


- " -

</td>
</tr>
<tr>
<td>


6

</td>
<td>


socket

</td>
<td>


unused, MBZ

</td>
</tr>
<tr>
<td>


7

</td>
<td>


fifo

</td>
<td>


unused, MBZ

</td>
</tr>
</tbody>
</table>

Note that hard links are specifically marked in this filesystem, but they will behave as you can expect (i.e. share the inode number). Note also that it is your responsibility to not create hard link loops, and creating all the . and .. links for directories.  This is normally done correctly by the genromfs program.  Please refrain from using the executable bits for special purposes on the socket and fifo special files, they may have other uses in the future.  Additionally, please remember that only regular files, and symlinks are supposed to have a nonzero size field; they contain the number of bytes available directly after the (padded) file name.

Another thing to note is that romfs works on file headers and data aligned to 16 byte boundaries, but most hardware devices and the block device drivers are unable to cope with smaller than block-sized data. To overcome this limitation, the whole size of the file system must be padded to an 1024 byte boundary.

If you have any problems or suggestions concerning this file system, please contact me.  However, think twice before wanting me to add features and code, because the primary and most important advantage of this file system is the small code.  On the other hand, don't be alarmed, I'm not getting that much romfs related mail.  Now I can understand why Avery wrote poems in the ARCnet docs to get some more feedback. :)

romfs has also a mailing list, and to date, it hasn't received any traffic, so you are welcome to join it to discuss your ideas. :)

It's run by ezmlm, so you can subscribe to it by sending a message to [romfs-subscribe@shadow.banki.hu](<mailto:romfs-subscribe@shadow.banki.hu>), the content is irrelevant.

Pending issues:

- Permissions and owner information are pretty essential features of a Un\*x like system, but romfs does not provide the full possibilities. I have never found this limiting, but others might.

- The file system is read only, so it can be very small, but in case one would want to write \_anything\_ to a file system, he still needs a writable file system, thus negating the size advantages.  Possible solutions: implement write access as a compile-time option, or a new, similarly small writable filesystem for RAM disks.

- Since the files are only required to have alignment on a 16 byte boundary, it is currently possibly suboptimal to read or execute files from the filesystem.  It might be resolved by reordering file data to have most of it (i.e. except the start and the end) laying at "natural" boundaries, thus it would be possible to directly map a big portion of the file contents to the mm subsystem.

- Compression might be an useful feature, but memory is quite a limiting factor in my eyes.

- Where it is used?

- Does it work on other architectures than intel and motorola?

Have fun,

Janos Farkas &lt;[chexum@shadow.banki.hu](<mailto:chexum@shadow.banki.hu>)&gt;

---

# The seq_file Interface

_Peios Kernel / Internals / Filesystems_

> Copyright 2003 Jonathan Corbet <corbet@lwn.net>

<a id="rst-the-seq-file-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Copyright 2003 Jonathan Corbet &lt;[corbet@lwn.net](<mailto:corbet@lwn.net>)&gt;
>
> This file is originally from the LWN.net Driver Porting series at [https://lwn.net/Articles/driver-porting/](<https://lwn.net/Articles/driver-porting/>)

There are numerous ways for a device driver (or other kernel component) to provide information to the user or system administrator.  One useful technique is the creation of virtual files, in debugfs, /proc or elsewhere. Virtual files can provide human-readable output that is easy to get at without any special utility programs; they can also make life easier for script writers. It is not surprising that the use of virtual files has grown over the years.

Creating those files correctly has always been a bit of a challenge, however. It is not that hard to make a virtual file which returns a string. But life gets trickier if the output is long - anything greater than an application is likely to read in a single operation.  Handling multiple reads (and seeks) requires careful attention to the reader's position within the virtual file - that position is, likely as not, in the middle of a line of output. The kernel has traditionally had a number of implementations that got this wrong.

The 2.6 kernel contains a set of functions (implemented by Alexander Viro) which are designed to make it easy for virtual file creators to get it right.

The seq_file interface is available via &lt;linux/seq_file.h&gt;. There are three aspects to seq_file:

> - An iterator interface which lets a virtual file implementation step through the objects it is presenting.
>
> - Some utility functions for formatting objects for output without needing to worry about things like output buffers.
>
> - A set of canned file_operations which implement most operations on the virtual file.

We'll look at the seq_file interface via an extremely simple example: a loadable module which creates a file called /proc/sequence. The file, when read, simply produces a set of increasing integer values, one per line. The sequence will continue until the user loses patience and finds something better to do. The file is seekable, in that one can do something like the following:



```text
dd if=/proc/sequence of=out1 count=1
dd if=/proc/sequence skip=1 of=out2 count=1
```

Then concatenate the output files out1 and out2 and get the right result. Yes, it is a thoroughly useless module, but the point is to show how the mechanism works without getting lost in other details.  (Those wanting to see the full source for this module can find it at [https://lwn.net/Articles/22359/](<https://lwn.net/Articles/22359/>)).

<a id="rst-deprecated-create-proc-entry"></a>

## Deprecated create_proc_entry

Note that the above article uses create_proc_entry which was removed in kernel 3.10. Current versions require the following update:



```text
-   entry = create_proc_entry("sequence", 0, NULL);
-   if (entry)
-           entry->proc_fops = &ct_file_ops;
+   entry = proc_create("sequence", 0, NULL, &ct_file_ops);
```

<a id="rst-the-iterator-interface"></a>

## The iterator interface

Modules implementing a virtual file with seq_file must implement an iterator object that allows stepping through the data of interest during a "session" (roughly one read() system call).  If the iterator is able to move to a specific position - like the file they implement, though with freedom to map the position number to a sequence location in whatever way is convenient - the iterator need only exist transiently during a session.  If the iterator cannot easily find a numerical position but works well with a first/next interface, the iterator can be stored in the private data area and continue from one session to the next.

A seq_file implementation that is formatting firewall rules from a table, for example, could provide a simple iterator that interprets position N as the Nth rule in the chain.  A seq_file implementation that presents the content of a, potentially volatile, linked list might record a pointer into that list, providing that can be done without risk of the current location being removed.

Positioning can thus be done in whatever way makes the most sense for the generator of the data, which need not be aware of how a position translates to an offset in the virtual file. The one obvious exception is that a position of zero should indicate the beginning of the file.

The /proc/sequence iterator just uses the count of the next number it will output as its position.

Four functions must be implemented to make the iterator work. The first, called start(), starts a session and takes a position as an argument, returning an iterator which will start reading at that position.  The pos passed to start() will always be either zero, or the most recent pos used in the previous session.

For our simple sequence example, the start() function looks like:



```text
static void *ct_seq_start(struct seq_file *s, loff_t *pos)
{
        loff_t *spos = kmalloc(sizeof(loff_t), GFP_KERNEL);
        if (! spos)
                return NULL;
        *spos = *pos;
        return spos;
}
```

The entire data structure for this iterator is a single loff_t value holding the current position. There is no upper bound for the sequence iterator, but that will not be the case for most other seq_file implementations; in most cases the start() function should check for a "past end of file" condition and return NULL if need be.

For more complicated applications, the private field of the seq_file structure can be used to hold state from session to session.  There is also a special value which can be returned by the start() function called SEQ_START_TOKEN; it can be used if you wish to instruct your show() function (described below) to print a header at the top of the output. SEQ_START_TOKEN should only be used if the offset is zero, however.  SEQ_START_TOKEN has no special meaning to the core seq_file code.  It is provided as a convenience for a start() function to communicate with the next() and show() functions.

The next function to implement is called, amazingly, next(); its job is to move the iterator forward to the next position in the sequence.  The example module can simply increment the position by one; more useful modules will do what is needed to step through some data structure. The next() function returns a new iterator, or NULL if the sequence is complete. Here's the example version:



```text
static void *ct_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
        loff_t *spos = v;
        *pos = ++*spos;
        return spos;
}
```

The next() function should set `*pos` to a value that start() can use to find the new location in the sequence.  When the iterator is being stored in the private data area, rather than being reinitialized on each start(), it might seem sufficient to simply set `*pos` to any non-zero value (zero always tells start() to restart the sequence).  This is not sufficient due to historical problems.

Historically, many next() functions have *not* updated `*pos` at end-of-file.  If the value is then used by start() to initialise the iterator, this can result in corner cases where the last entry in the sequence is reported twice in the file.  In order to discourage this bug from being resurrected, the core seq_file code now produces a warning if a next() function does not change the value of `*pos`.  Consequently a next() function *must* change the value of `*pos`, and of course must set it to a non-zero value.

The stop() function closes a session; its job, of course, is to clean up. If dynamic memory is allocated for the iterator, stop() is the place to free it; if a lock was taken by start(), stop() must release that lock.  The value that `*pos` was set to by the last next() call before stop() is remembered, and used for the first start() call of the next session unless lseek() has been called on the file; in that case next start() will be asked to start at position zero:



```text
static void ct_seq_stop(struct seq_file *s, void *v)
{
        kfree(v);
}
```

Finally, the show() function should format the object currently pointed to by the iterator for output.  The example module's show() function is:



```text
static int ct_seq_show(struct seq_file *s, void *v)
{
        loff_t *spos = v;
        seq_printf(s, "%lld\n", (long long)*spos);
        return 0;
}
```

If all is well, the show() function should return zero.  A negative error code in the usual manner indicates that something went wrong; it will be passed back to user space.  This function can also return SEQ_SKIP, which causes the current item to be skipped; if the show() function has already generated output before returning SEQ_SKIP, that output will be dropped.

We will look at seq_printf() in a moment. But first, the definition of the seq_file iterator is finished by creating a seq_operations structure with the four functions we have just defined:



```text
static const struct seq_operations ct_seq_ops = {
        .start = ct_seq_start,
        .next  = ct_seq_next,
        .stop  = ct_seq_stop,
        .show  = ct_seq_show
};
```

This structure will be needed to tie our iterator to the /proc file in a little bit.

It's worth noting that the iterator value returned by start() and manipulated by the other functions is considered to be completely opaque by the seq_file code. It can thus be anything that is useful in stepping through the data to be output. Counters can be useful, but it could also be a direct pointer into an array or linked list. Anything goes, as long as the programmer is aware that things can happen between calls to the iterator function. However, the seq_file code (by design) will not sleep between the calls to start() and stop(), so holding a lock during that time is a reasonable thing to do. The seq_file code will also avoid taking any other locks while the iterator is active.

The iterator value returned by start() or next() is guaranteed to be passed to a subsequent next() or stop() call.  This allows resources such as locks that were taken to be reliably released.  There is *no* guarantee that the iterator will be passed to show(), though in practice it often will be.

<a id="rst-formatted-output"></a>

## Formatted output

The seq_file code manages positioning within the output created by the iterator and getting it into the user's buffer. But, for that to work, that output must be passed to the seq_file code. Some utility functions have been defined which make this task easy.

Most code will simply use seq_printf(), which works pretty much like printk(), but which requires the seq_file pointer as an argument.

For straight character output, the following functions may be used:



```text
seq_putc(struct seq_file *m, char c);
seq_puts(struct seq_file *m, const char *s);
seq_escape(struct seq_file *m, const char *s, const char *esc);
```

The first two output a single character and a string, just like one would expect. seq_escape() is like seq_puts(), except that any character in s which is in the string esc will be represented in octal form in the output.

There are also a pair of functions for printing filenames:



```text
int seq_path(struct seq_file *m, const struct path *path,
             const char *esc);
int seq_path_root(struct seq_file *m, const struct path *path,
                  const struct path *root, const char *esc)
```

Here, path indicates the file of interest, and esc is a set of characters which should be escaped in the output.  A call to seq_path() will output the path relative to the current process's filesystem root.  If a different root is desired, it can be used with seq_path_root().  If it turns out that path cannot be reached from root, seq_path_root() returns SEQ_SKIP.

A function producing complicated output may want to check:



```text
bool seq_has_overflowed(struct seq_file *m);
```

and avoid further seq\_&lt;output&gt; calls if true is returned.

A true return from seq_has_overflowed means that the seq_file buffer will be discarded and the seq_show function will attempt to allocate a larger buffer and retry printing.

<a id="rst-making-it-all-work"></a>

## Making it all work

So far, we have a nice set of functions which can produce output within the seq_file system, but we have not yet turned them into a file that a user can see. Creating a file within the kernel requires, of course, the creation of a set of file_operations which implement the operations on that file. The seq_file interface provides a set of canned operations which do most of the work. The virtual file author still must implement the open() method, however, to hook everything up. The open function is often a single line, as in the example module:



```text
static int ct_open(struct inode *inode, struct file *file)
{
        return seq_open(file, &ct_seq_ops);
}
```

Here, the call to seq_open() takes the seq_operations structure we created before, and gets set up to iterate through the virtual file.

On a successful open, seq_open() stores the struct seq_file pointer in file-&gt;private_data. If you have an application where the same iterator can be used for more than one file, you can store an arbitrary pointer in the private field of the seq_file structure; that value can then be retrieved by the iterator functions.

There is also a wrapper function to seq_open() called seq_open_private(). It kmallocs a zero filled block of memory and stores a pointer to it in the private field of the seq_file structure, returning 0 on success. The block size is specified in a third parameter to the function, e.g.:



```text
static int ct_open(struct inode *inode, struct file *file)
{
        return seq_open_private(file, &ct_seq_ops,
                                sizeof(struct mystruct));
}
```

There is also a variant function, \__seq_open_private(), which is functionally identical except that, if successful, it returns the pointer to the allocated memory block, allowing further initialisation e.g.:



```text
static int ct_open(struct inode *inode, struct file *file)
{
        struct mystruct *p =
                __seq_open_private(file, &ct_seq_ops, sizeof(*p));

        if (!p)
                return -ENOMEM;

        p->foo = bar; /* initialize my stuff */
                ...
        p->baz = true;

        return 0;
}
```

A corresponding close function, seq_release_private() is available which frees the memory allocated in the corresponding open.

The other operations of interest - read(), llseek(), and release() - are all implemented by the seq_file code itself. So a virtual file's file_operations structure will look like:



```text
static const struct file_operations ct_file_ops = {
        .owner   = THIS_MODULE,
        .open    = ct_open,
        .read    = seq_read,
        .llseek  = seq_lseek,
        .release = seq_release
};
```

There is also a seq_release_private() which passes the contents of the seq_file private field to kfree() before releasing the structure.

The final step is the creation of the /proc file itself. In the example code, that is done in the initialization code in the usual way:



```text
static int ct_init(void)
{
        struct proc_dir_entry *entry;

        proc_create("sequence", 0, NULL, &ct_file_ops);
        return 0;
}

module_init(ct_init);
```

And that is pretty much it.

<a id="rst-seq-list"></a>

## seq_list

If your file will be iterating through a linked list, you may find these routines useful:



```text
struct list_head *seq_list_start(struct list_head *head,
                                 loff_t pos);
struct list_head *seq_list_start_head(struct list_head *head,
                                      loff_t pos);
struct list_head *seq_list_next(void *v, struct list_head *head,
                                loff_t *ppos);
```

These helpers will interpret pos as a position within the list and iterate accordingly.  Your start() and next() functions need only invoke the `seq_list_*` helpers with a pointer to the appropriate list_head structure.

<a id="rst-the-extra-simple-version"></a>

## The extra-simple version

For extremely simple virtual files, there is an even easier interface.  A module can define only the show() function, which should create all the output that the virtual file will contain. The file's open() method then calls:



```text
int single_open(struct file *file,
                int (*show)(struct seq_file *m, void *p),
                void *data);
```

When output time comes, the show() function will be called once. The data value given to single_open() can be found in the private field of the seq_file structure. When using single_open(), the programmer should use single_release() instead of seq_release() in the file_operations structure to avoid a memory leak.

---

# Shared Subtrees

_Peios Kernel / Internals / Filesystems_

> Consider the following situation:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-shared-subtrees"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:
1) Overview
2) Features
3) Setting mount states
4) Use-case
5) Detailed semantics
6) Quiz
7) FAQ
8) Implementation -->

<a id="rst-overview"></a>

## 1) Overview

Consider the following situation:

A process wants to clone its own namespace, but still wants to access the CD that got mounted recently.  Shared subtree semantics provide the necessary mechanism to accomplish the above.

It provides the necessary building blocks for features like per-user-namespace and versioned filesystem.

<a id="rst-features"></a>

## 2) Features

Shared subtree provides four different flavors of mounts; struct vfsmount to be precise:

- **a)** A **shared mount** can be replicated to as many mountpoints and all the replicas continue to be exactly same.

  Here is an example:

  Let's say /mnt has a mount that is shared:



  ```text
  # mount --make-shared /mnt
  ```

  > [!NOTE]
  >
  > mount(8) command now supports the --make-shared flag, so the sample 'smount' program is no longer needed and has been removed.



  ```text
  # mount --bind /mnt /tmp
  ```

  The above command replicates the mount at /mnt to the mountpoint /tmp and the contents of both the mounts remain identical.



  ```text
  #ls /mnt
  a b c

  #ls /tmp
  a b c
  ```

  Now let's say we mount a device at /tmp/a:



  ```text
  # mount /dev/sd0  /tmp/a

  # ls /tmp/a
  t1 t2 t3

  # ls /mnt/a
  t1 t2 t3
  ```

  Note that the mount has propagated to the mount at /mnt as well.

  And the same is true even when /dev/sd0 is mounted on /mnt/a. The contents will be visible under /tmp/a too.

- **b)** A **slave mount** is like a shared mount except that mount and umount events only propagate towards it.

  All slave mounts have a master mount which is a shared.

  Here is an example:

  Let's say /mnt has a mount which is shared:



  ```text
  # mount --make-shared /mnt
  ```

  Let's bind mount /mnt to /tmp:



  ```text
  # mount --bind /mnt /tmp
  ```

  the new mount at /tmp becomes a shared mount and it is a replica of the mount at /mnt.

  Now let's make the mount at /tmp; a slave of /mnt:



  ```text
  # mount --make-slave /tmp
  ```

  let's mount /dev/sd0 on /mnt/a:



  ```text
  # mount /dev/sd0 /mnt/a

  # ls /mnt/a
  t1 t2 t3

  # ls /tmp/a
  t1 t2 t3
  ```

  Note the mount event has propagated to the mount at /tmp

  However let's see what happens if we mount something on the mount at /tmp:



  ```text
  # mount /dev/sd1 /tmp/b

  # ls /tmp/b
  s1 s2 s3

  # ls /mnt/b
  ```

  Note how the mount event has not propagated to the mount at /mnt

- **c)** A **private mount** does not forward or receive propagation.

  This is the mount we are familiar with. Its the default type.

- **d)** An **unbindable mount** is, as the name suggests, an unbindable private mount.

  let's say we have a mount at /mnt and we make it unbindable:



  ```text
  # mount --make-unbindable /mnt
  ```

  Let's try to bind mount this mount somewhere else:



  ```text
  # mount --bind /mnt /tmp mount: wrong fs type, bad option, bad
  superblock on /mnt, or too many mounted file systems
  ```

  Binding a unbindable mount is a invalid operation.

<a id="rst-setting-mount-states"></a>

## 3) Setting mount states

The mount command (util-linux package) can be used to set mount states:



```text
mount --make-shared mountpoint
mount --make-slave mountpoint
mount --make-private mountpoint
mount --make-unbindable mountpoint
```

<a id="rst-use-cases"></a>

## 4) Use cases

- **A)** A process wants to clone its own namespace, but still wants to access the CD that got mounted recently.

  Solution:

  The system administrator can make the mount at /cdrom shared:



  ```text
  mount --bind /cdrom /cdrom
  mount --make-shared /cdrom
  ```

  Now any process that clones off a new namespace will have a mount at /cdrom which is a replica of the same mount in the parent namespace.

  So when a CD is inserted and mounted at /cdrom that mount gets propagated to the other mount at /cdrom in all the other clone namespaces.

- **B)** A process wants its mounts invisible to any other process, but still be able to see the other system mounts.

  Solution:

  To begin with, the administrator can mark the entire mount tree as shareable:



  ```text
  mount --make-rshared /
  ```

  A new process can clone off a new namespace. And mark some part of its namespace as slave:



  ```text
  mount --make-rslave /myprivatetree
  ```

  Hence forth any mounts within the /myprivatetree done by the process will not show up in any other namespace. However mounts done in the parent namespace under /myprivatetree still shows up in the process's namespace.

Apart from the above semantics this feature provides the building blocks to solve the following problems:

- **C)** Per-user namespace

  The above semantics allows a way to share mounts across namespaces.  But namespaces are associated with processes. If namespaces are made first class objects with user API to associate/disassociate a namespace with userid, then each user could have his/her own namespace and tailor it to his/her requirements. This needs to be supported in PAM.

- **D)** Versioned files

  If the entire mount tree is visible at multiple locations, then an underlying versioning file system can return different versions of the file depending on the path used to access that file.

  An example is:



  ```text
  mount --make-shared /
  mount --rbind / /view/v1
  mount --rbind / /view/v2
  mount --rbind / /view/v3
  mount --rbind / /view/v4
  ```

  and if /usr has a versioning filesystem mounted, then that mount appears at /view/v1/usr, /view/v2/usr, /view/v3/usr and /view/v4/usr too

  A user can request v3 version of the file /usr/fs/namespace.c by accessing /view/v3/usr/fs/namespace.c . The underlying versioning filesystem can then decipher that v3 version of the filesystem is being requested and return the corresponding inode.

<a id="rst-detailed-semantics"></a>

## 5) Detailed semantics

The section below explains the detailed semantics of bind, rbind, move, mount, umount and clone-namespace operations.

> [!NOTE]
>
> the word 'vfsmount' and the noun 'mount' have been used to mean the same thing, throughout this document.

- **a)** Mount states

  A **propagation event** is defined as event generated on a vfsmount that leads to mount or unmount actions in other vfsmounts.

  A **peer group** is defined as a group of vfsmounts that propagate events to each other.

  A given mount can be in one of the following states:

  1. Shared mounts

     A **shared mount** is defined as a vfsmount that belongs to a peer group.

     For example:



     ```text
     mount --make-shared /mnt
     mount --bind /mnt /tmp
     ```

     The mount at /mnt and that at /tmp are both shared and belong to the same peer group. Anything mounted or unmounted under /mnt or /tmp reflect in all the other mounts of its peer group.

  2. Slave mounts

     A **slave mount** is defined as a vfsmount that receives propagation events and does not forward propagation events.

     A slave mount as the name implies has a master mount from which mount/unmount events are received. Events do not propagate from the slave mount to the master.  Only a shared mount can be made a slave by executing the following command:



     ```text
     mount --make-slave mount
     ```

     A shared mount that is made as a slave is no more shared unless modified to become shared.

  3. Shared and Slave

     A vfsmount can be both **shared** as well as **slave**.  This state indicates that the mount is a slave of some vfsmount, and has its own peer group too.  This vfsmount receives propagation events from its master vfsmount, and also forwards propagation events to its 'peer group' and to its slave vfsmounts.

     Strictly speaking, the vfsmount is shared having its own peer group, and this peer-group is a slave of some other peer group.

     Only a slave vfsmount can be made as 'shared and slave' by either executing the following command:



     ```text
     mount --make-shared mount
     ```

     or by moving the slave vfsmount under a shared vfsmount.

  4. Private mount

     A **private mount** is defined as vfsmount that does not receive or forward any propagation events.

  5. Unbindable mount

     A **unbindable mount** is defined as vfsmount that does not receive or forward any propagation events and cannot be bind mounted.

     State diagram:

     The state diagram below explains the state transition of a mount, in response to various commands:



     ```text
     -----------------------------------------------------------------------
     |             |make-shared |  make-slave  | make-private |make-unbindab|
     --------------|------------|--------------|--------------|-------------|
     |shared       |shared      |*slave/private|   private    | unbindable  |
     |             |            |              |              |             |
     |-------------|------------|--------------|--------------|-------------|
     |slave        |shared      | **slave      |    private   | unbindable  |
     |             |and slave   |              |              |             |
     |-------------|------------|--------------|--------------|-------------|
     |shared       |shared      | slave        |    private   | unbindable  |
     |and slave    |and slave   |              |              |             |
     |-------------|------------|--------------|--------------|-------------|
     |private      |shared      |  **private   |    private   | unbindable  |
     |-------------|------------|--------------|--------------|-------------|
     |unbindable   |shared      |**unbindable  |    private   | unbindable  |
     ------------------------------------------------------------------------

     * if the shared mount is the only mount in its peer group, making it
     slave, makes it private automatically. Note that there is no master to
     which it can be slaved to.

     ** slaving a non-shared mount has no effect on the mount.
     ```

     Apart from the commands listed below, the 'move' operation also changes the state of a mount depending on type of the destination mount. Its explained in section 5d.

- **b)** Bind semantics

  Consider the following command:



  ```text
  mount --bind A/a  B/b
  ```

  where 'A' is the source mount, 'a' is the dentry in the mount 'A', 'B' is the destination mount and 'b' is the dentry in the destination mount.

  The outcome depends on the type of mount of 'A' and 'B'. The table below contains quick reference:



  ```text
  --------------------------------------------------------------------------
  |         BIND MOUNT OPERATION                                           |
  |************************************************************************|
  |source(A)->| shared      |       private  |       slave    | unbindable |
  | dest(B)  |              |                |                |            |
  |   |      |              |                |                |            |
  |   v      |              |                |                |            |
  |************************************************************************|
  |  shared  | shared       |     shared     | shared & slave |  invalid   |
  |          |              |                |                |            |
  |non-shared| shared       |      private   |      slave     |  invalid   |
  **************************************************************************
  ```

  Details:

  1. 'A' is a shared mount and 'B' is a shared mount. A new mount 'C' which is clone of 'A', is created. Its root dentry is 'a' . 'C' is mounted on mount 'B' at dentry 'b'. Also new mount 'C1', 'C2', 'C3' ... are created and mounted at the dentry 'b' on all mounts where 'B' propagates to. A new propagation tree containing 'C1',..,'Cn' is created. This propagation tree is identical to the propagation tree of 'B'.  And finally the peer-group of 'C' is merged with the peer group of 'A'.

  2. 'A' is a private mount and 'B' is a shared mount. A new mount 'C' which is clone of 'A', is created. Its root dentry is 'a'. 'C' is mounted on mount 'B' at dentry 'b'. Also new mount 'C1', 'C2', 'C3' ... are created and mounted at the dentry 'b' on all mounts where 'B' propagates to. A new propagation tree is set containing all new mounts 'C', 'C1', .., 'Cn' with exactly the same configuration as the propagation tree for 'B'.

  3. 'A' is a slave mount of mount 'Z' and 'B' is a shared mount. A new mount 'C' which is clone of 'A', is created. Its root dentry is 'a' . 'C' is mounted on mount 'B' at dentry 'b'. Also new mounts 'C1', 'C2', 'C3' ... are created and mounted at the dentry 'b' on all mounts where 'B' propagates to. A new propagation tree containing the new mounts 'C','C1',..  'Cn' is created. This propagation tree is identical to the propagation tree for 'B'. And finally the mount 'C' and its peer group is made the slave of mount 'Z'.  In other words, mount 'C' is in the state 'slave and shared'.

  4. 'A' is a unbindable mount and 'B' is a shared mount. This is a invalid operation.

  5. 'A' is a private mount and 'B' is a non-shared(private or slave or unbindable) mount. A new mount 'C' which is clone of 'A', is created. Its root dentry is 'a'. 'C' is mounted on mount 'B' at dentry 'b'.

  6. 'A' is a shared mount and 'B' is a non-shared mount. A new mount 'C' which is a clone of 'A' is created. Its root dentry is 'a'. 'C' is mounted on mount 'B' at dentry 'b'.  'C' is made a member of the peer-group of 'A'.

  7. 'A' is a slave mount of mount 'Z' and 'B' is a non-shared mount. A new mount 'C' which is a clone of 'A' is created. Its root dentry is 'a'.  'C' is mounted on mount 'B' at dentry 'b'. Also 'C' is set as a slave mount of 'Z'. In other words 'A' and 'C' are both slave mounts of 'Z'.  All mount/unmount events on 'Z' propagates to 'A' and 'C'. But mount/unmount on 'A' do not propagate anywhere else. Similarly mount/unmount on 'C' do not propagate anywhere else.

  8. 'A' is a unbindable mount and 'B' is a non-shared mount. This is a invalid operation. A unbindable mount cannot be bind mounted.

- **c)** Rbind semantics

  rbind is same as bind. Bind replicates the specified mount.  Rbind replicates all the mounts in the tree belonging to the specified mount. Rbind mount is bind mount applied to all the mounts in the tree.

  If the source tree that is rbind has some unbindable mounts, then the subtree under the unbindable mount is pruned in the new location.

  eg:

  let's say we have the following mount tree:



  ```text
     A
   /   \
   B   C
  / \ / \
  D E F G
  ```

  Let's say all the mount except the mount C in the tree are of a type other than unbindable.

  If this tree is rbound to say Z

  We will have the following tree at the new location:



  ```text
      Z
      |
      A'
     /
    B'                Note how the tree under C is pruned
   / \                in the new location.
  D' E'
  ```

- **d)** Move semantics

  Consider the following command:



  ```text
  mount --move A  B/b
  ```

  where 'A' is the source mount, 'B' is the destination mount and 'b' is the dentry in the destination mount.

  The outcome depends on the type of the mount of 'A' and 'B'. The table below is a quick reference:



  ```text
  ---------------------------------------------------------------------------
  |                   MOVE MOUNT OPERATION                                 |
  |**************************************************************************
  | source(A)->| shared      |       private  |       slave    | unbindable |
  | dest(B)  |               |                |                |            |
  |   |      |               |                |                |            |
  |   v      |               |                |                |            |
  |**************************************************************************
  |  shared  | shared        |     shared     |shared and slave|  invalid   |
  |          |               |                |                |            |
  |non-shared| shared        |      private   |    slave       | unbindable |
  ***************************************************************************
  ```

  > [!NOTE]
  >
  > moving a mount residing under a shared mount is invalid.

  Details follow:

  1. 'A' is a shared mount and 'B' is a shared mount.  The mount 'A' is mounted on mount 'B' at dentry 'b'.  Also new mounts 'A1', 'A2'...'An' are created and mounted at dentry 'b' on all mounts that receive propagation from mount 'B'. A new propagation tree is created in the exact same configuration as that of 'B'. This new propagation tree contains all the new mounts 'A1', 'A2'...  'An'.  And this new propagation tree is appended to the already existing propagation tree of 'A'.

  2. 'A' is a private mount and 'B' is a shared mount. The mount 'A' is mounted on mount 'B' at dentry 'b'. Also new mount 'A1', 'A2'... 'An' are created and mounted at dentry 'b' on all mounts that receive propagation from mount 'B'. The mount 'A' becomes a shared mount and a propagation tree is created which is identical to that of 'B'. This new propagation tree contains all the new mounts 'A1', 'A2'...  'An'.

  3. 'A' is a slave mount of mount 'Z' and 'B' is a shared mount.  The mount 'A' is mounted on mount 'B' at dentry 'b'.  Also new mounts 'A1', 'A2'... 'An' are created and mounted at dentry 'b' on all mounts that receive propagation from mount 'B'. A new propagation tree is created in the exact same configuration as that of 'B'. This new propagation tree contains all the new mounts 'A1', 'A2'...  'An'.  And this new propagation tree is appended to the already existing propagation tree of 'A'.  Mount 'A' continues to be the slave mount of 'Z' but it also becomes 'shared'.

  4. 'A' is a unbindable mount and 'B' is a shared mount. The operation is invalid. Because mounting anything on the shared mount 'B' can create new mounts that get mounted on the mounts that receive propagation from 'B'.  And since the mount 'A' is unbindable, cloning it to mount at other mountpoints is not possible.

  5. 'A' is a private mount and 'B' is a non-shared(private or slave or unbindable) mount. The mount 'A' is mounted on mount 'B' at dentry 'b'.

  6. 'A' is a shared mount and 'B' is a non-shared mount.  The mount 'A' is mounted on mount 'B' at dentry 'b'.  Mount 'A' continues to be a shared mount.

  7. 'A' is a slave mount of mount 'Z' and 'B' is a non-shared mount. The mount 'A' is mounted on mount 'B' at dentry 'b'.  Mount 'A' continues to be a slave mount of mount 'Z'.

  8. 'A' is a unbindable mount and 'B' is a non-shared mount. The mount 'A' is mounted on mount 'B' at dentry 'b'. Mount 'A' continues to be a unbindable mount.

- **e)** Mount semantics

  Consider the following command:



  ```text
  mount device  B/b
  ```

  'B' is the destination mount and 'b' is the dentry in the destination mount.

  The above operation is the same as bind operation with the exception that the source mount is always a private mount.

- **f)** Unmount semantics

  Consider the following command:



  ```text
  umount A
  ```

  where 'A' is a mount mounted on mount 'B' at dentry 'b'.

  If mount 'B' is shared, then all most-recently-mounted mounts at dentry 'b' on mounts that receive propagation from mount 'B' and does not have sub-mounts within them are unmounted.

  Example: Let's say 'B1', 'B2', 'B3' are shared mounts that propagate to each other.

  let's say 'A1', 'A2', 'A3' are first mounted at dentry 'b' on mount 'B1', 'B2' and 'B3' respectively.

  let's say 'C1', 'C2', 'C3' are next mounted at the same dentry 'b' on mount 'B1', 'B2' and 'B3' respectively.

  if 'C1' is unmounted, all the mounts that are most-recently-mounted on 'B1' and on the mounts that 'B1' propagates-to are unmounted.

  'B1' propagates to 'B2' and 'B3'. And the most recently mounted mount on 'B2' at dentry 'b' is 'C2', and that of mount 'B3' is 'C3'.

  So all 'C1', 'C2' and 'C3' should be unmounted.

  If any of 'C2' or 'C3' has some child mounts, then that mount is not unmounted, but all other mounts are unmounted. However if 'C1' is told to be unmounted and 'C1' has some sub-mounts, the umount operation is failed entirely.

- **g)** Clone Namespace

  A cloned namespace contains all the mounts as that of the parent namespace.

  Let's say 'A' and 'B' are the corresponding mounts in the parent and the child namespace.

  If 'A' is shared, then 'B' is also shared and 'A' and 'B' propagate to each other.

  If 'A' is a slave mount of 'Z', then 'B' is also the slave mount of 'Z'.

  If 'A' is a private mount, then 'B' is a private mount too.

  If 'A' is unbindable mount, then 'B' is a unbindable mount too.

<a id="rst-quiz"></a>

## 6) Quiz

- **A.** What is the result of the following command sequence?



  ```text
  mount --bind /mnt /mnt
  mount --make-shared /mnt
  mount --bind /mnt /tmp
  mount --move /tmp /mnt/1
  ```

  what should be the contents of /mnt /mnt/1 /mnt/1/1 should be? Should they all be identical? or should /mnt and /mnt/1 be identical only?

- **B.** What is the result of the following command sequence?



  ```text
  mount --make-rshared /
  mkdir -p /v/1
  mount --rbind / /v/1
  ```

  what should be the content of /v/1/v/1 be?

- **C.** What is the result of the following command sequence?



  ```text
  mount --bind /mnt /mnt
  mount --make-shared /mnt
  mkdir -p /mnt/1/2/3 /mnt/1/test
  mount --bind /mnt/1 /tmp
  mount --make-slave /mnt
  mount --make-shared /mnt
  mount --bind /mnt/1/2 /tmp1
  mount --make-slave /mnt
  ```

  At this point we have the first mount at /tmp and its root dentry is 1. Let's call this mount 'A' And then we have a second mount at /tmp1 with root dentry 2. Let's call this mount 'B' Next we have a third mount at /mnt with root dentry mnt. Let's call this mount 'C'

  'B' is the slave of 'A' and 'C' is a slave of 'B' A -&gt; B -&gt; C

  at this point if we execute the following command:



  ```text
  mount --bind /bin /tmp/test
  ```

  The mount is attempted on 'A'

  will the mount propagate to 'B' and 'C' ?

  what would be the contents of /mnt/1/test be?

<a id="rst-faq"></a>

## 7) FAQ

1. Why is bind mount needed? How is it different from symbolic links?

   symbolic links can get stale if the destination mount gets unmounted or moved. Bind mounts continue to exist even if the other mount is unmounted or moved.

2. Why can't the shared subtree be implemented using exportfs?

   exportfs is a heavyweight way of accomplishing part of what shared subtree can do. I cannot imagine a way to implement the semantics of slave mount using exportfs?

3. Why is unbindable mount needed?

   Let's say we want to replicate the mount tree at multiple locations within the same subtree.

   if one rbind mounts a tree within the same subtree 'n' times the number of mounts created is an exponential function of 'n'. Having unbindable mount can help prune the unneeded bind mounts. Here is an example.

   - **step 1:**

     let's say the root tree has just two directories with one vfsmount:



     ```text
       root
      /    \
     tmp    usr
     ```

     And we want to replicate the tree at multiple mountpoints under /root/tmp

   - **step 2:**



     ```text
     mount --make-shared /root

     mkdir -p /tmp/m1

     mount --rbind /root /tmp/m1
     ```

     the new tree now looks like this:



     ```text
             root
            /    \
          tmp    usr
         /
        m1
       /  \
      tmp  usr
      /
     m1
     ```

     it has two vfsmounts

   - **step 3:**



     ```text
     mkdir -p /tmp/m2
     mount --rbind /root /tmp/m2
     ```

     the new tree now looks like this:



     ```text
                       root
                      /    \
                    tmp     usr
                   /    \
                 m1       m2
                / \       /  \
              tmp  usr   tmp  usr
              / \          /
             m1  m2      m1
                 / \     /  \
               tmp usr  tmp   usr
               /        / \
              m1       m1  m2
             /  \
           tmp   usr
           /  \
          m1   m2

     it has 6 vfsmounts
     ```

   - **step 4:**



     ```text
     mkdir -p /tmp/m3
     mount --rbind /root /tmp/m3
     ```

     I won't draw the tree..but it has 24 vfsmounts

   at step i the number of vfsmounts is V\[i\] = i\*V\[i-1\]. This is an exponential function. And this tree has way more mounts than what we really needed in the first place.

   One could use a series of umount at each step to prune out the unneeded mounts. But there is a better solution. Unclonable mounts come in handy here.

   - **step 1:**

     let's say the root tree has just two directories with one vfsmount:



     ```text
                                root
                               /    \
                              tmp    usr

     How do we set up the same tree at multiple locations under
     /root/tmp
     ```

   - **step 2:**



     ```text
     mount --bind /root/tmp /root/tmp

     mount --make-rshared /root
     mount --make-unbindable /root/tmp

     mkdir -p /tmp/m1

     mount --rbind /root /tmp/m1
     ```

     the new tree now looks like this:



     ```text
            root
           /    \
         tmp    usr
        /
       m1
      /  \
     tmp  usr
     ```

   - **step 3:**



     ```text
     mkdir -p /tmp/m2
     mount --rbind /root /tmp/m2
     ```

     the new tree now looks like this:



     ```text
            root
           /    \
         tmp    usr
        /   \
       m1     m2
      /  \     / \
     tmp  usr tmp usr
     ```

   - **step 4:**



     ```text
     mkdir -p /tmp/m3
     mount --rbind /root /tmp/m3
     ```

     the new tree now looks like this:



     ```text
                  root
              /           \
             tmp           usr
         /    \    \
       m1     m2     m3
      /  \     / \    /  \
     tmp  usr tmp usr tmp usr
     ```

<a id="rst-implementation"></a>

## 8) Implementation

- **A)** Datastructure

  Several new fields are introduced to struct vfsmount:

  - **-&gt;mnt_share**

    Links together all the mount to/from which this vfsmount send/receives propagation events.

  - **-&gt;mnt_slave_list**

    Links all the mounts to which this vfsmount propagates to.

  - **-&gt;mnt_slave**

    Links together all the slaves that its master vfsmount propagates to.

  - **-&gt;mnt_master**

    Points to the master vfsmount from which this vfsmount receives propagation.

  - **-&gt;mnt_flags**

    Takes two more flags to indicate the propagation status of the vfsmount.  MNT_SHARE indicates that the vfsmount is a shared vfsmount.  MNT_UNCLONABLE indicates that the vfsmount cannot be replicated.

  All the shared vfsmounts in a peer group form a cyclic list through -&gt;mnt_share.

  All vfsmounts with the same -&gt;mnt_master form on a cyclic list anchored in -&gt;mnt_master-&gt;mnt_slave_list and going through -&gt;mnt_slave.

  -&gt;mnt_master can point to arbitrary (and possibly different) members of master peer group.  To find all immediate slaves of a peer group you need to go through \_all\_ -&gt;mnt_slave_list of its members. Conceptually it's just a single set - distribution among the individual lists does not affect propagation or the way propagation tree is modified by operations.

  All vfsmounts in a peer group have the same -&gt;mnt_master.  If it is non-NULL, they form a contiguous (ordered) segment of slave list.

  A example propagation tree looks as shown in the figure below.

  > [!NOTE]
  >
  > Though it looks like a forest, if we consider all the shared mounts as a conceptual entity called 'pnode', it becomes a tree.



  ```text
      A <--> B <--> C <---> D
     /|\            /|      |\
    / F G          J K      H I
   /
  E<-->K
      /|\
     M L N
  ```

  In the above figure  A,B,C and D all are shared and propagate to each other.   'A' has got 3 slave mounts 'E' 'F' and 'G' 'C' has got 2 slave mounts 'J' and 'K'  and  'D' has got two slave mounts 'H' and 'I'. 'E' is also shared with 'K' and they propagate to each other.  And 'K' has 3 slaves 'M', 'L' and 'N'

  A's -&gt;mnt_share links with the -&gt;mnt_share of 'B' 'C' and 'D'

  A's -&gt;mnt_slave_list links with -&gt;mnt_slave of 'E', 'K', 'F' and 'G'

  E's -&gt;mnt_share links with -&gt;mnt_share of K

  'E', 'K', 'F', 'G' have their -&gt;mnt_master point to struct vfsmount of 'A'

  'M', 'L', 'N' have their -&gt;mnt_master point to struct vfsmount of 'K'

  K's -&gt;mnt_slave_list links with -&gt;mnt_slave of 'M', 'L' and 'N'

  C's -&gt;mnt_slave_list links with -&gt;mnt_slave of 'J' and 'K'

  J and K's -&gt;mnt_master points to struct vfsmount of C

  and finally D's -&gt;mnt_slave_list links with -&gt;mnt_slave of 'H' and 'I'

  'H' and 'I' have their -&gt;mnt_master pointing to struct vfsmount of 'D'.

  NOTE: The propagation tree is orthogonal to the mount tree.

- **B)** Locking:

  -&gt;mnt_share, -&gt;mnt_slave, -&gt;mnt_slave_list, -&gt;mnt_master are protected by namespace_sem (exclusive for modifications, shared for reading).

  Normally we have -&gt;mnt_flags modifications serialized by vfsmount_lock. There are two exceptions: do_add_mount() and clone_mnt(). The former modifies a vfsmount that has not been visible in any shared data structures yet. The latter holds namespace_sem and the only references to vfsmount are in lists that can't be traversed without namespace_sem.

- **C)** Algorithm:

  The crux of the implementation resides in rbind/move operation.

  The overall algorithm breaks the operation into 3 phases: (look at attach_recursive_mnt() and propagate_mnt())

  1. Prepare phase.

     For each mount in the source tree:

     - **a)** Create the necessary number of mount trees to be attached to each of the mounts that receive propagation from the destination mount.

     - **b)** Do not attach any of the trees to its destination. However note down its -&gt;mnt_parent and -&gt;mnt_mountpoint

     - **c)** Link all the new mounts to form a propagation tree that is identical to the propagation tree of the destination mount.

     If this phase is successful, there should be 'n' new propagation trees; where 'n' is the number of mounts in the source tree.  Go to the commit phase

     Also there should be 'm' new mount trees, where 'm' is the number of mounts to which the destination mount propagates to.

     If any memory allocations fail, go to the abort phase.

  2. Commit phase.

     Attach each of the mount trees to their corresponding destination mounts.

  3. Abort phase.

     Delete all the newly created trees.

  > [!NOTE]
  >
  > all the propagation related functionality resides in the file pnode.c

---

version 0.1  (created the initial document, Ram Pai [linuxram@us.ibm.com](<mailto:linuxram@us.ibm.com>))

version 0.2  (Incorporated comments from Al Viro)

---

# splice and pipes

_Peios Kernel / Internals / Filesystems_

> splice is a method for moving blocks of data around inside the kernel, without continually transferring them between the kernel and user space.

<a id="rst-splice-and-pipes"></a>

<a id="rst-splice-api"></a>

## splice API

splice is a method for moving blocks of data around inside the kernel, without continually transferring them between the kernel and user space.


#### <a id="c-splice_to_pipe"></a>`splice_to_pipe()`

```c
ssize_t splice_to_pipe(struct pipe_inode_info *pipe, struct splice_pipe_desc *spd)
```

fill passed data into a pipe

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to fill
- `struct splice_pipe_desc *spd`: data to fill

**Description**

**spd** contains a map of pages and len/offset tuples, along with
the struct pipe_buf_operations associated with these pages. This
function will link that data to the pipe.

#### <a id="c-copy_splice_read"></a>`copy_splice_read()`

```c
ssize_t copy_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags)
```

Copy data from a file and splice the copy into a pipe

**Parameters**

- `struct file *in`: The file to read from
- `loff_t *ppos`: Pointer to the file position to read from
- `struct pipe_inode_info *pipe`: The pipe to splice into
- `size_t len`: The amount to splice
- `unsigned int flags`: The SPLICE_F_* flags

**Description**

This function allocates a bunch of pages sufficient to hold the requested
amount of data (but limited by the remaining pipe capacity), passes it to
the file's ->`read_iter()` to read into and then splices the used pages into
the pipe.

**Return**

On success, the number of bytes read will be returned and **\*ppos**
will be updated if appropriate; 0 will be returned if there is no more data
to be read; -EAGAIN will be returned if the pipe had no space, and some
other negative error code will be returned on error.  A short read may occur
if the pipe has insufficient space, we reach the end of the data or we hit a
hole.

#### <a id="c-splice_from_pipe_feed"></a>`splice_from_pipe_feed()`

```c
int splice_from_pipe_feed(struct pipe_inode_info *pipe, struct splice_desc *sd, splice_actor *actor)
```

feed available data from a pipe to a file

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct splice_desc *sd`: information to **actor**
- `splice_actor *actor`: handler that splices the data

**Description**

This function loops over the pipe and calls **actor** to do the
actual moving of a single struct pipe_buffer to the desired
destination.  It returns when there's no more buffers left in
the pipe or if the requested number of bytes (**sd->total_len**)
have been copied.  It returns a positive number (one) if the
pipe needs to be filled with more data, zero if the required
number of bytes have been copied and -errno on error.

This, together with splice_from_pipe_{begin,end,next}, may be
used to implement the functionality of [`__splice_from_pipe()`](#c-__splice_from_pipe) when
locking is required around copying the pipe buffers to the
destination.

#### <a id="c-splice_from_pipe_next"></a>`splice_from_pipe_next()`

```c
int splice_from_pipe_next(struct pipe_inode_info *pipe, struct splice_desc *sd)
```

wait for some data to splice from

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct splice_desc *sd`: information about the splice operation

**Description**

This function will wait for some data and return a positive
value (one) if pipe buffers are available.  It will return zero
or -errno if no more data needs to be spliced.

#### <a id="c-splice_from_pipe_begin"></a>`splice_from_pipe_begin()`

```c
void splice_from_pipe_begin(struct splice_desc *sd)
```

start splicing from pipe

**Parameters**

- `struct splice_desc *sd`: information about the splice operation

**Description**

This function should be called before a loop containing
[`splice_from_pipe_next()`](#c-splice_from_pipe_next) and [`splice_from_pipe_feed()`](#c-splice_from_pipe_feed) to
initialize the necessary fields of **sd**.

#### <a id="c-splice_from_pipe_end"></a>`splice_from_pipe_end()`

```c
void splice_from_pipe_end(struct pipe_inode_info *pipe, struct splice_desc *sd)
```

finish splicing from pipe

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct splice_desc *sd`: information about the splice operation

**Description**

This function will wake up pipe writers if necessary.  It should
be called after a loop containing [`splice_from_pipe_next()`](#c-splice_from_pipe_next) and
[`splice_from_pipe_feed()`](#c-splice_from_pipe_feed).

#### <a id="c-__splice_from_pipe"></a>`__splice_from_pipe()`

```c
ssize_t __splice_from_pipe(struct pipe_inode_info *pipe, struct splice_desc *sd, splice_actor *actor)
```

splice data from a pipe to given actor

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct splice_desc *sd`: information to **actor**
- `splice_actor *actor`: handler that splices the data

**Description**

This function does little more than loop over the pipe and call
**actor** to do the actual moving of a single struct pipe_buffer to
the desired destination. See pipe_to_file, pipe_to_sendmsg, or
pipe_to_user.

#### <a id="c-splice_from_pipe"></a>`splice_from_pipe()`

```c
ssize_t splice_from_pipe(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags, splice_actor *actor)
```

splice data from a pipe to a file

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct file *out`: file to splice to
- `loff_t *ppos`: position in **out**
- `size_t len`: how many bytes to splice
- `unsigned int flags`: splice modifier flags
- `splice_actor *actor`: handler that splices the data

**Description**

See __splice_from_pipe. This function locks the pipe inode,
otherwise it's identical to [`__splice_from_pipe()`](#c-__splice_from_pipe).

#### <a id="c-iter_file_splice_write"></a>`iter_file_splice_write()`

```c
ssize_t iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags)
```

splice data from a pipe to a file

**Parameters**

- `struct pipe_inode_info *pipe`: pipe info
- `struct file *out`: file to write to
- `loff_t *ppos`: position in **out**
- `size_t len`: number of bytes to splice
- `unsigned int flags`: splice modifier flags

**Description**

Will either move or copy pages (determined by **flags** options) from
the given pipe inode to the given file.
This one is ->write_iter-based.

#### <a id="c-splice_to_socket"></a>`splice_to_socket()`

```c
ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags)
```

splice data from a pipe to a socket

**Parameters**

- `struct pipe_inode_info *pipe`: pipe to splice from
- `struct file *out`: socket to write to
- `loff_t *ppos`: position in **out**
- `size_t len`: number of bytes to splice
- `unsigned int flags`: splice modifier flags

**Description**

Will send **len** bytes from the pipe to a network socket. No data copying
is involved.

#### <a id="c-vfs_splice_read"></a>`vfs_splice_read()`

```c
ssize_t vfs_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags)
```

Read data from a file and splice it into a pipe

**Parameters**

- `struct file *in`: File to splice from
- `loff_t *ppos`: Input file offset
- `struct pipe_inode_info *pipe`: Pipe to splice to
- `size_t len`: Number of bytes to splice
- `unsigned int flags`: Splice modifier flags (SPLICE_F_*)

**Description**

Splice the requested amount of data from the input file to the pipe.  This
is synchronous as the caller must hold the pipe lock across the entire
operation.

If successful, it returns the amount of data spliced, 0 if it hit the EOF or
a hole and a negative error code otherwise.

#### <a id="c-splice_direct_to_actor"></a>`splice_direct_to_actor()`

```c
ssize_t splice_direct_to_actor(struct file *in, struct splice_desc *sd, splice_direct_actor *actor)
```

splices data directly between two non-pipes

**Parameters**

- `struct file *in`: file to splice from
- `struct splice_desc *sd`: actor information on where to splice to
- `splice_direct_actor *actor`: handles the data splicing

**Description**

This is a special case helper to splice directly between two
points, without requiring an explicit pipe. Internally an allocated
pipe is cached in the process, and reused during the lifetime of
that process.

#### <a id="c-do_splice_direct"></a>`do_splice_direct()`

```c
ssize_t do_splice_direct(struct file *in, loff_t *ppos, struct file *out, loff_t *opos, size_t len, unsigned int flags)
```

splices data directly between two files

**Parameters**

- `struct file *in`: file to splice from
- `loff_t *ppos`: input file offset
- `struct file *out`: file to splice to
- `loff_t *opos`: output file offset
- `size_t len`: number of bytes to splice
- `unsigned int flags`: splice modifier flags

**Description**

For use by `do_sendfile()`. splice can easily emulate sendfile, but
doing it in the application would incur an extra system call
(splice in + splice out, as compared to just `sendfile()`). So this helper
can splice directly through a process-private pipe.

Callers already called `rw_verify_area()` on the entire range.

#### <a id="c-splice_file_range"></a>`splice_file_range()`

```c
ssize_t splice_file_range(struct file *in, loff_t *ppos, struct file *out, loff_t *opos, size_t len)
```

splices data between two files for `copy_file_range()`

**Parameters**

- `struct file *in`: file to splice from
- `loff_t *ppos`: input file offset
- `struct file *out`: file to splice to
- `loff_t *opos`: output file offset
- `size_t len`: number of bytes to splice

**Description**

For use by ->`copy_file_range()` methods.
Like [`do_splice_direct()`](#c-do_splice_direct), but `vfs_copy_file_range()` already holds
`start_file_write()` on **out** file.

Callers already called `rw_verify_area()` on the entire range.


<a id="rst-pipes-api"></a>

## pipes API

Pipe interfaces are all for in-kernel (builtin image) use. They are not exported for use by modules.


#### <a id="c-struct-pipe_buffer"></a>`struct pipe_buffer`

a linux kernel pipe buffer

**Definition**

```c
struct pipe_buffer {
    struct page *page;
    unsigned int offset, len;
    const struct pipe_buf_operations *ops;
    unsigned int flags;
    unsigned long private;
};
```

**Members**

- `page`: the page containing the data for the pipe buffer
- `offset`: offset of data inside the **page**
- `len`: length of data inside the **page**
- `ops`: operations associated with this buffer. See **pipe_buf_operations**.
- `flags`: pipe buffer flags. See above.
- `private`: private data owned by the ops.

#### <a id="c-union-pipe_index"></a>`union pipe_index`

pipe indeces

**Definition**

```c
union pipe_index {
    unsigned long head_tail;
    struct {
        pipe_index_t head;
        pipe_index_t tail;
    };
};
```

**Members**

- `head_tail`: unsigned long union of **head** and **tail**
- `{unnamed_struct}`: anonymous
- `head`: The point of buffer production
- `tail`: The point of buffer consumption

#### <a id="c-struct-pipe_inode_info"></a>`struct pipe_inode_info`

a linux kernel pipe

**Definition**

```c
struct pipe_inode_info {
        struct mutex mutex;
        wait_queue_head_t rd_wait, wr_wait;
        union pipe_index;
        unsigned int max_usage;
        unsigned int ring_size;
        unsigned int nr_accounted;
        unsigned int readers;
        unsigned int writers;
        unsigned int files;
        unsigned int r_counter;
        unsigned int w_counter;
        bool poll_usage;
    #ifdef CONFIG_WATCH_QUEUE;
        bool note_loss;
    #endif;
        struct page *tmp_page[2];
        struct fasync_struct *fasync_readers;
        struct fasync_struct *fasync_writers;
        struct pipe_buffer *bufs;
        struct user_struct *user;
    #ifdef CONFIG_WATCH_QUEUE;
        struct watch_queue *watch_queue;
    #endif;
};
```

**Members**

- `mutex`: mutex protecting the whole thing
- `rd_wait`: reader wait point in case of empty pipe
- `wr_wait`: writer wait point in case of full pipe
- `pipe_index`: the pipe indeces
- `max_usage`: The maximum number of slots that may be used in the ring
- `ring_size`: total number of buffers (should be a power of 2)
- `nr_accounted`: The amount this pipe accounts for in user->pipe_bufs
- `readers`: number of current readers of this pipe
- `writers`: number of current writers of this pipe
- `files`: number of struct file referring this pipe (protected by ->i_lock)
- `r_counter`: reader counter
- `w_counter`: writer counter
- `poll_usage`: is this pipe used for epoll, which has crazy wakeups?
- `note_loss`: The next `read()` should insert a data-lost message
- `tmp_page`: cached released page
- `fasync_readers`: reader side fasync
- `fasync_writers`: writer side fasync
- `bufs`: the circular array of pipe buffers
- `user`: the user who created this pipe
- `watch_queue`: If this pipe is a watch_queue, this is the stuff for that

#### <a id="c-pipe_has_watch_queue"></a>`pipe_has_watch_queue()`

```c
bool pipe_has_watch_queue(const struct pipe_inode_info *pipe)
```

Check whether the pipe is a watch_queue, i.e. it was created with O_NOTIFICATION_PIPE

**Parameters**

- `const struct pipe_inode_info *pipe`: The pipe to check

**Return**

true if pipe is a watch queue, false otherwise.

#### <a id="c-pipe_occupancy"></a>`pipe_occupancy()`

```c
unsigned int pipe_occupancy(unsigned int head, unsigned int tail)
```

Return number of slots used in the pipe

**Parameters**

- `unsigned int head`: The pipe ring head pointer
- `unsigned int tail`: The pipe ring tail pointer

#### <a id="c-pipe_empty"></a>`pipe_empty()`

```c
bool pipe_empty(unsigned int head, unsigned int tail)
```

Return true if the pipe is empty

**Parameters**

- `unsigned int head`: The pipe ring head pointer
- `unsigned int tail`: The pipe ring tail pointer

#### <a id="c-pipe_full"></a>`pipe_full()`

```c
bool pipe_full(unsigned int head, unsigned int tail, unsigned int limit)
```

Return true if the pipe is full

**Parameters**

- `unsigned int head`: The pipe ring head pointer
- `unsigned int tail`: The pipe ring tail pointer
- `unsigned int limit`: The maximum amount of slots available.

#### <a id="c-pipe_is_full"></a>`pipe_is_full()`

```c
bool pipe_is_full(const struct pipe_inode_info *pipe)
```

Return true if the pipe is full

**Parameters**

- `const struct pipe_inode_info *pipe`: the pipe

#### <a id="c-pipe_is_empty"></a>`pipe_is_empty()`

```c
bool pipe_is_empty(const struct pipe_inode_info *pipe)
```

Return true if the pipe is empty

**Parameters**

- `const struct pipe_inode_info *pipe`: the pipe

#### <a id="c-pipe_buf_usage"></a>`pipe_buf_usage()`

```c
unsigned int pipe_buf_usage(const struct pipe_inode_info *pipe)
```

Return how many pipe buffers are in use

**Parameters**

- `const struct pipe_inode_info *pipe`: the pipe

#### <a id="c-pipe_buf"></a>`pipe_buf()`

```c
struct pipe_buffer * pipe_buf(const struct pipe_inode_info *pipe, unsigned int slot)
```

Return the pipe buffer for the specified slot in the pipe ring

**Parameters**

- `const struct pipe_inode_info *pipe`: The pipe to access
- `unsigned int slot`: The slot of interest

#### <a id="c-pipe_head_buf"></a>`pipe_head_buf()`

```c
struct pipe_buffer * pipe_head_buf(const struct pipe_inode_info *pipe)
```

Return the pipe buffer at the head of the pipe ring

**Parameters**

- `const struct pipe_inode_info *pipe`: The pipe to access

#### <a id="c-pipe_buf_get"></a>`pipe_buf_get()`

```c
bool pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

get a reference to a pipe_buffer

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to get a reference to

**Return**

`true` if the reference was successfully obtained.

#### <a id="c-pipe_buf_release"></a>`pipe_buf_release()`

```c
void pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

put a reference to a pipe_buffer

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to put a reference to

#### <a id="c-pipe_buf_confirm"></a>`pipe_buf_confirm()`

```c
int pipe_buf_confirm(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

verify contents of the pipe buffer

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to confirm

#### <a id="c-pipe_buf_try_steal"></a>`pipe_buf_try_steal()`

```c
bool pipe_buf_try_steal(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

attempt to take ownership of a pipe_buffer

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to attempt to steal



#### <a id="c-generic_pipe_buf_try_steal"></a>`generic_pipe_buf_try_steal()`

```c
bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

attempt to take ownership of a [`pipe_buffer`](#c-struct-pipe_buffer)

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to attempt to steal

**Description**

This function attempts to steal the `struct page` attached to
**buf**. If successful, this function returns 0 and returns with
the page locked. The caller may then reuse the page for whatever
he wishes; the typical use is insertion into a different file
page cache.

#### <a id="c-generic_pipe_buf_get"></a>`generic_pipe_buf_get()`

```c
bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

get a reference to a [`struct pipe_buffer`](#c-struct-pipe_buffer)

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to get a reference to

**Description**

This function grabs an extra reference to **buf**. It's used in
the `tee()` system call, when we duplicate the buffers in one
pipe into another.

#### <a id="c-generic_pipe_buf_release"></a>`generic_pipe_buf_release()`

```c
void generic_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
```

put a reference to a [`struct pipe_buffer`](#c-struct-pipe_buffer)

**Parameters**

- `struct pipe_inode_info *pipe`: the pipe that the buffer belongs to
- `struct pipe_buffer *buf`: the buffer to put a reference to

**Description**

This function releases a reference to **buf**.

---

# Squashfs 4.0 Filesystem

_Peios Kernel / Internals / Filesystems_

> Squashfs is a compressed read-only filesystem for Linux.

<a id="rst-squashfs-4-0-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Squashfs is a compressed read-only filesystem for Linux.

It uses zlib, lz4, lzo, xz or zstd compression to compress files, inodes and directories.  Inodes in the system are very small and all blocks are packed to minimise data overhead. Block sizes greater than 4K are supported up to a maximum of 1Mbytes (default block size 128K).

Squashfs is intended for general read-only filesystem use, for archival use (i.e. in cases where a .tar.gz file may be used), and in constrained block device/memory systems (e.g. embedded systems) where low overhead is needed.

Mailing list (kernel code): [linux-fsdevel@vger.kernel.org](<mailto:linux-fsdevel@vger.kernel.org>) Web site: github.com/plougher/squashfs-tools

<a id="rst-filesystem-features"></a>

## 1. Filesystem Features

Squashfs filesystem features versus Cramfs:


<table>
<thead>
<tr>
<th>




</th>
<th>




</th>
<th>




</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Max filesystem size

</td>
<td>


2^64

</td>
<td>


256 MiB

</td>
</tr>
<tr>
<td>


Max file size

</td>
<td>


\~ 2 TiB

</td>
<td>


16 MiB

</td>
</tr>
<tr>
<td>


Max files

</td>
<td>


unlimited

</td>
<td>


unlimited

</td>
</tr>
<tr>
<td>


Max directories

</td>
<td>


unlimited

</td>
<td>


unlimited

</td>
</tr>
<tr>
<td>


Max entries per directory

</td>
<td>


unlimited

</td>
<td>


unlimited

</td>
</tr>
<tr>
<td>


Max block size

</td>
<td>


1 MiB

</td>
<td>


4 KiB

</td>
</tr>
<tr>
<td>


Metadata compression

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Directory indexes

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Sparse file support

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Tail-end packing (fragments)

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Exportable (NFS etc.)

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Hard link support

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


"." and ".." in readdir

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Real inode numbers

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


32-bit uids/gids

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


File creation time

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Xattr support

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


ACL support

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
</tbody>
</table>

Squashfs compresses data, inodes and directories.  In addition, inode and directory data are highly compacted, and packed on byte boundaries.  Each compressed inode is on average 8 bytes in length (the exact length varies on file type, i.e. regular file, directory, symbolic link, and block/char device inodes have different sizes).

<a id="rst-using-squashfs"></a>

## 2. Using Squashfs

As squashfs is a read-only filesystem, the mksquashfs program must be used to create populated squashfs filesystems.  This and other squashfs utilities are very likely packaged by your linux distribution (called squashfs-tools). The source code can be obtained from github.com/plougher/squashfs-tools. Usage instructions can also be obtained from this site.

<a id="rst-mount-options"></a>

## 2.1 Mount options


<table>
<tbody>
<tr>
<td>


errors=%s

</td>
<td>


Specify whether squashfs errors trigger a kernel panic or not


<table>
<tbody>
<tr>
<td>


continue

</td>
<td>


errors don't trigger a panic (default)

</td>
</tr>
<tr>
<td>


panic

</td>
<td>


trigger a panic when errors are encountered, similar to several other filesystems (e.g. btrfs, ext4, f2fs, GFS2, jfs, ntfs, ubifs)

This allows a kernel dump to be saved, useful for analyzing and debugging the corruption.

</td>
</tr>
</tbody>
</table>

</td>
</tr>
<tr>
<td>


threads=%s

</td>
<td>


Select the decompression mode or the number of threads

If SQUASHFS_CHOICE_DECOMP_BY_MOUNT is set:


<table>
<tbody>
<tr>
<td>


single

</td>
<td>


use single-threaded decompression (default)

Only one block (data or metadata) can be decompressed at any one time. This limits CPU and memory usage to a minimum, but it also gives poor performance on parallel I/O workloads when using multiple CPU machines due to waiting on decompressor availability.

</td>
</tr>
<tr>
<td>


multi

</td>
<td>


use up to two parallel decompressors per core

If you have a parallel I/O workload and your system has enough memory, using this option may improve overall I/O performance. It dynamically allocates decompressors on a demand basis.

</td>
</tr>
<tr>
<td>


percpu

</td>
<td>


use a maximum of one decompressor per core

It uses percpu variables to ensure decompression is load-balanced across the cores.

</td>
</tr>
<tr>
<td>


1\|2\|3\|...

</td>
<td>


configure the number of threads used for decompression

The upper limit is num_online_cpus() \* 2.

</td>
</tr>
</tbody>
</table>

If SQUASHFS_CHOICE_DECOMP_BY_MOUNT is **not** set and SQUASHFS_DECOMP_MULTI, SQUASHFS_MOUNT_DECOMP_THREADS are both set:


<table>
<tbody>
<tr>
<td>


2\|3\|...

</td>
<td>


configure the number of threads used for decompression

The upper limit is num_online_cpus() \* 2.

</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>

<a id="rst-squashfs-filesystem-design"></a>

## 3. Squashfs Filesystem Design

A squashfs filesystem consists of a maximum of nine parts, packed together on a byte alignment:



```text
 ---------------
|  superblock   |
|---------------|
|  compression  |
|    options    |
|---------------|
|  datablocks   |
|  & fragments  |
|---------------|
|  inode table  |
|---------------|
|   directory   |
|     table     |
|---------------|
|   fragment    |
|    table      |
|---------------|
|    export     |
|    table      |
|---------------|
|    uid/gid    |
|  lookup table |
|---------------|
|     xattr     |
|     table     |
 ---------------
```

Compressed data blocks are written to the filesystem as files are read from the source directory, and checked for duplicates.  Once all file data has been written the completed inode, directory, fragment, export, uid/gid lookup and xattr tables are written.

<a id="rst-compression-options"></a>

## 3.1 Compression options

Compressors can optionally support compression specific options (e.g. dictionary size).  If non-default compression options have been used, then these are stored here.

<a id="rst-inodes"></a>

## 3.2 Inodes

Metadata (inodes and directories) are compressed in 8Kbyte blocks.  Each compressed block is prefixed by a two byte length, the top bit is set if the block is uncompressed.  A block will be uncompressed if the -noI option is set, or if the compressed block was larger than the uncompressed block.

Inodes are packed into the metadata blocks, and are not aligned to block boundaries, therefore inodes overlap compressed blocks.  Inodes are identified by a 48-bit number which encodes the location of the compressed metadata block containing the inode, and the byte offset into that block where the inode is placed (&lt;block, offset&gt;).

To maximise compression there are different inodes for each file type (regular file, directory, device, etc.), the inode contents and length varying with the type.

To further maximise compression, two types of regular file inode and directory inode are defined: inodes optimised for frequently occurring regular files and directories, and extended types where extra information has to be stored.

<a id="rst-directories"></a>

## 3.3 Directories

Like inodes, directories are packed into compressed metadata blocks, stored in a directory table.  Directories are accessed using the start address of the metablock containing the directory and the offset into the decompressed block (&lt;block, offset&gt;).

Directories are organised in a slightly complex way, and are not simply a list of file names.  The organisation takes advantage of the fact that (in most cases) the inodes of the files will be in the same compressed metadata block, and therefore, can share the start block. Directories are therefore organised in a two level list, a directory header containing the shared start block value, and a sequence of directory entries, each of which share the shared start block.  A new directory header is written once/if the inode start block changes.  The directory header/directory entry list is repeated as many times as necessary.

Directories are sorted, and can contain a directory index to speed up file lookup.  Directory indexes store one entry per metablock, each entry storing the index/filename mapping to the first directory header in each metadata block.  Directories are sorted in alphabetical order, and at lookup the index is scanned linearly looking for the first filename alphabetically larger than the filename being looked up.  At this point the location of the metadata block the filename is in has been found. The general idea of the index is to ensure only one metadata block needs to be decompressed to do a lookup irrespective of the length of the directory. This scheme has the advantage that it doesn't require extra memory overhead and doesn't require much extra storage on disk.

<a id="rst-file-data"></a>

## 3.4 File data

Regular files consist of a sequence of contiguous compressed blocks, and/or a compressed fragment block (tail-end packed block).   The compressed size of each datablock is stored in a block list contained within the file inode.

To speed up access to datablocks when reading 'large' files (256 Mbytes or larger), the code implements an index cache that caches the mapping from block index to datablock location on disk.

The index cache allows Squashfs to handle large files (up to 1.75 TiB) while retaining a simple and space-efficient block list on disk.  The cache is split into slots, caching up to eight 224 GiB files (128 KiB blocks). Larger files use multiple slots, with 1.75 TiB files using all 8 slots. The index cache is designed to be memory efficient, and by default uses 16 KiB.

<a id="rst-fragment-lookup-table"></a>

## 3.5 Fragment lookup table

Regular files can contain a fragment index which is mapped to a fragment location on disk and compressed size using a fragment lookup table.  This fragment lookup table is itself stored compressed into metadata blocks. A second index table is used to locate these.  This second index table for speed of access (and because it is small) is read at mount time and cached in memory.

<a id="rst-uid-gid-lookup-table"></a>

## 3.6 Uid/gid lookup table

For space efficiency regular files store uid and gid indexes, which are converted to 32-bit uids/gids using an id look up table.  This table is stored compressed into metadata blocks.  A second index table is used to locate these.  This second index table for speed of access (and because it is small) is read at mount time and cached in memory.

<a id="rst-export-table"></a>

## 3.7 Export table

To enable Squashfs filesystems to be exportable (via NFS etc.) filesystems can optionally (disabled with the -no-exports Mksquashfs option) contain an inode number to inode disk location lookup table.  This is required to enable Squashfs to map inode numbers passed in filehandles to the inode location on disk, which is necessary when the export code reinstantiates expired/flushed inodes.

This table is stored compressed into metadata blocks.  A second index table is used to locate these.  This second index table for speed of access (and because it is small) is read at mount time and cached in memory.

<a id="rst-xattr-table"></a>

## 3.8 Xattr table

The xattr table contains extended attributes for each inode.  The xattrs for each inode are stored in a list, each list entry containing a type, name and value field.  The type field encodes the xattr prefix ("user.", "trusted." etc) and it also encodes how the name/value fields should be interpreted.  Currently the type indicates whether the value is stored inline (in which case the value field contains the xattr value), or if it is stored out of line (in which case the value field stores a reference to where the actual value is stored).  This allows large values to be stored out of line improving scanning and lookup performance and it also allows values to be de-duplicated, the value being stored once, and all other occurrences holding an out of line reference to that value.

The xattr lists are packed into compressed 8K metadata blocks. To reduce overhead in inodes, rather than storing the on-disk location of the xattr list inside each inode, a 32-bit xattr id is stored.  This xattr id is mapped into the location of the xattr list using a second xattr id lookup table.

<a id="rst-todos-and-outstanding-issues"></a>

## 4. TODOs and Outstanding Issues

<a id="rst-todo-list"></a>

## 4.1 TODO list

Implement ACL support.

<a id="rst-squashfs-internal-cache"></a>

## 4.2 Squashfs Internal Cache

Blocks in Squashfs are compressed.  To avoid repeatedly decompressing recently accessed data Squashfs uses two small metadata and fragment caches.

The cache is not used for file datablocks, these are decompressed and cached in the page-cache in the normal way.  The cache is used to temporarily cache fragment and metadata blocks which have been read as a result of a metadata (i.e. inode or directory) or fragment access.  Because metadata and fragments are packed together into blocks (to gain greater compression) the read of a particular piece of metadata or fragment will retrieve other metadata/fragments which have been packed with it, these because of locality-of-reference may be read in the near future. Temporarily caching them ensures they are available for near future access without requiring an additional read and decompress.

In the future this internal cache may be replaced with an implementation which uses the kernel page cache.  Because the page cache operates on page sized units this may introduce additional complexity in terms of locking and associated race conditions.

---

# sysfs - _The_ filesystem for exporting kernel objects

_Peios Kernel / Internals / Filesystems_

> Patrick Mochel <mochel@osdl.org>

> **Peios:** References to Unix root and file modes below describe the inherited interface conventions. They are not sufficient Peios authorization: native descriptor/handle checks, the separate sysfs write gate, and mapped native privileges apply as appropriate. Debugfs additionally remains subject to integrity lockdown. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-sysfs-the-filesystem-for-exporting-kernel-objects"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Patrick Mochel  &lt;[mochel@osdl.org](<mailto:mochel@osdl.org>)&gt;

Mike Murphy &lt;[mamurph@cs.clemson.edu](<mailto:mamurph@cs.clemson.edu>)&gt;

**Revised:** 16 August 2011

**Original:** 10 January 2003

<a id="rst-what-it-is"></a>

## What it is

sysfs is a RAM-based filesystem initially based on ramfs. It provides a means to export kernel data structures, their attributes, and the linkages between them to userspace.

sysfs is tied inherently to the kobject infrastructure. Please read [Documentation/core-api/kobject.rst](/kernel/internals/core-api/kobject.md) for more information concerning the kobject interface.

<a id="rst-using-sysfs"></a>

## Using sysfs

sysfs is always compiled in if CONFIG_SYSFS is defined. You can access it by doing:



```text
mount -t sysfs sysfs /sys
```

<a id="rst-directory-creation"></a>

## Directory Creation

For every kobject that is registered with the system, a directory is created for it in sysfs. That directory is created as a subdirectory of the kobject's parent, expressing internal object hierarchies to userspace. Top-level directories in sysfs represent the common ancestors of object hierarchies; i.e. the subsystems the objects belong to.

sysfs internally stores a pointer to the kobject that implements a directory in the kernfs_node object associated with the directory. In the past this kobject pointer has been used by sysfs to do reference counting directly on the kobject whenever the file is opened or closed. With the current sysfs implementation the kobject reference count is only modified directly by the function sysfs_schedule_callback().

<a id="rst-attributes"></a>

## Attributes

Attributes can be exported for kobjects in the form of regular files in the filesystem. sysfs forwards file I/O operations to methods defined for the attributes, providing a means to read and write kernel attributes.

Attributes should be ASCII text files, preferably with only one value per file. It is noted that it may not be efficient to contain only one value per file, so it is socially acceptable to express an array of values of the same type.

Mixing types, expressing multiple lines of data, and doing fancy formatting of data is heavily frowned upon. Doing these things may get you publicly humiliated and your code rewritten without notice.

An attribute definition is simply:



```text
struct attribute {
        char                    *name;
        struct module           *owner;
        umode_t                 mode;
};


int sysfs_create_file(struct kobject * kobj, const struct attribute * attr);
void sysfs_remove_file(struct kobject * kobj, const struct attribute * attr);
```

A bare attribute contains no means to read or write the value of the attribute. Subsystems are encouraged to define their own attribute structure and wrapper functions for adding and removing attributes for a specific object type.

For example, the driver model defines struct device_attribute like:



```text
struct device_attribute {
        struct attribute    attr;
        ssize_t (*show)(struct device *dev, struct device_attribute *attr,
                        char *buf);
        ssize_t (*store)(struct device *dev, struct device_attribute *attr,
                        const char *buf, size_t count);
};

int device_create_file(struct device *, const struct device_attribute *);
void device_remove_file(struct device *, const struct device_attribute *);
```

It also defines this helper for defining device attributes:



```text
#define DEVICE_ATTR(_name, _mode, _show, _store) \
struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store)
```

For example, declaring:



```text
static DEVICE_ATTR(foo, S_IWUSR | S_IRUGO, show_foo, store_foo);
```

is equivalent to doing:



```text
static struct device_attribute dev_attr_foo = {
        .attr = {
                .name = "foo",
                .mode = S_IWUSR | S_IRUGO,
        },
        .show = show_foo,
        .store = store_foo,
};
```

Note as stated in include/linux/sysfs.h "OTHER_WRITABLE?  Generally considered a bad idea." so trying to set a sysfs file writable for everyone will fail reverting to RO mode for "Others".

For the common cases sysfs.h provides convenience macros to make defining attributes easier as well as making code more concise and readable. The above case could be shortened to:

static struct device_attribute dev_attr_foo = \__ATTR_RW(foo);

the list of helpers available to define your wrapper function is:

- **\__ATTR_RO(name):**

  assumes default name_show and mode 0444

- **\__ATTR_WO(name):**

  assumes a name_store only and sets Unix mode 0200. In Peios that mode does not replace the native sysfs write gate.

- **\__ATTR_RO_MODE(name, mode):**

  for more restrictive RO access; currently only use case is the EFI System Resource Table (see drivers/firmware/efi/esrt.c)

- **\__ATTR_RW(name):**

  assumes default name_show, name_store and setting mode to 0644.

- **\__ATTR_NULL:**

  which sets the name to NULL and is used as end of list indicator (see: kernel/workqueue.c)

<a id="rst-subsystem-specific-callbacks"></a>

## Subsystem-Specific Callbacks

When a subsystem defines a new attribute type, it must implement a set of sysfs operations for forwarding read and write calls to the show and store methods of the attribute owners:



```text
struct sysfs_ops {
        ssize_t (*show)(struct kobject *, struct attribute *, char *);
        ssize_t (*store)(struct kobject *, struct attribute *, const char *, size_t);
};
```

\[ Subsystems should have already defined a struct kobj_type as a descriptor for this type, which is where the sysfs_ops pointer is stored. See the kobject documentation for more information. \]

When a file is read or written, sysfs calls the appropriate method for the type. The method then translates the generic struct kobject and struct attribute pointers to the appropriate pointer types, and calls the associated methods.

To illustrate:



```text
#define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)

static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
                            char *buf)
{
        struct device_attribute *dev_attr = to_dev_attr(attr);
        struct device *dev = kobj_to_dev(kobj);
        ssize_t ret = -EIO;

        if (dev_attr->show)
                ret = dev_attr->show(dev, dev_attr, buf);
        if (ret >= (ssize_t)PAGE_SIZE) {
                printk("dev_attr_show: %pS returned bad count\n",
                                dev_attr->show);
        }
        return ret;
}
```

<a id="rst-reading-writing-attribute-data"></a>

## Reading/Writing Attribute Data

To read or write attributes, show() or store() methods must be specified when declaring the attribute. The method types should be as simple as those defined for device attributes:



```text
ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf);
ssize_t (*store)(struct device *dev, struct device_attribute *attr,
                const char *buf, size_t count);
```

IOW, they should take only an object, an attribute, and a buffer as parameters.

sysfs allocates a buffer of size (PAGE_SIZE) and passes it to the method. sysfs will call the method exactly once for each read or write. This forces the following behavior on the method implementations:

- On read(2), the show() method should fill the entire buffer. Recall that an attribute should only be exporting one value, or an array of similar values, so this shouldn't be that expensive.

  This allows userspace to do partial reads and forward seeks arbitrarily over the entire file at will. If userspace seeks back to zero or does a pread(2) with an offset of '0' the show() method will be called again, rearmed, to fill the buffer.

- On write(2), sysfs expects the entire buffer to be passed during the first write. sysfs then passes the entire buffer to the store() method. A terminating null is added after the data on stores. This makes functions like sysfs_streq() safe to use.

  When writing sysfs files, userspace processes should first read the entire file, modify the values it wishes to change, then write the entire buffer back.

  Attribute method implementations should operate on an identical buffer when reading and writing values.

Other notes:

- Writing causes the show() method to be rearmed regardless of current file position.

- The buffer will always be PAGE_SIZE bytes in length. On x86, this is 4096.

- show() methods should return the number of bytes printed into the buffer.

- New implementations of show() methods should only use sysfs_emit() or sysfs_emit_at() when formatting the value to be returned to user space.

- store() should return the number of bytes used from the buffer. If the entire buffer has been used, just return the count argument.

- show() or store() can always return errors. If a bad value comes through, be sure to return an error.

- The object passed to the methods will be pinned in memory via sysfs reference counting its embedded object. However, the physical entity (e.g. device) the object represents may not be present. Be sure to have a way to check this, if necessary.

A very simple (and naive) implementation of a device attribute is:



```text
static ssize_t show_name(struct device *dev, struct device_attribute *attr,
                        char *buf)
{
        return sysfs_emit(buf, "%s\n", dev->name);
}

static ssize_t store_name(struct device *dev, struct device_attribute *attr,
                        const char *buf, size_t count)
{
        snprintf(dev->name, sizeof(dev->name), "%.*s",
                (int)min(count, sizeof(dev->name) - 1), buf);
        return count;
}

static DEVICE_ATTR(name, S_IRUGO, show_name, store_name);
```

(Note that the real implementation doesn't allow userspace to set the name for a device.)

<a id="rst-top-level-directory-layout"></a>

## Top Level Directory Layout

The sysfs directory arrangement exposes the relationship of kernel data structures.

The top level sysfs directory looks like:



```text
block/
bus/
class/
dev/
devices/
firmware/
fs/
hypervisor/
kernel/
module/
power/
```

devices/ contains a filesystem representation of the device tree. It maps directly to the internal kernel device tree, which is a hierarchy of struct device.

bus/ contains flat directory layout of the various bus types in the kernel. Each bus's directory contains two subdirectories:



```text
devices/
drivers/
```

devices/ contains symlinks for each device discovered in the system that point to the device's directory under /sys/devices.

drivers/ contains a directory for each device driver that is loaded for devices on that particular bus (this assumes that drivers do not span multiple bus types).

fs/ contains a directory for some filesystems.  Currently each filesystem wanting to export attributes must create its own hierarchy below fs/ (see fuse/fuse.rst for an example).

module/ contains parameter values and state information for all loaded system modules, for both builtin and loadable modules.

dev/ contains two directories: char/ and block/. Inside these two directories there are symlinks named &lt;major&gt;:&lt;minor&gt;.  These symlinks point to the directories under /sys/devices for each device.  /sys/dev provides a quick way to lookup the sysfs interface for a device from the result of a stat(2) operation.

More information on driver-model specific features can be found in Documentation/driver-api/driver-model/.

block/ contains symlinks to all the block devices discovered on the system. These symlinks point to directories under /sys/devices.

class/ contains a directory for each device class, grouped by functional type. Each directory in class/ contains symlinks to devices in the /sys/devices directory.

firmware/ contains system firmware data and configuration such as firmware tables, ACPI information, and device tree data.

hypervisor/ contains virtualization platform information and provides an interface to the underlying hypervisor.  It is only present when running on a virtual machine.

kernel/ contains runtime kernel parameters, configuration settings, and status.

power/ contains power management subsystem information including sleep states, suspend/resume capabilities, and policies.

<a id="rst-current-interfaces"></a>

## Current Interfaces

The following interface layers currently exist in sysfs.

<a id="rst-devices-include-linux-device-h"></a>

### devices (include/linux/device.h)

Structure:



```text
struct device_attribute {
        struct attribute    attr;
        ssize_t (*show)(struct device *dev, struct device_attribute *attr,
                        char *buf);
        ssize_t (*store)(struct device *dev, struct device_attribute *attr,
                        const char *buf, size_t count);
};
```

Declaring:



```text
DEVICE_ATTR(_name, _mode, _show, _store);
```

Creation/Removal:



```text
int device_create_file(struct device *dev, const struct device_attribute * attr);
void device_remove_file(struct device *dev, const struct device_attribute * attr);
```

<a id="rst-bus-drivers-include-linux-device-h"></a>

### bus drivers (include/linux/device.h)

Structure:



```text
struct bus_attribute {
        struct attribute        attr;
        ssize_t (*show)(const struct bus_type *, char * buf);
        ssize_t (*store)(const struct bus_type *, const char * buf, size_t count);
};
```

Declaring:



```text
static BUS_ATTR_RW(name);
static BUS_ATTR_RO(name);
static BUS_ATTR_WO(name);
```

Creation/Removal:



```text
int bus_create_file(struct bus_type *, struct bus_attribute *);
void bus_remove_file(struct bus_type *, struct bus_attribute *);
```

<a id="rst-device-drivers-include-linux-device-h"></a>

### device drivers (include/linux/device.h)

Structure:



```text
struct driver_attribute {
        struct attribute        attr;
        ssize_t (*show)(struct device_driver *, char * buf);
        ssize_t (*store)(struct device_driver *, const char * buf,
                        size_t count);
};
```

Declaring:



```text
DRIVER_ATTR_RO(_name)
DRIVER_ATTR_RW(_name)
```

Creation/Removal:



```text
int driver_create_file(struct device_driver *, const struct driver_attribute *);
void driver_remove_file(struct device_driver *, const struct driver_attribute *);
```

<a id="rst-documentation"></a>

## Documentation

The sysfs directory structure and the attributes in each directory define an ABI between the kernel and user space. As for any ABI, it is important that this ABI is stable and properly documented. All new sysfs attributes must be documented in Documentation/ABI. See also Documentation/ABI/README for more information.

---

# Tmpfs

_Peios Kernel / Internals / Filesystems_

> Tmpfs is a file system which keeps all of its files in virtual memory.

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-tmpfs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Tmpfs is a file system which keeps all of its files in virtual memory.

Everything in tmpfs is temporary in the sense that no files will be created on your hard drive. If you unmount a tmpfs instance, everything stored therein is lost.

tmpfs puts everything into the kernel internal caches and grows and shrinks to accommodate the files it contains and is able to swap unneeded pages out to swap space, if swap was enabled for the tmpfs mount. tmpfs also supports THP.

tmpfs extends ramfs with a few userspace configurable options listed and explained further below, some of which can be reconfigured dynamically on the fly using a remount ('mount -o remount ...') of the filesystem. A tmpfs filesystem can be resized but it cannot be resized to a size below its current usage. The inherited tmpfs implementation has POSIX ACL and extended-attribute support, including trusted.\*, security.\* and user.\*. Peios rejects POSIX ACL updates through KACS; native access uses security descriptors. Generic writes to the canonical SD xattr are not a descriptor-management interface. ramfs does not use swap and you cannot modify any parameter for a ramfs filesystem. The size limit of a ramfs filesystem is how much memory you have available, and so care must be taken if used so to not run out of memory.

An alternative to tmpfs and ramfs is to use brd to create RAM disks (/dev/ram\*), which allows you to simulate a block device disk in physical RAM. To write data you would just then need to create an regular filesystem on top this ramdisk. As with ramfs, brd ramdisks cannot swap. brd ramdisks are also configured in size at initialization and you cannot dynamically resize them. Contrary to brd ramdisks, tmpfs has its own filesystem, it does not rely on the block layer at all.

Since tmpfs lives completely in the page cache and optionally on swap, all tmpfs pages will be shown as "Shmem" in /proc/meminfo and "Shared" in free(1). Notice that these counters also include shared memory (shmem, see ipcs(1)). The most reliable way to get the count is using df(1) and du(1).

tmpfs has the following uses:

1. There is always a kernel internal mount which you will not see at all. This is used for shared anonymous mappings and SYSV shared memory.

   This mount does not depend on CONFIG_TMPFS. If CONFIG_TMPFS is not set, the user visible part of tmpfs is not built. But the internal mechanisms are always present.

2. glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory (shm_open, shm_unlink). Adding the following line to /etc/fstab should take care of this:



   ```text
   tmpfs   /dev/shm        tmpfs   defaults        0 0
   ```

   Remember to create the directory that you intend to mount tmpfs on if necessary.

   This mount is \_not\_ needed for SYSV shared memory. The internal mount is used for that. (In the 2.3 kernel versions it was necessary to mount the predecessor of tmpfs (shm fs) to use SYSV shared memory.)

3. Some people (including me) find it very convenient to mount it e.g. on /tmp and /var/tmp and have a big swap partition. And now loop mounts of tmpfs files do work, so mkinitrd shipped by most distributions should succeed with a tmpfs /tmp.

4. And probably a lot more I do not know about :-)

tmpfs has three mount options for sizing:


<table>
<tbody>
<tr>
<td>


size

</td>
<td>


The limit of allocated bytes for this tmpfs instance. The default is half of your physical RAM without swap. If you oversize your tmpfs instances the machine will deadlock since the OOM handler will not be able to free that memory.

</td>
</tr>
<tr>
<td>


nr_blocks

</td>
<td>


The same as size, but in blocks of PAGE_SIZE.

</td>
</tr>
<tr>
<td>


nr_inodes

</td>
<td>


The maximum number of inodes for this instance. The default is half of the number of your physical RAM pages, or (on a machine with highmem) the number of lowmem RAM pages, whichever is the lower.

</td>
</tr>
</tbody>
</table>

These parameters accept a suffix k, m or g for kilo, mega and giga and can be changed on remount.  The size parameter also accepts a suffix % to limit this tmpfs instance to that percentage of your physical RAM: the default, when neither size nor nr_blocks is specified, is size=50%

If nr_blocks=0 (or size=0), blocks will not be limited in that instance; if nr_inodes=0, inodes will not be limited.  It is generally unwise to mount with such options, since it allows any user with write access to use up all the memory on the machine; but enhances the scalability of that instance in a system with many CPUs making intensive use of it.

If nr_inodes is not 0, that limited space for inodes is also used up by extended attributes: "df -i"'s IUsed and IUse% increase, IFree decreases.

tmpfs blocks may be swapped out, when there is a shortage of memory. tmpfs has a mount option to disable its use of swap:


<table>
<tbody>
<tr>
<td>


noswap

</td>
<td>


Disables swap. Remounts must respect the original settings. By default swap is enabled.

</td>
</tr>
</tbody>
</table>

tmpfs also supports Transparent Huge Pages which requires a kernel configured with CONFIG_TRANSPARENT_HUGEPAGE and with huge supported for your system (has_transparent_hugepage(), which is architecture specific). The mount options for this are:


<table>
<tbody>
<tr>
<td>


huge=never

</td>
<td>


Do not allocate huge pages.  This is the default.

</td>
</tr>
<tr>
<td>


huge=always

</td>
<td>


Attempt to allocate huge page every time a new page is needed.

</td>
</tr>
<tr>
<td>


huge=within_size

</td>
<td>


Only allocate huge page if it will be fully within i_size. Also respect madvise(2) hints.

</td>
</tr>
<tr>
<td>


huge=advise

</td>
<td>


Only allocate huge page if requested with madvise(2).

</td>
</tr>
</tbody>
</table>

See also [Documentation/admin-guide/mm/transhuge.rst](/kernel/administration/admin-guide/mm/transhuge.md), which describes the sysfs file /sys/kernel/mm/transparent_hugepage/shmem_enabled: which can be used to deny huge pages on all tmpfs mounts in an emergency, or to force huge pages on all tmpfs mounts for testing.

tmpfs also supports quota with the following mount options


<table>
<tbody>
<tr>
<td>


quota

</td>
<td>


User and group quota accounting and enforcement is enabled on the mount. Tmpfs is using hidden system quota files that are initialized on mount.

</td>
</tr>
<tr>
<td>


usrquota

</td>
<td>


User quota accounting and enforcement is enabled on the mount.

</td>
</tr>
<tr>
<td>


grpquota

</td>
<td>


Group quota accounting and enforcement is enabled on the mount.

</td>
</tr>
<tr>
<td>


usrquota_block_hardlimit

</td>
<td>


Set global user quota block hard limit.

</td>
</tr>
<tr>
<td>


usrquota_inode_hardlimit

</td>
<td>


Set global user quota inode hard limit.

</td>
</tr>
<tr>
<td>


grpquota_block_hardlimit

</td>
<td>


Set global group quota block hard limit.

</td>
</tr>
<tr>
<td>


grpquota_inode_hardlimit

</td>
<td>


Set global group quota inode hard limit.

</td>
</tr>
</tbody>
</table>

None of the quota related mount options can be set or changed on remount.

Quota limit parameters accept a suffix k, m or g for kilo, mega and giga and can't be changed on remount. Default global quota limits are taking effect for any and all user/group/project except root the first time the quota entry for user/group/project id is being accessed - typically the first time an inode with a particular id ownership is being created after the mount. In other words, instead of the limits being initialized to zero, they are initialized with the particular value provided with these mount options. The limits can be changed for any user/group id at any time as they normally can be.

Note that tmpfs quotas do not support user namespaces so no uid/gid translation is done if quotas are enabled inside user namespaces.

tmpfs has a mount option to set the NUMA memory allocation policy for all files in that instance (if CONFIG_NUMA is enabled) - which can be adjusted on the fly via 'mount -o remount ...'


<table>
<tbody>
<tr>
<td>


mpol=default

</td>
<td>


use the process allocation policy (see set_mempolicy(2))

</td>
</tr>
<tr>
<td>


mpol=prefer:Node

</td>
<td>


prefers to allocate memory from the given Node

</td>
</tr>
<tr>
<td>


mpol=bind:NodeList

</td>
<td>


allocates memory only from nodes in NodeList

</td>
</tr>
<tr>
<td>


mpol=interleave

</td>
<td>


prefers to allocate from each node in turn

</td>
</tr>
<tr>
<td>


mpol=interleave:NodeList

</td>
<td>


allocates from each node of NodeList in turn

</td>
</tr>
<tr>
<td>


mpol=local

</td>
<td>


prefers to allocate memory from the local node

</td>
</tr>
</tbody>
</table>

NodeList format is a comma-separated list of decimal numbers and ranges, a range being two hyphen-separated decimal numbers, the smallest and largest node numbers in the range.  For example, mpol=bind:0-3,5,7,9-15

A memory policy with a valid NodeList will be saved, as specified, for use at file creation time.  When a task allocates a file in the file system, the mount option memory policy will be applied with a NodeList, if any, modified by the calling task's cpuset constraints \[See [Documentation/admin-guide/cgroup-v1/cpusets.rst](/kernel/administration/admin-guide/cgroup-v1/cpusets.md)\] and any optional flags, listed below.  If the resulting NodeLists is the empty set, the effective memory policy for the file will revert to "default" policy.

NUMA memory allocation policies have optional flags that can be used in conjunction with their modes.  These optional flags can be specified when tmpfs is mounted by appending them to the mode before the NodeList. See [Documentation/admin-guide/mm/numa_memory_policy.rst](/kernel/administration/admin-guide/mm/numa-memory-policy.md) for a list of all available memory allocation policy mode flags and their effect on memory policy.



```text
=static         is equivalent to        MPOL_F_STATIC_NODES
=relative       is equivalent to        MPOL_F_RELATIVE_NODES
```

For example, mpol=bind=static:NodeList, is the equivalent of an allocation policy of MPOL_BIND \| MPOL_F_STATIC_NODES.

Note that trying to mount a tmpfs with an mpol option will fail if the running kernel does not support NUMA; and will fail if its nodelist specifies a node which is not online.  If your system relies on that tmpfs being mounted, but from time to time runs a kernel built without NUMA capability (perhaps a safe recovery kernel), or with fewer nodes online, then it is advisable to omit the mpol option from automatic mount options.  It can be added later, when the tmpfs is already mounted on MountPoint, by 'mount -o remount,mpol=Policy:NodeList MountPoint'.

To specify the initial root directory you can use the following mount options:


<table>
<tbody>
<tr>
<td>


mode

</td>
<td>


The permissions as an octal number

</td>
</tr>
<tr>
<td>


uid

</td>
<td>


The user id

</td>
</tr>
<tr>
<td>


gid

</td>
<td>


The group id

</td>
</tr>
</tbody>
</table>

These options do not have any effect on remount. You can change these parameters with chmod(1), chown(1) and chgrp(1) on a mounted filesystem.

tmpfs has a mount option to select whether it will wrap at 32- or 64-bit inode numbers:


<table>
<tbody>
<tr>
<td>


inode64

</td>
<td>


Use 64-bit inode numbers

</td>
</tr>
<tr>
<td>


inode32

</td>
<td>


Use 32-bit inode numbers

</td>
</tr>
</tbody>
</table>

On a 32-bit kernel, inode32 is implicit, and inode64 is refused at mount time. On a 64-bit kernel, CONFIG_TMPFS_INODE64 sets the default.  inode64 avoids the possibility of multiple files with the same inode number on a single device; but risks glibc failing with EOVERFLOW once 33-bit inode numbers are reached - if a long-lived tmpfs is accessed by 32-bit applications so ancient that opening a file larger than 2GiB fails with EINVAL.

The command `mount -t tmpfs -o size=10G,nr_inodes=10k,mode=700 tmpfs /mytmpfs` sets a 10GB RAM/swap and 10240-inode limit, with Unix mode 0700 on the root directory. In Peios, that mode alone does not establish access: the mount's native descriptor policy does. Privileged system tmpfs mounts need seeded descriptors; tmpfs admitted through the mount-namespace descriptor path receives an ephemeral template.

tmpfs has the following mounting options for case-insensitive lookup support:


<table>
<tbody>
<tr>
<td>


casefold

</td>
<td>


Enable casefold support at this mount point using the given argument as the encoding standard. Currently only UTF-8 encodings are supported. If no argument is used, it will load the latest UTF-8 encoding available.

</td>
</tr>
<tr>
<td>


strict_encoding

</td>
<td>


Enable strict encoding at this mount point (disabled by default). In this mode, the filesystem refuses to create file and directory with names containing invalid UTF-8 characters.

</td>
</tr>
</tbody>
</table>

This option doesn't render the entire filesystem case-insensitive. One needs to still set the casefold flag per directory, by flipping the +F attribute in an empty directory. Nevertheless, new directories will inherit the attribute. The mountpoint itself cannot be made case-insensitive.

Example:



```text
$ mount -t tmpfs -o casefold=utf8-12.1.0,strict_encoding fs_name /mytmpfs
$ mount -t tmpfs -o casefold fs_name /mytmpfs
```

**Author:** Christoph Rohland &lt;[cr@sap.com](<mailto:cr@sap.com>)&gt;, 1.12.01

**Updated:** Hugh Dickins, 4 June 2007

**Updated:** KOSAKI Motohiro, 16 Mar 2010

**Updated:** Chris Down, 13 July 2020

**Updated:** André Almeida, 23 Aug 2024

---

# UBIFS Authentication Support

_Peios Kernel / Internals / Filesystems_

> UBIFS utilizes the fscrypt framework to provide confidentiality for file contents and file names. This prevents attacks where an attacker is able to read contents of the filesystem on a single point in time. A classic example is a lost…

<a id="rst-ubifs-authentication-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- UBIFS Authentication -->

<!-- sigma star gmbh -->

<!-- 2018 -->

<a id="rst-introduction"></a>

## Introduction

UBIFS utilizes the fscrypt framework to provide confidentiality for file contents and file names. This prevents attacks where an attacker is able to read contents of the filesystem on a single point in time. A classic example is a lost smartphone where the attacker is unable to read personal data stored on the device without the filesystem decryption key.

At the current state, UBIFS encryption however does not prevent attacks where the attacker is able to modify the filesystem contents and the user uses the device afterwards. In such a scenario an attacker can modify filesystem contents arbitrarily without the user noticing. One example is to modify a binary to perform a malicious action when executed \[DMC-CBC-ATTACK\]. Since most of the filesystem metadata of UBIFS is stored in plain, this makes it fairly easy to swap files and replace their contents.

Other full disk encryption systems like dm-crypt cover all filesystem metadata, which makes such kinds of attacks more complicated, but not impossible. Especially, if the attacker is given access to the device multiple points in time. For dm-crypt and other filesystems that build upon the Linux block IO layer, the dm-integrity or dm-verity subsystems \[DM-INTEGRITY, DM-VERITY\] can be used to get full data authentication at the block layer. These can also be combined with dm-crypt \[CRYPTSETUP2\].

This document describes an approach to get file contents \_and\_ full metadata authentication for UBIFS. Since UBIFS uses fscrypt for file contents and file name encryption, the authentication system could be tied into fscrypt such that existing features like key derivation can be utilized. It should however also be possible to use UBIFS authentication without using encryption.

<a id="rst-mtd-ubi-ubifs"></a>

### MTD, UBI &amp; UBIFS

On Linux, the MTD (Memory Technology Devices) subsystem provides a uniform interface to access raw flash devices. One of the more prominent subsystems that work on top of MTD is UBI (Unsorted Block Images). It provides volume management for flash devices and is thus somewhat similar to LVM for block devices. In addition, it deals with flash-specific wear-leveling and transparent I/O error handling. UBI offers logical erase blocks (LEBs) to the layers on top of it and maps them transparently to physical erase blocks (PEBs) on the flash.

UBIFS is a filesystem for raw flash which operates on top of UBI. Thus, wear leveling and some flash specifics are left to UBI, while UBIFS focuses on scalability, performance and recoverability.



```text
+------------+ +*******+ +-----------+ +-----+
|            | * UBIFS * | UBI-BLOCK | | ... |
| JFFS/JFFS2 | +*******+ +-----------+ +-----+
|            | +-----------------------------+ +-----------+ +-----+
|            | |              UBI            | | MTD-BLOCK | | ... |
+------------+ +-----------------------------+ +-----------+ +-----+
+------------------------------------------------------------------+
|                  MEMORY TECHNOLOGY DEVICES (MTD)                 |
+------------------------------------------------------------------+
+-----------------------------+ +--------------------------+ +-----+
|         NAND DRIVERS        | |        NOR DRIVERS       | | ... |
+-----------------------------+ +--------------------------+ +-----+

    Figure 1: Linux kernel subsystems for dealing with raw flash
```

Internally, UBIFS maintains multiple data structures which are persisted on the flash:

- *Index*: an on-flash B+ tree where the leaf nodes contain filesystem data

- *Journal*: an additional data structure to collect FS changes before updating the on-flash index and reduce flash wear.

- *Tree Node Cache (TNC)*: an in-memory B+ tree that reflects the current FS state to avoid frequent flash reads. It is basically the in-memory representation of the index, but contains additional attributes.

- *LEB property tree (LPT)*: an on-flash B+ tree for free space accounting per UBI LEB.

In the remainder of this section we will cover the on-flash UBIFS data structures in more detail. The TNC is of less importance here since it is never persisted onto the flash directly. More details on UBIFS can also be found in \[UBIFS-WP\].

<a id="rst-ubifs-index-tree-node-cache"></a>

#### UBIFS Index &amp; Tree Node Cache

Basic on-flash UBIFS entities are called *nodes*. UBIFS knows different types of nodes. Eg. data nodes (`struct ubifs_data_node`) which store chunks of file contents or inode nodes (`struct ubifs_ino_node`) which represent VFS inodes. Almost all types of nodes share a common header (`ubifs_ch`) containing basic information like node type, node length, a sequence number, etc. (see `fs/ubifs/ubifs-media.h` in kernel source). Exceptions are entries of the LPT and some less important node types like padding nodes which are used to pad unusable content at the end of LEBs.

To avoid re-writing the whole B+ tree on every single change, it is implemented as *wandering tree*, where only the changed nodes are re-written and previous versions of them are obsoleted without erasing them right away. As a result, the index is not stored in a single place on the flash, but *wanders* around and there are obsolete parts on the flash as long as the LEB containing them is not reused by UBIFS. To find the most recent version of the index, UBIFS stores a special node called *master node* into UBI LEB 1 which always points to the most recent root node of the UBIFS index. For recoverability, the master node is additionally duplicated to LEB 2. Mounting UBIFS is thus a simple read of LEB 1 and 2 to get the current master node and from there get the location of the most recent on-flash index.

The TNC is the in-memory representation of the on-flash index. It contains some additional runtime attributes per node which are not persisted. One of these is a dirty-flag which marks nodes that have to be persisted the next time the index is written onto the flash. The TNC acts as a write-back cache and all modifications of the on-flash index are done through the TNC. Like other caches, the TNC does not have to mirror the full index into memory, but reads parts of it from flash whenever needed. A *commit* is the UBIFS operation of updating the on-flash filesystem structures like the index. On every commit, the TNC nodes marked as dirty are written to the flash to update the persisted index.

<a id="rst-journal"></a>

#### Journal

To avoid wearing out the flash, the index is only persisted (*committed*) when certain conditions are met (eg. `fsync(2)`). The journal is used to record any changes (in form of inode nodes, data nodes etc.) between commits of the index. During mount, the journal is read from the flash and replayed onto the TNC (which will be created on-demand from the on-flash index).

UBIFS reserves a bunch of LEBs just for the journal called *log area*. The amount of log area LEBs is configured on filesystem creation (using `mkfs.ubifs`) and stored in the superblock node. The log area contains only two types of nodes: *reference nodes* and *commit start nodes*. A commit start node is written whenever an index commit is performed. Reference nodes are written on every journal update. Each reference node points to the position of other nodes (inode nodes, data nodes etc.) on the flash that are part of this journal entry. These nodes are called *buds* and describe the actual filesystem changes including their data.

The log area is maintained as a ring. Whenever the journal is almost full, a commit is initiated. This also writes a commit start node so that during mount, UBIFS will seek for the most recent commit start node and just replay every reference node after that. Every reference node before the commit start node will be ignored as they are already part of the on-flash index.

When writing a journal entry, UBIFS first ensures that enough space is available to write the reference node and buds part of this entry. Then, the reference node is written and afterwards the buds describing the file changes. On replay, UBIFS will record every reference node and inspect the location of the referenced LEBs to discover the buds. If these are corrupt or missing, UBIFS will attempt to recover them by re-reading the LEB. This is however only done for the last referenced LEB of the journal. Only this can become corrupt because of a power cut. If the recovery fails, UBIFS will not mount. An error for every other LEB will directly cause UBIFS to fail the mount operation.



```text
| ----    LOG AREA     ---- | ----------    MAIN AREA    ------------ |

 -----+------+-----+--------+----   ------+-----+-----+---------------
 \    |      |     |        |   /  /      |     |     |               \
 / CS |  REF | REF |        |   \  \ DENT | INO | INO |               /
 \    |      |     |        |   /  /      |     |     |               \
  ----+------+-----+--------+---   -------+-----+-----+----------------
          |     |                  ^            ^
          |     |                  |            |
          +------------------------+            |
                |                               |
                +-------------------------------+


         Figure 2: UBIFS flash layout of log area with commit start nodes
                   (CS) and reference nodes (REF) pointing to main area
                   containing their buds
```

<a id="rst-leb-property-tree-table"></a>

#### LEB Property Tree/Table

The LEB property tree is used to store per-LEB information. This includes the LEB type and amount of free and *dirty* (old, obsolete content) space <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1) on the LEB. The type is important, because UBIFS never mixes index nodes with data nodes on a single LEB and thus each LEB has a specific purpose. This again is useful for free space calculations. See \[UBIFS-WP\] for more details.

The LEB property tree again is a B+ tree, but it is much smaller than the index. Due to its smaller size it is always written as one chunk on every commit. Thus, saving the LPT is an atomic operation.

<a id="rst-footnote-1"></a>



**[1]** Since LEBs can only be appended and never overwritten, there is a difference between free space ie. the remaining space left on the LEB to be written to without erasing it and previously written content that is obsolete but can't be overwritten without erasing the full LEB.

<a id="rst-ubifs-authentication"></a>

## UBIFS Authentication

This chapter introduces UBIFS authentication which enables UBIFS to verify the authenticity and integrity of metadata and file contents stored on flash.

<a id="rst-threat-model"></a>

### Threat Model

UBIFS authentication enables detection of offline data modification. While it does not prevent it, it enables (trusted) code to check the integrity and authenticity of on-flash file contents and filesystem metadata. This covers attacks where file contents are swapped.

UBIFS authentication will not protect against rollback of full flash contents. Ie. an attacker can still dump the flash and restore it at a later time without detection. It will also not protect against partial rollback of individual index commits. That means that an attacker is able to partially undo changes. This is possible because UBIFS does not immediately overwrites obsolete versions of the index tree or the journal, but instead marks them as obsolete and garbage collection erases them at a later time. An attacker can use this by erasing parts of the current tree and restoring old versions that are still on the flash and have not yet been erased. This is possible, because every commit will always write a new version of the index root node and the master node without overwriting the previous version. This is further helped by the wear-leveling operations of UBI which copies contents from one physical eraseblock to another and does not atomically erase the first eraseblock.

UBIFS authentication does not cover attacks where an attacker is able to execute code on the device after the authentication key was provided. Additional measures like secure boot and trusted boot have to be taken to ensure that only trusted code is executed on a device.

<a id="rst-authentication"></a>

### Authentication

To be able to fully trust data read from flash, all UBIFS data structures stored on flash are authenticated. That is:

- The index which includes file contents, file metadata like extended attributes, file length etc.

- The journal which also contains file contents and metadata by recording changes to the filesystem

- The LPT which stores UBI LEB metadata which UBIFS uses for free space accounting

<a id="rst-index-authentication"></a>

#### Index Authentication

Through UBIFS' concept of a wandering tree, it already takes care of only updating and persisting changed parts from leaf node up to the root node of the full B+ tree. This enables us to augment the index nodes of the tree with a hash over each node's child nodes. As a result, the index basically also a Merkle tree. Since the leaf nodes of the index contain the actual filesystem data, the hashes of their parent index nodes thus cover all the file contents and file metadata. When a file changes, the UBIFS index is updated accordingly from the leaf nodes up to the root node including the master node. This process can be hooked to recompute the hash only for each changed node at the same time. Whenever a file is read, UBIFS can verify the hashes from each leaf node up to the root node to ensure the node's integrity.

To ensure the authenticity of the whole index, the UBIFS master node stores a keyed hash (HMAC) over its own contents and a hash of the root node of the index tree. As mentioned above, the master node is always written to the flash whenever the index is persisted (ie. on index commit).

Using this approach only UBIFS index nodes and the master node are changed to include a hash. All other types of nodes will remain unchanged. This reduces the storage overhead which is precious for users of UBIFS (ie. embedded devices).



```text
                  +---------------+
                  |  Master Node  |
                  |    (hash)     |
                  +---------------+
                          |
                          v
                 +-------------------+
                 |  Index Node #1    |
                 |                   |
                 | branch0   branchn |
                 | (hash)    (hash)  |
                 +-------------------+
                    |    ...   |  (fanout: 8)
                    |          |
            +-------+          +------+
            |                         |
            v                         v
 +-------------------+       +-------------------+
 |  Index Node #2    |       |  Index Node #3    |
 |                   |       |                   |
 | branch0   branchn |       | branch0   branchn |
 | (hash)    (hash)  |       | (hash)    (hash)  |
 +-------------------+       +-------------------+
      |   ...                     |   ...   |
      v                           v         v
    +-----------+         +----------+  +-----------+
    | Data Node |         | INO Node |  | DENT Node |
    +-----------+         +----------+  +-----------+


Figure 3: Coverage areas of index node hash and master node HMAC
```

The most important part for robustness and power-cut safety is to atomically persist the hash and file contents. Here the existing UBIFS logic for how changed nodes are persisted is already designed for this purpose such that UBIFS can safely recover if a power-cut occurs while persisting. Adding hashes to index nodes does not change this since each hash will be persisted atomically together with its respective node.

<a id="rst-journal-authentication"></a>

#### Journal Authentication

The journal is authenticated too. Since the journal is continuously written it is necessary to also add authentication information frequently to the journal so that in case of a powercut not too much data can't be authenticated. This is done by creating a continuous hash beginning from the commit start node over the previous reference nodes, the current reference node, and the bud nodes. From time to time whenever it is suitable authentication nodes are added between the bud nodes. This new node type contains a HMAC over the current state of the hash chain. That way a journal can be authenticated up to the last authentication node. The tail of the journal which may not have a authentication node cannot be authenticated and is skipped during journal replay.

We get this picture for journal authentication:



```text
,,,,,,,,
,......,...........................................
,. CS  ,               hash1.----.           hash2.----.
,.  |  ,                    .    |hmac            .    |hmac
,.  v  ,                    .    v                .    v
,.REF#0,-> bud -> bud -> bud.-> auth -> bud -> bud.-> auth ...
,..|...,...........................................
,  |   ,
,  |   ,,,,,,,,,,,,,,,
.  |            hash3,----.
,  |                 ,    |hmac
,  v                 ,    v
, REF#1 -> bud -> bud,-> auth ...
,,,|,,,,,,,,,,,,,,,,,,
   v
  REF#2 -> ...
   |
   V
  ...
```

Since the hash also includes the reference nodes an attacker cannot reorder or skip any journal heads for replay. An attacker can only remove bud nodes or reference nodes from the end of the journal, effectively rewinding the filesystem at maximum back to the last commit.

The location of the log area is stored in the master node. Since the master node is authenticated with a HMAC as described above, it is not possible to tamper with that without detection. The size of the log area is specified when the filesystem is created using `mkfs.ubifs` and stored in the superblock node. To avoid tampering with this and other values stored there, a HMAC is added to the superblock struct. The superblock node is stored in LEB 0 and is only modified on feature flag or similar changes, but never on file changes.

<a id="rst-lpt-authentication"></a>

#### LPT Authentication

The location of the LPT root node on the flash is stored in the UBIFS master node. Since the LPT is written and read atomically on every commit, there is no need to authenticate individual nodes of the tree. It suffices to protect the integrity of the full LPT by a simple hash stored in the master node. Since the master node itself is authenticated, the LPTs authenticity can be verified by verifying the authenticity of the master node and comparing the LTP hash stored there with the hash computed from the read on-flash LPT.

<a id="rst-key-management"></a>

### Key Management

For simplicity, UBIFS authentication uses a single key to compute the HMACs of superblock, master, commit start and reference nodes. This key has to be available on creation of the filesystem (`mkfs.ubifs`) to authenticate the superblock node. Further, it has to be available on mount of the filesystem to verify authenticated nodes and generate new HMACs for changes.

UBIFS authentication is intended to operate side-by-side with UBIFS encryption (fscrypt) to provide confidentiality and authenticity. Since UBIFS encryption has a different approach of encryption policies per directory, there can be multiple fscrypt master keys and there might be folders without encryption. UBIFS authentication on the other hand has an all-or-nothing approach in the sense that it either authenticates everything of the filesystem or nothing. Because of this and because UBIFS authentication should also be usable without encryption, it does not share the same master key with fscrypt, but manages a dedicated authentication key.

The API for providing the authentication key has yet to be defined, but the key can eg. be provided by userspace through a keyring similar to the way it is currently done in fscrypt. It should however be noted that the current fscrypt approach has shown its flaws and the userspace API will eventually change \[FSCRYPT-POLICY2\].

Nevertheless, it will be possible for a user to provide a single passphrase or key in userspace that covers UBIFS authentication and encryption. This can be solved by the corresponding userspace tools which derive a second key for authentication in addition to the derived fscrypt master key used for encryption.

To be able to check if the proper key is available on mount, the UBIFS superblock node will additionally store a hash of the authentication key. This approach is similar to the approach proposed for fscrypt encryption policy v2 \[FSCRYPT-POLICY2\].

<a id="rst-future-extensions"></a>

## Future Extensions

In certain cases where a vendor wants to provide an authenticated filesystem image to customers, it should be possible to do so without sharing the secret UBIFS authentication key. Instead, in addition the each HMAC a digital signature could be stored where the vendor shares the public key alongside the filesystem image. In case this filesystem has to be modified afterwards, UBIFS can exchange all digital signatures with HMACs on first mount similar to the way the IMA/EVM subsystem deals with such situations. The HMAC key will then have to be provided beforehand in the normal way.

<a id="rst-references"></a>

## References

\[CRYPTSETUP2\]        [https://www.saout.de/pipermail/dm-crypt/2017-November/005745.html](<https://www.saout.de/pipermail/dm-crypt/2017-November/005745.html>)

\[DMC-CBC-ATTACK\]     [https://www.jakoblell.com/blog/2013/12/22/practical-malleability-attack-against-cbc-encrypted-luks-partitions/](<https://www.jakoblell.com/blog/2013/12/22/practical-malleability-attack-against-cbc-encrypted-luks-partitions/>)

\[DM-INTEGRITY\]       [https://www.kernel.org/doc/Documentation/device-mapper/dm-integrity.rst](<https://www.kernel.org/doc/Documentation/device-mapper/dm-integrity.rst>)

\[DM-VERITY\]          [https://www.kernel.org/doc/Documentation/device-mapper/verity.rst](<https://www.kernel.org/doc/Documentation/device-mapper/verity.rst>)

\[FSCRYPT-POLICY2\]    [https://lore.kernel.org/r/20171023214058.128121-1-ebiggers3@gmail.com/](<https://lore.kernel.org/r/20171023214058.128121-1-ebiggers3@gmail.com/>)

\[UBIFS-WP\]           [http://www.linux-mtd.infradead.org/doc/ubifs_whitepaper.pdf](<http://www.linux-mtd.infradead.org/doc/ubifs_whitepaper.pdf>)

---

# UBI File System

_Peios Kernel / Internals / Filesystems_

> UBIFS file-system stands for UBI File System. UBI stands for "Unsorted Block Images". UBIFS is a flash file system, which means it is designed to work with flash devices. It is important to understand, that UBIFS is completely different to…

<a id="rst-ubi-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

UBIFS file-system stands for UBI File System. UBI stands for "Unsorted Block Images". UBIFS is a flash file system, which means it is designed to work with flash devices. It is important to understand, that UBIFS is completely different to any traditional file-system in Linux, like Ext2, XFS, JFS, etc. UBIFS represents a separate class of file-systems which work with MTD devices, not block devices. The other Linux file-system of this class is JFFS2.

To make it more clear, here is a small comparison of MTD devices and block devices.

- **1 MTD devices represent flash devices and they consist of eraseblocks of**

  rather large size, typically about 128KiB. Block devices consist of small blocks, typically 512 bytes.

- **2 MTD devices support 3 main operations - read from some offset within an**

  eraseblock, write to some offset within an eraseblock, and erase a whole eraseblock. Block  devices support 2 main operations - read a whole block and write a whole block.

- **3 The whole eraseblock has to be erased before it becomes possible to**

  re-write its contents. Blocks may be just re-written.

- **4 Eraseblocks become worn out after some number of erase cycles -**

  typically 100K-1G for SLC NAND and NOR flashes, and 1K-10K for MLC NAND flashes. Blocks do not have the wear-out property.

- **5 Eraseblocks may become bad (only on NAND flashes) and software should**

  deal with this. Blocks on hard drives typically do not become bad, because hardware has mechanisms to substitute bad blocks, at least in modern LBA disks.

It should be quite obvious why UBIFS is very different to traditional file-systems.

UBIFS works on top of UBI. UBI is a separate software layer which may be found in drivers/mtd/ubi. UBI is basically a volume management and wear-leveling layer. It provides so called UBI volumes which is a higher level abstraction than a MTD device. The programming model of UBI devices is very similar to MTD devices - they still consist of large eraseblocks, they have read/write/erase operations, but UBI devices are devoid of limitations like wear and bad blocks (items 4 and 5 in the above list).

In a sense, UBIFS is a next generation of JFFS2 file-system, but it is very different and incompatible to JFFS2. The following are the main differences.

- JFFS2 works on top of MTD devices, UBIFS depends on UBI and works on top of UBI volumes.

- JFFS2 does not have on-media index and has to build it while mounting, which requires full media scan. UBIFS maintains the FS indexing information on the flash media and does not require full media scan, so it mounts many times faster than JFFS2.

- JFFS2 is a write-through file-system, while UBIFS supports write-back, which makes UBIFS much faster on writes.

Similarly to JFFS2, UBIFS supports on-the-fly compression which makes it possible to fit quite a lot of data to the flash.

Similarly to JFFS2, UBIFS is tolerant of unclean reboots and power-cuts. It does not need stuff like fsck.ext2. UBIFS automatically replays its journal and recovers from crashes, ensuring that the on-flash data structures are consistent.

UBIFS scales logarithmically (most of the data structures it uses are trees), so the mount time and memory consumption do not linearly depend on the flash size, like in case of JFFS2. This is because UBIFS maintains the FS index on the flash media. However, UBIFS depends on UBI, which scales linearly. So overall UBI/UBIFS stack scales linearly. Nevertheless, UBI/UBIFS scales considerably better than JFFS2.

The authors of UBIFS believe, that it is possible to develop UBI2 which would scale logarithmically as well. UBI2 would support the same API as UBI, but it would be binary incompatible to UBI. So UBIFS would not need to be changed to use UBI2

<a id="rst-mount-options"></a>

## Mount options

(\*) == default.


<table>
<tbody>
<tr>
<td>


bulk_read

</td>
<td>


read more in one go to take advantage of flash media that read faster sequentially

</td>
</tr>
<tr>
<td>


no_bulk_read (\*)

</td>
<td>


do not bulk-read

</td>
</tr>
<tr>
<td>


no_chk_data_crc (\*)

</td>
<td>


skip checking of CRCs on data nodes in order to improve read performance. Use this option only if the flash media is highly reliable. The effect of this option is that corruption of the contents of a file can go unnoticed.

</td>
</tr>
<tr>
<td>


chk_data_crc

</td>
<td>


do not skip checking CRCs on data nodes

</td>
</tr>
<tr>
<td>


compr=none

</td>
<td>


override default compressor and set it to "none"

</td>
</tr>
<tr>
<td>


compr=lzo

</td>
<td>


override default compressor and set it to "lzo"

</td>
</tr>
<tr>
<td>


compr=zlib

</td>
<td>


override default compressor and set it to "zlib"

</td>
</tr>
<tr>
<td>


auth_key=

</td>
<td>


specify the key used for authenticating the filesystem. Passing this option makes authentication mandatory. The passed key must be present in the kernel keyring and must be of type 'logon'

</td>
</tr>
<tr>
<td>


auth_hash_name=

</td>
<td>


The hash algorithm used for authentication. Used for both hashing and for creating HMACs. Typical values include "sha256" or "sha512"

</td>
</tr>
</tbody>
</table>

<a id="rst-quick-usage-instructions"></a>

## Quick usage instructions

The UBI volume to mount is specified using "ubiX_Y" or "ubiX:NAME" syntax, where "X" is UBI device number, "Y" is UBI volume number, and "NAME" is UBI volume name.

Mount volume 0 on UBI device 0 to /mnt/ubifs:



```text
$ mount -t ubifs ubi0_0 /mnt/ubifs
```

Mount "rootfs" volume of UBI device 0 to /mnt/ubifs ("rootfs" is volume name):



```text
$ mount -t ubifs ubi0:rootfs /mnt/ubifs
```

The following is an example of the kernel boot arguments to attach mtd0 to UBI and mount volume "rootfs": ubi.mtd=0 root=ubi0:rootfs rootfstype=ubifs

<a id="rst-references"></a>

## References

UBIFS documentation and FAQ/HOWTO at the MTD web site:

- [http://www.linux-mtd.infradead.org/doc/ubifs.html](<http://www.linux-mtd.infradead.org/doc/ubifs.html>)

- [http://www.linux-mtd.infradead.org/faq/ubifs.html](<http://www.linux-mtd.infradead.org/faq/ubifs.html>)

---

# UDF file system

_Peios Kernel / Internals / Filesystems_

> If you encounter problems with reading UDF discs using this driver, please report them according to MAINTAINERS file.

<a id="rst-udf-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

If you encounter problems with reading UDF discs using this driver, please report them according to MAINTAINERS file.

Write support requires a block driver which supports writing.  Currently dvd+rw drives and media support true random sector writes, and so a udf filesystem on such devices can be directly mounted read/write.  CD-RW media however, does not support this.  Instead the media can be formatted for packet mode using the utility cdrwtool, then the pktcdvd driver can be bound to the underlying cd device to provide the required buffering and read-modify-write cycles to allow the filesystem random sector writes while providing the hardware with only full packet writes.  While not required for dvd+rw media, use of the pktcdvd driver often enhances performance due to very poor read-modify-write support supplied internally by drive firmware.

---

The following mount options are supported:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> gid=
>
> </td>
> <td>
>
>
> Set the default group.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> umask=
>
> </td>
> <td>
>
>
> Set the default umask.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mode=
>
> </td>
> <td>
>
>
> Set the default file permissions.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dmode=
>
> </td>
> <td>
>
>
> Set the default directory permissions.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> uid=
>
> </td>
> <td>
>
>
> Set the default user.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> bs=
>
> </td>
> <td>
>
>
> Set the block size.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> unhide
>
> </td>
> <td>
>
>
> Show otherwise hidden files.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> undelete
>
> </td>
> <td>
>
>
> Show deleted files in lists.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> adinicb
>
> </td>
> <td>
>
>
> Embed data in the inode (default)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> noadinicb
>
> </td>
> <td>
>
>
> Don't embed data in the inode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> shortad
>
> </td>
> <td>
>
>
> Use short ad's
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> longad
>
> </td>
> <td>
>
>
> Use long ad's (default)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nostrict
>
> </td>
> <td>
>
>
> Unset strict conformance
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> iocharset=
>
> </td>
> <td>
>
>
> Set the NLS character set
>
> </td>
> </tr>
> </tbody>
> </table>

The uid= and gid= options need a bit more explaining.  They will accept a decimal numeric value and all inodes on that mount will then appear as belonging to that uid and gid.  Mount options also accept the string "forget". The forget option causes all IDs to be written to disk as -1 which is a way of UDF standard to indicate that IDs are not supported for these files .

For typical desktop use of removable media, you should set the ID to that of the interactively logged on user, and also specify the forget option.  This way the interactive user will always see the files on the disk as belonging to him.

The remaining are for debugging and disaster recovery:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> novrs
>
> </td>
> <td>
>
>
> Skip volume sequence recognition
>
> </td>
> </tr>
> </tbody>
> </table>

The following expect a offset from 0.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> session=
>
> </td>
> <td>
>
>
> Set the CDROM session (default= last session)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> anchor=
>
> </td>
> <td>
>
>
> Override standard anchor location. (default= 256)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> lastblock=
>
> </td>
> <td>
>
>
> Set the last block of the filesystem/
>
> </td>
> </tr>
> </tbody>
> </table>

---

- **For the latest version and toolset see:**

  [https://github.com/pali/udftools](<https://github.com/pali/udftools>)

- **Documentation on UDF and ECMA 167 is available FREE from:**

  - [http://www.osta.org/](<http://www.osta.org/>)

  - [https://www.ecma-international.org/](<https://www.ecma-international.org/>)

---

# VFAT

_Peios Kernel / Internals / Filesystems_

> To use the vfat filesystem, use the filesystem type 'vfat'. i.e.:

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-vfat"></a>

<a id="rst-using-vfat"></a>

## USING VFAT

To use the vfat filesystem, use the filesystem type 'vfat'.  i.e.:



```text
mount -t vfat /dev/fd0 /mnt
```

No special partition formatter is required, 'mkdosfs' will work fine if you want to format from within Linux.

<a id="rst-vfat-mount-options"></a>

## VFAT MOUNT OPTIONS

- ****uid=\#\#\#****

  Set the owner of all files on this filesystem. The default is the uid of current process.

- ****gid=\#\#\#****

  Set the group of all files on this filesystem. The default is the gid of current process.

- ****umask=\#\#\#****

  The permission mask (for files and directories, see *umask(1)*). The default is the umask of current process.

- ****dmask=\#\#\#****

  The permission mask for the directory. The default is the umask of current process.

- ****fmask=\#\#\#****

  The permission mask for files. The default is the umask of current process.

- ****allow_utime=\#\#\#****

  This option controls the permission check of mtime/atime.

  > **-20**: If current process is in group of file's group ID, you can change timestamp.
  >
  > **-2**: Other users can change timestamp.

  The default is set from dmask option. If the directory is writable, utime(2) is also allowed. i.e. \~dmask &amp; 022.

  Normally utime(2) checks current process is owner of the file, or it has CAP_FOWNER capability. But FAT filesystem doesn't have uid/gid on disk, so normal check is too inflexible. With this option you can relax it.

- ****codepage=\#\#\#****

  Sets the codepage number for converting to shortname characters on FAT filesystem. By default, FAT_DEFAULT_CODEPAGE setting is used.

- ****iocharset=&lt;name&gt;****

  Character set to use for converting between the encoding is used for user visible filename and 16 bit Unicode characters. Long filenames are stored on disk in Unicode format, but Unix for the most part doesn't know how to deal with Unicode. By default, FAT_DEFAULT_IOCHARSET setting is used.

  There is also an option of doing UTF-8 translations with the utf8 option.

> [!NOTE]
>
> `iocharset=utf8` is not recommended. If unsure, you should consider the utf8 option instead.

- ****utf8=&lt;bool&gt;****

  UTF-8 is the filesystem safe version of Unicode that is used by the console. It can be enabled or disabled for the filesystem with this option. If 'uni_xlate' gets set, UTF-8 gets disabled. By default, FAT_DEFAULT_UTF8 setting is used.

- ****uni_xlate=&lt;bool&gt;****

  Translate unhandled Unicode characters to special escaped sequences.  This would let you backup and restore filenames that are created with any Unicode characters.  Until Linux supports Unicode for real, this gives you an alternative.  Without this option, a '?' is used when no translation is possible.  The escape character is ':' because it is otherwise illegal on the vfat filesystem.  The escape sequence that gets used is ':' and the four digits of hexadecimal unicode.

- ****nonumtail=&lt;bool&gt;****

  When creating 8.3 aliases, normally the alias will end in '\~1' or tilde followed by some number.  If this option is set, then if the filename is "longfilename.txt" and "longfile.txt" does not currently exist in the directory, longfile.txt will be the short alias instead of longfi\~1.txt.

- ****usefree****

  Use the "free clusters" value stored on FSINFO. It will be used to determine number of free clusters without scanning disk. But it's not used by default, because recent Windows don't update it correctly in some case. If you are sure the "free clusters" on FSINFO is correct, by this option you can avoid scanning disk.

- ****quiet****

  Stops printing certain warning messages.

- ****check=s\|r\|n****

  Case sensitivity checking setting.

  **s**: strict, case sensitive

  **r**: relaxed, case insensitive

  **n**: normal, default setting, currently case insensitive

- ****nocase****

  This was deprecated for vfat. Use `shortname=win95` instead.

- ****shortname=lower\|win95\|winnt\|mixed****

  Shortname display/create setting.

  **lower**: convert to lowercase for display, emulate the Windows 95 rule for create.

  **win95**: emulate the Windows 95 rule for display/create.

  **winnt**: emulate the Windows NT rule for display/create.

  **mixed**: emulate the Windows NT rule for display, emulate the Windows 95 rule for create.

  Default setting is `mixed`.

- ****tz=UTC****

  Interpret timestamps as UTC rather than local time. This option disables the conversion of timestamps between local time (as used by Windows on FAT) and UTC (which Linux uses internally).  This is particularly useful when mounting devices (like digital cameras) that are set to UTC in order to avoid the pitfalls of local time.

- ****time_offset=minutes****

  Set offset for conversion of timestamps from local time used by FAT to UTC. I.e. &lt;minutes&gt; minutes will be subtracted from each timestamp to convert it to UTC used internally by Linux. This is useful when time zone set in `sys_tz` is not the time zone used by the filesystem. Note that this option still does not provide correct time stamps in all cases in presence of DST - time stamps in a different DST setting will be off by one hour.

- ****showexec****

  If set, the execute permission bits of the file will be allowed only if the extension part of the name is .EXE, .COM, or .BAT. Not set by default.

- ****debug****

  Can be set, but unused by the current implementation.

- ****sys_immutable****

  If set, ATTR_SYS attribute on FAT is handled as IMMUTABLE flag on Linux. Not set by default.

- ****flush****

  If set, the filesystem will try to flush to disk more early than normal. Not set by default.

- ****rodir****

  FAT has the ATTR_RO (read-only) attribute. On Windows, the ATTR_RO of the directory will just be ignored, and is used only by applications as a flag (e.g. it's set for the customized folder).

  If you want to use ATTR_RO as read-only flag even for the directory, set this option.

- ****errors=panic\|continue\|remount-ro****

  specify FAT behavior on critical errors: panic, continue without doing anything or remount the partition in read-only mode (default behavior).

- ****discard****

  If set, issues discard/TRIM commands to the block device when blocks are freed. This is useful for SSD devices and sparse/thinly-provisioned LUNs.

- ****nfs=stale_rw\|nostale_ro****

  Enable this only if you want to export the FAT filesystem over NFS.

  > **stale_rw**: This option maintains an index (cache) of directory *inodes* by *i_logstart* which is used by the nfs-related code to improve look-ups. Full file operations (read/write) over NFS is supported but with cache eviction at NFS server, this could result in ESTALE issues.
  >
  > **nostale_ro**: This option bases the *inode* number and filehandle on the on-disk location of a file in the MS-DOS directory entry. This ensures that ESTALE will not be returned after a file is evicted from the inode cache. However, it means that operations such as rename, create and unlink could cause filehandles that previously pointed at one file to point at a different file, potentially causing data corruption. For this reason, this option also mounts the filesystem readonly.

  To maintain backward compatibility, `'-o nfs'` is also accepted, defaulting to "stale_rw".

- ****dos1xfloppy  &lt;bool&gt;: 0,1,yes,no,true,false****

  If set, use a fallback default BIOS Parameter Block configuration, determined by backing device size. These static parameters match defaults assumed by DOS 1.x for 160 kiB, 180 kiB, 320 kiB, and 360 kiB floppies and floppy images.

<a id="rst-limitation"></a>

## LIMITATION

The fallocated region of file is discarded at umount/evict time when using fallocate with FALLOC_FL_KEEP_SIZE. So, User should assume that fallocated region can be discarded at last close if there is memory pressure resulting in eviction of the inode from the memory. As a result, for any dependency on the fallocated region, user should make sure to recheck fallocate after reopening the file.

<a id="rst-todo"></a>

## TODO

Need to get rid of the raw scanning stuff.  Instead, always use a get next directory entry approach.  The only thing left that uses raw scanning is the directory renaming code.

<a id="rst-possible-problems"></a>

## POSSIBLE PROBLEMS

- vfat_valid_longname does not properly checked reserved names.

- When a volume name is the same as a directory name in the root directory of the filesystem, the directory name sometimes shows up as an empty file.

- autoconv option does not work correctly.

<a id="rst-test-suite"></a>

## TEST SUITE

If you plan to make any modifications to the vfat filesystem, please get the test suite that comes with the vfat distribution at

[http://web.archive.org/web/\*/http://bmrc.berkeley.edu/people/chaffee/vfat.html](<http://web.archive.org/web/*/http://bmrc.berkeley.edu/people/chaffee/vfat.html>)<a id="rst-http-web-archive-org-web-http-bmrc-berkeley-edu-people-chaffee-vfat-html"></a>

This tests quite a few parts of the vfat filesystem and additional tests for new features or untested features would be appreciated.

<a id="rst-notes-on-the-structure-of-the-vfat-filesystem"></a>

## NOTES ON THE STRUCTURE OF THE VFAT FILESYSTEM

This documentation was provided by Galen C. Hunt [gchunt@cs.rochester.edu](<mailto:gchunt@cs.rochester.edu>) and lightly annotated by Gordon Chaffee.

This document presents a very rough, technical overview of my knowledge of the extended FAT file system used in Windows NT 3.5 and Windows 95.  I don't guarantee that any of the following is correct, but it appears to be so.

The extended FAT file system is almost identical to the FAT file system used in DOS versions up to and including *6.223410239847* :-).  The significant change has been the addition of long file names. These names support up to 255 characters including spaces and lower case characters as opposed to the traditional 8.3 short names.

Here is the description of the traditional FAT entry in the current Windows 95 filesystem:



```text
struct directory { // Short 8.3 names
        unsigned char name[8];          // file name
        unsigned char ext[3];           // file extension
        unsigned char attr;             // attribute byte
        unsigned char lcase;            // Case for base and extension
        unsigned char ctime_ms;         // Creation time, milliseconds
        unsigned char ctime[2];         // Creation time
        unsigned char cdate[2];         // Creation date
        unsigned char adate[2];         // Last access date
        unsigned char reserved[2];      // reserved values (ignored)
        unsigned char time[2];          // time stamp
        unsigned char date[2];          // date stamp
        unsigned char start[2];         // starting cluster number
        unsigned char size[4];          // size of the file
};
```

The lcase field specifies if the base and/or the extension of an 8.3 name should be capitalized.  This field does not seem to be used by Windows 95 but it is used by Windows NT.  The case of filenames is not completely compatible from Windows NT to Windows 95.  It is not completely compatible in the reverse direction, however.  Filenames that fit in the 8.3 namespace and are written on Windows NT to be lowercase will show up as uppercase on Windows 95.

> [!NOTE]
>
> Note that the `start` and `size` values are actually little endian integer values.  The descriptions of the fields in this structure are public knowledge and can be found elsewhere.

With the extended FAT system, Microsoft has inserted extra directory entries for any files with extended names.  (Any name which legally fits within the old 8.3 encoding scheme does not have extra entries.)  I call these extra entries slots.  Basically, a slot is a specially formatted directory entry which holds up to 13 characters of a file's extended name.  Think of slots as additional labeling for the directory entry of the file to which they correspond.  Microsoft prefers to refer to the 8.3 entry for a file as its alias and the extended slot directory entries as the file name.

The C structure for a slot directory entry follows:



```text
struct slot { // Up to 13 characters of a long name
        unsigned char id;               // sequence number for slot
        unsigned char name0_4[10];      // first 5 characters in name
        unsigned char attr;             // attribute byte
        unsigned char reserved;         // always 0
        unsigned char alias_checksum;   // checksum for 8.3 alias
        unsigned char name5_10[12];     // 6 more characters in name
        unsigned char start[2];         // starting cluster number
        unsigned char name11_12[4];     // last 2 characters in name
};
```

If the layout of the slots looks a little odd, it's only because of Microsoft's efforts to maintain compatibility with old software.  The slots must be disguised to prevent old software from panicking.  To this end, a number of measures are taken:

> 1. The attribute byte for a slot directory entry is always set to 0x0f.  This corresponds to an old directory entry with attributes of "hidden", "system", "read-only", and "volume label".  Most old software will ignore any directory entries with the "volume label" bit set.  Real volume label entries don't have the other three bits set.
>
> 2. The starting cluster is always set to 0, an impossible value for a DOS file.

Because the extended FAT system is backward compatible, it is possible for old software to modify directory entries.  Measures must be taken to ensure the validity of slots.  An extended FAT system can verify that a slot does in fact belong to an 8.3 directory entry by the following:

> 1. Positioning.  Slots for a file always immediately proceed their corresponding 8.3 directory entry.  In addition, each slot has an id which marks its order in the extended file name.  Here is a very abbreviated view of an 8.3 directory entry and its corresponding long name slots for the file "My Big File.Extension which is long":
>
>
>
>    ```text
>    <proceeding files...>
>    <slot #3, id = 0x43, characters = "h is long">
>    <slot #2, id = 0x02, characters = "xtension whic">
>    <slot #1, id = 0x01, characters = "My Big File.E">
>    <directory entry, name = "MYBIGFIL.EXT">
>    ```
>
>    > [!NOTE]
>    >
>    > Note that the slots are stored from last to first.  Slots are numbered from 1 to N.  The Nth slot is `or'ed` with 0x40 to mark it as the last one.
>
> 2. Checksum.  Each slot has an alias_checksum value.  The checksum is calculated from the 8.3 name using the following algorithm:
>
>
>
>    ```text
>    for (sum = i = 0; i < 11; i++) {
>            sum = (((sum&1)<<7)|((sum&0xfe)>>1)) + name[i]
>    }
>    ```
>
> 3. If there is free space in the final slot, a Unicode `NULL (0x0000)` is stored after the final character.  After that, all unused characters in the final slot are set to Unicode 0xFFFF.

Finally, note that the extended name is stored in Unicode.  Each Unicode character takes either two or four bytes, UTF-16LE encoded.

---

# Overview of the Linux Virtual File System

_Peios Kernel / Internals / Filesystems_

> Original author: Richard Gooch <rgooch@atnf.csiro.au>

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-overview-of-the-linux-virtual-file-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Original author: Richard Gooch &lt;[rgooch@atnf.csiro.au](<mailto:rgooch@atnf.csiro.au>)&gt;

- Copyright (C) 1999 Richard Gooch

- Copyright (C) 2005 Pekka Enberg

<a id="rst-introduction"></a>

## Introduction

The Virtual File System (also known as the Virtual Filesystem Switch) is the software layer in the kernel that provides the filesystem interface to userspace programs.  It also provides an abstraction within the kernel which allows different filesystem implementations to coexist.

VFS system calls open(2), stat(2), read(2), write(2), chmod(2) and so on are called from a process context.  Filesystem locking is described in the document [Documentation/filesystems/locking.rst](/kernel/internals/filesystems/locking.md).

<a id="rst-directory-entry-cache-dcache"></a>

### Directory Entry Cache (dcache)

The VFS implements the open(2), stat(2), chmod(2), and similar system calls.  The pathname argument that is passed to them is used by the VFS to search through the directory entry cache (also known as the dentry cache or dcache).  This provides a very fast look-up mechanism to translate a pathname (filename) into a specific dentry.  Dentries live in RAM and are never saved to disc: they exist only for performance.

The dentry cache is meant to be a view into your entire filespace.  As most computers cannot fit all dentries in the RAM at the same time, some bits of the cache are missing.  In order to resolve your pathname into a dentry, the VFS may have to resort to creating dentries along the way, and then loading the inode.  This is done by looking up the inode.

<a id="rst-the-inode-object"></a>

### The Inode Object

An individual dentry usually has a pointer to an inode.  Inodes are filesystem objects such as regular files, directories, FIFOs and other beasts.  They live either on the disc (for block device filesystems) or in the memory (for pseudo filesystems).  Inodes that live on the disc are copied into the memory when required and changes to the inode are written back to disc.  A single inode can be pointed to by multiple dentries (hard links, for example, do this).

To look up an inode requires that the VFS calls the lookup() method of the parent directory inode.  This method is installed by the specific filesystem implementation that the inode lives in.  Once the VFS has the required dentry (and hence the inode), we can do all those boring things like open(2) the file, or stat(2) it to peek at the inode data.  The stat(2) operation is fairly simple: once the VFS has the dentry, it peeks at the inode data and passes some of it back to userspace.

<a id="rst-the-file-object"></a>

### The File Object

Opening a file requires another operation: allocation of a file structure (this is the kernel-side implementation of file descriptors). The freshly allocated file structure is initialized with a pointer to the dentry and a set of file operation member functions.  These are taken from the inode data.  The open() file method is then called so the specific filesystem implementation can do its work.  You can see that this is another switch performed by the VFS.  The file structure is placed into the file descriptor table for the process.

Reading, writing and closing files (and other assorted VFS operations) is done by using the userspace file descriptor to grab the appropriate file structure, and then calling the required file structure method to do whatever is required.  For as long as the file is open, it keeps the dentry in use, which in turn means that the VFS inode is still in use.

<a id="rst-registering-and-mounting-a-filesystem"></a>

## Registering and Mounting a Filesystem

To register and unregister a filesystem, use the following API functions:



```c
#include <linux/fs.h>

extern int register_filesystem(struct file_system_type *);
extern int unregister_filesystem(struct file_system_type *);
```

The passed struct file_system_type describes your filesystem.  When a request is made to mount a filesystem onto a directory in your namespace, the VFS will call the appropriate get_tree() method for the specific filesystem.  See [Documentation/filesystems/mount_api.rst](/kernel/internals/filesystems/mount-api.md) for more details.

You can see all filesystems that are registered to the kernel in the file /proc/filesystems.

<a id="rst-struct-file-system-type"></a>

### struct file_system_type

This describes the filesystem.  The following members are defined:



```c
struct file_system_type {
        const char *name;
        int fs_flags;
        int (*init_fs_context)(struct fs_context *);
        const struct fs_parameter_spec *parameters;
        void (*kill_sb) (struct super_block *);
        struct module *owner;
        struct file_system_type * next;
        struct hlist_head fs_supers;

        struct lock_class_key s_lock_key;
        struct lock_class_key s_umount_key;
        struct lock_class_key s_vfs_rename_key;
        struct lock_class_key s_writers_key[SB_FREEZE_LEVELS];

        struct lock_class_key i_lock_key;
        struct lock_class_key i_mutex_key;
        struct lock_class_key invalidate_lock_key;
        struct lock_class_key i_mutex_dir_key;
};
```

- **`name`**

  the name of the filesystem type, such as "ext2", "iso9660", "msdos" and so on

- **`fs_flags`**

  various flags (i.e. FS_REQUIRES_DEV, FS_NO_DCACHE, etc.)

- **`init_fs_context`**

  Initializes 'struct fs_context' -&gt;ops and -&gt;fs_private fields with filesystem-specific data.

- **`parameters`**

  Pointer to the array of filesystem parameters descriptors 'struct fs_parameter_spec'. More info in [Documentation/filesystems/mount_api.rst](/kernel/internals/filesystems/mount-api.md).

- **`kill_sb`**

  the method to call when an instance of this filesystem should be shut down

- **`owner`**

  for internal VFS use: you should initialize this to THIS_MODULE in most cases.

- **`next`**

  for internal VFS use: you should initialize this to NULL

- **`fs_supers`**

  > for internal VFS use: hlist of filesystem instances (superblocks)

  s_lock_key, s_umount_key, s_vfs_rename_key, s_writers_key, i_lock_key, i_mutex_key, invalidate_lock_key, i_mutex_dir_key: lockdep-specific

<a id="rst-the-superblock-object"></a>

## The Superblock Object

A superblock object represents a mounted filesystem.

<a id="rst-struct-super-operations"></a>

### struct super_operations

This describes how the VFS can manipulate the superblock of your filesystem.  The following members are defined:



```c
struct super_operations {
        int (*validate_mountpoint)(struct super_block *sb,
                                  const struct path *mountpoint);
        struct inode *(*alloc_inode)(struct super_block *sb);
        void (*destroy_inode)(struct inode *);
        void (*free_inode)(struct inode *);

        void (*dirty_inode) (struct inode *, int flags);
        int (*write_inode) (struct inode *, struct writeback_control *wbc);
        int (*drop_inode) (struct inode *);
        void (*evict_inode) (struct inode *);
        void (*put_super) (struct super_block *);
        int (*sync_fs)(struct super_block *sb, int wait);
        int (*freeze_super) (struct super_block *sb,
                                enum freeze_holder who);
        int (*freeze_fs) (struct super_block *);
        int (*thaw_super) (struct super_block *sb,
                                enum freeze_wholder who);
        int (*unfreeze_fs) (struct super_block *);
        int (*statfs) (struct dentry *, struct kstatfs *);
        void (*umount_begin) (struct super_block *);

        int (*show_options)(struct seq_file *, struct dentry *);
        int (*show_devname)(struct seq_file *, struct dentry *);
        int (*show_path)(struct seq_file *, struct dentry *);
        int (*show_stats)(struct seq_file *, struct dentry *);

        ssize_t (*quota_read)(struct super_block *, int, char *, size_t, loff_t);
        ssize_t (*quota_write)(struct super_block *, int, const char *, size_t, loff_t);
        struct dquot **(*get_dquots)(struct inode *);

        long (*nr_cached_objects)(struct super_block *,
                                struct shrink_control *);
        long (*free_cached_objects)(struct super_block *,
                                struct shrink_control *);
};
```

All methods are called without any locks being held, unless otherwise noted.  This means that most methods can block safely.  All methods are only called from a process context (i.e. not from an interrupt handler or bottom half).

- **`validate_mountpoint`**

  Peios calls this optional callback before attaching a new filesystem mount, bind mount or moved mount. Return zero to accept the destination or a negative error to reject it. StrataFS uses it to reject provider/view cycles. This validation does not replace namespace authorization.

- **`alloc_inode`**

  this method is called by alloc_inode() to allocate memory for struct inode and initialize it.  If this function is not defined, a simple 'struct inode' is allocated.  Normally alloc_inode will be used to allocate a larger structure which contains a 'struct inode' embedded within it.

- **`destroy_inode`**

  this method is called by destroy_inode() to release resources allocated for struct inode.  It is only required if -&gt;alloc_inode was defined and simply undoes anything done by -&gt;alloc_inode.

- **`free_inode`**

  this method is called from RCU callback. If you use call_rcu() in -&gt;destroy_inode to free 'struct inode' memory, then it's better to release memory in this method.

- **`dirty_inode`**

  this method is called by the VFS when an inode is marked dirty. This is specifically for the inode itself being marked dirty, not its data.  If the update needs to be persisted by fdatasync(), then I_DIRTY_DATASYNC will be set in the flags argument. I_DIRTY_TIME will be set in the flags in case lazytime is enabled and struct inode has times updated since the last -&gt;dirty_inode call.

- **`write_inode`**

  this method is called when the VFS needs to write an inode to disc.  The second parameter indicates whether the write should be synchronous or not, not all filesystems check this flag.

- **`drop_inode`**

  called when the last access to the inode is dropped, with the inode-&gt;i_lock spinlock held.

  This method should be either NULL (normal UNIX filesystem semantics) or "inode_just_drop" (for filesystems that do not want to cache inodes - causing "delete_inode" to always be called regardless of the value of i_nlink)

  The "inode_just_drop()" behavior is equivalent to the old practice of using "force_delete" in the put_inode() case, but does not have the races that the "force_delete()" approach had.

- **`evict_inode`**

  called when the VFS wants to evict an inode. Caller does *not* evict the pagecache or inode-associated metadata buffers; the method has to use truncate_inode_pages_final() to get rid of those. Caller makes sure async writeback cannot be running for the inode while (or after) -&gt;evict_inode() is called. Optional.

- **`put_super`**

  called when the VFS wishes to free the superblock (i.e. unmount).  This is called with the superblock lock held

- **`sync_fs`**

  called when VFS is writing out all dirty data associated with a superblock.  The second parameter indicates whether the method should wait until the write out has been completed.  Optional.

- **`freeze_super`**

  Called instead of -&gt;freeze_fs callback if provided. Main difference is that -&gt;freeze_super is called without taking down_write(&amp;sb-&gt;s_umount). If filesystem implements it and wants -&gt;freeze_fs to be called too, then it has to call -&gt;freeze_fs explicitly from this callback. Optional.

- **`freeze_fs`**

  called when VFS is locking a filesystem and forcing it into a consistent state.  This method is currently used by the Logical Volume Manager (LVM) and ioctl(FIFREEZE). Optional.

- **`thaw_super`**

  called when VFS is unlocking a filesystem and making it writable again after -&gt;freeze_super. Optional.

- **`unfreeze_fs`**

  called when VFS is unlocking a filesystem and making it writable again after -&gt;freeze_fs. Optional.

- **`statfs`**

  called when the VFS needs to get filesystem statistics.

- **`umount_begin`**

  called when the VFS is unmounting a filesystem.

- **`show_options`**

  called by the VFS to show mount options for /proc/&lt;pid&gt;/mounts and /proc/&lt;pid&gt;/mountinfo. (see "Mount Options" section)

- **`show_devname`**

  Optional. Called by the VFS to show device name for /proc/&lt;pid&gt;/\{mounts,mountinfo,mountstats\}. If not provided then '(struct mount).mnt_devname' will be used.

- **`show_path`**

  Optional. Called by the VFS (for /proc/&lt;pid&gt;/mountinfo) to show the mount root dentry path relative to the filesystem root.

- **`show_stats`**

  Optional. Called by the VFS (for /proc/&lt;pid&gt;/mountstats) to show filesystem-specific mount statistics.

- **`quota_read`**

  called by the VFS to read from filesystem quota file.

- **`quota_write`**

  called by the VFS to write to filesystem quota file.

- **`get_dquots`**

  called by quota to get 'struct dquot' array for a particular inode. Optional.

- **`nr_cached_objects`**

  called by the sb cache shrinking function for the filesystem to return the number of freeable cached objects it contains. Optional.

- **`free_cache_objects`**

  called by the sb cache shrinking function for the filesystem to scan the number of objects indicated to try to free them. Optional, but any filesystem implementing this method needs to also implement -&gt;nr_cached_objects for it to be called correctly.

  We can't do anything with any errors that the filesystem might encountered, hence the void return type.  This will never be called if the VM is trying to reclaim under GFP_NOFS conditions, hence this method does not need to handle that situation itself.

  Implementations must include conditional reschedule calls inside any scanning loop that is done.  This allows the VFS to determine appropriate scan batch sizes without having to worry about whether implementations will cause holdoff problems due to large scan batch sizes.

Whoever sets up the inode is responsible for filling in the "i_op" field.  This is a pointer to a "struct inode_operations" which describes the methods that can be performed on individual inodes.

<a id="rst-struct-xattr-handler"></a>

### struct xattr_handler

On filesystems that support extended attributes (xattrs), the s_xattr superblock field points to a NULL-terminated array of xattr handlers. Extended attributes are name:value pairs.

- **`name`**

  Indicates that the handler matches attributes with the specified name (such as "system.posix_acl_access"); the prefix field must be NULL.

- **`prefix`**

  Indicates that the handler matches all attributes with the specified name prefix (such as "user."); the name field must be NULL.

- **`list`**

  Determine if attributes matching this xattr handler should be listed for a particular dentry.  Used by some listxattr implementations like generic_listxattr.

- **`get`**

  Called by the VFS to get the value of a particular extended attribute.  This method is called by the getxattr(2) system call.

- **`set`**

  Called by the VFS to set the value of a particular extended attribute.  When the new value is NULL, called to remove a particular extended attribute.  This method is called by the setxattr(2) and removexattr(2) system calls.

When none of the xattr handlers of a filesystem match the specified attribute name or when a filesystem doesn't support extended attributes, the various `*xattr(2)` system calls return -EOPNOTSUPP.

<a id="rst-the-inode-object-1"></a>

## The Inode Object

An inode object represents an object within the filesystem.

<a id="rst-struct-inode-operations"></a>

### struct inode_operations

This describes how the VFS can manipulate an inode in your filesystem. As of kernel 2.6.22, the following members are defined:



```c
struct inode_operations {
        int (*create) (struct mnt_idmap *, struct inode *,struct dentry *, umode_t, bool);
        struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
        int (*link) (struct dentry *,struct inode *,struct dentry *);
        int (*unlink) (struct inode *,struct dentry *);
        int (*symlink) (struct mnt_idmap *, struct inode *,struct dentry *,const char *);
        struct dentry *(*mkdir) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t);
        int (*rmdir) (struct inode *,struct dentry *);
        int (*mknod) (struct mnt_idmap *, struct inode *,struct dentry *,umode_t,dev_t);
        int (*rename) (struct mnt_idmap *, struct inode *, struct dentry *,
                       struct inode *, struct dentry *, unsigned int);
        int (*readlink) (struct dentry *, char __user *,int);
        const char *(*get_link) (struct dentry *, struct inode *,
                                 struct delayed_call *);
        int (*permission) (struct mnt_idmap *, struct inode *, int);
        struct posix_acl * (*get_inode_acl)(struct inode *, int, bool);
        int (*setattr) (struct mnt_idmap *, struct dentry *, struct iattr *);
        int (*getattr) (struct mnt_idmap *, const struct path *, struct kstat *, u32, unsigned int);
        ssize_t (*listxattr) (struct dentry *, char *, size_t);
        void (*update_time)(struct inode *inode, enum fs_update_time type,
                            int flags);
        void (*sync_lazytime)(struct inode *inode);
        int (*atomic_open)(struct inode *, struct dentry *, struct file *,
                           unsigned open_flag, umode_t create_mode);
        int (*tmpfile) (struct mnt_idmap *, struct inode *, struct file *, umode_t);
        struct posix_acl * (*get_acl)(struct mnt_idmap *, struct dentry *, int);
        int (*set_acl)(struct mnt_idmap *, struct dentry *, struct posix_acl *, int);
        int (*fileattr_set)(struct mnt_idmap *idmap,
                            struct dentry *dentry, struct file_kattr *fa);
        int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
        struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
};
```

Again, all methods are called without any locks being held, unless otherwise noted.

- **`create`**

  called by the open(2) and creat(2) system calls.  Only required if you want to support regular files.  The dentry you get should not have an inode (i.e. it should be a negative dentry).  Here you will probably call d_instantiate() with the dentry and the newly created inode

- **`lookup`**

  called when the VFS needs to look up an inode in a parent directory.  The name to look for is found in the dentry.  This method must call d_add() to insert the found inode into the dentry.  The "i_count" field in the inode structure should be incremented.  If the named inode does not exist a NULL inode should be inserted into the dentry (this is called a negative dentry).  Returning an error code from this routine must only be done on a real error, otherwise creating inodes with system calls like create(2), mknod(2), mkdir(2) and so on will fail. If you wish to overload the dentry methods then you should initialise the "d_dop" field in the dentry; this is a pointer to a struct "dentry_operations".  This method is called with the directory inode semaphore held

- **`link`**

  called by the link(2) system call.  Only required if you want to support hard links.  You will probably need to call d_instantiate() just as you would in the create() method

- **`unlink`**

  called by the unlink(2) system call.  Only required if you want to support deleting inodes

- **`symlink`**

  called by the symlink(2) system call.  Only required if you want to support symlinks.  You will probably need to call d_instantiate() just as you would in the create() method

- **`mkdir`**

  called by the mkdir(2) system call.  Only required if you want to support creating subdirectories.  You will probably need to call d_instantiate_new() just as you would in the create() method.

  If d_instantiate_new() is not used and if the fh_to_dentry() export operation is provided, or if the storage might be accessible by another path (e.g. with a network filesystem) then more care may be needed.  Importantly d_instantate() should not be used with an inode that is no longer I_NEW if there any chance that the inode could already be attached to a dentry. This is because of a hard rule in the VFS that a directory must only ever have one dentry.

  For example, if an NFS filesystem is mounted twice the new directory could be visible on the other mount before it is on the original mount, and a pair of name_to_handle_at(), open_by_handle_at() calls could instantiate the directory inode with an IS_ROOT() dentry before the first mkdir returns.

  If there is any chance this could happen, then the new inode should be d_drop()ed and attached with d_splice_alias().  The returned dentry (if any) should be returned by -&gt;mkdir().

- **`rmdir`**

  called by the rmdir(2) system call.  Only required if you want to support deleting subdirectories

- **`mknod`**

  called by the mknod(2) system call to create a device (char, block) inode or a named pipe (FIFO) or socket.  Only required if you want to support creating these types of inodes.  You will probably need to call d_instantiate() just as you would in the create() method

- **`rename`**

  called by the rename(2) system call to rename the object to have the parent and name given by the second inode and dentry.

  The filesystem must return -EINVAL for any unsupported or unknown flags.  Currently the following flags are implemented: (1) RENAME_NOREPLACE: this flag indicates that if the target of the rename exists the rename should fail with -EEXIST instead of replacing the target.  The VFS already checks for existence, so for local filesystems the RENAME_NOREPLACE implementation is equivalent to plain rename. (2) RENAME_EXCHANGE: exchange source and target.  Both must exist; this is checked by the VFS.  Unlike plain rename, source and target may be of different type.

- **`get_link`**

  called by the VFS to follow a symbolic link to the inode it points to.  Only required if you want to support symbolic links. This method returns the symlink body to traverse (and possibly resets the current position with nd_jump_link()).  If the body won't go away until the inode is gone, nothing else is needed; if it needs to be otherwise pinned, arrange for its release by having get_link(..., ..., done) do set_delayed_call(done, destructor, argument).  In that case destructor(argument) will be called once VFS is done with the body you've returned.  May be called in RCU mode; that is indicated by NULL dentry argument.  If request can't be handled without leaving RCU mode, have it return ERR_PTR(-ECHILD).

  If the filesystem stores the symlink target in -&gt;i_link, the VFS may use it directly without calling -&gt;get_link(); however, -&gt;get_link() must still be provided.  -&gt;i_link must not be freed until after an RCU grace period.  Writing to -&gt;i_link post-iget() time requires a 'release' memory barrier.

- **`readlink`**

  this is now just an override for use by readlink(2) for the cases when -&gt;get_link uses nd_jump_link() or object is not in fact a symlink.  Normally filesystems should only implement -&gt;get_link for symlinks and readlink(2) will automatically use that.

- **`permission`**

  called by the VFS to check for access rights on a POSIX-like filesystem.

  May be called in rcu-walk mode (mask &amp; MAY_NOT_BLOCK).  If in rcu-walk mode, the filesystem must check the permission without blocking or storing to the inode.

  If a situation is encountered that rcu-walk cannot handle, return -ECHILD and it will be called again in ref-walk mode.

- **`setattr`**

  called by the VFS to set attributes for a file.  This method is called by chmod(2) and related system calls.

- **`getattr`**

  called by the VFS to get attributes of a file.  This method is called by stat(2) and related system calls.

- **`listxattr`**

  called by the VFS to list all extended attributes for a given file.  This method is called by the listxattr(2) system call.

- **`update_time`**

  called by the VFS to update a specific time or the i_version of an inode.  If this is not defined the VFS will update the inode itself and call mark_inode_dirty_sync.

- **`sync_lazytime`:**

  called by the writeback code to update the lazy time stamps to regular time stamp updates that get syncing into the on-disk inode.

- **`atomic_open`**

  called on the last component of an open.  Using this optional method the filesystem can look up, possibly create and open the file in one atomic operation.  If it wants to leave actual opening to the caller (e.g. if the file turned out to be a symlink, device, or just something filesystem won't do atomic open for), it may signal this by returning finish_no_open(file, dentry).  This method is only called if the last component is negative or needs lookup.  Cached positive dentries are still handled by f_op-&gt;open().  If the file was created, FMODE_CREATED flag should be set in file-&gt;f_mode.  In case of O_EXCL the method must only succeed if the file didn't exist and hence FMODE_CREATED shall always be set on success.

- **`tmpfile`**

  called in the end of O_TMPFILE open().  Optional, equivalent to atomically creating, opening and unlinking a file in given directory.  On success needs to return with the file already open; this can be done by calling finish_open_simple() right at the end.

- **`fileattr_get`**

  called on ioctl(FS_IOC_GETFLAGS) and ioctl(FS_IOC_FSGETXATTR) to retrieve miscellaneous file flags and attributes.  Also called before the relevant SET operation to check what is being changed (in this case with i_rwsem locked exclusive).  If unset, then fall back to f_op-&gt;ioctl().

- **`fileattr_set`**

  called on ioctl(FS_IOC_SETFLAGS) and ioctl(FS_IOC_FSSETXATTR) to change miscellaneous file flags and attributes.  Callers hold i_rwsem exclusive.  If unset, then fall back to f_op-&gt;ioctl().

- **`get_offset_ctx`**

  called to get the offset context for a directory inode. A filesystem must define this operation to use simple_offset_dir_operations.

<a id="rst-the-address-space-object"></a>

## The Address Space Object

The address space object is used to group and manage pages in the page cache.  It can be used to keep track of the pages in a file (or anything else) and also track the mapping of sections of the file into process address spaces.

There are a number of distinct yet related services that an address-space can provide.  These include communicating memory pressure, page lookup by address, and keeping track of pages tagged as Dirty or Writeback.

The first can be used independently to the others.  The VM can try to release clean pages in order to reuse them.  To do this it can call -&gt;release_folio on clean folios with the private flag set.  Clean pages without PagePrivate and with no external references will be released without notice being given to the address_space.

To achieve this functionality, pages need to be placed on an LRU with lru_cache_add and mark_page_active needs to be called whenever the page is used.

Pages are normally kept in a radix tree index by -&gt;index.  This tree maintains information about the PG_Dirty and PG_Writeback status of each page, so that pages with either of these flags can be found quickly.

The Dirty tag is primarily used by mpage_writepages - the default -&gt;writepages method.  It uses the tag to find dirty pages to write back.  If mpage_writepages is not used (i.e. the address provides its own -&gt;writepages) , the PAGECACHE_TAG_DIRTY tag is almost unused.  write_inode_now and sync_inode do use it (through \__sync_single_inode) to check if -&gt;writepages has been successful in writing out the whole address_space.

The Writeback tag is used by filemap\*wait\* and sync_page\* functions, via filemap_fdatawait_range, to wait for all writeback to complete.

An address_space handler may attach extra information to a page, typically using the 'private' field in the 'struct page'.  If such information is attached, the PG_Private flag should be set.  This will cause various VM routines to make extra calls into the address_space handler to deal with that data.

An address space acts as an intermediate between storage and application.  Data is read into the address space a whole page at a time, and provided to the application either by copying of the page, or by memory-mapping the page.  Data is written into the address space by the application, and then written-back to storage typically in whole pages, however the address_space has finer control of write sizes.

The read process essentially only requires 'read_folio'.  The write process is more complicated and uses write_begin/write_end or dirty_folio to write data into the address_space, and writepages to writeback data to storage.

Removing pages from an address_space requires holding the inode's i_rwsem exclusively, while adding pages to the address_space requires holding the inode's i_mapping-&gt;invalidate_lock exclusively.

When data is written to a page, the PG_Dirty flag should be set.  It typically remains set until writepages asks for it to be written.  This should clear PG_Dirty and set PG_Writeback.  It can be actually written at any point after PG_Dirty is clear.  Once it is known to be safe, PG_Writeback is cleared.

Writeback makes use of a writeback_control structure to direct the operations.  This gives the writepages operation some information about the nature of and reason for the writeback request, and the constraints under which it is being done.  It is also used to return information back to the caller about the result of a writepages request.

<a id="rst-handling-errors-during-writeback"></a>

### Handling errors during writeback

Most applications that do buffered I/O will periodically call a file synchronization call (fsync, fdatasync, msync or sync_file_range) to ensure that data written has made it to the backing store.  When there is an error during writeback, they expect that error to be reported when a file sync request is made.  After an error has been reported on one request, subsequent requests on the same file descriptor should return 0, unless further writeback errors have occurred since the previous file synchronization.

Ideally, the kernel would report errors only on file descriptions on which writes were done that subsequently failed to be written back.  The generic pagecache infrastructure does not track the file descriptions that have dirtied each individual page however, so determining which file descriptors should get back an error is not possible.

Instead, the generic writeback error tracking infrastructure in the kernel settles for reporting errors to fsync on all file descriptions that were open at the time that the error occurred.  In a situation with multiple writers, all of them will get back an error on a subsequent fsync, even if all of the writes done through that particular file descriptor succeeded (or even if there were no writes on that file descriptor at all).

Filesystems that wish to use this infrastructure should call mapping_set_error to record the error in the address_space when it occurs.  Then, after writing back data from the pagecache in their file-&gt;fsync operation, they should call file_check_and_advance_wb_err to ensure that the struct file's error cursor has advanced to the correct point in the stream of errors emitted by the backing device(s).

<a id="rst-struct-address-space-operations"></a>

### struct address_space_operations

This describes how the VFS can manipulate mapping of a file to page cache in your filesystem.  The following members are defined:



```c
struct address_space_operations {
        int (*read_folio)(struct file *, struct folio *);
        int (*writepages)(struct address_space *, struct writeback_control *);
        bool (*dirty_folio)(struct address_space *, struct folio *);
        void (*readahead)(struct readahead_control *);
        int (*write_begin)(const struct kiocb *, struct address_space *mapping,
                           loff_t pos, unsigned len,
                           struct page **pagep, void **fsdata);
        int (*write_end)(const struct kiocb *, struct address_space *mapping,
                         loff_t pos, unsigned len, unsigned copied,
                         struct folio *folio, void *fsdata);
        sector_t (*bmap)(struct address_space *, sector_t);
        void (*invalidate_folio) (struct folio *, size_t start, size_t len);
        bool (*release_folio)(struct folio *, gfp_t);
        void (*free_folio)(struct folio *);
        ssize_t (*direct_IO)(struct kiocb *, struct iov_iter *iter);
        int (*migrate_folio)(struct mapping *, struct folio *dst,
                        struct folio *src, enum migrate_mode);
        int (*launder_folio) (struct folio *);

        bool (*is_partially_uptodate) (struct folio *, size_t from,
                                       size_t count);
        void (*is_dirty_writeback)(struct folio *, bool *, bool *);
        int (*error_remove_folio)(struct mapping *mapping, struct folio *);
        int (*swap_activate)(struct swap_info_struct *sis, struct file *f, sector_t *span)
        int (*swap_deactivate)(struct file *);
        int (*swap_rw)(struct kiocb *iocb, struct iov_iter *iter);
};
```

- **`read_folio`**

  Called by the page cache to read a folio from the backing store. The 'file' argument supplies authentication information to network filesystems, and is generally not used by block based filesystems. It may be NULL if the caller does not have an open file (eg if the kernel is performing a read for itself rather than on behalf of a userspace process with an open file).

  If the mapping does not support large folios, the folio will contain a single page.  The folio will be locked when read_folio is called.  If the read completes successfully, the folio should be marked uptodate.  The filesystem should unlock the folio once the read has completed, whether it was successful or not. The filesystem does not need to modify the refcount on the folio; the page cache holds a reference count and that will not be released until the folio is unlocked.

  Filesystems may implement -&gt;read_folio() synchronously. In normal operation, folios are read through the -&gt;readahead() method.  Only if this fails, or if the caller needs to wait for the read to complete will the page cache call -&gt;read_folio(). Filesystems should not attempt to perform their own readahead in the -&gt;read_folio() operation.

  If the filesystem cannot perform the read at this time, it can unlock the folio, do whatever action it needs to ensure that the read will succeed in the future and return AOP_TRUNCATED_PAGE. In this case, the caller should look up the folio, lock it, and call -&gt;read_folio again.

  Callers may invoke the -&gt;read_folio() method directly, but using read_mapping_folio() will take care of locking, waiting for the read to complete and handle cases such as AOP_TRUNCATED_PAGE.

- **`writepages`**

  called by the VM to write out pages associated with the address_space object.  If wbc-&gt;sync_mode is WB_SYNC_ALL, then the writeback_control will specify a range of pages that must be written out.  If it is WB_SYNC_NONE, then a nr_to_write is given and that many pages should be written if possible.  If no -&gt;writepages is given, then mpage_writepages is used instead. This will choose pages from the address space that are tagged as DIRTY and will write them back.

- **`dirty_folio`**

  called by the VM to mark a folio as dirty.  This is particularly needed if an address space attaches private data to a folio, and that data needs to be updated when a folio is dirtied.  This is called, for example, when a memory mapped page gets modified. If defined, it should set the folio dirty flag, and the PAGECACHE_TAG_DIRTY search mark in i_pages.

- **`readahead`**

  Called by the VM to read pages associated with the address_space object.  The pages are consecutive in the page cache and are locked.  The implementation should decrement the page refcount after starting I/O on each page.  Usually the page will be unlocked by the I/O completion handler.  The set of pages are divided into some sync pages followed by some async pages, rac-&gt;ra-&gt;async_size gives the number of async pages.  The filesystem should attempt to read all sync pages but may decide to stop once it reaches the async pages.  If it does decide to stop attempting I/O, it can simply return.  The caller will remove the remaining pages from the address space, unlock them and decrement the page refcount.  Set PageUptodate if the I/O completes successfully.

- **`write_begin`**

  Called by the generic buffered write code to ask the filesystem to prepare to write len bytes at the given offset in the file. The address_space should check that the write will be able to complete, by allocating space if necessary and doing any other internal housekeeping.  If the write will update parts of any basic-blocks on storage, then those blocks should be pre-read (if they haven't been read already) so that the updated blocks can be written out properly.

  The filesystem must return the locked pagecache folio for the specified offset, in `*foliop`, for the caller to write into.

  It must be able to cope with short writes (where the length passed to write_begin is greater than the number of bytes copied into the folio).

  A void \* may be returned in fsdata, which then gets passed into write_end.

  Returns 0 on success; &lt; 0 on failure (which is the error code), in which case write_end is not called.

- **`write_end`**

  After a successful write_begin, and data copy, write_end must be called.  len is the original len passed to write_begin, and copied is the amount that was able to be copied.

  The filesystem must take care of unlocking the folio, decrementing its refcount, and updating i_size.

  Returns &lt; 0 on failure, otherwise the number of bytes (&lt;= 'copied') that were able to be copied into pagecache.

- **`bmap`**

  called by the VFS to map a logical block offset within object to physical block number.  This method is used by the FIBMAP ioctl and for working with swap-files.  To be able to swap to a file, the file must have a stable mapping to a block device.  The swap system does not go through the filesystem but instead uses bmap to find out where the blocks in the file are and uses those addresses directly.

- **`invalidate_folio`**

  If a folio has private data, then invalidate_folio will be called when part or all of the folio is to be removed from the address space.  This generally corresponds to either a truncation, punch hole or a complete invalidation of the address space (in the latter case 'offset' will always be 0 and 'length' will be folio_size()).  Any private data associated with the folio should be updated to reflect this truncation.  If offset is 0 and length is folio_size(), then the private data should be released, because the folio must be able to be completely discarded.  This may be done by calling the -&gt;release_folio function, but in this case the release MUST succeed.

- **`release_folio`**

  release_folio is called on folios with private data to tell the filesystem that the folio is about to be freed.  -&gt;release_folio should remove any private data from the folio and clear the private flag.  If release_folio() fails, it should return false. release_folio() is used in two distinct though related cases. The first is when the VM wants to free a clean folio with no active users.  If -&gt;release_folio succeeds, the folio will be removed from the address_space and be freed.

  The second case is when a request has been made to invalidate some or all folios in an address_space.  This can happen through the fadvise(POSIX_FADV_DONTNEED) system call or by the filesystem explicitly requesting it as nfs and 9p do (when they believe the cache may be out of date with storage) by calling invalidate_inode_pages2().  If the filesystem makes such a call, and needs to be certain that all folios are invalidated, then its release_folio will need to ensure this.  Possibly it can clear the uptodate flag if it cannot free private data yet.

- **`free_folio`**

  free_folio is called once the folio is no longer visible in the page cache in order to allow the cleanup of any private data. Since it may be called by the memory reclaimer, it should not assume that the original address_space mapping still exists, and it should not block.

- **`direct_IO`**

  called by the generic read/write routines to perform direct_IO - that is IO requests which bypass the page cache and transfer data directly between the storage and the application's address space.

- **`migrate_folio`**

  This is used to compact the physical memory usage.  If the VM wants to relocate a folio (maybe from a memory device that is signalling imminent failure) it will pass a new folio and an old folio to this function.  migrate_folio should transfer any private data across and update any references that it has to the folio.

- **`launder_folio`**

  Called before freeing a folio - it writes back the dirty folio. To prevent redirtying the folio, it is kept locked during the whole operation.

- **`is_partially_uptodate`**

  Called by the VM when reading a file through the pagecache when the underlying blocksize is smaller than the size of the folio. If the required block is up to date then the read can complete without needing I/O to bring the whole page up to date.

- **`is_dirty_writeback`**

  Called by the VM when attempting to reclaim a folio.  The VM uses dirty and writeback information to determine if it needs to stall to allow flushers a chance to complete some IO. Ordinarily it can use folio_test_dirty and folio_test_writeback but some filesystems have more complex state (unstable folios in NFS prevent reclaim) or do not set those flags due to locking problems.  This callback allows a filesystem to indicate to the VM if a folio should be treated as dirty or writeback for the purposes of stalling.

- **`error_remove_folio`**

  normally set to generic_error_remove_folio if truncation is ok for this address space.  Used for memory failure handling. Setting this implies you deal with pages going away under you, unless you have them locked or reference counts increased.

`swap_activate`

> Called to prepare the given file for swap.  It should perform any validation and preparation necessary to ensure that writes can be performed with minimal memory allocation.  It should call add_swap_extent(), or the helper iomap_swapfile_activate(), and return the number of extents added.  If IO should be submitted through -&gt;swap_rw(), it should set SWP_FS_OPS, otherwise IO will be submitted directly to the block device `sis->bdev`.

- **`swap_deactivate`**

  Called during swapoff on files where swap_activate was successful.

- **`swap_rw`**

  Called to read or write swap pages when SWP_FS_OPS is set.

<a id="rst-the-file-object-1"></a>

## The File Object

A file object represents a file opened by a process.  This is also known as an "open file description" in POSIX parlance.

<a id="rst-struct-file-operations"></a>

### struct file_operations

This describes how the VFS can manipulate an open file.  As of kernel 4.18, the following members are defined:



```c
struct file_operations {
        struct module *owner;
        fop_flags_t fop_flags;
        loff_t (*llseek) (struct file *, loff_t, int);
        ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
        ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
        ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
        ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
        int (*iopoll)(struct kiocb *kiocb, struct io_comp_batch *,
                        unsigned int flags);
        int (*iterate_shared) (struct file *, struct dir_context *);
        __poll_t (*poll) (struct file *, struct poll_table_struct *);
        long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
        long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
        int (*mmap) (struct file *, struct vm_area_struct *);
        int (*open) (struct inode *, struct file *);
        int (*flush) (struct file *, fl_owner_t id);
        int (*release) (struct inode *, struct file *);
        int (*fsync) (struct file *, loff_t, loff_t, int datasync);
        int (*fasync) (int, struct file *, int);
        int (*lock) (struct file *, int, struct file_lock *);
        unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
        int (*check_flags)(int);
        int (*flock) (struct file *, int, struct file_lock *);
        ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
        ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
        void (*splice_eof)(struct file *file);
        int (*setlease)(struct file *, int, struct file_lease **, void **);
        int (*getlease)(struct file *file, struct file *lease_file,
                        unsigned int flavor);
        long (*fallocate)(struct file *file, int mode, loff_t offset,
                          loff_t len);
        void (*show_fdinfo)(struct seq_file *m, struct file *f);
#ifndef CONFIG_MMU
        unsigned (*mmap_capabilities)(struct file *);
#endif
        ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
                        loff_t, size_t, unsigned int);
        loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
                                   struct file *file_out, loff_t pos_out,
                                   loff_t len, unsigned int remap_flags);
        int (*fadvise)(struct file *, loff_t, loff_t, int);
        int (*uring_cmd)(struct io_uring_cmd *ioucmd, unsigned int issue_flags);
        int (*uring_cmd_iopoll)(struct io_uring_cmd *, struct io_comp_batch *,
                                unsigned int poll_flags);
        int (*mmap_prepare)(struct vm_area_desc *);
};
```

Again, all methods are called without any locks being held, unless otherwise noted.

- **`llseek`**

  called when the VFS needs to move the file position index

- **`read`**

  called by read(2) and related system calls

- **`read_iter`**

  possibly asynchronous read with iov_iter as destination

- **`write`**

  called by write(2) and related system calls

- **`write_iter`**

  possibly asynchronous write with iov_iter as source

- **`iopoll`**

  called when aio wants to poll for completions on HIPRI iocbs

- **`iterate_shared`**

  called when the VFS needs to read the directory contents

- **`poll`**

  called by the VFS when a process wants to check if there is activity on this file and (optionally) go to sleep until there is activity.  Called by the select(2) and poll(2) system calls

- **`unlocked_ioctl`**

  called by the ioctl(2) system call.

- **`compat_ioctl`**

  - **called by the ioctl(2) system call when 32 bit system calls are**

    used on 64 bit kernels.

- **`mmap`**

  called by the mmap(2) system call. Deprecated in favour of `mmap_prepare`.

- **`open`**

  called by the VFS when an inode should be opened.  When the VFS opens a file, it creates a new "struct file".  It then calls the open method for the newly allocated file structure.  You might think that the open method really belongs in "struct inode_operations", and you may be right.  I think it's done the way it is because it makes filesystems simpler to implement. The open() method is a good place to initialize the "private_data" member in the file structure if you want to point to a device structure

- **`flush`**

  called by the close(2) system call to flush a file

- **`release`**

  called when the last reference to an open file is closed

- **`fsync`**

  called by the fsync(2) system call.  Also see the section above entitled "Handling errors during writeback".

- **`fasync`**

  called by the fcntl(2) system call when asynchronous (non-blocking) mode is enabled for a file

- **`lock`**

  called by the fcntl(2) system call for F_GETLK, F_SETLK, and F_SETLKW commands

- **`get_unmapped_area`**

  called by the mmap(2) system call

- **`check_flags`**

  called by the fcntl(2) system call for F_SETFL command

- **`flock`**

  called by the flock(2) system call

- **`splice_write`**

  called by the VFS to splice data from a pipe to a file.  This method is used by the splice(2) system call

- **`splice_read`**

  called by the VFS to splice data from file to a pipe.  This method is used by the splice(2) system call

- **`setlease`**

  called by the VFS to set or release a file lock lease.  Local filesystems that wish to use the kernel-internal lease implementation should set this to generic_setlease(). Other setlease implementations should call generic_setlease() to record or remove the lease in the inode after setting it. When set to NULL, attempts to set or remove a lease will return -EINVAL.

- **`getlease`**

  Peios calls this optional method through `kernel_getlease()` for lease or delegation queries. `file` identifies the current backing file, while `lease_file` preserves the lease owner identity when forwarding through a layered filesystem. `flavor` is `FL_LEASE` or `FL_DELEG`. Return the lock type or a negative error. Without the method, the VFS queries its generic lease state. StrataFS forwards queries across its backing-file transitions.

- **`fallocate`**

  called by the VFS to preallocate blocks or punch a hole.

- **`copy_file_range`**

  called by the copy_file_range(2) system call.

- **`remap_file_range`**

  called by the ioctl(2) system call for FICLONERANGE and FICLONE and FIDEDUPERANGE commands to remap file ranges.  An implementation should remap len bytes at pos_in of the source file into the dest file at pos_out.  Implementations must handle callers passing in len == 0; this means "remap to the end of the source file".  The return value should the number of bytes remapped, or the usual negative error code if errors occurred before any bytes were remapped.  The remap_flags parameter accepts REMAP_FILE\_\* flags.  If REMAP_FILE_DEDUP is set then the implementation must only remap if the requested file ranges have identical contents.  If REMAP_FILE_CAN_SHORTEN is set, the caller is ok with the implementation shortening the request length to satisfy alignment or EOF requirements (or any other reason).

- **`fadvise`**

  possibly called by the fadvise64() system call.

- **`mmap_prepare`**

  Called by the mmap(2) system call. Allows a VFS to set up a file-backed memory mapping, most notably establishing relevant private state and VMA callbacks.

  If further action such as pre-population of page tables is required, this can be specified by the vm_area_desc-&gt;action field and related parameters.

Note that the file operations are implemented by the specific filesystem in which the inode resides.  When opening a device node (character or block special) most filesystems will call special support routines in the VFS which will locate the required device driver information.  These support routines replace the filesystem file operations with those for the device driver, and then proceed to call the new open() method for the file.  This is how opening a device file in the filesystem eventually ends up calling the device driver open() method.

<a id="rst-directory-entry-cache-dcache-1"></a>

## Directory Entry Cache (dcache)

<a id="rst-struct-dentry-operations"></a>

### struct dentry_operations

This describes how a filesystem can overload the standard dentry operations.  Dentries and the dcache are the domain of the VFS and the individual filesystem implementations.  Device drivers have no business here.  These methods may be set to NULL, as they are either optional or the VFS uses a default.  As of kernel 2.6.22, the following members are defined:



```c
struct dentry_operations {
        int (*d_revalidate)(struct inode *, const struct qstr *,
                            struct dentry *, unsigned int);
        int (*d_weak_revalidate)(struct dentry *, unsigned int);
        int (*d_hash)(const struct dentry *, struct qstr *);
        int (*d_compare)(const struct dentry *,
                         unsigned int, const char *, const struct qstr *);
        int (*d_delete)(const struct dentry *);
        int (*d_init)(struct dentry *);
        void (*d_release)(struct dentry *);
        void (*d_iput)(struct dentry *, struct inode *);
        char *(*d_dname)(struct dentry *, char *, int);
        struct vfsmount *(*d_automount)(struct path *);
        int (*d_manage)(const struct path *, bool);
        struct dentry *(*d_real)(struct dentry *, enum d_real_type type);
        bool (*d_unalias_trylock)(const struct dentry *);
        void (*d_unalias_unlock)(const struct dentry *);
};
```

- **`d_revalidate`**

  called when the VFS needs to revalidate a dentry.  This is called whenever a name look-up finds a dentry in the dcache. Most local filesystems leave this as NULL, because all their dentries in the dcache are valid.  Network filesystems are different since things can change on the server without the client necessarily being aware of it.

  This function should return a positive value if the dentry is still valid, and zero or a negative error code if it isn't.

  d_revalidate may be called in rcu-walk mode (flags &amp; LOOKUP_RCU).  If in rcu-walk mode, the filesystem must revalidate the dentry without blocking or storing to the dentry, d_parent and d_inode should not be used without care (because they can change and, in d_inode case, even become NULL under us).

  If a situation is encountered that rcu-walk cannot handle, return -ECHILD and it will be called again in ref-walk mode.

- **`d_weak_revalidate`**

  called when the VFS needs to revalidate a "jumped" dentry.  This is called when a path-walk ends at dentry that was not acquired by doing a lookup in the parent directory.  This includes "/", "." and "..", as well as procfs-style symlinks and mountpoint traversal.

  In this case, we are less concerned with whether the dentry is still fully correct, but rather that the inode is still valid. As with d_revalidate, most local filesystems will set this to NULL since their dcache entries are always valid.

  This function has the same return code semantics as d_revalidate.

  d_weak_revalidate is only called after leaving rcu-walk mode.

- **`d_hash`**

  called when the VFS adds a dentry to the hash table.  The first dentry passed to d_hash is the parent directory that the name is to be hashed into.

  Same locking and synchronisation rules as d_compare regarding what is safe to dereference etc.

- **`d_compare`**

  called to compare a dentry name with a given name.  The first dentry is the parent of the dentry to be compared, the second is the child dentry.  len and name string are properties of the dentry to be compared.  qstr is the name to compare it with.

  Must be constant and idempotent, and should not take locks if possible, and should not or store into the dentry.  Should not dereference pointers outside the dentry without lots of care (eg.  d_parent, d_inode, d_name should not be used).

  However, our vfsmount is pinned, and RCU held, so the dentries and inodes won't disappear, neither will our sb or filesystem module.  -&gt;d_sb may be used.

  It is a tricky calling convention because it needs to be called under "rcu-walk", ie. without any locks or references on things.

- **`d_delete`**

  called when the last reference to a dentry is dropped and the dcache is deciding whether or not to cache it.  Return 1 to delete immediately, or 0 to cache the dentry.  Default is NULL which means to always cache a reachable dentry.  d_delete must be constant and idempotent.

- **`d_init`**

  called when a dentry is allocated

- **`d_release`**

  called when a dentry is really deallocated

- **`d_iput`**

  called when a dentry loses its inode (just prior to its being deallocated).  The default when this is NULL is that the VFS calls iput().  If you define this method, you must call iput() yourself

- **`d_dname`**

  called when the pathname of a dentry should be generated. Useful for some pseudo filesystems (sockfs, pipefs, ...) to delay pathname generation.  (Instead of doing it when dentry is created, it's done only when the path is needed.).  Real filesystems probably dont want to use it, because their dentries are present in global dcache hash, so their hash should be an invariant.  As no lock is held, d_dname() should not try to modify the dentry itself, unless appropriate SMP safety is used. CAUTION : d_path() logic is quite tricky.  The correct way to return for example "Hello" is to put it at the end of the buffer, and returns a pointer to the first char. dynamic_dname() helper function is provided to take care of this.

  Example :



```c
static char *pipefs_dname(struct dentry *dent, char *buffer, int buflen)
{
        return dynamic_dname(dentry, buffer, buflen, "pipe:[%lu]",
                        dentry->d_inode->i_ino);
}
```

- **`d_automount`**

  called when an automount dentry is to be traversed (optional). This should create a new VFS mount record and return the record to the caller.  The caller is supplied with a path parameter giving the automount directory to describe the automount target and the parent VFS mount record to provide inheritable mount parameters.  NULL should be returned if someone else managed to make the automount first.  If the vfsmount creation failed, then an error code should be returned.  If -EISDIR is returned, then the directory will be treated as an ordinary directory and returned to pathwalk to continue walking.

  If a vfsmount is returned, the caller will attempt to mount it on the mountpoint and will remove the vfsmount from its expiration list in the case of failure.

  This function is only used if DCACHE_NEED_AUTOMOUNT is set on the dentry.  This is set by \__d_instantiate() if S_AUTOMOUNT is set on the inode being added.

- **`d_manage`**

  called to allow the filesystem to manage the transition from a dentry (optional).  This allows autofs, for example, to hold up clients waiting to explore behind a 'mountpoint' while letting the daemon go past and construct the subtree there.  0 should be returned to let the calling process continue.  -EISDIR can be returned to tell pathwalk to use this directory as an ordinary directory and to ignore anything mounted on it and not to check the automount flag.  Any other error code will abort pathwalk completely.

  If the 'rcu_walk' parameter is true, then the caller is doing a pathwalk in RCU-walk mode.  Sleeping is not permitted in this mode, and the caller can be asked to leave it and call again by returning -ECHILD.  -EISDIR may also be returned to tell pathwalk to ignore d_automount or any mounts.

  This function is only used if DCACHE_MANAGE_TRANSIT is set on the dentry being transited from.

- **`d_real`**

  overlay/union type filesystems implement this method to return one of the underlying dentries of a regular file hidden by the overlay.

  The 'type' argument takes the values D_REAL_DATA or D_REAL_METADATA for returning the real underlying dentry that refers to the inode hosting the file's data or metadata respectively.

  For non-regular files, the 'dentry' argument is returned.

- **`d_unalias_trylock`**

  if present, will be called by d_splice_alias() before moving a preexisting attached alias.  Returning false prevents \__d_move(), making d_splice_alias() fail with -ESTALE.

  Rationale: setting FS_RENAME_DOES_D_MOVE will prevent d_move() and d_exchange() calls from the outside of filesystem methods; however, it does not guarantee that attached dentries won't be renamed or moved by d_splice_alias() finding a preexisting alias for a directory inode.  Normally we would not care; however, something that wants to stabilize the entire path to root over a blocking operation might need that.  See 9p for one (and hopefully only) example.

- **`d_unalias_unlock`**

  should be paired with `d_unalias_trylock`; that one is called after \__d_move() call in \__d_unalias().

Each dentry has a pointer to its parent dentry, as well as a hash list of child dentries.  Child dentries are basically like files in a directory.

<a id="rst-directory-entry-cache-api"></a>

### Directory Entry Cache API

There are a number of functions defined which permit a filesystem to manipulate dentries:

- **`dget`**

  open a new handle for an existing dentry (this just increments the usage count)

- **`dput`**

  close a handle for a dentry (decrements the usage count).  If the usage count drops to 0, and the dentry is still in its parent's hash, the "d_delete" method is called to check whether it should be cached.  If it should not be cached, or if the dentry is not hashed, it is deleted.  Otherwise cached dentries are put into an LRU list to be reclaimed on memory shortage.

- **`d_drop`**

  this unhashes a dentry from its parents hash list.  A subsequent call to dput() will deallocate the dentry if its usage count drops to 0

- **`d_delete`**

  delete a dentry.  If there are no other open references to the dentry then the dentry is turned into a negative dentry (the d_iput() method is called).  If there are other references, then d_drop() is called instead

- **`d_add`**

  add a dentry to its parents hash list and then calls d_instantiate()

- **`d_instantiate`**

  add a dentry to the alias hash list for the inode and updates the "d_inode" member.  The "i_count" member in the inode structure should be set/incremented.  If the inode pointer is NULL, the dentry is called a "negative dentry".  This function is commonly called when an inode is created for an existing negative dentry

- **`d_lookup`**

  look up a dentry given its parent and path name component It looks up the child of that given name from the dcache hash table.  If it is found, the reference count is incremented and the dentry is returned.  The caller must use dput() to free the dentry when it finishes using it.

<a id="rst-mount-options"></a>

## Mount Options

<a id="rst-parsing-options"></a>

### Parsing options

On mount and remount the filesystem is passed a string containing a comma separated list of mount options.  The options can have either of these forms:

> option option=value

The &lt;linux/parser.h&gt; header defines an API that helps parse these options.  There are plenty of examples on how to use it in existing filesystems.

<a id="rst-showing-options"></a>

### Showing options

If a filesystem accepts mount options, it must define show_options() to show all the currently active options.  The rules are:

> - options MUST be shown which are not default or their values differ from the default
>
> - options MAY be shown which are enabled by default or have their default value

Options used only internally between a mount helper and the kernel (such as file descriptors), or which only have an effect during the mounting (such as ones controlling the creation of a journal) are exempt from the above rules.

The underlying reason for the above rules is to make sure, that a mount can be accurately replicated (e.g. umounting and mounting again) based on the information found in /proc/mounts.

<a id="rst-resources"></a>

## Resources

- **(Note some of these resources are not up-to-date with the latest kernel**

  version.)

- **Creating Linux virtual filesystems. 2002**

  &lt;[https://lwn.net/Articles/13325/](<https://lwn.net/Articles/13325/>)&gt;

- **The Linux Virtual File-system Layer by Neil Brown. 1999**

  &lt;[http://www.cse.unsw.edu.au/\~neilb/oss/linux-commentary/vfs.html](<http://www.cse.unsw.edu.au/~neilb/oss/linux-commentary/vfs.html>)&gt;

- **A tour of the Linux VFS by Michael K. Johnson. 1996**

  &lt;[https://www.tldp.org/LDP/khg/HyperNews/get/fs/vfstour.html](<https://www.tldp.org/LDP/khg/HyperNews/get/fs/vfstour.html>)&gt;

- **A small trail through the Linux kernel by Andries Brouwer. 2001**

  &lt;[https://www.win.tue.nl/\~aeb/linux/vfs/trail.html](<https://www.win.tue.nl/~aeb/linux/vfs/trail.html>)&gt;

---

# virtiofs: virtio-fs host<->guest shared file system

_Peios Kernel / Internals / Filesystems_

> Copyright (C) 2019 Red Hat, Inc.

<a id="rst-virtiofs-virtio-fs-host-guest-shared-file-system"></a>
<a id="rst-virtiofs-index"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- Copyright (C) 2019 Red Hat, Inc.

<a id="rst-introduction"></a>

## Introduction

The virtiofs file system for Linux implements a driver for the paravirtualized VIRTIO "virtio-fs" device for guest&lt;-&gt;host file system sharing.  It allows a guest to mount a directory that has been exported on the host.

Guests often require access to files residing on the host or remote systems. Use cases include making files available to new guests during installation, booting from a root file system located on the host, persistent storage for stateless or ephemeral guests, and sharing a directory between guests.

Although it is possible to use existing network file systems for some of these tasks, they require configuration steps that are hard to automate and they expose the storage network to the guest.  The virtio-fs device was designed to solve these problems by providing file system access without networking.

Furthermore the virtio-fs device takes advantage of the co-location of the guest and host to increase performance and provide semantics that are not possible with network file systems.

<a id="rst-usage"></a>

## Usage

Mount file system with tag `myfs` on `/mnt`:



```sh
guest# mount -t virtiofs myfs /mnt
```

Please see [https://virtio-fs.gitlab.io/](<https://virtio-fs.gitlab.io/>) for details on how to configure QEMU and the virtiofsd daemon.

<a id="rst-mount-options"></a>

### Mount options

virtiofs supports general VFS mount options, for example, remount, ro, rw, context, etc. It also supports FUSE mount options.

<a id="rst-atime-behavior"></a>

#### atime behavior

The atime-related mount options, for example, noatime, strictatime, are ignored. The atime behavior for virtiofs is the same as the underlying filesystem of the directory that has been exported on the host.

<a id="rst-internals"></a>

## Internals

Since the virtio-fs device uses the FUSE protocol for file system requests, the virtiofs file system for Linux is integrated closely with the FUSE file system client.  The guest acts as the FUSE client while the host acts as the FUSE server.  The /dev/fuse interface between the kernel and userspace is replaced with the virtio-fs device interface.

FUSE requests are placed into a virtqueue and processed by the host.  The response portion of the buffer is filled in by the host and the guest handles the request completion.

Mapping /dev/fuse to virtqueues requires solving differences in semantics between /dev/fuse and virtqueues.  Each time the /dev/fuse device is read, the FUSE client may choose which request to transfer, making it possible to prioritize certain requests over others.  Virtqueues have queue semantics and it is not possible to change the order of requests that have been enqueued. This is especially important if the virtqueue becomes full since it is then impossible to add high priority requests.  In order to address this difference, the virtio-fs device uses a "hiprio" virtqueue specifically for requests that have priority over normal requests.

---

# ZoneFS - Zone filesystem for Zoned block devices

_Peios Kernel / Internals / Filesystems_

> zonefs is a very simple file system exposing each zone of a zoned block device as a file. Unlike a regular POSIX-compliant file system with native zoned block device support (e.g. f2fs), zonefs does not hide the sequential write constraint…

<a id="rst-zonefs-zone-filesystem-for-zoned-block-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

zonefs is a very simple file system exposing each zone of a zoned block device as a file. Unlike a regular POSIX-compliant file system with native zoned block device support (e.g. f2fs), zonefs does not hide the sequential write constraint of zoned block devices to the user. Files representing sequential write zones of the device must be written sequentially starting from the end of the file (append only writes).

As such, zonefs is in essence closer to a raw block device access interface than to a full-featured POSIX file system. The goal of zonefs is to simplify the implementation of zoned block device support in applications by replacing raw block device file accesses with a richer file API, avoiding relying on direct block device file ioctls which may be more obscure to developers. One example of this approach is the implementation of LSM (log-structured merge) tree structures (such as used in RocksDB and LevelDB) on zoned block devices by allowing SSTables to be stored in a zone file similarly to a regular file system rather than as a range of sectors of the entire disk. The introduction of the higher level construct "one file is one zone" can help reducing the amount of changes needed in the application as well as introducing support for different application programming languages.

<a id="rst-zoned-block-devices"></a>

### Zoned block devices

Zoned storage devices belong to a class of storage devices with an address space that is divided into zones. A zone is a group of consecutive LBAs and all zones are contiguous (there are no LBA gaps). Zones may have different types.

- Conventional zones: there are no access constraints to LBAs belonging to conventional zones. Any read or write access can be executed, similarly to a regular block device.

- Sequential zones: these zones accept random reads but must be written sequentially. Each sequential zone has a write pointer maintained by the device that keeps track of the mandatory start LBA position of the next write to the device. As a result of this write constraint, LBAs in a sequential zone cannot be overwritten. Sequential zones must first be erased using a special command (zone reset) before rewriting.

Zoned storage devices can be implemented using various recording and media technologies. The most common form of zoned storage today uses the SCSI Zoned Block Commands (ZBC) and Zoned ATA Commands (ZAC) interfaces on Shingled Magnetic Recording (SMR) HDDs.

Solid State Disks (SSD) storage devices can also implement a zoned interface to, for instance, reduce internal write amplification due to garbage collection. The NVMe Zoned NameSpace (ZNS) is a technical proposal of the NVMe standard committee aiming at adding a zoned storage interface to the NVMe protocol.

<a id="rst-zonefs-overview"></a>

## Zonefs Overview

Zonefs exposes the zones of a zoned block device as files. The files representing zones are grouped by zone type, which are themselves represented by sub-directories. This file structure is built entirely using zone information provided by the device and so does not require any complex on-disk metadata structure.

<a id="rst-on-disk-metadata"></a>

### On-disk metadata

zonefs on-disk metadata is reduced to an immutable super block which persistently stores a magic number and optional feature flags and values. On mount, zonefs uses blkdev_report_zones() to obtain the device zone configuration and populates the mount point with a static file tree solely based on this information. File sizes come from the device zone type and write pointer position managed by the device itself.

The super block is always written on disk at sector 0. The first zone of the device storing the super block is never exposed as a zone file by zonefs. If the zone containing the super block is a sequential zone, the mkzonefs format tool always "finishes" the zone, that is, it transitions the zone to a full state to make it read-only, preventing any data write.

<a id="rst-zone-type-sub-directories"></a>

### Zone type sub-directories

Files representing zones of the same type are grouped together under the same sub-directory automatically created on mount.

For conventional zones, the sub-directory "cnv" is used. This directory is however created if and only if the device has usable conventional zones. If the device only has a single conventional zone at sector 0, the zone will not be exposed as a file as it will be used to store the zonefs super block. For such devices, the "cnv" sub-directory will not be created.

For sequential write zones, the sub-directory "seq" is used.

These two directories are the only directories that exist in zonefs. Users cannot create other directories and cannot rename nor delete the "cnv" and "seq" sub-directories.

The size of the directories indicated by the st_size field of struct stat, obtained with the stat() or fstat() system calls, indicates the number of files existing under the directory.

<a id="rst-zone-files"></a>

### Zone files

Zone files are named using the number of the zone they represent within the set of zones of a particular type. That is, both the "cnv" and "seq" directories contain files named "0", "1", "2", ... The file numbers also represent increasing zone start sector on the device.

All read and write operations to zone files are not allowed beyond the file maximum size, that is, beyond the zone capacity. Any access exceeding the zone capacity is failed with the -EFBIG error.

Creating, deleting, renaming or modifying any attribute of files and sub-directories is not allowed.

The number of blocks of a file as reported by stat() and fstat() indicates the capacity of the zone file, or in other words, the maximum file size.

<a id="rst-conventional-zone-files"></a>

### Conventional zone files

The size of conventional zone files is fixed to the size of the zone they represent. Conventional zone files cannot be truncated.

These files can be randomly read and written using any type of I/O operation: buffered I/Os, direct I/Os, memory mapped I/Os (mmap), etc. There are no I/O constraint for these files beyond the file size limit mentioned above.

<a id="rst-sequential-zone-files"></a>

### Sequential zone files

The size of sequential zone files grouped in the "seq" sub-directory represents the file's zone write pointer position relative to the zone start sector.

Sequential zone files can only be written sequentially, starting from the file end, that is, write operations can only be append writes. Zonefs makes no attempt at accepting random writes and will fail any write request that has a start offset not corresponding to the end of the file, or to the end of the last write issued and still in-flight (for asynchronous I/O operations).

Since dirty page writeback by the page cache does not guarantee a sequential write pattern, zonefs prevents buffered writes and writeable shared mappings on sequential files. Only direct I/O writes are accepted for these files. zonefs relies on the sequential delivery of write I/O requests to the device implemented by the block layer elevator. An elevator implementing the sequential write feature for zoned block device (ELEVATOR_F_ZBD_SEQ_WRITE elevator feature) must be used. This type of elevator (e.g. mq-deadline) is set by default for zoned block devices on device initialization.

There are no restrictions on the type of I/O used for read operations in sequential zone files. Buffered I/Os, direct I/Os and shared read mappings are all accepted.

Truncating sequential zone files is allowed only down to 0, in which case, the zone is reset to rewind the file zone write pointer position to the start of the zone, or up to the zone capacity, in which case the file's zone is transitioned to the FULL state (finish zone operation).

<a id="rst-format-options"></a>

### Format options

Several optional features of zonefs can be enabled at format time.

- Conventional zone aggregation: ranges of contiguous conventional zones can be aggregated into a single larger file instead of the default one file per zone.

- File ownership: The owner UID and GID of zone files is by default 0 (root) but can be changed to any valid UID/GID.

- File access permissions: the default 640 access permissions can be changed.

<a id="rst-io-error-handling"></a>

### IO error handling

Zoned block devices may fail I/O requests for reasons similar to regular block devices, e.g. due to bad sectors. However, in addition to such known I/O failure pattern, the standards governing zoned block devices behavior define additional conditions that result in I/O errors.

- A zone may transition to the read-only condition (BLK_ZONE_COND_READONLY): While the data already written in the zone is still readable, the zone can no longer be written. No user action on the zone (zone management command or read/write access) can change the zone condition back to a normal read/write state. While the reasons for the device to transition a zone to read-only state are not defined by the standards, a typical cause for such transition would be a defective write head on an HDD (all zones under this head are changed to read-only).

- A zone may transition to the offline condition (BLK_ZONE_COND_OFFLINE): An offline zone cannot be read nor written. No user action can transition an offline zone back to an operational good state. Similarly to zone read-only transitions, the reasons for a drive to transition a zone to the offline condition are undefined. A typical cause would be a defective read-write head on an HDD causing all zones on the platter under the broken head to be inaccessible.

- Unaligned write errors: These errors result from the host issuing write requests with a start sector that does not correspond to a zone write pointer position when the write request is executed by the device. Even though zonefs enforces sequential file write for sequential zones, unaligned write errors may still happen in the case of a partial failure of a very large direct I/O operation split into multiple BIOs/requests or asynchronous I/O operations. If one of the write request within the set of sequential write requests issued to the device fails, all write requests queued after it will become unaligned and fail.

- Delayed write errors: similarly to regular block devices, if the device side write cache is enabled, write errors may occur in ranges of previously completed writes when the device write cache is flushed, e.g. on fsync(). Similarly to the previous immediate unaligned write error case, delayed write errors can propagate through a stream of cached sequential data for a zone causing all data to be dropped after the sector that caused the error.

All I/O errors detected by zonefs are notified to the user with an error code return for the system call that triggered or detected the error. The recovery actions taken by zonefs in response to I/O errors depend on the I/O type (read vs write) and on the reason for the error (bad sector, unaligned writes or zone condition change).

- For read I/O errors, zonefs does not execute any particular recovery action, but only if the file zone is still in a good condition and there is no inconsistency between the file inode size and its zone write pointer position. If a problem is detected, I/O error recovery is executed (see below table).

- For write I/O errors, zonefs I/O error recovery is always executed.

- A zone condition change to read-only or offline also always triggers zonefs I/O error recovery.

Zonefs minimal I/O error recovery may change a file size and file access permissions.

- File size changes: Immediate or delayed write errors in a sequential zone file may cause the file inode size to be inconsistent with the amount of data successfully written in the file zone. For instance, the partial failure of a multi-BIO large write operation will cause the zone write pointer to advance partially, even though the entire write operation will be reported as failed to the user. In such case, the file inode size must be advanced to reflect the zone write pointer change and eventually allow the user to restart writing at the end of the file. A file size may also be reduced to reflect a delayed write error detected on fsync(): in this case, the amount of data effectively written in the zone may be less than originally indicated by the file inode size. After such I/O error, zonefs always fixes the file inode size to reflect the amount of data persistently stored in the file zone.

- Access permission changes: A zone condition change to read-only is indicated with a change in the file access permissions to render the file read-only. This disables changes to the file attributes and data modification. For offline zones, all permissions (read and write) to the file are disabled.

Further action taken by zonefs I/O error recovery can be controlled by the user with the "errors=xxx" mount option. The table below summarizes the result of zonefs I/O error processing depending on the mount option and on the zone conditions:



```text
+--------------+-----------+-----------------------------------------+
|              |           |            Post error state             |
| "errors=xxx" |  device   |                 access permissions      |
|    mount     |   zone    | file         file          device zone  |
|    option    | condition | size     read    write    read    write |
+--------------+-----------+-----------------------------------------+
|              | good      | fixed    yes     no       yes     yes   |
| remount-ro   | read-only | as is    yes     no       yes     no    |
| (default)    | offline   |   0      no      no       no      no    |
+--------------+-----------+-----------------------------------------+
|              | good      | fixed    yes     no       yes     yes   |
| zone-ro      | read-only | as is    yes     no       yes     no    |
|              | offline   |   0      no      no       no      no    |
+--------------+-----------+-----------------------------------------+
|              | good      |   0      no      no       yes     yes   |
| zone-offline | read-only |   0      no      no       yes     no    |
|              | offline   |   0      no      no       no      no    |
+--------------+-----------+-----------------------------------------+
|              | good      | fixed    yes     yes      yes     yes   |
| repair       | read-only | as is    yes     no       yes     no    |
|              | offline   |   0      no      no       no      no    |
+--------------+-----------+-----------------------------------------+
```

Further notes:

- The "errors=remount-ro" mount option is the default behavior of zonefs I/O error processing if no errors mount option is specified.

- With the "errors=remount-ro" mount option, the change of the file access permissions to read-only applies to all files. The file system is remounted read-only.

- Access permission and file size changes due to the device transitioning zones to the offline condition are permanent. Remounting or reformatting the device with mkfs.zonefs (mkzonefs) will not change back offline zone files to a good state.

- File access permission changes to read-only due to the device transitioning zones to the read-only condition are permanent. Remounting or reformatting the device will not re-enable file write access.

- File access permission changes implied by the remount-ro, zone-ro and zone-offline mount options are temporary for zones in a good condition. Unmounting and remounting the file system will restore the previous default (format time values) access rights to the files affected.

- The repair mount option triggers only the minimal set of I/O error recovery actions, that is, file size fixes for zones in a good condition. Zones indicated as being read-only or offline by the device still imply changes to the zone file access permissions as noted in the table above.

<a id="rst-mount-options"></a>

### Mount options

zonefs defines several mount options: \* errors=&lt;behavior&gt; \* explicit-open

<a id="rst-errors-behavior-option"></a>

#### "errors=&lt;behavior&gt;" option

The "errors=&lt;behavior&gt;" option mount option allows the user to specify zonefs behavior in response to I/O errors, inode size inconsistencies or zone condition changes. The defined behaviors are as follow:

- remount-ro (default)

- zone-ro

- zone-offline

- repair

The run-time I/O error actions defined for each behavior are detailed in the previous section. Mount time I/O errors will cause the mount operation to fail. The handling of read-only zones also differs between mount-time and run-time. If a read-only zone is found at mount time, the zone is always treated in the same manner as offline zones, that is, all accesses are disabled and the zone file size set to 0. This is necessary as the write pointer of read-only zones is defined as invalib by the ZBC and ZAC standards, making it impossible to discover the amount of data that has been written to the zone. In the case of a read-only zone discovered at run-time, as indicated in the previous section. The size of the zone file is left unchanged from its last updated value.

<a id="rst-explicit-open-option"></a>

#### "explicit-open" option

A zoned block device (e.g. an NVMe Zoned Namespace device) may have limits on the number of zones that can be active, that is, zones that are in the implicit open, explicit open or closed conditions.  This potential limitation translates into a risk for applications to see write IO errors due to this limit being exceeded if the zone of a file is not already active when a write request is issued by the user.

To avoid these potential errors, the "explicit-open" mount option forces zones to be made active using an open zone command when a file is opened for writing for the first time. If the zone open command succeeds, the application is then guaranteed that write requests can be processed. Conversely, the "explicit-open" mount option will result in a zone close command being issued to the device on the last close() of a zone file if the zone is not full nor empty.

<a id="rst-runtime-sysfs-attributes"></a>

### Runtime sysfs attributes

zonefs defines several sysfs attributes for mounted devices.  All attributes are user readable and can be found in the directory /sys/fs/zonefs/&lt;dev&gt;/, where &lt;dev&gt; is the name of the mounted zoned block device.

The attributes defined are as follows.

- **max_wro_seq_files**:  This attribute reports the maximum number of sequential zone files that can be open for writing.  This number corresponds to the maximum number of explicitly or implicitly open zones that the device supports.  A value of 0 means that the device has no limit and that any zone (any file) can be open for writing and written at any time, regardless of the state of other zones.  When the *explicit-open* mount option is used, zonefs will fail any open() system call requesting to open a sequential zone file for writing when the number of sequential zone files already open for writing has reached the *max_wro_seq_files* limit.

- **nr_wro_seq_files**:  This attribute reports the current number of sequential zone files open for writing.  When the "explicit-open" mount option is used, this number can never exceed *max_wro_seq_files*.  If the *explicit-open* mount option is not used, the reported number can be greater than *max_wro_seq_files*.  In such case, it is the responsibility of the application to not write simultaneously more than *max_wro_seq_files* sequential zone files.  Failure to do so can result in write errors.

- **max_active_seq_files**:  This attribute reports the maximum number of sequential zone files that are in an active state, that is, sequential zone files that are partially written (not empty nor full) or that have a zone that is explicitly open (which happens only if the *explicit-open* mount option is used).  This number is always equal to the maximum number of active zones that the device supports.  A value of 0 means that the mounted device has no limit on the number of sequential zone files that can be active.

- **nr_active_seq_files**:  This attributes reports the current number of sequential zone files that are active. If *max_active_seq_files* is not 0, then the value of *nr_active_seq_files* can never exceed the value of *nr_active_seq_files*, regardless of the use of the *explicit-open* mount option.

<a id="rst-zonefs-user-space-tools"></a>

## Zonefs User Space Tools

The mkzonefs tool is used to format zoned block devices for use with zonefs. This tool is available on Github at:

[https://github.com/damien-lemoal/zonefs-tools](<https://github.com/damien-lemoal/zonefs-tools>)

zonefs-tools also includes a test suite which can be run against any zoned block device, including null_blk block device created with zoned mode.

<a id="rst-examples"></a>

### Examples

The following formats a 15TB host-managed SMR HDD with 256 MB zones with the conventional zones aggregation feature enabled:



```text
# mkzonefs -o aggr_cnv /dev/sdX
# mount -t zonefs /dev/sdX /mnt
# ls -l /mnt/
total 0
dr-xr-xr-x 2 root root     1 Nov 25 13:23 cnv
dr-xr-xr-x 2 root root 55356 Nov 25 13:23 seq
```

The size of the zone files sub-directories indicate the number of files existing for each type of zones. In this example, there is only one conventional zone file (all conventional zones are aggregated under a single file):



```text
# ls -l /mnt/cnv
total 137101312
-rw-r----- 1 root root 140391743488 Nov 25 13:23 0
```

This aggregated conventional zone file can be used as a regular file:



```text
# mkfs.ext4 /mnt/cnv/0
# mount -o loop /mnt/cnv/0 /data
```

The "seq" sub-directory grouping files for sequential write zones has in this example 55356 zones:



```text
# ls -lv /mnt/seq
total 14511243264
-rw-r----- 1 root root 0 Nov 25 13:23 0
-rw-r----- 1 root root 0 Nov 25 13:23 1
-rw-r----- 1 root root 0 Nov 25 13:23 2
...
-rw-r----- 1 root root 0 Nov 25 13:23 55354
-rw-r----- 1 root root 0 Nov 25 13:23 55355
```

For sequential write zone files, the file size changes as data is appended at the end of the file, similarly to any regular file system:



```text
# dd if=/dev/zero of=/mnt/seq/0 bs=4096 count=1 conv=notrunc oflag=direct
1+0 records in
1+0 records out
4096 bytes (4.1 kB, 4.0 KiB) copied, 0.00044121 s, 9.3 MB/s

# ls -l /mnt/seq/0
-rw-r----- 1 root root 4096 Nov 25 13:23 /mnt/seq/0
```

The written file can be truncated to the zone size, preventing any further write operation:



```text
# truncate -s 268435456 /mnt/seq/0
# ls -l /mnt/seq/0
-rw-r----- 1 root root 268435456 Nov 25 13:49 /mnt/seq/0
```

Truncation to 0 size allows freeing the file zone storage space and restart append-writes to the file:



```text
# truncate -s 0 /mnt/seq/0
# ls -l /mnt/seq/0
-rw-r----- 1 root root 0 Nov 25 13:49 /mnt/seq/0
```

Since files are statically mapped to zones on the disk, the number of blocks of a file as reported by stat() and fstat() indicates the capacity of the file zone:



```text
# stat /mnt/seq/0
File: /mnt/seq/0
Size: 0             Blocks: 524288     IO Block: 4096   regular empty file
Device: 870h/2160d  Inode: 50431       Links: 1
Access: (0640/-rw-r-----)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2019-11-25 13:23:57.048971997 +0900
Modify: 2019-11-25 13:52:25.553805765 +0900
Change: 2019-11-25 13:52:25.553805765 +0900
Birth: -
```

The number of blocks of the file ("Blocks") in units of 512B blocks gives the maximum file size of 524288 \* 512 B = 256 MB, corresponding to the device zone capacity in this example. Of note is that the "IO block" field always indicates the minimum I/O size for writes and corresponds to the device physical sector size.

---

# Filesystem Caching

_Peios Kernel / Internals / Filesystems / caching_

> Reference for Filesystem Caching.

<a id="rst-filesystem-caching"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [General Filesystem Caching](</kernel/internals/filesystems/caching/fscache.md>)
- [Network Filesystem Caching API](</kernel/internals/filesystems/caching/netfs-api.md>)
- [Cache Backend API](</kernel/internals/filesystems/caching/backend-api.md>)
- [Cache on Already Mounted Filesystem](</kernel/internals/filesystems/caching/cachefiles.md>)

---

# Cache Backend API

_Peios Kernel / Internals / Filesystems / caching_

> The FS-Cache system provides an API by which actual caches can be supplied to FS-Cache for it to then serve out to network filesystems and other interested parties. This API is used by:

<a id="rst-cache-backend-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The FS-Cache system provides an API by which actual caches can be supplied to FS-Cache for it to then serve out to network filesystems and other interested parties.  This API is used by:



```text
#include <linux/fscache-cache.h>.
```

<a id="rst-overview"></a>

## Overview

Interaction with the API is handled on three levels: cache, volume and data storage, and each level has its own type of cookie object:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COOKIE
>
> </th>
> <th>
>
>
> C TYPE
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> Cache cookie
>
> </td>
> <td>
>
>
> struct fscache_cache
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Volume cookie
>
> </td>
> <td>
>
>
> struct fscache_volume
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Data storage cookie
>
> </td>
> <td>
>
>
> struct fscache_cookie
>
> </td>
> </tr>
> </tbody>
> </table>

Cookies are used to provide some filesystem data to the cache, manage state and pin the cache during access in addition to acting as reference points for the API functions.  Each cookie has a debugging ID that is included in trace points to make it easier to correlate traces.  Note, though, that debugging IDs are simply allocated from incrementing counters and will eventually wrap.

The cache backend and the network filesystem can both ask for cache cookies - and if they ask for one of the same name, they'll get the same cookie.  Volume and data cookies, however, are created at the behest of the filesystem only.

<a id="rst-cache-cookies"></a>

## Cache Cookies

Caches are represented in the API by cache cookies.  These are objects of type:



```text
struct fscache_cache {
        void            *cache_priv;
        unsigned int    debug_id;
        char            *name;
        ...
};
```

There are a few fields that the cache backend might be interested in.  The `debug_id` can be used in tracing to match lines referring to the same cache and `name` is the name the cache was registered with.  The `cache_priv` member is private data provided by the cache when it is brought online.  The other fields are for internal use.

<a id="rst-registering-a-cache"></a>

## Registering a Cache

When a cache backend wants to bring a cache online, it should first register the cache name and that will get it a cache cookie.  This is done with:



```text
struct fscache_cache *fscache_acquire_cache(const char *name);
```

This will look up and potentially create a cache cookie.  The cache cookie may have already been created by a network filesystem looking for it, in which case that cache cookie will be used.  If the cache cookie is not in use by another cache, it will be moved into the preparing state, otherwise it will return busy.

If successful, the cache backend can then start setting up the cache.  In the event that the initialisation fails, the cache backend should call:



```text
void fscache_relinquish_cache(struct fscache_cache *cache);
```

to reset and discard the cookie.

<a id="rst-bringing-a-cache-online"></a>

## Bringing a Cache Online

Once the cache is set up, it can be brought online by calling:



```text
int fscache_add_cache(struct fscache_cache *cache,
                      const struct fscache_cache_ops *ops,
                      void *cache_priv);
```

This stores the cache operations table pointer and cache private data into the cache cookie and moves the cache to the active state, thereby allowing accesses to take place.

<a id="rst-withdrawing-a-cache-from-service"></a>

## Withdrawing a Cache From Service

The cache backend can withdraw a cache from service by calling this function:



```text
void fscache_withdraw_cache(struct fscache_cache *cache);
```

This moves the cache to the withdrawn state to prevent new cache- and volume-level accesses from starting and then waits for outstanding cache-level accesses to complete.

The cache must then go through the data storage objects it has and tell fscache to withdraw them, calling:



```text
void fscache_withdraw_cookie(struct fscache_cookie *cookie);
```

on the cookie that each object belongs to.  This schedules the specified cookie for withdrawal.  This gets offloaded to a workqueue.  The cache backend can wait for completion by calling:



```text
void fscache_wait_for_objects(struct fscache_cache *cache);
```

Once all the cookies are withdrawn, a cache backend can withdraw all the volumes, calling:



```text
void fscache_withdraw_volume(struct fscache_volume *volume);
```

to tell fscache that a volume has been withdrawn.  This waits for all outstanding accesses on the volume to complete before returning.

When the cache is completely withdrawn, fscache should be notified by calling:



```text
void fscache_relinquish_cache(struct fscache_cache *cache);
```

to clear fields in the cookie and discard the caller's ref on it.

<a id="rst-volume-cookies"></a>

## Volume Cookies

Within a cache, the data storage objects are organised into logical volumes. These are represented in the API as objects of type:



```text
struct fscache_volume {
        struct fscache_cache            *cache;
        void                            *cache_priv;
        unsigned int                    debug_id;
        char                            *key;
        unsigned int                    key_hash;
        ...
        u8                              coherency_len;
        u8                              coherency[];
};
```

There are a number of fields here that are of interest to the caching backend:

> - `cache` - The parent cache cookie.
>
> - `cache_priv` - A place for the cache to stash private data.
>
> - `debug_id` - A debugging ID for logging in tracepoints.
>
> - `key` - A printable string with no '/' characters in it that represents the index key for the volume.  The key is NUL-terminated and padded out to a multiple of 4 bytes.
>
> - `key_hash` - A hash of the index key.  This should work out the same, no matter the cpu arch and endianness.
>
> - `coherency` - A piece of coherency data that should be checked when the volume is bound to in the cache.
>
> - `coherency_len` - The amount of data in the coherency buffer.

<a id="rst-data-storage-cookies"></a>

## Data Storage Cookies

A volume is a logical group of data storage objects, each of which is represented to the network filesystem by a cookie.  Cookies are represented in the API as objects of type:



```text
struct fscache_cookie {
        struct fscache_volume           *volume;
        void                            *cache_priv;
        unsigned long                   flags;
        unsigned int                    debug_id;
        unsigned int                    inval_counter;
        loff_t                          object_size;
        u8                              advice;
        u32                             key_hash;
        u8                              key_len;
        u8                              aux_len;
        ...
};
```

The fields in the cookie that are of interest to the cache backend are:

> - `volume` - The parent volume cookie.
>
> - `cache_priv` - A place for the cache to stash private data.
>
> - `flags` - A collection of bit flags, including:
>
>   > - FSCACHE_COOKIE_NO_DATA_TO_READ - There is no data available in the cache to be read as the cookie has been created or invalidated.
>   >
>   > - FSCACHE_COOKIE_NEEDS_UPDATE - The coherency data and/or object size has been changed and needs committing.
>   >
>   > - FSCACHE_COOKIE_LOCAL_WRITE - The netfs's data has been modified locally, so the cache object may be in an incoherent state with respect to the server.
>   >
>   > - FSCACHE_COOKIE_HAVE_DATA - The backend should set this if it successfully stores data into the cache.
>   >
>   > - FSCACHE_COOKIE_RETIRED - The cookie was invalidated when it was relinquished and the cached data should be discarded.
>
> - `debug_id` - A debugging ID for logging in tracepoints.
>
> - `inval_counter` - The number of invalidations done on the cookie.
>
> - `advice` - Information about how the cookie is to be used.
>
> - `key_hash` - A hash of the index key.  This should work out the same, no matter the cpu arch and endianness.
>
> - `key_len` - The length of the index key.
>
> - `aux_len` - The length of the coherency data buffer.

Each cookie has an index key, which may be stored inline to the cookie or elsewhere.  A pointer to this can be obtained by calling:



```text
void *fscache_get_key(struct fscache_cookie *cookie);
```

The index key is a binary blob, the storage for which is padded out to a multiple of 4 bytes.

Each cookie also has a buffer for coherency data.  This may also be inline or detached from the cookie and a pointer is obtained by calling:



```text
void *fscache_get_aux(struct fscache_cookie *cookie);
```

<a id="rst-cookie-accounting"></a>

## Cookie Accounting

Data storage cookies are counted and this is used to block cache withdrawal completion until all objects have been destroyed.  The following functions are provided to the cache to deal with that:



```text
void fscache_count_object(struct fscache_cache *cache);
void fscache_uncount_object(struct fscache_cache *cache);
void fscache_wait_for_objects(struct fscache_cache *cache);
```

The count function records the allocation of an object in a cache and the uncount function records its destruction.  Warning: by the time the uncount function returns, the cache may have been destroyed.

The wait function can be used during the withdrawal procedure to wait for fscache to finish withdrawing all the objects in the cache.  When it completes, there will be no remaining objects referring to the cache object or any volume objects.

<a id="rst-cache-management-api"></a>

## Cache Management API

The cache backend implements the cache management API by providing a table of operations that fscache can use to manage various aspects of the cache.  These are held in a structure of type:



```text
struct fscache_cache_ops {
        const char *name;
        ...
};
```

This contains a printable name for the cache backend driver plus a number of pointers to methods to allow fscache to request management of the cache:

> - Set up a volume cookie \[optional\]:
>
>
>
>   ```text
>   void (*acquire_volume)(struct fscache_volume *volume);
>   ```
>
>   This method is called when a volume cookie is being created.  The caller holds a cache-level access pin to prevent the cache from going away for the duration.  This method should set up the resources to access a volume in the cache and should not return until it has done so.
>
>   If successful, it can set `cache_priv` to its own data.
>
> - Clean up volume cookie \[optional\]:
>
>
>
>   ```text
>   void (*free_volume)(struct fscache_volume *volume);
>   ```
>
>   This method is called when a volume cookie is being released if `cache_priv` is set.
>
> - Look up a cookie in the cache \[mandatory\]:
>
>
>
>   ```text
>   bool (*lookup_cookie)(struct fscache_cookie *cookie);
>   ```
>
>   This method is called to look up/create the resources needed to access the data storage for a cookie.  It is called from a worker thread with a volume-level access pin in the cache to prevent it from being withdrawn.
>
>   True should be returned if successful and false otherwise.  If false is returned, the withdraw_cookie op (see below) will be called.
>
>   If lookup fails, but the object could still be created (e.g. it hasn't been cached before), then:
>
>
>
>   ```text
>   void fscache_cookie_lookup_negative(
>           struct fscache_cookie *cookie);
>   ```
>
>   can be called to let the network filesystem proceed and start downloading stuff whilst the cache backend gets on with the job of creating things.
>
>   If successful, `cookie->cache_priv` can be set.
>
> - Withdraw an object without any cookie access counts held \[mandatory\]:
>
>
>
>   ```text
>   void (*withdraw_cookie)(struct fscache_cookie *cookie);
>   ```
>
>   This method is called to withdraw a cookie from service.  It will be called when the cookie is relinquished by the netfs, withdrawn or culled by the cache backend or closed after a period of non-use by fscache.
>
>   The caller doesn't hold any access pins, but it is called from a non-reentrant work item to manage races between the various ways withdrawal can occur.
>
>   The cookie will have the `FSCACHE_COOKIE_RETIRED` flag set on it if the associated data is to be removed from the cache.
>
> - Change the size of a data storage object \[mandatory\]:
>
>
>
>   ```text
>   void (*resize_cookie)(struct netfs_cache_resources *cres,
>                         loff_t new_size);
>   ```
>
>   This method is called to inform the cache backend of a change in size of the netfs file due to local truncation.  The cache backend should make all of the changes it needs to make before returning as this is done under the netfs inode mutex.
>
>   The caller holds a cookie-level access pin to prevent a race with withdrawal and the netfs must have the cookie marked in-use to prevent garbage collection or culling from removing any resources.
>
> - Invalidate a data storage object \[mandatory\]:
>
>
>
>   ```text
>   bool (*invalidate_cookie)(struct fscache_cookie *cookie);
>   ```
>
>   This is called when the network filesystem detects a third-party modification or when an O_DIRECT write is made locally.  This requests that the cache backend should throw away all the data in the cache for this object and start afresh.  It should return true if successful and false otherwise.
>
>   On entry, new I O/operations are blocked.  Once the cache is in a position to accept I/O again, the backend should release the block by calling:
>
>
>
>   ```text
>   void fscache_resume_after_invalidation(struct fscache_cookie *cookie);
>   ```
>
>   If the method returns false, caching will be withdrawn for this cookie.
>
> - Prepare to make local modifications to the cache \[mandatory\]:
>
>
>
>   ```text
>   void (*prepare_to_write)(struct fscache_cookie *cookie);
>   ```
>
>   This method is called when the network filesystem finds that it is going to need to modify the contents of the cache due to local writes or truncations.  This gives the cache a chance to note that a cache object may be incoherent with respect to the server and may need writing back later.  This may also cause the cached data to be scrapped on later rebinding if not properly committed.
>
> - Begin an operation for the netfs lib \[mandatory\]:
>
>
>
>   ```text
>   bool (*begin_operation)(struct netfs_cache_resources *cres,
>                           enum fscache_want_state want_state);
>   ```
>
>   This method is called when an I/O operation is being set up (read, write or resize).  The caller holds an access pin on the cookie and must have marked the cookie as in-use.
>
>   If it can, the backend should attach any resources it needs to keep around to the netfs_cache_resources object and return true.
>
>   If it can't complete the setup, it should return false.
>
>   The want_state parameter indicates the state the caller needs the cache object to be in and what it wants to do during the operation:
>
>   > - `FSCACHE_WANT_PARAMS` - The caller just wants to access cache object parameters; it doesn't need to do data I/O yet.
>   >
>   > - `FSCACHE_WANT_READ` - The caller wants to read data.
>   >
>   > - `FSCACHE_WANT_WRITE` - The caller wants to write to or resize the cache object.
>
>   Note that there won't necessarily be anything attached to the cookie's cache_priv yet if the cookie is still being created.

<a id="rst-data-i-o-api"></a>

## Data I/O API

A cache backend provides a data I/O API by through the netfs library's `struct netfs_cache_ops` attached to a `struct netfs_cache_resources` by the `begin_operation` method described above.

See the [Documentation/filesystems/netfs_library.rst](/kernel/internals/filesystems/netfs-library.md) for a description.

<a id="rst-miscellaneous-functions"></a>

## Miscellaneous Functions

FS-Cache provides some utilities that a cache backend may make use of:

> - Note occurrence of an I/O error in a cache:
>
>
>
>   ```text
>   void fscache_io_error(struct fscache_cache *cache);
>   ```
>
>   This tells FS-Cache that an I/O error occurred in the cache.  This prevents any new I/O from being started on the cache.
>
>   This does not actually withdraw the cache.  That must be done separately.
>
> - Note cessation of caching on a cookie due to failure:
>
>
>
>   ```text
>   void fscache_caching_failed(struct fscache_cookie *cookie);
>   ```
>
>   This notes that a the caching that was being done on a cookie failed in some way, for instance the backing storage failed to be created or invalidation failed and that no further I/O operations should take place on it until the cache is reset.
>
> - Count I/O requests:
>
>
>
>   ```text
>   void fscache_count_read(void);
>   void fscache_count_write(void);
>   ```
>
>   These record reads and writes from/to the cache.  The numbers are displayed in /proc/fs/fscache/stats.
>
> - Count out-of-space errors:
>
>
>
>   ```text
>   void fscache_count_no_write_space(void);
>   void fscache_count_no_create_space(void);
>   ```
>
>   These record ENOSPC errors in the cache, divided into failures of data writes and failures of filesystem object creations (e.g. mkdir).
>
> - Count objects culled:
>
>
>
>   ```text
>   void fscache_count_culled(void);
>   ```
>
>   This records the culling of an object.
>
> - Get the cookie from a set of cache resources:
>
>
>
>   ```text
>   struct fscache_cookie *fscache_cres_cookie(struct netfs_cache_resources *cres)
>   ```
>
>   Pull a pointer to the cookie from the cache resources.  This may return a NULL cookie if no cookie was set.

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-fscache_cookie_state"></a>`fscache_cookie_state()`

```c
enum fscache_cookie_state fscache_cookie_state(struct fscache_cookie *cookie)
```

Read the state of a cookie

**Parameters**

- `struct fscache_cookie *cookie`: The cookie to query

**Description**

Get the state of a cookie, imposing an ordering between the cookie contents
and the state value.  Paired with `fscache_set_cookie_state()`.

#### <a id="c-fscache_get_key"></a>`fscache_get_key()`

```c
void * fscache_get_key(struct fscache_cookie *cookie)
```

Get a pointer to the cookie key

**Parameters**

- `struct fscache_cookie *cookie`: The cookie to query

**Description**

Return a pointer to the where a cookie's key is stored.

#### <a id="c-fscache_count_object"></a>`fscache_count_object()`

```c
void fscache_count_object(struct fscache_cache *cache)
```

Tell fscache that an object has been added

**Parameters**

- `struct fscache_cache *cache`: The cache to account to

**Description**

Tell fscache that an object has been added to the cache.  This prevents the
cache from tearing down the cache structure until the object is uncounted.

#### <a id="c-fscache_uncount_object"></a>`fscache_uncount_object()`

```c
void fscache_uncount_object(struct fscache_cache *cache)
```

Tell fscache that an object has been removed

**Parameters**

- `struct fscache_cache *cache`: The cache to account to

**Description**

Tell fscache that an object has been removed from the cache and will no
longer be accessed.  After this point, the cache cookie may be destroyed.

#### <a id="c-fscache_wait_for_objects"></a>`fscache_wait_for_objects()`

```c
void fscache_wait_for_objects(struct fscache_cache *cache)
```

Wait for all objects to be withdrawn

**Parameters**

- `struct fscache_cache *cache`: The cache to query

**Description**

Wait for all extant objects in a cache to finish being withdrawn
and go away.

---

# Cache on Already Mounted Filesystem

_Peios Kernel / Internals / Filesystems / caching_

> CacheFiles is a caching backend that's meant to use as a cache a directory on an already mounted filesystem of a local type (such as Ext3).

> **Peios:** Unix mode, ownership and ACL examples describe the inherited metadata model. On managed Peios mounts, native security descriptors and granted handle rights determine access; `chmod`, `chown` and POSIX ACL recipes alone do not delegate it. Mount operations also require native authorization. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for mount-policy defaults and the tmpfs rootfs rule.


<a id="rst-cache-on-already-mounted-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

(*) Overview.

(*) Requirements.

(*) Configuration.

(*) Starting the cache.

(*) Things to avoid.

(*) Cache culling.

(*) Cache structure.

(*) Security model and SELinux.

(*) A note on security.

(*) Statistical information.

(*) Debugging.

(*) On-demand Read. -->

<a id="rst-overview"></a>

## Overview

CacheFiles is a caching backend that's meant to use as a cache a directory on an already mounted filesystem of a local type (such as Ext3).

CacheFiles uses a userspace daemon to do some of the cache management - such as reaping stale nodes and culling.  This is called cachefilesd and lives in /sbin.

The filesystem and data integrity of the cache are only as good as those of the filesystem providing the backing services.  Note that CacheFiles does not attempt to journal anything since the journalling interfaces of the various filesystems are very specific in nature.

CacheFiles creates a misc character device - "/dev/cachefiles" - that is used to communication with the daemon.  Only one thing may have this open at once, and while it is open, a cache is at least partially in existence.  The daemon opens this and sends commands down it to control the cache.

CacheFiles is currently limited to a single cache.

CacheFiles attempts to maintain at least a certain percentage of free space on the filesystem, shrinking the cache by culling the objects it contains to make space if necessary - see the "Cache Culling" section.  This means it can be placed on the same medium as a live set of data, and will expand to make use of spare space and automatically contract when the set of data requires more space.

<a id="rst-requirements"></a>

## Requirements

The use of CacheFiles and its daemon requires the following features to be available in the system and in the cache filesystem:

> - dnotify.
>
> - extended attributes (xattrs).
>
> - openat() and friends.
>
> - bmap() support on files in the filesystem (FIBMAP ioctl).
>
> - The use of bmap() to detect a partial page at the end of the file.

It is strongly recommended that the "dir_index" option is enabled on Ext3 filesystems being used as a cache.

<a id="rst-configuration"></a>

## Configuration

The cache is configured by a script in /etc/cachefilesd.conf.  These commands set up cache ready for use.  The following script commands are available:

> - **brun &lt;N&gt;%, bcull &lt;N&gt;%, bstop &lt;N&gt;%, frun &lt;N&gt;%, fcull &lt;N&gt;%, fstop &lt;N&gt;%**
>
>   Configure the culling limits.  Optional.  See the section on culling The defaults are 7% (run), 5% (cull) and 1% (stop) respectively.
>
>   The commands beginning with a 'b' are file space (block) limits, those beginning with an 'f' are file count limits.
>
> - **dir &lt;path&gt;**
>
>   Specify the directory containing the root of the cache.  Mandatory.
>
> - **tag &lt;name&gt;**
>
>   Specify a tag to FS-Cache to use in distinguishing multiple caches. Optional.  The default is "CacheFiles".
>
> - **debug &lt;mask&gt;**
>
>   Specify a numeric bitmask to control debugging in the kernel module. Optional.  The default is zero (all off).  The following values can be OR'd into the mask to collect various information:
>
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > 1
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Turn on trace of function entry (\_enter() macros)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > 2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Turn on trace of function exit (\_leave() macros)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > 4
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Turn on trace of internal debug points (\_debug())
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>
>
>   This mask can also be set through sysfs, eg:
>
>
>
>   ```text
>   echo 5 > /sys/module/cachefiles/parameters/debug
>   ```

<a id="rst-starting-the-cache"></a>

## Starting the Cache

The cache is started by running the daemon.  The daemon opens the cache device, configures the cache and tells it to begin caching.  At that point the cache binds to fscache and the cache becomes live.

The daemon is run as follows:



```text
/sbin/cachefilesd [-d]* [-s] [-n] [-f <configfile>]
```

The flags are:

> - **`-d`**
>
>   Increase the debugging level.  This can be specified multiple times and is cumulative with itself.
>
> - **`-s`**
>
>   Send messages to stderr instead of syslog.
>
> - **`-n`**
>
>   Don't daemonise and go into background.
>
> - **`-f <configfile>`**
>
>   Use an alternative configuration file rather than the default one.

<a id="rst-things-to-avoid"></a>

## Things to Avoid

Do not mount other things within the cache as this will cause problems.  The kernel module contains its own very cut-down path walking facility that ignores mountpoints, but the daemon can't avoid them.

Do not create, rename or unlink files and directories in the cache while the cache is active, as this may cause the state to become uncertain.

Renaming files in the cache might make objects appear to be other objects (the filename is part of the lookup key).

Do not change or remove the extended attributes attached to cache files by the cache as this will cause the cache state management to get confused.

Do not create files or directories in the cache, lest the cache get confused or serve incorrect data.

Do not chmod files in the cache.  The module creates things with minimal permissions to prevent random users being able to access them directly.

<a id="rst-cache-culling"></a>

## Cache Culling

The cache may need culling occasionally to make space.  This involves discarding objects from the cache that have been used less recently than anything else.  Culling is based on the access time of data objects.  Empty directories are culled if not in use.

Cache culling is done on the basis of the percentage of blocks and the percentage of files available in the underlying filesystem.  There are six "limits":

> - **brun, frun**
>
>   If the amount of free space and the number of available files in the cache rises above both these limits, then culling is turned off.
>
> - **bcull, fcull**
>
>   If the amount of available space or the number of available files in the cache falls below either of these limits, then culling is started.
>
> - **bstop, fstop**
>
>   If the amount of available space or the number of available files in the cache falls below either of these limits, then no further allocation of disk space or files is permitted until culling has raised things above these limits again.

These must be configured thusly:



```text
0 <= bstop < bcull < brun < 100
0 <= fstop < fcull < frun < 100
```

Note that these are percentages of available space and available files, and do \_not\_ appear as 100 minus the percentage displayed by the "df" program.

The userspace daemon scans the cache to build up a table of cullable objects. These are then culled in least recently used order.  A new scan of the cache is started as soon as space is made in the table.  Objects will be skipped if their atimes have changed or if the kernel module says it is still using them.

<a id="rst-cache-structure"></a>

## Cache Structure

The CacheFiles module will create two directories in the directory it was given:

> - cache/
>
> - graveyard/

The active cache objects all reside in the first directory.  The CacheFiles kernel module moves any retired or culled objects that it can't simply unlink to the graveyard from which the daemon will actually delete them.

The daemon uses dnotify to monitor the graveyard directory, and will delete anything that appears therein.

The module represents index objects as directories with the filename "I..." or "J...".  Note that the "cache/" directory is itself a special index.

Data objects are represented as files if they have no children, or directories if they do.  Their filenames all begin "D..." or "E...".  If represented as a directory, data objects will have a file in the directory called "data" that actually holds the data.

Special objects are similar to data objects, except their filenames begin "S..." or "T...".

If an object has children, then it will be represented as a directory. Immediately in the representative directory are a collection of directories named for hash values of the child object keys with an '@' prepended.  Into this directory, if possible, will be placed the representations of the child objects:



```text
 /INDEX    /INDEX     /INDEX                            /DATA FILES
/=========/==========/=================================/================
cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400
cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...DB1ry
cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...N22ry
cache/@4a/I03nfs/@30/Ji000000000000000--fHg8hi8400/@75/Es0g000w...FP1ry
```

If the key is so long that it exceeds NAME_MAX with the decorations added on to it, then it will be cut into pieces, the first few of which will be used to make a nest of directories, and the last one of which will be the objects inside the last directory.  The names of the intermediate directories will have '+' prepended:



```text
J1223/@23/+xy...z/+kl...m/Epqr
```

Note that keys are raw data, and not only may they exceed NAME_MAX in size, they may also contain things like '/' and NUL characters, and so they may not be suitable for turning directly into a filename.

To handle this, CacheFiles will use a suitably printable filename directly and "base-64" encode ones that aren't directly suitable.  The two versions of object filenames indicate the encoding:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> OBJECT TYPE
>
> </th>
> <th>
>
>
> PRINTABLE
>
> </th>
> <th>
>
>
> ENCODED
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> Index
>
> </td>
> <td>
>
>
> "I..."
>
> </td>
> <td>
>
>
> "J..."
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Data
>
> </td>
> <td>
>
>
> "D..."
>
> </td>
> <td>
>
>
> "E..."
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Special
>
> </td>
> <td>
>
>
> "S..."
>
> </td>
> <td>
>
>
> "T..."
>
> </td>
> </tr>
> </tbody>
> </table>

Intermediate directories are always "@" or "+" as appropriate.

Each object in the cache has an extended attribute label that holds the object type ID (required to distinguish special objects) and the auxiliary data from the netfs.  The latter is used to detect stale objects in the cache and update or retire them.

Note that CacheFiles will erase from the cache any file it doesn't recognise or any file of an incorrect type (such as a FIFO file or a device file).

<a id="rst-security-model-and-selinux"></a>

## Security Model and SELinux

CacheFiles is implemented to deal properly with the LSM security features of the Linux kernel and the SELinux facility.

One of the problems that CacheFiles faces is that it is generally acting on behalf of a process, and running in that process's context, and that includes a security context that is not appropriate for accessing the cache - either because the files in the cache are inaccessible to that process, or because if the process creates a file in the cache, that file may be inaccessible to other processes.

The way CacheFiles works is to temporarily change the security context (fsuid, fsgid and actor security label) that the process acts as - without changing the security context of the process when it the target of an operation performed by some other process (so signalling and suchlike still work correctly).

When the CacheFiles module is asked to bind to its cache, it:

> 1. Finds the security label attached to the root cache directory and uses that as the security label with which it will create files.  By default, this is:
>
>
>
>    ```text
>    cachefiles_var_t
>    ```
>
> 2. Finds the security label of the process which issued the bind request (presumed to be the cachefilesd daemon), which by default will be:
>
>
>
>    ```text
>    cachefilesd_t
>    ```
>
>    and asks LSM to supply a security ID as which it should act given the daemon's label.  By default, this will be:
>
>
>
>    ```text
>    cachefiles_kernel_t
>    ```
>
>    SELinux transitions the daemon's security ID to the module's security ID based on a rule of this form in the policy:
>
>
>
>    ```text
>    type_transition <daemon's-ID> kernel_t : process <module's-ID>;
>    ```
>
>    For instance:
>
>
>
>    ```text
>    type_transition cachefilesd_t kernel_t : process cachefiles_kernel_t;
>    ```

The module's security ID gives it permission to create, move and remove files and directories in the cache, to find and access directories and files in the cache, to set and access extended attributes on cache objects, and to read and write files in the cache.

The daemon's security ID gives it only a very restricted set of permissions: it may scan directories, stat files and erase files and directories.  It may not read or write files in the cache, and so it is precluded from accessing the data cached therein; nor is it permitted to create new files in the cache.

There are policy source files available in:

> [https://people.redhat.com/\~dhowells/fscache/cachefilesd-0.8.tar.bz2](<https://people.redhat.com/~dhowells/fscache/cachefilesd-0.8.tar.bz2>)

and later versions.  In that tarball, see the files:



```text
cachefilesd.te
cachefilesd.fc
cachefilesd.if
```

They are built and installed directly by the RPM.

If a non-RPM based system is being used, then copy the above files to their own directory and run:



```text
make -f /usr/share/selinux/devel/Makefile
semodule -i cachefilesd.pp
```

You will need checkpolicy and selinux-policy-devel installed prior to the build.

By default, the cache is located in /var/fscache, but if it is desirable that it should be elsewhere, than either the above policy files must be altered, or an auxiliary policy must be installed to label the alternate location of the cache.

For instructions on how to add an auxiliary policy to enable the cache to be located elsewhere when SELinux is in enforcing mode, please see:



```text
/usr/share/doc/cachefilesd-*/move-cache.txt
```

When the cachefilesd rpm is installed; alternatively, the document can be found in the sources.

<a id="rst-a-note-on-security"></a>

## A Note on Security

CacheFiles makes use of the split security in the task_struct.  It allocates its own task_security structure, and redirects current-&gt;cred to point to it when it acts on behalf of another process, in that process's context.

The reason it does this is that it calls vfs_mkdir() and suchlike rather than bypassing security and calling inode ops directly.  Therefore the VFS and LSM may deny the CacheFiles access to the cache data because under some circumstances the caching code is running in the security context of whatever process issued the original syscall on the netfs.

Furthermore, should CacheFiles create a file or directory, the security parameters with that object is created (UID, GID, security label) would be derived from that process that issued the system call, thus potentially preventing other processes from accessing the cache - including CacheFiles's cache management daemon (cachefilesd).

What is required is to temporarily override the security of the process that issued the system call.  We can't, however, just do an in-place change of the security data as that affects the process as an object, not just as a subject. This means it may lose signals or ptrace events for example, and affects what the process looks like in /proc.

So CacheFiles makes use of a logical split in the security between the objective security (task-&gt;real_cred) and the subjective security (task-&gt;cred). The objective security holds the intrinsic security properties of a process and is never overridden.  This is what appears in /proc, and is what is used when a process is the target of an operation by some other process (SIGKILL for example).

The subjective security holds the active security properties of a process, and may be overridden.  This is not seen externally, and is used when a process acts upon another object, for example SIGKILLing another process or opening a file.

LSM hooks exist that allow SELinux (or Smack or whatever) to reject a request for CacheFiles to run in a context of a specific security label, or to create files and directories with another security label.

<a id="rst-statistical-information"></a>

## Statistical Information

If FS-Cache is compiled with the following option enabled:



```text
CONFIG_CACHEFILES_HISTOGRAM=y
```

then it will gather certain statistics and display them through a proc file.

> /proc/fs/cachefiles/histogram
>
> >
> >
> > ```text
> > cat /proc/fs/cachefiles/histogram
> > JIFS  SECS  LOOKUPS   MKDIRS    CREATES
> > ===== ===== ========= ========= =========
> > ```
> >
> > This shows the breakdown of the number of times each amount of time between 0 jiffies and HZ-1 jiffies a variety of tasks took to run.  The columns are as follows:
> >
> > >
> > > <table>
> > > <thead>
> > > <tr>
> > > <th>
> > >
> > >
> > > COLUMN
> > >
> > > </th>
> > > <th>
> > >
> > >
> > > TIME MEASUREMENT
> > >
> > > </th>
> > > </tr>
> > > </thead>
> > > <tbody>
> > > <tr>
> > > <td>
> > >
> > >
> > > LOOKUPS
> > >
> > > </td>
> > > <td>
> > >
> > >
> > > Length of time to perform a lookup on the backing fs
> > >
> > > </td>
> > > </tr>
> > > <tr>
> > > <td>
> > >
> > >
> > > MKDIRS
> > >
> > > </td>
> > > <td>
> > >
> > >
> > > Length of time to perform a mkdir on the backing fs
> > >
> > > </td>
> > > </tr>
> > > <tr>
> > > <td>
> > >
> > >
> > > CREATES
> > >
> > > </td>
> > > <td>
> > >
> > >
> > > Length of time to perform a create on the backing fs
> > >
> > > </td>
> > > </tr>
> > > </tbody>
> > > </table>
> >
> > Each row shows the number of events that took a particular range of times. Each step is 1 jiffy in size.  The JIFS column indicates the particular jiffy range covered, and the SECS field the equivalent number of seconds.

<a id="rst-debugging"></a>

## Debugging

If CONFIG_CACHEFILES_DEBUG is enabled, the CacheFiles facility can have runtime debugging enabled by adjusting the value in:



```text
/sys/module/cachefiles/parameters/debug
```

This is a bitmask of debugging streams to enable:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> BIT
>
> </th>
> <th>
>
>
> VALUE
>
> </th>
> <th>
>
>
> STREAM
>
> </th>
> <th>
>
>
> POINT
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> General
>
> </td>
> <td>
>
>
> Function entry trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Function exit trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> General
>
> </td>
> </tr>
> </tbody>
> </table>

The appropriate set of values should be OR'd together and the result written to the control file.  For example:



```text
echo $((1|4|8)) >/sys/module/cachefiles/parameters/debug
```

will turn on all function entry debugging.

<a id="rst-on-demand-read"></a>

## On-demand Read

When working in its original mode, CacheFiles serves as a local cache for a remote networking fs - while in on-demand read mode, CacheFiles can boost the scenario where on-demand read semantics are needed, e.g. container image distribution.

The essential difference between these two modes is seen when a cache miss occurs: In the original mode, the netfs will fetch the data from the remote server and then write it to the cache file; in on-demand read mode, fetching the data and writing it into the cache is delegated to a user daemon.

`CONFIG_CACHEFILES_ONDEMAND` should be enabled to support on-demand read mode.

<a id="rst-protocol-communication"></a>

### Protocol Communication

The on-demand read mode uses a simple protocol for communication between kernel and user daemon. The protocol can be modeled as:



```text
kernel --[request]--> user daemon --[reply]--> kernel
```

CacheFiles will send requests to the user daemon when needed.  The user daemon should poll the devnode ('/dev/cachefiles') to check if there's a pending request to be processed.  A POLLIN event will be returned when there's a pending request.

The user daemon then reads the devnode to fetch a request to process.  It should be noted that each read only gets one request. When it has finished processing the request, the user daemon should write the reply to the devnode.

Each request starts with a message header of the form:



```text
struct cachefiles_msg {
        __u32 msg_id;
        __u32 opcode;
        __u32 len;
        __u32 object_id;
        __u8  data[];
};
```

where:

> - `msg_id` is a unique ID identifying this request among all pending requests.
>
> - `opcode` indicates the type of this request.
>
> - `object_id` is a unique ID identifying the cache file operated on.
>
> - `data` indicates the payload of this request.
>
> - `len` indicates the whole length of this request, including the header and following type-specific payload.

<a id="rst-turning-on-on-demand-mode"></a>

### Turning on On-demand Mode

An optional parameter becomes available to the "bind" command:



```text
bind [ondemand]
```

When the "bind" command is given no argument, it defaults to the original mode. When it is given the "ondemand" argument, i.e. "bind ondemand", on-demand read mode will be enabled.

<a id="rst-the-open-request"></a>

### The OPEN Request

When the netfs opens a cache file for the first time, a request with the CACHEFILES_OP_OPEN opcode, a.k.a an OPEN request will be sent to the user daemon.  The payload format is of the form:



```text
struct cachefiles_open {
        __u32 volume_key_size;
        __u32 cookie_key_size;
        __u32 fd;
        __u32 flags;
        __u8  data[];
};
```

where:

> - `data` contains the volume_key followed directly by the cookie_key. The volume key is a NUL-terminated string; the cookie key is binary data.
>
> - `volume_key_size` indicates the size of the volume key in bytes.
>
> - `cookie_key_size` indicates the size of the cookie key in bytes.
>
> - `fd` indicates an anonymous fd referring to the cache file, through which the user daemon can perform write/llseek file operations on the cache file.

The user daemon can use the given (volume_key, cookie_key) pair to distinguish the requested cache file.  With the given anonymous fd, the user daemon can fetch the data and write it to the cache file in the background, even when kernel has not triggered a cache miss yet.

Be noted that each cache file has a unique object_id, while it may have multiple anonymous fds.  The user daemon may duplicate anonymous fds from the initial anonymous fd indicated by the @fd field through dup().  Thus each object_id can be mapped to multiple anonymous fds, while the usr daemon itself needs to maintain the mapping.

When implementing a user daemon, please be careful of RLIMIT_NOFILE, `/proc/sys/fs/nr_open` and `/proc/sys/fs/file-max`.  Typically these needn't be huge since they're related to the number of open device blobs rather than open files of each individual filesystem.

The user daemon should reply the OPEN request by issuing a "copen" (complete open) command on the devnode:



```text
copen <msg_id>,<cache_size>
```

where:

> - `msg_id` must match the msg_id field of the OPEN request.
>
> - When &gt;= 0, `cache_size` indicates the size of the cache file; when &lt; 0, `cache_size` indicates any error code encountered by the user daemon.

<a id="rst-the-close-request"></a>

### The CLOSE Request

When a cookie withdrawn, a CLOSE request (opcode CACHEFILES_OP_CLOSE) will be sent to the user daemon.  This tells the user daemon to close all anonymous fds associated with the given object_id.  The CLOSE request has no extra payload, and shouldn't be replied.

<a id="rst-the-read-request"></a>

### The READ Request

When a cache miss is encountered in on-demand read mode, CacheFiles will send a READ request (opcode CACHEFILES_OP_READ) to the user daemon. This tells the user daemon to fetch the contents of the requested file range.  The payload is of the form:



```text
struct cachefiles_read {
        __u64 off;
        __u64 len;
};
```

where:

> - `off` indicates the starting offset of the requested file range.
>
> - `len` indicates the length of the requested file range.

When it receives a READ request, the user daemon should fetch the requested data and write it to the cache file identified by object_id.

When it has finished processing the READ request, the user daemon should reply by using the CACHEFILES_IOC_READ_COMPLETE ioctl on one of the anonymous fds associated with the object_id given in the READ request.  The ioctl is of the form:



```text
ioctl(fd, CACHEFILES_IOC_READ_COMPLETE, msg_id);
```

where:

> - `fd` is one of the anonymous fds associated with the object_id given.
>
> - `msg_id` must match the msg_id field of the READ request.

---

# General Filesystem Caching

_Peios Kernel / Internals / Filesystems / caching_

> This facility is a general purpose cache for network filesystems, though it could be used for caching other things such as ISO9660 filesystems too.

<a id="rst-general-filesystem-caching"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

This facility is a general purpose cache for network filesystems, though it could be used for caching other things such as ISO9660 filesystems too.

FS-Cache mediates between cache backends (such as CacheFiles) and network filesystems:



```text
+---------+
|         |                                    +--------------+
|   NFS   |--+                                 |              |
|         |  |                             +-->|   CacheFS    |
+---------+  |               +----------+  |   |  /dev/hda5   |
             |               |          |  |   +--------------+
+---------+  +-------------->|          |  |
|         |      +-------+   |          |--+
|   AFS   |----->|       |   | FS-Cache |
|         |      | netfs |-->|          |--+
+---------+  +-->|  lib  |   |          |  |
             |   |       |   |          |  |   +--------------+
+---------+  |   +-------+   +----------+  |   |              |
|         |  |                             +-->|  CacheFiles  |
|   9P    |--+                                 |  /var/cache  |
|         |                                    +--------------+
+---------+
```

Or to look at it another way, FS-Cache is a module that provides a caching facility to a network filesystem such that the cache is transparent to the user:



```text
+---------+
|         |
| Server  |
|         |
+---------+
     |                  NETWORK
~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     |
     |           +----------+
     V           |          |
+---------+      |          |
|         |      |          |
|   NFS   |----->| FS-Cache |
|         |      |          |--+
+---------+      |          |  |   +--------------+   +--------------+
     |           |          |  |   |              |   |              |
     V           +----------+  +-->|  CacheFiles  |-->|  Ext3        |
+---------+                        |  /var/cache  |   |  /dev/sda6   |
|         |                        +--------------+   +--------------+
|   VFS   |                                ^                     ^
|         |                                |                     |
+---------+                                +--------------+      |
     |                  KERNEL SPACE                      |      |
~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|~~~~~~|~~~~
     |                  USER SPACE                        |      |
     V                                                    |      |
+---------+                                           +--------------+
|         |                                           |              |
| Process |                                           | cachefilesd  |
|         |                                           |              |
+---------+                                           +--------------+
```

FS-Cache does not follow the idea of completely loading every netfs file opened in its entirety into a cache before permitting it to be accessed and then serving the pages out of that cache rather than the netfs inode because:

> 1. It must be practical to operate without a cache.
>
> 2. The size of any accessible file must not be limited to the size of the cache.
>
> 3. The combined size of all opened files (this includes mapped libraries) must not be limited to the size of the cache.
>
> 4. The user should not be forced to download an entire file just to do a one-off access of a small portion of it (such as might be done with the "file" program).

It instead serves the cache out in chunks as and when requested by the netfs using it.

FS-Cache provides the following facilities:

> - More than one cache can be used at once.  Caches can be selected explicitly by use of tags.
>
> - Caches can be added / removed at any time, even whilst being accessed.
>
> - The netfs is provided with an interface that allows either party to withdraw caching facilities from a file (required for (2)).
>
> - The interface to the netfs returns as few errors as possible, preferring rather to let the netfs remain oblivious.
>
> - There are three types of cookie: cache, volume and data file cookies. Cache cookies represent the cache as a whole and are not normally visible to the netfs; the netfs gets a volume cookie to represent a collection of files (typically something that a netfs would get for a superblock); and data file cookies are used to cache data (something that would be got for an inode).
>
> - Volumes are matched using a key.  This is a printable string that is used to encode all the information that might be needed to distinguish one superblock, say, from another.  This would be a compound of things like cell name or server address, volume name or share path.  It must be a valid pathname.
>
> - Cookies are matched using a key.  This is a binary blob and is used to represent the object within a volume (so the volume key need not form part of the blob).  This might include things like an inode number and uniquifier or a file handle.
>
> - Cookie resources are set up and pinned by marking the cookie in-use. This prevents the backing resources from being culled.  Timed garbage collection is employed to eliminate cookies that haven't been used for a short while, thereby reducing resource overload.  This is intended to be used when a file is opened or closed.
>
>   A cookie can be marked in-use multiple times simultaneously; each mark must be unused.
>
> - Begin/end access functions are provided to delay cache withdrawal for the duration of an operation and prevent structs from being freed whilst we're looking at them.
>
> - Data I/O is done by asynchronous DIO to/from a buffer described by the netfs using an iov_iter.
>
> - An invalidation facility is available to discard data from the cache and to deal with I/O that's in progress that is accessing old data.
>
> - Cookies can be "retired" upon release, thereby causing the object to be removed from the cache.

The netfs API to FS-Cache can be found in:

> [Documentation/filesystems/caching/netfs-api.rst](/kernel/internals/filesystems/caching/netfs-api.md)

The cache backend API to FS-Cache can be found in:

> [Documentation/filesystems/caching/backend-api.rst](/kernel/internals/filesystems/caching/backend-api.md)

<a id="rst-statistical-information"></a>

## Statistical Information

If FS-Cache is compiled with the following options enabled:



```text
CONFIG_FSCACHE_STATS=y
```

then it will gather certain statistics and display them through:

> /proc/fs/fscache/stats

This shows counts of a number of events that can happen in FS-Cache:


<table>
<thead>
<tr>
<th>


CLASS

</th>
<th>


EVENT

</th>
<th>


MEANING

</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="4">


Cookies

</td>
<td>


n=N

</td>
<td>


Number of data storage cookies allocated

</td>
</tr>
<tr>
<td>


v=N

</td>
<td>


Number of volume index cookies allocated

</td>
</tr>
<tr>
<td>


vcol=N

</td>
<td>


Number of volume index key collisions

</td>
</tr>
<tr>
<td>


voom=N

</td>
<td>


Number of OOM events when allocating volume cookies

</td>
</tr>
<tr>
<td rowspan="3">


Acquire

</td>
<td>


n=N

</td>
<td>


Number of acquire cookie requests seen

</td>
</tr>
<tr>
<td>


ok=N

</td>
<td>


Number of acq reqs succeeded

</td>
</tr>
<tr>
<td>


oom=N

</td>
<td>


Number of acq reqs failed on ENOMEM

</td>
</tr>
<tr>
<td rowspan="5">


LRU

</td>
<td>


n=N

</td>
<td>


Number of cookies currently on the LRU

</td>
</tr>
<tr>
<td>


exp=N

</td>
<td>


Number of cookies expired off of the LRU

</td>
</tr>
<tr>
<td>


rmv=N

</td>
<td>


Number of cookies removed from the LRU

</td>
</tr>
<tr>
<td>


drp=N

</td>
<td>


Number of LRU'd cookies relinquished/withdrawn

</td>
</tr>
<tr>
<td>


at=N

</td>
<td>


Time till next LRU cull (jiffies)

</td>
</tr>
<tr>
<td>


Invals

</td>
<td>


n=N

</td>
<td>


Number of invalidations

</td>
</tr>
<tr>
<td rowspan="3">


Updates

</td>
<td>


n=N

</td>
<td>


Number of update cookie requests seen

</td>
</tr>
<tr>
<td>


rsz=N

</td>
<td>


Number of resize requests

</td>
</tr>
<tr>
<td>


rsn=N

</td>
<td>


Number of skipped resize requests

</td>
</tr>
<tr>
<td rowspan="3">


Relinqs

</td>
<td>


n=N

</td>
<td>


Number of relinquish cookie requests seen

</td>
</tr>
<tr>
<td>


rtr=N

</td>
<td>


Number of rlq reqs with retire=true

</td>
</tr>
<tr>
<td>


drop=N

</td>
<td>


Number of cookies no longer blocking re-acquisition

</td>
</tr>
<tr>
<td rowspan="3">


NoSpace

</td>
<td>


nwr=N

</td>
<td>


Number of write requests refused due to lack of space

</td>
</tr>
<tr>
<td>


ncr=N

</td>
<td>


Number of create requests refused due to lack of space

</td>
</tr>
<tr>
<td>


cull=N

</td>
<td>


Number of objects culled to make space

</td>
</tr>
<tr>
<td rowspan="2">


IO

</td>
<td>


rd=N

</td>
<td>


Number of read operations in the cache

</td>
</tr>
<tr>
<td>


wr=N

</td>
<td>


Number of write operations in the cache

</td>
</tr>
</tbody>
</table>

Netfslib will also add some stats counters of its own.

<a id="rst-cache-list"></a>

## Cache List

FS-Cache provides a list of cache cookies:

> /proc/fs/fscache/cookies

This will look something like:



```text
# cat /proc/fs/fscache/caches
CACHE    REF   VOLS  OBJS  ACCES S NAME
======== ===== ===== ===== ===== = ===============
00000001     2     1  2123     1 A default
```

where the columns are:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COLUMN
>
> </th>
> <th>
>
>
> DESCRIPTION
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> CACHE
>
> </td>
> <td>
>
>
> Cache cookie debug ID (also appears in traces)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> REF
>
> </td>
> <td>
>
>
> Number of references on the cache cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> VOLS
>
> </td>
> <td>
>
>
> Number of volumes cookies in this cache
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> OBJS
>
> </td>
> <td>
>
>
> Number of cache objects in use
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ACCES
>
> </td>
> <td>
>
>
> Number of accesses pinning the cache
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> S
>
> </td>
> <td>
>
>
> State
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> NAME
>
> </td>
> <td>
>
>
> Name of the cache.
>
> </td>
> </tr>
> </tbody>
> </table>

The state can be (-) Inactive, (P)reparing, (A)ctive, (E)rror or (W)ithdrawing.

<a id="rst-volume-list"></a>

## Volume List

FS-Cache provides a list of volume cookies:

> /proc/fs/fscache/volumes

This will look something like:



```text
VOLUME   REF   nCOOK ACC FL CACHE           KEY
======== ===== ===== === == =============== ================
00000001    55    54   1 00 default         afs,example.com,100058
```

where the columns are:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COLUMN
>
> </th>
> <th>
>
>
> DESCRIPTION
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> VOLUME
>
> </td>
> <td>
>
>
> The volume cookie debug ID (also appears in traces)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> REF
>
> </td>
> <td>
>
>
> Number of references on the volume cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nCOOK
>
> </td>
> <td>
>
>
> Number of cookies in the volume
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ACC
>
> </td>
> <td>
>
>
> Number of accesses pinning the cache
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> FL
>
> </td>
> <td>
>
>
> Flags on the volume cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> CACHE
>
> </td>
> <td>
>
>
> Name of the cache or "-"
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KEY
>
> </td>
> <td>
>
>
> The indexing key for the volume
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-cookie-list"></a>

## Cookie List

FS-Cache provides a list of cookies:

> /proc/fs/fscache/cookies

This will look something like:



```text
# head /proc/fs/fscache/cookies
COOKIE   VOLUME   REF ACT ACC S FL DEF
======== ======== === === === = == ================
00000435 00000001   1   0  -1 - 08 0000000201d080070000000000000000, 0000000000000000
00000436 00000001   1   0  -1 - 00 0000005601d080080000000000000000, 0000000000000051
00000437 00000001   1   0  -1 - 08 00023b3001d0823f0000000000000000, 0000000000000000
00000438 00000001   1   0  -1 - 08 0000005801d0807b0000000000000000, 0000000000000000
00000439 00000001   1   0  -1 - 08 00023b3201d080a10000000000000000, 0000000000000000
0000043a 00000001   1   0  -1 - 08 00023b3401d080a30000000000000000, 0000000000000000
0000043b 00000001   1   0  -1 - 08 00023b3601d080b30000000000000000, 0000000000000000
0000043c 00000001   1   0  -1 - 08 00023b3801d080b40000000000000000, 0000000000000000
```

where the columns are:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> COLUMN
>
> </th>
> <th>
>
>
> DESCRIPTION
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> COOKIE
>
> </td>
> <td>
>
>
> The cookie debug ID (also appears in traces)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> VOLUME
>
> </td>
> <td>
>
>
> The parent volume cookie debug ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> REF
>
> </td>
> <td>
>
>
> Number of references on the volume cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ACT
>
> </td>
> <td>
>
>
> Number of times the cookie is marked for in use
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ACC
>
> </td>
> <td>
>
>
> Number of access pins in the cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> S
>
> </td>
> <td>
>
>
> State of the cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> FL
>
> </td>
> <td>
>
>
> Flags on the cookie
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> DEF
>
> </td>
> <td>
>
>
> Key, auxiliary data
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-debugging"></a>

## Debugging

If CONFIG_NETFS_DEBUG is enabled, the FS-Cache facility and NETFS support can have runtime debugging enabled by adjusting the value in:



```text
/sys/module/netfs/parameters/debug
```

This is a bitmask of debugging streams to enable:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> BIT
>
> </th>
> <th>
>
>
> VALUE
>
> </th>
> <th>
>
>
> STREAM
>
> </th>
> <th>
>
>
> POINT
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> Cache management
>
> </td>
> <td>
>
>
> Function entry trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Function exit trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> General
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 8
>
> </td>
> <td>
>
>
> Cookie management
>
> </td>
> <td>
>
>
> Function entry trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 16
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Function exit trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> 32
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> General
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 6-8
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> (Not used)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 9
>
> </td>
> <td>
>
>
> 512
>
> </td>
> <td>
>
>
> I/O operation management
>
> </td>
> <td>
>
>
> Function entry trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10
>
> </td>
> <td>
>
>
> 1024
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Function exit trace
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 2048
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> General
>
> </td>
> </tr>
> </tbody>
> </table>

The appropriate set of values should be OR'd together and the result written to the control file.  For example:



```text
echo $((1|8|512)) >/sys/module/netfs/parameters/debug
```

will turn on all function entry debugging.

---

# Network Filesystem Caching API

_Peios Kernel / Internals / Filesystems / caching_

> Fscache provides an API by which a network filesystem can make use of local caching facilities. The API is arranged around a number of principles:

<a id="rst-network-filesystem-caching-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Fscache provides an API by which a network filesystem can make use of local caching facilities.  The API is arranged around a number of principles:

> 1. A cache is logically organised into volumes and data storage objects within those volumes.
>
> 2. Volumes and data storage objects are represented by various types of cookie.
>
> 3. Cookies have keys that distinguish them from their peers.
>
> 4. Cookies have coherency data that allows a cache to determine if the cached data is still valid.
>
> 5. I/O is done asynchronously where possible.

This API is used by:



```text
#include <linux/fscache.h>.
```

<!-- This document contains the following sections:

 (1) Overview
 (2) Volume registration
 (3) Data file registration
 (4) Declaring a cookie to be in use
 (5) Resizing a data file (truncation)
 (6) Data I/O API
 (7) Data file coherency
 (8) Data file invalidation
 (9) Write back resource management
(10) Caching of local modifications
(11) Page release and invalidation -->

<a id="rst-overview"></a>

## Overview

The fscache hierarchy is organised on two levels from a network filesystem's point of view.  The upper level represents "volumes" and the lower level represents "data storage objects".  These are represented by two types of cookie, hereafter referred to as "volume cookies" and "cookies".

A network filesystem acquires a volume cookie for a volume using a volume key, which represents all the information that defines that volume (e.g. cell name or server address, volume ID or share name).  This must be rendered as a printable string that can be used as a directory name (ie. no '/' characters and shouldn't begin with a '.').  The maximum name length is one less than the maximum size of a filename component (allowing the cache backend one char for its own purposes).

A filesystem would typically have a volume cookie for each superblock.

The filesystem then acquires a cookie for each file within that volume using an object key.  Object keys are binary blobs and only need to be unique within their parent volume.  The cache backend is responsible for rendering the binary blob into something it can use and may employ hash tables, trees or whatever to improve its ability to find an object.  This is transparent to the network filesystem.

A filesystem would typically have a cookie for each inode, and would acquire it in iget and relinquish it when evicting the cookie.

Once it has a cookie, the filesystem needs to mark the cookie as being in use. This causes fscache to send the cache backend off to look up/create resources for the cookie in the background, to check its coherency and, if necessary, to mark the object as being under modification.

A filesystem would typically "use" the cookie in its file open routine and unuse it in file release and it needs to use the cookie around calls to truncate the cookie locally.  It *also* needs to use the cookie when the pagecache becomes dirty and unuse it when writeback is complete.  This is slightly tricky, and provision is made for it.

When performing a read, write or resize on a cookie, the filesystem must first begin an operation.  This copies the resources into a holding struct and puts extra pins into the cache to stop cache withdrawal from tearing down the structures being used.  The actual operation can then be issued and conflicting invalidations can be detected upon completion.

The filesystem is expected to use netfslib to access the cache, but that's not actually required and it can use the fscache I/O API directly.

<a id="rst-volume-registration"></a>

## Volume Registration

The first step for a network filesystem is to acquire a volume cookie for the volume it wants to access:



```text
struct fscache_volume *
fscache_acquire_volume(const char *volume_key,
                       const char *cache_name,
                       const void *coherency_data,
                       size_t coherency_len);
```

This function creates a volume cookie with the specified volume key as its name and notes the coherency data.

The volume key must be a printable string with no '/' characters in it.  It should begin with the name of the filesystem and should be no longer than 254 characters.  It should uniquely represent the volume and will be matched with what's stored in the cache.

The caller may also specify the name of the cache to use.  If specified, fscache will look up or create a cache cookie of that name and will use a cache of that name if it is online or comes online.  If no cache name is specified, it will use the first cache that comes to hand and set the name to that.

The specified coherency data is stored in the cookie and will be matched against coherency data stored on disk.  The data pointer may be NULL if no data is provided.  If the coherency data doesn't match, the entire cache volume will be invalidated.

This function can return errors such as EBUSY if the volume key is already in use by an acquired volume or ENOMEM if an allocation failure occurred.  It may also return a NULL volume cookie if fscache is not enabled.  It is safe to pass a NULL cookie to any function that takes a volume cookie.  This will cause that function to do nothing.

When the network filesystem has finished with a volume, it should relinquish it by calling:



```text
void fscache_relinquish_volume(struct fscache_volume *volume,
                               const void *coherency_data,
                               bool invalidate);
```

This will cause the volume to be committed or removed, and if sealed the coherency data will be set to the value supplied.  The amount of coherency data must match the length specified when the volume was acquired.  Note that all data cookies obtained in this volume must be relinquished before the volume is relinquished.

<a id="rst-data-file-registration"></a>

## Data File Registration

Once it has a volume cookie, a network filesystem can use it to acquire a cookie for data storage:



```text
struct fscache_cookie *
fscache_acquire_cookie(struct fscache_volume *volume,
                       u8 advice,
                       const void *index_key,
                       size_t index_key_len,
                       const void *aux_data,
                       size_t aux_data_len,
                       loff_t object_size)
```

This creates the cookie in the volume using the specified index key.  The index key is a binary blob of the given length and must be unique for the volume. This is saved into the cookie.  There are no restrictions on the content, but its length shouldn't exceed about three quarters of the maximum filename length to allow for encoding.

The caller should also pass in a piece of coherency data in aux_data.  A buffer of size aux_data_len will be allocated and the coherency data copied in.  It is assumed that the size is invariant over time.  The coherency data is used to check the validity of data in the cache.  Functions are provided by which the coherency data can be updated.

The file size of the object being cached should also be provided.  This may be used to trim the data and will be stored with the coherency data.

This function never returns an error, though it may return a NULL cookie on allocation failure or if fscache is not enabled.  It is safe to pass in a NULL volume cookie and pass the NULL cookie returned to any function that takes it. This will cause that function to do nothing.

When the network filesystem has finished with a cookie, it should relinquish it by calling:



```text
void fscache_relinquish_cookie(struct fscache_cookie *cookie,
                               bool retire);
```

This will cause fscache to either commit the storage backing the cookie or delete it.

<a id="rst-marking-a-cookie-in-use"></a>

## Marking A Cookie In-Use

Once a cookie has been acquired by a network filesystem, the filesystem should tell fscache when it intends to use the cookie (typically done on file open) and should say when it has finished with it (typically on file close):



```text
void fscache_use_cookie(struct fscache_cookie *cookie,
                        bool will_modify);
void fscache_unuse_cookie(struct fscache_cookie *cookie,
                          const void *aux_data,
                          const loff_t *object_size);
```

The *use* function tells fscache that it will use the cookie and, additionally, indicate if the user is intending to modify the contents locally.  If not yet done, this will trigger the cache backend to go and gather the resources it needs to access/store data in the cache.  This is done in the background, and so may not be complete by the time the function returns.

The *unuse* function indicates that a filesystem has finished using a cookie. It optionally updates the stored coherency data and object size and then decreases the in-use counter.  When the last user unuses the cookie, it is scheduled for garbage collection.  If not reused within a short time, the resources will be released to reduce system resource consumption.

A cookie must be marked in-use before it can be accessed for read, write or resize - and an in-use mark must be kept whilst there is dirty data in the pagecache in order to avoid an oops due to trying to open a file during process exit.

Note that in-use marks are cumulative.  For each time a cookie is marked in-use, it must be unused.

<a id="rst-resizing-a-data-file-truncation"></a>

## Resizing A Data File (Truncation)

If a network filesystem file is resized locally by truncation, the following should be called to notify the cache:



```text
void fscache_resize_cookie(struct fscache_cookie *cookie,
                           loff_t new_size);
```

The caller must have first marked the cookie in-use.  The cookie and the new size are passed in and the cache is synchronously resized.  This is expected to be called from `->setattr()` inode operation under the inode lock.

<a id="rst-data-i-o-api"></a>

## Data I/O API

To do data I/O operations directly through a cookie, the following functions are available:



```text
int fscache_begin_read_operation(struct netfs_cache_resources *cres,
                                 struct fscache_cookie *cookie);
int fscache_read(struct netfs_cache_resources *cres,
                 loff_t start_pos,
                 struct iov_iter *iter,
                 enum netfs_read_from_hole read_hole,
                 netfs_io_terminated_t term_func,
                 void *term_func_priv);
int fscache_write(struct netfs_cache_resources *cres,
                  loff_t start_pos,
                  struct iov_iter *iter,
                  netfs_io_terminated_t term_func,
                  void *term_func_priv);
```

The *begin* function sets up an operation, attaching the resources required to the cache resources block from the cookie.  Assuming it doesn't return an error (for instance, it will return -ENOBUFS if given a NULL cookie, but otherwise do nothing), then one of the other two functions can be issued.

The *read* and *write* functions initiate a direct-IO operation.  Both take the previously set up cache resources block, an indication of the start file position, and an I/O iterator that describes buffer and indicates the amount of data.

The read function also takes a parameter to indicate how it should handle a partially populated region (a hole) in the disk content.  This may be to ignore it, skip over an initial hole and place zeros in the buffer or give an error.

The read and write functions can be given an optional termination function that will be run on completion:



```text
typedef
void (*netfs_io_terminated_t)(void *priv, ssize_t transferred_or_error,
                              bool was_async);
```

If a termination function is given, the operation will be run asynchronously and the termination function will be called upon completion.  If not given, the operation will be run synchronously.  Note that in the asynchronous case, it is possible for the operation to complete before the function returns.

Both the read and write functions end the operation when they complete, detaching any pinned resources.

The read operation will fail with ESTALE if invalidation occurred whilst the operation was ongoing.

<a id="rst-data-file-coherency"></a>

## Data File Coherency

To request an update of the coherency data and file size on a cookie, the following should be called:



```text
void fscache_update_cookie(struct fscache_cookie *cookie,
                           const void *aux_data,
                           const loff_t *object_size);
```

This will update the cookie's coherency data and/or file size.

<a id="rst-data-file-invalidation"></a>

## Data File Invalidation

Sometimes it will be necessary to invalidate an object that contains data. Typically this will be necessary when the server informs the network filesystem of a remote third-party change - at which point the filesystem has to throw away the state and cached data that it had for an file and reload from the server.

To indicate that a cache object should be invalidated, the following should be called:



```text
void fscache_invalidate(struct fscache_cookie *cookie,
                        const void *aux_data,
                        loff_t size,
                        unsigned int flags);
```

This increases the invalidation counter in the cookie to cause outstanding reads to fail with -ESTALE, sets the coherency data and file size from the information supplied, blocks new I/O on the cookie and dispatches the cache to go and get rid of the old data.

Invalidation runs asynchronously in a worker thread so that it doesn't block too much.

<a id="rst-write-back-resource-management"></a>

## Write-Back Resource Management

To write data to the cache from network filesystem writeback, the cache resources required need to be pinned at the point the modification is made (for instance when the page is marked dirty) as it's not possible to open a file in a thread that's exiting.

The following facilities are provided to manage this:

> - An inode flag, `I_PINNING_FSCACHE_WB`, is provided to indicate that an in-use is held on the cookie for this inode.  It can only be changed if the the inode lock is held.
>
> - A flag, `unpinned_fscache_wb` is placed in the `writeback_control` struct that gets set if `__writeback_single_inode()` clears `I_PINNING_FSCACHE_WB` because all the dirty pages were cleared.

To support this, the following functions are provided:



```text
bool fscache_dirty_folio(struct address_space *mapping,
                         struct folio *folio,
                         struct fscache_cookie *cookie);
void fscache_unpin_writeback(struct writeback_control *wbc,
                             struct fscache_cookie *cookie);
void fscache_clear_inode_writeback(struct fscache_cookie *cookie,
                                   struct inode *inode,
                                   const void *aux);
```

The *set* function is intended to be called from the filesystem's `dirty_folio` address space operation.  If `I_PINNING_FSCACHE_WB` is not set, it sets that flag and increments the use count on the cookie (the caller must already have called `fscache_use_cookie()`).

The *unpin* function is intended to be called from the filesystem's `write_inode` superblock operation.  It cleans up after writing by unusing the cookie if unpinned_fscache_wb is set in the writeback_control struct.

The *clear* function is intended to be called from the netfs's `evict_inode` superblock operation.  It must be called *after* `truncate_inode_pages_final()`, but *before* `clear_inode()`.  This cleans up any hanging `I_PINNING_FSCACHE_WB`.  It also allows the coherency data to be updated.

<a id="rst-caching-of-local-modifications"></a>

## Caching of Local Modifications

If a network filesystem has locally modified data that it wants to write to the cache, it needs to mark the pages to indicate that a write is in progress, and if the mark is already present, it needs to wait for it to be removed first (presumably due to an already in-progress operation).  This prevents multiple competing DIO writes to the same storage in the cache.

Firstly, the netfs should determine if caching is available by doing something like:



```text
bool caching = fscache_cookie_enabled(cookie);
```

If caching is to be attempted, pages should be waited for and then marked using the following functions provided by the netfs helper library:



```text
void set_page_fscache(struct page *page);
void wait_on_page_fscache(struct page *page);
int wait_on_page_fscache_killable(struct page *page);
```

Once all the pages in the span are marked, the netfs can ask fscache to schedule a write of that region:



```text
void fscache_write_to_cache(struct fscache_cookie *cookie,
                            struct address_space *mapping,
                            loff_t start, size_t len, loff_t i_size,
                            netfs_io_terminated_t term_func,
                            void *term_func_priv,
                            bool caching)
```

And if an error occurs before that point is reached, the marks can be removed by calling:



```text
void fscache_clear_page_bits(struct address_space *mapping,
                             loff_t start, size_t len,
                             bool caching)
```

In these functions, a pointer to the mapping to which the source pages are attached is passed in and start and len indicate the size of the region that's going to be written (it doesn't have to align to page boundaries necessarily, but it does have to align to DIO boundaries on the backing filesystem).  The caching parameter indicates if caching should be skipped, and if false, the functions do nothing.

The write function takes some additional parameters: the cookie representing the cache object to be written to, i_size indicates the size of the netfs file and term_func indicates an optional completion function, to which term_func_priv will be passed, along with the error or amount written.

Note that the write function will always run asynchronously and will unmark all the pages upon completion before calling term_func.

<a id="rst-page-release-and-invalidation"></a>

## Page Release and Invalidation

Fscache keeps track of whether we have any data in the cache yet for a cache object we've just created.  It knows it doesn't have to do any reading until it has done a write and then the page it wrote from has been released by the VM, after which it *has* to look in the cache.

To inform fscache that a page might now be in the cache, the following function should be called from the `release_folio` address space op:



```text
void fscache_note_page_release(struct fscache_cookie *cookie);
```

if the page has been released (ie. release_folio returned true).

Page release and page invalidation should also wait for any mark left on the page to say that a DIO write is underway from that page:



```text
void wait_on_page_fscache(struct page *page);
int wait_on_page_fscache_killable(struct page *page);
```

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-fscache_acquire_volume"></a>`fscache_acquire_volume()`

```c
struct fscache_volume * fscache_acquire_volume(const char *volume_key, const char *cache_name, const void *coherency_data, size_t coherency_len)
```

Register a volume as desiring caching services

**Parameters**

- `const char *volume_key`: An identification string for the volume
- `const char *cache_name`: The name of the cache to use (or NULL for the default)
- `const void *coherency_data`: Piece of arbitrary coherency data to check (or NULL)
- `size_t coherency_len`: The size of the coherency data

**Description**

Register a volume as desiring caching services if they're available.  The
caller must provide an identifier for the volume and may also indicate which
cache it should be in.  If a preexisting volume entry is found in the cache,
the coherency data must match otherwise the entry will be invalidated.

Returns a cookie pointer on success, -ENOMEM if out of memory or -EBUSY if a
cache volume of that name is already acquired.  Note that "NULL" is a valid
cookie pointer and can be returned if caching is refused.

#### <a id="c-fscache_relinquish_volume"></a>`fscache_relinquish_volume()`

```c
void fscache_relinquish_volume(struct fscache_volume *volume, const void *coherency_data, bool invalidate)
```

Cease caching a volume

**Parameters**

- `struct fscache_volume *volume`: The volume cookie
- `const void *coherency_data`: Piece of arbitrary coherency data to set (or NULL)
- `bool invalidate`: True if the volume should be invalidated

**Description**

Indicate that a filesystem no longer desires caching services for a volume.
The caller must have relinquished all file cookies prior to calling this.
The stored coherency data is updated.

#### <a id="c-fscache_acquire_cookie"></a>`fscache_acquire_cookie()`

```c
struct fscache_cookie * fscache_acquire_cookie(struct fscache_volume *volume, u8 advice, const void *index_key, size_t index_key_len, const void *aux_data, size_t aux_data_len, loff_t object_size)
```

Acquire a cookie to represent a cache object

**Parameters**

- `struct fscache_volume *volume`: The volume in which to locate/create this cookie
- `u8 advice`: Advice flags (FSCACHE_COOKIE_ADV_*)
- `const void *index_key`: The index key for this cookie
- `size_t index_key_len`: Size of the index key
- `const void *aux_data`: The auxiliary data for the cookie (may be NULL)
- `size_t aux_data_len`: Size of the auxiliary data buffer
- `loff_t object_size`: The initial size of object

**Description**

Acquire a cookie to represent a data file within the given cache volume.

See Documentation/filesystems/caching/netfs-api.rst for a complete
description.

#### <a id="c-fscache_use_cookie"></a>`fscache_use_cookie()`

```c
void fscache_use_cookie(struct fscache_cookie *cookie, bool will_modify)
```

Request usage of cookie attached to an object

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `bool will_modify`: If cache is expected to be modified locally

**Description**

Request usage of the cookie attached to an object.  The caller should tell
the cache if the object's contents are about to be modified locally and then
the cache can apply the policy that has been set to handle this case.

#### <a id="c-fscache_unuse_cookie"></a>`fscache_unuse_cookie()`

```c
void fscache_unuse_cookie(struct fscache_cookie *cookie, const void *aux_data, const loff_t *object_size)
```

Cease usage of cookie attached to an object

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `const void *aux_data`: Updated auxiliary data (or NULL)
- `const loff_t *object_size`: Revised size of the object (or NULL)

**Description**

Cease usage of the cookie attached to an object.  When the users count
reaches zero then the cookie relinquishment will be permitted to proceed.

#### <a id="c-fscache_relinquish_cookie"></a>`fscache_relinquish_cookie()`

```c
void fscache_relinquish_cookie(struct fscache_cookie *cookie, bool retire)
```

Return the cookie to the cache, maybe discarding it

**Parameters**

- `struct fscache_cookie *cookie`: The cookie being returned
- `bool retire`: True if the cache object the cookie represents is to be discarded

**Description**

This function returns a cookie to the cache, forcibly discarding the
associated cache object if retire is set to true.

See Documentation/filesystems/caching/netfs-api.rst for a complete
description.

#### <a id="c-fscache_update_cookie"></a>`fscache_update_cookie()`

```c
void fscache_update_cookie(struct fscache_cookie *cookie, const void *aux_data, const loff_t *object_size)
```

Request that a cache object be updated

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `const void *aux_data`: The updated auxiliary data for the cookie (may be NULL)
- `const loff_t *object_size`: The current size of the object (may be NULL)

**Description**

Request an update of the index data for the cache object associated with the
cookie.  The auxiliary data on the cookie will be updated first if **aux_data**
is set and the object size will be updated and the object possibly trimmed
if **object_size** is set.

See Documentation/filesystems/caching/netfs-api.rst for a complete
description.

#### <a id="c-fscache_resize_cookie"></a>`fscache_resize_cookie()`

```c
void fscache_resize_cookie(struct fscache_cookie *cookie, loff_t new_size)
```

Request that a cache object be resized

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `loff_t new_size`: The new size of the object (may be NULL)

**Description**

Request that the size of an object be changed.

See Documentation/filesystems/caching/netfs-api.rst for a complete
description.

#### <a id="c-fscache_invalidate"></a>`fscache_invalidate()`

```c
void fscache_invalidate(struct fscache_cookie *cookie, const void *aux_data, loff_t size, unsigned int flags)
```

Notify cache that an object needs invalidation

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `const void *aux_data`: The updated auxiliary data for the cookie (may be NULL)
- `loff_t size`: The revised size of the object.
- `unsigned int flags`: Invalidation flags (FSCACHE_INVAL_*)

**Description**

Notify the cache that an object is needs to be invalidated and that it
should abort any retrievals or stores it is doing on the cache.  This
increments inval_counter on the cookie which can be used by the caller to
reconsider I/O requests as they complete.

If **flags** has FSCACHE_INVAL_DIO_WRITE set, this indicates that this is due
to a direct I/O write and will cause caching to be disabled on this cookie
until it is completely unused.

See Documentation/filesystems/caching/netfs-api.rst for a complete
description.

#### <a id="c-fscache_operation_valid"></a>`fscache_operation_valid()`

```c
const struct netfs_cache_ops * fscache_operation_valid(const struct netfs_cache_resources *cres)
```

Return true if operations resources are usable

**Parameters**

- `const struct netfs_cache_resources *cres`: The resources to check.

**Description**

Returns a pointer to the operations table if usable or NULL if not.

#### <a id="c-fscache_begin_read_operation"></a>`fscache_begin_read_operation()`

```c
int fscache_begin_read_operation(struct netfs_cache_resources *cres, struct fscache_cookie *cookie)
```

Begin a read operation for the netfs lib

**Parameters**

- `struct netfs_cache_resources *cres`: The cache resources for the read being performed
- `struct fscache_cookie *cookie`: The cookie representing the cache object

**Description**

Begin a read operation on behalf of the netfs helper library.  **cres**
indicates the cache resources to which the operation state should be
attached; **cookie** indicates the cache object that will be accessed.

**cres->inval_counter** is set from **cookie->inval_counter** for comparison at
the end of the operation.  This allows invalidation during the operation to
be detected by the caller.

**Return**

* 0          - Success
* -ENOBUFS   - No caching available
* Other error code from the cache, such as -ENOMEM.

#### <a id="c-fscache_end_operation"></a>`fscache_end_operation()`

```c
void fscache_end_operation(struct netfs_cache_resources *cres)
```

End the read operation for the netfs lib

**Parameters**

- `struct netfs_cache_resources *cres`: The cache resources for the read operation

**Description**

Clean up the resources at the end of the read request.

#### <a id="c-fscache_read"></a>`fscache_read()`

```c
int fscache_read(struct netfs_cache_resources *cres, loff_t start_pos, struct iov_iter *iter, enum netfs_read_from_hole read_hole, netfs_io_terminated_t term_func, void *term_func_priv)
```

Start a read from the cache.

**Parameters**

- `struct netfs_cache_resources *cres`: The cache resources to use
- `loff_t start_pos`: The beginning file offset in the cache file
- `struct iov_iter *iter`: The buffer to fill - and also the length
- `enum netfs_read_from_hole read_hole`: How to handle a hole in the data.
- `netfs_io_terminated_t term_func`: The function to call upon completion
- `void *term_func_priv`: The private data for **term_func**

**Description**

Start a read from the cache.  **cres** indicates the cache object to read from
and must be obtained by a call to `fscache_begin_operation()` beforehand.

The data is read into the iterator, **iter**, and that also indicates the size
of the operation.  **start_pos** is the start position in the file, though if
**seek_data** is set appropriately, the cache can use SEEK_DATA to find the
next piece of data, writing zeros for the hole into the iterator.

Upon termination of the operation, **term_func** will be called and supplied
with **term_func_priv** plus the amount of data written, if successful, or the
error code otherwise.

**read_hole** indicates how a partially populated region in the cache should be
handled.  It can be one of a number of settings:

NETFS_READ_HOLE_IGNORE - Just try to read (may return a short read).

NETFS_READ_HOLE_FAIL - Give ENODATA if we encounter a hole.

#### <a id="c-fscache_begin_write_operation"></a>`fscache_begin_write_operation()`

```c
int fscache_begin_write_operation(struct netfs_cache_resources *cres, struct fscache_cookie *cookie)
```

Begin a write operation for the netfs lib

**Parameters**

- `struct netfs_cache_resources *cres`: The cache resources for the write being performed
- `struct fscache_cookie *cookie`: The cookie representing the cache object

**Description**

Begin a write operation on behalf of the netfs helper library.  **cres**
indicates the cache resources to which the operation state should be
attached; **cookie** indicates the cache object that will be accessed.

**cres->inval_counter** is set from **cookie->inval_counter** for comparison at
the end of the operation.  This allows invalidation during the operation to
be detected by the caller.

**Return**

* 0          - Success
* -ENOBUFS   - No caching available
* Other error code from the cache, such as -ENOMEM.

#### <a id="c-fscache_write"></a>`fscache_write()`

```c
int fscache_write(struct netfs_cache_resources *cres, loff_t start_pos, struct iov_iter *iter, netfs_io_terminated_t term_func, void *term_func_priv)
```

Start a write to the cache.

**Parameters**

- `struct netfs_cache_resources *cres`: The cache resources to use
- `loff_t start_pos`: The beginning file offset in the cache file
- `struct iov_iter *iter`: The data to write - and also the length
- `netfs_io_terminated_t term_func`: The function to call upon completion
- `void *term_func_priv`: The private data for **term_func**

**Description**

Start a write to the cache.  **cres** indicates the cache object to write to and
must be obtained by a call to `fscache_begin_operation()` beforehand.

The data to be written is obtained from the iterator, **iter**, and that also
indicates the size of the operation.  **start_pos** is the start position in
the file.

Upon termination of the operation, **term_func** will be called and supplied
with **term_func_priv** plus the amount of data written, if successful, or the
error code otherwise.

#### <a id="c-fscache_clear_page_bits"></a>`fscache_clear_page_bits()`

```c
void fscache_clear_page_bits(struct address_space *mapping, loff_t start, size_t len, bool caching)
```

Clear the PG_fscache bits from a set of pages

**Parameters**

- `struct address_space *mapping`: The netfs inode to use as the source
- `loff_t start`: The start position in **mapping**
- `size_t len`: The amount of data to unlock
- `bool caching`: If PG_fscache has been set

**Description**

Clear the PG_fscache flag from a sequence of pages and wake up anyone who's
waiting.

#### <a id="c-fscache_write_to_cache"></a>`fscache_write_to_cache()`

```c
void fscache_write_to_cache(struct fscache_cookie *cookie, struct address_space *mapping, loff_t start, size_t len, loff_t i_size, netfs_io_terminated_t term_func, void *term_func_priv, bool using_pgpriv2, bool caching)
```

Save a write to the cache and clear PG_fscache

**Parameters**

- `struct fscache_cookie *cookie`: The cookie representing the cache object
- `struct address_space *mapping`: The netfs inode to use as the source
- `loff_t start`: The start position in **mapping**
- `size_t len`: The amount of data to write back
- `loff_t i_size`: The new size of the inode
- `netfs_io_terminated_t term_func`: The function to call upon completion
- `void *term_func_priv`: The private data for **term_func**
- `bool using_pgpriv2`: If we're using PG_private_2 to mark in-progress write
- `bool caching`: If we actually want to do the caching

**Description**

Helper function for a netfs to write dirty data from an inode into the cache
object that's backing it.

**start** and **len** describe the range of the data.  This does not need to be
page-aligned, but to satisfy DIO requirements, the cache may expand it up to
the page boundaries on either end.  All the pages covering the range must be
marked with PG_fscache.

If given, **term_func** will be called upon completion and supplied with
**term_func_priv**.  Note that if **using_pgpriv2** is set, the PG_private_2 flags
will have been cleared by this point, so the netfs must retain its own pin
on the mapping.

#### <a id="c-fscache_note_page_release"></a>`fscache_note_page_release()`

```c
void fscache_note_page_release(struct fscache_cookie *cookie)
```

Note that a netfs page got released

**Parameters**

- `struct fscache_cookie *cookie`: The cookie corresponding to the file

**Description**

Note that a page that has been copied to the cache has been released.  This
means that future reads will need to look in the cache to see if it's there.

---

# ext4 Data Structures and Algorithms

_Peios Kernel / Internals / Filesystems / ext4_

> Reference for ext4 Data Structures and Algorithms.

<a id="rst-ext4-data-structures-and-algorithms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1. [About this Book](</kernel/internals/filesystems/ext4/about.md>)
2. [High Level Design](</kernel/internals/filesystems/ext4/overview.md>)
3. [Global Structures](</kernel/internals/filesystems/ext4/globals.md>)
4. [Dynamic Structures](</kernel/internals/filesystems/ext4/dynamic.md>)

---

# About this Book

_Peios Kernel / Internals / Filesystems / ext4_

> This document attempts to describe the on-disk format for ext4 filesystems. The same general ideas should apply to ext2/3 filesystems as well, though they do not support all the features that ext4 supports, and the fields will be shorter.

<a id="rst-about-this-book"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document attempts to describe the on-disk format for ext4 filesystems. The same general ideas should apply to ext2/3 filesystems as well, though they do not support all the features that ext4 supports, and the fields will be shorter.

**NOTE**: This is a work in progress, based on notes that the author (djwong) made while picking apart a filesystem by hand. The data structure definitions should be current as of Linux 4.18 and e2fsprogs-1.44. All comments and corrections are welcome, since there is undoubtedly plenty of lore that might not be reflected in freshly created demonstration filesystems.

<a id="rst-license"></a>

## License

This book is licensed under the terms of the GNU Public License, v2.

<a id="rst-terminology"></a>

## Terminology

ext4 divides a storage device into an array of logical blocks both to reduce bookkeeping overhead and to increase throughput by forcing larger transfer sizes. Generally, the block size will be 4KiB (the same size as pages on x86 and the block layer's default block size), though the actual size is calculated as 2 ^ (10 + `sb.s_log_block_size`) bytes. Throughout this document, disk locations are given in terms of these logical blocks, not raw LBAs, and not 1024-byte blocks. For the sake of convenience, the logical block size will be referred to as `$block_size` throughout the rest of the document.

When referenced in `preformatted text` blocks, `sb` refers to fields in the super block, and `inode` refers to fields in an inode table entry.

<a id="rst-other-references"></a>

## Other References

Also see [https://www.nongnu.org/ext2-doc/](<https://www.nongnu.org/ext2-doc/>) for quite a collection of information about ext2/3. Here's another old reference: [http://wiki.osdev.org/Ext2](<http://wiki.osdev.org/Ext2>)

---

# Block and Inode Allocation Policy

_Peios Kernel / Internals / Filesystems / ext4_

> ext4 recognizes (better than ext3, anyway) that data locality is generally a desirably quality of a filesystem. On a spinning disk, keeping related blocks near each other reduces the amount of movement that the head actuator and disk must…

<a id="rst-block-and-inode-allocation-policy"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ext4 recognizes (better than ext3, anyway) that data locality is generally a desirably quality of a filesystem. On a spinning disk, keeping related blocks near each other reduces the amount of movement that the head actuator and disk must perform to access a data block, thus speeding up disk IO. On an SSD there of course are no moving parts, but locality can increase the size of each transfer request while reducing the total number of requests. This locality may also have the effect of concentrating writes on a single erase block, which can speed up file rewrites significantly. Therefore, it is useful to reduce fragmentation whenever possible.

The first tool that ext4 uses to combat fragmentation is the multi-block allocator. When a file is first created, the block allocator speculatively allocates 8KiB of disk space to the file on the assumption that the space will get written soon. When the file is closed, the unused speculative allocations are of course freed, but if the speculation is correct (typically the case for full writes of small files) then the file data gets written out in a single multi-block extent. A second related trick that ext4 uses is delayed allocation. Under this scheme, when a file needs more blocks to absorb file writes, the filesystem defers deciding the exact placement on the disk until all the dirty buffers are being written out to disk. By not committing to a particular placement until it's absolutely necessary (the commit timeout is hit, or sync() is called, or the kernel runs out of memory), the hope is that the filesystem can make better location decisions.

The third trick that ext4 (and ext3) uses is that it tries to keep a file's data blocks in the same block group as its inode. This cuts down on the seek penalty when the filesystem first has to read a file's inode to learn where the file's data blocks live and then seek over to the file's data blocks to begin I/O operations.

The fourth trick is that all the inodes in a directory are placed in the same block group as the directory, when feasible. The working assumption here is that all the files in a directory might be related, therefore it is useful to try to keep them all together.

The fifth trick is that the disk volume is cut up into 128MB block groups; these mini-containers are used as outlined above to try to maintain data locality. However, there is a deliberate quirk -- when a directory is created in the root directory, the inode allocator scans the block groups and puts that directory into the least heavily loaded block group that it can find. This encourages directories to spread out over a disk; as the top-level directory/file blobs fill up one block group, the allocators simply move on to the next block group. Allegedly this scheme evens out the loading on the block groups, though the author suspects that the directories which are so unlucky as to land towards the end of a spinning drive get a raw deal performance-wise.

Of course if all of these mechanisms fail, one can always use e4defrag to defragment files.

---

# Atomic Block Writes

_Peios Kernel / Internals / Filesystems / ext4_

> Atomic (untorn) block writes ensure that either the entire write is committed to disk or none of it is. This prevents "torn writes" during power loss or system crashes. The ext4 filesystem supports atomic writes (only with Direct I/O) on…

<a id="rst-atomic-block-writes"></a>
<a id="rst-atomic-writes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Atomic (untorn) block writes ensure that either the entire write is committed to disk or none of it is. This prevents "torn writes" during power loss or system crashes. The ext4 filesystem supports atomic writes (only with Direct I/O) on regular files with extents, provided the underlying storage device supports hardware atomic writes. This is supported in the following two ways:

1. **Single-fsblock Atomic Writes**: EXT4 supports atomic write operations with a single filesystem block since v6.13. In this the atomic write unit minimum and maximum sizes are both set to filesystem blocksize. e.g. doing atomic write of 16KB with 16KB filesystem blocksize on 64KB pagesize system is possible.

2. **Multi-fsblock Atomic Writes with Bigalloc**: EXT4 now also supports atomic writes spanning multiple filesystem blocks using a feature known as bigalloc. The atomic write unit's minimum and maximum sizes are determined by the filesystem block size and cluster size, based on the underlying device’s supported atomic write unit limits.

<a id="rst-requirements"></a>

## Requirements

Basic requirements for atomic writes in ext4:

> 1. The extents feature must be enabled (default for ext4)
>
> 2. The underlying block device must support atomic writes
>
> 3. For single-fsblock atomic writes:
>
>    1. A filesystem with appropriate block size (up to the page size)
>
> 4. For multi-fsblock atomic writes:
>
>    1. The bigalloc feature must be enabled
>
>    2. The cluster size must be appropriately configured

NOTE: EXT4 does not support software or COW based atomic write, which means atomic writes on ext4 are only supported if underlying storage device supports it.

<a id="rst-multi-fsblock-implementation-details"></a>

## Multi-fsblock Implementation Details

The bigalloc feature changes ext4 to allocate in units of multiple filesystem blocks, also known as clusters. With bigalloc each bit within block bitmap represents a cluster (power of 2 number of blocks) rather than individual filesystem blocks. EXT4 supports multi-fsblock atomic writes with bigalloc, subject to the following constraints. The minimum atomic write size is the larger of the fs block size and the minimum hardware atomic write unit; and the maximum atomic write size is smaller of the bigalloc cluster size and the maximum hardware atomic write unit.  Bigalloc ensures that all allocations are aligned to the cluster size, which satisfies the LBA alignment requirements of the hardware device if the start of the partition/logical volume is itself aligned correctly.

Here is the block allocation strategy in bigalloc for atomic writes:

> - For regions with fully mapped extents, no additional work is needed
>
> - For append writes, a new mapped extent is allocated
>
> - For regions that are entirely holes, unwritten extent is created
>
> - For large unwritten extents, the extent gets split into two unwritten extents of appropriate requested size
>
> - For mixed mapping regions (combinations of holes, unwritten extents, or mapped extents), ext4_map_blocks() is called in a loop with EXT4_GET_BLOCKS_ZERO flag to convert the region into a single contiguous mapped extent by writing zeroes to it and converting any unwritten extents to written, if found within the range.

Note: Writing on a single contiguous underlying extent, whether mapped or unwritten, is not inherently problematic. However, writing to a mixed mapping region (i.e. one containing a combination of mapped and unwritten extents) must be avoided when performing atomic writes.

The reason is that, atomic writes when issued via pwritev2() with the RWF_ATOMIC flag, requires that either all data is written or none at all. In the event of a system crash or unexpected power loss during the write operation, the affected region (when later read) must reflect either the complete old data or the complete new data, but never a mix of both.

To enforce this guarantee, we ensure that the write target is backed by a single, contiguous extent before any data is written. This is critical because ext4 defers the conversion of unwritten extents to written extents until the I/O completion path (typically in -&gt;end_io()). If a write is allowed to proceed over a mixed mapping region (with mapped and unwritten extents) and a failure occurs mid-write, the system could observe partially updated regions after reboot, i.e. new data over mapped areas, and stale (old) data over unwritten extents that were never marked written. This violates the atomicity and/or torn write prevention guarantee.

To prevent such torn writes, ext4 proactively allocates a single contiguous extent for the entire requested region in `ext4_iomap_alloc` via `ext4_map_blocks_atomic()`. EXT4 also force commits the current journalling transaction in case if allocation is done over mixed mapping. This ensures any pending metadata updates (like unwritten to written extents conversion) in this range are in consistent state with the file data blocks, before performing the actual write I/O. If the commit fails, the whole I/O must be aborted to prevent from any possible torn writes. Only after this step, the actual data write operation is performed by the iomap.

<a id="rst-handling-split-extents-across-leaf-blocks"></a>

## Handling Split Extents Across Leaf Blocks

There can be a special edge case where we have logically and physically contiguous extents stored in separate leaf nodes of the on-disk extent tree. This occurs because on-disk extent tree merges only happens within the leaf blocks except for a case where we have 2-level tree which can get merged and collapsed entirely into the inode. If such a layout exists and, in the worst case, the extent status cache entries are reclaimed due to memory pressure, `ext4_map_blocks()` may never return a single contiguous extent for these split leaf extents.

To address this edge case, a new get block flag `EXT4_GET_BLOCKS_QUERY_LEAF_BLOCKS flag` is added to enhance the `ext4_map_query_blocks()` lookup behavior.

This new get block flag allows `ext4_map_blocks()` to first check if there is an entry in the extent status cache for the full range. If not present, it consults the on-disk extent tree using `ext4_map_query_blocks()`. If the located extent is at the end of a leaf node, it probes the next logical block (lblk) to detect a contiguous extent in the adjacent leaf.

For now only one additional leaf block is queried to maintain efficiency, as atomic writes are typically constrained to small sizes (e.g. \[blocksize, clustersize\]).

<a id="rst-handling-journal-transactions"></a>

## Handling Journal transactions

To support multi-fsblock atomic writes, we ensure enough journal credits are reserved during:

> 1. Block allocation time in `ext4_iomap_alloc()`. We first query if there could be a mixed mapping for the underlying requested range. If yes, then we reserve credits of up to `m_len`, assuming every alternate block can be an unwritten extent followed by a hole.
>
> 2. During `->end_io()` call, we make sure a single transaction is started for doing unwritten-to-written conversion. The loop for conversion is mainly only required to handle a split extent across leaf blocks.

<a id="rst-how-to"></a>

## How to

<a id="rst-creating-filesystems-with-atomic-write-support"></a>

### Creating Filesystems with Atomic Write Support

First check the atomic write units supported by block device. See [Hardware Support](<#rst-atomic-write-bdev-support>) for more details.

For single-fsblock atomic writes with a larger block size (on systems with block size &lt; page size):



```bash
# Create an ext4 filesystem with a 16KB block size
# (requires page size >= 16KB)
mkfs.ext4 -b 16384 /dev/device
```

For multi-fsblock atomic writes with bigalloc:



```bash
# Create an ext4 filesystem with bigalloc and 64KB cluster size
mkfs.ext4 -F -O bigalloc -b 4096 -C 65536 /dev/device
```

Where `-b` specifies the block size, `-C` specifies the cluster size in bytes, and `-O bigalloc` enables the bigalloc feature.

<a id="rst-application-interface"></a>

### Application Interface

Applications can use the `pwritev2()` system call with the `RWF_ATOMIC` flag to perform atomic writes:



```c
pwritev2(fd, iov, iovcnt, offset, RWF_ATOMIC);
```

The write must be aligned to the filesystem's block size and not exceed the filesystem's maximum atomic write unit size. See `generic_atomic_write_valid()` for more details.

`statx()` system call with `STATX_WRITE_ATOMIC` flag can provide following details:

> - `stx_atomic_write_unit_min`: Minimum size of an atomic write request.
>
> - `stx_atomic_write_unit_max`: Maximum size of an atomic write request.
>
> - `stx_atomic_write_segments_max`: Upper limit for segments. The number of separate memory buffers that can be gathered into a write operation (e.g., the iovcnt parameter for IOV_ITER). Currently, this is always set to one.

The STATX_ATTR_WRITE_ATOMIC flag in `statx->attributes` is set if atomic writes are supported.

<a id="rst-hardware-support"></a>
<a id="rst-atomic-write-bdev-support"></a>

## Hardware Support

The underlying storage device must support atomic write operations. Modern NVMe and SCSI devices often provide this capability. The Linux kernel exposes this information through sysfs:

- `/sys/block/<device>/queue/atomic_write_unit_min` - Minimum atomic write size

- `/sys/block/<device>/queue/atomic_write_unit_max` - Maximum atomic write size

Nonzero values for these attributes indicate that the device supports atomic writes.

<a id="rst-see-also"></a>

## See Also

- [Bigalloc](</kernel/internals/filesystems/ext4/bigalloc.md>) - Documentation on the bigalloc feature

- [Block and Inode Allocation Policy](</kernel/internals/filesystems/ext4/allocators.md>) - Documentation on block allocation in ext4

- Support for atomic block writes in 6.13: [https://lwn.net/Articles/1009298/](<https://lwn.net/Articles/1009298/>)

---

# Extended Attributes

_Peios Kernel / Internals / Filesystems / ext4_

> Extended attributes (xattrs) are typically stored in a separate data block on the disk and referenced from inodes via inode.i_file_acl*. The first use of extended attributes seems to have been for storing file ACLs and other security data…

<a id="rst-extended-attributes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Extended attributes (xattrs) are typically stored in a separate data block on the disk and referenced from inodes via `inode.i_file_acl*`. The first use of extended attributes seems to have been for storing file ACLs and other security data (selinux). With the `user_xattr` mount option it is possible for users to store extended attributes so long as all attribute names begin with “user”; this restriction seems to have disappeared as of Linux 3.0.

There are two places where extended attributes can be found. The first place is between the end of each inode entry and the beginning of the next inode entry. For example, if inode.i_extra_isize = 28 and sb.inode_size = 256, then there are 256 - (128 + 28) = 100 bytes available for in-inode extended attribute storage. The second place where extended attributes can be found is in the block pointed to by `inode.i_file_acl`. As of Linux 3.11, it is not possible for this block to contain a pointer to a second extended attribute block (or even the remaining blocks of a cluster). In theory it is possible for each attribute's value to be stored in a separate data block, though as of Linux 3.11 the code does not permit this.

Keys are generally assumed to be ASCIIZ strings, whereas values can be strings or binary data.

Extended attributes, when stored after the inode, have a header `ext4_xattr_ibody_header` that is 4 bytes long:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


h_magic

</td>
<td>


Magic number for identification, 0xEA020000. This value is set by the Linux driver, though e2fsprogs doesn't seem to check it(?)

</td>
</tr>
</tbody>
</table>

The beginning of an extended attribute block is in `struct ext4_xattr_header`, which is 32 bytes long:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


h_magic

</td>
<td>


Magic number for identification, 0xEA020000.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


h_refcount

</td>
<td>


Reference count.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le32

</td>
<td>


h_blocks

</td>
<td>


Number of disk blocks used.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__le32

</td>
<td>


h_hash

</td>
<td>


Hash value of all attributes.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__le32

</td>
<td>


h_checksum

</td>
<td>


Checksum of the extended attribute block.

</td>
</tr>
<tr>
<td>


0x14

</td>
<td>


\__u32

</td>
<td>


h_reserved\[3\]

</td>
<td>


Zero.

</td>
</tr>
</tbody>
</table>

The checksum is calculated against the FS UUID, the 64-bit block number of the extended attribute block, and the entire block (header + entries).

Following the `struct ext4_xattr_header` or `struct ext4_xattr_ibody_header` is an array of `struct ext4_xattr_entry`; each of these entries is at least 16 bytes long. When stored in an external block, the `struct ext4_xattr_entry` entries must be stored in sorted order. The sort order is `e_name_index`, then `e_name_len`, and finally `e_name`. Attributes stored inside an inode do not need be stored in sorted order.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__u8

</td>
<td>


e_name_len

</td>
<td>


Length of name.

</td>
</tr>
<tr>
<td>


0x1

</td>
<td>


\__u8

</td>
<td>


e_name_index

</td>
<td>


Attribute name index. There is a discussion of this below.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


\__le16

</td>
<td>


e_value_offs

</td>
<td>


Location of this attribute's value on the disk block where it is stored. Multiple attributes can share the same value. For an inode attribute this value is relative to the start of the first entry; for a block this value is relative to the start of the block (i.e. the header).

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


e_value_inum

</td>
<td>


The inode where the value is stored. Zero indicates the value is in the same block as this entry. This field is only used if the INCOMPAT_EA_INODE feature is enabled.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le32

</td>
<td>


e_value_size

</td>
<td>


Length of attribute value.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__le32

</td>
<td>


e_hash

</td>
<td>


Hash value of attribute name and attribute value. The kernel doesn't update the hash for in-inode attributes, so for that case this value must be zero, because e2fsck validates any non-zero hash regardless of where the xattr lives.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


char

</td>
<td>


e_name\[e_name_len\]

</td>
<td>


Attribute name. Does not include trailing NULL.

</td>
</tr>
</tbody>
</table>

Attribute values can follow the end of the entry table. There appears to be a requirement that they be aligned to 4-byte boundaries. The values are stored starting at the end of the block and grow towards the xattr_header/xattr_entry table. When the two collide, the overflow is put into a separate disk block. If the disk block fills up, the filesystem returns -ENOSPC.

The first four fields of the `ext4_xattr_entry` are set to zero to mark the end of the key list.

<a id="rst-attribute-name-indices"></a>

## Attribute Name Indices

Logically speaking, extended attributes are a series of key=value pairs. The keys are assumed to be NULL-terminated strings. To reduce the amount of on-disk space that the keys consume, the beginning of the key string is matched against the attribute name index. If a match is found, the attribute name index field is set, and matching string is removed from the key name. Here is a map of name index values to key prefixes:


<table>
<thead>
<tr>
<th>


Name Index

</th>
<th>


Key Prefix

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


(no prefix)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


“user.”

</td>
</tr>
<tr>
<td>


2

</td>
<td>


“system.posix_acl_access”

</td>
</tr>
<tr>
<td>


3

</td>
<td>


“system.posix_acl_default”

</td>
</tr>
<tr>
<td>


4

</td>
<td>


“trusted.”

</td>
</tr>
<tr>
<td>


6

</td>
<td>


“security.”

</td>
</tr>
<tr>
<td>


7

</td>
<td>


“system.” (inline_data only?)

</td>
</tr>
<tr>
<td>


8

</td>
<td>


“system.richacl” (SuSE kernels only?)

</td>
</tr>
</tbody>
</table>

For example, if the attribute key is “user.fubar”, the attribute name index is set to 1 and the “fubar” name is recorded on disk.

<a id="rst-posix-acls"></a>

## POSIX ACLs

POSIX ACLs are stored in a reduced version of the Linux kernel (and libacl's) internal ACL format. The key difference is that the version number is different (1) and the `e_id` field is only stored for named user and group ACLs.

---

# Bigalloc

_Peios Kernel / Internals / Filesystems / ext4_

> At the moment, the default size of a block is 4KiB, which is a commonly supported page size on most MMU-capable hardware. This is fortunate, as ext4 code is not prepared to handle the case where the block size exceeds the page size.…

<a id="rst-bigalloc"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

At the moment, the default size of a block is 4KiB, which is a commonly supported page size on most MMU-capable hardware. This is fortunate, as ext4 code is not prepared to handle the case where the block size exceeds the page size. However, for a filesystem of mostly huge files, it is desirable to be able to allocate disk blocks in units of multiple blocks to reduce both fragmentation and metadata overhead. The bigalloc feature provides exactly this ability.

The bigalloc feature (EXT4_FEATURE_RO_COMPAT_BIGALLOC) changes ext4 to use clustered allocation, so that each bit in the ext4 block allocation bitmap addresses a power of two number of blocks. For example, if the file system is mainly going to be storing large files in the 4-32 megabyte range, it might make sense to set a cluster size of 1 megabyte. This means that each bit in the block allocation bitmap now addresses 256 4k blocks. This shrinks the total size of the block allocation bitmaps for a 2T file system from 64 megabytes to 256 kilobytes. It also means that a block group addresses 32 gigabytes instead of 128 megabytes, also shrinking the amount of file system overhead for metadata.

The administrator can set a block cluster size at mkfs time (which is stored in the s_log_cluster_size field in the superblock); from then on, the block bitmaps track clusters, not individual blocks. This means that block groups can be several gigabytes in size (instead of just 128MiB); however, the minimum allocation unit becomes a cluster, not a block, even for directories. TaoBao had a patchset to extend the “use units of clusters instead of blocks” to the extent tree, though it is not clear where those patches went-- they eventually morphed into “extent tree v2” but that code has not landed as of May 2015.

---

# Block and inode Bitmaps

_Peios Kernel / Internals / Filesystems / ext4_

> The data block bitmap tracks the usage of data blocks within the block group.

<a id="rst-block-and-inode-bitmaps"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The data block bitmap tracks the usage of data blocks within the block group.

The inode bitmap records which entries in the inode table are in use.

As with most bitmaps, one bit represents the usage status of one data block or inode table entry. This implies a block group size of 8 \* number_of_bytes_in_a_logical_block.

NOTE: If `BLOCK_UNINIT` is set for a given block group, various parts of the kernel and e2fsprogs code pretends that the block bitmap contains zeros (i.e. all blocks in the group are free). However, it is not necessarily the case that no blocks are in use -- if `meta_bg` is set, the bitmaps and group descriptor live inside the group. Unfortunately, ext2fs_test_block_bitmap2() will return '0' for those locations, which produces confusing debugfs output.

---

# Block Groups

_Peios Kernel / Internals / Filesystems / ext4_

> The layout of a standard block group is approximately as follows (each of these fields is discussed in a separate section below):

<a id="rst-block-groups"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-layout"></a>

## Layout

The layout of a standard block group is approximately as follows (each of these fields is discussed in a separate section below):


<table>
<thead>
<tr>
<th>


Group 0 Padding

</th>
<th>


ext4 Super Block

</th>
<th>


Group Descriptors

</th>
<th>


Reserved GDT Blocks

</th>
<th>


Data Block Bitmap

</th>
<th>


inode Bitmap

</th>
<th>


inode Table

</th>
<th>


Data Blocks

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


1024 bytes

</td>
<td>


1 block

</td>
<td>


many blocks

</td>
<td>


many blocks

</td>
<td>


1 block

</td>
<td>


1 block

</td>
<td>


many blocks

</td>
<td>


many more blocks

</td>
</tr>
</tbody>
</table>

For the special case of block group 0, the first 1024 bytes are unused, to allow for the installation of x86 boot sectors and other oddities. The superblock will start at offset 1024 bytes, whichever block that happens to be (usually 0). However, if for some reason the block size = 1024, then block 0 is marked in use and the superblock goes in block 1. For all other block groups, there is no padding.

The ext4 driver primarily works with the superblock and the group descriptors that are found in block group 0. Redundant copies of the superblock and group descriptors are written to some of the block groups across the disk in case the beginning of the disk gets trashed, though not all block groups necessarily host a redundant copy (see following paragraph for more details). If the group does not have a redundant copy, the block group begins with the data block bitmap. Note also that when the filesystem is freshly formatted, mkfs will allocate “reserve GDT block” space after the block group descriptors and before the start of the block bitmaps to allow for future expansion of the filesystem. By default, a filesystem is allowed to increase in size by a factor of 1024x over the original filesystem size.

The location of the inode table is given by `grp.bg_inode_table_*`. It is continuous range of blocks large enough to contain `sb.s_inodes_per_group * sb.s_inode_size` bytes.

As for the ordering of items in a block group, it is generally established that the super block and the group descriptor table, if present, will be at the beginning of the block group. The bitmaps and the inode table can be anywhere, and it is quite possible for the bitmaps to come after the inode table, or for both to be in different groups (flex_bg). Leftover space is used for file data blocks, indirect block maps, extent tree blocks, and extended attributes.

<a id="rst-flexible-block-groups"></a>

## Flexible Block Groups

Starting in ext4, there is a new feature called flexible block groups (flex_bg). In a flex_bg, several block groups are tied together as one logical block group; the bitmap spaces and the inode table space in the first block group of the flex_bg are expanded to include the bitmaps and inode tables of all other block groups in the flex_bg. For example, if the flex_bg size is 4, then group 0 will contain (in order) the superblock, group descriptors, data block bitmaps for groups 0-3, inode bitmaps for groups 0-3, inode tables for groups 0-3, and the remaining space in group 0 is for file data. The effect of this is to group the block group metadata close together for faster loading, and to enable large files to be continuous on disk. Backup copies of the superblock and group descriptors are always at the beginning of block groups, even if flex_bg is enabled. The number of block groups that make up a flex_bg is given by 2 ^ `sb.s_log_groups_per_flex`.

<a id="rst-meta-block-groups"></a>

## Meta Block Groups

Without the option META_BG, for safety concerns, all block group descriptors copies are kept in the first block group. Given the default 128MiB(2^27 bytes) block group size and 64-byte group descriptors, ext4 can have at most 2^27/64 = 2^21 block groups. This limits the entire filesystem size to 2^21 \* 2^27 = 2^48bytes or 256TiB.

The solution to this problem is to use the metablock group feature (META_BG), which is already in ext3 for all 2.6 releases. With the META_BG feature, ext4 filesystems are partitioned into many metablock groups. Each metablock group is a cluster of block groups whose group descriptor structures can be stored in a single disk block. For ext4 filesystems with 4 KB block size, a single metablock group partition includes 64 block groups, or 8 GiB of disk space. The metablock group feature moves the location of the group descriptors from the congested first block group of the whole filesystem into the first group of each metablock group itself. The backups are in the second and last group of each metablock group. This increases the 2^21 maximum block groups limit to the hard limit 2^32, allowing support for a 512PiB filesystem.

The change in the filesystem format replaces the current scheme where the superblock is followed by a variable-length set of block group descriptors. Instead, the superblock and a single block group descriptor block is placed at the beginning of the first, second, and last block groups in a meta-block group. A meta-block group is a collection of block groups which can be described by a single block group descriptor block. Since the size of the block group descriptor structure is 64 bytes, a meta-block group contains 16 block groups for filesystems with a 1KB block size, and 64 block groups for filesystems with a 4KB blocksize. Filesystems can either be created using this new block group descriptor layout, or existing filesystems can be resized on-line, and the field s_first_meta_bg in the superblock will indicate the first block group using this new layout.

Please see an important note about `BLOCK_UNINIT` in the section about block and inode bitmaps.

<a id="rst-lazy-block-group-initialization"></a>

## Lazy Block Group Initialization

A new feature for ext4 are three block group descriptor flags that enable mkfs to skip initializing other parts of the block group metadata. Specifically, the INODE_UNINIT and BLOCK_UNINIT flags mean that the inode and block bitmaps for that group can be calculated and therefore the on-disk bitmap blocks are not initialized. This is generally the case for an empty block group or a block group containing only fixed-location block group metadata. The INODE_ZEROED flag means that the inode table has been initialized; mkfs will unset this flag and rely on the kernel to initialize the inode tables in the background.

By not writing zeroes to the bitmaps and inode table, mkfs time is reduced considerably. Note the feature flag is RO_COMPAT_GDT_CSUM, but the dumpe2fs output prints this as “uninit_bg”. They are the same thing.

---

# Blocks

_Peios Kernel / Internals / Filesystems / ext4_

> ext4 allocates storage space in units of “blocks”. A block is a group of sectors between 1KiB and 64KiB, and the number of sectors must be an integral power of 2. Blocks are in turn grouped into larger units called block groups. Block size…

<a id="rst-blocks"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ext4 allocates storage space in units of “blocks”. A block is a group of sectors between 1KiB and 64KiB, and the number of sectors must be an integral power of 2. Blocks are in turn grouped into larger units called block groups. Block size is specified at mkfs time and typically is 4KiB. You may experience mounting problems if block size is greater than page size (i.e. 64KiB blocks on a i386 which only has 4KiB memory pages). By default a filesystem can contain 2^32 blocks; if the '64bit' feature is enabled, then a filesystem can have 2^64 blocks. The location of structures is stored in terms of the block number the structure lives in and not the absolute offset on disk.

For 32-bit filesystems, limits are as follows:


<table>
<thead>
<tr>
<th>


Item

</th>
<th>


1KiB

</th>
<th>


2KiB

</th>
<th>


4KiB

</th>
<th>


64KiB

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Blocks

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
</tr>
<tr>
<td>


Inodes

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
</tr>
<tr>
<td>


File System Size

</td>
<td>


4TiB

</td>
<td>


8TiB

</td>
<td>


16TiB

</td>
<td>


256TiB

</td>
</tr>
<tr>
<td>


Blocks Per Block Group

</td>
<td>


8,192

</td>
<td>


16,384

</td>
<td>


32,768

</td>
<td>


524,288

</td>
</tr>
<tr>
<td>


Inodes Per Block Group

</td>
<td>


8,192

</td>
<td>


16,384

</td>
<td>


32,768

</td>
<td>


524,288

</td>
</tr>
<tr>
<td>


Block Group Size

</td>
<td>


8MiB

</td>
<td>


32MiB

</td>
<td>


128MiB

</td>
<td>


32GiB

</td>
</tr>
<tr>
<td>


Blocks Per File, Extents

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
</tr>
<tr>
<td>


Blocks Per File, Block Maps

</td>
<td>


16,843,020

</td>
<td>


134,480,396

</td>
<td>


1,074,791,436

</td>
<td>


4,398,314,962,956 (really 2^32 due to field size limitations)

</td>
</tr>
<tr>
<td>


File Size, Extents

</td>
<td>


4TiB

</td>
<td>


8TiB

</td>
<td>


16TiB

</td>
<td>


256TiB

</td>
</tr>
<tr>
<td>


File Size, Block Maps

</td>
<td>


16GiB

</td>
<td>


256GiB

</td>
<td>


4TiB

</td>
<td>


256TiB

</td>
</tr>
</tbody>
</table>

For 64-bit filesystems, limits are as follows:


<table>
<thead>
<tr>
<th>


Item

</th>
<th>


1KiB

</th>
<th>


2KiB

</th>
<th>


4KiB

</th>
<th>


64KiB

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Blocks

</td>
<td>


2^64

</td>
<td>


2^64

</td>
<td>


2^64

</td>
<td>


2^64

</td>
</tr>
<tr>
<td>


Inodes

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
</tr>
<tr>
<td>


File System Size

</td>
<td>


16ZiB

</td>
<td>


32ZiB

</td>
<td>


64ZiB

</td>
<td>


1YiB

</td>
</tr>
<tr>
<td>


Blocks Per Block Group

</td>
<td>


8,192

</td>
<td>


16,384

</td>
<td>


32,768

</td>
<td>


524,288

</td>
</tr>
<tr>
<td>


Inodes Per Block Group

</td>
<td>


8,192

</td>
<td>


16,384

</td>
<td>


32,768

</td>
<td>


524,288

</td>
</tr>
<tr>
<td>


Block Group Size

</td>
<td>


8MiB

</td>
<td>


32MiB

</td>
<td>


128MiB

</td>
<td>


32GiB

</td>
</tr>
<tr>
<td>


Blocks Per File, Extents

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
<td>


2^32

</td>
</tr>
<tr>
<td>


Blocks Per File, Block Maps

</td>
<td>


16,843,020

</td>
<td>


134,480,396

</td>
<td>


1,074,791,436

</td>
<td>


4,398,314,962,956 (really 2^32 due to field size limitations)

</td>
</tr>
<tr>
<td>


File Size, Extents

</td>
<td>


4TiB

</td>
<td>


8TiB

</td>
<td>


16TiB

</td>
<td>


256TiB

</td>
</tr>
<tr>
<td>


File Size, Block Maps

</td>
<td>


16GiB

</td>
<td>


256GiB

</td>
<td>


4TiB

</td>
<td>


256TiB

</td>
</tr>
</tbody>
</table>

Note: Files not using extents (i.e. files using block maps) must be placed within the first 2^32 blocks of a filesystem. Files with extents must be placed within the first 2^48 blocks of a filesystem. It's not clear what happens with larger filesystems.

---

# Checksums

_Peios Kernel / Internals / Filesystems / ext4_

> Starting in early 2012, metadata checksums were added to all major ext4 and jbd2 data structures. The associated feature flag is metadata_csum. The desired checksum algorithm is indicated in the superblock, though as of October 2012 the…

<a id="rst-checksums"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Starting in early 2012, metadata checksums were added to all major ext4 and jbd2 data structures. The associated feature flag is metadata_csum. The desired checksum algorithm is indicated in the superblock, though as of October 2012 the only supported algorithm is crc32c. Some data structures did not have space to fit a full 32-bit checksum, so only the lower 16 bits are stored. Enabling the 64bit feature increases the data structure size so that full 32-bit checksums can be stored for many data structures. However, existing 32-bit filesystems cannot be extended to enable 64bit mode, at least not without the experimental resize2fs patches to do so.

Existing filesystems can have checksumming added by running `tune2fs -O metadata_csum` against the underlying device. If tune2fs encounters directory blocks that lack sufficient empty space to add a checksum, it will request that you run `e2fsck -D` to have the directories rebuilt with checksums. This has the added benefit of removing slack space from the directory files and rebalancing the htree indexes. If you \_ignore\_ this step, your directories will not be protected by a checksum\!

The following table describes the data elements that go into each type of checksum. The checksum function is whatever the superblock describes (crc32c as of October 2013) unless noted otherwise.


<table>
<thead>
<tr>
<th>


Metadata

</th>
<th>


Length

</th>
<th>


Ingredients

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Superblock

</td>
<td>


\__le32

</td>
<td>


The entire superblock up to the checksum field. The UUID lives inside the superblock.

</td>
</tr>
<tr>
<td>


MMP

</td>
<td>


\__le32

</td>
<td>


UUID + the entire MMP block up to the checksum field.

</td>
</tr>
<tr>
<td>


Extended Attributes

</td>
<td>


\__le32

</td>
<td>


UUID + the entire extended attribute block. The checksum field is set to zero.

</td>
</tr>
<tr>
<td>


Directory Entries

</td>
<td>


\__le32

</td>
<td>


UUID + inode number + inode generation + the directory block up to the fake entry enclosing the checksum field.

</td>
</tr>
<tr>
<td>


HTREE Nodes

</td>
<td>


\__le32

</td>
<td>


UUID + inode number + inode generation + all valid extents + HTREE tail. The checksum field is set to zero.

</td>
</tr>
<tr>
<td>


Extents

</td>
<td>


\__le32

</td>
<td>


UUID + inode number + inode generation + the entire extent block up to the checksum field.

</td>
</tr>
<tr>
<td>


Bitmaps

</td>
<td>


\__le32 or \__le16

</td>
<td>


UUID + the entire bitmap. Checksums are stored in the group descriptor, and truncated if the group descriptor size is 32 bytes (i.e. ^64bit)

</td>
</tr>
<tr>
<td>


Inodes

</td>
<td>


\__le32

</td>
<td>


UUID + inode number + inode generation + the entire inode. The checksum field is set to zero. Each inode has its own checksum.

</td>
</tr>
<tr>
<td>


Group Descriptors

</td>
<td>


\__le16

</td>
<td>


If metadata_csum, then UUID + group number + the entire descriptor; else if gdt_csum, then crc16(UUID + group number + the entire descriptor). In all cases, only the lower 16 bits are stored.

</td>
</tr>
</tbody>
</table>

---

# Directory Entries

_Peios Kernel / Internals / Filesystems / ext4_

> In an ext4 filesystem, a directory is more or less a flat file that maps an arbitrary byte string (usually ASCII) to an inode number on the filesystem. There can be many directory entries across the filesystem that reference the same inode…

<a id="rst-directory-entries"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In an ext4 filesystem, a directory is more or less a flat file that maps an arbitrary byte string (usually ASCII) to an inode number on the filesystem. There can be many directory entries across the filesystem that reference the same inode number--these are known as hard links, and that is why hard links cannot reference files on other filesystems. As such, directory entries are found by reading the data block(s) associated with a directory file for the particular directory entry that is desired.

<a id="rst-linear-classic-directories"></a>

## Linear (Classic) Directories

By default, each directory lists its entries in an “almost-linear” array. I write “almost” because it's not a linear array in the memory sense because directory entries are not split across filesystem blocks. Therefore, it is more accurate to say that a directory is a series of data blocks and that each block contains a linear array of directory entries. The end of each per-block array is signified by reaching the end of the block; the last entry in the block has a record length that takes it all the way to the end of the block. The end of the entire directory is of course signified by reaching the end of the file. Unused directory entries are signified by inode = 0. By default the filesystem uses `struct ext4_dir_entry_2` for directory entries unless the “filetype” feature flag is not set, in which case it uses `struct ext4_dir_entry`.

The original directory entry format is `struct ext4_dir_entry`, which is at most 263 bytes long, though on disk you'll need to reference `dirent.rec_len` to know for sure.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


inode

</td>
<td>


Number of the inode that this directory entry points to.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


rec_len

</td>
<td>


Length of this directory entry. Must be a multiple of 4.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__le16

</td>
<td>


name_len

</td>
<td>


Length of the file name.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


char

</td>
<td>


name\[EXT4_NAME_LEN\]

</td>
<td>


File name.

</td>
</tr>
</tbody>
</table>

Since file names cannot be longer than 255 bytes, the new directory entry format shortens the name_len field and uses the space for a file type flag, probably to avoid having to load every inode during directory tree traversal. This format is `ext4_dir_entry_2`, which is at most 263 bytes long, though on disk you'll need to reference `dirent.rec_len` to know for sure.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


inode

</td>
<td>


Number of the inode that this directory entry points to.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


rec_len

</td>
<td>


Length of this directory entry.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__u8

</td>
<td>


name_len

</td>
<td>


Length of the file name.

</td>
</tr>
<tr>
<td>


0x7

</td>
<td>


\__u8

</td>
<td>


file_type

</td>
<td>


File type code, see [ftype](<#rst-ftype>) table below.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


char

</td>
<td>


name\[EXT4_NAME_LEN\]

</td>
<td>


File name.

</td>
</tr>
</tbody>
</table>

<a id="rst-ftype"></a>

The directory file type is one of the following values:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


Unknown.

</td>
</tr>
<tr>
<td>


0x1

</td>
<td>


Regular file.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


Directory.

</td>
</tr>
<tr>
<td>


0x3

</td>
<td>


Character device file.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


Block device file.

</td>
</tr>
<tr>
<td>


0x5

</td>
<td>


FIFO.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


Socket.

</td>
</tr>
<tr>
<td>


0x7

</td>
<td>


Symbolic link.

</td>
</tr>
</tbody>
</table>

To support directories that are both encrypted and casefolded directories, we must also include hash information in the directory entry. We append `ext4_extended_dir_entry_2` to `ext4_dir_entry_2` except for the entries for dot and dotdot, which are kept the same. The structure follows immediately after `name` and is included in the size listed by `rec_len` If a directory entry uses this extension, it may be up to 271 bytes.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


hash

</td>
<td>


The hash of the directory name

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


minor_hash

</td>
<td>


The minor hash of the directory name

</td>
</tr>
</tbody>
</table>

In order to add checksums to these classic directory blocks, a phony `struct ext4_dir_entry` is placed at the end of each leaf block to hold the checksum. The directory entry is 12 bytes long. The inode number and name_len fields are set to zero to fool old software into ignoring an apparently empty directory entry, and the checksum is stored in the place where the name normally goes. The structure is `struct ext4_dir_entry_tail`:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


det_reserved_zero1

</td>
<td>


Inode number, which must be zero.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


det_rec_len

</td>
<td>


Length of this directory entry, which must be 12.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__u8

</td>
<td>


det_reserved_zero2

</td>
<td>


Length of the file name, which must be zero.

</td>
</tr>
<tr>
<td>


0x7

</td>
<td>


\__u8

</td>
<td>


det_reserved_ft

</td>
<td>


File type, which must be 0xDE.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le32

</td>
<td>


det_checksum

</td>
<td>


Directory leaf block checksum.

</td>
</tr>
</tbody>
</table>

The leaf directory block checksum is calculated against the FS UUID (or the checksum seed, if that feature is enabled for the fs), the directory's inode number, the directory's inode generation number, and the entire directory entry block up to (but not including) the fake directory entry.

<a id="rst-hash-tree-directories"></a>

## Hash Tree Directories

A linear array of directory entries isn't great for performance, so a new feature was added to ext3 to provide a faster (but peculiar) balanced tree keyed off a hash of the directory entry name. If the EXT4_INDEX_FL (0x1000) flag is set in the inode, this directory uses a hashed btree (htree) to organize and find directory entries. For backwards read-only compatibility with ext2, interior tree nodes are actually hidden inside the directory file, masquerading as “empty” directory entries spanning the whole block. It was stated previously that directory entries with the inode set to 0 are treated as unused entries; this is (ab)used to fool the old linear-scan algorithm into skipping over those blocks containing the interior tree node data.

The root of the tree always lives in the first data block of the directory. By ext2 custom, the '.' and '..' entries must appear at the beginning of this first block, so they are put here as two `struct ext4_dir_entry_2` s and not stored in the tree. The rest of the root node contains metadata about the tree and finally a hash-&gt;block map to find nodes that are lower in the htree. If `dx_root.info.indirect_levels` is non-zero then the htree has that many levels and the blocks pointed to by the root node's map are interior nodes. These interior nodes have a zeroed out `struct ext4_dir_entry_2` followed by a hash-&gt;block map to find nodes of the next level. Leaf nodes look like classic linear directory blocks, but all of its entries have a hash value equal or greater than the indicated hash of the parent node.

The actual hash value for an entry name is only 31 bits, the least-significant bit is set to 0. However, if there is a hash collision between directory entries, the least-significant bit may get set to 1 on interior nodes in the case where these two (or more) hash-colliding entries do not fit into one leaf node and must be split across multiple nodes.

To look up a name in such a htree, the code calculates the hash of the desired file name and uses it to find the leaf node with the range of hash values the calculated hash falls into (in other words, a lookup works basically the same as it would in a B-Tree keyed by the hash value), and possibly also scanning the leaf nodes that follow (in tree order) in case of hash collisions.

To traverse the directory as a linear array (such as the old code does), the code simply reads every data block in the directory. The blocks used for the htree will appear to have no entries (aside from '.' and '..') and so only the leaf nodes will appear to have any interesting content.

The root of the htree is in `struct dx_root`, which is the full length of a data block:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


dot.inode

</td>
<td>


inode number of this directory.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


dot.rec_len

</td>
<td>


Length of this record, 12.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


u8

</td>
<td>


dot.name_len

</td>
<td>


Length of the name, 1.

</td>
</tr>
<tr>
<td>


0x7

</td>
<td>


u8

</td>
<td>


dot.file_type

</td>
<td>


File type of this entry, 0x2 (directory) (if the feature flag is set).

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


char

</td>
<td>


dot.name\[4\]

</td>
<td>


“.000”

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__le32

</td>
<td>


dotdot.inode

</td>
<td>


inode number of parent directory.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__le16

</td>
<td>


dotdot.rec_len

</td>
<td>


block_size - 12. The record length is long enough to cover all htree data.

</td>
</tr>
<tr>
<td>


0x12

</td>
<td>


u8

</td>
<td>


dotdot.name_len

</td>
<td>


Length of the name, 2.

</td>
</tr>
<tr>
<td>


0x13

</td>
<td>


u8

</td>
<td>


dotdot.file_type

</td>
<td>


File type of this entry, 0x2 (directory) (if the feature flag is set).

</td>
</tr>
<tr>
<td>


0x14

</td>
<td>


char

</td>
<td>


dotdot_name\[4\]

</td>
<td>


“..00”

</td>
</tr>
<tr>
<td>


0x18

</td>
<td>


\__le32

</td>
<td>


struct dx_root_info.reserved_zero

</td>
<td>


Zero.

</td>
</tr>
<tr>
<td>


0x1C

</td>
<td>


u8

</td>
<td>


struct dx_root_info.hash_version

</td>
<td>


Hash type, see [dirhash](<#rst-dirhash>) table below.

</td>
</tr>
<tr>
<td>


0x1D

</td>
<td>


u8

</td>
<td>


struct dx_root_info.info_length

</td>
<td>


Length of the tree information, 0x8.

</td>
</tr>
<tr>
<td>


0x1E

</td>
<td>


u8

</td>
<td>


struct dx_root_info.indirect_levels

</td>
<td>


Depth of the htree. Cannot be larger than 3 if the INCOMPAT_LARGEDIR feature is set; cannot be larger than 2 otherwise.

</td>
</tr>
<tr>
<td>


0x1F

</td>
<td>


u8

</td>
<td>


struct dx_root_info.unused_flags

</td>
<td>




</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


\__le16

</td>
<td>


limit

</td>
<td>


Maximum number of dx_entries that can follow this header, plus 1 for the header itself.

</td>
</tr>
<tr>
<td>


0x22

</td>
<td>


\__le16

</td>
<td>


count

</td>
<td>


Actual number of dx_entries that follow this header, plus 1 for the header itself.

</td>
</tr>
<tr>
<td>


0x24

</td>
<td>


\__le32

</td>
<td>


block

</td>
<td>


The block number (within the directory file) that lead to the left-most leaf node, i.e. the leaf containing entries with the lowest hash values.

</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


struct dx_entry

</td>
<td>


entries\[0\]

</td>
<td>


As many 8-byte `struct dx_entry` as fits in the rest of the data block.

</td>
</tr>
</tbody>
</table>

<a id="rst-dirhash"></a>

The directory hash is one of the following values:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


Legacy.

</td>
</tr>
<tr>
<td>


0x1

</td>
<td>


Half MD4.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


Tea.

</td>
</tr>
<tr>
<td>


0x3

</td>
<td>


Legacy, unsigned.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


Half MD4, unsigned.

</td>
</tr>
<tr>
<td>


0x5

</td>
<td>


Tea, unsigned.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


Siphash.

</td>
</tr>
</tbody>
</table>

Interior nodes of an htree are recorded as `struct dx_node`, which is also the full length of a data block:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


fake.inode

</td>
<td>


Zero, to make it look like this entry is not in use.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


fake.rec_len

</td>
<td>


The size of the block, in order to hide all of the dx_node data.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


u8

</td>
<td>


name_len

</td>
<td>


Zero. There is no name for this “unused” directory entry.

</td>
</tr>
<tr>
<td>


0x7

</td>
<td>


u8

</td>
<td>


file_type

</td>
<td>


Zero. There is no file type for this “unused” directory entry.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le16

</td>
<td>


limit

</td>
<td>


Maximum number of dx_entries that can follow this header, plus 1 for the header itself.

</td>
</tr>
<tr>
<td>


0xA

</td>
<td>


\__le16

</td>
<td>


count

</td>
<td>


Actual number of dx_entries that follow this header, plus 1 for the header itself.

</td>
</tr>
<tr>
<td>


0xE

</td>
<td>


\__le32

</td>
<td>


block

</td>
<td>


The block number (within the directory file) that goes with the lowest hash value of this block. This value is stored in the parent block.

</td>
</tr>
<tr>
<td>


0x12

</td>
<td>


struct dx_entry

</td>
<td>


entries\[0\]

</td>
<td>


As many 8-byte `struct dx_entry` as fits in the rest of the data block.

</td>
</tr>
</tbody>
</table>

The hash maps that exist in both `struct dx_root` and `struct dx_node` are recorded as `struct dx_entry`, which is 8 bytes long:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


hash

</td>
<td>


Hash code.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


block

</td>
<td>


Block number (within the directory file, not filesystem blocks) of the next node in the htree.

</td>
</tr>
</tbody>
</table>

(If you think this is all quite clever and peculiar, so does the author.)

If metadata checksums are enabled, the last 8 bytes of the directory block (precisely the length of one dx_entry) are used to store a `struct dx_tail`, which contains the checksum. The `limit` and `count` entries in the dx_root/dx_node structures are adjusted as necessary to fit the dx_tail into the block. If there is no space for the dx_tail, the user is notified to run e2fsck -D to rebuild the directory index (which will ensure that there's space for the checksum. The dx_tail structure is 8 bytes long and looks like this:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


u32

</td>
<td>


dt_reserved

</td>
<td>


Unused (but still part of the checksum curiously).

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


dt_checksum

</td>
<td>


Checksum of the htree directory block.

</td>
</tr>
</tbody>
</table>

The checksum is calculated against the FS UUID, the htree index header (dx_root or dx_node), all of the htree indices (dx_entry) that are in use, and the tail block (dx_tail) with the dt_checksum initially set to 0.

---

# Dynamic Structures

_Peios Kernel / Internals / Filesystems / ext4_

> Dynamic metadata are created on the fly when files and blocks are allocated to files.

<a id="rst-dynamic-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Dynamic metadata are created on the fly when files and blocks are allocated to files.

- [Index Nodes](</kernel/internals/filesystems/ext4/inodes.md>)
- [ifork](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/ext4/ifork.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Directory Entries](</kernel/internals/filesystems/ext4/directory.md>)
- [Extended Attributes](</kernel/internals/filesystems/ext4/attributes.md>)

---

# Large Extended Attribute Values

_Peios Kernel / Internals / Filesystems / ext4_

> To enable ext4 to store extended attribute values that do not fit in the inode or in the single extended attribute block attached to an inode, the EA_INODE feature allows us to store the value in the data blocks of a regular file inode.…

<a id="rst-large-extended-attribute-values"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

To enable ext4 to store extended attribute values that do not fit in the inode or in the single extended attribute block attached to an inode, the EA_INODE feature allows us to store the value in the data blocks of a regular file inode. This “EA inode” is linked only from the extended attribute name index and must not appear in a directory entry. The inode's i_atime field is used to store a checksum of the xattr value; and i_ctime/i_version store a 64-bit reference count, which enables sharing of large xattr values between multiple owning inodes. For backward compatibility with older versions of this feature, the i_mtime/i_generation *may* store a back-reference to the inode number and i_generation of the **one** owning inode (in cases where the EA inode is not referenced by multiple inodes) to verify that the EA inode is the correct one being accessed.

---

# Global Structures

_Peios Kernel / Internals / Filesystems / ext4_

> The filesystem is sharded into a number of block groups, each of which have static metadata at fixed locations.

<a id="rst-global-structures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The filesystem is sharded into a number of block groups, each of which have static metadata at fixed locations.

- [Super Block](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/ext4/super.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Block Group Descriptors](</kernel/internals/filesystems/ext4/group-descr.md>)
- [Block and inode Bitmaps](</kernel/internals/filesystems/ext4/bitmaps.md>)
- [Inode Table](</kernel/internals/filesystems/ext4/inode-table.md>)
- [Multiple Mount Protection](</kernel/internals/filesystems/ext4/mmp.md>)
- [Journal (jbd2)](</kernel/internals/filesystems/ext4/journal.md>)
- [Orphan file](</kernel/internals/filesystems/ext4/orphan.md>)

---

# Block Group Descriptors

_Peios Kernel / Internals / Filesystems / ext4_

> Each block group on the filesystem has one of these descriptors associated with it. As noted in the Layout section above, the group descriptors (if present) are the second item in the block group. The standard configuration is for each…

<a id="rst-block-group-descriptors"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Each block group on the filesystem has one of these descriptors associated with it. As noted in the Layout section above, the group descriptors (if present) are the second item in the block group. The standard configuration is for each block group to contain a full copy of the block group descriptor table unless the sparse_super feature flag is set.

Notice how the group descriptor records the location of both bitmaps and the inode table (i.e. they can float). This means that within a block group, the only data structures with fixed locations are the superblock and the group descriptor table. The flex_bg mechanism uses this property to group several block groups into a flex group and lay out all of the groups' bitmaps and inode tables into one long run in the first group of the flex group.

If the meta_bg feature flag is set, then several block groups are grouped together into a meta group. Note that in the meta_bg case, however, the first and last two block groups within the larger meta group contain only group descriptors for the groups inside the meta group.

flex_bg and meta_bg do not appear to be mutually exclusive features.

In ext2, ext3, and ext4 (when the 64bit feature is not enabled), the block group descriptor was only 32 bytes long and therefore ends at bg_checksum. On an ext4 filesystem with the 64bit feature enabled, the block group descriptor expands to at least the 64 bytes described below; the size is stored in the superblock.

If gdt_csum is set and metadata_csum is not set, the block group checksum is the crc16 of the FS UUID, the group number, and the group descriptor structure. If metadata_csum is set, then the block group checksum is the lower 16 bits of the checksum of the FS UUID, the group number, and the group descriptor structure. Both block and inode bitmap checksums are calculated against the FS UUID, the group number, and the entire bitmap.

The block group descriptor is laid out in `struct ext4_group_desc`.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


bg_block_bitmap_lo

</td>
<td>


Lower 32-bits of location of block bitmap.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


bg_inode_bitmap_lo

</td>
<td>


Lower 32-bits of location of inode bitmap.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le32

</td>
<td>


bg_inode_table_lo

</td>
<td>


Lower 32-bits of location of inode table.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__le16

</td>
<td>


bg_free_blocks_count_lo

</td>
<td>


Lower 16-bits of free block count.

</td>
</tr>
<tr>
<td>


0xE

</td>
<td>


\__le16

</td>
<td>


bg_free_inodes_count_lo

</td>
<td>


Lower 16-bits of free inode count.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__le16

</td>
<td>


bg_used_dirs_count_lo

</td>
<td>


Lower 16-bits of directory count.

</td>
</tr>
<tr>
<td>


0x12

</td>
<td>


\__le16

</td>
<td>


bg_flags

</td>
<td>


Block group flags. See the [bgflags](<#rst-bgflags>) table below.

</td>
</tr>
<tr>
<td>


0x14

</td>
<td>


\__le32

</td>
<td>


bg_exclude_bitmap_lo

</td>
<td>


Lower 32-bits of location of snapshot exclusion bitmap.

</td>
</tr>
<tr>
<td>


0x18

</td>
<td>


\__le16

</td>
<td>


bg_block_bitmap_csum_lo

</td>
<td>


Lower 16-bits of the block bitmap checksum.

</td>
</tr>
<tr>
<td>


0x1A

</td>
<td>


\__le16

</td>
<td>


bg_inode_bitmap_csum_lo

</td>
<td>


Lower 16-bits of the inode bitmap checksum.

</td>
</tr>
<tr>
<td>


0x1C

</td>
<td>


\__le16

</td>
<td>


bg_itable_unused_lo

</td>
<td>


Lower 16-bits of unused inode count. If set, we needn't scan past the `(sb.s_inodes_per_group - gdt.bg_itable_unused)` th entry in the inode table for this group.

</td>
</tr>
<tr>
<td>


0x1E

</td>
<td>


\__le16

</td>
<td>


bg_checksum

</td>
<td>


Group descriptor checksum; crc16(sb_uuid+group_num+bg_desc) if the RO_COMPAT_GDT_CSUM feature is set, or crc32c(sb_uuid+group_num+bg_desc) &amp; 0xFFFF if the RO_COMPAT_METADATA_CSUM feature is set.  The bg_checksum field in bg_desc is skipped when calculating crc16 checksum, and set to zero if crc32c checksum is used.

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


These fields only exist if the 64bit feature is enabled and s_desc_size &gt; 32.

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


\__le32

</td>
<td>


bg_block_bitmap_hi

</td>
<td>


Upper 32-bits of location of block bitmap.

</td>
</tr>
<tr>
<td>


0x24

</td>
<td>


\__le32

</td>
<td>


bg_inode_bitmap_hi

</td>
<td>


Upper 32-bits of location of inodes bitmap.

</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


\__le32

</td>
<td>


bg_inode_table_hi

</td>
<td>


Upper 32-bits of location of inodes table.

</td>
</tr>
<tr>
<td>


0x2C

</td>
<td>


\__le16

</td>
<td>


bg_free_blocks_count_hi

</td>
<td>


Upper 16-bits of free block count.

</td>
</tr>
<tr>
<td>


0x2E

</td>
<td>


\__le16

</td>
<td>


bg_free_inodes_count_hi

</td>
<td>


Upper 16-bits of free inode count.

</td>
</tr>
<tr>
<td>


0x30

</td>
<td>


\__le16

</td>
<td>


bg_used_dirs_count_hi

</td>
<td>


Upper 16-bits of directory count.

</td>
</tr>
<tr>
<td>


0x32

</td>
<td>


\__le16

</td>
<td>


bg_itable_unused_hi

</td>
<td>


Upper 16-bits of unused inode count.

</td>
</tr>
<tr>
<td>


0x34

</td>
<td>


\__le32

</td>
<td>


bg_exclude_bitmap_hi

</td>
<td>


Upper 32-bits of location of snapshot exclusion bitmap.

</td>
</tr>
<tr>
<td>


0x38

</td>
<td>


\__le16

</td>
<td>


bg_block_bitmap_csum_hi

</td>
<td>


Upper 16-bits of the block bitmap checksum.

</td>
</tr>
<tr>
<td>


0x3A

</td>
<td>


\__le16

</td>
<td>


bg_inode_bitmap_csum_hi

</td>
<td>


Upper 16-bits of the inode bitmap checksum.

</td>
</tr>
<tr>
<td>


0x3C

</td>
<td>


\__u32

</td>
<td>


bg_reserved

</td>
<td>


Padding to 64 bytes.

</td>
</tr>
</tbody>
</table>

<a id="rst-bgflags"></a>

Block group flags can be any combination of the following:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


inode table and bitmap are not initialized (EXT4_BG_INODE_UNINIT).

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


block bitmap is not initialized (EXT4_BG_BLOCK_UNINIT).

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


inode table is zeroed (EXT4_BG_INODE_ZEROED).

</td>
</tr>
</tbody>
</table>

---

# The Contents of inode.i_block

_Peios Kernel / Internals / Filesystems / ext4_

> Depending on the type of file an inode describes, the 60 bytes of storage in inode.i_block can be used in different ways. In general, regular files and directories will use it for file block indexing information, and special files will use…

<a id="rst-the-contents-of-inode-i-block"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Depending on the type of file an inode describes, the 60 bytes of storage in `inode.i_block` can be used in different ways. In general, regular files and directories will use it for file block indexing information, and special files will use it for special purposes.

<a id="rst-symbolic-links"></a>

## Symbolic Links

The target of a symbolic link will be stored in this field if the target string is less than 60 bytes long. Otherwise, either extents or block maps will be used to allocate data blocks to store the link target.

<a id="rst-direct-indirect-block-addressing"></a>

## Direct/Indirect Block Addressing

In ext2/3, file block numbers were mapped to logical block numbers by means of an (up to) three level 1-1 block map. To find the logical block that stores a particular file block, the code would navigate through this increasingly complicated structure. Notice that there is neither a magic number nor a checksum to provide any level of confidence that the block isn't full of garbage.



<!-- SPDX-License-Identifier: GPL-2.0 -->


<table>
<thead>
<tr>
<th>



i.i\_block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to 11

</td>
<td>



Direct map to file blocks 0 to 11.

</td>
</tr>
<tr>
<td>



12

</td>
<td>



Indirect block: (file blocks 12 to (`$block_size` / 4) + 11, or 12 to 1035 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Direct map to (`$block_size` / 4) blocks (1024 if 4KiB blocks)

</td>
</tr>
</tbody>
</table>

</td>
</tr>
<tr>
<td>



13

</td>
<td>



Double-indirect block: (file blocks `$block_size`/4 + 12 to (`$block_size` / 4) ^ 2 + (`$block_size` / 4) + 11, or 1036 to 1049611 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Double Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Map to (`$block_size` / 4) indirect blocks (1024 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Direct map to (`$block_size` / 4) blocks (1024 if 4KiB blocks)

</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>

</td>
</tr>
<tr>
<td>



14

</td>
<td>



Triple-indirect block: (file blocks (`$block_size` / 4) ^ 2 + (`$block_size` / 4) + 12 to (`$block_size` / 4) ^ 3 + (`$block_size` / 4) ^ 2 + (`$block_size` / 4) + 12, or 1049612 to 1074791436 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Triple Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Map to (`$block_size` / 4) double indirect blocks (1024 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Double Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Map to (`$block_size` / 4) indirect blocks (1024 if 4KiB blocks)


<table>
<thead>
<tr>
<th>



Indirect Block Offset

</th>
<th>



Where It Points

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0 to (`$block_size` / 4)

</td>
<td>



Direct map to (`$block_size` / 4) blocks (1024 if 4KiB blocks)

</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>





Note that with this block mapping scheme, it is necessary to fill out a lot of mapping data even for a large contiguous file\! This inefficiency led to the creation of the extent mapping scheme, discussed below.

Notice also that a file using this mapping scheme cannot be placed higher than 2^32 blocks.

<a id="rst-extent-tree"></a>

## Extent Tree

In ext4, the file to logical block map has been replaced with an extent tree. Under the old scheme, allocating a contiguous run of 1,000 blocks requires an indirect block to map all 1,000 entries; with extents, the mapping is reduced to a single `struct ext4_extent` with `ee_len = 1000`. If flex\_bg is enabled, it is possible to allocate very large files with a single extent, at a considerable reduction in metadata block use, and some improvement in disk efficiency. The inode must have the extents flag (0x80000) flag set for this feature to be in use.

Extents are arranged as a tree. Each node of the tree begins with a `struct ext4_extent_header`. If the node is an interior node (`eh.eh_depth` &gt; 0), the header is followed by `eh.eh_entries` instances of `struct ext4_extent_idx`; each of these index entries points to a block containing more nodes in the extent tree. If the node is a leaf node (`eh.eh_depth == 0`), then the header is followed by `eh.eh_entries` instances of `struct ext4_extent`; these instances point to the file's data blocks. The root node of the extent tree is stored in `inode.i_block`, which allows for the first four extents to be recorded without the use of extra metadata blocks.

The extent tree header is recorded in `struct ext4_extent_header`, which is 12 bytes long:


<table>
<thead>
<tr>
<th>



Offset

</th>
<th>



Size

</th>
<th>



Name

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



\_\_le16

</td>
<td>



eh\_magic

</td>
<td>



Magic number, 0xF30A.

</td>
</tr>
<tr>
<td>



0x2

</td>
<td>



\_\_le16

</td>
<td>



eh\_entries

</td>
<td>



Number of valid entries following the header.

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



\_\_le16

</td>
<td>



eh\_max

</td>
<td>



Maximum number of entries that could follow the header.

</td>
</tr>
<tr>
<td>



0x6

</td>
<td>



\_\_le16

</td>
<td>



eh\_depth

</td>
<td>



Depth of this extent node in the extent tree. 0 = this extent node points to data blocks; otherwise, this extent node points to other extent nodes. The extent tree can be at most 5 levels deep: a logical block number can be at most `2^32`, and the smallest `n` that satisfies `4*(((blocksize - 12)/12)^n) >= 2^32` is 5.

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



\_\_le32

</td>
<td>



eh\_generation

</td>
<td>



Generation of the tree. (Used by Lustre, but not standard ext4).

</td>
</tr>
</tbody>
</table>

Internal nodes of the extent tree, also known as index nodes, are recorded as `struct ext4_extent_idx`, and are 12 bytes long:


<table>
<thead>
<tr>
<th>



Offset

</th>
<th>



Size

</th>
<th>



Name

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



\_\_le32

</td>
<td>



ei\_block

</td>
<td>



This index node covers file blocks from 'block' onward.

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



\_\_le32

</td>
<td>



ei\_leaf\_lo

</td>
<td>



Lower 32-bits of the block number of the extent node that is the next level lower in the tree. The tree node pointed to can be either another internal node or a leaf node, described below.

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



\_\_le16

</td>
<td>



ei\_leaf\_hi

</td>
<td>



Upper 16-bits of the previous field.

</td>
</tr>
<tr>
<td>



0xA

</td>
<td>



\_\_u16

</td>
<td>



ei\_unused

</td>
<td>





</td>
</tr>
</tbody>
</table>

Leaf nodes of the extent tree are recorded as `struct ext4_extent`, and are also 12 bytes long:


<table>
<thead>
<tr>
<th>



Offset

</th>
<th>



Size

</th>
<th>



Name

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



\_\_le32

</td>
<td>



ee\_block

</td>
<td>



First file block number that this extent covers.

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



\_\_le16

</td>
<td>



ee\_len

</td>
<td>



Number of blocks covered by extent. If the value of this field is &lt;= 32768, the extent is initialized. If the value of the field is &gt; 32768, the extent is uninitialized and the actual extent length is `ee_len` - 32768. Therefore, the maximum length of a initialized extent is 32768 blocks, and the maximum length of an uninitialized extent is 32767.

</td>
</tr>
<tr>
<td>



0x6

</td>
<td>



\_\_le16

</td>
<td>



ee\_start\_hi

</td>
<td>



Upper 16-bits of the block number to which this extent points.

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



\_\_le32

</td>
<td>



ee\_start\_lo

</td>
<td>



Lower 32-bits of the block number to which this extent points.

</td>
</tr>
</tbody>
</table>

Prior to the introduction of metadata checksums, the extent header + extent entries always left at least 4 bytes of unallocated space at the end of each extent tree data block (because (2^x % 12) &gt;= 4). Therefore, the 32-bit checksum is inserted into this space. The 4 extents in the inode do not need checksumming, since the inode is already checksummed. The checksum is calculated against the FS UUID, the inode number, the inode generation, and the entire extent block leading up to (but not including) the checksum itself.

`struct ext4_extent_tail` is 4 bytes long:


<table>
<thead>
<tr>
<th>



Offset

</th>
<th>



Size

</th>
<th>



Name

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



\_\_le32

</td>
<td>



eb\_checksum

</td>
<td>



Checksum of the extent block, crc32c(uuid+inum+igeneration+extentblock)

</td>
</tr>
</tbody>
</table>

<a id="rst-inline-data"></a>

## Inline Data

If the inline data feature is enabled for the filesystem and the flag is set for the inode, it is possible that the first 60 bytes of the file data are stored here.

---

# Inline Data

_Peios Kernel / Internals / Filesystems / ext4_

> The inline data feature was designed to handle the case that a file's data is so tiny that it readily fits inside the inode, which (theoretically) reduces disk block consumption and reduces seeks. If the file is smaller than 60 bytes, then…

<a id="rst-inline-data"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The inline data feature was designed to handle the case that a file's data is so tiny that it readily fits inside the inode, which (theoretically) reduces disk block consumption and reduces seeks. If the file is smaller than 60 bytes, then the data are stored inline in `inode.i_block`. If the rest of the file would fit inside the extended attribute space, then it might be found as an extended attribute “system.data” within the inode body (“ibody EA”). This of course constrains the amount of extended attributes one can attach to an inode. If the data size increases beyond i_block + ibody EA, a regular block is allocated and the contents moved to that block.

Pending a change to compact the extended attribute key used to store inline data, one ought to be able to store 160 bytes of data in a 256-byte inode (as of June 2015, when i_extra_isize is 28). Prior to that, the limit was 156 bytes due to inefficient use of inode space.

The inline data feature requires the presence of an extended attribute for “system.data”, even if the attribute value is zero length.

<a id="rst-inline-directories"></a>

## Inline Directories

The first four bytes of i_block are the inode number of the parent directory. Following that is a 56-byte space for an array of directory entries; see `struct ext4_dir_entry`. If there is a “system.data” attribute in the inode body, the EA value is an array of `struct ext4_dir_entry` as well. Note that for inline directories, the i_block and EA space are treated as separate dirent blocks; directory entries cannot span the two.

Inline directory entries are not checksummed, as the inode checksum should protect all inline data contents.

---

# Inode Table

_Peios Kernel / Internals / Filesystems / ext4_

> Inode tables are statically allocated at mkfs time. Each block group descriptor points to the start of the table, and the superblock records the number of inodes per group. See inode documentation <inodes> for more information on inode…

<a id="rst-inode-table"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Inode tables are statically allocated at mkfs time.  Each block group descriptor points to the start of the table, and the superblock records the number of inodes per group.  See [inode documentation](</kernel/internals/filesystems/ext4/inodes.md>) for more information on inode table layout.

---

# Index Nodes

_Peios Kernel / Internals / Filesystems / ext4_

> In a regular UNIX filesystem, the inode stores all the metadata pertaining to the file (time stamps, block maps, extended attributes, etc), not the directory entry. To find the information associated with a file, one must traverse the…

<a id="rst-index-nodes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In a regular UNIX filesystem, the inode stores all the metadata pertaining to the file (time stamps, block maps, extended attributes, etc), not the directory entry. To find the information associated with a file, one must traverse the directory files to find the directory entry associated with a file, then load the inode to find the metadata for that file. ext4 appears to cheat (for performance reasons) a little bit by storing a copy of the file type (normally stored in the inode) in the directory entry. (Compare all this to FAT, which stores all the file information directly in the directory entry, but does not support hard links and is in general more seek-happy than ext4 due to its simpler block allocator and extensive use of linked lists.)

The inode table is a linear array of `struct ext4_inode`. The table is sized to have enough blocks to store at least `sb.s_inode_size * sb.s_inodes_per_group` bytes. The number of the block group containing an inode can be calculated as `(inode_number - 1) / sb.s_inodes_per_group`, and the offset into the group's table is `(inode_number - 1) % sb.s_inodes_per_group`. There is no inode 0.

The inode checksum is calculated against the FS UUID, the inode number, and the inode structure itself.

The inode table entry is laid out in `struct ext4_inode`.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le16

</td>
<td>


i_mode

</td>
<td>


File mode. See the table [i_mode](<#rst-i-mode>) below.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


\__le16

</td>
<td>


i_uid

</td>
<td>


Lower 16-bits of Owner UID.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


i_size_lo

</td>
<td>


Lower 32-bits of size in bytes.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le32

</td>
<td>


i_atime

</td>
<td>


Last access time, in seconds since the epoch. However, if the EA_INODE inode flag is set, this inode stores an extended attribute value and this field contains the checksum of the value.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__le32

</td>
<td>


i_ctime

</td>
<td>


Last inode change time, in seconds since the epoch. However, if the EA_INODE inode flag is set, this inode stores an extended attribute value and this field contains the lower 32 bits of the attribute value's reference count.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__le32

</td>
<td>


i_mtime

</td>
<td>


Last data modification time, in seconds since the epoch. However, if the EA_INODE inode flag is set, this inode stores an extended attribute value and this field contains the number of the inode that owns the extended attribute.

</td>
</tr>
<tr>
<td>


0x14

</td>
<td>


\__le32

</td>
<td>


i_dtime

</td>
<td>


Deletion Time, in seconds since the epoch.

</td>
</tr>
<tr>
<td>


0x18

</td>
<td>


\__le16

</td>
<td>


i_gid

</td>
<td>


Lower 16-bits of GID.

</td>
</tr>
<tr>
<td>


0x1A

</td>
<td>


\__le16

</td>
<td>


i_links_count

</td>
<td>


Hard link count. Normally, ext4 does not permit an inode to have more than 65,000 hard links. This applies to files as well as directories, which means that there cannot be more than 64,998 subdirectories in a directory (each subdirectory's '..' entry counts as a hard link, as does the '.' entry in the directory itself). With the DIR_NLINK feature enabled, ext4 supports more than 64,998 subdirectories by setting this field to 1 to indicate that the number of hard links is not known.

</td>
</tr>
<tr>
<td>


0x1C

</td>
<td>


\__le32

</td>
<td>


i_blocks_lo

</td>
<td>


Lower 32-bits of “block” count. If the huge_file feature flag is not set on the filesystem, the file consumes `i_blocks_lo` 512-byte blocks on disk. If huge_file is set and EXT4_HUGE_FILE_FL is NOT set in `inode.i_flags`, then the file consumes `i_blocks_lo + (i_blocks_hi << 32)` 512-byte blocks on disk. If huge_file is set and EXT4_HUGE_FILE_FL IS set in `inode.i_flags`, then this file consumes (`i_blocks_lo + i_blocks_hi` &lt;&lt; 32) filesystem blocks on disk.

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


\__le32

</td>
<td>


i_flags

</td>
<td>


Inode flags. See the table [i_flags](<#rst-i-flags>) below.

</td>
</tr>
<tr>
<td>


0x24

</td>
<td>


4 bytes

</td>
<td>


i_osd1

</td>
<td>


See the table [i_osd1](<#rst-i-osd1>) for more details.

</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


60 bytes

</td>
<td>


i_block\[EXT4_N_BLOCKS=15\]

</td>
<td>


Block map or extent tree. See the section “The Contents of inode.i_block”.

</td>
</tr>
<tr>
<td>


0x64

</td>
<td>


\__le32

</td>
<td>


i_generation

</td>
<td>


File version (for NFS).

</td>
</tr>
<tr>
<td>


0x68

</td>
<td>


\__le32

</td>
<td>


i_file_acl_lo

</td>
<td>


Lower 32-bits of extended attribute block. ACLs are of course one of many possible extended attributes; I think the name of this field is a result of the first use of extended attributes being for ACLs.

</td>
</tr>
<tr>
<td>


0x6C

</td>
<td>


\__le32

</td>
<td>


i_size_high / i_dir_acl

</td>
<td>


Upper 32-bits of file/directory size. In ext2/3 this field was named i_dir_acl, though it was usually set to zero and never used.

</td>
</tr>
<tr>
<td>


0x70

</td>
<td>


\__le32

</td>
<td>


i_obso_faddr

</td>
<td>


(Obsolete) fragment address.

</td>
</tr>
<tr>
<td>


0x74

</td>
<td>


12 bytes

</td>
<td>


i_osd2

</td>
<td>


See the table [i_osd2](<#rst-i-osd2>) for more details.

</td>
</tr>
<tr>
<td>


0x80

</td>
<td>


\__le16

</td>
<td>


i_extra_isize

</td>
<td>


Size of this inode - 128. Alternately, the size of the extended inode fields beyond the original ext2 inode, including this field.

</td>
</tr>
<tr>
<td>


0x82

</td>
<td>


\__le16

</td>
<td>


i_checksum_hi

</td>
<td>


Upper 16-bits of the inode checksum.

</td>
</tr>
<tr>
<td>


0x84

</td>
<td>


\__le32

</td>
<td>


i_ctime_extra

</td>
<td>


Extra change time bits. This provides sub-second precision. See Inode Timestamps section.

</td>
</tr>
<tr>
<td>


0x88

</td>
<td>


\__le32

</td>
<td>


i_mtime_extra

</td>
<td>


Extra modification time bits. This provides sub-second precision.

</td>
</tr>
<tr>
<td>


0x8C

</td>
<td>


\__le32

</td>
<td>


i_atime_extra

</td>
<td>


Extra access time bits. This provides sub-second precision.

</td>
</tr>
<tr>
<td>


0x90

</td>
<td>


\__le32

</td>
<td>


i_crtime

</td>
<td>


File creation time, in seconds since the epoch.

</td>
</tr>
<tr>
<td>


0x94

</td>
<td>


\__le32

</td>
<td>


i_crtime_extra

</td>
<td>


Extra file creation time bits. This provides sub-second precision.

</td>
</tr>
<tr>
<td>


0x98

</td>
<td>


\__le32

</td>
<td>


i_version_hi

</td>
<td>


Upper 32-bits for version number.

</td>
</tr>
<tr>
<td>


0x9C

</td>
<td>


\__le32

</td>
<td>


i_projid

</td>
<td>


Project ID.

</td>
</tr>
</tbody>
</table>

<a id="rst-i-mode"></a>

The `i_mode` value is a combination of the following flags:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


S_IXOTH (Others may execute)

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


S_IWOTH (Others may write)

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


S_IROTH (Others may read)

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


S_IXGRP (Group members may execute)

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


S_IWGRP (Group members may write)

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


S_IRGRP (Group members may read)

</td>
</tr>
<tr>
<td>


0x40

</td>
<td>


S_IXUSR (Owner may execute)

</td>
</tr>
<tr>
<td>


0x80

</td>
<td>


S_IWUSR (Owner may write)

</td>
</tr>
<tr>
<td>


0x100

</td>
<td>


S_IRUSR (Owner may read)

</td>
</tr>
<tr>
<td>


0x200

</td>
<td>


S_ISVTX (Sticky bit)

</td>
</tr>
<tr>
<td>


0x400

</td>
<td>


S_ISGID (Set GID)

</td>
</tr>
<tr>
<td>


0x800

</td>
<td>


S_ISUID (Set UID)

</td>
</tr>
<tr>
<td>




</td>
<td>


These are mutually-exclusive file types:

</td>
</tr>
<tr>
<td>


0x1000

</td>
<td>


S_IFIFO (FIFO)

</td>
</tr>
<tr>
<td>


0x2000

</td>
<td>


S_IFCHR (Character device)

</td>
</tr>
<tr>
<td>


0x4000

</td>
<td>


S_IFDIR (Directory)

</td>
</tr>
<tr>
<td>


0x6000

</td>
<td>


S_IFBLK (Block device)

</td>
</tr>
<tr>
<td>


0x8000

</td>
<td>


S_IFREG (Regular file)

</td>
</tr>
<tr>
<td>


0xA000

</td>
<td>


S_IFLNK (Symbolic link)

</td>
</tr>
<tr>
<td>


0xC000

</td>
<td>


S_IFSOCK (Socket)

</td>
</tr>
</tbody>
</table>

<a id="rst-i-flags"></a>

The `i_flags` field is a combination of these values:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


This file requires secure deletion (EXT4_SECRM_FL). (not implemented)

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


This file should be preserved, should undeletion be desired (EXT4_UNRM_FL). (not implemented)

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


File is compressed (EXT4_COMPR_FL). (not really implemented)

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


All writes to the file must be synchronous (EXT4_SYNC_FL).

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


File is immutable (EXT4_IMMUTABLE_FL).

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


File can only be appended (EXT4_APPEND_FL).

</td>
</tr>
<tr>
<td>


0x40

</td>
<td>


The dump(1) utility should not dump this file (EXT4_NODUMP_FL).

</td>
</tr>
<tr>
<td>


0x80

</td>
<td>


Do not update access time (EXT4_NOATIME_FL).

</td>
</tr>
<tr>
<td>


0x100

</td>
<td>


Dirty compressed file (EXT4_DIRTY_FL). (not used)

</td>
</tr>
<tr>
<td>


0x200

</td>
<td>


File has one or more compressed clusters (EXT4_COMPRBLK_FL). (not used)

</td>
</tr>
<tr>
<td>


0x400

</td>
<td>


Do not compress file (EXT4_NOCOMPR_FL). (not used)

</td>
</tr>
<tr>
<td>


0x800

</td>
<td>


Encrypted inode (EXT4_ENCRYPT_FL). This bit value previously was EXT4_ECOMPR_FL (compression error), which was never used.

</td>
</tr>
<tr>
<td>


0x1000

</td>
<td>


Directory has hashed indexes (EXT4_INDEX_FL).

</td>
</tr>
<tr>
<td>


0x2000

</td>
<td>


AFS magic directory (EXT4_IMAGIC_FL).

</td>
</tr>
<tr>
<td>


0x4000

</td>
<td>


File data must always be written through the journal (EXT4_JOURNAL_DATA_FL).

</td>
</tr>
<tr>
<td>


0x8000

</td>
<td>


File tail should not be merged (EXT4_NOTAIL_FL). (not used by ext4)

</td>
</tr>
<tr>
<td>


0x10000

</td>
<td>


All directory entry data should be written synchronously (see `dirsync`) (EXT4_DIRSYNC_FL).

</td>
</tr>
<tr>
<td>


0x20000

</td>
<td>


Top of directory hierarchy (EXT4_TOPDIR_FL).

</td>
</tr>
<tr>
<td>


0x40000

</td>
<td>


This is a huge file (EXT4_HUGE_FILE_FL).

</td>
</tr>
<tr>
<td>


0x80000

</td>
<td>


Inode uses extents (EXT4_EXTENTS_FL).

</td>
</tr>
<tr>
<td>


0x100000

</td>
<td>


Verity protected file (EXT4_VERITY_FL).

</td>
</tr>
<tr>
<td>


0x200000

</td>
<td>


Inode stores a large extended attribute value in its data blocks (EXT4_EA_INODE_FL).

</td>
</tr>
<tr>
<td>


0x400000

</td>
<td>


This file has blocks allocated past EOF (EXT4_EOFBLOCKS_FL). (deprecated)

</td>
</tr>
<tr>
<td>


0x01000000

</td>
<td>


Inode is a snapshot (`EXT4_SNAPFILE_FL`). (not in mainline)

</td>
</tr>
<tr>
<td>


0x04000000

</td>
<td>


Snapshot is being deleted (`EXT4_SNAPFILE_DELETED_FL`). (not in mainline)

</td>
</tr>
<tr>
<td>


0x08000000

</td>
<td>


Snapshot shrink has completed (`EXT4_SNAPFILE_SHRUNK_FL`). (not in mainline)

</td>
</tr>
<tr>
<td>


0x10000000

</td>
<td>


Inode has inline data (EXT4_INLINE_DATA_FL).

</td>
</tr>
<tr>
<td>


0x20000000

</td>
<td>


Create children with the same project ID (EXT4_PROJINHERIT_FL).

</td>
</tr>
<tr>
<td>


0x40000000

</td>
<td>


Use case-insensitive lookups for directory contents (EXT4_CASEFOLD_FL).

</td>
</tr>
<tr>
<td>


0x80000000

</td>
<td>


Reserved for ext4 library (EXT4_RESERVED_FL).

</td>
</tr>
<tr>
<td>




</td>
<td>


Aggregate flags:

</td>
</tr>
<tr>
<td>


0x705BDFFF

</td>
<td>


User-visible flags.

</td>
</tr>
<tr>
<td>


0x604BC0FF

</td>
<td>


User-modifiable flags. Note that while EXT4_JOURNAL_DATA_FL and EXT4_EXTENTS_FL can be set with setattr, they are not in the kernel's EXT4_FL_USER_MODIFIABLE mask, since it needs to handle the setting of these flags in a special manner and they are masked out of the set of flags that are saved directly to i_flags.

</td>
</tr>
</tbody>
</table>

<a id="rst-i-osd1"></a>

The `osd1` field has multiple meanings depending on the creator:

Linux:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


l_i_version

</td>
<td>


Inode version. However, if the EA_INODE inode flag is set, this inode stores an extended attribute value and this field contains the upper 32 bits of the attribute value's reference count.

</td>
</tr>
</tbody>
</table>

Hurd:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


h_i_translator

</td>
<td>


??

</td>
</tr>
</tbody>
</table>

Masix:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


m_i_reserved

</td>
<td>


??

</td>
</tr>
</tbody>
</table>

<a id="rst-i-osd2"></a>

The `osd2` field has multiple meanings depending on the filesystem creator:

Linux:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le16

</td>
<td>


l_i_blocks_high

</td>
<td>


Upper 16-bits of the block count. Please see the note attached to i_blocks_lo.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


\__le16

</td>
<td>


l_i_file_acl_high

</td>
<td>


Upper 16-bits of the extended attribute block (historically, the file ACL location). See the Extended Attributes section below.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


l_i_uid_high

</td>
<td>


Upper 16-bits of the Owner UID.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__le16

</td>
<td>


l_i_gid_high

</td>
<td>


Upper 16-bits of the GID.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le16

</td>
<td>


l_i_checksum_lo

</td>
<td>


Lower 16-bits of the inode checksum.

</td>
</tr>
<tr>
<td>


0xA

</td>
<td>


\__le16

</td>
<td>


l_i_reserved

</td>
<td>


Unused.

</td>
</tr>
</tbody>
</table>

Hurd:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le16

</td>
<td>


h_i_reserved1

</td>
<td>


??

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


\__u16

</td>
<td>


h_i_mode_high

</td>
<td>


Upper 16-bits of the file mode.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le16

</td>
<td>


h_i_uid_high

</td>
<td>


Upper 16-bits of the Owner UID.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__le16

</td>
<td>


h_i_gid_high

</td>
<td>


Upper 16-bits of the GID.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__u32

</td>
<td>


h_i_author

</td>
<td>


Author code?

</td>
</tr>
</tbody>
</table>

Masix:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Size

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le16

</td>
<td>


h_i_reserved1

</td>
<td>


??

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


\__u16

</td>
<td>


m_i_file_acl_high

</td>
<td>


Upper 16-bits of the extended attribute block (historically, the file ACL location).

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__u32

</td>
<td>


m_i_reserved2\[2\]

</td>
<td>


??

</td>
</tr>
</tbody>
</table>

<a id="rst-inode-size"></a>

## Inode Size

In ext2 and ext3, the inode structure size was fixed at 128 bytes (`EXT2_GOOD_OLD_INODE_SIZE`) and each inode had a disk record size of 128 bytes. Starting with ext4, it is possible to allocate a larger on-disk inode at format time for all inodes in the filesystem to provide space beyond the end of the original ext2 inode. The on-disk inode record size is recorded in the superblock as `s_inode_size`. The number of bytes actually used by struct ext4_inode beyond the original 128-byte ext2 inode is recorded in the `i_extra_isize` field for each inode, which allows struct ext4_inode to grow for a new kernel without having to upgrade all of the on-disk inodes. Access to fields beyond EXT2_GOOD_OLD_INODE_SIZE should be verified to be within `i_extra_isize`. By default, ext4 inode records are 256 bytes, and (as of August 2019) the inode structure is 160 bytes (`i_extra_isize = 32`). The extra space between the end of the inode structure and the end of the inode record can be used to store extended attributes. Each inode record can be as large as the filesystem block size, though this is not terribly efficient.

<a id="rst-finding-an-inode"></a>

## Finding an Inode

Each block group contains `sb->s_inodes_per_group` inodes. Because inode 0 is defined not to exist, this formula can be used to find the block group that an inode lives in: `bg = (inode_num - 1) / sb->s_inodes_per_group`. The particular inode can be found within the block group's inode table at `index = (inode_num - 1) % sb->s_inodes_per_group`. To get the byte address within the inode table, use `offset = index * sb->s_inode_size`.

<a id="rst-inode-timestamps"></a>

## Inode Timestamps

Four timestamps are recorded in the lower 128 bytes of the inode structure -- inode change time (ctime), access time (atime), data modification time (mtime), and deletion time (dtime). The four fields are 32-bit signed integers that represent seconds since the Unix epoch (1970-01-01 00:00:00 GMT), which means that the fields will overflow in January 2038. If the filesystem does not have orphan_file feature, inodes that are not linked from any directory but are still open (orphan inodes) have the dtime field overloaded for use with the orphan list. The superblock field `s_last_orphan` points to the first inode in the orphan list; dtime is then the number of the next orphaned inode, or zero if there are no more orphans.

If the inode structure size `sb->s_inode_size` is larger than 128 bytes and the `i_inode_extra` field is large enough to encompass the respective `i_[cma]time_extra` field, the ctime, atime, and mtime inode fields are widened to 64 bits. Within this “extra” 32-bit field, the lower two bits are used to extend the 32-bit seconds field to be 34 bit wide; the upper 30 bits are used to provide nanosecond timestamp accuracy. Therefore, timestamps should not overflow until May 2446. dtime was not widened. There is also a fifth timestamp to record inode creation time (crtime); this field is 64-bits wide and decoded in the same manner as 64-bit \[cma\]time. Neither crtime nor dtime are accessible through the regular stat() interface, though debugfs will report them.

We use the 32-bit signed time value plus (2^32 \* (extra epoch bits)). In other words:


<table>
<thead>
<tr>
<th>


Extra epoch bits

</th>
<th>


MSB of 32-bit time

</th>
<th>


Adjustment for signed 32-bit to 64-bit tv_sec

</th>
<th>


Decoded 64-bit tv_sec

</th>
<th>


valid time range

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0 0

</td>
<td>


1

</td>
<td>


0

</td>
<td>


`-0x80000000 - -0x00000001`

</td>
<td>


1901-12-13 to 1969-12-31

</td>
</tr>
<tr>
<td>


0 0

</td>
<td>


0

</td>
<td>


0

</td>
<td>


`0x000000000 - 0x07fffffff`

</td>
<td>


1970-01-01 to 2038-01-19

</td>
</tr>
<tr>
<td>


0 1

</td>
<td>


1

</td>
<td>


0x100000000

</td>
<td>


`0x080000000 - 0x0ffffffff`

</td>
<td>


2038-01-19 to 2106-02-07

</td>
</tr>
<tr>
<td>


0 1

</td>
<td>


0

</td>
<td>


0x100000000

</td>
<td>


`0x100000000 - 0x17fffffff`

</td>
<td>


2106-02-07 to 2174-02-25

</td>
</tr>
<tr>
<td>


1 0

</td>
<td>


1

</td>
<td>


0x200000000

</td>
<td>


`0x180000000 - 0x1ffffffff`

</td>
<td>


2174-02-25 to 2242-03-16

</td>
</tr>
<tr>
<td>


1 0

</td>
<td>


0

</td>
<td>


0x200000000

</td>
<td>


`0x200000000 - 0x27fffffff`

</td>
<td>


2242-03-16 to 2310-04-04

</td>
</tr>
<tr>
<td>


1 1

</td>
<td>


1

</td>
<td>


0x300000000

</td>
<td>


`0x280000000 - 0x2ffffffff`

</td>
<td>


2310-04-04 to 2378-04-22

</td>
</tr>
<tr>
<td>


1 1

</td>
<td>


0

</td>
<td>


0x300000000

</td>
<td>


`0x300000000 - 0x37fffffff`

</td>
<td>


2378-04-22 to 2446-05-10

</td>
</tr>
</tbody>
</table>

This is a somewhat odd encoding since there are effectively seven times as many positive values as negative values. There have also been long-standing bugs decoding and encoding dates beyond 2038, which don't seem to be fixed as of kernel 3.12 and e2fsprogs 1.42.8. 64-bit kernels incorrectly use the extra epoch bits 1,1 for dates between 1901 and 1970. At some point the kernel will be fixed and e2fsck will fix this situation, assuming that it is run before 2310.

---

# Journal (jbd2)

_Peios Kernel / Internals / Filesystems / ext4_

> Introduced in ext3, the ext4 filesystem employs a journal to protect the filesystem against metadata inconsistencies in the case of a system crash. Up to 10,240,000 file system blocks (see man mke2fs(8) for more details on journal size…

<a id="rst-journal-jbd2"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Introduced in ext3, the ext4 filesystem employs a journal to protect the filesystem against metadata inconsistencies in the case of a system crash. Up to 10,240,000 file system blocks (see man mke2fs(8) for more details on journal size limits) can be reserved inside the filesystem as a place to land “important” data writes on-disk as quickly as possible. Once the important data transaction is fully written to the disk and flushed from the disk write cache, a record of the data being committed is also written to the journal. At some later point in time, the journal code writes the transactions to their final locations on disk (this could involve a lot of seeking or a lot of small read-write-erases) before erasing the commit record. Should the system crash during the second slow write, the journal can be replayed all the way to the latest commit record, guaranteeing the atomicity of whatever gets written through the journal to the disk. The effect of this is to guarantee that the filesystem does not become stuck midway through a metadata update.

For performance reasons, ext4 by default only writes filesystem metadata through the journal. This means that file data blocks are /not/ guaranteed to be in any consistent state after a crash. If this default guarantee level (`data=ordered`) is not satisfactory, there is a mount option to control journal behavior. If `data=journal`, all data and metadata are written to disk through the journal. This is slower but safest. If `data=writeback`, dirty data blocks are not flushed to the disk before the metadata are written to disk through the journal.

In case of `data=ordered` mode, Ext4 also supports fast commits which help reduce commit latency significantly. The default `data=ordered` mode works by logging metadata blocks to the journal. In fast commit mode, Ext4 only stores the minimal delta needed to recreate the affected metadata in fast commit space that is shared with JBD2. Once the fast commit area fills in or if fast commit is not possible or if JBD2 commit timer goes off, Ext4 performs a traditional full commit. A full commit invalidates all the fast commits that happened before it and thus it makes the fast commit area empty for further fast commits. This feature needs to be enabled at mkfs time.

The journal inode is typically inode 8. The first 68 bytes of the journal inode are replicated in the ext4 superblock. The journal itself is normal (but hidden) file within the filesystem. The file usually consumes an entire block group, though mke2fs tries to put it in the middle of the disk.

All fields in jbd2 are written to disk in big-endian order. This is the opposite of ext4.

NOTE: Both ext4 and ocfs2 use jbd2.

The maximum size of a journal embedded in an ext4 filesystem is 2^32 blocks. jbd2 itself does not seem to care.

<a id="rst-layout"></a>

## Layout

Generally speaking, the journal has this format:


<table>
<thead>
<tr>
<th>


Superblock

</th>
<th>


descriptor_block (data_blocks or revocation_block) \[more data or revocations\] commmit_block

</th>
<th>


\[more transactions...\]

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>


One transaction

</td>
<td>




</td>
</tr>
</tbody>
</table>

Notice that a transaction begins with either a descriptor and some data, or a block revocation list. A finished transaction always ends with a commit. If there is no commit record (or the checksums don't match), the transaction will be discarded during replay.

<a id="rst-external-journal"></a>

## External Journal

Optionally, an ext4 filesystem can be created with an external journal device (as opposed to an internal journal, which uses a reserved inode). In this case, on the filesystem device, `s_journal_inum` should be zero and `s_journal_uuid` should be set. On the journal device there will be an ext4 super block in the usual place, with a matching UUID. The journal superblock will be in the next full block after the superblock.


<table>
<thead>
<tr>
<th>


1024 bytes of padding

</th>
<th>


ext4 Superblock

</th>
<th>


Journal Superblock

</th>
<th>


descriptor_block (data_blocks or revocation_block) \[more data or revocations\] commmit_block

</th>
<th>


\[more transactions...\]

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


One transaction

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-block-header"></a>

## Block Header

Every block in the journal starts with a common 12-byte header `struct journal_header_s`:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__be32

</td>
<td>


h_magic

</td>
<td>


jbd2 magic number, 0xC03B3998.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__be32

</td>
<td>


h_blocktype

</td>
<td>


Description of what this block contains. See the [jbd2_blocktype](<#rst-jbd2-blocktype>) table below.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__be32

</td>
<td>


h_sequence

</td>
<td>


The transaction ID that goes with this block.

</td>
</tr>
</tbody>
</table>

<a id="rst-jbd2-blocktype"></a>

The journal block type can be any one of:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


1

</td>
<td>


Descriptor. This block precedes a series of data blocks that were written through the journal during a transaction.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Block commit record. This block signifies the completion of a transaction.

</td>
</tr>
<tr>
<td>


3

</td>
<td>


Journal superblock, v1.

</td>
</tr>
<tr>
<td>


4

</td>
<td>


Journal superblock, v2.

</td>
</tr>
<tr>
<td>


5

</td>
<td>


Block revocation records. This speeds up recovery by enabling the journal to skip writing blocks that were subsequently rewritten.

</td>
</tr>
</tbody>
</table>

<a id="rst-super-block"></a>

## Super Block

The super block for the journal is much simpler as compared to ext4's. The key data kept within are size of the journal, and where to find the start of the log of transactions.

The journal superblock is recorded as `struct journal_superblock_s`, which is 1024 bytes long:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


Static information describing the journal.

</td>
</tr>
<tr>
<td>


0x0

</td>
<td>


journal_header_t (12 bytes)

</td>
<td>


s_header

</td>
<td>


Common header identifying this as a superblock.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__be32

</td>
<td>


s_blocksize

</td>
<td>


Journal device block size.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__be32

</td>
<td>


s_maxlen

</td>
<td>


Total number of blocks in this journal.

</td>
</tr>
<tr>
<td>


0x14

</td>
<td>


\__be32

</td>
<td>


s_first

</td>
<td>


First block of log information.

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


Dynamic information describing the current state of the log.

</td>
</tr>
<tr>
<td>


0x18

</td>
<td>


\__be32

</td>
<td>


s_sequence

</td>
<td>


First commit ID expected in log.

</td>
</tr>
<tr>
<td>


0x1C

</td>
<td>


\__be32

</td>
<td>


s_start

</td>
<td>


Block number of the start of log. Contrary to the comments, this field being zero does not imply that the journal is clean\!

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


\__be32

</td>
<td>


s_errno

</td>
<td>


Error value, as set by jbd2_journal_abort().

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


The remaining fields are only valid in a v2 superblock.

</td>
</tr>
<tr>
<td>


0x24

</td>
<td>


\__be32

</td>
<td>


s_feature_compat;

</td>
<td>


Compatible feature set. See the table [jbd2_compat](<#rst-jbd2-compat>) below.

</td>
</tr>
<tr>
<td>


0x28

</td>
<td>


\__be32

</td>
<td>


s_feature_incompat

</td>
<td>


Incompatible feature set. See the table [jbd2_incompat](<#rst-jbd2-incompat>) below.

</td>
</tr>
<tr>
<td>


0x2C

</td>
<td>


\__be32

</td>
<td>


s_feature_ro_compat

</td>
<td>


Read-only compatible feature set. There aren't any of these currently.

</td>
</tr>
<tr>
<td>


0x30

</td>
<td>


\__u8

</td>
<td>


s_uuid\[16\]

</td>
<td>


128-bit uuid for journal. This is compared against the copy in the ext4 super block at mount time.

</td>
</tr>
<tr>
<td>


0x40

</td>
<td>


\__be32

</td>
<td>


s_nr_users

</td>
<td>


Number of file systems sharing this journal.

</td>
</tr>
<tr>
<td>


0x44

</td>
<td>


\__be32

</td>
<td>


s_dynsuper

</td>
<td>


Location of dynamic super block copy. (Not used?)

</td>
</tr>
<tr>
<td>


0x48

</td>
<td>


\__be32

</td>
<td>


s_max_transaction

</td>
<td>


Limit of journal blocks per transaction. (Not used?)

</td>
</tr>
<tr>
<td>


0x4C

</td>
<td>


\__be32

</td>
<td>


s_max_trans_data

</td>
<td>


Limit of data blocks per transaction. (Not used?)

</td>
</tr>
<tr>
<td>


0x50

</td>
<td>


\__u8

</td>
<td>


s_checksum_type

</td>
<td>


Checksum algorithm used for the journal.  See [jbd2_checksum_type](<#rst-jbd2-checksum-type>) for more info.

</td>
</tr>
<tr>
<td>


0x51

</td>
<td>


\__u8\[3\]

</td>
<td>


s_padding2

</td>
<td>




</td>
</tr>
<tr>
<td>


0x54

</td>
<td>


\__be32

</td>
<td>


s_num_fc_blocks

</td>
<td>


Number of fast commit blocks in the journal.

</td>
</tr>
<tr>
<td>


0x58

</td>
<td>


\__be32

</td>
<td>


s_head

</td>
<td>


Block number of the head (first unused block) of the journal, only up-to-date when the journal is empty.

</td>
</tr>
<tr>
<td>


0x5C

</td>
<td>


\__u32

</td>
<td>


s_padding\[40\]

</td>
<td>




</td>
</tr>
<tr>
<td>


0xFC

</td>
<td>


\__be32

</td>
<td>


s_checksum

</td>
<td>


Checksum of the entire superblock, with this field set to zero.

</td>
</tr>
<tr>
<td>


0x100

</td>
<td>


\__u8

</td>
<td>


s_users\[16\*48\]

</td>
<td>


ids of all file systems sharing the log. e2fsprogs/Linux don't allow shared external journals, but I imagine Lustre (or ocfs2?), which use the jbd2 code, might.

</td>
</tr>
</tbody>
</table>

<a id="rst-jbd2-compat"></a>

The journal compat features are any combination of the following:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


Journal maintains checksums on the data blocks. (JBD2_FEATURE_COMPAT_CHECKSUM)

</td>
</tr>
</tbody>
</table>

<a id="rst-jbd2-incompat"></a>

The journal incompat features are any combination of the following:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


Journal has block revocation records. (JBD2_FEATURE_INCOMPAT_REVOKE)

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


Journal can deal with 64-bit block numbers. (JBD2_FEATURE_INCOMPAT_64BIT)

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


Journal commits asynchronously. (JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT)

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


This journal uses v2 of the checksum on-disk format. Each journal metadata block gets its own checksum, and the block tags in the descriptor table contain checksums for each of the data blocks in the journal. (JBD2_FEATURE_INCOMPAT_CSUM_V2)

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


This journal uses v3 of the checksum on-disk format. This is the same as v2, but the journal block tag size is fixed regardless of the size of block numbers. (JBD2_FEATURE_INCOMPAT_CSUM_V3)

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


Journal has fast commit blocks. (JBD2_FEATURE_INCOMPAT_FAST_COMMIT)

</td>
</tr>
</tbody>
</table>

<a id="rst-jbd2-checksum-type"></a>

Journal checksum type codes are one of the following.  crc32 or crc32c are the most likely choices.


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


1

</td>
<td>


CRC32

</td>
</tr>
<tr>
<td>


2

</td>
<td>


MD5

</td>
</tr>
<tr>
<td>


3

</td>
<td>


SHA1

</td>
</tr>
<tr>
<td>


4

</td>
<td>


CRC32C

</td>
</tr>
</tbody>
</table>

<a id="rst-descriptor-block"></a>

## Descriptor Block

The descriptor block contains an array of journal block tags that describe the final locations of the data blocks that follow in the journal. Descriptor blocks are open-coded instead of being completely described by a data structure, but here is the block structure anyway. Descriptor blocks consume at least 36 bytes, but use a full block:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Descriptor

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


journal_header_t

</td>
<td>


(open coded)

</td>
<td>


Common block header.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


struct journal_block_tag_s

</td>
<td>


open coded array\[\]

</td>
<td>


Enough tags either to fill up the block or to describe all the data blocks that follow this descriptor block.

</td>
</tr>
</tbody>
</table>

Journal block tags have any of the following formats, depending on which journal feature and block tag flags are set.

If JBD2_FEATURE_INCOMPAT_CSUM_V3 is set, the journal block tag is defined as `struct journal_block_tag3_s`, which looks like the following. The size is 16 or 32 bytes.


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Descriptor

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__be32

</td>
<td>


t_blocknr

</td>
<td>


Lower 32-bits of the location of where the corresponding data block should end up on disk.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__be32

</td>
<td>


t_flags

</td>
<td>


Flags that go with the descriptor. See the table [jbd2_tag_flags](<#rst-jbd2-tag-flags>) for more info.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__be32

</td>
<td>


t_blocknr_high

</td>
<td>


Upper 32-bits of the location of where the corresponding data block should end up on disk. This is zero if JBD2_FEATURE_INCOMPAT_64BIT is not enabled.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__be32

</td>
<td>


t_checksum

</td>
<td>


Checksum of the journal UUID, the sequence number, and the data block.

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


This field appears to be open coded. It always comes at the end of the tag, after t_checksum. This field is not present if the "same UUID" flag is set.

</td>
</tr>
<tr>
<td>


0x8 or 0xC

</td>
<td>


char

</td>
<td>


uuid\[16\]

</td>
<td>


A UUID to go with this tag. This field appears to be copied from the `j_uuid` field in `struct journal_s`, but only tune2fs touches that field.

</td>
</tr>
</tbody>
</table>

<a id="rst-jbd2-tag-flags"></a>

The journal tag flags are any combination of the following:


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x1

</td>
<td>


On-disk block is escaped. The first four bytes of the data block just happened to match the jbd2 magic number.

</td>
</tr>
<tr>
<td>


0x2

</td>
<td>


This block has the same UUID as previous, therefore the UUID field is omitted.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


The data block was deleted by the transaction. (Not used?)

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


This is the last tag in this descriptor block.

</td>
</tr>
</tbody>
</table>

If JBD2_FEATURE_INCOMPAT_CSUM_V3 is NOT set, the journal block tag is defined as `struct journal_block_tag_s`, which looks like the following. The size is 8, 12, 24, or 28 bytes:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Descriptor

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__be32

</td>
<td>


t_blocknr

</td>
<td>


Lower 32-bits of the location of where the corresponding data block should end up on disk.

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__be16

</td>
<td>


t_checksum

</td>
<td>


Checksum of the journal UUID, the sequence number, and the data block. Note that only the lower 16 bits are stored.

</td>
</tr>
<tr>
<td>


0x6

</td>
<td>


\__be16

</td>
<td>


t_flags

</td>
<td>


Flags that go with the descriptor. See the table [jbd2_tag_flags](<#rst-jbd2-tag-flags>) for more info.

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


This next field is only present if the super block indicates support for 64-bit block numbers.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__be32

</td>
<td>


t_blocknr_high

</td>
<td>


Upper 32-bits of the location of where the corresponding data block should end up on disk.

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


This field appears to be open coded. It always comes at the end of the tag, after t_flags or t_blocknr_high. This field is not present if the "same UUID" flag is set.

</td>
</tr>
<tr>
<td>


0x8 or 0xC

</td>
<td>


char

</td>
<td>


uuid\[16\]

</td>
<td>


A UUID to go with this tag. This field appears to be copied from the `j_uuid` field in `struct journal_s`, but only tune2fs touches that field.

</td>
</tr>
</tbody>
</table>

If JBD2_FEATURE_INCOMPAT_CSUM_V2 or JBD2_FEATURE_INCOMPAT_CSUM_V3 are set, the end of the block is a `struct jbd2_journal_block_tail`, which looks like this:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Descriptor

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__be32

</td>
<td>


t_checksum

</td>
<td>


Checksum of the journal UUID + the descriptor block, with this field set to zero.

</td>
</tr>
</tbody>
</table>

<a id="rst-data-block"></a>

## Data Block

In general, the data blocks being written to disk through the journal are written verbatim into the journal file after the descriptor block. However, if the first four bytes of the block match the jbd2 magic number then those four bytes are replaced with zeroes and the “escaped” flag is set in the descriptor block tag.

<a id="rst-revocation-block"></a>

## Revocation Block

A revocation block is used to prevent replay of a block in an earlier transaction. This is used to mark blocks that were journalled at one time but are no longer journalled. Typically this happens if a metadata block is freed and re-allocated as a file data block; in this case, a journal replay after the file block was written to disk will cause corruption.

**NOTE**: This mechanism is NOT used to express “this journal block is superseded by this other journal block”, as the author (djwong) mistakenly thought. Any block being added to a transaction will cause the removal of all existing revocation records for that block.

Revocation blocks are described in `struct jbd2_journal_revoke_header_s`, are at least 16 bytes in length, but use a full block:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


journal_header_t

</td>
<td>


r_header

</td>
<td>


Common block header.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


\__be32

</td>
<td>


r_count

</td>
<td>


Number of bytes used in this block.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__be32 or \__be64

</td>
<td>


blocks\[0\]

</td>
<td>


Blocks to revoke.

</td>
</tr>
</tbody>
</table>

After r_count is a linear array of block numbers that are effectively revoked by this transaction. The size of each block number is 8 bytes if the superblock advertises 64-bit block number support, or 4 bytes otherwise.

If JBD2_FEATURE_INCOMPAT_CSUM_V2 or JBD2_FEATURE_INCOMPAT_CSUM_V3 are set, the end of the revocation block is a `struct jbd2_journal_revoke_tail`, which has this format:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__be32

</td>
<td>


r_checksum

</td>
<td>


Checksum of the journal UUID + revocation block

</td>
</tr>
</tbody>
</table>

<a id="rst-commit-block"></a>

## Commit Block

The commit block is a sentry that indicates that a transaction has been completely written to the journal. Once this commit block reaches the journal, the data stored with this transaction can be written to their final locations on disk.

The commit block is described by `struct commit_header`, which is 32 bytes long (but uses a full block):


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Descriptor

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


journal_header_s

</td>
<td>


(open coded)

</td>
<td>


Common block header.

</td>
</tr>
<tr>
<td>


0xC

</td>
<td>


unsigned char

</td>
<td>


h_chksum_type

</td>
<td>


The type of checksum to use to verify the integrity of the data blocks in the transaction. See [jbd2_checksum_type](<#rst-jbd2-checksum-type>) for more info.

</td>
</tr>
<tr>
<td>


0xD

</td>
<td>


unsigned char

</td>
<td>


h_chksum_size

</td>
<td>


The number of bytes used by the checksum. Most likely 4.

</td>
</tr>
<tr>
<td>


0xE

</td>
<td>


unsigned char

</td>
<td>


h_padding\[2\]

</td>
<td>




</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


\__be32

</td>
<td>


h_chksum\[JBD2_CHECKSUM_BYTES\]

</td>
<td>


32 bytes of space to store checksums. If JBD2_FEATURE_INCOMPAT_CSUM_V2 or JBD2_FEATURE_INCOMPAT_CSUM_V3 are set, the first `__be32` is the checksum of the journal UUID and the entire commit block, with this field zeroed. If JBD2_FEATURE_COMPAT_CHECKSUM is set, the first `__be32` is the crc32 of all the blocks already written to the transaction.

</td>
</tr>
<tr>
<td>


0x30

</td>
<td>


\__be64

</td>
<td>


h_commit_sec

</td>
<td>


The time that the transaction was committed, in seconds since the epoch.

</td>
</tr>
<tr>
<td>


0x38

</td>
<td>


\__be32

</td>
<td>


h_commit_nsec

</td>
<td>


Nanoseconds component of the above timestamp.

</td>
</tr>
</tbody>
</table>

<a id="rst-fast-commits"></a>

## Fast commits

Fast commit area is organized as a log of tag length values. Each TLV has a `struct ext4_fc_tl` in the beginning which stores the tag and the length of the entire field. It is followed by variable length tag specific value. Here is the list of supported tags and their meanings:


<table>
<thead>
<tr>
<th>


Tag

</th>
<th>


Meaning

</th>
<th>


Value struct

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


EXT4_FC_TAG_HEAD

</td>
<td>


Fast commit area header

</td>
<td>


`struct ext4_fc_head`

</td>
<td>


Stores the TID of the transaction after which these fast commits should be applied.

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_ADD_RANGE

</td>
<td>


Add extent to inode

</td>
<td>


`struct ext4_fc_add_range`

</td>
<td>


Stores the inode number and extent to be added in this inode

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_DEL_RANGE

</td>
<td>


Remove logical offsets to inode

</td>
<td>


`struct ext4_fc_del_range`

</td>
<td>


Stores the inode number and the logical offset range that needs to be removed

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_CREAT

</td>
<td>


Create directory entry for a newly created file

</td>
<td>


`struct ext4_fc_dentry_info`

</td>
<td>


Stores the parent inode number, inode number and directory entry of the newly created file

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_LINK

</td>
<td>


Link a directory entry to an inode

</td>
<td>


`struct ext4_fc_dentry_info`

</td>
<td>


Stores the parent inode number, inode number and directory entry

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_UNLINK

</td>
<td>


Unlink a directory entry of an inode

</td>
<td>


`struct ext4_fc_dentry_info`

</td>
<td>


Stores the parent inode number, inode number and directory entry

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_PAD

</td>
<td>


Padding (unused area)

</td>
<td>


None

</td>
<td>


Unused bytes in the fast commit area.

</td>
</tr>
<tr>
<td>


EXT4_FC_TAG_TAIL

</td>
<td>


Mark the end of a fast commit

</td>
<td>


`struct ext4_fc_tail`

</td>
<td>


Stores the TID of the commit, CRC of the fast commit of which this tag represents the end of

</td>
</tr>
</tbody>
</table>

<a id="rst-fast-commit-replay-idempotence"></a>

## Fast Commit Replay Idempotence

Fast commits tags are idempotent in nature provided the recovery code follows certain rules. The guiding principle that the commit path follows while committing is that it stores the result of a particular operation instead of storing the procedure.

Let's consider this rename operation: 'mv /a /b'. Let's assume dirent '/a' was associated with inode 10. During fast commit, instead of storing this operation as a procedure "rename a to b", we store the resulting file system state as a "series" of outcomes:

- Link dirent b to inode 10

- Unlink dirent a

- Inode 10 with valid refcount

Now when recovery code runs, it needs "enforce" this state on the file system. This is what guarantees idempotence of fast commit replay.

Let's take an example of a procedure that is not idempotent and see how fast commits make it idempotent. Consider following sequence of operations:

1. rm A

2. mv B A

3. read A

If we store this sequence of operations as is then the replay is not idempotent. Let's say while in replay, we crash after (2). During the second replay, file A (which was actually created as a result of "mv B A" operation) would get deleted. Thus, file named A would be absent when we try to read A. So, this sequence of operations is not idempotent. However, as mentioned above, instead of storing the procedure fast commits store the outcome of each procedure. Thus the fast commit log for above procedure would be as follows:

(Let's assume dirent A was linked to inode 10 and dirent B was linked to inode 11 before the replay)

1. Unlink A

2. Link A to inode 11

3. Unlink B

4. Inode 11

If we crash after (3) we will have file A linked to inode 11. During the second replay, we will remove file A (inode 11). But we will create it back and make it point to inode 11. We won't find B, so we'll just skip that step. At this point, the refcount for inode 11 is not reliable, but that gets fixed by the replay of last inode 11 tag. Thus, by converting a non-idempotent procedure into a series of idempotent outcomes, fast commits ensured idempotence during the replay.

<a id="rst-journal-checkpoint"></a>

## Journal Checkpoint

Checkpointing the journal ensures all transactions and their associated buffers are submitted to the disk. In-progress transactions are waited upon and included in the checkpoint. Checkpointing is used internally during critical updates to the filesystem including journal recovery, filesystem resizing, and freeing of the journal_t structure.

A journal checkpoint can be triggered from userspace via the ioctl EXT4_IOC_CHECKPOINT. This ioctl takes a single, u64 argument for flags. Currently, three flags are supported. First, EXT4_IOC_CHECKPOINT_FLAG_DRY_RUN can be used to verify input to the ioctl. It returns error if there is any invalid input, otherwise it returns success without performing any checkpointing. This can be used to check whether the ioctl exists on a system and to verify there are no issues with arguments or flags. The other two flags are EXT4_IOC_CHECKPOINT_FLAG_DISCARD and EXT4_IOC_CHECKPOINT_FLAG_ZEROOUT. These flags cause the journal blocks to be discarded or zero-filled, respectively, after the journal checkpoint is complete. EXT4_IOC_CHECKPOINT_FLAG_DISCARD and EXT4_IOC_CHECKPOINT_FLAG_ZEROOUT cannot both be set. The ioctl may be useful when snapshotting a system or for complying with content deletion SLOs.

---

# Multiple Mount Protection

_Peios Kernel / Internals / Filesystems / ext4_

> Multiple mount protection (MMP) is a feature that protects the filesystem against multiple hosts trying to use the filesystem simultaneously. When a filesystem is opened (for mounting, or fsck, etc.), the MMP code running on the node (call…

<a id="rst-multiple-mount-protection"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Multiple mount protection (MMP) is a feature that protects the filesystem against multiple hosts trying to use the filesystem simultaneously. When a filesystem is opened (for mounting, or fsck, etc.), the MMP code running on the node (call it node A) checks a sequence number. If the sequence number is EXT4_MMP_SEQ_CLEAN, the open continues. If the sequence number is EXT4_MMP_SEQ_FSCK, then fsck is (hopefully) running, and open fails immediately. Otherwise, the open code will wait for twice the specified MMP check interval and check the sequence number again. If the sequence number has changed, then the filesystem is active on another machine and the open fails. If the MMP code passes all of those checks, a new MMP sequence number is generated and written to the MMP block, and the mount proceeds.

While the filesystem is live, the kernel sets up a timer to re-check the MMP block at the specified MMP check interval. To perform the re-check, the MMP sequence number is re-read; if it does not match the in-memory MMP sequence number, then another node (node B) has mounted the filesystem, and node A remounts the filesystem read-only. If the sequence numbers match, the sequence number is incremented both in memory and on disk, and the re-check is complete.

The hostname and device filename are written into the MMP block whenever an open operation succeeds. The MMP code does not use these values; they are provided purely for informational purposes.

The checksum is calculated against the FS UUID and the MMP structure. The MMP structure (`struct mmp_struct`) is as follows:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


\__le32

</td>
<td>


mmp_magic

</td>
<td>


Magic number for MMP, 0x004D4D50 (“MMP”).

</td>
</tr>
<tr>
<td>


0x4

</td>
<td>


\__le32

</td>
<td>


mmp_seq

</td>
<td>


Sequence number, updated periodically.

</td>
</tr>
<tr>
<td>


0x8

</td>
<td>


\__le64

</td>
<td>


mmp_time

</td>
<td>


Time that the MMP block was last updated.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


char\[64\]

</td>
<td>


mmp_nodename

</td>
<td>


Hostname of the node that opened the filesystem.

</td>
</tr>
<tr>
<td>


0x50

</td>
<td>


char\[32\]

</td>
<td>


mmp_bdevname

</td>
<td>


Block device name of the filesystem.

</td>
</tr>
<tr>
<td>


0x70

</td>
<td>


\__le16

</td>
<td>


mmp_check_interval

</td>
<td>


The MMP re-check interval, in seconds.

</td>
</tr>
<tr>
<td>


0x72

</td>
<td>


\__le16

</td>
<td>


mmp_pad1

</td>
<td>


Zero.

</td>
</tr>
<tr>
<td>


0x74

</td>
<td>


\__le32\[226\]

</td>
<td>


mmp_pad2

</td>
<td>


Zero.

</td>
</tr>
<tr>
<td>


0x3FC

</td>
<td>


\__le32

</td>
<td>


mmp_checksum

</td>
<td>


Checksum of the MMP block.

</td>
</tr>
</tbody>
</table>

---

# Orphan file

_Peios Kernel / Internals / Filesystems / ext4_

> In unix there can inodes that are unlinked from directory hierarchy but that are still alive because they are open. In case of crash the filesystem has to clean up these inodes as otherwise they (and the blocks referenced from them) would…

<a id="rst-orphan-file"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In unix there can inodes that are unlinked from directory hierarchy but that are still alive because they are open. In case of crash the filesystem has to clean up these inodes as otherwise they (and the blocks referenced from them) would leak. Similarly if we truncate or extend the file, we need not be able to perform the operation in a single journalling transaction. In such case we track the inode as orphan so that in case of crash extra blocks allocated to the file get truncated.

Traditionally ext4 tracks orphan inodes in a form of single linked list where superblock contains the inode number of the last orphan inode (s_last_orphan field) and then each inode contains inode number of the previously orphaned inode (we overload i_dtime inode field for this). However this filesystem global single linked list is a scalability bottleneck for workloads that result in heavy creation of orphan inodes. When orphan file feature (COMPAT_ORPHAN_FILE) is enabled, the filesystem has a special inode (referenced from the superblock through s_orphan_file_inum) with several blocks. Each of these blocks has a structure:


<table>
<thead>
<tr>
<th>


Offset

</th>
<th>


Type

</th>
<th>


Name

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x0

</td>
<td>


Array of \__le32 entries

</td>
<td>


Orphan inode entries

</td>
<td>


Each \__le32 entry is either empty (0) or it contains inode number of an orphan inode.

</td>
</tr>
<tr>
<td>


blocksize-8

</td>
<td>


\__le32

</td>
<td>


ob_magic

</td>
<td>


Magic value stored in orphan block tail (0x0b10ca04)

</td>
</tr>
<tr>
<td>


blocksize-4

</td>
<td>


\__le32

</td>
<td>


ob_checksum

</td>
<td>


Checksum of the orphan block.

</td>
</tr>
</tbody>
</table>

When a filesystem with orphan file feature is writeably mounted, we set RO_COMPAT_ORPHAN_PRESENT feature in the superblock to indicate there may be valid orphan entries. In case we see this feature when mounting the filesystem, we read the whole orphan file and process all orphan inodes found there as usual. When cleanly unmounting the filesystem we remove the RO_COMPAT_ORPHAN_PRESENT feature to avoid unnecessary scanning of the orphan file and also make the filesystem fully compatible with older kernels.

---

# High Level Design

_Peios Kernel / Internals / Filesystems / ext4_

> An ext4 file system is split into a series of block groups. To reduce performance difficulties due to fragmentation, the block allocator tries very hard to keep each file's blocks within the same group, thereby reducing seek times. The…

<a id="rst-high-level-design"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

An ext4 file system is split into a series of block groups. To reduce performance difficulties due to fragmentation, the block allocator tries very hard to keep each file's blocks within the same group, thereby reducing seek times. The size of a block group is specified in `sb.s_blocks_per_group` blocks, though it can also calculated as 8 \* `block_size_in_bytes`. With the default block size of 4KiB, each group will contain 32,768 blocks, for a length of 128MiB. The number of block groups is the size of the device divided by the size of a block group.

All fields in ext4 are written to disk in little-endian order. HOWEVER, all fields in jbd2 (the journal) are written to disk in big-endian order.

- [Blocks](</kernel/internals/filesystems/ext4/blocks.md>)
- [Block Groups](</kernel/internals/filesystems/ext4/blockgroup.md>)
- [Special inodes](</kernel/internals/filesystems/ext4/special-inodes.md>)
- [Block and Inode Allocation Policy](</kernel/internals/filesystems/ext4/allocators.md>)
- [Checksums](</kernel/internals/filesystems/ext4/checksums.md>)
- [Bigalloc](</kernel/internals/filesystems/ext4/bigalloc.md>)
- [Inline Data](</kernel/internals/filesystems/ext4/inlinedata.md>)
- [Large Extended Attribute Values](</kernel/internals/filesystems/ext4/eainode.md>)
- [Verity files](</kernel/internals/filesystems/ext4/verity.md>)
- [Atomic Block Writes](</kernel/internals/filesystems/ext4/atomic-writes.md>)

---

# Special inodes

_Peios Kernel / Internals / Filesystems / ext4_

> ext4 reserves some inode for special features, as follows:

<a id="rst-special-inodes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ext4 reserves some inode for special features, as follows:


<table>
<thead>
<tr>
<th>


inode Number

</th>
<th>


Purpose

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


Doesn't exist; there is no inode 0.

</td>
</tr>
<tr>
<td>


1

</td>
<td>


List of defective blocks.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Root directory.

</td>
</tr>
<tr>
<td>


3

</td>
<td>


User quota.

</td>
</tr>
<tr>
<td>


4

</td>
<td>


Group quota.

</td>
</tr>
<tr>
<td>


5

</td>
<td>


Boot loader.

</td>
</tr>
<tr>
<td>


6

</td>
<td>


Undelete directory.

</td>
</tr>
<tr>
<td>


7

</td>
<td>


Reserved group descriptors inode. (“resize inode”)

</td>
</tr>
<tr>
<td>


8

</td>
<td>


Journal inode.

</td>
</tr>
<tr>
<td>


9

</td>
<td>


The “exclude” inode, for snapshots(?)

</td>
</tr>
<tr>
<td>


10

</td>
<td>


Replica inode, used for some non-upstream feature?

</td>
</tr>
<tr>
<td>


11

</td>
<td>


Traditional first non-reserved inode. Usually this is the lost+found directory. See s_first_ino in the superblock.

</td>
</tr>
</tbody>
</table>

Note that there are also some inodes allocated from non-reserved inode numbers for other filesystem features which are not referenced from standard directory hierarchy. These are generally reference from the superblock. They are:


<table>
<thead>
<tr>
<th>


Superblock field

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


s_lpf_ino

</td>
<td>


Inode number of lost+found directory.

</td>
</tr>
<tr>
<td>


s_prj_quota_inum

</td>
<td>


Inode number of quota file tracking project quotas

</td>
</tr>
<tr>
<td>


s_orphan_file_inum

</td>
<td>


Inode number of file tracking orphan inodes.

</td>
</tr>
</tbody>
</table>

---

# Super Block

_Peios Kernel / Internals / Filesystems / ext4_

> The superblock records various information about the enclosing filesystem, such as block counts, inode counts, supported features, maintenance information, and more.

<a id="rst-super-block"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The superblock records various information about the enclosing filesystem, such as block counts, inode counts, supported features, maintenance information, and more.

If the sparse\_super feature flag is set, redundant copies of the superblock and group descriptors are kept only in the groups whose group number is either 0 or a power of 3, 5, or 7. If the flag is not set, redundant copies are kept in all groups.

The superblock checksum is calculated against the superblock structure, which includes the FS UUID.

The ext4 superblock is laid out as follows in `struct ext4_super_block`:


<table>
<thead>
<tr>
<th>



Offset

</th>
<th>



Size

</th>
<th>



Name

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



\_\_le32

</td>
<td>



s\_inodes\_count

</td>
<td>



Total inode count.

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



\_\_le32

</td>
<td>



s\_blocks\_count\_lo

</td>
<td>



Total block count.

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



\_\_le32

</td>
<td>



s\_r\_blocks\_count\_lo

</td>
<td>



This number of blocks can only be allocated by the super-user.

</td>
</tr>
<tr>
<td>



0xC

</td>
<td>



\_\_le32

</td>
<td>



s\_free\_blocks\_count\_lo

</td>
<td>



Free block count.

</td>
</tr>
<tr>
<td>



0x10

</td>
<td>



\_\_le32

</td>
<td>



s\_free\_inodes\_count

</td>
<td>



Free inode count.

</td>
</tr>
<tr>
<td>



0x14

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_data\_block

</td>
<td>



First data block. This must be at least 1 for 1k-block filesystems and is typically 0 for all other block sizes.

</td>
</tr>
<tr>
<td>



0x18

</td>
<td>



\_\_le32

</td>
<td>



s\_log\_block\_size

</td>
<td>



Block size is 2 ^ (10 + s\_log\_block\_size).

</td>
</tr>
<tr>
<td>



0x1C

</td>
<td>



\_\_le32

</td>
<td>



s\_log\_cluster\_size

</td>
<td>



Cluster size is 2 ^ (10 + s\_log\_cluster\_size) blocks if bigalloc is enabled. Otherwise s\_log\_cluster\_size must equal s\_log\_block\_size.

</td>
</tr>
<tr>
<td>



0x20

</td>
<td>



\_\_le32

</td>
<td>



s\_blocks\_per\_group

</td>
<td>



Blocks per group.

</td>
</tr>
<tr>
<td>



0x24

</td>
<td>



\_\_le32

</td>
<td>



s\_clusters\_per\_group

</td>
<td>



Clusters per group, if bigalloc is enabled. Otherwise s\_clusters\_per\_group must equal s\_blocks\_per\_group.

</td>
</tr>
<tr>
<td>



0x28

</td>
<td>



\_\_le32

</td>
<td>



s\_inodes\_per\_group

</td>
<td>



Inodes per group.

</td>
</tr>
<tr>
<td>



0x2C

</td>
<td>



\_\_le32

</td>
<td>



s\_mtime

</td>
<td>



Mount time, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x30

</td>
<td>



\_\_le32

</td>
<td>



s\_wtime

</td>
<td>



Write time, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x34

</td>
<td>



\_\_le16

</td>
<td>



s\_mnt\_count

</td>
<td>



Number of mounts since the last fsck.

</td>
</tr>
<tr>
<td>



0x36

</td>
<td>



\_\_le16

</td>
<td>



s\_max\_mnt\_count

</td>
<td>



Number of mounts beyond which a fsck is needed.

</td>
</tr>
<tr>
<td>



0x38

</td>
<td>



\_\_le16

</td>
<td>



s\_magic

</td>
<td>



Magic signature, 0xEF53

</td>
</tr>
<tr>
<td>



0x3A

</td>
<td>



\_\_le16

</td>
<td>



s\_state

</td>
<td>



File system state. See [super\_state](<#rst-super-state>) for more info.

</td>
</tr>
<tr>
<td>



0x3C

</td>
<td>



\_\_le16

</td>
<td>



s\_errors

</td>
<td>



Behaviour when detecting errors. See [super\_errors](<#rst-super-errors>) for more info.

</td>
</tr>
<tr>
<td>



0x3E

</td>
<td>



\_\_le16

</td>
<td>



s\_minor\_rev\_level

</td>
<td>



Minor revision level.

</td>
</tr>
<tr>
<td>



0x40

</td>
<td>



\_\_le32

</td>
<td>



s\_lastcheck

</td>
<td>



Time of last check, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x44

</td>
<td>



\_\_le32

</td>
<td>



s\_checkinterval

</td>
<td>



Maximum time between checks, in seconds.

</td>
</tr>
<tr>
<td>



0x48

</td>
<td>



\_\_le32

</td>
<td>



s\_creator\_os

</td>
<td>



Creator OS. See the table [super\_creator](<#rst-super-creator>) for more info.

</td>
</tr>
<tr>
<td>



0x4C

</td>
<td>



\_\_le32

</td>
<td>



s\_rev\_level

</td>
<td>



Revision level. See the table [super\_revision](<#rst-super-revision>) for more info.

</td>
</tr>
<tr>
<td>



0x50

</td>
<td>



\_\_le16

</td>
<td>



s\_def\_resuid

</td>
<td>



Default uid for reserved blocks.

</td>
</tr>
<tr>
<td>



0x52

</td>
<td>



\_\_le16

</td>
<td>



s\_def\_resgid

</td>
<td>



Default gid for reserved blocks.

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>





</td>
<td>



These fields are for EXT4\_DYNAMIC\_REV superblocks only.

Note: the difference between the compatible feature set and the incompatible feature set is that if there is a bit set in the incompatible feature set that the kernel doesn't know about, it should refuse to mount the filesystem.

e2fsck's requirements are more strict; if it doesn't know about a feature in either the compatible or incompatible feature set, it must abort and not try to meddle with things it doesn't understand...

</td>
</tr>
<tr>
<td>



0x54

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_ino

</td>
<td>



First non-reserved inode.

</td>
</tr>
<tr>
<td>



0x58

</td>
<td>



\_\_le16

</td>
<td>



s\_inode\_size

</td>
<td>



Size of inode structure, in bytes.

</td>
</tr>
<tr>
<td>



0x5A

</td>
<td>



\_\_le16

</td>
<td>



s\_block\_group\_nr

</td>
<td>



Block group \# of this superblock.

</td>
</tr>
<tr>
<td>



0x5C

</td>
<td>



\_\_le32

</td>
<td>



s\_feature\_compat

</td>
<td>



Compatible feature set flags. Kernel can still read/write this fs even if it doesn't understand a flag; fsck should not do that. See the [super\_compat](<#rst-super-compat>) table for more info.

</td>
</tr>
<tr>
<td>



0x60

</td>
<td>



\_\_le32

</td>
<td>



s\_feature\_incompat

</td>
<td>



Incompatible feature set. If the kernel or fsck doesn't understand one of these bits, it should stop. See the [super\_incompat](<#rst-super-incompat>) table for more info.

</td>
</tr>
<tr>
<td>



0x64

</td>
<td>



\_\_le32

</td>
<td>



s\_feature\_ro\_compat

</td>
<td>



Readonly-compatible feature set. If the kernel doesn't understand one of these bits, it can still mount read-only. See the [super\_rocompat](<#rst-super-rocompat>) table for more info.

</td>
</tr>
<tr>
<td>



0x68

</td>
<td>



\_\_u8

</td>
<td>



s\_uuid\[16\]

</td>
<td>



128-bit UUID for volume.

</td>
</tr>
<tr>
<td>



0x78

</td>
<td>



char

</td>
<td>



s\_volume\_name\[16\]

</td>
<td>



Volume label.

</td>
</tr>
<tr>
<td>



0x88

</td>
<td>



char

</td>
<td>



s\_last\_mounted\[64\]

</td>
<td>



Directory where filesystem was last mounted.

</td>
</tr>
<tr>
<td>



0xC8

</td>
<td>



\_\_le32

</td>
<td>



s\_algorithm\_usage\_bitmap

</td>
<td>



For compression (Not used in e2fsprogs/Linux)

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>





</td>
<td>



Performance hints.  Directory preallocation should only happen if the EXT4\_FEATURE\_COMPAT\_DIR\_PREALLOC flag is on.

</td>
</tr>
<tr>
<td>



0xCC

</td>
<td>



\_\_u8

</td>
<td>



s\_prealloc\_blocks

</td>
<td>



\#. of blocks to try to preallocate for ... files? (Not used in e2fsprogs/Linux)

</td>
</tr>
<tr>
<td>



0xCD

</td>
<td>



\_\_u8

</td>
<td>



s\_prealloc\_dir\_blocks

</td>
<td>



\#. of blocks to preallocate for directories. (Not used in e2fsprogs/Linux)

</td>
</tr>
<tr>
<td>



0xCE

</td>
<td>



\_\_le16

</td>
<td>



s\_reserved\_gdt\_blocks

</td>
<td>



Number of reserved GDT entries for future filesystem expansion.

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>





</td>
<td>



Journalling support is valid only if EXT4\_FEATURE\_COMPAT\_HAS\_JOURNAL is set.

</td>
</tr>
<tr>
<td>



0xD0

</td>
<td>



\_\_u8

</td>
<td>



s\_journal\_uuid\[16\]

</td>
<td>



UUID of journal superblock

</td>
</tr>
<tr>
<td>



0xE0

</td>
<td>



\_\_le32

</td>
<td>



s\_journal\_inum

</td>
<td>



inode number of journal file.

</td>
</tr>
<tr>
<td>



0xE4

</td>
<td>



\_\_le32

</td>
<td>



s\_journal\_dev

</td>
<td>



Device number of journal file, if the external journal feature flag is set.

</td>
</tr>
<tr>
<td>



0xE8

</td>
<td>



\_\_le32

</td>
<td>



s\_last\_orphan

</td>
<td>



Start of list of orphaned inodes to delete.

</td>
</tr>
<tr>
<td>



0xEC

</td>
<td>



\_\_le32

</td>
<td>



s\_hash\_seed\[4\]

</td>
<td>



HTREE hash seed.

</td>
</tr>
<tr>
<td>



0xFC

</td>
<td>



\_\_u8

</td>
<td>



s\_def\_hash\_version

</td>
<td>



Default hash algorithm to use for directory hashes. See [super\_def\_hash](<#rst-super-def-hash>) for more info.

</td>
</tr>
<tr>
<td>



0xFD

</td>
<td>



\_\_u8

</td>
<td>



s\_jnl\_backup\_type

</td>
<td>



If this value is 0 or EXT3\_JNL\_BACKUP\_BLOCKS (1), then the `s_jnl_blocks` field contains a duplicate copy of the inode's `i_block[]` array and `i_size`.

</td>
</tr>
<tr>
<td>



0xFE

</td>
<td>



\_\_le16

</td>
<td>



s\_desc\_size

</td>
<td>



Size of group descriptors, in bytes, if the 64bit incompat feature flag is set.

</td>
</tr>
<tr>
<td>



0x100

</td>
<td>



\_\_le32

</td>
<td>



s\_default\_mount\_opts

</td>
<td>



Default mount options. See the [super\_mountopts](<#rst-super-mountopts>) table for more info.

</td>
</tr>
<tr>
<td>



0x104

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_meta\_bg

</td>
<td>



First metablock block group, if the meta\_bg feature is enabled.

</td>
</tr>
<tr>
<td>



0x108

</td>
<td>



\_\_le32

</td>
<td>



s\_mkfs\_time

</td>
<td>



When the filesystem was created, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x10C

</td>
<td>



\_\_le32

</td>
<td>



s\_jnl\_blocks\[17\]

</td>
<td>



Backup copy of the journal inode's `i_block[]` array in the first 15 elements and i\_size\_high and i\_size in the 16th and 17th elements, respectively.

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>





</td>
<td>



64bit support is valid only if EXT4\_FEATURE\_COMPAT\_64BIT is set.

</td>
</tr>
<tr>
<td>



0x150

</td>
<td>



\_\_le32

</td>
<td>



s\_blocks\_count\_hi

</td>
<td>



High 32-bits of the block count.

</td>
</tr>
<tr>
<td>



0x154

</td>
<td>



\_\_le32

</td>
<td>



s\_r\_blocks\_count\_hi

</td>
<td>



High 32-bits of the reserved block count.

</td>
</tr>
<tr>
<td>



0x158

</td>
<td>



\_\_le32

</td>
<td>



s\_free\_blocks\_count\_hi

</td>
<td>



High 32-bits of the free block count.

</td>
</tr>
<tr>
<td>



0x15C

</td>
<td>



\_\_le16

</td>
<td>



s\_min\_extra\_isize

</td>
<td>



All inodes have at least \# bytes.

</td>
</tr>
<tr>
<td>



0x15E

</td>
<td>



\_\_le16

</td>
<td>



s\_want\_extra\_isize

</td>
<td>



New inodes should reserve \# bytes.

</td>
</tr>
<tr>
<td>



0x160

</td>
<td>



\_\_le32

</td>
<td>



s\_flags

</td>
<td>



Miscellaneous flags. See the [super\_flags](<#rst-super-flags>) table for more info.

</td>
</tr>
<tr>
<td>



0x164

</td>
<td>



\_\_le16

</td>
<td>



s\_raid\_stride

</td>
<td>



RAID stride. This is the number of logical blocks read from or written to the disk before moving to the next disk. This affects the placement of filesystem metadata, which will hopefully make RAID storage faster.

</td>
</tr>
<tr>
<td>



0x166

</td>
<td>



\_\_le16

</td>
<td>



s\_mmp\_interval

</td>
<td>



\#. seconds to wait in multi-mount prevention (MMP) checking. In theory, MMP is a mechanism to record in the superblock which host and device have mounted the filesystem, in order to prevent multiple mounts. This feature does not seem to be implemented...

</td>
</tr>
<tr>
<td>



0x168

</td>
<td>



\_\_le64

</td>
<td>



s\_mmp\_block

</td>
<td>



Block \# for multi-mount protection data.

</td>
</tr>
<tr>
<td>



0x170

</td>
<td>



\_\_le32

</td>
<td>



s\_raid\_stripe\_width

</td>
<td>



RAID stripe width. This is the number of logical blocks read from or written to the disk before coming back to the current disk. This is used by the block allocator to try to reduce the number of read-modify-write operations in a RAID5/6.

</td>
</tr>
<tr>
<td>



0x174

</td>
<td>



\_\_u8

</td>
<td>



s\_log\_groups\_per\_flex

</td>
<td>



Size of a flexible block group is 2 ^ `s_log_groups_per_flex`.

</td>
</tr>
<tr>
<td>



0x175

</td>
<td>



\_\_u8

</td>
<td>



s\_checksum\_type

</td>
<td>



Metadata checksum algorithm type. The only valid value is 1 (crc32c).

</td>
</tr>
<tr>
<td>



0x176

</td>
<td>



\_\_u8

</td>
<td>



s\_encryption\_level

</td>
<td>



Versioning level for encryption.

</td>
</tr>
<tr>
<td>



0x177

</td>
<td>



\_\_u8

</td>
<td>



s\_reserved\_pad

</td>
<td>



Padding to next 32bits.

</td>
</tr>
<tr>
<td>



0x178

</td>
<td>



\_\_le64

</td>
<td>



s\_kbytes\_written

</td>
<td>



Number of KiB written to this filesystem over its lifetime.

</td>
</tr>
<tr>
<td>



0x180

</td>
<td>



\_\_le32

</td>
<td>



s\_snapshot\_inum

</td>
<td>



inode number of active snapshot. (Not used in e2fsprogs/Linux.)

</td>
</tr>
<tr>
<td>



0x184

</td>
<td>



\_\_le32

</td>
<td>



s\_snapshot\_id

</td>
<td>



Sequential ID of active snapshot. (Not used in e2fsprogs/Linux.)

</td>
</tr>
<tr>
<td>



0x188

</td>
<td>



\_\_le64

</td>
<td>



s\_snapshot\_r\_blocks\_count

</td>
<td>



Number of blocks reserved for active snapshot's future use. (Not used in e2fsprogs/Linux.)

</td>
</tr>
<tr>
<td>



0x190

</td>
<td>



\_\_le32

</td>
<td>



s\_snapshot\_list

</td>
<td>



inode number of the head of the on-disk snapshot list. (Not used in e2fsprogs/Linux.)

</td>
</tr>
<tr>
<td>



0x194

</td>
<td>



\_\_le32

</td>
<td>



s\_error\_count

</td>
<td>



Number of errors seen.

</td>
</tr>
<tr>
<td>



0x198

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_error\_time

</td>
<td>



First time an error happened, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x19C

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_error\_ino

</td>
<td>



inode involved in first error.

</td>
</tr>
<tr>
<td>



0x1A0

</td>
<td>



\_\_le64

</td>
<td>



s\_first\_error\_block

</td>
<td>



Number of block involved of first error.

</td>
</tr>
<tr>
<td>



0x1A8

</td>
<td>



\_\_u8

</td>
<td>



s\_first\_error\_func\[32\]

</td>
<td>



Name of function where the error happened.

</td>
</tr>
<tr>
<td>



0x1C8

</td>
<td>



\_\_le32

</td>
<td>



s\_first\_error\_line

</td>
<td>



Line number where error happened.

</td>
</tr>
<tr>
<td>



0x1CC

</td>
<td>



\_\_le32

</td>
<td>



s\_last\_error\_time

</td>
<td>



Time of most recent error, in seconds since the epoch.

</td>
</tr>
<tr>
<td>



0x1D0

</td>
<td>



\_\_le32

</td>
<td>



s\_last\_error\_ino

</td>
<td>



inode involved in most recent error.

</td>
</tr>
<tr>
<td>



0x1D4

</td>
<td>



\_\_le32

</td>
<td>



s\_last\_error\_line

</td>
<td>



Line number where most recent error happened.

</td>
</tr>
<tr>
<td>



0x1D8

</td>
<td>



\_\_le64

</td>
<td>



s\_last\_error\_block

</td>
<td>



Number of block involved in most recent error.

</td>
</tr>
<tr>
<td>



0x1E0

</td>
<td>



\_\_u8

</td>
<td>



s\_last\_error\_func\[32\]

</td>
<td>



Name of function where the most recent error happened.

</td>
</tr>
<tr>
<td>



0x200

</td>
<td>



\_\_u8

</td>
<td>



s\_mount\_opts\[64\]

</td>
<td>



ASCIIZ string of mount options.

</td>
</tr>
<tr>
<td>



0x240

</td>
<td>



\_\_le32

</td>
<td>



s\_usr\_quota\_inum

</td>
<td>



Inode number of user [quota](</kernel/internals/filesystems/quota.md>) file.

</td>
</tr>
<tr>
<td>



0x244

</td>
<td>



\_\_le32

</td>
<td>



s\_grp\_quota\_inum

</td>
<td>



Inode number of group [quota](</kernel/internals/filesystems/quota.md>) file.

</td>
</tr>
<tr>
<td>



0x248

</td>
<td>



\_\_le32

</td>
<td>



s\_overhead\_blocks

</td>
<td>



Overhead blocks/clusters in fs. (Huh? This field is always zero, which means that the kernel calculates it dynamically.)

</td>
</tr>
<tr>
<td>



0x24C

</td>
<td>



\_\_le32

</td>
<td>



s\_backup\_bgs\[2\]

</td>
<td>



Block groups containing superblock backups (if sparse\_super2)

</td>
</tr>
<tr>
<td>



0x254

</td>
<td>



\_\_u8

</td>
<td>



s\_encrypt\_algos\[4\]

</td>
<td>



Encryption algorithms in use. There can be up to four algorithms in use at any time; valid algorithm codes are given in the [super\_encrypt](<#rst-super-encrypt>) table below.

</td>
</tr>
<tr>
<td>



0x258

</td>
<td>



\_\_u8

</td>
<td>



s\_encrypt\_pw\_salt\[16\]

</td>
<td>



Salt for the string2key algorithm for encryption.

</td>
</tr>
<tr>
<td>



0x268

</td>
<td>



\_\_le32

</td>
<td>



s\_lpf\_ino

</td>
<td>



Inode number of lost+found

</td>
</tr>
<tr>
<td>



0x26C

</td>
<td>



\_\_le32

</td>
<td>



s\_prj\_quota\_inum

</td>
<td>



Inode that tracks project quotas.

</td>
</tr>
<tr>
<td>



0x270

</td>
<td>



\_\_le32

</td>
<td>



s\_checksum\_seed

</td>
<td>



Checksum seed used for metadata\_csum calculations. This value is crc32c(\~0, $orig\_fs\_uuid).

</td>
</tr>
<tr>
<td>



0x274

</td>
<td>



\_\_u8

</td>
<td>



s\_wtime\_hi

</td>
<td>



Upper 8 bits of the s\_wtime field.

</td>
</tr>
<tr>
<td>



0x275

</td>
<td>



\_\_u8

</td>
<td>



s\_mtime\_hi

</td>
<td>



Upper 8 bits of the s\_mtime field.

</td>
</tr>
<tr>
<td>



0x276

</td>
<td>



\_\_u8

</td>
<td>



s\_mkfs\_time\_hi

</td>
<td>



Upper 8 bits of the s\_mkfs\_time field.

</td>
</tr>
<tr>
<td>



0x277

</td>
<td>



\_\_u8

</td>
<td>



s\_lastcheck\_hi

</td>
<td>



Upper 8 bits of the s\_lastcheck field.

</td>
</tr>
<tr>
<td>



0x278

</td>
<td>



\_\_u8

</td>
<td>



s\_first\_error\_time\_hi

</td>
<td>



Upper 8 bits of the s\_first\_error\_time field.

</td>
</tr>
<tr>
<td>



0x279

</td>
<td>



\_\_u8

</td>
<td>



s\_last\_error\_time\_hi

</td>
<td>



Upper 8 bits of the s\_last\_error\_time field.

</td>
</tr>
<tr>
<td>



0x27A

</td>
<td>



\_\_u8

</td>
<td>



s\_first\_error\_errcode

</td>
<td>





</td>
</tr>
<tr>
<td>



0x27B

</td>
<td>



\_\_u8

</td>
<td>



s\_last\_error\_errcode

</td>
<td>





</td>
</tr>
<tr>
<td>



0x27C

</td>
<td>



\_\_le16

</td>
<td>



s\_encoding

</td>
<td>



Filename charset encoding.

</td>
</tr>
<tr>
<td>



0x27E

</td>
<td>



\_\_le16

</td>
<td>



s\_encoding\_flags

</td>
<td>



Filename charset encoding flags.

</td>
</tr>
<tr>
<td>



0x280

</td>
<td>



\_\_le32

</td>
<td>



s\_orphan\_file\_inum

</td>
<td>



Orphan file inode number.

</td>
</tr>
<tr>
<td>



0x284

</td>
<td>



\_\_le32

</td>
<td>



s\_reserved\[94\]

</td>
<td>



Padding to the end of the block.

</td>
</tr>
<tr>
<td>



0x3FC

</td>
<td>



\_\_le32

</td>
<td>



s\_checksum

</td>
<td>



Superblock checksum.

</td>
</tr>
</tbody>
</table>

<a id="rst-super-state"></a>

The superblock state is some combination of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0001

</td>
<td>



Cleanly umounted

</td>
</tr>
<tr>
<td>



0x0002

</td>
<td>



Errors detected

</td>
</tr>
<tr>
<td>



0x0004

</td>
<td>



Orphans being recovered

</td>
</tr>
</tbody>
</table>

<a id="rst-super-errors"></a>

The superblock error policy is one of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



1

</td>
<td>



Continue

</td>
</tr>
<tr>
<td>



2

</td>
<td>



Remount read-only

</td>
</tr>
<tr>
<td>



3

</td>
<td>



Panic

</td>
</tr>
</tbody>
</table>

<a id="rst-super-creator"></a>

The filesystem creator is one of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0

</td>
<td>



Linux

</td>
</tr>
<tr>
<td>



1

</td>
<td>



Hurd

</td>
</tr>
<tr>
<td>



2

</td>
<td>



Masix

</td>
</tr>
<tr>
<td>



3

</td>
<td>



FreeBSD

</td>
</tr>
<tr>
<td>



4

</td>
<td>



Lites

</td>
</tr>
</tbody>
</table>

<a id="rst-super-revision"></a>

The superblock revision is one of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0

</td>
<td>



Original format

</td>
</tr>
<tr>
<td>



1

</td>
<td>



v2 format w/ dynamic inode sizes

</td>
</tr>
</tbody>
</table>

Note that `EXT4_DYNAMIC_REV` refers to a revision 1 or newer filesystem.

<a id="rst-super-compat"></a>

The superblock compatible features field is a combination of any of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x1

</td>
<td>



Directory preallocation (COMPAT\_DIR\_PREALLOC).

</td>
</tr>
<tr>
<td>



0x2

</td>
<td>



“imagic inodes”. Not clear from the code what this does (COMPAT\_IMAGIC\_INODES).

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



Has a journal (COMPAT\_HAS\_JOURNAL).

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



Supports extended attributes (COMPAT\_EXT\_ATTR).

</td>
</tr>
<tr>
<td>



0x10

</td>
<td>



Has reserved GDT blocks for filesystem expansion (COMPAT\_RESIZE\_INODE). Requires RO\_COMPAT\_SPARSE\_SUPER.

</td>
</tr>
<tr>
<td>



0x20

</td>
<td>



Has directory indices (COMPAT\_DIR\_INDEX).

</td>
</tr>
<tr>
<td>



0x40

</td>
<td>



“Lazy BG”. Not in Linux kernel, seems to have been for uninitialized block groups? (COMPAT\_LAZY\_BG)

</td>
</tr>
<tr>
<td>



0x80

</td>
<td>



“Exclude inode”. Not used. (COMPAT\_EXCLUDE\_INODE).

</td>
</tr>
<tr>
<td>



0x100

</td>
<td>



“Exclude bitmap”. Seems to be used to indicate the presence of snapshot-related exclude bitmaps? Not defined in kernel or used in e2fsprogs (COMPAT\_EXCLUDE\_BITMAP).

</td>
</tr>
<tr>
<td>



0x200

</td>
<td>



Sparse Super Block, v2. If this flag is set, the SB field s\_backup\_bgs points to the two block groups that contain backup superblocks (COMPAT\_SPARSE\_SUPER2).

</td>
</tr>
<tr>
<td>



0x400

</td>
<td>



Fast commits supported. Although fast commits blocks are backward incompatible, fast commit blocks are not always present in the journal. If fast commit blocks are present in the journal, JBD2 incompat feature (JBD2\_FEATURE\_INCOMPAT\_FAST\_COMMIT) gets set (COMPAT\_FAST\_COMMIT).

</td>
</tr>
<tr>
<td>



0x1000

</td>
<td>



Orphan file allocated. This is the special file for more efficient tracking of unlinked but still open inodes. When there may be any entries in the file, we additionally set proper rocompat feature (RO\_COMPAT\_ORPHAN\_PRESENT).

</td>
</tr>
</tbody>
</table>

<a id="rst-super-incompat"></a>

The superblock incompatible features field is a combination of any of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x1

</td>
<td>



Compression (INCOMPAT\_COMPRESSION).

</td>
</tr>
<tr>
<td>



0x2

</td>
<td>



Directory entries record the file type. See ext4\_dir\_entry\_2 below (INCOMPAT\_FILETYPE).

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



Filesystem needs recovery (INCOMPAT\_RECOVER).

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



Filesystem has a separate journal device (INCOMPAT\_JOURNAL\_DEV).

</td>
</tr>
<tr>
<td>



0x10

</td>
<td>



Meta block groups. See the earlier discussion of this feature (INCOMPAT\_META\_BG).

</td>
</tr>
<tr>
<td>



0x40

</td>
<td>



Files in this filesystem use extents (INCOMPAT\_EXTENTS).

</td>
</tr>
<tr>
<td>



0x80

</td>
<td>



Enable a filesystem size of 2^64 blocks (INCOMPAT\_64BIT).

</td>
</tr>
<tr>
<td>



0x100

</td>
<td>



Multiple mount protection (INCOMPAT\_MMP).

</td>
</tr>
<tr>
<td>



0x200

</td>
<td>



Flexible block groups. See the earlier discussion of this feature (INCOMPAT\_FLEX\_BG).

</td>
</tr>
<tr>
<td>



0x400

</td>
<td>



Inodes can be used to store large extended attribute values (INCOMPAT\_EA\_INODE).

</td>
</tr>
<tr>
<td>



0x1000

</td>
<td>



Data in directory entry (INCOMPAT\_DIRDATA). (Not implemented?)

</td>
</tr>
<tr>
<td>



0x2000

</td>
<td>



Metadata checksum seed is stored in the superblock. This feature enables the administrator to change the UUID of a metadata\_csum filesystem while the filesystem is mounted; without it, the checksum definition requires all metadata blocks to be rewritten (INCOMPAT\_CSUM\_SEED).

</td>
</tr>
<tr>
<td>



0x4000

</td>
<td>



Large directory &gt;2GB or 3-level htree (INCOMPAT\_LARGEDIR). Prior to this feature, directories could not be larger than 4GiB and could not have an htree more than 2 levels deep. If this feature is enabled, directories can be larger than 4GiB and have a maximum htree depth of 3.

</td>
</tr>
<tr>
<td>



0x8000

</td>
<td>



Data in inode (INCOMPAT\_INLINE\_DATA).

</td>
</tr>
<tr>
<td>



0x10000

</td>
<td>



Encrypted inodes can be present. (INCOMPAT\_ENCRYPT).

</td>
</tr>
<tr>
<td>



0x20000

</td>
<td>



Directories can be marked case-insensitive. (INCOMPAT\_CASEFOLD).

</td>
</tr>
</tbody>
</table>

<a id="rst-super-rocompat"></a>

The superblock read-only compatible features field is a combination of any of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x1

</td>
<td>



Sparse superblocks. See the earlier discussion of this feature (RO\_COMPAT\_SPARSE\_SUPER).

</td>
</tr>
<tr>
<td>



0x2

</td>
<td>



This filesystem has been used to store a file greater than 2GiB (RO\_COMPAT\_LARGE\_FILE).

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



Not used in kernel or e2fsprogs (RO\_COMPAT\_BTREE\_DIR).

</td>
</tr>
<tr>
<td>



0x8

</td>
<td>



This filesystem has files whose sizes are represented in units of logical blocks, not 512-byte sectors. This implies a very large file indeed\! (RO\_COMPAT\_HUGE\_FILE)

</td>
</tr>
<tr>
<td>



0x10

</td>
<td>



Group descriptors have checksums. In addition to detecting corruption, this is useful for lazy formatting with uninitialized groups (RO\_COMPAT\_GDT\_CSUM).

</td>
</tr>
<tr>
<td>



0x20

</td>
<td>



Indicates that the old ext3 32,000 subdirectory limit no longer applies (RO\_COMPAT\_DIR\_NLINK). A directory's i\_links\_count will be set to 1 if it is incremented past 64,999.

</td>
</tr>
<tr>
<td>



0x40

</td>
<td>



Indicates that large inodes exist on this filesystem (RO\_COMPAT\_EXTRA\_ISIZE).

</td>
</tr>
<tr>
<td>



0x80

</td>
<td>



This filesystem has a snapshot (RO\_COMPAT\_HAS\_SNAPSHOT).

</td>
</tr>
<tr>
<td>



0x100

</td>
<td>



[Quota](</kernel/internals/filesystems/quota.md>) (RO\_COMPAT\_QUOTA).

</td>
</tr>
<tr>
<td>



0x200

</td>
<td>



This filesystem supports “bigalloc”, which means that file extents are tracked in units of clusters (of blocks) instead of blocks (RO\_COMPAT\_BIGALLOC).

</td>
</tr>
<tr>
<td>



0x400

</td>
<td>



This filesystem supports metadata checksumming. (RO\_COMPAT\_METADATA\_CSUM; implies RO\_COMPAT\_GDT\_CSUM, though GDT\_CSUM must not be set)

</td>
</tr>
<tr>
<td>



0x800

</td>
<td>



Filesystem supports replicas. This feature is neither in the kernel nor e2fsprogs. (RO\_COMPAT\_REPLICA)

</td>
</tr>
<tr>
<td>



0x1000

</td>
<td>



Read-only filesystem image; the kernel will not mount this image read-write and most tools will refuse to write to the image. (RO\_COMPAT\_READONLY)

</td>
</tr>
<tr>
<td>



0x2000

</td>
<td>



Filesystem tracks project quotas. (RO\_COMPAT\_PROJECT)

</td>
</tr>
<tr>
<td>



0x8000

</td>
<td>



Verity inodes may be present on the filesystem. (RO\_COMPAT\_VERITY)

</td>
</tr>
<tr>
<td>



0x10000

</td>
<td>



Indicates orphan file may have valid orphan entries and thus we need to clean them up when mounting the filesystem (RO\_COMPAT\_ORPHAN\_PRESENT).

</td>
</tr>
</tbody>
</table>

<a id="rst-super-def-hash"></a>

The `s_def_hash_version` field is one of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0

</td>
<td>



Legacy.

</td>
</tr>
<tr>
<td>



0x1

</td>
<td>



Half MD4.

</td>
</tr>
<tr>
<td>



0x2

</td>
<td>



Tea.

</td>
</tr>
<tr>
<td>



0x3

</td>
<td>



Legacy, unsigned.

</td>
</tr>
<tr>
<td>



0x4

</td>
<td>



Half MD4, unsigned.

</td>
</tr>
<tr>
<td>



0x5

</td>
<td>



Tea, unsigned.

</td>
</tr>
</tbody>
</table>

<a id="rst-super-mountopts"></a>

The `s_default_mount_opts` field is any combination of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0001

</td>
<td>



Print debugging info upon (re)mount. (EXT4\_DEFM\_DEBUG)

</td>
</tr>
<tr>
<td>



0x0002

</td>
<td>



New files take the gid of the containing directory (instead of the fsgid of the current process). (EXT4\_DEFM\_BSDGROUPS)

</td>
</tr>
<tr>
<td>



0x0004

</td>
<td>



Support userspace-provided extended attributes. (EXT4\_DEFM\_XATTR\_USER)

</td>
</tr>
<tr>
<td>



0x0008

</td>
<td>



Support POSIX access control lists (ACLs). (EXT4\_DEFM\_ACL)

</td>
</tr>
<tr>
<td>



0x0010

</td>
<td>



Do not support 32-bit UIDs. (EXT4\_DEFM\_UID16)

</td>
</tr>
<tr>
<td>



0x0020

</td>
<td>



All data and metadata are committed to the journal. (EXT4\_DEFM\_JMODE\_DATA)

</td>
</tr>
<tr>
<td>



0x0040

</td>
<td>



All data are flushed to the disk before metadata are committed to the journal. (EXT4\_DEFM\_JMODE\_ORDERED)

</td>
</tr>
<tr>
<td>



0x0060

</td>
<td>



Data ordering is not preserved; data may be written after the metadata has been written. (EXT4\_DEFM\_JMODE\_WBACK)

</td>
</tr>
<tr>
<td>



0x0100

</td>
<td>



Disable write flushes. (EXT4\_DEFM\_NOBARRIER)

</td>
</tr>
<tr>
<td>



0x0200

</td>
<td>



Track which blocks in a filesystem are metadata and therefore should not be used as data blocks. This option will be enabled by default on 3.18, hopefully. (EXT4\_DEFM\_BLOCK\_VALIDITY)

</td>
</tr>
<tr>
<td>



0x0400

</td>
<td>



Enable DISCARD support, where the storage device is told about blocks becoming unused. (EXT4\_DEFM\_DISCARD)

</td>
</tr>
<tr>
<td>



0x0800

</td>
<td>



Disable delayed allocation. (EXT4\_DEFM\_NODELALLOC)

</td>
</tr>
</tbody>
</table>

<a id="rst-super-flags"></a>

The `s_flags` field is any combination of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0x0001

</td>
<td>



Signed directory hash in use.

</td>
</tr>
<tr>
<td>



0x0002

</td>
<td>



Unsigned directory hash in use.

</td>
</tr>
<tr>
<td>



0x0004

</td>
<td>



To test development code.

</td>
</tr>
</tbody>
</table>

<a id="rst-super-encrypt"></a>

The `s_encrypt_algos` list can contain any of the following:


<table>
<thead>
<tr>
<th>



Value

</th>
<th>



Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



0

</td>
<td>



Invalid algorithm (ENCRYPTION\_MODE\_INVALID).

</td>
</tr>
<tr>
<td>



1

</td>
<td>



256-bit AES in XTS mode (ENCRYPTION\_MODE\_AES\_256\_XTS).

</td>
</tr>
<tr>
<td>



2

</td>
<td>



256-bit AES in GCM mode (ENCRYPTION\_MODE\_AES\_256\_GCM).

</td>
</tr>
<tr>
<td>



3

</td>
<td>



256-bit AES in CBC mode (ENCRYPTION\_MODE\_AES\_256\_CBC).

</td>
</tr>
</tbody>
</table>

Total size of the superblock is 1024 bytes.

---

# Verity files

_Peios Kernel / Internals / Filesystems / ext4_

> ext4 supports fs-verity, which is a filesystem feature that provides Merkle tree based hashing for individual readonly files. Most of fs-verity is common to all filesystems that support it; see Documentation/filesystems/fsverity.rst…

<a id="rst-verity-files"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

ext4 supports fs-verity, which is a filesystem feature that provides Merkle tree based hashing for individual readonly files.  Most of fs-verity is common to all filesystems that support it; see [Documentation/filesystems/fsverity.rst](</kernel/internals/filesystems/fsverity.md#rst-fsverity>) for the fs-verity documentation.  However, the on-disk layout of the verity metadata is filesystem-specific.  On ext4, the verity metadata is stored after the end of the file data itself, in the following format:

- Zero-padding to the next 65536-byte boundary.  This padding need not actually be allocated on-disk, i.e. it may be a hole.

- The Merkle tree, as documented in [Documentation/filesystems/fsverity.rst](</kernel/internals/filesystems/fsverity.md#rst-fsverity-merkle-tree>), with the tree levels stored in order from root to leaf, and the tree blocks within each level stored in their natural order.

- Zero-padding to the next filesystem block boundary.

- The verity descriptor, as documented in [Documentation/filesystems/fsverity.rst](</kernel/internals/filesystems/fsverity.md#rst-fsverity-descriptor>), with optionally appended signature blob.

- Zero-padding to the next offset that is 4 bytes before a filesystem block boundary.

- The size of the verity descriptor in bytes, as a 4-byte little endian integer.

Verity inodes have EXT4_VERITY_FL set, and they must use extents, i.e. EXT4_EXTENTS_FL must be set and EXT4_INLINE_DATA_FL must be clear. They can have EXT4_ENCRYPT_FL set, in which case the verity metadata is encrypted as well as the data itself.

Verity files cannot have blocks allocated past the end of the verity metadata.

Verity and DAX are not compatible and attempts to set both of these flags on a file will fail.

---

# FUSE (Filesystem in Userspace) Technical Documentation

_Peios Kernel / Internals / Filesystems / fuse_

> Reference for FUSE (Filesystem in Userspace) Technical Documentation.

<a id="rst-fuse-filesystem-in-userspace-technical-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1. [FUSE Overview](</kernel/internals/filesystems/fuse/fuse.md>)
2. [FUSE I/O Modes](</kernel/internals/filesystems/fuse/fuse-io.md>)
3. [FUSE-over-io-uring design documentation](</kernel/internals/filesystems/fuse/fuse-io-uring.md>)
4. [FUSE Passthrough](</kernel/internals/filesystems/fuse/fuse-passthrough.md>)

---

# FUSE-over-io-uring design documentation

_Peios Kernel / Internals / Filesystems / fuse_

> This documentation covers basic details how the fuse kernel/userspace communication through io-uring is configured and works. For generic details about FUSE see fuse.rst.

<a id="rst-fuse-over-io-uring-design-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This documentation covers basic details how the fuse kernel/userspace communication through io-uring is configured and works. For generic details about FUSE see [fuse.rst](/kernel/internals/filesystems/fuse/fuse.md).

This document also covers the current interface, which is still in development and might change.

<a id="rst-limitations"></a>

## Limitations

As of now not all requests types are supported through io-uring, userspace is required to also handle requests through /dev/fuse after io-uring setup is complete. Specifically notifications (initiated from the daemon side) and interrupts.

<a id="rst-fuse-io-uring-configuration"></a>

## Fuse io-uring configuration

Fuse kernel requests are queued through the classical /dev/fuse read/write interface - until io-uring setup is complete.

In order to set up fuse-over-io-uring fuse-server (user-space) needs to submit SQEs (opcode = IORING_OP_URING_CMD) to the /dev/fuse connection file descriptor. Initial submit is with the sub command FUSE_URING_REQ_REGISTER, which will just register entries to be available in the kernel.

Once at least one entry per queue is submitted, kernel starts to enqueue to ring queues. Note, every CPU core has its own fuse-io-uring queue. Userspace handles the CQE/fuse-request and submits the result as subcommand FUSE_URING_REQ_COMMIT_AND_FETCH - kernel completes the requests and also marks the entry available again. If there are pending requests waiting the request will be immediately submitted to the daemon again.

Initial SQE -----------:



```text
|                                    |  FUSE filesystem daemon
|                                    |
|                                    |  >io_uring_submit()
|                                    |   IORING_OP_URING_CMD /
|                                    |   FUSE_URING_CMD_REGISTER
|                                    |  [wait cqe]
|                                    |   >io_uring_wait_cqe() or
|                                    |   >io_uring_submit_and_wait()
|                                    |
|  >fuse_uring_cmd()                 |
|   >fuse_uring_register()           |
```

Sending requests with CQEs --------------------------:



```text
|                                           |  FUSE filesystem daemon
|                                           |  [waiting for CQEs]
|  "rm /mnt/fuse/file"                      |
|                                           |
|  >sys_unlink()                            |
|    >fuse_unlink()                         |
|      [allocate request]                   |
|      >fuse_send_one()                     |
|        ...                                |
|       >fuse_uring_queue_fuse_req          |
|        [queue request on fg queue]        |
|         >fuse_uring_add_req_to_ring_ent() |
|         ...                               |
|          >fuse_uring_copy_to_ring()       |
|          >io_uring_cmd_done()             |
|       >request_wait_answer()              |
|         [sleep on req->waitq]             |
|                                           |  [receives and handles CQE]
|                                           |  [submit result and fetch next]
|                                           |  >io_uring_submit()
|                                           |   IORING_OP_URING_CMD/
|                                           |   FUSE_URING_CMD_COMMIT_AND_FETCH
|  >fuse_uring_cmd()                        |
|   >fuse_uring_commit_fetch()              |
|    >fuse_uring_commit()                   |
|     >fuse_uring_copy_from_ring()          |
|      [ copy the result to the fuse req]   |
|     >fuse_uring_req_end()                 |
|      >fuse_request_end()                  |
|       [wake up req->waitq]                |
|    >fuse_uring_next_fuse_req              |
|       [wait or handle next req]           |
|                                           |
|       [req->waitq woken up]               |
|    <fuse_unlink()                         |
|  <sys_unlink()                            |
```

---

# FUSE I/O Modes

_Peios Kernel / Internals / Filesystems / fuse_

> Fuse supports the following I/O modes:

<a id="rst-fuse-i-o-modes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Fuse supports the following I/O modes:

- direct-io

- cached + write-through + writeback-cache

The direct-io mode can be selected with the FOPEN_DIRECT_IO flag in the FUSE_OPEN reply.

In direct-io mode the page cache is completely bypassed for reads and writes. No read-ahead takes place. Shared mmap is disabled by default. To allow shared mmap, the FUSE_DIRECT_IO_ALLOW_MMAP flag may be enabled in the FUSE_INIT reply.

In cached mode reads may be satisfied from the page cache, and data may be read-ahead by the kernel to fill the cache.  The cache is always kept consistent after any writes to the file.  All mmap modes are supported.

The cached mode has two sub modes controlling how writes are handled.  The write-through mode is the default and is supported on all kernels.  The writeback-cache mode may be selected by the FUSE_WRITEBACK_CACHE flag in the FUSE_INIT reply.

In write-through mode each write is immediately sent to userspace as one or more WRITE requests, as well as updating any cached pages (and caching previously uncached, but fully written pages).  No READ requests are ever sent for writes, so when an uncached page is partially written, the page is discarded.

In writeback-cache mode (enabled by the FUSE_WRITEBACK_CACHE flag) writes go to the cache only, which means that the write(2) syscall can often complete very fast.  Dirty pages are written back implicitly (background writeback or page reclaim on memory pressure) or explicitly (invoked by close(2), fsync(2) and when the last ref to the file is being released on munmap(2)).  This mode assumes that all changes to the filesystem go through the FUSE kernel module (size and atime/ctime/mtime attributes are kept up-to-date by the kernel), so it's generally not suitable for network filesystems.  If a partial page is written, then the page needs to be first read from userspace.  This means, that even for files opened for O_WRONLY it is possible that READ requests will be generated by the kernel.

---

# FUSE Passthrough

_Peios Kernel / Internals / Filesystems / fuse_

> FUSE (Filesystem in Userspace) passthrough is a feature designed to improve the performance of FUSE filesystems for I/O operations. Typically, FUSE operations involve communication between the kernel and a userspace FUSE daemon, which can…

> **Peios:** `CAP_SYS_ADMIN` here maps to `SeTcbPrivilege`. Passing this gate does not remove KACS checks on backing files, device handles or mounts. FUSE is outside the unprivileged mount-type allowlist. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-fuse-passthrough"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

FUSE (Filesystem in Userspace) passthrough is a feature designed to improve the performance of FUSE filesystems for I/O operations. Typically, FUSE operations involve communication between the kernel and a userspace FUSE daemon, which can incur overhead. Passthrough allows certain operations on a FUSE file to bypass the userspace daemon and be executed directly by the kernel on an underlying "backing file".

This is achieved by the FUSE daemon registering a file descriptor (pointing to the backing file on a lower filesystem) with the FUSE kernel module. The kernel then receives an identifier (`backing_id`) for this registered backing file. When a FUSE file is subsequently opened, the FUSE daemon can, in its response to the `OPEN` request, include this `backing_id` and set the `FOPEN_PASSTHROUGH` flag. This establishes a direct link for specific operations.

Currently, passthrough is supported for operations like `read(2)`/`write(2)` (via `read_iter`/`write_iter`), `splice(2)`, and `mmap(2)`.

<a id="rst-enabling-passthrough"></a>

## Enabling Passthrough

To use FUSE passthrough:

> 1. The FUSE filesystem must be compiled with `CONFIG_FUSE_PASSTHROUGH` enabled.
>
> 2. The FUSE daemon, during the `FUSE_INIT` handshake, must negotiate the `FUSE_PASSTHROUGH` capability and specify its desired `max_stack_depth`.
>
> 3. The (privileged) FUSE daemon uses the `FUSE_DEV_IOC_BACKING_OPEN` ioctl on its connection file descriptor (e.g., `/dev/fuse`) to register a backing file descriptor and obtain a `backing_id`.
>
> 4. When handling an `OPEN` or `CREATE` request for a FUSE file, the daemon replies with the `FOPEN_PASSTHROUGH` flag set in `fuse_open_out::open_flags` and provides the corresponding `backing_id` in `fuse_open_out::backing_id`.
>
> 5. The FUSE daemon should eventually call `FUSE_DEV_IOC_BACKING_CLOSE` with the `backing_id` to release the kernel's reference to the backing file when it's no longer needed for passthrough setups.

<a id="rst-privilege-requirements"></a>

## Privilege Requirements

Setting up passthrough functionality currently requires the FUSE daemon to possess the `CAP_SYS_ADMIN` capability. This requirement stems from several security and resource management considerations that are actively being discussed and worked on. The primary reasons for this restriction are detailed below.

<a id="rst-resource-accounting-and-visibility"></a>

### Resource Accounting and Visibility

The core mechanism for passthrough involves the FUSE daemon opening a file descriptor to a backing file and registering it with the FUSE kernel module via the `FUSE_DEV_IOC_BACKING_OPEN` ioctl. This ioctl returns a `backing_id` associated with a kernel-internal `struct fuse_backing` object, which holds a reference to the backing `struct file`.

A significant concern arises because the FUSE daemon can close its own file descriptor to the backing file after registration. The kernel, however, will still hold a reference to the `struct file` via the `struct fuse_backing` object as long as it's associated with a `backing_id` (or subsequently, with an open FUSE file in passthrough mode).

This behavior leads to two main issues for unprivileged FUSE daemons:

> 1. **Invisibility to lsof and other inspection tools**: Once the FUSE daemon closes its file descriptor, the open backing file held by the kernel becomes "hidden." Standard tools like `lsof`, which typically inspect process file descriptor tables, would not be able to identify that this file is still open by the system on behalf of the FUSE filesystem. This makes it difficult for system administrators to track resource usage or debug issues related to open files (e.g., preventing unmounts).
>
> 2. **Bypassing RLIMIT_NOFILE**: The FUSE daemon process is subject to resource limits, including the maximum number of open file descriptors (`RLIMIT_NOFILE`). If an unprivileged daemon could register backing files and then close its own FDs, it could potentially cause the kernel to hold an unlimited number of open `struct file` references without these being accounted against the daemon's `RLIMIT_NOFILE`. This could lead to a denial-of-service (DoS) by exhausting system-wide file resources.

The `CAP_SYS_ADMIN` requirement acts as a safeguard against these issues, restricting this powerful capability to trusted processes.

**NOTE**: `io_uring` solves this similar issue by exposing its "fixed files", which are visible via `fdinfo` and accounted under the registering user's `RLIMIT_NOFILE`.

<a id="rst-filesystem-stacking-and-shutdown-loops"></a>

### Filesystem Stacking and Shutdown Loops

Another concern relates to the potential for creating complex and problematic filesystem stacking scenarios if unprivileged users could set up passthrough. A FUSE passthrough filesystem might use a backing file that resides:

> - On the *same* FUSE filesystem.
>
> - On another filesystem (like OverlayFS) which itself might have an upper or lower layer that is a FUSE filesystem.

These configurations could create dependency loops, particularly during filesystem shutdown or unmount sequences, leading to deadlocks or system instability. This is conceptually similar to the risks associated with the `LOOP_SET_FD` ioctl, which also requires `CAP_SYS_ADMIN`.

To mitigate this, FUSE passthrough already incorporates checks based on filesystem stacking depth (`sb->s_stack_depth` and `fc->max_stack_depth`). For example, during the `FUSE_INIT` handshake, the FUSE daemon can negotiate the `max_stack_depth` it supports. When a backing file is registered via `FUSE_DEV_IOC_BACKING_OPEN`, the kernel checks if the backing file's filesystem stack depth is within the allowed limit.

The `CAP_SYS_ADMIN` requirement provides an additional layer of security, ensuring that only privileged users can create these potentially complex stacking arrangements.

<a id="rst-general-security-posture"></a>

### General Security Posture

As a general principle for new kernel features that allow userspace to instruct the kernel to perform direct operations on its behalf based on user-provided file descriptors, starting with a higher privilege requirement (like `CAP_SYS_ADMIN`) is a conservative and common security practice. This allows the feature to be used and tested while further security implications are evaluated and addressed.

---

# FUSE Overview

_Peios Kernel / Internals / Filesystems / fuse_

> A filesystem in which data and metadata are provided by an ordinary userspace process. The filesystem can be accessed normally through the kernel interface.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-fuse-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-definitions"></a>

## Definitions

- **Userspace filesystem:**

  A filesystem in which data and metadata are provided by an ordinary userspace process.  The filesystem can be accessed normally through the kernel interface.

- **Filesystem daemon:**

  The process(es) providing the data and metadata of the filesystem.

- **Non-privileged mount (or user mount):**

  A userspace filesystem mounted by a non-privileged (non-root) user. The filesystem daemon is running with the privileges of the mounting user.  NOTE: this is not the same as mounts allowed with the "user" option in /etc/fstab, which is not discussed here.

- **Filesystem connection:**

  A connection between the filesystem daemon and the kernel.  The connection exists until either the daemon dies, or the filesystem is umounted.  Note that detaching (or lazy umounting) the filesystem does *not* break the connection, in this case it will exist until the last reference to the filesystem is released.

- **Mount owner:**

  The user who does the mounting.

- **User:**

  The user who is performing filesystem operations.

<a id="rst-what-is-fuse"></a>

## What is FUSE?

FUSE is a userspace filesystem framework.  It consists of a kernel module (fuse.ko), a userspace library (libfuse.\*) and a mount utility (fusermount).

One of the most important features of FUSE is allowing secure, non-privileged mounts.  This opens up new possibilities for the use of filesystems.  A good example is sshfs: a secure network filesystem using the sftp protocol.

The userspace library and utilities are available from the [FUSE homepage:](<https://github.com/libfuse/>)<a id="rst-fuse-homepage"></a>

<a id="rst-filesystem-type"></a>

## Filesystem type

The filesystem type given to mount(2) can be one of the following:

> - **fuse**
>
>   This is the usual way to mount a FUSE filesystem.  The first argument of the mount system call may contain an arbitrary string, which is not interpreted by the kernel.
>
> - **fuseblk**
>
>   The filesystem is block device based.  The first argument of the mount system call is interpreted as the name of the device.

<a id="rst-mount-options"></a>

## Mount options

- **fd=N**

  The file descriptor to use for communication between the userspace filesystem and the kernel.  The file descriptor must have been obtained by opening the FUSE device ('/dev/fuse').

- **rootmode=M**

  The file mode of the filesystem's root in octal representation.

- **user_id=N**

  The numeric user id of the mount owner.

- **group_id=N**

  The numeric group id of the mount owner.

- **default_permissions**

  By default FUSE doesn't check file access permissions, the filesystem is free to implement its access policy or leave it to the underlying file access mechanism (e.g. in case of network filesystems).  This option enables permission checking, restricting access based on file mode.  It is usually useful together with the 'allow_other' mount option.

- **allow_other**

  This option overrides the security measure restricting file access to the user mounting the filesystem.  This option is by default only allowed to root, but this restriction can be removed with a (userspace) configuration option.

- **max_read=N**

  With this option the maximum size of read operations can be set. The default is infinite.  Note that the size of read requests is limited anyway to 32 pages (which is 128kbyte on i386).

- **blksize=N**

  Set the block size for the filesystem.  The default is 512.  This option is only valid for 'fuseblk' type mounts.

<a id="rst-control-filesystem"></a>

## Control filesystem

There's a control filesystem for FUSE, which can be mounted by:



```text
mount -t fusectl none /sys/fs/fuse/connections
```

Mounting it under the '/sys/fs/fuse/connections' directory makes it backwards compatible with earlier versions.

Under the fuse control filesystem each connection has a directory named by a unique number.

For each connection the following files exist within this directory:

> - **waiting**
>
>   The number of requests which are waiting to be transferred to userspace or being processed by the filesystem daemon.  If there is no filesystem activity and 'waiting' is non-zero, then the filesystem is hung or deadlocked.
>
> - **abort**
>
>   Writing anything into this file will abort the filesystem connection.  This means that all waiting requests will be aborted an error returned for all aborted and new requests.
>
> - **max_background**
>
>   The maximum number of background requests that can be outstanding at a time. When the number of background requests reaches this limit, further requests will be blocked until some are completed, potentially causing I/O operations to stall.
>
> - **congestion_threshold**
>
>   The threshold of background requests at which the kernel considers the filesystem to be congested. When the number of background requests exceeds this value, the kernel will skip asynchronous readahead operations, reducing read-ahead optimizations but preserving essential I/O, as well as suspending non-synchronous writeback operations (WB_SYNC_NONE), delaying page cache flushing to the filesystem.

Only the owner of the mount may read or write these files.

<a id="rst-interrupting-filesystem-operations"></a>

### Interrupting filesystem operations

If a process issuing a FUSE filesystem request is interrupted, the following will happen:

> - If the request is not yet sent to userspace AND the signal is fatal (SIGKILL or unhandled fatal signal), then the request is dequeued and returns immediately.
>
> - If the request is not yet sent to userspace AND the signal is not fatal, then an interrupted flag is set for the request.  When the request has been successfully transferred to userspace and this flag is set, an INTERRUPT request is queued.
>
> - If the request is already sent to userspace, then an INTERRUPT request is queued.

INTERRUPT requests take precedence over other requests, so the userspace filesystem will receive queued INTERRUPTs before any others.

The userspace filesystem may ignore the INTERRUPT requests entirely, or may honor them by sending a reply to the *original* request, with the error set to EINTR.

It is also possible that there's a race between processing the original request and its INTERRUPT request.  There are two possibilities:

> 1. The INTERRUPT request is processed before the original request is processed
>
> 2. The INTERRUPT request is processed after the original request has been answered

If the filesystem cannot find the original request, it should wait for some timeout and/or a number of new requests to arrive, after which it should reply to the INTERRUPT request with an EAGAIN error.  In case 1) the INTERRUPT request will be requeued.  In case 2) the INTERRUPT reply will be ignored.

<a id="rst-aborting-a-filesystem-connection"></a>

## Aborting a filesystem connection

It is possible to get into certain situations where the filesystem is not responding.  Reasons for this may be:

> - **a)** Broken userspace filesystem implementation
>
> - **b)** Network connection down
>
> - **c)** Accidental deadlock
>
> - **d)** Malicious deadlock

(For more on c) and d) see later sections)

In either of these cases it may be useful to abort the connection to the filesystem.  There are several ways to do this:

> - Kill the filesystem daemon.  Works in case of a) and b)
>
> - Kill the filesystem daemon and all users of the filesystem.  Works in all cases except some malicious deadlocks
>
> - Use forced umount (umount -f).  Works in all cases but only if filesystem is still attached (it hasn't been lazy unmounted)
>
> - Abort filesystem through the FUSE control filesystem.  Most powerful method, always works.

<a id="rst-how-do-non-privileged-mounts-work"></a>

## How do non-privileged mounts work?

The upstream Linux workflow uses a set-user-ID `fusermount` helper. Peios does not gain native mount authority through that bit. FUSE is outside the descriptor-only mount-type allowlist, so a Peios mounting service needs the native mount privilege path (`SeManageVolumePrivilege` or `SeTcbPrivilege`) as well as device and filesystem access. The discussion below describes the inherited FUSE safety model, not a Peios set-user-ID deployment procedure.

The implication of providing non-privileged mounts is that the mount owner must not be able to use this capability to compromise the system.  Obvious requirements arising from this are:

> - **A)** mount owner should not be able to get elevated privileges with the help of the mounted filesystem
>
> - **B)** mount owner should not get illegitimate access to information from other users' and the super user's processes
>
> - **C)** mount owner should not be able to induce undesired behavior in other users' or the super user's processes

<a id="rst-how-are-requirements-fulfilled"></a>

## How are requirements fulfilled?

> - **A)** The mount owner could gain elevated privileges by either:
>
>   1. creating a filesystem containing a device file, then opening this device
>
>   2. creating a filesystem containing a suid or sgid application, then executing this application
>
>   The solution is not to allow opening device files and ignore setuid and setgid bits when executing programs.  To ensure this fusermount always adds "nosuid" and "nodev" to the mount options for non-privileged mounts.
>
> - **B)** If another user is accessing files or directories in the filesystem, the filesystem daemon serving requests can record the exact sequence and timing of operations performed.  This information is otherwise inaccessible to the mount owner, so this counts as an information leak.
>
>   The solution to this problem will be presented in point 2) of C).
>
> - **C)** There are several ways in which the mount owner can induce undesired behavior in other users' processes, such as:
>
>   > 1. mounting a filesystem over a file or directory which the mount owner could otherwise not be able to modify (or could only make limited modifications).
>   >
>   >    This is solved in fusermount, by checking the access permissions on the mountpoint and only allowing the mount if the mount owner can do unlimited modification (has write access to the mountpoint, and mountpoint is not a "sticky" directory)
>   >
>   > 2. Even if 1) is solved the mount owner can change the behavior of other users' processes.
>   >
>   >    > - **i)** It can slow down or indefinitely delay the execution of a filesystem operation creating a DoS against the user or the whole system.  For example a suid application locking a system file, and then accessing a file on the mount owner's filesystem could be stopped, and thus causing the system file to be locked forever.
>   >    >
>   >    > - **ii)** It can present files or directories of unlimited length, or directory structures of unlimited depth, possibly causing a system process to eat up diskspace, memory or other resources, again causing *DoS*.
>   >
>   >    The solution to this as well as B) is not to allow processes to access the filesystem, which could otherwise not be monitored or manipulated by the mount owner.  Since if the mount owner can ptrace a process, it can do all of the above without using a FUSE mount, the same criteria as used in ptrace can be used to check if a process is allowed to access the filesystem or not.
>   >
>   >    Note that the *ptrace* check is not strictly necessary to prevent C/2/i, it is enough to check if mount owner has enough privilege to send signal to the process accessing the filesystem, since *SIGSTOP* can be used to get a similar effect.

<a id="rst-i-think-these-limitations-are-unacceptable"></a>

## I think these limitations are unacceptable?

If a sysadmin trusts the users enough, or can ensure through other measures, that system processes will never enter non-privileged mounts, it can relax the last limitation in several ways:

> - With the 'user_allow_other' config option. If this config option is set, the mounting user can add the 'allow_other' mount option which disables the check for other users' processes.
>
>   User namespaces have an unintuitive interaction with 'allow_other': an unprivileged user - normally restricted from mounting with 'allow_other' - could do so in a user namespace where they're privileged. If any process could access such an 'allow_other' mount this would give the mounting user the ability to manipulate processes in user namespaces where they're unprivileged. For this reason 'allow_other' restricts access to users in the same userns or a descendant.
>
> - With the 'allow_sys_admin_access' module option. If this option is set, super user's processes have unrestricted access to mounts irrespective of allow_other setting or user namespace of the mounting user.

Note that both of these relaxations expose the system to potential information leak or *DoS* as described in points B and C/2/i-ii in the preceding section.

<a id="rst-kernel-userspace-interface"></a>

## Kernel - userspace interface

The following diagram shows how a filesystem operation (in this example unlink) is performed in FUSE.



```text
|  "rm /mnt/fuse/file"               |  FUSE filesystem daemon
|                                    |
|                                    |  >sys_read()
|                                    |    >fuse_dev_read()
|                                    |      >request_wait()
|                                    |        [sleep on fc->waitq]
|                                    |
|  >sys_unlink()                     |
|    >fuse_unlink()                  |
|      [get request from             |
|       fc->unused_list]             |
|      >request_send()               |
|        [queue req on fc->pending]  |
|        [wake up fc->waitq]         |        [woken up]
|        >request_wait_answer()      |
|          [sleep on req->waitq]     |
|                                    |      <request_wait()
|                                    |      [remove req from fc->pending]
|                                    |      [copy req to read buffer]
|                                    |      [add req to fc->processing]
|                                    |    <fuse_dev_read()
|                                    |  <sys_read()
|                                    |
|                                    |  [perform unlink]
|                                    |
|                                    |  >sys_write()
|                                    |    >fuse_dev_write()
|                                    |      [look up req in fc->processing]
|                                    |      [remove from fc->processing]
|                                    |      [copy write buffer to req]
|          [woken up]                |      [wake up req->waitq]
|                                    |    <fuse_dev_write()
|                                    |  <sys_write()
|        <request_wait_answer()      |
|      <request_send()               |
|      [add request to               |
|       fc->unused_list]             |
|    <fuse_unlink()                  |
|  <sys_unlink()                     |
```

> [!NOTE]
>
> Everything in the description above is greatly simplified

There are a couple of ways in which to deadlock a FUSE filesystem. Since we are talking about unprivileged userspace programs, something must be done about these.

**Scenario 1 -  Simple deadlock**:



```text
|  "rm /mnt/fuse/file"               |  FUSE filesystem daemon
|                                    |
|  >sys_unlink("/mnt/fuse/file")     |
|    [acquire inode semaphore        |
|     for "file"]                    |
|    >fuse_unlink()                  |
|      [sleep on req->waitq]         |
|                                    |  <sys_read()
|                                    |  >sys_unlink("/mnt/fuse/file")
|                                    |    [acquire inode semaphore
|                                    |     for "file"]
|                                    |    *DEADLOCK*
```

The solution for this is to allow the filesystem to be aborted.

**Scenario 2 - Tricky deadlock**

This one needs a carefully crafted filesystem.  It's a variation on the above, only the call back to the filesystem is not explicit, but is caused by a pagefault.



```text
|  Kamikaze filesystem thread 1      |  Kamikaze filesystem thread 2
|                                    |
|  [fd = open("/mnt/fuse/file")]     |  [request served normally]
|  [mmap fd to 'addr']               |
|  [close fd]                        |  [FLUSH triggers 'magic' flag]
|  [read a byte from addr]           |
|    >do_page_fault()                |
|      [find or create page]         |
|      [lock page]                   |
|      >fuse_readpage()              |
|         [queue READ request]       |
|         [sleep on req->waitq]      |
|                                    |  [read request to buffer]
|                                    |  [create reply header before addr]
|                                    |  >sys_write(addr - headerlength)
|                                    |    >fuse_dev_write()
|                                    |      [look up req in fc->processing]
|                                    |      [remove from fc->processing]
|                                    |      [copy write buffer to req]
|                                    |        >do_page_fault()
|                                    |           [find or create page]
|                                    |           [lock page]
|                                    |           * DEADLOCK *
```

The solution is basically the same as above.

An additional problem is that while the write buffer is being copied to the request, the request must not be interrupted/aborted.  This is because the destination address of the copy may not be valid after the request has returned.

This is solved with doing the copy atomically, and allowing abort while the page(s) belonging to the write buffer are faulted with get_user_pages().  The 'req-&gt;locked' flag indicates when the copy is taking place, and abort is delayed until this flag is unset.

---

# Global File System 2

_Peios Kernel / Internals / Filesystems / gfs2_

> GFS2 is a cluster file system. It allows a cluster of computers to simultaneously use a block device that is shared between them (with FC, iSCSI, NBD, etc). GFS2 reads and writes to the block device like a local file system, but also uses…

<a id="rst-global-file-system-2"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

GFS2 is a cluster file system. It allows a cluster of computers to simultaneously use a block device that is shared between them (with FC, iSCSI, NBD, etc).  GFS2 reads and writes to the block device like a local file system, but also uses a lock module to allow the computers coordinate their I/O so file system consistency is maintained.  One of the nifty features of GFS2 is perfect consistency -- changes made to the file system on one machine show up immediately on all other machines in the cluster.

GFS2 uses interchangeable inter-node locking mechanisms, the currently supported mechanisms are:

> - **lock_nolock**
>
>   - allows GFS2 to be used as a local file system
>
> - **lock_dlm**
>
>   - uses the distributed lock manager (dlm) for inter-node locking. The dlm is found at linux/fs/dlm/

lock_dlm depends on user space cluster management systems found at the URL above.

To use GFS2 as a local file system, no external clustering systems are needed, simply:



```text
$ mkfs -t gfs2 -p lock_nolock -j 1 /dev/block_device
$ mount -t gfs2 /dev/block_device /dir
```

The gfs2-utils package is required on all cluster nodes and, for lock_dlm, you will also need the dlm and corosync user space utilities configured as per the documentation.

gfs2-utils can be found at [https://pagure.io/gfs2-utils](<https://pagure.io/gfs2-utils>)

GFS2 is not on-disk compatible with previous versions of GFS, but it is pretty close.

The following man pages are available from gfs2-utils:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> fsck.gfs2
>
> </td>
> <td>
>
>
> to repair a filesystem
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gfs2_grow
>
> </td>
> <td>
>
>
> to expand a filesystem online
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gfs2_jadd
>
> </td>
> <td>
>
>
> to add journals to a filesystem online
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> tunegfs2
>
> </td>
> <td>
>
>
> to manipulate, examine and tune a filesystem
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> gfs2_convert
>
> </td>
> <td>
>
>
> to convert a gfs filesystem to GFS2 in-place
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mkfs.gfs2
>
> </td>
> <td>
>
>
> to make a filesystem
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-implementation-notes"></a>

## Implementation Notes

- [Glock internal locking rules](</kernel/internals/filesystems/gfs2/glocks.md>)
- [uevents and GFS2](</kernel/internals/filesystems/gfs2/uevents.md>)

---

# Glock internal locking rules

_Peios Kernel / Internals / Filesystems / gfs2_

> This documents the basic principles of the glock state machine internals. Each glock (struct gfs2_glock in fs/gfs2/incore.h) has two main (internal) locks:

<a id="rst-glock-internal-locking-rules"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This documents the basic principles of the glock state machine internals. Each glock (struct gfs2_glock in fs/gfs2/incore.h) has two main (internal) locks:

> 1. A spinlock (gl_lockref.lock) which protects the internal state such as gl_state, gl_target and the list of holders (gl_holders)
>
> 2. A non-blocking bit lock, GLF_LOCK, which is used to prevent other threads from making calls to the DLM, etc. at the same time. If a thread takes this lock, it must then call run_queue (usually via the workqueue) when it releases it in order to ensure any pending tasks are completed.

The gl_holders list contains all the queued lock requests (not just the holders) associated with the glock. If there are any held locks, then they will be contiguous entries at the head of the list. Locks are granted in strictly the order that they are queued.

There are three lock states that users of the glock layer can request, namely shared (SH), deferred (DF) and exclusive (EX). Those translate to the following DLM lock modes:


<table>
<thead>
<tr>
<th>


Glock mode

</th>
<th>


DLM

</th>
<th>


lock mode

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


UN

</td>
<td>


IV/NL

</td>
<td>


Unlocked (no DLM lock associated with glock) or NL

</td>
</tr>
<tr>
<td>


SH

</td>
<td>


PR

</td>
<td>


(Protected read)

</td>
</tr>
<tr>
<td>


DF

</td>
<td>


CW

</td>
<td>


(Concurrent write)

</td>
</tr>
<tr>
<td>


EX

</td>
<td>


EX

</td>
<td>


(Exclusive)

</td>
</tr>
</tbody>
</table>

Thus DF is basically a shared mode which is incompatible with the "normal" shared lock mode, SH. In GFS2 the DF mode is used exclusively for direct I/O operations. The glocks are basically a lock plus some routines which deal with cache management. The following rules apply for the cache:


<table>
<thead>
<tr>
<th>


Glock mode

</th>
<th>


Cache Metadata

</th>
<th>


Cache data

</th>
<th>


Dirty Data

</th>
<th>


Dirty Metadata

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


UN

</td>
<td>


No

</td>
<td>


No

</td>
<td>


No

</td>
<td>


No

</td>
</tr>
<tr>
<td>


DF

</td>
<td>


Yes

</td>
<td>


No

</td>
<td>


No

</td>
<td>


No

</td>
</tr>
<tr>
<td>


SH

</td>
<td>


Yes

</td>
<td>


Yes

</td>
<td>


No

</td>
<td>


No

</td>
</tr>
<tr>
<td>


EX

</td>
<td>


Yes

</td>
<td>


Yes

</td>
<td>


Yes

</td>
<td>


Yes

</td>
</tr>
</tbody>
</table>

These rules are implemented using the various glock operations which are defined for each type of glock. Not all types of glocks use all the modes. Only inode glocks use the DF mode for example.

Table of glock operations and per type constants:


<table>
<thead>
<tr>
<th>


Field

</th>
<th>


Purpose

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


go_sync

</td>
<td>


Called before remote state change (e.g. to sync dirty data)

</td>
</tr>
<tr>
<td>


go_xmote_bh

</td>
<td>


Called after remote state change (e.g. to refill cache)

</td>
</tr>
<tr>
<td>


go_inval

</td>
<td>


Called if remote state change requires invalidating the cache

</td>
</tr>
<tr>
<td>


go_instantiate

</td>
<td>


Called when a glock has been acquired

</td>
</tr>
<tr>
<td>


go_held

</td>
<td>


Called every time a glock holder is acquired

</td>
</tr>
<tr>
<td>


go_dump

</td>
<td>


Called to print content of object for debugfs file, or on error to dump glock to the log.

</td>
</tr>
<tr>
<td>


go_callback

</td>
<td>


Called if the DLM sends a callback to drop this lock

</td>
</tr>
<tr>
<td>


go_unlocked

</td>
<td>


Called when a glock is unlocked (dlm_unlock())

</td>
</tr>
<tr>
<td>


go_type

</td>
<td>


The type of the glock, `LM_TYPE_*`

</td>
</tr>
<tr>
<td>


go_flags

</td>
<td>


GLOF_ASPACE is set, if the glock has an address space associated with it

</td>
</tr>
</tbody>
</table>

The minimum hold time for each lock is the time after a remote lock grant for which we ignore remote demote requests. This is in order to prevent a situation where locks are being bounced around the cluster from node to node with none of the nodes making any progress. This tends to show up most with shared mmapped files which are being written to by multiple nodes. By delaying the demotion in response to a remote callback, that gives the userspace program time to make some progress before the pages are unmapped.

Eventually, we hope to make the glock "EX" mode locally shared such that any local locking will be done with the i_mutex as required rather than via the glock.

Locking rules for glock operations:


<table>
<thead>
<tr>
<th>


Operation

</th>
<th>


GLF_LOCK bit lock held

</th>
<th>


gl_lockref.lock spinlock held

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


go_sync

</td>
<td>


Yes

</td>
<td>


No

</td>
</tr>
<tr>
<td>


go_xmote_bh

</td>
<td>


Yes

</td>
<td>


No

</td>
</tr>
<tr>
<td>


go_inval

</td>
<td>


Yes

</td>
<td>


No

</td>
</tr>
<tr>
<td>


go_instantiate

</td>
<td>


No

</td>
<td>


No

</td>
</tr>
<tr>
<td>


go_held

</td>
<td>


No

</td>
<td>


No

</td>
</tr>
<tr>
<td>


go_dump

</td>
<td>


Sometimes

</td>
<td>


Yes

</td>
</tr>
<tr>
<td>


go_callback

</td>
<td>


Sometimes (N/A)

</td>
<td>


Yes

</td>
</tr>
<tr>
<td>


go_unlocked

</td>
<td>


Yes

</td>
<td>


No

</td>
</tr>
</tbody>
</table>

> [!NOTE]
>
> Operations must not drop either the bit lock or the spinlock if its held on entry. go_dump and do_demote_ok must never block. Note that go_dump will only be called if the glock's state indicates that it is caching up-to-date data.

Glock locking order within GFS2:

> 1. i_rwsem (if required)
>
> 2. Rename glock (for rename only)
>
> 3. Inode glock(s) (Parents before children, inodes at "same level" with same parent in lock number order)
>
> 4. Rgrp glock(s) (for (de)allocation operations)
>
> 5. Transaction glock (via gfs2_trans_begin) for non-read operations
>
> 6. i_rw_mutex (if required)
>
> 7. Page lock  (always last, very important\!)

There are two glocks per inode. One deals with access to the inode itself (locking order as above), and the other, known as the iopen glock is used in conjunction with the i_nlink field in the inode to determine the lifetime of the inode in question. Locking of inodes is on a per-inode basis. Locking of rgrps is on a per rgrp basis. In general we prefer to lock local locks prior to cluster locks.

<a id="rst-glock-statistics"></a>

## Glock Statistics

The stats are divided into two sets: those relating to the super block and those relating to an individual glock. The super block stats are done on a per cpu basis in order to try and reduce the overhead of gathering them. They are also further divided by glock type. All timings are in nanoseconds.

In the case of both the super block and glock statistics, the same information is gathered in each case. The super block timing statistics are used to provide default values for the glock timing statistics, so that newly created glocks should have, as far as possible, a sensible starting point. The per-glock counters are initialised to zero when the glock is created. The per-glock statistics are lost when the glock is ejected from memory.

The statistics are divided into three pairs of mean and variance, plus two counters. The mean/variance pairs are smoothed exponential estimates and the algorithm used is one which will be very familiar to those used to calculation of round trip times in network code. See "TCP/IP Illustrated, Volume 1", W. Richard Stevens, sect 21.3, "Round-Trip Time Measurement", p. 299 and onwards. Also, Volume 2, Sect. 25.10, p. 838 and onwards. Unlike the TCP/IP Illustrated case, the mean and variance are not scaled, but are in units of integer nanoseconds.

The three pairs of mean/variance measure the following things:

> 1. DLM lock time (non-blocking requests)
>
> 2. DLM lock time (blocking requests)
>
> 3. Inter-request time (again to the DLM)

A non-blocking request is one which will complete right away, whatever the state of the DLM lock in question. That currently means any requests when (a) the current state of the lock is exclusive, i.e. a lock demotion (b) the requested state is either null or unlocked (again, a demotion) or (c) the "try lock" flag is set. A blocking request covers all the other lock requests.

There are two counters. The first is there primarily to show how many lock requests have been made, and thus how much data has gone into the mean/variance calculations. The other counter is counting queuing of holders at the top layer of the glock code. Hopefully that number will be a lot larger than the number of dlm lock requests issued.

So why gather these statistics? There are several reasons we'd like to get a better idea of these timings:

1. To be able to better set the glock "min hold time"

2. To spot performance issues more easily

3. To improve the algorithm for selecting resource groups for allocation (to base it on lock wait time, rather than blindly using a "try lock")

Due to the smoothing action of the updates, a step change in some input quantity being sampled will only fully be taken into account after 8 samples (or 4 for the variance) and this needs to be carefully considered when interpreting the results.

Knowing both the time it takes a lock request to complete and the average time between lock requests for a glock means we can compute the total percentage of the time for which the node is able to use a glock vs. time that the rest of the cluster has its share. That will be very useful when setting the lock min hold time.

Great care has been taken to ensure that we measure exactly the quantities that we want, as accurately as possible. There are always inaccuracies in any measuring system, but I hope this is as accurate as we can reasonably make it.

Per sb stats can be found here:



```text
/sys/kernel/debug/gfs2/<fsname>/sbstats
```

Per glock stats can be found here:



```text
/sys/kernel/debug/gfs2/<fsname>/glstats
```

Assuming that debugfs is mounted on /sys/kernel/debug and also that &lt;fsname&gt; is replaced with the name of the gfs2 filesystem in question.

The abbreviations used in the output as are follows:


<table>
<tbody>
<tr>
<td>


srtt

</td>
<td>


Smoothed round trip time for non blocking dlm requests

</td>
</tr>
<tr>
<td>


srttvar

</td>
<td>


Variance estimate for srtt

</td>
</tr>
<tr>
<td>


srttb

</td>
<td>


Smoothed round trip time for (potentially) blocking dlm requests

</td>
</tr>
<tr>
<td>


srttvarb

</td>
<td>


Variance estimate for srttb

</td>
</tr>
<tr>
<td>


sirt

</td>
<td>


Smoothed inter request time (for dlm requests)

</td>
</tr>
<tr>
<td>


sirtvar

</td>
<td>


Variance estimate for sirt

</td>
</tr>
<tr>
<td>


dlm

</td>
<td>


Number of dlm requests made (dcnt in glstats file)

</td>
</tr>
<tr>
<td>


queue

</td>
<td>


Number of glock requests queued (qcnt in glstats file)

</td>
</tr>
</tbody>
</table>

The sbstats file contains a set of these stats for each glock type (so 8 lines for each type) and for each cpu (one column per cpu). The glstats file contains a set of these stats for each glock in a similar format to the glocks file, but using the format mean/variance for each of the timing stats.

The gfs2_glock_lock_time tracepoint prints out the current values of the stats for the glock in question, along with some addition information on each dlm reply that is received:


<table>
<tbody>
<tr>
<td>


status

</td>
<td>


The status of the dlm request

</td>
</tr>
<tr>
<td>


flags

</td>
<td>


The dlm request flags

</td>
</tr>
<tr>
<td>


tdiff

</td>
<td>


The time taken by this specific request

</td>
</tr>
</tbody>
</table>

(remaining fields as per above list)

---

# uevents and GFS2

_Peios Kernel / Internals / Filesystems / gfs2_

> During the lifetime of a GFS2 mount, a number of uevents are generated. This document explains what the events are and what they are used for (by gfs_controld in gfs2-utils).

<a id="rst-uevents-and-gfs2"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

During the lifetime of a GFS2 mount, a number of uevents are generated. This document explains what the events are and what they are used for (by gfs_controld in gfs2-utils).

<a id="rst-a-list-of-gfs2-uevents"></a>

## A list of GFS2 uevents

<a id="rst-add"></a>

### 1. ADD

The ADD event occurs at mount time. It will always be the first uevent generated by the newly created filesystem. If the mount is successful, an ONLINE uevent will follow.  If it is not successful then a REMOVE uevent will follow.

The ADD uevent has two environment variables: SPECTATOR=\[0\|1\] and RDONLY=\[0\|1\] that specify the spectator status (a read-only mount with no journal assigned), and read-only (with journal assigned) status of the filesystem respectively.

<a id="rst-online"></a>

### 2. ONLINE

The ONLINE uevent is generated after a successful mount or remount. It has the same environment variables as the ADD uevent. The ONLINE uevent, along with the two environment variables for spectator and RDONLY are a relatively recent addition (2.6.32-rc+) and will not be generated by older kernels.

<a id="rst-change"></a>

### 3. CHANGE

The CHANGE uevent is used in two places. One is when reporting the successful mount of the filesystem by the first node (FIRSTMOUNT=Done). This is used as a signal by gfs_controld that it is then ok for other nodes in the cluster to mount the filesystem.

The other CHANGE uevent is used to inform of the completion of journal recovery for one of the filesystems journals. It has two environment variables, JID= which specifies the journal id which has just been recovered, and RECOVERY=\[Done\|Failed\] to indicate the success (or otherwise) of the operation. These uevents are generated for every journal recovered, whether it is during the initial mount process or as the result of gfs_controld requesting a specific journal recovery via the /sys/fs/gfs2/&lt;fsname&gt;/lock_module/recovery file.

Because the CHANGE uevent was used (in early versions of gfs_controld) without checking the environment variables to discover the state, we cannot add any more functions to it without running the risk of someone using an older version of the user tools and breaking their cluster. For this reason the ONLINE uevent was used when adding a new uevent for a successful mount or remount.

<a id="rst-offline"></a>

### 4. OFFLINE

The OFFLINE uevent is only generated due to filesystem errors and is used as part of the "withdraw" mechanism. Currently this doesn't give any information about what the error is, which is something that needs to be fixed.

<a id="rst-remove"></a>

### 5. REMOVE

The REMOVE uevent is generated at the end of an unsuccessful mount or at the end of a umount of the filesystem. All REMOVE uevents will have been preceded by at least an ADD uevent for the same filesystem, and unlike the other uevents is generated automatically by the kernel's kobject subsystem.

<a id="rst-information-common-to-all-gfs2-uevents-uevent-environment-variables"></a>

## Information common to all GFS2 uevents (uevent environment variables)

<a id="rst-locktable"></a>

### 1. LOCKTABLE=

The LOCKTABLE is a string, as supplied on the mount command line (locktable=) or via fstab. It is used as a filesystem label as well as providing the information for a lock_dlm mount to be able to join the cluster.

<a id="rst-lockproto"></a>

### 2. LOCKPROTO=

The LOCKPROTO is a string, and its value depends on what is set on the mount command line, or via fstab. It will be either lock_nolock or lock_dlm. In the future other lock managers may be supported.

<a id="rst-journalid"></a>

### 3. JOURNALID=

If a journal is in use by the filesystem (journals are not assigned for spectator mounts) then this will give the numeric journal id in all GFS2 uevents.

<a id="rst-uuid"></a>

### 4. UUID=

With recent versions of gfs2-utils, mkfs.gfs2 writes a UUID into the filesystem superblock. If it exists, this will be included in every uevent relating to the filesystem.

---

# VFS iomap Documentation

_Peios Kernel / Internals / Filesystems / iomap_

> Reference for VFS iomap Documentation.

<a id="rst-vfs-iomap-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1. [Library Design](</kernel/internals/filesystems/iomap/design.md>)
2. [Supported File Operations](</kernel/internals/filesystems/iomap/operations.md>)
3. [Porting Your Filesystem](</kernel/internals/filesystems/iomap/porting.md>)

---

# Library Design

_Peios Kernel / Internals / Filesystems / iomap_

> Introduction

<a id="rst-library-design"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-iomap-design"></a>



<!-- Dumb style notes to maintain the author's sanity:
Please try to start sentences on separate lines so that
sentence changes don't bleed colors in diff.
Heading decorations are documented in sphinx.rst. -->

<a id="rst-table-of-contents"></a>



<a id="rst-introduction"></a>

## Introduction

iomap is a filesystem library for handling common file operations. The library has two layers:

> 1. A lower layer that provides an iterator over ranges of file offsets. This layer tries to obtain mappings of each file ranges to storage from the filesystem, but the storage information is not necessarily required.
>
> 2. An upper layer that acts upon the space mappings provided by the lower layer iterator.

The iteration can involve mappings of file's logical offset ranges to physical extents, but the storage layer information is not necessarily required, e.g. for walking cached file information. The library exports various APIs for implementing file operations such as:

> - Pagecache reads and writes
>
> - Folio write faults to the pagecache
>
> - Writeback of dirty folios
>
> - Direct I/O reads and writes
>
> - fsdax I/O reads, writes, loads, and stores
>
> - FIEMAP
>
> - lseek `SEEK_DATA` and `SEEK_HOLE`
>
> - swapfile activation

This origins of this library is the file I/O path that XFS once used; it has now been extended to cover several other operations.

<a id="rst-who-should-read-this"></a>

## Who Should Read This?

The target audience for this document are filesystem, storage, and pagecache programmers and code reviewers.

If you are working on PCI, machine architectures, or device drivers, you are most likely in the wrong place.

<a id="rst-how-is-this-better"></a>

## How Is This Better?

Unlike the classic Linux I/O model which breaks file I/O into small units (generally memory pages or blocks) and looks up space mappings on the basis of that unit, the iomap model asks the filesystem for the largest space mappings that it can create for a given file operation and initiates operations on that basis. This strategy improves the filesystem's visibility into the size of the operation being performed, which enables it to combat fragmentation with larger space allocations when possible. Larger space mappings improve runtime performance by amortizing the cost of mapping function calls into the filesystem across a larger amount of data.

At a high level, an iomap operation [looks like this](<https://lore.kernel.org/all/ZGbVaewzcCysclPt@dread.disaster.area/>)<a id="rst-looks-like-this"></a>:

1. For each byte in the operation range...

   1. Obtain a space mapping via `->iomap_begin`

   2. For each sub-unit of work...

      1. Revalidate the mapping and go back to (1) above, if necessary. So far only the pagecache operations need to do this.

      2. Do the work

   3. Increment operation cursor

   4. Release the mapping via `->iomap_end`, if necessary

Each iomap operation will be covered in more detail below. This library was covered previously by an [LWN article](<https://lwn.net/Articles/935934/>)<a id="rst-lwn-article"></a> and a [KernelNewbies page](<https://kernelnewbies.org/KernelProjects/iomap>)<a id="rst-kernelnewbies-page"></a>.

The goal of this document is to provide a brief discussion of the design and capabilities of iomap, followed by a more detailed catalog of the interfaces presented by iomap. If you change iomap, please update this design document.

<a id="rst-file-range-iterator"></a>

## File Range Iterator

<a id="rst-definitions"></a>

### Definitions

> - **buffer head**: Shattered remnants of the old buffer cache.
>
> - `fsblock`: The block size of a file, also known as `i_blocksize`.
>
> - `i_rwsem`: The VFS `struct inode` rwsemaphore. Processes hold this in shared mode to read file state and contents. Some filesystems may allow shared mode for writes. Processes often hold this in exclusive mode to change file state and contents.
>
> - `invalidate_lock`: The pagecache `struct address_space` rwsemaphore that protects against folio insertion and removal for filesystems that support punching out folios below EOF. Processes wishing to insert folios must hold this lock in shared mode to prevent removal, though concurrent insertion is allowed. Processes wishing to remove folios must hold this lock in exclusive mode to prevent insertions. Concurrent removals are not allowed.
>
> - `dax_read_lock`: The RCU read lock that dax takes to prevent a device pre-shutdown hook from returning before other threads have released resources.
>
> - **filesystem mapping lock**: This synchronization primitive is internal to the filesystem and must protect the file mapping data from updates while a mapping is being sampled. The filesystem author must determine how this coordination should happen; it does not need to be an actual lock.
>
> - **iomap internal operation lock**: This is a general term for synchronization primitives that iomap functions take while holding a mapping. A specific example would be taking the folio lock while reading or writing the pagecache.
>
> - **pure overwrite**: A write operation that does not require any metadata or zeroing operations to perform during either submission or completion. This implies that the filesystem must have already allocated space on disk as `IOMAP_MAPPED` and the filesystem must not place any constraints on IO alignment or size. The only constraints on I/O alignment are device level (minimum I/O size and alignment, typically sector size).

<a id="rst-struct-iomap"></a>

### `struct iomap`

The filesystem communicates to the iomap iterator the mapping of byte ranges of a file to byte ranges of a storage device with the structure below:



```c
struct iomap {
    u64                 addr;
    loff_t              offset;
    u64                 length;
    u16                 type;
    u16                 flags;
    struct block_device *bdev;
    struct dax_device   *dax_dev;
    void                *inline_data;
    void                *private;
    u64                 validity_cookie;
};
```

The fields are as follows:

> - `offset` and `length` describe the range of file offsets, in bytes, covered by this mapping. These fields must always be set by the filesystem.
>
> - `type` describes the type of the space mapping:
>
>   - **IOMAP_HOLE**: No storage has been allocated. This type must never be returned in response to an `IOMAP_WRITE` operation because writes must allocate and map space, and return the mapping. The `addr` field must be set to `IOMAP_NULL_ADDR`. iomap does not support writing (whether via pagecache or direct I/O) to a hole.
>
>   - **IOMAP_DELALLOC**: A promise to allocate space at a later time ("delayed allocation"). If the filesystem returns IOMAP_F_NEW here and the write fails, the `->iomap_end` function must delete the reservation. The `addr` field must be set to `IOMAP_NULL_ADDR`.
>
>   - **IOMAP_MAPPED**: The file range maps to specific space on the storage device. The device is returned in `bdev` or `dax_dev`. The device address, in bytes, is returned via `addr`.
>
>   - **IOMAP_UNWRITTEN**: The file range maps to specific space on the storage device, but the space has not yet been initialized. The device is returned in `bdev` or `dax_dev`. The device address, in bytes, is returned via `addr`. Reads from this type of mapping will return zeroes to the caller. For a write or writeback operation, the ioend should update the mapping to MAPPED. Refer to the sections about ioends for more details.
>
>   - **IOMAP_INLINE**: The file range maps to the memory buffer specified by `inline_data`. For write operation, the `->iomap_end` function presumably handles persisting the data. The `addr` field must be set to `IOMAP_NULL_ADDR`.
>
> - `flags` describe the status of the space mapping. These flags should be set by the filesystem in `->iomap_begin`:
>
>   - **IOMAP_F_NEW**: The space under the mapping is newly allocated. Areas that will not be written to must be zeroed. If a write fails and the mapping is a space reservation, the reservation must be deleted.
>
>   - **IOMAP_F_DIRTY**: The inode will have uncommitted metadata needed to access any data written. fdatasync is required to commit these changes to persistent storage. This needs to take into account metadata changes that *may* be made at I/O completion, such as file size updates from direct I/O.
>
>   - **IOMAP_F_SHARED**: The space under the mapping is shared. Copy on write is necessary to avoid corrupting other file data.
>
>   - **IOMAP_F_BUFFER_HEAD**: This mapping requires the use of buffer heads for pagecache operations. Do not add more uses of this.
>
>   - **IOMAP_F_MERGED**: Multiple contiguous block mappings were coalesced into this single mapping. This is only useful for FIEMAP.
>
>   - **IOMAP_F_XATTR**: The mapping is for extended attribute data, not regular file data. This is only useful for FIEMAP.
>
>   - **IOMAP_F_BOUNDARY**: This indicates I/O and its completion must not be merged with any other I/O or completion. Filesystems must use this when submitting I/O to devices that cannot handle I/O crossing certain LBAs (e.g. ZNS devices). This flag applies only to buffered I/O writeback; all other functions ignore it.
>
>   - **IOMAP_F_PRIVATE**: This flag is reserved for filesystem private use.
>
>   - **IOMAP_F_ANON_WRITE**: Indicates that (write) I/O does not have a target block assigned to it yet and the file system will do that in the bio submission handler, splitting the I/O as needed.
>
>   - **IOMAP_F_ATOMIC_BIO**: This indicates write I/O must be submitted with the `REQ_ATOMIC` flag set in the bio. Filesystems need to set this flag to inform iomap that the write I/O operation requires torn-write protection based on HW-offload mechanism. They must also ensure that mapping updates upon the completion of the I/O must be performed in a single metadata update.
>
>   These flags can be set by iomap itself during file operations. The filesystem should supply an `->iomap_end` function if it needs to observe these flags:
>
>   - **IOMAP_F_SIZE_CHANGED**: The file size has changed as a result of using this mapping.
>
>   - **IOMAP_F_STALE**: The mapping was found to be stale. iomap will call `->iomap_end` on this mapping and then `->iomap_begin` to obtain a new mapping.
>
>   Currently, these flags are only set by pagecache operations.
>
> - `addr` describes the device address, in bytes.
>
> - `bdev` describes the block device for this mapping. This only needs to be set for mapped or unwritten operations.
>
> - `dax_dev` describes the DAX device for this mapping. This only needs to be set for mapped or unwritten operations, and only for a fsdax operation.
>
> - `inline_data` points to a memory buffer for I/O involving `IOMAP_INLINE` mappings. This value is ignored for all other mapping types.
>
> - `private` is a pointer to [filesystem-private information](<https://lore.kernel.org/all/20180619164137.13720-7-hch@lst.de/>)<a id="rst-filesystem-private-information"></a>. This value will be passed unchanged to `->iomap_end`.
>
> - `validity_cookie` is a magic freshness value set by the filesystem that should be used to detect stale mappings. For pagecache operations this is critical for correct operation because page faults can occur, which implies that filesystem locks should not be held between `->iomap_begin` and `->iomap_end`. Filesystems with completely static mappings need not set this value. Only pagecache operations revalidate mappings; see the section about `iomap_valid` for details.

<a id="rst-struct-iomap-ops"></a>

### `struct iomap_ops`

Every iomap function requires the filesystem to pass an operations structure to obtain a mapping and (optionally) to release the mapping:



```c
struct iomap_ops {
    int (*iomap_begin)(struct inode *inode, loff_t pos, loff_t length,
                       unsigned flags, struct iomap *iomap,
                       struct iomap *srcmap);

    int (*iomap_end)(struct inode *inode, loff_t pos, loff_t length,
                     ssize_t written, unsigned flags,
                     struct iomap *iomap);
};
```

<a id="rst-iomap-begin"></a>

#### `->iomap_begin`

iomap operations call `->iomap_begin` to obtain one file mapping for the range of bytes specified by `pos` and `length` for the file `inode`. This mapping should be returned through the `iomap` pointer. The mapping must cover at least the first byte of the supplied file range, but it does not need to cover the entire requested range.

Each iomap operation describes the requested operation through the `flags` argument. The exact value of `flags` will be documented in the operation-specific sections below. These flags can, at least in principle, apply generally to iomap operations:

> - `IOMAP_DIRECT` is set when the caller wishes to issue file I/O to block storage.
>
> - `IOMAP_DAX` is set when the caller wishes to issue file I/O to memory-like storage.
>
> - `IOMAP_NOWAIT` is set when the caller wishes to perform a best effort attempt to avoid any operation that would result in blocking the submitting task. This is similar in intent to `O_NONBLOCK` for network APIs - it is intended for asynchronous applications to keep doing other work instead of waiting for the specific unavailable filesystem resource to become available. Filesystems implementing `IOMAP_NOWAIT` semantics need to use trylock algorithms. They need to be able to satisfy the entire I/O request range with a single iomap mapping. They need to avoid reading or writing metadata synchronously. They need to avoid blocking memory allocations. They need to avoid waiting on transaction reservations to allow modifications to take place. They probably should not be allocating new space. And so on. If there is any doubt in the filesystem developer's mind as to whether any specific `IOMAP_NOWAIT` operation may end up blocking, then they should return `-EAGAIN` as early as possible rather than start the operation and force the submitting task to block. `IOMAP_NOWAIT` is often set on behalf of `IOCB_NOWAIT` or `RWF_NOWAIT`.
>
> - `IOMAP_DONTCACHE` is set when the caller wishes to perform a buffered file I/O and would like the kernel to drop the pagecache after the I/O completes, if it isn't already being used by another thread.

If it is necessary to read existing file contents from a [different](<https://lore.kernel.org/all/20191008071527.29304-9-hch@lst.de/>)<a id="rst-different"></a> device or address range on a device, the filesystem should return that information via `srcmap`. Only pagecache and fsdax operations support reading from one mapping and writing to another.

<a id="rst-iomap-end"></a>

#### `->iomap_end`

After the operation completes, the `->iomap_end` function, if present, is called to signal that iomap is finished with a mapping. Typically, implementations will use this function to tear down any context that were set up in `->iomap_begin`. For example, a write might wish to commit the reservations for the bytes that were operated upon and unreserve any space that was not operated upon. `written` might be zero if no bytes were touched. `flags` will contain the same value passed to `->iomap_begin`. iomap ops for reads are not likely to need to supply this function.

Both functions should return a negative errno code on error, or zero on success.

<a id="rst-preparing-for-file-operations"></a>

## Preparing for File Operations

iomap only handles mapping and I/O. Filesystems must still call out to the VFS to check input parameters and file state before initiating an I/O operation. It does not handle obtaining filesystem freeze protection, updating of timestamps, stripping privileges, or access control.

<a id="rst-locking-hierarchy"></a>

## Locking Hierarchy

iomap requires that filesystems supply their own locking model. There are three categories of synchronization primitives, as far as iomap is concerned:

> - The **upper** level primitive is provided by the filesystem to coordinate access to different iomap operations. The exact primitive is specific to the filesystem and operation, but is often a VFS inode, pagecache invalidation, or folio lock. For example, a filesystem might take `i_rwsem` before calling `iomap_file_buffered_write` and `iomap_file_unshare` to prevent these two file operations from clobbering each other. Pagecache writeback may lock a folio to prevent other threads from accessing the folio until writeback is underway.
>
>   - The **lower** level primitive is taken by the filesystem in the `->iomap_begin` and `->iomap_end` functions to coordinate access to the file space mapping information. The fields of the iomap object should be filled out while holding this primitive. The upper level synchronization primitive, if any, remains held while acquiring the lower level synchronization primitive. For example, XFS takes `ILOCK_EXCL` and ext4 takes `i_data_sem` while sampling mappings. Filesystems with immutable mapping information may not require synchronization here.
>
>   - The **operation** primitive is taken by an iomap operation to coordinate access to its own internal data structures. The upper level synchronization primitive, if any, remains held while acquiring this primitive. The lower level primitive is not held while acquiring this primitive. For example, pagecache write operations will obtain a file mapping, then grab and lock a folio to copy new contents. It may also lock an internal folio state object to update metadata.

The exact locking requirements are specific to the filesystem; for certain operations, some of these locks can be elided. All further mentions of locking are *recommendations*, not mandates. Each filesystem author must figure out the locking for themself.

<a id="rst-bugs-and-limitations"></a>

## Bugs and Limitations

> - No support for fscrypt.
>
> - No support for compression.
>
> - No support for fsverity yet.
>
> - Strong assumptions that IO should work the way it does on XFS.
>
> - Does iomap *actually* work for non-regular file data?

Patches welcome\!

---

# Supported File Operations

_Peios Kernel / Internals / Filesystems / iomap_

> Buffered I/O

<a id="rst-supported-file-operations"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-iomap-operations"></a>



<!-- Dumb style notes to maintain the author's sanity:
Please try to start sentences on separate lines so that
sentence changes don't bleed colors in diff.
Heading decorations are documented in sphinx.rst. -->

<a id="rst-table-of-contents"></a>



Below are a discussion of the high level file operations that iomap implements.

<a id="rst-buffered-i-o"></a>

## Buffered I/O

Buffered I/O is the default file I/O path in Linux. File contents are cached in memory ("pagecache") to satisfy reads and writes. Dirty cache will be written back to disk at some point that can be forced via `fsync` and variants.

iomap implements nearly all the folio and pagecache management that filesystems have to implement themselves under the legacy I/O model. This means that the filesystem need not know the details of allocating, mapping, managing uptodate and dirty state, or writeback of pagecache folios. Under the legacy I/O model, this was managed very inefficiently with linked lists of buffer heads instead of the per-folio bitmaps that iomap uses. Unless the filesystem explicitly opts in to buffer heads, they will not be used, which makes buffered I/O much more efficient, and the pagecache maintainer much happier.

<a id="rst-struct-address-space-operations"></a>

### `struct address_space_operations`

The following iomap functions can be referenced directly from the address space operations structure:

> - `iomap_dirty_folio`
>
> - `iomap_release_folio`
>
> - `iomap_invalidate_folio`
>
> - `iomap_is_partially_uptodate`

The following address space operations can be wrapped easily:

> - `read_folio`
>
> - `readahead`
>
> - `writepages`
>
> - `bmap`
>
> - `swap_activate`

<a id="rst-struct-iomap-write-ops"></a>

### `struct iomap_write_ops`



```c
struct iomap_write_ops {
    struct folio *(*get_folio)(struct iomap_iter *iter, loff_t pos,
                               unsigned len);
    void (*put_folio)(struct inode *inode, loff_t pos, unsigned copied,
                      struct folio *folio);
    bool (*iomap_valid)(struct inode *inode, const struct iomap *iomap);
    int (*read_folio_range)(const struct iomap_iter *iter,
                       struct folio *folio, loff_t pos, size_t len);
};
```

iomap calls these functions:

> - `get_folio`: Called to allocate and return an active reference to a locked folio prior to starting a write. If this function is not provided, iomap will call `iomap_get_folio`. This could be used to [set up per-folio filesystem state](<https://lore.kernel.org/all/20190429220934.10415-5-agruenba@redhat.com/>)<a id="rst-set-up-per-folio-filesystem-state"></a> for a write.
>
> - `put_folio`: Called to unlock and put a folio after a pagecache operation completes. If this function is not provided, iomap will `folio_unlock` and `folio_put` on its own. This could be used to [commit per-folio filesystem state](<https://lore.kernel.org/all/20180619164137.13720-6-hch@lst.de/>)<a id="rst-commit-per-folio-filesystem-state"></a> that was set up by `->get_folio`.
>
> - `iomap_valid`: The filesystem may not hold locks between `->iomap_begin` and `->iomap_end` because pagecache operations can take folio locks, fault on userspace pages, initiate writeback for memory reclamation, or engage in other time-consuming actions. If a file's space mapping data are mutable, it is possible that the mapping for a particular pagecache folio can [change in the time it takes](<https://lore.kernel.org/all/20221123055812.747923-8-david@fromorbit.com/>)<a id="rst-change-in-the-time-it-takes"></a> to allocate, install, and lock that folio.
>
>   For the pagecache, races can happen if writeback doesn't take `i_rwsem` or `invalidate_lock` and updates mapping information. Races can also happen if the filesystem allows concurrent writes. For such files, the mapping *must* be revalidated after the folio lock has been taken so that iomap can manage the folio correctly.
>
>   fsdax does not need this revalidation because there's no writeback and no support for unwritten extents.
>
>   Filesystems subject to this kind of race must provide a `->iomap_valid` function to decide if the mapping is still valid. If the mapping is not valid, the mapping will be sampled again.
>
>   To support making the validity decision, the filesystem's `->iomap_begin` function may set `struct iomap::validity_cookie` at the same time that it populates the other iomap fields. A simple validation cookie implementation is a sequence counter. If the filesystem bumps the sequence counter every time it modifies the inode's extent map, it can be placed in the `struct iomap::validity_cookie` during `->iomap_begin`. If the value in the cookie is found to be different to the value the filesystem holds when the mapping is passed back to `->iomap_valid`, then the iomap should considered stale and the validation failed.
>
> - `read_folio_range`: Called to synchronously read in the range that will be written to. If this function is not provided, iomap will default to submitting a bio read request.

These `struct kiocb` flags are significant for buffered I/O with iomap:

> - `IOCB_NOWAIT`: Turns on `IOMAP_NOWAIT`.
>
> - `IOCB_DONTCACHE`: Turns on `IOMAP_DONTCACHE`.

<a id="rst-struct-iomap-read-ops"></a>

### `struct iomap_read_ops`



```c
struct iomap_read_ops {
    int (*read_folio_range)(const struct iomap_iter *iter,
                            struct iomap_read_folio_ctx *ctx, size_t len);
    void (*submit_read)(struct iomap_read_folio_ctx *ctx);
};
```

iomap calls these functions:

> - `read_folio_range`: Called to read in the range. This must be provided by the caller. If this succeeds, iomap_finish_folio_read() must be called after the range is read in, regardless of whether the read succeeded or failed.
>
> - `submit_read`: Submit any pending read requests. This function is optional.

<a id="rst-internal-per-folio-state"></a>

### Internal per-Folio State

If the fsblock size matches the size of a pagecache folio, it is assumed that all disk I/O operations will operate on the entire folio. The uptodate (memory contents are at least as new as what's on disk) and dirty (memory contents are newer than what's on disk) status of the folio are all that's needed for this case.

If the fsblock size is less than the size of a pagecache folio, iomap tracks the per-fsblock uptodate and dirty state itself. This enables iomap to handle both "bs &lt; ps" [filesystems](<https://lore.kernel.org/all/20230725122932.144426-1-ritesh.list@gmail.com/>)<a id="rst-filesystems"></a> and large folios in the pagecache.

iomap internally tracks two state bits per fsblock:

> - `uptodate`: iomap will try to keep folios fully up to date. If there are read(ahead) errors, those fsblocks will not be marked uptodate. The folio itself will be marked uptodate when all fsblocks within the folio are uptodate.
>
> - `dirty`: iomap will set the per-block dirty state when programs write to the file. The folio itself will be marked dirty when any fsblock within the folio is dirty.

iomap also tracks the amount of read and write disk IOs that are in flight. This structure is much lighter weight than `struct buffer_head` because there is only one per folio, and the per-fsblock overhead is two bits vs. 104 bytes.

Filesystems wishing to turn on large folios in the pagecache should call `mapping_set_large_folios` when initializing the incore inode.

<a id="rst-buffered-readahead-and-reads"></a>

### Buffered Readahead and Reads

The `iomap_readahead` function initiates readahead to the pagecache. The `iomap_read_folio` function reads one folio's worth of data into the pagecache. The `flags` argument to `->iomap_begin` will be set to zero. The pagecache takes whatever locks it needs before calling the filesystem.

Both `iomap_readahead` and `iomap_read_folio` pass in a `struct iomap_read_folio_ctx`:



```c
struct iomap_read_folio_ctx {
   const struct iomap_read_ops *ops;
   struct folio *cur_folio;
   struct readahead_control *rac;
   void *read_ctx;
};
```

- **`iomap_readahead` must set:**

  - `ops->read_folio_range()` and `rac`

- **`iomap_read_folio` must set:**

  - `ops->read_folio_range()` and `cur_folio`

`ops->submit_read()` and `read_ctx` are optional. `read_ctx` is used to pass in any custom data the caller needs accessible in the ops callbacks for fulfilling reads.

<a id="rst-buffered-writes"></a>

### Buffered Writes

The `iomap_file_buffered_write` function writes an `iocb` to the pagecache. `IOMAP_WRITE` or `IOMAP_WRITE` \| `IOMAP_NOWAIT` will be passed as the `flags` argument to `->iomap_begin`. Callers commonly take `i_rwsem` in either shared or exclusive mode before calling this function.

<a id="rst-mmap-write-faults"></a>

#### mmap Write Faults

The `iomap_page_mkwrite` function handles a write fault to a folio in the pagecache. `IOMAP_WRITE | IOMAP_FAULT` will be passed as the `flags` argument to `->iomap_begin`. Callers commonly take the mmap `invalidate_lock` in shared or exclusive mode before calling this function.

<a id="rst-buffered-write-failures"></a>

#### Buffered Write Failures

After a short write to the pagecache, the areas not written will not become marked dirty. The filesystem must arrange to [cancel](<https://lore.kernel.org/all/20221123055812.747923-6-david@fromorbit.com/>)<a id="rst-cancel"></a> such [reservations](<https://lore.kernel.org/linux-xfs/20220817093627.GZ3600936@dread.disaster.area/>)<a id="rst-reservations"></a> because writeback will not consume the reservation. The `iomap_write_delalloc_release` can be called from a `->iomap_end` function to find all the clean areas of the folios caching a fresh (`IOMAP_F_NEW`) delalloc mapping. It takes the `invalidate_lock`.

The filesystem must supply a function `punch` to be called for each file range in this state. This function must *only* remove delayed allocation reservations, in case another thread racing with the current thread writes successfully to the same region and triggers writeback to flush the dirty data out to disk.

<a id="rst-zeroing-for-file-operations"></a>

#### Zeroing for File Operations

Filesystems can call `iomap_zero_range` to perform zeroing of the pagecache for non-truncation file operations that are not aligned to the fsblock size. `IOMAP_ZERO` will be passed as the `flags` argument to `->iomap_begin`. Callers typically hold `i_rwsem` and `invalidate_lock` in exclusive mode before calling this function.

<a id="rst-unsharing-reflinked-file-data"></a>

#### Unsharing Reflinked File Data

Filesystems can call `iomap_file_unshare` to force a file sharing storage with another file to preemptively copy the shared data to newly allocate storage. `IOMAP_WRITE | IOMAP_UNSHARE` will be passed as the `flags` argument to `->iomap_begin`. Callers typically hold `i_rwsem` and `invalidate_lock` in exclusive mode before calling this function.

<a id="rst-truncation"></a>

### Truncation

Filesystems can call `iomap_truncate_page` to zero the bytes in the pagecache from EOF to the end of the fsblock during a file truncation operation. `truncate_setsize` or `truncate_pagecache` will take care of everything after the EOF block. `IOMAP_ZERO` will be passed as the `flags` argument to `->iomap_begin`. Callers typically hold `i_rwsem` and `invalidate_lock` in exclusive mode before calling this function.

<a id="rst-pagecache-writeback"></a>

### Pagecache Writeback

Filesystems can call `iomap_writepages` to respond to a request to write dirty pagecache folios to disk. The `mapping` and `wbc` parameters should be passed unchanged. The `wpc` pointer should be allocated by the filesystem and must be initialized to zero.

The pagecache will lock each folio before trying to schedule it for writeback. It does not lock `i_rwsem` or `invalidate_lock`.

The dirty bit will be cleared for all folios run through the `->writeback_range` machinery described below even if the writeback fails. This is to prevent dirty folio clots when storage devices fail; an `-EIO` is recorded for userspace to collect via `fsync`.

The `ops` structure must be specified and is as follows:

<a id="rst-struct-iomap-writeback-ops"></a>

#### `struct iomap_writeback_ops`



```c
struct iomap_writeback_ops {
   int (*writeback_range)(struct iomap_writepage_ctx *wpc,
       struct folio *folio, u64 pos, unsigned int len, u64 end_pos);
   int (*writeback_submit)(struct iomap_writepage_ctx *wpc, int error);
};
```

The fields are as follows:

> - `writeback_range`: Sets `wpc->iomap` to the space mapping of the file range (in bytes) given by `offset` and `len`. iomap calls this function for each dirty fs block in each dirty folio, though it will [reuse mappings](<https://lore.kernel.org/all/20231207072710.176093-15-hch@lst.de/>)<a id="rst-reuse-mappings"></a> for runs of contiguous dirty fsblocks within a folio. Do not return `IOMAP_INLINE` mappings here; the `->iomap_end` function must deal with persisting written data. Do not return `IOMAP_DELALLOC` mappings here; iomap currently requires mapping to allocated space. Filesystems can skip a potentially expensive mapping lookup if the mappings have not changed. This revalidation must be open-coded by the filesystem; it is unclear if `iomap::validity_cookie` can be reused for this purpose.
>
>   If this methods fails to schedule I/O for any part of a dirty folio, it should throw away any reservations that may have been made for the write. The folio will be marked clean and an `-EIO` recorded in the pagecache. Filesystems can use this callback to [remove](<https://lore.kernel.org/all/20201029163313.1766967-1-bfoster@redhat.com/>)<a id="rst-remove"></a> delalloc reservations to avoid having delalloc reservations for clean pagecache. This function must be supplied by the filesystem. If this succeeds, iomap_finish_folio_write() must be called once writeback completes for the range, regardless of whether the writeback succeeded or failed.
>
> - `writeback_submit`: Submit the previous built writeback context. Block based file systems should use the iomap_ioend_writeback_submit helper, other file system can implement their own. File systems can optionally hook into writeback bio submission. This might include pre-write space accounting updates, or installing a custom `->bi_end_io` function for internal purposes, such as deferring the ioend completion to a workqueue to run metadata update transactions from process context before submitting the bio. This function must be supplied by the filesystem.

<a id="rst-pagecache-writeback-completion"></a>

#### Pagecache Writeback Completion

To handle the bookkeeping that must happen after disk I/O for writeback completes, iomap creates chains of `struct iomap_ioend` objects that wrap the `bio` that is used to write pagecache data to disk. By default, iomap finishes writeback ioends by clearing the writeback bit on the folios attached to the `ioend`. If the write failed, it will also set the error bits on the folios and the address space. This can happen in interrupt or process context, depending on the storage device. Filesystems that need to update internal bookkeeping (e.g. unwritten extent conversions) should set their own bi_end_io on the bios submitted by `->submit_writeback` This function should call `iomap_finish_ioends` after finishing its own work (e.g. unwritten extent conversion).

Some filesystems may wish to [amortize the cost of running metadata transactions](<https://lore.kernel.org/all/20220120034733.221737-1-david@fromorbit.com/>)<a id="rst-amortize-the-cost-of-running-metadata-transactions"></a> for post-writeback updates by batching them. They may also require transactions to run from process context, which implies punting batches to a workqueue. iomap ioends contain a `list_head` to enable batching.

Given a batch of ioends, iomap has a few helpers to assist with amortization:

> - `iomap_sort_ioends`: Sort all the ioends in the list by file offset.
>
> - `iomap_ioend_try_merge`: Given an ioend that is not in any list and a separate list of sorted ioends, merge as many of the ioends from the head of the list into the given ioend. ioends can only be merged if the file range and storage addresses are contiguous; the unwritten and shared status are the same; and the write I/O outcome is the same. The merged ioends become their own list.
>
> - `iomap_finish_ioends`: Finish an ioend that possibly has other ioends linked to it.

<a id="rst-direct-i-o"></a>

## Direct I/O

In Linux, direct I/O is defined as file I/O that is issued directly to storage, bypassing the pagecache. The `iomap_dio_rw` function implements O_DIRECT (direct I/O) reads and writes for files.



```c
ssize_t iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
                     const struct iomap_ops *ops,
                     const struct iomap_dio_ops *dops,
                     unsigned int dio_flags, void *private,
                     size_t done_before);
```

The filesystem can provide the `dops` parameter if it needs to perform extra work before or after the I/O is issued to storage. The `done_before` parameter tells the how much of the request has already been transferred. It is used to continue a request asynchronously when [part of the request](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=c03098d4b9ad76bca2966a8769dcfe59f7f85103>)<a id="rst-part-of-the-request"></a> has already been completed synchronously.

The `done_before` parameter should be set if writes for the `iocb` have been initiated prior to the call. The direction of the I/O is determined from the `iocb` passed in.

The `dio_flags` argument can be set to any combination of the following values:

> - `IOMAP_DIO_FORCE_WAIT`: Wait for the I/O to complete even if the kiocb is not synchronous.
>
> - `IOMAP_DIO_OVERWRITE_ONLY`: Perform a pure overwrite for this range or fail with `-EAGAIN`. This can be used by filesystems with complex unaligned I/O write paths to provide an optimised fast path for unaligned writes. If a pure overwrite can be performed, then serialisation against other I/Os to the same filesystem block(s) is unnecessary as there is no risk of stale data exposure or data loss. If a pure overwrite cannot be performed, then the filesystem can perform the serialisation steps needed to provide exclusive access to the unaligned I/O range so that it can perform allocation and sub-block zeroing safely. Filesystems can use this flag to try to reduce locking contention, but a lot of [detailed checking](<https://lore.kernel.org/linux-ext4/20230314130759.642710-1-bfoster@redhat.com/>)<a id="rst-detailed-checking"></a> is required to do it [correctly](<https://lore.kernel.org/linux-ext4/20230810165559.946222-1-bfoster@redhat.com/>)<a id="rst-correctly"></a>.
>
> - `IOMAP_DIO_PARTIAL`: If a page fault occurs, return whatever progress has already been made. The caller may deal with the page fault and retry the operation. If the caller decides to retry the operation, it should pass the accumulated return values of all previous calls as the `done_before` parameter to the next call.

These `struct kiocb` flags are significant for direct I/O with iomap:

> - `IOCB_NOWAIT`: Turns on `IOMAP_NOWAIT`.
>
> - `IOCB_SYNC`: Ensure that the device has persisted data to disk before completing the call. In the case of pure overwrites, the I/O may be issued with FUA enabled.
>
> - `IOCB_HIPRI`: Poll for I/O completion instead of waiting for an interrupt. Only meaningful for asynchronous I/O, and only if the entire I/O can be issued as a single `struct bio`.

Filesystems should call `iomap_dio_rw` from `->read_iter` and `->write_iter`, and set `FMODE_CAN_ODIRECT` in the `->open` function for the file. They should not set `->direct_IO`, which is deprecated.

If a filesystem wishes to perform its own work before direct I/O completion, it should call `__iomap_dio_rw`. If its return value is not an error pointer or a NULL pointer, the filesystem should pass the return value to `iomap_dio_complete` after finishing its internal work.

<a id="rst-return-values"></a>

### Return Values

`iomap_dio_rw` can return one of the following:

> - A non-negative number of bytes transferred.
>
> - `-ENOTBLK`: Fall back to buffered I/O. iomap itself will return this value if it cannot invalidate the page cache before issuing the I/O to storage. The `->iomap_begin` or `->iomap_end` functions may also return this value.
>
> - `-EIOCBQUEUED`: The asynchronous direct I/O request has been queued and will be completed separately.
>
> - Any of the other negative error codes.

<a id="rst-direct-reads"></a>

### Direct Reads

A direct I/O read initiates a read I/O from the storage device to the caller's buffer. Dirty parts of the pagecache are flushed to storage before initiating the read io. The `flags` value for `->iomap_begin` will be `IOMAP_DIRECT` with any combination of the following enhancements:

> - `IOMAP_NOWAIT`, as defined previously.

Callers commonly hold `i_rwsem` in shared mode before calling this function.

<a id="rst-direct-writes"></a>

### Direct Writes

A direct I/O write initiates a write I/O to the storage device from the caller's buffer. Dirty parts of the pagecache are flushed to storage before initiating the write io. The pagecache is invalidated both before and after the write io. The `flags` value for `->iomap_begin` will be `IOMAP_DIRECT | IOMAP_WRITE` with any combination of the following enhancements:

> - `IOMAP_NOWAIT`, as defined previously.
>
> - `IOMAP_OVERWRITE_ONLY`: Allocating blocks and zeroing partial blocks is not allowed. The entire file range must map to a single written or unwritten extent. The file I/O range must be aligned to the filesystem block size if the mapping is unwritten and the filesystem cannot handle zeroing the unaligned regions without exposing stale contents.
>
> - `IOMAP_ATOMIC`: This write is being issued with torn-write protection. Torn-write protection may be provided based on HW-offload or by a software mechanism provided by the filesystem.
>
>   For HW-offload based support, only a single bio can be created for the write, and the write must not be split into multiple I/O requests, i.e. flag REQ_ATOMIC must be set. The file range to write must be aligned to satisfy the requirements of both the filesystem and the underlying block device's atomic commit capabilities. If filesystem metadata updates are required (e.g. unwritten extent conversion or copy-on-write), all updates for the entire file range must be committed atomically as well. Untorn-writes may be longer than a single file block. In all cases, the mapping start disk block must have at least the same alignment as the write offset. The filesystems must set IOMAP_F_ATOMIC_BIO to inform iomap core of an untorn-write based on HW-offload.
>
>   For untorn-writes based on a software mechanism provided by the filesystem, all the disk block alignment and single bio restrictions which apply for HW-offload based untorn-writes do not apply. The mechanism would typically be used as a fallback for when HW-offload based untorn-writes may not be issued, e.g. the range of the write covers multiple extents, meaning that it is not possible to issue a single bio. All filesystem metadata updates for the entire file range must be committed atomically as well.

Callers commonly hold `i_rwsem` in shared or exclusive mode before calling this function.

<a id="rst-struct-iomap-dio-ops"></a>

### `struct iomap_dio_ops:`



```c
struct iomap_dio_ops {
    void (*submit_io)(const struct iomap_iter *iter, struct bio *bio,
                      loff_t file_offset);
    int (*end_io)(struct kiocb *iocb, ssize_t size, int error,
                  unsigned flags);
    struct bio_set *bio_set;
};
```

The fields of this structure are as follows:

> - `submit_io`: iomap calls this function when it has constructed a `struct bio` object for the I/O requested, and wishes to submit it to the block device. If no function is provided, `submit_bio` will be called directly. Filesystems that would like to perform additional work before (e.g. data replication for btrfs) should implement this function.
>
> - `end_io`: This is called after the `struct bio` completes. This function should perform post-write conversions of unwritten extent mappings, handle write failures, etc. The `flags` argument may be set to a combination of the following:
>
>   - `IOMAP_DIO_UNWRITTEN`: The mapping was unwritten, so the ioend should mark the extent as written.
>
>   - `IOMAP_DIO_COW`: Writing to the space in the mapping required a copy on write operation, so the ioend should switch mappings.
>
> - `bio_set`: This allows the filesystem to provide a custom bio_set for allocating direct I/O bios. This enables filesystems to [stash additional per-bio information](<https://lore.kernel.org/all/20220505201115.937837-3-hch@lst.de/>)<a id="rst-stash-additional-per-bio-information"></a> for private use. If this field is NULL, generic `struct bio` objects will be used.

Filesystems that want to perform extra work after an I/O completion should set a custom `->bi_end_io` function via `->submit_io`. Afterwards, the custom endio function must call `iomap_dio_bio_end_io` to finish the direct I/O.

<a id="rst-dax-i-o"></a>

## DAX I/O

Some storage devices can be directly mapped as memory. These devices support a new access mode known as "fsdax" that allows loads and stores through the CPU and memory controller.

<a id="rst-fsdax-reads"></a>

### fsdax Reads

A fsdax read performs a memcpy from storage device to the caller's buffer. The `flags` value for `->iomap_begin` will be `IOMAP_DAX` with any combination of the following enhancements:

> - `IOMAP_NOWAIT`, as defined previously.

Callers commonly hold `i_rwsem` in shared mode before calling this function.

<a id="rst-fsdax-writes"></a>

### fsdax Writes

A fsdax write initiates a memcpy to the storage device from the caller's buffer. The `flags` value for `->iomap_begin` will be `IOMAP_DAX | IOMAP_WRITE` with any combination of the following enhancements:

> - `IOMAP_NOWAIT`, as defined previously.
>
> - `IOMAP_OVERWRITE_ONLY`: The caller requires a pure overwrite to be performed from this mapping. This requires the filesystem extent mapping to already exist as an `IOMAP_MAPPED` type and span the entire range of the write I/O request. If the filesystem cannot map this request in a way that allows the iomap infrastructure to perform a pure overwrite, it must fail the mapping operation with `-EAGAIN`.

Callers commonly hold `i_rwsem` in exclusive mode before calling this function.

<a id="rst-fsdax-mmap-faults"></a>

#### fsdax mmap Faults

The `dax_iomap_fault` function handles read and write faults to fsdax storage. For a read fault, `IOMAP_DAX | IOMAP_FAULT` will be passed as the `flags` argument to `->iomap_begin`. For a write fault, `IOMAP_DAX | IOMAP_FAULT | IOMAP_WRITE` will be passed as the `flags` argument to `->iomap_begin`.

Callers commonly hold the same locks as they do to call their iomap pagecache counterparts.

<a id="rst-fsdax-truncation-fallocate-and-unsharing"></a>

### fsdax Truncation, fallocate, and Unsharing

For fsdax files, the following functions are provided to replace their iomap pagecache I/O counterparts. The `flags` argument to `->iomap_begin` are the same as the pagecache counterparts, with `IOMAP_DAX` added.

> - `dax_file_unshare`
>
> - `dax_zero_range`
>
> - `dax_truncate_page`

Callers commonly hold the same locks as they do to call their iomap pagecache counterparts.

<a id="rst-fsdax-deduplication"></a>

### fsdax Deduplication

Filesystems implementing the `FIDEDUPERANGE` ioctl must call the `dax_remap_file_range_prep` function with their own iomap read ops.

<a id="rst-seeking-files"></a>

## Seeking Files

iomap implements the two iterating whence modes of the `llseek` system call.

<a id="rst-seek-data"></a>

### SEEK_DATA

The `iomap_seek_data` function implements the SEEK_DATA "whence" value for llseek. `IOMAP_REPORT` will be passed as the `flags` argument to `->iomap_begin`.

For unwritten mappings, the pagecache will be searched. Regions of the pagecache with a folio mapped and uptodate fsblocks within those folios will be reported as data areas.

Callers commonly hold `i_rwsem` in shared mode before calling this function.

<a id="rst-seek-hole"></a>

### SEEK_HOLE

The `iomap_seek_hole` function implements the SEEK_HOLE "whence" value for llseek. `IOMAP_REPORT` will be passed as the `flags` argument to `->iomap_begin`.

For unwritten mappings, the pagecache will be searched. Regions of the pagecache with no folio mapped, or a \!uptodate fsblock within a folio will be reported as sparse hole areas.

Callers commonly hold `i_rwsem` in shared mode before calling this function.

<a id="rst-swap-file-activation"></a>

## Swap File Activation

The `iomap_swapfile_activate` function finds all the base-page aligned regions in a file and sets them up as swap space. The file will be `fsync()`'d before activation. `IOMAP_REPORT` will be passed as the `flags` argument to `->iomap_begin`. All mappings must be mapped or unwritten; cannot be dirty or shared, and cannot span multiple block devices. Callers must hold `i_rwsem` in exclusive mode; this is already provided by `swapon`.

<a id="rst-file-space-mapping-reporting"></a>

## File Space Mapping Reporting

iomap implements two of the file space mapping system calls.

<a id="rst-fs-ioc-fiemap"></a>

### FS_IOC_FIEMAP

The `iomap_fiemap` function exports file extent mappings to userspace in the format specified by the `FS_IOC_FIEMAP` ioctl. `IOMAP_REPORT` will be passed as the `flags` argument to `->iomap_begin`. Callers commonly hold `i_rwsem` in shared mode before calling this function.

<a id="rst-fibmap-deprecated"></a>

### FIBMAP (deprecated)

`iomap_bmap` implements FIBMAP. The calling conventions are the same as for FIEMAP. This function is only provided to maintain compatibility for filesystems that implemented FIBMAP prior to conversion. This ioctl is deprecated; do **not** add a FIBMAP implementation to filesystems that do not have it. Callers should probably hold `i_rwsem` in shared mode before calling this function, but this is unclear.

---

# Porting Your Filesystem

_Peios Kernel / Internals / Filesystems / iomap_

> Why Convert?

<a id="rst-porting-your-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-iomap-porting"></a>



<!-- Dumb style notes to maintain the author's sanity:
Please try to start sentences on separate lines so that
sentence changes don't bleed colors in diff.
Heading decorations are documented in sphinx.rst. -->

<a id="rst-table-of-contents"></a>



<a id="rst-why-convert"></a>

## Why Convert?

There are several reasons to convert a filesystem to iomap:

> 1. The classic Linux I/O path is not terribly efficient. Pagecache operations lock a single base page at a time and then call into the filesystem to return a mapping for only that page. Direct I/O operations build I/O requests a single file block at a time. This worked well enough for direct/indirect-mapped filesystems such as ext2, but is very inefficient for extent-based filesystems such as XFS.
>
> 2. Large folios are only supported via iomap; there are no plans to convert the old buffer_head path to use them.
>
> 3. Direct access to storage on memory-like devices (fsdax) is only supported via iomap.
>
> 4. Lower maintenance overhead for individual filesystem maintainers. iomap handles common pagecache related operations itself, such as allocating, instantiating, locking, and unlocking of folios. No -&gt;write_begin(), -&gt;write_end() or direct_IO address_space_operations are required to be implemented by filesystem using iomap.

<a id="rst-how-do-i-convert-a-filesystem"></a>

## How Do I Convert a Filesystem?

First, add `#include <linux/iomap.h>` from your source code and add `select FS_IOMAP` to your filesystem's Kconfig option. Build the kernel, run fstests with the `-g all` option across a wide variety of your filesystem's supported configurations to build a baseline of which tests pass and which ones fail.

The recommended approach is first to implement `->iomap_begin` (and `->iomap_end` if necessary) to allow iomap to obtain a read-only mapping of a file range. In most cases, this is a relatively trivial conversion of the existing `get_block()` function for read-only mappings. `FS_IOC_FIEMAP` is a good first target because it is trivial to implement support for it and then to determine that the extent map iteration is correct from userspace. If FIEMAP is returning the correct information, it's a good sign that other read-only mapping operations will do the right thing.

Next, modify the filesystem's `get_block(create = false)` implementation to use the new `->iomap_begin` implementation to map file space for selected read operations. Hide behind a debugging knob the ability to switch on the iomap mapping functions for selected call paths. It is necessary to write some code to fill out the bufferhead-based mapping information from the `iomap` structure, but the new functions can be tested without needing to implement any iomap APIs.

Once the read-only functions are working like this, convert each high level file operation one by one to use iomap native APIs instead of going through `get_block()`. Done one at a time, regressions should be self evident. You *do* have a regression test baseline for fstests, right? It is suggested to convert swap file activation, `SEEK_DATA`, and `SEEK_HOLE` before tackling the I/O paths. A likely complexity at this point will be converting the buffered read I/O path because of bufferheads. The buffered read I/O paths doesn't need to be converted yet, though the direct I/O read path should be converted in this phase.

At this point, you should look over your `->iomap_begin` function. If it switches between large blocks of code based on dispatching of the `flags` argument, you should consider breaking it up into per-operation iomap ops with smaller, more cohesive functions. XFS is a good example of this.

The next thing to do is implement `get_blocks(create == true)` functionality in the `->iomap_begin`/`->iomap_end` methods. It is strongly recommended to create separate mapping functions and iomap ops for write operations. Then convert the direct I/O write path to iomap, and start running fsx w/ DIO enabled in earnest on filesystem. This will flush out lots of data integrity corner case bugs that the new write mapping implementation introduces.

Now, convert any remaining file operations to call the iomap functions. This will get the entire filesystem using the new mapping functions, and they should largely be debugged and working correctly after this step.

Most likely at this point, the buffered read and write paths will still need to be converted. The mapping functions should all work correctly, so all that needs to be done is rewriting all the code that interfaces with bufferheads to interface with iomap and folios. It is much easier first to get regular file I/O (without any fancy features like fscrypt, fsverity, compression, or data=journaling) converted to use iomap. Some of those fancy features (fscrypt and compression) aren't implemented yet in iomap. For unjournalled filesystems that use the pagecache for symbolic links and directories, you might also try converting their handling to iomap.

The rest is left as an exercise for the reader, as it will be different for every filesystem. If you encounter problems, email the people and lists in `get_maintainers.pl` for help.

---

# NFS

_Peios Kernel / Internals / Filesystems / nfs_

> Reference for NFS.

<a id="rst-nfs"></a>

- [NFSv4 client identifier](</kernel/internals/filesystems/nfs/client-identifier.md>)
- [Making Filesystems Exportable](</kernel/internals/filesystems/nfs/exporting.md>)
- [NFS LOCALIO](</kernel/internals/filesystems/nfs/localio.md>)
- [Reference counting in pnfs](</kernel/internals/filesystems/nfs/pnfs.md>)
- [RPC Cache](</kernel/internals/filesystems/nfs/rpc-cache.md>)
- [rpcsec_gss support for kernel RPC servers](</kernel/internals/filesystems/nfs/rpc-server-gss.md>)
- [NFSv4.1 Server Implementation](</kernel/internals/filesystems/nfs/nfs41-server.md>)
- [NFSD IO MODES](</kernel/internals/filesystems/nfs/nfsd-io-modes.md>)
- [Kernel NFS Server Statistics](</kernel/internals/filesystems/nfs/knfsd-stats.md>)
- [Reexporting NFS filesystems](</kernel/internals/filesystems/nfs/reexport.md>)

---

# NFSv4 client identifier

_Peios Kernel / Internals / Filesystems / nfs_

> This document explains how the NFSv4 protocol identifies client instances in order to maintain file open and lock state during system restarts. A special identifier and principal are maintained on each client. These can be set by…

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-nfsv4-client-identifier"></a>

## NFSv4 client identifier

This document explains how the NFSv4 protocol identifies client instances in order to maintain file open and lock state during system restarts. A special identifier and principal are maintained on each client. These can be set by administrators, scripts provided by site administrators, or tools provided by Linux distributors.

There are risks if a client's NFSv4 identifier and its principal are not chosen carefully.

<a id="rst-introduction"></a>

### Introduction

The NFSv4 protocol uses "lease-based file locking". Leases help NFSv4 servers provide file lock guarantees and manage their resources.

Simply put, an NFSv4 server creates a lease for each NFSv4 client. The server collects each client's file open and lock state under the lease for that client.

The client is responsible for periodically renewing its leases. While a lease remains valid, the server holding that lease guarantees the file locks the client has created remain in place.

If a client stops renewing its lease (for example, if it crashes), the NFSv4 protocol allows the server to remove the client's open and lock state after a certain period of time. When a client restarts, it indicates to servers that open and lock state associated with its previous leases is no longer valid and can be destroyed immediately.

In addition, each NFSv4 server manages a persistent list of client leases. When the server restarts and clients attempt to recover their state, the server uses this list to distinguish amongst clients that held state before the server restarted and clients sending fresh OPEN and LOCK requests. This enables file locks to persist safely across server restarts.

<a id="rst-nfsv4-client-identifiers"></a>

### NFSv4 client identifiers

Each NFSv4 client presents an identifier to NFSv4 servers so that they can associate the client with its lease. Each client's identifier consists of two elements:

> - co_ownerid: An arbitrary but fixed string.
>
> - boot verifier: A 64-bit incarnation verifier that enables a server to distinguish successive boot epochs of the same client.

The NFSv4.0 specification refers to these two items as an "nfs_client_id4". The NFSv4.1 specification refers to these two items as a "client_owner4".

NFSv4 servers tie this identifier to the principal and security flavor that the client used when presenting it. Servers use this principal to authorize subsequent lease modification operations sent by the client. Effectively this principal is a third element of the identifier.

As part of the identity presented to servers, a good "co_ownerid" string has several important properties:

> - The "co_ownerid" string identifies the client during reboot recovery, therefore the string is persistent across client reboots.
>
> - The "co_ownerid" string helps servers distinguish the client from others, therefore the string is globally unique. Note that there is no central authority that assigns "co_ownerid" strings.
>
> - Because it often appears on the network in the clear, the "co_ownerid" string does not reveal private information about the client itself.
>
> - The content of the "co_ownerid" string is set and unchanging before the client attempts NFSv4 mounts after a restart.
>
> - The NFSv4 protocol places a 1024-byte limit on the size of the "co_ownerid" string.

<a id="rst-protecting-nfsv4-lease-state"></a>

### Protecting NFSv4 lease state

NFSv4 servers utilize the "client_owner4" as described above to assign a unique lease to each client. Under this scheme, there are circumstances where clients can interfere with each other. This is referred to as "lease stealing".

If distinct clients present the same "co_ownerid" string and use the same principal (for example, AUTH_SYS and UID 0), a server is unable to tell that the clients are not the same. Each distinct client presents a different boot verifier, so it appears to the server as if there is one client that is rebooting frequently. Neither client can maintain open or lock state in this scenario.

If distinct clients present the same "co_ownerid" string and use distinct principals, the server is likely to allow the first client to operate normally but reject subsequent clients with the same "co_ownerid" string.

If a client's "co_ownerid" string or principal are not stable, state recovery after a server or client reboot is not guaranteed. If a client unexpectedly restarts but presents a different "co_ownerid" string or principal to the server, the server orphans the client's previous open and lock state. This blocks access to locked files until the server removes the orphaned state.

If the server restarts and a client presents a changed "co_ownerid" string or principal to the server, the server will not allow the client to reclaim its open and lock state, and may give those locks to other clients in the meantime. This is referred to as "lock stealing".

Lease stealing and lock stealing increase the potential for denial of service and in rare cases even data corruption.

<a id="rst-selecting-an-appropriate-client-identifier"></a>

### Selecting an appropriate client identifier

By default, the Linux NFSv4 client implementation constructs its "co_ownerid" string starting with the words "Linux NFS" followed by the client's UTS node name (the same node name, incidentally, that is used as the "machine name" in an AUTH_SYS credential). In small deployments, this construction is usually adequate. Often, however, the node name by itself is not adequately unique, and can change unexpectedly. Problematic situations include:

> - NFS-root (diskless) clients, where the local DHCP server (or equivalent) does not provide a unique host name.
>
> - "Containers" within a single Linux host.  If each container has a separate network namespace, but does not use the UTS namespace to provide a unique host name, then there can be multiple NFS client instances with the same host name.
>
> - Clients across multiple administrative domains that access a common NFS server. If hostnames are not assigned centrally then uniqueness cannot be guaranteed unless a domain name is included in the hostname.

Linux provides two mechanisms to add uniqueness to its "co_ownerid" string:

> - **nfs.nfs4_unique_id**
>
>   This module parameter can set an arbitrary uniquifier string via the kernel command line, or when the "nfs" module is loaded.
>
> - **/sys/fs/nfs/net/nfs_client/identifier**
>
>   This virtual file, available since Linux 5.3, is local to the network namespace in which it is accessed and so can provide distinction between network namespaces (containers) when the hostname remains uniform.

Note that this file is empty on name-space creation. If the container system has access to some sort of per-container identity then that uniquifier can be used. For example, a uniquifier might be formed at boot using the container's internal identifier:

> - **sha256sum /etc/machine-id \| awk '\{print $1\}' \\**
>
>   &gt; /sys/fs/nfs/net/nfs_client/identifier

<a id="rst-security-considerations"></a>

### Security considerations

The use of cryptographic security for lease management operations is strongly encouraged.

If NFS with Kerberos is not configured, a Linux NFSv4 client uses AUTH_SYS and UID 0 as the principal part of its client identity. This configuration is not only insecure, it increases the risk of lease and lock stealing. However, it might be the only choice for client configurations that have no local persistent storage. "co_ownerid" string uniqueness and persistence is critical in this case.

When a Kerberos keytab is present on a Linux NFS client, the client attempts to use one of the principals in that keytab when identifying itself to servers. The "sec=" mount option does not control this behavior. Alternately, a single-user client with a Kerberos principal can use that principal in place of the client's host principal.

Using Kerberos for this purpose enables the client and server to use the same lease for operations covered by all "sec=" settings. Additionally, the Linux NFS client uses the RPCSEC_GSS security flavor with Kerberos and the integrity QOS to prevent in-transit modification of lease modification requests.

<a id="rst-additional-notes"></a>

### Additional notes

The Linux NFSv4 client establishes a single lease on each NFSv4 server it accesses. NFSv4 mounts from a Linux NFSv4 client of a particular server then share that lease.

Once a client establishes open and lock state, the NFSv4 protocol enables lease state to transition to other servers, following data that has been migrated. This hides data migration completely from running applications. The Linux NFSv4 client facilitates state migration by presenting the same "client_owner4" to all servers it encounters.

<a id="rst-see-also"></a>

## See Also

> - nfs(5)
>
> - kerberos(7)
>
> - RFC 7530 for the NFSv4.0 specification
>
> - RFC 8881 for the NFSv4.1 specification.

---

# Making Filesystems Exportable

_Peios Kernel / Internals / Filesystems / nfs_

> All filesystem operations require a dentry (or two) as a starting point. Local applications have a reference-counted hold on suitable dentries via open file descriptors or cwd/root. However remote applications that access a filesystem via…

**orphan:** 

<a id="rst-making-filesystems-exportable"></a>

## Making Filesystems Exportable

<a id="rst-overview"></a>

### Overview

All filesystem operations require a dentry (or two) as a starting point.  Local applications have a reference-counted hold on suitable dentries via open file descriptors or cwd/root.  However remote applications that access a filesystem via a remote filesystem protocol such as NFS may not be able to hold such a reference, and so need a different way to refer to a particular dentry.  As the alternative form of reference needs to be stable across renames, truncates, and server-reboot (among other things, though these tend to be the most problematic), there is no simple answer like 'filename'.

The mechanism discussed here allows each filesystem implementation to specify how to generate an opaque (outside of the filesystem) byte string for any dentry, and how to find an appropriate dentry for any given opaque byte string. This byte string will be called a "filehandle fragment" as it corresponds to part of an NFS filehandle.

A filesystem which supports the mapping between filehandle fragments and dentries will be termed "exportable".

<a id="rst-dcache-issues"></a>

### Dcache Issues

The dcache normally contains a proper prefix of any given filesystem tree.  This means that if any filesystem object is in the dcache, then all of the ancestors of that filesystem object are also in the dcache. As normal access is by filename this prefix is created naturally and maintained easily (by each object maintaining a reference count on its parent).

However when objects are included into the dcache by interpreting a filehandle fragment, there is no automatic creation of a path prefix for the object.  This leads to two related but distinct features of the dcache that are not needed for normal filesystem access.

1. The dcache must sometimes contain objects that are not part of the proper prefix. i.e that are not connected to the root.

2. The dcache must be prepared for a newly found (via -&gt;lookup) directory to already have a (non-connected) dentry, and must be able to move that dentry into place (based on the parent and name in the -&gt;lookup).   This is particularly needed for directories as it is a dcache invariant that directories only have one dentry.

To implement these features, the dcache has:

- **a.** A dentry flag DCACHE_DISCONNECTED which is set on any dentry that might not be part of the proper prefix. This is set when anonymous dentries are created, and cleared when a dentry is noticed to be a child of a dentry which is in the proper prefix.  If the refcount on a dentry with this flag set becomes zero, the dentry is immediately discarded, rather than being kept in the dcache.  If a dentry that is not already in the dcache is repeatedly accessed by filehandle (as NFSD might do), an new dentry will be a allocated for each access, and discarded at the end of the access.

  Note that such a dentry can acquire children, name, ancestors, etc. without losing DCACHE_DISCONNECTED - that flag is only cleared when subtree is successfully reconnected to root.  Until then dentries in such subtree are retained only as long as there are references; refcount reaching zero means immediate eviction, same as for unhashed dentries.  That guarantees that we won't need to hunt them down upon umount.

- **b.** A primitive for creation of secondary roots - d_obtain_root(inode). Those do \_not\_ bear DCACHE_DISCONNECTED.  They are placed on the per-superblock list (-&gt;s_roots), so they can be located at umount time for eviction purposes.

- **c.** Helper routines to allocate anonymous dentries, and to help attach loose directory dentries at lookup time. They are:

  > - **d_obtain_alias(inode) will return a dentry for the given inode.**
  >
  >   If the inode already has a dentry, one of those is returned.
  >
  >   If it doesn't, a new anonymous (IS_ROOT and DCACHE_DISCONNECTED) dentry is allocated and attached.
  >
  >   In the case of a directory, care is taken that only one dentry can ever be attached.
  >
  > - **d_splice_alias(inode, dentry) will introduce a new dentry into the tree;**
  >
  >   either the passed-in dentry or a preexisting alias for the given inode (such as an anonymous one created by d_obtain_alias), if appropriate. It returns NULL when the passed-in dentry is used, following the calling convention of -&gt;lookup.

<a id="rst-filesystem-issues"></a>

### Filesystem Issues

For a filesystem to be exportable it must:

> 1. provide the filehandle fragment routines described below.
>
> 2. make sure that d_splice_alias is used rather than d_add when -&gt;lookup finds an inode for a given parent and name.
>
>    If inode is NULL, d_splice_alias(inode, dentry) is equivalent to:
>
>
>
>    ```text
>    d_add(dentry, inode), NULL
>    ```
>
>    Similarly, d_splice_alias(ERR_PTR(err), dentry) = ERR_PTR(err)
>
>    Typically the -&gt;lookup routine will simply end with a:
>
>
>
>    ```text
>            return d_splice_alias(inode, dentry);
>    }
>    ```

A file system implementation declares that instances of the filesystem are exportable by setting the s_export_op field in the struct super_block.  This field must point to a struct export_operations which has the following members:


#### <a id="c-struct-export_operations"></a>`struct export_operations`

for nfsd to communicate with file systems

**Definition**

```c
struct export_operations {
        int (*encode_fh)(struct inode *inode, __u32 *fh, int *max_len, struct inode *parent);
        struct dentry * (*fh_to_dentry)(struct super_block *sb, struct fid *fid, int fh_len, int fh_type);
        struct dentry * (*fh_to_parent)(struct super_block *sb, struct fid *fid, int fh_len, int fh_type);
        int (*get_name)(struct dentry *parent, char *name, struct dentry *child);
        struct dentry * (*get_parent)(struct dentry *child);
        int (*commit_metadata)(struct inode *inode);
        int (*get_uuid)(struct super_block *sb, u8 *buf, u32 *len, u64 *offset);
        int (*map_blocks)(struct inode *inode, loff_t offset, u64 len, struct iomap *iomap, bool write, u32 *device_generation);
        int (*commit_blocks)(struct inode *inode, struct iomap *iomaps, int nr_iomaps, struct iattr *iattr);
        int (*permission)(struct handle_to_path_ctx *ctx, unsigned int oflags);
        struct file * (*open)(const struct path *path, unsigned int oflags);
    #define EXPORT_OP_NOWCC                 (0x1);
    #define EXPORT_OP_NOSUBTREECHK          (0x2);
    #define EXPORT_OP_CLOSE_BEFORE_UNLINK   (0x4);
    #define EXPORT_OP_REMOTE_FS             (0x8);
    #define EXPORT_OP_NOATOMIC_ATTR         (0x10)#define EXPORT_OP_FLUSH_ON_CLOSE        (0x20);
    #define EXPORT_OP_NOLOCKS               (0x40);
        unsigned long   flags;
};
```

**Members**

- `encode_fh`:

  **encode_fh** should store in the file handle fragment **fh** (using at most
  **max_len** bytes) information that can be used by **decode_fh** to recover the
  file referred to by the `struct dentry` **de**.  If **flag** has CONNECTABLE bit
  set, the `encode_fh()` should store sufficient information so that a good
  attempt can be made to find not only the file but also it's place in the
  filesystem.   This typically means storing a reference to de->d_parent in
  the filehandle fragment.  `encode_fh()` should return the fileid_type on
  success and on error returns 255 (if the space needed to encode fh is
  greater than **max_len***4 bytes). On error **max_len** contains the minimum
  size(in 4 byte unit) needed to encode the file handle.
- `fh_to_dentry`:

  **fh_to_dentry** is given a `struct super_block` (**sb**) and a file handle
  fragment (**fh**, **fh_len**). It should return a `struct dentry` which refers
  to the same file that the file handle fragment refers to.  If it cannot,
  it should return a `NULL` pointer if the file cannot be found, or an
  `ERR_PTR` error code of `ENOMEM` if a memory allocation failure occurred.
  Any other error code is treated like `NULL`, and will cause an `ESTALE` error
  for callers of `exportfs_decode_fh()`.
  Any suitable dentry can be returned including, if necessary, a new dentry
  created with d_alloc_root.  The caller can then find any other extant
  dentries by following the d_alias links.
- `fh_to_parent`: Same as **fh_to_dentry**, except that it returns a pointer to the parent
  dentry if it was encoded into the filehandle fragment by **encode_fh**.
- `get_name`:

  **get_name** should find a name for the given **child** in the given **parent**
  directory.  The name should be stored in the **name** (with the
  understanding that it is already pointing to a `NAME_MAX` + 1 sized
  buffer.   `get_name()` should return `0` on success, a negative error code
  or error.  **get_name** will be called without **parent->i_rwsem** held.
- `get_parent`:

  **get_parent** should find the parent directory for the given **child** which
  is also a directory.  In the event that it cannot be found, or storage
  space cannot be allocated, a `ERR_PTR` should be returned.
- `commit_metadata`:

  **commit_metadata** should commit metadata changes to stable storage.
- `get_uuid`: Get a filesystem unique signature exposed to clients.
- `map_blocks`: Map and, if necessary, allocate blocks for a layout.
- `commit_blocks`: Commit blocks in a layout once the client is done with them.
- `permission`: Allow filesystems to specify a custom permission function for the
  open_by_handle_at(2) syscall instead of the default permission check.
  This custom permission function is not respected by nfsd.
- `open`: Allow filesystems to specify a custom open function for the
  open_by_handle_at(2) syscall instead of the default `file_open_root()`.
  This custom open function is not respected by nfsd.
- `flags`: Allows the filesystem to communicate to nfsd that it may want to do things
  differently when dealing with it.

**Description**

Methods for open_by_handle(2) syscall with special kernel file systems:

See Documentation/filesystems/nfs/exporting.rst for details on how to use
this interface correctly and the definition of the flags.

- Locking rules:
  get_parent is called with child->d_inode->i_rwsem down
  get_name is not (which is possibly inconsistent)


A filehandle fragment consists of an array of 1 or more 4byte words, together with a one byte "type". The decode_fh routine should not depend on the stated size that is passed to it.  This size may be larger than the original filehandle generated by encode_fh, in which case it will have been padded with nuls.  Rather, the encode_fh routine should choose a "type" which indicates the decode_fh how much of the filehandle is valid, and how it should be interpreted.

<a id="rst-export-operations-flags"></a>

### Export Operations Flags

In addition to the operation vector pointers, struct export_operations also contains a "flags" field that allows the filesystem to communicate to nfsd that it may want to do things differently when dealing with it. The following flags are defined:

> - **EXPORT_OP_NOWCC - disable NFSv3 WCC attributes on this filesystem**
>
>   RFC 1813 recommends that servers always send weak cache consistency (WCC) data to the client after each operation. The server should atomically collect attributes about the inode, do an operation on it, and then collect the attributes afterward. This allows the client to skip issuing GETATTRs in some situations but means that the server is calling vfs_getattr for almost all RPCs. On some filesystems (particularly those that are clustered or networked) this is expensive and atomicity is difficult to guarantee. This flag indicates to nfsd that it should skip providing WCC attributes to the client in NFSv3 replies when doing operations on this filesystem. Consider enabling this on filesystems that have an expensive -&gt;getattr inode operation, or when atomicity between pre and post operation attribute collection is impossible to guarantee.
>
> - **EXPORT_OP_NOSUBTREECHK - disallow subtree checking on this fs**
>
>   Many NFS operations deal with filehandles, which the server must then vet to ensure that they live inside of an exported tree. When the export consists of an entire filesystem, this is trivial. nfsd can just ensure that the filehandle live on the filesystem. When only part of a filesystem is exported however, then nfsd must walk the ancestors of the inode to ensure that it's within an exported subtree. This is an expensive operation and not all filesystems can support it properly. This flag exempts the filesystem from subtree checking and causes exportfs to get back an error if it tries to enable subtree checking on it.
>
> - **EXPORT_OP_CLOSE_BEFORE_UNLINK - always close cached files before unlinking**
>
>   On some exportable filesystems (such as NFS) unlinking a file that is still open can cause a fair bit of extra work. For instance, the NFS client will do a "sillyrename" to ensure that the file sticks around while it's still open. When reexporting, that open file is held by nfsd so we usually end up doing a sillyrename, and then immediately deleting the sillyrenamed file just afterward when the link count actually goes to zero. Sometimes this delete can race with other operations (for instance an rmdir of the parent directory). This flag causes nfsd to close any open files for this inode \_before\_ calling into the vfs to do an unlink or a rename that would replace an existing file.
>
> - **EXPORT_OP_REMOTE_FS - Backing storage for this filesystem is remote**
>
>   PF_LOCAL_THROTTLE exists for loopback NFSD, where a thread needs to write to one bdi (the final bdi) in order to free up writes queued to another bdi (the client bdi). Such threads get a private balance of dirty pages so that dirty pages for the client bdi do not imact the daemon writing to the final bdi. For filesystems whose durable storage is not local (such as exported NFS filesystems), this constraint has negative consequences. EXPORT_OP_REMOTE_FS enables an export to disable writeback throttling.
>
> - **EXPORT_OP_NOATOMIC_ATTR - Filesystem does not update attributes atomically**
>
>   EXPORT_OP_NOATOMIC_ATTR indicates that the exported filesystem cannot provide the semantics required by the "atomic" boolean in NFSv4's change_info4. This boolean indicates to a client whether the returned before and after change attributes were obtained atomically with the respect to the requested metadata operation (UNLINK, OPEN/CREATE, MKDIR, etc).
>
> - **EXPORT_OP_FLUSH_ON_CLOSE - Filesystem flushes file data on close(2)**
>
>   On most filesystems, inodes can remain under writeback after the file is closed. NFSD relies on client activity or local flusher threads to handle writeback. Certain filesystems, such as NFS, flush all of an inode's dirty data on last close. Exports that behave this way should set EXPORT_OP_FLUSH_ON_CLOSE so that NFSD knows to skip waiting for writeback when closing such files.

---

# Kernel NFS Server Statistics

_Peios Kernel / Internals / Filesystems / nfs_

> This document describes the format and semantics of the statistics which the kernel NFS server makes available to userspace. These statistics are available in several text form pseudo files, each of which is described separately below.

<a id="rst-kernel-nfs-server-statistics"></a>

**Authors:** Greg Banks &lt;[gnb@sgi.com](<mailto:gnb@sgi.com>)&gt; - 26 Mar 2009

This document describes the format and semantics of the statistics which the kernel NFS server makes available to userspace.  These statistics are available in several text form pseudo files, each of which is described separately below.

In most cases you don't need to know these formats, as the nfsstat(8) program from the nfs-utils distribution provides a helpful command-line interface for extracting and printing them.

All the files described here are formatted as a sequence of text lines, separated by newline 'n' characters.  Lines beginning with a hash '\#' character are comments intended for humans and should be ignored by parsing routines.  All other lines contain a sequence of fields separated by whitespace.

<a id="rst-proc-fs-nfsd-pool-stats"></a>

## /proc/fs/nfsd/pool_stats

This file is available in kernels from 2.6.30 onwards, if the /proc/fs/nfsd filesystem is mounted (it almost always should be).

The first line is a comment which describes the fields present in all the other lines.  The other lines present the following data as a sequence of unsigned decimal numeric fields.  One line is shown for each NFS thread pool.

All counters are 64 bits wide and wrap naturally.  There is no way to zero these counters, instead applications should do their own rate conversion.

- **pool**

  The id number of the NFS thread pool to which this line applies. This number does not change.

  Thread pool ids are a contiguous set of small integers starting at zero.  The maximum value depends on the thread pool mode, but currently cannot be larger than the number of CPUs in the system. Note that in the default case there will be a single thread pool which contains all the nfsd threads and all the CPUs in the system, and thus this file will have a single line with a pool id of "0".

- **packets-arrived**

  Counts how many NFS packets have arrived.  More precisely, this is the number of times that the network stack has notified the sunrpc server layer that new data may be available on a transport (e.g. an NFS or UDP socket or an NFS/RDMA endpoint).

  Depending on the NFS workload patterns and various network stack effects (such as Large Receive Offload) which can combine packets on the wire, this may be either more or less than the number of NFS calls received (which statistic is available elsewhere). However this is a more accurate and less workload-dependent measure of how much CPU load is being placed on the sunrpc server layer due to NFS network traffic.

- **sockets-enqueued**

  Counts how many times an NFS transport is enqueued to wait for an nfsd thread to service it, i.e. no nfsd thread was considered available.

  The circumstance this statistic tracks indicates that there was NFS network-facing work to be done but it couldn't be done immediately, thus introducing a small delay in servicing NFS calls.  The ideal rate of change for this counter is zero; significantly non-zero values may indicate a performance limitation.

  This can happen because there are too few nfsd threads in the thread pool for the NFS workload (the workload is thread-limited), in which case configuring more nfsd threads will probably improve the performance of the NFS workload.

- **threads-woken**

  Counts how many times an idle nfsd thread is woken to try to receive some data from an NFS transport.

  This statistic tracks the circumstance where incoming network-facing NFS work is being handled quickly, which is a good thing.  The ideal rate of change for this counter will be close to but less than the rate of change of the packets-arrived counter.

- **threads-timedout**

  Counts how many times an nfsd thread triggered an idle timeout, i.e. was not woken to handle any incoming network packets for some time.

  This statistic counts a circumstance where there are more nfsd threads configured than can be used by the NFS workload.  This is a clue that the number of nfsd threads can be reduced without affecting performance.  Unfortunately, it's only a clue and not a strong indication, for a couple of reasons:

  > - Currently the rate at which the counter is incremented is quite slow; the idle timeout is 60 minutes.  Unless the NFS workload remains constant for hours at a time, this counter is unlikely to be providing information that is still useful.
  >
  > - It is usually a wise policy to provide some slack, i.e. configure a few more nfsds than are currently needed, to allow for future spikes in load.

Note that incoming packets on NFS transports will be dealt with in one of three ways.  An nfsd thread can be woken (threads-woken counts this case), or the transport can be enqueued for later attention (sockets-enqueued counts this case), or the packet can be temporarily deferred because the transport is currently being used by an nfsd thread.  This last case is not very interesting and is not explicitly counted, but can be inferred from the other counters thus:



```text
packets-deferred = packets-arrived - ( sockets-enqueued + threads-woken )
```

<a id="rst-more"></a>

## More

Descriptions of the other statistics file should go here.

---

# NFS LOCALIO

_Peios Kernel / Internals / Filesystems / nfs_

> The LOCALIO auxiliary RPC protocol allows the Linux NFS client and server to reliably handshake to determine if they are on the same host. Select "NFS client and server support for LOCALIO auxiliary protocol" in menuconfig to enable…

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-nfs-localio"></a>

<a id="rst-overview"></a>

## Overview

The LOCALIO auxiliary RPC protocol allows the Linux NFS client and server to reliably handshake to determine if they are on the same host. Select "NFS client and server support for LOCALIO auxiliary protocol" in menuconfig to enable CONFIG_NFS_LOCALIO in the kernel config (both CONFIG_NFS_FS and CONFIG_NFSD must also be enabled).

Once an NFS client and server handshake as "local", the client will bypass the network RPC protocol for read, write and commit operations. Due to this XDR and RPC bypass, these operations will operate faster.

The LOCALIO auxiliary protocol's implementation, which uses the same connection as NFS traffic, follows the pattern established by the NFS ACL protocol extension.

The LOCALIO auxiliary protocol is needed to allow robust discovery of clients local to their servers. In a private implementation that preceded use of this LOCALIO protocol, a fragile sockaddr network address based match against all local network interfaces was attempted. But unlike the LOCALIO protocol, the sockaddr-based matching didn't handle use of iptables or containers.

The robust handshake between local client and server is just the beginning, the ultimate use case this locality makes possible is the client is able to open files and issue reads, writes and commits directly to the server without having to go over the network. The requirement is to perform these loopback NFS operations as efficiently as possible, this is particularly useful for container use cases (e.g. kubernetes) where it is possible to run an IO job local to the server.

The performance advantage realized from LOCALIO's ability to bypass using XDR and RPC for reads, writes and commits can be extreme, e.g.:

- **fio for 20 secs with directio, qd of 8, 16 libaio threads:**

  - With LOCALIO: 4K read:    IOPS=979k,  BW=3825MiB/s (4011MB/s)(74.7GiB/20002msec) 4K write:   IOPS=165k,  BW=646MiB/s  (678MB/s)(12.6GiB/20002msec) 128K read:  IOPS=402k,  BW=49.1GiB/s (52.7GB/s)(982GiB/20002msec) 128K write: IOPS=11.5k, BW=1433MiB/s (1503MB/s)(28.0GiB/20004msec)

  - Without LOCALIO: 4K read:    IOPS=79.2k, BW=309MiB/s  (324MB/s)(6188MiB/20003msec) 4K write:   IOPS=59.8k, BW=234MiB/s  (245MB/s)(4671MiB/20002msec) 128K read:  IOPS=33.9k, BW=4234MiB/s (4440MB/s)(82.7GiB/20004msec) 128K write: IOPS=11.5k, BW=1434MiB/s (1504MB/s)(28.0GiB/20011msec)

- **fio for 20 secs with directio, qd of 8, 1 libaio thread:**

  - With LOCALIO: 4K read:    IOPS=230k,  BW=898MiB/s  (941MB/s)(17.5GiB/20001msec) 4K write:   IOPS=22.6k, BW=88.3MiB/s (92.6MB/s)(1766MiB/20001msec) 128K read:  IOPS=38.8k, BW=4855MiB/s (5091MB/s)(94.8GiB/20001msec) 128K write: IOPS=11.4k, BW=1428MiB/s (1497MB/s)(27.9GiB/20001msec)

  - Without LOCALIO: 4K read:    IOPS=77.1k, BW=301MiB/s  (316MB/s)(6022MiB/20001msec) 4K write:   IOPS=32.8k, BW=128MiB/s  (135MB/s)(2566MiB/20001msec) 128K read:  IOPS=24.4k, BW=3050MiB/s (3198MB/s)(59.6GiB/20001msec) 128K write: IOPS=11.4k, BW=1430MiB/s (1500MB/s)(27.9GiB/20001msec)

<a id="rst-faq"></a>

## FAQ

1. What are the use cases for LOCALIO?

   - **a.** Workloads where the NFS client and server are on the same host realize improved IO performance. In particular, it is common when running containerised workloads for jobs to find themselves running on the same host as the knfsd server being used for storage.

2. What are the requirements for LOCALIO?

   - **a.** Bypass use of the network RPC protocol as much as possible. This includes bypassing XDR and RPC for open, read, write and commit operations.

   - **b.** Allow client and server to autonomously discover if they are running local to each other without making any assumptions about the local network topology.

   - **c.** Support the use of containers by being compatible with relevant namespaces (e.g. network, user, mount).

   - **d.** Support all versions of NFS. NFSv3 is of particular importance because it has wide enterprise usage and pNFS flexfiles makes use of it for the data path.

3. Why doesn’t LOCALIO just compare IP addresses or hostnames when deciding if the NFS client and server are co-located on the same host?

   Since one of the main use cases is containerised workloads, we cannot assume that IP addresses will be shared between the client and server. This sets up a requirement for a handshake protocol that needs to go over the same connection as the NFS traffic in order to identify that the client and the server really are running on the same host. The handshake uses a secret that is sent over the wire, and can be verified by both parties by comparing with a value stored in shared kernel memory if they are truly co-located.

4. Does LOCALIO improve pNFS flexfiles?

   Yes, LOCALIO complements pNFS flexfiles by allowing it to take advantage of NFS client and server locality.  Policy that initiates client IO as closely to the server where the data is stored naturally benefits from the data path optimization LOCALIO provides.

5. Why not develop a new pNFS layout to enable LOCALIO?

   A new pNFS layout could be developed, but doing so would put the onus on the server to somehow discover that the client is co-located when deciding to hand out the layout. There is value in a simpler approach (as provided by LOCALIO) that allows the NFS client to negotiate and leverage locality without requiring more elaborate modeling and discovery of such locality in a more centralized manner.

6. Why is having the client perform a server-side file OPEN, without using RPC, beneficial?  Is the benefit pNFS specific?

   Avoiding the use of XDR and RPC for file opens is beneficial to performance regardless of whether pNFS is used. Especially when dealing with small files its best to avoid going over the wire whenever possible, otherwise it could reduce or even negate the benefits of avoiding the wire for doing the small file I/O itself. Given LOCALIO's requirements the current approach of having the client perform a server-side file open, without using RPC, is ideal. If in the future requirements change then we can adapt accordingly.

7. Why is LOCALIO only supported with UNIX Authentication (AUTH_UNIX)?

   Strong authentication is usually tied to the connection itself. It works by establishing a context that is cached by the server, and that acts as the key for discovering the authorisation token, which can then be passed to rpc.mountd to complete the authentication process. On the other hand, in the case of AUTH_UNIX, the credential that was passed over the wire is used directly as the key in the upcall to rpc.mountd. This simplifies the authentication process, and so makes AUTH_UNIX easier to support.

8. How do export options that translate RPC user IDs behave for LOCALIO operations (eg. root_squash, all_squash)?

   Export options that translate user IDs are managed by nfsd_setuser() which is called by nfsd_setuser_and_check_port() which is called by \__fh_verify().  So they get handled exactly the same way for LOCALIO as they do for non-LOCALIO.

9. How does LOCALIO make certain that object lifetimes are managed properly given NFSD and NFS operate in different contexts?

   See the detailed "NFS Client and Server Interlock" section below.

<a id="rst-rpc"></a>

## RPC

The LOCALIO auxiliary RPC protocol consists of a single "UUID_IS_LOCAL" RPC method that allows the Linux NFS client to verify the local Linux NFS server can see the nonce (single-use UUID) the client generated and made available in nfs_common. This protocol isn't part of an IETF standard, nor does it need to be considering it is Linux-to-Linux auxiliary RPC protocol that amounts to an implementation detail.

The UUID_IS_LOCAL method encodes the client generated uuid_t in terms of the fixed UUID_SIZE (16 bytes). The fixed size opaque encode and decode XDR methods are used instead of the less efficient variable sized methods.

The RPC program number for the NFS_LOCALIO_PROGRAM is 400122 (as assigned by IANA, see [https://www.iana.org/assignments/rpc-program-numbers/](<https://www.iana.org/assignments/rpc-program-numbers/>) ): Linux Kernel Organization       400122  nfslocalio

The LOCALIO protocol spec in rpcgen syntax is:



```text
/* raw RFC 9562 UUID */
#define UUID_SIZE 16
typedef u8 uuid_t<UUID_SIZE>;

program NFS_LOCALIO_PROGRAM {
    version LOCALIO_V1 {
        void
            NULL(void) = 0;

        void
            UUID_IS_LOCAL(uuid_t) = 1;
    } = 1;
} = 400122;
```

LOCALIO uses the same transport connection as NFS traffic. As such, LOCALIO is not registered with rpcbind.

<a id="rst-nfs-common-and-client-server-handshake"></a>

## NFS Common and Client/Server Handshake

fs/nfs_common/nfslocalio.c provides interfaces that enable an NFS client to generate a nonce (single-use UUID) and associated short-lived nfs_uuid_t struct, register it with nfs_common for subsequent lookup and verification by the NFS server and if matched the NFS server populates members in the nfs_uuid_t struct. The NFS client then uses nfs_common to transfer the nfs_uuid_t from its nfs_uuids to the nn-&gt;nfsd_serv clients_list from the nfs_common's uuids_list.  See: fs/nfs/localio.c:nfs_local_probe()

nfs_common's nfs_uuids list is the basis for LOCALIO enablement, as such it has members that point to nfsd memory for direct use by the client (e.g. 'net' is the server's network namespace, through it the client can access nn-&gt;nfsd_serv with proper rcu read access). It is this client and server synchronization that enables advanced usage and lifetime of objects to span from the host kernel's nfsd to per-container knfsd instances that are connected to nfs client's running on the same local host.

<a id="rst-nfs-client-and-server-interlock"></a>

## NFS Client and Server Interlock

LOCALIO provides the nfs_uuid_t object and associated interfaces to allow proper network namespace (net-ns) and NFSD object refcounting.

LOCALIO required the introduction and use of NFSD's percpu nfsd_net_ref to interlock nfsd_shutdown_net() and nfsd_open_local_fh(), to ensure each net-ns is not destroyed while in use by nfsd_open_local_fh(), and warrants a more detailed explanation:

> nfsd_open_local_fh() uses nfsd_net_try_get() before opening its nfsd_file handle and then the caller (NFS client) must drop the reference for the nfsd_file and associated net-ns using nfsd_file_put_local() once it has completed its IO.
>
> This interlock working relies heavily on nfsd_open_local_fh() being afforded the ability to safely deal with the possibility that the NFSD's net-ns (and nfsd_net by association) may have been destroyed by nfsd_destroy_serv() via nfsd_shutdown_net().

This interlock of the NFS client and server has been verified to fix an easy to hit crash that would occur if an NFSD instance running in a container, with a LOCALIO client mounted, is shutdown. Upon restart of the container and associated NFSD, the client would go on to crash due to NULL pointer dereference that occurred due to the LOCALIO client's attempting to nfsd_open_local_fh() without having a proper reference on NFSD's net-ns.

<a id="rst-nfs-client-issues-io-instead-of-server"></a>

## NFS Client issues IO instead of Server

Because LOCALIO is focused on protocol bypass to achieve improved IO performance, alternatives to the traditional NFS wire protocol (SUNRPC with XDR) must be provided to access the backing filesystem.

See fs/nfs/localio.c:nfs_local_open_fh() and fs/nfsd/localio.c:nfsd_open_local_fh() for the interface that makes focused use of select nfs server objects to allow a client local to a server to open a file pointer without needing to go over the network.

The client's fs/nfs/localio.c:nfs_local_open_fh() will call into the server's fs/nfsd/localio.c:nfsd_open_local_fh() and carefully access both the associated nfsd network namespace and nn-&gt;nfsd_serv in terms of RCU. If nfsd_open_local_fh() finds that the client no longer sees valid nfsd objects (be it struct net or nn-&gt;nfsd_serv) it returns -ENXIO to nfs_local_open_fh() and the client will try to reestablish the LOCALIO resources needed by calling nfs_local_probe() again. This recovery is needed if/when an nfsd instance running in a container were to reboot while a LOCALIO client is connected to it.

Once the client has an open nfsd_file pointer it will issue reads, writes and commits directly to the underlying local filesystem (normally done by the nfs server). As such, for these operations, the NFS client is issuing IO to the underlying local filesystem that it is sharing with the NFS server. See: fs/nfs/localio.c:nfs_local_doio() and fs/nfs/localio.c:nfs_local_commit().

With normal NFS that makes use of RPC to issue IO to the server, if an application uses O_DIRECT the NFS client will bypass the pagecache but the NFS server will not. The NFS server's use of buffered IO affords applications to be less precise with their alignment when issuing IO to the NFS client. But if all applications properly align their IO, LOCALIO can be configured to use end-to-end O_DIRECT semantics from the NFS client to the underlying local filesystem, that it is sharing with the NFS server, by setting the 'localio_O_DIRECT_semantics' nfs module parameter to Y, e.g.:

> echo Y &gt; /sys/module/nfs/parameters/localio_O_DIRECT_semantics

Once enabled, it will cause LOCALIO to use end-to-end O_DIRECT semantics (but again, this may cause IO to fail if applications do not properly align their IO).

<a id="rst-security"></a>

## Security

LOCALIO is only supported when UNIX-style authentication (AUTH_UNIX, aka AUTH_SYS) is used.

Care is taken to ensure the same NFS security mechanisms are used (authentication, etc) regardless of whether LOCALIO or regular NFS access is used. The auth_domain established as part of the traditional NFS client access to the NFS server is also used for LOCALIO.

Relative to containers, LOCALIO gives the client access to the network namespace the server has. This is required to allow the client to access the server's per-namespace nfsd_net struct. With traditional NFS, the client is afforded this same level of access (albeit in terms of the NFS protocol via SUNRPC). No other namespaces (user, mount, etc) have been altered or purposely extended from the server to the client.

<a id="rst-module-parameters"></a>

## Module Parameters

/sys/module/nfs/parameters/localio_enabled (bool) controls if LOCALIO is enabled, defaults to Y. If client and server are local but 'localio_enabled' is set to N then LOCALIO will not be used.

/sys/module/nfs/parameters/localio_O_DIRECT_semantics (bool) controls if O_DIRECT extends down to the underlying filesystem, defaults to N. Application IO must be logical blocksize aligned, otherwise O_DIRECT will fail.

/sys/module/nfsv3/parameters/nfs3_localio_probe_throttle (uint) controls if NFSv3 read and write IOs will trigger (re)enabling of LOCALIO every N (nfs3_localio_probe_throttle) IOs, defaults to 0 (disabled). Must be power-of-2, admin keeps all the pieces if they misconfigure (too low a value or non-power-of-2).

<a id="rst-testing"></a>

## Testing

The LOCALIO auxiliary protocol and associated NFS LOCALIO read, write and commit access have proven stable against various test scenarios:

- Client and server both on the same host.

- All permutations of client and server support enablement for both local and remote client and server.

- Testing against NFS storage products that don't support the LOCALIO protocol was also performed.

- Client on host, server within a container (for both v3 and v4.2). The container testing was in terms of podman managed containers and includes successful container stop/restart scenario.

- Formalizing these test scenarios in terms of existing test infrastructure is on-going. Initial regular coverage is provided in terms of ktest running xfstests against a LOCALIO-enabled NFS loopback mount configuration, and includes lockdep and KASAN coverage, see: [https://evilpiepirate.org/\~testdashboard/ci?user=snitzer&amp;branch=snitm-nfs-next](<https://evilpiepirate.org/~testdashboard/ci?user=snitzer&branch=snitm-nfs-next>) [https://github.com/koverstreet/ktest](<https://github.com/koverstreet/ktest>)

- Various kdevops testing (in terms of "Chuck's BuildBot") has been performed to regularly verify the LOCALIO changes haven't caused any regressions to non-LOCALIO NFS use cases.

- All of Hammerspace's various sanity tests pass with LOCALIO enabled (this includes numerous pNFS and flexfiles tests).

---

# NFSv4.1 Server Implementation

_Peios Kernel / Internals / Filesystems / nfs_

> Server support for minorversion 1 can be controlled using the /proc/fs/nfsd/versions control file. The string output returned by reading this file will contain either "+4.1" or "-4.1" correspondingly.

<a id="rst-nfsv4-1-server-implementation"></a>

Server support for minorversion 1 can be controlled using the /proc/fs/nfsd/versions control file.  The string output returned by reading this file will contain either "+4.1" or "-4.1" correspondingly.

Currently, server support for minorversion 1 is enabled by default. It can be disabled at run time by writing the string "-4.1" to the /proc/fs/nfsd/versions control file.  Note that to write this control file, the nfsd service must be taken down.  You can use rpc.nfsd for this; see rpc.nfsd(8).

(Warning: older servers will interpret "+4.1" and "-4.1" as "+4" and "-4", respectively.  Therefore, code meant to work on both new and old kernels must turn 4.1 on or off *before* turning support for version 4 on or off; rpc.nfsd does this correctly.)

The NFSv4 minorversion 1 (NFSv4.1) implementation in nfsd is based on RFC 5661.

From the many new features in NFSv4.1 the current implementation focuses on the mandatory-to-implement NFSv4.1 Sessions, providing "exactly once" semantics and better control and throttling of the resources allocated for each client.

The table below, taken from the NFSv4.1 document, lists the operations that are mandatory to implement (REQ), optional (OPT), and NFSv4.0 operations that are required not to implement (MNI) in minor version 1.  The first column indicates the operations that are not supported yet by the linux server implementation.

The OPTIONAL features identified and their abbreviations are as follows:

- **pNFS**      Parallel NFS

- **FDELG**     File Delegations

- **DDELG**     Directory Delegations

The following abbreviations indicate the linux server implementation status.

- **I** Implemented NFSv4.1 operations.

- **NS**        Not Supported.

- **NS\***      Unimplemented optional feature.

<a id="rst-operations"></a>

## Operations


<table>
<thead>
<tr>
<th>


Implementation status

</th>
<th>


Operation

</th>
<th>


REQ,REC, OPT or NMI

</th>
<th>


Feature (REQ, REC or OPT)

</th>
<th>


Definition

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>


ACCESS

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.1

</td>
</tr>
<tr>
<td>


I

</td>
<td>


BACKCHANNEL_CTL

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.33

</td>
</tr>
<tr>
<td>


I

</td>
<td>


BIND_CONN_TO_SESSION

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.34

</td>
</tr>
<tr>
<td>




</td>
<td>


CLOSE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.2

</td>
</tr>
<tr>
<td>




</td>
<td>


COMMIT

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.3

</td>
</tr>
<tr>
<td>




</td>
<td>


CREATE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.4

</td>
</tr>
<tr>
<td>


I

</td>
<td>


CREATE_SESSION

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.36

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


DELEGPURGE

</td>
<td>


OPT

</td>
<td>


FDELG (REQ)

</td>
<td>


Section 18.5

</td>
</tr>
<tr>
<td>




</td>
<td>


DELEGRETURN

</td>
<td>


OPT

</td>
<td>


FDELG,

</td>
<td>


Section 18.6

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


DDELG, pNFS

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
<tr>
<td>


I

</td>
<td>


DESTROY_CLIENTID

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.50

</td>
</tr>
<tr>
<td>


I

</td>
<td>


DESTROY_SESSION

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.37

</td>
</tr>
<tr>
<td>


I

</td>
<td>


EXCHANGE_ID

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.35

</td>
</tr>
<tr>
<td>


I

</td>
<td>


FREE_STATEID

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.38

</td>
</tr>
<tr>
<td>




</td>
<td>


GETATTR

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.7

</td>
</tr>
<tr>
<td>


I

</td>
<td>


GETDEVICEINFO

</td>
<td>


OPT

</td>
<td>


pNFS (REQ)

</td>
<td>


Section 18.40

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


GETDEVICELIST

</td>
<td>


OPT

</td>
<td>


pNFS (OPT)

</td>
<td>


Section 18.41

</td>
</tr>
<tr>
<td>




</td>
<td>


GETFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.8

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


GET_DIR_DELEGATION

</td>
<td>


OPT

</td>
<td>


DDELG (REQ)

</td>
<td>


Section 18.39

</td>
</tr>
<tr>
<td>


I

</td>
<td>


LAYOUTCOMMIT

</td>
<td>


OPT

</td>
<td>


pNFS (REQ)

</td>
<td>


Section 18.42

</td>
</tr>
<tr>
<td>


I

</td>
<td>


LAYOUTGET

</td>
<td>


OPT

</td>
<td>


pNFS (REQ)

</td>
<td>


Section 18.43

</td>
</tr>
<tr>
<td>


I

</td>
<td>


LAYOUTRETURN

</td>
<td>


OPT

</td>
<td>


pNFS (REQ)

</td>
<td>


Section 18.44

</td>
</tr>
<tr>
<td>




</td>
<td>


LINK

</td>
<td>


OPT

</td>
<td>




</td>
<td>


Section 18.9

</td>
</tr>
<tr>
<td>




</td>
<td>


LOCK

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.10

</td>
</tr>
<tr>
<td>




</td>
<td>


LOCKT

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.11

</td>
</tr>
<tr>
<td>




</td>
<td>


LOCKU

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.12

</td>
</tr>
<tr>
<td>




</td>
<td>


LOOKUP

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.13

</td>
</tr>
<tr>
<td>




</td>
<td>


LOOKUPP

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.14

</td>
</tr>
<tr>
<td>




</td>
<td>


NVERIFY

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.15

</td>
</tr>
<tr>
<td>




</td>
<td>


OPEN

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.16

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


OPENATTR

</td>
<td>


OPT

</td>
<td>




</td>
<td>


Section 18.17

</td>
</tr>
<tr>
<td>




</td>
<td>


OPEN_CONFIRM

</td>
<td>


MNI

</td>
<td>




</td>
<td>


N/A

</td>
</tr>
<tr>
<td>




</td>
<td>


OPEN_DOWNGRADE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.18

</td>
</tr>
<tr>
<td>




</td>
<td>


PUTFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.19

</td>
</tr>
<tr>
<td>




</td>
<td>


PUTPUBFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.20

</td>
</tr>
<tr>
<td>




</td>
<td>


PUTROOTFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.21

</td>
</tr>
<tr>
<td>




</td>
<td>


READ

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.22

</td>
</tr>
<tr>
<td>




</td>
<td>


READDIR

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.23

</td>
</tr>
<tr>
<td>




</td>
<td>


READLINK

</td>
<td>


OPT

</td>
<td>




</td>
<td>


Section 18.24

</td>
</tr>
<tr>
<td>




</td>
<td>


RECLAIM_COMPLETE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.51

</td>
</tr>
<tr>
<td>




</td>
<td>


RELEASE_LOCKOWNER

</td>
<td>


MNI

</td>
<td>




</td>
<td>


N/A

</td>
</tr>
<tr>
<td>




</td>
<td>


REMOVE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.25

</td>
</tr>
<tr>
<td>




</td>
<td>


RENAME

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.26

</td>
</tr>
<tr>
<td>




</td>
<td>


RENEW

</td>
<td>


MNI

</td>
<td>




</td>
<td>


N/A

</td>
</tr>
<tr>
<td>




</td>
<td>


RESTOREFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.27

</td>
</tr>
<tr>
<td>




</td>
<td>


SAVEFH

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.28

</td>
</tr>
<tr>
<td>




</td>
<td>


SECINFO

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.29

</td>
</tr>
<tr>
<td>


I

</td>
<td>


SECINFO_NO_NAME

</td>
<td>


REC

</td>
<td>


pNFS files

</td>
<td>


Section 18.45,

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


layout (REQ)

</td>
<td>


Section 13.12

</td>
</tr>
<tr>
<td>


I

</td>
<td>


SEQUENCE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.46

</td>
</tr>
<tr>
<td>




</td>
<td>


SETATTR

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.30

</td>
</tr>
<tr>
<td>




</td>
<td>


SETCLIENTID

</td>
<td>


MNI

</td>
<td>




</td>
<td>


N/A

</td>
</tr>
<tr>
<td>




</td>
<td>


SETCLIENTID_CONFIRM

</td>
<td>


MNI

</td>
<td>




</td>
<td>


N/A

</td>
</tr>
<tr>
<td>


NS

</td>
<td>


SET_SSV

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.47

</td>
</tr>
<tr>
<td>


I

</td>
<td>


TEST_STATEID

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.48

</td>
</tr>
<tr>
<td>




</td>
<td>


VERIFY

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.31

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


WANT_DELEGATION

</td>
<td>


OPT

</td>
<td>


FDELG (OPT)

</td>
<td>


Section 18.49

</td>
</tr>
<tr>
<td>




</td>
<td>


WRITE

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 18.32

</td>
</tr>
</tbody>
</table>

<a id="rst-callback-operations"></a>

## Callback Operations


<table>
<thead>
<tr>
<th>


Implementation status

</th>
<th>


Operation

</th>
<th>


REQ,REC, OPT or NMI

</th>
<th>


Feature (REQ, REC or OPT)

</th>
<th>


Definition

</th>
</tr>
</thead>
<tbody>
<tr>
<td>




</td>
<td>


CB_GETATTR

</td>
<td>


OPT

</td>
<td>


FDELG (REQ)

</td>
<td>


Section 20.1

</td>
</tr>
<tr>
<td>


I

</td>
<td>


CB_LAYOUTRECALL

</td>
<td>


OPT

</td>
<td>


pNFS (REQ)

</td>
<td>


Section 20.3

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_NOTIFY

</td>
<td>


OPT

</td>
<td>


DDELG (REQ)

</td>
<td>


Section 20.4

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_NOTIFY_DEVICEID

</td>
<td>


OPT

</td>
<td>


pNFS (OPT)

</td>
<td>


Section 20.12

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_NOTIFY_LOCK

</td>
<td>


OPT

</td>
<td>




</td>
<td>


Section 20.11

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_PUSH_DELEG

</td>
<td>


OPT

</td>
<td>


FDELG (OPT)

</td>
<td>


Section 20.5

</td>
</tr>
<tr>
<td>




</td>
<td>


CB_RECALL

</td>
<td>


OPT

</td>
<td>


FDELG,

</td>
<td>


Section 20.2

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


DDELG, pNFS

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_RECALL_ANY

</td>
<td>


OPT

</td>
<td>


FDELG,

</td>
<td>


Section 20.6

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


DDELG, pNFS

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
<tr>
<td>


NS

</td>
<td>


CB_RECALL_SLOT

</td>
<td>


REQ

</td>
<td>




</td>
<td>


Section 20.8

</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_RECALLABLE_OBJ_AVAIL

</td>
<td>


OPT

</td>
<td>


DDELG, pNFS

</td>
<td>


Section 20.7

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
<tr>
<td>


I

</td>
<td>


CB_SEQUENCE

</td>
<td>


OPT

</td>
<td>


FDELG,

</td>
<td>


Section 20.9

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


DDELG, pNFS

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
<tr>
<td>


NS\*

</td>
<td>


CB_WANTS_CANCELLED

</td>
<td>


OPT

</td>
<td>


FDELG,

</td>
<td>


Section 20.10

</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


DDELG, pNFS

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>




</td>
<td>




</td>
<td>


(REQ)

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-implementation-notes"></a>

## Implementation notes:

- **SSV:**

  The spec claims this is mandatory, but we don't actually know of any implementations, so we're ignoring it for now.  The server returns NFS4ERR_ENCR_ALG_UNSUPP on EXCHANGE_ID, which should be future-proof.

- **GSS on the backchannel:**

  Again, theoretically required but not widely implemented (in particular, the current Linux client doesn't request it).  We return NFS4ERR_ENCR_ALG_UNSUPP on CREATE_SESSION.

- **DELEGPURGE:**

  mandatory only for servers that support CLAIM_DELEGATE_PREV and/or CLAIM_DELEG_PREV_FH (which allows clients to keep delegations that persist across client reboots).  Thus we need not implement this for now.

- **EXCHANGE_ID:**

  implementation ids are ignored

- **CREATE_SESSION:**

  backchannel attributes are ignored

- **SEQUENCE:**

  no support for dynamic slot table renegotiation (optional)

- **Nonstandard compound limitations:**

  No support for a sessions fore channel RPC compound that requires both a ca_maxrequestsize request and a ca_maxresponsesize reply, so we may fail to live up to the promise we made in CREATE_SESSION fore channel negotiation.

See also [http://wiki.linux-nfs.org/wiki/index.php/Server_4.0_and_4.1_issues](<http://wiki.linux-nfs.org/wiki/index.php/Server_4.0_and_4.1_issues>).

---

# NFSD IO MODES

_Peios Kernel / Internals / Filesystems / nfs_

> NFSD has historically always used buffered IO when servicing READ and WRITE operations. BUFFERED is NFSD's default IO mode, but it is possible to override that default to use either DONTCACHE or DIRECT IO modes.

<a id="rst-nfsd-io-modes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

NFSD has historically always used buffered IO when servicing READ and WRITE operations. BUFFERED is NFSD's default IO mode, but it is possible to override that default to use either DONTCACHE or DIRECT IO modes.

Experimental NFSD debugfs interfaces are available to allow the NFSD IO mode used for READ and WRITE to be configured independently. See both:

- /sys/kernel/debug/nfsd/io_cache_read

- /sys/kernel/debug/nfsd/io_cache_write

The default value for both io_cache_read and io_cache_write reflects NFSD's default IO mode (which is NFSD_IO_BUFFERED=0).

Based on the configured settings, NFSD's IO will either be:

- cached using page cache (NFSD_IO_BUFFERED=0)

- cached but removed from page cache on completion (NFSD_IO_DONTCACHE=1)

- not cached stable_how=NFS_UNSTABLE (NFSD_IO_DIRECT=2)

To set an NFSD IO mode, write a supported value (0 - 2) to the corresponding IO operation's debugfs interface, e.g.:



```text
echo 2 > /sys/kernel/debug/nfsd/io_cache_read
echo 2 > /sys/kernel/debug/nfsd/io_cache_write
```

To check which IO mode NFSD is using for READ or WRITE, simply read the corresponding IO operation's debugfs interface, e.g.:



```text
cat /sys/kernel/debug/nfsd/io_cache_read
cat /sys/kernel/debug/nfsd/io_cache_write
```

If you experiment with NFSD's IO modes on a recent kernel and have interesting results, please report them to [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>)

<a id="rst-nfsd-dontcache"></a>

## NFSD DONTCACHE

DONTCACHE offers a hybrid approach to servicing IO that aims to offer the benefits of using DIRECT IO without any of the strict alignment requirements that DIRECT IO imposes. To achieve this buffered IO is used but the IO is flagged to "drop behind" (meaning associated pages are dropped from the page cache) when IO completes.

DONTCACHE aims to avoid what has proven to be a fairly significant limition of Linux's memory management subsystem if/when large amounts of data is infrequently accessed (e.g. read once \_or\_ written once but not read until much later). Such use-cases are particularly problematic because the page cache will eventually become a bottleneck to servicing new IO requests.

For more context on DONTCACHE, please see these Linux commit headers:

- Overview:  9ad6344568cc3 ("mm/filemap: change filemap_create_folio() to take a struct kiocb")

- for READ:  8026e49bff9b1 ("mm/filemap: add read support for RWF_DONTCACHE")

- for WRITE: 974c5e6139db3 ("xfs: flag as supporting FOP_DONTCACHE")

NFSD_IO_DONTCACHE will fall back to NFSD_IO_BUFFERED if the underlying filesystem doesn't indicate support by setting FOP_DONTCACHE.

<a id="rst-nfsd-direct"></a>

## NFSD DIRECT

DIRECT IO doesn't make use of the page cache, as such it is able to avoid the Linux memory management's page reclaim scalability problems without resorting to the hybrid use of page cache that DONTCACHE does.

Some workloads benefit from NFSD avoiding the page cache, particularly those with a working set that is significantly larger than available system memory. The pathological worst-case workload that NFSD DIRECT has proven to help most is: NFS client issuing large sequential IO to a file that is 2-3 times larger than the NFS server's available system memory. The reason for such improvement is NFSD DIRECT eliminates a lot of work that the memory management subsystem would otherwise be required to perform (e.g. page allocation, dirty writeback, page reclaim). When using NFSD DIRECT, kswapd and kcompactd are no longer commanding CPU time trying to find adequate free pages so that forward IO progress can be made.

The performance win associated with using NFSD DIRECT was previously discussed on linux-nfs, see: [https://lore.kernel.org/linux-nfs/aEslwqa9iMeZjjlV@kernel.org/](<https://lore.kernel.org/linux-nfs/aEslwqa9iMeZjjlV@kernel.org/>)

But in summary:

- NFSD DIRECT can significantly reduce memory requirements

- NFSD DIRECT can reduce CPU load by avoiding costly page reclaim work

- NFSD DIRECT can offer more deterministic IO performance

As always, your mileage may vary and so it is important to carefully consider if/when it is beneficial to make use of NFSD DIRECT. When assessing comparative performance of your workload please be sure to log relevant performance metrics during testing (e.g. memory usage, cpu usage, IO performance). Using perf to collect perf data that may be used to generate a "flamegraph" for work Linux must perform on behalf of your test is a really meaningful way to compare the relative health of the system and how switching NFSD's IO mode changes what is observed.

If NFSD_IO_DIRECT is specified by writing 2 (or 3 and 4 for WRITE) to NFSD's debugfs interfaces, ideally the IO will be aligned relative to the underlying block device's logical_block_size. Also the memory buffer used to store the READ or WRITE payload must be aligned relative to the underlying block device's dma_alignment.

But NFSD DIRECT does handle misaligned IO in terms of O_DIRECT as best it can:

- **Misaligned READ:**

  If NFSD_IO_DIRECT is used, expand any misaligned READ to the next DIO-aligned block (on either end of the READ). The expanded READ is verified to have proper offset/len (logical_block_size) and dma_alignment checking.

- **Misaligned WRITE:**

  If NFSD_IO_DIRECT is used, split any misaligned WRITE into a start, middle and end as needed. The large middle segment is DIO-aligned and the start and/or end are misaligned. Buffered IO is used for the misaligned segments and O_DIRECT is used for the middle DIO-aligned segment. DONTCACHE buffered IO is \_not\_ used for the misaligned segments because using normal buffered IO offers significant RMW performance benefit when handling streaming misaligned WRITEs.

- **Tracing:**

  The nfsd_read_direct trace event shows how NFSD expands any misaligned READ to the next DIO-aligned block (on either end of the original READ, as needed).

  This combination of trace events is useful for READs:



  ```text
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_read_vector/enable
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_read_direct/enable
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_read_io_done/enable
  echo 1 > /sys/kernel/tracing/events/xfs/xfs_file_direct_read/enable
  ```

  The nfsd_write_direct trace event shows how NFSD splits a given misaligned WRITE into a DIO-aligned middle segment.

  This combination of trace events is useful for WRITEs:



  ```text
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_write_opened/enable
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_write_direct/enable
  echo 1 > /sys/kernel/tracing/events/nfsd/nfsd_write_io_done/enable
  echo 1 > /sys/kernel/tracing/events/xfs/xfs_file_direct_write/enable
  ```

---

# NFSD Maintainer Entry Profile

_Peios Kernel / Internals / Filesystems / nfs_

> A Maintainer Entry Profile supplements the top-level process documents (found in Documentation/process/) with customs that are specific to a subsystem and its maintainers. A contributor may use this document to set their expectations and…

<a id="rst-nfsd-maintainer-entry-profile"></a>

A Maintainer Entry Profile supplements the top-level process documents (found in Documentation/process/) with customs that are specific to a subsystem and its maintainers. A contributor may use this document to set their expectations and avoid common mistakes. A maintainer may use these profiles to look across subsystems for opportunities to converge on best common practices.

<a id="rst-overview"></a>

## Overview

The Network File System (NFS) is a standardized family of network protocols that enable access to files across a set of network- connected peer hosts. Applications on NFS clients access files that reside on file systems that are shared by NFS servers. A single network peer can act as both an NFS client and an NFS server.

NFSD refers to the NFS server implementation included in the Linux kernel. An in-kernel NFS server has fast access to files stored in file systems local to that server. NFSD can share files stored on most of the file system types native to Linux, including xfs, ext4, btrfs, and tmpfs.

<a id="rst-mailing-list"></a>

## Mailing list

The [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>) mailing list is a public list. Its purpose is to enable collaboration among developers working on the Linux NFS stack, both client and server. It is not a place for conversations that are not related directly to the Linux NFS stack.

The linux-nfs mailing list is archived on [lore.kernel.org](<https://lore.kernel.org/linux-nfs/>)<a id="rst-lore-kernel-org"></a>.

The Linux NFS community does not have any chat room.

<a id="rst-reporting-bugs"></a>

## Reporting bugs

If you experience an NFSD-related bug on a distribution-built kernel, please start by working with your Linux distributor.

Bug reports against upstream Linux code bases are welcome on the [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>) mailing list, where some active triage can be done. NFSD bugs may also be reported in the Linux kernel community's bugzilla at:

> [https://bugzilla.kernel.org](<https://bugzilla.kernel.org>)

Please file NFSD-related bugs under the "Filesystems/NFSD" component. In general, including as much detail as possible is a good start, including pertinent system log messages from both the client and server.

User space software related to NFSD, such as mountd or the exportfs command, is contained in the nfs-utils package. Report problems with those components to [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>). You might be directed to move the report to a specific bug tracker.

<a id="rst-contributor-s-guide"></a>

## Contributor's Guide

<a id="rst-standards-compliance"></a>

### Standards compliance

The priority is for NFSD to interoperate fully with the Linux NFS client. We also test against other popular NFS client implementa- tions regularly at NFS bake-a-thon events (also known as plug- fests). Non-Linux NFS clients are not part of upstream NFSD CI/CD.

The NFSD community strives to provide an NFS server implementation that interoperates with all standards-compliant NFS client implementations. This is done by staying as close as is sensible to the normative mandates in the IETF's published NFS, RPC, and GSS-API standards.

It is always useful to reference an RFC and section number in a code comment where behavior deviates from the standard (and even when the behavior is compliant but the implementation is obfuscatory).

On the rare occasion when a deviation from standard-mandated behavior is needed, brief documentation of the use case or deficiencies in the standard is a required part of in-code documentation.

Care must always be taken to avoid leaking local error codes (ie, errnos) to clients of NFSD. A proper NFS status code is always required in NFS protocol replies.

<a id="rst-nfsd-administrative-interfaces"></a>

### NFSD administrative interfaces

NFSD administrative interfaces include:

- an NFSD or SUNRPC module parameter

- export options in /etc/exports

- files under /proc/fs/nfsd/ or /proc/sys/sunrpc/

- the NFSD netlink protocol

Frequently, a request is made to introduce or modify one of NFSD's traditional administrative interfaces. Certainly it is technically easy to introduce a new administrative setting. However, there are good reasons why the NFSD maintainers prefer to leave that as a last resort:

- As with any API, administrative interfaces are difficult to get right.

- Once they are documented and have a legacy of use, administrative interfaces become difficult to modify or remove.

- Every new administrative setting multiplies the NFSD test matrix.

- The cost of one administrative interface is incremental, but costs add up across all of the existing interfaces.

It is often better for everyone if effort is made up front to understanding the underlying requirement of the new setting, and then trying to make it tune itself (or to become otherwise unnecessary).

If a new setting is indeed necessary, first consider adding it to the NFSD netlink protocol. Or if it doesn't need to be a reliable long term user space feature, it can be added to NFSD's menagerie of experimental settings which reside under /sys/kernel/debug/nfsd/ .

<a id="rst-field-observability"></a>

### Field observability

NFSD employs several different mechanisms for observing operation, including counters, printks, WARNings, and static trace points. Each have their strengths and weaknesses. Contributors should select the most appropriate tool for their task.

- BUG must be avoided if at all possible, as it will frequently result in a full system crash.

- WARN is appropriate only when a full stack trace is useful.

- printk can show detailed information. These must not be used in code paths where they can be triggered repeatedly by remote users.

- dprintk can show detailed information, but can be enabled only in pre-set groups. The overhead of emitting output makes dprintk inappropriate for frequent operations like I/O.

- Counters are always on, but provide little information about individual events other than how frequently they occur.

- static trace points can be enabled individually or in groups (via a glob). These are generally low overhead, and thus are favored for use in hot paths.

- dynamic tracing, such as kprobes or eBPF, are quite flexible but cannot be used in certain environments (eg, full kernel lock- down).

<a id="rst-testing"></a>

### Testing

The kdevops project

> [https://github.com/linux-kdevops/kdevops](<https://github.com/linux-kdevops/kdevops>)

contains several NFS-specific workflows, as well as the community standard fstests suite. These workflows are based on open source testing tools such as ltp and fio. Contributors are encouraged to use these tools without kdevops, or contributors should install and use kdevops themselves to verify their patches before submission.

<a id="rst-coding-style"></a>

### Coding style

Follow the coding style preferences described in

> [Documentation/process/coding-style.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/coding-style.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)

with the following exceptions:

- Add new local variables to a function in reverse Christmas tree order

- Use the kdoc comment style for + non-static functions + static inline functions + static functions that are callbacks/virtual functions

- All new function names start with `nfsd_` for non-NFS-version- specific functions.

- New function names that are specific to NFSv2 or NFSv3, or are used by all minor versions of NFSv4, use `nfsdN_` where N is the version.

- New function names specific to an NFSv4 minor version can be named with `nfsd4M_` where M is the minor version.

<a id="rst-patch-preparation"></a>

### Patch preparation

Read and follow all guidelines in

> [Documentation/process/submitting-patches.rst](/kernel/development/process/submitting-patches.md)

Use tagging to identify all patch authors. However, reviewers and testers should be added by replying to the email patch submission. Email is extensively used in order to publicly archive review and testing attributions. These tags are automatically inserted into your patches when they are applied.

The code in the body of the diff already shows /what/ is being changed. Thus it is not necessary to repeat that in the patch description. Instead, the description should contain one or more of:

- A brief problem statement ("what is this patch trying to fix?") with a root-cause analysis.

- End-user visible symptoms or items that a support engineer might use to search for the patch, like stack traces.

- A brief explanation of why the patch is the best way to address the problem.

- Any context that reviewers might need to understand the changes made by the patch.

- Any relevant benchmarking results, and/or functional test results.

As detailed in [Documentation/process/submitting-patches.rst](/kernel/development/process/submitting-patches.md), identify the point in history that the issue being addressed was introduced by using a Fixes: tag.

Mention in the patch description if that point in history cannot be determined -- that is, no Fixes: tag can be provided. In this case, please make it clear to maintainers whether an LTS backport is needed even though there is no Fixes: tag.

The NFSD maintainers prefer to add stable tagging themselves, after public discussion in response to the patch submission. Contributors may suggest stable tagging, but be aware that many version management tools add such stable Cc's when you post your patches. Don't add "Cc: stable" unless you are absolutely sure the patch needs to go to stable during the initial submission process.

<a id="rst-patch-submission"></a>

### Patch submission

Patches to NFSD are submitted via the kernel's email-based review process that is common to most other kernel subsystems.

Just before each submission, rebase your patch or series on the nfsd-testing branch at

> [https://git.kernel.org/pub/scm/linux/kernel/git/cel/linux.git](<https://git.kernel.org/pub/scm/linux/kernel/git/cel/linux.git>)

The NFSD subsystem is maintained separately from the Linux in-kernel NFS client. The NFSD maintainers do not normally take submissions for client changes, nor can they respond authoritatively to bug reports or feature requests for NFS client code.

This means that contributors might be asked to resubmit patches if they were emailed to the incorrect set of maintainers and reviewers. This is not a rejection, but simply a correction of the submission process.

When in doubt, consult the NFSD entry in the MAINTAINERS file to see which files and directories fall under the NFSD subsystem.

The proper set of email addresses for NFSD patches are:

To: the NFSD maintainers and reviewers listed in MAINTAINERS Cc: [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>) and optionally linux-kernel@

If there are other subsystems involved in the patches (for example MM or RDMA) their primary mailing list address can be included in the Cc: field. Other contributors and interested parties may be included there as well.

In general we prefer that contributors use common patch email tools such as "git send-email" or "stg email format/send", which tend to get the details right without a lot of fuss.

A series consisting of a single patch is not required to have a cover letter. However, a cover letter can be included if there is substantial context that is not appropriate to include in the patch description.

Please note that, with an e-mail based submission process, series cover letters are not part of the work that is committed to the kernel source code base or its commit history. Therefore always try to keep pertinent information in the patch descriptions.

Design documentation is welcome, but as cover letters are not preserved, a perhaps better option is to include a patch that adds such documentation under Documentation/filesystems/nfs/.

Reviewers will ask about test coverage and what use cases the patches are expected to address. Please be prepared to answer these questions.

Review comments from maintainers might be politely stated, but in general, these are not optional to address when they are actionable. If necessary, the maintainers retain the right to not apply patches when contributors refuse to address reasonable requests.

Post changes to kernel source code and user space source code as separate series. You can connect the two series with comments in your cover letters.

Generally the NFSD maintainers ask for a reposts even for simple modifications in order to publicly archive the request and the resulting repost before it is pulled into the NFSD trees. This also enables us to rebuild a patch series quickly without missing changes that might have been discussed via email.

Avoid frequently reposting large series with only small changes. As a rule of thumb, posting substantial changes more than once a week will result in reviewer overload.

Remember, there are only a handful of subsystem maintainers and reviewers, but potentially many sources of contributions. The maintainers and reviewers, therefore, are always the less scalable resource. Be kind to your friendly neighborhood maintainer.

<a id="rst-patch-acceptance"></a>

### Patch Acceptance

There isn't a formal review process for NFSD, but we like to see at least two Reviewed-by: notices for patches that are more than simple clean-ups. Reviews are done in public on [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>) and are archived on lore.kernel.org.

Currently the NFSD patch queues are maintained in branches here:

> [https://git.kernel.org/pub/scm/linux/kernel/git/cel/linux.git](<https://git.kernel.org/pub/scm/linux/kernel/git/cel/linux.git>)

The NFSD maintainers apply patches initially to the nfsd-testing branch, which is always open to new submissions. Patches can be applied while review is ongoing. nfsd-testing is a topic branch, so it can change frequently, it will be rebased, and your patch might get dropped if there is a problem with it.

Generally a script-generated "thank you" email will indicate when your patch has been added to the nfsd-testing branch. You can track the progress of your patch using the linux-nfs patchworks instance:

> [https://patchwork.kernel.org/project/linux-nfs/list/](<https://patchwork.kernel.org/project/linux-nfs/list/>)

While your patch is in nfsd-testing, it is exposed to a variety of test environments, including community zero-day bots, static analysis tools, and NFSD continuous integration testing. The soak period is three to four weeks.

Each patch that survives in nfsd-testing for the soak period without changes is moved to the nfsd-next branch.

The nfsd-next branch is automatically merged into linux-next and fs-next on a nightly basis.

Patches that survive in nfsd-next are included in the next NFSD merge window pull request. These windows typically occur once every 63 days (nine weeks).

When the upstream merge window closes, the nfsd-next branch is renamed nfsd-fixes, and a new nfsd-next branch is created, based on the upstream -rc1 tag.

Fixes that are destined for an upstream -rc release also run the nfsd-testing gauntlet, but are then applied to the nfsd-fixes branch. That branch is made available for Linus to pull after a short time. In order to limit the risk of introducing regressions, we limit such fixes to emergency situations or fixes to breakage that occurred during the most recent upstream merge.

Please make it clear when submitting an emergency patch that immediate action (either application to -rc or LTS backport) is needed.

<a id="rst-sensitive-patch-submissions-and-bug-reports"></a>

### Sensitive patch submissions and bug reports

CVEs are generated by specific members of the Linux kernel community and several external entities. The Linux NFS community does not emit or assign CVEs. CVEs are assigned after an issue and its fix are known.

However, the NFSD maintainers sometimes receive sensitive security reports, and at times these are significant enough to need to be embargoed. In such rare cases, fixes can be developed and reviewed out of the public eye.

Please be aware that many version management tools add the stable Cc's when you post your patches. This is generally a nuisance, but it can result in outing an embargoed security issue accidentally. Don't add "Cc: stable" unless you are absolutely sure the patch needs to go to stable@ during the initial submission process.

Patches that are merged without ever appearing on any list, and which carry a Reported-by: or Fixes: tag are detected as suspicious by security-focused people. We encourage that, after any private review, security-sensitive patches should be posted to linux-nfs@ for the usual public review, archiving, and test period.

<a id="rst-llm-generated-submissions"></a>

### LLM-generated submissions

The Linux kernel community as a whole is still exploring the new world of LLM-generated code. The NFSD maintainers will entertain submission of patches that are partially or wholly generated by LLM-based development tools. Such submissions are held to the same standards as submissions created entirely by human authors:

- The human contributor identifies themselves via a Signed-off-by: tag. This tag counts as a DoC.

- The human contributor is solely responsible for code provenance and any contamination by inadvertently-included code with a conflicting license, as usual.

- The human contributor must be able to answer and address review questions. A patch description such as "This fixed my problem but I don't know why" is not acceptable.

- The contribution is subjected to the same test regimen as all other submissions.

- An indication (via a Generated-by: tag or otherwise) that the contribution is LLM-generated is not required.

It is easy to address review comments and fix requests in LLM generated code. So easy, in fact, that it becomes tempting to repost refreshed code immediately. Please resist that temptation.

As always, please avoid reposting series revisions more than once every 24 hours.

<a id="rst-clean-up-patches"></a>

### Clean-up patches

The NFSD maintainers discourage patches which perform simple clean- ups, which are not in the context of other work. For example:

- Addressing `checkpatch.pl` warnings after merge

- Addressing [Local variable ordering](</kernel/development/process/maintainer-netdev.md#rst-rcs>) issues

- Addressing long-standing whitespace damage

This is because it is felt that the churn that such changes produce comes at a greater cost than the value of such clean-ups.

Conversely, spelling and grammar fixes are encouraged.

<a id="rst-stable-and-lts-support"></a>

## Stable and LTS support

Upstream NFSD continuous integration testing runs against LTS trees whenever they are updated.

Please indicate when a patch containing a fix needs to be considered for LTS kernels, either via a Fixes: tag or explicit mention.

<a id="rst-feature-requests"></a>

## Feature requests

There is no one way to make an official feature request, but discussion about the request should eventually make its way to the [linux-nfs@vger.kernel.org](<mailto:linux-nfs@vger.kernel.org>) mailing list for public review by the community.

<a id="rst-subsystem-boundaries"></a>

### Subsystem boundaries

NFSD itself is not much more than a protocol engine. This means its primary responsibility is to translate the NFS protocol into API calls in the Linux kernel. For example, NFSD is not responsible for knowing exactly how bytes or file attributes are managed on a block device. It relies on other kernel subsystems for that.

If the subsystems on which NFSD relies do not implement a particular feature, even if the standard NFS protocols do support that feature, that usually means NFSD cannot provide that feature without substantial development work in other areas of the kernel.

<a id="rst-specificity"></a>

### Specificity

Feature requests can come from anywhere, and thus can often be nebulous. A requester might not understand what a "use case" or "user story" is. These descriptive paradigms are often used by developers and architects to understand what is required of a design, but are terms of art in the software trade, not used in the everyday world.

In order to prevent contributors and maintainers from becoming overwhelmed, we won't be afraid of saying "no" politely to underspecified requests.

<a id="rst-community-roles-and-their-authority"></a>

## Community roles and their authority

The purpose of Linux subsystem communities is to provide expertise and active stewardship of a narrow set of source files in the Linux kernel. This can include managing user space tooling as well.

To contextualize the structure of the Linux NFS community that is responsible for stewardship of the NFS server code base, we define the community roles here.

- **Contributor** : Anyone who submits a code change, bug fix, recommendation, documentation fix, and so on. A contributor can submit regularly or infrequently.

- **Outside Contributor** : A contributor who is not a regular actor in the Linux NFS community. This can mean someone who contributes to other parts of the kernel, or someone who just noticed a misspelling in a comment and sent a patch.

- **Reviewer** : Someone who is named in the MAINTAINERS file as a reviewer is an area expert who can request changes to contributed code, and expects that contributors will address the request.

- **External Reviewer** : Someone who is not named in the MAINTAINERS file as a reviewer, but who is an area expert. Examples include Linux kernel contributors with networking, security, or persistent storage expertise, or developers who contribute primarily to other NFS implementations.

One or more people will take on the following roles. These people are often generically referred to as "maintainers", and are identified in the MAINTAINERS file with the "M:" tag under the NFSD subsystem.

- **Upstream Release Manager** : This role is responsible for curating contributions into a branch, reviewing test results, and then sending a pull request during merge windows. There is a trust relationship between the release manager and Linus.

- **Bug Triager** : Someone who is a first responder to bug reports submitted to the linux-nfs mailing list or bug trackers, and helps troubleshoot and identify next steps.

- **Security Lead** : The security lead handles contacts from the security community to resolve immediate issues, as well as dealing with long-term security issues such as supply chain concerns. For upstream, that's usually whether contributions violate licensing or other intellectual property agreements.

- **Testing Lead** : The testing lead builds and runs the test infrastructure for the subsystem. The testing lead may ask for patches to be dropped because of ongoing high defect rates.

- **LTS Maintainer** : The LTS maintainer is responsible for managing the Fixes: and Cc: stable annotations on patches, and seeing that patches that cannot be automatically applied to LTS kernels get proper manual backports as necessary.

- **Community Manager** : This umpire role can be asked to call balls and strikes during conflicts, but is also responsible for ensuring the health of the relationships within the community and for facilitating discussions on long-term topics such as how to manage growing technical debt.

---

# Reference counting in pnfs

_Peios Kernel / Internals / Filesystems / nfs_

> The are several inter-related caches. We have layouts which can reference multiple devices, each of which can reference multiple data servers. Each data server can be referenced by multiple devices. Each device can be referenced by…

<a id="rst-reference-counting-in-pnfs"></a>

The are several inter-related caches.  We have layouts which can reference multiple devices, each of which can reference multiple data servers. Each data server can be referenced by multiple devices.  Each device can be referenced by multiple layouts. To keep all of this straight, we need to reference count.

<a id="rst-struct-pnfs-layout-hdr"></a>

## struct pnfs_layout_hdr

The on-the-wire command LAYOUTGET corresponds to struct pnfs_layout_segment, usually referred to by the variable name lseg. Each nfs_inode may hold a pointer to a cache of these layout segments in nfsi-&gt;layout, of type struct pnfs_layout_hdr.

We reference the header for the inode pointing to it, across each outstanding RPC call that references it (LAYOUTGET, LAYOUTRETURN, LAYOUTCOMMIT), and for each lseg held within.

Each header is also (when non-empty) put on a list associated with struct nfs_client (cl_layouts).  Being put on this list does not bump the reference count, as the layout is kept around by the lseg that keeps it in the list.

<a id="rst-deviceid-cache"></a>

## deviceid_cache

lsegs reference device ids, which are resolved per nfs_client and layout driver type.  The device ids are held in a RCU cache (struct nfs4_deviceid_cache).  The cache itself is referenced across each mount.  The entries (struct nfs4_deviceid) themselves are held across the lifetime of each lseg referencing them.

RCU is used because the deviceid is basically a write once, read many data structure.  The hlist size of 32 buckets needs better justification, but seems reasonable given that we can have multiple deviceid's per filesystem, and multiple filesystems per nfs_client.

The hash code is copied from the nfsd code base.  A discussion of hashing and variations of this algorithm can be found [here.](<http://groups.google.com/group/comp.lang.c/browse_thread/thread/9522965e2b8d3809>)<a id="rst-here"></a>

<a id="rst-data-server-cache"></a>

## data server cache

file driver devices refer to data servers, which are kept in a module level cache.  Its reference is held over the lifetime of the deviceid pointing to it.

<a id="rst-lseg"></a>

## lseg

lseg maintains an extra reference corresponding to the NFS_LSEG_VALID bit which holds it in the pnfs_layout_hdr's list.  When the final lseg is removed from the pnfs_layout_hdr's list, the NFS_LAYOUT_DESTROYED bit is set, preventing any new lsegs from being added.

<a id="rst-layout-drivers"></a>

## layout drivers

PNFS utilizes what is called layout drivers. The STD defines 4 basic layout types: "files", "objects", "blocks", and "flexfiles". For each of these types there is a layout-driver with a common function-vectors table which are called by the nfs-client pnfs-core to implement the different layout types.

Files-layout-driver code is in: fs/nfs/filelayout/.. directory Blocks-layout-driver code is in: fs/nfs/blocklayout/.. directory Flexfiles-layout-driver code is in: fs/nfs/flexfilelayout/.. directory

<a id="rst-blocks-layout-setup"></a>

## blocks-layout setup

TODO: Document the setup needs of the blocks layout driver

---

# Reexporting NFS filesystems

_Peios Kernel / Internals / Filesystems / nfs_

> It is possible to reexport an NFS filesystem over NFS. However, this feature comes with a number of limitations. Before trying it, we recommend some careful research to determine whether it will work for your purposes.

<a id="rst-reexporting-nfs-filesystems"></a>

<a id="rst-overview"></a>

## Overview

It is possible to reexport an NFS filesystem over NFS.  However, this feature comes with a number of limitations.  Before trying it, we recommend some careful research to determine whether it will work for your purposes.

A discussion of current known limitations follows.

<a id="rst-fsid-required-crossmnt-broken"></a>

## "fsid=" required, crossmnt broken

We require the "fsid=" export option on any reexport of an NFS filesystem.  You can use "uuidgen -r" to generate a unique argument.

The "crossmnt" export does not propagate "fsid=", so it will not allow traversing into further nfs filesystems; if you wish to export nfs filesystems mounted under the exported filesystem, you'll need to export them explicitly, assigning each its own unique "fsid= option.

<a id="rst-reboot-recovery"></a>

## Reboot recovery

The NFS protocol's normal reboot recovery mechanisms don't work for the case when the reexport server reboots because the source server has not rebooted, and so it is not in grace.  Since the source server is not in grace, it cannot offer any guarantees that the file won't have been changed between the locks getting lost and any attempt to recover them. The same applies to delegations and any associated locks.  Clients are not allowed to get file locks or delegations from a reexport server, any attempts will fail with operation not supported.

<a id="rst-filehandle-limits"></a>

## Filehandle limits

If the original server uses an X byte filehandle for a given object, the reexport server's filehandle for the reexported object will be X+22 bytes, rounded up to the nearest multiple of four bytes.

The result must fit into the RFC-mandated filehandle size limits:


<table>
<tbody>
<tr>
<td>


NFSv2

</td>
<td>


32 bytes

</td>
</tr>
<tr>
<td>


NFSv3

</td>
<td>


64 bytes

</td>
</tr>
<tr>
<td>


NFSv4

</td>
<td>


128 bytes

</td>
</tr>
</tbody>
</table>

So, for example, you will only be able to reexport a filesystem over NFSv2 if the original server gives you filehandles that fit in 10 bytes--which is unlikely.

In general there's no way to know the maximum filehandle size given out by an NFS server without asking the server vendor.

But the following table gives a few examples.  The first column is the typical length of the filehandle from a Linux server exporting the given filesystem, the second is the length after that nfs export is reexported by another Linux host:


<table>
<thead>
<tr>
<th>




</th>
<th>


filehandle length

</th>
<th>


after reexport

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


ext4:

</td>
<td>


28 bytes

</td>
<td>


52 bytes

</td>
</tr>
<tr>
<td>


xfs:

</td>
<td>


32 bytes

</td>
<td>


56 bytes

</td>
</tr>
<tr>
<td>


btrfs:

</td>
<td>


40 bytes

</td>
<td>


64 bytes

</td>
</tr>
</tbody>
</table>

All will therefore fit in an NFSv3 or NFSv4 filehandle after reexport, but none are reexportable over NFSv2.

Linux server filehandles are a bit more complicated than this, though; for example:

> - The (non-default) "subtreecheck" export option generally requires another 4 to 8 bytes in the filehandle.
>
> - If you export a subdirectory of a filesystem (instead of exporting the filesystem root), that also usually adds 4 to 8 bytes.
>
> - If you export over NFSv2, knfsd usually uses a shorter filesystem identifier that saves 8 bytes.
>
> - The root directory of an export uses a filehandle that is shorter.

As you can see, the 128-byte NFSv4 filehandle is large enough that you're unlikely to have trouble using NFSv4 to reexport any filesystem exported from a Linux server.  In general, if the original server is something that also supports NFSv3, you're *probably* OK.  Re-exporting over NFSv3 may be dicier, and reexporting over NFSv2 will probably never work.

For more details of Linux filehandle structure, the best reference is the source code and comments; see in particular:

> - include/linux/exportfs.h:enum fid_type
>
> - include/uapi/linux/nfsd/nfsfh.h:struct nfs_fhbase_new
>
> - fs/nfsd/nfsfh.c:set_version_and_fsid_type
>
> - fs/nfs/export.c:nfs_encode_fh

<a id="rst-open-deny-bits-ignored"></a>

## Open DENY bits ignored

NFS since NFSv4 supports ALLOW and DENY bits taken from Windows, which allow you, for example, to open a file in a mode which forbids other read opens or write opens. The Linux client doesn't use them, and the server's support has always been incomplete: they are enforced only against other NFS users, not against processes accessing the exported filesystem locally. A reexport server will also not pass them along to the original server, so they will not be enforced between clients of different reexport servers.

---

# RPC Cache

_Peios Kernel / Internals / Filesystems / nfs_

> This document gives a brief introduction to the caching mechanisms in the sunrpc layer that is used, in particular, for NFS authentication.

<a id="rst-rpc-cache"></a>

This document gives a brief introduction to the caching mechanisms in the sunrpc layer that is used, in particular, for NFS authentication.

<a id="rst-caches"></a>

## Caches

The caching replaces the old exports table and allows for a wide variety of values to be caches.

There are a number of caches that are similar in structure though quite possibly very different in content and use.  There is a corpus of common code for managing these caches.

Examples of caches that are likely to be needed are:

> - mapping from IP address to client name
>
> - mapping from client name and filesystem to export options
>
> - mapping from UID to list of GIDs, to work around NFS's limitation of 16 gids.
>
> - mappings between local UID/GID and remote UID/GID for sites that do not have uniform uid assignment
>
> - mapping from network identify to public key for crypto authentication.

The common code handles such things as:

> - general cache lookup with correct locking
>
> - supporting 'NEGATIVE' as well as positive entries
>
> - allowing an EXPIRED time on cache items, and removing items after they expire, and are no longer in-use.
>
> - making requests to user-space to fill in cache entries
>
> - allowing user-space to directly set entries in the cache
>
> - delaying RPC requests that depend on as-yet incomplete cache entries, and replaying those requests when the cache entry is complete.
>
> - clean out old entries as they expire.

<a id="rst-creating-a-cache"></a>

### Creating a Cache

- A cache needs a datum to store.  This is in the form of a structure definition that must contain a struct cache_head as an element, usually the first. It will also contain a key and some content. Each cache element is reference counted and contains expiry and update times for use in cache management.

- A cache needs a "cache_detail" structure that describes the cache.  This stores the hash table, some parameters for cache management, and some operations detailing how to work with particular cache items.

  The operations are:

  > - **struct cache_head \*alloc(void)**
  >
  >   This simply allocates appropriate memory and returns a pointer to the cache_detail embedded within the structure
  >
  > - **void cache_put(struct kref \*)**
  >
  >   This is called when the last reference to an item is dropped.  The pointer passed is to the 'ref' field in the cache_head.  cache_put should release any references create by 'cache_init' and, if CACHE_VALID is set, any references created by cache_update. It should then release the memory allocated by 'alloc'.
  >
  > - **int match(struct cache_head \*orig, struct cache_head \*new)**
  >
  >   test if the keys in the two structures match.  Return 1 if they do, 0 if they don't.
  >
  > - **void init(struct cache_head \*orig, struct cache_head \*new)**
  >
  >   Set the 'key' fields in 'new' from 'orig'.  This may include taking references to shared objects.
  >
  > - **void update(struct cache_head \*orig, struct cache_head \*new)**
  >
  >   Set the 'content' fields in 'new' from 'orig'.
  >
  > - **int cache_show(struct seq_file \*m, struct cache_detail \*cd, struct cache_head \*h)**
  >
  >   Optional.  Used to provide a /proc file that lists the contents of a cache.  This should show one item, usually on just one line.
  >
  > - **int cache_request(struct cache_detail \*cd, struct cache_head \*h, char \*\*bpp, int \*blen)**
  >
  >   Format a request to be send to user-space for an item to be instantiated.  \*bpp is a buffer of size \*blen. bpp should be moved forward over the encoded message, and  \*blen should be reduced to show how much free space remains.  Return 0 on success or &lt;0 if not enough room or other problem.
  >
  > - **int cache_parse(struct cache_detail \*cd, char \*buf, int len)**
  >
  >   A message from user space has arrived to fill out a cache entry.  It is in 'buf' of length 'len'. cache_parse should parse this, find the item in the cache with sunrpc_cache_lookup_rcu, and update the item with sunrpc_cache_update.

- A cache needs to be registered using cache_register().  This includes it on a list of caches that will be regularly cleaned to discard old data.

<a id="rst-using-a-cache"></a>

### Using a cache

To find a value in a cache, call sunrpc_cache_lookup_rcu passing a pointer to the cache_head in a sample item with the 'key' fields filled in. This will be passed to -&gt;match to identify the target entry.  If no entry is found, a new entry will be create, added to the cache, and marked as not containing valid data.

The item returned is typically passed to cache_check which will check if the data is valid, and may initiate an up-call to get fresh data. cache_check will return -ENOENT in the entry is negative or if an up call is needed but not possible, -EAGAIN if an upcall is pending, or 0 if the data is valid;

cache_check can be passed a "struct cache_req\*".  This structure is typically embedded in the actual request and can be used to create a deferred copy of the request (struct cache_deferred_req).  This is done when the found cache item is not uptodate, but the is reason to believe that userspace might provide information soon.  When the cache item does become valid, the deferred copy of the request will be revisited (-&gt;revisit).  It is expected that this method will reschedule the request for processing.

The value returned by sunrpc_cache_lookup_rcu can also be passed to sunrpc_cache_update to set the content for the item.  A second item is passed which should hold the content.  If the item found by \_lookup has valid data, then it is discarded and a new item is created.  This saves any user of an item from worrying about content changing while it is being inspected.  If the item found by \_lookup does not contain valid data, then the content is copied across and CACHE_VALID is set.

<a id="rst-populating-a-cache"></a>

### Populating a cache

Each cache has a name, and when the cache is registered, a directory with that name is created in /proc/net/rpc

This directory contains a file called 'channel' which is a channel for communicating between kernel and user for populating the cache. This directory may later contain other files of interacting with the cache.

The 'channel' works a bit like a datagram socket. Each 'write' is passed as a whole to the cache for parsing and interpretation. Each cache can treat the write requests differently, but it is expected that a message written will contain:

> - a key
>
> - an expiry time
>
> - a content.

with the intention that an item in the cache with the give key should be create or updated to have the given content, and the expiry time should be set on that item.

Reading from a channel is a bit more interesting.  When a cache lookup fails, or when it succeeds but finds an entry that may soon expire, a request is lodged for that cache item to be updated by user-space.  These requests appear in the channel file.

Successive reads will return successive requests. If there are no more requests to return, read will return EOF, but a select or poll for read will block waiting for another request to be added.

Thus a user-space helper is likely to:



```text
open the channel.
  select for readable
  read a request
  write a response
loop.
```

If it dies and needs to be restarted, any requests that have not been answered will still appear in the file and will be read by the new instance of the helper.

Each cache should define a "cache_parse" method which takes a message written from user-space and processes it.  It should return an error (which propagates back to the write syscall) or 0.

Each cache should also define a "cache_request" method which takes a cache item and encodes a request into the buffer provided.

> [!NOTE]
>
> If a cache has no active readers on the channel, and has had not active readers for more than 60 seconds, further requests will not be added to the channel but instead all lookups that do not find a valid entry will fail.  This is partly for backward compatibility: The previous nfs exports table was deemed to be authoritative and a failed lookup meant a definite 'no'.

<a id="rst-request-response-format"></a>

### request/response format

While each cache is free to use its own format for requests and responses over channel, the following is recommended as appropriate and support routines are available to help: Each request or response record should be printable ASCII with precisely one newline character which should be at the end. Fields within the record should be separated by spaces, normally one. If spaces, newlines, or nul characters are needed in a field they much be quoted.  two mechanisms are available:

- If a field begins 'x' then it must contain an even number of hex digits, and pairs of these digits provide the bytes in the field.

- otherwise a in the field must be followed by 3 octal digits which give the code for a byte.  Other characters are treated as them selves.  At the very least, space, newline, nul, and '' must be quoted in this way.

---

# rpcsec_gss support for kernel RPC servers

_Peios Kernel / Internals / Filesystems / nfs_

> This document gives references to the standards and protocols used to implement RPCGSS authentication in kernel RPC servers such as the NFS server and the NFS client's NFSv4.0 callback server. (But note that NFSv4.1 and higher don't…

<a id="rst-rpcsec-gss-support-for-kernel-rpc-servers"></a>

This document gives references to the standards and protocols used to implement RPCGSS authentication in kernel RPC servers such as the NFS server and the NFS client's NFSv4.0 callback server.  (But note that NFSv4.1 and higher don't require the client to act as a server for the purposes of authentication.)

RPCGSS is specified in a few IETF documents:

> - RFC2203 v1: [https://tools.ietf.org/rfc/rfc2203.txt](<https://tools.ietf.org/rfc/rfc2203.txt>)
>
> - RFC5403 v2: [https://tools.ietf.org/rfc/rfc5403.txt](<https://tools.ietf.org/rfc/rfc5403.txt>)

There is a third version that we don't currently implement:

> - RFC7861 v3: [https://tools.ietf.org/rfc/rfc7861.txt](<https://tools.ietf.org/rfc/rfc7861.txt>)

<a id="rst-background"></a>

## Background

The RPCGSS Authentication method describes a way to perform GSSAPI Authentication for NFS.  Although GSSAPI is itself completely mechanism agnostic, in many cases only the KRB5 mechanism is supported by NFS implementations.

The Linux kernel, at the moment, supports only the KRB5 mechanism, and depends on GSSAPI extensions that are KRB5 specific.

GSSAPI is a complex library, and implementing it completely in kernel is unwarranted. However GSSAPI operations are fundamentally separable in 2 parts:

- initial context establishment

- integrity/privacy protection (signing and encrypting of individual packets)

The former is more complex and policy-independent, but less performance-sensitive.  The latter is simpler and needs to be very fast.

Therefore, we perform per-packet integrity and privacy protection in the kernel, but leave the initial context establishment to userspace.  We need upcalls to request userspace to perform context establishment.

<a id="rst-nfs-server-legacy-upcall-mechanism"></a>

## NFS Server Legacy Upcall Mechanism

The classic upcall mechanism uses a custom text based upcall mechanism to talk to a custom daemon called rpc.svcgssd that is provide by the nfs-utils package.

This upcall mechanism has 2 limitations:

- **A)** It can handle tokens that are no bigger than 2KiB

In some Kerberos deployment GSSAPI tokens can be quite big, up and beyond 64KiB in size due to various authorization extensions attacked to the Kerberos tickets, that needs to be sent through the GSS layer in order to perform context establishment.

B) It does not properly handle creds where the user is member of more than a few thousand groups (the current hard limit in the kernel is 65K groups) due to limitation on the size of the buffer that can be send back to the kernel (4KiB).

<a id="rst-nfs-server-new-rpc-upcall-mechanism"></a>

## NFS Server New RPC Upcall Mechanism

The newer upcall mechanism uses RPC over a unix socket to a daemon called gss-proxy, implemented by a userspace program called Gssproxy.

The gss_proxy RPC protocol is currently documented [here](<https://fedorahosted.org/gss-proxy/wiki/ProtocolDocumentation>)<a id="rst-here"></a>.

This upcall mechanism uses the kernel rpc client and connects to the gssproxy userspace program over a regular unix socket. The gssproxy protocol does not suffer from the size limitations of the legacy protocol.

<a id="rst-negotiating-upcall-mechanisms"></a>

## Negotiating Upcall Mechanisms

To provide backward compatibility, the kernel defaults to using the legacy mechanism.  To switch to the new mechanism, gss-proxy must bind to /var/run/gssproxy.sock and then write "1" to /proc/net/rpc/use-gss-proxy.  If gss-proxy dies, it must repeat both steps.

Once the upcall mechanism is chosen, it cannot be changed.  To prevent locking into the legacy mechanisms, the above steps must be performed before starting nfsd.  Whoever starts nfsd can guarantee this by reading from /proc/net/rpc/use-gss-proxy and checking that it contains a "1"--the read will block until gss-proxy has done its write to the file.

---

# CIFS

_Peios Kernel / Internals / Filesystems / smb_

> Reference for CIFS.

<a id="rst-cifs"></a>

- [KSMBD - SMB3 Kernel Server](</kernel/internals/filesystems/smb/ksmbd.md>)
- [Mounting root file system via SMB (cifs.ko)](</kernel/internals/filesystems/smb/cifsroot.md>)
- [SMB Direct - SMB3 over RDMA](</kernel/internals/filesystems/smb/smbdirect.md>)

---

# Mounting root file system via SMB (cifs.ko)

_Peios Kernel / Internals / Filesystems / smb_

> Written 2019 by Paulo Alcantara <palcantara@suse.de>

<a id="rst-mounting-root-file-system-via-smb-cifs-ko"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Written 2019 by Paulo Alcantara &lt;[palcantara@suse.de](<mailto:palcantara@suse.de>)&gt;

Written 2019 by Aurelien Aptel &lt;[aaptel@suse.com](<mailto:aaptel@suse.com>)&gt;

The CONFIG_CIFS_ROOT option enables experimental root file system support over the SMB protocol via cifs.ko.

It introduces a new kernel command-line option called 'cifsroot=' which will tell the kernel to mount the root file system over the network by utilizing SMB or CIFS protocol.

In order to mount, the network stack will also need to be set up by using 'ip=' config option. For more details, see [Documentation/admin-guide/nfs/nfsroot.rst](/kernel/administration/admin-guide/nfs/nfsroot.md).

A CIFS root mount currently requires the use of SMB1+UNIX Extensions which is only supported by the Samba server. SMB1 is the older deprecated version of the protocol but it has been extended to support POSIX features (See \[1\]). The equivalent extensions for the newer recommended version of the protocol (SMB3) have not been fully implemented yet which means SMB3 doesn't support some required POSIX file system objects (e.g. block devices, pipes, sockets).

As a result, a CIFS root will default to SMB1 for now but the version to use can nonetheless be changed via the 'vers=' mount option.  This default will change once the SMB3 POSIX extensions are fully implemented.

<a id="rst-server-configuration"></a>

## Server configuration

To enable SMB1+UNIX extensions you will need to set these global settings in Samba smb.conf:



```text
[global]
server min protocol = NT1
unix extension = yes        # default
```

<a id="rst-kernel-command-line"></a>

## Kernel command line



```text
root=/dev/cifs
```

This is just a virtual device that basically tells the kernel to mount the root file system via SMB protocol.



```text
cifsroot=//<server-ip>/<share>[,options]
```

Enables the kernel to mount the root file system via SMB that are located in the &lt;server-ip&gt; and &lt;share&gt; specified in this option.

The default mount options are set in fs/smb/client/cifsroot.c.

- **server-ip**

  IPv4 address of the server.

- **share**

  Path to SMB share (rootfs).

- **options**

  Optional mount options. For more information, see mount.cifs(8).

<a id="rst-examples"></a>

## Examples

Export root file system as a Samba share in smb.conf file:



```text
...
[linux]
        path = /path/to/rootfs
        read only = no
        guest ok = yes
        force user = root
        force group = root
        browseable = yes
        writeable = yes
        admin users = root
        public = yes
        create mask = 0777
        directory mask = 0777
...
```

Restart smb service:



```text
# systemctl restart smb
```

Test it under QEMU on a kernel built with CONFIG_CIFS_ROOT and CONFIG_IP_PNP options enabled:



```text
# qemu-system-x86_64 -enable-kvm -cpu host -m 1024 \
-kernel /path/to/linux/arch/x86/boot/bzImage -nographic \
-append "root=/dev/cifs rw ip=dhcp cifsroot=//10.0.2.2/linux,username=foo,password=bar console=ttyS0 3"
```

1: [https://wiki.samba.org/index.php/UNIX_Extensions](<https://wiki.samba.org/index.php/UNIX_Extensions>)

---

# KSMBD - SMB3 Kernel Server

_Peios Kernel / Internals / Filesystems / smb_

> KSMBD is a linux kernel server which implements SMB3 protocol in kernel space for sharing files over network.

<a id="rst-ksmbd-smb3-kernel-server"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

KSMBD is a linux kernel server which implements SMB3 protocol in kernel space for sharing files over network.

<a id="rst-ksmbd-architecture"></a>

## KSMBD architecture

The subset of performance related operations belong in kernelspace and the other subset which belong to operations which are not really related with performance in userspace. So, DCE/RPC management that has historically resulted into a number of buffer overflow issues and dangerous security bugs and user account management are implemented in user space as ksmbd.mountd. File operations that are related with performance (open/read/write/close etc.) in kernel space (ksmbd). This also allows for easier integration with VFS interface for all file operations.

<a id="rst-ksmbd-kernel-daemon"></a>

### ksmbd (kernel daemon)

When the server daemon is started, It starts up a forker thread (ksmbd/interface name) at initialization time and open a dedicated port 445 for listening to SMB requests. Whenever new clients make a request, the Forker thread will accept the client connection and fork a new thread for a dedicated communication channel between the client and the server. It allows for parallel processing of SMB requests(commands) from clients as well as allowing for new clients to make new connections. Each instance is named ksmbd/1\~n(port number) to indicate connected clients. Depending on the SMB request types, each new thread can decide to pass through the commands to the user space (ksmbd.mountd), currently DCE/RPC commands are identified to be handled through the user space. To further utilize the linux kernel, it has been chosen to process the commands as workitems and to be executed in the handlers of the ksmbd-io kworker threads. It allows for multiplexing of the handlers as the kernel takes care of initiating extra worker threads if the load is increased and vice versa, if the load is decreased it destroys the extra worker threads. So, after the connection is established with the client. Dedicated ksmbd/1..n(port number) takes complete ownership of receiving/parsing of SMB commands. Each received command is worked in parallel i.e., there can be multiple client commands which are worked in parallel. After receiving each command a separated kernel workitem is prepared for each command which is further queued to be handled by ksmbd-io kworkers. So, each SMB workitem is queued to the kworkers. This allows the benefit of load sharing to be managed optimally by the default kernel and optimizing client performance by handling client commands in parallel.

<a id="rst-ksmbd-mountd-user-space-daemon"></a>

### ksmbd.mountd (user space daemon)

ksmbd.mountd is a userspace process to, transfer the user account and password that are registered using ksmbd.adduser (part of utils for user space). Further it allows sharing information parameters that are parsed from smb.conf to ksmbd in kernel. For the execution part it has a daemon which is continuously running and connected to the kernel interface using netlink socket, it waits for the requests (dcerpc and share/user info). It handles RPC calls (at a minimum few dozen) that are most important for file server from NetShareEnum and NetServerGetInfo. Complete DCE/RPC response is prepared from the user space and passed over to the associated kernel thread for the client.

<a id="rst-ksmbd-feature-status"></a>

## KSMBD Feature Status


<table>
<thead>
<tr>
<th>


Feature name

</th>
<th>


Status

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Dialects

</td>
<td>


Supported. SMB2.1 SMB3.0, SMB3.1.1 dialects (intentionally excludes security vulnerable SMB1 dialect).

</td>
</tr>
<tr>
<td>


Auto Negotiation

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Compound Request

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Oplock Cache Mechanism

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


SMB2 leases(v1 lease)

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Directory leases(v2 lease)

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Multi-credits

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


NTLM/NTLMv2

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


HMAC-SHA256 Signing

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Secure negotiate

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Signing Update

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Pre-authentication integrity

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


SMB3 encryption(CCM, GCM)

</td>
<td>


Supported. (CCM/GCM128 and CCM/GCM256 supported)

</td>
</tr>
<tr>
<td>


SMB direct(RDMA)

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


SMB3 Multi-channel

</td>
<td>


Partially Supported. Planned to implement replay/retry mechanisms for future.

</td>
</tr>
<tr>
<td>


Receive Side Scaling mode

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


SMB3.1.1 POSIX extension

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


ACLs

</td>
<td>


Partially Supported. only DACLs available, SACLs (auditing) is planned for the future. For ownership (SIDs) ksmbd generates random subauth values(then store it to disk) and use uid/gid get from inode as RID for local domain SID. The current acl implementation is limited to standalone server, not a domain member. Integration with Samba tools is being worked on to allow future support for running as a domain member.

</td>
</tr>
<tr>
<td>


Kerberos

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


Durable handle v1,v2

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


Persistent handle

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


SMB2 notify

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


Sparse file support

</td>
<td>


Supported.

</td>
</tr>
<tr>
<td>


DCE/RPC support

</td>
<td>


Partially Supported. a few calls(NetShareEnumAll, NetServerGetInfo, SAMR, LSARPC) that are needed for file server handled via netlink interface from ksmbd.mountd. Additional integration with Samba tools and libraries via upcall is being investigated to allow support for additional DCE/RPC management calls (and future support for Witness protocol e.g.)

</td>
</tr>
<tr>
<td>


ksmbd/nfsd interoperability

</td>
<td>


Planned for future. The features that ksmbd support are Leases, Notify, ACLs and Share modes.

</td>
</tr>
<tr>
<td>


SMB3.1.1 Compression

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


SMB3.1.1 over QUIC

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


Signing/Encryption over RDMA

</td>
<td>


Planned for future.

</td>
</tr>
<tr>
<td>


SMB3.1.1 GMAC signing support

</td>
<td>


Planned for future.

</td>
</tr>
</tbody>
</table>

<a id="rst-how-to-run"></a>

## How to run

1. Download ksmbd-tools([https://github.com/cifsd-team/ksmbd-tools/releases](<https://github.com/cifsd-team/ksmbd-tools/releases>)) and compile them.

   - Refer to README([https://github.com/cifsd-team/ksmbd-tools/blob/master/README.md](<https://github.com/cifsd-team/ksmbd-tools/blob/master/README.md>)) to know how to use ksmbd.mountd/adduser/addshare/control utils

     $ ./autogen.sh $ ./configure --with-rundir=/run $ make &amp;&amp; sudo make install

2. Create /usr/local/etc/ksmbd/ksmbd.conf file, add SMB share in ksmbd.conf file.

   - Refer to ksmbd.conf.example in ksmbd-utils, See ksmbd.conf manpage for details to configure shares.

     > $ man ksmbd.conf

3. Create user/password for SMB share.

   - See ksmbd.adduser manpage.

     $ man ksmbd.adduser $ sudo ksmbd.adduser -a &lt;Enter USERNAME for SMB share access&gt;

4. Insert the ksmbd.ko module after you build your kernel. No need to load the module if ksmbd is built into the kernel.

   - - **Set ksmbd in menuconfig(e.g. $ make menuconfig)**

       - **\[\*\] Network File Systems  ---&gt;**

         > &lt;M&gt; SMB3 server support (EXPERIMENTAL)

         $ sudo modprobe ksmbd.ko

5. Start ksmbd user space daemon

   > $ sudo ksmbd.mountd

6. Access share from Windows or Linux using SMB3 client (cifs.ko or smbclient of samba)

<a id="rst-shutdown-ksmbd"></a>

## Shutdown KSMBD

1. - **kill user and kernel space daemon**

     \# sudo ksmbd.control -s

<a id="rst-how-to-turn-debug-print-on"></a>

## How to turn debug print on

Each layer /sys/class/ksmbd-control/debug

1. - **Enable all component prints**

     \# sudo ksmbd.control -d "all"

2. - **Enable one of the components (smb, auth, vfs, oplock, ipc, conn, rdma)**

     \# sudo ksmbd.control -d "smb"

3. - **Show what prints are enabled.**

     - **\# cat /sys/class/ksmbd-control/debug**

       \[smb\] auth vfs oplock ipc conn \[rdma\]

4. - **Disable prints:**

     If you try the selected component once more, It is disabled without brackets.

---

# SMB Direct - SMB3 over RDMA

_Peios Kernel / Internals / Filesystems / smb_

> This document describes how to set up the Linux SMB client and server to use RDMA.

<a id="rst-smb-direct-smb3-over-rdma"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes how to set up the Linux SMB client and server to use RDMA.

<a id="rst-overview"></a>

## Overview

The Linux SMB kernel client supports SMB Direct, which is a transport scheme for SMB3 that uses RDMA (Remote Direct Memory Access) to provide high throughput and low latencies by bypassing the traditional TCP/IP stack. SMB Direct on the Linux SMB client can be tested against KSMBD - a kernel-space SMB server.

<a id="rst-installation"></a>

## Installation

- Install an RDMA device. As long as the RDMA device driver is supported by the kernel, it should work. This includes both software emulators (soft RoCE, soft iWARP) and hardware devices (InfiniBand, RoCE, iWARP).

- Install a kernel with SMB Direct support. The first kernel release to support SMB Direct on both the client and server side is 5.15. Therefore, a distribution compatible with kernel 5.15 or later is required.

- Install cifs-utils, which provides the `mount.cifs` command to mount SMB shares.

- Configure the RDMA stack

  Make sure that your kernel configuration has RDMA support enabled. Under Device Drivers -&gt; Infiniband support, update the kernel configuration to enable Infiniband support.

  Enable the appropriate IB HCA support or iWARP adapter support, depending on your hardware.

  If you are using InfiniBand, enable IP-over-InfiniBand support.

  For soft RDMA, enable either the soft iWARP (`RDMA _SIW`) or soft RoCE (`RDMA_RXE`) module. Install the `iproute2` package and use the `rdma link add` command to load the module and create an RDMA interface.

  e.g. if your local ethernet interface is `eth0`, you can use:

  >
  >
  > ```bash
  > sudo rdma link add siw0 type siw netdev eth0
  > ```

- Enable SMB Direct support for both the server and the client in the kernel configuration.

  > Server Setup
  >
  >
  >
  > ```text
  > Network File Systems  --->
  >     <M> SMB3 server support
  >         [*] Support for SMB Direct protocol
  > ```
  >
  > Client Setup
  >
  >
  >
  > ```text
  > Network File Systems  --->
  >     <M> SMB3 and CIFS support (advanced network filesystem)
  >         [*] SMB Direct support
  > ```

- Build and install the kernel. SMB Direct support will be enabled in the cifs.ko and ksmbd.ko modules.

<a id="rst-setup-and-usage"></a>

## Setup and Usage

- Set up and start a KSMBD server as described in the [KSMBD documentation](<https://www.kernel.org/doc/Documentation/filesystems/smb/ksmbd.rst>)<a id="rst-ksmbd-documentation"></a>. Also add the "server multi channel support = yes" parameter to ksmbd.conf.

- On the client, mount the share with `rdma` mount option to use SMB Direct (specify a SMB version 3.0 or higher using `vers`).

  For example:

  >
  >
  > ```bash
  > mount -t cifs //server/share /mnt/point -o vers=3.1.1,rdma
  > ```

- To verify that the mount is using SMB Direct, you can check dmesg for the following log line after mounting:

  >
  >
  > ```text
  > CIFS: VFS: RDMA transport established
  > ```

  Or, verify `rdma` mount option for the share in `/proc/mounts`:

  >
  >
  > ```bash
  > cat /proc/mounts | grep cifs
  > ```

---

# SPU Filesystem

_Peios Kernel / Internals / Filesystems / spufs_

> Reference for SPU Filesystem.

<a id="rst-spu-filesystem"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [spufs](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/filesystems/spufs/spufs.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [spu_create](</kernel/internals/filesystems/spufs/spu-create.md>)
- [spu_run](</kernel/internals/filesystems/spufs/spu-run.md>)

---

# spu_create

_Peios Kernel / Internals / Filesystems / spufs_

> spu_create - create a new spu context

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-spu-create"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-name"></a>

## Name

> spu_create - create a new spu context

<a id="rst-synopsis"></a>

## Synopsis

>
>
> ```text
> #include <sys/types.h>
> #include <sys/spu.h>
>
> int spu_create(const char *pathname, int flags, mode_t mode);
> ```

<a id="rst-description"></a>

## Description

> The  spu_create  system call is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to  access  Synergistic Processor  Units (SPUs). It creates a new logical context for an SPU in pathname and returns a handle to associated  with  it.   pathname  must point  to  a  non-existing directory in the mount point of the SPU file system (spufs).  When spu_create is successful, a directory  gets  cre- ated on pathname and it is populated with files.
>
> The  returned  file  handle can only be passed to spu_run(2) or closed, other operations are not defined on it. When it is closed, all  associ- ated  directory entries in spufs are removed. When the last file handle pointing either inside  of  the  context  directory  or  to  this  file descriptor is closed, the logical SPU context is destroyed.
>
> The  parameter flags can be zero or any bitwise or'd combination of the following constants:
>
> - **SPU_RAWIO**
>
>   Allow mapping of some of the hardware registers of the SPU  into user space. This flag requires the CAP_SYS_RAWIO capability, see capabilities(7).
>
> The mode parameter specifies the permissions used for creating the  new directory  in  spufs.   mode is modified with the user's umask(2) value and then used for both the directory and the files contained in it. The file permissions mask out some more bits of mode because they typically support only read or write access. See stat(2) for a full list  of  the possible mode values.

<a id="rst-return-value"></a>

## Return Value

> spu_create  returns a new file descriptor. It may return -1 to indicate an error condition and set errno to  one  of  the  error  codes  listed below.

<a id="rst-errors"></a>

## Errors

> - **EACCES**
>
>   The  current  user does not have write access on the spufs mount point.
>
> EEXIST An SPU context already exists at the given path name.
>
> - **EFAULT pathname is not a valid string pointer in  the  current  address**
>
>   space.
>
> EINVAL pathname is not a directory in the spufs mount point.
>
> ELOOP  Too many symlinks were found while resolving pathname.
>
> EMFILE The process has reached its maximum open file limit.
>
> - **ENAMETOOLONG**
>
>   pathname was too long.
>
> ENFILE The system has reached the global open file limit.
>
> ENOENT Part of pathname could not be resolved.
>
> ENOMEM The kernel could not allocate all resources required.
>
> - **ENOSPC There  are  not  enough  SPU resources available to create a new**
>
>   context or the user specific limit for the number  of  SPU  con- texts has been reached.
>
> - **ENOSYS the functionality is not provided by the current system, because**
>
>   either the hardware does not provide SPUs or the spufs module is not loaded.
>
> - **ENOTDIR**
>
>   A part of pathname is not a directory.

<a id="rst-notes"></a>

## Notes

> spu_create  is  meant  to  be used from libraries that implement a more abstract interface to SPUs, not to be used from  regular  applications. See  [http://www.bsc.es/projects/deepcomputing/linuxoncell/](<http://www.bsc.es/projects/deepcomputing/linuxoncell/>) for the rec- ommended libraries.

<a id="rst-files"></a>

## Files

> pathname must point to a location beneath the mount point of spufs.  By convention, it gets mounted in /spu.

<a id="rst-conforming-to"></a>

## Conforming to

> This call is Linux specific and only implemented by the ppc64 architecture. Programs using this system call are not portable.

<a id="rst-bugs"></a>

## Bugs

> The code does not yet fully implement all features lined out here.

<a id="rst-author"></a>

## Author

> Arnd Bergmann &lt;[arndb@de.ibm.com](<mailto:arndb@de.ibm.com>)&gt;

<a id="rst-see-also"></a>

## See Also

> capabilities(7), close(2), spu_run(2), spufs(7)

---

# spu_run

_Peios Kernel / Internals / Filesystems / spufs_

> spu_run - execute an spu context

<a id="rst-spu-run"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-name"></a>

## Name

> spu_run - execute an spu context

<a id="rst-synopsis"></a>

## Synopsis

>
>
> ```text
> #include <sys/spu.h>
>
> int spu_run(int fd, unsigned int *npc, unsigned int *event);
> ```

<a id="rst-description"></a>

## Description

> The  spu_run system call is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to access Synergistic  Pro- cessor  Units  (SPUs).  It  uses the fd that was returned from spu_cre- ate(2) to address a specific SPU context. When the context gets  sched- uled  to a physical SPU, it starts execution at the instruction pointer passed in npc.
>
> Execution of SPU code happens synchronously, meaning that spu_run  does not  return  while the SPU is still running. If there is a need to exe- cute SPU code in parallel with other code on either  the  main  CPU  or other  SPUs,  you  need to create a new thread of execution first, e.g. using the pthread_create(3) call.
>
> When spu_run returns, the current value of the SPU instruction  pointer is  written back to npc, so you can call spu_run again without updating the pointers.
>
> event can be a NULL pointer or point to an extended  status  code  that gets  filled  when spu_run returns. It can be one of the following con- stants:
>
> - **SPE_EVENT_DMA_ALIGNMENT**
>
>   A DMA alignment error
>
> - **SPE_EVENT_SPE_DATA_SEGMENT**
>
>   A DMA segmentation error
>
> - **SPE_EVENT_SPE_DATA_STORAGE**
>
>   A DMA storage error
>
> If NULL is passed as the event argument, these errors will result in  a signal delivered to the calling process.

<a id="rst-return-value"></a>

## Return Value

> spu_run  returns the value of the spu_status register or -1 to indicate an error and set errno to one of the error  codes  listed  below.   The spu_status  register  value  contains  a  bit  mask of status codes and optionally a 14 bit code returned from the stop-and-signal  instruction on the SPU. The bit masks for the status codes are:
>
> - **0x02**
>
>   SPU was stopped by stop-and-signal.
>
> - **0x04**
>
>   SPU was stopped by halt.
>
> - **0x08**
>
>   SPU is waiting for a channel.
>
> - **0x10**
>
>   SPU is in single-step mode.
>
> - **0x20**
>
>   SPU has tried to execute an invalid instruction.
>
> - **0x40**
>
>   SPU has tried to access an invalid channel.
>
> - **0x3fff0000**
>
>   The  bits  masked with this value contain the code returned from stop-and-signal.
>
> There are always one or more of the lower eight bits set  or  an  error code is returned from spu_run.

<a id="rst-errors"></a>

## Errors

> - **EAGAIN or EWOULDBLOCK**
>
>   fd is in non-blocking mode and spu_run would block.
>
> EBADF  fd is not a valid file descriptor.
>
> - **EFAULT npc is not a valid pointer or status is neither NULL nor a valid**
>
>   pointer.
>
> - **EINTR  A signal occurred while spu_run was in progress.  The npc  value**
>
>   has  been updated to the new program counter value if necessary.
>
> EINVAL fd is not a file descriptor returned from spu_create(2).
>
> - **ENOMEM Insufficient memory was available to handle a page fault result-**
>
>   ing from an MFC direct memory access.
>
> - **ENOSYS the functionality is not provided by the current system, because**
>
>   either the hardware does not provide SPUs or the spufs module is not loaded.

<a id="rst-notes"></a>

## Notes

> spu_run  is  meant  to  be  used  from  libraries that implement a more abstract interface to SPUs, not to be used from  regular  applications. See  [http://www.bsc.es/projects/deepcomputing/linuxoncell/](<http://www.bsc.es/projects/deepcomputing/linuxoncell/>) for the rec- ommended libraries.

<a id="rst-conforming-to"></a>

## Conforming to

> This call is Linux specific and only implemented by the ppc64 architecture. Programs using this system call are not portable.

<a id="rst-bugs"></a>

## Bugs

> The code does not yet fully implement all features lined out here.

<a id="rst-author"></a>

## Author

> Arnd Bergmann &lt;[arndb@de.ibm.com](<mailto:arndb@de.ibm.com>)&gt;

<a id="rst-see-also"></a>

## See Also

> capabilities(7), close(2), spu_create(2), spufs(7)

---

# spufs

_Peios Kernel / Internals / Filesystems / spufs_

> spufs - the SPU file system

<a id="rst-spufs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-name"></a>

## Name

> spufs - the SPU file system

<a id="rst-description"></a>

## Description

> The SPU file system is used on PowerPC machines that implement the Cell Broadband Engine Architecture in order to access Synergistic  Processor Units (SPUs).
>
> The file system provides a name space similar to posix shared memory or message queues. Users that have write permissions on  the  file  system can use spu\_create(2) to establish SPU contexts in the spufs root.
>
> Every SPU context is represented by a directory containing a predefined set of files. These files can be used for manipulating the state of the logical SPU. Users can change permissions on those files, but not actu- ally add or remove files.

<a id="rst-mount-options"></a>

## Mount Options

> - **uid=&lt;uid&gt;**
>
>   set the user owning the mount point, the default is 0 (root).
>
> - **gid=&lt;gid&gt;**
>
>   set the group owning the mount point, the default is 0 (root).

<a id="rst-files"></a>

## Files

> > The files in spufs mostly follow the standard behavior for regular sys- tem  calls like read(2) or write(2), but often support only a subset of the operations supported on regular file systems. This list details the supported  operations  and  the  deviations  from  the behaviour in the respective man pages.
> >
> > All files that support the read(2) operation also support readv(2)  and all  files  that support the write(2) operation also support writev(2). All files support the access(2) and stat(2) family of  operations,  but only  the  st\_mode,  st\_nlink,  st\_uid and st\_gid fields of struct stat contain reliable information.
> >
> > All files support the chmod(2)/fchmod(2) and chown(2)/fchown(2)  opera- tions,  but  will  not be able to grant permissions that contradict the possible operations, e.g. read access on the wbox file.
> >
> > The current set of files is:
>
> - `/mem`
>
>   the contents of the local storage memory  of  the  SPU.   This  can  be accessed  like  a regular shared memory file and contains both code and data in the address space of the SPU.  The possible  operations  on  an open mem file are:
>
>   - **read(2), pread(2), write(2), pwrite(2), lseek(2)**
>
>     These  operate  as  documented, with the exception that seek(2), write(2) and pwrite(2) are not supported beyond the end  of  the file. The file size is the size of the local storage of the SPU, which normally is 256 kilobytes.
>
>   - **mmap(2)**
>
>     Mapping mem into the process address space gives access  to  the SPU  local  storage  within  the  process  address  space.  Only MAP\_SHARED mappings are allowed.
>
> - `/mbox`
>
>   The first SPU to CPU communication mailbox. This file is read-only  and can  be  read  in  units of 32 bits.  The file can only be used in non- blocking mode and it even poll() will not block on  it.   The  possible operations on an open mbox file are:
>
>   - **read(2)**
>
>     If  a  count smaller than four is requested, read returns -1 and sets errno to EINVAL.  If there is no data available in the mail box,  the  return  value  is set to -1 and errno becomes EAGAIN. When data has been read successfully, four bytes are  placed  in the data buffer and the value four is returned.
>
> - `/ibox`
>
>   The  second  SPU  to CPU communication mailbox. This file is similar to the first mailbox file, but can be read in blocking I/O mode,  and  the poll  family of system calls can be used to wait for it.  The  possible operations on an open ibox file are:
>
>   - **read(2)**
>
>     If a count smaller than four is requested, read returns  -1  and sets errno to EINVAL.  If there is no data available in the mail box and the file descriptor has been opened with O\_NONBLOCK, the return value is set to -1 and errno becomes EAGAIN.
>
>     If  there  is  no  data  available  in the mail box and the file descriptor has been opened without  O\_NONBLOCK,  the  call  will block  until  the  SPU  writes to its interrupt mailbox channel. When data has been read successfully, four bytes are  placed  in the data buffer and the value four is returned.
>
>   - **poll(2)**
>
>     Poll  on  the  ibox  file returns (POLLIN \| POLLRDNORM) whenever data is available for reading.
>
> - `/wbox`
>
>   The CPU to SPU communation mailbox. It is write-only and can be written in  units  of  32  bits. If the mailbox is full, write() will block and poll can be used to wait for it becoming  empty  again.   The  possible operations  on  an open wbox file are: write(2) If a count smaller than four is requested, write returns -1 and sets errno to EINVAL.  If there is  no space available in the mail box and the file descriptor has been opened with O\_NONBLOCK, the return value is set to -1 and errno becomes EAGAIN.
>
>   If  there is no space available in the mail box and the file descriptor has been opened without O\_NONBLOCK, the call will block until  the  SPU reads  from  its PPE mailbox channel.  When data has been read success- fully, four bytes are placed in the data buffer and the value  four  is returned.
>
>   - **poll(2)**
>
>     Poll  on  the  ibox file returns (POLLOUT \| POLLWRNORM) whenever space is available for writing.
>
> - `/mbox_stat, /ibox_stat, /wbox_stat`
>
>   Read-only files that contain the length of the current queue, i.e.  how many  words  can  be  read  from  mbox or ibox or how many words can be written to wbox without blocking.  The files can be read only in 4-byte units  and  return  a  big-endian  binary integer number.  The possible operations on an open `*box_stat` file are:
>
>   - **read(2)**
>
>     If a count smaller than four is requested, read returns  -1  and sets errno to EINVAL.  Otherwise, a four byte value is placed in the data buffer, containing the number of elements that  can  be read  from  (for  mbox\_stat  and  ibox\_stat)  or written to (for wbox\_stat) the respective mail box without blocking or resulting in EAGAIN.
>
> - `/npc, /decr, /decr_status, /spu_tag_mask, /event_mask, /srr0`
>
>   Internal  registers  of  the SPU. The representation is an ASCII string with the numeric value of the next instruction to  be  executed.  These can  be  used in read/write mode for debugging, but normal operation of programs should not rely on them because access to any of  them  except npc requires an SPU context save and is therefore very inefficient.
>
>   The contents of these files are:
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>
>   npc
>
>   </td>
>   <td>
>
>
>
>   Next Program Counter
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>
>   decr
>
>   </td>
>   <td>
>
>
>
>   SPU Decrementer
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>
>   decr\_status
>
>   </td>
>   <td>
>
>
>
>   Decrementer Status
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>
>   spu\_tag\_mask
>
>   </td>
>   <td>
>
>
>
>   MFC tag mask for SPU DMA
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>
>   event\_mask
>
>   </td>
>   <td>
>
>
>
>   Event mask for SPU interrupts
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>
>   srr0
>
>   </td>
>   <td>
>
>
>
>   Interrupt Return address register
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   The   possible   operations   on   an   open  npc,  decr,  decr\_status, spu\_tag\_mask, event\_mask or srr0 file are:
>
>   - **read(2)**
>
>     When the count supplied to the read call  is  shorter  than  the required  length for the pointer value plus a newline character, subsequent reads from the same file descriptor  will  result  in completing  the string, regardless of changes to the register by a running SPU task.  When a complete string has been  read,  all subsequent read operations will return zero bytes and a new file descriptor needs to be opened to read the value again.
>
>   - **write(2)**
>
>     A write operation on the file results in setting the register to the  value  given  in  the string. The string is parsed from the beginning to the first non-numeric character or the end  of  the buffer.  Subsequent writes to the same file descriptor overwrite the previous setting.
>
> - `/fpcr`
>
>   This file gives access to the Floating Point Status and Control  Regis- ter as a four byte long file. The operations on the fpcr file are:
>
>   - **read(2)**
>
>     If  a  count smaller than four is requested, read returns -1 and sets errno to EINVAL.  Otherwise, a four byte value is placed in the data buffer, containing the current value of the fpcr regis- ter.
>
>   - **write(2)**
>
>     If a count smaller than four is requested, write returns -1  and sets  errno  to  EINVAL.  Otherwise, a four byte value is copied from the data buffer, updating the value of the fpcr register.
>
> - `/signal1, /signal2`
>
>   The two signal notification channels of an SPU.  These  are  read-write files  that  operate  on  a 32 bit word.  Writing to one of these files triggers an interrupt on the SPU.  The  value  written  to  the  signal files can be read from the SPU through a channel read or from host user space through the file.  After the value has been read by the  SPU,  it is  reset  to zero.  The possible operations on an open signal1 or sig- nal2 file are:
>
>   - **read(2)**
>
>     If a count smaller than four is requested, read returns  -1  and sets errno to EINVAL.  Otherwise, a four byte value is placed in the data buffer, containing the current value of  the  specified signal notification register.
>
>   - **write(2)**
>
>     If  a count smaller than four is requested, write returns -1 and sets errno to EINVAL.  Otherwise, a four byte  value  is  copied from the data buffer, updating the value of the specified signal notification register.  The signal  notification  register  will either be replaced with the input data or will be updated to the bitwise OR of the old value and the input data, depending on the contents  of  the  signal1\_type,  or  signal2\_type respectively, file.
>
> - `/signal1_type, /signal2_type`
>
>   These two files change the behavior of the signal1 and signal2  notifi- cation  files.  The  contain  a numerical ASCII string which is read as either "1" or "0".  In mode 0 (overwrite), the  hardware  replaces  the contents of the signal channel with the data that is written to it.  in mode 1 (logical OR), the hardware accumulates the bits that are  subse- quently written to it.  The possible operations on an open signal1\_type or signal2\_type file are:
>
>   - **read(2)**
>
>     When the count supplied to the read call  is  shorter  than  the required  length  for the digit plus a newline character, subse- quent reads from the same file descriptor will  result  in  com- pleting  the  string.  When a complete string has been read, all subsequent read operations will return zero bytes and a new file descriptor needs to be opened to read the value again.
>
>   - **write(2)**
>
>     A write operation on the file results in setting the register to the value given in the string. The string  is  parsed  from  the beginning  to  the first non-numeric character or the end of the buffer.  Subsequent writes to the same file descriptor overwrite the previous setting.

<a id="rst-examples"></a>

## Examples

> - **/etc/fstab entry**
>
>   none      /spu      spufs     gid=spu   0    0

<a id="rst-authors"></a>

## Authors

> Arnd  Bergmann  &lt;[arndb@de.ibm.com](<mailto:arndb@de.ibm.com>)&gt;,  Mark  Nutter &lt;[mnutter@us.ibm.com](<mailto:mnutter@us.ibm.com>)&gt;, Ulrich Weigand &lt;[Ulrich.Weigand@de.ibm.com](<mailto:Ulrich.Weigand@de.ibm.com>)&gt;

<a id="rst-see-also"></a>

## See Also

> capabilities(7), close(2), spu\_create(2), spu\_run(2), spufs(7)

---

# XFS Filesystem Documentation

_Peios Kernel / Internals / Filesystems / xfs_

> Reference for XFS Filesystem Documentation.

<a id="rst-xfs-filesystem-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1. [XFS Logging Design](</kernel/internals/filesystems/xfs/xfs-delayed-logging-design.md>)
2. [XFS Maintainer Entry Profile](</kernel/internals/filesystems/xfs/xfs-maintainer-entry-profile.md>)
3. [XFS Self Describing Metadata](</kernel/internals/filesystems/xfs/xfs-self-describing-metadata.md>)
4. [XFS Online Fsck Design](</kernel/internals/filesystems/xfs/xfs-online-fsck-design.md>)

---

# XFS Logging Design

_Peios Kernel / Internals / Filesystems / xfs_

> This document describes the design and algorithms that the XFS journalling subsystem is based on. This document describes the design and algorithms that the XFS journalling subsystem is based on so that readers may familiarize themselves…

<a id="rst-xfs-logging-design"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-preamble"></a>

## Preamble

This document describes the design and algorithms that the XFS journalling subsystem is based on. This document describes the design and algorithms that the XFS journalling subsystem is based on so that readers may familiarize themselves with the general concepts of how transaction processing in XFS works.

We begin with an overview of transactions in XFS, followed by describing how transaction reservations are structured and accounted, and then move into how we guarantee forwards progress for long running transactions with finite initial reservations bounds. At this point we need to explain how relogging works. With the basic concepts covered, the design of the delayed logging mechanism is documented.

<a id="rst-introduction"></a>

## Introduction

XFS uses Write Ahead Logging for ensuring changes to the filesystem metadata are atomic and recoverable. For reasons of space and time efficiency, the logging mechanisms are varied and complex, combining intents, logical and physical logging mechanisms to provide the necessary recovery guarantees the filesystem requires.

Some objects, such as inodes and dquots, are logged in logical format where the details logged are made up of the changes to in-core structures rather than on-disk structures. Other objects - typically buffers - have their physical changes logged. Long running atomic modifications have individual changes chained together by intents, ensuring that journal recovery can restart and finish an operation that was only partially done when the system stopped functioning.

The reason for these differences is to keep the amount of log space and CPU time required to process objects being modified as small as possible and hence the logging overhead as low as possible. Some items are very frequently modified, and some parts of objects are more frequently modified than others, so keeping the overhead of metadata logging low is of prime importance.

The method used to log an item or chain modifications together isn't particularly important in the scope of this document. It suffices to know that the method used for logging a particular object or chaining modifications together are different and are dependent on the object and/or modification being performed. The logging subsystem only cares that certain specific rules are followed to guarantee forwards progress and prevent deadlocks.

<a id="rst-transactions-in-xfs"></a>

## Transactions in XFS

XFS has two types of high level transactions, defined by the type of log space reservation they take. These are known as "one shot" and "permanent" transactions. Permanent transaction reservations can take reservations that span commit boundaries, whilst "one shot" transactions are for a single atomic modification.

The type and size of reservation must be matched to the modification taking place.  This means that permanent transactions can be used for one-shot modifications, but one-shot reservations cannot be used for permanent transactions.

In the code, a one-shot transaction pattern looks somewhat like this:



```text
tp = xfs_trans_alloc(<reservation>)
<lock items>
<join item to transaction>
<do modification>
xfs_trans_commit(tp);
```

As items are modified in the transaction, the dirty regions in those items are tracked via the transaction handle.  Once the transaction is committed, all resources joined to it are released, along with the remaining unused reservation space that was taken at the transaction allocation time.

In contrast, a permanent transaction is made up of multiple linked individual transactions, and the pattern looks like this:



```text
tp = xfs_trans_alloc(<reservation>)
xfs_ilock(ip, XFS_ILOCK_EXCL)

loop {
        xfs_trans_ijoin(tp, 0);
        <do modification>
        xfs_trans_log_inode(tp, ip);
        xfs_trans_roll(&tp);
}

xfs_trans_commit(tp);
xfs_iunlock(ip, XFS_ILOCK_EXCL);
```

While this might look similar to a one-shot transaction, there is an important difference: xfs_trans_roll() performs a specific operation that links two transactions together:



```text
ntp = xfs_trans_dup(tp);
xfs_trans_commit(tp);
xfs_trans_reserve(ntp);
```

This results in a series of "rolling transactions" where the inode is locked across the entire chain of transactions.  Hence while this series of rolling transactions is running, nothing else can read from or write to the inode and this provides a mechanism for complex changes to appear atomic from an external observer's point of view.

It is important to note that a series of rolling transactions in a permanent transaction does not form an atomic change in the journal. While each individual modification is atomic, the chain is *not atomic*. If we crash half way through, then recovery will only replay up to the last transactional modification the loop made that was committed to the journal.

This affects long running permanent transactions in that it is not possible to predict how much of a long running operation will actually be recovered because there is no guarantee of how much of the operation reached stale storage. Hence if a long running operation requires multiple transactions to fully complete, the high level operation must use intents and deferred operations to guarantee recovery can complete the operation once the first transactions is persisted in the on-disk journal.

<a id="rst-transactions-are-asynchronous"></a>

## Transactions are Asynchronous

In XFS, all high level transactions are asynchronous by default. This means that xfs_trans_commit() does not guarantee that the modification has been committed to stable storage when it returns. Hence when a system crashes, not all the completed transactions will be replayed during recovery.

However, the logging subsystem does provide global ordering guarantees, such that if a specific change is seen after recovery, all metadata modifications that were committed prior to that change will also be seen.

For single shot operations that need to reach stable storage immediately, or ensuring that a long running permanent transaction is fully committed once it is complete, we can explicitly tag a transaction as synchronous. This will trigger a "log force" to flush the outstanding committed transactions to stable storage in the journal and wait for that to complete.

Synchronous transactions are rarely used, however, because they limit logging throughput to the IO latency limitations of the underlying storage. Instead, we tend to use log forces to ensure modifications are on stable storage only when a user operation requires a synchronisation point to occur (e.g. fsync).

<a id="rst-transaction-reservations"></a>

## Transaction Reservations

It has been mentioned a number of times now that the logging subsystem needs to provide a forwards progress guarantee so that no modification ever stalls because it can't be written to the journal due to a lack of space in the journal. This is achieved by the transaction reservations that are made when a transaction is first allocated. For permanent transactions, these reservations are maintained as part of the transaction rolling mechanism.

A transaction reservation provides a guarantee that there is physical log space available to write the modification into the journal before we start making modifications to objects and items. As such, the reservation needs to be large enough to take into account the amount of metadata that the change might need to log in the worst case. This means that if we are modifying a btree in the transaction, we have to reserve enough space to record a full leaf-to-root split of the btree. As such, the reservations are quite complex because we have to take into account all the hidden changes that might occur.

For example, a user data extent allocation involves allocating an extent from free space, which modifies the free space trees. That's two btrees.  Inserting the extent into the inode's extent map might require a split of the extent map btree, which requires another allocation that can modify the free space trees again.  Then we might have to update reverse mappings, which modifies yet another btree which might require more space. And so on.  Hence the amount of metadata that a "simple" operation can modify can be quite large.

This "worst case" calculation provides us with the static "unit reservation" for the transaction that is calculated at mount time. We must guarantee that the log has this much space available before the transaction is allowed to proceed so that when we come to write the dirty metadata into the log we don't run out of log space half way through the write.

For one-shot transactions, a single unit space reservation is all that is required for the transaction to proceed. For permanent transactions, however, we also have a "log count" that affects the size of the reservation that is to be made.

While a permanent transaction can get by with a single unit of space reservation, it is somewhat inefficient to do this as it requires the transaction rolling mechanism to re-reserve space on every transaction roll. We know from the implementation of the permanent transactions how many transaction rolls are likely for the common modifications that need to be made.

For example, an inode allocation is typically two transactions - one to physically allocate a free inode chunk on disk, and another to allocate an inode from an inode chunk that has free inodes in it.  Hence for an inode allocation transaction, we might set the reservation log count to a value of 2 to indicate that the common/fast path transaction will commit two linked transactions in a chain. Each time a permanent transaction rolls, it consumes an entire unit reservation.

Hence when the permanent transaction is first allocated, the log space reservation is increased from a single unit reservation to multiple unit reservations. That multiple is defined by the reservation log count, and this means we can roll the transaction multiple times before we have to re-reserve log space when we roll the transaction. This ensures that the common modifications we make only need to reserve log space once.

If the log count for a permanent transaction reaches zero, then it needs to re-reserve physical space in the log. This is somewhat complex, and requires an understanding of how the log accounts for space that has been reserved.

<a id="rst-log-space-accounting"></a>

## Log Space Accounting

The position in the log is typically referred to as a Log Sequence Number (LSN). The log is circular, so the positions in the log are defined by the combination of a cycle number - the number of times the log has been overwritten - and the offset into the log.  A LSN carries the cycle in the upper 32 bits and the offset in the lower 32 bits. The offset is in units of "basic blocks" (512 bytes). Hence we can do relatively simple LSN based math to keep track of available space in the log.

Log space accounting is done via a pair of constructs called "grant heads".  The position of the grant heads is an absolute value, so the amount of space available in the log is defined by the distance between the position of the grant head and the current log tail. That is, how much space can be reserved/consumed before the grant heads would fully wrap the log and overtake the tail position.

The first grant head is the "reserve" head. This tracks the byte count of the reservations currently held by active transactions. It is a purely in-memory accounting of the space reservation and, as such, actually tracks byte offsets into the log rather than basic blocks. Hence it technically isn't using LSNs to represent the log position, but it is still treated like a split \{cycle,offset\} tuple for the purposes of tracking reservation space.

The reserve grant head is used to accurately account for exact transaction reservations amounts and the exact byte count that modifications actually make and need to write into the log. The reserve head is used to prevent new transactions from taking new reservations when the head reaches the current tail. It will block new reservations in a FIFO queue and as the log tail moves forward it will wake them in order once sufficient space is available. This FIFO mechanism ensures no transaction is starved of resources when log space shortages occur.

The other grant head is the "write" head. Unlike the reserve head, this grant head contains an LSN and it tracks the physical space usage in the log. While this might sound like it is accounting the same state as the reserve grant head - and it mostly does track exactly the same location as the reserve grant head - there are critical differences in behaviour between them that provides the forwards progress guarantees that rolling permanent transactions require.

These differences when a permanent transaction is rolled and the internal "log count" reaches zero and the initial set of unit reservations have been exhausted. At this point, we still require a log space reservation to continue the next transaction in the sequeunce, but we have none remaining. We cannot sleep during the transaction commit process waiting for new log space to become available, as we may end up on the end of the FIFO queue and the items we have locked while we sleep could end up pinning the tail of the log before there is enough free space in the log to fulfill all of the pending reservations and then wake up transaction commit in progress.

To take a new reservation without sleeping requires us to be able to take a reservation even if there is no reservation space currently available. That is, we need to be able to *overcommit* the log reservation space. As has already been detailed, we cannot overcommit physical log space. However, the reserve grant head does not track physical space - it only accounts for the amount of reservations we currently have outstanding. Hence if the reserve head passes over the tail of the log all it means is that new reservations will be throttled immediately and remain throttled until the log tail is moved forward far enough to remove the overcommit and start taking new reservations. In other words, we can overcommit the reserve head without violating the physical log head and tail rules.

As a result, permanent transactions only "regrant" reservation space during xfs_trans_commit() calls, while the physical log space reservation - tracked by the write head - is then reserved separately by a call to xfs_log_reserve() after the commit completes. Once the commit completes, we can sleep waiting for physical log space to be reserved from the write grant head, but only if one critical rule has been observed:



```text
Code using permanent reservations must always log the items they hold
locked across each transaction they roll in the chain.
```

"Re-logging" the locked items on every transaction roll ensures that the items attached to the transaction chain being rolled are always relocated to the physical head of the log and so do not pin the tail of the log. If a locked item pins the tail of the log when we sleep on the write reservation, then we will deadlock the log as we cannot take the locks needed to write back that item and move the tail of the log forwards to free up write grant space. Re-logging the locked items avoids this deadlock and guarantees that the log reservation we are making cannot self-deadlock.

If all rolling transactions obey this rule, then they can all make forwards progress independently because nothing will block the progress of the log tail moving forwards and hence ensuring that write grant space is always (eventually) made available to permanent transactions no matter how many times they roll.

<a id="rst-re-logging-explained"></a>

## Re-logging Explained

XFS allows multiple separate modifications to a single object to be carried in the log at any given time.  This allows the log to avoid needing to flush each change to disk before recording a new change to the object. XFS does this via a method called "re-logging". Conceptually, this is quite simple - all it requires is that any new change to the object is recorded with a *new copy* of all the existing changes in the new transaction that is written to the log.

That is, if we have a sequence of changes A through to F, and the object was written to disk after change D, we would see in the log the following series of transactions, their contents and the log sequence number (LSN) of the transaction:



```text
Transaction             Contents        LSN
   A                       A               X
   B                      A+B             X+n
   C                     A+B+C           X+n+m
   D                    A+B+C+D         X+n+m+o
    <object written to disk>
   E                       E               Y (> X+n+m+o)
   F                      E+F             Y+p
```

In other words, each time an object is relogged, the new transaction contains the aggregation of all the previous changes currently held only in the log.

This relogging technique allows objects to be moved forward in the log so that an object being relogged does not prevent the tail of the log from ever moving forward.  This can be seen in the table above by the changing (increasing) LSN of each subsequent transaction, and it's the technique that allows us to implement long-running, multiple-commit permanent transactions.

A typical example of a rolling transaction is the removal of extents from an inode which can only be done at a rate of two extents per transaction because of reservation size limitations. Hence a rolling extent removal transaction keeps relogging the inode and btree buffers as they get modified in each removal operation. This keeps them moving forward in the log as the operation progresses, ensuring that current operation never gets blocked by itself if the log wraps around.

Hence it can be seen that the relogging operation is fundamental to the correct working of the XFS journalling subsystem. From the above description, most people should be able to see why the XFS metadata operations writes so much to the log - repeated operations to the same objects write the same changes to the log over and over again. Worse is the fact that objects tend to get dirtier as they get relogged, so each subsequent transaction is writing more metadata into the log.

It should now also be obvious how relogging and asynchronous transactions go hand in hand. That is, transactions don't get written to the physical journal until either a log buffer is filled (a log buffer can hold multiple transactions) or a synchronous operation forces the log buffers holding the transactions to disk. This means that XFS is doing aggregation of transactions in memory - batching them, if you like - to minimise the impact of the log IO on transaction throughput.

The limitation on asynchronous transaction throughput is the number and size of log buffers made available by the log manager. By default there are 8 log buffers available and the size of each is 32kB - the size can be increased up to 256kB by use of a mount option.

Effectively, this gives us the maximum bound of outstanding metadata changes that can be made to the filesystem at any point in time - if all the log buffers are full and under IO, then no more transactions can be committed until the current batch completes. It is now common for a single current CPU core to be to able to issue enough transactions to keep the log buffers full and under IO permanently. Hence the XFS journalling subsystem can be considered to be IO bound.

<a id="rst-delayed-logging-concepts"></a>

## Delayed Logging: Concepts

The key thing to note about the asynchronous logging combined with the relogging technique XFS uses is that we can be relogging changed objects multiple times before they are committed to disk in the log buffers. If we return to the previous relogging example, it is entirely possible that transactions A through D are committed to disk in the same log buffer.

That is, a single log buffer may contain multiple copies of the same object, but only one of those copies needs to be there - the last one "D", as it contains all the changes from the previous changes. In other words, we have one necessary copy in the log buffer, and three stale copies that are simply wasting space. When we are doing repeated operations on the same set of objects, these "stale objects" can be over 90% of the space used in the log buffers. It is clear that reducing the number of stale objects written to the log would greatly reduce the amount of metadata we write to the log, and this is the fundamental goal of delayed logging.

From a conceptual point of view, XFS is already doing relogging in memory (where memory == log buffer), only it is doing it extremely inefficiently. It is using logical to physical formatting to do the relogging because there is no infrastructure to keep track of logical changes in memory prior to physically formatting the changes in a transaction to the log buffer. Hence we cannot avoid accumulating stale objects in the log buffers.

Delayed logging is the name we've given to keeping and tracking transactional changes to objects in memory outside the log buffer infrastructure. Because of the relogging concept fundamental to the XFS journalling subsystem, this is actually relatively easy to do - all the changes to logged items are already tracked in the current infrastructure. The big problem is how to accumulate them and get them to the log in a consistent, recoverable manner. Describing the problems and how they have been solved is the focus of this document.

One of the key changes that delayed logging makes to the operation of the journalling subsystem is that it disassociates the amount of outstanding metadata changes from the size and number of log buffers available. In other words, instead of there only being a maximum of 2MB of transaction changes not written to the log at any point in time, there may be a much greater amount being accumulated in memory. Hence the potential for loss of metadata on a crash is much greater than for the existing logging mechanism.

It should be noted that this does not change the guarantee that log recovery will result in a consistent filesystem. What it does mean is that as far as the recovered filesystem is concerned, there may be many thousands of transactions that simply did not occur as a result of the crash. This makes it even more important that applications that care about their data use fsync() where they need to ensure application level data integrity is maintained.

It should be noted that delayed logging is not an innovative new concept that warrants rigorous proofs to determine whether it is correct or not. The method of accumulating changes in memory for some period before writing them to the log is used effectively in many filesystems including ext3 and ext4. Hence no time is spent in this document trying to convince the reader that the concept is sound. Instead it is simply considered a "solved problem" and as such implementing it in XFS is purely an exercise in software engineering.

The fundamental requirements for delayed logging in XFS are simple:

> 1. Reduce the amount of metadata written to the log by at least an order of magnitude.
>
> 2. Supply sufficient statistics to validate Requirement \#1.
>
> 3. Supply sufficient new tracing infrastructure to be able to debug problems with the new code.
>
> 4. No on-disk format change (metadata or log format).
>
> 5. Enable and disable with a mount option.
>
> 6. No performance regressions for synchronous transaction workloads.

<a id="rst-delayed-logging-design"></a>

## Delayed Logging: Design

<a id="rst-storing-changes"></a>

### Storing Changes

The problem with accumulating changes at a logical level (i.e. just using the existing log item dirty region tracking) is that when it comes to writing the changes to the log buffers, we need to ensure that the object we are formatting is not changing while we do this. This requires locking the object to prevent concurrent modification. Hence flushing the logical changes to the log would require us to lock every object, format them, and then unlock them again.

This introduces lots of scope for deadlocks with transactions that are already running. For example, a transaction has object A locked and modified, but needs the delayed logging tracking lock to commit the transaction. However, the flushing thread has the delayed logging tracking lock already held, and is trying to get the lock on object A to flush it to the log buffer. This appears to be an unsolvable deadlock condition, and it was solving this problem that was the barrier to implementing delayed logging for so long.

The solution is relatively simple - it just took a long time to recognise it. Put simply, the current logging code formats the changes to each item into an vector array that points to the changed regions in the item. The log write code simply copies the memory these vectors point to into the log buffer during transaction commit while the item is locked in the transaction. Instead of using the log buffer as the destination of the formatting code, we can use an allocated memory buffer big enough to fit the formatted vector.

If we then copy the vector into the memory buffer and rewrite the vector to point to the memory buffer rather than the object itself, we now have a copy of the changes in a format that is compatible with the log buffer writing code. that does not require us to lock the item to access. This formatting and rewriting can all be done while the object is locked during transaction commit, resulting in a vector that is transactionally consistent and can be accessed without needing to lock the owning item.

Hence we avoid the need to lock items when we need to flush outstanding asynchronous transactions to the log. The differences between the existing formatting method and the delayed logging formatting can be seen in the diagram below.

Current format log vector:



```text
Object    +---------------------------------------------+
Vector 1      +----+
Vector 2                    +----+
Vector 3                                   +----------+
```

After formatting:



```text
Log Buffer    +-V1-+-V2-+----V3----+
```

Delayed logging vector:



```text
Object    +---------------------------------------------+
Vector 1      +----+
Vector 2                    +----+
Vector 3                                   +----------+
```

After formatting:



```text
Memory Buffer +-V1-+-V2-+----V3----+
Vector 1      +----+
Vector 2           +----+
Vector 3                +----------+
```

The memory buffer and associated vector need to be passed as a single object, but still need to be associated with the parent object so if the object is relogged we can replace the current memory buffer with a new memory buffer that contains the latest changes.

The reason for keeping the vector around after we've formatted the memory buffer is to support splitting vectors across log buffer boundaries correctly. If we don't keep the vector around, we do not know where the region boundaries are in the item, so we'd need a new encapsulation method for regions in the log buffer writing (i.e. double encapsulation). This would be an on-disk format change and as such is not desirable.  It also means we'd have to write the log region headers in the formatting stage, which is problematic as there is per region state that needs to be placed into the headers during the log write.

Hence we need to keep the vector, but by attaching the memory buffer to it and rewriting the vector addresses to point at the memory buffer we end up with a self-describing object that can be passed to the log buffer write code to be handled in exactly the same manner as the existing log vectors are handled. Hence we avoid needing a new on-disk format to handle items that have been relogged in memory.

<a id="rst-tracking-changes"></a>

### Tracking Changes

Now that we can record transactional changes in memory in a form that allows them to be used without limitations, we need to be able to track and accumulate them so that they can be written to the log at some later point in time.  The log item is the natural place to store this vector and buffer, and also makes sense to be the object that is used to track committed objects as it will always exist once the object has been included in a transaction.

The log item is already used to track the log items that have been written to the log but not yet written to disk. Such log items are considered "active" and as such are stored in the Active Item List (AIL) which is a LSN-ordered double linked list. Items are inserted into this list during log buffer IO completion, after which they are unpinned and can be written to disk. An object that is in the AIL can be relogged, which causes the object to be pinned again and then moved forward in the AIL when the log buffer IO completes for that transaction.

Essentially, this shows that an item that is in the AIL can still be modified and relogged, so any tracking must be separate to the AIL infrastructure. As such, we cannot reuse the AIL list pointers for tracking committed items, nor can we store state in any field that is protected by the AIL lock. Hence the committed item tracking needs its own locks, lists and state fields in the log item.

Similar to the AIL, tracking of committed items is done through a new list called the Committed Item List (CIL).  The list tracks log items that have been committed and have formatted memory buffers attached to them. It tracks objects in transaction commit order, so when an object is relogged it is removed from its place in the list and re-inserted at the tail. This is entirely arbitrary and done to make it easy for debugging - the last items in the list are the ones that are most recently modified. Ordering of the CIL is not necessary for transactional integrity (as discussed in the next section) so the ordering is done for convenience/sanity of the developers.

<a id="rst-delayed-logging-checkpoints"></a>

### Delayed Logging: Checkpoints

When we have a log synchronisation event, commonly known as a "log force", all the items in the CIL must be written into the log via the log buffers. We need to write these items in the order that they exist in the CIL, and they need to be written as an atomic transaction. The need for all the objects to be written as an atomic transaction comes from the requirements of relogging and log replay - all the changes in all the objects in a given transaction must either be completely replayed during log recovery, or not replayed at all. If a transaction is not replayed because it is not complete in the log, then no later transactions should be replayed, either.

To fulfill this requirement, we need to write the entire CIL in a single log transaction. Fortunately, the XFS log code has no fixed limit on the size of a transaction, nor does the log replay code. The only fundamental limit is that the transaction cannot be larger than just under half the size of the log.  The reason for this limit is that to find the head and tail of the log, there must be at least one complete transaction in the log at any given time. If a transaction is larger than half the log, then there is the possibility that a crash during the write of a such a transaction could partially overwrite the only complete previous transaction in the log. This will result in a recovery failure and an inconsistent filesystem and hence we must enforce the maximum size of a checkpoint to be slightly less than a half the log.

Apart from this size requirement, a checkpoint transaction looks no different to any other transaction - it contains a transaction header, a series of formatted log items and a commit record at the tail. From a recovery perspective, the checkpoint transaction is also no different - just a lot bigger with a lot more items in it. The worst case effect of this is that we might need to tune the recovery transaction object hash size.

Because the checkpoint is just another transaction and all the changes to log items are stored as log vectors, we can use the existing log buffer writing code to write the changes into the log. To do this efficiently, we need to minimise the time we hold the CIL locked while writing the checkpoint transaction. The current log write code enables us to do this easily with the way it separates the writing of the transaction contents (the log vectors) from the transaction commit record, but tracking this requires us to have a per-checkpoint context that travels through the log write process through to checkpoint completion.

Hence a checkpoint has a context that tracks the state of the current checkpoint from initiation to checkpoint completion. A new context is initiated at the same time a checkpoint transaction is started. That is, when we remove all the current items from the CIL during a checkpoint operation, we move all those changes into the current checkpoint context. We then initialise a new context and attach that to the CIL for aggregation of new transactions.

This allows us to unlock the CIL immediately after transfer of all the committed items and effectively allows new transactions to be issued while we are formatting the checkpoint into the log. It also allows concurrent checkpoints to be written into the log buffers in the case of log force heavy workloads, just like the existing transaction commit code does. This, however, requires that we strictly order the commit records in the log so that checkpoint sequence order is maintained during log replay.

To ensure that we can be writing an item into a checkpoint transaction at the same time another transaction modifies the item and inserts the log item into the new CIL, then checkpoint transaction commit code cannot use log items to store the list of log vectors that need to be written into the transaction. Hence log vectors need to be able to be chained together to allow them to be detached from the log items. That is, when the CIL is flushed the memory buffer and log vector attached to each log item needs to be attached to the checkpoint context so that the log item can be released. In diagrammatic form, the CIL would look like this before the flush:



```text
CIL Head
   |
   V
Log Item <-> log vector 1       -> memory buffer
   |                            -> vector array
   V
Log Item <-> log vector 2       -> memory buffer
   |                            -> vector array
   V
......
   |
   V
Log Item <-> log vector N-1     -> memory buffer
   |                            -> vector array
   V
Log Item <-> log vector N       -> memory buffer
                                -> vector array
```

And after the flush the CIL head is empty, and the checkpoint context log vector list would look like:



```text
Checkpoint Context
   |
   V
log vector 1    -> memory buffer
   |            -> vector array
   |            -> Log Item
   V
log vector 2    -> memory buffer
   |            -> vector array
   |            -> Log Item
   V
......
   |
   V
log vector N-1  -> memory buffer
   |            -> vector array
   |            -> Log Item
   V
log vector N    -> memory buffer
                -> vector array
                -> Log Item
```

Once this transfer is done, the CIL can be unlocked and new transactions can start, while the checkpoint flush code works over the log vector chain to commit the checkpoint.

Once the checkpoint is written into the log buffers, the checkpoint context is attached to the log buffer that the commit record was written to along with a completion callback. Log IO completion will call that callback, which can then run transaction committed processing for the log items (i.e. insert into AIL and unpin) in the log vector chain and then free the log vector chain and checkpoint context.

Discussion Point: I am uncertain as to whether the log item is the most efficient way to track vectors, even though it seems like the natural way to do it. The fact that we walk the log items (in the CIL) just to chain the log vectors and break the link between the log item and the log vector means that we take a cache line hit for the log item list modification, then another for the log vector chaining. If we track by the log vectors, then we only need to break the link between the log item and the log vector, which means we should dirty only the log item cachelines. Normally I wouldn't be concerned about one vs two dirty cachelines except for the fact I've seen upwards of 80,000 log vectors in one checkpoint transaction. I'd guess this is a "measure and compare" situation that can be done after a working and reviewed implementation is in the dev tree....

<a id="rst-delayed-logging-checkpoint-sequencing"></a>

### Delayed Logging: Checkpoint Sequencing

One of the key aspects of the XFS transaction subsystem is that it tags committed transactions with the log sequence number of the transaction commit. This allows transactions to be issued asynchronously even though there may be future operations that cannot be completed until that transaction is fully committed to the log. In the rare case that a dependent operation occurs (e.g. re-using a freed metadata extent for a data extent), a special, optimised log force can be issued to force the dependent transaction to disk immediately.

To do this, transactions need to record the LSN of the commit record of the transaction. This LSN comes directly from the log buffer the transaction is written into. While this works just fine for the existing transaction mechanism, it does not work for delayed logging because transactions are not written directly into the log buffers. Hence some other method of sequencing transactions is required.

As discussed in the checkpoint section, delayed logging uses per-checkpoint contexts, and as such it is simple to assign a sequence number to each checkpoint. Because the switching of checkpoint contexts must be done atomically, it is simple to ensure that each new context has a monotonically increasing sequence number assigned to it without the need for an external atomic counter - we can just take the current context sequence number and add one to it for the new context.

Then, instead of assigning a log buffer LSN to the transaction commit LSN during the commit, we can assign the current checkpoint sequence. This allows operations that track transactions that have not yet completed know what checkpoint sequence needs to be committed before they can continue. As a result, the code that forces the log to a specific LSN now needs to ensure that the log forces to a specific checkpoint.

To ensure that we can do this, we need to track all the checkpoint contexts that are currently committing to the log. When we flush a checkpoint, the context gets added to a "committing" list which can be searched. When a checkpoint commit completes, it is removed from the committing list. Because the checkpoint context records the LSN of the commit record for the checkpoint, we can also wait on the log buffer that contains the commit record, thereby using the existing log force mechanisms to execute synchronous forces.

It should be noted that the synchronous forces may need to be extended with mitigation algorithms similar to the current log buffer code to allow aggregation of multiple synchronous transactions if there are already synchronous transactions being flushed. Investigation of the performance of the current design is needed before making any decisions here.

The main concern with log forces is to ensure that all the previous checkpoints are also committed to disk before the one we need to wait for. Therefore we need to check that all the prior contexts in the committing list are also complete before waiting on the one we need to complete. We do this synchronisation in the log force code so that we don't need to wait anywhere else for such serialisation - it only matters when we do a log force.

The only remaining complexity is that a log force now also has to handle the case where the forcing sequence number is the same as the current context. That is, we need to flush the CIL and potentially wait for it to complete. This is a simple addition to the existing log forcing code to check the sequence numbers and push if required. Indeed, placing the current sequence checkpoint flush in the log force code enables the current mechanism for issuing synchronous transactions to remain untouched (i.e. commit an asynchronous transaction, then force the log at the LSN of that transaction) and so the higher level code behaves the same regardless of whether delayed logging is being used or not.

<a id="rst-delayed-logging-checkpoint-log-space-accounting"></a>

### Delayed Logging: Checkpoint Log Space Accounting

The big issue for a checkpoint transaction is the log space reservation for the transaction. We don't know how big a checkpoint transaction is going to be ahead of time, nor how many log buffers it will take to write out, nor the number of split log vector regions are going to be used. We can track the amount of log space required as we add items to the commit item list, but we still need to reserve the space in the log for the checkpoint.

A typical transaction reserves enough space in the log for the worst case space usage of the transaction. The reservation accounts for log record headers, transaction and region headers, headers for split regions, buffer tail padding, etc. as well as the actual space for all the changed metadata in the transaction. While some of this is fixed overhead, much of it is dependent on the size of the transaction and the number of regions being logged (the number of log vectors in the transaction).

An example of the differences would be logging directory changes versus logging inode changes. If you modify lots of inode cores (e.g. `chmod -R g+w *`), then there are lots of transactions that only contain an inode core and an inode log format structure. That is, two vectors totaling roughly 150 bytes. If we modify 10,000 inodes, we have about 1.5MB of metadata to write in 20,000 vectors. Each vector is 12 bytes, so the total to be logged is approximately 1.75MB. In comparison, if we are logging full directory buffers, they are typically 4KB each, so we in 1.5MB of directory buffers we'd have roughly 400 buffers and a buffer format structure for each buffer - roughly 800 vectors or 1.51MB total space.  From this, it should be obvious that a static log space reservation is not particularly flexible and is difficult to select the "optimal value" for all workloads.

Further, if we are going to use a static reservation, which bit of the entire reservation does it cover? We account for space used by the transaction reservation by tracking the space currently used by the object in the CIL and then calculating the increase or decrease in space used as the object is relogged. This allows for a checkpoint reservation to only have to account for log buffer metadata used such as log header records.

However, even using a static reservation for just the log metadata is problematic. Typically log record headers use at least 16KB of log space per 1MB of log space consumed (512 bytes per 32k) and the reservation needs to be large enough to handle arbitrary sized checkpoint transactions. This reservation needs to be made before the checkpoint is started, and we need to be able to reserve the space without sleeping.  For a 8MB checkpoint, we need a reservation of around 150KB, which is a non-trivial amount of space.

A static reservation needs to manipulate the log grant counters - we can take a permanent reservation on the space, but we still need to make sure we refresh the write reservation (the actual space available to the transaction) after every checkpoint transaction completion. Unfortunately, if this space is not available when required, then the regrant code will sleep waiting for it.

The problem with this is that it can lead to deadlocks as we may need to commit checkpoints to be able to free up log space (refer back to the description of rolling transactions for an example of this).  Hence we *must* always have space available in the log if we are to use static reservations, and that is very difficult and complex to arrange. It is possible to do, but there is a simpler way.

The simpler way of doing this is tracking the entire log space used by the items in the CIL and using this to dynamically calculate the amount of log space required by the log metadata. If this log metadata space changes as a result of a transaction commit inserting a new memory buffer into the CIL, then the difference in space required is removed from the transaction that causes the change. Transactions at this level will *always* have enough space available in their reservation for this as they have already reserved the maximal amount of log metadata space they require, and such a delta reservation will always be less than or equal to the maximal amount in the reservation.

Hence we can grow the checkpoint transaction reservation dynamically as items are added to the CIL and avoid the need for reserving and regranting log space up front. This avoids deadlocks and removes a blocking point from the checkpoint flush code.

As mentioned early, transactions can't grow to more than half the size of the log. Hence as part of the reservation growing, we need to also check the size of the reservation against the maximum allowed transaction size. If we reach the maximum threshold, we need to push the CIL to the log. This is effectively a "background flush" and is done on demand. This is identical to a CIL push triggered by a log force, only that there is no waiting for the checkpoint commit to complete. This background push is checked and executed by transaction commit code.

If the transaction subsystem goes idle while we still have items in the CIL, they will be flushed by the periodic log force issued by the xfssyncd. This log force will push the CIL to disk, and if the transaction subsystem stays idle, allow the idle log to be covered (effectively marked clean) in exactly the same manner that is done for the existing logging method. A discussion point is whether this log force needs to be done more frequently than the current rate which is once every 30s.

<a id="rst-delayed-logging-log-item-pinning"></a>

### Delayed Logging: Log Item Pinning

Currently log items are pinned during transaction commit while the items are still locked. This happens just after the items are formatted, though it could be done any time before the items are unlocked. The result of this mechanism is that items get pinned once for every transaction that is committed to the log buffers. Hence items that are relogged in the log buffers will have a pin count for every outstanding transaction they were dirtied in. When each of these transactions is completed, they will unpin the item once. As a result, the item only becomes unpinned when all the transactions complete and there are no pending transactions. Thus the pinning and unpinning of a log item is symmetric as there is a 1:1 relationship with transaction commit and log item completion.

For delayed logging, however, we have an asymmetric transaction commit to completion relationship. Every time an object is relogged in the CIL it goes through the commit process without a corresponding completion being registered. That is, we now have a many-to-one relationship between transaction commit and log item completion. The result of this is that pinning and unpinning of the log items becomes unbalanced if we retain the "pin on transaction commit, unpin on transaction completion" model.

To keep pin/unpin symmetry, the algorithm needs to change to a "pin on insertion into the CIL, unpin on checkpoint completion". In other words, the pinning and unpinning becomes symmetric around a checkpoint context. We have to pin the object the first time it is inserted into the CIL - if it is already in the CIL during a transaction commit, then we do not pin it again. Because there can be multiple outstanding checkpoint contexts, we can still see elevated pin counts, but as each checkpoint completes the pin count will retain the correct value according to its context.

Just to make matters slightly more complex, this checkpoint level context for the pin count means that the pinning of an item must take place under the CIL commit/flush lock. If we pin the object outside this lock, we cannot guarantee which context the pin count is associated with. This is because of the fact pinning the item is dependent on whether the item is present in the current CIL or not. If we don't pin the CIL first before we check and pin the object, we have a race with CIL being flushed between the check and the pin (or not pinning, as the case may be). Hence we must hold the CIL flush/commit lock to guarantee that we pin the items correctly.

<a id="rst-delayed-logging-concurrent-scalability"></a>

### Delayed Logging: Concurrent Scalability

A fundamental requirement for the CIL is that accesses through transaction commits must scale to many concurrent commits. The current transaction commit code does not break down even when there are transactions coming from 2048 processors at once. The current transaction code does not go any faster than if there was only one CPU using it, but it does not slow down either.

As a result, the delayed logging transaction commit code needs to be designed for concurrency from the ground up. It is obvious that there are serialisation points in the design - the three important ones are:

> 1. Locking out new transaction commits while flushing the CIL
>
> 2. Adding items to the CIL and updating item space accounting
>
> 3. Checkpoint commit ordering

Looking at the transaction commit and CIL flushing interactions, it is clear that we have a many-to-one interaction here. That is, the only restriction on the number of concurrent transactions that can be trying to commit at once is the amount of space available in the log for their reservations. The practical limit here is in the order of several hundred concurrent transactions for a 128MB log, which means that it is generally one per CPU in a machine.

The amount of time a transaction commit needs to hold out a flush is a relatively long period of time - the pinning of log items needs to be done while we are holding out a CIL flush, so at the moment that means it is held across the formatting of the objects into memory buffers (i.e. while memcpy()s are in progress). Ultimately a two pass algorithm where the formatting is done separately to the pinning of objects could be used to reduce the hold time of the transaction commit side.

Because of the number of potential transaction commit side holders, the lock really needs to be a sleeping lock - if the CIL flush takes the lock, we do not want every other CPU in the machine spinning on the CIL lock. Given that flushing the CIL could involve walking a list of tens of thousands of log items, it will get held for a significant time and so spin contention is a significant concern. Preventing lots of CPUs spinning doing nothing is the main reason for choosing a sleeping lock even though nothing in either the transaction commit or CIL flush side sleeps with the lock held.

It should also be noted that CIL flushing is also a relatively rare operation compared to transaction commit for asynchronous transaction workloads - only time will tell if using a read-write semaphore for exclusion will limit transaction commit concurrency due to cache line bouncing of the lock on the read side.

The second serialisation point is on the transaction commit side where items are inserted into the CIL. Because transactions can enter this code concurrently, the CIL needs to be protected separately from the above commit/flush exclusion. It also needs to be an exclusive lock but it is only held for a very short time and so a spin lock is appropriate here. It is possible that this lock will become a contention point, but given the short hold time once per transaction I think that contention is unlikely.

The final serialisation point is the checkpoint commit record ordering code that is run as part of the checkpoint commit and log force sequencing. The code path that triggers a CIL flush (i.e. whatever triggers the log force) will enter an ordering loop after writing all the log vectors into the log buffers but before writing the commit record. This loop walks the list of committing checkpoints and needs to block waiting for checkpoints to complete their commit record write. As a result it needs a lock and a wait variable. Log force sequencing also requires the same lock, list walk, and blocking mechanism to ensure completion of checkpoints.

These two sequencing operations can use the mechanism even though the events they are waiting for are different. The checkpoint commit record sequencing needs to wait until checkpoint contexts contain a commit LSN (obtained through completion of a commit record write) while log force sequencing needs to wait until previous checkpoint contexts are removed from the committing list (i.e. they've completed). A simple wait variable and broadcast wakeups (thundering herds) has been used to implement these two serialisation queues. They use the same lock as the CIL, too. If we see too much contention on the CIL lock, or too many context switches as a result of the broadcast wakeups these operations can be put under a new spinlock and given separate wait lists to reduce lock contention and the number of processes woken by the wrong event.

<a id="rst-lifecycle-changes"></a>

### Lifecycle Changes

The existing log item life cycle is as follows:



```text
1. Transaction allocate
2. Transaction reserve
3. Lock item
4. Join item to transaction
        If not already attached,
                Allocate log item
                Attach log item to owner item
        Attach log item to transaction
5. Modify item
        Record modifications in log item
6. Transaction commit
        Pin item in memory
        Format item into log buffer
        Write commit LSN into transaction
        Unlock item
        Attach transaction to log buffer

<log buffer IO dispatched>
<log buffer IO completes>

7. Transaction completion
        Mark log item committed
        Insert log item into AIL
                Write commit LSN into log item
        Unpin log item
8. AIL traversal
        Lock item
        Mark log item clean
        Flush item to disk

<item IO completion>

9. Log item removed from AIL
        Moves log tail
        Item unlocked
```

Essentially, steps 1-6 operate independently from step 7, which is also independent of steps 8-9. An item can be locked in steps 1-6 or steps 8-9 at the same time step 7 is occurring, but only steps 1-6 or 8-9 can occur at the same time. If the log item is in the AIL or between steps 6 and 7 and steps 1-6 are re-entered, then the item is relogged. Only when steps 8-9 are entered and completed is the object considered clean.

With delayed logging, there are new steps inserted into the life cycle:



```text
1. Transaction allocate
2. Transaction reserve
3. Lock item
4. Join item to transaction
        If not already attached,
                Allocate log item
                Attach log item to owner item
        Attach log item to transaction
5. Modify item
        Record modifications in log item
6. Transaction commit
        Pin item in memory if not pinned in CIL
        Format item into log vector + buffer
        Attach log vector and buffer to log item
        Insert log item into CIL
        Write CIL context sequence into transaction
        Unlock item

<next log force>

7. CIL push
        lock CIL flush
        Chain log vectors and buffers together
        Remove items from CIL
        unlock CIL flush
        write log vectors into log
        sequence commit records
        attach checkpoint context to log buffer

<log buffer IO dispatched>
<log buffer IO completes>

8. Checkpoint completion
        Mark log item committed
        Insert item into AIL
                Write commit LSN into log item
        Unpin log item
9. AIL traversal
        Lock item
        Mark log item clean
        Flush item to disk
<item IO completion>
10. Log item removed from AIL
        Moves log tail
        Item unlocked
```

From this, it can be seen that the only life cycle differences between the two logging methods are in the middle of the life cycle - they still have the same beginning and end and execution constraints. The only differences are in the committing of the log items to the log itself and the completion processing. Hence delayed logging should not introduce any constraints on log item behaviour, allocation or freeing that don't already exist.

As a result of this zero-impact "insertion" of delayed logging infrastructure and the design of the internal structures to avoid on disk format changes, we can basically switch between delayed logging and the existing mechanism with a mount option. Fundamentally, there is no reason why the log manager would not be able to swap methods automatically and transparently depending on load characteristics, but this should not be necessary if delayed logging works as designed.

---

# XFS Maintainer Entry Profile

_Peios Kernel / Internals / Filesystems / xfs_

> XFS is a well known high-performance filesystem in the Linux kernel. The aim of this project is to provide and maintain a robust and performant filesystem.

<a id="rst-xfs-maintainer-entry-profile"></a>

<a id="rst-overview"></a>

## Overview

XFS is a well known high-performance filesystem in the Linux kernel. The aim of this project is to provide and maintain a robust and performant filesystem.

Patches are generally merged to the for-next branch of the appropriate git repository. After a testing period, the for-next branch is merged to the master branch.

Kernel code are merged to the xfs-linux tree\[0\]. Userspace code are merged to the xfsprogs tree\[1\]. Test cases are merged to the xfstests tree\[2\]. Ondisk format documentation are merged to the xfs-documentation tree\[3\].

All patchsets involving XFS *must* be cc'd in their entirety to the mailing list [linux-xfs@vger.kernel.org](<mailto:linux-xfs@vger.kernel.org>).

<a id="rst-roles"></a>

## Roles

There are eight key roles in the XFS project. A person can take on multiple roles, and a role can be filled by multiple people. Anyone taking on a role is advised to check in with themselves and others on a regular basis about burnout.

- **Outside Contributor**: Anyone who sends a patch but is not involved in the XFS project on a regular basis. These folks are usually people who work on other filesystems or elsewhere in the kernel community.

- **Developer**: Someone who is familiar with the XFS codebase enough to write new code, documentation, and tests.

  Developers can often be found in the IRC channel mentioned by the `C:` entry in the kernel MAINTAINERS file.

- **Senior Developer**: A developer who is very familiar with at least some part of the XFS codebase and/or other subsystems in the kernel. These people collectively decide the long term goals of the project and nudge the community in that direction. They should help prioritize development and review work for each release cycle.

  Senior developers tend to be more active participants in the IRC channel.

- **Reviewer**: Someone (most likely also a developer) who reads code submissions to decide:

  0. Is the idea behind the contribution sound?

  1. Does the idea fit the goals of the project?

  2. Is the contribution designed correctly?

  3. Is the contribution polished?

  4. Can the contribution be tested effectively?

  Reviewers should identify themselves with an `R:` entry in the kernel and fstests MAINTAINERS files.

- **Testing Lead**: This person is responsible for setting the test coverage goals of the project, negotiating with developers to decide on new tests for new features, and making sure that developers and release managers execute on the testing.

  The testing lead should identify themselves with an `M:` entry in the XFS section of the fstests MAINTAINERS file.

- **Bug Triager**: Someone who examines incoming bug reports in just enough detail to identify the person to whom the report should be forwarded.

  The bug triagers should identify themselves with a `B:` entry in the kernel MAINTAINERS file.

- **Release Manager**: This person merges reviewed patchsets into an integration branch, tests the result locally, pushes the branch to a public git repository, and sends pull requests further upstream. The release manager is not expected to work on new feature patchsets. If a developer and a reviewer fail to reach a resolution on some point, the release manager must have the ability to intervene to try to drive a resolution.

  The release manager should identify themselves with an `M:` entry in the kernel MAINTAINERS file.

- **Community Manager**: This person calls and moderates meetings of as many XFS participants as they can get when mailing list discussions prove insufficient for collective decisionmaking. They may also serve as liaison between managers of the organizations sponsoring work on any part of XFS.

- **LTS Maintainer**: Someone who backports and tests bug fixes from upstream to the LTS kernels. There tend to be six separate LTS trees at any given time.

  The maintainer for a given LTS release should identify themselves with an `M:` entry in the MAINTAINERS file for that LTS tree. Unmaintained LTS kernels should be marked with status `S: Orphan` in that same file.

<a id="rst-submission-checklist-addendum"></a>

## Submission Checklist Addendum

Please follow these additional rules when submitting to XFS:

- Patches affecting only the filesystem itself should be based against the latest -rc or the for-next branch. These patches will be merged back to the for-next branch.

- Authors of patches touching other subsystems need to coordinate with the maintainers of XFS and the relevant subsystems to decide how to proceed with a merge.

- Any patchset changing XFS should be cc'd in its entirety to linux-xfs. Do not send partial patchsets; that makes analysis of the broader context of the changes unnecessarily difficult.

- Anyone making kernel changes that have corresponding changes to the userspace utilities should send the userspace changes as separate patchsets immediately after the kernel patchsets.

- Authors of bug fix patches are expected to use fstests\[2\] to perform an A/B test of the patch to determine that there are no regressions. When possible, a new regression test case should be written for fstests.

- Authors of new feature patchsets must ensure that fstests will have appropriate functional and input corner-case test cases for the new feature.

- When implementing a new feature, it is strongly suggested that the developers write a design document to answer the following questions:

  - **What** problem is this trying to solve?

  - **Who** will benefit from this solution, and **where** will they access it?

  - **How** will this new feature work?  This should touch on major data structures and algorithms supporting the solution at a higher level than code comments.

  - **What** userspace interfaces are necessary to build off of the new features?

  - **How** will this work be tested to ensure that it solves the problems laid out in the design document without causing new problems?

  The design document should be committed in the kernel documentation directory. It may be omitted if the feature is already well known to the community.

- Patchsets for the new tests should be submitted as separate patchsets immediately after the kernel and userspace code patchsets.

- Changes to the on-disk format of XFS must be described in the ondisk format document\[3\] and submitted as a patchset after the fstests patchsets.

- Patchsets implementing bug fixes and further code cleanups should put the bug fixes at the beginning of the series to ease backporting.

<a id="rst-key-release-cycle-dates"></a>

## Key Release Cycle Dates

Bug fixes may be sent at any time, though the release manager may decide to defer a patch when the next merge window is close.

Code submissions targeting the next merge window should be sent between -rc1 and -rc6. This gives the community time to review the changes, to suggest other changes, and for the author to retest those changes.

Code submissions also requiring changes to fs/iomap and targeting the next merge window should be sent between -rc1 and -rc4. This allows the broader kernel community adequate time to test the infrastructure changes.

<a id="rst-review-cadence"></a>

## Review Cadence

In general, please wait at least one week before pinging for feedback. To find reviewers, either consult the MAINTAINERS file, or ask developers that have Reviewed-by tags for XFS changes to take a look and offer their opinion.

<a id="rst-references"></a>

## References

\[0\] [https://git.kernel.org/pub/scm/fs/xfs/xfs-linux.git/](<https://git.kernel.org/pub/scm/fs/xfs/xfs-linux.git/>)  
\[1\] [https://git.kernel.org/pub/scm/fs/xfs/xfsprogs-dev.git/](<https://git.kernel.org/pub/scm/fs/xfs/xfsprogs-dev.git/>)  
\[2\] [https://git.kernel.org/pub/scm/fs/xfs/xfstests-dev.git/](<https://git.kernel.org/pub/scm/fs/xfs/xfstests-dev.git/>)  
\[3\] [https://git.kernel.org/pub/scm/fs/xfs/xfs-documentation.git/](<https://git.kernel.org/pub/scm/fs/xfs/xfs-documentation.git/>)

---

# XFS Online Fsck Design

_Peios Kernel / Internals / Filesystems / xfs_

> This document captures the design of the online filesystem check feature for XFS. The purpose of this document is threefold:

<a id="rst-xfs-online-fsck-design-1"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-xfs-online-fsck-design"></a>



<!-- Mapping of heading styles within this document:
Heading 1 uses "====" above and below
Heading 2 uses "===="
Heading 3 uses "----"
Heading 4 uses "````"
Heading 5 uses "^^^^"
Heading 6 uses "~~~~"
Heading 7 uses "...."

Sections are manually numbered because apparently that's what everyone
does in the kernel. -->

This document captures the design of the online filesystem check feature for XFS. The purpose of this document is threefold:

- To help kernel distributors understand exactly what the XFS online fsck feature is, and issues about which they should be aware.

- To help people reading the code to familiarize themselves with the relevant concepts and design points before they start digging into the code.

- To help developers maintaining the system by capturing the reasons supporting higher level decision making.

As the online fsck code is merged, the links in this document to topic branches will be replaced with links to code.

This document is licensed under the terms of the GNU Public License, v2. The primary author is Darrick J. Wong.

This design document is split into seven parts. Part 1 defines what fsck tools are and the motivations for writing a new one. Parts 2 and 3 present a high level overview of how online fsck process works and how it is tested to ensure correct functionality. Part 4 discusses the user interface and the intended usage modes of the new program. Parts 5 and 6 show off the high level components and how they fit together, and then present case studies of how each repair function actually works. Part 7 sums up what has been discussed so far and speculates about what else might be built atop online fsck.

<a id="rst-table-of-contents"></a>



<a id="rst-what-is-a-filesystem-check"></a>

## 1. What is a Filesystem Check?

A Unix filesystem has four main responsibilities:

- Provide a hierarchy of names through which application programs can associate arbitrary blobs of data for any length of time,

- Virtualize physical storage media across those names, and

- Retrieve the named data blobs at any time.

- Examine resource usage.

Metadata directly supporting these functions (e.g. files, directories, space mappings) are sometimes called primary metadata. Secondary metadata (e.g. reverse mapping and directory parent pointers) support operations internal to the filesystem, such as internal consistency checking and reorganization. Summary metadata, as the name implies, condense information contained in primary metadata for performance reasons.

The filesystem check (fsck) tool examines all the metadata in a filesystem to look for errors. In addition to looking for obvious metadata corruptions, fsck also cross-references different types of metadata records with each other to look for inconsistencies. People do not like losing data, so most fsck tools also contains some ability to correct any problems found. As a word of caution -- the primary goal of most Linux fsck tools is to restore the filesystem metadata to a consistent state, not to maximize the data recovered. That precedent will not be challenged here.

Filesystems of the 20th century generally lacked any redundancy in the ondisk format, which means that fsck can only respond to errors by erasing files until errors are no longer detected. More recent filesystem designs contain enough redundancy in their metadata that it is now possible to regenerate data structures when non-catastrophic errors occur; this capability aids both strategies.


<table>
<tbody>
<tr>
<td>


**Note**:

</td>
</tr>
<tr>
<td>


System administrators avoid data loss by increasing the number of separate storage systems through the creation of backups; and they avoid downtime by increasing the redundancy of each storage system through the creation of RAID arrays. fsck tools address only the first problem.

</td>
</tr>
</tbody>
</table>

<a id="rst-tldr-show-me-the-code"></a>

### TLDR; Show Me the Code\!

Kernel and userspace code has been fully merged as of October 2025.

Each kernel patchset adding an online repair function will use the same branch name across the kernel, xfsprogs, and fstests git repos.

<a id="rst-existing-tools"></a>

### Existing Tools

The online fsck tool described here will be the third tool in the history of XFS (on Linux) to check and repair filesystems. Two programs precede it:

The first program, `xfs_check`, was created as part of the XFS debugger (`xfs_db`) and can only be used with unmounted filesystems. It walks all metadata in the filesystem looking for inconsistencies in the metadata, though it lacks any ability to repair what it finds. Due to its high memory requirements and inability to repair things, this program is now deprecated and will not be discussed further.

The second program, `xfs_repair`, was created to be faster and more robust than the first program. Like its predecessor, it can only be used with unmounted filesystems. It uses extent-based in-memory data structures to reduce memory consumption, and tries to schedule readahead IO appropriately to reduce I/O waiting time while it scans the metadata of the entire filesystem. The most important feature of this tool is its ability to respond to inconsistencies in file metadata and directory tree by erasing things as needed to eliminate problems. Space usage metadata are rebuilt from the observed file metadata.

<a id="rst-problem-statement"></a>

### Problem Statement

The current XFS tools leave several problems unsolved:

1. **User programs** suddenly **lose access** to the filesystem when unexpected shutdowns occur as a result of silent corruptions in the metadata. These occur **unpredictably** and often without warning.

2. **Users** experience a **total loss of service** during the recovery period after an **unexpected shutdown** occurs.

3. **Users** experience a **total loss of service** if the filesystem is taken offline to **look for problems** proactively.

4. **Data owners** cannot **check the integrity** of their stored data without reading all of it. This may expose them to substantial billing costs when a linear media scan performed by the storage system administrator might suffice.

5. **System administrators** cannot **schedule** a maintenance window to deal with corruptions if they **lack the means** to assess filesystem health while the filesystem is online.

6. **Fleet monitoring tools** cannot **automate periodic checks** of filesystem health when doing so requires **manual intervention** and downtime.

7. **Users** can be tricked into **doing things they do not desire** when malicious actors **exploit quirks of Unicode** to place misleading names in directories.

Given this definition of the problems to be solved and the actors who would benefit, the proposed solution is a third fsck tool that acts on a running filesystem.

This new third program has three components: an in-kernel facility to check metadata, an in-kernel facility to repair metadata, and a userspace driver program to drive fsck activity on a live filesystem. `xfs_scrub` is the name of the driver program. The rest of this document presents the goals and use cases of the new fsck tool, describes its major design points in connection to those goals, and discusses the similarities and differences with existing tools.


<table>
<tbody>
<tr>
<td>


**Note**:

</td>
</tr>
<tr>
<td>


Throughout this document, the existing offline fsck tool can also be referred to by its current name "`xfs_repair`". The userspace driver program for the new online fsck tool can be referred to as "`xfs_scrub`". The kernel portion of online fsck that validates metadata is called "online scrub", and portion of the kernel that fixes metadata is called "online repair".

</td>
</tr>
</tbody>
</table>

The naming hierarchy is broken up into objects known as directories and files and the physical space is split into pieces known as allocation groups. Sharding enables better performance on highly parallel systems and helps to contain the damage when corruptions occur. The division of the filesystem into principal objects (allocation groups and inodes) means that there are ample opportunities to perform targeted checks and repairs on a subset of the filesystem.

While this is going on, other parts continue processing IO requests. Even if a piece of filesystem metadata can only be regenerated by scanning the entire system, the scan can still be done in the background while other file operations continue.

In summary, online fsck takes advantage of resource sharding and redundant metadata to enable targeted checking and repair operations while the system is running. This capability will be coupled to automatic system management so that autonomous self-healing of XFS maximizes service availability.

<a id="rst-theory-of-operation"></a>

## 2. Theory of Operation

Because it is necessary for online fsck to lock and scan live metadata objects, online fsck consists of three separate code components. The first is the userspace driver program `xfs_scrub`, which is responsible for identifying individual metadata items, scheduling work items for them, reacting to the outcomes appropriately, and reporting results to the system administrator. The second and third are in the kernel, which implements functions to check and repair each type of online fsck work item.


<table>
<tbody>
<tr>
<td>


**Note**:

</td>
</tr>
<tr>
<td>


For brevity, this document shortens the phrase "online fsck work item" to "scrub item".

</td>
</tr>
</tbody>
</table>

Scrub item types are delineated in a manner consistent with the Unix design philosophy, which is to say that each item should handle one aspect of a metadata structure, and handle it well.

<a id="rst-scope"></a>

### Scope

In principle, online fsck should be able to check and to repair everything that the offline fsck program can handle. However, online fsck cannot be running 100% of the time, which means that latent errors may creep in after a scrub completes. If these errors cause the next mount to fail, offline fsck is the only solution. This limitation means that maintenance of the offline fsck tool will continue. A second limitation of online fsck is that it must follow the same resource sharing and lock acquisition rules as the regular filesystem. This means that scrub cannot take *any* shortcuts to save time, because doing so could lead to concurrency problems. In other words, online fsck is not a complete replacement for offline fsck, and a complete run of online fsck may take longer than offline fsck. However, both of these limitations are acceptable tradeoffs to satisfy the different motivations of online fsck, which are to **minimize system downtime** and to **increase predictability of operation**.

<a id="rst-phases-of-work"></a>
<a id="rst-scrubphases"></a>

### Phases of Work

The userspace driver program `xfs_scrub` splits the work of checking and repairing an entire filesystem into seven phases. Each phase concentrates on checking specific types of scrub items and depends on the success of all previous phases. The seven phases are as follows:

1. Collect geometry information about the mounted filesystem and computer, discover the online fsck capabilities of the kernel, and open the underlying storage devices.

2. Check allocation group metadata, all realtime volume metadata, and all quota files. Each metadata structure is scheduled as a separate scrub item. If corruption is found in the inode header or inode btree and `xfs_scrub` is permitted to perform repairs, then those scrub items are repaired to prepare for phase 3. Repairs are implemented by using the information in the scrub item to resubmit the kernel scrub call with the repair flag enabled; this is discussed in the next section. Optimizations and all other repairs are deferred to phase 4.

3. Check all metadata of every file in the filesystem. Each metadata structure is also scheduled as a separate scrub item. If repairs are needed and `xfs_scrub` is permitted to perform repairs, and there were no problems detected during phase 2, then those scrub items are repaired immediately. Optimizations, deferred repairs, and unsuccessful repairs are deferred to phase 4.

4. All remaining repairs and scheduled optimizations are performed during this phase, if the caller permits them. Before starting repairs, the summary counters are checked and any necessary repairs are performed so that subsequent repairs will not fail the resource reservation step due to wildly incorrect summary counters. Unsuccessful repairs are requeued as long as forward progress on repairs is made somewhere in the filesystem. Free space in the filesystem is trimmed at the end of phase 4 if the filesystem is clean.

5. By the start of this phase, all primary and secondary filesystem metadata must be correct. Summary counters such as the free space counts and quota resource counts are checked and corrected. Directory entry names and extended attribute names are checked for suspicious entries such as control characters or confusing Unicode sequences appearing in names.

6. If the caller asks for a media scan, read all allocated and written data file extents in the filesystem. The ability to use hardware-assisted data file integrity checking is new to online fsck; neither of the previous tools have this capability. If media errors occur, they will be mapped to the owning files and reported.

7. Re-check the summary counters and presents the caller with a summary of space usage and file counts.

This allocation of responsibilities will be [revisited](<#rst-scrubcheck>) later in this document.

<a id="rst-steps-for-each-scrub-item"></a>

### Steps for Each Scrub Item

The kernel scrub code uses a three-step strategy for checking and repairing the one aspect of a metadata object represented by a scrub item:

1. The scrub item of interest is checked for corruptions; opportunities for optimization; and for values that are directly controlled by the system administrator but look suspicious. If the item is not corrupt or does not need optimization, resource are released and the positive scan results are returned to userspace. If the item is corrupt or could be optimized but the caller does not permit this, resources are released and the negative scan results are returned to userspace. Otherwise, the kernel moves on to the second step.

2. The repair function is called to rebuild the data structure. Repair functions generally choose rebuild a structure from other metadata rather than try to salvage the existing structure. If the repair fails, the scan results from the first step are returned to userspace. Otherwise, the kernel moves on to the third step.

3. In the third step, the kernel runs the same checks over the new metadata item to assess the efficacy of the repairs. The results of the reassessment are returned to userspace.

<a id="rst-classification-of-metadata"></a>

### Classification of Metadata

Each type of metadata object (and therefore each type of scrub item) is classified as follows:

<a id="rst-primary-metadata"></a>

#### Primary Metadata

Metadata structures in this category should be most familiar to filesystem users either because they are directly created by the user or they index objects created by the user Most filesystem objects fall into this class:

- Free space and reference count information

- Inode records and indexes

- Storage mapping information for file data

- Directories

- Extended attributes

- Symbolic links

- Quota limits

Scrub obeys the same rules as regular filesystem accesses for resource and lock acquisition.

Primary metadata objects are the simplest for scrub to process. The principal filesystem object (either an allocation group or an inode) that owns the item being scrubbed is locked to guard against concurrent updates. The check function examines every record associated with the type for obvious errors and cross-references healthy records against other metadata to look for inconsistencies. Repairs for this class of scrub item are simple, since the repair function starts by holding all the resources acquired in the previous step. The repair function scans available metadata as needed to record all the observations needed to complete the structure. Next, it stages the observations in a new ondisk structure and commits it atomically to complete the repair. Finally, the storage from the old data structure are carefully reaped.

Because `xfs_scrub` locks a primary object for the duration of the repair, this is effectively an offline repair operation performed on a subset of the filesystem. This minimizes the complexity of the repair code because it is not necessary to handle concurrent updates from other threads, nor is it necessary to access any other part of the filesystem. As a result, indexed structures can be rebuilt very quickly, and programs trying to access the damaged structure will be blocked until repairs complete. The only infrastructure needed by the repair code are the staging area for observations and a means to write new structures to disk. Despite these limitations, the advantage that online repair holds is clear: targeted work on individual shards of the filesystem avoids total loss of service.

This mechanism is described in section 2.1 ("Off-Line Algorithm") of V. Srinivasan and M. J. Carey, ["Performance of On-Line Index Construction Algorithms"](<https://minds.wisconsin.edu/bitstream/handle/1793/59524/TR1047.pdf>)<a id="rst-performance-of-on-line-index-construction-algorithms"></a>, *Extending Database Technology*, pp. 293-309, 1992.

Most primary metadata repair functions stage their intermediate results in an in-memory array prior to formatting the new ondisk structure, which is very similar to the list-based algorithm discussed in section 2.3 ("List-Based Algorithms") of Srinivasan. However, any data structure builder that maintains a resource lock for the duration of the repair is *always* an offline algorithm.

<a id="rst-secondary-metadata-1"></a>
<a id="rst-secondary-metadata"></a>

#### Secondary Metadata

Metadata structures in this category reflect records found in primary metadata, but are only needed for online fsck or for reorganization of the filesystem.

Secondary metadata include:

- Reverse mapping information

- Directory parent pointers

This class of metadata is difficult for scrub to process because scrub attaches to the secondary object but needs to check primary metadata, which runs counter to the usual order of resource acquisition. Frequently, this means that full filesystems scans are necessary to rebuild the metadata. Check functions can be limited in scope to reduce runtime. Repairs, however, require a full scan of primary metadata, which can take a long time to complete. Under these conditions, `xfs_scrub` cannot lock resources for the entire duration of the repair.

Instead, repair functions set up an in-memory staging structure to store observations. Depending on the requirements of the specific repair function, the staging index will either have the same format as the ondisk structure or a design specific to that repair function. The next step is to release all locks and start the filesystem scan. When the repair scanner needs to record an observation, the staging data are locked long enough to apply the update. While the filesystem scan is in progress, the repair function hooks the filesystem so that it can apply pending filesystem updates to the staging information. Once the scan is done, the owning object is re-locked, the live data is used to write a new ondisk structure, and the repairs are committed atomically. The hooks are disabled and the staging area is freed. Finally, the storage from the old data structure are carefully reaped.

Introducing concurrency helps online repair avoid various locking problems, but comes at a high cost to code complexity. Live filesystem code has to be hooked so that the repair function can observe updates in progress. The staging area has to become a fully functional parallel structure so that updates can be merged from the hooks. Finally, the hook, the filesystem scan, and the inode locking model must be sufficiently well integrated that a hook event can decide if a given update should be applied to the staging structure.

In theory, the scrub implementation could apply these same techniques for primary metadata, but doing so would make it massively more complex and less performant. Programs attempting to access the damaged structures are not blocked from operation, which may cause application failure or an unplanned filesystem shutdown.

Inspiration for the secondary metadata repair strategy was drawn from section 2.4 of Srinivasan above, and sections 2 ("NSF: Index Build Without Side-File") and 3.1.1 ("Duplicate Key Insert Problem") in C. Mohan, ["Algorithms for Creating Indexes for Very Large Tables Without Quiescing Updates"](<https://dl.acm.org/doi/10.1145/130283.130337>)<a id="rst-algorithms-for-creating-indexes-for-very-large-tables-without-quiescing-updates"></a>, 1992.

The sidecar index mentioned above bears some resemblance to the side file method mentioned in Srinivasan and Mohan. Their method consists of an index builder that extracts relevant record data to build the new structure as quickly as possible; and an auxiliary structure that captures all updates that would be committed to the index by other threads were the new index already online. After the index building scan finishes, the updates recorded in the side file are applied to the new index. To avoid conflicts between the index builder and other writer threads, the builder maintains a publicly visible cursor that tracks the progress of the scan through the record space. To avoid duplication of work between the side file and the index builder, side file updates are elided when the record ID for the update is greater than the cursor position within the record ID space.

To minimize changes to the rest of the codebase, XFS online repair keeps the replacement index hidden until it's completely ready to go. In other words, there is no attempt to expose the keyspace of the new index while repair is running. The complexity of such an approach would be very high and perhaps more appropriate to building *new* indices.

**Future Work Question**: Can the full scan and live update code used to facilitate a repair also be used to implement a comprehensive check?

*Answer*: In theory, yes.  Check would be much stronger if each scrub function employed these live scans to build a shadow copy of the metadata and then compared the shadow records to the ondisk records. However, doing that is a fair amount more work than what the checking functions do now. The live scans and hooks were developed much later. That in turn increases the runtime of those scrub functions.

<a id="rst-summary-information"></a>

#### Summary Information

Metadata structures in this last category summarize the contents of primary metadata records. These are often used to speed up resource usage queries, and are many times smaller than the primary metadata which they represent.

Examples of summary information include:

- Summary counts of free space and inodes

- File link counts from directories

- Quota resource usage counts

Check and repair require full filesystem scans, but resource and lock acquisition follow the same paths as regular filesystem accesses.

The superblock summary counters have special requirements due to the underlying implementation of the incore counters, and will be treated separately. Check and repair of the other types of summary counters (quota resource counts and file link counts) employ the same filesystem scanning and hooking techniques as outlined above, but because the underlying data are sets of integer counters, the staging data need not be a fully functional mirror of the ondisk structure.

Inspiration for quota and file link count repair strategies were drawn from sections 2.12 ("Online Index Operations") through 2.14 ("Incremental View Maintenance") of G.  Graefe, ["Concurrent Queries and Updates in Summary Views and Their Indexes"](<http://www.odbms.org/wp-content/uploads/2014/06/Increment-locks.pdf>)<a id="rst-concurrent-queries-and-updates-in-summary-views-and-their-indexes"></a>, 2011.

Since quotas are non-negative integer counts of resource usage, online quotacheck can use the incremental view deltas described in section 2.14 to track pending changes to the block and inode usage counts in each transaction, and commit those changes to a dquot side file when the transaction commits. Delta tracking is necessary for dquots because the index builder scans inodes, whereas the data structure being rebuilt is an index of dquots. Link count checking combines the view deltas and commit step into one because it sets attributes of the objects being scanned instead of writing them to a separate data structure. Each online fsck function will be discussed as case studies later in this document.

<a id="rst-risk-management"></a>

### Risk Management

During the development of online fsck, several risk factors were identified that may make the feature unsuitable for certain distributors and users. Steps can be taken to mitigate or eliminate those risks, though at a cost to functionality.

- **Decreased performance**: Adding metadata indices to the filesystem increases the time cost of persisting changes to disk, and the reverse space mapping and directory parent pointers are no exception. System administrators who require the maximum performance can disable the reverse mapping features at format time, though this choice dramatically reduces the ability of online fsck to find inconsistencies and repair them.

- **Incorrect repairs**: As with all software, there might be defects in the software that result in incorrect repairs being written to the filesystem. Systematic fuzz testing (detailed in the next section) is employed by the authors to find bugs early, but it might not catch everything. The kernel build system provides Kconfig options (`CONFIG_XFS_ONLINE_SCRUB` and `CONFIG_XFS_ONLINE_REPAIR`) to enable distributors to choose not to accept this risk. The xfsprogs build system has a configure option (`--enable-scrub=no`) that disables building of the `xfs_scrub` binary, though this is not a risk mitigation if the kernel functionality remains enabled.

- **Inability to repair**: Sometimes, a filesystem is too badly damaged to be repairable. If the keyspaces of several metadata indices overlap in some manner but a coherent narrative cannot be formed from records collected, then the repair fails. To reduce the chance that a repair will fail with a dirty transaction and render the filesystem unusable, the online repair functions have been designed to stage and validate all new records before committing the new structure.

- **Misbehavior**: Online fsck requires many privileges -- raw IO to block devices, opening files by handle, ignoring Unix discretionary access control, and the ability to perform administrative changes. Running this automatically in the background scares people, so the systemd background service is configured to run with only the privileges required. Obviously, this cannot address certain problems like the kernel crashing or deadlocking, but it should be sufficient to prevent the scrub process from escaping and reconfiguring the system. The cron job does not have this protection.

- **Fuzz Kiddiez**: There are many people now who seem to think that running automated fuzz testing of ondisk artifacts to find mischievous behavior and spraying exploit code onto the public mailing list for instant zero-day disclosure is somehow of some social benefit. In the view of this author, the benefit is realized only when the fuzz operators help to **fix** the flaws, but this opinion apparently is not widely shared among security "researchers". The XFS maintainers' continuing ability to manage these events presents an ongoing risk to the stability of the development process. Automated testing should front-load some of the risk while the feature is considered EXPERIMENTAL.

Many of these risks are inherent to software programming. Despite this, it is hoped that this new functionality will prove useful in reducing unexpected downtime.

<a id="rst-testing-plan"></a>

## 3. Testing Plan

As stated before, fsck tools have three main goals:

1. Detect inconsistencies in the metadata;

2. Eliminate those inconsistencies; and

3. Minimize further loss of data.

Demonstrations of correct operation are necessary to build users' confidence that the software behaves within expectations. Unfortunately, it was not really feasible to perform regular exhaustive testing of every aspect of a fsck tool until the introduction of low-cost virtual machines with high-IOPS storage. With ample hardware availability in mind, the testing strategy for the online fsck project involves differential analysis against the existing fsck tools and systematic testing of every attribute of every type of metadata object. Testing can be split into four major categories, as discussed below.

<a id="rst-integrated-testing-with-fstests"></a>

### Integrated Testing with fstests

The primary goal of any free software QA effort is to make testing as inexpensive and widespread as possible to maximize the scaling advantages of community. In other words, testing should maximize the breadth of filesystem configuration scenarios and hardware setups. This improves code quality by enabling the authors of online fsck to find and fix bugs early, and helps developers of new features to find integration issues earlier in their development effort.

The Linux filesystem community shares a common QA testing suite, [fstests](<https://git.kernel.org/pub/scm/fs/xfs/xfstests-dev.git/>)<a id="rst-fstests"></a>, for functional and regression testing. Even before development work began on online fsck, fstests (when run on XFS) would run both the `xfs_check` and `xfs_repair -n` commands on the test and scratch filesystems between each test. This provides a level of assurance that the kernel and the fsck tools stay in alignment about what constitutes consistent metadata. During development of the online checking code, fstests was modified to run `xfs_scrub -n` between each test to ensure that the new checking code produces the same results as the two existing fsck tools.

To start development of online repair, fstests was modified to run `xfs_repair` to rebuild the filesystem's metadata indices between tests. This ensures that offline repair does not crash, leave a corrupt filesystem after it exists, or trigger complaints from the online check. This also established a baseline for what can and cannot be repaired offline. To complete the first phase of development of online repair, fstests was modified to be able to run `xfs_scrub` in a "force rebuild" mode. This enables a comparison of the effectiveness of online repair as compared to the existing offline repair tools.

<a id="rst-general-fuzz-testing-of-metadata-blocks"></a>

### General Fuzz Testing of Metadata Blocks

XFS benefits greatly from having a very robust debugging tool, `xfs_db`.

Before development of online fsck even began, a set of fstests were created to test the rather common fault that entire metadata blocks get corrupted. This required the creation of fstests library code that can create a filesystem containing every possible type of metadata object. Next, individual test cases were created to create a test filesystem, identify a single block of a specific type of metadata object, trash it with the existing `blocktrash` command in `xfs_db`, and test the reaction of a particular metadata validation strategy.

This earlier test suite enabled XFS developers to test the ability of the in-kernel validation functions and the ability of the offline fsck tool to detect and eliminate the inconsistent metadata. This part of the test suite was extended to cover online fsck in exactly the same manner.

In other words, for a given fstests filesystem configuration:

- For each metadata object existing on the filesystem:

  - Write garbage to it

  - Test the reactions of:

    1. The kernel verifiers to stop obviously bad metadata

    2. Offline repair (`xfs_repair`) to detect and fix

    3. Online repair (`xfs_scrub`) to detect and fix

<a id="rst-targeted-fuzz-testing-of-metadata-records"></a>

### Targeted Fuzz Testing of Metadata Records

The testing plan for online fsck includes extending the existing fs testing infrastructure to provide a much more powerful facility: targeted fuzz testing of every metadata field of every metadata object in the filesystem. `xfs_db` can modify every field of every metadata structure in every block in the filesystem to simulate the effects of memory corruption and software bugs. Given that fstests already contains the ability to create a filesystem containing every metadata format known to the filesystem, `xfs_db` can be used to perform exhaustive fuzz testing\!

For a given fstests filesystem configuration:

- For each metadata object existing on the filesystem...

  - For each record inside that metadata object...

    - For each field inside that record...

      - For each conceivable type of transformation that can be applied to a bit field...

        1. Clear all bits

        2. Set all bits

        3. Toggle the most significant bit

        4. Toggle the middle bit

        5. Toggle the least significant bit

        6. Add a small quantity

        7. Subtract a small quantity

        8. Randomize the contents

        - ...test the reactions of:

          1. The kernel verifiers to stop obviously bad metadata

          2. Offline checking (`xfs_repair -n`)

          3. Offline repair (`xfs_repair`)

          4. Online checking (`xfs_scrub -n`)

          5. Online repair (`xfs_scrub`)

          6. Both repair tools (`xfs_scrub` and then `xfs_repair` if online repair doesn't succeed)

This is quite the combinatoric explosion\!

Fortunately, having this much test coverage makes it easy for XFS developers to check the responses of XFS' fsck tools. Since the introduction of the fuzz testing framework, these tests have been used to discover incorrect repair code and missing functionality for entire classes of metadata objects in `xfs_repair`. The enhanced testing was used to finalize the deprecation of `xfs_check` by confirming that `xfs_repair` could detect at least as many corruptions as the older tool.

These tests have been very valuable for `xfs_scrub` in the same ways -- they allow the online fsck developers to compare online fsck against offline fsck, and they enable XFS developers to find deficiencies in the code base.

Proposed patchsets include [fuzzing baselines](<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfstests-dev.git/log/?h=fuzz-baseline>)<a id="rst-fuzzing-baselines"></a>.

<a id="rst-stress-testing"></a>

### Stress Testing

A unique requirement to online fsck is the ability to operate on a filesystem concurrently with regular workloads. Although it is of course impossible to run `xfs_scrub` with *zero* observable impact on the running system, the online repair code should never introduce inconsistencies into the filesystem metadata, and regular workloads should never notice resource starvation. To verify that these conditions are being met, fstests has been enhanced in the following ways:

- For each scrub item type, create a test to exercise checking that item type while running `fsstress`.

- For each scrub item type, create a test to exercise repairing that item type while running `fsstress`.

- Race `fsstress` and `xfs_scrub -n` to ensure that checking the whole filesystem doesn't cause problems.

- Race `fsstress` and `xfs_scrub` in force-rebuild mode to ensure that force-repairing the whole filesystem doesn't cause problems.

- Race `xfs_scrub` in check and force-repair mode against `fsstress` while freezing and thawing the filesystem.

- Race `xfs_scrub` in check and force-repair mode against `fsstress` while remounting the filesystem read-only and read-write.

- The same, but running `fsx` instead of `fsstress`.  (Not done yet?)

Success is defined by the ability to run all of these tests without observing any unexpected filesystem shutdowns due to corrupted metadata, kernel hang check warnings, or any other sort of mischief.

<a id="rst-user-interface"></a>

## 4. User Interface

The primary user of online fsck is the system administrator, just like offline repair. Online fsck presents two modes of operation to administrators: A foreground CLI process for online fsck on demand, and a background service that performs autonomous checking and repair.

<a id="rst-checking-on-demand"></a>

### Checking on Demand

For administrators who want the absolute freshest information about the metadata in a filesystem, `xfs_scrub` can be run as a foreground process on a command line. The program checks every piece of metadata in the filesystem while the administrator waits for the results to be reported, just like the existing `xfs_repair` tool. Both tools share a `-n` option to perform a read-only scan, and a `-v` option to increase the verbosity of the information reported.

A new feature of `xfs_scrub` is the `-x` option, which employs the error correction capabilities of the hardware to check data file contents. The media scan is not enabled by default because it may dramatically increase program runtime and consume a lot of bandwidth on older storage hardware.

The output of a foreground invocation is captured in the system log.

The `xfs_scrub_all` program walks the list of mounted filesystems and initiates `xfs_scrub` for each of them in parallel. It serializes scans for any filesystems that resolve to the same top level kernel block device to prevent resource overconsumption.

<a id="rst-background-service"></a>

### Background Service

To reduce the workload of system administrators, the `xfs_scrub` package provides a suite of [systemd](<https://systemd.io/>)<a id="rst-systemd"></a> timers and services that run online fsck automatically on weekends by default. The background service configures scrub to run with as little privilege as possible, the lowest CPU and IO priority, and in a CPU-constrained single threaded mode. This can be tuned by the systemd administrator at any time to suit the latency and throughput requirements of customer workloads.

The output of the background service is also captured in the system log. If desired, reports of failures (either due to inconsistencies or mere runtime errors) can be emailed automatically by setting the `EMAIL_ADDR` environment variable in the following service files:

- `xfs_scrub_fail@.service`

- `xfs_scrub_media_fail@.service`

- `xfs_scrub_all_fail.service`

The decision to enable the background scan is left to the system administrator. This can be done by enabling either of the following services:

- `xfs_scrub_all.timer` on systemd systems

- `xfs_scrub_all.cron` on non-systemd systems

This automatic weekly scan is configured out of the box to perform an additional media scan of all file data once per month. This is less foolproof than, say, storing file data block checksums, but much more performant if application software provides its own integrity checking, redundancy can be provided elsewhere above the filesystem, or the storage device's integrity guarantees are deemed sufficient.

The systemd unit file definitions have been subjected to a security audit (as of systemd 249) to ensure that the xfs_scrub processes have as little access to the rest of the system as possible. This was performed via `systemd-analyze security`, after which privileges were restricted to the minimum required, sandboxing was set up to the maximal extent possible with sandboxing and system call filtering; and access to the filesystem tree was restricted to the minimum needed to start the program and access the filesystem being scanned. The service definition files restrict CPU usage to 80% of one CPU core, and apply as nice of a priority to IO and CPU scheduling as possible. This measure was taken to minimize delays in the rest of the filesystem. No such hardening has been performed for the cron job.

<a id="rst-health-reporting"></a>

### Health Reporting

XFS caches a summary of each filesystem's health status in memory. The information is updated whenever `xfs_scrub` is run, or whenever inconsistencies are detected in the filesystem metadata during regular operations. System administrators should use the `health` command of `xfs_spaceman` to download this information into a human-readable format. If problems have been observed, the administrator can schedule a reduced service window to run the online repair tool to correct the problem. Failing that, the administrator can decide to schedule a maintenance window to run the traditional offline repair tool to correct the problem.

**Future Work Question**: Should the health reporting integrate with the new inotify fs error notification system? Would it be helpful for sysadmins to have a daemon to listen for corruption notifications and initiate a repair?

*Answer*: These questions remain unanswered, but should be a part of the conversation with early adopters and potential downstream users of XFS.

<a id="rst-kernel-algorithms-and-data-structures"></a>

## 5. Kernel Algorithms and Data Structures

This section discusses the key algorithms and data structures of the kernel code that provide the ability to check and repair metadata while the system is running. The first chapters in this section reveal the pieces that provide the foundation for checking metadata. The remainder of this section presents the mechanisms through which XFS regenerates itself.

<a id="rst-self-describing-metadata"></a>

### Self Describing Metadata

Starting with XFS version 5 in 2012, XFS updated the format of nearly every ondisk block header to record a magic number, a checksum, a universally "unique" identifier (UUID), an owner code, the ondisk address of the block, and a log sequence number. When loading a block buffer from disk, the magic number, UUID, owner, and ondisk address confirm that the retrieved block matches the specific owner of the current filesystem, and that the information contained in the block is supposed to be found at the ondisk address. The first three components enable checking tools to disregard alleged metadata that doesn't belong to the filesystem, and the fourth component enables the filesystem to detect lost writes.

Whenever a file system operation modifies a block, the change is submitted to the log as part of a transaction. The log then processes these transactions marking them done once they are safely persisted to storage. The logging code maintains the checksum and the log sequence number of the last transactional update. Checksums are useful for detecting torn writes and other discrepancies that can be introduced between the computer and its storage devices. Sequence number tracking enables log recovery to avoid applying out of date log updates to the filesystem.

These two features improve overall runtime resiliency by providing a means for the filesystem to detect obvious corruption when reading metadata blocks from disk, but these buffer verifiers cannot provide any consistency checking between metadata structures.

For more information, please see the documentation for [Documentation/filesystems/xfs/xfs-self-describing-metadata.rst](/kernel/internals/filesystems/xfs/xfs-self-describing-metadata.md)

<a id="rst-reverse-mapping"></a>

### Reverse Mapping

The original design of XFS (circa 1993) is an improvement upon 1980s Unix filesystem design. In those days, storage density was expensive, CPU time was scarce, and excessive seek time could kill performance. For performance reasons, filesystem authors were reluctant to add redundancy to the filesystem, even at the cost of data integrity. Filesystems designers in the early 21st century choose different strategies to increase internal redundancy -- either storing nearly identical copies of metadata, or more space-efficient encoding techniques.

For XFS, a different redundancy strategy was chosen to modernize the design: a secondary space usage index that maps allocated disk extents back to their owners. By adding a new index, the filesystem retains most of its ability to scale well to heavily threaded workloads involving large datasets, since the primary file metadata (the directory tree, the file block map, and the allocation groups) remain unchanged. Like any system that improves redundancy, the reverse-mapping feature increases overhead costs for space mapping activities. However, it has two critical advantages: first, the reverse index is key to enabling online fsck and other requested functionality such as free space defragmentation, better media failure reporting, and filesystem shrinking. Second, the different ondisk storage format of the reverse mapping btree defeats device-level deduplication because the filesystem requires real redundancy.


<table>
<tbody>
<tr>
<td>


**Sidebar**:

</td>
</tr>
<tr>
<td>


A criticism of adding the secondary index is that it does nothing to improve the robustness of user data storage itself. This is a valid point, but adding a new index for file data block checksums increases write amplification by turning data overwrites into copy-writes, which age the filesystem prematurely. In keeping with thirty years of precedent, users who want file data integrity can supply as powerful a solution as they require. As for metadata, the complexity of adding a new secondary index of space usage is much less than adding volume management and storage device mirroring to XFS itself. Perfection of RAID and volume management are best left to existing layers in the kernel.

</td>
</tr>
</tbody>
</table>

The information captured in a reverse space mapping record is as follows:



```c
struct xfs_rmap_irec {
    xfs_agblock_t    rm_startblock;   /* extent start block */
    xfs_extlen_t     rm_blockcount;   /* extent length */
    uint64_t         rm_owner;        /* extent owner */
    uint64_t         rm_offset;       /* offset within the owner */
    unsigned int     rm_flags;        /* state flags */
};
```

The first two fields capture the location and size of the physical space, in units of filesystem blocks. The owner field tells scrub which metadata structure or file inode have been assigned this space. For space allocated to files, the offset field tells scrub where the space was mapped within the file fork. Finally, the flags field provides extra information about the space usage -- is this an attribute fork extent?  A file mapping btree extent?  Or an unwritten data extent?

Online filesystem checking judges the consistency of each primary metadata record by comparing its information against all other space indices. The reverse mapping index plays a key role in the consistency checking process because it contains a centralized alternate copy of all space allocation information. Program runtime and ease of resource acquisition are the only real limits to what online checking can consult. For example, a file data extent mapping can be checked against:

- The absence of an entry in the free space information.

- The absence of an entry in the inode index.

- The absence of an entry in the reference count data if the file is not marked as having shared extents.

- The correspondence of an entry in the reverse mapping information.

There are several observations to make about reverse mapping indices:

1. Reverse mappings can provide a positive affirmation of correctness if any of the above primary metadata are in doubt. The checking code for most primary metadata follows a path similar to the one outlined above.

2. Proving the consistency of secondary metadata with the primary metadata is difficult because that requires a full scan of all primary space metadata, which is very time intensive. For example, checking a reverse mapping record for a file extent mapping btree block requires locking the file and searching the entire btree to confirm the block. Instead, scrub relies on rigorous cross-referencing during the primary space mapping structure checks.

3. Consistency scans must use non-blocking lock acquisition primitives if the required locking order is not the same order used by regular filesystem operations. For example, if the filesystem normally takes a file ILOCK before taking the AGF buffer lock but scrub wants to take a file ILOCK while holding an AGF buffer lock, scrub cannot block on that second acquisition. This means that forward progress during this part of a scan of the reverse mapping data cannot be guaranteed if system load is heavy.

In summary, reverse mappings play a key role in reconstruction of primary metadata. The details of how these records are staged, written to disk, and committed into the filesystem are covered in subsequent sections.

<a id="rst-checking-and-cross-referencing"></a>

### Checking and Cross-Referencing

The first step of checking a metadata structure is to examine every record contained within the structure and its relationship with the rest of the system. XFS contains multiple layers of checking to try to prevent inconsistent metadata from wreaking havoc on the system. Each of these layers contributes information that helps the kernel to make three decisions about the health of a metadata structure:

- Is a part of this structure obviously corrupt (`XFS_SCRUB_OFLAG_CORRUPT`) ?

- Is this structure inconsistent with the rest of the system (`XFS_SCRUB_OFLAG_XCORRUPT`) ?

- Is there so much damage around the filesystem that cross-referencing is not possible (`XFS_SCRUB_OFLAG_XFAIL`) ?

- Can the structure be optimized to improve performance or reduce the size of metadata (`XFS_SCRUB_OFLAG_PREEN`) ?

- Does the structure contain data that is not inconsistent but deserves review by the system administrator (`XFS_SCRUB_OFLAG_WARNING`) ?

The following sections describe how the metadata scrubbing process works.

<a id="rst-metadata-buffer-verification"></a>

#### Metadata Buffer Verification

The lowest layer of metadata protection in XFS are the metadata verifiers built into the buffer cache. These functions perform inexpensive internal consistency checking of the block itself, and answer these questions:

- Does the block belong to this filesystem?

- Does the block belong to the structure that asked for the read? This assumes that metadata blocks only have one owner, which is always true in XFS.

- Is the type of data stored in the block within a reasonable range of what scrub is expecting?

- Does the physical location of the block match the location it was read from?

- Does the block checksum match the data?

The scope of the protections here are very limited -- verifiers can only establish that the filesystem code is reasonably free of gross corruption bugs and that the storage system is reasonably competent at retrieval. Corruption problems observed at runtime cause the generation of health reports, failed system calls, and in the extreme case, filesystem shutdowns if the corrupt metadata force the cancellation of a dirty transaction.

Every online fsck scrubbing function is expected to read every ondisk metadata block of a structure in the course of checking the structure. Corruption problems observed during a check are immediately reported to userspace as corruption; during a cross-reference, they are reported as a failure to cross-reference once the full examination is complete. Reads satisfied by a buffer already in cache (and hence already verified) bypass these checks.

<a id="rst-internal-consistency-checks"></a>

#### Internal Consistency Checks

After the buffer cache, the next level of metadata protection is the internal record verification code built into the filesystem. These checks are split between the buffer verifiers, the in-filesystem users of the buffer cache, and the scrub code itself, depending on the amount of higher level context required. The scope of checking is still internal to the block. These higher level checking functions answer these questions:

- Does the type of data stored in the block match what scrub is expecting?

- Does the block belong to the owning structure that asked for the read?

- If the block contains records, do the records fit within the block?

- If the block tracks internal free space information, is it consistent with the record areas?

- Are the records contained inside the block free of obvious corruptions?

Record checks in this category are more rigorous and more time-intensive. For example, block pointers and inumbers are checked to ensure that they point within the dynamically allocated parts of an allocation group and within the filesystem. Names are checked for invalid characters, and flags are checked for invalid combinations. Other record attributes are checked for sensible values. Btree records spanning an interval of the btree keyspace are checked for correct order and lack of mergeability (except for file fork mappings). For performance reasons, regular code may skip some of these checks unless debugging is enabled or a write is about to occur. Scrub functions, of course, must check all possible problems.

<a id="rst-validation-of-userspace-controlled-record-attributes"></a>

#### Validation of Userspace-Controlled Record Attributes

Various pieces of filesystem metadata are directly controlled by userspace. Because of this nature, validation work cannot be more precise than checking that a value is within the possible range. These fields include:

- Superblock fields controlled by mount options

- Filesystem labels

- File timestamps

- File permissions

- File size

- File flags

- Names present in directory entries, extended attribute keys, and filesystem labels

- Extended attribute key namespaces

- Extended attribute values

- File data block contents

- Quota limits

- Quota timer expiration (if resource usage exceeds the soft limit)

<a id="rst-cross-referencing-space-metadata"></a>

#### Cross-Referencing Space Metadata

After internal block checks, the next higher level of checking is cross-referencing records between metadata structures. For regular runtime code, the cost of these checks is considered to be prohibitively expensive, but as scrub is dedicated to rooting out inconsistencies, it must pursue all avenues of inquiry. The exact set of cross-referencing is highly dependent on the context of the data structure being checked.

The XFS btree code has keyspace scanning functions that online fsck uses to cross reference one structure with another. Specifically, scrub can scan the key space of an index to determine if that keyspace is fully, sparsely, or not at all mapped to records. For the reverse mapping btree, it is possible to mask parts of the key for the purposes of performing a keyspace scan so that scrub can decide if the rmap btree contains records mapping a certain extent of physical space without the sparsenses of the rest of the rmap keyspace getting in the way.

Btree blocks undergo the following checks before cross-referencing:

- Does the type of data stored in the block match what scrub is expecting?

- Does the block belong to the owning structure that asked for the read?

- Do the records fit within the block?

- Are the records contained inside the block free of obvious corruptions?

- Are the name hashes in the correct order?

- Do node pointers within the btree point to valid block addresses for the type of btree?

- Do child pointers point towards the leaves?

- Do sibling pointers point across the same level?

- For each node block record, does the record key accurate reflect the contents of the child block?

Space allocation records are cross-referenced as follows:

1. Any space mentioned by any metadata structure are cross-referenced as follows:

   - Does the reverse mapping index list only the appropriate owner as the owner of each block?

   - Are none of the blocks claimed as free space?

   - If these aren't file data blocks, are none of the blocks claimed as space shared by different owners?

2. Btree blocks are cross-referenced as follows:

   - Everything in class 1 above.

   - If there's a parent node block, do the keys listed for this block match the keyspace of this block?

   - Do the sibling pointers point to valid blocks?  Of the same level?

   - Do the child pointers point to valid blocks?  Of the next level down?

3. Free space btree records are cross-referenced as follows:

   - Everything in class 1 and 2 above.

   - Does the reverse mapping index list no owners of this space?

   - Is this space not claimed by the inode index for inodes?

   - Is it not mentioned by the reference count index?

   - Is there a matching record in the other free space btree?

4. Inode btree records are cross-referenced as follows:

   - Everything in class 1 and 2 above.

   - Is there a matching record in free inode btree?

   - Do cleared bits in the holemask correspond with inode clusters?

   - Do set bits in the freemask correspond with inode records with zero link count?

5. Inode records are cross-referenced as follows:

   - Everything in class 1.

   - Do all the fields that summarize information about the file forks actually match those forks?

   - Does each inode with zero link count correspond to a record in the free inode btree?

6. File fork space mapping records are cross-referenced as follows:

   - Everything in class 1 and 2 above.

   - Is this space not mentioned by the inode btrees?

   - If this is a CoW fork mapping, does it correspond to a CoW entry in the reference count btree?

7. Reference count records are cross-referenced as follows:

   - Everything in class 1 and 2 above.

   - Within the space subkeyspace of the rmap btree (that is to say, all records mapped to a particular space extent and ignoring the owner info), are there the same number of reverse mapping records for each block as the reference count record claims?

<a id="rst-checking-extended-attributes"></a>

#### Checking Extended Attributes

Extended attributes implement a key-value store that enable fragments of data to be attached to any file. Both the kernel and userspace can access the keys and values, subject to namespace and privilege restrictions. Most typically these fragments are metadata about the file -- origins, security contexts, user-supplied labels, indexing information, etc.

Names can be as long as 255 bytes and can exist in several different namespaces. Values can be as large as 64KB. A file's extended attributes are stored in blocks mapped by the attr fork. The mappings point to leaf blocks, remote value blocks, or dabtree blocks. Block 0 in the attribute fork is always the top of the structure, but otherwise each of the three types of blocks can be found at any offset in the attr fork. Leaf blocks contain attribute key records that point to the name and the value. Names are always stored elsewhere in the same leaf block. Values that are less than 3/4 the size of a filesystem block are also stored elsewhere in the same leaf block. Remote value blocks contain values that are too large to fit inside a leaf. If the leaf information exceeds a single filesystem block, a dabtree (also rooted at block 0) is created to map hashes of the attribute names to leaf blocks in the attr fork.

Checking an extended attribute structure is not so straightforward due to the lack of separation between attr blocks and index blocks. Scrub must read each block mapped by the attr fork and ignore the non-leaf blocks:

1. Walk the dabtree in the attr fork (if present) to ensure that there are no irregularities in the blocks or dabtree mappings that do not point to attr leaf blocks.

2. Walk the blocks of the attr fork looking for leaf blocks. For each entry inside a leaf:

   - **a.** Validate that the name does not contain invalid characters.

   - **b.** Read the attr value. This performs a named lookup of the attr name to ensure the correctness of the dabtree. If the value is stored in a remote block, this also validates the integrity of the remote value block.

<a id="rst-checking-and-cross-referencing-directories"></a>

#### Checking and Cross-Referencing Directories

The filesystem directory tree is a directed acylic graph structure, with files constituting the nodes, and directory entries (dirents) constituting the edges. Directories are a special type of file containing a set of mappings from a 255-byte sequence (name) to an inumber. These are called directory entries, or dirents for short. Each directory file must have exactly one directory pointing to the file. A root directory points to itself. Directory entries point to files of any type. Each non-directory file may have multiple directories point to it.

In XFS, directories are implemented as a file containing up to three 32GB partitions. The first partition contains directory entry data blocks. Each data block contains variable-sized records associating a user-provided name with an inumber and, optionally, a file type. If the directory entry data grows beyond one block, the second partition (which exists as post-EOF extents) is populated with a block containing free space information and an index that maps hashes of the dirent names to directory data blocks in the first partition. This makes directory name lookups very fast. If this second partition grows beyond one block, the third partition is populated with a linear array of free space information for faster expansions. If the free space has been separated and the second partition grows again beyond one block, then a dabtree is used to map hashes of dirent names to directory data blocks.

Checking a directory is pretty straightforward:

1. Walk the dabtree in the second partition (if present) to ensure that there are no irregularities in the blocks or dabtree mappings that do not point to dirent blocks.

2. Walk the blocks of the first partition looking for directory entries. Each dirent is checked as follows:

   - **a.** Does the name contain no invalid characters?

   - **b.** Does the inumber correspond to an actual, allocated inode?

   - **c.** Does the child inode have a nonzero link count?

   - **d.** If a file type is included in the dirent, does it match the type of the inode?

   - **e.** If the child is a subdirectory, does the child's dotdot pointer point back to the parent?

   - **f.** If the directory has a second partition, perform a named lookup of the dirent name to ensure the correctness of the dabtree.

3. Walk the free space list in the third partition (if present) to ensure that the free spaces it describes are really unused.

Checking operations involving [parents](<#rst-dirparent>) and [file link counts](<#rst-nlinks>) are discussed in more detail in later sections.

<a id="rst-checking-directory-attribute-btrees"></a>

##### Checking Directory/Attribute Btrees

As stated in previous sections, the directory/attribute btree (dabtree) index maps user-provided names to improve lookup times by avoiding linear scans. Internally, it maps a 32-bit hash of the name to a block offset within the appropriate file fork.

The internal structure of a dabtree closely resembles the btrees that record fixed-size metadata records -- each dabtree block contains a magic number, a checksum, sibling pointers, a UUID, a tree level, and a log sequence number. The format of leaf and node records are the same -- each entry points to the next level down in the hierarchy, with dabtree node records pointing to dabtree leaf blocks, and dabtree leaf records pointing to non-dabtree blocks elsewhere in the fork.

Checking and cross-referencing the dabtree is very similar to what is done for space btrees:

- Does the type of data stored in the block match what scrub is expecting?

- Does the block belong to the owning structure that asked for the read?

- Do the records fit within the block?

- Are the records contained inside the block free of obvious corruptions?

- Are the name hashes in the correct order?

- Do node pointers within the dabtree point to valid fork offsets for dabtree blocks?

- Do leaf pointers within the dabtree point to valid fork offsets for directory or attr leaf blocks?

- Do child pointers point towards the leaves?

- Do sibling pointers point across the same level?

- For each dabtree node record, does the record key accurate reflect the contents of the child dabtree block?

- For each dabtree leaf record, does the record key accurate reflect the contents of the directory or attr block?

<a id="rst-cross-referencing-summary-counters"></a>

#### Cross-Referencing Summary Counters

XFS maintains three classes of summary counters: available resources, quota resource usage, and file link counts.

In theory, the amount of available resources (data blocks, inodes, realtime extents) can be found by walking the entire filesystem. This would make for very slow reporting, so a transactional filesystem can maintain summaries of this information in the superblock. Cross-referencing these values against the filesystem metadata should be a simple matter of walking the free space and inode metadata in each AG and the realtime bitmap, but there are complications that will be discussed in [more detail](<#rst-fscounters>) later.

[Quota usage](<#rst-quotacheck>) and [file link count](<#rst-nlinks>) checking are sufficiently complicated to warrant separate sections.

<a id="rst-post-repair-reverification"></a>

#### Post-Repair Reverification

After performing a repair, the checking code is run a second time to validate the new structure, and the results of the health assessment are recorded internally and returned to the calling process. This step is critical for enabling system administrator to monitor the status of the filesystem and the progress of any repairs. For developers, it is a useful means to judge the efficacy of error detection and correction in the online and offline checking tools.

<a id="rst-eventual-consistency-vs-online-fsck"></a>

### Eventual Consistency vs. Online Fsck

Complex operations can make modifications to multiple per-AG data structures with a chain of transactions. These chains, once committed to the log, are restarted during log recovery if the system crashes while processing the chain. Because the AG header buffers are unlocked between transactions within a chain, online checking must coordinate with chained operations that are in progress to avoid incorrectly detecting inconsistencies due to pending chains. Furthermore, online repair must not run when operations are pending because the metadata are temporarily inconsistent with each other, and rebuilding is not possible.

Only online fsck has this requirement of total consistency of AG metadata, and should be relatively rare as compared to filesystem change operations. Online fsck coordinates with transaction chains as follows:

- For each AG, maintain a count of intent items targeting that AG. The count should be bumped whenever a new item is added to the chain. The count should be dropped when the filesystem has locked the AG header buffers and finished the work.

- When online fsck wants to examine an AG, it should lock the AG header buffers to quiesce all transaction chains that want to modify that AG. If the count is zero, proceed with the checking operation. If it is nonzero, cycle the buffer locks to allow the chain to make forward progress.

This may lead to online fsck taking a long time to complete, but regular filesystem updates take precedence over background checking activity. Details about the discovery of this situation are presented in the [next section](<#rst-chain-coordination>), and details about the solution are presented [after that](<#rst-intent-drains>).

<a id="rst-discovery-of-the-problem"></a>
<a id="rst-chain-coordination"></a>

#### Discovery of the Problem

Midway through the development of online scrubbing, the fsstress tests uncovered a misinteraction between online fsck and compound transaction chains created by other writer threads that resulted in false reports of metadata inconsistency. The root cause of these reports is the eventual consistency model introduced by the expansion of deferred work items and compound transaction chains when reverse mapping and reflink were introduced.

Originally, transaction chains were added to XFS to avoid deadlocks when unmapping space from files. Deadlock avoidance rules require that AGs only be locked in increasing order, which makes it impossible (say) to use a single transaction to free a space extent in AG 7 and then try to free a now superfluous block mapping btree block in AG 3. To avoid these kinds of deadlocks, XFS creates Extent Freeing Intent (EFI) log items to commit to freeing some space in one transaction while deferring the actual metadata updates to a fresh transaction. The transaction sequence looks like this:

1. The first transaction contains a physical update to the file's block mapping structures to remove the mapping from the btree blocks. It then attaches to the in-memory transaction an action item to schedule deferred freeing of space. Concretely, each transaction maintains a list of `struct xfs_defer_pending` objects, each of which maintains a list of `struct xfs_extent_free_item` objects. Returning to the example above, the action item tracks the freeing of both the unmapped space from AG 7 and the block mapping btree (BMBT) block from AG 3. Deferred frees recorded in this manner are committed in the log by creating an EFI log item from the `struct xfs_extent_free_item` object and attaching the log item to the transaction. When the log is persisted to disk, the EFI item is written into the ondisk transaction record. EFIs can list up to 16 extents to free, all sorted in AG order.

2. The second transaction contains a physical update to the free space btrees of AG 3 to release the former BMBT block and a second physical update to the free space btrees of AG 7 to release the unmapped file space. Observe that the physical updates are resequenced in the correct order when possible. Attached to the transaction is a an extent free done (EFD) log item. The EFD contains a pointer to the EFI logged in transaction \#1 so that log recovery can tell if the EFI needs to be replayed.

If the system goes down after transaction \#1 is written back to the filesystem but before \#2 is committed, a scan of the filesystem metadata would show inconsistent filesystem metadata because there would not appear to be any owner of the unmapped space. Happily, log recovery corrects this inconsistency for us -- when recovery finds an intent log item but does not find a corresponding intent done item, it will reconstruct the incore state of the intent item and finish it. In the example above, the log must replay both frees described in the recovered EFI to complete the recovery phase.

There are subtleties to XFS' transaction chaining strategy to consider:

- Log items must be added to a transaction in the correct order to prevent conflicts with principal objects that are not held by the transaction. In other words, all per-AG metadata updates for an unmapped block must be completed before the last update to free the extent, and extents should not be reallocated until that last update commits to the log.

- AG header buffers are released between each transaction in a chain. This means that other threads can observe an AG in an intermediate state, but as long as the first subtlety is handled, this should not affect the correctness of filesystem operations.

- Unmounting the filesystem flushes all pending work to disk, which means that offline fsck never sees the temporary inconsistencies caused by deferred work item processing.

In this manner, XFS employs a form of eventual consistency to avoid deadlocks and increase parallelism.

During the design phase of the reverse mapping and reflink features, it was decided that it was impractical to cram all the reverse mapping updates for a single filesystem change into a single transaction because a single file mapping operation can explode into many small updates:

- The block mapping update itself

- A reverse mapping update for the block mapping update

- Fixing the freelist

- A reverse mapping update for the freelist fix

- A shape change to the block mapping btree

- A reverse mapping update for the btree update

- Fixing the freelist (again)

- A reverse mapping update for the freelist fix

- An update to the reference counting information

- A reverse mapping update for the refcount update

- Fixing the freelist (a third time)

- A reverse mapping update for the freelist fix

- Freeing any space that was unmapped and not owned by any other file

- Fixing the freelist (a fourth time)

- A reverse mapping update for the freelist fix

- Freeing the space used by the block mapping btree

- Fixing the freelist (a fifth time)

- A reverse mapping update for the freelist fix

Free list fixups are not usually needed more than once per AG per transaction chain, but it is theoretically possible if space is very tight. For copy-on-write updates this is even worse, because this must be done once to remove the space from a staging area and again to map it into the file\!

To deal with this explosion in a calm manner, XFS expands its use of deferred work items to cover most reverse mapping updates and all refcount updates. This reduces the worst case size of transaction reservations by breaking the work into a long chain of small updates, which increases the degree of eventual consistency in the system. Again, this generally isn't a problem because XFS orders its deferred work items carefully to avoid resource reuse conflicts between unsuspecting threads.

However, online fsck changes the rules -- remember that although physical updates to per-AG structures are coordinated by locking the buffers for AG headers, buffer locks are dropped between transactions. Once scrub acquires resources and takes locks for a data structure, it must do all the validation work without releasing the lock. If the main lock for a space btree is an AG header buffer lock, scrub may have interrupted another thread that is midway through finishing a chain. For example, if a thread performing a copy-on-write has completed a reverse mapping update but not the corresponding refcount update, the two AG btrees will appear inconsistent to scrub and an observation of corruption will be recorded.  This observation will not be correct. If a repair is attempted in this state, the results will be catastrophic\!

Several other solutions to this problem were evaluated upon discovery of this flaw and rejected:

1. Add a higher level lock to allocation groups and require writer threads to acquire the higher level lock in AG order before making any changes. This would be very difficult to implement in practice because it is difficult to determine which locks need to be obtained, and in what order, without simulating the entire operation. Performing a dry run of a file operation to discover necessary locks would make the filesystem very slow.

2. Make the deferred work coordinator code aware of consecutive intent items targeting the same AG and have it hold the AG header buffers locked across the transaction roll between updates. This would introduce a lot of complexity into the coordinator since it is only loosely coupled with the actual deferred work items. It would also fail to solve the problem because deferred work items can generate new deferred subtasks, but all subtasks must be complete before work can start on a new sibling task.

3. Teach online fsck to walk all transactions waiting for whichever lock(s) protect the data structure being scrubbed to look for pending operations. The checking and repair operations must factor these pending operations into the evaluations being performed. This solution is a nonstarter because it is *extremely* invasive to the main filesystem.

<a id="rst-intent-drains-1"></a>
<a id="rst-intent-drains"></a>

#### Intent Drains

Online fsck uses an atomic intent item counter and lock cycling to coordinate with transaction chains. There are two key properties to the drain mechanism. First, the counter is incremented when a deferred work item is *queued* to a transaction, and it is decremented after the associated intent done log item is *committed* to another transaction. The second property is that deferred work can be added to a transaction without holding an AG header lock, but per-AG work items cannot be marked done without locking that AG header buffer to log the physical updates and the intent done log item. The first property enables scrub to yield to running transaction chains, which is an explicit deprioritization of online fsck to benefit file operations. The second property of the drain is key to the correct coordination of scrub, since scrub will always be able to decide if a conflict is possible.

For regular filesystem code, the drain works as follows:

1. Call the appropriate subsystem function to add a deferred work item to a transaction.

2. The function calls `xfs_defer_drain_bump` to increase the counter.

3. When the deferred item manager wants to finish the deferred work item, it calls `->finish_item` to complete it.

4. The `->finish_item` implementation logs some changes and calls `xfs_defer_drain_drop` to decrease the sloppy counter and wake up any threads waiting on the drain.

5. The subtransaction commits, which unlocks the resource associated with the intent item.

For scrub, the drain works as follows:

1. Lock the resource(s) associated with the metadata being scrubbed. For example, a scan of the refcount btree would lock the AGI and AGF header buffers.

2. If the counter is zero (`xfs_defer_drain_busy` returns false), there are no chains in progress and the operation may proceed.

3. Otherwise, release the resources grabbed in step 1.

4. Wait for the intent counter to reach zero (`xfs_defer_drain_intents`), then go back to step 1 unless a signal has been caught.

To avoid polling in step 4, the drain provides a waitqueue for scrub threads to be woken up whenever the intent count drops to zero.

<a id="rst-static-keys-aka-jump-label-patching"></a>
<a id="rst-jump-labels"></a>

#### Static Keys (aka Jump Label Patching)

Online fsck for XFS separates the regular filesystem from the checking and repair code as much as possible. However, there are a few parts of online fsck (such as the intent drains, and later, live update hooks) where it is useful for the online fsck code to know what's going on in the rest of the filesystem. Since it is not expected that online fsck will be constantly running in the background, it is very important to minimize the runtime overhead imposed by these hooks when online fsck is compiled into the kernel but not actively running on behalf of userspace. Taking locks in the hot path of a writer thread to access a data structure only to find that no further action is necessary is expensive -- on the author's computer, this have an overhead of 40-50ns per access. Fortunately, the kernel supports dynamic code patching, which enables XFS to replace a static branch to hook code with `nop` sleds when online fsck isn't running. This sled has an overhead of however long it takes the instruction decoder to skip past the sled, which seems to be on the order of less than 1ns and does not access memory outside of instruction fetching.

When online fsck enables the static key, the sled is replaced with an unconditional branch to call the hook code. The switchover is quite expensive (\~22000ns) but is paid entirely by the program that invoked online fsck, and can be amortized if multiple threads enter online fsck at the same time, or if multiple filesystems are being checked at the same time. Changing the branch direction requires taking the CPU hotplug lock, and since CPU initialization requires memory allocation, online fsck must be careful not to change a static key while holding any locks or resources that could be accessed in the memory reclaim paths. To minimize contention on the CPU hotplug lock, care should be taken not to enable or disable static keys unnecessarily.

Because static keys are intended to minimize hook overhead for regular filesystem operations when xfs_scrub is not running, the intended usage patterns are as follows:

- The hooked part of XFS should declare a static-scoped static key that defaults to false. The `DEFINE_STATIC_KEY_FALSE` macro takes care of this. The static key itself should be declared as a `static` variable.

- When deciding to invoke code that's only used by scrub, the regular filesystem should call the `static_branch_unlikely` predicate to avoid the scrub-only hook code if the static key is not enabled.

- The regular filesystem should export helper functions that call `static_branch_inc` to enable and `static_branch_dec` to disable the static key. Wrapper functions make it easy to compile out the relevant code if the kernel distributor turns off online fsck at build time.

- Scrub functions wanting to turn on scrub-only XFS functionality should call the `xchk_fsgates_enable` from the setup function to enable a specific hook. This must be done before obtaining any resources that are used by memory reclaim. Callers had better be sure they really need the functionality gated by the static key; the `TRY_HARDER` flag is useful here.

Online scrub has resource acquisition helpers (e.g. `xchk_perag_lock`) to handle locking AGI and AGF buffers for all scrubber functions. If it detects a conflict between scrub and the running transactions, it will try to wait for intents to complete. If the caller of the helper has not enabled the static key, the helper will return -EDEADLOCK, which should result in the scrub being restarted with the `TRY_HARDER` flag set. The scrub setup function should detect that flag, enable the static key, and try the scrub again. Scrub teardown disables all static keys obtained by `xchk_fsgates_enable`.

For more information, please see the kernel documentation of [Documentation/staging/static-keys.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/staging/static-keys.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92).

<a id="rst-pageable-kernel-memory"></a>
<a id="rst-xfile"></a>

### Pageable Kernel Memory

Some online checking functions work by scanning the filesystem to build a shadow copy of an ondisk metadata structure in memory and comparing the two copies. For online repair to rebuild a metadata structure, it must compute the record set that will be stored in the new structure before it can persist that new structure to disk. Ideally, repairs complete with a single atomic commit that introduces a new data structure. To meet these goals, the kernel needs to collect a large amount of information in a place that doesn't require the correct operation of the filesystem.

Kernel memory isn't suitable because:

- Allocating a contiguous region of memory to create a C array is very difficult, especially on 32-bit systems.

- Linked lists of records introduce double pointer overhead which is very high and eliminate the possibility of indexed lookups.

- Kernel memory is pinned, which can drive the system into OOM conditions.

- The system might not have sufficient memory to stage all the information.

At any given time, online fsck does not need to keep the entire record set in memory, which means that individual records can be paged out if necessary. Continued development of online fsck demonstrated that the ability to perform indexed data storage would also be very useful. Fortunately, the Linux kernel already has a facility for byte-addressable and pageable storage: tmpfs. In-kernel graphics drivers (most notably i915) take advantage of tmpfs files to store intermediate data that doesn't need to be in memory at all times, so that usage precedent is already established. Hence, the `xfile` was born\!


<table>
<tbody>
<tr>
<td>


**Historical Sidebar**:

</td>
</tr>
<tr>
<td>


The first edition of online repair inserted records into a new btree as it found them, which failed because filesystem could shut down with a built data structure, which would be live after recovery finished.

The second edition solved the half-rebuilt structure problem by storing everything in memory, but frequently ran the system out of memory.

The third edition solved the OOM problem by using linked lists, but the memory overhead of the list pointers was extreme.

</td>
</tr>
</tbody>
</table>

<a id="rst-xfile-access-models"></a>

#### xfile Access Models

A survey of the intended uses of xfiles suggested these use cases:

1. Arrays of fixed-sized records (space management btrees, directory and extended attribute entries)

2. Sparse arrays of fixed-sized records (quotas and link counts)

3. Large binary objects (BLOBs) of variable sizes (directory and extended attribute names and values)

4. Staging btrees in memory (reverse mapping btrees)

5. Arbitrary contents (realtime space management)

To support the first four use cases, high level data structures wrap the xfile to share functionality between online fsck functions. The rest of this section discusses the interfaces that the xfile presents to four of those five higher level data structures. The fifth use case is discussed in the [realtime summary](<#rst-rtsummary>) case study.

XFS is very record-based, which suggests that the ability to load and store complete records is important. To support these cases, a pair of `xfile_load` and `xfile_store` functions are provided to read and persist objects into an xfile that treat any error as an out of memory error.  For online repair, squashing error conditions in this manner is an acceptable behavior because the only reaction is to abort the operation back to userspace.

However, no discussion of file access idioms is complete without answering the question, "But what about mmap?" It is convenient to access storage directly with pointers, just like userspace code does with regular memory. Online fsck must not drive the system into OOM conditions, which means that xfiles must be responsive to memory reclamation. tmpfs can only push a pagecache folio to the swap cache if the folio is neither pinned nor locked, which means the xfile must not pin too many folios.

Short term direct access to xfile contents is done by locking the pagecache folio and mapping it into kernel address space.  Object load and store uses this mechanism.  Folio locks are not supposed to be held for long periods of time, so long term direct access to xfile contents is done by bumping the folio refcount, mapping it into kernel address space, and dropping the folio lock. These long term users *must* be responsive to memory reclaim by hooking into the shrinker infrastructure to know when to release folios.

The `xfile_get_folio` and `xfile_put_folio` functions are provided to retrieve the (locked) folio that backs part of an xfile and to release it. The only code to use these folio lease functions are the xfarray [sorting](<#rst-xfarray-sort>) algorithms and the [in-memory btrees](<#rst-xfbtree>).

<a id="rst-xfile-access-coordination"></a>

#### xfile Access Coordination

For security reasons, xfiles must be owned privately by the kernel. They are marked `S_PRIVATE` to prevent interference from the security system, must never be mapped into process file descriptor tables, and their pages must never be mapped into userspace processes.

To avoid locking recursion issues with the VFS, all accesses to the shmfs file are performed by manipulating the page cache directly. xfile writers call the `->write_begin` and `->write_end` functions of the xfile's address space to grab writable pages, copy the caller's buffer into the page, and release the pages. xfile readers call `shmem_read_mapping_page_gfp` to grab pages directly before copying the contents into the caller's buffer. In other words, xfiles ignore the VFS read and write code paths to avoid having to create a dummy `struct kiocb` and to avoid taking inode and freeze locks. tmpfs cannot be frozen, and xfiles must not be exposed to userspace.

If an xfile is shared between threads to stage repairs, the caller must provide its own locks to coordinate access. For example, if a scrub function stores scan results in an xfile and needs other threads to provide updates to the scanned data, the scrub function must provide a lock for all threads to share.

<a id="rst-arrays-of-fixed-sized-records"></a>
<a id="rst-xfarray"></a>

#### Arrays of Fixed-Sized Records

In XFS, each type of indexed space metadata (free space, inodes, reference counts, file fork space, and reverse mappings) consists of a set of fixed-size records indexed with a classic B+ tree. Directories have a set of fixed-size dirent records that point to the names, and extended attributes have a set of fixed-size attribute keys that point to names and values. Quota counters and file link counters index records with numbers. During a repair, scrub needs to stage new records during the gathering step and retrieve them during the btree building step.

Although this requirement can be satisfied by calling the read and write methods of the xfile directly, it is simpler for callers for there to be a higher level abstraction to take care of computing array offsets, to provide iterator functions, and to deal with sparse records and sorting. The `xfarray` abstraction presents a linear array for fixed-size records atop the byte-accessible xfile.

<a id="rst-array-access-patterns"></a>
<a id="rst-xfarray-access-patterns"></a>

##### Array Access Patterns

Array access patterns in online fsck tend to fall into three categories. Iteration of records is assumed to be necessary for all cases and will be covered in the next section.

The first type of caller handles records that are indexed by position. Gaps may exist between records, and a record may be updated multiple times during the collection step. In other words, these callers want a sparse linearly addressed table file. The typical use case are quota records or file link count records. Access to array elements is performed programmatically via `xfarray_load` and `xfarray_store` functions, which wrap the similarly-named xfile functions to provide loading and storing of array elements at arbitrary array indices. Gaps are defined to be null records, and null records are defined to be a sequence of all zero bytes. Null records are detected by calling `xfarray_element_is_null`. They are created either by calling `xfarray_unset` to null out an existing record or by never storing anything to an array index.

The second type of caller handles records that are not indexed by position and do not require multiple updates to a record. The typical use case here is rebuilding space btrees and key/value btrees. These callers can add records to the array without caring about array indices via the `xfarray_append` function, which stores a record at the end of the array. For callers that require records to be presentable in a specific order (e.g. rebuilding btree data), the `xfarray_sort` function can arrange the sorted records; this function will be covered later.

The third type of caller is a bag, which is useful for counting records. The typical use case here is constructing space extent reference counts from reverse mapping information. Records can be put in the bag in any order, they can be removed from the bag at any time, and uniqueness of records is left to callers. The `xfarray_store_anywhere` function is used to insert a record in any null record slot in the bag; and the `xfarray_unset` function removes a record from the bag.

<a id="rst-iterating-array-elements"></a>

##### Iterating Array Elements

Most users of the xfarray require the ability to iterate the records stored in the array. Callers can probe every possible array index with the following:



```c
xfarray_idx_t i;
foreach_xfarray_idx(array, i) {
    xfarray_load(array, i, &rec);

    /* do something with rec */
}
```

All users of this idiom must be prepared to handle null records or must already know that there aren't any.

For xfarray users that want to iterate a sparse array, the `xfarray_iter` function ignores indices in the xfarray that have never been written to by calling `xfile_seek_data` (which internally uses `SEEK_DATA`) to skip areas of the array that are not populated with memory pages. Once it finds a page, it will skip the zeroed areas of the page.



```c
xfarray_idx_t i = XFARRAY_CURSOR_INIT;
while ((ret = xfarray_iter(array, &i, &rec)) == 1) {
    /* do something with rec */
}
```

<a id="rst-sorting-array-elements"></a>
<a id="rst-xfarray-sort"></a>

##### Sorting Array Elements

During the fourth demonstration of online repair, a community reviewer remarked that for performance reasons, online repair ought to load batches of records into btree record blocks instead of inserting records into a new btree one at a time. The btree insertion code in XFS is responsible for maintaining correct ordering of the records, so naturally the xfarray must also support sorting the record set prior to bulk loading.

<a id="rst-case-study-sorting-xfarrays"></a>

###### Case Study: Sorting xfarrays

The sorting algorithm used in the xfarray is actually a combination of adaptive quicksort and a heapsort subalgorithm in the spirit of [Sedgewick](<https://algs4.cs.princeton.edu/23quicksort/>)<a id="rst-sedgewick"></a> and [pdqsort](<https://github.com/orlp/pdqsort>)<a id="rst-pdqsort"></a>, with customizations for the Linux kernel. To sort records in a reasonably short amount of time, `xfarray` takes advantage of the binary subpartitioning offered by quicksort, but it also uses heapsort to hedge against performance collapse if the chosen quicksort pivots are poor. Both algorithms are (in general) O(n \* lg(n)), but there is a wide performance gulf between the two implementations.

The Linux kernel already contains a reasonably fast implementation of heapsort. It only operates on regular C arrays, which limits the scope of its usefulness. There are two key places where the xfarray uses it:

- Sorting any record subset backed by a single xfile page.

- Loading a small number of xfarray records from potentially disparate parts of the xfarray into a memory buffer, and sorting the buffer.

In other words, `xfarray` uses heapsort to constrain the nested recursion of quicksort, thereby mitigating quicksort's worst runtime behavior.

Choosing a quicksort pivot is a tricky business. A good pivot splits the set to sort in half, leading to the divide and conquer behavior that is crucial to  O(n \* lg(n)) performance. A poor pivot barely splits the subset at all, leading to O(n<sup>2</sup>) runtime. The xfarray sort routine tries to avoid picking a bad pivot by sampling nine records into a memory buffer and using the kernel heapsort to identify the median of the nine.

Most modern quicksort implementations employ Tukey's "ninther" to select a pivot from a classic C array. Typical ninther implementations pick three unique triads of records, sort each of the triads, and then sort the middle value of each triad to determine the ninther value. As stated previously, however, xfile accesses are not entirely cheap. It turned out to be much more performant to read the nine elements into a memory buffer, run the kernel's in-memory heapsort on the buffer, and choose the 4th element of that buffer as the pivot. Tukey's ninthers are described in J. W. Tukey, `The ninther, a technique for low-effort robust (resistant) location in large samples`, in *Contributions to Survey Sampling and Applied Statistics*, edited by H. David, (Academic Press, 1978), pp. 251–257.

The partitioning of quicksort is fairly textbook -- rearrange the record subset around the pivot, then set up the current and next stack frames to sort with the larger and the smaller halves of the pivot, respectively. This keeps the stack space requirements to log2(record count).

As a final performance optimization, the hi and lo scanning phase of quicksort keeps examined xfile pages mapped in the kernel for as long as possible to reduce map/unmap cycles. Surprisingly, this reduces overall sort runtime by nearly half again after accounting for the application of heapsort directly onto xfile pages.

<a id="rst-blob-storage"></a>
<a id="rst-xfblob"></a>

#### Blob Storage

Extended attributes and directories add an additional requirement for staging records: arbitrary byte sequences of finite length. Each directory entry record needs to store entry name, and each extended attribute needs to store both the attribute name and value. The names, keys, and values can consume a large amount of memory, so the `xfblob` abstraction was created to simplify management of these blobs atop an xfile.

Blob arrays provide `xfblob_load` and `xfblob_store` functions to retrieve and persist objects. The store function returns a magic cookie for every object that it persists. Later, callers provide this cookie to the `xblob_load` to recall the object. The `xfblob_free` function frees a specific blob, and the `xfblob_truncate` function frees them all because compaction is not needed.

The details of repairing directories and extended attributes will be discussed in a subsequent section about atomic file content exchanges. However, it should be noted that these repair functions only use blob storage to cache a small number of entries before adding them to a temporary ondisk file, which is why compaction is not required.

<a id="rst-in-memory-b-trees"></a>
<a id="rst-xfbtree"></a>

#### In-Memory B+Trees

The chapter about [secondary metadata](<#rst-secondary-metadata>) mentioned that checking and repairing of secondary metadata commonly requires coordination between a live metadata scan of the filesystem and writer threads that are updating that metadata. Keeping the scan data up to date requires the ability to propagate metadata updates from the filesystem into the data being collected by the scan. This *can* be done by appending concurrent updates into a separate log file and applying them before writing the new metadata to disk, but this leads to unbounded memory consumption if the rest of the system is very busy. Another option is to skip the side-log and commit live updates from the filesystem directly into the scan data, which trades more overhead for a lower maximum memory requirement. In both cases, the data structure holding the scan results must support indexed access to perform well.

Given that indexed lookups of scan data is required for both strategies, online fsck employs the second strategy of committing live updates directly into scan data. Because xfarrays are not indexed and do not enforce record ordering, they are not suitable for this task. Conveniently, however, XFS has a library to create and maintain ordered reverse mapping records: the existing rmap btree code\! If only there was a means to create one in memory.

Recall that the [xfile](<#rst-xfile>) abstraction represents memory pages as a regular file, which means that the kernel can create byte or block addressable virtual address spaces at will. The XFS buffer cache specializes in abstracting IO to block-oriented  address spaces, which means that adaptation of the buffer cache to interface with xfiles enables reuse of the entire btree library. Btrees built atop an xfile are collectively known as `xfbtrees`. The next few sections describe how they actually work.

<a id="rst-using-xfiles-as-a-buffer-cache-target"></a>

##### Using xfiles as a Buffer Cache Target

Two modifications are necessary to support xfiles as a buffer cache target. The first is to make it possible for the `struct xfs_buftarg` structure to host the `struct xfs_buf` rhashtable, because normally those are held by a per-AG structure. The second change is to modify the buffer `ioapply` function to "read" cached pages from the xfile and "write" cached pages back to the xfile. Multiple access to individual buffers is controlled by the `xfs_buf` lock, since the xfile does not provide any locking on its own. With this adaptation in place, users of the xfile-backed buffer cache use exactly the same APIs as users of the disk-backed buffer cache. The separation between xfile and buffer cache implies higher memory usage since they do not share pages, but this property could some day enable transactional updates to an in-memory btree. Today, however, it simply eliminates the need for new code.

<a id="rst-space-management-with-an-xfbtree"></a>

##### Space Management with an xfbtree

Space management for an xfile is very simple -- each btree block is one memory page in size. These blocks use the same header format as an on-disk btree, but the in-memory block verifiers ignore the checksums, assuming that xfile memory is no more corruption-prone than regular DRAM. Reusing existing code here is more important than absolute memory efficiency.

The very first block of an xfile backing an xfbtree contains a header block. The header describes the owner, height, and the block number of the root xfbtree block.

To allocate a btree block, use `xfile_seek_data` to find a gap in the file. If there are no gaps, create one by extending the length of the xfile. Preallocate space for the block with `xfile_prealloc`, and hand back the location. To free an xfbtree block, use `xfile_discard` (which internally uses `FALLOC_FL_PUNCH_HOLE`) to remove the memory page from the xfile.

<a id="rst-populating-an-xfbtree"></a>

##### Populating an xfbtree

An online fsck function that wants to create an xfbtree should proceed as follows:

1. Call `xfile_create` to create an xfile.

2. Call `xfs_alloc_memory_buftarg` to create a buffer cache target structure pointing to the xfile.

3. Pass the buffer cache target, buffer ops, and other information to `xfbtree_init` to initialize the passed in `struct xfbtree` and write an initial root block to the xfile. Each btree type should define a wrapper that passes necessary arguments to the creation function. For example, rmap btrees define `xfs_rmapbt_mem_create` to take care of all the necessary details for callers.

4. Pass the xfbtree object to the btree cursor creation function for the btree type. Following the example above, `xfs_rmapbt_mem_cursor` takes care of this for callers.

5. Pass the btree cursor to the regular btree functions to make queries against and to update the in-memory btree. For example, a btree cursor for an rmap xfbtree can be passed to the `xfs_rmap_*` functions just like any other btree cursor. See the [next section](<#rst-xfbtree-commit>) for information on dealing with xfbtree updates that are logged to a transaction.

6. When finished, delete the btree cursor, destroy the xfbtree object, free the buffer target, and the destroy the xfile to release all resources.

<a id="rst-committing-logged-xfbtree-buffers"></a>
<a id="rst-xfbtree-commit"></a>

##### Committing Logged xfbtree Buffers

Although it is a clever hack to reuse the rmap btree code to handle the staging structure, the ephemeral nature of the in-memory btree block storage presents some challenges of its own. The XFS transaction manager must not commit buffer log items for buffers backed by an xfile because the log format does not understand updates for devices other than the data device. An ephemeral xfbtree probably will not exist by the time the AIL checkpoints log transactions back into the filesystem, and certainly won't exist during log recovery. For these reasons, any code updating an xfbtree in transaction context must remove the buffer log items from the transaction and write the updates into the backing xfile before committing or cancelling the transaction.

The `xfbtree_trans_commit` and `xfbtree_trans_cancel` functions implement this functionality as follows:

1. Find each buffer log item whose buffer targets the xfile.

2. Record the dirty/ordered status of the log item.

3. Detach the log item from the buffer.

4. Queue the buffer to a special delwri list.

5. Clear the transaction dirty flag if the only dirty log items were the ones that were detached in step 3.

6. Submit the delwri list to commit the changes to the xfile, if the updates are being committed.

After removing xfile logged buffers from the transaction in this manner, the transaction can be committed or cancelled.

<a id="rst-bulk-loading-of-ondisk-b-trees"></a>

### Bulk Loading of Ondisk B+Trees

As mentioned previously, early iterations of online repair built new btree structures by creating a new btree and adding observations individually. Loading a btree one record at a time had a slight advantage of not requiring the incore records to be sorted prior to commit, but was very slow and leaked blocks if the system went down during a repair. Loading records one at a time also meant that repair could not control the loading factor of the blocks in the new btree.

Fortunately, the venerable `xfs_repair` tool had a more efficient means for rebuilding a btree index from a collection of records -- bulk btree loading. This was implemented rather inefficiently code-wise, since `xfs_repair` had separate copy-pasted implementations for each btree type.

To prepare for online fsck, each of the four bulk loaders were studied, notes were taken, and the four were refactored into a single generic btree bulk loading mechanism. Those notes in turn have been refreshed and are presented below.

<a id="rst-geometry-computation"></a>

#### Geometry Computation

The zeroth step of bulk loading is to assemble the entire record set that will be stored in the new btree, and sort the records. Next, call `xfs_btree_bload_compute_geometry` to compute the shape of the btree from the record set, the type of btree, and any load factor preferences. This information is required for resource reservation.

First, the geometry computation computes the minimum and maximum records that will fit in a leaf block from the size of a btree block and the size of the block header. Roughly speaking, the maximum number of records is:



```text
maxrecs = (block_size - header_size) / record_size
```

The XFS design specifies that btree blocks should be merged when possible, which means the minimum number of records is half of maxrecs:



```text
minrecs = maxrecs / 2
```

The next variable to determine is the desired loading factor. This must be at least minrecs and no more than maxrecs. Choosing minrecs is undesirable because it wastes half the block. Choosing maxrecs is also undesirable because adding a single record to each newly rebuilt leaf block will cause a tree split, which causes a noticeable drop in performance immediately afterwards. The default loading factor was chosen to be 75% of maxrecs, which provides a reasonably compact structure without any immediate split penalties:



```text
default_load_factor = (maxrecs + minrecs) / 2
```

If space is tight, the loading factor will be set to maxrecs to try to avoid running out of space:



```text
leaf_load_factor = enough space ? default_load_factor : maxrecs
```

Load factor is computed for btree node blocks using the combined size of the btree key and pointer as the record size:



```text
maxrecs = (block_size - header_size) / (key_size + ptr_size)
minrecs = maxrecs / 2
node_load_factor = enough space ? default_load_factor : maxrecs
```

Once that's done, the number of leaf blocks required to store the record set can be computed as:



```text
leaf_blocks = ceil(record_count / leaf_load_factor)
```

The number of node blocks needed to point to the next level down in the tree is computed as:



```text
n_blocks = (n == 0 ? leaf_blocks : node_blocks[n])
node_blocks[n + 1] = ceil(n_blocks / node_load_factor)
```

The entire computation is performed recursively until the current level only needs one block. The resulting geometry is as follows:

- For AG-rooted btrees, this level is the root level, so the height of the new tree is `level + 1` and the space needed is the summation of the number of blocks on each level.

- For inode-rooted btrees where the records in the top level do not fit in the inode fork area, the height is `level + 2`, the space needed is the summation of the number of blocks on each level, and the inode fork points to the root block.

- For inode-rooted btrees where the records in the top level can be stored in the inode fork area, then the root block can be stored in the inode, the height is `level + 1`, and the space needed is one less than the summation of the number of blocks on each level. This only becomes relevant when non-bmap btrees gain the ability to root in an inode, which is a future patchset and only included here for completeness.

<a id="rst-reserving-new-b-tree-blocks"></a>
<a id="rst-newbt"></a>

#### Reserving New B+Tree Blocks

Once repair knows the number of blocks needed for the new btree, it allocates those blocks using the free space information. Each reserved extent is tracked separately by the btree builder state data. To improve crash resilience, the reservation code also logs an Extent Freeing Intent (EFI) item in the same transaction as each space allocation and attaches its in-memory `struct xfs_extent_free_item` object to the space reservation. If the system goes down, log recovery will use the unfinished EFIs to free the unused space, the free space, leaving the filesystem unchanged.

Each time the btree builder claims a block for the btree from a reserved extent, it updates the in-memory reservation to reflect the claimed space. Block reservation tries to allocate as much contiguous space as possible to reduce the number of EFIs in play.

While repair is writing these new btree blocks, the EFIs created for the space reservations pin the tail of the ondisk log. It's possible that other parts of the system will remain busy and push the head of the log towards the pinned tail. To avoid livelocking the filesystem, the EFIs must not pin the tail of the log for too long. To alleviate this problem, the dynamic relogging capability of the deferred ops mechanism is reused here to commit a transaction at the log head containing an EFD for the old EFI and new EFI at the head. This enables the log to release the old EFI to keep the log moving forwards.

EFIs have a role to play during the commit and reaping phases; please see the next section and the section about [reaping](<#rst-reaping>) for more details.

<a id="rst-writing-the-new-tree"></a>

#### Writing the New Tree

This part is pretty simple -- the btree builder (`xfs_btree_bulkload`) claims a block from the reserved list, writes the new btree block header, fills the rest of the block with records, and adds the new leaf block to a list of written blocks:



```text
┌────┐
│leaf│
│RRR │
└────┘
```

Sibling pointers are set every time a new block is added to the level:



```text
┌────┐ ┌────┐ ┌────┐ ┌────┐
│leaf│→│leaf│→│leaf│→│leaf│
│RRR │←│RRR │←│RRR │←│RRR │
└────┘ └────┘ └────┘ └────┘
```

When it finishes writing the record leaf blocks, it moves on to the node blocks To fill a node block, it walks each block in the next level down in the tree to compute the relevant keys and write them into the parent node:



```text
    ┌────┐       ┌────┐
    │node│──────→│node│
    │PP  │←──────│PP  │
    └────┘       └────┘
    ↙   ↘         ↙   ↘
┌────┐ ┌────┐ ┌────┐ ┌────┐
│leaf│→│leaf│→│leaf│→│leaf│
│RRR │←│RRR │←│RRR │←│RRR │
└────┘ └────┘ └────┘ └────┘
```

When it reaches the root level, it is ready to commit the new btree\!:



```text
        ┌─────────┐
        │  root   │
        │   PP    │
        └─────────┘
        ↙         ↘
    ┌────┐       ┌────┐
    │node│──────→│node│
    │PP  │←──────│PP  │
    └────┘       └────┘
    ↙   ↘         ↙   ↘
┌────┐ ┌────┐ ┌────┐ ┌────┐
│leaf│→│leaf│→│leaf│→│leaf│
│RRR │←│RRR │←│RRR │←│RRR │
└────┘ └────┘ └────┘ └────┘
```

The first step to commit the new btree is to persist the btree blocks to disk synchronously. This is a little complicated because a new btree block could have been freed in the recent past, so the builder must use `xfs_buf_delwri_queue_here` to remove the (stale) buffer from the AIL list before it can write the new blocks to disk. Blocks are queued for IO using a delwri list and written in one large batch with `xfs_buf_delwri_submit`.

Once the new blocks have been persisted to disk, control returns to the individual repair function that called the bulk loader. The repair function must log the location of the new root in a transaction, clean up the space reservations that were made for the new btree, and reap the old metadata blocks:

1. Commit the location of the new btree root.

2. For each incore reservation:

   - **a.** Log Extent Freeing Done (EFD) items for all the space that was consumed by the btree builder.  The new EFDs must point to the EFIs attached to the reservation to prevent log recovery from freeing the new blocks.

   - **b.** For unclaimed portions of incore reservations, create a regular deferred extent free work item to be free the unused space later in the transaction chain.

   - **c.** The EFDs and EFIs logged in steps 2a and 2b must not overrun the reservation of the committing transaction. If the btree loading code suspects this might be about to happen, it must call `xrep_defer_finish` to clear out the deferred work and obtain a fresh transaction.

3. Clear out the deferred work a second time to finish the commit and clean the repair transaction.

The transaction rolling in steps 2c and 3 represent a weakness in the repair algorithm, because a log flush and a crash before the end of the reap step can result in space leaking. Online repair functions minimize the chances of this occurring by using very large transactions, which each can accommodate many thousands of block freeing instructions. Repair moves on to reaping the old blocks, which will be presented in a subsequent [section](<#rst-reaping>) after a few case studies of bulk loading.

<a id="rst-case-study-rebuilding-the-inode-index"></a>

##### Case Study: Rebuilding the Inode Index

The high level process to rebuild the inode index btree is:

1. Walk the reverse mapping records to generate `struct xfs_inobt_rec` records from the inode chunk information and a bitmap of the old inode btree blocks.

2. Append the records to an xfarray in inode order.

3. Use the `xfs_btree_bload_compute_geometry` function to compute the number of blocks needed for the inode btree. If the free space inode btree is enabled, call it again to estimate the geometry of the finobt.

4. Allocate the number of blocks computed in the previous step.

5. Use `xfs_btree_bload` to write the xfarray records to btree blocks and generate the internal node blocks. If the free space inode btree is enabled, call it again to load the finobt.

6. Commit the location of the new btree root block(s) to the AGI.

7. Reap the old btree blocks using the bitmap created in step 1.

Details are as follows.

The inode btree maps inumbers to the ondisk location of the associated inode records, which means that the inode btrees can be rebuilt from the reverse mapping information. Reverse mapping records with an owner of `XFS_RMAP_OWN_INOBT` marks the location of the old inode btree blocks. Each reverse mapping record with an owner of `XFS_RMAP_OWN_INODES` marks the location of at least one inode cluster buffer. A cluster is the smallest number of ondisk inodes that can be allocated or freed in a single transaction; it is never smaller than 1 fs block or 4 inodes.

For the space represented by each inode cluster, ensure that there are no records in the free space btrees nor any records in the reference count btree. If there are, the space metadata inconsistencies are reason enough to abort the operation. Otherwise, read each cluster buffer to check that its contents appear to be ondisk inodes and to decide if the file is allocated (`xfs_dinode.i_mode != 0`) or free (`xfs_dinode.i_mode == 0`). Accumulate the results of successive inode cluster buffer reads until there is enough information to fill a single inode chunk record, which is 64 consecutive numbers in the inumber keyspace. If the chunk is sparse, the chunk record may include holes.

Once the repair function accumulates one chunk's worth of data, it calls `xfarray_append` to add the inode btree record to the xfarray. This xfarray is walked twice during the btree creation step -- once to populate the inode btree with all inode chunk records, and a second time to populate the free inode btree with records for chunks that have free non-sparse inodes. The number of records for the inode btree is the number of xfarray records, but the record count for the free inode btree has to be computed as inode chunk records are stored in the xfarray.

<a id="rst-case-study-rebuilding-the-space-reference-counts"></a>

##### Case Study: Rebuilding the Space Reference Counts

Reverse mapping records are used to rebuild the reference count information. Reference counts are required for correct operation of copy on write for shared file data. Imagine the reverse mapping entries as rectangles representing extents of physical blocks, and that the rectangles can be laid down to allow them to overlap each other. From the diagram below, it is apparent that a reference count record must start or end wherever the height of the stack changes. In other words, the record emission stimulus is level-triggered:



```text
                █    ███
      ██      █████ ████   ███        ██████
██   ████     ███████████ ████     █████████
████████████████████████████████ ███████████
^ ^  ^^ ^^    ^ ^^ ^^^  ^^^^  ^ ^^ ^  ^     ^
2 1  23 21    3 43 234  2123  1 01 2  3     0
```

The ondisk reference count btree does not store the refcount == 0 cases because the free space btree already records which blocks are free. Extents being used to stage copy-on-write operations should be the only records with refcount == 1. Single-owner file blocks aren't recorded in either the free space or the reference count btrees.

The high level process to rebuild the reference count btree is:

1. Walk the reverse mapping records to generate `struct xfs_refcount_irec` records for any space having more than one reverse mapping and add them to the xfarray. Any records owned by `XFS_RMAP_OWN_COW` are also added to the xfarray because these are extents allocated to stage a copy on write operation and are tracked in the refcount btree.

   Use any records owned by `XFS_RMAP_OWN_REFC` to create a bitmap of old refcount btree blocks.

2. Sort the records in physical extent order, putting the CoW staging extents at the end of the xfarray. This matches the sorting order of records in the refcount btree.

3. Use the `xfs_btree_bload_compute_geometry` function to compute the number of blocks needed for the new tree.

4. Allocate the number of blocks computed in the previous step.

5. Use `xfs_btree_bload` to write the xfarray records to btree blocks and generate the internal node blocks.

6. Commit the location of new btree root block to the AGF.

7. Reap the old btree blocks using the bitmap created in step 1.

Details are as follows; the same algorithm is used by `xfs_repair` to generate refcount information from reverse mapping records.

- Until the reverse mapping btree runs out of records:

  - Retrieve the next record from the btree and put it in a bag.

  - Collect all records with the same starting block from the btree and put them in the bag.

  - While the bag isn't empty:

    - Among the mappings in the bag, compute the lowest block number where the reference count changes. This position will be either the starting block number of the next unprocessed reverse mapping or the next block after the shortest mapping in the bag.

    - Remove all mappings from the bag that end at this position.

    - Collect all reverse mappings that start at this position from the btree and put them in the bag.

    - If the size of the bag changed and is greater than one, create a new refcount record associating the block number range that we just walked to the size of the bag.

The bag-like structure in this case is a type 2 xfarray as discussed in the [xfarray access patterns](<#rst-xfarray-access-patterns>) section. Reverse mappings are added to the bag using `xfarray_store_anywhere` and removed via `xfarray_unset`. Bag members are examined through `xfarray_iter` loops.

<a id="rst-case-study-rebuilding-file-fork-mapping-indices"></a>

##### Case Study: Rebuilding File Fork Mapping Indices

The high level process to rebuild a data/attr fork mapping btree is:

1. Walk the reverse mapping records to generate `struct xfs_bmbt_rec` records from the reverse mapping records for that inode and fork. Append these records to an xfarray. Compute the bitmap of the old bmap btree blocks from the `BMBT_BLOCK` records.

2. Use the `xfs_btree_bload_compute_geometry` function to compute the number of blocks needed for the new tree.

3. Sort the records in file offset order.

4. If the extent records would fit in the inode fork immediate area, commit the records to that immediate area and skip to step 8.

5. Allocate the number of blocks computed in the previous step.

6. Use `xfs_btree_bload` to write the xfarray records to btree blocks and generate the internal node blocks.

7. Commit the new btree root block to the inode fork immediate area.

8. Reap the old btree blocks using the bitmap created in step 1.

There are some complications here: First, it's possible to move the fork offset to adjust the sizes of the immediate areas if the data and attr forks are not both in BMBT format. Second, if there are sufficiently few fork mappings, it may be possible to use EXTENTS format instead of BMBT, which may require a conversion. Third, the incore extent map must be reloaded carefully to avoid disturbing any delayed allocation extents.

<a id="rst-reaping-old-metadata-blocks"></a>
<a id="rst-reaping"></a>

### Reaping Old Metadata Blocks

Whenever online fsck builds a new data structure to replace one that is suspect, there is a question of how to find and dispose of the blocks that belonged to the old structure. The laziest method of course is not to deal with them at all, but this slowly leads to service degradations as space leaks out of the filesystem. Hopefully, someone will schedule a rebuild of the free space information to plug all those leaks. Offline repair rebuilds all space metadata after recording the usage of the files and directories that it decides not to clear, hence it can build new structures in the discovered free space and avoid the question of reaping.

As part of a repair, online fsck relies heavily on the reverse mapping records to find space that is owned by the corresponding rmap owner yet truly free. Cross referencing rmap records with other rmap records is necessary because there may be other data structures that also think they own some of those blocks (e.g. crosslinked trees). Permitting the block allocator to hand them out again will not push the system towards consistency.

For space metadata, the process of finding extents to dispose of generally follows this format:

1. Create a bitmap of space used by data structures that must be preserved. The space reservations used to create the new metadata can be used here if the same rmap owner code is used to denote all of the objects being rebuilt.

2. Survey the reverse mapping data to create a bitmap of space owned by the same `XFS_RMAP_OWN_*` number for the metadata that is being preserved.

3. Use the bitmap disunion operator to subtract (1) from (2). The remaining set bits represent candidate extents that could be freed. The process moves on to step 4 below.

Repairs for file-based metadata such as extended attributes, directories, symbolic links, quota files and realtime bitmaps are performed by building a new structure attached to a temporary file and exchanging all mappings in the file forks. Afterward, the mappings in the old file fork are the candidate blocks for disposal.

The process for disposing of old extents is as follows:

4. For each candidate extent, count the number of reverse mapping records for the first block in that extent that do not have the same rmap owner for the data structure being repaired.

   - If zero, the block has a single owner and can be freed.

   - If not, the block is part of a crosslinked structure and must not be freed.

5. Starting with the next block in the extent, figure out how many more blocks have the same zero/nonzero other owner status as that first block.

6. If the region is crosslinked, delete the reverse mapping entry for the structure being repaired and move on to the next region.

7. If the region is to be freed, mark any corresponding buffers in the buffer cache as stale to prevent log writeback.

8. Free the region and move on.

However, there is one complication to this procedure. Transactions are of finite size, so the reaping process must be careful to roll the transactions to avoid overruns. Overruns come from two sources:

- **a.** EFIs logged on behalf of space that is no longer occupied

- **b.** Log items for buffer invalidations

This is also a window in which a crash during the reaping process can leak blocks. As stated earlier, online repair functions use very large transactions to minimize the chances of this occurring.

<a id="rst-case-study-reaping-after-a-regular-btree-repair"></a>

#### Case Study: Reaping After a Regular Btree Repair

Old reference count and inode btrees are the easiest to reap because they have rmap records with special owner codes: `XFS_RMAP_OWN_REFC` for the refcount btree, and `XFS_RMAP_OWN_INOBT` for the inode and free inode btrees. Creating a list of extents to reap the old btree blocks is quite simple, conceptually:

1. Lock the relevant AGI/AGF header buffers to prevent allocation and frees.

2. For each reverse mapping record with an rmap owner corresponding to the metadata structure being rebuilt, set the corresponding range in a bitmap.

3. Walk the current data structures that have the same rmap owner. For each block visited, clear that range in the above bitmap.

4. Each set bit in the bitmap represents a block that could be a block from the old data structures and hence is a candidate for reaping. In other words, `(rmap_records_owned_by & ~blocks_reachable_by_walk)` are the blocks that might be freeable.

If it is possible to maintain the AGF lock throughout the repair (which is the common case), then step 2 can be performed at the same time as the reverse mapping record walk that creates the records for the new btree.

<a id="rst-case-study-rebuilding-the-free-space-indices"></a>

#### Case Study: Rebuilding the Free Space Indices

The high level process to rebuild the free space indices is:

1. Walk the reverse mapping records to generate `struct xfs_alloc_rec_incore` records from the gaps in the reverse mapping btree.

2. Append the records to an xfarray.

3. Use the `xfs_btree_bload_compute_geometry` function to compute the number of blocks needed for each new tree.

4. Allocate the number of blocks computed in the previous step from the free space information collected.

5. Use `xfs_btree_bload` to write the xfarray records to btree blocks and generate the internal node blocks for the free space by length index. Call it again for the free space by block number index.

6. Commit the locations of the new btree root blocks to the AGF.

7. Reap the old btree blocks by looking for space that is not recorded by the reverse mapping btree, the new free space btrees, or the AGFL.

Repairing the free space btrees has three key complications over a regular btree repair:

First, free space is not explicitly tracked in the reverse mapping records. Hence, the new free space records must be inferred from gaps in the physical space component of the keyspace of the reverse mapping btree.

Second, free space repairs cannot use the common btree reservation code because new blocks are reserved out of the free space btrees. This is impossible when repairing the free space btrees themselves. However, repair holds the AGF buffer lock for the duration of the free space index reconstruction, so it can use the collected free space information to supply the blocks for the new free space btrees. It is not necessary to back each reserved extent with an EFI because the new free space btrees are constructed in what the ondisk filesystem thinks is unowned space. However, if reserving blocks for the new btrees from the collected free space information changes the number of free space records, repair must re-estimate the new free space btree geometry with the new record count until the reservation is sufficient. As part of committing the new btrees, repair must ensure that reverse mappings are created for the reserved blocks and that unused reserved blocks are inserted into the free space btrees. Deferrred rmap and freeing operations are used to ensure that this transition is atomic, similar to the other btree repair functions.

Third, finding the blocks to reap after the repair is not overly straightforward. Blocks for the free space btrees and the reverse mapping btrees are supplied by the AGFL. Blocks put onto the AGFL have reverse mapping records with the owner `XFS_RMAP_OWN_AG`. This ownership is retained when blocks move from the AGFL into the free space btrees or the reverse mapping btrees. When repair walks reverse mapping records to synthesize free space records, it creates a bitmap (`ag_owner_bitmap`) of all the space claimed by `XFS_RMAP_OWN_AG` records. The repair context maintains a second bitmap corresponding to the rmap btree blocks and the AGFL blocks (`rmap_agfl_bitmap`). When the walk is complete, the bitmap disunion operation `(ag_owner_bitmap & ~rmap_agfl_bitmap)` computes the extents that are used by the old free space btrees. These blocks can then be reaped using the methods outlined above.

<a id="rst-case-study-reaping-after-repairing-reverse-mapping-btrees"></a>
<a id="rst-rmap-reap"></a>

#### Case Study: Reaping After Repairing Reverse Mapping Btrees

Old reverse mapping btrees are less difficult to reap after a repair. As mentioned in the previous section, blocks on the AGFL, the two free space btree blocks, and the reverse mapping btree blocks all have reverse mapping records with `XFS_RMAP_OWN_AG` as the owner. The full process of gathering reverse mapping records and building a new btree are described in the case study of [live rebuilds of rmap data](<#rst-rmap-repair>), but a crucial point from that discussion is that the new rmap btree will not contain any records for the old rmap btree, nor will the old btree blocks be tracked in the free space btrees. The list of candidate reaping blocks is computed by setting the bits corresponding to the gaps in the new rmap btree records, and then clearing the bits corresponding to extents in the free space btrees and the current AGFL blocks. The result `(new_rmapbt_gaps & ~(agfl | bnobt_records))` are reaped using the methods outlined above.

The rest of the process of rebuildng the reverse mapping btree is discussed in a separate [case study](<#rst-rmap-repair>).

<a id="rst-case-study-rebuilding-the-agfl"></a>

#### Case Study: Rebuilding the AGFL

The allocation group free block list (AGFL) is repaired as follows:

1. Create a bitmap for all the space that the reverse mapping data claims is owned by `XFS_RMAP_OWN_AG`.

2. Subtract the space used by the two free space btrees and the rmap btree.

3. Subtract any space that the reverse mapping data claims is owned by any other owner, to avoid re-adding crosslinked blocks to the AGFL.

4. Once the AGFL is full, reap any blocks leftover.

5. The next operation to fix the freelist will right-size the list.

See [fs/xfs/scrub/agheader_repair.c](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/xfs/scrub/agheader_repair.c>)<a id="rst-fs-xfs-scrub-agheader-repair-c"></a> for more details.

<a id="rst-inode-record-repairs"></a>

### Inode Record Repairs

Inode records must be handled carefully, because they have both ondisk records ("dinodes") and an in-memory ("cached") representation. There is a very high potential for cache coherency issues if online fsck is not careful to access the ondisk metadata *only* when the ondisk metadata is so badly damaged that the filesystem cannot load the in-memory representation. When online fsck wants to open a damaged file for scrubbing, it must use specialized resource acquisition functions that return either the in-memory representation *or* a lock on whichever object is necessary to prevent any update to the ondisk location.

The only repairs that should be made to the ondisk inode buffers are whatever is necessary to get the in-core structure loaded. This means fixing whatever is caught by the inode cluster buffer and inode fork verifiers, and retrying the `iget` operation. If the second `iget` fails, the repair has failed.

Once the in-memory representation is loaded, repair can lock the inode and can subject it to comprehensive checks, repairs, and optimizations. Most inode attributes are easy to check and constrain, or are user-controlled arbitrary bit patterns; these are both easy to fix. Dealing with the data and attr fork extent counts and the file block counts is more complicated, because computing the correct value requires traversing the forks, or if that fails, leaving the fields invalid and waiting for the fork fsck functions to run.

<a id="rst-quota-record-repairs"></a>

### Quota Record Repairs

Similar to inodes, quota records ("dquots") also have both ondisk records and an in-memory representation, and hence are subject to the same cache coherency issues. Somewhat confusingly, both are known as dquots in the XFS codebase.

The only repairs that should be made to the ondisk quota record buffers are whatever is necessary to get the in-core structure loaded. Once the in-memory representation is loaded, the only attributes needing checking are obviously bad limits and timer values.

Quota usage counters are checked, repaired, and discussed separately in the section about [live quotacheck](<#rst-quotacheck>).

<a id="rst-freezing-to-fix-summary-counters"></a>
<a id="rst-fscounters"></a>

### Freezing to Fix Summary Counters

Filesystem summary counters track availability of filesystem resources such as free blocks, free inodes, and allocated inodes. This information could be compiled by walking the free space and inode indexes, but this is a slow process, so XFS maintains a copy in the ondisk superblock that should reflect the ondisk metadata, at least when the filesystem has been unmounted cleanly. For performance reasons, XFS also maintains incore copies of those counters, which are key to enabling resource reservations for active transactions. Writer threads reserve the worst-case quantities of resources from the incore counter and give back whatever they don't use at commit time. It is therefore only necessary to serialize on the superblock when the superblock is being committed to disk.

The lazy superblock counter feature introduced in XFS v5 took this even further by training log recovery to recompute the summary counters from the AG headers, which eliminated the need for most transactions even to touch the superblock. The only time XFS commits the summary counters is at filesystem unmount. To reduce contention even further, the incore counter is implemented as a percpu counter, which means that each CPU is allocated a batch of blocks from a global incore counter and can satisfy small allocations from the local batch.

The high-performance nature of the summary counters makes it difficult for online fsck to check them, since there is no way to quiesce a percpu counter while the system is running. Although online fsck can read the filesystem metadata to compute the correct values of the summary counters, there's no way to hold the value of a percpu counter stable, so it's quite possible that the counter will be out of date by the time the walk is complete. Earlier versions of online scrub would return to userspace with an incomplete scan flag, but this is not a satisfying outcome for a system administrator. For repairs, the in-memory counters must be stabilized while walking the filesystem metadata to get an accurate reading and install it in the percpu counter.

To satisfy this requirement, online fsck must prevent other programs in the system from initiating new writes to the filesystem, it must disable background garbage collection threads, and it must wait for existing writer programs to exit the kernel. Once that has been established, scrub can walk the AG free space indexes, the inode btrees, and the realtime bitmap to compute the correct value of all four summary counters. This is very similar to a filesystem freeze, though not all of the pieces are necessary:

- The final freeze state is set one higher than `SB_FREEZE_COMPLETE` to prevent other threads from thawing the filesystem, or other scrub threads from initiating another fscounters freeze.

- It does not quiesce the log.

With this code in place, it is now possible to pause the filesystem for just long enough to check and correct the summary counters.


<table>
<tbody>
<tr>
<td>


**Historical Sidebar**:

</td>
</tr>
<tr>
<td>


The initial implementation used the actual VFS filesystem freeze mechanism to quiesce filesystem activity. With the filesystem frozen, it is possible to resolve the counter values with exact precision, but there are many problems with calling the VFS methods directly:

- Other programs can unfreeze the filesystem without our knowledge. This leads to incorrect scan results and incorrect repairs.

- Adding an extra lock to prevent others from thawing the filesystem required the addition of a `->freeze_super` function to wrap `freeze_fs()`. This in turn caused other subtle problems because it turns out that the VFS `freeze_super` and `thaw_super` functions can drop the last reference to the VFS superblock, and any subsequent access becomes a UAF bug\! This can happen if the filesystem is unmounted while the underlying block device has frozen the filesystem. This problem could be solved by grabbing extra references to the superblock, but it felt suboptimal given the other inadequacies of this approach.

- The log need not be quiesced to check the summary counters, but a VFS freeze initiates one anyway. This adds unnecessary runtime to live fscounter fsck operations.

- Quiescing the log means that XFS flushes the (possibly incorrect) counters to disk as part of cleaning the log.

- A bug in the VFS meant that freeze could complete even when sync_filesystem fails to flush the filesystem and returns an error. This bug was fixed in Linux 5.17.

</td>
</tr>
</tbody>
</table>

<a id="rst-full-filesystem-scans"></a>

### Full Filesystem Scans

Certain types of metadata can only be checked by walking every file in the entire filesystem to record observations and comparing the observations against what's recorded on disk. Like every other type of online repair, repairs are made by writing those observations to disk in a replacement structure and committing it atomically. However, it is not practical to shut down the entire filesystem to examine hundreds of billions of files because the downtime would be excessive. Therefore, online fsck must build the infrastructure to manage a live scan of all the files in the filesystem. There are two questions that need to be solved to perform a live walk:

- How does scrub manage the scan while it is collecting data?

- How does the scan keep abreast of changes being made to the system by other threads?

<a id="rst-coordinated-inode-scans"></a>
<a id="rst-iscan"></a>

#### Coordinated Inode Scans

In the original Unix filesystems of the 1970s, each directory entry contained an index number (*inumber*) which was used as an index into on ondisk array (*itable*) of fixed-size records (*inodes*) describing a file's attributes and its data block mapping. This system is described by J. Lions, ["inode (5659)"](<http://www.lemis.com/grog/Documentation/Lions/>)<a id="rst-inode-5659"></a> in *Lions' Commentary on UNIX, 6th Edition*, (Dept. of Computer Science, the University of New South Wales, November 1977), pp. 18-2; and later by D. Ritchie and K. Thompson, ["Implementation of the File System"](<https://archive.org/details/bstj57-6-1905/page/n8/mode/1up>)<a id="rst-implementation-of-the-file-system"></a>, from *The UNIX Time-Sharing System*, (The Bell System Technical Journal, July 1978), pp. 1913-4.

XFS retains most of this design, except now inumbers are search keys over all the space in the data section filesystem. They form a continuous keyspace that can be expressed as a 64-bit integer, though the inodes themselves are sparsely distributed within the keyspace. Scans proceed in a linear fashion across the inumber keyspace, starting from `0x0` and ending at `0xFFFFFFFFFFFFFFFF`. Naturally, a scan through a keyspace requires a scan cursor object to track the scan progress. Because this keyspace is sparse, this cursor contains two parts. The first part of this scan cursor object tracks the inode that will be examined next; call this the examination cursor. Somewhat less obviously, the scan cursor object must also track which parts of the keyspace have already been visited, which is critical for deciding if a concurrent filesystem update needs to be incorporated into the scan data. Call this the visited inode cursor.

Advancing the scan cursor is a multi-step process encapsulated in `xchk_iscan_iter`:

1. Lock the AGI buffer of the AG containing the inode pointed to by the visited inode cursor. This guarantee that inodes in this AG cannot be allocated or freed while advancing the cursor.

2. Use the per-AG inode btree to look up the next inumber after the one that was just visited, since it may not be keyspace adjacent.

3. If there are no more inodes left in this AG:

   - **a.** Move the examination cursor to the point of the inumber keyspace that corresponds to the start of the next AG.

   - **b.** Adjust the visited inode cursor to indicate that it has "visited" the last possible inode in the current AG's inode keyspace. XFS inumbers are segmented, so the cursor needs to be marked as having visited the entire keyspace up to just before the start of the next AG's inode keyspace.

   - **c.** Unlock the AGI and return to step 1 if there are unexamined AGs in the filesystem.

   - **d.** If there are no more AGs to examine, set both cursors to the end of the inumber keyspace. The scan is now complete.

4. Otherwise, there is at least one more inode to scan in this AG:

   - **a.** Move the examination cursor ahead to the next inode marked as allocated by the inode btree.

   - **b.** Adjust the visited inode cursor to point to the inode just prior to where the examination cursor is now. Because the scanner holds the AGI buffer lock, no inodes could have been created in the part of the inode keyspace that the visited inode cursor just advanced.

5. Get the incore inode for the inumber of the examination cursor. By maintaining the AGI buffer lock until this point, the scanner knows that it was safe to advance the examination cursor across the entire keyspace, and that it has stabilized this next inode so that it cannot disappear from the filesystem until the scan releases the incore inode.

6. Drop the AGI lock and return the incore inode to the caller.

Online fsck functions scan all files in the filesystem as follows:

1. Start a scan by calling `xchk_iscan_start`.

2. Advance the scan cursor (`xchk_iscan_iter`) to get the next inode. If one is provided:

   - **a.** Lock the inode to prevent updates during the scan.

   - **b.** Scan the inode.

   - **c.** While still holding the inode lock, adjust the visited inode cursor (`xchk_iscan_mark_visited`) to point to this inode.

   - **d.** Unlock and release the inode.

8. Call `xchk_iscan_teardown` to complete the scan.

There are subtleties with the inode cache that complicate grabbing the incore inode for the caller. Obviously, it is an absolute requirement that the inode metadata be consistent enough to load it into the inode cache. Second, if the incore inode is stuck in some intermediate state, the scan coordinator must release the AGI and push the main filesystem to get the inode back into a loadable state.

<a id="rst-inode-management"></a>

#### Inode Management

In regular filesystem code, references to allocated XFS incore inodes are always obtained (`xfs_iget`) outside of transaction context because the creation of the incore context for an existing file does not require metadata updates. However, it is important to note that references to incore inodes obtained as part of file creation must be performed in transaction context because the filesystem must ensure the atomicity of the ondisk inode btree index updates and the initialization of the actual ondisk inode.

References to incore inodes are always released (`xfs_irele`) outside of transaction context because there are a handful of activities that might require ondisk updates:

- The VFS may decide to kick off writeback as part of a `DONTCACHE` inode release.

- Speculative preallocations need to be unreserved.

- An unlinked file may have lost its last reference, in which case the entire file must be inactivated, which involves releasing all of its resources in the ondisk metadata and freeing the inode.

These activities are collectively called inode inactivation. Inactivation has two parts -- the VFS part, which initiates writeback on all dirty file pages, and the XFS part, which cleans up XFS-specific information and frees the inode if it was unlinked. If the inode is unlinked (or unconnected after a file handle operation), the kernel drops the inode into the inactivation machinery immediately.

During normal operation, resource acquisition for an update follows this order to avoid deadlocks:

1. Inode reference (`iget`).

2. Filesystem freeze protection, if repairing (`mnt_want_write_file`).

3. Inode `IOLOCK` (VFS `i_rwsem`) lock to control file IO.

4. Inode `MMAPLOCK` (page cache `invalidate_lock`) lock for operations that can update page cache mappings.

5. Log feature enablement.

6. Transaction log space grant.

7. Space on the data and realtime devices for the transaction.

8. Incore dquot references, if a file is being repaired. Note that they are not locked, merely acquired.

9. Inode `ILOCK` for file metadata updates.

10. AG header buffer locks / Realtime metadata inode ILOCK.

11. Realtime metadata buffer locks, if applicable.

12. Extent mapping btree blocks, if applicable.

Resources are often released in the reverse order, though this is not required. However, online fsck differs from regular XFS operations because it may examine an object that normally is acquired in a later stage of the locking order, and then decide to cross-reference the object with an object that is acquired earlier in the order. The next few sections detail the specific ways in which online fsck takes care to avoid deadlocks.

<a id="rst-iget-and-irele-during-a-scrub"></a>

##### iget and irele During a Scrub

An inode scan performed on behalf of a scrub operation runs in transaction context, and possibly with resources already locked and bound to it. This isn't much of a problem for `iget` since it can operate in the context of an existing transaction, as long as all of the bound resources are acquired before the inode reference in the regular filesystem.

When the VFS `iput` function is given a linked inode with no other references, it normally puts the inode on an LRU list in the hope that it can save time if another process re-opens the file before the system runs out of memory and frees it. Filesystem callers can short-circuit the LRU process by setting a `DONTCACHE` flag on the inode to cause the kernel to try to drop the inode into the inactivation machinery immediately.

In the past, inactivation was always done from the process that dropped the inode, which was a problem for scrub because scrub may already hold a transaction, and XFS does not support nesting transactions. On the other hand, if there is no scrub transaction, it is desirable to drop otherwise unused inodes immediately to avoid polluting caches. To capture these nuances, the online fsck code has a separate `xchk_irele` function to set or clear the `DONTCACHE` flag to get the required release behavior.

<a id="rst-locking-inodes"></a>
<a id="rst-ilocking"></a>

##### Locking Inodes

In regular filesystem code, the VFS and XFS will acquire multiple IOLOCK locks in a well-known order: parent → child when updating the directory tree, and in numerical order of the addresses of their `struct inode` object otherwise. For regular files, the MMAPLOCK can be acquired after the IOLOCK to stop page faults. If two MMAPLOCKs must be acquired, they are acquired in numerical order of the addresses of their `struct address_space` objects. Due to the structure of existing filesystem code, IOLOCKs and MMAPLOCKs must be acquired before transactions are allocated. If two ILOCKs must be acquired, they are acquired in inumber order.

Inode lock acquisition must be done carefully during a coordinated inode scan. Online fsck cannot abide these conventions, because for a directory tree scanner, the scrub process holds the IOLOCK of the file being scanned and it needs to take the IOLOCK of the file at the other end of the directory link. If the directory tree is corrupt because it contains a cycle, `xfs_scrub` cannot use the regular inode locking functions and avoid becoming trapped in an ABBA deadlock.

Solving both of these problems is straightforward -- any time online fsck needs to take a second lock of the same class, it uses trylock to avoid an ABBA deadlock. If the trylock fails, scrub drops all inode locks and use trylock loops to (re)acquire all necessary resources. Trylock loops enable scrub to check for pending fatal signals, which is how scrub avoids deadlocking the filesystem or becoming an unresponsive process. However, trylock loops means that online fsck must be prepared to measure the resource being scrubbed before and after the lock cycle to detect changes and react accordingly.

<a id="rst-case-study-finding-a-directory-parent"></a>
<a id="rst-dirparent"></a>

##### Case Study: Finding a Directory Parent

Consider the directory parent pointer repair code as an example. Online fsck must verify that the dotdot dirent of a directory points up to a parent directory, and that the parent directory contains exactly one dirent pointing down to the child directory. Fully validating this relationship (and repairing it if possible) requires a walk of every directory on the filesystem while holding the child locked, and while updates to the directory tree are being made. The coordinated inode scan provides a way to walk the filesystem without the possibility of missing an inode. The child directory is kept locked to prevent updates to the dotdot dirent, but if the scanner fails to lock a parent, it can drop and relock both the child and the prospective parent. If the dotdot entry changes while the directory is unlocked, then a move or rename operation must have changed the child's parentage, and the scan can exit early.

<a id="rst-filesystem-hooks"></a>
<a id="rst-fshooks"></a>

#### Filesystem Hooks

The second piece of support that online fsck functions need during a full filesystem scan is the ability to stay informed about updates being made by other threads in the filesystem, since comparisons against the past are useless in a dynamic environment. Two pieces of Linux kernel infrastructure enable online fsck to monitor regular filesystem operations: filesystem hooks and [static keys](<#rst-jump-labels>).

Filesystem hooks convey information about an ongoing filesystem operation to a downstream consumer. In this case, the downstream consumer is always an online fsck function. Because multiple fsck functions can run in parallel, online fsck uses the Linux notifier call chain facility to dispatch updates to any number of interested fsck processes. Call chains are a dynamic list, which means that they can be configured at run time. Because these hooks are private to the XFS module, the information passed along contains exactly what the checking function needs to update its observations.

The current implementation of XFS hooks uses SRCU notifier chains to reduce the impact to highly threaded workloads. Regular blocking notifier chains use a rwsem and seem to have a much lower overhead for single-threaded applications. However, it may turn out that the combination of blocking chains and static keys are a more performant combination; more study is needed here.

The following pieces are necessary to hook a certain point in the filesystem:

- A `struct xfs_hooks` object must be embedded in a convenient place such as a well-known incore filesystem object.

- Each hook must define an action code and a structure containing more context about the action.

- Hook providers should provide appropriate wrapper functions and structs around the `xfs_hooks` and `xfs_hook` objects to take advantage of type checking to ensure correct usage.

- A callsite in the regular filesystem code must be chosen to call `xfs_hooks_call` with the action code and data structure. This place should be adjacent to (and not earlier than) the place where the filesystem update is committed to the transaction. In general, when the filesystem calls a hook chain, it should be able to handle sleeping and should not be vulnerable to memory reclaim or locking recursion. However, the exact requirements are very dependent on the context of the hook caller and the callee.

- The online fsck function should define a structure to hold scan data, a lock to coordinate access to the scan data, and a `struct xfs_hook` object. The scanner function and the regular filesystem code must acquire resources in the same order; see the next section for details.

- The online fsck code must contain a C function to catch the hook action code and data structure. If the object being updated has already been visited by the scan, then the hook information must be applied to the scan data.

- Prior to unlocking inodes to start the scan, online fsck must call `xfs_hooks_setup` to initialize the `struct xfs_hook`, and `xfs_hooks_add` to enable the hook.

- Online fsck must call `xfs_hooks_del` to disable the hook once the scan is complete.

The number of hooks should be kept to a minimum to reduce complexity. Static keys are used to reduce the overhead of filesystem hooks to nearly zero when online fsck is not running.

<a id="rst-live-updates-during-a-scan"></a>
<a id="rst-liveupdate"></a>

#### Live Updates During a Scan

The code paths of the online fsck scanning code and the [hooked](<#rst-fshooks>) filesystem code look like this:



```text
other program
      ↓
inode lock ←────────────────────┐
      ↓                         │
AG header lock                  │
      ↓                         │
filesystem function             │
      ↓                         │
notifier call chain             │    same
      ↓                         ├─── inode
scrub hook function             │    lock
      ↓                         │
scan data mutex ←──┐    same    │
      ↓            ├─── scan    │
update scan data   │    lock    │
      ↑            │            │
scan data mutex ←──┘            │
      ↑                         │
inode lock ←────────────────────┘
      ↑
scrub function
      ↑
inode scanner
      ↑
xfs_scrub
```

These rules must be followed to ensure correct interactions between the checking code and the code making an update to the filesystem:

- Prior to invoking the notifier call chain, the filesystem function being hooked must acquire the same lock that the scrub scanning function acquires to scan the inode.

- The scanning function and the scrub hook function must coordinate access to the scan data by acquiring a lock on the scan data.

- Scrub hook function must not add the live update information to the scan observations unless the inode being updated has already been scanned. The scan coordinator has a helper predicate (`xchk_iscan_want_live_update`) for this.

- Scrub hook functions must not change the caller's state, including the transaction that it is running. They must not acquire any resources that might conflict with the filesystem function being hooked.

- The hook function can abort the inode scan to avoid breaking the other rules.

The inode scan APIs are pretty simple:

- `xchk_iscan_start` starts a scan

- `xchk_iscan_iter` grabs a reference to the next inode in the scan or returns zero if there is nothing left to scan

- `xchk_iscan_want_live_update` to decide if an inode has already been visited in the scan. This is critical for hook functions to decide if they need to update the in-memory scan information.

- `xchk_iscan_mark_visited` to mark an inode as having been visited in the scan

- `xchk_iscan_teardown` to finish the scan

<a id="rst-case-study-quota-counter-checking"></a>
<a id="rst-quotacheck"></a>

##### Case Study: Quota Counter Checking

It is useful to compare the mount time quotacheck code to the online repair quotacheck code. Mount time quotacheck does not have to contend with concurrent operations, so it does the following:

1. Make sure the ondisk dquots are in good enough shape that all the incore dquots will actually load, and zero the resource usage counters in the ondisk buffer.

2. Walk every inode in the filesystem. Add each file's resource usage to the incore dquot.

3. Walk each incore dquot. If the incore dquot is not being flushed, add the ondisk buffer backing the incore dquot to a delayed write (delwri) list.

4. Write the buffer list to disk.

Like most online fsck functions, online quotacheck can't write to regular filesystem objects until the newly collected metadata reflect all filesystem state. Therefore, online quotacheck records file resource usage to a shadow dquot index implemented with a sparse `xfarray`, and only writes to the real dquots once the scan is complete. Handling transactional updates is tricky because quota resource usage updates are handled in phases to minimize contention on dquots:

1. The inodes involved are joined and locked to a transaction.

2. For each dquot attached to the file:

   - **a.** The dquot is locked.

   - **b.** A quota reservation is added to the dquot's resource usage. The reservation is recorded in the transaction.

   - **c.** The dquot is unlocked.

3. Changes in actual quota usage are tracked in the transaction.

4. At transaction commit time, each dquot is examined again:

   - **a.** The dquot is locked again.

   - **b.** Quota usage changes are logged and unused reservation is given back to the dquot.

   - **c.** The dquot is unlocked.

For online quotacheck, hooks are placed in steps 2 and 4. The step 2 hook creates a shadow version of the transaction dquot context (`dqtrx`) that operates in a similar manner to the regular code. The step 4 hook commits the shadow `dqtrx` changes to the shadow dquots. Notice that both hooks are called with the inode locked, which is how the live update coordinates with the inode scanner.

The quotacheck scan looks like this:

1. Set up a coordinated inode scan.

2. For each inode returned by the inode scan iterator:

   - **a.** Grab and lock the inode.

   - **b.** Determine that inode's resource usage (data blocks, inode counts, realtime blocks) and add that to the shadow dquots for the user, group, and project ids associated with the inode.

   - **c.** Unlock and release the inode.

3. For each dquot in the system:

   - **a.** Grab and lock the dquot.

   - **b.** Check the dquot against the shadow dquots created by the scan and updated by the live hooks.

Live updates are key to being able to walk every quota record without needing to hold any locks for a long duration. If repairs are desired, the real and shadow dquots are locked and their resource counts are set to the values in the shadow dquot.

<a id="rst-case-study-file-link-count-checking"></a>
<a id="rst-nlinks"></a>

##### Case Study: File Link Count Checking

File link count checking also uses live update hooks. The coordinated inode scanner is used to visit all directories on the filesystem, and per-file link count records are stored in a sparse `xfarray` indexed by inumber. During the scanning phase, each entry in a directory generates observation data as follows:

1. If the entry is a dotdot (`'..'`) entry of the root directory, the directory's parent link count is bumped because the root directory's dotdot entry is self referential.

2. If the entry is a dotdot entry of a subdirectory, the parent's backref count is bumped.

3. If the entry is neither a dot nor a dotdot entry, the target file's parent count is bumped.

4. If the target is a subdirectory, the parent's child link count is bumped.

A crucial point to understand about how the link count inode scanner interacts with the live update hooks is that the scan cursor tracks which *parent* directories have been scanned. In other words, the live updates ignore any update about `A → B` when A has not been scanned, even if B has been scanned. Furthermore, a subdirectory A with a dotdot entry pointing back to B is accounted as a backref counter in the shadow data for A, since child dotdot entries affect the parent's link count. Live update hooks are carefully placed in all parts of the filesystem that create, change, or remove directory entries, since those operations involve bumplink and droplink.

For any file, the correct link count is the number of parents plus the number of child subdirectories. Non-directories never have children of any kind. The backref information is used to detect inconsistencies in the number of links pointing to child subdirectories and the number of dotdot entries pointing back.

After the scan completes, the link count of each file can be checked by locking both the inode and the shadow data, and comparing the link counts. A second coordinated inode scan cursor is used for comparisons. Live updates are key to being able to walk every inode without needing to hold any locks between inodes. If repairs are desired, the inode's link count is set to the value in the shadow information. If no parents are found, the file must be [reparented](<#rst-orphanage>) to the orphanage to prevent the file from being lost forever.

<a id="rst-case-study-rebuilding-reverse-mapping-records"></a>
<a id="rst-rmap-repair"></a>

##### Case Study: Rebuilding Reverse Mapping Records

Most repair functions follow the same pattern: lock filesystem resources, walk the surviving ondisk metadata looking for replacement metadata records, and use an [in-memory array](<#rst-xfarray>) to store the gathered observations. The primary advantage of this approach is the simplicity and modularity of the repair code -- code and data are entirely contained within the scrub module, do not require hooks in the main filesystem, and are usually the most efficient in memory use. A secondary advantage of this repair approach is atomicity -- once the kernel decides a structure is corrupt, no other threads can access the metadata until the kernel finishes repairing and revalidating the metadata.

For repairs going on within a shard of the filesystem, these advantages outweigh the delays inherent in locking the shard while repairing parts of the shard. Unfortunately, repairs to the reverse mapping btree cannot use the "standard" btree repair strategy because it must scan every space mapping of every fork of every file in the filesystem, and the filesystem cannot stop. Therefore, rmap repair foregoes atomicity between scrub and repair. It combines a [coordinated inode scanner](<#rst-iscan>), [live update hooks](<#rst-liveupdate>), and an [in-memory rmap btree](<#rst-xfbtree>) to complete the scan for reverse mapping records.

1. Set up an xfbtree to stage rmap records.

2. While holding the locks on the AGI and AGF buffers acquired during the scrub, generate reverse mappings for all AG metadata: inodes, btrees, CoW staging extents, and the internal log.

3. Set up an inode scanner.

4. Hook into rmap updates for the AG being repaired so that the live scan data can receive updates to the rmap btree from the rest of the filesystem during the file scan.

5. For each space mapping found in either fork of each file scanned, decide if the mapping matches the AG of interest. If so:

   - **a.** Create a btree cursor for the in-memory btree.

   - **b.** Use the rmap code to add the record to the in-memory btree.

   - **c.** Use the [special commit function](<#rst-xfbtree-commit>) to write the xfbtree changes to the xfile.

6. For each live update received via the hook, decide if the owner has already been scanned. If so, apply the live update into the scan data:

   - **a.** Create a btree cursor for the in-memory btree.

   - **b.** Replay the operation into the in-memory btree.

   - **c.** Use the [special commit function](<#rst-xfbtree-commit>) to write the xfbtree changes to the xfile. This is performed with an empty transaction to avoid changing the caller's state.

7. When the inode scan finishes, create a new scrub transaction and relock the two AG headers.

8. Compute the new btree geometry using the number of rmap records in the shadow btree, like all other btree rebuilding functions.

9. Allocate the number of blocks computed in the previous step.

10. Perform the usual btree bulk loading and commit to install the new rmap btree.

11. Reap the old rmap btree blocks as discussed in the case study about how to [reap after rmap btree repair](<#rst-rmap-reap>).

12. Free the xfbtree now that it not needed.

<a id="rst-staging-repairs-with-temporary-files-on-disk"></a>

### Staging Repairs with Temporary Files on Disk

XFS stores a substantial amount of metadata in file forks: directories, extended attributes, symbolic link targets, free space bitmaps and summary information for the realtime volume, and quota records. File forks map 64-bit logical file fork space extents to physical storage space extents, similar to how a memory management unit maps 64-bit virtual addresses to physical memory addresses. Therefore, file-based tree structures (such as directories and extended attributes) use blocks mapped in the file fork offset address space that point to other blocks mapped within that same address space, and file-based linear structures (such as bitmaps and quota records) compute array element offsets in the file fork offset address space.

Because file forks can consume as much space as the entire filesystem, repairs cannot be staged in memory, even when a paging scheme is available. Therefore, online repair of file-based metadata createas a temporary file in the XFS filesystem, writes a new structure at the correct offsets into the temporary file, and atomically exchanges all file fork mappings (and hence the fork contents) to commit the repair. Once the repair is complete, the old fork can be reaped as necessary; if the system goes down during the reap, the iunlink code will delete the blocks during log recovery.

**Note**: All space usage and inode indices in the filesystem *must* be consistent to use a temporary file safely\! This dependency is the reason why online repair can only use pageable kernel memory to stage ondisk space usage information.

Exchanging metadata file mappings with a temporary file requires the owner field of the block headers to match the file being repaired and not the temporary file. The directory, extended attribute, and symbolic link functions were all modified to allow callers to specify owner numbers explicitly.

There is a downside to the reaping process -- if the system crashes during the reap phase and the fork extents are crosslinked, the iunlink processing will fail because freeing space will find the extra reverse mappings and abort.

Temporary files created for repair are similar to `O_TMPFILE` files created by userspace. They are not linked into a directory and the entire file will be reaped when the last reference to the file is lost. The key differences are that these files must have no access permission outside the kernel at all, they must be specially marked to prevent them from being opened by handle, and they must never be linked into the directory tree.


<table>
<tbody>
<tr>
<td>


**Historical Sidebar**:

</td>
</tr>
<tr>
<td>


In the initial iteration of file metadata repair, the damaged metadata blocks would be scanned for salvageable data; the extents in the file fork would be reaped; and then a new structure would be built in its place. This strategy did not survive the introduction of the atomic repair requirement expressed earlier in this document.

The second iteration explored building a second structure at a high offset in the fork from the salvage data, reaping the old extents, and using a `COLLAPSE_RANGE` operation to slide the new extents into place.

This had many drawbacks:

- Array structures are linearly addressed, and the regular filesystem codebase does not have the concept of a linear offset that could be applied to the record offset computation to build an alternate copy.

- Extended attributes are allowed to use the entire attr fork offset address space.

- Even if repair could build an alternate copy of a data structure in a different part of the fork address space, the atomic repair commit requirement means that online repair would have to be able to perform a log assisted `COLLAPSE_RANGE` operation to ensure that the old structure was completely replaced.

- A crash after construction of the secondary tree but before the range collapse would leave unreachable blocks in the file fork. This would likely confuse things further.

- Reaping blocks after a repair is not a simple operation, and initiating a reap operation from a restarted range collapse operation during log recovery is daunting.

- Directory entry blocks and quota records record the file fork offset in the header area of each block. An atomic range collapse operation would have to rewrite this part of each block header. Rewriting a single field in block headers is not a huge problem, but it's something to be aware of.

- Each block in a directory or extended attributes btree index contains sibling and child block pointers. Were the atomic commit to use a range collapse operation, each block would have to be rewritten very carefully to preserve the graph structure. Doing this as part of a range collapse means rewriting a large number of blocks repeatedly, which is not conducive to quick repairs.

This lead to the introduction of temporary file staging.

</td>
</tr>
</tbody>
</table>

<a id="rst-using-a-temporary-file"></a>

#### Using a Temporary File

Online repair code should use the `xrep_tempfile_create` function to create a temporary file inside the filesystem. This allocates an inode, marks the in-core inode private, and attaches it to the scrub context. These files are hidden from userspace, may not be added to the directory tree, and must be kept private.

Temporary files only use two inode locks: the IOLOCK and the ILOCK. The MMAPLOCK is not needed here, because there must not be page faults from userspace for data fork blocks. The usage patterns of these two locks are the same as for any other XFS file -- access to file data are controlled via the IOLOCK, and access to file metadata are controlled via the ILOCK. Locking helpers are provided so that the temporary file and its lock state can be cleaned up by the scrub context. To comply with the nested locking strategy laid out in the [inode locking](<#rst-ilocking>) section, it is recommended that scrub functions use the xrep_tempfile_ilock\*\_nowait lock helpers.

Data can be written to a temporary file by two means:

1. `xrep_tempfile_copyin` can be used to set the contents of a regular temporary file from an xfile.

2. The regular directory, symbolic link, and extended attribute functions can be used to write to the temporary file.

Once a good copy of a data file has been constructed in a temporary file, it must be conveyed to the file being repaired, which is the topic of the next section.

<a id="rst-logged-file-content-exchanges"></a>

### Logged File Content Exchanges

Once repair builds a temporary file with a new data structure written into it, it must commit the new changes into the existing file. It is not possible to swap the inumbers of two files, so instead the new metadata must replace the old. This suggests the need for the ability to swap extents, but the existing extent swapping code used by the file defragmenting tool `xfs_fsr` is not sufficient for online repair because:

- **a.** When the reverse-mapping btree is enabled, the swap code must keep the reverse mapping information up to date with every exchange of mappings. Therefore, it can only exchange one mapping per transaction, and each transaction is independent.

- **b.** Reverse-mapping is critical for the operation of online fsck, so the old defragmentation code (which swapped entire extent forks in a single operation) is not useful here.

- **c.** Defragmentation is assumed to occur between two files with identical contents. For this use case, an incomplete exchange will not result in a user-visible change in file contents, even if the operation is interrupted.

- **d.** Online repair needs to swap the contents of two files that are by definition *not* identical. For directory and xattr repairs, the user-visible contents might be the same, but the contents of individual blocks may be very different.

- **e.** Old blocks in the file may be cross-linked with another structure and must not reappear if the system goes down mid-repair.

These problems are overcome by creating a new deferred operation and a new type of log intent item to track the progress of an operation to exchange two file ranges. The new exchange operation type chains together the same transactions used by the reverse-mapping extent swap code, but records intermedia progress in the log so that operations can be restarted after a crash. This new functionality is called the file contents exchange (xfs_exchrange) code. The underlying implementation exchanges file fork mappings (xfs_exchmaps). The new log item records the progress of the exchange to ensure that once an exchange begins, it will always run to completion, even there are interruptions. The new `XFS_SB_FEAT_INCOMPAT_EXCHRANGE` incompatible feature flag in the superblock protects these new log item records from being replayed on old kernels.


<table>
<tbody>
<tr>
<td>


**Sidebar: Using Log-Incompatible Feature Flags**

</td>
</tr>
<tr>
<td>


Starting with XFS v5, the superblock contains a `sb_features_log_incompat` field to indicate that the log contains records that might not readable by all kernels that could mount this filesystem. In short, log incompat features protect the log contents against kernels that will not understand the contents. Unlike the other superblock feature bits, log incompat bits are ephemeral because an empty (clean) log does not need protection. The log cleans itself after its contents have been committed into the filesystem, either as part of an unmount or because the system is otherwise idle. Because upper level code can be working on a transaction at the same time that the log cleans itself, it is necessary for upper level code to communicate to the log when it is going to use a log incompatible feature.

The log coordinates access to incompatible features through the use of one `struct rw_semaphore` for each feature. The log cleaning code tries to take this rwsem in exclusive mode to clear the bit; if the lock attempt fails, the feature bit remains set. The code supporting a log incompat feature should create wrapper functions to obtain the log feature and call `xfs_add_incompat_log_feature` to set the feature bits in the primary superblock. The superblock update is performed transactionally, so the wrapper to obtain log assistance must be called just prior to the creation of the transaction that uses the functionality. For a file operation, this step must happen after taking the IOLOCK and the MMAPLOCK, but before allocating the transaction. When the transaction is complete, the `xlog_drop_incompat_feat` function is called to release the feature. The feature bit will not be cleared from the superblock until the log becomes clean.

Log-assisted extended attribute updates and file content exchanges bothe use log incompat features and provide convenience wrappers around the functionality.

</td>
</tr>
</tbody>
</table>

<a id="rst-mechanics-of-a-logged-file-content-exchange"></a>

#### Mechanics of a Logged File Content Exchange

Exchanging contents between file forks is a complex task. The goal is to exchange all file fork mappings between two file fork offset ranges. There are likely to be many extent mappings in each fork, and the edges of the mappings aren't necessarily aligned. Furthermore, there may be other updates that need to happen after the exchange, such as exchanging file sizes, inode flags, or conversion of fork data to local format. This is roughly the format of the new deferred exchange-mapping work item:



```c
struct xfs_exchmaps_intent {
    /* Inodes participating in the operation. */
    struct xfs_inode    *xmi_ip1;
    struct xfs_inode    *xmi_ip2;

    /* File offset range information. */
    xfs_fileoff_t       xmi_startoff1;
    xfs_fileoff_t       xmi_startoff2;
    xfs_filblks_t       xmi_blockcount;

    /* Set these file sizes after the operation, unless negative. */
    xfs_fsize_t         xmi_isize1;
    xfs_fsize_t         xmi_isize2;

    /* XFS_EXCHMAPS_* log operation flags */
    uint64_t            xmi_flags;
};
```

The new log intent item contains enough information to track two logical fork offset ranges: `(inode1, startoff1, blockcount)` and `(inode2, startoff2, blockcount)`. Each step of an exchange operation exchanges the largest file range mapping possible from one file to the other. After each step in the exchange operation, the two startoff fields are incremented and the blockcount field is decremented to reflect the progress made. The flags field captures behavioral parameters such as exchanging attr fork mappings instead of the data fork and other work to be done after the exchange. The two isize fields are used to exchange the file sizes at the end of the operation if the file data fork is the target of the operation.

When the exchange is initiated, the sequence of operations is as follows:

1. Create a deferred work item for the file mapping exchange. At the start, it should contain the entirety of the file block ranges to be exchanged.

2. Call `xfs_defer_finish` to process the exchange. This is encapsulated in `xrep_tempexch_contents` for scrub operations. This will log an extent swap intent item to the transaction for the deferred mapping exchange work item.

3. Until `xmi_blockcount` of the deferred mapping exchange work item is zero,

   - **a.** Read the block maps of both file ranges starting at `xmi_startoff1` and `xmi_startoff2`, respectively, and compute the longest extent that can be exchanged in a single step. This is the minimum of the two `br_blockcount` s in the mappings. Keep advancing through the file forks until at least one of the mappings contains written blocks. Mutual holes, unwritten extents, and extent mappings to the same physical space are not exchanged.

     For the next few steps, this document will refer to the mapping that came from file 1 as "map1", and the mapping that came from file 2 as "map2".

   - **b.** Create a deferred block mapping update to unmap map1 from file 1.

   - **c.** Create a deferred block mapping update to unmap map2 from file 2.

   - **d.** Create a deferred block mapping update to map map1 into file 2.

   - **e.** Create a deferred block mapping update to map map2 into file 1.

   - **f.** Log the block, quota, and extent count updates for both files.

   - **g.** Extend the ondisk size of either file if necessary.

   - **h.** Log a mapping exchange done log item for th mapping exchange intent log item that was read at the start of step 3.

   - **i.** Compute the amount of file range that has just been covered. This quantity is `(map1.br_startoff + map1.br_blockcount - xmi_startoff1)`, because step 3a could have skipped holes.

   - **j.** Increase the starting offsets of `xmi_startoff1` and `xmi_startoff2` by the number of blocks computed in the previous step, and decrease `xmi_blockcount` by the same quantity. This advances the cursor.

   - **k.** Log a new mapping exchange intent log item reflecting the advanced state of the work item.

   - **l.** Return the proper error code (EAGAIN) to the deferred operation manager to inform it that there is more work to be done. The operation manager completes the deferred work in steps 3b-3e before moving back to the start of step 3.

4. Perform any post-processing. This will be discussed in more detail in subsequent sections.

If the filesystem goes down in the middle of an operation, log recovery will find the most recent unfinished mapping exchange log intent item and restart from there. This is how atomic file mapping exchanges guarantees that an outside observer will either see the old broken structure or the new one, and never a mismash of both.

<a id="rst-preparation-for-file-content-exchanges"></a>

#### Preparation for File Content Exchanges

There are a few things that need to be taken care of before initiating an atomic file mapping exchange operation. First, regular files require the page cache to be flushed to disk before the operation begins, and directio writes to be quiesced. Like any filesystem operation, file mapping exchanges must determine the maximum amount of disk space and quota that can be consumed on behalf of both files in the operation, and reserve that quantity of resources to avoid an unrecoverable out of space failure once it starts dirtying metadata. The preparation step scans the ranges of both files to estimate:

- Data device blocks needed to handle the repeated updates to the fork mappings.

- Change in data and realtime block counts for both files.

- Increase in quota usage for both files, if the two files do not share the same set of quota ids.

- The number of extent mappings that will be added to each file.

- Whether or not there are partially written realtime extents. User programs must never be able to access a realtime file extent that maps to different extents on the realtime volume, which could happen if the operation fails to run to completion.

The need for precise estimation increases the run time of the exchange operation, but it is very important to maintain correct accounting. The filesystem must not run completely out of free space, nor can the mapping exchange ever add more extent mappings to a fork than it can support. Regular users are required to abide the quota limits, though metadata repairs may exceed quota to resolve inconsistent metadata elsewhere.

<a id="rst-special-features-for-exchanging-metadata-file-contents"></a>

#### Special Features for Exchanging Metadata File Contents

Extended attributes, symbolic links, and directories can set the fork format to "local" and treat the fork as a literal area for data storage. Metadata repairs must take extra steps to support these cases:

- If both forks are in local format and the fork areas are large enough, the exchange is performed by copying the incore fork contents, logging both forks, and committing. The atomic file mapping exchange mechanism is not necessary, since this can be done with a single transaction.

- If both forks map blocks, then the regular atomic file mapping exchange is used.

- Otherwise, only one fork is in local format. The contents of the local format fork are converted to a block to perform the exchange. The conversion to block format must be done in the same transaction that logs the initial mapping exchange intent log item. The regular atomic mapping exchange is used to exchange the metadata file mappings. Special flags are set on the exchange operation so that the transaction can be rolled one more time to convert the second file's fork back to local format so that the second file will be ready to go as soon as the ILOCK is dropped.

Extended attributes and directories stamp the owning inode into every block, but the buffer verifiers do not actually check the inode number\! Although there is no verification, it is still important to maintain referential integrity, so prior to performing the mapping exchange, online repair builds every block in the new data structure with the owner field of the file being repaired.

After a successful exchange operation, the repair operation must reap the old fork blocks by processing each fork mapping through the standard [file extent reaping](<#rst-reaping>) mechanism that is done post-repair. If the filesystem should go down during the reap part of the repair, the iunlink processing at the end of recovery will free both the temporary file and whatever blocks were not reaped. However, this iunlink processing omits the cross-link detection of online repair, and is not completely foolproof.

<a id="rst-exchanging-temporary-file-contents"></a>

#### Exchanging Temporary File Contents

To repair a metadata file, online repair proceeds as follows:

1. Create a temporary repair file.

2. Use the staging data to write out new contents into the temporary repair file. The same fork must be written to as is being repaired.

3. Commit the scrub transaction, since the exchange resource estimation step must be completed before transaction reservations are made.

4. Call `xrep_tempexch_trans_alloc` to allocate a new scrub transaction with the appropriate resource reservations, locks, and fill out a `struct xfs_exchmaps_req` with the details of the exchange operation.

5. Call `xrep_tempexch_contents` to exchange the contents.

6. Commit the transaction to complete the repair.

<a id="rst-case-study-repairing-the-realtime-summary-file"></a>
<a id="rst-rtsummary"></a>

##### Case Study: Repairing the Realtime Summary File

In the "realtime" section of an XFS filesystem, free space is tracked via a bitmap, similar to Unix FFS. Each bit in the bitmap represents one realtime extent, which is a multiple of the filesystem block size between 4KiB and 1GiB in size. The realtime summary file indexes the number of free extents of a given size to the offset of the block within the realtime free space bitmap where those free extents begin. In other words, the summary file helps the allocator find free extents by length, similar to what the free space by count (cntbt) btree does for the data section.

The summary file itself is a flat file (with no block headers or checksums\!) partitioned into `log2(total rt extents)` sections containing enough 32-bit counters to match the number of blocks in the rt bitmap. Each counter records the number of free extents that start in that bitmap block and can satisfy a power-of-two allocation request.

To check the summary file against the bitmap:

1. Take the ILOCK of both the realtime bitmap and summary files.

2. For each free space extent recorded in the bitmap:

   - **a.** Compute the position in the summary file that contains a counter that represents this free extent.

   - **b.** Read the counter from the xfile.

   - **c.** Increment it, and write it back to the xfile.

3. Compare the contents of the xfile against the ondisk file.

To repair the summary file, write the xfile contents into the temporary file and use atomic mapping exchange to commit the new contents. The temporary file is then reaped.

<a id="rst-case-study-salvaging-extended-attributes"></a>

##### Case Study: Salvaging Extended Attributes

In XFS, extended attributes are implemented as a namespaced name-value store. Values are limited in size to 64KiB, but there is no limit in the number of names. The attribute fork is unpartitioned, which means that the root of the attribute structure is always in logical block zero, but attribute leaf blocks, dabtree index blocks, and remote value blocks are intermixed. Attribute leaf blocks contain variable-sized records that associate user-provided names with the user-provided values. Values larger than a block are allocated separate extents and written there. If the leaf information expands beyond a single block, a directory/attribute btree (`dabtree`) is created to map hashes of attribute names to entries for fast lookup.

Salvaging extended attributes is done as follows:

1. Walk the attr fork mappings of the file being repaired to find the attribute leaf blocks. When one is found,

   - **a.** Walk the attr leaf block to find candidate keys. When one is found,

     1. Check the name for problems, and ignore the name if there are.

     2. Retrieve the value. If that succeeds, add the name and value to the staging xfarray and xfblob.

2. If the memory usage of the xfarray and xfblob exceed a certain amount of memory or there are no more attr fork blocks to examine, unlock the file and add the staged extended attributes to the temporary file.

3. Use atomic file mapping exchange to exchange the new and old extended attribute structures. The old attribute blocks are now attached to the temporary file.

4. Reap the temporary file.

<a id="rst-fixing-directories"></a>

### Fixing Directories

Fixing directories is difficult with currently available filesystem features, since directory entries are not redundant. The offline repair tool scans all inodes to find files with nonzero link count, and then it scans all directories to establish parentage of those linked files. Damaged files and directories are zapped, and files with no parent are moved to the `/lost+found` directory. It does not try to salvage anything.

The best that online repair can do at this time is to read directory data blocks and salvage any dirents that look plausible, correct link counts, and move orphans back into the directory tree. The salvage process is discussed in the case study at the end of this section. The [file link count fsck](<#rst-nlinks>) code takes care of fixing link counts and moving orphans to the `/lost+found` directory.

<a id="rst-case-study-salvaging-directories"></a>

#### Case Study: Salvaging Directories

Unlike extended attributes, directory blocks are all the same size, so salvaging directories is straightforward:

1. Find the parent of the directory. If the dotdot entry is not unreadable, try to confirm that the alleged parent has a child entry pointing back to the directory being repaired. Otherwise, walk the filesystem to find it.

2. Walk the first partition of data fork of the directory to find the directory entry data blocks. When one is found,

   - **a.** Walk the directory data block to find candidate entries. When an entry is found:

     - **i.** Check the name for problems, and ignore the name if there are.

     - **ii.** Retrieve the inumber and grab the inode. If that succeeds, add the name, inode number, and file type to the staging xfarray and xblob.

3. If the memory usage of the xfarray and xfblob exceed a certain amount of memory or there are no more directory data blocks to examine, unlock the directory and add the staged dirents into the temporary directory. Truncate the staging files.

4. Use atomic file mapping exchange to exchange the new and old directory structures. The old directory blocks are now attached to the temporary file.

5. Reap the temporary file.

**Future Work Question**: Should repair revalidate the dentry cache when rebuilding a directory?

*Answer*: Yes, it should.

In theory it is necessary to scan all dentry cache entries for a directory to ensure that one of the following apply:

1. The cached dentry reflects an ondisk dirent in the new directory.

2. The cached dentry no longer has a corresponding ondisk dirent in the new directory and the dentry can be purged from the cache.

3. The cached dentry no longer has an ondisk dirent but the dentry cannot be purged. This is the problem case.

Unfortunately, the current dentry cache design doesn't provide a means to walk every child dentry of a specific directory, which makes this a hard problem. There is no known solution.

<a id="rst-parent-pointers"></a>

#### Parent Pointers

A parent pointer is a piece of file metadata that enables a user to locate the file's parent directory without having to traverse the directory tree from the root. Without them, reconstruction of directory trees is hindered in much the same way that the historic lack of reverse space mapping information once hindered reconstruction of filesystem space metadata. The parent pointer feature, however, makes total directory reconstruction possible.

XFS parent pointers contain the information needed to identify the corresponding directory entry in the parent directory. In other words, child files use extended attributes to store pointers to parents in the form `(dirent_name) → (parent_inum, parent_gen)`. The directory checking process can be strengthened to ensure that the target of each dirent also contains a parent pointer pointing back to the dirent. Likewise, each parent pointer can be checked by ensuring that the target of each parent pointer is a directory and that it contains a dirent matching the parent pointer. Both online and offline repair can use this strategy.


<table>
<tbody>
<tr>
<td>


**Historical Sidebar**:

</td>
</tr>
<tr>
<td>


Directory parent pointers were first proposed as an XFS feature more than a decade ago by SGI. Each link from a parent directory to a child file is mirrored with an extended attribute in the child that could be used to identify the parent directory. Unfortunately, this early implementation had major shortcomings and was never merged into Linux XFS:

1. The XFS codebase of the late 2000s did not have the infrastructure to enforce strong referential integrity in the directory tree. It did not guarantee that a change in a forward link would always be followed up with the corresponding change to the reverse links.

2. Referential integrity was not integrated into offline repair. Checking and repairs were performed on mounted filesystems without taking any kernel or inode locks to coordinate access. It is not clear how this actually worked properly.

3. The extended attribute did not record the name of the directory entry in the parent, so the SGI parent pointer implementation cannot be used to reconnect the directory tree.

4. Extended attribute forks only support 65,536 extents, which means that parent pointer attribute creation is likely to fail at some point before the maximum file link count is achieved.

The original parent pointer design was too unstable for something like a file system repair to depend on. Allison Henderson, Chandan Babu, and Catherine Hoang are working on a second implementation that solves all shortcomings of the first. During 2022, Allison introduced log intent items to track physical manipulations of the extended attribute structures. This solves the referential integrity problem by making it possible to commit a dirent update and a parent pointer update in the same transaction. Chandan increased the maximum extent counts of both data and attribute forks, thereby ensuring that the extended attribute structure can grow to handle the maximum hardlink count of any file.

For this second effort, the ondisk parent pointer format as originally proposed was `(parent_inum, parent_gen, dirent_pos) → (dirent_name)`. The format was changed during development to eliminate the requirement of repair tools needing to ensure that the `dirent_pos` field always matched when reconstructing a directory.

There were a few other ways to have solved that problem:

1. The field could be designated advisory, since the other three values are sufficient to find the entry in the parent. However, this makes indexed key lookup impossible while repairs are ongoing.

2. We could allow creating directory entries at specified offsets, which solves the referential integrity problem but runs the risk that dirent creation will fail due to conflicts with the free space in the directory.

   These conflicts could be resolved by appending the directory entry and amending the xattr code to support updating an xattr key and reindexing the dabtree, though this would have to be performed with the parent directory still locked.

3. Same as above, but remove the old parent pointer entry and add a new one atomically.

4. Change the ondisk xattr format to `(parent_inum, name) → (parent_gen)`, which would provide the attr name uniqueness that we require, without forcing repair code to update the dirent position. Unfortunately, this requires changes to the xattr code to support attr names as long as 263 bytes.

5. Change the ondisk xattr format to `(parent_inum, hash(name)) → (name, parent_gen)`. If the hash is sufficiently resistant to collisions (e.g. sha256) then this should provide the attr name uniqueness that we require. Names shorter than 247 bytes could be stored directly.

6. Change the ondisk xattr format to `(dirent_name) → (parent_ino, parent_gen)`.  This format doesn't require any of the complicated nested name hashing of the previous suggestions.  However, it was discovered that multiple hardlinks to the same inode with the same filename caused performance problems with hashed xattr lookups, so the parent inumber is now xor'd into the hash index.

In the end, it was decided that solution \#6 was the most compact and the most performant.  A new hash function was designed for parent pointers.

</td>
</tr>
</tbody>
</table>

<a id="rst-case-study-repairing-directories-with-parent-pointers"></a>

##### Case Study: Repairing Directories with Parent Pointers

Directory rebuilding uses a [coordinated inode scan](<#rst-iscan>) and a [directory entry live update hook](<#rst-liveupdate>) as follows:

1. Set up a temporary directory for generating the new directory structure, an xfblob for storing entry names, and an xfarray for stashing the fixed size fields involved in a directory update: `(child inumber, add vs. remove, name cookie, ftype)`.

2. Set up an inode scanner and hook into the directory entry code to receive updates on directory operations.

3. For each parent pointer found in each file scanned, decide if the parent pointer references the directory of interest. If so:

   - **a.** Stash the parent pointer name and an addname entry for this dirent in the xfblob and xfarray, respectively.

   - **b.** When finished scanning that file or the kernel memory consumption exceeds a threshold, flush the stashed updates to the temporary directory.

4. For each live directory update received via the hook, decide if the child has already been scanned. If so:

   - **a.** Stash the parent pointer name an addname or removename entry for this dirent update in the xfblob and xfarray for later. We cannot write directly to the temporary directory because hook functions are not allowed to modify filesystem metadata. Instead, we stash updates in the xfarray and rely on the scanner thread to apply the stashed updates to the temporary directory.

5. When the scan is complete, replay any stashed entries in the xfarray.

6. When the scan is complete, atomically exchange the contents of the temporary directory and the directory being repaired. The temporary directory now contains the damaged directory structure.

7. Reap the temporary directory.

<a id="rst-case-study-repairing-parent-pointers"></a>

##### Case Study: Repairing Parent Pointers

Online reconstruction of a file's parent pointer information works similarly to directory reconstruction:

1. Set up a temporary file for generating a new extended attribute structure, an xfblob for storing parent pointer names, and an xfarray for stashing the fixed size fields involved in a parent pointer update: `(parent inumber, parent generation, add vs. remove, name cookie)`.

2. Set up an inode scanner and hook into the directory entry code to receive updates on directory operations.

3. For each directory entry found in each directory scanned, decide if the dirent references the file of interest. If so:

   - **a.** Stash the dirent name and an addpptr entry for this parent pointer in the xfblob and xfarray, respectively.

   - **b.** When finished scanning the directory or the kernel memory consumption exceeds a threshold, flush the stashed updates to the temporary file.

4. For each live directory update received via the hook, decide if the parent has already been scanned. If so:

   - **a.** Stash the dirent name and an addpptr or removepptr entry for this dirent update in the xfblob and xfarray for later. We cannot write parent pointers directly to the temporary file because hook functions are not allowed to modify filesystem metadata. Instead, we stash updates in the xfarray and rely on the scanner thread to apply the stashed parent pointer updates to the temporary file.

5. When the scan is complete, replay any stashed entries in the xfarray.

6. Copy all non-parent pointer extended attributes to the temporary file.

7. When the scan is complete, atomically exchange the mappings of the attribute forks of the temporary file and the file being repaired. The temporary file now contains the damaged extended attribute structure.

8. Reap the temporary file.

<a id="rst-digression-offline-checking-of-parent-pointers"></a>

##### Digression: Offline Checking of Parent Pointers

Examining parent pointers in offline repair works differently because corrupt files are erased long before directory tree connectivity checks are performed. Parent pointer checks are therefore a second pass to be added to the existing connectivity checks:

1. After the set of surviving files has been established (phase 6), walk the surviving directories of each AG in the filesystem. This is already performed as part of the connectivity checks.

2. For each directory entry found,

   - **a.** If the name has already been stored in the xfblob, then use that cookie and skip the next step.

   - **b.** Otherwise, record the name in an xfblob, and remember the xfblob cookie. Unique mappings are critical for

     1. Deduplicating names to reduce memory usage, and

     2. Creating a stable sort key for the parent pointer indexes so that the parent pointer validation described below will work.

   - **c.** Store `(child_ag_inum, parent_inum, parent_gen, name_hash, name_len, name_cookie)` tuples in a per-AG in-memory slab.  The `name_hash` referenced in this section is the regular directory entry name hash, not the specialized one used for parent pointer xattrs.

3. For each AG in the filesystem,

   - **a.** Sort the per-AG tuple set in order of `child_ag_inum`, `parent_inum`, `name_hash`, and `name_cookie`. Having a single `name_cookie` for each `name` is critical for handling the uncommon case of a directory containing multiple hardlinks to the same file where all the names hash to the same value.

   - **b.** For each inode in the AG,

     1. Scan the inode for parent pointers. For each parent pointer found,

        - **a.** Validate the ondisk parent pointer. If validation fails, move on to the next parent pointer in the file.

        - **b.** If the name has already been stored in the xfblob, then use that cookie and skip the next step.

        - **c.** Record the name in a per-file xfblob, and remember the xfblob cookie.

        - **d.** Store `(parent_inum, parent_gen, name_hash, name_len, name_cookie)` tuples in a per-file slab.

     2. Sort the per-file tuples in order of `parent_inum`, `name_hash`, and `name_cookie`.

     3. Position one slab cursor at the start of the inode's records in the per-AG tuple slab. This should be trivial since the per-AG tuples are in child inumber order.

     4. Position a second slab cursor at the start of the per-file tuple slab.

     5. Iterate the two cursors in lockstep, comparing the `parent_ino`, `name_hash`, and `name_cookie` fields of the records under each cursor:

        - **a.** If the per-AG cursor is at a lower point in the keyspace than the per-file cursor, then the per-AG cursor points to a missing parent pointer. Add the parent pointer to the inode and advance the per-AG cursor.

        - **b.** If the per-file cursor is at a lower point in the keyspace than the per-AG cursor, then the per-file cursor points to a dangling parent pointer. Remove the parent pointer from the inode and advance the per-file cursor.

        - **c.** Otherwise, both cursors point at the same parent pointer. Update the parent_gen component if necessary. Advance both cursors.

4. Move on to examining link counts, as we do today.

Rebuilding directories from parent pointers in offline repair would be very challenging because xfs_repair currently uses two single-pass scans of the filesystem during phases 3 and 4 to decide which files are corrupt enough to be zapped. This scan would have to be converted into a multi-pass scan:

1. The first pass of the scan zaps corrupt inodes, forks, and attributes much as it does now. Corrupt directories are noted but not zapped.

2. The next pass records parent pointers pointing to the directories noted as being corrupt in the first pass. This second pass may have to happen after the phase 4 scan for duplicate blocks, if phase 4 is also capable of zapping directories.

3. The third pass resets corrupt directories to an empty shortform directory. Free space metadata has not been ensured yet, so repair cannot yet use the directory building code in libxfs.

4. At the start of phase 6, space metadata have been rebuilt. Use the parent pointer information recorded during step 2 to reconstruct the dirents and add them to the now-empty directories.

This code has not yet been constructed.

<a id="rst-case-study-directory-tree-structure"></a>
<a id="rst-dirtree"></a>

##### Case Study: Directory Tree Structure

As mentioned earlier, the filesystem directory tree is supposed to be a directed acylic graph structure. However, each node in this graph is a separate `xfs_inode` object with its own locks, which makes validating the tree qualities difficult. Fortunately, non-directories are allowed to have multiple parents and cannot have children, so only directories need to be scanned. Directories typically constitute 5-10% of the files in a filesystem, which reduces the amount of work dramatically.

If the directory tree could be frozen, it would be easy to discover cycles and disconnected regions by running a depth (or breadth) first search downwards from the root directory and marking a bitmap for each directory found. At any point in the walk, trying to set an already set bit means there is a cycle. After the scan completes, XORing the marked inode bitmap with the inode allocation bitmap reveals disconnected inodes. However, one of online repair's design goals is to avoid locking the entire filesystem unless it's absolutely necessary. Directory tree updates can move subtrees across the scanner wavefront on a live filesystem, so the bitmap algorithm cannot be applied.

Directory parent pointers enable an incremental approach to validation of the tree structure. Instead of using one thread to scan the entire filesystem, multiple threads can walk from individual subdirectories upwards towards the root. For this to work, all directory entries and parent pointers must be internally consistent, each directory entry must have a parent pointer, and the link counts of all directories must be correct. Each scanner thread must be able to take the IOLOCK of an alleged parent directory while holding the IOLOCK of the child directory to prevent either directory from being moved within the tree. This is not possible since the VFS does not take the IOLOCK of a child subdirectory when moving that subdirectory, so instead the scanner stabilizes the parent -&gt; child relationship by taking the ILOCKs and installing a dirent update hook to detect changes.

The scanning process uses a dirent hook to detect changes to the directories mentioned in the scan data. The scan works as follows:

1. For each subdirectory in the filesystem,

   - **a.** For each parent pointer of that subdirectory,

     1. Create a path object for that parent pointer, and mark the subdirectory inode number in the path object's bitmap.

     2. Record the parent pointer name and inode number in a path structure.

     3. If the alleged parent is the subdirectory being scrubbed, the path is a cycle. Mark the path for deletion and repeat step 1a with the next subdirectory parent pointer.

     4. Try to mark the alleged parent inode number in a bitmap in the path object. If the bit is already set, then there is a cycle in the directory tree. Mark the path as a cycle and repeat step 1a with the next subdirectory parent pointer.

     5. Load the alleged parent. If the alleged parent is not a linked directory, abort the scan because the parent pointer information is inconsistent.

     6. For each parent pointer of this alleged ancestor directory,

        - **a.** Record the parent pointer name and inode number in the path object if no parent has been set for that level.

        - **b.** If an ancestor has more than one parent, mark the path as corrupt. Repeat step 1a with the next subdirectory parent pointer.

        - **c.** Repeat steps 1a3-1a6 for the ancestor identified in step 1a6a. This repeats until the directory tree root is reached or no parents are found.

     7. If the walk terminates at the root directory, mark the path as ok.

     8. If the walk terminates without reaching the root, mark the path as disconnected.

2. If the directory entry update hook triggers, check all paths already found by the scan. If the entry matches part of a path, mark that path and the scan stale. When the scanner thread sees that the scan has been marked stale, it deletes all scan data and starts over.

Repairing the directory tree works as follows:

1. Walk each path of the target subdirectory.

   - **a.** Corrupt paths and cycle paths are counted as suspect.

   - **b.** Paths already marked for deletion are counted as bad.

   - **c.** Paths that reached the root are counted as good.

2. If the subdirectory is either the root directory or has zero link count, delete all incoming directory entries in the immediate parents. Repairs are complete.

3. If the subdirectory has exactly one path, set the dotdot entry to the parent and exit.

4. If the subdirectory has at least one good path, delete all the other incoming directory entries in the immediate parents.

5. If the subdirectory has no good paths and more than one suspect path, delete all the other incoming directory entries in the immediate parents.

6. If the subdirectory has zero paths, attach it to the lost and found.

<a id="rst-the-orphanage"></a>
<a id="rst-orphanage"></a>

### The Orphanage

Filesystems present files as a directed, and hopefully acyclic, graph. In other words, a tree. The root of the filesystem is a directory, and each entry in a directory points downwards either to more subdirectories or to non-directory files. Unfortunately, a disruption in the directory graph pointers result in a disconnected graph, which makes files impossible to access via regular path resolution.

Without parent pointers, the directory parent pointer online scrub code can detect a dotdot entry pointing to a parent directory that doesn't have a link back to the child directory and the file link count checker can detect a file that isn't pointed to by any directory in the filesystem. If such a file has a positive link count, the file is an orphan.

With parent pointers, directories can be rebuilt by scanning parent pointers and parent pointers can be rebuilt by scanning directories. This should reduce the incidence of files ending up in `/lost+found`.

When orphans are found, they should be reconnected to the directory tree. Offline fsck solves the problem by creating a directory `/lost+found` to serve as an orphanage, and linking orphan files into the orphanage by using the inumber as the name. Reparenting a file to the orphanage does not reset any of its permissions or ACLs.

This process is more involved in the kernel than it is in userspace. The directory and file link count repair setup functions must use the regular VFS mechanisms to create the orphanage directory with all the necessary security attributes and dentry cache entries, just like a regular directory tree modification.

Orphaned files are adopted by the orphanage as follows:

1. Call `xrep_orphanage_try_create` at the start of the scrub setup function to try to ensure that the lost and found directory actually exists. This also attaches the orphanage directory to the scrub context.

2. If the decision is made to reconnect a file, take the IOLOCK of both the orphanage and the file being reattached. The `xrep_orphanage_iolock_two` function follows the inode locking strategy discussed earlier.

3. Use `xrep_adoption_trans_alloc` to reserve resources to the repair transaction.

4. Call `xrep_orphanage_compute_name` to compute the new name in the orphanage.

5. If the adoption is going to happen, call `xrep_adoption_reparent` to reparent the orphaned file into the lost and found and invalidate the dentry cache.

6. Call `xrep_adoption_finish` to commit any filesystem updates, release the orphanage ILOCK, and clean the scrub transaction.  Call `xrep_adoption_commit` to commit the updates and the scrub transaction.

7. If a runtime error happens, call `xrep_adoption_cancel` to release all resources.

<a id="rst-userspace-algorithms-and-data-structures"></a>

## 6. Userspace Algorithms and Data Structures

This section discusses the key algorithms and data structures of the userspace program, `xfs_scrub`, that provide the ability to drive metadata checks and repairs in the kernel, verify file data, and look for other potential problems.

<a id="rst-checking-metadata"></a>
<a id="rst-scrubcheck"></a>

### Checking Metadata

Recall the [phases of fsck work](<#rst-scrubphases>) outlined earlier. That structure follows naturally from the data dependencies designed into the filesystem from its beginnings in 1993. In XFS, there are several groups of metadata dependencies:

- **a.** Filesystem summary counts depend on consistency within the inode indices, the allocation group space btrees, and the realtime volume space information.

- **b.** Quota resource counts depend on consistency within the quota file data forks, inode indices, inode records, and the forks of every file on the system.

- **c.** The naming hierarchy depends on consistency within the directory and extended attribute structures. This includes file link counts.

- **d.** Directories, extended attributes, and file data depend on consistency within the file forks that map directory and extended attribute data to physical storage media.

- **e.** The file forks depends on consistency within inode records and the space metadata indices of the allocation groups and the realtime volume. This includes quota and realtime metadata files.

- **f.** Inode records depends on consistency within the inode metadata indices.

- **g.** Realtime space metadata depend on the inode records and data forks of the realtime metadata inodes.

- **h.** The allocation group metadata indices (free space, inodes, reference count, and reverse mapping btrees) depend on consistency within the AG headers and between all the AG metadata btrees.

- **i.** `xfs_scrub` depends on the filesystem being mounted and kernel support for online fsck functionality.

Therefore, a metadata dependency graph is a convenient way to schedule checking operations in the `xfs_scrub` program:

- Phase 1 checks that the provided path maps to an XFS filesystem and detect the kernel's scrubbing abilities, which validates group (i).

- Phase 2 scrubs groups (g) and (h) in parallel using a threaded workqueue.

- Phase 3 scans inodes in parallel. For each inode, groups (f), (e), and (d) are checked, in that order.

- Phase 4 repairs everything in groups (i) through (d) so that phases 5 and 6 may run reliably.

- Phase 5 starts by checking groups (b) and (c) in parallel before moving on to checking names.

- Phase 6 depends on groups (i) through (b) to find file data blocks to verify, to read them, and to report which blocks of which files are affected.

- Phase 7 checks group (a), having validated everything else.

Notice that the data dependencies between groups are enforced by the structure of the program flow.

<a id="rst-parallel-inode-scans"></a>

### Parallel Inode Scans

An XFS filesystem can easily contain hundreds of millions of inodes. Given that XFS targets installations with large high-performance storage, it is desirable to scrub inodes in parallel to minimize runtime, particularly if the program has been invoked manually from a command line. This requires careful scheduling to keep the threads as evenly loaded as possible.

Early iterations of the `xfs_scrub` inode scanner naïvely created a single workqueue and scheduled a single workqueue item per AG. Each workqueue item walked the inode btree (with `XFS_IOC_INUMBERS`) to find inode chunks and then called bulkstat (`XFS_IOC_BULKSTAT`) to gather enough information to construct file handles. The file handle was then passed to a function to generate scrub items for each metadata object of each inode. This simple algorithm leads to thread balancing problems in phase 3 if the filesystem contains one AG with a few large sparse files and the rest of the AGs contain many smaller files. The inode scan dispatch function was not sufficiently granular; it should have been dispatching at the level of individual inodes, or, to constrain memory consumption, inode btree records.

Thanks to Dave Chinner, bounded workqueues in userspace enable `xfs_scrub` to avoid this problem with ease by adding a second workqueue. Just like before, the first workqueue is seeded with one workqueue item per AG, and it uses INUMBERS to find inode btree chunks. The second workqueue, however, is configured with an upper bound on the number of items that can be waiting to be run. Each inode btree chunk found by the first workqueue's workers are queued to the second workqueue, and it is this second workqueue that queries BULKSTAT, creates a file handle, and passes it to a function to generate scrub items for each metadata object of each inode. If the second workqueue is too full, the workqueue add function blocks the first workqueue's workers until the backlog eases. This doesn't completely solve the balancing problem, but reduces it enough to move on to more pressing issues.

<a id="rst-scheduling-repairs"></a>
<a id="rst-scrubrepair"></a>

### Scheduling Repairs

During phase 2, corruptions and inconsistencies reported in any AGI header or inode btree are repaired immediately, because phase 3 relies on proper functioning of the inode indices to find inodes to scan. Failed repairs are rescheduled to phase 4. Problems reported in any other space metadata are deferred to phase 4. Optimization opportunities are always deferred to phase 4, no matter their origin.

During phase 3, corruptions and inconsistencies reported in any part of a file's metadata are repaired immediately if all space metadata were validated during phase 2. Repairs that fail or cannot be repaired immediately are scheduled for phase 4.

In the original design of `xfs_scrub`, it was thought that repairs would be so infrequent that the `struct xfs_scrub_metadata` objects used to communicate with the kernel could also be used as the primary object to schedule repairs. With recent increases in the number of optimizations possible for a given filesystem object, it became much more memory-efficient to track all eligible repairs for a given filesystem object with a single repair item. Each repair item represents a single lockable object -- AGs, metadata files, individual inodes, or a class of summary information.

Phase 4 is responsible for scheduling a lot of repair work in as quick a manner as is practical. The [data dependencies](<#rst-scrubcheck>) outlined earlier still apply, which means that `xfs_scrub` must try to complete the repair work scheduled by phase 2 before trying repair work scheduled by phase 3. The repair process is as follows:

1. Start a round of repair with a workqueue and enough workers to keep the CPUs as busy as the user desires.

   - **a.** For each repair item queued by phase 2,

     - **i.** Ask the kernel to repair everything listed in the repair item for a given filesystem object.

     - **ii.** Make a note if the kernel made any progress in reducing the number of repairs needed for this object.

     - **iii.** If the object no longer requires repairs, revalidate all metadata associated with this object. If the revalidation succeeds, drop the repair item. If not, requeue the item for more repairs.

   - **b.** If any repairs were made, jump back to 1a to retry all the phase 2 items.

   - **c.** For each repair item queued by phase 3,

     - **i.** Ask the kernel to repair everything listed in the repair item for a given filesystem object.

     - **ii.** Make a note if the kernel made any progress in reducing the number of repairs needed for this object.

     - **iii.** If the object no longer requires repairs, revalidate all metadata associated with this object. If the revalidation succeeds, drop the repair item. If not, requeue the item for more repairs.

   - **d.** If any repairs were made, jump back to 1c to retry all the phase 3 items.

2. If step 1 made any repair progress of any kind, jump back to step 1 to start another round of repair.

3. If there are items left to repair, run them all serially one more time. Complain if the repairs were not successful, since this is the last chance to repair anything.

Corruptions and inconsistencies encountered during phases 5 and 7 are repaired immediately. Corrupt file data blocks reported by phase 6 cannot be recovered by the filesystem.

<a id="rst-checking-names-for-confusable-unicode-sequences"></a>

### Checking Names for Confusable Unicode Sequences

If `xfs_scrub` succeeds in validating the filesystem metadata by the end of phase 4, it moves on to phase 5, which checks for suspicious looking names in the filesystem. These names consist of the filesystem label, names in directory entries, and the names of extended attributes. Like most Unix filesystems, XFS imposes the sparest of constraints on the contents of a name:

- Slashes and null bytes are not allowed in directory entries.

- Null bytes are not allowed in userspace-visible extended attributes.

- Null bytes are not allowed in the filesystem label.

Directory entries and attribute keys store the length of the name explicitly ondisk, which means that nulls are not name terminators. For this section, the term "naming domain" refers to any place where names are presented together -- all the names in a directory, or all the attributes of a file.

Although the Unix naming constraints are very permissive, the reality of most modern-day Linux systems is that programs work with Unicode character code points to support international languages. These programs typically encode those code points in UTF-8 when interfacing with the C library because the kernel expects null-terminated names. In the common case, therefore, names found in an XFS filesystem are actually UTF-8 encoded Unicode data.

To maximize its expressiveness, the Unicode standard defines separate control points for various characters that render similarly or identically in writing systems around the world. For example, the character "Cyrillic Small Letter A" U+0430 "а" often renders identically to "Latin Small Letter A" U+0061 "a".

The standard also permits characters to be constructed in multiple ways -- either by using a defined code point, or by combining one code point with various combining marks. For example, the character "Angstrom Sign U+212B "Å" can also be expressed as "Latin Capital Letter A" U+0041 "A" followed by "Combining Ring Above" U+030A "◌̊". Both sequences render identically.

Like the standards that preceded it, Unicode also defines various control characters to alter the presentation of text. For example, the character "Right-to-Left Override" U+202E can trick some programs into rendering "moo\\xe2\\x80\\xaegnp.txt" as "mootxt.png". A second category of rendering problems involves whitespace characters. If the character "Zero Width Space" U+200B is encountered in a file name, the name will render identically to a name that does not have the zero width space.

If two names within a naming domain have different byte sequences but render identically, a user may be confused by it. The kernel, in its indifference to upper level encoding schemes, permits this. Most filesystem drivers persist the byte sequence names that are given to them by the VFS.

Techniques for detecting confusable names are explained in great detail in sections 4 and 5 of the [Unicode Security Mechanisms](<https://unicode.org/reports/tr39/>)<a id="rst-unicode-security-mechanisms"></a> document. When `xfs_scrub` detects UTF-8 encoding in use on a system, it uses the Unicode normalization form NFD in conjunction with the confusable name detection component of [libicu](<https://github.com/unicode-org/icu>)<a id="rst-libicu"></a> to identify names with a directory or within a file's extended attributes that could be confused for each other. Names are also checked for control characters, non-rendering characters, and mixing of bidirectional characters. All of these potential issues are reported to the system administrator during phase 5.

<a id="rst-media-verification-of-file-data-extents"></a>

### Media Verification of File Data Extents

The system administrator can elect to initiate a media scan of all file data blocks. This scan after validation of all filesystem metadata (except for the summary counters) as phase 6. The scan starts by calling `FS_IOC_GETFSMAP` to scan the filesystem space map to find areas that are allocated to file data fork extents. Gaps between data fork extents that are smaller than 64k are treated as if they were data fork extents to reduce the command setup overhead. When the space map scan accumulates a region larger than 32MB, a media verification request is sent to the disk as a directio read of the raw block device.

If the verification read fails, `xfs_scrub` retries with single-block reads to narrow down the failure to the specific region of the media and recorded. When it has finished issuing verification requests, it again uses the space mapping ioctl to map the recorded media errors back to metadata structures and report what has been lost. For media errors in blocks owned by files, parent pointers can be used to construct file paths from inode numbers for user-friendly reporting.

<a id="rst-conclusion-and-future-work"></a>

## 7. Conclusion and Future Work

It is hoped that the reader of this document has followed the designs laid out in this document and now has some familiarity with how XFS performs online rebuilding of its metadata indices, and how filesystem users can interact with that functionality. Although the scope of this work is daunting, it is hoped that this guide will make it easier for code readers to understand what has been built, for whom it has been built, and why. Please feel free to contact the XFS mailing list with questions.

<a id="rst-xfs-ioc-exchange-range"></a>

### XFS_IOC_EXCHANGE_RANGE

As discussed earlier, a second frontend to the atomic file mapping exchange mechanism is a new ioctl call that userspace programs can use to commit updates to files atomically. This frontend has been out for review for several years now, though the necessary refinements to online repair and lack of customer demand mean that the proposal has not been pushed very hard.

<a id="rst-file-content-exchanges-with-regular-user-files"></a>

#### File Content Exchanges with Regular User Files

As mentioned earlier, XFS has long had the ability to swap extents between files, which is used almost exclusively by `xfs_fsr` to defragment files. The earliest form of this was the fork swap mechanism, where the entire contents of data forks could be exchanged between two files by exchanging the raw bytes in each inode fork's immediate area. When XFS v5 came along with self-describing metadata, this old mechanism grew some log support to continue rewriting the owner fields of BMBT blocks during log recovery. When the reverse mapping btree was later added to XFS, the only way to maintain the consistency of the fork mappings with the reverse mapping index was to develop an iterative mechanism that used deferred bmap and rmap operations to swap mappings one at a time. This mechanism is identical to steps 2-3 from the procedure above except for the new tracking items, because the atomic file mapping exchange mechanism is an iteration of an existing mechanism and not something totally novel. For the narrow case of file defragmentation, the file contents must be identical, so the recovery guarantees are not much of a gain.

Atomic file content exchanges are much more flexible than the existing swapext implementations because it can guarantee that the caller never sees a mix of old and new contents even after a crash, and it can operate on two arbitrary file fork ranges. The extra flexibility enables several new use cases:

- **Atomic commit of file writes**: A userspace process opens a file that it wants to update. Next, it opens a temporary file and calls the file clone operation to reflink the first file's contents into the temporary file. Writes to the original file should instead be written to the temporary file. Finally, the process calls the atomic file mapping exchange system call (`XFS_IOC_EXCHANGE_RANGE`) to exchange the file contents, thereby committing all of the updates to the original file, or none of them.

<a id="rst-exchrange-if-unchanged"></a>

- **Transactional file updates**: The same mechanism as above, but the caller only wants the commit to occur if the original file's contents have not changed. To make this happen, the calling process snapshots the file modification and change timestamps of the original file before reflinking its data to the temporary file. When the program is ready to commit the changes, it passes the timestamps into the kernel as arguments to the atomic file mapping exchange system call. The kernel only commits the changes if the provided timestamps match the original file. A new ioctl (`XFS_IOC_COMMIT_RANGE`) is provided to perform this.

- **Emulation of atomic block device writes**: Export a block device with a logical sector size matching the filesystem block size to force all writes to be aligned to the filesystem block size. Stage all writes to a temporary file, and when that is complete, call the atomic file mapping exchange system call with a flag to indicate that holes in the temporary file should be ignored. This emulates an atomic device write in software, and can support arbitrary scattered writes.

(This functionality was merged into mainline as of 2025)

<a id="rst-vectorized-scrub"></a>

### Vectorized Scrub

As it turns out, the [refactoring](<#rst-scrubrepair>) of repair items mentioned earlier was a catalyst for enabling a vectorized scrub system call. Since 2018, the cost of making a kernel call has increased considerably on some systems to mitigate the effects of speculative execution attacks. This incentivizes program authors to make as few system calls as possible to reduce the number of times an execution path crosses a security boundary.

With vectorized scrub, userspace pushes to the kernel the identity of a filesystem object, a list of scrub types to run against that object, and a simple representation of the data dependencies between the selected scrub types. The kernel executes as much of the caller's plan as it can until it hits a dependency that cannot be satisfied due to a corruption, and tells userspace how much was accomplished. It is hoped that `io_uring` will pick up enough of this functionality that online fsck can use that instead of adding a separate vectored scrub system call to XFS.

(This functionality was merged into mainline as of 2025)

<a id="rst-quality-of-service-targets-for-scrub"></a>

### Quality of Service Targets for Scrub

One serious shortcoming of the online fsck code is that the amount of time that it can spend in the kernel holding resource locks is basically unbounded. Userspace is allowed to send a fatal signal to the process which will cause `xfs_scrub` to exit when it reaches a good stopping point, but there's no way for userspace to provide a time budget to the kernel. Given that the scrub codebase has helpers to detect fatal signals, it shouldn't be too much work to allow userspace to specify a timeout for a scrub/repair operation and abort the operation if it exceeds budget. However, most repair functions have the property that once they begin to touch ondisk metadata, the operation cannot be cancelled cleanly, after which a QoS timeout is no longer useful.

<a id="rst-defragmenting-free-space"></a>

### Defragmenting Free Space

Over the years, many XFS users have requested the creation of a program to clear a portion of the physical storage underlying a filesystem so that it becomes a contiguous chunk of free space. Call this free space defragmenter `clearspace` for short.

The first piece the `clearspace` program needs is the ability to read the reverse mapping index from userspace. This already exists in the form of the `FS_IOC_GETFSMAP` ioctl. The second piece it needs is a new fallocate mode (`FALLOC_FL_MAP_FREE_SPACE`) that allocates the free space in a region and maps it to a file. Call this file the "space collector" file. The third piece is the ability to force an online repair.

To clear all the metadata out of a portion of physical storage, clearspace uses the new fallocate map-freespace call to map any free space in that region to the space collector file. Next, clearspace finds all metadata blocks in that region by way of `GETFSMAP` and issues forced repair requests on the data structure. This often results in the metadata being rebuilt somewhere that is not being cleared. After each relocation, clearspace calls the "map free space" function again to collect any newly freed space in the region being cleared.

To clear all the file data out of a portion of the physical storage, clearspace uses the FSMAP information to find relevant file data blocks. Having identified a good target, it uses the `FICLONERANGE` call on that part of the file to try to share the physical space with a dummy file. Cloning the extent means that the original owners cannot overwrite the contents; any changes will be written somewhere else via copy-on-write. Clearspace makes its own copy of the frozen extent in an area that is not being cleared, and uses `FIEDEUPRANGE` (or the [atomic file content exchanges](<#rst-exchrange-if-unchanged>) feature) to change the target file's data extent mapping away from the area being cleared. When all other mappings have been moved, clearspace reflinks the space into the space collector file so that it becomes unavailable.

There are further optimizations that could apply to the above algorithm. To clear a piece of physical storage that has a high sharing factor, it is strongly desirable to retain this sharing factor. In fact, these extents should be moved first to maximize sharing factor after the operation completes. To make this work smoothly, clearspace needs a new ioctl (`FS_IOC_GETREFCOUNTS`) to report reference count information to userspace. With the refcount information exposed, clearspace can quickly find the longest, most shared data extents in the filesystem, and target them first.

**Future Work Question**: How might the filesystem move inode chunks?

*Answer*: To move inode chunks, Dave Chinner constructed a prototype program that creates a new file with the old contents and then locklessly runs around the filesystem updating directory entries. The operation cannot complete if the filesystem goes down. That problem isn't totally insurmountable: create an inode remapping table hidden behind a jump label, and a log item that tracks the kernel walking the filesystem to update directory entries. The trouble is, the kernel can't do anything about open files, since it cannot revoke them.

**Future Work Question**: Can static keys be used to minimize the cost of supporting `revoke()` on XFS files?

*Answer*: Yes. Until the first revocation, the bailout code need not be in the call path at all.

The relevant patchsets are the [kernel freespace defrag](<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfs-linux.git/log/?h=defrag-freespace>)<a id="rst-kernel-freespace-defrag"></a> and [userspace freespace defrag](<https://git.kernel.org/pub/scm/linux/kernel/git/djwong/xfsprogs-dev.git/log/?h=defrag-freespace>)<a id="rst-userspace-freespace-defrag"></a> series.

<a id="rst-shrinking-filesystems"></a>

### Shrinking Filesystems

Removing the end of the filesystem ought to be a simple matter of evacuating the data and metadata at the end of the filesystem, and handing the freed space to the shrink code. That requires an evacuation of the space at end of the filesystem, which is a use of free space defragmentation\!

---

# XFS Self Describing Metadata

_Peios Kernel / Internals / Filesystems / xfs_

> The largest scalability problem facing XFS is not one of algorithmic scalability, but of verification of the filesystem structure. Scalabilty of the structures and indexes on disk and the algorithms for iterating them are adequate for…

<a id="rst-xfs-self-describing-metadata-1"></a>
<a id="rst-xfs-self-describing-metadata"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The largest scalability problem facing XFS is not one of algorithmic scalability, but of verification of the filesystem structure. Scalabilty of the structures and indexes on disk and the algorithms for iterating them are adequate for supporting PB scale filesystems with billions of inodes, however it is this very scalability that causes the verification problem.

Almost all metadata on XFS is dynamically allocated. The only fixed location metadata is the allocation group headers (SB, AGF, AGFL and AGI), while all other metadata structures need to be discovered by walking the filesystem structure in different ways. While this is already done by userspace tools for validating and repairing the structure, there are limits to what they can verify, and this in turn limits the supportable size of an XFS filesystem.

For example, it is entirely possible to manually use xfs_db and a bit of scripting to analyse the structure of a 100TB filesystem when trying to determine the root cause of a corruption problem, but it is still mainly a manual task of verifying that things like single bit errors or misplaced writes weren't the ultimate cause of a corruption event. It may take a few hours to a few days to perform such forensic analysis, so for at this scale root cause analysis is entirely possible.

However, if we scale the filesystem up to 1PB, we now have 10x as much metadata to analyse and so that analysis blows out towards weeks/months of forensic work. Most of the analysis work is slow and tedious, so as the amount of analysis goes up, the more likely that the cause will be lost in the noise.  Hence the primary concern for supporting PB scale filesystems is minimising the time and effort required for basic forensic analysis of the filesystem structure.

<a id="rst-self-describing-metadata"></a>

## Self Describing Metadata

One of the problems with the current metadata format is that apart from the magic number in the metadata block, we have no other way of identifying what it is supposed to be. We can't even identify if it is the right place. Put simply, you can't look at a single metadata block in isolation and say "yes, it is supposed to be there and the contents are valid".

Hence most of the time spent on forensic analysis is spent doing basic verification of metadata values, looking for values that are in range (and hence not detected by automated verification checks) but are not correct. Finding and understanding how things like cross linked block lists (e.g. sibling pointers in a btree end up with loops in them) are the key to understanding what went wrong, but it is impossible to tell what order the blocks were linked into each other or written to disk after the fact.

Hence we need to record more information into the metadata to allow us to quickly determine if the metadata is intact and can be ignored for the purpose of analysis. We can't protect against every possible type of error, but we can ensure that common types of errors are easily detectable.  Hence the concept of self describing metadata.

The first, fundamental requirement of self describing metadata is that the metadata object contains some form of unique identifier in a well known location. This allows us to identify the expected contents of the block and hence parse and verify the metadata object. IF we can't independently identify the type of metadata in the object, then the metadata doesn't describe itself very well at all\!

Luckily, almost all XFS metadata has magic numbers embedded already - only the AGFL, remote symlinks and remote attribute blocks do not contain identifying magic numbers. Hence we can change the on-disk format of all these objects to add more identifying information and detect this simply by changing the magic numbers in the metadata objects. That is, if it has the current magic number, the metadata isn't self identifying. If it contains a new magic number, it is self identifying and we can do much more expansive automated verification of the metadata object at runtime, during forensic analysis or repair.

As a primary concern, self describing metadata needs some form of overall integrity checking. We cannot trust the metadata if we cannot verify that it has not been changed as a result of external influences. Hence we need some form of integrity check, and this is done by adding CRC32c validation to the metadata block. If we can verify the block contains the metadata it was intended to contain, a large amount of the manual verification work can be skipped.

CRC32c was selected as metadata cannot be more than 64k in length in XFS and hence a 32 bit CRC is more than sufficient to detect multi-bit errors in metadata blocks. CRC32c is also now hardware accelerated on common CPUs so it is fast. So while CRC32c is not the strongest of possible integrity checks that could be used, it is more than sufficient for our needs and has relatively little overhead. Adding support for larger integrity fields and/or algorithms does really provide any extra value over CRC32c, but it does add a lot of complexity and so there is no provision for changing the integrity checking mechanism.

Self describing metadata needs to contain enough information so that the metadata block can be verified as being in the correct place without needing to look at any other metadata. This means it needs to contain location information. Just adding a block number to the metadata is not sufficient to protect against mis-directed writes - a write might be misdirected to the wrong LUN and so be written to the "correct block" of the wrong filesystem. Hence location information must contain a filesystem identifier as well as a block number.

Another key information point in forensic analysis is knowing who the metadata block belongs to. We already know the type, the location, that it is valid and/or corrupted, and how long ago that it was last modified. Knowing the owner of the block is important as it allows us to find other related metadata to determine the scope of the corruption. For example, if we have a extent btree object, we don't know what inode it belongs to and hence have to walk the entire filesystem to find the owner of the block. Worse, the corruption could mean that no owner can be found (i.e. it's an orphan block), and so without an owner field in the metadata we have no idea of the scope of the corruption. If we have an owner field in the metadata object, we can immediately do top down validation to determine the scope of the problem.

Different types of metadata have different owner identifiers. For example, directory, attribute and extent tree blocks are all owned by an inode, while freespace btree blocks are owned by an allocation group. Hence the size and contents of the owner field are determined by the type of metadata object we are looking at.  The owner information can also identify misplaced writes (e.g. freespace btree block written to the wrong AG).

Self describing metadata also needs to contain some indication of when it was written to the filesystem. One of the key information points when doing forensic analysis is how recently the block was modified. Correlation of set of corrupted metadata blocks based on modification times is important as it can indicate whether the corruptions are related, whether there's been multiple corruption events that lead to the eventual failure, and even whether there are corruptions present that the run-time verification is not detecting.

For example, we can determine whether a metadata object is supposed to be free space or still allocated if it is still referenced by its owner by looking at when the free space btree block that contains the block was last written compared to when the metadata object itself was last written.  If the free space block is more recent than the object and the object's owner, then there is a very good chance that the block should have been removed from the owner.

To provide this "written timestamp", each metadata block gets the Log Sequence Number (LSN) of the most recent transaction it was modified on written into it. This number will always increase over the life of the filesystem, and the only thing that resets it is running xfs_repair on the filesystem. Further, by use of the LSN we can tell if the corrupted metadata all belonged to the same log checkpoint and hence have some idea of how much modification occurred between the first and last instance of corrupt metadata on disk and, further, how much modification occurred between the corruption being written and when it was detected.

<a id="rst-runtime-validation"></a>

## Runtime Validation

Validation of self-describing metadata takes place at runtime in two places:

> - immediately after a successful read from disk
>
> - immediately prior to write IO submission

The verification is completely stateless - it is done independently of the modification process, and seeks only to check that the metadata is what it says it is and that the metadata fields are within bounds and internally consistent. As such, we cannot catch all types of corruption that can occur within a block as there may be certain limitations that operational state enforces of the metadata, or there may be corruption of interblock relationships (e.g. corrupted sibling pointer lists). Hence we still need stateful checking in the main code body, but in general most of the per-field validation is handled by the verifiers.

For read verification, the caller needs to specify the expected type of metadata that it should see, and the IO completion process verifies that the metadata object matches what was expected. If the verification process fails, then it marks the object being read as EFSCORRUPTED. The caller needs to catch this error (same as for IO errors), and if it needs to take special action due to a verification error it can do so by catching the EFSCORRUPTED error value. If we need more discrimination of error type at higher levels, we can define new error numbers for different errors as necessary.

The first step in read verification is checking the magic number and determining whether CRC validating is necessary. If it is, the CRC32c is calculated and compared against the value stored in the object itself. Once this is validated, further checks are made against the location information, followed by extensive object specific metadata validation. If any of these checks fail, then the buffer is considered corrupt and the EFSCORRUPTED error is set appropriately.

Write verification is the opposite of the read verification - first the object is extensively verified and if it is OK we then update the LSN from the last modification made to the object, After this, we calculate the CRC and insert it into the object. Once this is done the write IO is allowed to continue. If any error occurs during this process, the buffer is again marked with a EFSCORRUPTED error for the higher layers to catch.

<a id="rst-structures"></a>

## Structures

A typical on-disk structure needs to contain the following information:



```text
struct xfs_ondisk_hdr {
        __be32  magic;              /* magic number */
        __be32  crc;                /* CRC, not logged */
        uuid_t  uuid;               /* filesystem identifier */
        __be64  owner;              /* parent object */
        __be64  blkno;              /* location on disk */
        __be64  lsn;                /* last modification in log, not logged */
};
```

Depending on the metadata, this information may be part of a header structure separate to the metadata contents, or may be distributed through an existing structure. The latter occurs with metadata that already contains some of this information, such as the superblock and AG headers.

Other metadata may have different formats for the information, but the same level of information is generally provided. For example:

> - short btree blocks have a 32 bit owner (ag number) and a 32 bit block number for location. The two of these combined provide the same information as @owner and @blkno in eh above structure, but using 8 bytes less space on disk.
>
> - directory/attribute node blocks have a 16 bit magic number, and the header that contains the magic number has other information in it as well. hence the additional metadata headers change the overall format of the metadata.

A typical buffer read verifier is structured as follows:



```text
#define XFS_FOO_CRC_OFF             offsetof(struct xfs_ondisk_hdr, crc)

static void
xfs_foo_read_verify(
        struct xfs_buf      *bp)
{
    struct xfs_mount *mp = bp->b_mount;

        if ((xfs_sb_version_hascrc(&mp->m_sb) &&
            !xfs_verify_cksum(bp->b_addr, BBTOB(bp->b_length),
                                        XFS_FOO_CRC_OFF)) ||
            !xfs_foo_verify(bp)) {
                XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp, bp->b_addr);
                xfs_buf_ioerror(bp, EFSCORRUPTED);
        }
}
```

The code ensures that the CRC is only checked if the filesystem has CRCs enabled by checking the superblock of the feature bit, and then if the CRC verifies OK (or is not needed) it verifies the actual contents of the block.

The verifier function will take a couple of different forms, depending on whether the magic number can be used to determine the format of the block. In the case it can't, the code is structured as follows:



```text
static bool
xfs_foo_verify(
        struct xfs_buf              *bp)
{
        struct xfs_mount    *mp = bp->b_mount;
        struct xfs_ondisk_hdr       *hdr = bp->b_addr;

        if (hdr->magic != cpu_to_be32(XFS_FOO_MAGIC))
                return false;

        if (!xfs_sb_version_hascrc(&mp->m_sb)) {
                if (!uuid_equal(&hdr->uuid, &mp->m_sb.sb_uuid))
                        return false;
                if (bp->b_bn != be64_to_cpu(hdr->blkno))
                        return false;
                if (hdr->owner == 0)
                        return false;
        }

        /* object specific verification checks here */

        return true;
}
```

If there are different magic numbers for the different formats, the verifier will look like:



```text
static bool
xfs_foo_verify(
        struct xfs_buf              *bp)
{
        struct xfs_mount    *mp = bp->b_mount;
        struct xfs_ondisk_hdr       *hdr = bp->b_addr;

        if (hdr->magic == cpu_to_be32(XFS_FOO_CRC_MAGIC)) {
                if (!uuid_equal(&hdr->uuid, &mp->m_sb.sb_uuid))
                        return false;
                if (bp->b_bn != be64_to_cpu(hdr->blkno))
                        return false;
                if (hdr->owner == 0)
                        return false;
        } else if (hdr->magic != cpu_to_be32(XFS_FOO_MAGIC))
                return false;

        /* object specific verification checks here */

        return true;
}
```

Write verifiers are very similar to the read verifiers, they just do things in the opposite order to the read verifiers. A typical write verifier:



```text
static void
xfs_foo_write_verify(
        struct xfs_buf      *bp)
{
        struct xfs_mount    *mp = bp->b_mount;
        struct xfs_buf_log_item     *bip = bp->b_fspriv;

        if (!xfs_foo_verify(bp)) {
                XFS_CORRUPTION_ERROR(__func__, XFS_ERRLEVEL_LOW, mp, bp->b_addr);
                xfs_buf_ioerror(bp, EFSCORRUPTED);
                return;
        }

        if (!xfs_sb_version_hascrc(&mp->m_sb))
                return;


        if (bip) {
                struct xfs_ondisk_hdr       *hdr = bp->b_addr;
                hdr->lsn = cpu_to_be64(bip->bli_item.li_lsn);
        }
        xfs_update_cksum(bp->b_addr, BBTOB(bp->b_length), XFS_FOO_CRC_OFF);
}
```

This will verify the internal structure of the metadata before we go any further, detecting corruptions that have occurred as the metadata has been modified in memory. If the metadata verifies OK, and CRCs are enabled, we then update the LSN field (when it was last modified) and calculate the CRC on the metadata. Once this is done, we can issue the IO.

<a id="rst-inodes-and-dquots"></a>

## Inodes and Dquots

Inodes and dquots are special snowflakes. They have per-object CRC and self-identifiers, but they are packed so that there are multiple objects per buffer. Hence we do not use per-buffer verifiers to do the work of per-object verification and CRC calculations. The per-buffer verifiers simply perform basic identification of the buffer - that they contain inodes or dquots, and that there are magic numbers in all the expected spots. All further CRC and verification checks are done when each inode is read from or written back to the buffer.

The structure of the verifiers and the identifiers checks is very similar to the buffer code described above. The only difference is where they are called. For example, inode read verification is done in xfs_inode_from_disk() when the inode is first read out of the buffer and the struct xfs_inode is instantiated. The inode is already extensively verified during writeback in xfs_iflush_int, so the only addition here is to add the LSN and CRC to the inode as it is copied back into the buffer.

XXX: inode unlinked list modification doesn't recalculate the inode CRC\! None of the unlinked list modifications check or update CRCs, neither during unlink nor log recovery. So, it's gone unnoticed until now. This won't matter immediately - repair will probably complain about it - but it needs to be fixed.

---

# Path walking and name lookup locking

_Peios Kernel / Internals / Filesystems_

> Kernel reference: Path walking and name lookup locking.

Path resolution is the finding a dentry corresponding to a path name string, by
performing a path walk. Typically, for every open(), stat() etc., the path name
will be resolved. Paths are resolved by walking the namespace tree, starting
with the first component of the pathname (eg. root or cwd) with a known dentry,
then finding the child of that dentry, which is named the next component in the
path string. Then repeating the lookup from the child dentry and finding its
child with the next element, and so on.

Since it is a frequent operation for workloads like multiuser environments and
web servers, it is important to optimize this code.

Path walking synchronisation history:
Prior to 2.5.10, dcache\_lock was acquired in d\_lookup (dcache hash lookup) and
thus in every component during path look-up. Since 2.5.10 onwards, fast-walk
algorithm changed this by holding the dcache\_lock at the beginning and walking
as many cached path component dentries as possible. This significantly
decreases the number of acquisition of dcache\_lock. However it also increases
the lock hold time significantly and affects performance in large SMP machines.
Since 2.5.62 kernel, dcache has been using a new locking model that uses RCU to
make dcache look-up lock-free.

All the above algorithms required taking a lock and reference count on the
dentry that was looked up, so that may be used as the basis for walking the
next path element. This is inefficient and unscalable. It is inefficient
because of the locks and atomic operations required for every dentry element
slows things down. It is not scalable because many parallel applications that
are path-walk intensive tend to do path lookups starting from a common dentry
(usually, the root "/" or current working directory). So contention on these
common path elements causes lock and cacheline queueing.

Since 2.6.38, RCU is used to make a significant part of the entire path walk
(including dcache look-up) completely "store-free" (so, no locks, atomics, or
even stores into cachelines of common dentries). This is known as "rcu-walk"
path walking.

## Path walking overview

A name string specifies a start (root directory, cwd, fd-relative) and a
sequence of elements (directory entry names), which together refer to a path in
the namespace. A path is represented as a (dentry, vfsmount) tuple. The name
elements are sub-strings, separated by '/'.

Name lookups will want to find a particular path that a name string refers to
(usually the final element, or parent of final element). This is done by taking
the path given by the name's starting point (which we know in advance -- eg.
current-&gt;fs-&gt;cwd or current-&gt;fs-&gt;root) as the first parent of the lookup. Then
iteratively for each subsequent name element, look up the child of the current
parent with the given name and if it is not the desired entry, make it the
parent for the next lookup.

A parent, of course, must be a directory, and we must have appropriate
permissions on the parent inode to be able to walk into it.

Turning the child into a parent for the next lookup requires more checks and
procedures. Symlinks essentially substitute the symlink name for the target
name in the name string, and require some recursive path walking.  Mount points
must be followed into (thus changing the vfsmount that subsequent path elements
refer to), switching from the mount point path to the root of the particular
mounted vfsmount. These behaviours are variously modified depending on the
exact path walking flags.

Path walking then must, broadly, do several particular things:

- find the start point of the walk;
- perform permissions and validity checks on inodes;
- perform dcache hash name lookups on (parent, name element) tuples;
- traverse mount points;
- traverse symlinks;
- lookup and create missing parts of the path on demand.

## Safe store-free look-up of dcache hash table

### Dcache name lookup

In order to lookup a dcache (parent, name) tuple, we take a hash on the tuple
and use that to select a bucket in the dcache-hash table. The list of entries
in that bucket is then walked, and we do a full comparison of each entry
against our (parent, name) tuple.

The hash lists are RCU protected, so list walking is not serialised with
concurrent updates (insertion, deletion from the hash). This is a standard RCU
list application with the exception of renames, which will be covered below.

Parent and name members of a dentry, as well as its membership in the dcache
hash, and its inode are protected by the per-dentry d\_lock spinlock. A
reference is taken on the dentry (while the fields are verified under d\_lock),
and this stabilises its d\_inode pointer and actual inode. This gives a stable
point to perform the next step of our path walk against.

These members are also protected by d\_seq seqlock, although this offers
read-only protection and no durability of results, so care must be taken when
using d\_seq for synchronisation (see seqcount based lookups, below).

### Renames

Back to the rename case. In usual RCU protected lists, the only operations that
will happen to an object is insertion, and then eventually removal from the
list. The object will not be reused until an RCU grace period is complete.
This ensures the RCU list traversal primitives can run over the object without
problems (see RCU documentation for how this works).

However when a dentry is renamed, its hash value can change, requiring it to be
moved to a new hash list. Allocating and inserting a new alias would be
expensive and also problematic for directory dentries. Latency would be far to
high to wait for a grace period after removing the dentry and before inserting
it in the new hash bucket. So what is done is to insert the dentry into the
new list immediately.

However, when the dentry's list pointers are updated to point to objects in the
new list before waiting for a grace period, this can result in a concurrent RCU
lookup of the old list veering off into the new (incorrect) list and missing
the remaining dentries on the list.

There is no fundamental problem with walking down the wrong list, because the
dentry comparisons will never match. However it is fatal to miss a matching
dentry. So a seqlock is used to detect when a rename has occurred, and so the
lookup can be retried.

```text
         1      2      3
        +---+  +---+  +---+
```

```text
hlist-->| N-+->| N-+->| N-+->
head <--+-P |<-+-P |<-+-P |
```

```text
        +---+  +---+  +---+
```

Rename of dentry 2 may require it deleted from the above list, and inserted
into a new list. Deleting 2 gives the following list.

```text
         1             3
        +---+         +---+     (don't worry, the longer pointers do not
```

```text
hlist-->| N-+-------->| N-+->    impose a measurable performance overhead
head <--+-P |<--------+-P |      on modern CPUs)
```

```text
        +---+         +---+
          ^      2      ^
          |    +---+    |
          |    | N-+----+
          +----+-P |
               +---+
```

This is a standard RCU-list deletion, which leaves the deleted object's
pointers intact, so a concurrent list walker that is currently looking at
object 2 will correctly continue to object 3 when it is time to traverse the
next object.

However, when inserting object 2 onto a new list, we end up with this:

```text
         1             3
        +---+         +---+
```

```text
hlist-->| N-+-------->| N-+->
head <--+-P |<--------+-P |
```

```text
        +---+         +---+
                 2
               +---+
               | N-+---->
          <----+-P |
               +---+
```

Because we didn't wait for a grace period, there may be a concurrent lookup
still at 2. Now when it follows 2's 'next' pointer, it will walk off into
another list without ever having checked object 3.

A related, but distinctly different, issue is that of rename atomicity versus
lookup operations. If a file is renamed from 'A' to 'B', a lookup must only
find either 'A' or 'B'. So if a lookup of 'A' returns NULL, a subsequent lookup
of 'B' must succeed (note the reverse is not true).

Between deleting the dentry from the old hash list, and inserting it on the new
hash list, a lookup may find neither 'A' nor 'B' matching the dentry. The same
rename seqlock is also used to cover this race in much the same way, by
retrying a negative lookup result if a rename was in progress.

### Seqcount based lookups

In refcount based dcache lookups, d\_lock is used to serialise access to
the dentry, stabilising it while comparing its name and parent and then
taking a reference count (the reference count then gives a stable place to
start the next part of the path walk from).

As explained above, we would like to do path walking without taking locks or
reference counts on intermediate dentries along the path. To do this, a per
dentry seqlock (d\_seq) is used to take a "coherent snapshot" of what the dentry
looks like (its name, parent, and inode). That snapshot is then used to start
the next part of the path walk. When loading the coherent snapshot under d\_seq,
care must be taken to load the members up-front, and use those pointers rather
than reloading from the dentry later on (otherwise we'd have interesting things
like d\_inode going NULL underneath us, if the name was unlinked).

Also important is to avoid performing any destructive operations (pretty much:
no non-atomic stores to shared data), and to recheck the seqcount when we are
"done" with the operation. Retry or abort if the seqcount does not match.
Avoiding destructive or changing operations means we can easily unwind from
failure.

What this means is that a caller, provided they are holding RCU lock to
protect the dentry object from disappearing, can perform a seqcount based
lookup which does not increment the refcount on the dentry or write to
it in any way. This returned dentry can be used for subsequent operations,
provided that d\_seq is rechecked after that operation is complete.

Inodes are also rcu freed, so the seqcount lookup dentry's inode may also be
queried for permissions.

With this two parts of the puzzle, we can do path lookups without taking
locks or refcounts on dentry elements.

## RCU-walk path walking design

Path walking code now has two distinct modes, ref-walk and rcu-walk. ref-walk
is the traditional\[\*\] way of performing dcache lookups using d\_lock to
serialise concurrent modifications to the dentry and take a reference count on
it. ref-walk is simple and obvious, and may sleep, take locks, etc while path
walking is operating on each dentry. rcu-walk uses seqcount based dentry
lookups, and can perform lookup of intermediate elements without any stores to
shared data in the dentry or inode. rcu-walk can not be applied to all cases,
eg. if the filesystem must sleep or perform non trivial operations, rcu-walk
must be switched to ref-walk mode.

\[\*\] RCU is still used for the dentry hash lookup in ref-walk, but not the full

```text
    path walk.
```

Where ref-walk uses a stable, refcounted \`\`parent'' to walk the remaining
path string, rcu-walk uses a d\_seq protected snapshot. When looking up a
child of this parent snapshot, we open d\_seq critical section on the child
before closing d\_seq critical section on the parent. This gives an interlocking
ladder of snapshots to walk down.

```text
     proc 101
      /----------------\
     / comm:    "vi"    \
    /  fs.root: dentry0  \
    \  fs.cwd:  dentry2  /
     \                  /
      \----------------/
```

So when vi wants to open("/home/npiggin/test.c", O\_RDWR), then it will
start from current-&gt;fs-&gt;root, which is a pinned dentry. Alternatively,
"./test.c" would start from cwd; both names refer to the same path in
the context of proc101.

```text
     dentry 0
    +---------------------+   rcu-walk begins here, we note d_seq, check the
    | name:    "/"        |   inode's permission, and then look up the next
    | inode:   10         |   path element which is "home"...
    | children:"home", ...|
    +---------------------+
              |
     dentry 1 V
    +---------------------+   ... which brings us here. We find dentry1 via
    | name:    "home"     |   hash lookup, then note d_seq and compare name
    | inode:   678        |   string and parent pointer. When we have a match,
    | children:"npiggin"  |   we now recheck the d_seq of dentry0. Then we
    +---------------------+   check inode and look up the next element.
              |
     dentry2  V
    +---------------------+   Note: if dentry0 is now modified, lookup is
    | name:    "npiggin"  |   not necessarily invalid, so we need only keep a
    | inode:   543        |   parent for d_seq verification, and grandparents
    | children:"a.c", ... |   can be forgotten.
    +---------------------+
              |
     dentry3  V
    +---------------------+   At this point we have our destination dentry.
    | name:    "a.c"      |   We now take its d_lock, verify d_seq of this
    | inode:   14221      |   dentry. If that checks out, we can increment
    | children:NULL       |   its refcount because we're holding d_lock.
    +---------------------+
```

Taking a refcount on a dentry from rcu-walk mode, by taking its d\_lock,
re-checking its d\_seq, and then incrementing its refcount is called
"dropping rcu" or dropping from rcu-walk into ref-walk mode.

It is, in some sense, a bit of a house of cards. If the seqcount check of the
parent snapshot fails, the house comes down, because we had closed the d\_seq
section on the grandparent, so we have nothing left to stand on. In that case,
the path walk must be fully restarted (which we do in ref-walk mode, to avoid
live locks). It is costly to have a full restart, but fortunately they are
quite rare.

When we reach a point where sleeping is required, or a filesystem callout
requires ref-walk, then instead of restarting the walk, we attempt to drop rcu
at the last known good dentry we have. Avoiding a full restart in ref-walk in
these cases is fundamental for performance and scalability because blocking
operations such as creates and unlinks are not uncommon.

The detailed design for rcu-walk is like this:

- LOOKUP\_RCU is set in nd-&gt;flags, which distinguishes rcu-walk from ref-walk.
- Take the RCU lock for the entire path walk, starting with the acquiring
  of the starting path (eg. root/cwd/fd-path). So now dentry refcounts are
  not required for dentry persistence.
- synchronize\_rcu is called when unregistering a filesystem, so we can
  access d\_ops and i\_ops during rcu-walk.
- Similarly take the vfsmount lock for the entire path walk. So now mnt
  refcounts are not required for persistence. Also we are free to perform mount
  lookups, and to assume dentry mount points and mount roots are stable up and
  down the path.
- Have a per-dentry seqlock to protect the dentry name, parent, and inode,
  so we can load this tuple atomically, and also check whether any of its
  members have changed.
- Dentry lookups (based on parent, candidate string tuple) recheck the parent
  sequence after the child is found in case anything changed in the parent
  during the path walk.
- inode is also RCU protected so we can load d\_inode and use the inode for
  limited things.
- i\_mode, i\_uid, i\_gid can be tested for exec permissions during path walk.
- i\_op can be loaded.
- When the destination dentry is reached, drop rcu there (ie. take d\_lock,
  verify d\_seq, increment refcount).
- If seqlock verification fails anywhere along the path, do a full restart
  of the path lookup in ref-walk mode. -ECHILD tends to be used (for want of
  a better errno) to signal an rcu-walk failure.

The cases where rcu-walk cannot continue are:

- NULL dentry (ie. any uncached path element)
- Following links

It may be possible eventually to make following links rcu-walk aware.

Uncached path elements will always require dropping to ref-walk mode, at the
very least because i\_mutex needs to be grabbed, and objects allocated.

Final note:
"store-free" path walking is not strictly store free. We take vfsmount lock
and refcounts (both of which can be made per-cpu), and we also store to the
stack (which is essentially CPU-local), and we also have to take locks and
refcount on final dentry.

The point is that shared data, where practically possible, is not locked
or stored into. The result is massive improvements in performance and
scalability of path resolution.

## Interesting statistics

The following table gives rcu lookup statistics for a few simple workloads
(2s12c24t Westmere, debian non-graphical system). Ungraceful are attempts to
drop rcu that fail due to d\_seq failure and requiring the entire path lookup
again. Other cases are successful rcu-drops that are required before the final
element, nodentry for missing dentry, revalidate for filesystem revalidate
routine requiring rcu drop, permission for permission check requiring drop,
and link for symlink traversal requiring drop.

```text
     rcu-lookups     restart  nodentry          link  revalidate  permission
```

```text
bootup     47121           0      4624          1010       10283        7852
dbench  25386793           0   6778659(26.7%)     55         549        1156
kbuild   2696672          10     64442(2.3%)  108764(4.0%)     1        1590
git diff   39605           0        28             2           0         106
vfstest 24185492        4945    708725(2.9%) 1076136(4.4%)     0        2651
```

What this shows is that failed rcu-walk lookups, ie. ones that are restarted
entirely with ref-walk, are quite rare. Even the "vfstest" case which
specifically has concurrent renames/mkdir/rmdir/ creat/unlink/etc to exercise
such races is not showing a huge amount of restarts.

Dropping from rcu-walk to ref-walk mean that we have encountered a dentry where
the reference count needs to be taken for some reason. This is either because
we have reached the target of the path walk, or because we have encountered a
condition that can't be resolved in rcu-walk mode.  Ideally, we drop rcu-walk
only when we have reached the target dentry, so the other statistics show where
this does not happen.

Note that a graceful drop from rcu-walk mode due to something such as the
dentry not existing (which can be common) is not necessarily a failure of
rcu-walk scheme, because some elements of the path may have been walked in
rcu-walk mode. The further we get from common path elements (such as cwd or
root), the less contended the dentry is likely to be. The closer we are to
common path elements, the more likely they will exist in dentry cache.

## Papers and other documentation on dcache locking

1. Scaling dcache with RCU (https://linuxjournal.com/article.php?sid=7124).

2. http://lse.sourceforge.net/locking/dcache/dcache.html

3. [path-lookup.rst](</kernel/internals/filesystems/path-lookup.md>) in this directory.

---

# Notes on propagate_umount()

_Peios Kernel / Internals / Filesystems_

> Kernel reference: Notes on propagate_umount().

Umount propagation starts with a set of mounts we are already going to
take out.  Ideally, we would like to add all downstream cognates to
that set - anything with the same mountpoint as one of the removed
mounts and with parent that would receive events from the parent of that
mount.  However, there are some constraints the resulting set must
satisfy.

It is convenient to define several properties of sets of mounts:

1) A set S of mounts is non-shifting if for any mount X belonging
   to S all subtrees mounted strictly inside of X (i.e. not overmounting
   the root of X) contain only elements of S.

2) A set S is non-revealing if all locked mounts that belong to S have
   parents that also belong to S.

3) A set S is closed if it contains all children of its elements.

The set of mounts taken out by umount(2) must be non-shifting and
non-revealing; the first constraint is what allows to reparent
any remaining mounts and the second is what prevents the exposure
of any concealed mountpoints.

propagate\_umount() takes the original set as an argument and tries to
extend that set.  The original set is a full subtree and its root is
unlocked; what matters is that it's closed and non-revealing.
Resulting set may not be closed; there might still be mounts outside
of that set, but only on top of stacks of root-overmounting elements
of set.  They can be reparented to the place where the bottom of
stack is attached to a mount that will survive.  NOTE: doing that
will violate a constraint on having no more than one mount with
the same parent/mountpoint pair; however, the caller (umount\_tree())
will immediately remedy that - it may keep unmounted element attached
to parent, but only if the parent itself is unmounted.  Since all
conflicts created by reparenting have common parent \*not\* in the
set and one side of the conflict (bottom of the stack of overmounts)
is in the set, it will be resolved.  However, we rely upon umount\_tree()
doing that pretty much immediately after the call of propagate\_umount().

Algorithm is based on two statements:

1) for any set S, there is a maximal non-shifting subset of S
   and it can be calculated in O(#S) time.
2) for any non-shifting set S, there is a maximal non-revealing
   subset of S.  That subset is also non-shifting and it can be calculated
   in O(#S) time.

## Finding candidates.

We are given a closed set U and we want to find all mounts that have
the same mountpoint as some mount m in U \*and\* whose parent receives
propagation from the parent of the same mount m.  Naive implementation
would be

```text
	S = {}
	for each m in U
		add m to S
		p = parent(m)
		for each q in Propagation(p) - {p}
			child = look_up(q, mountpoint(m))
			if child
				add child to S
```

but that can lead to excessive work - there might be propagation among the
subtrees of U, in which case we'd end up examining the same candidates
many times.  Since propagation is transitive, the same will happen to
everything downstream of that candidate and it's not hard to construct
cases where the approach above leads to the time quadratic by the actual
number of candidates.

Note that if we run into a candidate we'd already seen, it must've been
added on an earlier iteration of the outer loop - all additions made
during one iteration of the outer loop have different parents.  So
if we find a child already added to the set, we know that everything
in Propagation(parent(child)) with the same mountpoint has been already
added.

```text
	S = {}
	for each m in U
		if m in S
			continue
		add m to S
		p = parent(m)
		q = propagation_next(p, p)
		while q
			child = look_up(q, mountpoint(m))
			if child
				if child in S
					q = skip_them(q, p)
					continue;
				add child to S
			q = propagation_next(q, p)
```

where
skip\_them(q, p)

```text
	keep walking Propagation(p) from q until we find something
	not in Propagation(q)
```

would get rid of that problem, but we need a sane implementation of
skip\_them().  That's not hard to do - split propagation\_next() into
"down into mnt\_slave\_list" and "forward-and-up" parts, with the
skip\_them() being "repeat the forward-and-up part until we get NULL
or something that isn't a peer of the one we are skipping".

Note that there can be no absolute roots among the extra candidates -
they all come from mount lookups.  Absolute root among the original
set is \_currently\_ impossible, but it might be worth protecting
against.

## Maximal non-shifting subsets.

Let's call a mount m in a set S forbidden in that set if there is a
subtree mounted strictly inside m and containing mounts that do not
belong to S.

The set is non-shifting when none of its elements are forbidden in it.

If mount m is forbidden in a set S, it is forbidden in any subset S' it
belongs to.  In other words, it can't belong to any of the non-shifting
subsets of S.  If we had a way to find a forbidden mount or show that
there's none, we could use it to find the maximal non-shifting subset
simply by finding and removing them until none remain.

Suppose mount m is forbidden in S; then any mounts forbidden in S - {m}
must have been forbidden in S itself.  Indeed, since m has descendents
that do not belong to S, any subtree that fits into S will fit into
S - {m} as well.

So in principle we could go through elements of S, checking if they
are forbidden in S and removing the ones that are.  Removals will
not invalidate the checks done for earlier mounts - if they were not
forbidden at the time we checked, they won't become forbidden later.
It's too costly to be practical, but there is a similar approach that
is linear by size of S.

Let's say that mount x in a set S is forbidden by mount y, if

- both x and y belong to S.
- there is a chain of mounts starting at x and leaving S
  immediately after passing through y, with the first
  mountpoint strictly inside x.
  Note 1: x may be equal to y - that's the case when something not
  belonging to S is mounted strictly inside x.
  Note 2: if y does not belong to S, it can't forbid anything in S.
  Note 3: if y has no children outside of S, it can't forbid anything in S.

It's easy to show that mount x is forbidden in S if and only if x is
forbidden in S by some mount y.  And it's easy to find all mounts in S
forbidden by a given mount.

Consider the following operation:

```text
	Trim(S, m) = S - {x : x is forbidden by m in S}
```

Note that if m does not belong to S or has no children outside of S we
are guaranteed that Trim(S, m) is equal to S.

The following is true: if x is forbidden by y in Trim(S, m), it was
already forbidden by y in S.

Proof: Suppose x is forbidden by y in Trim(S, m).  Then there is a
chain of mounts (x\_0 = x, ..., x\_k = y, x\_{k+1} = r), such that x\_{k+1}
is the first element that doesn't belong to Trim(S, m) and the
mountpoint of x\_1 is strictly inside x.  If mount r belongs to S, it must
have been removed by Trim(S, m), i.e. it was forbidden in S by m.
Then there was a mount chain from r to some child of m that stayed in
S all the way until m, but that's impossible since x belongs to Trim(S, m)
and prepending (x\_0, ..., x\_k) to that chain demonstrates that x is also
forbidden in S by m, and thus can't belong to Trim(S, m).
Therefore r can not belong to S and our chain demonstrates that
x is forbidden by y in S.  QED.

Corollary: no mount is forbidden by m in Trim(S, m).  Indeed, any
such mount would have been forbidden by m in S and thus would have been
in the part of S removed in Trim(S, m).

Corollary: no mount is forbidden by m in Trim(Trim(S, m), n).  Indeed,
any such would have to have been forbidden by m in Trim(S, m), which
is impossible.

Corollary: after

```text
	S = Trim(S, x_1)
	S = Trim(S, x_2)
	...
	S = Trim(S, x_k)
```

no mount remaining in S will be forbidden by either of x\_1,...,x\_k.

The following will reduce S to its maximal non-shifting subset:

```text
	visited = {}
	while S contains elements not belonging to visited
		let m be an arbitrary such element of S
		S = Trim(S, m)
		add m to visited
```

S never grows, so the number of elements of S not belonging to visited
decreases at least by one on each iteration.  When the loop terminates,
all mounts remaining in S belong to visited.  It's easy to see that at
the beginning of each iteration no mount remaining in S will be forbidden
by any element of visited.  In other words, no mount remaining in S will
be forbidden, i.e. final value of S will be non-shifting.  It will be
the maximal non-shifting subset, since we were removing only forbidden
elements.

```text
	There are two difficulties in implementing the above in linear
```

time, both due to the fact that Trim() might need to remove more than one
element.  Naive implementation of Trim() is vulnerable to running into a
long chain of mounts, each mounted on top of parent's root.  Nothing in
that chain is forbidden, so nothing gets removed from it.  We need to
recognize such chains and avoid walking them again on subsequent calls of
Trim(), otherwise we will end up with worst-case time being quadratic by
the number of elements in S.  Another difficulty is in implementing the
outer loop - we need to iterate through all elements of a shrinking set.
That would be trivial if we never removed more than one element at a time
(linked list, with list\_for\_each\_entry\_safe for iterator), but we may
need to remove more than one entry, possibly including the ones we have
already visited.

```text
	Let's start with naive algorithm for Trim():
```

Trim\_one(m)

```text
	found = false
	for each n in children(m)
		if n not in S
			found = true
			if (mountpoint(n) != root(m))
				remove m from S
				break
	if found
		Trim_ancestors(m)
```

Trim\_ancestors(m)

```text
	for (; parent(m) in S; m = parent(m)) {
		if (mountpoint(m) != root(parent(m)))
			remove parent(m) from S
	}
```

If m belongs to S, Trim\_one(m) will replace S with Trim(S, m).
Proof:

```text
	Consider the chains excluding elements from Trim(S, m).  The last
```

two elements in such chain are m and some child of m that does not belong
to S.  If m has no such children, Trim(S, m) is equal to S.

```text
	m itself is removed if and only if the chain has exactly two
```

elements, i.e. when the last element does not overmount the root of m.
In other words, that happens when m has a child not in S that does not
overmount the root of m.

```text
	All other elements to remove will be ancestors of m, such that
```

the entire descent chain from them to m is contained in S.  Let
(x\_0, x\_1, ..., x\_k = m) be the longest such chain.  x\_i needs to be
removed if and only if x\_{i+1} does not overmount its root.  It's easy
to see that Trim\_ancestors(m) will iterate through that chain from
x\_k to x\_1 and that it will remove exactly the elements that need to be
removed.

```text
	Note that if the loop in Trim_ancestors() walks into an already
```

visited element, we are guaranteed that remaining iterations will see
only elements that had already been visited and remove none of them.
That's the weakness that makes it vulnerable to long chains of full
overmounts.

```text
	It's easy to deal with, if we can afford setting marks on
```

elements of S; we would mark all elements already visited by
Trim\_ancestors() and have it bail out as soon as it sees an already
marked element.

```text
	The problems with iterating through the set can be dealt with in
```

several ways, depending upon the representation we choose for our set.
One useful observation is that we are given a closed subset in S - the
original set passed to propagate\_umount().  Its elements can neither
forbid anything nor be forbidden by anything - all their descendents
belong to S, so they can not occur anywhere in any excluding chain.
In other words, the elements of that subset will remain in S until
the end and Trim\_one(S, m) is a no-op for all m from that subset.

```text
	That suggests keeping S as a disjoint union of a closed set U
```

('will be unmounted, no matter what') and the set of all elements of
S that do not belong to U.  That set ('candidates') is all we need
to iterate through.  Let's represent it as a subset in a cyclic list,
consisting of all list elements that are marked as candidates (initially -
all of them).  Then we could have Trim\_ancestors() only remove the mark,
leaving the elements on the list.  Then Trim\_one() would never remove
anything other than its argument from the containing list, allowing to
use list\_for\_each\_entry\_safe() as iterator.

```text
	Assuming that representation we get the following:
```

```text
	list_for_each_entry_safe(m, ..., Candidates, ...)
		Trim_one(m)
```

where
Trim\_one(m)

```text
	if (m is not marked as a candidate)
		strip the "seen by Trim_ancestors" mark from m
		remove m from the Candidates list
		return
```

```text
	remove_this = false
	found = false
	for each n in children(m)
		if n not in S
			found = true
			if (mountpoint(n) != root(m))
				remove_this = true
				break
	if found
		Trim_ancestors(m)
	if remove_this
		strip the "seen by Trim_ancestors" mark from m
		strip the "candidate" mark from m
		remove m from the Candidate list
```

Trim\_ancestors(m)

```text
	for (p = parent(m); p is marked as candidate ; m = p, p = parent(p)) {
		if m is marked as seen by Trim_ancestors
			return
		mark m as seen by Trim_ancestors
		if (mountpoint(m) != root(p))
			strip the "candidate" mark from p
	}
```

```text
	Terminating condition in the loop in Trim_ancestors() is correct,
```

since that loop will never run into p belonging to U - p is always
an ancestor of argument of Trim\_one() and since U is closed, the argument
of Trim\_one() would also have to belong to U.  But Trim\_one() is never
called for elements of U.  In other words, p belongs to S if and only
if it belongs to candidates.

```text
	Time complexity:
```

- we get no more than O(#S) calls of Trim\_one()
- the loop over children in Trim\_one() never looks at the same child
  twice through all the calls.
- iterations of that loop for children in S are no more than O(#S)
  in the worst case
- at most two children that are not elements of S are considered per
  call of Trim\_one().
- the loop in Trim\_ancestors() sets its mark once per iteration and
  no element of S has is set more than once.

```text
	In the end we may have some elements excluded from S by
```

Trim\_ancestors() still stuck on the list.  We could do a separate
loop removing them from the list (also no worse than O(#S) time),
but it's easier to leave that until the next phase - there we will
iterate through the candidates anyway.

```text
	The caller has already removed all elements of U from their parents'
```

lists of children, which means that checking if child belongs to S is
equivalent to checking if it's marked as a candidate; we'll never see
the elements of U in the loop over children in Trim\_one().

```text
	What's more, if we see that children(m) is empty and m is not
```

locked, we can immediately move m into the committed subset (remove
from the parent's list of children, etc.).  That's one fewer mount we'll
have to look into when we check the list of children of its parent \*and\*
when we get to building the non-revealing subset.

## Maximal non-revealing subsets

If S is not a non-revealing subset, there is a locked element x in S
such that parent of x is not in S.

Obviously, no non-revealing subset of S may contain x.  Removing such
elements one by one will obviously end with the maximal non-revealing
subset (possibly empty one).  Note that removal of an element will
require removal of all its locked children, etc.

If the set had been non-shifting, it will remain non-shifting after
such removals.
Proof: suppose S was non-shifting, x is a locked element of S, parent of x
is not in S and S - {x} is not non-shifting.  Then there is an element m
in S - {x} and a subtree mounted strictly inside m, such that m contains
an element not in S - {x}.  Since S is non-shifting, everything in
that subtree must belong to S.  But that means that this subtree must
contain x somewhere \*and\* that parent of x either belongs that subtree
or is equal to m.  Either way it must belong to S.  Contradiction.

// same representation as for finding maximal non-shifting subsets:
// S is a disjoint union of a non-revealing set U (the ones we are committed
// to unmount) and a set of candidates, represented as a subset of list
// elements that have "is a candidate" mark on them.
// Elements of U are removed from their parents' lists of children.
// In the end candidates becomes empty and maximal non-revealing non-shifting
// subset of S is now in U

```text
	while (Candidates list is non-empty)
		handle_locked(first(Candidates))
```

handle\_locked(m)

```text
	if m is not marked as a candidate
		strip the "seen by Trim_ancestors" mark from m
		remove m from the list
		return
	cutoff = m
	for (p = m; p in candidates; p = parent(p)) {
		strip the "seen by Trim_ancestors" mark from p
		strip the "candidate" mark from p
		remove p from the Candidates list
		if (!locked(p))
			cutoff = parent(p)
	}
	if p in U
		cutoff = p
	while m != cutoff
		remove m from children(parent(m))
		add m to U
		m = parent(m)
```

Let (x\_0, ..., x\_n = m) be the maximal chain of descent of m within S.

- If it contains some elements of U, let x\_k be the last one of those.
  Then union of U with {x\_{k+1}, ..., x\_n} is obviously non-revealing.
- otherwise if all its elements are locked, then none of {x\_0, ..., x\_n}
  may be elements of a non-revealing subset of S.
- otherwise let x\_k be the first unlocked element of the chain.  Then none
  of {x\_0, ..., x\_{k-1}} may be an element of a non-revealing subset of
  S and union of U and {x\_k, ..., x\_n} is non-revealing.

handle\_locked(m) finds which of these cases applies and adjusts Candidates
and U accordingly.  U remains non-revealing, union of Candidates and
U still contains any non-revealing subset of S and after the call of
handle\_locked(m) m is guaranteed to be not in Candidates list.  So having
it called for each element of S would suffice to empty Candidates,
leaving U the maximal non-revealing subset of S.

However, handle\_locked(m) is a no-op when m belongs to U, so it's enough
to have it called for elements of Candidates list until none remain.

Time complexity: number of calls of handle\_locked() is limited by
#Candidates, each iteration of the first loop in handle\_locked() removes
an element from the list, so their total number of executions is also
limited by #Candidates; number of iterations in the second loop is no
greater than the number of iterations of the first loop.

## Reparenting

After we'd calculated the final set, we still need to deal with
reparenting - if an element of the final set has a child not in it,
we need to reparent such child.

Such children can only be root-overmounting (otherwise the set wouldn't
be non-shifting) and their parents can not belong to the original set,
since the original is guaranteed to be closed.

## Putting all of that together

The plan is to

- find all candidates
- trim down to maximal non-shifting subset
- trim down to maximal non-revealing subset
- reparent anything that needs to be reparented
- return the resulting set to the caller

For the 2nd and 3rd steps we want to separate the set into growing
non-revealing subset, initially containing the original set ("U" in
terms of the pseudocode above) and everything we are still not sure about
("candidates").  It means that for the output of the 1st step we'd like
the extra candidates separated from the stuff already in the original set.
For the 4th step we would like the additions to U separate from the
original set.

So let's go for

- original set ("set").  Linkage via mnt\_list
- undecided candidates ("candidates").  Subset of a list,
  consisting of all its elements marked with a new flag (T\_UMOUNT\_CANDIDATE).
  Initially all elements of the list will be marked that way; in the
  end the list will become empty and no mounts will remain marked with
  that flag.
- Reuse T\_MARKED for "has been already seen by trim\_ancestors()".
- anything in U that hadn't been in the original set - elements of
  candidates will gradually be either discarded or moved there.  In other
  words, it's the candidates we have already decided to unmount.	Its role
  is reasonably close to the old "to\_umount", so let's use that name.
  Linkage via mnt\_list.

For gather\_candidates() we'll need to maintain both candidates (S -
set) and intersection of S with set.  Use T\_UMOUNT\_CANDIDATE for
all elements we encounter, putting the ones not already in the original
set into the list of candidates.  When we are done, strip that flag from
all elements of the original set.  That gives a cheap way to check
if element belongs to S (in gather\_candidates) and to candidates
itself (at later stages).  Call that predicate is\_candidate(); it would
be m-&gt;mnt\_t\_flags &amp; T\_UMOUNT\_CANDIDATE.

All elements of the original set are marked with MNT\_UMOUNT and we'll
need the same for elements added when joining the contents of to\_umount
to set in the end.  Let's set MNT\_UMOUNT at the time we add an element
to to\_umount; that's close to what the old 'umount\_one' is doing, so
let's keep that name.  It also gives us another predicate we need -
"belongs to union of set and to\_umount"; will\_be\_unmounted() for now.

Removals from the candidates list should strip both T\_MARKED and
T\_UMOUNT\_CANDIDATE; call it remove\_from\_candidates\_list().

---

# Overview

_Peios Kernel / Internals / NTFE_

> NTFE is the Peios packet engine — where it stands in the kernel, what it replaced, how its C glue and Rust core divide the work, and the terms this chapter uses.

<a id="trm-6-1"></a>

NTFE — the Network Traffic Filtering Engine — is the kernel's packet
filter. It executes the packet layers of PNP, the Peios Network Policy:
PNP is the policy language and its registry layout under
`Machine\System\Network`, and NTFE is one of the components that carry
it out (netd is another, for the interface layer). It stands at
the netfilter seats, judges every traversal against the policy it reads
from the LCS registry itself, and applies the result: a verdict on the
packet, side effects on the flow and machine, and an event for whoever
is watching. <a id="cite-ntfe-engine.judges-from-registry-policy-itself"></a> No userspace process is in the enforcement path; the
viewer daemon (pnpd) observes and authors, it never decides. <a id="cite-ntfe-engine.no-userspace-in-enforcement-path"></a>

<a id="trm-6-1-1"></a>

## What it replaced

Peios ships a clean slate below NTFE. The netfilter **hook framework**
and **conntrack** (built in, with events, zones and timeouts; helpers
off) are kept, as are `nf_defrag` and the `nf_reject` machinery NTFE uses
to phrase refusals. <a id="cite-ntfe-engine.keeps-hooks-conntrack-defrag-reject"></a> With helpers off nothing assigns a
helper to a flow (only a conntrack entry a privileged process creates
over ctnetlink, naming one, could carry it), so no flow is *expected*
by another: `ct->master` stays NULL, and the Flow layer's `Related`
fact ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)) is false on every flow the stack tracks. <a id="cite-ntfe-engine.helpers-off-related-never-true"></a> Everything that was a policy *frontend* is
configured out: nf_tables, the xtables family (`iptables`, `ip6tables`,
`ebtables`, `arptables`), ipset, NFQUEUE, NFLOG, the flow table offload,
bridge netfilter, the netfilter BPF link and IPVS. <a id="cite-ntfe-engine.policy-frontends-configured-out"></a> `NF_NAT` is built but
dormant. <a id="cite-ntfe-engine.nf-nat-built-but-dormant"></a> The kernel config gate (`peios/verify-config.sh`)
asserts both halves so a merge cannot quietly bring a frontend back. <a id="cite-ntfe-engine.config-gate-asserts-both-halves"></a>

One consequence is worth knowing: conntrack's hooks are demand-activated,
historically by a ct-using iptables rule. With no frontend left, NTFE pins
them itself at init (`nf_ct_netns_get(&init_net, NFPROTO_INET)`); without
that pin `nf_ct_get()` is NULL on every packet and the `FlowState` fact
reads `untracked` forever. <a id="cite-ntfe-engine.pins-conntrack-hooks-at-init"></a>

<a id="trm-6-1-2"></a>

## Two halves

The engine is split along the line that kernels are good at and pure
code is good at.

**`net/ntfe/` (C)** owns everything that touches the kernel: the hook
registrations and the dispatch law (`seats.c`), building the fact
snapshot from an `sk_buff` (`snapshot.c`), RCU publication of policy
generations (`policy.c`), walking the registry into the builder
(`ingest.c`), the three machinery stores — flow tags on a conntrack
extension (`tags.c`), counter tables (`counters.c`), report emission into
KMES (`report.c`) — the Flow layer's sentence cache and dispatch
(`flow.c`), the refusals a `REJECT` sends (`refuse.c`), and the verdict
event ring behind `/dev/peios-ntfe` (`events.c`). <a id="cite-ntfe-engine.c-glue-owns-kernel-facing-work"></a>

**`pnp-core` (Rust, `security/pkm/pnp_core`)** owns everything the policy
*means*: the action language, the fact vocabulary and operators,
registry-shaped ingestion and validation, the forest, and the evaluation
algorithm. <a id="cite-ntfe-engine.core-owns-policy-meaning"></a> It is `no_std`, allocates only through the fallible PKM
wrappers, and has no I/O. <a id="cite-ntfe-engine.core-no-std-fallible-alloc-no-io"></a> The same source compiles twice: under cargo,
where a test suite encodes every ratified law by name, and into the
kernel, compiled from `security/pkm/pnp_core` as modules of the
`security/pkm` Rust crate and reached over a C ABI (`security/pkm/kacs/ntfe_runtime.rs`,
the bridge). <a id="cite-ntfe-engine.core-compiles-for-cargo-and-kernel"></a> Nothing about a rule's semantics exists in C. <a id="cite-ntfe-engine.no-rule-semantics-in-c"></a>

The bridge is the only place the two meet. <a id="cite-ntfe-engine.bridge-is-only-meeting-point"></a> C hands it a snapshot and a
forest; it resolves the forest's machinery facts against the packet by
calling back into the stores, evaluates, and applies the effects — after
collation, so a `COUNT` lands after this packet's own reads and a
`REPORT` can carry the verdict. <a id="cite-ntfe-engine.effects-applied-after-collation"></a>

<a id="trm-6-1-3"></a>

## Terms

- **Traversal** — one packet passing one direction through the machine.
- **Seat** — a netfilter hook NTFE stands at: the device *ingress* and
  *egress* seats (per interface) and the two IP seats, *inbound*
  (`LOCAL_IN`) and *outbound* (`LOCAL_OUT`).
- **Layer** — one of the three rule forests, `RawPacket`, `Packet` and
  `Flow`, each a registry key under `Machine\System\Network\Rules`.
- **Flow** — what conntrack tracks: a tuple-identified, bidirectional
  exchange. The unit the Flow layer judges.
- **Sentence** — the Flow layer's cached verdict on a flow: verdict,
  generation, expiry, on the flow's conntrack extension.
- **Snapshot** — the immutable set of facts one traversal is judged
  against at its seat.
- **Generation** — one published policy. Advances on every successful
  ingestion; <a id="cite-ntfe-engine.generation-advances-per-ingestion"></a> 0 means nothing was ever ingested and every layer is
  permissive, loudly. <a id="cite-ntfe-engine.generation-zero-is-permissive"></a>
- **Forest** — a layer's rule trees plus the machinery names it mentions:
  the tags it reads or writes, the counter streams it writes, and the
  counter views it reads.
- **Effect** — a side effect an evaluation yields (`TAG`, `COUNT`,
  `REPORT`, a prompt), applied by the glue.
- **Confession** — a counter in the engine status for something the
  engine refused or could not do. Nothing in NTFE fails silently. <a id="cite-ntfe-engine.nothing-fails-silently"></a>
- **Owner** — the identity KACS stamps on an inet socket ([Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md#trm-3-12-2>)): the
  effective token and process facts at the last act that committed the
  socket to a role. What the Flow layer's `Local.*` facts are read from.
- **Endpoint kind** — what stands at a local end of a flow: `program`,
  `kernel`, `shared` or `none` ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)).

The chapter follows a packet: the seats it meets ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)), the snapshot
taken of it ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)), how the forest judges it ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)), where that forest
came from ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)), the stores its effects land in ([The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>)), the event that
records it ([The event stream](</kernel/internals/ntfe/event-ring-and-delivery.md#trm-6-7>)), what happens when it is the first packet of a flow
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), and who stands at its local end ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)). [NTFE ABI Reference](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>) is the generated
ABI of `/dev/peios-ntfe`; [NTFE ABI Notes](</kernel/userspace/native/ntfe/device-operations-and-errors.md#trm-6-b>) is what the ABI tables cannot say.

<a id="trm-6-b-8"></a>

## Build configuration

`CONFIG_PEIOS_NTFE` (bool) depends on `SECURITY_PKM`, `NETFILTER`,
`NETFILTER_INGRESS`, `NETFILTER_EGRESS` and `NF_CONNTRACK=y` — NTFE is built in and reads flow
facts on the packet path, so conntrack must be too. <a id="cite-ntfe-abi-notes.config-ntfe-dependencies"></a> `CONFIG_PEIOS_NTFE_KUNIT`
builds the kernel-resident tests (`pkm_kunit_ntfe`), defaulting to
`SECURITY_PKM_KUNIT`. <a id="cite-ntfe-abi-notes.config-kunit-default"></a> The production fragment (`build/config/pkm.fragment`)
enables NTFE and configures the nf_tables/xtables family out; <a id="cite-ntfe-abi-notes.production-fragment-ntfe-on-nftables-off"></a>
`peios/verify-config.sh` asserts both. <a id="cite-ntfe-abi-notes.verify-kernel-config-asserts-fragment"></a>

## Related explanations

- [Event records and status semantics](</kernel/userspace/native/ntfe/event-records-and-status-semantics.md>)
- [Device operations and errors](</kernel/userspace/native/ntfe/device-operations-and-errors.md>)

## Calling the subsystem

The [native NTFE interface reference](</kernel/userspace/native/ntfe/overview.md>) collects the caller contracts and generated ABI tables.

---

# Seats and dispatch

_Peios Kernel / Internals / NTFE_

> The netfilter hooks NTFE stands at, the dispatch law that gives every traversal exactly one proper seat per layer, and how verdicts — refusals included — are applied where they land.

<a id="trm-6-2"></a>

<a id="trm-6-2-1"></a>

## The seats

NTFE registers at four kinds of netfilter hook.

- **Device ingress** (`NF_NETDEV_INGRESS`) and **device egress**
  (`NF_NETDEV_EGRESS`), per interface. A netdevice notifier registers
  both on every `NETDEV_REGISTER` in `init_net` and unregisters them on
  `NETDEV_UNREGISTER`; <a id="cite-ntfe-seat.device-seats-follow-netdev-notifier"></a> because `register_netdevice_notifier()` replays
  `NETDEV_REGISTER` for devices that already exist, boot-time interfaces
  get their seats too. <a id="cite-ntfe-seat.boot-time-interfaces-get-seats"></a> These seats see frames — the Ethernet header is
  present, VLAN tags are visible, and on the inbound side conntrack has
  not yet run. <a id="cite-ntfe-seat.device-seats-see-frames"></a>
- **IP inbound** (`NF_INET_LOCAL_IN`, IPv4 and IPv6) at priority
  `NF_IP_PRI_FILTER`. Conntrack and defragmentation have run; the packet
  is whole and its flow is classified — and still unconfirmed, since
  conntrack confirms at the end of this hook. <a id="cite-ntfe-seat.ip-inbound-at-local-in-filter-priority"></a>
- **IP outbound** (`NF_INET_LOCAL_OUT`, IPv4 and IPv6) at filter
  priority. The first point after conntrack has classified a locally
  generated packet's flow; the sending socket is attached; the entry is
  unconfirmed until `POST_ROUTING`. <a id="cite-ntfe-seat.ip-outbound-at-local-out-filter-priority"></a>

Only `init_net` is instrumented: Peios has no container or network
namespace story yet, and the notifier ignores devices in other
namespaces. <a id="cite-ntfe-seat.only-init-net-instrumented"></a> Of netfilter's other hooks, `FORWARD` is empty on a host that
does not forward, and `PRE_ROUTING` and `POST_ROUTING` see nothing the IP
seats do not, save NAT.

<a id="trm-6-2-2"></a>

## The dispatch law

The ratified law, with the Flow layer's clause:

> RawPacket matches all traffic at the device seats, unconditionally. <a id="cite-ntfe-seat.rawpacket-at-device-seats-unconditionally"></a>
> The Packet layer judges every traversal exactly once, at its proper
> seat — inbound IP at the IP hook, everything outbound at egress — <a id="cite-ntfe-seat.packet-judged-exactly-once-at-proper-seat"></a>
> falling back to the ingress seat iff the traversal will never reach its
> proper seat. <a id="cite-ntfe-seat.packet-falls-back-to-ingress-iff-unreachable"></a> The Flow layer judges every tracked flow once per local
> endpoint, at the IP seats, <a id="cite-ntfe-seat.flow-judged-once-per-local-endpoint"></a> and its sentence answers for every later
> packet of the flow. <a id="cite-ntfe-seat.sentence-answers-for-later-packets"></a>

"Will never reach its proper seat" is decidable at ingress from two
facts, and `peios_ntfe_traversal_reaches_ip_seat()` decides it: the
ethertype (only `ETH_P_IP` and `ETH_P_IPV6` cross the IP hooks) and the
device's disposition (`netif_is_bridge_port()` — a frame on a
bridge-enslaved port is switched at L2 and never enters this device's IP
stack; a copy delivered to the bridge device itself is a separate
traversal on that device, judged there). <a id="cite-ntfe-seat.reaches-ip-seat-from-ethertype-and-bridge-port"></a>

So at each seat the hook builds one snapshot and judges an ordered list
of layers:

| Seat | Layers, in traversal order |
|---|---|
| Ingress, IP frame on a plain port | `RawPacket` only (the Packet layer is *deferred* to `LOCAL_IN`) <a id="cite-ntfe-seat.ingress-ip-plain-port-rawpacket-only"></a> |
| Ingress, non-IP frame or bridge port | `RawPacket`, then `Packet` (the *fallback* judgment) <a id="cite-ntfe-seat.ingress-non-ip-or-bridge-port-rawpacket-then-packet"></a> |
| `LOCAL_IN` | `Packet`, then the flow's sentence or `Flow` <a id="cite-ntfe-seat.local-in-packet-then-flow"></a> |
| `LOCAL_OUT` | the flow's sentence or `Flow` <a id="cite-ntfe-seat.local-out-flow-only"></a> |
| Egress | `Packet`, then `RawPacket` <a id="cite-ntfe-seat.egress-packet-then-rawpacket"></a> |

Traversal order is wire order: `RawPacket` is wire-proximate, so it is
first in and last out; `Flow` is innermost, last in and first out. <a id="cite-ntfe-seat.traversal-order-is-wire-order"></a> Each
per-packet layer is evaluated once per traversal, <a id="cite-ntfe-seat.per-packet-layer-once-per-traversal"></a> and the first non-`PASS`
verdict ends the traversal. <a id="cite-ntfe-seat.first-non-pass-ends-traversal"></a> A layer with no published forest is
*permissive* and counted as such — at generation 0 that is every layer. <a id="cite-ntfe-seat.unpublished-layer-permissive-and-counted"></a>

At the IP seats, a packet goes on to the flow dispatch ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — at
`LOCAL_IN` once the Packet layer has passed it, at `LOCAL_OUT` before
any Packet judgment, since the Packet layer judges outbound traffic at
egress, after it: an untracked packet has no flow to judge and is
accepted, so inbound the Packet verdict stands and outbound egress
judges it next; <a id="cite-ntfe-seat.untracked-packet-keeps-packet-verdict"></a> a tracked packet with a current sentence gets that
sentence, <a id="cite-ntfe-seat.tracked-packet-gets-current-sentence"></a> and one without is evaluated by the Flow forest and sentenced. <a id="cite-ntfe-seat.unsentenced-flow-evaluated-and-sentenced"></a>

<a id="trm-6-2-3"></a>

## Applying a verdict

`PASS` continues to the next layer, then `NF_ACCEPT`. <a id="cite-ntfe-seat.pass-continues-then-accept"></a> `DROP` is
`NF_DROP`. <a id="cite-ntfe-seat.drop-is-nf-drop"></a> `REJECT` is `NF_DROP` plus a refusal, phrased by the kind the
rule chose and the packet's protocol: <a id="cite-ntfe-seat.reject-is-drop-plus-refusal"></a>

| Kind | IPv4 | IPv6 |
|---|---|---|
| `Refused` (default) | TCP: RST; else ICMP port-unreachable | TCP: RST; else ICMPv6 port-unreachable <a id="cite-ntfe-seat.refused-kind-rst-or-port-unreachable"></a> |
| `Prohibited` | ICMP `ICMP_PKT_FILTERED` (type 3, code 13) | ICMPv6 `ICMPV6_ADM_PROHIBITED` (type 1, code 1) <a id="cite-ntfe-seat.prohibited-kind-admin-filtered"></a> |

Every seat can refuse IP traffic — the ingress seat only on an Ethernet
device. <a id="cite-ntfe-seat.every-seat-can-refuse-ip"></a> `refuse.c` builds the answer with the
kernel's frame-less reject builders (`nf_reject_skb_v4_tcp_reset()`,
`nf_reject_skb_v4_unreach()` and the v6 pair — the ones nftables' netdev
reject uses), attaches the flow to it (`nf_ct_attach()`, so conntrack
files it as the reply it claims to be), marks it, and delivers it: <a id="cite-ntfe-seat.refusal-attached-to-flow-and-marked"></a>

- from the **ingress** seat, to the peer on the wire — `dev_hard_header()`
  with the offending frame's MACs swapped, then `dev_queue_xmit()`; <a id="cite-ntfe-seat.ingress-refusal-sent-to-wire-peer"></a>
  that needs an Ethernet device (`ARPHRD_ETHER`) and a link header to
  swap, so at the ingress seat of any other device — the loopback
  device, a tunnel — a `REJECT` always degrades (below); <a id="cite-ntfe-seat.ingress-refusal-needs-ethernet"></a>
- from **every other seat**, to ourselves — `skb_dst_set_noref()` from
  the offending packet's route, `ip_route_me_harder()` (or the v6
  helper), then `ip_local_out()`. <a id="cite-ntfe-seat.non-ingress-refusal-routed-through-local-out"></a> Inbound, that routes the answer out to
  the peer with our address as its source; <a id="cite-ntfe-seat.inbound-refusal-routed-to-peer"></a> to a link-local address it is
  routed on the device the offending packet arrived on, without the
  helper, which would scope the lookup to the loopback device the local
  delivery route names; <a id="cite-ntfe-seat.inbound-link-local-answer-routed-on-ingress"></a> outbound, the answer is the
  peer's, addressed to us, so the route lands on the loopback device and
  the stack's own RST and ICMP-error handlers fail the local socket at
  once, with the error the kernel maps the answer to: `ECONNREFUSED`
  for a reset or a port unreachable, `EHOSTUNREACH` for IPv4's
  admin-filtered, `EACCES` for IPv6's admin-prohibited. TCP takes an
  ICMP error that reaches a socket its owner is holding as a soft error,
  and a refused SYN is refused inside `connect()`, which holds it: so an
  ICMP answer to a held TCP socket is sent a tick later (one jiffy, on
  the system workqueue), once the call has let go. A reset needs no
  wait: TCP queues it on the socket's backlog. <a id="cite-ntfe-seat.outbound-refusal-fails-local-socket-at-once"></a> The loopback device retains
  the route the packet was sent with, so the foreign source address
  never meets source validation. <a id="cite-ntfe-seat.outbound-refusal-skips-source-validation"></a>

The builders read the offending packet from `skb->data` as though it
pointed at the network header, as it does at the IP hooks; at the
egress seat it points at the link header the device has pushed, so
`refuse.c` pulls the packet to its network header for the build and
pushes it back after. <a id="cite-ntfe-seat.refusal-built-from-network-header"></a>

When the refused packet belongs to an **established TCP** flow, the far
end is torn down too: `peios_ntfe_teardown_build()` turns the refused
packet itself into a reset — same addresses, ports, sequence and
acknowledgement numbers, `RST` set, no data — marks it, and sends it
where the packet was going by the same routed path (outbound, to the
peer on the wire; inbound, to our own socket over loopback). <a id="cite-ntfe-seat.established-tcp-reject-tears-down-far-end"></a> The refused
end gets the kind's story; the far end gets the only story TCP listens
to mid-connection. Counted in `teardowns_emitted`. <a id="cite-ntfe-seat.teardowns-counted"></a> New flows and UDP
have no far end; <a id="cite-ntfe-seat.no-teardown-for-new-flow-or-udp"></a> a reset is never answered with a reset; <a id="cite-ntfe-seat.no-teardown-of-a-reset"></a> the ingress
seat has no flow facts and never tears down. <a id="cite-ntfe-seat.ingress-never-tears-down"></a>

The answer is not sent, and the `REJECT` **degrades to `DROP`** (counted
in `reject_degraded`, flagged `REJECT_DEGRADED` in the event, the kind
still named), when there is nothing to send: a non-IP frame, a broadcast
or multicast destination, an ingress frame on a non-Ethernet device, a
builder that declines (a non-first fragment, which has no transport
header to answer from; a failed checksum; a refusal of a refusal), a
packet with no route to reason from, or an allocation failure. <a id="cite-ntfe-seat.reject-degrades-to-drop-when-nothing-to-send"></a> A
*first* fragment passes the builders' fragment check and is declined by
their checksum check instead — its transport checksum covers a payload
it carries only part of — so one whose checksum the builder does not
verify (one the stack has already marked as checked, or a protocol the builders
skip: UDP with a zero checksum, SCTP, ESP, AH, GRE, UDP-Lite) is
answered. Fragments meet the builders only at the device seats:
`LOCAL_IN` sees reassembled packets. <a id="cite-ntfe-seat.first-fragment-declined-by-checksum"></a> Refusals sent are counted in
`refusals_emitted`. <a id="cite-ntfe-seat.refusals-sent-counted"></a>

<a id="trm-6-2-4"></a>

## The refusal law

**NTFE does not judge its own refusals.** The answer `refuse.c` builds
carries `skb->ntfe_refusal`, a bit the `ntfe-refusal-bit` patch adds to
`struct sk_buff` inside its `headers` group (so clones and copies keep
it); <a id="cite-ntfe-seat.refusal-bit-survives-clone-and-copy"></a> every hook checks it first and returns `NF_ACCEPT` without a
snapshot, an evaluation or an event, counting `refusals_bypassed`. <a id="cite-ntfe-seat.refusals-bypass-every-hook"></a>
Refusals are verdict machinery, not traffic: without the bit, an inbound
`REJECT`'s RST would cross the egress seat and could be dropped — and
attributed — by an outbound rule, and an outbound `REJECT`'s forged peer
answer would be judged as inbound traffic on its way to the socket.

<a id="trm-6-2-5"></a>

## Failing closed

Evaluation can fail: the core allocates `GFP_ATOMIC` during a walk and
an allocation can be refused. The hook then drops the packet, counts
`fail_closed`, and emits an event attributed to `fail-closed` with the
`FAIL_CLOSED` flag. <a id="cite-ntfe-seat.evaluation-failure-drops-counts-and-reports"></a> Totality does not take "no answer" for an answer.

A snapshot that cannot be built — a frame too mangled to describe — is
counted (`parse_errors`) and judged on its seat facts alone; the
absent-fact law does the rest. <a id="cite-ntfe-seat.unbuildable-snapshot-judged-on-seat-facts"></a>

---

# The snapshot

_Peios Kernel / Internals / NTFE_

> How one traversal's facts are extracted from the sk_buff into the fixed-size seat snapshot, what the validity bits mean, and what crosses into the Rust core.

<a id="trm-6-3"></a>

Every judgment reads a **snapshot**: a fixed-size, stack-allocated
`struct peios_ntfe_snapshot` built once per seat by
`peios_ntfe_snapshot_from_skb()` and never mutated during evaluation. <a id="cite-ntfe-snapshot.built-once-per-seat-never-mutated"></a>
That immutability is a ratified law, not an implementation detail —
nothing a rule writes is visible to the same evaluation's matching, so
temporal feedback (the next packet sees it) is the only feedback there
is. <a id="cite-ntfe-snapshot.writes-invisible-to-same-evaluation"></a>

<a id="trm-6-3-1"></a>

## Validity bits

Many facts have meaningful zero values (port 0, TTL 0, VLAN 0), so
presence is carried separately in `has`, a bitmask of `PEIOS_NTFE_HAS_*`:
ethertype, MACs, source MAC alone, VLAN, TTL, DSCP, fragment, ports, TCP
flags, ICMP, time, the flow's start time, and the network context. <a id="cite-ntfe-snapshot.has-bitmask-carries-presence"></a> Address facts use
`addr_family` (0, 4 or 6) as their validity; <a id="cite-ntfe-snapshot.addr-family-is-address-validity"></a> the protocol is valid iff a
family is. <a id="cite-ntfe-snapshot.protocol-valid-iff-family"></a> Flow state uses its own `ABSENT` value; <a id="cite-ntfe-snapshot.flow-state-has-own-absent-value"></a> `flow_related` is
valid iff `flow` is. <a id="cite-ntfe-snapshot.flow-related-valid-iff-flow"></a> The bridge turns each clear bit into `None` on the
Rust side, <a id="cite-ntfe-snapshot.clear-bit-lifts-to-none"></a> and the absent-fact law makes every condition over a `None`
false. <a id="cite-ntfe-snapshot.condition-over-none-is-false"></a>

<a id="trm-6-3-2"></a>

## Extraction

Seat facts first: seat, direction, interface (`ifindex` and name), the
network context of that interface (below), whether the device is the
loopback (`IFF_LOOPBACK` — the flow dispatch's "two endpoints" test), <a id="cite-ntfe-snapshot.loopback-flag-from-iff-loopback"></a>
the packet length as the stack sees it
(`skb->len` — not the wire length), <a id="cite-ntfe-snapshot.length-is-skb-len"></a> and the wall clock
(`ktime_get_real_seconds()` through `time64_to_tm()`, UTC, with
`tm_wday` re-based so the `DayOfWeek` fact is ISO: 1 = Monday .. 7 =
Sunday), <a id="cite-ntfe-snapshot.clock-is-utc-with-iso-day-of-week"></a> kept alongside as epoch seconds (`t_secs`) for the time-flip
arithmetic ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)) and the sentence expiry check ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). <a id="cite-ntfe-snapshot.clock-kept-as-epoch-seconds"></a>

Then the frame: the ethertype from `skb->protocol`. <a id="cite-ntfe-snapshot.ethertype-from-skb-protocol"></a> The VLAN id is the
frame's tag if `skb_vlan_tag_present()`, else the device's if
`is_vlan_dev()` — the VLAN is a fact of the frame at the device seats
and of the device at the IP seats, where inbound the VLAN code has
already stripped the tag and re-parented the packet onto the VLAN
device, and outbound the tag is pushed only when that device transmits. <a id="cite-ntfe-snapshot.vlan-from-frame-tag-else-device"></a>
(Before the Flow slice the IP seats read the stripped tag and `Vlan` was
absent on VLAN interfaces there.) The MAC pair if the MAC header is set
and the device is `ARPHRD_ETHER`; <a id="cite-ntfe-snapshot.mac-pair-on-ethernet-with-mac-header"></a> failing that, at an IP seat on an
Ethernet device — a locally generated packet with no link header yet —
the source alone, from the device's own address (`HAS_SRC_MAC`): present
so every flow carries the same fact set, and not useful. <a id="cite-ntfe-snapshot.headerless-ip-seat-gets-device-source-mac"></a> The destination
is unknown until neighbour resolution, after the seat: absent. <a id="cite-ntfe-snapshot.headerless-ip-seat-dst-mac-absent"></a>

Then IP, from `skb_network_offset()`:

- **IPv4** — addresses, TTL, DSCP (`tos >> 2`), the fragment flag (`IP_MF`
  set or a non-zero fragment offset), the protocol, and the L4 facts
  from `ihl * 4` on. <a id="cite-ntfe-snapshot.ipv4-facts"></a> A *non-first* fragment (non-zero offset) has no
  L4 facts — its payload begins mid-datagram — though it still reads
  the protocol its header names. <a id="cite-ntfe-snapshot.ipv4-non-first-fragment-has-no-l4"></a>
- **IPv6** — addresses, hop limit, DSCP from the traffic class, and a
  bounded walk (eight hops) of the extension-header chain: hop-by-hop,
  routing and destination options are skipped by `(hdrlen + 1) * 8`; <a id="cite-ntfe-snapshot.ipv6-extension-walk-bounded-eight-hops"></a> a
  fragment header sets the fragment fact, <a id="cite-ntfe-snapshot.ipv6-fragment-header-sets-fragment"></a> and a *non-first* fragment
  ends the walk with no L4 facts (there are none to read). <a id="cite-ntfe-snapshot.ipv6-non-first-fragment-has-no-l4"></a> The protocol
  fact is the header the walk stops at — so an MLD report behind a
  hop-by-hop header reads `Protocol = icmpv6`, as a rule would expect.
  Every way out of the walk names one: a non-first fragment reads the
  protocol its fragment header names, as a later IPv4 fragment reads
  its own; an extension header too short to read is itself the
  protocol; and after eight hops the next header is the protocol, with
  L4 facts if it is not another extension header. <a id="cite-ntfe-snapshot.ipv6-protocol-is-walk-terminus"></a>

Then L4, by protocol: ports for TCP, UDP and SCTP; <a id="cite-ntfe-snapshot.ports-for-tcp-udp-sctp"></a> the flag byte for TCP
(`TcpFlags` is the TCP header's byte at offset 13, `FIN` in bit 0
through `CWR` in bit 7, the same encoding `tcp_flag_byte()` uses); <a id="cite-ntfe-snapshot.tcp-flags-encoding"></a> type and code for ICMP and
ICMPv6. <a id="cite-ntfe-snapshot.icmp-type-and-code"></a> Every header read goes through `skb_header_pointer()`, so a
packet whose headers are paged or truncated yields absent facts rather
than a fault. <a id="cite-ntfe-snapshot.truncated-headers-yield-absent-facts"></a>

<a id="trm-6-3-3"></a>

## Flow state and the flow

At the ingress seat conntrack has not run and the flow state is
`ABSENT`; <a id="cite-ntfe-snapshot.ingress-flow-state-absent"></a> at `LOCAL_IN`, `LOCAL_OUT` and egress, `nf_ct_get()` gives the
entry and `ctinfo` maps to the fact: `IP_CT_ESTABLISHED` and its reply →
`established`; `IP_CT_RELATED` and reply → `related`; `IP_CT_NEW` →
`new`; anything else, or no entry at all, → `untracked`. <a id="cite-ntfe-snapshot.ctinfo-maps-to-flow-state"></a> The `invalid`
value is reserved: distinguishing an incoherent packet needs conntrack's
own verdict, which this seat does not receive. <a id="cite-ntfe-snapshot.invalid-flow-state-reserved"></a>

The snapshot also carries `flow`: the `struct nf_conn *` itself (never a
template), or NULL. <a id="cite-ntfe-snapshot.flow-is-conn-never-template"></a> This is the tag store's and the sentence's scope —
`TAG` writes land on that entry's extension, tag reads come from it, and
the Flow layer's verdict is cached there. <a id="cite-ntfe-snapshot.flow-scopes-tags-and-sentence"></a> It is the one pointer in the
snapshot that outlives the extraction, and it is valid because the skb
holds a reference to the entry for the duration of the hook. <a id="cite-ntfe-snapshot.flow-pointer-valid-for-hook"></a>

With the flow come two facts that exist only on a flow: `flow_related`
(`ct->master != NULL` — the flow was expected by another) <a id="cite-ntfe-snapshot.flow-related-is-ct-master-set"></a> and the
flow's start time, read from the extension's `start_secs` (stamped when
conntrack created the entry) through the same `time64_to_tm()` lowering
as the clock, into the `s_*` fields (`HAS_START`). <a id="cite-ntfe-snapshot.flow-start-from-extension-start-secs"></a> These are the Flow
layer's `Related` and `Start.*` facts. `flow_reply` says whether this
packet travels in the flow's reply direction — the Flow layer's view
builder ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) uses it to turn the packet's tuple back into the flow's. <a id="cite-ntfe-snapshot.flow-reply-marks-reply-direction"></a>

<a id="trm-6-3-4"></a>

## What the core sees

`NtfeSnapshotC` in `security/pkm/kacs/ntfe_runtime.rs` mirrors the C struct field for
field (`#[repr(C)]`; keep them in lockstep). <a id="cite-ntfe-snapshot.rust-mirror-matches-c-struct"></a> `snapshot_from_c()` lifts
it into the core's `Snapshot` — an `Option` per fact — and the bridge
then fills in the two machinery fact tables: `tags`, as `(name hash,
value)` pairs for every tag name the forest can read that the flow
carries, and `counter_views`, as `(view index, value)` for every view the
forest reads that the store can answer for this packet. <a id="cite-ntfe-snapshot.bridge-fills-tags-and-counter-views"></a> Both are
resolved *before* evaluation, against the forest being evaluated, which
is why the forest carries its name sets ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.machinery-facts-resolved-before-evaluation"></a>

Three visibility laws are enforced here, and again in the core, which
builds a condition over a fact its layer never has never to hold
([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)): a
`RawPacket` forest is given no tags whatever the flow says (tags flow
upward only, and RawPacket is the lowest layer; `Packet` and `Flow`
forests read them); <a id="cite-ntfe-snapshot.rawpacket-forest-gets-no-tags"></a> an ingress snapshot has no flow, so no tags exist to
give; <a id="cite-ntfe-snapshot.ingress-snapshot-has-no-tags"></a> and the flow-only facts (`Related`, `Start.*`, and the identity
facts) are given to a `Flow` forest alone — everywhere else they are
absent by law, exactly as ingestion's lint says ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.flow-only-facts-for-flow-forest-alone"></a> The clock is
given to every layer, and so is the trace of consulted time conditions
([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)); <a id="cite-ntfe-snapshot.clock-and-time-trace-given-to-every-layer"></a> only the Flow seat acts on it. <a id="cite-ntfe-snapshot.only-flow-seat-acts-on-time-trace"></a>

<a id="trm-6-3-5"></a>

## The network context

Three string fields are not read from the packet either:
`network_id`, `network_name` and `network_trust`, the `Network.*` facts.
`peios_ntfe_context_fill()` (`context.c`) looks the device's name up in
the active context table — the kernel's reading of netd's inventory,
one entry per interface standing on an identified network, built by
ingestion ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)) and published under RCU — and copies the entry's three
strings in, setting `HAS_NETWORK`. <a id="cite-ntfe-snapshot.context-filled-from-active-table"></a> The bridge lifts the id whenever the
bit is set, <a id="cite-ntfe-snapshot.network-id-lifted-when-bit-set"></a> and the name and trust only when non-empty (a record the
operator has not labelled). <a id="cite-ntfe-snapshot.empty-network-name-and-trust-absent"></a> No entry, no bit: an interface no network
has been identified on carries no context, and every condition over the
three facts is false there. <a id="cite-ntfe-snapshot.no-context-entry-no-network-facts"></a> The strings are bounded (40, 64 and 32
bytes with their NUL, `PEIOS_NTFE_NETWORK_*_LEN`); <a id="cite-ntfe-snapshot.network-strings-bounded"></a> a longer registry value — a
record's `Name` or `Trust`, or the `Network` an interface's `Status`
names — is truncated at ingestion and the truncation logged once. <a id="cite-ntfe-snapshot.long-network-value-truncated-and-logged-once"></a>
The id of a record is its key *name* under `Networks\`, not a value,
and is not truncated: a name of 40 bytes or more is ignored, record and
all ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-snapshot.overlong-network-id-name-ignored"></a>

The fields are the three `Network.*` facts the interface layer — the
fourth layer, which netd builds and judges in userspace — conditions on
beside its own (see [the interface layer](https://learn.peios.org/peios/reference/netd/the-interface-layer/building-a-generation/)):
netd fills them from the interface record when it judges an interface,
the kernel from the table when it judges a packet, so
`Network.Trust.Equal` reads the same record in either layer. <a id="cite-ntfe-snapshot.network-facts-match-interface-layer"></a>

Flow refreshes these facts on a cache miss after capturing its cache
invalidation generation ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), because this packet snapshot can predate
a context publication. Packet and RawPacket continue to use their
traversal snapshot; their verdicts are not retained as Flow sentences.

<a id="trm-6-3-6"></a>

## The identity fields

The snapshot's last fields are not extracted from the packet at all.
The Flow layer's view builder ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) sets them from the flow's
extension: for the local end, and on loopback for the other end, the
kind (`program`, `kernel`, `shared`, `none`), the process GUID, pid and
comm, and a *borrowed* pointer to the KACS token the socket was stamped
with — the extension holds the reference for the flow's life, so the
pointer is valid for the hook. <a id="cite-ntfe-snapshot.identity-fields-set-from-flow-extension"></a> The bridge lifts a program end into a
`Principal` the core's `Local.*` and `Remote.*` conditions question
([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)); <a id="cite-ntfe-snapshot.program-end-lifts-to-principal"></a> every other snapshot leaves the fields zero, which lifts to
absent. <a id="cite-ntfe-snapshot.identity-fields-zero-elsewhere-lift-absent"></a>

---

# Evaluation

_Peios Kernel / Internals / NTFE_

> The pnp-core algorithm — trigger set, abstention and speakers, collation, the backstop — and how the bridge carries a snapshot in and a verdict plus applied effects out.

<a id="trm-6-4"></a>

Evaluation is `pnp_core::eval::evaluate(forest, snapshot, ctx)`: pure,
allocation-fallible, and the same code under cargo and in the kernel. <a id="cite-ntfe-eval.evaluate-is-pure-and-shared"></a>
Its steps are the ratified design's six, in order. <a id="cite-ntfe-eval.six-steps-in-order"></a>

<a id="trm-6-4-1"></a>

## 1. Matching

A rule matches iff it is enabled and every one of its conditions holds
against the snapshot. <a id="cite-ntfe-eval.rule-matches-iff-enabled-and-all-conditions-hold"></a> Conditions are a conjunction; a value written as a
list is a disjunction *within* that one field. <a id="cite-ntfe-eval.list-value-is-disjunction-within-field"></a> A disabled rule never
matches, so its subtree is unreachable. <a id="cite-ntfe-eval.disabled-rule-subtree-unreachable"></a>

Conditions are evaluated in the order ingestion stored them, which puts
live-time conditions (`Time.*`) **last**, <a id="cite-ntfe-eval.live-time-conditions-evaluated-last"></a> and the conjunction stops at
the first false one. <a id="cite-ntfe-eval.conjunction-stops-at-first-false"></a> Every live-time condition actually reached — true
or false — is *consulted*, and `Rule::matches_traced()` records into a
`MatchTrace` the moment it would next flip (`Condition::next_flip()`): <a id="cite-ntfe-eval.reached-clock-conditions-record-next-flip"></a>
for hour, minute, second and day-of-week, the value sequence is scanned
one cycle ahead with the condition's own operator, so `Time.Hour.Equal
9-17` at 10:30 flips at 18:00 and `Time.Hour.LessThan 24` never does; <a id="cite-ntfe-eval.clock-flip-scans-one-cycle-ahead"></a>
day-of-month, month and year answer "next midnight", since exact flips
need calendar arithmetic nobody has asked for. <a id="cite-ntfe-eval.calendar-fields-flip-at-next-midnight"></a> A false condition is
consulted too: a higher-priority rule that missed only on the clock may
match later. <a id="cite-ntfe-eval.false-clock-condition-is-consulted"></a> A rule whose address or port conditions fail first never
consults its clock and contributes nothing. <a id="cite-ntfe-eval.unreached-clock-condition-not-consulted"></a> The earliest consulted flip
is the evaluation's `expires_at` — the Flow layer's sentence expiry
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)); <a id="cite-ntfe-eval.expires-at-is-earliest-consulted-flip"></a> the per-packet layers compute it and ignore it. <a id="cite-ntfe-eval.per-packet-layers-ignore-expires-at"></a>

<a id="trm-6-4-2"></a>

## 2. The trigger set

The walk descends each tree from its root. A node **triggers** iff it
matches and none of its children match: a matching child shadows its
parent. <a id="cite-ntfe-eval.matching-child-shadows-its-parent"></a> Shadowing exists only within a lineage — two trees never shadow
each other, and their order in the forest carries no meaning. <a id="cite-ntfe-eval.trees-never-shadow-each-other"></a> The walk
returns "matched" to the parent so the parent knows it was shadowed. <a id="cite-ntfe-eval.walk-reports-match-to-parent"></a>

<a id="trm-6-4-3"></a>

## 3. Resolving a triggered rule

Every triggered rule's action list is resolved once. <a id="cite-ntfe-eval.triggered-rule-resolved-once"></a> Verdict actions fold
to the strictest listed; <a id="cite-ntfe-eval.verdict-actions-fold-to-strictest"></a> `TAG` and `COUNT` push effects; <a id="cite-ntfe-eval.tag-and-count-push-effects"></a> `REPORT` folds
to the highest level listed and pushes one effect if that level is at
or above `CurrentReportingLevel` (`level >= CurrentReportingLevel`; one
report per rule per evaluation); <a id="cite-ntfe-eval.report-folds-to-highest-level-and-gates"></a> `PROMPT`
pushes a prompt-issued effect and, with no handler transport in this
release, resolves its fallback in place <a id="cite-ntfe-eval.prompt-resolves-fallback-in-place"></a> (nesting bounded by
`MAX_PROMPT_CHAIN`, 4). <a id="cite-ntfe-eval.prompt-chain-bounded-at-four"></a> Side effects always execute — they are pushed
before anyone knows whether the rule's verdict will win. <a id="cite-ntfe-eval.side-effects-execute-regardless-of-verdict"></a>

<a id="trm-6-4-4"></a>

## 4. Abstention

A triggered rule that yields no verdict abstains. The walk then goes up
the rule's own parentage — the chain it descended by — to the nearest
ancestor whose actions contain a *direct* verdict (a top-level `PASS`,
`DROP` or `REJECT`; a verdict inside a `PROMPT` fallback does not count), <a id="cite-ntfe-eval.prompt-fallback-verdict-is-not-direct"></a>
and that ancestor **speaks for the region**: its full action list
resolves, once. <a id="cite-ntfe-eval.abstainer-climbs-to-nearest-verdict-ancestor"></a> A speaker reached by several abstaining descendants in
one evaluation executes only the first time (`spoken` tracks resolved
speakers by identity). <a id="cite-ntfe-eval.speaker-executes-once-per-evaluation"></a> Intermediate abstaining ancestors execute
nothing. <a id="cite-ntfe-eval.intermediate-abstainers-execute-nothing"></a> If no ancestor bears a verdict, the branch contributes nothing
and other trees or the backstop answer. <a id="cite-ntfe-eval.verdictless-branch-contributes-nothing"></a>

The attribution of a speaker's verdict is the speaker's path, not the
abstaining descendant's. <a id="cite-ntfe-eval.speaker-verdict-attributed-to-speaker"></a>

<a id="trm-6-4-5"></a>

## 5. Collation

Every yielded verdict is a candidate `(verdict, priority, path)`. <a id="cite-ntfe-eval.every-verdict-is-a-candidate"></a> The
winner has the highest priority; at equal priority the strictest
verdict: `DROP` (3) > `REJECT(Refused)` (2) > `REJECT(Prohibited)` (1) >
`PASS` (0). <a id="cite-ntfe-eval.highest-priority-then-strictest-wins"></a> The two reject ranks are a deterministic tie-break — the
quieter story wins — that exists only because candidate order is
meaningless. Priority is the rule's *effective* priority, resolved at
ingestion: a rule's own `Priority` value, else its parent's, else 0. <a id="cite-ntfe-eval.effective-priority-inherits-from-parent"></a>

<a id="trm-6-4-6"></a>

## 6. The backstop

No candidate at all: the verdict is `DROP`, attributed to `backstop`,
and the evaluation is flagged so the event can say so. <a id="cite-ntfe-eval.no-candidate-drops-via-flagged-backstop"></a> The backstop is
compiled in and un-deletable; <a id="cite-ntfe-eval.backstop-is-undeletable"></a> every permissive statement in a policy is
therefore a visible rule.

<a id="trm-6-4-7"></a>

## The evaluation as data

Tree traversal, ancestor fallback, and candidate collation live in
`pnp_core::machinery`. Its domain adapter supplies matching, action resolution
and verdict strictness. Packet and interface evaluation retain the
`pnp_core::eval::evaluate` entry point and their existing fact and action types.
Userspace domains can share the same traversal without constructing synthetic
packet snapshots. The machinery computes results and optional explanation
steps; callers retain responsibility for applying effects and refusing conflicts.

`Evaluation` carries the winning verdict, its attribution, the backstop
flag, every effect to apply, every candidate (winners and losers alike)
for observability, and `expires_at`. <a id="cite-ntfe-eval.evaluation-carries-every-candidate-and-effect"></a> Effects reference their stores by
name *and* hash: `Effect::Tag { hash, op }`, `Effect::Count { hash,
amount }` with the amount already resolved (`Length` becomes the packet
length, or 0 when the packet has none), <a id="cite-ntfe-eval.count-length-is-packet-length-or-zero"></a> `Effect::Report { rule, level }`,
`Effect::PromptIssued { rule, handler }`. <a id="cite-ntfe-eval.effects-carry-name-and-hash"></a>

<a id="trm-6-4-8"></a>

## The bridge

`ntfe_rust_evaluate(forest, snap, layer, reporting_level, out)` is what
`policy.c` calls under `rcu_read_lock()`. <a id="cite-ntfe-eval.bridge-runs-under-rcu-read-lock"></a> It:

1. lifts the C snapshot ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)) and resolves the forest's machinery facts
   through the stores — `peios_ntfe_tag_lookup()` for every tag name the
   forest mentions (`Packet` and `Flow` layers; `RawPacket` reads none), <a id="cite-ntfe-eval.rawpacket-forest-reads-no-tags"></a>
   `peios_ntfe_counter_read()` for every view — and gives a `Flow` forest
   its own facts, `Related` and `Start.*`; <a id="cite-ntfe-eval.bridge-resolves-machinery-facts-before-eval"></a>
2. evaluates with `EvalContext { reporting_level }`; <a id="cite-ntfe-eval.bridge-passes-reporting-level"></a>
3. writes the verdict, the reject kind, the backstop flag, the
   attribution (cut to 95 bytes), the FNV-1a-64 of the whole
   attributing path (`attributed_hash`) and `expires_at` (0 = never)
   into `struct peios_ntfe_outcome`; <a id="cite-ntfe-eval.bridge-writes-outcome"></a>
4. **then** applies the effects — `peios_ntfe_tag_apply()`,
   `peios_ntfe_counter_add()`, `peios_ntfe_report_emit()` with the verdict
   it just computed — counting each species into the outcome. <a id="cite-ntfe-eval.effects-applied-after-verdict"></a>

Ordering 4 after 2 is what the snapshot-immutability law requires: a
`COUNT` is applied after this packet's own view reads, so a rule cannot
trip its own threshold, <a id="cite-ntfe-eval.count-cannot-trip-own-threshold"></a> and a `REPORT` can name the verdict. <a id="cite-ntfe-eval.report-names-the-verdict"></a> Every
allocation in 1–2 is `GFP_ATOMIC` (`pnp-core`'s `pkm_alloc` in kernel
mode); <a id="cite-ntfe-eval.bridge-allocations-are-atomic"></a> a failure returns `-ENOMEM` and the hook fails closed ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)). <a id="cite-ntfe-eval.allocation-failure-fails-closed"></a> The
store calls never sleep. <a id="cite-ntfe-eval.store-calls-never-sleep"></a>

---

# Policy ingestion and validation

_Peios Kernel / Internals / NTFE_

> Policy ingestion and validation: behaviour and implementation of the Peios kernel.

<a id="trm-6-5"></a>

The kernel reads its own policy. There is no daemon that compiles rules
and pushes them down; `ingest.c` walks the registry through the LCS
source interface, feeds what it finds to the `pnp-core` builder over the
bridge, and publishes the result as a generation — or keeps the previous
one, loudly. <a id="cite-ntfe-ingest.refused-walk-keeps-previous-generation"></a> The same walk reads netd's inventory beside the rules into
the network context table ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)), <a id="cite-ntfe-ingest.walk-reads-inventory-with-rules"></a> because to a flow the two change
together: a network being recognised on an interface is as much a
policy change as a rule being written.

<a id="trm-6-5-1"></a>

## Discovery and change notification

At LCS bootstrap, NTFE's key is discovered fifth alongside the other
kernel-owned subtrees: <a id="cite-ntfe-ingest.key-discovered-at-bootstrap"></a> `pkm_lcs_walk_absolute_components()` resolves
`Machine\System\Network` (the leading `Machine` hive component is
resolved locally against the hive root, not round-tripped), <a id="cite-ntfe-ingest.machine-component-resolved-locally"></a> and its
absence is not an error — no key, no policy and no context, generation
stays where it is. <a id="cite-ntfe-ingest.absent-network-key-is-not-an-error"></a> When the key exists one internal watch is armed on
it, depth-unbounded, for every change of content at any depth — LCS
delivers it a value set, a value deleted, a subkey created, a subkey
deleted and a key deleted; a security-descriptor change is not
delivered: <a id="cite-ntfe-ingest.one-unbounded-watch-on-network-key"></a> `Rules\`, `Interfaces\` and
`Networks\` beneath it are what NTFE reads; <a id="cite-ntfe-ingest.ntfe-reads-rules-interfaces-networks"></a> `Profiles\` and `Dns\` are
netd's and resolvd's, and a write there fires the watch and costs a
walk that publishes nothing. <a id="cite-ntfe-ingest.foreign-subtree-write-publishes-nothing"></a>

Watch events arrive per key and uncoalesced.
`peios_ntfe_network_registry_changed()` records the source and key, sets
a pending flag, and `mod_delayed_work()`s a re-walk with a 50 ms
debounce: <a id="cite-ntfe-ingest.rewalk-debounced-50ms"></a> a burst of writes (a transaction touching a rule and its
values, an autoapply seeding a whole policy, netd syncing every
interface's `Status` after a link event) yields one re-walk after the
burst goes quiet. <a id="cite-ntfe-ingest.burst-yields-one-rewalk"></a> The walk itself runs in process context on
`system_wq`, one at a time under a mutex, since the bootstrap refresh
and the deferred work may overlap. <a id="cite-ntfe-ingest.walks-serialized-under-mutex"></a>

<a id="trm-6-5-2"></a>

## The walk

`peios_ntfe_network_refresh_from_key()` snapshots the LCS runtime limits,
sequence and layer view, enumerates the Network key's children for
`Rules`, `Interfaces` and `Networks`, and runs two independent stages —
the rules, then the context; <a id="cite-ntfe-ingest.rules-stage-then-context-stage"></a> a failure in the first does not skip the
second, and the walk reports the first error. <a id="cite-ntfe-ingest.rules-failure-does-not-skip-context"></a> No `Rules` key leaves the
previous generation standing, exactly as a walk that refused would. <a id="cite-ntfe-ingest.absent-rules-key-keeps-generation"></a>

The rules stage:

1. reads the Rules key's own values for `CurrentReportingLevel`
   (`REG_DWORD`, `REG_DWORD_BIG_ENDIAN` or `REG_QWORD`; 1..6; absent =
   1; anything else refuses); <a id="cite-ntfe-ingest.reporting-level-type-and-range"></a>
2. enumerates its children for the layer keys `Packet`, `RawPacket` and
   `Flow` (`Interface` is netd's — the interface layer is built and judged
   in userspace with the same `pnp-core`, and the kernel never reads it;
   any other name is ignored); <a id="cite-ntfe-ingest.kernel-reads-three-layer-keys-only"></a>
3. for each present layer, opens a builder and walks the layer key's
   subkeys as rule roots. Each rule is one `RSI_QUERY_VALUES` round trip
   (its effective, layering-resolved values, delivered in the batch
   record format `u32 name_len | name | u32 type | u32 data_len | data`)
   followed by one `RSI_ENUM_CHILDREN` round trip for its exceptions,
   recursively, <a id="cite-ntfe-ingest.rule-read-is-two-round-trips"></a> bounded by depth 12 and 4096 rules per layer: a root rule
   is depth 0, so a chain of 13 keys is the deepest read, and a rule
   deeper than that or a 4097th rule refuses the walk. <a id="cite-ntfe-ingest.walk-bounded-depth-12-and-4096-rules"></a>

Registry types are lowered as the builder ABI expects: `REG_SZ` and
`REG_EXPAND_SZ` to strings (NUL termination stripped), `REG_DWORD` and
`REG_DWORD_BIG_ENDIAN` to integers, `REG_QWORD` to a signed 64-bit
integer, `REG_MULTI_SZ` to a list of strings. <a id="cite-ntfe-ingest.registry-type-lowering"></a> Any other type in a rule
refuses the walk: <a id="cite-ntfe-ingest.other-value-type-refuses-walk"></a> atomic transitions prefer a loud rejection over a
silently half-read rule. So does an integer of the wrong length — a
`REG_DWORD` or `REG_DWORD_BIG_ENDIAN` whose data is not 4 bytes, a
`REG_QWORD` not 8 — in a rule or in `CurrentReportingLevel`. <a id="cite-ntfe-ingest.wrong-length-integer-refuses-walk"></a>

Everything the stage feeds the builder — each layer and whether its key
exists, rule name and depth, value name, type and bytes — also goes
through an FNV-1a digest, and so does the reporting level's *value*
(not its bytes: the same level re-written as another integer type
digests the same). <a id="cite-ntfe-ingest.rules-input-digested"></a> When the digest equals the one of the last walk that
published (none before the first), the stage publishes nothing: the
built forests are freed and the generation does not move. <a id="cite-ntfe-ingest.unchanged-digest-publishes-nothing"></a> The
active generation already *is* this policy — even when that policy is
no forests at all — and republishing would only make every sentence
stale for nothing. A walk fired by an inventory write therefore
publishes no rules; it moves the generation only if the context stage
finds the table changed (below). The writes of a transaction reach the
watch together at its commit and, like any burst, coalesce into one
walk. <a id="cite-ntfe-ingest.inventory-write-changes-no-generation"></a>

<a id="trm-6-5-2-1"></a>

### The context stage

The inventory is read into one `struct peios_ntfe_context_table`, at
most 64 entries of interface name, network id, name and trust: <a id="cite-ntfe-ingest.context-table-at-most-64-entries"></a>

1. every child of `Networks\` is a record; its key name is the id (a
   UUID — a name of 40 bytes or more, which no id field can hold, is
   ignored with its record, once loudly), <a id="cite-ntfe-ingest.overlong-network-id-ignored-once-loudly"></a> and one
   `RSI_QUERY_VALUES` round trip reads its `Name` and `Trust`
   (`REG_SZ`; absent or unreadable is empty, and the id is still a
   fact), <a id="cite-ntfe-ingest.unreadable-name-or-trust-is-empty"></a> up to 256 records; <a id="cite-ntfe-ingest.network-records-up-to-256"></a>
2. every child of `Interfaces\` is an interface; its `Status` subkey is
   found by one `RSI_ENUM_CHILDREN` and read by one `RSI_QUERY_VALUES`
   for `Name` (the kernel interface name) and `Network` (the id netd
   identified on it). <a id="cite-ntfe-ingest.interface-status-read"></a> Both present make an entry, joined to the record
   of that id for its name and trust; <a id="cite-ntfe-ingest.interface-entry-joins-network-record"></a> either absent — no link, no
   offer yet, an `IGNORE`d or `DOWN` interface — makes none. <a id="cite-ntfe-ingest.incomplete-status-makes-no-entry"></a>

Nothing in the stage refuses a generation. <a id="cite-ntfe-ingest.context-stage-never-refuses"></a> A record that cannot be read is
logged and skipped — an interface key whose subkeys cannot be listed,
or whose `Status` cannot be read, carries no context; a network record
whose values cannot be read keeps its id with no name and no trust; <a id="cite-ntfe-ingest.unreadable-record-skipped"></a>
an interface beyond the 64th carries no context, <a id="cite-ntfe-ingest.interface-beyond-64th-has-no-context"></a> a value
longer than its field is truncated with one warning. <a id="cite-ntfe-ingest.overlong-context-value-truncated"></a> If the list of
`Networks\` or `Interfaces\` itself cannot be read, the stage publishes
nothing and the previous table stands: a table built from half a list
would strip every network after the failure point of its name and
trust, and with them every rule that names them. That failure is the
walk's error — it shows in `last_ingest_error` — and the rules stage's
outcome is untouched by it. <a id="cite-ntfe-ingest.unreadable-list-keeps-previous-table"></a> Otherwise the table goes to `peios_ntfe_context_publish()` ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)): if it equals the active
one entry for entry it is freed and nothing happens; <a id="cite-ntfe-ingest.equal-context-table-publishes-nothing"></a> otherwise it is
`rcu_assign_pointer()`ed into place, the generation counter advances,
the old table is freed after grace, and the kernel log says how many
interfaces carry a context. <a id="cite-ntfe-ingest.changed-context-table-advances-generation"></a> The generation advance is the whole
mechanism by which a context change reaches running flows: every
sentence is now stale and is re-judged on its flow's next packet
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)), the same path a rule change takes. <a id="cite-ntfe-ingest.context-change-rejudges-flows-on-next-packet"></a>

<a id="trm-6-5-3"></a>

## Building and validating

The builder (`ntfe_rust_builder_*`) accumulates `RuleInput` trees; `build`
runs `pnp_core::ingest::build_forest`, which parses every condition key
and action expression, orders each rule's conditions with the live-time
ones last ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)), <a id="cite-ntfe-ingest.build-orders-live-time-conditions-last"></a> resolves priority inheritance, <a id="cite-ntfe-ingest.build-resolves-priority-inheritance"></a> lints layer-impossible
facts (a `FlowState` or tag condition in a `RawPacket` forest; a
per-packet fact — `Length`, `TcpFlags`, `Fragment`, `Ttl`, `Dscp`,
`EtherType`, `DstMac`, `FlowState` — in a `Flow` forest; `Related` or
`Start.*` anywhere but `Flow` — all legal, and built never to hold; the kernel drops
lints, the authoring surface shows them), <a id="cite-ntfe-ingest.layer-impossible-facts-lint-not-refuse"></a> and collects the forest's
**name sets**: every tag name mentioned in a `TAG` action, a `PROMPT`
fallback, or a `Tag.<n>` condition, split into the names the forest
*writes* and the first rule reading each; every stream a `COUNT` writes;
every distinct counter view a `Counter.<n>(...)` condition reads, with
the first rule and value that mentioned it. <a id="cite-ntfe-ingest.build-collects-name-sets"></a> Views are deduplicated and
conditions refer to them by index — that index is what the bridge uses
when it fills `counter_views` ([The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>)). <a id="cite-ntfe-ingest.views-deduplicated-and-indexed"></a>

Refusals, each carrying the offending rule's path (`BuildError`):
unknown fact, <a id="cite-ntfe-ingest.refuse-unknown-fact"></a> unsupported operator, <a id="cite-ntfe-ingest.refuse-unsupported-operator"></a> unparsable pattern, <a id="cite-ntfe-ingest.refuse-unparsable-pattern"></a> a counter view
that does not parse (bad duration, unknown key fact, duplicate
arguments, a window over the one-day horizon, or a multibyte character
where the argument grammar requires ASCII),
<a id="cite-ntfe-ingest.refuse-unparsable-counter-view"></a>
a non-list `Actions`,
<a id="cite-ntfe-ingest.refuse-non-list-actions"></a> an
unparsable action, <a id="cite-ntfe-ingest.refuse-unparsable-action"></a> a `REJECT` kind that is not `Refused` or
`Prohibited`, <a id="cite-ntfe-ingest.refuse-unknown-reject-kind"></a> a `PROMPT` chain nested deeper than `MAX_PROMPT_CHAIN`
(4), refused as an unparsable action, <a id="cite-ntfe-ingest.refuse-prompt-chain-too-deep"></a> an action the layer does not
speak (`JOIN`, `IGNORE` or `DOWN`, the interface layer's verdicts, in
a kernel layer, directly or as a `PROMPT` fallback), <a id="cite-ntfe-ingest.refuse-action-not-at-layer"></a> a `Present`
condition on a fact that never exists at the rule's layer (every other
operator over such a fact is only linted, below; `Present` looks
through the absent-fact law, so `X.Present = 0` there would always
hold), <a id="cite-ntfe-ingest.refuse-present-never-at-layer"></a> a `Priority` that is not an integer, <a id="cite-ntfe-ingest.refuse-non-integer-priority"></a> an `Enabled` that is
not 0 or 1, <a id="cite-ntfe-ingest.refuse-enabled-not-0-or-1"></a> a rule name that is empty or contains a path separator <a id="cite-ntfe-ingest.refuse-rule-name-with-path-separator"></a>
(a backstop: LCS refuses such a key name before the walk could read
it) — and, over the name sets, two distinct tag names (or stream names)
whose 64-bit hashes collide. <a id="cite-ntfe-ingest.refuse-name-hash-collision"></a>

After all three layers build, `ntfe_rust_forests_check()` runs the checks
that span forests, because the stores are machine-wide: tag and stream
hashes must be distinct across *every* forest; <a id="cite-ntfe-ingest.hashes-distinct-across-forests"></a> every counter view must
have a writer in *some* forest — a view over a stream no rule writes is
statically dead (it can only ever read absent) and is refused with the
rule and key that read it; <a id="cite-ntfe-ingest.refuse-view-without-writer"></a> and no forest may read a tag a *higher*
forest writes (`RawPacket` < `Packet` < `Flow`) — tags flow strictly
upward, and since rules are the only source of tag names the downward
read is refused statically, with the reading rule and the name. <a id="cite-ntfe-ingest.refuse-downward-tag-read"></a>

## Related explanations

- [Generation publication and recovery](</kernel/internals/ntfe/generation-publication-and-recovery.md>)

---

# Generation publication and recovery

_Peios Kernel / Internals / NTFE_

> Generation publication and recovery: behaviour and implementation of the Peios kernel.

<a id="trm-6-5-4"></a>

## Publication

`peios_ntfe_policy_publish(packet, raw, flow, reporting_level)` is
process context under a mutex. <a id="cite-ntfe-ingest.publish-serialized-under-mutex"></a> It runs the cross-forest check, then
materializes the counter store for the union of every forest's views
([The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>)) — so a store that cannot be built (allocation, more than eight
windows on one table) refuses the generation before anything is
swapped. <a id="cite-ntfe-ingest.unbuildable-counter-store-refuses-generation"></a> Only then does it advance the generation counter, allocate the
new `struct peios_ntfe_policy` (three opaque forest pointers plus the
reporting level) and `rcu_assign_pointer()` it into place. <a id="cite-ntfe-ingest.generation-advances-only-after-checks"></a> Hook-path
readers dereference it under `rcu_read_lock()` and never block; <a id="cite-ntfe-ingest.hook-readers-never-block"></a> they see
the old generation or the new one, never a mix. <a id="cite-ntfe-ingest.readers-never-see-mixed-generation"></a> The old policy is
released by `call_rcu()`, and its forests by `ntfe_rust_forest_free()` in
the callback after grace. <a id="cite-ntfe-ingest.old-policy-freed-after-grace"></a>

Every walk records its outcome: `last_ingest_error` (0, or the positive
errno of the last failed walk) and `last_ingest_t_ns`, both in the
status. <a id="cite-ntfe-ingest.walk-outcome-in-status"></a> A refusal leaves the previous generation active and says so in
the kernel log. <a id="cite-ntfe-ingest.refusal-logged-and-previous-stays-active"></a> `contexts` in the status is the number of interfaces in
the active context table. <a id="cite-ntfe-ingest.status-contexts-counts-interfaces"></a>

<a id="trm-6-5-4-1"></a>

### In the event stream

NTFE writes its own lifecycle to KMES, origin class `KMES_ORIGIN_NTFE`
(4), beside the reports of [The stores](</kernel/internals/ntfe/the-stores.md#trm-6-6>). Every publication writes one
`ntfe.policy.published`, after the swap; a refusal writes none. <a id="cite-ntfe-ingest.publish-emits-policy-published"></a>
Its payload is one `policy` map: `generation`, the generation now in
force; `generation-previous`, the generation of the policy it replaced,
0 for the first since boot; `layers`, the layers that have a forest, in
the order `raw-packet`, `packet`, `flow`, and an empty list for a policy
of no forests; and `report-threshold` and `report-threshold-previous`,
the new and the replaced `CurrentReportingLevel`, the latter 1 when
nothing was replaced. <a id="cite-ntfe-ingest.published-event-payload"></a> A walk
whose digest is unchanged publishes nothing, and so writes nothing. <a id="cite-ntfe-ingest.unchanged-walk-writes-no-published-event"></a>
A context-table change advances the generation without a policy and
writes no `ntfe.policy.published` either, so the generations between
two of these events are the earlier policy under a changed context.

A refused rules walk writes one `ntfe.policy.rejected`. <a id="cite-ntfe-ingest.refusal-emits-policy-rejected"></a>
Its `policy` map holds the `generation` still in force and
`previous-retained`, always true. Its `outcome` map holds `errno`, the
walk's negative errno, and `reason`. When the refusal is in, or names,
one rule, a `rule` map follows. It holds `layer` when the refusal arose
building one layer's forest, and `action-error` for a `bad-action`. It
holds `name`, the rule's path relative to its layer key; a path longer
than 255 bytes is cut at a character boundary, with `name-truncated`. <a id="cite-ntfe-ingest.rejected-event-payload"></a>

The errno is the walk's, unchanged. The reason is new: the bridge's
`ntfe_rust_builder_build_why()` and `ntfe_rust_forests_check_why()`
fill a `struct peios_ntfe_build_why` from pnp-core's `BuildError`. A
builder refusal keeps its own name and its rule's path, such as
`unknown-fact`, `bad-action` with its action error, `bad-priority`, or
`tag-downward-read` from the cross-forest checks, which name the rule
but no layer. <a id="cite-ntfe-ingest.build-refusal-reason-crosses-bridge"></a> The walk names the refusals it makes itself:

- `rule-too-deep` and `too-many-rules`, with `-E2BIG`;
- `bad-value-type`, `bad-value-length` and `not-utf8`, in the rule that
  holds the value;
- `bad-reporting-level`, `counter-store-refused` and `out-of-memory`;
- `registry-read-failed` for a source round trip that failed. <a id="cite-ntfe-ingest.walk-refusal-reasons"></a>

A walk that finds no `Rules` key writes the event too, with reason
`no-rules-key`, no `errno` and no rule. <a id="cite-ntfe-ingest.absent-rules-key-emits-rejected"></a>

Every walk re-reads the policy, including the walks netd's inventory
writes cause, so a broken policy is refused again and again until it
is fixed. The event is written once per distinct refusal: a walk whose
digest, errno and reason equal those of the last refusal written writes
none. A walk the rules stage accepts, published or unchanged, clears
that memory, so the next refusal is written whatever it is. A missing
`Rules` key is therefore written once each time the key goes missing. <a id="cite-ntfe-ingest.repeated-refusal-written-once"></a>
The kernel log line is written for every refusal, as before, and now
names the reason. Both events are built on the stack in process context,
under the publication mutex or the walk mutex; neither is ever written
from the packet path.

<a id="trm-6-5-4-2"></a>

### In force

A registry write that has returned is delivered, not enforced: the walk
that reads it runs after the debounce. <a id="cite-ntfe-ingest.returned-write-not-yet-enforced"></a> Two status counters say which a
writer is looking at. `changes_noted` is incremented by
`peios_ntfe_network_registry_changed()` for every watch event, <a id="cite-ntfe-ingest.changes-noted-counts-watch-events"></a> and LCS
delivers its internal watches inside the write that caused them, after
the commit and before the syscall returns, so a writer that reads the
status after its write sees its own change counted. <a id="cite-ntfe-ingest.writer-sees-own-change-noted"></a> The deferred work
reads `changes_noted` under the same lock that clears the pending flag,
before it walks, and stores that value in `changes_walked` when the walk
returns, whether it published or was refused. <a id="cite-ntfe-ingest.changes-walked-set-from-pre-walk-noted"></a>

So a writer is in force once `changes_walked` reaches the `changes_noted`
it read after writing: the walk that satisfied it started after the
write committed. <a id="cite-ntfe-ingest.in-force-when-walked-reaches-noted"></a> A change that lands mid-walk raises `changes_noted`
again and re-arms the work, so the pair stays unequal until a later walk
covers it. <a id="cite-ntfe-ingest.mid-walk-change-rearms-work"></a> A refused walk still advances `changes_walked`; <a id="cite-ntfe-ingest.refused-walk-advances-changes-walked"></a> the writer
then reads `last_ingest_error` to learn that what it wrote is not what
is enforced. The walk records its error before it stores
`changes_walked`, and the status reads them in the other order, so a
status that shows a change walked shows that walk's error or a later
one's, never an older one. The bootstrap walk is not a noted change and moves neither
counter. <a id="cite-ntfe-ingest.bootstrap-walk-moves-neither-counter"></a> `net policy wait` is this loop.

<a id="trm-6-5-5"></a>

## Generation 0

Until the first successful ingestion there is no policy at all, and
every layer is permissive: <a id="cite-ntfe-ingest.generation-zero-is-permissive"></a> `judged` stays 0, `permissive` counts
traversals, no events are emitted (there is no decision to attribute),
and the status reports `enforcing = 0`. <a id="cite-ntfe-ingest.generation-zero-status-and-no-events"></a> The init log line says it
plainly. This is the ratified loud default — the alternative, a
compiled-in policy the registry cannot see, was rejected.

A new generation does not touch the flows: every sentence written under
the old one is stale by generation and is re-judged on its flow's next
packet ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). <a id="cite-ntfe-ingest.new-generation-stales-sentences-without-flow-walk"></a> That is how a policy change — and a context change,
which advances the same counter — reaches running connections without
a walk of the conntrack table.

---

# The stores

_Peios Kernel / Internals / NTFE_

> The three machinery stores behind NTFE's effects — flow tags on a conntrack extension, counter tables materialized from the forest's views, and REPORT emission into KMES — with their bounds and confessions.

<a id="trm-6-6"></a>

Effects need somewhere to land. Three stores, each with a small C
surface the bridge calls during evaluation, each confessing what it
refuses into the engine status.

<a id="trm-6-6-1"></a>

## Identities

Tag and stream names cross into the stores as 64-bit **FNV-1a hashes**
(`pnp_core::hash::name_hash`). <a id="cite-ntfe-store.names-cross-as-fnv1a-hashes"></a> The stores never see a string on the
packet path, and never a generation: a flow's tag table holds `(hash,
value)` pairs, a counter table is keyed by its stream's hash. <a id="cite-ntfe-store.stores-hold-no-strings-or-generations"></a> Two
consequences: tags survive policy reloads by construction (the table
knows nothing to invalidate), <a id="cite-ntfe-store.tags-survive-policy-reload"></a> and a hash must be a deterministic
identity, not a probabilistic one — which ingestion guarantees by
refusing any generation whose distinct names collide ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)). <a id="cite-ntfe-store.colliding-names-refuse-generation"></a> Within a
running policy a collision is impossible; across generations the
residual is a 64-bit birthday bound over a handful of names, documented
and not defended.

<a id="trm-6-6-2"></a>

## Flow tags

A tag is a named unsigned integer on a conntrack entry. The store is the
`tags` pointer of NTFE's **conntrack extension** — `NF_CT_EXT_NTFE`,
`struct peios_ntfe_ct` (`include/linux/peios_ntfe.h`), added to every flow
at creation (`init_conntrack()`, by the `ntfe-conntrack-ext.patch`), <a id="cite-ntfe-store.ct-extension-added-at-flow-creation"></a> with
the pointer NULL until the flow's first `TAG`. <a id="cite-ntfe-store.tag-table-null-until-first-tag"></a> The extension *block* of
a confirmed conntrack entry is immutable (upstream removed post-confirm
resizing as an RCU-reader race), and NTFE's egress seat runs after
confirmation, so the extension must exist before it is needed; a fixed
extension on every flow is the cheapest way to guarantee that. Since the
Flow slice the extension also holds the flow's start time and its two
sentences ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — 88 bytes per flow, most of it the sentences — <a id="cite-ntfe-store.ct-extension-holds-start-and-sentences"></a> while
untagged flows, nearly all of them, still pay nothing for a table.

The first `TAG` allocates (`GFP_ATOMIC`) a table of eight `(hash, value,
present)` entries; <a id="cite-ntfe-store.first-tag-allocates-eight-entries"></a> a full table is replaced by one twice the size —
copy, `rcu_assign_pointer()`, `kfree_rcu()` the old — <a id="cite-ntfe-store.full-tag-table-doubles"></a> up to the tripwire
of 64 distinct tags per flow. <a id="cite-ntfe-store.tag-tripwire-64-per-flow"></a> Readers walk the table under RCU with no
lock (the hook path already holds the read lock); <a id="cite-ntfe-store.tag-readers-lockless-under-rcu"></a> writers serialize on
the flow's own `ct->lock`. <a id="cite-ntfe-store.tag-writers-serialize-on-ct-lock"></a> `Clear` tombstones an entry (`present = 0`)
rather than compacting, so a concurrent reader never sees the table
shift under it, <a id="cite-ntfe-store.clear-tombstones-without-compacting"></a> and a later `Set` reuses the slot. <a id="cite-ntfe-store.set-reuses-tombstoned-slot"></a> `Add` saturates at
`U64_MAX`. <a id="cite-ntfe-store.tag-add-saturates"></a> The entry's identity is published before the length that
exposes it (`smp_wmb()` then `WRITE_ONCE(len)`), so a reader that sees
the new length sees a complete entry. <a id="cite-ntfe-store.tag-entry-published-before-length"></a>

When the flow dies, `nf_conntrack_free()` calls `peios_ntfe_ct_destroy()`
(the same patch), which `kfree_rcu()`s the table — a reader that found
the entry under RCU may still be walking it. <a id="cite-ntfe-store.tag-table-freed-after-grace-on-flow-death"></a>

Confessions: `tag_writes` (ops applied), <a id="cite-ntfe-store.tag-writes-counts-applied-ops"></a> `tag_untracked` (a `TAG` on a
packet with no flow — untracked traffic, or the ingress seat — is a
no-op), <a id="cite-ntfe-store.tag-without-flow-is-untracked-no-op"></a> `tag_refused` (the tripwire, an allocation failure, or a flow
whose extension could not be allocated at creation). <a id="cite-ntfe-store.tag-refused-confessions"></a> Clearing an absent
tag is a no-op, not a refusal. <a id="cite-ntfe-store.clearing-absent-tag-is-no-op"></a>

<a id="trm-6-6-3"></a>

## Counters

`COUNT(Name[, amount])` emits into a **stream**; every
`Counter.Name([window][, key])` a rule reads is a **view**. Nothing is
declared: views are compile-time constants (rules are their only
source), so at publication ([Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>)) the store receives the complete view
set of all three forests — `Packet`, `RawPacket` and `Flow` — and materializes exactly that — one **table** per
distinct `(stream hash, key-spec)`, each answering every window any
view of that pair asks for, plus the cumulative total. <a id="cite-ntfe-store.one-table-per-stream-and-key-spec"></a> A `COUNT`
increments every table of its stream; <a id="cite-ntfe-store.count-increments-every-table-of-stream"></a> the amplification is bounded by
what policy authors wrote, the trusted side of the trust asymmetry.

A table is a 1024-bucket hash of **cells** (`jhash` over the cell key)
under a per-table spinlock (`_bh`, since the publisher runs in process
context). <a id="cite-ntfe-store.table-is-1024-bucket-hash-under-bh-lock"></a> A cell key is built from the packet by the table's key-spec:
address family, source and destination address (16 bytes each, v4 in
the first four), interface index — only the facts the spec names, the
rest zero. <a id="cite-ntfe-store.cell-key-holds-only-named-facts"></a> A packet lacking a keyed fact (an ARP frame for a
`SrcAddr`-keyed table) has no cell: its `COUNT` no-ops into that table
(`count_key_absent`) <a id="cite-ntfe-store.count-without-key-fact-no-ops"></a> and its view reads absent — the absent-fact law on
both sides. <a id="cite-ntfe-store.view-without-key-fact-reads-absent"></a>

A cell holds a cumulative `total`, the seconds of its last write, and
one **ring** per table window: eight buckets, each stamped with the
*period* it belongs to (`now / bucket_secs`, where `bucket_secs =
max(1, window / 8)`). <a id="cite-ntfe-store.ring-is-eight-period-stamped-buckets"></a> A write zeroes a bucket whose stamp is stale
before adding; <a id="cite-ntfe-store.write-zeroes-stale-bucket"></a> a read sums the buckets whose stamp is within the last
eight periods. <a id="cite-ntfe-store.read-sums-last-eight-periods"></a> Advancement is lazy — there are no timers — and the
window is an approximation up to one bucket wide, by design. <a id="cite-ntfe-store.window-approximate-to-one-bucket"></a>

The keyspace of a keyed table is chosen by whoever sends packets, so
tables are hard-capped at **4096 cells**. <a id="cite-ntfe-store.table-capped-at-4096-cells"></a> At the cap the store first
reaps cells idle for longer than the table's longest window (floor
60 s); <a id="cite-ntfe-store.cap-reaps-idle-cells-first"></a> if none are idle the new key is refused and confessed
(`count_refused`). <a id="cite-ntfe-store.cap-refuses-new-key-when-none-idle"></a> Never silent eviction.

The store outlives generations. <a id="cite-ntfe-store.counter-store-outlives-generations"></a> Re-publication keeps tables whose window
set did not change, <a id="cite-ntfe-store.republish-keeps-unchanged-tables"></a> creates new ones, <a id="cite-ntfe-store.republish-creates-new-tables"></a> **migrates** tables whose windows
changed (each cell is re-allocated in the new ring layout; the total and
any window both sets share carry over, new windows start empty and
converge), <a id="cite-ntfe-store.republish-migrates-changed-tables"></a> and retires tables no forest views any more — `list_del_rcu()`
then free after grace, cells included. <a id="cite-ntfe-store.republish-retires-unviewed-tables"></a> Reads on the packet path walk the
table list and the cell lists under RCU; <a id="cite-ntfe-store.counter-reads-under-rcu"></a> the publisher holds a mutex.

`PEIOS_NTFE_IOC_COUNTERS` dumps every cell of every table for the viewer:
stream name, key-spec, the key, the total, the last-write time, and the
current value of each window. <a id="cite-ntfe-store.counters-ioctl-dumps-every-cell"></a> It is a best-effort snapshot, which is fine
for counters that are approximate by design: the cells are gathered
into a kernel batch under one RCU read section and copied out after
it, and a store with more cells than a batch holds (4096) takes
further passes, each resuming after the cells already written, so a
cell created or retired between passes may be missed or seen twice. <a id="cite-ntfe-store.counters-dump-is-best-effort"></a>

<a id="trm-6-6-4"></a>

## Reports

`REPORT(level)` at or above `CurrentReportingLevel` becomes one KMES event:
origin class `KMES_ORIGIN_NTFE` (4), event type `ntfe.verdict.reported`, <a id="cite-ntfe-store.report-becomes-one-kmes-event"></a> and a
msgpack payload laid out as the event catalogue's `ntfe` fragment
says: nested string-keyed maps, one per path segment. `rule` carries
the attribution (`name`, the path, and `hash`, the FNV-1a-64 of the
whole path), the `report-level`, and where the judgment stood
(`layer`: `raw-packet`, `packet` or `flow`; `seat`). `outcome` carries
what it said (`verdict`: `pass`, `reject` or `drop`; and `reason`,
`prohibited` or `refused`, when it was a reject). The packet is
`network` (`direction`, `interface` with its `name` and `index`,
`ether-type`, `family` as the `AF_*` number, `protocol`, `length`),
`source` and `destination` (each an `address` as text and a `port`),
and `flow` (`state`). `policy` carries the `generation`. The time is
the KMES header's; the payload does not repeat it. <a id="cite-ntfe-store.report-payload-keys"></a> A packet key whose fact can be
absent is present only when the packet has it: `network.protocol`,
`source` and `destination` when it has an address family, their ports
when it has ports, `flow` when the flow-state fact is present.
`network.direction`, `network.interface.index`, `network.ether-type`,
`network.family` and `network.length` are always emitted — an
interface index of 0 and a family of `AF_UNSPEC` (0) are the catalogue's
own values for none. `network.interface.name` is left out when no
device was there to name; no key is ever written as an empty string. <a id="cite-ntfe-store.report-omits-absent-packet-keys"></a>

The payload is built on the stack (512 bytes) <a id="cite-ntfe-store.report-payload-built-on-stack"></a> because the packet path runs in softirq and
`pkm_kmes_emit_kernel()` is a preempt-disabled per-CPU ring write with
no allocation of its own. Every map's size is known before it is
written, save `rule`'s, whose one-byte header is settled once the
name's fate is. Every value but `rule.name` is bounded, so `rule` goes
in last and `name` last within it: a path too long for the room left
is cut at a character boundary to fit, and `rule.name-truncated`
(`true`, absent when the name is whole) says so. The event is always
emitted, and `rule.hash` still names the whole path, so a reader
resolves the rule against the policy. <a id="cite-ntfe-store.report-long-rule-cut-and-said"></a> Flood control is the author's by design — the
level gate — with KMES's own ring accounting as the backstop.
`reports_emitted` counts what reached the ring. <a id="cite-ntfe-store.reports-emitted-counts-ring-arrivals"></a>

---

# Event ring and delivery

_Peios Kernel / Internals / NTFE_

> Event ring and delivery: behaviour and implementation of the Peios kernel.

<a id="trm-6-7"></a>

Every real evaluation — a published forest judged the traversal, or a
fail-closed drop — appends one `struct peios_ntfe_event` to a bounded
ring. <a id="cite-ntfe-stream.each-evaluation-appends-one-event"></a> Permissive traversals emit nothing: there is no decision to
attribute, and the status tells that story instead. <a id="cite-ntfe-stream.permissive-emits-no-event"></a> A packet answered by
its flow's cached sentence emits nothing either: there was no
evaluation, and `flow_cached` counts it. <a id="cite-ntfe-stream.cached-sentence-emits-no-event"></a> The layouts are in [NTFE ABI Reference](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>); this
page is what they mean.

<a id="trm-6-7-2"></a>

## The ring and its reader

The ring holds 4096 events under a spinlock (`irqsave`: emission happens
in softirq). <a id="cite-ntfe-stream.ring-4096-events-irqsave-lock"></a> A full ring overwrites the **oldest** event and counts the
loss in `events_dropped` — the honesty rule: a slow reader loses data
and is told so, in the status and by the gap in sequence numbers. <a id="cite-ntfe-stream.full-ring-overwrites-oldest"></a>

`/dev/peios-ntfe` is a misc device, mode 0600. <a id="cite-ntfe-stream.device-misc-mode-0600"></a> Any number of files may
be open on it, because the status and dump ioctls are asked by tools
while a viewer holds the stream, <a id="cite-ntfe-stream.device-many-openers"></a> but the ring has one drain: the first
file to `read()` claims it until it closes, and another file's `read()`
returns `-EBUSY` meanwhile. <a id="cite-ntfe-stream.first-reader-claims-ring-others-ebusy"></a> `read()` returns whole
records only, up to 64 per call, <a id="cite-ntfe-stream.read-whole-records-up-to-64"></a> and blocks on an empty ring unless
`O_NONBLOCK`; <a id="cite-ntfe-stream.read-blocks-unless-nonblock"></a> `poll()` raises `POLLIN` when events wait. <a id="cite-ntfe-stream.poll-pollin-when-events-wait"></a> A reader that
reconnects resumes from whatever the ring still holds, and catches the
gap from the sequence numbers. <a id="cite-ntfe-stream.reconnect-resumes-from-ring"></a>

The viewer daemon reads it with a small wrinkle worth knowing about: its
own HTTP responses to a viewer are judged traffic too, so every event it
sends produces another event — a feedback loop. pnpd hides events about
its own TCP port from what it serves and counts them (`own_verdicts_hidden`),
which is the same treatment the wire tap gives its own frames. <a id="cite-ntfe-stream.viewer-hides-own-port-events"></a>

## Related explanations

- [Event records and status semantics](</kernel/userspace/native/ntfe/event-records-and-status-semantics.md>)

---

# The Flow layer

_Peios Kernel / Internals / NTFE_

> The second rung — one judgment per local endpoint of a flow, cached on the conntrack entry as a sentence, re-judged when the policy or the clock makes it stale, and dumped for the viewer.

<a id="trm-6-8"></a>

The Flow layer (`Rules\Flow`, the rung-2 design on PEI-598) is the same
rule atom, verbs and evaluation as the per-packet layers, applied to a
different unit: the **flow**, what conntrack tracks. It exists because
the per-packet evaluator has no early exit — collation and
side-effects-always mean every packet walks the whole forest, so an
`Established → PASS` rule saves nothing — and because flows carry facts
(a start time, relatedness, one day an owner) and effect units (a
connection, not a packet) that packets do not. The Packet layer becomes
the cheap filter in front; the decisions move here and run once per
connection. <a id="cite-ntfe-flow.decisions-run-once-per-connection"></a>

<a id="trm-6-8-1"></a>

## One judgment per local endpoint

`peios_ntfe_flow_dispatch()` (`flow.c`) is called at the IP seats:
inbound, at `LOCAL_IN`, for every packet the Packet layer passed;
outbound, at `LOCAL_OUT`, for every packet, before any Packet judgment
— the Packet layer judges outbound traffic at egress, after it ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)). <a id="cite-ntfe-flow.dispatch-after-packet-pass"></a>
An untracked packet (`snap->flow == NULL`) has no flow to judge and is
accepted, `NF_ACCEPT`: inbound the Packet verdict stands, outbound the
Packet layer judges it next at egress. <a id="cite-ntfe-flow.untracked-packet-keeps-packet-verdict"></a> A
tracked packet reads its flow's **sentence**:

- a *current* sentence — its policy object and policy/context invalidation
  generation are both current, and its expiry (if any) has not passed — is applied
  without evaluation (`flow_cached`); <a id="cite-ntfe-flow.current-sentence-applied-without-evaluation"></a>
- otherwise the Flow forest is evaluated against the snapshot
  (`peios_ntfe_policy_snapshot_eval()`, counted in `judged`
  and `flow_judged`), the outcome is written as the new sentence, an
  event is emitted (with `REJUDGED` when a stale sentence was replaced,
  `flow_rejudged` or `flow_expired` saying why), and the verdict is
  applied. <a id="cite-ntfe-flow.stale-sentence-evaluated-and-rewritten"></a> A refusal goes out before the event, so the event can confess
  a degradation. <a id="cite-ntfe-flow.refusal-sent-before-event"></a>

No Flow forest at all (generation 0, or no `Flow` key) is permissive,
counted, and caches nothing. <a id="cite-ntfe-flow.no-forest-permissive-uncached"></a>

Flow dispatch holds one RCU policy snapshot while checking layer
presence, preparing identity facts and evaluating. The sentence retains
that policy object's generation as an internal stamp alongside the
existing invalidation generation, which also changes when network
context changes. Both must match before either endpoint's cached verdict
can be reused. A packet already evaluating an old policy may finish;
its old verdict cannot remain current after a new policy is published.
The extra policy stamp does not change the flow-dump ABI.

On a cache miss, Flow refreshes `Network.*` from the active context table
for the packet's traversal interface after capturing the invalidation
generation. It clears the old fields first, so removing a context makes
those facts absent. Context publication swaps the table before advancing
the generation; the reader's acquire of that generation precedes its
context lookup. Thus a packet snapshot taken before publication cannot
leave an old network verdict cached under the new generation. A context
published after the captured generation makes the resulting sentence
stale on the next traversal, even if that evaluation already saw the new
facts. A current cached sentence needs no extra context lookup.

What the Flow forest judges is the **flow view**, not the packet's
snapshot: a Flow fact is one identical for every packet of the flow, so
`ntfe_flow_view()` builds it from the flow. <a id="cite-ntfe-flow.judges-flow-view-not-packet"></a> A reply-direction packet's
addresses and ports are swapped back to the original tuple (and its
ICMP type replaced by the tuple's); <a id="cite-ntfe-flow.reply-view-uses-original-tuple"></a> the direction is the originator's,
recorded at the first judgment along with the interface, the VLAN, the
peer's MAC and the endpoints' identities ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), so a re-judgment on a
reply sees exactly the facts the first judgment saw. <a id="cite-ntfe-flow.rejudgment-sees-first-judgment-facts"></a> (Found live before the fix: an inbound viewer flow
re-judged on its reply packet as `out`, and matched `outbound-ok`.) A
loopback flow's view takes the slot's direction. <a id="cite-ntfe-flow.loopback-view-takes-slot-direction"></a> The refusal, when the
verdict is one, answers the packet in hand; <a id="cite-ntfe-flow.refusal-answers-packet-in-hand"></a> the event describes the flow
as judged. <a id="cite-ntfe-flow.event-describes-flow-as-judged"></a>

A normal flow has one local endpoint and one sentence, slot 0, written
at the originator's seat on the first packet; the reply direction, and
every later packet, reads it. <a id="cite-ntfe-flow.normal-flow-one-sentence-slot-0"></a> `Direction` in the judgment is the
originator's side. <a id="cite-ntfe-flow.direction-is-originator-side"></a> A **loopback** flow has two local endpoints and two
sentences: the outbound one (slot 0) at `LOCAL_OUT` and the inbound one
(slot 1) at `LOCAL_IN`, both on the same first packet, <a id="cite-ntfe-flow.loopback-two-sentences-same-first-packet"></a> and every packet
of it answers to the *stricter* of the two (DROP > REJECT(Refused) >
REJECT(Prohibited) > PASS). <a id="cite-ntfe-flow.loopback-stricter-sentence-applies"></a> The comparison is made before any
refusal is sent: a `REJECT` overruled by the other end's `DROP` sends
nothing, and one overruled by the other end's stricter `REJECT` sends
that one's kind. <a id="cite-ntfe-flow.loopback-stricter-decided-before-refusal"></a> Loopback-ness is the seat's device
(`IFF_LOOPBACK`, `snap->loopback`); <a id="cite-ntfe-flow.loopback-by-seat-device"></a> a stale other-endpoint sentence is
not applied — it is that seat's to refresh when it next sees the flow. <a id="cite-ntfe-flow.stale-other-slot-not-applied"></a>

<a id="trm-6-8-2"></a>

## The sentence

`struct peios_ntfe_sentence` lives in NTFE's conntrack extension
(`include/linux/peios_ntfe.h`), two per flow: the invalidation generation
that judged (0 = empty), the generation of the policy object that judged,
`expires_at` (epoch seconds, 0 = never), the FNV-1a-64 hash
of the attributing rule's whole path (the outcome's `attributed_hash`:
the event's `attributed` text is cut short, the hash never is; the same
identity the tag and counter stores use for names, so the viewer
resolves it against the policy), the verdict and the reject kind. <a id="cite-ntfe-flow.sentence-fields"></a> Alongside: `start_secs`, stamped when
conntrack created the entry (`peios_ntfe_ct_ext_add()`) — the `Start.*`
facts — <a id="cite-ntfe-flow.start-secs-stamped-at-ct-creation"></a> and, from the first judgment, the interface, the direction and
whether the flow is loopback, for the dump. <a id="cite-ntfe-flow.extension-records-first-judgment-facts"></a>

NTFE shares conntrack extension storage with accounting and other
kernel features. Its allocation sizes and offsets use 16-bit fields;
the build-time capacity guard includes the NTFE payload and alignment
padding for every allocation order. Adding another extension must not
wrap the total length or overwrite an existing extension. These fields
are kernel-internal and do not change the flow-dump ABI.

Writes take the flow's lock (`ct->lock`, `_bh`), zero the generation
first, write the fields, and publish the generation last with a release
store. <a id="cite-ntfe-flow.sentence-write-publishes-generation-last"></a> Each slot also has a modification
sequence, advanced at the start and end of every write, including a
refresh under the same policy generation. The policy generation
identifies the policy; it cannot detect every cache update.

Reads are lock-free on the hook path and in the flow dump. They make
one attempt: an active writer or a changed modification sequence makes
the sentence read as absent. Readers neither spin nor acquire the
flow's lock. On a cache miss the flow is evaluated as usual. <a id="cite-ntfe-flow.torn-sentence-reads-absent"></a> Two packets of a new flow racing on two CPUs may both
evaluate; the second sentence write wins (both judged the identities
the first resolution recorded, [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), and the effects ran twice — the only
place NTFE tolerates that, because the alternative is a lock on the fast
path for a race that needs a flow's first two packets to arrive
concurrently. <a id="cite-ntfe-flow.first-packet-race-second-write-wins"></a>

The cache holds the verdict only. <a id="cite-ntfe-flow.cache-holds-verdict-only"></a> Effects run at every evaluation of the
flow and never per packet. <a id="cite-ntfe-flow.effects-per-evaluation-not-per-packet"></a> `DROP` and `REJECT` sentences persist for the
life of a flow conntrack has confirmed: a cached `REJECT` refuses every
subsequent packet of it. <a id="cite-ntfe-flow.drop-reject-sentences-persist"></a> A `DROP` or `REJECT` on a flow's first packet
at a seat that stands before confirmation — `LOCAL_IN` for an inbound
flow, `LOCAL_OUT` for an outbound one — leaves nothing to persist:
nothing kills the entry, but its packet is dropped before conntrack
confirms it (the refusal is filed as the entry's reply, which confirms
nothing), so the unconfirmed entry dies with the packet, sentence and
all. A retransmitted SYN is then a fresh flow, judged again — effects
included — and refused again. <a id="cite-ntfe-flow.new-flow-drop-reject-kills-entry"></a> So the cached refusal answers only on a
confirmed flow: one re-judged mid-life, or a loopback flow's inbound
end, judged at `LOCAL_IN` after `POST_ROUTING` confirmed the entry. A
`Refused` reset to a confirmed TCP flow also moves it to conntrack's
`CLOSE` state (`nf_ct_set_closing()`), whose short timeout ends it. <a id="cite-ntfe-flow.refused-tcp-flow-set-closing"></a> A flow whose extension could not be allocated has nowhere to hold
a sentence and is evaluated on every packet (`flow_uncached`). <a id="cite-ntfe-flow.no-extension-evaluated-per-packet"></a>

<a id="trm-6-8-3"></a>

## Staleness

A sentence is stale when its invalidation generation is not the current
one (a policy published, or a network context published — [Ingestion and generations](</kernel/internals/ntfe/policy-ingestion-and-validation.md#trm-6-5>) — both
advance the one counter), when the policy object that judged it is not
the current policy object, or when `t_secs >= expires_at`. <a id="cite-ntfe-flow.stale-by-generation-or-expiry"></a> Both are checked lazily, on the flow's next
packet — an idle flow past a policy change is killed when it next
speaks, or conntrack times it out; there are no timers and no walk of
the table at publication. <a id="cite-ntfe-flow.staleness-checked-lazily"></a> Grandfathering was rejected: the registry must
not lie about what is enforced, and a `REJECT` rule must be able to
reject something already running. A refused packet of an
established TCP flow tears down both ends at once ([Seats and dispatch](</kernel/internals/ntfe/seats-and-dispatch.md#trm-6-2>)): the end that
sent it is refused with the kind's story, and the packet, turned into a
reset, is sent on to the other end. <a id="cite-ntfe-flow.refused-established-tcp-teardown-both-ends"></a> Before the teardown existed, a
killed viewer stream froze at the local end while the silent host peer
waited for its own next packet to meet the cached `REJECT` sentence —
correct under the lazy law, and half a kill.

The expiry is the evaluation's `expires_at` ([Evaluation](</kernel/internals/ntfe/evaluation.md#trm-6-4>)): the earliest moment
any live-time condition the judgment *consulted* would flip. <a id="cite-ntfe-flow.expiry-earliest-consulted-flip"></a> A forest
with no time conditions never expires a sentence; <a id="cite-ntfe-flow.no-time-conditions-never-expires"></a> `Start.*` conditions
never contribute, which is the point of them. <a id="cite-ntfe-flow.start-conditions-never-contribute-expiry"></a>

<a id="trm-6-8-4"></a>

## The flows dump

`PEIOS_NTFE_IOC_FLOWS` walks conntrack's table the way `ctnetlink` does —
`local_bh_disable()`, each bucket under its `nf_conntrack_locks` lock,
original-direction entries of `init_net` that are neither expired nor
dying <a id="cite-ntfe-flow.dump-walks-live-original-entries"></a> — and fills `struct peios_ntfe_flow_rec` per flow: conntrack's id,
family, protocol, the original tuple (ports, or ICMP id and type/code),
`seen_reply`/`assured`/`related`, the remaining lifetime, packet and
byte counts (NTFE turns conntrack accounting on at init — the
`net.netfilter.nf_conntrack_acct` sysctl, `init_net.ct.sysctl_acct` —
since it is conntrack's consumer now), <a id="cite-ntfe-flow.init-enables-conntrack-acct"></a> and the extension: start time, first-judgment interface
and direction, loopback, both sentences, both ends' identities, and up
to eight tags by hash with the flow's total tag count. <a id="cite-ntfe-flow.dump-record-contents"></a>
Records are batched in kernel memory (32 to a batch) and copied to user
between passes over the buckets, never under a lock; a bucket holding
more flows than the batch has room for is walked again under its lock
from where the batch filled, rather than losing the rest. <a id="cite-ntfe-flow.dump-copies-out-between-buckets"></a> The walk counts every live flow it saw so
a short buffer is visible, and is best-effort against a table that
changes under it. <a id="cite-ntfe-flow.dump-counts-every-live-flow"></a>

<a id="trm-6-8-5"></a>

## What was decided against

- **Backstop inheritance** (the flow's verdict as the Packet layer's
  compiled-in default): unnecessary once Packet is the filter in front
  and passes tracked traffic by shipped configuration.
- **Two layers, Inbound and Outbound**: direction-blind rules are common
  and shadowing gives the direction-specific exceptions; the posture is
  a visible root rule; per-seat direction pruning is a future evaluator
  optimisation, invisible to authors.
- **Effects on first judgment only**: a kill by `REJECT, REPORT(n)` must
  report; the `COUNT` noise is per generation, not per packet.
- **Identity in the sentence.** The sentence caches the verdict; the
  identities the judgment read are recorded beside it ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)), not
  re-derived per packet.

---

# The identity facts

_Peios Kernel / Internals / NTFE_

> The third rung — who stands at each local end of a flow, read once from the socket KACS stamped, fixed for the flow's life, and judged as the Flow layer's Local and Remote facts.

<a id="trm-6-9"></a>

The identity facts (rung 3 on PEI-598) answer the question the address
facts cannot: not *where* a flow goes but *who* on this machine is
speaking or listening. They are Flow-layer facts by the same law as
`Related` and `Start.*` — a flow has one answer for its whole life — and
they are the first facts NTFE reads from somewhere other than the packet.
KACS provides them; the engine resolves them once per flow.

<a id="trm-6-9-1"></a>

## What KACS stamps on a socket

Every inet socket carries a **governing identity**, recorded by KACS in
the socket's security state ([Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md#trm-3-12-2>)): the caller's *effective* token —
so a service thread impersonating a client attributes the socket to the
client, as audit does — and the process facts of that moment: the
process GUID, the thread-group id and the `comm` of the thread that
made the stamp (a thread's own name, which need not be its process's). <a id="cite-ntfe-identity.socket-stamp-effective-token-and-process-facts"></a> The stamp is
taken at every act that commits the socket to a role: creation, `bind`,
`listen`, `connect`, inheritance at `accept`, and `KACS_SO_RESTAMP`. <a id="cite-ntfe-identity.stamp-taken-at-role-acts"></a> The
last stamp governs, which is how a listener handed to another program
(socket activation, descriptor passing) is governed as that program's. <a id="cite-ntfe-identity.last-stamp-governs"></a>
A kernel socket is stamped as the kernel's, with no token. <a id="cite-ntfe-identity.kernel-socket-stamped-without-token"></a>

The engine reads the stamp through one accessor,
`pkm_kacs_socket_owner()` (`<linux/peios_ntfe.h>`), which hands it a
counted reference to the token and a copy of the process facts. <a id="cite-ntfe-identity.owner-accessor-counted-ref-and-copy"></a> The
facts outlive the process; the reference outlives the socket. <a id="cite-ntfe-identity.facts-outlive-process-and-socket"></a>

<a id="trm-6-9-2"></a>

## What stands at an end

`identity.c` classifies each local end of a flow by **whether anyone
answers**, not by whether a socket structure exists. The result is the
`Local` fact (`program`, `kernel`, `shared`, `none`) and, for a program,
the principal behind `Local.*`. <a id="cite-ntfe-identity.local-fact-kinds"></a>

**Outbound**, at `LOCAL_OUT`: the sending socket's stamp. A stamped
program socket is `program`; <a id="cite-ntfe-identity.outbound-stamped-socket-program"></a> a kernel socket, or no socket at all
(resets, ICMP errors, IGMP) is `kernel`. <a id="cite-ntfe-identity.outbound-kernel-or-no-socket-kernel"></a>

**Inbound**, at `LOCAL_IN`, a transport lookup for the receiver of this
very packet:

- UDP to a multicast or broadcast destination is `shared` before any
  lookup: the stack delivers it to every socket bound to the port — one
  flow, many endpoints — and the per-program question belongs to the
  *join*, not to the packet. `Local.*` is absent. <a id="cite-ntfe-identity.inbound-multicast-broadcast-udp-shared"></a>
- TCP, UDP and UDP-Lite are looked up by tuple, the way the netfilter
  socket match does — listeners included, and through the same hash a
  `SO_REUSEPORT` group steers by, so the sentence names the socket that
  will actually receive. <a id="cite-ntfe-identity.inbound-transport-lookup-by-tuple"></a> Early demux may already have found it, and
  its socket is used in place of the lookup — for UDP only once the
  datagram has passed the `shared` test above, since early demux also
  attaches the one socket a multicast datagram happens to match. An early
  result is used only if its socket still has a live reference that NTFE
  can pin. UDP early demux keeps the pointer valid under RCU but does not
  itself hold a reference; if the socket's last reference has gone, NTFE
  falls back to the ordinary tuple lookup without reviving the socket.
  A missing receiver then gives the same `none` result as an ordinary
  lookup miss. The temporary socket reference is released after reading
  the identity. <a id="cite-ntfe-identity.early-receiver-pin-or-lookup"></a>
  Any other protocol is looked up among raw sockets bound to it. <a id="cite-ntfe-identity.inbound-other-protocol-raw-lookup"></a>
- A socket found is `program` (a request minisock stands for its
  listener; a `TIME_WAIT` minisock is nobody's: `kernel`). <a id="cite-ntfe-identity.inbound-found-socket-program"></a>
- Nothing found: `kernel` if the stack has a handler registered for the
  protocol — ICMP and ICMPv6 (neighbour discovery, router advertisements,
  MLD), IGMP, the tunnel and IPsec outers that are decapsulated and
  re-enter the ingress seat as their inner packet — else `none`, which
  the stack will answer with a reset or an unreachable. <a id="cite-ntfe-identity.inbound-nothing-found-kernel-or-none"></a>

The classification is a rule, not a list of protocols. Two consequences
are documented rather than special-cased: SCTP, a socket transport whose
table lives inside its module, reads `kernel` while the module is
loaded; <a id="cite-ntfe-identity.sctp-reads-kernel"></a> and a ping socket's echo reply pairs with the outbound request in
conntrack and inherits the outbound `program` sentence, so the direct
lookup is deferred. <a id="cite-ntfe-identity.ping-reply-inherits-outbound-sentence"></a>

The lookup runs **once per flow**, on the first judgment, and only when
a `Flow` forest is published: a permissive machine pays nothing. <a id="cite-ntfe-identity.lookup-once-per-flow-only-with-flow-forest"></a>

<a id="trm-6-9-3"></a>

## Loopback: both ends

A loopback flow has two local ends and two sentences ([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)). The
outbound seat resolves both on the first packet — its own end from the
socket, the other by running the receiver lookup early on the
loopback-destined packet — and records them on the flow's extension. <a id="cite-ntfe-identity.loopback-outbound-seat-resolves-both-ends"></a>
The inbound seat's judgment, on the same packet, reads both from there:
`Local.*` is its own end and `Remote.*` the sender's. <a id="cite-ntfe-identity.loopback-inbound-local-own-remote-sender"></a> The inbound seat
cannot see a loopback packet's sender itself (loopback transmission
orphans the buffer), so a flow whose extension could not be allocated
reads `Remote` as absent there, confessed. <a id="cite-ntfe-identity.loopback-no-extension-remote-absent-confessed"></a> Off loopback `Remote` is
always absent: nothing is provable about a peer yet. <a id="cite-ntfe-identity.remote-absent-off-loopback"></a>

<a id="trm-6-9-4"></a>

## Fixed for the flow's life

The identities are recorded on the conntrack extension at the first
judgment, per slot, beside the direction and the interface, and never
replaced: a re-judgment after a policy change or a time edge sees the
same principal, and a later restamp of the socket, a fork after
`accept`, or a `SO_REUSEPORT` sibling taking over the port changes
nothing for flows already judged. <a id="cite-ntfe-identity.fixed-at-first-judgment"></a> The extension holds one counted token
reference per slot and releases it when conntrack frees the flow. <a id="cite-ntfe-identity.token-ref-per-slot-released-on-free"></a> Two
CPUs racing on a new flow's first packets may both resolve; the first
record stands — unlike the sentence, where the second write wins
([The Flow layer](</kernel/internals/ntfe/the-flow-layer.md#trm-6-8>)) — and the loser releases its reference and judges the recorded
identity instead of its own. <a id="cite-ntfe-identity.resolve-race-first-record-stands"></a>

<a id="trm-6-9-5"></a>

## Across the bridge

The flow view carries, per end, the kind, the process facts and a
borrowed token pointer. <a id="cite-ntfe-identity.flow-view-carries-borrowed-token"></a> The bridge (`security/pkm/kacs/ntfe_runtime.rs`) implements
pnp-core's `Principal` trait over the token — user SID, enabled-group
membership (deny-only groups are invisible to policy), <a id="cite-ntfe-identity.deny-only-groups-invisible"></a> integrity level,
confinement SID and capabilities, the per-service SID found among the
enabled groups, the process GUID as text (PCDS's string form —
`Data1`, `Data2` and `Data3` read as little-endian numbers and written
most significant digit first, `Data4` bytes in order — lowercase and unbraced, `8-4-4-4-12`; ingestion lowercases a
`Local.Process` or `Remote.Process` pattern and strips braces from a
braced one to match) — without copying the group
list: a token may carry a thousand groups and the judgment runs in
softirq context, so the snapshot borrows a view and asks membership
questions of it. <a id="cite-ntfe-identity.principal-view-without-copying-groups"></a> The view is lock-free: group SIDs are fixed at token
creation and each group's attributes are an atomic. <a id="cite-ntfe-identity.principal-view-lock-free"></a>

The judgment compares SIDs and nothing else; what NTFE knows of a SID's
meaning is only what pnp-core compiles into it — the service-SID
derivation and a table of well-known names — used once, at ingestion,
to turn a name a rule wrote into a SID. The engine holds no directory
of principals and resolves no SID back to a name. <a id="cite-ntfe-identity.no-sid-meaning-in-kernel"></a> `Local.Service.Equal
= resolvd` is turned into the service's SID at ingestion by pnp-core,
with the same derivation peinit and authd use to mint it (the SHA-1 of
the uppercased UTF-16LE name under `S-1-5-80`); <a id="cite-ntfe-identity.service-name-to-sid-at-ingestion"></a> `Local.User.Equal =
LocalService` by a table of well-known names. <a id="cite-ntfe-identity.well-known-user-names-by-table"></a> The viewer resolves the
other way, from the service definitions in the registry. <a id="cite-ntfe-identity.viewer-resolves-sids-from-registry"></a>

<a id="trm-6-9-6"></a>

## What the stream says

A `Flow` event and a flow record carry both ends: the kind, the process
GUID, pid and comm, the user SID and the service SID (ABI 4, [NTFE ABI Reference](</kernel/userspace/native/ntfe/generated-device-abi.md#trm-6-a>),
[NTFE ABI Notes](</kernel/userspace/native/ntfe/device-operations-and-errors.md#trm-6-b>)). <a id="cite-ntfe-identity.event-and-record-carry-both-ends"></a> An end that could not be attributed — a socket with no KACS
state, an inet socket nobody stamped, a loopback sender the inbound
seat could not see — is confessed: `identity_unresolved` in the status,
`PEIOS_NTFE_EV_F_IDENTITY_UNRESOLVED` on the event, and the flag on the
flow record's slot. <a id="cite-ntfe-identity.unattributed-end-confessed"></a>

<a id="trm-6-9-7"></a>

## At rest: the listeners dump

The same stamp, read without a packet: `PEIOS_NTFE_IOC_LISTENERS`
(`listeners.c`) walks the listening TCP hash and the bound UDP and
UDP-Lite tables of the root namespace the way `/proc/net/tcp` and
`/proc/net/udp` do — each bucket under its lock, records copied out
between buckets — and reports every socket prepared to receive with the
identity that governs it. <a id="cite-ntfe-identity.listeners-dump-reports-receivers-with-identity"></a> It is the attack surface as a list, by whom,
and it exercises the stamp before a single flow is judged.

<a id="trm-6-9-8"></a>

## What was decided against

- **Identity in the per-packet layers.** A packet carries no owner; the
  socket does. `Local.*` in a `Packet` rule is linted as never present, <a id="cite-ntfe-identity.local-in-packet-rule-linted-never-present"></a>
  and `Present` on it refuses the generation. <a id="cite-ntfe-identity.present-local-in-packet-rule-refuses-generation"></a>
- **Many sentences for a shared receiver.** Inbound multicast is one
  flow with many endpoints; modelling N judgments would have made the
  join-time question a per-packet one. `shared` and a later gate on
  `IP_ADD_MEMBERSHIP` (C11) instead.
- **Copying the group list into the snapshot.** Up to 1024 SIDs per
  token, in softirq: the `Principal` view answers membership instead.
- **`Program.Trust` and the image hash.** PIP is under review, and
  unsigned binaries are not hashed at exec today; both wait.

---

# Authoring Packet Rules

_Peios Kernel / Internals / NTFE_

> Adapt exception, counting, and time-based policy patterns while checking the complete rule forest.

These layouts illustrate individual patterns, not complete replacement
policies. Read the existing forest and retain a local recovery path before
changing live access. Registry paths below are relative to
`Machine\System\Network`.

## Apply a pattern safely

1. Identify the layer and the facts available at its seat. Include protocol
   and traffic scope in every gating rule.
2. Choose a pattern below and adapt addresses, ports, names, and priorities.
   Check competing trees; a child is an exception only within its own tree.
3. Apply the reviewed edit, then inspect the accepted kernel generation.
4. Test the intended connection and inspect attribution and loss counters.
   A write or capture alone does not establish packet delivery.

## Allow one inbound connection class

```text
Rules\Flow\inbound          Direction.Equal = in
                              Actions = REJECT
Rules\Flow\inbound\ssh-lan  Protocol.Equal = tcp, DstPort.Equal = 22
                              SrcAddr.Equal = 10.0.0.0/8
                              Actions = PASS
```

The child narrows the parent region. It does not bypass other layers or
higher-priority trees. A rejection on an established TCP flow can terminate
both endpoints; use `DROP` if the intended refusal is silent.

## Count packets or bytes before gating a source

```text
Rules\Packet\dns-count  Protocol.Equal = udp, DstPort.Equal = 53
                          Actions = COUNT(dns)
Rules\Packet\dns-cap    Protocol.Equal = udp, DstPort.Equal = 53
                          Counter.dns(10s, SrcAddr).GreaterThan = 20
                          Actions = REJECT(Prohibited)
```

The counter rule abstains from a verdict. Matching reads the view before the
current evaluation's count, and the window is approximate. Keep the protocol
and port conditions on the gating rule: removing them broadens refusal to
other traffic from that source.

Use `COUNT(egress, Length)` with an outbound packet rule for byte accounting.
A threshold such as `Counter.egress(1m, SrcAddr).GreaterThan = 104857600`
then measures bytes, not packet count. To count connections instead, use a
`Flow` rule with `COUNT(conns)`; reevaluations can run that effect again.

## Distinguish live time from connection start

```text
Rules\Flow\curfew  Direction.Equal = out
                     Start.Hour.Equal = 22-23, 0-5
                     Priority = 10
                     Actions = REJECT(Prohibited), REPORT(3)
```

This example restricts new outbound flows during those UTC hours. Replacing
`Start.Hour` with `Time.Hour` also makes running flows subject to time-edge
reevaluation. `Time.*` and `Start.*` are not interchangeable schedules.

## Tag a flow and observe its reply

```text
Rules\Packet\tag-dns  Protocol.Equal = udp, DstPort.Equal = 53
                        Actions = TAG(dnsq, Add)
Rules\Packet\reply    Protocol.Equal = udp, SrcPort.Equal = 53
                        Tag.dnsq.GreaterThan = 0
                        Actions = REPORT(4)
```

A tag changes observation state, not access. Tags are flow-scoped, retain
state across generations, and obey layer dependency restrictions.

## Use network context deliberately

```text
Rules\Flow\no-ssh       Direction.Equal = in
                           Protocol.Equal = tcp, DstPort.Equal = 22
                           Actions = DROP
Rules\Flow\no-ssh\home  Network.Trust.Equal = home
                           Actions = PASS
```

`home` is an operator label on the identified network, not cryptographic
proof of location. Missing context cannot satisfy that exception. Changing
the context can cause a new judgment on an established flow's next packet.
Interface/profile selection belongs to netd; it is not Wi-Fi association.

---

# NetLabel

_Peios Kernel / Internals / Network labelling_

> Reference for NetLabel.

<a id="rst-netlabel"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [NetLabel Introduction](</kernel/internals/netlabel/introduction.md>)
- [NetLabel CIPSO/IPv4 Protocol Engine](</kernel/internals/netlabel/cipso-ipv4.md>)
- [NetLabel Linux Security Module Interface](</kernel/internals/netlabel/lsm-interface.md>)
- [Draft IETF CIPSO IP Security](</kernel/internals/netlabel/draft-ietf.md>)

---

# NetLabel CIPSO/IPv4 Protocol Engine

_Peios Kernel / Internals / Network labelling_

> Paul Moore, paul.moore@hp.com

<a id="rst-netlabel-cipso-ipv4-protocol-engine"></a>

Paul Moore, [paul.moore@hp.com](<mailto:paul.moore@hp.com>)

May 17, 2006

<a id="rst-overview"></a>

## Overview

The NetLabel CIPSO/IPv4 protocol engine is based on the IETF Commercial IP Security Option (CIPSO) draft from July 16, 1992.  A copy of this draft can be found in this directory (draft-ietf-cipso-ipsecurity-01.txt).  While the IETF draft never made it to an RFC standard it has become a de-facto standard for labeled networking and is used in many trusted operating systems.

<a id="rst-outbound-packet-processing"></a>

## Outbound Packet Processing

The CIPSO/IPv4 protocol engine applies the CIPSO IP option to packets by adding the CIPSO label to the socket.  This causes all packets leaving the system through the socket to have the CIPSO IP option applied.  The socket's CIPSO label can be changed at any point in time, however, it is recommended that it is set upon the socket's creation.  The LSM can set the socket's CIPSO label by using the NetLabel security module API; if the NetLabel "domain" is configured to use CIPSO for packet labeling then a CIPSO IP option will be generated and attached to the socket.

<a id="rst-inbound-packet-processing"></a>

## Inbound Packet Processing

The CIPSO/IPv4 protocol engine validates every CIPSO IP option it finds at the IP layer without any special handling required by the LSM.  However, in order to decode and translate the CIPSO label on the packet the LSM must use the NetLabel security module API to extract the security attributes of the packet. This is typically done at the socket layer using the 'socket_sock_rcv_skb()' LSM hook.

<a id="rst-label-translation"></a>

## Label Translation

The CIPSO/IPv4 protocol engine contains a mechanism to translate CIPSO security attributes such as sensitivity level and category to values which are appropriate for the host.  These mappings are defined as part of a CIPSO Domain Of Interpretation (DOI) definition and are configured through the NetLabel user space communication layer.  Each DOI definition can have a different security attribute mapping table.

<a id="rst-label-translation-cache"></a>

## Label Translation Cache

The NetLabel system provides a framework for caching security attribute mappings from the network labels to the corresponding LSM identifiers.  The CIPSO/IPv4 protocol engine supports this caching mechanism.

---

# Draft IETF CIPSO IP Security

_Peios Kernel / Internals / Network labelling_

> Reference for Draft IETF CIPSO IP Security.

<a id="rst-draft-ietf-cipso-ip-security"></a>

>
>
> 
> ```text
> IETF CIPSO Working Group
> 16 July, 1992
>
>
>
>                  COMMERCIAL IP SECURITY OPTION (CIPSO 2.2)
>
>
>
> 1.    Status
>
> This Internet Draft provides the high level specification for a Commercial
> IP Security Option (CIPSO).  This draft reflects the version as approved by
> the CIPSO IETF Working Group.  Distribution of this memo is unlimited.
>
> This document is an Internet Draft.  Internet Drafts are working documents
> of the Internet Engineering Task Force (IETF), its Areas, and its Working
> Groups. Note that other groups may also distribute working documents as
> Internet Drafts.
>
> Internet Drafts are draft documents valid for a maximum of six months.
> Internet Drafts may be updated, replaced, or obsoleted by other documents
> at any time.  It is not appropriate to use Internet Drafts as reference
> material or to cite them other than as a "working draft" or "work in
> progress."
>
> Please check the I-D abstract listing contained in each Internet Draft
> directory to learn the current status of this or any other Internet Draft.
>
>
>
>
> 2.    Background
>
> Currently the Internet Protocol includes two security options.  One of
> these options is the DoD Basic Security Option (BSO) (Type 130) which allows
> IP datagrams to be labeled with security classifications.  This option
> provides sixteen security classifications and a variable number of handling
> restrictions.  To handle additional security information, such as security
> categories or compartments, another security option (Type 133) exists and
> is referred to as the DoD Extended Security Option (ESO).  The values for
> the fixed fields within these two options are administered by the Defense
> Information Systems Agency (DISA).
>
> Computer vendors are now building commercial operating systems with
> mandatory access controls and multi-level security.  These systems are
> no longer built specifically for a particular group in the defense or
> intelligence communities.  They are generally available commercial systems
> for use in a variety of government and civil sector environments.
>
> The small number of ESO format codes can not support all the possible
> applications of a commercial security option.  The BSO and ESO were
> designed to only support the United States DoD.  CIPSO has been designed
> to support multiple security policies.  This Internet Draft provides the
> format and procedures required to support a Mandatory Access Control
> security policy.  Support for additional security policies shall be
> defined in future RFCs.
>
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 1]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
>
> 3.    CIPSO Format
>
> Option type: 134 (Class 0, Number 6, Copy on Fragmentation)
> Option length: Variable
>
> This option permits security related information to be passed between
> systems within a single Domain of Interpretation (DOI).  A DOI is a
> collection of systems which agree on the meaning of particular values
> in the security option.  An authority that has been assigned a DOI
> identifier will define a mapping between appropriate CIPSO field values
> and their human readable equivalent.  This authority will distribute that
> mapping to hosts within the authority's domain.  These mappings may be
> sensitive, therefore a DOI authority is not required to make these
> mappings available to anyone other than the systems that are included in
> the DOI.
>
> This option MUST be copied on fragmentation.  This option appears at most
> once in a datagram.  All multi-octet fields in the option are defined to be
> transmitted in network byte order.  The format of this option is as follows:
>
> +----------+----------+------//------+-----------//---------+
> | 10000110 | LLLLLLLL | DDDDDDDDDDDD | TTTTTTTTTTTTTTTTTTTT |
> +----------+----------+------//------+-----------//---------+
>
>   TYPE=134    OPTION    DOMAIN OF               TAGS
>               LENGTH    INTERPRETATION
>
>
>                 Figure 1. CIPSO Format
>
>
> 3.1    Type
>
> This field is 1 octet in length.  Its value is 134.
>
>
> 3.2    Length
>
> This field is 1 octet in length.  It is the total length of the option
> including the type and length fields.  With the current IP header length
> restriction of 40 octets the value of this field MUST not exceed 40.
>
>
> 3.3    Domain of Interpretation Identifier
>
> This field is an unsigned 32 bit integer.  The value 0 is reserved and MUST
> not appear as the DOI identifier in any CIPSO option.  Implementations
> should assume that the DOI identifier field is not aligned on any particular
> byte boundary.
>
> To conserve space in the protocol, security levels and categories are
> represented by numbers rather than their ASCII equivalent.  This requires
> a mapping table within CIPSO hosts to map these numbers to their
> corresponding ASCII representations.  Non-related groups of systems may
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 2]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> have their own unique mappings.  For example, one group of systems may
> use the number 5 to represent Unclassified while another group may use the
> number 1 to represent that same security level.  The DOI identifier is used
> to identify which mapping was used for the values within the option.
>
>
> 3.4    Tag Types
>
> A common format for passing security related information is necessary
> for interoperability.  CIPSO uses sets of "tags" to contain the security
> information relevant to the data in the IP packet.  Each tag begins with
> a tag type identifier followed by the length of the tag and ends with the
> actual security information to be passed.  All multi-octet fields in a tag
> are defined to be transmitted in network byte order.  Like the DOI
> identifier field in the CIPSO header, implementations should assume that
> all tags, as well as fields within a tag, are not aligned on any particular
> octet boundary.   The tag types defined in this document contain alignment
> bytes to assist alignment of some information, however alignment can not
> be guaranteed if CIPSO is not the first IP option.
>
> CIPSO tag types 0 through 127 are reserved for defining standard tag
> formats.  Their definitions will be published in RFCs.  Tag types whose
> identifiers are greater than 127 are defined by the DOI authority and may
> only be meaningful in certain Domains of Interpretation.  For these tag
> types, implementations will require the DOI identifier as well as the tag
> number to determine the security policy and the format associated with the
> tag.  Use of tag types above 127 are restricted to closed networks where
> interoperability with other networks will not be an issue.  Implementations
> that support a tag type greater than 127 MUST support at least one DOI that
> requires only tag types 1 to 127.
>
> Tag type 0 is reserved. Tag types 1, 2, and 5 are defined in this
> Internet Draft.  Types 3 and 4 are reserved for work in progress.
> The standard format for all current and future CIPSO tags is shown below:
>
> +----------+----------+--------//--------+
> | TTTTTTTT | LLLLLLLL | IIIIIIIIIIIIIIII |
> +----------+----------+--------//--------+
>     TAG       TAG         TAG
>     TYPE      LENGTH      INFORMATION
>
>     Figure 2:  Standard Tag Format
>
> In the three tag types described in this document, the length and count
> restrictions are based on the current IP limitation of 40 octets for all
> IP options.  If the IP header is later expanded, then the length and count
> restrictions specified in this document may increase to use the full area
> provided for IP options.
>
>
> 3.4.1    Tag Type Classes
>
> Tag classes consist of tag types that have common processing requirements
> and support the same security policy.  The three tags defined in this
> Internet Draft belong to the Mandatory Access Control (MAC) Sensitivity
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 3]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> class and support the MAC Sensitivity security policy.
>
>
> 3.4.2    Tag Type 1
>
> This is referred to as the "bit-mapped" tag type.  Tag type 1 is included
> in the MAC Sensitivity tag type class.  The format of this tag type is as
> follows:
>
> +----------+----------+----------+----------+--------//---------+
> | 00000001 | LLLLLLLL | 00000000 | LLLLLLLL | CCCCCCCCCCCCCCCCC |
> +----------+----------+----------+----------+--------//---------+
>
>     TAG       TAG      ALIGNMENT  SENSITIVITY    BIT MAP OF
>     TYPE      LENGTH   OCTET      LEVEL          CATEGORIES
>
>             Figure 3. Tag Type 1 Format
>
>
> 3.4.2.1    Tag Type
>
> This field is 1 octet in length and has a value of 1.
>
>
> 3.4.2.2    Tag Length
>
> This field is 1 octet in length.  It is the total length of the tag type
> including the type and length fields.  With the current IP header length
> restriction of 40 bytes the value within this field is between 4 and 34.
>
>
> 3.4.2.3    Alignment Octet
>
> This field is 1 octet in length and always has the value of 0.  Its purpose
> is to align the category bitmap field on an even octet boundary.  This will
> speed many implementations including router implementations.
>
>
> 3.4.2.4    Sensitivity Level
>
> This field is 1 octet in length.  Its value is from 0 to 255.  The values
> are ordered with 0 being the minimum value and 255 representing the maximum
> value.
>
>
> 3.4.2.5    Bit Map of Categories
>
> The length of this field is variable and ranges from 0 to 30 octets.  This
> provides representation of categories 0 to 239.  The ordering of the bits
> is left to right or MSB to LSB.  For example category 0 is represented by
> the most significant bit of the first byte and category 15 is represented
> by the least significant bit of the second byte.  Figure 4 graphically
> shows this ordering.  Bit N is binary 1 if category N is part of the label
> for the datagram, and bit N is binary 0 if category N is not part of the
> label.  Except for the optimized tag 1 format described in the next section,
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 4]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> minimal encoding SHOULD be used resulting in no trailing zero octets in the
> category bitmap.
>
>         octet 0  octet 1  octet 2  octet 3  octet 4  octet 5
>         XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX . . .
> bit     01234567 89111111 11112222 22222233 33333333 44444444
> number             012345 67890123 45678901 23456789 01234567
>
>             Figure 4. Ordering of Bits in Tag 1 Bit Map
>
>
> 3.4.2.6    Optimized Tag 1 Format
>
> Routers work most efficiently when processing fixed length fields.  To
> support these routers there is an optimized form of tag type 1.  The format
> does not change.  The only change is to the category bitmap which is set to
> a constant length of 10 octets.  Trailing octets required to fill out the 10
> octets are zero filled.  Ten octets, allowing for 80 categories, was chosen
> because it makes the total length of the CIPSO option 20 octets.  If CIPSO
> is the only option then the option will be full word aligned and additional
> filler octets will not be required.
>
>
> 3.4.3    Tag Type 2
>
> This is referred to as the "enumerated" tag type.  It is used to describe
> large but sparsely populated sets of categories.  Tag type 2 is in the MAC
> Sensitivity tag type class.  The format of this tag type is as follows:
>
> +----------+----------+----------+----------+-------------//-------------+
> | 00000010 | LLLLLLLL | 00000000 | LLLLLLLL | CCCCCCCCCCCCCCCCCCCCCCCCCC |
> +----------+----------+----------+----------+-------------//-------------+
>
>     TAG       TAG      ALIGNMENT  SENSITIVITY         ENUMERATED
>     TYPE      LENGTH   OCTET      LEVEL               CATEGORIES
>
>                 Figure 5. Tag Type 2 Format
>
>
> 3.4.3.1     Tag Type
>
> This field is one octet in length and has a value of 2.
>
>
> 3.4.3.2    Tag Length
>
> This field is 1 octet in length. It is the total length of the tag type
> including the type and length fields.  With the current IP header length
> restriction of 40 bytes the value within this field is between 4 and 34.
>
>
> 3.4.3.3    Alignment Octet
>
> This field is 1 octet in length and always has the value of 0.  Its purpose
> is to align the category field on an even octet boundary.  This will
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 5]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> speed many implementations including router implementations.
>
>
> 3.4.3.4    Sensitivity Level
>
> This field is 1 octet in length. Its value is from 0 to 255.  The values
> are ordered with 0 being the minimum value and 255 representing the
> maximum value.
>
>
> 3.4.3.5    Enumerated Categories
>
> In this tag, categories are represented by their actual value rather than
> by their position within a bit field.  The length of each category is 2
> octets.  Up to 15 categories may be represented by this tag.  Valid values
> for categories are 0 to 65534.  Category 65535 is not a valid category
> value.  The categories MUST be listed in ascending order within the tag.
>
>
> 3.4.4    Tag Type 5
>
> This is referred to as the "range" tag type.  It is used to represent
> labels where all categories in a range, or set of ranges, are included
> in the sensitivity label.  Tag type 5 is in the MAC Sensitivity tag type
> class.  The format of this tag type is as follows:
>
> +----------+----------+----------+----------+------------//-------------+
> | 00000101 | LLLLLLLL | 00000000 | LLLLLLLL |  Top/Bottom | Top/Bottom  |
> +----------+----------+----------+----------+------------//-------------+
>
>     TAG       TAG      ALIGNMENT  SENSITIVITY        CATEGORY RANGES
>     TYPE      LENGTH   OCTET      LEVEL
>
>                      Figure 6. Tag Type 5 Format
>
>
> 3.4.4.1     Tag Type
>
> This field is one octet in length and has a value of 5.
>
>
> 3.4.4.2    Tag Length
>
> This field is 1 octet in length. It is the total length of the tag type
> including the type and length fields.  With the current IP header length
> restriction of 40 bytes the value within this field is between 4 and 34.
>
>
> 3.4.4.3    Alignment Octet
>
> This field is 1 octet in length and always has the value of 0.  Its purpose
> is to align the category range field on an even octet boundary.  This will
> speed many implementations including router implementations.
>
>
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 6]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> 3.4.4.4    Sensitivity Level
>
> This field is 1 octet in length. Its value is from 0 to 255.  The values
> are ordered with 0 being the minimum value and 255 representing the maximum
> value.
>
>
> 3.4.4.5    Category Ranges
>
> A category range is a 4 octet field comprised of the 2 octet index of the
> highest numbered category followed by the 2 octet index of the lowest
> numbered category.  These range endpoints are inclusive within the range of
> categories.  All categories within a range are included in the sensitivity
> label.  This tag may contain a maximum of 7 category pairs.  The bottom
> category endpoint for the last pair in the tag MAY be omitted and SHOULD be
> assumed to be 0.  The ranges MUST be non-overlapping and be listed in
> descending order.  Valid values for categories are 0 to 65534.  Category
> 65535 is not a valid category value.
>
>
> 3.4.5     Minimum Requirements
>
> A CIPSO implementation MUST be capable of generating at least tag type 1 in
> the non-optimized form.  In addition, a CIPSO implementation MUST be able
> to receive any valid tag type 1 even those using the optimized tag type 1
> format.
>
>
> 4.    Configuration Parameters
>
> The configuration parameters defined below are required for all CIPSO hosts,
> gateways, and routers that support multiple sensitivity labels.  A CIPSO
> host is defined to be the origination or destination system for an IP
> datagram.  A CIPSO gateway provides IP routing services between two or more
> IP networks and may be required to perform label translations between
> networks.  A CIPSO gateway may be an enhanced CIPSO host or it may just
> provide gateway services with no end system CIPSO capabilities.  A CIPSO
> router is a dedicated IP router that routes IP datagrams between two or more
> IP networks.
>
> An implementation of CIPSO on a host MUST have the capability to reject a
> datagram for reasons that the information contained can not be adequately
> protected by the receiving host or if acceptance may result in violation of
> the host or network security policy.  In addition, a CIPSO gateway or router
> MUST be able to reject datagrams going to networks that can not provide
> adequate protection or may violate the network's security policy.  To
> provide this capability the following minimal set of configuration
> parameters are required for CIPSO implementations:
>
> HOST_LABEL_MAX - This parameter contains the maximum sensitivity label that
> a CIPSO host is authorized to handle.  All datagrams that have a label
> greater than this maximum MUST be rejected by the CIPSO host.  This
> parameter does not apply to CIPSO gateways or routers.  This parameter need
> not be defined explicitly as it can be implicitly derived from the
> PORT_LABEL_MAX parameters for the associated interfaces.
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 7]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
>
> HOST_LABEL_MIN - This parameter contains the minimum sensitivity label that
> a CIPSO host is authorized to handle.  All datagrams that have a label less
> than this minimum MUST be rejected by the CIPSO host.  This parameter does
> not apply to CIPSO gateways or routers.  This parameter need not be defined
> explicitly as it can be implicitly derived from the PORT_LABEL_MIN
> parameters for the associated interfaces.
>
> PORT_LABEL_MAX - This parameter contains the maximum sensitivity label for
> all datagrams that may exit a particular network interface port.  All
> outgoing datagrams that have a label greater than this maximum MUST be
> rejected by the CIPSO system.  The label within this parameter MUST be
> less than or equal to the label within the HOST_LABEL_MAX parameter.  This
> parameter does not apply to CIPSO hosts that support only one network port.
>
> PORT_LABEL_MIN - This parameter contains the minimum sensitivity label for
> all datagrams that may exit a particular network interface port.  All
> outgoing datagrams that have a label less than this minimum MUST be
> rejected by the CIPSO system.  The label within this parameter MUST be
> greater than or equal to the label within the HOST_LABEL_MIN parameter.
> This parameter does not apply to CIPSO hosts that support only one network
> port.
>
> PORT_DOI - This parameter is used to assign a DOI identifier value to a
> particular network interface port.  All CIPSO labels within datagrams
> going out this port MUST use the specified DOI identifier.  All CIPSO
> hosts and gateways MUST support either this parameter, the NET_DOI
> parameter, or the HOST_DOI parameter.
>
> NET_DOI - This parameter is used to assign a DOI identifier value to a
> particular IP network address.  All CIPSO labels within datagrams destined
> for the particular IP network MUST use the specified DOI identifier.  All
> CIPSO hosts and gateways MUST support either this parameter, the PORT_DOI
> parameter, or the HOST_DOI parameter.
>
> HOST_DOI - This parameter is used to assign a DOI identifier value to a
> particular IP host address.  All CIPSO labels within datagrams destined for
> the particular IP host will use the specified DOI identifier.  All CIPSO
> hosts and gateways MUST support either this parameter, the PORT_DOI
> parameter, or the NET_DOI parameter.
>
> This list represents the minimal set of configuration parameters required
> to be compliant.  Implementors are encouraged to add to this list to
> provide enhanced functionality and control.  For example, many security
> policies may require both incoming and outgoing datagrams be checked against
> the port and host label ranges.
>
>
> 4.1    Port Range Parameters
>
> The labels represented by the PORT_LABEL_MAX and PORT_LABEL_MIN parameters
> MAY be in CIPSO or local format.  Some CIPSO systems, such as routers, may
> want to have the range parameters expressed in CIPSO format so that incoming
> labels do not have to be converted to a local format before being compared
> against the range.  If multiple DOIs are supported by one of these CIPSO
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 8]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> systems then multiple port range parameters would be needed, one set for
> each DOI supported on a particular port.
>
> The port range will usually represent the total set of labels that may
> exist on the logical network accessed through the corresponding network
> interface.  It may, however, represent a subset of these labels that are
> allowed to enter the CIPSO system.
>
>
> 4.2    Single Label CIPSO Hosts
>
> CIPSO implementations that support only one label are not required to
> support the parameters described above.  These limited implementations are
> only required to support a NET_LABEL parameter.  This parameter contains
> the CIPSO label that may be inserted in datagrams that exit the host.  In
> addition, the host MUST reject any incoming datagram that has a label which
> is not equivalent to the NET_LABEL parameter.
>
>
> 5.    Handling Procedures
>
> This section describes the processing requirements for incoming and
> outgoing IP datagrams.  Just providing the correct CIPSO label format
> is not enough.  Assumptions will be made by one system on how a
> receiving system will handle the CIPSO label.  Wrong assumptions may
> lead to non-interoperability or even a security incident.  The
> requirements described below represent the minimal set needed for
> interoperability and that provide users some level of confidence.
> Many other requirements could be added to increase user confidence,
> however at the risk of restricting creativity and limiting vendor
> participation.
>
>
> 5.1    Input Procedures
>
> All datagrams received through a network port MUST have a security label
> associated with them, either contained in the datagram or assigned to the
> receiving port.  Without this label the host, gateway, or router will not
> have the information it needs to make security decisions.  This security
> label will be obtained from the CIPSO if the option is present in the
> datagram.  See section 4.1.2 for handling procedures for unlabeled
> datagrams.  This label will be compared against the PORT (if appropriate)
> and HOST configuration parameters defined in section 3.
>
> If any field within the CIPSO option, such as the DOI identifier, is not
> recognized the IP datagram is discarded and an ICMP "parameter problem"
> (type 12) is generated and returned.  The ICMP code field is set to "bad
> parameter" (code 0) and the pointer is set to the start of the CIPSO field
> that is unrecognized.
>
> If the contents of the CIPSO are valid but the security label is
> outside of the configured host or port label range, the datagram is
> discarded and an ICMP "destination unreachable" (type 3) is generated
> and returned.  The code field of the ICMP is set to "communication with
> destination network administratively prohibited" (code 9) or to
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 9]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> "communication with destination host administratively prohibited"
> (code 10).  The value of the code field used is dependent upon whether
> the originator of the ICMP message is acting as a CIPSO host or a CIPSO
> gateway.  The recipient of the ICMP message MUST be able to handle either
> value.  The same procedure is performed if a CIPSO can not be added to an
> IP packet because it is too large to fit in the IP options area.
>
> If the error is triggered by receipt of an ICMP message, the message
> is discarded and no response is permitted (consistent with general ICMP
> processing rules).
>
>
> 5.1.1    Unrecognized tag types
>
> The default condition for any CIPSO implementation is that an
> unrecognized tag type MUST be treated as a "parameter problem" and
> handled as described in section 4.1.  A CIPSO implementation MAY allow
> the system administrator to identify tag types that may safely be
> ignored.  This capability is an allowable enhancement, not a
> requirement.
>
>
> 5.1.2    Unlabeled Packets
>
> A network port may be configured to not require a CIPSO label for all
> incoming  datagrams.  For this configuration a CIPSO label must be
> assigned to that network port and associated with all unlabeled IP
> datagrams.  This capability might be used for single level networks or
> networks that have CIPSO and non-CIPSO hosts and the non-CIPSO hosts
> all operate at the same label.
>
> If a CIPSO option is required and none is found, the datagram is
> discarded and an ICMP "parameter problem" (type 12) is generated and
> returned to the originator of the datagram.  The code field of the ICMP
> is set to "option missing" (code 1) and the ICMP pointer is set to 134
> (the value of the option type for the missing CIPSO option).
>
>
> 5.2    Output Procedures
>
> A CIPSO option MUST appear only once in a datagram.  Only one tag type
> from the MAC Sensitivity class MAY be included in a CIPSO option.  Given
> the current set of defined tag types, this means that CIPSO labels at
> first will contain only one tag.
>
> All datagrams leaving a CIPSO system MUST meet the following condition:
>
>         PORT_LABEL_MIN <= CIPSO label <= PORT_LABEL_MAX
>
> If this condition is not satisfied the datagram MUST be discarded.
> If the CIPSO system only supports one port, the HOST_LABEL_MIN and the
> HOST_LABEL_MAX parameters MAY be substituted for the PORT parameters in
> the above condition.
>
> The DOI identifier to be used for all outgoing datagrams is configured by
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 10]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
> the administrator.  If port level DOI identifier assignment is used, then
> the PORT_DOI configuration parameter MUST contain the DOI identifier to
> use.  If network level DOI assignment is used, then the NET_DOI parameter
> MUST contain the DOI identifier to use.  And if host level DOI assignment
> is employed, then the HOST_DOI parameter MUST contain the DOI identifier
> to use.  A CIPSO implementation need only support one level of DOI
> assignment.
>
>
> 5.3    DOI Processing Requirements
>
> A CIPSO implementation MUST support at least one DOI and SHOULD support
> multiple DOIs.  System and network administrators are cautioned to
> ensure that at least one DOI is common within an IP network to allow for
> broadcasting of IP datagrams.
>
> CIPSO gateways MUST be capable of translating a CIPSO option from one
> DOI to another when forwarding datagrams between networks.  For
> efficiency purposes this capability is only a desired feature for CIPSO
> routers.
>
>
> 5.4    Label of ICMP Messages
>
> The CIPSO label to be used on all outgoing ICMP messages MUST be equivalent
> to the label of the datagram that caused the ICMP message.  If the ICMP was
> generated due to a problem associated with the original CIPSO label then the
> following responses are allowed:
>
>   a.  Use the CIPSO label of the original IP datagram
>   b.  Drop the original datagram with no return message generated
>
> In most cases these options will have the same effect.  If you can not
> interpret the label or if it is outside the label range of your host or
> interface then an ICMP message with the same label will probably not be
> able to exit the system.
>
>
> 6.    Assignment of DOI Identifier Numbers                                   =
>
> Requests for assignment of a DOI identifier number should be addressed to
> the Internet Assigned Numbers Authority (IANA).
>
>
> 7.    Acknowledgements
>
> Much of the material in this RFC is based on (and copied from) work
> done by Gary Winiger of Sun Microsystems and published as Commercial
> IP Security Option at the INTEROP 89, Commercial IPSO Workshop.
>
>
> 8.    Author's Address
>
> To submit mail for distribution to members of the IETF CIPSO Working
> Group, send mail to: cipso@wdl1.wdl.loral.com.
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 11]
>
>
>
> CIPSO INTERNET DRAFT                                         16 July, 1992
>
>
>
>
> To be added to or deleted from this distribution, send mail to:
> cipso-request@wdl1.wdl.loral.com.
>
>
> 9.    References
>
> RFC 1038, "Draft Revised IP Security Option", M. St. Johns, IETF, January
> 1988.
>
> RFC 1108, "U.S. Department of Defense Security Options
> for the Internet Protocol", Stephen Kent, IAB, 1 March, 1991.
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> Internet Draft, Expires 15 Jan 93                                 [PAGE 12]
>
>
>
>
> ```
>

---

# NetLabel Introduction

_Peios Kernel / Internals / Network labelling_

> Paul Moore, paul.moore@hp.com

<a id="rst-netlabel-introduction"></a>

Paul Moore, [paul.moore@hp.com](<mailto:paul.moore@hp.com>)

August 2, 2006

<a id="rst-overview"></a>

## Overview

NetLabel is a mechanism which can be used by kernel security modules to attach security attributes to outgoing network packets generated from user space applications and read security attributes from incoming network packets.  It is composed of three main components, the protocol engines, the communication layer, and the kernel security module API.

<a id="rst-protocol-engines"></a>

## Protocol Engines

The protocol engines are responsible for both applying and retrieving the network packet's security attributes.  If any translation between the network security attributes and those on the host are required then the protocol engine will handle those tasks as well.  Other kernel subsystems should refrain from calling the protocol engines directly, instead they should use the NetLabel kernel security module API described below.

Detailed information about each NetLabel protocol engine can be found in this directory.

<a id="rst-communication-layer"></a>

## Communication Layer

The communication layer exists to allow NetLabel configuration and monitoring from user space.  The NetLabel communication layer uses a message based protocol built on top of the Generic NETLINK transport mechanism.  The exact formatting of these NetLabel messages as well as the Generic NETLINK family names can be found in the 'net/netlabel/' directory as comments in the header files as well as in 'include/net/netlabel.h'.

<a id="rst-security-module-api"></a>

## Security Module API

The purpose of the NetLabel security module API is to provide a protocol independent interface to the underlying NetLabel protocol engines.  In addition to protocol independence, the security module API is designed to be completely LSM independent which should allow multiple LSMs to leverage the same code base.

Detailed information about the NetLabel security module API can be found in the 'include/net/netlabel.h' header file as well as the 'lsm_interface.txt' file found in this directory.

---

# NetLabel Linux Security Module Interface

_Peios Kernel / Internals / Network labelling_

> Paul Moore, paul.moore@hp.com

<a id="rst-netlabel-linux-security-module-interface"></a>

Paul Moore, [paul.moore@hp.com](<mailto:paul.moore@hp.com>)

May 17, 2006

<a id="rst-overview"></a>

## Overview

NetLabel is a mechanism which can set and retrieve security attributes from network packets.  It is intended to be used by LSM developers who want to make use of a common code base for several different packet labeling protocols. The NetLabel security module API is defined in 'include/net/netlabel.h' but a brief overview is given below.

<a id="rst-netlabel-security-attributes"></a>

## NetLabel Security Attributes

Since NetLabel supports multiple different packet labeling protocols and LSMs it uses the concept of security attributes to refer to the packet's security labels.  The NetLabel security attributes are defined by the 'netlbl_lsm_secattr' structure in the NetLabel header file.  Internally the NetLabel subsystem converts the security attributes to and from the correct low-level packet label depending on the NetLabel build time and run time configuration.  It is up to the LSM developer to translate the NetLabel security attributes into whatever security identifiers are in use for their particular LSM.

<a id="rst-netlabel-lsm-protocol-operations"></a>

## NetLabel LSM Protocol Operations

These are the functions which allow the LSM developer to manipulate the labels on outgoing packets as well as read the labels on incoming packets.  Functions exist to operate both on sockets as well as the sk_buffs directly.  These high level functions are translated into low level protocol operations based on how the administrator has configured the NetLabel subsystem.

<a id="rst-netlabel-label-mapping-cache-operations"></a>

## NetLabel Label Mapping Cache Operations

Depending on the exact configuration, translation between the network packet label and the internal LSM security identifier can be time consuming.  The NetLabel label mapping cache is a caching mechanism which can be used to sidestep much of this overhead once a mapping has been established.  Once the LSM has received a packet, used NetLabel to decode its security attributes, and translated the security attributes into a LSM internal identifier the LSM can use the NetLabel caching functions to associate the LSM internal identifier with the network packet's label.  This means that in the future when a incoming packet matches a cached value not only are the internal NetLabel translation mechanisms bypassed but the LSM translation mechanisms are bypassed as well which should result in a significant reduction in overhead.

---

# Netlink Family Specifications

_Peios Kernel / Internals / Netlink / specs_

> Reference for Netlink Family Specifications.

<a id="rst-netlink-family-specifications"></a>
<a id="rst-specs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Family binder netlink specification](</kernel/internals/netlink/specs/binder.md>)
- [Family conntrack netlink specification](</kernel/internals/netlink/specs/conntrack.md>)
- [Family dev-energymodel netlink specification](</kernel/internals/netlink/specs/dev-energymodel.md>)
- [Family devlink netlink specification](</kernel/internals/netlink/specs/devlink.md>)
- [Family dpll netlink specification](</kernel/internals/netlink/specs/dpll.md>)
- [Family ethtool netlink specification](</kernel/internals/netlink/specs/ethtool.md>)
- [Family fou netlink specification](</kernel/internals/netlink/specs/fou.md>)
- [Family handshake netlink specification](</kernel/internals/netlink/specs/handshake.md>)
- [Family lockd netlink specification](</kernel/internals/netlink/specs/lockd.md>)
- [Family mptcp_pm netlink specification](</kernel/internals/netlink/specs/mptcp-pm.md>)
- [Family net-shaper netlink specification](</kernel/internals/netlink/specs/net-shaper.md>)
- [Family netdev netlink specification](</kernel/internals/netlink/specs/netdev.md>)
- [Family nfsd netlink specification](</kernel/internals/netlink/specs/nfsd.md>)
- [Family nftables netlink specification](</kernel/internals/netlink/specs/nftables.md>)
- [Family nl80211 netlink specification](</kernel/internals/netlink/specs/nl80211.md>)
- [Family nlctrl netlink specification](</kernel/internals/netlink/specs/nlctrl.md>)
- [Family ovpn netlink specification](</kernel/internals/netlink/specs/ovpn.md>)
- [Family ovs_datapath netlink specification](</kernel/internals/netlink/specs/ovs-datapath.md>)
- [Family ovs_flow netlink specification](</kernel/internals/netlink/specs/ovs-flow.md>)
- [Family ovs_vport netlink specification](</kernel/internals/netlink/specs/ovs-vport.md>)
- [Family psp netlink specification](</kernel/internals/netlink/specs/psp.md>)
- [Family rt-addr netlink specification](</kernel/internals/netlink/specs/rt-addr.md>)
- [Family rt-link netlink specification](</kernel/internals/netlink/specs/rt-link.md>)
- [Family rt-neigh netlink specification](</kernel/internals/netlink/specs/rt-neigh.md>)
- [Family rt-route netlink specification](</kernel/internals/netlink/specs/rt-route.md>)
- [Family rt-rule netlink specification](</kernel/internals/netlink/specs/rt-rule.md>)
- [Family tc netlink specification](</kernel/internals/netlink/specs/tc.md>)
- [Family tcp_metrics netlink specification](</kernel/internals/netlink/specs/tcp-metrics.md>)
- [Family team netlink specification](</kernel/internals/netlink/specs/team.md>)
- [Family wireguard netlink specification](</kernel/internals/netlink/specs/wireguard.md>)

---

# Family binder netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the binder Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-binder-netlink-specification"></a>
<a id="rst-netlink-binder"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Binder interface over generic netlink

<a id="rst-operations"></a>



## Operations

<a id="rst-report"></a>
<a id="rst-binder-operation-report"></a>



### report



A multicast event sent to userspace subscribers to notify them about
binder transaction failures. The generated report provides the full
details of the specific transaction that failed. The intention is for
programs to monitor these events and react to the failures as needed.

- **attribute-set**:

  [report](#rst-binder-attribute-set-report)

- **mcgrp**:

  report

- **event**:

  - **attributes**:

    \[`error`, `context`, `from-pid`, `from-tid`, `to-pid`, `to-tid`, `is-reply`, `flags`, `code`, `data-size`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- report


<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-report-1"></a>
<a id="rst-binder-attribute-set-report"></a>



### report



Attributes included within a transaction failure report. The elements
correspond directly with the specific transaction that failed, along
with the error returned to the sender e.g. BR\_DEAD\_REPLY.

<a id="rst-error-u32"></a>



#### error (`u32`)

- **doc**:

  The enum binder\_driver\_return\_protocol returned to the sender.

<a id="rst-context-string"></a>



#### context (`string`)

- **doc**:

  The binder context where the transaction occurred.

<a id="rst-from-pid-u32"></a>



#### from-pid (`u32`)

- **doc**:

  The PID of the sender process.

<a id="rst-from-tid-u32"></a>



#### from-tid (`u32`)

- **doc**:

  The TID of the sender thread.

<a id="rst-to-pid-u32"></a>



#### to-pid (`u32`)

- **doc**:

  The PID of the recipient process. This attribute may not be present if the target could not be determined.

<a id="rst-to-tid-u32"></a>



#### to-tid (`u32`)

- **doc**:

  The TID of the recipient thread. This attribute may not be present if the target could not be determined.

<a id="rst-is-reply-flag"></a>



#### is-reply (`flag`)

- **doc**:

  When present, indicates the failed transaction is a reply.

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **doc**:

  The bitmask of enum transaction\_flags from the transaction.

<a id="rst-code-u32"></a>



#### code (`u32`)

- **doc**:

  The application-defined code from the transaction.

<a id="rst-data-size-u32"></a>



#### data-size (`u32`)

- **doc**:

  The transaction payload size in bytes.

---

# Family conntrack netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the conntrack Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-conntrack-netlink-specification"></a>
<a id="rst-netlink-conntrack"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netfilter connection tracking subsystem over nfnetlink

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-conntrack-operation-get"></a>



### get



get / dump entries

- **attribute-set**:

  [conntrack-attrs](#rst-conntrack-attribute-set-conntrack-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-conntrack-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`tuple-orig`, `tuple-reply`, `zone`\]

  **reply**

  - **attributes**:

    \[`tuple-orig`, `tuple-reply`, `status`, `protoinfo`, `help`, `nat-src`, `nat-dst`, `timeout`, `mark`, `counters-orig`, `counters-reply`, `use`, `id`, `nat-dst`, `tuple-master`, `seq-adj-orig`, `seq-adj-reply`, `zone`, `secctx`, `labels`, `synproxy`\]

- **dump**:

  **request**

  - **attributes**:

    \[`mark`, `filter`, `status`, `zone`\]

  **reply**

  - **attributes**:

    \[`tuple-orig`, `tuple-reply`, `status`, `protoinfo`, `help`, `nat-src`, `nat-dst`, `timeout`, `mark`, `counters-orig`, `counters-reply`, `use`, `id`, `nat-dst`, `tuple-master`, `seq-adj-orig`, `seq-adj-reply`, `zone`, `secctx`, `labels`, `synproxy`\]

<a id="rst-get-stats"></a>
<a id="rst-conntrack-operation-get-stats"></a>



### get-stats



dump pcpu conntrack stats

- **attribute-set**:

  [conntrack-stats-attrs](#rst-conntrack-attribute-set-conntrack-stats-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-conntrack-definition-nfgenmsg)

- **dump**:

  **request**

  **reply**

  - **attributes**:

    \[`searched`, `found`, `insert`, `insert-failed`, `drop`, `early-drop`, `error`, `search-restart`, `clash-resolve`, `chain-toolong`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-nfgenmsg"></a>
<a id="rst-conntrack-definition-nfgenmsg"></a>



### nfgenmsg

- **type**:

  struct

- **members**:

  - **nfgen-family (`u8`)**

  - **version (`u8`)**

  - **res-id (`u16`)**

<a id="rst-nf-ct-tcp-flags-mask"></a>
<a id="rst-conntrack-definition-nf-ct-tcp-flags-mask"></a>



### nf-ct-tcp-flags-mask

- **type**:

  struct

- **members**:

  - **flags (`u8`)**

  - **mask (`u8`)**

<a id="rst-nf-ct-tcp-flags"></a>
<a id="rst-conntrack-definition-nf-ct-tcp-flags"></a>



### nf-ct-tcp-flags

- **type**:

  flags

- **entries**:

  - `window-scale`


  - `sack-perm`


  - `close-init`


  - `be-liberal`


  - `unacked`


  - `maxack`


  - `challenge-ack`


  - `simultaneous-open`

<a id="rst-nf-ct-tcp-state"></a>
<a id="rst-conntrack-definition-nf-ct-tcp-state"></a>



### nf-ct-tcp-state

- **type**:

  enum

- **entries**:

  - `none`


  - `syn-sent`


  - `syn-recv`


  - `established`


  - `fin-wait`


  - `close-wait`


  - `last-ack`


  - `time-wait`


  - `close`


  - `syn-sent2`


  - `max`


  - `ignore`


  - `retrans`


  - `unack`


  - `timeout-max`

<a id="rst-nf-ct-sctp-state"></a>
<a id="rst-conntrack-definition-nf-ct-sctp-state"></a>



### nf-ct-sctp-state

- **type**:

  enum

- **entries**:

  - `none`


  - `cloned`


  - `cookie-wait`


  - `cookie-echoed`


  - `established`


  - `shutdown-sent`


  - `shutdown-received`


  - `shutdown-ack-sent`


  - `shutdown-heartbeat-sent`

<a id="rst-nf-ct-status"></a>
<a id="rst-conntrack-definition-nf-ct-status"></a>



### nf-ct-status

- **type**:

  flags

- **entries**:

  - `expected`


  - `seen-reply`


  - `assured`


  - `confirmed`


  - `src-nat`


  - `dst-nat`


  - `seq-adj`


  - `src-nat-done`


  - `dst-nat-done`


  - `dying`


  - `fixed-timeout`


  - `template`


  - `nat-clash`


  - `helper`


  - `offload`


  - `hw-offload`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-counter-attrs"></a>
<a id="rst-conntrack-attribute-set-counter-attrs"></a>



### counter-attrs

<a id="rst-packets-u64"></a>



#### packets (`u64`)

- **byte-order**:

  big-endian

<a id="rst-bytes-u64"></a>



#### bytes (`u64`)

- **byte-order**:

  big-endian

<a id="rst-packets-old-u32"></a>



#### packets-old (`u32`)

<a id="rst-bytes-old-u32"></a>



#### bytes-old (`u32`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-tuple-proto-attrs"></a>
<a id="rst-conntrack-attribute-set-tuple-proto-attrs"></a>



### tuple-proto-attrs

<a id="rst-proto-num-u8"></a>



#### proto-num (`u8`)

- **doc**:

  l4 protocol number

<a id="rst-proto-src-port-u16"></a>



#### proto-src-port (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  l4 source port

<a id="rst-proto-dst-port-u16"></a>



#### proto-dst-port (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  l4 source port

<a id="rst-proto-icmp-id-u16"></a>



#### proto-icmp-id (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  l4 icmp id

<a id="rst-proto-icmp-type-u8"></a>



#### proto-icmp-type (`u8`)

<a id="rst-proto-icmp-code-u8"></a>



#### proto-icmp-code (`u8`)

<a id="rst-proto-icmpv6-id-u16"></a>



#### proto-icmpv6-id (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  l4 icmp id

<a id="rst-proto-icmpv6-type-u8"></a>



#### proto-icmpv6-type (`u8`)

<a id="rst-proto-icmpv6-code-u8"></a>



#### proto-icmpv6-code (`u8`)

<a id="rst-tuple-ip-attrs"></a>
<a id="rst-conntrack-attribute-set-tuple-ip-attrs"></a>



### tuple-ip-attrs

<a id="rst-ip-v4-src-u32"></a>



#### ip-v4-src (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

- **doc**:

  ipv4 source address

<a id="rst-ip-v4-dst-u32"></a>



#### ip-v4-dst (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

- **doc**:

  ipv4 destination address

<a id="rst-ip-v6-src-binary"></a>



#### ip-v6-src (`binary`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv6

- **doc**:

  ipv6 source address

<a id="rst-ip-v6-dst-binary"></a>



#### ip-v6-dst (`binary`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv6

- **doc**:

  ipv6 destination address

<a id="rst-tuple-attrs"></a>
<a id="rst-conntrack-attribute-set-tuple-attrs"></a>



### tuple-attrs

<a id="rst-tuple-ip-nest"></a>



#### tuple-ip (`nest`)

- **nested-attributes**:

  [tuple-ip-attrs](#rst-conntrack-attribute-set-tuple-ip-attrs)

- **doc**:

  conntrack l3 information

<a id="rst-tuple-proto-nest"></a>



#### tuple-proto (`nest`)

- **nested-attributes**:

  [tuple-proto-attrs](#rst-conntrack-attribute-set-tuple-proto-attrs)

- **doc**:

  conntrack l4 information

<a id="rst-tuple-zone-u16"></a>



#### tuple-zone (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  conntrack zone id

<a id="rst-protoinfo-tcp-attrs"></a>
<a id="rst-conntrack-attribute-set-protoinfo-tcp-attrs"></a>



### protoinfo-tcp-attrs

<a id="rst-tcp-state-u8"></a>



#### tcp-state (`u8`)

- **enum**:

  [nf-ct-tcp-state](#rst-conntrack-definition-nf-ct-tcp-state)

- **doc**:

  tcp connection state

<a id="rst-tcp-wscale-original-u8"></a>



#### tcp-wscale-original (`u8`)

- **doc**:

  window scaling factor in original direction

<a id="rst-tcp-wscale-reply-u8"></a>



#### tcp-wscale-reply (`u8`)

- **doc**:

  window scaling factor in reply direction

<a id="rst-tcp-flags-original-binary"></a>



#### tcp-flags-original (`binary`)

- **struct**:

  [nf-ct-tcp-flags-mask](#rst-conntrack-definition-nf-ct-tcp-flags-mask)

<a id="rst-tcp-flags-reply-binary"></a>



#### tcp-flags-reply (`binary`)

- **struct**:

  [nf-ct-tcp-flags-mask](#rst-conntrack-definition-nf-ct-tcp-flags-mask)

<a id="rst-protoinfo-dccp-attrs"></a>
<a id="rst-conntrack-attribute-set-protoinfo-dccp-attrs"></a>



### protoinfo-dccp-attrs

<a id="rst-dccp-state-u8"></a>



#### dccp-state (`u8`)

- **doc**:

  dccp connection state

<a id="rst-dccp-role-u8"></a>



#### dccp-role (`u8`)

<a id="rst-dccp-handshake-seq-u64"></a>



#### dccp-handshake-seq (`u64`)

- **byte-order**:

  big-endian

<a id="rst-dccp-pad-pad"></a>



#### dccp-pad (`pad`)

<a id="rst-protoinfo-sctp-attrs"></a>
<a id="rst-conntrack-attribute-set-protoinfo-sctp-attrs"></a>



### protoinfo-sctp-attrs

<a id="rst-sctp-state-u8"></a>



#### sctp-state (`u8`)

- **doc**:

  sctp connection state

- **enum**:

  [nf-ct-sctp-state](#rst-conntrack-definition-nf-ct-sctp-state)

<a id="rst-vtag-original-u32"></a>



#### vtag-original (`u32`)

- **byte-order**:

  big-endian

<a id="rst-vtag-reply-u32"></a>



#### vtag-reply (`u32`)

- **byte-order**:

  big-endian

<a id="rst-protoinfo-attrs"></a>
<a id="rst-conntrack-attribute-set-protoinfo-attrs"></a>



### protoinfo-attrs

<a id="rst-protoinfo-tcp-nest"></a>



#### protoinfo-tcp (`nest`)

- **nested-attributes**:

  [protoinfo-tcp-attrs](#rst-conntrack-attribute-set-protoinfo-tcp-attrs)

- **doc**:

  conntrack tcp state information

<a id="rst-protoinfo-dccp-nest"></a>



#### protoinfo-dccp (`nest`)

- **nested-attributes**:

  [protoinfo-dccp-attrs](#rst-conntrack-attribute-set-protoinfo-dccp-attrs)

- **doc**:

  conntrack dccp state information

<a id="rst-protoinfo-sctp-nest"></a>



#### protoinfo-sctp (`nest`)

- **nested-attributes**:

  [protoinfo-sctp-attrs](#rst-conntrack-attribute-set-protoinfo-sctp-attrs)

- **doc**:

  conntrack sctp state information

<a id="rst-help-attrs"></a>
<a id="rst-conntrack-attribute-set-help-attrs"></a>



### help-attrs

<a id="rst-help-name-string"></a>



#### help-name (`string`)

- **doc**:

  helper name

<a id="rst-nat-proto-attrs"></a>
<a id="rst-conntrack-attribute-set-nat-proto-attrs"></a>



### nat-proto-attrs

<a id="rst-nat-port-min-u16"></a>



#### nat-port-min (`u16`)

- **byte-order**:

  big-endian

<a id="rst-nat-port-max-u16"></a>



#### nat-port-max (`u16`)

- **byte-order**:

  big-endian

<a id="rst-nat-attrs"></a>
<a id="rst-conntrack-attribute-set-nat-attrs"></a>



### nat-attrs

<a id="rst-nat-v4-minip-u32"></a>



#### nat-v4-minip (`u32`)

- **byte-order**:

  big-endian

<a id="rst-nat-v4-maxip-u32"></a>



#### nat-v4-maxip (`u32`)

- **byte-order**:

  big-endian

<a id="rst-nat-v6-minip-binary"></a>



#### nat-v6-minip (`binary`)

<a id="rst-nat-v6-maxip-binary"></a>



#### nat-v6-maxip (`binary`)

<a id="rst-nat-proto-nest"></a>



#### nat-proto (`nest`)

- **nested-attributes**:

  [nat-proto-attrs](#rst-conntrack-attribute-set-nat-proto-attrs)

<a id="rst-seqadj-attrs"></a>
<a id="rst-conntrack-attribute-set-seqadj-attrs"></a>



### seqadj-attrs

<a id="rst-correction-pos-u32"></a>



#### correction-pos (`u32`)

- **byte-order**:

  big-endian

<a id="rst-offset-before-u32"></a>



#### offset-before (`u32`)

- **byte-order**:

  big-endian

<a id="rst-offset-after-u32"></a>



#### offset-after (`u32`)

- **byte-order**:

  big-endian

<a id="rst-secctx-attrs"></a>
<a id="rst-conntrack-attribute-set-secctx-attrs"></a>



### secctx-attrs

<a id="rst-secctx-name-string"></a>



#### secctx-name (`string`)

<a id="rst-synproxy-attrs"></a>
<a id="rst-conntrack-attribute-set-synproxy-attrs"></a>



### synproxy-attrs

<a id="rst-isn-u32"></a>



#### isn (`u32`)

- **byte-order**:

  big-endian

<a id="rst-its-u32"></a>



#### its (`u32`)

- **byte-order**:

  big-endian

<a id="rst-tsoff-u32"></a>



#### tsoff (`u32`)

- **byte-order**:

  big-endian

<a id="rst-conntrack-attrs"></a>
<a id="rst-conntrack-attribute-set-conntrack-attrs"></a>



### conntrack-attrs

<a id="rst-tuple-orig-nest"></a>



#### tuple-orig (`nest`)

- **nested-attributes**:

  [tuple-attrs](#rst-conntrack-attribute-set-tuple-attrs)

- **doc**:

  conntrack l3+l4 protocol information, original direction

<a id="rst-tuple-reply-nest"></a>



#### tuple-reply (`nest`)

- **nested-attributes**:

  [tuple-attrs](#rst-conntrack-attribute-set-tuple-attrs)

- **doc**:

  conntrack l3+l4 protocol information, reply direction

<a id="rst-status-u32"></a>



#### status (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [nf-ct-status](#rst-conntrack-definition-nf-ct-status)

- **enum-as-flags**:

  True

- **doc**:

  conntrack flag bits

<a id="rst-protoinfo-nest"></a>



#### protoinfo (`nest`)

- **nested-attributes**:

  [protoinfo-attrs](#rst-conntrack-attribute-set-protoinfo-attrs)

<a id="rst-help-nest"></a>



#### help (`nest`)

- **nested-attributes**:

  [help-attrs](#rst-conntrack-attribute-set-help-attrs)

<a id="rst-nat-src-nest"></a>



#### nat-src (`nest`)

- **nested-attributes**:

  [nat-attrs](#rst-conntrack-attribute-set-nat-attrs)

<a id="rst-timeout-u32"></a>



#### timeout (`u32`)

- **byte-order**:

  big-endian

<a id="rst-mark-u32"></a>



#### mark (`u32`)

- **byte-order**:

  big-endian

<a id="rst-counters-orig-nest"></a>



#### counters-orig (`nest`)

- **nested-attributes**:

  [counter-attrs](#rst-conntrack-attribute-set-counter-attrs)

<a id="rst-counters-reply-nest"></a>



#### counters-reply (`nest`)

- **nested-attributes**:

  [counter-attrs](#rst-conntrack-attribute-set-counter-attrs)

<a id="rst-use-u32"></a>



#### use (`u32`)

- **byte-order**:

  big-endian

<a id="rst-id-u32"></a>



#### id (`u32`)

- **byte-order**:

  big-endian

<a id="rst-nat-dst-nest"></a>



#### nat-dst (`nest`)

- **nested-attributes**:

  [nat-attrs](#rst-conntrack-attribute-set-nat-attrs)

<a id="rst-tuple-master-nest"></a>



#### tuple-master (`nest`)

- **nested-attributes**:

  [tuple-attrs](#rst-conntrack-attribute-set-tuple-attrs)

<a id="rst-seq-adj-orig-nest"></a>



#### seq-adj-orig (`nest`)

- **nested-attributes**:

  [seqadj-attrs](#rst-conntrack-attribute-set-seqadj-attrs)

<a id="rst-seq-adj-reply-nest"></a>



#### seq-adj-reply (`nest`)

- **nested-attributes**:

  [seqadj-attrs](#rst-conntrack-attribute-set-seqadj-attrs)

<a id="rst-secmark-binary"></a>



#### secmark (`binary`)

- **doc**:

  obsolete

<a id="rst-zone-u16"></a>



#### zone (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  conntrack zone id

<a id="rst-secctx-nest"></a>



#### secctx (`nest`)

- **nested-attributes**:

  [secctx-attrs](#rst-conntrack-attribute-set-secctx-attrs)

<a id="rst-timestamp-u64"></a>



#### timestamp (`u64`)

- **byte-order**:

  big-endian

<a id="rst-mark-mask-u32"></a>



#### mark-mask (`u32`)

- **byte-order**:

  big-endian

<a id="rst-labels-binary"></a>



#### labels (`binary`)

<a id="rst-labels-mask-binary"></a>



#### labels-mask (`binary`)

<a id="rst-synproxy-nest"></a>



#### synproxy (`nest`)

- **nested-attributes**:

  [synproxy-attrs](#rst-conntrack-attribute-set-synproxy-attrs)

<a id="rst-filter-nest"></a>



#### filter (`nest`)

- **nested-attributes**:

  [tuple-attrs](#rst-conntrack-attribute-set-tuple-attrs)

<a id="rst-status-mask-u32"></a>



#### status-mask (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [nf-ct-status](#rst-conntrack-definition-nf-ct-status)

- **enum-as-flags**:

  True

- **doc**:

  conntrack flag bits to change

<a id="rst-timestamp-event-u64"></a>



#### timestamp-event (`u64`)

- **byte-order**:

  big-endian

<a id="rst-conntrack-stats-attrs"></a>
<a id="rst-conntrack-attribute-set-conntrack-stats-attrs"></a>



### conntrack-stats-attrs

<a id="rst-searched-u32"></a>



#### searched (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-found-u32"></a>



#### found (`u32`)

- **byte-order**:

  big-endian

<a id="rst-new-u32"></a>



#### new (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-invalid-u32"></a>



#### invalid (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-ignore-u32"></a>



#### ignore (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-delete-u32"></a>



#### delete (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-delete-list-u32"></a>



#### delete-list (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  obsolete

<a id="rst-insert-u32"></a>



#### insert (`u32`)

- **byte-order**:

  big-endian

<a id="rst-insert-failed-u32"></a>



#### insert-failed (`u32`)

- **byte-order**:

  big-endian

<a id="rst-drop-u32"></a>



#### drop (`u32`)

- **byte-order**:

  big-endian

<a id="rst-early-drop-u32"></a>



#### early-drop (`u32`)

- **byte-order**:

  big-endian

<a id="rst-error-u32"></a>



#### error (`u32`)

- **byte-order**:

  big-endian

<a id="rst-search-restart-u32"></a>



#### search-restart (`u32`)

- **byte-order**:

  big-endian

<a id="rst-clash-resolve-u32"></a>



#### clash-resolve (`u32`)

- **byte-order**:

  big-endian

<a id="rst-chain-toolong-u32"></a>



#### chain-toolong (`u32`)

- **byte-order**:

  big-endian

---

# Family dev-energymodel netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the dev-energymodel Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-dev-energymodel-netlink-specification"></a>
<a id="rst-netlink-dev-energymodel"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Energy model netlink interface to notify its changes.

<a id="rst-operations"></a>



## Operations

<a id="rst-get-perf-domains"></a>
<a id="rst-dev-energymodel-operation-get-perf-domains"></a>



### get-perf-domains



Get the list of information for all performance domains.

- **attribute-set**:

  [perf-domain](#rst-dev-energymodel-attribute-set-perf-domain)

- **do**:

  **request**

  - **attributes**:

    \[`perf-domain-id`\]

  **reply**

  - **attributes**:

    \[`pad`, `perf-domain-id`, `flags`, `cpus`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`pad`, `perf-domain-id`, `flags`, `cpus`\]

<a id="rst-get-perf-table"></a>
<a id="rst-dev-energymodel-operation-get-perf-table"></a>



### get-perf-table



Get the energy model table of a performance domain.

- **attribute-set**:

  [perf-table](#rst-dev-energymodel-attribute-set-perf-table)

- **do**:

  **request**

  - **attributes**:

    \[`perf-domain-id`\]

  **reply**

  - **attributes**:

    \[`perf-domain-id`, `perf-state`\]

<a id="rst-perf-domain-created"></a>
<a id="rst-dev-energymodel-operation-perf-domain-created"></a>



### perf-domain-created



A performance domain is created.

- **notify**:

  get-perf-table

- **mcgrp**:

  event

<a id="rst-perf-domain-updated"></a>
<a id="rst-dev-energymodel-operation-perf-domain-updated"></a>



### perf-domain-updated



A performance domain is updated.

- **notify**:

  get-perf-table

- **mcgrp**:

  event

<a id="rst-perf-domain-deleted"></a>
<a id="rst-dev-energymodel-operation-perf-domain-deleted"></a>



### perf-domain-deleted



A performance domain is deleted.

- **attribute-set**:

  [perf-table](#rst-dev-energymodel-attribute-set-perf-table)

- **mcgrp**:

  event

- **event**:

  - **attributes**:

    \[`perf-domain-id`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- event


<a id="rst-definitions"></a>



## Definitions

<a id="rst-perf-state-flags"></a>
<a id="rst-dev-energymodel-definition-perf-state-flags"></a>



### perf-state-flags

- **type**:

  flags

- **entries**:

  - **perf-state-inefficient**:

    The performance state is inefficient. There is in this perf-domain, another performance state with a higher frequency but a lower or equal power cost.

<a id="rst-perf-domain-flags"></a>
<a id="rst-dev-energymodel-definition-perf-domain-flags"></a>



### perf-domain-flags

- **type**:

  flags

- **entries**:

  - **perf-domain-microwatts**:

    The power values are in micro-Watts or some other scale.

  - **perf-domain-skip-inefficiencies**:

    Skip inefficient states when estimating energy consumption.

  - **perf-domain-artificial**:

    The power values are artificial and might be created by platform missing real power information.

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-perf-domain"></a>
<a id="rst-dev-energymodel-attribute-set-perf-domain"></a>



### perf-domain



Information on a single performance domains.

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-perf-domain-id-u32"></a>



#### perf-domain-id (`u32`)

- **doc**:

  A unique ID number for each performance domain.

<a id="rst-flags-u64"></a>



#### flags (`u64`)

- **doc**:

  Bitmask of performance domain flags.

- **enum**:

  [perf-domain-flags](#rst-dev-energymodel-definition-perf-domain-flags)

<a id="rst-cpus-u64"></a>



#### cpus (`u64`)

- **multi-attr**:

  True

- **doc**:

  CPUs that belong to this performance domain.

<a id="rst-perf-table"></a>
<a id="rst-dev-energymodel-attribute-set-perf-table"></a>



### perf-table



Performance states table.

<a id="rst-perf-domain-id-u32-1"></a>



#### perf-domain-id (`u32`)

- **doc**:

  A unique ID number for each performance domain.

<a id="rst-perf-state-nest"></a>



#### perf-state (`nest`)

- **nested-attributes**:

  [perf-state](#rst-dev-energymodel-attribute-set-perf-state)

- **multi-attr**:

  True

<a id="rst-perf-state"></a>
<a id="rst-dev-energymodel-attribute-set-perf-state"></a>



### perf-state



Performance state of a performance domain.

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-performance-u64"></a>



#### performance (`u64`)

- **doc**:

  CPU performance (capacity) at a given frequency.

<a id="rst-frequency-u64"></a>



#### frequency (`u64`)

- **doc**:

  The frequency in KHz, for consistency with CPUFreq.

<a id="rst-power-u64"></a>



#### power (`u64`)

- **doc**:

  The power consumed at this level (by 1 CPU or by a registered device). It can be a total power: static and dynamic.

<a id="rst-cost-u64"></a>



#### cost (`u64`)

- **doc**:

  The cost coefficient associated with this level, used during energy calculation. Equal to: power \* max\_frequency / frequency.

<a id="rst-flags-u64-1"></a>



#### flags (`u64`)

- **doc**:

  Bitmask of performance state flags.

- **enum**:

  [perf-state-flags](#rst-dev-energymodel-definition-perf-state-flags)

---

# Family devlink netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the devlink Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-devlink-netlink-specification"></a>
<a id="rst-netlink-devlink"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Partial family for Devlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-devlink-operation-get"></a>



### get



Get devlink instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict', 'dump'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `reload-failed`, `dev-stats`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `reload-failed`, `dev-stats`\]

<a id="rst-port-get"></a>
<a id="rst-devlink-operation-port-get"></a>



### port-get



Get devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-port-set"></a>
<a id="rst-devlink-operation-port-set"></a>



### port-set



Set devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `port-type`, `port-function`\]

<a id="rst-port-new"></a>
<a id="rst-devlink-operation-port-new"></a>



### port-new



Create devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `port-flavour`, `port-pci-pf-number`, `port-pci-sf-number`, `port-controller-number`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-port-del"></a>
<a id="rst-devlink-operation-port-del"></a>



### port-del



Delete devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-port-split"></a>
<a id="rst-devlink-operation-port-split"></a>



### port-split



Split devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `port-split-count`\]

<a id="rst-port-unsplit"></a>
<a id="rst-devlink-operation-port-unsplit"></a>



### port-unsplit



Unplit devlink port instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-sb-get"></a>
<a id="rst-devlink-operation-sb-get"></a>



### sb-get



Get shared buffer instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`\]

<a id="rst-sb-pool-get"></a>
<a id="rst-devlink-operation-sb-pool-get"></a>



### sb-pool-get



Get shared buffer pool instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`, `sb-pool-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`, `sb-pool-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`, `sb-pool-index`\]

<a id="rst-sb-pool-set"></a>
<a id="rst-devlink-operation-sb-pool-set"></a>



### sb-pool-set



Set shared buffer pool instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`, `sb-pool-index`, `sb-pool-threshold-type`, `sb-pool-size`\]

<a id="rst-sb-port-pool-get"></a>
<a id="rst-devlink-operation-sb-port-pool-get"></a>



### sb-port-pool-get



Get shared buffer port-pool combinations and threshold.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-index`\]

<a id="rst-sb-port-pool-set"></a>
<a id="rst-devlink-operation-sb-port-pool-set"></a>



### sb-port-pool-set



Set shared buffer port-pool combinations and threshold.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-index`, `sb-threshold`\]

<a id="rst-sb-tc-pool-bind-get"></a>
<a id="rst-devlink-operation-sb-tc-pool-bind-get"></a>



### sb-tc-pool-bind-get



Get shared buffer port-TC to pool bindings and threshold.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-type`, `sb-tc-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-type`, `sb-tc-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-type`, `sb-tc-index`\]

<a id="rst-sb-tc-pool-bind-set"></a>
<a id="rst-devlink-operation-sb-tc-pool-bind-set"></a>



### sb-tc-pool-bind-set



Set shared buffer port-TC to pool bindings and threshold.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `sb-index`, `sb-pool-index`, `sb-pool-type`, `sb-tc-index`, `sb-threshold`\]

<a id="rst-sb-occ-snapshot"></a>
<a id="rst-devlink-operation-sb-occ-snapshot"></a>



### sb-occ-snapshot



Take occupancy snapshot of shared buffer.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`\]

<a id="rst-sb-occ-max-clear"></a>
<a id="rst-devlink-operation-sb-occ-max-clear"></a>



### sb-occ-max-clear



Clear occupancy watermarks of shared buffer.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `sb-index`\]

<a id="rst-eswitch-get"></a>
<a id="rst-devlink-operation-eswitch-get"></a>



### eswitch-get



Get eswitch attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `eswitch-mode`, `eswitch-inline-mode`, `eswitch-encap-mode`\]

<a id="rst-eswitch-set"></a>
<a id="rst-devlink-operation-eswitch-set"></a>



### eswitch-set



Set eswitch attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `eswitch-mode`, `eswitch-inline-mode`, `eswitch-encap-mode`\]

<a id="rst-dpipe-table-get"></a>
<a id="rst-devlink-operation-dpipe-table-get"></a>



### dpipe-table-get



Get dpipe table attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-table-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-tables`\]

<a id="rst-dpipe-entries-get"></a>
<a id="rst-devlink-operation-dpipe-entries-get"></a>



### dpipe-entries-get



Get dpipe entries attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-table-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-entries`\]

<a id="rst-dpipe-headers-get"></a>
<a id="rst-devlink-operation-dpipe-headers-get"></a>



### dpipe-headers-get



Get dpipe headers attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-headers`\]

<a id="rst-dpipe-table-counters-set"></a>
<a id="rst-devlink-operation-dpipe-table-counters-set"></a>



### dpipe-table-counters-set



Set dpipe counter attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `dpipe-table-name`, `dpipe-table-counters-enabled`\]

<a id="rst-resource-set"></a>
<a id="rst-devlink-operation-resource-set"></a>



### resource-set



Set resource attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `resource-id`, `resource-size`\]

<a id="rst-resource-dump"></a>
<a id="rst-devlink-operation-resource-dump"></a>



### resource-dump



Get resource attributes.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `resource-list`\]

<a id="rst-reload"></a>
<a id="rst-devlink-operation-reload"></a>



### reload



Reload devlink.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-dev-lock

  **post**



  devlink-nl-post-doit-dev-lock

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `reload-action`, `reload-limits`, `netns-pid`, `netns-fd`, `netns-id`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `reload-actions-performed`\]

<a id="rst-param-get"></a>
<a id="rst-devlink-operation-param-get"></a>



### param-get



Get param instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `param-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `param-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `param-name`\]

<a id="rst-param-set"></a>
<a id="rst-devlink-operation-param-set"></a>



### param-set



Set param instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `param-name`, `param-type`, `param-value-cmode`, `param-reset-default`\]

<a id="rst-region-get"></a>
<a id="rst-devlink-operation-region-get"></a>



### region-get



Get region instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`\]

<a id="rst-region-new"></a>
<a id="rst-devlink-operation-region-new"></a>



### region-new



Create region snapshot.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`, `region-snapshot-id`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`, `region-snapshot-id`\]

<a id="rst-region-del"></a>
<a id="rst-devlink-operation-region-del"></a>



### region-del



Delete region snapshot.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`, `region-snapshot-id`\]

<a id="rst-region-read"></a>
<a id="rst-devlink-operation-region-read"></a>



### region-read



Read region data.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['dump-strict'\]

- **flags**:

  \[`admin-perm`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`, `region-snapshot-id`, `region-direct`, `region-chunk-addr`, `region-chunk-len`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `region-name`\]

<a id="rst-port-param-get"></a>
<a id="rst-devlink-operation-port-param-get"></a>



### port-param-get



Get port param instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict', 'dump-strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-port-param-set"></a>
<a id="rst-devlink-operation-port-param-set"></a>



### port-param-set



Set port param instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-info-get"></a>
<a id="rst-devlink-operation-info-get"></a>



### info-get



Get device information, like driver name, hardware and firmware versions
etc.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict', 'dump'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `info-driver-name`, `info-serial-number`, `info-version-fixed`, `info-version-running`, `info-version-stored`, `info-board-serial-number`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `info-driver-name`, `info-serial-number`, `info-version-fixed`, `info-version-running`, `info-version-stored`, `info-board-serial-number`\]

<a id="rst-health-reporter-get"></a>
<a id="rst-devlink-operation-health-reporter-get"></a>



### health-reporter-get



Get health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

<a id="rst-health-reporter-set"></a>
<a id="rst-devlink-operation-health-reporter-set"></a>



### health-reporter-set



Set health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`, `health-reporter-graceful-period`, `health-reporter-auto-recover`, `health-reporter-auto-dump`, `health-reporter-burst-period`\]

<a id="rst-health-reporter-recover"></a>
<a id="rst-devlink-operation-health-reporter-recover"></a>



### health-reporter-recover



Recover health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

<a id="rst-health-reporter-diagnose"></a>
<a id="rst-devlink-operation-health-reporter-diagnose"></a>



### health-reporter-diagnose



Diagnose health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

<a id="rst-health-reporter-dump-get"></a>
<a id="rst-devlink-operation-health-reporter-dump-get"></a>



### health-reporter-dump-get



Dump health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['dump-strict'\]

- **flags**:

  \[`admin-perm`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

  **reply**

  - **attributes**:

    \[`fmsg`\]

<a id="rst-health-reporter-dump-clear"></a>
<a id="rst-devlink-operation-health-reporter-dump-clear"></a>



### health-reporter-dump-clear



Clear dump of health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

<a id="rst-flash-update"></a>
<a id="rst-devlink-operation-flash-update"></a>



### flash-update



Flash update devlink instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `flash-update-file-name`, `flash-update-component`, `flash-update-overwrite-mask`\]

<a id="rst-trap-get"></a>
<a id="rst-devlink-operation-trap-get"></a>



### trap-get



Get trap instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-name`\]

<a id="rst-trap-set"></a>
<a id="rst-devlink-operation-trap-set"></a>



### trap-set



Set trap instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-name`, `trap-action`\]

<a id="rst-trap-group-get"></a>
<a id="rst-devlink-operation-trap-group-get"></a>



### trap-group-get



Get trap group instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-group-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-group-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-group-name`\]

<a id="rst-trap-group-set"></a>
<a id="rst-devlink-operation-trap-group-set"></a>



### trap-group-set



Set trap group instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-group-name`, `trap-action`, `trap-policer-id`\]

<a id="rst-trap-policer-get"></a>
<a id="rst-devlink-operation-trap-policer-get"></a>



### trap-policer-get



Get trap policer instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-policer-id`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-policer-id`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-policer-id`\]

<a id="rst-trap-policer-set"></a>
<a id="rst-devlink-operation-trap-policer-set"></a>



### trap-policer-set



Get trap policer instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `trap-policer-id`, `trap-policer-rate`, `trap-policer-burst`\]

<a id="rst-health-reporter-test"></a>
<a id="rst-devlink-operation-health-reporter-test"></a>



### health-reporter-test



Test health reporter instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit-port-optional

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `health-reporter-name`\]

<a id="rst-rate-get"></a>
<a id="rst-devlink-operation-rate-get"></a>



### rate-get



Get rate instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `rate-node-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `rate-node-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`, `rate-node-name`\]

<a id="rst-rate-set"></a>
<a id="rst-devlink-operation-rate-set"></a>



### rate-set



Set rate instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `rate-node-name`, `rate-tx-share`, `rate-tx-max`, `rate-tx-priority`, `rate-tx-weight`, `rate-parent-node-name`, `rate-tc-bws`\]

<a id="rst-rate-new"></a>
<a id="rst-devlink-operation-rate-new"></a>



### rate-new



Create rate instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `rate-node-name`, `rate-tx-share`, `rate-tx-max`, `rate-tx-priority`, `rate-tx-weight`, `rate-parent-node-name`, `rate-tc-bws`\]

<a id="rst-rate-del"></a>
<a id="rst-devlink-operation-rate-del"></a>



### rate-del



Delete rate instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `rate-node-name`\]

<a id="rst-linecard-get"></a>
<a id="rst-devlink-operation-linecard-get"></a>



### linecard-get



Get line card instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `linecard-index`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `linecard-index`\]

- **dump**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`, `linecard-index`\]

<a id="rst-linecard-set"></a>
<a id="rst-devlink-operation-linecard-set"></a>



### linecard-set



Set line card instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `linecard-index`, `linecard-type`\]

<a id="rst-selftests-get"></a>
<a id="rst-devlink-operation-selftests-get"></a>



### selftests-get



Get device selftest instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict', 'dump'\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`bus-name`, `dev-name`\]

<a id="rst-selftests-run"></a>
<a id="rst-devlink-operation-selftests-run"></a>



### selftests-run



Run device selftest instances.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  devlink-nl-pre-doit

  **post**



  devlink-nl-post-doit

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `selftests`\]

<a id="rst-notify-filter-set"></a>
<a id="rst-devlink-operation-notify-filter-set"></a>



### notify-filter-set



Set notification messages socket filter.

- **attribute-set**:

  [devlink](#rst-devlink-attribute-set-devlink)

- **do**:

  **request**

  - **attributes**:

    \[`bus-name`, `dev-name`, `port-index`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-sb-pool-type"></a>
<a id="rst-devlink-definition-sb-pool-type"></a>



### sb-pool-type

- **type**:

  enum

- **entries**:

  - **ingress**

  - **egress**

<a id="rst-port-type"></a>
<a id="rst-devlink-definition-port-type"></a>



### port-type

- **type**:

  enum

- **entries**:

  - **notset**

  - **auto**

  - **eth**

  - **ib**

<a id="rst-port-flavour"></a>
<a id="rst-devlink-definition-port-flavour"></a>



### port-flavour

- **type**:

  enum

- **entries**:

  - **physical**

  - **cpu**

  - **dsa**

  - **pci-pf**

  - **pci-vf**

  - **virtual**

  - **unused**

  - **pci-sf**

<a id="rst-port-fn-state"></a>
<a id="rst-devlink-definition-port-fn-state"></a>



### port-fn-state

- **type**:

  enum

- **entries**:

  - **inactive**

  - **active**

<a id="rst-port-fn-opstate"></a>
<a id="rst-devlink-definition-port-fn-opstate"></a>



### port-fn-opstate

- **type**:

  enum

- **entries**:

  - **detached**

  - **attached**

<a id="rst-port-fn-attr-cap"></a>
<a id="rst-devlink-definition-port-fn-attr-cap"></a>



### port-fn-attr-cap

- **type**:

  enum

- **entries**:

  - **roce-bit**

  - **migratable-bit**

  - **ipsec-crypto-bit**

  - **ipsec-packet-bit**

<a id="rst-rate-type"></a>
<a id="rst-devlink-definition-rate-type"></a>



### rate-type

- **type**:

  enum

- **entries**:

  - **leaf**

  - **node**

<a id="rst-sb-threshold-type"></a>
<a id="rst-devlink-definition-sb-threshold-type"></a>



### sb-threshold-type

- **type**:

  enum

- **entries**:

  - **static**

  - **dynamic**

<a id="rst-eswitch-mode"></a>
<a id="rst-devlink-definition-eswitch-mode"></a>



### eswitch-mode

- **type**:

  enum

- **entries**:

  - **legacy**

  - **switchdev**

  - **switchdev-inactive**

<a id="rst-eswitch-inline-mode"></a>
<a id="rst-devlink-definition-eswitch-inline-mode"></a>



### eswitch-inline-mode

- **type**:

  enum

- **entries**:

  - **none**

  - **link**

  - **network**

  - **transport**

<a id="rst-eswitch-encap-mode"></a>
<a id="rst-devlink-definition-eswitch-encap-mode"></a>



### eswitch-encap-mode

- **type**:

  enum

- **entries**:

  - **none**

  - **basic**

<a id="rst-dpipe-header-id"></a>
<a id="rst-devlink-definition-dpipe-header-id"></a>



### dpipe-header-id

- **type**:

  enum

- **entries**:

  - **ethernet**

  - **ipv4**

  - **ipv6**

<a id="rst-dpipe-match-type"></a>
<a id="rst-devlink-definition-dpipe-match-type"></a>



### dpipe-match-type

- **type**:

  enum

- **entries**:

  - **field-exact**

<a id="rst-dpipe-action-type"></a>
<a id="rst-devlink-definition-dpipe-action-type"></a>



### dpipe-action-type

- **type**:

  enum

- **entries**:

  - **field-modify**

<a id="rst-dpipe-field-mapping-type"></a>
<a id="rst-devlink-definition-dpipe-field-mapping-type"></a>



### dpipe-field-mapping-type

- **type**:

  enum

- **entries**:

  - **none**

  - **ifindex**

<a id="rst-resource-unit"></a>
<a id="rst-devlink-definition-resource-unit"></a>



### resource-unit

- **type**:

  enum

- **entries**:

  - **entry**

<a id="rst-reload-action"></a>
<a id="rst-devlink-definition-reload-action"></a>



### reload-action

- **type**:

  enum

- **entries**:

  - **driver-reinit**

  - **fw-activate**

<a id="rst-param-cmode"></a>
<a id="rst-devlink-definition-param-cmode"></a>



### param-cmode

- **type**:

  enum

- **entries**:

  - **runtime**

  - **driverinit**

  - **permanent**

<a id="rst-flash-overwrite"></a>
<a id="rst-devlink-definition-flash-overwrite"></a>



### flash-overwrite

- **type**:

  enum

- **entries**:

  - **settings-bit**

  - **identifiers-bit**

<a id="rst-trap-action"></a>
<a id="rst-devlink-definition-trap-action"></a>



### trap-action

- **type**:

  enum

- **entries**:

  - **drop**

  - **trap**

  - **mirror**

<a id="rst-trap-type"></a>
<a id="rst-devlink-definition-trap-type"></a>



### trap-type

- **type**:

  enum

- **entries**:

  - **drop**

  - **exception**

  - **control**

<a id="rst-var-attr-type"></a>
<a id="rst-devlink-definition-var-attr-type"></a>



### var-attr-type

- **type**:

  enum

- **entries**:

  - **u8**

  - **u16**

  - **u32**

  - **u64**

  - **string**

  - **flag**

  - **nul-string**

  - **binary**

<a id="rst-rate-tc-index-max"></a>
<a id="rst-devlink-definition-rate-tc-index-max"></a>



### rate-tc-index-max

- **type**:

  const

- **value**:

  7

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-devlink"></a>
<a id="rst-devlink-attribute-set-devlink"></a>



### devlink

<a id="rst-bus-name-string"></a>



#### bus-name (`string`)

- **value**:

  1

<a id="rst-dev-name-string"></a>



#### dev-name (`string`)

<a id="rst-port-index-u32"></a>



#### port-index (`u32`)

<a id="rst-port-type-u16"></a>



#### port-type (`u16`)

- **enum**:

  [port-type](#rst-devlink-definition-port-type)

<a id="rst-port-desired-type-u16"></a>



#### port-desired-type (`u16`)

<a id="rst-port-netdev-ifindex-u32"></a>



#### port-netdev-ifindex (`u32`)

<a id="rst-port-netdev-name-string"></a>



#### port-netdev-name (`string`)

<a id="rst-port-ibdev-name-string"></a>



#### port-ibdev-name (`string`)

<a id="rst-port-split-count-u32"></a>



#### port-split-count (`u32`)

<a id="rst-port-split-group-u32"></a>



#### port-split-group (`u32`)

<a id="rst-sb-index-u32"></a>



#### sb-index (`u32`)

<a id="rst-sb-size-u32"></a>



#### sb-size (`u32`)

<a id="rst-sb-ingress-pool-count-u16"></a>



#### sb-ingress-pool-count (`u16`)

<a id="rst-sb-egress-pool-count-u16"></a>



#### sb-egress-pool-count (`u16`)

<a id="rst-sb-ingress-tc-count-u16"></a>



#### sb-ingress-tc-count (`u16`)

<a id="rst-sb-egress-tc-count-u16"></a>



#### sb-egress-tc-count (`u16`)

<a id="rst-sb-pool-index-u16"></a>



#### sb-pool-index (`u16`)

<a id="rst-sb-pool-type-u8"></a>



#### sb-pool-type (`u8`)

- **enum**:

  [sb-pool-type](#rst-devlink-definition-sb-pool-type)

<a id="rst-sb-pool-size-u32"></a>



#### sb-pool-size (`u32`)

<a id="rst-sb-pool-threshold-type-u8"></a>



#### sb-pool-threshold-type (`u8`)

- **enum**:

  [sb-threshold-type](#rst-devlink-definition-sb-threshold-type)

<a id="rst-sb-threshold-u32"></a>



#### sb-threshold (`u32`)

<a id="rst-sb-tc-index-u16"></a>



#### sb-tc-index (`u16`)

<a id="rst-sb-occ-cur-u32"></a>



#### sb-occ-cur (`u32`)

<a id="rst-sb-occ-max-u32"></a>



#### sb-occ-max (`u32`)

<a id="rst-eswitch-mode-u16"></a>



#### eswitch-mode (`u16`)

- **enum**:

  [eswitch-mode](#rst-devlink-definition-eswitch-mode)

<a id="rst-eswitch-inline-mode-u8"></a>



#### eswitch-inline-mode (`u8`)

- **enum**:

  [eswitch-inline-mode](#rst-devlink-definition-eswitch-inline-mode)

<a id="rst-dpipe-tables-nest"></a>



#### dpipe-tables (`nest`)

- **nested-attributes**:

  [dl-dpipe-tables](#rst-devlink-attribute-set-dl-dpipe-tables)

<a id="rst-dpipe-table-nest"></a>



#### dpipe-table (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-table](#rst-devlink-attribute-set-dl-dpipe-table)

<a id="rst-dpipe-table-name-string"></a>



#### dpipe-table-name (`string`)

<a id="rst-dpipe-table-size-u64"></a>



#### dpipe-table-size (`u64`)

<a id="rst-dpipe-table-matches-nest"></a>



#### dpipe-table-matches (`nest`)

- **nested-attributes**:

  [dl-dpipe-table-matches](#rst-devlink-attribute-set-dl-dpipe-table-matches)

<a id="rst-dpipe-table-actions-nest"></a>



#### dpipe-table-actions (`nest`)

- **nested-attributes**:

  [dl-dpipe-table-actions](#rst-devlink-attribute-set-dl-dpipe-table-actions)

<a id="rst-dpipe-table-counters-enabled-u8"></a>



#### dpipe-table-counters-enabled (`u8`)

<a id="rst-dpipe-entries-nest"></a>



#### dpipe-entries (`nest`)

- **nested-attributes**:

  [dl-dpipe-entries](#rst-devlink-attribute-set-dl-dpipe-entries)

<a id="rst-dpipe-entry-nest"></a>



#### dpipe-entry (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-entry](#rst-devlink-attribute-set-dl-dpipe-entry)

<a id="rst-dpipe-entry-index-u64"></a>



#### dpipe-entry-index (`u64`)

<a id="rst-dpipe-entry-match-values-nest"></a>



#### dpipe-entry-match-values (`nest`)

- **nested-attributes**:

  [dl-dpipe-entry-match-values](#rst-devlink-attribute-set-dl-dpipe-entry-match-values)

<a id="rst-dpipe-entry-action-values-nest"></a>



#### dpipe-entry-action-values (`nest`)

- **nested-attributes**:

  [dl-dpipe-entry-action-values](#rst-devlink-attribute-set-dl-dpipe-entry-action-values)

<a id="rst-dpipe-entry-counter-u64"></a>



#### dpipe-entry-counter (`u64`)

<a id="rst-dpipe-match-nest"></a>



#### dpipe-match (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-match](#rst-devlink-attribute-set-dl-dpipe-match)

<a id="rst-dpipe-match-value-nest"></a>



#### dpipe-match-value (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-match-value](#rst-devlink-attribute-set-dl-dpipe-match-value)

<a id="rst-dpipe-match-type-u32"></a>



#### dpipe-match-type (`u32`)

- **enum**:

  [dpipe-match-type](#rst-devlink-definition-dpipe-match-type)

<a id="rst-dpipe-action-nest"></a>



#### dpipe-action (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-action](#rst-devlink-attribute-set-dl-dpipe-action)

<a id="rst-dpipe-action-value-nest"></a>



#### dpipe-action-value (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-action-value](#rst-devlink-attribute-set-dl-dpipe-action-value)

<a id="rst-dpipe-action-type-u32"></a>



#### dpipe-action-type (`u32`)

- **enum**:

  [dpipe-action-type](#rst-devlink-definition-dpipe-action-type)

<a id="rst-dpipe-value-binary"></a>



#### dpipe-value (`binary`)

<a id="rst-dpipe-value-mask-binary"></a>



#### dpipe-value-mask (`binary`)

<a id="rst-dpipe-value-mapping-u32"></a>



#### dpipe-value-mapping (`u32`)

<a id="rst-dpipe-headers-nest"></a>



#### dpipe-headers (`nest`)

- **nested-attributes**:

  [dl-dpipe-headers](#rst-devlink-attribute-set-dl-dpipe-headers)

<a id="rst-dpipe-header-nest"></a>



#### dpipe-header (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-header](#rst-devlink-attribute-set-dl-dpipe-header)

<a id="rst-dpipe-header-name-string"></a>



#### dpipe-header-name (`string`)

<a id="rst-dpipe-header-id-u32"></a>



#### dpipe-header-id (`u32`)

- **enum**:

  [dpipe-header-id](#rst-devlink-definition-dpipe-header-id)

<a id="rst-dpipe-header-fields-nest"></a>



#### dpipe-header-fields (`nest`)

- **nested-attributes**:

  [dl-dpipe-header-fields](#rst-devlink-attribute-set-dl-dpipe-header-fields)

<a id="rst-dpipe-header-global-u8"></a>



#### dpipe-header-global (`u8`)

<a id="rst-dpipe-header-index-u32"></a>



#### dpipe-header-index (`u32`)

<a id="rst-dpipe-field-nest"></a>



#### dpipe-field (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-dpipe-field](#rst-devlink-attribute-set-dl-dpipe-field)

<a id="rst-dpipe-field-name-string"></a>



#### dpipe-field-name (`string`)

<a id="rst-dpipe-field-id-u32"></a>



#### dpipe-field-id (`u32`)

<a id="rst-dpipe-field-bitwidth-u32"></a>



#### dpipe-field-bitwidth (`u32`)

<a id="rst-dpipe-field-mapping-type-u32"></a>



#### dpipe-field-mapping-type (`u32`)

- **enum**:

  [dpipe-field-mapping-type](#rst-devlink-definition-dpipe-field-mapping-type)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-eswitch-encap-mode-u8"></a>



#### eswitch-encap-mode (`u8`)

- **enum**:

  [eswitch-encap-mode](#rst-devlink-definition-eswitch-encap-mode)

<a id="rst-resource-list-nest"></a>



#### resource-list (`nest`)

- **nested-attributes**:

  [dl-resource-list](#rst-devlink-attribute-set-dl-resource-list)

<a id="rst-resource-nest"></a>



#### resource (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-resource](#rst-devlink-attribute-set-dl-resource)

<a id="rst-resource-name-string"></a>



#### resource-name (`string`)

<a id="rst-resource-id-u64"></a>



#### resource-id (`u64`)

<a id="rst-resource-size-u64"></a>



#### resource-size (`u64`)

<a id="rst-resource-size-new-u64"></a>



#### resource-size-new (`u64`)

<a id="rst-resource-size-valid-u8"></a>



#### resource-size-valid (`u8`)

<a id="rst-resource-size-min-u64"></a>



#### resource-size-min (`u64`)

<a id="rst-resource-size-max-u64"></a>



#### resource-size-max (`u64`)

<a id="rst-resource-size-gran-u64"></a>



#### resource-size-gran (`u64`)

<a id="rst-resource-unit-u8"></a>



#### resource-unit (`u8`)

- **enum**:

  [resource-unit](#rst-devlink-definition-resource-unit)

<a id="rst-resource-occ-u64"></a>



#### resource-occ (`u64`)

<a id="rst-dpipe-table-resource-id-u64"></a>



#### dpipe-table-resource-id (`u64`)

<a id="rst-dpipe-table-resource-units-u64"></a>



#### dpipe-table-resource-units (`u64`)

<a id="rst-port-flavour-u16"></a>



#### port-flavour (`u16`)

- **enum**:

  [port-flavour](#rst-devlink-definition-port-flavour)

<a id="rst-port-number-u32"></a>



#### port-number (`u32`)

<a id="rst-port-split-subport-number-u32"></a>



#### port-split-subport-number (`u32`)

<a id="rst-param-nest"></a>



#### param (`nest`)

- **nested-attributes**:

  [dl-param](#rst-devlink-attribute-set-dl-param)

<a id="rst-param-name-string"></a>



#### param-name (`string`)

<a id="rst-param-generic-flag"></a>



#### param-generic (`flag`)

<a id="rst-param-type-u8"></a>



#### param-type (`u8`)

- **enum**:

  [var-attr-type](#rst-devlink-definition-var-attr-type)

<a id="rst-param-value-cmode-u8"></a>



#### param-value-cmode (`u8`)

- **enum**:

  [param-cmode](#rst-devlink-definition-param-cmode)

- **value**:

  87

<a id="rst-region-name-string"></a>



#### region-name (`string`)

<a id="rst-region-size-u64"></a>



#### region-size (`u64`)

<a id="rst-region-snapshots-nest"></a>



#### region-snapshots (`nest`)

- **nested-attributes**:

  [dl-region-snapshots](#rst-devlink-attribute-set-dl-region-snapshots)

<a id="rst-region-snapshot-nest"></a>



#### region-snapshot (`nest`)

- **nested-attributes**:

  [dl-region-snapshot](#rst-devlink-attribute-set-dl-region-snapshot)

<a id="rst-region-snapshot-id-u32"></a>



#### region-snapshot-id (`u32`)

<a id="rst-region-chunks-nest"></a>



#### region-chunks (`nest`)

- **nested-attributes**:

  [dl-region-chunks](#rst-devlink-attribute-set-dl-region-chunks)

<a id="rst-region-chunk-nest"></a>



#### region-chunk (`nest`)

- **nested-attributes**:

  [dl-region-chunk](#rst-devlink-attribute-set-dl-region-chunk)

<a id="rst-region-chunk-data-binary"></a>



#### region-chunk-data (`binary`)

<a id="rst-region-chunk-addr-u64"></a>



#### region-chunk-addr (`u64`)

<a id="rst-region-chunk-len-u64"></a>



#### region-chunk-len (`u64`)

<a id="rst-info-driver-name-string"></a>



#### info-driver-name (`string`)

<a id="rst-info-serial-number-string"></a>



#### info-serial-number (`string`)

<a id="rst-info-version-fixed-nest"></a>



#### info-version-fixed (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-info-version](#rst-devlink-attribute-set-dl-info-version)

<a id="rst-info-version-running-nest"></a>



#### info-version-running (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-info-version](#rst-devlink-attribute-set-dl-info-version)

<a id="rst-info-version-stored-nest"></a>



#### info-version-stored (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-info-version](#rst-devlink-attribute-set-dl-info-version)

<a id="rst-info-version-name-string"></a>



#### info-version-name (`string`)

<a id="rst-info-version-value-string"></a>



#### info-version-value (`string`)

<a id="rst-sb-pool-cell-size-u32"></a>



#### sb-pool-cell-size (`u32`)

<a id="rst-fmsg-nest"></a>



#### fmsg (`nest`)

- **nested-attributes**:

  [dl-fmsg](#rst-devlink-attribute-set-dl-fmsg)

<a id="rst-fmsg-obj-nest-start-flag"></a>



#### fmsg-obj-nest-start (`flag`)

<a id="rst-fmsg-pair-nest-start-flag"></a>



#### fmsg-pair-nest-start (`flag`)

<a id="rst-fmsg-arr-nest-start-flag"></a>



#### fmsg-arr-nest-start (`flag`)

<a id="rst-fmsg-nest-end-flag"></a>



#### fmsg-nest-end (`flag`)

<a id="rst-fmsg-obj-name-string"></a>



#### fmsg-obj-name (`string`)

<a id="rst-fmsg-obj-value-type-u8"></a>



#### fmsg-obj-value-type (`u8`)

- **enum**:

  [var-attr-type](#rst-devlink-definition-var-attr-type)

<a id="rst-health-reporter-nest"></a>



#### health-reporter (`nest`)

- **value**:

  114

- **nested-attributes**:

  [dl-health-reporter](#rst-devlink-attribute-set-dl-health-reporter)

<a id="rst-health-reporter-name-string"></a>



#### health-reporter-name (`string`)

<a id="rst-health-reporter-state-u8"></a>



#### health-reporter-state (`u8`)

<a id="rst-health-reporter-err-count-u64"></a>



#### health-reporter-err-count (`u64`)

<a id="rst-health-reporter-recover-count-u64"></a>



#### health-reporter-recover-count (`u64`)

<a id="rst-health-reporter-dump-ts-u64"></a>



#### health-reporter-dump-ts (`u64`)

<a id="rst-health-reporter-graceful-period-u64"></a>



#### health-reporter-graceful-period (`u64`)

<a id="rst-health-reporter-auto-recover-u8"></a>



#### health-reporter-auto-recover (`u8`)

<a id="rst-flash-update-file-name-string"></a>



#### flash-update-file-name (`string`)

<a id="rst-flash-update-component-string"></a>



#### flash-update-component (`string`)

<a id="rst-flash-update-status-msg-string"></a>



#### flash-update-status-msg (`string`)

<a id="rst-flash-update-status-done-u64"></a>



#### flash-update-status-done (`u64`)

<a id="rst-flash-update-status-total-u64"></a>



#### flash-update-status-total (`u64`)

<a id="rst-port-pci-pf-number-u16"></a>



#### port-pci-pf-number (`u16`)

<a id="rst-port-pci-vf-number-u16"></a>



#### port-pci-vf-number (`u16`)

<a id="rst-stats-nest"></a>



#### stats (`nest`)

- **nested-attributes**:

  [dl-attr-stats](#rst-devlink-attribute-set-dl-attr-stats)

<a id="rst-trap-name-string"></a>



#### trap-name (`string`)

<a id="rst-trap-action-u8"></a>



#### trap-action (`u8`)

- **enum**:

  [trap-action](#rst-devlink-definition-trap-action)

<a id="rst-trap-type-u8"></a>



#### trap-type (`u8`)

- **enum**:

  [trap-type](#rst-devlink-definition-trap-type)

<a id="rst-trap-generic-flag"></a>



#### trap-generic (`flag`)

<a id="rst-trap-metadata-nest"></a>



#### trap-metadata (`nest`)

- **nested-attributes**:

  [dl-trap-metadata](#rst-devlink-attribute-set-dl-trap-metadata)

<a id="rst-trap-group-name-string"></a>



#### trap-group-name (`string`)

<a id="rst-reload-failed-u8"></a>



#### reload-failed (`u8`)

<a id="rst-health-reporter-dump-ts-ns-u64"></a>



#### health-reporter-dump-ts-ns (`u64`)

<a id="rst-netns-fd-u32"></a>



#### netns-fd (`u32`)

<a id="rst-netns-pid-u32"></a>



#### netns-pid (`u32`)

<a id="rst-netns-id-u32"></a>



#### netns-id (`u32`)

<a id="rst-health-reporter-auto-dump-u8"></a>



#### health-reporter-auto-dump (`u8`)

<a id="rst-trap-policer-id-u32"></a>



#### trap-policer-id (`u32`)

<a id="rst-trap-policer-rate-u64"></a>



#### trap-policer-rate (`u64`)

<a id="rst-trap-policer-burst-u64"></a>



#### trap-policer-burst (`u64`)

<a id="rst-port-function-nest"></a>



#### port-function (`nest`)

- **nested-attributes**:

  [dl-port-function](#rst-devlink-attribute-set-dl-port-function)

<a id="rst-info-board-serial-number-string"></a>



#### info-board-serial-number (`string`)

<a id="rst-port-lanes-u32"></a>



#### port-lanes (`u32`)

<a id="rst-port-splittable-u8"></a>



#### port-splittable (`u8`)

<a id="rst-port-external-u8"></a>



#### port-external (`u8`)

<a id="rst-port-controller-number-u32"></a>



#### port-controller-number (`u32`)

<a id="rst-flash-update-status-timeout-u64"></a>



#### flash-update-status-timeout (`u64`)

<a id="rst-flash-update-overwrite-mask-bitfield32"></a>



#### flash-update-overwrite-mask (`bitfield32`)

- **enum**:

  [flash-overwrite](#rst-devlink-definition-flash-overwrite)

- **enum-as-flags**:

  True

<a id="rst-reload-action-u8"></a>



#### reload-action (`u8`)

- **enum**:

  [reload-action](#rst-devlink-definition-reload-action)

<a id="rst-reload-actions-performed-bitfield32"></a>



#### reload-actions-performed (`bitfield32`)

- **enum**:

  [reload-action](#rst-devlink-definition-reload-action)

- **enum-as-flags**:

  True

<a id="rst-reload-limits-bitfield32"></a>



#### reload-limits (`bitfield32`)

- **enum**:

  [reload-action](#rst-devlink-definition-reload-action)

- **enum-as-flags**:

  True

<a id="rst-dev-stats-nest"></a>



#### dev-stats (`nest`)

- **nested-attributes**:

  [dl-dev-stats](#rst-devlink-attribute-set-dl-dev-stats)

<a id="rst-reload-stats-nest"></a>



#### reload-stats (`nest`)

- **nested-attributes**:

  [dl-reload-stats](#rst-devlink-attribute-set-dl-reload-stats)

<a id="rst-reload-stats-entry-nest"></a>



#### reload-stats-entry (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-reload-stats-entry](#rst-devlink-attribute-set-dl-reload-stats-entry)

<a id="rst-reload-stats-limit-u8"></a>



#### reload-stats-limit (`u8`)

<a id="rst-reload-stats-value-u32"></a>



#### reload-stats-value (`u32`)

<a id="rst-remote-reload-stats-nest"></a>



#### remote-reload-stats (`nest`)

- **nested-attributes**:

  [dl-reload-stats](#rst-devlink-attribute-set-dl-reload-stats)

<a id="rst-reload-action-info-nest"></a>



#### reload-action-info (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-reload-act-info](#rst-devlink-attribute-set-dl-reload-act-info)

<a id="rst-reload-action-stats-nest"></a>



#### reload-action-stats (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-reload-act-stats](#rst-devlink-attribute-set-dl-reload-act-stats)

<a id="rst-port-pci-sf-number-u32"></a>



#### port-pci-sf-number (`u32`)

<a id="rst-rate-type-u16"></a>



#### rate-type (`u16`)

- **enum**:

  [rate-type](#rst-devlink-definition-rate-type)

<a id="rst-rate-tx-share-u64"></a>



#### rate-tx-share (`u64`)

<a id="rst-rate-tx-max-u64"></a>



#### rate-tx-max (`u64`)

<a id="rst-rate-node-name-string"></a>



#### rate-node-name (`string`)

<a id="rst-rate-parent-node-name-string"></a>



#### rate-parent-node-name (`string`)

<a id="rst-region-max-snapshots-u32"></a>



#### region-max-snapshots (`u32`)

<a id="rst-linecard-index-u32"></a>



#### linecard-index (`u32`)

<a id="rst-linecard-state-u8"></a>



#### linecard-state (`u8`)

<a id="rst-linecard-type-string"></a>



#### linecard-type (`string`)

<a id="rst-linecard-supported-types-nest"></a>



#### linecard-supported-types (`nest`)

- **nested-attributes**:

  [dl-linecard-supported-types](#rst-devlink-attribute-set-dl-linecard-supported-types)

<a id="rst-selftests-nest"></a>



#### selftests (`nest`)

- **value**:

  176

- **nested-attributes**:

  [dl-selftest-id](#rst-devlink-attribute-set-dl-selftest-id)

<a id="rst-rate-tx-priority-u32"></a>



#### rate-tx-priority (`u32`)

<a id="rst-rate-tx-weight-u32"></a>



#### rate-tx-weight (`u32`)

<a id="rst-region-direct-flag"></a>



#### region-direct (`flag`)

<a id="rst-rate-tc-bws-nest"></a>



#### rate-tc-bws (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [dl-rate-tc-bws](#rst-devlink-attribute-set-dl-rate-tc-bws)

<a id="rst-health-reporter-burst-period-u64"></a>



#### health-reporter-burst-period (`u64`)

- **doc**:

  Time (in msec) for recoveries before starting the grace period.

<a id="rst-param-reset-default-flag"></a>



#### param-reset-default (`flag`)

- **doc**:

  Request restoring parameter to its default value.

- **value**:

  183

<a id="rst-dl-dev-stats"></a>
<a id="rst-devlink-attribute-set-dl-dev-stats"></a>



### dl-dev-stats

<a id="rst-reload-stats"></a>



#### reload-stats

<a id="rst-remote-reload-stats"></a>



#### remote-reload-stats

<a id="rst-dl-reload-stats"></a>
<a id="rst-devlink-attribute-set-dl-reload-stats"></a>



### dl-reload-stats

<a id="rst-reload-action-info"></a>



#### reload-action-info

<a id="rst-dl-reload-act-info"></a>
<a id="rst-devlink-attribute-set-dl-reload-act-info"></a>



### dl-reload-act-info

<a id="rst-reload-action-1"></a>



#### reload-action

<a id="rst-reload-action-stats"></a>



#### reload-action-stats

<a id="rst-dl-reload-act-stats"></a>
<a id="rst-devlink-attribute-set-dl-reload-act-stats"></a>



### dl-reload-act-stats

<a id="rst-reload-stats-entry"></a>



#### reload-stats-entry

<a id="rst-dl-reload-stats-entry"></a>
<a id="rst-devlink-attribute-set-dl-reload-stats-entry"></a>



### dl-reload-stats-entry

<a id="rst-reload-stats-limit"></a>



#### reload-stats-limit

<a id="rst-reload-stats-value"></a>



#### reload-stats-value

<a id="rst-dl-info-version"></a>
<a id="rst-devlink-attribute-set-dl-info-version"></a>



### dl-info-version

<a id="rst-info-version-name"></a>



#### info-version-name

<a id="rst-info-version-value"></a>



#### info-version-value

<a id="rst-dl-port-function"></a>
<a id="rst-devlink-attribute-set-dl-port-function"></a>



### dl-port-function

<a id="rst-hw-addr-binary"></a>



#### hw-addr (`binary`)

- **name-prefix**:

  devlink-port-function-attr-

- **value**:

  1

<a id="rst-state-u8"></a>



#### state (`u8`)

- **enum**:

  [port-fn-state](#rst-devlink-definition-port-fn-state)

<a id="rst-opstate-u8"></a>



#### opstate (`u8`)

- **enum**:

  [port-fn-opstate](#rst-devlink-definition-port-fn-opstate)

<a id="rst-caps-bitfield32"></a>



#### caps (`bitfield32`)

- **enum**:

  [port-fn-attr-cap](#rst-devlink-definition-port-fn-attr-cap)

- **enum-as-flags**:

  True

<a id="rst-dl-dpipe-tables"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-tables"></a>



### dl-dpipe-tables

<a id="rst-dpipe-table"></a>



#### dpipe-table

<a id="rst-dl-dpipe-table"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-table"></a>



### dl-dpipe-table

<a id="rst-dpipe-table-name"></a>



#### dpipe-table-name

<a id="rst-dpipe-table-size"></a>



#### dpipe-table-size

<a id="rst-dpipe-table-name-1"></a>



#### dpipe-table-name

<a id="rst-dpipe-table-size-1"></a>



#### dpipe-table-size

<a id="rst-dpipe-table-matches"></a>



#### dpipe-table-matches

<a id="rst-dpipe-table-actions"></a>



#### dpipe-table-actions

<a id="rst-dpipe-table-counters-enabled"></a>



#### dpipe-table-counters-enabled

<a id="rst-dpipe-table-resource-id"></a>



#### dpipe-table-resource-id

<a id="rst-dpipe-table-resource-units"></a>



#### dpipe-table-resource-units

<a id="rst-dl-dpipe-table-matches"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-table-matches"></a>



### dl-dpipe-table-matches

<a id="rst-dpipe-match"></a>



#### dpipe-match

<a id="rst-dl-dpipe-table-actions"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-table-actions"></a>



### dl-dpipe-table-actions

<a id="rst-dpipe-action"></a>



#### dpipe-action

<a id="rst-dl-dpipe-entries"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-entries"></a>



### dl-dpipe-entries

<a id="rst-dpipe-entry"></a>



#### dpipe-entry

<a id="rst-dl-dpipe-entry"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-entry"></a>



### dl-dpipe-entry

<a id="rst-dpipe-entry-index"></a>



#### dpipe-entry-index

<a id="rst-dpipe-entry-match-values"></a>



#### dpipe-entry-match-values

<a id="rst-dpipe-entry-action-values"></a>



#### dpipe-entry-action-values

<a id="rst-dpipe-entry-counter"></a>



#### dpipe-entry-counter

<a id="rst-dl-dpipe-entry-match-values"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-entry-match-values"></a>



### dl-dpipe-entry-match-values

<a id="rst-dpipe-match-value"></a>



#### dpipe-match-value

<a id="rst-dl-dpipe-entry-action-values"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-entry-action-values"></a>



### dl-dpipe-entry-action-values

<a id="rst-dpipe-action-value"></a>



#### dpipe-action-value

<a id="rst-dl-dpipe-match"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-match"></a>



### dl-dpipe-match

<a id="rst-dpipe-match-type-1"></a>



#### dpipe-match-type

<a id="rst-dpipe-header-id-1"></a>



#### dpipe-header-id

<a id="rst-dpipe-header-global"></a>



#### dpipe-header-global

<a id="rst-dpipe-header-index"></a>



#### dpipe-header-index

<a id="rst-dpipe-field-id"></a>



#### dpipe-field-id

<a id="rst-dl-dpipe-match-value"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-match-value"></a>



### dl-dpipe-match-value

<a id="rst-dpipe-match-1"></a>



#### dpipe-match

<a id="rst-dpipe-value"></a>



#### dpipe-value

<a id="rst-dpipe-value-mask"></a>



#### dpipe-value-mask

<a id="rst-dpipe-value-mapping"></a>



#### dpipe-value-mapping

<a id="rst-dl-dpipe-action"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-action"></a>



### dl-dpipe-action

<a id="rst-dpipe-action-type-1"></a>



#### dpipe-action-type

<a id="rst-dpipe-header-id-2"></a>



#### dpipe-header-id

<a id="rst-dpipe-header-global-1"></a>



#### dpipe-header-global

<a id="rst-dpipe-header-index-1"></a>



#### dpipe-header-index

<a id="rst-dpipe-field-id-1"></a>



#### dpipe-field-id

<a id="rst-dl-dpipe-action-value"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-action-value"></a>



### dl-dpipe-action-value

<a id="rst-dpipe-action-1"></a>



#### dpipe-action

<a id="rst-dpipe-value-1"></a>



#### dpipe-value

<a id="rst-dpipe-value-mask-1"></a>



#### dpipe-value-mask

<a id="rst-dpipe-value-mapping-1"></a>



#### dpipe-value-mapping

<a id="rst-dl-dpipe-headers"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-headers"></a>



### dl-dpipe-headers

<a id="rst-dpipe-header"></a>



#### dpipe-header

<a id="rst-dl-dpipe-header"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-header"></a>



### dl-dpipe-header

<a id="rst-dpipe-header-name"></a>



#### dpipe-header-name

<a id="rst-dpipe-header-id-3"></a>



#### dpipe-header-id

<a id="rst-dpipe-header-global-2"></a>



#### dpipe-header-global

<a id="rst-dpipe-header-fields"></a>



#### dpipe-header-fields

<a id="rst-dl-dpipe-header-fields"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-header-fields"></a>



### dl-dpipe-header-fields

<a id="rst-dpipe-field"></a>



#### dpipe-field

<a id="rst-dl-dpipe-field"></a>
<a id="rst-devlink-attribute-set-dl-dpipe-field"></a>



### dl-dpipe-field

<a id="rst-dpipe-field-name"></a>



#### dpipe-field-name

<a id="rst-dpipe-field-id-2"></a>



#### dpipe-field-id

<a id="rst-dpipe-field-bitwidth"></a>



#### dpipe-field-bitwidth

<a id="rst-dpipe-field-mapping-type-1"></a>



#### dpipe-field-mapping-type

<a id="rst-dl-resource"></a>
<a id="rst-devlink-attribute-set-dl-resource"></a>



### dl-resource

<a id="rst-resource-name"></a>



#### resource-name

<a id="rst-resource-id"></a>



#### resource-id

<a id="rst-resource-size"></a>



#### resource-size

<a id="rst-resource-size-new"></a>



#### resource-size-new

<a id="rst-resource-size-valid"></a>



#### resource-size-valid

<a id="rst-resource-size-min"></a>



#### resource-size-min

<a id="rst-resource-size-max"></a>



#### resource-size-max

<a id="rst-resource-size-gran"></a>



#### resource-size-gran

<a id="rst-resource-unit-1"></a>



#### resource-unit

<a id="rst-resource-occ"></a>



#### resource-occ

<a id="rst-dl-resource-list"></a>
<a id="rst-devlink-attribute-set-dl-resource-list"></a>



### dl-resource-list

<a id="rst-resource"></a>



#### resource

<a id="rst-dl-param"></a>
<a id="rst-devlink-attribute-set-dl-param"></a>



### dl-param

<a id="rst-param-name"></a>



#### param-name

<a id="rst-param-generic"></a>



#### param-generic

<a id="rst-param-type"></a>



#### param-type

<a id="rst-dl-region-snapshots"></a>
<a id="rst-devlink-attribute-set-dl-region-snapshots"></a>



### dl-region-snapshots

<a id="rst-region-snapshot"></a>



#### region-snapshot

<a id="rst-dl-region-snapshot"></a>
<a id="rst-devlink-attribute-set-dl-region-snapshot"></a>



### dl-region-snapshot

<a id="rst-region-snapshot-id"></a>



#### region-snapshot-id

<a id="rst-dl-region-chunks"></a>
<a id="rst-devlink-attribute-set-dl-region-chunks"></a>



### dl-region-chunks

<a id="rst-region-chunk"></a>



#### region-chunk

<a id="rst-dl-region-chunk"></a>
<a id="rst-devlink-attribute-set-dl-region-chunk"></a>



### dl-region-chunk

<a id="rst-region-chunk-data"></a>



#### region-chunk-data

<a id="rst-region-chunk-addr"></a>



#### region-chunk-addr

<a id="rst-dl-fmsg"></a>
<a id="rst-devlink-attribute-set-dl-fmsg"></a>



### dl-fmsg

<a id="rst-fmsg-obj-nest-start"></a>



#### fmsg-obj-nest-start

<a id="rst-fmsg-pair-nest-start"></a>



#### fmsg-pair-nest-start

<a id="rst-fmsg-arr-nest-start"></a>



#### fmsg-arr-nest-start

<a id="rst-fmsg-nest-end"></a>



#### fmsg-nest-end

<a id="rst-fmsg-obj-name"></a>



#### fmsg-obj-name

<a id="rst-dl-health-reporter"></a>
<a id="rst-devlink-attribute-set-dl-health-reporter"></a>



### dl-health-reporter

<a id="rst-health-reporter-name"></a>



#### health-reporter-name

<a id="rst-health-reporter-state"></a>



#### health-reporter-state

<a id="rst-health-reporter-err-count"></a>



#### health-reporter-err-count

<a id="rst-health-reporter-recover-count"></a>



#### health-reporter-recover-count

<a id="rst-health-reporter-graceful-period"></a>



#### health-reporter-graceful-period

<a id="rst-health-reporter-auto-recover"></a>



#### health-reporter-auto-recover

<a id="rst-health-reporter-dump-ts"></a>



#### health-reporter-dump-ts

<a id="rst-health-reporter-dump-ts-ns"></a>



#### health-reporter-dump-ts-ns

<a id="rst-health-reporter-auto-dump"></a>



#### health-reporter-auto-dump

<a id="rst-health-reporter-burst-period"></a>



#### health-reporter-burst-period

<a id="rst-dl-attr-stats"></a>
<a id="rst-devlink-attribute-set-dl-attr-stats"></a>



### dl-attr-stats

<a id="rst-stats-rx-packets-u64"></a>



#### stats-rx-packets (`u64`)

- **value**:

  0

<a id="rst-stats-rx-bytes-u64"></a>



#### stats-rx-bytes (`u64`)

<a id="rst-stats-rx-dropped-u64"></a>



#### stats-rx-dropped (`u64`)

<a id="rst-dl-trap-metadata"></a>
<a id="rst-devlink-attribute-set-dl-trap-metadata"></a>



### dl-trap-metadata

<a id="rst-trap-metadata-type-in-port-flag"></a>



#### trap-metadata-type-in-port (`flag`)

- **value**:

  0

<a id="rst-trap-metadata-type-fa-cookie-flag"></a>



#### trap-metadata-type-fa-cookie (`flag`)

<a id="rst-dl-linecard-supported-types"></a>
<a id="rst-devlink-attribute-set-dl-linecard-supported-types"></a>



### dl-linecard-supported-types

<a id="rst-linecard-type"></a>



#### linecard-type

<a id="rst-dl-selftest-id"></a>
<a id="rst-devlink-attribute-set-dl-selftest-id"></a>



### dl-selftest-id

<a id="rst-flash-flag"></a>



#### flash (`flag`)

<a id="rst-dl-rate-tc-bws"></a>
<a id="rst-devlink-attribute-set-dl-rate-tc-bws"></a>



### dl-rate-tc-bws

<a id="rst-index-u8"></a>



#### index (`u8`)

<a id="rst-bw-u32"></a>



#### bw (`u32`)

- **doc**:

  Specifies the bandwidth share assigned to the Traffic Class. The bandwidth for the traffic class is determined in proportion to the sum of the shares of all configured classes.

---

# Family dpll netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the dpll Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-dpll-netlink-specification"></a>
<a id="rst-netlink-dpll"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



DPLL subsystem.

<a id="rst-operations"></a>



## Operations

<a id="rst-device-id-get"></a>
<a id="rst-dpll-operation-device-id-get"></a>



### device-id-get



Get id of dpll device that matches given attributes

- **attribute-set**:

  [dpll](#rst-dpll-attribute-set-dpll)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-lock-doit

  **post**



  dpll-unlock-doit

  **request**

  - **attributes**:

    \[`module-name`, `clock-id`, `type`\]

  **reply**

  - **attributes**:

    \[`id`\]

<a id="rst-device-get"></a>
<a id="rst-dpll-operation-device-get"></a>



### device-get



Get list of DPLL devices (dump) or attributes of a single dpll device

- **attribute-set**:

  [dpll](#rst-dpll-attribute-set-dpll)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-pre-doit

  **post**



  dpll-post-doit

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `module-name`, `mode`, `mode-supported`, `lock-status`, `lock-status-error`, `temp`, `clock-id`, `type`, `phase-offset-monitor`, `phase-offset-avg-factor`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`id`, `module-name`, `mode`, `mode-supported`, `lock-status`, `lock-status-error`, `temp`, `clock-id`, `type`, `phase-offset-monitor`, `phase-offset-avg-factor`\]

<a id="rst-device-set"></a>
<a id="rst-dpll-operation-device-set"></a>



### device-set



Set attributes for a DPLL device

- **attribute-set**:

  [dpll](#rst-dpll-attribute-set-dpll)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-pre-doit

  **post**



  dpll-post-doit

  **request**

  - **attributes**:

    \[`id`, `mode`, `phase-offset-monitor`, `phase-offset-avg-factor`\]

<a id="rst-device-create-ntf"></a>
<a id="rst-dpll-operation-device-create-ntf"></a>



### device-create-ntf



Notification about device appearing

- **notify**:

  device-get

- **mcgrp**:

  monitor

<a id="rst-device-delete-ntf"></a>
<a id="rst-dpll-operation-device-delete-ntf"></a>



### device-delete-ntf



Notification about device disappearing

- **notify**:

  device-get

- **mcgrp**:

  monitor

<a id="rst-device-change-ntf"></a>
<a id="rst-dpll-operation-device-change-ntf"></a>



### device-change-ntf



Notification about device configuration being changed

- **notify**:

  device-get

- **mcgrp**:

  monitor

<a id="rst-pin-id-get"></a>
<a id="rst-dpll-operation-pin-id-get"></a>



### pin-id-get



Get id of a pin that matches given attributes

- **attribute-set**:

  [pin](#rst-dpll-attribute-set-pin)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-lock-doit

  **post**



  dpll-unlock-doit

  **request**

  - **attributes**:

    \[`module-name`, `clock-id`, `board-label`, `panel-label`, `package-label`, `type`\]

  **reply**

  - **attributes**:

    \[`id`\]

<a id="rst-pin-get"></a>
<a id="rst-dpll-operation-pin-get"></a>



### pin-get



Get list of pins and its attributes.

- dump request without any attributes given - list all the pins in the
  system

- dump request with target dpll - list all the pins registered with
  a given dpll device

- do request with target dpll and target pin - single pin attributes


- **attribute-set**:

  [pin](#rst-dpll-attribute-set-pin)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-pin-pre-doit

  **post**



  dpll-pin-post-doit

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `module-name`, `clock-id`, `board-label`, `panel-label`, `package-label`, `type`, `frequency`, `frequency-supported`, `capabilities`, `parent-device`, `parent-pin`, `phase-adjust-gran`, `phase-adjust-min`, `phase-adjust-max`, `phase-adjust`, `fractional-frequency-offset`, `fractional-frequency-offset-ppt`, `esync-frequency`, `esync-frequency-supported`, `esync-pulse`, `reference-sync`\]

- **dump**:

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `module-name`, `clock-id`, `board-label`, `panel-label`, `package-label`, `type`, `frequency`, `frequency-supported`, `capabilities`, `parent-device`, `parent-pin`, `phase-adjust-gran`, `phase-adjust-min`, `phase-adjust-max`, `phase-adjust`, `fractional-frequency-offset`, `fractional-frequency-offset-ppt`, `esync-frequency`, `esync-frequency-supported`, `esync-pulse`, `reference-sync`\]

<a id="rst-pin-set"></a>
<a id="rst-dpll-operation-pin-set"></a>



### pin-set



Set attributes of a target pin

- **attribute-set**:

  [pin](#rst-dpll-attribute-set-pin)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  dpll-pin-pre-doit

  **post**



  dpll-pin-post-doit

  **request**

  - **attributes**:

    \[`id`, `frequency`, `direction`, `prio`, `state`, `parent-device`, `parent-pin`, `phase-adjust`, `esync-frequency`, `reference-sync`\]

<a id="rst-pin-create-ntf"></a>
<a id="rst-dpll-operation-pin-create-ntf"></a>



### pin-create-ntf



Notification about pin appearing

- **notify**:

  pin-get

- **mcgrp**:

  monitor

<a id="rst-pin-delete-ntf"></a>
<a id="rst-dpll-operation-pin-delete-ntf"></a>



### pin-delete-ntf



Notification about pin disappearing

- **notify**:

  pin-get

- **mcgrp**:

  monitor

<a id="rst-pin-change-ntf"></a>
<a id="rst-dpll-operation-pin-change-ntf"></a>



### pin-change-ntf



Notification about pin configuration being changed

- **notify**:

  pin-get

- **mcgrp**:

  monitor

<a id="rst-multicast-groups"></a>



## Multicast groups

- monitor


<a id="rst-definitions"></a>



## Definitions

<a id="rst-mode"></a>
<a id="rst-dpll-definition-mode"></a>



### mode

- **type**:

  enum

- **doc**:

  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

- **entries**:

  - **manual**:

    input can be only selected by sending a request to dpll

  - **automatic**:

    highest prio input pin auto selected by dpll

<a id="rst-lock-status"></a>
<a id="rst-dpll-definition-lock-status"></a>



### lock-status

- **type**:

  enum

- **doc**:

  provides information of dpll device lock status, valid values for DPLL\_A\_LOCK\_STATUS attribute

- **entries**:

  - **unlocked**:

    dpll was not yet locked to any valid input (or forced by setting DPLL\_A\_MODE to DPLL\_MODE\_DETACHED)

  - **locked**:

    dpll is locked to a valid signal, but no holdover available

  - **locked-ho-acq**:

    dpll is locked and holdover acquired

  - **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="rst-lock-status-error"></a>
<a id="rst-dpll-definition-lock-status-error"></a>



### lock-status-error

- **type**:

  enum

- **doc**:

  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

- **entries**:

  - **none**:

    dpll device lock status was changed without any 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.

  - **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.

  - **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="rst-clock-quality-level"></a>
<a id="rst-dpll-definition-clock-quality-level"></a>



### clock-quality-level

- **type**:

  enum

- **doc**:

  level of quality of a clock device. This mainly applies when the dpll lock-status is DPLL\_LOCK\_STATUS\_HOLDOVER. The current list is defined according to the table 11-7 contained in ITU-T G.8264/Y.1364 document. One may extend this list freely by other ITU-T defined clock qualities, or different ones defined by another standardization body (for those, please use different prefix).

- **entries**:

  - **itu-opt1-prc**

  - **itu-opt1-ssu-a**

  - **itu-opt1-ssu-b**

  - **itu-opt1-eec1**

  - **itu-opt1-prtc**

  - **itu-opt1-eprtc**

  - **itu-opt1-eeec**

  - **itu-opt1-eprc**

<a id="rst-temp-divider"></a>
<a id="rst-dpll-definition-temp-divider"></a>



### temp-divider

- **type**:

  const

- **value**:

  1000

- **doc**:

  temperature divider allowing userspace to calculate the temperature as float with three digit decimal precision. Value of (DPLL\_A\_TEMP / DPLL\_TEMP\_DIVIDER) is integer part of temperature value. Value of (DPLL\_A\_TEMP % DPLL\_TEMP\_DIVIDER) is fractional part of temperature value.

<a id="rst-type"></a>
<a id="rst-dpll-definition-type"></a>



### type

- **type**:

  enum

- **doc**:

  type of dpll, valid values for DPLL\_A\_TYPE attribute

- **entries**:

  - **pps**:

    dpll produces Pulse-Per-Second signal

  - **eec**:

    dpll drives the Ethernet Equipment Clock

<a id="rst-pin-type"></a>
<a id="rst-dpll-definition-pin-type"></a>



### pin-type

- **type**:

  enum

- **doc**:

  defines possible types of a pin, valid values for DPLL\_A\_PIN\_TYPE attribute

- **entries**:

  - **mux**:

    aggregates another layer of selectable pins

  - **ext**:

    external input

  - **synce-eth-port**:

    ethernet port PHY's recovered clock

  - **int-oscillator**:

    device internal oscillator

  - **gnss**:

    GNSS recovered clock

<a id="rst-pin-direction"></a>
<a id="rst-dpll-definition-pin-direction"></a>



### pin-direction

- **type**:

  enum

- **doc**:

  defines possible direction of a pin, valid values for DPLL\_A\_PIN\_DIRECTION attribute

- **entries**:

  - **input**:

    pin used as a input of a signal

  - **output**:

    pin used to output the signal

<a id="rst-pin-frequency-1-hz"></a>
<a id="rst-dpll-definition-pin-frequency-1-hz"></a>



### pin-frequency-1-hz

- **type**:

  const

- **value**:

  1

<a id="rst-pin-frequency-10-khz"></a>
<a id="rst-dpll-definition-pin-frequency-10-khz"></a>



### pin-frequency-10-khz

- **type**:

  const

- **value**:

  10000

<a id="rst-pin-frequency-77-5-khz"></a>
<a id="rst-dpll-definition-pin-frequency-77-5-khz"></a>



### pin-frequency-77-5-khz

- **type**:

  const

- **value**:

  77500

<a id="rst-pin-frequency-10-mhz"></a>
<a id="rst-dpll-definition-pin-frequency-10-mhz"></a>



### pin-frequency-10-mhz

- **type**:

  const

- **value**:

  10000000

<a id="rst-pin-state"></a>
<a id="rst-dpll-definition-pin-state"></a>



### pin-state

- **type**:

  enum

- **doc**:

  defines possible states of a pin, valid values for DPLL\_A\_PIN\_STATE attribute

- **entries**:

  - **connected**:

    pin connected, active input of phase locked loop

  - **disconnected**:

    pin disconnected, not considered as a valid input

  - **selectable**:

    pin enabled for automatic input selection

<a id="rst-pin-capabilities"></a>
<a id="rst-dpll-definition-pin-capabilities"></a>



### pin-capabilities

- **type**:

  flags

- **doc**:

  defines possible capabilities of a pin, valid flags on DPLL\_A\_PIN\_CAPABILITIES attribute

- **entries**:

  - **direction-can-change**:

    pin direction can be changed

  - **priority-can-change**:

    pin priority can be changed

  - **state-can-change**:

    pin state can be changed

<a id="rst-phase-offset-divider"></a>
<a id="rst-dpll-definition-phase-offset-divider"></a>



### phase-offset-divider

- **type**:

  const

- **value**:

  1000

- **doc**:

  phase offset divider allows userspace to calculate a value of measured signal phase difference between a pin and dpll device as a fractional value with three digit decimal precision. Value of (DPLL\_A\_PHASE\_OFFSET / DPLL\_PHASE\_OFFSET\_DIVIDER) is an integer part of a measured phase offset value. Value of (DPLL\_A\_PHASE\_OFFSET % DPLL\_PHASE\_OFFSET\_DIVIDER) is a fractional part of a measured phase offset value.

<a id="rst-feature-state"></a>
<a id="rst-dpll-definition-feature-state"></a>



### feature-state

- **type**:

  enum

- **doc**:

  Allow control (enable/disable) and status checking over features.

- **entries**:

  - **disable**:

    feature shall be disabled

  - **enable**:

    feature shall be enabled

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-dpll"></a>
<a id="rst-dpll-attribute-set-dpll"></a>



### dpll

<a id="rst-id-u32"></a>



#### id (`u32`)

<a id="rst-module-name-string"></a>



#### module-name (`string`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-clock-id-u64"></a>



#### clock-id (`u64`)

<a id="rst-mode-u32"></a>



#### mode (`u32`)

- **enum**:

  [mode](#rst-dpll-definition-mode)

<a id="rst-mode-supported-u32"></a>



#### mode-supported (`u32`)

- **enum**:

  [mode](#rst-dpll-definition-mode)

- **multi-attr**:

  True

<a id="rst-lock-status-u32"></a>



#### lock-status (`u32`)

- **enum**:

  [lock-status](#rst-dpll-definition-lock-status)

<a id="rst-temp-s32"></a>



#### temp (`s32`)

<a id="rst-type-u32"></a>



#### type (`u32`)

- **enum**:

  [type](#rst-dpll-definition-type)

<a id="rst-lock-status-error-u32"></a>



#### lock-status-error (`u32`)

- **enum**:

  [lock-status-error](#rst-dpll-definition-lock-status-error)

<a id="rst-clock-quality-level-u32"></a>



#### clock-quality-level (`u32`)

- **enum**:

  [clock-quality-level](#rst-dpll-definition-clock-quality-level)

- **multi-attr**:

  True

- **doc**:

  Level of quality of a clock device. This mainly applies when the dpll lock-status is DPLL\_LOCK\_STATUS\_HOLDOVER. This could be put to message multiple times to indicate possible parallel quality levels (e.g. one specified by ITU option 1 and another one specified by option 2).

<a id="rst-phase-offset-monitor-u32"></a>



#### phase-offset-monitor (`u32`)

- **enum**:

  [feature-state](#rst-dpll-definition-feature-state)

- **doc**:

  Receive or request state of phase offset monitor feature. If enabled, dpll device shall monitor and notify all currently available inputs for changes of their phase offset against the dpll device.

<a id="rst-phase-offset-avg-factor-u32"></a>



#### phase-offset-avg-factor (`u32`)

- **doc**:

  Averaging factor applied to calculation of reported phase offset.

<a id="rst-pin"></a>
<a id="rst-dpll-attribute-set-pin"></a>



### pin

<a id="rst-id-u32-1"></a>



#### id (`u32`)

<a id="rst-parent-id-u32"></a>



#### parent-id (`u32`)

<a id="rst-module-name-string-1"></a>



#### module-name (`string`)

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-clock-id-u64-1"></a>



#### clock-id (`u64`)

<a id="rst-board-label-string"></a>



#### board-label (`string`)

<a id="rst-panel-label-string"></a>



#### panel-label (`string`)

<a id="rst-package-label-string"></a>



#### package-label (`string`)

<a id="rst-type-u32-1"></a>



#### type (`u32`)

- **enum**:

  [pin-type](#rst-dpll-definition-pin-type)

<a id="rst-direction-u32"></a>



#### direction (`u32`)

- **enum**:

  [pin-direction](#rst-dpll-definition-pin-direction)

<a id="rst-frequency-u64"></a>



#### frequency (`u64`)

<a id="rst-frequency-supported-nest"></a>



#### frequency-supported (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [frequency-range](#rst-dpll-attribute-set-frequency-range)

<a id="rst-frequency-min-u64"></a>



#### frequency-min (`u64`)

<a id="rst-frequency-max-u64"></a>



#### frequency-max (`u64`)

<a id="rst-prio-u32"></a>



#### prio (`u32`)

<a id="rst-state-u32"></a>



#### state (`u32`)

- **enum**:

  [pin-state](#rst-dpll-definition-pin-state)

<a id="rst-capabilities-u32"></a>



#### capabilities (`u32`)

- **enum**:

  [pin-capabilities](#rst-dpll-definition-pin-capabilities)

<a id="rst-parent-device-nest"></a>



#### parent-device (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [pin-parent-device](#rst-dpll-attribute-set-pin-parent-device)

<a id="rst-parent-pin-nest"></a>



#### parent-pin (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [pin-parent-pin](#rst-dpll-attribute-set-pin-parent-pin)

<a id="rst-phase-adjust-min-s32"></a>



#### phase-adjust-min (`s32`)

<a id="rst-phase-adjust-max-s32"></a>



#### phase-adjust-max (`s32`)

<a id="rst-phase-adjust-s32"></a>



#### phase-adjust (`s32`)

<a id="rst-phase-offset-s64"></a>



#### phase-offset (`s64`)

<a id="rst-fractional-frequency-offset-sint"></a>



#### fractional-frequency-offset (`sint`)

- **doc**:

  The FFO (Fractional Frequency Offset) between the RX and TX symbol rate on the media associated with the pin: (rx\_frequency-tx\_frequency)/rx\_frequency Value is in PPM (parts per million). This may be implemented for example for pin of type PIN\_TYPE\_SYNCE\_ETH\_PORT.

<a id="rst-esync-frequency-u64"></a>



#### esync-frequency (`u64`)

- **doc**:

  Frequency of Embedded SYNC signal. If provided, the pin is configured with a SYNC signal embedded into its base clock frequency.

<a id="rst-esync-frequency-supported-nest"></a>



#### esync-frequency-supported (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [frequency-range](#rst-dpll-attribute-set-frequency-range)

- **doc**:

  If provided a pin is capable of embedding a SYNC signal (within given range) into its base frequency signal.

<a id="rst-esync-pulse-u32"></a>



#### esync-pulse (`u32`)

- **doc**:

  A ratio of high to low state of a SYNC signal pulse embedded into base clock frequency. Value is in percents.

<a id="rst-reference-sync-nest"></a>



#### reference-sync (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [reference-sync](#rst-dpll-attribute-set-reference-sync)

- **doc**:

  Capable pin provides list of pins that can be bound to create a reference-sync pin pair.

<a id="rst-phase-adjust-gran-u32"></a>



#### phase-adjust-gran (`u32`)

- **doc**:

  Granularity of phase adjustment, in picoseconds. The value of phase adjustment must be a multiple of this granularity.

<a id="rst-fractional-frequency-offset-ppt-sint"></a>



#### fractional-frequency-offset-ppt (`sint`)

- **doc**:

  The FFO (Fractional Frequency Offset) of the pin with respect to the nominal frequency. Value = (frequency\_measured - frequency\_nominal) / frequency\_nominal Value is in PPT (parts per trillion, 10^-12). Note: This attribute provides higher resolution than the standard fractional-frequency-offset (which is in PPM).

<a id="rst-pin-parent-device"></a>
<a id="rst-dpll-attribute-set-pin-parent-device"></a>



### pin-parent-device

<a id="rst-parent-id"></a>



#### parent-id

<a id="rst-direction"></a>



#### direction

<a id="rst-prio"></a>



#### prio

<a id="rst-state"></a>



#### state

<a id="rst-phase-offset"></a>



#### phase-offset

<a id="rst-pin-parent-pin"></a>
<a id="rst-dpll-attribute-set-pin-parent-pin"></a>



### pin-parent-pin

<a id="rst-parent-id-1"></a>



#### parent-id

<a id="rst-state-1"></a>



#### state

<a id="rst-frequency-range"></a>
<a id="rst-dpll-attribute-set-frequency-range"></a>



### frequency-range

<a id="rst-frequency-min"></a>



#### frequency-min

<a id="rst-frequency-max"></a>



#### frequency-max

<a id="rst-reference-sync"></a>
<a id="rst-dpll-attribute-set-reference-sync"></a>



### reference-sync

<a id="rst-id"></a>



#### id

<a id="rst-state-2"></a>



#### state

---

# Family ethtool netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the ethtool Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-ethtool-netlink-specification"></a>
<a id="rst-netlink-ethtool"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Partial family for Ethtool Netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-strset-get"></a>
<a id="rst-ethtool-operation-strset-get"></a>



### strset-get



Get string set from the kernel.

- **attribute-set**:

  [strset](#rst-ethtool-attribute-set-strset)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `stringsets`, `counts-only`\]

  **reply**

  - **attributes**:

    \[`header`, `stringsets`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`, `stringsets`, `counts-only`\]

  **reply**

  - **attributes**:

    \[`header`, `stringsets`\]

<a id="rst-linkinfo-get"></a>
<a id="rst-ethtool-operation-linkinfo-get"></a>



### linkinfo-get



Get link info.

- **attribute-set**:

  [linkinfo](#rst-ethtool-attribute-set-linkinfo)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `port`, `phyaddr`, `tp-mdix`, `tp-mdix-ctrl`, `transceiver`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `port`, `phyaddr`, `tp-mdix`, `tp-mdix-ctrl`, `transceiver`\]

<a id="rst-linkinfo-set"></a>
<a id="rst-ethtool-operation-linkinfo-set"></a>



### linkinfo-set



Set link info.

- **attribute-set**:

  [linkinfo](#rst-ethtool-attribute-set-linkinfo)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `port`, `phyaddr`, `tp-mdix`, `tp-mdix-ctrl`, `transceiver`\]

<a id="rst-linkinfo-ntf"></a>
<a id="rst-ethtool-operation-linkinfo-ntf"></a>



### linkinfo-ntf



Notification for change in link info.

- **notify**:

  linkinfo-get

<a id="rst-linkmodes-get"></a>
<a id="rst-ethtool-operation-linkmodes-get"></a>



### linkmodes-get



Get link modes.

- **attribute-set**:

  [linkmodes](#rst-ethtool-attribute-set-linkmodes)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `autoneg`, `ours`, `peer`, `speed`, `duplex`, `master-slave-cfg`, `master-slave-state`, `lanes`, `rate-matching`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `autoneg`, `ours`, `peer`, `speed`, `duplex`, `master-slave-cfg`, `master-slave-state`, `lanes`, `rate-matching`\]

<a id="rst-linkmodes-set"></a>
<a id="rst-ethtool-operation-linkmodes-set"></a>



### linkmodes-set



Set link modes.

- **attribute-set**:

  [linkmodes](#rst-ethtool-attribute-set-linkmodes)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `autoneg`, `ours`, `peer`, `speed`, `duplex`, `master-slave-cfg`, `master-slave-state`, `lanes`, `rate-matching`\]

<a id="rst-linkmodes-ntf"></a>
<a id="rst-ethtool-operation-linkmodes-ntf"></a>



### linkmodes-ntf



Notification for change in link modes.

- **notify**:

  linkmodes-get

<a id="rst-linkstate-get"></a>
<a id="rst-ethtool-operation-linkstate-get"></a>



### linkstate-get



Get link state.

- **attribute-set**:

  [linkstate](#rst-ethtool-attribute-set-linkstate)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `link`, `sqi`, `sqi-max`, `ext-state`, `ext-substate`, `ext-down-cnt`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `link`, `sqi`, `sqi-max`, `ext-state`, `ext-substate`, `ext-down-cnt`\]

<a id="rst-debug-get"></a>
<a id="rst-ethtool-operation-debug-get"></a>



### debug-get



Get debug message mask.

- **attribute-set**:

  [debug](#rst-ethtool-attribute-set-debug)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `msgmask`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `msgmask`\]

<a id="rst-debug-set"></a>
<a id="rst-ethtool-operation-debug-set"></a>



### debug-set



Set debug message mask.

- **attribute-set**:

  [debug](#rst-ethtool-attribute-set-debug)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `msgmask`\]

<a id="rst-debug-ntf"></a>
<a id="rst-ethtool-operation-debug-ntf"></a>



### debug-ntf



Notification for change in debug message mask.

- **notify**:

  debug-get

<a id="rst-wol-get"></a>
<a id="rst-ethtool-operation-wol-get"></a>



### wol-get



Get WOL params.

- **attribute-set**:

  [wol](#rst-ethtool-attribute-set-wol)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes`, `sopass`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes`, `sopass`\]

<a id="rst-wol-set"></a>
<a id="rst-ethtool-operation-wol-set"></a>



### wol-set



Set WOL params.

- **attribute-set**:

  [wol](#rst-ethtool-attribute-set-wol)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `modes`, `sopass`\]

<a id="rst-wol-ntf"></a>
<a id="rst-ethtool-operation-wol-ntf"></a>



### wol-ntf



Notification for change in WOL params.

- **notify**:

  wol-get

<a id="rst-features-get"></a>
<a id="rst-ethtool-operation-features-get"></a>



### features-get



Get features.

- **attribute-set**:

  [features](#rst-ethtool-attribute-set-features)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `hw`, `wanted`, `active`, `nochange`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `hw`, `wanted`, `active`, `nochange`\]

<a id="rst-features-set"></a>
<a id="rst-ethtool-operation-features-set"></a>



### features-set



Set features.

- **attribute-set**:

  [features](#rst-ethtool-attribute-set-features)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `hw`, `wanted`, `active`, `nochange`\]

  **reply**

  - **attributes**:

    \[`header`, `hw`, `wanted`, `active`, `nochange`\]

<a id="rst-features-ntf"></a>
<a id="rst-ethtool-operation-features-ntf"></a>



### features-ntf



Notification for change in features.

- **notify**:

  features-get

<a id="rst-privflags-get"></a>
<a id="rst-ethtool-operation-privflags-get"></a>



### privflags-get



Get device private flags.

- **attribute-set**:

  [privflags](#rst-ethtool-attribute-set-privflags)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `flags`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `flags`\]

<a id="rst-privflags-set"></a>
<a id="rst-ethtool-operation-privflags-set"></a>



### privflags-set



Set device private flags.

- **attribute-set**:

  [privflags](#rst-ethtool-attribute-set-privflags)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `flags`\]

<a id="rst-privflags-ntf"></a>
<a id="rst-ethtool-operation-privflags-ntf"></a>



### privflags-ntf



Notification for change in device private flags.

- **notify**:

  privflags-get

<a id="rst-rings-get"></a>
<a id="rst-ethtool-operation-rings-get"></a>



### rings-get



Get ring params.

- **attribute-set**:

  [rings](#rst-ethtool-attribute-set-rings)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-max`, `rx-mini-max`, `rx-jumbo-max`, `tx-max`, `rx`, `rx-mini`, `rx-jumbo`, `tx`, `rx-buf-len`, `tcp-data-split`, `cqe-size`, `tx-push`, `rx-push`, `tx-push-buf-len`, `tx-push-buf-len-max`, `hds-thresh`, `hds-thresh-max`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-max`, `rx-mini-max`, `rx-jumbo-max`, `tx-max`, `rx`, `rx-mini`, `rx-jumbo`, `tx`, `rx-buf-len`, `tcp-data-split`, `cqe-size`, `tx-push`, `rx-push`, `tx-push-buf-len`, `tx-push-buf-len-max`, `hds-thresh`, `hds-thresh-max`\]

<a id="rst-rings-set"></a>
<a id="rst-ethtool-operation-rings-set"></a>



### rings-set



Set ring params.

- **attribute-set**:

  [rings](#rst-ethtool-attribute-set-rings)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `rx-max`, `rx-mini-max`, `rx-jumbo-max`, `tx-max`, `rx`, `rx-mini`, `rx-jumbo`, `tx`, `rx-buf-len`, `tcp-data-split`, `cqe-size`, `tx-push`, `rx-push`, `tx-push-buf-len`, `tx-push-buf-len-max`, `hds-thresh`, `hds-thresh-max`\]

<a id="rst-rings-ntf"></a>
<a id="rst-ethtool-operation-rings-ntf"></a>



### rings-ntf



Notification for change in ring params.

- **notify**:

  rings-get

<a id="rst-channels-get"></a>
<a id="rst-ethtool-operation-channels-get"></a>



### channels-get



Get channel params.

- **attribute-set**:

  [channels](#rst-ethtool-attribute-set-channels)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-max`, `tx-max`, `other-max`, `combined-max`, `rx-count`, `tx-count`, `other-count`, `combined-count`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-max`, `tx-max`, `other-max`, `combined-max`, `rx-count`, `tx-count`, `other-count`, `combined-count`\]

<a id="rst-channels-set"></a>
<a id="rst-ethtool-operation-channels-set"></a>



### channels-set



Set channel params.

- **attribute-set**:

  [channels](#rst-ethtool-attribute-set-channels)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `rx-max`, `tx-max`, `other-max`, `combined-max`, `rx-count`, `tx-count`, `other-count`, `combined-count`\]

<a id="rst-channels-ntf"></a>
<a id="rst-ethtool-operation-channels-ntf"></a>



### channels-ntf



Notification for change in channel params.

- **notify**:

  channels-get

<a id="rst-coalesce-get"></a>
<a id="rst-ethtool-operation-coalesce-get"></a>



### coalesce-get



Get coalesce params.

- **attribute-set**:

  [coalesce](#rst-ethtool-attribute-set-coalesce)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-usecs`, `rx-max-frames`, `rx-usecs-irq`, `rx-max-frames-irq`, `tx-usecs`, `tx-max-frames`, `tx-usecs-irq`, `tx-max-frames-irq`, `stats-block-usecs`, `use-adaptive-rx`, `use-adaptive-tx`, `pkt-rate-low`, `rx-usecs-low`, `rx-max-frames-low`, `tx-usecs-low`, `tx-max-frames-low`, `pkt-rate-high`, `rx-usecs-high`, `rx-max-frames-high`, `tx-usecs-high`, `tx-max-frames-high`, `rate-sample-interval`, `use-cqe-mode-tx`, `use-cqe-mode-rx`, `tx-aggr-max-bytes`, `tx-aggr-max-frames`, `tx-aggr-time-usecs`, `rx-profile`, `tx-profile`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `rx-usecs`, `rx-max-frames`, `rx-usecs-irq`, `rx-max-frames-irq`, `tx-usecs`, `tx-max-frames`, `tx-usecs-irq`, `tx-max-frames-irq`, `stats-block-usecs`, `use-adaptive-rx`, `use-adaptive-tx`, `pkt-rate-low`, `rx-usecs-low`, `rx-max-frames-low`, `tx-usecs-low`, `tx-max-frames-low`, `pkt-rate-high`, `rx-usecs-high`, `rx-max-frames-high`, `tx-usecs-high`, `tx-max-frames-high`, `rate-sample-interval`, `use-cqe-mode-tx`, `use-cqe-mode-rx`, `tx-aggr-max-bytes`, `tx-aggr-max-frames`, `tx-aggr-time-usecs`, `rx-profile`, `tx-profile`\]

<a id="rst-coalesce-set"></a>
<a id="rst-ethtool-operation-coalesce-set"></a>



### coalesce-set



Set coalesce params.

- **attribute-set**:

  [coalesce](#rst-ethtool-attribute-set-coalesce)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `rx-usecs`, `rx-max-frames`, `rx-usecs-irq`, `rx-max-frames-irq`, `tx-usecs`, `tx-max-frames`, `tx-usecs-irq`, `tx-max-frames-irq`, `stats-block-usecs`, `use-adaptive-rx`, `use-adaptive-tx`, `pkt-rate-low`, `rx-usecs-low`, `rx-max-frames-low`, `tx-usecs-low`, `tx-max-frames-low`, `pkt-rate-high`, `rx-usecs-high`, `rx-max-frames-high`, `tx-usecs-high`, `tx-max-frames-high`, `rate-sample-interval`, `use-cqe-mode-tx`, `use-cqe-mode-rx`, `tx-aggr-max-bytes`, `tx-aggr-max-frames`, `tx-aggr-time-usecs`, `rx-profile`, `tx-profile`\]

<a id="rst-coalesce-ntf"></a>
<a id="rst-ethtool-operation-coalesce-ntf"></a>



### coalesce-ntf



Notification for change in coalesce params.

- **notify**:

  coalesce-get

<a id="rst-pause-get"></a>
<a id="rst-ethtool-operation-pause-get"></a>



### pause-get



Get pause params.

- **attribute-set**:

  [pause](#rst-ethtool-attribute-set-pause)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `autoneg`, `rx`, `tx`, `stats`, `stats-src`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `autoneg`, `rx`, `tx`, `stats`, `stats-src`\]

<a id="rst-pause-set"></a>
<a id="rst-ethtool-operation-pause-set"></a>



### pause-set



Set pause params.

- **attribute-set**:

  [pause](#rst-ethtool-attribute-set-pause)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `autoneg`, `rx`, `tx`, `stats`, `stats-src`\]

<a id="rst-pause-ntf"></a>
<a id="rst-ethtool-operation-pause-ntf"></a>



### pause-ntf



Notification for change in pause params.

- **notify**:

  pause-get

<a id="rst-eee-get"></a>
<a id="rst-ethtool-operation-eee-get"></a>



### eee-get



Get eee params.

- **attribute-set**:

  [eee](#rst-ethtool-attribute-set-eee)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes-ours`, `modes-peer`, `active`, `enabled`, `tx-lpi-enabled`, `tx-lpi-timer`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes-ours`, `modes-peer`, `active`, `enabled`, `tx-lpi-enabled`, `tx-lpi-timer`\]

<a id="rst-eee-set"></a>
<a id="rst-ethtool-operation-eee-set"></a>



### eee-set



Set eee params.

- **attribute-set**:

  [eee](#rst-ethtool-attribute-set-eee)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `modes-ours`, `modes-peer`, `active`, `enabled`, `tx-lpi-enabled`, `tx-lpi-timer`\]

<a id="rst-eee-ntf"></a>
<a id="rst-ethtool-operation-eee-ntf"></a>



### eee-ntf



Notification for change in eee params.

- **notify**:

  eee-get

<a id="rst-tsinfo-get"></a>
<a id="rst-ethtool-operation-tsinfo-get"></a>



### tsinfo-get



Get tsinfo params.

- **attribute-set**:

  [tsinfo](#rst-ethtool-attribute-set-tsinfo)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `hwtstamp-provider`\]

  **reply**

  - **attributes**:

    \[`header`, `timestamping`, `tx-types`, `rx-filters`, `phc-index`, `stats`, `hwtstamp-provider`, `hwtstamp-source`, `hwtstamp-phyindex`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`, `hwtstamp-provider`\]

  **reply**

  - **attributes**:

    \[`header`, `timestamping`, `tx-types`, `rx-filters`, `phc-index`, `stats`, `hwtstamp-provider`, `hwtstamp-source`, `hwtstamp-phyindex`\]

<a id="rst-cable-test-act"></a>
<a id="rst-ethtool-operation-cable-test-act"></a>



### cable-test-act



Cable test.

- **attribute-set**:

  [cable-test](#rst-ethtool-attribute-set-cable-test)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

<a id="rst-cable-test-ntf"></a>
<a id="rst-ethtool-operation-cable-test-ntf"></a>



### cable-test-ntf



Cable test notification.

- **attribute-set**:

  [cable-test-ntf](#rst-ethtool-attribute-set-cable-test-ntf)

- **event**:

  - **attributes**:

    \[`header`, `status`\]

<a id="rst-cable-test-tdr-act"></a>
<a id="rst-ethtool-operation-cable-test-tdr-act"></a>



### cable-test-tdr-act



Cable test TDR.

- **attribute-set**:

  [cable-test-tdr](#rst-ethtool-attribute-set-cable-test-tdr)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

<a id="rst-cable-test-tdr-ntf"></a>
<a id="rst-ethtool-operation-cable-test-tdr-ntf"></a>



### cable-test-tdr-ntf



Cable test TDR notification.

- **attribute-set**:

  [cable-test-tdr-ntf](#rst-ethtool-attribute-set-cable-test-tdr-ntf)

- **event**:

  - **attributes**:

    \[`header`, `status`, `nest`\]

<a id="rst-tunnel-info-get"></a>
<a id="rst-ethtool-operation-tunnel-info-get"></a>



### tunnel-info-get



Get tsinfo params.

- **attribute-set**:

  [tunnel-info](#rst-ethtool-attribute-set-tunnel-info)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `udp-ports`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `udp-ports`\]

<a id="rst-fec-get"></a>
<a id="rst-ethtool-operation-fec-get"></a>



### fec-get



Get FEC params.

- **attribute-set**:

  [fec](#rst-ethtool-attribute-set-fec)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes`, `auto`, `active`, `stats`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `modes`, `auto`, `active`, `stats`\]

<a id="rst-fec-set"></a>
<a id="rst-ethtool-operation-fec-set"></a>



### fec-set



Set FEC params.

- **attribute-set**:

  [fec](#rst-ethtool-attribute-set-fec)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `modes`, `auto`, `active`, `stats`\]

<a id="rst-fec-ntf"></a>
<a id="rst-ethtool-operation-fec-ntf"></a>



### fec-ntf



Notification for change in FEC params.

- **notify**:

  fec-get

<a id="rst-module-eeprom-get"></a>
<a id="rst-ethtool-operation-module-eeprom-get"></a>



### module-eeprom-get



Get module EEPROM params.

- **attribute-set**:

  [module-eeprom](#rst-ethtool-attribute-set-module-eeprom)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `offset`, `length`, `page`, `bank`, `i2c-address`\]

  **reply**

  - **attributes**:

    \[`header`, `data`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`, `offset`, `length`, `page`, `bank`, `i2c-address`\]

  **reply**

  - **attributes**:

    \[`header`, `data`\]

<a id="rst-stats-get"></a>
<a id="rst-ethtool-operation-stats-get"></a>



### stats-get



Get statistics.

- **attribute-set**:

  [stats](#rst-ethtool-attribute-set-stats)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `groups`\]

  **reply**

  - **attributes**:

    \[`header`, `groups`, `grp`, `src`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`, `groups`\]

  **reply**

  - **attributes**:

    \[`header`, `groups`, `grp`, `src`\]

<a id="rst-phc-vclocks-get"></a>
<a id="rst-ethtool-operation-phc-vclocks-get"></a>



### phc-vclocks-get



Get PHC VCLOCKs.

- **attribute-set**:

  [phc-vclocks](#rst-ethtool-attribute-set-phc-vclocks)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `num`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `num`\]

<a id="rst-module-get"></a>
<a id="rst-ethtool-operation-module-get"></a>



### module-get



Get module params.

- **attribute-set**:

  [module](#rst-ethtool-attribute-set-module)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `power-mode-policy`, `power-mode`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `power-mode-policy`, `power-mode`\]

<a id="rst-module-set"></a>
<a id="rst-ethtool-operation-module-set"></a>



### module-set



Set module params.

- **attribute-set**:

  [module](#rst-ethtool-attribute-set-module)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `power-mode-policy`, `power-mode`\]

<a id="rst-module-ntf"></a>
<a id="rst-ethtool-operation-module-ntf"></a>



### module-ntf



Notification for change in module params.

- **notify**:

  module-get

<a id="rst-pse-get"></a>
<a id="rst-ethtool-operation-pse-get"></a>



### pse-get



Get Power Sourcing Equipment params.

- **attribute-set**:

  [pse](#rst-ethtool-attribute-set-pse)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `podl-pse-admin-state`, `podl-pse-admin-control`, `podl-pse-pw-d-status`, `c33-pse-admin-state`, `c33-pse-admin-control`, `c33-pse-pw-d-status`, `c33-pse-pw-class`, `c33-pse-actual-pw`, `c33-pse-ext-state`, `c33-pse-ext-substate`, `c33-pse-avail-pw-limit`, `c33-pse-pw-limit-ranges`, `pse-pw-d-id`, `pse-prio-max`, `pse-prio`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `podl-pse-admin-state`, `podl-pse-admin-control`, `podl-pse-pw-d-status`, `c33-pse-admin-state`, `c33-pse-admin-control`, `c33-pse-pw-d-status`, `c33-pse-pw-class`, `c33-pse-actual-pw`, `c33-pse-ext-state`, `c33-pse-ext-substate`, `c33-pse-avail-pw-limit`, `c33-pse-pw-limit-ranges`, `pse-pw-d-id`, `pse-prio-max`, `pse-prio`\]

<a id="rst-pse-set"></a>
<a id="rst-ethtool-operation-pse-set"></a>



### pse-set



Set Power Sourcing Equipment params.

- **attribute-set**:

  [pse](#rst-ethtool-attribute-set-pse)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `podl-pse-admin-control`, `c33-pse-admin-control`, `c33-pse-avail-pw-limit`, `pse-prio`\]

<a id="rst-rss-get"></a>
<a id="rst-ethtool-operation-rss-get"></a>



### rss-get



Get RSS params.

- **attribute-set**:

  [rss](#rst-ethtool-attribute-set-rss)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `context`\]

  **reply**

  - **attributes**:

    \[`header`, `context`, `hfunc`, `indir`, `hkey`, `input-xfrm`, `flow-hash`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`, `start-context`\]

  **reply**

  - **attributes**:

    \[`header`, `context`, `hfunc`, `indir`, `hkey`, `input-xfrm`, `flow-hash`\]

<a id="rst-plca-get-cfg"></a>
<a id="rst-ethtool-operation-plca-get-cfg"></a>



### plca-get-cfg



Get PLCA params.

- **attribute-set**:

  [plca](#rst-ethtool-attribute-set-plca)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `version`, `enabled`, `status`, `node-cnt`, `node-id`, `to-tmr`, `burst-cnt`, `burst-tmr`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `version`, `enabled`, `status`, `node-cnt`, `node-id`, `to-tmr`, `burst-cnt`, `burst-tmr`\]

<a id="rst-plca-set-cfg"></a>
<a id="rst-ethtool-operation-plca-set-cfg"></a>



### plca-set-cfg



Set PLCA params.

- **attribute-set**:

  [plca](#rst-ethtool-attribute-set-plca)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `version`, `enabled`, `status`, `node-cnt`, `node-id`, `to-tmr`, `burst-cnt`, `burst-tmr`\]

<a id="rst-plca-get-status"></a>
<a id="rst-ethtool-operation-plca-get-status"></a>



### plca-get-status



Get PLCA status params.

- **attribute-set**:

  [plca](#rst-ethtool-attribute-set-plca)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `version`, `enabled`, `status`, `node-cnt`, `node-id`, `to-tmr`, `burst-cnt`, `burst-tmr`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `version`, `enabled`, `status`, `node-cnt`, `node-id`, `to-tmr`, `burst-cnt`, `burst-tmr`\]

<a id="rst-plca-ntf"></a>
<a id="rst-ethtool-operation-plca-ntf"></a>



### plca-ntf



Notification for change in PLCA params.

- **notify**:

  plca-get-cfg

<a id="rst-mm-get"></a>
<a id="rst-ethtool-operation-mm-get"></a>



### mm-get



Get MAC Merge configuration and state

- **attribute-set**:

  [mm](#rst-ethtool-attribute-set-mm)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `pmac-enabled`, `tx-enabled`, `tx-active`, `tx-min-frag-size`, `rx-min-frag-size`, `verify-enabled`, `verify-time`, `max-verify-time`, `stats`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `pmac-enabled`, `tx-enabled`, `tx-active`, `tx-min-frag-size`, `rx-min-frag-size`, `verify-enabled`, `verify-time`, `max-verify-time`, `stats`\]

<a id="rst-mm-set"></a>
<a id="rst-ethtool-operation-mm-set"></a>



### mm-set



Set MAC Merge configuration

- **attribute-set**:

  [mm](#rst-ethtool-attribute-set-mm)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `verify-enabled`, `verify-time`, `tx-enabled`, `pmac-enabled`, `tx-min-frag-size`\]

<a id="rst-mm-ntf"></a>
<a id="rst-ethtool-operation-mm-ntf"></a>



### mm-ntf



Notification for change in MAC Merge configuration.

- **notify**:

  mm-get

<a id="rst-module-fw-flash-act"></a>
<a id="rst-ethtool-operation-module-fw-flash-act"></a>



### module-fw-flash-act



Flash transceiver module firmware.

- **attribute-set**:

  [module-fw-flash](#rst-ethtool-attribute-set-module-fw-flash)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `file-name`, `password`\]

<a id="rst-module-fw-flash-ntf"></a>
<a id="rst-ethtool-operation-module-fw-flash-ntf"></a>



### module-fw-flash-ntf



Notification for firmware flashing progress and status.

- **attribute-set**:

  [module-fw-flash](#rst-ethtool-attribute-set-module-fw-flash)

- **event**:

  - **attributes**:

    \[`header`, `status`, `status-msg`, `done`, `total`\]

<a id="rst-phy-get"></a>
<a id="rst-ethtool-operation-phy-get"></a>



### phy-get



Get PHY devices attached to an interface

- **attribute-set**:

  [phy](#rst-ethtool-attribute-set-phy)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `index`, `drvname`, `name`, `upstream-type`, `upstream-index`, `upstream-sfp-name`, `downstream-sfp-name`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `index`, `drvname`, `name`, `upstream-type`, `upstream-index`, `upstream-sfp-name`, `downstream-sfp-name`\]

<a id="rst-phy-ntf"></a>
<a id="rst-ethtool-operation-phy-ntf"></a>



### phy-ntf



Notification for change in PHY devices.

- **notify**:

  phy-get

<a id="rst-tsconfig-get"></a>
<a id="rst-ethtool-operation-tsconfig-get"></a>



### tsconfig-get



Get hwtstamp config.

- **attribute-set**:

  [tsconfig](#rst-ethtool-attribute-set-tsconfig)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `hwtstamp-provider`, `tx-types`, `rx-filters`, `hwtstamp-flags`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `hwtstamp-provider`, `tx-types`, `rx-filters`, `hwtstamp-flags`\]

<a id="rst-tsconfig-set"></a>
<a id="rst-ethtool-operation-tsconfig-set"></a>



### tsconfig-set



Set hwtstamp config.

- **attribute-set**:

  [tsconfig](#rst-ethtool-attribute-set-tsconfig)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `hwtstamp-provider`, `tx-types`, `rx-filters`, `hwtstamp-flags`\]

  **reply**

  - **attributes**:

    \[`header`, `hwtstamp-provider`, `tx-types`, `rx-filters`, `hwtstamp-flags`\]

<a id="rst-pse-ntf"></a>
<a id="rst-ethtool-operation-pse-ntf"></a>



### pse-ntf



Notification for PSE events.

- **attribute-set**:

  [pse-ntf](#rst-ethtool-attribute-set-pse-ntf)

- **event**:

  - **attributes**:

    \[`header`, `events`\]

<a id="rst-rss-set"></a>
<a id="rst-ethtool-operation-rss-set"></a>



### rss-set



Set RSS params.

- **attribute-set**:

  [rss](#rst-ethtool-attribute-set-rss)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `context`, `hfunc`, `indir`, `hkey`, `input-xfrm`, `flow-hash`\]

<a id="rst-rss-ntf"></a>
<a id="rst-ethtool-operation-rss-ntf"></a>



### rss-ntf



Notification for change in RSS configuration.
For additional contexts only modifications use this notification,
creation and deletion have dedicated messages.

- **notify**:

  rss-get

<a id="rst-rss-create-act"></a>
<a id="rst-ethtool-operation-rss-create-act"></a>



### rss-create-act



Create an RSS context.

- **attribute-set**:

  [rss](#rst-ethtool-attribute-set-rss)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `context`, `hfunc`, `indir`, `hkey`, `input-xfrm`\]

  **reply**

  - **attributes**:

    \[`header`, `context`, `hfunc`, `indir`, `hkey`, `input-xfrm`\]

<a id="rst-rss-create-ntf"></a>
<a id="rst-ethtool-operation-rss-create-ntf"></a>



### rss-create-ntf



Notification for creation of an additional RSS context.

- **notify**:

  rss-create-act

<a id="rst-rss-delete-act"></a>
<a id="rst-ethtool-operation-rss-delete-act"></a>



### rss-delete-act



Delete an RSS context.

- **attribute-set**:

  [rss](#rst-ethtool-attribute-set-rss)

- **do**:

  **request**

  - **attributes**:

    \[`header`, `context`\]

<a id="rst-rss-delete-ntf"></a>
<a id="rst-ethtool-operation-rss-delete-ntf"></a>



### rss-delete-ntf



Notification for deletion of an additional RSS context.

- **attribute-set**:

  [rss](#rst-ethtool-attribute-set-rss)

- **event**:

  - **attributes**:

    \[`header`, `context`\]

<a id="rst-mse-get"></a>
<a id="rst-ethtool-operation-mse-get"></a>



### mse-get



Get PHY MSE measurement data and capabilities.

- **attribute-set**:

  [mse](#rst-ethtool-attribute-set-mse)

- **do**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `capabilities`, `channel-a`, `channel-b`, `channel-c`, `channel-d`, `worst-channel`, `link`\]

- **dump**:

  **request**

  - **attributes**:

    \[`header`\]

  **reply**

  - **attributes**:

    \[`header`, `capabilities`, `channel-a`, `channel-b`, `channel-c`, `channel-d`, `worst-channel`, `link`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- monitor


<a id="rst-definitions"></a>



## Definitions

<a id="rst-udp-tunnel-type"></a>
<a id="rst-ethtool-definition-udp-tunnel-type"></a>



### udp-tunnel-type

- **enum-name**:

  None

- **type**:

  enum

- **enum-cnt-name**:

  \_\_ethtool-udp-tunnel-type-cnt

- **entries**:

  - `vxlan`


  - `geneve`


  - `vxlan-gpe`

<a id="rst-stringset"></a>
<a id="rst-ethtool-definition-stringset"></a>



### stringset

- **type**:

  enum

- **header**:

  linux/ethtool.h

- **entries**

<a id="rst-header-flags"></a>
<a id="rst-ethtool-definition-header-flags"></a>



### header-flags

- **type**:

  flags

- **name-prefix**:

  ethtool-flag-

- **doc**:

  common ethtool header flags

- **entries**:

  - **compact-bitsets**:

    use compact bitsets in reply

  - **omit-reply**:

    provide optional reply for SET or ACT requests

  - **stats**:

    request statistics, if supported by the driver

<a id="rst-module-fw-flash-status"></a>
<a id="rst-ethtool-definition-module-fw-flash-status"></a>



### module-fw-flash-status

- **type**:

  enum

- **doc**:

  plug-in module firmware flashing status

- **header**:

  linux/ethtool.h

- **entries**:

  - **started**:

    The firmware flashing process has started.

  - **in-progress**:

    The firmware flashing process is in progress.

  - **completed**:

    The firmware flashing process was completed successfully.

  - **error**:

    The firmware flashing process was stopped due to an error.

<a id="rst-c33-pse-ext-state"></a>
<a id="rst-ethtool-definition-c33-pse-ext-state"></a>



### c33-pse-ext-state

- **doc**:

  "groups of PSE extended states functions. IEEE 802.3-2022 33.2.4.4 Variables"

- **type**:

  enum

- **name-prefix**:

  ethtool-c33-pse-ext-state-

- **header**:

  linux/ethtool.h

- **entries**:

  - **none**:

    none

  - **error-condition**:

    Group of error\_condition states

  - **mr-mps-valid**:

    Group of mr\_mps\_valid states

  - **mr-pse-enable**:

    Group of mr\_pse\_enable states

  - **option-detect-ted**:

    Group of option\_detect\_ted states

  - **option-vport-lim**:

    Group of option\_vport\_lim states

  - **ovld-detected**:

    Group of ovld\_detected states

  - **power-not-available**:

    Group of power\_not\_available states

  - **short-detected**:

    Group of short\_detected states

<a id="rst-phy-upstream-type"></a>
<a id="rst-ethtool-definition-phy-upstream-type"></a>



### phy-upstream-type

- **enum-name**:

  phy-upstream

- **header**:

  linux/ethtool.h

- **type**:

  enum

- **name-prefix**:

  phy-upstream

- **entries**:

  - `mac`


  - `phy`

<a id="rst-tcp-data-split"></a>
<a id="rst-ethtool-definition-tcp-data-split"></a>



### tcp-data-split

- **type**:

  enum

- **entries**:

  - `unknown`


  - `disabled`


  - `enabled`

<a id="rst-hwtstamp-source"></a>
<a id="rst-ethtool-definition-hwtstamp-source"></a>



### hwtstamp-source

- **doc**:

  Source of the hardware timestamp

- **enum-name**:

  hwtstamp-source

- **name-prefix**:

  hwtstamp-source-

- **type**:

  enum

- **entries**:

  - **netdev**:

    Hardware timestamp comes from a MAC or a device which has MAC and PHY integrated

  - **phylib**:

    Hardware timestamp comes from one PHY device of the network topology

<a id="rst-pse-event"></a>
<a id="rst-ethtool-definition-pse-event"></a>



### pse-event

- **doc**:

  PSE event list for the PSE controller

- **type**:

  flags

- **name-prefix**:

  ethtool-

- **entries**:

  - **pse-event-over-current**:

    PSE output current is too high

  - **pse-event-over-temp**:

    PSE in over temperature state

  - **c33-pse-event-detection**:

    detection process occur on the PSE. IEEE 802.3-2022 33.2.5 and 145.2.6 PSE detection of PDs. IEEE 802.3-202 30.9.1.1.5 aPSEPowerDetectionStatus

  - **c33-pse-event-classification**:

    classification process occur on the PSE. IEEE 802.3-2022 33.2.6 and 145.2.8 classification of PDs mutual identification. IEEE 802.3-2022 30.9.1.1.8 aPSEPowerClassification.

  - **c33-pse-event-disconnection**:

    PD has been disconnected on the PSE. IEEE 802.3-2022 33.3.8 and 145.3.9 PD Maintain Power Signature. IEEE 802.3-2022 33.5.1.2.9 MPS Absent. IEEE 802.3-2022 30.9.1.1.20 aPSEMPSAbsentCounter.

  - **pse-event-over-budget**:

    PSE turned off due to over budget situation

  - **pse-event-sw-pw-control-error**:

    PSE faced an error managing the power control from software

<a id="rst-input-xfrm"></a>
<a id="rst-ethtool-definition-input-xfrm"></a>



### input-xfrm

- **doc**:

  RSS hash function transformations.

- **type**:

  flags

- **enum-name**:

  None

- **name-prefix**:

  rxh-xfrm-

- **header**:

  linux/ethtool.h

- **entries**:

  - **sym-xor**:

    XOR the corresponding source and destination fields of each specified protocol. Both copies of the XOR'ed fields are fed into the RSS and RXHASH calculation. Note that this XORing reduces the input set entropy and could be exploited to reduce the RSS queue spread.

  - **sym-or-xor**:

    Similar to SYM\_XOR, except that one copy of the XOR'ed fields is replaced by an OR of the same fields.

<a id="rst-rxfh-fields"></a>
<a id="rst-ethtool-definition-rxfh-fields"></a>



### rxfh-fields

- **name-prefix**:

  rxh-

- **enum-name**:

  None

- **header**:

  linux/ethtool.h

- **type**:

  flags

- **entries**:

  - **l2da**

  - **vlan**

  - **l3-proto**

  - **ip-src**

  - **ip-dst**

  - **l4-b-0-1**:

    src port in case of TCP/UDP/SCTP

  - **l4-b-2-3**:

    dst port in case of TCP/UDP/SCTP

  - **gtp-teid**

  - **ip6-fl**:

    IPv6 Flow Label

  - **discard**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-header"></a>
<a id="rst-ethtool-attribute-set-header"></a>



### header

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-dev-index-u32"></a>



#### dev-index (`u32`)

<a id="rst-dev-name-string"></a>



#### dev-name (`string`)

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **enum**:

  [header-flags](#rst-ethtool-definition-header-flags)

<a id="rst-phy-index-u32"></a>



#### phy-index (`u32`)

<a id="rst-bitset-bit"></a>
<a id="rst-ethtool-attribute-set-bitset-bit"></a>



### bitset-bit

<a id="rst-unspec-unused-1"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-index-u32"></a>



#### index (`u32`)

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-value-flag"></a>



#### value (`flag`)

<a id="rst-bitset-bits"></a>
<a id="rst-ethtool-attribute-set-bitset-bits"></a>



### bitset-bits

<a id="rst-unspec-unused-2"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-bit-nest"></a>



#### bit (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [bitset-bit](#rst-ethtool-attribute-set-bitset-bit)

<a id="rst-bitset"></a>
<a id="rst-ethtool-attribute-set-bitset"></a>



### bitset

<a id="rst-unspec-unused-3"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-nomask-flag"></a>



#### nomask (`flag`)

<a id="rst-size-u32"></a>



#### size (`u32`)

<a id="rst-bits-nest"></a>



#### bits (`nest`)

- **nested-attributes**:

  [bitset-bits](#rst-ethtool-attribute-set-bitset-bits)

<a id="rst-value-binary"></a>



#### value (`binary`)

<a id="rst-mask-binary"></a>



#### mask (`binary`)

<a id="rst-string"></a>
<a id="rst-ethtool-attribute-set-string"></a>



### string

<a id="rst-unspec-unused-4"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-index-u32-1"></a>



#### index (`u32`)

<a id="rst-value-string"></a>



#### value (`string`)

<a id="rst-strings"></a>
<a id="rst-ethtool-attribute-set-strings"></a>



### strings

<a id="rst-unspec-unused-5"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-unspec-unused-6"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-string-nest"></a>



#### string (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [string](#rst-ethtool-attribute-set-string)

<a id="rst-stringset-1"></a>
<a id="rst-ethtool-attribute-set-stringset"></a>



### stringset

<a id="rst-unspec-unused-7"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-id-u32"></a>



#### id (`u32`)

<a id="rst-count-u32"></a>



#### count (`u32`)

<a id="rst-strings-nest"></a>



#### strings (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [strings](#rst-ethtool-attribute-set-strings)

<a id="rst-stringsets"></a>
<a id="rst-ethtool-attribute-set-stringsets"></a>



### stringsets

<a id="rst-unspec-unused-8"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-stringset-nest"></a>



#### stringset (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [stringset](#rst-ethtool-attribute-set-stringset)

<a id="rst-strset"></a>
<a id="rst-ethtool-attribute-set-strset"></a>



### strset

<a id="rst-unspec-unused-9"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-stringsets-nest"></a>



#### stringsets (`nest`)

- **nested-attributes**:

  [stringsets](#rst-ethtool-attribute-set-stringsets)

<a id="rst-counts-only-flag"></a>



#### counts-only (`flag`)

<a id="rst-privflags"></a>
<a id="rst-ethtool-attribute-set-privflags"></a>



### privflags

<a id="rst-unspec-unused-10"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-1"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-flags-nest"></a>



#### flags (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-rings"></a>
<a id="rst-ethtool-attribute-set-rings"></a>



### rings

<a id="rst-unspec-unused-11"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-2"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-rx-max-u32"></a>



#### rx-max (`u32`)

<a id="rst-rx-mini-max-u32"></a>



#### rx-mini-max (`u32`)

<a id="rst-rx-jumbo-max-u32"></a>



#### rx-jumbo-max (`u32`)

<a id="rst-tx-max-u32"></a>



#### tx-max (`u32`)

<a id="rst-rx-u32"></a>



#### rx (`u32`)

<a id="rst-rx-mini-u32"></a>



#### rx-mini (`u32`)

<a id="rst-rx-jumbo-u32"></a>



#### rx-jumbo (`u32`)

<a id="rst-tx-u32"></a>



#### tx (`u32`)

<a id="rst-rx-buf-len-u32"></a>



#### rx-buf-len (`u32`)

<a id="rst-tcp-data-split-u8"></a>



#### tcp-data-split (`u8`)

- **enum**:

  [tcp-data-split](#rst-ethtool-definition-tcp-data-split)

<a id="rst-cqe-size-u32"></a>



#### cqe-size (`u32`)

<a id="rst-tx-push-u8"></a>



#### tx-push (`u8`)

<a id="rst-rx-push-u8"></a>



#### rx-push (`u8`)

<a id="rst-tx-push-buf-len-u32"></a>



#### tx-push-buf-len (`u32`)

<a id="rst-tx-push-buf-len-max-u32"></a>



#### tx-push-buf-len-max (`u32`)

<a id="rst-hds-thresh-u32"></a>



#### hds-thresh (`u32`)

<a id="rst-hds-thresh-max-u32"></a>



#### hds-thresh-max (`u32`)

<a id="rst-mm-stat"></a>
<a id="rst-ethtool-attribute-set-mm-stat"></a>



### mm-stat



MAC Merge (802.3)

<a id="rst-unspec-unused-12"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-reassembly-errors-u64"></a>



#### reassembly-errors (`u64`)

- **doc**:

  aMACMergeFrameAssErrorCount

<a id="rst-smd-errors-u64"></a>



#### smd-errors (`u64`)

- **doc**:

  aMACMergeFrameSmdErrorCount

<a id="rst-reassembly-ok-u64"></a>



#### reassembly-ok (`u64`)

- **doc**:

  aMACMergeFrameAssOkCount

<a id="rst-rx-frag-count-u64"></a>



#### rx-frag-count (`u64`)

- **doc**:

  aMACMergeFragCountRx

<a id="rst-tx-frag-count-u64"></a>



#### tx-frag-count (`u64`)

- **doc**:

  aMACMergeFragCountTx

<a id="rst-hold-count-u64"></a>



#### hold-count (`u64`)

- **doc**:

  aMACMergeHoldCount

<a id="rst-mm"></a>
<a id="rst-ethtool-attribute-set-mm"></a>



### mm

<a id="rst-unspec-unused-13"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-3"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-pmac-enabled-u8"></a>



#### pmac-enabled (`u8`)

<a id="rst-tx-enabled-u8"></a>



#### tx-enabled (`u8`)

<a id="rst-tx-active-u8"></a>



#### tx-active (`u8`)

<a id="rst-tx-min-frag-size-u32"></a>



#### tx-min-frag-size (`u32`)

<a id="rst-rx-min-frag-size-u32"></a>



#### rx-min-frag-size (`u32`)

<a id="rst-verify-enabled-u8"></a>



#### verify-enabled (`u8`)

<a id="rst-verify-status-u8"></a>



#### verify-status (`u8`)

<a id="rst-verify-time-u32"></a>



#### verify-time (`u32`)

<a id="rst-max-verify-time-u32"></a>



#### max-verify-time (`u32`)

<a id="rst-stats-nest"></a>



#### stats (`nest`)

- **nested-attributes**:

  [mm-stat](#rst-ethtool-attribute-set-mm-stat)

<a id="rst-linkinfo"></a>
<a id="rst-ethtool-attribute-set-linkinfo"></a>



### linkinfo

<a id="rst-unspec-unused-14"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-4"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-port-u8"></a>



#### port (`u8`)

<a id="rst-phyaddr-u8"></a>



#### phyaddr (`u8`)

<a id="rst-tp-mdix-u8"></a>



#### tp-mdix (`u8`)

<a id="rst-tp-mdix-ctrl-u8"></a>



#### tp-mdix-ctrl (`u8`)

<a id="rst-transceiver-u8"></a>



#### transceiver (`u8`)

<a id="rst-linkmodes"></a>
<a id="rst-ethtool-attribute-set-linkmodes"></a>



### linkmodes

<a id="rst-unspec-unused-15"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-5"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-autoneg-u8"></a>



#### autoneg (`u8`)

<a id="rst-ours-nest"></a>



#### ours (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-peer-nest"></a>



#### peer (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-speed-u32"></a>



#### speed (`u32`)

<a id="rst-duplex-u8"></a>



#### duplex (`u8`)

<a id="rst-master-slave-cfg-u8"></a>



#### master-slave-cfg (`u8`)

<a id="rst-master-slave-state-u8"></a>



#### master-slave-state (`u8`)

<a id="rst-lanes-u32"></a>



#### lanes (`u32`)

<a id="rst-rate-matching-u8"></a>



#### rate-matching (`u8`)

<a id="rst-linkstate"></a>
<a id="rst-ethtool-attribute-set-linkstate"></a>



### linkstate

<a id="rst-unspec-unused-16"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-6"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-link-u8"></a>



#### link (`u8`)

<a id="rst-sqi-u32"></a>



#### sqi (`u32`)

<a id="rst-sqi-max-u32"></a>



#### sqi-max (`u32`)

<a id="rst-ext-state-u8"></a>



#### ext-state (`u8`)

<a id="rst-ext-substate-u8"></a>



#### ext-substate (`u8`)

<a id="rst-ext-down-cnt-u32"></a>



#### ext-down-cnt (`u32`)

<a id="rst-debug"></a>
<a id="rst-ethtool-attribute-set-debug"></a>



### debug

<a id="rst-unspec-unused-17"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-7"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-msgmask-nest"></a>



#### msgmask (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-wol"></a>
<a id="rst-ethtool-attribute-set-wol"></a>



### wol

<a id="rst-unspec-unused-18"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-8"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-modes-nest"></a>



#### modes (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-sopass-binary"></a>



#### sopass (`binary`)

<a id="rst-features"></a>
<a id="rst-ethtool-attribute-set-features"></a>



### features

<a id="rst-unspec-unused-19"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-9"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-hw-nest"></a>



#### hw (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-wanted-nest"></a>



#### wanted (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-active-nest"></a>



#### active (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-nochange-nest"></a>



#### nochange (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-channels"></a>
<a id="rst-ethtool-attribute-set-channels"></a>



### channels

<a id="rst-unspec-unused-20"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-10"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-rx-max-u32-1"></a>



#### rx-max (`u32`)

<a id="rst-tx-max-u32-1"></a>



#### tx-max (`u32`)

<a id="rst-other-max-u32"></a>



#### other-max (`u32`)

<a id="rst-combined-max-u32"></a>



#### combined-max (`u32`)

<a id="rst-rx-count-u32"></a>



#### rx-count (`u32`)

<a id="rst-tx-count-u32"></a>



#### tx-count (`u32`)

<a id="rst-other-count-u32"></a>



#### other-count (`u32`)

<a id="rst-combined-count-u32"></a>



#### combined-count (`u32`)

<a id="rst-irq-moderation"></a>
<a id="rst-ethtool-attribute-set-irq-moderation"></a>



### irq-moderation

<a id="rst-unspec-unused-21"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-usec-u32"></a>



#### usec (`u32`)

<a id="rst-pkts-u32"></a>



#### pkts (`u32`)

<a id="rst-comps-u32"></a>



#### comps (`u32`)

<a id="rst-profile"></a>
<a id="rst-ethtool-attribute-set-profile"></a>



### profile

<a id="rst-unspec-unused-22"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-irq-moderation-nest"></a>



#### irq-moderation (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [irq-moderation](#rst-ethtool-attribute-set-irq-moderation)

<a id="rst-coalesce"></a>
<a id="rst-ethtool-attribute-set-coalesce"></a>



### coalesce

<a id="rst-unspec-unused-23"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-11"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-rx-usecs-u32"></a>



#### rx-usecs (`u32`)

<a id="rst-rx-max-frames-u32"></a>



#### rx-max-frames (`u32`)

<a id="rst-rx-usecs-irq-u32"></a>



#### rx-usecs-irq (`u32`)

<a id="rst-rx-max-frames-irq-u32"></a>



#### rx-max-frames-irq (`u32`)

<a id="rst-tx-usecs-u32"></a>



#### tx-usecs (`u32`)

<a id="rst-tx-max-frames-u32"></a>



#### tx-max-frames (`u32`)

<a id="rst-tx-usecs-irq-u32"></a>



#### tx-usecs-irq (`u32`)

<a id="rst-tx-max-frames-irq-u32"></a>



#### tx-max-frames-irq (`u32`)

<a id="rst-stats-block-usecs-u32"></a>



#### stats-block-usecs (`u32`)

<a id="rst-use-adaptive-rx-u8"></a>



#### use-adaptive-rx (`u8`)

<a id="rst-use-adaptive-tx-u8"></a>



#### use-adaptive-tx (`u8`)

<a id="rst-pkt-rate-low-u32"></a>



#### pkt-rate-low (`u32`)

<a id="rst-rx-usecs-low-u32"></a>



#### rx-usecs-low (`u32`)

<a id="rst-rx-max-frames-low-u32"></a>



#### rx-max-frames-low (`u32`)

<a id="rst-tx-usecs-low-u32"></a>



#### tx-usecs-low (`u32`)

<a id="rst-tx-max-frames-low-u32"></a>



#### tx-max-frames-low (`u32`)

<a id="rst-pkt-rate-high-u32"></a>



#### pkt-rate-high (`u32`)

<a id="rst-rx-usecs-high-u32"></a>



#### rx-usecs-high (`u32`)

<a id="rst-rx-max-frames-high-u32"></a>



#### rx-max-frames-high (`u32`)

<a id="rst-tx-usecs-high-u32"></a>



#### tx-usecs-high (`u32`)

<a id="rst-tx-max-frames-high-u32"></a>



#### tx-max-frames-high (`u32`)

<a id="rst-rate-sample-interval-u32"></a>



#### rate-sample-interval (`u32`)

<a id="rst-use-cqe-mode-tx-u8"></a>



#### use-cqe-mode-tx (`u8`)

<a id="rst-use-cqe-mode-rx-u8"></a>



#### use-cqe-mode-rx (`u8`)

<a id="rst-tx-aggr-max-bytes-u32"></a>



#### tx-aggr-max-bytes (`u32`)

<a id="rst-tx-aggr-max-frames-u32"></a>



#### tx-aggr-max-frames (`u32`)

<a id="rst-tx-aggr-time-usecs-u32"></a>



#### tx-aggr-time-usecs (`u32`)

<a id="rst-rx-profile-nest"></a>



#### rx-profile (`nest`)

- **nested-attributes**:

  [profile](#rst-ethtool-attribute-set-profile)

<a id="rst-tx-profile-nest"></a>



#### tx-profile (`nest`)

- **nested-attributes**:

  [profile](#rst-ethtool-attribute-set-profile)

<a id="rst-pause-stat"></a>
<a id="rst-ethtool-attribute-set-pause-stat"></a>



### pause-stat

<a id="rst-unspec-unused-24"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-tx-frames-u64"></a>



#### tx-frames (`u64`)

<a id="rst-rx-frames-u64"></a>



#### rx-frames (`u64`)

<a id="rst-pause"></a>
<a id="rst-ethtool-attribute-set-pause"></a>



### pause

<a id="rst-unspec-unused-25"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-12"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-autoneg-u8-1"></a>



#### autoneg (`u8`)

<a id="rst-rx-u8"></a>



#### rx (`u8`)

<a id="rst-tx-u8"></a>



#### tx (`u8`)

<a id="rst-stats-nest-1"></a>



#### stats (`nest`)

- **nested-attributes**:

  [pause-stat](#rst-ethtool-attribute-set-pause-stat)

<a id="rst-stats-src-u32"></a>



#### stats-src (`u32`)

<a id="rst-eee"></a>
<a id="rst-ethtool-attribute-set-eee"></a>



### eee

<a id="rst-unspec-unused-26"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-13"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-modes-ours-nest"></a>



#### modes-ours (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-modes-peer-nest"></a>



#### modes-peer (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-active-u8"></a>



#### active (`u8`)

<a id="rst-enabled-u8"></a>



#### enabled (`u8`)

<a id="rst-tx-lpi-enabled-u8"></a>



#### tx-lpi-enabled (`u8`)

<a id="rst-tx-lpi-timer-u32"></a>



#### tx-lpi-timer (`u32`)

<a id="rst-ts-stat"></a>
<a id="rst-ethtool-attribute-set-ts-stat"></a>



### ts-stat

<a id="rst-unspec-unused-27"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-tx-pkts-uint"></a>



#### tx-pkts (`uint`)

<a id="rst-tx-lost-uint"></a>



#### tx-lost (`uint`)

<a id="rst-tx-err-uint"></a>



#### tx-err (`uint`)

<a id="rst-tx-onestep-pkts-unconfirmed-uint"></a>



#### tx-onestep-pkts-unconfirmed (`uint`)

<a id="rst-ts-hwtstamp-provider"></a>
<a id="rst-ethtool-attribute-set-ts-hwtstamp-provider"></a>



### ts-hwtstamp-provider

<a id="rst-unspec-unused-28"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-index-u32-2"></a>



#### index (`u32`)

<a id="rst-qualifier-u32"></a>



#### qualifier (`u32`)

<a id="rst-tsinfo"></a>
<a id="rst-ethtool-attribute-set-tsinfo"></a>



### tsinfo

<a id="rst-unspec-unused-29"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-14"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-timestamping-nest"></a>



#### timestamping (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-tx-types-nest"></a>



#### tx-types (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-rx-filters-nest"></a>



#### rx-filters (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-phc-index-u32"></a>



#### phc-index (`u32`)

<a id="rst-stats-nest-2"></a>



#### stats (`nest`)

- **nested-attributes**:

  [ts-stat](#rst-ethtool-attribute-set-ts-stat)

<a id="rst-hwtstamp-provider-nest"></a>



#### hwtstamp-provider (`nest`)

- **nested-attributes**:

  [ts-hwtstamp-provider](#rst-ethtool-attribute-set-ts-hwtstamp-provider)

<a id="rst-hwtstamp-source-u32"></a>



#### hwtstamp-source (`u32`)

- **enum**:

  [hwtstamp-source](#rst-ethtool-definition-hwtstamp-source)

<a id="rst-hwtstamp-phyindex-u32"></a>



#### hwtstamp-phyindex (`u32`)

<a id="rst-cable-result"></a>
<a id="rst-ethtool-attribute-set-cable-result"></a>



### cable-result

<a id="rst-unspec-unused-30"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pair-u8"></a>



#### pair (`u8`)

- **doc**:

  ETHTOOL\_A\_CABLE\_PAIR

<a id="rst-code-u8"></a>



#### code (`u8`)

- **doc**:

  ETHTOOL\_A\_CABLE\_RESULT\_CODE

<a id="rst-src-u32"></a>



#### src (`u32`)

- **doc**:

  ETHTOOL\_A\_CABLE\_INF\_SRC

<a id="rst-cable-fault-length"></a>
<a id="rst-ethtool-attribute-set-cable-fault-length"></a>



### cable-fault-length

<a id="rst-unspec-unused-31"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pair-u8-1"></a>



#### pair (`u8`)

<a id="rst-cm-u32"></a>



#### cm (`u32`)

<a id="rst-src-u32-1"></a>



#### src (`u32`)

<a id="rst-cable-nest"></a>
<a id="rst-ethtool-attribute-set-cable-nest"></a>



### cable-nest

<a id="rst-unspec-unused-32"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-result-nest"></a>



#### result (`nest`)

- **nested-attributes**:

  [cable-result](#rst-ethtool-attribute-set-cable-result)

<a id="rst-fault-length-nest"></a>



#### fault-length (`nest`)

- **nested-attributes**:

  [cable-fault-length](#rst-ethtool-attribute-set-cable-fault-length)

<a id="rst-cable-test"></a>
<a id="rst-ethtool-attribute-set-cable-test"></a>



### cable-test

<a id="rst-unspec-unused-33"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-15"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-cable-test-ntf-1"></a>
<a id="rst-ethtool-attribute-set-cable-test-ntf"></a>



### cable-test-ntf

<a id="rst-unspec-unused-34"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-16"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-status-u8"></a>



#### status (`u8`)

- **doc**:

  \_STARTED/\_COMPLETE

<a id="rst-nest-nest"></a>



#### nest (`nest`)

- **nested-attributes**:

  [cable-nest](#rst-ethtool-attribute-set-cable-nest)

<a id="rst-cable-test-tdr-cfg"></a>
<a id="rst-ethtool-attribute-set-cable-test-tdr-cfg"></a>



### cable-test-tdr-cfg

<a id="rst-unspec-unused-35"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-first-u32"></a>



#### first (`u32`)

<a id="rst-last-u32"></a>



#### last (`u32`)

<a id="rst-step-u32"></a>



#### step (`u32`)

<a id="rst-pair-u8-2"></a>



#### pair (`u8`)

<a id="rst-cable-test-tdr-ntf-1"></a>
<a id="rst-ethtool-attribute-set-cable-test-tdr-ntf"></a>



### cable-test-tdr-ntf

<a id="rst-unspec-unused-36"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-17"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-status-u8-1"></a>



#### status (`u8`)

<a id="rst-nest-nest-1"></a>



#### nest (`nest`)

- **nested-attributes**:

  [cable-nest](#rst-ethtool-attribute-set-cable-nest)

<a id="rst-cable-test-tdr"></a>
<a id="rst-ethtool-attribute-set-cable-test-tdr"></a>



### cable-test-tdr

<a id="rst-unspec-unused-37"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-18"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-cfg-nest"></a>



#### cfg (`nest`)

- **nested-attributes**:

  [cable-test-tdr-cfg](#rst-ethtool-attribute-set-cable-test-tdr-cfg)

<a id="rst-tunnel-udp-entry"></a>
<a id="rst-ethtool-attribute-set-tunnel-udp-entry"></a>



### tunnel-udp-entry

<a id="rst-unspec-unused-38"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-port-u16"></a>



#### port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-type-u32"></a>



#### type (`u32`)

- **enum**:

  [udp-tunnel-type](#rst-ethtool-definition-udp-tunnel-type)

<a id="rst-tunnel-udp-table"></a>
<a id="rst-ethtool-attribute-set-tunnel-udp-table"></a>



### tunnel-udp-table

<a id="rst-unspec-unused-39"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-size-u32-1"></a>



#### size (`u32`)

<a id="rst-types-nest"></a>



#### types (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-entry-nest"></a>



#### entry (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [tunnel-udp-entry](#rst-ethtool-attribute-set-tunnel-udp-entry)

<a id="rst-tunnel-udp"></a>
<a id="rst-ethtool-attribute-set-tunnel-udp"></a>



### tunnel-udp

<a id="rst-unspec-unused-40"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-table-nest"></a>



#### table (`nest`)

- **nested-attributes**:

  [tunnel-udp-table](#rst-ethtool-attribute-set-tunnel-udp-table)

<a id="rst-tunnel-info"></a>
<a id="rst-ethtool-attribute-set-tunnel-info"></a>



### tunnel-info

<a id="rst-unspec-unused-41"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-19"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-udp-ports-nest"></a>



#### udp-ports (`nest`)

- **nested-attributes**:

  [tunnel-udp](#rst-ethtool-attribute-set-tunnel-udp)

<a id="rst-fec-hist"></a>
<a id="rst-ethtool-attribute-set-fec-hist"></a>



### fec-hist

<a id="rst-pad-pad-2"></a>



#### pad (`pad`)

<a id="rst-bin-low-u32"></a>



#### bin-low (`u32`)

- **doc**:

  Low bound of FEC bin (inclusive)

<a id="rst-bin-high-u32"></a>



#### bin-high (`u32`)

- **doc**:

  High bound of FEC bin (inclusive)

<a id="rst-bin-val-uint"></a>



#### bin-val (`uint`)

- **doc**:

  Error count in the bin (optional if per-lane values exist)

<a id="rst-bin-val-per-lane-binary"></a>



#### bin-val-per-lane (`binary`)

- **sub-type**:

  u64

- **doc**:

  An array of per-lane error counters in the bin (optional)

<a id="rst-fec-stat"></a>
<a id="rst-ethtool-attribute-set-fec-stat"></a>



### fec-stat

<a id="rst-unspec-unused-42"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pad-pad-3"></a>



#### pad (`pad`)

<a id="rst-corrected-binary"></a>



#### corrected (`binary`)

- **sub-type**:

  u64

<a id="rst-uncorr-binary"></a>



#### uncorr (`binary`)

- **sub-type**:

  u64

<a id="rst-corr-bits-binary"></a>



#### corr-bits (`binary`)

- **sub-type**:

  u64

<a id="rst-hist-nest"></a>



#### hist (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [fec-hist](#rst-ethtool-attribute-set-fec-hist)

<a id="rst-fec"></a>
<a id="rst-ethtool-attribute-set-fec"></a>



### fec

<a id="rst-unspec-unused-43"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-20"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-modes-nest-1"></a>



#### modes (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-auto-u8"></a>



#### auto (`u8`)

<a id="rst-active-u32"></a>



#### active (`u32`)

<a id="rst-stats-nest-3"></a>



#### stats (`nest`)

- **nested-attributes**:

  [fec-stat](#rst-ethtool-attribute-set-fec-stat)

<a id="rst-module-eeprom"></a>
<a id="rst-ethtool-attribute-set-module-eeprom"></a>



### module-eeprom

<a id="rst-unspec-unused-44"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-21"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-offset-u32"></a>



#### offset (`u32`)

<a id="rst-length-u32"></a>



#### length (`u32`)

<a id="rst-page-u8"></a>



#### page (`u8`)

<a id="rst-bank-u8"></a>



#### bank (`u8`)

<a id="rst-i2c-address-u8"></a>



#### i2c-address (`u8`)

<a id="rst-data-binary"></a>



#### data (`binary`)

<a id="rst-stats-grp"></a>
<a id="rst-ethtool-attribute-set-stats-grp"></a>



### stats-grp

<a id="rst-unspec-unused-45"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pad-pad-4"></a>



#### pad (`pad`)

<a id="rst-id-u32-1"></a>



#### id (`u32`)

<a id="rst-ss-id-u32"></a>



#### ss-id (`u32`)

<a id="rst-stat-u64"></a>



#### stat (`u64`)

- **type-value**:

  \['id'\]

<a id="rst-hist-rx-nest"></a>



#### hist-rx (`nest`)

- **nested-attributes**:

  [stats-grp-hist](#rst-ethtool-attribute-set-stats-grp-hist)

<a id="rst-hist-tx-nest"></a>



#### hist-tx (`nest`)

- **nested-attributes**:

  [stats-grp-hist](#rst-ethtool-attribute-set-stats-grp-hist)

<a id="rst-hist-bkt-low-u32"></a>



#### hist-bkt-low (`u32`)

<a id="rst-hist-bkt-hi-u32"></a>



#### hist-bkt-hi (`u32`)

<a id="rst-hist-val-u64"></a>



#### hist-val (`u64`)

<a id="rst-stats-grp-hist"></a>
<a id="rst-ethtool-attribute-set-stats-grp-hist"></a>



### stats-grp-hist

<a id="rst-hist-bkt-low"></a>



#### hist-bkt-low

<a id="rst-hist-bkt-hi"></a>



#### hist-bkt-hi

<a id="rst-hist-val"></a>



#### hist-val

<a id="rst-stats"></a>
<a id="rst-ethtool-attribute-set-stats"></a>



### stats

<a id="rst-unspec-unused-46"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-pad-pad-5"></a>



#### pad (`pad`)

<a id="rst-header-nest-22"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-groups-nest"></a>



#### groups (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-grp-nest"></a>



#### grp (`nest`)

- **nested-attributes**:

  [stats-grp](#rst-ethtool-attribute-set-stats-grp)

<a id="rst-src-u32-2"></a>



#### src (`u32`)

<a id="rst-phc-vclocks"></a>
<a id="rst-ethtool-attribute-set-phc-vclocks"></a>



### phc-vclocks

<a id="rst-unspec-unused-47"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-23"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-num-u32"></a>



#### num (`u32`)

<a id="rst-index-binary"></a>



#### index (`binary`)

- **sub-type**:

  s32

<a id="rst-module"></a>
<a id="rst-ethtool-attribute-set-module"></a>



### module

<a id="rst-unspec-unused-48"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-24"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-power-mode-policy-u8"></a>



#### power-mode-policy (`u8`)

<a id="rst-power-mode-u8"></a>



#### power-mode (`u8`)

<a id="rst-c33-pse-pw-limit"></a>
<a id="rst-ethtool-attribute-set-c33-pse-pw-limit"></a>



### c33-pse-pw-limit

<a id="rst-unspec-unused-49"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-min-u32"></a>



#### min (`u32`)

<a id="rst-max-u32"></a>



#### max (`u32`)

<a id="rst-pse"></a>
<a id="rst-ethtool-attribute-set-pse"></a>



### pse

<a id="rst-unspec-unused-50"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-25"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-podl-pse-admin-state-u32"></a>



#### podl-pse-admin-state (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-podl-pse-admin-control-u32"></a>



#### podl-pse-admin-control (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-podl-pse-pw-d-status-u32"></a>



#### podl-pse-pw-d-status (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-admin-state-u32"></a>



#### c33-pse-admin-state (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-admin-control-u32"></a>



#### c33-pse-admin-control (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-pw-d-status-u32"></a>



#### c33-pse-pw-d-status (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-pw-class-u32"></a>



#### c33-pse-pw-class (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-actual-pw-u32"></a>



#### c33-pse-actual-pw (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-ext-state-u32"></a>



#### c33-pse-ext-state (`u32`)

- **name-prefix**:

  ethtool-a-

- **enum**:

  [c33-pse-ext-state](#rst-ethtool-definition-c33-pse-ext-state)

<a id="rst-c33-pse-ext-substate-u32"></a>



#### c33-pse-ext-substate (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-avail-pw-limit-u32"></a>



#### c33-pse-avail-pw-limit (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-c33-pse-pw-limit-ranges-nest"></a>



#### c33-pse-pw-limit-ranges (`nest`)

- **name-prefix**:

  ethtool-a-

- **multi-attr**:

  True

- **nested-attributes**:

  [c33-pse-pw-limit](#rst-ethtool-attribute-set-c33-pse-pw-limit)

<a id="rst-pse-pw-d-id-u32"></a>



#### pse-pw-d-id (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-pse-prio-max-u32"></a>



#### pse-prio-max (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-pse-prio-u32"></a>



#### pse-prio (`u32`)

- **name-prefix**:

  ethtool-a-

<a id="rst-flow"></a>
<a id="rst-ethtool-attribute-set-flow"></a>



### flow



Flow types, corresponding to those defined in the old
ethtool header for RXFH and RXNFC as \${PROTO}\_FLOW.
The values are not matching the old ones to avoid carrying
into Netlink the IP\_USER\_FLOW vs IPV4\_FLOW vs IPV4\_USER\_FLOW confusion.

<a id="rst-ether-uint"></a>



#### ether (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ip4-uint"></a>



#### ip4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ip6-uint"></a>



#### ip6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-tcp4-uint"></a>



#### tcp4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-tcp6-uint"></a>



#### tcp6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-udp4-uint"></a>



#### udp4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-udp6-uint"></a>



#### udp6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-sctp4-uint"></a>



#### sctp4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-sctp6-uint"></a>



#### sctp6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ah4-uint"></a>



#### ah4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ah6-uint"></a>



#### ah6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-esp4-uint"></a>



#### esp4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-esp6-uint"></a>



#### esp6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ah-esp4-uint"></a>



#### ah-esp4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-ah-esp6-uint"></a>



#### ah-esp6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu4-uint"></a>



#### gtpu4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu6-uint"></a>



#### gtpu6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpc4-uint"></a>



#### gtpc4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpc6-uint"></a>



#### gtpc6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpc-teid4-uint"></a>



#### gtpc-teid4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpc-teid6-uint"></a>



#### gtpc-teid6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-eh4-uint"></a>



#### gtpu-eh4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-eh6-uint"></a>



#### gtpu-eh6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-ul4-uint"></a>



#### gtpu-ul4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-ul6-uint"></a>



#### gtpu-ul6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-dl4-uint"></a>



#### gtpu-dl4 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-gtpu-dl6-uint"></a>



#### gtpu-dl6 (`uint`)

- **enum**:

  [rxfh-fields](#rst-ethtool-definition-rxfh-fields)

<a id="rst-rss"></a>
<a id="rst-ethtool-attribute-set-rss"></a>



### rss

<a id="rst-unspec-unused-51"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-26"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-context-u32"></a>



#### context (`u32`)

<a id="rst-hfunc-u32"></a>



#### hfunc (`u32`)

<a id="rst-indir-binary"></a>



#### indir (`binary`)

- **sub-type**:

  u32

<a id="rst-hkey-binary"></a>



#### hkey (`binary`)

<a id="rst-input-xfrm-u32"></a>



#### input-xfrm (`u32`)

- **enum**:

  [input-xfrm](#rst-ethtool-definition-input-xfrm)

<a id="rst-start-context-u32"></a>



#### start-context (`u32`)

<a id="rst-flow-hash-nest"></a>



#### flow-hash (`nest`)

- **nested-attributes**:

  [flow](#rst-ethtool-attribute-set-flow)

<a id="rst-plca"></a>
<a id="rst-ethtool-attribute-set-plca"></a>



### plca

<a id="rst-unspec-unused-52"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-27"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-version-u16"></a>



#### version (`u16`)

<a id="rst-enabled-u8-1"></a>



#### enabled (`u8`)

<a id="rst-status-u8-2"></a>



#### status (`u8`)

<a id="rst-node-cnt-u32"></a>



#### node-cnt (`u32`)

<a id="rst-node-id-u32"></a>



#### node-id (`u32`)

<a id="rst-to-tmr-u32"></a>



#### to-tmr (`u32`)

<a id="rst-burst-cnt-u32"></a>



#### burst-cnt (`u32`)

<a id="rst-burst-tmr-u32"></a>



#### burst-tmr (`u32`)

<a id="rst-module-fw-flash"></a>
<a id="rst-ethtool-attribute-set-module-fw-flash"></a>



### module-fw-flash

<a id="rst-unspec-unused-53"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-28"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-file-name-string"></a>



#### file-name (`string`)

<a id="rst-password-u32"></a>



#### password (`u32`)

<a id="rst-status-u32"></a>



#### status (`u32`)

- **enum**:

  [module-fw-flash-status](#rst-ethtool-definition-module-fw-flash-status)

<a id="rst-status-msg-string"></a>



#### status-msg (`string`)

<a id="rst-done-uint"></a>



#### done (`uint`)

<a id="rst-total-uint"></a>



#### total (`uint`)

<a id="rst-phy"></a>
<a id="rst-ethtool-attribute-set-phy"></a>



### phy

<a id="rst-unspec-unused-54"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-29"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-index-u32-3"></a>



#### index (`u32`)

<a id="rst-drvname-string"></a>



#### drvname (`string`)

<a id="rst-name-string-1"></a>



#### name (`string`)

<a id="rst-upstream-type-u32"></a>



#### upstream-type (`u32`)

- **enum**:

  [phy-upstream-type](#rst-ethtool-definition-phy-upstream-type)

<a id="rst-upstream-index-u32"></a>



#### upstream-index (`u32`)

<a id="rst-upstream-sfp-name-string"></a>



#### upstream-sfp-name (`string`)

<a id="rst-downstream-sfp-name-string"></a>



#### downstream-sfp-name (`string`)

<a id="rst-tsconfig"></a>
<a id="rst-ethtool-attribute-set-tsconfig"></a>



### tsconfig

<a id="rst-unspec-unused-55"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-header-nest-30"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-hwtstamp-provider-nest-1"></a>



#### hwtstamp-provider (`nest`)

- **nested-attributes**:

  [ts-hwtstamp-provider](#rst-ethtool-attribute-set-ts-hwtstamp-provider)

<a id="rst-tx-types-nest-1"></a>



#### tx-types (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-rx-filters-nest-1"></a>



#### rx-filters (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-hwtstamp-flags-nest"></a>



#### hwtstamp-flags (`nest`)

- **nested-attributes**:

  [bitset](#rst-ethtool-attribute-set-bitset)

<a id="rst-pse-ntf-1"></a>
<a id="rst-ethtool-attribute-set-pse-ntf"></a>



### pse-ntf

<a id="rst-header-nest-31"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-events-uint"></a>



#### events (`uint`)

- **enum**:

  [pse-event](#rst-ethtool-definition-pse-event)

- **doc**:

  List of events reported by the PSE controller

<a id="rst-mse-capabilities"></a>
<a id="rst-ethtool-attribute-set-mse-capabilities"></a>



### mse-capabilities



MSE capabilities attribute set

<a id="rst-max-average-mse-uint"></a>



#### max-average-mse (`uint`)

<a id="rst-max-peak-mse-uint"></a>



#### max-peak-mse (`uint`)

<a id="rst-refresh-rate-ps-uint"></a>



#### refresh-rate-ps (`uint`)

<a id="rst-num-symbols-uint"></a>



#### num-symbols (`uint`)

<a id="rst-mse-snapshot"></a>
<a id="rst-ethtool-attribute-set-mse-snapshot"></a>



### mse-snapshot



MSE snapshot attribute set

<a id="rst-average-mse-uint"></a>



#### average-mse (`uint`)

<a id="rst-peak-mse-uint"></a>



#### peak-mse (`uint`)

<a id="rst-worst-peak-mse-uint"></a>



#### worst-peak-mse (`uint`)

<a id="rst-mse"></a>
<a id="rst-ethtool-attribute-set-mse"></a>



### mse

<a id="rst-header-nest-32"></a>



#### header (`nest`)

- **nested-attributes**:

  [header](#rst-ethtool-attribute-set-header)

<a id="rst-capabilities-nest"></a>



#### capabilities (`nest`)

- **nested-attributes**:

  [mse-capabilities](#rst-ethtool-attribute-set-mse-capabilities)

<a id="rst-channel-a-nest"></a>



#### channel-a (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

<a id="rst-channel-b-nest"></a>



#### channel-b (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

<a id="rst-channel-c-nest"></a>



#### channel-c (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

<a id="rst-channel-d-nest"></a>



#### channel-d (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

<a id="rst-worst-channel-nest"></a>



#### worst-channel (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

<a id="rst-link-nest"></a>



#### link (`nest`)

- **nested-attributes**:

  [mse-snapshot](#rst-ethtool-attribute-set-mse-snapshot)

---

# Family fou netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the fou Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-fou-netlink-specification"></a>
<a id="rst-netlink-fou"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Foo-over-UDP.

<a id="rst-operations"></a>



## Operations

<a id="rst-unspec"></a>
<a id="rst-fou-operation-unspec"></a>



### unspec



unused

- **value**:

  0

<a id="rst-add"></a>
<a id="rst-fou-operation-add"></a>



### add



Add port.

- **attribute-set**:

  [fou](#rst-fou-attribute-set-fou)

- **dont-validate**:

  \['strict', 'dump'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`port`, `ipproto`, `type`, `remcsum-nopartial`, `local-v4`, `peer-v4`, `local-v6`, `peer-v6`, `peer-port`, `ifindex`\]

<a id="rst-del"></a>
<a id="rst-fou-operation-del"></a>



### del



Delete port.

- **attribute-set**:

  [fou](#rst-fou-attribute-set-fou)

- **dont-validate**:

  \['strict', 'dump'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`af`, `ifindex`, `port`, `peer-port`, `local-v4`, `peer-v4`, `local-v6`, `peer-v6`\]

<a id="rst-get"></a>
<a id="rst-fou-operation-get"></a>



### get



Get tunnel info.

- **attribute-set**:

  [fou](#rst-fou-attribute-set-fou)

- **dont-validate**:

  \['strict', 'dump'\]

- **do**:

  **request**

  - **attributes**:

    \[`af`, `ifindex`, `port`, `peer-port`, `local-v4`, `peer-v4`, `local-v6`, `peer-v6`\]

  **reply**

  - **attributes**:

    \[`port`, `ipproto`, `type`, `remcsum-nopartial`, `local-v4`, `peer-v4`, `local-v6`, `peer-v6`, `peer-port`, `ifindex`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`port`, `ipproto`, `type`, `remcsum-nopartial`, `local-v4`, `peer-v4`, `local-v6`, `peer-v6`, `peer-port`, `ifindex`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-encap-type"></a>
<a id="rst-fou-definition-encap-type"></a>



### encap-type

- **type**:

  enum

- **name-prefix**:

  fou-encap-

- **enum-name**:

  None

- **entries**:

  - `unspec`


  - `direct`


  - `gue`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-fou"></a>
<a id="rst-fou-attribute-set-fou"></a>



### fou

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-port-u16"></a>



#### port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-af-u8"></a>



#### af (`u8`)

<a id="rst-ipproto-u8"></a>



#### ipproto (`u8`)

<a id="rst-type-u8"></a>



#### type (`u8`)

<a id="rst-remcsum-nopartial-flag"></a>



#### remcsum-nopartial (`flag`)

<a id="rst-local-v4-u32"></a>



#### local-v4 (`u32`)

<a id="rst-local-v6-binary"></a>



#### local-v6 (`binary`)

<a id="rst-peer-v4-u32"></a>



#### peer-v4 (`u32`)

<a id="rst-peer-v6-binary"></a>



#### peer-v6 (`binary`)

<a id="rst-peer-port-u16"></a>



#### peer-port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-ifindex-s32"></a>



#### ifindex (`s32`)

---

# Family handshake netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the handshake Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-handshake-netlink-specification"></a>
<a id="rst-netlink-handshake"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netlink protocol to request a transport layer security handshake.

<a id="rst-operations"></a>



## Operations

<a id="rst-ready"></a>
<a id="rst-handshake-operation-ready"></a>



### ready



Notify handlers that a new handshake request is waiting

- **notify**:

  accept

<a id="rst-accept"></a>
<a id="rst-handshake-operation-accept"></a>



### accept



Handler retrieves next queued handshake request

- **attribute-set**:

  [accept](#rst-handshake-attribute-set-accept)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`handler-class`\]

  **reply**

  - **attributes**:

    \[`sockfd`, `message-type`, `timeout`, `auth-mode`, `peer-identity`, `certificate`, `peername`, `keyring`\]

<a id="rst-done"></a>
<a id="rst-handshake-operation-done"></a>



### done



Handler reports handshake completion

- **attribute-set**:

  [done](#rst-handshake-attribute-set-done)

- **do**:

  **request**

  - **attributes**:

    \[`status`, `sockfd`, `remote-auth`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- none


- tlshd


<a id="rst-definitions"></a>



## Definitions

<a id="rst-handler-class"></a>
<a id="rst-handshake-definition-handler-class"></a>



### handler-class

- **type**:

  enum

- **value-start**:

  0

- **entries**:

  - `none`


  - `tlshd`


  - `max`

<a id="rst-msg-type"></a>
<a id="rst-handshake-definition-msg-type"></a>



### msg-type

- **type**:

  enum

- **value-start**:

  0

- **entries**:

  - `unspec`


  - `clienthello`


  - `serverhello`

<a id="rst-auth"></a>
<a id="rst-handshake-definition-auth"></a>



### auth

- **type**:

  enum

- **value-start**:

  0

- **entries**:

  - `unspec`


  - `unauth`


  - `psk`


  - `x509`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-x509"></a>
<a id="rst-handshake-attribute-set-x509"></a>



### x509

<a id="rst-cert-s32"></a>



#### cert (`s32`)

<a id="rst-privkey-s32"></a>



#### privkey (`s32`)

<a id="rst-accept-1"></a>
<a id="rst-handshake-attribute-set-accept"></a>



### accept

<a id="rst-sockfd-s32"></a>



#### sockfd (`s32`)

<a id="rst-handler-class-u32"></a>



#### handler-class (`u32`)

- **enum**:

  [handler-class](#rst-handshake-definition-handler-class)

<a id="rst-message-type-u32"></a>



#### message-type (`u32`)

- **enum**:

  [msg-type](#rst-handshake-definition-msg-type)

<a id="rst-timeout-u32"></a>



#### timeout (`u32`)

<a id="rst-auth-mode-u32"></a>



#### auth-mode (`u32`)

- **enum**:

  [auth](#rst-handshake-definition-auth)

<a id="rst-peer-identity-u32"></a>



#### peer-identity (`u32`)

- **multi-attr**:

  True

<a id="rst-certificate-nest"></a>



#### certificate (`nest`)

- **nested-attributes**:

  [x509](#rst-handshake-attribute-set-x509)

- **multi-attr**:

  True

<a id="rst-peername-string"></a>



#### peername (`string`)

<a id="rst-keyring-u32"></a>



#### keyring (`u32`)

<a id="rst-done-1"></a>
<a id="rst-handshake-attribute-set-done"></a>



### done

<a id="rst-status-u32"></a>



#### status (`u32`)

<a id="rst-sockfd-s32-1"></a>



#### sockfd (`s32`)

<a id="rst-remote-auth-u32"></a>



#### remote-auth (`u32`)

- **multi-attr**:

  True

---

# Family lockd netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the lockd Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-lockd-netlink-specification"></a>
<a id="rst-netlink-lockd"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



lockd configuration over generic netlink

<a id="rst-operations"></a>



## Operations

<a id="rst-server-set"></a>
<a id="rst-lockd-operation-server-set"></a>



### server-set



set the lockd server parameters

- **attribute-set**:

  [server](#rst-lockd-attribute-set-server)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`gracetime`, `tcp-port`, `udp-port`\]

<a id="rst-server-get"></a>
<a id="rst-lockd-operation-server-get"></a>



### server-get



get the lockd server parameters

- **attribute-set**:

  [server](#rst-lockd-attribute-set-server)

- **do**:

  **reply**

  - **attributes**:

    \[`gracetime`, `tcp-port`, `udp-port`\]

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-server"></a>
<a id="rst-lockd-attribute-set-server"></a>



### server

<a id="rst-gracetime-u32"></a>



#### gracetime (`u32`)

<a id="rst-tcp-port-u16"></a>



#### tcp-port (`u16`)

<a id="rst-udp-port-u16"></a>



#### udp-port (`u16`)

---

# Family mptcp_pm netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the mptcp_pm Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-mptcp-pm-netlink-specification"></a>
<a id="rst-netlink-mptcp-pm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Multipath TCP.

<a id="rst-operations"></a>



## Operations

<a id="rst-unspec"></a>
<a id="rst-mptcp-pm-operation-unspec"></a>



### unspec



unused

- **value**:

  0

<a id="rst-add-addr"></a>
<a id="rst-mptcp-pm-operation-add-addr"></a>



### add-addr



Add endpoint

- **attribute-set**:

  [endpoint](#rst-mptcp-pm-attribute-set-endpoint)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`\]

<a id="rst-del-addr"></a>
<a id="rst-mptcp-pm-operation-del-addr"></a>



### del-addr



Delete endpoint

- **attribute-set**:

  [endpoint](#rst-mptcp-pm-attribute-set-endpoint)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`\]

<a id="rst-get-addr"></a>
<a id="rst-mptcp-pm-operation-get-addr"></a>



### get-addr



Get endpoint information

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`, `token`\]

  **reply**

  - **attributes**:

    \[`addr`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`addr`\]

<a id="rst-flush-addrs"></a>
<a id="rst-mptcp-pm-operation-flush-addrs"></a>



### flush-addrs



Flush addresses

- **attribute-set**:

  [endpoint](#rst-mptcp-pm-attribute-set-endpoint)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`\]

<a id="rst-set-limits"></a>
<a id="rst-mptcp-pm-operation-set-limits"></a>



### set-limits



Set protocol limits

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`rcv-add-addrs`, `subflows`\]

<a id="rst-get-limits"></a>
<a id="rst-mptcp-pm-operation-get-limits"></a>



### get-limits



Get protocol limits

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **do**:

  **request**

  - **attributes**:

    \[`rcv-add-addrs`, `subflows`\]

  **reply**

  - **attributes**:

    \[`rcv-add-addrs`, `subflows`\]

<a id="rst-set-flags"></a>
<a id="rst-mptcp-pm-operation-set-flags"></a>



### set-flags



Change endpoint flags

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`, `token`, `addr-remote`\]

<a id="rst-announce"></a>
<a id="rst-mptcp-pm-operation-announce"></a>



### announce



Announce new address

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`, `token`\]

<a id="rst-remove"></a>
<a id="rst-mptcp-pm-operation-remove"></a>



### remove



Announce removal

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`token`, `loc-id`\]

<a id="rst-subflow-create"></a>
<a id="rst-mptcp-pm-operation-subflow-create"></a>



### subflow-create



Create subflow

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`, `token`, `addr-remote`\]

<a id="rst-subflow-destroy"></a>
<a id="rst-mptcp-pm-operation-subflow-destroy"></a>



### subflow-destroy



Destroy subflow

- **attribute-set**:

  [attr](#rst-mptcp-pm-attribute-set-attr)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`, `token`, `addr-remote`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-event-type"></a>
<a id="rst-mptcp-pm-definition-event-type"></a>



### event-type

- **type**:

  enum

- **enum-name**:

  mptcp-event-type

- **doc**:

  Netlink MPTCP event types

- **name-prefix**:

  mptcp-event-

- **entries**:

  - **unspec**:

    unused event

  - **created**:

    A new MPTCP connection has been created. It is the good time to allocate memory and send ADD\_ADDR if needed. Depending on the traffic-patterns it can take a long time until the MPTCP\_EVENT\_ESTABLISHED is sent. Attributes: token, family, saddr4 \| saddr6, daddr4 \| daddr6, sport, dport, \[server-side\], \[flags\].

  - **established**:

    A MPTCP connection is established (can start new subflows). Attributes: token, family, saddr4 \| saddr6, daddr4 \| daddr6, sport, dport, \[server-side\], \[flags\].

  - **closed**:

    A MPTCP connection has stopped. Attribute: token.

  - **announced**:

    A new address has been announced by the peer. Attributes: token, rem\_id, family, daddr4 \| daddr6 \[, dport\].

  - **removed**:

    An address has been lost by the peer. Attributes: token, rem\_id.

  - **sub-established**:

    A new subflow has been established. 'error' should not be set. Attributes: token, family, loc\_id, rem\_id, saddr4 \| saddr6, daddr4 \| daddr6, sport, dport, backup, if-idx \[, error\].

  - **sub-closed**:

    A subflow has been closed. An error (copy of sk\_err) could be set if an error has been detected for this subflow. Attributes: token, family, loc\_id, rem\_id, saddr4 \| saddr6, daddr4 \| daddr6, sport, dport, backup, if-idx \[, error\].

  - **sub-priority**:

    The priority of a subflow has changed. 'error' should not be set. Attributes: token, family, loc\_id, rem\_id, saddr4 \| saddr6, daddr4 \| daddr6, sport, dport, backup, if-idx \[, error\].

  - **listener-created**:

    A new PM listener is created. Attributes: family, sport, saddr4 \| saddr6.

  - **listener-closed**:

    A PM listener is closed. Attributes: family, sport, saddr4 \| saddr6.

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-address"></a>
<a id="rst-mptcp-pm-attribute-set-address"></a>



### address

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-family-u16"></a>



#### family (`u16`)

<a id="rst-id-u8"></a>



#### id (`u8`)

<a id="rst-addr4-u32"></a>



#### addr4 (`u32`)

- **byte-order**:

  big-endian

<a id="rst-addr6-binary"></a>



#### addr6 (`binary`)

<a id="rst-port-u16"></a>



#### port (`u16`)

<a id="rst-flags-u32"></a>



#### flags (`u32`)

<a id="rst-if-idx-s32"></a>



#### if-idx (`s32`)

<a id="rst-subflow-attribute"></a>
<a id="rst-mptcp-pm-attribute-set-subflow-attribute"></a>



### subflow-attribute

<a id="rst-unspec-unused-1"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-token-rem-u32"></a>



#### token-rem (`u32`)

<a id="rst-token-loc-u32"></a>



#### token-loc (`u32`)

<a id="rst-relwrite-seq-u32"></a>



#### relwrite-seq (`u32`)

<a id="rst-map-seq-u64"></a>



#### map-seq (`u64`)

<a id="rst-map-sfseq-u32"></a>



#### map-sfseq (`u32`)

<a id="rst-ssn-offset-u32"></a>



#### ssn-offset (`u32`)

<a id="rst-map-datalen-u16"></a>



#### map-datalen (`u16`)

<a id="rst-flags-u32-1"></a>



#### flags (`u32`)

<a id="rst-id-rem-u8"></a>



#### id-rem (`u8`)

<a id="rst-id-loc-u8"></a>



#### id-loc (`u8`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-endpoint"></a>
<a id="rst-mptcp-pm-attribute-set-endpoint"></a>



### endpoint

<a id="rst-addr-nest"></a>



#### addr (`nest`)

- **nested-attributes**:

  [address](#rst-mptcp-pm-attribute-set-address)

<a id="rst-attr"></a>
<a id="rst-mptcp-pm-attribute-set-attr"></a>



### attr

<a id="rst-unspec-unused-2"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-addr-nest-1"></a>



#### addr (`nest`)

- **nested-attributes**:

  [address](#rst-mptcp-pm-attribute-set-address)

<a id="rst-rcv-add-addrs-u32"></a>



#### rcv-add-addrs (`u32`)

<a id="rst-subflows-u32"></a>



#### subflows (`u32`)

<a id="rst-token-u32"></a>



#### token (`u32`)

<a id="rst-loc-id-u8"></a>



#### loc-id (`u8`)

<a id="rst-addr-remote-nest"></a>



#### addr-remote (`nest`)

- **nested-attributes**:

  [address](#rst-mptcp-pm-attribute-set-address)

<a id="rst-event-attr"></a>
<a id="rst-mptcp-pm-attribute-set-event-attr"></a>



### event-attr

<a id="rst-unspec-unused-3"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-token-u32-1"></a>



#### token (`u32`)

<a id="rst-family-u16-1"></a>



#### family (`u16`)

<a id="rst-loc-id-u8-1"></a>



#### loc-id (`u8`)

<a id="rst-rem-id-u8"></a>



#### rem-id (`u8`)

<a id="rst-saddr4-u32"></a>



#### saddr4 (`u32`)

- **byte-order**:

  big-endian

<a id="rst-saddr6-binary"></a>



#### saddr6 (`binary`)

<a id="rst-daddr4-u32"></a>



#### daddr4 (`u32`)

- **byte-order**:

  big-endian

<a id="rst-daddr6-binary"></a>



#### daddr6 (`binary`)

<a id="rst-sport-u16"></a>



#### sport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-dport-u16"></a>



#### dport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-backup-u8"></a>



#### backup (`u8`)

<a id="rst-error-u8"></a>



#### error (`u8`)

<a id="rst-flags-u16"></a>



#### flags (`u16`)

<a id="rst-timeout-u32"></a>



#### timeout (`u32`)

<a id="rst-if-idx-s32-1"></a>



#### if-idx (`s32`)

<a id="rst-reset-reason-u32"></a>



#### reset-reason (`u32`)

<a id="rst-reset-flags-u32"></a>



#### reset-flags (`u32`)

<a id="rst-server-side-u8"></a>



#### server-side (`u8`)

- **doc**:

  Deprecated: use 'flags'

---

# Family net-shaper netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the net_shaper Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-net-shaper-netlink-specification"></a>
<a id="rst-netlink-net-shaper"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Networking HW rate limiting configuration.



This API allows configuring HW shapers available on the network
devices at different levels (queues, network device) and allows
arbitrary manipulation of the scheduling tree of the involved
shapers.



Each @shaper is identified within the given device, by a @handle,
comprising both a @scope and an @id.



Depending on the @scope value, the shapers are attached to specific
HW objects (queues, devices) or, for @node scope, represent a
scheduling group, that can be placed in an arbitrary location of
the scheduling tree.



Shapers can be created with two different operations: the @set
operation, to create and update a single "attached" shaper, and
the @group operation, to create and update a scheduling
group. Only the @group operation can create @node scope shapers.



Existing shapers can be deleted/reset via the @delete operation.



The user can query the running configuration via the @get operation.



Different devices can provide different feature sets, e.g. with no
support for complex scheduling hierarchy, or for some shaping
parameters. The user can introspect the HW capabilities via the
@cap-get operation.

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-net-shaper-operation-get"></a>



### get



Get information about a shaper for a given device.

- **attribute-set**:

  [net-shaper](#rst-net-shaper-attribute-set-net-shaper)

- **do**:

  **pre**



  net-shaper-nl-pre-doit

  **post**



  net-shaper-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `handle`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `parent`, `handle`, `metric`, `bw-min`, `bw-max`, `burst`, `priority`, `weight`\]

- **dump**:

  **pre**



  net-shaper-nl-pre-dumpit

  **post**



  net-shaper-nl-post-dumpit

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `parent`, `handle`, `metric`, `bw-min`, `bw-max`, `burst`, `priority`, `weight`\]

<a id="rst-set"></a>
<a id="rst-net-shaper-operation-set"></a>



### set



Create or update the specified shaper.
The set operation can't be used to create a @node scope shaper,
use the @group operation instead.

- **attribute-set**:

  [net-shaper](#rst-net-shaper-attribute-set-net-shaper)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  net-shaper-nl-pre-doit-write

  **post**



  net-shaper-nl-post-doit-write

  **request**

  - **attributes**:

    \[`ifindex`, `handle`, `metric`, `bw-min`, `bw-max`, `burst`, `priority`, `weight`\]

<a id="rst-delete"></a>
<a id="rst-net-shaper-operation-delete"></a>



### delete



Clear (remove) the specified shaper. When deleting
a @node shaper, reattach all the node's leaves to the
deleted node's parent.
If, after the removal, the parent shaper has no more
leaves and the parent shaper scope is @node, the parent
node is deleted, recursively.
When deleting a @queue shaper or a @netdev shaper,
the shaper disappears from the hierarchy, but the
queue/device can still send traffic: it has an implicit
node with infinite bandwidth. The queue's implicit node
feeds an implicit RR node at the root of the hierarchy.

- **attribute-set**:

  [net-shaper](#rst-net-shaper-attribute-set-net-shaper)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  net-shaper-nl-pre-doit-write

  **post**



  net-shaper-nl-post-doit-write

  **request**

  - **attributes**:

    \[`ifindex`, `handle`\]

<a id="rst-group"></a>
<a id="rst-net-shaper-operation-group"></a>



### group



Create or update a scheduling group, attaching the specified
@leaves shapers under the specified node identified by @handle.
The @leaves shapers scope must be @queue and the node shaper
scope must be either @node or @netdev.
When the node shaper has @node scope, if the @handle @id is not
specified, a new shaper of such scope is created, otherwise the
specified node must already exist.
When updating an existing node shaper, the specified @leaves are
added to the existing node; such node will also retain any preexisting
leave.
The @parent handle for a new node shaper defaults to the parent
of all the leaves, provided all the leaves share the same parent.
Otherwise @parent handle must be specified.
The user can optionally provide shaping attributes for the node
shaper.
The operation is atomic, on failure no change is applied to
the device shaping configuration, otherwise the @node shaper
full identifier, comprising @binding and @handle, is provided
as the reply.

- **attribute-set**:

  [net-shaper](#rst-net-shaper-attribute-set-net-shaper)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  net-shaper-nl-pre-doit-write

  **post**



  net-shaper-nl-post-doit-write

  **request**

  - **attributes**:

    \[`ifindex`, `parent`, `handle`, `metric`, `bw-min`, `bw-max`, `burst`, `priority`, `weight`, `leaves`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `handle`\]

<a id="rst-cap-get"></a>
<a id="rst-net-shaper-operation-cap-get"></a>



### cap-get



Get the shaper capabilities supported by the given device
for the specified scope.

- **attribute-set**:

  [caps](#rst-net-shaper-attribute-set-caps)

- **do**:

  **pre**



  net-shaper-nl-cap-pre-doit

  **post**



  net-shaper-nl-cap-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `scope`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `scope`, `support-metric-bps`, `support-metric-pps`, `support-nesting`, `support-bw-min`, `support-bw-max`, `support-burst`, `support-priority`, `support-weight`\]

- **dump**:

  **pre**



  net-shaper-nl-cap-pre-dumpit

  **post**



  net-shaper-nl-cap-post-dumpit

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `scope`, `support-metric-bps`, `support-metric-pps`, `support-nesting`, `support-bw-min`, `support-bw-max`, `support-burst`, `support-priority`, `support-weight`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-scope"></a>
<a id="rst-net-shaper-definition-scope"></a>



### scope

- **type**:

  enum

- **doc**:

  Defines the shaper @id interpretation.

- **entries**:

  - **unspec**:

    The scope is not specified.

  - **netdev**:

    The main shaper for the given network device.

  - **queue**:

    The shaper is attached to the given device queue, the @id represents the queue number.

  - **node**:

    The shaper allows grouping of queues or other node shapers; can be nested in either @netdev shapers or other @node shapers, allowing placement in any location of the scheduling tree, except leaves and root.

<a id="rst-metric"></a>
<a id="rst-net-shaper-definition-metric"></a>



### metric

- **type**:

  enum

- **doc**:

  Different metric supported by the shaper.

- **entries**:

  - **bps**:

    Shaper operates on a bits per second basis.

  - **pps**:

    Shaper operates on a packets per second basis.

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-net-shaper"></a>
<a id="rst-net-shaper-attribute-set-net-shaper"></a>



### net-shaper

<a id="rst-handle-nest"></a>



#### handle (`nest`)

- **nested-attributes**:

  [handle](#rst-net-shaper-attribute-set-handle)

- **doc**:

  Unique identifier for the given shaper inside the owning device.

<a id="rst-metric-u32"></a>



#### metric (`u32`)

- **enum**:

  [metric](#rst-net-shaper-definition-metric)

- **doc**:

  Metric used by the given shaper for bw-min, bw-max and burst.

<a id="rst-bw-min-uint"></a>



#### bw-min (`uint`)

- **doc**:

  Guaranteed bandwidth for the given shaper.

<a id="rst-bw-max-uint"></a>



#### bw-max (`uint`)

- **doc**:

  Maximum bandwidth for the given shaper or 0 when unlimited.

<a id="rst-burst-uint"></a>



#### burst (`uint`)

- **doc**:

  Maximum burst-size for shaping. Should not be interpreted as a quantum.

<a id="rst-priority-u32"></a>



#### priority (`u32`)

- **doc**:

  Scheduling priority for the given shaper. The priority scheduling is applied to sibling shapers.

<a id="rst-weight-u32"></a>



#### weight (`u32`)

- **doc**:

  Relative weight for round robin scheduling of the given shaper. The scheduling is applied to all sibling shapers with the same priority.

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

- **doc**:

  Interface index owning the specified shaper.

<a id="rst-parent-nest"></a>



#### parent (`nest`)

- **nested-attributes**:

  [handle](#rst-net-shaper-attribute-set-handle)

- **doc**:

  Identifier for the parent of the affected shaper. Only needed for @group operation.

<a id="rst-leaves-nest"></a>



#### leaves (`nest`)

- **multi-attr**:

  True

- **nested-attributes**:

  [leaf-info](#rst-net-shaper-attribute-set-leaf-info)

- **doc**:

  Describes a set of leaves shapers for a @group operation.

<a id="rst-handle"></a>
<a id="rst-net-shaper-attribute-set-handle"></a>



### handle

<a id="rst-scope-u32"></a>



#### scope (`u32`)

- **enum**:

  [scope](#rst-net-shaper-definition-scope)

- **doc**:

  Defines the shaper @id interpretation.

<a id="rst-id-u32"></a>



#### id (`u32`)

- **doc**:

  Numeric identifier of a shaper. The id semantic depends on the scope. For @queue scope it's the queue id and for @node scope it's the node identifier.

<a id="rst-leaf-info"></a>
<a id="rst-net-shaper-attribute-set-leaf-info"></a>



### leaf-info

<a id="rst-handle-1"></a>



#### handle

<a id="rst-priority"></a>



#### priority

<a id="rst-weight"></a>



#### weight

<a id="rst-caps"></a>
<a id="rst-net-shaper-attribute-set-caps"></a>



### caps

<a id="rst-ifindex-u32-1"></a>



#### ifindex (`u32`)

- **doc**:

  Interface index queried for shapers capabilities.

<a id="rst-scope-u32-1"></a>



#### scope (`u32`)

- **enum**:

  [scope](#rst-net-shaper-definition-scope)

- **doc**:

  The scope to which the queried capabilities apply.

<a id="rst-support-metric-bps-flag"></a>



#### support-metric-bps (`flag`)

- **doc**:

  The device accepts 'bps' metric for bw-min, bw-max and burst.

<a id="rst-support-metric-pps-flag"></a>



#### support-metric-pps (`flag`)

- **doc**:

  The device accepts 'pps' metric for bw-min, bw-max and burst.

<a id="rst-support-nesting-flag"></a>



#### support-nesting (`flag`)

- **doc**:

  The device supports nesting shaper belonging to this scope below 'node' scoped shapers. Only 'queue' and 'node' scope can have flag 'support-nesting'.

<a id="rst-support-bw-min-flag"></a>



#### support-bw-min (`flag`)

- **doc**:

  The device supports a minimum guaranteed B/W.

<a id="rst-support-bw-max-flag"></a>



#### support-bw-max (`flag`)

- **doc**:

  The device supports maximum B/W shaping.

<a id="rst-support-burst-flag"></a>



#### support-burst (`flag`)

- **doc**:

  The device supports a maximum burst size.

<a id="rst-support-priority-flag"></a>



#### support-priority (`flag`)

- **doc**:

  The device supports priority scheduling.

<a id="rst-support-weight-flag"></a>



#### support-weight (`flag`)

- **doc**:

  The device supports weighted round robin scheduling.

---

# Family netdev netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the netdev Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-netdev-netlink-specification"></a>
<a id="rst-netlink-netdev"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



netdev configuration over generic netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-dev-get"></a>
<a id="rst-netdev-operation-dev-get"></a>



### dev-get



Get / dump information about a netdev.

- **attribute-set**:

  [dev](#rst-netdev-attribute-set-dev)

- **do**:

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `xdp-features`, `xdp-zc-max-segs`, `xdp-rx-metadata-features`, `xsk-features`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`ifindex`, `xdp-features`, `xdp-zc-max-segs`, `xdp-rx-metadata-features`, `xsk-features`\]

<a id="rst-dev-add-ntf"></a>
<a id="rst-netdev-operation-dev-add-ntf"></a>



### dev-add-ntf



Notification about device appearing.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-dev-del-ntf"></a>
<a id="rst-netdev-operation-dev-del-ntf"></a>



### dev-del-ntf



Notification about device disappearing.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-dev-change-ntf"></a>
<a id="rst-netdev-operation-dev-change-ntf"></a>



### dev-change-ntf



Notification about device configuration being changed.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-page-pool-get"></a>
<a id="rst-netdev-operation-page-pool-get"></a>



### page-pool-get



Get / dump information about Page Pools.
Only Page Pools associated by the driver with a net\_device
can be listed. ifindex will not be reported if the net\_device
no longer exists.

- **attribute-set**:

  [page-pool](#rst-netdev-attribute-set-page-pool)

- **config-cond**:

  page-pool

- **do**:

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `napi-id`, `inflight`, `inflight-mem`, `detach-time`, `dmabuf`, `io-uring`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `napi-id`, `inflight`, `inflight-mem`, `detach-time`, `dmabuf`, `io-uring`\]

<a id="rst-page-pool-add-ntf"></a>
<a id="rst-netdev-operation-page-pool-add-ntf"></a>



### page-pool-add-ntf



Notification about page pool appearing.

- **notify**:

  page-pool-get

- **mcgrp**:

  page-pool

- **config-cond**:

  page-pool

<a id="rst-page-pool-del-ntf"></a>
<a id="rst-netdev-operation-page-pool-del-ntf"></a>



### page-pool-del-ntf



Notification about page pool disappearing.

- **notify**:

  page-pool-get

- **mcgrp**:

  page-pool

- **config-cond**:

  page-pool

<a id="rst-page-pool-change-ntf"></a>
<a id="rst-netdev-operation-page-pool-change-ntf"></a>



### page-pool-change-ntf



Notification about page pool configuration being changed.

- **notify**:

  page-pool-get

- **mcgrp**:

  page-pool

- **config-cond**:

  page-pool

<a id="rst-page-pool-stats-get"></a>
<a id="rst-netdev-operation-page-pool-stats-get"></a>



### page-pool-stats-get



Get page pool statistics.

- **attribute-set**:

  [page-pool-stats](#rst-netdev-attribute-set-page-pool-stats)

- **config-cond**:

  page-pool-stats

- **do**:

  **request**

  - **attributes**:

    \[`info`\]

  **reply**

  - **attributes**:

    \[`info`, `alloc-fast`, `alloc-slow`, `alloc-slow-high-order`, `alloc-empty`, `alloc-refill`, `alloc-waive`, `recycle-cached`, `recycle-cache-full`, `recycle-ring`, `recycle-ring-full`, `recycle-released-refcnt`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`info`, `alloc-fast`, `alloc-slow`, `alloc-slow-high-order`, `alloc-empty`, `alloc-refill`, `alloc-waive`, `recycle-cached`, `recycle-cache-full`, `recycle-ring`, `recycle-ring-full`, `recycle-released-refcnt`\]

<a id="rst-queue-get"></a>
<a id="rst-netdev-operation-queue-get"></a>



### queue-get



Get queue information from the kernel. Only configured queues will be reported (as opposed to all available hardware queues).

- **attribute-set**:

  [queue](#rst-netdev-attribute-set-queue)

- **do**:

  **request**

  - **attributes**:

    \[`ifindex`, `type`, `id`\]

  **reply**

  - **attributes**:

    \[`id`, `type`, `napi-id`, `ifindex`, `dmabuf`, `io-uring`, `xsk`\]

- **dump**:

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`id`, `type`, `napi-id`, `ifindex`, `dmabuf`, `io-uring`, `xsk`\]

<a id="rst-napi-get"></a>
<a id="rst-netdev-operation-napi-get"></a>



### napi-get



Get information about NAPI instances configured on the system.

- **attribute-set**:

  [napi](#rst-netdev-attribute-set-napi)

- **do**:

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `irq`, `pid`, `defer-hard-irqs`, `gro-flush-timeout`, `irq-suspend-timeout`, `threaded`\]

- **dump**:

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `irq`, `pid`, `defer-hard-irqs`, `gro-flush-timeout`, `irq-suspend-timeout`, `threaded`\]

<a id="rst-qstats-get"></a>
<a id="rst-netdev-operation-qstats-get"></a>



### qstats-get



Get / dump fine grained statistics. Which statistics are reported
depends on the device and the driver, and whether the driver stores
software counters per-queue.

- **attribute-set**:

  [qstats](#rst-netdev-attribute-set-qstats)

- **dump**:

  **request**

  - **attributes**:

    \[`ifindex`, `scope`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `queue-type`, `queue-id`, `rx-packets`, `rx-bytes`, `tx-packets`, `tx-bytes`, `rx-alloc-fail`, `rx-hw-drops`, `rx-hw-drop-overruns`, `rx-csum-complete`, `rx-csum-unnecessary`, `rx-csum-none`, `rx-csum-bad`, `rx-hw-gro-packets`, `rx-hw-gro-bytes`, `rx-hw-gro-wire-packets`, `rx-hw-gro-wire-bytes`, `rx-hw-drop-ratelimits`, `tx-hw-drops`, `tx-hw-drop-errors`, `tx-csum-none`, `tx-needs-csum`, `tx-hw-gso-packets`, `tx-hw-gso-bytes`, `tx-hw-gso-wire-packets`, `tx-hw-gso-wire-bytes`, `tx-hw-drop-ratelimits`, `tx-stop`, `tx-wake`\]

<a id="rst-bind-rx"></a>
<a id="rst-netdev-operation-bind-rx"></a>



### bind-rx



Bind dmabuf to netdev

- **attribute-set**:

  [dmabuf](#rst-netdev-attribute-set-dmabuf)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`ifindex`, `fd`, `queues`\]

  **reply**

  - **attributes**:

    \[`id`\]

<a id="rst-napi-set"></a>
<a id="rst-netdev-operation-napi-set"></a>



### napi-set



Set configurable NAPI instance settings.

- **attribute-set**:

  [napi](#rst-netdev-attribute-set-napi)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`id`, `defer-hard-irqs`, `gro-flush-timeout`, `irq-suspend-timeout`, `threaded`\]

<a id="rst-bind-tx"></a>
<a id="rst-netdev-operation-bind-tx"></a>



### bind-tx



Bind dmabuf to netdev for TX

- **attribute-set**:

  [dmabuf](#rst-netdev-attribute-set-dmabuf)

- **do**:

  **request**

  - **attributes**:

    \[`ifindex`, `fd`\]

  **reply**

  - **attributes**:

    \[`id`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- mgmt


- page-pool


<a id="rst-definitions"></a>



## Definitions

<a id="rst-xdp-act"></a>
<a id="rst-netdev-definition-xdp-act"></a>



### xdp-act

- **type**:

  flags

- **entries**:

  - **basic**:

    XDP features set supported by all drivers (XDP\_ABORTED, XDP\_DROP, XDP\_PASS, XDP\_TX)

  - **redirect**:

    The netdev supports XDP\_REDIRECT

  - **ndo-xmit**:

    This feature informs if netdev implements ndo\_xdp\_xmit callback.

  - **xsk-zerocopy**:

    This feature informs if netdev supports AF\_XDP in zero copy mode.

  - **hw-offload**:

    This feature informs if netdev supports XDP hw offloading.

  - **rx-sg**:

    This feature informs if netdev implements non-linear XDP buffer support in the driver napi callback.

  - **ndo-xmit-sg**:

    This feature informs if netdev implements non-linear XDP buffer support in ndo\_xdp\_xmit callback.

<a id="rst-xdp-rx-metadata"></a>
<a id="rst-netdev-definition-xdp-rx-metadata"></a>



### xdp-rx-metadata

- **type**:

  flags

- **entries**:

  - **timestamp**:

    Device is capable of exposing receive HW timestamp via bpf\_xdp\_metadata\_rx\_timestamp().

  - **hash**:

    Device is capable of exposing receive packet hash via bpf\_xdp\_metadata\_rx\_hash().

  - **vlan-tag**:

    Device is capable of exposing receive packet VLAN tag via bpf\_xdp\_metadata\_rx\_vlan\_tag().

<a id="rst-xsk-flags"></a>
<a id="rst-netdev-definition-xsk-flags"></a>



### xsk-flags

- **type**:

  flags

- **entries**:

  - **tx-timestamp**:

    HW timestamping egress packets is supported by the driver.

  - **tx-checksum**:

    L3 checksum HW offload is supported by the driver.

  - **tx-launch-time-fifo**:

    Launch time HW offload is supported by the driver.

<a id="rst-queue-type"></a>
<a id="rst-netdev-definition-queue-type"></a>



### queue-type

- **type**:

  enum

- **entries**:

  - `rx`


  - `tx`

<a id="rst-qstats-scope"></a>
<a id="rst-netdev-definition-qstats-scope"></a>



### qstats-scope

- **type**:

  flags

- **entries**:

  - `queue`

<a id="rst-napi-threaded"></a>
<a id="rst-netdev-definition-napi-threaded"></a>



### napi-threaded

- **type**:

  enum

- **entries**:

  - `disabled`


  - `enabled`


  - `busy-poll`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-dev"></a>
<a id="rst-netdev-attribute-set-dev"></a>



### dev

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

- **doc**:

  netdev ifindex

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-xdp-features-u64"></a>



#### xdp-features (`u64`)

- **doc**:

  Bitmask of enabled xdp-features.

- **enum**:

  [xdp-act](#rst-netdev-definition-xdp-act)

<a id="rst-xdp-zc-max-segs-u32"></a>



#### xdp-zc-max-segs (`u32`)

- **doc**:

  max fragment count supported by ZC driver

<a id="rst-xdp-rx-metadata-features-u64"></a>



#### xdp-rx-metadata-features (`u64`)

- **doc**:

  Bitmask of supported XDP receive metadata features. See Documentation/networking/xdp-rx-metadata.rst for more details.

- **enum**:

  [xdp-rx-metadata](#rst-netdev-definition-xdp-rx-metadata)

<a id="rst-xsk-features-u64"></a>



#### xsk-features (`u64`)

- **doc**:

  Bitmask of enabled AF\_XDP features.

- **enum**:

  [xsk-flags](#rst-netdev-definition-xsk-flags)

<a id="rst-io-uring-provider-info"></a>
<a id="rst-netdev-attribute-set-io-uring-provider-info"></a>



### io-uring-provider-info

<a id="rst-page-pool"></a>
<a id="rst-netdev-attribute-set-page-pool"></a>



### page-pool

<a id="rst-id-uint"></a>



#### id (`uint`)

- **doc**:

  Unique ID of a Page Pool instance.

<a id="rst-ifindex-u32-1"></a>



#### ifindex (`u32`)

- **doc**:

  ifindex of the netdev to which the pool belongs. May not be reported if the page pool was allocated for a netdev which got destroyed already (page pools may outlast their netdevs because they wait for all memory to be returned).

<a id="rst-napi-id-uint"></a>



#### napi-id (`uint`)

- **doc**:

  Id of NAPI using this Page Pool instance.

<a id="rst-inflight-uint"></a>



#### inflight (`uint`)

- **doc**:

  Number of outstanding references to this page pool (allocated but yet to be freed pages). Allocated pages may be held in socket receive queues, driver receive ring, page pool recycling ring, the page pool cache, etc.

<a id="rst-inflight-mem-uint"></a>



#### inflight-mem (`uint`)

- **doc**:

  Amount of memory held by inflight pages.

<a id="rst-detach-time-uint"></a>



#### detach-time (`uint`)

- **doc**:

  Seconds in CLOCK\_BOOTTIME of when Page Pool was detached by the driver. Once detached Page Pool can no longer be used to allocate memory. Page Pools wait for all the memory allocated from them to be freed before truly disappearing. "Detached" Page Pools cannot be "re-attached", they are just waiting to disappear. Attribute is absent if Page Pool has not been detached, and can still be used to allocate new memory.

<a id="rst-dmabuf-u32"></a>



#### dmabuf (`u32`)

- **doc**:

  ID of the dmabuf this page-pool is attached to.

<a id="rst-io-uring-nest"></a>



#### io-uring (`nest`)

- **doc**:

  io-uring memory provider information.

- **nested-attributes**:

  [io-uring-provider-info](#rst-netdev-attribute-set-io-uring-provider-info)

<a id="rst-page-pool-info"></a>
<a id="rst-netdev-attribute-set-page-pool-info"></a>



### page-pool-info

<a id="rst-id"></a>



#### id

<a id="rst-ifindex"></a>



#### ifindex

<a id="rst-page-pool-stats"></a>
<a id="rst-netdev-attribute-set-page-pool-stats"></a>



### page-pool-stats



Page pool statistics, see docs for struct page\_pool\_stats
for information about individual statistics.

<a id="rst-info-nest"></a>



#### info (`nest`)

- **doc**:

  Page pool identifying information.

- **nested-attributes**:

  [page-pool-info](#rst-netdev-attribute-set-page-pool-info)

<a id="rst-alloc-fast-uint"></a>



#### alloc-fast (`uint`)

- **value**:

  8

<a id="rst-alloc-slow-uint"></a>



#### alloc-slow (`uint`)

<a id="rst-alloc-slow-high-order-uint"></a>



#### alloc-slow-high-order (`uint`)

<a id="rst-alloc-empty-uint"></a>



#### alloc-empty (`uint`)

<a id="rst-alloc-refill-uint"></a>



#### alloc-refill (`uint`)

<a id="rst-alloc-waive-uint"></a>



#### alloc-waive (`uint`)

<a id="rst-recycle-cached-uint"></a>



#### recycle-cached (`uint`)

<a id="rst-recycle-cache-full-uint"></a>



#### recycle-cache-full (`uint`)

<a id="rst-recycle-ring-uint"></a>



#### recycle-ring (`uint`)

<a id="rst-recycle-ring-full-uint"></a>



#### recycle-ring-full (`uint`)

<a id="rst-recycle-released-refcnt-uint"></a>



#### recycle-released-refcnt (`uint`)

<a id="rst-napi"></a>
<a id="rst-netdev-attribute-set-napi"></a>



### napi

<a id="rst-ifindex-u32-2"></a>



#### ifindex (`u32`)

- **doc**:

  ifindex of the netdevice to which NAPI instance belongs.

<a id="rst-id-u32"></a>



#### id (`u32`)

- **doc**:

  ID of the NAPI instance.

<a id="rst-irq-u32"></a>



#### irq (`u32`)

- **doc**:

  The associated interrupt vector number for the napi

<a id="rst-pid-u32"></a>



#### pid (`u32`)

- **doc**:

  PID of the napi thread, if NAPI is configured to operate in threaded mode. If NAPI is not in threaded mode (i.e. uses normal softirq context), the attribute will be absent.

<a id="rst-defer-hard-irqs-u32"></a>



#### defer-hard-irqs (`u32`)

- **doc**:

  The number of consecutive empty polls before IRQ deferral ends and hardware IRQs are re-enabled.

<a id="rst-gro-flush-timeout-uint"></a>



#### gro-flush-timeout (`uint`)

- **doc**:

  The timeout, in nanoseconds, of when to trigger the NAPI watchdog timer which schedules NAPI processing. Additionally, a non-zero value will also prevent GRO from flushing recent super-frames at the end of a NAPI cycle. This may add receive latency in exchange for reducing the number of frames processed by the network stack.

<a id="rst-irq-suspend-timeout-uint"></a>



#### irq-suspend-timeout (`uint`)

- **doc**:

  The timeout, in nanoseconds, of how long to suspend irq processing, if event polling finds events

<a id="rst-threaded-u32"></a>



#### threaded (`u32`)

- **doc**:

  Whether the NAPI is configured to operate in threaded polling mode. If this is set to enabled then the NAPI context operates in threaded polling mode. If this is set to busy-poll, then the threaded polling mode also busy polls.

- **enum**:

  [napi-threaded](#rst-netdev-definition-napi-threaded)

<a id="rst-xsk-info"></a>
<a id="rst-netdev-attribute-set-xsk-info"></a>



### xsk-info

<a id="rst-queue"></a>
<a id="rst-netdev-attribute-set-queue"></a>



### queue

<a id="rst-id-u32-1"></a>



#### id (`u32`)

- **doc**:

  Queue index; most queue types are indexed like a C array, with indexes starting at 0 and ending at queue count - 1. Queue indexes are scoped to an interface and queue type.

<a id="rst-ifindex-u32-3"></a>



#### ifindex (`u32`)

- **doc**:

  ifindex of the netdevice to which the queue belongs.

<a id="rst-type-u32"></a>



#### type (`u32`)

- **doc**:

  Queue type as rx, tx. Each queue type defines a separate ID space. XDP TX queues allocated in the kernel are not linked to NAPIs and thus not listed. AF\_XDP queues will have more information set in the xsk attribute.

- **enum**:

  [queue-type](#rst-netdev-definition-queue-type)

<a id="rst-napi-id-u32"></a>



#### napi-id (`u32`)

- **doc**:

  ID of the NAPI instance which services this queue.

<a id="rst-dmabuf-u32-1"></a>



#### dmabuf (`u32`)

- **doc**:

  ID of the dmabuf attached to this queue, if any.

<a id="rst-io-uring-nest-1"></a>



#### io-uring (`nest`)

- **doc**:

  io\_uring memory provider information.

- **nested-attributes**:

  [io-uring-provider-info](#rst-netdev-attribute-set-io-uring-provider-info)

<a id="rst-xsk-nest"></a>



#### xsk (`nest`)

- **doc**:

  XSK information for this queue, if any.

- **nested-attributes**:

  [xsk-info](#rst-netdev-attribute-set-xsk-info)

<a id="rst-qstats"></a>
<a id="rst-netdev-attribute-set-qstats"></a>



### qstats



Get device statistics, scoped to a device or a queue.
These statistics extend (and partially duplicate) statistics available
in struct rtnl\_link\_stats64.
Value of the *scope* attribute determines how statistics are
aggregated. When aggregated for the entire device the statistics
represent the total number of events since last explicit reset of
the device (i.e. not a reconfiguration like changing queue count).
When reported per-queue, however, the statistics may not add
up to the total number of events, will only be reported for currently
active objects, and will likely report the number of events since last
reconfiguration.

<a id="rst-ifindex-u32-4"></a>



#### ifindex (`u32`)

- **doc**:

  ifindex of the netdevice to which stats belong.

<a id="rst-queue-type-u32"></a>



#### queue-type (`u32`)

- **doc**:

  Queue type as rx, tx, for queue-id.

- **enum**:

  [queue-type](#rst-netdev-definition-queue-type)

<a id="rst-queue-id-u32"></a>



#### queue-id (`u32`)

- **doc**:

  Queue ID, if stats are scoped to a single queue instance.

<a id="rst-scope-uint"></a>



#### scope (`uint`)

- **doc**:

  What object type should be used to iterate over the stats.

- **enum**:

  [qstats-scope](#rst-netdev-definition-qstats-scope)

<a id="rst-rx-packets-uint"></a>



#### rx-packets (`uint`)

- **doc**:

  Number of wire packets successfully received and passed to the stack. For drivers supporting XDP, XDP is considered the first layer of the stack, so packets consumed by XDP are still counted here.

- **value**:

  8

<a id="rst-rx-bytes-uint"></a>



#### rx-bytes (`uint`)

- **doc**:

  Successfully received bytes, see *rx-packets*.

<a id="rst-tx-packets-uint"></a>



#### tx-packets (`uint`)

- **doc**:

  Number of wire packets successfully sent. Packet is considered to be successfully sent once it is in device memory (usually this means the device has issued a DMA completion for the packet).

<a id="rst-tx-bytes-uint"></a>



#### tx-bytes (`uint`)

- **doc**:

  Successfully sent bytes, see *tx-packets*.

<a id="rst-rx-alloc-fail-uint"></a>



#### rx-alloc-fail (`uint`)

- **doc**:

  Number of times skb or buffer allocation failed on the Rx datapath. Allocation failure may, or may not result in a packet drop, depending on driver implementation and whether system recovers quickly.

<a id="rst-rx-hw-drops-uint"></a>



#### rx-hw-drops (`uint`)

- **doc**:

  Number of all packets which entered the device, but never left it, including but not limited to: packets dropped due to lack of buffer space, processing errors, explicit or implicit policies and packet filters.

<a id="rst-rx-hw-drop-overruns-uint"></a>



#### rx-hw-drop-overruns (`uint`)

- **doc**:

  Number of packets dropped due to transient lack of resources, such as buffer space, host descriptors etc.

<a id="rst-rx-csum-complete-uint"></a>



#### rx-csum-complete (`uint`)

- **doc**:

  Number of packets that were marked as CHECKSUM\_COMPLETE.

<a id="rst-rx-csum-unnecessary-uint"></a>



#### rx-csum-unnecessary (`uint`)

- **doc**:

  Number of packets that were marked as CHECKSUM\_UNNECESSARY.

<a id="rst-rx-csum-none-uint"></a>



#### rx-csum-none (`uint`)

- **doc**:

  Number of packets that were not checksummed by device.

<a id="rst-rx-csum-bad-uint"></a>



#### rx-csum-bad (`uint`)

- **doc**:

  Number of packets with bad checksum. The packets are not discarded, but still delivered to the stack.

<a id="rst-rx-hw-gro-packets-uint"></a>



#### rx-hw-gro-packets (`uint`)

- **doc**:

  Number of packets that were coalesced from smaller packets by the device. Counts only packets coalesced with the HW-GRO netdevice feature, LRO-coalesced packets are not counted.

<a id="rst-rx-hw-gro-bytes-uint"></a>



#### rx-hw-gro-bytes (`uint`)

- **doc**:

  See *rx-hw-gro-packets*.

<a id="rst-rx-hw-gro-wire-packets-uint"></a>



#### rx-hw-gro-wire-packets (`uint`)

- **doc**:

  Number of packets that were coalesced to bigger packetss with the HW-GRO netdevice feature. LRO-coalesced packets are not counted.

<a id="rst-rx-hw-gro-wire-bytes-uint"></a>



#### rx-hw-gro-wire-bytes (`uint`)

- **doc**:

  See *rx-hw-gro-wire-packets*.

<a id="rst-rx-hw-drop-ratelimits-uint"></a>



#### rx-hw-drop-ratelimits (`uint`)

- **doc**:

  Number of the packets dropped by the device due to the received packets bitrate exceeding the device rate limit.

<a id="rst-tx-hw-drops-uint"></a>



#### tx-hw-drops (`uint`)

- **doc**:

  Number of packets that arrived at the device but never left it, encompassing packets dropped for reasons such as processing errors, as well as those affected by explicitly defined policies and packet filtering criteria.

<a id="rst-tx-hw-drop-errors-uint"></a>



#### tx-hw-drop-errors (`uint`)

- **doc**:

  Number of packets dropped because they were invalid or malformed.

<a id="rst-tx-csum-none-uint"></a>



#### tx-csum-none (`uint`)

- **doc**:

  Number of packets that did not require the device to calculate the checksum.

<a id="rst-tx-needs-csum-uint"></a>



#### tx-needs-csum (`uint`)

- **doc**:

  Number of packets that required the device to calculate the checksum. This counter includes the number of GSO wire packets for which device calculated the L4 checksum.

<a id="rst-tx-hw-gso-packets-uint"></a>



#### tx-hw-gso-packets (`uint`)

- **doc**:

  Number of packets that necessitated segmentation into smaller packets by the device.

<a id="rst-tx-hw-gso-bytes-uint"></a>



#### tx-hw-gso-bytes (`uint`)

- **doc**:

  See *tx-hw-gso-packets*.

<a id="rst-tx-hw-gso-wire-packets-uint"></a>



#### tx-hw-gso-wire-packets (`uint`)

- **doc**:

  Number of wire-sized packets generated by processing *tx-hw-gso-packets*

<a id="rst-tx-hw-gso-wire-bytes-uint"></a>



#### tx-hw-gso-wire-bytes (`uint`)

- **doc**:

  See *tx-hw-gso-wire-packets*.

<a id="rst-tx-hw-drop-ratelimits-uint"></a>



#### tx-hw-drop-ratelimits (`uint`)

- **doc**:

  Number of the packets dropped by the device due to the transmit packets bitrate exceeding the device rate limit.

<a id="rst-tx-stop-uint"></a>



#### tx-stop (`uint`)

- **doc**:

  Number of times driver paused accepting new tx packets from the stack to this queue, because the queue was full. Note that if BQL is supported and enabled on the device the networking stack will avoid queuing a lot of data at once.

<a id="rst-tx-wake-uint"></a>



#### tx-wake (`uint`)

- **doc**:

  Number of times driver re-started accepting send requests to this queue from the stack.

<a id="rst-queue-id"></a>
<a id="rst-netdev-attribute-set-queue-id"></a>



### queue-id

<a id="rst-id-1"></a>



#### id

<a id="rst-type"></a>



#### type

<a id="rst-dmabuf"></a>
<a id="rst-netdev-attribute-set-dmabuf"></a>



### dmabuf

<a id="rst-ifindex-u32-5"></a>



#### ifindex (`u32`)

- **doc**:

  netdev ifindex to bind the dmabuf to.

<a id="rst-queues-nest"></a>



#### queues (`nest`)

- **doc**:

  receive queues to bind the dmabuf to.

- **nested-attributes**:

  [queue-id](#rst-netdev-attribute-set-queue-id)

- **multi-attr**:

  True

<a id="rst-fd-u32"></a>



#### fd (`u32`)

- **doc**:

  dmabuf file descriptor to bind.

<a id="rst-id-u32-2"></a>



#### id (`u32`)

- **doc**:

  id of the dmabuf binding

---

# Family nfsd netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the nfsd Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-nfsd-netlink-specification"></a>
<a id="rst-netlink-nfsd"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



NFSD configuration over generic netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-rpc-status-get"></a>
<a id="rst-nfsd-operation-rpc-status-get"></a>



### rpc-status-get



dump pending nfsd rpc

- **attribute-set**:

  [rpc-status](#rst-nfsd-attribute-set-rpc-status)

- **dump**:

  **reply**

  - **attributes**:

    \[`xid`, `flags`, `prog`, `version`, `proc`, `service-time`, `saddr4`, `daddr4`, `saddr6`, `daddr6`, `sport`, `dport`, `compound-ops`\]

<a id="rst-threads-set"></a>
<a id="rst-nfsd-operation-threads-set"></a>



### threads-set



set the maximum number of running threads

- **attribute-set**:

  [server](#rst-nfsd-attribute-set-server)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`threads`, `gracetime`, `leasetime`, `scope`, `min-threads`\]

<a id="rst-threads-get"></a>
<a id="rst-nfsd-operation-threads-get"></a>



### threads-get



get the maximum number of running threads

- **attribute-set**:

  [server](#rst-nfsd-attribute-set-server)

- **do**:

  **reply**

  - **attributes**:

    \[`threads`, `gracetime`, `leasetime`, `scope`, `min-threads`\]

<a id="rst-version-set"></a>
<a id="rst-nfsd-operation-version-set"></a>



### version-set



set nfs enabled versions

- **attribute-set**:

  [server-proto](#rst-nfsd-attribute-set-server-proto)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`version`\]

<a id="rst-version-get"></a>
<a id="rst-nfsd-operation-version-get"></a>



### version-get



get nfs enabled versions

- **attribute-set**:

  [server-proto](#rst-nfsd-attribute-set-server-proto)

- **do**:

  **reply**

  - **attributes**:

    \[`version`\]

<a id="rst-listener-set"></a>
<a id="rst-nfsd-operation-listener-set"></a>



### listener-set



set nfs running sockets

- **attribute-set**:

  [server-sock](#rst-nfsd-attribute-set-server-sock)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr`\]

<a id="rst-listener-get"></a>
<a id="rst-nfsd-operation-listener-get"></a>



### listener-get



get nfs running listeners

- **attribute-set**:

  [server-sock](#rst-nfsd-attribute-set-server-sock)

- **do**:

  **reply**

  - **attributes**:

    \[`addr`\]

<a id="rst-pool-mode-set"></a>
<a id="rst-nfsd-operation-pool-mode-set"></a>



### pool-mode-set



set the current server pool-mode

- **attribute-set**:

  [pool-mode](#rst-nfsd-attribute-set-pool-mode)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`mode`\]

<a id="rst-pool-mode-get"></a>
<a id="rst-nfsd-operation-pool-mode-get"></a>



### pool-mode-get



get info about server pool-mode

- **attribute-set**:

  [pool-mode](#rst-nfsd-attribute-set-pool-mode)

- **do**:

  **reply**

  - **attributes**:

    \[`mode`, `npools`\]

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-rpc-status"></a>
<a id="rst-nfsd-attribute-set-rpc-status"></a>



### rpc-status

<a id="rst-xid-u32"></a>



#### xid (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32"></a>



#### flags (`u32`)

<a id="rst-prog-u32"></a>



#### prog (`u32`)

<a id="rst-version-u8"></a>



#### version (`u8`)

<a id="rst-proc-u32"></a>



#### proc (`u32`)

<a id="rst-service-time-s64"></a>



#### service-time (`s64`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-saddr4-u32"></a>



#### saddr4 (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-daddr4-u32"></a>



#### daddr4 (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-saddr6-binary"></a>



#### saddr6 (`binary`)

- **display-hint**:

  ipv6

<a id="rst-daddr6-binary"></a>



#### daddr6 (`binary`)

- **display-hint**:

  ipv6

<a id="rst-sport-u16"></a>



#### sport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-dport-u16"></a>



#### dport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-compound-ops-u32"></a>



#### compound-ops (`u32`)

- **multi-attr**:

  True

<a id="rst-server"></a>
<a id="rst-nfsd-attribute-set-server"></a>



### server

<a id="rst-threads-u32"></a>



#### threads (`u32`)

- **multi-attr**:

  True

<a id="rst-gracetime-u32"></a>



#### gracetime (`u32`)

<a id="rst-leasetime-u32"></a>



#### leasetime (`u32`)

<a id="rst-scope-string"></a>



#### scope (`string`)

<a id="rst-min-threads-u32"></a>



#### min-threads (`u32`)

<a id="rst-version"></a>
<a id="rst-nfsd-attribute-set-version"></a>



### version

<a id="rst-major-u32"></a>



#### major (`u32`)

<a id="rst-minor-u32"></a>



#### minor (`u32`)

<a id="rst-enabled-flag"></a>



#### enabled (`flag`)

<a id="rst-server-proto"></a>
<a id="rst-nfsd-attribute-set-server-proto"></a>



### server-proto

<a id="rst-version-nest"></a>



#### version (`nest`)

- **nested-attributes**:

  [version](#rst-nfsd-attribute-set-version)

- **multi-attr**:

  True

<a id="rst-sock"></a>
<a id="rst-nfsd-attribute-set-sock"></a>



### sock

<a id="rst-addr-binary"></a>



#### addr (`binary`)

<a id="rst-transport-name-string"></a>



#### transport-name (`string`)

<a id="rst-server-sock"></a>
<a id="rst-nfsd-attribute-set-server-sock"></a>



### server-sock

<a id="rst-addr-nest"></a>



#### addr (`nest`)

- **nested-attributes**:

  [sock](#rst-nfsd-attribute-set-sock)

- **multi-attr**:

  True

<a id="rst-pool-mode"></a>
<a id="rst-nfsd-attribute-set-pool-mode"></a>



### pool-mode

<a id="rst-mode-string"></a>



#### mode (`string`)

<a id="rst-npools-u32"></a>



#### npools (`u32`)

---

# Family nftables netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the nftables Netlink family, generated from the Peios kernel specification.

> **Peios:** This describes an upstream interface disabled in the configured Peios kernel. Peios uses NTFE; nftables/iptables, IPVS and flow-table configuration are not enabled policy paths. Retained schemas and reference text do not imply runtime availability. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-nftables-netlink-specification"></a>
<a id="rst-netlink-nftables"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netfilter nftables configuration over netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-batch-begin"></a>
<a id="rst-nftables-operation-batch-begin"></a>



### batch-begin



Start a batch of operations

- **attribute-set**:

  [batch-attrs](#rst-nftables-attribute-set-batch-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`genid`\]

  **reply**

  - **attributes**:

    \[`genid`\]

<a id="rst-batch-end"></a>
<a id="rst-nftables-operation-batch-end"></a>



### batch-end



Finish a batch of operations

- **attribute-set**:

  [batch-attrs](#rst-nftables-attribute-set-batch-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`genid`\]

<a id="rst-newtable"></a>
<a id="rst-nftables-operation-newtable"></a>



### newtable



Create a new table.

- **attribute-set**:

  [table-attrs](#rst-nftables-attribute-set-table-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-gettable"></a>
<a id="rst-nftables-operation-gettable"></a>



### gettable



Get / dump tables.

- **attribute-set**:

  [table-attrs](#rst-nftables-attribute-set-table-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-deltable"></a>
<a id="rst-nftables-operation-deltable"></a>



### deltable



Delete an existing table.

- **attribute-set**:

  [table-attrs](#rst-nftables-attribute-set-table-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroytable"></a>
<a id="rst-nftables-operation-destroytable"></a>



### destroytable



Delete an existing table with destroy semantics (ignoring ENOENT
errors).

- **attribute-set**:

  [table-attrs](#rst-nftables-attribute-set-table-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-newchain"></a>
<a id="rst-nftables-operation-newchain"></a>



### newchain



Create a new chain.

- **attribute-set**:

  [chain-attrs](#rst-nftables-attribute-set-chain-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getchain"></a>
<a id="rst-nftables-operation-getchain"></a>



### getchain



Get / dump chains.

- **attribute-set**:

  [chain-attrs](#rst-nftables-attribute-set-chain-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delchain"></a>
<a id="rst-nftables-operation-delchain"></a>



### delchain



Delete an existing chain.

- **attribute-set**:

  [chain-attrs](#rst-nftables-attribute-set-chain-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroychain"></a>
<a id="rst-nftables-operation-destroychain"></a>



### destroychain



Delete an existing chain with destroy semantics (ignoring ENOENT
errors).

- **attribute-set**:

  [chain-attrs](#rst-nftables-attribute-set-chain-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-newrule"></a>
<a id="rst-nftables-operation-newrule"></a>



### newrule



Create a new rule.

- **attribute-set**:

  [rule-attrs](#rst-nftables-attribute-set-rule-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getrule"></a>
<a id="rst-nftables-operation-getrule"></a>



### getrule



Get / dump rules.

- **attribute-set**:

  [rule-attrs](#rst-nftables-attribute-set-rule-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-getrule-reset"></a>
<a id="rst-nftables-operation-getrule-reset"></a>



### getrule-reset



Get / dump rules and reset stateful expressions.

- **attribute-set**:

  [rule-attrs](#rst-nftables-attribute-set-rule-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delrule"></a>
<a id="rst-nftables-operation-delrule"></a>



### delrule



Delete an existing rule.

- **attribute-set**:

  [rule-attrs](#rst-nftables-attribute-set-rule-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroyrule"></a>
<a id="rst-nftables-operation-destroyrule"></a>



### destroyrule



Delete an existing rule with destroy semantics (ignoring ENOENT errors).

- **attribute-set**:

  [rule-attrs](#rst-nftables-attribute-set-rule-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-newset"></a>
<a id="rst-nftables-operation-newset"></a>



### newset



Create a new set.

- **attribute-set**:

  [set-attrs](#rst-nftables-attribute-set-set-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getset"></a>
<a id="rst-nftables-operation-getset"></a>



### getset



Get / dump sets.

- **attribute-set**:

  [set-attrs](#rst-nftables-attribute-set-set-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delset"></a>
<a id="rst-nftables-operation-delset"></a>



### delset



Delete an existing set.

- **attribute-set**:

  [set-attrs](#rst-nftables-attribute-set-set-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroyset"></a>
<a id="rst-nftables-operation-destroyset"></a>



### destroyset



Delete an existing set with destroy semantics (ignoring ENOENT errors).

- **attribute-set**:

  [set-attrs](#rst-nftables-attribute-set-set-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-newsetelem"></a>
<a id="rst-nftables-operation-newsetelem"></a>



### newsetelem



Create a new set element.

- **attribute-set**:

  [setelem-list-attrs](#rst-nftables-attribute-set-setelem-list-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getsetelem"></a>
<a id="rst-nftables-operation-getsetelem"></a>



### getsetelem



Get / dump set elements.

- **attribute-set**:

  [setelem-list-attrs](#rst-nftables-attribute-set-setelem-list-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-getsetelem-reset"></a>
<a id="rst-nftables-operation-getsetelem-reset"></a>



### getsetelem-reset



Get / dump set elements and reset stateful expressions.

- **attribute-set**:

  [setelem-list-attrs](#rst-nftables-attribute-set-setelem-list-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delsetelem"></a>
<a id="rst-nftables-operation-delsetelem"></a>



### delsetelem



Delete an existing set element.

- **attribute-set**:

  [setelem-list-attrs](#rst-nftables-attribute-set-setelem-list-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroysetelem"></a>
<a id="rst-nftables-operation-destroysetelem"></a>



### destroysetelem



Delete an existing set element with destroy semantics.

- **attribute-set**:

  [setelem-list-attrs](#rst-nftables-attribute-set-setelem-list-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getgen"></a>
<a id="rst-nftables-operation-getgen"></a>



### getgen



Get / dump rule-set generation.

- **attribute-set**:

  [gen-attrs](#rst-nftables-attribute-set-gen-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-newobj"></a>
<a id="rst-nftables-operation-newobj"></a>



### newobj



Create a new stateful object.

- **attribute-set**:

  [obj-attrs](#rst-nftables-attribute-set-obj-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getobj"></a>
<a id="rst-nftables-operation-getobj"></a>



### getobj



Get / dump stateful objects.

- **attribute-set**:

  [obj-attrs](#rst-nftables-attribute-set-obj-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delobj"></a>
<a id="rst-nftables-operation-delobj"></a>



### delobj



Delete an existing stateful object.

- **attribute-set**:

  [obj-attrs](#rst-nftables-attribute-set-obj-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroyobj"></a>
<a id="rst-nftables-operation-destroyobj"></a>



### destroyobj



Delete an existing stateful object with destroy semantics.

- **attribute-set**:

  [obj-attrs](#rst-nftables-attribute-set-obj-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-newflowtable"></a>
<a id="rst-nftables-operation-newflowtable"></a>



### newflowtable



Create a new flow table.

- **attribute-set**:

  [flowtable-attrs](#rst-nftables-attribute-set-flowtable-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-getflowtable"></a>
<a id="rst-nftables-operation-getflowtable"></a>



### getflowtable



Get / dump flow tables.

- **attribute-set**:

  [flowtable-attrs](#rst-nftables-attribute-set-flowtable-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`\]

<a id="rst-delflowtable"></a>
<a id="rst-nftables-operation-delflowtable"></a>



### delflowtable



Delete an existing flow table.

- **attribute-set**:

  [flowtable-attrs](#rst-nftables-attribute-set-flowtable-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-destroyflowtable"></a>
<a id="rst-nftables-operation-destroyflowtable"></a>



### destroyflowtable



Delete an existing flow table with destroy semantics.

- **attribute-set**:

  [flowtable-attrs](#rst-nftables-attribute-set-flowtable-attrs)

- **fixed-header**:

  [nfgenmsg](#rst-nftables-definition-nfgenmsg)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- mgmt


<a id="rst-definitions"></a>



## Definitions

<a id="rst-nfgenmsg"></a>
<a id="rst-nftables-definition-nfgenmsg"></a>



### nfgenmsg

- **type**:

  struct

- **members**:

  - **nfgen-family (`u8`)**

  - **version (`u8`)**

  - **res-id (`u16`)**

<a id="rst-meta-keys"></a>
<a id="rst-nftables-definition-meta-keys"></a>



### meta-keys

- **type**:

  enum

- **entries**:

  - `len`


  - `protocol`


  - `priority`


  - `mark`


  - `iif`


  - `oif`


  - `iifname`


  - `oifname`


  - `iftype`


  - `oiftype`


  - `skuid`


  - `skgid`


  - `nftrace`


  - `rtclassid`


  - `secmark`


  - `nfproto`


  - `l4-proto`


  - `bri-iifname`


  - `bri-oifname`


  - `pkttype`


  - `cpu`


  - `iifgroup`


  - `oifgroup`


  - `cgroup`


  - `prandom`


  - `secpath`


  - `iifkind`


  - `oifkind`


  - `bri-iifpvid`


  - `bri-iifvproto`


  - `time-ns`


  - `time-day`


  - `time-hour`


  - `sdif`


  - `sdifname`


  - `bri-broute`

<a id="rst-bitwise-ops"></a>
<a id="rst-nftables-definition-bitwise-ops"></a>



### bitwise-ops

- **type**:

  enum

- **entries**:

  - `bool`


  - `lshift`


  - `rshift`

<a id="rst-cmp-ops"></a>
<a id="rst-nftables-definition-cmp-ops"></a>



### cmp-ops

- **type**:

  enum

- **entries**:

  - `eq`


  - `neq`


  - `lt`


  - `lte`


  - `gt`


  - `gte`

<a id="rst-object-type"></a>
<a id="rst-nftables-definition-object-type"></a>



### object-type

- **type**:

  enum

- **entries**:

  - `unspec`


  - `counter`


  - `quota`


  - `ct-helper`


  - `limit`


  - `connlimit`


  - `tunnel`


  - `ct-timeout`


  - `secmark`


  - `ct-expect`


  - `synproxy`

<a id="rst-nat-range-flags"></a>
<a id="rst-nftables-definition-nat-range-flags"></a>



### nat-range-flags

- **type**:

  flags

- **entries**:

  - `map-ips`


  - `proto-specified`


  - `proto-random`


  - `persistent`


  - `proto-random-fully`


  - `proto-offset`


  - `netmap`

<a id="rst-table-flags"></a>
<a id="rst-nftables-definition-table-flags"></a>



### table-flags

- **type**:

  flags

- **entries**:

  - `dormant`


  - `owner`


  - `persist`

<a id="rst-chain-flags"></a>
<a id="rst-nftables-definition-chain-flags"></a>



### chain-flags

- **type**:

  flags

- **entries**:

  - `base`


  - `hw-offload`


  - `binding`

<a id="rst-set-flags"></a>
<a id="rst-nftables-definition-set-flags"></a>



### set-flags

- **type**:

  flags

- **entries**:

  - `anonymous`


  - `constant`


  - `interval`


  - `map`


  - `timeout`


  - `eval`


  - `object`


  - `concat`


  - `expr`

<a id="rst-lookup-flags"></a>
<a id="rst-nftables-definition-lookup-flags"></a>



### lookup-flags

- **type**:

  flags

- **entries**:

  - `invert`

<a id="rst-ct-keys"></a>
<a id="rst-nftables-definition-ct-keys"></a>



### ct-keys

- **type**:

  enum

- **entries**:

  - `state`


  - `direction`


  - `status`


  - `mark`


  - `secmark`


  - `expiration`


  - `helper`


  - `l3protocol`


  - `src`


  - `dst`


  - `protocol`


  - `proto-src`


  - `proto-dst`


  - `labels`


  - `pkts`


  - `bytes`


  - `avgpkt`


  - `zone`


  - `eventmask`


  - `src-ip`


  - `dst-ip`


  - `src-ip6`


  - `dst-ip6`


  - `ct-id`

<a id="rst-ct-direction"></a>
<a id="rst-nftables-definition-ct-direction"></a>



### ct-direction

- **type**:

  enum

- **entries**:

  - `original`


  - `reply`

<a id="rst-quota-flags"></a>
<a id="rst-nftables-definition-quota-flags"></a>



### quota-flags

- **type**:

  flags

- **entries**:

  - `invert`


  - `depleted`

<a id="rst-verdict-code"></a>
<a id="rst-nftables-definition-verdict-code"></a>



### verdict-code

- **type**:

  enum

- **entries**:

  - **continue**

  - **break**

  - **jump**

  - **goto**

  - **return**

  - **drop**

  - **accept**

  - **stolen**

  - **queue**

  - **repeat**

<a id="rst-fib-result"></a>
<a id="rst-nftables-definition-fib-result"></a>



### fib-result

- **type**:

  enum

- **entries**:

  - `oif`


  - `oifname`


  - `addrtype`

<a id="rst-fib-flags"></a>
<a id="rst-nftables-definition-fib-flags"></a>



### fib-flags

- **type**:

  flags

- **entries**:

  - `saddr`


  - `daddr`


  - `mark`


  - `iif`


  - `oif`


  - `present`

<a id="rst-reject-types"></a>
<a id="rst-nftables-definition-reject-types"></a>



### reject-types

- **type**:

  enum

- **entries**:

  - `icmp-unreach`


  - `tcp-rst`


  - `icmpx-unreach`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-empty-attrs"></a>
<a id="rst-nftables-attribute-set-empty-attrs"></a>



### empty-attrs

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-batch-attrs"></a>
<a id="rst-nftables-attribute-set-batch-attrs"></a>



### batch-attrs

<a id="rst-genid-u32"></a>



#### genid (`u32`)

- **byte-order**:

  big-endian

<a id="rst-table-attrs"></a>
<a id="rst-nftables-attribute-set-table-attrs"></a>



### table-attrs

<a id="rst-name-string-1"></a>



#### name (`string`)

- **doc**:

  name of the table

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  bitmask of flags

- **enum**:

  [table-flags](#rst-nftables-definition-table-flags)

- **enum-as-flags**:

  True

<a id="rst-use-u32"></a>



#### use (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  number of chains in this table

<a id="rst-handle-u64"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  numeric handle of the table

<a id="rst-userdata-binary"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-chain-attrs"></a>
<a id="rst-nftables-attribute-set-chain-attrs"></a>



### chain-attrs

<a id="rst-table-string"></a>



#### table (`string`)

- **doc**:

  name of the table containing the chain

<a id="rst-handle-u64-1"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  numeric handle of the chain

<a id="rst-name-string-2"></a>



#### name (`string`)

- **doc**:

  name of the chain

<a id="rst-hook-nest"></a>



#### hook (`nest`)

- **nested-attributes**:

  [nft-hook-attrs](#rst-nftables-attribute-set-nft-hook-attrs)

- **doc**:

  hook specification for basechains

<a id="rst-policy-u32"></a>



#### policy (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  numeric policy of the chain

<a id="rst-use-u32-1"></a>



#### use (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  number of references to this chain

<a id="rst-type-string"></a>



#### type (`string`)

- **doc**:

  type name of the chain

<a id="rst-counters-nest"></a>



#### counters (`nest`)

- **nested-attributes**:

  [nft-counter-attrs](#rst-nftables-attribute-set-nft-counter-attrs)

- **doc**:

  counter specification of the chain

<a id="rst-flags-u32-1"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  chain flags

- **enum**:

  [chain-flags](#rst-nftables-definition-chain-flags)

- **enum-as-flags**:

  True

<a id="rst-id-u32"></a>



#### id (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  uniquely identifies a chain in a transaction

<a id="rst-userdata-binary-1"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-counter-attrs"></a>
<a id="rst-nftables-attribute-set-counter-attrs"></a>



### counter-attrs

<a id="rst-bytes-u64"></a>



#### bytes (`u64`)

- **byte-order**:

  big-endian

<a id="rst-packets-u64"></a>



#### packets (`u64`)

- **byte-order**:

  big-endian

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-nft-hook-attrs"></a>
<a id="rst-nftables-attribute-set-nft-hook-attrs"></a>



### nft-hook-attrs

<a id="rst-num-u32"></a>



#### num (`u32`)

- **byte-order**:

  big-endian

<a id="rst-priority-s32"></a>



#### priority (`s32`)

- **byte-order**:

  big-endian

<a id="rst-dev-string"></a>



#### dev (`string`)

- **doc**:

  net device name

<a id="rst-devs-nest"></a>



#### devs (`nest`)

- **nested-attributes**:

  [hook-dev-attrs](#rst-nftables-attribute-set-hook-dev-attrs)

- **doc**:

  list of net devices

<a id="rst-hook-dev-attrs"></a>
<a id="rst-nftables-attribute-set-hook-dev-attrs"></a>



### hook-dev-attrs

<a id="rst-name-string-3"></a>



#### name (`string`)

- **multi-attr**:

  True

<a id="rst-nft-counter-attrs"></a>
<a id="rst-nftables-attribute-set-nft-counter-attrs"></a>



### nft-counter-attrs

<a id="rst-bytes-u64-1"></a>



#### bytes (`u64`)

<a id="rst-packets-u64-1"></a>



#### packets (`u64`)

<a id="rst-rule-attrs"></a>
<a id="rst-nftables-attribute-set-rule-attrs"></a>



### rule-attrs

<a id="rst-table-string-1"></a>



#### table (`string`)

- **doc**:

  name of the table containing the rule

<a id="rst-chain-string"></a>



#### chain (`string`)

- **doc**:

  name of the chain containing the rule

<a id="rst-handle-u64-2"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  numeric handle of the rule

<a id="rst-expressions-nest"></a>



#### expressions (`nest`)

- **nested-attributes**:

  [expr-list-attrs](#rst-nftables-attribute-set-expr-list-attrs)

- **doc**:

  list of expressions

<a id="rst-compat-nest"></a>



#### compat (`nest`)

- **nested-attributes**:

  [rule-compat-attrs](#rst-nftables-attribute-set-rule-compat-attrs)

- **doc**:

  compatibility specifications of the rule

<a id="rst-position-u64"></a>



#### position (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  numeric handle of the previous rule

<a id="rst-userdata-binary-2"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-id-u32-1"></a>



#### id (`u32`)

- **doc**:

  uniquely identifies a rule in a transaction

<a id="rst-position-id-u32"></a>



#### position-id (`u32`)

- **doc**:

  transaction unique identifier of the previous rule

<a id="rst-chain-id-u32"></a>



#### chain-id (`u32`)

- **doc**:

  add the rule to chain by ID, alternative to chain name

<a id="rst-expr-list-attrs"></a>
<a id="rst-nftables-attribute-set-expr-list-attrs"></a>



### expr-list-attrs

<a id="rst-elem-nest"></a>



#### elem (`nest`)

- **nested-attributes**:

  [expr-attrs](#rst-nftables-attribute-set-expr-attrs)

- **multi-attr**:

  True

<a id="rst-expr-attrs"></a>
<a id="rst-nftables-attribute-set-expr-attrs"></a>



### expr-attrs

<a id="rst-name-string-4"></a>



#### name (`string`)

- **doc**:

  name of the expression type

<a id="rst-data-sub-message"></a>



#### data (`sub-message`)

- **sub-message**:

  [expr-ops](#rst-nftables-sub-message-expr-ops)

- **selector**:

  name

- **doc**:

  type specific data

<a id="rst-rule-compat-attrs"></a>
<a id="rst-nftables-attribute-set-rule-compat-attrs"></a>



### rule-compat-attrs

<a id="rst-proto-binary"></a>



#### proto (`binary`)

- **doc**:

  numeric value of the handled protocol

<a id="rst-flags-binary"></a>



#### flags (`binary`)

- **doc**:

  bitmask of flags

<a id="rst-set-attrs"></a>
<a id="rst-nftables-attribute-set-set-attrs"></a>



### set-attrs

<a id="rst-table-string-2"></a>



#### table (`string`)

- **doc**:

  table name

<a id="rst-name-string-5"></a>



#### name (`string`)

- **doc**:

  set name

<a id="rst-flags-u32-2"></a>



#### flags (`u32`)

- **enum**:

  [set-flags](#rst-nftables-definition-set-flags)

- **byte-order**:

  big-endian

- **doc**:

  bitmask of enum nft\_set\_flags

<a id="rst-key-type-u32"></a>



#### key-type (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  key data type, informational purpose only

<a id="rst-key-len-u32"></a>



#### key-len (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  key data length

<a id="rst-data-type-u32"></a>



#### data-type (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  mapping data type

<a id="rst-data-len-u32"></a>



#### data-len (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  mapping data length

<a id="rst-policy-u32-1"></a>



#### policy (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  selection policy

<a id="rst-desc-nest"></a>



#### desc (`nest`)

- **nested-attributes**:

  [set-desc-attrs](#rst-nftables-attribute-set-set-desc-attrs)

- **doc**:

  set description

<a id="rst-id-u32-2"></a>



#### id (`u32`)

- **doc**:

  uniquely identifies a set in a transaction

<a id="rst-timeout-u64"></a>



#### timeout (`u64`)

- **doc**:

  default timeout value

<a id="rst-gc-interval-u32"></a>



#### gc-interval (`u32`)

- **doc**:

  garbage collection interval

<a id="rst-userdata-binary-3"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-obj-type-u32"></a>



#### obj-type (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  stateful object type

<a id="rst-handle-u64-3"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  set handle

<a id="rst-expr-nest"></a>



#### expr (`nest`)

- **nested-attributes**:

  [expr-attrs](#rst-nftables-attribute-set-expr-attrs)

- **doc**:

  set expression

- **multi-attr**:

  True

<a id="rst-expressions-nest-1"></a>



#### expressions (`nest`)

- **nested-attributes**:

  [set-list-attrs](#rst-nftables-attribute-set-set-list-attrs)

- **doc**:

  list of expressions

<a id="rst-set-desc-attrs"></a>
<a id="rst-nftables-attribute-set-set-desc-attrs"></a>



### set-desc-attrs

<a id="rst-size-u32"></a>



#### size (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  number of elements in set

<a id="rst-concat-nest"></a>



#### concat (`nest`)

- **nested-attributes**:

  [set-desc-concat-attrs](#rst-nftables-attribute-set-set-desc-concat-attrs)

- **doc**:

  description of field concatenation

- **multi-attr**:

  True

<a id="rst-set-desc-concat-attrs"></a>
<a id="rst-nftables-attribute-set-set-desc-concat-attrs"></a>



### set-desc-concat-attrs

<a id="rst-elem-nest-1"></a>



#### elem (`nest`)

- **nested-attributes**:

  [set-field-attrs](#rst-nftables-attribute-set-set-field-attrs)

<a id="rst-set-field-attrs"></a>
<a id="rst-nftables-attribute-set-set-field-attrs"></a>



### set-field-attrs

<a id="rst-len-u32"></a>



#### len (`u32`)

- **byte-order**:

  big-endian

<a id="rst-set-list-attrs"></a>
<a id="rst-nftables-attribute-set-set-list-attrs"></a>



### set-list-attrs

<a id="rst-elem-nest-2"></a>



#### elem (`nest`)

- **nested-attributes**:

  [expr-attrs](#rst-nftables-attribute-set-expr-attrs)

- **multi-attr**:

  True

<a id="rst-setelem-attrs"></a>
<a id="rst-nftables-attribute-set-setelem-attrs"></a>



### setelem-attrs

<a id="rst-key-nest"></a>



#### key (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

- **doc**:

  key value

<a id="rst-data-nest"></a>



#### data (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

- **doc**:

  data value of mapping

<a id="rst-flags-binary-1"></a>



#### flags (`binary`)

- **doc**:

  bitmask of nft\_set\_elem\_flags

<a id="rst-timeout-u64-1"></a>



#### timeout (`u64`)

- **doc**:

  timeout value

<a id="rst-expiration-u64"></a>



#### expiration (`u64`)

- **doc**:

  expiration time

<a id="rst-userdata-binary-4"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-expr-nest-1"></a>



#### expr (`nest`)

- **nested-attributes**:

  [expr-attrs](#rst-nftables-attribute-set-expr-attrs)

- **doc**:

  expression

<a id="rst-objref-string"></a>



#### objref (`string`)

- **doc**:

  stateful object reference

<a id="rst-key-end-nest"></a>



#### key-end (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

- **doc**:

  closing key value

<a id="rst-expressions-nest-2"></a>



#### expressions (`nest`)

- **nested-attributes**:

  [expr-list-attrs](#rst-nftables-attribute-set-expr-list-attrs)

- **doc**:

  list of expressions

<a id="rst-setelem-list-elem-attrs"></a>
<a id="rst-nftables-attribute-set-setelem-list-elem-attrs"></a>



### setelem-list-elem-attrs

<a id="rst-elem-nest-3"></a>



#### elem (`nest`)

- **nested-attributes**:

  [setelem-attrs](#rst-nftables-attribute-set-setelem-attrs)

- **multi-attr**:

  True

<a id="rst-setelem-list-attrs"></a>
<a id="rst-nftables-attribute-set-setelem-list-attrs"></a>



### setelem-list-attrs

<a id="rst-table-string-3"></a>



#### table (`string`)

<a id="rst-set-string"></a>



#### set (`string`)

<a id="rst-elements-nest"></a>



#### elements (`nest`)

- **nested-attributes**:

  [setelem-list-elem-attrs](#rst-nftables-attribute-set-setelem-list-elem-attrs)

<a id="rst-set-id-u32"></a>



#### set-id (`u32`)

<a id="rst-gen-attrs"></a>
<a id="rst-nftables-attribute-set-gen-attrs"></a>



### gen-attrs

<a id="rst-id-u32-3"></a>



#### id (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  ruleset generation id

<a id="rst-proc-pid-u32"></a>



#### proc-pid (`u32`)

- **byte-order**:

  big-endian

<a id="rst-proc-name-string"></a>



#### proc-name (`string`)

<a id="rst-obj-attrs"></a>
<a id="rst-nftables-attribute-set-obj-attrs"></a>



### obj-attrs

<a id="rst-table-string-4"></a>



#### table (`string`)

- **doc**:

  name of the table containing the expression

<a id="rst-name-string-6"></a>



#### name (`string`)

- **doc**:

  name of this expression type

<a id="rst-type-u32"></a>



#### type (`u32`)

- **enum**:

  [object-type](#rst-nftables-definition-object-type)

- **byte-order**:

  big-endian

- **doc**:

  stateful object type

<a id="rst-data-sub-message-1"></a>



#### data (`sub-message`)

- **sub-message**:

  [obj-data](#rst-nftables-sub-message-obj-data)

- **selector**:

  type

- **doc**:

  stateful object data

<a id="rst-use-u32-2"></a>



#### use (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  number of references to this expression

<a id="rst-handle-u64-4"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

- **doc**:

  object handle

<a id="rst-pad-pad-2"></a>



#### pad (`pad`)

<a id="rst-userdata-binary-5"></a>



#### userdata (`binary`)

- **doc**:

  user data

<a id="rst-quota-attrs"></a>
<a id="rst-nftables-attribute-set-quota-attrs"></a>



### quota-attrs

<a id="rst-bytes-u64-2"></a>



#### bytes (`u64`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32-3"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [quota-flags](#rst-nftables-definition-quota-flags)

<a id="rst-pad-pad-3"></a>



#### pad (`pad`)

<a id="rst-consumed-u64"></a>



#### consumed (`u64`)

- **byte-order**:

  big-endian

<a id="rst-flowtable-attrs"></a>
<a id="rst-nftables-attribute-set-flowtable-attrs"></a>



### flowtable-attrs

<a id="rst-table-string-5"></a>



#### table (`string`)

<a id="rst-name-string-7"></a>



#### name (`string`)

<a id="rst-hook-nest-1"></a>



#### hook (`nest`)

- **nested-attributes**:

  [flowtable-hook-attrs](#rst-nftables-attribute-set-flowtable-hook-attrs)

<a id="rst-use-u32-3"></a>



#### use (`u32`)

- **byte-order**:

  big-endian

<a id="rst-handle-u64-5"></a>



#### handle (`u64`)

- **byte-order**:

  big-endian

<a id="rst-pad-pad-4"></a>



#### pad (`pad`)

<a id="rst-flags-u32-4"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flowtable-hook-attrs"></a>
<a id="rst-nftables-attribute-set-flowtable-hook-attrs"></a>



### flowtable-hook-attrs

<a id="rst-num-u32-1"></a>



#### num (`u32`)

- **byte-order**:

  big-endian

<a id="rst-priority-u32"></a>



#### priority (`u32`)

- **byte-order**:

  big-endian

<a id="rst-devs-nest-1"></a>



#### devs (`nest`)

- **nested-attributes**:

  [hook-dev-attrs](#rst-nftables-attribute-set-hook-dev-attrs)

<a id="rst-expr-bitwise-attrs"></a>
<a id="rst-nftables-attribute-set-expr-bitwise-attrs"></a>



### expr-bitwise-attrs

<a id="rst-sreg-u32"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-dreg-u32"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-len-u32-1"></a>



#### len (`u32`)

- **byte-order**:

  big-endian

<a id="rst-mask-nest"></a>



#### mask (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

<a id="rst-xor-nest"></a>



#### xor (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

<a id="rst-op-u32"></a>



#### op (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [bitwise-ops](#rst-nftables-definition-bitwise-ops)

<a id="rst-data-nest-1"></a>



#### data (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

<a id="rst-expr-cmp-attrs"></a>
<a id="rst-nftables-attribute-set-expr-cmp-attrs"></a>



### expr-cmp-attrs

<a id="rst-sreg-u32-1"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-op-u32-1"></a>



#### op (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [cmp-ops](#rst-nftables-definition-cmp-ops)

<a id="rst-data-nest-2"></a>



#### data (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

<a id="rst-data-attrs"></a>
<a id="rst-nftables-attribute-set-data-attrs"></a>



### data-attrs

<a id="rst-value-binary"></a>



#### value (`binary`)

<a id="rst-verdict-nest"></a>



#### verdict (`nest`)

- **nested-attributes**:

  [verdict-attrs](#rst-nftables-attribute-set-verdict-attrs)

<a id="rst-verdict-attrs"></a>
<a id="rst-nftables-attribute-set-verdict-attrs"></a>



### verdict-attrs

<a id="rst-code-u32"></a>



#### code (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [verdict-code](#rst-nftables-definition-verdict-code)

<a id="rst-chain-string-1"></a>



#### chain (`string`)

<a id="rst-chain-id-u32-1"></a>



#### chain-id (`u32`)

<a id="rst-expr-counter-attrs"></a>
<a id="rst-nftables-attribute-set-expr-counter-attrs"></a>



### expr-counter-attrs

<a id="rst-bytes-u64-3"></a>



#### bytes (`u64`)

- **doc**:

  Number of bytes

<a id="rst-packets-u64-2"></a>



#### packets (`u64`)

- **doc**:

  Number of packets

<a id="rst-pad-pad-5"></a>



#### pad (`pad`)

<a id="rst-expr-fib-attrs"></a>
<a id="rst-nftables-attribute-set-expr-fib-attrs"></a>



### expr-fib-attrs

<a id="rst-dreg-u32-1"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-result-u32"></a>



#### result (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [fib-result](#rst-nftables-definition-fib-result)

<a id="rst-flags-u32-5"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [fib-flags](#rst-nftables-definition-fib-flags)

<a id="rst-expr-ct-attrs"></a>
<a id="rst-nftables-attribute-set-expr-ct-attrs"></a>



### expr-ct-attrs

<a id="rst-dreg-u32-2"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-u32"></a>



#### key (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [ct-keys](#rst-nftables-definition-ct-keys)

<a id="rst-direction-u8"></a>



#### direction (`u8`)

- **enum**:

  [ct-direction](#rst-nftables-definition-ct-direction)

<a id="rst-sreg-u32-2"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-expr-flow-offload-attrs"></a>
<a id="rst-nftables-attribute-set-expr-flow-offload-attrs"></a>



### expr-flow-offload-attrs

<a id="rst-name-string-8"></a>



#### name (`string`)

- **doc**:

  Flow offload table name

<a id="rst-expr-immediate-attrs"></a>
<a id="rst-nftables-attribute-set-expr-immediate-attrs"></a>



### expr-immediate-attrs

<a id="rst-dreg-u32-3"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-data-nest-3"></a>



#### data (`nest`)

- **nested-attributes**:

  [data-attrs](#rst-nftables-attribute-set-data-attrs)

<a id="rst-expr-lookup-attrs"></a>
<a id="rst-nftables-attribute-set-expr-lookup-attrs"></a>



### expr-lookup-attrs

<a id="rst-set-string-1"></a>



#### set (`string`)

- **doc**:

  Name of set to use

<a id="rst-set-id-u32-1"></a>



#### set-id (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  ID of set to use

<a id="rst-sreg-u32-3"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-dreg-u32-4"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32-6"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [lookup-flags](#rst-nftables-definition-lookup-flags)

<a id="rst-expr-meta-attrs"></a>
<a id="rst-nftables-attribute-set-expr-meta-attrs"></a>



### expr-meta-attrs

<a id="rst-dreg-u32-5"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-u32-1"></a>



#### key (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [meta-keys](#rst-nftables-definition-meta-keys)

<a id="rst-sreg-u32-4"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-expr-nat-attrs"></a>
<a id="rst-nftables-attribute-set-expr-nat-attrs"></a>



### expr-nat-attrs

<a id="rst-type-u32-1"></a>



#### type (`u32`)

- **byte-order**:

  big-endian

<a id="rst-family-u32"></a>



#### family (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-addr-min-u32"></a>



#### reg-addr-min (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-addr-max-u32"></a>



#### reg-addr-max (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-proto-min-u32"></a>



#### reg-proto-min (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-proto-max-u32"></a>



#### reg-proto-max (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32-7"></a>



#### flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [nat-range-flags](#rst-nftables-definition-nat-range-flags)

- **enum-as-flags**:

  True

<a id="rst-expr-payload-attrs"></a>
<a id="rst-nftables-attribute-set-expr-payload-attrs"></a>



### expr-payload-attrs

<a id="rst-dreg-u32-6"></a>



#### dreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-base-u32"></a>



#### base (`u32`)

- **byte-order**:

  big-endian

<a id="rst-offset-u32"></a>



#### offset (`u32`)

- **byte-order**:

  big-endian

<a id="rst-len-u32-2"></a>



#### len (`u32`)

- **byte-order**:

  big-endian

<a id="rst-sreg-u32-5"></a>



#### sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-csum-type-u32"></a>



#### csum-type (`u32`)

- **byte-order**:

  big-endian

<a id="rst-csum-offset-u32"></a>



#### csum-offset (`u32`)

- **byte-order**:

  big-endian

<a id="rst-csum-flags-u32"></a>



#### csum-flags (`u32`)

- **byte-order**:

  big-endian

<a id="rst-expr-reject-attrs"></a>
<a id="rst-nftables-attribute-set-expr-reject-attrs"></a>



### expr-reject-attrs

<a id="rst-type-u32-2"></a>



#### type (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [reject-types](#rst-nftables-definition-reject-types)

<a id="rst-icmp-code-u8"></a>



#### icmp-code (`u8`)

<a id="rst-expr-target-attrs"></a>
<a id="rst-nftables-attribute-set-expr-target-attrs"></a>



### expr-target-attrs

<a id="rst-name-string-9"></a>



#### name (`string`)

<a id="rst-rev-u32"></a>



#### rev (`u32`)

- **byte-order**:

  big-endian

<a id="rst-info-binary"></a>



#### info (`binary`)

<a id="rst-expr-tproxy-attrs"></a>
<a id="rst-nftables-attribute-set-expr-tproxy-attrs"></a>



### expr-tproxy-attrs

<a id="rst-family-u32-1"></a>



#### family (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-addr-u32"></a>



#### reg-addr (`u32`)

- **byte-order**:

  big-endian

<a id="rst-reg-port-u32"></a>



#### reg-port (`u32`)

- **byte-order**:

  big-endian

<a id="rst-expr-objref-attrs"></a>
<a id="rst-nftables-attribute-set-expr-objref-attrs"></a>



### expr-objref-attrs

<a id="rst-imm-type-u32"></a>



#### imm-type (`u32`)

- **byte-order**:

  big-endian

<a id="rst-imm-name-string"></a>



#### imm-name (`string`)

- **doc**:

  object name

<a id="rst-set-sreg-u32"></a>



#### set-sreg (`u32`)

- **byte-order**:

  big-endian

<a id="rst-set-name-string"></a>



#### set-name (`string`)

- **doc**:

  name of object map

<a id="rst-set-id-u32-2"></a>



#### set-id (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  id of object map

<a id="rst-sub-messages"></a>



## Sub-messages

<a id="rst-expr-ops"></a>
<a id="rst-nftables-sub-message-expr-ops"></a>



### expr-ops

- **bitwise**

  - **attribute-set**:

    [expr-bitwise-attrs](#rst-nftables-attribute-set-expr-bitwise-attrs)

- **cmp**

  - **attribute-set**:

    [expr-cmp-attrs](#rst-nftables-attribute-set-expr-cmp-attrs)

- **counter**

  - **attribute-set**:

    [expr-counter-attrs](#rst-nftables-attribute-set-expr-counter-attrs)

- **ct**

  - **attribute-set**:

    [expr-ct-attrs](#rst-nftables-attribute-set-expr-ct-attrs)

- **fib**

  - **attribute-set**:

    [expr-fib-attrs](#rst-nftables-attribute-set-expr-fib-attrs)

- **flow\_offload**

  - **attribute-set**:

    [expr-flow-offload-attrs](#rst-nftables-attribute-set-expr-flow-offload-attrs)

- **immediate**

  - **attribute-set**:

    [expr-immediate-attrs](#rst-nftables-attribute-set-expr-immediate-attrs)

- **lookup**

  - **attribute-set**:

    [expr-lookup-attrs](#rst-nftables-attribute-set-expr-lookup-attrs)

- **meta**

  - **attribute-set**:

    [expr-meta-attrs](#rst-nftables-attribute-set-expr-meta-attrs)

- **nat**

  - **attribute-set**:

    [expr-nat-attrs](#rst-nftables-attribute-set-expr-nat-attrs)

- **objref**

  - **attribute-set**:

    [expr-objref-attrs](#rst-nftables-attribute-set-expr-objref-attrs)

- **payload**

  - **attribute-set**:

    [expr-payload-attrs](#rst-nftables-attribute-set-expr-payload-attrs)

- **quota**

  - **attribute-set**:

    [quota-attrs](#rst-nftables-attribute-set-quota-attrs)

- **reject**

  - **attribute-set**:

    [expr-reject-attrs](#rst-nftables-attribute-set-expr-reject-attrs)

- **target**

  - **attribute-set**:

    [expr-target-attrs](#rst-nftables-attribute-set-expr-target-attrs)

- **tproxy**

  - **attribute-set**:

    [expr-tproxy-attrs](#rst-nftables-attribute-set-expr-tproxy-attrs)

<a id="rst-obj-data"></a>
<a id="rst-nftables-sub-message-obj-data"></a>



### obj-data

- **counter**

  - **attribute-set**:

    [counter-attrs](#rst-nftables-attribute-set-counter-attrs)

- **quota**

  - **attribute-set**:

    [quota-attrs](#rst-nftables-attribute-set-quota-attrs)

---

# Family nl80211 netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the nl80211 Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-nl80211-netlink-specification"></a>
<a id="rst-netlink-nl80211"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netlink API for 802.11 wireless devices

<a id="rst-operations"></a>



## Operations

<a id="rst-get-wiphy"></a>
<a id="rst-nl80211-operation-get-wiphy"></a>



### get-wiphy



Get information about a wiphy or dump a list of all wiphys. Requests to
dump get-wiphy should unconditionally include the split-wiphy-dump flag
in the request.

- **attribute-set**:

  [nl80211-attrs](#rst-nl80211-attribute-set-nl80211-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`wiphy`, `wdev`, `ifindex`\]

  **reply**

  - **attributes**:

    \[`bands`, `cipher-suites`, `control-port-ethertype`, `ext-capa`, `ext-capa-mask`, `ext-features`, `feature-flags`, `generation`, `ht-capability-mask`, `interface-combinations`, `mac`, `max-csa-counters`, `max-match-sets`, `max-num-akm-suites`, `max-num-pmkids`, `max-num-scan-ssids`, `max-num-sched-scan-plans`, `max-num-sched-scan-ssids`, `max-remain-on-channel-duration`, `max-scan-ie-len`, `max-scan-plan-interval`, `max-scan-plan-iterations`, `max-sched-scan-ie-len`, `offchannel-tx-ok`, `rx-frame-types`, `sar-spec`, `sched-scan-max-reqs`, `software-iftypes`, `support-ap-uapsd`, `supported-commands`, `supported-iftypes`, `tdls-external-setup`, `tdls-support`, `tx-frame-types`, `txq-limit`, `txq-memory-limit`, `txq-quantum`, `txq-stats`, `vht-capability-mask`, `wiphy`, `wiphy-antenna-avail-rx`, `wiphy-antenna-avail-tx`, `wiphy-antenna-rx`, `wiphy-antenna-tx`, `wiphy-bands`, `wiphy-coverage-class`, `wiphy-frag-threshold`, `wiphy-name`, `wiphy-retry-long`, `wiphy-retry-short`, `wiphy-rts-threshold`, `wowlan-triggers-supported`\]

- **dump**:

  **request**

  - **attributes**:

    \[`wiphy`, `wdev`, `ifindex`, `split-wiphy-dump`\]

  **reply**

  - **attributes**:

    \[`bands`, `cipher-suites`, `control-port-ethertype`, `ext-capa`, `ext-capa-mask`, `ext-features`, `feature-flags`, `generation`, `ht-capability-mask`, `interface-combinations`, `mac`, `max-csa-counters`, `max-match-sets`, `max-num-akm-suites`, `max-num-pmkids`, `max-num-scan-ssids`, `max-num-sched-scan-plans`, `max-num-sched-scan-ssids`, `max-remain-on-channel-duration`, `max-scan-ie-len`, `max-scan-plan-interval`, `max-scan-plan-iterations`, `max-sched-scan-ie-len`, `offchannel-tx-ok`, `rx-frame-types`, `sar-spec`, `sched-scan-max-reqs`, `software-iftypes`, `support-ap-uapsd`, `supported-commands`, `supported-iftypes`, `tdls-external-setup`, `tdls-support`, `tx-frame-types`, `txq-limit`, `txq-memory-limit`, `txq-quantum`, `txq-stats`, `vht-capability-mask`, `wiphy`, `wiphy-antenna-avail-rx`, `wiphy-antenna-avail-tx`, `wiphy-antenna-rx`, `wiphy-antenna-tx`, `wiphy-bands`, `wiphy-coverage-class`, `wiphy-frag-threshold`, `wiphy-name`, `wiphy-retry-long`, `wiphy-retry-short`, `wiphy-rts-threshold`, `wowlan-triggers-supported`\]

<a id="rst-get-interface"></a>
<a id="rst-nl80211-operation-get-interface"></a>



### get-interface



Get information about an interface or dump a list of all interfaces

- **attribute-set**:

  [nl80211-attrs](#rst-nl80211-attribute-set-nl80211-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`ifname`\]

  **reply**

  - **attributes**:

    \[`ifname`, `iftype`, `ifindex`, `wiphy`, `wdev`, `mac`, `generation`, `txq-stats`, `4addr`\]

- **dump**:

  **request**

  - **attributes**:

    \[`ifname`\]

  **reply**

  - **attributes**:

    \[`ifname`, `iftype`, `ifindex`, `wiphy`, `wdev`, `mac`, `generation`, `txq-stats`, `4addr`\]

<a id="rst-get-protocol-features"></a>
<a id="rst-nl80211-operation-get-protocol-features"></a>



### get-protocol-features



Get information about supported protocol features

- **attribute-set**:

  [nl80211-attrs](#rst-nl80211-attribute-set-nl80211-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`protocol-features`\]

  **reply**

  - **attributes**:

    \[`protocol-features`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- config


- scan


- regulatory


- mlme


- vendor


- nan


- testmode


<a id="rst-definitions"></a>



## Definitions

<a id="rst-commands"></a>
<a id="rst-nl80211-definition-commands"></a>



### commands

- **type**:

  enum

- **entries**:

  - `unspec`


  - `get-wiphy`


  - `set-wiphy`


  - `new-wiphy`


  - `del-wiphy`


  - `get-interface`


  - `set-interface`


  - `new-interface`


  - `del-interface`


  - `get-key`


  - `set-key`


  - `new-key`


  - `del-key`


  - `get-beacon`


  - `set-beacon`


  - `new-beacon`


  - `del-beacon`


  - `get-station`


  - `set-station`


  - `new-station`


  - `del-station`


  - `get-mpath`


  - `set-mpath`


  - `new-mpath`


  - `del-mpath`


  - `set-bss`


  - `set-reg`


  - `req-set-reg`


  - `get-mesh-config`


  - `set-mesh-config`


  - `set-mgmt-extra-ie`


  - `get-reg`


  - `get-scan`


  - `trigger-scan`


  - `new-scan-results`


  - `scan-aborted`


  - `reg-change`


  - `authenticate`


  - `associate`


  - `deauthenticate`


  - `disassociate`


  - `michael-mic-failure`


  - `reg-beacon-hint`


  - `join-ibss`


  - `leave-ibss`


  - `testmode`


  - `connect`


  - `roam`


  - `disconnect`


  - `set-wiphy-netns`


  - `get-survey`


  - `new-survey-results`


  - `set-pmksa`


  - `del-pmksa`


  - `flush-pmksa`


  - `remain-on-channel`


  - `cancel-remain-on-channel`


  - `set-tx-bitrate-mask`


  - `register-action`


  - `action`


  - `action-tx-status`


  - `set-power-save`


  - `get-power-save`


  - `set-cqm`


  - `notify-cqm`


  - `set-channel`


  - `set-wds-peer`


  - `frame-wait-cancel`


  - `join-mesh`


  - `leave-mesh`


  - `unprot-deauthenticate`


  - `unprot-disassociate`


  - `new-peer-candidate`


  - `get-wowlan`


  - `set-wowlan`


  - `start-sched-scan`


  - `stop-sched-scan`


  - `sched-scan-results`


  - `sched-scan-stopped`


  - `set-rekey-offload`


  - `pmksa-candidate`


  - `tdls-oper`


  - `tdls-mgmt`


  - `unexpected-frame`


  - `probe-client`


  - `register-beacons`


  - `unexpected-4-addr-frame`


  - `set-noack-map`


  - `ch-switch-notify`


  - `start-p2p-device`


  - `stop-p2p-device`


  - `conn-failed`


  - `set-mcast-rate`


  - `set-mac-acl`


  - `radar-detect`


  - `get-protocol-features`


  - `update-ft-ies`


  - `ft-event`


  - `crit-protocol-start`


  - `crit-protocol-stop`


  - `get-coalesce`


  - `set-coalesce`


  - `channel-switch`


  - `vendor`


  - `set-qos-map`


  - `add-tx-ts`


  - `del-tx-ts`


  - `get-mpp`


  - `join-ocb`


  - `leave-ocb`


  - `ch-switch-started-notify`


  - `tdls-channel-switch`


  - `tdls-cancel-channel-switch`


  - `wiphy-reg-change`


  - `abort-scan`


  - `start-nan`


  - `stop-nan`


  - `add-nan-function`


  - `del-nan-function`


  - `change-nan-config`


  - `nan-match`


  - `set-multicast-to-unicast`


  - `update-connect-params`


  - `set-pmk`


  - `del-pmk`


  - `port-authorized`


  - `reload-regdb`


  - `external-auth`


  - `sta-opmode-changed`


  - `control-port-frame`


  - `get-ftm-responder-stats`


  - `peer-measurement-start`


  - `peer-measurement-result`


  - `peer-measurement-complete`


  - `notify-radar`


  - `update-owe-info`


  - `probe-mesh-link`


  - `set-tid-config`


  - `unprot-beacon`


  - `control-port-frame-tx-status`


  - `set-sar-specs`


  - `obss-color-collision`


  - `color-change-request`


  - `color-change-started`


  - `color-change-aborted`


  - `color-change-completed`


  - `set-fils-aad`


  - `assoc-comeback`


  - `add-link`


  - `remove-link`


  - `add-link-sta`


  - `modify-link-sta`


  - `remove-link-sta`


  - `set-hw-timestamp`


  - `links-removed`


  - `set-tid-to-link-mapping`

<a id="rst-feature-flags"></a>
<a id="rst-nl80211-definition-feature-flags"></a>



### feature-flags

- **type**:

  flags

- **entries**:

  - `sk-tx-status`


  - `ht-ibss`


  - `inactivity-timer`


  - `cell-base-reg-hints`


  - `p2p-device-needs-channel`


  - `sae`


  - `low-priority-scan`


  - `scan-flush`


  - `ap-scan`


  - `vif-txpower`


  - `need-obss-scan`


  - `p2p-go-ctwin`


  - `p2p-go-oppps`


  - `reserved`


  - `advertise-chan-limits`


  - `full-ap-client-state`


  - `userspace-mpm`


  - `active-monitor`


  - `ap-mode-chan-width-change`


  - `ds-param-set-ie-in-probes`


  - `wfa-tpc-ie-in-probes`


  - `quiet`


  - `tx-power-insertion`


  - `ackto-estimation`


  - `static-smps`


  - `dynamic-smps`


  - `supports-wmm-admission`


  - `mac-on-create`


  - `tdls-channel-switch`


  - `scan-random-mac-addr`


  - `sched-scan-random-mac-addr`


  - `no-random-mac-addr`

<a id="rst-channel-type"></a>
<a id="rst-nl80211-definition-channel-type"></a>



### channel-type

- **type**:

  enum

- **entries**:

  - `no-ht`


  - `ht20`


  - `ht40minus`


  - `ht40plus`

<a id="rst-sta-flag-update"></a>
<a id="rst-nl80211-definition-sta-flag-update"></a>



### sta-flag-update

- **type**:

  struct

- **members**:

  - **mask (`u32`)**

  - **set (`u32`)**

<a id="rst-protocol-features"></a>
<a id="rst-nl80211-definition-protocol-features"></a>



### protocol-features

- **type**:

  flags

- **entries**:

  - `split-wiphy-dump`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-nl80211-attrs"></a>
<a id="rst-nl80211-attribute-set-nl80211-attrs"></a>



### nl80211-attrs

<a id="rst-wiphy-u32"></a>



#### wiphy (`u32`)

<a id="rst-wiphy-name-string"></a>



#### wiphy-name (`string`)

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

<a id="rst-ifname-string"></a>



#### ifname (`string`)

<a id="rst-iftype-u32"></a>



#### iftype (`u32`)

<a id="rst-mac-binary"></a>



#### mac (`binary`)

- **display-hint**:

  mac

<a id="rst-key-data-binary"></a>



#### key-data (`binary`)

<a id="rst-key-idx-u8"></a>



#### key-idx (`u8`)

<a id="rst-key-cipher-u32"></a>



#### key-cipher (`u32`)

<a id="rst-key-seq-binary"></a>



#### key-seq (`binary`)

<a id="rst-key-default-flag"></a>



#### key-default (`flag`)

<a id="rst-beacon-interval-u32"></a>



#### beacon-interval (`u32`)

<a id="rst-dtim-period-u32"></a>



#### dtim-period (`u32`)

<a id="rst-beacon-head-binary"></a>



#### beacon-head (`binary`)

<a id="rst-beacon-tail-binary"></a>



#### beacon-tail (`binary`)

<a id="rst-sta-aid-u16"></a>



#### sta-aid (`u16`)

<a id="rst-sta-flags-binary"></a>



#### sta-flags (`binary`)

<a id="rst-sta-listen-interval-u16"></a>



#### sta-listen-interval (`u16`)

<a id="rst-sta-supported-rates-binary"></a>



#### sta-supported-rates (`binary`)

<a id="rst-sta-vlan-u32"></a>



#### sta-vlan (`u32`)

<a id="rst-sta-info-binary"></a>



#### sta-info (`binary`)

<a id="rst-wiphy-bands-nest"></a>



#### wiphy-bands (`nest`)

- **nested-attributes**:

  [wiphy-bands](#rst-nl80211-attribute-set-wiphy-bands)

<a id="rst-mntr-flags-binary"></a>



#### mntr-flags (`binary`)

<a id="rst-mesh-id-binary"></a>



#### mesh-id (`binary`)

<a id="rst-sta-plink-action-u8"></a>



#### sta-plink-action (`u8`)

<a id="rst-mpath-next-hop-binary"></a>



#### mpath-next-hop (`binary`)

- **display-hint**:

  mac

<a id="rst-mpath-info-binary"></a>



#### mpath-info (`binary`)

<a id="rst-bss-cts-prot-u8"></a>



#### bss-cts-prot (`u8`)

<a id="rst-bss-short-preamble-u8"></a>



#### bss-short-preamble (`u8`)

<a id="rst-bss-short-slot-time-u8"></a>



#### bss-short-slot-time (`u8`)

<a id="rst-ht-capability-binary"></a>



#### ht-capability (`binary`)

<a id="rst-supported-iftypes-nest"></a>



#### supported-iftypes (`nest`)

- **nested-attributes**:

  [supported-iftypes](#rst-nl80211-attribute-set-supported-iftypes)

<a id="rst-reg-alpha2-binary"></a>



#### reg-alpha2 (`binary`)

<a id="rst-reg-rules-binary"></a>



#### reg-rules (`binary`)

<a id="rst-mesh-config-binary"></a>



#### mesh-config (`binary`)

<a id="rst-bss-basic-rates-binary"></a>



#### bss-basic-rates (`binary`)

<a id="rst-wiphy-txq-params-binary"></a>



#### wiphy-txq-params (`binary`)

<a id="rst-wiphy-freq-u32"></a>



#### wiphy-freq (`u32`)

<a id="rst-wiphy-channel-type-u32"></a>



#### wiphy-channel-type (`u32`)

- **enum**:

  [channel-type](#rst-nl80211-definition-channel-type)

<a id="rst-key-default-mgmt-flag"></a>



#### key-default-mgmt (`flag`)

<a id="rst-mgmt-subtype-u8"></a>



#### mgmt-subtype (`u8`)

<a id="rst-ie-binary"></a>



#### ie (`binary`)

<a id="rst-max-num-scan-ssids-u8"></a>



#### max-num-scan-ssids (`u8`)

<a id="rst-scan-frequencies-binary"></a>



#### scan-frequencies (`binary`)

<a id="rst-scan-ssids-binary"></a>



#### scan-ssids (`binary`)

<a id="rst-generation-u32"></a>



#### generation (`u32`)

<a id="rst-bss-binary"></a>



#### bss (`binary`)

<a id="rst-reg-initiator-u8"></a>



#### reg-initiator (`u8`)

<a id="rst-reg-type-u8"></a>



#### reg-type (`u8`)

<a id="rst-supported-commands-indexed-array"></a>



#### supported-commands (`indexed-array`)

- **sub-type**:

  u32

- **enum**:

  [commands](#rst-nl80211-definition-commands)

<a id="rst-frame-binary"></a>



#### frame (`binary`)

<a id="rst-ssid-binary"></a>



#### ssid (`binary`)

<a id="rst-auth-type-u32"></a>



#### auth-type (`u32`)

<a id="rst-reason-code-u16"></a>



#### reason-code (`u16`)

<a id="rst-key-type-u32"></a>



#### key-type (`u32`)

<a id="rst-max-scan-ie-len-u16"></a>



#### max-scan-ie-len (`u16`)

<a id="rst-cipher-suites-binary"></a>



#### cipher-suites (`binary`)

- **sub-type**:

  u32

- **display-hint**:

  hex

<a id="rst-freq-before-binary"></a>



#### freq-before (`binary`)

<a id="rst-freq-after-binary"></a>



#### freq-after (`binary`)

<a id="rst-freq-fixed-flag"></a>



#### freq-fixed (`flag`)

<a id="rst-wiphy-retry-short-u8"></a>



#### wiphy-retry-short (`u8`)

<a id="rst-wiphy-retry-long-u8"></a>



#### wiphy-retry-long (`u8`)

<a id="rst-wiphy-frag-threshold-u32"></a>



#### wiphy-frag-threshold (`u32`)

<a id="rst-wiphy-rts-threshold-u32"></a>



#### wiphy-rts-threshold (`u32`)

<a id="rst-timed-out-flag"></a>



#### timed-out (`flag`)

<a id="rst-use-mfp-u32"></a>



#### use-mfp (`u32`)

<a id="rst-sta-flags2-binary"></a>



#### sta-flags2 (`binary`)

- **struct**:

  [sta-flag-update](#rst-nl80211-definition-sta-flag-update)

<a id="rst-control-port-flag"></a>



#### control-port (`flag`)

<a id="rst-testdata-binary"></a>



#### testdata (`binary`)

<a id="rst-privacy-flag"></a>



#### privacy (`flag`)

<a id="rst-disconnected-by-ap-flag"></a>



#### disconnected-by-ap (`flag`)

<a id="rst-status-code-u16"></a>



#### status-code (`u16`)

<a id="rst-cipher-suites-pairwise-binary"></a>



#### cipher-suites-pairwise (`binary`)

<a id="rst-cipher-suite-group-u32"></a>



#### cipher-suite-group (`u32`)

<a id="rst-wpa-versions-u32"></a>



#### wpa-versions (`u32`)

<a id="rst-akm-suites-binary"></a>



#### akm-suites (`binary`)

<a id="rst-req-ie-binary"></a>



#### req-ie (`binary`)

<a id="rst-resp-ie-binary"></a>



#### resp-ie (`binary`)

<a id="rst-prev-bssid-binary"></a>



#### prev-bssid (`binary`)

<a id="rst-key-binary"></a>



#### key (`binary`)

<a id="rst-keys-binary"></a>



#### keys (`binary`)

<a id="rst-pid-u32"></a>



#### pid (`u32`)

<a id="rst-addr-u8"></a>



#### 4addr (`u8`)

<a id="rst-survey-info-binary"></a>



#### survey-info (`binary`)

<a id="rst-pmkid-binary"></a>



#### pmkid (`binary`)

<a id="rst-max-num-pmkids-u8"></a>



#### max-num-pmkids (`u8`)

<a id="rst-duration-u32"></a>



#### duration (`u32`)

<a id="rst-cookie-u64"></a>



#### cookie (`u64`)

<a id="rst-wiphy-coverage-class-u8"></a>



#### wiphy-coverage-class (`u8`)

<a id="rst-tx-rates-binary"></a>



#### tx-rates (`binary`)

<a id="rst-frame-match-binary"></a>



#### frame-match (`binary`)

<a id="rst-ack-flag"></a>



#### ack (`flag`)

<a id="rst-ps-state-u32"></a>



#### ps-state (`u32`)

<a id="rst-cqm-binary"></a>



#### cqm (`binary`)

<a id="rst-local-state-change-flag"></a>



#### local-state-change (`flag`)

<a id="rst-ap-isolate-u8"></a>



#### ap-isolate (`u8`)

<a id="rst-wiphy-tx-power-setting-u32"></a>



#### wiphy-tx-power-setting (`u32`)

<a id="rst-wiphy-tx-power-level-u32"></a>



#### wiphy-tx-power-level (`u32`)

<a id="rst-tx-frame-types-nest"></a>



#### tx-frame-types (`nest`)

- **nested-attributes**:

  [iftype-attrs](#rst-nl80211-attribute-set-iftype-attrs)

<a id="rst-rx-frame-types-nest"></a>



#### rx-frame-types (`nest`)

- **nested-attributes**:

  [iftype-attrs](#rst-nl80211-attribute-set-iftype-attrs)

<a id="rst-frame-type-u16"></a>



#### frame-type (`u16`)

<a id="rst-control-port-ethertype-flag"></a>



#### control-port-ethertype (`flag`)

<a id="rst-control-port-no-encrypt-flag"></a>



#### control-port-no-encrypt (`flag`)

<a id="rst-support-ibss-rsn-flag"></a>



#### support-ibss-rsn (`flag`)

<a id="rst-wiphy-antenna-tx-u32"></a>



#### wiphy-antenna-tx (`u32`)

<a id="rst-wiphy-antenna-rx-u32"></a>



#### wiphy-antenna-rx (`u32`)

<a id="rst-mcast-rate-u32"></a>



#### mcast-rate (`u32`)

<a id="rst-offchannel-tx-ok-flag"></a>



#### offchannel-tx-ok (`flag`)

<a id="rst-bss-ht-opmode-u16"></a>



#### bss-ht-opmode (`u16`)

<a id="rst-key-default-types-binary"></a>



#### key-default-types (`binary`)

<a id="rst-max-remain-on-channel-duration-u32"></a>



#### max-remain-on-channel-duration (`u32`)

<a id="rst-mesh-setup-binary"></a>



#### mesh-setup (`binary`)

<a id="rst-wiphy-antenna-avail-tx-u32"></a>



#### wiphy-antenna-avail-tx (`u32`)

<a id="rst-wiphy-antenna-avail-rx-u32"></a>



#### wiphy-antenna-avail-rx (`u32`)

<a id="rst-support-mesh-auth-flag"></a>



#### support-mesh-auth (`flag`)

<a id="rst-sta-plink-state-u8"></a>



#### sta-plink-state (`u8`)

<a id="rst-wowlan-triggers-binary"></a>



#### wowlan-triggers (`binary`)

<a id="rst-wowlan-triggers-supported-nest"></a>



#### wowlan-triggers-supported (`nest`)

- **nested-attributes**:

  [wowlan-triggers-attrs](#rst-nl80211-attribute-set-wowlan-triggers-attrs)

<a id="rst-sched-scan-interval-u32"></a>



#### sched-scan-interval (`u32`)

<a id="rst-interface-combinations-indexed-array"></a>



#### interface-combinations (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [if-combination-attributes](#rst-nl80211-attribute-set-if-combination-attributes)

<a id="rst-software-iftypes-nest"></a>



#### software-iftypes (`nest`)

- **nested-attributes**:

  [supported-iftypes](#rst-nl80211-attribute-set-supported-iftypes)

<a id="rst-rekey-data-binary"></a>



#### rekey-data (`binary`)

<a id="rst-max-num-sched-scan-ssids-u8"></a>



#### max-num-sched-scan-ssids (`u8`)

<a id="rst-max-sched-scan-ie-len-u16"></a>



#### max-sched-scan-ie-len (`u16`)

<a id="rst-scan-supp-rates-binary"></a>



#### scan-supp-rates (`binary`)

<a id="rst-hidden-ssid-u32"></a>



#### hidden-ssid (`u32`)

<a id="rst-ie-probe-resp-binary"></a>



#### ie-probe-resp (`binary`)

<a id="rst-ie-assoc-resp-binary"></a>



#### ie-assoc-resp (`binary`)

<a id="rst-sta-wme-binary"></a>



#### sta-wme (`binary`)

<a id="rst-support-ap-uapsd-flag"></a>



#### support-ap-uapsd (`flag`)

<a id="rst-roam-support-flag"></a>



#### roam-support (`flag`)

<a id="rst-sched-scan-match-binary"></a>



#### sched-scan-match (`binary`)

<a id="rst-max-match-sets-u8"></a>



#### max-match-sets (`u8`)

<a id="rst-pmksa-candidate-binary"></a>



#### pmksa-candidate (`binary`)

<a id="rst-tx-no-cck-rate-flag"></a>



#### tx-no-cck-rate (`flag`)

<a id="rst-tdls-action-u8"></a>



#### tdls-action (`u8`)

<a id="rst-tdls-dialog-token-u8"></a>



#### tdls-dialog-token (`u8`)

<a id="rst-tdls-operation-u8"></a>



#### tdls-operation (`u8`)

<a id="rst-tdls-support-flag"></a>



#### tdls-support (`flag`)

<a id="rst-tdls-external-setup-flag"></a>



#### tdls-external-setup (`flag`)

<a id="rst-device-ap-sme-u32"></a>



#### device-ap-sme (`u32`)

<a id="rst-dont-wait-for-ack-flag"></a>



#### dont-wait-for-ack (`flag`)

<a id="rst-feature-flags-u32"></a>



#### feature-flags (`u32`)

- **enum**:

  [feature-flags](#rst-nl80211-definition-feature-flags)

- **enum-as-flags**:

  True

<a id="rst-probe-resp-offload-u32"></a>



#### probe-resp-offload (`u32`)

<a id="rst-probe-resp-binary"></a>



#### probe-resp (`binary`)

<a id="rst-dfs-region-u8"></a>



#### dfs-region (`u8`)

<a id="rst-disable-ht-flag"></a>



#### disable-ht (`flag`)

<a id="rst-ht-capability-mask-binary"></a>



#### ht-capability-mask (`binary`)

<a id="rst-noack-map-u16"></a>



#### noack-map (`u16`)

<a id="rst-inactivity-timeout-u16"></a>



#### inactivity-timeout (`u16`)

<a id="rst-rx-signal-dbm-u32"></a>



#### rx-signal-dbm (`u32`)

<a id="rst-bg-scan-period-u16"></a>



#### bg-scan-period (`u16`)

<a id="rst-wdev-u64"></a>



#### wdev (`u64`)

<a id="rst-user-reg-hint-type-u32"></a>



#### user-reg-hint-type (`u32`)

<a id="rst-conn-failed-reason-u32"></a>



#### conn-failed-reason (`u32`)

<a id="rst-auth-data-binary"></a>



#### auth-data (`binary`)

<a id="rst-vht-capability-binary"></a>



#### vht-capability (`binary`)

<a id="rst-scan-flags-u32"></a>



#### scan-flags (`u32`)

<a id="rst-channel-width-u32"></a>



#### channel-width (`u32`)

<a id="rst-center-freq1-u32"></a>



#### center-freq1 (`u32`)

<a id="rst-center-freq2-u32"></a>



#### center-freq2 (`u32`)

<a id="rst-p2p-ctwindow-u8"></a>



#### p2p-ctwindow (`u8`)

<a id="rst-p2p-oppps-u8"></a>



#### p2p-oppps (`u8`)

<a id="rst-local-mesh-power-mode-u32"></a>



#### local-mesh-power-mode (`u32`)

<a id="rst-acl-policy-u32"></a>



#### acl-policy (`u32`)

<a id="rst-mac-addrs-binary"></a>



#### mac-addrs (`binary`)

<a id="rst-mac-acl-max-u32"></a>



#### mac-acl-max (`u32`)

<a id="rst-radar-event-u32"></a>



#### radar-event (`u32`)

<a id="rst-ext-capa-binary"></a>



#### ext-capa (`binary`)

<a id="rst-ext-capa-mask-binary"></a>



#### ext-capa-mask (`binary`)

<a id="rst-sta-capability-u16"></a>



#### sta-capability (`u16`)

<a id="rst-sta-ext-capability-binary"></a>



#### sta-ext-capability (`binary`)

<a id="rst-protocol-features-u32"></a>



#### protocol-features (`u32`)

- **enum**:

  [protocol-features](#rst-nl80211-definition-protocol-features)

<a id="rst-split-wiphy-dump-flag"></a>



#### split-wiphy-dump (`flag`)

<a id="rst-disable-vht-flag"></a>



#### disable-vht (`flag`)

<a id="rst-vht-capability-mask-binary"></a>



#### vht-capability-mask (`binary`)

<a id="rst-mdid-u16"></a>



#### mdid (`u16`)

<a id="rst-ie-ric-binary"></a>



#### ie-ric (`binary`)

<a id="rst-crit-prot-id-u16"></a>



#### crit-prot-id (`u16`)

<a id="rst-max-crit-prot-duration-u16"></a>



#### max-crit-prot-duration (`u16`)

<a id="rst-peer-aid-u16"></a>



#### peer-aid (`u16`)

<a id="rst-coalesce-rule-binary"></a>



#### coalesce-rule (`binary`)

<a id="rst-ch-switch-count-u32"></a>



#### ch-switch-count (`u32`)

<a id="rst-ch-switch-block-tx-flag"></a>



#### ch-switch-block-tx (`flag`)

<a id="rst-csa-ies-binary"></a>



#### csa-ies (`binary`)

<a id="rst-cntdwn-offs-beacon-binary"></a>



#### cntdwn-offs-beacon (`binary`)

<a id="rst-cntdwn-offs-presp-binary"></a>



#### cntdwn-offs-presp (`binary`)

<a id="rst-rxmgmt-flags-binary"></a>



#### rxmgmt-flags (`binary`)

<a id="rst-sta-supported-channels-binary"></a>



#### sta-supported-channels (`binary`)

<a id="rst-sta-supported-oper-classes-binary"></a>



#### sta-supported-oper-classes (`binary`)

<a id="rst-handle-dfs-flag"></a>



#### handle-dfs (`flag`)

<a id="rst-support-5-mhz-flag"></a>



#### support-5-mhz (`flag`)

<a id="rst-support-10-mhz-flag"></a>



#### support-10-mhz (`flag`)

<a id="rst-opmode-notif-u8"></a>



#### opmode-notif (`u8`)

<a id="rst-vendor-id-u32"></a>



#### vendor-id (`u32`)

<a id="rst-vendor-subcmd-u32"></a>



#### vendor-subcmd (`u32`)

<a id="rst-vendor-data-binary"></a>



#### vendor-data (`binary`)

<a id="rst-vendor-events-binary"></a>



#### vendor-events (`binary`)

<a id="rst-qos-map-binary"></a>



#### qos-map (`binary`)

<a id="rst-mac-hint-binary"></a>



#### mac-hint (`binary`)

- **display-hint**:

  mac

<a id="rst-wiphy-freq-hint-u32"></a>



#### wiphy-freq-hint (`u32`)

<a id="rst-max-ap-assoc-sta-u32"></a>



#### max-ap-assoc-sta (`u32`)

<a id="rst-tdls-peer-capability-u32"></a>



#### tdls-peer-capability (`u32`)

<a id="rst-socket-owner-flag"></a>



#### socket-owner (`flag`)

<a id="rst-csa-c-offsets-tx-binary"></a>



#### csa-c-offsets-tx (`binary`)

<a id="rst-max-csa-counters-u8"></a>



#### max-csa-counters (`u8`)

<a id="rst-tdls-initiator-flag"></a>



#### tdls-initiator (`flag`)

<a id="rst-use-rrm-flag"></a>



#### use-rrm (`flag`)

<a id="rst-wiphy-dyn-ack-flag"></a>



#### wiphy-dyn-ack (`flag`)

<a id="rst-tsid-u8"></a>



#### tsid (`u8`)

<a id="rst-user-prio-u8"></a>



#### user-prio (`u8`)

<a id="rst-admitted-time-u16"></a>



#### admitted-time (`u16`)

<a id="rst-smps-mode-u8"></a>



#### smps-mode (`u8`)

<a id="rst-oper-class-u8"></a>



#### oper-class (`u8`)

<a id="rst-mac-mask-binary"></a>



#### mac-mask (`binary`)

- **display-hint**:

  mac

<a id="rst-wiphy-self-managed-reg-flag"></a>



#### wiphy-self-managed-reg (`flag`)

<a id="rst-ext-features-binary"></a>



#### ext-features (`binary`)

<a id="rst-survey-radio-stats-binary"></a>



#### survey-radio-stats (`binary`)

<a id="rst-netns-fd-u32"></a>



#### netns-fd (`u32`)

<a id="rst-sched-scan-delay-u32"></a>



#### sched-scan-delay (`u32`)

<a id="rst-reg-indoor-flag"></a>



#### reg-indoor (`flag`)

<a id="rst-max-num-sched-scan-plans-u32"></a>



#### max-num-sched-scan-plans (`u32`)

<a id="rst-max-scan-plan-interval-u32"></a>



#### max-scan-plan-interval (`u32`)

<a id="rst-max-scan-plan-iterations-u32"></a>



#### max-scan-plan-iterations (`u32`)

<a id="rst-sched-scan-plans-binary"></a>



#### sched-scan-plans (`binary`)

<a id="rst-pbss-flag"></a>



#### pbss (`flag`)

<a id="rst-bss-select-binary"></a>



#### bss-select (`binary`)

<a id="rst-sta-support-p2p-ps-u8"></a>



#### sta-support-p2p-ps (`u8`)

<a id="rst-pad-binary"></a>



#### pad (`binary`)

<a id="rst-iftype-ext-capa-binary"></a>



#### iftype-ext-capa (`binary`)

<a id="rst-mu-mimo-group-data-binary"></a>



#### mu-mimo-group-data (`binary`)

<a id="rst-mu-mimo-follow-mac-addr-binary"></a>



#### mu-mimo-follow-mac-addr (`binary`)

- **display-hint**:

  mac

<a id="rst-scan-start-time-tsf-u64"></a>



#### scan-start-time-tsf (`u64`)

<a id="rst-scan-start-time-tsf-bssid-binary"></a>



#### scan-start-time-tsf-bssid (`binary`)

<a id="rst-measurement-duration-u16"></a>



#### measurement-duration (`u16`)

<a id="rst-measurement-duration-mandatory-flag"></a>



#### measurement-duration-mandatory (`flag`)

<a id="rst-mesh-peer-aid-u16"></a>



#### mesh-peer-aid (`u16`)

<a id="rst-nan-master-pref-u8"></a>



#### nan-master-pref (`u8`)

<a id="rst-bands-u32"></a>



#### bands (`u32`)

<a id="rst-nan-func-binary"></a>



#### nan-func (`binary`)

<a id="rst-nan-match-binary"></a>



#### nan-match (`binary`)

<a id="rst-fils-kek-binary"></a>



#### fils-kek (`binary`)

<a id="rst-fils-nonces-binary"></a>



#### fils-nonces (`binary`)

<a id="rst-multicast-to-unicast-enabled-flag"></a>



#### multicast-to-unicast-enabled (`flag`)

<a id="rst-bssid-binary"></a>



#### bssid (`binary`)

- **display-hint**:

  mac

<a id="rst-sched-scan-relative-rssi-s8"></a>



#### sched-scan-relative-rssi (`s8`)

<a id="rst-sched-scan-rssi-adjust-binary"></a>



#### sched-scan-rssi-adjust (`binary`)

<a id="rst-timeout-reason-u32"></a>



#### timeout-reason (`u32`)

<a id="rst-fils-erp-username-binary"></a>



#### fils-erp-username (`binary`)

<a id="rst-fils-erp-realm-binary"></a>



#### fils-erp-realm (`binary`)

<a id="rst-fils-erp-next-seq-num-u16"></a>



#### fils-erp-next-seq-num (`u16`)

<a id="rst-fils-erp-rrk-binary"></a>



#### fils-erp-rrk (`binary`)

<a id="rst-fils-cache-id-binary"></a>



#### fils-cache-id (`binary`)

<a id="rst-pmk-binary"></a>



#### pmk (`binary`)

<a id="rst-sched-scan-multi-flag"></a>



#### sched-scan-multi (`flag`)

<a id="rst-sched-scan-max-reqs-u32"></a>



#### sched-scan-max-reqs (`u32`)

<a id="rst-want-1x-4way-hs-flag"></a>



#### want-1x-4way-hs (`flag`)

<a id="rst-pmkr0-name-binary"></a>



#### pmkr0-name (`binary`)

<a id="rst-port-authorized-binary"></a>



#### port-authorized (`binary`)

<a id="rst-external-auth-action-u32"></a>



#### external-auth-action (`u32`)

<a id="rst-external-auth-support-flag"></a>



#### external-auth-support (`flag`)

<a id="rst-nss-u8"></a>



#### nss (`u8`)

<a id="rst-ack-signal-s32"></a>



#### ack-signal (`s32`)

<a id="rst-control-port-over-nl80211-flag"></a>



#### control-port-over-nl80211 (`flag`)

<a id="rst-txq-stats-nest"></a>



#### txq-stats (`nest`)

- **nested-attributes**:

  [txq-stats-attrs](#rst-nl80211-attribute-set-txq-stats-attrs)

<a id="rst-txq-limit-u32"></a>



#### txq-limit (`u32`)

<a id="rst-txq-memory-limit-u32"></a>



#### txq-memory-limit (`u32`)

<a id="rst-txq-quantum-u32"></a>



#### txq-quantum (`u32`)

<a id="rst-he-capability-binary"></a>



#### he-capability (`binary`)

<a id="rst-ftm-responder-binary"></a>



#### ftm-responder (`binary`)

<a id="rst-ftm-responder-stats-binary"></a>



#### ftm-responder-stats (`binary`)

<a id="rst-timeout-u32"></a>



#### timeout (`u32`)

<a id="rst-peer-measurements-binary"></a>



#### peer-measurements (`binary`)

<a id="rst-airtime-weight-u16"></a>



#### airtime-weight (`u16`)

<a id="rst-sta-tx-power-setting-u8"></a>



#### sta-tx-power-setting (`u8`)

<a id="rst-sta-tx-power-s16"></a>



#### sta-tx-power (`s16`)

<a id="rst-sae-password-binary"></a>



#### sae-password (`binary`)

<a id="rst-twt-responder-flag"></a>



#### twt-responder (`flag`)

<a id="rst-he-obss-pd-binary"></a>



#### he-obss-pd (`binary`)

<a id="rst-wiphy-edmg-channels-u8"></a>



#### wiphy-edmg-channels (`u8`)

<a id="rst-wiphy-edmg-bw-config-u8"></a>



#### wiphy-edmg-bw-config (`u8`)

<a id="rst-vlan-id-u16"></a>



#### vlan-id (`u16`)

<a id="rst-he-bss-color-binary"></a>



#### he-bss-color (`binary`)

<a id="rst-iftype-akm-suites-binary"></a>



#### iftype-akm-suites (`binary`)

<a id="rst-tid-config-binary"></a>



#### tid-config (`binary`)

<a id="rst-control-port-no-preauth-flag"></a>



#### control-port-no-preauth (`flag`)

<a id="rst-pmk-lifetime-u32"></a>



#### pmk-lifetime (`u32`)

<a id="rst-pmk-reauth-threshold-u8"></a>



#### pmk-reauth-threshold (`u8`)

<a id="rst-receive-multicast-flag"></a>



#### receive-multicast (`flag`)

<a id="rst-wiphy-freq-offset-u32"></a>



#### wiphy-freq-offset (`u32`)

<a id="rst-center-freq1-offset-u32"></a>



#### center-freq1-offset (`u32`)

<a id="rst-scan-freq-khz-binary"></a>



#### scan-freq-khz (`binary`)

<a id="rst-he-6ghz-capability-binary"></a>



#### he-6ghz-capability (`binary`)

<a id="rst-fils-discovery-binary"></a>



#### fils-discovery (`binary`)

<a id="rst-unsol-bcast-probe-resp-binary"></a>



#### unsol-bcast-probe-resp (`binary`)

<a id="rst-s1g-capability-binary"></a>



#### s1g-capability (`binary`)

<a id="rst-s1g-capability-mask-binary"></a>



#### s1g-capability-mask (`binary`)

<a id="rst-sae-pwe-u8"></a>



#### sae-pwe (`u8`)

<a id="rst-reconnect-requested-binary"></a>



#### reconnect-requested (`binary`)

<a id="rst-sar-spec-nest"></a>



#### sar-spec (`nest`)

- **nested-attributes**:

  [sar-attributes](#rst-nl80211-attribute-set-sar-attributes)

<a id="rst-disable-he-flag"></a>



#### disable-he (`flag`)

<a id="rst-obss-color-bitmap-u64"></a>



#### obss-color-bitmap (`u64`)

<a id="rst-color-change-count-u8"></a>



#### color-change-count (`u8`)

<a id="rst-color-change-color-u8"></a>



#### color-change-color (`u8`)

<a id="rst-color-change-elems-binary"></a>



#### color-change-elems (`binary`)

<a id="rst-mbssid-config-binary"></a>



#### mbssid-config (`binary`)

<a id="rst-mbssid-elems-binary"></a>



#### mbssid-elems (`binary`)

<a id="rst-radar-background-flag"></a>



#### radar-background (`flag`)

<a id="rst-ap-settings-flags-u32"></a>



#### ap-settings-flags (`u32`)

<a id="rst-eht-capability-binary"></a>



#### eht-capability (`binary`)

<a id="rst-disable-eht-flag"></a>



#### disable-eht (`flag`)

<a id="rst-mlo-links-binary"></a>



#### mlo-links (`binary`)

<a id="rst-mlo-link-id-u8"></a>



#### mlo-link-id (`u8`)

<a id="rst-mld-addr-binary"></a>



#### mld-addr (`binary`)

- **display-hint**:

  mac

<a id="rst-mlo-support-flag"></a>



#### mlo-support (`flag`)

<a id="rst-max-num-akm-suites-binary"></a>



#### max-num-akm-suites (`binary`)

<a id="rst-eml-capability-u16"></a>



#### eml-capability (`u16`)

<a id="rst-mld-capa-and-ops-u16"></a>



#### mld-capa-and-ops (`u16`)

<a id="rst-tx-hw-timestamp-u64"></a>



#### tx-hw-timestamp (`u64`)

<a id="rst-rx-hw-timestamp-u64"></a>



#### rx-hw-timestamp (`u64`)

<a id="rst-td-bitmap-binary"></a>



#### td-bitmap (`binary`)

<a id="rst-punct-bitmap-u32"></a>



#### punct-bitmap (`u32`)

<a id="rst-max-hw-timestamp-peers-u16"></a>



#### max-hw-timestamp-peers (`u16`)

<a id="rst-hw-timestamp-enabled-flag"></a>



#### hw-timestamp-enabled (`flag`)

<a id="rst-ema-rnr-elems-binary"></a>



#### ema-rnr-elems (`binary`)

<a id="rst-mlo-link-disabled-flag"></a>



#### mlo-link-disabled (`flag`)

<a id="rst-bss-dump-include-use-data-flag"></a>



#### bss-dump-include-use-data (`flag`)

<a id="rst-mlo-ttlm-dlink-u16"></a>



#### mlo-ttlm-dlink (`u16`)

<a id="rst-mlo-ttlm-ulink-u16"></a>



#### mlo-ttlm-ulink (`u16`)

<a id="rst-assoc-spp-amsdu-flag"></a>



#### assoc-spp-amsdu (`flag`)

<a id="rst-wiphy-radios-binary"></a>



#### wiphy-radios (`binary`)

<a id="rst-wiphy-interface-combinations-binary"></a>



#### wiphy-interface-combinations (`binary`)

<a id="rst-vif-radio-mask-u32"></a>



#### vif-radio-mask (`u32`)

<a id="rst-frame-type-attrs"></a>
<a id="rst-nl80211-attribute-set-frame-type-attrs"></a>



### frame-type-attrs

<a id="rst-frame-type"></a>



#### frame-type

<a id="rst-wiphy-bands"></a>
<a id="rst-nl80211-attribute-set-wiphy-bands"></a>



### wiphy-bands

<a id="rst-ghz-nest"></a>



#### 2ghz (`nest`)

- **doc**:

  2.4 GHz ISM band

- **value**:

  0

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-ghz-nest-1"></a>



#### 5ghz (`nest`)

- **doc**:

  around 5 GHz band (4.9 - 5.7 GHz)

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-ghz-nest-2"></a>



#### 60ghz (`nest`)

- **doc**:

  around 60 GHz band (58.32 - 69.12 GHz)

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-ghz-nest-3"></a>



#### 6ghz (`nest`)

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-s1ghz-nest"></a>



#### s1ghz (`nest`)

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-lc-nest"></a>



#### lc (`nest`)

- **nested-attributes**:

  [band-attrs](#rst-nl80211-attribute-set-band-attrs)

<a id="rst-band-attrs"></a>
<a id="rst-nl80211-attribute-set-band-attrs"></a>



### band-attrs

<a id="rst-freqs-indexed-array"></a>



#### freqs (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [frequency-attrs](#rst-nl80211-attribute-set-frequency-attrs)

<a id="rst-rates-indexed-array"></a>



#### rates (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [bitrate-attrs](#rst-nl80211-attribute-set-bitrate-attrs)

<a id="rst-ht-mcs-set-binary"></a>



#### ht-mcs-set (`binary`)

<a id="rst-ht-capa-u16"></a>



#### ht-capa (`u16`)

<a id="rst-ht-ampdu-factor-u8"></a>



#### ht-ampdu-factor (`u8`)

<a id="rst-ht-ampdu-density-u8"></a>



#### ht-ampdu-density (`u8`)

<a id="rst-vht-mcs-set-binary"></a>



#### vht-mcs-set (`binary`)

<a id="rst-vht-capa-u32"></a>



#### vht-capa (`u32`)

<a id="rst-iftype-data-indexed-array"></a>



#### iftype-data (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [iftype-data-attrs](#rst-nl80211-attribute-set-iftype-data-attrs)

<a id="rst-edmg-channels-binary"></a>



#### edmg-channels (`binary`)

<a id="rst-edmg-bw-config-binary"></a>



#### edmg-bw-config (`binary`)

<a id="rst-s1g-mcs-nss-set-binary"></a>



#### s1g-mcs-nss-set (`binary`)

<a id="rst-s1g-capa-binary"></a>



#### s1g-capa (`binary`)

<a id="rst-bitrate-attrs"></a>
<a id="rst-nl80211-attribute-set-bitrate-attrs"></a>



### bitrate-attrs

<a id="rst-rate-u32"></a>



#### rate (`u32`)

<a id="rst-ghz-shortpreamble-flag"></a>



#### 2ghz-shortpreamble (`flag`)

<a id="rst-frequency-attrs"></a>
<a id="rst-nl80211-attribute-set-frequency-attrs"></a>



### frequency-attrs

<a id="rst-freq-u32"></a>



#### freq (`u32`)

<a id="rst-disabled-flag"></a>



#### disabled (`flag`)

<a id="rst-no-ir-flag"></a>



#### no-ir (`flag`)

<a id="rst-no-ibss-flag"></a>



#### no-ibss (`flag`)

- **name-prefix**:

  \_\_nl80211-frequency-attr-

<a id="rst-radar-flag"></a>



#### radar (`flag`)

<a id="rst-max-tx-power-u32"></a>



#### max-tx-power (`u32`)

<a id="rst-dfs-state-u32"></a>



#### dfs-state (`u32`)

<a id="rst-dfs-time-binary"></a>



#### dfs-time (`binary`)

<a id="rst-no-ht40-minus-binary"></a>



#### no-ht40-minus (`binary`)

<a id="rst-no-ht40-plus-binary"></a>



#### no-ht40-plus (`binary`)

<a id="rst-no-80mhz-binary"></a>



#### no-80mhz (`binary`)

<a id="rst-no-160mhz-binary"></a>



#### no-160mhz (`binary`)

<a id="rst-dfs-cac-time-binary"></a>



#### dfs-cac-time (`binary`)

<a id="rst-indoor-only-binary"></a>



#### indoor-only (`binary`)

<a id="rst-ir-concurrent-binary"></a>



#### ir-concurrent (`binary`)

<a id="rst-no-20mhz-binary"></a>



#### no-20mhz (`binary`)

<a id="rst-no-10mhz-binary"></a>



#### no-10mhz (`binary`)

<a id="rst-wmm-indexed-array"></a>



#### wmm (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [wmm-attrs](#rst-nl80211-attribute-set-wmm-attrs)

<a id="rst-no-he-binary"></a>



#### no-he (`binary`)

<a id="rst-offset-u32"></a>



#### offset (`u32`)

<a id="rst-mhz-binary"></a>



#### 1mhz (`binary`)

<a id="rst-mhz-binary-1"></a>



#### 2mhz (`binary`)

<a id="rst-mhz-binary-2"></a>



#### 4mhz (`binary`)

<a id="rst-mhz-binary-3"></a>



#### 8mhz (`binary`)

<a id="rst-mhz-binary-4"></a>



#### 16mhz (`binary`)

<a id="rst-no-320mhz-binary"></a>



#### no-320mhz (`binary`)

<a id="rst-no-eht-binary"></a>



#### no-eht (`binary`)

<a id="rst-psd-binary"></a>



#### psd (`binary`)

<a id="rst-dfs-concurrent-binary"></a>



#### dfs-concurrent (`binary`)

<a id="rst-no-6ghz-vlp-client-binary"></a>



#### no-6ghz-vlp-client (`binary`)

<a id="rst-no-6ghz-afc-client-binary"></a>



#### no-6ghz-afc-client (`binary`)

<a id="rst-can-monitor-binary"></a>



#### can-monitor (`binary`)

<a id="rst-allow-6ghz-vlp-ap-binary"></a>



#### allow-6ghz-vlp-ap (`binary`)

<a id="rst-if-combination-attributes"></a>
<a id="rst-nl80211-attribute-set-if-combination-attributes"></a>



### if-combination-attributes

<a id="rst-limits-indexed-array"></a>



#### limits (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [iface-limit-attributes](#rst-nl80211-attribute-set-iface-limit-attributes)

<a id="rst-maxnum-u32"></a>



#### maxnum (`u32`)

<a id="rst-sta-ap-bi-match-flag"></a>



#### sta-ap-bi-match (`flag`)

<a id="rst-num-channels-u32"></a>



#### num-channels (`u32`)

<a id="rst-radar-detect-widths-u32"></a>



#### radar-detect-widths (`u32`)

<a id="rst-radar-detect-regions-u32"></a>



#### radar-detect-regions (`u32`)

<a id="rst-bi-min-gcd-u32"></a>



#### bi-min-gcd (`u32`)

<a id="rst-iface-limit-attributes"></a>
<a id="rst-nl80211-attribute-set-iface-limit-attributes"></a>



### iface-limit-attributes

<a id="rst-max-u32"></a>



#### max (`u32`)

<a id="rst-types-nest"></a>



#### types (`nest`)

- **nested-attributes**:

  [supported-iftypes](#rst-nl80211-attribute-set-supported-iftypes)

<a id="rst-iftype-data-attrs"></a>
<a id="rst-nl80211-attribute-set-iftype-data-attrs"></a>



### iftype-data-attrs

<a id="rst-iftypes-binary"></a>



#### iftypes (`binary`)

<a id="rst-he-cap-mac-binary"></a>



#### he-cap-mac (`binary`)

<a id="rst-he-cap-phy-binary"></a>



#### he-cap-phy (`binary`)

<a id="rst-he-cap-mcs-set-binary"></a>



#### he-cap-mcs-set (`binary`)

<a id="rst-he-cap-ppe-binary"></a>



#### he-cap-ppe (`binary`)

<a id="rst-he-6ghz-capa-binary"></a>



#### he-6ghz-capa (`binary`)

<a id="rst-vendor-elems-binary"></a>



#### vendor-elems (`binary`)

<a id="rst-eht-cap-mac-binary"></a>



#### eht-cap-mac (`binary`)

<a id="rst-eht-cap-phy-binary"></a>



#### eht-cap-phy (`binary`)

<a id="rst-eht-cap-mcs-set-binary"></a>



#### eht-cap-mcs-set (`binary`)

<a id="rst-eht-cap-ppe-binary"></a>



#### eht-cap-ppe (`binary`)

<a id="rst-iftype-attrs"></a>
<a id="rst-nl80211-attribute-set-iftype-attrs"></a>



### iftype-attrs

<a id="rst-unspecified-nest"></a>



#### unspecified (`nest`)

- **value**:

  0

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-adhoc-nest"></a>



#### adhoc (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-station-nest"></a>



#### station (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-ap-nest"></a>



#### ap (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-ap-vlan-nest"></a>



#### ap-vlan (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-wds-nest"></a>



#### wds (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-monitor-nest"></a>



#### monitor (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-mesh-point-nest"></a>



#### mesh-point (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-p2p-client-nest"></a>



#### p2p-client (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-p2p-go-nest"></a>



#### p2p-go (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-p2p-device-nest"></a>



#### p2p-device (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-ocb-nest"></a>



#### ocb (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-nan-nest"></a>



#### nan (`nest`)

- **nested-attributes**:

  [frame-type-attrs](#rst-nl80211-attribute-set-frame-type-attrs)

<a id="rst-sar-attributes"></a>
<a id="rst-nl80211-attribute-set-sar-attributes"></a>



### sar-attributes

<a id="rst-type-u32"></a>



#### type (`u32`)

<a id="rst-specs-indexed-array"></a>



#### specs (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [sar-specs](#rst-nl80211-attribute-set-sar-specs)

<a id="rst-sar-specs"></a>
<a id="rst-nl80211-attribute-set-sar-specs"></a>



### sar-specs

<a id="rst-power-s32"></a>



#### power (`s32`)

<a id="rst-range-index-u32"></a>



#### range-index (`u32`)

<a id="rst-start-freq-u32"></a>



#### start-freq (`u32`)

<a id="rst-end-freq-u32"></a>



#### end-freq (`u32`)

<a id="rst-supported-iftypes"></a>
<a id="rst-nl80211-attribute-set-supported-iftypes"></a>



### supported-iftypes

<a id="rst-adhoc-flag"></a>



#### adhoc (`flag`)

<a id="rst-station-flag"></a>



#### station (`flag`)

<a id="rst-ap-flag"></a>



#### ap (`flag`)

<a id="rst-ap-vlan-flag"></a>



#### ap-vlan (`flag`)

<a id="rst-wds-flag"></a>



#### wds (`flag`)

<a id="rst-monitor-flag"></a>



#### monitor (`flag`)

<a id="rst-mesh-point-flag"></a>



#### mesh-point (`flag`)

<a id="rst-p2p-client-flag"></a>



#### p2p-client (`flag`)

<a id="rst-p2p-go-flag"></a>



#### p2p-go (`flag`)

<a id="rst-p2p-device-flag"></a>



#### p2p-device (`flag`)

<a id="rst-ocb-flag"></a>



#### ocb (`flag`)

<a id="rst-nan-flag"></a>



#### nan (`flag`)

<a id="rst-txq-stats-attrs"></a>
<a id="rst-nl80211-attribute-set-txq-stats-attrs"></a>



### txq-stats-attrs

<a id="rst-backlog-bytes-u32"></a>



#### backlog-bytes (`u32`)

<a id="rst-backlog-packets-u32"></a>



#### backlog-packets (`u32`)

<a id="rst-flows-u32"></a>



#### flows (`u32`)

<a id="rst-drops-u32"></a>



#### drops (`u32`)

<a id="rst-ecn-marks-u32"></a>



#### ecn-marks (`u32`)

<a id="rst-overlimit-u32"></a>



#### overlimit (`u32`)

<a id="rst-overmemory-u32"></a>



#### overmemory (`u32`)

<a id="rst-collisions-u32"></a>



#### collisions (`u32`)

<a id="rst-tx-bytes-u32"></a>



#### tx-bytes (`u32`)

<a id="rst-tx-packets-u32"></a>



#### tx-packets (`u32`)

<a id="rst-max-flows-u32"></a>



#### max-flows (`u32`)

<a id="rst-wmm-attrs"></a>
<a id="rst-nl80211-attribute-set-wmm-attrs"></a>



### wmm-attrs

<a id="rst-cw-min-u16"></a>



#### cw-min (`u16`)

<a id="rst-cw-max-u16"></a>



#### cw-max (`u16`)

<a id="rst-aifsn-u8"></a>



#### aifsn (`u8`)

<a id="rst-txop-u16"></a>



#### txop (`u16`)

<a id="rst-wowlan-triggers-attrs"></a>
<a id="rst-nl80211-attribute-set-wowlan-triggers-attrs"></a>



### wowlan-triggers-attrs

<a id="rst-any-flag"></a>



#### any (`flag`)

<a id="rst-disconnect-flag"></a>



#### disconnect (`flag`)

<a id="rst-magic-pkt-flag"></a>



#### magic-pkt (`flag`)

<a id="rst-pkt-pattern-flag"></a>



#### pkt-pattern (`flag`)

<a id="rst-gtk-rekey-supported-flag"></a>



#### gtk-rekey-supported (`flag`)

<a id="rst-gtk-rekey-failure-flag"></a>



#### gtk-rekey-failure (`flag`)

<a id="rst-eap-ident-request-flag"></a>



#### eap-ident-request (`flag`)

<a id="rst-way-handshake-flag"></a>



#### 4way-handshake (`flag`)

<a id="rst-rfkill-release-flag"></a>



#### rfkill-release (`flag`)

<a id="rst-wakeup-pkt-80211-flag"></a>



#### wakeup-pkt-80211 (`flag`)

<a id="rst-wakeup-pkt-80211-len-flag"></a>



#### wakeup-pkt-80211-len (`flag`)

<a id="rst-wakeup-pkt-8023-flag"></a>



#### wakeup-pkt-8023 (`flag`)

<a id="rst-wakeup-pkt-8023-len-flag"></a>



#### wakeup-pkt-8023-len (`flag`)

<a id="rst-tcp-connection-flag"></a>



#### tcp-connection (`flag`)

<a id="rst-wakeup-tcp-match-flag"></a>



#### wakeup-tcp-match (`flag`)

<a id="rst-wakeup-tcp-connlost-flag"></a>



#### wakeup-tcp-connlost (`flag`)

<a id="rst-wakeup-tcp-nomoretokens-flag"></a>



#### wakeup-tcp-nomoretokens (`flag`)

<a id="rst-net-detect-flag"></a>



#### net-detect (`flag`)

<a id="rst-net-detect-results-flag"></a>



#### net-detect-results (`flag`)

<a id="rst-unprotected-deauth-disassoc-flag"></a>



#### unprotected-deauth-disassoc (`flag`)

---

# Family nlctrl netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the nlctrl Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-nlctrl-netlink-specification"></a>
<a id="rst-netlink-nlctrl"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



genetlink meta-family that exposes information about all genetlink
families registered in the kernel (including itself).

<a id="rst-operations"></a>



## Operations

<a id="rst-getfamily"></a>
<a id="rst-nlctrl-operation-getfamily"></a>



### getfamily



Get / dump genetlink families

- **attribute-set**:

  [ctrl-attrs](#rst-nlctrl-attribute-set-ctrl-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`family-name`\]

  **reply**

  - **attributes**:

    \[`family-id`, `family-name`, `hdrsize`, `maxattr`, `mcast-groups`, `ops`, `version`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`family-id`, `family-name`, `hdrsize`, `maxattr`, `mcast-groups`, `ops`, `version`\]

<a id="rst-getpolicy"></a>
<a id="rst-nlctrl-operation-getpolicy"></a>



### getpolicy



Get / dump genetlink policies

- **attribute-set**:

  [ctrl-attrs](#rst-nlctrl-attribute-set-ctrl-attrs)

- **dump**:

  **request**

  - **attributes**:

    \[`family-name`, `family-id`, `op`\]

  **reply**

  - **attributes**:

    \[`family-id`, `op-policy`, `policy`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-op-flags"></a>
<a id="rst-nlctrl-definition-op-flags"></a>



### op-flags

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `admin-perm`


  - `cmd-cap-do`


  - `cmd-cap-dump`


  - `cmd-cap-haspol`


  - `uns-admin-perm`

<a id="rst-attr-type"></a>
<a id="rst-nlctrl-definition-attr-type"></a>



### attr-type

- **enum-name**:

  netlink-attribute-type

- **type**:

  enum

- **entries**:

  - `invalid`


  - `flag`


  - `u8`


  - `u16`


  - `u32`


  - `u64`


  - `s8`


  - `s16`


  - `s32`


  - `s64`


  - `binary`


  - `string`


  - `nul-string`


  - `nested`


  - `nested-array`


  - `bitfield32`


  - `sint`


  - `uint`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-ctrl-attrs"></a>
<a id="rst-nlctrl-attribute-set-ctrl-attrs"></a>



### ctrl-attrs

<a id="rst-family-id-u16"></a>



#### family-id (`u16`)

<a id="rst-family-name-string"></a>



#### family-name (`string`)

<a id="rst-version-u32"></a>



#### version (`u32`)

<a id="rst-hdrsize-u32"></a>



#### hdrsize (`u32`)

<a id="rst-maxattr-u32"></a>



#### maxattr (`u32`)

<a id="rst-ops-indexed-array"></a>



#### ops (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [op-attrs](#rst-nlctrl-attribute-set-op-attrs)

<a id="rst-mcast-groups-indexed-array"></a>



#### mcast-groups (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [mcast-group-attrs](#rst-nlctrl-attribute-set-mcast-group-attrs)

<a id="rst-policy-nest-type-value"></a>



#### policy (`nest-type-value`)

- **type-value**:

  \['policy-id', 'attr-id'\]

- **nested-attributes**:

  [policy-attrs](#rst-nlctrl-attribute-set-policy-attrs)

<a id="rst-op-policy-nest-type-value"></a>



#### op-policy (`nest-type-value`)

- **type-value**:

  \['op-id'\]

- **nested-attributes**:

  [op-policy-attrs](#rst-nlctrl-attribute-set-op-policy-attrs)

<a id="rst-op-u32"></a>



#### op (`u32`)

<a id="rst-mcast-group-attrs"></a>
<a id="rst-nlctrl-attribute-set-mcast-group-attrs"></a>



### mcast-group-attrs

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-id-u32"></a>



#### id (`u32`)

<a id="rst-op-attrs"></a>
<a id="rst-nlctrl-attribute-set-op-attrs"></a>



### op-attrs

<a id="rst-id-u32-1"></a>



#### id (`u32`)

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **enum**:

  [op-flags](#rst-nlctrl-definition-op-flags)

- **enum-as-flags**:

  True

<a id="rst-policy-attrs"></a>
<a id="rst-nlctrl-attribute-set-policy-attrs"></a>



### policy-attrs

<a id="rst-type-u32"></a>



#### type (`u32`)

- **enum**:

  [attr-type](#rst-nlctrl-definition-attr-type)

<a id="rst-min-value-s-s64"></a>



#### min-value-s (`s64`)

<a id="rst-max-value-s-s64"></a>



#### max-value-s (`s64`)

<a id="rst-min-value-u-u64"></a>



#### min-value-u (`u64`)

<a id="rst-max-value-u-u64"></a>



#### max-value-u (`u64`)

<a id="rst-min-length-u32"></a>



#### min-length (`u32`)

<a id="rst-max-length-u32"></a>



#### max-length (`u32`)

<a id="rst-policy-idx-u32"></a>



#### policy-idx (`u32`)

<a id="rst-policy-maxtype-u32"></a>



#### policy-maxtype (`u32`)

<a id="rst-bitfield32-mask-u32"></a>



#### bitfield32-mask (`u32`)

<a id="rst-mask-u64"></a>



#### mask (`u64`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-op-policy-attrs"></a>
<a id="rst-nlctrl-attribute-set-op-policy-attrs"></a>



### op-policy-attrs

<a id="rst-do-u32"></a>



#### do (`u32`)

<a id="rst-dump-u32"></a>



#### dump (`u32`)

---

# Family ovpn netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the ovpn Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-ovpn-netlink-specification"></a>
<a id="rst-netlink-ovpn"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netlink protocol to control OpenVPN network devices

<a id="rst-operations"></a>



## Operations

<a id="rst-peer-new"></a>
<a id="rst-ovpn-operation-peer-new"></a>



### peer-new



Add a remote peer

- **attribute-set**:

  [ovpn-peer-new-input](#rst-ovpn-attribute-set-ovpn-peer-new-input)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `peer`\]

<a id="rst-peer-set"></a>
<a id="rst-ovpn-operation-peer-set"></a>



### peer-set



modify a remote peer

- **attribute-set**:

  [ovpn-peer-set-input](#rst-ovpn-attribute-set-ovpn-peer-set-input)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `peer`\]

<a id="rst-peer-get"></a>
<a id="rst-ovpn-operation-peer-get"></a>



### peer-get



Retrieve data about existing remote peers (or a specific one)

- **attribute-set**:

  [ovpn](#rst-ovpn-attribute-set-ovpn)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `peer`\]

  **reply**

  - **attributes**:

    \[`peer`\]

- **dump**:

  **request**

  - **attributes**:

    \[`ifindex`\]

  **reply**

  - **attributes**:

    \[`peer`\]

<a id="rst-peer-del"></a>
<a id="rst-ovpn-operation-peer-del"></a>



### peer-del



Delete existing remote peer

- **attribute-set**:

  [ovpn-peer-del-input](#rst-ovpn-attribute-set-ovpn-peer-del-input)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `peer`\]

<a id="rst-peer-del-ntf"></a>
<a id="rst-ovpn-operation-peer-del-ntf"></a>



### peer-del-ntf



Notification about a peer being deleted

- **notify**:

  peer-get

- **mcgrp**:

  peers

<a id="rst-key-new"></a>
<a id="rst-ovpn-operation-key-new"></a>



### key-new



Add a cipher key for a specific peer

- **attribute-set**:

  [ovpn](#rst-ovpn-attribute-set-ovpn)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `keyconf`\]

<a id="rst-key-get"></a>
<a id="rst-ovpn-operation-key-get"></a>



### key-get



Retrieve non-sensitive data about peer key and cipher

- **attribute-set**:

  [ovpn-keyconf-get](#rst-ovpn-attribute-set-ovpn-keyconf-get)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `keyconf`\]

  **reply**

  - **attributes**:

    \[`keyconf`\]

<a id="rst-key-swap"></a>
<a id="rst-ovpn-operation-key-swap"></a>



### key-swap



Swap primary and secondary session keys for a specific peer

- **attribute-set**:

  [ovpn-keyconf-swap-input](#rst-ovpn-attribute-set-ovpn-keyconf-swap-input)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `keyconf`\]

<a id="rst-key-swap-ntf"></a>
<a id="rst-ovpn-operation-key-swap-ntf"></a>



### key-swap-ntf



Notification about key having exhausted its IV space and requiring renegotiation

- **notify**:

  key-get

- **mcgrp**:

  peers

<a id="rst-key-del"></a>
<a id="rst-ovpn-operation-key-del"></a>



### key-del



Delete cipher key for a specific peer

- **attribute-set**:

  [ovpn-keyconf-del-input](#rst-ovpn-attribute-set-ovpn-keyconf-del-input)

- **flags**:

  \[`admin-perm`\]

- **do**:

  **pre**



  ovpn-nl-pre-doit

  **post**



  ovpn-nl-post-doit

  **request**

  - **attributes**:

    \[`ifindex`, `keyconf`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- peers


<a id="rst-definitions"></a>



## Definitions

<a id="rst-nonce-tail-size"></a>
<a id="rst-ovpn-definition-nonce-tail-size"></a>



### nonce-tail-size

- **type**:

  const

- **value**:

  8

<a id="rst-cipher-alg"></a>
<a id="rst-ovpn-definition-cipher-alg"></a>



### cipher-alg

- **type**:

  enum

- **entries**:

  - `none`


  - `aes-gcm`


  - `chacha20-poly1305`

<a id="rst-del-peer-reason"></a>
<a id="rst-ovpn-definition-del-peer-reason"></a>



### del-peer-reason

- **type**:

  enum

- **entries**:

  - `teardown`


  - `userspace`


  - `expired`


  - `transport-error`


  - `transport-disconnect`

<a id="rst-key-slot"></a>
<a id="rst-ovpn-definition-key-slot"></a>



### key-slot

- **type**:

  enum

- **entries**:

  - `primary`


  - `secondary`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-peer"></a>
<a id="rst-ovpn-attribute-set-peer"></a>



### peer

<a id="rst-id-u32"></a>



#### id (`u32`)

- **doc**:

  The unique ID of the peer in the device context. To be used to identify peers during operations for a specific device

<a id="rst-remote-ipv4-u32"></a>



#### remote-ipv4 (`u32`)

- **doc**:

  The remote IPv4 address of the peer

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-remote-ipv6-binary"></a>



#### remote-ipv6 (`binary`)

- **doc**:

  The remote IPv6 address of the peer

- **display-hint**:

  ipv6

<a id="rst-remote-ipv6-scope-id-u32"></a>



#### remote-ipv6-scope-id (`u32`)

- **doc**:

  The scope id of the remote IPv6 address of the peer (RFC2553)

<a id="rst-remote-port-u16"></a>



#### remote-port (`u16`)

- **doc**:

  The remote port of the peer

- **byte-order**:

  big-endian

<a id="rst-socket-u32"></a>



#### socket (`u32`)

- **doc**:

  The socket to be used to communicate with the peer

<a id="rst-socket-netnsid-s32"></a>



#### socket-netnsid (`s32`)

- **doc**:

  The ID of the netns the socket assigned to this peer lives in

<a id="rst-vpn-ipv4-u32"></a>



#### vpn-ipv4 (`u32`)

- **doc**:

  The IPv4 address assigned to the peer by the server

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-vpn-ipv6-binary"></a>



#### vpn-ipv6 (`binary`)

- **doc**:

  The IPv6 address assigned to the peer by the server

- **display-hint**:

  ipv6

<a id="rst-local-ipv4-u32"></a>



#### local-ipv4 (`u32`)

- **doc**:

  The local IPv4 to be used to send packets to the peer (UDP only)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-local-ipv6-binary"></a>



#### local-ipv6 (`binary`)

- **doc**:

  The local IPv6 to be used to send packets to the peer (UDP only)

- **display-hint**:

  ipv6

<a id="rst-local-port-u16"></a>



#### local-port (`u16`)

- **doc**:

  The local port to be used to send packets to the peer (UDP only)

- **byte-order**:

  big-endian

<a id="rst-keepalive-interval-u32"></a>



#### keepalive-interval (`u32`)

- **doc**:

  The number of seconds after which a keep alive message is sent to the peer

<a id="rst-keepalive-timeout-u32"></a>



#### keepalive-timeout (`u32`)

- **doc**:

  The number of seconds from the last activity after which the peer is assumed dead

<a id="rst-del-reason-u32"></a>



#### del-reason (`u32`)

- **doc**:

  The reason why a peer was deleted

- **enum**:

  [del-peer-reason](#rst-ovpn-definition-del-peer-reason)

<a id="rst-vpn-rx-bytes-uint"></a>



#### vpn-rx-bytes (`uint`)

- **doc**:

  Number of bytes received over the tunnel

<a id="rst-vpn-tx-bytes-uint"></a>



#### vpn-tx-bytes (`uint`)

- **doc**:

  Number of bytes transmitted over the tunnel

<a id="rst-vpn-rx-packets-uint"></a>



#### vpn-rx-packets (`uint`)

- **doc**:

  Number of packets received over the tunnel

<a id="rst-vpn-tx-packets-uint"></a>



#### vpn-tx-packets (`uint`)

- **doc**:

  Number of packets transmitted over the tunnel

<a id="rst-link-rx-bytes-uint"></a>



#### link-rx-bytes (`uint`)

- **doc**:

  Number of bytes received at the transport level

<a id="rst-link-tx-bytes-uint"></a>



#### link-tx-bytes (`uint`)

- **doc**:

  Number of bytes transmitted at the transport level

<a id="rst-link-rx-packets-uint"></a>



#### link-rx-packets (`uint`)

- **doc**:

  Number of packets received at the transport level

<a id="rst-link-tx-packets-uint"></a>



#### link-tx-packets (`uint`)

- **doc**:

  Number of packets transmitted at the transport level

<a id="rst-peer-new-input"></a>
<a id="rst-ovpn-attribute-set-peer-new-input"></a>



### peer-new-input

<a id="rst-id"></a>



#### id

<a id="rst-remote-ipv4"></a>



#### remote-ipv4

<a id="rst-remote-ipv6"></a>



#### remote-ipv6

<a id="rst-remote-ipv6-scope-id"></a>



#### remote-ipv6-scope-id

<a id="rst-remote-port"></a>



#### remote-port

<a id="rst-socket"></a>



#### socket

<a id="rst-vpn-ipv4"></a>



#### vpn-ipv4

<a id="rst-vpn-ipv6"></a>



#### vpn-ipv6

<a id="rst-local-ipv4"></a>



#### local-ipv4

<a id="rst-local-ipv6"></a>



#### local-ipv6

<a id="rst-keepalive-interval"></a>



#### keepalive-interval

<a id="rst-keepalive-timeout"></a>



#### keepalive-timeout

<a id="rst-peer-set-input"></a>
<a id="rst-ovpn-attribute-set-peer-set-input"></a>



### peer-set-input

<a id="rst-id-1"></a>



#### id

<a id="rst-remote-ipv4-1"></a>



#### remote-ipv4

<a id="rst-remote-ipv6-1"></a>



#### remote-ipv6

<a id="rst-remote-ipv6-scope-id-1"></a>



#### remote-ipv6-scope-id

<a id="rst-remote-port-1"></a>



#### remote-port

<a id="rst-vpn-ipv4-1"></a>



#### vpn-ipv4

<a id="rst-vpn-ipv6-1"></a>



#### vpn-ipv6

<a id="rst-local-ipv4-1"></a>



#### local-ipv4

<a id="rst-local-ipv6-1"></a>



#### local-ipv6

<a id="rst-keepalive-interval-1"></a>



#### keepalive-interval

<a id="rst-keepalive-timeout-1"></a>



#### keepalive-timeout

<a id="rst-peer-del-input"></a>
<a id="rst-ovpn-attribute-set-peer-del-input"></a>



### peer-del-input

<a id="rst-id-2"></a>



#### id

<a id="rst-keyconf"></a>
<a id="rst-ovpn-attribute-set-keyconf"></a>



### keyconf

<a id="rst-peer-id-u32"></a>



#### peer-id (`u32`)

- **doc**:

  The unique ID of the peer in the device context. To be used to identify peers during key operations

<a id="rst-slot-u32"></a>



#### slot (`u32`)

- **doc**:

  The slot where the key should be stored

- **enum**:

  [key-slot](#rst-ovpn-definition-key-slot)

<a id="rst-key-id-u32"></a>



#### key-id (`u32`)

- **doc**:

  The unique ID of the key in the peer context. Used to fetch the correct key upon decryption

<a id="rst-cipher-alg-u32"></a>



#### cipher-alg (`u32`)

- **doc**:

  The cipher to be used when communicating with the peer

- **enum**:

  [cipher-alg](#rst-ovpn-definition-cipher-alg)

<a id="rst-encrypt-dir-nest"></a>



#### encrypt-dir (`nest`)

- **doc**:

  Key material for encrypt direction

- **nested-attributes**:

  [keydir](#rst-ovpn-attribute-set-keydir)

<a id="rst-decrypt-dir-nest"></a>



#### decrypt-dir (`nest`)

- **doc**:

  Key material for decrypt direction

- **nested-attributes**:

  [keydir](#rst-ovpn-attribute-set-keydir)

<a id="rst-keydir"></a>
<a id="rst-ovpn-attribute-set-keydir"></a>



### keydir

<a id="rst-cipher-key-binary"></a>



#### cipher-key (`binary`)

- **doc**:

  The actual key to be used by the cipher

<a id="rst-nonce-tail-binary"></a>



#### nonce-tail (`binary`)

- **doc**:

  Random nonce to be concatenated to the packet ID, in order to obtain the actual cipher IV

<a id="rst-keyconf-get"></a>
<a id="rst-ovpn-attribute-set-keyconf-get"></a>



### keyconf-get

<a id="rst-peer-id"></a>



#### peer-id

<a id="rst-slot"></a>



#### slot

<a id="rst-key-id"></a>



#### key-id

<a id="rst-cipher-alg-1"></a>



#### cipher-alg

<a id="rst-keyconf-swap-input"></a>
<a id="rst-ovpn-attribute-set-keyconf-swap-input"></a>



### keyconf-swap-input

<a id="rst-peer-id-1"></a>



#### peer-id

<a id="rst-keyconf-del-input"></a>
<a id="rst-ovpn-attribute-set-keyconf-del-input"></a>



### keyconf-del-input

<a id="rst-peer-id-2"></a>



#### peer-id

<a id="rst-slot-1"></a>



#### slot

<a id="rst-ovpn"></a>
<a id="rst-ovpn-attribute-set-ovpn"></a>



### ovpn

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

- **doc**:

  Index of the ovpn interface to operate on

<a id="rst-peer-nest"></a>



#### peer (`nest`)

- **doc**:

  The peer object containing the attributed of interest for the specific operation

- **nested-attributes**:

  [peer](#rst-ovpn-attribute-set-peer)

<a id="rst-keyconf-nest"></a>



#### keyconf (`nest`)

- **doc**:

  Peer specific cipher configuration

- **nested-attributes**:

  [keyconf](#rst-ovpn-attribute-set-keyconf)

<a id="rst-ovpn-peer-new-input"></a>
<a id="rst-ovpn-attribute-set-ovpn-peer-new-input"></a>



### ovpn-peer-new-input

<a id="rst-ifindex"></a>



#### ifindex

<a id="rst-peer-1"></a>



#### peer

- **nested-attributes**:

  [peer-new-input](#rst-ovpn-attribute-set-peer-new-input)

<a id="rst-ovpn-peer-set-input"></a>
<a id="rst-ovpn-attribute-set-ovpn-peer-set-input"></a>



### ovpn-peer-set-input

<a id="rst-ifindex-1"></a>



#### ifindex

<a id="rst-peer-2"></a>



#### peer

- **nested-attributes**:

  [peer-set-input](#rst-ovpn-attribute-set-peer-set-input)

<a id="rst-ovpn-peer-del-input"></a>
<a id="rst-ovpn-attribute-set-ovpn-peer-del-input"></a>



### ovpn-peer-del-input

<a id="rst-ifindex-2"></a>



#### ifindex

<a id="rst-peer-3"></a>



#### peer

- **nested-attributes**:

  [peer-del-input](#rst-ovpn-attribute-set-peer-del-input)

<a id="rst-ovpn-keyconf-get"></a>
<a id="rst-ovpn-attribute-set-ovpn-keyconf-get"></a>



### ovpn-keyconf-get

<a id="rst-ifindex-3"></a>



#### ifindex

<a id="rst-keyconf-1"></a>



#### keyconf

- **nested-attributes**:

  [keyconf-get](#rst-ovpn-attribute-set-keyconf-get)

<a id="rst-ovpn-keyconf-swap-input"></a>
<a id="rst-ovpn-attribute-set-ovpn-keyconf-swap-input"></a>



### ovpn-keyconf-swap-input

<a id="rst-ifindex-4"></a>



#### ifindex

<a id="rst-keyconf-2"></a>



#### keyconf

- **nested-attributes**:

  [keyconf-swap-input](#rst-ovpn-attribute-set-keyconf-swap-input)

<a id="rst-ovpn-keyconf-del-input"></a>
<a id="rst-ovpn-attribute-set-ovpn-keyconf-del-input"></a>



### ovpn-keyconf-del-input

<a id="rst-ifindex-5"></a>



#### ifindex

<a id="rst-keyconf-3"></a>



#### keyconf

- **nested-attributes**:

  [keyconf-del-input](#rst-ovpn-attribute-set-keyconf-del-input)

---

# Family ovs_datapath netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the ovs_datapath Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-ovs-datapath-netlink-specification"></a>
<a id="rst-netlink-ovs-datapath"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



OVS datapath configuration over generic netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-ovs-datapath-operation-get"></a>



### get



Get / dump OVS data path configuration and state

- **value**:

  3

- **attribute-set**:

  [datapath](#rst-ovs-datapath-attribute-set-datapath)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`, `upcall-pid`, `stats`, `megaflow-stats`, `user-features`, `masks-cache-size`, `per-cpu-pids`\]

- **dump**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`name`, `upcall-pid`, `stats`, `megaflow-stats`, `user-features`, `masks-cache-size`, `per-cpu-pids`\]

<a id="rst-new"></a>
<a id="rst-ovs-datapath-operation-new"></a>



### new



Create new OVS data path

- **value**:

  1

- **attribute-set**:

  [datapath](#rst-ovs-datapath-attribute-set-datapath)

- **do**:

  **request**

  - **attributes**:

    \[`name`, `upcall-pid`, `user-features`\]

<a id="rst-del"></a>
<a id="rst-ovs-datapath-operation-del"></a>



### del



Delete existing OVS data path

- **value**:

  2

- **attribute-set**:

  [datapath](#rst-ovs-datapath-attribute-set-datapath)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- ovs\_datapath


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ovs-header"></a>
<a id="rst-ovs-datapath-definition-ovs-header"></a>



### ovs-header

- **type**:

  struct

- **members**:

  - **dp-ifindex (`u32`)**

<a id="rst-user-features"></a>
<a id="rst-ovs-datapath-definition-user-features"></a>



### user-features

- **type**:

  flags

- **name-prefix**:

  ovs-dp-f-

- **enum-name**:

  None

- **entries**:

  - **unaligned**:

    Allow last Netlink attribute to be unaligned

  - **vport-pids**:

    Allow datapath to associate multiple Netlink PIDs to each vport

  - **tc-recirc-sharing**:

    Allow tc offload recirc sharing

  - **dispatch-upcall-per-cpu**:

    Allow per-cpu dispatch of upcalls

<a id="rst-ovs-dp-stats"></a>
<a id="rst-ovs-datapath-definition-ovs-dp-stats"></a>



### ovs-dp-stats

- **type**:

  struct

- **members**:

  - **n-hit (`u64`)**

  - **n-missed (`u64`)**

  - **n-lost (`u64`)**

  - **n-flows (`u64`)**

<a id="rst-ovs-dp-megaflow-stats"></a>
<a id="rst-ovs-datapath-definition-ovs-dp-megaflow-stats"></a>



### ovs-dp-megaflow-stats

- **type**:

  struct

- **members**:

  - **n-mask-hit (`u64`)**

  - **n-masks (`u32`)**

  - **padding (`u32`)**

  - **n-cache-hit (`u64`)**

  - **pad1 (`u64`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-datapath"></a>
<a id="rst-ovs-datapath-attribute-set-datapath"></a>



### datapath

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-upcall-pid-u32"></a>



#### upcall-pid (`u32`)

- **doc**:

  upcall pid

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [ovs-dp-stats](#rst-ovs-datapath-definition-ovs-dp-stats)

<a id="rst-megaflow-stats-binary"></a>



#### megaflow-stats (`binary`)

- **struct**:

  [ovs-dp-megaflow-stats](#rst-ovs-datapath-definition-ovs-dp-megaflow-stats)

<a id="rst-user-features-u32"></a>



#### user-features (`u32`)

- **enum**:

  [user-features](#rst-ovs-datapath-definition-user-features)

- **enum-as-flags**:

  True

<a id="rst-pad-unused"></a>



#### pad (`unused`)

<a id="rst-masks-cache-size-u32"></a>



#### masks-cache-size (`u32`)

<a id="rst-per-cpu-pids-binary"></a>



#### per-cpu-pids (`binary`)

- **sub-type**:

  u32

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

---

# Family ovs_flow netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the ovs_flow Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-ovs-flow-netlink-specification"></a>
<a id="rst-netlink-ovs-flow"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



OVS flow configuration over generic netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-ovs-flow-operation-get"></a>



### get



Get / dump OVS flow configuration and state

- **value**:

  3

- **attribute-set**:

  [flow-attrs](#rst-ovs-flow-attribute-set-flow-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`key`, `ufid`, `ufid-flags`\]

  **reply**

  - **attributes**:

    \[`key`, `ufid`, `mask`, `stats`, `actions`\]

- **dump**:

  **request**

  - **attributes**:

    \[`key`, `ufid`, `ufid-flags`\]

  **reply**

  - **attributes**:

    \[`key`, `ufid`, `mask`, `stats`, `actions`\]

<a id="rst-new"></a>
<a id="rst-ovs-flow-operation-new"></a>



### new



Create OVS flow configuration in a data path

- **value**:

  1

- **attribute-set**:

  [flow-attrs](#rst-ovs-flow-attribute-set-flow-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`key`, `ufid`, `mask`, `actions`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- ovs\_flow


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ovs-header"></a>
<a id="rst-ovs-flow-definition-ovs-header"></a>



### ovs-header

- **type**:

  struct

- **doc**:

  Header for OVS Generic Netlink messages.

- **members**:

  - **dp-ifindex (`u32`)**:

    ifindex of local port for datapath (0 to make a request not specific to a datapath).

<a id="rst-ovs-flow-stats"></a>
<a id="rst-ovs-flow-definition-ovs-flow-stats"></a>



### ovs-flow-stats

- **type**:

  struct

- **members**:

  - **n-packets (`u64`)**:

    Number of matched packets.

  - **n-bytes (`u64`)**:

    Number of matched bytes.

<a id="rst-ovs-key-ethernet"></a>
<a id="rst-ovs-flow-definition-ovs-key-ethernet"></a>



### ovs-key-ethernet

- **type**:

  struct

- **members**:

  - **eth-src (`binary`)**

  - **eth-dst (`binary`)**

<a id="rst-ovs-key-mpls"></a>
<a id="rst-ovs-flow-definition-ovs-key-mpls"></a>



### ovs-key-mpls

- **type**:

  struct

- **members**:

  - **mpls-lse (`u32`)**

<a id="rst-ovs-key-ipv4"></a>
<a id="rst-ovs-flow-definition-ovs-key-ipv4"></a>



### ovs-key-ipv4

- **type**:

  struct

- **members**:

  - **ipv4-src (`u32`)**

  - **ipv4-dst (`u32`)**

  - **ipv4-proto (`u8`)**

  - **ipv4-tos (`u8`)**

  - **ipv4-ttl (`u8`)**

  - **ipv4-frag (`u8`)**

<a id="rst-ovs-key-ipv6"></a>
<a id="rst-ovs-flow-definition-ovs-key-ipv6"></a>



### ovs-key-ipv6

- **type**:

  struct

- **members**:

  - **ipv6-src (`binary`)**

  - **ipv6-dst (`binary`)**

  - **ipv6-label (`u32`)**

  - **ipv6-proto (`u8`)**

  - **ipv6-tclass (`u8`)**

  - **ipv6-hlimit (`u8`)**

  - **ipv6-frag (`u8`)**

<a id="rst-ovs-key-ipv6-exthdrs"></a>
<a id="rst-ovs-flow-definition-ovs-key-ipv6-exthdrs"></a>



### ovs-key-ipv6-exthdrs

- **type**:

  struct

- **members**:

  - **hdrs (`u16`)**

<a id="rst-ovs-frag-type"></a>
<a id="rst-ovs-flow-definition-ovs-frag-type"></a>



### ovs-frag-type

- **name-prefix**:

  ovs-frag-type-

- **enum-name**:

  ovs-frag-type

- **type**:

  enum

- **entries**:

  - **none**:

    Packet is not a fragment.

  - **first**:

    Packet is a fragment with offset 0.

  - **later**:

    Packet is a fragment with nonzero offset.

  - **any**

<a id="rst-ovs-key-tcp"></a>
<a id="rst-ovs-flow-definition-ovs-key-tcp"></a>



### ovs-key-tcp

- **type**:

  struct

- **members**:

  - **tcp-src (`u16`)**

  - **tcp-dst (`u16`)**

<a id="rst-ovs-key-udp"></a>
<a id="rst-ovs-flow-definition-ovs-key-udp"></a>



### ovs-key-udp

- **type**:

  struct

- **members**:

  - **udp-src (`u16`)**

  - **udp-dst (`u16`)**

<a id="rst-ovs-key-sctp"></a>
<a id="rst-ovs-flow-definition-ovs-key-sctp"></a>



### ovs-key-sctp

- **type**:

  struct

- **members**:

  - **sctp-src (`u16`)**

  - **sctp-dst (`u16`)**

<a id="rst-ovs-key-icmp"></a>
<a id="rst-ovs-flow-definition-ovs-key-icmp"></a>



### ovs-key-icmp

- **type**:

  struct

- **members**:

  - **icmp-type (`u8`)**

  - **icmp-code (`u8`)**

<a id="rst-ovs-key-arp"></a>
<a id="rst-ovs-flow-definition-ovs-key-arp"></a>



### ovs-key-arp

- **type**:

  struct

- **members**:

  - **arp-sip (`u32`)**

  - **arp-tip (`u32`)**

  - **arp-op (`u16`)**

  - **arp-sha (`binary`)**

  - **arp-tha (`binary`)**

<a id="rst-ovs-key-nd"></a>
<a id="rst-ovs-flow-definition-ovs-key-nd"></a>



### ovs-key-nd

- **type**:

  struct

- **members**:

  - **nd-target (`binary`)**

  - **nd-sll (`binary`)**

  - **nd-tll (`binary`)**

<a id="rst-ovs-key-ct-tuple-ipv4"></a>
<a id="rst-ovs-flow-definition-ovs-key-ct-tuple-ipv4"></a>



### ovs-key-ct-tuple-ipv4

- **type**:

  struct

- **members**:

  - **ipv4-src (`u32`)**

  - **ipv4-dst (`u32`)**

  - **src-port (`u16`)**

  - **dst-port (`u16`)**

  - **ipv4-proto (`u8`)**

<a id="rst-ovs-action-push-vlan"></a>
<a id="rst-ovs-flow-definition-ovs-action-push-vlan"></a>



### ovs-action-push-vlan

- **type**:

  struct

- **members**:

  - **vlan-tpid (`u16`)**:

    Tag protocol identifier (TPID) to push.

  - **vlan-tci (`u16`)**:

    Tag control identifier (TCI) to push.

<a id="rst-ovs-ufid-flags"></a>
<a id="rst-ovs-flow-definition-ovs-ufid-flags"></a>



### ovs-ufid-flags

- **name-prefix**:

  ovs-ufid-f-

- **enum-name**:

  None

- **type**:

  flags

- **entries**:

  - `omit-key`


  - `omit-mask`


  - `omit-actions`

<a id="rst-ovs-action-hash"></a>
<a id="rst-ovs-flow-definition-ovs-action-hash"></a>



### ovs-action-hash

- **type**:

  struct

- **members**:

  - **hash-alg (`u32`)**:

    Algorithm used to compute hash prior to recirculation.

  - **hash-basis (`u32`)**:

    Basis used for computing hash.

<a id="rst-ovs-hash-alg"></a>
<a id="rst-ovs-flow-definition-ovs-hash-alg"></a>



### ovs-hash-alg

- **enum-name**:

  ovs-hash-alg

- **type**:

  enum

- **doc**:

  Data path hash algorithm for computing Datapath hash. The algorithm type only specifies the fields in a flow will be used as part of the hash. Each datapath is free to use its own hash algorithm. The hash value will be opaque to the user space daemon.

- **entries**:

  - `ovs-hash-alg-l4`

<a id="rst-ovs-action-push-mpls"></a>
<a id="rst-ovs-flow-definition-ovs-action-push-mpls"></a>



### ovs-action-push-mpls

- **type**:

  struct

- **members**:

  - **mpls-lse (`u32`)**:

    MPLS label stack entry to push

  - **mpls-ethertype (`u32`)**:

    Ethertype to set in the encapsulating ethernet frame.  The only values ethertype should ever be given are ETH\_P\_MPLS\_UC and ETH\_P\_MPLS\_MC, indicating MPLS unicast or multicast. Other are rejected.

<a id="rst-ovs-action-add-mpls"></a>
<a id="rst-ovs-flow-definition-ovs-action-add-mpls"></a>



### ovs-action-add-mpls

- **type**:

  struct

- **members**:

  - **mpls-lse (`u32`)**:

    MPLS label stack entry to push

  - **mpls-ethertype (`u32`)**:

    Ethertype to set in the encapsulating ethernet frame.  The only values ethertype should ever be given are ETH\_P\_MPLS\_UC and ETH\_P\_MPLS\_MC, indicating MPLS unicast or multicast. Other are rejected.

  - **tun-flags (`u16`)**:

    MPLS tunnel attributes.

<a id="rst-ct-state-flags"></a>
<a id="rst-ovs-flow-definition-ct-state-flags"></a>



### ct-state-flags

- **enum-name**:

  None

- **type**:

  flags

- **name-prefix**:

  ovs-cs-f-

- **entries**:

  - **new**:

    Beginning of a new connection.

  - **established**:

    Part of an existing connenction

  - **related**:

    Related to an existing connection.

  - **reply-dir**:

    Flow is in the reply direction.

  - **invalid**:

    Could not track the connection.

  - **tracked**:

    Conntrack has occurred.

  - **src-nat**:

    Packet's source address/port was mangled by NAT.

  - **dst-nat**:

    Packet's destination address/port was mangled by NAT.

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-flow-attrs"></a>
<a id="rst-ovs-flow-attribute-set-flow-attrs"></a>



### flow-attrs

<a id="rst-key-nest"></a>



#### key (`nest`)

- **nested-attributes**:

  [key-attrs](#rst-ovs-flow-attribute-set-key-attrs)

- **doc**:

  Nested attributes specifying the flow key. Always present in notifications. Required for all requests (except dumps).

<a id="rst-actions-nest"></a>



#### actions (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

- **doc**:

  Nested attributes specifying the actions to take for packets that match the key. Always present in notifications. Required for OVS\_FLOW\_CMD\_NEW requests, optional for OVS\_FLOW\_CMD\_SET requests.  An OVS\_FLOW\_CMD\_SET without OVS\_FLOW\_ATTR\_ACTIONS will not modify the actions.  To clear the actions, an OVS\_FLOW\_ATTR\_ACTIONS without any nested attributes must be given.

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [ovs-flow-stats](#rst-ovs-flow-definition-ovs-flow-stats)

- **doc**:

  Statistics for this flow. Present in notifications if the stats would be nonzero. Ignored in requests.

<a id="rst-tcp-flags-u8"></a>



#### tcp-flags (`u8`)

- **doc**:

  An 8-bit value giving the ORed value of all of the TCP flags seen on packets in this flow. Only present in notifications for TCP flows, and only if it would be nonzero. Ignored in requests.

<a id="rst-used-u64"></a>



#### used (`u64`)

- **doc**:

  A 64-bit integer giving the time, in milliseconds on the system monotonic clock, at which a packet was last processed for this flow. Only present in notifications if a packet has been processed for this flow. Ignored in requests.

<a id="rst-clear-flag"></a>



#### clear (`flag`)

- **doc**:

  If present in a OVS\_FLOW\_CMD\_SET request, clears the last-used time, accumulated TCP flags, and statistics for this flow.  Otherwise ignored in requests. Never present in notifications.

<a id="rst-mask-nest"></a>



#### mask (`nest`)

- **nested-attributes**:

  [key-attrs](#rst-ovs-flow-attribute-set-key-attrs)

- **doc**:

  Nested attributes specifying the mask bits for wildcarded flow match. Mask bit value '1' specifies exact match with corresponding flow key bit, while mask bit value '0' specifies a wildcarded match. Omitting attribute is treated as wildcarding all corresponding fields. Optional for all requests. If not present, all flow key bits are exact match bits.

<a id="rst-probe-binary"></a>



#### probe (`binary`)

- **doc**:

  Flow operation is a feature probe, error logging should be suppressed.

<a id="rst-ufid-binary"></a>



#### ufid (`binary`)

- **doc**:

  A value between 1-16 octets specifying a unique identifier for the flow. Causes the flow to be indexed by this value rather than the value of the OVS\_FLOW\_ATTR\_KEY attribute. Optional for all requests. Present in notifications if the flow was created with this attribute.

- **display-hint**:

  uuid

<a id="rst-ufid-flags-u32"></a>



#### ufid-flags (`u32`)

- **enum**:

  [ovs-ufid-flags](#rst-ovs-flow-definition-ovs-ufid-flags)

- **doc**:

  A 32-bit value of ORed flags that provide alternative semantics for flow installation and retrieval. Optional for all requests.

<a id="rst-pad-binary"></a>



#### pad (`binary`)

<a id="rst-key-attrs"></a>
<a id="rst-ovs-flow-attribute-set-key-attrs"></a>



### key-attrs

<a id="rst-encap-nest"></a>



#### encap (`nest`)

- **nested-attributes**:

  [key-attrs](#rst-ovs-flow-attribute-set-key-attrs)

<a id="rst-priority-u32"></a>



#### priority (`u32`)

<a id="rst-in-port-u32"></a>



#### in-port (`u32`)

<a id="rst-ethernet-binary"></a>



#### ethernet (`binary`)

- **struct**:

  [ovs-key-ethernet](#rst-ovs-flow-definition-ovs-key-ethernet)

- **doc**:

  struct ovs\_key\_ethernet

<a id="rst-vlan-u16"></a>



#### vlan (`u16`)

- **byte-order**:

  big-endian

<a id="rst-ethertype-u16"></a>



#### ethertype (`u16`)

- **byte-order**:

  big-endian

<a id="rst-ipv4-binary"></a>



#### ipv4 (`binary`)

- **struct**:

  [ovs-key-ipv4](#rst-ovs-flow-definition-ovs-key-ipv4)

<a id="rst-ipv6-binary"></a>



#### ipv6 (`binary`)

- **struct**:

  [ovs-key-ipv6](#rst-ovs-flow-definition-ovs-key-ipv6)

- **doc**:

  struct ovs\_key\_ipv6

<a id="rst-tcp-binary"></a>



#### tcp (`binary`)

- **struct**:

  [ovs-key-tcp](#rst-ovs-flow-definition-ovs-key-tcp)

<a id="rst-udp-binary"></a>



#### udp (`binary`)

- **struct**:

  [ovs-key-udp](#rst-ovs-flow-definition-ovs-key-udp)

<a id="rst-icmp-binary"></a>



#### icmp (`binary`)

- **struct**:

  [ovs-key-icmp](#rst-ovs-flow-definition-ovs-key-icmp)

<a id="rst-icmpv6-binary"></a>



#### icmpv6 (`binary`)

- **struct**:

  [ovs-key-icmp](#rst-ovs-flow-definition-ovs-key-icmp)

<a id="rst-arp-binary"></a>



#### arp (`binary`)

- **struct**:

  [ovs-key-arp](#rst-ovs-flow-definition-ovs-key-arp)

- **doc**:

  struct ovs\_key\_arp

<a id="rst-nd-binary"></a>



#### nd (`binary`)

- **struct**:

  [ovs-key-nd](#rst-ovs-flow-definition-ovs-key-nd)

- **doc**:

  struct ovs\_key\_nd

<a id="rst-skb-mark-u32"></a>



#### skb-mark (`u32`)

<a id="rst-tunnel-nest"></a>



#### tunnel (`nest`)

- **nested-attributes**:

  [tunnel-key-attrs](#rst-ovs-flow-attribute-set-tunnel-key-attrs)

<a id="rst-sctp-binary"></a>



#### sctp (`binary`)

- **struct**:

  [ovs-key-sctp](#rst-ovs-flow-definition-ovs-key-sctp)

<a id="rst-tcp-flags-u16"></a>



#### tcp-flags (`u16`)

- **byte-order**:

  big-endian

<a id="rst-dp-hash-u32"></a>



#### dp-hash (`u32`)

- **doc**:

  Value 0 indicates the hash is not computed by the datapath.

<a id="rst-recirc-id-u32"></a>



#### recirc-id (`u32`)

<a id="rst-mpls-binary"></a>



#### mpls (`binary`)

- **struct**:

  [ovs-key-mpls](#rst-ovs-flow-definition-ovs-key-mpls)

<a id="rst-ct-state-u32"></a>



#### ct-state (`u32`)

- **enum**:

  [ct-state-flags](#rst-ovs-flow-definition-ct-state-flags)

- **enum-as-flags**:

  True

<a id="rst-ct-zone-u16"></a>



#### ct-zone (`u16`)

- **doc**:

  connection tracking zone

<a id="rst-ct-mark-u32"></a>



#### ct-mark (`u32`)

- **doc**:

  connection tracking mark

<a id="rst-ct-labels-binary"></a>



#### ct-labels (`binary`)

- **display-hint**:

  hex

- **doc**:

  16-octet connection tracking label

<a id="rst-ct-orig-tuple-ipv4-binary"></a>



#### ct-orig-tuple-ipv4 (`binary`)

- **struct**:

  [ovs-key-ct-tuple-ipv4](#rst-ovs-flow-definition-ovs-key-ct-tuple-ipv4)

<a id="rst-ct-orig-tuple-ipv6-binary"></a>



#### ct-orig-tuple-ipv6 (`binary`)

- **doc**:

  struct ovs\_key\_ct\_tuple\_ipv6

<a id="rst-nsh-nest"></a>



#### nsh (`nest`)

- **nested-attributes**:

  [ovs-nsh-key-attrs](#rst-ovs-flow-attribute-set-ovs-nsh-key-attrs)

<a id="rst-packet-type-u32"></a>



#### packet-type (`u32`)

- **byte-order**:

  big-endian

- **doc**:

  Should not be sent to the kernel

<a id="rst-nd-extensions-binary"></a>



#### nd-extensions (`binary`)

- **doc**:

  Should not be sent to the kernel

<a id="rst-tunnel-info-binary"></a>



#### tunnel-info (`binary`)

- **doc**:

  struct ip\_tunnel\_info

<a id="rst-ipv6-exthdrs-binary"></a>



#### ipv6-exthdrs (`binary`)

- **struct**:

  [ovs-key-ipv6-exthdrs](#rst-ovs-flow-definition-ovs-key-ipv6-exthdrs)

- **doc**:

  struct ovs\_key\_ipv6\_exthdr

<a id="rst-action-attrs"></a>
<a id="rst-ovs-flow-attribute-set-action-attrs"></a>



### action-attrs

<a id="rst-output-u32"></a>



#### output (`u32`)

- **doc**:

  ovs port number in datapath

<a id="rst-userspace-nest"></a>



#### userspace (`nest`)

- **nested-attributes**:

  [userspace-attrs](#rst-ovs-flow-attribute-set-userspace-attrs)

<a id="rst-set-nest"></a>



#### set (`nest`)

- **nested-attributes**:

  [key-attrs](#rst-ovs-flow-attribute-set-key-attrs)

- **doc**:

  Replaces the contents of an existing header. The single nested attribute specifies a header to modify and its value.

<a id="rst-push-vlan-binary"></a>



#### push-vlan (`binary`)

- **struct**:

  [ovs-action-push-vlan](#rst-ovs-flow-definition-ovs-action-push-vlan)

- **doc**:

  Push a new outermost 802.1Q or 802.1ad header onto the packet.

<a id="rst-pop-vlan-flag"></a>



#### pop-vlan (`flag`)

- **doc**:

  Pop the outermost 802.1Q or 802.1ad header from the packet.

<a id="rst-sample-nest"></a>



#### sample (`nest`)

- **nested-attributes**:

  [sample-attrs](#rst-ovs-flow-attribute-set-sample-attrs)

- **doc**:

  Probabilistically executes actions, as specified in the nested attributes.

<a id="rst-recirc-u32"></a>



#### recirc (`u32`)

- **doc**:

  recirc id

<a id="rst-hash-binary"></a>



#### hash (`binary`)

- **struct**:

  [ovs-action-hash](#rst-ovs-flow-definition-ovs-action-hash)

<a id="rst-push-mpls-binary"></a>



#### push-mpls (`binary`)

- **struct**:

  [ovs-action-push-mpls](#rst-ovs-flow-definition-ovs-action-push-mpls)

- **doc**:

  Push a new MPLS label stack entry onto the top of the packets MPLS label stack. Set the ethertype of the encapsulating frame to either ETH\_P\_MPLS\_UC or ETH\_P\_MPLS\_MC to indicate the new packet contents.

<a id="rst-pop-mpls-u16"></a>



#### pop-mpls (`u16`)

- **byte-order**:

  big-endian

- **doc**:

  ethertype

<a id="rst-set-masked-nest"></a>



#### set-masked (`nest`)

- **nested-attributes**:

  [key-attrs](#rst-ovs-flow-attribute-set-key-attrs)

- **doc**:

  Replaces the contents of an existing header. A nested attribute specifies a header to modify, its value, and a mask. For every bit set in the mask, the corresponding bit value is copied from the value to the packet header field, rest of the bits are left unchanged. The non-masked value bits must be passed in as zeroes. Masking is not supported for the OVS\_KEY\_ATTR\_TUNNEL attribute.

<a id="rst-ct-nest"></a>



#### ct (`nest`)

- **nested-attributes**:

  [ct-attrs](#rst-ovs-flow-attribute-set-ct-attrs)

- **doc**:

  Track the connection. Populate the conntrack-related entries in the flow key.

<a id="rst-trunc-u32"></a>



#### trunc (`u32`)

- **doc**:

  struct ovs\_action\_trunc is a u32 max length

<a id="rst-push-eth-binary"></a>



#### push-eth (`binary`)

- **doc**:

  struct ovs\_action\_push\_eth

<a id="rst-pop-eth-flag"></a>



#### pop-eth (`flag`)

<a id="rst-ct-clear-flag"></a>



#### ct-clear (`flag`)

<a id="rst-push-nsh-nest"></a>



#### push-nsh (`nest`)

- **nested-attributes**:

  [ovs-nsh-key-attrs](#rst-ovs-flow-attribute-set-ovs-nsh-key-attrs)

- **doc**:

  Push NSH header to the packet.

<a id="rst-pop-nsh-flag"></a>



#### pop-nsh (`flag`)

- **doc**:

  Pop the outermost NSH header off the packet.

<a id="rst-meter-u32"></a>



#### meter (`u32`)

- **doc**:

  Run packet through a meter, which may drop the packet, or modify the packet (e.g., change the DSCP field)

<a id="rst-clone-nest"></a>



#### clone (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

- **doc**:

  Make a copy of the packet and execute a list of actions without affecting the original packet and key.

<a id="rst-check-pkt-len-nest"></a>



#### check-pkt-len (`nest`)

- **nested-attributes**:

  [check-pkt-len-attrs](#rst-ovs-flow-attribute-set-check-pkt-len-attrs)

- **doc**:

  Check the packet length and execute a set of actions if greater than the specified packet length, else execute another set of actions.

<a id="rst-add-mpls-binary"></a>



#### add-mpls (`binary`)

- **struct**:

  [ovs-action-add-mpls](#rst-ovs-flow-definition-ovs-action-add-mpls)

- **doc**:

  Push a new MPLS label stack entry at the start of the packet or at the start of the l3 header depending on the value of l3 tunnel flag in the tun\_flags field of this OVS\_ACTION\_ATTR\_ADD\_MPLS argument.

<a id="rst-dec-ttl-nest"></a>



#### dec-ttl (`nest`)

- **nested-attributes**:

  [dec-ttl-attrs](#rst-ovs-flow-attribute-set-dec-ttl-attrs)

<a id="rst-psample-nest"></a>



#### psample (`nest`)

- **nested-attributes**:

  [psample-attrs](#rst-ovs-flow-attribute-set-psample-attrs)

- **doc**:

  Sends a packet sample to psample for external observation.

<a id="rst-tunnel-key-attrs"></a>
<a id="rst-ovs-flow-attribute-set-tunnel-key-attrs"></a>



### tunnel-key-attrs

<a id="rst-id-u64"></a>



#### id (`u64`)

- **byte-order**:

  big-endian

- **value**:

  0

<a id="rst-ipv4-src-u32"></a>



#### ipv4-src (`u32`)

- **byte-order**:

  big-endian

<a id="rst-ipv4-dst-u32"></a>



#### ipv4-dst (`u32`)

- **byte-order**:

  big-endian

<a id="rst-tos-u8"></a>



#### tos (`u8`)

<a id="rst-ttl-u8"></a>



#### ttl (`u8`)

<a id="rst-dont-fragment-flag"></a>



#### dont-fragment (`flag`)

<a id="rst-csum-flag"></a>



#### csum (`flag`)

<a id="rst-oam-flag"></a>



#### oam (`flag`)

<a id="rst-geneve-opts-binary"></a>



#### geneve-opts (`binary`)

- **sub-type**:

  u32

<a id="rst-tp-src-u16"></a>



#### tp-src (`u16`)

- **byte-order**:

  big-endian

<a id="rst-tp-dst-u16"></a>



#### tp-dst (`u16`)

- **byte-order**:

  big-endian

<a id="rst-vxlan-opts-nest"></a>



#### vxlan-opts (`nest`)

- **nested-attributes**:

  [vxlan-ext-attrs](#rst-ovs-flow-attribute-set-vxlan-ext-attrs)

<a id="rst-ipv6-src-binary"></a>



#### ipv6-src (`binary`)

- **doc**:

  struct in6\_addr source IPv6 address

<a id="rst-ipv6-dst-binary"></a>



#### ipv6-dst (`binary`)

- **doc**:

  struct in6\_addr destination IPv6 address

<a id="rst-pad-binary-1"></a>



#### pad (`binary`)

<a id="rst-erspan-opts-binary"></a>



#### erspan-opts (`binary`)

- **doc**:

  struct erspan\_metadata

<a id="rst-ipv4-info-bridge-flag"></a>



#### ipv4-info-bridge (`flag`)

<a id="rst-check-pkt-len-attrs"></a>
<a id="rst-ovs-flow-attribute-set-check-pkt-len-attrs"></a>



### check-pkt-len-attrs

<a id="rst-pkt-len-u16"></a>



#### pkt-len (`u16`)

<a id="rst-actions-if-greater-nest"></a>



#### actions-if-greater (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

<a id="rst-actions-if-less-equal-nest"></a>



#### actions-if-less-equal (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

<a id="rst-sample-attrs"></a>
<a id="rst-ovs-flow-attribute-set-sample-attrs"></a>



### sample-attrs

<a id="rst-probability-u32"></a>



#### probability (`u32`)

<a id="rst-actions-nest-1"></a>



#### actions (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

<a id="rst-userspace-attrs"></a>
<a id="rst-ovs-flow-attribute-set-userspace-attrs"></a>



### userspace-attrs

<a id="rst-pid-u32"></a>



#### pid (`u32`)

<a id="rst-userdata-binary"></a>



#### userdata (`binary`)

<a id="rst-egress-tun-port-u32"></a>



#### egress-tun-port (`u32`)

<a id="rst-actions-flag"></a>



#### actions (`flag`)

<a id="rst-ovs-nsh-key-attrs"></a>
<a id="rst-ovs-flow-attribute-set-ovs-nsh-key-attrs"></a>



### ovs-nsh-key-attrs

<a id="rst-base-binary"></a>



#### base (`binary`)

<a id="rst-md1-binary"></a>



#### md1 (`binary`)

<a id="rst-md2-binary"></a>



#### md2 (`binary`)

<a id="rst-ct-attrs"></a>
<a id="rst-ovs-flow-attribute-set-ct-attrs"></a>



### ct-attrs

<a id="rst-commit-flag"></a>



#### commit (`flag`)

<a id="rst-zone-u16"></a>



#### zone (`u16`)

<a id="rst-mark-binary"></a>



#### mark (`binary`)

<a id="rst-labels-binary"></a>



#### labels (`binary`)

<a id="rst-helper-string"></a>



#### helper (`string`)

<a id="rst-nat-nest"></a>



#### nat (`nest`)

- **nested-attributes**:

  [nat-attrs](#rst-ovs-flow-attribute-set-nat-attrs)

<a id="rst-force-commit-flag"></a>



#### force-commit (`flag`)

<a id="rst-eventmask-u32"></a>



#### eventmask (`u32`)

<a id="rst-timeout-string"></a>



#### timeout (`string`)

<a id="rst-nat-attrs"></a>
<a id="rst-ovs-flow-attribute-set-nat-attrs"></a>



### nat-attrs

<a id="rst-src-flag"></a>



#### src (`flag`)

<a id="rst-dst-flag"></a>



#### dst (`flag`)

<a id="rst-ip-min-binary"></a>



#### ip-min (`binary`)

<a id="rst-ip-max-binary"></a>



#### ip-max (`binary`)

<a id="rst-proto-min-u16"></a>



#### proto-min (`u16`)

<a id="rst-proto-max-u16"></a>



#### proto-max (`u16`)

<a id="rst-persistent-flag"></a>



#### persistent (`flag`)

<a id="rst-proto-hash-flag"></a>



#### proto-hash (`flag`)

<a id="rst-proto-random-flag"></a>



#### proto-random (`flag`)

<a id="rst-dec-ttl-attrs"></a>
<a id="rst-ovs-flow-attribute-set-dec-ttl-attrs"></a>



### dec-ttl-attrs

<a id="rst-action-nest"></a>



#### action (`nest`)

- **nested-attributes**:

  [action-attrs](#rst-ovs-flow-attribute-set-action-attrs)

<a id="rst-vxlan-ext-attrs"></a>
<a id="rst-ovs-flow-attribute-set-vxlan-ext-attrs"></a>



### vxlan-ext-attrs

<a id="rst-gbp-u32"></a>



#### gbp (`u32`)

<a id="rst-psample-attrs"></a>
<a id="rst-ovs-flow-attribute-set-psample-attrs"></a>



### psample-attrs

<a id="rst-group-u32"></a>



#### group (`u32`)

<a id="rst-cookie-binary"></a>



#### cookie (`binary`)

---

# Family ovs_vport netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the ovs_vport Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-ovs-vport-netlink-specification"></a>
<a id="rst-netlink-ovs-vport"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



OVS vport configuration over generic netlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-new"></a>
<a id="rst-ovs-vport-operation-new"></a>



### new



Create a new OVS vport

- **attribute-set**:

  [vport](#rst-ovs-vport-attribute-set-vport)

- **do**:

  **request**

  - **attributes**:

    \[`name`, `type`, `upcall-pid`, `ifindex`, `options`\]

<a id="rst-del"></a>
<a id="rst-ovs-vport-operation-del"></a>



### del



Delete existing OVS vport from a data path

- **attribute-set**:

  [vport](#rst-ovs-vport-attribute-set-vport)

- **do**:

  **request**

  - **attributes**:

    \[`port-no`, `type`, `name`\]

<a id="rst-get"></a>
<a id="rst-ovs-vport-operation-get"></a>



### get



Get / dump OVS vport configuration and state

- **attribute-set**:

  [vport](#rst-ovs-vport-attribute-set-vport)

- **do**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`port-no`, `type`, `name`, `upcall-pid`, `stats`, `ifindex`, `netnsid`, `upcall-stats`\]

- **dump**:

  **request**

  - **attributes**:

    \[`name`\]

  **reply**

  - **attributes**:

    \[`port-no`, `type`, `name`, `upcall-pid`, `stats`, `ifindex`, `netnsid`, `upcall-stats`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- ovs\_vport


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ovs-header"></a>
<a id="rst-ovs-vport-definition-ovs-header"></a>



### ovs-header

- **type**:

  struct

- **members**:

  - **dp-ifindex (`u32`)**

<a id="rst-vport-type"></a>
<a id="rst-ovs-vport-definition-vport-type"></a>



### vport-type

- **type**:

  enum

- **enum-name**:

  ovs-vport-type

- **name-prefix**:

  ovs-vport-type-

- **entries**:

  - `unspec`


  - `netdev`


  - `internal`


  - `gre`


  - `vxlan`


  - `geneve`

<a id="rst-ovs-vport-stats"></a>
<a id="rst-ovs-vport-definition-ovs-vport-stats"></a>



### ovs-vport-stats

- **type**:

  struct

- **members**:

  - **rx-packets (`u64`)**

  - **tx-packets (`u64`)**

  - **rx-bytes (`u64`)**

  - **tx-bytes (`u64`)**

  - **rx-errors (`u64`)**

  - **tx-errors (`u64`)**

  - **rx-dropped (`u64`)**

  - **tx-dropped (`u64`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-vport-options"></a>
<a id="rst-ovs-vport-attribute-set-vport-options"></a>



### vport-options

<a id="rst-dst-port-u32"></a>



#### dst-port (`u32`)

<a id="rst-extension-u32"></a>



#### extension (`u32`)

<a id="rst-upcall-stats"></a>
<a id="rst-ovs-vport-attribute-set-upcall-stats"></a>



### upcall-stats

<a id="rst-success-u64"></a>



#### success (`u64`)

- **value**:

  0

<a id="rst-fail-u64"></a>



#### fail (`u64`)

<a id="rst-vport"></a>
<a id="rst-ovs-vport-attribute-set-vport"></a>



### vport

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-port-no-u32"></a>



#### port-no (`u32`)

<a id="rst-type-u32"></a>



#### type (`u32`)

- **enum**:

  [vport-type](#rst-ovs-vport-definition-vport-type)

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-options-nest"></a>



#### options (`nest`)

- **nested-attributes**:

  [vport-options](#rst-ovs-vport-attribute-set-vport-options)

<a id="rst-upcall-pid-binary"></a>



#### upcall-pid (`binary`)

- **sub-type**:

  u32

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [ovs-vport-stats](#rst-ovs-vport-definition-ovs-vport-stats)

<a id="rst-pad-unused"></a>



#### pad (`unused`)

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

<a id="rst-netnsid-u32"></a>



#### netnsid (`u32`)

<a id="rst-upcall-stats-nest"></a>



#### upcall-stats (`nest`)

- **nested-attributes**:

  [upcall-stats](#rst-ovs-vport-attribute-set-upcall-stats)

---

# Family psp netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the psp Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-psp-netlink-specification"></a>
<a id="rst-netlink-psp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



PSP Security Protocol Generic Netlink family.

<a id="rst-operations"></a>



## Operations

<a id="rst-dev-get"></a>
<a id="rst-psp-operation-dev-get"></a>



### dev-get



Get / dump information about PSP capable devices on the system.

- **attribute-set**:

  [dev](#rst-psp-attribute-set-dev)

- **do**:

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `psp-versions-cap`, `psp-versions-ena`\]

  **pre**



  psp-device-get-locked

  **post**



  psp-device-unlock

- **dump**:

  **reply**

  - **attributes**:

    \[`id`, `ifindex`, `psp-versions-cap`, `psp-versions-ena`\]

<a id="rst-dev-add-ntf"></a>
<a id="rst-psp-operation-dev-add-ntf"></a>



### dev-add-ntf



Notification about device appearing.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-dev-del-ntf"></a>
<a id="rst-psp-operation-dev-del-ntf"></a>



### dev-del-ntf



Notification about device disappearing.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-dev-set"></a>
<a id="rst-psp-operation-dev-set"></a>



### dev-set



Set the configuration of a PSP device.

- **attribute-set**:

  [dev](#rst-psp-attribute-set-dev)

- **do**:

  **request**

  - **attributes**:

    \[`id`, `psp-versions-ena`\]

  **reply**

  - **attributes**:

    \[\]

  **pre**



  psp-device-get-locked

  **post**



  psp-device-unlock

<a id="rst-dev-change-ntf"></a>
<a id="rst-psp-operation-dev-change-ntf"></a>



### dev-change-ntf



Notification about device configuration being changed.

- **notify**:

  dev-get

- **mcgrp**:

  mgmt

<a id="rst-key-rotate"></a>
<a id="rst-psp-operation-key-rotate"></a>



### key-rotate



Rotate the device key.

- **attribute-set**:

  [dev](#rst-psp-attribute-set-dev)

- **do**:

  **request**

  - **attributes**:

    \[`id`\]

  **reply**

  - **attributes**:

    \[`id`\]

  **pre**



  psp-device-get-locked

  **post**



  psp-device-unlock

<a id="rst-key-rotate-ntf"></a>
<a id="rst-psp-operation-key-rotate-ntf"></a>



### key-rotate-ntf



Notification about device key getting rotated.

- **notify**:

  key-rotate

- **mcgrp**:

  use

<a id="rst-rx-assoc"></a>
<a id="rst-psp-operation-rx-assoc"></a>



### rx-assoc



Allocate a new Rx key + SPI pair, associate it with a socket.

- **attribute-set**:

  [assoc](#rst-psp-attribute-set-assoc)

- **do**:

  **request**

  - **attributes**:

    \[`dev-id`, `version`, `sock-fd`\]

  **reply**

  - **attributes**:

    \[`dev-id`, `rx-key`\]

  **pre**



  psp-assoc-device-get-locked

  **post**



  psp-device-unlock

<a id="rst-tx-assoc"></a>
<a id="rst-psp-operation-tx-assoc"></a>



### tx-assoc



Add a PSP Tx association.

- **attribute-set**:

  [assoc](#rst-psp-attribute-set-assoc)

- **do**:

  **request**

  - **attributes**:

    \[`dev-id`, `version`, `tx-key`, `sock-fd`\]

  **reply**

  - **attributes**:

    \[\]

  **pre**



  psp-assoc-device-get-locked

  **post**



  psp-device-unlock

<a id="rst-get-stats"></a>
<a id="rst-psp-operation-get-stats"></a>



### get-stats



Get device statistics.

- **attribute-set**:

  [stats](#rst-psp-attribute-set-stats)

- **do**:

  **request**

  - **attributes**:

    \[`dev-id`\]

  **reply**

  - **attributes**:

    \[`dev-id`, `key-rotations`, `stale-events`\]

  **pre**



  psp-device-get-locked

  **post**



  psp-device-unlock

- **dump**:

  **reply**

  - **attributes**:

    \[`dev-id`, `key-rotations`, `stale-events`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- mgmt


- use


<a id="rst-definitions"></a>



## Definitions

<a id="rst-version"></a>
<a id="rst-psp-definition-version"></a>



### version

- **type**:

  enum

- **entries**:

  - `hdr0-aes-gcm-128`


  - `hdr0-aes-gcm-256`


  - `hdr0-aes-gmac-128`


  - `hdr0-aes-gmac-256`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-dev"></a>
<a id="rst-psp-attribute-set-dev"></a>



### dev

<a id="rst-id-u32"></a>



#### id (`u32`)

- **doc**:

  PSP device ID.

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

- **doc**:

  ifindex of the main netdevice linked to the PSP device.

<a id="rst-psp-versions-cap-u32"></a>



#### psp-versions-cap (`u32`)

- **doc**:

  Bitmask of PSP versions supported by the device.

- **enum**:

  [version](#rst-psp-definition-version)

- **enum-as-flags**:

  True

<a id="rst-psp-versions-ena-u32"></a>



#### psp-versions-ena (`u32`)

- **doc**:

  Bitmask of currently enabled (accepted on Rx) PSP versions.

- **enum**:

  [version](#rst-psp-definition-version)

- **enum-as-flags**:

  True

<a id="rst-assoc"></a>
<a id="rst-psp-attribute-set-assoc"></a>



### assoc

<a id="rst-dev-id-u32"></a>



#### dev-id (`u32`)

- **doc**:

  PSP device ID.

<a id="rst-version-u32"></a>



#### version (`u32`)

- **doc**:

  PSP versions (AEAD and protocol version) used by this association, dictates the size of the key.

- **enum**:

  [version](#rst-psp-definition-version)

<a id="rst-rx-key-nest"></a>



#### rx-key (`nest`)

- **nested-attributes**:

  [keys](#rst-psp-attribute-set-keys)

<a id="rst-tx-key-nest"></a>



#### tx-key (`nest`)

- **nested-attributes**:

  [keys](#rst-psp-attribute-set-keys)

<a id="rst-sock-fd-u32"></a>



#### sock-fd (`u32`)

- **doc**:

  Sockets which should be bound to the association immediately.

<a id="rst-keys"></a>
<a id="rst-psp-attribute-set-keys"></a>



### keys

<a id="rst-key-binary"></a>



#### key (`binary`)

<a id="rst-spi-u32"></a>



#### spi (`u32`)

- **doc**:

  Security Parameters Index (SPI) of the association.

<a id="rst-stats"></a>
<a id="rst-psp-attribute-set-stats"></a>



### stats

<a id="rst-dev-id-u32-1"></a>



#### dev-id (`u32`)

- **doc**:

  PSP device ID.

<a id="rst-key-rotations-uint"></a>



#### key-rotations (`uint`)

- **doc**:

  Number of key rotations during the lifetime of the device. Kernel statistic.

<a id="rst-stale-events-uint"></a>



#### stale-events (`uint`)

- **doc**:

  Number of times a socket's Rx got shut down due to using a key which went stale (fully rotated out). Kernel statistic.

<a id="rst-rx-packets-uint"></a>



#### rx-packets (`uint`)

- **doc**:

  Number of successfully processed and authenticated PSP packets. Device statistic (from the PSP spec).

<a id="rst-rx-bytes-uint"></a>



#### rx-bytes (`uint`)

- **doc**:

  Number of successfully authenticated PSP bytes received, counting from the first byte after the IV through the last byte of payload. The fixed initial portion of the PSP header (16 bytes) and the PSP trailer/ICV (16 bytes) are not included in this count. Device statistic (from the PSP spec).

<a id="rst-rx-auth-fail-uint"></a>



#### rx-auth-fail (`uint`)

- **doc**:

  Number of received PSP packets with unsuccessful authentication. Device statistic (from the PSP spec).

<a id="rst-rx-error-uint"></a>



#### rx-error (`uint`)

- **doc**:

  Number of received PSP packets with length/framing errors. Device statistic (from the PSP spec).

<a id="rst-rx-bad-uint"></a>



#### rx-bad (`uint`)

- **doc**:

  Number of received PSP packets with miscellaneous errors (invalid master key indicated by SPI, unsupported version, etc.) Device statistic (from the PSP spec).

<a id="rst-tx-packets-uint"></a>



#### tx-packets (`uint`)

- **doc**:

  Number of successfully processed PSP packets for transmission. Device statistic (from the PSP spec).

<a id="rst-tx-bytes-uint"></a>



#### tx-bytes (`uint`)

- **doc**:

  Number of successfully processed PSP bytes for transmit, counting from the first byte after the IV through the last byte of payload. The fixed initial portion of the PSP header (16 bytes) and the PSP trailer/ICV (16 bytes) are not included in this count. Device statistic (from the PSP spec).

<a id="rst-tx-error-uint"></a>



#### tx-error (`uint`)

- **doc**:

  Number of PSP packets for transmission with errors. Device statistic (from the PSP spec).

---

# Family rt-addr netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the rt-addr Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-rt-addr-netlink-specification"></a>
<a id="rst-netlink-rt-addr"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Address configuration over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-newaddr"></a>
<a id="rst-rt-addr-operation-newaddr"></a>



### newaddr



Add new address

- **attribute-set**:

  [addr-attrs](#rst-rt-addr-attribute-set-addr-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`address`, `label`, `local`, `cacheinfo`\]

<a id="rst-deladdr"></a>
<a id="rst-rt-addr-operation-deladdr"></a>



### deladdr



Remove address

- **attribute-set**:

  [addr-attrs](#rst-rt-addr-attribute-set-addr-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`address`, `local`\]

<a id="rst-getaddr"></a>
<a id="rst-rt-addr-operation-getaddr"></a>



### getaddr



Dump address information.

- **attribute-set**:

  [addr-attrs](#rst-rt-addr-attribute-set-addr-attrs)

- **dump**:

  **request**

  - **attributes**:

    \[\]

  **reply**

  - **attributes**:

    \[`address`, `label`, `local`, `cacheinfo`\]

<a id="rst-getmulticast"></a>
<a id="rst-rt-addr-operation-getmulticast"></a>



### getmulticast



Get / dump IPv4/IPv6 multicast addresses.

- **attribute-set**:

  [addr-attrs](#rst-rt-addr-attribute-set-addr-attrs)

- **fixed-header**:

  [ifaddrmsg](#rst-rt-addr-definition-ifaddrmsg)

- **do**:

  **request**

  - **attributes**:

    \[\]

  **reply**

  - **attributes**:

    \[`multicast`, `cacheinfo`\]

- **dump**:

  **request**

  - **attributes**:

    \[\]

  **reply**

  - **attributes**:

    \[`multicast`, `cacheinfo`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- rtnlgrp-ipv4-ifaddr


- rtnlgrp-ipv6-ifaddr


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ifaddrmsg"></a>
<a id="rst-rt-addr-definition-ifaddrmsg"></a>



### ifaddrmsg

- **type**:

  struct

- **members**:

  - **ifa-family (`u8`)**

  - **ifa-prefixlen (`u8`)**

  - **ifa-flags (`u8`)**

  - **ifa-scope (`u8`)**

  - **ifa-index (`u32`)**

<a id="rst-ifa-cacheinfo"></a>
<a id="rst-rt-addr-definition-ifa-cacheinfo"></a>



### ifa-cacheinfo

- **type**:

  struct

- **members**:

  - **ifa-prefered (`u32`)**

  - **ifa-valid (`u32`)**

  - **cstamp (`u32`)**

  - **tstamp (`u32`)**

<a id="rst-ifa-flags"></a>
<a id="rst-rt-addr-definition-ifa-flags"></a>



### ifa-flags

- **type**:

  flags

- **name-prefix**:

  ifa-f-

- **enum-name**:

  None

- **entries**:

  - **secondary**

  - **nodad**

  - **optimistic**

  - **dadfailed**

  - **homeaddress**

  - **deprecated**

  - **tentative**

  - **permanent**

  - **managetempaddr**

  - **noprefixroute**

  - **mcautojoin**

  - **stable-privacy**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-addr-attrs"></a>
<a id="rst-rt-addr-attribute-set-addr-attrs"></a>



### addr-attrs

<a id="rst-address-binary"></a>



#### address (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-local-binary"></a>



#### local (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-label-string"></a>



#### label (`string`)

<a id="rst-broadcast-u32"></a>



#### broadcast (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-anycast-binary"></a>



#### anycast (`binary`)

<a id="rst-cacheinfo-binary"></a>



#### cacheinfo (`binary`)

- **struct**:

  [ifa-cacheinfo](#rst-rt-addr-definition-ifa-cacheinfo)

<a id="rst-multicast-binary"></a>



#### multicast (`binary`)

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **enum**:

  [ifa-flags](#rst-rt-addr-definition-ifa-flags)

- **enum-as-flags**:

  True

<a id="rst-rt-priority-u32"></a>



#### rt-priority (`u32`)

<a id="rst-target-netnsid-binary"></a>



#### target-netnsid (`binary`)

<a id="rst-proto-u8"></a>



#### proto (`u8`)

---

# Family rt-link netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the rt-link Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-rt-link-netlink-specification"></a>
<a id="rst-netlink-rt-link"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Link configuration over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-newlink"></a>
<a id="rst-rt-link-operation-newlink"></a>



### newlink



Create a new link.

- **attribute-set**:

  [link-attrs](#rst-rt-link-attribute-set-link-attrs)

- **fixed-header**:

  [ifinfomsg](#rst-rt-link-definition-ifinfomsg)

- **do**:

  **request**

  - **attributes**:

    \[`ifname`, `net-ns-pid`, `net-ns-fd`, `target-netnsid`, `link-netnsid`, `linkinfo`, `group`, `num-tx-queues`, `num-rx-queues`, `address`, `broadcast`, `mtu`, `txqlen`, `operstate`, `linkmode`, `gso-max-size`, `gso-max-segs`, `gro-max-size`, `gso-ipv4-max-size`, `gro-ipv4-max-size`, `af-spec`\]

<a id="rst-newlink-ntf"></a>
<a id="rst-rt-link-operation-newlink-ntf"></a>



### newlink-ntf



Notify that a link has been created

- **value**:

  16

- **notify**:

  getlink

- **fixed-header**:

  [ifinfomsg](#rst-rt-link-definition-ifinfomsg)

<a id="rst-dellink"></a>
<a id="rst-rt-link-operation-dellink"></a>



### dellink



Delete an existing link.

- **attribute-set**:

  [link-attrs](#rst-rt-link-attribute-set-link-attrs)

- **fixed-header**:

  [ifinfomsg](#rst-rt-link-definition-ifinfomsg)

- **do**:

  **request**

  - **attributes**:

    \[`ifname`\]

<a id="rst-getlink"></a>
<a id="rst-rt-link-operation-getlink"></a>



### getlink



Get / dump information about a link.

- **attribute-set**:

  [link-attrs](#rst-rt-link-attribute-set-link-attrs)

- **fixed-header**:

  [ifinfomsg](#rst-rt-link-definition-ifinfomsg)

- **do**:

  **request**

  - **attributes**:

    \[`ifname`, `alt-ifname`, `ext-mask`, `target-netnsid`\]

  **reply**

  - **attributes**:

    \[`address`, `broadcast`, `ifname`, `mtu`, `link`, `qdisc`, `stats`, `cost`, `priority`, `master`, `wireless`, `protinfo`, `txqlen`, `map`, `weight`, `operstate`, `linkmode`, `linkinfo`, `net-ns-pid`, `ifalias`, `num-vf`, `vfinfo-list`, `stats64`, `vf-ports`, `port-self`, `af-spec`, `group`, `net-ns-fd`, `ext-mask`, `promiscuity`, `num-tx-queues`, `num-rx-queues`, `carrier`, `phys-port-id`, `carrier-changes`, `phys-switch-id`, `link-netnsid`, `phys-port-name`, `proto-down`, `gso-max-segs`, `gso-max-size`, `pad`, `xdp`, `event`, `new-netnsid`, `target-netnsid`, `carrier-up-count`, `carrier-down-count`, `new-ifindex`, `min-mtu`, `max-mtu`, `prop-list`, `perm-address`, `proto-down-reason`, `parent-dev-name`, `parent-dev-bus-name`, `gro-max-size`, `tso-max-size`, `tso-max-segs`, `allmulti`, `devlink-port`, `gso-ipv4-max-size`, `gro-ipv4-max-size`\]

- **dump**:

  **request**

  - **attributes**:

    \[`target-netnsid`, `ext-mask`, `master`, `linkinfo`\]

  **reply**

  - **attributes**:

    \[`address`, `broadcast`, `ifname`, `mtu`, `link`, `qdisc`, `stats`, `cost`, `priority`, `master`, `wireless`, `protinfo`, `txqlen`, `map`, `weight`, `operstate`, `linkmode`, `linkinfo`, `net-ns-pid`, `ifalias`, `num-vf`, `vfinfo-list`, `stats64`, `vf-ports`, `port-self`, `af-spec`, `group`, `net-ns-fd`, `ext-mask`, `promiscuity`, `num-tx-queues`, `num-rx-queues`, `carrier`, `phys-port-id`, `carrier-changes`, `phys-switch-id`, `link-netnsid`, `phys-port-name`, `proto-down`, `gso-max-segs`, `gso-max-size`, `pad`, `xdp`, `event`, `new-netnsid`, `target-netnsid`, `carrier-up-count`, `carrier-down-count`, `new-ifindex`, `min-mtu`, `max-mtu`, `prop-list`, `perm-address`, `proto-down-reason`, `parent-dev-name`, `parent-dev-bus-name`, `gro-max-size`, `tso-max-size`, `tso-max-segs`, `allmulti`, `devlink-port`, `gso-ipv4-max-size`, `gro-ipv4-max-size`\]

<a id="rst-setlink"></a>
<a id="rst-rt-link-operation-setlink"></a>



### setlink



Set information about a link.

- **attribute-set**:

  [link-attrs](#rst-rt-link-attribute-set-link-attrs)

- **fixed-header**:

  [ifinfomsg](#rst-rt-link-definition-ifinfomsg)

- **do**:

  **request**

  - **attributes**:

    \[`address`, `broadcast`, `ifname`, `mtu`, `link`, `qdisc`, `stats`, `cost`, `priority`, `master`, `wireless`, `protinfo`, `txqlen`, `map`, `weight`, `operstate`, `linkmode`, `linkinfo`, `net-ns-pid`, `ifalias`, `num-vf`, `vfinfo-list`, `stats64`, `vf-ports`, `port-self`, `af-spec`, `group`, `net-ns-fd`, `ext-mask`, `promiscuity`, `num-tx-queues`, `num-rx-queues`, `carrier`, `phys-port-id`, `carrier-changes`, `phys-switch-id`, `link-netnsid`, `phys-port-name`, `proto-down`, `gso-max-segs`, `gso-max-size`, `pad`, `xdp`, `event`, `new-netnsid`, `target-netnsid`, `carrier-up-count`, `carrier-down-count`, `new-ifindex`, `min-mtu`, `max-mtu`, `prop-list`, `perm-address`, `proto-down-reason`, `parent-dev-name`, `parent-dev-bus-name`, `gro-max-size`, `tso-max-size`, `tso-max-segs`, `allmulti`, `devlink-port`, `gso-ipv4-max-size`, `gro-ipv4-max-size`\]

<a id="rst-getstats"></a>
<a id="rst-rt-link-operation-getstats"></a>



### getstats



Get / dump link stats.

- **attribute-set**:

  [stats-attrs](#rst-rt-link-attribute-set-stats-attrs)

- **fixed-header**:

  [if-stats-msg](#rst-rt-link-definition-if-stats-msg)

- **do**:

  **request**

  **reply**

  - **attributes**:

    \[`link-64`, `link-xstats`, `link-xstats-slave`, `link-offload-xstats`, `af-spec`\]

- **dump**:

  **request**

  **reply**

  - **attributes**:

    \[`link-64`, `link-xstats`, `link-xstats-slave`, `link-offload-xstats`, `af-spec`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- rtnlgrp-link


- rtnlgrp-stats


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ifinfo-flags"></a>
<a id="rst-rt-link-definition-ifinfo-flags"></a>



### ifinfo-flags

- **type**:

  flags

- **header**:

  linux/if.h

- **enum-name**:

  net-device-flags

- **name-prefix**:

  iff-

- **entries**:

  - **up**

  - **broadcast**

  - **debug**

  - **loopback**

  - **point-to-point**

  - **no-trailers**

  - **running**

  - **no-arp**

  - **promisc**

  - **all-multi**

  - **master**

  - **slave**

  - **multicast**

  - **portsel**

  - **auto-media**

  - **dynamic**

  - **lower-up**

  - **dormant**

  - **echo**

<a id="rst-vlan-protocols"></a>
<a id="rst-rt-link-definition-vlan-protocols"></a>



### vlan-protocols

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - **8021q**

  - **8021ad**

<a id="rst-rtgenmsg"></a>
<a id="rst-rt-link-definition-rtgenmsg"></a>



### rtgenmsg

- **type**:

  struct

- **members**:

  - **family (`u8`)**

<a id="rst-ifinfomsg"></a>
<a id="rst-rt-link-definition-ifinfomsg"></a>



### ifinfomsg

- **type**:

  struct

- **members**:

  - **ifi-family (`u8`)**

  - **ifi-type (`u16`)**

  - **ifi-index (`s32`)**

  - **ifi-flags (`u32`)**

  - **ifi-change (`u32`)**

<a id="rst-ifla-bridge-id"></a>
<a id="rst-rt-link-definition-ifla-bridge-id"></a>



### ifla-bridge-id

- **type**:

  struct

- **members**:

  - **prio (`u16`)**

  - **addr (`binary`)**

<a id="rst-ifla-cacheinfo"></a>
<a id="rst-rt-link-definition-ifla-cacheinfo"></a>



### ifla-cacheinfo

- **type**:

  struct

- **members**:

  - **max-reasm-len (`u32`)**

  - **tstamp (`u32`)**

  - **reachable-time (`s32`)**

  - **retrans-time (`u32`)**

<a id="rst-rtnl-link-stats"></a>
<a id="rst-rt-link-definition-rtnl-link-stats"></a>



### rtnl-link-stats

- **type**:

  struct

- **members**:

  - **rx-packets (`u32`)**

  - **tx-packets (`u32`)**

  - **rx-bytes (`u32`)**

  - **tx-bytes (`u32`)**

  - **rx-errors (`u32`)**

  - **tx-errors (`u32`)**

  - **rx-dropped (`u32`)**

  - **tx-dropped (`u32`)**

  - **multicast (`u32`)**

  - **collisions (`u32`)**

  - **rx-length-errors (`u32`)**

  - **rx-over-errors (`u32`)**

  - **rx-crc-errors (`u32`)**

  - **rx-frame-errors (`u32`)**

  - **rx-fifo-errors (`u32`)**

  - **rx-missed-errors (`u32`)**

  - **tx-aborted-errors (`u32`)**

  - **tx-carrier-errors (`u32`)**

  - **tx-fifo-errors (`u32`)**

  - **tx-heartbeat-errors (`u32`)**

  - **tx-window-errors (`u32`)**

  - **rx-compressed (`u32`)**

  - **tx-compressed (`u32`)**

  - **rx-nohandler (`u32`)**

<a id="rst-rtnl-link-stats64"></a>
<a id="rst-rt-link-definition-rtnl-link-stats64"></a>



### rtnl-link-stats64

- **type**:

  struct

- **members**:

  - **rx-packets (`u64`)**

  - **tx-packets (`u64`)**

  - **rx-bytes (`u64`)**

  - **tx-bytes (`u64`)**

  - **rx-errors (`u64`)**

  - **tx-errors (`u64`)**

  - **rx-dropped (`u64`)**

  - **tx-dropped (`u64`)**

  - **multicast (`u64`)**

  - **collisions (`u64`)**

  - **rx-length-errors (`u64`)**

  - **rx-over-errors (`u64`)**

  - **rx-crc-errors (`u64`)**

  - **rx-frame-errors (`u64`)**

  - **rx-fifo-errors (`u64`)**

  - **rx-missed-errors (`u64`)**

  - **tx-aborted-errors (`u64`)**

  - **tx-carrier-errors (`u64`)**

  - **tx-fifo-errors (`u64`)**

  - **tx-heartbeat-errors (`u64`)**

  - **tx-window-errors (`u64`)**

  - **rx-compressed (`u64`)**

  - **tx-compressed (`u64`)**

  - **rx-nohandler (`u64`)**

  - **rx-otherhost-dropped (`u64`)**

<a id="rst-rtnl-link-ifmap"></a>
<a id="rst-rt-link-definition-rtnl-link-ifmap"></a>



### rtnl-link-ifmap

- **type**:

  struct

- **members**:

  - **mem-start (`u64`)**

  - **mem-end (`u64`)**

  - **base-addr (`u64`)**

  - **irq (`u16`)**

  - **dma (`u8`)**

  - **port (`u8`)**

<a id="rst-ipv4-devconf"></a>
<a id="rst-rt-link-definition-ipv4-devconf"></a>



### ipv4-devconf

- **enum-name**:

  None

- **type**:

  enum

- **entries**:

  - **forwarding**

  - **mc-forwarding**

  - **proxy-arp**

  - **accept-redirects**

  - **secure-redirects**

  - **send-redirects**

  - **shared-media**

  - **rp-filter**

  - **accept-source-route**

  - **bootp-relay**

  - **log-martians**

  - **tag**

  - **arpfilter**

  - **medium-id**

  - **noxfrm**

  - **nopolicy**

  - **force-igmp-version**

  - **arp-announce**

  - **arp-ignore**

  - **promote-secondaries**

  - **arp-accept**

  - **arp-notify**

  - **accept-local**

  - **src-vmark**

  - **proxy-arp-pvlan**

  - **route-localnet**

  - **igmpv2-unsolicited-report-interval**

  - **igmpv3-unsolicited-report-interval**

  - **ignore-routes-with-linkdown**

  - **drop-unicast-in-l2-multicast**

  - **drop-gratuitous-arp**

  - **bc-forwarding**

  - **arp-evict-nocarrier**

<a id="rst-ipv6-devconf"></a>
<a id="rst-rt-link-definition-ipv6-devconf"></a>



### ipv6-devconf

- **enum-name**:

  None

- **type**:

  enum

- **entries**:

  - **forwarding**

  - **hoplimit**

  - **mtu6**

  - **accept-ra**

  - **accept-redirects**

  - **autoconf**

  - **dad-transmits**

  - **rtr-solicits**

  - **rtr-solicit-interval**

  - **rtr-solicit-delay**

  - **use-tempaddr**

  - **temp-valid-lft**

  - **temp-prefered-lft**

  - **regen-max-retry**

  - **max-desync-factor**

  - **max-addresses**

  - **force-mld-version**

  - **accept-ra-defrtr**

  - **accept-ra-pinfo**

  - **accept-ra-rtr-pref**

  - **rtr-probe-interval**

  - **accept-ra-rt-info-max-plen**

  - **proxy-ndp**

  - **optimistic-dad**

  - **accept-source-route**

  - **mc-forwarding**

  - **disable-ipv6**

  - **accept-dad**

  - **force-tllao**

  - **ndisc-notify**

  - **mldv1-unsolicited-report-interval**

  - **mldv2-unsolicited-report-interval**

  - **suppress-frag-ndisc**

  - **accept-ra-from-local**

  - **use-optimistic**

  - **accept-ra-mtu**

  - **stable-secret**

  - **use-oif-addrs-only**

  - **accept-ra-min-hop-limit**

  - **ignore-routes-with-linkdown**

  - **drop-unicast-in-l2-multicast**

  - **drop-unsolicited-na**

  - **keep-addr-on-down**

  - **rtr-solicit-max-interval**

  - **seg6-enabled**

  - **seg6-require-hmac**

  - **enhanced-dad**

  - **addr-gen-mode**

  - **disable-policy**

  - **accept-ra-rt-info-min-plen**

  - **ndisc-tclass**

  - **rpl-seg-enabled**

  - **ra-defrtr-metric**

  - **ioam6-enabled**

  - **ioam6-id**

  - **ioam6-id-wide**

  - **ndisc-evict-nocarrier**

  - **accept-untracked-na**

<a id="rst-ifla-icmp6-stats"></a>
<a id="rst-rt-link-definition-ifla-icmp6-stats"></a>



### ifla-icmp6-stats

- **enum-name**:

  None

- **type**:

  enum

- **entries**:

  - **num**

  - **inmsgs**

  - **inerrors**

  - **outmsgs**

  - **outerrors**

  - **csumerrors**

  - **ratelimithost**

<a id="rst-ifla-inet6-stats"></a>
<a id="rst-rt-link-definition-ifla-inet6-stats"></a>



### ifla-inet6-stats

- **enum-name**:

  None

- **type**:

  enum

- **entries**:

  - **num**

  - **inpkts**

  - **inoctets**

  - **indelivers**

  - **outforwdatagrams**

  - **outpkts**

  - **outoctets**

  - **inhdrerrors**

  - **intoobigerrors**

  - **innoroutes**

  - **inaddrerrors**

  - **inunknownprotos**

  - **intruncatedpkts**

  - **indiscards**

  - **outdiscards**

  - **outnoroutes**

  - **reasmtimeout**

  - **reasmreqds**

  - **reasmoks**

  - **reasmfails**

  - **fragoks**

  - **fragfails**

  - **fragcreates**

  - **inmcastpkts**

  - **outmcastpkts**

  - **inbcastpkts**

  - **outbcastpkts**

  - **inmcastoctets**

  - **outmcastoctets**

  - **inbcastoctets**

  - **outbcastoctets**

  - **csumerrors**

  - **noectpkts**

  - **ect1-pkts**

  - **ect0-pkts**

  - **cepkts**

  - **reasm-overlaps**

<a id="rst-br-boolopt-multi"></a>
<a id="rst-rt-link-definition-br-boolopt-multi"></a>



### br-boolopt-multi

- **type**:

  struct

- **header**:

  linux/if\_bridge.h

- **members**:

  - **optval (`u32`)**

  - **optmask (`u32`)**

<a id="rst-if-stats-msg"></a>
<a id="rst-rt-link-definition-if-stats-msg"></a>



### if-stats-msg

- **type**:

  struct

- **members**:

  - **family (`u8`)**

  - **ifindex (`u32`)**

  - **filter-mask (`u32`)**

<a id="rst-ifla-vlan-flags"></a>
<a id="rst-rt-link-definition-ifla-vlan-flags"></a>



### ifla-vlan-flags

- **type**:

  struct

- **members**:

  - **flags (`u32`)**

  - **mask (`u32`)**

<a id="rst-vlan-flags"></a>
<a id="rst-rt-link-definition-vlan-flags"></a>



### vlan-flags

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `reorder-hdr`


  - `gvrp`


  - `loose-binding`


  - `mvrp`


  - `bridge-binding`

<a id="rst-ifla-vlan-qos-mapping"></a>
<a id="rst-rt-link-definition-ifla-vlan-qos-mapping"></a>



### ifla-vlan-qos-mapping

- **type**:

  struct

- **members**:

  - **from (`u32`)**

  - **to (`u32`)**

<a id="rst-ifla-geneve-port-range"></a>
<a id="rst-rt-link-definition-ifla-geneve-port-range"></a>



### ifla-geneve-port-range

- **type**:

  struct

- **members**:

  - **low (`u16`)**

  - **high (`u16`)**

<a id="rst-ifla-vf-mac"></a>
<a id="rst-rt-link-definition-ifla-vf-mac"></a>



### ifla-vf-mac

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **mac (`binary`)**

<a id="rst-ifla-vf-vlan"></a>
<a id="rst-rt-link-definition-ifla-vf-vlan"></a>



### ifla-vf-vlan

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **vlan (`u32`)**

  - **qos (`u32`)**

<a id="rst-ifla-vf-tx-rate"></a>
<a id="rst-rt-link-definition-ifla-vf-tx-rate"></a>



### ifla-vf-tx-rate

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **rate (`u32`)**

<a id="rst-ifla-vf-spoofchk"></a>
<a id="rst-rt-link-definition-ifla-vf-spoofchk"></a>



### ifla-vf-spoofchk

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **setting (`u32`)**

<a id="rst-ifla-vf-link-state"></a>
<a id="rst-rt-link-definition-ifla-vf-link-state"></a>



### ifla-vf-link-state

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **link-state (`u32`)**

<a id="rst-ifla-vf-link-state-enum"></a>
<a id="rst-rt-link-definition-ifla-vf-link-state-enum"></a>



### ifla-vf-link-state-enum

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - `auto`


  - `enable`


  - `disable`

<a id="rst-ifla-vf-rate"></a>
<a id="rst-rt-link-definition-ifla-vf-rate"></a>



### ifla-vf-rate

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **min-tx-rate (`u32`)**

  - **max-tx-rate (`u32`)**

<a id="rst-ifla-vf-rss-query-en"></a>
<a id="rst-rt-link-definition-ifla-vf-rss-query-en"></a>



### ifla-vf-rss-query-en

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **setting (`u32`)**

<a id="rst-ifla-vf-trust"></a>
<a id="rst-rt-link-definition-ifla-vf-trust"></a>



### ifla-vf-trust

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **setting (`u32`)**

<a id="rst-ifla-vf-guid"></a>
<a id="rst-rt-link-definition-ifla-vf-guid"></a>



### ifla-vf-guid

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **guid (`u64`)**

<a id="rst-ifla-vf-vlan-info"></a>
<a id="rst-rt-link-definition-ifla-vf-vlan-info"></a>



### ifla-vf-vlan-info

- **type**:

  struct

- **members**:

  - **vf (`u32`)**

  - **vlan (`u32`)**

  - **qos (`u32`)**

  - **vlan-proto (`u32`)**

<a id="rst-rtext-filter"></a>
<a id="rst-rt-link-definition-rtext-filter"></a>



### rtext-filter

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `vf`


  - `brvlan`


  - `brvlan-compressed`


  - `skip-stats`


  - `mrp`


  - `cfm-config`


  - `cfm-status`


  - `mst`

<a id="rst-netkit-policy"></a>
<a id="rst-rt-link-definition-netkit-policy"></a>



### netkit-policy

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - **forward**

  - **blackhole**

<a id="rst-netkit-mode"></a>
<a id="rst-rt-link-definition-netkit-mode"></a>



### netkit-mode

- **type**:

  enum

- **enum-name**:

  netkit-mode

- **entries**:

  - **l2**

  - **l3**

<a id="rst-netkit-scrub"></a>
<a id="rst-rt-link-definition-netkit-scrub"></a>



### netkit-scrub

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - **none**

  - **default**

<a id="rst-ovpn-mode"></a>
<a id="rst-rt-link-definition-ovpn-mode"></a>



### ovpn-mode

- **enum-name**:

  ovpn-mode

- **name-prefix**:

  ovpn-mode

- **type**:

  enum

- **entries**:

  - `p2p`


  - `mp`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-link-attrs"></a>
<a id="rst-rt-link-attribute-set-link-attrs"></a>



### link-attrs

<a id="rst-address-binary"></a>



#### address (`binary`)

- **display-hint**:

  mac

<a id="rst-broadcast-binary"></a>



#### broadcast (`binary`)

- **display-hint**:

  mac

<a id="rst-ifname-string"></a>



#### ifname (`string`)

<a id="rst-mtu-u32"></a>



#### mtu (`u32`)

<a id="rst-link-u32"></a>



#### link (`u32`)

<a id="rst-qdisc-string"></a>



#### qdisc (`string`)

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [rtnl-link-stats](#rst-rt-link-definition-rtnl-link-stats)

<a id="rst-cost-string"></a>



#### cost (`string`)

<a id="rst-priority-string"></a>



#### priority (`string`)

<a id="rst-master-u32"></a>



#### master (`u32`)

<a id="rst-wireless-string"></a>



#### wireless (`string`)

<a id="rst-protinfo-string"></a>



#### protinfo (`string`)

<a id="rst-txqlen-u32"></a>



#### txqlen (`u32`)

<a id="rst-map-binary"></a>



#### map (`binary`)

- **struct**:

  [rtnl-link-ifmap](#rst-rt-link-definition-rtnl-link-ifmap)

<a id="rst-weight-u32"></a>



#### weight (`u32`)

<a id="rst-operstate-u8"></a>



#### operstate (`u8`)

<a id="rst-linkmode-u8"></a>



#### linkmode (`u8`)

<a id="rst-linkinfo-nest"></a>



#### linkinfo (`nest`)

- **nested-attributes**:

  [linkinfo-attrs](#rst-rt-link-attribute-set-linkinfo-attrs)

<a id="rst-net-ns-pid-u32"></a>



#### net-ns-pid (`u32`)

<a id="rst-ifalias-string"></a>



#### ifalias (`string`)

<a id="rst-num-vf-u32"></a>



#### num-vf (`u32`)

<a id="rst-vfinfo-list-nest"></a>



#### vfinfo-list (`nest`)

- **nested-attributes**:

  [vfinfo-list-attrs](#rst-rt-link-attribute-set-vfinfo-list-attrs)

<a id="rst-stats64-binary"></a>



#### stats64 (`binary`)

- **struct**:

  [rtnl-link-stats64](#rst-rt-link-definition-rtnl-link-stats64)

<a id="rst-vf-ports-nest"></a>



#### vf-ports (`nest`)

- **nested-attributes**:

  [vf-ports-attrs](#rst-rt-link-attribute-set-vf-ports-attrs)

<a id="rst-port-self-nest"></a>



#### port-self (`nest`)

- **nested-attributes**:

  [port-self-attrs](#rst-rt-link-attribute-set-port-self-attrs)

<a id="rst-af-spec-nest"></a>



#### af-spec (`nest`)

- **nested-attributes**:

  [af-spec-attrs](#rst-rt-link-attribute-set-af-spec-attrs)

<a id="rst-group-u32"></a>



#### group (`u32`)

<a id="rst-net-ns-fd-u32"></a>



#### net-ns-fd (`u32`)

<a id="rst-ext-mask-u32"></a>



#### ext-mask (`u32`)

- **enum**:

  [rtext-filter](#rst-rt-link-definition-rtext-filter)

- **enum-as-flags**:

  True

<a id="rst-promiscuity-u32"></a>



#### promiscuity (`u32`)

<a id="rst-num-tx-queues-u32"></a>



#### num-tx-queues (`u32`)

<a id="rst-num-rx-queues-u32"></a>



#### num-rx-queues (`u32`)

<a id="rst-carrier-u8"></a>



#### carrier (`u8`)

<a id="rst-phys-port-id-binary"></a>



#### phys-port-id (`binary`)

<a id="rst-carrier-changes-u32"></a>



#### carrier-changes (`u32`)

<a id="rst-phys-switch-id-binary"></a>



#### phys-switch-id (`binary`)

<a id="rst-link-netnsid-s32"></a>



#### link-netnsid (`s32`)

<a id="rst-phys-port-name-string"></a>



#### phys-port-name (`string`)

<a id="rst-proto-down-u8"></a>



#### proto-down (`u8`)

<a id="rst-gso-max-segs-u32"></a>



#### gso-max-segs (`u32`)

<a id="rst-gso-max-size-u32"></a>



#### gso-max-size (`u32`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-xdp-nest"></a>



#### xdp (`nest`)

- **nested-attributes**:

  [xdp-attrs](#rst-rt-link-attribute-set-xdp-attrs)

<a id="rst-event-u32"></a>



#### event (`u32`)

<a id="rst-new-netnsid-s32"></a>



#### new-netnsid (`s32`)

<a id="rst-target-netnsid-s32"></a>



#### target-netnsid (`s32`)

<a id="rst-carrier-up-count-u32"></a>



#### carrier-up-count (`u32`)

<a id="rst-carrier-down-count-u32"></a>



#### carrier-down-count (`u32`)

<a id="rst-new-ifindex-s32"></a>



#### new-ifindex (`s32`)

<a id="rst-min-mtu-u32"></a>



#### min-mtu (`u32`)

<a id="rst-max-mtu-u32"></a>



#### max-mtu (`u32`)

<a id="rst-prop-list-nest"></a>



#### prop-list (`nest`)

- **nested-attributes**:

  [prop-list-link-attrs](#rst-rt-link-attribute-set-prop-list-link-attrs)

<a id="rst-alt-ifname-string"></a>



#### alt-ifname (`string`)

<a id="rst-perm-address-binary"></a>



#### perm-address (`binary`)

- **display-hint**:

  mac

<a id="rst-proto-down-reason-string"></a>



#### proto-down-reason (`string`)

<a id="rst-parent-dev-name-string"></a>



#### parent-dev-name (`string`)

<a id="rst-parent-dev-bus-name-string"></a>



#### parent-dev-bus-name (`string`)

<a id="rst-gro-max-size-u32"></a>



#### gro-max-size (`u32`)

<a id="rst-tso-max-size-u32"></a>



#### tso-max-size (`u32`)

<a id="rst-tso-max-segs-u32"></a>



#### tso-max-segs (`u32`)

<a id="rst-allmulti-u32"></a>



#### allmulti (`u32`)

<a id="rst-devlink-port-binary"></a>



#### devlink-port (`binary`)

<a id="rst-gso-ipv4-max-size-u32"></a>



#### gso-ipv4-max-size (`u32`)

<a id="rst-gro-ipv4-max-size-u32"></a>



#### gro-ipv4-max-size (`u32`)

<a id="rst-dpll-pin-nest"></a>



#### dpll-pin (`nest`)

- **nested-attributes**:

  [link-dpll-pin-attrs](#rst-rt-link-attribute-set-link-dpll-pin-attrs)

<a id="rst-max-pacing-offload-horizon-uint"></a>



#### max-pacing-offload-horizon (`uint`)

- **doc**:

  EDT offload horizon supported by the device (in nsec).

<a id="rst-netns-immutable-u8"></a>



#### netns-immutable (`u8`)

<a id="rst-headroom-u16"></a>



#### headroom (`u16`)

<a id="rst-tailroom-u16"></a>



#### tailroom (`u16`)

<a id="rst-prop-list-link-attrs"></a>
<a id="rst-rt-link-attribute-set-prop-list-link-attrs"></a>



### prop-list-link-attrs

<a id="rst-alt-ifname"></a>



#### alt-ifname

- **multi-attr**:

  True

<a id="rst-af-spec-attrs"></a>
<a id="rst-rt-link-attribute-set-af-spec-attrs"></a>



### af-spec-attrs

<a id="rst-inet-nest"></a>



#### inet (`nest`)

- **value**:

  2

- **nested-attributes**:

  [ifla-attrs](#rst-rt-link-attribute-set-ifla-attrs)

<a id="rst-inet6-nest"></a>



#### inet6 (`nest`)

- **value**:

  10

- **nested-attributes**:

  [ifla6-attrs](#rst-rt-link-attribute-set-ifla6-attrs)

<a id="rst-mctp-nest"></a>



#### mctp (`nest`)

- **value**:

  45

- **nested-attributes**:

  [mctp-attrs](#rst-rt-link-attribute-set-mctp-attrs)

<a id="rst-vfinfo-list-attrs"></a>
<a id="rst-rt-link-attribute-set-vfinfo-list-attrs"></a>



### vfinfo-list-attrs

<a id="rst-info-nest"></a>



#### info (`nest`)

- **nested-attributes**:

  [vfinfo-attrs](#rst-rt-link-attribute-set-vfinfo-attrs)

- **multi-attr**:

  True

<a id="rst-vfinfo-attrs"></a>
<a id="rst-rt-link-attribute-set-vfinfo-attrs"></a>



### vfinfo-attrs

<a id="rst-mac-binary"></a>



#### mac (`binary`)

- **struct**:

  [ifla-vf-mac](#rst-rt-link-definition-ifla-vf-mac)

<a id="rst-vlan-binary"></a>



#### vlan (`binary`)

- **struct**:

  [ifla-vf-vlan](#rst-rt-link-definition-ifla-vf-vlan)

<a id="rst-tx-rate-binary"></a>



#### tx-rate (`binary`)

- **struct**:

  [ifla-vf-tx-rate](#rst-rt-link-definition-ifla-vf-tx-rate)

<a id="rst-spoofchk-binary"></a>



#### spoofchk (`binary`)

- **struct**:

  [ifla-vf-spoofchk](#rst-rt-link-definition-ifla-vf-spoofchk)

<a id="rst-link-state-binary"></a>



#### link-state (`binary`)

- **struct**:

  [ifla-vf-link-state](#rst-rt-link-definition-ifla-vf-link-state)

<a id="rst-rate-binary"></a>



#### rate (`binary`)

- **struct**:

  [ifla-vf-rate](#rst-rt-link-definition-ifla-vf-rate)

<a id="rst-rss-query-en-binary"></a>



#### rss-query-en (`binary`)

- **struct**:

  [ifla-vf-rss-query-en](#rst-rt-link-definition-ifla-vf-rss-query-en)

<a id="rst-stats-nest"></a>



#### stats (`nest`)

- **nested-attributes**:

  [vf-stats-attrs](#rst-rt-link-attribute-set-vf-stats-attrs)

<a id="rst-trust-binary"></a>



#### trust (`binary`)

- **struct**:

  [ifla-vf-trust](#rst-rt-link-definition-ifla-vf-trust)

<a id="rst-ib-node-guid-binary"></a>



#### ib-node-guid (`binary`)

- **struct**:

  [ifla-vf-guid](#rst-rt-link-definition-ifla-vf-guid)

<a id="rst-ib-port-guid-binary"></a>



#### ib-port-guid (`binary`)

- **struct**:

  [ifla-vf-guid](#rst-rt-link-definition-ifla-vf-guid)

<a id="rst-vlan-list-nest"></a>



#### vlan-list (`nest`)

- **nested-attributes**:

  [vf-vlan-attrs](#rst-rt-link-attribute-set-vf-vlan-attrs)

<a id="rst-broadcast-binary-1"></a>



#### broadcast (`binary`)

<a id="rst-vf-stats-attrs"></a>
<a id="rst-rt-link-attribute-set-vf-stats-attrs"></a>



### vf-stats-attrs

<a id="rst-rx-packets-u64"></a>



#### rx-packets (`u64`)

- **value**:

  0

<a id="rst-tx-packets-u64"></a>



#### tx-packets (`u64`)

<a id="rst-rx-bytes-u64"></a>



#### rx-bytes (`u64`)

<a id="rst-tx-bytes-u64"></a>



#### tx-bytes (`u64`)

<a id="rst-broadcast-u64"></a>



#### broadcast (`u64`)

<a id="rst-multicast-u64"></a>



#### multicast (`u64`)

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-rx-dropped-u64"></a>



#### rx-dropped (`u64`)

<a id="rst-tx-dropped-u64"></a>



#### tx-dropped (`u64`)

<a id="rst-vf-vlan-attrs"></a>
<a id="rst-rt-link-attribute-set-vf-vlan-attrs"></a>



### vf-vlan-attrs

<a id="rst-info-binary"></a>



#### info (`binary`)

- **struct**:

  [ifla-vf-vlan-info](#rst-rt-link-definition-ifla-vf-vlan-info)

- **multi-attr**:

  True

<a id="rst-vf-ports-attrs"></a>
<a id="rst-rt-link-attribute-set-vf-ports-attrs"></a>



### vf-ports-attrs

<a id="rst-port-self-attrs"></a>
<a id="rst-rt-link-attribute-set-port-self-attrs"></a>



### port-self-attrs

<a id="rst-linkinfo-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-attrs"></a>



### linkinfo-attrs

<a id="rst-kind-string"></a>



#### kind (`string`)

<a id="rst-data-sub-message"></a>



#### data (`sub-message`)

- **sub-message**:

  [linkinfo-data-msg](#rst-rt-link-sub-message-linkinfo-data-msg)

- **selector**:

  kind

<a id="rst-xstats-binary"></a>



#### xstats (`binary`)

<a id="rst-slave-kind-string"></a>



#### slave-kind (`string`)

<a id="rst-slave-data-sub-message"></a>



#### slave-data (`sub-message`)

- **sub-message**:

  [linkinfo-member-data-msg](#rst-rt-link-sub-message-linkinfo-member-data-msg)

- **selector**:

  slave-kind

<a id="rst-linkinfo-bond-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-bond-attrs"></a>



### linkinfo-bond-attrs

<a id="rst-mode-u8"></a>



#### mode (`u8`)

<a id="rst-active-slave-u32"></a>



#### active-slave (`u32`)

<a id="rst-miimon-u32"></a>



#### miimon (`u32`)

<a id="rst-updelay-u32"></a>



#### updelay (`u32`)

<a id="rst-downdelay-u32"></a>



#### downdelay (`u32`)

<a id="rst-use-carrier-u8"></a>



#### use-carrier (`u8`)

<a id="rst-arp-interval-u32"></a>



#### arp-interval (`u32`)

<a id="rst-arp-ip-target-indexed-array"></a>



#### arp-ip-target (`indexed-array`)

- **sub-type**:

  u32

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-arp-validate-u32"></a>



#### arp-validate (`u32`)

<a id="rst-arp-all-targets-u32"></a>



#### arp-all-targets (`u32`)

<a id="rst-primary-u32"></a>



#### primary (`u32`)

<a id="rst-primary-reselect-u8"></a>



#### primary-reselect (`u8`)

<a id="rst-fail-over-mac-u8"></a>



#### fail-over-mac (`u8`)

<a id="rst-xmit-hash-policy-u8"></a>



#### xmit-hash-policy (`u8`)

<a id="rst-resend-igmp-u32"></a>



#### resend-igmp (`u32`)

<a id="rst-num-peer-notif-u8"></a>



#### num-peer-notif (`u8`)

<a id="rst-all-slaves-active-u8"></a>



#### all-slaves-active (`u8`)

<a id="rst-min-links-u32"></a>



#### min-links (`u32`)

<a id="rst-lp-interval-u32"></a>



#### lp-interval (`u32`)

<a id="rst-packets-per-slave-u32"></a>



#### packets-per-slave (`u32`)

<a id="rst-ad-lacp-rate-u8"></a>



#### ad-lacp-rate (`u8`)

<a id="rst-ad-select-u8"></a>



#### ad-select (`u8`)

<a id="rst-ad-info-nest"></a>



#### ad-info (`nest`)

- **nested-attributes**:

  [bond-ad-info-attrs](#rst-rt-link-attribute-set-bond-ad-info-attrs)

<a id="rst-ad-actor-sys-prio-u16"></a>



#### ad-actor-sys-prio (`u16`)

<a id="rst-ad-user-port-key-u16"></a>



#### ad-user-port-key (`u16`)

<a id="rst-ad-actor-system-binary"></a>



#### ad-actor-system (`binary`)

- **display-hint**:

  mac

<a id="rst-tlb-dynamic-lb-u8"></a>



#### tlb-dynamic-lb (`u8`)

<a id="rst-peer-notif-delay-u32"></a>



#### peer-notif-delay (`u32`)

<a id="rst-ad-lacp-active-u8"></a>



#### ad-lacp-active (`u8`)

<a id="rst-missed-max-u8"></a>



#### missed-max (`u8`)

<a id="rst-ns-ip6-target-indexed-array"></a>



#### ns-ip6-target (`indexed-array`)

- **sub-type**:

  binary

- **display-hint**:

  ipv6

<a id="rst-coupled-control-u8"></a>



#### coupled-control (`u8`)

<a id="rst-bond-ad-info-attrs"></a>
<a id="rst-rt-link-attribute-set-bond-ad-info-attrs"></a>



### bond-ad-info-attrs

<a id="rst-aggregator-u16"></a>



#### aggregator (`u16`)

<a id="rst-num-ports-u16"></a>



#### num-ports (`u16`)

<a id="rst-actor-key-u16"></a>



#### actor-key (`u16`)

<a id="rst-partner-key-u16"></a>



#### partner-key (`u16`)

<a id="rst-partner-mac-binary"></a>



#### partner-mac (`binary`)

- **display-hint**:

  mac

<a id="rst-bond-slave-attrs"></a>
<a id="rst-rt-link-attribute-set-bond-slave-attrs"></a>



### bond-slave-attrs

<a id="rst-state-u8"></a>



#### state (`u8`)

<a id="rst-mii-status-u8"></a>



#### mii-status (`u8`)

<a id="rst-link-failure-count-u32"></a>



#### link-failure-count (`u32`)

<a id="rst-perm-hwaddr-binary"></a>



#### perm-hwaddr (`binary`)

- **display-hint**:

  mac

<a id="rst-queue-id-u16"></a>



#### queue-id (`u16`)

<a id="rst-ad-aggregator-id-u16"></a>



#### ad-aggregator-id (`u16`)

<a id="rst-ad-actor-oper-port-state-u8"></a>



#### ad-actor-oper-port-state (`u8`)

<a id="rst-ad-partner-oper-port-state-u16"></a>



#### ad-partner-oper-port-state (`u16`)

<a id="rst-prio-u32"></a>



#### prio (`u32`)

<a id="rst-linkinfo-bridge-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-bridge-attrs"></a>



### linkinfo-bridge-attrs

<a id="rst-forward-delay-u32"></a>



#### forward-delay (`u32`)

<a id="rst-hello-time-u32"></a>



#### hello-time (`u32`)

<a id="rst-max-age-u32"></a>



#### max-age (`u32`)

<a id="rst-ageing-time-u32"></a>



#### ageing-time (`u32`)

<a id="rst-stp-state-u32"></a>



#### stp-state (`u32`)

<a id="rst-priority-u16"></a>



#### priority (`u16`)

<a id="rst-vlan-filtering-u8"></a>



#### vlan-filtering (`u8`)

<a id="rst-vlan-protocol-u16"></a>



#### vlan-protocol (`u16`)

<a id="rst-group-fwd-mask-u16"></a>



#### group-fwd-mask (`u16`)

<a id="rst-root-id-binary"></a>



#### root-id (`binary`)

- **struct**:

  [ifla-bridge-id](#rst-rt-link-definition-ifla-bridge-id)

<a id="rst-bridge-id-binary"></a>



#### bridge-id (`binary`)

- **struct**:

  [ifla-bridge-id](#rst-rt-link-definition-ifla-bridge-id)

<a id="rst-root-port-u16"></a>



#### root-port (`u16`)

<a id="rst-root-path-cost-u32"></a>



#### root-path-cost (`u32`)

<a id="rst-topology-change-u8"></a>



#### topology-change (`u8`)

<a id="rst-topology-change-detected-u8"></a>



#### topology-change-detected (`u8`)

<a id="rst-hello-timer-u64"></a>



#### hello-timer (`u64`)

<a id="rst-tcn-timer-u64"></a>



#### tcn-timer (`u64`)

<a id="rst-topology-change-timer-u64"></a>



#### topology-change-timer (`u64`)

<a id="rst-gc-timer-u64"></a>



#### gc-timer (`u64`)

<a id="rst-group-addr-binary"></a>



#### group-addr (`binary`)

- **display-hint**:

  mac

<a id="rst-fdb-flush-binary"></a>



#### fdb-flush (`binary`)

<a id="rst-mcast-router-u8"></a>



#### mcast-router (`u8`)

<a id="rst-mcast-snooping-u8"></a>



#### mcast-snooping (`u8`)

<a id="rst-mcast-query-use-ifaddr-u8"></a>



#### mcast-query-use-ifaddr (`u8`)

<a id="rst-mcast-querier-u8"></a>



#### mcast-querier (`u8`)

<a id="rst-mcast-hash-elasticity-u32"></a>



#### mcast-hash-elasticity (`u32`)

<a id="rst-mcast-hash-max-u32"></a>



#### mcast-hash-max (`u32`)

<a id="rst-mcast-last-member-cnt-u32"></a>



#### mcast-last-member-cnt (`u32`)

<a id="rst-mcast-startup-query-cnt-u32"></a>



#### mcast-startup-query-cnt (`u32`)

<a id="rst-mcast-last-member-intvl-u64"></a>



#### mcast-last-member-intvl (`u64`)

<a id="rst-mcast-membership-intvl-u64"></a>



#### mcast-membership-intvl (`u64`)

<a id="rst-mcast-querier-intvl-u64"></a>



#### mcast-querier-intvl (`u64`)

<a id="rst-mcast-query-intvl-u64"></a>



#### mcast-query-intvl (`u64`)

<a id="rst-mcast-query-response-intvl-u64"></a>



#### mcast-query-response-intvl (`u64`)

<a id="rst-mcast-startup-query-intvl-u64"></a>



#### mcast-startup-query-intvl (`u64`)

<a id="rst-nf-call-iptables-u8"></a>



#### nf-call-iptables (`u8`)

<a id="rst-nf-call-ip6tables-u8"></a>



#### nf-call-ip6tables (`u8`)

<a id="rst-nf-call-arptables-u8"></a>



#### nf-call-arptables (`u8`)

<a id="rst-vlan-default-pvid-u16"></a>



#### vlan-default-pvid (`u16`)

<a id="rst-pad-pad-2"></a>



#### pad (`pad`)

<a id="rst-vlan-stats-enabled-u8"></a>



#### vlan-stats-enabled (`u8`)

<a id="rst-mcast-stats-enabled-u8"></a>



#### mcast-stats-enabled (`u8`)

<a id="rst-mcast-igmp-version-u8"></a>



#### mcast-igmp-version (`u8`)

<a id="rst-mcast-mld-version-u8"></a>



#### mcast-mld-version (`u8`)

<a id="rst-vlan-stats-per-port-u8"></a>



#### vlan-stats-per-port (`u8`)

<a id="rst-multi-boolopt-binary"></a>



#### multi-boolopt (`binary`)

- **struct**:

  [br-boolopt-multi](#rst-rt-link-definition-br-boolopt-multi)

<a id="rst-mcast-querier-state-binary"></a>



#### mcast-querier-state (`binary`)

<a id="rst-fdb-n-learned-u32"></a>



#### fdb-n-learned (`u32`)

<a id="rst-fdb-max-learned-u32"></a>



#### fdb-max-learned (`u32`)

<a id="rst-linkinfo-brport-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-brport-attrs"></a>



### linkinfo-brport-attrs

<a id="rst-state-u8-1"></a>



#### state (`u8`)

<a id="rst-priority-u16-1"></a>



#### priority (`u16`)

<a id="rst-cost-u32"></a>



#### cost (`u32`)

<a id="rst-mode-flag"></a>



#### mode (`flag`)

<a id="rst-guard-flag"></a>



#### guard (`flag`)

<a id="rst-protect-flag"></a>



#### protect (`flag`)

<a id="rst-fast-leave-flag"></a>



#### fast-leave (`flag`)

<a id="rst-learning-flag"></a>



#### learning (`flag`)

<a id="rst-unicast-flood-flag"></a>



#### unicast-flood (`flag`)

<a id="rst-proxyarp-flag"></a>



#### proxyarp (`flag`)

<a id="rst-learning-sync-flag"></a>



#### learning-sync (`flag`)

<a id="rst-proxyarp-wifi-flag"></a>



#### proxyarp-wifi (`flag`)

<a id="rst-root-id-binary-1"></a>



#### root-id (`binary`)

- **struct**:

  [ifla-bridge-id](#rst-rt-link-definition-ifla-bridge-id)

<a id="rst-bridge-id-binary-1"></a>



#### bridge-id (`binary`)

- **struct**:

  [ifla-bridge-id](#rst-rt-link-definition-ifla-bridge-id)

<a id="rst-designated-port-u16"></a>



#### designated-port (`u16`)

<a id="rst-designated-cost-u16"></a>



#### designated-cost (`u16`)

<a id="rst-id-u16"></a>



#### id (`u16`)

<a id="rst-no-u16"></a>



#### no (`u16`)

<a id="rst-topology-change-ack-u8"></a>



#### topology-change-ack (`u8`)

<a id="rst-config-pending-u8"></a>



#### config-pending (`u8`)

<a id="rst-message-age-timer-u64"></a>



#### message-age-timer (`u64`)

<a id="rst-forward-delay-timer-u64"></a>



#### forward-delay-timer (`u64`)

<a id="rst-hold-timer-u64"></a>



#### hold-timer (`u64`)

<a id="rst-flush-flag"></a>



#### flush (`flag`)

<a id="rst-multicast-router-u8"></a>



#### multicast-router (`u8`)

<a id="rst-pad-pad-3"></a>



#### pad (`pad`)

<a id="rst-mcast-flood-flag"></a>



#### mcast-flood (`flag`)

<a id="rst-mcast-to-ucast-flag"></a>



#### mcast-to-ucast (`flag`)

<a id="rst-vlan-tunnel-flag"></a>



#### vlan-tunnel (`flag`)

<a id="rst-bcast-flood-flag"></a>



#### bcast-flood (`flag`)

<a id="rst-group-fwd-mask-u16-1"></a>



#### group-fwd-mask (`u16`)

<a id="rst-neigh-suppress-flag"></a>



#### neigh-suppress (`flag`)

<a id="rst-isolated-flag"></a>



#### isolated (`flag`)

<a id="rst-backup-port-u32"></a>



#### backup-port (`u32`)

<a id="rst-mrp-ring-open-flag"></a>



#### mrp-ring-open (`flag`)

<a id="rst-mrp-in-open-flag"></a>



#### mrp-in-open (`flag`)

<a id="rst-mcast-eht-hosts-limit-u32"></a>



#### mcast-eht-hosts-limit (`u32`)

<a id="rst-mcast-eht-hosts-cnt-u32"></a>



#### mcast-eht-hosts-cnt (`u32`)

<a id="rst-locked-flag"></a>



#### locked (`flag`)

<a id="rst-mab-flag"></a>



#### mab (`flag`)

<a id="rst-mcast-n-groups-u32"></a>



#### mcast-n-groups (`u32`)

<a id="rst-mcast-max-groups-u32"></a>



#### mcast-max-groups (`u32`)

<a id="rst-neigh-vlan-suppress-flag"></a>



#### neigh-vlan-suppress (`flag`)

<a id="rst-backup-nhid-u32"></a>



#### backup-nhid (`u32`)

<a id="rst-linkinfo-gre-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-gre-attrs"></a>



### linkinfo-gre-attrs

<a id="rst-link-u32-1"></a>



#### link (`u32`)

<a id="rst-iflags-u16"></a>



#### iflags (`u16`)

- **byte-order**:

  big-endian

<a id="rst-oflags-u16"></a>



#### oflags (`u16`)

- **byte-order**:

  big-endian

<a id="rst-ikey-u32"></a>



#### ikey (`u32`)

- **byte-order**:

  big-endian

<a id="rst-okey-u32"></a>



#### okey (`u32`)

- **byte-order**:

  big-endian

<a id="rst-local-binary"></a>



#### local (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-remote-binary"></a>



#### remote (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-ttl-u8"></a>



#### ttl (`u8`)

<a id="rst-tos-u8"></a>



#### tos (`u8`)

<a id="rst-pmtudisc-u8"></a>



#### pmtudisc (`u8`)

<a id="rst-encap-limit-u8"></a>



#### encap-limit (`u8`)

<a id="rst-flowinfo-u32"></a>



#### flowinfo (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32"></a>



#### flags (`u32`)

<a id="rst-encap-type-u16"></a>



#### encap-type (`u16`)

<a id="rst-encap-flags-u16"></a>



#### encap-flags (`u16`)

<a id="rst-encap-sport-u16"></a>



#### encap-sport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-encap-dport-u16"></a>



#### encap-dport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-collect-metadata-flag"></a>



#### collect-metadata (`flag`)

<a id="rst-ignore-df-u8"></a>



#### ignore-df (`u8`)

<a id="rst-fwmark-u32"></a>



#### fwmark (`u32`)

<a id="rst-erspan-index-u32"></a>



#### erspan-index (`u32`)

<a id="rst-erspan-ver-u8"></a>



#### erspan-ver (`u8`)

<a id="rst-erspan-dir-u8"></a>



#### erspan-dir (`u8`)

<a id="rst-erspan-hwid-u16"></a>



#### erspan-hwid (`u16`)

<a id="rst-linkinfo-gre6-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-gre6-attrs"></a>



### linkinfo-gre6-attrs

<a id="rst-link"></a>



#### link

<a id="rst-iflags"></a>



#### iflags

<a id="rst-oflags"></a>



#### oflags

<a id="rst-ikey"></a>



#### ikey

<a id="rst-okey"></a>



#### okey

<a id="rst-local"></a>



#### local

- **display-hint**:

  ipv6

<a id="rst-remote"></a>



#### remote

- **display-hint**:

  ipv6

<a id="rst-ttl"></a>



#### ttl

<a id="rst-encap-limit"></a>



#### encap-limit

<a id="rst-flowinfo"></a>



#### flowinfo

<a id="rst-flags"></a>



#### flags

<a id="rst-encap-type"></a>



#### encap-type

<a id="rst-encap-flags"></a>



#### encap-flags

<a id="rst-encap-sport"></a>



#### encap-sport

<a id="rst-encap-dport"></a>



#### encap-dport

<a id="rst-collect-metadata"></a>



#### collect-metadata

<a id="rst-fwmark"></a>



#### fwmark

<a id="rst-erspan-index"></a>



#### erspan-index

<a id="rst-erspan-ver"></a>



#### erspan-ver

<a id="rst-erspan-dir"></a>



#### erspan-dir

<a id="rst-erspan-hwid"></a>



#### erspan-hwid

<a id="rst-linkinfo-vti-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-vti-attrs"></a>



### linkinfo-vti-attrs

<a id="rst-link-u32-2"></a>



#### link (`u32`)

<a id="rst-ikey-u32-1"></a>



#### ikey (`u32`)

- **byte-order**:

  big-endian

<a id="rst-okey-u32-1"></a>



#### okey (`u32`)

- **byte-order**:

  big-endian

<a id="rst-local-binary-1"></a>



#### local (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-remote-binary-1"></a>



#### remote (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-fwmark-u32-1"></a>



#### fwmark (`u32`)

<a id="rst-linkinfo-vti6-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-vti6-attrs"></a>



### linkinfo-vti6-attrs

<a id="rst-link-1"></a>



#### link

<a id="rst-ikey-1"></a>



#### ikey

<a id="rst-okey-1"></a>



#### okey

<a id="rst-local-1"></a>



#### local

- **display-hint**:

  ipv6

<a id="rst-remote-1"></a>



#### remote

- **display-hint**:

  ipv6

<a id="rst-fwmark-1"></a>



#### fwmark

<a id="rst-linkinfo-geneve-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-geneve-attrs"></a>



### linkinfo-geneve-attrs

<a id="rst-id-u32"></a>



#### id (`u32`)

<a id="rst-remote-u32"></a>



#### remote (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-ttl-u8-1"></a>



#### ttl (`u8`)

<a id="rst-tos-u8-1"></a>



#### tos (`u8`)

<a id="rst-port-u16"></a>



#### port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-collect-metadata-flag-1"></a>



#### collect-metadata (`flag`)

<a id="rst-remote6-binary"></a>



#### remote6 (`binary`)

- **display-hint**:

  ipv6

<a id="rst-udp-csum-u8"></a>



#### udp-csum (`u8`)

<a id="rst-udp-zero-csum6-tx-u8"></a>



#### udp-zero-csum6-tx (`u8`)

<a id="rst-udp-zero-csum6-rx-u8"></a>



#### udp-zero-csum6-rx (`u8`)

<a id="rst-label-u32"></a>



#### label (`u32`)

- **byte-order**:

  big-endian

<a id="rst-ttl-inherit-u8"></a>



#### ttl-inherit (`u8`)

<a id="rst-df-u8"></a>



#### df (`u8`)

<a id="rst-inner-proto-inherit-flag"></a>



#### inner-proto-inherit (`flag`)

<a id="rst-port-range-binary"></a>



#### port-range (`binary`)

- **struct**:

  [ifla-geneve-port-range](#rst-rt-link-definition-ifla-geneve-port-range)

<a id="rst-gro-hint-flag"></a>



#### gro-hint (`flag`)

<a id="rst-linkinfo-hsr-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-hsr-attrs"></a>



### linkinfo-hsr-attrs

<a id="rst-slave1-u32"></a>



#### slave1 (`u32`)

<a id="rst-slave2-u32"></a>



#### slave2 (`u32`)

<a id="rst-multicast-spec-u8"></a>



#### multicast-spec (`u8`)

<a id="rst-supervision-addr-binary"></a>



#### supervision-addr (`binary`)

- **display-hint**:

  mac

<a id="rst-seq-nr-u16"></a>



#### seq-nr (`u16`)

<a id="rst-version-u8"></a>



#### version (`u8`)

<a id="rst-protocol-u8"></a>



#### protocol (`u8`)

<a id="rst-interlink-u32"></a>



#### interlink (`u32`)

<a id="rst-linkinfo-iptun-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-iptun-attrs"></a>



### linkinfo-iptun-attrs

<a id="rst-link-u32-3"></a>



#### link (`u32`)

<a id="rst-local-binary-2"></a>



#### local (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-remote-binary-2"></a>



#### remote (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-ttl-u8-2"></a>



#### ttl (`u8`)

<a id="rst-tos-u8-2"></a>



#### tos (`u8`)

<a id="rst-encap-limit-u8-1"></a>



#### encap-limit (`u8`)

<a id="rst-flowinfo-u32-1"></a>



#### flowinfo (`u32`)

- **byte-order**:

  big-endian

<a id="rst-flags-u16"></a>



#### flags (`u16`)

- **byte-order**:

  big-endian

<a id="rst-proto-u8"></a>



#### proto (`u8`)

<a id="rst-pmtudisc-u8-1"></a>



#### pmtudisc (`u8`)

<a id="rst-rd-prefix-binary"></a>



#### 6rd-prefix (`binary`)

- **display-hint**:

  ipv6

<a id="rst-rd-relay-prefix-u32"></a>



#### 6rd-relay-prefix (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-rd-prefixlen-u16"></a>



#### 6rd-prefixlen (`u16`)

<a id="rst-rd-relay-prefixlen-u16"></a>



#### 6rd-relay-prefixlen (`u16`)

<a id="rst-encap-type-u16-1"></a>



#### encap-type (`u16`)

<a id="rst-encap-flags-u16-1"></a>



#### encap-flags (`u16`)

<a id="rst-encap-sport-u16-1"></a>



#### encap-sport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-encap-dport-u16-1"></a>



#### encap-dport (`u16`)

- **byte-order**:

  big-endian

<a id="rst-collect-metadata-flag-2"></a>



#### collect-metadata (`flag`)

<a id="rst-fwmark-u32-2"></a>



#### fwmark (`u32`)

<a id="rst-linkinfo-ip6tnl-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-ip6tnl-attrs"></a>



### linkinfo-ip6tnl-attrs

<a id="rst-link-2"></a>



#### link

<a id="rst-local-2"></a>



#### local

- **display-hint**:

  ipv6

<a id="rst-remote-2"></a>



#### remote

- **display-hint**:

  ipv6

<a id="rst-ttl-1"></a>



#### ttl

<a id="rst-encap-limit-1"></a>



#### encap-limit

<a id="rst-flowinfo-1"></a>



#### flowinfo

<a id="rst-flags-u32-1"></a>



#### flags (`u32`)

<a id="rst-proto"></a>



#### proto

<a id="rst-encap-type-1"></a>



#### encap-type

<a id="rst-encap-flags-1"></a>



#### encap-flags

<a id="rst-encap-sport-1"></a>



#### encap-sport

<a id="rst-encap-dport-1"></a>



#### encap-dport

<a id="rst-collect-metadata-1"></a>



#### collect-metadata

<a id="rst-fwmark-2"></a>



#### fwmark

<a id="rst-linkinfo-tun-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-tun-attrs"></a>



### linkinfo-tun-attrs

<a id="rst-owner-u32"></a>



#### owner (`u32`)

<a id="rst-group-u32-1"></a>



#### group (`u32`)

<a id="rst-type-u8"></a>



#### type (`u8`)

<a id="rst-pi-u8"></a>



#### pi (`u8`)

<a id="rst-vnet-hdr-u8"></a>



#### vnet-hdr (`u8`)

<a id="rst-persist-u8"></a>



#### persist (`u8`)

<a id="rst-multi-queue-u8"></a>



#### multi-queue (`u8`)

<a id="rst-num-queues-u32"></a>



#### num-queues (`u32`)

<a id="rst-num-disabled-queues-u32"></a>



#### num-disabled-queues (`u32`)

<a id="rst-linkinfo-vlan-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-vlan-attrs"></a>



### linkinfo-vlan-attrs

<a id="rst-id-u16-1"></a>



#### id (`u16`)

<a id="rst-flags-binary"></a>



#### flags (`binary`)

- **struct**:

  [ifla-vlan-flags](#rst-rt-link-definition-ifla-vlan-flags)

<a id="rst-egress-qos-nest"></a>



#### egress-qos (`nest`)

- **nested-attributes**:

  [ifla-vlan-qos](#rst-rt-link-attribute-set-ifla-vlan-qos)

<a id="rst-ingress-qos-nest"></a>



#### ingress-qos (`nest`)

- **nested-attributes**:

  [ifla-vlan-qos](#rst-rt-link-attribute-set-ifla-vlan-qos)

<a id="rst-protocol-u16"></a>



#### protocol (`u16`)

- **enum**:

  [vlan-protocols](#rst-rt-link-definition-vlan-protocols)

- **byte-order**:

  big-endian

<a id="rst-ifla-vlan-qos"></a>
<a id="rst-rt-link-attribute-set-ifla-vlan-qos"></a>



### ifla-vlan-qos

<a id="rst-mapping-binary"></a>



#### mapping (`binary`)

- **multi-attr**:

  True

- **struct**:

  [ifla-vlan-qos-mapping](#rst-rt-link-definition-ifla-vlan-qos-mapping)

<a id="rst-linkinfo-vrf-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-vrf-attrs"></a>



### linkinfo-vrf-attrs

<a id="rst-table-u32"></a>



#### table (`u32`)

<a id="rst-xdp-attrs"></a>
<a id="rst-rt-link-attribute-set-xdp-attrs"></a>



### xdp-attrs

<a id="rst-fd-s32"></a>



#### fd (`s32`)

<a id="rst-attached-u8"></a>



#### attached (`u8`)

<a id="rst-flags-u32-2"></a>



#### flags (`u32`)

<a id="rst-prog-id-u32"></a>



#### prog-id (`u32`)

<a id="rst-drv-prog-id-u32"></a>



#### drv-prog-id (`u32`)

<a id="rst-skb-prog-id-u32"></a>



#### skb-prog-id (`u32`)

<a id="rst-hw-prog-id-u32"></a>



#### hw-prog-id (`u32`)

<a id="rst-expected-fd-s32"></a>



#### expected-fd (`s32`)

<a id="rst-ifla-attrs"></a>
<a id="rst-rt-link-attribute-set-ifla-attrs"></a>



### ifla-attrs

<a id="rst-conf-binary"></a>



#### conf (`binary`)

- **sub-type**:

  u32

- **doc**:

  u32 indexed by ipv4-devconf - 1 on output, on input it's a nest

<a id="rst-ifla6-attrs"></a>
<a id="rst-rt-link-attribute-set-ifla6-attrs"></a>



### ifla6-attrs

<a id="rst-flags-u32-3"></a>



#### flags (`u32`)

<a id="rst-conf-binary-1"></a>



#### conf (`binary`)

- **sub-type**:

  u32

- **doc**:

  u32 indexed by ipv6-devconf - 1 on output, on input it's a nest

<a id="rst-stats-binary-1"></a>



#### stats (`binary`)

- **sub-type**:

  u64

<a id="rst-mcast-binary"></a>



#### mcast (`binary`)

<a id="rst-cacheinfo-binary"></a>



#### cacheinfo (`binary`)

- **struct**:

  [ifla-cacheinfo](#rst-rt-link-definition-ifla-cacheinfo)

<a id="rst-icmp6stats-binary"></a>



#### icmp6stats (`binary`)

- **sub-type**:

  u64

<a id="rst-token-binary"></a>



#### token (`binary`)

<a id="rst-addr-gen-mode-u8"></a>



#### addr-gen-mode (`u8`)

<a id="rst-ra-mtu-u32"></a>



#### ra-mtu (`u32`)

<a id="rst-mctp-attrs"></a>
<a id="rst-rt-link-attribute-set-mctp-attrs"></a>



### mctp-attrs

<a id="rst-net-u32"></a>



#### net (`u32`)

<a id="rst-phys-binding-u8"></a>



#### phys-binding (`u8`)

<a id="rst-stats-attrs"></a>
<a id="rst-rt-link-attribute-set-stats-attrs"></a>



### stats-attrs

<a id="rst-link-64-binary"></a>



#### link-64 (`binary`)

- **struct**:

  [rtnl-link-stats64](#rst-rt-link-definition-rtnl-link-stats64)

<a id="rst-link-xstats-binary"></a>



#### link-xstats (`binary`)

<a id="rst-link-xstats-slave-binary"></a>



#### link-xstats-slave (`binary`)

<a id="rst-link-offload-xstats-nest"></a>



#### link-offload-xstats (`nest`)

- **nested-attributes**:

  [link-offload-xstats](#rst-rt-link-attribute-set-link-offload-xstats)

<a id="rst-af-spec-binary"></a>



#### af-spec (`binary`)

<a id="rst-link-offload-xstats"></a>
<a id="rst-rt-link-attribute-set-link-offload-xstats"></a>



### link-offload-xstats

<a id="rst-cpu-hit-binary"></a>



#### cpu-hit (`binary`)

<a id="rst-hw-s-info-indexed-array"></a>



#### hw-s-info (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [hw-s-info-one](#rst-rt-link-attribute-set-hw-s-info-one)

<a id="rst-l3-stats-binary"></a>



#### l3-stats (`binary`)

<a id="rst-hw-s-info-one"></a>
<a id="rst-rt-link-attribute-set-hw-s-info-one"></a>



### hw-s-info-one

<a id="rst-request-u8"></a>



#### request (`u8`)

<a id="rst-used-u8"></a>



#### used (`u8`)

<a id="rst-link-dpll-pin-attrs"></a>
<a id="rst-rt-link-attribute-set-link-dpll-pin-attrs"></a>



### link-dpll-pin-attrs

<a id="rst-id-u32-1"></a>



#### id (`u32`)

<a id="rst-linkinfo-netkit-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-netkit-attrs"></a>



### linkinfo-netkit-attrs

<a id="rst-peer-info-binary"></a>



#### peer-info (`binary`)

<a id="rst-primary-u8"></a>



#### primary (`u8`)

<a id="rst-policy-u32"></a>



#### policy (`u32`)

- **enum**:

  [netkit-policy](#rst-rt-link-definition-netkit-policy)

<a id="rst-peer-policy-u32"></a>



#### peer-policy (`u32`)

- **enum**:

  [netkit-policy](#rst-rt-link-definition-netkit-policy)

<a id="rst-mode-u32"></a>



#### mode (`u32`)

- **enum**:

  [netkit-mode](#rst-rt-link-definition-netkit-mode)

<a id="rst-scrub-u32"></a>



#### scrub (`u32`)

- **enum**:

  [netkit-scrub](#rst-rt-link-definition-netkit-scrub)

<a id="rst-peer-scrub-u32"></a>



#### peer-scrub (`u32`)

- **enum**:

  [netkit-scrub](#rst-rt-link-definition-netkit-scrub)

<a id="rst-headroom-u16-1"></a>



#### headroom (`u16`)

<a id="rst-tailroom-u16-1"></a>



#### tailroom (`u16`)

<a id="rst-linkinfo-ovpn-attrs"></a>
<a id="rst-rt-link-attribute-set-linkinfo-ovpn-attrs"></a>



### linkinfo-ovpn-attrs

<a id="rst-mode-u8-1"></a>



#### mode (`u8`)

- **enum**:

  [ovpn-mode](#rst-rt-link-definition-ovpn-mode)

<a id="rst-sub-messages"></a>



## Sub-messages

<a id="rst-linkinfo-data-msg"></a>
<a id="rst-rt-link-sub-message-linkinfo-data-msg"></a>



### linkinfo-data-msg

- **bond**

  - **attribute-set**:

    [linkinfo-bond-attrs](#rst-rt-link-attribute-set-linkinfo-bond-attrs)

- **bridge**

  - **attribute-set**:

    [linkinfo-bridge-attrs](#rst-rt-link-attribute-set-linkinfo-bridge-attrs)

- **erspan**

  - **attribute-set**:

    [linkinfo-gre-attrs](#rst-rt-link-attribute-set-linkinfo-gre-attrs)

- **gre**

  - **attribute-set**:

    [linkinfo-gre-attrs](#rst-rt-link-attribute-set-linkinfo-gre-attrs)

- **gretap**

  - **attribute-set**:

    [linkinfo-gre-attrs](#rst-rt-link-attribute-set-linkinfo-gre-attrs)

- **ip6gre**

  - **attribute-set**:

    [linkinfo-gre6-attrs](#rst-rt-link-attribute-set-linkinfo-gre6-attrs)

- **geneve**

  - **attribute-set**:

    [linkinfo-geneve-attrs](#rst-rt-link-attribute-set-linkinfo-geneve-attrs)

- **hsr**

  - **attribute-set**:

    [linkinfo-hsr-attrs](#rst-rt-link-attribute-set-linkinfo-hsr-attrs)

- **ipip**

  - **attribute-set**:

    [linkinfo-iptun-attrs](#rst-rt-link-attribute-set-linkinfo-iptun-attrs)

- **ip6tnl**

  - **attribute-set**:

    [linkinfo-ip6tnl-attrs](#rst-rt-link-attribute-set-linkinfo-ip6tnl-attrs)

- **sit**

  - **attribute-set**:

    [linkinfo-iptun-attrs](#rst-rt-link-attribute-set-linkinfo-iptun-attrs)

- **tun**

  - **attribute-set**:

    [linkinfo-tun-attrs](#rst-rt-link-attribute-set-linkinfo-tun-attrs)

- **vlan**

  - **attribute-set**:

    [linkinfo-vlan-attrs](#rst-rt-link-attribute-set-linkinfo-vlan-attrs)

- **vrf**

  - **attribute-set**:

    [linkinfo-vrf-attrs](#rst-rt-link-attribute-set-linkinfo-vrf-attrs)

- **vti**

  - **attribute-set**:

    [linkinfo-vti-attrs](#rst-rt-link-attribute-set-linkinfo-vti-attrs)

- **vti6**

  - **attribute-set**:

    [linkinfo-vti6-attrs](#rst-rt-link-attribute-set-linkinfo-vti6-attrs)

- **netkit**

  - **attribute-set**:

    [linkinfo-netkit-attrs](#rst-rt-link-attribute-set-linkinfo-netkit-attrs)

- **ovpn**

  - **attribute-set**:

    [linkinfo-ovpn-attrs](#rst-rt-link-attribute-set-linkinfo-ovpn-attrs)

<a id="rst-linkinfo-member-data-msg"></a>
<a id="rst-rt-link-sub-message-linkinfo-member-data-msg"></a>



### linkinfo-member-data-msg

- **bridge**

  - **attribute-set**:

    [linkinfo-brport-attrs](#rst-rt-link-attribute-set-linkinfo-brport-attrs)

- **bond**

  - **attribute-set**:

    [bond-slave-attrs](#rst-rt-link-attribute-set-bond-slave-attrs)

---

# Family rt-neigh netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the rt-neigh Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-rt-neigh-netlink-specification"></a>
<a id="rst-netlink-rt-neigh"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



IP neighbour management over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-newneigh"></a>
<a id="rst-rt-neigh-operation-newneigh"></a>



### newneigh



Add new neighbour entry

- **fixed-header**:

  [ndmsg](#rst-rt-neigh-definition-ndmsg)

- **attribute-set**:

  [neighbour-attrs](#rst-rt-neigh-attribute-set-neighbour-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`dst`, `lladdr`, `probes`, `vlan`, `port`, `vni`, `ifindex`, `master`, `protocol`, `nh-id`, `flags-ext`, `fdb-ext-attrs`\]

<a id="rst-delneigh"></a>
<a id="rst-rt-neigh-operation-delneigh"></a>



### delneigh



Remove an existing neighbour entry

- **fixed-header**:

  [ndmsg](#rst-rt-neigh-definition-ndmsg)

- **attribute-set**:

  [neighbour-attrs](#rst-rt-neigh-attribute-set-neighbour-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`dst`, `ifindex`\]

<a id="rst-delneigh-ntf"></a>
<a id="rst-rt-neigh-operation-delneigh-ntf"></a>



### delneigh-ntf



Notify a neighbour deletion

- **value**:

  29

- **notify**:

  getneigh

- **fixed-header**:

  [ndmsg](#rst-rt-neigh-definition-ndmsg)

<a id="rst-getneigh"></a>
<a id="rst-rt-neigh-operation-getneigh"></a>



### getneigh



Get or dump neighbour entries

- **fixed-header**:

  [ndmsg](#rst-rt-neigh-definition-ndmsg)

- **attribute-set**:

  [neighbour-attrs](#rst-rt-neigh-attribute-set-neighbour-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`dst`\]

  **reply**

  - **attributes**:

    \[`dst`, `lladdr`, `probes`, `vlan`, `port`, `vni`, `ifindex`, `master`, `protocol`, `nh-id`, `flags-ext`, `fdb-ext-attrs`\]

- **dump**:

  **request**

  - **attributes**:

    \[`ifindex`, `master`\]

  **reply**

  - **attributes**:

    \[`dst`, `lladdr`, `probes`, `vlan`, `port`, `vni`, `ifindex`, `master`, `protocol`, `nh-id`, `flags-ext`, `fdb-ext-attrs`\]

<a id="rst-newneigh-ntf"></a>
<a id="rst-rt-neigh-operation-newneigh-ntf"></a>



### newneigh-ntf



Notify a neighbour creation

- **value**:

  28

- **notify**:

  getneigh

- **fixed-header**:

  [ndmsg](#rst-rt-neigh-definition-ndmsg)

<a id="rst-getneightbl"></a>
<a id="rst-rt-neigh-operation-getneightbl"></a>



### getneightbl



Get or dump neighbour tables

- **fixed-header**:

  [ndtmsg](#rst-rt-neigh-definition-ndtmsg)

- **attribute-set**:

  [ndt-attrs](#rst-rt-neigh-attribute-set-ndt-attrs)

- **dump**:

  **request**

  **reply**

  - **attributes**:

    \[`name`, `thresh1`, `thresh2`, `thresh3`, `config`, `parms`, `stats`, `gc-interval`\]

<a id="rst-setneightbl"></a>
<a id="rst-rt-neigh-operation-setneightbl"></a>



### setneightbl



Set neighbour tables

- **fixed-header**:

  [ndtmsg](#rst-rt-neigh-definition-ndtmsg)

- **attribute-set**:

  [ndt-attrs](#rst-rt-neigh-attribute-set-ndt-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`name`, `thresh1`, `thresh2`, `thresh3`, `parms`, `gc-interval`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- rtnlgrp-neigh


<a id="rst-definitions"></a>



## Definitions

<a id="rst-ndmsg"></a>
<a id="rst-rt-neigh-definition-ndmsg"></a>



### ndmsg

- **type**:

  struct

- **members**:

  - **ndm-family (`u8`)**

  - **ndm-pad (`pad`)**

  - **ndm-ifindex (`s32`)**

  - **ndm-state (`u16`)**

  - **ndm-flags (`u8`)**

  - **ndm-type (`u8`)**

<a id="rst-ndtmsg"></a>
<a id="rst-rt-neigh-definition-ndtmsg"></a>



### ndtmsg

- **type**:

  struct

- **members**:

  - **family (`u8`)**

<a id="rst-nud-state"></a>
<a id="rst-rt-neigh-definition-nud-state"></a>



### nud-state

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `incomplete`


  - `reachable`


  - `stale`


  - `delay`


  - `probe`


  - `failed`


  - `noarp`


  - `permanent`

<a id="rst-ntf-flags"></a>
<a id="rst-rt-neigh-definition-ntf-flags"></a>



### ntf-flags

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `use`


  - `self`


  - `master`


  - `proxy`


  - `ext-learned`


  - `offloaded`


  - `sticky`


  - `router`

<a id="rst-ntf-ext-flags"></a>
<a id="rst-rt-neigh-definition-ntf-ext-flags"></a>



### ntf-ext-flags

- **type**:

  flags

- **enum-name**:

  None

- **entries**:

  - `managed`


  - `locked`


  - `ext-validated`

<a id="rst-rtm-type"></a>
<a id="rst-rt-neigh-definition-rtm-type"></a>



### rtm-type

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - `unspec`


  - `unicast`


  - `local`


  - `broadcast`


  - `anycast`


  - `multicast`


  - `blackhole`


  - `unreachable`


  - `prohibit`


  - `throw`


  - `nat`


  - `xresolve`

<a id="rst-nda-cacheinfo"></a>
<a id="rst-rt-neigh-definition-nda-cacheinfo"></a>



### nda-cacheinfo

- **type**:

  struct

- **members**:

  - **confirmed (`u32`)**

  - **used (`u32`)**

  - **updated (`u32`)**

  - **refcnt (`u32`)**

<a id="rst-ndt-config"></a>
<a id="rst-rt-neigh-definition-ndt-config"></a>



### ndt-config

- **type**:

  struct

- **members**:

  - **key-len (`u16`)**

  - **entry-size (`u16`)**

  - **entries (`u32`)**

  - **last-flush (`u32`)**

  - **last-rand (`u32`)**

  - **hash-rnd (`u32`)**

  - **hash-mask (`u32`)**

  - **hash-chain-gc (`u32`)**

  - **proxy-qlen (`u32`)**

<a id="rst-ndt-stats"></a>
<a id="rst-rt-neigh-definition-ndt-stats"></a>



### ndt-stats

- **type**:

  struct

- **members**:

  - **allocs (`u64`)**

  - **destroys (`u64`)**

  - **hash-grows (`u64`)**

  - **res-failed (`u64`)**

  - **lookups (`u64`)**

  - **hits (`u64`)**

  - **rcv-probes-mcast (`u64`)**

  - **rcv-probes-ucast (`u64`)**

  - **periodic-gc-runs (`u64`)**

  - **forced-gc-runs (`u64`)**

  - **table-fulls (`u64`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-neighbour-attrs"></a>
<a id="rst-rt-neigh-attribute-set-neighbour-attrs"></a>



### neighbour-attrs

<a id="rst-unspec-binary"></a>



#### unspec (`binary`)

- **value**:

  0

<a id="rst-dst-binary"></a>



#### dst (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-lladdr-binary"></a>



#### lladdr (`binary`)

- **display-hint**:

  mac

<a id="rst-cacheinfo-binary"></a>



#### cacheinfo (`binary`)

- **struct**:

  [nda-cacheinfo](#rst-rt-neigh-definition-nda-cacheinfo)

<a id="rst-probes-u32"></a>



#### probes (`u32`)

<a id="rst-vlan-u16"></a>



#### vlan (`u16`)

<a id="rst-port-u16"></a>



#### port (`u16`)

<a id="rst-vni-u32"></a>



#### vni (`u32`)

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

<a id="rst-master-u32"></a>



#### master (`u32`)

<a id="rst-link-netnsid-s32"></a>



#### link-netnsid (`s32`)

<a id="rst-src-vni-u32"></a>



#### src-vni (`u32`)

<a id="rst-protocol-u8"></a>



#### protocol (`u8`)

<a id="rst-nh-id-u32"></a>



#### nh-id (`u32`)

<a id="rst-fdb-ext-attrs-binary"></a>



#### fdb-ext-attrs (`binary`)

<a id="rst-flags-ext-u32"></a>



#### flags-ext (`u32`)

- **enum**:

  [ntf-ext-flags](#rst-rt-neigh-definition-ntf-ext-flags)

<a id="rst-ndm-state-mask-u16"></a>



#### ndm-state-mask (`u16`)

<a id="rst-ndm-flags-mask-u8"></a>



#### ndm-flags-mask (`u8`)

<a id="rst-ndt-attrs"></a>
<a id="rst-rt-neigh-attribute-set-ndt-attrs"></a>



### ndt-attrs

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-thresh1-u32"></a>



#### thresh1 (`u32`)

<a id="rst-thresh2-u32"></a>



#### thresh2 (`u32`)

<a id="rst-thresh3-u32"></a>



#### thresh3 (`u32`)

<a id="rst-config-binary"></a>



#### config (`binary`)

- **struct**:

  [ndt-config](#rst-rt-neigh-definition-ndt-config)

<a id="rst-parms-nest"></a>



#### parms (`nest`)

- **nested-attributes**:

  [ndtpa-attrs](#rst-rt-neigh-attribute-set-ndtpa-attrs)

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [ndt-stats](#rst-rt-neigh-definition-ndt-stats)

<a id="rst-gc-interval-u64"></a>



#### gc-interval (`u64`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-ndtpa-attrs"></a>
<a id="rst-rt-neigh-attribute-set-ndtpa-attrs"></a>



### ndtpa-attrs

<a id="rst-ifindex-u32-1"></a>



#### ifindex (`u32`)

<a id="rst-refcnt-u32"></a>



#### refcnt (`u32`)

<a id="rst-reachable-time-u64"></a>



#### reachable-time (`u64`)

<a id="rst-base-reachable-time-u64"></a>



#### base-reachable-time (`u64`)

<a id="rst-retrans-time-u64"></a>



#### retrans-time (`u64`)

<a id="rst-gc-staletime-u64"></a>



#### gc-staletime (`u64`)

<a id="rst-delay-probe-time-u64"></a>



#### delay-probe-time (`u64`)

<a id="rst-queue-len-u32"></a>



#### queue-len (`u32`)

<a id="rst-app-probes-u32"></a>



#### app-probes (`u32`)

<a id="rst-ucast-probes-u32"></a>



#### ucast-probes (`u32`)

<a id="rst-mcast-probes-u32"></a>



#### mcast-probes (`u32`)

<a id="rst-anycast-delay-u64"></a>



#### anycast-delay (`u64`)

<a id="rst-proxy-delay-u64"></a>



#### proxy-delay (`u64`)

<a id="rst-proxy-qlen-u32"></a>



#### proxy-qlen (`u32`)

<a id="rst-locktime-u64"></a>



#### locktime (`u64`)

<a id="rst-queue-lenbytes-u32"></a>



#### queue-lenbytes (`u32`)

<a id="rst-mcast-reprobes-u32"></a>



#### mcast-reprobes (`u32`)

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-interval-probe-time-ms-u64"></a>



#### interval-probe-time-ms (`u64`)

---

# Family rt-route netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the rt-route Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-rt-route-netlink-specification"></a>
<a id="rst-netlink-rt-route"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Route configuration over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-getroute"></a>
<a id="rst-rt-route-operation-getroute"></a>



### getroute



Dump route information.

- **attribute-set**:

  [route-attrs](#rst-rt-route-attribute-set-route-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`src`, `dst`, `iif`, `oif`, `ip-proto`, `sport`, `dport`, `mark`, `uid`, `flowlabel`\]

  **reply**

  - **attributes**:

    \[`dst`, `src`, `iif`, `oif`, `gateway`, `priority`, `prefsrc`, `metrics`, `multipath`, `flow`, `cacheinfo`, `table`, `mark`, `mfc-stats`, `via`, `newdst`, `pref`, `encap-type`, `encap`, `expires`, `pad`, `uid`, `ttl-propagate`, `ip-proto`, `sport`, `dport`, `nh-id`, `flowlabel`\]

- **dump**:

  **request**

  - **attributes**:

    \[\]

  **reply**

  - **attributes**:

    \[`dst`, `src`, `iif`, `oif`, `gateway`, `priority`, `prefsrc`, `metrics`, `multipath`, `flow`, `cacheinfo`, `table`, `mark`, `mfc-stats`, `via`, `newdst`, `pref`, `encap-type`, `encap`, `expires`, `pad`, `uid`, `ttl-propagate`, `ip-proto`, `sport`, `dport`, `nh-id`, `flowlabel`\]

<a id="rst-newroute"></a>
<a id="rst-rt-route-operation-newroute"></a>



### newroute



Create a new route

- **attribute-set**:

  [route-attrs](#rst-rt-route-attribute-set-route-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`dst`, `src`, `iif`, `oif`, `gateway`, `priority`, `prefsrc`, `metrics`, `multipath`, `flow`, `cacheinfo`, `table`, `mark`, `mfc-stats`, `via`, `newdst`, `pref`, `encap-type`, `encap`, `expires`, `pad`, `uid`, `ttl-propagate`, `ip-proto`, `sport`, `dport`, `nh-id`, `flowlabel`\]

<a id="rst-delroute"></a>
<a id="rst-rt-route-operation-delroute"></a>



### delroute



Delete an existing route

- **attribute-set**:

  [route-attrs](#rst-rt-route-attribute-set-route-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`dst`, `src`, `iif`, `oif`, `gateway`, `priority`, `prefsrc`, `metrics`, `multipath`, `flow`, `cacheinfo`, `table`, `mark`, `mfc-stats`, `via`, `newdst`, `pref`, `encap-type`, `encap`, `expires`, `pad`, `uid`, `ttl-propagate`, `ip-proto`, `sport`, `dport`, `nh-id`, `flowlabel`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-rtm-type"></a>
<a id="rst-rt-route-definition-rtm-type"></a>



### rtm-type

- **name-prefix**:

  rtn-

- **enum-name**:

  None

- **type**:

  enum

- **entries**:

  - `unspec`


  - `unicast`


  - `local`


  - `broadcast`


  - `anycast`


  - `multicast`


  - `blackhole`


  - `unreachable`


  - `prohibit`


  - `throw`


  - `nat`


  - `xresolve`

<a id="rst-rtmsg"></a>
<a id="rst-rt-route-definition-rtmsg"></a>



### rtmsg

- **type**:

  struct

- **members**:

  - **rtm-family (`u8`)**

  - **rtm-dst-len (`u8`)**

  - **rtm-src-len (`u8`)**

  - **rtm-tos (`u8`)**

  - **rtm-table (`u8`)**

  - **rtm-protocol (`u8`)**

  - **rtm-scope (`u8`)**

  - **rtm-type (`u8`)**

  - **rtm-flags (`u32`)**

<a id="rst-rta-cacheinfo"></a>
<a id="rst-rt-route-definition-rta-cacheinfo"></a>



### rta-cacheinfo

- **type**:

  struct

- **members**:

  - **rta-clntref (`u32`)**

  - **rta-lastuse (`u32`)**

  - **rta-expires (`u32`)**

  - **rta-error (`u32`)**

  - **rta-used (`u32`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-route-attrs"></a>
<a id="rst-rt-route-attribute-set-route-attrs"></a>



### route-attrs

<a id="rst-dst-binary"></a>



#### dst (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-src-binary"></a>



#### src (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-iif-u32"></a>



#### iif (`u32`)

<a id="rst-oif-u32"></a>



#### oif (`u32`)

<a id="rst-gateway-binary"></a>



#### gateway (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-priority-u32"></a>



#### priority (`u32`)

<a id="rst-prefsrc-binary"></a>



#### prefsrc (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-metrics-nest"></a>



#### metrics (`nest`)

- **nested-attributes**:

  [metrics](#rst-rt-route-attribute-set-metrics)

<a id="rst-multipath-binary"></a>



#### multipath (`binary`)

<a id="rst-protoinfo-binary"></a>



#### protoinfo (`binary`)

<a id="rst-flow-u32"></a>



#### flow (`u32`)

<a id="rst-cacheinfo-binary"></a>



#### cacheinfo (`binary`)

- **struct**:

  [rta-cacheinfo](#rst-rt-route-definition-rta-cacheinfo)

<a id="rst-session-binary"></a>



#### session (`binary`)

<a id="rst-mp-algo-binary"></a>



#### mp-algo (`binary`)

<a id="rst-table-u32"></a>



#### table (`u32`)

<a id="rst-mark-u32"></a>



#### mark (`u32`)

<a id="rst-mfc-stats-binary"></a>



#### mfc-stats (`binary`)

<a id="rst-via-binary"></a>



#### via (`binary`)

<a id="rst-newdst-binary"></a>



#### newdst (`binary`)

<a id="rst-pref-u8"></a>



#### pref (`u8`)

<a id="rst-encap-type-u16"></a>



#### encap-type (`u16`)

<a id="rst-encap-binary"></a>



#### encap (`binary`)

<a id="rst-expires-u32"></a>



#### expires (`u32`)

<a id="rst-pad-binary"></a>



#### pad (`binary`)

<a id="rst-uid-u32"></a>



#### uid (`u32`)

<a id="rst-ttl-propagate-u8"></a>



#### ttl-propagate (`u8`)

<a id="rst-ip-proto-u8"></a>



#### ip-proto (`u8`)

<a id="rst-sport-u16"></a>



#### sport (`u16`)

<a id="rst-dport-u16"></a>



#### dport (`u16`)

<a id="rst-nh-id-u32"></a>



#### nh-id (`u32`)

<a id="rst-flowlabel-u32"></a>



#### flowlabel (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  hex

<a id="rst-metrics"></a>
<a id="rst-rt-route-attribute-set-metrics"></a>



### metrics

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-lock-u32"></a>



#### lock (`u32`)

<a id="rst-mtu-u32"></a>



#### mtu (`u32`)

<a id="rst-window-u32"></a>



#### window (`u32`)

<a id="rst-rtt-u32"></a>



#### rtt (`u32`)

<a id="rst-rttvar-u32"></a>



#### rttvar (`u32`)

<a id="rst-ssthresh-u32"></a>



#### ssthresh (`u32`)

<a id="rst-cwnd-u32"></a>



#### cwnd (`u32`)

<a id="rst-advmss-u32"></a>



#### advmss (`u32`)

<a id="rst-reordering-u32"></a>



#### reordering (`u32`)

<a id="rst-hoplimit-u32"></a>



#### hoplimit (`u32`)

<a id="rst-initcwnd-u32"></a>



#### initcwnd (`u32`)

<a id="rst-features-u32"></a>



#### features (`u32`)

<a id="rst-rto-min-u32"></a>



#### rto-min (`u32`)

<a id="rst-initrwnd-u32"></a>



#### initrwnd (`u32`)

<a id="rst-quickack-u32"></a>



#### quickack (`u32`)

<a id="rst-cc-algo-string"></a>



#### cc-algo (`string`)

<a id="rst-fastopen-no-cookie-u32"></a>



#### fastopen-no-cookie (`u32`)

---

# Family rt-rule netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the rt-rule Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-rt-rule-netlink-specification"></a>
<a id="rst-netlink-rt-rule"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



FIB rule management over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-newrule"></a>
<a id="rst-rt-rule-operation-newrule"></a>



### newrule



Add new FIB rule

- **attribute-set**:

  [fib-rule-attrs](#rst-rt-rule-attribute-set-fib-rule-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`iifname`, `oifname`, `priority`, `fwmark`, `flow`, `tun-id`, `fwmask`, `table`, `suppress-prefixlen`, `suppress-ifgroup`, `goto`, `l3mdev`, `uid-range`, `protocol`, `ip-proto`, `sport-range`, `dport-range`, `dscp`, `flowlabel`, `flowlabel-mask`, `sport-mask`, `dport-mask`, `dscp-mask`\]

<a id="rst-newrule-ntf"></a>
<a id="rst-rt-rule-operation-newrule-ntf"></a>



### newrule-ntf



Notify a rule creation

- **value**:

  32

- **notify**:

  getrule

<a id="rst-delrule"></a>
<a id="rst-rt-rule-operation-delrule"></a>



### delrule



Remove an existing FIB rule

- **attribute-set**:

  [fib-rule-attrs](#rst-rt-rule-attribute-set-fib-rule-attrs)

- **do**:

  **request**

  - **attributes**:

    \[`iifname`, `oifname`, `priority`, `fwmark`, `flow`, `tun-id`, `fwmask`, `table`, `suppress-prefixlen`, `suppress-ifgroup`, `goto`, `l3mdev`, `uid-range`, `protocol`, `ip-proto`, `sport-range`, `dport-range`, `dscp`, `flowlabel`, `flowlabel-mask`, `sport-mask`, `dport-mask`, `dscp-mask`\]

<a id="rst-delrule-ntf"></a>
<a id="rst-rt-rule-operation-delrule-ntf"></a>



### delrule-ntf



Notify a rule deletion

- **value**:

  33

- **notify**:

  getrule

<a id="rst-getrule"></a>
<a id="rst-rt-rule-operation-getrule"></a>



### getrule



Dump all FIB rules

- **attribute-set**:

  [fib-rule-attrs](#rst-rt-rule-attribute-set-fib-rule-attrs)

- **dump**:

  **request**

  **reply**

  - **attributes**:

    \[`iifname`, `oifname`, `priority`, `fwmark`, `flow`, `tun-id`, `fwmask`, `table`, `suppress-prefixlen`, `suppress-ifgroup`, `goto`, `l3mdev`, `uid-range`, `protocol`, `ip-proto`, `sport-range`, `dport-range`, `dscp`, `flowlabel`, `flowlabel-mask`, `sport-mask`, `dport-mask`, `dscp-mask`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- rtnlgrp-ipv4-rule


- rtnlgrp-ipv6-rule


<a id="rst-definitions"></a>



## Definitions

<a id="rst-rtgenmsg"></a>
<a id="rst-rt-rule-definition-rtgenmsg"></a>



### rtgenmsg

- **type**:

  struct

- **members**:

  - **family (`u8`)**

<a id="rst-fib-rule-hdr"></a>
<a id="rst-rt-rule-definition-fib-rule-hdr"></a>



### fib-rule-hdr

- **type**:

  struct

- **members**:

  - **family (`u8`)**

  - **dst-len (`u8`)**

  - **src-len (`u8`)**

  - **tos (`u8`)**

  - **table (`u8`)**

  - **res1 (`pad`)**

  - **res2 (`pad`)**

  - **action (`u8`)**

  - **flags (`u32`)**

<a id="rst-fr-act"></a>
<a id="rst-rt-rule-definition-fr-act"></a>



### fr-act

- **type**:

  enum

- **enum-name**:

  None

- **entries**:

  - `unspec`


  - `to-tbl`


  - `goto`


  - `nop`


  - `res3`


  - `res4`


  - `blackhole`


  - `unreachable`


  - `prohibit`

<a id="rst-fib-rule-port-range"></a>
<a id="rst-rt-rule-definition-fib-rule-port-range"></a>



### fib-rule-port-range

- **type**:

  struct

- **members**:

  - **start (`u16`)**

  - **end (`u16`)**

<a id="rst-fib-rule-uid-range"></a>
<a id="rst-rt-rule-definition-fib-rule-uid-range"></a>



### fib-rule-uid-range

- **type**:

  struct

- **members**:

  - **start (`u32`)**

  - **end (`u32`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-fib-rule-attrs"></a>
<a id="rst-rt-rule-attribute-set-fib-rule-attrs"></a>



### fib-rule-attrs

<a id="rst-dst-binary"></a>



#### dst (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-src-binary"></a>



#### src (`binary`)

- **display-hint**:

  ipv4-or-v6

<a id="rst-iifname-string"></a>



#### iifname (`string`)

<a id="rst-goto-u32"></a>



#### goto (`u32`)

<a id="rst-unused2-pad"></a>



#### unused2 (`pad`)

<a id="rst-priority-u32"></a>



#### priority (`u32`)

<a id="rst-unused3-pad"></a>



#### unused3 (`pad`)

<a id="rst-unused4-pad"></a>



#### unused4 (`pad`)

<a id="rst-unused5-pad"></a>



#### unused5 (`pad`)

<a id="rst-fwmark-u32"></a>



#### fwmark (`u32`)

- **display-hint**:

  hex

<a id="rst-flow-u32"></a>



#### flow (`u32`)

<a id="rst-tun-id-u64"></a>



#### tun-id (`u64`)

<a id="rst-suppress-ifgroup-u32"></a>



#### suppress-ifgroup (`u32`)

<a id="rst-suppress-prefixlen-u32"></a>



#### suppress-prefixlen (`u32`)

- **display-hint**:

  hex

<a id="rst-table-u32"></a>



#### table (`u32`)

<a id="rst-fwmask-u32"></a>



#### fwmask (`u32`)

- **display-hint**:

  hex

<a id="rst-oifname-string"></a>



#### oifname (`string`)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-l3mdev-u8"></a>



#### l3mdev (`u8`)

<a id="rst-uid-range-binary"></a>



#### uid-range (`binary`)

- **struct**:

  [fib-rule-uid-range](#rst-rt-rule-definition-fib-rule-uid-range)

<a id="rst-protocol-u8"></a>



#### protocol (`u8`)

<a id="rst-ip-proto-u8"></a>



#### ip-proto (`u8`)

<a id="rst-sport-range-binary"></a>



#### sport-range (`binary`)

- **struct**:

  [fib-rule-port-range](#rst-rt-rule-definition-fib-rule-port-range)

<a id="rst-dport-range-binary"></a>



#### dport-range (`binary`)

- **struct**:

  [fib-rule-port-range](#rst-rt-rule-definition-fib-rule-port-range)

<a id="rst-dscp-u8"></a>



#### dscp (`u8`)

<a id="rst-flowlabel-u32"></a>



#### flowlabel (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  hex

<a id="rst-flowlabel-mask-u32"></a>



#### flowlabel-mask (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  hex

<a id="rst-sport-mask-u16"></a>



#### sport-mask (`u16`)

- **display-hint**:

  hex

<a id="rst-dport-mask-u16"></a>



#### dport-mask (`u16`)

- **display-hint**:

  hex

<a id="rst-dscp-mask-u8"></a>



#### dscp-mask (`u8`)

- **display-hint**:

  hex

---

# Family tc netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the tc Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-tc-netlink-specification"></a>
<a id="rst-netlink-tc"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Netlink raw family for tc qdisc, chain, class and filter configuration over rtnetlink.

<a id="rst-operations"></a>



## Operations

<a id="rst-newqdisc"></a>
<a id="rst-tc-operation-newqdisc"></a>



### newqdisc



Create new tc qdisc.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`kind`, `options`, `rate`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-delqdisc"></a>
<a id="rst-tc-operation-delqdisc"></a>



### delqdisc



Delete existing tc qdisc.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

<a id="rst-getqdisc"></a>
<a id="rst-tc-operation-getqdisc"></a>



### getqdisc



Get / dump tc qdisc information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`dump-invisible`\]

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

- **dump**:

  **request**

  - **attributes**:

    \[`dump-invisible`\]

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-newtclass"></a>
<a id="rst-tc-operation-newtclass"></a>



### newtclass



Get / dump tc traffic class information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`kind`, `options`, `rate`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-deltclass"></a>
<a id="rst-tc-operation-deltclass"></a>



### deltclass



Get / dump tc traffic class information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

<a id="rst-gettclass"></a>
<a id="rst-tc-operation-gettclass"></a>



### gettclass



Get / dump tc traffic class information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-newtfilter"></a>
<a id="rst-tc-operation-newtfilter"></a>



### newtfilter



Get / dump tc filter information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`kind`, `options`, `rate`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-deltfilter"></a>
<a id="rst-tc-operation-deltfilter"></a>



### deltfilter



Get / dump tc filter information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`chain`, `kind`\]

<a id="rst-gettfilter"></a>
<a id="rst-tc-operation-gettfilter"></a>



### gettfilter



Get / dump tc filter information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`chain`, `kind`\]

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

- **dump**:

  **request**

  - **attributes**:

    \[`chain`, `dump-flags`\]

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-newchain"></a>
<a id="rst-tc-operation-newchain"></a>



### newchain



Get / dump tc chain information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`kind`, `options`, `rate`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-delchain"></a>
<a id="rst-tc-operation-delchain"></a>



### delchain



Get / dump tc chain information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`chain`\]

<a id="rst-getchain"></a>
<a id="rst-tc-operation-getchain"></a>



### getchain



Get / dump tc chain information.

- **attribute-set**:

  [attrs](#rst-tc-attribute-set-attrs)

- **fixed-header**:

  [tcmsg](#rst-tc-definition-tcmsg)

- **do**:

  **request**

  - **attributes**:

    \[`chain`\]

  **reply**

  - **attributes**:

    \[`kind`, `options`, `stats`, `xstats`, `rate`, `fcnt`, `stats2`, `stab`, `chain`, `ingress-block`, `egress-block`\]

<a id="rst-multicast-groups"></a>



## Multicast groups

- rtnlgrp-tc


<a id="rst-definitions"></a>



## Definitions

<a id="rst-tcmsg"></a>
<a id="rst-tc-definition-tcmsg"></a>



### tcmsg

- **type**:

  struct

- **header**:

  linux/rtnetlink.h

- **members**:

  - **family (`u8`)**

  - **ifindex (`s32`)**

  - **handle (`u32`)**

  - **parent (`u32`)**

  - **info (`u32`)**

<a id="rst-cls-flags"></a>
<a id="rst-tc-definition-cls-flags"></a>



### cls-flags

- **enum-name**:

  None

- **type**:

  flags

- **entries**:

  - `skip-hw`


  - `skip-sw`


  - `in-hw`


  - `not-in-nw`


  - `verbose`

<a id="rst-flower-key-ctrl-flags"></a>
<a id="rst-tc-definition-flower-key-ctrl-flags"></a>



### flower-key-ctrl-flags

- **name-prefix**:

  tca-flower-key-flags-

- **enum-name**:

  None

- **type**:

  flags

- **entries**:

  - `frag`


  - `firstfrag`


  - `tuncsum`


  - `tundf`


  - `tunoam`


  - `tuncrit`

<a id="rst-dualpi2-drop-overload"></a>
<a id="rst-tc-definition-dualpi2-drop-overload"></a>



### dualpi2-drop-overload

- **type**:

  enum

- **entries**:

  - `overflow`


  - `drop`

<a id="rst-dualpi2-drop-early"></a>
<a id="rst-tc-definition-dualpi2-drop-early"></a>



### dualpi2-drop-early

- **type**:

  enum

- **entries**:

  - `drop-dequeue`


  - `drop-enqueue`

<a id="rst-dualpi2-ecn-mask"></a>
<a id="rst-tc-definition-dualpi2-ecn-mask"></a>



### dualpi2-ecn-mask

- **type**:

  enum

- **value-start**:

  1

- **entries**:

  - `l4s-ect`


  - `cla-ect`


  - `any-ect`

<a id="rst-dualpi2-split-gso"></a>
<a id="rst-tc-definition-dualpi2-split-gso"></a>



### dualpi2-split-gso

- **type**:

  enum

- **entries**:

  - `no-split-gso`


  - `split-gso`

<a id="rst-tc-stats"></a>
<a id="rst-tc-definition-tc-stats"></a>



### tc-stats

- **type**:

  struct

- **members**:

  - **bytes (`u64`)**:

    Number of enqueued bytes

  - **packets (`u32`)**:

    Number of enqueued packets

  - **drops (`u32`)**:

    Packets dropped because of lack of resources

  - **overlimits (`u32`)**:

    Number of throttle events when this flow goes out of allocated bandwidth

  - **bps (`u32`)**:

    Current flow byte rate

  - **pps (`u32`)**:

    Current flow packet rate

  - **qlen (`u32`)**

  - **backlog (`u32`)**

<a id="rst-tc-cbs-qopt"></a>
<a id="rst-tc-definition-tc-cbs-qopt"></a>



### tc-cbs-qopt

- **type**:

  struct

- **members**:

  - **offload (`u8`)**

  - **hicredit (`s32`)**

  - **locredit (`s32`)**

  - **idleslope (`s32`)**

  - **sendslope (`s32`)**

<a id="rst-tc-etf-qopt"></a>
<a id="rst-tc-definition-tc-etf-qopt"></a>



### tc-etf-qopt

- **type**:

  struct

- **members**:

  - **delta (`s32`)**

  - **clockid (`s32`)**

  - **flags (`s32`)**

<a id="rst-tc-fifo-qopt"></a>
<a id="rst-tc-definition-tc-fifo-qopt"></a>



### tc-fifo-qopt

- **type**:

  struct

- **members**:

  - **limit (`u32`)**:

    Queue length; bytes for bfifo, packets for pfifo

<a id="rst-tc-htb-opt"></a>
<a id="rst-tc-definition-tc-htb-opt"></a>



### tc-htb-opt

- **type**:

  struct

- **members**:

  - **rate (`binary`)**

  - **ceil (`binary`)**

  - **buffer (`u32`)**

  - **cbuffer (`u32`)**

  - **quantum (`u32`)**

  - **level (`u32`)**

  - **prio (`u32`)**

<a id="rst-tc-htb-glob"></a>
<a id="rst-tc-definition-tc-htb-glob"></a>



### tc-htb-glob

- **type**:

  struct

- **members**:

  - **version (`u32`)**

  - **rate2quantum (`u32`)**:

    bps-\>quantum divisor

  - **defcls (`u32`)**:

    Default class number

  - **debug (`u32`)**:

    Debug flags

  - **direct-pkts (`u32`)**:

    Count of non shaped packets

<a id="rst-tc-gred-qopt"></a>
<a id="rst-tc-definition-tc-gred-qopt"></a>



### tc-gred-qopt

- **type**:

  struct

- **members**:

  - **limit (`u32`)**:

    HARD maximal queue length in bytes

  - **qth-min (`u32`)**:

    Min average length threshold in bytes

  - **qth-max (`u32`)**:

    Max average length threshold in bytes

  - **DP (`u32`)**:

    Up to 2^32 DPs

  - **backlog (`u32`)**

  - **qave (`u32`)**

  - **forced (`u32`)**

  - **early (`u32`)**

  - **other (`u32`)**

  - **pdrop (`u32`)**

  - **Wlog (`u8`)**:

    log(W)

  - **Plog (`u8`)**:

    log(P\_max / (qth-max - qth-min))

  - **Scell-log (`u8`)**:

    cell size for idle damping

  - **prio (`u8`)**:

    Priority of this VQ

  - **packets (`u32`)**

  - **bytesin (`u32`)**

<a id="rst-tc-gred-sopt"></a>
<a id="rst-tc-definition-tc-gred-sopt"></a>



### tc-gred-sopt

- **type**:

  struct

- **members**:

  - **DPs (`u32`)**

  - **def-DP (`u32`)**

  - **grio (`u8`)**

  - **flags (`u8`)**

<a id="rst-tc-hfsc-qopt"></a>
<a id="rst-tc-definition-tc-hfsc-qopt"></a>



### tc-hfsc-qopt

- **type**:

  struct

- **members**:

  - **defcls (`u16`)**

<a id="rst-tc-mqprio-qopt"></a>
<a id="rst-tc-definition-tc-mqprio-qopt"></a>



### tc-mqprio-qopt

- **type**:

  struct

- **members**:

  - **num-tc (`u8`)**

  - **prio-tc-map (`binary`)**

  - **hw (`u8`)**

  - **count (`binary`)**

  - **offset (`binary`)**

<a id="rst-tc-multiq-qopt"></a>
<a id="rst-tc-definition-tc-multiq-qopt"></a>



### tc-multiq-qopt

- **type**:

  struct

- **members**:

  - **bands (`u16`)**:

    Number of bands

  - **max-bands (`u16`)**:

    Maximum number of queues

<a id="rst-tc-netem-qopt"></a>
<a id="rst-tc-definition-tc-netem-qopt"></a>



### tc-netem-qopt

- **type**:

  struct

- **members**:

  - **latency (`u32`)**:

    Added delay in microseconds

  - **limit (`u32`)**:

    Fifo limit in packets

  - **loss (`u32`)**:

    Random packet loss (0=none, \~0=100%)

  - **gap (`u32`)**:

    Re-ordering gap (0 for none)

  - **duplicate (`u32`)**:

    Random packet duplication (0=none, \~0=100%)

  - **jitter (`u32`)**:

    Random jitter latency in microseconds

<a id="rst-tc-netem-gimodel"></a>
<a id="rst-tc-definition-tc-netem-gimodel"></a>



### tc-netem-gimodel

- **doc**:

  State transition probabilities for 4 state model

- **type**:

  struct

- **members**:

  - **p13 (`u32`)**

  - **p31 (`u32`)**

  - **p32 (`u32`)**

  - **p14 (`u32`)**

  - **p23 (`u32`)**

<a id="rst-tc-netem-gemodel"></a>
<a id="rst-tc-definition-tc-netem-gemodel"></a>



### tc-netem-gemodel

- **doc**:

  Gilbert-Elliot models

- **type**:

  struct

- **members**:

  - **p (`u32`)**

  - **r (`u32`)**

  - **h (`u32`)**

  - **k1 (`u32`)**

<a id="rst-tc-netem-corr"></a>
<a id="rst-tc-definition-tc-netem-corr"></a>



### tc-netem-corr

- **type**:

  struct

- **members**:

  - **delay-corr (`u32`)**:

    Delay correlation

  - **loss-corr (`u32`)**:

    Packet loss correlation

  - **dup-corr (`u32`)**:

    Duplicate correlation

<a id="rst-tc-netem-reorder"></a>
<a id="rst-tc-definition-tc-netem-reorder"></a>



### tc-netem-reorder

- **type**:

  struct

- **members**:

  - **probability (`u32`)**

  - **correlation (`u32`)**

<a id="rst-tc-netem-corrupt"></a>
<a id="rst-tc-definition-tc-netem-corrupt"></a>



### tc-netem-corrupt

- **type**:

  struct

- **members**:

  - **probability (`u32`)**

  - **correlation (`u32`)**

<a id="rst-tc-netem-rate"></a>
<a id="rst-tc-definition-tc-netem-rate"></a>



### tc-netem-rate

- **type**:

  struct

- **members**:

  - **rate (`u32`)**

  - **packet-overhead (`s32`)**

  - **cell-size (`u32`)**

  - **cell-overhead (`s32`)**

<a id="rst-tc-netem-slot"></a>
<a id="rst-tc-definition-tc-netem-slot"></a>



### tc-netem-slot

- **type**:

  struct

- **members**:

  - **min-delay (`s64`)**

  - **max-delay (`s64`)**

  - **max-packets (`s32`)**

  - **max-bytes (`s32`)**

  - **dist-delay (`s64`)**

  - **dist-jitter (`s64`)**

<a id="rst-tc-plug-qopt"></a>
<a id="rst-tc-definition-tc-plug-qopt"></a>



### tc-plug-qopt

- **type**:

  struct

- **members**:

  - **action (`s32`)**

  - **limit (`u32`)**

<a id="rst-tc-prio-qopt"></a>
<a id="rst-tc-definition-tc-prio-qopt"></a>



### tc-prio-qopt

- **type**:

  struct

- **members**:

  - **bands (`u32`)**:

    Number of bands

  - **priomap (`binary`)**:

    Map of logical priority -\> PRIO band

<a id="rst-tc-red-qopt"></a>
<a id="rst-tc-definition-tc-red-qopt"></a>



### tc-red-qopt

- **type**:

  struct

- **members**:

  - **limit (`u32`)**:

    Hard queue length in packets

  - **qth-min (`u32`)**:

    Min average threshold in packets

  - **qth-max (`u32`)**:

    Max average threshold in packets

  - **Wlog (`u8`)**:

    log(W)

  - **Plog (`u8`)**:

    log(P\_max / (qth-max - qth-min))

  - **Scell-log (`u8`)**:

    Cell size for idle damping

  - **flags (`u8`)**

<a id="rst-tc-sfb-qopt"></a>
<a id="rst-tc-definition-tc-sfb-qopt"></a>



### tc-sfb-qopt

- **type**:

  struct

- **members**:

  - **rehash-interval (`u32`)**

  - **warmup-time (`u32`)**

  - **max (`u32`)**

  - **bin-size (`u32`)**

  - **increment (`u32`)**

  - **decrement (`u32`)**

  - **limit (`u32`)**

  - **penalty-rate (`u32`)**

  - **penalty-burst (`u32`)**

<a id="rst-tc-sfq-qopt"></a>
<a id="rst-tc-definition-tc-sfq-qopt"></a>



### tc-sfq-qopt

- **type**:

  struct

- **members**:

  - **quantum (`u32`)**:

    Bytes per round allocated to flow

  - **perturb-period (`s32`)**:

    Period of hash perturbation

  - **limit (`u32`)**:

    Maximal packets in queue

  - **divisor (`u32`)**:

    Hash divisor

  - **flows (`u32`)**:

    Maximal number of flows

<a id="rst-tc-sfqred-stats"></a>
<a id="rst-tc-definition-tc-sfqred-stats"></a>



### tc-sfqred-stats

- **type**:

  struct

- **members**:

  - **prob-drop (`u32`)**:

    Early drops, below max threshold

  - **forced-drop (`u32`)**:

    Early drops, after max threshold

  - **prob-mark (`u32`)**:

    Marked packets, below max threshold

  - **forced-mark (`u32`)**:

    Marked packets, after max threshold

  - **prob-mark-head (`u32`)**:

    Marked packets, below max threshold

  - **forced-mark-head (`u32`)**:

    Marked packets, after max threshold

<a id="rst-tc-sfq-qopt-v1"></a>
<a id="rst-tc-definition-tc-sfq-qopt-v1"></a>



### tc-sfq-qopt-v1

- **type**:

  struct

- **members**:

  - **v0 (`binary`)**

  - **depth (`u32`)**:

    Maximum number of packets per flow

  - **headdrop (`u32`)**

  - **limit (`u32`)**:

    HARD maximal flow queue length in bytes

  - **qth-min (`u32`)**:

    Min average length threshold in bytes

  - **qth-max (`u32`)**:

    Max average length threshold in bytes

  - **Wlog (`u8`)**:

    log(W)

  - **Plog (`u8`)**:

    log(P\_max / (qth-max - qth-min))

  - **Scell-log (`u8`)**:

    Cell size for idle damping

  - **flags (`u8`)**

  - **max-P (`u32`)**:

    probability, high resolution

  - **stats (`binary`)**

<a id="rst-tc-ratespec"></a>
<a id="rst-tc-definition-tc-ratespec"></a>



### tc-ratespec

- **type**:

  struct

- **header**:

  linux/pkt\_sched.h

- **members**:

  - **cell-log (`u8`)**

  - **linklayer (`u8`)**

  - **overhead (`u8`)**

  - **cell-align (`u8`)**

  - **mpu (`u8`)**

  - **rate (`u32`)**

<a id="rst-tc-tbf-qopt"></a>
<a id="rst-tc-definition-tc-tbf-qopt"></a>



### tc-tbf-qopt

- **type**:

  struct

- **members**:

  - **rate (`binary`)**

  - **peakrate (`binary`)**

  - **limit (`u32`)**

  - **buffer (`u32`)**

  - **mtu (`u32`)**

<a id="rst-tc-sizespec"></a>
<a id="rst-tc-definition-tc-sizespec"></a>



### tc-sizespec

- **type**:

  struct

- **members**:

  - **cell-log (`u8`)**

  - **size-log (`u8`)**

  - **cell-align (`s16`)**

  - **overhead (`s32`)**

  - **linklayer (`u32`)**

  - **mpu (`u32`)**

  - **mtu (`u32`)**

  - **tsize (`u32`)**

<a id="rst-gnet-estimator"></a>
<a id="rst-tc-definition-gnet-estimator"></a>



### gnet-estimator

- **type**:

  struct

- **members**:

  - **interval (`s8`)**:

    Sampling period

  - **ewma-log (`u8`)**:

    The log() of measurement window weight

<a id="rst-tc-choke-xstats"></a>
<a id="rst-tc-definition-tc-choke-xstats"></a>



### tc-choke-xstats

- **type**:

  struct

- **members**:

  - **early (`u32`)**:

    Early drops

  - **pdrop (`u32`)**:

    Drops due to queue limits

  - **other (`u32`)**:

    Drops due to drop() calls

  - **marked (`u32`)**:

    Marked packets

  - **matched (`u32`)**:

    Drops due to flow match

<a id="rst-tc-codel-xstats"></a>
<a id="rst-tc-definition-tc-codel-xstats"></a>



### tc-codel-xstats

- **type**:

  struct

- **members**:

  - **maxpacket (`u32`)**:

    Largest packet we've seen so far

  - **count (`u32`)**:

    How many drops we've done since the last time we entered dropping state

  - **lastcount (`u32`)**:

    Count at entry to dropping state

  - **ldelay (`u32`)**:

    in-queue delay seen by most recently dequeued packet

  - **drop-next (`s32`)**:

    Time to drop next packet

  - **drop-overlimit (`u32`)**:

    Number of times max qdisc packet limit was hit

  - **ecn-mark (`u32`)**:

    Number of packets we've ECN marked instead of dropped

  - **dropping (`u32`)**:

    Are we in a dropping state?

  - **ce-mark (`u32`)**:

    Number of CE marked packets because of ce-threshold

<a id="rst-tc-fq-codel-xstats"></a>
<a id="rst-tc-definition-tc-fq-codel-xstats"></a>



### tc-fq-codel-xstats

- **type**:

  struct

- **members**:

  - **type (`u32`)**

  - **maxpacket (`u32`)**:

    Largest packet we've seen so far

  - **drop-overlimit (`u32`)**:

    Number of times max qdisc packet limit was hit

  - **ecn-mark (`u32`)**:

    Number of packets we ECN marked instead of being dropped

  - **new-flow-count (`u32`)**:

    Number of times packets created a new flow

  - **new-flows-len (`u32`)**:

    Count of flows in new list

  - **old-flows-len (`u32`)**:

    Count of flows in old list

  - **ce-mark (`u32`)**:

    Packets above ce-threshold

  - **memory-usage (`u32`)**:

    Memory usage in bytes

  - **drop-overmemory (`u32`)**

<a id="rst-tc-dualpi2-xstats"></a>
<a id="rst-tc-definition-tc-dualpi2-xstats"></a>



### tc-dualpi2-xstats

- **type**:

  struct

- **members**:

  - **prob (`u32`)**:

    Current base PI probability

  - **delay-c (`u32`)**:

    Current C-queue delay in microseconds

  - **delay-l (`u32`)**:

    Current L-queue delay in microseconds

  - **pkts-in-c (`u32`)**:

    Number of packets enqueued in the C-queue

  - **pkts-in-l (`u32`)**:

    Number of packets enqueued in the L-queue

  - **maxq (`u32`)**:

    Maximum number of packets seen by the DualPI2

  - **ecn-mark (`u32`)**:

    All packets marked with ECN

  - **step-mark (`u32`)**:

    Only packets marked with ECN due to L-queue step AQM

  - **credit (`s32`)**:

    Current credit value for WRR

  - **memory-used (`u32`)**:

    Memory used in bytes by the DualPI2

  - **max-memory-used (`u32`)**:

    Maximum memory used in bytes by the DualPI2

  - **memory-limit (`u32`)**:

    Memory limit in bytes

<a id="rst-tc-fq-pie-xstats"></a>
<a id="rst-tc-definition-tc-fq-pie-xstats"></a>



### tc-fq-pie-xstats

- **type**:

  struct

- **members**:

  - **packets-in (`u32`)**:

    Total number of packets enqueued

  - **dropped (`u32`)**:

    Packets dropped due to fq\_pie\_action

  - **overlimit (`u32`)**:

    Dropped due to lack of space in queue

  - **overmemory (`u32`)**:

    Dropped due to lack of memory in queue

  - **ecn-mark (`u32`)**:

    Packets marked with ECN

  - **new-flow-count (`u32`)**:

    Count of new flows created by packets

  - **new-flows-len (`u32`)**:

    Count of flows in new list

  - **old-flows-len (`u32`)**:

    Count of flows in old list

  - **memory-usage (`u32`)**:

    Total memory across all queues

<a id="rst-tc-fq-qd-stats"></a>
<a id="rst-tc-definition-tc-fq-qd-stats"></a>



### tc-fq-qd-stats

- **type**:

  struct

- **members**:

  - **gc-flows (`u64`)**

  - **highprio-packets (`u64`)**:

    obsolete

  - **tcp-retrans (`u64`)**:

    obsolete

  - **throttled (`u64`)**

  - **flows-plimit (`u64`)**

  - **pkts-too-long (`u64`)**

  - **allocation-errors (`u64`)**

  - **time-next-delayed-flow (`s64`)**

  - **flows (`u32`)**

  - **inactive-flows (`u32`)**

  - **throttled-flows (`u32`)**

  - **unthrottle-latency-ns (`u32`)**

  - **ce-mark (`u64`)**:

    Packets above ce-threshold

  - **horizon-drops (`u64`)**

  - **horizon-caps (`u64`)**

  - **fastpath-packets (`u64`)**

  - **band-drops (`binary`)**

  - **band-pkt-count (`binary`)**

<a id="rst-tc-hhf-xstats"></a>
<a id="rst-tc-definition-tc-hhf-xstats"></a>



### tc-hhf-xstats

- **type**:

  struct

- **members**:

  - **drop-overlimit (`u32`)**:

    Number of times max qdisc packet limit was hit

  - **hh-overlimit (`u32`)**:

    Number of times max heavy-hitters was hit

  - **hh-tot-count (`u32`)**:

    Number of captured heavy-hitters so far

  - **hh-cur-count (`u32`)**:

    Number of current heavy-hitters

<a id="rst-tc-pie-xstats"></a>
<a id="rst-tc-definition-tc-pie-xstats"></a>



### tc-pie-xstats

- **type**:

  struct

- **members**:

  - **prob (`u64`)**:

    Current probability

  - **delay (`u32`)**:

    Current delay in ms

  - **avg-dq-rate (`u32`)**:

    Current average dq rate in bits/pie-time

  - **dq-rate-estimating (`u32`)**:

    Is avg-dq-rate being calculated?

  - **packets-in (`u32`)**:

    Total number of packets enqueued

  - **dropped (`u32`)**:

    Packets dropped due to pie action

  - **overlimit (`u32`)**:

    Dropped due to lack of space in queue

  - **maxq (`u32`)**:

    Maximum queue size

  - **ecn-mark (`u32`)**:

    Packets marked with ECN

<a id="rst-tc-red-xstats"></a>
<a id="rst-tc-definition-tc-red-xstats"></a>



### tc-red-xstats

- **type**:

  struct

- **members**:

  - **early (`u32`)**:

    Early drops

  - **pdrop (`u32`)**:

    Drops due to queue limits

  - **other (`u32`)**:

    Drops due to drop() calls

  - **marked (`u32`)**:

    Marked packets

<a id="rst-tc-sfb-xstats"></a>
<a id="rst-tc-definition-tc-sfb-xstats"></a>



### tc-sfb-xstats

- **type**:

  struct

- **members**:

  - **earlydrop (`u32`)**

  - **penaltydrop (`u32`)**

  - **bucketdrop (`u32`)**

  - **queuedrop (`u32`)**

  - **childdrop (`u32`)**:

    drops in child qdisc

  - **marked (`u32`)**

  - **maxqlen (`u32`)**

  - **maxprob (`u32`)**

  - **avgprob (`u32`)**

<a id="rst-tc-sfq-xstats"></a>
<a id="rst-tc-definition-tc-sfq-xstats"></a>



### tc-sfq-xstats

- **type**:

  struct

- **members**:

  - **allot (`s32`)**

<a id="rst-gnet-stats-basic"></a>
<a id="rst-tc-definition-gnet-stats-basic"></a>



### gnet-stats-basic

- **type**:

  struct

- **members**:

  - **bytes (`u64`)**

  - **packets (`u32`)**

<a id="rst-gnet-stats-rate-est"></a>
<a id="rst-tc-definition-gnet-stats-rate-est"></a>



### gnet-stats-rate-est

- **type**:

  struct

- **members**:

  - **bps (`u32`)**

  - **pps (`u32`)**

<a id="rst-gnet-stats-rate-est64"></a>
<a id="rst-tc-definition-gnet-stats-rate-est64"></a>



### gnet-stats-rate-est64

- **type**:

  struct

- **members**:

  - **bps (`u64`)**

  - **pps (`u64`)**

<a id="rst-gnet-stats-queue"></a>
<a id="rst-tc-definition-gnet-stats-queue"></a>



### gnet-stats-queue

- **type**:

  struct

- **members**:

  - **qlen (`u32`)**

  - **backlog (`u32`)**

  - **drops (`u32`)**

  - **requeues (`u32`)**

  - **overlimits (`u32`)**

<a id="rst-tc-u32-key"></a>
<a id="rst-tc-definition-tc-u32-key"></a>



### tc-u32-key

- **type**:

  struct

- **members**:

  - **mask (`u32`)**

  - **val (`u32`)**

  - **off (`s32`)**

  - **offmask (`s32`)**

<a id="rst-tc-u32-mark"></a>
<a id="rst-tc-definition-tc-u32-mark"></a>



### tc-u32-mark

- **type**:

  struct

- **members**:

  - **val (`u32`)**

  - **mask (`u32`)**

  - **success (`u32`)**

<a id="rst-tc-u32-sel"></a>
<a id="rst-tc-definition-tc-u32-sel"></a>



### tc-u32-sel

- **type**:

  struct

- **members**:

  - **flags (`u8`)**

  - **offshift (`u8`)**

  - **nkeys (`u8`)**

  - **offmask (`u16`)**

  - **off (`u16`)**

  - **offoff (`s16`)**

  - **hoff (`s16`)**

  - **hmask (`u32`)**

  - **keys (`binary`)**

<a id="rst-tc-u32-pcnt"></a>
<a id="rst-tc-definition-tc-u32-pcnt"></a>



### tc-u32-pcnt

- **type**:

  struct

- **members**:

  - **rcnt (`u64`)**

  - **rhit (`u64`)**

  - **kcnts (`u64`)**

<a id="rst-tcf-t"></a>
<a id="rst-tc-definition-tcf-t"></a>



### tcf-t

- **type**:

  struct

- **members**:

  - **install (`u64`)**

  - **lastuse (`u64`)**

  - **expires (`u64`)**

  - **firstuse (`u64`)**

<a id="rst-tc-gact"></a>
<a id="rst-tc-definition-tc-gact"></a>



### tc-gact

- **type**:

  struct

- **members**:

  - **index (`u32`)**

  - **capab (`u32`)**

  - **action (`s32`)**

  - **refcnt (`s32`)**

  - **bindcnt (`s32`)**

<a id="rst-tc-gact-p"></a>
<a id="rst-tc-definition-tc-gact-p"></a>



### tc-gact-p

- **type**:

  struct

- **members**:

  - **ptype (`u16`)**

  - **pval (`u16`)**

  - **paction (`s32`)**

<a id="rst-tcf-ematch-tree-hdr"></a>
<a id="rst-tc-definition-tcf-ematch-tree-hdr"></a>



### tcf-ematch-tree-hdr

- **type**:

  struct

- **members**:

  - **nmatches (`u16`)**

  - **progid (`u16`)**

<a id="rst-tc-basic-pcnt"></a>
<a id="rst-tc-definition-tc-basic-pcnt"></a>



### tc-basic-pcnt

- **type**:

  struct

- **members**:

  - **rcnt (`u64`)**

  - **rhit (`u64`)**

<a id="rst-tc-matchall-pcnt"></a>
<a id="rst-tc-definition-tc-matchall-pcnt"></a>



### tc-matchall-pcnt

- **type**:

  struct

- **members**:

  - **rhit (`u64`)**

<a id="rst-tc-mpls"></a>
<a id="rst-tc-definition-tc-mpls"></a>



### tc-mpls

- **type**:

  struct

- **members**:

  - **index (`u32`)**

  - **capab (`u32`)**

  - **action (`s32`)**

  - **refcnt (`s32`)**

  - **bindcnt (`s32`)**

  - **m-action (`s32`)**

<a id="rst-tc-police"></a>
<a id="rst-tc-definition-tc-police"></a>



### tc-police

- **type**:

  struct

- **members**:

  - **index (`u32`)**

  - **action (`s32`)**

  - **limit (`u32`)**

  - **burst (`u32`)**

  - **mtu (`u32`)**

  - **rate (`binary`)**

  - **peakrate (`binary`)**

  - **refcnt (`s32`)**

  - **bindcnt (`s32`)**

  - **capab (`u32`)**

<a id="rst-tc-pedit-sel"></a>
<a id="rst-tc-definition-tc-pedit-sel"></a>



### tc-pedit-sel

- **type**:

  struct

- **members**:

  - **index (`u32`)**

  - **capab (`u32`)**

  - **action (`s32`)**

  - **refcnt (`s32`)**

  - **bindcnt (`s32`)**

  - **nkeys (`u8`)**

  - **flags (`u8`)**

  - **keys (`binary`)**

<a id="rst-tc-pedit-key"></a>
<a id="rst-tc-definition-tc-pedit-key"></a>



### tc-pedit-key

- **type**:

  struct

- **members**:

  - **mask (`u32`)**

  - **val (`u32`)**

  - **off (`u32`)**

  - **at (`u32`)**

  - **offmask (`u32`)**

  - **shift (`u32`)**

<a id="rst-tc-vlan"></a>
<a id="rst-tc-definition-tc-vlan"></a>



### tc-vlan

- **type**:

  struct

- **members**:

  - **index (`u32`)**

  - **capab (`u32`)**

  - **action (`s32`)**

  - **refcnt (`s32`)**

  - **bindcnt (`s32`)**

  - **v-action (`s32`)**

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-attrs"></a>
<a id="rst-tc-attribute-set-attrs"></a>



### attrs

<a id="rst-kind-string"></a>



#### kind (`string`)

<a id="rst-options-sub-message"></a>



#### options (`sub-message`)

- **sub-message**:

  [options-msg](#rst-tc-sub-message-options-msg)

- **selector**:

  kind

<a id="rst-stats-binary"></a>



#### stats (`binary`)

- **struct**:

  [tc-stats](#rst-tc-definition-tc-stats)

<a id="rst-xstats-sub-message"></a>



#### xstats (`sub-message`)

- **sub-message**:

  [tca-stats-app-msg](#rst-tc-sub-message-tca-stats-app-msg)

- **selector**:

  kind

<a id="rst-rate-binary"></a>



#### rate (`binary`)

- **struct**:

  [gnet-estimator](#rst-tc-definition-gnet-estimator)

<a id="rst-fcnt-u32"></a>



#### fcnt (`u32`)

<a id="rst-stats2-nest"></a>



#### stats2 (`nest`)

- **nested-attributes**:

  [tca-stats-attrs](#rst-tc-attribute-set-tca-stats-attrs)

<a id="rst-stab-nest"></a>



#### stab (`nest`)

- **nested-attributes**:

  [tca-stab-attrs](#rst-tc-attribute-set-tca-stab-attrs)

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-dump-invisible-flag"></a>



#### dump-invisible (`flag`)

<a id="rst-chain-u32"></a>



#### chain (`u32`)

<a id="rst-hw-offload-u8"></a>



#### hw-offload (`u8`)

<a id="rst-ingress-block-u32"></a>



#### ingress-block (`u32`)

<a id="rst-egress-block-u32"></a>



#### egress-block (`u32`)

<a id="rst-dump-flags-bitfield32"></a>



#### dump-flags (`bitfield32`)

<a id="rst-ext-warn-msg-string"></a>



#### ext-warn-msg (`string`)

<a id="rst-act-attrs"></a>
<a id="rst-tc-attribute-set-act-attrs"></a>



### act-attrs

<a id="rst-kind-string-1"></a>



#### kind (`string`)

<a id="rst-options-sub-message-1"></a>



#### options (`sub-message`)

- **sub-message**:

  [act-options-msg](#rst-tc-sub-message-act-options-msg)

- **selector**:

  kind

<a id="rst-index-u32"></a>



#### index (`u32`)

<a id="rst-stats-nest"></a>



#### stats (`nest`)

- **nested-attributes**:

  [tca-stats-attrs](#rst-tc-attribute-set-tca-stats-attrs)

<a id="rst-pad-pad-1"></a>



#### pad (`pad`)

<a id="rst-cookie-binary"></a>



#### cookie (`binary`)

<a id="rst-flags-bitfield32"></a>



#### flags (`bitfield32`)

<a id="rst-hw-stats-bitfield32"></a>



#### hw-stats (`bitfield32`)

<a id="rst-used-hw-stats-bitfield32"></a>



#### used-hw-stats (`bitfield32`)

<a id="rst-in-hw-count-u32"></a>



#### in-hw-count (`u32`)

<a id="rst-act-bpf-attrs"></a>
<a id="rst-tc-attribute-set-act-bpf-attrs"></a>



### act-bpf-attrs

<a id="rst-tm-binary"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary"></a>



#### parms (`binary`)

<a id="rst-ops-len-u16"></a>



#### ops-len (`u16`)

<a id="rst-ops-binary"></a>



#### ops (`binary`)

<a id="rst-fd-u32"></a>



#### fd (`u32`)

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-pad-pad-2"></a>



#### pad (`pad`)

<a id="rst-tag-binary"></a>



#### tag (`binary`)

<a id="rst-id-binary"></a>



#### id (`binary`)

<a id="rst-act-connmark-attrs"></a>
<a id="rst-tc-attribute-set-act-connmark-attrs"></a>



### act-connmark-attrs

<a id="rst-parms-binary-1"></a>



#### parms (`binary`)

<a id="rst-tm-binary-1"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-pad-pad-3"></a>



#### pad (`pad`)

<a id="rst-act-csum-attrs"></a>
<a id="rst-tc-attribute-set-act-csum-attrs"></a>



### act-csum-attrs

<a id="rst-parms-binary-2"></a>



#### parms (`binary`)

<a id="rst-tm-binary-2"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-pad-pad-4"></a>



#### pad (`pad`)

<a id="rst-act-ct-attrs"></a>
<a id="rst-tc-attribute-set-act-ct-attrs"></a>



### act-ct-attrs

<a id="rst-parms-binary-3"></a>



#### parms (`binary`)

<a id="rst-tm-binary-3"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-action-u16"></a>



#### action (`u16`)

<a id="rst-zone-u16"></a>



#### zone (`u16`)

<a id="rst-mark-u32"></a>



#### mark (`u32`)

<a id="rst-mark-mask-u32"></a>



#### mark-mask (`u32`)

<a id="rst-labels-binary"></a>



#### labels (`binary`)

<a id="rst-labels-mask-binary"></a>



#### labels-mask (`binary`)

<a id="rst-nat-ipv4-min-u32"></a>



#### nat-ipv4-min (`u32`)

- **byte-order**:

  big-endian

<a id="rst-nat-ipv4-max-u32"></a>



#### nat-ipv4-max (`u32`)

- **byte-order**:

  big-endian

<a id="rst-nat-ipv6-min-binary"></a>



#### nat-ipv6-min (`binary`)

<a id="rst-nat-ipv6-max-binary"></a>



#### nat-ipv6-max (`binary`)

<a id="rst-nat-port-min-u16"></a>



#### nat-port-min (`u16`)

- **byte-order**:

  big-endian

<a id="rst-nat-port-max-u16"></a>



#### nat-port-max (`u16`)

- **byte-order**:

  big-endian

<a id="rst-pad-pad-5"></a>



#### pad (`pad`)

<a id="rst-helper-name-string"></a>



#### helper-name (`string`)

<a id="rst-helper-family-u8"></a>



#### helper-family (`u8`)

<a id="rst-helper-proto-u8"></a>



#### helper-proto (`u8`)

<a id="rst-act-ctinfo-attrs"></a>
<a id="rst-tc-attribute-set-act-ctinfo-attrs"></a>



### act-ctinfo-attrs

<a id="rst-pad-pad-6"></a>



#### pad (`pad`)

<a id="rst-tm-binary-4"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-act-binary"></a>



#### act (`binary`)

<a id="rst-zone-u16-1"></a>



#### zone (`u16`)

<a id="rst-parms-dscp-mask-u32"></a>



#### parms-dscp-mask (`u32`)

<a id="rst-parms-dscp-statemask-u32"></a>



#### parms-dscp-statemask (`u32`)

<a id="rst-parms-cpmark-mask-u32"></a>



#### parms-cpmark-mask (`u32`)

<a id="rst-stats-dscp-set-u64"></a>



#### stats-dscp-set (`u64`)

<a id="rst-stats-dscp-error-u64"></a>



#### stats-dscp-error (`u64`)

<a id="rst-stats-cpmark-set-u64"></a>



#### stats-cpmark-set (`u64`)

<a id="rst-act-gate-attrs"></a>
<a id="rst-tc-attribute-set-act-gate-attrs"></a>



### act-gate-attrs

<a id="rst-tm-binary-5"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-4"></a>



#### parms (`binary`)

<a id="rst-pad-pad-7"></a>



#### pad (`pad`)

<a id="rst-priority-s32"></a>



#### priority (`s32`)

<a id="rst-entry-list-binary"></a>



#### entry-list (`binary`)

<a id="rst-base-time-u64"></a>



#### base-time (`u64`)

<a id="rst-cycle-time-u64"></a>



#### cycle-time (`u64`)

<a id="rst-cycle-time-ext-u64"></a>



#### cycle-time-ext (`u64`)

<a id="rst-flags-u32"></a>



#### flags (`u32`)

<a id="rst-clockid-s32"></a>



#### clockid (`s32`)

<a id="rst-act-ife-attrs"></a>
<a id="rst-tc-attribute-set-act-ife-attrs"></a>



### act-ife-attrs

<a id="rst-parms-binary-5"></a>



#### parms (`binary`)

<a id="rst-tm-binary-6"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-dmac-binary"></a>



#### dmac (`binary`)

<a id="rst-smac-binary"></a>



#### smac (`binary`)

<a id="rst-type-u16"></a>



#### type (`u16`)

<a id="rst-metalst-binary"></a>



#### metalst (`binary`)

<a id="rst-pad-pad-8"></a>



#### pad (`pad`)

<a id="rst-act-mirred-attrs"></a>
<a id="rst-tc-attribute-set-act-mirred-attrs"></a>



### act-mirred-attrs

<a id="rst-tm-binary-7"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-6"></a>



#### parms (`binary`)

<a id="rst-pad-pad-9"></a>



#### pad (`pad`)

<a id="rst-blockid-binary"></a>



#### blockid (`binary`)

<a id="rst-act-mpls-attrs"></a>
<a id="rst-tc-attribute-set-act-mpls-attrs"></a>



### act-mpls-attrs

<a id="rst-tm-binary-8"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-7"></a>



#### parms (`binary`)

- **struct**:

  [tc-mpls](#rst-tc-definition-tc-mpls)

<a id="rst-pad-pad-10"></a>



#### pad (`pad`)

<a id="rst-proto-u16"></a>



#### proto (`u16`)

- **byte-order**:

  big-endian

<a id="rst-label-u32"></a>



#### label (`u32`)

<a id="rst-tc-u8"></a>



#### tc (`u8`)

<a id="rst-ttl-u8"></a>



#### ttl (`u8`)

<a id="rst-bos-u8"></a>



#### bos (`u8`)

<a id="rst-act-nat-attrs"></a>
<a id="rst-tc-attribute-set-act-nat-attrs"></a>



### act-nat-attrs

<a id="rst-parms-binary-8"></a>



#### parms (`binary`)

<a id="rst-tm-binary-9"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-pad-pad-11"></a>



#### pad (`pad`)

<a id="rst-act-pedit-attrs"></a>
<a id="rst-tc-attribute-set-act-pedit-attrs"></a>



### act-pedit-attrs

<a id="rst-tm-binary-10"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-9"></a>



#### parms (`binary`)

- **struct**:

  [tc-pedit-sel](#rst-tc-definition-tc-pedit-sel)

<a id="rst-pad-pad-12"></a>



#### pad (`pad`)

<a id="rst-parms-ex-binary"></a>



#### parms-ex (`binary`)

<a id="rst-keys-ex-binary"></a>



#### keys-ex (`binary`)

<a id="rst-key-ex-binary"></a>



#### key-ex (`binary`)

<a id="rst-act-simple-attrs"></a>
<a id="rst-tc-attribute-set-act-simple-attrs"></a>



### act-simple-attrs

<a id="rst-tm-binary-11"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-10"></a>



#### parms (`binary`)

<a id="rst-data-binary"></a>



#### data (`binary`)

<a id="rst-pad-pad-13"></a>



#### pad (`pad`)

<a id="rst-act-skbedit-attrs"></a>
<a id="rst-tc-attribute-set-act-skbedit-attrs"></a>



### act-skbedit-attrs

<a id="rst-tm-binary-12"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-11"></a>



#### parms (`binary`)

<a id="rst-priority-u32"></a>



#### priority (`u32`)

<a id="rst-queue-mapping-u16"></a>



#### queue-mapping (`u16`)

<a id="rst-mark-u32-1"></a>



#### mark (`u32`)

<a id="rst-pad-pad-14"></a>



#### pad (`pad`)

<a id="rst-ptype-u16"></a>



#### ptype (`u16`)

<a id="rst-mask-u32"></a>



#### mask (`u32`)

<a id="rst-flags-u64"></a>



#### flags (`u64`)

<a id="rst-queue-mapping-max-u16"></a>



#### queue-mapping-max (`u16`)

<a id="rst-act-skbmod-attrs"></a>
<a id="rst-tc-attribute-set-act-skbmod-attrs"></a>



### act-skbmod-attrs

<a id="rst-tm-binary-13"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-12"></a>



#### parms (`binary`)

<a id="rst-dmac-binary-1"></a>



#### dmac (`binary`)

<a id="rst-smac-binary-1"></a>



#### smac (`binary`)

<a id="rst-etype-binary"></a>



#### etype (`binary`)

<a id="rst-pad-pad-15"></a>



#### pad (`pad`)

<a id="rst-act-tunnel-key-attrs"></a>
<a id="rst-tc-attribute-set-act-tunnel-key-attrs"></a>



### act-tunnel-key-attrs

<a id="rst-tm-binary-14"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-13"></a>



#### parms (`binary`)

<a id="rst-enc-ipv4-src-u32"></a>



#### enc-ipv4-src (`u32`)

- **byte-order**:

  big-endian

<a id="rst-enc-ipv4-dst-u32"></a>



#### enc-ipv4-dst (`u32`)

- **byte-order**:

  big-endian

<a id="rst-enc-ipv6-src-binary"></a>



#### enc-ipv6-src (`binary`)

<a id="rst-enc-ipv6-dst-binary"></a>



#### enc-ipv6-dst (`binary`)

<a id="rst-enc-key-id-u64"></a>



#### enc-key-id (`u64`)

- **byte-order**:

  big-endian

<a id="rst-pad-pad-16"></a>



#### pad (`pad`)

<a id="rst-enc-dst-port-u16"></a>



#### enc-dst-port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-no-csum-u8"></a>



#### no-csum (`u8`)

<a id="rst-enc-opts-binary"></a>



#### enc-opts (`binary`)

<a id="rst-enc-tos-u8"></a>



#### enc-tos (`u8`)

<a id="rst-enc-ttl-u8"></a>



#### enc-ttl (`u8`)

<a id="rst-no-frag-flag"></a>



#### no-frag (`flag`)

<a id="rst-act-vlan-attrs"></a>
<a id="rst-tc-attribute-set-act-vlan-attrs"></a>



### act-vlan-attrs

<a id="rst-tm-binary-15"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-14"></a>



#### parms (`binary`)

- **struct**:

  [tc-vlan](#rst-tc-definition-tc-vlan)

<a id="rst-push-vlan-id-u16"></a>



#### push-vlan-id (`u16`)

<a id="rst-push-vlan-protocol-u16"></a>



#### push-vlan-protocol (`u16`)

<a id="rst-pad-pad-17"></a>



#### pad (`pad`)

<a id="rst-push-vlan-priority-u8"></a>



#### push-vlan-priority (`u8`)

<a id="rst-push-eth-dst-binary"></a>



#### push-eth-dst (`binary`)

<a id="rst-push-eth-src-binary"></a>



#### push-eth-src (`binary`)

<a id="rst-basic-attrs"></a>
<a id="rst-tc-attribute-set-basic-attrs"></a>



### basic-attrs

<a id="rst-classid-u32"></a>



#### classid (`u32`)

<a id="rst-ematches-nest"></a>



#### ematches (`nest`)

- **nested-attributes**:

  [ematch-attrs](#rst-tc-attribute-set-ematch-attrs)

<a id="rst-act-indexed-array"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-police-nest"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-pcnt-binary"></a>



#### pcnt (`binary`)

- **struct**:

  [tc-basic-pcnt](#rst-tc-definition-tc-basic-pcnt)

<a id="rst-pad-pad-18"></a>



#### pad (`pad`)

<a id="rst-bpf-attrs"></a>
<a id="rst-tc-attribute-set-bpf-attrs"></a>



### bpf-attrs

<a id="rst-act-indexed-array-1"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-police-nest-1"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-classid-u32-1"></a>



#### classid (`u32`)

<a id="rst-ops-len-u16-1"></a>



#### ops-len (`u16`)

<a id="rst-ops-binary-1"></a>



#### ops (`binary`)

<a id="rst-fd-u32-1"></a>



#### fd (`u32`)

<a id="rst-name-string-1"></a>



#### name (`string`)

<a id="rst-flags-u32-1"></a>



#### flags (`u32`)

<a id="rst-flags-gen-u32"></a>



#### flags-gen (`u32`)

<a id="rst-tag-binary-1"></a>



#### tag (`binary`)

<a id="rst-id-u32"></a>



#### id (`u32`)

<a id="rst-cake-attrs"></a>
<a id="rst-tc-attribute-set-cake-attrs"></a>



### cake-attrs

<a id="rst-pad-pad-19"></a>



#### pad (`pad`)

<a id="rst-base-rate64-u64"></a>



#### base-rate64 (`u64`)

<a id="rst-diffserv-mode-u32"></a>



#### diffserv-mode (`u32`)

<a id="rst-atm-u32"></a>



#### atm (`u32`)

<a id="rst-flow-mode-u32"></a>



#### flow-mode (`u32`)

<a id="rst-overhead-u32"></a>



#### overhead (`u32`)

<a id="rst-rtt-u32"></a>



#### rtt (`u32`)

<a id="rst-target-u32"></a>



#### target (`u32`)

<a id="rst-autorate-u32"></a>



#### autorate (`u32`)

<a id="rst-memory-u32"></a>



#### memory (`u32`)

<a id="rst-nat-u32"></a>



#### nat (`u32`)

<a id="rst-raw-u32"></a>



#### raw (`u32`)

<a id="rst-wash-u32"></a>



#### wash (`u32`)

<a id="rst-mpu-u32"></a>



#### mpu (`u32`)

<a id="rst-ingress-u32"></a>



#### ingress (`u32`)

<a id="rst-ack-filter-u32"></a>



#### ack-filter (`u32`)

<a id="rst-split-gso-u32"></a>



#### split-gso (`u32`)

<a id="rst-fwmark-u32"></a>



#### fwmark (`u32`)

<a id="rst-cake-stats-attrs"></a>
<a id="rst-tc-attribute-set-cake-stats-attrs"></a>



### cake-stats-attrs

<a id="rst-pad-pad-20"></a>



#### pad (`pad`)

<a id="rst-capacity-estimate64-u64"></a>



#### capacity-estimate64 (`u64`)

<a id="rst-memory-limit-u32"></a>



#### memory-limit (`u32`)

<a id="rst-memory-used-u32"></a>



#### memory-used (`u32`)

<a id="rst-avg-netoff-u32"></a>



#### avg-netoff (`u32`)

<a id="rst-min-netlen-u32"></a>



#### min-netlen (`u32`)

<a id="rst-max-netlen-u32"></a>



#### max-netlen (`u32`)

<a id="rst-min-adjlen-u32"></a>



#### min-adjlen (`u32`)

<a id="rst-max-adjlen-u32"></a>



#### max-adjlen (`u32`)

<a id="rst-tin-stats-indexed-array"></a>



#### tin-stats (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [cake-tin-stats-attrs](#rst-tc-attribute-set-cake-tin-stats-attrs)

<a id="rst-deficit-s32"></a>



#### deficit (`s32`)

<a id="rst-cobalt-count-u32"></a>



#### cobalt-count (`u32`)

<a id="rst-dropping-u32"></a>



#### dropping (`u32`)

<a id="rst-drop-next-us-s32"></a>



#### drop-next-us (`s32`)

<a id="rst-p-drop-u32"></a>



#### p-drop (`u32`)

<a id="rst-blue-timer-us-s32"></a>



#### blue-timer-us (`s32`)

<a id="rst-active-queues-u32"></a>



#### active-queues (`u32`)

<a id="rst-cake-tin-stats-attrs"></a>
<a id="rst-tc-attribute-set-cake-tin-stats-attrs"></a>



### cake-tin-stats-attrs

<a id="rst-pad-pad-21"></a>



#### pad (`pad`)

<a id="rst-sent-packets-u32"></a>



#### sent-packets (`u32`)

<a id="rst-sent-bytes64-u64"></a>



#### sent-bytes64 (`u64`)

<a id="rst-dropped-packets-u32"></a>



#### dropped-packets (`u32`)

<a id="rst-dropped-bytes64-u64"></a>



#### dropped-bytes64 (`u64`)

<a id="rst-acks-dropped-packets-u32"></a>



#### acks-dropped-packets (`u32`)

<a id="rst-acks-dropped-bytes64-u64"></a>



#### acks-dropped-bytes64 (`u64`)

<a id="rst-ecn-marked-packets-u32"></a>



#### ecn-marked-packets (`u32`)

<a id="rst-ecn-marked-bytes64-u64"></a>



#### ecn-marked-bytes64 (`u64`)

<a id="rst-backlog-packets-u32"></a>



#### backlog-packets (`u32`)

<a id="rst-backlog-bytes-u32"></a>



#### backlog-bytes (`u32`)

<a id="rst-threshold-rate64-u64"></a>



#### threshold-rate64 (`u64`)

<a id="rst-target-us-u32"></a>



#### target-us (`u32`)

<a id="rst-interval-us-u32"></a>



#### interval-us (`u32`)

<a id="rst-way-indirect-hits-u32"></a>



#### way-indirect-hits (`u32`)

<a id="rst-way-misses-u32"></a>



#### way-misses (`u32`)

<a id="rst-way-collisions-u32"></a>



#### way-collisions (`u32`)

<a id="rst-peak-delay-us-u32"></a>



#### peak-delay-us (`u32`)

<a id="rst-avg-delay-us-u32"></a>



#### avg-delay-us (`u32`)

<a id="rst-base-delay-us-u32"></a>



#### base-delay-us (`u32`)

<a id="rst-sparse-flows-u32"></a>



#### sparse-flows (`u32`)

<a id="rst-bulk-flows-u32"></a>



#### bulk-flows (`u32`)

<a id="rst-unresponsive-flows-u32"></a>



#### unresponsive-flows (`u32`)

<a id="rst-max-skblen-u32"></a>



#### max-skblen (`u32`)

<a id="rst-flow-quantum-u32"></a>



#### flow-quantum (`u32`)

<a id="rst-cbs-attrs"></a>
<a id="rst-tc-attribute-set-cbs-attrs"></a>



### cbs-attrs

<a id="rst-parms-binary-15"></a>



#### parms (`binary`)

- **struct**:

  [tc-cbs-qopt](#rst-tc-definition-tc-cbs-qopt)

<a id="rst-cgroup-attrs"></a>
<a id="rst-tc-attribute-set-cgroup-attrs"></a>



### cgroup-attrs

<a id="rst-act-indexed-array-2"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-police-nest-2"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-ematches-binary"></a>



#### ematches (`binary`)

<a id="rst-choke-attrs"></a>
<a id="rst-tc-attribute-set-choke-attrs"></a>



### choke-attrs

<a id="rst-parms-binary-16"></a>



#### parms (`binary`)

- **struct**:

  [tc-red-qopt](#rst-tc-definition-tc-red-qopt)

<a id="rst-stab-binary"></a>



#### stab (`binary`)

<a id="rst-max-p-u32"></a>



#### max-p (`u32`)

<a id="rst-codel-attrs"></a>
<a id="rst-tc-attribute-set-codel-attrs"></a>



### codel-attrs

<a id="rst-target-u32-1"></a>



#### target (`u32`)

<a id="rst-limit-u32"></a>



#### limit (`u32`)

<a id="rst-interval-u32"></a>



#### interval (`u32`)

<a id="rst-ecn-u32"></a>



#### ecn (`u32`)

<a id="rst-ce-threshold-u32"></a>



#### ce-threshold (`u32`)

<a id="rst-drr-attrs"></a>
<a id="rst-tc-attribute-set-drr-attrs"></a>



### drr-attrs

<a id="rst-quantum-u32"></a>



#### quantum (`u32`)

<a id="rst-dualpi2-attrs"></a>
<a id="rst-tc-attribute-set-dualpi2-attrs"></a>



### dualpi2-attrs

<a id="rst-limit-u32-1"></a>



#### limit (`u32`)

- **doc**:

  Limit of total number of packets in queue

<a id="rst-memory-limit-u32-1"></a>



#### memory-limit (`u32`)

- **doc**:

  Memory limit of total number of packets in queue

<a id="rst-target-u32-2"></a>



#### target (`u32`)

- **doc**:

  Classic target delay in microseconds

<a id="rst-tupdate-u32"></a>



#### tupdate (`u32`)

- **doc**:

  Drop probability update interval time in microseconds

<a id="rst-alpha-u32"></a>



#### alpha (`u32`)

- **doc**:

  Integral gain factor in Hz for PI controller

<a id="rst-beta-u32"></a>



#### beta (`u32`)

- **doc**:

  Proportional gain factor in Hz for PI controller

<a id="rst-step-thresh-pkts-u32"></a>



#### step-thresh-pkts (`u32`)

- **doc**:

  L4S step marking threshold in packets

<a id="rst-step-thresh-us-u32"></a>



#### step-thresh-us (`u32`)

- **doc**:

  L4S Step marking threshold in microseconds

<a id="rst-min-qlen-step-u32"></a>



#### min-qlen-step (`u32`)

- **doc**:

  Packets enqueued to the L-queue can apply the step threshold when the queue length of L-queue is larger than this value. (0 is recommended)

<a id="rst-coupling-u8"></a>



#### coupling (`u8`)

- **doc**:

  Probability coupling factor between Classic and L4S (2 is recommended)

<a id="rst-drop-overload-u8"></a>



#### drop-overload (`u8`)

- **doc**:

  Control the overload strategy (drop to preserve latency or let the queue overflow)

- **enum**:

  [dualpi2-drop-overload](#rst-tc-definition-dualpi2-drop-overload)

<a id="rst-drop-early-u8"></a>



#### drop-early (`u8`)

- **doc**:

  Decide where the Classic packets are PI-based dropped or marked

- **enum**:

  [dualpi2-drop-early](#rst-tc-definition-dualpi2-drop-early)

<a id="rst-c-protection-u8"></a>



#### c-protection (`u8`)

- **doc**:

  Classic WRR weight in percentage (from 0 to 100)

<a id="rst-ecn-mask-u8"></a>



#### ecn-mask (`u8`)

- **doc**:

  Configure the L-queue ECN classifier

- **enum**:

  [dualpi2-ecn-mask](#rst-tc-definition-dualpi2-ecn-mask)

<a id="rst-split-gso-u8"></a>



#### split-gso (`u8`)

- **doc**:

  Split aggregated skb or not

- **enum**:

  [dualpi2-split-gso](#rst-tc-definition-dualpi2-split-gso)

<a id="rst-ematch-attrs"></a>
<a id="rst-tc-attribute-set-ematch-attrs"></a>



### ematch-attrs

<a id="rst-tree-hdr-binary"></a>



#### tree-hdr (`binary`)

- **struct**:

  [tcf-ematch-tree-hdr](#rst-tc-definition-tcf-ematch-tree-hdr)

<a id="rst-tree-list-binary"></a>



#### tree-list (`binary`)

<a id="rst-flow-attrs"></a>
<a id="rst-tc-attribute-set-flow-attrs"></a>



### flow-attrs

<a id="rst-keys-u32"></a>



#### keys (`u32`)

<a id="rst-mode-u32"></a>



#### mode (`u32`)

<a id="rst-baseclass-u32"></a>



#### baseclass (`u32`)

<a id="rst-rshift-u32"></a>



#### rshift (`u32`)

<a id="rst-addend-u32"></a>



#### addend (`u32`)

<a id="rst-mask-u32-1"></a>



#### mask (`u32`)

<a id="rst-xor-u32"></a>



#### xor (`u32`)

<a id="rst-divisor-u32"></a>



#### divisor (`u32`)

<a id="rst-act-binary-1"></a>



#### act (`binary`)

<a id="rst-police-nest-3"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-ematches-binary-1"></a>



#### ematches (`binary`)

<a id="rst-perturb-u32"></a>



#### perturb (`u32`)

<a id="rst-flower-attrs"></a>
<a id="rst-tc-attribute-set-flower-attrs"></a>



### flower-attrs

<a id="rst-classid-u32-2"></a>



#### classid (`u32`)

<a id="rst-indev-string"></a>



#### indev (`string`)

<a id="rst-act-indexed-array-3"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-key-eth-dst-binary"></a>



#### key-eth-dst (`binary`)

- **display-hint**:

  mac

<a id="rst-key-eth-dst-mask-binary"></a>



#### key-eth-dst-mask (`binary`)

- **display-hint**:

  mac

<a id="rst-key-eth-src-binary"></a>



#### key-eth-src (`binary`)

- **display-hint**:

  mac

<a id="rst-key-eth-src-mask-binary"></a>



#### key-eth-src-mask (`binary`)

- **display-hint**:

  mac

<a id="rst-key-eth-type-u16"></a>



#### key-eth-type (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-ip-proto-u8"></a>



#### key-ip-proto (`u8`)

<a id="rst-key-ipv4-src-u32"></a>



#### key-ipv4-src (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-ipv4-src-mask-u32"></a>



#### key-ipv4-src-mask (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-ipv4-dst-u32"></a>



#### key-ipv4-dst (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-ipv4-dst-mask-u32"></a>



#### key-ipv4-dst-mask (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-ipv6-src-binary"></a>



#### key-ipv6-src (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-ipv6-src-mask-binary"></a>



#### key-ipv6-src-mask (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-ipv6-dst-binary"></a>



#### key-ipv6-dst (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-ipv6-dst-mask-binary"></a>



#### key-ipv6-dst-mask (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-tcp-src-u16"></a>



#### key-tcp-src (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-tcp-dst-u16"></a>



#### key-tcp-dst (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-udp-src-u16"></a>



#### key-udp-src (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-udp-dst-u16"></a>



#### key-udp-dst (`u16`)

- **byte-order**:

  big-endian

<a id="rst-flags-u32-2"></a>



#### flags (`u32`)

- **enum**:

  [cls-flags](#rst-tc-definition-cls-flags)

- **enum-as-flags**:

  True

<a id="rst-key-vlan-id-u16"></a>



#### key-vlan-id (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-vlan-prio-u8"></a>



#### key-vlan-prio (`u8`)

<a id="rst-key-vlan-eth-type-u16"></a>



#### key-vlan-eth-type (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-key-id-u32"></a>



#### key-enc-key-id (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-ipv4-src-u32"></a>



#### key-enc-ipv4-src (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-enc-ipv4-src-mask-u32"></a>



#### key-enc-ipv4-src-mask (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-enc-ipv4-dst-u32"></a>



#### key-enc-ipv4-dst (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-enc-ipv4-dst-mask-u32"></a>



#### key-enc-ipv4-dst-mask (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-key-enc-ipv6-src-binary"></a>



#### key-enc-ipv6-src (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-enc-ipv6-src-mask-binary"></a>



#### key-enc-ipv6-src-mask (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-enc-ipv6-dst-binary"></a>



#### key-enc-ipv6-dst (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-enc-ipv6-dst-mask-binary"></a>



#### key-enc-ipv6-dst-mask (`binary`)

- **display-hint**:

  ipv6

<a id="rst-key-tcp-src-mask-u16"></a>



#### key-tcp-src-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-tcp-dst-mask-u16"></a>



#### key-tcp-dst-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-udp-src-mask-u16"></a>



#### key-udp-src-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-udp-dst-mask-u16"></a>



#### key-udp-dst-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-sctp-src-mask-u16"></a>



#### key-sctp-src-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-sctp-dst-mask-u16"></a>



#### key-sctp-dst-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-sctp-src-u16"></a>



#### key-sctp-src (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-sctp-dst-u16"></a>



#### key-sctp-dst (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-udp-src-port-u16"></a>



#### key-enc-udp-src-port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-udp-src-port-mask-u16"></a>



#### key-enc-udp-src-port-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-udp-dst-port-u16"></a>



#### key-enc-udp-dst-port (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-udp-dst-port-mask-u16"></a>



#### key-enc-udp-dst-port-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-flags-u32"></a>



#### key-flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [flower-key-ctrl-flags](#rst-tc-definition-flower-key-ctrl-flags)

- **enum-as-flags**:

  True

<a id="rst-key-flags-mask-u32"></a>



#### key-flags-mask (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [flower-key-ctrl-flags](#rst-tc-definition-flower-key-ctrl-flags)

- **enum-as-flags**:

  True

<a id="rst-key-icmpv4-code-u8"></a>



#### key-icmpv4-code (`u8`)

<a id="rst-key-icmpv4-code-mask-u8"></a>



#### key-icmpv4-code-mask (`u8`)

<a id="rst-key-icmpv4-type-u8"></a>



#### key-icmpv4-type (`u8`)

<a id="rst-key-icmpv4-type-mask-u8"></a>



#### key-icmpv4-type-mask (`u8`)

<a id="rst-key-icmpv6-code-u8"></a>



#### key-icmpv6-code (`u8`)

<a id="rst-key-icmpv6-code-mask-u8"></a>



#### key-icmpv6-code-mask (`u8`)

<a id="rst-key-icmpv6-type-u8"></a>



#### key-icmpv6-type (`u8`)

<a id="rst-key-icmpv6-type-mask-u8"></a>



#### key-icmpv6-type-mask (`u8`)

<a id="rst-key-arp-sip-u32"></a>



#### key-arp-sip (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-arp-sip-mask-u32"></a>



#### key-arp-sip-mask (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-arp-tip-u32"></a>



#### key-arp-tip (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-arp-tip-mask-u32"></a>



#### key-arp-tip-mask (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-arp-op-u8"></a>



#### key-arp-op (`u8`)

<a id="rst-key-arp-op-mask-u8"></a>



#### key-arp-op-mask (`u8`)

<a id="rst-key-arp-sha-binary"></a>



#### key-arp-sha (`binary`)

- **display-hint**:

  mac

<a id="rst-key-arp-sha-mask-binary"></a>



#### key-arp-sha-mask (`binary`)

- **display-hint**:

  mac

<a id="rst-key-arp-tha-binary"></a>



#### key-arp-tha (`binary`)

- **display-hint**:

  mac

<a id="rst-key-arp-tha-mask-binary"></a>



#### key-arp-tha-mask (`binary`)

- **display-hint**:

  mac

<a id="rst-key-mpls-ttl-u8"></a>



#### key-mpls-ttl (`u8`)

<a id="rst-key-mpls-bos-u8"></a>



#### key-mpls-bos (`u8`)

<a id="rst-key-mpls-tc-u8"></a>



#### key-mpls-tc (`u8`)

<a id="rst-key-mpls-label-u32"></a>



#### key-mpls-label (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-tcp-flags-u16"></a>



#### key-tcp-flags (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-tcp-flags-mask-u16"></a>



#### key-tcp-flags-mask (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-ip-tos-u8"></a>



#### key-ip-tos (`u8`)

<a id="rst-key-ip-tos-mask-u8"></a>



#### key-ip-tos-mask (`u8`)

<a id="rst-key-ip-ttl-u8"></a>



#### key-ip-ttl (`u8`)

<a id="rst-key-ip-ttl-mask-u8"></a>



#### key-ip-ttl-mask (`u8`)

<a id="rst-key-cvlan-id-u16"></a>



#### key-cvlan-id (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-cvlan-prio-u8"></a>



#### key-cvlan-prio (`u8`)

<a id="rst-key-cvlan-eth-type-u16"></a>



#### key-cvlan-eth-type (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-ip-tos-u8"></a>



#### key-enc-ip-tos (`u8`)

<a id="rst-key-enc-ip-tos-mask-u8"></a>



#### key-enc-ip-tos-mask (`u8`)

<a id="rst-key-enc-ip-ttl-u8"></a>



#### key-enc-ip-ttl (`u8`)

<a id="rst-key-enc-ip-ttl-mask-u8"></a>



#### key-enc-ip-ttl-mask (`u8`)

<a id="rst-key-enc-opts-nest"></a>



#### key-enc-opts (`nest`)

- **nested-attributes**:

  [flower-key-enc-opts-attrs](#rst-tc-attribute-set-flower-key-enc-opts-attrs)

<a id="rst-key-enc-opts-mask-nest"></a>



#### key-enc-opts-mask (`nest`)

- **nested-attributes**:

  [flower-key-enc-opts-attrs](#rst-tc-attribute-set-flower-key-enc-opts-attrs)

<a id="rst-in-hw-count-u32-1"></a>



#### in-hw-count (`u32`)

<a id="rst-key-port-src-min-u16"></a>



#### key-port-src-min (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-port-src-max-u16"></a>



#### key-port-src-max (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-port-dst-min-u16"></a>



#### key-port-dst-min (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-port-dst-max-u16"></a>



#### key-port-dst-max (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-ct-state-u16"></a>



#### key-ct-state (`u16`)

<a id="rst-key-ct-state-mask-u16"></a>



#### key-ct-state-mask (`u16`)

<a id="rst-key-ct-zone-u16"></a>



#### key-ct-zone (`u16`)

<a id="rst-key-ct-zone-mask-u16"></a>



#### key-ct-zone-mask (`u16`)

<a id="rst-key-ct-mark-u32"></a>



#### key-ct-mark (`u32`)

<a id="rst-key-ct-mark-mask-u32"></a>



#### key-ct-mark-mask (`u32`)

<a id="rst-key-ct-labels-binary"></a>



#### key-ct-labels (`binary`)

<a id="rst-key-ct-labels-mask-binary"></a>



#### key-ct-labels-mask (`binary`)

<a id="rst-key-mpls-opts-nest"></a>



#### key-mpls-opts (`nest`)

- **nested-attributes**:

  [flower-key-mpls-opt-attrs](#rst-tc-attribute-set-flower-key-mpls-opt-attrs)

<a id="rst-key-hash-u32"></a>



#### key-hash (`u32`)

<a id="rst-key-hash-mask-u32"></a>



#### key-hash-mask (`u32`)

<a id="rst-key-num-of-vlans-u8"></a>



#### key-num-of-vlans (`u8`)

<a id="rst-key-pppoe-sid-u16"></a>



#### key-pppoe-sid (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-ppp-proto-u16"></a>



#### key-ppp-proto (`u16`)

- **byte-order**:

  big-endian

<a id="rst-key-l2tpv3-sid-u32"></a>



#### key-l2tpv3-sid (`u32`)

- **byte-order**:

  big-endian

<a id="rst-l2-miss-u8"></a>



#### l2-miss (`u8`)

<a id="rst-key-cfm-nest"></a>



#### key-cfm (`nest`)

- **nested-attributes**:

  [flower-key-cfm-attrs](#rst-tc-attribute-set-flower-key-cfm-attrs)

<a id="rst-key-spi-u32"></a>



#### key-spi (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-spi-mask-u32"></a>



#### key-spi-mask (`u32`)

- **byte-order**:

  big-endian

<a id="rst-key-enc-flags-u32"></a>



#### key-enc-flags (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [flower-key-ctrl-flags](#rst-tc-definition-flower-key-ctrl-flags)

- **enum-as-flags**:

  True

<a id="rst-key-enc-flags-mask-u32"></a>



#### key-enc-flags-mask (`u32`)

- **byte-order**:

  big-endian

- **enum**:

  [flower-key-ctrl-flags](#rst-tc-definition-flower-key-ctrl-flags)

- **enum-as-flags**:

  True

<a id="rst-flower-key-enc-opts-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-enc-opts-attrs"></a>



### flower-key-enc-opts-attrs

<a id="rst-geneve-nest"></a>



#### geneve (`nest`)

- **nested-attributes**:

  [flower-key-enc-opt-geneve-attrs](#rst-tc-attribute-set-flower-key-enc-opt-geneve-attrs)

<a id="rst-vxlan-nest"></a>



#### vxlan (`nest`)

- **nested-attributes**:

  [flower-key-enc-opt-vxlan-attrs](#rst-tc-attribute-set-flower-key-enc-opt-vxlan-attrs)

<a id="rst-erspan-nest"></a>



#### erspan (`nest`)

- **nested-attributes**:

  [flower-key-enc-opt-erspan-attrs](#rst-tc-attribute-set-flower-key-enc-opt-erspan-attrs)

<a id="rst-gtp-nest"></a>



#### gtp (`nest`)

- **nested-attributes**:

  [flower-key-enc-opt-gtp-attrs](#rst-tc-attribute-set-flower-key-enc-opt-gtp-attrs)

<a id="rst-flower-key-enc-opt-geneve-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-enc-opt-geneve-attrs"></a>



### flower-key-enc-opt-geneve-attrs

<a id="rst-class-u16"></a>



#### class (`u16`)

<a id="rst-type-u8"></a>



#### type (`u8`)

<a id="rst-data-binary-1"></a>



#### data (`binary`)

<a id="rst-flower-key-enc-opt-vxlan-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-enc-opt-vxlan-attrs"></a>



### flower-key-enc-opt-vxlan-attrs

<a id="rst-gbp-u32"></a>



#### gbp (`u32`)

<a id="rst-flower-key-enc-opt-erspan-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-enc-opt-erspan-attrs"></a>



### flower-key-enc-opt-erspan-attrs

<a id="rst-ver-u8"></a>



#### ver (`u8`)

<a id="rst-index-u32-1"></a>



#### index (`u32`)

<a id="rst-dir-u8"></a>



#### dir (`u8`)

<a id="rst-hwid-u8"></a>



#### hwid (`u8`)

<a id="rst-flower-key-enc-opt-gtp-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-enc-opt-gtp-attrs"></a>



### flower-key-enc-opt-gtp-attrs

<a id="rst-pdu-type-u8"></a>



#### pdu-type (`u8`)

<a id="rst-qfi-u8"></a>



#### qfi (`u8`)

<a id="rst-flower-key-mpls-opt-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-mpls-opt-attrs"></a>



### flower-key-mpls-opt-attrs

<a id="rst-lse-depth-u8"></a>



#### lse-depth (`u8`)

<a id="rst-lse-ttl-u8"></a>



#### lse-ttl (`u8`)

<a id="rst-lse-bos-u8"></a>



#### lse-bos (`u8`)

<a id="rst-lse-tc-u8"></a>



#### lse-tc (`u8`)

<a id="rst-lse-label-u32"></a>



#### lse-label (`u32`)

<a id="rst-flower-key-cfm-attrs"></a>
<a id="rst-tc-attribute-set-flower-key-cfm-attrs"></a>



### flower-key-cfm-attrs

<a id="rst-md-level-u8"></a>



#### md-level (`u8`)

<a id="rst-opcode-u8"></a>



#### opcode (`u8`)

<a id="rst-fw-attrs"></a>
<a id="rst-tc-attribute-set-fw-attrs"></a>



### fw-attrs

<a id="rst-classid-u32-3"></a>



#### classid (`u32`)

<a id="rst-police-nest-4"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-indev-string-1"></a>



#### indev (`string`)

<a id="rst-act-indexed-array-4"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-mask-u32-2"></a>



#### mask (`u32`)

<a id="rst-gred-attrs"></a>
<a id="rst-tc-attribute-set-gred-attrs"></a>



### gred-attrs

<a id="rst-parms-binary-17"></a>



#### parms (`binary`)

<a id="rst-stab-binary-1"></a>



#### stab (`binary`)

- **sub-type**:

  u8

<a id="rst-dps-binary"></a>



#### dps (`binary`)

- **struct**:

  [tc-gred-sopt](#rst-tc-definition-tc-gred-sopt)

<a id="rst-max-p-binary"></a>



#### max-p (`binary`)

- **sub-type**:

  u32

<a id="rst-limit-u32-2"></a>



#### limit (`u32`)

<a id="rst-vq-list-nest"></a>



#### vq-list (`nest`)

- **nested-attributes**:

  [tca-gred-vq-list-attrs](#rst-tc-attribute-set-tca-gred-vq-list-attrs)

<a id="rst-tca-gred-vq-list-attrs"></a>
<a id="rst-tc-attribute-set-tca-gred-vq-list-attrs"></a>



### tca-gred-vq-list-attrs

<a id="rst-entry-nest"></a>



#### entry (`nest`)

- **nested-attributes**:

  [tca-gred-vq-entry-attrs](#rst-tc-attribute-set-tca-gred-vq-entry-attrs)

- **multi-attr**:

  True

<a id="rst-tca-gred-vq-entry-attrs"></a>
<a id="rst-tc-attribute-set-tca-gred-vq-entry-attrs"></a>



### tca-gred-vq-entry-attrs

<a id="rst-pad-pad-22"></a>



#### pad (`pad`)

<a id="rst-dp-u32"></a>



#### dp (`u32`)

<a id="rst-stat-bytes-u64"></a>



#### stat-bytes (`u64`)

<a id="rst-stat-packets-u32"></a>



#### stat-packets (`u32`)

<a id="rst-stat-backlog-u32"></a>



#### stat-backlog (`u32`)

<a id="rst-stat-prob-drop-u32"></a>



#### stat-prob-drop (`u32`)

<a id="rst-stat-prob-mark-u32"></a>



#### stat-prob-mark (`u32`)

<a id="rst-stat-forced-drop-u32"></a>



#### stat-forced-drop (`u32`)

<a id="rst-stat-forced-mark-u32"></a>



#### stat-forced-mark (`u32`)

<a id="rst-stat-pdrop-u32"></a>



#### stat-pdrop (`u32`)

<a id="rst-stat-other-u32"></a>



#### stat-other (`u32`)

<a id="rst-flags-u32-3"></a>



#### flags (`u32`)

<a id="rst-hfsc-attrs"></a>
<a id="rst-tc-attribute-set-hfsc-attrs"></a>



### hfsc-attrs

<a id="rst-rsc-binary"></a>



#### rsc (`binary`)

<a id="rst-fsc-binary"></a>



#### fsc (`binary`)

<a id="rst-usc-binary"></a>



#### usc (`binary`)

<a id="rst-hhf-attrs"></a>
<a id="rst-tc-attribute-set-hhf-attrs"></a>



### hhf-attrs

<a id="rst-backlog-limit-u32"></a>



#### backlog-limit (`u32`)

<a id="rst-quantum-u32-1"></a>



#### quantum (`u32`)

<a id="rst-hh-flows-limit-u32"></a>



#### hh-flows-limit (`u32`)

<a id="rst-reset-timeout-u32"></a>



#### reset-timeout (`u32`)

<a id="rst-admit-bytes-u32"></a>



#### admit-bytes (`u32`)

<a id="rst-evict-timeout-u32"></a>



#### evict-timeout (`u32`)

<a id="rst-non-hh-weight-u32"></a>



#### non-hh-weight (`u32`)

<a id="rst-htb-attrs"></a>
<a id="rst-tc-attribute-set-htb-attrs"></a>



### htb-attrs

<a id="rst-parms-binary-18"></a>



#### parms (`binary`)

- **struct**:

  [tc-htb-opt](#rst-tc-definition-tc-htb-opt)

<a id="rst-init-binary"></a>



#### init (`binary`)

- **struct**:

  [tc-htb-glob](#rst-tc-definition-tc-htb-glob)

<a id="rst-ctab-binary"></a>



#### ctab (`binary`)

<a id="rst-rtab-binary"></a>



#### rtab (`binary`)

<a id="rst-direct-qlen-u32"></a>



#### direct-qlen (`u32`)

<a id="rst-rate64-u64"></a>



#### rate64 (`u64`)

<a id="rst-ceil64-u64"></a>



#### ceil64 (`u64`)

<a id="rst-pad-pad-23"></a>



#### pad (`pad`)

<a id="rst-offload-flag"></a>



#### offload (`flag`)

<a id="rst-matchall-attrs"></a>
<a id="rst-tc-attribute-set-matchall-attrs"></a>



### matchall-attrs

<a id="rst-classid-u32-4"></a>



#### classid (`u32`)

<a id="rst-act-indexed-array-5"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-flags-u32-4"></a>



#### flags (`u32`)

<a id="rst-pcnt-binary-1"></a>



#### pcnt (`binary`)

- **struct**:

  [tc-matchall-pcnt](#rst-tc-definition-tc-matchall-pcnt)

<a id="rst-pad-pad-24"></a>



#### pad (`pad`)

<a id="rst-etf-attrs"></a>
<a id="rst-tc-attribute-set-etf-attrs"></a>



### etf-attrs

<a id="rst-parms-binary-19"></a>



#### parms (`binary`)

- **struct**:

  [tc-etf-qopt](#rst-tc-definition-tc-etf-qopt)

<a id="rst-ets-attrs"></a>
<a id="rst-tc-attribute-set-ets-attrs"></a>



### ets-attrs

<a id="rst-nbands-u8"></a>



#### nbands (`u8`)

<a id="rst-nstrict-u8"></a>



#### nstrict (`u8`)

<a id="rst-quanta-nest"></a>



#### quanta (`nest`)

- **nested-attributes**:

  [ets-attrs](#rst-tc-attribute-set-ets-attrs)

<a id="rst-quanta-band-u32"></a>



#### quanta-band (`u32`)

- **multi-attr**:

  True

<a id="rst-priomap-nest"></a>



#### priomap (`nest`)

- **nested-attributes**:

  [ets-attrs](#rst-tc-attribute-set-ets-attrs)

<a id="rst-priomap-band-u8"></a>



#### priomap-band (`u8`)

- **multi-attr**:

  True

<a id="rst-fq-attrs"></a>
<a id="rst-tc-attribute-set-fq-attrs"></a>



### fq-attrs

<a id="rst-plimit-u32"></a>



#### plimit (`u32`)

- **doc**:

  Limit of total number of packets in queue

<a id="rst-flow-plimit-u32"></a>



#### flow-plimit (`u32`)

- **doc**:

  Limit of packets per flow

<a id="rst-quantum-u32-2"></a>



#### quantum (`u32`)

- **doc**:

  RR quantum

<a id="rst-initial-quantum-u32"></a>



#### initial-quantum (`u32`)

- **doc**:

  RR quantum for new flow

<a id="rst-rate-enable-u32"></a>



#### rate-enable (`u32`)

- **doc**:

  Enable / disable rate limiting

<a id="rst-flow-default-rate-u32"></a>



#### flow-default-rate (`u32`)

- **doc**:

  Obsolete, do not use

<a id="rst-flow-max-rate-u32"></a>



#### flow-max-rate (`u32`)

- **doc**:

  Per flow max rate

<a id="rst-buckets-log-u32"></a>



#### buckets-log (`u32`)

- **doc**:

  log2(number of buckets)

<a id="rst-flow-refill-delay-u32"></a>



#### flow-refill-delay (`u32`)

- **doc**:

  Flow credit refill delay in usec

<a id="rst-orphan-mask-u32"></a>



#### orphan-mask (`u32`)

- **doc**:

  Mask applied to orphaned skb hashes

<a id="rst-low-rate-threshold-u32"></a>



#### low-rate-threshold (`u32`)

- **doc**:

  Per packet delay under this rate

<a id="rst-ce-threshold-u32-1"></a>



#### ce-threshold (`u32`)

- **doc**:

  DCTCP-like CE marking threshold

<a id="rst-timer-slack-u32"></a>



#### timer-slack (`u32`)

<a id="rst-horizon-u32"></a>



#### horizon (`u32`)

- **doc**:

  Time horizon in usec

<a id="rst-horizon-drop-u8"></a>



#### horizon-drop (`u8`)

- **doc**:

  Drop packets beyond horizon, or cap their EDT

<a id="rst-priomap-binary"></a>



#### priomap (`binary`)

- **struct**:

  [tc-prio-qopt](#rst-tc-definition-tc-prio-qopt)

<a id="rst-weights-binary"></a>



#### weights (`binary`)

- **sub-type**:

  s32

- **doc**:

  Weights for each band

<a id="rst-fq-codel-attrs"></a>
<a id="rst-tc-attribute-set-fq-codel-attrs"></a>



### fq-codel-attrs

<a id="rst-target-u32-3"></a>



#### target (`u32`)

<a id="rst-limit-u32-3"></a>



#### limit (`u32`)

<a id="rst-interval-u32-1"></a>



#### interval (`u32`)

<a id="rst-ecn-u32-1"></a>



#### ecn (`u32`)

<a id="rst-flows-u32"></a>



#### flows (`u32`)

<a id="rst-quantum-u32-3"></a>



#### quantum (`u32`)

<a id="rst-ce-threshold-u32-2"></a>



#### ce-threshold (`u32`)

<a id="rst-drop-batch-size-u32"></a>



#### drop-batch-size (`u32`)

<a id="rst-memory-limit-u32-2"></a>



#### memory-limit (`u32`)

<a id="rst-ce-threshold-selector-u8"></a>



#### ce-threshold-selector (`u8`)

<a id="rst-ce-threshold-mask-u8"></a>



#### ce-threshold-mask (`u8`)

<a id="rst-fq-pie-attrs"></a>
<a id="rst-tc-attribute-set-fq-pie-attrs"></a>



### fq-pie-attrs

<a id="rst-limit-u32-4"></a>



#### limit (`u32`)

<a id="rst-flows-u32-1"></a>



#### flows (`u32`)

<a id="rst-target-u32-4"></a>



#### target (`u32`)

<a id="rst-tupdate-u32-1"></a>



#### tupdate (`u32`)

<a id="rst-alpha-u32-1"></a>



#### alpha (`u32`)

<a id="rst-beta-u32-1"></a>



#### beta (`u32`)

<a id="rst-quantum-u32-4"></a>



#### quantum (`u32`)

<a id="rst-memory-limit-u32-3"></a>



#### memory-limit (`u32`)

<a id="rst-ecn-prob-u32"></a>



#### ecn-prob (`u32`)

<a id="rst-ecn-u32-2"></a>



#### ecn (`u32`)

<a id="rst-bytemode-u32"></a>



#### bytemode (`u32`)

<a id="rst-dq-rate-estimator-u32"></a>



#### dq-rate-estimator (`u32`)

<a id="rst-netem-attrs"></a>
<a id="rst-tc-attribute-set-netem-attrs"></a>



### netem-attrs

<a id="rst-corr-binary"></a>



#### corr (`binary`)

- **struct**:

  [tc-netem-corr](#rst-tc-definition-tc-netem-corr)

<a id="rst-delay-dist-binary"></a>



#### delay-dist (`binary`)

- **sub-type**:

  s16

<a id="rst-reorder-binary"></a>



#### reorder (`binary`)

- **struct**:

  [tc-netem-reorder](#rst-tc-definition-tc-netem-reorder)

<a id="rst-corrupt-binary"></a>



#### corrupt (`binary`)

- **struct**:

  [tc-netem-corrupt](#rst-tc-definition-tc-netem-corrupt)

<a id="rst-loss-nest"></a>



#### loss (`nest`)

- **nested-attributes**:

  [netem-loss-attrs](#rst-tc-attribute-set-netem-loss-attrs)

<a id="rst-rate-binary-1"></a>



#### rate (`binary`)

- **struct**:

  [tc-netem-rate](#rst-tc-definition-tc-netem-rate)

<a id="rst-ecn-u32-3"></a>



#### ecn (`u32`)

<a id="rst-rate64-u64-1"></a>



#### rate64 (`u64`)

<a id="rst-pad-u32"></a>



#### pad (`u32`)

<a id="rst-latency64-s64"></a>



#### latency64 (`s64`)

<a id="rst-jitter64-s64"></a>



#### jitter64 (`s64`)

<a id="rst-slot-binary"></a>



#### slot (`binary`)

- **struct**:

  [tc-netem-slot](#rst-tc-definition-tc-netem-slot)

<a id="rst-slot-dist-binary"></a>



#### slot-dist (`binary`)

- **sub-type**:

  s16

<a id="rst-prng-seed-u64"></a>



#### prng-seed (`u64`)

<a id="rst-netem-loss-attrs"></a>
<a id="rst-tc-attribute-set-netem-loss-attrs"></a>



### netem-loss-attrs

<a id="rst-gi-binary"></a>



#### gi (`binary`)

- **doc**:

  General Intuitive - 4 state model

- **struct**:

  [tc-netem-gimodel](#rst-tc-definition-tc-netem-gimodel)

<a id="rst-ge-binary"></a>



#### ge (`binary`)

- **doc**:

  Gilbert Elliot models

- **struct**:

  [tc-netem-gemodel](#rst-tc-definition-tc-netem-gemodel)

<a id="rst-pie-attrs"></a>
<a id="rst-tc-attribute-set-pie-attrs"></a>



### pie-attrs

<a id="rst-target-u32-5"></a>



#### target (`u32`)

<a id="rst-limit-u32-5"></a>



#### limit (`u32`)

<a id="rst-tupdate-u32-2"></a>



#### tupdate (`u32`)

<a id="rst-alpha-u32-2"></a>



#### alpha (`u32`)

<a id="rst-beta-u32-2"></a>



#### beta (`u32`)

<a id="rst-ecn-u32-4"></a>



#### ecn (`u32`)

<a id="rst-bytemode-u32-1"></a>



#### bytemode (`u32`)

<a id="rst-dq-rate-estimator-u32-1"></a>



#### dq-rate-estimator (`u32`)

<a id="rst-police-attrs"></a>
<a id="rst-tc-attribute-set-police-attrs"></a>



### police-attrs

<a id="rst-tbf-binary"></a>



#### tbf (`binary`)

- **struct**:

  [tc-police](#rst-tc-definition-tc-police)

<a id="rst-rate-binary-2"></a>



#### rate (`binary`)

<a id="rst-peakrate-binary"></a>



#### peakrate (`binary`)

<a id="rst-avrate-u32"></a>



#### avrate (`u32`)

<a id="rst-result-u32"></a>



#### result (`u32`)

<a id="rst-tm-binary-16"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-pad-pad-25"></a>



#### pad (`pad`)

<a id="rst-rate64-u64-2"></a>



#### rate64 (`u64`)

<a id="rst-peakrate64-u64"></a>



#### peakrate64 (`u64`)

<a id="rst-pktrate64-u64"></a>



#### pktrate64 (`u64`)

<a id="rst-pktburst64-u64"></a>



#### pktburst64 (`u64`)

<a id="rst-qfq-attrs"></a>
<a id="rst-tc-attribute-set-qfq-attrs"></a>



### qfq-attrs

<a id="rst-weight-u32"></a>



#### weight (`u32`)

<a id="rst-lmax-u32"></a>



#### lmax (`u32`)

<a id="rst-red-attrs"></a>
<a id="rst-tc-attribute-set-red-attrs"></a>



### red-attrs

<a id="rst-parms-binary-20"></a>



#### parms (`binary`)

- **struct**:

  [tc-red-qopt](#rst-tc-definition-tc-red-qopt)

<a id="rst-stab-binary-2"></a>



#### stab (`binary`)

<a id="rst-max-p-u32-1"></a>



#### max-p (`u32`)

<a id="rst-flags-bitfield32-1"></a>



#### flags (`bitfield32`)

<a id="rst-early-drop-block-u32"></a>



#### early-drop-block (`u32`)

<a id="rst-mark-block-u32"></a>



#### mark-block (`u32`)

<a id="rst-route-attrs"></a>
<a id="rst-tc-attribute-set-route-attrs"></a>



### route-attrs

<a id="rst-classid-u32-5"></a>



#### classid (`u32`)

<a id="rst-to-u32"></a>



#### to (`u32`)

<a id="rst-from-u32"></a>



#### from (`u32`)

<a id="rst-iif-u32"></a>



#### iif (`u32`)

<a id="rst-police-nest-5"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-act-indexed-array-6"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-taprio-attrs"></a>
<a id="rst-tc-attribute-set-taprio-attrs"></a>



### taprio-attrs

<a id="rst-priomap-binary-1"></a>



#### priomap (`binary`)

- **struct**:

  [tc-mqprio-qopt](#rst-tc-definition-tc-mqprio-qopt)

<a id="rst-sched-entry-list-nest"></a>



#### sched-entry-list (`nest`)

- **nested-attributes**:

  [taprio-sched-entry-list](#rst-tc-attribute-set-taprio-sched-entry-list)

<a id="rst-sched-base-time-s64"></a>



#### sched-base-time (`s64`)

<a id="rst-sched-single-entry-nest"></a>



#### sched-single-entry (`nest`)

- **nested-attributes**:

  [taprio-sched-entry](#rst-tc-attribute-set-taprio-sched-entry)

<a id="rst-sched-clockid-s32"></a>



#### sched-clockid (`s32`)

<a id="rst-pad-pad-26"></a>



#### pad (`pad`)

<a id="rst-admin-sched-binary"></a>



#### admin-sched (`binary`)

<a id="rst-sched-cycle-time-s64"></a>



#### sched-cycle-time (`s64`)

<a id="rst-sched-cycle-time-extension-s64"></a>



#### sched-cycle-time-extension (`s64`)

<a id="rst-flags-u32-5"></a>



#### flags (`u32`)

<a id="rst-txtime-delay-u32"></a>



#### txtime-delay (`u32`)

<a id="rst-tc-entry-nest"></a>



#### tc-entry (`nest`)

- **nested-attributes**:

  [taprio-tc-entry-attrs](#rst-tc-attribute-set-taprio-tc-entry-attrs)

<a id="rst-taprio-sched-entry-list"></a>
<a id="rst-tc-attribute-set-taprio-sched-entry-list"></a>



### taprio-sched-entry-list

<a id="rst-entry-nest-1"></a>



#### entry (`nest`)

- **nested-attributes**:

  [taprio-sched-entry](#rst-tc-attribute-set-taprio-sched-entry)

- **multi-attr**:

  True

<a id="rst-taprio-sched-entry"></a>
<a id="rst-tc-attribute-set-taprio-sched-entry"></a>



### taprio-sched-entry

<a id="rst-index-u32-2"></a>



#### index (`u32`)

<a id="rst-cmd-u8"></a>



#### cmd (`u8`)

<a id="rst-gate-mask-u32"></a>



#### gate-mask (`u32`)

<a id="rst-interval-u32-2"></a>



#### interval (`u32`)

<a id="rst-taprio-tc-entry-attrs"></a>
<a id="rst-tc-attribute-set-taprio-tc-entry-attrs"></a>



### taprio-tc-entry-attrs

<a id="rst-index-u32-3"></a>



#### index (`u32`)

<a id="rst-max-sdu-u32"></a>



#### max-sdu (`u32`)

<a id="rst-fp-u32"></a>



#### fp (`u32`)

<a id="rst-tbf-attrs"></a>
<a id="rst-tc-attribute-set-tbf-attrs"></a>



### tbf-attrs

<a id="rst-parms-binary-21"></a>



#### parms (`binary`)

- **struct**:

  [tc-tbf-qopt](#rst-tc-definition-tc-tbf-qopt)

<a id="rst-rtab-binary-1"></a>



#### rtab (`binary`)

<a id="rst-ptab-binary"></a>



#### ptab (`binary`)

<a id="rst-rate64-u64-3"></a>



#### rate64 (`u64`)

<a id="rst-prate64-u64"></a>



#### prate64 (`u64`)

<a id="rst-burst-u32"></a>



#### burst (`u32`)

<a id="rst-pburst-u32"></a>



#### pburst (`u32`)

<a id="rst-pad-pad-27"></a>



#### pad (`pad`)

<a id="rst-act-sample-attrs"></a>
<a id="rst-tc-attribute-set-act-sample-attrs"></a>



### act-sample-attrs

<a id="rst-tm-binary-17"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-22"></a>



#### parms (`binary`)

- **struct**:

  [tc-gact](#rst-tc-definition-tc-gact)

<a id="rst-rate-u32"></a>



#### rate (`u32`)

<a id="rst-trunc-size-u32"></a>



#### trunc-size (`u32`)

<a id="rst-psample-group-u32"></a>



#### psample-group (`u32`)

<a id="rst-pad-pad-28"></a>



#### pad (`pad`)

<a id="rst-act-gact-attrs"></a>
<a id="rst-tc-attribute-set-act-gact-attrs"></a>



### act-gact-attrs

<a id="rst-tm-binary-18"></a>



#### tm (`binary`)

- **struct**:

  [tcf-t](#rst-tc-definition-tcf-t)

<a id="rst-parms-binary-23"></a>



#### parms (`binary`)

- **struct**:

  [tc-gact](#rst-tc-definition-tc-gact)

<a id="rst-prob-binary"></a>



#### prob (`binary`)

- **struct**:

  [tc-gact-p](#rst-tc-definition-tc-gact-p)

<a id="rst-pad-pad-29"></a>



#### pad (`pad`)

<a id="rst-tca-stab-attrs"></a>
<a id="rst-tc-attribute-set-tca-stab-attrs"></a>



### tca-stab-attrs

<a id="rst-base-binary"></a>



#### base (`binary`)

- **struct**:

  [tc-sizespec](#rst-tc-definition-tc-sizespec)

<a id="rst-data-binary-2"></a>



#### data (`binary`)

<a id="rst-tca-stats-attrs"></a>
<a id="rst-tc-attribute-set-tca-stats-attrs"></a>



### tca-stats-attrs

<a id="rst-basic-binary"></a>



#### basic (`binary`)

- **struct**:

  [gnet-stats-basic](#rst-tc-definition-gnet-stats-basic)

<a id="rst-rate-est-binary"></a>



#### rate-est (`binary`)

- **struct**:

  [gnet-stats-rate-est](#rst-tc-definition-gnet-stats-rate-est)

<a id="rst-queue-binary"></a>



#### queue (`binary`)

- **struct**:

  [gnet-stats-queue](#rst-tc-definition-gnet-stats-queue)

<a id="rst-app-sub-message"></a>



#### app (`sub-message`)

- **sub-message**:

  [tca-stats-app-msg](#rst-tc-sub-message-tca-stats-app-msg)

- **selector**:

  kind

<a id="rst-rate-est64-binary"></a>



#### rate-est64 (`binary`)

- **struct**:

  [gnet-stats-rate-est64](#rst-tc-definition-gnet-stats-rate-est64)

<a id="rst-pad-pad-30"></a>



#### pad (`pad`)

<a id="rst-basic-hw-binary"></a>



#### basic-hw (`binary`)

- **struct**:

  [gnet-stats-basic](#rst-tc-definition-gnet-stats-basic)

<a id="rst-pkt64-u64"></a>



#### pkt64 (`u64`)

<a id="rst-u32-attrs"></a>
<a id="rst-tc-attribute-set-u32-attrs"></a>



### u32-attrs

<a id="rst-classid-u32-6"></a>



#### classid (`u32`)

<a id="rst-hash-u32"></a>



#### hash (`u32`)

<a id="rst-link-u32"></a>



#### link (`u32`)

<a id="rst-divisor-u32-1"></a>



#### divisor (`u32`)

<a id="rst-sel-binary"></a>



#### sel (`binary`)

- **struct**:

  [tc-u32-sel](#rst-tc-definition-tc-u32-sel)

<a id="rst-police-nest-6"></a>



#### police (`nest`)

- **nested-attributes**:

  [police-attrs](#rst-tc-attribute-set-police-attrs)

<a id="rst-act-indexed-array-7"></a>



#### act (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [act-attrs](#rst-tc-attribute-set-act-attrs)

<a id="rst-indev-string-2"></a>



#### indev (`string`)

<a id="rst-pcnt-binary-2"></a>



#### pcnt (`binary`)

- **struct**:

  [tc-u32-pcnt](#rst-tc-definition-tc-u32-pcnt)

<a id="rst-mark-binary"></a>



#### mark (`binary`)

- **struct**:

  [tc-u32-mark](#rst-tc-definition-tc-u32-mark)

<a id="rst-flags-u32-6"></a>



#### flags (`u32`)

<a id="rst-pad-pad-31"></a>



#### pad (`pad`)

<a id="rst-sub-messages"></a>



## Sub-messages

<a id="rst-options-msg"></a>
<a id="rst-tc-sub-message-options-msg"></a>



### options-msg

- **basic**

  - **attribute-set**:

    [basic-attrs](#rst-tc-attribute-set-basic-attrs)

- **bpf**

  - **attribute-set**:

    [bpf-attrs](#rst-tc-attribute-set-bpf-attrs)

- **bfifo**

  - **fixed-header**:

    [tc-fifo-qopt](#rst-tc-definition-tc-fifo-qopt)

- **cake**

  - **attribute-set**:

    [cake-attrs](#rst-tc-attribute-set-cake-attrs)

- **cbs**

  - **attribute-set**:

    [cbs-attrs](#rst-tc-attribute-set-cbs-attrs)

- **cgroup**

  - **attribute-set**:

    [cgroup-attrs](#rst-tc-attribute-set-cgroup-attrs)

- **choke**

  - **attribute-set**:

    [choke-attrs](#rst-tc-attribute-set-choke-attrs)

- **clsact**


- **codel**

  - **attribute-set**:

    [codel-attrs](#rst-tc-attribute-set-codel-attrs)

- **drr**

  - **attribute-set**:

    [drr-attrs](#rst-tc-attribute-set-drr-attrs)

- **dualpi2**

  - **attribute-set**:

    [dualpi2-attrs](#rst-tc-attribute-set-dualpi2-attrs)

- **etf**

  - **attribute-set**:

    [etf-attrs](#rst-tc-attribute-set-etf-attrs)

- **ets**

  - **attribute-set**:

    [ets-attrs](#rst-tc-attribute-set-ets-attrs)

- **flow**

  - **attribute-set**:

    [flow-attrs](#rst-tc-attribute-set-flow-attrs)

- **flower**

  - **attribute-set**:

    [flower-attrs](#rst-tc-attribute-set-flower-attrs)

- **fq**

  - **attribute-set**:

    [fq-attrs](#rst-tc-attribute-set-fq-attrs)

- **fq\_codel**

  - **attribute-set**:

    [fq-codel-attrs](#rst-tc-attribute-set-fq-codel-attrs)

- **fq\_pie**

  - **attribute-set**:

    [fq-pie-attrs](#rst-tc-attribute-set-fq-pie-attrs)

- **fw**

  - **attribute-set**:

    [fw-attrs](#rst-tc-attribute-set-fw-attrs)

- **gred**

  - **attribute-set**:

    [gred-attrs](#rst-tc-attribute-set-gred-attrs)

- **hfsc**

  - **fixed-header**:

    [tc-hfsc-qopt](#rst-tc-definition-tc-hfsc-qopt)

- **hhf**

  - **attribute-set**:

    [hhf-attrs](#rst-tc-attribute-set-hhf-attrs)

- **htb**

  - **attribute-set**:

    [htb-attrs](#rst-tc-attribute-set-htb-attrs)

- **ingress**


- **matchall**

  - **attribute-set**:

    [matchall-attrs](#rst-tc-attribute-set-matchall-attrs)

- **mq**


- **mqprio**

  - **fixed-header**:

    [tc-mqprio-qopt](#rst-tc-definition-tc-mqprio-qopt)

- **multiq**

  - **fixed-header**:

    [tc-multiq-qopt](#rst-tc-definition-tc-multiq-qopt)

- **netem**

  - **fixed-header**:

    [tc-netem-qopt](#rst-tc-definition-tc-netem-qopt)

  - **attribute-set**:

    [netem-attrs](#rst-tc-attribute-set-netem-attrs)

- **pfifo**

  - **fixed-header**:

    [tc-fifo-qopt](#rst-tc-definition-tc-fifo-qopt)

- **pfifo\_fast**

  - **fixed-header**:

    [tc-prio-qopt](#rst-tc-definition-tc-prio-qopt)

- **pfifo\_head\_drop**

  - **fixed-header**:

    [tc-fifo-qopt](#rst-tc-definition-tc-fifo-qopt)

- **pie**

  - **attribute-set**:

    [pie-attrs](#rst-tc-attribute-set-pie-attrs)

- **plug**

  - **fixed-header**:

    [tc-plug-qopt](#rst-tc-definition-tc-plug-qopt)

- **prio**

  - **fixed-header**:

    [tc-prio-qopt](#rst-tc-definition-tc-prio-qopt)

- **qfq**

  - **attribute-set**:

    [qfq-attrs](#rst-tc-attribute-set-qfq-attrs)

- **red**

  - **attribute-set**:

    [red-attrs](#rst-tc-attribute-set-red-attrs)

- **route**

  - **attribute-set**:

    [route-attrs](#rst-tc-attribute-set-route-attrs)

- **sfb**

  - **fixed-header**:

    [tc-sfb-qopt](#rst-tc-definition-tc-sfb-qopt)

- **sfq**

  - **fixed-header**:

    [tc-sfq-qopt-v1](#rst-tc-definition-tc-sfq-qopt-v1)

- **taprio**

  - **attribute-set**:

    [taprio-attrs](#rst-tc-attribute-set-taprio-attrs)

- **tbf**

  - **attribute-set**:

    [tbf-attrs](#rst-tc-attribute-set-tbf-attrs)

- **u32**

  - **attribute-set**:

    [u32-attrs](#rst-tc-attribute-set-u32-attrs)

<a id="rst-act-options-msg"></a>
<a id="rst-tc-sub-message-act-options-msg"></a>



### act-options-msg

- **bpf**

  - **attribute-set**:

    [act-bpf-attrs](#rst-tc-attribute-set-act-bpf-attrs)

- **connmark**

  - **attribute-set**:

    [act-connmark-attrs](#rst-tc-attribute-set-act-connmark-attrs)

- **csum**

  - **attribute-set**:

    [act-csum-attrs](#rst-tc-attribute-set-act-csum-attrs)

- **ct**

  - **attribute-set**:

    [act-ct-attrs](#rst-tc-attribute-set-act-ct-attrs)

- **ctinfo**

  - **attribute-set**:

    [act-ctinfo-attrs](#rst-tc-attribute-set-act-ctinfo-attrs)

- **gact**

  - **attribute-set**:

    [act-gact-attrs](#rst-tc-attribute-set-act-gact-attrs)

- **gate**

  - **attribute-set**:

    [act-gate-attrs](#rst-tc-attribute-set-act-gate-attrs)

- **ife**

  - **attribute-set**:

    [act-ife-attrs](#rst-tc-attribute-set-act-ife-attrs)

- **mirred**

  - **attribute-set**:

    [act-mirred-attrs](#rst-tc-attribute-set-act-mirred-attrs)

- **mpls**

  - **attribute-set**:

    [act-mpls-attrs](#rst-tc-attribute-set-act-mpls-attrs)

- **nat**

  - **attribute-set**:

    [act-nat-attrs](#rst-tc-attribute-set-act-nat-attrs)

- **pedit**

  - **attribute-set**:

    [act-pedit-attrs](#rst-tc-attribute-set-act-pedit-attrs)

- **police**

  - **attribute-set**:

    [police-attrs](#rst-tc-attribute-set-police-attrs)

- **sample**

  - **attribute-set**:

    [act-sample-attrs](#rst-tc-attribute-set-act-sample-attrs)

- **simple**

  - **attribute-set**:

    [act-simple-attrs](#rst-tc-attribute-set-act-simple-attrs)

- **skbedit**

  - **attribute-set**:

    [act-skbedit-attrs](#rst-tc-attribute-set-act-skbedit-attrs)

- **skbmod**

  - **attribute-set**:

    [act-skbmod-attrs](#rst-tc-attribute-set-act-skbmod-attrs)

- **tunnel\_key**

  - **attribute-set**:

    [act-tunnel-key-attrs](#rst-tc-attribute-set-act-tunnel-key-attrs)

- **vlan**

  - **attribute-set**:

    [act-vlan-attrs](#rst-tc-attribute-set-act-vlan-attrs)

<a id="rst-tca-stats-app-msg"></a>
<a id="rst-tc-sub-message-tca-stats-app-msg"></a>



### tca-stats-app-msg

- **cake**

  - **attribute-set**:

    [cake-stats-attrs](#rst-tc-attribute-set-cake-stats-attrs)

- **choke**

  - **fixed-header**:

    [tc-choke-xstats](#rst-tc-definition-tc-choke-xstats)

- **codel**

  - **fixed-header**:

    [tc-codel-xstats](#rst-tc-definition-tc-codel-xstats)

- **dualpi2**

  - **fixed-header**:

    [tc-dualpi2-xstats](#rst-tc-definition-tc-dualpi2-xstats)

- **fq**

  - **fixed-header**:

    [tc-fq-qd-stats](#rst-tc-definition-tc-fq-qd-stats)

- **fq\_codel**

  - **fixed-header**:

    [tc-fq-codel-xstats](#rst-tc-definition-tc-fq-codel-xstats)

- **fq\_pie**

  - **fixed-header**:

    [tc-fq-pie-xstats](#rst-tc-definition-tc-fq-pie-xstats)

- **hhf**

  - **fixed-header**:

    [tc-hhf-xstats](#rst-tc-definition-tc-hhf-xstats)

- **pie**

  - **fixed-header**:

    [tc-pie-xstats](#rst-tc-definition-tc-pie-xstats)

- **red**

  - **fixed-header**:

    [tc-red-xstats](#rst-tc-definition-tc-red-xstats)

- **sfb**

  - **fixed-header**:

    [tc-sfb-xstats](#rst-tc-definition-tc-sfb-xstats)

- **sfq**

  - **fixed-header**:

    [tc-sfq-xstats](#rst-tc-definition-tc-sfq-xstats)

---

# Family tcp_metrics netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the tcp_metrics Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-tcp-metrics-netlink-specification"></a>
<a id="rst-netlink-tcp-metrics"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Management interface for TCP metrics.

<a id="rst-operations"></a>



## Operations

<a id="rst-get"></a>
<a id="rst-tcp-metrics-operation-get"></a>



### get



Retrieve metrics.

- **attribute-set**:

  [tcp-metrics](#rst-tcp-metrics-attribute-set-tcp-metrics)

- **dont-validate**:

  \['strict', 'dump'\]

- **do**:

  **request**

  - **attributes**:

    \[`addr-ipv4`, `addr-ipv6`, `saddr-ipv4`, `saddr-ipv6`\]

  **reply**

  - **attributes**:

    \[`addr-ipv4`, `addr-ipv6`, `saddr-ipv4`, `saddr-ipv6`, `age`, `vals`, `fopen-mss`, `fopen-syn-drops`, `fopen-syn-drop-ts`, `fopen-cookie`\]

- **dump**:

  **reply**

  - **attributes**:

    \[`addr-ipv4`, `addr-ipv6`, `saddr-ipv4`, `saddr-ipv6`, `age`, `vals`, `fopen-mss`, `fopen-syn-drops`, `fopen-syn-drop-ts`, `fopen-cookie`\]

<a id="rst-del"></a>
<a id="rst-tcp-metrics-operation-del"></a>



### del



Delete metrics.

- **attribute-set**:

  [tcp-metrics](#rst-tcp-metrics-attribute-set-tcp-metrics)

- **dont-validate**:

  \['strict', 'dump'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`addr-ipv4`, `addr-ipv6`, `saddr-ipv4`, `saddr-ipv6`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-tcp-fastopen-cookie-max"></a>
<a id="rst-tcp-metrics-definition-tcp-fastopen-cookie-max"></a>



### tcp-fastopen-cookie-max

- **type**:

  const

- **value**:

  16

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-tcp-metrics"></a>
<a id="rst-tcp-metrics-attribute-set-tcp-metrics"></a>



### tcp-metrics

<a id="rst-addr-ipv4-u32"></a>



#### addr-ipv4 (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-addr-ipv6-binary"></a>



#### addr-ipv6 (`binary`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv6

<a id="rst-age-u64"></a>



#### age (`u64`)

<a id="rst-tw-tsval-u32"></a>



#### tw-tsval (`u32`)

- **doc**:

  unused

<a id="rst-tw-ts-stamp-s32"></a>



#### tw-ts-stamp (`s32`)

- **doc**:

  unused

<a id="rst-vals-nest"></a>



#### vals (`nest`)

- **nested-attributes**:

  [metrics](#rst-tcp-metrics-attribute-set-metrics)

<a id="rst-fopen-mss-u16"></a>



#### fopen-mss (`u16`)

<a id="rst-fopen-syn-drops-u16"></a>



#### fopen-syn-drops (`u16`)

<a id="rst-fopen-syn-drop-ts-u64"></a>



#### fopen-syn-drop-ts (`u64`)

<a id="rst-fopen-cookie-binary"></a>



#### fopen-cookie (`binary`)

<a id="rst-saddr-ipv4-u32"></a>



#### saddr-ipv4 (`u32`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv4

<a id="rst-saddr-ipv6-binary"></a>



#### saddr-ipv6 (`binary`)

- **byte-order**:

  big-endian

- **display-hint**:

  ipv6

<a id="rst-pad-pad"></a>



#### pad (`pad`)

<a id="rst-metrics"></a>
<a id="rst-tcp-metrics-attribute-set-metrics"></a>



### metrics



Attributes with metrics. Note that the values here do not match
the TCP\_METRIC\_\* defines in the kernel, because kernel defines
are off-by one (e.g. rtt is defined as enum 0, while netlink carries
attribute type 1).

<a id="rst-rtt-u32"></a>



#### rtt (`u32`)

- **doc**:

  Round Trip Time (RTT), in msecs with 3 bits fractional (left-shift by 3 to get the msec value).

<a id="rst-rttvar-u32"></a>



#### rttvar (`u32`)

- **doc**:

  Round Trip Time VARiance (RTT), in msecs with 2 bits fractional (left-shift by 2 to get the msec value).

<a id="rst-ssthresh-u32"></a>



#### ssthresh (`u32`)

- **doc**:

  Slow Start THRESHold.

<a id="rst-cwnd-u32"></a>



#### cwnd (`u32`)

- **doc**:

  Congestion Window.

<a id="rst-reodering-u32"></a>



#### reodering (`u32`)

- **doc**:

  Reodering metric.

<a id="rst-rtt-us-u32"></a>



#### rtt-us (`u32`)

- **doc**:

  Round Trip Time (RTT), in usecs, with 3 bits fractional (left-shift by 3 to get the msec value).

<a id="rst-rttvar-us-u32"></a>



#### rttvar-us (`u32`)

- **doc**:

  Round Trip Time (RTT), in usecs, with 2 bits fractional (left-shift by 3 to get the msec value).

---

# Family team netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the team Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-team-netlink-specification"></a>
<a id="rst-netlink-team"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



Network team device driver.

<a id="rst-operations"></a>



## Operations

<a id="rst-noop"></a>
<a id="rst-team-operation-noop"></a>



### noop



No operation

- **value**:

  0

- **attribute-set**:

  [team](#rst-team-attribute-set-team)

- **dont-validate**:

  \['strict'\]

- **do**:

  **reply**

  - **attributes**:

    \[`team-ifindex`\]

<a id="rst-options-set"></a>
<a id="rst-team-operation-options-set"></a>



### options-set



Set team options

- **attribute-set**:

  [team](#rst-team-attribute-set-team)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`team-ifindex`, `list-option`\]

  **reply**

  - **attributes**:

    \[`team-ifindex`, `list-option`\]

<a id="rst-options-get"></a>
<a id="rst-team-operation-options-get"></a>



### options-get



Get team options info

- **attribute-set**:

  [team](#rst-team-attribute-set-team)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`team-ifindex`\]

  **reply**

  - **attributes**:

    \[`team-ifindex`, `list-option`\]

<a id="rst-port-list-get"></a>
<a id="rst-team-operation-port-list-get"></a>



### port-list-get



Get team ports info

- **attribute-set**:

  [team](#rst-team-attribute-set-team)

- **dont-validate**:

  \['strict'\]

- **flags**:

  \[`admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`team-ifindex`\]

  **reply**

  - **attributes**:

    \[`team-ifindex`, `list-port`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-string-max-len"></a>
<a id="rst-team-definition-string-max-len"></a>



### string-max-len

- **type**:

  const

- **value**:

  32

<a id="rst-genl-change-event-mc-grp-name"></a>
<a id="rst-team-definition-genl-change-event-mc-grp-name"></a>



### genl-change-event-mc-grp-name

- **type**:

  const

- **value**:

  change\_event

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-team"></a>
<a id="rst-team-attribute-set-team"></a>



### team



The team nested layout of get/set msg looks like:

```text
[TEAM_ATTR_LIST_OPTION]
    [TEAM_ATTR_ITEM_OPTION]
        [TEAM_ATTR_OPTION_*], ...
    [TEAM_ATTR_ITEM_OPTION]
        [TEAM_ATTR_OPTION_*], ...
    ...
[TEAM_ATTR_LIST_PORT]
    [TEAM_ATTR_ITEM_PORT]
        [TEAM_ATTR_PORT_*], ...
    [TEAM_ATTR_ITEM_PORT]
        [TEAM_ATTR_PORT_*], ...
    ...
```

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-team-ifindex-u32"></a>



#### team-ifindex (`u32`)

<a id="rst-list-option-nest"></a>



#### list-option (`nest`)

- **nested-attributes**:

  [item-option](#rst-team-attribute-set-item-option)

<a id="rst-list-port-nest"></a>



#### list-port (`nest`)

- **nested-attributes**:

  [item-port](#rst-team-attribute-set-item-port)

<a id="rst-item-option"></a>
<a id="rst-team-attribute-set-item-option"></a>



### item-option

<a id="rst-option-unspec-unused"></a>



#### option-unspec (`unused`)

- **value**:

  0

<a id="rst-option-nest"></a>



#### option (`nest`)

- **nested-attributes**:

  [attr-option](#rst-team-attribute-set-attr-option)

<a id="rst-attr-option"></a>
<a id="rst-team-attribute-set-attr-option"></a>



### attr-option

<a id="rst-unspec-unused-1"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-name-string"></a>



#### name (`string`)

<a id="rst-changed-flag"></a>



#### changed (`flag`)

<a id="rst-type-u8"></a>



#### type (`u8`)

<a id="rst-data-binary"></a>



#### data (`binary`)

<a id="rst-removed-flag"></a>



#### removed (`flag`)

<a id="rst-port-ifindex-u32"></a>



#### port-ifindex (`u32`)

- **doc**:

  for per-port options

<a id="rst-array-index-u32"></a>



#### array-index (`u32`)

- **doc**:

  for array options

<a id="rst-item-port"></a>
<a id="rst-team-attribute-set-item-port"></a>



### item-port

<a id="rst-port-unspec-unused"></a>



#### port-unspec (`unused`)

- **value**:

  0

<a id="rst-port-nest"></a>



#### port (`nest`)

- **nested-attributes**:

  [attr-port](#rst-team-attribute-set-attr-port)

<a id="rst-attr-port"></a>
<a id="rst-team-attribute-set-attr-port"></a>



### attr-port

<a id="rst-unspec-unused-2"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

<a id="rst-changed-flag-1"></a>



#### changed (`flag`)

<a id="rst-linkup-flag"></a>



#### linkup (`flag`)

<a id="rst-speed-u32"></a>



#### speed (`u32`)

<a id="rst-duplex-u8"></a>



#### duplex (`u8`)

<a id="rst-removed-flag-1"></a>



#### removed (`flag`)

---

# Family wireguard netlink specification

_Peios Kernel / Internals / Netlink / specs_

> Protocol reference for the wireguard Netlink family, generated from the Peios kernel specification.

<!-- SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) -->


<a id="rst-family-wireguard-netlink-specification"></a>
<a id="rst-netlink-wireguard"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>



## Summary



**Netlink protocol to control WireGuard network devices.**



The below enums and macros are for interfacing with WireGuard, using generic
netlink, with family `WG_GENL_NAME` and version `WG_GENL_VERSION`. It
defines two commands: get and set. Note that while they share many common
attributes, these two commands actually accept a slightly different set of
inputs and outputs. These differences are noted under the individual
attributes.

<a id="rst-operations"></a>



## Operations

<a id="rst-get-device"></a>
<a id="rst-wireguard-operation-get-device"></a>



### get-device

<a id="rst-retrieve-wireguard-device"></a>



#### Retrieve WireGuard device



The command should be called with one but not both of:

- `WGDEVICE_A_IFINDEX`


- `WGDEVICE_A_IFNAME`




The kernel will then return several messages (`NLM_F_MULTI`). It is
possible that all of the allowed IPs of a single peer will not fit
within a single netlink message. In that case, the same peer will be
written in the following message, except it will only contain
`WGPEER_A_PUBLIC_KEY` and `WGPEER_A_ALLOWEDIPS`. This may occur
several times in a row for the same peer. It is then up to the receiver
to coalesce adjacent peers. Likewise, it is possible that all peers will
not fit within a single message. So, subsequent peers will be sent in
following messages, except those will only contain `WGDEVICE_A_IFNAME`
and `WGDEVICE_A_PEERS`. It is then up to the receiver to coalesce
these messages to form the complete list of peers.



Since this is an `NLA_F_DUMP` command, the final message will always
be `NLMSG_DONE`, even if an error occurs. However, this `NLMSG_DONE`
message contains an integer error code. It is either zero or a negative
error code corresponding to the errno.

- **value**:

  0

- **attribute-set**:

  [wgdevice](#rst-wireguard-attribute-set-wgdevice)

- **flags**:

  \[`uns-admin-perm`\]

- **dump**:

  **pre**



  wg-get-device-start

  **post**



  wg-get-device-done

  **request**

  - **attributes**:

    \[`ifindex`, `ifname`\]

  **reply**

  - **attributes**:

    \[`ifindex`, `ifname`, `private-key`, `public-key`, `flags`, `listen-port`, `fwmark`, `peers`\]

<a id="rst-set-device"></a>
<a id="rst-wireguard-operation-set-device"></a>



### set-device

<a id="rst-set-wireguard-device"></a>



#### Set WireGuard device



This command should be called with a wgdevice set, containing one but
not both of `WGDEVICE_A_IFINDEX` and `WGDEVICE_A_IFNAME`.



It is possible that the amount of configuration data exceeds that of the
maximum message length accepted by the kernel. In that case, several
messages should be sent one after another, with each successive one
filling in information not contained in the prior. Note that if
`WGDEVICE_F_REPLACE_PEERS` is specified in the first message, it
probably should not be specified in fragments that come after, so that
the list of peers is only cleared the first time but appended after.
Likewise for peers, if `WGPEER_F_REPLACE_ALLOWEDIPS` is specified in
the first message of a peer, it likely should not be specified in
subsequent fragments.



If an error occurs, `NLMSG_ERROR` will reply containing an errno.

- **value**:

  1

- **attribute-set**:

  [wgdevice](#rst-wireguard-attribute-set-wgdevice)

- **flags**:

  \[`uns-admin-perm`\]

- **do**:

  **request**

  - **attributes**:

    \[`ifindex`, `ifname`, `private-key`, `public-key`, `flags`, `listen-port`, `fwmark`, `peers`\]

<a id="rst-definitions"></a>



## Definitions

<a id="rst-key-len"></a>
<a id="rst-wireguard-definition-key-len"></a>



### key-len

- **name-prefix**:

  wg-

- **type**:

  const

- **value**:

  32

<a id="rst-kernel-timespec"></a>
<a id="rst-wireguard-definition-kernel-timespec"></a>



### --kernel-timespec

- **type**:

  struct

- **header**:

  linux/time\_types.h

- **members**:

  - **sec (`u64`)**:

    Number of seconds, since UNIX epoch.

  - **nsec (`u64`)**:

    Number of nanoseconds, after the second began.

<a id="rst-wgdevice-flags"></a>
<a id="rst-wireguard-definition-wgdevice-flags"></a>



### wgdevice-flags

- **name-prefix**:

  wgdevice-f-

- **enum-name**:

  wgdevice-flag

- **type**:

  flags

- **entries**:

  - `replace-peers`

<a id="rst-wgpeer-flags"></a>
<a id="rst-wireguard-definition-wgpeer-flags"></a>



### wgpeer-flags

- **name-prefix**:

  wgpeer-f-

- **enum-name**:

  wgpeer-flag

- **type**:

  flags

- **entries**:

  - `remove-me`


  - `replace-allowedips`


  - `update-only`

<a id="rst-wgallowedip-flags"></a>
<a id="rst-wireguard-definition-wgallowedip-flags"></a>



### wgallowedip-flags

- **name-prefix**:

  wgallowedip-f-

- **enum-name**:

  wgallowedip-flag

- **type**:

  flags

- **entries**:

  - `remove-me`

<a id="rst-attribute-sets"></a>



## Attribute sets

<a id="rst-wgdevice"></a>
<a id="rst-wireguard-attribute-set-wgdevice"></a>



### wgdevice

<a id="rst-unspec-unused"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-ifindex-u32"></a>



#### ifindex (`u32`)

<a id="rst-ifname-string"></a>



#### ifname (`string`)

<a id="rst-private-key-binary"></a>



#### private-key (`binary`)

- **doc**:

  Set to all zeros to remove.

- **display-hint**:

  hex

<a id="rst-public-key-binary"></a>



#### public-key (`binary`)

- **display-hint**:

  hex

<a id="rst-flags-u32"></a>



#### flags (`u32`)

- **doc**:

  `0` or `WGDEVICE_F_REPLACE_PEERS` if all current peers should be removed prior to adding the list below.

- **enum**:

  [wgdevice-flags](#rst-wireguard-definition-wgdevice-flags)

<a id="rst-listen-port-u16"></a>



#### listen-port (`u16`)

- **doc**:

  Set as `0` to choose randomly.

<a id="rst-fwmark-u32"></a>



#### fwmark (`u32`)

- **doc**:

  Set as `0` to disable.

<a id="rst-peers-indexed-array"></a>



#### peers (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [wgpeer](#rst-wireguard-attribute-set-wgpeer)

- **doc**:

  The index/type parameter is unused on `SET_DEVICE` operations and is zero on `GET_DEVICE` operations.

<a id="rst-wgpeer"></a>
<a id="rst-wireguard-attribute-set-wgpeer"></a>



### wgpeer

<a id="rst-unspec-unused-1"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-public-key-binary-1"></a>



#### public-key (`binary`)

- **display-hint**:

  hex

<a id="rst-preshared-key-binary"></a>



#### preshared-key (`binary`)

- **doc**:

  Set as all zeros to remove.

- **display-hint**:

  hex

<a id="rst-flags-u32-1"></a>



#### flags (`u32`)

- **doc**:

  `0` and/or `WGPEER_F_REMOVE_ME` if the specified peer should not exist at the end of the operation, rather than added/updated and/or `WGPEER_F_REPLACE_ALLOWEDIPS` if all current allowed IPs of this peer should be removed prior to adding the list below and/or `WGPEER_F_UPDATE_ONLY` if the peer should only be set if it already exists.

- **enum**:

  [wgpeer-flags](#rst-wireguard-definition-wgpeer-flags)

<a id="rst-endpoint-binary"></a>



#### endpoint (`binary`)

- **doc**:

  struct sockaddr\_in or struct sockaddr\_in6

<a id="rst-persistent-keepalive-interval-u16"></a>



#### persistent-keepalive-interval (`u16`)

- **doc**:

  Set as `0` to disable.

<a id="rst-last-handshake-time-binary"></a>



#### last-handshake-time (`binary`)

- **struct**:

  [--kernel-timespec](#rst-wireguard-definition-kernel-timespec)

<a id="rst-rx-bytes-u64"></a>



#### rx-bytes (`u64`)

<a id="rst-tx-bytes-u64"></a>



#### tx-bytes (`u64`)

<a id="rst-allowedips-indexed-array"></a>



#### allowedips (`indexed-array`)

- **sub-type**:

  nest

- **nested-attributes**:

  [wgallowedip](#rst-wireguard-attribute-set-wgallowedip)

- **doc**:

  The index/type parameter is unused on `SET_DEVICE` operations and is zero on `GET_DEVICE` operations.

<a id="rst-protocol-version-u32"></a>



#### protocol-version (`u32`)

- **doc**:

  Should not be set or used at all by most users of this API, as the most recent protocol will be used when this is unset. Otherwise, must be set to `1`.

<a id="rst-wgallowedip"></a>
<a id="rst-wireguard-attribute-set-wgallowedip"></a>



### wgallowedip

<a id="rst-unspec-unused-2"></a>



#### unspec (`unused`)

- **value**:

  0

<a id="rst-family-u16"></a>



#### family (`u16`)

- **doc**:

  IP family, either `AF_INET` or `AF_INET6`.

<a id="rst-ipaddr-binary"></a>



#### ipaddr (`binary`)

- **doc**:

  Either `struct in_addr` or `struct in6_addr`.

- **display-hint**:

  ipv4-or-v6

<a id="rst-cidr-mask-u8"></a>



#### cidr-mask (`u8`)

<a id="rst-flags-u32-2"></a>



#### flags (`u32`)

- **doc**:

  `WGALLOWEDIP_F_REMOVE_ME` if the specified IP should be removed; otherwise, this IP will be added if it is not already present.

- **enum**:

  [wgallowedip-flags](#rst-wireguard-definition-wgallowedip-flags)

---

# genetlink-c Netlink schema

_Peios Kernel / Internals / Netlink_

> Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.

Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.


```yaml
# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
%YAML 1.2
---
$id: http://kernel.org/schemas/netlink/genetlink-c.yaml#
$schema: https://json-schema.org/draft-07/schema

# Common defines
$defs:
  uint:
    type: integer
    minimum: 0
  len-or-define:
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+( - 1)?$
    minimum: 0
  len-or-limit:
    # literal int, const name, or limit based on fixed-width type
    # e.g. u8-min, u16-max, etc.
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+$
    minimum: 0

# Schema for specs
title: Protocol
description: Specification of a genetlink protocol
type: object
required: [ name, doc, attribute-sets, operations ]
additionalProperties: False
properties:
  name:
    description: Name of the genetlink family.
    type: string
  doc:
    type: string
  protocol:
    description: Schema compatibility level. Default is "genetlink".
    enum: [ genetlink, genetlink-c ]
  uapi-header:
    description: Path to the uAPI header, default is linux/${family-name}.h
    type: string
  # Start genetlink-c
  c-family-name:
    description: Name of the define for the family name.
    type: string
  c-version-name:
    description: Name of the define for the version of the family.
    type: string
  max-by-define:
    description: Makes the number of attributes and commands be specified by a define, not an enum value.
    type: boolean
  cmd-max-name:
    description: Name of the define for the last operation in the list.
    type: string
  cmd-cnt-name:
    description: The explicit name for constant holding the count of operations (last operation + 1).
    type: string
  # End genetlink-c

  definitions:
    description: List of type and constant definitions (enums, flags, defines).
    type: array
    items:
      type: object
      required: [ type, name ]
      additionalProperties: False
      properties:
        name:
          type: string
        header:
          description: For C-compatible languages, header which already defines this value.
          type: string
        type:
          enum: [ const, enum, flags ]
        doc:
          type: string
        # For const
        value:
          description: For const - the value.
          type: [ string, integer ]
        # For enum and flags
        value-start:
          description: For enum or flags the literal initializer for the first value.
          type: [ string, integer ]
        entries:
          description: For enum or flags array of values.
          type: array
          items:
            oneOf:
              - type: string
              - type: object
                required: [ name ]
                additionalProperties: False
                properties:
                  name:
                    type: string
                  value:
                    type: integer
                  doc:
                    type: string
        render-max:
          description: Render the max members for this enum.
          type: boolean
        # Start genetlink-c
        enum-name:
          description: Name for enum, if empty no name will be used.
          type: [ string, "null" ]
        name-prefix:
          description: For enum the prefix of the values, optional.
          type: string
        enum-cnt-name:
          description: Name of the render-max counter enum entry.
          type: string
        # End genetlink-c

  attribute-sets:
    description: Definition of attribute spaces for this family.
    type: array
    items:
      description: Definition of a single attribute space.
      type: object
      required: [ name, attributes ]
      additionalProperties: False
      properties:
        name:
          description: |
            Name used when referring to this space in other definitions, not used outside of the spec.
          type: string
        name-prefix:
          description: |
            Prefix for the C enum name of the attributes. Default family[name]-set[name]-a-
          type: string
        enum-name:
          description: |
            Name for the enum type of the attribute, if empty no name will be used.
          type: [ string, "null" ]
        doc:
          description: Documentation of the space.
          type: string
        subset-of:
          description: |
            Name of another space which this is a logical part of. Sub-spaces can be used to define
            a limited group of attributes which are used in a nest.
          type: string
        # Start genetlink-c
        attr-cnt-name:
          description: The explicit name for constant holding the count of attributes (last attr + 1).
          type: string
        attr-max-name:
          description: The explicit name for last member of attribute enum.
          type: string
        header:
          description: For C-compatible languages, header which already defines this attribute set.
          type: string
        # End genetlink-c
        attributes:
          description: List of attributes in the space.
          type: array
          items:
            type: object
            required: [ name ]
            additionalProperties: False
            properties:
              name:
                type: string
              type: &attr-type
                enum: [ unused, pad, flag, binary,
                        uint, sint, u8, u16, u32, u64, s8, s16, s32, s64,
                        string, nest, indexed-array, nest-type-value ]
              doc:
                description: Documentation of the attribute.
                type: string
              value:
                description: Value for the enum item representing this attribute in the uAPI.
                $ref: '#/$defs/uint'
              type-value:
                description: Name of the value extracted from the type of a nest-type-value attribute.
                type: array
                items:
                  type: string
              byte-order:
                enum: [ little-endian, big-endian ]
              multi-attr:
                type: boolean
              nested-attributes:
                description: Name of the space (sub-space) used inside the attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              enum-as-flags:
                description: |
                  Treat the enum as flags. In most cases enum is either used as flags or as values.
                  Sometimes, however, both forms are necessary, in which case header contains the enum
                  form while specific attributes may request to convert the values into a bitfield.
                type: boolean
              checks:
                description: Kernel input validation.
                type: object
                additionalProperties: False
                properties:
                  flags-mask:
                    description: Name of the flags constant on which to base mask (unsigned scalar types only).
                    type: string
                  min:
                    description: Min value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  max:
                    description: Max value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  min-len:
                    description: Min length for a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  max-len:
                    description: Max length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  exact-len:
                    description: Exact length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  unterminated-ok:
                    description: |
                      For string attributes, do not check whether attribute
                      contains the terminating null character.
                    type: boolean
              sub-type: *attr-type
              display-hint: &display-hint
                description: |
                  Optional format indicator that is intended only for choosing
                  the right formatting mechanism when displaying values of this
                  type.
                enum: [ hex, mac, fddi, ipv4, ipv6, ipv4-or-v6, uuid ]
              # Start genetlink-c
              name-prefix:
                type: string
              # End genetlink-c

      # Make sure name-prefix does not appear in subsets (subsets inherit naming)
      dependencies:
        name-prefix:
          not:
            required: [ subset-of ]
        subset-of:
          not:
            required: [ name-prefix ]

      # type property is only required if not in subset definition
      if:
        properties:
          subset-of:
            not:
              type: string
      then:
        properties:
          attributes:
            items:
              required: [ type ]

  operations:
    description: Operations supported by the protocol.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      enum-model:
        description: |
          The model of assigning values to the operations.
          "unified" is the recommended model where all message types belong
          to a single enum.
          "directional" has the messages sent to the kernel and from the kernel
          enumerated separately.
        enum: [ unified ]
      name-prefix:
        description: |
          Prefix for the C enum name of the command. The name is formed by concatenating
          the prefix with the upper case name of the command, with dashes replaced by underscores.
        type: string
      enum-name:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      async-prefix:
        description: Same as name-prefix but used to render notifications and events to separate enum.
        type: string
      async-enum:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      list:
        description: List of commands
        type: array
        items:
          type: object
          additionalProperties: False
          required: [ name, doc ]
          properties:
            name:
              description: Name of the operation, also defining its C enum value in uAPI.
              type: string
            doc:
              description: Documentation for the command.
              type: string
            value:
              description: Value for the enum in the uAPI.
              $ref: '#/$defs/uint'
            attribute-set:
              description: |
                Attribute space from which attributes directly in the requests and replies
                to this command are defined.
              type: string
            flags: &cmd_flags
              description: Command flags.
              type: array
              items:
                enum: [ admin-perm ]
            dont-validate:
              description: Kernel attribute validation flags.
              type: array
              items:
                enum: [ strict, dump, dump-strict ]
            config-cond:
              description: |
                Name of the kernel config option gating the presence of
                the operation, without the 'CONFIG_' prefix.
              type: string
            do: &subop-type
              description: Main command handler.
              type: object
              additionalProperties: False
              properties:
                request: &subop-attr-list
                  description: Definition of the request message for a given command.
                  type: object
                  additionalProperties: False
                  properties:
                    attributes:
                      description: |
                        Names of attributes from the attribute-set (not full attribute
                        definitions, just names).
                      type: array
                      items:
                        type: string
                reply: *subop-attr-list
                pre:
                  description: Hook for a function to run before the main callback (pre_doit or start).
                  type: string
                post:
                  description: Hook for a function to run after the main callback (post_doit or done).
                  type: string
            dump: *subop-type
            notify:
              description: Name of the command sharing the reply type with this notification.
              type: string
            event:
              type: object
              additionalProperties: False
              properties:
                attributes:
                  description: Explicit list of the attributes for the notification.
                  type: array
                  items:
                    type: string
            mcgrp:
              description: Name of the multicast group generating given notification.
              type: string
  mcast-groups:
    description: List of multicast groups.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      list:
        description: List of groups.
        type: array
        items:
          type: object
          required: [ name ]
          additionalProperties: False
          properties:
            name:
              description: |
                The name for the group, used to form the define and the value of the define.
              type: string
            # Start genetlink-c
            c-define-name:
              description: Override for the name of the define in C uAPI.
              type: string
            # End genetlink-c
            flags: *cmd_flags

  kernel-family:
    description: Additional global attributes used for kernel C code generation.
    type: object
    additionalProperties: False
    properties:
      headers:
        description: |
          List of extra headers which should be included in the source
          of the generated code.
        type: array
        items:
          type: string
      sock-priv:
        description: |
          Literal name of the type which is used within the kernel
          to store the socket state. The type / structure is internal
          to the kernel, and is not defined in the spec.
        type: string

```

---

# genetlink-legacy Netlink schema

_Peios Kernel / Internals / Netlink_

> Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.

Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.


```yaml
# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
%YAML 1.2
---
$id: http://kernel.org/schemas/netlink/genetlink-legacy.yaml#
$schema: https://json-schema.org/draft-07/schema

# Common defines
$defs:
  name:
    type: string
    pattern: ^[0-9a-z-]+$
  uint:
    type: integer
    minimum: 0
  len-or-define:
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+( - 1)?$
    minimum: 0
  len-or-limit:
    # literal int, const name, or limit based on fixed-width type
    # e.g. u8-min, u16-max, etc.
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+$
    minimum: 0

# Schema for specs
title: Protocol
description: Specification of a genetlink protocol
type: object
required: [ name, doc, attribute-sets, operations ]
additionalProperties: False
properties:
  name:
    description: Name of the genetlink family.
    type: string
  doc:
    type: string
  protocol:
    description: Schema compatibility level. Default is "genetlink".
    enum: [ genetlink, genetlink-c, genetlink-legacy ] # Trim
  uapi-header:
    description: Path to the uAPI header, default is linux/${family-name}.h
    type: string
  # Start genetlink-c
  c-family-name:
    description: Name of the define for the family name.
    type: string
  c-version-name:
    description: Name of the define for the version of the family.
    type: string
  max-by-define:
    description: Makes the number of attributes and commands be specified by a define, not an enum value.
    type: boolean
  cmd-max-name:
    description: Name of the define for the last operation in the list.
    type: string
  cmd-cnt-name:
    description: The explicit name for constant holding the count of operations (last operation + 1).
    type: string
  # End genetlink-c
  # Start genetlink-legacy
  kernel-policy:
    description: |
      Defines if the input policy in the kernel is global, per-operation, or split per operation type.
      Default is split.
    enum: [ split, per-op, global ]
  version:
    description: Generic Netlink family version. Default is 1.
    type: integer
    minimum: 1
  # End genetlink-legacy

  definitions:
    description: List of type and constant definitions (enums, flags, defines).
    type: array
    items:
      type: object
      required: [ type, name ]
      additionalProperties: False
      properties:
        name:
          $ref: '#/$defs/name'
        header:
          description: For C-compatible languages, header which already defines this value.
          type: string
        type:
          enum: [ const, enum, flags, struct ] # Trim
        doc:
          type: string
        # For const
        value:
          description: For const - the value.
          type: [ string, integer ]
        # For enum and flags
        value-start:
          description: For enum or flags the literal initializer for the first value.
          type: [ string, integer ]
        entries:
          description: For enum or flags array of values.
          type: array
          items:
            oneOf:
              - type: string
              - type: object
                required: [ name ]
                additionalProperties: False
                properties:
                  name:
                    $ref: '#/$defs/name'
                  value:
                    type: integer
                  doc:
                    type: string
        render-max:
          description: Render the max members for this enum.
          type: boolean
        # Start genetlink-c
        enum-name:
          description: Name for enum, if empty no name will be used.
          type: [ string, "null" ]
        name-prefix:
          description: For enum the prefix of the values, optional.
          type: string
        enum-cnt-name:
          description: Name of the render-max counter enum entry.
          type: string
        # End genetlink-c
        # Start genetlink-legacy
        members:
          description: List of struct members. Only scalars and strings members allowed.
          type: array
          items:
            type: object
            required: [ name, type ]
            additionalProperties: False
            properties:
              name:
                $ref: '#/$defs/name'
              type:
                description: The netlink attribute type
                enum: [ u8, u16, u32, u64, s8, s16, s32, s64, string, binary ]
              len:
                $ref: '#/$defs/len-or-define'
              byte-order:
                enum: [ little-endian, big-endian ]
              doc:
                description: Documentation for the struct member attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              display-hint: &display-hint
                description: |
                  Optional format indicator that is intended only for choosing
                  the right formatting mechanism when displaying values of this
                  type.
                enum: [ hex, mac, fddi, ipv4, ipv6, ipv4-or-v6, uuid ]
              struct:
                description: Name of the nested struct type.
                type: string
        # End genetlink-legacy

  attribute-sets:
    description: Definition of attribute spaces for this family.
    type: array
    items:
      description: Definition of a single attribute space.
      type: object
      required: [ name, attributes ]
      additionalProperties: False
      properties:
        name:
          description: |
            Name used when referring to this space in other definitions, not used outside of the spec.
          $ref: '#/$defs/name'
        name-prefix:
          description: |
            Prefix for the C enum name of the attributes. Default family[name]-set[name]-a-
          type: string
        enum-name:
          description: |
            Name for the enum type of the attribute, if empty no name will be used.
          type: [ string, "null" ]
        doc:
          description: Documentation of the space.
          type: string
        subset-of:
          description: |
            Name of another space which this is a logical part of. Sub-spaces can be used to define
            a limited group of attributes which are used in a nest.
          type: string
        # Start genetlink-c
        attr-cnt-name:
          description: The explicit name for constant holding the count of attributes (last attr + 1).
          type: string
        attr-max-name:
          description: The explicit name for last member of attribute enum.
          type: string
        header:
          description: For C-compatible languages, header which already defines this attribute set.
          type: string
        # End genetlink-c
        attributes:
          description: List of attributes in the space.
          type: array
          items:
            type: object
            required: [ name ]
            additionalProperties: False
            properties:
              name:
                $ref: '#/$defs/name'
              type: &attr-type
                description: The netlink attribute type
                enum: [ unused, pad, flag, binary, bitfield32,
                        uint, sint, u8, u16, u32, u64, s8, s16, s32, s64,
                        string, nest, indexed-array, nest-type-value ]
              doc:
                description: Documentation of the attribute.
                type: string
              value:
                description: Value for the enum item representing this attribute in the uAPI.
                $ref: '#/$defs/uint'
              type-value:
                description: Name of the value extracted from the type of a nest-type-value attribute.
                type: array
                items:
                  type: string
              byte-order:
                enum: [ little-endian, big-endian ]
              multi-attr:
                type: boolean
              nested-attributes:
                description: Name of the space (sub-space) used inside the attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              enum-as-flags:
                description: |
                  Treat the enum as flags. In most cases enum is either used as flags or as values.
                  Sometimes, however, both forms are necessary, in which case header contains the enum
                  form while specific attributes may request to convert the values into a bitfield.
                type: boolean
              checks:
                description: Kernel input validation.
                type: object
                additionalProperties: False
                properties:
                  flags-mask:
                    description: Name of the flags constant on which to base mask (unsigned scalar types only).
                    type: string
                  min:
                    description: Min value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  max:
                    description: Max value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  min-len:
                    description: Min length for a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  max-len:
                    description: Max length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  exact-len:
                    description: Exact length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  unterminated-ok:
                    description: |
                      For string attributes, do not check whether attribute
                      contains the terminating null character.
                    type: boolean
              sub-type: *attr-type
              display-hint: *display-hint
              # Start genetlink-c
              name-prefix:
                type: string
              # End genetlink-c
              # Start genetlink-legacy
              struct:
                description: Name of the struct type used for the attribute.
                type: string
              # End genetlink-legacy

      # Make sure name-prefix does not appear in subsets (subsets inherit naming)
      dependencies:
        name-prefix:
          not:
            required: [ subset-of ]
        subset-of:
          not:
            required: [ name-prefix ]

      # type property is only required if not in subset definition
      if:
        properties:
          subset-of:
            not:
              type: string
      then:
        properties:
          attributes:
            items:
              required: [ type ]

  operations:
    description: Operations supported by the protocol.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      enum-model:
        description: |
          The model of assigning values to the operations.
          "unified" is the recommended model where all message types belong
          to a single enum.
          "directional" has the messages sent to the kernel and from the kernel
          enumerated separately.
        enum: [ unified, directional ] # Trim
      name-prefix:
        description: |
          Prefix for the C enum name of the command. The name is formed by concatenating
          the prefix with the upper case name of the command, with dashes replaced by underscores.
        type: string
      enum-name:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      async-prefix:
        description: Same as name-prefix but used to render notifications and events to separate enum.
        type: string
      async-enum:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      # Start genetlink-legacy
      fixed-header: &fixed-header
        description: |
          Name of the structure defining the optional fixed-length protocol
          header. This header is placed in a message after the netlink and
          genetlink headers and before any attributes.
        type: string
      # End genetlink-legacy
      list:
        description: List of commands
        type: array
        items:
          type: object
          additionalProperties: False
          required: [ name, doc ]
          properties:
            name:
              description: Name of the operation, also defining its C enum value in uAPI.
              $ref: '#/$defs/name'
            doc:
              description: Documentation for the command.
              type: string
            value:
              description: Value for the enum in the uAPI.
              $ref: '#/$defs/uint'
            attribute-set:
              description: |
                Attribute space from which attributes directly in the requests and replies
                to this command are defined.
              type: string
            flags: &cmd_flags
              description: Command flags.
              type: array
              items:
                enum: [ admin-perm, uns-admin-perm ]
            dont-validate:
              description: Kernel attribute validation flags.
              type: array
              items:
                enum: [ strict, dump, dump-strict ]
            config-cond:
              description: |
                Name of the kernel config option gating the presence of
                the operation, without the 'CONFIG_' prefix.
              type: string
            # Start genetlink-legacy
            fixed-header: *fixed-header
            # End genetlink-legacy
            do: &subop-type
              description: Main command handler.
              type: object
              additionalProperties: False
              properties:
                request: &subop-attr-list
                  description: Definition of the request message for a given command.
                  type: object
                  additionalProperties: False
                  properties:
                    attributes:
                      description: |
                        Names of attributes from the attribute-set (not full attribute
                        definitions, just names).
                      type: array
                      items:
                        type: string
                    # Start genetlink-legacy
                    value:
                      description: |
                        ID of this message if value for request and response differ,
                        i.e. requests and responses have different message enums.
                      $ref: '#/$defs/uint'
                    # End genetlink-legacy
                reply: *subop-attr-list
                pre:
                  description: Hook for a function to run before the main callback (pre_doit or start).
                  type: string
                post:
                  description: Hook for a function to run after the main callback (post_doit or done).
                  type: string
            dump: *subop-type
            notify:
              description: Name of the command sharing the reply type with this notification.
              type: string
            event:
              type: object
              additionalProperties: False
              properties:
                attributes:
                  description: Explicit list of the attributes for the notification.
                  type: array
                  items:
                    type: string
            mcgrp:
              description: Name of the multicast group generating given notification.
              type: string
  mcast-groups:
    description: List of multicast groups.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      list:
        description: List of groups.
        type: array
        items:
          type: object
          required: [ name ]
          additionalProperties: False
          properties:
            name:
              description: |
                The name for the group, used to form the define and the value of the define.
              type: string
            # Start genetlink-c
            c-define-name:
              description: Override for the name of the define in C uAPI.
              type: string
            # End genetlink-c
            flags: *cmd_flags

  kernel-family:
    description: Additional global attributes used for kernel C code generation.
    type: object
    additionalProperties: False
    properties:
      headers:
        description: |
          List of extra headers which should be included in the source
          of the generated code.
        type: array
        items:
          type: string
      sock-priv:
        description: |
          Literal name of the type which is used within the kernel
          to store the socket state. The type / structure is internal
          to the kernel, and is not defined in the spec.
        type: string

```

---

# genetlink Netlink schema

_Peios Kernel / Internals / Netlink_

> Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.

Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.


```yaml
# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
%YAML 1.2
---
$id: http://kernel.org/schemas/netlink/genetlink-legacy.yaml#
$schema: https://json-schema.org/draft-07/schema

# Common defines
$defs:
  name:
    type: string
    pattern: ^[0-9a-z-]+$
  uint:
    type: integer
    minimum: 0
  len-or-define:
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+( - 1)?$
    minimum: 0
  len-or-limit:
    # literal int, const name, or limit based on fixed-width type
    # e.g. u8-min, u16-max, etc.
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+$
    minimum: 0

# Schema for specs
title: Protocol
description: Specification of a genetlink protocol
type: object
required: [ name, doc, attribute-sets, operations ]
additionalProperties: False
properties:
  name:
    description: Name of the genetlink family.
    $ref: '#/$defs/name'
  doc:
    type: string
  protocol:
    description: Schema compatibility level. Default is "genetlink".
    enum: [ genetlink ]
  uapi-header:
    description: Path to the uAPI header, default is linux/${family-name}.h
    type: string

  definitions:
    description: List of type and constant definitions (enums, flags, defines).
    type: array
    items:
      type: object
      required: [ type, name ]
      additionalProperties: False
      properties:
        name:
          $ref: '#/$defs/name'
        header:
          description: For C-compatible languages, header which already defines this value.
          type: string
        type:
          enum: [ const, enum, flags ]
        doc:
          type: string
        # For const
        value:
          description: For const - the value.
          type: [ string, integer ]
        # For enum and flags
        value-start:
          description: For enum or flags the literal initializer for the first value.
          type: [ string, integer ]
        entries:
          description: For enum or flags array of values.
          type: array
          items:
            oneOf:
              - type: string
              - type: object
                required: [ name ]
                additionalProperties: False
                properties:
                  name:
                    $ref: '#/$defs/name'
                  value:
                    type: integer
                  doc:
                    type: string
        render-max:
          description: Render the max members for this enum.
          type: boolean

  attribute-sets:
    description: Definition of attribute spaces for this family.
    type: array
    items:
      description: Definition of a single attribute space.
      type: object
      required: [ name, attributes ]
      additionalProperties: False
      properties:
        name:
          description: |
            Name used when referring to this space in other definitions, not used outside of the spec.
          $ref: '#/$defs/name'
        name-prefix:
          description: |
            Prefix for the C enum name of the attributes. Default family[name]-set[name]-a-
          type: string
        enum-name:
          description: Name for the enum type of the attribute.
          type: string
        doc:
          description: Documentation of the space.
          type: string
        subset-of:
          description: |
            Name of another space which this is a logical part of. Sub-spaces can be used to define
            a limited group of attributes which are used in a nest.
          type: string
        attributes:
          description: List of attributes in the space.
          type: array
          items:
            type: object
            required: [ name ]
            additionalProperties: False
            properties:
              name:
                $ref: '#/$defs/name'
              type: &attr-type
                enum: [ unused, pad, flag, binary,
                        uint, sint, u8, u16, u32, u64, s8, s16, s32, s64,
                        string, nest, indexed-array, nest-type-value ]
              doc:
                description: Documentation of the attribute.
                type: string
              value:
                description: Value for the enum item representing this attribute in the uAPI.
                $ref: '#/$defs/uint'
              type-value:
                description: Name of the value extracted from the type of a nest-type-value attribute.
                type: array
                items:
                  type: string
              byte-order:
                enum: [ little-endian, big-endian ]
              multi-attr:
                type: boolean
              nested-attributes:
                description: Name of the space (sub-space) used inside the attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              enum-as-flags:
                description: |
                  Treat the enum as flags. In most cases enum is either used as flags or as values.
                  Sometimes, however, both forms are necessary, in which case header contains the enum
                  form while specific attributes may request to convert the values into a bitfield.
                type: boolean
              checks:
                description: Kernel input validation.
                type: object
                additionalProperties: False
                properties:
                  flags-mask:
                    description: Name of the flags constant on which to base mask (unsigned scalar types only).
                    type: string
                  min:
                    description: Min value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  max:
                    description: Max value for an integer attribute.
                    $ref: '#/$defs/len-or-limit'
                  min-len:
                    description: Min length for a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  max-len:
                    description: Max length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  exact-len:
                    description: Exact length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
              sub-type: *attr-type
              display-hint: &display-hint
                description: |
                  Optional format indicator that is intended only for choosing
                  the right formatting mechanism when displaying values of this
                  type.
                enum: [ hex, mac, fddi, ipv4, ipv6, ipv4-or-v6, uuid ]

      # Make sure name-prefix does not appear in subsets (subsets inherit naming)
      dependencies:
        name-prefix:
          not:
            required: [ subset-of ]
        subset-of:
          not:
            required: [ name-prefix ]

      # type property is only required if not in subset definition
      if:
        properties:
          subset-of:
            not:
              type: string
      then:
        properties:
          attributes:
            items:
              required: [ type ]

  operations:
    description: Operations supported by the protocol.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      enum-model:
        description: |
          The model of assigning values to the operations.
          "unified" is the recommended model where all message types belong
          to a single enum.
          "directional" has the messages sent to the kernel and from the kernel
          enumerated separately.
        enum: [ unified ]
      name-prefix:
        description: |
          Prefix for the C enum name of the command. The name is formed by concatenating
          the prefix with the upper case name of the command, with dashes replaced by underscores.
        type: string
      enum-name:
        description: Name for the enum type with commands.
        type: string
      async-prefix:
        description: Same as name-prefix but used to render notifications and events to separate enum.
        type: string
      async-enum:
        description: Name for the enum type with notifications/events.
        type: string
      list:
        description: List of commands
        type: array
        items:
          type: object
          additionalProperties: False
          required: [ name, doc ]
          properties:
            name:
              description: Name of the operation, also defining its C enum value in uAPI.
              $ref: '#/$defs/name'
            doc:
              description: Documentation for the command.
              type: string
            value:
              description: Value for the enum in the uAPI.
              $ref: '#/$defs/uint'
            attribute-set:
              description: |
                Attribute space from which attributes directly in the requests and replies
                to this command are defined.
              type: string
            flags: &cmd_flags
              description: Command flags.
              type: array
              items:
                enum: [ admin-perm ]
            dont-validate:
              description: Kernel attribute validation flags.
              type: array
              items:
                enum: [ strict, dump, dump-strict ]
            config-cond:
              description: |
                Name of the kernel config option gating the presence of
                the operation, without the 'CONFIG_' prefix.
              type: string
            do: &subop-type
              description: Main command handler.
              type: object
              additionalProperties: False
              properties:
                request: &subop-attr-list
                  description: Definition of the request message for a given command.
                  type: object
                  additionalProperties: False
                  properties:
                    attributes:
                      description: |
                        Names of attributes from the attribute-set (not full attribute
                        definitions, just names).
                      type: array
                      items:
                        type: string
                reply: *subop-attr-list
                pre:
                  description: Hook for a function to run before the main callback (pre_doit or start).
                  type: string
                post:
                  description: Hook for a function to run after the main callback (post_doit or done).
                  type: string
            dump: *subop-type
            notify:
              description: Name of the command sharing the reply type with this notification.
              type: string
            event:
              type: object
              additionalProperties: False
              properties:
                attributes:
                  description: Explicit list of the attributes for the notification.
                  type: array
                  items:
                    type: string
            mcgrp:
              description: Name of the multicast group generating given notification.
              type: string
  mcast-groups:
    description: List of multicast groups.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      list:
        description: List of groups.
        type: array
        items:
          type: object
          required: [ name ]
          additionalProperties: False
          properties:
            name:
              description: |
                The name for the group, used to form the define and the value of the define.
              $ref: '#/$defs/name'
            flags: *cmd_flags

  kernel-family:
    description: Additional global attributes used for kernel C code generation.
    type: object
    additionalProperties: False
    properties:
      headers:
        description: |
          List of extra headers which should be included in the source
          of the generated code.
        type: array
        items:
          type: string
      sock-priv:
        description: |
          Literal name of the type which is used within the kernel
          to store the socket state. The type / structure is internal
          to the kernel, and is not defined in the spec.
        type: string

```

---

# netlink-raw Netlink schema

_Peios Kernel / Internals / Netlink_

> Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.

Machine-readable schema defining the structure and constraints of Netlink specifications. This is the schema source, including its descriptions and validation rules.


```yaml
# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
%YAML 1.2
---
$id: http://kernel.org/schemas/netlink/netlink-raw.yaml#
$schema: https://json-schema.org/draft-07/schema

# Common defines
$defs:
  name:
    type: string
    pattern: ^[0-9a-z-]+$
  name-cap:
    type: string
    pattern: ^[0-9a-zA-Z-]+$
  uint:
    type: integer
    minimum: 0
  len-or-define:
    type: [ string, integer ]
    pattern: ^[0-9A-Za-z_-]+( - 1)?$
    minimum: 0

# Schema for specs
title: Protocol
description: Specification of a raw netlink protocol
type: object
required: [ name, doc, attribute-sets, operations ]
additionalProperties: False
properties:
  name:
    description: Name of the netlink family.
    type: string
  doc:
    type: string
  protocol:
    description: Schema compatibility level.
    enum: [ netlink-raw ] # Trim
  # Start netlink-raw
  protonum:
    description: Protocol number to use for netlink-raw
    type: integer
  # End netlink-raw
  uapi-header:
    description: Path to the uAPI header, default is linux/${family-name}.h
    type: string
  # Start genetlink-c
  c-family-name:
    description: Name of the define for the family name.
    type: string
  c-version-name:
    description: Name of the define for the version of the family.
    type: string
  max-by-define:
    description: Makes the number of attributes and commands be specified by a define, not an enum value.
    type: boolean
  cmd-max-name:
    description: Name of the define for the last operation in the list.
    type: string
  cmd-cnt-name:
    description: The explicit name for constant holding the count of operations (last operation + 1).
    type: string
  # End genetlink-c
  # Start genetlink-legacy
  kernel-policy:
    description: |
      Defines if the input policy in the kernel is global, per-operation, or split per operation type.
      Default is split.
    enum: [ split, per-op, global ]
  # End genetlink-legacy

  definitions:
    description: List of type and constant definitions (enums, flags, defines).
    type: array
    items:
      type: object
      required: [ type, name ]
      additionalProperties: False
      properties:
        name:
          $ref: '#/$defs/name'
        header:
          description: For C-compatible languages, header which already defines this value.
          type: string
        type:
          enum: [ const, enum, flags, struct ] # Trim
        doc:
          type: string
        # For const
        value:
          description: For const - the value.
          type: [ string, integer ]
        # For enum and flags
        value-start:
          description: For enum or flags the literal initializer for the first value.
          type: [ string, integer ]
        entries:
          description: For enum or flags array of values.
          type: array
          items:
            oneOf:
              - type: string
              - type: object
                required: [ name ]
                additionalProperties: False
                properties:
                  name:
                    $ref: '#/$defs/name'
                  value:
                    type: integer
                  doc:
                    type: string
        render-max:
          description: Render the max members for this enum.
          type: boolean
        # Start genetlink-c
        enum-name:
          description: Name for enum, if empty no name will be used.
          type: [ string, "null" ]
        name-prefix:
          description: For enum the prefix of the values, optional.
          type: string
        # End genetlink-c
        # Start genetlink-legacy
        members:
          description: List of struct members. Only scalars and strings members allowed.
          type: array
          items:
            type: object
            required: [ name, type ]
            additionalProperties: False
            properties:
              name:
                $ref: '#/$defs/name-cap'
              type:
                description: |
                  The netlink attribute type. Members of type 'binary' or 'pad'
                  must also have the 'len' property set.
                enum: [ u8, u16, u32, u64, s8, s16, s32, s64, string, binary, pad ]
              len:
                $ref: '#/$defs/len-or-define'
              byte-order:
                enum: [ little-endian, big-endian ]
              doc:
                description: Documentation for the struct member attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              enum-as-flags:
                description: |
                  Treat the enum as flags. In most cases enum is either used as flags or as values.
                  Sometimes, however, both forms are necessary, in which case header contains the enum
                  form while specific attributes may request to convert the values into a bitfield.
                type: boolean
              display-hint: &display-hint
                description: |
                  Optional format indicator that is intended only for choosing
                  the right formatting mechanism when displaying values of this
                  type.
                enum: [ hex, mac, fddi, ipv4, ipv6, ipv4-or-v6, uuid ]
              struct:
                description: Name of the nested struct type.
                type: string
            if:
              properties:
                type:
                  const: pad
            then:
              required: [ len ]
            if:
              properties:
                type:
                  const: binary
            then:
              oneOf:
                - required: [ len ]
                - required: [ struct ]
        # End genetlink-legacy

  attribute-sets:
    description: Definition of attribute spaces for this family.
    type: array
    items:
      description: Definition of a single attribute space.
      type: object
      required: [ name, attributes ]
      additionalProperties: False
      properties:
        name:
          description: |
            Name used when referring to this space in other definitions, not used outside of the spec.
          $ref: '#/$defs/name'
        name-prefix:
          description: |
            Prefix for the C enum name of the attributes. Default family[name]-set[name]-a-
          type: string
        enum-name:
          description: |
            Name for the enum type of the attribute, if empty no name will be used.
          type: [ string, "null" ]
        doc:
          description: Documentation of the space.
          type: string
        subset-of:
          description: |
            Name of another space which this is a logical part of. Sub-spaces can be used to define
            a limited group of attributes which are used in a nest.
          type: string
        # Start genetlink-c
        attr-cnt-name:
          description: The explicit name for constant holding the count of attributes (last attr + 1).
          type: string
        attr-max-name:
          description: The explicit name for last member of attribute enum.
          type: string
        header:
          description: For C-compatible languages, header which already defines this attribute set.
          type: string
        # End genetlink-c
        attributes:
          description: List of attributes in the space.
          type: array
          items:
            type: object
            required: [ name ]
            additionalProperties: False
            properties:
              name:
                $ref: '#/$defs/name'
              type: &attr-type
                description: The netlink attribute type
                enum: [ unused, pad, flag, binary, bitfield32,
                        uint, sint, u8, u16, u32, u64, s8, s16, s32, s64,
                        string, nest, indexed-array, nest-type-value,
                        sub-message ]
              doc:
                description: Documentation of the attribute.
                type: string
              value:
                description: Value for the enum item representing this attribute in the uAPI.
                $ref: '#/$defs/uint'
              type-value:
                description: Name of the value extracted from the type of a nest-type-value attribute.
                type: array
                items:
                  type: string
              byte-order:
                enum: [ little-endian, big-endian ]
              multi-attr:
                type: boolean
              nested-attributes:
                description: Name of the space (sub-space) used inside the attribute.
                type: string
              enum:
                description: Name of the enum type used for the attribute.
                type: string
              enum-as-flags:
                description: |
                  Treat the enum as flags. In most cases enum is either used as flags or as values.
                  Sometimes, however, both forms are necessary, in which case header contains the enum
                  form while specific attributes may request to convert the values into a bitfield.
                type: boolean
              checks:
                description: Kernel input validation.
                type: object
                additionalProperties: False
                properties:
                  flags-mask:
                    description: Name of the flags constant on which to base mask (unsigned scalar types only).
                    type: string
                  min:
                    description: Min value for an integer attribute.
                    type: integer
                  min-len:
                    description: Min length for a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  max-len:
                    description: Max length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  exact-len:
                    description: Exact length for a string or a binary attribute.
                    $ref: '#/$defs/len-or-define'
                  unterminated-ok:
                    description: |
                      For string attributes, do not check whether attribute
                      contains the terminating null character.
                    type: boolean
              sub-type: *attr-type
              display-hint: *display-hint
              # Start genetlink-c
              name-prefix:
                type: string
              # End genetlink-c
              # Start genetlink-legacy
              struct:
                description: Name of the struct type used for the attribute.
                type: string
              # End genetlink-legacy
              # Start netlink-raw
              sub-message:
                description: |
                  Name of the sub-message definition to use for the attribute.
                type: string
              selector:
                description: |
                  Name of the attribute to use for dynamic selection of sub-message
                  format specifier.
                type: string
              # End netlink-raw

      # Make sure name-prefix does not appear in subsets (subsets inherit naming)
      dependencies:
        name-prefix:
          not:
            required: [ subset-of ]
        subset-of:
          not:
            required: [ name-prefix ]

      # type property is only required if not in subset definition
      if:
        properties:
          subset-of:
            not:
              type: string
      then:
        properties:
          attributes:
            items:
              required: [ type ]

  # Start netlink-raw
  sub-messages:
    description: Definition of sub message attributes
    type: array
    items:
      type: object
      additionalProperties: False
      required: [ name, formats ]
      properties:
        name:
          description: Name of the sub-message definition
          type: string
        formats:
          description: Dynamically selected format specifiers
          type: array
          items:
            type: object
            additionalProperties: False
            required: [ value ]
            properties:
              value:
                description: |
                  Value to match for dynamic selection of sub-message format
                  specifier.
                type: string
              fixed-header:
                description: |
                  Name of the struct definition to use as the fixed header
                  for the sub message.
                type: string
              attribute-set:
                description: |
                  Name of the attribute space from which to resolve attributes
                  in the sub message.
                type: string
  # End netlink-raw

  operations:
    description: Operations supported by the protocol.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      enum-model:
        description: |
          The model of assigning values to the operations.
          "unified" is the recommended model where all message types belong
          to a single enum.
          "directional" has the messages sent to the kernel and from the kernel
          enumerated separately.
        enum: [ unified, directional ] # Trim
      name-prefix:
        description: |
          Prefix for the C enum name of the command. The name is formed by concatenating
          the prefix with the upper case name of the command, with dashes replaced by underscores.
        type: string
      enum-name:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      async-prefix:
        description: Same as name-prefix but used to render notifications and events to separate enum.
        type: string
      async-enum:
        description: |
          Name for the enum type with commands, if empty no name will be used.
        type: [ string, "null" ]
      # Start genetlink-legacy
      fixed-header: &fixed-header
        description: |
          Name of the structure defining the optional fixed-length protocol
          header. This header is placed in a message after the netlink and
          genetlink headers and before any attributes.
        type: string
      # End genetlink-legacy
      list:
        description: List of commands
        type: array
        items:
          type: object
          additionalProperties: False
          required: [ name, doc ]
          properties:
            name:
              description: Name of the operation, also defining its C enum value in uAPI.
              $ref: '#/$defs/name'
            doc:
              description: Documentation for the command.
              type: string
            value:
              description: Value for the enum in the uAPI.
              $ref: '#/$defs/uint'
            attribute-set:
              description: |
                Attribute space from which attributes directly in the requests and replies
                to this command are defined.
              type: string
            flags: &cmd_flags
              description: Command flags.
              type: array
              items:
                enum: [ admin-perm ]
            dont-validate:
              description: Kernel attribute validation flags.
              type: array
              items:
                enum: [ strict, dump ]
            # Start genetlink-legacy
            fixed-header: *fixed-header
            # End genetlink-legacy
            do: &subop-type
              description: Main command handler.
              type: object
              additionalProperties: False
              properties:
                request: &subop-attr-list
                  description: Definition of the request message for a given command.
                  type: object
                  additionalProperties: False
                  properties:
                    attributes:
                      description: |
                        Names of attributes from the attribute-set (not full attribute
                        definitions, just names).
                      type: array
                      items:
                        type: string
                    # Start genetlink-legacy
                    value:
                      description: |
                        ID of this message if value for request and response differ,
                        i.e. requests and responses have different message enums.
                      $ref: '#/$defs/uint'
                    # End genetlink-legacy
                reply: *subop-attr-list
                pre:
                  description: Hook for a function to run before the main callback (pre_doit or start).
                  type: string
                post:
                  description: Hook for a function to run after the main callback (post_doit or done).
                  type: string
            dump: *subop-type
            notify:
              description: Name of the command sharing the reply type with this notification.
              type: string
            event:
              type: object
              additionalProperties: False
              properties:
                attributes:
                  description: Explicit list of the attributes for the notification.
                  type: array
                  items:
                    type: string
            mcgrp:
              description: Name of the multicast group generating given notification.
              type: string
  mcast-groups:
    description: List of multicast groups.
    type: object
    required: [ list ]
    additionalProperties: False
    properties:
      list:
        description: List of groups.
        type: array
        items:
          type: object
          required: [ name ]
          additionalProperties: False
          properties:
            name:
              description: |
                The name for the group, used to form the define and the value of the define.
              type: string
            # Start genetlink-c
            c-define-name:
              description: Override for the name of the define in C uAPI.
              type: string
            # End genetlink-c
            flags: *cmd_flags
            # Start netlink-raw
            value:
              description: Value of the netlink multicast group in the uAPI.
              type: integer
            # End netlink-raw

```

---

# Networking

_Peios Kernel / Internals / Networking_

> Refer to netdev-FAQ for a guide on netdev development process specifics.

<a id="rst-networking"></a>

Refer to [Networking subsystem (netdev)](</kernel/development/process/maintainer-netdev.md#rst-netdev-faq>) for a guide on netdev development process specifics.

Contents:

- [AF_XDP](</kernel/internals/networking/af-xdp.md>)
- [Bare UDP Tunnelling Module Documentation](</kernel/internals/networking/bareudp.md>)
- [batman-adv](</kernel/internals/networking/batman-adv.md>)
- [SocketCAN - Controller Area Network](</kernel/internals/networking/can.md>)
- [The UCAN Protocol](</kernel/internals/networking/can-ucan-protocol.md>)
- [Hardware Device Drivers](</kernel/internals/networking/device-drivers/index.md>)
- [Networking Diagnostics](</kernel/internals/networking/diagnostic/index.md>)
- [Distributed Switch Architecture](</kernel/internals/networking/dsa/index.md>)
- [Linux Devlink Documentation](</kernel/internals/networking/devlink/index.md>)
- [CAIF](</kernel/internals/networking/caif/index.md>)
- [Netlink interface for ethtool](</kernel/internals/networking/ethtool-netlink.md>)
- [IEEE 802.15.4 Developer's Guide](</kernel/internals/networking/ieee802154.md>)
- [ISO 15765-2 (ISO-TP)](</kernel/internals/networking/iso15765-2.md>)
- [J1939 Documentation](</kernel/internals/networking/j1939.md>)
- [Linux Networking and Network Devices APIs](</kernel/internals/networking/kapi.md>)
- [MSG_ZEROCOPY](</kernel/internals/networking/msg-zerocopy.md>)
- [FAILOVER](</kernel/internals/networking/failover.md>)
- [Net DIM - Generic Network Dynamic Interrupt Moderation](</kernel/internals/networking/net-dim.md>)
- [NET_FAILOVER](</kernel/internals/networking/net-failover.md>)
- [Page Pool API](</kernel/internals/networking/page-pool.md>)
- [PHY Abstraction Layer](</kernel/internals/networking/phy.md>)
- [phylink](</kernel/internals/networking/sfp-phylink.md>)
- [IP-Aliasing](</kernel/internals/networking/alias.md>)
- [Ethernet Bridging](</kernel/internals/networking/bridge.md>)
- [SNMP counter](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/snmp_counter.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Checksum Offloads](</kernel/internals/networking/checksum-offloads.md>)
- [Segmentation Offloads](</kernel/internals/networking/segmentation-offloads.md>)
- [Scaling in the Linux Networking Stack](</kernel/internals/networking/scaling.md>)
- [Kernel TLS](</kernel/internals/networking/tls.md>)
- [Kernel TLS offload](</kernel/internals/networking/tls-offload.md>)
- [In-Kernel TLS Handshake](</kernel/internals/networking/tls-handshake.md>)
- [Linux NFC subsystem](</kernel/internals/networking/nfc.md>)
- [Netdev private dataroom for 6lowpan interfaces](</kernel/internals/networking/6lowpan.md>)
- [6pack Protocol](</kernel/internals/networking/6pack.md>)
- [ARCnet Hardware](</kernel/internals/networking/arcnet-hardware.md>)
- [ARCnet](</kernel/internals/networking/arcnet.md>)
- [ATM](</kernel/internals/networking/atm.md>)
- [AX.25](</kernel/internals/networking/ax25.md>)
- [Linux Ethernet Bonding Driver HOWTO](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/bonding.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [cdc_mbim - Driver for CDC MBIM Mobile Broadband modems](</kernel/internals/networking/cdc-mbim.md>)
- [DCTCP (DataCenter TCP)](</kernel/internals/networking/dctcp.md>)
- [Device Memory TCP](</kernel/internals/networking/devmem.md>)
- [DNS Resolver Module](</kernel/internals/networking/dns-resolver.md>)
- [Softnet Driver Issues](</kernel/internals/networking/driver.md>)
- [EQL Driver: Serial IP Load Balancing HOWTO](</kernel/internals/networking/eql.md>)
- [LC-trie implementation notes](</kernel/internals/networking/fib-trie.md>)
- [Linux Socket Filtering aka Berkeley Packet Filter (BPF)](</kernel/internals/networking/filter.md>)
- [Generic HDLC layer](</kernel/internals/networking/generic-hdlc.md>)
- [Generic Netlink](</kernel/internals/networking/generic-netlink.md>)
- [Netlink Family Specifications](</kernel/internals/netlink/specs/index.md>)
- [Generic networking statistics for netlink users](</kernel/internals/networking/gen-stats.md>)
- [The Linux kernel GTP tunneling module](</kernel/internals/networking/gtp.md>)
- [Identifier Locator Addressing (ILA)](</kernel/internals/networking/ila.md>)
- [IOAM6 Sysfs variables](</kernel/internals/networking/ioam6-sysctl.md>)
- [io_uring zero copy Rx](</kernel/internals/networking/iou-zcrx.md>)
- [IP dynamic address hack-port v0.03](</kernel/internals/networking/ip-dynaddr.md>)
- [IPsec](</kernel/internals/networking/ipsec.md>)
- [IP Sysctl](</kernel/internals/networking/ip-sysctl.md>)
- [IPv6](</kernel/internals/networking/ipv6.md>)
- [IPVLAN Driver HOWTO](</kernel/internals/networking/ipvlan.md>)
- [IPvs-sysctl](</kernel/internals/networking/ipvs-sysctl.md>)
- [Kernel Connection Multiplexor](</kernel/internals/networking/kcm.md>)
- [L2TP](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/l2tp.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [The Linux LAPB Module Interface](</kernel/internals/networking/lapb-module.md>)
- [How to use packet injection with mac80211](</kernel/internals/networking/mac80211-injection.md>)
- [Management Component Transport Protocol (MCTP)](</kernel/internals/networking/mctp.md>)
- [MPLS Sysfs variables](</kernel/internals/networking/mpls-sysctl.md>)
- [Multipath TCP (MPTCP)](</kernel/internals/networking/mptcp.md>)
- [MPTCP Sysfs variables](</kernel/internals/networking/mptcp-sysctl.md>)
- [HOWTO for multiqueue network device support](</kernel/internals/networking/multiqueue.md>)
- [Multi-PF Netdev](</kernel/internals/networking/multi-pf-netdev.md>)
- [NAPI](</kernel/internals/networking/napi.md>)
- [Common Networking Struct Cachelines](</kernel/internals/networking/net-cachelines/index.md>)
- [Netconsole](</kernel/internals/networking/netconsole.md>)
- [Netdev features mess and how to get out from it alive](</kernel/internals/networking/netdev-features.md>)
- [Network Devices, the Kernel, and You\!](</kernel/internals/networking/netdevices.md>)
- [Netfilter Sysfs variables](</kernel/internals/networking/netfilter-sysctl.md>)
- [NETIF Msg Level](</kernel/internals/networking/netif-msg.md>)
- [Netmem Support for Network Drivers](</kernel/internals/networking/netmem.md>)
- [Resilient Next-hop Groups](</kernel/internals/networking/nexthop-group-resilient.md>)
- [Netfilter Conntrack Sysfs variables](</kernel/internals/networking/nf-conntrack-sysctl.md>)
- [Netfilter's flowtable infrastructure](</kernel/internals/networking/nf-flowtable.md>)
- [OPEN Alliance 10BASE-T1x MAC-PHY Serial Interface (TC6) Framework Support](</kernel/internals/networking/oa-tc6-framework.md>)
- [Open vSwitch datapath developer documentation](</kernel/internals/networking/openvswitch.md>)
- [Operational States](</kernel/internals/networking/operstates.md>)
- [Packet MMAP](</kernel/internals/networking/packet-mmap.md>)
- [Linux Phonet protocol family](</kernel/internals/networking/phonet.md>)
- [PHY link topology](</kernel/internals/networking/phy-link-topology.md>)
- [Ethernet ports](</kernel/internals/networking/phy-port.md>)
- [HOWTO for the linux packet generator](</kernel/internals/networking/pktgen.md>)
- [PLIP: The Parallel Line Internet Protocol Device](</kernel/internals/networking/plip.md>)
- [PPP Generic Driver and Channel Interface](</kernel/internals/networking/ppp-generic.md>)
- [The proc/net/tcp and proc/net/tcp6 variables](</kernel/internals/networking/proc-net-tcp.md>)
- [Power Sourcing Equipment (PSE) Documentation](</kernel/internals/networking/pse-pd/index.md>)
- [PSP Security Protocol](</kernel/internals/networking/psp.md>)
- [How to use radiotap headers](</kernel/internals/networking/radiotap-headers.md>)
- [RDS](</kernel/internals/networking/rds.md>)
- [Linux wireless regulatory documentation](</kernel/internals/networking/regulatory.md>)
- [Network Function Representors](</kernel/internals/networking/representors.md>)
- [RxRPC Network Protocol](</kernel/internals/networking/rxrpc.md>)
- [Linux Kernel SCTP](</kernel/internals/networking/sctp.md>)
- [LSM/SeLinux secid](</kernel/internals/networking/secid.md>)
- [Seg6 Sysfs variables](</kernel/internals/networking/seg6-sysctl.md>)
- [struct sk_buff](</kernel/internals/networking/skbuff.md>)
- [SMC Sysctl](</kernel/internals/networking/smc-sysctl.md>)
- [NIC SR-IOV APIs](</kernel/internals/networking/sriov.md>)
- [Interface statistics](</kernel/internals/networking/statistics.md>)
- [Stream Parser (strparser)](</kernel/internals/networking/strparser.md>)
- [Ethernet switch device driver model (switchdev)](</kernel/internals/networking/switchdev.md>)
- [Sysfs tagging](</kernel/internals/networking/sysfs-tagging.md>)
- [TC Actions - Environmental Rules](</kernel/internals/networking/tc-actions-env-rules.md>)
- [TC queue based filtering](</kernel/internals/networking/tc-queue-filters.md>)
- [TCP Authentication Option Linux implementation (RFC5925)](</kernel/internals/networking/tcp-ao.md>)
- [Thin-streams and TCP](</kernel/internals/networking/tcp-thin.md>)
- [Team](</kernel/internals/networking/team.md>)
- [Timestamping](</kernel/internals/networking/timestamping.md>)
- [Linux Kernel TIPC](</kernel/internals/networking/tipc.md>)
- [Transparent proxy support](</kernel/internals/networking/tproxy.md>)
- [Universal TUN/TAP device driver](</kernel/internals/networking/tuntap.md>)
- [The UDP-Lite protocol (RFC 3828)](</kernel/internals/networking/udplite.md>)
- [Virtual Routing and Forwarding (VRF)](</kernel/internals/networking/vrf.md>)
- [Virtual eXtensible Local Area Networking documentation](</kernel/internals/networking/vxlan.md>)
- [Linux X.25 Project](</kernel/internals/networking/x25.md>)
- [X.25 Device Driver Interface](</kernel/internals/networking/x25-iface.md>)
- [XFRM Framework](</kernel/internals/networking/xfrm/index.md>)
- [XDP RX Metadata](</kernel/internals/networking/xdp-rx-metadata.md>)
- [AF_XDP TX Metadata](</kernel/internals/networking/xsk-tx-metadata.md>)

---

# Netdev private dataroom for 6lowpan interfaces

_Peios Kernel / Internals / Networking_

> All 6lowpan able net devices, means all interfaces with ARPHRD_6LOWPAN, must have "struct lowpan_priv" placed at beginning of netdev_priv.

<a id="rst-netdev-private-dataroom-for-6lowpan-interfaces"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

All 6lowpan able net devices, means all interfaces with ARPHRD_6LOWPAN, must have "struct lowpan_priv" placed at beginning of netdev_priv.

The priv_size of each interface should be calculate by:



```text
dev->priv_size = LOWPAN_PRIV_SIZE(LL_6LOWPAN_PRIV_DATA);
```

Where LL_PRIV_6LOWPAN_DATA is sizeof linklayer 6lowpan private data struct. To access the LL_PRIV_6LOWPAN_DATA structure you can cast:



```text
lowpan_priv(dev)-priv;
```

to your LL_6LOWPAN_PRIV_DATA structure.

Before registering the lowpan netdev interface you must run:



```text
lowpan_netdev_setup(dev, LOWPAN_LLTYPE_FOOBAR);
```

wheres LOWPAN_LLTYPE_FOOBAR is a define for your 6LoWPAN linklayer type of enum lowpan_lltypes.

Example to evaluate the private usually you can do:



```text
static inline struct lowpan_priv_foobar *
lowpan_foobar_priv(struct net_device *dev)
{
       return (struct lowpan_priv_foobar *)lowpan_priv(dev)->priv;
}

switch (dev->type) {
case ARPHRD_6LOWPAN:
       lowpan_priv = lowpan_priv(dev);
       /* do great stuff which is ARPHRD_6LOWPAN related */
       switch (lowpan_priv->lltype) {
       case LOWPAN_LLTYPE_FOOBAR:
               /* do 802.15.4 6LoWPAN handling here */
               lowpan_foobar_priv(dev)->bar = foo;
               break;
       ...
       }
       break;
...
}
```

In case of generic 6lowpan branch ("net/6lowpan") you can remove the check on ARPHRD_6LOWPAN, because you can be sure that these function are called by ARPHRD_6LOWPAN interfaces.

---

# 6pack Protocol

_Peios Kernel / Internals / Networking_

> This is the 6pack-mini-HOWTO, written by

<a id="rst-pack-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This is the 6pack-mini-HOWTO, written by

Andreas Könsgen DG3KQ

**Internet:** [ajk@comnets.uni-bremen.de](<mailto:ajk@comnets.uni-bremen.de>)

**AMPR-net:** [dg3kq@db0pra.ampr.org](<mailto:dg3kq@db0pra.ampr.org>)

**AX.25:** [dg3kq@db0ach.\#nrw.deu.eu](<mailto:dg3kq@db0ach.#nrw.deu.eu>)

Last update: April 7, 1998

<a id="rst-what-is-6pack-and-what-are-the-advantages-to-kiss"></a>

## 1. What is 6pack, and what are the advantages to KISS?

6pack is a transmission protocol for data exchange between the PC and the TNC over a serial line. It can be used as an alternative to KISS.

6pack has two major advantages:

- The PC is given full control over the radio channel. Special control data is exchanged between the PC and the TNC so that the PC knows at any time if the TNC is receiving data, if a TNC buffer underrun or overrun has occurred, if the PTT is set and so on. This control data is processed at a higher priority than normal data, so a data stream can be interrupted at any time to issue an important event. This helps to improve the channel access and timing algorithms as everything is computed in the PC. It would even be possible to experiment with something completely different from the known CSMA and DAMA channel access methods. This kind of real-time control is especially important to supply several TNCs that are connected between each other and the PC by a daisy chain (however, this feature is not supported yet by the Linux 6pack driver).

- Each packet transferred over the serial line is supplied with a checksum, so it is easy to detect errors due to problems on the serial line. Received packets that are corrupt are not passed on to the AX.25 layer. Damaged packets that the TNC has received from the PC are not transmitted.

More details about 6pack are described in the file 6pack.ps that is located in the doc directory of the AX.25 utilities package.

<a id="rst-who-has-developed-the-6pack-protocol"></a>

## 2. Who has developed the 6pack protocol?

The 6pack protocol has been developed by Ekki Plicht DF4OR, Henning Rech DF9IC and Gunter Jost DK7WJ. A driver for 6pack, written by Gunter Jost and Matthias Welwarsky DG2FEF, comes along with the PC version of FlexNet. They have also written a firmware for TNCs to perform the 6pack protocol (see section 4 below).

<a id="rst-where-can-i-get-the-latest-version-of-6pack-for-linux"></a>

## 3. Where can I get the latest version of 6pack for LinuX?

At the moment, the 6pack stuff can obtained via anonymous ftp from db0bm.automation.fh-aachen.de. In the directory /incoming/dg3kq, there is a file named 6pack.tgz.

<a id="rst-preparing-the-tnc-for-6pack-operation"></a>

## 4. Preparing the TNC for 6pack operation

To be able to use 6pack, a special firmware for the TNC is needed. The EPROM of a newly bought TNC does not contain 6pack, so you will have to program an EPROM yourself. The image file for 6pack EPROMs should be available on any packet radio box where PC/FlexNet can be found. The name of the file is 6pack.bin. This file is copyrighted and maintained by the FlexNet team. It can be used under the terms of the license that comes along with PC/FlexNet. Please do not ask me about the internals of this file as I don't know anything about it. I used a textual description of the 6pack protocol to program the Linux driver.

TNCs contain a 64kByte EPROM, the lower half of which is used for the firmware/KISS. The upper half is either empty or is sometimes programmed with software called TAPR. In the latter case, the TNC is supplied with a DIP switch so you can easily change between the two systems. When programming a new EPROM, one of the systems is replaced by 6pack. It is useful to replace TAPR, as this software is rarely used nowadays. If your TNC is not equipped with the switch mentioned above, you can build in one yourself that switches over the highest address pin of the EPROM between HIGH and LOW level. After having inserted the new EPROM and switched to 6pack, apply power to the TNC for a first test. The connect and the status LED are lit for about a second if the firmware initialises the TNC correctly.

<a id="rst-building-and-installing-the-6pack-driver"></a>

## 5. Building and installing the 6pack driver

The driver has been tested with kernel version 2.1.90. Use with older kernels may lead to a compilation error because the interface to a kernel function has been changed in the 2.1.8x kernels.

<a id="rst-how-to-turn-on-6pack-support"></a>

### How to turn on 6pack support:

- In the linux kernel configuration program, select the code maturity level options menu and turn on the prompting for development drivers.

- Select the amateur radio support menu and turn on the serial port 6pack driver.

- Compile and install the kernel and the modules.

To use the driver, the kissattach program delivered with the AX.25 utilities has to be modified.

- Do a cd to the directory that holds the kissattach sources. Edit the kissattach.c file. At the top, insert the following lines:



  ```text
  #ifndef N_6PACK
  #define N_6PACK (N_AX25+1)
  #endif
  ```

  Then find the line:

  > int disc = N_AX25;

  and replace N_AX25 by N_6PACK.

- Recompile kissattach. Rename it to spattach to avoid confusions.

<a id="rst-installing-the-driver"></a>

### Installing the driver:

- Do an insmod 6pack. Look at your /var/log/messages file to check if the module has printed its initialization message.

- Do a spattach as you would launch kissattach when starting a KISS port. Check if the kernel prints the message '6pack: TNC found'.

- From here, everything should work as if you were setting up a KISS port. The only difference is that the network device that represents the 6pack port is called sp instead of sl or ax. So, sp0 would be the first 6pack port.

Although the driver has been tested on various platforms, I still declare it ALPHA. BE CAREFUL\! Sync your disks before insmoding the 6pack module and spattaching. Watch out if your computer behaves strangely. Read section 6 of this file about known problems.

Note that the connect and status LEDs of the TNC are controlled in a different way than they are when the TNC is used with PC/FlexNet. When using FlexNet, the connect LED is on if there is a connection; the status LED is on if there is data in the buffer of the PC's AX.25 engine that has to be transmitted. Under Linux, the 6pack layer is beyond the AX.25 layer, so the 6pack driver doesn't know anything about connects or data that has not yet been transmitted. Therefore the LEDs are controlled as they are in KISS mode: The connect LED is turned on if data is transferred from the PC to the TNC over the serial line, the status LED if data is sent to the PC.

<a id="rst-known-problems"></a>

## 6. Known problems

When testing the driver with 2.0.3x kernels and operating with data rates on the radio channel of 9600 Baud or higher, the driver may, on certain systems, sometimes print the message '6pack: bad checksum', which is due to data loss if the other station sends two or more subsequent packets. I have been told that this is due to a problem with the serial driver of 2.0.3x kernels. I don't know yet if the problem still exists with 2.1.x kernels, as I have heard that the serial driver code has been changed with 2.1.x.

When shutting down the sp interface with ifconfig, the kernel crashes if there is still an AX.25 connection left over which an IP connection was running, even if that IP connection is already closed. The problem does not occur when there is a bare AX.25 connection still running. I don't know if this is a problem of the 6pack driver or something else in the kernel.

The driver has been tested as a module, not yet as a kernel-builtin driver.

The 6pack protocol supports daisy-chaining of TNCs in a token ring, which is connected to one serial port of the PC. This feature is not implemented and at least at the moment I won't be able to do it because I do not have the opportunity to build a TNC daisy-chain and test it.

Some of the comments in the source code are inaccurate. They are left from the SLIP/KISS driver, from which the 6pack driver has been derived. I haven't modified or removed them yet -- sorry\! The code itself needs some cleaning and optimizing. This will be done in a later release.

If you encounter a bug or if you have a question or suggestion concerning the driver, feel free to mail me, using the addresses given at the beginning of this file.

Have fun\!

Andreas

---

# AF_XDP

_Peios Kernel / Internals / Networking_

> AF_XDP is an address family that is optimized for high performance packet processing.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-af-xdp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

AF_XDP is an address family that is optimized for high performance packet processing.

This document assumes that the reader is familiar with BPF and XDP. If not, the Cilium project has an excellent reference guide at [http://cilium.readthedocs.io/en/latest/bpf/](<http://cilium.readthedocs.io/en/latest/bpf/>).

Using the XDP_REDIRECT action from an XDP program, the program can redirect ingress frames to other XDP enabled netdevs, using the bpf_redirect_map() function. AF_XDP sockets enable the possibility for XDP programs to redirect frames to a memory buffer in a user-space application.

An AF_XDP socket (XSK) is created with the normal socket() syscall. Associated with each XSK are two rings: the RX ring and the TX ring. A socket can receive packets on the RX ring and it can send packets on the TX ring. These rings are registered and sized with the setsockopts XDP_RX_RING and XDP_TX_RING, respectively. It is mandatory to have at least one of these rings for each socket. An RX or TX descriptor ring points to a data buffer in a memory area called a UMEM. RX and TX can share the same UMEM so that a packet does not have to be copied between RX and TX. Moreover, if a packet needs to be kept for a while due to a possible retransmit, the descriptor that points to that packet can be changed to point to another and reused right away. This again avoids copying data.

The UMEM consists of a number of equally sized chunks. A descriptor in one of the rings references a frame by referencing its addr. The addr is simply an offset within the entire UMEM region. The user space allocates memory for this UMEM using whatever means it feels is most appropriate (malloc, mmap, huge pages, etc). This memory area is then registered with the kernel using the new setsockopt XDP_UMEM_REG. The UMEM also has two rings: the FILL ring and the COMPLETION ring. The FILL ring is used by the application to send down addr for the kernel to fill in with RX packet data. References to these frames will then appear in the RX ring once each packet has been received. The COMPLETION ring, on the other hand, contains frame addr that the kernel has transmitted completely and can now be used again by user space, for either TX or RX. Thus, the frame addrs appearing in the COMPLETION ring are addrs that were previously transmitted using the TX ring. In summary, the RX and FILL rings are used for the RX path and the TX and COMPLETION rings are used for the TX path.

The socket is then finally bound with a bind() call to a device and a specific queue id on that device, and it is not until bind is completed that traffic starts to flow.

The UMEM can be shared between processes, if desired. If a process wants to do this, it simply skips the registration of the UMEM and its corresponding two rings, sets the XDP_SHARED_UMEM flag in the bind call and submits the XSK of the process it would like to share UMEM with as well as its own newly created XSK socket. The new process will then receive frame addr references in its own RX ring that point to this shared UMEM. Note that since the ring structures are single-consumer / single-producer (for performance reasons), the new process has to create its own socket with associated RX and TX rings, since it cannot share this with the other process. This is also the reason that there is only one set of FILL and COMPLETION rings per UMEM. It is the responsibility of a single process to handle the UMEM.

How is then packets distributed from an XDP program to the XSKs? There is a BPF map called XSKMAP (or BPF_MAP_TYPE_XSKMAP in full). The user-space application can place an XSK at an arbitrary place in this map. The XDP program can then redirect a packet to a specific index in this map and at this point XDP validates that the XSK in that map was indeed bound to that device and ring number. If not, the packet is dropped. If the map is empty at that index, the packet is also dropped. This also means that it is currently mandatory to have an XDP program loaded (and one XSK in the XSKMAP) to be able to get any traffic to user space through the XSK.

AF_XDP can operate in two different modes: XDP_SKB and XDP_DRV. If the driver does not have support for XDP, or XDP_SKB is explicitly chosen when loading the XDP program, XDP_SKB mode is employed that uses SKBs together with the generic XDP support and copies out the data to user space. A fallback mode that works for any network device. On the other hand, if the driver has support for XDP, it will be used by the AF_XDP code to provide better performance, but there is still a copy of the data into user space.

<a id="rst-concepts"></a>

## Concepts

In order to use an AF_XDP socket, a number of associated objects need to be setup. These objects and their options are explained in the following sections.

For an overview on how AF_XDP works, you can also take a look at the Linux Plumbers paper from 2018 on the subject: [http://vger.kernel.org/lpc_net2018_talks/lpc18_paper_af_xdp_perf-v2.pdf](<http://vger.kernel.org/lpc_net2018_talks/lpc18_paper_af_xdp_perf-v2.pdf>). Do NOT consult the paper from 2017 on "AF_PACKET v4", the first attempt at AF_XDP. Nearly everything changed since then. Jonathan Corbet has also written an excellent article on LWN, "Accelerating networking with AF_XDP". It can be found at [https://lwn.net/Articles/750845/](<https://lwn.net/Articles/750845/>).

<a id="rst-umem"></a>

### UMEM

UMEM is a region of virtual contiguous memory, divided into equal-sized frames. An UMEM is associated to a netdev and a specific queue id of that netdev. It is created and configured (chunk size, headroom, start address and size) by using the XDP_UMEM_REG setsockopt system call. A UMEM is bound to a netdev and queue id, via the bind() system call.

An AF_XDP is socket linked to a single UMEM, but one UMEM can have multiple AF_XDP sockets. To share an UMEM created via one socket A, the next socket B can do this by setting the XDP_SHARED_UMEM flag in struct sockaddr_xdp member sxdp_flags, and passing the file descriptor of A to struct sockaddr_xdp member sxdp_shared_umem_fd.

The UMEM has two single-producer/single-consumer rings that are used to transfer ownership of UMEM frames between the kernel and the user-space application.

<a id="rst-rings"></a>

### Rings

There are a four different kind of rings: FILL, COMPLETION, RX and TX. All rings are single-producer/single-consumer, so the user-space application need explicit synchronization of multiple processes/threads are reading/writing to them.

The UMEM uses two rings: FILL and COMPLETION. Each socket associated with the UMEM must have an RX queue, TX queue or both. Say, that there is a setup with four sockets (all doing TX and RX). Then there will be one FILL ring, one COMPLETION ring, four TX rings and four RX rings.

The rings are head(producer)/tail(consumer) based rings. A producer writes the data ring at the index pointed out by struct xdp_ring producer member, and increasing the producer index. A consumer reads the data ring at the index pointed out by struct xdp_ring consumer member, and increasing the consumer index.

The rings are configured and created via the \_RING setsockopt system calls and mmapped to user-space using the appropriate offset to mmap() (XDP_PGOFF_RX_RING, XDP_PGOFF_TX_RING, XDP_UMEM_PGOFF_FILL_RING and XDP_UMEM_PGOFF_COMPLETION_RING).

The size of the rings need to be of size power of two.

<a id="rst-umem-fill-ring"></a>

#### UMEM Fill Ring

The FILL ring is used to transfer ownership of UMEM frames from user-space to kernel-space. The UMEM addrs are passed in the ring. As an example, if the UMEM is 64k and each chunk is 4k, then the UMEM has 16 chunks and can pass addrs between 0 and 64k.

Frames passed to the kernel are used for the ingress path (RX rings).

The user application produces UMEM addrs to this ring. Note that, if running the application with aligned chunk mode, the kernel will mask the incoming addr.  E.g. for a chunk size of 2k, the log2(2048) LSB of the addr will be masked off, meaning that 2048, 2050 and 3000 refers to the same chunk. If the user application is run in the unaligned chunks mode, then the incoming addr will be left untouched.

<a id="rst-umem-completion-ring"></a>

#### UMEM Completion Ring

The COMPLETION Ring is used transfer ownership of UMEM frames from kernel-space to user-space. Just like the FILL ring, UMEM indices are used.

Frames passed from the kernel to user-space are frames that has been sent (TX ring) and can be used by user-space again.

The user application consumes UMEM addrs from this ring.

<a id="rst-rx-ring"></a>

#### RX Ring

The RX ring is the receiving side of a socket. Each entry in the ring is a struct xdp_desc descriptor. The descriptor contains UMEM offset (addr) and the length of the data (len).

If no frames have been passed to kernel via the FILL ring, no descriptors will (or can) appear on the RX ring.

The user application consumes struct xdp_desc descriptors from this ring.

<a id="rst-tx-ring"></a>

#### TX Ring

The TX ring is used to send frames. The struct xdp_desc descriptor is filled (index, length and offset) and passed into the ring.

To start the transfer a sendmsg() system call is required. This might be relaxed in the future.

The user application produces struct xdp_desc descriptors to this ring.

<a id="rst-libbpf"></a>

## Libbpf

Libbpf is a helper library for eBPF and XDP that makes using these technologies a lot simpler. It also contains specific helper functions in tools/testing/selftests/bpf/xsk.h for facilitating the use of AF_XDP. It contains two types of functions: those that can be used to make the setup of AF_XDP socket easier and ones that can be used in the data plane to access the rings safely and quickly.

We recommend that you use this library unless you have become a power user. It will make your program a lot simpler.

<a id="rst-xskmap-bpf-map-type-xskmap"></a>

## XSKMAP / BPF_MAP_TYPE_XSKMAP

On XDP side there is a BPF map type BPF_MAP_TYPE_XSKMAP (XSKMAP) that is used in conjunction with bpf_redirect_map() to pass the ingress frame to a socket.

The user application inserts the socket into the map, via the bpf() system call.

Note that if an XDP program tries to redirect to a socket that does not match the queue configuration and netdev, the frame will be dropped. E.g. an AF_XDP socket is bound to netdev eth0 and queue 17. Only the XDP program executing for eth0 and queue 17 will successfully pass data to the socket. Please refer to the sample application (samples/bpf/) in for an example.

<a id="rst-configuration-flags-and-socket-options"></a>

## Configuration Flags and Socket Options

These are the various configuration flags that can be used to control and monitor the behavior of AF_XDP sockets.

<a id="rst-xdp-copy-and-xdp-zerocopy-bind-flags"></a>

### XDP_COPY and XDP_ZEROCOPY bind flags

When you bind to a socket, the kernel will first try to use zero-copy copy. If zero-copy is not supported, it will fall back on using copy mode, i.e. copying all packets out to user space. But if you would like to force a certain mode, you can use the following flags. If you pass the XDP_COPY flag to the bind call, the kernel will force the socket into copy mode. If it cannot use copy mode, the bind call will fail with an error. Conversely, the XDP_ZEROCOPY flag will force the socket into zero-copy mode or fail.

<a id="rst-xdp-shared-umem-bind-flag"></a>

### XDP_SHARED_UMEM bind flag

This flag enables you to bind multiple sockets to the same UMEM. It works on the same queue id, between queue ids and between netdevs/devices. In this mode, each socket has their own RX and TX rings as usual, but you are going to have one or more FILL and COMPLETION ring pairs. You have to create one of these pairs per unique netdev and queue id tuple that you bind to.

Starting with the case were we would like to share a UMEM between sockets bound to the same netdev and queue id. The UMEM (tied to the fist socket created) will only have a single FILL ring and a single COMPLETION ring as there is only on unique netdev,queue_id tuple that we have bound to. To use this mode, create the first socket and bind it in the normal way. Create a second socket and create an RX and a TX ring, or at least one of them, but no FILL or COMPLETION rings as the ones from the first socket will be used. In the bind call, set he XDP_SHARED_UMEM option and provide the initial socket's fd in the sxdp_shared_umem_fd field. You can attach an arbitrary number of extra sockets this way.

What socket will then a packet arrive on? This is decided by the XDP program. Put all the sockets in the XSK_MAP and just indicate which index in the array you would like to send each packet to. A simple round-robin example of distributing packets is shown below:



```c
#include <linux/bpf.h>
#include "bpf_helpers.h"

#define MAX_SOCKS 16

struct {
    __uint(type, BPF_MAP_TYPE_XSKMAP);
    __uint(max_entries, MAX_SOCKS);
    __uint(key_size, sizeof(int));
    __uint(value_size, sizeof(int));
} xsks_map SEC(".maps");

static unsigned int rr;

SEC("xdp_sock") int xdp_sock_prog(struct xdp_md *ctx)
{
    rr = (rr + 1) & (MAX_SOCKS - 1);

    return bpf_redirect_map(&xsks_map, rr, XDP_DROP);
}
```

Note, that since there is only a single set of FILL and COMPLETION rings, and they are single producer, single consumer rings, you need to make sure that multiple processes or threads do not use these rings concurrently. There are no synchronization primitives in the libbpf code that protects multiple users at this point in time.

Libbpf uses this mode if you create more than one socket tied to the same UMEM. However, note that you need to supply the XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD libbpf_flag with the xsk_socket__create calls and load your own XDP program as there is no built in one in libbpf that will route the traffic for you.

The second case is when you share a UMEM between sockets that are bound to different queue ids and/or netdevs. In this case you have to create one FILL ring and one COMPLETION ring for each unique netdev,queue_id pair. Let us say you want to create two sockets bound to two different queue ids on the same netdev. Create the first socket and bind it in the normal way. Create a second socket and create an RX and a TX ring, or at least one of them, and then one FILL and COMPLETION ring for this socket. Then in the bind call, set he XDP_SHARED_UMEM option and provide the initial socket's fd in the sxdp_shared_umem_fd field as you registered the UMEM on that socket. These two sockets will now share one and the same UMEM.

There is no need to supply an XDP program like the one in the previous case where sockets were bound to the same queue id and device. Instead, use the NIC's packet steering capabilities to steer the packets to the right queue. In the previous example, there is only one queue shared among sockets, so the NIC cannot do this steering. It can only steer between queues.

In libbpf, you need to use the xsk_socket__create_shared() API as it takes a reference to a FILL ring and a COMPLETION ring that will be created for you and bound to the shared UMEM. You can use this function for all the sockets you create, or you can use it for the second and following ones and use xsk_socket__create() for the first one. Both methods yield the same result.

Note that a UMEM can be shared between sockets on the same queue id and device, as well as between queues on the same device and between devices at the same time.

<a id="rst-xdp-use-need-wakeup-bind-flag"></a>

### XDP_USE_NEED_WAKEUP bind flag

This option adds support for a new flag called need_wakeup that is present in the FILL ring and the TX ring, the rings for which user space is a producer. When this option is set in the bind call, the need_wakeup flag will be set if the kernel needs to be explicitly woken up by a syscall to continue processing packets. If the flag is zero, no syscall is needed.

If the flag is set on the FILL ring, the application needs to call poll() to be able to continue to receive packets on the RX ring. This can happen, for example, when the kernel has detected that there are no more buffers on the FILL ring and no buffers left on the RX HW ring of the NIC. In this case, interrupts are turned off as the NIC cannot receive any packets (as there are no buffers to put them in), and the need_wakeup flag is set so that user space can put buffers on the FILL ring and then call poll() so that the kernel driver can put these buffers on the HW ring and start to receive packets.

If the flag is set for the TX ring, it means that the application needs to explicitly notify the kernel to send any packets put on the TX ring. This can be accomplished either by a poll() call, as in the RX path, or by calling sendto().

An example with the use of libbpf helpers would look like this for the TX path:



```c
if (xsk_ring_prod__needs_wakeup(&my_tx_ring))
    sendto(xsk_socket__fd(xsk_handle), NULL, 0, MSG_DONTWAIT, NULL, 0);
```

I.e., only use the syscall if the flag is set.

We recommend that you always enable this mode as it usually leads to better performance especially if you run the application and the driver on the same core, but also if you use different cores for the application and the kernel driver, as it reduces the number of syscalls needed for the TX path.

<a id="rst-xdp-rx-tx-umem-fill-umem-completion-ring-setsockopts"></a>

### XDP\_\{RX\|TX\|UMEM_FILL\|UMEM_COMPLETION\}\_RING setsockopts

These setsockopts sets the number of descriptors that the RX, TX, FILL, and COMPLETION rings respectively should have. It is mandatory to set the size of at least one of the RX and TX rings. If you set both, you will be able to both receive and send traffic from your application, but if you only want to do one of them, you can save resources by only setting up one of them. Both the FILL ring and the COMPLETION ring are mandatory as you need to have a UMEM tied to your socket. But if the XDP_SHARED_UMEM flag is used, any socket after the first one does not have a UMEM and should in that case not have any FILL or COMPLETION rings created as the ones from the shared UMEM will be used. Note, that the rings are single-producer single-consumer, so do not try to access them from multiple processes at the same time. See the XDP_SHARED_UMEM section.

In libbpf, you can create Rx-only and Tx-only sockets by supplying NULL to the rx and tx arguments, respectively, to the xsk_socket__create function.

If you create a Tx-only socket, we recommend that you do not put any packets on the fill ring. If you do this, drivers might think you are going to receive something when you in fact will not, and this can negatively impact performance.

<a id="rst-xdp-umem-reg-setsockopt"></a>

### XDP_UMEM_REG setsockopt

This setsockopt registers a UMEM to a socket. This is the area that contain all the buffers that packet can reside in. The call takes a pointer to the beginning of this area and the size of it. Moreover, it also has parameter called chunk_size that is the size that the UMEM is divided into. It can only be 2K or 4K at the moment. If you have an UMEM area that is 128K and a chunk size of 2K, this means that you will be able to hold a maximum of 128K / 2K = 64 packets in your UMEM area and that your largest packet size can be 2K.

There is also an option to set the headroom of each single buffer in the UMEM. If you set this to N bytes, it means that the packet will start N bytes into the buffer leaving the first N bytes for the application to use. The final option is the flags field, but it will be dealt with in separate sections for each UMEM flag.

<a id="rst-so-bindtodevice-setsockopt"></a>

### SO_BINDTODEVICE setsockopt

This is a generic SOL_SOCKET option that can be used to tie AF_XDP socket to a particular network interface.  It is useful when a socket is created by a privileged process and passed to a non-privileged one. Once the option is set, kernel will refuse attempts to bind that socket to a different interface.  Updating the value requires CAP_NET_RAW.

<a id="rst-xdp-max-tx-skb-budget-setsockopt"></a>

### XDP_MAX_TX_SKB_BUDGET setsockopt

This setsockopt sets the maximum number of descriptors that can be handled and passed to the driver at one send syscall. It is applied in the copy mode to allow application to tune the per-socket maximum iteration for better throughput and less frequency of send syscall. Allowed range is \[32, xs-&gt;tx-&gt;nentries\].

<a id="rst-xdp-statistics-getsockopt"></a>

### XDP_STATISTICS getsockopt

Gets drop statistics of a socket that can be useful for debug purposes. The supported statistics are shown below:



```c
struct xdp_statistics {
    __u64 rx_dropped; /* Dropped for reasons other than invalid desc */
    __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
    __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
};
```

<a id="rst-xdp-options-getsockopt"></a>

### XDP_OPTIONS getsockopt

Gets options from an XDP socket. The only one supported so far is XDP_OPTIONS_ZEROCOPY which tells you if zero-copy is on or not.

<a id="rst-multi-buffer-support"></a>

## Multi-Buffer Support

With multi-buffer support, programs using AF_XDP sockets can receive and transmit packets consisting of multiple buffers both in copy and zero-copy mode. For example, a packet can consist of two frames/buffers, one with the header and the other one with the data, or a 9K Ethernet jumbo frame can be constructed by chaining together three 4K frames.

Some definitions:

- A packet consists of one or more frames

- A descriptor in one of the AF_XDP rings always refers to a single frame. In the case the packet consists of a single frame, the descriptor refers to the whole packet.

To enable multi-buffer support for an AF_XDP socket, use the new bind flag XDP_USE_SG. If this is not provided, all multi-buffer packets will be dropped just as before. Note that the XDP program loaded also needs to be in multi-buffer mode. This can be accomplished by using "xdp.frags" as the section name of the XDP program used.

To represent a packet consisting of multiple frames, a new flag called XDP_PKT_CONTD is introduced in the options field of the Rx and Tx descriptors. If it is true (1) the packet continues with the next descriptor and if it is false (0) it means this is the last descriptor of the packet. Why the reverse logic of end-of-packet (eop) flag found in many NICs? Just to preserve compatibility with non-multi-buffer applications that have this bit set to false for all packets on Rx, and the apps set the options field to zero for Tx, as anything else will be treated as an invalid descriptor.

These are the semantics for producing packets onto AF_XDP Tx ring consisting of multiple frames:

- When an invalid descriptor is found, all the other descriptors/frames of this packet are marked as invalid and not completed. The next descriptor is treated as the start of a new packet, even if this was not the intent (because we cannot guess the intent). As before, if your program is producing invalid descriptors you have a bug that must be fixed.

- Zero length descriptors are treated as invalid descriptors.

- For copy mode, the maximum supported number of frames in a packet is equal to CONFIG_MAX_SKB_FRAGS + 1. If it is exceeded, all descriptors accumulated so far are dropped and treated as invalid. To produce an application that will work on any system regardless of this config setting, limit the number of frags to 18, as the minimum value of the config is 17.

- For zero-copy mode, the limit is up to what the NIC HW supports. Usually at least five on the NICs we have checked. We consciously chose to not enforce a rigid limit (such as CONFIG_MAX_SKB_FRAGS + 1) for zero-copy mode, as it would have resulted in copy actions under the hood to fit into what limit the NIC supports. Kind of defeats the purpose of zero-copy mode. How to probe for this limit is explained in the "probe for multi-buffer support" section.

On the Rx path in copy-mode, the xsk core copies the XDP data into multiple descriptors, if needed, and sets the XDP_PKT_CONTD flag as detailed before. Zero-copy mode works the same, though the data is not copied. When the application gets a descriptor with the XDP_PKT_CONTD flag set to one, it means that the packet consists of multiple buffers and it continues with the next buffer in the following descriptor. When a descriptor with XDP_PKT_CONTD == 0 is received, it means that this is the last buffer of the packet. AF_XDP guarantees that only a complete packet (all frames in the packet) is sent to the application. If there is not enough space in the AF_XDP Rx ring, all frames of the packet will be dropped.

If application reads a batch of descriptors, using for example the libxdp interfaces, it is not guaranteed that the batch will end with a full packet. It might end in the middle of a packet and the rest of the buffers of that packet will arrive at the beginning of the next batch, since the libxdp interface does not read the whole ring (unless you have an enormous batch size or a very small ring size).

An example program each for Rx and Tx multi-buffer support can be found later in this document.

<a id="rst-usage"></a>

### Usage

In order to use AF_XDP sockets two parts are needed. The user-space application and the XDP program. For a complete setup and usage example, please refer to the xdp-project at [https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example](<https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example>).

The XDP code sample is the following:



```c
SEC("xdp_sock") int xdp_sock_prog(struct xdp_md *ctx)
{
    int index = ctx->rx_queue_index;

    // A set entry here means that the corresponding queue_id
    // has an active AF_XDP socket bound to it.
    if (bpf_map_lookup_elem(&xsks_map, &index))
        return bpf_redirect_map(&xsks_map, index, 0);

    return XDP_PASS;
}
```

A simple but not so performance ring dequeue and enqueue could look like this:



```c
// struct xdp_rxtx_ring {
//     __u32 *producer;
//     __u32 *consumer;
//     struct xdp_desc *desc;
// };

// struct xdp_umem_ring {
//     __u32 *producer;
//     __u32 *consumer;
//     __u64 *desc;
// };

// typedef struct xdp_rxtx_ring RING;
// typedef struct xdp_umem_ring RING;

// typedef struct xdp_desc RING_TYPE;
// typedef __u64 RING_TYPE;

int dequeue_one(RING *ring, RING_TYPE *item)
{
    __u32 entries = *ring->producer - *ring->consumer;

    if (entries == 0)
        return -1;

    // read-barrier!

    *item = ring->desc[*ring->consumer & (RING_SIZE - 1)];
    (*ring->consumer)++;
    return 0;
}

int enqueue_one(RING *ring, const RING_TYPE *item)
{
    u32 free_entries = RING_SIZE - (*ring->producer - *ring->consumer);

    if (free_entries == 0)
        return -1;

    ring->desc[*ring->producer & (RING_SIZE - 1)] = *item;

    // write-barrier!

    (*ring->producer)++;
    return 0;
}
```

But please use the libbpf functions as they are optimized and ready to use. Will make your life easier.

<a id="rst-usage-multi-buffer-rx"></a>

### Usage Multi-Buffer Rx

Here is a simple Rx path pseudo-code example (using libxdp interfaces for simplicity). Error paths have been excluded to keep it short:



```c
void rx_packets(struct xsk_socket_info *xsk)
{
    static bool new_packet = true;
    u32 idx_rx = 0, idx_fq = 0;
    static char *pkt;

    int rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);

    xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);

    for (int i = 0; i < rcvd; i++) {
        struct xdp_desc *desc = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++);
        char *frag = xsk_umem__get_data(xsk->umem->buffer, desc->addr);
        bool eop = !(desc->options & XDP_PKT_CONTD);

        if (new_packet)
            pkt = frag;
        else
            add_frag_to_pkt(pkt, frag);

        if (eop)
            process_pkt(pkt);

        new_packet = eop;

        *xsk_ring_prod__fill_addr(&xsk->umem->fq, idx_fq++) = desc->addr;
    }

    xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
    xsk_ring_cons__release(&xsk->rx, rcvd);
}
```

<a id="rst-usage-multi-buffer-tx"></a>

### Usage Multi-Buffer Tx

Here is an example Tx path pseudo-code (using libxdp interfaces for simplicity) ignoring that the umem is finite in size, and that we eventually will run out of packets to send. Also assumes pkts.addr points to a valid location in the umem.



```c
void tx_packets(struct xsk_socket_info *xsk, struct pkt *pkts,
                int batch_size)
{
    u32 idx, i, pkt_nb = 0;

    xsk_ring_prod__reserve(&xsk->tx, batch_size, &idx);

    for (i = 0; i < batch_size;) {
        u64 addr = pkts[pkt_nb].addr;
        u32 len = pkts[pkt_nb].size;

        do {
            struct xdp_desc *tx_desc;

            tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i++);
            tx_desc->addr = addr;

            if (len > xsk_frame_size) {
                tx_desc->len = xsk_frame_size;
                tx_desc->options = XDP_PKT_CONTD;
            } else {
                tx_desc->len = len;
                tx_desc->options = 0;
                pkt_nb++;
            }
            len -= tx_desc->len;
            addr += xsk_frame_size;

            if (i == batch_size) {
                /* Remember len, addr, pkt_nb for next iteration.
                 * Skipped for simplicity.
                 */
                break;
            }
        } while (len);
    }

    xsk_ring_prod__submit(&xsk->tx, i);
}
```

<a id="rst-probing-for-multi-buffer-support"></a>

### Probing for Multi-Buffer Support

To discover if a driver supports multi-buffer AF_XDP in SKB or DRV mode, use the XDP_FEATURES feature of netlink in linux/netdev.h to query for NETDEV_XDP_ACT_RX_SG support. This is the same flag as for querying for XDP multi-buffer support. If XDP supports multi-buffer in a driver, then AF_XDP will also support that in SKB and DRV mode.

To discover if a driver supports multi-buffer AF_XDP in zero-copy mode, use XDP_FEATURES and first check the NETDEV_XDP_ACT_XSK_ZEROCOPY flag. If it is set, it means that at least zero-copy is supported and you should go and check the netlink attribute NETDEV_A_DEV_XDP_ZC_MAX_SEGS in linux/netdev.h. An unsigned integer value will be returned stating the max number of frags that are supported by this device in zero-copy mode. These are the possible return values:

- **1: Multi-buffer for zero-copy is not supported by this device, as max**

  one fragment supported means that multi-buffer is not possible.

- **&gt;=2: Multi-buffer is supported in zero-copy mode for this device. The**

  returned number signifies the max number of frags supported.

For an example on how these are used through libbpf, please take a look at tools/testing/selftests/bpf/xskxceiver.c.

<a id="rst-multi-buffer-support-for-zero-copy-drivers"></a>

### Multi-Buffer Support for Zero-Copy Drivers

Zero-copy drivers usually use the batched APIs for Rx and Tx processing. Note that the Tx batch API guarantees that it will provide a batch of Tx descriptors that ends with full packet at the end. This to facilitate extending a zero-copy driver with multi-buffer support.

<a id="rst-sample-application"></a>

## Sample application

There is a xdpsock benchmarking/test application that can be found at [https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example](<https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example>) that demonstrates how to use AF_XDP sockets with private UMEMs. Say that you would like your UDP traffic from port 4242 to end up in queue 16, that we will enable AF_XDP on. Here, we use ethtool for this:



```text
ethtool -N p3p2 rx-flow-hash udp4 fn
ethtool -N p3p2 flow-type udp4 src-port 4242 dst-port 4242 \
    action 16
```

Running the rxdrop benchmark in XDP_DRV mode can then be done using:



```text
samples/bpf/xdpsock -i p3p2 -q 16 -r -N
```

For XDP_SKB mode, use the switch "-S" instead of "-N" and all options can be displayed with "-h", as usual.

This sample application uses libbpf to make the setup and usage of AF_XDP simpler. If you want to know how the raw uapi of AF_XDP is really used to make something more advanced, take a look at the libbpf code in tools/testing/selftests/bpf/xsk.\[ch\].

<a id="rst-faq"></a>

## FAQ

Q: I am not seeing any traffic on the socket. What am I doing wrong?

- **A: When a netdev of a physical NIC is initialized, Linux usually**

  allocates one RX and TX queue pair per core. So on a 8 core system, queue ids 0 to 7 will be allocated, one per core. In the AF_XDP bind call or the xsk_socket__create libbpf function call, you specify a specific queue id to bind to and it is only the traffic towards that queue you are going to get on you socket. So in the example above, if you bind to queue 0, you are NOT going to get any traffic that is distributed to queues 1 through 7. If you are lucky, you will see the traffic, but usually it will end up on one of the queues you have not bound to.

  There are a number of ways to solve the problem of getting the traffic you want to the queue id you bound to. If you want to see all the traffic, you can force the netdev to only have 1 queue, queue id 0, and then bind to queue 0. You can use ethtool to do this:



  ```text
  sudo ethtool -L <interface> combined 1
  ```

  If you want to only see part of the traffic, you can program the NIC through ethtool to filter out your traffic to a single queue id that you can bind your XDP socket to. Here is one example in which UDP traffic to and from port 4242 are sent to queue 2:



  ```text
  sudo ethtool -N <interface> rx-flow-hash udp4 fn
  sudo ethtool -N <interface> flow-type udp4 src-port 4242 dst-port \
  4242 action 2
  ```

  A number of other ways are possible all up to the capabilities of the NIC you have.

- **Q: Can I use the XSKMAP to implement a switch between different umems**

  in copy mode?

- **A: The short answer is no, that is not supported at the moment. The**

  XSKMAP can only be used to switch traffic coming in on queue id X to sockets bound to the same queue id X. The XSKMAP can contain sockets bound to different queue ids, for example X and Y, but only traffic goming in from queue id Y can be directed to sockets bound to the same queue id Y. In zero-copy mode, you should use the switch, or other distribution mechanism, in your NIC to direct traffic to the correct queue id and socket.

Q: My packets are sometimes corrupted. What is wrong?

- **A: Care has to be taken not to feed the same buffer in the UMEM into**

  more than one ring at the same time. If you for example feed the same buffer into the FILL ring and the TX ring at the same time, the NIC might receive data into the buffer at the same time it is sending it. This will cause some packets to become corrupted. Same thing goes for feeding the same buffer into the FILL rings belonging to different queue ids or netdevs bound with the XDP_SHARED_UMEM flag.

<a id="rst-credits"></a>

## Credits

- Björn Töpel (AF_XDP core)

- Magnus Karlsson (AF_XDP core)

- Alexander Duyck

- Alexei Starovoitov

- Daniel Borkmann

- Jesper Dangaard Brouer

- John Fastabend

- Jonathan Corbet (LWN coverage)

- Michael S. Tsirkin

- Qi Z Zhang

- Willem de Bruijn

---

# IP-Aliasing

_Peios Kernel / Internals / Networking_

> IP-aliases are an obsolete way to manage multiple IP-addresses/masks per interface. Newer tools such as iproute2 support multiple address/prefixes per interface, but aliases are still supported for backwards compatibility.

<a id="rst-ip-aliasing"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

IP-aliases are an obsolete way to manage multiple IP-addresses/masks per interface. Newer tools such as iproute2 support multiple address/prefixes per interface, but aliases are still supported for backwards compatibility.

An alias is formed by adding a colon and a string when running ifconfig. This string is usually numeric, but this is not a must.

<a id="rst-alias-creation"></a>

## Alias creation

Alias creation is done by 'magic' interface naming: eg. to create a 200.1.1.1 alias for eth0 ...



```text
# ifconfig eth0:0 200.1.1.1  etc,etc....
      ~~ -> request alias #0 creation (if not yet exists) for eth0
```

The corresponding route is also set up by this command.  Please note: The route always points to the base interface.

<a id="rst-alias-deletion"></a>

## Alias deletion

The alias is removed by shutting the alias down:



```text
# ifconfig eth0:0 down
      ~~~~~~~~~~ -> will delete alias
```

<a id="rst-alias-re-configuring"></a>

## Alias (re-)configuring

Aliases are not real devices, but programs should be able to configure and refer to them as usual (ifconfig, route, etc).

<a id="rst-relationship-with-main-device"></a>

## Relationship with main device

If the base device is shut down the added aliases will be deleted too.

---

# ARCnet Hardware

_Peios Kernel / Internals / Networking_

> Because so many people (myself included) seem to have obtained ARCnet cards without manuals, this file contains a quick introduction to ARCnet hardware, some cabling tips, and a listing of all jumper settings I can find. If you have any…

<a id="rst-arcnet-hardware"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Avery Pennarun &lt;[apenwarr@worldvisions.ca](<mailto:apenwarr@worldvisions.ca>)&gt;

> [!NOTE]
>
> 1. This file is a supplement to [arcnet.rst](/kernel/internals/networking/arcnet.md).  Please read that for general driver configuration help.
>
> 2. This file is no longer Linux-specific.  It should probably be moved out of the kernel sources.  Ideas?

Because so many people (myself included) seem to have obtained ARCnet cards without manuals, this file contains a quick introduction to ARCnet hardware, some cabling tips, and a listing of all jumper settings I can find. If you have any settings for your particular card, and/or any other information you have, do not hesitate to [email to netdev](</kernel/internals/networking/arcnet.md#rst-arcnet-netdev>).

<a id="rst-introduction-to-arcnet"></a>

## Introduction to ARCnet

ARCnet is a network type which works in a way similar to popular Ethernet networks but which is also different in some very important ways.

First of all, you can get ARCnet cards in at least two speeds: 2.5 Mbps (slower than Ethernet) and 100 Mbps (faster than normal Ethernet).  In fact, there are others as well, but these are less common.  The different hardware types, as far as I'm aware, are not compatible and so you cannot wire a 100 Mbps card to a 2.5 Mbps card, and so on.  From what I hear, my driver does work with 100 Mbps cards, but I haven't been able to verify this myself, since I only have the 2.5 Mbps variety.  It is probably not going to saturate your 100 Mbps card.  Stop complaining. :)

You also cannot connect an ARCnet card to any kind of Ethernet card and expect it to work.

There are two "types" of ARCnet - STAR topology and BUS topology.  This refers to how the cards are meant to be wired together.  According to most available documentation, you can only connect STAR cards to STAR cards and BUS cards to BUS cards.  That makes sense, right?  Well, it's not quite true; see below under "Cabling."

Once you get past these little stumbling blocks, ARCnet is actually quite a well-designed standard.  It uses something called "modified token passing" which makes it completely incompatible with so-called "Token Ring" cards, but which makes transfers much more reliable than Ethernet does.  In fact, ARCnet will guarantee that a packet arrives safely at the destination, and even if it can't possibly be delivered properly (ie. because of a cable break, or because the destination computer does not exist) it will at least tell the sender about it.

Because of the carefully defined action of the "token", it will always make a pass around the "ring" within a maximum length of time.  This makes it useful for realtime networks.

In addition, all known ARCnet cards have an (almost) identical programming interface.  This means that with one ARCnet driver you can support any card, whereas with Ethernet each manufacturer uses what is sometimes a completely different programming interface, leading to a lot of different, sometimes very similar, Ethernet drivers.  Of course, always using the same programming interface also means that when high-performance hardware facilities like PCI bus mastering DMA appear, it's hard to take advantage of them.  Let's not go into that.

One thing that makes ARCnet cards difficult to program for, however, is the limit on their packet sizes; standard ARCnet can only send packets that are up to 508 bytes in length.  This is smaller than the Internet "bare minimum" of 576 bytes, let alone the Ethernet MTU of 1500.  To compensate, an extra level of encapsulation is defined by RFC1201, which I call "packet splitting," that allows "virtual packets" to grow as large as 64K each, although they are generally kept down to the Ethernet-style 1500 bytes.

For more information on ARCnet networks, visit the "ARCNET Resource Center" WWW page at:

> [https://www.arcnet.cc](<https://www.arcnet.cc>)

<a id="rst-cabling-arcnet-networks"></a>

## Cabling ARCnet Networks

This section was rewritten by

> Vojtech Pavlik     &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;

using information from several people, including:

> - Avery Pennraun     &lt;[apenwarr@worldvisions.ca](<mailto:apenwarr@worldvisions.ca>)&gt;
>
> - Stephen A. Wood    &lt;[saw@hallc1.cebaf.gov](<mailto:saw@hallc1.cebaf.gov>)&gt;
>
> - John Paul Morrison &lt;[jmorriso@bogomips.ee.ubc.ca](<mailto:jmorriso@bogomips.ee.ubc.ca>)&gt;
>
> - Joachim Koenig     &lt;[jojo@repas.de](<mailto:jojo@repas.de>)&gt;

and Avery touched it up a bit, at Vojtech's request.

ARCnet (the classic 2.5 Mbps version) can be connected by two different types of cabling: coax and twisted pair.  The other ARCnet-type networks (100 Mbps TCNS and 320 kbps - 32 Mbps ARCnet Plus) use different types of cabling (Type1, Fiber, C1, C4, C5).

For a coax network, you "should" use 93 Ohm RG-62 cable.  But other cables also work fine, because ARCnet is a very stable network. I personally use 75 Ohm TV antenna cable.

Cards for coax cabling are shipped in two different variants: for BUS and STAR network topologies.  They are mostly the same.  The only difference lies in the hybrid chip installed.  BUS cards use high impedance output, while STAR use low impedance.  Low impedance card (STAR) is electrically equal to a high impedance one with a terminator installed.

Usually, the ARCnet networks are built up from STAR cards and hubs.  There are two types of hubs - active and passive.  Passive hubs are small boxes with four BNC connectors containing four 47 Ohm resistors:



```text
   |         | wires
   R         + junction
-R-+-R-      R 47 Ohm resistors
   R
   |
```

The shielding is connected together.  Active hubs are much more complicated; they are powered and contain electronics to amplify the signal and send it to other segments of the net.  They usually have eight connectors.  Active hubs come in two variants - dumb and smart.  The dumb variant just amplifies, but the smart one decodes to digital and encodes back all packets coming through.  This is much better if you have several hubs in the net, since many dumb active hubs may worsen the signal quality.

And now to the cabling.  What you can connect together:

1. A card to a card.  This is the simplest way of creating a 2-computer network.

2. A card to a passive hub.  Remember that all unused connectors on the hub must be properly terminated with 93 Ohm (or something else if you don't have the right ones) terminators.

   > (Avery's note: oops, I didn't know that.  Mine (TV cable) works anyway, though.)

3. A card to an active hub.  Here is no need to terminate the unused connectors except some kind of aesthetic feeling.  But, there may not be more than eleven active hubs between any two computers.  That of course doesn't limit the number of active hubs on the network.

4. An active hub to another.

5. An active hub to passive hub.

Remember that you cannot connect two passive hubs together.  The power loss implied by such a connection is too high for the net to operate reliably.

An example of a typical ARCnet network:



```text
       R                     S - STAR type card
S------H--------A-------S    R - Terminator
       |        |            H - Hub
       |        |            A - Active hub
       |   S----H----S
       S        |
                |
                S
```

The BUS topology is very similar to the one used by Ethernet.  The only difference is in cable and terminators: they should be 93 Ohm.  Ethernet uses 50 Ohm impedance. You use T connectors to put the computers on a single line of cable, the bus. You have to put terminators at both ends of the cable. A typical BUS ARCnet network looks like:



```text
  RT----T------T------T------T------TR
   B    B      B      B      B      B

B - BUS type card
R - Terminator
T - T connector
```

But that is not all\! The two types can be connected together.  According to the official documentation the only way of connecting them is using an active hub:



```text
    A------T------T------TR
    |      B      B      B
S---H---S
    |
    S
```

The official docs also state that you can use STAR cards at the ends of BUS network in place of a BUS card and a terminator:



```text
S------T------T------S
       B      B
```

But, according to my own experiments, you can simply hang a BUS type card anywhere in middle of a cable in a STAR topology network.  And more - you can use the bus card in place of any star card if you use a terminator. Then you can build very complicated networks fulfilling all your needs\!  An example:



```text
                              S
                              |
       RT------T-------T------H------S
        B      B       B      |
                              |       R
S------A------T-------T-------A-------H------TR
       |      B       B       |       |      B
       |   S                 BT       |
       |   |                  |  S----A-----S
S------H---A----S             |       |
       |   |      S------T----H---S   |
       S   S             B    R       S
```

A basically different cabling scheme is used with Twisted Pair cabling. Each of the TP cards has two RJ (phone-cord style) connectors.  The cards are then daisy-chained together using a cable connecting every two neighboring cards.  The ends are terminated with RJ 93 Ohm terminators which plug into the empty connectors of cards on the ends of the chain.  An example:



```text
     ___________   ___________
 _R_|_         _|_|_         _|_R_
|     |       |     |       |     |
|Card |       |Card |       |Card |
|_____|       |_____|       |_____|
```

There are also hubs for the TP topology.  There is nothing difficult involved in using them; you just connect a TP chain to a hub on any end or even at both.  This way you can create almost any network configuration. The maximum of 11 hubs between any two computers on the net applies here as well.  An example:



```text
RP-------P--------P--------H-----P------P-----PR
                           |
  RP-----H--------P--------H-----P------PR
         |                 |
         PR                PR

R - RJ Terminator
P - TP Card
H - TP Hub
```

Like any network, ARCnet has a limited cable length.  These are the maximum cable lengths between two active ends (an active end being an active hub or a STAR card).

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> RG-62
>
> </td>
> <td>
>
>
> 93 Ohm
>
> </td>
> <td>
>
>
> up to 650 m
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> RG-59/U
>
> </td>
> <td>
>
>
> 75 Ohm
>
> </td>
> <td>
>
>
> up to 457 m
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> RG-11/U
>
> </td>
> <td>
>
>
> 75 Ohm
>
> </td>
> <td>
>
>
> up to 533 m
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> IBM Type 1
>
> </td>
> <td>
>
>
> 150 Ohm
>
> </td>
> <td>
>
>
> up to 200 m
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> IBM Type 3
>
> </td>
> <td>
>
>
> 100 Ohm
>
> </td>
> <td>
>
>
> up to 100 m
>
> </td>
> </tr>
> </tbody>
> </table>

The maximum length of all cables connected to a passive hub is limited to 65 meters for RG-62 cabling; less for others.  You can see that using passive hubs in a large network is a bad idea. The maximum length of a single "BUS Trunk" is about 300 meters for RG-62. The maximum distance between the two most distant points of the net is limited to 3000 meters. The maximum length of a TP cable between two cards/hubs is 650 meters.

<a id="rst-setting-the-jumpers"></a>

## Setting the Jumpers

All ARCnet cards should have a total of four or five different settings:

> - the I/O address:  this is the "port" your ARCnet card is on.  Probed values in the Linux ARCnet driver are only from 0x200 through 0x3F0. (If your card has additional ones, which is possible, please tell me.) This should not be the same as any other device on your system.  According to a doc I got from Novell, MS Windows prefers values of 0x300 or more, eating net connections on my system (at least) otherwise.  My guess is this may be because, if your card is at 0x2E0, probing for a serial port at 0x2E8 will reset the card and probably mess things up royally.
>
>   > - Avery's favourite: 0x300.
>
> - - **the IRQ: on  8-bit cards, it might be 2 (9), 3, 4, 5, or 7.**
>
>     on 16-bit cards, it might be 2 (9), 3, 4, 5, 7, or 10-15.
>
>   Make sure this is different from any other card on your system.  Note that IRQ2 is the same as IRQ9, as far as Linux is concerned.  You can "cat /proc/interrupts" for a somewhat complete list of which ones are in use at any given time.  Here is a list of common usages from Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;:
>
>   > ("Not on bus" means there is no way for a card to generate this interrupt)
>   >
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  0
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Timer 0 (Not on bus)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  1
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Keyboard (Not on bus)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > IRQ Controller 2 (Not on bus, nor does interrupt the CPU)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  3
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > COM2
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  4
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > COM1
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  5
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE (LPT2 if you have it; sometimes COM3; maybe PLIP)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  6
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Floppy disk controller
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  7
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE (LPT1 if you don't use the polling driver; PLIP)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  8
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Realtime Clock Interrupt (Not on bus)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ  9
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE (VGA vertical sync interrupt if enabled)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 10
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 11
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 12
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 13
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Numeric Coprocessor (Not on bus)
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 14
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Fixed Disk Controller
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > IRQ 15
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > FREE (Fixed Disk Controller 2 if you have it)
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>
>   >
>   > > [!NOTE]
>   > >
>   > > IRQ 9 is used on some video cards for the "vertical retrace" interrupt.  This interrupt would have been handy for things like video games, as it occurs exactly once per screen refresh, but unfortunately IBM cancelled this feature starting with the original VGA and thus many VGA/SVGA cards do not support it.  For this reason, no modern software uses this interrupt and it can almost always be safely disabled, if your video card supports it at all.
>   >
>   > If your card for some reason CANNOT disable this IRQ (usually there is a jumper), one solution would be to clip the printed circuit contact on the board: it's the fourth contact from the left on the back side.  I take no responsibility if you try this.
>   >
>   > - Avery's favourite: IRQ2 (actually IRQ9).  Watch that VGA, though.
>
> - the memory address:  Unlike most cards, ARCnets use "shared memory" for copying buffers around.  Make SURE it doesn't conflict with any other used memory in your system\!
>
>
>
>   ```text
>   A0000           - VGA graphics memory (ok if you don't have VGA)
>   B0000           - Monochrome text mode
>   C0000           \  One of these is your VGA BIOS - usually C0000.
>   E0000           /
>   F0000           - System BIOS
>   ```
>
>   Anything less than 0xA0000 is, well, a BAD idea since it isn't above 640k.
>
>   > - Avery's favourite: 0xD0000
>
> - the station address:  Every ARCnet card has its own "unique" network address from 0 to 255.  Unlike Ethernet, you can set this address yourself with a jumper or switch (or on some cards, with special software).  Since it's only 8 bits, you can only have 254 ARCnet cards on a network.  DON'T use 0 or 255, since these are reserved (although neat stuff will probably happen if you DO use them).  By the way, if you haven't already guessed, don't set this the same as any other ARCnet on your network\!
>
>   > - Avery's favourite:  3 and 4.  Not that it matters.
>
> - There may be ETS1 and ETS2 settings.  These may or may not make a difference on your card (many manuals call them "reserved"), but are used to change the delays used when powering up a computer on the network.  This is only necessary when wiring VERY long range ARCnet networks, on the order of 4km or so; in any case, the only real requirement here is that all cards on the network with ETS1 and ETS2 jumpers have them in the same position.  Chris Hindy &lt;[chrish@io.org](<mailto:chrish@io.org>)&gt; sent in a chart with actual values for this:
>
>   >
>   > <table>
>   > <thead>
>   > <tr>
>   > <th>
>   >
>   >
>   > ET1
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > ET2
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > Response Time
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > Reconfiguration Time
>   >
>   > </th>
>   > </tr>
>   > </thead>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > open
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > open
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 74.7us
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 840us
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > open
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > closed
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 283.4us
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 1680us
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > closed
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > open
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 561.8us
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 1680us
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > closed
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > closed
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 1118.6us
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 1680us
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>
>
>   Make sure you set ETS1 and ETS2 to the SAME VALUE for all cards on your network.

Also, on many cards (not mine, though) there are red and green LED's. Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt; tells me this is what they mean:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> GREEN
>
> </th>
> <th>
>
>
> RED
>
> </th>
> <th>
>
>
> Status
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> OFF
>
> </td>
> <td>
>
>
> OFF
>
> </td>
> <td>
>
>
> Power off
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> OFF
>
> </td>
> <td>
>
>
> Short flashes
>
> </td>
> <td>
>
>
> Cabling problems (broken cable or not terminated)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> OFF (short)
>
> </td>
> <td>
>
>
> ON
>
> </td>
> <td>
>
>
> Card init
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ON
>
> </td>
> <td>
>
>
> ON
>
> </td>
> <td>
>
>
> Normal state - everything OK, nothing happens
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ON
>
> </td>
> <td>
>
>
> Long flashes
>
> </td>
> <td>
>
>
> Data transfer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ON
>
> </td>
> <td>
>
>
> OFF
>
> </td>
> <td>
>
>
> Never happens (maybe when wrong ID)
>
> </td>
> </tr>
> </tbody>
> </table>

The following is all the specific information people have sent me about their own particular ARCnet cards.  It is officially a mess, and contains huge amounts of duplicated information.  I have no time to fix it.  If you want to, PLEASE DO\!  Just send me a 'diff -u' of all your changes.

The model \# is listed right above specifics for that card, so you should be able to use your text viewer's "search" function to find the entry you want. If you don't KNOW what kind of card you have, try looking through the various diagrams to see if you can tell.

If your model isn't listed and/or has different settings, PLEASE PLEASE tell me.  I had to figure mine out without the manual, and it WASN'T FUN\!

Even if your ARCnet model isn't listed, but has the same jumpers as another model that is, please e-mail me to say so.

Cards Listed in this file (in this order, mostly):

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Manufacturer
>
> </th>
> <th>
>
>
> Model \#
>
> </th>
> <th>
>
>
> Bits
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC100
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC110
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC120
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC130
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC270E
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC500
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC500Longboard
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC550Longboard
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC600
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC
>
> </td>
> <td>
>
>
> PC710
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> SMC?
>
> </td>
> <td>
>
>
> LCS-8830(-T)
>
> </td>
> <td>
>
>
> 8/16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Puredata
>
> </td>
> <td>
>
>
> PDI507
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> CNet Tech
>
> </td>
> <td>
>
>
> CN120-Series
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> CNet Tech
>
> </td>
> <td>
>
>
> CN160-Series
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Lantech?
>
> </td>
> <td>
>
>
> UM9065L chipset
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Acer
>
> </td>
> <td>
>
>
> 5210-003
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Datapoint?
>
> </td>
> <td>
>
>
> LAN-ARC-8
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Topware
>
> </td>
> <td>
>
>
> TA-ARC/10
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Thomas-Conrad
>
> </td>
> <td>
>
>
> 500-6242-0097 REV A
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Waterloo?
>
> </td>
> <td>
>
>
> (C)1985 Waterloo Micro.
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> No Name
>
> </td>
> <td>
>
>
> --
>
> </td>
> <td>
>
>
> 8/16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> No Name
>
> </td>
> <td>
>
>
> Taiwan R.O.C?
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> No Name
>
> </td>
> <td>
>
>
> Model 9058
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Tiara
>
> </td>
> <td>
>
>
> Tiara Lancard?
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> </tbody>
> </table>

- SMC = Standard Microsystems Corp.

- CNet Tech = CNet Technology, Inc.

<a id="rst-unclassified-stuff"></a>

## Unclassified Stuff

> - Please send any other information you can find.
>
> - And some other stuff (more info is welcome\!):
>
>
>
>   ```text
>   From: root@ultraworld.xs4all.nl (Timo Hilbrink)
>   To: apenwarr@foxnet.net (Avery Pennarun)
>   Date: Wed, 26 Oct 1994 02:10:32 +0000 (GMT)
>   Reply-To: timoh@xs4all.nl
>
>   [...parts deleted...]
>
>   About the jumpers: On my PC130 there is one more jumper, located near the
>   cable-connector and it's for changing to star or bus topology;
>   closed: star - open: bus
>   On the PC500 are some more jumper-pins, one block labeled with RX,PDN,TXI
>   and another with ALE,LA17,LA18,LA19 these are undocumented..
>
>   [...more parts deleted...]
>
>   --- CUT ---
>   ```

<a id="rst-standard-microsystems-corp-smc"></a>

## Standard Microsystems Corp (SMC)

<a id="rst-pc100-pc110-pc120-pc130-8-bit-cards-and-pc500-pc600-16-bit-cards"></a>

### PC100, PC110, PC120, PC130 (8-bit cards) and PC500, PC600 (16-bit cards)

> - mainly from Avery Pennarun &lt;[apenwarr@worldvisions.ca](<mailto:apenwarr@worldvisions.ca>)&gt;.  Values depicted are from Avery's setup.
>
> - special thanks to Timo Hilbrink &lt;[timoh@xs4all.nl](<mailto:timoh@xs4all.nl>)&gt; for noting that PC120, 130, 500, and 600 all have the same switches as Avery's PC100. PC500/600 have several extra, undocumented pins though. (?)
>
> - PC110 settings were verified by Stephen A. Wood &lt;[saw@cebaf.gov](<mailto:saw@cebaf.gov>)&gt;
>
> - Also, the JP- and S-numbers probably don't match your card exactly.  Try to find jumpers/switches with the same number of settings - it's probably more reliable.



```text
     JP5                       [|]    :    :    :    :
(IRQ Setting)                 IRQ2  IRQ3 IRQ4 IRQ5 IRQ7
                Put exactly one jumper on exactly one set of pins.


                          1  2   3  4  5  6   7  8  9 10
     S1                /----------------------------------\
(I/O and Memory        |  1  1 * 0  0  0  0 * 1  1  0  1  |
 addresses)            \----------------------------------/
                          |--|   |--------|   |--------|
                          (a)       (b)           (m)

                WARNING.  It's very important when setting these which way
                you're holding the card, and which way you think is '1'!

                If you suspect that your settings are not being made
                correctly, try reversing the direction or inverting the
                switch positions.

                a: The first digit of the I/O address.
                        Setting         Value
                        -------         -----
                        00              0
                        01              1
                        10              2
                        11              3

                b: The second digit of the I/O address.
                        Setting         Value
                        -------         -----
                        0000            0
                        0001            1
                        0010            2
                        ...             ...
                        1110            E
                        1111            F

                The I/O address is in the form ab0.  For example, if
                a is 0x2 and b is 0xE, the address will be 0x2E0.

                DO NOT SET THIS LESS THAN 0x200!!!!!


                m: The first digit of the memory address.
                        Setting         Value
                        -------         -----
                        0000            0
                        0001            1
                        0010            2
                        ...             ...
                        1110            E
                        1111            F

                The memory address is in the form m0000.  For example, if
                m is D, the address will be 0xD0000.

                DO NOT SET THIS TO C0000, F0000, OR LESS THAN A0000!

                          1  2  3  4  5  6  7  8
     S2                /--------------------------\
(Station Address)      |  1  1  0  0  0  0  0  0  |
                       \--------------------------/

                        Setting         Value
                        -------         -----
                        00000000        00
                        10000000        01
                        01000000        02
                        ...
                        01111111        FE
                        11111111        FF

                Note that this is binary with the digits reversed!

                DO NOT SET THIS TO 0 OR 255 (0xFF)!
```

<a id="rst-pc130e-pc270e-8-bit-cards"></a>

### PC130E/PC270E (8-bit cards)

> - from Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt;

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the following Original SMC Manual

> "Configuration Guide for ARCNET(R)-PC130E/PC270 Network Controller Boards Pub. \# 900.044A June, 1989"

ARCNET is a registered trademark of the Datapoint Corporation SMC is a registered trademark of the Standard Microsystems Corporation

The PC130E is an enhanced version of the PC130 board, is equipped with a standard BNC female connector for connection to RG-62/U coax cable. Since this board is designed both for point-to-point connection in star networks and for connection to bus networks, it is downwardly compatible with all the other standard boards designed for coax networks (that is, the PC120, PC110 and PC100 star topology boards and the PC220, PC210 and PC200 bus topology boards).

The PC270E is an enhanced version of the PC260 board, is equipped with two modular RJ11-type jacks for connection to twisted pair wiring. It can be used in a star or a daisy-chained network.



```text
      8 7 6 5 4 3 2 1
 ________________________________________________________________
|   |       S1        |                                          |
|   |_________________|                                          |
|    Offs|Base |I/O Addr                                         |
|     RAM Addr |                                              ___|
|         ___  ___                                       CR3 |___|
|        |   \/   |                                      CR4 |___|
|        |  PROM  |                                           ___|
|        |        |                                        N |   | 8
|        | SOCKET |                                        o |   | 7
|        |________|                                        d |   | 6
|                   ___________________                    e |   | 5
|                  |                   |                   A | S | 4
|       |oo| EXT2  |                   |                   d | 2 | 3
|       |oo| EXT1  |       SMC         |                   d |   | 2
|       |oo| ROM   |      90C63        |                   r |___| 1
|       |oo| IRQ7  |                   |               |o|  _____|
|       |oo| IRQ5  |                   |               |o| | J1  |
|       |oo| IRQ4  |                   |              STAR |_____|
|       |oo| IRQ3  |                   |                   | J2  |
|       |oo| IRQ2  |___________________|                   |_____|
|___                                               ______________|
    |                                             |
    |_____________________________________________|
```

Legend:



```text
SMC 90C63     ARCNET Controller / Transceiver /Logic
S1    1-3:    I/O Base Address Select
      4-6:    Memory Base Address Select
      7-8:    RAM Offset Select
S2    1-8:    Node ID Select
EXT           Extended Timeout Select
ROM           ROM Enable Select
STAR          Selected - Star Topology        (PC130E only)
              Deselected - Bus Topology       (PC130E only)
CR3/CR4       Diagnostic LEDs
J1            BNC RG62/U Connector            (PC130E only)
J1            6-position Telephone Jack       (PC270E only)
J2            6-position Telephone Jack       (PC270E only)
```

Setting one of the switches to Off/Open means "1", On/Closed means "0".

<a id="rst-setting-the-node-id"></a>

#### Setting the Node ID

The eight switches in group S2 are used to set the node ID. These switches work in a way similar to the PC100-series cards; see that entry for more information.

<a id="rst-setting-the-i-o-base-address"></a>

#### Setting the I/O Base Address

The first three switches in switch group S1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch | Hex I/O
1 2 3  | Address
-------|--------
0 0 0  |  260
0 0 1  |  290
0 1 0  |  2E0  (Manufacturer's default)
0 1 1  |  2F0
1 0 0  |  300
1 0 1  |  350
1 1 0  |  380
1 1 1  |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer requires 2K of a 16K block of RAM. The base of this 16K block can be located in any of eight positions. Switches 4-6 of switch group S1 select the Base of the 16K block. Within that 16K address space, the buffer may be assigned any one of four positions, determined by the offset, switches 7 and 8 of group S1.



```text
 Switch     | Hex RAM | Hex ROM
 4 5 6  7 8 | Address | Address *)
 -----------|---------|-----------
 0 0 0  0 0 |  C0000  |  C2000
 0 0 0  0 1 |  C0800  |  C2000
 0 0 0  1 0 |  C1000  |  C2000
 0 0 0  1 1 |  C1800  |  C2000
            |         |
 0 0 1  0 0 |  C4000  |  C6000
 0 0 1  0 1 |  C4800  |  C6000
 0 0 1  1 0 |  C5000  |  C6000
 0 0 1  1 1 |  C5800  |  C6000
            |         |
 0 1 0  0 0 |  CC000  |  CE000
 0 1 0  0 1 |  CC800  |  CE000
 0 1 0  1 0 |  CD000  |  CE000
 0 1 0  1 1 |  CD800  |  CE000
            |         |
 0 1 1  0 0 |  D0000  |  D2000  (Manufacturer's default)
 0 1 1  0 1 |  D0800  |  D2000
 0 1 1  1 0 |  D1000  |  D2000
 0 1 1  1 1 |  D1800  |  D2000
            |         |
 1 0 0  0 0 |  D4000  |  D6000
 1 0 0  0 1 |  D4800  |  D6000
 1 0 0  1 0 |  D5000  |  D6000
 1 0 0  1 1 |  D5800  |  D6000
            |         |
 1 0 1  0 0 |  D8000  |  DA000
 1 0 1  0 1 |  D8800  |  DA000
 1 0 1  1 0 |  D9000  |  DA000
 1 0 1  1 1 |  D9800  |  DA000
            |         |
 1 1 0  0 0 |  DC000  |  DE000
 1 1 0  0 1 |  DC800  |  DE000
 1 1 0  1 0 |  DD000  |  DE000
 1 1 0  1 1 |  DD800  |  DE000
            |         |
 1 1 1  0 0 |  E0000  |  E2000
 1 1 1  0 1 |  E0800  |  E2000
 1 1 1  1 0 |  E1000  |  E2000
 1 1 1  1 1 |  E1800  |  E2000

*) To enable the 8K Boot PROM install the jumper ROM.
   The default is jumper ROM not installed.
```

<a id="rst-setting-the-timeouts-and-interrupt"></a>

#### Setting the Timeouts and Interrupt

The jumpers labeled EXT1 and EXT2 are used to determine the timeout parameters. These two jumpers are normally left open.

To select a hardware interrupt level set one (only one\!) of the jumpers IRQ2, IRQ3, IRQ4, IRQ5, IRQ7. The Manufacturer's default is IRQ2.

<a id="rst-configuring-the-pc130e-for-star-or-bus-topology"></a>

#### Configuring the PC130E for Star or Bus Topology

The single jumper labeled STAR is used to configure the PC130E board for star or bus topology. When the jumper is installed, the board may be used in a star network, when it is removed, the board can be used in a bus topology.

<a id="rst-diagnostic-leds"></a>

#### Diagnostic LEDs

Two diagnostic LEDs are visible on the rear bracket of the board. The green LED monitors the network activity: the red one shows the board activity:



```text
Green  | Status               Red      | Status
-------|-------------------   ---------|-------------------
 on    | normal activity      flash/on | data transfer
 blink | reconfiguration      off      | no data transfer;
 off   | defective board or            | incorrect memory or
       | node ID is zero               | I/O address
```

<a id="rst-pc500-pc550-longboard-16-bit-cards"></a>

### PC500/PC550 Longboard (16-bit cards)

> - from Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt;
>
> > [!NOTE]
> >
> > There is another Version of the PC500 called Short Version, which is different in hard- and software\! The most important differences are:
> >
> > - The long board has no Shared memory.
> >
> > - On the long board the selection of the interrupt is done by binary coded switch, on the short board directly by jumper.

\[Avery's note: pay special attention to that: the long board HAS NO SHARED MEMORY.  This means the current Linux-ARCnet driver can't use these cards. I have obtained a PC500Longboard and will be doing some experiments on it in the future, but don't hold your breath.  Thanks again to Juergen Seifert for his advice about this\!\]

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the following Original SMC Manual

> "Configuration Guide for SMC ARCNET-PC500/PC550 Series Network Controller Boards Pub. \# 900.033 Rev. A November, 1989"

ARCNET is a registered trademark of the Datapoint Corporation SMC is a registered trademark of the Standard Microsystems Corporation

The PC500 is equipped with a standard BNC female connector for connection to RG-62/U coax cable. The board is designed both for point-to-point connection in star networks and for connection to bus networks.

The PC550 is equipped with two modular RJ11-type jacks for connection to twisted pair wiring. It can be used in a star or a daisy-chained (BUS) network.



```text
    1
    0 9 8 7 6 5 4 3 2 1     6 5 4 3 2 1
 ____________________________________________________________________
< |         SW1         | |     SW2     |                            |
> |_____________________| |_____________|                            |
<   IRQ    |I/O Addr                                                 |
>                                                                 ___|
<                                                            CR4 |___|
>                                                            CR3 |___|
<                                                                 ___|
>                                                              N |   | 8
<                                                              o |   | 7
>                                                              d | S | 6
<                                                              e | W | 5
>                                                              A | 3 | 4
<                                                              d |   | 3
>                                                              d |   | 2
<                                                              r |___| 1
>                                                        |o|    _____|
<                                                        |o|   | J1  |
>  3 1                                                   JP6   |_____|
< |o|o| JP2                                                    | J2  |
> |o|o|                                                        |_____|
<  4 2__                                               ______________|
>    |  |                                             |
<____|  |_____________________________________________|
```

Legend:



```text
SW1   1-6:    I/O Base Address Select
      7-10:   Interrupt Select
SW2   1-6:    Reserved for Future Use
SW3   1-8:    Node ID Select
JP2   1-4:    Extended Timeout Select
JP6           Selected - Star Topology        (PC500 only)
              Deselected - Bus Topology       (PC500 only)
CR3   Green   Monitors Network Activity
CR4   Red     Monitors Board Activity
J1            BNC RG62/U Connector            (PC500 only)
J1            6-position Telephone Jack       (PC550 only)
J2            6-position Telephone Jack       (PC550 only)
```

Setting one of the switches to Off/Open means "1", On/Closed means "0".

<a id="rst-setting-the-node-id-1"></a>

#### Setting the Node ID

The eight switches in group SW3 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 1 serves as the least significant bit (LSB).

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  1    |   1
  2    |   2
  3    |   4
  4    |   8
  5    |  16
  6    |  32
  7    |  64
  8    | 128
```

Some Examples:



```text
 Switch         | Hex     | Decimal
8 7 6 5 4 3 2 1 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-1"></a>

#### Setting the I/O Base Address

The first six switches in switch group SW1 are used to select one of 32 possible I/O Base addresses using the following table:



```text
Switch       | Hex I/O
6 5  4 3 2 1 | Address
-------------|--------
0 1  0 0 0 0 |  200
0 1  0 0 0 1 |  210
0 1  0 0 1 0 |  220
0 1  0 0 1 1 |  230
0 1  0 1 0 0 |  240
0 1  0 1 0 1 |  250
0 1  0 1 1 0 |  260
0 1  0 1 1 1 |  270
0 1  1 0 0 0 |  280
0 1  1 0 0 1 |  290
0 1  1 0 1 0 |  2A0
0 1  1 0 1 1 |  2B0
0 1  1 1 0 0 |  2C0
0 1  1 1 0 1 |  2D0
0 1  1 1 1 0 |  2E0 (Manufacturer's default)
0 1  1 1 1 1 |  2F0
1 1  0 0 0 0 |  300
1 1  0 0 0 1 |  310
1 1  0 0 1 0 |  320
1 1  0 0 1 1 |  330
1 1  0 1 0 0 |  340
1 1  0 1 0 1 |  350
1 1  0 1 1 0 |  360
1 1  0 1 1 1 |  370
1 1  1 0 0 0 |  380
1 1  1 0 0 1 |  390
1 1  1 0 1 0 |  3A0
1 1  1 0 1 1 |  3B0
1 1  1 1 0 0 |  3C0
1 1  1 1 0 1 |  3D0
1 1  1 1 1 0 |  3E0
1 1  1 1 1 1 |  3F0
```

<a id="rst-setting-the-interrupt"></a>

#### Setting the Interrupt

Switches seven through ten of switch group SW1 are used to select the interrupt level. The interrupt level is binary coded, so selections from 0 to 15 would be possible, but only the following eight values will be supported: 3, 4, 5, 7, 9, 10, 11, 12.



```text
Switch   | IRQ
10 9 8 7 |
---------|--------
 0 0 1 1 |  3
 0 1 0 0 |  4
 0 1 0 1 |  5
 0 1 1 1 |  7
 1 0 0 1 |  9 (=2) (default)
 1 0 1 0 | 10
 1 0 1 1 | 11
 1 1 0 0 | 12
```

<a id="rst-setting-the-timeouts"></a>

#### Setting the Timeouts

The two jumpers JP2 (1-4) are used to determine the timeout parameters. These two jumpers are normally left open. Refer to the COM9026 Data Sheet for alternate configurations.

<a id="rst-configuring-the-pc500-for-star-or-bus-topology"></a>

#### Configuring the PC500 for Star or Bus Topology

The single jumper labeled JP6 is used to configure the PC500 board for star or bus topology. When the jumper is installed, the board may be used in a star network, when it is removed, the board can be used in a bus topology.

<a id="rst-diagnostic-leds-1"></a>

#### Diagnostic LEDs

Two diagnostic LEDs are visible on the rear bracket of the board. The green LED monitors the network activity: the red one shows the board activity:



```text
Green  | Status               Red      | Status
-------|-------------------   ---------|-------------------
 on    | normal activity      flash/on | data transfer
 blink | reconfiguration      off      | no data transfer;
 off   | defective board or            | incorrect memory or
       | node ID is zero               | I/O address
```

<a id="rst-pc710-8-bit-card"></a>

### PC710 (8-bit card)

> - from J.S. van Oosten &lt;[jvoosten@compiler.tdcnet.nl](<mailto:jvoosten@compiler.tdcnet.nl>)&gt;

Note: this data is gathered by experimenting and looking at info of other cards. However, I'm sure I got 99% of the settings right.

The SMC710 card resembles the PC270 card, but is much more basic (i.e. no LEDs, RJ11 jacks, etc.) and 8 bit. Here's a little drawing:



```text
 _______________________________________
| +---------+  +---------+              |____
| |   S2    |  |   S1    |              |
| +---------+  +---------+              |
|                                       |
|  +===+    __                          |
|  | R |   |  | X-tal                 ###___
|  | O |   |__|                      ####__'|
|  | M |    ||                        ###
|  +===+                                |
|                                       |
|   .. JP1   +----------+               |
|   ..       | big chip |               |
|   ..       |  90C63   |               |
|   ..       |          |               |
|   ..       +----------+               |
 -------                     -----------
        |||||||||||||||||||||
```

The row of jumpers at JP1 actually consists of 8 jumpers, (sometimes labelled) the same as on the PC270, from top to bottom: EXT2, EXT1, ROM, IRQ7, IRQ5, IRQ4, IRQ3, IRQ2 (gee, wonder what they would do? :-) )

S1 and S2 perform the same function as on the PC270, only their numbers are swapped (S1 is the nodeaddress, S2 sets IO- and RAM-address).

I know it works when connected to a PC110 type ARCnet board.

---

<a id="rst-possibly-smc"></a>

## Possibly SMC

<a id="rst-lcs-8830-t-8-and-16-bit-cards"></a>

### LCS-8830(-T) (8 and 16-bit cards)

> - from Mathias Katzer &lt;[mkatzer@HRZ.Uni-Bielefeld.DE](<mailto:mkatzer@HRZ.Uni-Bielefeld.DE>)&gt;
>
> - Marek Michalkiewicz &lt;[marekm@i17linuxb.ists.pwr.wroc.pl](<mailto:marekm@i17linuxb.ists.pwr.wroc.pl>)&gt; says the LCS-8830 is slightly different from LCS-8830-T.  These are 8 bit, BUS only (the JP0 jumper is hardwired), and BNC only.

This is a LCS-8830-T made by SMC, I think ('SMC' only appears on one PLCC, nowhere else, not even on the few Xeroxed sheets from the manual).

SMC ARCnet Board Type LCS-8830-T:



```text
   ------------------------------------
  |                                    |
  |              JP3 88  8 JP2         |
  |       #####      | \               |
  |       #####    ET1 ET2          ###|
  |                              8  ###|
  |  U3   SW 1                  JP0 ###|  Phone Jacks
  |  --                             ###|
  | |  |                               |
  | |  |   SW2                         |
  | |  |                               |
  | |  |  #####                        |
  |  --   #####                       ####  BNC Connector
  |                                   ####
  |   888888 JP1                       |
  |   234567                           |
   --                           -------
     |||||||||||||||||||||||||||
      --------------------------


SW1: DIP-Switches for Station Address
SW2: DIP-Switches for Memory Base and I/O Base addresses

JP0: If closed, internal termination on (default open)
JP1: IRQ Jumpers
JP2: Boot-ROM enabled if closed
JP3: Jumpers for response timeout

U3: Boot-ROM Socket


ET1 ET2     Response Time     Idle Time    Reconfiguration Time

               78                86               840
 X            285               316              1680
     X        563               624              1680
 X   X       1130              1237              1680

(X means closed jumper)

(DIP-Switch downwards means "0")
```

The station address is binary-coded with SW1.

The I/O base address is coded with DIP-Switches 6,7 and 8 of SW2:


<table>
<thead>
<tr>
<th>


Switches

</th>
<th>


Base

</th>
</tr>
<tr>
<th>


678

</th>
<th>


Address

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


000

</td>
<td>


260-26f

</td>
</tr>
<tr>
<td>


100

</td>
<td>


290-29f

</td>
</tr>
<tr>
<td>


010

</td>
<td>


2e0-2ef

</td>
</tr>
<tr>
<td>


110

</td>
<td>


2f0-2ff

</td>
</tr>
<tr>
<td>


001

</td>
<td>


300-30f

</td>
</tr>
<tr>
<td>


101

</td>
<td>


350-35f

</td>
</tr>
<tr>
<td>


011

</td>
<td>


380-38f

</td>
</tr>
<tr>
<td>


111

</td>
<td>


3e0-3ef

</td>
</tr>
</tbody>
</table>

DIP Switches 1-5 of SW2 encode the RAM and ROM Address Range:


<table>
<thead>
<tr>
<th>


Switches

</th>
<th>


RAM

</th>
<th>


ROM

</th>
</tr>
<tr>
<th>


12345

</th>
<th>


Address Range

</th>
<th>


Address Range

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


00000

</td>
<td>


C:0000-C:07ff

</td>
<td>


C:2000-C:3fff

</td>
</tr>
<tr>
<td>


10000

</td>
<td>


C:0800-C:0fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01000

</td>
<td>


C:1000-C:17ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11000

</td>
<td>


C:1800-C:1fff

</td>
<td>




</td>
</tr>
<tr>
<td>


00100

</td>
<td>


C:4000-C:47ff

</td>
<td>


C:6000-C:7fff

</td>
</tr>
<tr>
<td>


10100

</td>
<td>


C:4800-C:4fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01100

</td>
<td>


C:5000-C:57ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11100

</td>
<td>


C:5800-C:5fff

</td>
<td>




</td>
</tr>
<tr>
<td>


00010

</td>
<td>


C:C000-C:C7ff

</td>
<td>


C:E000-C:ffff

</td>
</tr>
<tr>
<td>


10010

</td>
<td>


C:C800-C:Cfff

</td>
<td>




</td>
</tr>
<tr>
<td>


01010

</td>
<td>


C:D000-C:D7ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11010

</td>
<td>


C:D800-C:Dfff

</td>
<td>




</td>
</tr>
<tr>
<td>


00110

</td>
<td>


D:0000-D:07ff

</td>
<td>


D:2000-D:3fff

</td>
</tr>
<tr>
<td>


10110

</td>
<td>


D:0800-D:0fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01110

</td>
<td>


D:1000-D:17ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11110

</td>
<td>


D:1800-D:1fff

</td>
<td>




</td>
</tr>
<tr>
<td>


00001

</td>
<td>


D:4000-D:47ff

</td>
<td>


D:6000-D:7fff

</td>
</tr>
<tr>
<td>


10001

</td>
<td>


D:4800-D:4fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01001

</td>
<td>


D:5000-D:57ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11001

</td>
<td>


D:5800-D:5fff

</td>
<td>




</td>
</tr>
<tr>
<td>


00101

</td>
<td>


D:8000-D:87ff

</td>
<td>


D:A000-D:bfff

</td>
</tr>
<tr>
<td>


10101

</td>
<td>


D:8800-D:8fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01101

</td>
<td>


D:9000-D:97ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11101

</td>
<td>


D:9800-D:9fff

</td>
<td>




</td>
</tr>
<tr>
<td>


00011

</td>
<td>


D:C000-D:c7ff

</td>
<td>


D:E000-D:ffff

</td>
</tr>
<tr>
<td>


10011

</td>
<td>


D:C800-D:cfff

</td>
<td>




</td>
</tr>
<tr>
<td>


01011

</td>
<td>


D:D000-D:d7ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11011

</td>
<td>


D:D800-D:dfff

</td>
<td>




</td>
</tr>
<tr>
<td>


00111

</td>
<td>


E:0000-E:07ff

</td>
<td>


E:2000-E:3fff

</td>
</tr>
<tr>
<td>


10111

</td>
<td>


E:0800-E:0fff

</td>
<td>




</td>
</tr>
<tr>
<td>


01111

</td>
<td>


E:1000-E:17ff

</td>
<td>




</td>
</tr>
<tr>
<td>


11111

</td>
<td>


E:1800-E:1fff

</td>
<td>




</td>
</tr>
</tbody>
</table>

<a id="rst-puredata-corp"></a>

## PureData Corp

<a id="rst-pdi507-8-bit-card"></a>

### PDI507 (8-bit card)

> - from Mark Rejhon &lt;[mdrejhon@magi.com](<mailto:mdrejhon@magi.com>)&gt; (slight modifications by Avery)
>
> - Avery's note: I think PDI508 cards (but definitely NOT PDI508Plus cards) are mostly the same as this.  PDI508Plus cards appear to be mainly software-configured.

Jumpers:

> There is a jumper array at the bottom of the card, near the edge connector.  This array is labelled J1.  They control the IRQs and something else.  Put only one jumper on the IRQ pins.
>
> ETS1, ETS2 are for timing on very long distance networks.  See the more general information near the top of this file.
>
> There is a J2 jumper on two pins.  A jumper should be put on them, since it was already there when I got the card.  I don't know what this jumper is for though.
>
> There is a two-jumper array for J3.  I don't know what it is for, but there were already two jumpers on it when I got the card.  It's a six pin grid in a two-by-three fashion.  The jumpers were configured as follows:
>
>
>
> ```text
>   .-------.
> o | o   o |
>   :-------:    ------> Accessible end of card with connectors
> o | o   o |             in this direction ------->
>   `-------'
> ```

Carl de Billy &lt;[CARL@carainfo.com](<mailto:CARL@carainfo.com>)&gt; explains J3 and J4:

> > J3 Diagram:
> >
> >
> >
> > ```text
> >   .-------.
> > o | o   o |
> >   :-------:    TWIST Technology
> > o | o   o |
> >   `-------'
> >   .-------.
> >   | o   o | o
> >   :-------:    COAX Technology
> >   | o   o | o
> >   `-------'
> > ```
>
> - If using coax cable in a bus topology the J4 jumper must be removed; place it on one pin.
>
> - If using bus topology with twisted pair wiring move the J3 jumpers so they connect the middle pin and the pins closest to the RJ11 Connectors.  Also the J4 jumper must be removed; place it on one pin of J4 jumper for storage.
>
> - If using  star topology with twisted pair wiring move the J3 jumpers so they connect the middle pin and the pins closest to the RJ11 connectors.

DIP Switches:

> The DIP switches accessible on the accessible end of the card while it is installed, is used to set the ARCnet address.  There are 8 switches.  Use an address from 1 to 254
>
>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Switch No.
>
> </th>
> <th>
>
>
> ARCnet address
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 12345678
>
> </th>
> <th>
>
>
>
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 00000000
>
> </td>
> <td>
>
>
> FF      (Don't use this\!)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 00000001
>
> </td>
> <td>
>
>
> FE
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 00000010
>
> </td>
> <td>
>
>
> FD
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11111101
>
> </td>
> <td>
>
>
> 2
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11111110
>
> </td>
> <td>
>
>
> 1
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11111111
>
> </td>
> <td>
>
>
> 0       (Don't use this\!)
>
> </td>
> </tr>
> </tbody>
> </table>
>
> There is another array of eight DIP switches at the top of the card.  There are five labelled MS0-MS4 which seem to control the memory address, and another three labelled IO0-IO2 which seem to control the base I/O address of the card.
>
> This was difficult to test by trial and error, and the I/O addresses are in a weird order.  This was tested by setting the DIP switches, rebooting the computer, and attempting to load ARCETHER at various addresses (mostly between 0x200 and 0x400).  The address that caused the red transmit LED to blink, is the one that I thought works.
>
> Also, the address 0x3D0 seem to have a special meaning, since the ARCETHER packet driver loaded fine, but without the red LED blinking.  I don't know what 0x3D0 is for though.  I recommend using an address of 0x300 since Windows may not like addresses below 0x300.
>
>
> <table>
> <thead>
> <tr>
> <th>
>
>
> IO Switch No.
>
> </th>
> <th>
>
>
> I/O address
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 210
>
> </th>
> <th>
>
>
>
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 111
>
> </td>
> <td>
>
>
> 0x260
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 110
>
> </td>
> <td>
>
>
> 0x290
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 101
>
> </td>
> <td>
>
>
> 0x2E0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 100
>
> </td>
> <td>
>
>
> 0x2F0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 011
>
> </td>
> <td>
>
>
> 0x300
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 010
>
> </td>
> <td>
>
>
> 0x350
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 001
>
> </td>
> <td>
>
>
> 0x380
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 000
>
> </td>
> <td>
>
>
> 0x3E0
>
> </td>
> </tr>
> </tbody>
> </table>
>
> The memory switches set a reserved address space of 0x1000 bytes (0x100 segment units, or 4k).  For example if I set an address of 0xD000, it will use up addresses 0xD000 to 0xD100.
>
> The memory switches were tested by booting using QEMM386 stealth, and using LOADHI to see what address automatically became excluded from the upper memory regions, and then attempting to load ARCETHER using these addresses.
>
> I recommend using an ARCnet memory address of 0xD000, and putting the EMS page frame at 0xC000 while using QEMM stealth mode.  That way, you get contiguous high memory from 0xD100 almost all the way the end of the megabyte.
>
> Memory Switch 0 (MS0) didn't seem to work properly when set to OFF on my card.  It could be malfunctioning on my card.  Experiment with it ON first, and if it doesn't work, set it to OFF.  (It may be a modifier for the 0x200 bit?)
>
>
> <table>
> <thead>
> <tr>
> <th>
>
>
> MS Switch No.
>
> </th>
> <th>
>
>
>
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 43210
>
> </th>
> <th>
>
>
> Memory address
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 00001
>
> </td>
> <td>
>
>
> 0xE100  (guessed - was not detected by QEMM)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 00011
>
> </td>
> <td>
>
>
> 0xE000  (guessed - was not detected by QEMM)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 00101
>
> </td>
> <td>
>
>
> 0xDD00
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 00111
>
> </td>
> <td>
>
>
> 0xDC00
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 01001
>
> </td>
> <td>
>
>
> 0xD900
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 01011
>
> </td>
> <td>
>
>
> 0xD800
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 01101
>
> </td>
> <td>
>
>
> 0xD500
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 01111
>
> </td>
> <td>
>
>
> 0xD400
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10001
>
> </td>
> <td>
>
>
> 0xD100
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10011
>
> </td>
> <td>
>
>
> 0xD000
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10101
>
> </td>
> <td>
>
>
> 0xCD00
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10111
>
> </td>
> <td>
>
>
> 0xCC00
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11001
>
> </td>
> <td>
>
>
> 0xC900 (guessed - crashes tested system)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11011
>
> </td>
> <td>
>
>
> 0xC800 (guessed - crashes tested system)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11101
>
> </td>
> <td>
>
>
> 0xC500 (guessed - crashes tested system)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11111
>
> </td>
> <td>
>
>
> 0xC400 (guessed - crashes tested system)
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-cnet-technology-inc-8-bit-cards"></a>

## CNet Technology Inc. (8-bit cards)

<a id="rst-series-8-bit-cards"></a>

### 120 Series (8-bit cards)

> - from Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt;

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the following Original CNet Manual

> "ARCNET USER'S MANUAL for CN120A CN120AB CN120TP CN120ST CN120SBT P/N:12-01-0007 Revision 3.00"

ARCNET is a registered trademark of the Datapoint Corporation

- P/N 120A   ARCNET 8 bit XT/AT Star

- P/N 120AB  ARCNET 8 bit XT/AT Bus

- P/N 120TP  ARCNET 8 bit XT/AT Twisted Pair

- P/N 120ST  ARCNET 8 bit XT/AT Star, Twisted Pair

- P/N 120SBT ARCNET 8 bit XT/AT Star, Bus, Twisted Pair



```text
 __________________________________________________________________
|                                                                  |
|                                                               ___|
|                                                          LED |___|
|                                                               ___|
|                                                            N |   | ID7
|                                                            o |   | ID6
|                                                            d | S | ID5
|                                                            e | W | ID4
|                     ___________________                    A | 2 | ID3
|                    |                   |                   d |   | ID2
|                    |                   |  1 2 3 4 5 6 7 8  d |   | ID1
|                    |                   | _________________ r |___| ID0
|                    |      90C65        ||       SW1       |  ____|
|  JP 8 7            |                   ||_________________| |    |
|    |o|o|  JP1      |                   |                    | J2 |
|    |o|o|  |oo|     |                   |         JP 1 1 1   |    |
|   ______________   |                   |            0 1 2   |____|
|  |  PROM        |  |___________________|           |o|o|o|  _____|
|  >  SOCKET      |  JP 6 5 4 3 2                    |o|o|o| | J1  |
|  |______________|    |o|o|o|o|o|                   |o|o|o| |_____|
|_____                 |o|o|o|o|o|                   ______________|
      |                                             |
      |_____________________________________________|
```

Legend:



```text
90C65       ARCNET Probe
S1  1-5:    Base Memory Address Select
    6-8:    Base I/O Address Select
S2  1-8:    Node ID Select (ID0-ID7)
JP1     ROM Enable Select
JP2     IRQ2
JP3     IRQ3
JP4     IRQ4
JP5     IRQ5
JP6     IRQ7
JP7/JP8     ET1, ET2 Timeout Parameters
JP10/JP11   Coax / Twisted Pair Select  (CN120ST/SBT only)
JP12        Terminator Select       (CN120AB/ST/SBT only)
J1      BNC RG62/U Connector        (all except CN120TP)
J2      Two 6-position Telephone Jack   (CN120TP/ST/SBT only)
```

Setting one of the switches to Off means "1", On means "0".

<a id="rst-setting-the-node-id-2"></a>

#### Setting the Node ID

The eight switches in SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 1 (ID0) serves as the least significant bit (LSB).

The node ID is the sum of the values of all switches set to "1" These values are:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Switch
>
> </th>
> <th>
>
>
> Label
>
> </th>
> <th>
>
>
> Value
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> ID0
>
> </td>
> <td>
>
>
> 1
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> ID1
>
> </td>
> <td>
>
>
> 2
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> ID2
>
> </td>
> <td>
>
>
> 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> ID3
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> ID4
>
> </td>
> <td>
>
>
> 16
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> ID5
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 7
>
> </td>
> <td>
>
>
> ID6
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 8
>
> </td>
> <td>
>
>
> ID7
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> </tbody>
> </table>

Some Examples:



```text
 Switch         | Hex     | Decimal
8 7 6 5 4 3 2 1 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-2"></a>

#### Setting the I/O Base Address

The last three switches in switch block SW1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 6   7   8  | Address
------------|--------
ON  ON  ON  |  260
OFF ON  ON  |  290
ON  OFF ON  |  2E0  (Manufacturer's default)
OFF OFF ON  |  2F0
ON  ON  OFF |  300
OFF ON  OFF |  350
ON  OFF OFF |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-1"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer (RAM) requires 2K. The base of this buffer can be located in any of eight positions. The address of the Boot Prom is memory base + 8K or memory base + 0x2000. Switches 1-5 of switch block SW1 select the Memory Base address.



```text
 Switch              | Hex RAM | Hex ROM
  1   2   3   4   5  | Address | Address *)
 --------------------|---------|-----------
 ON  ON  ON  ON  ON  |  C0000  |  C2000
 ON  ON  OFF ON  ON  |  C4000  |  C6000
 ON  ON  ON  OFF ON  |  CC000  |  CE000
 ON  ON  OFF OFF ON  |  D0000  |  D2000  (Manufacturer's default)
 ON  ON  ON  ON  OFF |  D4000  |  D6000
 ON  ON  OFF ON  OFF |  D8000  |  DA000
 ON  ON  ON  OFF OFF |  DC000  |  DE000
 ON  ON  OFF OFF OFF |  E0000  |  E2000

*) To enable the Boot ROM install the jumper JP1
```

> [!NOTE]
>
> Since the switches 1 and 2 are always set to ON it may be possible that they can be used to add an offset of 2K, 4K or 6K to the base address, but this feature is not documented in the manual and I haven't tested it yet.

<a id="rst-setting-the-interrupt-line"></a>

#### Setting the Interrupt Line

To select a hardware interrupt level install one (only one\!) of the jumpers JP2, JP3, JP4, JP5, JP6. JP2 is the default:



```text
Jumper | IRQ
-------|-----
  2    |  2
  3    |  3
  4    |  4
  5    |  5
  6    |  7
```

<a id="rst-setting-the-internal-terminator-on-cn120ab-tp-sbt"></a>

#### Setting the Internal Terminator on CN120AB/TP/SBT

The jumper JP12 is used to enable the internal terminator:



```text
                      -----
    0                |  0  |
  -----   ON         |     |  ON
 |  0  |             |  0  |
 |     |  OFF         -----   OFF
 |  0  |                0
  -----
Terminator          Terminator
 disabled            enabled
```

<a id="rst-selecting-the-connector-type-on-cn120st-sbt"></a>

#### Selecting the Connector Type on CN120ST/SBT



```text
 JP10    JP11        JP10    JP11
                     -----   -----
   0       0        |  0  | |  0  |
 -----   -----      |     | |     |
|  0  | |  0  |     |  0  | |  0  |
|     | |     |      -----   -----
|  0  | |  0  |        0       0
 -----   -----
 Coaxial Cable       Twisted Pair Cable
   (Default)
```

<a id="rst-setting-the-timeout-parameters"></a>

#### Setting the Timeout Parameters

The jumpers labeled EXT1 and EXT2 are used to determine the timeout parameters. These two jumpers are normally left open.

<a id="rst-cnet-technology-inc-16-bit-cards"></a>

## CNet Technology Inc. (16-bit cards)

<a id="rst-series-16-bit-cards"></a>

### 160 Series (16-bit cards)

> - from Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt;

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the following Original CNet Manual

> "ARCNET USER'S MANUAL for CN160A CN160AB CN160TP P/N:12-01-0006 Revision 3.00"

ARCNET is a registered trademark of the Datapoint Corporation

- P/N 160A   ARCNET 16 bit XT/AT Star

- P/N 160AB  ARCNET 16 bit XT/AT Bus

- P/N 160TP  ARCNET 16 bit XT/AT Twisted Pair



```text
 ___________________________________________________________________
<                             _________________________          ___|
>               |oo| JP2     |                         |    LED |___|
<               |oo| JP1     |        9026             |    LED |___|
>                            |_________________________|         ___|
<                                                             N |   | ID7
>                                                      1      o |   | ID6
<                                    1 2 3 4 5 6 7 8 9 0      d | S | ID5
>         _______________           _____________________     e | W | ID4
<        |     PROM      |         |         SW1         |    A | 2 | ID3
>        >    SOCKET     |         |_____________________|    d |   | ID2
<        |_______________|          | IO-Base   | MEM   |     d |   | ID1
>                                                             r |___| ID0
<                                                               ____|
>                                                              |    |
<                                                              | J1 |
>                                                              |    |
<                                                              |____|
>                            1 1 1 1                                |
<  3 4 5 6 7      JP     8 9 0 1 2 3                                |
> |o|o|o|o|o|           |o|o|o|o|o|o|                               |
< |o|o|o|o|o| __        |o|o|o|o|o|o|                    ___________|
>            |  |                                       |
<____________|  |_______________________________________|
```

Legend:



```text
9026            ARCNET Probe
SW1 1-6:    Base I/O Address Select
    7-10:   Base Memory Address Select
SW2 1-8:    Node ID Select (ID0-ID7)
JP1/JP2     ET1, ET2 Timeout Parameters
JP3-JP13    Interrupt Select
J1      BNC RG62/U Connector        (CN160A/AB only)
J1      Two 6-position Telephone Jack   (CN160TP only)
LED
```

Setting one of the switches to Off means "1", On means "0".

<a id="rst-setting-the-node-id-3"></a>

#### Setting the Node ID

The eight switches in SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 1 (ID0) serves as the least significant bit (LSB).

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Label | Value
-------|-------|-------
  1    | ID0   |   1
  2    | ID1   |   2
  3    | ID2   |   4
  4    | ID3   |   8
  5    | ID4   |  16
  6    | ID5   |  32
  7    | ID6   |  64
  8    | ID7   | 128
```

Some Examples:



```text
 Switch         | Hex     | Decimal
8 7 6 5 4 3 2 1 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-3"></a>

#### Setting the I/O Base Address

The first six switches in switch block SW1 are used to select the I/O Base address using the following table:



```text
          Switch        | Hex I/O
 1   2   3   4   5   6  | Address
------------------------|--------
OFF ON  ON  OFF OFF ON  |  260
OFF ON  OFF ON  ON  OFF |  290
OFF ON  OFF OFF OFF ON  |  2E0  (Manufacturer's default)
OFF ON  OFF OFF OFF OFF |  2F0
OFF OFF ON  ON  ON  ON  |  300
OFF OFF ON  OFF ON  OFF |  350
OFF OFF OFF ON  ON  ON  |  380
OFF OFF OFF OFF OFF ON  |  3E0
```

- **Note: Other IO-Base addresses seem to be selectable, but only the above**

  combinations are documented.

<a id="rst-setting-the-base-memory-ram-buffer-address-2"></a>

#### Setting the Base Memory (RAM) buffer Address

The switches 7-10 of switch block SW1 are used to select the Memory Base address of the RAM (2K) and the PROM:



```text
Switch          | Hex RAM | Hex ROM
 7   8   9  10  | Address | Address
----------------|---------|-----------
OFF OFF ON  ON  |  C0000  |  C8000
OFF OFF ON  OFF |  D0000  |  D8000 (Default)
OFF OFF OFF ON  |  E0000  |  E8000
```

> [!NOTE]
>
> Other MEM-Base addresses seem to be selectable, but only the above combinations are documented.

<a id="rst-setting-the-interrupt-line-1"></a>

#### Setting the Interrupt Line

To select a hardware interrupt level install one (only one\!) of the jumpers JP3 through JP13 using the following table:



```text
Jumper | IRQ
-------|-----------------
  3    |  14
  4    |  15
  5    |  12
  6    |  11
  7    |  10
  8    |   3
  9    |   4
 10    |   5
 11    |   6
 12    |   7
 13    |   2 (=9) Default!
```

> [!NOTE]
>
> - Do not use JP11=IRQ6, it may conflict with your Floppy Disk Controller
>
> - Use JP3=IRQ14 only, if you don't have an IDE-, MFM-, or RLL- Hard Disk, it may conflict with their controllers

<a id="rst-setting-the-timeout-parameters-1"></a>

### Setting the Timeout Parameters

The jumpers labeled JP1 and JP2 are used to determine the timeout parameters. These two jumpers are normally left open.

<a id="rst-lantech"></a>

## Lantech

<a id="rst-bit-card-unknown-model"></a>

### 8-bit card, unknown model

> - from Vlad Lungu &lt;[vlungu@ugal.ro](<mailto:vlungu@ugal.ro>)&gt; - his e-mail address seemed broken at the time I tried to reach him.  Sorry Vlad, if you didn't get my reply.



```text
________________________________________________________________
|   1         8                                                 |
|   ___________                                               __|
|   |   SW1    |                                         LED |__|
|   |__________|                                                |
|                                                            ___|
|                _____________________                       |S | 8
|                |                   |                       |W |
|                |                   |                       |2 |
|                |                   |                       |__| 1
|                |      UM9065L      |     |o|  JP4         ____|____
|                |                   |     |o|              |  CN    |
|                |                   |                      |________|
|                |                   |                          |
|                |___________________|                          |
|                                                               |
|                                                               |
|      _____________                                            |
|      |            |                                           |
|      |    PROM    |        |ooooo|  JP6                       |
|      |____________|        |ooooo|                            |
|_____________                                             _   _|
             |____________________________________________| |__|
```

UM9065L : ARCnet Controller

SW 1    : Shared Memory Address and I/O Base



```text
ON=0

12345|Memory Address
-----|--------------
00001|  D4000
00010|  CC000
00110|  D0000
01110|  D1000
01101|  D9000
10010|  CC800
10011|  DC800
11110|  D1800
```

It seems that the bits are considered in reverse order.  Also, you must observe that some of those addresses are unusual and I didn't probe them; I used a memory dump in DOS to identify them.  For the 00000 configuration and some others that I didn't write here the card seems to conflict with the video card (an S3 GENDAC). I leave the full decoding of those addresses to you.



```text
      678| I/O Address
      ---|------------
      000|    260
      001|    failed probe
      010|    2E0
      011|    380
      100|    290
      101|    350
      110|    failed probe
      111|    3E0

SW 2  : Node ID (binary coded)

JP 4  : Boot PROM enable   CLOSE - enabled
                           OPEN  - disabled

JP 6  : IRQ set (ONLY ONE jumper on 1-5 for IRQ 2-6)
```

<a id="rst-acer"></a>

## Acer

<a id="rst-bit-card-model-5210-003"></a>

### 8-bit card, Model 5210-003

> - from Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt; using portions of the existing arcnet-hardware file.

This is a 90C26 based card.  Its configuration seems similar to the SMC PC100, but has some additional jumpers I don't know the meaning of.



```text
              __
             |  |
  ___________|__|_________________________
 |         |      |                       |
 |         | BNC  |                       |
 |         |______|                    ___|
 |  _____________________             |___
 | |                     |                |
 | | Hybrid IC           |                |
 | |                     |       o|o J1   |
 | |_____________________|       8|8      |
 |                               8|8 J5   |
 |                               o|o      |
 |                               8|8      |
 |__                             8|8      |
(|__| LED                        o|o      |
 |                               8|8      |
 |                               8|8 J15  |
 |                                        |
 |                    _____               |
 |                   |     |   _____      |
 |                   |     |  |     |  ___|
 |                   |     |  |     | |
 |  _____            | ROM |  | UFS | |
 | |     |           |     |  |     | |
 | |     |     ___   |     |  |     | |
 | |     |    |   |  |__.__|  |__.__| |
 | | NCR |    |XTL|   _____    _____  |
 | |     |    |___|  |     |  |     | |
 | |90C26|           |     |  |     | |
 | |     |           | RAM |  | UFS | |
 | |     | J17 o|o   |     |  |     | |
 | |     | J16 o|o   |     |  |     | |
 | |__.__|           |__.__|  |__.__| |
 |  ___                               |
 | |   |8                             |
 | |SW2|                              |
 | |   |                              |
 | |___|1                             |
 |  ___                               |
 | |   |10           J18 o|o          |
 | |   |                 o|o          |
 | |SW1|                 o|o          |
 | |   |             J21 o|o          |
 | |___|1                             |
 |                                    |
 |____________________________________|
```

Legend:



```text
90C26       ARCNET Chip
XTL         20 MHz Crystal
SW1 1-6     Base I/O Address Select
    7-10    Memory Address Select
SW2 1-8     Node ID Select (ID0-ID7)
J1-J5       IRQ Select
J6-J21      Unknown (Probably extra timeouts & ROM enable ...)
LED1        Activity LED
BNC         Coax connector (STAR ARCnet)
RAM         2k of SRAM
ROM         Boot ROM socket
UFS         Unidentified Flying Sockets
```

<a id="rst-setting-the-node-id-4"></a>

#### Setting the Node ID

The eight switches in SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must not be 0. Switch 1 (ID0) serves as the least significant bit (LSB).

Setting one of the switches to OFF means "1", ON means "0".

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  1    |   1
  2    |   2
  3    |   4
  4    |   8
  5    |  16
  6    |  32
  7    |  64
  8    | 128
```

Don't set this to 0 or 255; these values are reserved.

<a id="rst-setting-the-i-o-base-address-4"></a>

#### Setting the I/O Base Address

The switches 1 to 6 of switch block SW1 are used to select one of 32 possible I/O Base addresses using the following tables:



```text
       | Hex
Switch | Value
-------|-------
  1    | 200
  2    | 100
  3    |  80
  4    |  40
  5    |  20
  6    |  10
```

The I/O address is sum of all switches set to "1". Remember that the I/O address space below 0x200 is RESERVED for mainboard, so switch 1 should be ALWAYS SET TO OFF.

<a id="rst-setting-the-base-memory-ram-buffer-address-3"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer (RAM) requires 2K. The base of this buffer can be located in any of sixteen positions. However, the addresses below A0000 are likely to cause system hang because there's main RAM.

Jumpers 7-10 of switch block SW1 select the Memory Base address:



```text
Switch          | Hex RAM
 7   8   9  10  | Address
----------------|---------
OFF OFF OFF OFF |  F0000 (conflicts with main BIOS)
OFF OFF OFF ON  |  E0000
OFF OFF ON  OFF |  D0000
OFF OFF ON  ON  |  C0000 (conflicts with video BIOS)
OFF ON  OFF OFF |  B0000 (conflicts with mono video)
OFF ON  OFF ON  |  A0000 (conflicts with graphics)
```

<a id="rst-setting-the-interrupt-line-2"></a>

#### Setting the Interrupt Line

Jumpers 1-5 of the jumper block J1 control the IRQ level. ON means shorted, OFF means open:



```text
 Jumper              |  IRQ
 1   2   3   4   5   |
----------------------------
 ON  OFF OFF OFF OFF |  7
 OFF ON  OFF OFF OFF |  5
 OFF OFF ON  OFF OFF |  4
 OFF OFF OFF ON  OFF |  3
 OFF OFF OFF OFF ON  |  2
```

<a id="rst-unknown-jumpers-sockets"></a>

#### Unknown jumpers &amp; sockets

I know nothing about these. I just guess that J16&amp;J17 are timeout jumpers and maybe one of J18-J21 selects ROM. Also J6-J10 and J11-J15 are connecting IRQ2-7 to some pins on the UFSs. I can't guess the purpose.

<a id="rst-datapoint"></a>

## Datapoint?

<a id="rst-lan-arc-8-an-8-bit-card"></a>

### LAN-ARC-8, an 8-bit card

> - from Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;

This is another SMC 90C65-based ARCnet card. I couldn't identify the manufacturer, but it might be DataPoint, because the card has the original arcNet logo in its upper right corner.



```text
 _______________________________________________________
|                         _________                     |
|                        |   SW2   | ON      arcNet     |
|                        |_________| OFF             ___|
|  _____________         1 ______  8                |   | 8
| |             | SW1     | XTAL | ____________     | S |
| > RAM (2k)    |         |______||            |    | W |
| |_____________|                 |      H     |    | 3 |
|                        _________|_____ y     |    |___| 1
|  _________            |         |     |b     |        |
| |_________|           |         |     |r     |        |
|                       |     SMC |     |i     |        |
|                       |    90C65|     |d     |        |
|  _________            |         |     |      |        |
| |   SW1   | ON        |         |     |I     |        |
| |_________| OFF       |_________|_____/C     |   _____|
|  1       8                      |            |  |     |___
|  ______________                 |            |  | BNC |___|
| |              |                |____________|  |_____|
| > EPROM SOCKET |              _____________           |
| |______________|             |_____________|          |
|                                         ______________|
|                                        |
|________________________________________|
```

Legend:



```text
90C65       ARCNET Chip
SW1 1-5:    Base Memory Address Select
    6-8:    Base I/O Address Select
SW2 1-8:    Node ID Select
SW3 1-5:    IRQ Select
    6-7:    Extra Timeout
    8  :    ROM Enable
BNC         Coax connector
XTAL        20 MHz Crystal
```

<a id="rst-setting-the-node-id-5"></a>

#### Setting the Node ID

The eight switches in SW3 are used to set the node ID. Each node attached to the network must have an unique node ID which must not be 0. Switch 1 serves as the least significant bit (LSB).

Setting one of the switches to Off means "1", On means "0".

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  1    |   1
  2    |   2
  3    |   4
  4    |   8
  5    |  16
  6    |  32
  7    |  64
  8    | 128
```

<a id="rst-setting-the-i-o-base-address-5"></a>

#### Setting the I/O Base Address

The last three switches in switch block SW1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 6   7   8  | Address
------------|--------
ON  ON  ON  |  260
OFF ON  ON  |  290
ON  OFF ON  |  2E0  (Manufacturer's default)
OFF OFF ON  |  2F0
ON  ON  OFF |  300
OFF ON  OFF |  350
ON  OFF OFF |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-4"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer (RAM) requires 2K. The base of this buffer can be located in any of eight positions. The address of the Boot Prom is memory base + 0x2000.

Jumpers 3-5 of switch block SW1 select the Memory Base address.



```text
 Switch              | Hex RAM | Hex ROM
  1   2   3   4   5  | Address | Address *)
 --------------------|---------|-----------
 ON  ON  ON  ON  ON  |  C0000  |  C2000
 ON  ON  OFF ON  ON  |  C4000  |  C6000
 ON  ON  ON  OFF ON  |  CC000  |  CE000
 ON  ON  OFF OFF ON  |  D0000  |  D2000  (Manufacturer's default)
 ON  ON  ON  ON  OFF |  D4000  |  D6000
 ON  ON  OFF ON  OFF |  D8000  |  DA000
 ON  ON  ON  OFF OFF |  DC000  |  DE000
 ON  ON  OFF OFF OFF |  E0000  |  E2000

*) To enable the Boot ROM set the switch 8 of switch block SW3 to position ON.
```

The switches 1 and 2 probably add 0x0800 and 0x1000 to RAM base address.

<a id="rst-setting-the-interrupt-line-3"></a>

#### Setting the Interrupt Line

Switches 1-5 of the switch block SW3 control the IRQ level:



```text
 Jumper              |  IRQ
 1   2   3   4   5   |
----------------------------
 ON  OFF OFF OFF OFF |  3
 OFF ON  OFF OFF OFF |  4
 OFF OFF ON  OFF OFF |  5
 OFF OFF OFF ON  OFF |  7
 OFF OFF OFF OFF ON  |  2
```

<a id="rst-setting-the-timeout-parameters-2"></a>

#### Setting the Timeout Parameters

The switches 6-7 of the switch block SW3 are used to determine the timeout parameters.  These two switches are normally left in the OFF position.

<a id="rst-topware"></a>

## Topware

<a id="rst-bit-card-ta-arc-10"></a>

### 8-bit card, TA-ARC/10

> - from Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;

This is another very similar 90C65 card. Most of the switches and jumpers are the same as on other clones.



```text
 _____________________________________________________________________
|  ___________   |                         |            ______        |
| |SW2 NODE ID|  |                         |           | XTAL |       |
| |___________|  |  Hybrid IC              |           |______|       |
|  ___________   |                         |                        __|
| |SW1 MEM+I/O|  |_________________________|                   LED1|__|)
| |___________|           1 2                                         |
|                     J3 |o|o| TIMEOUT                          ______|
|     ______________     |o|o|                                 |      |
|    |              |  ___________________                     | RJ   |
|    > EPROM SOCKET | |                   \                    |------|
|J2  |______________| |                    |                   |      |
||o|                  |                    |                   |______|
||o| ROM ENABLE       |        SMC         |    _________             |
|     _____________   |       90C65        |   |_________|       _____|
|    |             |  |                    |                    |     |___
|    > RAM (2k)    |  |                    |                    | BNC |___|
|    |_____________|  |                    |                    |_____|
|                     |____________________|                          |
| ________ IRQ 2 3 4 5 7                  ___________                 |
||________|   |o|o|o|o|o|                |___________|                |
|________   J1|o|o|o|o|o|                               ______________|
         |                                             |
         |_____________________________________________|
```

Legend:



```text
90C65       ARCNET Chip
XTAL        20 MHz Crystal
SW1 1-5     Base Memory Address Select
    6-8     Base I/O Address Select
SW2 1-8     Node ID Select (ID0-ID7)
J1          IRQ Select
J2          ROM Enable
J3          Extra Timeout
LED1        Activity LED
BNC         Coax connector (BUS ARCnet)
RJ          Twisted Pair Connector (daisy chain)
```

<a id="rst-setting-the-node-id-6"></a>

#### Setting the Node ID

The eight switches in SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must not be 0.  Switch 1 (ID0) serves as the least significant bit (LSB).

Setting one of the switches to Off means "1", On means "0".

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Label | Value
-------|-------|-------
  1    | ID0   |   1
  2    | ID1   |   2
  3    | ID2   |   4
  4    | ID3   |   8
  5    | ID4   |  16
  6    | ID5   |  32
  7    | ID6   |  64
  8    | ID7   | 128
```

<a id="rst-setting-the-i-o-base-address-6"></a>

#### Setting the I/O Base Address

The last three switches in switch block SW1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 6   7   8  | Address
------------|--------
ON  ON  ON  |  260  (Manufacturer's default)
OFF ON  ON  |  290
ON  OFF ON  |  2E0
OFF OFF ON  |  2F0
ON  ON  OFF |  300
OFF ON  OFF |  350
ON  OFF OFF |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-5"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer (RAM) requires 2K. The base of this buffer can be located in any of eight positions. The address of the Boot Prom is memory base + 0x2000.

Jumpers 3-5 of switch block SW1 select the Memory Base address.



```text
Switch              | Hex RAM | Hex ROM
 1   2   3   4   5  | Address | Address *)
--------------------|---------|-----------
ON  ON  ON  ON  ON  |  C0000  |  C2000
ON  ON  OFF ON  ON  |  C4000  |  C6000  (Manufacturer's default)
ON  ON  ON  OFF ON  |  CC000  |  CE000
ON  ON  OFF OFF ON  |  D0000  |  D2000
ON  ON  ON  ON  OFF |  D4000  |  D6000
ON  ON  OFF ON  OFF |  D8000  |  DA000
ON  ON  ON  OFF OFF |  DC000  |  DE000
ON  ON  OFF OFF OFF |  E0000  |  E2000

*) To enable the Boot ROM short the jumper J2.
```

The jumpers 1 and 2 probably add 0x0800 and 0x1000 to RAM address.

<a id="rst-setting-the-interrupt-line-4"></a>

#### Setting the Interrupt Line

Jumpers 1-5 of the jumper block J1 control the IRQ level.  ON means shorted, OFF means open:



```text
 Jumper              |  IRQ
 1   2   3   4   5   |
----------------------------
 ON  OFF OFF OFF OFF |  2
 OFF ON  OFF OFF OFF |  3
 OFF OFF ON  OFF OFF |  4
 OFF OFF OFF ON  OFF |  5
 OFF OFF OFF OFF ON  |  7
```

<a id="rst-setting-the-timeout-parameters-3"></a>

#### Setting the Timeout Parameters

The jumpers J3 are used to set the timeout parameters. These two jumpers are normally left open.

<a id="rst-thomas-conrad"></a>

## Thomas-Conrad

<a id="rst-model-500-6242-0097-rev-a-8-bit-card"></a>

### Model \#500-6242-0097 REV A (8-bit card)

> - from Lars Karlsson &lt;[100617.3473@compuserve.com](<mailto:100617.3473@compuserve.com>)&gt;



```text
  ________________________________________________________
|          ________   ________                           |_____
|         |........| |........|                            |
|         |________| |________|                         ___|
|            SW 3       SW 1                           |   |
|         Base I/O   Base Addr.                Station |   |
|                                              address |   |
|    ______                                    switch  |   |
|   |      |                                           |   |
|   |      |                                           |___|
|   |      |                                 ______        |___._
|   |______|                                |______|         ____| BNC
|                                            Jumper-        _____| Connector
|   Main chip                                block  _    __|   '
|                                                  | |  |    RJ Connector
|                                                  |_|  |    with 110 Ohm
|                                                       |__  Terminator
|    ___________                                         __|
|   |...........|                                       |    RJ-jack
|   |...........|    _____                              |    (unused)
|   |___________|   |_____|                             |__
|  Boot PROM socket IRQ-jumpers                            |_  Diagnostic
|________                                       __          _| LED (red)
         | | | | | | | | | | | | | | | | | | | |  |        |
         | | | | | | | | | | | | | | | | | | | |  |________|
                                                           |
                                                           |
```

And here are the settings for some of the switches and jumpers on the cards.



```text
          I/O

         1 2 3 4 5 6 7 8

2E0----- 0 0 0 1 0 0 0 1
2F0----- 0 0 0 1 0 0 0 0
300----- 0 0 0 0 1 1 1 1
350----- 0 0 0 0 1 1 1 0
```

"0" in the above example means switch is off "1" means that it is on.



```text
    ShMem address.

      1 2 3 4 5 6 7 8

CX00--0 0 1 1 | |   |
DX00--0 0 1 0       |
X000--------- 1 1   |
X400--------- 1 0   |
X800--------- 0 1   |
XC00--------- 0 0
ENHANCED----------- 1
COMPATIBLE--------- 0
```



```text
    IRQ


3 4 5 7 2
. . . . .
. . . . .
```

There is a DIP-switch with 8 switches, used to set the shared memory address to be used. The first 6 switches set the address, the 7th doesn't have any function, and the 8th switch is used to select "compatible" or "enhanced". When I got my two cards, one of them had this switch set to "enhanced". That card didn't work at all, it wasn't even recognized by the driver. The other card had this switch set to "compatible" and it behaved absolutely normally. I guess that the switch on one of the cards, must have been changed accidentally when the card was taken out of its former host. The question remains unanswered, what is the purpose of the "enhanced" position?

\[Avery's note: "enhanced" probably either disables shared memory (use IO ports instead) or disables IO ports (use memory addresses instead).  This varies by the type of card involved.  I fail to see how either of these enhance anything.  Send me more detailed information about this mode, or just use "compatible" mode instead.\]

<a id="rst-waterloo-microsystems-inc"></a>

## Waterloo Microsystems Inc. ??

<a id="rst-bit-card-c-1985"></a>

### 8-bit card (C) 1985

> - from Robert Michael Best &lt;[rmb117@cs.usask.ca](<mailto:rmb117@cs.usask.ca>)&gt;

\[Avery's note: these don't work with my driver for some reason.  These cards SEEM to have settings similar to the PDI508Plus, which is software-configured and doesn't work with my driver either.  The "Waterloo chip" is a boot PROM, probably designed specifically for the University of Waterloo.  If you have any further information about this card, please e-mail me.\]

The probe has not been able to detect the card on any of the J2 settings, and I tried them again with the "Waterloo" chip removed.



```text
 _____________________________________________________________________
| \/  \/              ___  __ __                                      |
| C4  C4     |^|     | M ||  ^  ||^|                                  |
| --  --     |_|     | 5 ||     || | C3                               |
| \/  \/      C10    |___||     ||_|                                  |
| C4  C4             _  _ |     |                 ??                  |
| --  --            | \/ ||     |                                     |
|                   |    ||     |                                     |
|                   |    ||  C1 |                                     |
|                   |    ||     |  \/                            _____|
|                   | C6 ||     |  C9                           |     |___
|                   |    ||     |  --                           | BNC |___|
|                   |    ||     |          >C7|                 |_____|
|                   |    ||     |                                     |
| __ __             |____||_____|       1 2 3     6                   |
||  ^  |     >C4|                      |o|o|o|o|o|o| J2    >C4|       |
||     |                               |o|o|o|o|o|o|                  |
|| C2  |     >C4|                                          >C4|       |
||     |                                   >C8|                       |
||     |       2 3 4 5 6 7  IRQ                            >C4|       |
||_____|      |o|o|o|o|o|o| J3                                        |
|_______      |o|o|o|o|o|o|                            _______________|
        |                                             |
        |_____________________________________________|

C1 -- "COM9026
       SMC 8638"
      In a chip socket.

C2 -- "@Copyright
       Waterloo Microsystems Inc.
       1985"
      In a chip Socket with info printed on a label covering a round window
      showing the circuit inside. (The window indicates it is an EPROM chip.)

C3 -- "COM9032
       SMC 8643"
      In a chip socket.

C4 -- "74LS"
      9 total no sockets.

M5 -- "50006-136
       20.000000 MHZ
       MTQ-T1-S3
       0 M-TRON 86-40"
      Metallic case with 4 pins, no socket.

C6 -- "MOSTEK@TC8643
       MK6116N-20
       MALAYSIA"
      No socket.

C7 -- No stamp or label but in a 20 pin chip socket.

C8 -- "PAL10L8CN
       8623"
      In a 20 pin socket.

C9 -- "PAl16R4A-2CN
       8641"
      In a 20 pin socket.

C10 -- "M8640
          NMC
        9306N"
       In an 8 pin socket.

?? -- Some components on a smaller board and attached with 20 pins all
      along the side closest to the BNC connector.  The are coated in a dark
      resin.
```

On the board there are two jumper banks labeled J2 and J3. The manufacturer didn't put a J1 on the board. The two boards I have both came with a jumper box for each bank.



```text
J2 -- Numbered 1 2 3 4 5 6.
      4 and 5 are not stamped due to solder points.

J3 -- IRQ 2 3 4 5 6 7
```

The board itself has a maple leaf stamped just above the irq jumpers and "-2 46-86" beside C2. Between C1 and C6 "ASS 'Y 300163" and "@1986 CORMAN CUSTOM ELECTRONICS CORP." stamped just below the BNC connector. Below that "MADE IN CANADA"

<a id="rst-no-name"></a>

## No Name

<a id="rst-bit-cards-16-bit-cards"></a>

### 8-bit cards, 16-bit cards

> - from Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt;

I have named this ARCnet card "NONAME", since there is no name of any manufacturer on the Installation manual nor on the shipping box. The only hint to the existence of a manufacturer at all is written in copper, it is "Made in Taiwan"

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the Original

> "ARCnet Installation Manual"



```text
 ________________________________________________________________
| |STAR| BUS| T/P|                                               |
| |____|____|____|                                               |
|                            _____________________               |
|                           |                     |              |
|                           |                     |              |
|                           |                     |              |
|                           |        SMC          |              |
|                           |                     |              |
|                           |       COM90C65      |              |
|                           |                     |              |
|                           |                     |              |
|                           |__________-__________|              |
|                                                           _____|
|      _______________                                     |  CN |
|     | PROM          |                                    |_____|
|     > SOCKET        |                                          |
|     |_______________|         1 2 3 4 5 6 7 8  1 2 3 4 5 6 7 8 |
|                               _______________  _______________ |
|           |o|o|o|o|o|o|o|o|  |      SW1      ||      SW2      ||
|           |o|o|o|o|o|o|o|o|  |_______________||_______________||
|___         2 3 4 5 7 E E R        Node ID       IOB__|__MEM____|
    |        \ IRQ   / T T O                      |
    |__________________1_2_M______________________|
```

Legend:



```text
COM90C65:       ARCnet Probe
S1  1-8:    Node ID Select
S2  1-3:    I/O Base Address Select
    4-6:    Memory Base Address Select
    7-8:    RAM Offset Select
ET1, ET2    Extended Timeout Select
ROM     ROM Enable Select
CN              RG62 Coax Connector
STAR| BUS | T/P Three fields for placing a sign (colored circle)
                indicating the topology of the card
```

Setting one of the switches to Off means "1", On means "0".

<a id="rst-setting-the-node-id-7"></a>

#### Setting the Node ID

The eight switches in group SW1 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 8 serves as the least significant bit (LSB).

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  8    |   1
  7    |   2
  6    |   4
  5    |   8
  4    |  16
  3    |  32
  2    |  64
  1    | 128
```

Some Examples:



```text
 Switch         | Hex     | Decimal
1 2 3 4 5 6 7 8 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-7"></a>

#### Setting the I/O Base Address

The first three switches in switch group SW2 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 1   2   3  | Address
------------|--------
ON  ON  ON  |  260
ON  ON  OFF |  290
ON  OFF ON  |  2E0  (Manufacturer's default)
ON  OFF OFF |  2F0
OFF ON  ON  |  300
OFF ON  OFF |  350
OFF OFF ON  |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-6"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer requires 2K of a 16K block of RAM. The base of this 16K block can be located in any of eight positions. Switches 4-6 of switch group SW2 select the Base of the 16K block. Within that 16K address space, the buffer may be assigned any one of four positions, determined by the offset, switches 7 and 8 of group SW2.



```text
Switch     | Hex RAM | Hex ROM
4 5 6  7 8 | Address | Address *)
-----------|---------|-----------
0 0 0  0 0 |  C0000  |  C2000
0 0 0  0 1 |  C0800  |  C2000
0 0 0  1 0 |  C1000  |  C2000
0 0 0  1 1 |  C1800  |  C2000
           |         |
0 0 1  0 0 |  C4000  |  C6000
0 0 1  0 1 |  C4800  |  C6000
0 0 1  1 0 |  C5000  |  C6000
0 0 1  1 1 |  C5800  |  C6000
           |         |
0 1 0  0 0 |  CC000  |  CE000
0 1 0  0 1 |  CC800  |  CE000
0 1 0  1 0 |  CD000  |  CE000
0 1 0  1 1 |  CD800  |  CE000
           |         |
0 1 1  0 0 |  D0000  |  D2000  (Manufacturer's default)
0 1 1  0 1 |  D0800  |  D2000
0 1 1  1 0 |  D1000  |  D2000
0 1 1  1 1 |  D1800  |  D2000
           |         |
1 0 0  0 0 |  D4000  |  D6000
1 0 0  0 1 |  D4800  |  D6000
1 0 0  1 0 |  D5000  |  D6000
1 0 0  1 1 |  D5800  |  D6000
           |         |
1 0 1  0 0 |  D8000  |  DA000
1 0 1  0 1 |  D8800  |  DA000
1 0 1  1 0 |  D9000  |  DA000
1 0 1  1 1 |  D9800  |  DA000
           |         |
1 1 0  0 0 |  DC000  |  DE000
1 1 0  0 1 |  DC800  |  DE000
1 1 0  1 0 |  DD000  |  DE000
1 1 0  1 1 |  DD800  |  DE000
           |         |
1 1 1  0 0 |  E0000  |  E2000
1 1 1  0 1 |  E0800  |  E2000
1 1 1  1 0 |  E1000  |  E2000
1 1 1  1 1 |  E1800  |  E2000

*) To enable the 8K Boot PROM install the jumper ROM.
   The default is jumper ROM not installed.
```

<a id="rst-setting-interrupt-request-lines-irq"></a>

#### Setting Interrupt Request Lines (IRQ)

To select a hardware interrupt level set one (only one\!) of the jumpers IRQ2, IRQ3, IRQ4, IRQ5 or IRQ7. The manufacturer's default is IRQ2.

<a id="rst-setting-the-timeouts-1"></a>

#### Setting the Timeouts

The two jumpers labeled ET1 and ET2 are used to determine the timeout parameters (response and reconfiguration time). Every node in a network must be set to the same timeout values.



```text
ET1 ET2 | Response Time (us) | Reconfiguration Time (ms)
--------|--------------------|--------------------------
Off Off |        78          |          840   (Default)
Off On  |       285          |         1680
On  Off |       563          |         1680
On  On  |      1130          |         1680
```

On means jumper installed, Off means jumper not installed

<a id="rst-bit-arcnet"></a>

### 16-BIT ARCNET

The manual of my 8-Bit NONAME ARCnet Card contains another description of a 16-Bit Coax / Twisted Pair Card. This description is incomplete, because there are missing two pages in the manual booklet. (The table of contents reports pages ... 2-9, 2-11, 2-12, 3-1, ... but inside the booklet there is a different way of counting ... 2-9, 2-10, A-1, (empty page), 3-1, ..., 3-18, A-1 (again), A-2) Also the picture of the board layout is not as good as the picture of 8-Bit card, because there isn't any letter like "SW1" written to the picture.

Should somebody have such a board, please feel free to complete this description or to send a mail to me\!

This description has been written by Juergen Seifert &lt;[seifert@htwm.de](<mailto:seifert@htwm.de>)&gt; using information from the Original

> "ARCnet Installation Manual"



```text
 ___________________________________________________________________
<                    _________________  _________________           |
>                   |       SW?       ||      SW?        |          |
<                   |_________________||_________________|          |
>                       ____________________                        |
<                      |                    |                       |
>                      |                    |                       |
<                      |                    |                       |
>                      |                    |                       |
<                      |                    |                       |
>                      |                    |                       |
<                      |                    |                       |
>                      |____________________|                       |
<                                                               ____|
>                       ____________________                   |    |
<                      |                    |                  | J1 |
>                      |                    <                  |    |
<                      |____________________|  ? ? ? ? ? ?     |____|
>                                             |o|o|o|o|o|o|         |
<                                             |o|o|o|o|o|o|         |
>                                                                   |
<             __                                         ___________|
>            |  |                                       |
<____________|  |_______________________________________|
```

Setting one of the switches to Off means "1", On means "0".

<a id="rst-setting-the-node-id-8"></a>

#### Setting the Node ID

The eight switches in group SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 8 serves as the least significant bit (LSB).

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  8    |   1
  7    |   2
  6    |   4
  5    |   8
  4    |  16
  3    |  32
  2    |  64
  1    | 128
```

Some Examples:



```text
 Switch         | Hex     | Decimal
1 2 3 4 5 6 7 8 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-8"></a>

#### Setting the I/O Base Address

The first three switches in switch group SW1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 3   2   1  | Address
------------|--------
ON  ON  ON  |  260
ON  ON  OFF |  290
ON  OFF ON  |  2E0  (Manufacturer's default)
ON  OFF OFF |  2F0
OFF ON  ON  |  300
OFF ON  OFF |  350
OFF OFF ON  |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-7"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer requires 2K of a 16K block of RAM. The base of this 16K block can be located in any of eight positions. Switches 6-8 of switch group SW1 select the Base of the 16K block. Within that 16K address space, the buffer may be assigned any one of four positions, determined by the offset, switches 4 and 5 of group SW1:



```text
Switch     | Hex RAM | Hex ROM
8 7 6  5 4 | Address | Address
-----------|---------|-----------
0 0 0  0 0 |  C0000  |  C2000
0 0 0  0 1 |  C0800  |  C2000
0 0 0  1 0 |  C1000  |  C2000
0 0 0  1 1 |  C1800  |  C2000
           |         |
0 0 1  0 0 |  C4000  |  C6000
0 0 1  0 1 |  C4800  |  C6000
0 0 1  1 0 |  C5000  |  C6000
0 0 1  1 1 |  C5800  |  C6000
           |         |
0 1 0  0 0 |  CC000  |  CE000
0 1 0  0 1 |  CC800  |  CE000
0 1 0  1 0 |  CD000  |  CE000
0 1 0  1 1 |  CD800  |  CE000
           |         |
0 1 1  0 0 |  D0000  |  D2000  (Manufacturer's default)
0 1 1  0 1 |  D0800  |  D2000
0 1 1  1 0 |  D1000  |  D2000
0 1 1  1 1 |  D1800  |  D2000
           |         |
1 0 0  0 0 |  D4000  |  D6000
1 0 0  0 1 |  D4800  |  D6000
1 0 0  1 0 |  D5000  |  D6000
1 0 0  1 1 |  D5800  |  D6000
           |         |
1 0 1  0 0 |  D8000  |  DA000
1 0 1  0 1 |  D8800  |  DA000
1 0 1  1 0 |  D9000  |  DA000
1 0 1  1 1 |  D9800  |  DA000
           |         |
1 1 0  0 0 |  DC000  |  DE000
1 1 0  0 1 |  DC800  |  DE000
1 1 0  1 0 |  DD000  |  DE000
1 1 0  1 1 |  DD800  |  DE000
           |         |
1 1 1  0 0 |  E0000  |  E2000
1 1 1  0 1 |  E0800  |  E2000
1 1 1  1 0 |  E1000  |  E2000
1 1 1  1 1 |  E1800  |  E2000
```

<a id="rst-setting-interrupt-request-lines-irq-1"></a>

#### Setting Interrupt Request Lines (IRQ)

---

<a id="rst-setting-the-timeouts-2"></a>

#### Setting the Timeouts

---

<a id="rst-bit-cards-made-in-taiwan-r-o-c"></a>

### 8-bit cards ("Made in Taiwan R.O.C.")

> - from Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;

I have named this ARCnet card "NONAME", since I got only the card with no manual at all and the only text identifying the manufacturer is "MADE IN TAIWAN R.O.C" printed on the card.



```text
 ____________________________________________________________
|                 1 2 3 4 5 6 7 8                            |
| |o|o| JP1       o|o|o|o|o|o|o|o| ON                        |
|  +              o|o|o|o|o|o|o|o|                        ___|
|  _____________  o|o|o|o|o|o|o|o| OFF         _____     |   | ID7
| |             | SW1                         |     |    |   | ID6
| > RAM (2k)    |        ____________________ |  H  |    | S | ID5
| |_____________|       |                    ||  y  |    | W | ID4
|                       |                    ||  b  |    | 2 | ID3
|                       |                    ||  r  |    |   | ID2
|                       |                    ||  i  |    |   | ID1
|                       |       90C65        ||  d  |    |___| ID0
|      SW3              |                    ||     |        |
| |o|o|o|o|o|o|o|o| ON  |                    ||  I  |        |
| |o|o|o|o|o|o|o|o|     |                    ||  C  |        |
| |o|o|o|o|o|o|o|o| OFF |____________________||     |   _____|
|  1 2 3 4 5 6 7 8                            |     |  |     |___
|  ______________                             |     |  | BNC |___|
| |              |                            |_____|  |_____|
| > EPROM SOCKET |                                           |
| |______________|                                           |
|                                              ______________|
|                                             |
|_____________________________________________|
```

Legend:



```text
90C65       ARCNET Chip
SW1 1-5:    Base Memory Address Select
    6-8:    Base I/O Address Select
SW2 1-8:    Node ID Select (ID0-ID7)
SW3 1-5:    IRQ Select
    6-7:    Extra Timeout
    8  :    ROM Enable
JP1         Led connector
BNC         Coax connector
```

Although the jumpers SW1 and SW3 are marked SW, not JP, they are jumpers, not switches.

Setting the jumpers to ON means connecting the upper two pins, off the bottom two - or - in case of IRQ setting, connecting none of them at all.

<a id="rst-setting-the-node-id-9"></a>

#### Setting the Node ID

The eight switches in SW2 are used to set the node ID. Each node attached to the network must have an unique node ID which must not be 0. Switch 1 (ID0) serves as the least significant bit (LSB).

Setting one of the switches to Off means "1", On means "0".

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Label | Value
-------|-------|-------
  1    | ID0   |   1
  2    | ID1   |   2
  3    | ID2   |   4
  4    | ID3   |   8
  5    | ID4   |  16
  6    | ID5   |  32
  7    | ID6   |  64
  8    | ID7   | 128
```

Some Examples:



```text
 Switch         | Hex     | Decimal
8 7 6 5 4 3 2 1 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed
0 0 0 0 0 0 0 1 |    1    |    1
0 0 0 0 0 0 1 0 |    2    |    2
0 0 0 0 0 0 1 1 |    3    |    3
    . . .       |         |
0 1 0 1 0 1 0 1 |   55    |   85
    . . .       |         |
1 0 1 0 1 0 1 0 |   AA    |  170
    . . .       |         |
1 1 1 1 1 1 0 1 |   FD    |  253
1 1 1 1 1 1 1 0 |   FE    |  254
1 1 1 1 1 1 1 1 |   FF    |  255
```

<a id="rst-setting-the-i-o-base-address-9"></a>

#### Setting the I/O Base Address

The last three switches in switch block SW1 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch      | Hex I/O
 6   7   8  | Address
------------|--------
ON  ON  ON  |  260
OFF ON  ON  |  290
ON  OFF ON  |  2E0  (Manufacturer's default)
OFF OFF ON  |  2F0
ON  ON  OFF |  300
OFF ON  OFF |  350
ON  OFF OFF |  380
OFF OFF OFF |  3E0
```

<a id="rst-setting-the-base-memory-ram-buffer-address-8"></a>

#### Setting the Base Memory (RAM) buffer Address

The memory buffer (RAM) requires 2K. The base of this buffer can be located in any of eight positions. The address of the Boot Prom is memory base + 0x2000.

Jumpers 3-5 of jumper block SW1 select the Memory Base address.



```text
 Switch              | Hex RAM | Hex ROM
  1   2   3   4   5  | Address | Address *)
 --------------------|---------|-----------
 ON  ON  ON  ON  ON  |  C0000  |  C2000
 ON  ON  OFF ON  ON  |  C4000  |  C6000
 ON  ON  ON  OFF ON  |  CC000  |  CE000
 ON  ON  OFF OFF ON  |  D0000  |  D2000  (Manufacturer's default)
 ON  ON  ON  ON  OFF |  D4000  |  D6000
 ON  ON  OFF ON  OFF |  D8000  |  DA000
 ON  ON  ON  OFF OFF |  DC000  |  DE000
 ON  ON  OFF OFF OFF |  E0000  |  E2000

*) To enable the Boot ROM set the jumper 8 of jumper block SW3 to position ON.
```

The jumpers 1 and 2 probably add 0x0800, 0x1000 and 0x1800 to RAM adders.

<a id="rst-setting-the-interrupt-line-5"></a>

#### Setting the Interrupt Line

Jumpers 1-5 of the jumper block SW3 control the IRQ level:



```text
 Jumper              |  IRQ
 1   2   3   4   5   |
----------------------------
 ON  OFF OFF OFF OFF |  2
 OFF ON  OFF OFF OFF |  3
 OFF OFF ON  OFF OFF |  4
 OFF OFF OFF ON  OFF |  5
 OFF OFF OFF OFF ON  |  7
```

<a id="rst-setting-the-timeout-parameters-4"></a>

#### Setting the Timeout Parameters

The jumpers 6-7 of the jumper block SW3 are used to determine the timeout parameters. These two jumpers are normally left in the OFF position.

<a id="rst-generic-model-9058"></a>

### (Generic Model 9058)

> - from Andrew J. Kroll &lt;[ag784@freenet.buffalo.edu](<mailto:ag784@freenet.buffalo.edu>)&gt;
>
> - Sorry this sat in my to-do box for so long, Andrew\! (yikes - over a year\!)



```text
                                                                   _____
                                                                  |    <
                                                                  | .---'
 ________________________________________________________________ | |
|                           |     SW2     |                      |  |
|   ___________             |_____________|                      |  |
|  |           |              1 2 3 4 5 6                     ___|  |
|  >  6116 RAM |         _________                         8 |   |  |
|  |___________|        |20MHzXtal|                        7 |   |  |
|                       |_________|       __________       6 | S |  |
|    74LS373                             |          |-     5 | W |  |
|   _________                            |      E   |-     4 |   |  |
|   >_______|              ______________|..... P   |-     3 | 3 |  |
|                         |              |    : O   |-     2 |   |  |
|                         |              |    : X   |-     1 |___|  |
|   ________________      |              |    : Y   |-           |  |
|  |      SW1       |     |      SL90C65 |    :     |-           |  |
|  |________________|     |              |    : B   |-           |  |
|    1 2 3 4 5 6 7 8      |              |    : O   |-           |  |
|                         |_________o____|..../ A   |-    _______|  |
|    ____________________                |      R   |-   |       |------,
|   |                    |               |      D   |-   |  BNC  |   #  |
|   > 2764 PROM SOCKET   |               |__________|-   |_______|------'
|   |____________________|              _________                |  |
|                                       >________| <- 74LS245    |  |
|                                                                |  |
|___                                               ______________|  |
    |H H H H H H H H H H H H H H H H H H H H H H H|               | |
    |U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U_U|               | |
                                                                   \|
```

Legend:



```text
SL90C65       ARCNET Controller / Transceiver /Logic
SW1   1-5:    IRQ Select
        6:    ET1
        7:    ET2
        8:    ROM ENABLE
SW2   1-3:    Memory Buffer/PROM Address
      3-6:    I/O Address Map
SW3   1-8:    Node ID Select
BNC           BNC RG62/U Connection
              *I* have had success using RG59B/U with *NO* terminators!
              What gives?!
```

<a id="rst-sw1-timeouts-interrupt-and-rom"></a>

#### SW1: Timeouts, Interrupt and ROM

To select a hardware interrupt level set one (only one\!) of the dip switches up (on) SW1...(switches 1-5) IRQ3, IRQ4, IRQ5, IRQ7, IRQ2. The Manufacturer's default is IRQ2.

The switches on SW1 labeled EXT1 (switch 6) and EXT2 (switch 7) are used to determine the timeout parameters. These two dip switches are normally left off (down).

> To enable the 8K Boot PROM position SW1 switch 8 on (UP) labeled ROM. The default is jumper ROM not installed.

<a id="rst-setting-the-i-o-base-address-10"></a>

#### Setting the I/O Base Address

The last three switches in switch group SW2 are used to select one of eight possible I/O Base addresses using the following table:



```text
Switch | Hex I/O
4 5 6  | Address
-------|--------
0 0 0  |  260
0 0 1  |  290
0 1 0  |  2E0  (Manufacturer's default)
0 1 1  |  2F0
1 0 0  |  300
1 0 1  |  350
1 1 0  |  380
1 1 1  |  3E0
```

<a id="rst-setting-the-base-memory-address-ram-rom"></a>

#### Setting the Base Memory Address (RAM &amp; ROM)

The memory buffer requires 2K of a 16K block of RAM. The base of this 16K block can be located in any of eight positions. Switches 1-3 of switch group SW2 select the Base of the 16K block. (0 = DOWN, 1 = UP) I could, however, only verify two settings...



```text
Switch| Hex RAM | Hex ROM
1 2 3 | Address | Address
------|---------|-----------
0 0 0 |  E0000  |  E2000
0 0 1 |  D0000  |  D2000  (Manufacturer's default)
0 1 0 |  ?????  |  ?????
0 1 1 |  ?????  |  ?????
1 0 0 |  ?????  |  ?????
1 0 1 |  ?????  |  ?????
1 1 0 |  ?????  |  ?????
1 1 1 |  ?????  |  ?????
```

<a id="rst-setting-the-node-id-10"></a>

#### Setting the Node ID

The eight switches in group SW3 are used to set the node ID. Each node attached to the network must have an unique node ID which must be different from 0. Switch 1 serves as the least significant bit (LSB). switches in the DOWN position are OFF (0) and in the UP position are ON (1)

The node ID is the sum of the values of all switches set to "1" These values are:



```text
Switch | Value
-------|-------
  1    |   1
  2    |   2
  3    |   4
  4    |   8
  5    |  16
  6    |  32
  7    |  64
  8    | 128
```

Some Examples:



```text
    Switch#     |   Hex   | Decimal
8 7 6 5 4 3 2 1 | Node ID | Node ID
----------------|---------|---------
0 0 0 0 0 0 0 0 |    not allowed  <-.
0 0 0 0 0 0 0 1 |    1    |    1    |
0 0 0 0 0 0 1 0 |    2    |    2    |
0 0 0 0 0 0 1 1 |    3    |    3    |
    . . .       |         |         |
0 1 0 1 0 1 0 1 |   55    |   85    |
    . . .       |         |         + Don't use 0 or 255!
1 0 1 0 1 0 1 0 |   AA    |  170    |
    . . .       |         |         |
1 1 1 1 1 1 0 1 |   FD    |  253    |
1 1 1 1 1 1 1 0 |   FE    |  254    |
1 1 1 1 1 1 1 1 |   FF    |  255  <-'
```

<a id="rst-tiara"></a>

## Tiara

<a id="rst-model-unknown"></a>

### (model unknown)

> - from Christoph Lameter &lt;[cl@gentwo.org](<mailto:cl@gentwo.org>)&gt;

Here is information about my card as far as I could figure it out:



```text
----------------------------------------------- tiara
Tiara LanCard of Tiara Computer Systems.

+----------------------------------------------+
!           ! Transmitter Unit !               !
!           +------------------+             -------
!          MEM                              Coax Connector
!  ROM    7654321 <- I/O                     -------
!  :  :   +--------+                           !
!  :  :   ! 90C66LJ!                         +++
!  :  :   !        !                         !D  Switch to set
!  :  :   !        !                         !I  the Nodenumber
!  :  :   +--------+                         !P
!                                            !++
!         234567 <- IRQ                      !
+------------!!!!!!!!!!!!!!!!!!!!!!!!--------+
             !!!!!!!!!!!!!!!!!!!!!!!!
```

- 0 = Jumper Installed

- 1 = Open

Top Jumper line Bit 7 = ROM Enable 654=Memory location 321=I/O

Settings for Memory Location (Top Jumper Line)


<table>
<thead>
<tr>
<th>


456

</th>
<th>


Address selected

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


000

</td>
<td>


C0000

</td>
</tr>
<tr>
<td>


001

</td>
<td>


C4000

</td>
</tr>
<tr>
<td>


010

</td>
<td>


CC000

</td>
</tr>
<tr>
<td>


011

</td>
<td>


D0000

</td>
</tr>
<tr>
<td>


100

</td>
<td>


D4000

</td>
</tr>
<tr>
<td>


101

</td>
<td>


D8000

</td>
</tr>
<tr>
<td>


110

</td>
<td>


DC000

</td>
</tr>
<tr>
<td>


111

</td>
<td>


E0000

</td>
</tr>
</tbody>
</table>

Settings for I/O Address (Top Jumper Line)


<table>
<thead>
<tr>
<th>


123

</th>
<th>


Port

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


000

</td>
<td>


260

</td>
</tr>
<tr>
<td>


001

</td>
<td>


290

</td>
</tr>
<tr>
<td>


010

</td>
<td>


2E0

</td>
</tr>
<tr>
<td>


011

</td>
<td>


2F0

</td>
</tr>
<tr>
<td>


100

</td>
<td>


300

</td>
</tr>
<tr>
<td>


101

</td>
<td>


350

</td>
</tr>
<tr>
<td>


110

</td>
<td>


380

</td>
</tr>
<tr>
<td>


111

</td>
<td>


3E0

</td>
</tr>
</tbody>
</table>

Settings for IRQ Selection (Lower Jumper Line)


<table>
<thead>
<tr>
<th>


234567

</th>
<th>




</th>
</tr>
</thead>
<tbody>
<tr>
<td>


011111

</td>
<td>


IRQ 2

</td>
</tr>
<tr>
<td>


101111

</td>
<td>


IRQ 3

</td>
</tr>
<tr>
<td>


110111

</td>
<td>


IRQ 4

</td>
</tr>
<tr>
<td>


111011

</td>
<td>


IRQ 5

</td>
</tr>
<tr>
<td>


111110

</td>
<td>


IRQ 7

</td>
</tr>
</tbody>
</table>

<a id="rst-other-cards"></a>

## Other Cards

I have no information on other models of ARCnet cards at the moment.

Thanks.

---

# ARCnet

_Peios Kernel / Internals / Networking_

> Since no one seems to listen to me otherwise, perhaps a poem will get your attention:

<a id="rst-arcnet"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Avery Pennarun &lt;[apenwarr@worldvisions.ca](<mailto:apenwarr@worldvisions.ca>)&gt;

> [!NOTE]
>
> See also arcnet-hardware.txt in this directory for jumper-setting and cabling information if you're like many of us and didn't happen to get a manual with your ARCnet card.

Since no one seems to listen to me otherwise, perhaps a poem will get your attention:



```text
This driver's getting fat and beefy,
But my cat is still named Fifi.
```

Hmm, I think I'm allowed to call that a poem, even though it's only two lines.  Hey, I'm in Computer Science, not English.  Give me a break.

The point is:  I REALLY REALLY REALLY REALLY REALLY want to hear from you if you test this and get it working.  Or if you don't.  Or anything.

ARCnet 0.32 ALPHA first made it into the Linux kernel 1.1.80 - this was nice, but after that even FEWER people started writing to me because they didn't even have to install the patch.  &lt;sigh&gt;

Come on, be a sport\!  Send me a success report\!

(hey, that was even better than my original poem... this is getting bad\!)

---

These are the ARCnet drivers for Linux.

This new release (2.91) has been put together by David Woodhouse &lt;[dwmw2@infradead.org](<mailto:dwmw2@infradead.org>)&gt;, in an attempt to tidy up the driver after adding support for yet another chipset. Now the generic support has been separated from the individual chipset drivers, and the source files aren't quite so packed with \#ifdefs\! I've changed this file a bit, but kept it in the first person from Avery, because I didn't want to completely rewrite it.

The previous release resulted from many months of on-and-off effort from me (Avery Pennarun), many bug reports/fixes and suggestions from others, and in particular a lot of input and coding from Tomasz Motylewski.  Starting with ARCnet 2.10 ALPHA, Tomasz's all-new-and-improved RFC1051 support has been included and seems to be working fine\!

<a id="rst-where-do-i-discuss-these-drivers"></a>
<a id="rst-arcnet-netdev"></a>

## Where do I discuss these drivers?

ARCnet discussions take place on netdev. Simply send your email to [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>) and make sure to Cc: maintainer listed in "ARCNET NETWORK LAYER" heading of [Documentation/process/maintainers.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/maintainers.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92).

<a id="rst-other-drivers-and-info"></a>

## Other Drivers and Info

You can try my ARCNET page on the World Wide Web at:

> [http://www.qis.net/\~jschmitz/arcnet/](<http://www.qis.net/~jschmitz/arcnet/>)

Also, SMC (one of the companies that makes ARCnet cards) has a WWW site you might be interested in, which includes several drivers for various cards including ARCnet.  Try:

> [http://www.smc.com/](<http://www.smc.com/>)

Performance Technologies makes various network software that supports ARCnet:

> [http://www.perftech.com/](<http://www.perftech.com/>) or ftp to ftp.perftech.com.

Novell makes a networking stack for DOS which includes ARCnet drivers.  Try FTPing to ftp.novell.com.

You can get the Crynwr packet driver collection (including arcether.com, the one you'll want to use with ARCnet cards) from oak.oakland.edu:/simtel/msdos/pktdrvr. It won't work perfectly on a 386+ without patches, though, and also doesn't like several cards.  Fixed versions are available on my WWW page, or via e-mail if you don't have WWW access.

<a id="rst-installing-the-driver"></a>

## Installing the Driver

All you will need to do in order to install the driver is:



```text
make config
        (be sure to choose ARCnet in the network devices
        and at least one chipset driver.)
make clean
make zImage
```

If you obtained this ARCnet package as an upgrade to the ARCnet driver in your current kernel, you will need to first copy arcnet.c over the one in the linux/drivers/net directory.

You will know the driver is installed properly if you get some ARCnet messages when you reboot into the new Linux kernel.

There are four chipset options:

> 1. Standard ARCnet COM90xx chipset.

This is the normal ARCnet card, which you've probably got. This is the only chipset driver which will autoprobe if not told where the card is. It following options on the command line:



```text
com90xx=[<io>[,<irq>[,<shmem>]]][,<name>] | <name>
```

If you load the chipset support as a module, the options are:



```text
io=<io> irq=<irq> shmem=<shmem> device=<name>
```

To disable the autoprobe, just specify "com90xx=" on the kernel command line. To specify the name alone, but allow autoprobe, just put "com90xx=&lt;name&gt;"

> 2. ARCnet COM20020 chipset.

This is the new chipset from SMC with support for promiscuous mode (packet sniffing), extra diagnostic information, etc. Unfortunately, there is no sensible method of autoprobing for these cards. You must specify the I/O address on the kernel command line.

The command line options are:



```text
com20020=<io>[,<irq>[,<node_ID>[,backplane[,CKP[,timeout]]]]][,name]
```

If you load the chipset support as a module, the options are:



```text
io=<io> irq=<irq> node=<node_ID> backplane=<backplane> clock=<CKP>
timeout=<timeout> device=<name>
```

The COM20020 chipset allows you to set the node ID in software, overriding the default which is still set in DIP switches on the card. If you don't have the COM20020 data sheets, and you don't know what the other three options refer to, then they won't interest you - forget them.

> 3. ARCnet COM90xx chipset in IO-mapped mode.

This will also work with the normal ARCnet cards, but doesn't use the shared memory. It performs less well than the above driver, but is provided in case you have a card which doesn't support shared memory, or (strangely) in case you have so many ARCnet cards in your machine that you run out of shmem slots. If you don't give the IO address on the kernel command line, then the driver will not find the card.

The command line options are:



```text
com90io=<io>[,<irq>][,<name>]
```

- **If you load the chipset support as a module, the options are:**

  io=&lt;io&gt; irq=&lt;irq&gt; device=&lt;name&gt;

  4. ARCnet RIM I cards.

These are COM90xx chips which are \_completely\_ memory mapped. The support for these is not tested. If you have one, please mail the author with a success report. All options must be specified, except the device name. Command line options:



```text
arcrimi=<shmem>,<irq>,<node_ID>[,<name>]
```

If you load the chipset support as a module, the options are:



```text
shmem=<shmem> irq=<irq> node=<node_ID> device=<name>
```

<a id="rst-loadable-module-support"></a>

## Loadable Module Support

Configure and rebuild Linux.  When asked, answer 'm' to "Generic ARCnet support" and to support for your ARCnet chipset if you want to use the loadable module. You can also say 'y' to "Generic ARCnet support" and 'm' to the chipset support if you wish.



```text
make config
make clean
make zImage
make modules
```

If you're using a loadable module, you need to use insmod to load it, and you can specify various characteristics of your card on the command line.  (In recent versions of the driver, autoprobing is much more reliable and works as a module, so most of this is now unnecessary.)

For example:



```text
cd /usr/src/linux/modules
insmod arcnet.o
insmod com90xx.o
insmod com20020.o io=0x2e0 device=eth1
```

<a id="rst-using-the-driver"></a>

## Using the Driver

If you build your kernel with ARCnet COM90xx support included, it should probe for your card automatically when you boot. If you use a different chipset driver complied into the kernel, you must give the necessary options on the kernel command line, as detailed above.

Go read the NET-2-HOWTO and ETHERNET-HOWTO for Linux; they should be available where you picked up this driver.  Think of your ARCnet as a souped-up (or down, as the case may be) Ethernet card.

By the way, be sure to change all references from "eth0" to "arc0" in the HOWTOs.  Remember that ARCnet isn't a "true" Ethernet, and the device name is DIFFERENT.

<a id="rst-multiple-cards-in-one-computer"></a>

## Multiple Cards in One Computer

Linux has pretty good support for this now, but since I've been busy, the ARCnet driver has somewhat suffered in this respect. COM90xx support, if compiled into the kernel, will (try to) autodetect all the installed cards.

If you have other cards, with support compiled into the kernel, then you can just repeat the options on the kernel command line, e.g.:



```text
LILO: linux com20020=0x2e0 com20020=0x380 com90io=0x260
```

If you have the chipset support built as a loadable module, then you need to do something like this:



```text
insmod -o arc0 com90xx
insmod -o arc1 com20020 io=0x2e0
insmod -o arc2 com90xx
```

The ARCnet drivers will now sort out their names automatically.

<a id="rst-how-do-i-get-it-to-work-with"></a>

## How do I get it to work with...?

- **NFS:**

  Should be fine linux-&gt;linux, just pretend you're using Ethernet cards. oak.oakland.edu:/simtel/msdos/nfs has some nice DOS clients.  There is also a DOS-based NFS server called SOSS.  It doesn't multitask quite the way Linux does (actually, it doesn't multitask AT ALL) but you never know what you might need.

  With AmiTCP (and possibly others), you may need to set the following options in your Amiga nfstab:  MD 1024 MR 1024 MW 1024 (Thanks to Christian Gottschling &lt;[ferksy@indigo.tng.oche.de](<mailto:ferksy@indigo.tng.oche.de>)&gt; for this.)

  Probably these refer to maximum NFS data/read/write block sizes.  I don't know why the defaults on the Amiga didn't work; write to me if you know more.

- **DOS:**

  If you're using the freeware arcether.com, you might want to install the driver patch from my web page.  It helps with PC/TCP, and also can get arcether to load if it timed out too quickly during initialization.  In fact, if you use it on a 386+ you REALLY need the patch, really.

- **Windows:**

  See DOS :)  Trumpet Winsock works fine with either the Novell or Arcether client, assuming you remember to load winpkt of course.

- **LAN Manager and Windows for Workgroups:**

  These programs use protocols that are incompatible with the Internet standard.  They try to pretend the cards are Ethernet, and confuse everyone else on the network.

  However, v2.00 and higher of the Linux ARCnet driver supports this protocol via the 'arc0e' device.  See the section on "Multiprotocol Support" for more information.

  Using the freeware Samba server and clients for Linux, you can now interface quite nicely with TCP/IP-based WfWg or Lan Manager networks.

- **Windows 95:**

  Tools are included with Win95 that let you use either the LANMAN style network drivers (NDIS) or Novell drivers (ODI) to handle your ARCnet packets.  If you use ODI, you'll need to use the 'arc0' device with Linux.  If you use NDIS, then try the 'arc0e' device. See the "Multiprotocol Support" section below if you need arc0e, you're completely insane, and/or you need to build some kind of hybrid network that uses both encapsulation types.

- **OS/2:**

  I've been told it works under Warp Connect with an ARCnet driver from SMC.  You need to use the 'arc0e' interface for this.  If you get the SMC driver to work with the TCP/IP stuff included in the "normal" Warp Bonus Pack, let me know.

  ftp.microsoft.com also has a freeware "Lan Manager for OS/2" client which should use the same protocol as WfWg does.  I had no luck installing it under Warp, however.  Please mail me with any results.

- **NetBSD/AmiTCP:**

  These use an old version of the Internet standard ARCnet protocol (RFC1051) which is compatible with the Linux driver v2.10 ALPHA and above using the arc0s device. (See "Multiprotocol ARCnet" below.)  \*\* Newer versions of NetBSD apparently support RFC1201.

<a id="rst-using-multiprotocol-arcnet"></a>

## Using Multiprotocol ARCnet

The ARCnet driver v2.10 ALPHA supports three protocols, each on its own "virtual network device":

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> arc0
>
> </td>
> <td>
>
>
> RFC1201 protocol, the official Internet standard which just happens to be 100% compatible with Novell's TRXNET driver. Version 1.00 of the ARCnet driver supported \_only\_ this protocol.  arc0 is the fastest of the three protocols (for whatever reason), and allows larger packets to be used because it supports RFC1201 "packet splitting" operations. Unless you have a specific need to use a different protocol, I strongly suggest that you stick with this one.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> arc0e
>
> </td>
> <td>
>
>
> "Ethernet-Encapsulation" which sends packets over ARCnet that are actually a lot like Ethernet packets, including the 6-byte hardware addresses.  This protocol is compatible with Microsoft's NDIS ARCnet driver, like the one in WfWg and LANMAN.  Because the MTU of 493 is actually smaller than the one "required" by TCP/IP (576), there is a chance that some network operations will not function properly.  The Linux TCP/IP layer can compensate in most cases, however, by automatically fragmenting the TCP/IP packets to make them fit.  arc0e also works slightly more slowly than arc0, for reasons yet to be determined.  (Probably it's the smaller MTU that does it.)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> arc0s
>
> </td>
> <td>
>
>
> The "\[s\]imple" RFC1051 protocol is the "previous" Internet standard that is completely incompatible with the new standard.  Some software today, however, continues to support the old standard (and only the old standard) including NetBSD and AmiTCP.  RFC1051 also does not support RFC1201's packet splitting, and the MTU of 507 is still smaller than the Internet "requirement," so it's quite possible that you may run into problems.  It's also slower than RFC1201 by about 25%, for the same reason as arc0e.
>
> The arc0s support was contributed by Tomasz Motylewski and modified somewhat by me.  Bugs are probably my fault.
>
> </td>
> </tr>
> </tbody>
> </table>

You can choose not to compile arc0e and arc0s into the driver if you want - this will save you a bit of memory and avoid confusion when eg. trying to use the "NFS-root" stuff in recent Linux kernels.

The arc0e and arc0s devices are created automatically when you first ifconfig the arc0 device.  To actually use them, though, you need to also ifconfig the other virtual devices you need.  There are a number of ways you can set up your network then:

1. Single Protocol.

   This is the simplest way to configure your network: use just one of the two available protocols.  As mentioned above, it's a good idea to use only arc0 unless you have a good reason (like some other software, ie. WfWg, that only works with arc0e).

   If you need only arc0, then the following commands should get you going:



   ```text
   ifconfig arc0 MY.IP.ADD.RESS
   route add MY.IP.ADD.RESS arc0
   route add -net SUB.NET.ADD.RESS arc0
   [add other local routes here]
   ```

   If you need arc0e (and only arc0e), it's a little different:



   ```text
   ifconfig arc0 MY.IP.ADD.RESS
   ifconfig arc0e MY.IP.ADD.RESS
   route add MY.IP.ADD.RESS arc0e
   route add -net SUB.NET.ADD.RESS arc0e
   ```

   arc0s works much the same way as arc0e.

2. More than one protocol on the same wire.

   Now things start getting confusing.  To even try it, you may need to be partly crazy.  Here's what *I* did. :) Note that I don't include arc0s in my home network; I don't have any NetBSD or AmiTCP computers, so I only use arc0s during limited testing.

   I have three computers on my home network; two Linux boxes (which prefer RFC1201 protocol, for reasons listed above), and one XT that can't run Linux but runs the free Microsoft LANMAN Client instead.

   Worse, one of the Linux computers (freedom) also has a modem and acts as a router to my Internet provider.  The other Linux box (insight) also has its own IP address and needs to use freedom as its default gateway.  The XT (patience), however, does not have its own Internet IP address and so I assigned it one on a "private subnet" (as defined by RFC1597).

   To start with, take a simple network with just insight and freedom. Insight needs to:

   > - talk to freedom via RFC1201 (arc0) protocol, because I like it more and it's faster.
   >
   > - use freedom as its Internet gateway.

   That's pretty easy to do.  Set up insight like this:



   ```text
   ifconfig arc0 insight
   route add insight arc0
   route add freedom arc0  /* I would use the subnet here (like I said
                                   to in "single protocol" above),
                                   but the rest of the subnet
                                   unfortunately lies across the PPP
                                   link on freedom, which confuses
                                   things. */
   route add default gw freedom
   ```

   And freedom gets configured like so:



   ```text
   ifconfig arc0 freedom
   route add freedom arc0
   route add insight arc0
   /* and default gateway is configured by pppd */
   ```

   Great, now insight talks to freedom directly on arc0, and sends packets to the Internet through freedom.  If you didn't know how to do the above, you should probably stop reading this section now because it only gets worse.

   Now, how do I add patience into the network?  It will be using LANMAN Client, which means I need the arc0e device.  It needs to be able to talk to both insight and freedom, and also use freedom as a gateway to the Internet.  (Recall that patience has a "private IP address" which won't work on the Internet; that's okay, I configured Linux IP masquerading on freedom for this subnet).

   So patience (necessarily; I don't have another IP number from my provider) has an IP address on a different subnet than freedom and insight, but needs to use freedom as an Internet gateway.  Worse, most DOS networking programs, including LANMAN, have braindead networking schemes that rely completely on the netmask and a 'default gateway' to determine how to route packets.  This means that to get to freedom or insight, patience WILL send through its default gateway, regardless of the fact that both freedom and insight (courtesy of the arc0e device) could understand a direct transmission.

   I compensate by giving freedom an extra IP address - aliased 'gatekeeper' - that is on my private subnet, the same subnet that patience is on.  I then define gatekeeper to be the default gateway for patience.

   To configure freedom (in addition to the commands above):



   ```text
   ifconfig arc0e gatekeeper
   route add gatekeeper arc0e
   route add patience arc0e
   ```

   This way, freedom will send all packets for patience through arc0e, giving its IP address as gatekeeper (on the private subnet).  When it talks to insight or the Internet, it will use its "freedom" Internet IP address.

   You will notice that we haven't configured the arc0e device on insight. This would work, but is not really necessary, and would require me to assign insight another special IP number from my private subnet.  Since both insight and patience are using freedom as their default gateway, the two can already talk to each other.

   It's quite fortunate that I set things up like this the first time (cough cough) because it's really handy when I boot insight into DOS.  There, it runs the Novell ODI protocol stack, which only works with RFC1201 ARCnet. In this mode it would be impossible for insight to communicate directly with patience, since the Novell stack is incompatible with Microsoft's Ethernet-Encap.  Without changing any settings on freedom or patience, I simply set freedom as the default gateway for insight (now in DOS, remember) and all the forwarding happens "automagically" between the two hosts that would normally not be able to communicate at all.

   For those who like diagrams, I have created two "virtual subnets" on the same physical ARCnet wire.  You can picture it like this:



   ```text
       [RFC1201 NETWORK]                   [ETHER-ENCAP NETWORK]
   (registered Internet subnet)           (RFC1597 private subnet)

                          (IP Masquerade)
       /---------------\         *            /---------------\
       |               |         *            |               |
       |               +-Freedom-*-Gatekeeper-+               |
       |               |    |    *            |               |
       \-------+-------/    |    *            \-------+-------/
               |            |                         |
            Insight         |                      Patience
                        (Internet)
   ```

<a id="rst-it-works-what-now"></a>

## It works: what now?

Send mail following [Where do I discuss these drivers?](<#rst-arcnet-netdev>). Describe your setup, preferably including driver version, kernel version, ARCnet card model, CPU type, number of systems on your network, and list of software in use.

<a id="rst-it-doesn-t-work-what-now"></a>

## It doesn't work: what now?

Do the same as above, but also include the output of the ifconfig and route commands, as well as any pertinent log entries (ie. anything that starts with "arcnet:" and has shown up since the last reboot) in your mail.

If you want to try fixing it yourself (I strongly recommend that you mail me about the problem first, since it might already have been solved) you may want to try some of the debug levels available.  For heavy testing on D_DURING or more, it would be a REALLY good idea to kill your klogd daemon first\!  D_DURING displays 4-5 lines for each packet sent or received.  D_TX, D_RX, and D_SKB actually DISPLAY each packet as it is sent or received, which is obviously quite big.

Starting with v2.40 ALPHA, the autoprobe routines have changed significantly.  In particular, they won't tell you why the card was not found unless you turn on the D_INIT_REASONS debugging flag.

Once the driver is running, you can run the arcdump shell script (available from me or in the full ARCnet package, if you have it) as root to list the contents of the arcnet buffers at any time.  To make any sense at all out of this, you should grab the pertinent RFCs. (some are listed near the top of arcnet.c).  arcdump assumes your card is at 0xD0000.  If it isn't, edit the script.

Buffers 0 and 1 are used for receiving, and Buffers 2 and 3 are for sending. Ping-pong buffers are implemented both ways.

If your debug level includes D_DURING and you did NOT define SLOW_XMIT_COPY, the buffers are cleared to a constant value of 0x42 every time the card is reset (which should only happen when you do an ifconfig up, or when Linux decides that the driver is broken).  During a transmit, unused parts of the buffer will be cleared to 0x42 as well.  This is to make it easier to figure out which bytes are being used by a packet.

You can change the debug level without recompiling the kernel by typing:



```text
ifconfig arc0 down metric 1xxx
/etc/rc.d/rc.inet1
```

where "xxx" is the debug level you want.  For example, "metric 1015" would put you at debug level 15.  Debug level 7 is currently the default.

Note that the debug level is (starting with v1.90 ALPHA) a binary combination of different debug flags; so debug level 7 is really 1+2+4 or D_NORMAL+D_EXTRA+D_INIT.  To include D_DURING, you would add 16 to this, resulting in debug level 23.

If you don't understand that, you probably don't want to know anyway. E-mail me about your problem.

<a id="rst-i-want-to-send-money-what-now"></a>

## I want to send money: what now?

Go take a nap or something.  You'll feel better in the morning.

---

# ATM

_Peios Kernel / Internals / Networking_

> In order to use anything but the most primitive functions of ATM, several user-mode programs are required to assist the kernel. These programs and related material can be found via the ATM on Linux Web page at…

<a id="rst-atm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In order to use anything but the most primitive functions of ATM, several user-mode programs are required to assist the kernel. These programs and related material can be found via the ATM on Linux Web page at [http://linux-atm.sourceforge.net/](<http://linux-atm.sourceforge.net/>)

If you encounter problems with ATM, please report them on the ATM on Linux mailing list. Subscription information, archives, etc., can be found on [http://linux-atm.sourceforge.net/](<http://linux-atm.sourceforge.net/>)

---

# AX.25

_Peios Kernel / Internals / Networking_

> To use the amateur radio protocols within Linux you will need to get a suitable copy of the AX.25 Utilities. More detailed information about AX.25, NET/ROM and ROSE, associated programs and utilities can be found on…

<a id="rst-ax-25"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

To use the amateur radio protocols within Linux you will need to get a suitable copy of the AX.25 Utilities. More detailed information about AX.25, NET/ROM and ROSE, associated programs and utilities can be found on [https://linux-ax25.in-berlin.de](<https://linux-ax25.in-berlin.de>).

There is a mailing list for discussing Linux amateur radio matters called [linux-hams@vger.kernel.org](<mailto:linux-hams@vger.kernel.org>). To subscribe to it, send a message to [linux-hams+subscribe@vger.kernel.org](<mailto:linux-hams+subscribe@vger.kernel.org>) or use the web interface at [https://vger.kernel.org](<https://vger.kernel.org>). The subject and body of the message are ignored.  You don't need to be subscribed to post but of course that means you might miss an answer.

---

# Bare UDP Tunnelling Module Documentation

_Peios Kernel / Internals / Networking_

> There are various L3 encapsulation standards using UDP being discussed to leverage the UDP based load balancing capability of different networks. MPLSoUDP (https://tools.ietf.org/html/rfc7510) is one among them.

<a id="rst-bare-udp-tunnelling-module-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

There are various L3 encapsulation standards using UDP being discussed to leverage the UDP based load balancing capability of different networks. MPLSoUDP ([https://tools.ietf.org/html/rfc7510](<https://tools.ietf.org/html/rfc7510>)) is one among them.

The Bareudp tunnel module provides a generic L3 encapsulation support for tunnelling different L3 protocols like MPLS, IP, NSH etc. inside a UDP tunnel.

<a id="rst-special-handling"></a>

## Special Handling

The bareudp device supports special handling for MPLS &amp; IP as they can have multiple ethertypes. The MPLS protocol can have ethertypes ETH_P_MPLS_UC (unicast) &amp; ETH_P_MPLS_MC (multicast). IP protocol can have ethertypes ETH_P_IP (v4) &amp; ETH_P_IPV6 (v6). This special handling can be enabled only for ethertypes ETH_P_IP &amp; ETH_P_MPLS_UC with a flag called multiproto mode.

<a id="rst-usage"></a>

## Usage

1. Device creation &amp; deletion

   > - **a)** ip link add dev bareudp0 type bareudp dstport 6635 ethertype mpls_uc
   >
   >   This creates a bareudp tunnel device which tunnels L3 traffic with ethertype 0x8847 (MPLS traffic). The destination port of the UDP header will be set to 6635.The device will listen on UDP port 6635 to receive traffic.
   >
   > - **b)** ip link delete bareudp0

2. Device creation with multiproto mode enabled

The multiproto mode allows bareudp tunnels to handle several protocols of the same family. It is currently only available for IP and MPLS. This mode has to be enabled explicitly with the "multiproto" flag.

> - **a)** ip link add dev bareudp0 type bareudp dstport 6635 ethertype ipv4 multiproto
>
>   For an IPv4 tunnel the multiproto mode allows the tunnel to also handle IPv6.
>
> - **b)** ip link add dev bareudp0 type bareudp dstport 6635 ethertype mpls_uc multiproto
>
>   For MPLS, the multiproto mode allows the tunnel to handle both unicast and multicast MPLS packets.

3. Device Usage

The bareudp device could be used along with OVS or flower filter in TC. The OVS or TC flower layer must set the tunnel information in the SKB dst field before sending the packet buffer to the bareudp device for transmission. On reception, the bareUDP device extracts and stores the tunnel information in the SKB dst field before passing the packet buffer to the network stack.

---

# batman-adv

_Peios Kernel / Internals / Networking_

> Batman advanced is a new approach to wireless networking which does no longer operate on the IP basis. Unlike the batman daemon, which exchanges information using UDP packets and sets routing tables, batman-advanced operates on ISO/OSI…

<a id="rst-batman-adv"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Batman advanced is a new approach to wireless networking which does no longer operate on the IP basis. Unlike the batman daemon, which exchanges information using UDP packets and sets routing tables, batman-advanced operates on ISO/OSI Layer 2 only and uses and routes (or better: bridges) Ethernet Frames. It emulates a virtual network switch of all nodes participating. Therefore all nodes appear to be link local, thus all higher operating protocols won't be affected by any changes within the network. You can run almost any protocol above batman advanced, prominent examples are: IPv4, IPv6, DHCP, IPX.

Batman advanced was implemented as a Linux kernel driver to reduce the overhead to a minimum. It does not depend on any (other) network driver, and can be used on wifi as well as ethernet lan, vpn, etc ... (anything with ethernet-style layer 2).

<a id="rst-configuration"></a>

## Configuration

Load the batman-adv module into your kernel:



```text
$ insmod batman-adv.ko
```

The module is now waiting for activation. You must add some interfaces on which batman-adv can operate. The batman-adv mesh-interface can be created using the iproute2 tool `ip`:



```text
$ ip link add name bat0 type batadv
```

To activate a given interface simply attach it to the `bat0` interface:



```text
$ ip link set dev eth0 master bat0
```

Repeat this step for all interfaces you wish to add. Now batman-adv starts using/broadcasting on this/these interface(s).

To deactivate an interface you have to detach it from the "bat0" interface:



```text
$ ip link set dev eth0 nomaster
```

The same can also be done using the batctl interface subcommand:



```text
batctl -m bat0 interface create
batctl -m bat0 interface add -M eth0
```

To detach eth0 and destroy bat0:



```text
batctl -m bat0 interface del -M eth0
batctl -m bat0 interface destroy
```

There are additional settings for each batadv mesh interface, vlan and hardif which can be modified using batctl. Detailed information about this can be found in its manual.

For instance, you can check the current originator interval (value in milliseconds which determines how often batman-adv sends its broadcast packets):



```text
$ batctl -M bat0 orig_interval
1000
```

and also change its value:



```text
$ batctl -M bat0 orig_interval 3000
```

In very mobile scenarios, you might want to adjust the originator interval to a lower value. This will make the mesh more responsive to topology changes, but will also increase the overhead.

Information about the current state can be accessed via the batadv generic netlink family. batctl provides a human readable version via its debug tables subcommands.

<a id="rst-usage"></a>

## Usage

To make use of your newly created mesh, batman advanced provides a new interface "bat0" which you should use from this point on. All interfaces added to batman advanced are not relevant any longer because batman handles them for you. Basically, one "hands over" the data by using the batman interface and batman will make sure it reaches its destination.

The "bat0" interface can be used like any other regular interface. It needs an IP address which can be either statically configured or dynamically (by using DHCP or similar services):



```text
NodeA: ip link set up dev bat0
NodeA: ip addr add 192.168.0.1/24 dev bat0

NodeB: ip link set up dev bat0
NodeB: ip addr add 192.168.0.2/24 dev bat0
NodeB: ping 192.168.0.1
```

Note: In order to avoid problems remove all IP addresses previously assigned to interfaces now used by batman advanced, e.g.:



```text
$ ip addr flush dev eth0
```

<a id="rst-logging-debugging"></a>

## Logging/Debugging

All error messages, warnings and information messages are sent to the kernel log. Depending on your operating system distribution this can be read in one of a number of ways. Try using the commands: `dmesg`, `logread`, or looking in the files `/var/log/kern.log` or `/var/log/syslog`. All batman-adv messages are prefixed with "batman-adv:" So to see just these messages try:



```text
$ dmesg | grep batman-adv
```

When investigating problems with your mesh network, it is sometimes necessary to see more detailed debug messages. This must be enabled when compiling the batman-adv module. When building batman-adv as part of the kernel, use "make menuconfig" and enable the option `B.A.T.M.A.N. debugging` (`CONFIG_BATMAN_ADV_DEBUG=y`).

Those additional debug messages can be accessed using the perf infrastructure:



```text
$ trace-cmd stream -e batadv:batadv_dbg
```

The additional debug output is by default disabled. It can be enabled during run time:



```text
$ batctl -m bat0 loglevel routes tt
```

will enable debug messages for when routes and translation table entries change.

Counters for different types of packets entering and leaving the batman-adv module are available through ethtool:



```text
$ ethtool --statistics bat0
```

<a id="rst-batctl"></a>

## batctl

As batman advanced operates on layer 2, all hosts participating in the virtual switch are completely transparent for all protocols above layer 2. Therefore the common diagnosis tools do not work as expected. To overcome these problems, batctl was created. At the moment the batctl contains ping, traceroute, tcpdump and interfaces to the kernel module settings.

For more information, please see the manpage (`man batctl`).

batctl is available on [https://www.open-mesh.org/](<https://www.open-mesh.org/>)

<a id="rst-contact"></a>

## Contact

Please send us comments, experiences, questions, anything :)

- **IRC:**

  \#batadv on ircs://irc.hackint.org/

- **Mailing-list:**

  [b.a.t.m.a.n@lists.open-mesh.org](<mailto:b.a.t.m.a.n@lists.open-mesh.org>) (optional subscription at [https://lists.open-mesh.org/mailman3/postorius/lists/b.a.t.m.a.n.lists.open-mesh.org/](<https://lists.open-mesh.org/mailman3/postorius/lists/b.a.t.m.a.n.lists.open-mesh.org/>))

You can also contact the Authors:

- Marek Lindner &lt;[marek.lindner@mailbox.org](<mailto:marek.lindner@mailbox.org>)&gt;

- Simon Wunderlich &lt;[sw@simonwunderlich.de](<mailto:sw@simonwunderlich.de>)&gt;

---

# Linux Ethernet Bonding Driver HOWTO

_Peios Kernel / Internals / Networking_

> Latest update: 27 April 2011

<a id="rst-linux-ethernet-bonding-driver-howto"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Latest update: 27 April 2011

Initial release: Thomas Davis &lt;tadavis at lbl.gov&gt;

Corrections, HA extensions: 2000/10/03-15:

> - Willy Tarreau &lt;willy at meta-x.org&gt;
>
> - Constantine Gavrilov &lt;const-g at xpert.com&gt;
>
> - Chad N. Tindel &lt;ctindel at ieee dot org&gt;
>
> - Janice Girouard &lt;girouard at us dot ibm dot com&gt;
>
> - Jay Vosburgh &lt;fubar at us dot ibm dot com&gt;

Reorganized and updated Feb 2005 by Jay Vosburgh Added Sysfs information: 2006/04/24

> - Mitch Williams &lt;mitch.a.williams at intel.com&gt;

<a id="rst-introduction"></a>

## Introduction

The Linux bonding driver provides a method for aggregating multiple network interfaces into a single logical "bonded" interface. The behavior of the bonded interfaces depends upon the mode; generally speaking, modes provide either hot standby or load balancing services. Additionally, link integrity monitoring may be performed.

The bonding driver originally came from Donald Becker's beowulf patches for kernel 2.0. It has changed quite a bit since, and the original tools from extreme-linux and beowulf sites will not work with this version of the driver.

For new versions of the driver, updated userspace tools, and who to ask for help, please follow the links at the end of this file.

<!-- Table of Contents

1. Bonding Driver Installation

2. Bonding Driver Options

3. Configuring Bonding Devices
3.1  Configuration with Sysconfig Support
3.1.1                Using DHCP with Sysconfig
3.1.2                Configuring Multiple Bonds with Sysconfig
3.2  Configuration with Initscripts Support
3.2.1                Using DHCP with Initscripts
3.2.2                Configuring Multiple Bonds with Initscripts
3.3  Configuring Bonding Manually with Ifenslave
3.3.1                Configuring Multiple Bonds Manually
3.4  Configuring Bonding Manually via Sysfs
3.5  Configuration with Interfaces Support
3.6  Overriding Configuration for Special Cases
3.7 Configuring LACP for 802.3ad mode in a more secure way

4. Querying Bonding Configuration
4.1  Bonding Configuration
4.2  Network Configuration

5. Switch Configuration

6. 802.1q VLAN Support

7. Link Monitoring
7.1  ARP Monitor Operation
7.2  Configuring Multiple ARP Targets
7.3  MII Monitor Operation

8. Potential Trouble Sources
8.1  Adventures in Routing
8.2  Ethernet Device Renaming
8.3  Painfully Slow Or No Failed Link Detection By Miimon

9. SNMP agents

10. Promiscuous mode

11. Configuring Bonding for High Availability
11.1 High Availability in a Single Switch Topology
11.2 High Availability in a Multiple Switch Topology
11.2.1               HA Bonding Mode Selection for Multiple Switch Topology
11.2.2               HA Link Monitoring for Multiple Switch Topology

12. Configuring Bonding for Maximum Throughput
12.1 Maximum Throughput in a Single Switch Topology
12.1.1               MT Bonding Mode Selection for Single Switch Topology
12.1.2               MT Link Monitoring for Single Switch Topology
12.2 Maximum Throughput in a Multiple Switch Topology
12.2.1               MT Bonding Mode Selection for Multiple Switch Topology
12.2.2               MT Link Monitoring for Multiple Switch Topology

13. Switch Behavior Issues
13.1 Link Establishment and Failover Delays
13.2 Duplicated Incoming Packets

14. Hardware Specific Considerations
14.1 IBM BladeCenter

15. Frequently Asked Questions

16. Resources and Links -->

<a id="rst-bonding-driver-installation"></a>

## 1. Bonding Driver Installation

Most popular distro kernels ship with the bonding driver already available as a module. If your distro does not, or you have need to compile bonding from source (e.g., configuring and installing a mainline kernel from kernel.org), you'll need to perform the following steps:

<a id="rst-configure-and-build-the-kernel-with-bonding"></a>

### 1.1 Configure and build the kernel with bonding

The current version of the bonding driver is available in the drivers/net/bonding subdirectory of the most recent kernel source (which is available on [http://kernel.org](<http://kernel.org>)).  Most users "rolling their own" will want to use the most recent kernel from kernel.org.

Configure kernel with "make menuconfig" (or "make xconfig" or "make config"), then select "Bonding driver support" in the "Network device support" section.  It is recommended that you configure the driver as module since it is currently the only way to pass parameters to the driver or configure more than one bonding device.

Build and install the new kernel and modules.

<a id="rst-bonding-control-utility"></a>

### 1.2 Bonding Control Utility

It is recommended to configure bonding via iproute2 (netlink) or sysfs, the old ifenslave control utility is obsolete.

<a id="rst-bonding-driver-options"></a>

## 2. Bonding Driver Options

Options for the bonding driver are supplied as parameters to the bonding module at load time, or are specified via sysfs.

Module options may be given as command line arguments to the insmod or modprobe command, but are usually specified in either the `/etc/modprobe.d/*.conf` configuration files, or in a distro-specific configuration file (some of which are detailed in the next section).

Details on bonding support for sysfs is provided in the "Configuring Bonding Manually via Sysfs" section, below.

The available bonding driver parameters are listed below. If a parameter is not specified the default value is used.  When initially configuring a bond, it is recommended "tail -f /var/log/messages" be run in a separate window to watch for bonding driver error messages.

It is critical that either the miimon or arp\_interval and arp\_ip\_target parameters be specified, otherwise serious network degradation will occur during link failures.  Very few devices do not support at least miimon, so there is really no reason not to use it.

Options with textual values will accept either the text name or, for backwards compatibility, the option value.  E.g., "mode=802.3ad" and "mode=4" set the same mode.

The parameters are as follows:

active\_slave

> Specifies the new active slave for modes that support it (active-backup, balance-alb and balance-tlb).  Possible values are the name of any currently enslaved interface, or an empty string.  If a name is given, the slave and its link must be up in order to be selected as the new active slave.  If an empty string is specified, the current active slave is cleared, and a new active slave is selected automatically.
>
> Note that this is only available through the sysfs interface. No module parameter by this name exists.
>
> The normal value of this option is the name of the currently active slave, or the empty string if there is no active slave or the current mode does not use an active slave.

ad\_actor\_sys\_prio

> In an AD system, this specifies the system priority. The allowed range is 1 - 65535. If the value is not specified, it takes 65535 as the default value.
>
> This parameter has effect only in 802.3ad mode and is available through SysFs interface.

actor\_port\_prio

> In an AD system, this specifies the port priority. The allowed range is 1 - 65535. If the value is not specified, it takes 255 as the default value.
>
> This parameter has effect only in 802.3ad mode and is available through netlink interface.

ad\_actor\_system

> In an AD system, this specifies the mac-address for the actor in protocol packet exchanges (LACPDUs). The value cannot be a multicast address. If the all-zeroes MAC is specified, bonding will internally use the MAC of the bond itself. It is preferred to have the local-admin bit set for this mac but driver does not enforce it. If the value is not given then system defaults to using the masters' mac address as actors' system address.
>
> This parameter has effect only in 802.3ad mode and is available through SysFs interface.

ad\_select

> Specifies the 802.3ad aggregation selection logic to use.  The possible values and their effects are:
>
> stable or 0
>
> > The active aggregator is chosen by largest aggregate bandwidth.
> >
> > Reselection of the active aggregator occurs only when all slaves of the active aggregator are down or the active aggregator has no slaves.
> >
> > This is the default value.
>
> bandwidth or 1
>
> > The active aggregator is chosen by largest aggregate bandwidth.  Reselection occurs if:
> >
> > - A slave is added to or removed from the bond
> >
> > - Any slave's link state changes
> >
> > - Any slave's 802.3ad association state changes
> >
> > - The bond's administrative state changes to up
>
> count or 2
>
> > The active aggregator is chosen by the largest number of ports (slaves).  Reselection occurs as described under the "bandwidth" setting, above.
>
> actor\_port\_prio or 3
>
> > The active aggregator is chosen by the highest total sum of actor port priorities across its active ports. Note this priority is actor\_port\_prio, not per port prio, which is used for primary reselect.
>
> The bandwidth, count and actor\_port\_prio selection policies permit failover of 802.3ad aggregations when partial failure of the active aggregator occurs. This keeps the aggregator with the highest availability (either in bandwidth, number of ports, or total value of port priorities) active at all times.
>
> This option was added in bonding version 3.4.0.

ad\_user\_port\_key

> In an AD system, the port-key has three parts as shown below -
>
> >
> > <table>
> > <thead>
> > <tr>
> > <th>
> >
> >
> > Bits
> >
> > </th>
> > <th>
> >
> >
> > Use
> >
> > </th>
> > </tr>
> > </thead>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 00
> >
> > </td>
> > <td>
> >
> >
> > Duplex
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 01-05
> >
> > </td>
> > <td>
> >
> >
> > Speed
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 06-15
> >
> > </td>
> > <td>
> >
> >
> > User-defined
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> This defines the upper 10 bits of the port key. The values can be from 0 - 1023. If not given, the system defaults to 0.
>
> This parameter has effect only in 802.3ad mode and is available through SysFs interface.

all\_slaves\_active

> Specifies that duplicate frames (received on inactive ports) should be dropped (0) or delivered (1).
>
> Normally, bonding will drop duplicate frames (received on inactive ports), which is desirable for most users. But there are some times it is nice to allow duplicate frames to be delivered.
>
> The default value is 0 (drop duplicate frames received on inactive ports).

arp\_interval

> Specifies the ARP link monitoring frequency in milliseconds.
>
> The ARP monitor works by periodically checking the slave devices to determine whether they have sent or received traffic recently (the precise criteria depends upon the bonding mode, and the state of the slave).  Regular traffic is generated via ARP probes issued for the addresses specified by the arp\_ip\_target option.
>
> This behavior can be modified by the arp\_validate option, below.
>
> If ARP monitoring is used in an etherchannel compatible mode (modes 0 and 2), the switch should be configured in a mode that evenly distributes packets across all links. If the switch is configured to distribute the packets in an XOR fashion, all replies from the ARP targets will be received on the same link which could cause the other team members to fail.  ARP monitoring should not be used in conjunction with miimon.  A value of 0 disables ARP monitoring.  The default value is 0.

arp\_ip\_target

> Specifies the IP addresses to use as ARP monitoring peers when arp\_interval is &gt; 0.  These are the targets of the ARP request sent to determine the health of the link to the targets. Specify these values in ddd.ddd.ddd.ddd format.  Multiple IP addresses must be separated by a comma.  At least one IP address must be given for ARP monitoring to function.  The maximum number of targets that can be specified is 16.  The default value is no IP addresses.

ns\_ip6\_target

> Specifies the IPv6 addresses to use as IPv6 monitoring peers when arp\_interval is &gt; 0.  These are the targets of the NS request sent to determine the health of the link to the targets. Specify these values in ffff:ffff::ffff:ffff format.  Multiple IPv6 addresses must be separated by a comma.  At least one IPv6 address must be given for NS/NA monitoring to function.  The maximum number of targets that can be specified is 16.  The default value is no IPv6 addresses.

arp\_validate

> Specifies whether or not ARP probes and replies should be validated in any mode that supports arp monitoring, or whether non-ARP traffic should be filtered (disregarded) for link monitoring purposes.
>
> Possible values are:
>
> none or 0
>
> > No validation or filtering is performed.
>
> active or 1
>
> > Validation is performed only for the active slave.
>
> backup or 2
>
> > Validation is performed only for backup slaves.
>
> all or 3
>
> > Validation is performed for all slaves.
>
> filter or 4
>
> > Filtering is applied to all slaves. No validation is performed.
>
> filter\_active or 5
>
> > Filtering is applied to all slaves, validation is performed only for the active slave.
>
> filter\_backup or 6
>
> > Filtering is applied to all slaves, validation is performed only for backup slaves.
>
> Validation:
>
> Enabling validation causes the ARP monitor to examine the incoming ARP requests and replies, and only consider a slave to be up if it is receiving the appropriate ARP traffic.
>
> For an active slave, the validation checks ARP replies to confirm that they were generated by an arp\_ip\_target.  Since backup slaves do not typically receive these replies, the validation performed for backup slaves is on the broadcast ARP request sent out via the active slave.  It is possible that some switch or network configurations may result in situations wherein the backup slaves do not receive the ARP requests; in such a situation, validation of backup slaves must be disabled.
>
> The validation of ARP requests on backup slaves is mainly helping bonding to decide which slaves are more likely to work in case of the active slave failure, it doesn't really guarantee that the backup slave will work if it's selected as the next active slave.
>
> Validation is useful in network configurations in which multiple bonding hosts are concurrently issuing ARPs to one or more targets beyond a common switch.  Should the link between the switch and target fail (but not the switch itself), the probe traffic generated by the multiple bonding instances will fool the standard ARP monitor into considering the links as still up.  Use of validation can resolve this, as the ARP monitor will only consider ARP requests and replies associated with its own instance of bonding.
>
> Filtering:
>
> Enabling filtering causes the ARP monitor to only use incoming ARP packets for link availability purposes.  Arriving packets that are not ARPs are delivered normally, but do not count when determining if a slave is available.
>
> Filtering operates by only considering the reception of ARP packets (any ARP packet, regardless of source or destination) when determining if a slave has received traffic for link availability purposes.
>
> Filtering is useful in network configurations in which significant levels of third party broadcast traffic would fool the standard ARP monitor into considering the links as still up.  Use of filtering can resolve this, as only ARP traffic is considered for link availability purposes.
>
> This option was added in bonding version 3.1.0.

arp\_all\_targets

> Specifies the quantity of arp\_ip\_targets that must be reachable in order for the ARP monitor to consider a slave as being up. This option affects only active-backup mode for slaves with arp\_validation enabled.
>
> Possible values are:
>
> any or 0
>
> > consider the slave up only when any of the arp\_ip\_targets is reachable
>
> all or 1
>
> > consider the slave up only when all of the arp\_ip\_targets are reachable

arp\_missed\_max

> Specifies the number of arp\_interval monitor checks that must fail in order for an interface to be marked down by the ARP monitor.
>
> In order to provide orderly failover semantics, backup interfaces are permitted an extra monitor check (i.e., they must fail arp\_missed\_max + 1 times before being marked down).
>
> The default value is 2, and the allowable range is 1 - 255.

coupled\_control

> Specifies whether the LACP state machine's MUX in the 802.3ad mode should have separate Collecting and Distributing states.
>
> This is by implementing the independent control state machine per IEEE 802.1AX-2008 5.4.15 in addition to the existing coupled control state machine.
>
> The default value is 1. This setting does not separate the Collecting and Distributing states, maintaining the bond in coupled control.

downdelay

> Specifies the time, in milliseconds, to wait before disabling a slave after a link failure has been detected.  This option is only valid for the miimon link monitor.  The downdelay value should be a multiple of the miimon value; if not, it will be rounded down to the nearest multiple.  The default value is 0.

fail\_over\_mac

> Specifies whether active-backup mode should set all slaves to the same MAC address at enslavement (the traditional behavior), or, when enabled, perform special handling of the bond's MAC address in accordance with the selected policy.
>
> Possible values are:
>
> none or 0
>
> > This setting disables fail\_over\_mac, and causes bonding to set all slaves of an active-backup bond to the same MAC address at enslavement time.  This is the default.
>
> active or 1
>
> > The "active" fail\_over\_mac policy indicates that the MAC address of the bond should always be the MAC address of the currently active slave.  The MAC address of the slaves is not changed; instead, the MAC address of the bond changes during a failover.
> >
> > This policy is useful for devices that cannot ever alter their MAC address, or for devices that refuse incoming broadcasts with their own source MAC (which interferes with the ARP monitor).
> >
> > The down side of this policy is that every device on the network must be updated via gratuitous ARP, vs. just updating a switch or set of switches (which often takes place for any traffic, not just ARP traffic, if the switch snoops incoming traffic to update its tables) for the traditional method.  If the gratuitous ARP is lost, communication may be disrupted.
> >
> > When this policy is used in conjunction with the mii monitor, devices which assert link up prior to being able to actually transmit and receive are particularly susceptible to loss of the gratuitous ARP, and an appropriate updelay setting may be required.
>
> follow or 2
>
> > The "follow" fail\_over\_mac policy causes the MAC address of the bond to be selected normally (normally the MAC address of the first slave added to the bond). However, the second and subsequent slaves are not set to this MAC address while they are in a backup role; a slave is programmed with the bond's MAC address at failover time (and the formerly active slave receives the newly active slave's MAC address).
> >
> > This policy is useful for multiport devices that either become confused or incur a performance penalty when multiple ports are programmed with the same MAC address.
>
> The default policy is none, unless the first slave cannot change its MAC address, in which case the active policy is selected by default.
>
> This option may be modified via sysfs only when no slaves are present in the bond.
>
> This option was added in bonding version 3.2.0.  The "follow" policy was added in bonding version 3.3.0.

- **lacp\_active**

  Option specifying whether to send LACPDU frames periodically.

  - **off or 0**

    LACPDU frames acts as "speak when spoken to".

  - **on or 1**

    LACPDU frames are sent along the configured links periodically. See lacp\_rate for more details.

  The default is on.

lacp\_rate

> Option specifying the rate in which we'll ask our link partner to transmit LACPDU packets in 802.3ad mode.  Possible values are:
>
> - **slow or 0**
>
>   Request partner to transmit LACPDUs every 30 seconds
>
> - **fast or 1**
>
>   Request partner to transmit LACPDUs every 1 second
>
> The default is slow.

broadcast\_neighbor

> Option specifying whether to broadcast ARP/ND packets to all active slaves.  This option has no effect in modes other than 802.3ad mode.  The default is off (0).

max\_bonds

> Specifies the number of bonding devices to create for this instance of the bonding driver.  E.g., if max\_bonds is 3, and the bonding driver is not already loaded, then bond0, bond1 and bond2 will be created.  The default value is 1.  Specifying a value of 0 will load bonding, but will not create any devices.

miimon

> Specifies the MII link monitoring frequency in milliseconds. This determines how often the link state of each slave is inspected for link failures.  A value of zero disables MII link monitoring.  A value of 100 is a good starting point.
>
> The default value is 100 if arp\_interval is not set.

min\_links

> Specifies the minimum number of links that must be active before asserting carrier. It is similar to the Cisco EtherChannel min-links feature. This allows setting the minimum number of member ports that must be up (link-up state) before marking the bond device as up (carrier on). This is useful for situations where higher level services such as clustering want to ensure a minimum number of low bandwidth links are active before switchover. This option only affect 802.3ad mode.
>
> The default value is 0. This will cause carrier to be asserted (for 802.3ad mode) whenever there is an active aggregator, regardless of the number of available links in that aggregator. Note that, because an aggregator cannot be active without at least one available link, setting this option to 0 or to 1 has the exact same effect.

mode

> Specifies one of the bonding policies. The default is balance-rr (round robin).  Possible values are:
>
> balance-rr or 0
>
> > Round-robin policy: Transmit packets in sequential order from the first available slave through the last.  This mode provides load balancing and fault tolerance.
>
> active-backup or 1
>
> > Active-backup policy: Only one slave in the bond is active.  A different slave becomes active if, and only if, the active slave fails.  The bond's MAC address is externally visible on only one port (network adapter) to avoid confusing the switch.
> >
> > In bonding version 2.6.2 or later, when a failover occurs in active-backup mode, bonding will issue one or more gratuitous ARPs on the newly active slave. One gratuitous ARP is issued for the bonding master interface and each VLAN interfaces configured above it, provided that the interface has at least one IP address configured.  Gratuitous ARPs issued for VLAN interfaces are tagged with the appropriate VLAN id.
> >
> > This mode provides fault tolerance.  The primary option, documented below, affects the behavior of this mode.
>
> balance-xor or 2
>
> > XOR policy: Transmit based on the selected transmit hash policy.  The default policy is a simple \[(source MAC address XOR'd with destination MAC address XOR packet type ID) modulo slave count\].  Alternate transmit policies may be selected via the xmit\_hash\_policy option, described below.
> >
> > This mode provides load balancing and fault tolerance.
>
> broadcast or 3
>
> > Broadcast policy: transmits everything on all slave interfaces.  This mode provides fault tolerance.
>
> 802.3ad or 4
>
> > IEEE 802.3ad Dynamic link aggregation.  Creates aggregation groups that share the same speed and duplex settings.  Utilizes all slaves in the active aggregator according to the 802.3ad specification.
> >
> > Slave selection for outgoing traffic is done according to the transmit hash policy, which may be changed from the default simple XOR policy via the xmit\_hash\_policy option, documented below.  Note that not all transmit policies may be 802.3ad compliant, particularly in regards to the packet mis-ordering requirements of section 43.2.4 of the 802.3ad standard.  Differing peer implementations will have varying tolerances for noncompliance.
> >
> > Prerequisites:
> >
> > 1\. Ethtool support in the base drivers for retrieving the speed and duplex of each slave.
> >
> > 2\. A switch that supports IEEE 802.3ad Dynamic link aggregation.
> >
> > Most switches will require some type of configuration to enable 802.3ad mode.
>
> balance-tlb or 5
>
> > Adaptive transmit load balancing: channel bonding that does not require any special switch support.
> >
> > In tlb\_dynamic\_lb=1 mode; the outgoing traffic is distributed according to the current load (computed relative to the speed) on each slave.
> >
> > In tlb\_dynamic\_lb=0 mode; the load balancing based on current load is disabled and the load is distributed only using the hash distribution.
> >
> > Incoming traffic is received by the current slave. If the receiving slave fails, another slave takes over the MAC address of the failed receiving slave.
> >
> > Prerequisite:
> >
> > Ethtool support in the base drivers for retrieving the speed of each slave.
>
> balance-alb or 6
>
> > Adaptive load balancing: includes balance-tlb plus receive load balancing (rlb) for IPV4 traffic, and does not require any special switch support.  The receive load balancing is achieved by ARP negotiation. The bonding driver intercepts the ARP Replies sent by the local system on their way out and overwrites the source hardware address with the unique hardware address of one of the slaves in the bond such that different peers use different hardware addresses for the server.
> >
> > Receive traffic from connections created by the server is also balanced.  When the local system sends an ARP Request the bonding driver copies and saves the peer's IP information from the ARP packet.  When the ARP Reply arrives from the peer, its hardware address is retrieved and the bonding driver initiates an ARP reply to this peer assigning it to one of the slaves in the bond.  A problematic outcome of using ARP negotiation for balancing is that each time that an ARP request is broadcast it uses the hardware address of the bond.  Hence, peers learn the hardware address of the bond and the balancing of receive traffic collapses to the current slave.  This is handled by sending updates (ARP Replies) to all the peers with their individually assigned hardware address such that the traffic is redistributed.  Receive traffic is also redistributed when a new slave is added to the bond and when an inactive slave is re-activated.  The receive load is distributed sequentially (round robin) among the group of highest speed slaves in the bond.
> >
> > When a link is reconnected or a new slave joins the bond the receive traffic is redistributed among all active slaves in the bond by initiating ARP Replies with the selected MAC address to each of the clients. The updelay parameter (detailed below) must be set to a value equal or greater than the switch's forwarding delay so that the ARP Replies sent to the peers will not be blocked by the switch.
> >
> > Prerequisites:
> >
> > 1\. Ethtool support in the base drivers for retrieving the speed of each slave.
> >
> > 2\. Base driver support for setting the hardware address of a device while it is open.  This is required so that there will always be one slave in the team using the bond hardware address (the curr\_active\_slave) while having a unique hardware address for each slave in the bond.  If the curr\_active\_slave fails its hardware address is swapped with the new curr\_active\_slave that was chosen.

num\_grat\_arp, num\_unsol\_na

> Specify the number of peer notifications (gratuitous ARPs and unsolicited IPv6 Neighbor Advertisements) to be issued after a failover event.  As soon as the link is up on the new slave (possibly immediately) a peer notification is sent on the bonding device and each VLAN sub-device. This is repeated at the rate specified by peer\_notif\_delay if the number is greater than 1.
>
> The valid range is 0 - 255; the default value is 1.  These options affect the active-backup or 802.3ad (broadcast\_neighbor enabled) mode. These options were added for bonding versions 3.3.0 and 3.4.0 respectively.
>
> From Linux 3.0 and bonding version 3.7.1, these notifications are generated by the ipv4 and ipv6 code and the numbers of repetitions cannot be set independently.

packets\_per\_slave

> Specify the number of packets to transmit through a slave before moving to the next one. When set to 0 then a slave is chosen at random.
>
> The valid range is 0 - 65535; the default value is 1. This option has effect only in balance-rr mode.

peer\_notif\_delay

> Specify the delay, in milliseconds, between each peer notification (gratuitous ARP and unsolicited IPv6 Neighbor Advertisement) when they are issued after a failover event. This delay should be a multiple of the MII link monitor interval (miimon).
>
> The valid range is 0 - 300000. The default value is 0, which means to match the value of the MII link monitor interval.

- **prio**

  Slave priority. A higher number means higher priority. The primary slave has the highest priority. This option also follows the primary\_reselect rules.

  This option could only be configured via netlink, and is only valid for active-backup(1), balance-tlb (5) and balance-alb (6) mode. The valid value range is a signed 32 bit integer.

  The default value is 0.

primary

> A string (eth0, eth2, etc) specifying which slave is the primary device.  The specified device will always be the active slave while it is available.  Only when the primary is off-line will alternate devices be used.  This is useful when one slave is preferred over another, e.g., when one slave has higher throughput than another.
>
> The primary option is only valid for active-backup(1), balance-tlb (5) and balance-alb (6) mode.

primary\_reselect

> Specifies the reselection policy for the primary slave.  This affects how the primary slave is chosen to become the active slave when failure of the active slave or recovery of the primary slave occurs.  This option is designed to prevent flip-flopping between the primary slave and other slaves.  Possible values are:
>
> always or 0 (default)
>
> > The primary slave becomes the active slave whenever it comes back up.
>
> better or 1
>
> > The primary slave becomes the active slave when it comes back up, if the speed and duplex of the primary slave is better than the speed and duplex of the current active slave.
>
> failure or 2
>
> > The primary slave becomes the active slave only if the current active slave fails and the primary slave is up.
>
> The primary\_reselect setting is ignored in two cases:
>
> > If no slaves are active, the first slave to recover is made the active slave.
> >
> > When initially enslaved, the primary slave is always made the active slave.
>
> Changing the primary\_reselect policy via sysfs will cause an immediate selection of the best active slave according to the new policy.  This may or may not result in a change of the active slave, depending upon the circumstances.
>
> This option was added for bonding version 3.6.0.

tlb\_dynamic\_lb

> Specifies if dynamic shuffling of flows is enabled in tlb or alb mode. The value has no effect on any other modes.
>
> The default behavior of tlb mode is to shuffle active flows across slaves based on the load in that interval. This gives nice lb characteristics but can cause packet reordering. If re-ordering is a concern use this variable to disable flow shuffling and rely on load balancing provided solely by the hash distribution. xmit-hash-policy can be used to select the appropriate hashing for the setup.
>
> The sysfs entry can be used to change the setting per bond device and the initial value is derived from the module parameter. The sysfs entry is allowed to be changed only if the bond device is down.
>
> The default value is "1" that enables flow shuffling while value "0" disables it. This option was added in bonding driver 3.7.1

updelay

> Specifies the time, in milliseconds, to wait before enabling a slave after a link recovery has been detected.  This option is only valid for the miimon link monitor.  The updelay value should be a multiple of the miimon value; if not, it will be rounded down to the nearest multiple.  The default value is 0.

use\_carrier

> Obsolete option that previously selected between MII / ETHTOOL ioctls and netif\_carrier\_ok() to determine link state.
>
> All link state checks are now done with netif\_carrier\_ok().
>
> For backwards compatibility, this option's value may be inspected or set.  The only valid setting is 1.

xmit\_hash\_policy

> Selects the transmit hash policy to use for slave selection in balance-xor, 802.3ad, and tlb modes.  Possible values are:
>
> layer2
>
> > Uses XOR of hardware MAC addresses and packet type ID field to generate the hash. The formula is
> >
> > hash = source MAC\[5\] XOR destination MAC\[5\] XOR packet type ID slave number = hash modulo slave count
> >
> > This algorithm will place all traffic to a particular network peer on the same slave.
> >
> > This algorithm is 802.3ad compliant.
>
> layer2+3
>
> > This policy uses a combination of layer2 and layer3 protocol information to generate the hash.
> >
> > Uses XOR of hardware MAC addresses and IP addresses to generate the hash.  The formula is
> >
> > hash = source MAC\[5\] XOR destination MAC\[5\] XOR packet type ID hash = hash XOR source IP XOR destination IP hash = hash XOR (hash RSHIFT 16) hash = hash XOR (hash RSHIFT 8) And then hash is reduced modulo slave count.
> >
> > If the protocol is IPv6 then the source and destination addresses are first hashed using ipv6\_addr\_hash.
> >
> > This algorithm will place all traffic to a particular network peer on the same slave.  For non-IP traffic, the formula is the same as for the layer2 transmit hash policy.
> >
> > This policy is intended to provide a more balanced distribution of traffic than layer2 alone, especially in environments where a layer3 gateway device is required to reach most destinations.
> >
> > This algorithm is 802.3ad compliant.
>
> layer3+4
>
> > This policy uses upper layer protocol information, when available, to generate the hash.  This allows for traffic to a particular network peer to span multiple slaves, although a single connection will not span multiple slaves.
> >
> > The formula for unfragmented TCP and UDP packets is
> >
> > hash = source port, destination port (as in the header) hash = hash XOR source IP XOR destination IP hash = hash XOR (hash RSHIFT 16) hash = hash XOR (hash RSHIFT 8) hash = hash RSHIFT 1 And then hash is reduced modulo slave count.
> >
> > If the protocol is IPv6 then the source and destination addresses are first hashed using ipv6\_addr\_hash.
> >
> > For fragmented TCP or UDP packets and all other IPv4 and IPv6 protocol traffic, the source and destination port information is omitted.  For non-IP traffic, the formula is the same as for the layer2 transmit hash policy.
> >
> > This algorithm is not fully 802.3ad compliant.  A single TCP or UDP conversation containing both fragmented and unfragmented packets will see packets striped across two interfaces.  This may result in out of order delivery.  Most traffic types will not meet this criteria, as TCP rarely fragments traffic, and most UDP traffic is not involved in extended conversations.  Other implementations of 802.3ad may or may not tolerate this noncompliance.
>
> encap2+3
>
> > This policy uses the same formula as layer2+3 but it relies on skb\_flow\_dissect to obtain the header fields which might result in the use of inner headers if an encapsulation protocol is used. For example this will improve the performance for tunnel users because the packets will be distributed according to the encapsulated flows.
>
> encap3+4
>
> > This policy uses the same formula as layer3+4 but it relies on skb\_flow\_dissect to obtain the header fields which might result in the use of inner headers if an encapsulation protocol is used. For example this will improve the performance for tunnel users because the packets will be distributed according to the encapsulated flows.
>
> vlan+srcmac
>
> > This policy uses a very rudimentary vlan ID and source mac hash to load-balance traffic per-vlan, with failover should one leg fail. The intended use case is for a bond shared by multiple virtual machines, all configured to use their own vlan, to give lacp-like functionality without requiring lacp-capable switching hardware.
> >
> > The formula for the hash is simply
> >
> > hash = (vlan ID) XOR (source MAC vendor) XOR (source MAC dev)
>
> The default value is layer2.  This option was added in bonding version 2.6.3.  In earlier versions of bonding, this parameter does not exist, and the layer2 policy is the only policy.  The layer2+3 value was added for bonding version 3.2.2.

resend\_igmp

> Specifies the number of IGMP membership reports to be issued after a failover event. One membership report is issued immediately after the failover, subsequent packets are sent in each 200ms interval.
>
> The valid range is 0 - 255; the default value is 1. A value of 0 prevents the IGMP membership report from being issued in response to the failover event.
>
> This option is useful for bonding modes balance-rr (0), active-backup (1), balance-tlb (5) and balance-alb (6), in which a failover can switch the IGMP traffic from one slave to another.  Therefore a fresh IGMP report must be issued to cause the switch to forward the incoming IGMP traffic over the newly selected slave.
>
> This option was added for bonding version 3.7.0.

lp\_interval

> Specifies the number of seconds between instances where the bonding driver sends learning packets to each slaves peer switch.
>
> The valid range is 1 - 0x7fffffff; the default value is 1. This Option has effect only in balance-tlb and balance-alb modes.

<a id="rst-configuring-bonding-devices"></a>

## 3. Configuring Bonding Devices

You can configure bonding using either your distro's network initialization scripts, or manually using either iproute2 or the sysfs interface.  Distros generally use one of three packages for the network initialization scripts: initscripts, sysconfig or interfaces. Recent versions of these packages have support for bonding, while older versions do not.

We will first describe the options for configuring bonding for distros using versions of initscripts, sysconfig and interfaces with full or partial support for bonding, then provide information on enabling bonding without support from the network initialization scripts (i.e., older versions of initscripts or sysconfig).

If you're unsure whether your distro uses sysconfig, initscripts or interfaces, or don't know if it's new enough, have no fear. Determining this is fairly straightforward.

First, look for a file called interfaces in /etc/network directory. If this file is present in your system, then your system use interfaces. See Configuration with Interfaces Support.

Else, issue the command:



```text
$ rpm -qf /sbin/ifup
```

It will respond with a line of text starting with either "initscripts" or "sysconfig," followed by some numbers.  This is the package that provides your network initialization scripts.

Next, to determine if your installation supports bonding, issue the command:



```text
$ grep ifenslave /sbin/ifup
```

If this returns any matches, then your initscripts or sysconfig has support for bonding.

<a id="rst-configuration-with-sysconfig-support"></a>

### 3.1 Configuration with Sysconfig Support

This section applies to distros using a version of sysconfig with bonding support, for example, SuSE Linux Enterprise Server 9.

SuSE SLES 9's networking configuration system does support bonding, however, at this writing, the YaST system configuration front end does not provide any means to work with bonding devices. Bonding devices can be managed by hand, however, as follows.

First, if they have not already been configured, configure the slave devices.  On SLES 9, this is most easily done by running the yast2 sysconfig configuration utility.  The goal is for to create an ifcfg-id file for each slave device.  The simplest way to accomplish this is to configure the devices for DHCP (this is only to get the file ifcfg-id file created; see below for some issues with DHCP).  The name of the configuration file for each device will be of the form:



```text
ifcfg-id-xx:xx:xx:xx:xx:xx
```

Where the "xx" portion will be replaced with the digits from the device's permanent MAC address.

Once the set of ifcfg-id-xx:xx:xx:xx:xx:xx files has been created, it is necessary to edit the configuration files for the slave devices (the MAC addresses correspond to those of the slave devices). Before editing, the file will contain multiple lines, and will look something like this:



```text
BOOTPROTO='dhcp'
STARTMODE='on'
USERCTL='no'
UNIQUE='XNzu.WeZGOGF+4wE'
_nm_name='bus-pci-0001:61:01.0'
```

Change the BOOTPROTO and STARTMODE lines to the following:



```text
BOOTPROTO='none'
STARTMODE='off'
```

Do not alter the UNIQUE or \_nm\_name lines.  Remove any other lines (USERCTL, etc).

Once the ifcfg-id-xx:xx:xx:xx:xx:xx files have been modified, it's time to create the configuration file for the bonding device itself.  This file is named ifcfg-bondX, where X is the number of the bonding device to create, starting at 0.  The first such file is ifcfg-bond0, the second is ifcfg-bond1, and so on.  The sysconfig network configuration system will correctly start multiple instances of bonding.

The contents of the ifcfg-bondX file is as follows:



```text
BOOTPROTO="static"
BROADCAST="10.0.2.255"
IPADDR="10.0.2.10"
NETMASK="255.255.0.0"
NETWORK="10.0.2.0"
REMOTE_IPADDR=""
STARTMODE="onboot"
BONDING_MASTER="yes"
BONDING_MODULE_OPTS="mode=active-backup miimon=100"
BONDING_SLAVE0="eth0"
BONDING_SLAVE1="bus-pci-0000:06:08.1"
```

Replace the sample BROADCAST, IPADDR, NETMASK and NETWORK values with the appropriate values for your network.

The STARTMODE specifies when the device is brought online. The possible values are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> onboot
>
> </td>
> <td>
>
>
> The device is started at boot time.  If you're not sure, this is probably what you want.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> manual
>
> </td>
> <td>
>
>
> The device is started only when ifup is called manually.  Bonding devices may be configured this way if you do not wish them to start automatically at boot for some reason.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> hotplug
>
> </td>
> <td>
>
>
> The device is started by a hotplug event.  This is not a valid choice for a bonding device.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> off or
>
> </td>
> <td>
>
>
> The device configuration is ignored.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ignore
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> </tbody>
> </table>

The line BONDING\_MASTER='yes' indicates that the device is a bonding master device.  The only useful value is "yes."

The contents of BONDING\_MODULE\_OPTS are supplied to the instance of the bonding module for this device.  Specify the options for the bonding mode, link monitoring, and so on here.  Do not include the max\_bonds bonding parameter; this will confuse the configuration system if you have multiple bonding devices.

Finally, supply one BONDING\_SLAVEn="slave device" for each slave.  where "n" is an increasing value, one for each slave.  The "slave device" is either an interface name, e.g., "eth0", or a device specifier for the network device.  The interface name is easier to find, but the ethN names are subject to change at boot time if, e.g., a device early in the sequence has failed.  The device specifiers (bus-pci-0000:06:08.1 in the example above) specify the physical network device, and will not change unless the device's bus location changes (for example, it is moved from one PCI slot to another).  The example above uses one of each type for demonstration purposes; most configurations will choose one or the other for all slave devices.

When all configuration files have been modified or created, networking must be restarted for the configuration changes to take effect.  This can be accomplished via the following:



```text
# /etc/init.d/network restart
```

Note that the network control script (/sbin/ifdown) will remove the bonding module as part of the network shutdown processing, so it is not necessary to remove the module by hand if, e.g., the module parameters have changed.

Also, at this writing, YaST/YaST2 will not manage bonding devices (they do not show bonding interfaces on its list of network devices).  It is necessary to edit the configuration file by hand to change the bonding configuration.

Additional general options and details of the ifcfg file format can be found in an example ifcfg template file:



```text
/etc/sysconfig/network/ifcfg.template
```

Note that the template does not document the various `BONDING_*` settings described above, but does describe many of the other options.

<a id="rst-using-dhcp-with-sysconfig"></a>

### 3.1.1 Using DHCP with Sysconfig

Under sysconfig, configuring a device with BOOTPROTO='dhcp' will cause it to query DHCP for its IP address information.  At this writing, this does not function for bonding devices; the scripts attempt to obtain the device address from DHCP prior to adding any of the slave devices.  Without active slaves, the DHCP requests are not sent to the network.

<a id="rst-configuring-multiple-bonds-with-sysconfig"></a>

### 3.1.2 Configuring Multiple Bonds with Sysconfig

The sysconfig network initialization system is capable of handling multiple bonding devices.  All that is necessary is for each bonding instance to have an appropriately configured ifcfg-bondX file (as described above).  Do not specify the "max\_bonds" parameter to any instance of bonding, as this will confuse sysconfig.  If you require multiple bonding devices with identical parameters, create multiple ifcfg-bondX files.

Because the sysconfig scripts supply the bonding module options in the ifcfg-bondX file, it is not necessary to add them to the system `/etc/modules.d/*.conf` configuration files.

<a id="rst-configuration-with-initscripts-support"></a>

### 3.2 Configuration with Initscripts Support

This section applies to distros using a recent version of initscripts with bonding support, for example, Red Hat Enterprise Linux version 3 or later, Fedora, etc.  On these systems, the network initialization scripts have knowledge of bonding, and can be configured to control bonding devices.  Note that older versions of the initscripts package have lower levels of support for bonding; this will be noted where applicable.

These distros will not automatically load the network adapter driver unless the ethX device is configured with an IP address. Because of this constraint, users must manually configure a network-script file for all physical adapters that will be members of a bondX link.  Network script files are located in the directory:

/etc/sysconfig/network-scripts

The file name must be prefixed with "ifcfg-eth" and suffixed with the adapter's physical adapter number.  For example, the script for eth0 would be named /etc/sysconfig/network-scripts/ifcfg-eth0. Place the following text in the file:



```text
DEVICE=eth0
USERCTL=no
ONBOOT=yes
MASTER=bond0
SLAVE=yes
BOOTPROTO=none
```

The DEVICE= line will be different for every ethX device and must correspond with the name of the file, i.e., ifcfg-eth1 must have a device line of DEVICE=eth1.  The setting of the MASTER= line will also depend on the final bonding interface name chosen for your bond. As with other network devices, these typically start at 0, and go up one for each device, i.e., the first bonding instance is bond0, the second is bond1, and so on.

Next, create a bond network script.  The file name for this script will be /etc/sysconfig/network-scripts/ifcfg-bondX where X is the number of the bond.  For bond0 the file is named "ifcfg-bond0", for bond1 it is named "ifcfg-bond1", and so on.  Within that file, place the following text:



```text
DEVICE=bond0
IPADDR=192.168.1.1
NETMASK=255.255.255.0
NETWORK=192.168.1.0
BROADCAST=192.168.1.255
ONBOOT=yes
BOOTPROTO=none
USERCTL=no
```

Be sure to change the networking specific lines (IPADDR, NETMASK, NETWORK and BROADCAST) to match your network configuration.

For later versions of initscripts, such as that found with Fedora 7 (or later) and Red Hat Enterprise Linux version 5 (or later), it is possible, and, indeed, preferable, to specify the bonding options in the ifcfg-bond0 file, e.g. a line of the format:



```text
BONDING_OPTS="mode=active-backup arp_interval=60 arp_ip_target=192.168.1.254"
```

will configure the bond with the specified options.  The options specified in BONDING\_OPTS are identical to the bonding module parameters except for the arp\_ip\_target field when using versions of initscripts older than and 8.57 (Fedora 8) and 8.45.19 (Red Hat Enterprise Linux 5.2).  When using older versions each target should be included as a separate option and should be preceded by a '+' to indicate it should be added to the list of queried targets, e.g.,:



```text
arp_ip_target=+192.168.1.1 arp_ip_target=+192.168.1.2
```

is the proper syntax to specify multiple targets.  When specifying options via BONDING\_OPTS, it is not necessary to edit `/etc/modprobe.d/*.conf`.

For even older versions of initscripts that do not support BONDING\_OPTS, it is necessary to edit /etc/modprobe.d/<em>.conf, depending upon your distro) to load the bonding module with your desired options when the bond0 interface is brought up.  The following lines in /etc/modprobe.d/</em>.conf will load the bonding module, and select its options:

> alias bond0 bonding options bond0 mode=balance-alb miimon=100

Replace the sample parameters with the appropriate set of options for your configuration.

Finally run "/etc/rc.d/init.d/network restart" as root.  This will restart the networking subsystem and your bond link should be now up and running.

<a id="rst-using-dhcp-with-initscripts"></a>

### 3.2.1 Using DHCP with Initscripts

Recent versions of initscripts (the versions supplied with Fedora Core 3 and Red Hat Enterprise Linux 4, or later versions, are reported to work) have support for assigning IP information to bonding devices via DHCP.

To configure bonding for DHCP, configure it as described above, except replace the line "BOOTPROTO=none" with "BOOTPROTO=dhcp" and add a line consisting of "TYPE=Bonding".  Note that the TYPE value is case sensitive.

<a id="rst-configuring-multiple-bonds-with-initscripts"></a>

### 3.2.2 Configuring Multiple Bonds with Initscripts

Initscripts packages that are included with Fedora 7 and Red Hat Enterprise Linux 5 support multiple bonding interfaces by simply specifying the appropriate BONDING\_OPTS= in ifcfg-bondX where X is the number of the bond.  This support requires sysfs support in the kernel, and a bonding driver of version 3.0.0 or later.  Other configurations may not support this method for specifying multiple bonding interfaces; for those instances, see the "Configuring Multiple Bonds Manually" section, below.

<a id="rst-configuring-bonding-manually-with-iproute2"></a>

### 3.3 Configuring Bonding Manually with iproute2

This section applies to distros whose network initialization scripts (the sysconfig or initscripts package) do not have specific knowledge of bonding.  One such distro is SuSE Linux Enterprise Server version 8.

The general method for these systems is to place the bonding module parameters into a config file in /etc/modprobe.d/ (as appropriate for the installed distro), then add modprobe and/or `ip link` commands to the system's global init script.  The name of the global init script differs; for sysconfig, it is /etc/init.d/boot.local and for initscripts it is /etc/rc.d/rc.local.

For example, if you wanted to make a simple bond of two e100 devices (presumed to be eth0 and eth1), and have it persist across reboots, edit the appropriate file (/etc/init.d/boot.local or /etc/rc.d/rc.local), and add the following:



```text
modprobe bonding mode=balance-alb miimon=100
modprobe e100
ifconfig bond0 192.168.1.1 netmask 255.255.255.0 up
ip link set eth0 master bond0
ip link set eth1 master bond0
```

Replace the example bonding module parameters and bond0 network configuration (IP address, netmask, etc) with the appropriate values for your configuration.

Unfortunately, this method will not provide support for the ifup and ifdown scripts on the bond devices.  To reload the bonding configuration, it is necessary to run the initialization script, e.g.,:



```text
# /etc/init.d/boot.local
```

or:



```text
# /etc/rc.d/rc.local
```

It may be desirable in such a case to create a separate script which only initializes the bonding configuration, then call that separate script from within boot.local.  This allows for bonding to be enabled without re-running the entire global init script.

To shut down the bonding devices, it is necessary to first mark the bonding device itself as being down, then remove the appropriate device driver modules.  For our example above, you can do the following:



```text
# ifconfig bond0 down
# rmmod bonding
# rmmod e100
```

Again, for convenience, it may be desirable to create a script with these commands.

<a id="rst-configuring-multiple-bonds-manually"></a>

### 3.3.1 Configuring Multiple Bonds Manually

This section contains information on configuring multiple bonding devices with differing options for those systems whose network initialization scripts lack support for configuring multiple bonds.

If you require multiple bonding devices, but all with the same options, you may wish to use the "max\_bonds" module parameter, documented above.

To create multiple bonding devices with differing options, it is preferable to use bonding parameters exported by sysfs, documented in the section below.

For versions of bonding without sysfs support, the only means to provide multiple instances of bonding with differing options is to load the bonding driver multiple times.  Note that current versions of the sysconfig network initialization scripts handle this automatically; if your distro uses these scripts, no special action is needed.  See the section Configuring Bonding Devices, above, if you're not sure about your network initialization scripts.

To load multiple instances of the module, it is necessary to specify a different name for each instance (the module loading system requires that every loaded module, even multiple instances of the same module, have a unique name).  This is accomplished by supplying multiple sets of bonding options in `/etc/modprobe.d/*.conf`, for example:



```text
alias bond0 bonding
options bond0 -o bond0 mode=balance-rr miimon=100

alias bond1 bonding
options bond1 -o bond1 mode=balance-alb miimon=50
```

will load the bonding module two times.  The first instance is named "bond0" and creates the bond0 device in balance-rr mode with an miimon of 100.  The second instance is named "bond1" and creates the bond1 device in balance-alb mode with an miimon of 50.

In some circumstances (typically with older distributions), the above does not work, and the second bonding instance never sees its options.  In that case, the second options line can be substituted as follows:



```text
install bond1 /sbin/modprobe --ignore-install bonding -o bond1 \
                             mode=balance-alb miimon=50
```

This may be repeated any number of times, specifying a new and unique name in place of bond1 for each subsequent instance.

It has been observed that some Red Hat supplied kernels are unable to rename modules at load time (the "-o bond1" part).  Attempts to pass that option to modprobe will produce an "Operation not permitted" error. This has been reported on some Fedora Core kernels, and has been seen on RHEL 4 as well.  On kernels exhibiting this problem, it will be impossible to configure multiple bonds with differing parameters (as they are older kernels, and also lack sysfs support).

<a id="rst-configuring-bonding-manually-via-sysfs"></a>

### 3.4 Configuring Bonding Manually via Sysfs

Starting with version 3.0.0, Channel Bonding may be configured via the sysfs interface.  This interface allows dynamic configuration of all bonds in the system without unloading the module.  It also allows for adding and removing bonds at runtime.  Ifenslave is no longer required, though it is still supported.

Use of the sysfs interface allows you to use multiple bonds with different configurations without having to reload the module. It also allows you to use multiple, differently configured bonds when bonding is compiled into the kernel.

You must have the sysfs filesystem mounted to configure bonding this way.  The examples in this document assume that you are using the standard mount point for sysfs, e.g. /sys.  If your sysfs filesystem is mounted elsewhere, you will need to adjust the example paths accordingly.

<a id="rst-creating-and-destroying-bonds"></a>

### Creating and Destroying Bonds

To add a new bond foo:



```text
# echo +foo > /sys/class/net/bonding_masters
```

To remove an existing bond bar:



```text
# echo -bar > /sys/class/net/bonding_masters
```

To show all existing bonds:



```text
# cat /sys/class/net/bonding_masters
```

> [!NOTE]
>
> due to 4K size limitation of sysfs files, this list may be truncated if you have more than a few hundred bonds.  This is unlikely to occur under normal operating conditions.

<a id="rst-adding-and-removing-slaves"></a>

### Adding and Removing Slaves

Interfaces may be enslaved to a bond using the file /sys/class/net/&lt;bond&gt;/bonding/slaves.  The semantics for this file are the same as for the bonding\_masters file.

To enslave interface eth0 to bond bond0:



```text
# ifconfig bond0 up
# echo +eth0 > /sys/class/net/bond0/bonding/slaves
```

To free slave eth0 from bond bond0:



```text
# echo -eth0 > /sys/class/net/bond0/bonding/slaves
```

When an interface is enslaved to a bond, symlinks between the two are created in the sysfs filesystem.  In this case, you would get /sys/class/net/bond0/slave\_eth0 pointing to /sys/class/net/eth0, and /sys/class/net/eth0/master pointing to /sys/class/net/bond0.

This means that you can tell quickly whether or not an interface is enslaved by looking for the master symlink.  Thus: \# echo -eth0 &gt; /sys/class/net/eth0/master/bonding/slaves will free eth0 from whatever bond it is enslaved to, regardless of the name of the bond interface.

<a id="rst-changing-a-bond-s-configuration"></a>

### Changing a Bond's Configuration

Each bond may be configured individually by manipulating the files located in /sys/class/net/&lt;bond name&gt;/bonding

The names of these files correspond directly with the command- line parameters described elsewhere in this file, and, with the exception of arp\_ip\_target, they accept the same values.  To see the current setting, simply cat the appropriate file.

A few examples will be given here; for specific usage guidelines for each parameter, see the appropriate section in this document.

To configure bond0 for balance-alb mode:



```text
# ifconfig bond0 down
# echo 6 > /sys/class/net/bond0/bonding/mode
- or -
# echo balance-alb > /sys/class/net/bond0/bonding/mode
```

> [!NOTE]
>
> The bond interface must be down before the mode can be changed.

To enable MII monitoring on bond0 with a 1 second interval:



```text
# echo 1000 > /sys/class/net/bond0/bonding/miimon
```

> [!NOTE]
>
> If ARP monitoring is enabled, it will disabled when MII monitoring is enabled, and vice-versa.

To add ARP targets:



```text
# echo +192.168.0.100 > /sys/class/net/bond0/bonding/arp_ip_target
# echo +192.168.0.101 > /sys/class/net/bond0/bonding/arp_ip_target
```

> [!NOTE]
>
> up to 16 target addresses may be specified.

To remove an ARP target:



```text
# echo -192.168.0.100 > /sys/class/net/bond0/bonding/arp_ip_target
```

To configure the interval between learning packet transmits:



```text
# echo 12 > /sys/class/net/bond0/bonding/lp_interval
```

> [!NOTE]
>
> the lp\_interval is the number of seconds between instances where the bonding driver sends learning packets to each slaves peer switch.  The default interval is 1 second.

<a id="rst-example-configuration"></a>

### Example Configuration

We begin with the same example that is shown in section 3.3, executed with sysfs, and without using ifenslave.

To make a simple bond of two e100 devices (presumed to be eth0 and eth1), and have it persist across reboots, edit the appropriate file (/etc/init.d/boot.local or /etc/rc.d/rc.local), and add the following:



```text
modprobe bonding
modprobe e100
echo balance-alb > /sys/class/net/bond0/bonding/mode
ifconfig bond0 192.168.1.1 netmask 255.255.255.0 up
echo 100 > /sys/class/net/bond0/bonding/miimon
echo +eth0 > /sys/class/net/bond0/bonding/slaves
echo +eth1 > /sys/class/net/bond0/bonding/slaves
```

To add a second bond, with two e1000 interfaces in active-backup mode, using ARP monitoring, add the following lines to your init script:



```text
modprobe e1000
echo +bond1 > /sys/class/net/bonding_masters
echo active-backup > /sys/class/net/bond1/bonding/mode
ifconfig bond1 192.168.2.1 netmask 255.255.255.0 up
echo +192.168.2.100 /sys/class/net/bond1/bonding/arp_ip_target
echo 2000 > /sys/class/net/bond1/bonding/arp_interval
echo +eth2 > /sys/class/net/bond1/bonding/slaves
echo +eth3 > /sys/class/net/bond1/bonding/slaves
```

<a id="rst-configuration-with-interfaces-support"></a>

### 3.5 Configuration with Interfaces Support

This section applies to distros which use /etc/network/interfaces file to describe network interface configuration, most notably Debian and its derivatives.

The ifup and ifdown commands on Debian don't support bonding out of the box. The ifenslave-2.6 package should be installed to provide bonding support.  Once installed, this package will provide `bond-*` options to be used into /etc/network/interfaces.

Note that ifenslave-2.6 package will load the bonding module and use the ifenslave command when appropriate.

<a id="rst-example-configurations"></a>

### Example Configurations

In /etc/network/interfaces, the following stanza will configure bond0, in active-backup mode, with eth0 and eth1 as slaves:



```text
auto bond0
iface bond0 inet dhcp
        bond-slaves eth0 eth1
        bond-mode active-backup
        bond-miimon 100
        bond-primary eth0 eth1
```

If the above configuration doesn't work, you might have a system using upstart for system startup. This is most notably true for recent Ubuntu versions. The following stanza in /etc/network/interfaces will produce the same result on those systems:



```text
auto bond0
iface bond0 inet dhcp
        bond-slaves none
        bond-mode active-backup
        bond-miimon 100

auto eth0
iface eth0 inet manual
        bond-master bond0
        bond-primary eth0 eth1

auto eth1
iface eth1 inet manual
        bond-master bond0
        bond-primary eth0 eth1
```

For a full list of `bond-*` supported options in /etc/network/interfaces and some more advanced examples tailored to you particular distros, see the files in /usr/share/doc/ifenslave-2.6.

<a id="rst-overriding-configuration-for-special-cases"></a>

### 3.6 Overriding Configuration for Special Cases

When using the bonding driver, the physical port which transmits a frame is typically selected by the bonding driver, and is not relevant to the user or system administrator.  The output port is simply selected using the policies of the selected bonding mode.  On occasion however, it is helpful to direct certain classes of traffic to certain physical interfaces on output to implement slightly more complex policies.  For example, to reach a web server over a bonded interface in which eth0 connects to a private network, while eth1 connects via a public network, it may be desirous to bias the bond to send said traffic over eth0 first, using eth1 only as a fall back, while all other traffic can safely be sent over either interface.  Such configurations may be achieved using the traffic control utilities inherent in linux.

By default the bonding driver is multiqueue aware and 16 queues are created when the driver initializes (see [Documentation/networking/multiqueue.rst](/kernel/internals/networking/multiqueue.md) for details).  If more or less queues are desired the module parameter tx\_queues can be used to change this value.  There is no sysfs parameter available as the allocation is done at module init time.

The output of the file /proc/net/bonding/bondX has changed so the output Queue ID is now printed for each slave:



```text
Bonding Mode: fault-tolerance (active-backup)
Primary Slave: None
Currently Active Slave: eth0
MII Status: up
MII Polling Interval (ms): 0
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eth0
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:1a:a0:12:8f:cb
Slave queue ID: 0

Slave Interface: eth1
MII Status: up
Link Failure Count: 0
Permanent HW addr: 00:1a:a0:12:8f:cc
Slave queue ID: 2
```

The queue\_id for a slave can be set using the command:



```text
# echo "eth1:2" > /sys/class/net/bond0/bonding/queue_id
```

Any interface that needs a queue\_id set should set it with multiple calls like the one above until proper priorities are set for all interfaces.  On distributions that allow configuration via initscripts, multiple 'queue\_id' arguments can be added to BONDING\_OPTS to set all needed slave queues.

These queue id's can be used in conjunction with the tc utility to configure a multiqueue qdisc and filters to bias certain traffic to transmit on certain slave devices.  For instance, say we wanted, in the above configuration to force all traffic bound to 192.168.1.100 to use eth1 in the bond as its output device. The following commands would accomplish this:



```text
# tc qdisc add dev bond0 handle 1 root multiq

# tc filter add dev bond0 protocol ip parent 1: prio 1 u32 match ip \
        dst 192.168.1.100 action skbedit queue_mapping 2
```

These commands tell the kernel to attach a multiqueue queue discipline to the bond0 interface and filter traffic enqueued to it, such that packets with a dst ip of 192.168.1.100 have their output queue mapping value overwritten to 2. This value is then passed into the driver, causing the normal output path selection policy to be overridden, selecting instead qid 2, which maps to eth1.

Note that qid values begin at 1.  Qid 0 is reserved to initiate to the driver that normal output policy selection should take place.  One benefit to simply leaving the qid for a slave to 0 is the multiqueue awareness in the bonding driver that is now present.  This awareness allows tc filters to be placed on slave devices as well as bond devices and the bonding driver will simply act as a pass-through for selecting output queues on the slave device rather than output port selection.

This feature first appeared in bonding driver version 3.7.0 and support for output slave selection was limited to round-robin and active-backup modes.

<a id="rst-configuring-lacp-for-802-3ad-mode-in-a-more-secure-way"></a>

### 3.7 Configuring LACP for 802.3ad mode in a more secure way

When using 802.3ad bonding mode, the Actor (host) and Partner (switch) exchange LACPDUs.  These LACPDUs cannot be sniffed, because they are destined to link local mac addresses (which switches/bridges are not supposed to forward).  However, most of the values are easily predictable or are simply the machine's MAC address (which is trivially known to all other hosts in the same L2).  This implies that other machines in the L2 domain can spoof LACPDU packets from other hosts to the switch and potentially cause mayhem by joining (from the point of view of the switch) another machine's aggregate, thus receiving a portion of that hosts incoming traffic and / or spoofing traffic from that machine themselves (potentially even successfully terminating some portion of flows). Though this is not a likely scenario, one could avoid this possibility by simply configuring few bonding parameters:

> - **(a)** ad\_actor\_system : You can set a random mac-address that can be used for these LACPDU exchanges. The value can not be either NULL or Multicast. Also it's preferable to set the local-admin bit. Following shell code generates a random mac-address as described above:
>
>
>
>   ```text
>   # sys_mac_addr=$(printf '%02x:%02x:%02x:%02x:%02x:%02x' \
>                            $(( (RANDOM & 0xFE) | 0x02 )) \
>                            $(( RANDOM & 0xFF )) \
>                            $(( RANDOM & 0xFF )) \
>                            $(( RANDOM & 0xFF )) \
>                            $(( RANDOM & 0xFF )) \
>                            $(( RANDOM & 0xFF )))
>   # echo $sys_mac_addr > /sys/class/net/bond0/bonding/ad_actor_system
>   ```
>
> - **(b)** ad\_actor\_sys\_prio : Randomize the system priority. The default value is 65535, but system can take the value from 1 - 65535. Following shell code generates random priority and sets it:
>
>
>
>   ```text
>   # sys_prio=$(( 1 + RANDOM + RANDOM ))
>   # echo $sys_prio > /sys/class/net/bond0/bonding/ad_actor_sys_prio
>   ```
>
> - **(c)** ad\_user\_port\_key : Use the user portion of the port-key. The default keeps this empty. These are the upper 10 bits of the port-key and value ranges from 0 - 1023. Following shell code generates these 10 bits and sets it:
>
>
>
>   ```text
>   # usr_port_key=$(( RANDOM & 0x3FF ))
>   # echo $usr_port_key > /sys/class/net/bond0/bonding/ad_user_port_key
>   ```

<a id="rst-querying-bonding-configuration"></a>

## 4 Querying Bonding Configuration

<a id="rst-bonding-configuration"></a>

### 4.1 Bonding Configuration

Each bonding device has a read-only file residing in the /proc/net/bonding directory.  The file contents include information about the bonding configuration, options and state of each slave.

For example, the contents of /proc/net/bonding/bond0 after the driver is loaded with parameters of mode=0 and miimon=1000 is generally as follows:



```text
Ethernet Channel Bonding Driver: 2.6.1 (October 29, 2004)
Bonding Mode: load balancing (round-robin)
Currently Active Slave: eth0
MII Status: up
MII Polling Interval (ms): 1000
Up Delay (ms): 0
Down Delay (ms): 0

Slave Interface: eth1
MII Status: up
Link Failure Count: 1

Slave Interface: eth0
MII Status: up
Link Failure Count: 1
```

The precise format and contents will change depending upon the bonding configuration, state, and version of the bonding driver.

<a id="rst-network-configuration"></a>

### 4.2 Network configuration

The network configuration can be inspected using the ifconfig command.  Bonding devices will have the MASTER flag set; Bonding slave devices will have the SLAVE flag set.  The ifconfig output does not contain information on which slaves are associated with which masters.

In the example below, the bond0 interface is the master (MASTER) while eth0 and eth1 are slaves (SLAVE). Notice all slaves of bond0 have the same MAC address (HWaddr) as bond0 for all modes except TLB and ALB that require a unique MAC address for each slave:



```text
# /sbin/ifconfig
bond0     Link encap:Ethernet  HWaddr 00:C0:F0:1F:37:B4
          inet addr:XXX.XXX.XXX.YYY  Bcast:XXX.XXX.XXX.255  Mask:255.255.252.0
          UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1
          RX packets:7224794 errors:0 dropped:0 overruns:0 frame:0
          TX packets:3286647 errors:1 dropped:0 overruns:1 carrier:0
          collisions:0 txqueuelen:0

eth0      Link encap:Ethernet  HWaddr 00:C0:F0:1F:37:B4
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
          RX packets:3573025 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1643167 errors:1 dropped:0 overruns:1 carrier:0
          collisions:0 txqueuelen:100
          Interrupt:10 Base address:0x1080

eth1      Link encap:Ethernet  HWaddr 00:C0:F0:1F:37:B4
          UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1
          RX packets:3651769 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1643480 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          Interrupt:9 Base address:0x1400
```

<a id="rst-switch-configuration"></a>

## 5. Switch Configuration

For this section, "switch" refers to whatever system the bonded devices are directly connected to (i.e., where the other end of the cable plugs into).  This may be an actual dedicated switch device, or it may be another regular system (e.g., another computer running Linux),

The active-backup, balance-tlb and balance-alb modes do not require any specific configuration of the switch.

The 802.3ad mode requires that the switch have the appropriate ports configured as an 802.3ad aggregation.  The precise method used to configure this varies from switch to switch, but, for example, a Cisco 3550 series switch requires that the appropriate ports first be grouped together in a single etherchannel instance, then that etherchannel is set to mode "lacp" to enable 802.3ad (instead of standard EtherChannel).

The balance-rr, balance-xor and broadcast modes generally require that the switch have the appropriate ports grouped together. The nomenclature for such a group differs between switches, it may be called an "etherchannel" (as in the Cisco example, above), a "trunk group" or some other similar variation.  For these modes, each switch will also have its own configuration options for the switch's transmit policy to the bond.  Typical choices include XOR of either the MAC or IP addresses.  The transmit policy of the two peers does not need to match.  For these three modes, the bonding mode really selects a transmit policy for an EtherChannel group; all three will interoperate with another EtherChannel group.

<a id="rst-q-vlan-support"></a>

## 6. 802.1q VLAN Support

It is possible to configure VLAN devices over a bond interface using the 8021q driver.  However, only packets coming from the 8021q driver and passing through bonding will be tagged by default.  Self generated packets, for example, bonding's learning packets or ARP packets generated by either ALB mode or the ARP monitor mechanism, are tagged internally by bonding itself.  As a result, bonding must "learn" the VLAN IDs configured above it, and use those IDs to tag self generated packets.

For reasons of simplicity, and to support the use of adapters that can do VLAN hardware acceleration offloading, the bonding interface declares itself as fully hardware offloading capable, it gets the add\_vid/kill\_vid notifications to gather the necessary information, and it propagates those actions to the slaves.  In case of mixed adapter types, hardware accelerated tagged packets that should go through an adapter that is not offloading capable are "un-accelerated" by the bonding driver so the VLAN tag sits in the regular location.

VLAN interfaces <em>must</em> be added on top of a bonding interface only after enslaving at least one slave.  The bonding interface has a hardware address of 00:00:00:00:00:00 until the first slave is added. If the VLAN interface is created prior to the first enslavement, it would pick up the all-zeroes hardware address.  Once the first slave is attached to the bond, the bond device itself will pick up the slave's hardware address, which is then available for the VLAN device.

Also, be aware that a similar problem can occur if all slaves are released from a bond that still has one or more VLAN interfaces on top of it.  When a new slave is added, the bonding interface will obtain its hardware address from the first slave, which might not match the hardware address of the VLAN interfaces (which was ultimately copied from an earlier slave).

There are two methods to ensure that the VLAN device operates with the correct hardware address if all slaves are removed from a bond interface:

1. Remove all VLAN interfaces then recreate them

2\. Set the bonding interface's hardware address so that it matches the hardware address of the VLAN interfaces.

Note that changing a VLAN interface's HW address would set the underlying device -- i.e. the bonding interface -- to promiscuous mode, which might not be what you want.

<a id="rst-link-monitoring"></a>

## 7. Link Monitoring

The bonding driver at present supports two schemes for monitoring a slave device's link state: the ARP monitor and the MII monitor.

At the present time, due to implementation restrictions in the bonding driver itself, it is not possible to enable both ARP and MII monitoring simultaneously.

<a id="rst-arp-monitor-operation"></a>

### 7.1 ARP Monitor Operation

The ARP monitor operates as its name suggests: it sends ARP queries to one or more designated peer systems on the network, and uses the response as an indication that the link is operating.  This gives some assurance that traffic is actually flowing to and from one or more peers on the local network.

<a id="rst-configuring-multiple-arp-targets"></a>

### 7.2 Configuring Multiple ARP Targets

While ARP monitoring can be done with just one target, it can be useful in a High Availability setup to have several targets to monitor.  In the case of just one target, the target itself may go down or have a problem making it unresponsive to ARP requests.  Having an additional target (or several) increases the reliability of the ARP monitoring.

Multiple ARP targets must be separated by commas as follows:



```text
# example options for ARP monitoring with three targets
alias bond0 bonding
options bond0 arp_interval=60 arp_ip_target=192.168.0.1,192.168.0.3,192.168.0.9
```

For just a single target the options would resemble:



```text
# example options for ARP monitoring with one target
alias bond0 bonding
options bond0 arp_interval=60 arp_ip_target=192.168.0.100
```

<a id="rst-mii-monitor-operation"></a>

### 7.3 MII Monitor Operation

The MII monitor monitors only the carrier state of the local network interface.  It accomplishes this in one of three ways: by depending upon the device driver to maintain its carrier state, by querying the device's MII registers, or by making an ethtool query to the device.

The MII monitor relies on the driver for carrier state information (via the netif\_carrier subsystem).

<a id="rst-potential-sources-of-trouble"></a>

## 8. Potential Sources of Trouble

<a id="rst-adventures-in-routing"></a>

### 8.1 Adventures in Routing

When bonding is configured, it is important that the slave devices not have routes that supersede routes of the master (or, generally, not have routes at all).  For example, suppose the bonding device bond0 has two slaves, eth0 and eth1, and the routing table is as follows:



```text
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.0.0.0        0.0.0.0         255.255.0.0     U        40 0          0 eth0
10.0.0.0        0.0.0.0         255.255.0.0     U        40 0          0 eth1
10.0.0.0        0.0.0.0         255.255.0.0     U        40 0          0 bond0
127.0.0.0       0.0.0.0         255.0.0.0       U        40 0          0 lo
```

This routing configuration will likely still update the receive/transmit times in the driver (needed by the ARP monitor), but may bypass the bonding driver (because outgoing traffic to, in this case, another host on network 10 would use eth0 or eth1 before bond0).

The ARP monitor (and ARP itself) may become confused by this configuration, because ARP requests (generated by the ARP monitor) will be sent on one interface (bond0), but the corresponding reply will arrive on a different interface (eth0).  This reply looks to ARP as an unsolicited ARP reply (because ARP matches replies on an interface basis), and is discarded.  The MII monitor is not affected by the state of the routing table.

The solution here is simply to ensure that slaves do not have routes of their own, and if for some reason they must, those routes do not supersede routes of their master.  This should generally be the case, but unusual configurations or errant manual or automatic static route additions may cause trouble.

<a id="rst-ethernet-device-renaming"></a>

### 8.2 Ethernet Device Renaming

On systems with network configuration scripts that do not associate physical devices directly with network interface names (so that the same physical device always has the same "ethX" name), it may be necessary to add some special logic to config files in /etc/modprobe.d/.

For example, given a modules.conf containing the following:



```text
alias bond0 bonding
options bond0 mode=some-mode miimon=50
alias eth0 tg3
alias eth1 tg3
alias eth2 e1000
alias eth3 e1000
```

If neither eth0 and eth1 are slaves to bond0, then when the bond0 interface comes up, the devices may end up reordered.  This happens because bonding is loaded first, then its slave device's drivers are loaded next.  Since no other drivers have been loaded, when the e1000 driver loads, it will receive eth0 and eth1 for its devices, but the bonding configuration tries to enslave eth2 and eth3 (which may later be assigned to the tg3 devices).

Adding the following:



```text
add above bonding e1000 tg3
```

causes modprobe to load e1000 then tg3, in that order, when bonding is loaded.  This command is fully documented in the modules.conf manual page.

On systems utilizing modprobe an equivalent problem can occur. In this case, the following can be added to config files in /etc/modprobe.d/ as:



```text
softdep bonding pre: tg3 e1000
```

This will load tg3 and e1000 modules before loading the bonding one. Full documentation on this can be found in the modprobe.d and modprobe manual pages.

<a id="rst-snmp-agents"></a>

## 9. SNMP agents

If running SNMP agents, the bonding driver should be loaded before any network drivers participating in a bond.  This requirement is due to the interface index (ipAdEntIfIndex) being associated to the first interface found with a given IP address.  That is, there is only one ipAdEntIfIndex for each IP address.  For example, if eth0 and eth1 are slaves of bond0 and the driver for eth0 is loaded before the bonding driver, the interface for the IP address will be associated with the eth0 interface.  This configuration is shown below, the IP address 192.168.1.1 has an interface index of 2 which indexes to eth0 in the ifDescr table (ifDescr.2).



```text
interfaces.ifTable.ifEntry.ifDescr.1 = lo
interfaces.ifTable.ifEntry.ifDescr.2 = eth0
interfaces.ifTable.ifEntry.ifDescr.3 = eth1
interfaces.ifTable.ifEntry.ifDescr.4 = eth2
interfaces.ifTable.ifEntry.ifDescr.5 = eth3
interfaces.ifTable.ifEntry.ifDescr.6 = bond0
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.10.10.10.10 = 5
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.192.168.1.1 = 2
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.10.74.20.94 = 4
ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.127.0.0.1 = 1
```

This problem is avoided by loading the bonding driver before any network drivers participating in a bond.  Below is an example of loading the bonding driver first, the IP address 192.168.1.1 is correctly associated with ifDescr.2.

> interfaces.ifTable.ifEntry.ifDescr.1 = lo interfaces.ifTable.ifEntry.ifDescr.2 = bond0 interfaces.ifTable.ifEntry.ifDescr.3 = eth0 interfaces.ifTable.ifEntry.ifDescr.4 = eth1 interfaces.ifTable.ifEntry.ifDescr.5 = eth2 interfaces.ifTable.ifEntry.ifDescr.6 = eth3 ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.10.10.10.10 = 6 ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.192.168.1.1 = 2 ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.10.74.20.94 = 5 ip.ipAddrTable.ipAddrEntry.ipAdEntIfIndex.127.0.0.1 = 1

While some distributions may not report the interface name in ifDescr, the association between the IP address and IfIndex remains and SNMP functions such as Interface\_Scan\_Next will report that association.

<a id="rst-promiscuous-mode"></a>

## 10. Promiscuous mode

When running network monitoring tools, e.g., tcpdump, it is common to enable promiscuous mode on the device, so that all traffic is seen (instead of seeing only traffic destined for the local host). The bonding driver handles promiscuous mode changes to the bonding master device (e.g., bond0), and propagates the setting to the slave devices.

For the balance-rr, balance-xor, broadcast, and 802.3ad modes, the promiscuous mode setting is propagated to all slaves.

For the active-backup, balance-tlb and balance-alb modes, the promiscuous mode setting is propagated only to the active slave.

For balance-tlb mode, the active slave is the slave currently receiving inbound traffic.

For balance-alb mode, the active slave is the slave used as a "primary."  This slave is used for mode-specific control traffic, for sending to peers that are unassigned or if the load is unbalanced.

For the active-backup, balance-tlb and balance-alb modes, when the active slave changes (e.g., due to a link failure), the promiscuous setting will be propagated to the new active slave.

<a id="rst-configuring-bonding-for-high-availability"></a>

## 11. Configuring Bonding for High Availability

High Availability refers to configurations that provide maximum network availability by having redundant or backup devices, links or switches between the host and the rest of the world.  The goal is to provide the maximum availability of network connectivity (i.e., the network always works), even though other configurations could provide higher throughput.

<a id="rst-high-availability-in-a-single-switch-topology"></a>

### 11.1 High Availability in a Single Switch Topology

If two hosts (or a host and a single switch) are directly connected via multiple physical links, then there is no availability penalty to optimizing for maximum bandwidth.  In this case, there is only one switch (or peer), so if it fails, there is no alternative access to fail over to.  Additionally, the bonding load balance modes support link monitoring of their members, so if individual links fail, the load will be rebalanced across the remaining devices.

See Section 12, "Configuring Bonding for Maximum Throughput" for information on configuring bonding with one peer device.

<a id="rst-high-availability-in-a-multiple-switch-topology"></a>

### 11.2 High Availability in a Multiple Switch Topology

With multiple switches, the configuration of bonding and the network changes dramatically.  In multiple switch topologies, there is a trade off between network availability and usable bandwidth.

Below is a sample network, configured to maximize the availability of the network:



```text
      |                                     |
      |port3                           port3|
+-----+----+                          +-----+----+
|          |port2       ISL      port2|          |
| switch A +--------------------------+ switch B |
|          |                          |          |
+-----+----+                          +-----++---+
      |port1                           port1|
      |             +-------+               |
      +-------------+ host1 +---------------+
               eth0 +-------+ eth1
```

In this configuration, there is a link between the two switches (ISL, or inter switch link), and multiple ports connecting to the outside world ("port3" on each switch).  There is no technical reason that this could not be extended to a third switch.

<a id="rst-ha-bonding-mode-selection-for-multiple-switch-topology"></a>

### 11.2.1 HA Bonding Mode Selection for Multiple Switch Topology

In a topology such as the example above, the active-backup and broadcast modes are the only useful bonding modes when optimizing for availability; the other modes require all links to terminate on the same peer for them to behave rationally.

- **active-backup:**

  This is generally the preferred mode, particularly if the switches have an ISL and play together well.  If the network configuration is such that one switch is specifically a backup switch (e.g., has lower capacity, higher cost, etc), then the primary option can be used to ensure that the preferred link is always used when it is available.

- **broadcast:**

  This mode is really a special purpose mode, and is suitable only for very specific needs.  For example, if the two switches are not connected (no ISL), and the networks beyond them are totally independent.  In this case, if it is necessary for some specific one-way traffic to reach both independent networks, then the broadcast mode may be suitable.

<a id="rst-ha-link-monitoring-selection-for-multiple-switch-topology"></a>

### 11.2.2 HA Link Monitoring Selection for Multiple Switch Topology

The choice of link monitoring ultimately depends upon your switch.  If the switch can reliably fail ports in response to other failures, then either the MII or ARP monitors should work.  For example, in the above example, if the "port3" link fails at the remote end, the MII monitor has no direct means to detect this.  The ARP monitor could be configured with a target at the remote end of port3, thus detecting that failure without switch support.

In general, however, in a multiple switch topology, the ARP monitor can provide a higher level of reliability in detecting end to end connectivity failures (which may be caused by the failure of any individual component to pass traffic for any reason).  Additionally, the ARP monitor should be configured with multiple targets (at least one for each switch in the network).  This will ensure that, regardless of which switch is active, the ARP monitor has a suitable target to query.

Note, also, that of late many switches now support a functionality generally referred to as "trunk failover."  This is a feature of the switch that causes the link state of a particular switch port to be set down (or up) when the state of another switch port goes down (or up). Its purpose is to propagate link failures from logically "exterior" ports to the logically "interior" ports that bonding is able to monitor via miimon.  Availability and configuration for trunk failover varies by switch, but this can be a viable alternative to the ARP monitor when using suitable switches.

<a id="rst-configuring-bonding-for-maximum-throughput"></a>

## 12. Configuring Bonding for Maximum Throughput

<a id="rst-maximizing-throughput-in-a-single-switch-topology"></a>

### 12.1 Maximizing Throughput in a Single Switch Topology

In a single switch configuration, the best method to maximize throughput depends upon the application and network environment.  The various load balancing modes each have strengths and weaknesses in different environments, as detailed below.

For this discussion, we will break down the topologies into two categories.  Depending upon the destination of most traffic, we categorize them into either "gatewayed" or "local" configurations.

In a gatewayed configuration, the "switch" is acting primarily as a router, and the majority of traffic passes through this router to other networks.  An example would be the following:



```text
+----------+                     +----------+
|          |eth0            port1|          | to other networks
| Host A   +---------------------+ router   +------------------->
|          +---------------------+          | Hosts B and C are out
|          |eth1            port2|          | here somewhere
+----------+                     +----------+
```

The router may be a dedicated router device, or another host acting as a gateway.  For our discussion, the important point is that the majority of traffic from Host A will pass through the router to some other network before reaching its final destination.

In a gatewayed network configuration, although Host A may communicate with many other systems, all of its traffic will be sent and received via one other peer on the local network, the router.

Note that the case of two systems connected directly via multiple physical links is, for purposes of configuring bonding, the same as a gatewayed configuration.  In that case, it happens that all traffic is destined for the "gateway" itself, not some other network beyond the gateway.

In a local configuration, the "switch" is acting primarily as a switch, and the majority of traffic passes through this switch to reach other stations on the same network.  An example would be the following:



```text
+----------+            +----------+       +--------+
|          |eth0   port1|          +-------+ Host B |
|  Host A  +------------+  switch  |port3  +--------+
|          +------------+          |                  +--------+
|          |eth1   port2|          +------------------+ Host C |
+----------+            +----------+port4             +--------+
```

Again, the switch may be a dedicated switch device, or another host acting as a gateway.  For our discussion, the important point is that the majority of traffic from Host A is destined for other hosts on the same local network (Hosts B and C in the above example).

In summary, in a gatewayed configuration, traffic to and from the bonded device will be to the same MAC level peer on the network (the gateway itself, i.e., the router), regardless of its final destination.  In a local configuration, traffic flows directly to and from the final destinations, thus, each destination (Host B, Host C) will be addressed directly by their individual MAC addresses.

This distinction between a gatewayed and a local network configuration is important because many of the load balancing modes available use the MAC addresses of the local network source and destination to make load balancing decisions.  The behavior of each mode is described below.

<a id="rst-mt-bonding-mode-selection-for-single-switch-topology"></a>

### 12.1.1 MT Bonding Mode Selection for Single Switch Topology

This configuration is the easiest to set up and to understand, although you will have to decide which bonding mode best suits your needs.  The trade offs for each mode are detailed below:

- **balance-rr:**

  This mode is the only mode that will permit a single TCP/IP connection to stripe traffic across multiple interfaces. It is therefore the only mode that will allow a single TCP/IP stream to utilize more than one interface's worth of throughput.  This comes at a cost, however: the striping generally results in peer systems receiving packets out of order, causing TCP/IP's congestion control system to kick in, often by retransmitting segments.

  It is possible to adjust TCP/IP's congestion limits by altering the net.ipv4.tcp\_reordering sysctl parameter.  The usual default value is 3. But keep in mind TCP stack is able to automatically increase this when it detects reorders.

  Note that the fraction of packets that will be delivered out of order is highly variable, and is unlikely to be zero.  The level of reordering depends upon a variety of factors, including the networking interfaces, the switch, and the topology of the configuration.  Speaking in general terms, higher speed network cards produce more reordering (due to factors such as packet coalescing), and a "many to many" topology will reorder at a higher rate than a "many slow to one fast" configuration.

  Many switches do not support any modes that stripe traffic (instead choosing a port based upon IP or MAC level addresses); for those devices, traffic for a particular connection flowing through the switch to a balance-rr bond will not utilize greater than one interface's worth of bandwidth.

  If you are utilizing protocols other than TCP/IP, UDP for example, and your application can tolerate out of order delivery, then this mode can allow for single stream datagram performance that scales near linearly as interfaces are added to the bond.

  This mode requires the switch to have the appropriate ports configured for "etherchannel" or "trunking."

- **active-backup:**

  There is not much advantage in this network topology to the active-backup mode, as the inactive backup devices are all connected to the same peer as the primary.  In this case, a load balancing mode (with link monitoring) will provide the same level of network availability, but with increased available bandwidth.  On the plus side, active-backup mode does not require any configuration of the switch, so it may have value if the hardware available does not support any of the load balance modes.

- **balance-xor:**

  This mode will limit traffic such that packets destined for specific peers will always be sent over the same interface.  Since the destination is determined by the MAC addresses involved, this mode works best in a "local" network configuration (as described above), with destinations all on the same local network.  This mode is likely to be suboptimal if all your traffic is passed through a single router (i.e., a "gatewayed" network configuration, as described above).

  As with balance-rr, the switch ports need to be configured for "etherchannel" or "trunking."

- **broadcast:**

  Like active-backup, there is not much advantage to this mode in this type of network topology.

- **802.3ad:**

  This mode can be a good choice for this type of network topology.  The 802.3ad mode is an IEEE standard, so all peers that implement 802.3ad should interoperate well.  The 802.3ad protocol includes automatic configuration of the aggregates, so minimal manual configuration of the switch is needed (typically only to designate that some set of devices is available for 802.3ad).  The 802.3ad standard also mandates that frames be delivered in order (within certain limits), so in general single connections will not see misordering of packets.  The 802.3ad mode does have some drawbacks: the standard mandates that all devices in the aggregate operate at the same speed and duplex.  Also, as with all bonding load balance modes other than balance-rr, no single connection will be able to utilize more than a single interface's worth of bandwidth.

  Additionally, the linux bonding 802.3ad implementation distributes traffic by peer (using an XOR of MAC addresses and packet type ID), so in a "gatewayed" configuration, all outgoing traffic will generally use the same device.  Incoming traffic may also end up on a single device, but that is dependent upon the balancing policy of the peer's 802.3ad implementation.  In a "local" configuration, traffic will be distributed across the devices in the bond.

  Finally, the 802.3ad mode mandates the use of the MII monitor, therefore, the ARP monitor is not available in this mode.

- **balance-tlb:**

  The balance-tlb mode balances outgoing traffic by peer. Since the balancing is done according to MAC address, in a "gatewayed" configuration (as described above), this mode will send all traffic across a single device.  However, in a "local" network configuration, this mode balances multiple local network peers across devices in a vaguely intelligent manner (not a simple XOR as in balance-xor or 802.3ad mode), so that mathematically unlucky MAC addresses (i.e., ones that XOR to the same value) will not all "bunch up" on a single interface.

  Unlike 802.3ad, interfaces may be of differing speeds, and no special switch configuration is required.  On the down side, in this mode all incoming traffic arrives over a single interface, this mode requires certain ethtool support in the network device driver of the slave interfaces, and the ARP monitor is not available.

- **balance-alb:**

  This mode is everything that balance-tlb is, and more. It has all of the features (and restrictions) of balance-tlb, and will also balance incoming traffic from local network peers (as described in the Bonding Module Options section, above).

  The only additional down side to this mode is that the network device driver must support changing the hardware address while the device is open.

<a id="rst-mt-link-monitoring-for-single-switch-topology"></a>

### 12.1.2 MT Link Monitoring for Single Switch Topology

The choice of link monitoring may largely depend upon which mode you choose to use.  The more advanced load balancing modes do not support the use of the ARP monitor, and are thus restricted to using the MII monitor (which does not provide as high a level of end to end assurance as the ARP monitor).

<a id="rst-maximum-throughput-in-a-multiple-switch-topology"></a>

### 12.2 Maximum Throughput in a Multiple Switch Topology

Multiple switches may be utilized to optimize for throughput when they are configured in parallel as part of an isolated network between two or more systems, for example:



```text
              +-----------+
              |  Host A   |
              +-+---+---+-+
                |   |   |
       +--------+   |   +---------+
       |            |             |
+------+---+  +-----+----+  +-----+----+
| Switch A |  | Switch B |  | Switch C |
+------+---+  +-----+----+  +-----+----+
       |            |             |
       +--------+   |   +---------+
                |   |   |
              +-+---+---+-+
              |  Host B   |
              +-----------+
```

In this configuration, the switches are isolated from one another.  One reason to employ a topology such as this is for an isolated network with many hosts (a cluster configured for high performance, for example), using multiple smaller switches can be more cost effective than a single larger switch, e.g., on a network with 24 hosts, three 24 port switches can be significantly less expensive than a single 72 port switch.

If access beyond the network is required, an individual host can be equipped with an additional network device connected to an external network; this host then additionally acts as a gateway.

<a id="rst-mt-bonding-mode-selection-for-multiple-switch-topology"></a>

### 12.2.1 MT Bonding Mode Selection for Multiple Switch Topology

In actual practice, the bonding mode typically employed in configurations of this type is balance-rr.  Historically, in this network configuration, the usual caveats about out of order packet delivery are mitigated by the use of network adapters that do not do any kind of packet coalescing (via the use of NAPI, or because the device itself does not generate interrupts until some number of packets has arrived).  When employed in this fashion, the balance-rr mode allows individual connections between two hosts to effectively utilize greater than one interface's bandwidth.

<a id="rst-mt-link-monitoring-for-multiple-switch-topology"></a>

### 12.2.2 MT Link Monitoring for Multiple Switch Topology

Again, in actual practice, the MII monitor is most often used in this configuration, as performance is given preference over availability.  The ARP monitor will function in this topology, but its advantages over the MII monitor are mitigated by the volume of probes needed as the number of systems involved grows (remember that each host in the network is configured with bonding).

<a id="rst-switch-behavior-issues"></a>

## 13. Switch Behavior Issues

<a id="rst-link-establishment-and-failover-delays"></a>

### 13.1 Link Establishment and Failover Delays

Some switches exhibit undesirable behavior with regard to the timing of link up and down reporting by the switch.

First, when a link comes up, some switches may indicate that the link is up (carrier available), but not pass traffic over the interface for some period of time.  This delay is typically due to some type of autonegotiation or routing protocol, but may also occur during switch initialization (e.g., during recovery after a switch failure).  If you find this to be a problem, specify an appropriate value to the updelay bonding module option to delay the use of the relevant interface(s).

Second, some switches may "bounce" the link state one or more times while a link is changing state.  This occurs most commonly while the switch is initializing.  Again, an appropriate updelay value may help.

Note that when a bonding interface has no active links, the driver will immediately reuse the first link that goes up, even if the updelay parameter has been specified (the updelay is ignored in this case).  If there are slave interfaces waiting for the updelay timeout to expire, the interface that first went into that state will be immediately reused.  This reduces down time of the network if the value of updelay has been overestimated, and since this occurs only in cases with no connectivity, there is no additional penalty for ignoring the updelay.

In addition to the concerns about switch timings, if your switches take a long time to go into backup mode, it may be desirable to not activate a backup interface immediately after a link goes down. Failover may be delayed via the downdelay bonding module option.

<a id="rst-duplicated-incoming-packets"></a>

### 13.2 Duplicated Incoming Packets

NOTE: Starting with version 3.0.2, the bonding driver has logic to suppress duplicate packets, which should largely eliminate this problem. The following description is kept for reference.

It is not uncommon to observe a short burst of duplicated traffic when the bonding device is first used, or after it has been idle for some period of time.  This is most easily observed by issuing a "ping" to some other host on the network, and noticing that the output from ping flags duplicates (typically one per slave).

For example, on a bond in active-backup mode with five slaves all connected to one switch, the output may appear as follows:



```text
# ping -n 10.0.4.2
PING 10.0.4.2 (10.0.4.2) from 10.0.3.10 : 56(84) bytes of data.
64 bytes from 10.0.4.2: icmp_seq=1 ttl=64 time=13.7 ms
64 bytes from 10.0.4.2: icmp_seq=1 ttl=64 time=13.8 ms (DUP!)
64 bytes from 10.0.4.2: icmp_seq=1 ttl=64 time=13.8 ms (DUP!)
64 bytes from 10.0.4.2: icmp_seq=1 ttl=64 time=13.8 ms (DUP!)
64 bytes from 10.0.4.2: icmp_seq=1 ttl=64 time=13.8 ms (DUP!)
64 bytes from 10.0.4.2: icmp_seq=2 ttl=64 time=0.216 ms
64 bytes from 10.0.4.2: icmp_seq=3 ttl=64 time=0.267 ms
64 bytes from 10.0.4.2: icmp_seq=4 ttl=64 time=0.222 ms
```

This is not due to an error in the bonding driver, rather, it is a side effect of how many switches update their MAC forwarding tables.  Initially, the switch does not associate the MAC address in the packet with a particular switch port, and so it may send the traffic to all ports until its MAC forwarding table is updated.  Since the interfaces attached to the bond may occupy multiple ports on a single switch, when the switch (temporarily) floods the traffic to all ports, the bond device receives multiple copies of the same packet (one per slave device).

The duplicated packet behavior is switch dependent, some switches exhibit this, and some do not.  On switches that display this behavior, it can be induced by clearing the MAC forwarding table (on most Cisco switches, the privileged command "clear mac address-table dynamic" will accomplish this).

<a id="rst-hardware-specific-considerations"></a>

## 14. Hardware Specific Considerations

This section contains additional information for configuring bonding on specific hardware platforms, or for interfacing bonding with particular switches or other devices.

<a id="rst-ibm-bladecenter"></a>

### 14.1 IBM BladeCenter

This applies to the JS20 and similar systems.

On the JS20 blades, the bonding driver supports only balance-rr, active-backup, balance-tlb and balance-alb modes.  This is largely due to the network topology inside the BladeCenter, detailed below.

<a id="rst-js20-network-adapter-information"></a>

### JS20 network adapter information

All JS20s come with two Broadcom Gigabit Ethernet ports integrated on the planar (that's "motherboard" in IBM-speak).  In the BladeCenter chassis, the eth0 port of all JS20 blades is hard wired to I/O Module \#1; similarly, all eth1 ports are wired to I/O Module \#2. An add-on Broadcom daughter card can be installed on a JS20 to provide two more Gigabit Ethernet ports.  These ports, eth2 and eth3, are wired to I/O Modules 3 and 4, respectively.

Each I/O Module may contain either a switch or a passthrough module (which allows ports to be directly connected to an external switch).  Some bonding modes require a specific BladeCenter internal network topology in order to function; these are detailed below.

Additional BladeCenter-specific networking information can be found in two IBM Redbooks (www.ibm.com/redbooks):

- "IBM eServer BladeCenter Networking Options"

- "IBM eServer BladeCenter Layer 2-7 Network Switching"

<a id="rst-bladecenter-networking-configuration"></a>

### BladeCenter networking configuration

Because a BladeCenter can be configured in a very large number of ways, this discussion will be confined to describing basic configurations.

Normally, Ethernet Switch Modules (ESMs) are used in I/O modules 1 and 2.  In this configuration, the eth0 and eth1 ports of a JS20 will be connected to different internal switches (in the respective I/O modules).

A passthrough module (OPM or CPM, optical or copper, passthrough module) connects the I/O module directly to an external switch.  By using PMs in I/O module \#1 and \#2, the eth0 and eth1 interfaces of a JS20 can be redirected to the outside world and connected to a common external switch.

Depending upon the mix of ESMs and PMs, the network will appear to bonding as either a single switch topology (all PMs) or as a multiple switch topology (one or more ESMs, zero or more PMs).  It is also possible to connect ESMs together, resulting in a configuration much like the example in "High Availability in a Multiple Switch Topology," above.

<a id="rst-requirements-for-specific-modes"></a>

### Requirements for specific modes

The balance-rr mode requires the use of passthrough modules for devices in the bond, all connected to an common external switch. That switch must be configured for "etherchannel" or "trunking" on the appropriate ports, as is usual for balance-rr.

The balance-alb and balance-tlb modes will function with either switch modules or passthrough modules (or a mix).  The only specific requirement for these modes is that all network interfaces must be able to reach all destinations for traffic sent over the bonding device (i.e., the network must converge at some point outside the BladeCenter).

The active-backup mode has no additional requirements.

<a id="rst-link-monitoring-issues"></a>

### Link monitoring issues

When an Ethernet Switch Module is in place, only the ARP monitor will reliably detect link loss to an external switch.  This is nothing unusual, but examination of the BladeCenter cabinet would suggest that the "external" network ports are the ethernet ports for the system, when it fact there is a switch between these "external" ports and the devices on the JS20 system itself.  The MII monitor is only able to detect link failures between the ESM and the JS20 system.

When a passthrough module is in place, the MII monitor does detect failures to the "external" port, which is then directly connected to the JS20 system.

<a id="rst-other-concerns"></a>

### Other concerns

The Serial Over LAN (SoL) link is established over the primary ethernet (eth0) only, therefore, any loss of link to eth0 will result in losing your SoL connection.  It will not fail over with other network traffic, as the SoL system is beyond the control of the bonding driver.

It may be desirable to disable spanning tree on the switch (either the internal Ethernet Switch Module, or an external switch) to avoid fail-over delay issues when using bonding.

<a id="rst-frequently-asked-questions"></a>

## 15. Frequently Asked Questions

<a id="rst-is-it-smp-safe"></a>

### 1.  Is it SMP safe?

Yes. The old 2.0.xx channel bonding patch was not SMP safe. The new driver was designed to be SMP safe from the start.

<a id="rst-what-type-of-cards-will-work-with-it"></a>

### 2.  What type of cards will work with it?

Any Ethernet type cards (you can even mix cards - a Intel EtherExpress PRO/100 and a 3com 3c905b, for example).  For most modes, devices need not be of the same speed.

Starting with version 3.2.1, bonding also supports Infiniband slaves in active-backup mode.

<a id="rst-how-many-bonding-devices-can-i-have"></a>

### 3.  How many bonding devices can I have?

There is no limit.

<a id="rst-how-many-slaves-can-a-bonding-device-have"></a>

### 4.  How many slaves can a bonding device have?

This is limited only by the number of network interfaces Linux supports and/or the number of network cards you can place in your system.

<a id="rst-what-happens-when-a-slave-link-dies"></a>

### 5.  What happens when a slave link dies?

If link monitoring is enabled, then the failing device will be disabled.  The active-backup mode will fail over to a backup link, and other modes will ignore the failed link.  The link will continue to be monitored, and should it recover, it will rejoin the bond (in whatever manner is appropriate for the mode). See the sections on High Availability and the documentation for each mode for additional information.

Link monitoring can be enabled via either the miimon or arp\_interval parameters (described in the module parameters section, above).  In general, miimon monitors the carrier state as sensed by the underlying network device, and the arp monitor (arp\_interval) monitors connectivity to another host on the local network.

If no link monitoring is configured, the bonding driver will be unable to detect link failures, and will assume that all links are always available.  This will likely result in lost packets, and a resulting degradation of performance.  The precise performance loss depends upon the bonding mode and network configuration.

<a id="rst-can-bonding-be-used-for-high-availability"></a>

### 6.  Can bonding be used for High Availability?

Yes.  See the section on High Availability for details.

<a id="rst-which-switches-systems-does-it-work-with"></a>

### 7.  Which switches/systems does it work with?

The full answer to this depends upon the desired mode.

In the basic balance modes (balance-rr and balance-xor), it works with any system that supports etherchannel (also called trunking).  Most managed switches currently available have such support, and many unmanaged switches as well.

The advanced balance modes (balance-tlb and balance-alb) do not have special switch requirements, but do need device drivers that support specific features (described in the appropriate section under module parameters, above).

In 802.3ad mode, it works with systems that support IEEE 802.3ad Dynamic Link Aggregation.  Most managed and many unmanaged switches currently available support 802.3ad.

The active-backup mode should work with any Layer-II switch.

<a id="rst-where-does-a-bonding-device-get-its-mac-address-from"></a>

### 8.  Where does a bonding device get its MAC address from?

When using slave devices that have fixed MAC addresses, or when the fail\_over\_mac option is enabled, the bonding device's MAC address is the MAC address of the active slave.

For other configurations, if not explicitly configured (with ifconfig or ip link), the MAC address of the bonding device is taken from its first slave device.  This MAC address is then passed to all following slaves and remains persistent (even if the first slave is removed) until the bonding device is brought down or reconfigured.

If you wish to change the MAC address, you can set it with ifconfig or ip link:



```text
# ifconfig bond0 hw ether 00:11:22:33:44:55

# ip link set bond0 address 66:77:88:99:aa:bb
```

The MAC address can be also changed by bringing down/up the device and then changing its slaves (or their order):



```text
# ifconfig bond0 down ; modprobe -r bonding
# ifconfig bond0 .... up
# ifenslave bond0 eth...
```

This method will automatically take the address from the next slave that is added.

To restore your slaves' MAC addresses, you need to detach them from the bond (`ifenslave -d bond0 eth0`). The bonding driver will then restore the MAC addresses that the slaves had before they were enslaved.

<a id="rst-what-bonding-modes-support-native-xdp"></a>

### 9.  What bonding modes support native XDP?

> - balance-rr (0)
>
> - active-backup (1)
>
> - balance-xor (2)
>
> - 802.3ad (4)

Note that the vlan+srcmac hash policy does not support native XDP. For other bonding modes, the XDP program must be loaded with generic mode.

<a id="rst-resources-and-links"></a>

## 16. Resources and Links

The latest version of the bonding driver can be found in the latest version of the linux kernel, found on [http://kernel.org](<http://kernel.org>)

The latest version of this document can be found in the latest kernel source (named [Documentation/networking/bonding.rst](/kernel/internals/networking/bonding.md)).

Discussions regarding the development of the bonding driver take place on the main Linux network mailing list, hosted at vger.kernel.org. The list address is:

[netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>)

The administrative interface (to subscribe or unsubscribe) can be found at:

[http://vger.kernel.org/vger-lists.html\#netdev](<http://vger.kernel.org/vger-lists.html#netdev>)

---

# Ethernet Bridging

_Peios Kernel / Internals / Networking_

> The IEEE 802.1Q-2022 (Bridges and Bridged Networks) standard defines the operation of bridges in computer networks. A bridge, in the context of this standard, is a device that connects two or more network segments and operates at the data…

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-ethernet-bridging"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The IEEE 802.1Q-2022 (Bridges and Bridged Networks) standard defines the operation of bridges in computer networks. A bridge, in the context of this standard, is a device that connects two or more network segments and operates at the data link layer (Layer 2) of the OSI (Open Systems Interconnection) model. The purpose of a bridge is to filter and forward frames between different segments based on the destination MAC (Media Access Control) address.

<a id="rst-bridge-kapi"></a>

## Bridge kAPI

Here are some core structures of bridge code. Note that the kAPI is *unstable*, and can be changed at any time.


#### <a id="c-struct-net_bridge_vlan"></a>`struct net_bridge_vlan`

per-vlan entry

**Definition**

```c
struct net_bridge_vlan {
    struct rhash_head               vnode;
    struct rhash_head               tnode;
    u16 vid;
    u16 flags;
    u16 priv_flags;
    u8 state;
    struct pcpu_sw_netstats __percpu *stats;
    union {
        struct net_bridge       *br;
        struct net_bridge_port  *port;
    };
    union {
        refcount_t refcnt;
        struct net_bridge_vlan  *brvlan;
    };
    struct br_tunnel_info           tinfo;
    union {
        struct net_bridge_mcast         br_mcast_ctx;
        struct net_bridge_mcast_port    port_mcast_ctx;
    };
    u16 msti;
    struct list_head                vlist;
    struct rcu_head                 rcu;
};
```

**Members**

- `vnode`: rhashtable member
- `tnode`: rhashtable member
- `vid`: VLAN id
- `flags`: bridge vlan flags
- `priv_flags`: private (in-kernel) bridge vlan flags
- `state`: STP state (e.g. blocking, learning, forwarding)
- `stats`: per-cpu VLAN statistics
- `{unnamed_union}`: anonymous
- `br`: if MASTER flag set, this points to a bridge struct
- `port`: if MASTER flag unset, this points to a port struct
- `{unnamed_union}`: anonymous
- `refcnt`: if MASTER flag set, this is bumped for each port referencing it
- `brvlan`: if MASTER flag unset, this points to the global per-VLAN context
  for this VLAN entry
- `tinfo`: bridge tunnel info
- `{unnamed_union}`: anonymous
- `br_mcast_ctx`: if MASTER flag set, this is the global vlan multicast context
- `port_mcast_ctx`: if MASTER flag unset, this is the per-port/vlan multicast
  context
- `msti`: if MASTER flag set, this holds the VLANs MST instance
- `vlist`: sorted list of VLAN entries
- `rcu`: used for entry destruction

**Description**

This structure is shared between the global per-VLAN entries contained in
the bridge rhashtable and the local per-port per-VLAN entries contained in
the port's rhashtable. The union entries should be interpreted depending on
the entry flags that are set.


<a id="rst-bridge-uapi"></a>

## Bridge uAPI

Modern Linux bridge uAPI is accessed via Netlink interface. You can find below files where the bridge and bridge port netlink attributes are defined.

<a id="rst-bridge-netlink-attributes"></a>

### Bridge netlink attributes


Please *note* that the timer values in the following section are expected
in clock_t format, which is seconds multiplied by USER_HZ (generally
defined as 100).

- **IFLA_BR_FORWARD_DELAY**:
  The bridge forwarding delay is the time spent in LISTENING state
  (before moving to LEARNING) and in LEARNING state (before moving
  to FORWARDING). Only relevant if STP is enabled.

  The valid values are between (2 * USER_HZ) and (30 * USER_HZ).
  The default value is (15 * USER_HZ).

- **IFLA_BR_HELLO_TIME**:
  The time between hello packets sent by the bridge, when it is a root
  bridge or a designated bridge. Only relevant if STP is enabled.

  The valid values are between (1 * USER_HZ) and (10 * USER_HZ).
  The default value is (2 * USER_HZ).

- **IFLA_BR_MAX_AGE**:
  The hello packet timeout is the time until another bridge in the
  spanning tree is assumed to be dead, after reception of its last hello
  message. Only relevant if STP is enabled.

  The valid values are between (6 * USER_HZ) and (40 * USER_HZ).
  The default value is (20 * USER_HZ).

- **IFLA_BR_AGEING_TIME**:
  Configure the bridge's FDB entries aging time. It is the time a MAC
  address will be kept in the FDB after a packet has been received from
  that address. After this time has passed, entries are cleaned up.
  Allow values outside the 802.1 standard specification for special cases:

  * 0 - entry never ages (all permanent)
  * 1 - entry disappears (no persistence)

  The default value is (300 * USER_HZ).

- **IFLA_BR_STP_STATE**:
  Turn spanning tree protocol on (*IFLA_BR_STP_STATE* > 0) or off
  (*IFLA_BR_STP_STATE* == 0) for this bridge.

  The default value is 0 (disabled).

- **IFLA_BR_PRIORITY**:
  Set this bridge's spanning tree priority, used during STP root bridge
  election.

  The valid values are between 0 and 65535.

- **IFLA_BR_VLAN_FILTERING**:
  Turn VLAN filtering on (*IFLA_BR_VLAN_FILTERING* > 0) or off
  (*IFLA_BR_VLAN_FILTERING* == 0). When disabled, the bridge will not
  consider the VLAN tag when handling packets.

  The default value is 0 (disabled).

- **IFLA_BR_VLAN_PROTOCOL**:
  Set the protocol used for VLAN filtering.

  The valid values are 0x8100(802.1Q) or 0x88A8(802.1AD). The default value
  is 0x8100(802.1Q).

- **IFLA_BR_GROUP_FWD_MASK**:
  The group forwarding mask. This is the bitmask that is applied to
  decide whether to forward incoming frames destined to link-local
  addresses (of the form 01:80:C2:00:00:0X).

  The default value is 0, which means the bridge does not forward any
  link-local frames coming on this port.

- **IFLA_BR_ROOT_ID**:
  The bridge root id, read only.

- **IFLA_BR_BRIDGE_ID**:
  The bridge id, read only.

- **IFLA_BR_ROOT_PORT**:
  The bridge root port, read only.

- **IFLA_BR_ROOT_PATH_COST**:
  The bridge root path cost, read only.

- **IFLA_BR_TOPOLOGY_CHANGE**:
  The bridge topology change, read only.

- **IFLA_BR_TOPOLOGY_CHANGE_DETECTED**:
  The bridge topology change detected, read only.

- **IFLA_BR_HELLO_TIMER**:
  The bridge hello timer, read only.

- **IFLA_BR_TCN_TIMER**:
  The bridge tcn timer, read only.

- **IFLA_BR_TOPOLOGY_CHANGE_TIMER**:
  The bridge topology change timer, read only.

- **IFLA_BR_GC_TIMER**:
  The bridge gc timer, read only.

- **IFLA_BR_GROUP_ADDR**:
  Set the MAC address of the multicast group this bridge uses for STP.
  The address must be a link-local address in standard Ethernet MAC address
  format. It is an address of the form 01:80:C2:00:00:0X, with X in \[0, 4..f\].

  The default value is 0.

- **IFLA_BR_FDB_FLUSH**:
  Flush bridge's fdb dynamic entries.

- **IFLA_BR_MCAST_ROUTER**:
  Set bridge's multicast router if IGMP snooping is enabled.
  The valid values are:

  * 0 - disabled.
  * 1 - automatic (queried).
  * 2 - permanently enabled.

  The default value is 1.

- **IFLA_BR_MCAST_SNOOPING**:
  Turn multicast snooping on (*IFLA_BR_MCAST_SNOOPING* > 0) or off
  (*IFLA_BR_MCAST_SNOOPING* == 0).

  The default value is 1.

- **IFLA_BR_MCAST_QUERY_USE_IFADDR**:
  If enabled use the bridge's own IP address as source address for IGMP
  queries (*IFLA_BR_MCAST_QUERY_USE_IFADDR* > 0) or the default of 0.0.0.0
  (*IFLA_BR_MCAST_QUERY_USE_IFADDR* == 0).

  The default value is 0 (disabled).

- **IFLA_BR_MCAST_QUERIER**:
  Enable (*IFLA_BR_MULTICAST_QUERIER* > 0) or disable
  (*IFLA_BR_MULTICAST_QUERIER* == 0) IGMP querier, ie sending of multicast
  queries by the bridge.

  The default value is 0 (disabled).

- **IFLA_BR_MCAST_HASH_ELASTICITY**:
  Set multicast database hash elasticity, It is the maximum chain length in
  the multicast hash table. This attribute is *deprecated* and the value
  is always 16.

- **IFLA_BR_MCAST_HASH_MAX**:
  Set maximum size of the multicast hash table

  The default value is 4096, the value must be a power of 2.

- **IFLA_BR_MCAST_LAST_MEMBER_CNT**:
  The Last Member Query Count is the number of Group-Specific Queries
  sent before the router assumes there are no local members. The Last
  Member Query Count is also the number of Group-and-Source-Specific
  Queries sent before the router assumes there are no listeners for a
  particular source.

  The default value is 2.

- **IFLA_BR_MCAST_STARTUP_QUERY_CNT**:
  The Startup Query Count is the number of Queries sent out on startup,
  separated by the Startup Query Interval.

  The default value is 2.

- **IFLA_BR_MCAST_LAST_MEMBER_INTVL**:
  The Last Member Query Interval is the Max Response Time inserted into
  Group-Specific Queries sent in response to Leave Group messages, and
  is also the amount of time between Group-Specific Query messages.

  The default value is (1 * USER_HZ).

- **IFLA_BR_MCAST_MEMBERSHIP_INTVL**:
  The interval after which the bridge will leave a group, if no membership
  reports for this group are received.

  The default value is (260 * USER_HZ).

- **IFLA_BR_MCAST_QUERIER_INTVL**:
  The interval between queries sent by other routers. if no queries are
  seen after this delay has passed, the bridge will start to send its own
  queries (as if *IFLA_BR_MCAST_QUERIER_INTVL* was enabled).

  The default value is (255 * USER_HZ).

- **IFLA_BR_MCAST_QUERY_INTVL**:
  The Query Interval is the interval between General Queries sent by
  the Querier.

  The default value is (125 * USER_HZ). The minimum value is (1 * USER_HZ).

- **IFLA_BR_MCAST_QUERY_RESPONSE_INTVL**:
  The Max Response Time used to calculate the Max Resp Code inserted
  into the periodic General Queries.

  The default value is (10 * USER_HZ).

- **IFLA_BR_MCAST_STARTUP_QUERY_INTVL**:
  The interval between queries in the startup phase.

  The default value is (125 * USER_HZ) / 4. The minimum value is (1 * USER_HZ).

- **IFLA_BR_NF_CALL_IPTABLES**:
  Enable (*NF_CALL_IPTABLES* > 0) or disable (*NF_CALL_IPTABLES* == 0)
  iptables hooks on the bridge.

  The default value is 0 (disabled).

- **IFLA_BR_NF_CALL_IP6TABLES**:
  Enable (*NF_CALL_IP6TABLES* > 0) or disable (*NF_CALL_IP6TABLES* == 0)
  ip6tables hooks on the bridge.

  The default value is 0 (disabled).

- **IFLA_BR_NF_CALL_ARPTABLES**:
  Enable (*NF_CALL_ARPTABLES* > 0) or disable (*NF_CALL_ARPTABLES* == 0)
  arptables hooks on the bridge.

  The default value is 0 (disabled).

- **IFLA_BR_VLAN_DEFAULT_PVID**:
  VLAN ID applied to untagged and priority-tagged incoming packets.

  The default value is 1. Setting to the special value 0 makes all ports of
  this bridge not have a PVID by default, which means that they will
  not accept VLAN-untagged traffic.

- **IFLA_BR_PAD**:
  Bridge attribute padding type for netlink message.

- **IFLA_BR_VLAN_STATS_ENABLED**:
  Enable (*IFLA_BR_VLAN_STATS_ENABLED* == 1) or disable
  (*IFLA_BR_VLAN_STATS_ENABLED* == 0) per-VLAN stats accounting.

  The default value is 0 (disabled).

- **IFLA_BR_MCAST_STATS_ENABLED**:
  Enable (*IFLA_BR_MCAST_STATS_ENABLED* > 0) or disable
  (*IFLA_BR_MCAST_STATS_ENABLED* == 0) multicast (IGMP/MLD) stats
  accounting.

  The default value is 0 (disabled).

- **IFLA_BR_MCAST_IGMP_VERSION**:
  Set the IGMP version.

  The valid values are 2 and 3. The default value is 2.

- **IFLA_BR_MCAST_MLD_VERSION**:
  Set the MLD version.

  The valid values are 1 and 2. The default value is 1.

- **IFLA_BR_VLAN_STATS_PER_PORT**:
  Enable (*IFLA_BR_VLAN_STATS_PER_PORT* == 1) or disable
  (*IFLA_BR_VLAN_STATS_PER_PORT* == 0) per-VLAN per-port stats accounting.
  Can be changed only when there are no port VLANs configured.

  The default value is 0 (disabled).

- **IFLA_BR_MULTI_BOOLOPT**:
  The multi_boolopt is used to control new boolean options to avoid adding
  new netlink attributes. You can look at `enum br_boolopt_id` for those
  options.

- **IFLA_BR_MCAST_QUERIER_STATE**:
  Bridge mcast querier states, read only.

- **IFLA_BR_FDB_N_LEARNED**:
  The number of dynamically learned FDB entries for the current bridge,
  read only.

- **IFLA_BR_FDB_MAX_LEARNED**:
  Set the number of max dynamically learned FDB entries for the current
  bridge.


<a id="rst-bridge-port-netlink-attributes"></a>

### Bridge port netlink attributes


- **IFLA_BRPORT_STATE**:
  The operation state of the port. Here are the valid values.

  * 0 - port is in STP *DISABLED* state. Make this port completely
    inactive for STP. This is also called BPDU filter and could be used
    to disable STP on an untrusted port, like a leaf virtual device.
    The traffic forwarding is also stopped on this port.
  * 1 - port is in STP *LISTENING* state. Only valid if STP is enabled
    on the bridge. In this state the port listens for STP BPDUs and
    drops all other traffic frames.
  * 2 - port is in STP *LEARNING* state. Only valid if STP is enabled on
    the bridge. In this state the port will accept traffic only for the
    purpose of updating MAC address tables.
  * 3 - port is in STP *FORWARDING* state. Port is fully active.
  * 4 - port is in STP *BLOCKING* state. Only valid if STP is enabled on
    the bridge. This state is used during the STP election process.
    In this state, port will only process STP BPDUs.

- **IFLA_BRPORT_PRIORITY**:
  The STP port priority. The valid values are between 0 and 255.

- **IFLA_BRPORT_COST**:
  The STP path cost of the port. The valid values are between 1 and 65535.

- **IFLA_BRPORT_MODE**:
  Set the bridge port mode. See *BRIDGE_MODE_HAIRPIN* for more details.

- **IFLA_BRPORT_GUARD**:
  Controls whether STP BPDUs will be processed by the bridge port. By
  default, the flag is turned off to allow BPDU processing. Turning this
  flag on will disable the bridge port if a STP BPDU packet is received.

  If the bridge has Spanning Tree enabled, hostile devices on the network
  may send BPDU on a port and cause network failure. Setting *guard on*
  will detect and stop this by disabling the port. The port will be
  restarted if the link is brought down, or removed and reattached.

- **IFLA_BRPORT_PROTECT**:
  Controls whether a given port is allowed to become a root port or not.
  Only used when STP is enabled on the bridge. By default the flag is off.

  This feature is also called root port guard. If BPDU is received from a
  leaf (edge) port, it should not be elected as root port. This could
  be used if using STP on a bridge and the downstream bridges are not fully
  trusted; this prevents a hostile guest from rerouting traffic.

- **IFLA_BRPORT_FAST_LEAVE**:
  This flag allows the bridge to immediately stop multicast traffic
  forwarding on a port that receives an IGMP Leave message. It is only used
  when IGMP snooping is enabled on the bridge. By default the flag is off.

- **IFLA_BRPORT_LEARNING**:
  Controls whether a given port will learn *source* MAC addresses from
  received traffic or not. Also controls whether dynamic FDB entries
  (which can also be added by software) will be refreshed by incoming
  traffic. By default this flag is on.

- **IFLA_BRPORT_UNICAST_FLOOD**:
  Controls whether unicast traffic for which there is no FDB entry will
  be flooded towards this port. By default this flag is on.

- **IFLA_BRPORT_PROXYARP**:
  Enable proxy ARP on this port.

- **IFLA_BRPORT_LEARNING_SYNC**:
  Controls whether a given port will sync MAC addresses learned on device
  port to bridge FDB.

- **IFLA_BRPORT_PROXYARP_WIFI**:
  Enable proxy ARP on this port which meets extended requirements by
  IEEE 802.11 and Hotspot 2.0 specifications.

**IFLA_BRPORT_ROOT_ID**

**IFLA_BRPORT_BRIDGE_ID**

**IFLA_BRPORT_DESIGNATED_PORT**

**IFLA_BRPORT_DESIGNATED_COST**

**IFLA_BRPORT_ID**

**IFLA_BRPORT_NO**

**IFLA_BRPORT_TOPOLOGY_CHANGE_ACK**

**IFLA_BRPORT_CONFIG_PENDING**

**IFLA_BRPORT_MESSAGE_AGE_TIMER**

**IFLA_BRPORT_FORWARD_DELAY_TIMER**

**IFLA_BRPORT_HOLD_TIMER**

- **IFLA_BRPORT_FLUSH**:
  Flush bridge ports' fdb dynamic entries.

- **IFLA_BRPORT_MULTICAST_ROUTER**:
  Configure the port's multicast router presence. A port with
  a multicast router will receive all multicast traffic.
  The valid values are:

  * 0 disable multicast routers on this port
  * 1 let the system detect the presence of routers (default)
  * 2 permanently enable multicast traffic forwarding on this port
  * 3 enable multicast routers temporarily on this port, not depending
    on incoming queries.

**IFLA_BRPORT_PAD**

- **IFLA_BRPORT_MCAST_FLOOD**:
  Controls whether a given port will flood multicast traffic for which
  there is no MDB entry. By default this flag is on.

- **IFLA_BRPORT_MCAST_TO_UCAST**:
  Controls whether a given port will replicate packets using unicast
  instead of multicast. By default this flag is off.

  This is done by copying the packet per host and changing the multicast
  destination MAC to a unicast one accordingly.

  *mcast_to_unicast* works on top of the multicast snooping feature of the
  bridge. Which means unicast copies are only delivered to hosts which
  are interested in unicast and signaled this via IGMP/MLD reports previously.

  This feature is intended for interface types which have a more reliable
  and/or efficient way to deliver unicast packets than broadcast ones
  (e.g. WiFi).

  However, it should only be enabled on interfaces where no IGMPv2/MLDv1
  report suppression takes place. IGMP/MLD report suppression issue is
  usually overcome by the network daemon (supplicant) enabling AP isolation
  and by that separating all STAs.

  Delivery of STA-to-STA IP multicast is made possible again by enabling
  and utilizing the bridge hairpin mode, which considers the incoming port
  as a potential outgoing port, too (see *BRIDGE_MODE_HAIRPIN* option).
  Hairpin mode is performed after multicast snooping, therefore leading
  to only deliver reports to STAs running a multicast router.

- **IFLA_BRPORT_VLAN_TUNNEL**:
  Controls whether vlan to tunnel mapping is enabled on the port.
  By default this flag is off.

- **IFLA_BRPORT_BCAST_FLOOD**:
  Controls flooding of broadcast traffic on the given port. By default
  this flag is on.

- **IFLA_BRPORT_GROUP_FWD_MASK**:
  Set the group forward mask. This is a bitmask that is applied to
  decide whether to forward incoming frames destined to link-local
  addresses. The addresses of the form are 01:80:C2:00:00:0X (defaults
  to 0, which means the bridge does not forward any link-local frames
  coming on this port).

- **IFLA_BRPORT_NEIGH_SUPPRESS**:
  Controls whether neighbor discovery (arp and nd) proxy and suppression
  is enabled on the port. By default this flag is off.

- **IFLA_BRPORT_ISOLATED**:
  Controls whether a given port will be isolated, which means it will be
  able to communicate with non-isolated ports only. By default this
  flag is off.

- **IFLA_BRPORT_BACKUP_PORT**:
  Set a backup port. If the port loses carrier all traffic will be
  redirected to the configured backup port. Set the value to 0 to disable
  it.

**IFLA_BRPORT_MRP_RING_OPEN**

**IFLA_BRPORT_MRP_IN_OPEN**

- **IFLA_BRPORT_MCAST_EHT_HOSTS_LIMIT**:
  The number of per-port EHT hosts limit. The default value is 512.
  Setting to 0 is not allowed.

- **IFLA_BRPORT_MCAST_EHT_HOSTS_CNT**:
  The current number of tracked hosts, read only.

- **IFLA_BRPORT_LOCKED**:
  Controls whether a port will be locked, meaning that hosts behind the
  port will not be able to communicate through the port unless an FDB
  entry with the unit's MAC address is in the FDB. The common use case is
  that hosts are allowed access through authentication with the IEEE 802.1X
  protocol or based on whitelists. By default this flag is off.

  Please note that secure 802.1X deployments should always use the
  *BR_BOOLOPT_NO_LL_LEARN* flag, to not permit the bridge to populate its
  FDB based on link-local (EAPOL) traffic received on the port.

- **IFLA_BRPORT_MAB**:
  Controls whether a port will use MAC Authentication Bypass (MAB), a
  technique through which select MAC addresses may be allowed on a locked
  port, without using 802.1X authentication. Packets with an unknown source
  MAC address generates a "locked" FDB entry on the incoming bridge port.
  The common use case is for user space to react to these bridge FDB
  notifications and optionally replace the locked FDB entry with a normal
  one, allowing traffic to pass for whitelisted MAC addresses.

  Setting this flag also requires *IFLA_BRPORT_LOCKED* and
  *IFLA_BRPORT_LEARNING*. *IFLA_BRPORT_LOCKED* ensures that unauthorized
  data packets are dropped, and *IFLA_BRPORT_LEARNING* allows the dynamic
  FDB entries installed by user space (as replacements for the locked FDB
  entries) to be refreshed and/or aged out.

**IFLA_BRPORT_MCAST_N_GROUPS**

- **IFLA_BRPORT_MCAST_MAX_GROUPS**:
  Sets the maximum number of MDB entries that can be registered for a
  given port. Attempts to register more MDB entries at the port than this
  limit allows will be rejected, whether they are done through netlink
  (e.g. the bridge tool), or IGMP or MLD membership reports. Setting a
  limit of 0 disables the limit. The default value is 0.

- **IFLA_BRPORT_NEIGH_VLAN_SUPPRESS**:
  Controls whether neighbor discovery (arp and nd) proxy and suppression is
  enabled for a given port. By default this flag is off.

  Note that this option only takes effect when *IFLA_BRPORT_NEIGH_SUPPRESS*
  is enabled for a given port.

- **IFLA_BRPORT_BACKUP_NHID**:
  The FDB nexthop object ID to attach to packets being redirected to a
  backup port that has VLAN tunnel mapping enabled (via the
  *IFLA_BRPORT_VLAN_TUNNEL* option). Setting a value of 0 (default) has
  the effect of not attaching any ID.


<a id="rst-bridge-sysfs"></a>

### Bridge sysfs

The sysfs interface is deprecated and should not be extended if new options are added.

<a id="rst-stp"></a>

## STP

The STP (Spanning Tree Protocol) implementation in the Linux bridge driver is a critical feature that helps prevent loops and broadcast storms in Ethernet networks by identifying and disabling redundant links. In a Linux bridge context, STP is crucial for network stability and availability.

STP is a Layer 2 protocol that operates at the Data Link Layer of the OSI model. It was originally developed as IEEE 802.1D and has since evolved into multiple versions, including Rapid Spanning Tree Protocol (RSTP) and [Multiple Spanning Tree Protocol (MSTP)](<https://lore.kernel.org/netdev/20220316150857.2442916-1-tobias@waldekranz.com/>)<a id="rst-multiple-spanning-tree-protocol-mstp"></a>.

The 802.1D-2004 removed the original Spanning Tree Protocol, instead incorporating the Rapid Spanning Tree Protocol (RSTP). By 2014, all the functionality defined by IEEE 802.1D has been incorporated into either IEEE 802.1Q (Bridges and Bridged Networks) or IEEE 802.1AC (MAC Service Definition). 802.1D has been officially withdrawn in 2022.

<a id="rst-bridge-ports-and-stp-states"></a>

### Bridge Ports and STP States

- **In the context of STP, bridge ports can be in one of the following states:**

  - Blocking: The port is disabled for data traffic and only listens for BPDUs (Bridge Protocol Data Units) from other devices to determine the network topology.

  - Listening: The port begins to participate in the STP process and listens for BPDUs.

  - Learning: The port continues to listen for BPDUs and begins to learn MAC addresses from incoming frames but does not forward data frames.

  - Forwarding: The port is fully operational and forwards both BPDUs and data frames.

  - Disabled: The port is administratively disabled and does not participate in the STP process. The data frames forwarding are also disabled.

<a id="rst-root-bridge-and-convergence"></a>

### Root Bridge and Convergence

In the context of networking and Ethernet bridging in Linux, the root bridge is a designated switch in a bridged network that serves as a reference point for the spanning tree algorithm to create a loop-free topology.

- **Here's how the STP works and root bridge is chosen:**

  1. Bridge Priority: Each bridge running a spanning tree protocol, has a configurable Bridge Priority value. The lower the value, the higher the priority. By default, the Bridge Priority is set to a standard value (e.g., 32768).

  2. Bridge ID: The Bridge ID is composed of two components: Bridge Priority and the MAC address of the bridge. It uniquely identifies each bridge in the network. The Bridge ID is used to compare the priorities of different bridges.

  3. Bridge Election: When the network starts, all bridges initially assume that they are the root bridge. They start advertising Bridge Protocol Data Units (BPDU) to their neighbors, containing their Bridge ID and other information.

  4. BPDU Comparison: Bridges exchange BPDUs to determine the root bridge. Each bridge examines the received BPDUs, including the Bridge Priority and Bridge ID, to determine if it should adjust its own priorities. The bridge with the lowest Bridge ID will become the root bridge.

  5. Root Bridge Announcement: Once the root bridge is determined, it sends BPDUs with information about the root bridge to all other bridges in the network. This information is used by other bridges to calculate the shortest path to the root bridge and, in doing so, create a loop-free topology.

  6. Forwarding Ports: After the root bridge is selected and the spanning tree topology is established, each bridge determines which of its ports should be in the forwarding state (used for data traffic) and which should be in the blocking state (used to prevent loops). The root bridge's ports are all in the forwarding state. while other bridges have some ports in the blocking state to avoid loops.

  7. Root Ports: After the root bridge is selected and the spanning tree topology is established, each non-root bridge processes incoming BPDUs and determines which of its ports provides the shortest path to the root bridge based on the information in the received BPDUs. This port is designated as the root port. And it is in the Forwarding state, allowing it to actively forward network traffic.

  8. Designated ports: A designated port is the port through which the non-root bridge will forward traffic towards the designated segment. Designated ports are placed in the Forwarding state. All other ports on the non-root bridge that are not designated for specific segments are placed in the Blocking state to prevent network loops.

STP ensures network convergence by calculating the shortest path and disabling redundant links. When network topology changes occur (e.g., a link failure), STP recalculates the network topology to restore connectivity while avoiding loops.

Proper configuration of STP parameters, such as the bridge priority, can influence network performance, path selection and which bridge becomes the Root Bridge.

<a id="rst-user-space-stp-helper"></a>

### User space STP helper

The user space STP helper *bridge-stp* is a program to control whether to use user mode spanning tree. The `/sbin/bridge-stp <bridge> <start|stop>` is called by the kernel when STP is enabled/disabled on a bridge (via `brctl stp <bridge> <on|off>` or `ip link set <bridge> type bridge stp_state <0|1>`).  The kernel enables user_stp mode if that command returns 0, or enables kernel_stp mode if that command returns any other value.

<a id="rst-vlan"></a>

## VLAN

A LAN (Local Area Network) is a network that covers a small geographic area, typically within a single building or a campus. LANs are used to connect computers, servers, printers, and other networked devices within a localized area. LANs can be wired (using Ethernet cables) or wireless (using Wi-Fi).

A VLAN (Virtual Local Area Network) is a logical segmentation of a physical network into multiple isolated broadcast domains. VLANs are used to divide a single physical LAN into multiple virtual LANs, allowing different groups of devices to communicate as if they were on separate physical networks.

Typically there are two VLAN implementations, IEEE 802.1Q and IEEE 802.1ad (also known as QinQ). IEEE 802.1Q is a standard for VLAN tagging in Ethernet networks. It allows network administrators to create logical VLANs on a physical network and tag Ethernet frames with VLAN information, which is called *VLAN-tagged frames*. IEEE 802.1ad, commonly known as QinQ or Double VLAN, is an extension of the IEEE 802.1Q standard. QinQ allows for the stacking of multiple VLAN tags within a single Ethernet frame. The Linux bridge supports both the IEEE 802.1Q and [802.1AD](<https://lore.kernel.org/netdev/1402401565-15423-1-git-send-email-makita.toshiaki@lab.ntt.co.jp/>)<a id="rst-ad"></a> protocol for VLAN tagging.

[VLAN filtering](<https://lore.kernel.org/netdev/1360792820-14116-1-git-send-email-vyasevic@redhat.com/>)<a id="rst-vlan-filtering"></a> on a bridge is disabled by default. After enabling VLAN filtering on a bridge, it will start forwarding frames to appropriate destinations based on their destination MAC address and VLAN tag (both must match).

<a id="rst-multicast"></a>

## Multicast

The Linux bridge driver has multicast support allowing it to process Internet Group Management Protocol (IGMP) or Multicast Listener Discovery (MLD) messages, and to efficiently forward multicast data packets. The bridge driver supports IGMPv2/IGMPv3 and MLDv1/MLDv2.

<a id="rst-multicast-snooping"></a>

### Multicast snooping

Multicast snooping is a networking technology that allows network switches to intelligently manage multicast traffic within a local area network (LAN).

The switch maintains a multicast group table, which records the association between multicast group addresses and the ports where hosts have joined these groups. The group table is dynamically updated based on the IGMP/MLD messages received. With the multicast group information gathered through snooping, the switch optimizes the forwarding of multicast traffic. Instead of blindly broadcasting the multicast traffic to all ports, it sends the multicast traffic based on the destination MAC address only to ports which have subscribed the respective destination multicast group.

When created, the Linux bridge devices have multicast snooping enabled by default. It maintains a Multicast forwarding database (MDB) which keeps track of port and group relationships.

<a id="rst-igmpv3-mldv2-eht-support"></a>

### IGMPv3/MLDv2 EHT support

The Linux bridge supports IGMPv3/MLDv2 EHT (Explicit Host Tracking), which was added by [474ddb37fa3a ("net: bridge: multicast: add EHT allow/block handling")](<https://lore.kernel.org/netdev/20210120145203.1109140-1-razor@blackwall.org/>)<a id="rst-ddb37fa3a-net-bridge-multicast-add-eht-allow-block-handling"></a>

The explicit host tracking enables the device to keep track of each individual host that is joined to a particular group or channel. The main benefit of the explicit host tracking in IGMP is to allow minimal leave latencies when a host leaves a multicast group or channel.

The length of time between a host wanting to leave and a device stopping traffic forwarding is called the IGMP leave latency. A device configured with IGMPv3 or MLDv2 and explicit tracking can immediately stop forwarding traffic if the last host to request to receive traffic from the device indicates that it no longer wants to receive traffic. The leave latency is thus bound only by the packet transmission latencies in the multiaccess network and the processing time in the device.

<a id="rst-other-multicast-features"></a>

### Other multicast features

The Linux bridge also supports [per-VLAN multicast snooping](<https://lore.kernel.org/netdev/20210719170637.435541-1-razor@blackwall.org/>)<a id="rst-per-vlan-multicast-snooping"></a>, which is disabled by default but can be enabled. And [Multicast Router Discovery](<https://lore.kernel.org/netdev/20190121062628.2710-1-linus.luessing@c0d3.blue/>)<a id="rst-multicast-router-discovery"></a>, which help identify the location of multicast routers.

<a id="rst-switchdev"></a>

## Switchdev

Linux Bridge Switchdev is a feature in the Linux kernel that extends the capabilities of the traditional Linux bridge to work more efficiently with hardware switches that support switchdev. With Linux Bridge Switchdev, certain networking functions like forwarding, filtering, and learning of Ethernet frames can be offloaded to a hardware switch. This offloading reduces the burden on the Linux kernel and CPU, leading to improved network performance and lower latency.

To use Linux Bridge Switchdev, you need hardware switches that support the switchdev interface. This means that the switch hardware needs to have the necessary drivers and functionality to work in conjunction with the Linux kernel.

Please see the [Switchdev](<#rst-switchdev>) document for more details.

<a id="rst-netfilter"></a>

## Netfilter

The bridge netfilter module is a legacy feature that allows to filter bridged packets with iptables and ip6tables. Its use is discouraged. Users should consider using nftables for packet filtering.

The older ebtables tool is more feature-limited compared to nftables, but just like nftables it doesn't need this module either to function.

The br_netfilter module intercepts packets entering the bridge, performs minimal sanity tests on ipv4 and ipv6 packets and then pretends that these packets are being routed, not bridged. br_netfilter then calls the ip and ipv6 netfilter hooks from the bridge layer, i.e. ip(6)tables rulesets will also see these packets.

br_netfilter is also the reason for the iptables *physdev* match: This match is the only way to reliably tell routed and bridged packets apart in an iptables ruleset.

Note that ebtables and nftables will work fine without the br_netfilter module. iptables/ip6tables/arptables do not work for bridged traffic because they plug in the routing stack. nftables rules in ip/ip6/inet/arp families won't see traffic that is forwarded by a bridge either, but that's very much how it should be.

Historically the feature set of ebtables was very limited (it still is), this module was added to pretend packets are routed and invoke the ipv4/ipv6 netfilter hooks from the bridge so users had access to the more feature-rich iptables matching capabilities (including conntrack). nftables doesn't have this limitation, pretty much all features work regardless of the protocol family.

So, br_netfilter is only needed if users, for some reason, need to use ip(6)tables to filter packets forwarded by the bridge, or NAT bridged traffic. For pure link layer filtering, this module isn't needed.

<a id="rst-other-features"></a>

## Other Features

The Linux bridge also supports [IEEE 802.11 Proxy ARP](<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=958501163ddd6ea22a98f94fa0e7ce6d4734e5c4>)<a id="rst-ieee-802-11-proxy-arp"></a>, [Media Redundancy Protocol (MRP)](<https://lore.kernel.org/netdev/20200426132208.3232-1-horatiu.vultur@microchip.com/>)<a id="rst-media-redundancy-protocol-mrp"></a>, [Media Redundancy Protocol (MRP) LC mode](<https://lore.kernel.org/r/20201124082525.273820-1-horatiu.vultur@microchip.com>)<a id="rst-media-redundancy-protocol-mrp-lc-mode"></a>, [IEEE 802.1X port authentication](<https://lore.kernel.org/netdev/20220218155148.2329797-1-schultz.hans+netdev@gmail.com/>)<a id="rst-ieee-802-1x-port-authentication"></a>, and [MAC Authentication Bypass (MAB)](<https://lore.kernel.org/netdev/20221101193922.2125323-2-idosch@nvidia.com/>)<a id="rst-mac-authentication-bypass-mab"></a>.

<a id="rst-faq"></a>

## FAQ

<a id="rst-what-does-a-bridge-do"></a>

### What does a bridge do?

A bridge transparently forwards traffic between multiple network interfaces. In plain English this means that a bridge connects two or more physical Ethernet networks, to form one larger (logical) Ethernet network.

<a id="rst-is-it-l3-protocol-independent"></a>

### Is it L3 protocol independent?

Yes. The bridge sees all frames, but it *uses* only L2 headers/information. As such, the bridging functionality is protocol independent, and there should be no trouble forwarding IPX, NetBEUI, IP, IPv6, etc.

<a id="rst-contact-info"></a>

## Contact Info

The code is currently maintained by Roopa Prabhu &lt;[roopa@nvidia.com](<mailto:roopa@nvidia.com>)&gt; and Nikolay Aleksandrov &lt;[razor@blackwall.org](<mailto:razor@blackwall.org>)&gt;. Bridge bugs and enhancements are discussed on the linux-netdev mailing list [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>) and [bridge@lists.linux.dev](<mailto:bridge@lists.linux.dev>).

The list is open to anyone interested: [http://vger.kernel.org/vger-lists.html\#netdev](<http://vger.kernel.org/vger-lists.html#netdev>)

<a id="rst-external-links"></a>

## External Links

The old Documentation for Linux bridging is on: [https://wiki.linuxfoundation.org/networking/bridge](<https://wiki.linuxfoundation.org/networking/bridge>)

---

# SocketCAN - Controller Area Network

_Peios Kernel / Internals / Networking_

> The socketcan package is an implementation of CAN protocols (Controller Area Network) for Linux. CAN is a networking technology which has widespread use in automation, embedded devices, and automotive fields. While there have been other…

<a id="rst-socketcan-controller-area-network"></a>

<a id="rst-overview-what-is-socketcan"></a>

## Overview / What is SocketCAN

The socketcan package is an implementation of CAN protocols (Controller Area Network) for Linux.  CAN is a networking technology which has widespread use in automation, embedded devices, and automotive fields.  While there have been other CAN implementations for Linux based on character devices, SocketCAN uses the Berkeley socket API, the Linux network stack and implements the CAN device drivers as network interfaces.  The CAN socket API has been designed as similar as possible to the TCP/IP protocols to allow programmers, familiar with network programming, to easily learn how to use CAN sockets.

<a id="rst-motivation-why-using-the-socket-api"></a>
<a id="rst-socketcan-motivation"></a>

## Motivation / Why Using the Socket API

There have been CAN implementations for Linux before SocketCAN so the question arises, why we have started another project.  Most existing implementations come as a device driver for some CAN hardware, they are based on character devices and provide comparatively little functionality.  Usually, there is only a hardware-specific device driver which provides a character device interface to send and receive raw CAN frames, directly to/from the controller hardware. Queueing of frames and higher-level transport protocols like ISO-TP have to be implemented in user space applications.  Also, most character-device implementations support only one single process to open the device at a time, similar to a serial interface.  Exchanging the CAN controller requires employment of another device driver and often the need for adaption of large parts of the application to the new driver's API.

SocketCAN was designed to overcome all of these limitations.  A new protocol family has been implemented which provides a socket interface to user space applications and which builds upon the Linux network layer, enabling use all of the provided queueing functionality.  A device driver for CAN controller hardware registers itself with the Linux network layer as a network device, so that CAN frames from the controller can be passed up to the network layer and on to the CAN protocol family module and also vice-versa.  Also, the protocol family module provides an API for transport protocol modules to register, so that any number of transport protocols can be loaded or unloaded dynamically.  In fact, the can core module alone does not provide any protocol and cannot be used without loading at least one additional protocol module.  Multiple sockets can be opened at the same time, on different or the same protocol module and they can listen/send frames on different or the same CAN IDs.  Several sockets listening on the same interface for frames with the same CAN ID are all passed the same received matching CAN frames.  An application wishing to communicate using a specific transport protocol, e.g. ISO-TP, just selects that protocol when opening the socket, and then can read and write application data byte streams, without having to deal with CAN-IDs, frames, etc.

Similar functionality visible from user-space could be provided by a character device, too, but this would lead to a technically inelegant solution for a couple of reasons:

- **Intricate usage:**  Instead of passing a protocol argument to socket(2) and using bind(2) to select a CAN interface and CAN ID, an application would have to do all these operations using ioctl(2)s.

- **Code duplication:**  A character device cannot make use of the Linux network queueing code, so all that code would have to be duplicated for CAN networking.

- **Abstraction:**  In most existing character-device implementations, the hardware-specific device driver for a CAN controller directly provides the character device for the application to work with. This is at least very unusual in Unix systems for both, char and block devices.  For example you don't have a character device for a certain UART of a serial interface, a certain sound chip in your computer, a SCSI or IDE controller providing access to your hard disk or tape streamer device.  Instead, you have abstraction layers which provide a unified character or block device interface to the application on the one hand, and a interface for hardware-specific device drivers on the other hand.  These abstractions are provided by subsystems like the tty layer, the audio subsystem or the SCSI and IDE subsystems for the devices mentioned above.

  The easiest way to implement a CAN device driver is as a character device without such a (complete) abstraction layer, as is done by most existing drivers.  The right way, however, would be to add such a layer with all the functionality like registering for certain CAN IDs, supporting several open file descriptors and (de)multiplexing CAN frames between them, (sophisticated) queueing of CAN frames, and providing an API for device drivers to register with.  However, then it would be no more difficult, or may be even easier, to use the networking framework provided by the Linux kernel, and this is what SocketCAN does.

The use of the networking framework of the Linux kernel is just the natural and most appropriate way to implement CAN for Linux.

<a id="rst-socketcan-concept-1"></a>
<a id="rst-socketcan-concept"></a>

## SocketCAN Concept

As described in [Motivation / Why Using the Socket API](<#rst-socketcan-motivation>) the main goal of SocketCAN is to provide a socket interface to user space applications which builds upon the Linux network layer. In contrast to the commonly known TCP/IP and ethernet networking, the CAN bus is a broadcast-only(\!) medium that has no MAC-layer addressing like ethernet. The CAN-identifier (can_id) is used for arbitration on the CAN-bus. Therefore the CAN-IDs have to be chosen uniquely on the bus. When designing a CAN-ECU network the CAN-IDs are mapped to be sent by a specific ECU. For this reason a CAN-ID can be treated best as a kind of source address.

<a id="rst-receive-lists"></a>
<a id="rst-socketcan-receive-lists"></a>

### Receive Lists

The network transparent access of multiple applications leads to the problem that different applications may be interested in the same CAN-IDs from the same CAN network interface. The SocketCAN core module - which implements the protocol family CAN - provides several high efficient receive lists for this reason. If e.g. a user space application opens a CAN RAW socket, the raw protocol module itself requests the (range of) CAN-IDs from the SocketCAN core that are requested by the user. The subscription and unsubscription of CAN-IDs can be done for specific CAN interfaces or for all(\!) known CAN interfaces with the can_rx\_(un)register() functions provided to CAN protocol modules by the SocketCAN core (see [SocketCAN Core Module](<#rst-socketcan-core-module>)). To optimize the CPU usage at runtime the receive lists are split up into several specific lists per device that match the requested filter complexity for a given use-case.

<a id="rst-local-loopback-of-sent-frames"></a>
<a id="rst-socketcan-local-loopback1"></a>

### Local Loopback of Sent Frames

As known from other networking concepts the data exchanging applications may run on the same or different nodes without any change (except for the according addressing information):



```text
 ___   ___   ___                   _______   ___
| _ | | _ | | _ |                 | _   _ | | _ |
||A|| ||B|| ||C||                 ||A| |B|| ||C||
|___| |___| |___|                 |_______| |___|
  |     |     |                       |       |
-----------------(1)- CAN bus -(2)---------------
```

To ensure that application A receives the same information in the example (2) as it would receive in example (1) there is need for some kind of local loopback of the sent CAN frames on the appropriate node.

The Linux network devices (by default) just can handle the transmission and reception of media dependent frames. Due to the arbitration on the CAN bus the transmission of a low prio CAN-ID may be delayed by the reception of a high prio CAN frame. To reflect the correct <a id="rst-footnote-reference-1"></a>[1](#rst-f1) traffic on the node the loopback of the sent data has to be performed right after a successful transmission. If the CAN network interface is not capable of performing the loopback for some reason the SocketCAN core can do this task as a fallback solution. See [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames-1>) for details (recommended).

The loopback functionality is enabled by default to reflect standard networking behaviour for CAN applications. Due to some requests from the RT-SocketCAN group the loopback optionally may be disabled for each separate socket. See sockopts from the CAN RAW sockets in [RAW Protocol Sockets with can_filters (SOCK_RAW)](<#rst-socketcan-raw-sockets>).

<a id="rst-f1"></a>



**[1]** you really like to have this when you're running analyser tools like 'candump' or 'cansniffer' on the (same) node.

<a id="rst-network-problem-notifications"></a>
<a id="rst-socketcan-network-problem-notifications"></a>

### Network Problem Notifications

The use of the CAN bus may lead to several problems on the physical and media access control layer. Detecting and logging of these lower layer problems is a vital requirement for CAN users to identify hardware issues on the physical transceiver layer as well as arbitration problems and error frames caused by the different ECUs. The occurrence of detected errors are important for diagnosis and have to be logged together with the exact timestamp. For this reason the CAN interface driver can generate so called Error Message Frames that can optionally be passed to the user application in the same way as other CAN frames. Whenever an error on the physical layer or the MAC layer is detected (e.g. by the CAN controller) the driver creates an appropriate error message frame. Error messages frames can be requested by the user application using the common CAN filter mechanisms. Inside this filter definition the (interested) type of errors may be selected. The reception of error messages is disabled by default. The format of the CAN error message frame is briefly described in the Linux header file "include/uapi/linux/can/error.h".

<a id="rst-how-to-use-socketcan"></a>

## How to use SocketCAN

Like TCP/IP, you first need to open a socket for communicating over a CAN network. Since SocketCAN implements a new protocol family, you need to pass PF_CAN as the first argument to the socket(2) system call. Currently, there are two CAN protocols to choose from, the raw socket protocol and the broadcast manager (BCM). So to open a socket, you would write:



```text
s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
```

and:



```text
s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
```

respectively.  After the successful creation of the socket, you would normally use the bind(2) system call to bind the socket to a CAN interface (which is different from TCP/IP due to different addressing - see [SocketCAN Concept](<#rst-socketcan-concept>)). After binding (CAN_RAW) or connecting (CAN_BCM) the socket, you can read(2) and write(2) from/to the socket or use send(2), sendto(2), sendmsg(2) and the recv\* counterpart operations on the socket as usual. There are also CAN specific socket options described below.

The Classical CAN frame structure (aka CAN 2.0B), the CAN FD frame structure and the sockaddr structure are defined in include/linux/can.h:



```C
struct can_frame {
        canid_t can_id;  /* 32 bit CAN_ID + EFF/RTR/ERR flags */
        union {
                /* CAN frame payload length in byte (0 .. CAN_MAX_DLEN)
                 * was previously named can_dlc so we need to carry that
                 * name for legacy support
                 */
                __u8 len;
                __u8 can_dlc; /* deprecated */
        };
        __u8    __pad;   /* padding */
        __u8    __res0;  /* reserved / padding */
        __u8    len8_dlc; /* optional DLC for 8 byte payload length (9 .. 15) */
        __u8    data[8] __attribute__((aligned(8)));
};
```

Remark: The len element contains the payload length in bytes and should be used instead of can_dlc. The deprecated can_dlc was misleadingly named as it always contained the plain payload length in bytes and not the so called 'data length code' (DLC).

To pass the raw DLC from/to a Classical CAN network device the len8_dlc element can contain values 9 .. 15 when the len element is 8 (the real payload length for all DLC values greater or equal to 8).

The alignment of the (linear) payload data\[\] to a 64bit boundary allows the user to define their own structs and unions to easily access the CAN payload. There is no given byteorder on the CAN bus by default. A read(2) system call on a CAN_RAW socket transfers a struct can_frame to the user space.

The sockaddr_can structure has an interface index like the PF_PACKET socket, that also binds to a specific interface:



```C
struct sockaddr_can {
        sa_family_t can_family;
        int         can_ifindex;
        union {
                /* transport protocol class address info (e.g. ISOTP) */
                struct { canid_t rx_id, tx_id; } tp;

                /* J1939 address information */
                struct {
                        /* 8 byte name when using dynamic addressing */
                        __u64 name;

                        /* pgn:
                         * 8 bit: PS in PDU2 case, else 0
                         * 8 bit: PF
                         * 1 bit: DP
                         * 1 bit: reserved
                         */
                        __u32 pgn;

                        /* 1 byte address */
                        __u8 addr;
                } j1939;

                /* reserved for future CAN protocols address information */
        } can_addr;
};
```

To determine the interface index an appropriate ioctl() has to be used (example for CAN_RAW sockets without error checking):



```C
int s;
struct sockaddr_can addr;
struct ifreq ifr;

s = socket(PF_CAN, SOCK_RAW, CAN_RAW);

strcpy(ifr.ifr_name, "can0" );
ioctl(s, SIOCGIFINDEX, &ifr);

addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;

bind(s, (struct sockaddr *)&addr, sizeof(addr));

(..)
```

To bind a socket to all(\!) CAN interfaces the interface index must be 0 (zero). In this case the socket receives CAN frames from every enabled CAN interface. To determine the originating CAN interface the system call recvfrom(2) may be used instead of read(2). To send on a socket that is bound to 'any' interface sendto(2) is needed to specify the outgoing interface.

Reading CAN frames from a bound CAN_RAW socket (see above) consists of reading a struct can_frame:



```C
struct can_frame frame;

nbytes = read(s, &frame, sizeof(struct can_frame));

if (nbytes < 0) {
        perror("can raw socket read");
        return 1;
}

/* paranoid check ... */
if (nbytes < sizeof(struct can_frame)) {
        fprintf(stderr, "read: incomplete CAN frame\n");
        return 1;
}

/* do something with the received CAN frame */
```

Writing CAN frames can be done similarly, with the write(2) system call:



```text
nbytes = write(s, &frame, sizeof(struct can_frame));
```

When the CAN interface is bound to 'any' existing CAN interface (addr.can_ifindex = 0) it is recommended to use recvfrom(2) if the information about the originating CAN interface is needed:



```C
struct sockaddr_can addr;
struct ifreq ifr;
socklen_t len = sizeof(addr);
struct can_frame frame;

nbytes = recvfrom(s, &frame, sizeof(struct can_frame),
                  0, (struct sockaddr*)&addr, &len);

/* get interface name of the received CAN frame */
ifr.ifr_ifindex = addr.can_ifindex;
ioctl(s, SIOCGIFNAME, &ifr);
printf("Received a CAN frame from interface %s", ifr.ifr_name);
```

To write CAN frames on sockets bound to 'any' CAN interface the outgoing interface has to be defined certainly:



```C
strcpy(ifr.ifr_name, "can0");
ioctl(s, SIOCGIFINDEX, &ifr);
addr.can_ifindex = ifr.ifr_ifindex;
addr.can_family  = AF_CAN;

nbytes = sendto(s, &frame, sizeof(struct can_frame),
                0, (struct sockaddr*)&addr, sizeof(addr));
```

An accurate timestamp can be obtained with an ioctl(2) call after reading a message from the socket:



```C
struct timeval tv;
ioctl(s, SIOCGSTAMP, &tv);
```

The timestamp has a resolution of one microsecond and is set automatically at the reception of a CAN frame.

Remark about CAN FD (flexible data rate) support:

Generally the handling of CAN FD is very similar to the formerly described examples. The new CAN FD capable CAN controllers support two different bitrates for the arbitration phase and the payload phase of the CAN FD frame and up to 64 bytes of payload. This extended payload length breaks all the kernel interfaces (ABI) which heavily rely on the CAN frame with fixed eight bytes of payload (struct can_frame) like the CAN_RAW socket. Therefore e.g. the CAN_RAW socket supports a new socket option CAN_RAW_FD_FRAMES that switches the socket into a mode that allows the handling of CAN FD frames and Classical CAN frames simultaneously (see [RAW Socket Option CAN_RAW_FD_FRAMES](<#rst-socketcan-rawfd>)).

The struct canfd_frame is defined in include/linux/can.h:



```C
struct canfd_frame {
        canid_t can_id;  /* 32 bit CAN_ID + EFF/RTR/ERR flags */
        __u8    len;     /* frame payload length in byte (0 .. 64) */
        __u8    flags;   /* additional flags for CAN FD */
        __u8    __res0;  /* reserved / padding */
        __u8    __res1;  /* reserved / padding */
        __u8    data[64] __attribute__((aligned(8)));
};
```

The struct canfd_frame and the existing struct can_frame have the can_id, the payload length and the payload data at the same offset inside their structures. This allows to handle the different structures very similar. When the content of a struct can_frame is copied into a struct canfd_frame all structure elements can be used as-is - only the data\[\] becomes extended.

When introducing the struct canfd_frame it turned out that the data length code (DLC) of the struct can_frame was used as a length information as the length and the DLC has a 1:1 mapping in the range of 0 .. 8. To preserve the easy handling of the length information the canfd_frame.len element contains a plain length value from 0 .. 64. So both canfd_frame.len and can_frame.len are equal and contain a length information and no DLC. For details about the distinction of CAN and CAN FD capable devices and the mapping to the bus-relevant data length code (DLC), see [CAN FD (Flexible Data Rate) Driver Support](<#rst-socketcan-can-fd-driver>).

The length of the two CAN(FD) frame structures define the maximum transfer unit (MTU) of the CAN(FD) network interface and skbuff data length. Two definitions are specified for CAN specific MTUs in include/linux/can.h:



```C
#define CAN_MTU   (sizeof(struct can_frame))   == 16  => Classical CAN frame
#define CANFD_MTU (sizeof(struct canfd_frame)) == 72  => CAN FD frame
```

<a id="rst-returned-message-flags"></a>

### Returned Message Flags

When using the system call recvmsg(2) on a RAW or a BCM socket, the msg-&gt;msg_flags field may contain the following flags:

- **MSG_DONTROUTE:**

  set when the received frame was created on the local host.

- **MSG_CONFIRM:**

  set when the frame was sent via the socket it is received on. This flag can be interpreted as a 'transmission confirmation' when the CAN driver supports the echo of frames on driver level, see [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames>) and [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames-1>). (Note: In order to receive such messages on a RAW socket, CAN_RAW_RECV_OWN_MSGS must be set.)

<a id="rst-raw-protocol-sockets-with-can-filters-sock-raw"></a>
<a id="rst-socketcan-raw-sockets"></a>

### RAW Protocol Sockets with can_filters (SOCK_RAW)

Using CAN_RAW sockets is extensively comparable to the commonly known access to CAN character devices. To meet the new possibilities provided by the multi user SocketCAN approach, some reasonable defaults are set at RAW socket binding time:

- The filters are set to exactly one filter receiving everything

- The socket only receives valid data frames (=&gt; no error message frames)

- The loopback of sent CAN frames is enabled (see [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames-1>))

- The socket does not receive its own sent frames (in loopback mode)

These default settings may be changed before or after binding the socket. To use the referenced definitions of the socket options for CAN_RAW sockets, include &lt;linux/can/raw.h&gt;.

<a id="rst-raw-socket-option-can-raw-filter"></a>
<a id="rst-socketcan-rawfilter"></a>

#### RAW socket option CAN_RAW_FILTER

The reception of CAN frames using CAN_RAW sockets can be controlled by defining 0 .. n filters with the CAN_RAW_FILTER socket option.

The CAN filter structure is defined in include/linux/can.h:



```C
struct can_filter {
        canid_t can_id;
        canid_t can_mask;
};
```

A filter matches, when:



```C
<received_can_id> & mask == can_id & mask
```

which is analogous to known CAN controllers hardware filter semantics. The filter can be inverted in this semantic, when the CAN_INV_FILTER bit is set in can_id element of the can_filter structure. In contrast to CAN controller hardware filters the user may set 0 .. n receive filters for each open socket separately:



```C
struct can_filter rfilter[2];

rfilter[0].can_id   = 0x123;
rfilter[0].can_mask = CAN_SFF_MASK;
rfilter[1].can_id   = 0x200;
rfilter[1].can_mask = 0x700;

setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
```

To disable the reception of CAN frames on the selected CAN_RAW socket:



```C
setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
```

To set the filters to zero filters is quite obsolete as to not read data causes the raw socket to discard the received CAN frames. But having this 'send only' use-case we may remove the receive list in the Kernel to save a little (really a very little\!) CPU usage.

<a id="rst-can-filter-usage-optimisation"></a>

##### CAN Filter Usage Optimisation

The CAN filters are processed in per-device filter lists at CAN frame reception time. To reduce the number of checks that need to be performed while walking through the filter lists the CAN core provides an optimized filter handling when the filter subscription focuses on a single CAN ID.

For the possible 2048 SFF CAN identifiers the identifier is used as an index to access the corresponding subscription list without any further checks. For the 2^29 possible EFF CAN identifiers a 10 bit XOR folding is used as hash function to retrieve the EFF table index.

To benefit from the optimized filters for single CAN identifiers the CAN_SFF_MASK or CAN_EFF_MASK have to be set into can_filter.mask together with set CAN_EFF_FLAG and CAN_RTR_FLAG bits. A set CAN_EFF_FLAG bit in the can_filter.mask makes clear that it matters whether a SFF or EFF CAN ID is subscribed. E.g. in the example from above:



```C
rfilter[0].can_id   = 0x123;
rfilter[0].can_mask = CAN_SFF_MASK;
```

both SFF frames with CAN ID 0x123 and EFF frames with 0xXXXXX123 can pass.

To filter for only 0x123 (SFF) and 0x12345678 (EFF) CAN identifiers the filter has to be defined in this way to benefit from the optimized filters:



```C
struct can_filter rfilter[2];

rfilter[0].can_id   = 0x123;
rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_SFF_MASK);
rfilter[1].can_id   = 0x12345678 | CAN_EFF_FLAG;
rfilter[1].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);

setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter));
```

<a id="rst-raw-socket-option-can-raw-err-filter"></a>

#### RAW Socket Option CAN_RAW_ERR_FILTER

As described in [Network Problem Notifications](<#rst-socketcan-network-problem-notifications>) the CAN interface driver can generate so called Error Message Frames that can optionally be passed to the user application in the same way as other CAN frames. The possible errors are divided into different error classes that may be filtered using the appropriate error mask. To register for every possible error condition CAN_ERR_MASK can be used as value for the error mask. The values for the error mask are defined in linux/can/error.h:



```C
can_err_mask_t err_mask = ( CAN_ERR_TX_TIMEOUT | CAN_ERR_BUSOFF );

setsockopt(s, SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
           &err_mask, sizeof(err_mask));
```

<a id="rst-raw-socket-option-can-raw-loopback"></a>

#### RAW Socket Option CAN_RAW_LOOPBACK

To meet multi user needs the local loopback is enabled by default (see [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames>) for details). But in some embedded use-cases (e.g. when only one application uses the CAN bus) this loopback functionality can be disabled (separately for each socket):



```C
int loopback = 0; /* 0 = disabled, 1 = enabled (default) */

setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback));
```

<a id="rst-raw-socket-option-can-raw-recv-own-msgs"></a>

#### RAW socket option CAN_RAW_RECV_OWN_MSGS

When the local loopback is enabled, all the sent CAN frames are looped back to the open CAN sockets that registered for the CAN frames' CAN-ID on this given interface to meet the multi user needs. The reception of the CAN frames on the same socket that was sending the CAN frame is assumed to be unwanted and therefore disabled by default. This default behaviour may be changed on demand:



```C
int recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */

setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
           &recv_own_msgs, sizeof(recv_own_msgs));
```

Note that reception of a socket's own CAN frames are subject to the same filtering as other CAN frames (see [RAW socket option CAN_RAW_FILTER](<#rst-socketcan-rawfilter>)).

<a id="rst-raw-socket-option-can-raw-fd-frames"></a>
<a id="rst-socketcan-rawfd"></a>

#### RAW Socket Option CAN_RAW_FD_FRAMES

CAN FD support in CAN_RAW sockets can be enabled with a new socket option CAN_RAW_FD_FRAMES which is off by default. When the new socket option is not supported by the CAN_RAW socket (e.g. on older kernels), switching the CAN_RAW_FD_FRAMES option returns the error -ENOPROTOOPT.

Once CAN_RAW_FD_FRAMES is enabled the application can send both CAN frames and CAN FD frames. OTOH the application has to handle CAN and CAN FD frames when reading from the socket:



```C
CAN_RAW_FD_FRAMES enabled:  CAN_MTU and CANFD_MTU are allowed
CAN_RAW_FD_FRAMES disabled: only CAN_MTU is allowed (default)
```

Example:



```C
[ remember: CANFD_MTU == sizeof(struct canfd_frame) ]

struct canfd_frame cfd;

nbytes = read(s, &cfd, CANFD_MTU);

if (nbytes == CANFD_MTU) {
        printf("got CAN FD frame with length %d\n", cfd.len);
        /* cfd.flags contains valid data */
} else if (nbytes == CAN_MTU) {
        printf("got Classical CAN frame with length %d\n", cfd.len);
        /* cfd.flags is undefined */
} else {
        fprintf(stderr, "read: invalid CAN(FD) frame\n");
        return 1;
}

/* the content can be handled independently from the received MTU size */

printf("can_id: %X data length: %d data: ", cfd.can_id, cfd.len);
for (i = 0; i < cfd.len; i++)
        printf("%02X ", cfd.data[i]);
```

When reading with size CANFD_MTU only returns CAN_MTU bytes that have been received from the socket a Classical CAN frame has been read into the provided CAN FD structure. Note that the canfd_frame.flags data field is not specified in the struct can_frame and therefore it is only valid in CANFD_MTU sized CAN FD frames.

Implementation hint for new CAN applications:

To build a CAN FD aware application use struct canfd_frame as basic CAN data structure for CAN_RAW based applications. When the application is executed on an older Linux kernel and switching the CAN_RAW_FD_FRAMES socket option returns an error: No problem. You'll get Classical CAN frames or CAN FD frames and can process them the same way.

When sending to CAN devices make sure that the device is capable to handle CAN FD frames by checking if the device maximum transfer unit is CANFD_MTU. The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall.

<a id="rst-raw-socket-option-can-raw-join-filters"></a>

#### RAW socket option CAN_RAW_JOIN_FILTERS

The CAN_RAW socket can set multiple CAN identifier specific filters that lead to multiple filters in the af_can.c filter processing. These filters are independent from each other which leads to logical OR'ed filters when applied (see [RAW socket option CAN_RAW_FILTER](<#rst-socketcan-rawfilter>)).

This socket option joins the given CAN filters in the way that only CAN frames are passed to user space that matched *all* given CAN filters. The semantic for the applied filters is therefore changed to a logical AND.

This is useful especially when the filterset is a combination of filters where the CAN_INV_FILTER flag is set in order to notch single CAN IDs or CAN ID ranges from the incoming traffic.

<a id="rst-broadcast-manager-protocol-sockets-sock-dgram"></a>

### Broadcast Manager Protocol Sockets (SOCK_DGRAM)

The Broadcast Manager protocol provides a command based configuration interface to filter and send (e.g. cyclic) CAN messages in kernel space.

Receive filters can be used to down sample frequent messages; detect events such as message contents changes, packet length changes, and do time-out monitoring of received messages.

Periodic transmission tasks of CAN frames or a sequence of CAN frames can be created and modified at runtime; both the message content and the two possible transmit intervals can be altered.

A BCM socket is not intended for sending individual CAN frames using the struct can_frame as known from the CAN_RAW socket. Instead a special BCM configuration message is defined. The basic BCM configuration message used to communicate with the broadcast manager and the available operations are defined in the linux/can/bcm.h include. The BCM message consists of a message header with a command ('opcode') followed by zero or more CAN frames. The broadcast manager sends responses to user space in the same form:



```C
struct bcm_msg_head {
        __u32 opcode;                   /* command */
        __u32 flags;                    /* special flags */
        __u32 count;                    /* run 'count' times with ival1 */
        struct timeval ival1, ival2;    /* count and subsequent interval */
        canid_t can_id;                 /* unique can_id for task */
        __u32 nframes;                  /* number of can_frames following */
        struct can_frame frames[];
};
```

The aligned payload 'frames' uses the same basic CAN frame structure defined at the beginning of [RAW Socket Option CAN_RAW_FD_FRAMES](<#rst-socketcan-rawfd>) and in the include/linux/can.h include. All messages to the broadcast manager from user space have this structure.

Note a CAN_BCM socket must be connected instead of bound after socket creation (example without error checking):



```C
int s;
struct sockaddr_can addr;
struct ifreq ifr;

s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);

strcpy(ifr.ifr_name, "can0");
ioctl(s, SIOCGIFINDEX, &ifr);

addr.can_family = AF_CAN;
addr.can_ifindex = ifr.ifr_ifindex;

connect(s, (struct sockaddr *)&addr, sizeof(addr));

(..)
```

The broadcast manager socket is able to handle any number of in flight transmissions or receive filters concurrently. The different RX/TX jobs are distinguished by the unique can_id in each BCM message. However additional CAN_BCM sockets are recommended to communicate on multiple CAN interfaces. When the broadcast manager socket is bound to 'any' CAN interface (=&gt; the interface index is set to zero) the configured receive filters apply to any CAN interface unless the sendto() syscall is used to overrule the 'any' CAN interface index. When using recvfrom() instead of read() to retrieve BCM socket messages the originating CAN interface is provided in can_ifindex.

<a id="rst-broadcast-manager-operations"></a>

#### Broadcast Manager Operations

The opcode defines the operation for the broadcast manager to carry out, or details the broadcast managers response to several events, including user requests.

Transmit Operations (user space to broadcast manager):

- **TX_SETUP:**

  Create (cyclic) transmission task.

- **TX_DELETE:**

  Remove (cyclic) transmission task, requires only can_id.

- **TX_READ:**

  Read properties of (cyclic) transmission task for can_id.

- **TX_SEND:**

  Send one CAN frame.

Transmit Responses (broadcast manager to user space):

- **TX_STATUS:**

  Reply to TX_READ request (transmission task configuration).

- **TX_EXPIRED:**

  Notification when counter finishes sending at initial interval 'ival1'. Requires the TX_COUNTEVT flag to be set at TX_SETUP.

Receive Operations (user space to broadcast manager):

- **RX_SETUP:**

  Create RX content filter subscription.

- **RX_DELETE:**

  Remove RX content filter subscription, requires only can_id.

- **RX_READ:**

  Read properties of RX content filter subscription for can_id.

Receive Responses (broadcast manager to user space):

- **RX_STATUS:**

  Reply to RX_READ request (filter task configuration).

- **RX_TIMEOUT:**

  Cyclic message is detected to be absent (timer ival1 expired).

- **RX_CHANGED:**

  BCM message with updated CAN frame (detected content change). Sent on first message received or on receipt of revised CAN messages.

<a id="rst-broadcast-manager-message-flags"></a>

#### Broadcast Manager Message Flags

When sending a message to the broadcast manager the 'flags' element may contain the following flag definitions which influence the behaviour:

- **SETTIMER:**

  Set the values of ival1, ival2 and count

- **STARTTIMER:**

  Start the timer with the actual values of ival1, ival2 and count. Starting the timer leads simultaneously to emit a CAN frame.

- **TX_COUNTEVT:**

  Create the message TX_EXPIRED when count expires

- **TX_ANNOUNCE:**

  A change of data by the process is emitted immediately.

- **TX_CP_CAN_ID:**

  Copies the can_id from the message header to each subsequent frame in frames. This is intended as usage simplification. For TX tasks the unique can_id from the message header may differ from the can_id(s) stored for transmission in the subsequent struct can_frame(s).

- **RX_FILTER_ID:**

  Filter by can_id alone, no frames required (nframes=0).

- **RX_CHECK_DLC:**

  A change of the DLC leads to an RX_CHANGED.

- **RX_NO_AUTOTIMER:**

  Prevent automatically starting the timeout monitor.

- **RX_ANNOUNCE_RESUME:**

  If passed at RX_SETUP and a receive timeout occurred, a RX_CHANGED message will be generated when the (cyclic) receive restarts.

- **TX_RESET_MULTI_IDX:**

  Reset the index for the multiple frame transmission.

- **RX_RTR_FRAME:**

  Send reply for RTR-request (placed in op-&gt;frames\[0\]).

- **CAN_FD_FRAME:**

  The CAN frames following the bcm_msg_head are struct canfd_frame's

<a id="rst-broadcast-manager-transmission-timers"></a>

#### Broadcast Manager Transmission Timers

Periodic transmission configurations may use up to two interval timers. In this case the BCM sends a number of messages ('count') at an interval 'ival1', then continuing to send at another given interval 'ival2'. When only one timer is needed 'count' is set to zero and only 'ival2' is used. When SET_TIMER and START_TIMER flag were set the timers are activated. The timer values can be altered at runtime when only SET_TIMER is set.

<a id="rst-broadcast-manager-message-sequence-transmission"></a>

#### Broadcast Manager message sequence transmission

Up to 256 CAN frames can be transmitted in a sequence in the case of a cyclic TX task configuration. The number of CAN frames is provided in the 'nframes' element of the BCM message head. The defined number of CAN frames are added as array to the TX_SETUP BCM configuration message:



```C
/* create a struct to set up a sequence of four CAN frames */
struct {
        struct bcm_msg_head msg_head;
        struct can_frame frame[4];
} mytxmsg;

(..)
mytxmsg.msg_head.nframes = 4;
(..)

write(s, &mytxmsg, sizeof(mytxmsg));
```

With every transmission the index in the array of CAN frames is increased and set to zero at index overflow.

<a id="rst-broadcast-manager-receive-filter-timers"></a>

#### Broadcast Manager Receive Filter Timers

The timer values ival1 or ival2 may be set to non-zero values at RX_SETUP. When the SET_TIMER flag is set the timers are enabled:

- **ival1:**

  Send RX_TIMEOUT when a received message is not received again within the given time. When START_TIMER is set at RX_SETUP the timeout detection is activated directly - even without a former CAN frame reception.

- **ival2:**

  Throttle the received message rate down to the value of ival2. This is useful to reduce messages for the application when the signal inside the CAN frame is stateless as state changes within the ival2 period may get lost.

<a id="rst-broadcast-manager-multiplex-message-receive-filter"></a>

#### Broadcast Manager Multiplex Message Receive Filter

To filter for content changes in multiplex message sequences an array of more than one CAN frames can be passed in a RX_SETUP configuration message. The data bytes of the first CAN frame contain the mask of relevant bits that have to match in the subsequent CAN frames with the received CAN frame. If one of the subsequent CAN frames is matching the bits in that frame data mark the relevant content to be compared with the previous received content. Up to 257 CAN frames (multiplex filter bit mask CAN frame plus 256 CAN filters) can be added as array to the TX_SETUP BCM configuration message:



```C
/* usually used to clear CAN frame data[] - beware of endian problems! */
#define U64_DATA(p) (*(unsigned long long*)(p)->data)

struct {
        struct bcm_msg_head msg_head;
        struct can_frame frame[5];
} msg;

msg.msg_head.opcode  = RX_SETUP;
msg.msg_head.can_id  = 0x42;
msg.msg_head.flags   = 0;
msg.msg_head.nframes = 5;
U64_DATA(&msg.frame[0]) = 0xFF00000000000000ULL; /* MUX mask */
U64_DATA(&msg.frame[1]) = 0x01000000000000FFULL; /* data mask (MUX 0x01) */
U64_DATA(&msg.frame[2]) = 0x0200FFFF000000FFULL; /* data mask (MUX 0x02) */
U64_DATA(&msg.frame[3]) = 0x330000FFFFFF0003ULL; /* data mask (MUX 0x33) */
U64_DATA(&msg.frame[4]) = 0x4F07FC0FF0000000ULL; /* data mask (MUX 0x4F) */

write(s, &msg, sizeof(msg));
```

<a id="rst-broadcast-manager-can-fd-support"></a>

#### Broadcast Manager CAN FD Support

The programming API of the CAN_BCM depends on struct can_frame which is given as array directly behind the bcm_msg_head structure. To follow this schema for the CAN FD frames a new flag 'CAN_FD_FRAME' in the bcm_msg_head flags indicates that the concatenated CAN frame structures behind the bcm_msg_head are defined as struct canfd_frame:



```C
struct {
        struct bcm_msg_head msg_head;
        struct canfd_frame frame[5];
} msg;

msg.msg_head.opcode  = RX_SETUP;
msg.msg_head.can_id  = 0x42;
msg.msg_head.flags   = CAN_FD_FRAME;
msg.msg_head.nframes = 5;
(..)
```

When using CAN FD frames for multiplex filtering the MUX mask is still expected in the first 64 bit of the struct canfd_frame data section.

<a id="rst-connected-transport-protocols-sock-seqpacket"></a>

### Connected Transport Protocols (SOCK_SEQPACKET)

(to be written)

<a id="rst-unconnected-transport-protocols-sock-dgram"></a>

### Unconnected Transport Protocols (SOCK_DGRAM)

(to be written)

<a id="rst-socketcan-core-module-1"></a>
<a id="rst-socketcan-core-module"></a>

## SocketCAN Core Module

The SocketCAN core module implements the protocol family PF_CAN. CAN protocol modules are loaded by the core module at runtime. The core module provides an interface for CAN protocol modules to subscribe needed CAN IDs (see [Receive Lists](<#rst-socketcan-receive-lists>)).

<a id="rst-can-ko-module-params"></a>

### can.ko Module Params

- **stats_timer**: To calculate the SocketCAN core statistics (e.g. current/maximum frames per second) this 1 second timer is invoked at can.ko module start time by default. This timer can be disabled by using stattimer=0 on the module commandline.

- **debug**: (removed since SocketCAN SVN r546)

<a id="rst-procfs-content"></a>

### procfs content

As described in [Receive Lists](<#rst-socketcan-receive-lists>) the SocketCAN core uses several filter lists to deliver received CAN frames to CAN protocol modules. These receive lists, their filters and the count of filter matches can be checked in the appropriate receive list. All entries contain the device and a protocol module identifier:



```text
foo@bar:~$ cat /proc/net/can/rcvlist_all

receive list 'rx_all':
  (vcan3: no entry)
  (vcan2: no entry)
  (vcan1: no entry)
  device   can_id   can_mask  function  userdata   matches  ident
   vcan0     000    00000000  f88e6370  f6c6f400         0  raw
  (any: no entry)
```

In this example an application requests any CAN traffic from vcan0:



```text
rcvlist_all - list for unfiltered entries (no filter operations)
rcvlist_eff - list for single extended frame (EFF) entries
rcvlist_err - list for error message frames masks
rcvlist_fil - list for mask/value filters
rcvlist_inv - list for mask/value filters (inverse semantic)
rcvlist_sff - list for single standard frame (SFF) entries
```

Additional procfs files in /proc/net/can:



```text
stats       - SocketCAN core statistics (rx/tx frames, match ratios, ...)
reset_stats - manual statistic reset
version     - prints SocketCAN core and ABI version (removed in Linux 5.10)
```

<a id="rst-writing-own-can-protocol-modules"></a>

### Writing Own CAN Protocol Modules

To implement a new protocol in the protocol family PF_CAN a new protocol has to be defined in include/linux/can.h . The prototypes and definitions to use the SocketCAN core can be accessed by including include/linux/can/core.h . In addition to functions that register the CAN protocol and the CAN device notifier chain there are functions to subscribe CAN frames received by CAN interfaces and to send CAN frames:



```text
can_rx_register   - subscribe CAN frames from a specific interface
can_rx_unregister - unsubscribe CAN frames from a specific interface
can_send          - transmit a CAN frame (optional with local loopback)
```

For details see the kerneldoc documentation in net/can/af_can.c or the source code of net/can/raw.c or net/can/bcm.c .

<a id="rst-can-network-drivers"></a>

## CAN Network Drivers

Writing a CAN network device driver is much easier than writing a CAN character device driver. Similar to other known network device drivers you mainly have to deal with:

- TX: Put the CAN frame from the socket buffer to the CAN controller.

- RX: Put the CAN frame from the CAN controller to the socket buffer.

See e.g. at [Documentation/networking/netdevices.rst](/kernel/internals/networking/netdevices.md) . The differences for writing CAN network device driver are described below:

<a id="rst-general-settings"></a>

### General Settings

CAN network device drivers can use alloc_candev_mqs() and friends instead of alloc_netdev_mqs(), to automatically take care of CAN-specific setup:



```C
dev = alloc_candev_mqs(...);
```

The struct can_frame or struct canfd_frame is the payload of each socket buffer (skbuff) in the protocol family PF_CAN.

<a id="rst-local-loopback-of-sent-frames-1"></a>
<a id="rst-socketcan-local-loopback2"></a>

### Local Loopback of Sent Frames

As described in [Local Loopback of Sent Frames](<#rst-local-loopback-of-sent-frames>) the CAN network device driver should support a local loopback functionality similar to the local echo e.g. of tty devices. In this case the driver flag IFF_ECHO has to be set to prevent the PF_CAN core from locally echoing sent frames (aka loopback) as fallback solution:



```text
dev->flags = (IFF_NOARP | IFF_ECHO);
```

<a id="rst-can-controller-hardware-filters"></a>

### CAN Controller Hardware Filters

To reduce the interrupt load on deep embedded systems some CAN controllers support the filtering of CAN IDs or ranges of CAN IDs. These hardware filter capabilities vary from controller to controller and have to be identified as not feasible in a multi-user networking approach. The use of the very controller specific hardware filters could make sense in a very dedicated use-case, as a filter on driver level would affect all users in the multi-user system. The high efficient filter sets inside the PF_CAN core allow to set different multiple filters for each socket separately. Therefore the use of hardware filters goes to the category 'handmade tuning on deep embedded systems'. The author is running a MPC603e @133MHz with four SJA1000 CAN controllers from 2002 under heavy bus load without any problems ...

<a id="rst-switchable-termination-resistors"></a>

### Switchable Termination Resistors

CAN bus requires a specific impedance across the differential pair, typically provided by two 120Ohm resistors on the farthest nodes of the bus. Some CAN controllers support activating / deactivating a termination resistor(s) to provide the correct impedance.

Query the available resistances:



```text
$ ip -details link show can0
...
termination 120 [ 0, 120 ]
```

Activate the terminating resistor:



```text
$ ip link set dev can0 type can termination 120
```

Deactivate the terminating resistor:



```text
$ ip link set dev can0 type can termination 0
```

To enable termination resistor support to a can-controller, either implement in the controller's struct can-priv:



```text
termination_const
termination_const_cnt
do_set_termination
```

or add gpio control with the device tree entries from Documentation/devicetree/bindings/net/can/can-controller.yaml

<a id="rst-the-virtual-can-driver-vcan"></a>

### The Virtual CAN Driver (vcan)

Similar to the network loopback devices, vcan offers a virtual local CAN interface. A full qualified address on CAN consists of

- a unique CAN Identifier (CAN ID)

- the CAN bus this CAN ID is transmitted on (e.g. can0)

so in common use cases more than one virtual CAN interface is needed.

The virtual CAN interfaces allow the transmission and reception of CAN frames without real CAN controller hardware. Virtual CAN network devices are usually named 'vcanX', like vcan0 vcan1 vcan2 ... When compiled as a module the virtual CAN driver module is called vcan.ko

Since Linux Kernel version 2.6.24 the vcan driver supports the Kernel netlink interface to create vcan network devices. The creation and removal of vcan network devices can be managed with the ip(8) tool:



```text
- Create a virtual CAN network interface:
     $ ip link add type vcan

- Create a virtual CAN network interface with a specific name 'vcan42':
     $ ip link add dev vcan42 type vcan

- Remove a (virtual CAN) network interface 'vcan42':
     $ ip link del vcan42
```

<a id="rst-the-can-network-device-driver-interface"></a>

### The CAN Network Device Driver Interface

The CAN network device driver interface provides a generic interface to setup, configure and monitor CAN network devices. The user can then configure the CAN device, like setting the bit-timing parameters, via the netlink interface using the program "ip" from the "IPROUTE2" utility suite. The following chapter describes briefly how to use it. Furthermore, the interface uses a common data structure and exports a set of common functions, which all real CAN network device drivers should use. Please have a look to the SJA1000 or MSCAN driver to understand how to use them. The name of the module is can-dev.ko.

<a id="rst-netlink-interface-to-set-get-devices-properties"></a>

#### Netlink interface to set/get devices properties

The CAN device must be configured via netlink interface. The supported netlink message types are defined and briefly described in "include/linux/can/netlink.h". CAN link support for the program "ip" of the IPROUTE2 utility suite is available and it can be used as shown below:

Setting CAN device properties:



```text
$ ip link set can0 type can help
Usage: ip link set DEVICE type can
    [ bitrate BITRATE [ sample-point SAMPLE-POINT] ] |
    [ tq TQ prop-seg PROP_SEG phase-seg1 PHASE-SEG1
      phase-seg2 PHASE-SEG2 [ sjw SJW ] ]

    [ dbitrate BITRATE [ dsample-point SAMPLE-POINT] ] |
    [ dtq TQ dprop-seg PROP_SEG dphase-seg1 PHASE-SEG1
      dphase-seg2 PHASE-SEG2 [ dsjw SJW ] ]

    [ loopback { on | off } ]
    [ listen-only { on | off } ]
    [ triple-sampling { on | off } ]
    [ one-shot { on | off } ]
    [ berr-reporting { on | off } ]
    [ fd { on | off } ]
    [ fd-non-iso { on | off } ]
    [ presume-ack { on | off } ]
    [ cc-len8-dlc { on | off } ]

    [ restart-ms TIME-MS ]
    [ restart ]

    Where: BITRATE       := { 1..1000000 }
           SAMPLE-POINT  := { 0.000..0.999 }
           TQ            := { NUMBER }
           PROP-SEG      := { 1..8 }
           PHASE-SEG1    := { 1..8 }
           PHASE-SEG2    := { 1..8 }
           SJW           := { 1..4 }
           RESTART-MS    := { 0 | NUMBER }
```

Display CAN device details and statistics:



```text
$ ip -details -statistics link show can0
2: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UP qlen 10
  link/can
  can <TRIPLE-SAMPLING> state ERROR-ACTIVE restart-ms 100
  bitrate 125000 sample_point 0.875
  tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
  sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
  clock 8000000
  re-started bus-errors arbit-lost error-warn error-pass bus-off
  41         17457      0          41         42         41
  RX: bytes  packets  errors  dropped overrun mcast
  140859     17608    17457   0       0       0
  TX: bytes  packets  errors  dropped carrier collsns
  861        112      0       41      0       0
```

More info to the above output:

- **"&lt;TRIPLE-SAMPLING&gt;"**

  Shows the list of selected CAN controller modes: LOOPBACK, LISTEN-ONLY, or TRIPLE-SAMPLING.

- **"state ERROR-ACTIVE"**

  The current state of the CAN controller: "ERROR-ACTIVE", "ERROR-WARNING", "ERROR-PASSIVE", "BUS-OFF" or "STOPPED"

- **"restart-ms 100"**

  Automatic restart delay time. If set to a non-zero value, a restart of the CAN controller will be triggered automatically in case of a bus-off condition after the specified delay time in milliseconds. By default it's off.

- **"bitrate 125000 sample-point 0.875"**

  Shows the real bit-rate in bits/sec and the sample-point in the range 0.000..0.999. If the calculation of bit-timing parameters is enabled in the kernel (CONFIG_CAN_CALC_BITTIMING=y), the bit-timing can be defined by setting the "bitrate" argument. Optionally the "sample-point" can be specified. By default it's 0.000 assuming CIA-recommended sample-points.

- **"tq 125 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1"**

  Shows the time quanta in ns, propagation segment, phase buffer segment 1 and 2 and the synchronisation jump width in units of tq. They allow to define the CAN bit-timing in a hardware independent format as proposed by the Bosch CAN 2.0 spec (see chapter 8 of [http://www.semiconductors.bosch.de/pdf/can2spec.pdf](<http://www.semiconductors.bosch.de/pdf/can2spec.pdf>)).

- **"sja1000: tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1 clock 8000000"**

  Shows the bit-timing constants of the CAN controller, here the "sja1000". The minimum and maximum values of the time segment 1 and 2, the synchronisation jump width in units of tq, the bitrate pre-scaler and the CAN system clock frequency in Hz. These constants could be used for user-defined (non-standard) bit-timing calculation algorithms in user-space.

- **"re-started bus-errors arbit-lost error-warn error-pass bus-off"**

  Shows the number of restarts, bus and arbitration lost errors, and the state changes to the error-warning, error-passive and bus-off state. RX overrun errors are listed in the "overrun" field of the standard network statistics.

<a id="rst-setting-the-can-bit-timing"></a>

#### Setting the CAN Bit-Timing

The CAN bit-timing parameters can always be defined in a hardware independent format as proposed in the Bosch CAN 2.0 specification specifying the arguments "tq", "prop_seg", "phase_seg1", "phase_seg2" and "sjw":



```text
$ ip link set canX type can tq 125 prop-seg 6 \
                            phase-seg1 7 phase-seg2 2 sjw 1
```

If the kernel option CONFIG_CAN_CALC_BITTIMING is enabled, CIA recommended CAN bit-timing parameters will be calculated if the bit- rate is specified with the argument "bitrate":



```text
$ ip link set canX type can bitrate 125000
```

Note that this works fine for the most common CAN controllers with standard bit-rates but may *fail* for exotic bit-rates or CAN system clock frequencies. Disabling CONFIG_CAN_CALC_BITTIMING saves some space and allows user-space tools to solely determine and set the bit-timing parameters. The CAN controller specific bit-timing constants can be used for that purpose. They are listed by the following command:



```text
$ ip -details link show can0
...
  sja1000: clock 8000000 tseg1 1..16 tseg2 1..8 sjw 1..4 brp 1..64 brp-inc 1
```

<a id="rst-starting-and-stopping-the-can-network-device"></a>

#### Starting and Stopping the CAN Network Device

A CAN network device is started or stopped as usual with the command "ifconfig canX up/down" or "ip link set canX up/down". Be aware that you *must* define proper bit-timing parameters for real CAN devices before you can start it to avoid error-prone default settings:



```text
$ ip link set canX up type can bitrate 125000
```

A device may enter the "bus-off" state if too many errors occurred on the CAN bus. Then no more messages are received or sent. An automatic bus-off recovery can be enabled by setting the "restart-ms" to a non-zero value, e.g.:



```text
$ ip link set canX type can restart-ms 100
```

Alternatively, the application may realize the "bus-off" condition by monitoring CAN error message frames and do a restart when appropriate with the command:



```text
$ ip link set canX type can restart
```

Note that a restart will also create a CAN error message frame (see also [Network Problem Notifications](<#rst-socketcan-network-problem-notifications>)).

<a id="rst-can-fd-flexible-data-rate-driver-support"></a>
<a id="rst-socketcan-can-fd-driver"></a>

### CAN FD (Flexible Data Rate) Driver Support

CAN FD capable CAN controllers support two different bitrates for the arbitration phase and the payload phase of the CAN FD frame. Therefore a second bit timing has to be specified in order to enable the CAN FD bitrate.

Additionally CAN FD capable CAN controllers support up to 64 bytes of payload. The representation of this length in can_frame.len and canfd_frame.len for userspace applications and inside the Linux network layer is a plain value from 0 .. 64 instead of the Classical CAN length which ranges from 0 to 8. The payload length to the bus-relevant DLC mapping is only performed inside the CAN drivers, preferably with the helper functions can_fd_dlc2len() and can_fd_len2dlc().

The CAN netdevice driver capabilities can be distinguished by the network devices maximum transfer unit (MTU):



```text
MTU = 16 (CAN_MTU)   => sizeof(struct can_frame)   => Classical CAN device
MTU = 72 (CANFD_MTU) => sizeof(struct canfd_frame) => CAN FD capable device
```

The CAN device MTU can be retrieved e.g. with a SIOCGIFMTU ioctl() syscall. N.B. CAN FD capable devices can also handle and send Classical CAN frames.

When configuring CAN FD capable CAN controllers an additional 'data' bitrate has to be set. This bitrate for the data phase of the CAN FD frame has to be at least the bitrate which was configured for the arbitration phase. This second bitrate is specified analogue to the first bitrate but the bitrate setting keywords for the 'data' bitrate start with 'd' e.g. dbitrate, dsample-point, dsjw or dtq and similar settings. When a data bitrate is set within the configuration process the controller option "fd on" can be specified to enable the CAN FD mode in the CAN controller. This controller option also switches the device MTU to 72 (CANFD_MTU).

The first CAN FD specification presented as whitepaper at the International CAN Conference 2012 needed to be improved for data integrity reasons. Therefore two CAN FD implementations have to be distinguished today:

- ISO compliant:     The ISO 11898-1:2015 CAN FD implementation (default)

- non-ISO compliant: The CAN FD implementation following the 2012 whitepaper

Finally there are three types of CAN FD controllers:

1. ISO compliant (fixed)

2. non-ISO compliant (fixed, like the M_CAN IP core v3.0.1 in m_can.c)

3. ISO/non-ISO CAN FD controllers (switchable, like the PEAK PCAN-USB FD)

The current ISO/non-ISO mode is announced by the CAN controller driver via netlink and displayed by the 'ip' tool (controller option FD-NON-ISO). The ISO/non-ISO-mode can be altered by setting 'fd-non-iso \{on\|off\}' for switchable CAN FD controllers only.

Example configuring 500 kbit/s arbitration bitrate and 4 Mbit/s data bitrate:



```text
$ ip link set can0 up type can bitrate 500000 sample-point 0.75 \
                               dbitrate 4000000 dsample-point 0.8 fd on
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UNKNOWN \
         mode DEFAULT group default qlen 10
link/can  promiscuity 0
can <FD> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
      bitrate 500000 sample-point 0.750
      tq 50 prop-seg 14 phase-seg1 15 phase-seg2 10 sjw 1
      pcan_usb_pro_fd: tseg1 1..64 tseg2 1..16 sjw 1..16 brp 1..1024 \
      brp-inc 1
      dbitrate 4000000 dsample-point 0.800
      dtq 12 dprop-seg 7 dphase-seg1 8 dphase-seg2 4 dsjw 1
      pcan_usb_pro_fd: dtseg1 1..16 dtseg2 1..8 dsjw 1..4 dbrp 1..1024 \
      dbrp-inc 1
      clock 80000000
```

Example when 'fd-non-iso on' is added on this switchable CAN FD adapter:



```text
can <FD,FD-NON-ISO> state ERROR-ACTIVE (berr-counter tx 0 rx 0) restart-ms 0
```

<a id="rst-transmitter-delay-compensation"></a>

#### Transmitter Delay Compensation

At high bit rates, the propagation delay from the TX pin to the RX pin of the transceiver might become greater than the actual bit time causing measurement errors: the RX pin would still be measuring the previous bit.

The Transmitter Delay Compensation (thereafter, TDC) resolves this problem by introducing a Secondary Sample Point (SSP) equal to the distance, in minimum time quantum, from the start of the bit time on the TX pin to the actual measurement on the RX pin. The SSP is calculated as the sum of two configurable values: the TDC Value (TDCV) and the TDC offset (TDCO).

TDC, if supported by the device, can be configured together with CAN-FD using the ip tool's "tdc-mode" argument as follow:

- ****omitted****

  When no "tdc-mode" option is provided, the kernel will automatically decide whether TDC should be turned on, in which case it will calculate a default TDCO and use the TDCV as measured by the device. This is the recommended method to use TDC.

- ****"tdc-mode off"****

  TDC is explicitly disabled.

- ****"tdc-mode auto"****

  The user must provide the "tdco" argument. The TDCV will be automatically calculated by the device. This option is only available if the device supports the TDC-AUTO CAN controller mode.

- ****"tdc-mode manual"****

  The user must provide both the "tdco" and "tdcv" arguments. This option is only available if the device supports the TDC-MANUAL CAN controller mode.

Note that some devices may offer an additional parameter: "tdcf" (TDC Filter window). If supported by your device, this can be added as an optional argument to either "tdc-mode auto" or "tdc-mode manual".

Example configuring a 500 kbit/s arbitration bitrate, a 5 Mbit/s data bitrate, a TDCO of 15 minimum time quantum and a TDCV automatically measured by the device:



```text
$ ip link set can0 up type can bitrate 500000 \
                               fd on dbitrate 4000000 \
                               tdc-mode auto tdco 15
$ ip -details link show can0
5: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 72 qdisc pfifo_fast state UP \
         mode DEFAULT group default qlen 10
    link/can  promiscuity 0 allmulti 0 minmtu 72 maxmtu 72
    can <FD,TDC-AUTO> state ERROR-ACTIVE restart-ms 0
      bitrate 500000 sample-point 0.875
      tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 10 brp 1
      ES582.1/ES584.1: tseg1 2..256 tseg2 2..128 sjw 1..128 brp 1..512 \
      brp_inc 1
      dbitrate 4000000 dsample-point 0.750
      dtq 12 dprop-seg 7 dphase-seg1 7 dphase-seg2 5 dsjw 2 dbrp 1
      tdco 15 tdcf 0
      ES582.1/ES584.1: dtseg1 2..32 dtseg2 1..16 dsjw 1..8 dbrp 1..32 \
      dbrp_inc 1
      tdco 0..127 tdcf 0..127
      clock 80000000
```

<a id="rst-supported-can-hardware"></a>

### Supported CAN Hardware

Please check the "Kconfig" file in "drivers/net/can" to get an actual list of the support CAN hardware. On the SocketCAN project website (see [SocketCAN Resources](<#rst-socketcan-resources>)) there might be further drivers available, also for older kernel versions.

<a id="rst-socketcan-resources-1"></a>
<a id="rst-socketcan-resources"></a>

## SocketCAN Resources

The Linux CAN / SocketCAN project resources (project site / mailing list) are referenced in the MAINTAINERS file in the Linux source tree. Search for CAN NETWORK \[LAYERS\|DRIVERS\].

<a id="rst-credits"></a>

## Credits

- Oliver Hartkopp (PF_CAN core, filters, drivers, bcm, SJA1000 driver)

- Urs Thuermann (PF_CAN core, kernel integration, socket interfaces, raw, vcan)

- Jan Kizka (RT-SocketCAN core, Socket-API reconciliation)

- Wolfgang Grandegger (RT-SocketCAN core &amp; drivers, Raw Socket-API reviews, CAN device driver interface, MSCAN driver)

- Robert Schwebel (design reviews, PTXdist integration)

- Marc Kleine-Budde (design reviews, Kernel 2.6 cleanups, drivers)

- Benedikt Spranger (reviews)

- Thomas Gleixner (LKML reviews, coding style, posting hints)

- Andrey Volkov (kernel subtree structure, ioctls, MSCAN driver)

- Matthias Brukner (first SJA1000 CAN netdevice implementation Q2/2003)

- Klaus Hitschler (PEAK driver integration)

- Uwe Koppe (CAN netdevices with PF_PACKET approach)

- Michael Schulze (driver layer loopback requirement, RT CAN drivers review)

- Pavel Pisa (Bit-timing calculation)

- Sascha Hauer (SJA1000 platform driver)

- Sebastian Haas (SJA1000 EMS PCI driver)

- Markus Plessing (SJA1000 EMS PCI driver)

- Per Dalen (SJA1000 Kvaser PCI driver)

- Sam Ravnborg (reviews, coding style, kbuild help)

---

# The UCAN Protocol

_Peios Kernel / Internals / Networking_

> UCAN is the protocol used by the microcontroller-based USB-CAN adapter that is integrated on System-on-Modules from Theobroma Systems and that is also available as a standalone USB stick.

<a id="rst-the-ucan-protocol"></a>

UCAN is the protocol used by the microcontroller-based USB-CAN adapter that is integrated on System-on-Modules from Theobroma Systems and that is also available as a standalone USB stick.

The UCAN protocol has been designed to be hardware-independent. It is modeled closely after how Linux represents CAN devices internally. All multi-byte integers are encoded as Little Endian.

All structures mentioned in this document are defined in `drivers/net/can/usb/ucan.c`.

<a id="rst-usb-endpoints"></a>

## USB Endpoints

UCAN devices use three USB endpoints:

- **CONTROL endpoint**

  The driver sends device management commands on this endpoint

- **IN endpoint**

  The device sends CAN data frames and CAN error frames

- **OUT endpoint**

  The driver sends CAN data frames on the out endpoint

<a id="rst-control-messages"></a>

## CONTROL Messages

UCAN devices are configured using vendor requests on the control pipe.

To support multiple CAN interfaces in a single USB device all configuration commands target the corresponding interface in the USB descriptor.

The driver uses `ucan_ctrl_command_in/out` and `ucan_device_request_in` to deliver commands to the device.

<a id="rst-setup-packet"></a>

### Setup Packet


<table>
<tbody>
<tr>
<td>


`bmRequestType`

</td>
<td>


Direction \| Vendor \| (Interface or Device)

</td>
</tr>
<tr>
<td>


`bRequest`

</td>
<td>


Command Number

</td>
</tr>
<tr>
<td>


`wValue`

</td>
<td>


Subcommand Number (16 Bit) or 0 if not used

</td>
</tr>
<tr>
<td>


`wIndex`

</td>
<td>


USB Interface Index (0 for device commands)

</td>
</tr>
<tr>
<td>


`wLength`

</td>
<td>


- Host to Device - Number of bytes to transmit

- Device to Host - Maximum Number of bytes to receive. If the device send less. Common ZLP semantics are used.

</td>
</tr>
</tbody>
</table>

<a id="rst-error-handling"></a>

### Error Handling

The device indicates failed control commands by stalling the pipe.

<a id="rst-device-commands"></a>

### Device Commands

<a id="rst-ucan-device-get-fw-string"></a>

#### UCAN_DEVICE_GET_FW_STRING

*Dev2Host; optional*

Request the device firmware string.

<a id="rst-interface-commands"></a>

### Interface Commands

<a id="rst-ucan-command-start"></a>

#### UCAN_COMMAND_START

*Host2Dev; mandatory*

Bring the CAN interface up.

- **Payload Format**

  `ucan_ctl_payload_t.cmd_start`


<table>
<tbody>
<tr>
<td>


mode

</td>
<td>


or mask of `UCAN_MODE_*`

</td>
</tr>
</tbody>
</table>

<a id="rst-ucan-command-stop"></a>

#### UCAN_COMMAND_STOP

*Host2Dev; mandatory*

Stop the CAN interface

- **Payload Format**

  *empty*

<a id="rst-ucan-command-reset"></a>

#### UCAN_COMMAND_RESET

*Host2Dev; mandatory*

Reset the CAN controller (including error counters)

- **Payload Format**

  *empty*

<a id="rst-ucan-command-get"></a>

#### UCAN_COMMAND_GET

*Host2Dev; mandatory*

Get Information from the Device

<a id="rst-subcommands"></a>

##### Subcommands

- **UCAN_COMMAND_GET_INFO**

  Request the device information structure `ucan_ctl_payload_t.device_info`.

  See the `device_info` field for details, and `uapi/linux/can/netlink.h` for an explanation of the `can_bittiming fields`.

  - **Payload Format**

    `ucan_ctl_payload_t.device_info`

UCAN_COMMAND_GET_PROTOCOL_VERSION

> Request the device protocol version `ucan_ctl_payload_t.protocol_version`. The current protocol version is 3.
>
> - **Payload Format**
>
>   `ucan_ctl_payload_t.protocol_version`

> [!NOTE]
>
> Devices that do not implement this command use the old protocol version 1

<a id="rst-ucan-command-set-bittiming"></a>

#### UCAN_COMMAND_SET_BITTIMING

*Host2Dev; mandatory*

Setup bittiming by sending the structure `ucan_ctl_payload_t.cmd_set_bittiming` (see `struct bittiming` for details)

- **Payload Format**

  `ucan_ctl_payload_t.cmd_set_bittiming`.

<a id="rst-ucan-sleep-wake"></a>

#### UCAN_SLEEP/WAKE

*Host2Dev; optional*

Configure sleep and wake modes. Not yet supported by the driver.

<a id="rst-ucan-filter"></a>

#### UCAN_FILTER

*Host2Dev; optional*

Setup hardware CAN filters. Not yet supported by the driver.

<a id="rst-allowed-interface-commands"></a>

### Allowed interface commands


<table>
<thead>
<tr>
<th>


Legal Device State

</th>
<th>


Command

</th>
<th>


New Device State

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


stopped

</td>
<td>


SET_BITTIMING

</td>
<td>


stopped

</td>
</tr>
<tr>
<td>


stopped

</td>
<td>


START

</td>
<td>


started

</td>
</tr>
<tr>
<td>


started

</td>
<td>


STOP or RESET

</td>
<td>


stopped

</td>
</tr>
<tr>
<td>


stopped

</td>
<td>


STOP or RESET

</td>
<td>


stopped

</td>
</tr>
<tr>
<td>


started

</td>
<td>


RESTART

</td>
<td>


started

</td>
</tr>
<tr>
<td>


any

</td>
<td>


GET

</td>
<td>


*no change*

</td>
</tr>
</tbody>
</table>

<a id="rst-in-message-format"></a>

## IN Message Format

A data packet on the USB IN endpoint contains one or more `ucan_message_in` values. If multiple messages are batched in a USB data packet, the `len` field can be used to jump to the next `ucan_message_in` value (take care to sanity-check the `len` value against the actual data size).

<a id="rst-len-field"></a>
<a id="rst-can-ucan-in-message-len"></a>

### `len` field

Each `ucan_message_in` must be aligned to a 4-byte boundary (relative to the start of the start of the data buffer). That means that there may be padding bytes between multiple `ucan_message_in` values:



```text
+----------------------------+ < 0
|                            |
|   struct ucan_message_in   |
|                            |
+----------------------------+ < len
          [padding]
+----------------------------+ < round_up(len, 4)
|                            |
|   struct ucan_message_in   |
|                            |
+----------------------------+
            [...]
```

<a id="rst-type-field"></a>

### `type` field

The `type` field specifies the type of the message.

<a id="rst-ucan-in-rx"></a>

#### UCAN_IN_RX

- **`subtype`**

  zero

Data received from the CAN bus (ID + payload).

<a id="rst-ucan-in-tx-complete"></a>

#### UCAN_IN_TX_COMPLETE

- **`subtype`**

  zero

The CAN device has sent a message to the CAN bus. It answers with a list of tuples &lt;echo-ids, flags&gt;.

The echo-id identifies the frame from (echos the id from a previous UCAN_OUT_TX message). The flag indicates the result of the transmission. Whereas a set Bit 0 indicates success. All other bits are reserved and set to zero.

<a id="rst-flow-control"></a>

### Flow Control

When receiving CAN messages there is no flow control on the USB buffer. The driver has to handle inbound message quickly enough to avoid drops. I case the device buffer overflow the condition is reported by sending corresponding error frames (see [CAN Error Handling](<#rst-can-ucan-error-handling>))

<a id="rst-out-message-format"></a>

## OUT Message Format

A data packet on the USB OUT endpoint contains one or more `struct ucan_message_out` values. If multiple messages are batched into one data packet, the device uses the `len` field to jump to the next ucan_message_out value. Each ucan_message_out must be aligned to 4 bytes (relative to the start of the data buffer). The mechanism is same as described in [len field](<#rst-can-ucan-in-message-len>).



```text
+----------------------------+ < 0
|                            |
|   struct ucan_message_out  |
|                            |
+----------------------------+ < len
          [padding]
+----------------------------+ < round_up(len, 4)
|                            |
|   struct ucan_message_out  |
|                            |
+----------------------------+
            [...]
```

<a id="rst-type-field-1"></a>

### `type` field

In protocol version 3 only `UCAN_OUT_TX` is defined, others are used only by legacy devices (protocol version 1).

<a id="rst-ucan-out-tx"></a>

#### UCAN_OUT_TX

- **`subtype`**

  echo id to be replied within a CAN_IN_TX_COMPLETE message

Transmit a CAN frame. (parameters: `id`, `data`)

<a id="rst-flow-control-1"></a>

### Flow Control

When the device outbound buffers are full it starts sending *NAKs* on the *OUT* pipe until more buffers are available. The driver stops the queue when a certain threshold of out packets are incomplete.

<a id="rst-can-error-handling"></a>
<a id="rst-can-ucan-error-handling"></a>

## CAN Error Handling

If error reporting is turned on the device encodes errors into CAN error frames (see `uapi/linux/can/error.h`) and sends it using the IN endpoint. The driver updates its error statistics and forwards it.

Although UCAN devices can suppress error frames completely, in Linux the driver is always interested. Hence, the device is always started with the `UCAN_MODE_BERR_REPORT` set. Filtering those messages for the user space is done by the driver.

<a id="rst-bus-off"></a>

### Bus OFF

- The device does not recover from bus of automatically.

- Bus OFF is indicated by an error frame (see `uapi/linux/can/error.h`)

- Bus OFF recovery is started by `UCAN_COMMAND_RESTART`

- Once Bus OFF recover is completed the device sends an error frame indicating that it is on ERROR-ACTIVE state.

- During Bus OFF no frames are sent by the device.

- During Bus OFF transmission requests from the host are completed immediately with the success bit left unset.

<a id="rst-example-conversation"></a>

## Example Conversation

1. Device is connected to USB

2. Host sends command `UCAN_COMMAND_RESET`, subcmd 0

3. Host sends command `UCAN_COMMAND_GET`, subcmd `UCAN_COMMAND_GET_INFO`

4. Device sends `UCAN_IN_DEVICE_INFO`

5. Host sends command `UCAN_OUT_SET_BITTIMING`

6. Host sends command `UCAN_COMMAND_START`, subcmd 0, mode `UCAN_MODE_BERR_REPORT`

---

# cdc_mbim - Driver for CDC MBIM Mobile Broadband modems

_Peios Kernel / Internals / Networking_

> The cdc_mbim driver supports USB devices conforming to the "Universal Serial Bus Communications Class Subclass Specification for Mobile Broadband Interface Model" [1], which is a further development of "Universal Serial Bus Communications…

<a id="rst-cdc-mbim-driver-for-cdc-mbim-mobile-broadband-modems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The cdc_mbim driver supports USB devices conforming to the "Universal Serial Bus Communications Class Subclass Specification for Mobile Broadband Interface Model" \[1\], which is a further development of "Universal Serial Bus Communications Class Subclass Specifications for Network Control Model Devices" \[2\] optimized for Mobile Broadband devices, aka "3G/LTE modems".

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

The cdc_mbim driver has no parameters of its own.  But the probing behaviour for NCM 1.0 backwards compatible MBIM functions (an "NCM/MBIM function" as defined in section 3.2 of \[1\]) is affected by a cdc_ncm driver parameter:

<a id="rst-prefer-mbim"></a>

### prefer_mbim

**Type:** Boolean

**Valid Range:** N/Y (0-1)

**Default Value:** Y (MBIM is preferred)

This parameter sets the system policy for NCM/MBIM functions.  Such functions will be handled by either the cdc_ncm driver or the cdc_mbim driver depending on the prefer_mbim setting.  Setting prefer_mbim=N makes the cdc_mbim driver ignore these functions and lets the cdc_ncm driver handle them instead.

The parameter is writable, and can be changed at any time. A manual unbind/bind is required to make the change effective for NCM/MBIM functions bound to the "wrong" driver

<a id="rst-basic-usage"></a>

## Basic usage

MBIM functions are inactive when unmanaged. The cdc_mbim driver only provides a userspace interface to the MBIM control channel, and will not participate in the management of the function. This implies that a userspace MBIM management application always is required to enable a MBIM function.

Such userspace applications includes, but are not limited to:

> - mbimcli (included with the libmbim \[3\] library), and
>
> - ModemManager \[4\]

Establishing a MBIM IP session requires at least these actions by the management application:

> - open the control channel
>
> - configure network connection settings
>
> - connect to network
>
> - configure IP interface

<a id="rst-management-application-development"></a>

### Management application development

The driver &lt;-&gt; userspace interfaces are described below.  The MBIM control channel protocol is described in \[1\].

<a id="rst-mbim-control-channel-userspace-abi"></a>

## MBIM control channel userspace ABI

<a id="rst-dev-cdc-wdmx-character-device"></a>

### /dev/cdc-wdmX character device

The driver creates a two-way pipe to the MBIM function control channel using the cdc-wdm driver as a subdriver.  The userspace end of the control channel pipe is a /dev/cdc-wdmX character device.

The cdc_mbim driver does not process or police messages on the control channel.  The channel is fully delegated to the userspace management application.  It is therefore up to this application to ensure that it complies with all the control channel requirements in \[1\].

The cdc-wdmX device is created as a child of the MBIM control interface USB device.  The character device associated with a specific MBIM function can be looked up using sysfs.  For example:



```text
bjorn@nemi:~$ ls /sys/bus/usb/drivers/cdc_mbim/2-4:2.12/usbmisc
cdc-wdm0

bjorn@nemi:~$ grep . /sys/bus/usb/drivers/cdc_mbim/2-4:2.12/usbmisc/cdc-wdm0/dev
180:0
```

<a id="rst-usb-configuration-descriptors"></a>

### USB configuration descriptors

The wMaxControlMessage field of the CDC MBIM functional descriptor limits the maximum control message size. The management application is responsible for negotiating a control message size complying with the requirements in section 9.3.1 of \[1\], taking this descriptor field into consideration.

The userspace application can access the CDC MBIM functional descriptor of a MBIM function using either of the two USB configuration descriptor kernel interfaces described in \[6\] or \[7\].

See also the ioctl documentation below.

<a id="rst-fragmentation"></a>

### Fragmentation

The userspace application is responsible for all control message fragmentation and defragmentaion, as described in section 9.5 of \[1\].

<a id="rst-dev-cdc-wdmx-write"></a>

### /dev/cdc-wdmX write()

The MBIM control messages from the management application *must not* exceed the negotiated control message size.

<a id="rst-dev-cdc-wdmx-read"></a>

### /dev/cdc-wdmX read()

The management application *must* accept control messages of up the negotiated control message size.

<a id="rst-dev-cdc-wdmx-ioctl"></a>

### /dev/cdc-wdmX ioctl()

IOCTL_WDM_MAX_COMMAND: Get Maximum Command Size This ioctl returns the wMaxControlMessage field of the CDC MBIM functional descriptor for MBIM devices.  This is intended as a convenience, eliminating the need to parse the USB descriptors from userspace.



```text
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/usb/cdc-wdm.h>
int main()
{
        __u16 max;
        int fd = open("/dev/cdc-wdm0", O_RDWR);
        if (!ioctl(fd, IOCTL_WDM_MAX_COMMAND, &max))
                printf("wMaxControlMessage is %d\n", max);
}
```

<a id="rst-custom-device-services"></a>

### Custom device services

The MBIM specification allows vendors to freely define additional services.  This is fully supported by the cdc_mbim driver.

Support for new MBIM services, including vendor specified services, is implemented entirely in userspace, like the rest of the MBIM control protocol

New services should be registered in the MBIM Registry \[5\].

<a id="rst-mbim-data-channel-userspace-abi"></a>

## MBIM data channel userspace ABI

<a id="rst-wwany-network-device"></a>

### wwanY network device

The cdc_mbim driver represents the MBIM data channel as a single network device of the "wwan" type. This network device is initially mapped to MBIM IP session 0.

<a id="rst-multiplexed-ip-sessions-ips"></a>

### Multiplexed IP sessions (IPS)

MBIM allows multiplexing up to 256 IP sessions over a single USB data channel.  The cdc_mbim driver models such IP sessions as 802.1q VLAN subdevices of the master wwanY device, mapping MBIM IP session Z to VLAN ID Z for all values of Z greater than 0.

The device maximum Z is given in the MBIM_DEVICE_CAPS_INFO structure described in section 10.5.1 of \[1\].

The userspace management application is responsible for adding new VLAN links prior to establishing MBIM IP sessions where the SessionId is greater than 0. These links can be added by using the normal VLAN kernel interfaces, either ioctl or netlink.

For example, adding a link for a MBIM IP session with SessionId 3:



```text
ip link add link wwan0 name wwan0.3 type vlan id 3
```

The driver will automatically map the "wwan0.3" network device to MBIM IP session 3.

<a id="rst-device-service-streams-dss"></a>

### Device Service Streams (DSS)

MBIM also allows up to 256 non-IP data streams to be multiplexed over the same shared USB data channel.  The cdc_mbim driver models these sessions as another set of 802.1q VLAN subdevices of the master wwanY device, mapping MBIM DSS session A to VLAN ID (256 + A) for all values of A.

The device maximum A is given in the MBIM_DEVICE_SERVICES_INFO structure described in section 10.5.29 of \[1\].

The DSS VLAN subdevices are used as a practical interface between the shared MBIM data channel and a MBIM DSS aware userspace application. It is not intended to be presented as-is to an end user. The assumption is that a userspace application initiating a DSS session also takes care of the necessary framing of the DSS data, presenting the stream to the end user in an appropriate way for the stream type.

The network device ABI requires a dummy ethernet header for every DSS data frame being transported.  The contents of this header is arbitrary, with the following exceptions:

> - TX frames using an IP protocol (0x0800 or 0x86dd) will be dropped
>
> - RX frames will have the protocol field set to ETH_P_802_3 (but will not be properly formatted 802.3 frames)
>
> - RX frames will have the destination address set to the hardware address of the master device

The DSS supporting userspace management application is responsible for adding the dummy ethernet header on TX and stripping it on RX.

This is a simple example using tools commonly available, exporting DssSessionId 5 as a pty character device pointed to by a /dev/nmea symlink:



```text
ip link add link wwan0 name wwan0.dss5 type vlan id 261
ip link set dev wwan0.dss5 up
socat INTERFACE:wwan0.dss5,type=2 PTY:,echo=0,link=/dev/nmea
```

This is only an example, most suitable for testing out a DSS service. Userspace applications supporting specific MBIM DSS services are expected to use the tools and programming interfaces required by that service.

Note that adding VLAN links for DSS sessions is entirely optional.  A management application may instead choose to bind a packet socket directly to the master network device, using the received VLAN tags to map frames to the correct DSS session and adding 18 byte VLAN ethernet headers with the appropriate tag on TX.  In this case using a socket filter is recommended, matching only the DSS VLAN subset. This avoid unnecessary copying of unrelated IP session data to userspace.  For example:



```text
static struct sock_filter dssfilter[] = {
      /* use special negative offsets to get VLAN tag */
      BPF_STMT(BPF_LD|BPF_B|BPF_ABS, SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT),
      BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 1, 0, 6), /* true */

      /* verify DSS VLAN range */
      BPF_STMT(BPF_LD|BPF_H|BPF_ABS, SKF_AD_OFF + SKF_AD_VLAN_TAG),
      BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, 256, 0, 4),     /* 256 is first DSS VLAN */
      BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, 512, 3, 0),     /* 511 is last DSS VLAN */

      /* verify ethertype */
      BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 2 * ETH_ALEN),
      BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, ETH_P_802_3, 0, 1),

      BPF_STMT(BPF_RET|BPF_K, (u_int)-1),     /* accept */
      BPF_STMT(BPF_RET|BPF_K, 0),             /* ignore */
};
```

<a id="rst-tagged-ip-session-0-vlan"></a>

### Tagged IP session 0 VLAN

As described above, MBIM IP session 0 is treated as special by the driver.  It is initially mapped to untagged frames on the wwanY network device.

This mapping implies a few restrictions on multiplexed IPS and DSS sessions, which may not always be practical:

> - no IPS or DSS session can use a frame size greater than the MTU on IP session 0
>
> - no IPS or DSS session can be in the up state unless the network device representing IP session 0 also is up

These problems can be avoided by optionally making the driver map IP session 0 to a VLAN subdevice, similar to all other IP sessions.  This behaviour is triggered by adding a VLAN link for the magic VLAN ID 4094.  The driver will then immediately start mapping MBIM IP session 0 to this VLAN, and will drop untagged frames on the master wwanY device.

Tip: It might be less confusing to the end user to name this VLAN subdevice after the MBIM SessionID instead of the VLAN ID.  For example:



```text
ip link add link wwan0 name wwan0.0 type vlan id 4094
```

<a id="rst-vlan-mapping"></a>

### VLAN mapping

Summarizing the cdc_mbim driver mapping described above, we have this relationship between VLAN tags on the wwanY network device and MBIM sessions on the shared USB data channel:



```text
VLAN ID       MBIM type   MBIM SessionID           Notes
---------------------------------------------------------
untagged      IPS         0                        a)
1 - 255       IPS         1 - 255 <VLANID>
256 - 511     DSS         0 - 255 <VLANID - 256>
512 - 4093                                         b)
4094          IPS         0                        c)

  a) if no VLAN ID 4094 link exists, else dropped
  b) unsupported VLAN range, unconditionally dropped
  c) if a VLAN ID 4094 link exists, else dropped
```

<a id="rst-references"></a>

## References

> 1. USB Implementers Forum, Inc. - "Universal Serial Bus Communications Class Subclass Specification for Mobile Broadband Interface Model", Revision 1.0 (Errata 1), May 1, 2013
>
>    > - [http://www.usb.org/developers/docs/devclass_docs/](<http://www.usb.org/developers/docs/devclass_docs/>)
>
> 2. USB Implementers Forum, Inc. - "Universal Serial Bus Communications Class Subclass Specifications for Network Control Model Devices", Revision 1.0 (Errata 1), November 24, 2010
>
>    > - [http://www.usb.org/developers/docs/devclass_docs/](<http://www.usb.org/developers/docs/devclass_docs/>)
>
> 3. libmbim - "a glib-based library for talking to WWAN modems and devices which speak the Mobile Interface Broadband Model (MBIM) protocol"
>
>    > - [http://www.freedesktop.org/wiki/Software/libmbim/](<http://www.freedesktop.org/wiki/Software/libmbim/>)
>
> 4. ModemManager - "a DBus-activated daemon which controls mobile broadband (2G/3G/4G) devices and connections"
>
>    > - [http://www.freedesktop.org/wiki/Software/ModemManager/](<http://www.freedesktop.org/wiki/Software/ModemManager/>)
>
> 5. "MBIM (Mobile Broadband Interface Model) Registry"
>
>    > - [http://compliance.usb.org/mbim/](<http://compliance.usb.org/mbim/>)
>
> 6. "/sys/kernel/debug/usb/devices output format"
>
>    > - [Documentation/driver-api/usb/usb.rst](/kernel/hardware/driver-api/usb/usb.md)
>
> 7. "/sys/bus/usb/devices/.../descriptors"
>
>    > - Documentation/ABI/stable/sysfs-bus-usb

---

# Checksum Offloads

_Peios Kernel / Internals / Networking_

> This document describes a set of techniques in the Linux networking stack to take advantage of checksum offload capabilities of various NICs.

<a id="rst-checksum-offloads"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This document describes a set of techniques in the Linux networking stack to take advantage of checksum offload capabilities of various NICs.

The following technologies are described:

- TX Checksum Offload

- LCO: Local Checksum Offload

- RCO: Remote Checksum Offload

Things that should be documented here but aren't yet:

- RX Checksum Offload

- CHECKSUM_UNNECESSARY conversion

<a id="rst-tx-checksum-offload"></a>

## TX Checksum Offload

The interface for offloading a transmit checksum to a device is explained in detail in comments near the top of include/linux/skbuff.h.

In brief, it allows to request the device fill in a single ones-complement checksum defined by the sk_buff fields skb-&gt;csum_start and skb-&gt;csum_offset. The device should compute the 16-bit ones-complement checksum (i.e. the 'IP-style' checksum) from csum_start to the end of the packet, and fill in the result at (csum_start + csum_offset).

Because csum_offset cannot be negative, this ensures that the previous value of the checksum field is included in the checksum computation, thus it can be used to supply any needed corrections to the checksum (such as the sum of the pseudo-header for UDP or TCP).

This interface only allows a single checksum to be offloaded.  Where encapsulation is used, the packet may have multiple checksum fields in different header layers, and the rest will have to be handled by another mechanism such as LCO or RCO.

CRC32c can also be offloaded using this interface, by means of filling skb-&gt;csum_start and skb-&gt;csum_offset as described above, and setting skb-&gt;csum_not_inet: see skbuff.h comment (section 'D') for more details.

No offloading of the IP header checksum is performed; it is always done in software.  This is OK because when we build the IP header, we obviously have it in cache, so summing it isn't expensive.  It's also rather short.

The requirements for GSO are more complicated, because when segmenting an encapsulated packet both the inner and outer checksums may need to be edited or recomputed for each resulting segment.  See the skbuff.h comment (section 'E') for more details.

A driver declares its offload capabilities in netdev-&gt;hw_features; see [Documentation/networking/netdev-features.rst](/kernel/internals/networking/netdev-features.md) for more.  Note that a device which only advertises NETIF_F_IP\[V6\]\_CSUM must still obey the csum_start and csum_offset given in the SKB; if it tries to deduce these itself in hardware (as some NICs do) the driver should check that the values in the SKB match those which the hardware will deduce, and if not, fall back to checksumming in software instead (with skb_csum_hwoffload_help() or one of the skb_checksum_help() / skb_crc32c_csum_help functions, as mentioned in include/linux/skbuff.h).

The stack should, for the most part, assume that checksum offload is supported by the underlying device.  The only place that should check is validate_xmit_skb(), and the functions it calls directly or indirectly.  That function compares the offload features requested by the SKB (which may include other offloads besides TX Checksum Offload) and, if they are not supported or enabled on the device (determined by netdev-&gt;features), performs the corresponding offload in software.  In the case of TX Checksum Offload, that means calling skb_csum_hwoffload_help(skb, features).

<a id="rst-lco-local-checksum-offload"></a>

## LCO: Local Checksum Offload

LCO is a technique for efficiently computing the outer checksum of an encapsulated datagram when the inner checksum is due to be offloaded.

The ones-complement sum of a correctly checksummed TCP or UDP packet is equal to the complement of the sum of the pseudo header, because everything else gets 'cancelled out' by the checksum field.  This is because the sum was complemented before being written to the checksum field.

More generally, this holds in any case where the 'IP-style' ones complement checksum is used, and thus any checksum that TX Checksum Offload supports.

That is, if we have set up TX Checksum Offload with a start/offset pair, we know that after the device has filled in that checksum, the ones complement sum from csum_start to the end of the packet will be equal to the complement of whatever value we put in the checksum field beforehand.  This allows us to compute the outer checksum without looking at the payload: we simply stop summing when we get to csum_start, then add the complement of the 16-bit word at (csum_start + csum_offset).

Then, when the true inner checksum is filled in (either by hardware or by skb_checksum_help()), the outer checksum will become correct by virtue of the arithmetic.

LCO is performed by the stack when constructing an outer UDP header for an encapsulation such as VXLAN or GENEVE, in udp_set_csum().  Similarly for the IPv6 equivalents, in udp6_set_csum().

It is also performed when constructing an IPv4 GRE header, in net/ipv4/ip_gre.c:build_header().  It is *not* currently performed when constructing an IPv6 GRE header; the GRE checksum is computed over the whole packet in net/ipv6/ip6_gre.c:ip6gre_xmit2(), but it should be possible to use LCO here as IPv6 GRE still uses an IP-style checksum.

All of the LCO implementations use a helper function lco_csum(), in include/linux/skbuff.h.

LCO can safely be used for nested encapsulations; in this case, the outer encapsulation layer will sum over both its own header and the 'middle' header. This does mean that the 'middle' header will get summed multiple times, but there doesn't seem to be a way to avoid that without incurring bigger costs (e.g. in SKB bloat).

<a id="rst-rco-remote-checksum-offload"></a>

## RCO: Remote Checksum Offload

RCO is a technique for eliding the inner checksum of an encapsulated datagram, allowing the outer checksum to be offloaded.  It does, however, involve a change to the encapsulation protocols, which the receiver must also support. For this reason, it is disabled by default.

RCO is detailed in the following Internet-Drafts:

- [https://tools.ietf.org/html/draft-herbert-remotecsumoffload-00](<https://tools.ietf.org/html/draft-herbert-remotecsumoffload-00>)

- [https://tools.ietf.org/html/draft-herbert-vxlan-rco-00](<https://tools.ietf.org/html/draft-herbert-vxlan-rco-00>)

In Linux, RCO is implemented individually in each encapsulation protocol, and most tunnel types have flags controlling its use.  For instance, VXLAN has the flag VXLAN_F_REMCSUM_TX (per struct vxlan_rdst) to indicate that RCO should be used when transmitting to a given remote destination.

---

# DCTCP (DataCenter TCP)

_Peios Kernel / Internals / Networking_

> DCTCP is an enhancement to the TCP congestion control algorithm for data center networks and leverages Explicit Congestion Notification (ECN) in the data center network to provide multi-bit feedback to the end hosts.

<a id="rst-dctcp-datacenter-tcp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

DCTCP is an enhancement to the TCP congestion control algorithm for data center networks and leverages Explicit Congestion Notification (ECN) in the data center network to provide multi-bit feedback to the end hosts.

To enable it on end hosts:



```text
sysctl -w net.ipv4.tcp_congestion_control=dctcp
sysctl -w net.ipv4.tcp_ecn_fallback=0 (optional)
```

All switches in the data center network running DCTCP must support ECN marking and be configured for marking when reaching defined switch buffer thresholds. The default ECN marking threshold heuristic for DCTCP on switches is 20 packets (30KB) at 1Gbps, and 65 packets (\~100KB) at 10Gbps, but might need further careful tweaking.

For more details, see below documents:

Paper:

The algorithm is further described in detail in the following two SIGCOMM/SIGMETRICS papers:

> - **i)** Mohammad Alizadeh, Albert Greenberg, David A. Maltz, Jitendra Padhye, Parveen Patel, Balaji Prabhakar, Sudipta Sengupta, and Murari Sridharan:
>
>   > "Data Center TCP (DCTCP)", Data Center Networks session"
>   >
>   > Proc. ACM SIGCOMM, New Delhi, 2010.
>
>   [http://simula.stanford.edu/\~alizade/Site/DCTCP_files/dctcp-final.pdf](<http://simula.stanford.edu/~alizade/Site/DCTCP_files/dctcp-final.pdf>) [http://www.sigcomm.org/ccr/papers/2010/October/1851275.1851192](<http://www.sigcomm.org/ccr/papers/2010/October/1851275.1851192>)

- **ii)** Mohammad Alizadeh, Adel Javanmard, and Balaji Prabhakar:

  > "Analysis of DCTCP: Stability, Convergence, and Fairness" Proc. ACM SIGMETRICS, San Jose, 2011.

  [http://simula.stanford.edu/\~alizade/Site/DCTCP_files/dctcp_analysis-full.pdf](<http://simula.stanford.edu/~alizade/Site/DCTCP_files/dctcp_analysis-full.pdf>)

IETF informational draft:

> [http://tools.ietf.org/html/draft-bensley-tcpm-dctcp-00](<http://tools.ietf.org/html/draft-bensley-tcpm-dctcp-00>)

DCTCP site:

> [http://simula.stanford.edu/\~alizade/Site/DCTCP.html](<http://simula.stanford.edu/~alizade/Site/DCTCP.html>)

---

# Device Memory TCP

_Peios Kernel / Internals / Networking_

> Device memory TCP (devmem TCP) enables receiving data directly into device memory (dmabuf). The feature is currently implemented for TCP sockets.

<a id="rst-device-memory-tcp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-intro"></a>

## Intro

Device memory TCP (devmem TCP) enables receiving data directly into device memory (dmabuf). The feature is currently implemented for TCP sockets.

<a id="rst-opportunity"></a>

### Opportunity

A large number of data transfers have device memory as the source and/or destination. Accelerators drastically increased the prevalence of such transfers.  Some examples include:

- Distributed training, where ML accelerators, such as GPUs on different hosts, exchange data.

- Distributed raw block storage applications transfer large amounts of data with remote SSDs. Much of this data does not require host processing.

Typically the Device-to-Device data transfers in the network are implemented as the following low-level operations: Device-to-Host copy, Host-to-Host network transfer, and Host-to-Device copy.

The flow involving host copies is suboptimal, especially for bulk data transfers, and can put significant strains on system resources such as host memory bandwidth and PCIe bandwidth.

Devmem TCP optimizes this use case by implementing socket APIs that enable the user to receive incoming network packets directly into device memory.

Packet payloads go directly from the NIC to device memory.

Packet headers go to host memory and are processed by the TCP/IP stack normally. The NIC must support header split to achieve this.

Advantages:

- Alleviate host memory bandwidth pressure, compared to existing network-transfer + device-copy semantics.

- Alleviate PCIe bandwidth pressure, by limiting data transfer to the lowest level of the PCIe tree, compared to the traditional path which sends data through the root complex.

<a id="rst-more-info"></a>

### More Info

> - **slides, video**
>
>   [https://netdevconf.org/0x17/sessions/talk/device-memory-tcp.html](<https://netdevconf.org/0x17/sessions/talk/device-memory-tcp.html>)
>
> - **patchset**
>
>   \[PATCH net-next v24 00/13\] Device Memory TCP [https://lore.kernel.org/netdev/20240831004313.3713467-1-almasrymina@google.com/](<https://lore.kernel.org/netdev/20240831004313.3713467-1-almasrymina@google.com/>)

<a id="rst-rx-interface"></a>

## RX Interface

<a id="rst-example"></a>

### Example

./tools/testing/selftests/drivers/net/hw/ncdevmem:do_server shows an example of setting up the RX path of this API.

<a id="rst-nic-setup"></a>

### NIC Setup

Header split, flow steering, &amp; RSS are required features for devmem TCP.

Header split is used to split incoming packets into a header buffer in host memory, and a payload buffer in device memory.

Flow steering &amp; RSS are used to ensure that only flows targeting devmem land on an RX queue bound to devmem.

Enable header split &amp; flow steering:



```text
# enable header split
ethtool -G eth1 tcp-data-split on


# enable flow steering
ethtool -K eth1 ntuple on
```

Configure RSS to steer all traffic away from the target RX queue (queue 15 in this example):



```text
ethtool --set-rxfh-indir eth1 equal 15
```

The user must bind a dmabuf to any number of RX queues on a given NIC using the netlink API:



```text
/* Bind dmabuf to NIC RX queue 15 */
struct netdev_queue *queues;
queues = malloc(sizeof(*queues) * 1);

queues[0]._present.type = 1;
queues[0]._present.idx = 1;
queues[0].type = NETDEV_RX_QUEUE_TYPE_RX;
queues[0].idx = 15;

*ys = ynl_sock_create(&ynl_netdev_family, &yerr);

req = netdev_bind_rx_req_alloc();
netdev_bind_rx_req_set_ifindex(req, 1 /* ifindex */);
netdev_bind_rx_req_set_dmabuf_fd(req, dmabuf_fd);
__netdev_bind_rx_req_set_queues(req, queues, n_queue_index);

rsp = netdev_bind_rx(*ys, req);

dmabuf_id = rsp->dmabuf_id;
```

The netlink API returns a dmabuf_id: a unique ID that refers to this dmabuf that has been bound.

The user can unbind the dmabuf from the netdevice by closing the netlink socket that established the binding. We do this so that the binding is automatically unbound even if the userspace process crashes.

Note that any reasonably well-behaved dmabuf from any exporter should work with devmem TCP, even if the dmabuf is not actually backed by devmem. An example of this is udmabuf, which wraps user memory (non-devmem) in a dmabuf.

<a id="rst-socket-setup"></a>

### Socket Setup

The socket must be flow steered to the dmabuf bound RX queue:



```text
ethtool -N eth1 flow-type tcp4 ... queue 15
```

<a id="rst-receiving-data"></a>

### Receiving data

The user application must signal to the kernel that it is capable of receiving devmem data by passing the MSG_SOCK_DEVMEM flag to recvmsg:



```text
ret = recvmsg(fd, &msg, MSG_SOCK_DEVMEM);
```

Applications that do not specify the MSG_SOCK_DEVMEM flag will receive an EFAULT on devmem data.

Devmem data is received directly into the dmabuf bound to the NIC in 'NIC Setup', and the kernel signals such to the user via the SCM_DEVMEM\_\* cmsgs:



```text
for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) {
        if (cm->cmsg_level != SOL_SOCKET ||
                (cm->cmsg_type != SCM_DEVMEM_DMABUF &&
                 cm->cmsg_type != SCM_DEVMEM_LINEAR))
                continue;

        dmabuf_cmsg = (struct dmabuf_cmsg *)CMSG_DATA(cm);

        if (cm->cmsg_type == SCM_DEVMEM_DMABUF) {
                /* Frag landed in dmabuf.
                 *
                 * dmabuf_cmsg->dmabuf_id is the dmabuf the
                 * frag landed on.
                 *
                 * dmabuf_cmsg->frag_offset is the offset into
                 * the dmabuf where the frag starts.
                 *
                 * dmabuf_cmsg->frag_size is the size of the
                 * frag.
                 *
                 * dmabuf_cmsg->frag_token is a token used to
                 * refer to this frag for later freeing.
                 */

                struct dmabuf_token token;
                token.token_start = dmabuf_cmsg->frag_token;
                token.token_count = 1;
                continue;
        }

        if (cm->cmsg_type == SCM_DEVMEM_LINEAR)
                /* Frag landed in linear buffer.
                 *
                 * dmabuf_cmsg->frag_size is the size of the
                 * frag.
                 */
                continue;

}
```

Applications may receive 2 cmsgs:

- SCM_DEVMEM_DMABUF: this indicates the fragment landed in the dmabuf indicated by dmabuf_id.

- SCM_DEVMEM_LINEAR: this indicates the fragment landed in the linear buffer. This typically happens when the NIC is unable to split the packet at the header boundary, such that part (or all) of the payload landed in host memory.

Applications may receive no SO_DEVMEM\_\* cmsgs. That indicates non-devmem, regular TCP data that landed on an RX queue not bound to a dmabuf.

<a id="rst-freeing-frags"></a>

### Freeing frags

Frags received via SCM_DEVMEM_DMABUF are pinned by the kernel while the user processes the frag. The user must return the frag to the kernel via SO_DEVMEM_DONTNEED:



```text
ret = setsockopt(client_fd, SOL_SOCKET, SO_DEVMEM_DONTNEED, &token,
                 sizeof(token));
```

The user must ensure the tokens are returned to the kernel in a timely manner. Failure to do so will exhaust the limited dmabuf that is bound to the RX queue and will lead to packet drops.

The user must pass no more than 128 tokens, with no more than 1024 total frags among the token-&gt;token_count across all the tokens. If the user provides more than 1024 frags, the kernel will free up to 1024 frags and return early.

The kernel returns the number of actual frags freed. The number of frags freed can be less than the tokens provided by the user in case of:

- **(a)** an internal kernel leak bug.

- **(b)** the user passed more than 1024 frags.

<a id="rst-tx-interface"></a>

## TX Interface

<a id="rst-example-1"></a>

### Example

./tools/testing/selftests/drivers/net/hw/ncdevmem:do_client shows an example of setting up the TX path of this API.

<a id="rst-nic-setup-1"></a>

### NIC Setup

The user must bind a TX dmabuf to a given NIC using the netlink API:



```text
struct netdev_bind_tx_req *req = NULL;
struct netdev_bind_tx_rsp *rsp = NULL;
struct ynl_error yerr;

*ys = ynl_sock_create(&ynl_netdev_family, &yerr);

req = netdev_bind_tx_req_alloc();
netdev_bind_tx_req_set_ifindex(req, ifindex);
netdev_bind_tx_req_set_fd(req, dmabuf_fd);

rsp = netdev_bind_tx(*ys, req);

tx_dmabuf_id = rsp->id;
```

The netlink API returns a dmabuf_id: a unique ID that refers to this dmabuf that has been bound.

The user can unbind the dmabuf from the netdevice by closing the netlink socket that established the binding. We do this so that the binding is automatically unbound even if the userspace process crashes.

Note that any reasonably well-behaved dmabuf from any exporter should work with devmem TCP, even if the dmabuf is not actually backed by devmem. An example of this is udmabuf, which wraps user memory (non-devmem) in a dmabuf.

<a id="rst-socket-setup-1"></a>

### Socket Setup

The user application must use MSG_ZEROCOPY flag when sending devmem TCP. Devmem cannot be copied by the kernel, so the semantics of the devmem TX are similar to the semantics of MSG_ZEROCOPY:



```text
setsockopt(socket_fd, SOL_SOCKET, SO_ZEROCOPY, &opt, sizeof(opt));
```

It is also recommended that the user binds the TX socket to the same interface the dma-buf has been bound to via SO_BINDTODEVICE:



```text
setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname) + 1);
```

<a id="rst-sending-data"></a>

### Sending data

Devmem data is sent using the SCM_DEVMEM_DMABUF cmsg.

The user should create a msghdr where,

- iov_base is set to the offset into the dmabuf to start sending from

- iov_len is set to the number of bytes to be sent from the dmabuf

The user passes the dma-buf id to send from via the dmabuf_tx_cmsg.dmabuf_id.

The example below sends 1024 bytes from offset 100 into the dmabuf, and 2048 from offset 2000 into the dmabuf. The dmabuf to send from is tx_dmabuf_id:



```text
char ctrl_data[CMSG_SPACE(sizeof(struct dmabuf_tx_cmsg))];
struct dmabuf_tx_cmsg ddmabuf;
struct msghdr msg = {};
struct cmsghdr *cmsg;
struct iovec iov[2];

iov[0].iov_base = (void*)100;
iov[0].iov_len = 1024;
iov[1].iov_base = (void*)2000;
iov[1].iov_len = 2048;

msg.msg_iov = iov;
msg.msg_iovlen = 2;

msg.msg_control = ctrl_data;
msg.msg_controllen = sizeof(ctrl_data);

cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_DEVMEM_DMABUF;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct dmabuf_tx_cmsg));

ddmabuf.dmabuf_id = tx_dmabuf_id;

*((struct dmabuf_tx_cmsg *)CMSG_DATA(cmsg)) = ddmabuf;

sendmsg(socket_fd, &msg, MSG_ZEROCOPY);
```

<a id="rst-reusing-tx-dmabufs"></a>

### Reusing TX dmabufs

Similar to MSG_ZEROCOPY with regular memory, the user should not modify the contents of the dma-buf while a send operation is in progress. This is because the kernel does not keep a copy of the dmabuf contents. Instead, the kernel will pin and send data from the buffer available to the userspace.

Just as in MSG_ZEROCOPY, the kernel notifies the userspace of send completions using MSG_ERRQUEUE:



```text
int64_t tstop = gettimeofday_ms() + waittime_ms;
char control[CMSG_SPACE(100)] = {};
struct sock_extended_err *serr;
struct msghdr msg = {};
struct cmsghdr *cm;
int retries = 10;
__u32 hi, lo;

msg.msg_control = control;
msg.msg_controllen = sizeof(control);

while (gettimeofday_ms() < tstop) {
        if (!do_poll(fd)) continue;

        ret = recvmsg(fd, &msg, MSG_ERRQUEUE);

        for (cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) {
                serr = (void *)CMSG_DATA(cm);

                hi = serr->ee_data;
                lo = serr->ee_info;

                fprintf(stdout, "tx complete [%d,%d]\n", lo, hi);
        }
}
```

After the associated sendmsg has been completed, the dmabuf can be reused by the userspace.

<a id="rst-implementation-caveats"></a>

## Implementation &amp; Caveats

<a id="rst-unreadable-skbs"></a>

### Unreadable skbs

Devmem payloads are inaccessible to the kernel processing the packets. This results in a few quirks for payloads of devmem skbs:

- Loopback is not functional. Loopback relies on copying the payload, which is not possible with devmem skbs.

- Software checksum calculation fails.

- TCP Dump and bpf can't access devmem packet payloads.

<a id="rst-testing"></a>

## Testing

More realistic example code can be found in the kernel source under `tools/testing/selftests/drivers/net/hw/ncdevmem.c`

ncdevmem is a devmem TCP netcat. It works very similarly to netcat, but receives data directly into a udmabuf.

To run ncdevmem, you need to run it on a server on the machine under test, and you need to run netcat on a peer to provide the TX data.

ncdevmem has a validation mode as well that expects a repeating pattern of incoming data and validates it as such. For example, you can launch ncdevmem on the server by:



```text
ncdevmem -s <server IP> -c <client IP> -f <ifname> -l -p 5201 -v 7
```

On client side, use regular netcat to send TX data to ncdevmem process on the server:



```text
yes $(echo -e \\x01\\x02\\x03\\x04\\x05\\x06) | \
        tr \\n \\0 | head -c 5G | nc <server IP> 5201 -p 5201
```

---

# DNS Resolver Module

_Peios Kernel / Internals / Networking_

> The DNS resolver module provides a way for kernel services to make DNS queries by way of requesting a key of key type dns_resolver. These queries are upcalled to userspace through /sbin/request-key.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-dns-resolver-module"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

- Overview.
- Compilation.
- Setting up.
- Usage.
- Mechanism.
- Debugging. -->

<a id="rst-overview"></a>

## Overview

The DNS resolver module provides a way for kernel services to make DNS queries by way of requesting a key of key type dns_resolver.  These queries are upcalled to userspace through /sbin/request-key.

These routines must be supported by userspace tools dns.upcall, cifs.upcall and request-key.  It is under development and does not yet provide the full feature set.  The features it does support include:

> - Implements the dns_resolver key_type to contact userspace.

It does not yet support the following AFS features:

> - DNS query support for AFSDB resource record.

This code is extracted from the CIFS filesystem.

<a id="rst-compilation"></a>

## Compilation

The module should be enabled by turning on the kernel configuration options:



```text
CONFIG_DNS_RESOLVER     - tristate "DNS Resolver support"
```

<a id="rst-setting-up"></a>

## Setting up

To set up this facility, the /etc/request-key.conf file must be altered so that /sbin/request-key can appropriately direct the upcalls.  For example, to handle basic dname to IPv4/IPv6 address resolution, the following line should be added:



```text
#OP     TYPE            DESC    CO-INFO PROGRAM ARG1 ARG2 ARG3 ...
#====== ============    ======= ======= ==========================
create  dns_resolver    *       *       /usr/sbin/cifs.upcall %k
```

To direct a query for query type 'foo', a line of the following should be added before the more general line given above as the first match is the one taken:



```text
create  dns_resolver    foo:*   *       /usr/sbin/dns.foo %k
```

<a id="rst-usage"></a>

## Usage

To make use of this facility, first `dns_resolver.h` must be included:



```text
#include <linux/dns_resolver.h>
```

Then queries may be made by calling:



```text
int dns_query(const char *type, const char *name, size_t namelen,
             const char *options, char **_result, time_t *_expiry);
```

This is the basic access function.  It looks for a cached DNS query and if it doesn't find it, it upcalls to userspace to make a new DNS query, which may then be cached.  The key description is constructed as a string of the form:



```text
[<type>:]<name>
```

where &lt;type&gt; optionally specifies the particular upcall program to invoke, and thus the type of query, and &lt;name&gt; specifies the string to be looked up. The default query type is a straight hostname to IP address set lookup.

The name parameter is not required to be a NUL-terminated string, and its length should be given by the namelen argument.

The options parameter may be NULL or it may be a set of options appropriate to the query type.

The return value is a string appropriate to the query type.  For instance, for the default query type it is just a list of comma-separated IPv4 and IPv6 addresses.  The caller must free the result.

The length of the result string is returned on success, and a negative error code is returned otherwise.  -EKEYREJECTED will be returned if the DNS lookup failed.

If \_expiry is non-NULL, the expiry time (TTL) of the result will be returned also.

The kernel maintains an internal keyring in which it caches looked up keys. This can be cleared by any process that has the CAP_SYS_ADMIN capability by the use of KEYCTL_KEYRING_CLEAR on the keyring ID.

<a id="rst-reading-dns-keys-from-userspace"></a>

## Reading DNS Keys from Userspace

Keys of dns_resolver type can be read from userspace using keyctl_read() or "keyctl read/print/pipe".

<a id="rst-mechanism"></a>

## Mechanism

The dns_resolver module registers a key type called "dns_resolver".  Keys of this type are used to transport and cache DNS lookup results from userspace.

When dns_query() is invoked, it calls request_key() to search the local keyrings for a cached DNS result.  If that fails to find one, it upcalls to userspace to get a new result.

Upcalls to userspace are made through the request_key() upcall vector, and are directed by means of configuration lines in /etc/request-key.conf that tell /sbin/request-key what program to run to instantiate the key.

The upcall handler program is responsible for querying the DNS, processing the result into a form suitable for passing to the keyctl_instantiate_key() routine.  This then passes the data to dns_resolver_instantiate() which strips off and processes any options included in the data, and then attaches the remainder of the string to the key as its payload.

The upcall handler program should set the expiry time on the key to that of the lowest TTL of all the records it has extracted a result from.  This means that the key will be discarded and recreated when the data it holds has expired.

dns_query() returns a copy of the value attached to the key, or an error if that is indicated instead.

See [Documentation/security/keys/request-key.rst](/kernel/internals/security/keys/request-key.md) for further information about request-key function.

<a id="rst-debugging"></a>

## Debugging

Debugging messages can be turned on dynamically by writing a 1 into the following file:



```text
/sys/module/dns_resolver/parameters/debug
```

---

# Softnet Driver Issues

_Peios Kernel / Internals / Networking_

> Any hardware layer address you obtain for your device should be verified. For example, for ethernet check it with linux/etherdevice.h:is_valid_ether_addr()

<a id="rst-softnet-driver-issues"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-probing-guidelines"></a>

## Probing guidelines

<a id="rst-address-validation"></a>

### Address validation

Any hardware layer address you obtain for your device should be verified.  For example, for ethernet check it with linux/etherdevice.h:is_valid_ether_addr()

<a id="rst-close-stop-guidelines"></a>

## Close/stop guidelines

<a id="rst-quiescence"></a>

### Quiescence

After the ndo_stop routine has been called, the hardware must not receive or transmit any data.  All in flight packets must be aborted. If necessary, poll or wait for completion of any reset commands.

<a id="rst-auto-close"></a>

### Auto-close

The ndo_stop routine will be called by unregister_netdevice if device is still UP.

<a id="rst-transmit-path-guidelines"></a>

## Transmit path guidelines

<a id="rst-stop-queues-in-advance"></a>

### Stop queues in advance

The ndo_start_xmit method must not return NETDEV_TX_BUSY under any normal circumstances.  It is considered a hard error unless there is no way your device can tell ahead of time when its transmit function will become busy.

Instead it must maintain the queue properly.  For example, for a driver implementing scatter-gather this means:



```c
static u32 drv_tx_avail(struct drv_ring *dr)
{
        u32 used = READ_ONCE(dr->prod) - READ_ONCE(dr->cons);

        return dr->tx_ring_size - (used & bp->tx_ring_mask);
}

static netdev_tx_t drv_hard_start_xmit(struct sk_buff *skb,
                                       struct net_device *dev)
{
        struct drv *dp = netdev_priv(dev);
        struct netdev_queue *txq;
        struct drv_ring *dr;
        int idx;

        idx = skb_get_queue_mapping(skb);
        dr = dp->tx_rings[idx];
        txq = netdev_get_tx_queue(dev, idx);

        //...
        /* This should be a very rare race - log it. */
        if (drv_tx_avail(dr) <= skb_shinfo(skb)->nr_frags + 1) {
                netif_stop_queue(dev);
                netdev_warn(dev, "Tx Ring full when queue awake!\n");
                return NETDEV_TX_BUSY;
        }

        //... queue packet to card ...

        netdev_tx_sent_queue(txq, skb->len);

        //... update tx producer index using WRITE_ONCE() ...

        if (!netif_txq_maybe_stop(txq, drv_tx_avail(dr),
                                  MAX_SKB_FRAGS + 1, 2 * MAX_SKB_FRAGS))
                dr->stats.stopped++;

        //...
        return NETDEV_TX_OK;
}
```

And then at the end of your TX reclamation event handling:



```c
//... update tx consumer index using WRITE_ONCE() ...

netif_txq_completed_wake(txq, cmpl_pkts, cmpl_bytes,
                         drv_tx_avail(dr), 2 * MAX_SKB_FRAGS);
```

<a id="rst-lockless-queue-stop-wake-helper-macros"></a>

#### Lockless queue stop / wake helper macros


The `netif_txq_maybe_stop()` and `__netif_txq_completed_wake()`
macros are designed to safely implement stopping
and waking netdev queues without full lock protection.

We assume that there can be no concurrent stop attempts and no concurrent
wake attempts. The try-stop should happen from the xmit handler,
while wake up should be triggered from NAPI poll context.
The two may run concurrently (single producer, single consumer).

The try-stop side is expected to run from the xmit handler and therefore
it does not reschedule Tx (`netif_tx_start_queue()` instead of
`netif_tx_wake_queue()`). Uses of the `stop` macros outside of the xmit
handler may lead to xmit queue being enabled but not run.
The waking side does not have similar context restrictions.

The macros guarantee that rings will not remain stopped if there's
space available, but they do *not* prevent false wake ups when
the ring is full! Drivers should check for ring full at the start
for the xmit handler.

All descriptor ring indexes (and other relevant shared state) must
be updated before invoking the macros.


<a id="rst-no-exclusive-ownership"></a>

### No exclusive ownership

An ndo_start_xmit method must not modify the shared parts of a cloned SKB.

<a id="rst-timely-completions"></a>

### Timely completions

Do not forget that once you return NETDEV_TX_OK from your ndo_start_xmit method, it is your driver's responsibility to free up the SKB and in some finite amount of time.

For example, this means that it is not allowed for your TX mitigation scheme to let TX packets "hang out" in the TX ring unreclaimed forever if no new TX packets are sent. This error can deadlock sockets waiting for send buffer room to be freed up.

If you return NETDEV_TX_BUSY from the ndo_start_xmit method, you must not keep any reference to that SKB and you must not attempt to free it up.

---

# EQL Driver: Serial IP Load Balancing HOWTO

_Peios Kernel / Internals / Networking_

> Simon "Guru Aleph-Null" Janes, simon@ncm.com

<a id="rst-eql-driver-serial-ip-load-balancing-howto"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Simon "Guru Aleph-Null" Janes, [simon@ncm.com](<mailto:simon@ncm.com>)
>
> v1.1, February 27, 1995
>
> This is the manual for the EQL device driver. EQL is a software device that lets you load-balance IP serial links (SLIP or uncompressed PPP) to increase your bandwidth. It will not reduce your latency (i.e. ping times) except in the case where you already have lots of traffic on your link, in which it will help them out. This driver has been tested with the 1.1.75 kernel, and is known to have patched cleanly with 1.1.86.  Some testing with 1.1.92 has been done with the v1.1 patch which was only created to patch cleanly in the very latest kernel source trees. (Yes, it worked fine.)

<a id="rst-introduction"></a>

## 1. Introduction

> Which is worse? A huge fee for a 56K leased line or two phone lines? It's probably the former.  If you find yourself craving more bandwidth, and have a ISP that is flexible, it is now possible to bind modems together to work as one point-to-point link to increase your bandwidth.  All without having to have a special black box on either side.
>
> The eql driver has only been tested with the Livingston PortMaster-2e terminal server. I do not know if other terminal servers support load- balancing, but I do know that the PortMaster does it, and does it almost as well as the eql driver seems to do it (-- Unfortunately, in my testing so far, the Livingston PortMaster 2e's load-balancing is a good 1 to 2 KB/s slower than the test machine working with a 28.8 Kbps and 14.4 Kbps connection.  However, I am not sure that it really is the PortMaster, or if it's Linux's TCP drivers. I'm told that Linux's TCP implementation is pretty fast though.--)
>
> I suggest to ISPs out there that it would probably be fair to charge a load-balancing client 75% of the cost of the second line and 50% of the cost of the third line etc...
>
> Hey, we can all dream you know...

<a id="rst-kernel-configuration"></a>

## 2. Kernel Configuration

> Here I describe the general steps of getting a kernel up and working with the eql driver.  From patching, building, to installing.

<a id="rst-patching-the-kernel"></a>

### 2.1. Patching The Kernel

> If you do not have or cannot get a copy of the kernel with the eql driver folded into it, get your copy of the driver from [ftp://slaughter.ncm.com/pub/Linux/LOAD_BALANCING/eql-1.1.tar.gz](<ftp://slaughter.ncm.com/pub/Linux/LOAD_BALANCING/eql-1.1.tar.gz>). Unpack this archive someplace obvious like /usr/local/src/.  It will create the following files:
>
>
>
> ```text
> -rw-r--r-- guru/ncm      198 Jan 19 18:53 1995 eql-1.1/NO-WARRANTY
> -rw-r--r-- guru/ncm      30620 Feb 27 21:40 1995 eql-1.1/eql-1.1.patch
> -rwxr-xr-x guru/ncm      16111 Jan 12 22:29 1995 eql-1.1/eql_enslave
> -rw-r--r-- guru/ncm      2195 Jan 10 21:48 1995 eql-1.1/eql_enslave.c
> ```
>
> Unpack a recent kernel (something after 1.1.92) someplace convenient like say /usr/src/linux-1.1.92.eql. Use symbolic links to point /usr/src/linux to this development directory.
>
> Apply the patch by running the commands:
>
>
>
> ```text
> cd /usr/src
> patch </usr/local/src/eql-1.1/eql-1.1.patch
> ```

<a id="rst-building-the-kernel"></a>

### 2.2. Building The Kernel

> After patching the kernel, run make config and configure the kernel for your hardware.
>
> After configuration, make and install according to your habit.

<a id="rst-network-configuration"></a>

## 3. Network Configuration

> So far, I have only used the eql device with the DSLIP SLIP connection manager by Matt Dillon (-- "The man who sold his soul to code so much so quickly."--) .  How you configure it for other "connection" managers is up to you.  Most other connection managers that I've seen don't do a very good job when it comes to handling more than one connection.

<a id="rst-etc-rc-d-rc-inet1"></a>

### 3.1. /etc/rc.d/rc.inet1

> In rc.inet1, ifconfig the eql device to the IP address you usually use for your machine, and the MTU you prefer for your SLIP lines. One could argue that MTU should be roughly half the usual size for two modems, one-third for three, one-fourth for four, etc...  But going too far below 296 is probably overkill. Here is an example ifconfig command that sets up the eql device:
>
>
>
> ```text
> ifconfig eql 198.67.33.239 mtu 1006
> ```
>
> Once the eql device is up and running, add a static default route to it in the routing table using the cool new route syntax that makes life so much easier:
>
>
>
> ```text
> route add default eql
> ```

<a id="rst-enslaving-devices-by-hand"></a>

### 3.2. Enslaving Devices By Hand

> Enslaving devices by hand requires two utility programs: eql_enslave and eql_emancipate (-- eql_emancipate hasn't been written because when an enslaved device "dies", it is automatically taken out of the queue. I haven't found a good reason to write it yet... other than for completeness, but that isn't a good motivator is it?--)
>
> The syntax for enslaving a device is "eql_enslave &lt;master-name&gt; &lt;slave-name&gt; &lt;estimated-bps&gt;".  Here are some example enslavings:
>
>
>
> ```text
> eql_enslave eql sl0 28800
> eql_enslave eql ppp0 14400
> eql_enslave eql sl1 57600
> ```
>
> When you want to free a device from its life of slavery, you can either down the device with ifconfig (eql will automatically bury the dead slave and remove it from its queue) or use eql_emancipate to free it. (-- Or just ifconfig it down, and the eql driver will take it out for you.--):
>
>
>
> ```text
> eql_emancipate eql sl0
> eql_emancipate eql ppp0
> eql_emancipate eql sl1
> ```

<a id="rst-dslip-configuration-for-the-eql-device"></a>

### 3.3. DSLIP Configuration for the eql Device

> The general idea is to bring up and keep up as many SLIP connections as you need, automatically.

<a id="rst-etc-slip-runslip-conf"></a>

#### 3.3.1.  /etc/slip/runslip.conf

> Here is an example runslip.conf:
>
>
>
> ```text
> name          sl-line-1
> enabled
> baud          38400
> mtu           576
> ducmd         -e /etc/slip/dialout/cua2-288.xp -t 9
> command        eql_enslave eql $interface 28800
> address        198.67.33.239
> line          /dev/cua2
>
> name          sl-line-2
> enabled
> baud          38400
> mtu           576
> ducmd         -e /etc/slip/dialout/cua3-288.xp -t 9
> command        eql_enslave eql $interface 28800
> address        198.67.33.239
> line          /dev/cua3
> ```

<a id="rst-using-ppp-and-the-eql-device"></a>

### 3.4. Using PPP and the eql Device

> I have not yet done any load-balancing testing for PPP devices, mainly because I don't have a PPP-connection manager like SLIP has with DSLIP. I did find a good tip from LinuxNET:Billy for PPP performance: make sure you have asyncmap set to something so that control characters are not escaped.
>
> I tried to fix up a PPP script/system for redialing lost PPP connections for use with the eql driver the weekend of Feb 25-26 '95 (Hereafter known as the 8-hour PPP Hate Festival).  Perhaps later this year.

<a id="rst-about-the-slave-scheduler-algorithm"></a>

## 4. About the Slave Scheduler Algorithm

> The slave scheduler probably could be replaced with a dozen other things and push traffic much faster.  The formula in the current set up of the driver was tuned to handle slaves with wildly different bits-per-second "priorities".
>
> All testing I have done was with two 28.8 V.FC modems, one connecting at 28800 bps or slower, and the other connecting at 14400 bps all the time.
>
> One version of the scheduler was able to push 5.3 K/s through the 28800 and 14400 connections, but when the priorities on the links were very wide apart (57600 vs. 14400) the "faster" modem received all traffic and the "slower" modem starved.

<a id="rst-testers-reports"></a>

## 5. Testers' Reports

> Some people have experimented with the eql device with newer kernels (than 1.1.75).  I have since updated the driver to patch cleanly in newer kernels because of the removal of the old "slave- balancing" driver config option.
>
> - icee from LinuxNET patched 1.1.86 without any rejects and was able to boot the kernel and enslave a couple of ISDN PPP links.

<a id="rst-randolph-bentson-s-test-report"></a>

### 5.1. Randolph Bentson's Test Report

>
>
> ```text
> From bentson@grieg.seaslug.org Wed Feb  8 19:08:09 1995
> Date: Tue, 7 Feb 95 22:57 PST
> From: Randolph Bentson <bentson@grieg.seaslug.org>
> To: guru@ncm.com
> Subject: EQL driver tests
>
>
> I have been checking out your eql driver.  (Nice work, that!)
> Although you may already done this performance testing, here
> are some data I've discovered.
>
> Randolph Bentson
> bentson@grieg.seaslug.org
> ```

---

> A pseudo-device driver, EQL, written by Simon Janes, can be used to bundle multiple SLIP connections into what appears to be a single connection.  This allows one to improve dial-up network connectivity gradually, without having to buy expensive DSU/CSU hardware and services.
>
> I have done some testing of this software, with two goals in mind: first, to ensure it actually works as described and second, as a method of exercising my device driver.
>
> The following performance measurements were derived from a set of SLIP connections run between two Linux systems (1.1.84) using a 486DX2/66 with a Cyclom-8Ys and a 486SLC/40 with a Cyclom-16Y. (Ports 0,1,2,3 were used.  A later configuration will distribute port selection across the different Cirrus chips on the boards.) Once a link was established, I timed a binary ftp transfer of 289284 bytes of data. If there were no overhead (packet headers, inter-character and inter-packet delays, etc.) the transfers would take the following times:
>
>
>
> ```text
> bits/sec  seconds
> 345600    8.3
> 234600    12.3
> 172800    16.7
> 153600    18.8
> 76800     37.6
> 57600     50.2
> 38400     75.3
> 28800     100.4
> 19200     150.6
> 9600      301.3
> ```
>
> A single line running at the lower speeds and with large packets comes to within 2% of this.  Performance is limited for the higher speeds (as predicted by the Cirrus databook) to an aggregate of about 160 kbits/sec.  The next round of testing will distribute the load across two or more Cirrus chips.
>
> The good news is that one gets nearly the full advantage of the second, third, and fourth line's bandwidth.  (The bad news is that the connection establishment seemed fragile for the higher speeds.  Once established, the connection seemed robust enough.)
>
>
> <table>
> <thead>
> <tr>
> <th>
>
>
> \#lines
>
> </th>
> <th>
>
>
> speed kbit/sec
>
> </th>
> <th>
>
>
> mtu
>
> </th>
> <th>
>
>
> seconds duration
>
> </th>
> <th>
>
>
> theory speed
>
> </th>
> <th>
>
>
> actual speed
>
> </th>
> <th>
>
>
> %of max
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> \_
>
> </td>
> <td>
>
>
> 345600
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 18.1
>
> </td>
> <td>
>
>
> 345600
>
> </td>
> <td>
>
>
> 159825
>
> </td>
> <td>
>
>
> 46
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> \_
>
> </td>
> <td>
>
>
> 230400
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 18.1
>
> </td>
> <td>
>
>
> 230400
>
> </td>
> <td>
>
>
> 159825
>
> </td>
> <td>
>
>
> 69
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 19.3
>
> </td>
> <td>
>
>
> 230400
>
> </td>
> <td>
>
>
> 149888
>
> </td>
> <td>
>
>
> 65
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> \_
>
> </td>
> <td>
>
>
> 234600
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> \_
>
> </td>
> <td>
>
>
> 234600
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> \_
>
> </td>
> <td>
>
>
> 234600
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 20.9
>
> </td>
> <td>
>
>
> 172800
>
> </td>
> <td>
>
>
> 138413
>
> </td>
> <td>
>
>
> 80
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 21.2
>
> </td>
> <td>
>
>
> 172800
>
> </td>
> <td>
>
>
> 136455
>
> </td>
> <td>
>
>
> 78
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 21.7
>
> </td>
> <td>
>
>
> 345600
>
> </td>
> <td>
>
>
> 133311
>
> </td>
> <td>
>
>
> 38
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 22.5
>
> </td>
> <td>
>
>
> 172800
>
> </td>
> <td>
>
>
> 128571
>
> </td>
> <td>
>
>
> 74
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 25.2
>
> </td>
> <td>
>
>
> 153600
>
> </td>
> <td>
>
>
> 114795
>
> </td>
> <td>
>
>
> 74
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 26.4
>
> </td>
> <td>
>
>
> 153600
>
> </td>
> <td>
>
>
> 109577
>
> </td>
> <td>
>
>
> 71
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 27.3
>
> </td>
> <td>
>
>
> 153600
>
> </td>
> <td>
>
>
> 105965
>
> </td>
> <td>
>
>
> 68
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 29.1
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 99410.3
>
> </td>
> <td>
>
>
> 86
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 30.7
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 94229.3
>
> </td>
> <td>
>
>
> 81
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 30.2
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 95789.4
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 30.3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 95473.3
>
> </td>
> <td>
>
>
> 82
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 31.2
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 92719.2
>
> </td>
> <td>
>
>
> 80
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 31.3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 92423
>
> </td>
> <td>
>
>
> 80
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 32.3
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 89561.6
>
> </td>
> <td>
>
>
> 77
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 32.8
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 88196.3
>
> </td>
> <td>
>
>
> 76
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 33.5
>
> </td>
> <td>
>
>
> 115200
>
> </td>
> <td>
>
>
> 86353.4
>
> </td>
> <td>
>
>
> 74
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 43.7
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 66197.7
>
> </td>
> <td>
>
>
> 86
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 44
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 65746.4
>
> </td>
> <td>
>
>
> 85
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 47.2
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 61289
>
> </td>
> <td>
>
>
> 79
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 50.8
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 56945.7
>
> </td>
> <td>
>
>
> 74
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 53.2
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 54376.7
>
> </td>
> <td>
>
>
> 70
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 53.7
>
> </td>
> <td>
>
>
> 76800
>
> </td>
> <td>
>
>
> 53870.4
>
> </td>
> <td>
>
>
> 70
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 54.6
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 52982.4
>
> </td>
> <td>
>
>
> 91
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 56.2
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 51474
>
> </td>
> <td>
>
>
> 89
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 60.5
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 47815.5
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 60.2
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 48053.8
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 62
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 46658.7
>
> </td>
> <td>
>
>
> 81
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 64.7
>
> </td>
> <td>
>
>
> 57600
>
> </td>
> <td>
>
>
> 44711.6
>
> </td>
> <td>
>
>
> 77
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 79.4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 36433.8
>
> </td>
> <td>
>
>
> 94
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 82.4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 35107.3
>
> </td>
> <td>
>
>
> 91
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 84.4
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 34275.4
>
> </td>
> <td>
>
>
> 89
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 86.8
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 33327.6
>
> </td>
> <td>
>
>
> 86
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 87.6
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 33023.3
>
> </td>
> <td>
>
>
> 85
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 91.2
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 31719.7
>
> </td>
> <td>
>
>
> 82
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 94.7
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 30547.4
>
> </td>
> <td>
>
>
> 79
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 106
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 27290.9
>
> </td>
> <td>
>
>
> 71
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 110
>
> </td>
> <td>
>
>
> 38400
>
> </td>
> <td>
>
>
> 26298.5
>
> </td>
> <td>
>
>
> 68
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 118
>
> </td>
> <td>
>
>
> 28800
>
> </td>
> <td>
>
>
> 24515.6
>
> </td>
> <td>
>
>
> 85
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 120
>
> </td>
> <td>
>
>
> 28800
>
> </td>
> <td>
>
>
> 24107
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 131
>
> </td>
> <td>
>
>
> 28800
>
> </td>
> <td>
>
>
> 22082.7
>
> </td>
> <td>
>
>
> 76
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 155
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 18663.5
>
> </td>
> <td>
>
>
> 97
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 161
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 17968
>
> </td>
> <td>
>
>
> 93
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 170
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 17016.7
>
> </td>
> <td>
>
>
> 88
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 176
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 16436.6
>
> </td>
> <td>
>
>
> 85
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 180
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 16071.3
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 181
>
> </td>
> <td>
>
>
> 19200
>
> </td>
> <td>
>
>
> 15982.5
>
> </td>
> <td>
>
>
> 83
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 900
>
> </td>
> <td>
>
>
> 305
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 9484.72
>
> </td>
> <td>
>
>
> 98
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 600
>
> </td>
> <td>
>
>
> 314
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 9212.87
>
> </td>
> <td>
>
>
> 95
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 400
>
> </td>
> <td>
>
>
> 332
>
> </td>
> <td>
>
>
> 9600
>
> </td>
> <td>
>
>
> 8713.37
>
> </td>
> <td>
>
>
> 90
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-anthony-healy-s-report"></a>

### 5.2. Anthony Healy's Report

>
>
> ```text
> Date: Mon, 13 Feb 1995 16:17:29 +1100 (EST)
> From: Antony Healey <ahealey@st.nepean.uws.edu.au>
> To: Simon Janes <guru@ncm.com>
> Subject: Re: Load Balancing
>
> Hi Simon,
>       I've installed your patch and it works great. I have trialed
>       it over twin SL/IP lines, just over null modems, but I was
>       able to data at over 48Kb/s [ISDN link -Simon]. I managed a
>       transfer of up to 7.5 Kbyte/s on one go, but averaged around
>       6.4 Kbyte/s, which I think is pretty cool.  :)
> ```

---

# Netlink interface for ethtool

_Peios Kernel / Internals / Networking_

> Netlink interface for ethtool uses generic netlink family ethtool (userspace application should use macros ETHTOOL_GENL_NAME and ETHTOOL_GENL_VERSION defined in <linux/ethtool_netlink.h> uapi header). This family does not use a specific…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-netlink-interface-for-ethtool"></a>

<a id="rst-basic-information"></a>

## Basic information

Netlink interface for ethtool uses generic netlink family `ethtool` (userspace application should use macros `ETHTOOL_GENL_NAME` and `ETHTOOL_GENL_VERSION` defined in `<linux/ethtool_netlink.h>` uapi header). This family does not use a specific header, all information in requests and replies is passed using netlink attributes.

The ethtool netlink interface uses extended ACK for error and warning reporting, userspace application developers are encouraged to make these messages available to user in a suitable way.

Requests can be divided into three categories: "get" (retrieving information), "set" (setting parameters) and "action" (invoking an action).

All "set" and "action" type requests require admin privileges (`CAP_NET_ADMIN` in the namespace). Most "get" type requests are allowed for anyone but there are exceptions (where the response contains sensitive information). In some cases, the request as such is allowed for anyone but unprivileged users have attributes with sensitive information (e.g. wake-on-lan password) omitted.

<a id="rst-conventions"></a>

## Conventions

Attributes which represent a boolean value usually use NLA_U8 type so that we can distinguish three states: "on", "off" and "not present" (meaning the information is not available in "get" requests or value is not to be changed in "set" requests). For these attributes, the "true" value should be passed as number 1 but any non-zero value should be understood as "true" by recipient. In the tables below, "bool" denotes NLA_U8 attributes interpreted in this way.

In the message structure descriptions below, if an attribute name is suffixed with "+", parent nest can contain multiple attributes of the same type. This implements an array of entries.

Attributes that need to be filled-in by device drivers and that are dumped to user space based on whether they are valid or not should not use zero as a valid value. This avoids the need to explicitly signal the validity of the attribute in the device driver API.

<a id="rst-request-header"></a>

## Request header

Each request or reply message contains a nested attribute with common header. Structure of this header is

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_HEADER_DEV_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> device ifindex
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_HEADER_DEV_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> device name
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_HEADER_FLAGS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> flags common for all requests
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_HEADER_PHY_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> phy device index
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_HEADER_DEV_INDEX` and `ETHTOOL_A_HEADER_DEV_NAME` identify the device message relates to. One of them is sufficient in requests, if both are used, they must identify the same device. Some requests, e.g. global string sets, do not require device identification. Most `GET` requests also allow dump requests without device identification to query the same information for all devices providing it (each device in a separate message).

`ETHTOOL_A_HEADER_FLAGS` is a bitmap of request flags common for all request types. The interpretation of these flags is the same for all request types but the flags may not apply to requests. Recognized flags are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_FLAG_COMPACT_BITSETS`
>
> </td>
> <td>
>
>
> use compact format bitsets in reply
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_FLAG_OMIT_REPLY`
>
> </td>
> <td>
>
>
> omit optional reply (\_SET and \_ACT)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_FLAG_STATS`
>
> </td>
> <td>
>
>
> include optional device statistics
>
> </td>
> </tr>
> </tbody>
> </table>

New request flags should follow the general idea that if the flag is not set, the behaviour is backward compatible, i.e. requests from old clients not aware of the flag should be interpreted the way the client expects. A client must not set flags it does not understand.

`ETHTOOL_A_HEADER_PHY_INDEX` identifies the Ethernet PHY the message relates to. As there are numerous commands that are related to PHY configuration, and because there may be more than one PHY on the link, the PHY index can be passed in the request for the commands that needs it. It is, however, not mandatory, and if it is not passed for commands that target a PHY, the net_device.phydev pointer is used.

<a id="rst-bit-sets"></a>

## Bit sets

For short bitmaps of (reasonably) fixed length, standard `NLA_BITFIELD32` type is used. For arbitrary length bitmaps, ethtool netlink uses a nested attribute with contents of one of two forms: compact (two binary bitmaps representing bit values and mask of affected bits) and bit-by-bit (list of bits identified by either index or name).

Verbose (bit-by-bit) bitsets allow sending symbolic names for bits together with their values which saves a round trip (when the bitset is passed in a request) or at least a second request (when the bitset is in a reply). This is useful for one shot applications like traditional ethtool command. On the other hand, long running applications like ethtool monitor (displaying notifications) or network management daemons may prefer fetching the names only once and using compact form to save message size. Notifications from ethtool netlink interface always use compact form for bitsets.

A bitset can represent either a value/mask pair (`ETHTOOL_A_BITSET_NOMASK` not set) or a single bitmap (`ETHTOOL_A_BITSET_NOMASK` set). In requests modifying a bitmap, the former changes the bit set in mask to values set in value and preserves the rest; the latter sets the bits set in the bitmap and clears the rest.

Compact form: nested (bitset) attribute contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_BITSET_NOMASK`
>
> </td>
> <td>
>
>
> flag
>
> </td>
> <td>
>
>
> no mask, only a list
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_BITSET_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> number of significant bits
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_BITSET_VALUE`
>
> </td>
> <td>
>
>
> binary
>
> </td>
> <td>
>
>
> bitmap of bit values
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_BITSET_MASK`
>
> </td>
> <td>
>
>
> binary
>
> </td>
> <td>
>
>
> bitmap of valid bits
>
> </td>
> </tr>
> </tbody>
> </table>

Value and mask must have length at least `ETHTOOL_A_BITSET_SIZE` bits rounded up to a multiple of 32 bits. They consist of 32-bit words in host byte order, words ordered from least significant to most significant (i.e. the same way as bitmaps are passed with ioctl interface).

For compact form, `ETHTOOL_A_BITSET_SIZE` and `ETHTOOL_A_BITSET_VALUE` are mandatory. `ETHTOOL_A_BITSET_MASK` attribute is mandatory if `ETHTOOL_A_BITSET_NOMASK` is not set (bitset represents a value/mask pair); if `ETHTOOL_A_BITSET_NOMASK` is not set, `ETHTOOL_A_BITSET_MASK` is not allowed (bitset represents a single bitmap.

Kernel bit set length may differ from userspace length if older application is used on newer kernel or vice versa. If userspace bitmap is longer, an error is issued only if the request actually tries to set values of some bits not recognized by kernel.

Bit-by-bit form: nested (bitset) attribute contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_BITSET_NOMASK`
>
> </td>
> <td>
>
>
> flag
>
> </td>
> <td>
>
>
> no mask, only a list
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_BITSET_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> number of significant bits
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_BITSET_BITS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> array of bits
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_BITSET_BITS_BIT+`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one bit
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_BITSET_BIT_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> bit index (0 for LSB)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_BITSET_BIT_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> bit name
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_BITSET_BIT_VALUE`
>
> </td>
> <td>
>
>
> flag
>
> </td>
> <td>
>
>
> present if bit is set
>
> </td>
> </tr>
> </tbody>
> </table>

Bit size is optional for bit-by-bit form. `ETHTOOL_A_BITSET_BITS` nest can only contain `ETHTOOL_A_BITSET_BITS_BIT` attributes but there can be an arbitrary number of them.  A bit may be identified by its index or by its name. When used in requests, listed bits are set to 0 or 1 according to `ETHTOOL_A_BITSET_BIT_VALUE`, the rest is preserved. A request fails if index exceeds kernel bit length or if name is not recognized.

When `ETHTOOL_A_BITSET_NOMASK` flag is present, bitset is interpreted as a simple bitmap. `ETHTOOL_A_BITSET_BIT_VALUE` attributes are not used in such case. Such bitset represents a bitmap with listed bits set and the rest zero.

In requests, application can use either form. Form used by kernel in reply is determined by `ETHTOOL_FLAG_COMPACT_BITSETS` flag in flags field of request header. Semantics of value and mask depends on the attribute.

<a id="rst-list-of-message-types"></a>

## List of message types

All constants identifying message types use `ETHTOOL_CMD_` prefix and suffix according to message purpose:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `_GET`
>
> </td>
> <td>
>
>
> userspace request to retrieve data
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_SET`
>
> </td>
> <td>
>
>
> userspace request to set data
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_ACT`
>
> </td>
> <td>
>
>
> userspace request to perform an action
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_GET_REPLY`
>
> </td>
> <td>
>
>
> kernel reply to a `GET` request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_SET_REPLY`
>
> </td>
> <td>
>
>
> kernel reply to a `SET` request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_ACT_REPLY`
>
> </td>
> <td>
>
>
> kernel reply to an `ACT` request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `_NTF`
>
> </td>
> <td>
>
>
> kernel notification
>
> </td>
> </tr>
> </tbody>
> </table>

Userspace to kernel:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_STRSET_GET`
>
> </td>
> <td>
>
>
> get string set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_GET`
>
> </td>
> <td>
>
>
> get link settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_SET`
>
> </td>
> <td>
>
>
> set link settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKMODES_GET`
>
> </td>
> <td>
>
>
> get link modes info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKMODES_SET`
>
> </td>
> <td>
>
>
> set link modes info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKSTATE_GET`
>
> </td>
> <td>
>
>
> get link state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_GET`
>
> </td>
> <td>
>
>
> get debugging settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_SET`
>
> </td>
> <td>
>
>
> set debugging settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_WOL_GET`
>
> </td>
> <td>
>
>
> get wake-on-lan settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_WOL_SET`
>
> </td>
> <td>
>
>
> set wake-on-lan settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> <td>
>
>
> get device features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> <td>
>
>
> set device features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_GET`
>
> </td>
> <td>
>
>
> get private flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_SET`
>
> </td>
> <td>
>
>
> set private flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_GET`
>
> </td>
> <td>
>
>
> get ring sizes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_SET`
>
> </td>
> <td>
>
>
> set ring sizes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_GET`
>
> </td>
> <td>
>
>
> get channel counts
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_SET`
>
> </td>
> <td>
>
>
> set channel counts
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_GET`
>
> </td>
> <td>
>
>
> get coalescing parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_SET`
>
> </td>
> <td>
>
>
> set coalescing parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_GET`
>
> </td>
> <td>
>
>
> get pause parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_SET`
>
> </td>
> <td>
>
>
> set pause parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_EEE_GET`
>
> </td>
> <td>
>
>
> get EEE settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_EEE_SET`
>
> </td>
> <td>
>
>
> set EEE settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSINFO_GET`
>
> </td>
> <td>
>
>
> get timestamping info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_ACT`
>
> </td>
> <td>
>
>
> action start cable test
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_TDR_ACT`
>
> </td>
> <td>
>
>
> action start raw TDR cable test
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TUNNEL_INFO_GET`
>
> </td>
> <td>
>
>
> get tunnel offload info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEC_GET`
>
> </td>
> <td>
>
>
> get FEC settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEC_SET`
>
> </td>
> <td>
>
>
> set FEC settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_EEPROM_GET`
>
> </td>
> <td>
>
>
> read SFP module EEPROM
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_STATS_GET`
>
> </td>
> <td>
>
>
> get standard statistics
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PHC_VCLOCKS_GET`
>
> </td>
> <td>
>
>
> get PHC virtual clocks info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_SET`
>
> </td>
> <td>
>
>
> set transceiver module parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_GET`
>
> </td>
> <td>
>
>
> get transceiver module parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PSE_SET`
>
> </td>
> <td>
>
>
> set PSE parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PSE_GET`
>
> </td>
> <td>
>
>
> get PSE parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_GET`
>
> </td>
> <td>
>
>
> get RSS settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_CFG`
>
> </td>
> <td>
>
>
> get PLCA RS parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_SET_CFG`
>
> </td>
> <td>
>
>
> set PLCA RS parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_STATUS`
>
> </td>
> <td>
>
>
> get PLCA RS status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MM_GET`
>
> </td>
> <td>
>
>
> get MAC merge layer state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MM_SET`
>
> </td>
> <td>
>
>
> set MAC merge layer parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_FW_FLASH_ACT`
>
> </td>
> <td>
>
>
> flash transceiver module firmware
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PHY_GET`
>
> </td>
> <td>
>
>
> get Ethernet PHY information
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_GET`
>
> </td>
> <td>
>
>
> get hw timestamping configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_SET`
>
> </td>
> <td>
>
>
> set hw timestamping configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_SET`
>
> </td>
> <td>
>
>
> set RSS settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_CREATE_ACT`
>
> </td>
> <td>
>
>
> create an additional RSS context
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_DELETE_ACT`
>
> </td>
> <td>
>
>
> delete an additional RSS context
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MSE_GET`
>
> </td>
> <td>
>
>
> get MSE diagnostic data
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel to userspace:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_STRSET_GET_REPLY`
>
> </td>
> <td>
>
>
> string set contents
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_GET_REPLY`
>
> </td>
> <td>
>
>
> link settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_NTF`
>
> </td>
> <td>
>
>
> link settings notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKMODES_GET_REPLY`
>
> </td>
> <td>
>
>
> link modes info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKMODES_NTF`
>
> </td>
> <td>
>
>
> link modes notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_LINKSTATE_GET_REPLY`
>
> </td>
> <td>
>
>
> link state info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_GET_REPLY`
>
> </td>
> <td>
>
>
> debugging settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_NTF`
>
> </td>
> <td>
>
>
> debugging settings notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_WOL_GET_REPLY`
>
> </td>
> <td>
>
>
> wake-on-lan settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_WOL_NTF`
>
> </td>
> <td>
>
>
> wake-on-lan settings notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET_REPLY`
>
> </td>
> <td>
>
>
> device features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET_REPLY`
>
> </td>
> <td>
>
>
> optional reply to FEATURES_SET
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_NTF`
>
> </td>
> <td>
>
>
> netdev features notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_GET_REPLY`
>
> </td>
> <td>
>
>
> private flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_NTF`
>
> </td>
> <td>
>
>
> private flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_GET_REPLY`
>
> </td>
> <td>
>
>
> ring sizes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_NTF`
>
> </td>
> <td>
>
>
> ring sizes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_GET_REPLY`
>
> </td>
> <td>
>
>
> channel counts
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_NTF`
>
> </td>
> <td>
>
>
> channel counts
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_GET_REPLY`
>
> </td>
> <td>
>
>
> coalescing parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_NTF`
>
> </td>
> <td>
>
>
> coalescing parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_GET_REPLY`
>
> </td>
> <td>
>
>
> pause parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_NTF`
>
> </td>
> <td>
>
>
> pause parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_EEE_GET_REPLY`
>
> </td>
> <td>
>
>
> EEE settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_EEE_NTF`
>
> </td>
> <td>
>
>
> EEE settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSINFO_GET_REPLY`
>
> </td>
> <td>
>
>
> timestamping info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_NTF`
>
> </td>
> <td>
>
>
> Cable test results
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_TDR_NTF`
>
> </td>
> <td>
>
>
> Cable test TDR results
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TUNNEL_INFO_GET_REPLY`
>
> </td>
> <td>
>
>
> tunnel offload info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEC_GET_REPLY`
>
> </td>
> <td>
>
>
> FEC settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_FEC_NTF`
>
> </td>
> <td>
>
>
> FEC settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_EEPROM_GET_REPLY`
>
> </td>
> <td>
>
>
> read SFP module EEPROM
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_STATS_GET_REPLY`
>
> </td>
> <td>
>
>
> standard statistics
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PHC_VCLOCKS_GET_REPLY`
>
> </td>
> <td>
>
>
> PHC virtual clocks info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_GET_REPLY`
>
> </td>
> <td>
>
>
> transceiver module parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PSE_GET_REPLY`
>
> </td>
> <td>
>
>
> PSE parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_GET_REPLY`
>
> </td>
> <td>
>
>
> RSS settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_NTF`
>
> </td>
> <td>
>
>
> RSS settings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_CFG_REPLY`
>
> </td>
> <td>
>
>
> PLCA RS parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_STATUS_REPLY`
>
> </td>
> <td>
>
>
> PLCA RS status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_NTF`
>
> </td>
> <td>
>
>
> PLCA RS parameters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MM_GET_REPLY`
>
> </td>
> <td>
>
>
> MAC merge layer status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_FW_FLASH_NTF`
>
> </td>
> <td>
>
>
> transceiver module flash updates
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PHY_GET_REPLY`
>
> </td>
> <td>
>
>
> Ethernet PHY information
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PHY_NTF`
>
> </td>
> <td>
>
>
> Ethernet PHY information change
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_GET_REPLY`
>
> </td>
> <td>
>
>
> hw timestamping configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_SET_REPLY`
>
> </td>
> <td>
>
>
> new hw timestamping configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_PSE_NTF`
>
> </td>
> <td>
>
>
> PSE events notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_NTF`
>
> </td>
> <td>
>
>
> RSS settings notification
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_CREATE_ACT_REPLY`
>
> </td>
> <td>
>
>
> create an additional RSS context
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_CREATE_NTF`
>
> </td>
> <td>
>
>
> additional RSS context created
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_RSS_DELETE_NTF`
>
> </td>
> <td>
>
>
> additional RSS context deleted
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_MSG_MSE_GET_REPLY`
>
> </td>
> <td>
>
>
> MSE diagnostic data
>
> </td>
> </tr>
> </tbody>
> </table>

`GET` requests are sent by userspace applications to retrieve device information. They usually do not contain any message specific attributes. Kernel replies with corresponding "GET_REPLY" message. For most types, `GET` request with `NLM_F_DUMP` and no device identification can be used to query the information for all devices supporting the request.

If the data can be also modified, corresponding `SET` message with the same layout as corresponding `GET_REPLY` is used to request changes. Only attributes where a change is requested are included in such request (also, not all attributes may be changed). Replies to most `SET` request consist only of error code and extack; if kernel provides additional data, it is sent in the form of corresponding `SET_REPLY` message which can be suppressed by setting `ETHTOOL_FLAG_OMIT_REPLY` flag in request header.

Data modification also triggers sending a `NTF` message with a notification. These usually bear only a subset of attributes which was affected by the change. The same notification is issued if the data is modified using other means (mostly ioctl ethtool interface). Unlike notifications from ethtool netlink code which are only sent if something actually changed, notifications triggered by ioctl interface may be sent even if the request did not actually change any data.

`ACT` messages request kernel (driver) to perform a specific action. If some information is reported by kernel (which can be suppressed by setting `ETHTOOL_FLAG_OMIT_REPLY` flag in request header), the reply takes form of an `ACT_REPLY` message. Performing an action also triggers a notification (`NTF` message).

Later sections describe the format and semantics of these messages.

<a id="rst-strset-get"></a>

## STRSET_GET

Requests contents of a string set as provided by ioctl commands `ETHTOOL_GSSET_INFO` and `ETHTOOL_GSTRINGS.` String sets are not user writeable so that the corresponding `STRSET_SET` message is only used in kernel replies. There are two types of string sets: global (independent of a device, e.g. device feature names) and device specific (e.g. device private flags).

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_STRSET_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_STRSET_STRINGSETS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> string set to request
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_STRINGSETS_STRINGSET+`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one string set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STRINGSET_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> set id
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="5">
>
>
> `ETHTOOL_A_STRSET_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="5">
>
>
> `ETHTOOL_A_STRSET_STRINGSETS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> array of string sets
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="4">
>
>
> `ETHTOOL_A_STRINGSETS_STRINGSET+`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one string set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="3">
>
>
> `ETHTOOL_A_STRINGSET_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> set id
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="3">
>
>
> `ETHTOOL_A_STRINGSET_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> number of strings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="3">
>
>
> `ETHTOOL_A_STRINGSET_STRINGS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> array of strings
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_STRINGS_STRING+`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one string
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STRING_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> string index
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STRING_VALUE`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> string value
>
> </td>
> </tr>
> <tr>
> <td colspan="5">
>
>
> `ETHTOOL_A_STRSET_COUNTS_ONLY`
>
> </td>
> <td>
>
>
> flag
>
> </td>
> <td>
>
>
> return only counts
>
> </td>
> </tr>
> </tbody>
> </table>

Device identification in request header is optional. Depending on its presence a and `NLM_F_DUMP` flag, there are three type of `STRSET_GET` requests:

> - no `NLM_F_DUMP,` no device: get "global" stringsets
>
> - no `NLM_F_DUMP`, with device: get string sets related to the device
>
> - `NLM_F_DUMP`, no device: get device related string sets for all devices

If there is no `ETHTOOL_A_STRSET_STRINGSETS` array, all string sets of requested type are returned, otherwise only those specified in the request. Flag `ETHTOOL_A_STRSET_COUNTS_ONLY` tells kernel to only return string counts of the sets, not the actual strings.

<a id="rst-linkinfo-get"></a>

## LINKINFO_GET

Requests link settings as provided by `ETHTOOL_GLINKSETTINGS` except for link modes and autonegotiation related information. The request does not use any attributes.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_PORT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> physical port
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_PHYADDR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> phy MDIO address
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_TP_MDIX`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> MDI(-X) status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_TP_MDIX_CTRL`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> MDI(-X) control
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_TRANSCEIVER`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> transceiver
>
> </td>
> </tr>
> </tbody>
> </table>

Attributes and their values have the same meaning as matching members of the corresponding ioctl structures.

`LINKINFO_GET` allows dump requests (kernel returns reply message for all devices supporting the request).

<a id="rst-linkinfo-set"></a>

## LINKINFO_SET

`LINKINFO_SET` request allows setting some of the attributes reported by `LINKINFO_GET`.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_PORT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> physical port
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_PHYADDR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> phy MDIO address
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKINFO_TP_MDIX_CTRL`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> MDI(-X) control
>
> </td>
> </tr>
> </tbody>
> </table>

MDI(-X) status and transceiver cannot be set, request with the corresponding attributes is rejected.

<a id="rst-linkmodes-get"></a>

## LINKMODES_GET

Requests link modes (supported, advertised and peer advertised) and related information (autonegotiation status, link speed and duplex) as provided by `ETHTOOL_GLINKSETTINGS`. The request does not use any attributes.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_AUTONEG`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> autonegotiation status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_OURS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> advertised link modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_PEER`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> partner link modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_SPEED`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> link speed (Mb/s)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_DUPLEX`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> duplex mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Master/slave port mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_MASTER_SLAVE_STATE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Master/slave port state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_RATE_MATCHING`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PHY rate matching
>
> </td>
> </tr>
> </tbody>
> </table>

For `ETHTOOL_A_LINKMODES_OURS`, value represents advertised modes and mask represents supported modes. `ETHTOOL_A_LINKMODES_PEER` in the reply is a bit list.

`LINKMODES_GET` allows dump requests (kernel returns reply messages for all devices supporting the request).

<a id="rst-linkmodes-set"></a>

## LINKMODES_SET

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_AUTONEG`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> autonegotiation status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_OURS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> advertised link modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_PEER`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> partner link modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_SPEED`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> link speed (Mb/s)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_DUPLEX`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> duplex mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_MASTER_SLAVE_CFG`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Master/slave port mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_RATE_MATCHING`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PHY rate matching
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKMODES_LANES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> lanes
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_LINKMODES_OURS` bit set allows setting advertised link modes. If autonegotiation is on (either set now or kept from before), advertised modes are not changed (no `ETHTOOL_A_LINKMODES_OURS` attribute) and at least one of speed, duplex and lanes is specified, kernel adjusts advertised modes to all supported modes matching speed, duplex, lanes or all (whatever is specified). This autoselection is done on ethtool side with ioctl interface, netlink interface is supposed to allow requesting changes without knowing what exactly kernel supports.

<a id="rst-linkstate-get"></a>

## LINKSTATE_GET

Requests link state information. Link up/down flag (as provided by `ETHTOOL_GLINK` ioctl command) is provided. Optionally, extended state might be provided as well. In general, extended state describes reasons for why a port is down, or why it operates in some non-obvious mode. This request does not have any attributes.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_LINK`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> link state (up/down)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_SQI`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Current Signal Quality Index
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_SQI_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Max support SQI value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_EXT_STATE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> link extended state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_EXT_SUBSTATE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> link extended substate
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_LINKSTATE_EXT_DOWN_CNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> count of link down events
>
> </td>
> </tr>
> </tbody>
> </table>

For most NIC drivers, the value of `ETHTOOL_A_LINKSTATE_LINK` returns carrier flag provided by `netif_carrier_ok()` but there are drivers which define their own handler.

`ETHTOOL_A_LINKSTATE_EXT_STATE` and `ETHTOOL_A_LINKSTATE_EXT_SUBSTATE` are optional values. ethtool core can provide either both `ETHTOOL_A_LINKSTATE_EXT_STATE` and `ETHTOOL_A_LINKSTATE_EXT_SUBSTATE`, or only `ETHTOOL_A_LINKSTATE_EXT_STATE`, or none of them.

`LINKSTATE_GET` allows dump requests (kernel returns reply messages for all devices supporting the request).

Link extended states:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_AUTONEG`
>
> </td>
> <td>
>
>
> States relating to the autonegotiation or issues therein
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_LINK_TRAINING_FAILURE`
>
> </td>
> <td>
>
>
> Failure during link training
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_LINK_LOGICAL_MISMATCH`
>
> </td>
> <td>
>
>
> Logical mismatch in physical coding sublayer or forward error correction sublayer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_BAD_SIGNAL_INTEGRITY`
>
> </td>
> <td>
>
>
> Signal integrity issues
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_NO_CABLE`
>
> </td>
> <td>
>
>
> No cable connected
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_CABLE_ISSUE`
>
> </td>
> <td>
>
>
> Failure is related to cable, e.g., unsupported cable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_EEPROM_ISSUE`
>
> </td>
> <td>
>
>
> Failure is related to EEPROM, e.g., failure during reading or parsing the data
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_CALIBRATION_FAILURE`
>
> </td>
> <td>
>
>
> Failure during calibration algorithm
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_POWER_BUDGET_EXCEEDED`
>
> </td>
> <td>
>
>
> The hardware is not able to provide the power required from cable or module
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_OVERHEAT`
>
> </td>
> <td>
>
>
> The module is overheated
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_STATE_MODULE`
>
> </td>
> <td>
>
>
> Transceiver module issue
>
> </td>
> </tr>
> </tbody>
> </table>

Link extended substates:

> Autoneg substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_PARTNER_DETECTED`
>
> </td>
> <td>
>
>
> Peer side is down
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_ACK_NOT_RECEIVED`
>
> </td>
> <td>
>
>
> Ack not received from peer side
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_NEXT_PAGE_EXCHANGE_FAILED`
>
> </td>
> <td>
>
>
> Next page exchange failed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_PARTNER_DETECTED_FORCE_MODE`
>
> </td>
> <td>
>
>
> Peer side is down during force mode or there is no agreement of speed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_FEC_MISMATCH_DURING_OVERRIDE`
>
> </td>
> <td>
>
>
> Forward error correction modes in both sides are mismatched
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_AN_NO_HCD`
>
> </td>
> <td>
>
>
> No Highest Common Denominator
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Link training substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_FRAME_LOCK_NOT_ACQUIRED`
>
> </td>
> <td>
>
>
> Frames were not recognized, the lock failed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_LINK_INHIBIT_TIMEOUT`
>
> </td>
> <td>
>
>
> The lock did not occur before timeout
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LT_KR_LINK_PARTNER_DID_NOT_SET_RECEIVER_READY`
>
> </td>
> <td>
>
>
> Peer side did not send ready signal after training process
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LT_REMOTE_FAULT`
>
> </td>
> <td>
>
>
> Remote side is not ready yet
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Link logical mismatch substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_ACQUIRE_BLOCK_LOCK`
>
> </td>
> <td>
>
>
> Physical coding sublayer was not locked in first phase - block lock
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_ACQUIRE_AM_LOCK`
>
> </td>
> <td>
>
>
> Physical coding sublayer was not locked in second phase - alignment markers lock
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LLM_PCS_DID_NOT_GET_ALIGN_STATUS`
>
> </td>
> <td>
>
>
> Physical coding sublayer did not get align status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LLM_FC_FEC_IS_NOT_LOCKED`
>
> </td>
> <td>
>
>
> FC forward error correction is not locked
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_LLM_RS_FEC_IS_NOT_LOCKED`
>
> </td>
> <td>
>
>
> RS forward error correction is not locked
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Bad signal integrity substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_BSI_LARGE_NUMBER_OF_PHYSICAL_ERRORS`
>
> </td>
> <td>
>
>
> Large number of physical errors
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_BSI_UNSUPPORTED_RATE`
>
> </td>
> <td>
>
>
> The system attempted to operate the cable at a rate that is not formally supported, which led to signal integrity issues
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_BSI_SERDES_REFERENCE_CLOCK_LOST`
>
> </td>
> <td>
>
>
> The external clock signal for SerDes is too weak or unavailable.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_BSI_SERDES_ALOS`
>
> </td>
> <td>
>
>
> The received signal for SerDes is too weak because analog loss of signal.
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Cable issue substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_CI_UNSUPPORTED_CABLE`
>
> </td>
> <td>
>
>
> Unsupported cable
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_CI_CABLE_TEST_FAILURE`
>
> </td>
> <td>
>
>
> Cable test failure
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Transceiver module issue substates:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_LINK_EXT_SUBSTATE_MODULE_CMIS_NOT_READY`
>
> </td>
> <td>
>
>
> The CMIS Module State Machine did not reach the ModuleReady state. For example, if the module is stuck at ModuleFault state
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-debug-get"></a>

## DEBUG_GET

Requests debugging settings of a device. At the moment, only message mask is provided.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_DEBUG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_DEBUG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_DEBUG_MSGMASK`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> message mask
>
> </td>
> </tr>
> </tbody>
> </table>

The message mask (`ETHTOOL_A_DEBUG_MSGMASK`) is equal to message level as provided by `ETHTOOL_GMSGLVL` and set by `ETHTOOL_SMSGLVL` in ioctl interface. While it is called message level there for historical reasons, most drivers and almost all newer drivers use it as a mask of enabled message classes (represented by `NETIF_MSG_*` constants); therefore netlink interface follows its actual use in practice.

`DEBUG_GET` allows dump requests (kernel returns reply messages for all devices supporting the request).

<a id="rst-debug-set"></a>

## DEBUG_SET

Set or update debugging settings of a device. At the moment, only message mask is supported.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_DEBUG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_DEBUG_MSGMASK`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> message mask
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_DEBUG_MSGMASK` bit set allows setting or modifying mask of enabled debugging message types for the device.

<a id="rst-wol-get"></a>

## WOL_GET

Query device wake-on-lan settings. Unlike most "GET" type requests, `ETHTOOL_MSG_WOL_GET` requires (netns) `CAP_NET_ADMIN` privileges as it (potentially) provides SecureOn(tm) password which is confidential.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_MODES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> mask of enabled WoL modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_SOPASS`
>
> </td>
> <td>
>
>
> binary
>
> </td>
> <td>
>
>
> SecureOn(tm) password
>
> </td>
> </tr>
> </tbody>
> </table>

In reply, `ETHTOOL_A_WOL_MODES` mask consists of modes supported by the device, value of modes which are enabled. `ETHTOOL_A_WOL_SOPASS` is only included in reply if `WAKE_MAGICSECURE` mode is supported.

<a id="rst-wol-set"></a>

## WOL_SET

Set or update wake-on-lan settings.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_MODES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> enabled WoL modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_WOL_SOPASS`
>
> </td>
> <td>
>
>
> binary
>
> </td>
> <td>
>
>
> SecureOn(tm) password
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_WOL_SOPASS` is only allowed for devices supporting `WAKE_MAGICSECURE` mode.

<a id="rst-features-get"></a>

## FEATURES_GET

Gets netdev features like `ETHTOOL_GFEATURES` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_HW`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> dev-&gt;hw_features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_WANTED`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> dev-&gt;wanted_features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_ACTIVE`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> dev-&gt;features
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_NOCHANGE`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> NETIF_F_NEVER_CHANGE
>
> </td>
> </tr>
> </tbody>
> </table>

Bitmaps in kernel response have the same meaning as bitmaps used in ioctl interference but attribute names are different (they are based on corresponding members of struct net_device). Legacy "flags" are not provided, if userspace needs them (most likely only ethtool for backward compatibility), it can calculate their values from related feature bits itself. ETHA_FEATURES_HW uses mask consisting of all features recognized by kernel (to provide all names when using verbose bitmap format), the other three use no mask (simple bit lists).

<a id="rst-features-set"></a>

## FEATURES_SET

Request to set netdev features like `ETHTOOL_SFEATURES` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_WANTED`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> requested features
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_WANTED`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> diff wanted vs. result
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEATURES_ACTIVE`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> diff old vs. new active
>
> </td>
> </tr>
> </tbody>
> </table>

Request contains only one bitset which can be either value/mask pair (request to change specific feature bits and leave the rest) or only a value (request to set all features to specified set).

As request is subject to netdev_change_features() sanity checks, optional kernel reply (can be suppressed by `ETHTOOL_FLAG_OMIT_REPLY` flag in request header) informs client about the actual result. `ETHTOOL_A_FEATURES_WANTED` reports the difference between client request and actual result: mask consists of bits which differ between requested features and result (dev-&gt;features after the operation), value consists of values of these bits in the request (i.e. negated values from resulting features). `ETHTOOL_A_FEATURES_ACTIVE` reports the difference between old and new dev-&gt;features: mask consists of bits which have changed, values are their values in new dev-&gt;features (after the operation).

`ETHTOOL_MSG_FEATURES_NTF` notification is sent not only if device features are modified using `ETHTOOL_MSG_FEATURES_SET` request or on of ethtool ioctl request but also each time features are modified with netdev_update_features() or netdev_change_features().

<a id="rst-privflags-get"></a>

## PRIVFLAGS_GET

Gets private flags like `ETHTOOL_GPFLAGS` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PRIVFLAGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PRIVFLAGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PRIVFLAGS_FLAGS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> private flags
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_PRIVFLAGS_FLAGS` is a bitset with values of device private flags. These flags are defined by driver, their number and names (and also meaning) are device dependent. For compact bitset format, names can be retrieved as `ETH_SS_PRIV_FLAGS` string set. If verbose bitset format is requested, response uses all private flags supported by the device as mask so that client gets the full information without having to fetch the string set with names.

<a id="rst-privflags-set"></a>

## PRIVFLAGS_SET

Sets or modifies values of device private flags like `ETHTOOL_SPFLAGS` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PRIVFLAGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PRIVFLAGS_FLAGS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> private flags
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_PRIVFLAGS_FLAGS` can either set the whole set of private flags or modify only values of some of them.

<a id="rst-rings-get"></a>

## RINGS_GET

Gets ring sizes like `ETHTOOL_GRINGPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of RX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_MINI_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of RX mini ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_JUMBO_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of RX jumbo ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of TX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_MINI`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX mini ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_JUMBO`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX jumbo ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of TX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_BUF_LEN`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of buffers on the ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TCP_DATA_SPLIT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> TCP header / data split
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_CQE_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Size of TX/RX CQE
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_PUSH`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> flag of TX Push mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_PUSH`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> flag of RX Push mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of TX push buffer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of TX push buffer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HDS_THRESH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold of header / data split
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HDS_THRESH_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max threshold of header / data split
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_RINGS_TCP_DATA_SPLIT` indicates whether the device is usable with page-flipping TCP zero-copy receive (`getsockopt(TCP_ZEROCOPY_RECEIVE)`). If enabled the device is configured to place frame headers and data into separate buffers. The device configuration must make it possible to receive full memory pages of data, for example because MTU is high enough or through HW-GRO.

`ETHTOOL_A_RINGS_[RX|TX]_PUSH` flag is used to enable descriptor fast path to send or receive packets. In ordinary path, driver fills descriptors in DRAM and notifies NIC hardware. In fast path, driver pushes descriptors to the device through MMIO writes, thus reducing the latency. However, enabling this feature may increase the CPU cost. Drivers may enforce additional per-packet eligibility checks (e.g. on packet size).

`ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN` specifies the maximum number of bytes of a transmitted packet a driver can push directly to the underlying device ('push' mode). Pushing some of the payload bytes to the device has the advantages of reducing latency for small packets by avoiding DMA mapping (same as `ETHTOOL_A_RINGS_TX_PUSH` parameter) as well as allowing the underlying device to process packet headers ahead of fetching its payload. This can help the device to make fast actions based on the packet's headers. This is similar to the "tx-copybreak" parameter, which copies the packet to a preallocated DMA memory area instead of mapping new memory. However, tx-push-buff parameter copies the packet directly to the device to allow the device to take faster actions on the packet.

<a id="rst-rings-set"></a>

## RINGS_SET

Sets ring sizes like `ETHTOOL_SRINGPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_MINI`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX mini ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_JUMBO`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of RX jumbo ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of TX ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_BUF_LEN`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of buffers on the ring
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TCP_DATA_SPLIT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> TCP header / data split
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_CQE_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Size of TX/RX CQE
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_PUSH`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> flag of TX Push mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_RX_PUSH`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> flag of RX Push mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_TX_PUSH_BUF_LEN`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> size of TX push buffer
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_RINGS_HDS_THRESH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold of header / data split
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel checks that requested ring sizes do not exceed limits reported by driver. Driver may impose additional constraints and may not support all attributes.

`ETHTOOL_A_RINGS_CQE_SIZE` specifies the completion queue event size. Completion queue events (CQE) are the events posted by NIC to indicate the completion status of a packet when the packet is sent (like send success or error) or received (like pointers to packet fragments). The CQE size parameter enables to modify the CQE size other than default size if NIC supports it. A bigger CQE can have more receive buffer pointers, and in turn the NIC can transfer a bigger frame from wire. Based on the NIC hardware, the overall completion queue size can be adjusted in the driver if CQE size is modified.

`ETHTOOL_A_RINGS_HDS_THRESH` specifies the threshold value of header / data split feature. If a received packet size is larger than this threshold value, header and data will be split.

<a id="rst-channels-get"></a>

## CHANNELS_GET

Gets channel counts like `ETHTOOL_GCHANNELS` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_RX_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max receive channels
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_TX_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max transmit channels
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_OTHER_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max other channels
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_COMBINED_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max combined channels
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_RX_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> receive channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_TX_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> transmit channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_OTHER_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> other channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_COMBINED_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> combined channel count
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-channels-set"></a>

## CHANNELS_SET

Sets channel counts like `ETHTOOL_SCHANNELS` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_RX_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> receive channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_TX_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> transmit channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_OTHER_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> other channel count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CHANNELS_COMBINED_COUNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> combined channel count
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel checks that requested channel counts do not exceed limits reported by driver. Driver may impose additional constraints and may not support all attributes.

<a id="rst-coalesce-get"></a>

## COALESCE_GET

Gets coalescing parameters like `ETHTOOL_GCOALESCE` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), normal Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, normal Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), Rx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, Rx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), normal Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, normal Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), Tx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> IRQ packets, Tx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_STATS_BLOCK_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay of stats update
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> adaptive Rx coalesce
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> adaptive Tx coalesce
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_PKT_RATE_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold for low rate
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), low Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, low Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), low Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, low Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_PKT_RATE_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold for high rate
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), high Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, high Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), high Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, high Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> rate sampling interval
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_CQE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> timer reset mode, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_CQE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> timer reset mode, Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max aggr size, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max aggr packets, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> time (us), aggr, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_PROFILE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> profile of DIM, Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_PROFILE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> profile of DIM, Tx
>
> </td>
> </tr>
> </tbody>
> </table>

Attributes are only included in reply if their value is not zero or the corresponding bit in `ethtool_ops::supported_coalesce_params` is set (i.e. they are declared as supported by driver).

Timer reset mode (`ETHTOOL_A_COALESCE_USE_CQE_TX` and `ETHTOOL_A_COALESCE_USE_CQE_RX`) controls the interaction between packet arrival and the various time based delay parameters. By default timers are expected to limit the max delay between any packet arrival/departure and a corresponding interrupt. In this mode timer should be started by packet arrival (sometimes delivery of previous interrupt) and reset when interrupt is delivered. Setting the appropriate attribute to 1 will enable `CQE` mode, where each packet event resets the timer. In this mode timer is used to force the interrupt if queue goes idle, while busy queues depend on the packet limit to trigger interrupts.

Tx aggregation consists of copying frames into a contiguous buffer so that they can be submitted as a single IO operation. `ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES` describes the maximum size in bytes for the submitted buffer. `ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES` describes the maximum number of frames that can be aggregated into a single buffer. `ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS` describes the amount of time in usecs, counted since the first packet arrival in an aggregated block, after which the block should be sent. This feature is mainly of interest for specific USB devices which does not cope well with frequent small-sized URBs transmissions.

`ETHTOOL_A_COALESCE_RX_PROFILE` and `ETHTOOL_A_COALESCE_TX_PROFILE` refer to DIM parameters, see [Generic Network Dynamic Interrupt Moderation (Net DIM)](<https://www.kernel.org/doc/Documentation/networking/net_dim.rst>)<a id="rst-generic-network-dynamic-interrupt-moderation-net-dim"></a>.

<a id="rst-coalesce-set"></a>

## COALESCE_SET

Sets coalescing parameters like `ETHTOOL_SCOALESCE` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), normal Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, normal Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), Rx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, Rx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), normal Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, normal Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), Tx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_IRQ`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> IRQ packets, Tx in IRQ
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_STATS_BLOCK_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay of stats update
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_ADAPTIVE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> adaptive Rx coalesce
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_ADAPTIVE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> adaptive Tx coalesce
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_PKT_RATE_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold for low rate
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), low Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, low Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), low Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_LOW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, low Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_PKT_RATE_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> threshold for high rate
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_USECS_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), high Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_MAX_FRAMES_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, high Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_USECS_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay (us), high Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_MAX_FRAMES_HIGH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max packets, high Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RATE_SAMPLE_INTERVAL`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> rate sampling interval
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_CQE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> timer reset mode, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_USE_CQE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> timer reset mode, Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_MAX_BYTES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max aggr size, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_MAX_FRAMES`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max aggr packets, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_AGGR_TIME_USECS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> time (us), aggr, Tx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_RX_PROFILE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> profile of DIM, Rx
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_COALESCE_TX_PROFILE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> profile of DIM, Tx
>
> </td>
> </tr>
> </tbody>
> </table>

Request is rejected if it attributes declared as unsupported by driver (i.e. such that the corresponding bit in `ethtool_ops::supported_coalesce_params` is not set), regardless of their values. Driver may impose additional constraints on coalescing parameters and their values.

Compared to requests issued via the `ioctl()` netlink version of this request will try harder to make sure that values specified by the user have been applied and may call the driver twice.

<a id="rst-pause-get"></a>

## PAUSE_GET

Gets pause frame settings like `ETHTOOL_GPAUSEPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_STATS_SRC`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> source of statistics
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_PAUSE_STATS_SRC` is optional. It takes values from:


#### <a id="c-enum-ethtool_mac_stats_src"></a>`enum ethtool_mac_stats_src`

source of ethtool MAC statistics

**Constants**

- `ETHTOOL_MAC_STATS_SRC_AGGREGATE`: if device supports a MAC merge layer, this retrieves the aggregate
  statistics of the eMAC and pMAC. Otherwise, it retrieves just the
  statistics of the single (express) MAC.
- `ETHTOOL_MAC_STATS_SRC_EMAC`: if device supports a MM layer, this retrieves the eMAC statistics.
  Otherwise, it retrieves the statistics of the single (express) MAC.
- `ETHTOOL_MAC_STATS_SRC_PMAC`: if device supports a MM layer, this retrieves the pMAC statistics.


If absent from the request, stats will be provided with an `ETHTOOL_A_PAUSE_STATS_SRC` attribute in the response equal to `ETHTOOL_MAC_STATS_SRC_AGGREGATE`.

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_AUTONEG`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> pause autonegotiation
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> receive pause frames
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> transmit pause frames
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_STATS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> pause statistics
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_PAUSE_STATS` are reported if `ETHTOOL_FLAG_STATS` was set in `ETHTOOL_A_HEADER_FLAGS`. It will be empty if driver did not report any statistics. Drivers fill in the statistics in the following structure:


#### <a id="c-struct-ethtool_pause_stats"></a>`struct ethtool_pause_stats`

statistics for IEEE 802.3x pause frames

**Definition**

```c
struct ethtool_pause_stats {
    enum ethtool_mac_stats_src src;
    u64 tx_pause_frames;
    u64 rx_pause_frames;
};
```

**Members**

- `src`: input field denoting whether stats should be queried from the eMAC or
  pMAC (if the MM layer is supported). To be ignored otherwise.
- `tx_pause_frames`: transmitted pause frame count. Reported to user space
  as `ETHTOOL_A_PAUSE_STAT_TX_FRAMES`.
- `rx_pause_frames`: received pause frame count. Reported to user space
  as `ETHTOOL_A_PAUSE_STAT_RX_FRAMES`. Equivalent to:

**Description**

Equivalent to `30.3.4.2 aPAUSEMACCtrlFramesTransmitted`
from the standard.

Equivalent to `30.3.4.3 aPAUSEMACCtrlFramesReceived`
from the standard.


Each member has a corresponding attribute defined.

<a id="rst-pause-set"></a>

## PAUSE_SET

Sets pause parameters like `ETHTOOL_GPAUSEPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_AUTONEG`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> pause autonegotiation
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_RX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> receive pause frames
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PAUSE_TX`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> transmit pause frames
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-eee-get"></a>

## EEE_GET

Gets Energy Efficient Ethernet settings like `ETHTOOL_GEEE` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_MODES_OURS`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> supported/advertised modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_MODES_PEER`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> peer advertised link modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_ACTIVE`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> EEE is actively used
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> EEE is enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_TX_LPI_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> Tx lpi enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_TX_LPI_TIMER`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Tx lpi timeout (in us)
>
> </td>
> </tr>
> </tbody>
> </table>

In `ETHTOOL_A_EEE_MODES_OURS`, mask consists of link modes for which EEE is enabled, value of link modes for which EEE is advertised. Link modes for which peer advertises EEE are listed in `ETHTOOL_A_EEE_MODES_PEER` (no mask). The netlink interface allows reporting EEE status for all link modes but only first 32 are provided by the `ethtool_ops` callback.

<a id="rst-eee-set"></a>

## EEE_SET

Sets Energy Efficient Ethernet parameters like `ETHTOOL_SEEE` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_MODES_OURS`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> advertised modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> EEE is enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_TX_LPI_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> Tx lpi enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_EEE_TX_LPI_TIMER`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Tx lpi timeout (in us)
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_EEE_MODES_OURS` is used to either list link modes to advertise EEE for (if there is no mask) or specify changes to the list (if there is a mask). The netlink interface allows reporting EEE status for all link modes but only first 32 can be set at the moment as that is what the `ethtool_ops` callback supports.

<a id="rst-tsinfo-get"></a>

## TSINFO_GET

Gets timestamping information like `ETHTOOL_GET_TS_INFO` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_HWTSTAMP_PROVIDER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> PTP hw clock provider
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_TIMESTAMPING`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> SO_TIMESTAMPING flags
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_TX_TYPES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> supported Tx types
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_RX_FILTERS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> supported Rx filters
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_PHC_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> PTP hw clock index
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSINFO_STATS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> HW timestamping statistics
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_TSINFO_PHC_INDEX` is absent if there is no associated PHC (there is no special value for this case). The bitset attributes are omitted if they would be empty (no bit set).

Additional hardware timestamping statistics response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TS_STAT_TX_PKTS`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> Packets with Tx HW timestamps
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TS_STAT_TX_LOST`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> Tx HW timestamp not arrived count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TS_STAT_TX_ERR`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> HW error request Tx timestamp count
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TS_STAT_TX_ONESTEP_PKTS_UNCONFIRMED`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> Packets with one-step HW TX timestamps with unconfirmed delivery
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-cable-test"></a>

## CABLE_TEST

Start a cable test.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_CABLE_TEST_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Notification contents:

An Ethernet cable typically contains 1, 2 or 4 pairs. The length of the pair can only be measured when there is a fault in the pair and hence a reflection. Information about the fault may not be available, depending on the specific hardware. Hence the contents of the notify message are mostly optional. The attributes can be repeated an arbitrary number of times, in an arbitrary order, for an arbitrary number of pairs.

The example shows the notification sent when the test is completed for a T2 cable, i.e. two pairs. One pair is OK and hence has no length information. The second pair has a fault and does have length information.

>
> <table>
> <tbody>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_STATUS`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> completed
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_NTF_NEST`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> all the results
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_NEST_RESULT`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> cable test result
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_CODE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> result code
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_NEST_RESULT`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> cable test results
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_CODE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> result code
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULT_SRC`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> information source
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_NEST_FAULT_LENGTH`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> cable length
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_FAULT_LENGTH_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_FAULT_LENGTH_CM`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> length in cm
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_FAULT_LENGTH_SRC`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> information source
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-cable-test-tdr"></a>

## CABLE_TEST TDR

Start a cable test and report raw TDR data

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_CFG`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> test configuration
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_STEP_FIRST_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> first data distance
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_STEP_LAST_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> last data distance
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_STEP_STEP_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> distance of each step
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_CFG_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair to test
>
> </td>
> </tr>
> </tbody>
> </table>

The ETHTOOL_A_CABLE_TEST_TDR_CFG is optional, as well as all members of the nest. All distances are expressed in centimeters. The PHY takes the distances as a guide, and rounds to the nearest distance it actually supports. If a pair is passed, only that one pair will be tested. Otherwise all pairs are tested.

Notification contents:

Raw TDR data is gathered by sending a pulse down the cable and recording the amplitude of the reflected pulse for a given distance.

It can take a number of seconds to collect TDR data, especial if the full 100 meters is probed at 1 meter intervals. When the test is started a notification will be sent containing just ETHTOOL_A_CABLE_TEST_TDR_STATUS with the value ETHTOOL_A_CABLE_TEST_NTF_STATUS_STARTED.

When the test has completed a second notification will be sent containing ETHTOOL_A_CABLE_TEST_TDR_STATUS with the value ETHTOOL_A_CABLE_TEST_NTF_STATUS_COMPLETED and the TDR data.

The message may optionally contain the amplitude of the pulse send down the cable. This is measured in mV. A reflection should not be bigger than transmitted pulse.

Before the raw TDR data should be an ETHTOOL_A_CABLE_TDR_NEST_STEP nest containing information about the distance along the cable for the first reading, the last reading, and the step between each reading. Distances are measured in centimeters. These should be the exact values the PHY used. These may be different to what the user requested, if the native measurement resolution is greater than 1 cm.

For each step along the cable, a ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE is used to report the amplitude of the reflection for a given pair.

>
> <table>
> <tbody>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_STATUS`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> completed
>
> </td>
> </tr>
> <tr>
> <td colspan="3">
>
>
> `ETHTOOL_A_CABLE_TEST_TDR_NTF_NEST`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> all the results
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_TDR_NEST_PULSE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> TX Pulse amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_PULSE_mV`
>
> </td>
> <td>
>
>
> s16
>
> </td>
> <td>
>
>
> Pulse amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_NEST_STEP`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> TDR step info
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_STEP_FIRST_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> First data distance
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_STEP_LAST_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Last data distance
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_STEP_STEP_DISTANCE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> distance of each step
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_AMPLITUDE_mV`
>
> </td>
> <td>
>
>
> s16
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_AMPLITUDE_mV`
>
> </td>
> <td>
>
>
> s16
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_CABLE_TDR_NEST_AMPLITUDE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_RESULTS_PAIR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> pair number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_CABLE_AMPLITUDE_mV`
>
> </td>
> <td>
>
>
> s16
>
> </td>
> <td>
>
>
> Reflection amplitude
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-tunnel-info"></a>

## TUNNEL_INFO

Gets information about the tunnel state NIC is aware of.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TUNNEL_INFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="4">
>
>
> `ETHTOOL_A_TUNNEL_INFO_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="4">
>
>
> `ETHTOOL_A_TUNNEL_INFO_UDP_PORTS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> all UDP port tables
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td colspan="3">
>
>
> `ETHTOOL_A_TUNNEL_UDP_TABLE`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one UDP port table
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_TUNNEL_UDP_TABLE_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> max size of the table
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_TUNNEL_UDP_TABLE_TYPES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> tunnel types which table can hold
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td colspan="2">
>
>
> `ETHTOOL_A_TUNNEL_UDP_TABLE_ENTRY`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> offloaded UDP port
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_TUNNEL_UDP_ENTRY_PORT`
>
> </td>
> <td>
>
>
> be16
>
> </td>
> <td>
>
>
> UDP port
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_TUNNEL_UDP_ENTRY_TYPE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> tunnel type
>
> </td>
> </tr>
> </tbody>
> </table>

For UDP tunnel table empty `ETHTOOL_A_TUNNEL_UDP_TABLE_TYPES` indicates that the table contains static entries, hard-coded by the NIC.

<a id="rst-fec-get"></a>

## FEC_GET

Gets FEC configuration and state like `ETHTOOL_GFECPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_MODES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> configured modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_AUTO`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> FEC mode auto selection
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_ACTIVE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> index of active FEC mode
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_STATS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> FEC statistics
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_FEC_ACTIVE` is the bit index of the FEC link mode currently active on the interface. This attribute may not be present if device does not support FEC.

`ETHTOOL_A_FEC_MODES` and `ETHTOOL_A_FEC_AUTO` are only meaningful when autonegotiation is disabled. If `ETHTOOL_A_FEC_AUTO` is non-zero driver will select the FEC mode automatically based on the parameters of the SFP module. This is equivalent to the `ETHTOOL_FEC_AUTO` bit of the ioctl interface. `ETHTOOL_A_FEC_MODES` carry the current FEC configuration using link mode bits (rather than old `ETHTOOL_FEC_*` bits).

`ETHTOOL_A_FEC_STATS` are reported if `ETHTOOL_FLAG_STATS` was set in `ETHTOOL_A_HEADER_FLAGS`. Each attribute carries an array of 64bit statistics. First entry in the array contains the total number of events on the port, while the following entries are counters corresponding to lanes/PCS instances. The number of entries in the array will be:


<table>
<tbody>
<tr>
<td>


`0`

</td>
<td>


device does not support FEC statistics

</td>
</tr>
<tr>
<td>


`1`

</td>
<td>


device does not support per-lane break down

</td>
</tr>
<tr>
<td>


`1 + #lanes`

</td>
<td>


device has full support for FEC stats

</td>
</tr>
</tbody>
</table>

Drivers fill in the statistics in the following structure:


#### <a id="c-struct-ethtool_fec_stats"></a>`struct ethtool_fec_stats`

statistics for IEEE 802.3 FEC

**Definition**

```c
struct ethtool_fec_stats {
    struct ethtool_fec_stat {
        u64 total;
        u64 lanes[ETHTOOL_MAX_LANES];
    } corrected_blocks, uncorrectable_blocks, corrected_bits;
};
```

**Members**

- `corrected_blocks`: number of received blocks corrected by FEC
  Reported to user space as `ETHTOOL_A_FEC_STAT_CORRECTED`.
- `uncorrectable_blocks`: number of received blocks FEC was not able to correct
  Reported to user space as `ETHTOOL_A_FEC_STAT_UNCORR`.
- `corrected_bits`: number of bits corrected by FEC
  Similar to **corrected_blocks** but counts individual bit changes,
  not entire FEC data blocks. This is a non-standard statistic.
  Reported to user space as `ETHTOOL_A_FEC_STAT_CORR_BITS`.

**Description**

Equivalent to `30.5.1.1.17 aFECCorrectedBlocks` from the standard.

Equivalent to `30.5.1.1.18 aFECUncorrectableBlocks` from the standard.

For each of the above fields, the two substructure members are:

- **lanes**: per-lane/PCS-instance counts as defined by the standard
- **total**: error counts for the entire port, for drivers incapable of reporting
  per-lane stats

Drivers should fill in either only total or per-lane statistics, core
will take care of adding lane values up to produce the total.


Statistics may have FEC bins histogram attribute `ETHTOOL_A_FEC_STAT_HIST` as defined in IEEE 802.3ck-2022 and 802.3df-2024. Nested attributes will have the range of FEC errors in the bin (inclusive) and the amount of error events in the bin.

<a id="rst-fec-set"></a>

## FEC_SET

Sets FEC parameters like `ETHTOOL_SFECPARAM` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_MODES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> configured modes
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_FEC_AUTO`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> FEC mode auto selection
>
> </td>
> </tr>
> </tbody>
> </table>

`FEC_SET` is only meaningful when autonegotiation is disabled. Otherwise FEC mode is selected as part of autonegotiation.

`ETHTOOL_A_FEC_MODES` selects which FEC mode should be used. It's recommended to set only one bit, if multiple bits are set driver may choose between them in an implementation specific way.

`ETHTOOL_A_FEC_AUTO` requests the driver to choose FEC mode based on SFP module parameters. This does not mean autonegotiation.

<a id="rst-module-eeprom-get"></a>

## MODULE_EEPROM_GET

Fetch module EEPROM data dump. This interface is designed to allow dumps of at most 1/2 page at once. This means only dumps of 128 (or less) bytes are allowed, without crossing half page boundary located at offset 128. For pages other than 0 only high 128 bytes are accessible.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_OFFSET`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> offset within a page
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_LENGTH`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> amount of bytes to read
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_PAGE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> page number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_BANK`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> bank number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_I2C_ADDRESS`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> page I2C address
>
> </td>
> </tr>
> </tbody>
> </table>

If `ETHTOOL_A_MODULE_EEPROM_BANK` is not specified, bank 0 is assumed.

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_EEPROM_DATA`
>
> </td>
> <td>
>
>
> binary
>
> </td>
> <td>
>
>
> array of bytes from module EEPROM
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_MODULE_EEPROM_DATA` has an attribute length equal to the amount of bytes driver actually read.

<a id="rst-stats-get"></a>

## STATS_GET

Get standard statistics for the interface. Note that this is not a re-implementation of `ETHTOOL_GSTATS` which exposed driver-defined stats.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_STATS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_STATS_SRC`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> source of statistics
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_STATS_GROUPS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> requested groups of stats
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td colspan="2">
>
>
> `ETHTOOL_A_STATS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td colspan="2">
>
>
> `ETHTOOL_A_STATS_SRC`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> source of statistics
>
> </td>
> </tr>
> <tr>
> <td colspan="2">
>
>
> `ETHTOOL_A_STATS_GRP`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> one or more group of stats
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STATS_GRP_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> group ID - `ETHTOOL_STATS_*`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STATS_GRP_SS_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> string set ID for names
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STATS_GRP_STAT`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> nest containing a statistic
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STATS_GRP_HIST_RX`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> histogram statistic (Rx)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> `ETHTOOL_A_STATS_GRP_HIST_TX`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> histogram statistic (Tx)
>
> </td>
> </tr>
> </tbody>
> </table>

Users specify which groups of statistics they are requesting via the `ETHTOOL_A_STATS_GROUPS` bitset. Currently defined values are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ETHTOOL_STATS_ETH_MAC
>
> </td>
> <td>
>
>
> eth-mac
>
> </td>
> <td>
>
>
> Basic IEEE 802.3 MAC statistics (30.3.1.1.\*)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_STATS_ETH_PHY
>
> </td>
> <td>
>
>
> eth-phy
>
> </td>
> <td>
>
>
> Basic IEEE 802.3 PHY statistics (30.3.2.1.\*)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_STATS_ETH_CTRL
>
> </td>
> <td>
>
>
> eth-ctrl
>
> </td>
> <td>
>
>
> Basic IEEE 802.3 MAC Ctrl statistics (30.3.3.\*)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_STATS_RMON
>
> </td>
> <td>
>
>
> rmon
>
> </td>
> <td>
>
>
> RMON (RFC 2819) statistics
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_STATS_PHY
>
> </td>
> <td>
>
>
> phy
>
> </td>
> <td>
>
>
> Additional PHY statistics, not defined by IEEE
>
> </td>
> </tr>
> </tbody>
> </table>

Each group should have a corresponding `ETHTOOL_A_STATS_GRP` in the reply. `ETHTOOL_A_STATS_GRP_ID` identifies which group's statistics nest contains. `ETHTOOL_A_STATS_GRP_SS_ID` identifies the string set ID for the names of the statistics in the group, if available.

Statistics are added to the `ETHTOOL_A_STATS_GRP` nest under `ETHTOOL_A_STATS_GRP_STAT`. `ETHTOOL_A_STATS_GRP_STAT` should contain single 8 byte (u64) attribute inside - the type of that attribute is the statistic ID and the value is the value of the statistic. Each group has its own interpretation of statistic IDs. Attribute IDs correspond to strings from the string set identified by `ETHTOOL_A_STATS_GRP_SS_ID`. Complex statistics (such as RMON histogram entries) are also listed inside `ETHTOOL_A_STATS_GRP` and do not have a string defined in the string set.

RMON "histogram" counters count number of packets within given size range. Because RFC does not specify the ranges beyond the standard 1518 MTU devices differ in definition of buckets. For this reason the definition of packet ranges is left to each driver.

`ETHTOOL_A_STATS_GRP_HIST_RX` and `ETHTOOL_A_STATS_GRP_HIST_TX` nests contain the following attributes:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ETHTOOL_A_STATS_RMON_HIST_BKT_LOW
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> low bound of the packet size bucket
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_A_STATS_RMON_HIST_BKT_HI
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> high bound of the bucket
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ETHTOOL_A_STATS_RMON_HIST_VAL
>
> </td>
> <td>
>
>
> u64
>
> </td>
> <td>
>
>
> packet counter
>
> </td>
> </tr>
> </tbody>
> </table>

Low and high bounds are inclusive, for example:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> RFC statistic
>
> </th>
> <th>
>
>
> low
>
> </th>
> <th>
>
>
> high
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> etherStatsPkts64Octets
>
> </td>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> etherStatsPkts512to1023Octets
>
> </td>
> <td>
>
>
> 512
>
> </td>
> <td>
>
>
> 1023
>
> </td>
> </tr>
> </tbody>
> </table>

`ETHTOOL_A_STATS_SRC` is optional. Similar to `PAUSE_GET`, it takes values from `enum ethtool_mac_stats_src`. If absent from the request, stats will be provided with an `ETHTOOL_A_STATS_SRC` attribute in the response equal to `ETHTOOL_MAC_STATS_SRC_AGGREGATE`.

<a id="rst-phc-vclocks-get"></a>

## PHC_VCLOCKS_GET

Query device PHC virtual clocks information.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHC_VCLOCKS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHC_VCLOCKS_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHC_VCLOCKS_NUM`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> PHC virtual clocks number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHC_VCLOCKS_INDEX`
>
> </td>
> <td>
>
>
> s32
>
> </td>
> <td>
>
>
> PHC index array
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-module-get"></a>

## MODULE_GET

Gets transceiver module parameters.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_POWER_MODE_POLICY`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> power mode policy
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_POWER_MODE`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> operational power mode
>
> </td>
> </tr>
> </tbody>
> </table>

The optional `ETHTOOL_A_MODULE_POWER_MODE_POLICY` attribute encodes the transceiver module power mode policy enforced by the host. The default policy is driver-dependent, but "auto" is the recommended default and it should be implemented by new drivers and drivers where conformance to a legacy behavior is not critical.

The optional `ETHTHOOL_A_MODULE_POWER_MODE` attribute encodes the operational power mode policy of the transceiver module. It is only reported when a module is plugged-in. Possible values are:


#### <a id="c-enum-ethtool_module_power_mode"></a>`enum ethtool_module_power_mode`

plug-in module power mode

**Constants**

- `ETHTOOL_MODULE_POWER_MODE_LOW`: Module is in low power mode.
- `ETHTOOL_MODULE_POWER_MODE_HIGH`: Module is in high power mode.


<a id="rst-module-set"></a>

## MODULE_SET

Sets transceiver module parameters.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_POWER_MODE_POLICY`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> power mode policy
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the optional `ETHTOOL_A_MODULE_POWER_MODE_POLICY` attribute is used to set the transceiver module power policy enforced by the host. Possible values are:


#### <a id="c-enum-ethtool_module_power_mode_policy"></a>`enum ethtool_module_power_mode_policy`

plug-in module power mode policy

**Constants**

- `ETHTOOL_MODULE_POWER_MODE_POLICY_HIGH`: Module is always in high power mode.
- `ETHTOOL_MODULE_POWER_MODE_POLICY_AUTO`: Module is transitioned by the host
  to high power mode when the first port using it is put administratively
  up and to low power mode when the last port using it is put
  administratively down.


For SFF-8636 modules, low power mode is forced by the host according to table 6-10 in revision 2.10a of the specification.

For CMIS modules, low power mode is forced by the host according to table 6-12 in revision 5.0 of the specification.

<a id="rst-pse-get"></a>

## PSE_GET

Gets PSE attributes.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PODL_PSE_ADMIN_STATE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Operational state of the PoDL PSE functions
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PODL_PSE_PW_D_STATUS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> power detection status of the PoDL PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_ADMIN_STATE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Operational state of the PoE PSE functions.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_PW_D_STATUS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> power detection status of the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_PW_CLASS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> power class of the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_ACTUAL_PW`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> actual power drawn on the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_EXT_STATE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> power extended state of the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_EXT_SUBSTATE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> power extended substatus of the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_AVAIL_PW_LIMIT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> currently configured power limit of the PoE PSE.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_PW_LIMIT_RANGES`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> Supported power limit configuration ranges.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_PW_D_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Index of the PSE power domain
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_PRIO_MAX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Priority maximum configurable on the PoE PSE
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_PRIO`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Priority of the PoE PSE currently configured
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the optional `ETHTOOL_A_PODL_PSE_ADMIN_STATE` attribute identifies the operational state of the PoDL PSE functions.  The operational state of the PSE function can be changed using the `ETHTOOL_A_PODL_PSE_ADMIN_CONTROL` action. This attribute corresponds to `IEEE 802.3-2018` 30.15.1.1.2 aPoDLPSEAdminState. Possible values are:


#### <a id="c-enum-ethtool_podl_pse_admin_state"></a>`enum ethtool_podl_pse_admin_state`

operational state of the PoDL PSE functions. IEEE 802.3-2018 30.15.1.1.2 aPoDLPSEAdminState

**Constants**

- `ETHTOOL_PODL_PSE_ADMIN_STATE_UNKNOWN`: state of PoDL PSE functions are
  unknown
- `ETHTOOL_PODL_PSE_ADMIN_STATE_DISABLED`: PoDL PSE functions are disabled
- `ETHTOOL_PODL_PSE_ADMIN_STATE_ENABLED`: PoDL PSE functions are enabled


The same goes for `ETHTOOL_A_C33_PSE_ADMIN_STATE` implementing `IEEE 802.3-2022` 30.9.1.1.2 aPSEAdminState.


#### <a id="c-enum-ethtool_c33_pse_admin_state"></a>`enum ethtool_c33_pse_admin_state`

operational state of the PoDL PSE functions. IEEE 802.3-2022 30.9.1.1.2 aPSEAdminState

**Constants**

- `ETHTOOL_C33_PSE_ADMIN_STATE_UNKNOWN`: state of PSE functions is unknown
- `ETHTOOL_C33_PSE_ADMIN_STATE_DISABLED`: PSE functions are disabled
- `ETHTOOL_C33_PSE_ADMIN_STATE_ENABLED`: PSE functions are enabled


When set, the optional `ETHTOOL_A_PODL_PSE_PW_D_STATUS` attribute identifies the power detection status of the PoDL PSE.  The status depend on internal PSE state machine and automatic PD classification support. This attribute corresponds to `IEEE 802.3-2018` 30.15.1.1.3 aPoDLPSEPowerDetectionStatus. Possible values are:


#### <a id="c-enum-ethtool_podl_pse_pw_d_status"></a>`enum ethtool_podl_pse_pw_d_status`

power detection status of the PoDL PSE. IEEE 802.3-2018 30.15.1.1.3 aPoDLPSEPowerDetectionStatus:

**Constants**

- `ETHTOOL_PODL_PSE_PW_D_STATUS_UNKNOWN`: PoDL PSE
- `ETHTOOL_PODL_PSE_PW_D_STATUS_DISABLED`: "The enumeration “disabled” is
  asserted true when the PoDL PSE state diagram variable mr_pse_enable is
  false"
- `ETHTOOL_PODL_PSE_PW_D_STATUS_SEARCHING`: "The enumeration “searching” is
  asserted true when either of the PSE state diagram variables
  pi_detecting or pi_classifying is true."
- `ETHTOOL_PODL_PSE_PW_D_STATUS_DELIVERING`: "The enumeration “deliveringPower”
  is asserted true when the PoDL PSE state diagram variable pi_powered is
  true."
- `ETHTOOL_PODL_PSE_PW_D_STATUS_SLEEP`: "The enumeration “sleep” is asserted
  true when the PoDL PSE state diagram variable pi_sleeping is true."
- `ETHTOOL_PODL_PSE_PW_D_STATUS_IDLE`: "The enumeration “idle” is asserted true
  when the logical combination of the PoDL PSE state diagram variables
  pi_prebiased*!pi_sleeping is true."
- `ETHTOOL_PODL_PSE_PW_D_STATUS_ERROR`: "The enumeration “error” is asserted
  true when the PoDL PSE state diagram variable overload_held is true."


The same goes for `ETHTOOL_A_C33_PSE_ADMIN_PW_D_STATUS` implementing `IEEE 802.3-2022` 30.9.1.1.5 aPSEPowerDetectionStatus.


#### <a id="c-enum-ethtool_c33_pse_pw_d_status"></a>`enum ethtool_c33_pse_pw_d_status`

power detection status of the PSE. IEEE 802.3-2022 30.9.1.1.3 aPoDLPSEPowerDetectionStatus:

**Constants**

- `ETHTOOL_C33_PSE_PW_D_STATUS_UNKNOWN`: PSE status is unknown
- `ETHTOOL_C33_PSE_PW_D_STATUS_DISABLED`: The enumeration "disabled"
  indicates that the PSE State diagram is in the state DISABLED.
- `ETHTOOL_C33_PSE_PW_D_STATUS_SEARCHING`: The enumeration "searching"
  indicates the PSE State diagram is in a state other than those
  listed.
- `ETHTOOL_C33_PSE_PW_D_STATUS_DELIVERING`: The enumeration
  "deliveringPower" indicates that the PSE State diagram is in the
  state POWER_ON.
- `ETHTOOL_C33_PSE_PW_D_STATUS_TEST`: The enumeration "test" indicates that
  the PSE State diagram is in the state TEST_MODE.
- `ETHTOOL_C33_PSE_PW_D_STATUS_FAULT`: The enumeration "fault" indicates that
  the PSE State diagram is in the state TEST_ERROR.
- `ETHTOOL_C33_PSE_PW_D_STATUS_OTHERFAULT`: The enumeration "otherFault"
  indicates that the PSE State diagram is in the state IDLE due to
  the variable error_condition = true.


When set, the optional `ETHTOOL_A_C33_PSE_PW_CLASS` attribute identifies the power class of the C33 PSE. It depends on the class negotiated between the PSE and the PD. This attribute corresponds to `IEEE 802.3-2022` 30.9.1.1.8 aPSEPowerClassification.

When set, the optional `ETHTOOL_A_C33_PSE_ACTUAL_PW` attribute identifies the actual power drawn by the C33 PSE. This attribute corresponds to `IEEE 802.3-2022` 30.9.1.1.23 aPSEActualPower. Actual power is reported in mW.

When set, the optional `ETHTOOL_A_C33_PSE_EXT_STATE` attribute identifies the extended error state of the C33 PSE. Possible values are:


#### <a id="c-enum-ethtool_c33_pse_ext_state"></a>`enum ethtool_c33_pse_ext_state`

groups of PSE extended states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_STATE_ERROR_CONDITION`: Group of error_condition states
- `ETHTOOL_C33_PSE_EXT_STATE_MR_MPS_VALID`: Group of mr_mps_valid states
- `ETHTOOL_C33_PSE_EXT_STATE_MR_PSE_ENABLE`: Group of mr_pse_enable states
- `ETHTOOL_C33_PSE_EXT_STATE_OPTION_DETECT_TED`: Group of option_detect_ted
  states
- `ETHTOOL_C33_PSE_EXT_STATE_OPTION_VPORT_LIM`: Group of option_vport_lim states
- `ETHTOOL_C33_PSE_EXT_STATE_OVLD_DETECTED`: Group of ovld_detected states
- `ETHTOOL_C33_PSE_EXT_STATE_PD_DLL_POWER_TYPE`: Group of pd_dll_power_type
  states
- `ETHTOOL_C33_PSE_EXT_STATE_POWER_NOT_AVAILABLE`: Group of power_not_available
  states
- `ETHTOOL_C33_PSE_EXT_STATE_SHORT_DETECTED`: Group of short_detected states


When set, the optional `ETHTOOL_A_C33_PSE_EXT_SUBSTATE` attribute identifies the extended error state of the C33 PSE. Possible values are: Possible values are:


#### <a id="c-enum-ethtool_c33_pse_ext_substate_error_condition"></a>`enum ethtool_c33_pse_ext_substate_error_condition`

error_condition states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_NON_EXISTING_PORT`: Non-existing
  port number
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_UNDEFINED_PORT`: Undefined port
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_INTERNAL_HW_FAULT`: Internal
  hardware fault
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_COMM_ERROR_AFTER_FORCE_ON`: Communication error after force on
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_UNKNOWN_PORT_STATUS`: Unknown
  port status
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_HOST_CRASH_TURN_OFF`: Host
  crash turn off
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_HOST_CRASH_FORCE_SHUTDOWN`: Host crash force shutdown
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_CONFIG_CHANGE`: Configuration
  change
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_ERROR_CONDITION_DETECTED_OVER_TEMP`: Over
  temperature detected

**Description**

error_condition is a variable indicating the status of
implementation-specific fault conditions or optionally other system faults
that prevent the PSE from meeting the specifications in Table 33–11 and that
require the PSE not to source power. These error conditions are different
from those monitored by the state diagrams in Figure 33–10.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_mr_pse_enable"></a>`enum ethtool_c33_pse_ext_substate_mr_pse_enable`

mr_pse_enable states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_MR_PSE_ENABLE_DISABLE_PIN_ACTIVE`: Disable
  pin active

**Description**

mr_pse_enable is control variable that selects PSE operation and test
functions.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_option_detect_ted"></a>`enum ethtool_c33_pse_ext_substate_option_detect_ted`

option_detect_ted states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OPTION_DETECT_TED_DET_IN_PROCESS`: Detection
  in process
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OPTION_DETECT_TED_CONNECTION_CHECK_ERROR`: Connection check error

**Description**

option_detect_ted is a variable indicating if detection can be performed
by the PSE during the ted_timer interval.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_option_vport_lim"></a>`enum ethtool_c33_pse_ext_substate_option_vport_lim`

option_vport_lim states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OPTION_VPORT_LIM_HIGH_VOLTAGE`: Main supply
  voltage is high
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OPTION_VPORT_LIM_LOW_VOLTAGE`: Main supply
  voltage is low
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OPTION_VPORT_LIM_VOLTAGE_INJECTION`: Voltage
  injection into the port

**Description**

option_vport_lim is an optional variable indicates if VPSE is out of the
operating range during normal operating state.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_ovld_detected"></a>`enum ethtool_c33_pse_ext_substate_ovld_detected`

ovld_detected states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_OVLD_DETECTED_OVERLOAD`: Overload state

**Description**

ovld_detected is a variable indicating if the PSE output current has been
in an overload condition (see 33.2.7.6) for at least TCUT of a one-second
sliding time.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_power_not_available"></a>`enum ethtool_c33_pse_ext_substate_power_not_available`

power_not_available states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_POWER_NOT_AVAILABLE_BUDGET_EXCEEDED`: Power
  budget exceeded for the controller
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_POWER_NOT_AVAILABLE_PORT_PW_LIMIT_EXCEEDS_CONTROLLER_BUDGET`: Configured port power limit exceeded controller power budget
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_POWER_NOT_AVAILABLE_PD_REQUEST_EXCEEDS_PORT_LIMIT`: Power request from PD exceeds port limit
- `ETHTOOL_C33_PSE_EXT_SUBSTATE_POWER_NOT_AVAILABLE_HW_PW_LIMIT`: Power
  denied due to Hardware power limit

**Description**

power_not_available is a variable that is asserted in an
implementation-dependent manner when the PSE is no longer capable of
sourcing sufficient power to support the attached PD. Sufficient power
is defined by classification; see 33.2.6.

#### <a id="c-enum-ethtool_c33_pse_ext_substate_short_detected"></a>`enum ethtool_c33_pse_ext_substate_short_detected`

short_detected states functions. IEEE 802.3-2022 33.2.4.4 Variables

**Constants**

- `ETHTOOL_C33_PSE_EXT_SUBSTATE_SHORT_DETECTED_SHORT_CONDITION`: Short
  condition was detected

**Description**

short_detected is a variable indicating if the PSE output current has been
in a short circuit condition for TLIM within a sliding window (see 33.2.7.7).


When set, the optional `ETHTOOL_A_C33_PSE_AVAIL_PW_LIMIT` attribute identifies the C33 PSE power limit in mW.

When set the optional `ETHTOOL_A_C33_PSE_PW_LIMIT_RANGES` nested attribute identifies the C33 PSE power limit ranges through `ETHTOOL_A_C33_PSE_PWR_VAL_LIMIT_RANGE_MIN` and `ETHTOOL_A_C33_PSE_PWR_VAL_LIMIT_RANGE_MAX`. If the controller works with fixed classes, the min and max values will be equal.

The `ETHTOOL_A_PSE_PW_D_ID` attribute identifies the index of PSE power domain.

When set, the optional `ETHTOOL_A_PSE_PRIO_MAX` attribute identifies the PSE maximum priority value. When set, the optional `ETHTOOL_A_PSE_PRIO` attributes is used to identifies the currently configured PSE priority. For a description of PSE priority attributes, see `PSE_SET`.

<a id="rst-pse-set"></a>

## PSE_SET

Sets PSE parameters.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PODL_PSE_ADMIN_CONTROL`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Control PoDL PSE Admin state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_ADMIN_CONTROL`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Control PSE Admin state
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_C33_PSE_AVAIL_PWR_LIMIT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Control PoE PSE available power limit
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_PRIO`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Control priority of the PoE PSE
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the optional `ETHTOOL_A_PODL_PSE_ADMIN_CONTROL` attribute is used to control PoDL PSE Admin functions. This option implements `IEEE 802.3-2018` 30.15.1.2.1 acPoDLPSEAdminControl. See `ETHTOOL_A_PODL_PSE_ADMIN_STATE` for supported values.

The same goes for `ETHTOOL_A_C33_PSE_ADMIN_CONTROL` implementing `IEEE 802.3-2022` 30.9.1.2.1 acPSEAdminControl.

When set, the optional `ETHTOOL_A_C33_PSE_AVAIL_PWR_LIMIT` attribute is used to control the available power value limit for C33 PSE in milliwatts. This attribute corresponds  to the `pse_available_power` variable described in `IEEE 802.3-2022` 33.2.4.4 Variables  and `pse_avail_pwr` in 145.2.5.4 Variables, which are described in power classes.

It was decided to use milliwatts for this interface to unify it with other power monitoring interfaces, which also use milliwatts, and to align with various existing products that document power consumption in watts rather than classes. If power limit configuration based on classes is needed, the conversion can be done in user space, for example by ethtool.

When set, the optional `ETHTOOL_A_PSE_PRIO` attributes is used to control the PSE priority. Allowed priority value are between zero and the value of `ETHTOOL_A_PSE_PRIO_MAX` attribute.

A lower value indicates a higher priority, meaning that a priority value of 0 corresponds to the highest port priority. Port priority serves two functions:

> - Power-up Order: After a reset, ports are powered up in order of their priority from highest to lowest. Ports with higher priority (lower values) power up first.
>
> - Shutdown Order: When the power budget is exceeded, ports with lower priority (higher values) are turned off first.

<a id="rst-pse-ntf"></a>

## PSE_NTF

Notify PSE events.

Notification contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PSE_EVENTS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> PSE events
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the optional `ETHTOOL_A_PSE_EVENTS` attribute identifies the PSE events.


#### <a id="c-enum-ethtool_pse_event"></a>`enum ethtool_pse_event`

PSE event list for the PSE controller

**Constants**

- `ETHTOOL_PSE_EVENT_OVER_CURRENT`: PSE output current is too high
- `ETHTOOL_PSE_EVENT_OVER_TEMP`: PSE in over temperature state
- `ETHTOOL_C33_PSE_EVENT_DETECTION`: detection process occur on the PSE. IEEE
  802.3-2022 33.2.5 and 145.2.6 PSE detection of PDs. IEEE 802.3-202
  30.9.1.1.5 aPSEPowerDetectionStatus
- `ETHTOOL_C33_PSE_EVENT_CLASSIFICATION`: classification process occur on the
  PSE. IEEE 802.3-2022 33.2.6 and 145.2.8 classification of PDs mutual
  identification. IEEE 802.3-2022 30.9.1.1.8 aPSEPowerClassification.
- `ETHTOOL_C33_PSE_EVENT_DISCONNECTION`: PD has been disconnected on the PSE.
  IEEE 802.3-2022 33.3.8 and 145.3.9 PD Maintain Power Signature. IEEE
  802.3-2022 33.5.1.2.9 MPS Absent. IEEE 802.3-2022 30.9.1.1.20
  aPSEMPSAbsentCounter.
- `ETHTOOL_PSE_EVENT_OVER_BUDGET`: PSE turned off due to over budget situation
- `ETHTOOL_PSE_EVENT_SW_PW_CONTROL_ERROR`: PSE faced an error managing the
  power control from software


<a id="rst-rss-get"></a>

## RSS_GET

Get indirection table, hash key and hash function info associated with a RSS context of an interface similar to `ETHTOOL_GRSSH` ioctl request.

Request contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


request header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_START_CONTEXT`

</td>
<td>


u32

</td>
<td>


start context number (dumps)

</td>
</tr>
</tbody>
</table>

`ETHTOOL_A_RSS_CONTEXT` specifies which RSS context number to query, if not set context 0 (the main context) is queried. Dumps can be filtered by device (only listing contexts of a given netdev). Filtering single context number is not supported but `ETHTOOL_A_RSS_START_CONTEXT` can be used to start dumping context from the given number (primarily used to ignore context 0s and only dump additional contexts).

Kernel response contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


reply header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HFUNC`

</td>
<td>


u32

</td>
<td>


RSS hash func

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INDIR`

</td>
<td>


binary

</td>
<td>


Indir table bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HKEY`

</td>
<td>


binary

</td>
<td>


Hash key bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INPUT_XFRM`

</td>
<td>


u32

</td>
<td>


RSS input data transformation

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_FLOW_HASH`

</td>
<td>


nested

</td>
<td>


Header fields included in hash

</td>
</tr>
</tbody>
</table>

ETHTOOL_A_RSS_HFUNC attribute is bitmap indicating the hash function being used. Current supported options are toeplitz, xor or crc32. ETHTOOL_A_RSS_INDIR attribute returns RSS indirection table where each byte indicates queue number. ETHTOOL_A_RSS_INPUT_XFRM attribute is a bitmap indicating the type of transformation applied to the input protocol fields before given to the RSS hfunc. Current supported options are symmetric-xor and symmetric-or-xor. ETHTOOL_A_RSS_FLOW_HASH carries per-flow type bitmask of which header fields are included in the hash calculation.

<a id="rst-rss-set"></a>

## RSS_SET

Request contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


request header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HFUNC`

</td>
<td>


u32

</td>
<td>


RSS hash func

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INDIR`

</td>
<td>


binary

</td>
<td>


Indir table bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HKEY`

</td>
<td>


binary

</td>
<td>


Hash key bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INPUT_XFRM`

</td>
<td>


u32

</td>
<td>


RSS input data transformation

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_FLOW_HASH`

</td>
<td>


nested

</td>
<td>


Header fields included in hash

</td>
</tr>
</tbody>
</table>

`ETHTOOL_A_RSS_INDIR` is the minimal RSS table the user expects. Kernel and the device driver may replicate the table if its smaller than smallest table size supported by the device. For example if user requests `[0, 1]` but the device needs at least 8 entries - the real table in use will end up being `[0, 1, 0, 1, 0, 1, 0, 1]`. Most devices require the table size to be power of 2, so tables which size is not a power of 2 will likely be rejected. Using table of size 0 will reset the indirection table to the default.

<a id="rst-rss-create-act"></a>

## RSS_CREATE_ACT

Request contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


request header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HFUNC`

</td>
<td>


u32

</td>
<td>


RSS hash func

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INDIR`

</td>
<td>


binary

</td>
<td>


Indir table bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_HKEY`

</td>
<td>


binary

</td>
<td>


Hash key bytes

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_INPUT_XFRM`

</td>
<td>


u32

</td>
<td>


RSS input data transformation

</td>
</tr>
</tbody>
</table>

Kernel response contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


request header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
</tbody>
</table>

Create an additional RSS context, if `ETHTOOL_A_RSS_CONTEXT` is not specified kernel will allocate one automatically.

<a id="rst-rss-delete-act"></a>

## RSS_DELETE_ACT

Request contents:


<table>
<tbody>
<tr>
<td>


`ETHTOOL_A_RSS_HEADER`

</td>
<td>


nested

</td>
<td>


request header

</td>
</tr>
<tr>
<td>


`ETHTOOL_A_RSS_CONTEXT`

</td>
<td>


u32

</td>
<td>


context number

</td>
</tr>
</tbody>
</table>

Delete an additional RSS context.

<a id="rst-plca-get-cfg"></a>

## PLCA_GET_CFG

Gets the IEEE 802.3cg-2019 Clause 148 Physical Layer Collision Avoidance (PLCA) Reconciliation Sublayer (RS) attributes.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_VERSION`
>
> </td>
> <td>
>
>
> u16
>
> </td>
> <td>
>
>
> Supported PLCA management interface standard/version
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_ENABLED`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PLCA Admin State
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_NODE_ID`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> PLCA unique local node ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_NODE_CNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Number of PLCA nodes on the network, including the coordinator
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_TO_TMR`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Transmit Opportunity Timer value in bit-times (BT)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_BURST_CNT`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Number of additional packets the node is allowed to send within a single TO
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_BURST_TMR`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> Time to wait for the MAC to transmit a new frame before terminating the burst
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the optional `ETHTOOL_A_PLCA_VERSION` attribute indicates which standard and version the PLCA management interface complies to. When not set, the interface is vendor-specific and (possibly) supplied by the driver. The OPEN Alliance SIG specifies a standard register map for 10BASE-T1S PHYs embedding the PLCA Reconciliation Sublayer. See "10BASE-T1S PLCA Management Registers" at [https://www.opensig.org/about/specifications/](<https://www.opensig.org/about/specifications/>).

When set, the optional `ETHTOOL_A_PLCA_ENABLED` attribute indicates the administrative state of the PLCA RS. When not set, the node operates in "plain" CSMA/CD mode. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.1 aPLCAAdminState / 30.16.1.2.1 acPLCAAdminControl.

When set, the optional `ETHTOOL_A_PLCA_NODE_ID` attribute indicates the configured local node ID of the PHY. This ID determines which transmit opportunity (TO) is reserved for the node to transmit into. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.4 aPLCALocalNodeID. The valid range for this attribute is \[0 .. 255\] where 255 means "not configured".

When set, the optional `ETHTOOL_A_PLCA_NODE_CNT` attribute indicates the configured maximum number of PLCA nodes on the mixing-segment. This number determines the total number of transmit opportunities generated during a PLCA cycle. This attribute is relevant only for the PLCA coordinator, which is the node with aPLCALocalNodeID set to 0. Follower nodes ignore this setting. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.3 aPLCANodeCount. The valid range for this attribute is \[1 .. 255\].

When set, the optional `ETHTOOL_A_PLCA_TO_TMR` attribute indicates the configured value of the transmit opportunity timer in bit-times. This value must be set equal across all nodes sharing the medium for PLCA to work correctly. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.5 aPLCATransmitOpportunityTimer. The valid range for this attribute is \[0 .. 255\].

When set, the optional `ETHTOOL_A_PLCA_BURST_CNT` attribute indicates the configured number of extra packets that the node is allowed to send during a single transmit opportunity. By default, this attribute is 0, meaning that the node can only send a single frame per TO. When greater than 0, the PLCA RS keeps the TO after any transmission, waiting for the MAC to send a new frame for up to aPLCABurstTimer BTs. This can only happen a number of times per PLCA cycle up to the value of this parameter. After that, the burst is over and the normal counting of TOs resumes. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.6 aPLCAMaxBurstCount. The valid range for this attribute is \[0 .. 255\].

When set, the optional `ETHTOOL_A_PLCA_BURST_TMR` attribute indicates how many bit-times the PLCA RS waits for the MAC to initiate a new transmission when aPLCAMaxBurstCount is greater than 0. If the MAC fails to send a new frame within this time, the burst ends and the counting of TOs resumes. Otherwise, the new frame is sent as part of the current burst. This option is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.7 aPLCABurstTimer. The valid range for this attribute is \[0 .. 255\]. Although, the value should be set greater than the Inter-Frame-Gap (IFG) time of the MAC (plus some margin) for PLCA burst mode to work as intended.

<a id="rst-plca-set-cfg"></a>

## PLCA_SET_CFG

Sets PLCA RS parameters.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_ENABLED`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PLCA Admin State
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_NODE_ID`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PLCA unique local node ID
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_NODE_CNT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Number of PLCA nodes on the network, including the coordinator
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_TO_TMR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Transmit Opportunity Timer value in bit-times (BT)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_BURST_CNT`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Number of additional packets the node is allowed to send within a single TO
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_BURST_TMR`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> Time to wait for the MAC to transmit a new frame before terminating the burst
>
> </td>
> </tr>
> </tbody>
> </table>

For a description of each attribute, see `PLCA_GET_CFG`.

<a id="rst-plca-get-status"></a>

## PLCA_GET_STATUS

Gets PLCA RS status information.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PLCA_STATUS`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> PLCA RS operational status
>
> </td>
> </tr>
> </tbody>
> </table>

When set, the `ETHTOOL_A_PLCA_STATUS` attribute indicates whether the node is detecting the presence of the BEACON on the network. This flag is corresponding to `IEEE 802.3cg-2019` 30.16.1.1.2 aPLCAStatus.

<a id="rst-mm-get"></a>

## MM_GET

Retrieve 802.3 MAC Merge parameters.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_PMAC_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> set if RX of preemptible and SMD-V frames is enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_TX_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> set if TX of preemptible frames is administratively enabled (might be inactive if verification failed)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_TX_ACTIVE`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> set if TX of preemptible frames is operationally enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_TX_MIN_FRAG_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> minimum size of transmitted non-final fragments, in octets
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_RX_MIN_FRAG_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> minimum size of received non-final fragments, in octets
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_VERIFY_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> set if TX of SMD-V frames is administratively enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_VERIFY_STATUS`
>
> </td>
> <td>
>
>
> u8
>
> </td>
> <td>
>
>
> state of the verification function
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_VERIFY_TIME`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> delay between verification attempts
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `` ETHTOOL_A_MM_MAX_VERIFY_TIME` ``
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> maximum verification interval supported by device
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_STATS`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> IEEE 802.3-2018 subclause 30.14.1 oMACMergeEntity statistics counters
>
> </td>
> </tr>
> </tbody>
> </table>

The attributes are populated by the device driver through the following structure:


#### <a id="c-struct-ethtool_mm_state"></a>`struct ethtool_mm_state`

802.3 MAC merge layer state

**Definition**

```c
struct ethtool_mm_state {
    u32 verify_time;
    u32 max_verify_time;
    enum ethtool_mm_verify_status verify_status;
    bool tx_enabled;
    bool tx_active;
    bool pmac_enabled;
    bool verify_enabled;
    u32 tx_min_frag_size;
    u32 rx_min_frag_size;
};
```

**Members**

- `verify_time`: wait time between verification attempts in ms (according to clause
  30.14.1.6 aMACMergeVerifyTime)
- `max_verify_time`: maximum accepted value for the **verify_time** variable in set requests
- `verify_status`: state of the verification state machine of the MM layer (according to
  clause 30.14.1.2 aMACMergeStatusVerify)
- `tx_enabled`: set if the MM layer is administratively enabled in the TX direction
  (according to clause 30.14.1.3 aMACMergeEnableTx)
- `tx_active`: set if the MM layer is enabled in the TX direction, which makes FP
  possible (according to 30.14.1.5 aMACMergeStatusTx). This should be
  true if MM is enabled, and the verification status is either verified,
  or disabled.
- `pmac_enabled`: set if the preemptible MAC is powered on and is able to receive
  preemptible packets and respond to verification frames.
- `verify_enabled`: set if the Verify function of the MM layer (which sends SMD-V
  verification requests) is administratively enabled (regardless of
  whether it is currently in the ETHTOOL_MM_VERIFY_STATUS_DISABLED state
  or not), according to clause 30.14.1.4 aMACMergeVerifyDisableTx (but
  using positive rather than negative logic). The device should always
  respond to received SMD-V requests as long as **pmac_enabled** is set.
- `tx_min_frag_size`: the minimum size of non-final mPacket fragments that the link partner
  supports receiving, expressed in octets. Compared to the definition
  from clause 30.14.1.7 aMACMergeAddFragSize which is expressed in the
  range 0 to 3 (requiring a translation to the size in octets according
  to the formula 64 * (1 + addFragSize) - 4), a value in a continuous and
  unbounded range can be specified here.
- `rx_min_frag_size`: the minimum size of non-final mPacket fragments that this device
  supports receiving, expressed in octets.


The `ETHTOOL_A_MM_VERIFY_STATUS` will report one of the values from


#### <a id="c-enum-ethtool_mm_verify_status"></a>`enum ethtool_mm_verify_status`

status of MAC Merge Verify function

**Constants**

- `ETHTOOL_MM_VERIFY_STATUS_UNKNOWN`: verification status is unknown
- `ETHTOOL_MM_VERIFY_STATUS_INITIAL`: the 802.3 Verify State diagram is in the state INIT_VERIFICATION
- `ETHTOOL_MM_VERIFY_STATUS_VERIFYING`: the Verify State diagram is in the state VERIFICATION_IDLE,
  SEND_VERIFY or WAIT_FOR_RESPONSE
- `ETHTOOL_MM_VERIFY_STATUS_SUCCEEDED`: indicates that the Verify State diagram is in the state VERIFIED
- `ETHTOOL_MM_VERIFY_STATUS_FAILED`: the Verify State diagram is in the state VERIFY_FAIL
- `ETHTOOL_MM_VERIFY_STATUS_DISABLED`: verification of preemption operation is disabled


If `ETHTOOL_A_MM_VERIFY_ENABLED` was passed as false in the `MM_SET` command, `ETHTOOL_A_MM_VERIFY_STATUS` will report either `ETHTOOL_MM_VERIFY_STATUS_INITIAL` or `ETHTOOL_MM_VERIFY_STATUS_DISABLED`, otherwise it should report one of the other states.

It is recommended that drivers start with the pMAC disabled, and enable it upon user space request. It is also recommended that user space does not depend upon the default values from `ETHTOOL_MSG_MM_GET` requests.

`ETHTOOL_A_MM_STATS` are reported if `ETHTOOL_FLAG_STATS` was set in `ETHTOOL_A_HEADER_FLAGS`. The attribute will be empty if driver did not report any statistics. Drivers fill in the statistics in the following structure:


#### <a id="c-struct-ethtool_mm_stats"></a>`struct ethtool_mm_stats`

802.3 MAC merge layer statistics

**Definition**

```c
struct ethtool_mm_stats {
    u64 MACMergeFrameAssErrorCount;
    u64 MACMergeFrameSmdErrorCount;
    u64 MACMergeFrameAssOkCount;
    u64 MACMergeFragCountRx;
    u64 MACMergeFragCountTx;
    u64 MACMergeHoldCount;
};
```

**Members**

- `MACMergeFrameAssErrorCount`: received MAC frames with reassembly errors
- `MACMergeFrameSmdErrorCount`: received MAC frames/fragments rejected due to unknown or incorrect SMD
- `MACMergeFrameAssOkCount`: received MAC frames that were successfully reassembled and passed up
- `MACMergeFragCountRx`: number of additional correct SMD-C mPackets received due to preemption
- `MACMergeFragCountTx`: number of additional mPackets sent due to preemption
- `MACMergeHoldCount`: number of times the MM layer entered the HOLD state, which blocks
  transmission of preemptible traffic


<a id="rst-mm-set"></a>

## MM_SET

Modifies the configuration of the 802.3 MAC Merge layer.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_VERIFY_TIME`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> see MM_GET description
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_VERIFY_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> see MM_GET description
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_TX_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> see MM_GET description
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_PMAC_ENABLED`
>
> </td>
> <td>
>
>
> bool
>
> </td>
> <td>
>
>
> see MM_GET description
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MM_TX_MIN_FRAG_SIZE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> see MM_GET description
>
> </td>
> </tr>
> </tbody>
> </table>

The attributes are propagated to the driver through the following structure:


#### <a id="c-struct-ethtool_mm_cfg"></a>`struct ethtool_mm_cfg`

802.3 MAC merge layer configuration

**Definition**

```c
struct ethtool_mm_cfg {
    u32 verify_time;
    bool verify_enabled;
    bool tx_enabled;
    bool pmac_enabled;
    u32 tx_min_frag_size;
};
```

**Members**

- `verify_time`: see struct ethtool_mm_state
- `verify_enabled`: see struct ethtool_mm_state
- `tx_enabled`: see struct ethtool_mm_state
- `pmac_enabled`: see struct ethtool_mm_state
- `tx_min_frag_size`: see struct ethtool_mm_state


<a id="rst-module-fw-flash-act"></a>

## MODULE_FW_FLASH_ACT

Flashes transceiver module firmware.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_FILE_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> firmware image file name
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_PASSWORD`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> transceiver module password
>
> </td>
> </tr>
> </tbody>
> </table>

The firmware update process consists of three logical steps:

1. Downloading a firmware image to the transceiver module and validating it.

2. Running the firmware image.

3. Committing the firmware image so that it is run upon reset.

When flash command is given, those three steps are taken in that order.

This message merely schedules the update process and returns immediately without blocking. The process then runs asynchronously. Since it can take several minutes to complete, during the update process notifications are emitted from the kernel to user space updating it about the status and progress.

The `ETHTOOL_A_MODULE_FW_FLASH_FILE_NAME` attribute encodes the firmware image file name. The firmware image is downloaded to the transceiver module, validated, run and committed.

The optional `ETHTOOL_A_MODULE_FW_FLASH_PASSWORD` attribute encodes a password that might be required as part of the transceiver module firmware update process.

The firmware update process can take several minutes to complete. Therefore, during the update process notifications are emitted from the kernel to user space updating it about the status and progress.

Notification contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_STATUS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> status
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_STATUS_MSG`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> status message
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_DONE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> progress
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MODULE_FW_FLASH_TOTAL`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> total
>
> </td>
> </tr>
> </tbody>
> </table>

The `ETHTOOL_A_MODULE_FW_FLASH_STATUS` attribute encodes the current status of the firmware update process. Possible values are:


#### <a id="c-enum-ethtool_module_fw_flash_status"></a>`enum ethtool_module_fw_flash_status`

plug-in module firmware flashing status

**Constants**

- `ETHTOOL_MODULE_FW_FLASH_STATUS_STARTED`: The firmware flashing process has
  started.
- `ETHTOOL_MODULE_FW_FLASH_STATUS_IN_PROGRESS`: The firmware flashing process
  is in progress.
- `ETHTOOL_MODULE_FW_FLASH_STATUS_COMPLETED`: The firmware flashing process was
  completed successfully.
- `ETHTOOL_MODULE_FW_FLASH_STATUS_ERROR`: The firmware flashing process was
  stopped due to an error.


The `ETHTOOL_A_MODULE_FW_FLASH_STATUS_MSG` attribute encodes a status message string.

The `ETHTOOL_A_MODULE_FW_FLASH_DONE` and `ETHTOOL_A_MODULE_FW_FLASH_TOTAL` attributes encode the completed and total amount of work, respectively.

<a id="rst-phy-get"></a>

## PHY_GET

Retrieve information about a given Ethernet PHY sitting on the link. The DO operation returns all available information about dev-&gt;phydev. User can also specify a PHY_INDEX, in which case the DO request returns information about that specific PHY.

As there can be more than one PHY, the DUMP operation can be used to list the PHYs present on a given interface, by passing an interface index or name in the dump request.

For more information, refer to [PHY link topology](</kernel/internals/networking/phy-link-topology.md#rst-phy-link-topology>)

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> the phy's unique index, that can be used for phy-specific requests
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_DRVNAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> the phy driver name
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> the phy device name
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_UPSTREAM_TYPE`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> the type of device this phy is connected to
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_UPSTREAM_INDEX`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> the PHY index of the upstream PHY
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_UPSTREAM_SFP_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> if this PHY is connected to its parent PHY through an SFP bus, the name of this sfp bus
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_PHY_DOWNSTREAM_SFP_NAME`
>
> </td>
> <td>
>
>
> string
>
> </td>
> <td>
>
>
> if the phy controls an sfp bus, the name of the sfp bus
>
> </td>
> </tr>
> </tbody>
> </table>

When `ETHTOOL_A_PHY_UPSTREAM_TYPE` is PHY_UPSTREAM_PHY, the PHY's parent is another PHY.

<a id="rst-tsconfig-get"></a>

## TSCONFIG_GET

Retrieves the information about the current hardware timestamping source and configuration.

It is similar to the deprecated `SIOCGHWTSTAMP` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_PROVIDER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> PTP hw clock provider
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_TX_TYPES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Tx type
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_RX_FILTERS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Rx filter
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_FLAGS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> hwtstamp flags
>
> </td>
> </tr>
> </tbody>
> </table>

When set the `ETHTOOL_A_TSCONFIG_HWTSTAMP_PROVIDER` attribute identifies the source of the hw timestamping provider. It is composed by `ETHTOOL_A_TS_HWTSTAMP_PROVIDER_INDEX` attribute which describe the index of the PTP device and `ETHTOOL_A_TS_HWTSTAMP_PROVIDER_QUALIFIER` which describe the qualifier of the timestamp.

When set the `ETHTOOL_A_TSCONFIG_TX_TYPES`, `ETHTOOL_A_TSCONFIG_RX_FILTERS` and the `ETHTOOL_A_TSCONFIG_HWTSTAMP_FLAGS` attributes identify the Tx type, the Rx filter and the flags configured for the current hw timestamping provider. The attributes are propagated to the driver through the following structure:


#### <a id="c-struct-kernel_hwtstamp_config"></a>`struct kernel_hwtstamp_config`

Kernel copy of struct hwtstamp_config

**Definition**

```c
struct kernel_hwtstamp_config {
    int flags;
    int tx_type;
    int rx_filter;
    struct ifreq *ifr;
    bool copied_to_user;
    enum hwtstamp_source source;
    enum hwtstamp_provider_qualifier qualifier;
};
```

**Members**

- `flags`: see struct hwtstamp_config
- `tx_type`: see struct hwtstamp_config
- `rx_filter`: see struct hwtstamp_config
- `ifr`: pointer to ifreq structure from the original ioctl request, to pass to
  a legacy implementation of a lower driver
- `copied_to_user`: request was passed to a legacy implementation which already
  copied the ioctl request back to user space
- `source`: indication whether timestamps should come from the netdev or from
  an attached phylib PHY
- `qualifier`: qualifier of the hwtstamp provider

**Description**

Prefer using this structure for in-kernel processing of hardware
timestamping configuration, over the inextensible struct hwtstamp_config
exposed to the `SIOCGHWTSTAMP` and `SIOCSHWTSTAMP` ioctl UAPI.


<a id="rst-tsconfig-set"></a>

## TSCONFIG_SET

Set the information about the current hardware timestamping source and configuration.

It is similar to the deprecated `SIOCSHWTSTAMP` ioctl request.

Request contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_PROVIDER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> PTP hw clock provider
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_TX_TYPES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Tx type
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_RX_FILTERS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Rx filter
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_FLAGS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> hwtstamp flags
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel response contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_PROVIDER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> PTP hw clock provider
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_TX_TYPES`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Tx type
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_RX_FILTERS`
>
> </td>
> <td>
>
>
> bitset
>
> </td>
> <td>
>
>
> hwtstamp Rx filter
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_TSCONFIG_HWTSTAMP_FLAGS`
>
> </td>
> <td>
>
>
> u32
>
> </td>
> <td>
>
>
> hwtstamp flags
>
> </td>
> </tr>
> </tbody>
> </table>

For a description of each attribute, see `TSCONFIG_GET`.

<a id="rst-mse-get"></a>

## MSE_GET

Retrieves detailed Mean Square Error (MSE) diagnostic information from the PHY.

Request Contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> request header
>
> </td>
> </tr>
> </tbody>
> </table>

Kernel Response Contents:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_HEADER`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> reply header
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CAPABILITIES`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> capability/scale info for MSE measurements
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CHANNEL_A`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for Channel A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CHANNEL_B`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for Channel B
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CHANNEL_C`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for Channel C
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CHANNEL_D`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for Channel D
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_WORST_CHANNEL`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for worst channel
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_LINK`
>
> </td>
> <td>
>
>
> nested
>
> </td>
> <td>
>
>
> snapshot for link-wide aggregate
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-mse-capabilities"></a>

### MSE Capabilities

This nested attribute reports the capability / scaling properties used to interpret snapshot values.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CAPABILITIES_MAX_AVERAGE_MSE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> max avg_mse scale
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CAPABILITIES_MAX_PEAK_MSE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> max peak_mse scale
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CAPABILITIES_REFRESH_RATE_PS`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> sample rate (picoseconds)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_CAPABILITIES_NUM_SYMBOLS`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> symbols per HW sample
>
> </td>
> </tr>
> </tbody>
> </table>

The max-average/peak fields are included only if the corresponding metric is supported by the PHY. Their absence indicates that the metric is not available.

See `struct phy_mse_capability` kernel documentation in `include/linux/phy.h`.

<a id="rst-mse-snapshot"></a>

### MSE Snapshot

Each per-channel nest contains an atomic snapshot of MSE values for that selector (channel A/B/C/D, worst channel, or link).

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_SNAPSHOT_AVERAGE_MSE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> average MSE value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_SNAPSHOT_PEAK_MSE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> current peak MSE
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_A_MSE_SNAPSHOT_WORST_PEAK_MSE`
>
> </td>
> <td>
>
>
> uint
>
> </td>
> <td>
>
>
> worst-case peak MSE
>
> </td>
> </tr>
> </tbody>
> </table>

Within each channel nest, only the metrics supported by the PHY will be present.

See `struct phy_mse_snapshot` kernel documentation in `include/linux/phy.h`.

<a id="rst-request-translation"></a>

## Request translation

The following table maps ioctl commands to netlink commands providing their functionality. Entries with "n/a" in right column are commands which do not have their netlink replacement yet. Entries which "n/a" in the left column are netlink only.

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> ioctl command
>
> </th>
> <th>
>
>
> netlink command
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> `ETHTOOL_GSET`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_GET` `ETHTOOL_MSG_LINKMODES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SSET`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_SET` `ETHTOOL_MSG_LINKMODES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GDRVINFO`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GREGS`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GWOL`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_WOL_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SWOL`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_WOL_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GMSGLVL`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SMSGLVL`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_DEBUG_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_NWAY_RST`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GLINK`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_LINKSTATE_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GEEPROM`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SEEPROM`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GCOALESCE`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SCOALESCE`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_COALESCE_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRINGPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRINGPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RINGS_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GPAUSEPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SPAUSEPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PAUSE_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXCSUM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXCSUM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GTXCSUM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_STXCSUM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GSG`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SSG`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_TEST`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GSTRINGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_STRSET_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_PHYS_ID`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GSTATS`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GTSO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_STSO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GPERMADDR`
>
> </td>
> <td>
>
>
> rtnetlink `RTM_GETLINK`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GUFO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SUFO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GGSO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SGSO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GFLAGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SFLAGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GPFLAGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SPFLAGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PRIVFLAGS_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXFH`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RSS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXFH`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RSS_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GGRO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SGRO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXRINGS`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXCLSRLCNT`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXCLSRULE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXCLSRLALL`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXCLSRLDEL`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXCLSRLINS`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_FLASHDEV`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_RESET`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXNTUPLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXNTUPLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GSSET_INFO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_STRSET_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRXFHINDIR`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RSS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRXFHINDIR`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RSS_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GFEATURES`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SFEATURES`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEATURES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GCHANNELS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SCHANNELS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_CHANNELS_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SET_DUMP`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GET_DUMP_FLAG`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GET_DUMP_DATA`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GET_TS_INFO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_TSINFO_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GMODULEINFO`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_EEPROM_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GMODULEEEPROM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_EEPROM_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GEEE`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_EEE_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SEEE`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_EEE_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GRSSH`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_RSS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SRSSH`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GTUNABLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_STUNABLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GPHYSTATS`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_PERQUEUE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GLINKSETTINGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_GET` `ETHTOOL_MSG_LINKMODES_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SLINKSETTINGS`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_LINKINFO_SET` `ETHTOOL_MSG_LINKMODES_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_PHY_GTUNABLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_PHY_STUNABLE`
>
> </td>
> <td>
>
>
> n/a
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_GFECPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEC_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `ETHTOOL_SFECPARAM`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_FEC_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_ACT`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_CABLE_TEST_TDR_ACT`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_TUNNEL_INFO_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PHC_VCLOCKS_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_CFG`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_SET_CFG`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PLCA_GET_STATUS`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MM_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MM_SET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_MODULE_FW_FLASH_ACT`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> n/a
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_PHY_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `SIOCGHWTSTAMP`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_GET`
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `SIOCSHWTSTAMP`
>
> </td>
> <td>
>
>
> `ETHTOOL_MSG_TSCONFIG_SET`
>
> </td>
> </tr>
> </tbody>
> </table>

---

# FAILOVER

_Peios Kernel / Internals / Networking_

> The failover module provides a generic interface for paravirtual drivers to register a netdev and a set of ops with a failover instance. The ops are used as event handlers that get called to handle netdev register/ unregister/link…

<a id="rst-failover"></a>

<a id="rst-overview"></a>

## Overview

<!-- SPDX-License-Identifier: GPL-2.0 -->

The failover module provides a generic interface for paravirtual drivers to register a netdev and a set of ops with a failover instance. The ops are used as event handlers that get called to handle netdev register/ unregister/link change/name change events on slave pci ethernet devices with the same mac address as the failover netdev.

This enables paravirtual drivers to use a VF as an accelerated low latency datapath. It also allows live migration of VMs with direct attached VFs by failing over to the paravirtual datapath when the VF is unplugged.

---

# LC-trie implementation notes

_Peios Kernel / Internals / Networking_

> An end node with data. This has a copy of the relevant key, along with 'hlist' with routing table entries sorted by prefix length. See struct leaf and struct leaf_info.

<a id="rst-lc-trie-implementation-notes"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-node-types"></a>

## Node types

- **leaf**

  An end node with data. This has a copy of the relevant key, along with 'hlist' with routing table entries sorted by prefix length. See struct leaf and struct leaf_info.

- **trie node or tnode**

  An internal node, holding an array of child (leaf or tnode) pointers, indexed through a subset of the key. See Level Compression.

<a id="rst-a-few-concepts-explained"></a>

## A few concepts explained

- **Bits (tnode)**

  The number of bits in the key segment used for indexing into the child array - the "child index". See Level Compression.

- **Pos (tnode)**

  The position (in the key) of the key segment used for indexing into the child array. See Path Compression.

- **Path Compression / skipped bits**

  Any given tnode is linked to from the child array of its parent, using a segment of the key specified by the parent's "pos" and "bits" In certain cases, this tnode's own "pos" will not be immediately adjacent to the parent (pos+bits), but there will be some bits in the key skipped over because they represent a single path with no deviations. These "skipped bits" constitute Path Compression. Note that the search algorithm will simply skip over these bits when searching, making it necessary to save the keys in the leaves to verify that they actually do match the key we are searching for.

- **Level Compression / child arrays**

  the trie is kept level balanced moving, under certain conditions, the children of a full child (see "full_children") up one level, so that instead of a pure binary tree, each internal node ("tnode") may contain an arbitrarily large array of links to several children. Conversely, a tnode with a mostly empty child array (see empty_children) may be "halved", having some of its children moved downwards one level, in order to avoid ever-increasing child arrays.

- **empty_children**

  the number of positions in the child array of a given tnode that are NULL.

- **full_children**

  the number of children of a given tnode that aren't path compressed. (in other words, they aren't NULL or leaves and their "pos" is equal to this tnode's "pos"+"bits").

  (The word "full" here is used more in the sense of "complete" than as the opposite of "empty", which might be a tad confusing.)

<a id="rst-comments"></a>

## Comments

We have tried to keep the structure of the code as close to fib_hash as possible to allow verification and help up reviewing.

- **fib_find_node()**

  A good start for understanding this code. This function implements a straightforward trie lookup.

- **fib_insert_node()**

  Inserts a new leaf node in the trie. This is bit more complicated than fib_find_node(). Inserting a new node means we might have to run the level compression algorithm on part of the trie.

- **trie_leaf_remove()**

  Looks up a key, deletes it and runs the level compression algorithm.

- **trie_rebalance()**

  The key function for the dynamic trie after any change in the trie it is run to optimize and reorganize. It will walk the trie upwards towards the root from a given tnode, doing a resize() at each step to implement level compression.

- **resize()**

  Analyzes a tnode and optimizes the child array size by either inflating or shrinking it repeatedly until it fulfills the criteria for optimal level compression. This part follows the original paper pretty closely and there may be some room for experimentation here.

- **inflate()**

  Doubles the size of the child array within a tnode. Used by resize().

- **halve()**

  Halves the size of the child array within a tnode - the inverse of inflate(). Used by resize();

- **fn_trie_insert(), fn_trie_delete(), fn_trie_select_default()**

  The route manipulation functions. Should conform pretty closely to the corresponding functions in fib_hash.

- **fn_trie_flush()**

  This walks the full trie (using nextleaf()) and searches for empty leaves which have to be removed.

- **fn_trie_dump()**

  Dumps the routing table ordered by prefix length. This is somewhat slower than the corresponding fib_hash function, as we have to walk the entire trie for each prefix length. In comparison, fib_hash is organized as one "zone"/hash per prefix length.

<a id="rst-locking"></a>

## Locking

fib_lock is used for an RW-lock in the same way that this is done in fib_hash. However, the functions are somewhat separated for other possible locking scenarios. It might conceivably be possible to run trie_rebalance via RCU to avoid read_lock in the fn_trie_lookup() function.

<a id="rst-main-lookup-mechanism"></a>

## Main lookup mechanism

fn_trie_lookup() is the main lookup function.

The lookup is in its simplest form just like fib_find_node(). We descend the trie, key segment by key segment, until we find a leaf. check_leaf() does the fib_semantic_match in the leaf's sorted prefix hlist.

If we find a match, we are done.

If we don't find a match, we enter prefix matching mode. The prefix length, starting out at the same as the key length, is reduced one step at a time, and we backtrack upwards through the trie trying to find a longest matching prefix. The goal is always to reach a leaf and get a positive result from the fib_semantic_match mechanism.

Inside each tnode, the search for longest matching prefix consists of searching through the child array, chopping off (zeroing) the least significant "1" of the child index until we find a match or the child index consists of nothing but zeros.

At this point we backtrack (t-&gt;stats.backtrack++) up the trie, continuing to chop off part of the key in order to find the longest matching prefix.

At this point we will repeatedly descend subtries to look for a match, and there are some optimizations available that can provide us with "shortcuts" to avoid descending into dead ends. Look for "HL_OPTIMIZE" sections in the code.

To alleviate any doubts about the correctness of the route selection process, a new netlink operation has been added. Look for NETLINK_FIB_LOOKUP, which gives userland access to fib_lookup().

---

# Linux Socket Filtering aka Berkeley Packet Filter (BPF)

_Peios Kernel / Internals / Networking_

> Socket filtering, BPF mechanics and the configured Peios JIT and policy boundaries.

<a id="rst-linux-socket-filtering-aka-berkeley-packet-filter-bpf"></a>
<a id="rst-networking-filter"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-notice"></a>

## Notice

This file used to document the eBPF format and mechanisms even when not related to socket filtering.  The ../bpf/index.rst has more details on eBPF.

<a id="rst-introduction"></a>

## Introduction

Linux Socket Filtering (LSF) is derived from the Berkeley Packet Filter. Though there are some distinct differences between the BSD and Linux Kernel filtering, but when we speak of BPF or LSF in Linux context, we mean the very same mechanism of filtering in the Linux kernel.

BPF allows a user-space program to attach a filter onto any socket and allow or disallow certain types of data to come through the socket. LSF follows exactly the same filter code structure as BSD's BPF, so referring to the BSD bpf.4 manpage is very helpful in creating filters.

On Linux, BPF is much simpler than on BSD. One does not have to worry about devices or anything like that. You simply create your filter code, send it to the kernel via the SO_ATTACH_FILTER option and if your filter code passes the kernel check on it, you then immediately begin filtering data on that socket.

You can also detach filters from your socket via the SO_DETACH_FILTER option. This will probably not be used much since when you close a socket that has a filter on it the filter is automagically removed. The other less common case may be adding a different filter on the same socket where you had another filter that is still running: the kernel takes care of removing the old one and placing your new one in its place, assuming your filter has passed the checks, otherwise if it fails the old filter will remain on that socket.

SO_LOCK_FILTER option allows to lock the filter attached to a socket. Once locked, the filter cannot be removed, replaced or unlocked through these socket options. A service can arrange the filter before handing off a socket, but reducing native authority requires a real token restriction: a successful Unix-ID setter does not demonstrate that privileges were dropped in Peios.

The biggest user of this construct might be libpcap. Issuing a high-level filter command like `tcpdump -i em1 port 22` passes through the libpcap internal compiler that generates a structure that can eventually be loaded via SO_ATTACH_FILTER to the kernel. `tcpdump -i em1 port 22 -ddd` displays what is being placed into this structure.

Although we were only speaking about sockets here, BPF in Linux is used in many more places. Upstream includes xt_bpf for netfilter (disabled in the Peios profile), cls_bpf in the kernel qdisc layer, SECCOMP-BPF (SECure COMPuting <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)), and lots of other places such as team driver, PTP code, etc where BPF is being used.

<a id="rst-footnote-1"></a>



**[1]** [Documentation/userspace-api/seccomp_filter.rst](/kernel/userspace/userspace-api/security/seccomp-filter.md)

Original BPF paper:

Steven McCanne and Van Jacobson. 1993. The BSD packet filter: a new architecture for user-level packet capture. In Proceedings of the USENIX Winter 1993 Conference Proceedings on USENIX Winter 1993 Conference Proceedings (USENIX'93). USENIX Association, Berkeley, CA, USA, 2-2. \[[http://www.tcpdump.org/papers/bpf-usenix93.pdf](<http://www.tcpdump.org/papers/bpf-usenix93.pdf>)\]

<a id="rst-structure"></a>

## Structure

User space applications include &lt;linux/filter.h&gt; which contains the following relevant structures:



```text
struct sock_filter {    /* Filter block */
        __u16   code;   /* Actual filter code */
        __u8    jt;     /* Jump true */
        __u8    jf;     /* Jump false */
        __u32   k;      /* Generic multiuse field */
};
```

Such a structure is assembled as an array of 4-tuples, that contains a code, jt, jf and k value. jt and jf are jump offsets and k a generic value to be used for a provided code:



```text
struct sock_fprog {                     /* Required for SO_ATTACH_FILTER. */
        unsigned short             len; /* Number of filter blocks */
        struct sock_filter __user *filter;
};
```

For socket filtering, a pointer to this structure (as shown in follow-up example) is being passed to the kernel through setsockopt(2).

<a id="rst-example"></a>

## Example



```text
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <linux/if_ether.h>
/* ... */

/* From the example above: tcpdump -i em1 port 22 -dd */
struct sock_filter code[] = {
        { 0x28,  0,  0, 0x0000000c },
        { 0x15,  0,  8, 0x000086dd },
        { 0x30,  0,  0, 0x00000014 },
        { 0x15,  2,  0, 0x00000084 },
        { 0x15,  1,  0, 0x00000006 },
        { 0x15,  0, 17, 0x00000011 },
        { 0x28,  0,  0, 0x00000036 },
        { 0x15, 14,  0, 0x00000016 },
        { 0x28,  0,  0, 0x00000038 },
        { 0x15, 12, 13, 0x00000016 },
        { 0x15,  0, 12, 0x00000800 },
        { 0x30,  0,  0, 0x00000017 },
        { 0x15,  2,  0, 0x00000084 },
        { 0x15,  1,  0, 0x00000006 },
        { 0x15,  0,  8, 0x00000011 },
        { 0x28,  0,  0, 0x00000014 },
        { 0x45,  6,  0, 0x00001fff },
        { 0xb1,  0,  0, 0x0000000e },
        { 0x48,  0,  0, 0x0000000e },
        { 0x15,  2,  0, 0x00000016 },
        { 0x48,  0,  0, 0x00000010 },
        { 0x15,  0,  1, 0x00000016 },
        { 0x06,  0,  0, 0x0000ffff },
        { 0x06,  0,  0, 0x00000000 },
};

struct sock_fprog bpf = {
        .len = ARRAY_SIZE(code),
        .filter = code,
};

sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sock < 0)
        /* ... bail out ... */

ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
if (ret < 0)
        /* ... bail out ... */

/* ... */
close(sock);
```

The above example code attaches a socket filter for a PF_PACKET socket in order to let all IPv4/IPv6 packets with port 22 pass. The rest will be dropped for this socket.

The setsockopt(2) call to SO_DETACH_FILTER doesn't need any arguments and SO_LOCK_FILTER for preventing the filter to be detached, takes an integer value with 0 or 1.

Note that socket filters are not restricted to PF_PACKET sockets only, but can also be used on other socket families.

Summary of system calls:

> - setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &amp;val, sizeof(val));
>
> - setsockopt(sockfd, SOL_SOCKET, SO_DETACH_FILTER, &amp;val, sizeof(val));
>
> - setsockopt(sockfd, SOL_SOCKET, SO_LOCK_FILTER,   &amp;val, sizeof(val));

Normally, most use cases for socket filtering on packet sockets will be covered by libpcap in high-level syntax, so as an application developer you should stick to that. libpcap wraps its own layer around all that.

Unless i) using/linking to libpcap is not an option, ii) the required BPF filters use Linux extensions that are not supported by libpcap's compiler, iii) a filter might be more complex and not cleanly implementable with libpcap's compiler, or iv) particular filter codes should be optimized differently than libpcap's internal compiler does; then in such cases writing such a filter "by hand" can be of an alternative. For example, xt_bpf and cls_bpf users might have requirements that could result in more complex filter code, or one that cannot be expressed with libpcap (e.g. different return codes for various code paths). Moreover, BPF JIT implementors may wish to manually write test cases and thus need low-level access to BPF code as well.

<a id="rst-bpf-engine-and-instruction-set"></a>

## BPF engine and instruction set

Under tools/bpf/ there's a small helper tool called bpf_asm which can be used to write low-level filters for example scenarios mentioned in the previous section. Asm-like syntax mentioned here has been implemented in bpf_asm and will be used for further explanations (instead of dealing with less readable opcodes directly, principles are the same). The syntax is closely modelled after Steven McCanne's and Van Jacobson's BPF paper.

The BPF architecture consists of the following basic elements:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Element
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> A
>
> </td>
> <td>
>
>
> 32 bit wide accumulator
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> X
>
> </td>
> <td>
>
>
> 32 bit wide X register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> M\[\]
>
> </td>
> <td>
>
>
> 16 x 32 bit wide misc registers aka "scratch memory store", addressable from 0 to 15
>
> </td>
> </tr>
> </tbody>
> </table>

A program, that is translated by bpf_asm into "opcodes" is an array that consists of the following elements (as already mentioned):



```text
op:16, jt:8, jf:8, k:32
```

The element op is a 16 bit wide opcode that has a particular instruction encoded. jt and jf are two 8 bit wide jump targets, one for condition "jump if true", the other one "jump if false". Eventually, element k contains a miscellaneous argument that can be interpreted in different ways depending on the given instruction in op.

The instruction set consists of load, store, branch, alu, miscellaneous and return instructions that are also represented in bpf_asm syntax. This table lists all bpf_asm instructions available resp. what their underlying opcodes as defined in linux/filter.h stand for:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Instruction
>
> </th>
> <th>
>
>
> Addressing mode
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> ld
>
> </td>
> <td>
>
>
> 1, 2, 3, 4, 12
>
> </td>
> <td>
>
>
> Load word into A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldi
>
> </td>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> Load word into A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldh
>
> </td>
> <td>
>
>
> 1, 2
>
> </td>
> <td>
>
>
> Load half-word into A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldb
>
> </td>
> <td>
>
>
> 1, 2
>
> </td>
> <td>
>
>
> Load byte into A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldx
>
> </td>
> <td>
>
>
> 3, 4, 5, 12
>
> </td>
> <td>
>
>
> Load word into X
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldxi
>
> </td>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> Load word into X
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ldxb
>
> </td>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> Load byte into X
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> st
>
> </td>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> Store A into M\[\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> stx
>
> </td>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> Store X into M\[\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jmp
>
> </td>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> Jump to label
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ja
>
> </td>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> Jump to label
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jeq
>
> </td>
> <td>
>
>
> 7, 8, 9, 10
>
> </td>
> <td>
>
>
> Jump on A == &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jneq
>
> </td>
> <td>
>
>
> 9, 10
>
> </td>
> <td>
>
>
> Jump on A \!= &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jne
>
> </td>
> <td>
>
>
> 9, 10
>
> </td>
> <td>
>
>
> Jump on A \!= &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jlt
>
> </td>
> <td>
>
>
> 9, 10
>
> </td>
> <td>
>
>
> Jump on A &lt;  &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jle
>
> </td>
> <td>
>
>
> 9, 10
>
> </td>
> <td>
>
>
> Jump on A &lt;= &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jgt
>
> </td>
> <td>
>
>
> 7, 8, 9, 10
>
> </td>
> <td>
>
>
> Jump on A &gt;  &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jge
>
> </td>
> <td>
>
>
> 7, 8, 9, 10
>
> </td>
> <td>
>
>
> Jump on A &gt;= &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> jset
>
> </td>
> <td>
>
>
> 7, 8, 9, 10
>
> </td>
> <td>
>
>
> Jump on A &amp;  &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> add
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A + &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> sub
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A - &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mul
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A \* &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> div
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A / &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mod
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A % &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> neg
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> \!A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> and
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A &amp; &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> or
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A \| &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> xor
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A ^ &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> lsh
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A &lt;&lt; &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rsh
>
> </td>
> <td>
>
>
> 0, 4
>
> </td>
> <td>
>
>
> A &gt;&gt; &lt;x&gt;
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> tax
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Copy A into X
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> txa
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
> Copy X into A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ret
>
> </td>
> <td>
>
>
> 4, 11
>
> </td>
> <td>
>
>
> Return
>
> </td>
> </tr>
> </tbody>
> </table>

The next table shows addressing formats from the 2nd column:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Addressing mode
>
> </th>
> <th>
>
>
> Syntax
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> x/%x
>
> </td>
> <td>
>
>
> Register X
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> \[k\]
>
> </td>
> <td>
>
>
> BHW at byte offset k in the packet
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> \[x + k\]
>
> </td>
> <td>
>
>
> BHW at the offset X + k in the packet
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> M\[k\]
>
> </td>
> <td>
>
>
> Word at offset k in M\[\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> \#k
>
> </td>
> <td>
>
>
> Literal value stored in k
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> 4\*(\[k\]&amp;0xf)
>
> </td>
> <td>
>
>
> Lower nibble \* 4 at byte offset k in the packet
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> L
>
> </td>
> <td>
>
>
> Jump label L
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 7
>
> </td>
> <td>
>
>
> \#k,Lt,Lf
>
> </td>
> <td>
>
>
> Jump to Lt if true, otherwise jump to Lf
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 8
>
> </td>
> <td>
>
>
> x/%x,Lt,Lf
>
> </td>
> <td>
>
>
> Jump to Lt if true, otherwise jump to Lf
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 9
>
> </td>
> <td>
>
>
> \#k,Lt
>
> </td>
> <td>
>
>
> Jump to Lt if predicate is true
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 10
>
> </td>
> <td>
>
>
> x/%x,Lt
>
> </td>
> <td>
>
>
> Jump to Lt if predicate is true
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> a/%a
>
> </td>
> <td>
>
>
> Accumulator A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 12
>
> </td>
> <td>
>
>
> extension
>
> </td>
> <td>
>
>
> BPF extension
>
> </td>
> </tr>
> </tbody>
> </table>

The Linux kernel also has a couple of BPF extensions that are used along with the class of load instructions by "overloading" the k argument with a negative offset + a particular extension offset. The result of such BPF extensions are loaded into A.

Possible BPF extensions are shown in the following table:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Extension
>
> </th>
> <th>
>
>
> Description
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> len
>
> </td>
> <td>
>
>
> skb-&gt;len
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> proto
>
> </td>
> <td>
>
>
> skb-&gt;protocol
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> type
>
> </td>
> <td>
>
>
> skb-&gt;pkt_type
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> poff
>
> </td>
> <td>
>
>
> Payload start offset
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ifidx
>
> </td>
> <td>
>
>
> skb-&gt;dev-&gt;ifindex
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nla
>
> </td>
> <td>
>
>
> Netlink attribute of type X with offset A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> nlan
>
> </td>
> <td>
>
>
> Nested Netlink attribute of type X with offset A
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> mark
>
> </td>
> <td>
>
>
> skb-&gt;mark
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> queue
>
> </td>
> <td>
>
>
> skb-&gt;queue_mapping
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> hatype
>
> </td>
> <td>
>
>
> skb-&gt;dev-&gt;type
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rxhash
>
> </td>
> <td>
>
>
> skb-&gt;hash
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cpu
>
> </td>
> <td>
>
>
> raw_smp_processor_id()
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vlan_tci
>
> </td>
> <td>
>
>
> skb_vlan_tag_get(skb)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vlan_avail
>
> </td>
> <td>
>
>
> skb_vlan_tag_present(skb)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> vlan_tpid
>
> </td>
> <td>
>
>
> skb-&gt;vlan_proto
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> rand
>
> </td>
> <td>
>
>
> get_random_u32()
>
> </td>
> </tr>
> </tbody>
> </table>

These extensions can also be prefixed with '\#'. Examples for low-level BPF:

**ARP packets**:



```text
ldh [12]
jne #0x806, drop
ret #-1
drop: ret #0
```

**IPv4 TCP packets**:



```text
ldh [12]
jne #0x800, drop
ldb [23]
jneq #6, drop
ret #-1
drop: ret #0
```

**icmp random packet sampling, 1 in 4**:



```text
ldh [12]
jne #0x800, drop
ldb [23]
jneq #1, drop
# get a random uint32 number
ld rand
mod #4
jneq #1, drop
ret #-1
drop: ret #0
```

**SECCOMP filter example**:



```text
ld [4]                  /* offsetof(struct seccomp_data, arch) */
jne #0xc000003e, bad    /* AUDIT_ARCH_X86_64 */
ld [0]                  /* offsetof(struct seccomp_data, nr) */
jeq #15, good           /* __NR_rt_sigreturn */
jeq #231, good          /* __NR_exit_group */
jeq #60, good           /* __NR_exit */
jeq #0, good            /* __NR_read */
jeq #1, good            /* __NR_write */
jeq #5, good            /* __NR_fstat */
jeq #9, good            /* __NR_mmap */
jeq #14, good           /* __NR_rt_sigprocmask */
jeq #13, good           /* __NR_rt_sigaction */
jeq #35, good           /* __NR_nanosleep */
bad: ret #0             /* SECCOMP_RET_KILL_THREAD */
good: ret #0x7fff0000   /* SECCOMP_RET_ALLOW */
```

Examples for low-level BPF extension:

**Packet for interface index 13**:



```text
ld ifidx
jneq #13, drop
ret #-1
drop: ret #0
```

**(Accelerated) VLAN w/ id 10**:



```text
ld vlan_tci
jneq #10, drop
ret #-1
drop: ret #0
```

The above example code can be placed into a file (here called "foo"), and then be passed to the bpf_asm tool for generating opcodes, output that xt_bpf and cls_bpf understands and can directly be loaded with. Example with above ARP code:



```text
$ ./bpf_asm foo
4,40 0 0 12,21 0 1 2054,6 0 0 4294967295,6 0 0 0,
```

In copy and paste C-like output:



```text
$ ./bpf_asm -c foo
{ 0x28,  0,  0, 0x0000000c },
{ 0x15,  0,  1, 0x00000806 },
{ 0x06,  0,  0, 0xffffffff },
{ 0x06,  0,  0, 0000000000 },
```

In particular, as usage with xt_bpf or cls_bpf can result in more complex BPF filters that might not be obvious at first, it's good to test filters before attaching to a live system. For that purpose, there's a small tool called bpf_dbg under tools/bpf/ in the kernel source directory. This debugger allows for testing BPF filters against given pcap files, single stepping through the BPF code on the pcap's packets and to do BPF machine register dumps.

Starting bpf_dbg is trivial and just requires issuing:



```text
# ./bpf_dbg
```

In case input and output do not equal stdin/stdout, bpf_dbg takes an alternative stdin source as a first argument, and an alternative stdout sink as a second one, e.g. `./bpf_dbg test_in.txt test_out.txt`.

Other than that, a particular libreadline configuration can be set via file "\~/.bpf_dbg_init" and the command history is stored in the file "\~/.bpf_dbg_history".

Interaction in bpf_dbg happens through a shell that also has auto-completion support (follow-up example commands starting with '&gt;' denote bpf_dbg shell). The usual workflow would be to ...

- load bpf 6,40 0 0 12,21 0 3 2048,48 0 0 23,21 0 1 1,6 0 0 65535,6 0 0 0 Loads a BPF filter from standard output of bpf_asm, or transformed via e.g. `tcpdump -iem1 -ddd port 22 | tr '\n' ','`. Note that for JIT debugging (next section), this command creates a temporary socket and loads the BPF code into the kernel. Thus, this will also be useful for JIT developers.

- load pcap foo.pcap

  Loads standard tcpdump pcap file.

- run \[&lt;n&gt;\]

- **bpf passes:1 fails:9**

  Runs through all packets from a pcap to account how many passes and fails the filter will generate. A limit of packets to traverse can be given.

- disassemble:



  ```text
  l0:     ldh [12]
  l1:     jeq #0x800, l2, l5
  l2:     ldb [23]
  l3:     jeq #0x1, l4, l5
  l4:     ret #0xffff
  l5:     ret #0
  ```

  Prints out BPF code disassembly.

- dump:



  ```text
  /* { op, jt, jf, k }, */
  { 0x28,  0,  0, 0x0000000c },
  { 0x15,  0,  3, 0x00000800 },
  { 0x30,  0,  0, 0x00000017 },
  { 0x15,  0,  1, 0x00000001 },
  { 0x06,  0,  0, 0x0000ffff },
  { 0x06,  0,  0, 0000000000 },
  ```

  Prints out C-style BPF code dump.

- breakpoint 0:



  ```text
  breakpoint at: l0:      ldh [12]
  ```

- breakpoint 1:



  ```text
  breakpoint at: l1:      jeq #0x800, l2, l5
  ```

  ...

  Sets breakpoints at particular BPF instructions. Issuing a `run` command will walk through the pcap file continuing from the current packet and break when a breakpoint is being hit (another `run` will continue from the currently active breakpoint executing next instructions):

  - run:



    ```text
    -- register dump --
    pc:       [0]                       <-- program counter
    code:     [40] jt[0] jf[0] k[12]    <-- plain BPF code of current instruction
    curr:     l0:   ldh [12]              <-- disassembly of current instruction
    A:        [00000000][0]             <-- content of A (hex, decimal)
    X:        [00000000][0]             <-- content of X (hex, decimal)
    M[0,15]:  [00000000][0]             <-- folded content of M (hex, decimal)
    -- packet dump --                   <-- Current packet from pcap (hex)
    len: 42
        0: 00 19 cb 55 55 a4 00 14 a4 43 78 69 08 06 00 01
    16: 08 00 06 04 00 01 00 14 a4 43 78 69 0a 3b 01 26
    32: 00 00 00 00 00 00 0a 3b 01 01
    (breakpoint)
    >
    ```

  - breakpoint:



    ```text
    breakpoints: 0 1
    ```

    Prints currently set breakpoints.

- step \[-&lt;n&gt;, +&lt;n&gt;\]

  Performs single stepping through the BPF program from the current pc offset. Thus, on each step invocation, above register dump is issued. This can go forwards and backwards in time, a plain `step` will break on the next BPF instruction, thus +1. (No `run` needs to be issued here.)

- select &lt;n&gt;

  Selects a given packet from the pcap file to continue from. Thus, on the next `run` or `step`, the BPF program is being evaluated against the user pre-selected packet. Numbering starts just as in Wireshark with index 1.

- quit

  Exits bpf_dbg.

<a id="rst-jit-compiler"></a>

## JIT compiler

The Peios configuration enables `CONFIG_BPF_JIT_ALWAYS_ON`, so
`net.core.bpf_jit_enable` is fixed at 1. Attempts to select 0 or 2 fail.
Writes also pass a `CAP_SYS_ADMIN` check, mapped to enabled `SeTcbPrivilege`.
The historical value-2 kernel-log disassembly examples below describe a
different upstream debug configuration, not a setting available in this Peios
build. BPF program-loading authorization and socket access checks are separate
from selecting a JIT mode.

Example output from dmesg:



```text
[ 3389.935842] flen=6 proglen=70 pass=3 image=ffffffffa0069c8f
[ 3389.935847] JIT code: 00000000: 55 48 89 e5 48 83 ec 60 48 89 5d f8 44 8b 4f 68
[ 3389.935849] JIT code: 00000010: 44 2b 4f 6c 4c 8b 87 d8 00 00 00 be 0c 00 00 00
[ 3389.935850] JIT code: 00000020: e8 1d 94 ff e0 3d 00 08 00 00 75 16 be 17 00 00
[ 3389.935851] JIT code: 00000030: 00 e8 28 94 ff e0 83 f8 01 75 07 b8 ff ff 00 00
[ 3389.935852] JIT code: 00000040: eb 02 31 c0 c9 c3
```

When CONFIG_BPF_JIT_ALWAYS_ON is enabled, bpf_jit_enable is permanently set to 1 and setting any other value than that will return in failure. This is even the case for setting bpf_jit_enable to 2, since dumping the final JIT image into the kernel log is discouraged and introspection through bpftool (under tools/bpf/bpftool/) is the generally recommended approach instead.

In the kernel source tree under tools/bpf/, there's bpf_jit_disasm for generating disassembly out of the kernel log's hexdump:



```text
# ./bpf_jit_disasm
70 bytes emitted from JIT compiler (pass:3, flen:6)
ffffffffa0069c8f + <x>:
0:      push   %rbp
1:      mov    %rsp,%rbp
4:      sub    $0x60,%rsp
8:      mov    %rbx,-0x8(%rbp)
c:      mov    0x68(%rdi),%r9d
10:     sub    0x6c(%rdi),%r9d
14:     mov    0xd8(%rdi),%r8
1b:     mov    $0xc,%esi
20:     callq  0xffffffffe0ff9442
25:     cmp    $0x800,%eax
2a:     jne    0x0000000000000042
2c:     mov    $0x17,%esi
31:     callq  0xffffffffe0ff945e
36:     cmp    $0x1,%eax
39:     jne    0x0000000000000042
3b:     mov    $0xffff,%eax
40:     jmp    0x0000000000000044
42:     xor    %eax,%eax
44:     leaveq
45:     retq

Issuing option `-o` will "annotate" opcodes to resulting assembler
instructions, which can be very useful for JIT developers:

# ./bpf_jit_disasm -o
70 bytes emitted from JIT compiler (pass:3, flen:6)
ffffffffa0069c8f + <x>:
0:      push   %rbp
        55
1:      mov    %rsp,%rbp
        48 89 e5
4:      sub    $0x60,%rsp
        48 83 ec 60
8:      mov    %rbx,-0x8(%rbp)
        48 89 5d f8
c:      mov    0x68(%rdi),%r9d
        44 8b 4f 68
10:     sub    0x6c(%rdi),%r9d
        44 2b 4f 6c
14:     mov    0xd8(%rdi),%r8
        4c 8b 87 d8 00 00 00
1b:     mov    $0xc,%esi
        be 0c 00 00 00
20:     callq  0xffffffffe0ff9442
        e8 1d 94 ff e0
25:     cmp    $0x800,%eax
        3d 00 08 00 00
2a:     jne    0x0000000000000042
        75 16
2c:     mov    $0x17,%esi
        be 17 00 00 00
31:     callq  0xffffffffe0ff945e
        e8 28 94 ff e0
36:     cmp    $0x1,%eax
        83 f8 01
39:     jne    0x0000000000000042
        75 07
3b:     mov    $0xffff,%eax
        b8 ff ff 00 00
40:     jmp    0x0000000000000044
        eb 02
42:     xor    %eax,%eax
        31 c0
44:     leaveq
        c9
45:     retq
        c3
```

For BPF JIT developers, bpf_jit_disasm, bpf_asm and bpf_dbg provides a useful toolchain for developing and testing the kernel's JIT compiler.

<a id="rst-bpf-kernel-internals"></a>

## BPF kernel internals

Internally, for the kernel interpreter, a different instruction set format with similar underlying principles from BPF described in previous paragraphs is being used. However, the instruction set format is modelled closer to the underlying architecture to mimic native instruction sets, so that a better performance can be achieved (more details later). This new ISA is called eBPF.  See the ../bpf/index.rst for details.  (Note: eBPF which originates from \[e\]xtended BPF is not the same as BPF extensions\! While eBPF is an ISA, BPF extensions date back to classic BPF's 'overloading' of BPF_LD \| BPF\_\{B,H,W\} \| BPF_ABS instruction.)

The new instruction set was originally designed with the possible goal in mind to write programs in "restricted C" and compile into eBPF with a optional GCC/LLVM backend, so that it can just-in-time map to modern 64-bit CPUs with minimal performance overhead over two steps, that is, C -&gt; eBPF -&gt; native code.

Currently, the new format is being used for running user BPF programs, which includes seccomp BPF, classic socket filters, cls_bpf traffic classifier, team driver's classifier for its load-balancing mode, netfilter's xt_bpf extension (outside the configured Peios profile), PTP dissector/classifier, and much more. They are all internally converted by the kernel into the new instruction set representation and run in the eBPF interpreter. For in-kernel handlers, this all works transparently by using bpf_prog_create() for setting up the filter, resp. bpf_prog_destroy() for destroying it. The function bpf_prog_run(filter, ctx) transparently invokes eBPF interpreter or JITed code to run the filter. 'filter' is a pointer to struct bpf_prog that we got from bpf_prog_create(), and 'ctx' the given context (e.g. skb pointer). All constraints and restrictions from bpf_check_classic() apply before a conversion to the new layout is being done behind the scenes\!

Currently, the classic BPF format is being used for JITing on most 32-bit architectures, whereas x86-64, aarch64, s390x, powerpc64, sparc64, arm32, riscv64, riscv32, loongarch64, arc perform JIT compilation from eBPF instruction set.

<a id="rst-testing"></a>

## Testing

Next to the BPF toolchain, the kernel also ships a test module that contains various test cases for classic and eBPF that can be executed against the BPF interpreter and JIT compiler. It can be found in lib/test_bpf.c and enabled via Kconfig:



```text
CONFIG_TEST_BPF=m
```

After the module has been built and installed, the test suite can be executed via insmod or modprobe against 'test_bpf' module. Results of the test cases including timings in nsec can be found in the kernel log (dmesg).

<a id="rst-misc"></a>

## Misc

Also trinity, the Linux syscall fuzzer, has built-in support for BPF and SECCOMP-BPF kernel fuzzing.

<a id="rst-written-by"></a>

## Written by

The document was written in the hope that it is found useful and in order to give potential BPF hackers or security auditors a better overview of the underlying architecture.

- Jay Schulist &lt;[jschlst@samba.org](<mailto:jschlst@samba.org>)&gt;

- Daniel Borkmann &lt;[daniel@iogearbox.net](<mailto:daniel@iogearbox.net>)&gt;

- Alexei Starovoitov &lt;[ast@kernel.org](<mailto:ast@kernel.org>)&gt;

---

# Generic networking statistics for netlink users

_Peios Kernel / Internals / Networking_

> Statistic counters are grouped into structs:

<a id="rst-generic-networking-statistics-for-netlink-users"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Statistic counters are grouped into structs:


<table>
<thead>
<tr>
<th>


Struct

</th>
<th>


TLV type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


gnet_stats_basic

</td>
<td>


TCA_STATS_BASIC

</td>
<td>


Basic statistics

</td>
</tr>
<tr>
<td>


gnet_stats_rate_est

</td>
<td>


TCA_STATS_RATE_EST

</td>
<td>


Rate estimator

</td>
</tr>
<tr>
<td>


gnet_stats_queue

</td>
<td>


TCA_STATS_QUEUE

</td>
<td>


Queue statistics

</td>
</tr>
<tr>
<td>


none

</td>
<td>


TCA_STATS_APP

</td>
<td>


Application specific

</td>
</tr>
</tbody>
</table>

<a id="rst-collecting"></a>

## Collecting:

Declare the statistic structs you need:



```text
struct mystruct {
        struct gnet_stats_basic bstats;
        struct gnet_stats_queue qstats;
        ...
};
```

Update statistics, in dequeue() methods only, (while owning qdisc-&gt;running):



```text
mystruct->tstats.packet++;
mystruct->qstats.backlog += skb->pkt_len;
```

<a id="rst-export-to-userspace-dump"></a>

## Export to userspace (Dump):



```text
my_dumping_routine(struct sk_buff *skb, ...)
{
        struct gnet_dump dump;

        if (gnet_stats_start_copy(skb, TCA_STATS2, &mystruct->lock, &dump,
                                TCA_PAD) < 0)
                goto rtattr_failure;

        if (gnet_stats_copy_basic(&dump, &mystruct->bstats) < 0 ||
            gnet_stats_copy_queue(&dump, &mystruct->qstats) < 0 ||
                gnet_stats_copy_app(&dump, &xstats, sizeof(xstats)) < 0)
                goto rtattr_failure;

        if (gnet_stats_finish_copy(&dump) < 0)
                goto rtattr_failure;
        ...
}
```

<a id="rst-tca-stats-tca-xstats-backward-compatibility"></a>

## TCA_STATS/TCA_XSTATS backward compatibility:

Prior users of struct tc_stats and xstats can maintain backward compatibility by calling the compat wrappers to keep providing the existing TLV types:



```text
my_dumping_routine(struct sk_buff *skb, ...)
{
    if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS,
                                    TCA_XSTATS, &mystruct->lock, &dump,
                                    TCA_PAD) < 0)
                goto rtattr_failure;
        ...
}
```

A struct tc_stats will be filled out during gnet_stats_copy\_\* calls and appended to the skb. TCA_XSTATS is provided if gnet_stats_copy_app was called.

<a id="rst-locking"></a>

## Locking:

Locks are taken before writing and released once all statistics have been written. Locks are always released in case of an error. You are responsible for making sure that the lock is initialized.

<a id="rst-rate-estimator"></a>

## Rate Estimator:

0. Prepare an estimator attribute. Most likely this would be in user space. The value of this TLV should contain a tc_estimator structure. As usual, such a TLV needs to be 32 bit aligned and therefore the length needs to be appropriately set, etc. The estimator interval and ewma log need to be converted to the appropriate values. tc_estimator.c::tc_setup_estimator() is advisable to be used as the conversion routine. It does a few clever things. It takes a time interval in microsecs, a time constant also in microsecs and a struct tc_estimator to  be populated. The returned tc_estimator can be transported to the kernel.  Transfer such a structure in a TLV of type TCA_RATE to your code in the kernel.

In the kernel when setting up:

1. make sure you have basic stats and rate stats setup first.

2. make sure you have initialized stats lock that is used to setup such stats.

3. Now initialize a new estimator:



   ```text
   int ret = gen_new_estimator(my_basicstats,my_rate_est_stats,
       mystats_lock, attr_with_tcestimator_struct);

   if ret == 0
       success
   else
       failed
   ```

From now on, every time you dump my_rate_est_stats it will contain up-to-date info.

Once you are done, call gen_kill_estimator(my_basicstats, my_rate_est_stats) Make sure that my_basicstats and my_rate_est_stats are still valid (i.e still exist) at the time of making this call.

<a id="rst-authors"></a>

## Authors:

- Thomas Graf &lt;[tgraf@suug.ch](<mailto:tgraf@suug.ch>)&gt;

- Jamal Hadi Salim &lt;[hadi@cyberus.ca](<mailto:hadi@cyberus.ca>)&gt;

---

# Generic HDLC layer

_Peios Kernel / Internals / Networking_

> Krzysztof Halasa <khc@pm.waw.pl>

<a id="rst-generic-hdlc-layer"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Krzysztof Halasa &lt;[khc@pm.waw.pl](<mailto:khc@pm.waw.pl>)&gt;

Generic HDLC layer currently supports:

1. Frame Relay (ANSI, CCITT, Cisco and no LMI)

   - Normal (routed) and Ethernet-bridged (Ethernet device emulation) interfaces can share a single PVC.

   - ARP support (no InARP support in the kernel - there is an experimental InARP user-space daemon available on: [http://www.kernel.org/pub/linux/utils/net/hdlc/](<http://www.kernel.org/pub/linux/utils/net/hdlc/>)).

2. raw HDLC - either IP (IPv4) interface or Ethernet device emulation

3. Cisco HDLC

4. PPP

5. X.25 (uses X.25 routines).

Generic HDLC is a protocol driver only - it needs a low-level driver for your particular hardware.

Ethernet device emulation (using HDLC or Frame-Relay PVC) is compatible with IEEE 802.1Q (VLANs) and 802.1D (Ethernet bridging).

Make sure the hdlc.o and the hardware driver are loaded. It should create a number of "hdlc" (hdlc0 etc) network devices, one for each WAN port. You'll need the "sethdlc" utility, get it from:

> [http://www.kernel.org/pub/linux/utils/net/hdlc/](<http://www.kernel.org/pub/linux/utils/net/hdlc/>)

Compile sethdlc.c utility:



```text
gcc -O2 -Wall -o sethdlc sethdlc.c
```

Make sure you're using a correct version of sethdlc for your kernel.

Use sethdlc to set physical interface, clock rate, HDLC mode used, and add any required PVCs if using Frame Relay. Usually you want something like:



```text
sethdlc hdlc0 clock int rate 128000
sethdlc hdlc0 cisco interval 10 timeout 25
```

or:



```text
sethdlc hdlc0 rs232 clock ext
sethdlc hdlc0 fr lmi ansi
sethdlc hdlc0 create 99
ifconfig hdlc0 up
ifconfig pvc0 localIP pointopoint remoteIP
```

In Frame Relay mode, ifconfig master hdlc device up (without assigning any IP address to it) before using pvc devices.

Setting interface:

- - **v35 \| rs232 \| x21 \| t1 \| e1**

    - sets physical interface for a given port if the card has software-selectable interfaces

  - **loopback**

    - activate hardware loopback (for testing only)

- - **clock ext**

    - both RX clock and TX clock external

- - **clock int**

    - both RX clock and TX clock internal

- - **clock txint**

    - RX clock external, TX clock internal

- - **clock txfromrx**

    - RX clock external, TX clock derived from RX clock

- - **rate**

    - sets clock rate in bps (for "int" or "txint" clock only)

Setting protocol:

- hdlc - sets raw HDLC (IP-only) mode

  nrz / nrzi / fm-mark / fm-space / manchester - sets transmission code

  no-parity / crc16 / crc16-pr0 (CRC16 with preset zeros) / crc32-itu

  crc16-itu (CRC16 with ITU-T polynomial) / crc16-itu-pr0 - sets parity

- hdlc-eth - Ethernet device emulation using HDLC. Parity and encoding as above.

- cisco - sets Cisco HDLC mode (IP, IPv6 and IPX supported)

  interval - time in seconds between keepalive packets

  - **timeout - time in seconds after last received keepalive packet before**

    we assume the link is down

- ppp - sets synchronous PPP mode

- x25 - sets X.25 mode

- fr - Frame Relay mode

  lmi ansi / ccitt / cisco / none - LMI (link management) type

  dce - Frame Relay DCE (network) side LMI instead of default DTE (user).

  It has nothing to do with clocks\!

  - t391 - link integrity verification polling timer (in seconds) - user

  - t392 - polling verification timer (in seconds) - network

  - n391 - full status polling counter - user

  - n392 - error threshold - both user and network

  - n393 - monitored events count - both user and network

Frame-Relay only:

- create n \| delete n - adds / deletes PVC interface with DLCI \#n. Newly created interface will be named pvc0, pvc1 etc.

- create ether n \| delete ether n - adds a device for Ethernet-bridged frames. The device will be named pvceth0, pvceth1 etc.

<a id="rst-board-specific-issues"></a>

## Board-specific issues

n2.o and c101.o need parameters to work:



```text
insmod n2 hw=io,irq,ram,ports[:io,irq,...]
```

example:



```text
insmod n2 hw=0x300,10,0xD0000,01
```

or:



```text
insmod c101 hw=irq,ram[:irq,...]
```

example:



```text
insmod c101 hw=9,0xdc000
```

If built into the kernel, these drivers need kernel (command line) parameters:



```text
n2.hw=io,irq,ram,ports:...
```

or:



```text
c101.hw=irq,ram:...
```

If you have a problem with N2, C101 or PLX200SYN card, you can issue the "private" command to see port's packet descriptor rings (in kernel logs):



```text
sethdlc hdlc0 private
```

The hardware driver has to be build with \#define DEBUG_RINGS. Attaching this info to bug reports would be helpful. Anyway, let me know if you have problems using this.

For patches and other info look at: &lt;[http://www.kernel.org/pub/linux/utils/net/hdlc/](<http://www.kernel.org/pub/linux/utils/net/hdlc/>)&gt;.

---

# Generic Netlink

_Peios Kernel / Internals / Networking_

> A wiki document on how to use Generic Netlink can be found here:

<a id="rst-generic-netlink"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

A wiki document on how to use Generic Netlink can be found here:

> - [https://wiki.linuxfoundation.org/networking/generic_netlink_howto](<https://wiki.linuxfoundation.org/networking/generic_netlink_howto>)

---

# The Linux kernel GTP tunneling module

_Peios Kernel / Internals / Networking_

> Harald Welte <laforge@gnumonks.org> and Andreas Schultz <aschultz@tpip.net>

<a id="rst-the-linux-kernel-gtp-tunneling-module"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Documentation by**

  Harald Welte &lt;[laforge@gnumonks.org](<mailto:laforge@gnumonks.org>)&gt; and Andreas Schultz &lt;[aschultz@tpip.net](<mailto:aschultz@tpip.net>)&gt;

In 'drivers/net/gtp.c' you are finding a kernel-level implementation of a GTP tunnel endpoint.

<a id="rst-what-is-gtp"></a>

## What is GTP

GTP is the Generic Tunnel Protocol, which is a 3GPP protocol used for tunneling User-IP payload between a mobile station (phone, modem) and the interconnection between an external packet data network (such as the internet).

So when you start a 'data connection' from your mobile phone, the phone will use the control plane to signal for the establishment of such a tunnel between that external data network and the phone.  The tunnel endpoints thus reside on the phone and in the gateway.  All intermediate nodes just transport the encapsulated packet.

The phone itself does not implement GTP but uses some other technology-dependent protocol stack for transmitting the user IP payload, such as LLC/SNDCP/RLC/MAC.

At some network element inside the cellular operator infrastructure (SGSN in case of GPRS/EGPRS or classic UMTS, hNodeB in case of a 3G femtocell, eNodeB in case of 4G/LTE), the cellular protocol stacking is translated into GTP *without breaking the end-to-end tunnel*.  So intermediate nodes just perform some specific relay function.

At some point the GTP packet ends up on the so-called GGSN (GSM/UMTS) or P-GW (LTE), which terminates the tunnel, decapsulates the packet and forwards it onto an external packet data network.  This can be public internet, but can also be any private IP network (or even theoretically some non-IP network like X.25).

You can find the protocol specification in 3GPP TS 29.060, available publicly via the 3GPP website at [http://www.3gpp.org/DynaReport/29060.htm](<http://www.3gpp.org/DynaReport/29060.htm>)

A direct PDF link to v13.6.0 is provided for convenience below: [http://www.etsi.org/deliver/etsi_ts/129000_129099/129060/13.06.00_60/ts_129060v130600p.pdf](<http://www.etsi.org/deliver/etsi_ts/129000_129099/129060/13.06.00_60/ts_129060v130600p.pdf>)

<a id="rst-the-linux-gtp-tunnelling-module"></a>

## The Linux GTP tunnelling module

The module implements the function of a tunnel endpoint, i.e. it is able to decapsulate tunneled IP packets in the uplink originated by the phone, and encapsulate raw IP packets received from the external packet network in downlink towards the phone.

It *only* implements the so-called 'user plane', carrying the User-IP payload, called GTP-U.  It does not implement the 'control plane', which is a signaling protocol used for establishment and teardown of GTP tunnels (GTP-C).

So in order to have a working GGSN/P-GW setup, you will need a userspace program that implements the GTP-C protocol and which then uses the netlink interface provided by the GTP-U module in the kernel to configure the kernel module.

This split architecture follows the tunneling modules of other protocols, e.g. PPPoE or L2TP, where you also run a userspace daemon to handle the tunnel establishment, authentication etc. and only the data plane is accelerated inside the kernel.

Don't be confused by terminology:  The GTP User Plane goes through kernel accelerated path, while the GTP Control Plane goes to Userspace :)

The official homepage of the module is at [https://osmocom.org/projects/linux-kernel-gtp-u/wiki](<https://osmocom.org/projects/linux-kernel-gtp-u/wiki>)

<a id="rst-userspace-programs-with-linux-kernel-gtp-u-support"></a>

## Userspace Programs with Linux Kernel GTP-U support

At the time of this writing, there are at least two Free Software implementations that implement GTP-C and can use the netlink interface to make use of the Linux kernel GTP-U support:

- OpenGGSN (classic 2G/3G GGSN in C): [https://osmocom.org/projects/openggsn/wiki/OpenGGSN](<https://osmocom.org/projects/openggsn/wiki/OpenGGSN>)

- ergw (GGSN + P-GW in Erlang): [https://github.com/travelping/ergw](<https://github.com/travelping/ergw>)

<a id="rst-userspace-library-command-line-utilities"></a>

## Userspace Library / Command Line Utilities

There is a userspace library called 'libgtpnl' which is based on libmnl and which implements a C-language API towards the netlink interface provided by the Kernel GTP module:

[http://git.osmocom.org/libgtpnl/](<http://git.osmocom.org/libgtpnl/>)

<a id="rst-protocol-versions"></a>

## Protocol Versions

There are two different versions of GTP-U: v0 \[GSM TS 09.60\] and v1 \[3GPP TS 29.281\].  Both are implemented in the Kernel GTP module. Version 0 is a legacy version, and deprecated from recent 3GPP specifications.

GTP-U uses UDP for transporting PDUs.  The receiving UDP port is 2151 for GTPv1-U and 3386 for GTPv0-U.

There are three versions of GTP-C: v0, v1, and v2.  As the kernel doesn't implement GTP-C, we don't have to worry about this.  It's the responsibility of the control plane implementation in userspace to implement that.

<a id="rst-ipv6"></a>

## IPv6

The 3GPP specifications indicate either IPv4 or IPv6 can be used both on the inner (user) IP layer, or on the outer (transport) layer.

Unfortunately, the Kernel module currently supports IPv6 neither for the User IP payload, nor for the outer IP layer.  Patches or other Contributions to fix this are most welcome\!

<a id="rst-mailing-list"></a>

## Mailing List

If you have questions regarding how to use the Kernel GTP module from your own software, or want to contribute to the code, please use the osmocom-net-grps mailing list for related discussion. The list can be reached at [osmocom-net-gprs@lists.osmocom.org](<mailto:osmocom-net-gprs@lists.osmocom.org>) and the mailman interface for managing your subscription is at [https://lists.osmocom.org/mailman/listinfo/osmocom-net-gprs](<https://lists.osmocom.org/mailman/listinfo/osmocom-net-gprs>)

<a id="rst-issue-tracker"></a>

## Issue Tracker

The Osmocom project maintains an issue tracker for the Kernel GTP-U module at [https://osmocom.org/projects/linux-kernel-gtp-u/issues](<https://osmocom.org/projects/linux-kernel-gtp-u/issues>)

<a id="rst-history-acknowledgements"></a>

## History / Acknowledgements

The Module was originally created in 2012 by Harald Welte, but never completed.  Pablo came in to finish the mess Harald left behind.  But doe to a lack of user interest, it never got merged.

In 2015, Andreas Schultz came to the rescue and fixed lots more bugs, extended it with new features and finally pushed all of us to get it mainline, where it was merged in 4.7.0.

<a id="rst-architectural-details"></a>

## Architectural Details

<a id="rst-local-gtp-u-entity-and-tunnel-identification"></a>

### Local GTP-U entity and tunnel identification

GTP-U uses UDP for transporting PDU's. The receiving UDP port is 2152 for GTPv1-U and 3386 for GTPv0-U.

There is only one GTP-U entity (and therefore SGSN/GGSN/S-GW/PDN-GW instance) per IP address. Tunnel Endpoint Identifier (TEID) are unique per GTP-U entity.

A specific tunnel is only defined by the destination entity. Since the destination port is constant, only the destination IP and TEID define a tunnel. The source IP and Port have no meaning for the tunnel.

Therefore:

> - when sending, the remote entity is defined by the remote IP and the tunnel endpoint id. The source IP and port have no meaning and can be changed at any time.
>
> - when receiving the local entity is defined by the local destination IP and the tunnel endpoint id. The source IP and port have no meaning and can change at any time.

\[3GPP TS 29.281\] Section 4.3.0 defines this so:



```text
The TEID in the GTP-U header is used to de-multiplex traffic
incoming from remote tunnel endpoints so that it is delivered to the
User plane entities in a way that allows multiplexing of different
users, different packet protocols and different QoS levels.
Therefore no two remote GTP-U endpoints shall send traffic to a
GTP-U protocol entity using the same TEID value except
for data forwarding as part of mobility procedures.
```

The definition above only defines that two remote GTP-U endpoints *should not* send to the same TEID, it *does not* forbid or exclude such a scenario. In fact, the mentioned mobility procedures make it necessary that the GTP-U entity accepts traffic for TEIDs from multiple or unknown peers.

Therefore, the receiving side identifies tunnels exclusively based on TEIDs, not based on the source IP\!

<a id="rst-apn-vs-network-device"></a>

## APN vs. Network Device

The GTP-U driver creates a Linux network device for each Gi/SGi interface.

\[3GPP TS 29.281\] calls the Gi/SGi reference point an interface. This may lead to the impression that the GGSN/P-GW can have only one such interface.

Correct is that the Gi/SGi reference point defines the interworking between +the 3GPP packet domain (PDN) based on GTP-U tunnel and IP based networks.

There is no provision in any of the 3GPP documents that limits the number of Gi/SGi interfaces implemented by a GGSN/P-GW.

\[3GPP TS 29.061\] Section 11.3 makes it clear that the selection of a specific Gi/SGi interfaces is made through the Access Point Name (APN):



```text
2. each private network manages its own addressing. In general this
   will result in different private networks having overlapping
   address ranges. A logically separate connection (e.g. an IP in IP
   tunnel or layer 2 virtual circuit) is used between the GGSN/P-GW
   and each private network.

   In this case the IP address alone is not necessarily unique.  The
   pair of values, Access Point Name (APN) and IPv4 address and/or
   IPv6 prefixes, is unique.
```

In order to support the overlapping address range use case, each APN is mapped to a separate Gi/SGi interface (network device).

> [!NOTE]
>
> The Access Point Name is purely a control plane (GTP-C) concept. At the GTP-U level, only Tunnel Endpoint Identifiers are present in GTP-U packets and network devices are known

Therefore for a given UE the mapping in IP to PDN network is:

> - network device + MS IP -&gt; Peer IP + Peer TEID,

and from PDN to IP network:

> - local GTP-U IP + TEID  -&gt; network device

Furthermore, before a received T-PDU is injected into the network device the MS IP is checked against the IP recorded in PDP context.

---

# IEEE 802.15.4 Developer's Guide

_Peios Kernel / Internals / Networking_

> The IEEE 802.15.4 working group focuses on standardization of the bottom two layers: Medium Access Control (MAC) and Physical access (PHY). And there are mainly two options available for upper layers:

<a id="rst-ieee-802-15-4-developer-s-guide"></a>

<a id="rst-introduction"></a>

## Introduction

The IEEE 802.15.4 working group focuses on standardization of the bottom two layers: Medium Access Control (MAC) and Physical access (PHY). And there are mainly two options available for upper layers:

- ZigBee - proprietary protocol from the ZigBee Alliance

- 6LoWPAN - IPv6 networking over low rate personal area networks

The goal of the Linux-wpan is to provide a complete implementation of the IEEE 802.15.4 and 6LoWPAN protocols. IEEE 802.15.4 is a stack of protocols for organizing Low-Rate Wireless Personal Area Networks.

The stack is composed of three main parts:

- IEEE 802.15.4 layer;  We have chosen to use plain Berkeley socket API, the generic Linux networking stack to transfer IEEE 802.15.4 data messages and a special protocol over netlink for configuration/management

- MAC - provides access to shared channel and reliable data delivery

- PHY - represents device drivers

<a id="rst-socket-api"></a>

## Socket API



```text
int sd = socket(PF_IEEE802154, SOCK_DGRAM, 0);
```

The address family, socket addresses etc. are defined in the include/net/af_ieee802154.h header or in the special header in the userspace package (see either [https://linux-wpan.org/wpan-tools.html](<https://linux-wpan.org/wpan-tools.html>) or the git tree at [https://github.com/linux-wpan/wpan-tools](<https://github.com/linux-wpan/wpan-tools>)).

<a id="rst-lowpan-linux-implementation"></a>

## 6LoWPAN Linux implementation

The IEEE 802.15.4 standard specifies an MTU of 127 bytes, yielding about 80 octets of actual MAC payload once security is turned on, on a wireless link with a link throughput of 250 kbps or less.  The 6LoWPAN adaptation format \[RFC4944\] was specified to carry IPv6 datagrams over such constrained links, taking into account limited bandwidth, memory, or energy resources that are expected in applications such as wireless Sensor Networks.  \[RFC4944\] defines a Mesh Addressing header to support sub-IP forwarding, a Fragmentation header to support the IPv6 minimum MTU requirement \[RFC2460\], and stateless header compression for IPv6 datagrams (LOWPAN_HC1 and LOWPAN_HC2) to reduce the relatively large IPv6 and UDP headers down to (in the best case) several bytes.

In September 2011 the standard update was published - \[RFC6282\]. It deprecates HC1 and HC2 compression and defines IPHC encoding format which is used in this Linux implementation.

All the code related to 6lowpan you may find in files: net/6lowpan/\* and net/ieee802154/6lowpan/\*

To setup a 6LoWPAN interface you need: 1. Add IEEE802.15.4 interface and set channel and PAN ID; 2. Add 6lowpan interface by command like: \# ip link add link wpan0 name lowpan0 type lowpan 3. Bring up 'lowpan0' interface

<a id="rst-drivers"></a>

## Drivers

Like with WiFi, there are several types of devices implementing IEEE 802.15.4. 1) 'HardMAC'. The MAC layer is implemented in the device itself, the device exports a management (e.g. MLME) and data API. 2) 'SoftMAC' or just radio. These types of devices are just radio transceivers possibly with some kinds of acceleration like automatic CRC computation and comparison, automagic ACK handling, address matching, etc.

Each type of device requires a different approach to be hooked into the Linux kernel.

<a id="rst-hardmac"></a>

### HardMAC

See the header include/net/ieee802154_netdev.h. You have to implement Linux net_device, with .type = ARPHRD_IEEE802154. Data is exchanged with socket family code via plain sk_buffs. On skb reception skb-&gt;cb must contain additional info as described in the struct ieee802154_mac_cb. During packet transmission the skb-&gt;cb is used to provide additional data to the device's header_ops-&gt;create function. Be aware that this data can be overridden later (when socket code submits skb to qdisc), so if you need something from that cb later, you should store info in the skb-&gt;data on your own.

To hook the MLME interface you have to populate the ml_priv field of your net_device with a pointer to struct ieee802154_mlme_ops instance. The fields assoc_req, assoc_resp, disassoc_req, start_req, and scan_req are optional. All other fields are required.

<a id="rst-softmac"></a>

### SoftMAC

The MAC is the middle layer in the IEEE 802.15.4 Linux stack. At the moment, it provides an interface for driver registration and management of slave interfaces.

NOTE: Currently the only monitor device type is supported - it's IEEE 802.15.4 stack interface for network sniffers (e.g. WireShark).

This layer is going to be extended soon.

See header include/net/mac802154.h and several drivers in drivers/net/ieee802154/.

<a id="rst-fake-drivers"></a>

### Fake drivers

In addition there is a driver available which simulates a real device with SoftMAC (fakelb - IEEE 802.15.4 loopback driver) interface. This option provides a possibility to test and debug the stack without usage of real hardware.

<a id="rst-device-drivers-api"></a>

## Device drivers API

The include/net/mac802154.h defines following functions:





<a id="c-ieee802154_alloc_device"></a>

```c
struct ieee802154_dev *ieee802154_alloc_device (size_t priv_size, struct ieee802154_ops *ops)
```

Allocation of IEEE 802.15.4 compatible device.





<a id="c-ieee802154_free_device"></a>

```c
void ieee802154_free_device(struct ieee802154_dev *dev)
```

Freeing allocated device.





<a id="c-ieee802154_register_device"></a>

```c
int ieee802154_register_device(struct ieee802154_dev *dev)
```

Register PHY in the system.





<a id="c-ieee802154_unregister_device"></a>

```c
void ieee802154_unregister_device(struct ieee802154_dev *dev)
```

Freeing registered PHY.





<a id="c-ieee802154_rx_irqsafe"></a>

```c
void ieee802154_rx_irqsafe(struct ieee802154_hw *hw, struct sk_buff *skb, u8 lqi)
```

Telling 802.15.4 module there is a new received frame in the skb with the RF Link Quality Indicator (LQI) from the hardware device.





<a id="c-ieee802154_xmit_complete"></a>

```c
void ieee802154_xmit_complete(struct ieee802154_hw *hw, struct sk_buff *skb, bool ifs_handling)
```

Telling 802.15.4 module the frame in the skb is or going to be transmitted through the hardware device

The device driver must implement the following callbacks in the IEEE 802.15.4 operations structure at least:



```text
struct ieee802154_ops {
     ...
     int     (*start)(struct ieee802154_hw *hw);
     void    (*stop)(struct ieee802154_hw *hw);
     ...
     int     (*xmit_async)(struct ieee802154_hw *hw, struct sk_buff *skb);
     int     (*ed)(struct ieee802154_hw *hw, u8 *level);
     int     (*set_channel)(struct ieee802154_hw *hw, u8 page, u8 channel);
     ...
};
```





<a id="c-start"></a>

```c
int start(struct ieee802154_hw *hw)
```

Handler that 802.15.4 module calls for the hardware device initialization.





<a id="c-stop"></a>

```c
void stop(struct ieee802154_hw *hw)
```

Handler that 802.15.4 module calls for the hardware device cleanup.





<a id="c-xmit_async"></a>

```c
int xmit_async(struct ieee802154_hw *hw, struct sk_buff *skb)
```

Handler that 802.15.4 module calls for each frame in the skb going to be transmitted through the hardware device.





<a id="c-ed"></a>

```c
int ed(struct ieee802154_hw *hw, u8 *level)
```

Handler that 802.15.4 module calls for Energy Detection from the hardware device.





<a id="c-set_channel"></a>

```c
int set_channel(struct ieee802154_hw *hw, u8 page, u8 channel)
```

Set radio for listening on specific channel of the hardware device.

Moreover IEEE 802.15.4 device operations structure should be filled.

---

# Identifier Locator Addressing (ILA)

_Peios Kernel / Internals / Networking_

> Identifier-locator addressing (ILA) is a technique used with IPv6 that differentiates between location and identity of a network node. Part of an address expresses the immutable identity of the node, and another part indicates the location…

<a id="rst-identifier-locator-addressing-ila"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Identifier-locator addressing (ILA) is a technique used with IPv6 that differentiates between location and identity of a network node. Part of an address expresses the immutable identity of the node, and another part indicates the location of the node which can be dynamic. Identifier-locator addressing can be used to efficiently implement overlay networks for network virtualization as well as solutions for use cases in mobility.

ILA can be thought of as means to implement an overlay network without encapsulation. This is accomplished by performing network address translation on destination addresses as a packet traverses a network. To the network, an ILA translated packet appears to be no different than any other IPv6 packet. For instance, if the transport protocol is TCP then an ILA translated packet looks like just another TCP/IPv6 packet. The advantage of this is that ILA is transparent to the network so that optimizations in the network, such as ECMP, RSS, GRO, GSO, etc., just work.

The ILA protocol is described in Internet-Draft draft-herbert-intarea-ila.

<a id="rst-ila-terminology"></a>

## ILA terminology

> - - **Identifier**
>
>     A number that identifies an addressable node in the network independent of its location. ILA identifiers are sixty-four bit values.
>
> - - **Locator**
>
>     A network prefix that routes to a physical host. Locators provide the topological location of an addressed node. ILA locators are sixty-four bit prefixes.
>
> - - **ILA mapping**
>
>     A mapping of an ILA identifier to a locator (or to a locator and meta data). An ILA domain maintains a database that contains mappings for all destinations in the domain.
>
> - - **SIR address**
>
>     An IPv6 address composed of a SIR prefix (upper sixty- four bits) and an identifier (lower sixty-four bits). SIR addresses are visible to applications and provide a means for them to address nodes independent of their location.
>
> - - **ILA address**
>
>     An IPv6 address composed of a locator (upper sixty-four bits) and an identifier (low order sixty-four bits). ILA addresses are never visible to an application.
>
> - - **ILA host**
>
>     An end host that is capable of performing ILA translations on transmit or receive.
>
> - - **ILA router**
>
>     A network node that performs ILA translation and forwarding of translated packets.
>
> - - **ILA forwarding cache**
>
>     A type of ILA router that only maintains a working set cache of mappings.
>
> - - **ILA node**
>
>     A network node capable of performing ILA translations. This can be an ILA router, ILA forwarding cache, or ILA host.

<a id="rst-operation"></a>

## Operation

There are two fundamental operations with ILA:

> - Translate a SIR address to an ILA address. This is performed on ingress to an ILA overlay.
>
> - Translate an ILA address to a SIR address. This is performed on egress from the ILA overlay.

ILA can be deployed either on end hosts or intermediate devices in the network; these are provided by "ILA hosts" and "ILA routers" respectively. Configuration and datapath for these two points of deployment is somewhat different.

The diagram below illustrates the flow of packets through ILA as well as showing ILA hosts and routers:



```text
 +--------+                                                +--------+
 | Host A +-+                                         +--->| Host B |
 |        | |              (2) ILA                   (')   |        |
 +--------+ |            ...addressed....           (   )  +--------+
            V  +---+--+  .  packet      .  +---+--+  (_)
(1) SIR     |  | ILA  |----->-------->---->| ILA  |   |   (3) SIR
 addressed  +->|router|  .              .  |router|->-+    addressed
 packet        +---+--+  .     IPv6     .  +---+--+        packet
                /        .    Network   .
               /         .              .   +--+-++--------+
 +--------+   /          .              .   |ILA ||  Host  |
 |  Host  +--+           .              .- -|host||        |
 |        |              .              .   +--+-++--------+
 +--------+              ................
```

<a id="rst-transport-checksum-handling"></a>

## Transport checksum handling

When an address is translated by ILA, an encapsulated transport checksum that includes the translated address in a pseudo header may be rendered incorrect on the wire. This is a problem for intermediate devices, including checksum offload in NICs, that process the checksum. There are three options to deal with this:

- - **no action     Allow the checksum to be incorrect on the wire. Before**

    a receiver verifies a checksum the ILA to SIR address translation must be done.

- - **adjust transport checksum**

    When ILA translation is performed the packet is parsed and if a transport layer checksum is found then it is adjusted to reflect the correct checksum per the translated address.

- - **checksum neutral mapping**

    When an address is translated the difference can be offset elsewhere in a part of the packet that is covered by the checksum. The low order sixteen bits of the identifier are used. This method is preferred since it doesn't require parsing a packet beyond the IP header and in most cases the adjustment can be precomputed and saved with the mapping.

Note that the checksum neutral adjustment affects the low order sixteen bits of the identifier. When ILA to SIR address translation is done on egress the low order bits are restored to the original value which restores the identifier as it was originally sent.

<a id="rst-identifier-types"></a>

## Identifier types

ILA defines different types of identifiers for different use cases.

The defined types are:

> 0: interface identifier
>
> 1: locally unique identifier
>
> 2: virtual networking identifier for IPv4 address
>
> 3: virtual networking identifier for IPv6 unicast address
>
> 4: virtual networking identifier for IPv6 multicast address
>
> 5: non-local address identifier

In the current implementation of kernel ILA only locally unique identifiers (LUID) are supported. LUID allows for a generic, unformatted 64 bit identifier.

<a id="rst-identifier-formats"></a>

## Identifier formats

Kernel ILA supports two optional fields in an identifier for formatting: "C-bit" and "identifier type". The presence of these fields is determined by configuration as demonstrated below.

If the identifier type is present it occupies the three highest order bits of an identifier. The possible values are given in the above list.

If the C-bit is present,  this is used as an indication that checksum neutral mapping has been done. The C-bit can only be set in an ILA address, never a SIR address.

In the simplest format the identifier types, C-bit, and checksum adjustment value are not present so an identifier is considered an unstructured sixty-four bit value:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                            Identifier                         |
+                                                               +
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

The checksum neutral adjustment may be configured to always be present using neutral-map-auto. In this case there is no C-bit, but the checksum adjustment is in the low order 16 bits. The identifier is still sixty-four bits:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                            Identifier                         |
|                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |  Checksum-neutral adjustment  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

The C-bit may used to explicitly indicate that checksum neutral mapping has been applied to an ILA address. The format is:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     |C|                    Identifier                         |
|     +-+                       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |  Checksum-neutral adjustment  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

The identifier type field may be present to indicate the identifier type. If it is not present then the type is inferred based on mapping configuration. The checksum neutral adjustment may automatically used with the identifier type as illustrated below:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type|                      Identifier                         |
+-+-+-+                         +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |  Checksum-neutral adjustment  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

If the identifier type and the C-bit can be present simultaneously so the identifier format would be:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type|C|                    Identifier                         |
+-+-+-+-+                       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |  Checksum-neutral adjustment  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

<a id="rst-configuration"></a>

## Configuration

There are two methods to configure ILA mappings. One is by using LWT routes and the other is ila_xlat (called from NFHOOK PREROUTING hook). ila_xlat is intended to be used in the receive path for ILA hosts .

An ILA router has also been implemented in XDP. Description of that is outside the scope of this document.

The usage of for ILA LWT routes is:

ip route add DEST/128 encap ila LOC csum-mode MODE ident-type TYPE via ADDR

Destination (DEST) can either be a SIR address (for an ILA host or ingress ILA router) or an ILA address (egress ILA router). LOC is the sixty-four bit locator (with format W:X:Y:Z) that overwrites the upper sixty-four bits of the destination address.  Checksum MODE is one of "no-action", "adj-transport", "neutral-map", and "neutral-map-auto". If neutral-map is set then the C-bit will be present. Identifier TYPE one of "luid" or "use-format." In the case of use-format, the identifier type field is present and the effective type is taken from that.

The usage of ila_xlat is:

ip ila add loc_match MATCH loc LOC csum-mode MODE ident-type TYPE

MATCH indicates the incoming locator that must be matched to apply a the translaiton. LOC is the locator that overwrites the upper sixty-four bits of the destination address. MODE and TYPE have the same meanings as described above.

<a id="rst-some-examples"></a>

## Some examples



```text
# Configure an ILA route that uses checksum neutral mapping as well
# as type field. Note that the type field is set in the SIR address
# (the 2000 implies type is 1 which is LUID).
ip route add 3333:0:0:1:2000:0:1:87/128 encap ila 2001:0:87:0 \
     csum-mode neutral-map ident-type use-format

# Configure an ILA LWT route that uses auto checksum neutral mapping
# (no C-bit) and configure identifier type to be LUID so that the
# identifier type field will not be present.
ip route add 3333:0:0:1:2000:0:2:87/128 encap ila 2001:0:87:1 \
     csum-mode neutral-map-auto ident-type luid

ila_xlat configuration

# Configure an ILA to SIR mapping that matches a locator and overwrites
# it with a SIR address (3333:0:0:1 in this example). The C-bit and
# identifier field are used.
ip ila add loc_match 2001:0:119:0 loc 3333:0:0:1 \
    csum-mode neutral-map-auto ident-type use-format

# Configure an ILA to SIR mapping where checksum neutral is automatically
# set without the C-bit and the identifier type is configured to be LUID
# so that the identifier type field is not present.
ip ila add loc_match 2001:0:119:0 loc 3333:0:0:1 \
    csum-mode neutral-map-auto ident-type use-format
```

---

# IOAM6 Sysfs variables

_Peios Kernel / Internals / Networking_

> Accept (= enabled) or ignore (= disabled) IPv6 IOAM options on ingress for this interface.

<a id="rst-ioam6-sysfs-variables"></a>

<a id="rst-proc-sys-net-conf-iface-ioam6-variables"></a>

## /proc/sys/net/conf/&lt;iface&gt;/ioam6\_\* variables:

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **ioam6_enabled - BOOL**

  Accept (= enabled) or ignore (= disabled) IPv6 IOAM options on ingress for this interface.

  - 0 - disabled (default)

  - 1 - enabled

- **ioam6_id - SHORT INTEGER**

  Define the IOAM id of this interface.

  Default is \~0.

- **ioam6_id_wide - INTEGER**

  Define the wide IOAM id of this interface.

  Default is \~0.

---

# io_uring zero copy Rx

_Peios Kernel / Internals / Networking_

> io_uring zero copy Rx (ZC Rx) is a feature that removes kernel-to-user copy on the network receive path, allowing packet data to be received directly into userspace memory. This feature is different to TCP_ZEROCOPY_RECEIVE in that there…

<a id="rst-io-uring-zero-copy-rx"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

io_uring zero copy Rx (ZC Rx) is a feature that removes kernel-to-user copy on the network receive path, allowing packet data to be received directly into userspace memory. This feature is different to TCP_ZEROCOPY_RECEIVE in that there are no strict alignment requirements and no need to mmap()/munmap(). Compared to kernel bypass solutions such as e.g. DPDK, the packet headers are processed by the kernel TCP stack as normal.

<a id="rst-nic-hw-requirements"></a>

## NIC HW Requirements

Several NIC HW features are required for io_uring ZC Rx to work. For now the kernel API does not configure the NIC and it must be done by the user.

<a id="rst-header-data-split"></a>

### Header/data split

Required to split packets at the L4 boundary into a header and a payload. Headers are received into kernel memory as normal and processed by the TCP stack as normal. Payloads are received into userspace memory directly.

<a id="rst-flow-steering"></a>

### Flow steering

Specific HW Rx queues are configured for this feature, but modern NICs typically distribute flows across all HW Rx queues. Flow steering is required to ensure that only desired flows are directed towards HW queues that are configured for io_uring ZC Rx.

<a id="rst-rss"></a>

### RSS

In addition to flow steering above, RSS is required to steer all other non-zero copy flows away from queues that are configured for io_uring ZC Rx.

<a id="rst-usage"></a>

## Usage

<a id="rst-setup-nic"></a>

### Setup NIC

Must be done out of band for now.

Ensure there are at least two queues:



```text
ethtool -L eth0 combined 2
```

Enable header/data split:



```text
ethtool -G eth0 tcp-data-split on
```

Carve out half of the HW Rx queues for zero copy using RSS:



```text
ethtool -X eth0 equal 1
```

Set up flow steering, bearing in mind that queues are 0-indexed:



```text
ethtool -N eth0 flow-type tcp6 ... action 1
```

<a id="rst-setup-io-uring"></a>

### Setup io_uring

This section describes the low level io_uring kernel API. Please refer to liburing documentation for how to use the higher level API.

Create an io_uring instance with the following required setup flags:



```text
IORING_SETUP_SINGLE_ISSUER
IORING_SETUP_DEFER_TASKRUN
IORING_SETUP_CQE32 or IORING_SETUP_CQE_MIXED
```

<a id="rst-create-memory-area"></a>

### Create memory area

Allocate userspace memory area for receiving zero copy data:



```text
void *area_ptr = mmap(NULL, area_size,
                      PROT_READ | PROT_WRITE,
                      MAP_ANONYMOUS | MAP_PRIVATE,
                      0, 0);
```

<a id="rst-create-refill-ring"></a>

### Create refill ring

Allocate memory for a shared ringbuf used for returning consumed buffers:



```text
void *ring_ptr = mmap(NULL, ring_size,
                      PROT_READ | PROT_WRITE,
                      MAP_ANONYMOUS | MAP_PRIVATE,
                      0, 0);
```

This refill ring consists of some space for the header, followed by an array of `struct io_uring_zcrx_rqe`:



```text
size_t rq_entries = 4096;
size_t ring_size = rq_entries * sizeof(struct io_uring_zcrx_rqe) + PAGE_SIZE;
/* align to page size */
ring_size = (ring_size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
```

<a id="rst-register-zc-rx"></a>

### Register ZC Rx

Fill in registration structs:



```text
struct io_uring_zcrx_area_reg area_reg = {
  .addr = (__u64)(unsigned long)area_ptr,
  .len = area_size,
  .flags = 0,
};

struct io_uring_region_desc region_reg = {
  .user_addr = (__u64)(unsigned long)ring_ptr,
  .size = ring_size,
  .flags = IORING_MEM_REGION_TYPE_USER,
};

struct io_uring_zcrx_ifq_reg reg = {
  .if_idx = if_nametoindex("eth0"),
  /* this is the HW queue with desired flow steered into it */
  .if_rxq = 1,
  .rq_entries = rq_entries,
  .area_ptr = (__u64)(unsigned long)&area_reg,
  .region_ptr = (__u64)(unsigned long)&region_reg,
};
```

Register with kernel:



```text
io_uring_register_ifq(ring, &reg);
```

<a id="rst-map-refill-ring"></a>

### Map refill ring

The kernel fills in fields for the refill ring in the registration `struct io_uring_zcrx_ifq_reg`. Map it into userspace:



```text
struct io_uring_zcrx_rq refill_ring;

refill_ring.khead = (unsigned *)((char *)ring_ptr + reg.offsets.head);
refill_ring.khead = (unsigned *)((char *)ring_ptr + reg.offsets.tail);
refill_ring.rqes =
  (struct io_uring_zcrx_rqe *)((char *)ring_ptr + reg.offsets.rqes);
refill_ring.rq_tail = 0;
refill_ring.ring_ptr = ring_ptr;
```

<a id="rst-receiving-data"></a>

### Receiving data

Prepare a zero copy recv request:



```text
struct io_uring_sqe *sqe;

sqe = io_uring_get_sqe(ring);
io_uring_prep_rw(IORING_OP_RECV_ZC, sqe, fd, NULL, 0, 0);
sqe->ioprio |= IORING_RECV_MULTISHOT;
```

Now, submit and wait:



```text
io_uring_submit_and_wait(ring, 1);
```

Finally, process completions:



```text
struct io_uring_cqe *cqe;
unsigned int count = 0;
unsigned int head;

io_uring_for_each_cqe(ring, head, cqe) {
  struct io_uring_zcrx_cqe *rcqe = (struct io_uring_zcrx_cqe *)(cqe + 1);

  unsigned long mask = (1ULL << IORING_ZCRX_AREA_SHIFT) - 1;
  unsigned char *data = area_ptr + (rcqe->off & mask);
  /* do something with the data */

  count++;
}
io_uring_cq_advance(ring, count);
```

<a id="rst-recycling-buffers"></a>

### Recycling buffers

Return buffers back to the kernel to be used again:



```text
struct io_uring_zcrx_rqe *rqe;
unsigned mask = refill_ring.ring_entries - 1;
rqe = &refill_ring.rqes[refill_ring.rq_tail & mask];

unsigned long area_offset = rcqe->off & ~IORING_ZCRX_AREA_MASK;
rqe->off = area_offset | area_reg.rq_area_token;
rqe->len = cqe->res;
IO_URING_WRITE_ONCE(*refill_ring.ktail, ++refill_ring.rq_tail);
```

<a id="rst-area-chunking"></a>

### Area chunking

zcrx splits the memory area into fixed-length physically contiguous chunks. This limits the maximum buffer size returned in a single io_uring CQE. Users can provide a hint to the kernel to use larger chunks by setting the `rx_buf_len` field of `struct io_uring_zcrx_ifq_reg` to the desired length during registration. If this field is set to zero, the kernel defaults to the system page size.

To use larger sizes, the memory area must be backed by physically contiguous ranges whose sizes are multiples of `rx_buf_len`. It also requires kernel and hardware support. If registration fails, users are generally expected to fall back to defaults by setting `rx_buf_len` to zero.

Larger chunks don't give any additional guarantees about buffer sizes returned in CQEs, and they can vary depending on many factors like traffic pattern, hardware offload, etc. It doesn't require any application changes beyond zcrx registration.

<a id="rst-testing"></a>

## Testing

See `tools/testing/selftests/drivers/net/hw/iou-zcrx.c`

---

# IP Sysctl

_Peios Kernel / Internals / Networking_

> Forward Packets between interfaces.

<a id="rst-ip-sysctl"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-proc-sys-net-ipv4-variables"></a>

## /proc/sys/net/ipv4/\* Variables

- **ip_forward - BOOLEAN**

  Forward Packets between interfaces.

  This variable is special, its change resets all configuration parameters to their default state (RFC1122 for hosts, RFC1812 for routers)

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **ip_default_ttl - INTEGER**

  Default value of TTL field (Time To Live) for outgoing (but not forwarded) IP packets. Should be between 1 and 255 inclusive. Default: 64 (as recommended by RFC1700)

- **ip_no_pmtu_disc - INTEGER**

  Disable Path MTU Discovery. If enabled in mode 1 and a fragmentation-required ICMP is received, the PMTU to this destination will be set to the smallest of the old MTU to this destination and min_pmtu (see below). You will need to raise min_pmtu to the smallest interface MTU on your system manually if you want to avoid locally generated fragments.

  In mode 2 incoming Path MTU Discovery messages will be discarded. Outgoing frames are handled the same as in mode 1, implicitly setting IP_PMTUDISC_DONT on every created socket.

  Mode 3 is a hardened pmtu discover mode. The kernel will only accept fragmentation-needed errors if the underlying protocol can verify them besides a plain socket lookup. Current protocols for which pmtu events will be honored are TCP and SCTP as they verify e.g. the sequence number or the association. This mode should not be enabled globally but is only intended to secure e.g. name servers in namespaces where TCP path mtu must still work but path MTU information of other protocols should be discarded. If enabled globally this mode could break other protocols.

  Possible values: 0-3

  Default: FALSE

- **min_pmtu - INTEGER**

  default 552 - minimum Path MTU. Unless this is changed manually, each cached pmtu will never be lower than this setting.

- **ip_forward_use_pmtu - BOOLEAN**

  By default we don't trust protocol path MTUs while forwarding because they could be easily forged and can lead to unwanted fragmentation by the router. You only need to enable this if you have user-space software which tries to discover path mtus by itself and depends on the kernel honoring this information. This is normally not the case.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **fwmark_reflect - BOOLEAN**

  Controls the fwmark of kernel-generated IPv4 reply packets that are not associated with a socket for example, TCP RSTs or ICMP echo replies). If disabled, these packets have a fwmark of zero. If enabled, they have the fwmark of the packet they are replying to.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **fib_multipath_use_neigh - BOOLEAN**

  Use status of existing neighbor entry when determining nexthop for multipath routes. If disabled, neighbor information is not used and packets could be directed to a failed nexthop. Only valid for kernels built with CONFIG_IP_ROUTE_MULTIPATH enabled.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **fib_multipath_hash_policy - INTEGER**

  Controls which hash policy to use for multipath routes. Only valid for kernels built with CONFIG_IP_ROUTE_MULTIPATH enabled.

  Default: 0 (Layer 3)

  Possible values:

  - 0 - Layer 3

  - 1 - Layer 4

  - 2 - Layer 3 or inner Layer 3 if present

  - 3 - Custom multipath hash. Fields used for multipath hash calculation are determined by fib_multipath_hash_fields sysctl

- **fib_multipath_hash_fields - UNSIGNED INTEGER**

  When fib_multipath_hash_policy is set to 3 (custom multipath hash), the fields used for multipath hash calculation are determined by this sysctl.

  This value is a bitmask which enables various fields for multipath hash calculation.

  Possible fields are:


  <table>
  <tbody>
  <tr>
  <td>


  0x0001

  </td>
  <td>


  Source IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0002

  </td>
  <td>


  Destination IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0004

  </td>
  <td>


  IP protocol

  </td>
  </tr>
  <tr>
  <td>


  0x0008

  </td>
  <td>


  Unused (Flow Label)

  </td>
  </tr>
  <tr>
  <td>


  0x0010

  </td>
  <td>


  Source port

  </td>
  </tr>
  <tr>
  <td>


  0x0020

  </td>
  <td>


  Destination port

  </td>
  </tr>
  <tr>
  <td>


  0x0040

  </td>
  <td>


  Inner source IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0080

  </td>
  <td>


  Inner destination IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0100

  </td>
  <td>


  Inner IP protocol

  </td>
  </tr>
  <tr>
  <td>


  0x0200

  </td>
  <td>


  Inner Flow Label

  </td>
  </tr>
  <tr>
  <td>


  0x0400

  </td>
  <td>


  Inner source port

  </td>
  </tr>
  <tr>
  <td>


  0x0800

  </td>
  <td>


  Inner destination port

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x0007 (source IP, destination IP and IP protocol)

- **fib_multipath_hash_seed - UNSIGNED INTEGER**

  The seed value used when calculating hash for multipath routes. Applies to both IPv4 and IPv6 datapath. Only present for kernels built with CONFIG_IP_ROUTE_MULTIPATH enabled.

  When set to 0, the seed value used for multipath routing defaults to an internal random-generated one.

  The actual hashing algorithm is not specified -- there is no guarantee that a next hop distribution effected by a given seed will keep stable across kernel versions.

  Default: 0 (random)

- **fib_sync_mem - UNSIGNED INTEGER**

  Amount of dirty memory from fib entries that can be backlogged before synchronize_rcu is forced.

  Default: 512kB   Minimum: 64kB   Maximum: 64MB

- **ip_forward_update_priority - INTEGER**

  Whether to update SKB priority from "TOS" field in IPv4 header after it is forwarded. The new SKB priority is mapped from TOS field value according to an rt_tos2priority table (see e.g. man tc-prio).

  Default: 1 (Update priority.)

  Possible values:

  - 0 - Do not update priority.

  - 1 - Update priority.

- **route/max_size - INTEGER**

  Maximum number of routes allowed in the kernel.  Increase this when using large numbers of interfaces and/or routes.

  From linux kernel 3.6 onwards, this is deprecated for ipv4 as route cache is no longer used.

  From linux kernel 6.3 onwards, this is deprecated for ipv6 as garbage collection manages cached route entries.

- **neigh/default/gc_thresh1 - INTEGER**

  Minimum number of entries to keep.  Garbage collector will not purge entries if there are fewer than this number.

  Default: 128

- **neigh/default/gc_thresh2 - INTEGER**

  Threshold when garbage collector becomes more aggressive about purging entries. Entries older than 5 seconds will be cleared when over this number.

  Default: 512

- **neigh/default/gc_thresh3 - INTEGER**

  Maximum number of non-PERMANENT neighbor entries allowed.  Increase this when using large numbers of interfaces and when communicating with large numbers of directly-connected peers.

  Default: 1024

- **neigh/default/unres_qlen_bytes - INTEGER**

  The maximum number of bytes which may be used by packets queued for each unresolved address by other network layers. (added in linux 3.3)

  Setting negative value is meaningless and will return error.

  Default: SK_WMEM_DEFAULT, (same as net.core.wmem_default).

  > Exact value depends on architecture and kernel options, but should be enough to allow queuing 256 packets of medium size.

- **neigh/default/unres_qlen - INTEGER**

  The maximum number of packets which may be queued for each unresolved address by other network layers.

  (deprecated in linux 3.3) : use unres_qlen_bytes instead.

  Prior to linux 3.3, the default value is 3 which may cause unexpected packet loss. The current default value is calculated according to default value of unres_qlen_bytes and true size of packet.

  Default: 101

- **neigh/default/interval_probe_time_ms - INTEGER**

  The probe interval for neighbor entries with NTF_MANAGED flag, the min value is 1.

  Default: 5000

- **mtu_expires - INTEGER**

  Time, in seconds, that cached PMTU information is kept.

- **min_adv_mss - INTEGER**

  The advertised MSS depends on the first hop route MTU, but will never be lower than this setting.

- **fib_notify_on_flag_change - INTEGER**

  Whether to emit RTM_NEWROUTE notifications whenever RTM_F_OFFLOAD/ RTM_F_TRAP/RTM_F_OFFLOAD_FAILED flags are changed.

  After installing a route to the kernel, user space receives an acknowledgment, which means the route was installed in the kernel, but not necessarily in hardware. It is also possible for a route already installed in hardware to change its action and therefore its flags. For example, a host route that is trapping packets can be "promoted" to perform decapsulation following the installation of an IPinIP/VXLAN tunnel. The notifications will indicate to user-space the state of the route.

  Default: 0 (Do not emit notifications.)

  Possible values:

  - 0 - Do not emit notifications.

  - 1 - Emit notifications.

  - 2 - Emit notifications only for RTM_F_OFFLOAD_FAILED flag change.

IP Fragmentation:

- **ipfrag_high_thresh - LONG INTEGER**

  Maximum memory used to reassemble IP fragments.

- **ipfrag_low_thresh - LONG INTEGER**

  (Obsolete since linux-4.17) Maximum memory used to reassemble IP fragments before the kernel begins to remove incomplete fragment queues to free up resources. The kernel still accepts new fragments for defragmentation.

- **ipfrag_time - INTEGER**

  Time in seconds to keep an IP fragment in memory.

- **ipfrag_max_dist - INTEGER**

  ipfrag_max_dist is a non-negative integer value which defines the maximum "disorder" which is allowed among fragments which share a common IP source address. Note that reordering of packets is not unusual, but if a large number of fragments arrive from a source IP address while a particular fragment queue remains incomplete, it probably indicates that one or more fragments belonging to that queue have been lost. When ipfrag_max_dist is positive, an additional check is done on fragments before they are added to a reassembly queue - if ipfrag_max_dist (or more) fragments have arrived from a particular IP address between additions to any IP fragment queue using that source address, it's presumed that one or more fragments in the queue are lost. The existing fragment queue will be dropped, and a new one started. An ipfrag_max_dist value of zero disables this check.

  Using a very small value, e.g. 1 or 2, for ipfrag_max_dist can result in unnecessarily dropping fragment queues when normal reordering of packets occurs, which could lead to poor application performance. Using a very large value, e.g. 50000, increases the likelihood of incorrectly reassembling IP fragments that originate from different IP datagrams, which could result in data corruption. Default: 64

- **bc_forwarding - INTEGER**

  bc_forwarding enables the feature described in rfc1812\#section-5.3.5.2 and rfc2644. It allows the router to forward directed broadcast. To enable this feature, the 'all' entry and the input interface entry should be set to 1. Default: 0

<a id="rst-inet-peer-storage"></a>

## INET peer storage

- **inet_peer_threshold - INTEGER**

  The approximate size of the storage.  Starting from this threshold entries will be thrown aggressively.  This threshold also determines entries' time-to-live and time intervals between garbage collection passes.  More entries, less time-to-live, less GC interval.

- **inet_peer_minttl - INTEGER**

  Minimum time-to-live of entries.  Should be enough to cover fragment time-to-live on the reassembling side.  This minimum time-to-live  is guaranteed if the pool size is less than inet_peer_threshold. Measured in seconds.

- **inet_peer_maxttl - INTEGER**

  Maximum time-to-live of entries.  Unused entries will expire after this period of time if there is no memory pressure on the pool (i.e. when the number of entries in the pool is very small). Measured in seconds.

<a id="rst-tcp-variables"></a>

## TCP variables

- **somaxconn - INTEGER**

  Limit of socket listen() backlog, known in userspace as SOMAXCONN. Defaults to 4096. (Was 128 before linux-5.4) See also tcp_max_syn_backlog for additional tuning for TCP sockets.

- **tcp_abort_on_overflow - BOOLEAN**

  If listening service is too slow to accept new connections, reset them. Default state is FALSE. It means that if overflow occurred due to a burst, connection will recover. Enable this option \_only\_ if you are really sure that listening daemon cannot be tuned to accept connections faster. Enabling this option can harm clients of your server.

- **tcp_adv_win_scale - INTEGER**

  Obsolete since linux-6.6 Count buffering overhead as bytes/2^tcp_adv_win_scale (if tcp_adv_win_scale &gt; 0) or bytes-bytes/2^(-tcp_adv_win_scale), if it is &lt;= 0.

  Possible values are \[-31, 31\], inclusive.

  Default: 1

- **tcp_allowed_congestion_control - STRING**

  Show/set the congestion control choices available to non-privileged processes. The list is a subset of those listed in tcp_available_congestion_control.

  Default is "reno" and the default setting (tcp_congestion_control).

- **tcp_app_win - INTEGER**

  Reserve max(window/2^tcp_app_win, mss) of window for application buffer. Value 0 is special, it means that nothing is reserved.

  Possible values are \[0, 31\], inclusive.

  Default: 31

- **tcp_autocorking - BOOLEAN**

  Enable TCP auto corking : When applications do consecutive small write()/sendmsg() system calls, we try to coalesce these small writes as much as possible, to lower total amount of sent packets. This is done if at least one prior packet for the flow is waiting in Qdisc queues or device transmit queue. Applications can still use TCP_CORK for optimal behavior when they know how/when to uncork their sockets.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_available_congestion_control - STRING**

  Shows the available congestion control choices that are registered. More congestion control algorithms may be available as modules, but not loaded.

- **tcp_base_mss - INTEGER**

  The initial value of search_low to be used by the packetization layer Path MTU discovery (MTU probing).  If MTU probing is enabled, this is the initial MSS used by the connection.

- **tcp_mtu_probe_floor - INTEGER**

  If MTU probing is enabled this caps the minimum MSS used for search_low for the connection.

  Default : 48

- **tcp_min_snd_mss - INTEGER**

  TCP SYN and SYNACK messages usually advertise an ADVMSS option, as described in RFC 1122 and RFC 6691.

  If this ADVMSS option is smaller than tcp_min_snd_mss, it is silently capped to tcp_min_snd_mss.

  Default : 48 (at least 8 bytes of payload per segment)

- **tcp_congestion_control - STRING**

  Set the congestion control algorithm to be used for new connections. The algorithm "reno" is always available, but additional choices may be available based on kernel configuration. Default is set as part of kernel configuration. For passive connections, the listener congestion control choice is inherited.

  \[see setsockopt(listenfd, SOL_TCP, TCP_CONGESTION, "name" ...) \]

- **tcp_dsack - BOOLEAN**

  Allows TCP to send "duplicate" SACKs.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_early_retrans - INTEGER**

  Tail loss probe (TLP) converts RTOs occurring due to tail losses into fast recovery (RFC8985). Note that TLP requires RACK to function properly (see tcp_recovery below)

  Possible values:

  > - 0 disables TLP
  >
  > - 3 or 4 enables TLP

  Default: 3

- **tcp_ecn - INTEGER**

  Control use of Explicit Congestion Notification (ECN) by TCP. ECN is used only when both ends of the TCP connection indicate support for it. This feature is useful in avoiding losses due to congestion by allowing supporting routers to signal congestion before having to drop packets. A host that supports ECN both sends ECN at the IP layer and feeds back ECN at the TCP layer. The highest variant of ECN feedback that both peers support is chosen by the ECN negotiation (Accurate ECN, ECN, or no ECN).

  The highest negotiated variant for incoming connection requests and the highest variant requested by outgoing connection attempts:


  <table>
  <thead>
  <tr>
  <th>


  Value

  </th>
  <th>


  Incoming connections

  </th>
  <th>


  Outgoing connections

  </th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  No ECN

  </td>
  <td>


  No ECN

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  ECN

  </td>
  <td>


  ECN

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  ECN

  </td>
  <td>


  No ECN

  </td>
  </tr>
  <tr>
  <td>


  3

  </td>
  <td>


  AccECN

  </td>
  <td>


  AccECN

  </td>
  </tr>
  <tr>
  <td>


  4

  </td>
  <td>


  AccECN

  </td>
  <td>


  ECN

  </td>
  </tr>
  <tr>
  <td>


  5

  </td>
  <td>


  AccECN

  </td>
  <td>


  No ECN

  </td>
  </tr>
  </tbody>
  </table>

  Default: 2

- **tcp_ecn_option - INTEGER**

  Control Accurate ECN (AccECN) option sending when AccECN has been successfully negotiated during handshake. Send logic inhibits sending AccECN options regarless of this setting when no AccECN option has been seen for the reverse direction.

  Possible values are:


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  Never send AccECN option. This also disables sending AccECN option in SYN/ACK during handshake.

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  Send AccECN option sparingly according to the minimum option rules outlined in draft-ietf-tcpm-accurate-ecn.

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  Send AccECN option on every packet whenever it fits into TCP option space except when AccECN fallback is triggered.

  </td>
  </tr>
  <tr>
  <td>


  3

  </td>
  <td>


  Send AccECN option on every packet whenever it fits into TCP option space even when AccECN fallback is triggered.

  </td>
  </tr>
  </tbody>
  </table>

  Default: 2

- **tcp_ecn_option_beacon - INTEGER**

  Control Accurate ECN (AccECN) option sending frequency per RTT and it takes effect only when tcp_ecn_option is set to 2.

  Default: 3 (AccECN will be send at least 3 times per RTT)

- **tcp_ecn_fallback - BOOLEAN**

  If the kernel detects that ECN connection misbehaves, enable fall back to non-ECN. Currently, this knob implements the fallback from RFC3168, section 6.1.1.1., but we reserve that in future, additional detection mechanisms could be implemented under this knob. The value is not used, if tcp_ecn or per route (or congestion control) ECN settings are disabled.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_fack - BOOLEAN**

  This is a legacy option, it has no effect anymore.

- **tcp_fin_timeout - INTEGER**

  The length of time an orphaned (no longer referenced by any application) connection will remain in the FIN_WAIT_2 state before it is aborted at the local end.  While a perfectly valid "receive only" state for an un-orphaned connection, an orphaned connection in FIN_WAIT_2 state could otherwise wait forever for the remote to close its end of the connection.

  Cf. tcp_max_orphans

  Default: 60 seconds

- **tcp_frto - INTEGER**

  Enables Forward RTO-Recovery (F-RTO) defined in RFC5682. F-RTO is an enhanced recovery algorithm for TCP retransmission timeouts.  It is particularly beneficial in networks where the RTT fluctuates (e.g., wireless). F-RTO is sender-side only modification. It does not require any support from the peer.

  By default it's enabled with a non-zero value. 0 disables F-RTO.

- **tcp_fwmark_accept - BOOLEAN**

  If enabled, incoming connections to listening sockets that do not have a socket mark will set the mark of the accepting socket to the fwmark of the incoming SYN packet. This will cause all packets on that connection (starting from the first SYNACK) to be sent with that fwmark. The listening socket's mark is unchanged. Listening sockets that already have a fwmark set via setsockopt(SOL_SOCKET, SO_MARK, ...) are unaffected.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_invalid_ratelimit - INTEGER**

  Limit the maximal rate for sending duplicate acknowledgments in response to incoming TCP packets that are for an existing connection but that are invalid due to any of these reasons:

  > - **(a)** out-of-window sequence number,
  >
  > - **(b)** out-of-window acknowledgment number, or
  >
  > - **(c)** PAWS (Protection Against Wrapped Sequence numbers) check failure

  This can help mitigate simple "ack loop" DoS attacks, wherein a buggy or malicious middlebox or man-in-the-middle can rewrite TCP header fields in manner that causes each endpoint to think that the other is sending invalid TCP segments, thus causing each side to send an unterminating stream of duplicate acknowledgments for invalid segments.

  Using 0 disables rate-limiting of dupacks in response to invalid segments; otherwise this value specifies the minimal space between sending such dupacks, in milliseconds.

  Default: 500 (milliseconds).

- **tcp_keepalive_time - INTEGER**

  How often TCP sends out keepalive messages when keepalive is enabled. Default: 2hours.

- **tcp_keepalive_probes - INTEGER**

  How many keepalive probes TCP sends out, until it decides that the connection is broken. Default value: 9.

- **tcp_keepalive_intvl - INTEGER**

  How frequently the probes are send out. Multiplied by tcp_keepalive_probes it is time to kill not responding connection, after probes started. Default value: 75sec i.e. connection will be aborted after \~11 minutes of retries.

- **tcp_l3mdev_accept - BOOLEAN**

  Enables child sockets to inherit the L3 master device index. Enabling this option allows a "global" listen socket to work across L3 master domains (e.g., VRFs) with connected sockets derived from the listen socket to be bound to the L3 domain in which the packets originated. Only valid when the kernel was compiled with CONFIG_NET_L3_MASTER_DEV.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_low_latency - BOOLEAN**

  This is a legacy option, it has no effect anymore.

- **tcp_max_orphans - INTEGER**

  Maximal number of TCP sockets not attached to any user file handle, held by system. If this number is exceeded orphaned connections are reset immediately and warning is printed. This limit exists only to prevent simple DoS attacks, you \_must\_ not rely on this or lower the limit artificially, but rather increase it (probably, after increasing installed memory), if network conditions require more than default value, and tune network services to linger and kill such states more aggressively. Let me to remind again: each orphan eats up to \~64K of unswappable memory.

- **tcp_max_syn_backlog - INTEGER**

  Maximal number of remembered connection requests (SYN_RECV), which have not received an acknowledgment from connecting client.

  This is a per-listener limit.

  The minimal value is 128 for low memory machines, and it will increase in proportion to the memory of machine.

  If server suffers from overload, try increasing this number.

  Remember to also check /proc/sys/net/core/somaxconn A SYN_RECV request socket consumes about 304 bytes of memory.

- **tcp_max_tw_buckets - INTEGER**

  Maximal number of timewait sockets held by system simultaneously. If this number is exceeded time-wait socket is immediately destroyed and warning is printed. This limit exists only to prevent simple DoS attacks, you \_must\_ not lower the limit artificially, but rather increase it (probably, after increasing installed memory), if network conditions require more than default value.

- **tcp_mem - vector of 3 INTEGERs: min, pressure, max**

  min: below this number of pages TCP is not bothered about its memory appetite.

  pressure: when amount of memory allocated by TCP exceeds this number of pages, TCP moderates its memory consumption and enters memory pressure mode, which is exited when memory consumption falls under "min".

  max: number of pages allowed for queueing by all TCP sockets.

  Defaults are calculated at boot time from amount of available memory.

- **tcp_min_rtt_wlen - INTEGER**

  The window length of the windowed min filter to track the minimum RTT. A shorter window lets a flow more quickly pick up new (higher) minimum RTT when it is moved to a longer path (e.g., due to traffic engineering). A longer window makes the filter more resistant to RTT inflations such as transient congestion. The unit is seconds.

  Possible values: 0 - 86400 (1 day)

  Default: 300

- **tcp_moderate_rcvbuf - BOOLEAN**

  If enabled, TCP performs receive buffer auto-tuning, attempting to automatically size the buffer (no greater than tcp_rmem\[2\]) to match the size required by the path for full throughput.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_rcvbuf_low_rtt - INTEGER**

  rcvbuf autotuning can over estimate final socket rcvbuf, which can lead to cache trashing for high throughput flows.

  For small RTT flows (below tcp_rcvbuf_low_rtt usecs), we can relax rcvbuf growth: Few additional ms to reach the final (and smaller) rcvbuf is a good tradeoff.

  Default : 1000 (1 ms)

- **tcp_mtu_probing - INTEGER**

  Controls TCP Packetization-Layer Path MTU Discovery.  Takes three values:

  - 0 - Disabled

  - 1 - Disabled by default, enabled when an ICMP black hole detected

  - 2 - Always enabled, use initial MSS of tcp_base_mss.

- **tcp_probe_interval - UNSIGNED INTEGER**

  Controls how often to start TCP Packetization-Layer Path MTU Discovery reprobe. The default is reprobing every 10 minutes as per RFC4821.

- **tcp_probe_threshold - INTEGER**

  Controls when TCP Packetization-Layer Path MTU Discovery probing will stop in respect to the width of search range in bytes. Default is 8 bytes.

- **tcp_no_metrics_save - BOOLEAN**

  By default, TCP saves various connection metrics in the route cache when the connection closes, so that connections established in the near future can use these to set initial conditions.  Usually, this increases overall performance, but may sometimes cause performance degradation.  If enabled, TCP will not cache metrics on closing connections.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_no_ssthresh_metrics_save - BOOLEAN**

  Controls whether TCP saves ssthresh metrics in the route cache. If enabled, ssthresh metrics are disabled.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_orphan_retries - INTEGER**

  This value influences the timeout of a locally closed TCP connection, when RTO retransmissions remain unacknowledged. See tcp_retries2 for more details.

  The default value is 8.

  If your machine is a loaded WEB server, you should think about lowering this value, such sockets may consume significant resources. Cf. tcp_max_orphans.

- **tcp_recovery - INTEGER**

  This value is a bitmap to enable various experimental loss recovery features.


  <table>
  <tbody>
  <tr>
  <td>


  RACK: 0x1

  </td>
  <td>


  enables RACK loss detection, for fast detection of lost retransmissions and tail drops, and resilience to reordering. currently, setting this bit to 0 has no effect, since RACK is the only supported loss detection algorithm.

  </td>
  </tr>
  <tr>
  <td>


  RACK: 0x2

  </td>
  <td>


  makes RACK's reordering window static (min_rtt/4).

  </td>
  </tr>
  <tr>
  <td>


  RACK: 0x4

  </td>
  <td>


  disables RACK's DUPACK threshold heuristic

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x1

- **tcp_reflect_tos - BOOLEAN**

  For listening sockets, reuse the DSCP value of the initial SYN message for outgoing packets. This allows to have both directions of a TCP stream to use the same DSCP value, assuming DSCP remains unchanged for the lifetime of the connection.

  This options affects both IPv4 and IPv6.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_reordering - INTEGER**

  Initial reordering level of packets in a TCP stream. TCP stack can then dynamically adjust flow reordering level between this initial value and tcp_max_reordering

  Default: 3

- **tcp_max_reordering - INTEGER**

  Maximal reordering level of packets in a TCP stream. 300 is a fairly conservative value, but you might increase it if paths are using per packet load balancing (like bonding rr mode)

  Default: 300

- **tcp_retrans_collapse - BOOLEAN**

  Bug-to-bug compatibility with some broken printers. On retransmit try to send bigger packets to work around bugs in certain TCP stacks.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_retries1 - INTEGER**

  This value influences the time, after which TCP decides, that something is wrong due to unacknowledged RTO retransmissions, and reports this suspicion to the network layer. See tcp_retries2 for more details.

  RFC 1122 recommends at least 3 retransmissions, which is the default.

- **tcp_retries2 - INTEGER**

  This value influences the timeout of an alive TCP connection, when RTO retransmissions remain unacknowledged. Given a value of N, a hypothetical TCP connection following exponential backoff with an initial RTO of TCP_RTO_MIN would retransmit N times before killing the connection at the (N+1)th RTO.

  The default value of 15 yields a hypothetical timeout of 924.6 seconds and is a lower bound for the effective timeout. TCP will effectively time out at the first RTO which exceeds the hypothetical timeout. If tcp_rto_max_ms is decreased, it is recommended to also change tcp_retries2.

  RFC 1122 recommends at least 100 seconds for the timeout, which corresponds to a value of at least 8.

- **tcp_rfc1337 - BOOLEAN**

  If enabled, the TCP stack behaves conforming to RFC1337. If unset, we are not conforming to RFC, but prevent TCP TIME_WAIT assassination.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_rmem - vector of 3 INTEGERs: min, default, max**

  min: Minimal size of receive buffer used by TCP sockets. It is guaranteed to each TCP socket, even under moderate memory pressure.

  Default: 4K

  default: initial size of receive buffer used by TCP sockets. This value overrides net.core.rmem_default used by other protocols. Default: 131072 bytes. This value results in initial window of 65535.

  max: maximal size of receive buffer allowed for automatically selected receiver buffers for TCP socket. Calling setsockopt() with SO_RCVBUF disables automatic tuning of that socket's receive buffer size, in which case this value is ignored. Default: between 131072 and 32MB, depending on RAM size.

- **tcp_sack - BOOLEAN**

  Enable select acknowledgments (SACKS).

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_comp_sack_rtt_percent - INTEGER**

  Percentage of SRTT used for the compressed SACK feature. See tcp_comp_sack_nr, tcp_comp_sack_delay_ns, tcp_comp_sack_slack_ns.

  Possible values : 1 - 1000

  Default : 33 %

- **tcp_comp_sack_delay_ns - LONG INTEGER**

  TCP tries to reduce number of SACK sent, using a timer based on tcp_comp_sack_rtt_percent of SRTT, capped by this sysctl in nano seconds. The default is 1ms, based on TSO autosizing period.

  Default : 1,000,000 ns (1 ms)

- **tcp_comp_sack_slack_ns - LONG INTEGER**

  This sysctl control the slack used when arming the timer used by SACK compression. This gives extra time for small RTT flows, and reduces system overhead by allowing opportunistic reduction of timer interrupts. Too big values might reduce goodput.

  Default : 10,000 ns (10 us)

- **tcp_comp_sack_nr - INTEGER**

  Max number of SACK that can be compressed. Using 0 disables SACK compression.

  Default : 44

- **tcp_backlog_ack_defer - BOOLEAN**

  If enabled, user thread processing socket backlog tries sending one ACK for the whole queue. This helps to avoid potential long latencies at end of a TCP socket syscall.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_slow_start_after_idle - BOOLEAN**

  If enabled, provide RFC2861 behavior and time out the congestion window after an idle period.  An idle period is defined at the current RTO.  If unset, the congestion window will not be timed out after an idle period.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_stdurg - BOOLEAN**

  Use the Host requirements interpretation of the TCP urgent pointer field. Most hosts use the older BSD interpretation, so if enabled, Linux might not communicate correctly with them.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_synack_retries - INTEGER**

  Number of times SYNACKs for a passive TCP connection attempt will be retransmitted. Should not be higher than 255. Default value is 5, which corresponds to 31seconds till the last retransmission with the current initial RTO of 1second. With this the final timeout for a passive TCP connection will happen after 63seconds.

- **tcp_syncookies - INTEGER**

  Only valid when the kernel was compiled with CONFIG_SYN_COOKIES Send out syncookies when the syn backlog queue of a socket overflows. This is to prevent against the common 'SYN flood attack' Default: 1

  Note, that syncookies is fallback facility. It MUST NOT be used to help highly loaded servers to stand against legal connection rate. If you see SYN flood warnings in your logs, but investigation shows that they occur because of overload with legal connections, you should tune another parameters until this warning disappear. See: tcp_max_syn_backlog, tcp_synack_retries, tcp_abort_on_overflow.

  syncookies seriously violate TCP protocol, do not allow to use TCP extensions, can result in serious degradation of some services (f.e. SMTP relaying), visible not by you, but your clients and relays, contacting you. While you see SYN flood warnings in logs not being really flooded, your server is seriously misconfigured.

  If you want to test which effects syncookies have to your network connections you can set this knob to 2 to enable unconditionally generation of syncookies.

- **tcp_migrate_req - BOOLEAN**

  The incoming connection is tied to a specific listening socket when the initial SYN packet is received during the three-way handshake. When a listener is closed, in-flight request sockets during the handshake and established sockets in the accept queue are aborted.

  If the listener has SO_REUSEPORT enabled, other listeners on the same port should have been able to accept such connections. This option makes it possible to migrate such child sockets to another listener after close() or shutdown().

  The BPF_SK_REUSEPORT_SELECT_OR_MIGRATE type of eBPF program should usually be used to define the policy to pick an alive listener. Otherwise, the kernel will randomly pick an alive listener only if this option is enabled.

  Note that migration between listeners with different settings may crash applications. Let's say migration happens from listener A to B, and only B has TCP_SAVE_SYN enabled. B cannot read SYN data from the requests migrated from A. To avoid such a situation, cancel migration by returning SK_DROP in the type of eBPF program, or disable this option.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_fastopen - INTEGER**

  Enable TCP Fast Open (RFC7413) to send and accept data in the opening SYN packet.

  The client support is enabled by flag 0x1 (on by default). The client then must use sendmsg() or sendto() with the MSG_FASTOPEN flag, rather than connect() to send data in SYN.

  The server support is enabled by flag 0x2 (off by default). Then either enable for all listeners with another flag (0x400) or enable individual listeners via TCP_FASTOPEN socket option with the option value being the length of the syn-data backlog.

  The values (bitmap) are


  <table>
  <tbody>
  <tr>
  <td>


  0x1

  </td>
  <td>


  (client)

  </td>
  <td>


  enables sending data in the opening SYN on the client.

  </td>
  </tr>
  <tr>
  <td>


  0x2

  </td>
  <td>


  (server)

  </td>
  <td>


  enables the server support, i.e., allowing data in a SYN packet to be accepted and passed to the application before 3-way handshake finishes.

  </td>
  </tr>
  <tr>
  <td>


  0x4

  </td>
  <td>


  (client)

  </td>
  <td>


  send data in the opening SYN regardless of cookie availability and without a cookie option.

  </td>
  </tr>
  <tr>
  <td>


  0x200

  </td>
  <td>


  (server)

  </td>
  <td>


  accept data-in-SYN w/o any cookie option present.

  </td>
  </tr>
  <tr>
  <td>


  0x400

  </td>
  <td>


  (server)

  </td>
  <td>


  enable all listeners to support Fast Open by default without explicit TCP_FASTOPEN socket option.

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x1

  Note that additional client or server features are only effective if the basic support (0x1 and 0x2) are enabled respectively.

- **tcp_fastopen_blackhole_timeout_sec - INTEGER**

  Initial time period in second to disable Fastopen on active TCP sockets when a TFO firewall blackhole issue happens. This time period will grow exponentially when more blackhole issues get detected right after Fastopen is re-enabled and will reset to initial value when the blackhole issue goes away. 0 to disable the blackhole detection.

  By default, it is set to 0 (feature is disabled).

- **tcp_fastopen_key - list of comma separated 32-digit hexadecimal INTEGERs**

  The list consists of a primary key and an optional backup key. The primary key is used for both creating and validating cookies, while the optional backup key is only used for validating cookies. The purpose of the backup key is to maximize TFO validation when keys are rotated.

  A randomly chosen primary key may be configured by the kernel if the tcp_fastopen sysctl is set to 0x400 (see above), or if the TCP_FASTOPEN setsockopt() optname is set and a key has not been previously configured via sysctl. If keys are configured via setsockopt() by using the TCP_FASTOPEN_KEY optname, then those per-socket keys will be used instead of any keys that are specified via sysctl.

  A key is specified as 4 8-digit hexadecimal integers which are separated by a '-' as: xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx. Leading zeros may be omitted. A primary and a backup key may be specified by separating them by a comma. If only one key is specified, it becomes the primary key and any previously configured backup keys are removed.

- **tcp_syn_retries - INTEGER**

  Number of times initial SYNs for an active TCP connection attempt will be retransmitted. Should not be higher than 127. Default value is 6, which corresponds to 67seconds (with tcp_syn_linear_timeouts = 4) till the last retransmission with the current initial RTO of 1second. With this the final timeout for an active TCP connection attempt will happen after 131seconds.

- **tcp_timestamps - INTEGER**

  Enable timestamps as defined in RFC1323.

  - 0: Disabled.

  - 1: Enable timestamps as defined in RFC1323 and use random offset for each connection rather than only using the current time.

  - 2: Like 1, but without random offsets.

  Default: 1

- **tcp_min_tso_segs - INTEGER**

  Minimal number of segments per TSO frame.

  Since linux-3.12, TCP does an automatic sizing of TSO frames, depending on flow rate, instead of filling 64Kbytes packets. For specific usages, it's possible to force TCP to build big TSO frames. Note that TCP stack might split too big TSO packets if available window is too small.

  Default: 2

- **tcp_tso_rtt_log - INTEGER**

  Adjustment of TSO packet sizes based on min_rtt

  Starting from linux-5.18, TCP autosizing can be tweaked for flows having small RTT.

  Old autosizing was splitting the pacing budget to send 1024 TSO per second.

  tso_packet_size = sk-&gt;sk_pacing_rate / 1024;

  With the new mechanism, we increase this TSO sizing using:

  distance = min_rtt_usec / (2^tcp_tso_rtt_log) tso_packet_size += gso_max_size &gt;&gt; distance;

  This means that flows between very close hosts can use bigger TSO packets, reducing their cpu costs.

  If you want to use the old autosizing, set this sysctl to 0.

  Default: 9  (2^9 = 512 usec)

- **tcp_pacing_ss_ratio - INTEGER**

  sk-&gt;sk_pacing_rate is set by TCP stack using a ratio applied to current rate. (current_rate = cwnd \* mss / srtt) If TCP is in slow start, tcp_pacing_ss_ratio is applied to let TCP probe for bigger speeds, assuming cwnd can be doubled every other RTT.

  Default: 200

- **tcp_pacing_ca_ratio - INTEGER**

  sk-&gt;sk_pacing_rate is set by TCP stack using a ratio applied to current rate. (current_rate = cwnd \* mss / srtt) If TCP is in congestion avoidance phase, tcp_pacing_ca_ratio is applied to conservatively probe for bigger throughput.

  Default: 120

- **tcp_syn_linear_timeouts - INTEGER**

  The number of times for an active TCP connection to retransmit SYNs with a linear backoff timeout before defaulting to an exponential backoff timeout. This has no effect on SYNACK at the passive TCP side.

  With an initial RTO of 1 and tcp_syn_linear_timeouts = 4 we would expect SYN RTOs to be: 1, 1, 1, 1, 1, 2, 4, ... (4 linear timeouts, and the first exponential backoff using 2^0 \* initial_RTO). Default: 4

- **tcp_tso_win_divisor - INTEGER**

  This allows control over what percentage of the congestion window can be consumed by a single TSO frame. The setting of this parameter is a choice between burstiness and building larger TSO frames.

  Default: 3

- **tcp_tw_reuse - INTEGER**

  Enable reuse of TIME-WAIT sockets for new connections when it is safe from protocol viewpoint.

  - 0 - disable

  - 1 - global enable

  - 2 - enable for loopback traffic only

  It should not be changed without advice/request of technical experts.

  Default: 2

- **tcp_tw_reuse_delay - UNSIGNED INTEGER**

  The delay in milliseconds before a TIME-WAIT socket can be reused by a new connection, if TIME-WAIT socket reuse is enabled. The actual reuse threshold is within \[N, N+1\] range, where N is the requested delay in milliseconds, to ensure the delay interval is never shorter than the configured value.

  This setting contains an assumption about the other TCP timestamp clock tick interval. It should not be set to a value lower than the peer's clock tick for PAWS (Protection Against Wrapped Sequence numbers) mechanism work correctly for the reused connection.

  Default: 1000 (milliseconds)

- **tcp_window_scaling - BOOLEAN**

  Enable window scaling as defined in RFC1323.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **tcp_shrink_window - BOOLEAN**

  This changes how the TCP receive window is calculated.

  RFC 7323, section 2.4, says there are instances when a retracted window can be offered, and that TCP implementations MUST ensure that they handle a shrinking window, as specified in RFC 1122.

  Possible values:

  - 0 (disabled) - The window is never shrunk.

  - 1 (enabled)  - The window is shrunk when necessary to remain within the memory limit set by autotuning (sk_rcvbuf). This only occurs if a non-zero receive window scaling factor is also in effect.

  Default: 0 (disabled)

- **tcp_wmem - vector of 3 INTEGERs: min, default, max**

  min: Amount of memory reserved for send buffers for TCP sockets. Each TCP socket has rights to use it due to fact of its birth.

  Default: 4K

  default: initial size of send buffer used by TCP sockets.  This value overrides net.core.wmem_default used by other protocols.

  It is usually lower than net.core.wmem_default.

  Default: 16K

  max: Maximal amount of memory allowed for automatically tuned send buffers for TCP sockets. This value does not override net.core.wmem_max.  Calling setsockopt() with SO_SNDBUF disables automatic tuning of that socket's send buffer size, in which case this value is ignored.

  Default: between 64K and 4MB, depending on RAM size.

- **tcp_notsent_lowat - UNSIGNED INTEGER**

  A TCP socket can control the amount of unsent bytes in its write queue, thanks to TCP_NOTSENT_LOWAT socket option. poll()/select()/epoll() reports POLLOUT events if the amount of unsent bytes is below a per socket value, and if the write queue is not full. sendmsg() will also not add new buffers if the limit is hit.

  This global variable controls the amount of unsent data for sockets not using TCP_NOTSENT_LOWAT. For these sockets, a change to the global variable has immediate effect.

  Default: UINT_MAX (0xFFFFFFFF)

- **tcp_workaround_signed_windows - BOOLEAN**

  If enabled, assume no receipt of a window scaling option means the remote TCP is broken and treats the window as a signed quantity. If disabled, assume the remote TCP is not broken even if we do not receive a window scaling option from them.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_thin_linear_timeouts - BOOLEAN**

  Enable dynamic triggering of linear timeouts for thin streams. If enabled, a check is performed upon retransmission by timeout to determine if the stream is thin (less than 4 packets in flight). As long as the stream is found to be thin, up to 6 linear timeouts may be performed before exponential backoff mode is initiated. This improves retransmission latency for non-aggressive thin streams, often found to be time-dependent. For more information on thin streams, see [Documentation/networking/tcp-thin.rst](/kernel/internals/networking/tcp-thin.md)

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_limit_output_bytes - INTEGER**

  Controls TCP Small Queue limit per tcp socket. TCP bulk sender tends to increase packets in flight until it gets losses notifications. With SNDBUF autotuning, this can result in a large amount of packets queued on the local machine (e.g.: qdiscs, CPU backlog, or device) hurting latency of other flows, for typical pfifo_fast qdiscs.  tcp_limit_output_bytes limits the number of bytes on qdisc or device to reduce artificial RTT/cwnd and reduce bufferbloat.

  Default: 4194304 (4 MB)

- **tcp_challenge_ack_limit - INTEGER**

  Limits number of Challenge ACK sent per second, as recommended in RFC 5961 (Improving TCP's Robustness to Blind In-Window Attacks) Note that this per netns rate limit can allow some side channel attacks and probably should not be enabled. TCP stack implements per TCP socket limits anyway. Default: INT_MAX (unlimited)

- **tcp_ehash_entries - INTEGER**

  Show the number of hash buckets for TCP sockets in the current networking namespace.

  A negative value means the networking namespace does not own its hash buckets and shares the initial networking namespace's one.

- **tcp_child_ehash_entries - INTEGER**

  Control the number of hash buckets for TCP sockets in the child networking namespace, which must be set before clone() or unshare().

  If the value is not 0, the kernel uses a value rounded up to 2^n as the actual hash bucket size.  0 is a special value, meaning the child networking namespace will share the initial networking namespace's hash buckets.

  Note that the child will use the global one in case the kernel fails to allocate enough memory.  In addition, the global hash buckets are spread over available NUMA nodes, but the allocation of the child hash table depends on the current process's NUMA policy, which could result in performance differences.

  Note also that the default value of tcp_max_tw_buckets and tcp_max_syn_backlog depend on the hash bucket size.

  Possible values: 0, 2^n (n: 0 - 24 (16Mi))

  Default: 0

- **tcp_plb_enabled - BOOLEAN**

  If enabled and the underlying congestion control (e.g. DCTCP) supports and enables PLB feature, TCP PLB (Protective Load Balancing) is enabled. PLB is described in the following paper: [https://doi.org/10.1145/3544216.3544226](<https://doi.org/10.1145/3544216.3544226>). Based on PLB parameters, upon sensing sustained congestion, TCP triggers a change in flow label field for outgoing IPv6 packets. A change in flow label field potentially changes the path of outgoing packets for switches that use ECMP/WCMP for routing.

  PLB changes socket txhash which results in a change in IPv6 Flow Label field, and currently no-op for IPv4 headers. It is possible to apply PLB for IPv4 with other network header fields (e.g. TCP or IPv4 options) or using encapsulation where outer header is used by switches to determine next hop. In either case, further host and switch side changes will be needed.

  If enabled, PLB assumes that congestion signal (e.g. ECN) is made available and used by congestion control module to estimate a congestion measure (e.g. ce_ratio). PLB needs a congestion measure to make repathing decisions.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tcp_plb_idle_rehash_rounds - INTEGER**

  Number of consecutive congested rounds (RTT) seen after which a rehash can be performed, given there are no packets in flight. This is referred to as M in PLB paper: [https://doi.org/10.1145/3544216.3544226](<https://doi.org/10.1145/3544216.3544226>).

  Possible Values: 0 - 31

  Default: 3

- **tcp_plb_rehash_rounds - INTEGER**

  Number of consecutive congested rounds (RTT) seen after which a forced rehash can be performed. Be careful when setting this parameter, as a small value increases the risk of retransmissions. This is referred to as N in PLB paper: [https://doi.org/10.1145/3544216.3544226](<https://doi.org/10.1145/3544216.3544226>).

  Possible Values: 0 - 31

  Default: 12

- **tcp_plb_suspend_rto_sec - INTEGER**

  Time, in seconds, to suspend PLB in event of an RTO. In order to avoid having PLB repath onto a connectivity "black hole", after an RTO a TCP connection suspends PLB repathing for a random duration between 1x and 2x of this parameter. Randomness is added to avoid concurrent rehashing of multiple TCP connections. This should be set corresponding to the amount of time it takes to repair a failed link.

  Possible Values: 0 - 255

  Default: 60

- **tcp_plb_cong_thresh - INTEGER**

  Fraction of packets marked with congestion over a round (RTT) to tag that round as congested. This is referred to as K in the PLB paper: [https://doi.org/10.1145/3544216.3544226](<https://doi.org/10.1145/3544216.3544226>).

  The 0-1 fraction range is mapped to 0-256 range to avoid floating point operations. For example, 128 means that if at least 50% of the packets in a round were marked as congested then the round will be tagged as congested.

  Setting threshold to 0 means that PLB repaths every RTT regardless of congestion. This is not intended behavior for PLB and should be used only for experimentation purpose.

  Possible Values: 0 - 256

  Default: 128

- **tcp_pingpong_thresh - INTEGER**

  The number of estimated data replies sent for estimated incoming data requests that must happen before TCP considers that a connection is a "ping-pong" (request-response) connection for which delayed acknowledgments can provide benefits.

  This threshold is 1 by default, but some applications may need a higher threshold for optimal performance.

  Possible Values: 1 - 255

  Default: 1

- **tcp_rto_min_us - INTEGER**

  Minimal TCP retransmission timeout (in microseconds). Note that the rto_min route option has the highest precedence for configuring this setting, followed by the TCP_BPF_RTO_MIN and TCP_RTO_MIN_US socket options, followed by this tcp_rto_min_us sysctl.

  The recommended practice is to use a value less or equal to 200000 microseconds.

  Possible Values: 1 - INT_MAX

  Default: 200000

- **tcp_rto_max_ms - INTEGER**

  Maximal TCP retransmission timeout (in ms). Note that TCP_RTO_MAX_MS socket option has higher precedence.

  When changing tcp_rto_max_ms, it is important to understand that tcp_retries2 might need a change.

  Possible Values: 1000 - 120,000

  Default: 120,000

<a id="rst-udp-variables"></a>

## UDP variables

- **udp_l3mdev_accept - BOOLEAN**

  Enabling this option allows a "global" bound socket to work across L3 master domains (e.g., VRFs) with packets capable of being received regardless of the L3 domain in which they originated. Only valid when the kernel was compiled with CONFIG_NET_L3_MASTER_DEV.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **udp_mem - vector of 3 INTEGERs: min, pressure, max**

  Number of pages allowed for queueing by all UDP sockets.

  min: Number of pages allowed for queueing by all UDP sockets.

  pressure: This value was introduced to follow format of tcp_mem.

  max: This value was introduced to follow format of tcp_mem.

  Default is calculated at boot time from amount of available memory.

- **udp_rmem_min - INTEGER**

  Minimal size of receive buffer used by UDP sockets in moderation. Each UDP socket is able to use the size for receiving data, even if total pages of UDP sockets exceed udp_mem pressure. The unit is byte.

  Default: 4K

- **udp_wmem_min - INTEGER**

  UDP does not have tx memory accounting and this tunable has no effect.

- **udp_hash_entries - INTEGER**

  Show the number of hash buckets for UDP sockets in the current networking namespace.

  A negative value means the networking namespace does not own its hash buckets and shares the initial networking namespace's one.

- **udp_child_hash_entries - INTEGER**

  Control the number of hash buckets for UDP sockets in the child networking namespace, which must be set before clone() or unshare().

  If the value is not 0, the kernel uses a value rounded up to 2^n as the actual hash bucket size.  0 is a special value, meaning the child networking namespace will share the initial networking namespace's hash buckets.

  Note that the child will use the global one in case the kernel fails to allocate enough memory.  In addition, the global hash buckets are spread over available NUMA nodes, but the allocation of the child hash table depends on the current process's NUMA policy, which could result in performance differences.

  Possible values: 0, 2^n (n: 7 (128) - 16 (64K))

  Default: 0

<a id="rst-raw-variables"></a>

## RAW variables

- **raw_l3mdev_accept - BOOLEAN**

  Enabling this option allows a "global" bound socket to work across L3 master domains (e.g., VRFs) with packets capable of being received regardless of the L3 domain in which they originated. Only valid when the kernel was compiled with CONFIG_NET_L3_MASTER_DEV.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

<a id="rst-cipsov4-variables"></a>

## CIPSOv4 Variables

- **cipso_cache_enable - BOOLEAN**

  If enabled, enable additions to and lookups from the CIPSO label mapping cache.  If disabled, additions are ignored and lookups always result in a miss.  However, regardless of the setting the cache is still invalidated when required when means you can safely toggle this on and off and the cache will always be "safe".

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **cipso_cache_bucket_size - INTEGER**

  The CIPSO label cache consists of a fixed size hash table with each hash bucket containing a number of cache entries.  This variable limits the number of entries in each hash bucket; the larger the value is, the more CIPSO label mappings that can be cached.  When the number of entries in a given hash bucket reaches this limit adding new entries causes the oldest entry in the bucket to be removed to make room.

  Default: 10

- **cipso_rbm_optfmt - BOOLEAN**

  Enable the "Optimized Tag 1 Format" as defined in section 3.4.2.6 of the CIPSO draft specification (see Documentation/netlabel for details). This means that when set the CIPSO tag will be padded with empty categories in order to make the packet data 32-bit aligned.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **cipso_rbm_strictvalid - BOOLEAN**

  If enabled, do a very strict check of the CIPSO option when ip_options_compile() is called.  If disabled, relax the checks done during ip_options_compile().  Either way is "safe" as errors are caught else where in the CIPSO processing code but setting this to 0 (False) should result in less work (i.e. it should be faster) but could cause problems with other implementations that require strict checking.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

<a id="rst-ip-variables"></a>

## IP Variables

- **ip_local_port_range - 2 INTEGERS**

  Defines the local port range that is used by TCP and UDP to choose the local port. The first number is the first, the second the last local port number. If possible, it is better these numbers have different parity (one even and one odd value). Must be greater than or equal to ip_unprivileged_port_start. The default values are 32768 and 60999 respectively.

- **ip_local_reserved_ports - list of comma separated ranges**

  Specify the ports which are reserved for known third-party applications. These ports will not be used by automatic port assignments (e.g. when calling connect() or bind() with port number 0). Explicit port allocation behavior is unchanged.

  The format used for both input and output is a comma separated list of ranges (e.g. "1,2-4,10-10" for ports 1, 2, 3, 4 and 10). Writing to the file will clear all previously reserved ports and update the current list with the one given in the input.

  Note that ip_local_port_range and ip_local_reserved_ports settings are independent and both are considered by the kernel when determining which ports are available for automatic port assignments.

  You can reserve ports which are not in the current ip_local_port_range, e.g.:



  ```text
  $ cat /proc/sys/net/ipv4/ip_local_port_range
  32000       60999
  $ cat /proc/sys/net/ipv4/ip_local_reserved_ports
  8080,9148
  ```

  although this is redundant. However such a setting is useful if later the port range is changed to a value that will include the reserved ports. Also keep in mind, that overlapping of these ranges may affect probability of selecting ephemeral ports which are right after block of reserved ports.

  Default: Empty

- **ip_unprivileged_port_start - INTEGER**

  This per-namespace sysctl defines the first unprivileged port in the inherited Linux port model. Peios treats `CAP_NET_BIND_SERVICE` as a compatibility pass, so this threshold is not a native authority boundary. Native socket and port-reservation policy still applies. Setting the value to 0 disables the Linux privileged-port distinction. The privileged range must not overlap `ip_local_port_range`.

  Default: 1024

- **ip_nonlocal_bind - BOOLEAN**

  If enabled, allows processes to bind() to non-local IP addresses, which can be quite useful - but may break some applications.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **ip_autobind_reuse - BOOLEAN**

  By default, bind() does not select the ports automatically even if the new socket and all sockets bound to the port have SO_REUSEADDR. ip_autobind_reuse allows bind() to reuse the port and this is useful when you use bind()+connect(), but may break some applications. The preferred solution is to use IP_BIND_ADDRESS_NO_PORT and this option should only be set by experts.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **ip_dynaddr - INTEGER**

  If set non-zero, enables support for dynamic addresses. If set to a non-zero value larger than 1, a kernel log message will be printed when dynamic address rewriting occurs.

  Default: 0

- **ip_early_demux - BOOLEAN**

  Optimize input packet processing down to one demux for certain kinds of local sockets.  Currently we only do this for established TCP and connected UDP sockets.

  It may add an additional cost for pure routing workloads that reduces overall throughput, in such case you should disable it.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **ping_group_range - 2 INTEGERS**

  In upstream Linux this range authorizes ICMP datagram sockets by group membership. With Peios PKM enabled the group-range gate is bypassed: datagram ping uses the ordinary native network-policy path. Changing this sysctl does not grant or deny Peios ping authority. Raw sockets retain their separate privilege checks.

- **tcp_early_demux - BOOLEAN**

  Enable early demux for established TCP sockets.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **udp_early_demux - BOOLEAN**

  Enable early demux for connected UDP sockets. Disable this if your system could experience more unconnected load.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **icmp_echo_ignore_all - BOOLEAN**

  If enabled, then the kernel will ignore all ICMP ECHO requests sent to it.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **icmp_echo_enable_probe - BOOLEAN**

  If enabled, then the kernel will respond to RFC 8335 PROBE requests sent to it.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **icmp_echo_ignore_broadcasts - BOOLEAN**

  If enabled, then the kernel will ignore all ICMP ECHO and TIMESTAMP requests sent to it via broadcast/multicast.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **icmp_ratelimit - INTEGER**

  Limit the maximal rates for sending ICMP packets whose type matches icmp_ratemask (see below) to specific targets. 0 to disable any limiting, otherwise the minimal space between responses in milliseconds. Note that another sysctl, icmp_msgs_per_sec limits the number of ICMP packets sent on all targets.

  Default: 1000

- **icmp_msgs_per_sec - INTEGER**

  Limit maximal number of ICMP packets sent per second from this host. Only messages whose type matches icmp_ratemask (see below) are controlled by this limit. For security reasons, the precise count of messages per second is randomized.

  Default: 1000

- **icmp_msgs_burst - INTEGER**

  icmp_msgs_per_sec controls number of ICMP packets sent per second, while icmp_msgs_burst controls the burst size of these packets. For security reasons, the precise burst size is randomized.

  Default: 50

- **icmp_ratemask - INTEGER**

  Mask made of ICMP types for which rates are being limited.

  Significant bits: IHGFEDCBA9876543210

  Default mask:     0000001100000011000 (6168)

  Bit definitions (see include/linux/icmp.h):

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > 0
  >
  > </td>
  > <td>
  >
  >
  > Echo Reply
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 3
  >
  > </td>
  > <td>
  >
  >
  > Destination Unreachable <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 4
  >
  > </td>
  > <td>
  >
  >
  > Source Quench <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 5
  >
  > </td>
  > <td>
  >
  >
  > Redirect
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 8
  >
  > </td>
  > <td>
  >
  >
  > Echo Request
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > B
  >
  > </td>
  > <td>
  >
  >
  > Time Exceeded <a id="rst-footnote-reference-3"></a>[1](#rst-footnote-1)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > C
  >
  > </td>
  > <td>
  >
  >
  > Parameter Problem <a id="rst-footnote-reference-4"></a>[1](#rst-footnote-1)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > D
  >
  > </td>
  > <td>
  >
  >
  > Timestamp Request
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > E
  >
  > </td>
  > <td>
  >
  >
  > Timestamp Reply
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > F
  >
  > </td>
  > <td>
  >
  >
  > Info Request
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > G
  >
  > </td>
  > <td>
  >
  >
  > Info Reply
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > H
  >
  > </td>
  > <td>
  >
  >
  > Address Mask Request
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > I
  >
  > </td>
  > <td>
  >
  >
  > Address Mask Reply
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  <a id="rst-footnote-1"></a>



  **[1]** These are rate limited by default (see default mask above)

- **icmp_ignore_bogus_error_responses - BOOLEAN**

  Some routers violate RFC1122 by sending bogus responses to broadcast frames.  Such violations are normally logged via a kernel warning. If enabled, the kernel will not give such warnings, which will avoid log file clutter.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

icmp_errors_use_inbound_ifaddr - BOOLEAN

> If disabled, icmp error messages are sent with the primary address of the exiting interface.
>
> If enabled, the message will be sent with the primary address of the interface that received the packet that caused the icmp error. This is the behaviour many network administrators will expect from a router. And it can make debugging complicated network layouts much easier.
>
> Note that if no primary address exists for the interface selected, then the primary address of the first non-loopback interface that has one will be used regardless of this setting.
>
> Possible values:
>
> - 0 (disabled)
>
> - 1 (enabled)
>
> Default: 0 (disabled)

- **icmp_errors_extension_mask - UNSIGNED INTEGER**

  Bitmask of ICMP extensions to append to ICMPv4 error messages ("Destination Unreachable", "Time Exceeded" and "Parameter Problem"). The original datagram is trimmed / padded to 128 bytes in order to be compatible with applications that do not comply with RFC 4884.

  Possible extensions are:


  <table>
  <tbody>
  <tr>
  <td>


  0x01

  </td>
  <td>


  Incoming IP interface information according to RFC 5837. Extension will include the index, IPv4 address (if present), name and MTU of the IP interface that received the datagram which elicited the ICMP error.

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x00 (no extensions)

- **igmp_max_memberships - INTEGER**

  Change the maximum number of multicast groups we can subscribe to. Default: 20

  Theoretical maximum value is bounded by having to send a membership report in a single datagram (i.e. the report can't span multiple datagrams, or risk confusing the switch and leaving groups you don't intend to).

  The number of supported groups 'M' is bounded by the number of group report entries you can fit into a single datagram of 65535 bytes.

  M = 65536-sizeof (ip header)/(sizeof(Group record))

  Group records are variable length, with a minimum of 12 bytes. So net.ipv4.igmp_max_memberships should not be set higher than:

  (65536-24) / 12 = 5459

  The value 5459 assumes no IP header options, so in practice this number may be lower.

- **igmp_max_msf - INTEGER**

  Maximum number of addresses allowed in the source filter list for a multicast group.

  Default: 10

- **igmp_qrv - INTEGER**

  Controls the IGMP query robustness variable (see RFC2236 8.1).

  Default: 2 (as specified by RFC2236 8.1)

  Minimum: 1 (as specified by RFC6636 4.5)

- **force_igmp_version - INTEGER**

  - 0 - (default) No enforcement of a IGMP version, IGMPv1/v2 fallback allowed. Will back to IGMPv3 mode again if all IGMPv1/v2 Querier Present timer expires.

  - 1 - Enforce to use IGMP version 1. Will also reply IGMPv1 report if receive IGMPv2/v3 query.

  - 2 - Enforce to use IGMP version 2. Will fallback to IGMPv1 if receive IGMPv1 query message. Will reply report if receive IGMPv3 query.

  - 3 - Enforce to use IGMP version 3. The same react with default 0.

  > [!NOTE]
  >
  > this is not the same with force_mld_version because IGMPv3 RFC3376 Security Considerations does not have clear description that we could ignore other version messages completely as MLDv2 RFC3810. So make this value as default 0 is recommended.

- **`conf/interface/*`**

  changes special settings per interface (where interface" is the name of your network interface)

- **`conf/all/*`**

  is special, changes the settings for all interfaces

- **log_martians - BOOLEAN**

  Log packets with impossible addresses to kernel log. log_martians for the interface will be enabled if at least one of conf/\{all,interface\}/log_martians is set to TRUE, it will be disabled otherwise

- **accept_redirects - BOOLEAN**

  Accept ICMP redirect messages. accept_redirects for the interface will be enabled if:

  - both conf/\{all,interface\}/accept_redirects are TRUE in the case forwarding for the interface is enabled

  or

  - at least one of conf/\{all,interface\}/accept_redirects is TRUE in the case forwarding for the interface is disabled

  accept_redirects for the interface will be disabled otherwise

  default:

  > - TRUE (host)
  >
  > - FALSE (router)

- **forwarding - BOOLEAN**

  Enable IP forwarding on this interface.  This controls whether packets received \_on\_ this interface can be forwarded.

- **mc_forwarding - BOOLEAN**

  Do multicast routing. The kernel needs to be compiled with CONFIG_MROUTE and a multicast routing daemon is required. conf/all/mc_forwarding must also be set to TRUE to enable multicast routing for the interface

- **medium_id - INTEGER**

  Integer value used to differentiate the devices by the medium they are attached to. Two devices can have different id values when the broadcast packets are received only on one of them. The default value 0 means that the device is the only interface to its medium, value of -1 means that medium is not known.

  Currently, it is used to change the proxy_arp behavior: the proxy_arp feature is enabled for packets forwarded between two devices attached to different media.

- **proxy_arp - BOOLEAN**

  Do proxy arp.

  proxy_arp for the interface will be enabled if at least one of conf/\{all,interface\}/proxy_arp is set to TRUE, it will be disabled otherwise

- **proxy_arp_pvlan - BOOLEAN**

  Private VLAN proxy arp.

  Basically allow proxy arp replies back to the same interface (from which the ARP request/solicitation was received).

  This is done to support (ethernet) switch features, like RFC 3069, where the individual ports are NOT allowed to communicate with each other, but they are allowed to talk to the upstream router.  As described in RFC 3069, it is possible to allow these hosts to communicate through the upstream router by proxy_arp'ing. Don't need to be used together with proxy_arp.

  This technology is known by different names:

  - In RFC 3069 it is called VLAN Aggregation.

  - Cisco and Allied Telesyn call it Private VLAN.

  - Hewlett-Packard call it Source-Port filtering or port-isolation.

  - Ericsson call it MAC-Forced Forwarding (RFC Draft).

- **proxy_delay - INTEGER**

  Delay proxy response.

  Delay response to a neighbor solicitation when proxy_arp or proxy_ndp is enabled. A random value between \[0, proxy_delay) will be chosen, setting to zero means reply with no delay. Value in jiffies. Defaults to 80.

- **shared_media - BOOLEAN**

  Send(router) or accept(host) RFC1620 shared media redirects. Overrides secure_redirects.

  shared_media for the interface will be enabled if at least one of conf/\{all,interface\}/shared_media is set to TRUE, it will be disabled otherwise

  default TRUE

- **secure_redirects - BOOLEAN**

  Accept ICMP redirect messages only to gateways listed in the interface's current gateway list. Even if disabled, RFC1122 redirect rules still apply.

  Overridden by shared_media.

  secure_redirects for the interface will be enabled if at least one of conf/\{all,interface\}/secure_redirects is set to TRUE, it will be disabled otherwise

  default TRUE

- **send_redirects - BOOLEAN**

  Send redirects, if router.

  send_redirects for the interface will be enabled if at least one of conf/\{all,interface\}/send_redirects is set to TRUE, it will be disabled otherwise

  Default: TRUE

- **bootp_relay - BOOLEAN**

  Accept packets with source address 0.b.c.d destined not to this host as local ones. It is supposed, that BOOTP relay daemon will catch and forward such packets. conf/all/bootp_relay must also be set to TRUE to enable BOOTP relay for the interface

  default FALSE

  Not Implemented Yet.

- **accept_source_route - BOOLEAN**

  Accept packets with SRR option. conf/all/accept_source_route must also be set to TRUE to accept packets with SRR option on the interface

  default

  > - TRUE (router)
  >
  > - FALSE (host)

- **accept_local - BOOLEAN**

  Accept packets with local source addresses. In combination with suitable routing, this can be used to direct packets between two local interfaces over the wire and have them accepted properly. default FALSE

- **route_localnet - BOOLEAN**

  Do not consider loopback addresses as martian source or destination while routing. This enables the use of 127/8 for local routing purposes.

  default FALSE

- **rp_filter - INTEGER**

  - 0 - No source validation.

  - 1 - Strict mode as defined in RFC3704 Strict Reverse Path Each incoming packet is tested against the FIB and if the interface is not the best reverse path the packet check will fail. By default failed packets are discarded.

  - 2 - Loose mode as defined in RFC3704 Loose Reverse Path Each incoming packet's source address is also tested against the FIB and if the source address is not reachable via any interface the packet check will fail.

  Current recommended practice in RFC3704 is to enable strict mode to prevent IP spoofing from DDos attacks. If using asymmetric routing or other complicated routing, then loose mode is recommended.

  The max value from conf/\{all,interface\}/rp_filter is used when doing source validation on the \{interface\}.

  Default value is 0. Note that some distributions enable it in startup scripts.

- **src_valid_mark - BOOLEAN**

  - 0 - The fwmark of the packet is not included in reverse path route lookup.  This allows for asymmetric routing configurations utilizing the fwmark in only one direction, e.g., transparent proxying.

  - 1 - The fwmark of the packet is included in reverse path route lookup.  This permits rp_filter to function when the fwmark is used for routing traffic in both directions.

  This setting also affects the utilization of fmwark when performing source address selection for ICMP replies, or determining addresses stored for the IPOPT_TS_TSANDADDR and IPOPT_RR IP options.

  The max value from conf/\{all,interface\}/src_valid_mark is used.

  Default value is 0.

- **arp_filter - BOOLEAN**

  - 1 - Allows you to have multiple network interfaces on the same subnet, and have the ARPs for each interface be answered based on whether or not the kernel would route a packet from the ARP'd IP out that interface (therefore you must use source based routing for this to work). In other words it allows control of which cards (usually 1) will respond to an arp request.

  - 0 - (default) The kernel can respond to arp requests with addresses from other interfaces. This may seem wrong but it usually makes sense, because it increases the chance of successful communication. IP addresses are owned by the complete host on Linux, not by particular interfaces. Only for more complex setups like load- balancing, does this behaviour cause problems.

  arp_filter for the interface will be enabled if at least one of conf/\{all,interface\}/arp_filter is set to TRUE, it will be disabled otherwise

- **arp_announce - INTEGER**

  Define different restriction levels for announcing the local source IP address from IP packets in ARP requests sent on interface:

  - 0 - (default) Use any local address, configured on any interface

  - 1 - Try to avoid local addresses that are not in the target's subnet for this interface. This mode is useful when target hosts reachable via this interface require the source IP address in ARP requests to be part of their logical network configured on the receiving interface. When we generate the request we will check all our subnets that include the target IP and will preserve the source address if it is from such subnet. If there is no such subnet we select source address according to the rules for level 2.

  - 2 - Always use the best local address for this target. In this mode we ignore the source address in the IP packet and try to select local address that we prefer for talks with the target host. Such local address is selected by looking for primary IP addresses on all our subnets on the outgoing interface that include the target IP address. If no suitable local address is found we select the first local address we have on the outgoing interface or on all other interfaces, with the hope we will receive reply for our request and even sometimes no matter the source IP address we announce.

  The max value from conf/\{all,interface\}/arp_announce is used.

  Increasing the restriction level gives more chance for receiving answer from the resolved target while decreasing the level announces more valid sender's information.

- **arp_ignore - INTEGER**

  Define different modes for sending replies in response to received ARP requests that resolve local target IP addresses:

  - 0 - (default): reply for any local target IP address, configured on any interface

  - 1 - reply only if the target IP address is local address configured on the incoming interface

  - 2 - reply only if the target IP address is local address configured on the incoming interface and both with the sender's IP address are part from same subnet on this interface

  - 3 - do not reply for local addresses configured with scope host, only resolutions for global and link addresses are replied

  - 4-7 - reserved

  - 8 - do not reply for all local addresses

  The max value from conf/\{all,interface\}/arp_ignore is used when ARP request is received on the \{interface\}

- **arp_notify - BOOLEAN**

  Define mode for notification of address and device changes.

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > 0
  >
  > </td>
  > <td>
  >
  >
  > (default): do nothing
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 1
  >
  > </td>
  > <td>
  >
  >
  > Generate gratuitous arp requests when device is brought up or hardware address changes.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

- **arp_accept - INTEGER**

  Define behavior for accepting gratuitous ARP (garp) frames from devices that are not already present in the ARP table:

  - 0 - don't create new entries in the ARP table

  - 1 - create new entries in the ARP table

  - 2 - create new entries only if the source IP address is in the same subnet as an address configured on the interface that received the garp message.

  Both replies and requests type gratuitous arp will trigger the ARP table to be updated, if this setting is on.

  If the ARP table already contains the IP address of the gratuitous arp frame, the arp table will be updated regardless if this setting is on or off.

- **arp_evict_nocarrier - BOOLEAN**

  Clears the ARP cache on NOCARRIER events. This option is important for wireless devices where the ARP cache should not be cleared when roaming between access points on the same network. In most cases this should remain as the default (1).

  Possible values:

  - 0 (disabled) - Do not clear ARP cache on NOCARRIER events

  - 1 (enabled)  - Clear the ARP cache on NOCARRIER events

  Default: 1 (enabled)

- **mcast_solicit - INTEGER**

  The maximum number of multicast probes in INCOMPLETE state, when the associated hardware address is unknown.  Defaults to 3.

- **ucast_solicit - INTEGER**

  The maximum number of unicast probes in PROBE state, when the hardware address is being reconfirmed.  Defaults to 3.

- **app_solicit - INTEGER**

  The maximum number of probes to send to the user space ARP daemon via netlink before dropping back to multicast probes (see mcast_resolicit).  Defaults to 0.

- **mcast_resolicit - INTEGER**

  The maximum number of multicast probes after unicast and app probes in PROBE state.  Defaults to 0.

- **disable_policy - BOOLEAN**

  Disable IPSEC policy (SPD) for this interface

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **disable_xfrm - BOOLEAN**

  Disable IPSEC encryption on this interface, whatever the policy

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **igmpv2_unsolicited_report_interval - INTEGER**

  The interval in milliseconds in which the next unsolicited IGMPv1 or IGMPv2 report retransmit will take place.

  Default: 10000 (10 seconds)

- **igmpv3_unsolicited_report_interval - INTEGER**

  The interval in milliseconds in which the next unsolicited IGMPv3 report retransmit will take place.

  Default: 1000 (1 seconds)

- **ignore_routes_with_linkdown - BOOLEAN**

  Ignore routes whose link is down when performing a FIB lookup.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **promote_secondaries - BOOLEAN**

  When a primary IP address is removed from this interface promote a corresponding secondary IP address instead of removing all the corresponding secondary IP addresses.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **drop_unicast_in_l2_multicast - BOOLEAN**

  Drop any unicast IP packets that are received in link-layer multicast (or broadcast) frames.

  This behavior (for multicast) is actually a SHOULD in RFC 1122, but is disabled by default for compatibility reasons.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **drop_gratuitous_arp - BOOLEAN**

  Drop all gratuitous ARP frames, for example if there's a known good ARP proxy on the network and such frames need not be used (or in the case of 802.11, must not be used to prevent attacks.)

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **tag - INTEGER**

  Allows you to write a number, which can be used as required.

  Default value is 0.

- **xfrm4_gc_thresh - INTEGER**

  (Obsolete since linux-4.14) The threshold at which we will start garbage collecting for IPv4 destination cache entries.  At twice this value the system will refuse new allocations.

- **igmp_link_local_mcast_reports - BOOLEAN**

  Enable IGMP reports for link local multicast groups in the 224.0.0.X range.

  Default TRUE

Alexey Kuznetsov. [kuznet@ms2.inr.ac.ru](<mailto:kuznet@ms2.inr.ac.ru>)

Updated by:

- Andi Kleen [ak@muc.de](<mailto:ak@muc.de>)

- Nicolas Delon [delon.nicolas@wanadoo.fr](<mailto:delon.nicolas@wanadoo.fr>)

<a id="rst-proc-sys-net-ipv6-variables"></a>

## /proc/sys/net/ipv6/\* Variables

IPv6 has no global variables such as tcp\_\*.  tcp\_\* settings under ipv4/ also apply to IPv6 \[XXX?\].

- **bindv6only - BOOLEAN**

  Default value for IPV6_V6ONLY socket option, which restricts use of the IPv6 socket to IPv6 communication only.

  Possible values:

  - 0 (disabled) - enable IPv4-mapped address feature

  - 1 (enabled)  - disable IPv4-mapped address feature

  Default: 0 (disabled)

- **flowlabel_consistency - BOOLEAN**

  Protect the consistency (and unicity) of flow label. You have to disable it to use IPV6_FL_F_REFLECT flag on the flow label manager.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **auto_flowlabels - INTEGER**

  Automatically generate flow labels based on a flow hash of the packet. This allows intermediate devices, such as routers, to identify packet flows for mechanisms like Equal Cost Multipath Routing (see RFC 6438).


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  automatic flow labels are completely disabled

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  automatic flow labels are enabled by default, they can be disabled on a per socket basis using the IPV6_AUTOFLOWLABEL socket option

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  automatic flow labels are allowed, they may be enabled on a per socket basis using the IPV6_AUTOFLOWLABEL socket option

  </td>
  </tr>
  <tr>
  <td>


  3

  </td>
  <td>


  automatic flow labels are enabled and enforced, they cannot be disabled by the socket option

  </td>
  </tr>
  </tbody>
  </table>

  Default: 1

- **flowlabel_state_ranges - BOOLEAN**

  Split the flow label number space into two ranges. 0-0x7FFFF is reserved for the IPv6 flow manager facility, 0x80000-0xFFFFF is reserved for stateless flow labels as described in RFC6437.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

- **flowlabel_reflect - INTEGER**

  Control flow label reflection. Needed for Path MTU Discovery to work with Equal Cost Multipath Routing in anycast environments. See RFC 7690 and: [https://tools.ietf.org/html/draft-wang-6man-flow-label-reflection-01](<https://tools.ietf.org/html/draft-wang-6man-flow-label-reflection-01>)

  This is a bitmask.

  - 1: enabled for established flows

    Note that this prevents automatic flowlabel changes, as done in "tcp: change IPv6 flow-label upon receiving spurious retransmission" and "tcp: Change txhash on every SYN and RTO retransmit"

  - 2: enabled for TCP RESET packets (no active listener) If set, a RST packet sent in response to a SYN packet on a closed port will reflect the incoming flow label.

  - 4: enabled for ICMPv6 echo reply messages.

  Default: 0

- **fib_multipath_hash_policy - INTEGER**

  Controls which hash policy to use for multipath routes.

  Default: 0 (Layer 3)

  Possible values:

  - 0 - Layer 3 (source and destination addresses plus flow label)

  - 1 - Layer 4 (standard 5-tuple)

  - 2 - Layer 3 or inner Layer 3 if present

  - 3 - Custom multipath hash. Fields used for multipath hash calculation are determined by fib_multipath_hash_fields sysctl

- **fib_multipath_hash_fields - UNSIGNED INTEGER**

  When fib_multipath_hash_policy is set to 3 (custom multipath hash), the fields used for multipath hash calculation are determined by this sysctl.

  This value is a bitmask which enables various fields for multipath hash calculation.

  Possible fields are:


  <table>
  <tbody>
  <tr>
  <td>


  0x0001

  </td>
  <td>


  Source IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0002

  </td>
  <td>


  Destination IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0004

  </td>
  <td>


  IP protocol

  </td>
  </tr>
  <tr>
  <td>


  0x0008

  </td>
  <td>


  Flow Label

  </td>
  </tr>
  <tr>
  <td>


  0x0010

  </td>
  <td>


  Source port

  </td>
  </tr>
  <tr>
  <td>


  0x0020

  </td>
  <td>


  Destination port

  </td>
  </tr>
  <tr>
  <td>


  0x0040

  </td>
  <td>


  Inner source IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0080

  </td>
  <td>


  Inner destination IP address

  </td>
  </tr>
  <tr>
  <td>


  0x0100

  </td>
  <td>


  Inner IP protocol

  </td>
  </tr>
  <tr>
  <td>


  0x0200

  </td>
  <td>


  Inner Flow Label

  </td>
  </tr>
  <tr>
  <td>


  0x0400

  </td>
  <td>


  Inner source port

  </td>
  </tr>
  <tr>
  <td>


  0x0800

  </td>
  <td>


  Inner destination port

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x0007 (source IP, destination IP and IP protocol)

- **anycast_src_echo_reply - BOOLEAN**

  Controls the use of anycast addresses as source addresses for ICMPv6 echo reply

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **idgen_delay - INTEGER**

  Controls the delay in seconds after which time to retry privacy stable address generation if a DAD conflict is detected.

  Default: 1 (as specified in RFC7217)

- **idgen_retries - INTEGER**

  Controls the number of retries to generate a stable privacy address if a DAD conflict is detected.

  Default: 3 (as specified in RFC7217)

- **mld_qrv - INTEGER**

  Controls the MLD query robustness variable (see RFC3810 9.1).

  Default: 2 (as specified by RFC3810 9.1)

  Minimum: 1 (as specified by RFC6636 4.5)

- **max_dst_opts_number - INTEGER**

  Maximum number of non-padding TLVs allowed in a Destination options extension header. If this value is less than zero then unknown options are disallowed and the number of known TLVs allowed is the absolute value of this number.

  Default: 8

- **max_hbh_opts_number - INTEGER**

  Maximum number of non-padding TLVs allowed in a Hop-by-Hop options extension header. If this value is less than zero then unknown options are disallowed and the number of known TLVs allowed is the absolute value of this number.

  Default: 8

- **max_dst_opts_length - INTEGER**

  Maximum length allowed for a Destination options extension header.

  Default: INT_MAX (unlimited)

- **max_hbh_length - INTEGER**

  Maximum length allowed for a Hop-by-Hop options extension header.

  Default: INT_MAX (unlimited)

- **skip_notify_on_dev_down - BOOLEAN**

  Controls whether an RTM_DELROUTE message is generated for routes removed when a device is taken down or deleted. IPv4 does not generate this message; IPv6 does by default. Setting this sysctl to true skips the message, making IPv4 and IPv6 on par in relying on userspace caches to track link events and evict routes.

  Possible values:

  - 0 (disabled) - generate the message

  - 1 (enabled)  - skip generating the message

  Default: 0 (disabled)

- **nexthop_compat_mode - BOOLEAN**

  New nexthop API provides a means for managing nexthops independent of prefixes. Backwards compatibility with old route format is enabled by default which means route dumps and notifications contain the new nexthop attribute but also the full, expanded nexthop definition. Further, updates or deletes of a nexthop configuration generate route notifications for each fib entry using the nexthop. Once a system understands the new API, this sysctl can be disabled to achieve full performance benefits of the new API by disabling the nexthop expansion and extraneous notifications.

  Note that as a backward-compatible mode, dumping of modern features might be incomplete or wrong. For example, resilient groups will not be shown as such, but rather as just a list of next hops. Also weights that do not fit into 8 bits will show incorrectly.

  Default: true (backward compat mode)

- **fib_notify_on_flag_change - INTEGER**

  Whether to emit RTM_NEWROUTE notifications whenever RTM_F_OFFLOAD/ RTM_F_TRAP/RTM_F_OFFLOAD_FAILED flags are changed.

  After installing a route to the kernel, user space receives an acknowledgment, which means the route was installed in the kernel, but not necessarily in hardware. It is also possible for a route already installed in hardware to change its action and therefore its flags. For example, a host route that is trapping packets can be "promoted" to perform decapsulation following the installation of an IPinIP/VXLAN tunnel. The notifications will indicate to user-space the state of the route.

  Default: 0 (Do not emit notifications.)

  Possible values:

  - 0 - Do not emit notifications.

  - 1 - Emit notifications.

  - 2 - Emit notifications only for RTM_F_OFFLOAD_FAILED flag change.

- **ioam6_id - INTEGER**

  Define the IOAM id of this node. Uses only 24 bits out of 32 in total.

  Possible value range:

  - Min: 0

  - Max: 0xFFFFFF

  Default: 0xFFFFFF

- **ioam6_id_wide - LONG INTEGER**

  Define the wide IOAM id of this node. Uses only 56 bits out of 64 in total. Can be different from ioam6_id.

  Possible value range:

  - Min: 0

  - Max: 0xFFFFFFFFFFFFFF

  Default: 0xFFFFFFFFFFFFFF

IPv6 Fragmentation:

- **ip6frag_high_thresh - INTEGER**

  Maximum memory used to reassemble IPv6 fragments. When ip6frag_high_thresh bytes of memory is allocated for this purpose, the fragment handler will toss packets until ip6frag_low_thresh is reached.

- **ip6frag_low_thresh - INTEGER**

  See ip6frag_high_thresh

- **ip6frag_time - INTEGER**

  Time in seconds to keep an IPv6 fragment in memory.

- **`conf/default/*`:**

  Change the interface-specific default settings.

  These settings would be used during creating new interfaces.

- **`conf/all/*`:**

  Change all the interface-specific settings.

  \[XXX:  Other special features than forwarding?\]

- **conf/all/disable_ipv6 - BOOLEAN**

  Changing this value is same as changing `conf/default/disable_ipv6` setting and also all per-interface `disable_ipv6` settings to the same value.

  Reading this value does not have any particular meaning. It does not say whether IPv6 support is enabled or disabled. Returned value can be 1 also in the case when some interface has `disable_ipv6` set to 0 and has configured IPv6 addresses.

- **conf/all/forwarding - BOOLEAN**

  Enable global IPv6 forwarding between all interfaces.

  IPv4 and IPv6 work differently here; the `force_forwarding` flag must be used to control which interfaces may forward packets.

  This also sets all interfaces' Host/Router setting 'forwarding' to the specified value.  See below for details.

  This referred to as global forwarding.

- **proxy_ndp - BOOLEAN**

  Do proxy ndp.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **force_forwarding - BOOLEAN**

  Enable forwarding on this interface only -- regardless of the setting on `conf/all/forwarding`. When setting `conf.all.forwarding` to 0, the `force_forwarding` flag will be reset on all interfaces.

- **fwmark_reflect - BOOLEAN**

  Controls the fwmark of kernel-generated IPv6 reply packets that are not associated with a socket for example, TCP RSTs or ICMPv6 echo replies). If disabled, these packets have a fwmark of zero. If enabled, they have the fwmark of the packet they are replying to.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **`conf/interface/*`:**

  Change special settings per interface.

  The functional behaviour for certain settings is different depending on whether local forwarding is enabled or not.

- **accept_ra - INTEGER**

  Accept Router Advertisements; autoconfigure using them.

  It also determines whether or not to transmit Router Solicitations. If and only if the functional setting is to accept Router Advertisements, Router Solicitations will be transmitted.

  Possible values are:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > 0
  >
  > </td>
  > <td>
  >
  >
  > Do not accept Router Advertisements.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 1
  >
  > </td>
  > <td>
  >
  >
  > Accept Router Advertisements if forwarding is disabled.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 2
  >
  > </td>
  > <td>
  >
  >
  > Overrule forwarding behaviour. Accept Router Advertisements even if forwarding is enabled.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  Functional default:

  > - enabled if local forwarding is disabled.
  >
  > - disabled if local forwarding is enabled.

- **accept_ra_defrtr - BOOLEAN**

  Learn default router in Router Advertisement.

  Functional default:

  > - enabled if accept_ra is enabled.
  >
  > - disabled if accept_ra is disabled.

- **ra_defrtr_metric - UNSIGNED INTEGER**

  Route metric for default route learned in Router Advertisement. This value will be assigned as metric for the default route learned via IPv6 Router Advertisement. Takes affect only if accept_ra_defrtr is enabled.

  - **Possible values:**

    1 to 0xFFFFFFFF

    Default: IP6_RT_PRIO_USER i.e. 1024.

- **accept_ra_from_local - BOOLEAN**

  Accept RA with source-address that is found on local machine if the RA is otherwise proper and able to be accepted.

  Default is to NOT accept these as it may be an un-intended network loop.

  Functional default:

  > - enabled if accept_ra_from_local is enabled on a specific interface.
  >
  > - disabled if accept_ra_from_local is disabled on a specific interface.

- **accept_ra_min_hop_limit - INTEGER**

  Minimum hop limit Information in Router Advertisement.

  Hop limit Information in Router Advertisement less than this variable shall be ignored.

  Default: 1

- **accept_ra_min_lft - INTEGER**

  Minimum acceptable lifetime value in Router Advertisement.

  RA sections with a lifetime less than this value shall be ignored. Zero lifetimes stay unaffected.

  Default: 0

- **accept_ra_pinfo - BOOLEAN**

  Learn Prefix Information in Router Advertisement.

  Functional default:

  > - enabled if accept_ra is enabled.
  >
  > - disabled if accept_ra is disabled.

- **ra_honor_pio_life - BOOLEAN**

  Whether to use RFC4862 Section 5.5.3e to determine the valid lifetime of an address matching a prefix sent in a Router Advertisement Prefix Information Option.

  Possible values:

  - 0 (disabled) - RFC4862 section 5.5.3e is used to determine the valid lifetime of the address.

  - 1 (enabled)  - the PIO valid lifetime will always be honored.

  Default: 0 (disabled)

- **ra_honor_pio_pflag - BOOLEAN**

  The Prefix Information Option P-flag indicates the network can allocate a unique IPv6 prefix per client using DHCPv6-PD. This sysctl can be enabled when a userspace DHCPv6-PD client is running to cause the P-flag to take effect: i.e. the P-flag suppresses any effects of the A-flag within the same PIO. For a given PIO, P=1 and A=1 is treated as A=0.

  Possible values:

  - 0 (disabled) - the P-flag is ignored.

  - 1 (enabled)  - the P-flag will disable SLAAC autoconfiguration for the given Prefix Information Option.

  Default: 0 (disabled)

- **accept_ra_rt_info_min_plen - INTEGER**

  Minimum prefix length of Route Information in RA.

  Route Information w/ prefix smaller than this variable shall be ignored.

  Functional default:

  > - 0 if accept_ra_rtr_pref is enabled.
  >
  > - -1 if accept_ra_rtr_pref is disabled.

- **accept_ra_rt_info_max_plen - INTEGER**

  Maximum prefix length of Route Information in RA.

  Route Information w/ prefix larger than this variable shall be ignored.

  Functional default:

  > - 0 if accept_ra_rtr_pref is enabled.
  >
  > - -1 if accept_ra_rtr_pref is disabled.

- **accept_ra_rtr_pref - BOOLEAN**

  Accept Router Preference in RA.

  Functional default:

  > - enabled if accept_ra is enabled.
  >
  > - disabled if accept_ra is disabled.

- **accept_ra_mtu - BOOLEAN**

  Apply the MTU value specified in RA option 5 (RFC4861). If disabled, the MTU specified in the RA will be ignored.

  Functional default:

  > - enabled if accept_ra is enabled.
  >
  > - disabled if accept_ra is disabled.

- **accept_redirects - BOOLEAN**

  Accept Redirects.

  Functional default:

  > - enabled if local forwarding is disabled.
  >
  > - disabled if local forwarding is enabled.

- **accept_source_route - INTEGER**

  Accept source routing (routing extension header).

  - &gt;= 0: Accept only routing header type 2.

  - &lt; 0: Do not accept routing header.

  Default: 0

- **autoconf - BOOLEAN**

  Autoconfigure addresses using Prefix Information in Router Advertisements.

  Functional default:

  > - enabled if accept_ra_pinfo is enabled.
  >
  > - disabled if accept_ra_pinfo is disabled.

- **dad_transmits - INTEGER**

  The amount of Duplicate Address Detection probes to send.

  Default: 1

- **forwarding - INTEGER**

  Configure interface-specific Host/Router behaviour.

  > [!NOTE]
  >
  > It is recommended to have the same setting on all interfaces; mixed router/host scenarios are rather uncommon.

  Possible values are:

  > - 0 Forwarding disabled
  >
  > - 1 Forwarding enabled

  **FALSE (0)**:

  By default, Host behaviour is assumed.  This means:

  1. IsRouter flag is not set in Neighbour Advertisements.

  2. If accept_ra is TRUE (default), transmit Router Solicitations.

  3. If accept_ra is TRUE (default), accept Router Advertisements (and do autoconfiguration).

  4. If accept_redirects is TRUE (default), accept Redirects.

  **TRUE (1)**:

  If local forwarding is enabled, Router behaviour is assumed. This means exactly the reverse from the above:

  1. IsRouter flag is set in Neighbour Advertisements.

  2. Router Solicitations are not sent unless accept_ra is 2.

  3. Router Advertisements are ignored unless accept_ra is 2.

  4. Redirects are ignored.

  Default: 0 (disabled) if global forwarding is disabled (default), otherwise 1 (enabled).

- **hop_limit - INTEGER**

  Default Hop Limit to set.

  Default: 64

- **mtu - INTEGER**

  Default Maximum Transfer Unit

  Default: 1280 (IPv6 required minimum)

- **ip_nonlocal_bind - BOOLEAN**

  If enabled, allows processes to bind() to non-local IPv6 addresses, which can be quite useful - but may break some applications.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **router_probe_interval - INTEGER**

  Minimum interval (in seconds) between Router Probing described in RFC4191.

  Default: 60

- **router_solicitation_delay - INTEGER**

  Number of seconds to wait after interface is brought up before sending Router Solicitations.

  Default: 1

- **router_solicitation_interval - INTEGER**

  Number of seconds to wait between Router Solicitations.

  Default: 4

- **router_solicitations - INTEGER**

  Number of Router Solicitations to send until assuming no routers are present.

  Default: 3

- **use_oif_addrs_only - BOOLEAN**

  When enabled, the candidate source addresses for destinations routed via this interface are restricted to the set of addresses configured on this interface (vis. RFC 6724, section 4).

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **use_tempaddr - INTEGER**

  Preference for Privacy Extensions (RFC3041).

  > - &lt;= 0 : disable Privacy Extensions
  >
  > - == 1 : enable Privacy Extensions, but prefer public addresses over temporary addresses.
  >
  > - &gt;  1 : enable Privacy Extensions and prefer temporary addresses over public addresses.

  Default:

  > - 0 (for most devices)
  >
  > - -1 (for point-to-point devices and loopback devices)

- **temp_valid_lft - INTEGER**

  valid lifetime (in seconds) for temporary addresses. If less than the minimum required lifetime (typically 5-7 seconds), temporary addresses will not be created.

  Default: 172800 (2 days)

- **temp_prefered_lft - INTEGER**

  Preferred lifetime (in seconds) for temporary addresses. If temp_prefered_lft is less than the minimum required lifetime (typically 5-7 seconds), the preferred lifetime is the minimum required. If temp_prefered_lft is greater than temp_valid_lft, the preferred lifetime is temp_valid_lft.

  Default: 86400 (1 day)

- **keep_addr_on_down - INTEGER**

  Keep all IPv6 addresses on an interface down event. If set static global addresses with no expiration time are not flushed.

  - &gt;0 : enabled

  - 0 : system default

  - &lt;0 : disabled

  Default: 0 (addresses are removed)

- **max_desync_factor - INTEGER**

  Maximum value for DESYNC_FACTOR, which is a random value that ensures that clients don't synchronize with each other and generate new addresses at exactly the same time. value is in seconds.

  Default: 600

- **regen_min_advance - INTEGER**

  How far in advance (in seconds), at minimum, to create a new temporary address before the current one is deprecated. This value is added to the amount of time that may be required for duplicate address detection to determine when to create a new address. Linux permits setting this value to less than the default of 2 seconds, but a value less than 2 does not conform to RFC 8981.

  Default: 2

- **regen_max_retry - INTEGER**

  Number of attempts before give up attempting to generate valid temporary addresses.

  Default: 5

- **max_addresses - INTEGER**

  Maximum number of autoconfigured addresses per interface.  Setting to zero disables the limitation.  It is not recommended to set this value too large (or to zero) because it would be an easy way to crash the kernel by allowing too many addresses to be created.

  Default: 16

- **disable_ipv6 - BOOLEAN**

  Disable IPv6 operation.  If accept_dad is set to 2, this value will be dynamically set to TRUE if DAD fails for the link-local address.

  Default: FALSE (enable IPv6 operation)

  When this value is changed from 1 to 0 (IPv6 is being enabled), it will dynamically create a link-local address on the given interface and start Duplicate Address Detection, if necessary.

  When this value is changed from 0 to 1 (IPv6 is being disabled), it will dynamically delete all addresses and routes on the given interface. From now on it will not possible to add addresses/routes to the selected interface.

- **accept_dad - INTEGER**

  Whether to accept DAD (Duplicate Address Detection).

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > 0
  >
  > </td>
  > <td>
  >
  >
  > Disable DAD
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 1
  >
  > </td>
  > <td>
  >
  >
  > Enable DAD (default)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 2
  >
  > </td>
  > <td>
  >
  >
  > Enable DAD, and disable IPv6 operation if MAC-based duplicate link-local address has been found.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  DAD operation and mode on a given interface will be selected according to the maximum value of conf/\{all,interface\}/accept_dad.

- **force_tllao - BOOLEAN**

  Enable sending the target link-layer address option even when responding to a unicast neighbor solicitation.

  Default: FALSE

  Quoting from RFC 2461, section 4.4, Target link-layer address:

  "The option MUST be included for multicast solicitations in order to avoid infinite Neighbor Solicitation "recursion" when the peer node does not have a cache entry to return a Neighbor Advertisements message.  When responding to unicast solicitations, the option can be omitted since the sender of the solicitation has the correct link- layer address; otherwise it would not have be able to send the unicast solicitation in the first place. However, including the link-layer address in this case adds little overhead and eliminates a potential race condition where the sender deletes the cached link-layer address prior to receiving a response to a previous solicitation."

- **ndisc_notify - BOOLEAN**

  Define mode for notification of address and device changes.

  Possible values:

  - 0 (disabled) - do nothing

  - 1 (enabled)  - Generate unsolicited neighbour advertisements when device is brought up or hardware address changes.

  Default: 0 (disabled)

- **ndisc_tclass - INTEGER**

  The IPv6 Traffic Class to use by default when sending IPv6 Neighbor Discovery (Router Solicitation, Router Advertisement, Neighbor Solicitation, Neighbor Advertisement, Redirect) messages. These 8 bits can be interpreted as 6 high order bits holding the DSCP value and 2 low order bits representing ECN (which you probably want to leave cleared).

  - 0 - (default)

- **ndisc_evict_nocarrier - BOOLEAN**

  Clears the neighbor discovery table on NOCARRIER events. This option is important for wireless devices where the neighbor discovery cache should not be cleared when roaming between access points on the same network. In most cases this should remain as the default (1).

  Possible values:

  - 0 (disabled) - Do not clear neighbor discovery cache on NOCARRIER events.

  - 1 (enabled)  - Clear neighbor discover cache on NOCARRIER events.

  Default: 1 (enabled)

- **mldv1_unsolicited_report_interval - INTEGER**

  The interval in milliseconds in which the next unsolicited MLDv1 report retransmit will take place.

  Default: 10000 (10 seconds)

- **mldv2_unsolicited_report_interval - INTEGER**

  The interval in milliseconds in which the next unsolicited MLDv2 report retransmit will take place.

  Default: 1000 (1 second)

- **force_mld_version - INTEGER**

  - 0 - (default) No enforcement of a MLD version, MLDv1 fallback allowed

  - 1 - Enforce to use MLD version 1

  - 2 - Enforce to use MLD version 2

- **suppress_frag_ndisc - INTEGER**

  Control RFC 6980 (Security Implications of IPv6 Fragmentation with IPv6 Neighbor Discovery) behavior:

  - 1 - (default) discard fragmented neighbor discovery packets

  - 0 - allow fragmented neighbor discovery packets

- **optimistic_dad - BOOLEAN**

  Whether to perform Optimistic Duplicate Address Detection (RFC 4429).

  Optimistic Duplicate Address Detection for the interface will be enabled if at least one of conf/\{all,interface\}/optimistic_dad is set to 1, it will be disabled otherwise.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **use_optimistic - BOOLEAN**

  If enabled, do not classify optimistic addresses as deprecated during source address selection.  Preferred addresses will still be chosen before optimistic addresses, subject to other ranking in the source address selection algorithm.

  This will be enabled if at least one of conf/\{all,interface\}/use_optimistic is set to 1, disabled otherwise.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **stable_secret - IPv6 address**

  This IPv6 address will be used as a secret to generate IPv6 addresses for link-local addresses and autoconfigured ones. All addresses generated after setting this secret will be stable privacy ones by default. This can be changed via the addrgenmode ip-link. conf/default/stable_secret is used as the secret for the namespace, the interface specific ones can overwrite that. Writes to conf/all/stable_secret are refused.

  It is recommended to generate this secret during installation of a system and keep it stable after that.

  By default the stable secret is unset.

- **addr_gen_mode - INTEGER**

  Defines how link-local and autoconf addresses are generated.


  <table>
  <tbody>
  <tr>
  <td>


  0

  </td>
  <td>


  generate address based on EUI64 (default)

  </td>
  </tr>
  <tr>
  <td>


  1

  </td>
  <td>


  do no generate a link-local address, use EUI64 for addresses generated from autoconf

  </td>
  </tr>
  <tr>
  <td>


  2

  </td>
  <td>


  generate stable privacy addresses, using the secret from stable_secret (RFC7217)

  </td>
  </tr>
  <tr>
  <td>


  3

  </td>
  <td>


  generate stable privacy addresses, using a random secret if unset

  </td>
  </tr>
  </tbody>
  </table>

- **drop_unicast_in_l2_multicast - BOOLEAN**

  Drop any unicast IPv6 packets that are received in link-layer multicast (or broadcast) frames.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **drop_unsolicited_na - BOOLEAN**

  Drop all unsolicited neighbor advertisements, for example if there's a known good NA proxy on the network and such frames need not be used (or in the case of 802.11, must not be used to prevent attacks.)

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled).

- **accept_untracked_na - INTEGER**

  Define behavior for accepting neighbor advertisements from devices that are absent in the neighbor cache:

  - 0 - (default) Do not accept unsolicited and untracked neighbor advertisements.

  - 1 - Add a new neighbor cache entry in STALE state for routers on receiving a neighbor advertisement (either solicited or unsolicited) with target link-layer address option specified if no neighbor entry is already present for the advertised IPv6 address. Without this knob, NAs received for untracked addresses (absent in neighbor cache) are silently ignored.

    This is as per router-side behavior documented in RFC9131.

    This has lower precedence than drop_unsolicited_na.

    This will optimize the return path for the initial off-link communication that is initiated by a directly connected host, by ensuring that the first-hop router which turns on this setting doesn't have to buffer the initial return packets to do neighbor-solicitation. The prerequisite is that the host is configured to send unsolicited neighbor advertisements on interface bringup. This setting should be used in conjunction with the ndisc_notify setting on the host to satisfy this prerequisite.

  - 2 - Extend option (1) to add a new neighbor cache entry only if the source IP address is in the same subnet as an address configured on the interface that received the neighbor advertisement.

- **enhanced_dad - BOOLEAN**

  Include a nonce option in the IPv6 neighbor solicitation messages used for duplicate address detection per RFC7527. A received DAD NS will only signal a duplicate address if the nonce is different. This avoids any false detection of duplicates due to loopback of the NS messages that we send. The nonce option will be sent on an interface unless both of conf/\{all,interface\}/enhanced_dad are set to FALSE.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

<a id="rst-icmp"></a>

## `icmp/*`:

- **ratelimit - INTEGER**

  Limit the maximal rates for sending ICMPv6 messages to a particular peer.

  0 to disable any limiting, otherwise the space between responses in milliseconds.

  Default: 100

- **ratemask - list of comma separated ranges**

  For ICMPv6 message types matching the ranges in the ratemask, limit the sending of the message according to ratelimit parameter.

  The format used for both input and output is a comma separated list of ranges (e.g. "0-127,129" for ICMPv6 message type 0 to 127 and 129). Writing to the file will clear all previous ranges of ICMPv6 message types and update the current list with the input.

  Refer to: [https://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml](<https://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml>) for numerical values of ICMPv6 message types, e.g. echo request is 128 and echo reply is 129.

  Default: 0-1,3-127 (rate limit ICMPv6 errors except Packet Too Big)

- **echo_ignore_all - BOOLEAN**

  If enabled, then the kernel will ignore all ICMP ECHO requests sent to it over the IPv6 protocol.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **echo_ignore_multicast - BOOLEAN**

  If enabled, then the kernel will ignore all ICMP ECHO requests sent to it over the IPv6 protocol via multicast.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **echo_ignore_anycast - BOOLEAN**

  If enabled, then the kernel will ignore all ICMP ECHO requests sent to it over the IPv6 protocol destined to anycast address.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **error_anycast_as_unicast - BOOLEAN**

  If enabled, then the kernel will respond with ICMP Errors resulting from requests sent to it over the IPv6 protocol destined to anycast address essentially treating anycast as unicast.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 0 (disabled)

- **errors_extension_mask - UNSIGNED INTEGER**

  Bitmask of ICMP extensions to append to ICMPv6 error messages ("Destination Unreachable" and "Time Exceeded"). The original datagram is trimmed / padded to 128 bytes in order to be compatible with applications that do not comply with RFC 4884.

  Possible extensions are:


  <table>
  <tbody>
  <tr>
  <td>


  0x01

  </td>
  <td>


  Incoming IP interface information according to RFC 5837. Extension will include the index, IPv6 address (if present), name and MTU of the IP interface that received the datagram which elicited the ICMP error.

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0x00 (no extensions)

- **xfrm6_gc_thresh - INTEGER**

  (Obsolete since linux-4.14) The threshold at which we will start garbage collecting for IPv6 destination cache entries.  At twice this value the system will refuse new allocations.

IPv6 Update by: Pekka Savola &lt;[pekkas@netcore.fi](<mailto:pekkas@netcore.fi>)&gt; YOSHIFUJI Hideaki / USAGI Project &lt;[yoshfuji@linux-ipv6.org](<mailto:yoshfuji@linux-ipv6.org>)&gt;

<a id="rst-proc-sys-net-bridge-variables"></a>

## /proc/sys/net/bridge/\* Variables:

These variables belong to the optional upstream bridge-netfilter path. Peios
disables `CONFIG_BRIDGE_NETFILTER` and the iptables/arptables engines, so this
section does not describe available policy controls in the configured build.
NTFE policy is separate from these compatibility reference entries.

bridge-nf-call-arptables - BOOLEAN

> Possible values:
>
> - 0 (disabled) - disable this.
>
> - 1 (enabled)  - pass bridged ARP traffic to arptables' FORWARD chain.
>
> Default: 1 (enabled)

bridge-nf-call-iptables - BOOLEAN

> Possible values:
>
> - 0 (disabled) - disable this.
>
> - 1 (enabled)  - pass bridged IPv4 traffic to iptables' chains.
>
> Default: 1 (enabled)

bridge-nf-call-ip6tables - BOOLEAN

> Possible values:
>
> - 0 (disabled) - disable this.
>
> - 1 (enabled)  - pass bridged IPv6 traffic to ip6tables' chains.
>
> Default: 1 (enabled)

bridge-nf-filter-vlan-tagged - BOOLEAN

> Possible values:
>
> - 0 (disabled) - disable this.
>
> - 1 (enabled)  - pass bridged vlan-tagged ARP/IP/IPv6 traffic to \{arp,ip,ip6\}tables
>
> Default: 0 (disabled)

bridge-nf-filter-pppoe-tagged - BOOLEAN

> Possible values:
>
> - 0 (disabled) - disable this.
>
> - 1 (enabled)  - pass bridged pppoe-tagged IP/IPv6 traffic to \{ip,ip6\}tables.
>
> Default: 0 (disabled)

- **bridge-nf-pass-vlan-input-dev - BOOLEAN**

  - 1: if bridge-nf-filter-vlan-tagged is enabled, try to find a vlan interface on the bridge and set the netfilter input device to the vlan. This allows use of e.g. "iptables -i br0.1" and makes the REDIRECT target work with vlan-on-top-of-bridge interfaces.  When no matching vlan interface is found, or this switch is off, the input device is set to the bridge interface.

  - 0: disable bridge netfilter vlan interface lookup.

  Default: 0

<a id="rst-proc-sys-net-sctp-variables"></a>

## `proc/sys/net/sctp/*` Variables:

- **addip_enable - BOOLEAN**

  Enable or disable extension of  Dynamic Address Reconfiguration (ADD-IP) functionality specified in RFC5061.  This extension provides the ability to dynamically add and remove new addresses for the SCTP associations.

  Possible values:

  - 0 (disabled) - disable extension.

  - 1 (enabled)  - enable extension

  Default: 0 (disabled)

- **pf_enable - INTEGER**

  Enable or disable pf (pf is short for potentially failed) state. A value of pf_retrans &gt; path_max_retrans also disables pf state. That is, one of both pf_enable and pf_retrans &gt; path_max_retrans can disable pf state. Since pf_retrans and path_max_retrans can be changed by userspace application, sometimes user expects to disable pf state by the value of pf_retrans &gt; path_max_retrans, but occasionally the value of pf_retrans or path_max_retrans is changed by the user application, this pf state is enabled. As such, it is necessary to add this to dynamically enable and disable pf state. See: [https://datatracker.ietf.org/doc/draft-ietf-tsvwg-sctp-failover](<https://datatracker.ietf.org/doc/draft-ietf-tsvwg-sctp-failover>) for details.

  Possible values:

  - 1: Enable pf.

  - 0: Disable pf.

  Default: 1

- **pf_expose - INTEGER**

  Unset or enable/disable pf (pf is short for potentially failed) state exposure.  Applications can control the exposure of the PF path state in the SCTP_PEER_ADDR_CHANGE event and access of SCTP_PF-state transport info via SCTP_GET_PEER_ADDR_INFO sockopt.

  Possible values:

  - 0: Unset pf state exposure (compatible with old applications). No event will be sent but the transport info can be queried.

  - 1: Disable pf state exposure. No event will be sent and trying to obtain transport info will return -EACCESS.

  - 2: Enable pf state exposure. The event will be sent for a transport becoming SCTP_PF state and transport info can be obtained.

  Default: 0

- **addip_noauth_enable - BOOLEAN**

  Dynamic Address Reconfiguration (ADD-IP) requires the use of authentication to protect the operations of adding or removing new addresses.  This requirement is mandated so that unauthorized hosts would not be able to hijack associations.  However, older implementations may not have implemented this requirement while allowing the ADD-IP extension.  For reasons of interoperability, we provide this variable to control the enforcement of the authentication requirement.


  <table>
  <tbody>
  <tr>
  <td>


  1

  </td>
  <td>


  Allow ADD-IP extension to be used without authentication.  This should only be set in a closed environment for interoperability with older implementations.

  </td>
  </tr>
  <tr>
  <td>


  0

  </td>
  <td>


  Enforce the authentication requirement

  </td>
  </tr>
  </tbody>
  </table>

  Default: 0

- **auth_enable - BOOLEAN**

  Enable or disable Authenticated Chunks extension.  This extension provides the ability to send and receive authenticated chunks and is required for secure operation of Dynamic Address Reconfiguration (ADD-IP) extension.

  Possible values:

  - 0 (disabled) - disable extension.

  - 1 (enabled)  - enable extension

  Default: 0 (disabled)

- **prsctp_enable - BOOLEAN**

  Enable or disable the Partial Reliability extension (RFC3758) which is used to notify peers that a given DATA should no longer be expected.

  Possible values:

  - 0 (disabled) - disable extension.

  - 1 (enabled)  - enable extension

  Default: 1 (enabled)

- **max_burst - INTEGER**

  The limit of the number of new packets that can be initially sent.  It controls how bursty the generated traffic can be.

  Default: 4

- **association_max_retrans - INTEGER**

  Set the maximum number for retransmissions that an association can attempt deciding that the remote end is unreachable.  If this value is exceeded, the association is terminated.

  Default: 10

- **max_init_retransmits - INTEGER**

  The maximum number of retransmissions of INIT and COOKIE-ECHO chunks that an association will attempt before declaring the destination unreachable and terminating.

  Default: 8

- **path_max_retrans - INTEGER**

  The maximum number of retransmissions that will be attempted on a given path.  Once this threshold is exceeded, the path is considered unreachable, and new traffic will use a different path when the association is multihomed.

  Default: 5

- **pf_retrans - INTEGER**

  The number of retransmissions that will be attempted on a given path before traffic is redirected to an alternate transport (should one exist).  Note this is distinct from path_max_retrans, as a path that passes the pf_retrans threshold can still be used.  Its only deprioritized when a transmission path is selected by the stack.  This setting is primarily used to enable fast failover mechanisms without having to reduce path_max_retrans to a very low value.  See: [http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt](<http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt>) for details.  Note also that a value of pf_retrans &gt; path_max_retrans disables this feature. Since both pf_retrans and path_max_retrans can be changed by userspace application, a variable pf_enable is used to disable pf state.

  Default: 0

- **ps_retrans - INTEGER**

  Primary.Switchover.Max.Retrans (PSMR), it's a tunable parameter coming from section-5 "Primary Path Switchover" in rfc7829.  The primary path will be changed to another active path when the path error counter on the old primary path exceeds PSMR, so that "the SCTP sender is allowed to continue data transmission on a new working path even when the old primary destination address becomes active again".   Note this feature is disabled by initializing 'ps_retrans' per netns as 0xffff by default, and its value can't be less than 'pf_retrans' when changing by sysctl.

  Default: 0xffff

- **rto_initial - INTEGER**

  The initial round trip timeout value in milliseconds that will be used in calculating round trip times.  This is the initial time interval for retransmissions.

  Default: 3000

- **rto_max - INTEGER**

  The maximum value (in milliseconds) of the round trip timeout.  This is the largest time interval that can elapse between retransmissions.

  Default: 60000

- **rto_min - INTEGER**

  The minimum value (in milliseconds) of the round trip timeout.  This is the smallest time interval the can elapse between retransmissions.

  Default: 1000

- **hb_interval - INTEGER**

  The interval (in milliseconds) between HEARTBEAT chunks.  These chunks are sent at the specified interval on idle paths to probe the state of a given path between 2 associations.

  Default: 30000

- **sack_timeout - INTEGER**

  The amount of time (in milliseconds) that the implementation will wait to send a SACK.

  Default: 200

- **valid_cookie_life - INTEGER**

  The default lifetime of the SCTP cookie (in milliseconds).  The cookie is used during association establishment.

  Default: 60000

- **cookie_preserve_enable - BOOLEAN**

  Enable or disable the ability to extend the lifetime of the SCTP cookie that is used during the establishment phase of SCTP association

  Possible values:

  - 0 (disabled) - disable.

  - 1 (enabled)  - enable cookie lifetime extension.

  Default: 1 (enabled)

- **cookie_hmac_alg - STRING**

  Select the hmac algorithm used when generating the cookie value sent by a listening sctp socket to a connecting client in the INIT-ACK chunk. Valid values are:

  - sha256

  - none

  Default: sha256

- **rcvbuf_policy - INTEGER**

  Determines if the receive buffer is attributed to the socket or to association.   SCTP supports the capability to create multiple associations on a single socket.  When using this capability, it is possible that a single stalled association that's buffering a lot of data may block other associations from delivering their data by consuming all of the receive buffer space.  To work around this, the rcvbuf_policy could be set to attribute the receiver buffer space to each association instead of the socket.  This prevents the described blocking.

  - 1: rcvbuf space is per association

  - 0: rcvbuf space is per socket

  Default: 0

- **sndbuf_policy - INTEGER**

  Similar to rcvbuf_policy above, this applies to send buffer space.

  - 1: Send buffer is tracked per association

  - 0: Send buffer is tracked per socket.

  Default: 0

- **sctp_mem - vector of 3 INTEGERs: min, pressure, max**

  Number of pages allowed for queueing by all SCTP sockets.

  - min: Below this number of pages SCTP is not bothered about its memory usage. When amount of memory allocated by SCTP exceeds this number, SCTP starts to moderate memory usage.

  - pressure: This value was introduced to follow format of tcp_mem.

  - max: Maximum number of allowed pages.

  Default is calculated at boot time from amount of available memory.

- **sctp_rmem - vector of 3 INTEGERs: min, default, max**

  Only the first value ("min") is used, "default" and "max" are ignored.

  - min: Minimal size of receive buffer used by SCTP socket. It is guaranteed to each SCTP socket (but not association) even under moderate memory pressure.

  Default: 4K

- **sctp_wmem  - vector of 3 INTEGERs: min, default, max**

  Only the first value ("min") is used, "default" and "max" are ignored.

  - min: Minimum size of send buffer that can be used by SCTP sockets. It is guaranteed to each SCTP socket (but not association) even under moderate memory pressure.

  Default: 4K

- **addr_scope_policy - INTEGER**

  Control IPv4 address scoping (see [https://datatracker.ietf.org/doc/draft-stewart-tsvwg-sctp-ipv4/00/](<https://datatracker.ietf.org/doc/draft-stewart-tsvwg-sctp-ipv4/00/>) for details).

  - 0   - Disable IPv4 address scoping

  - 1   - Enable IPv4 address scoping

  - 2   - Follow draft but allow IPv4 private addresses

  - 3   - Follow draft but allow IPv4 link local addresses

  Default: 1

- **udp_port - INTEGER**

  The listening port for the local UDP tunneling sock. Normally it's using the IANA-assigned UDP port number 9899 (sctp-tunneling).

  This UDP sock is used for processing the incoming UDP-encapsulated SCTP packets (from RFC6951), and shared by all applications in the same net namespace. This UDP sock will be closed when the value is set to 0.

  The value will also be used to set the src port of the UDP header for the outgoing UDP-encapsulated SCTP packets. For the dest port, please refer to 'encap_port' below.

  Default: 0

- **encap_port - INTEGER**

  The default remote UDP encapsulation port.

  This value is used to set the dest port of the UDP header for the outgoing UDP-encapsulated SCTP packets by default. Users can also change the value for each sock/asoc/transport by using setsockopt. For further information, please refer to RFC6951.

  Note that when connecting to a remote server, the client should set this to the port that the UDP tunneling sock on the peer server is listening to and the local UDP tunneling sock on the client also must be started. On the server, it would get the encap_port from the incoming packet's source port.

  Default: 0

- **plpmtud_probe_interval - INTEGER**

  The time interval (in milliseconds) for the PLPMTUD probe timer, which is configured to expire after this period to receive an acknowledgment to a probe packet. This is also the time interval between the probes for the current pmtu when the probe search is done.

  PLPMTUD will be disabled when 0 is set, and other values for it must be &gt;= 5000.

  Default: 0

- **reconf_enable - BOOLEAN**

  Enable or disable extension of Stream Reconfiguration functionality specified in RFC6525. This extension provides the ability to "reset" a stream, and it includes the Parameters of "Outgoing/Incoming SSN Reset", "SSN/TSN Reset" and "Add Outgoing/Incoming Streams".

  Possible values:

  - 0 (disabled) - Disable extension.

  - 1 (enabled) - Enable extension.

  Default: 0 (disabled)

- **intl_enable - BOOLEAN**

  Enable or disable extension of User Message Interleaving functionality specified in RFC8260. This extension allows the interleaving of user messages sent on different streams. With this feature enabled, I-DATA chunk will replace DATA chunk to carry user messages if also supported by the peer. Note that to use this feature, one needs to set this option to 1 and also needs to set socket options SCTP_FRAGMENT_INTERLEAVE to 2 and SCTP_INTERLEAVING_SUPPORTED to 1.

  Possible values:

  - 0 (disabled) - Disable extension.

  - 1 (enabled) - Enable extension.

  Default: 0 (disabled)

- **ecn_enable - BOOLEAN**

  Control use of Explicit Congestion Notification (ECN) by SCTP. Like in TCP, ECN is used only when both ends of the SCTP connection indicate support for it. This feature is useful in avoiding losses due to congestion by allowing supporting routers to signal congestion before having to drop packets.

  Possible values:

  - 0 (disabled) - Disable ecn.

  - 1 (enabled) - Enable ecn.

  Default: 1 (enabled)

- **l3mdev_accept - BOOLEAN**

  Enabling this option allows a "global" bound socket to work across L3 master domains (e.g., VRFs) with packets capable of being received regardless of the L3 domain in which they originated. Only valid when the kernel was compiled with CONFIG_NET_L3_MASTER_DEV.

  Possible values:

  - 0 (disabled)

  - 1 (enabled)

  Default: 1 (enabled)

<a id="rst-proc-sys-net-core"></a>

## `/proc/sys/net/core/*`

> Please see: [Documentation/admin-guide/sysctl/net.rst](/kernel/administration/admin-guide/sysctl/net.md) for descriptions of these entries.

<a id="rst-proc-sys-net-unix"></a>

## `/proc/sys/net/unix/*`

- **max_dgram_qlen - INTEGER**

  The maximum length of dgram socket receive queue

  Default: 10

---

# IP dynamic address hack-port v0.03

_Peios Kernel / Internals / Networking_

> This stuff allows diald ONESHOT connections to get established by dynamically changing packet source address (and socket's if local procs). It is implemented for TCP diald-box connections(1) and IP_MASQuerading(2).

<a id="rst-ip-dynamic-address-hack-port-v0-03"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This stuff allows diald ONESHOT connections to get established by dynamically changing packet source address (and socket's if local procs). It is implemented for TCP diald-box connections(1) and IP_MASQuerading(2).

If enabled<a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1) and forwarding interface has changed:

> 1. Socket (and packet) source address is rewritten ON RETRANSMISSIONS while in SYN_SENT state (diald-box processes).
>
> 2. Out-bounded MASQueraded source address changes ON OUTPUT (when internal host does retransmission) until a packet from outside is received by the tunnel.

This is specially helpful for auto dialup links (diald), where the `actual` outgoing address is unknown at the moment the link is going up. So, the *same* (local AND masqueraded) connections requests that bring the link up will be able to get established.

<a id="rst-footnote-1"></a>



**[1]** At boot, by default no address rewriting is attempted.

To enable:



```text
# echo 1 > /proc/sys/net/ipv4/ip_dynaddr
```

To enable verbose mode:



```text
# echo 2 > /proc/sys/net/ipv4/ip_dynaddr
```

To disable (default):



```text
# echo 0 > /proc/sys/net/ipv4/ip_dynaddr
```

Enjoy\!

Juanjo  &lt;[jjciarla@raiz.uncu.edu.ar](<mailto:jjciarla@raiz.uncu.edu.ar>)&gt;

---

# IPsec

_Peios Kernel / Internals / Networking_

> Here documents known IPsec corner cases which need to be keep in mind when deploy various IPsec configuration in real world production environment.

<a id="rst-ipsec"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Here documents known IPsec corner cases which need to be keep in mind when deploy various IPsec configuration in real world production environment.

1. - **IPcomp:**

     Small IP packet won't get compressed at sender, and failed on policy check on receiver.

Quote from RFC3173:



```text
2.2. Non-Expansion Policy

 If the total size of a compressed payload and the IPComp header, as
 defined in section 3, is not smaller than the size of the original
 payload, the IP datagram MUST be sent in the original non-compressed
 form.  To clarify: If an IP datagram is sent non-compressed, no

 IPComp header is added to the datagram.  This policy ensures saving
 the decompression processing cycles and avoiding incurring IP
 datagram fragmentation when the expanded datagram is larger than the
 MTU.

 Small IP datagrams are likely to expand as a result of compression.
 Therefore, a numeric threshold should be applied before compression,
 where IP datagrams of size smaller than the threshold are sent in the
 original form without attempting compression.  The numeric threshold
 is implementation dependent.
```

Current IPComp implementation is indeed by the book, while as in practice when sending non-compressed packet to the peer (whether or not packet len is smaller than the threshold or the compressed len is larger than original packet len), the packet is dropped when checking the policy as this packet matches the selector but not coming from any XFRM layer, i.e., with no security path. Such naked packet will not eventually make it to upper layer. The result is much more wired to the user when ping peer with different payload length.

One workaround is try to set "level use" for each policy if user observed above scenario. The consequence of doing so is small packet(uncompressed) will skip policy checking on receiver side.

---

# IPv6

_Peios Kernel / Internals / Networking_

> Options for the ipv6 module are supplied as parameters at load time.

<a id="rst-ipv6"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Options for the ipv6 module are supplied as parameters at load time.

Module options may be given as command line arguments to the insmod or modprobe command, but are usually specified in either `/etc/modules.d/*.conf` configuration files, or in a distro-specific configuration file.

The available ipv6 module parameters are listed below.  If a parameter is not specified the default value is used.

The parameters are as follows:

disable

> Specifies whether to load the IPv6 module, but disable all its functionality.  This might be used when another module has a dependency on the IPv6 module being loaded, but no IPv6 addresses or operations are desired.
>
> The possible values and their effects are:
>
> - **0**
>
>   IPv6 is enabled.
>
>   This is the default value.
>
> - **1**
>
>   IPv6 is disabled.
>
>   No IPv6 addresses will be added to interfaces, and it will not be possible to open an IPv6 socket.
>
>   A reboot is required to enable IPv6.

autoconf

> Specifies whether to enable IPv6 address autoconfiguration on all interfaces.  This might be used when one does not wish for addresses to be automatically generated from prefixes received in Router Advertisements.
>
> The possible values and their effects are:
>
> - **0**
>
>   IPv6 address autoconfiguration is disabled on all interfaces.
>
>   Only the IPv6 loopback address (::1) and link-local addresses will be added to interfaces.
>
> - **1**
>
>   IPv6 address autoconfiguration is enabled on all interfaces.
>
>   This is the default value.

disable_ipv6

> Specifies whether to disable IPv6 on all interfaces. This might be used when no IPv6 addresses are desired.
>
> The possible values and their effects are:
>
> - **0**
>
>   IPv6 is enabled on all interfaces.
>
>   This is the default value.
>
> - **1**
>
>   IPv6 is disabled on all interfaces.
>
>   No IPv6 addresses will be added to interfaces.

---

# IPVLAN Driver HOWTO

_Peios Kernel / Internals / Networking_

> Mahesh Bandewar <maheshb AT google.com>

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-ipvlan-driver-howto"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Initial Release:**

  Mahesh Bandewar &lt;maheshb AT google.com&gt;

<a id="rst-introduction"></a>

## 1. Introduction:

This is conceptually very similar to the macvlan driver with one major exception of using L3 for mux-ing /demux-ing among slaves. This property makes the master device share the L2 with its slave devices. I have developed this driver in conjunction with network namespaces and not sure if there is use case outside of it.

<a id="rst-building-and-installation"></a>

## 2. Building and Installation:

In order to build the driver, please select the config item CONFIG_IPVLAN. The driver can be built into the kernel (CONFIG_IPVLAN=y) or as a module (CONFIG_IPVLAN=m).

<a id="rst-configuration"></a>

## 3. Configuration:

There are no module parameters for this driver and it can be configured using IProute2/ip utility.



```text
ip link add link <master> name <slave> type ipvlan [ mode MODE ] [ FLAGS ]
   where
     MODE: l3 (default) | l3s | l2
     FLAGS: bridge (default) | private | vepa
```

e.g.

> - **(a)** Following will create IPvlan link with eth0 as master in L3 bridge mode:
>
>
>
>   ```text
>   bash# ip link add link eth0 name ipvl0 type ipvlan
>   ```
>
> - **(b)** This command will create IPvlan link in L2 bridge mode:
>
>
>
>   ```text
>   bash# ip link add link eth0 name ipvl0 type ipvlan mode l2 bridge
>   ```
>
> - **(c)** This command will create an IPvlan device in L2 private mode:
>
>
>
>   ```text
>   bash# ip link add link eth0 name ipvlan type ipvlan mode l2 private
>   ```
>
> - **(d)** This command will create an IPvlan device in L2 vepa mode:
>
>
>
>   ```text
>   bash# ip link add link eth0 name ipvlan type ipvlan mode l2 vepa
>   ```

<a id="rst-operating-modes"></a>

## 4. Operating modes:

IPvlan has two modes of operation - L2 and L3. For a given master device, you can select one of these two modes and all slaves on that master will operate in the same (selected) mode. The RX mode is almost identical except that in L3 mode the slaves won't receive any multicast / broadcast traffic. L3 mode is more restrictive since routing is controlled from the other (mostly) default namespace.

<a id="rst-l2-mode"></a>

### 4.1 L2 mode:

In this mode TX processing happens on the stack instance attached to the slave device and packets are switched and queued to the master device to send out. In this mode the slaves will RX/TX multicast and broadcast (if applicable) as well.

<a id="rst-l3-mode"></a>

### 4.2 L3 mode:

In this mode TX processing up to L3 happens on the stack instance attached to the slave device and packets are switched to the stack instance of the master device for the L2 processing and routing from that instance will be used before packets are queued on the outbound device. In this mode the slaves will not receive nor can send multicast / broadcast traffic.

<a id="rst-l3s-mode"></a>

### 4.3 L3S mode:

This is very similar to the L3 mode except that iptables (conn-tracking) works in this mode and hence it is L3-symmetric (L3s). This will have slightly less performance but that shouldn't matter since you are choosing this mode over plain-L3 mode to make conn-tracking work.

<a id="rst-mode-flags"></a>

## 5. Mode flags:

At this time following mode flags are available

<a id="rst-bridge"></a>

### 5.1 bridge:

This is the default option. To configure the IPvlan port in this mode, user can choose to either add this option on the command-line or don't specify anything. This is the traditional mode where slaves can cross-talk among themselves apart from talking through the master device.

<a id="rst-private"></a>

### 5.2 private:

If this option is added to the command-line, the port is set in private mode. i.e. port won't allow cross communication between slaves.

<a id="rst-vepa"></a>

### 5.3 vepa:

If this is added to the command-line, the port is set in VEPA mode. i.e. port will offload switching functionality to the external entity as described in 802.1Qbg Note: VEPA mode in IPvlan has limitations. IPvlan uses the mac-address of the master-device, so the packets which are emitted in this mode for the adjacent neighbor will have source and destination mac same. This will make the switch / router send the redirect message.

<a id="rst-what-to-choose-macvlan-vs-ipvlan"></a>

## 6. What to choose (macvlan vs. ipvlan)?

These two devices are very similar in many regards and the specific use case could very well define which device to choose. if one of the following situations defines your use case then you can choose to use ipvlan:

- **(a)** The Linux host that is connected to the external switch / router has policy configured that allows only one mac per port.

- **(b)** No of virtual devices created on a master exceed the mac capacity and puts the NIC in promiscuous mode and degraded performance is a concern.

- **(c)** If the slave device is to be put into the hostile / untrusted network namespace where L2 on the slave could be changed / misused.

<a id="rst-example-configuration"></a>

## 6. Example configuration:



```text
+=============================================================+
|  Host: host1                                                |
|                                                             |
|   +----------------------+      +----------------------+    |
|   |   NS:ns0             |      |  NS:ns1              |    |
|   |                      |      |                      |    |
|   |                      |      |                      |    |
|   |        ipvl0         |      |         ipvl1        |    |
|   +----------#-----------+      +-----------#----------+    |
|              #                              #               |
|              ################################               |
|                              # eth0                         |
+==============================#==============================+
```

- **(a)** Create two network namespaces - ns0, ns1:



  ```text
  ip netns add ns0
  ip netns add ns1
  ```

- **(b)** Create two ipvlan slaves on eth0 (master device):



  ```text
  ip link add link eth0 ipvl0 type ipvlan mode l2
  ip link add link eth0 ipvl1 type ipvlan mode l2
  ```

- **(c)** Assign slaves to the respective network namespaces:



  ```text
  ip link set dev ipvl0 netns ns0
  ip link set dev ipvl1 netns ns1
  ```

- **(d)** Now switch to the namespace (ns0 or ns1) to configure the slave devices

  > - For ns0:
  >
  >
  >
  >   ```text
  >   (1) ip netns exec ns0 bash
  >   (2) ip link set dev ipvl0 up
  >   (3) ip link set dev lo up
  >   (4) ip -4 addr add 127.0.0.1 dev lo
  >   (5) ip -4 addr add $IPADDR dev ipvl0
  >   (6) ip -4 route add default via $ROUTER dev ipvl0
  >   ```
  >
  > - For ns1:
  >
  >
  >
  >   ```text
  >   (1) ip netns exec ns1 bash
  >   (2) ip link set dev ipvl1 up
  >   (3) ip link set dev lo up
  >   (4) ip -4 addr add 127.0.0.1 dev lo
  >   (5) ip -4 addr add $IPADDR dev ipvl1
  >   (6) ip -4 route add default via $ROUTER dev ipvl1
  >   ```

---

# IPvs-sysctl

_Peios Kernel / Internals / Networking_

> default 10

> **Peios:** This describes an upstream interface disabled in the configured Peios kernel. Peios uses NTFE; nftables/iptables, IPVS and flow-table configuration are not enabled policy paths. Retained schemas and reference text do not imply runtime availability. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-ipvs-sysctl"></a>

<a id="rst-proc-sys-net-ipv4-vs-variables"></a>

## /proc/sys/net/ipv4/vs/\* Variables:

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **am_droprate - INTEGER**

  default 10

  It sets the always mode drop rate, which is used in the mode 3 of the drop_rate defense.

- **amemthresh - INTEGER**

  default 1024

  It sets the available memory threshold (in pages), which is used in the automatic modes of defense. When there is no enough available memory, the respective strategy will be enabled and the variable is automatically set to 2, otherwise the strategy is disabled and the variable is  set  to 1.

- **backup_only - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  If set, disable the director function while the server is in backup mode to avoid packet loops for DR/TUN methods.

- **conn_reuse_mode - INTEGER**

  1 - default

  Controls how ipvs will deal with connections that are detected port reuse. It is a bitmap, with the values being:

  0: disable any special handling on port reuse. The new connection will be delivered to the same real server that was servicing the previous connection.

  bit 1: enable rescheduling of new connections when it is safe. That is, whenever expire_nodest_conn and for TCP sockets, when the connection is in TIME_WAIT state (which is only possible if you use NAT mode).

  bit 2: it is bit 1 plus, for TCP connections, when connections are in FIN_WAIT state, as this is the last state seen by load balancer in Direct Routing mode. This bit helps on adding new real servers to a very busy cluster.

- **conntrack - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  If set, maintain connection tracking entries for connections handled by IPVS.

  This should be enabled if connections handled by IPVS are to be also handled by stateful firewall rules. That is, iptables rules that make use of connection tracking.  It is a performance optimisation to disable this setting otherwise.

  Connections handled by the IPVS FTP application module will have connection tracking entries regardless of this setting.

  Only available when IPVS is compiled with CONFIG_IP_VS_NFCT enabled.

- **cache_bypass - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  If it is enabled, forward packets to the original destination directly when no cache server is available and destination address is not local (iph-&gt;daddr is RTN_UNICAST). It is mostly used in transparent web cache cluster.

- **debug_level - INTEGER**

  - 0          - transmission error messages (default)

  - 1          - non-fatal error messages

  - 2          - configuration

  - 3          - destination trash

  - 4          - drop entry

  - 5          - service lookup

  - 6          - scheduling

  - 7          - connection new/expire, lookup and synchronization

  - 8          - state transition

  - 9          - binding destination, template checks and applications

  - 10         - IPVS packet transmission

  - 11         - IPVS packet handling (ip_vs_in/ip_vs_out)

  - 12 or more - packet traversal

  Only available when IPVS is compiled with CONFIG_IP_VS_DEBUG enabled.

  Higher debugging levels include the messages for lower debugging levels, so setting debug level 2, includes level 0, 1 and 2 messages. Thus, logging becomes more and more verbose the higher the level.

- **drop_entry - INTEGER**

  - 0  - disabled (default)

  The drop_entry defense is to randomly drop entries in the connection hash table, just in order to collect back some memory for new connections. In the current code, the drop_entry procedure can be activated every second, then it randomly scans 1/32 of the whole and drops entries that are in the SYN-RECV/SYNACK state, which should be effective against syn-flooding attack.

  The valid values of drop_entry are from 0 to 3, where 0 means that this strategy is always disabled, 1 and 2 mean automatic modes (when there is no enough available memory, the strategy is enabled and the variable is automatically set to 2, otherwise the strategy is disabled and the variable is set to 1), and 3 means that the strategy is always enabled.

- **drop_packet - INTEGER**

  - 0  - disabled (default)

  The drop_packet defense is designed to drop 1/rate packets before forwarding them to real servers. If the rate is 1, then drop all the incoming packets.

  The value definition is the same as that of the drop_entry. In the automatic mode, the rate is determined by the follow formula: rate = amemthresh / (amemthresh - available_memory) when available memory is less than the available memory threshold. When the mode 3 is set, the always mode drop rate is controlled by the /proc/sys/net/ipv4/vs/am_droprate.

- **est_cpulist - CPULIST**

  Allowed CPUs for estimation kthreads

  Syntax: standard cpulist format empty list - stop kthread tasks and estimation default - the system's housekeeping CPUs for kthreads

  Example: "all": all possible CPUs "0-N": all possible CPUs, N denotes last CPU number "0,1-N:1/2": first and all CPUs with odd number "": empty list

- **est_nice - INTEGER**

  default 0 Valid range: -20 (more favorable) .. 19 (less favorable)

  Niceness value to use for the estimation kthreads (scheduling priority)

- **expire_nodest_conn - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  The default value is 0, the load balancer will silently drop packets when its destination server is not available. It may be useful, when user-space monitoring program deletes the destination server (because of server overload or wrong detection) and add back the server later, and the connections to the server can continue.

  If this feature is enabled, the load balancer will expire the connection immediately when a packet arrives and its destination server is not available, then the client program will be notified that the connection is closed. This is equivalent to the feature some people requires to flush connections when its destination is not available.

- **expire_quiescent_template - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  When set to a non-zero value, the load balancer will expire persistent templates when the destination server is quiescent. This may be useful, when a user makes a destination server quiescent by setting its weight to 0 and it is desired that subsequent otherwise persistent connections are sent to a different destination server.  By default new persistent connections are allowed to quiescent destination servers.

  If this feature is enabled, the load balancer will expire the persistence template if it is to be used to schedule a new connection and the destination server is quiescent.

- **ignore_tunneled - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  If set, ipvs will set the ipvs_property on all packets which are of unrecognized protocols.  This prevents us from routing tunneled protocols like ipip, which is useful to prevent rescheduling packets that have been tunneled to the ipvs host (i.e. to prevent ipvs routing loops when ipvs is also acting as a real server).

- **nat_icmp_send - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  It controls sending icmp error messages (ICMP_DEST_UNREACH) for VS/NAT when the load balancer receives packets from real servers but the connection entries don't exist.

- **pmtu_disc - BOOLEAN**

  - 0 - disabled

  - not 0 - enabled (default)

  By default, reject with FRAG_NEEDED all DF packets that exceed the PMTU, irrespective of the forwarding method. For TUN method the flag can be disabled to fragment such packets.

- **secure_tcp - INTEGER**

  - 0  - disabled (default)

  The secure_tcp defense is to use a more complicated TCP state transition table. For VS/NAT, it also delays entering the TCP ESTABLISHED state until the three way handshake is completed.

  The value definition is the same as that of drop_entry and drop_packet.

- **sync_threshold - vector of 2 INTEGERs: sync_threshold, sync_period**

  default 3 50

  It sets synchronization threshold, which is the minimum number of incoming packets that a connection needs to receive before the connection will be synchronized. A connection will be synchronized, every time the number of its incoming packets modulus sync_period equals the threshold. The range of the threshold is from 0 to sync_period.

  When sync_period and sync_refresh_period are 0, send sync only for state changes or only once when pkts matches sync_threshold

- **sync_refresh_period - UNSIGNED INTEGER**

  default 0

  In seconds, difference in reported connection timer that triggers new sync message. It can be used to avoid sync messages for the specified period (or half of the connection timeout if it is lower) if connection state is not changed since last sync.

  This is useful for normal connections with high traffic to reduce sync rate. Additionally, retry sync_retries times with period of sync_refresh_period/8.

- **sync_retries - INTEGER**

  default 0

  Defines sync retries with period of sync_refresh_period/8. Useful to protect against loss of sync messages. The range of the sync_retries is from 0 to 3.

sync_qlen_max - UNSIGNED LONG

> Hard limit for queued sync messages that are not sent yet. It defaults to 1/32 of the memory pages but actually represents number of messages. It will protect us from allocating large parts of memory when the sending rate is lower than the queuing rate.

- **sync_sock_size - INTEGER**

  default 0

  Configuration of SNDBUF (master) or RCVBUF (slave) socket limit. Default value is 0 (preserve system defaults).

- **sync_ports - INTEGER**

  default 1

  The number of threads that master and backup servers can use for sync traffic. Every thread will use single UDP port, thread 0 will use the default port 8848 while last thread will use port 8848+sync_ports-1.

- **snat_reroute - BOOLEAN**

  - 0 - disabled

  - not 0 - enabled (default)

  If enabled, recalculate the route of SNATed packets from realservers so that they are routed as if they originate from the director. Otherwise they are routed as if they are forwarded by the director.

  If policy routing is in effect then it is possible that the route of a packet originating from a director is routed differently to a packet being forwarded by the director.

  If policy routing is not in effect then the recalculated route will always be the same as the original route so it is an optimisation to disable snat_reroute and avoid the recalculation.

- **sync_persist_mode - INTEGER**

  default 0

  Controls the synchronisation of connections when using persistence

  0: All types of connections are synchronised

  1: Attempt to reduce the synchronisation traffic depending on the connection type. For persistent services avoid synchronisation for normal connections, do it only for persistence templates. In such case, for TCP and SCTP it may need enabling sloppy_tcp and sloppy_sctp flags on backup servers. For non-persistent services such optimization is not applied, mode 0 is assumed.

- **sync_version - INTEGER**

  default 1

  The version of the synchronisation protocol used when sending synchronisation messages.

  0 selects the original synchronisation protocol (version 0). This should be used when sending synchronisation messages to a legacy system that only understands the original synchronisation protocol.

  1 selects the current synchronisation protocol (version 1). This should be used where possible.

  Kernels with this sync_version entry are able to receive messages of both version 1 and version 2 of the synchronisation protocol.

- **run_estimation - BOOLEAN**

  0 - disabled not 0 - enabled (default)

  If disabled, the estimation will be suspended and kthread tasks stopped.

  You can always re-enable estimation by setting this value to 1. But be careful, the first estimation after re-enable is not accurate.

---

# ISO 15765-2 (ISO-TP)

_Peios Kernel / Internals / Networking_

> ISO 15765-2, also known as ISO-TP, is a transport protocol specifically defined for diagnostic communication on CAN. It is widely used in the automotive industry, for example as the transport protocol for UDSonCAN (ISO 14229-3) or…

<a id="rst-iso-15765-2-iso-tp"></a>

<!-- SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause) -->

<a id="rst-overview"></a>

## Overview

ISO 15765-2, also known as ISO-TP, is a transport protocol specifically defined for diagnostic communication on CAN. It is widely used in the automotive industry, for example as the transport protocol for UDSonCAN (ISO 14229-3) or emission-related diagnostic services (ISO 15031-5).

ISO-TP can be used both on CAN CC (aka Classical CAN) and CAN FD (CAN with Flexible Datarate) based networks. It is also designed to be compatible with a CAN network using SAE J1939 as data link layer (however, this is not a requirement).

<a id="rst-specifications-used"></a>

### Specifications used

- ISO 15765-2:2024 : Road vehicles - Diagnostic communication over Controller Area Network (DoCAN). Part 2: Transport protocol and network layer services.

<a id="rst-addressing"></a>

### Addressing

In its simplest form, ISO-TP is based on two kinds of addressing modes for the nodes connected to the same network:

- physical addressing is implemented by two node-specific addresses and is used in 1-to-1 communication.

- functional addressing is implemented by one node-specific address and is used in 1-to-N communication.

Three different addressing formats can be employed:

- "normal" : each address is represented simply by a CAN ID.

- "extended": each address is represented by a CAN ID plus the first byte of the CAN payload; both the CAN ID and the byte inside the payload shall be different between two addresses.

- "mixed": each address is represented by a CAN ID plus the first byte of the CAN payload; the CAN ID is different between two addresses, but the additional byte is the same.

<a id="rst-transport-protocol-and-associated-frame-types"></a>

### Transport protocol and associated frame types

When transmitting data using the ISO-TP protocol, the payload can either fit inside one single CAN message or not, also considering the overhead the protocol is generating and the optional extended addressing. In the first case, the data is transmitted at once using a so-called Single Frame (SF). In the second case, ISO-TP defines a multi-frame protocol, in which the sender provides (through a First Frame - FF) the PDU length which is to be transmitted and also asks for a Flow Control (FC) frame, which provides the maximum supported size of a macro data block (`blocksize`) and the minimum time between the single CAN messages composing such block (`stmin`). Once this information has been received, the sender starts to send frames containing fragments of the data payload (called Consecutive Frames - CF), stopping after every `blocksize`-sized block to wait confirmation from the receiver which should then send another Flow Control frame to inform the sender about its availability to receive more data.

<a id="rst-how-to-use-iso-tp"></a>

## How to Use ISO-TP

As with others CAN protocols, the ISO-TP stack support is built into the Linux network subsystem for the CAN bus, aka. Linux-CAN or SocketCAN, and thus follows the same socket API.

<a id="rst-creation-and-basic-usage-of-an-iso-tp-socket"></a>

### Creation and basic usage of an ISO-TP socket

To use the ISO-TP stack, `#include <linux/can/isotp.h>` shall be used. A socket can then be created using the `PF_CAN` protocol family, the `SOCK_DGRAM` type (as the underlying protocol is datagram-based by design) and the `CAN_ISOTP` protocol:



```C
s = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP);
```

After the socket has been successfully created, `bind(2)` shall be called to bind the socket to the desired CAN interface; to do so:

- a TX CAN ID shall be specified as part of the sockaddr supplied to the call itself.

- a RX CAN ID shall also be specified, unless broadcast flags have been set through socket option (explained below).

Once bound to an interface, the socket can be read from and written to using the usual `read(2)` and `write(2)` system calls, as well as `send(2)`, `sendmsg(2)`, `recv(2)` and `recvmsg(2)`. Unlike the CAN_RAW socket API, only the ISO-TP data field (the actual payload) is sent and received by the userspace application using these calls. The address information and the protocol information are automatically filled by the ISO-TP stack using the configuration supplied during socket creation. In the same way, the stack will use the transport mechanism when required (i.e., when the size of the data payload exceeds the MTU of the underlying CAN bus).

The sockaddr structure used for SocketCAN has extensions for use with ISO-TP, as specified below:



```C
struct sockaddr_can {
    sa_family_t can_family;
    int         can_ifindex;
    union {
        struct { canid_t rx_id, tx_id; } tp;
    ...
    } can_addr;
}
```

- `can_family` and `can_ifindex` serve the same purpose as for other SocketCAN sockets.

- `can_addr.tp.rx_id` specifies the receive (RX) CAN ID and will be used as a RX filter.

- `can_addr.tp.tx_id` specifies the transmit (TX) CAN ID

<a id="rst-iso-tp-socket-options"></a>

### ISO-TP socket options

When creating an ISO-TP socket, reasonable defaults are set. Some options can be modified with `setsockopt(2)` and/or read back with `getsockopt(2)`.

<a id="rst-general-options"></a>

#### General options

General socket options can be passed using the `CAN_ISOTP_OPTS` optname:



```C
struct can_isotp_options opts;
ret = setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts))
```

where the `can_isotp_options` structure has the following contents:



```C
struct can_isotp_options {
    u32 flags;
    u32 frame_txtime;
    u8  ext_address;
    u8  txpad_content;
    u8  rxpad_content;
    u8  rx_ext_address;
};
```

- `flags`: modifiers to be applied to the default behaviour of the ISO-TP stack. Following flags are available:

  - `CAN_ISOTP_LISTEN_MODE`: listen only (do not send FC frames); normally used as a testing feature.

  - `CAN_ISOTP_EXTEND_ADDR`: use the byte specified in `ext_address` as an additional address component. This enables the "mixed" addressing format if used alone, or the "extended" addressing format if used in conjunction with `CAN_ISOTP_RX_EXT_ADDR`.

  - `CAN_ISOTP_TX_PADDING`: enable padding for transmitted frames, using `txpad_content` as value for the padding bytes.

  - `CAN_ISOTP_RX_PADDING`: enable padding for the received frames, using `rxpad_content` as value for the padding bytes.

  - `CAN_ISOTP_CHK_PAD_LEN`: check for correct padding length on the received frames.

  - `CAN_ISOTP_CHK_PAD_DATA`: check padding bytes on the received frames against `rxpad_content`; if `CAN_ISOTP_RX_PADDING` is not specified, this flag is ignored.

  - `CAN_ISOTP_HALF_DUPLEX`: force ISO-TP socket in half duplex mode (that is, transport mechanism can only be incoming or outgoing at the same time, not both).

  - `CAN_ISOTP_FORCE_TXSTMIN`: ignore stmin from received FC; normally used as a testing feature.

  - `CAN_ISOTP_FORCE_RXSTMIN`: ignore CFs depending on rx stmin; normally used as a testing feature.

  - `CAN_ISOTP_RX_EXT_ADDR`: use `rx_ext_address` instead of `ext_address` as extended addressing byte on the reception path. If used in conjunction with `CAN_ISOTP_EXTEND_ADDR`, this flag effectively enables the "extended" addressing format.

  - `CAN_ISOTP_WAIT_TX_DONE`: wait until the frame is sent before returning from `write(2)` and `send(2)` calls (i.e., blocking write operations).

  - `CAN_ISOTP_SF_BROADCAST`: use 1-to-N functional addressing (cannot be specified alongside `CAN_ISOTP_CF_BROADCAST`).

  - `CAN_ISOTP_CF_BROADCAST`: use 1-to-N transmission without flow control (cannot be specified alongside `CAN_ISOTP_SF_BROADCAST`). NOTE: this is not covered by the ISO 15765-2 standard.

  - `CAN_ISOTP_DYN_FC_PARMS`: enable dynamic update of flow control parameters.

- `frame_txtime`: frame transmission time (defined as N_As/N_Ar inside the ISO standard); if `0`, the default (or the last set value) is used. To set the transmission time to `0`, the `CAN_ISOTP_FRAME_TXTIME_ZERO` macro (equal to 0xFFFFFFFF) shall be used.

- `ext_address`: extended addressing byte, used if the `CAN_ISOTP_EXTEND_ADDR` flag is specified.

- `txpad_content`: byte used as padding value for transmitted frames.

- `rxpad_content`: byte used as padding value for received frames.

- `rx_ext_address`: extended addressing byte for the reception path, used if the `CAN_ISOTP_RX_EXT_ADDR` flag is specified.

<a id="rst-flow-control-options"></a>

#### Flow Control options

Flow Control (FC) options can be passed using the `CAN_ISOTP_RECV_FC` optname to provide the communication parameters for receiving ISO-TP PDUs.



```C
struct can_isotp_fc_options fc_opts;
ret = setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_RECV_FC, &fc_opts, sizeof(fc_opts));
```

where the `can_isotp_fc_options` structure has the following contents:



```C
struct can_isotp_options {
    u8 bs;
    u8 stmin;
    u8 wftmax;
};
```

- `bs`: blocksize provided in flow control frames.

- `stmin`: minimum separation time provided in flow control frames; can have the following values (others are reserved):

  - 0x00 - 0x7F : 0 - 127 ms

  - 0xF1 - 0xF9 : 100 us - 900 us

- `wftmax`: maximum number of wait frames provided in flow control frames.

<a id="rst-link-layer-options"></a>

#### Link Layer options

Link Layer (LL) options can be passed using the `CAN_ISOTP_LL_OPTS` optname:



```C
struct can_isotp_ll_options ll_opts;
ret = setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_LL_OPTS, &ll_opts, sizeof(ll_opts));
```

where the `can_isotp_ll_options` structure has the following contents:



```C
struct can_isotp_ll_options {
    u8 mtu;
    u8 tx_dl;
    u8 tx_flags;
};
```

- `mtu`: generated and accepted CAN frame type, can be equal to `CAN_MTU` for classical CAN frames or `CANFD_MTU` for CAN FD frames.

- `tx_dl`: maximum payload length for transmitted frames, can have one value among: 8, 12, 16, 20, 24, 32, 48, 64. Values above 8 only apply to CAN FD traffic (i.e.: `mtu = CANFD_MTU`).

- `tx_flags`: flags set into `struct canfd_frame.flags` at frame creation. Only applies to CAN FD traffic (i.e.: `mtu = CANFD_MTU`).

<a id="rst-transmission-stmin"></a>

#### Transmission stmin

The transmission minimum separation time (stmin) can be forced using the `CAN_ISOTP_TX_STMIN` optname and providing an stmin value in microseconds as a 32bit unsigned integer; this will overwrite the value sent by the receiver in flow control frames:



```C
uint32_t stmin;
ret = setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_TX_STMIN, &stmin, sizeof(stmin));
```

<a id="rst-reception-stmin"></a>

#### Reception stmin

The reception minimum separation time (stmin) can be forced using the `CAN_ISOTP_RX_STMIN` optname and providing an stmin value in microseconds as a 32bit unsigned integer; received Consecutive Frames (CF) which timestamps differ less than this value will be ignored:



```C
uint32_t stmin;
ret = setsockopt(s, SOL_CAN_ISOTP, CAN_ISOTP_RX_STMIN, &stmin, sizeof(stmin));
```

<a id="rst-multi-frame-transport-support"></a>

### Multi-frame transport support

The ISO-TP stack contained inside the Linux kernel supports the multi-frame transport mechanism defined by the standard, with the following constraints:

- the maximum size of a PDU is defined by a module parameter, with an hard limit imposed at build time.

- when a transmission is in progress, subsequent calls to `write(2)` will block, while calls to `send(2)` will either block or fail depending on the presence of the `MSG_DONTWAIT` flag.

- no support is present for sending "wait frames": whether a PDU can be fully received or not is decided when the First Frame is received.

<a id="rst-errors"></a>

### Errors

Following errors are reported to userspace:

<a id="rst-rx-path-errors"></a>

#### RX path errors


<table>
<tbody>
<tr>
<td>


-ETIMEDOUT

</td>
<td>


timeout of data reception

</td>
</tr>
<tr>
<td>


-EILSEQ

</td>
<td>


sequence number mismatch during a multi-frame reception

</td>
</tr>
<tr>
<td>


-EBADMSG

</td>
<td>


data reception with wrong padding

</td>
</tr>
</tbody>
</table>

<a id="rst-tx-path-errors"></a>

#### TX path errors


<table>
<tbody>
<tr>
<td>


-ECOMM

</td>
<td>


flow control reception timeout

</td>
</tr>
<tr>
<td>


-EMSGSIZE

</td>
<td>


flow control reception overflow

</td>
</tr>
<tr>
<td>


-EBADMSG

</td>
<td>


flow control reception with wrong layout/padding

</td>
</tr>
</tbody>
</table>

<a id="rst-examples"></a>

## Examples

<a id="rst-basic-node-example"></a>

### Basic node example

Following example implements a node using "normal" physical addressing, with RX ID equal to 0x18DAF142 and a TX ID equal to 0x18DA42F1. All options are left to their default.



```C
int s;
struct sockaddr_can addr;
int ret;

s = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP);
if (s < 0)
    exit(1);

addr.can_family = AF_CAN;
addr.can_ifindex = if_nametoindex("can0");
addr.can_addr.tp.tx_id = 0x18DA42F1 | CAN_EFF_FLAG;
addr.can_addr.tp.rx_id = 0x18DAF142 | CAN_EFF_FLAG;

ret = bind(s, (struct sockaddr *)&addr, sizeof(addr));
if (ret < 0)
    exit(1);

/* Data can now be received using read(s, ...) and sent using write(s, ...) */
```

<a id="rst-additional-examples"></a>

### Additional examples

More complete (and complex) examples can be found inside the `isotp*` userland tools, distributed as part of the `can-utils` utilities at: [https://github.com/linux-can/can-utils](<https://github.com/linux-can/can-utils>)

---

# J1939 Documentation

_Peios Kernel / Internals / Networking_

> SAE J1939 defines a higher layer protocol on CAN. It implements a more sophisticated addressing scheme and extends the maximum packet size above 8 bytes. Several derived specifications exist, which differ from the original J1939 on the…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-j1939-documentation"></a>

<!-- SPDX-License-Identifier: (GPL-2.0 OR MIT) -->

<a id="rst-overview-what-is-j1939"></a>

## Overview / What Is J1939

SAE J1939 defines a higher layer protocol on CAN. It implements a more sophisticated addressing scheme and extends the maximum packet size above 8 bytes. Several derived specifications exist, which differ from the original J1939 on the application level, like MilCAN A, NMEA2000, and especially ISO-11783 (ISOBUS). This last one specifies the so-called ETP (Extended Transport Protocol), which has been included in this implementation. This results in a maximum packet size of ((2 ^ 24) - 1) \* 7 bytes == 111 MiB.

<a id="rst-specifications-used"></a>

### Specifications used

- SAE J1939-21 : data link layer

- SAE J1939-81 : network management

- ISO 11783-6  : Virtual Terminal (Extended Transport Protocol)

<a id="rst-motivation"></a>
<a id="rst-j1939-motivation"></a>

## Motivation

Given the fact there's something like SocketCAN with an API similar to BSD sockets, we found some reasons to justify a kernel implementation for the addressing and transport methods used by J1939.

- **Addressing:** when a process on an ECU communicates via J1939, it should not necessarily know its source address. Although, at least one process per ECU should know the source address. Other processes should be able to reuse that address. This way, address parameters for different processes cooperating for the same ECU, are not duplicated. This way of working is closely related to the UNIX concept, where programs do just one thing and do it well.

- **Dynamic addressing:** Address Claiming in J1939 is time critical. Furthermore, data transport should be handled properly during the address negotiation. Putting this functionality in the kernel eliminates it as a requirement for \_every\_ user space process that communicates via J1939. This results in a consistent J1939 bus with proper addressing.

- **Transport:** both TP &amp; ETP reuse some PGNs to relay big packets over them. Different processes may thus use the same TP &amp; ETP PGNs without actually knowing it. The individual TP &amp; ETP sessions \_must\_ be serialized (synchronized) between different processes. The kernel solves this problem properly and eliminates the serialization (synchronization) as a requirement for \_every\_ user space process that communicates via J1939.

J1939 defines some other features (relaying, gateway, fast packet transport, ...). In-kernel code for these would not contribute to protocol stability. Therefore, these parts are left to user space.

The J1939 sockets operate on CAN network devices (see SocketCAN). Any J1939 user space library operating on CAN raw sockets will still operate properly. Since such a library does not communicate with the in-kernel implementation, care must be taken that these two do not interfere. In practice, this means they cannot share ECU addresses. A single ECU (or virtual ECU) address is used by the library exclusively, or by the in-kernel system exclusively.

<a id="rst-j1939-concepts"></a>

## J1939 concepts

<a id="rst-data-sent-to-the-j1939-stack"></a>

### Data Sent to the J1939 Stack

The data buffers sent to the J1939 stack from user space are not CAN frames themselves. Instead, they are payloads that the J1939 stack converts into proper CAN frames based on the size of the buffer and the type of transfer. The size of the buffer influences how the stack processes the data and determines the internal code path used for the transfer.

**Handling of Different Buffer Sizes:**

- **Buffers with a size of 8 bytes or less:**

  - These are handled as simple sessions internally within the stack.

  - The stack converts the buffer directly into a single CAN frame without fragmentation.

  - This type of transfer does not require an actual client (receiver) on the receiving side.

- **Buffers up to 1785 bytes:**

  - These are automatically handled as J1939 Transport Protocol (TP) transfers.

  - Internally, the stack splits the buffer into multiple 8-byte CAN frames.

  - TP transfers can be unicast or broadcast.

  - **Broadcast TP:** Does not require a receiver on the other side and can be used in broadcast scenarios.

  - **Unicast TP:** Requires an active receiver (client) on the other side to acknowledge the transfer.

- **Buffers from 1786 bytes up to 111 MiB:**

  - These are handled as ISO 11783 Extended Transport Protocol (ETP) transfers.

  - ETP transfers are used for larger payloads and are split into multiple CAN frames internally.

  - **ETP transfers (unicast):** Require a receiver on the other side to process the incoming data and acknowledge each step of the transfer.

  - ETP transfers cannot be broadcast like TP transfers, and always require a receiver for operation.

**Non-Blocking Operation with \`MSG_DONTWAIT\`:**

The J1939 stack supports non-blocking operation when used in combination with the `MSG_DONTWAIT` flag. In this mode, the stack attempts to take as much data as the available memory for the socket allows. It returns the amount of data that was successfully taken, and it is the responsibility of user space to monitor this value and handle partial transfers.

- If the stack cannot take the entire buffer, it returns the number of bytes successfully taken, and user space should handle the remainder.

- **Error handling:** When using `MSG_DONTWAIT`, the user must rely on the error queue to detect transfer errors. See the **SO_J1939_ERRQUEUE** section for details on how to subscribe to error notifications. Without the error queue, there is no other way for user space to be notified of transfer errors during non-blocking operations.

**Behavior and Requirements:**

- **Simple transfers (&lt;= 8 bytes):** Do not require a receiver on the other side, making them easy to send without needing address claiming or coordination with a destination.

- **Unicast TP/ETP:** Requires a receiver on the other side to complete the transfer. The receiver must acknowledge the transfer for the session to proceed successfully.

- **Broadcast TP:** Allows sending data without a receiver, but only works for TP transfers. ETP cannot be broadcast and always needs a receiving client.

These different behaviors depend heavily on the size of the buffer provided to the stack, and the appropriate transport mechanism (TP or ETP) is selected based on the payload size. The stack automatically manages the fragmentation and reassembly of large payloads and ensures that the correct CAN frames are generated and transmitted for each session.

<a id="rst-pgn"></a>

### PGN

The J1939 protocol uses the 29-bit CAN identifier with the following structure:

>
> <table>
> <thead>
> <tr>
> <th colspan="3">
>
>
> 29 bit CAN-ID
>
> </th>
> </tr>
> <tr>
> <th colspan="3">
>
>
> Bit positions within the CAN-ID
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 28 ... 26
>
> </th>
> <th>
>
>
> 25 ... 8
>
> </th>
> <th>
>
>
> 7 ... 0
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> Priority
>
> </td>
> <td>
>
>
> PGN
>
> </td>
> <td>
>
>
> SA (Source Address)
>
> </td>
> </tr>
> </tbody>
> </table>

The PGN (Parameter Group Number) is a number to identify a packet. The PGN is composed as follows:

>
> <table>
> <thead>
> <tr>
> <th colspan="4">
>
>
> PGN
>
> </th>
> </tr>
> <tr>
> <th colspan="4">
>
>
> Bit positions within the CAN-ID
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 25
>
> </th>
> <th>
>
>
> 24
>
> </th>
> <th>
>
>
> 23 ... 16
>
> </th>
> <th>
>
>
> 15 ... 8
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> R (Reserved)
>
> </td>
> <td>
>
>
> DP (Data Page)
>
> </td>
> <td>
>
>
> PF (PDU Format)
>
> </td>
> <td>
>
>
> PS (PDU Specific)
>
> </td>
> </tr>
> </tbody>
> </table>

In J1939-21 distinction is made between PDU1 format (where PF &lt; 240) and PDU2 format (where PF &gt;= 240). Furthermore, when using the PDU2 format, the PS-field contains a so-called Group Extension, which is part of the PGN. When using PDU2 format, the Group Extension is set in the PS-field.

>
> <table>
> <thead>
> <tr>
> <th colspan="2">
>
>
> PDU1 Format (specific) (peer to peer)
>
> </th>
> </tr>
> <tr>
> <th colspan="2">
>
>
> Bit positions within the CAN-ID
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 23 ... 16
>
> </th>
> <th>
>
>
> 15 ... 8
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 00h ... EFh
>
> </td>
> <td>
>
>
> DA (Destination address)
>
> </td>
> </tr>
> </tbody>
> </table>
>
>
> <table>
> <thead>
> <tr>
> <th colspan="2">
>
>
> PDU2 Format (global) (broadcast)
>
> </th>
> </tr>
> <tr>
> <th colspan="2">
>
>
> Bit positions within the CAN-ID
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 23 ... 16
>
> </th>
> <th>
>
>
> 15 ... 8
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> F0h ... FFh
>
> </td>
> <td>
>
>
> GE (Group Extension)
>
> </td>
> </tr>
> </tbody>
> </table>

On the other hand, when using PDU1 format, the PS-field contains a so-called Destination Address, which is \_not\_ part of the PGN. When communicating a PGN from user space to kernel (or vice versa) and PDU1 format is used, the PS-field of the PGN shall be set to zero. The Destination Address shall be set elsewhere.

Regarding PGN mapping to 29-bit CAN identifier, the Destination Address shall be get/set from/to the appropriate bits of the identifier by the kernel.

<a id="rst-addressing"></a>

### Addressing

Both static and dynamic addressing methods can be used.

For static addresses, no extra checks are made by the kernel and provided addresses are considered right. This responsibility is for the OEM or system integrator.

For dynamic addressing, so-called Address Claiming, extra support is foreseen in the kernel. In J1939 any ECU is known by its 64-bit NAME. At the moment of a successful address claim, the kernel keeps track of both NAME and source address being claimed. This serves as a base for filter schemes. By default, packets with a destination that is not locally will be rejected.

Mixed mode packets (from a static to a dynamic address or vice versa) are allowed. The BSD sockets define separate API calls for getting/setting the local &amp; remote address and are applicable for J1939 sockets.

<a id="rst-filtering"></a>

### Filtering

J1939 defines white list filters per socket that a user can set in order to receive a subset of the J1939 traffic. Filtering can be based on:

- SA

- SOURCE_NAME

- PGN

When multiple filters are in place for a single socket, and a packet comes in that matches several of those filters, the packet is only received once for that socket.

<a id="rst-how-to-use-j1939"></a>

## How to Use J1939

<a id="rst-api-calls"></a>

### API Calls

On CAN, you first need to open a socket for communicating over a CAN network. To use J1939, `#include <linux/can/j1939.h>`. From there, `<linux/can.h>` will be included too. To open a socket, use:



```C
s = socket(PF_CAN, SOCK_DGRAM, CAN_J1939);
```

J1939 does use `SOCK_DGRAM` sockets. In the J1939 specification, connections are mentioned in the context of transport protocol sessions. These still deliver packets to the other end (using several CAN packets). `SOCK_STREAM` is not supported.

After the successful creation of the socket, you would normally use the `bind(2)` and/or `connect(2)` system call to bind the socket to a CAN interface. After binding and/or connecting the socket, you can `read(2)` and `write(2)` from/to the socket or use `send(2)`, `sendto(2)`, `sendmsg(2)` and the `recv*()` counterpart operations on the socket as usual. There are also J1939 specific socket options described below.

In order to send data, a `bind(2)` must have been successful. `bind(2)` assigns a local address to a socket.

Different from CAN is that the payload data is just the data that get sends, without its header info. The header info is derived from the sockaddr supplied to `bind(2)`, `connect(2)`, `sendto(2)` and `recvfrom(2)`. A `write(2)` with size 4 will result in a packet with 4 bytes.

The sockaddr structure has extensions for use with J1939 as specified below:



```C
struct sockaddr_can {
   sa_family_t can_family;
   int         can_ifindex;
   union {
      struct {
         __u64 name;
                  /* pgn:
                   * 8 bit: PS in PDU2 case, else 0
                   * 8 bit: PF
                   * 1 bit: DP
                   * 1 bit: reserved
                   */
         __u32 pgn;
         __u8  addr;
      } j1939;
   } can_addr;
}
```

`can_family` &amp; `can_ifindex` serve the same purpose as for other SocketCAN sockets.

`can_addr.j1939.pgn` specifies the PGN (max 0x3ffff). Individual bits are specified above.

`can_addr.j1939.name` contains the 64-bit J1939 NAME.

`can_addr.j1939.addr` contains the address.

The `bind(2)` system call assigns the local address, i.e. the source address when sending packages. If a PGN during `bind(2)` is set, it's used as a RX filter. I.e. only packets with a matching PGN are received. If an ADDR or NAME is set it is used as a receive filter, too. It will match the destination NAME or ADDR of the incoming packet. The NAME filter will work only if appropriate Address Claiming for this name was done on the CAN bus and registered/cached by the kernel.

On the other hand `connect(2)` assigns the remote address, i.e. the destination address. The PGN from `connect(2)` is used as the default PGN when sending packets. If ADDR or NAME is set it will be used as the default destination ADDR or NAME. Further a set ADDR or NAME during `connect(2)` is used as a receive filter. It will match the source NAME or ADDR of the incoming packet.

Both `write(2)` and `send(2)` will send a packet with local address from `bind(2)` and the remote address from `connect(2)`. Use `sendto(2)` to overwrite the destination address.

If `can_addr.j1939.name` is set (\!= 0) the NAME is looked up by the kernel and the corresponding ADDR is used. If `can_addr.j1939.name` is not set (== 0), `can_addr.j1939.addr` is used.

When creating a socket, reasonable defaults are set. Some options can be modified with `setsockopt(2)` &amp; `getsockopt(2)`.

RX path related options:

- `SO_J1939_FILTER` - configure array of filters

- `SO_J1939_PROMISC` - disable filters set by `bind(2)` and `connect(2)`

By default no broadcast packets can be send or received. To enable sending or receiving broadcast packets use the socket option `SO_BROADCAST`:



```C
int value = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
```

The following diagram illustrates the RX path:



```text
               +--------------------+
               |  incoming packet   |
               +--------------------+
                         |
                         V
               +--------------------+
               | SO_J1939_PROMISC?  |
               +--------------------+
                        |  |
                    no  |  | yes
                        |  |
              .---------'  `---------.
              |                      |
+---------------------------+        |
| bind() + connect() +      |        |
| SOCK_BROADCAST filter     |        |
+---------------------------+        |
              |                      |
              |<---------------------'
              V
+---------------------------+
|      SO_J1939_FILTER      |
+---------------------------+
              |
              V
+---------------------------+
|        socket recv()      |
+---------------------------+
```

TX path related options: `SO_J1939_SEND_PRIO` - change default send priority for the socket

<a id="rst-message-flags-during-send-and-related-system-calls"></a>

#### Message Flags during send() and Related System Calls

`send(2)`, `sendto(2)` and `sendmsg(2)` take a 'flags' argument. Currently supported flags are:

- `MSG_DONTWAIT`, i.e. non-blocking operation.

<a id="rst-recvmsg-2"></a>

#### recvmsg(2)

In most cases `recvmsg(2)` is needed if you want to extract more information than `recvfrom(2)` can provide. For example package priority and timestamp. The Destination Address, name and packet priority (if applicable) are attached to the msghdr in the `recvmsg(2)` call. They can be extracted using `cmsg(3)` macros, with `cmsg_level == SOL_J1939 && cmsg_type == SCM_J1939_DEST_ADDR`, `SCM_J1939_DEST_NAME` or `SCM_J1939_PRIO`. The returned data is a `uint8_t` for `priority` and `dst_addr`, and `uint64_t` for `dst_name`.



```C
uint8_t priority, dst_addr;
uint64_t dst_name;

for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
        switch (cmsg->cmsg_level) {
        case SOL_CAN_J1939:
                if (cmsg->cmsg_type == SCM_J1939_DEST_ADDR)
                        dst_addr = *CMSG_DATA(cmsg);
                else if (cmsg->cmsg_type == SCM_J1939_DEST_NAME)
                        memcpy(&dst_name, CMSG_DATA(cmsg), cmsg->cmsg_len - CMSG_LEN(0));
                else if (cmsg->cmsg_type == SCM_J1939_PRIO)
                        priority = *CMSG_DATA(cmsg);
                break;
        }
}
```

<a id="rst-setsockopt-2"></a>

#### setsockopt(2)

The `setsockopt(2)` function is used to configure various socket-level options for J1939 communication. The following options are supported:

<a id="rst-so-j1939-filter"></a>

##### `SO_J1939_FILTER`

The `SO_J1939_FILTER` option is essential when the default behavior of `bind(2)` and `connect(2)` is insufficient for specific use cases. By default, `bind(2)` and `connect(2)` allow a socket to be associated with a single unicast or broadcast address. However, there are scenarios where finer control over the incoming messages is required, such as filtering by Parameter Group Number (PGN) rather than by addresses.

For example, in a system where multiple types of J1939 messages are being transmitted, a process might only be interested in a subset of those messages, such as specific PGNs, and not want to receive all messages destined for its address or broadcast to the bus.

By applying the `SO_J1939_FILTER` option, you can filter messages based on:

- **Source Address (SA)**: Filter messages coming from specific source addresses.

- **Source Name**: Filter messages coming from ECUs with specific NAME identifiers.

- **Parameter Group Number (PGN)**: Focus on receiving messages with specific PGNs, filtering out irrelevant ones.

This filtering mechanism is particularly useful when:

- You want to receive a subset of messages based on their PGNs, even if the address is the same.

- You need to handle both broadcast and unicast messages but only care about certain message types or parameters.

- The `bind(2)` and `connect(2)` functions only allow binding to a single address, which might not be sufficient if the process needs to handle multiple PGNs but does not want to open multiple sockets.

To remove existing filters, you can pass `optval == NULL` or `optlen == 0` to `setsockopt(2)`. This will clear all currently set filters. If you want to **update** the set of filters, you must pass the updated filter set to `setsockopt(2)`, as the new filter set will **replace** the old one entirely. This behavior ensures that any previous filter configuration is discarded and only the new set is applied.

Example of removing all filters:



```c
setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, NULL, 0);
```

**Maximum number of filters:** The maximum amount of filters that can be applied using `SO_J1939_FILTER` is defined by `J1939_FILTER_MAX`, which is set to 512. This means you can configure up to 512 individual filters to match your specific filtering needs.

Practical use case: **Monitoring Address Claiming**

One practical use case is monitoring the J1939 address claiming process by filtering for specific PGNs related to address claiming. This allows a process to monitor and handle address claims without processing unrelated messages.

Example:



```c
struct j1939_filter filt[] = {
    {
        .pgn = J1939_PGN_ADDRESS_CLAIMED,
        .pgn_mask = J1939_PGN_PDU1_MAX,
    }, {
        .pgn = J1939_PGN_REQUEST,
        .pgn_mask = J1939_PGN_PDU1_MAX,
    }, {
        .pgn = J1939_PGN_ADDRESS_COMMANDED,
        .pgn_mask = J1939_PGN_MAX,
    },
};
setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));
```

In this example, the socket will only receive messages with the PGNs related to address claiming: `J1939_PGN_ADDRESS_CLAIMED`, `J1939_PGN_REQUEST`, and `J1939_PGN_ADDRESS_COMMANDED`. This is particularly useful in scenarios where you want to monitor and process address claims without being overwhelmed by other traffic on the J1939 network.

<a id="rst-so-j1939-promisc"></a>

##### `SO_J1939_PROMISC`

The `SO_J1939_PROMISC` option enables socket-level promiscuous mode. When this option is enabled, the socket will receive all J1939 traffic, regardless of any filters set by `bind()` or `connect()`. This is analogous to enabling promiscuous mode for an Ethernet interface, where all traffic on the network segment is captured.

However, **\`SO_J1939_FILTER\` has a higher priority** compared to `SO_J1939_PROMISC`. This means that even in promiscuous mode, you can reduce the number of packets received by applying specific filters with `SO_J1939_FILTER`. The filters will limit which packets are passed to the socket, allowing for more refined traffic selection while promiscuous mode is active.

The acceptable value size for this option is `sizeof(int)`, and the value is only differentiated between `0` and non-zero. A value of `0` disables promiscuous mode, while any non-zero value enables it.

This combination can be useful for debugging or monitoring specific types of traffic while still capturing a broad set of messages.

Example:



```c
int value = 1;
setsockopt(sock, SOL_CAN_J1939, SO_J1939_PROMISC, &value, sizeof(value));
```

In this example, setting `value` to any non-zero value (e.g., `1`) enables promiscuous mode, allowing the socket to receive all J1939 traffic on the network.

<a id="rst-so-broadcast"></a>

##### `SO_BROADCAST`

The `SO_BROADCAST` option enables the sending and receiving of broadcast messages. By default, broadcast messages are disabled for J1939 sockets. When this option is enabled, the socket will be allowed to send and receive broadcast packets on the J1939 network.

Due to the nature of the CAN bus as a shared medium, all messages transmitted on the bus are visible to all participants. In the context of J1939, broadcasting refers to using a specific destination address field, where the destination address is set to a value that indicates the message is intended for all participants (usually a global address such as 0xFF). Enabling the broadcast option allows the socket to send and receive such broadcast messages.

The acceptable value size for this option is `sizeof(int)`, and the value is only differentiated between `0` and non-zero. A value of `0` disables the ability to send and receive broadcast messages, while any non-zero value enables it.

Example:



```c
int value = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));
```

In this example, setting `value` to any non-zero value (e.g., `1`) enables the socket to send and receive broadcast messages.

<a id="rst-so-j1939-send-prio"></a>

##### `SO_J1939_SEND_PRIO`

The `SO_J1939_SEND_PRIO` option sets the priority of outgoing J1939 messages for the socket. In J1939, messages can have different priorities, and lower numerical values indicate higher priority. This option allows the user to control the priority of messages sent from the socket by adjusting the priority bits in the CAN identifier.

The acceptable value **size** for this option is `sizeof(int)`, and the value is expected to be in the range of 0 to 7, where `0` is the highest priority, and `7` is the lowest. By default, the priority is set to `6` if this option is not explicitly configured.

Note that the priority values `0` and `1` can only be set if the process has the `CAP_NET_ADMIN` capability. These are reserved for high-priority traffic and require administrative privileges.

Example:



```c
int prio = 3;  // Priority value between 0 (highest) and 7 (lowest)
setsockopt(sock, SOL_CAN_J1939, SO_J1939_SEND_PRIO, &prio, sizeof(prio));
```

In this example, the priority is set to `3`, meaning the outgoing messages will be sent with a moderate priority level.

<a id="rst-so-j1939-errqueue"></a>

##### `SO_J1939_ERRQUEUE`

The `SO_J1939_ERRQUEUE` option enables the socket to receive error messages from the error queue, providing diagnostic information about transmission failures, protocol violations, or other issues that occur during J1939 communication. Once this option is set, user space is required to handle `MSG_ERRQUEUE` messages.

Setting `SO_J1939_ERRQUEUE` to `0` will purge any currently present error messages in the error queue. When enabled, error messages can be retrieved using the `recvmsg(2)` system call.

When subscribing to the error queue, the following error events can be accessed:

- **\`\`J1939_EE_INFO_TX_ABORT\`\`**: Transmission abort errors.

- **\`\`J1939_EE_INFO_RX_RTS\`\`**: Reception of RTS (Request to Send) control frames.

- **\`\`J1939_EE_INFO_RX_DPO\`\`**: Reception of data packets with Data Page Offset (DPO).

- **\`\`J1939_EE_INFO_RX_ABORT\`\`**: Reception abort errors.

The error queue can be used to correlate errors with specific message transfer sessions using the session ID (`tskey`). The session ID is assigned via the `SOF_TIMESTAMPING_OPT_ID` flag, which is set by enabling the `SO_TIMESTAMPING` option.

If `SO_J1939_ERRQUEUE` is activated, the user is required to pull messages from the error queue, meaning that using plain `recv(2)` is not sufficient anymore. The user must use `recvmsg(2)` with appropriate flags to handle error messages. Failure to do so can result in the socket becoming blocked with unprocessed error messages in the queue.

It is **recommended** that `SO_J1939_ERRQUEUE` be used in combination with `SO_TIMESTAMPING` in most cases. This enables proper error handling along with session tracking and timestamping, providing a more detailed analysis of message transfers and errors.

The acceptable value **size** for this option is `sizeof(int)`, and the value is only differentiated between `0` and non-zero. A value of `0` disables error queue reception and purges any existing error messages, while any non-zero value enables it.

Example:



```c
int enable = 1;  // Enable error queue reception
setsockopt(sock, SOL_CAN_J1939, SO_J1939_ERRQUEUE, &enable, sizeof(enable));

// Enable timestamping with session tracking via tskey
int timestamping = SOF_TIMESTAMPING_OPT_ID | SOF_TIMESTAMPING_TX_ACK |
                   SOF_TIMESTAMPING_TX_SCHED |
                   SOF_TIMESTAMPING_RX_SOFTWARE | SOF_TIMESTAMPING_OPT_CMSG;
setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &timestamping,
           sizeof(timestamping));
```

When enabled, error messages can be retrieved using `recvmsg(2)`. By combining `SO_J1939_ERRQUEUE` with `SO_TIMESTAMPING` (with `SOF_TIMESTAMPING_OPT_ID` and `SOF_TIMESTAMPING_OPT_CMSG` enabled), the user can track message transfers, retrieve precise timestamps, and correlate errors with specific sessions.

For more information on enabling timestamps and session tracking, refer to the `SO_TIMESTAMPING` section.

<a id="rst-so-timestamping"></a>

##### `SO_TIMESTAMPING`

The `SO_TIMESTAMPING` option allows the socket to receive timestamps for various events related to message transmissions and receptions in J1939. This option is often used in combination with `SO_J1939_ERRQUEUE` to provide detailed diagnostic information, session tracking, and precise timing data for message transfers.

In J1939, all payloads provided by user space, regardless of size, are processed by the kernel as **sessions**. This includes both single-frame messages (up to 8 bytes) and multi-frame protocols such as the Transport Protocol (TP) and Extended Transport Protocol (ETP). Even for small, single-frame messages, the kernel creates a session to manage the transmission and reception. The concept of sessions allows the kernel to manage various aspects of the protocol, such as reassembling multi-frame messages and tracking the status of transmissions.

When receiving extended error messages from the error queue, the error information is delivered through a `struct sock_extended_err`, accessible via the control message (`cmsg`) retrieved using the `recvmsg(2)` system call.

There are two typical origins for the extended error messages in J1939:

1. `serr->ee_origin == SO_EE_ORIGIN_TIMESTAMPING`:

   In this case, the `serr->ee_info` field will contain one of the following timestamp types:

   - `SCM_TSTAMP_SCHED`: This timestamp is valid for Extended Transport Protocol (ETP) transfers and simple transfers (8 bytes or less). It indicates when a message or set of frames has been scheduled for transmission.

     - For simple transfers (8 bytes or less), it marks the point when the message is queued and ready to be sent onto the CAN bus.

     - For ETP transfers, it is sent after receiving a CTS (Clear to Send) frame on the sender side, indicating that a new set of frames has been scheduled for transmission.

     - The Transport Protocol (TP) case is currently not implemented for this timestamp.

     - On the receiver side, the counterpart to this event for ETP is represented by the `J1939_EE_INFO_RX_DPO` message, which indicates the reception of a Data Page Offset (DPO) control frame.

   - `SCM_TSTAMP_ACK`: This timestamp indicates the acknowledgment of the message or session.

     - For simple transfers (8 bytes or less), it marks when the message has been sent and an echo confirmation has been received from the CAN controller, indicating that the frame was transmitted onto the bus.

     - For multi-frame transfers (TP or ETP), it signifies that the entire session has been acknowledged, typically after receiving the End of Message Acknowledgment (EOMA) packet.

2. `serr->ee_origin == SO_EE_ORIGIN_LOCAL`:

   In this case, the `serr->ee_info` field will contain one of the following J1939 stack-specific message types:

   - `J1939_EE_INFO_TX_ABORT`: This message indicates that the transmission of a message or session was aborted. The cause of the abort can come from various sources:

     - **CAN stack failure**: The J1939 stack was unable to pass the frame to the CAN framework for transmission.

     - **Echo failure**: The J1939 stack did not receive an echo confirmation from the CAN controller, meaning the frame may not have been successfully transmitted to the CAN bus.

     - **Protocol-level issues**: For multi-frame transfers (TP/ETP), this could include protocol-related errors, such as an abort signaled by the receiver or a timeout at the protocol level, which causes the session to terminate prematurely.

     - The corresponding error code is stored in `serr->ee_data` (`session->err` on kernel side), providing additional details about the specific reason for the abort.

   - `J1939_EE_INFO_RX_RTS`: This message indicates that the J1939 stack has received a Request to Send (RTS) control frame, signaling the start of a multi-frame transfer using the Transport Protocol (TP) or Extended Transport Protocol (ETP).

     - It informs the receiver that the sender is ready to transmit a multi-frame message and includes details about the total message size and the number of frames to be sent.

     - Statistics such as `J1939_NLA_TOTAL_SIZE`, `J1939_NLA_PGN`, `J1939_NLA_SRC_NAME`, and `J1939_NLA_DEST_NAME` are provided along with the `J1939_EE_INFO_RX_RTS` message, giving detailed information about the incoming transfer.

   - `J1939_EE_INFO_RX_DPO`: This message indicates that the J1939 stack has received a Data Page Offset (DPO) control frame, which is part of the Extended Transport Protocol (ETP).

     - The DPO frame signals the continuation of an ETP multi-frame message by indicating the offset position in the data being transferred. It helps the receiver manage large data sets by identifying which portion of the message is being received.

     - It is typically paired with a corresponding `SCM_TSTAMP_SCHED` event on the sender side, which indicates when the next set of frames is scheduled for transmission.

     - This event includes statistics such as `J1939_NLA_BYTES_ACKED`, which tracks the number of bytes acknowledged up to that point in the session.

   - `J1939_EE_INFO_RX_ABORT`: This message indicates that the reception of a multi-frame message (Transport Protocol or Extended Transport Protocol) has been aborted.

     - The abort can be triggered by protocol-level errors such as timeouts, an unexpected frame, or a specific abort request from the sender.

     - This message signals that the receiver cannot continue processing the transfer, and the session is terminated.

     - The corresponding error code is stored in `serr->ee_data` (`session->err` on kernel side ), providing further details about the reason for the abort, such as protocol violations or timeouts.

     - After receiving this message, the receiver discards the partially received frames, and the multi-frame session is considered incomplete.

In both cases, if `SOF_TIMESTAMPING_OPT_ID` is enabled, `serr->ee_data` will be set to the session’s unique identifier (`session->tskey`). This allows user space to track message transfers by their session identifier across multiple frames or stages.

In all other cases, `serr->ee_errno` will be set to `ENOMSG`, except for the `J1939_EE_INFO_TX_ABORT` and `J1939_EE_INFO_RX_ABORT` cases, where the kernel sets `serr->ee_data` to the error stored in `session->err`.  All protocol-specific errors are converted to standard kernel error values and stored in `session->err`. These error values are unified across system calls and `serr->ee_errno`.  Some of the known error values are described in the `Error Codes in the J1939 Stack` section.

When the `J1939_EE_INFO_RX_RTS` message is provided, it will include the following statistics for multi-frame messages (TP and ETP):

> - `J1939_NLA_TOTAL_SIZE`: Total size of the message in the session.
>
> - `J1939_NLA_PGN`: Parameter Group Number (PGN) identifying the message type.
>
> - `J1939_NLA_SRC_NAME`: 64-bit name of the source ECU.
>
> - `J1939_NLA_DEST_NAME`: 64-bit name of the destination ECU.
>
> - `J1939_NLA_SRC_ADDR`: 8-bit source address of the sending ECU.
>
> - `J1939_NLA_DEST_ADDR`: 8-bit destination address of the receiving ECU.

- For other messages (including single-frame messages), only the following statistic is included:

  - `J1939_NLA_BYTES_ACKED`: Number of bytes successfully acknowledged in the session.

The key flags for `SO_TIMESTAMPING` include:

- `SOF_TIMESTAMPING_OPT_ID`: Enables the use of a unique session identifier (`tskey`) for each transfer. This identifier helps track message transfers and errors as distinct sessions in user space. When this option is enabled, `serr->ee_data` will be set to `session->tskey`.

- `SOF_TIMESTAMPING_OPT_CMSG`: Sends timestamp information through control messages (`struct scm_timestamping`), allowing the application to retrieve timestamps alongside the data.

- `SOF_TIMESTAMPING_TX_SCHED`: Provides the timestamp for when a message is scheduled for transmission (`SCM_TSTAMP_SCHED`).

- `SOF_TIMESTAMPING_TX_ACK`: Provides the timestamp for when a message transmission is fully acknowledged (`SCM_TSTAMP_ACK`).

- `SOF_TIMESTAMPING_RX_SOFTWARE`: Provides timestamps for reception-related events (e.g., `J1939_EE_INFO_RX_RTS`, `J1939_EE_INFO_RX_DPO`, `J1939_EE_INFO_RX_ABORT`).

These flags enable detailed monitoring of message lifecycles, including transmission scheduling, acknowledgments, reception timestamps, and gathering detailed statistics about the communication session, especially for multi-frame payloads like TP and ETP.

Example:



```c
// Enable timestamping with various options, including session tracking and
// statistics
int sock_opt = SOF_TIMESTAMPING_OPT_CMSG |
               SOF_TIMESTAMPING_TX_ACK |
               SOF_TIMESTAMPING_TX_SCHED |
               SOF_TIMESTAMPING_OPT_ID |
               SOF_TIMESTAMPING_RX_SOFTWARE;

setsockopt(sock, SOL_SOCKET, SO_TIMESTAMPING, &sock_opt, sizeof(sock_opt));
```

<a id="rst-dynamic-addressing"></a>

### Dynamic Addressing

Distinction has to be made between using the claimed address and doing an address claim. To use an already claimed address, one has to fill in the `j1939.name` member and provide it to `bind(2)`. If the name had claimed an address earlier, all further messages being sent will use that address. And the `j1939.addr` member will be ignored.

An exception on this is PGN 0x0ee00. This is the "Address Claim/Cannot Claim Address" message and the kernel will use the `j1939.addr` member for that PGN if necessary.

To claim an address following code example can be used:



```C
struct sockaddr_can baddr = {
        .can_family = AF_CAN,
        .can_addr.j1939 = {
                .name = name,
                .addr = J1939_IDLE_ADDR,
                .pgn = J1939_NO_PGN,    /* to disable bind() rx filter for PGN */
        },
        .can_ifindex = if_nametoindex("can0"),
};

bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));

/* for Address Claiming broadcast must be allowed */
int value = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &value, sizeof(value));

/* configured advanced RX filter with PGN needed for Address Claiming */
const struct j1939_filter filt[] = {
        {
                .pgn = J1939_PGN_ADDRESS_CLAIMED,
                .pgn_mask = J1939_PGN_PDU1_MAX,
        }, {
                .pgn = J1939_PGN_REQUEST,
                .pgn_mask = J1939_PGN_PDU1_MAX,
        }, {
                .pgn = J1939_PGN_ADDRESS_COMMANDED,
                .pgn_mask = J1939_PGN_MAX,
        },
};

setsockopt(sock, SOL_CAN_J1939, SO_J1939_FILTER, &filt, sizeof(filt));

uint64_t dat = htole64(name);
const struct sockaddr_can saddr = {
        .can_family = AF_CAN,
        .can_addr.j1939 = {
                .pgn = J1939_PGN_ADDRESS_CLAIMED,
                .addr = J1939_NO_ADDR,
        },
};

/* Afterwards do a sendto(2) with data set to the NAME (Little Endian). If the
 * NAME provided, does not match the j1939.name provided to bind(2), EPROTO
 * will be returned.
 */
sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));
```

If no-one else contests the address claim within 250ms after transmission, the kernel marks the NAME-SA assignment as valid. The valid assignment will be kept among other valid NAME-SA assignments. From that point, any socket bound to the NAME can send packets.

If another ECU claims the address, the kernel will mark the NAME-SA expired. No socket bound to the NAME can send packets (other than address claims). To claim another address, some socket bound to NAME, must `bind(2)` again, but with only `j1939.addr` changed to the new SA, and must then send a valid address claim packet. This restarts the state machine in the kernel (and any other participant on the bus) for this NAME.

`can-utils` also include the `j1939acd` tool, so it can be used as code example or as default Address Claiming daemon.

<a id="rst-send-examples"></a>

### Send Examples

<a id="rst-static-addressing"></a>

#### Static Addressing

This example will send a PGN (0x12300) from SA 0x20 to DA 0x30.

Bind:



```C
struct sockaddr_can baddr = {
        .can_family = AF_CAN,
        .can_addr.j1939 = {
                .name = J1939_NO_NAME,
                .addr = 0x20,
                .pgn = J1939_NO_PGN,
        },
        .can_ifindex = if_nametoindex("can0"),
};

bind(sock, (struct sockaddr *)&baddr, sizeof(baddr));
```

Now, the socket 'sock' is bound to the SA 0x20. Since no `connect(2)` was called, at this point we can use only `sendto(2)` or `sendmsg(2)`.

Send:



```C
const struct sockaddr_can saddr = {
        .can_family = AF_CAN,
        .can_addr.j1939 = {
                .name = J1939_NO_NAME;
                .addr = 0x30,
                .pgn = 0x12300,
        },
};

sendto(sock, dat, sizeof(dat), 0, (const struct sockaddr *)&saddr, sizeof(saddr));
```

<a id="rst-error-codes-in-the-j1939-stack"></a>

### Error Codes in the J1939 Stack

This section lists all potential kernel error codes that can be exposed to user space when interacting with the J1939 stack. It includes both standard error codes and those derived from protocol-specific abort codes.

- `EAGAIN`: Operation would block; retry may succeed. One common reason is that an active TP or ETP session exists, and an attempt was made to start a new overlapping TP or ETP session between the same peers.

- `ENETDOWN`: Network is down. This occurs when the CAN interface is switched to the "down" state.

- `ENOBUFS`: No buffer space available. This error occurs when the CAN interface's transmit (TX) queue is full, and no more messages can be queued.

- `EOVERFLOW`: Value too large for defined data type. In J1939, this can happen if the requested data lies outside of the queued buffer. For example, if a CTS (Clear to Send) requests an offset not available in the kernel buffer because user space did not provide enough data.

- `EBUSY`: Device or resource is busy. For example, this occurs if an identical session is already active and the stack is unable to recover from the condition.

- `EACCES`: Permission denied. This error can occur, for example, when attempting to send broadcast messages, but the socket is not configured with `SO_BROADCAST`.

- `EADDRNOTAVAIL`: Address not available. This error occurs in cases such as:

  - When attempting to use `getsockname(2)` to retrieve the peer's address, but the socket is not connected.

  - When trying to send data to or from a NAME, but address claiming for the NAME was not performed or detected by the stack.

- `EBADFD`: File descriptor in bad state. This error can occur if:

  - Attempting to send data to an unbound socket.

  - The socket is bound but has no source name, and the source address is `J1939_NO_ADDR`.

  - The `can_ifindex` is incorrect.

- `EFAULT`: Bad address. Occurs mostly when the stack can't copy from or to a sockptr, when there is insufficient data from user space, or when the buffer provided by user space is not large enough for the requested data.

- `EINTR`: A signal occurred before any data was transmitted; see `signal(7)`.

- `EINVAL`: Invalid argument passed. For example:

  - `msg->msg_namelen` is less than `J1939_MIN_NAMELEN`.

  - `addr->can_family` is not equal to `AF_CAN`.

  - An incorrect PGN was provided.

- `ENODEV`: No such device. This happens when the CAN network device cannot be found for the provided `can_ifindex` or if `can_ifindex` is 0.

- `ENOMEM`: Out of memory. Typically related to issues with memory allocation in the stack.

- `ENOPROTOOPT`: Protocol not available. This can occur when using `getsockopt(2)` or `setsockopt(2)` if the requested socket option is not available.

- `EDESTADDRREQ`: Destination address required. This error occurs:

  - In the case of `connect(2)`, if the `struct sockaddr *uaddr` is `NULL`.

  - In the case of `send*(2)`, if there is an attempt to send an ETP message to a broadcast address.

- `EDOM`: Argument out of domain. This error may happen if attempting to send a TP or ETP message to a PGN that is reserved for control PGNs for TP or ETP operations.

- `EIO`: I/O error. This can occur if the amount of data provided to the socket for a TP or ETP session does not match the announced amount of data for the session.

- `ENOENT`: No such file or directory. This can happen when the stack attempts to transfer CTS or EOMA but cannot find a matching receiving socket anymore.

- `ENOIOCTLCMD`: No ioctls are available for the socket layer.

- `EPERM`: Operation not permitted. For example, this can occur if a requested action requires `CAP_NET_ADMIN` privileges.

- `ENETUNREACH`: Network unreachable. Most likely, this occurs when frames cannot be transmitted to the CAN bus.

- `ETIME`: Timer expired. This can happen if a timeout occurs while attempting to send a simple message, for example, when an echo message from the controller is not received.

- `EPROTO`: Protocol error.

  - Used for various protocol-level errors in J1939, including:

    - Duplicate sequence number.

    - Unexpected EDPO or ECTS packet.

    - Invalid PGN or offset in EDPO/ECTS.

    - Number of EDPO packets exceeded CTS allowance.

    - Any other protocol-level error.

- `EMSGSIZE`: Message too long.

- `ENOMSG`: No message available.

- `EALREADY`: The ECU is already engaged in one or more connection-managed sessions and cannot support another.

- `EHOSTUNREACH`: A timeout occurred, and the session was aborted.

- `EBADMSG`: CTS (Clear to Send) messages were received during an active data transfer, causing an abort.

- `ENOTRECOVERABLE`: The maximum retransmission request limit was reached, and the session cannot recover.

- `ENOTCONN`: An unexpected data transfer packet was received.

- `EILSEQ`: A bad sequence number was received, and the software could not recover.

---

# Linux Networking and Network Devices APIs

_Peios Kernel / Internals / Networking_

> PHYLINK interfaces traditional network drivers with PHYLIB, fixed-links, and SFF modules (eg, hot-pluggable SFP) that may contain PHYs. PHYLINK provides management of the link state and link modes.

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-linux-networking-and-network-devices-apis"></a>

<a id="rst-linux-networking"></a>

## Linux Networking

<a id="rst-networking-base-types"></a>

### Networking Base Types


#### <a id="c-enum-sock_type"></a>`enum sock_type`

Socket types

**Constants**

- `SOCK_STREAM`: stream (connection) socket
- `SOCK_DGRAM`: datagram (conn.less) socket
- `SOCK_RAW`: raw socket
- `SOCK_RDM`: reliably-delivered message
- `SOCK_SEQPACKET`: sequential packet socket
- `SOCK_DCCP`: Datagram Congestion Control Protocol socket
- `SOCK_PACKET`: linux specific way of getting packets at the dev level.
  For writing rarp and other similar things on the user level.

**Description**

When adding some new socket type please
grep ARCH_HAS_SOCKET_TYPE include/asm-* /socket.h, at least MIPS
overrides this enum for binary compat reasons.

#### <a id="c-enum-sock_shutdown_cmd"></a>`enum sock_shutdown_cmd`

Shutdown types

**Constants**

- `SHUT_RD`: shutdown receptions
- `SHUT_WR`: shutdown transmissions
- `SHUT_RDWR`: shutdown receptions/transmissions

#### <a id="c-struct-socket"></a>`struct socket`

general BSD socket

**Definition**

```c
struct socket {
    socket_state state;
    short type;
    unsigned long           flags;
    struct file             *file;
    struct sock             *sk;
    const struct proto_ops  *ops;
    struct socket_wq        wq;
};
```

**Members**

- `state`: socket state (`SS_CONNECTED`, etc)
- `type`: socket type (`SOCK_STREAM`, etc)
- `flags`: socket flags (`SOCK_NOSPACE`, etc)
- `file`: File back pointer for gc
- `sk`: internal networking protocol agnostic socket representation
- `ops`: protocol specific socket operations
- `wq`: wait queue for several uses


<a id="rst-socket-buffer-functions"></a>

### Socket Buffer Functions


#### <a id="c-skb_frag_size"></a>`skb_frag_size()`

```c
unsigned int skb_frag_size(const skb_frag_t *frag)
```

Returns the size of a skb fragment

**Parameters**

- `const skb_frag_t *frag`: skb fragment

#### <a id="c-skb_frag_size_set"></a>`skb_frag_size_set()`

```c
void skb_frag_size_set(skb_frag_t *frag, unsigned int size)
```

Sets the size of a skb fragment

**Parameters**

- `skb_frag_t *frag`: skb fragment
- `unsigned int size`: size of fragment

#### <a id="c-skb_frag_size_add"></a>`skb_frag_size_add()`

```c
void skb_frag_size_add(skb_frag_t *frag, int delta)
```

Increments the size of a skb fragment by **delta**

**Parameters**

- `skb_frag_t *frag`: skb fragment
- `int delta`: value to add

#### <a id="c-skb_frag_size_sub"></a>`skb_frag_size_sub()`

```c
void skb_frag_size_sub(skb_frag_t *frag, int delta)
```

Decrements the size of a skb fragment by **delta**

**Parameters**

- `skb_frag_t *frag`: skb fragment
- `int delta`: value to subtract

#### <a id="c-skb_frag_must_loop"></a>`skb_frag_must_loop()`

```c
bool skb_frag_must_loop(struct page *p)
```

Test if `p` is a high memory page

**Parameters**

- `struct page *p`: fragment's page

#### <a id="c-skb_frag_foreach_page"></a>`skb_frag_foreach_page()`

```c
skb_frag_foreach_page(f, f_off, f_len, p, p_off, p_len, copied)
```

loop over pages in a fragment

**Parameters**

- `f`: skb frag to operate on
- `f_off`: offset from start of f->netmem
- `f_len`: length from f_off to loop over
- `p`: (temp var) current page
- `p_off`: (temp var) offset from start of current page,
  non-zero only on first page.
- `p_len`: (temp var) length in current page,
  \< PAGE_SIZE only on first and last page.
- `copied`: (temp var) length so far, excluding current p_len.

**Description**

A fragment can hold a compound page, in which case per-page
operations, notably kmap_atomic, must be called for each
regular page.

#### <a id="c-struct-skb_shared_hwtstamps"></a>`struct skb_shared_hwtstamps`

hardware time stamps

**Definition**

```c
struct skb_shared_hwtstamps {
    union {
        ktime_t hwtstamp;
        void *netdev_data;
    };
};
```

**Members**

- `{unnamed_union}`: anonymous
- `hwtstamp`: hardware time stamp transformed into duration
  since arbitrary point in time
- `netdev_data`: address/cookie of network device driver used as
  reference to actual hardware time stamp

**Description**

Software time stamps generated by `ktime_get_real()` are stored in
skb->tstamp.

hwtstamps can only be compared against other hwtstamps from
the same device.

This structure is attached to packets as part of the
`skb_shared_info`. Use `skb_hwtstamps()` to get a pointer.

#### <a id="c-struct-sk_buff"></a>`struct sk_buff`

socket buffer

**Definition**

```c
struct sk_buff {
        union {
            struct {
                struct sk_buff          *next;
                struct sk_buff          *prev;
                union {
                    struct net_device       *dev;
                    unsigned long           dev_scratch;
                };
            };
            struct rb_node          rbnode;
            struct list_head        list;
            struct llist_node       ll_node;
        };
        struct sock             *sk;
        union {
            ktime_t tstamp;
            u64 skb_mstamp_ns;
        };
        char cb[48] ;
        union {
            struct {
                unsigned long   _skb_refdst;
                void (*destructor)(struct sk_buff *skb);
            };
            struct list_head        tcp_tsorted_anchor;
    #ifdef CONFIG_NET_SOCK_MSG;
            unsigned long           _sk_redir;
    #endif;
        };
    #if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE);
        unsigned long            _nfct;
    #endif;
        unsigned int            len, data_len;
        __u16 mac_len, hdr_len;
        __u16 queue_mapping;
    #ifdef __BIG_ENDIAN_BITFIELD;
    #define CLONED_MASK     (1 << 7);
    #else;
    #define CLONED_MASK     1;
    #endif;
    #define CLONED_OFFSET           offsetof(struct sk_buff, __cloned_offset);
        __u8 cloned:1, nohdr:1, fclone:2, peeked:1, head_frag:1, pfmemalloc:1, pp_recycle:1;
    #ifdef CONFIG_SKB_EXTENSIONS;
        __u8 active_extensions;
    #endif;
        __u8 pkt_type:3;
        __u8 ignore_df:1;
        __u8 dst_pending_confirm:1;
        __u8 ip_summed:2;
        __u8 ooo_okay:1;
        __u8 tstamp_type:2;
    #ifdef CONFIG_NET_XGRESS;
        __u8 tc_at_ingress:1;
        __u8 tc_skip_classify:1;
    #endif;
        __u8 remcsum_offload:1;
        __u8 csum_complete_sw:1;
        __u8 csum_level:2;
        __u8 inner_protocol_type:1;
        __u8 l4_hash:1;
        __u8 sw_hash:1;
    #ifdef CONFIG_WIRELESS;
        __u8 wifi_acked_valid:1;
        __u8 wifi_acked:1;
    #endif;
        __u8 no_fcs:1;
        __u8 encapsulation:1;
        __u8 encap_hdr_csum:1;
        __u8 csum_valid:1;
    #ifdef CONFIG_IPV6_NDISC_NODETYPE;
        __u8 ndisc_nodetype:2;
    #endif;
    #if IS_ENABLED(CONFIG_IP_VS);
        __u8 ipvs_property:1;
    #endif;
    #if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE) || IS_ENABLED(CONFIG_NF_TABLES);
        __u8 nf_trace:1;
    #endif;
    #ifdef CONFIG_NET_SWITCHDEV;
        __u8 offload_fwd_mark:1;
        __u8 offload_l3_fwd_mark:1;
    #endif;
        __u8 redirected:1;
    #ifdef CONFIG_NET_REDIRECT;
        __u8 from_ingress:1;
    #endif;
    #ifdef CONFIG_NETFILTER_SKIP_EGRESS;
        __u8 nf_skip_egress:1;
    #endif;
    #ifdef CONFIG_SKB_DECRYPTED;
        __u8 decrypted:1;
    #endif;
        __u8 slow_gro:1;
    #if IS_ENABLED(CONFIG_IP_SCTP);
        __u8 csum_not_inet:1;
    #endif;
        __u8 unreadable:1;
    #if IS_ENABLED(CONFIG_PEIOS_NTFE);
        __u8 ntfe_refusal:1;
    #endif;
    #if defined(CONFIG_NET_SCHED) || defined(CONFIG_NET_XGRESS);
        __u16 tc_index;
    #endif;
        u16 alloc_cpu;
        union {
            __wsum csum;
            struct {
                __u16 csum_start;
                __u16 csum_offset;
            };
        };
        __u32 priority;
        int skb_iif;
        __u32 hash;
        union {
            u32 vlan_all;
            struct {
                __be16 vlan_proto;
                __u16 vlan_tci;
            };
        };
    #if defined(CONFIG_NET_RX_BUSY_POLL) || defined(CONFIG_XPS);
        union {
            unsigned int    napi_id;
            unsigned int    sender_cpu;
        };
    #endif;
    #ifdef CONFIG_NETWORK_SECMARK;
        __u32 secmark;
    #endif;
        union {
            __u32 mark;
            __u32 reserved_tailroom;
        };
        union {
            __be16 inner_protocol;
            __u8 inner_ipproto;
        };
        __u16 inner_transport_header;
        __u16 inner_network_header;
        __u16 inner_mac_header;
        __be16 protocol;
        __u16 transport_header;
        __u16 network_header;
        __u16 mac_header;
    #ifdef CONFIG_KCOV;
        u64 kcov_handle;
    #endif;
        sk_buff_data_t tail;
        sk_buff_data_t end;
        unsigned char           *head, *data;
        unsigned int            truesize;
        refcount_t users;
    #ifdef CONFIG_SKB_EXTENSIONS;
        struct skb_ext          *extensions;
    #endif;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `next`: Next buffer in list
- `prev`: Previous buffer in list
- `{unnamed_union}`: anonymous
- `dev`: Device we arrived on/are leaving by
- `dev_scratch`: (aka **dev**) alternate use of **dev** when **dev** would be `NULL`
- `rbnode`: RB tree node, alternative to next/prev for netem/tcp
- `list`: queue head
- `ll_node`: anchor in an llist (eg socket defer_list)
- `sk`: Socket we are owned by
- `{unnamed_union}`: anonymous
- `tstamp`: Time we arrived/left
- `skb_mstamp_ns`: (aka **tstamp**) earliest departure time; start point
  for retransmit timer
- `cb`: Control buffer. Free for use by every layer. Put private vars here
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `_skb_refdst`: destination entry (with norefcount bit)
- `destructor`: Destruct function
- `tcp_tsorted_anchor`: list structure for TCP (tp->tsorted_sent_queue)
- `_sk_redir`: socket redirection information for skmsg
- `_nfct`: Associated connection, if any (with nfctinfo bits)
- `len`: Length of actual data
- `data_len`: Data length
- `mac_len`: Length of link layer header
- `hdr_len`: writable header length of cloned skb
- `queue_mapping`: Queue mapping for multiqueue devices
- `cloned`: Head may be cloned (check refcnt to be sure)
- `nohdr`: Payload reference only, must not modify header
- `fclone`: skbuff clone status
- `peeked`: this packet has been seen already, so stats have been
  done for it, don't do them again
- `head_frag`: skb was allocated from page fragments,
  not allocated by [`kmalloc()`](/kernel/internals/core-api/mm-api.md#c-kmalloc) or [`vmalloc()`](/kernel/internals/core-api/mm-api.md#c-vmalloc).
- `pfmemalloc`: skbuff was allocated from PFMEMALLOC reserves
- `pp_recycle`: mark the packet for recycling instead of freeing (implies
  page_pool support on driver)
- `active_extensions`: active extensions (skb_ext_id types)
- `pkt_type`: Packet class
- `ignore_df`: allow local fragmentation
- `dst_pending_confirm`: need to confirm neighbour
- `ip_summed`: Driver fed us an IP checksum
- `ooo_okay`: allow the mapping of a socket to a queue to be changed
- `tstamp_type`: When set, skb->tstamp has the
  delivery_time clock base of skb->tstamp.
- `tc_at_ingress`: used within tc_classify to distinguish in/egress
- `tc_skip_classify`: do not classify packet. set by IFB device
- `remcsum_offload`: remote checksum offload is enabled
- `csum_complete_sw`: checksum was completed by software
- `csum_level`: indicates the number of consecutive checksums found in
  the packet minus one that have been verified as
  CHECKSUM_UNNECESSARY (max 3)
- `inner_protocol_type`: whether the inner protocol is
  ENCAP_TYPE_ETHER or ENCAP_TYPE_IPPROTO
- `l4_hash`: indicate hash is a canonical 4-tuple hash over transport
  ports.
- `sw_hash`: indicates hash was computed in software stack
- `wifi_acked_valid`: wifi_acked was set
- `wifi_acked`: whether frame was acked on wifi or not
- `no_fcs`: Request NIC to treat last 4 bytes as Ethernet FCS
- `encapsulation`: indicates the inner headers in the skbuff are valid
- `encap_hdr_csum`: software checksum is needed
- `csum_valid`: checksum is already valid
- `ndisc_nodetype`: router type (from link layer)
- `ipvs_property`: skbuff is owned by ipvs
- `nf_trace`: netfilter packet trace flag
- `offload_fwd_mark`: Packet was L2-forwarded in hardware
- `offload_l3_fwd_mark`: Packet was L3-forwarded in hardware
- `redirected`: packet was redirected by packet classifier
- `from_ingress`: packet was redirected from the ingress path
- `nf_skip_egress`: packet shall skip nf egress - see netfilter_netdev.h
- `decrypted`: Decrypted SKB
- `slow_gro`: state present at GRO time, slower prepare step required
- `csum_not_inet`: use CRC32c to resolve CHECKSUM_PARTIAL
- `unreadable`: indicates that at least 1 of the fragments in this skb is
  unreadable.
- `ntfe_refusal`: packet emitted by NTFE as a refusal response
- `tc_index`: Traffic control index
- `alloc_cpu`: CPU which did the skb allocation.
- `{unnamed_union}`: anonymous
- `csum`: Checksum (must include start/offset pair)
- `{unnamed_struct}`: anonymous
- `csum_start`: Offset from skb->head where checksumming should start
- `csum_offset`: Offset from csum_start where checksum should be stored
- `priority`: Packet queueing priority
- `skb_iif`: ifindex of device we arrived on
- `hash`: the packet hash
- `{unnamed_union}`: anonymous
- `vlan_all`: vlan fields (proto & tci)
- `{unnamed_struct}`: anonymous
- `vlan_proto`: vlan encapsulation protocol
- `vlan_tci`: vlan tag control information
- `{unnamed_union}`: anonymous
- `napi_id`: id of the NAPI struct this skb came from
- `sender_cpu`: (aka **napi_id**) source CPU in XPS
- `secmark`: security marking
- `{unnamed_union}`: anonymous
- `mark`: Generic packet mark
- `reserved_tailroom`: (aka **mark**) number of bytes of free space available
  at the tail of an sk_buff
- `{unnamed_union}`: anonymous
- `inner_protocol`: Protocol (encapsulation)
- `inner_ipproto`: (aka **inner_protocol**) stores ipproto when
  skb->inner_protocol_type == ENCAP_TYPE_IPPROTO;
- `inner_transport_header`: Inner transport layer header (encapsulation)
- `inner_network_header`: Network layer header (encapsulation)
- `inner_mac_header`: Link layer header (encapsulation)
- `protocol`: Packet protocol from driver
- `transport_header`: Transport layer header
- `network_header`: Network layer header
- `mac_header`: Link layer header
- `kcov_handle`: KCOV remote handle for remote coverage collection
- `tail`: Tail pointer
- `end`: End pointer
- `head`: Head of buffer
- `data`: Data head pointer
- `truesize`: Buffer size
- `users`: User count - see {datagram,tcp}.c
- `extensions`: allocated extensions, valid if active_extensions is nonzero

#### <a id="c-skb_pfmemalloc"></a>`skb_pfmemalloc()`

```c
bool skb_pfmemalloc(const struct sk_buff *skb)
```

Test if the skb was allocated from PFMEMALLOC reserves

**Parameters**

- `const struct sk_buff *skb`: buffer

#### <a id="c-skb_dst"></a>`skb_dst()`

```c
struct dst_entry * skb_dst(const struct sk_buff *skb)
```

returns skb dst_entry

**Parameters**

- `const struct sk_buff *skb`: buffer

**Return**

skb dst_entry, regardless of reference taken or not.

#### <a id="c-skb_dstref_steal"></a>`skb_dstref_steal()`

```c
unsigned long skb_dstref_steal(struct sk_buff *skb)
```

return current dst_entry value and clear it

**Parameters**

- `struct sk_buff *skb`: buffer

**Description**

Resets skb dst_entry without adjusting its reference count. Useful in
cases where dst_entry needs to be temporarily reset and restored.
Note that the returned value cannot be used directly because it
might contain SKB_DST_NOREF bit.

When in doubt, prefer `skb_dst_drop()` over [`skb_dstref_steal()`](#c-skb_dstref_steal) to correctly
handle dst_entry reference counting.

**Return**

original skb dst_entry.

#### <a id="c-skb_dstref_restore"></a>`skb_dstref_restore()`

```c
void skb_dstref_restore(struct sk_buff *skb, unsigned long refdst)
```

restore skb dst_entry removed via [`skb_dstref_steal()`](#c-skb_dstref_steal)

**Parameters**

- `struct sk_buff *skb`: buffer
- `unsigned long refdst`: dst entry from a call to [`skb_dstref_steal()`](#c-skb_dstref_steal)

#### <a id="c-skb_dst_set"></a>`skb_dst_set()`

```c
void skb_dst_set(struct sk_buff *skb, struct dst_entry *dst)
```

sets skb dst

**Parameters**

- `struct sk_buff *skb`: buffer
- `struct dst_entry *dst`: dst entry

**Description**

Sets skb dst, assuming a reference was taken on dst and should
be released by `skb_dst_drop()`

#### <a id="c-skb_dst_set_noref"></a>`skb_dst_set_noref()`

```c
void skb_dst_set_noref(struct sk_buff *skb, struct dst_entry *dst)
```

sets skb dst, hopefully, without taking reference

**Parameters**

- `struct sk_buff *skb`: buffer
- `struct dst_entry *dst`: dst entry

**Description**

Sets skb dst, assuming a reference was not taken on dst.
If dst entry is cached, we do not take reference and dst_release
will be avoided by refdst_drop. If dst entry is not cached, we take
reference, so that last dst_release can destroy the dst immediately.

#### <a id="c-skb_dst_is_noref"></a>`skb_dst_is_noref()`

```c
bool skb_dst_is_noref(const struct sk_buff *skb)
```

Test if skb dst isn't refcounted

**Parameters**

- `const struct sk_buff *skb`: buffer

#### <a id="c-skb_napi_id"></a>`skb_napi_id()`

```c
unsigned int skb_napi_id(const struct sk_buff *skb)
```

Returns the skb's NAPI id

**Parameters**

- `const struct sk_buff *skb`: buffer

#### <a id="c-skb_unref"></a>`skb_unref()`

```c
bool skb_unref(struct sk_buff *skb)
```

decrement the skb's reference count

**Parameters**

- `struct sk_buff *skb`: buffer

**Return**

true if we can free the skb.

#### <a id="c-kfree_skb"></a>`kfree_skb()`

```c
void kfree_skb(struct sk_buff *skb)
```

free an sk_buff with 'NOT_SPECIFIED' reason

**Parameters**

- `struct sk_buff *skb`: buffer to free

#### <a id="c-alloc_skb"></a>`alloc_skb()`

```c
struct sk_buff * alloc_skb(unsigned int size, gfp_t priority)
```

allocate a network buffer

**Parameters**

- `unsigned int size`: size to allocate
- `gfp_t priority`: allocation mask

**Description**

This function is a convenient wrapper around [`__alloc_skb()`](#c-__alloc_skb).

#### <a id="c-skb_fclone_busy"></a>`skb_fclone_busy()`

```c
bool skb_fclone_busy(const struct sock *sk, const struct sk_buff *skb)
```

check if fclone is busy

**Parameters**

- `const struct sock *sk`: socket
- `const struct sk_buff *skb`: buffer

**Return**

true if skb is a fast clone, and its clone is not freed.
Some drivers call [`skb_orphan()`](#c-skb_orphan) in their `ndo_start_xmit()`,
so we also check that didn't happen.

#### <a id="c-alloc_skb_fclone"></a>`alloc_skb_fclone()`

```c
struct sk_buff * alloc_skb_fclone(unsigned int size, gfp_t priority)
```

allocate a network buffer from fclone cache

**Parameters**

- `unsigned int size`: size to allocate
- `gfp_t priority`: allocation mask

**Description**

This function is a convenient wrapper around [`__alloc_skb()`](#c-__alloc_skb).

#### <a id="c-skb_pad"></a>`skb_pad()`

```c
int skb_pad(struct sk_buff *skb, int pad)
```

zero pad the tail of an skb

**Parameters**

- `struct sk_buff *skb`: buffer to pad
- `int pad`: space to pad

**Description**

Ensure that a buffer is followed by a padding area that is zero
filled. Used by network drivers which may DMA or transfer data
beyond the buffer end onto the wire.

May return error in out of memory cases. The skb is freed on error.

#### <a id="c-skb_queue_empty"></a>`skb_queue_empty()`

```c
int skb_queue_empty(const struct sk_buff_head *list)
```

check if a queue is empty

**Parameters**

- `const struct sk_buff_head *list`: queue head

**Description**

Returns true if the queue is empty, false otherwise.

#### <a id="c-skb_queue_empty_lockless"></a>`skb_queue_empty_lockless()`

```c
bool skb_queue_empty_lockless(const struct sk_buff_head *list)
```

check if a queue is empty

**Parameters**

- `const struct sk_buff_head *list`: queue head

**Description**

Returns true if the queue is empty, false otherwise.
This variant can be used in lockless contexts.

#### <a id="c-skb_queue_is_last"></a>`skb_queue_is_last()`

```c
bool skb_queue_is_last(const struct sk_buff_head *list, const struct sk_buff *skb)
```

check if skb is the last entry in the queue

**Parameters**

- `const struct sk_buff_head *list`: queue head
- `const struct sk_buff *skb`: buffer

**Description**

Returns true if **skb** is the last buffer on the list.

#### <a id="c-skb_queue_is_first"></a>`skb_queue_is_first()`

```c
bool skb_queue_is_first(const struct sk_buff_head *list, const struct sk_buff *skb)
```

check if skb is the first entry in the queue

**Parameters**

- `const struct sk_buff_head *list`: queue head
- `const struct sk_buff *skb`: buffer

**Description**

Returns true if **skb** is the first buffer on the list.

#### <a id="c-skb_queue_next"></a>`skb_queue_next()`

```c
struct sk_buff * skb_queue_next(const struct sk_buff_head *list, const struct sk_buff *skb)
```

return the next packet in the queue

**Parameters**

- `const struct sk_buff_head *list`: queue head
- `const struct sk_buff *skb`: current buffer

**Description**

Return the next packet in **list** after **skb**.  It is only valid to
call this if [`skb_queue_is_last()`](#c-skb_queue_is_last) evaluates to false.

#### <a id="c-skb_queue_prev"></a>`skb_queue_prev()`

```c
struct sk_buff * skb_queue_prev(const struct sk_buff_head *list, const struct sk_buff *skb)
```

return the prev packet in the queue

**Parameters**

- `const struct sk_buff_head *list`: queue head
- `const struct sk_buff *skb`: current buffer

**Description**

Return the prev packet in **list** before **skb**.  It is only valid to
call this if [`skb_queue_is_first()`](#c-skb_queue_is_first) evaluates to false.

#### <a id="c-skb_get"></a>`skb_get()`

```c
struct sk_buff * skb_get(struct sk_buff *skb)
```

reference buffer

**Parameters**

- `struct sk_buff *skb`: buffer to reference

**Description**

Makes another reference to a socket buffer and returns a pointer
to the buffer.

#### <a id="c-skb_cloned"></a>`skb_cloned()`

```c
int skb_cloned(const struct sk_buff *skb)
```

is the buffer a clone

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Returns true if the buffer was generated with [`skb_clone()`](#c-skb_clone) and is
one of multiple shared copies of the buffer. Cloned buffers are
shared data so must not be written to under normal circumstances.

#### <a id="c-skb_header_cloned"></a>`skb_header_cloned()`

```c
int skb_header_cloned(const struct sk_buff *skb)
```

is the header a clone

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Returns true if modifying the header part of the buffer requires
the data to be copied.

#### <a id="c-__skb_header_release"></a>`__skb_header_release()`

```c
void __skb_header_release(struct sk_buff *skb)
```

allow clones to use the headroom

**Parameters**

- `struct sk_buff *skb`: buffer to operate on

**Description**

See "DOC: dataref and headerless skbs".

#### <a id="c-skb_shared"></a>`skb_shared()`

```c
int skb_shared(const struct sk_buff *skb)
```

is the buffer shared

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Returns true if more than one person has a reference to this
buffer.

#### <a id="c-skb_share_check"></a>`skb_share_check()`

```c
struct sk_buff * skb_share_check(struct sk_buff *skb, gfp_t pri)
```

check if buffer is shared and if so clone it

**Parameters**

- `struct sk_buff *skb`: buffer to check
- `gfp_t pri`: priority for memory allocation

**Description**

If the buffer is shared the buffer is cloned and the old copy
drops a reference. A new clone with a single reference is returned.
If the buffer is not shared the original buffer is returned. When
being called from interrupt status or with spinlocks held pri must
be GFP_ATOMIC.

NULL is returned on a memory allocation failure.

#### <a id="c-skb_unshare"></a>`skb_unshare()`

```c
struct sk_buff * skb_unshare(struct sk_buff *skb, gfp_t pri)
```

make a copy of a shared buffer

**Parameters**

- `struct sk_buff *skb`: buffer to check
- `gfp_t pri`: priority for memory allocation

**Description**

If the socket buffer is a clone then this function creates a new
copy of the data, drops a reference count on the old copy and returns
the new copy with the reference count at 1. If the buffer is not a clone
the original buffer is returned. When called with a spinlock held or
from interrupt state **pri** must be `GFP_ATOMIC`

`NULL` is returned on a memory allocation failure.

#### <a id="c-skb_peek"></a>`skb_peek()`

```c
struct sk_buff * skb_peek(const struct sk_buff_head *list_)
```

peek at the head of an `sk_buff_head`

**Parameters**

- `const struct sk_buff_head *list_`: list to peek at

**Description**

Peek an [`sk_buff`](#c-struct-sk_buff). Unlike most other operations you _MUST_
be careful with this one. A peek leaves the buffer on the
list and someone else may run off with it. You must hold
the appropriate locks or have a private queue to do this.

Returns `NULL` for an empty list or a pointer to the head element.
The reference count is not incremented and the reference is therefore
volatile. Use with caution.

#### <a id="c-__skb_peek"></a>`__skb_peek()`

```c
struct sk_buff * __skb_peek(const struct sk_buff_head *list_)
```

peek at the head of a non-empty `sk_buff_head`

**Parameters**

- `const struct sk_buff_head *list_`: list to peek at

**Description**

Like [`skb_peek()`](#c-skb_peek), but the caller knows that the list is not empty.

#### <a id="c-skb_peek_next"></a>`skb_peek_next()`

```c
struct sk_buff * skb_peek_next(struct sk_buff *skb, const struct sk_buff_head *list_)
```

peek skb following the given one from a queue

**Parameters**

- `struct sk_buff *skb`: skb to start from
- `const struct sk_buff_head *list_`: list to peek at

**Description**

Returns `NULL` when the end of the list is met or a pointer to the
next element. The reference count is not incremented and the
reference is therefore volatile. Use with caution.

#### <a id="c-skb_peek_tail"></a>`skb_peek_tail()`

```c
struct sk_buff * skb_peek_tail(const struct sk_buff_head *list_)
```

peek at the tail of an `sk_buff_head`

**Parameters**

- `const struct sk_buff_head *list_`: list to peek at

**Description**

Peek an [`sk_buff`](#c-struct-sk_buff). Unlike most other operations you _MUST_
be careful with this one. A peek leaves the buffer on the
list and someone else may run off with it. You must hold
the appropriate locks or have a private queue to do this.

Returns `NULL` for an empty list or a pointer to the tail element.
The reference count is not incremented and the reference is therefore
volatile. Use with caution.

#### <a id="c-skb_queue_len"></a>`skb_queue_len()`

```c
__u32 skb_queue_len(const struct sk_buff_head *list_)
```

get queue length

**Parameters**

- `const struct sk_buff_head *list_`: list to measure

**Description**

Return the length of an [`sk_buff`](#c-struct-sk_buff) queue.

#### <a id="c-skb_queue_len_lockless"></a>`skb_queue_len_lockless()`

```c
__u32 skb_queue_len_lockless(const struct sk_buff_head *list_)
```

get queue length

**Parameters**

- `const struct sk_buff_head *list_`: list to measure

**Description**

Return the length of an [`sk_buff`](#c-struct-sk_buff) queue.
This variant can be used in lockless contexts.

#### <a id="c-__skb_queue_head_init"></a>`__skb_queue_head_init()`

```c
void __skb_queue_head_init(struct sk_buff_head *list)
```

initialize non-spinlock portions of sk_buff_head

**Parameters**

- `struct sk_buff_head *list`: queue to initialize

**Description**

This initializes only the list and queue length aspects of
an sk_buff_head object.  This allows to initialize the list
aspects of an sk_buff_head without reinitializing things like
the spinlock.  It can also be used for on-stack sk_buff_head
objects where the spinlock is known to not be used.

#### <a id="c-skb_queue_splice"></a>`skb_queue_splice()`

```c
void skb_queue_splice(const struct sk_buff_head *list, struct sk_buff_head *head)
```

join two skb lists, this is designed for stacks

**Parameters**

- `const struct sk_buff_head *list`: the new list to add
- `struct sk_buff_head *head`: the place to add it in the first list

#### <a id="c-skb_queue_splice_init"></a>`skb_queue_splice_init()`

```c
void skb_queue_splice_init(struct sk_buff_head *list, struct sk_buff_head *head)
```

join two skb lists and reinitialise the emptied list

**Parameters**

- `struct sk_buff_head *list`: the new list to add
- `struct sk_buff_head *head`: the place to add it in the first list

**Description**

The list at **list** is reinitialised

#### <a id="c-skb_queue_splice_tail"></a>`skb_queue_splice_tail()`

```c
void skb_queue_splice_tail(const struct sk_buff_head *list, struct sk_buff_head *head)
```

join two skb lists, each list being a queue

**Parameters**

- `const struct sk_buff_head *list`: the new list to add
- `struct sk_buff_head *head`: the place to add it in the first list

#### <a id="c-skb_queue_splice_tail_init"></a>`skb_queue_splice_tail_init()`

```c
void skb_queue_splice_tail_init(struct sk_buff_head *list, struct sk_buff_head *head)
```

join two skb lists and reinitialise the emptied list

**Parameters**

- `struct sk_buff_head *list`: the new list to add
- `struct sk_buff_head *head`: the place to add it in the first list

**Description**

Each of the lists is a queue.
The list at **list** is reinitialised

#### <a id="c-__skb_queue_after"></a>`__skb_queue_after()`

```c
void __skb_queue_after(struct sk_buff_head *list, struct sk_buff *prev, struct sk_buff *newsk)
```

queue a buffer at the list head

**Parameters**

- `struct sk_buff_head *list`: list to use
- `struct sk_buff *prev`: place after this buffer
- `struct sk_buff *newsk`: buffer to queue

**Description**

Queue a buffer int the middle of a list. This function takes no locks
and you must therefore hold required locks before calling it.

A buffer cannot be placed on two lists at the same time.

#### <a id="c-__skb_queue_head"></a>`__skb_queue_head()`

```c
void __skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
```

queue a buffer at the list head

**Parameters**

- `struct sk_buff_head *list`: list to use
- `struct sk_buff *newsk`: buffer to queue

**Description**

Queue a buffer at the start of a list. This function takes no locks
and you must therefore hold required locks before calling it.

A buffer cannot be placed on two lists at the same time.

#### <a id="c-__skb_queue_tail"></a>`__skb_queue_tail()`

```c
void __skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
```

queue a buffer at the list tail

**Parameters**

- `struct sk_buff_head *list`: list to use
- `struct sk_buff *newsk`: buffer to queue

**Description**

Queue a buffer at the end of a list. This function takes no locks
and you must therefore hold required locks before calling it.

A buffer cannot be placed on two lists at the same time.

#### <a id="c-__skb_dequeue"></a>`__skb_dequeue()`

```c
struct sk_buff * __skb_dequeue(struct sk_buff_head *list)
```

remove from the head of the queue

**Parameters**

- `struct sk_buff_head *list`: list to dequeue from

**Description**

Remove the head of the list. This function does not take any locks
so must be used with appropriate locks held only. The head item is
returned or `NULL` if the list is empty.

#### <a id="c-__skb_dequeue_tail"></a>`__skb_dequeue_tail()`

```c
struct sk_buff * __skb_dequeue_tail(struct sk_buff_head *list)
```

remove from the tail of the queue

**Parameters**

- `struct sk_buff_head *list`: list to dequeue from

**Description**

Remove the tail of the list. This function does not take any locks
so must be used with appropriate locks held only. The tail item is
returned or `NULL` if the list is empty.

#### <a id="c-skb_len_add"></a>`skb_len_add()`

```c
void skb_len_add(struct sk_buff *skb, int delta)
```

adds a number to len fields of skb

**Parameters**

- `struct sk_buff *skb`: buffer to add len to
- `int delta`: number of bytes to add

#### <a id="c-__skb_fill_netmem_desc"></a>`__skb_fill_netmem_desc()`

```c
void __skb_fill_netmem_desc(struct sk_buff *skb, int i, netmem_ref netmem, int off, int size)
```

initialise a fragment in an skb

**Parameters**

- `struct sk_buff *skb`: buffer containing fragment to be initialised
- `int i`: fragment index to initialise
- `netmem_ref netmem`: the netmem to use for this fragment
- `int off`: the offset to the data with **page**
- `int size`: the length of the data

**Description**

Initialises the **i**'th fragment of **skb** to point to `size` bytes at
offset **off** within **page**.

Does not take any additional reference on the fragment.

#### <a id="c-skb_fill_page_desc"></a>`skb_fill_page_desc()`

```c
void skb_fill_page_desc(struct sk_buff *skb, int i, struct page *page, int off, int size)
```

initialise a paged fragment in an skb

**Parameters**

- `struct sk_buff *skb`: buffer containing fragment to be initialised
- `int i`: paged fragment index to initialise
- `struct page *page`: the page to use for this fragment
- `int off`: the offset to the data with **page**
- `int size`: the length of the data

**Description**

As per `__skb_fill_page_desc()` -- initialises the **i**'th fragment of
**skb** to point to **size** bytes at offset **off** within **page**. In
addition updates **skb** such that **i** is the last fragment.

Does not take any additional reference on the fragment.

#### <a id="c-skb_fill_page_desc_noacc"></a>`skb_fill_page_desc_noacc()`

```c
void skb_fill_page_desc_noacc(struct sk_buff *skb, int i, struct page *page, int off, int size)
```

initialise a paged fragment in an skb

**Parameters**

- `struct sk_buff *skb`: buffer containing fragment to be initialised
- `int i`: paged fragment index to initialise
- `struct page *page`: the page to use for this fragment
- `int off`: the offset to the data with **page**
- `int size`: the length of the data

**Description**

Variant of [`skb_fill_page_desc()`](#c-skb_fill_page_desc) which does not deal with
pfmemalloc, if page is not owned by us.

#### <a id="c-skb_headroom"></a>`skb_headroom()`

```c
unsigned int skb_headroom(const struct sk_buff *skb)
```

bytes at buffer head

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Return the number of bytes of free space at the head of an [`sk_buff`](#c-struct-sk_buff).

#### <a id="c-skb_tailroom"></a>`skb_tailroom()`

```c
int skb_tailroom(const struct sk_buff *skb)
```

bytes at buffer end

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Return the number of bytes of free space at the tail of an sk_buff

#### <a id="c-skb_availroom"></a>`skb_availroom()`

```c
int skb_availroom(const struct sk_buff *skb)
```

bytes at buffer end

**Parameters**

- `const struct sk_buff *skb`: buffer to check

**Description**

Return the number of bytes of free space at the tail of an sk_buff
allocated by `sk_stream_alloc()`

#### <a id="c-skb_reserve"></a>`skb_reserve()`

```c
void skb_reserve(struct sk_buff *skb, int len)
```

adjust headroom

**Parameters**

- `struct sk_buff *skb`: buffer to alter
- `int len`: bytes to move

**Description**

Increase the headroom of an empty [`sk_buff`](#c-struct-sk_buff) by reducing the tail
room. This is only allowed for an empty buffer.

#### <a id="c-skb_tailroom_reserve"></a>`skb_tailroom_reserve()`

```c
void skb_tailroom_reserve(struct sk_buff *skb, unsigned int mtu, unsigned int needed_tailroom)
```

adjust reserved_tailroom

**Parameters**

- `struct sk_buff *skb`: buffer to alter
- `unsigned int mtu`: maximum amount of headlen permitted
- `unsigned int needed_tailroom`: minimum amount of reserved_tailroom

**Description**

Set reserved_tailroom so that headlen can be as large as possible but
not larger than mtu and tailroom cannot be smaller than
needed_tailroom.
The required headroom should already have been reserved before using
this function.

#### <a id="c-skb_reset_transport_header_careful"></a>`skb_reset_transport_header_careful()`

```c
bool skb_reset_transport_header_careful(struct sk_buff *skb)
```

conditionally reset transport header

**Parameters**

- `struct sk_buff *skb`: buffer to alter

**Description**

Hardened version of `skb_reset_transport_header()`.

**Return**

true if the operation was a success.

#### <a id="c-pskb_trim_unique"></a>`pskb_trim_unique()`

```c
void pskb_trim_unique(struct sk_buff *skb, unsigned int len)
```

remove end from a paged unique (not cloned) buffer

**Parameters**

- `struct sk_buff *skb`: buffer to alter
- `unsigned int len`: new length

**Description**

This is identical to pskb_trim except that the caller knows that
the skb is not cloned so we should never get an error due to out-
of-memory.

#### <a id="c-skb_orphan"></a>`skb_orphan()`

```c
void skb_orphan(struct sk_buff *skb)
```

orphan a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to orphan

**Description**

If a buffer currently has an owner then we call the owner's
destructor function and make the **skb** unowned. The buffer continues
to exist but is no longer charged to its former owner.

#### <a id="c-skb_orphan_frags"></a>`skb_orphan_frags()`

```c
int skb_orphan_frags(struct sk_buff *skb, gfp_t gfp_mask)
```

orphan the frags contained in a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to orphan frags from
- `gfp_t gfp_mask`: allocation mask for replacement pages

**Description**

For each frag in the SKB which needs a destructor (i.e. has an
owner) create a copy of that frag and release the original
page by calling the destructor.

#### <a id="c-__skb_queue_purge_reason"></a>`__skb_queue_purge_reason()`

```c
void __skb_queue_purge_reason(struct sk_buff_head *list, enum skb_drop_reason reason)
```

empty a list

**Parameters**

- `struct sk_buff_head *list`: list to empty
- `enum skb_drop_reason reason`: drop reason

**Description**

Delete all buffers on an [`sk_buff`](#c-struct-sk_buff) list. Each buffer is removed from
the list and one reference dropped. This function does not take the
list lock and the caller must hold the relevant locks to use it.

#### <a id="c-netdev_alloc_frag"></a>`netdev_alloc_frag()`

```c
void * netdev_alloc_frag(unsigned int fragsz)
```

allocate a page fragment

**Parameters**

- `unsigned int fragsz`: fragment size

**Description**

Allocates a frag from a page for receive buffer.
Uses GFP_ATOMIC allocations.

#### <a id="c-netdev_alloc_skb"></a>`netdev_alloc_skb()`

```c
struct sk_buff * netdev_alloc_skb(struct net_device *dev, unsigned int length)
```

allocate an skbuff for rx on a specific device

**Parameters**

- `struct net_device *dev`: network device to receive on
- `unsigned int length`: length to allocate

**Description**

Allocate a new [`sk_buff`](#c-struct-sk_buff) and assign it a usage count of one. The
buffer has unspecified headroom built in. Users should allocate
the headroom they think they need without accounting for the
built in space. The built in space is used for optimisations.

`NULL` is returned if there is no free memory. Although this function
allocates memory it can be called from an interrupt.

#### <a id="c-__dev_alloc_pages"></a>`__dev_alloc_pages()`

```c
struct page * __dev_alloc_pages(gfp_t gfp_mask, unsigned int order)
```

allocate page for network Rx

**Parameters**

- `gfp_t gfp_mask`: allocation priority. Set __GFP_NOMEMALLOC if not for network Rx
- `unsigned int order`: size of the allocation

**Description**

Allocate a new page.

`NULL` is returned if there is no free memory.

#### <a id="c-__dev_alloc_page"></a>`__dev_alloc_page()`

```c
struct page * __dev_alloc_page(gfp_t gfp_mask)
```

allocate a page for network Rx

**Parameters**

- `gfp_t gfp_mask`: allocation priority. Set __GFP_NOMEMALLOC if not for network Rx

**Description**

Allocate a new page.

`NULL` is returned if there is no free memory.

#### <a id="c-dev_page_is_reusable"></a>`dev_page_is_reusable()`

```c
bool dev_page_is_reusable(const struct page *page)
```

check whether a page can be reused for network Rx

**Parameters**

- `const struct page *page`: the page to test

**Description**

A page shouldn't be considered for reusing/recycling if it was allocated
under memory pressure or at a distant memory node.

**Return**

false if this page should be returned to page allocator, true
otherwise.

#### <a id="c-skb_propagate_pfmemalloc"></a>`skb_propagate_pfmemalloc()`

```c
void skb_propagate_pfmemalloc(const struct page *page, struct sk_buff *skb)
```

Propagate pfmemalloc if skb is allocated after RX page

**Parameters**

- `const struct page *page`: The page that was allocated from skb_alloc_page
- `struct sk_buff *skb`: The skb that may need pfmemalloc set

#### <a id="c-skb_frag_off"></a>`skb_frag_off()`

```c
unsigned int skb_frag_off(const skb_frag_t *frag)
```

Returns the offset of a skb fragment

**Parameters**

- `const skb_frag_t *frag`: the paged fragment

#### <a id="c-skb_frag_off_add"></a>`skb_frag_off_add()`

```c
void skb_frag_off_add(skb_frag_t *frag, int delta)
```

Increments the offset of a skb fragment by **delta**

**Parameters**

- `skb_frag_t *frag`: skb fragment
- `int delta`: value to add

#### <a id="c-skb_frag_off_set"></a>`skb_frag_off_set()`

```c
void skb_frag_off_set(skb_frag_t *frag, unsigned int offset)
```

Sets the offset of a skb fragment

**Parameters**

- `skb_frag_t *frag`: skb fragment
- `unsigned int offset`: offset of fragment

#### <a id="c-skb_frag_off_copy"></a>`skb_frag_off_copy()`

```c
void skb_frag_off_copy(skb_frag_t *fragto, const skb_frag_t *fragfrom)
```

Sets the offset of a skb fragment from another fragment

**Parameters**

- `skb_frag_t *fragto`: skb fragment where offset is set
- `const skb_frag_t *fragfrom`: skb fragment offset is copied from

#### <a id="c-skb_frag_net_iov"></a>`skb_frag_net_iov()`

```c
struct net_iov * skb_frag_net_iov(const skb_frag_t *frag)
```

retrieve the net_iov referred to by fragment

**Parameters**

- `const skb_frag_t *frag`: the fragment

**Return**

the `struct net_iov` associated with **frag**. Returns NULL if this
frag has no associated net_iov.

#### <a id="c-skb_frag_page"></a>`skb_frag_page()`

```c
struct page * skb_frag_page(const skb_frag_t *frag)
```

retrieve the page referred to by a paged fragment

**Parameters**

- `const skb_frag_t *frag`: the paged fragment

**Return**

the `struct page` associated with **frag**. Returns NULL if this frag
has no associated page.

#### <a id="c-skb_frag_netmem"></a>`skb_frag_netmem()`

```c
netmem_ref skb_frag_netmem(const skb_frag_t *frag)
```

retrieve the netmem referred to by a fragment

**Parameters**

- `const skb_frag_t *frag`: the fragment

**Return**

the `netmem_ref` associated with **frag**.

#### <a id="c-skb_frag_address"></a>`skb_frag_address()`

```c
void * skb_frag_address(const skb_frag_t *frag)
```

gets the address of the data contained in a paged fragment

**Parameters**

- `const skb_frag_t *frag`: the paged fragment buffer

**Return**

the address of the data within **frag**. The page must already
be mapped.

#### <a id="c-skb_frag_address_safe"></a>`skb_frag_address_safe()`

```c
void * skb_frag_address_safe(const skb_frag_t *frag)
```

gets the address of the data contained in a paged fragment

**Parameters**

- `const skb_frag_t *frag`: the paged fragment buffer

**Return**

the address of the data within **frag**. Checks that the page
is mapped and returns `NULL` otherwise.

#### <a id="c-skb_frag_page_copy"></a>`skb_frag_page_copy()`

```c
void skb_frag_page_copy(skb_frag_t *fragto, const skb_frag_t *fragfrom)
```

sets the page in a fragment from another fragment

**Parameters**

- `skb_frag_t *fragto`: skb fragment where page is set
- `const skb_frag_t *fragfrom`: skb fragment page is copied from

#### <a id="c-__skb_frag_dma_map"></a>`__skb_frag_dma_map()`

```c
dma_addr_t __skb_frag_dma_map(struct device *dev, const skb_frag_t *frag, size_t offset, size_t size, enum dma_data_direction dir)
```

maps a paged fragment via the DMA API

**Parameters**

- `struct device *dev`: the device to map the fragment to
- `const skb_frag_t *frag`: the paged fragment to map
- `size_t offset`: the offset within the fragment (starting at the
  fragment's own offset)
- `size_t size`: the number of bytes to map
- `enum dma_data_direction dir`: the direction of the mapping (`PCI_DMA_*`)

**Description**

Maps the page associated with **frag** to **device**.

#### <a id="c-skb_clone_writable"></a>`skb_clone_writable()`

```c
int skb_clone_writable(const struct sk_buff *skb, unsigned int len)
```

is the header of a clone writable

**Parameters**

- `const struct sk_buff *skb`: buffer to check
- `unsigned int len`: length up to which to write

**Description**

Returns true if modifying the header part of the cloned buffer
does not requires the data to be copied.

#### <a id="c-skb_cow"></a>`skb_cow()`

```c
int skb_cow(struct sk_buff *skb, unsigned int headroom)
```

copy header of skb when it is required

**Parameters**

- `struct sk_buff *skb`: buffer to cow
- `unsigned int headroom`: needed headroom

**Description**

If the skb passed lacks sufficient headroom or its data part
is shared, data is reallocated. If reallocation fails, an error
is returned and original skb is not changed.

The result is skb with writable area skb->head...skb->tail
and at least **headroom** of space at head.

#### <a id="c-skb_cow_head"></a>`skb_cow_head()`

```c
int skb_cow_head(struct sk_buff *skb, unsigned int headroom)
```

skb_cow but only making the head writable

**Parameters**

- `struct sk_buff *skb`: buffer to cow
- `unsigned int headroom`: needed headroom

**Description**

This function is identical to skb_cow except that we replace the
skb_cloned check by skb_header_cloned.  It should be used when
you only need to push on some header and do not need to modify
the data.

#### <a id="c-skb_padto"></a>`skb_padto()`

```c
int skb_padto(struct sk_buff *skb, unsigned int len)
```

pad an skbuff up to a minimal size

**Parameters**

- `struct sk_buff *skb`: buffer to pad
- `unsigned int len`: minimal length

**Description**

Pads up a buffer to ensure the trailing bytes exist and are
blanked. If the buffer already contains sufficient data it
is untouched. Otherwise it is extended. Returns zero on
success. The skb is freed on error.

#### <a id="c-__skb_put_padto"></a>`__skb_put_padto()`

```c
int __skb_put_padto(struct sk_buff *skb, unsigned int len, bool free_on_error)
```

increase size and pad an skbuff up to a minimal size

**Parameters**

- `struct sk_buff *skb`: buffer to pad
- `unsigned int len`: minimal length
- `bool free_on_error`: free buffer on error

**Description**

Pads up a buffer to ensure the trailing bytes exist and are
blanked. If the buffer already contains sufficient data it
is untouched. Otherwise it is extended. Returns zero on
success. The skb is freed on error if **free_on_error** is true.

#### <a id="c-skb_put_padto"></a>`skb_put_padto()`

```c
int skb_put_padto(struct sk_buff *skb, unsigned int len)
```

increase size and pad an skbuff up to a minimal size

**Parameters**

- `struct sk_buff *skb`: buffer to pad
- `unsigned int len`: minimal length

**Description**

Pads up a buffer to ensure the trailing bytes exist and are
blanked. If the buffer already contains sufficient data it
is untouched. Otherwise it is extended. Returns zero on
success. The skb is freed on error.

#### <a id="c-skb_linearize"></a>`skb_linearize()`

```c
int skb_linearize(struct sk_buff *skb)
```

convert paged skb to linear one

**Parameters**

- `struct sk_buff *skb`: buffer to linarize

**Description**

If there is no free memory -ENOMEM is returned, otherwise zero
is returned and the old skb data released.

#### <a id="c-skb_has_shared_frag"></a>`skb_has_shared_frag()`

```c
bool skb_has_shared_frag(const struct sk_buff *skb)
```

can any frag be overwritten

**Parameters**

- `const struct sk_buff *skb`: buffer to test

**Return**

true if the skb has at least one frag that might be modified
by an external entity (as in `vmsplice()`/`sendfile()`)

#### <a id="c-skb_linearize_cow"></a>`skb_linearize_cow()`

```c
int skb_linearize_cow(struct sk_buff *skb)
```

make sure skb is linear and writable

**Parameters**

- `struct sk_buff *skb`: buffer to process

**Description**

If there is no free memory -ENOMEM is returned, otherwise zero
is returned and the old skb data released.

#### <a id="c-skb_postpull_rcsum"></a>`skb_postpull_rcsum()`

```c
void skb_postpull_rcsum(struct sk_buff *skb, const void *start, unsigned int len)
```

update checksum for received skb after pull

**Parameters**

- `struct sk_buff *skb`: buffer to update
- `const void *start`: start of data before pull
- `unsigned int len`: length of data pulled

**Description**

After doing a pull on a received packet, you need to call this to
update the CHECKSUM_COMPLETE checksum, or set ip_summed to
CHECKSUM_NONE so that it can be recomputed from scratch.

#### <a id="c-skb_postpush_rcsum"></a>`skb_postpush_rcsum()`

```c
void skb_postpush_rcsum(struct sk_buff *skb, const void *start, unsigned int len)
```

update checksum for received skb after push

**Parameters**

- `struct sk_buff *skb`: buffer to update
- `const void *start`: start of data after push
- `unsigned int len`: length of data pushed

**Description**

After doing a push on a received packet, you need to call this to
update the CHECKSUM_COMPLETE checksum.

#### <a id="c-skb_push_rcsum"></a>`skb_push_rcsum()`

```c
void * skb_push_rcsum(struct sk_buff *skb, unsigned int len)
```

push skb and update receive checksum

**Parameters**

- `struct sk_buff *skb`: buffer to update
- `unsigned int len`: length of data pulled

**Description**

This function performs an skb_push on the packet and updates
the CHECKSUM_COMPLETE checksum.  It should be used on
receive path processing instead of skb_push unless you know
that the checksum difference is zero (e.g., a valid IP header)
or you are setting ip_summed to CHECKSUM_NONE.

#### <a id="c-pskb_trim_rcsum"></a>`pskb_trim_rcsum()`

```c
int pskb_trim_rcsum(struct sk_buff *skb, unsigned int len)
```

trim received skb and update checksum

**Parameters**

- `struct sk_buff *skb`: buffer to trim
- `unsigned int len`: new length

**Description**

This is exactly the same as pskb_trim except that it ensures the
checksum of received packets are still valid after the operation.
It can change skb pointers.

#### <a id="c-skb_needs_linearize"></a>`skb_needs_linearize()`

```c
bool skb_needs_linearize(struct sk_buff *skb, netdev_features_t features)
```

check if we need to linearize a given skb depending on the given device features.

**Parameters**

- `struct sk_buff *skb`: socket buffer to check
- `netdev_features_t features`: net device features

**Description**

Returns true if either:
1. skb has frag_list and the device doesn't support FRAGLIST, or
2. skb is fragmented and the device does not support SG.

#### <a id="c-skb_get_timestamp"></a>`skb_get_timestamp()`

```c
void skb_get_timestamp(const struct sk_buff *skb, struct __kernel_old_timeval *stamp)
```

get timestamp from a skb

**Parameters**

- `const struct sk_buff *skb`: skb to get stamp from
- `struct __kernel_old_timeval *stamp`: pointer to struct __kernel_old_timeval to store stamp in

**Description**

Timestamps are stored in the skb as offsets to a base timestamp.
This function converts the offset back to a struct timeval and stores
it in stamp.

#### <a id="c-skb_data_move"></a>`skb_data_move()`

```c
void skb_data_move(struct sk_buff *skb, const int len, const unsigned int n)
```

Move packet data and metadata after [`skb_push()`](#c-skb_push) or [`skb_pull()`](#c-skb_pull).

**Parameters**

- `struct sk_buff *skb`: packet to operate on
- `const int len`: number of bytes pushed or pulled from [`sk_buff->data`](#c-struct-sk_buff)
- `const unsigned int n`: number of bytes to [`memmove()`](/kernel/internals/core-api/kernel-api.md#c-memmove) from pre-push/pull [`sk_buff->data`](#c-struct-sk_buff)

**Description**

Moves **n** bytes of packet data, can be zero, and all bytes of skb metadata.

Assumes metadata is located immediately before [`sk_buff->data`](#c-struct-sk_buff) prior to the
push/pull, and that sufficient headroom exists to hold it after an
[`skb_push()`](#c-skb_push). Otherwise, metadata is cleared and a one-time warning is issued.

Prefer [`skb_postpull_data_move()`](#c-skb_postpull_data_move) or [`skb_postpush_data_move()`](#c-skb_postpush_data_move) to calling this
helper directly.

#### <a id="c-skb_postpull_data_move"></a>`skb_postpull_data_move()`

```c
void skb_postpull_data_move(struct sk_buff *skb, const unsigned int len, const unsigned int n)
```

Move packet data and metadata after [`skb_pull()`](#c-skb_pull).

**Parameters**

- `struct sk_buff *skb`: packet to operate on
- `const unsigned int len`: number of bytes pulled from [`sk_buff->data`](#c-struct-sk_buff)
- `const unsigned int n`: number of bytes to [`memmove()`](/kernel/internals/core-api/kernel-api.md#c-memmove) from pre-pull [`sk_buff->data`](#c-struct-sk_buff)

**Description**

See [`skb_data_move()`](#c-skb_data_move) for details.

#### <a id="c-skb_postpush_data_move"></a>`skb_postpush_data_move()`

```c
void skb_postpush_data_move(struct sk_buff *skb, const unsigned int len, const unsigned int n)
```

Move packet data and metadata after [`skb_push()`](#c-skb_push).

**Parameters**

- `struct sk_buff *skb`: packet to operate on
- `const unsigned int len`: number of bytes pushed onto [`sk_buff->data`](#c-struct-sk_buff)
- `const unsigned int n`: number of bytes to [`memmove()`](/kernel/internals/core-api/kernel-api.md#c-memmove) from pre-push [`sk_buff->data`](#c-struct-sk_buff)

**Description**

See [`skb_data_move()`](#c-skb_data_move) for details.

#### <a id="c-skb_complete_tx_timestamp"></a>`skb_complete_tx_timestamp()`

```c
void skb_complete_tx_timestamp(struct sk_buff *skb, struct skb_shared_hwtstamps *hwtstamps)
```

deliver cloned skb with tx timestamps

**Parameters**

- `struct sk_buff *skb`: clone of the original outgoing packet
- `struct skb_shared_hwtstamps *hwtstamps`: hardware time stamps

**Description**

PHY drivers may accept clones of transmitted packets for
timestamping via their phy_driver.txtstamp method. These drivers
must call this function to return the skb back to the stack with a
timestamp.

#### <a id="c-skb_tstamp_tx"></a>`skb_tstamp_tx()`

```c
void skb_tstamp_tx(struct sk_buff *orig_skb, struct skb_shared_hwtstamps *hwtstamps)
```

queue clone of skb with send time stamps

**Parameters**

- `struct sk_buff *orig_skb`: the original outgoing packet
- `struct skb_shared_hwtstamps *hwtstamps`: hardware time stamps, may be NULL if not available

**Description**

If the skb has a socket associated, then this function clones the
skb (thus sharing the actual data and optional structures), stores
the optional hardware time stamping information (if non NULL) or
generates a software time stamp (otherwise), then queues the clone
to the error queue of the socket.  Errors are silently ignored.

#### <a id="c-skb_tx_timestamp"></a>`skb_tx_timestamp()`

```c
void skb_tx_timestamp(struct sk_buff *skb)
```

Driver hook for transmit timestamping

**Parameters**

- `struct sk_buff *skb`: A socket buffer.

**Description**

Ethernet MAC Drivers should call this function in their `hard_xmit()`
function immediately before giving the sk_buff to the MAC hardware.

Specifically, one should make absolutely sure that this function is
called before TX completion of this packet can trigger.  Otherwise
the packet could potentially already be freed.

#### <a id="c-skb_complete_wifi_ack"></a>`skb_complete_wifi_ack()`

```c
void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
```

deliver skb with wifi status

**Parameters**

- `struct sk_buff *skb`: the original outgoing packet
- `bool acked`: ack status

#### <a id="c-skb_checksum_complete"></a>`skb_checksum_complete()`

```c
__sum16 skb_checksum_complete(struct sk_buff *skb)
```

Calculate checksum of an entire packet

**Parameters**

- `struct sk_buff *skb`: packet to process

**Description**

This function calculates the checksum over the entire packet plus
the value of skb->csum.  The latter can be used to supply the
checksum of a pseudo header as used by TCP/UDP.  It returns the
checksum.

For protocols that contain complete checksums such as ICMP/TCP/UDP,
this function can be used to verify that checksum on received
packets.  In that case the function should return zero if the
checksum is correct.  In particular, this function will return zero
if skb->ip_summed is CHECKSUM_UNNECESSARY which indicates that the
hardware has already verified the correctness of the checksum.

#### <a id="c-struct-skb_ext"></a>`struct skb_ext`

sk_buff extensions

**Definition**

```c
struct skb_ext {
    refcount_t refcnt;
    u8 offset[SKB_EXT_NUM];
    u8 chunks;
    char data[] ;
};
```

**Members**

- `refcnt`: 1 on allocation, deallocated on 0
- `offset`: offset to add to **data** to obtain extension address
- `chunks`: size currently allocated, stored in SKB_EXT_ALIGN_SHIFT units
- `data`: start of extension data, variable sized

**Note**

- offsets/lengths are stored in chunks of 8 bytes, this allows

  to use 'u8' types while allowing up to 2kb worth of extension data.

#### <a id="c-skb_checksum_none_assert"></a>`skb_checksum_none_assert()`

```c
void skb_checksum_none_assert(const struct sk_buff *skb)
```

make sure skb ip_summed is CHECKSUM_NONE

**Parameters**

- `const struct sk_buff *skb`: skb to check

**Description**

fresh skbs have their ip_summed set to CHECKSUM_NONE.
Instead of forcing ip_summed to CHECKSUM_NONE, we can
use this helper, to document places where we make this assertion.

#### <a id="c-skb_head_is_locked"></a>`skb_head_is_locked()`

```c
bool skb_head_is_locked(const struct sk_buff *skb)
```

Determine if the skb->head is locked down

**Parameters**

- `const struct sk_buff *skb`: skb to check

**Description**

The head on skbs build around a head frag can be removed if they are
not cloned.  This function returns true if the skb head is locked down
due to either being allocated via kmalloc, or by being a clone with
multiple references to the head.



#### <a id="c-struct-sock_common"></a>`struct sock_common`

minimal network layer representation of sockets

**Definition**

```c
struct sock_common {
        union {
            __addrpair skc_addrpair;
            struct {
                __be32 skc_daddr;
                __be32 skc_rcv_saddr;
            };
        };
        union {
            unsigned int    skc_hash;
            __u16 skc_u16hashes[2];
        };
        union {
            __portpair skc_portpair;
            struct {
                __be16 skc_dport;
                __u16 skc_num;
            };
        };
        unsigned short          skc_family;
        volatile unsigned char  skc_state;
        unsigned char           skc_reuse:4;
        unsigned char           skc_reuseport:1;
        unsigned char           skc_ipv6only:1;
        unsigned char           skc_net_refcnt:1;
        unsigned char           skc_bypass_prot_mem:1;
        int skc_bound_dev_if;
        union {
            struct hlist_node       skc_bind_node;
            struct hlist_node       skc_portaddr_node;
        };
        struct proto            *skc_prot;
        possible_net_t skc_net;
    #if IS_ENABLED(CONFIG_IPV6);
        struct in6_addr         skc_v6_daddr;
        struct in6_addr         skc_v6_rcv_saddr;
    #endif;
        atomic64_t skc_cookie;
        union {
            unsigned long   skc_flags;
            struct sock     *skc_listener;
            struct inet_timewait_death_row *skc_tw_dr;
        };
        union {
            struct hlist_node       skc_node;
            struct hlist_nulls_node skc_nulls_node;
        };
        unsigned short          skc_tx_queue_mapping;
    #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING;
        unsigned short          skc_rx_queue_mapping;
    #endif;
        union {
            int skc_incoming_cpu;
            u32 skc_rcv_wnd;
            u32 skc_tw_rcv_nxt;
        };
        refcount_t skc_refcnt;
};
```

**Members**

- `{unnamed_union}`: anonymous
- `skc_addrpair`: 8-byte-aligned __u64 union of **skc_daddr** & **skc_rcv_saddr**
- `{unnamed_struct}`: anonymous
- `skc_daddr`: Foreign IPv4 addr
- `skc_rcv_saddr`: Bound local IPv4 addr
- `{unnamed_union}`: anonymous
- `skc_hash`: hash value used with various protocol lookup tables
- `skc_u16hashes`: two u16 hash values used by UDP lookup tables
- `{unnamed_union}`: anonymous
- `skc_portpair`: __u32 union of **skc_dport** & **skc_num**
- `{unnamed_struct}`: anonymous
- `skc_dport`: placeholder for inet_dport/tw_dport
- `skc_num`: placeholder for inet_num/tw_num
- `skc_family`: network address family
- `skc_state`: Connection state
- `skc_reuse`: `SO_REUSEADDR` setting
- `skc_reuseport`: `SO_REUSEPORT` setting
- `skc_ipv6only`: socket is IPV6 only
- `skc_net_refcnt`: socket is using net ref counting
- `skc_bypass_prot_mem`: bypass the per-protocol memory accounting for skb
- `skc_bound_dev_if`: bound device index if != 0
- `{unnamed_union}`: anonymous
- `skc_bind_node`: bind hash linkage for various protocol lookup tables
- `skc_portaddr_node`: second hash linkage for UDP/UDP-Lite protocol
- `skc_prot`: protocol handlers inside a network family
- `skc_net`: reference to the network namespace of this socket
- `skc_v6_daddr`: IPV6 destination address
- `skc_v6_rcv_saddr`: IPV6 source address
- `skc_cookie`: socket's cookie value
- `{unnamed_union}`: anonymous
- `skc_flags`: place holder for sk_flags
  `SO_LINGER` (l_onoff), `SO_BROADCAST`, `SO_KEEPALIVE`,
  `SO_OOBINLINE` settings, `SO_TIMESTAMPING` settings
- `skc_listener`: connection request listener socket (aka rsk_listener)
  \[union with **skc_flags**\]
- `skc_tw_dr`: (aka tw_dr) ptr to `struct inet_timewait_death_row`
  \[union with **skc_flags**\]
- `{unnamed_union}`: anonymous
- `skc_node`: main hash linkage for various protocol lookup tables
- `skc_nulls_node`: main hash linkage for TCP/UDP/UDP-Lite protocol
- `skc_tx_queue_mapping`: tx queue number for this connection
- `skc_rx_queue_mapping`: rx queue number for this connection
- `{unnamed_union}`: anonymous
- `skc_incoming_cpu`: record/match cpu processing incoming packets
- `skc_rcv_wnd`: (aka rsk_rcv_wnd) TCP receive window size (possibly scaled)
  \[union with **skc_incoming_cpu**\]
- `skc_tw_rcv_nxt`: (aka tw_rcv_nxt) TCP window next expected seq number
  \[union with **skc_incoming_cpu**\]
- `skc_refcnt`: reference count

**Description**

This is the minimal network layer representation of sockets, the header
for struct sock and struct inet_timewait_sock.

#### <a id="c-struct-sock"></a>`struct sock`

network layer representation of sockets

**Definition**

```c
struct sock {
        struct sock_common      __sk_common;
    #define sk_node                 __sk_common.skc_node;
    #define sk_nulls_node           __sk_common.skc_nulls_node;
    #define sk_refcnt               __sk_common.skc_refcnt;
    #define sk_tx_queue_mapping     __sk_common.skc_tx_queue_mapping;
    #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING;
    #define sk_rx_queue_mapping     __sk_common.skc_rx_queue_mapping;
    #endif;
    #define sk_dontcopy_begin       __sk_common.skc_dontcopy_begin;
    #define sk_dontcopy_end         __sk_common.skc_dontcopy_end;
    #define sk_hash                 __sk_common.skc_hash;
    #define sk_portpair             __sk_common.skc_portpair;
    #define sk_num                  __sk_common.skc_num;
    #define sk_dport                __sk_common.skc_dport;
    #define sk_addrpair             __sk_common.skc_addrpair;
    #define sk_daddr                __sk_common.skc_daddr;
    #define sk_rcv_saddr            __sk_common.skc_rcv_saddr;
    #define sk_family               __sk_common.skc_family;
    #define sk_state                __sk_common.skc_state;
    #define sk_reuse                __sk_common.skc_reuse;
    #define sk_reuseport            __sk_common.skc_reuseport;
    #define sk_ipv6only             __sk_common.skc_ipv6only;
    #define sk_net_refcnt           __sk_common.skc_net_refcnt;
    #define sk_bypass_prot_mem      __sk_common.skc_bypass_prot_mem;
    #define sk_bound_dev_if         __sk_common.skc_bound_dev_if;
    #define sk_bind_node            __sk_common.skc_bind_node;
    #define sk_prot                 __sk_common.skc_prot;
    #define sk_net                  __sk_common.skc_net;
    #define sk_v6_daddr             __sk_common.skc_v6_daddr;
    #define sk_v6_rcv_saddr __sk_common.skc_v6_rcv_saddr;
    #define sk_cookie               __sk_common.skc_cookie;
    #define sk_incoming_cpu         __sk_common.skc_incoming_cpu;
    #define sk_flags                __sk_common.skc_flags;
    #define sk_rxhash               __sk_common.skc_rxhash;
        atomic_t sk_drops;
        __s32 sk_peek_off;
        struct sk_buff_head     sk_error_queue;
        struct sk_buff_head     sk_receive_queue;
        struct {
            atomic_t rmem_alloc;
            int len;
            struct sk_buff  *head;
            struct sk_buff  *tail;
        } sk_backlog;
    #define sk_rmem_alloc sk_backlog.rmem_alloc;
        struct dst_entry   *sk_rx_dst;
        int sk_rx_dst_ifindex;
        u32 sk_rx_dst_cookie;
    #ifdef CONFIG_NET_RX_BUSY_POLL;
        unsigned int            sk_ll_usec;
        unsigned int            sk_napi_id;
        u16 sk_busy_poll_budget;
        u8 sk_prefer_busy_poll;
    #endif;
        u8 sk_userlocks;
        int sk_rcvbuf;
        struct sk_filter   *sk_filter;
        union {
            struct socket_wq   *sk_wq;
        };
        void (*sk_data_ready)(struct sock *sk);
        long sk_rcvtimeo;
        int sk_rcvlowat;
        int sk_err;
        struct socket           *sk_socket;
    #ifdef CONFIG_MEMCG;
        struct mem_cgroup       *sk_memcg;
    #endif;
    #ifdef CONFIG_XFRM;
        struct xfrm_policy  *sk_policy[2];
    #endif;
    #if IS_ENABLED(CONFIG_INET_PSP);
        struct psp_assoc   *psp_assoc;
    #endif;
        socket_lock_t sk_lock;
        u32 sk_reserved_mem;
        int sk_forward_alloc;
        u32 sk_tsflags;
        int sk_write_pending;
        atomic_t sk_omem_alloc;
        int sk_err_soft;
        int sk_wmem_queued;
        refcount_t sk_wmem_alloc;
        unsigned long           sk_tsq_flags;
        union {
            struct sk_buff  *sk_send_head;
            struct rb_root  tcp_rtx_queue;
        };
        struct sk_buff_head     sk_write_queue;
        struct page_frag        sk_frag;
        union {
            struct timer_list       sk_timer;
            struct timer_list       tcp_retransmit_timer;
            struct timer_list       mptcp_retransmit_timer;
        };
        unsigned long           sk_pacing_rate;
        atomic_t sk_zckey;
        atomic_t sk_tskey;
        unsigned long           sk_tx_queue_mapping_jiffies;
        u32 sk_dst_pending_confirm;
        u32 sk_pacing_status;
        unsigned long           sk_max_pacing_rate;
        long sk_sndtimeo;
        u32 sk_priority;
        u32 sk_mark;
        kuid_t sk_uid;
        u16 sk_protocol;
        u16 sk_type;
        struct dst_entry   *sk_dst_cache;
        netdev_features_t sk_route_caps;
    #ifdef CONFIG_SOCK_VALIDATE_XMIT;
        struct sk_buff*         (*sk_validate_xmit_skb)(struct sock *sk, struct net_device *dev, struct sk_buff *skb);
    #endif;
        u16 sk_gso_type;
        u16 sk_gso_max_segs;
        unsigned int            sk_gso_max_size;
        gfp_t sk_allocation;
        u32 sk_txhash;
        int sk_sndbuf;
        u8 sk_pacing_shift;
        bool sk_use_task_frag;
        u8 sk_gso_disabled : 1, sk_kern_sock : 1, sk_no_check_tx : 1, sk_no_check_rx : 1;
        u8 sk_shutdown;
        unsigned long           sk_lingertime;
        struct proto            *sk_prot_creator;
        rwlock_t sk_callback_lock;
        u32 sk_ack_backlog;
        u32 sk_max_ack_backlog;
        unsigned long           sk_ino;
        spinlock_t sk_peer_lock;
        int sk_bind_phc;
        struct pid              *sk_peer_pid;
        const struct cred       *sk_peer_cred;
        ktime_t sk_stamp;
    #if BITS_PER_LONG==32;
        seqlock_t sk_stamp_seq;
    #endif;
        int sk_disconnects;
        union {
            u8 sk_txrehash;
            u8 sk_scm_recv_flags;
            struct {
                u8 sk_scm_credentials : 1, sk_scm_security : 1, sk_scm_pidfd : 1, sk_scm_rights : 1, sk_scm_unused : 4;
            };
        };
        u8 sk_clockid;
        u8 sk_txtime_deadline_mode : 1, sk_txtime_report_errors : 1, sk_txtime_unused : 6;
    #define SK_BPF_CB_FLAG_TEST(SK, FLAG) ((SK)->sk_bpf_cb_flags & (FLAG));
        u8 sk_bpf_cb_flags;
        void *sk_user_data;
    #ifdef CONFIG_SECURITY;
        void *sk_security;
    #endif;
        struct sock_cgroup_data sk_cgrp_data;
        void (*sk_state_change)(struct sock *sk);
        void (*sk_write_space)(struct sock *sk);
        void (*sk_error_report)(struct sock *sk);
        int (*sk_backlog_rcv)(struct sock *sk, struct sk_buff *skb);
        void (*sk_destruct)(struct sock *sk);
        struct sock_reuseport      *sk_reuseport_cb;
    #ifdef CONFIG_BPF_SYSCALL;
        struct bpf_local_storage   *sk_bpf_storage;
    #endif;
        struct numa_drop_counters *sk_drop_counters;
        union {
            struct rcu_head sk_rcu;
            freeptr_t sk_freeptr;
        };
        netns_tracker ns_tracker;
        struct xarray           sk_user_frags;
    #if IS_ENABLED(CONFIG_PROVE_LOCKING) && IS_ENABLED(CONFIG_MODULES);
        struct module           *sk_owner;
    #endif;
};
```

**Members**

- `__sk_common`: shared layout with inet_timewait_sock
- `sk_drops`: raw/udp drops counter
- `sk_peek_off`: current peek_offset value
- `sk_error_queue`: rarely used
- `sk_receive_queue`: incoming packets
- `sk_backlog`: always used with the per-socket spinlock held
- `sk_rx_dst`: receive input route used by early demux
- `sk_rx_dst_ifindex`: ifindex for **sk_rx_dst**
- `sk_rx_dst_cookie`: cookie for **sk_rx_dst**
- `sk_ll_usec`: usecs to busypoll when there is no data
- `sk_napi_id`: id of the last napi context to receive data for sk
- `sk_busy_poll_budget`: napi processing budget when busypolling
- `sk_prefer_busy_poll`: prefer busypolling over softirq processing
- `sk_userlocks`: `SO_SNDBUF` and `SO_RCVBUF` settings
- `sk_rcvbuf`: size of receive buffer in bytes
- `sk_filter`: socket filtering instructions
- `{unnamed_union}`: anonymous
- `sk_wq`: sock wait queue and async head
- `sk_data_ready`: callback to indicate there is data to be processed
- `sk_rcvtimeo`: `SO_RCVTIMEO` setting
- `sk_rcvlowat`: `SO_RCVLOWAT` setting
- `sk_err`: last error
- `sk_socket`: Identd and reporting IO signals
- `sk_memcg`: this socket's memory cgroup association
- `sk_policy`: flow policy
- `psp_assoc`: PSP association, if socket is PSP-secured
- `sk_lock`: synchronizer
- `sk_reserved_mem`: space reserved and non-reclaimable for the socket
- `sk_forward_alloc`: space allocated forward
- `sk_tsflags`: SO_TIMESTAMPING flags
- `sk_write_pending`: a write to stream socket waits to start
- `sk_omem_alloc`: "o" is "option" or "other"
- `sk_err_soft`: errors that don't cause failure but are the cause of a
  persistent failure not just 'timed out'
- `sk_wmem_queued`: persistent queue size
- `sk_wmem_alloc`: transmit queue bytes committed
- `sk_tsq_flags`: TCP Small Queues flags
- `{unnamed_union}`: anonymous
- `sk_send_head`: front of stuff to transmit
- `tcp_rtx_queue`: TCP re-transmit queue \[union with **sk_send_head**\]
- `sk_write_queue`: Packet sending queue
- `sk_frag`: cached page frag
- `{unnamed_union}`: anonymous
- `sk_timer`: sock cleanup timer
- `tcp_retransmit_timer`: tcp retransmit timer
- `mptcp_retransmit_timer`: mptcp retransmit timer
- `sk_pacing_rate`: Pacing rate (if supported by transport/packet scheduler)
- `sk_zckey`: counter to order MSG_ZEROCOPY notifications
- `sk_tskey`: counter to disambiguate concurrent tstamp requests
- `sk_tx_queue_mapping_jiffies`: time in jiffies of last **sk_tx_queue_mapping** refresh.
- `sk_dst_pending_confirm`: need to confirm neighbour
- `sk_pacing_status`: Pacing status (requested, handled by sch_fq)
- `sk_max_pacing_rate`: Maximum pacing rate (`SO_MAX_PACING_RATE`)
- `sk_sndtimeo`: `SO_SNDTIMEO` setting
- `sk_priority`: `SO_PRIORITY` setting
- `sk_mark`: generic packet mark
- `sk_uid`: user id of owner
- `sk_protocol`: which protocol this socket belongs in this network family
- `sk_type`: socket type (`SOCK_STREAM`, etc)
- `sk_dst_cache`: destination cache
- `sk_route_caps`: route capabilities (e.g. `NETIF_F_TSO`)
- `sk_validate_xmit_skb`: ptr to an optional validate function
- `sk_gso_type`: GSO type (e.g. `SKB_GSO_TCPV4`)
- `sk_gso_max_segs`: Maximum number of GSO segments
- `sk_gso_max_size`: Maximum GSO segment size to build
- `sk_allocation`: allocation mode
- `sk_txhash`: computed flow hash for use on transmit
- `sk_sndbuf`: size of send buffer in bytes
- `sk_pacing_shift`: scaling factor for TCP Small Queues
- `sk_use_task_frag`: allow [`sk_page_frag()`](#c-sk_page_frag) to use current->task_frag.
  Sockets that can be used under memory reclaim should
  set this to false.
- `sk_gso_disabled`: if set, NETIF_F_GSO_MASK is forbidden.
- `sk_kern_sock`: True if sock is using kernel lock classes
- `sk_no_check_tx`: `SO_NO_CHECK` setting, set checksum in TX packets
- `sk_no_check_rx`: allow zero checksum in RX packets
- `sk_shutdown`: mask of `SEND_SHUTDOWN` and/or `RCV_SHUTDOWN`
- `sk_lingertime`: `SO_LINGER` l_linger setting
- `sk_prot_creator`: sk_prot of original sock creator (see ipv6_setsockopt,
  IPV6_ADDRFORM for instance)
- `sk_callback_lock`: used with the callbacks in the end of this struct
- `sk_ack_backlog`: current listen backlog
- `sk_max_ack_backlog`: listen backlog set in `listen()`
- `sk_ino`: inode number (zero if orphaned)
- `sk_peer_lock`: lock protecting **sk_peer_pid** and **sk_peer_cred**
- `sk_bind_phc`: SO_TIMESTAMPING bind PHC index of PTP virtual clock
  for timestamping
- `sk_peer_pid`: `struct pid` for this socket's peer
- `sk_peer_cred`: `SO_PEERCRED` setting
- `sk_stamp`: time stamp of last packet received
- `sk_stamp_seq`: lock for accessing sk_stamp on 32 bit architectures only
- `sk_disconnects`: number of disconnect operations performed on this sock
- `{unnamed_union}`: anonymous
- `sk_txrehash`: enable TX hash rethink
- `sk_scm_recv_flags`: all flags used by `scm_recv()`
- `{unnamed_struct}`: anonymous
- `sk_scm_credentials`: flagged by SO_PASSCRED to recv SCM_CREDENTIALS
- `sk_scm_security`: flagged by SO_PASSSEC to recv SCM_SECURITY
- `sk_scm_pidfd`: flagged by SO_PASSPIDFD to recv SCM_PIDFD
- `sk_scm_rights`: flagged by SO_PASSRIGHTS to recv SCM_RIGHTS
- `sk_scm_unused`: unused flags for `scm_recv()`
- `sk_clockid`: clockid used by time-based scheduling (SO_TXTIME)
- `sk_txtime_deadline_mode`: set deadline mode for SO_TXTIME
- `sk_txtime_report_errors`: set report errors mode for SO_TXTIME
- `sk_txtime_unused`: unused txtime flags
- `sk_bpf_cb_flags`: used in `bpf_setsockopt()`
- `sk_user_data`: RPC layer private data. Write-protected by **sk_callback_lock**.
- `sk_security`: used by security modules
- `sk_cgrp_data`: cgroup data for this cgroup
- `sk_state_change`: callback to indicate change in the state of the sock
- `sk_write_space`: callback to indicate there is bf sending space available
- `sk_error_report`: callback to indicate errors (e.g. `MSG_ERRQUEUE`)
- `sk_backlog_rcv`: callback to process the backlog
- `sk_destruct`: called at sock freeing time, i.e. when all refcnt == 0
- `sk_reuseport_cb`: reuseport group container
- `sk_bpf_storage`: ptr to cache and control for bpf_sk_storage
- `sk_drop_counters`: optional pointer to numa_drop_counters
- `{unnamed_union}`: anonymous
- `sk_rcu`: used during RCU grace period
- `sk_freeptr`: used for SLAB_TYPESAFE_BY_RCU managed sockets
- `ns_tracker`: tracker for netns reference
- `sk_user_frags`: xarray of pages the user is holding a reference on.
- `sk_owner`: reference to the real owner of the socket that calls
  `sock_lock_init_class_and_name()`.

#### <a id="c-sk_user_data_is_nocopy"></a>`sk_user_data_is_nocopy()`

```c
bool sk_user_data_is_nocopy(const struct sock *sk)
```

Test if sk_user_data pointer must not be copied

**Parameters**

- `const struct sock *sk`: socket

#### <a id="c-__locked_read_sk_user_data_with_flags"></a>`__locked_read_sk_user_data_with_flags()`

```c
void * __locked_read_sk_user_data_with_flags(const struct sock *sk, uintptr_t flags)
```

return the pointer only if argument flags all has been set in sk_user_data. Otherwise return NULL

**Parameters**

- `const struct sock *sk`: socket
- `uintptr_t flags`: flag bits

**Description**

The caller must be holding sk->sk_callback_lock.

#### <a id="c-__rcu_dereference_sk_user_data_with_flags"></a>`__rcu_dereference_sk_user_data_with_flags()`

```c
void * __rcu_dereference_sk_user_data_with_flags(const struct sock *sk, uintptr_t flags)
```

return the pointer only if argument flags all has been set in sk_user_data. Otherwise return NULL

**Parameters**

- `const struct sock *sk`: socket
- `uintptr_t flags`: flag bits

#### <a id="c-sk_for_each_entry_offset_rcu"></a>`sk_for_each_entry_offset_rcu()`

```c
sk_for_each_entry_offset_rcu(tpos, pos, head, offset)
```

iterate over a list at a given struct offset

**Parameters**

- `tpos`: the type * to use as a loop cursor.
- `pos`: the `struct hlist_node` to use as a loop cursor.
- `head`: the head for your list.
- `offset`: offset of hlist_node within the struct.

#### <a id="c-SOCK_CONNECT_BIND"></a>`SOCK_CONNECT_BIND`

```c
SOCK_CONNECT_BIND
```

[`sock->sk_userlocks`](#c-struct-sock) flag for auto-bind at `connect()` time

#### <a id="c-lock_sock_fast"></a>`lock_sock_fast()`

```c
bool lock_sock_fast(struct sock *sk)
```

fast version of lock_sock

**Parameters**

- `struct sock *sk`: socket

**Description**

This version should be used for very small section, where process won't block
return false if fast path is taken:

sk_lock.slock locked, owned = 0, BH disabled

return true if slow path is taken:

sk_lock.slock unlocked, owned = 1, BH enabled

#### <a id="c-unlock_sock_fast"></a>`unlock_sock_fast()`

```c
void unlock_sock_fast(struct sock *sk, bool slow)
```

complement of lock_sock_fast

**Parameters**

- `struct sock *sk`: socket
- `bool slow`: slow mode

**Description**

fast unlock socket for user context.
If slow mode is on, we call regular `release_sock()`

#### <a id="c-sk_wmem_alloc_get"></a>`sk_wmem_alloc_get()`

```c
int sk_wmem_alloc_get(const struct sock *sk)
```

returns write allocations

**Parameters**

- `const struct sock *sk`: socket

**Return**

sk_wmem_alloc minus initial offset of one

#### <a id="c-sk_rmem_alloc_get"></a>`sk_rmem_alloc_get()`

```c
int sk_rmem_alloc_get(const struct sock *sk)
```

returns read allocations

**Parameters**

- `const struct sock *sk`: socket

**Return**

sk_rmem_alloc

#### <a id="c-sk_has_allocations"></a>`sk_has_allocations()`

```c
bool sk_has_allocations(const struct sock *sk)
```

check if allocations are outstanding

**Parameters**

- `const struct sock *sk`: socket

**Return**

true if socket has write or read allocations

#### <a id="c-skwq_has_sleeper"></a>`skwq_has_sleeper()`

```c
bool skwq_has_sleeper(struct socket_wq *wq)
```

check if there are any waiting processes

**Parameters**

- `struct socket_wq *wq`: struct socket_wq

**Return**

true if socket_wq has waiting processes

**Description**

The purpose of the skwq_has_sleeper and sock_poll_wait is to wrap the memory
barrier call. They were added due to the race found within the tcp code.

Consider following tcp code paths:

```text
CPU1                CPU2
sys_select          receive packet
...                 ...
__add_wait_queue    update tp->rcv_nxt
...                 ...
tp->rcv_nxt check   sock_def_readable
...                 {
schedule               rcu_read_lock();
                       wq = rcu_dereference(sk->sk_wq);
                       if (wq && waitqueue_active(&wq->wait))
                           wake_up_interruptible(&wq->wait)
                       ...
                    }
```

The race for tcp fires when the __add_wait_queue changes done by CPU1 stay
in its cache, and so does the tp->rcv_nxt update on CPU2 side.  The CPU1
could then endup calling schedule and sleep forever if there are no more
data on the socket.

#### <a id="c-sock_poll_wait"></a>`sock_poll_wait()`

```c
void sock_poll_wait(struct file *filp, struct socket *sock, poll_table *p)
```

wrapper for the poll_wait call.

**Parameters**

- `struct file *filp`: file
- `struct socket *sock`: socket to wait on
- `poll_table *p`: poll_table

**Description**

See the comments in the wq_has_sleeper function.

#### <a id="c-sk_page_frag"></a>`sk_page_frag()`

```c
struct page_frag * sk_page_frag(struct sock *sk)
```

return an appropriate page_frag

**Parameters**

- `struct sock *sk`: socket

**Description**

Use the per task page_frag instead of the per socket one for
optimization when we know that we're in process context and own
everything that's associated with `current`.

Both direct reclaim and page faults can nest inside other
socket operations and end up recursing into [`sk_page_frag()`](#c-sk_page_frag)
while it's already in use: explicitly avoid task page_frag
when users disable sk_use_task_frag.

**Return**

a per task page_frag if context allows that,
otherwise a per socket one.

#### <a id="c-_sock_tx_timestamp"></a>`_sock_tx_timestamp()`

```c
void _sock_tx_timestamp(struct sock *sk, const struct sockcm_cookie *sockc, __u8 *tx_flags, __u32 *tskey)
```

checks whether the outgoing packet is to be time stamped

**Parameters**

- `struct sock *sk`: socket sending this packet
- `const struct sockcm_cookie *sockc`: pointer to socket cmsg cookie to get timestamping info
- `__u8 *tx_flags`: completed with instructions for time stamping
- `__u32 *tskey`: filled in with next sk_tskey (not for TCP, which uses seqno)

**Note**

callers should take care of initial `*tx_flags` value (usually 0)

#### <a id="c-sk_eat_skb"></a>`sk_eat_skb()`

```c
void sk_eat_skb(struct sock *sk, struct sk_buff *skb)
```

Release a skb if it is no longer needed

**Parameters**

- `struct sock *sk`: socket to eat this skb from
- `struct sk_buff *skb`: socket buffer to eat

**Description**

This routine must be called with interrupts disabled or with the socket
locked so that the sk_buff queue operation is ok.



#### <a id="c-sock_alloc_file"></a>`sock_alloc_file()`

```c
struct file * sock_alloc_file(struct socket *sock, int flags, const char *dname)
```

Bind a [`socket`](#c-struct-socket) to a [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file)

**Parameters**

- `struct socket *sock`: socket
- `int flags`: file status flags
- `const char *dname`: protocol name

**Description**

Returns the [`file`](/kernel/internals/filesystems/api-summary.md#c-struct-file) bound with **sock**, implicitly storing it
in sock->file. If dname is `NULL`, sets to "".

On failure **sock** is released, and an ERR pointer is returned.

This function uses GFP_KERNEL internally.

#### <a id="c-sock_from_file"></a>`sock_from_file()`

```c
struct socket * sock_from_file(struct file *file)
```

Return the [`socket`](#c-struct-socket) bounded to **file**.

**Parameters**

- `struct file *file`: file

**Description**

On failure returns `NULL`.

#### <a id="c-sockfd_lookup"></a>`sockfd_lookup()`

```c
struct socket * sockfd_lookup(int fd, int *err)
```

Go from a file number to its socket slot

**Parameters**

- `int fd`: file handle
- `int *err`: pointer to an error code return

**Description**

The file handle passed in is locked and the socket it is bound
to is returned. If an error occurs the err pointer is overwritten
with a negative errno code and NULL is returned. The function checks
for both invalid handles and passing a handle which is not a socket.

On a success the socket object pointer is returned.

#### <a id="c-sock_alloc"></a>`sock_alloc()`

```c
struct socket * sock_alloc(void)
```

allocate a socket

**Parameters**

- `void`: no arguments

**Description**

Allocate a new inode and socket object. The two are bound together
and initialised. The socket is then returned. If we are out of inodes
NULL is returned. This functions uses GFP_KERNEL internally.

#### <a id="c-sock_release"></a>`sock_release()`

```c
void sock_release(struct socket *sock)
```

close a socket

**Parameters**

- `struct socket *sock`: socket to close

**Description**

The socket is released from the protocol stack if it has a release
callback, and the inode is then released if the socket is bound to
an inode not a file.

#### <a id="c-sock_sendmsg"></a>`sock_sendmsg()`

```c
int sock_sendmsg(struct socket *sock, struct msghdr *msg)
```

send a message through **sock**

**Parameters**

- `struct socket *sock`: socket
- `struct msghdr *msg`: message to send

**Description**

Sends **msg** through **sock**, passing through LSM.
Returns the number of bytes sent, or an error code.

#### <a id="c-kernel_sendmsg"></a>`kernel_sendmsg()`

```c
int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size)
```

send a message through **sock** (kernel-space)

**Parameters**

- `struct socket *sock`: socket
- `struct msghdr *msg`: message header
- `struct kvec *vec`: kernel vec
- `size_t num`: vec array length
- `size_t size`: total message data size

**Description**

Builds the message data with **vec** and sends it through **sock**.
Returns the number of bytes sent, or an error code.

#### <a id="c-sock_recvmsg"></a>`sock_recvmsg()`

```c
int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags)
```

receive a message from **sock**

**Parameters**

- `struct socket *sock`: socket
- `struct msghdr *msg`: message to receive
- `int flags`: message flags

**Description**

Receives **msg** from **sock**, passing through LSM. Returns the total number
of bytes received, or an error.

#### <a id="c-kernel_recvmsg"></a>`kernel_recvmsg()`

```c
int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags)
```

Receive a message from a socket (kernel space)

**Parameters**

- `struct socket *sock`: The socket to receive the message from
- `struct msghdr *msg`: Received message
- `struct kvec *vec`: Input s/g array for message data
- `size_t num`: Size of input s/g array
- `size_t size`: Number of bytes to read
- `int flags`: Message flags (MSG_DONTWAIT, etc...)

**Description**

On return the msg structure contains the scatter/gather array passed in the
vec argument. The array is modified so that it consists of the unfilled
portion of the original array.

The returned value is the total number of bytes received, or an error.

#### <a id="c-sock_create_lite"></a>`sock_create_lite()`

```c
int sock_create_lite(int family, int type, int protocol, struct socket **res)
```

creates a socket

**Parameters**

- `int family`: protocol family (AF_INET, ...)
- `int type`: communication type (SOCK_STREAM, ...)
- `int protocol`: protocol (0, ...)
- `struct socket **res`: new socket

**Description**

Creates a new socket and assigns it to **res**, passing through LSM.
The new socket initialization is not complete, see [`kernel_accept()`](#c-kernel_accept).
Returns 0 or an error. On failure **res** is set to `NULL`.
This function internally uses GFP_KERNEL.

#### <a id="c-__sock_create"></a>`__sock_create()`

```c
int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern)
```

creates a socket

**Parameters**

- `struct net *net`: net namespace
- `int family`: protocol family (AF_INET, ...)
- `int type`: communication type (SOCK_STREAM, ...)
- `int protocol`: protocol (0, ...)
- `struct socket **res`: new socket
- `int kern`: boolean for kernel space sockets

**Description**

Creates a new socket and assigns it to **res**, passing through LSM.
Returns 0 or an error. On failure **res** is set to `NULL`. **kern** must
be set to true if the socket resides in kernel space.
This function internally uses GFP_KERNEL.

#### <a id="c-sock_create"></a>`sock_create()`

```c
int sock_create(int family, int type, int protocol, struct socket **res)
```

creates a socket

**Parameters**

- `int family`: protocol family (AF_INET, ...)
- `int type`: communication type (SOCK_STREAM, ...)
- `int protocol`: protocol (0, ...)
- `struct socket **res`: new socket

**Description**

A wrapper around [`__sock_create()`](#c-__sock_create).
Returns 0 or an error. This function internally uses GFP_KERNEL.

#### <a id="c-sock_create_kern"></a>`sock_create_kern()`

```c
int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res)
```

creates a socket (kernel space)

**Parameters**

- `struct net *net`: net namespace
- `int family`: protocol family (AF_INET, ...)
- `int type`: communication type (SOCK_STREAM, ...)
- `int protocol`: protocol (0, ...)
- `struct socket **res`: new socket

**Description**

A wrapper around [`__sock_create()`](#c-__sock_create).
Returns 0 or an error. This function internally uses GFP_KERNEL.

#### <a id="c-sock_register"></a>`sock_register()`

```c
int sock_register(const struct net_proto_family *ops)
```

add a socket protocol handler

**Parameters**

- `const struct net_proto_family *ops`: description of protocol

**Description**

This function is called by a protocol handler that wants to
advertise its address family, and have it linked into the
socket interface. The value ops->family corresponds to the
socket system call protocol family.

#### <a id="c-sock_unregister"></a>`sock_unregister()`

```c
void sock_unregister(int family)
```

remove a protocol handler

**Parameters**

- `int family`: protocol family to remove

**Description**

This function is called by a protocol handler that wants to
remove its address family, and have it unlinked from the
new socket creation.

If protocol handler is a module, then it can use module reference
counts to protect against new references. If protocol handler is not
a module then it needs to provide its own protection in
the ops->create routine.

#### <a id="c-kernel_bind"></a>`kernel_bind()`

```c
int kernel_bind(struct socket *sock, struct sockaddr_unsized *addr, int addrlen)
```

bind an address to a socket (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr_unsized *addr`: address
- `int addrlen`: length of address

**Description**

Returns 0 or an error.

#### <a id="c-kernel_listen"></a>`kernel_listen()`

```c
int kernel_listen(struct socket *sock, int backlog)
```

move socket to listening state (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `int backlog`: pending connections queue size

**Description**

Returns 0 or an error.

#### <a id="c-kernel_accept"></a>`kernel_accept()`

```c
int kernel_accept(struct socket *sock, struct socket **newsock, int flags)
```

accept a connection (kernel space)

**Parameters**

- `struct socket *sock`: listening socket
- `struct socket **newsock`: new connected socket
- `int flags`: flags

**Description**

**flags** must be SOCK_CLOEXEC, SOCK_NONBLOCK or 0.
If it fails, **newsock** is guaranteed to be `NULL`.
Returns 0 or an error.

#### <a id="c-kernel_connect"></a>`kernel_connect()`

```c
int kernel_connect(struct socket *sock, struct sockaddr_unsized *addr, int addrlen, int flags)
```

connect a socket (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr_unsized *addr`: address
- `int addrlen`: address length
- `int flags`: flags (O_NONBLOCK, ...)

**Description**

For datagram sockets, **addr** is the address to which datagrams are sent
by default, and the only address from which datagrams are received.
For stream sockets, attempts to connect to **addr**.
Returns 0 or an error code.

#### <a id="c-kernel_getsockname"></a>`kernel_getsockname()`

```c
int kernel_getsockname(struct socket *sock, struct sockaddr *addr)
```

get the address which the socket is bound (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr *addr`: address holder

**Description**

Fills the **addr** pointer with the address which the socket is bound.
Returns the length of the address in bytes or an error code.

#### <a id="c-kernel_getpeername"></a>`kernel_getpeername()`

```c
int kernel_getpeername(struct socket *sock, struct sockaddr *addr)
```

get the address which the socket is connected (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `struct sockaddr *addr`: address holder

**Description**

Fills the **addr** pointer with the address which the socket is connected.
Returns the length of the address in bytes or an error code.

#### <a id="c-kernel_sock_shutdown"></a>`kernel_sock_shutdown()`

```c
int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
```

shut down part of a full-duplex connection (kernel space)

**Parameters**

- `struct socket *sock`: socket
- `enum sock_shutdown_cmd how`: connection part

**Description**

Returns 0 or an error.

#### <a id="c-kernel_sock_ip_overhead"></a>`kernel_sock_ip_overhead()`

```c
u32 kernel_sock_ip_overhead(struct sock *sk)
```

returns the IP overhead imposed by a socket

**Parameters**

- `struct sock *sk`: socket

**Description**

This routine returns the IP overhead imposed by a socket i.e.
the length of the underlying IP header, depending on whether
this is an IPv4 or IPv6 socket and the length from IP options turned
on at the socket. Assumes that the caller has a lock on the socket.



#### <a id="c-drop_reasons_register_subsys"></a>`drop_reasons_register_subsys()`

```c
void drop_reasons_register_subsys(enum skb_drop_reason_subsys subsys, const struct drop_reason_list *list)
```

register another drop reason subsystem

**Parameters**

- `enum skb_drop_reason_subsys subsys`: the subsystem to register, must not be the core
- `const struct drop_reason_list *list`: the list of drop reasons within the subsystem, must point to
  a statically initialized list

#### <a id="c-drop_reasons_unregister_subsys"></a>`drop_reasons_unregister_subsys()`

```c
void drop_reasons_unregister_subsys(enum skb_drop_reason_subsys subsys)
```

unregister a drop reason subsystem

**Parameters**

- `enum skb_drop_reason_subsys subsys`: the subsystem to remove, must not be the core

**Note**

This will [`synchronize_rcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_rcu) to ensure no users when it returns.

#### <a id="c-napi_skb_cache_get_bulk"></a>`napi_skb_cache_get_bulk()`

```c
u32 napi_skb_cache_get_bulk(void **skbs, u32 n)
```

obtain a number of zeroed skb heads from the cache

**Parameters**

- `void **skbs`: pointer to an at least **n**-sized array to fill with skb pointers
- `u32 n`: number of entries to provide

**Description**

Tries to obtain **n** [`sk_buff`](#c-struct-sk_buff) entries from the NAPI percpu cache and writes
the pointers into the provided array **skbs**. If there are less entries
available, tries to replenish the cache and bulk-allocates the diff from
the MM layer if needed.
The heads are being zeroed with either [`memset()`](/kernel/internals/core-api/kernel-api.md#c-memset) or `__GFP_ZERO`, so they are
ready for {,__}[`build_skb_around()`](#c-build_skb_around) and don't have any data buffers attached.
Must be called *only* from the BH context.

**Return**

number of successfully allocated skbs (**n** if no actual allocation
needed or `kmem_cache_alloc_bulk()` didn't fail).

#### <a id="c-build_skb_around"></a>`build_skb_around()`

```c
struct sk_buff * build_skb_around(struct sk_buff *skb, void *data, unsigned int frag_size)
```

build a network buffer around provided skb

**Parameters**

- `struct sk_buff *skb`: sk_buff provide by caller, must be memset cleared
- `void *data`: data buffer provided by caller
- `unsigned int frag_size`: size of data

#### <a id="c-napi_build_skb"></a>`napi_build_skb()`

```c
struct sk_buff * napi_build_skb(void *data, unsigned int frag_size)
```

build a network buffer

**Parameters**

- `void *data`: data buffer provided by caller
- `unsigned int frag_size`: size of data

**Description**

Version of `__napi_build_skb()` that takes care of skb->head_frag
and skb->pfmemalloc when the data is a page or page fragment.

Returns a new [`sk_buff`](#c-struct-sk_buff) on success, `NULL` on allocation failure.

#### <a id="c-__alloc_skb"></a>`__alloc_skb()`

```c
struct sk_buff * __alloc_skb(unsigned int size, gfp_t gfp_mask, int flags, int node)
```

allocate a network buffer

**Parameters**

- `unsigned int size`: size to allocate
- `gfp_t gfp_mask`: allocation mask
- `int flags`: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
  instead of head cache and allocate a cloned (child) skb.
  If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
  allocations in case the data is required for writeback
- `int node`: numa node to allocate memory on

**Description**

Allocate a new [`sk_buff`](#c-struct-sk_buff). The returned buffer has no headroom and a
tail room of at least size bytes. The object has a reference count
of one. The return is the buffer. On a failure the return is `NULL`.

Buffers may only be allocated from interrupts using a **gfp_mask** of
`GFP_ATOMIC`.

#### <a id="c-__netdev_alloc_skb"></a>`__netdev_alloc_skb()`

```c
struct sk_buff * __netdev_alloc_skb(struct net_device *dev, unsigned int len, gfp_t gfp_mask)
```

allocate an skbuff for rx on a specific device

**Parameters**

- `struct net_device *dev`: network device to receive on
- `unsigned int len`: length to allocate
- `gfp_t gfp_mask`: get_free_pages mask, passed to alloc_skb

**Description**

Allocate a new [`sk_buff`](#c-struct-sk_buff) and assign it a usage count of one. The
buffer has NET_SKB_PAD headroom built in. Users should allocate
the headroom they think they need without accounting for the
built in space. The built in space is used for optimisations.

`NULL` is returned if there is no free memory.

#### <a id="c-napi_alloc_skb"></a>`napi_alloc_skb()`

```c
struct sk_buff * napi_alloc_skb(struct napi_struct *napi, unsigned int len)
```

allocate skbuff for rx in a specific NAPI instance

**Parameters**

- `struct napi_struct *napi`: napi instance this buffer was allocated for
- `unsigned int len`: length to allocate

**Description**

Allocate a new sk_buff for use in NAPI receive.  This buffer will
attempt to allocate the head from a special reserved region used
only for NAPI Rx allocation.  By doing this we can save several
CPU cycles by avoiding having to disable and re-enable IRQs.

`NULL` is returned if there is no free memory.

#### <a id="c-__kfree_skb"></a>`__kfree_skb()`

```c
void __kfree_skb(struct sk_buff *skb)
```

private function

**Parameters**

- `struct sk_buff *skb`: buffer

**Description**

Free an sk_buff. Release anything attached to the buffer.
Clean the state. This is an internal helper function. Users should
always call kfree_skb

#### <a id="c-sk_skb_reason_drop"></a>`sk_skb_reason_drop()`

```c
void __fix_address sk_skb_reason_drop(struct sock *sk, struct sk_buff *skb, enum skb_drop_reason reason)
```

free an sk_buff with special reason

**Parameters**

- `struct sock *sk`: the socket to receive **skb**, or NULL if not applicable
- `struct sk_buff *skb`: buffer to free
- `enum skb_drop_reason reason`: reason why this skb is dropped

**Description**

Drop a reference to the buffer and free it if the usage count has hit
zero. Meanwhile, pass the receiving socket and drop reason to
'kfree_skb' tracepoint.

#### <a id="c-skb_tx_error"></a>`skb_tx_error()`

```c
void skb_tx_error(struct sk_buff *skb)
```

report an sk_buff xmit error

**Parameters**

- `struct sk_buff *skb`: buffer that triggered an error

**Description**

Report xmit error if a device callback is tracking this skb.
skb must be freed afterwards.

#### <a id="c-consume_skb"></a>`consume_skb()`

```c
void consume_skb(struct sk_buff *skb)
```

free an skbuff

**Parameters**

- `struct sk_buff *skb`: buffer to free

**Description**

Drop a ref to the buffer and free it if the usage count has hit zero
Functions identically to kfree_skb, but kfree_skb assumes that the frame
is being dropped after a failure and notes that

#### <a id="c-napi_consume_skb"></a>`napi_consume_skb()`

```c
void napi_consume_skb(struct sk_buff *skb, int budget)
```

consume skb in NAPI context, try to feed skb cache

**Parameters**

- `struct sk_buff *skb`: buffer to free
- `int budget`: NAPI budget

**Description**

Non-zero **budget** must come from the **budget** argument passed by the core
to a NAPI poll function. Note that core may pass budget of 0 to NAPI poll
for example when polling for netpoll / netconsole.

Passing **budget** of 0 is safe from any context, it turns this function
into `dev_consume_skb_any()`.

#### <a id="c-alloc_skb_for_msg"></a>`alloc_skb_for_msg()`

```c
struct sk_buff * alloc_skb_for_msg(struct sk_buff *first)
```

allocate sk_buff to wrap frag list forming a msg

**Parameters**

- `struct sk_buff *first`: first sk_buff of the msg

#### <a id="c-skb_morph"></a>`skb_morph()`

```c
struct sk_buff * skb_morph(struct sk_buff *dst, struct sk_buff *src)
```

morph one skb into another

**Parameters**

- `struct sk_buff *dst`: the skb to receive the contents
- `struct sk_buff *src`: the skb to supply the contents

**Description**

This is identical to skb_clone except that the target skb is
supplied by the user.

The target skb is returned upon exit.

#### <a id="c-skb_copy_ubufs"></a>`skb_copy_ubufs()`

```c
int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
```

copy userspace skb frags buffers to kernel

**Parameters**

- `struct sk_buff *skb`: the skb to modify
- `gfp_t gfp_mask`: allocation priority

**Description**

This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
It will copy all frags into kernel and drop the reference
to userspace pages.

If this function is called from an interrupt `gfp_mask()` must be
`GFP_ATOMIC`.

Returns 0 on success or a negative error code on failure
to allocate kernel memory to copy to.

#### <a id="c-skb_clone"></a>`skb_clone()`

```c
struct sk_buff * skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
```

duplicate an sk_buff

**Parameters**

- `struct sk_buff *skb`: buffer to clone
- `gfp_t gfp_mask`: allocation priority

**Description**

Duplicate an [`sk_buff`](#c-struct-sk_buff). The new one is not owned by a socket. Both
copies share the same packet data but not structure. The new
buffer has a reference count of 1. If the allocation fails the
function returns `NULL` otherwise the new buffer is returned.

If this function is called from an interrupt `gfp_mask()` must be
`GFP_ATOMIC`.

#### <a id="c-skb_copy"></a>`skb_copy()`

```c
struct sk_buff * skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
```

create private copy of an sk_buff

**Parameters**

- `const struct sk_buff *skb`: buffer to copy
- `gfp_t gfp_mask`: allocation priority

**Description**

Make a copy of both an [`sk_buff`](#c-struct-sk_buff) and its data. This is used when the
caller wishes to modify the data and needs a private copy of the
data to alter. Returns `NULL` on failure or the pointer to the buffer
on success. The returned buffer has a reference count of 1.

As by-product this function converts non-linear [`sk_buff`](#c-struct-sk_buff) to linear
one, so that [`sk_buff`](#c-struct-sk_buff) becomes completely private and caller is allowed
to modify all the data of returned buffer. This means that this
function is not recommended for use in circumstances when only
header is going to be modified. Use `pskb_copy()` instead.

#### <a id="c-__pskb_copy_fclone"></a>`__pskb_copy_fclone()`

```c
struct sk_buff * __pskb_copy_fclone(struct sk_buff *skb, int headroom, gfp_t gfp_mask, bool fclone)
```

create copy of an sk_buff with private head.

**Parameters**

- `struct sk_buff *skb`: buffer to copy
- `int headroom`: headroom of new skb
- `gfp_t gfp_mask`: allocation priority
- `bool fclone`: if true allocate the copy of the skb from the fclone
  cache instead of the head cache; it is recommended to set this
  to true for the cases where the copy will likely be cloned

**Description**

Make a copy of both an [`sk_buff`](#c-struct-sk_buff) and part of its data, located
in header. Fragmented data remain shared. This is used when
the caller wishes to modify only header of [`sk_buff`](#c-struct-sk_buff) and needs
private copy of the header to alter. Returns `NULL` on failure
or the pointer to the buffer on success.
The returned buffer has a reference count of 1.

#### <a id="c-pskb_expand_head"></a>`pskb_expand_head()`

```c
int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail, gfp_t gfp_mask)
```

reallocate header of [`sk_buff`](#c-struct-sk_buff)

**Parameters**

- `struct sk_buff *skb`: buffer to reallocate
- `int nhead`: room to add at head
- `int ntail`: room to add at tail
- `gfp_t gfp_mask`: allocation priority

**Description**

Expands (or creates identical copy, if **nhead** and **ntail** are zero)
header of **skb**. [`sk_buff`](#c-struct-sk_buff) itself is not changed. [`sk_buff`](#c-struct-sk_buff) MUST have
reference count of 1. Returns zero in the case of success or error,
if expansion failed. In the last case, [`sk_buff`](#c-struct-sk_buff) is not changed.

All the pointers pointing into skb header may change and must be
reloaded after call to this function.

**Note**

- If you [`skb_push()`](#c-skb_push) the start of the buffer after reallocating the

  header, call [`skb_postpush_data_move()`](#c-skb_postpush_data_move) first to move the metadata out of
  the way before writing to [`sk_buff->data`](#c-struct-sk_buff).

#### <a id="c-skb_expand_head"></a>`skb_expand_head()`

```c
struct sk_buff * skb_expand_head(struct sk_buff *skb, unsigned int headroom)
```

reallocate header of [`sk_buff`](#c-struct-sk_buff)

**Parameters**

- `struct sk_buff *skb`: buffer to reallocate
- `unsigned int headroom`: needed headroom

**Description**

Unlike skb_realloc_headroom, this one does not allocate a new skb
if possible; copies skb->sk to new skb as needed
and frees original skb in case of failures.

It expect increased headroom and generates warning otherwise.

#### <a id="c-skb_copy_expand"></a>`skb_copy_expand()`

```c
struct sk_buff * skb_copy_expand(const struct sk_buff *skb, int newheadroom, int newtailroom, gfp_t gfp_mask)
```

copy and expand sk_buff

**Parameters**

- `const struct sk_buff *skb`: buffer to copy
- `int newheadroom`: new free bytes at head
- `int newtailroom`: new free bytes at tail
- `gfp_t gfp_mask`: allocation priority

**Description**

Make a copy of both an [`sk_buff`](#c-struct-sk_buff) and its data and while doing so
allocate additional space.

This is used when the caller wishes to modify the data and needs a
private copy of the data to alter as well as more space for new fields.
Returns `NULL` on failure or the pointer to the buffer
on success. The returned buffer has a reference count of 1.

You must pass `GFP_ATOMIC` as the allocation priority if this function
is called from an interrupt.

#### <a id="c-__skb_pad"></a>`__skb_pad()`

```c
int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
```

zero pad the tail of an skb

**Parameters**

- `struct sk_buff *skb`: buffer to pad
- `int pad`: space to pad
- `bool free_on_error`: free buffer on error

**Description**

Ensure that a buffer is followed by a padding area that is zero
filled. Used by network drivers which may DMA or transfer data
beyond the buffer end onto the wire.

May return error in out of memory cases. The skb is freed on error
if **free_on_error** is true.

#### <a id="c-pskb_put"></a>`pskb_put()`

```c
void * pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
```

add data to the tail of a potentially fragmented buffer

**Parameters**

- `struct sk_buff *skb`: start of the buffer to use
- `struct sk_buff *tail`: tail fragment of the buffer to use
- `int len`: amount of data to add

**Description**

This function extends the used data area of the potentially
fragmented buffer. **tail** must be the last fragment of **skb** -- or
**skb** itself. If this would exceed the total buffer size the kernel
will panic. A pointer to the first byte of the extra data is
returned.

#### <a id="c-skb_put"></a>`skb_put()`

```c
void * skb_put(struct sk_buff *skb, unsigned int len)
```

add data to a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to use
- `unsigned int len`: amount of data to add

**Description**

This function extends the used data area of the buffer. If this would
exceed the total buffer size the kernel will panic. A pointer to the
first byte of the extra data is returned.

#### <a id="c-skb_push"></a>`skb_push()`

```c
void * skb_push(struct sk_buff *skb, unsigned int len)
```

add data to the start of a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to use
- `unsigned int len`: amount of data to add

**Description**

This function extends the used data area of the buffer at the buffer
start. If this would exceed the total buffer headroom the kernel will
panic. A pointer to the first byte of the extra data is returned.

#### <a id="c-skb_pull"></a>`skb_pull()`

```c
void * skb_pull(struct sk_buff *skb, unsigned int len)
```

remove data from the start of a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to use
- `unsigned int len`: amount of data to remove

**Description**

This function removes data from the start of a buffer, returning
the memory to the headroom. A pointer to the next data in the buffer
is returned. Once the data has been pulled future pushes will overwrite
the old data.

#### <a id="c-skb_pull_data"></a>`skb_pull_data()`

```c
void * skb_pull_data(struct sk_buff *skb, size_t len)
```

remove data from the start of a buffer returning its original position.

**Parameters**

- `struct sk_buff *skb`: buffer to use
- `size_t len`: amount of data to remove

**Description**

This function removes data from the start of a buffer, returning
the memory to the headroom. A pointer to the original data in the buffer
is returned after checking if there is enough data to pull. Once the
data has been pulled future pushes will overwrite the old data.

#### <a id="c-skb_trim"></a>`skb_trim()`

```c
void skb_trim(struct sk_buff *skb, unsigned int len)
```

remove end from a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to alter
- `unsigned int len`: new length

**Description**

Cut the length of a buffer down by removing data from the tail. If
the buffer is already under the length specified it is not modified.
The skb must be linear.

#### <a id="c-__pskb_pull_tail"></a>`__pskb_pull_tail()`

```c
void * __pskb_pull_tail(struct sk_buff *skb, int delta)
```

advance tail of skb header

**Parameters**

- `struct sk_buff *skb`: buffer to reallocate
- `int delta`: number of bytes to advance tail

**Description**

The function makes a sense only on a fragmented [`sk_buff`](#c-struct-sk_buff),
it expands header moving its tail forward and copying necessary
data from fragmented part.

[`sk_buff`](#c-struct-sk_buff) MUST have reference count of 1.

Returns `NULL` (and [`sk_buff`](#c-struct-sk_buff) does not change) if pull failed
or value of new tail of skb in the case of success.

All the pointers pointing into skb header may change and must be
reloaded after call to this function.

#### <a id="c-skb_copy_bits"></a>`skb_copy_bits()`

```c
int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
```

copy bits from skb to kernel buffer

**Parameters**

- `const struct sk_buff *skb`: source skb
- `int offset`: offset in source
- `void *to`: destination buffer
- `int len`: number of bytes to copy

**Description**

Copy the specified number of bytes from the source skb to the
destination buffer.

- CAUTION ! :
  If its prototype is ever changed,
  check arch/{*}/net/{*}.S files,
  since it is called from BPF assembly code.

#### <a id="c-skb_store_bits"></a>`skb_store_bits()`

```c
int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
```

store bits from kernel buffer to skb

**Parameters**

- `struct sk_buff *skb`: destination buffer
- `int offset`: offset in destination
- `const void *from`: source buffer
- `int len`: number of bytes to copy

**Description**

Copy the specified number of bytes from the source buffer to the
destination skb.  This function handles all the messy bits of
traversing fragment lists and such.

#### <a id="c-skb_zerocopy"></a>`skb_zerocopy()`

```c
int skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
```

Zero copy skb to skb

**Parameters**

- `struct sk_buff *to`: destination buffer
- `struct sk_buff *from`: source buffer
- `int len`: number of bytes to copy from source buffer
- `int hlen`: size of linear headroom in destination buffer

**Description**

Copies up to `len` bytes from `from` to `to` by creating references
to the frags in the source buffer.

The `hlen` as calculated by `skb_zerocopy_headlen()` specifies the
headroom in the `to` buffer.

Return value:
0: everything is OK
-ENOMEM: couldn't orphan frags of **from** due to lack of memory
-EFAULT: [`skb_copy_bits()`](#c-skb_copy_bits) found some problem with skb geometry

#### <a id="c-skb_dequeue"></a>`skb_dequeue()`

```c
struct sk_buff * skb_dequeue(struct sk_buff_head *list)
```

remove from the head of the queue

**Parameters**

- `struct sk_buff_head *list`: list to dequeue from

**Description**

Remove the head of the list. The list lock is taken so the function
may be used safely with other locking list functions. The head item is
returned or `NULL` if the list is empty.

#### <a id="c-skb_dequeue_tail"></a>`skb_dequeue_tail()`

```c
struct sk_buff * skb_dequeue_tail(struct sk_buff_head *list)
```

remove from the tail of the queue

**Parameters**

- `struct sk_buff_head *list`: list to dequeue from

**Description**

Remove the tail of the list. The list lock is taken so the function
may be used safely with other locking list functions. The tail item is
returned or `NULL` if the list is empty.

#### <a id="c-skb_queue_purge_reason"></a>`skb_queue_purge_reason()`

```c
void skb_queue_purge_reason(struct sk_buff_head *list, enum skb_drop_reason reason)
```

empty a list

**Parameters**

- `struct sk_buff_head *list`: list to empty
- `enum skb_drop_reason reason`: drop reason

**Description**

Delete all buffers on an [`sk_buff`](#c-struct-sk_buff) list. Each buffer is removed from
the list and one reference dropped. This function takes the list
lock and is atomic with respect to other list locking functions.

#### <a id="c-skb_queue_head"></a>`skb_queue_head()`

```c
void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
```

queue a buffer at the list head

**Parameters**

- `struct sk_buff_head *list`: list to use
- `struct sk_buff *newsk`: buffer to queue

**Description**

Queue a buffer at the start of the list. This function takes the
list lock and can be used safely with other locking [`sk_buff`](#c-struct-sk_buff) functions
safely.

A buffer cannot be placed on two lists at the same time.

#### <a id="c-skb_queue_tail"></a>`skb_queue_tail()`

```c
void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
```

queue a buffer at the list tail

**Parameters**

- `struct sk_buff_head *list`: list to use
- `struct sk_buff *newsk`: buffer to queue

**Description**

Queue a buffer at the tail of the list. This function takes the
list lock and can be used safely with other locking [`sk_buff`](#c-struct-sk_buff) functions
safely.

A buffer cannot be placed on two lists at the same time.

#### <a id="c-skb_unlink"></a>`skb_unlink()`

```c
void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
```

remove a buffer from a list

**Parameters**

- `struct sk_buff *skb`: buffer to remove
- `struct sk_buff_head *list`: list to use

**Description**

Remove a packet from a list. The list locks are taken and this
function is atomic with respect to other list locked calls

You must know what list the SKB is on.

#### <a id="c-skb_append"></a>`skb_append()`

```c
void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
```

append a buffer

**Parameters**

- `struct sk_buff *old`: buffer to insert after
- `struct sk_buff *newsk`: buffer to insert
- `struct sk_buff_head *list`: list to use

**Description**

Place a packet after a given packet in a list. The list locks are taken
and this function is atomic with respect to other list locked calls.
A buffer cannot be placed on two lists at the same time.

#### <a id="c-skb_split"></a>`skb_split()`

```c
void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
```

Split fragmented skb to two parts at length len.

**Parameters**

- `struct sk_buff *skb`: the buffer to split
- `struct sk_buff *skb1`: the buffer to receive the second part
- `const u32 len`: new length for skb

#### <a id="c-skb_prepare_seq_read"></a>`skb_prepare_seq_read()`

```c
void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from, unsigned int to, struct skb_seq_state *st)
```

Prepare a sequential read of skb data

**Parameters**

- `struct sk_buff *skb`: the buffer to read
- `unsigned int from`: lower offset of data to be read
- `unsigned int to`: upper offset of data to be read
- `struct skb_seq_state *st`: state variable

**Description**

Initializes the specified state variable. Must be called before
invoking [`skb_seq_read()`](#c-skb_seq_read) for the first time.

#### <a id="c-skb_seq_read"></a>`skb_seq_read()`

```c
unsigned int skb_seq_read(unsigned int consumed, const u8 **data, struct skb_seq_state *st)
```

Sequentially read skb data

**Parameters**

- `unsigned int consumed`: number of bytes consumed by the caller so far
- `const u8 **data`: destination pointer for data to be returned
- `struct skb_seq_state *st`: state variable

**Description**

Reads a block of skb data at **consumed** relative to the
lower offset specified to [`skb_prepare_seq_read()`](#c-skb_prepare_seq_read). Assigns
the head of the data block to **data** and returns the length
of the block or 0 if the end of the skb data or the upper
offset has been reached.

The caller is not required to consume all of the data
returned, i.e. **consumed** is typically set to the number
of bytes already consumed and the next call to
[`skb_seq_read()`](#c-skb_seq_read) will return the remaining part of the block.

- Note 1: The size of each block of data returned can be arbitrary,

  this limitation is the cost for zerocopy sequential
  reads of potentially non linear data.

- Note 2: Fragment lists within fragments are not implemented

  at the moment, state->root_skb could be replaced with
  a stack for this purpose.

#### <a id="c-skb_abort_seq_read"></a>`skb_abort_seq_read()`

```c
void skb_abort_seq_read(struct skb_seq_state *st)
```

Abort a sequential read of skb data

**Parameters**

- `struct skb_seq_state *st`: state variable

**Description**

Must be called if [`skb_seq_read()`](#c-skb_seq_read) was not called until it
returned 0.

#### <a id="c-skb_copy_seq_read"></a>`skb_copy_seq_read()`

```c
int skb_copy_seq_read(struct skb_seq_state *st, int offset, void *to, int len)
```

copy from a skb_seq_state to a buffer

**Parameters**

- `struct skb_seq_state *st`: source skb_seq_state
- `int offset`: offset in source
- `void *to`: destination buffer
- `int len`: number of bytes to copy

**Description**

Copy **len** bytes from **offset** bytes into the source **st** to the destination
buffer **to**. `offset` should increase (or be unchanged) with each subsequent
call to this function. If offset needs to decrease from the previous use `st`
should be reset first.

**Return**

0 on success or -EINVAL if the copy ended early

#### <a id="c-skb_find_text"></a>`skb_find_text()`

```c
unsigned int skb_find_text(struct sk_buff *skb, unsigned int from, unsigned int to, struct ts_config *config)
```

Find a text pattern in skb data

**Parameters**

- `struct sk_buff *skb`: the buffer to look in
- `unsigned int from`: search offset
- `unsigned int to`: search limit
- `struct ts_config *config`: textsearch configuration

**Description**

Finds a pattern in the skb data according to the specified
textsearch configuration. Use [`textsearch_next()`](/kernel/internals/core-api/kernel-api.md#c-textsearch_next) to retrieve
subsequent occurrences of the pattern. Returns the offset
to the first occurrence or UINT_MAX if no match was found.

#### <a id="c-skb_pull_rcsum"></a>`skb_pull_rcsum()`

```c
void * skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
```

pull skb and update receive checksum

**Parameters**

- `struct sk_buff *skb`: buffer to update
- `unsigned int len`: length of data pulled

**Description**

This function performs an skb_pull on the packet and updates
the CHECKSUM_COMPLETE checksum.  It should be used on
receive path processing instead of skb_pull unless you know
that the checksum difference is zero (e.g., a valid IP header)
or you are setting ip_summed to CHECKSUM_NONE.

#### <a id="c-skb_segment"></a>`skb_segment()`

```c
struct sk_buff * skb_segment(struct sk_buff *head_skb, netdev_features_t features)
```

Perform protocol segmentation on skb.

**Parameters**

- `struct sk_buff *head_skb`: buffer to segment
- `netdev_features_t features`: features for the output path (see dev->features)

**Description**

This function performs segmentation on the given skb.  It returns
a pointer to the first in a list of new skbs for the segments.
In case of error it returns ERR_PTR(err).

#### <a id="c-skb_to_sgvec"></a>`skb_to_sgvec()`

```c
int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
```

Fill a scatter-gather list from a socket buffer

**Parameters**

- `struct sk_buff *skb`: Socket buffer containing the buffers to be mapped
- `struct scatterlist *sg`: The scatter-gather list to map into
- `int offset`: The offset into the buffer's contents to start mapping
- `int len`: Length of buffer space to be mapped

**Description**

Fill the specified scatter-gather list with mappings/pointers into a
region of the buffer space attached to a socket buffer. Returns either
the number of scatterlist items used, or -EMSGSIZE if the contents
could not fit.

#### <a id="c-skb_cow_data"></a>`skb_cow_data()`

```c
int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
```

Check that a socket buffer's data buffers are writable

**Parameters**

- `struct sk_buff *skb`: The socket buffer to check.
- `int tailbits`: Amount of trailing space to be added
- `struct sk_buff **trailer`: Returned pointer to the skb where the **tailbits** space begins

**Description**

Make sure that the data buffers attached to a socket buffer are
writable. If they are not, private copies are made of the data buffers
and the socket buffer is set to use these instead.

If **tailbits** is given, make sure that there is space to write **tailbits**
bytes of data beyond current end of socket buffer.  **trailer** will be
set to point to the skb in which this space begins.

The number of scatterlist elements required to completely map the
COW'd and extended socket buffer will be returned.

#### <a id="c-skb_clone_sk"></a>`skb_clone_sk()`

```c
struct sk_buff * skb_clone_sk(struct sk_buff *skb)
```

create clone of skb, and take reference to socket

**Parameters**

- `struct sk_buff *skb`: the skb to clone

**Description**

This function creates a clone of a buffer that holds a reference on
sk_refcnt.  Buffers created via this function are meant to be
returned using sock_queue_err_skb, or free via kfree_skb.

When passing buffers allocated with this function to sock_queue_err_skb
it is necessary to wrap the call with sock_hold/sock_put in order to
prevent the socket from being released prior to being enqueued on
the sk_error_queue.

#### <a id="c-skb_partial_csum_set"></a>`skb_partial_csum_set()`

```c
bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
```

set up and verify partial csum values for packet

**Parameters**

- `struct sk_buff *skb`: the skb to set
- `u16 start`: the number of bytes after skb->data to start checksumming.
- `u16 off`: the offset from start to place the checksum.

**Description**

For untrusted partially-checksummed packets, we need to make sure the values
for skb->csum_start and skb->csum_offset are valid so we don't oops.

This function checks and sets those values and skb->ip_summed: if this
returns false you should drop the packet.

#### <a id="c-skb_checksum_setup"></a>`skb_checksum_setup()`

```c
int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
```

set up partial checksum offset

**Parameters**

- `struct sk_buff *skb`: the skb to set up
- `bool recalculate`: if true the pseudo-header checksum will be recalculated

#### <a id="c-skb_checksum_trimmed"></a>`skb_checksum_trimmed()`

```c
struct sk_buff * skb_checksum_trimmed(struct sk_buff *skb, unsigned int transport_len, __sum16(*skb_chkf)(struct sk_buff *skb))
```

validate checksum of an skb

**Parameters**

- `struct sk_buff *skb`: the skb to check
- `unsigned int transport_len`: the data length beyond the network header
- `__sum16(*skb_chkf)(struct sk_buff *skb)`: checksum function to use

**Description**

Applies the given checksum function skb_chkf to the provided skb.
Returns a checked and maybe trimmed skb. Returns NULL on error.

If the skb has data beyond the given transport length, then a
trimmed & cloned skb is checked and returned.

Caller needs to set the skb transport header and free any returned skb if it
differs from the provided skb.

#### <a id="c-skb_try_coalesce"></a>`skb_try_coalesce()`

```c
bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from, bool *fragstolen, int *delta_truesize)
```

try to merge skb to prior one

**Parameters**

- `struct sk_buff *to`: prior buffer
- `struct sk_buff *from`: buffer to add
- `bool *fragstolen`: pointer to boolean
- `int *delta_truesize`: how much more was allocated than was requested

#### <a id="c-skb_scrub_packet"></a>`skb_scrub_packet()`

```c
void skb_scrub_packet(struct sk_buff *skb, bool xnet)
```

scrub an skb

**Parameters**

- `struct sk_buff *skb`: buffer to clean
- `bool xnet`: packet is crossing netns

**Description**

skb_scrub_packet can be used after encapsulating or decapsulating a packet
into/from a tunnel. Some information have to be cleared during these
operations.
skb_scrub_packet can also be used to clean a skb before injecting it in
another namespace (**xnet** == true). We have to clear all information in the
skb that could impact namespace isolation.

#### <a id="c-skb_eth_pop"></a>`skb_eth_pop()`

```c
int skb_eth_pop(struct sk_buff *skb)
```

Drop the Ethernet header at the head of a packet

**Parameters**

- `struct sk_buff *skb`: Socket buffer to modify

**Description**

Drop the Ethernet header of **skb**.

Expects that skb->data points to the mac header and that no VLAN tags are
present.

Returns 0 on success, -errno otherwise.

#### <a id="c-skb_eth_push"></a>`skb_eth_push()`

```c
int skb_eth_push(struct sk_buff *skb, const unsigned char *dst, const unsigned char *src)
```

Add a new Ethernet header at the head of a packet

**Parameters**

- `struct sk_buff *skb`: Socket buffer to modify
- `const unsigned char *dst`: Destination MAC address of the new header
- `const unsigned char *src`: Source MAC address of the new header

**Description**

Prepend **skb** with a new Ethernet header.

Expects that skb->data points to the mac header, which must be empty.

Returns 0 on success, -errno otherwise.

#### <a id="c-skb_mpls_push"></a>`skb_mpls_push()`

```c
int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto, int mac_len, bool ethernet)
```

push a new MPLS header after mac_len bytes from start of the packet

**Parameters**

- `struct sk_buff *skb`: buffer
- `__be32 mpls_lse`: MPLS label stack entry to push
- `__be16 mpls_proto`: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
- `int mac_len`: length of the MAC header
- `bool ethernet`: flag to indicate if the resulting packet after skb_mpls_push is
  ethernet

**Description**

Expects skb->data at mac header.

Returns 0 on success, -errno otherwise.

#### <a id="c-skb_mpls_pop"></a>`skb_mpls_pop()`

```c
int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len, bool ethernet)
```

pop the outermost MPLS header

**Parameters**

- `struct sk_buff *skb`: buffer
- `__be16 next_proto`: ethertype of header after popped MPLS header
- `int mac_len`: length of the MAC header
- `bool ethernet`: flag to indicate if the packet is ethernet

**Description**

Expects skb->data at mac header.

Returns 0 on success, -errno otherwise.

#### <a id="c-skb_mpls_update_lse"></a>`skb_mpls_update_lse()`

```c
int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
```

modify outermost MPLS header and update csum

**Parameters**

- `struct sk_buff *skb`: buffer
- `__be32 mpls_lse`: new MPLS label stack entry to update to

**Description**

Expects skb->data at mac header.

Returns 0 on success, -errno otherwise.

#### <a id="c-skb_mpls_dec_ttl"></a>`skb_mpls_dec_ttl()`

```c
int skb_mpls_dec_ttl(struct sk_buff *skb)
```

decrement the TTL of the outermost MPLS header

**Parameters**

- `struct sk_buff *skb`: buffer

**Description**

Expects skb->data at mac header.

Returns 0 on success, -errno otherwise.

#### <a id="c-alloc_skb_with_frags"></a>`alloc_skb_with_frags()`

```c
struct sk_buff * alloc_skb_with_frags(unsigned long header_len, unsigned long data_len, int order, int *errcode, gfp_t gfp_mask)
```

allocate skb with page frags

**Parameters**

- `unsigned long header_len`: size of linear part
- `unsigned long data_len`: needed length in frags
- `int order`: max page order desired.
- `int *errcode`: pointer to error code if any
- `gfp_t gfp_mask`: allocation mask

**Description**

This can be used to allocate a paged skb, given a maximal order for frags.

#### <a id="c-skb_condense"></a>`skb_condense()`

```c
void skb_condense(struct sk_buff *skb)
```

try to get rid of fragments/frag_list if possible

**Parameters**

- `struct sk_buff *skb`: buffer

**Description**

Can be used to save memory before skb is added to a busy queue.
If packet has bytes in frags and enough tail room in skb->head,
pull all of them, so that we can free the frags right now and adjust
truesize.

**Notes**

We do not reallocate skb->head thus can not fail.
Caller must re-evaluate skb->truesize if needed.

#### <a id="c-__skb_ext_set"></a>`__skb_ext_set()`

```c
void * __skb_ext_set(struct sk_buff *skb, enum skb_ext_id id, struct skb_ext *ext)
```

attach the specified extension storage to this skb

**Parameters**

- `struct sk_buff *skb`: buffer
- `enum skb_ext_id id`: extension id
- `struct skb_ext *ext`: extension storage previously allocated via `__skb_ext_alloc()`

**Description**

Existing extensions, if any, are cleared.

Returns the pointer to the extension.

#### <a id="c-skb_ext_add"></a>`skb_ext_add()`

```c
void * skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
```

allocate space for given extension, COW if needed

**Parameters**

- `struct sk_buff *skb`: buffer
- `enum skb_ext_id id`: extension to allocate space for

**Description**

Allocates enough space for the given extension.
If the extension is already present, a pointer to that extension
is returned.

If the skb was cloned, COW applies and the returned memory can be
modified without changing the extension space of clones buffers.

Returns pointer to the extension or NULL on allocation failure.

#### <a id="c-skb_splice_from_iter"></a>`skb_splice_from_iter()`

```c
ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter, ssize_t maxsize)
```

Splice (or copy) pages to skbuff

**Parameters**

- `struct sk_buff *skb`: The buffer to add pages to
- `struct iov_iter *iter`: Iterator representing the pages to be added
- `ssize_t maxsize`: Maximum amount of pages to be added

**Description**

This is a common helper function for supporting MSG_SPLICE_PAGES.  It
extracts pages from an iterator and adds them to the socket buffer if
possible, copying them to fragments if not possible (such as if they're slab
pages).

Returns the amount of data spliced/copied or -EMSGSIZE if there's
insufficient space in the buffer to transfer anything.



#### <a id="c-sk_ns_capable"></a>`sk_ns_capable()`

```c
bool sk_ns_capable(const struct sock *sk, struct user_namespace *user_ns, int cap)
```

General socket capability test

**Parameters**

- `const struct sock *sk`: Socket to use a capability on or through
- `struct user_namespace *user_ns`: The user namespace of the capability to use
- `int cap`: The capability to use

**Description**

Test to see if the opener of the socket had when the socket was
created and the current process has the capability **cap** in the user
namespace **user_ns**.

#### <a id="c-sk_capable"></a>`sk_capable()`

```c
bool sk_capable(const struct sock *sk, int cap)
```

Socket global capability test

**Parameters**

- `const struct sock *sk`: Socket to use a capability on or through
- `int cap`: The global capability to use

**Description**

Test to see if the opener of the socket had when the socket was
created and the current process has the capability **cap** in all user
namespaces.

#### <a id="c-sk_net_capable"></a>`sk_net_capable()`

```c
bool sk_net_capable(const struct sock *sk, int cap)
```

Network namespace socket capability test

**Parameters**

- `const struct sock *sk`: Socket to use a capability on or through
- `int cap`: The capability to use

**Description**

Test to see if the opener of the socket had when the socket was created
and the current process has the capability **cap** over the network namespace
the socket is a member of.

#### <a id="c-sk_set_memalloc"></a>`sk_set_memalloc()`

```c
void sk_set_memalloc(struct sock *sk)
```

sets `SOCK_MEMALLOC`

**Parameters**

- `struct sock *sk`: socket to set it on

**Description**

Set `SOCK_MEMALLOC` on a socket for access to emergency reserves.
It's the responsibility of the admin to adjust min_free_kbytes
to meet the requirements

#### <a id="c-sk_alloc"></a>`sk_alloc()`

```c
struct sock * sk_alloc(struct net *net, int family, gfp_t priority, struct proto *prot, int kern)
```

All socket objects are allocated here

**Parameters**

- `struct net *net`: the applicable net namespace
- `int family`: protocol family
- `gfp_t priority`: for allocation (`GFP_KERNEL`, `GFP_ATOMIC`, etc)
- `struct proto *prot`: struct proto associated with this new sock instance
- `int kern`: is this to be a kernel socket?

#### <a id="c-sk_clone"></a>`sk_clone()`

```c
struct sock * sk_clone(const struct sock *sk, const gfp_t priority, bool lock)
```

clone a socket

**Parameters**

- `const struct sock *sk`: the socket to clone
- `const gfp_t priority`: for allocation (`GFP_KERNEL`, `GFP_ATOMIC`, etc)
- `bool lock`: if true, lock the cloned sk

**Description**

If **lock** is true, the clone is locked by `bh_lock_sock()`, and
caller must unlock socket even in error path by `bh_unlock_sock()`.

#### <a id="c-skb_page_frag_refill"></a>`skb_page_frag_refill()`

```c
bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
```

check that a page_frag contains enough room

**Parameters**

- `unsigned int sz`: minimum size of the fragment we want to get
- `struct page_frag *pfrag`: pointer to page_frag
- `gfp_t gfp`: priority for memory allocation

**Note**

While this allocator tries to use high order pages, there is
no guarantee that allocations succeed. Therefore, **sz** MUST be
less or equal than PAGE_SIZE.

#### <a id="c-sk_wait_data"></a>`sk_wait_data()`

```c
int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
```

wait for data to arrive at sk_receive_queue

**Parameters**

- `struct sock *sk`: sock to wait on
- `long *timeo`: for how long
- `const struct sk_buff *skb`: last skb seen on sk_receive_queue

**Description**

Now socket state including sk->sk_err is changed only under lock,
hence we may omit checks after joining wait queue.
We check receive queue before `schedule()` only as optimization;
it is very likely that `release_sock()` added new data.

#### <a id="c-__sk_mem_schedule"></a>`__sk_mem_schedule()`

```c
int __sk_mem_schedule(struct sock *sk, int size, int kind)
```

increase sk_forward_alloc and memory_allocated

**Parameters**

- `struct sock *sk`: socket
- `int size`: memory size to allocate
- `int kind`: allocation type

**Description**

If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
rmem allocation. This function assumes that protocols which have
memory_pressure use sk_wmem_queued as write buffer accounting.

#### <a id="c-__sk_mem_reclaim"></a>`__sk_mem_reclaim()`

```c
void __sk_mem_reclaim(struct sock *sk, int amount)
```

reclaim sk_forward_alloc and memory_allocated

**Parameters**

- `struct sock *sk`: socket
- `int amount`: number of bytes (rounded down to a PAGE_SIZE multiple)



#### <a id="c-__skb_try_recv_datagram"></a>`__skb_try_recv_datagram()`

```c
struct sk_buff * __skb_try_recv_datagram(struct sock *sk, struct sk_buff_head *queue, unsigned int flags, int *off, int *err, struct sk_buff **last)
```

Receive a datagram skbuff

**Parameters**

- `struct sock *sk`: socket
- `struct sk_buff_head *queue`: socket queue from which to receive
- `unsigned int flags`: MSG\_ flags
- `int *off`: an offset in bytes to peek skb from. Returns an offset
  within an skb where data actually starts
- `int *err`: error code returned
- `struct sk_buff **last`: set to last peeked message to inform the wait function
  what to look for when peeking

**Description**

Get a datagram skbuff, understands the peeking, nonblocking wakeups
and possible races. This replaces identical code in packet, raw and
udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
the long standing peek and read race for datagram sockets. If you
alter this routine remember it must be re-entrant.

This function will lock the socket if a skb is returned, so
the caller needs to unlock the socket in that case (usually by
calling skb_free_datagram). Returns NULL with **err** set to
-EAGAIN if no data was available or to some other value if an
error was detected.

* It does not lock socket since today. This function is
* free of race conditions. This measure should/can improve
* significantly datagram socket latencies at high loads,
* when data copying to user space takes lots of time.
* (BTW I've just killed the last `cli()` in IP/IPv6/core/netlink/packet
* 8) Great win.)
* --ANK (980729)

The order of the tests when we find no data waiting are specified
quite explicitly by POSIX 1003.1g, don't change them without having
the standard around please.

#### <a id="c-skb_kill_datagram"></a>`skb_kill_datagram()`

```c
int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
```

Free a datagram skbuff forcibly

**Parameters**

- `struct sock *sk`: socket
- `struct sk_buff *skb`: datagram skbuff
- `unsigned int flags`: MSG\_ flags

**Description**

This function frees a datagram skbuff that was received by
skb_recv_datagram.  The flags argument must match the one
used for skb_recv_datagram.

If the MSG_PEEK flag is set, and the packet is still on the
receive queue of the socket, it will be taken off the queue
before it is freed.

This function currently only disables BH when acquiring the
sk_receive_queue lock.  Therefore it must not be used in a
context where that lock is acquired in an IRQ context.

It returns 0 if the packet was removed by us.

#### <a id="c-skb_copy_and_crc32c_datagram_iter"></a>`skb_copy_and_crc32c_datagram_iter()`

```c
int skb_copy_and_crc32c_datagram_iter(const struct sk_buff *skb, int offset, struct iov_iter *to, int len, u32 *crcp)
```

Copy datagram to an iovec iterator and update a CRC32C value.

**Parameters**

- `const struct sk_buff *skb`: buffer to copy
- `int offset`: offset in the buffer to start copying from
- `struct iov_iter *to`: iovec iterator to copy to
- `int len`: amount of data to copy from buffer to iovec
- `u32 *crcp`: pointer to CRC32C value to update

**Return**

0 on success, -EFAULT if there was a fault during copy.

#### <a id="c-skb_copy_datagram_iter"></a>`skb_copy_datagram_iter()`

```c
int skb_copy_datagram_iter(const struct sk_buff *skb, int offset, struct iov_iter *to, int len)
```

Copy a datagram to an iovec iterator.

**Parameters**

- `const struct sk_buff *skb`: buffer to copy
- `int offset`: offset in the buffer to start copying from
- `struct iov_iter *to`: iovec iterator to copy to
- `int len`: amount of data to copy from buffer to iovec

#### <a id="c-skb_copy_datagram_from_iter"></a>`skb_copy_datagram_from_iter()`

```c
int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset, struct iov_iter *from, int len)
```

Copy a datagram from an iov_iter.

**Parameters**

- `struct sk_buff *skb`: buffer to copy
- `int offset`: offset in the buffer to start copying to
- `struct iov_iter *from`: the copy source
- `int len`: amount of data to copy to buffer from iovec

**Description**

Returns 0 or -EFAULT.

#### <a id="c-zerocopy_sg_from_iter"></a>`zerocopy_sg_from_iter()`

```c
int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
```

Build a zerocopy datagram from an iov_iter

**Parameters**

- `struct sk_buff *skb`: buffer to copy
- `struct iov_iter *from`: the source to copy from

**Description**

The function will first copy up to headlen, and then pin the userspace
pages and build frags through them.

Returns 0, -EFAULT or -EMSGSIZE.

#### <a id="c-skb_copy_and_csum_datagram_msg"></a>`skb_copy_and_csum_datagram_msg()`

```c
int skb_copy_and_csum_datagram_msg(struct sk_buff *skb, int hlen, struct msghdr *msg)
```

Copy and checksum skb to user iovec.

**Parameters**

- `struct sk_buff *skb`: skbuff
- `int hlen`: hardware length
- `struct msghdr *msg`: destination

**Description**

Caller _must_ check that skb will fit to this iovec.

**Return**

0       - success.
-EINVAL - checksum failure.
-EFAULT - fault during copy.

#### <a id="c-datagram_poll_queue"></a>`datagram_poll_queue()`

```c
__poll_t datagram_poll_queue(struct file *file, struct socket *sock, poll_table *wait, struct sk_buff_head *rcv_queue)
```

same as datagram_poll, but on a specific receive queue

**Parameters**

- `struct file *file`: file struct
- `struct socket *sock`: socket
- `poll_table *wait`: poll table
- `struct sk_buff_head *rcv_queue`: receive queue to poll

**Description**

Performs polling on the given receive queue, handling shutdown, error,
and connection state. This is useful for protocols that deliver
userspace-bound packets through a custom queue instead of
sk->sk_receive_queue.

**Return**

poll bitmask indicating the socket's current state

#### <a id="c-datagram_poll"></a>`datagram_poll()`

```c
__poll_t datagram_poll(struct file *file, struct socket *sock, poll_table *wait)
```

generic datagram poll

**Parameters**

- `struct file *file`: file struct
- `struct socket *sock`: socket
- `poll_table *wait`: poll table

**Description**

Datagram poll: Again totally generic. This also handles
sequenced packet sockets providing the socket receive queue
is only ever holding data ready to receive.

**Note**

- when you *don't* use this routine for this protocol,

  and you use a different write policy from `sock_writeable()`
  then please supply your own write_space callback.

**Return**

poll bitmask indicating the socket's current state



#### <a id="c-sk_stream_wait_connect"></a>`sk_stream_wait_connect()`

```c
int sk_stream_wait_connect(struct sock *sk, long *timeo_p)
```

Wait for a socket to get into the connected state

**Parameters**

- `struct sock *sk`: sock to wait on
- `long *timeo_p`: for how long to wait

**Description**

Must be called with the socket locked.

#### <a id="c-sk_stream_wait_memory"></a>`sk_stream_wait_memory()`

```c
int sk_stream_wait_memory(struct sock *sk, long *timeo_p)
```

Wait for more memory for a socket

**Parameters**

- `struct sock *sk`: socket to wait for memory
- `long *timeo_p`: for how long


<a id="rst-socket-filter"></a>

### Socket Filter


#### <a id="c-sk_filter_trim_cap"></a>`sk_filter_trim_cap()`

```c
int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap, enum skb_drop_reason *reason)
```

run a packet through a socket filter

**Parameters**

- `struct sock *sk`: sock associated with [`sk_buff`](#c-struct-sk_buff)
- `struct sk_buff *skb`: buffer to filter
- `unsigned int cap`: limit on how short the eBPF program may trim the packet
- `enum skb_drop_reason *reason`: record drop reason on errors (negative return value)

**Description**

Run the eBPF program and then cut skb->data to correct size returned by
the program. If pkt_len is 0 we toss packet. If skb->len is smaller
than pkt_len we keep whole skb->data. This is the socket level
wrapper to bpf_prog_run. It returns 0 if the packet should
be accepted or -EPERM if the packet should be tossed.

#### <a id="c-bpf_prog_create"></a>`bpf_prog_create()`

```c
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
```

create an unattached filter

**Parameters**

- `struct bpf_prog **pfp`: the unattached filter that is created
- `struct sock_fprog_kern *fprog`: the filter program

**Description**

Create a filter independent of any socket. We first run some
sanity checks on it to make sure it does not explode on us later.
If an error occurs or there is insufficient memory for the filter
a negative errno code is returned. On success the return is zero.

#### <a id="c-bpf_prog_create_from_user"></a>`bpf_prog_create_from_user()`

```c
int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog, bpf_aux_classic_check_t trans, bool save_orig)
```

create an unattached filter from user buffer

**Parameters**

- `struct bpf_prog **pfp`: the unattached filter that is created
- `struct sock_fprog *fprog`: the filter program
- `bpf_aux_classic_check_t trans`: post-classic verifier transformation handler
- `bool save_orig`: save classic BPF program

**Description**

This function effectively does the same as [`bpf_prog_create()`](#c-bpf_prog_create), only
that it builds up its insns buffer from user space provided buffer.
It also allows for passing a bpf_aux_classic_check_t handler.

#### <a id="c-sk_attach_filter"></a>`sk_attach_filter()`

```c
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
```

attach a socket filter

**Parameters**

- `struct sock_fprog *fprog`: the filter program
- `struct sock *sk`: the socket to use

**Description**

Attach the user's filter code. We first run some sanity checks on
it to make sure it does not explode on us later. If an error
occurs or there is insufficient memory for the filter a negative
errno code is returned. On success the return is zero.


<a id="rst-generic-network-statistics"></a>

### Generic Network Statistics


#### <a id="c-struct-gnet_stats_basic"></a>`struct gnet_stats_basic`

byte/packet throughput statistics

**Definition**

```c
struct gnet_stats_basic {
    __u64 bytes;
    __u32 packets;
};
```

**Members**

- `bytes`: number of seen bytes
- `packets`: number of seen packets

#### <a id="c-struct-gnet_stats_rate_est"></a>`struct gnet_stats_rate_est`

rate estimator

**Definition**

```c
struct gnet_stats_rate_est {
    __u32 bps;
    __u32 pps;
};
```

**Members**

- `bps`: current byte rate
- `pps`: current packet rate

#### <a id="c-struct-gnet_stats_rate_est64"></a>`struct gnet_stats_rate_est64`

rate estimator

**Definition**

```c
struct gnet_stats_rate_est64 {
    __u64 bps;
    __u64 pps;
};
```

**Members**

- `bps`: current byte rate
- `pps`: current packet rate

#### <a id="c-struct-gnet_stats_queue"></a>`struct gnet_stats_queue`

queuing statistics

**Definition**

```c
struct gnet_stats_queue {
    __u32 qlen;
    __u32 backlog;
    __u32 drops;
    __u32 requeues;
    __u32 overlimits;
};
```

**Members**

- `qlen`: queue length
- `backlog`: backlog size of queue
- `drops`: number of dropped packets
- `requeues`: number of requeues
- `overlimits`: number of enqueues over the limit

#### <a id="c-struct-gnet_estimator"></a>`struct gnet_estimator`

rate estimator configuration

**Definition**

```c
struct gnet_estimator {
    signed char     interval;
    unsigned char   ewma_log;
};
```

**Members**

- `interval`: sampling period
- `ewma_log`: the log of measurement window weight



#### <a id="c-gnet_stats_start_copy_compat"></a>`gnet_stats_start_copy_compat()`

```c
int gnet_stats_start_copy_compat(struct sk_buff *skb, int type, int tc_stats_type, int xstats_type, spinlock_t *lock, struct gnet_dump *d, int padattr)
```

start dumping procedure in compatibility mode

**Parameters**

- `struct sk_buff *skb`: socket buffer to put statistics TLVs into
- `int type`: TLV type for top level statistic TLV
- `int tc_stats_type`: TLV type for backward compatibility struct tc_stats TLV
- `int xstats_type`: TLV type for backward compatibility xstats TLV
- `spinlock_t *lock`: statistics lock
- `struct gnet_dump *d`: dumping handle
- `int padattr`: padding attribute

**Description**

Initializes the dumping handle, grabs the statistic lock and appends
an empty TLV header to the socket buffer for use a container for all
other statistic TLVS.

The dumping handle is marked to be in backward compatibility mode telling
all `gnet_stats_copy_XXX()` functions to fill a local copy of struct tc_stats.

Returns 0 on success or -1 if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_start_copy"></a>`gnet_stats_start_copy()`

```c
int gnet_stats_start_copy(struct sk_buff *skb, int type, spinlock_t *lock, struct gnet_dump *d, int padattr)
```

start dumping procedure in compatibility mode

**Parameters**

- `struct sk_buff *skb`: socket buffer to put statistics TLVs into
- `int type`: TLV type for top level statistic TLV
- `spinlock_t *lock`: statistics lock
- `struct gnet_dump *d`: dumping handle
- `int padattr`: padding attribute

**Description**

Initializes the dumping handle, grabs the statistic lock and appends
an empty TLV header to the socket buffer for use a container for all
other statistic TLVS.

Returns 0 on success or -1 if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_copy_basic"></a>`gnet_stats_copy_basic()`

```c
int gnet_stats_copy_basic(struct gnet_dump *d, struct gnet_stats_basic_sync __percpu *cpu, struct gnet_stats_basic_sync *b, bool running)
```

copy basic statistics into statistic TLV

**Parameters**

- `struct gnet_dump *d`: dumping handle
- `struct gnet_stats_basic_sync __percpu *cpu`: copy statistic per cpu
- `struct gnet_stats_basic_sync *b`: basic statistics
- `bool running`: true if **b** represents a running qdisc, thus **b**'s
  internal values might change during basic reads.
  Only used if **cpu** is NULL

**Context**

task; must not be run from IRQ or BH contexts

**Description**

Appends the basic statistics to the top level TLV created by
[`gnet_stats_start_copy()`](#c-gnet_stats_start_copy).

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_copy_basic_hw"></a>`gnet_stats_copy_basic_hw()`

```c
int gnet_stats_copy_basic_hw(struct gnet_dump *d, struct gnet_stats_basic_sync __percpu *cpu, struct gnet_stats_basic_sync *b, bool running)
```

copy basic hw statistics into statistic TLV

**Parameters**

- `struct gnet_dump *d`: dumping handle
- `struct gnet_stats_basic_sync __percpu *cpu`: copy statistic per cpu
- `struct gnet_stats_basic_sync *b`: basic statistics
- `bool running`: true if **b** represents a running qdisc, thus **b**'s
  internal values might change during basic reads.
  Only used if **cpu** is NULL

**Context**

task; must not be run from IRQ or BH contexts

**Description**

Appends the basic statistics to the top level TLV created by
[`gnet_stats_start_copy()`](#c-gnet_stats_start_copy).

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_copy_rate_est"></a>`gnet_stats_copy_rate_est()`

```c
int gnet_stats_copy_rate_est(struct gnet_dump *d, struct net_rate_estimator __rcu **rate_est)
```

copy rate estimator statistics into statistics TLV

**Parameters**

- `struct gnet_dump *d`: dumping handle
- `struct net_rate_estimator __rcu **rate_est`: rate estimator

**Description**

Appends the rate estimator statistics to the top level TLV created by
[`gnet_stats_start_copy()`](#c-gnet_stats_start_copy).

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_copy_queue"></a>`gnet_stats_copy_queue()`

```c
int gnet_stats_copy_queue(struct gnet_dump *d, struct gnet_stats_queue __percpu *cpu_q, struct gnet_stats_queue *q, __u32 qlen)
```

copy queue statistics into statistics TLV

**Parameters**

- `struct gnet_dump *d`: dumping handle
- `struct gnet_stats_queue __percpu *cpu_q`: per cpu queue statistics
- `struct gnet_stats_queue *q`: queue statistics
- `__u32 qlen`: queue length statistics

**Description**

Appends the queue statistics to the top level TLV created by
[`gnet_stats_start_copy()`](#c-gnet_stats_start_copy). Using per cpu queue statistics if
they are available.

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_copy_app"></a>`gnet_stats_copy_app()`

```c
int gnet_stats_copy_app(struct gnet_dump *d, void *st, int len)
```

copy application specific statistics into statistics TLV

**Parameters**

- `struct gnet_dump *d`: dumping handle
- `void *st`: application specific statistics data
- `int len`: length of data

**Description**

Appends the application specific statistics to the top level TLV created by
[`gnet_stats_start_copy()`](#c-gnet_stats_start_copy) and remembers the data for XSTATS if the dumping
handle is in backward compatibility mode.

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.

#### <a id="c-gnet_stats_finish_copy"></a>`gnet_stats_finish_copy()`

```c
int gnet_stats_finish_copy(struct gnet_dump *d)
```

finish dumping procedure

**Parameters**

- `struct gnet_dump *d`: dumping handle

**Description**

Corrects the length of the top level TLV to include all TLVs added
by `gnet_stats_copy_XXX()` calls. Adds the backward compatibility TLVs
if [`gnet_stats_start_copy_compat()`](#c-gnet_stats_start_copy_compat) was used and releases the statistics
lock.

Returns 0 on success or -1 with the statistic lock released
if the room in the socket buffer was not sufficient.



#### <a id="c-gen_new_estimator"></a>`gen_new_estimator()`

```c
int gen_new_estimator(struct gnet_stats_basic_sync *bstats, struct gnet_stats_basic_sync __percpu *cpu_bstats, struct net_rate_estimator __rcu **rate_est, spinlock_t *lock, bool running, struct nlattr *opt)
```

create a new rate estimator

**Parameters**

- `struct gnet_stats_basic_sync *bstats`: basic statistics
- `struct gnet_stats_basic_sync __percpu *cpu_bstats`: bstats per cpu
- `struct net_rate_estimator __rcu **rate_est`: rate estimator statistics
- `spinlock_t *lock`: lock for statistics and control path
- `bool running`: true if **bstats** represents a running qdisc, thus **bstats**'
  internal values might change during basic reads. Only used
  if **bstats_cpu** is NULL
- `struct nlattr *opt`: rate estimator configuration TLV

**Description**

Creates a new rate estimator with `bstats` as source and `rate_est`
as destination. A new timer with the interval specified in the
configuration TLV is created. Upon each interval, the latest statistics
will be read from `bstats` and the estimated rate will be stored in
`rate_est` with the statistics lock grabbed during this period.

Returns 0 on success or a negative error code.

#### <a id="c-gen_kill_estimator"></a>`gen_kill_estimator()`

```c
void gen_kill_estimator(struct net_rate_estimator __rcu **rate_est)
```

remove a rate estimator

**Parameters**

- `struct net_rate_estimator __rcu **rate_est`: rate estimator

**Description**

Removes the rate estimator.

#### <a id="c-gen_replace_estimator"></a>`gen_replace_estimator()`

```c
int gen_replace_estimator(struct gnet_stats_basic_sync *bstats, struct gnet_stats_basic_sync __percpu *cpu_bstats, struct net_rate_estimator __rcu **rate_est, spinlock_t *lock, bool running, struct nlattr *opt)
```

replace rate estimator configuration

**Parameters**

- `struct gnet_stats_basic_sync *bstats`: basic statistics
- `struct gnet_stats_basic_sync __percpu *cpu_bstats`: bstats per cpu
- `struct net_rate_estimator __rcu **rate_est`: rate estimator statistics
- `spinlock_t *lock`: lock for statistics and control path
- `bool running`: true if **bstats** represents a running qdisc, thus **bstats**'
  internal values might change during basic reads. Only used
  if **cpu_bstats** is NULL
- `struct nlattr *opt`: rate estimator configuration TLV

**Description**

Replaces the configuration of a rate estimator by calling
[`gen_kill_estimator()`](#c-gen_kill_estimator) and [`gen_new_estimator()`](#c-gen_new_estimator).

Returns 0 on success or a negative error code.

#### <a id="c-gen_estimator_active"></a>`gen_estimator_active()`

```c
bool gen_estimator_active(struct net_rate_estimator __rcu **rate_est)
```

test if estimator is currently in use

**Parameters**

- `struct net_rate_estimator __rcu **rate_est`: rate estimator

**Description**

Returns true if estimator is active, and false if not.


<a id="rst-sun-rpc-subsystem"></a>

### SUN RPC subsystem


#### <a id="c-xdr_encode_opaque_fixed"></a>`xdr_encode_opaque_fixed()`

```c
__be32 * xdr_encode_opaque_fixed(__be32 *p, const void *ptr, unsigned int nbytes)
```

Encode fixed length opaque data

**Parameters**

- `__be32 *p`: pointer to current position in XDR buffer.
- `const void *ptr`: pointer to data to encode (or NULL)
- `unsigned int nbytes`: size of data.

**Description**

Copy the array of data of length nbytes at ptr to the XDR buffer
at position p, then align to the next 32-bit boundary by padding
with zero bytes (see RFC1832).

**Note**

if ptr is NULL, only the padding is performed.

Returns the updated current XDR buffer position

#### <a id="c-xdr_encode_opaque"></a>`xdr_encode_opaque()`

```c
__be32 * xdr_encode_opaque(__be32 *p, const void *ptr, unsigned int nbytes)
```

Encode variable length opaque data

**Parameters**

- `__be32 *p`: pointer to current position in XDR buffer.
- `const void *ptr`: pointer to data to encode (or NULL)
- `unsigned int nbytes`: size of data.

**Description**

Returns the updated current XDR buffer position

#### <a id="c-xdr_terminate_string"></a>`xdr_terminate_string()`

```c
void xdr_terminate_string(const struct xdr_buf *buf, const u32 len)
```

'\0'-terminate a string residing in an xdr_buf

**Parameters**

- `const struct xdr_buf *buf`: XDR buffer where string resides
- `const u32 len`: length of string, in bytes

#### <a id="c-xdr_buf_to_bvec"></a>`xdr_buf_to_bvec()`

```c
unsigned int xdr_buf_to_bvec(struct bio_vec *bvec, unsigned int bvec_size, const struct xdr_buf *xdr)
```

Copy components of an xdr_buf into a bio_vec array

**Parameters**

- `struct bio_vec *bvec`: bio_vec array to populate
- `unsigned int bvec_size`: element count of **bio_vec**
- `const struct xdr_buf *xdr`: xdr_buf to be copied

**Description**

Returns the number of entries consumed in **bvec**.

#### <a id="c-xdr_inline_pages"></a>`xdr_inline_pages()`

```c
void xdr_inline_pages(struct xdr_buf *xdr, unsigned int offset, struct page **pages, unsigned int base, unsigned int len)
```

Prepare receive buffer for a large reply

**Parameters**

- `struct xdr_buf *xdr`: xdr_buf into which reply will be placed
- `unsigned int offset`: expected offset where data payload will start, in bytes
- `struct page **pages`: vector of struct page pointers
- `unsigned int base`: offset in first page where receive should start, in bytes
- `unsigned int len`: expected size of the upper layer data payload, in bytes

#### <a id="c-_copy_from_pages"></a>`_copy_from_pages()`

```c
void _copy_from_pages(char *p, struct page **pages, size_t pgbase, size_t len)
```

**Parameters**

- `char *p`: pointer to destination
- `struct page **pages`: array of pages
- `size_t pgbase`: offset of source data
- `size_t len`: length

**Description**

Copies data into an arbitrary memory location from an array of pages
The copy is assumed to be non-overlapping.

#### <a id="c-xdr_stream_pos"></a>`xdr_stream_pos()`

```c
unsigned int xdr_stream_pos(const struct xdr_stream *xdr)
```

Return the current offset from the start of the xdr_stream

**Parameters**

- `const struct xdr_stream *xdr`: pointer to struct xdr_stream

#### <a id="c-xdr_page_pos"></a>`xdr_page_pos()`

```c
unsigned int xdr_page_pos(const struct xdr_stream *xdr)
```

Return the current offset from the start of the xdr pages

**Parameters**

- `const struct xdr_stream *xdr`: pointer to struct xdr_stream

#### <a id="c-xdr_init_encode"></a>`xdr_init_encode()`

```c
void xdr_init_encode(struct xdr_stream *xdr, struct xdr_buf *buf, __be32 *p, struct rpc_rqst *rqst)
```

Initialize a struct xdr_stream for sending data.

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `struct xdr_buf *buf`: pointer to XDR buffer in which to encode data
- `__be32 *p`: current pointer inside XDR buffer
- `struct rpc_rqst *rqst`: pointer to controlling rpc_rqst, for debugging

**Note**

- at the moment the RPC client only passes the length of our

  scratch buffer in the xdr_buf's header kvec. Previously this
  meant we needed to call `xdr_adjust_iovec()` after encoding the
  data. With the new scheme, the xdr_stream manages the details
  of the buffer length, and takes care of adjusting the kvec
  length for us.

#### <a id="c-xdr_init_encode_pages"></a>`xdr_init_encode_pages()`

```c
void xdr_init_encode_pages(struct xdr_stream *xdr, struct xdr_buf *buf)
```

Initialize an xdr_stream for encoding into pages

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `struct xdr_buf *buf`: pointer to XDR buffer into which to encode data

#### <a id="c-__xdr_commit_encode"></a>`__xdr_commit_encode()`

```c
void __xdr_commit_encode(struct xdr_stream *xdr)
```

Ensure all data is written to buffer

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream

**Description**

We handle encoding across page boundaries by giving the caller a
temporary location to write to, then later copying the data into
place; xdr_commit_encode does that copying.

Normally the caller doesn't need to call this directly, as the
following xdr_reserve_space will do it.  But an explicit call may be
required at the end of encoding, or any other time when the xdr_buf
data might be read.

#### <a id="c-xdr_reserve_space"></a>`xdr_reserve_space()`

```c
__be32 * xdr_reserve_space(struct xdr_stream *xdr, size_t nbytes)
```

Reserve buffer space for sending

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `size_t nbytes`: number of bytes to reserve

**Description**

Checks that we have enough buffer space to encode 'nbytes' more
bytes of data. If so, update the total xdr_buf length, and
adjust the length of the current kvec.

The returned pointer is valid only until the next call to
[`xdr_reserve_space()`](#c-xdr_reserve_space) or `xdr_commit_encode()` on **xdr**. The current
implementation of this API guarantees that space reserved for a
four-byte data item remains valid until **xdr** is destroyed, but
that might not always be true in the future.

#### <a id="c-xdr_reserve_space_vec"></a>`xdr_reserve_space_vec()`

```c
int xdr_reserve_space_vec(struct xdr_stream *xdr, size_t nbytes)
```

Reserves a large amount of buffer space for sending

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `size_t nbytes`: number of bytes to reserve

**Description**

The size argument passed to [`xdr_reserve_space()`](#c-xdr_reserve_space) is determined based
on the number of bytes remaining in the current page to avoid
invalidating iov_base pointers when `xdr_commit_encode()` is called.

- Return values:
  `0`: success
  `-EMSGSIZE`: not enough space is available in **xdr**

#### <a id="c-xdr_truncate_encode"></a>`xdr_truncate_encode()`

```c
void xdr_truncate_encode(struct xdr_stream *xdr, size_t len)
```

truncate an encode buffer

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `size_t len`: new length of buffer

**Description**

Truncates the xdr stream, so that xdr->buf->len == len,
and xdr->p points at offset len from the start of the buffer, and
head, tail, and page lengths are adjusted to correspond.

If this means moving xdr->p to a different buffer, we assume that
the end pointer should be set to the end of the current page,
except in the case of the head buffer when we assume the head
buffer's current length represents the end of the available buffer.

This is *not* safe to use on a buffer that already has inlined page
cache pages (as in a zero-copy server read reply), except for the
simple case of truncating from one position in the tail to another.

#### <a id="c-xdr_truncate_decode"></a>`xdr_truncate_decode()`

```c
void xdr_truncate_decode(struct xdr_stream *xdr, size_t len)
```

Truncate a decoding stream

**Parameters**

- `struct xdr_stream *xdr`: pointer to struct xdr_stream
- `size_t len`: Number of bytes to remove

#### <a id="c-xdr_restrict_buflen"></a>`xdr_restrict_buflen()`

```c
int xdr_restrict_buflen(struct xdr_stream *xdr, int newbuflen)
```

decrease available buffer space

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `int newbuflen`: new maximum number of bytes available

**Description**

Adjust our idea of how much space is available in the buffer.
If we've already used too much space in the buffer, returns -1.
If the available space is already smaller than newbuflen, returns 0
and does nothing.  Otherwise, adjusts xdr->buf->buflen to newbuflen
and ensures xdr->end is set at most offset newbuflen from the start
of the buffer.

#### <a id="c-xdr_write_pages"></a>`xdr_write_pages()`

```c
void xdr_write_pages(struct xdr_stream *xdr, struct page **pages, unsigned int base, unsigned int len)
```

Insert a list of pages into an XDR buffer for sending

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `struct page **pages`: array of pages to insert
- `unsigned int base`: starting offset of first data byte in **pages**
- `unsigned int len`: number of data bytes in **pages** to insert

**Description**

After the **pages** are added, the tail iovec is instantiated pointing to
end of the head buffer, and the stream is set up to encode subsequent
items into the tail.

#### <a id="c-xdr_init_decode"></a>`xdr_init_decode()`

```c
void xdr_init_decode(struct xdr_stream *xdr, struct xdr_buf *buf, __be32 *p, struct rpc_rqst *rqst)
```

Initialize an xdr_stream for decoding data.

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `struct xdr_buf *buf`: pointer to XDR buffer from which to decode data
- `__be32 *p`: current pointer inside XDR buffer
- `struct rpc_rqst *rqst`: pointer to controlling rpc_rqst, for debugging

#### <a id="c-xdr_init_decode_pages"></a>`xdr_init_decode_pages()`

```c
void xdr_init_decode_pages(struct xdr_stream *xdr, struct xdr_buf *buf, struct page **pages, unsigned int len)
```

Initialize an xdr_stream for decoding into pages

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `struct xdr_buf *buf`: pointer to XDR buffer from which to decode data
- `struct page **pages`: list of pages to decode into
- `unsigned int len`: length in bytes of buffer in pages

#### <a id="c-xdr_finish_decode"></a>`xdr_finish_decode()`

```c
void xdr_finish_decode(struct xdr_stream *xdr)
```

Clean up the xdr_stream after decoding data.

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct

#### <a id="c-xdr_inline_decode"></a>`xdr_inline_decode()`

```c
__be32 * xdr_inline_decode(struct xdr_stream *xdr, size_t nbytes)
```

Retrieve XDR data to decode

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `size_t nbytes`: number of bytes of data to decode

**Description**

Check if the input buffer is long enough to enable us to decode
'nbytes' more bytes of data starting at the current position.
If so return the current pointer, then update the current
pointer position.

#### <a id="c-xdr_read_pages"></a>`xdr_read_pages()`

```c
unsigned int xdr_read_pages(struct xdr_stream *xdr, unsigned int len)
```

align page-based XDR data to current pointer position

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `unsigned int len`: number of bytes of page data

**Description**

Moves data beyond the current pointer position from the XDR head\[\] buffer
into the page list. Any data that lies beyond current position + **len**
bytes is moved into the XDR tail\[\]. The xdr_stream current position is
then advanced past that data to align to the next XDR object in the tail.

Returns the number of XDR encoded bytes now contained in the pages

#### <a id="c-xdr_set_pagelen"></a>`xdr_set_pagelen()`

```c
void xdr_set_pagelen(struct xdr_stream *xdr, unsigned int len)
```

Sets the length of the XDR pages

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `unsigned int len`: new length of the XDR page data

**Description**

Either grows or shrinks the length of the xdr pages by setting pagelen to
**len** bytes. When shrinking, any extra data is moved into buf->tail, whereas
when growing any data beyond the current pointer is moved into the tail.

Returns True if the operation was successful, and False otherwise.

#### <a id="c-xdr_enter_page"></a>`xdr_enter_page()`

```c
void xdr_enter_page(struct xdr_stream *xdr, unsigned int len)
```

decode data from the XDR page

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream struct
- `unsigned int len`: number of bytes of page data

**Description**

Moves data beyond the current pointer position from the XDR head\[\] buffer
into the page list. Any data that lies beyond current position + "len"
bytes is moved into the XDR tail\[\]. The current pointer is then
repositioned at the beginning of the first XDR page.

#### <a id="c-xdr_buf_subsegment"></a>`xdr_buf_subsegment()`

```c
int xdr_buf_subsegment(const struct xdr_buf *buf, struct xdr_buf *subbuf, unsigned int base, unsigned int len)
```

set subbuf to a portion of buf

**Parameters**

- `const struct xdr_buf *buf`: an xdr buffer
- `struct xdr_buf *subbuf`: the result buffer
- `unsigned int base`: beginning of range in bytes
- `unsigned int len`: length of range in bytes

**Description**

sets **subbuf** to an xdr buffer representing the portion of **buf** of
length **len** starting at offset **base**.

**buf** and **subbuf** may be pointers to the same struct xdr_buf.

Returns -1 if base or length are out of bounds.

#### <a id="c-xdr_stream_subsegment"></a>`xdr_stream_subsegment()`

```c
bool xdr_stream_subsegment(struct xdr_stream *xdr, struct xdr_buf *subbuf, unsigned int nbytes)
```

set **subbuf** to a portion of **xdr**

**Parameters**

- `struct xdr_stream *xdr`: an xdr_stream set up for decoding
- `struct xdr_buf *subbuf`: the result buffer
- `unsigned int nbytes`: length of **xdr** to extract, in bytes

**Description**

Sets up **subbuf** to represent a portion of **xdr**. The portion
starts at the current offset in **xdr**, and extends for a length
of **nbytes**. If this is successful, **xdr** is advanced to the next
XDR data item following that portion.

- Return values:
  `true`: **subbuf** has been initialized, and **xdr** has been advanced.
  `false`: a bounds error has occurred

#### <a id="c-xdr_stream_move_subsegment"></a>`xdr_stream_move_subsegment()`

```c
unsigned int xdr_stream_move_subsegment(struct xdr_stream *xdr, unsigned int offset, unsigned int target, unsigned int length)
```

Move part of a stream to another position

**Parameters**

- `struct xdr_stream *xdr`: the source xdr_stream
- `unsigned int offset`: the source offset of the segment
- `unsigned int target`: the target offset of the segment
- `unsigned int length`: the number of bytes to move

**Description**

Moves **length** bytes from **offset** to **target** in the xdr_stream, overwriting
anything in its space. Returns the number of bytes in the segment.

#### <a id="c-xdr_stream_zero"></a>`xdr_stream_zero()`

```c
unsigned int xdr_stream_zero(struct xdr_stream *xdr, unsigned int offset, unsigned int length)
```

zero out a portion of an xdr_stream

**Parameters**

- `struct xdr_stream *xdr`: an xdr_stream to zero out
- `unsigned int offset`: the starting point in the stream
- `unsigned int length`: the number of bytes to zero

#### <a id="c-xdr_buf_trim"></a>`xdr_buf_trim()`

```c
void xdr_buf_trim(struct xdr_buf *buf, unsigned int len)
```

lop at most "len" bytes off the end of "buf"

**Parameters**

- `struct xdr_buf *buf`: buf to be trimmed
- `unsigned int len`: number of bytes to reduce "buf" by

**Description**

Trim an xdr_buf by the given number of bytes by fixing up the lengths. Note
that it's possible that we'll trim less than that amount if the xdr_buf is
too small, or if (for instance) it's all in the head and the parser has
already read too far into it.

#### <a id="c-xdr_stream_decode_string_dup"></a>`xdr_stream_decode_string_dup()`

```c
ssize_t xdr_stream_decode_string_dup(struct xdr_stream *xdr, char **str, size_t maxlen, gfp_t gfp_flags)
```

Decode and duplicate variable length string

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `char **str`: location to store pointer to string
- `size_t maxlen`: maximum acceptable string length
- `gfp_t gfp_flags`: GFP mask to use

**Description**

- Return values:
  On success, returns length of NUL-terminated string stored in **\*ptr**
  `-EBADMSG` on XDR buffer overflow
  `-EMSGSIZE` if the size of the string would exceed **maxlen**
  `-ENOMEM` on memory allocation failure

#### <a id="c-xdr_stream_decode_opaque_auth"></a>`xdr_stream_decode_opaque_auth()`

```c
ssize_t xdr_stream_decode_opaque_auth(struct xdr_stream *xdr, u32 *flavor, void **body, unsigned int *body_len)
```

Decode struct opaque_auth (RFC5531 S8.2)

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `u32 *flavor`: location to store decoded flavor
- `void **body`: location to store decode body
- `unsigned int *body_len`: location to store length of decoded body

**Description**

- Return values:
  On success, returns the number of buffer bytes consumed
  `-EBADMSG` on XDR buffer overflow
  `-EMSGSIZE` if the decoded size of the body field exceeds 400 octets

#### <a id="c-xdr_stream_encode_opaque_auth"></a>`xdr_stream_encode_opaque_auth()`

```c
ssize_t xdr_stream_encode_opaque_auth(struct xdr_stream *xdr, u32 flavor, void *body, unsigned int body_len)
```

Encode struct opaque_auth (RFC5531 S8.2)

**Parameters**

- `struct xdr_stream *xdr`: pointer to xdr_stream
- `u32 flavor`: verifier flavor to encode
- `void *body`: content of body to encode
- `unsigned int body_len`: length of body to encode

**Description**

- Return values:
  On success, returns length in bytes of XDR buffer consumed
  `-EBADMSG` on XDR buffer overflow
  `-EMSGSIZE` if the size of **body** exceeds 400 octets



#### <a id="c-svc_reg_xprt_class"></a>`svc_reg_xprt_class()`

```c
int svc_reg_xprt_class(struct svc_xprt_class *xcl)
```

Register a server-side RPC transport class

**Parameters**

- `struct svc_xprt_class *xcl`: New transport class to be registered

**Description**

Returns zero on success; otherwise a negative errno is returned.

#### <a id="c-svc_unreg_xprt_class"></a>`svc_unreg_xprt_class()`

```c
void svc_unreg_xprt_class(struct svc_xprt_class *xcl)
```

Unregister a server-side RPC transport class

**Parameters**

- `struct svc_xprt_class *xcl`: Transport class to be unregistered

#### <a id="c-svc_xprt_deferred_close"></a>`svc_xprt_deferred_close()`

```c
void svc_xprt_deferred_close(struct svc_xprt *xprt)
```

Close a transport

**Parameters**

- `struct svc_xprt *xprt`: transport instance

**Description**

Used in contexts that need to defer the work of shutting down
the transport to an nfsd thread.

#### <a id="c-svc_xprt_received"></a>`svc_xprt_received()`

```c
void svc_xprt_received(struct svc_xprt *xprt)
```

start next receiver thread

**Parameters**

- `struct svc_xprt *xprt`: controlling transport

**Description**

The caller must hold the XPT_BUSY bit and must
not thereafter touch transport data.

**Note**

XPT_DATA only gets cleared when a read-attempt finds no (or
insufficient) data.

#### <a id="c-svc_xprt_create_from_sa"></a>`svc_xprt_create_from_sa()`

```c
int svc_xprt_create_from_sa(struct svc_serv *serv, const char *xprt_name, struct net *net, struct sockaddr *sap, int flags, const struct cred *cred)
```

Add a new listener to **serv** from socket address

**Parameters**

- `struct svc_serv *serv`: target RPC service
- `const char *xprt_name`: transport class name
- `struct net *net`: network namespace
- `struct sockaddr *sap`: socket address pointer
- `int flags`: SVC_SOCK flags
- `const struct cred *cred`: credential to bind to this transport

**Description**

Return local xprt port on success or `-EPROTONOSUPPORT` on failure

#### <a id="c-svc_xprt_create"></a>`svc_xprt_create()`

```c
int svc_xprt_create(struct svc_serv *serv, const char *xprt_name, struct net *net, const int family, const unsigned short port, int flags, const struct cred *cred)
```

Add a new listener to **serv**

**Parameters**

- `struct svc_serv *serv`: target RPC service
- `const char *xprt_name`: transport class name
- `struct net *net`: network namespace
- `const int family`: network address family
- `const unsigned short port`: listener port
- `int flags`: SVC_SOCK flags
- `const struct cred *cred`: credential to bind to this transport

**Description**

Return local xprt port on success or `-EPROTONOSUPPORT` on failure

#### <a id="c-svc_print_addr"></a>`svc_print_addr()`

```c
char * svc_print_addr(struct svc_rqst *rqstp, char *buf, size_t len)
```

Format rq_addr field for printing

**Parameters**

- `struct svc_rqst *rqstp`: svc_rqst struct containing address to print
- `char *buf`: target buffer for formatted address
- `size_t len`: length of target buffer

#### <a id="c-svc_xprt_enqueue"></a>`svc_xprt_enqueue()`

```c
void svc_xprt_enqueue(struct svc_xprt *xprt)
```

Queue a transport on an idle nfsd thread

**Parameters**

- `struct svc_xprt *xprt`: transport with data pending

#### <a id="c-svc_reserve"></a>`svc_reserve()`

```c
void svc_reserve(struct svc_rqst *rqstp, int space)
```

change the space reserved for the reply to a request.

**Parameters**

- `struct svc_rqst *rqstp`: The request in question
- `int space`: new max space to reserve

**Description**

Each request reserves some space on the output queue of the transport
to make sure the reply fits.  This function reduces that reserved
space to be the amount of space used already, plus **space**.

#### <a id="c-svc_wake_up"></a>`svc_wake_up()`

```c
void svc_wake_up(struct svc_serv *serv)
```

Wake up a service thread for non-transport work

**Parameters**

- `struct svc_serv *serv`: RPC service

**Description**

Some svc_serv's will have occasional work to do, even when a xprt is not
waiting to be serviced. This function is there to "kick" a task in one of
those services so that it can wake up and do that work. Note that we only
bother with pool 0 as we don't need to wake up more than one thread for
this purpose.

#### <a id="c-svc_recv"></a>`svc_recv()`

```c
int svc_recv(struct svc_rqst *rqstp, long timeo)
```

Receive and process the next request on any transport

**Parameters**

- `struct svc_rqst *rqstp`: an idle RPC service thread
- `long timeo`: timeout (in jiffies) (0 means infinite timeout)

**Description**

This code is carefully organised not to touch any cachelines in
the shared svc_serv structure, only cachelines in the local
svc_pool.

If the timeout is 0, then the sleep will never time out.

- Returns -ETIMEDOUT if idle for an extended period

  -EBUSY if there is more work to do than available threads
  0 otherwise.

#### <a id="c-svc_xprt_close"></a>`svc_xprt_close()`

```c
void svc_xprt_close(struct svc_xprt *xprt)
```

Close a client connection

**Parameters**

- `struct svc_xprt *xprt`: transport to disconnect

#### <a id="c-svc_xprt_destroy_all"></a>`svc_xprt_destroy_all()`

```c
void svc_xprt_destroy_all(struct svc_serv *serv, struct net *net, bool unregister)
```

Destroy transports associated with **serv**

**Parameters**

- `struct svc_serv *serv`: RPC service to be shut down
- `struct net *net`: target network namespace
- `bool unregister`: true if it is OK to unregister the destroyed xprts

**Description**

Server threads may still be running (especially in the case where the
service is still running in other network namespaces).

So we shut down sockets the same way we would on a running server, by
setting XPT_CLOSE, enqueuing, and letting a thread pick it up to do
the close.  In the case there are no such other threads,
threads running, `svc_clean_up_xprts()` does a simple version of a
server's main event loop, and in the case where there are other
threads, we may need to wait a little while and then check again to
see if they're done.

#### <a id="c-svc_find_listener"></a>`svc_find_listener()`

```c
struct svc_xprt * svc_find_listener(struct svc_serv *serv, const char *xcl_name, struct net *net, const struct sockaddr *sa)
```

find an RPC transport instance

**Parameters**

- `struct svc_serv *serv`: pointer to svc_serv to search
- `const char *xcl_name`: C string containing transport's class name
- `struct net *net`: owner net pointer
- `const struct sockaddr *sa`: sockaddr containing address

**Description**

Return the transport instance pointer for the endpoint accepting
connections/peer traffic from the specified transport class,
and matching sockaddr.

#### <a id="c-svc_find_xprt"></a>`svc_find_xprt()`

```c
struct svc_xprt * svc_find_xprt(struct svc_serv *serv, const char *xcl_name, struct net *net, const sa_family_t af, const unsigned short port)
```

find an RPC transport instance

**Parameters**

- `struct svc_serv *serv`: pointer to svc_serv to search
- `const char *xcl_name`: C string containing transport's class name
- `struct net *net`: owner net pointer
- `const sa_family_t af`: Address family of transport's local address
- `const unsigned short port`: transport's IP port number

**Description**

Return the transport instance pointer for the endpoint accepting
connections/peer traffic from the specified transport class,
address family and port.

Specifying 0 for the address family or port is effectively a
wild-card, and will result in matching the first transport in the
service's list that has a matching class name.

#### <a id="c-svc_xprt_names"></a>`svc_xprt_names()`

```c
int svc_xprt_names(struct svc_serv *serv, char *buf, const int buflen)
```

format a buffer with a list of transport names

**Parameters**

- `struct svc_serv *serv`: pointer to an RPC service
- `char *buf`: pointer to a buffer to be filled in
- `const int buflen`: length of buffer to be filled in

**Description**

Fills in **buf** with a string containing a list of transport names,
each name terminated with '\n'.

Returns positive length of the filled-in string on success; otherwise
a negative errno value is returned if an error occurs.



#### <a id="c-xprt_register_transport"></a>`xprt_register_transport()`

```c
int xprt_register_transport(struct xprt_class *transport)
```

register a transport implementation

**Parameters**

- `struct xprt_class *transport`: transport to register

**Description**

If a transport implementation is loaded as a kernel module, it can
call this interface to make itself known to the RPC client.

**Return**

0:           transport successfully registered
-EEXIST:     transport already registered
-EINVAL:     transport module being unloaded

#### <a id="c-xprt_unregister_transport"></a>`xprt_unregister_transport()`

```c
int xprt_unregister_transport(struct xprt_class *transport)
```

unregister a transport implementation

**Parameters**

- `struct xprt_class *transport`: transport to unregister

**Return**

0:           transport successfully unregistered
-ENOENT:     transport never registered

#### <a id="c-xprt_find_transport_ident"></a>`xprt_find_transport_ident()`

```c
int xprt_find_transport_ident(const char *netid)
```

convert a netid into a transport identifier

**Parameters**

- `const char *netid`: transport to load

**Return**

\> 0:         transport identifier
-ENOENT:     transport module not available

#### <a id="c-xprt_reserve_xprt"></a>`xprt_reserve_xprt()`

```c
int xprt_reserve_xprt(struct rpc_xprt *xprt, struct rpc_task *task)
```

serialize write access to transports

**Parameters**

- `struct rpc_xprt *xprt`: pointer to the target transport
- `struct rpc_task *task`: task that is requesting access to the transport

**Description**

This prevents mixing the payload of separate requests, and prevents
transport connects from colliding with writes.  No congestion control
is provided.

#### <a id="c-xprt_release_xprt"></a>`xprt_release_xprt()`

```c
void xprt_release_xprt(struct rpc_xprt *xprt, struct rpc_task *task)
```

allow other requests to use a transport

**Parameters**

- `struct rpc_xprt *xprt`: transport with other tasks potentially waiting
- `struct rpc_task *task`: task that is releasing access to the transport

**Description**

Note that "task" can be NULL.  No congestion control is provided.

#### <a id="c-xprt_release_xprt_cong"></a>`xprt_release_xprt_cong()`

```c
void xprt_release_xprt_cong(struct rpc_xprt *xprt, struct rpc_task *task)
```

allow other requests to use a transport

**Parameters**

- `struct rpc_xprt *xprt`: transport with other tasks potentially waiting
- `struct rpc_task *task`: task that is releasing access to the transport

**Description**

Note that "task" can be NULL.  Another task is awoken to use the
transport if the transport's congestion window allows it.

#### <a id="c-xprt_request_get_cong"></a>`xprt_request_get_cong()`

```c
bool xprt_request_get_cong(struct rpc_xprt *xprt, struct rpc_rqst *req)
```

Request congestion control credits

**Parameters**

- `struct rpc_xprt *xprt`: pointer to transport
- `struct rpc_rqst *req`: pointer to RPC request

**Description**

Useful for transports that require congestion control.

#### <a id="c-xprt_release_rqst_cong"></a>`xprt_release_rqst_cong()`

```c
void xprt_release_rqst_cong(struct rpc_task *task)
```

housekeeping when request is complete

**Parameters**

- `struct rpc_task *task`: RPC request that recently completed

**Description**

Useful for transports that require congestion control.

#### <a id="c-xprt_adjust_cwnd"></a>`xprt_adjust_cwnd()`

```c
void xprt_adjust_cwnd(struct rpc_xprt *xprt, struct rpc_task *task, int result)
```

adjust transport congestion window

**Parameters**

- `struct rpc_xprt *xprt`: pointer to xprt
- `struct rpc_task *task`: recently completed RPC request used to adjust window
- `int result`: result code of completed RPC request

**Description**

The transport code maintains an estimate on the maximum number of out-
standing RPC requests, using a smoothed version of the congestion
avoidance implemented in 44BSD. This is basically the Van Jacobson
congestion algorithm: If a retransmit occurs, the congestion window is
halved; otherwise, it is incremented by 1/cwnd when

- a reply is received and
- a full number of requests are outstanding and
- the congestion window hasn't been updated recently.

#### <a id="c-xprt_wake_pending_tasks"></a>`xprt_wake_pending_tasks()`

```c
void xprt_wake_pending_tasks(struct rpc_xprt *xprt, int status)
```

wake all tasks on a transport's pending queue

**Parameters**

- `struct rpc_xprt *xprt`: transport with waiting tasks
- `int status`: result code to plant in each task before waking it

#### <a id="c-xprt_wait_for_buffer_space"></a>`xprt_wait_for_buffer_space()`

```c
void xprt_wait_for_buffer_space(struct rpc_xprt *xprt)
```

wait for transport output buffer to clear

**Parameters**

- `struct rpc_xprt *xprt`: transport

**Description**

Note that we only set the timer for the case of `RPC_IS_SOFT()`, since
we don't in general want to force a socket disconnection due to
an incomplete RPC call transmission.

#### <a id="c-xprt_write_space"></a>`xprt_write_space()`

```c
bool xprt_write_space(struct rpc_xprt *xprt)
```

wake the task waiting for transport output buffer space

**Parameters**

- `struct rpc_xprt *xprt`: transport with waiting tasks

**Description**

Can be called in a soft IRQ context, so xprt_write_space never sleeps.

#### <a id="c-xprt_disconnect_done"></a>`xprt_disconnect_done()`

```c
void xprt_disconnect_done(struct rpc_xprt *xprt)
```

mark a transport as disconnected

**Parameters**

- `struct rpc_xprt *xprt`: transport to flag for disconnect

#### <a id="c-xprt_force_disconnect"></a>`xprt_force_disconnect()`

```c
void xprt_force_disconnect(struct rpc_xprt *xprt)
```

force a transport to disconnect

**Parameters**

- `struct rpc_xprt *xprt`: transport to disconnect

#### <a id="c-xprt_reconnect_delay"></a>`xprt_reconnect_delay()`

```c
unsigned long xprt_reconnect_delay(const struct rpc_xprt *xprt)
```

compute the wait before scheduling a connect

**Parameters**

- `const struct rpc_xprt *xprt`: transport instance

#### <a id="c-xprt_reconnect_backoff"></a>`xprt_reconnect_backoff()`

```c
void xprt_reconnect_backoff(struct rpc_xprt *xprt, unsigned long init_to)
```

compute the new re-establish timeout

**Parameters**

- `struct rpc_xprt *xprt`: transport instance
- `unsigned long init_to`: initial reestablish timeout

#### <a id="c-xprt_lookup_rqst"></a>`xprt_lookup_rqst()`

```c
struct rpc_rqst * xprt_lookup_rqst(struct rpc_xprt *xprt, __be32 xid)
```

find an RPC request corresponding to an XID

**Parameters**

- `struct rpc_xprt *xprt`: transport on which the original request was transmitted
- `__be32 xid`: RPC XID of incoming reply

**Description**

Caller holds xprt->queue_lock.

#### <a id="c-xprt_pin_rqst"></a>`xprt_pin_rqst()`

```c
void xprt_pin_rqst(struct rpc_rqst *req)
```

Pin a request on the transport receive list

**Parameters**

- `struct rpc_rqst *req`: Request to pin

**Description**

Caller must ensure this is atomic with the call to [`xprt_lookup_rqst()`](#c-xprt_lookup_rqst)
so should be holding xprt->queue_lock.

#### <a id="c-xprt_unpin_rqst"></a>`xprt_unpin_rqst()`

```c
void xprt_unpin_rqst(struct rpc_rqst *req)
```

Unpin a request on the transport receive list

**Parameters**

- `struct rpc_rqst *req`: Request to pin

**Description**

Caller should be holding xprt->queue_lock.

#### <a id="c-xprt_update_rtt"></a>`xprt_update_rtt()`

```c
void xprt_update_rtt(struct rpc_task *task)
```

Update RPC RTT statistics

**Parameters**

- `struct rpc_task *task`: RPC request that recently completed

**Description**

Caller holds xprt->queue_lock.

#### <a id="c-xprt_complete_rqst"></a>`xprt_complete_rqst()`

```c
void xprt_complete_rqst(struct rpc_task *task, int copied)
```

called when reply processing is complete

**Parameters**

- `struct rpc_task *task`: RPC request that recently completed
- `int copied`: actual number of bytes received from the transport

**Description**

Caller holds xprt->queue_lock.

#### <a id="c-xprt_wait_for_reply_request_def"></a>`xprt_wait_for_reply_request_def()`

```c
void xprt_wait_for_reply_request_def(struct rpc_task *task)
```

wait for reply

**Parameters**

- `struct rpc_task *task`: pointer to rpc_task

**Description**

Set a request's retransmit timeout based on the transport's
default timeout parameters.  Used by transports that don't adjust
the retransmit timeout based on round-trip time estimation,
and put the task to sleep on the pending queue.

#### <a id="c-xprt_wait_for_reply_request_rtt"></a>`xprt_wait_for_reply_request_rtt()`

```c
void xprt_wait_for_reply_request_rtt(struct rpc_task *task)
```

wait for reply using RTT estimator

**Parameters**

- `struct rpc_task *task`: pointer to rpc_task

**Description**

Set a request's retransmit timeout using the RTT estimator,
and put the task to sleep on the pending queue.

#### <a id="c-xprt_get"></a>`xprt_get()`

```c
struct rpc_xprt * xprt_get(struct rpc_xprt *xprt)
```

return a reference to an RPC transport.

**Parameters**

- `struct rpc_xprt *xprt`: pointer to the transport

#### <a id="c-xprt_put"></a>`xprt_put()`

```c
void xprt_put(struct rpc_xprt *xprt)
```

release a reference to an RPC transport.

**Parameters**

- `struct rpc_xprt *xprt`: pointer to the transport



#### <a id="c-rpc_wake_up"></a>`rpc_wake_up()`

```c
void rpc_wake_up(struct rpc_wait_queue *queue)
```

wake up all rpc_tasks

**Parameters**

- `struct rpc_wait_queue *queue`: rpc_wait_queue on which the tasks are sleeping

**Description**

Grabs queue->lock

#### <a id="c-rpc_wake_up_status"></a>`rpc_wake_up_status()`

```c
void rpc_wake_up_status(struct rpc_wait_queue *queue, int status)
```

wake up all rpc_tasks and set their status value.

**Parameters**

- `struct rpc_wait_queue *queue`: rpc_wait_queue on which the tasks are sleeping
- `int status`: status value to set

**Description**

Grabs queue->lock






#### <a id="c-rpc_alloc_iostats"></a>`rpc_alloc_iostats()`

```c
struct rpc_iostats * rpc_alloc_iostats(struct rpc_clnt *clnt)
```

allocate an rpc_iostats structure

**Parameters**

- `struct rpc_clnt *clnt`: RPC program, version, and xprt

#### <a id="c-rpc_free_iostats"></a>`rpc_free_iostats()`

```c
void rpc_free_iostats(struct rpc_iostats *stats)
```

release an rpc_iostats structure

**Parameters**

- `struct rpc_iostats *stats`: doomed rpc_iostats structure

#### <a id="c-rpc_count_iostats_metrics"></a>`rpc_count_iostats_metrics()`

```c
void rpc_count_iostats_metrics(const struct rpc_task *task, struct rpc_iostats *op_metrics)
```

tally up per-task stats

**Parameters**

- `const struct rpc_task *task`: completed rpc_task
- `struct rpc_iostats *op_metrics`: stat structure for OP that will accumulate stats from **task**

#### <a id="c-rpc_count_iostats"></a>`rpc_count_iostats()`

```c
void rpc_count_iostats(const struct rpc_task *task, struct rpc_iostats *stats)
```

tally up per-task stats

**Parameters**

- `const struct rpc_task *task`: completed rpc_task
- `struct rpc_iostats *stats`: array of stat structures

**Description**

Uses the statidx from **task**



#### <a id="c-rpc_queue_upcall"></a>`rpc_queue_upcall()`

```c
int rpc_queue_upcall(struct rpc_pipe *pipe, struct rpc_pipe_msg *msg)
```

queue an upcall message to userspace

**Parameters**

- `struct rpc_pipe *pipe`: upcall pipe on which to queue given message
- `struct rpc_pipe_msg *msg`: message to queue

**Description**

Call with an **inode** created by `rpc_mkpipe()` to queue an upcall.
A userspace process may then later read the upcall by performing a
read on an open file for this inode.  It is up to the caller to
initialize the fields of **msg** (other than **msg->list**) appropriately.

#### <a id="c-rpc_mkpipe_dentry"></a>`rpc_mkpipe_dentry()`

```c
int rpc_mkpipe_dentry(struct dentry *parent, const char *name, void *private, struct rpc_pipe *pipe)
```

make an rpc_pipefs file for kernel\<->userspace communication

**Parameters**

- `struct dentry *parent`: dentry of directory to create new "pipe" in
- `const char *name`: name of pipe
- `void *private`: private data to associate with the pipe, for the caller's use
- `struct rpc_pipe *pipe`: `rpc_pipe` containing input parameters

**Description**

Data is made available for userspace to read by calls to
[`rpc_queue_upcall()`](#c-rpc_queue_upcall).  The actual reads will result in calls to
**ops->upcall**, which will be called with the file pointer,
message, and userspace buffer to copy to.

Writes can come at any time, and do not necessarily have to be
responses to upcalls.  They will result in calls to **msg->downcall**.

The **private** argument passed here will be available to all these methods
from the file pointer, via RPC_I(file_inode(file))->private.

#### <a id="c-rpc_unlink"></a>`rpc_unlink()`

```c
void rpc_unlink(struct rpc_pipe *pipe)
```

remove a pipe

**Parameters**

- `struct rpc_pipe *pipe`: the pipe to be removed

**Description**

After this call, lookups will no longer find the pipe, and any
attempts to read or write using preexisting opens of the pipe will
return -EPIPE.

#### <a id="c-rpc_init_pipe_dir_head"></a>`rpc_init_pipe_dir_head()`

```c
void rpc_init_pipe_dir_head(struct rpc_pipe_dir_head *pdh)
```

initialise a struct rpc_pipe_dir_head

**Parameters**

- `struct rpc_pipe_dir_head *pdh`: pointer to struct rpc_pipe_dir_head

#### <a id="c-rpc_init_pipe_dir_object"></a>`rpc_init_pipe_dir_object()`

```c
void rpc_init_pipe_dir_object(struct rpc_pipe_dir_object *pdo, const struct rpc_pipe_dir_object_ops *pdo_ops, void *pdo_data)
```

initialise a struct rpc_pipe_dir_object

**Parameters**

- `struct rpc_pipe_dir_object *pdo`: pointer to struct rpc_pipe_dir_object
- `const struct rpc_pipe_dir_object_ops *pdo_ops`: pointer to const struct rpc_pipe_dir_object_ops
- `void *pdo_data`: pointer to caller-defined data

#### <a id="c-rpc_add_pipe_dir_object"></a>`rpc_add_pipe_dir_object()`

```c
int rpc_add_pipe_dir_object(struct net *net, struct rpc_pipe_dir_head *pdh, struct rpc_pipe_dir_object *pdo)
```

associate a rpc_pipe_dir_object to a directory

**Parameters**

- `struct net *net`: pointer to struct net
- `struct rpc_pipe_dir_head *pdh`: pointer to struct rpc_pipe_dir_head
- `struct rpc_pipe_dir_object *pdo`: pointer to struct rpc_pipe_dir_object

#### <a id="c-rpc_remove_pipe_dir_object"></a>`rpc_remove_pipe_dir_object()`

```c
void rpc_remove_pipe_dir_object(struct net *net, struct rpc_pipe_dir_head *pdh, struct rpc_pipe_dir_object *pdo)
```

remove a rpc_pipe_dir_object from a directory

**Parameters**

- `struct net *net`: pointer to struct net
- `struct rpc_pipe_dir_head *pdh`: pointer to struct rpc_pipe_dir_head
- `struct rpc_pipe_dir_object *pdo`: pointer to struct rpc_pipe_dir_object

#### <a id="c-rpc_find_or_alloc_pipe_dir_object"></a>`rpc_find_or_alloc_pipe_dir_object()`

```c
struct rpc_pipe_dir_object * rpc_find_or_alloc_pipe_dir_object(struct net *net, struct rpc_pipe_dir_head *pdh, int (*match)(struct rpc_pipe_dir_object *, void *), struct rpc_pipe_dir_object *(*alloc)(void *), void *data)
```

**Parameters**

- `struct net *net`: pointer to struct net
- `struct rpc_pipe_dir_head *pdh`: pointer to struct rpc_pipe_dir_head
- `int (*match)(struct rpc_pipe_dir_object *, void *)`: match struct rpc_pipe_dir_object to data
- `struct rpc_pipe_dir_object *(*alloc)(void *)`: allocate a new struct rpc_pipe_dir_object
- `void *data`: user defined data for `match()` and `alloc()`



#### <a id="c-rpcb_getport_async"></a>`rpcb_getport_async()`

```c
void rpcb_getport_async(struct rpc_task *task)
```

obtain the port for a given RPC service on a given host

**Parameters**

- `struct rpc_task *task`: task that is waiting for portmapper request

**Description**

This one can be called for an ongoing RPC request, and can be used in
an async (rpciod) context.



#### <a id="c-rpc_create"></a>`rpc_create()`

```c
struct rpc_clnt * rpc_create(struct rpc_create_args *args)
```

create an RPC client and transport with one call

**Parameters**

- `struct rpc_create_args *args`: rpc_clnt create argument structure

**Description**

Creates and initializes an RPC transport and an RPC client.

It can ping the server in order to determine if it is up, and to see if
it supports this program and version.  RPC_CLNT_CREATE_NOPING disables
this behavior so asynchronous tasks can also use rpc_create.

#### <a id="c-rpc_clone_client"></a>`rpc_clone_client()`

```c
struct rpc_clnt * rpc_clone_client(struct rpc_clnt *clnt)
```

Clone an RPC client structure

**Parameters**

- `struct rpc_clnt *clnt`: RPC client whose parameters are copied

**Description**

Returns a fresh RPC client or an ERR_PTR.

#### <a id="c-rpc_clone_client_set_auth"></a>`rpc_clone_client_set_auth()`

```c
struct rpc_clnt * rpc_clone_client_set_auth(struct rpc_clnt *clnt, rpc_authflavor_t flavor)
```

Clone an RPC client structure and set its auth

**Parameters**

- `struct rpc_clnt *clnt`: RPC client whose parameters are copied
- `rpc_authflavor_t flavor`: security flavor for new client

**Description**

Returns a fresh RPC client or an ERR_PTR.

#### <a id="c-rpc_switch_client_transport"></a>`rpc_switch_client_transport()`

```c
int rpc_switch_client_transport(struct rpc_clnt *clnt, struct xprt_create *args, const struct rpc_timeout *timeout)
```

switch the RPC transport on the fly

**Parameters**

- `struct rpc_clnt *clnt`: pointer to a struct rpc_clnt
- `struct xprt_create *args`: pointer to the new transport arguments
- `const struct rpc_timeout *timeout`: pointer to the new timeout parameters

**Description**

This function allows the caller to switch the RPC transport for the
rpc_clnt structure 'clnt' to allow it to connect to a mirrored NFS
server, for instance.  It assumes that the caller has ensured that
there are no active RPC tasks by using some form of locking.

Returns zero if "clnt" is now using the new xprt.  Otherwise a
negative errno is returned, and "clnt" continues to use the old
xprt.

#### <a id="c-rpc_clnt_iterate_for_each_xprt"></a>`rpc_clnt_iterate_for_each_xprt()`

```c
int rpc_clnt_iterate_for_each_xprt(struct rpc_clnt *clnt, int (*fn)(struct rpc_clnt *, struct rpc_xprt *, void *), void *data)
```

Apply a function to all transports

**Parameters**

- `struct rpc_clnt *clnt`: pointer to client
- `int (*fn)(struct rpc_clnt *, struct rpc_xprt *, void *)`: function to apply
- `void *data`: void pointer to function data

**Description**

Iterates through the list of RPC transports currently attached to the
client and applies the function fn(clnt, xprt, data).

On error, the iteration stops, and the function returns the error value.

#### <a id="c-rpc_cancel_tasks"></a>`rpc_cancel_tasks()`

```c
unsigned long rpc_cancel_tasks(struct rpc_clnt *clnt, int error, bool (*fnmatch)(const struct rpc_task *, const void *), const void *data)
```

try to cancel a set of RPC tasks

**Parameters**

- `struct rpc_clnt *clnt`: Pointer to RPC client
- `int error`: RPC task error value to set
- `bool (*fnmatch)(const struct rpc_task *, const void *)`: Pointer to selector function
- `const void *data`: User data

**Description**

Uses **fnmatch** to define a set of RPC tasks that are to be cancelled.
The argument **error** must be a negative error value.

#### <a id="c-rpc_bind_new_program"></a>`rpc_bind_new_program()`

```c
struct rpc_clnt * rpc_bind_new_program(struct rpc_clnt *old, const struct rpc_program *program, u32 vers)
```

bind a new RPC program to an existing client

**Parameters**

- `struct rpc_clnt *old`: old rpc_client
- `const struct rpc_program *program`: rpc program to set
- `u32 vers`: rpc program version

**Description**

Clones the rpc client and sets up a new RPC program. This is mainly
of use for enabling different RPC programs to share the same transport.
The Sun NFSv2/v3 ACL protocol can do this.

#### <a id="c-rpc_run_task"></a>`rpc_run_task()`

```c
struct rpc_task * rpc_run_task(const struct rpc_task_setup *task_setup_data)
```

Allocate a new RPC task, then run rpc_execute against it

**Parameters**

- `const struct rpc_task_setup *task_setup_data`: pointer to task initialisation data

#### <a id="c-rpc_call_sync"></a>`rpc_call_sync()`

```c
int rpc_call_sync(struct rpc_clnt *clnt, const struct rpc_message *msg, int flags)
```

Perform a synchronous RPC call

**Parameters**

- `struct rpc_clnt *clnt`: pointer to RPC client
- `const struct rpc_message *msg`: RPC call parameters
- `int flags`: RPC call flags

#### <a id="c-rpc_call_async"></a>`rpc_call_async()`

```c
int rpc_call_async(struct rpc_clnt *clnt, const struct rpc_message *msg, int flags, const struct rpc_call_ops *tk_ops, void *data)
```

Perform an asynchronous RPC call

**Parameters**

- `struct rpc_clnt *clnt`: pointer to RPC client
- `const struct rpc_message *msg`: RPC call parameters
- `int flags`: RPC call flags
- `const struct rpc_call_ops *tk_ops`: RPC call ops
- `void *data`: user call data

#### <a id="c-rpc_prepare_reply_pages"></a>`rpc_prepare_reply_pages()`

```c
void rpc_prepare_reply_pages(struct rpc_rqst *req, struct page **pages, unsigned int base, unsigned int len, unsigned int hdrsize)
```

Prepare to receive a reply data payload into pages

**Parameters**

- `struct rpc_rqst *req`: RPC request to prepare
- `struct page **pages`: vector of struct page pointers
- `unsigned int base`: offset in first page where receive should start, in bytes
- `unsigned int len`: expected size of the upper layer data payload, in bytes
- `unsigned int hdrsize`: expected size of upper layer reply header, in XDR words

#### <a id="c-rpc_peeraddr"></a>`rpc_peeraddr()`

```c
size_t rpc_peeraddr(struct rpc_clnt *clnt, struct sockaddr *buf, size_t bufsize)
```

extract remote peer address from clnt's xprt

**Parameters**

- `struct rpc_clnt *clnt`: RPC client structure
- `struct sockaddr *buf`: target buffer
- `size_t bufsize`: length of target buffer

**Description**

Returns the number of bytes that are actually in the stored address.

#### <a id="c-rpc_peeraddr2str"></a>`rpc_peeraddr2str()`

```c
const char * rpc_peeraddr2str(struct rpc_clnt *clnt, enum rpc_display_format_t format)
```

return remote peer address in printable format

**Parameters**

- `struct rpc_clnt *clnt`: RPC client structure
- `enum rpc_display_format_t format`: address format

**Description**

NB: the lifetime of the memory referenced by the returned pointer is
the same as the rpc_xprt itself.  As long as the caller uses this
pointer, it must hold the RCU read lock.

#### <a id="c-rpc_localaddr"></a>`rpc_localaddr()`

```c
int rpc_localaddr(struct rpc_clnt *clnt, struct sockaddr *buf, size_t buflen)
```

discover local endpoint address for an RPC client

**Parameters**

- `struct rpc_clnt *clnt`: RPC client structure
- `struct sockaddr *buf`: target buffer
- `size_t buflen`: size of target buffer, in bytes

**Description**

Returns zero and fills in "buf" and "buflen" if successful;
otherwise, a negative errno is returned.

This works even if the underlying transport is not currently connected,
or if the upper layer never previously provided a source address.

The result of this function call is transient: multiple calls in
succession may give different results, depending on how local
networking configuration changes over time.

#### <a id="c-rpc_net_ns"></a>`rpc_net_ns()`

```c
struct net * rpc_net_ns(struct rpc_clnt *clnt)
```

Get the network namespace for this RPC client

**Parameters**

- `struct rpc_clnt *clnt`: RPC client to query

#### <a id="c-rpc_max_payload"></a>`rpc_max_payload()`

```c
size_t rpc_max_payload(struct rpc_clnt *clnt)
```

Get maximum payload size for a transport, in bytes

**Parameters**

- `struct rpc_clnt *clnt`: RPC client to query

**Description**

For stream transports, this is one RPC record fragment (see RFC
1831), as we don't support multi-record requests yet.  For datagram
transports, this is the size of an IP packet minus the IP, UDP, and
RPC header sizes.

#### <a id="c-rpc_max_bc_payload"></a>`rpc_max_bc_payload()`

```c
size_t rpc_max_bc_payload(struct rpc_clnt *clnt)
```

Get maximum backchannel payload size, in bytes

**Parameters**

- `struct rpc_clnt *clnt`: RPC client to query

#### <a id="c-rpc_force_rebind"></a>`rpc_force_rebind()`

```c
void rpc_force_rebind(struct rpc_clnt *clnt)
```

force transport to check that remote port is unchanged

**Parameters**

- `struct rpc_clnt *clnt`: client to rebind

#### <a id="c-rpc_clnt_test_and_add_xprt"></a>`rpc_clnt_test_and_add_xprt()`

```c
int rpc_clnt_test_and_add_xprt(struct rpc_clnt *clnt, struct rpc_xprt_switch *xps, struct rpc_xprt *xprt, void *in_max_connect)
```

Test and add a new transport to a rpc_clnt

**Parameters**

- `struct rpc_clnt *clnt`: pointer to struct rpc_clnt
- `struct rpc_xprt_switch *xps`: pointer to struct rpc_xprt_switch,
- `struct rpc_xprt *xprt`: pointer struct rpc_xprt
- `void *in_max_connect`: pointer to the max_connect value for the passed in xprt transport

#### <a id="c-rpc_clnt_setup_test_and_add_xprt"></a>`rpc_clnt_setup_test_and_add_xprt()`

```c
int rpc_clnt_setup_test_and_add_xprt(struct rpc_clnt *clnt, struct rpc_xprt_switch *xps, struct rpc_xprt *xprt, void *data)
```

**Parameters**

- `struct rpc_clnt *clnt`: struct rpc_clnt to get the new transport
- `struct rpc_xprt_switch *xps`: the rpc_xprt_switch to hold the new transport
- `struct rpc_xprt *xprt`: the rpc_xprt to test
- `void *data`: a struct rpc_add_xprt_test pointer that holds the test function
  and test function call data

**Description**

- This is an rpc_clnt_add_xprt `setup()` function which returns 1 so:
  1) caller of the test function must dereference the rpc_xprt_switch
  and the rpc_xprt.
  2) test function must call rpc_xprt_switch_add_xprt, usually in
  the rpc_call_done routine.

Upon success (return of 1), the test function adds the new
transport to the rpc_clnt xprt switch

#### <a id="c-rpc_clnt_add_xprt"></a>`rpc_clnt_add_xprt()`

```c
int rpc_clnt_add_xprt(struct rpc_clnt *clnt, struct xprt_create *xprtargs, int (*setup)(struct rpc_clnt *, struct rpc_xprt_switch *, struct rpc_xprt *, void *), void *data)
```

Add a new transport to a rpc_clnt

**Parameters**

- `struct rpc_clnt *clnt`: pointer to struct rpc_clnt
- `struct xprt_create *xprtargs`: pointer to struct xprt_create
- `int (*setup)(struct rpc_clnt *, struct rpc_xprt_switch *, struct rpc_xprt *, void *)`: callback to test and/or set up the connection
- `void *data`: pointer to setup function data

**Description**

Creates a new transport using the parameters set in args and
adds it to clnt.
If ping is set, then test that connectivity succeeds before
adding the new transport.


<a id="rst-network-device-support"></a>

## Network device support

<a id="rst-driver-support"></a>

### Driver Support


#### <a id="c-dev_add_pack"></a>`dev_add_pack()`

```c
void dev_add_pack(struct packet_type *pt)
```

add packet handler

**Parameters**

- `struct packet_type *pt`: packet type declaration

**Description**

Add a protocol handler to the networking stack. The passed `packet_type`
is linked into kernel lists and may not be freed until it has been
removed from the kernel lists.

This call does not sleep therefore it can not
guarantee all CPU's that are in middle of receiving packets
will see the new packet type (until the next received packet).

#### <a id="c-__dev_remove_pack"></a>`__dev_remove_pack()`

```c
void __dev_remove_pack(struct packet_type *pt)
```

remove packet handler

**Parameters**

- `struct packet_type *pt`: packet type declaration

**Description**

Remove a protocol handler that was previously added to the kernel
protocol handlers by [`dev_add_pack()`](#c-dev_add_pack). The passed `packet_type` is removed
from the kernel lists and can be freed or reused once this function
returns.

The packet type might still be in use by receivers
and must not be freed until after all the CPU's have gone
through a quiescent state.

#### <a id="c-dev_remove_pack"></a>`dev_remove_pack()`

```c
void dev_remove_pack(struct packet_type *pt)
```

remove packet handler

**Parameters**

- `struct packet_type *pt`: packet type declaration

**Description**

Remove a protocol handler that was previously added to the kernel
protocol handlers by [`dev_add_pack()`](#c-dev_add_pack). The passed `packet_type` is removed
from the kernel lists and can be freed or reused once this function
returns.

This call sleeps to guarantee that no CPU is looking at the packet
type after return.

#### <a id="c-dev_get_iflink"></a>`dev_get_iflink()`

```c
int dev_get_iflink(const struct net_device *dev)
```

get 'iflink' value of a interface

**Parameters**

- `const struct net_device *dev`: targeted interface

**Description**

Indicates the ifindex the interface is linked to.
Physical interfaces have the same 'ifindex' and 'iflink' values.

#### <a id="c-dev_fill_metadata_dst"></a>`dev_fill_metadata_dst()`

```c
int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
```

Retrieve tunnel egress information.

**Parameters**

- `struct net_device *dev`: targeted interface
- `struct sk_buff *skb`: The packet.

**Description**

For better visibility of tunnel traffic OVS needs to retrieve
egress tunnel information for a packet. Following API allows
user to get this info.

#### <a id="c-__dev_get_by_name"></a>`__dev_get_by_name()`

```c
struct net_device * __dev_get_by_name(struct net *net, const char *name)
```

find a device by its name

**Parameters**

- `struct net *net`: the applicable net namespace
- `const char *name`: name to find

**Description**

Find an interface by name. Must be called under RTNL semaphore.
If the name is found a pointer to the device is returned.
If the name is not found then `NULL` is returned. The
reference counters are not incremented so the caller must be
careful with locks.

#### <a id="c-dev_get_by_name_rcu"></a>`dev_get_by_name_rcu()`

```c
struct net_device * dev_get_by_name_rcu(struct net *net, const char *name)
```

find a device by its name

**Parameters**

- `struct net *net`: the applicable net namespace
- `const char *name`: name to find

**Description**

Find an interface by name.
If the name is found a pointer to the device is returned.
If the name is not found then `NULL` is returned.
The reference counters are not incremented so the caller must be
careful with locks. The caller must hold RCU lock.

#### <a id="c-netdev_get_by_name"></a>`netdev_get_by_name()`

```c
struct net_device * netdev_get_by_name(struct net *net, const char *name, netdevice_tracker *tracker, gfp_t gfp)
```

find a device by its name

**Parameters**

- `struct net *net`: the applicable net namespace
- `const char *name`: name to find
- `netdevice_tracker *tracker`: tracking object for the acquired reference
- `gfp_t gfp`: allocation flags for the tracker

**Description**

Find an interface by name. This can be called from any
context and does its own locking. The returned handle has
the usage count incremented and the caller must use `netdev_put()` to
release it when it is no longer needed. `NULL` is returned if no
matching device is found.

#### <a id="c-__dev_get_by_index"></a>`__dev_get_by_index()`

```c
struct net_device * __dev_get_by_index(struct net *net, int ifindex)
```

find a device by its ifindex

**Parameters**

- `struct net *net`: the applicable net namespace
- `int ifindex`: index of device

**Description**

Search for an interface by index. Returns `NULL` if the device
is not found or a pointer to the device. The device has not
had its reference counter increased so the caller must be careful
about locking. The caller must hold the RTNL semaphore.

#### <a id="c-dev_get_by_index_rcu"></a>`dev_get_by_index_rcu()`

```c
struct net_device * dev_get_by_index_rcu(struct net *net, int ifindex)
```

find a device by its ifindex

**Parameters**

- `struct net *net`: the applicable net namespace
- `int ifindex`: index of device

**Description**

Search for an interface by index. Returns `NULL` if the device
is not found or a pointer to the device. The device has not
had its reference counter increased so the caller must be careful
about locking. The caller must hold RCU lock.

#### <a id="c-netdev_get_by_index"></a>`netdev_get_by_index()`

```c
struct net_device * netdev_get_by_index(struct net *net, int ifindex, netdevice_tracker *tracker, gfp_t gfp)
```

find a device by its ifindex

**Parameters**

- `struct net *net`: the applicable net namespace
- `int ifindex`: index of device
- `netdevice_tracker *tracker`: tracking object for the acquired reference
- `gfp_t gfp`: allocation flags for the tracker

**Description**

Search for an interface by index. Returns NULL if the device
is not found or a pointer to the device. The device returned has
had a reference added and the pointer is safe until the user calls
`netdev_put()` to indicate they have finished with it.

#### <a id="c-dev_getbyhwaddr_rcu"></a>`dev_getbyhwaddr_rcu()`

```c
struct net_device * dev_getbyhwaddr_rcu(struct net *net, unsigned short type, const char *ha)
```

find a device by its hardware address

**Parameters**

- `struct net *net`: the applicable net namespace
- `unsigned short type`: media type of device
- `const char *ha`: hardware address

**Description**

Search for an interface by MAC address. Returns NULL if the device
is not found or a pointer to the device.
The caller must hold RCU.
The returned device has not had its ref count increased
and the caller must therefore be careful about locking

#### <a id="c-dev_getbyhwaddr"></a>`dev_getbyhwaddr()`

```c
struct net_device * dev_getbyhwaddr(struct net *net, unsigned short type, const char *ha)
```

find a device by its hardware address

**Parameters**

- `struct net *net`: the applicable net namespace
- `unsigned short type`: media type of device
- `const char *ha`: hardware address

**Description**

Similar to [`dev_getbyhwaddr_rcu()`](#c-dev_getbyhwaddr_rcu), but the owner needs to hold
rtnl_lock.

**Context**

`rtnl_lock()` must be held.

**Return**

pointer to the net_device, or NULL if not found

#### <a id="c-dev_valid_name"></a>`dev_valid_name()`

```c
bool dev_valid_name(const char *name)
```

check if name is okay for network device

**Parameters**

- `const char *name`: name string

**Description**

Network device names need to be valid file names to
allow sysfs to work.  We also disallow any kind of
whitespace.

#### <a id="c-dev_alloc_name"></a>`dev_alloc_name()`

```c
int dev_alloc_name(struct net_device *dev, const char *name)
```

allocate a name for a device

**Parameters**

- `struct net_device *dev`: device
- `const char *name`: name format string

**Description**

Passed a format string - eg "lt`d`" it will try and find a suitable
id. It scans list of devices to build up a free map, then chooses
the first empty slot. The caller must hold the dev_base or rtnl lock
while allocating the name and adding the device in order to avoid
duplicates.
Limited to bits_per_byte * page size devices (ie 32K on most platforms).
Returns the number of the unit assigned or a negative errno code.

#### <a id="c-netdev_features_change"></a>`netdev_features_change()`

```c
void netdev_features_change(struct net_device *dev)
```

device changes features

**Parameters**

- `struct net_device *dev`: device to cause notification

**Description**

Called to indicate a device has changed features.

#### <a id="c-__netdev_notify_peers"></a>`__netdev_notify_peers()`

```c
void __netdev_notify_peers(struct net_device *dev)
```

notify network peers about existence of **dev**, to be called when rtnl lock is already held.

**Parameters**

- `struct net_device *dev`: network device

**Description**

Generate traffic such that interested network peers are aware of
**dev**, such as by generating a gratuitous ARP. This may be used when
a device wants to inform the rest of the network about some sort of
reconfiguration such as a failover event or virtual machine
migration.

#### <a id="c-netdev_notify_peers"></a>`netdev_notify_peers()`

```c
void netdev_notify_peers(struct net_device *dev)
```

notify network peers about existence of **dev**

**Parameters**

- `struct net_device *dev`: network device

**Description**

Generate traffic such that interested network peers are aware of
**dev**, such as by generating a gratuitous ARP. This may be used when
a device wants to inform the rest of the network about some sort of
reconfiguration such as a failover event or virtual machine
migration.

#### <a id="c-register_netdevice_notifier"></a>`register_netdevice_notifier()`

```c
int register_netdevice_notifier(struct notifier_block *nb)
```

register a network notifier block

**Parameters**

- `struct notifier_block *nb`: notifier

**Description**

Register a notifier to be called when network device events occur.
The notifier passed is linked into the kernel structures and must
not be reused until it has been unregistered. A negative errno code
is returned on a failure.

When registered all registration and up events are replayed
to the new notifier to allow device to have a race free
view of the network device list.

#### <a id="c-unregister_netdevice_notifier"></a>`unregister_netdevice_notifier()`

```c
int unregister_netdevice_notifier(struct notifier_block *nb)
```

unregister a network notifier block

**Parameters**

- `struct notifier_block *nb`: notifier

**Description**

Unregister a notifier previously registered by
[`register_netdevice_notifier()`](#c-register_netdevice_notifier). The notifier is unlinked into the
kernel structures and may then be reused. A negative errno code
is returned on a failure.

After unregistering unregister and down device events are synthesized
for all devices on the device list to the removed notifier to remove
the need for special case cleanup code.

#### <a id="c-register_netdevice_notifier_net"></a>`register_netdevice_notifier_net()`

```c
int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
```

register a per-netns network notifier block

**Parameters**

- `struct net *net`: network namespace
- `struct notifier_block *nb`: notifier

**Description**

Register a notifier to be called when network device events occur.
The notifier passed is linked into the kernel structures and must
not be reused until it has been unregistered. A negative errno code
is returned on a failure.

When registered all registration and up events are replayed
to the new notifier to allow device to have a race free
view of the network device list.

#### <a id="c-unregister_netdevice_notifier_net"></a>`unregister_netdevice_notifier_net()`

```c
int unregister_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
```

unregister a per-netns network notifier block

**Parameters**

- `struct net *net`: network namespace
- `struct notifier_block *nb`: notifier

**Description**

Unregister a notifier previously registered by
[`register_netdevice_notifier_net()`](#c-register_netdevice_notifier_net). The notifier is unlinked from the
kernel structures and may then be reused. A negative errno code
is returned on a failure.

After unregistering unregister and down device events are synthesized
for all devices on the device list to the removed notifier to remove
the need for special case cleanup code.

#### <a id="c-call_netdevice_notifiers"></a>`call_netdevice_notifiers()`

```c
int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
```

call all network notifier blocks

**Parameters**

- `unsigned long val`: value passed unmodified to notifier function
- `struct net_device *dev`: net_device pointer passed unmodified to notifier function

**Description**

Call all network notifier blocks.  Parameters and return value
are as for `raw_notifier_call_chain()`.

#### <a id="c-dev_forward_skb"></a>`dev_forward_skb()`

```c
int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
```

loopback an skb to another netif

**Parameters**

- `struct net_device *dev`: destination network device
- `struct sk_buff *skb`: buffer to forward

**Description**

- return values:
  NET_RX_SUCCESS  (no congestion)
  NET_RX_DROP     (packet was dropped, but freed)

dev_forward_skb can be used for injecting an skb from the
start_xmit function of one device into the receive queue
of another device.

The receiving device may be in another namespace, so
we have to clear all information in the skb that could
impact namespace isolation.

#### <a id="c-dev_nit_active_rcu"></a>`dev_nit_active_rcu()`

```c
bool dev_nit_active_rcu(const struct net_device *dev)
```

return true if any network interface taps are in use

**Parameters**

- `const struct net_device *dev`: network device to check for the presence of taps

**Description**

The caller must hold the RCU lock

#### <a id="c-netif_set_real_num_rx_queues"></a>`netif_set_real_num_rx_queues()`

```c
int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
```

set actual number of RX queues used

**Parameters**

- `struct net_device *dev`: Network device
- `unsigned int rxq`: Actual number of RX queues

**Description**

This must be called either with the rtnl_lock held or before
registration of the net device.  Returns 0 on success, or a
negative error code.  If called before registration, it always
succeeds.

#### <a id="c-netif_set_real_num_queues"></a>`netif_set_real_num_queues()`

```c
int netif_set_real_num_queues(struct net_device *dev, unsigned int txq, unsigned int rxq)
```

set actual number of RX and TX queues used

**Parameters**

- `struct net_device *dev`: Network device
- `unsigned int txq`: Actual number of TX queues
- `unsigned int rxq`: Actual number of RX queues

**Description**

Set the real number of both TX and RX queues.
Does nothing if the number of queues is already correct.

#### <a id="c-netif_set_tso_max_size"></a>`netif_set_tso_max_size()`

```c
void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
```

set the max size of TSO frames supported

**Parameters**

- `struct net_device *dev`: netdev to update
- `unsigned int size`: max skb->len of a TSO frame

**Description**

Set the limit on the size of TSO super-frames the device can handle.
Unless explicitly set the stack will assume the value of
`GSO_LEGACY_MAX_SIZE`.

#### <a id="c-netif_set_tso_max_segs"></a>`netif_set_tso_max_segs()`

```c
void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
```

set the max number of segs supported for TSO

**Parameters**

- `struct net_device *dev`: netdev to update
- `unsigned int segs`: max number of TCP segments

**Description**

Set the limit on the number of TCP segments the device can generate from
a single TSO super-frame.
Unless explicitly set the stack will assume the value of `GSO_MAX_SEGS`.

#### <a id="c-netif_inherit_tso_max"></a>`netif_inherit_tso_max()`

```c
void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
```

copy all TSO limits from a lower device to an upper

**Parameters**

- `struct net_device *to`: netdev to update
- `const struct net_device *from`: netdev from which to copy the limits

#### <a id="c-netif_get_num_default_rss_queues"></a>`netif_get_num_default_rss_queues()`

```c
int netif_get_num_default_rss_queues(void)
```

default number of RSS queues

**Parameters**

- `void`: no arguments

**Description**

Default value is the number of physical cores if there are only 1 or 2, or
divided by 2 if there are more.

#### <a id="c-netif_device_detach"></a>`netif_device_detach()`

```c
void netif_device_detach(struct net_device *dev)
```

mark device as removed

**Parameters**

- `struct net_device *dev`: network device

**Description**

Mark device as removed from system and therefore no longer available.

#### <a id="c-netif_device_attach"></a>`netif_device_attach()`

```c
void netif_device_attach(struct net_device *dev)
```

mark device as attached

**Parameters**

- `struct net_device *dev`: network device

**Description**

Mark device as attached from system and restart if needed.

#### <a id="c-dev_loopback_xmit"></a>`dev_loopback_xmit()`

```c
int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
```

loop back **skb**

**Parameters**

- `struct net *net`: network namespace this loopback is happening in
- `struct sock *sk`: sk needed to be a netfilter okfn
- `struct sk_buff *skb`: buffer to transmit

#### <a id="c-__dev_queue_xmit"></a>`__dev_queue_xmit()`

```c
int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
```

transmit a buffer

**Parameters**

- `struct sk_buff *skb`: buffer to transmit
- `struct net_device *sb_dev`: suboordinate device used for L2 forwarding offload

**Description**

Queue a buffer for transmission to a network device. The caller must
have set the device and priority and built the buffer before calling
this function. The function can be called from an interrupt.

When calling this method, interrupts MUST be enabled. This is because
the BH enable code must have IRQs enabled so that it will not deadlock.

Regardless of the return value, the skb is consumed, so it is currently
difficult to retry a send to this method. (You can bump the ref count
before sending to hold a reference for retry if you are careful.)

**Return**

* 0                          - buffer successfully transmitted
* positive qdisc return code - NET_XMIT_DROP etc.
* negative errno             - other errors

#### <a id="c-rps_may_expire_flow"></a>`rps_may_expire_flow()`

```c
bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index, u32 flow_id, u16 filter_id)
```

check whether an RFS hardware filter may be removed

**Parameters**

- `struct net_device *dev`: Device on which the filter was set
- `u16 rxq_index`: RX queue index
- `u32 flow_id`: Flow ID passed to `ndo_rx_flow_steer()`
- `u16 filter_id`: Filter ID returned by `ndo_rx_flow_steer()`

**Description**

Drivers that implement `ndo_rx_flow_steer()` should periodically call
this function for each installed filter and remove the filters for
which it returns `true`.

#### <a id="c-__netif_rx"></a>`__netif_rx()`

```c
int __netif_rx(struct sk_buff *skb)
```

Slightly optimized version of netif_rx

**Parameters**

- `struct sk_buff *skb`: buffer to post

**Description**

This behaves as netif_rx except that it does not disable bottom halves.
As a result this function may only be invoked from the interrupt context
(either hard or soft interrupt).

#### <a id="c-netif_rx"></a>`netif_rx()`

```c
int netif_rx(struct sk_buff *skb)
```

post buffer to the network code

**Parameters**

- `struct sk_buff *skb`: buffer to post

**Description**

This function receives a packet from a device driver and queues it for
the upper (protocol) levels to process via the backlog NAPI device. It
always succeeds. The buffer may be dropped during processing for
congestion control or by the protocol layers.
The network buffer is passed via the backlog NAPI device. Modern NIC
driver should use NAPI and GRO.
This function can used from interrupt and from process context. The
caller from process context must not disable interrupts before invoking
this function.

return values:
NET_RX_SUCCESS  (no congestion)
NET_RX_DROP     (packet was dropped)

#### <a id="c-netdev_is_rx_handler_busy"></a>`netdev_is_rx_handler_busy()`

```c
bool netdev_is_rx_handler_busy(struct net_device *dev)
```

check if receive handler is registered

**Parameters**

- `struct net_device *dev`: device to check

**Description**

Check if a receive handler is already registered for a given device.
Return true if there one.

The caller must hold the rtnl_mutex.

#### <a id="c-netdev_rx_handler_register"></a>`netdev_rx_handler_register()`

```c
int netdev_rx_handler_register(struct net_device *dev, rx_handler_func_t *rx_handler, void *rx_handler_data)
```

register receive handler

**Parameters**

- `struct net_device *dev`: device to register a handler for
- `rx_handler_func_t *rx_handler`: receive handler to register
- `void *rx_handler_data`: data pointer that is used by rx handler

**Description**

Register a receive handler for a device. This handler will then be
called from __netif_receive_skb. A negative errno code is returned
on a failure.

The caller must hold the rtnl_mutex.

For a general description of rx_handler, see enum rx_handler_result.

#### <a id="c-netdev_rx_handler_unregister"></a>`netdev_rx_handler_unregister()`

```c
void netdev_rx_handler_unregister(struct net_device *dev)
```

unregister receive handler

**Parameters**

- `struct net_device *dev`: device to unregister a handler from

**Description**

Unregister a receive handler from a device.

The caller must hold the rtnl_mutex.

#### <a id="c-netif_receive_skb_core"></a>`netif_receive_skb_core()`

```c
int netif_receive_skb_core(struct sk_buff *skb)
```

special purpose version of netif_receive_skb

**Parameters**

- `struct sk_buff *skb`: buffer to process

**Description**

More direct receive version of [`netif_receive_skb()`](#c-netif_receive_skb).  It should
only be used by callers that have a need to skip RPS and Generic XDP.
Caller must also take care of handling if `(page_is_)pfmemalloc`.

This function may only be called from softirq context and interrupts
should be enabled.

Return values (usually ignored):
NET_RX_SUCCESS: no congestion
NET_RX_DROP: packet was dropped

#### <a id="c-netif_receive_skb"></a>`netif_receive_skb()`

```c
int netif_receive_skb(struct sk_buff *skb)
```

process receive buffer from network

**Parameters**

- `struct sk_buff *skb`: buffer to process

**Description**

[`netif_receive_skb()`](#c-netif_receive_skb) is the main receive data processing function.
It always succeeds. The buffer may be dropped during processing
for congestion control or by the protocol layers.

This function may only be called from softirq context and interrupts
should be enabled.

Return values (usually ignored):
NET_RX_SUCCESS: no congestion
NET_RX_DROP: packet was dropped

#### <a id="c-netif_receive_skb_list"></a>`netif_receive_skb_list()`

```c
void netif_receive_skb_list(struct list_head *head)
```

process many receive buffers from network

**Parameters**

- `struct list_head *head`: list of skbs to process.

**Description**

Since return value of [`netif_receive_skb()`](#c-netif_receive_skb) is normally ignored, and
wouldn't be meaningful for a list, this function returns void.

This function may only be called from softirq context and interrupts
should be enabled.

#### <a id="c-__napi_schedule"></a>`__napi_schedule()`

```c
void __napi_schedule(struct napi_struct *n)
```

schedule for receive

**Parameters**

- `struct napi_struct *n`: entry to schedule

**Description**

The entry's receive function will be scheduled to run.
Consider using [`__napi_schedule_irqoff()`](#c-__napi_schedule_irqoff) if hard irqs are masked.

#### <a id="c-napi_schedule_prep"></a>`napi_schedule_prep()`

```c
bool napi_schedule_prep(struct napi_struct *n)
```

check if napi can be scheduled

**Parameters**

- `struct napi_struct *n`: napi context

**Description**

Test if NAPI routine is already running, and if not mark
it as running.  This is used as a condition variable to
insure only one NAPI poll instance runs.  We also make
sure there is no pending NAPI disable.

#### <a id="c-__napi_schedule_irqoff"></a>`__napi_schedule_irqoff()`

```c
void __napi_schedule_irqoff(struct napi_struct *n)
```

schedule for receive

**Parameters**

- `struct napi_struct *n`: entry to schedule

**Description**

Variant of [`__napi_schedule()`](#c-__napi_schedule) assuming hard irqs are masked.

On PREEMPT_RT enabled kernels this maps to [`__napi_schedule()`](#c-__napi_schedule)
because the interrupt disabled assumption might not be true
due to force-threaded interrupts and spinlock substitution.

#### <a id="c-netif_threaded_enable"></a>`netif_threaded_enable()`

```c
void netif_threaded_enable(struct net_device *dev)
```

enable threaded NAPIs

**Parameters**

- `struct net_device *dev`: net_device instance

**Description**

Enable threaded mode for the NAPI instances of the device. This may be useful
for devices where multiple NAPI instances get scheduled by a single
interrupt. Threaded NAPI allows moving the NAPI processing to cores other
than the core where IRQ is mapped.

This function should be called before **dev** is registered.

#### <a id="c-netif_queue_set_napi"></a>`netif_queue_set_napi()`

```c
void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index, enum netdev_queue_type type, struct napi_struct *napi)
```

Associate queue with the napi

**Parameters**

- `struct net_device *dev`: device to which NAPI and queue belong
- `unsigned int queue_index`: Index of queue
- `enum netdev_queue_type type`: queue type as RX or TX
- `struct napi_struct *napi`: NAPI context, pass NULL to clear previously set NAPI

**Description**

Set queue with its corresponding napi context. This should be done after
registering the NAPI handler for the queue-vector and the queues have been
mapped to the corresponding interrupt vector.

#### <a id="c-napi_disable"></a>`napi_disable()`

```c
void napi_disable(struct napi_struct *n)
```

prevent NAPI from scheduling

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

Stop NAPI from being scheduled on this context.
Waits till any outstanding processing completes.
Takes `netdev_lock()` for associated net_device.

#### <a id="c-napi_enable"></a>`napi_enable()`

```c
void napi_enable(struct napi_struct *n)
```

enable NAPI scheduling

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

Enable scheduling of a NAPI instance.
Must be paired with [`napi_disable()`](#c-napi_disable).
Takes `netdev_lock()` for associated net_device.

#### <a id="c-netdev_has_upper_dev"></a>`netdev_has_upper_dev()`

```c
bool netdev_has_upper_dev(struct net_device *dev, struct net_device *upper_dev)
```

Check if device is linked to an upper device

**Parameters**

- `struct net_device *dev`: device
- `struct net_device *upper_dev`: upper device to check

**Description**

Find out if a device is linked to specified upper device and return true
in case it is. Note that this checks only immediate upper device,
not through a complete stack of devices. The caller must hold the RTNL lock.

#### <a id="c-netdev_has_upper_dev_all_rcu"></a>`netdev_has_upper_dev_all_rcu()`

```c
bool netdev_has_upper_dev_all_rcu(struct net_device *dev, struct net_device *upper_dev)
```

Check if device is linked to an upper device

**Parameters**

- `struct net_device *dev`: device
- `struct net_device *upper_dev`: upper device to check

**Description**

Find out if a device is linked to specified upper device and return true
in case it is. Note that this checks the entire upper device chain.
The caller must hold rcu lock.

#### <a id="c-netdev_has_any_upper_dev"></a>`netdev_has_any_upper_dev()`

```c
bool netdev_has_any_upper_dev(struct net_device *dev)
```

Check if device is linked to some device

**Parameters**

- `struct net_device *dev`: device

**Description**

Find out if a device is linked to an upper device and return true in case
it is. The caller must hold the RTNL lock.

#### <a id="c-netdev_master_upper_dev_get"></a>`netdev_master_upper_dev_get()`

```c
struct net_device * netdev_master_upper_dev_get(struct net_device *dev)
```

Get master upper device

**Parameters**

- `struct net_device *dev`: device

**Description**

Find a master upper device and return pointer to it or NULL in case
it's not there. The caller must hold the RTNL lock.

#### <a id="c-netdev_upper_get_next_dev_rcu"></a>`netdev_upper_get_next_dev_rcu()`

```c
struct net_device * netdev_upper_get_next_dev_rcu(struct net_device *dev, struct list_head **iter)
```

Get the next dev from upper list

**Parameters**

- `struct net_device *dev`: device
- `struct list_head **iter`: list_head ** of the current position

**Description**

Gets the next device from the dev's upper list, starting from iter
position. The caller must hold RCU read lock.

#### <a id="c-netdev_lower_get_next_private"></a>`netdev_lower_get_next_private()`

```c
void * netdev_lower_get_next_private(struct net_device *dev, struct list_head **iter)
```

Get the next ->private from the lower neighbour list

**Parameters**

- `struct net_device *dev`: device
- `struct list_head **iter`: list_head ** of the current position

**Description**

Gets the next netdev_adjacent->private from the dev's lower neighbour
list, starting from iter position. The caller must hold either hold the
RTNL lock or its own locking that guarantees that the neighbour lower
list will remain unchanged.

#### <a id="c-netdev_lower_get_next_private_rcu"></a>`netdev_lower_get_next_private_rcu()`

```c
void * netdev_lower_get_next_private_rcu(struct net_device *dev, struct list_head **iter)
```

Get the next ->private from the lower neighbour list, RCU variant

**Parameters**

- `struct net_device *dev`: device
- `struct list_head **iter`: list_head ** of the current position

**Description**

Gets the next netdev_adjacent->private from the dev's lower neighbour
list, starting from iter position. The caller must hold RCU read lock.

#### <a id="c-netdev_lower_get_next"></a>`netdev_lower_get_next()`

```c
void * netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
```

Get the next device from the lower neighbour list

**Parameters**

- `struct net_device *dev`: device
- `struct list_head **iter`: list_head ** of the current position

**Description**

Gets the next netdev_adjacent from the dev's lower neighbour
list, starting from iter position. The caller must hold RTNL lock or
its own locking that guarantees that the neighbour lower
list will remain unchanged.

#### <a id="c-netdev_lower_get_first_private_rcu"></a>`netdev_lower_get_first_private_rcu()`

```c
void * netdev_lower_get_first_private_rcu(struct net_device *dev)
```

Get the first ->private from the lower neighbour list, RCU variant

**Parameters**

- `struct net_device *dev`: device

**Description**

Gets the first netdev_adjacent->private from the dev's lower neighbour
list. The caller must hold RCU read lock.

#### <a id="c-netdev_master_upper_dev_get_rcu"></a>`netdev_master_upper_dev_get_rcu()`

```c
struct net_device * netdev_master_upper_dev_get_rcu(struct net_device *dev)
```

Get master upper device

**Parameters**

- `struct net_device *dev`: device

**Description**

Find a master upper device and return pointer to it or NULL in case
it's not there. The caller must hold the RCU read lock.

#### <a id="c-netdev_upper_dev_link"></a>`netdev_upper_dev_link()`

```c
int netdev_upper_dev_link(struct net_device *dev, struct net_device *upper_dev, struct netlink_ext_ack *extack)
```

Add a link to the upper device

**Parameters**

- `struct net_device *dev`: device
- `struct net_device *upper_dev`: new upper device
- `struct netlink_ext_ack *extack`: netlink extended ack

**Description**

Adds a link to device which is upper to this one. The caller must hold
the RTNL lock. On a failure a negative errno code is returned.
On success the reference counts are adjusted and the function
returns zero.

#### <a id="c-netdev_master_upper_dev_link"></a>`netdev_master_upper_dev_link()`

```c
int netdev_master_upper_dev_link(struct net_device *dev, struct net_device *upper_dev, void *upper_priv, void *upper_info, struct netlink_ext_ack *extack)
```

Add a master link to the upper device

**Parameters**

- `struct net_device *dev`: device
- `struct net_device *upper_dev`: new upper device
- `void *upper_priv`: upper device private
- `void *upper_info`: upper info to be passed down via notifier
- `struct netlink_ext_ack *extack`: netlink extended ack

**Description**

Adds a link to device which is upper to this one. In this case, only
one master upper device can be linked, although other non-master devices
might be linked as well. The caller must hold the RTNL lock.
On a failure a negative errno code is returned. On success the reference
counts are adjusted and the function returns zero.

#### <a id="c-netdev_upper_dev_unlink"></a>`netdev_upper_dev_unlink()`

```c
void netdev_upper_dev_unlink(struct net_device *dev, struct net_device *upper_dev)
```

Removes a link to upper device

**Parameters**

- `struct net_device *dev`: device
- `struct net_device *upper_dev`: new upper device

**Description**

Removes a link to device which is upper to this one. The caller must hold
the RTNL lock.

#### <a id="c-netdev_bonding_info_change"></a>`netdev_bonding_info_change()`

```c
void netdev_bonding_info_change(struct net_device *dev, struct netdev_bonding_info *bonding_info)
```

Dispatch event about slave change

**Parameters**

- `struct net_device *dev`: device
- `struct netdev_bonding_info *bonding_info`: info to dispatch

**Description**

Send NETDEV_BONDING_INFO to netdev notifiers with info.
The caller must hold the RTNL lock.

#### <a id="c-netdev_get_xmit_slave"></a>`netdev_get_xmit_slave()`

```c
struct net_device * netdev_get_xmit_slave(struct net_device *dev, struct sk_buff *skb, bool all_slaves)
```

Get the xmit slave of master device

**Parameters**

- `struct net_device *dev`: device
- `struct sk_buff *skb`: The packet
- `bool all_slaves`: assume all the slaves are active

**Description**

The reference counters are not incremented so the caller must be
careful with locks. The caller must hold RCU lock.
`NULL` is returned if no slave is found.

#### <a id="c-netdev_sk_get_lowest_dev"></a>`netdev_sk_get_lowest_dev()`

```c
struct net_device * netdev_sk_get_lowest_dev(struct net_device *dev, struct sock *sk)
```

Get the lowest device in chain given device and socket

**Parameters**

- `struct net_device *dev`: device
- `struct sock *sk`: the socket

**Description**

`NULL` is returned if no lower device is found.

#### <a id="c-netdev_lower_state_changed"></a>`netdev_lower_state_changed()`

```c
void netdev_lower_state_changed(struct net_device *lower_dev, void *lower_state_info)
```

Dispatch event about lower device state change

**Parameters**

- `struct net_device *lower_dev`: device
- `void *lower_state_info`: state to dispatch

**Description**

Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
The caller must hold the RTNL lock.

#### <a id="c-netif_get_flags"></a>`netif_get_flags()`

```c
unsigned int netif_get_flags(const struct net_device *dev)
```

get flags reported to userspace

**Parameters**

- `const struct net_device *dev`: device

**Description**

Get the combination of flag bits exported through APIs to userspace.

#### <a id="c-netif_pre_changeaddr_notify"></a>`netif_pre_changeaddr_notify()`

```c
int netif_pre_changeaddr_notify(struct net_device *dev, const char *addr, struct netlink_ext_ack *extack)
```

Call NETDEV_PRE_CHANGEADDR.

**Parameters**

- `struct net_device *dev`: device
- `const char *addr`: new address
- `struct netlink_ext_ack *extack`: netlink extended ack

**Return**

0 on success, -errno on failure.

#### <a id="c-netif_get_port_parent_id"></a>`netif_get_port_parent_id()`

```c
int netif_get_port_parent_id(struct net_device *dev, struct netdev_phys_item_id *ppid, bool recurse)
```

Get the device's port parent identifier

**Parameters**

- `struct net_device *dev`: network device
- `struct netdev_phys_item_id *ppid`: pointer to a storage for the port's parent identifier
- `bool recurse`: allow/disallow recursion to lower devices

**Description**

Get the devices's port parent identifier.

**Return**

0 on success, -errno on failure.

#### <a id="c-netdev_port_same_parent_id"></a>`netdev_port_same_parent_id()`

```c
bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
```

Indicate if two network devices have the same port parent identifier

**Parameters**

- `struct net_device *a`: first network device
- `struct net_device *b`: second network device

#### <a id="c-netdev_update_features"></a>`netdev_update_features()`

```c
void netdev_update_features(struct net_device *dev)
```

recalculate device features

**Parameters**

- `struct net_device *dev`: the device to check

**Description**

Recalculate dev->features set and send notifications if it
has changed. Should be called after driver or hardware dependent
conditions might have changed that influence the features.

#### <a id="c-netdev_change_features"></a>`netdev_change_features()`

```c
void netdev_change_features(struct net_device *dev)
```

recalculate device features

**Parameters**

- `struct net_device *dev`: the device to check

**Description**

Recalculate dev->features set and send notifications even
if they have not changed. Should be called instead of
[`netdev_update_features()`](#c-netdev_update_features) if also dev->vlan_features might
have changed to allow the changes to be propagated to stacked
VLAN devices.

#### <a id="c-netif_stacked_transfer_operstate"></a>`netif_stacked_transfer_operstate()`

```c
void netif_stacked_transfer_operstate(const struct net_device *rootdev, struct net_device *dev)
```

transfer operstate

**Parameters**

- `const struct net_device *rootdev`: the root or lower level device to transfer state from
- `struct net_device *dev`: the device to transfer operstate to

**Description**

Transfer operational state from root to device. This is normally
called when a stacking relationship exists between the root
device and the device(a leaf device).

#### <a id="c-register_netdevice"></a>`register_netdevice()`

```c
int register_netdevice(struct net_device *dev)
```

register a network device

**Parameters**

- `struct net_device *dev`: device to register

**Description**

Take a prepared network device structure and make it externally accessible.
A `NETDEV_REGISTER` message is sent to the netdev notifier chain.
Callers must hold the rtnl lock - you may want [`register_netdev()`](#c-register_netdev)
instead of this.

#### <a id="c-register_netdev"></a>`register_netdev()`

```c
int register_netdev(struct net_device *dev)
```

register a network device

**Parameters**

- `struct net_device *dev`: device to register

**Description**

Take a completed network device structure and add it to the kernel
interfaces. A `NETDEV_REGISTER` message is sent to the netdev notifier
chain. 0 is returned on success. A negative errno code is returned
on a failure to set up the device, or if the name is a duplicate.

This is a wrapper around register_netdevice that takes the rtnl semaphore
and expands the device name if you passed a format string to
alloc_netdev.

#### <a id="c-dev_get_stats"></a>`dev_get_stats()`

```c
struct rtnl_link_stats64 * dev_get_stats(struct net_device *dev, struct rtnl_link_stats64 *storage)
```

get network device statistics

**Parameters**

- `struct net_device *dev`: device to get statistics from
- `struct rtnl_link_stats64 *storage`: place to store stats

**Description**

Get network statistics from device. Return **storage**.
The device driver may provide its own method by setting
dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
otherwise the internal statistics structure is used.

#### <a id="c-dev_fetch_sw_netstats"></a>`dev_fetch_sw_netstats()`

```c
void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s, const struct pcpu_sw_netstats __percpu *netstats)
```

get per-cpu network device statistics

**Parameters**

- `struct rtnl_link_stats64 *s`: place to store stats
- `const struct pcpu_sw_netstats __percpu *netstats`: per-cpu network stats to read from

**Description**

Read per-cpu network statistics and populate the related fields in **s**.

#### <a id="c-dev_get_tstats64"></a>`dev_get_tstats64()`

```c
void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
```

ndo_get_stats64 implementation

**Parameters**

- `struct net_device *dev`: device to get statistics from
- `struct rtnl_link_stats64 *s`: place to store stats

**Description**

Populate **s** from dev->stats and dev->tstats. Can be used as
`ndo_get_stats64()` callback.

#### <a id="c-netdev_sw_irq_coalesce_default_on"></a>`netdev_sw_irq_coalesce_default_on()`

```c
void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
```

enable SW IRQ coalescing by default

**Parameters**

- `struct net_device *dev`: netdev to enable the IRQ coalescing on

**Description**

Sets a conservative default for SW IRQ coalescing. Users can use
sysfs attributes to override the default values.

#### <a id="c-alloc_netdev_mqs"></a>`alloc_netdev_mqs()`

```c
struct net_device * alloc_netdev_mqs(int sizeof_priv, const char *name, unsigned char name_assign_type, void (*setup)(struct net_device *), unsigned int txqs, unsigned int rxqs)
```

allocate network device

**Parameters**

- `int sizeof_priv`: size of private data to allocate space for
- `const char *name`: device name format string
- `unsigned char name_assign_type`: origin of device name
- `void (*setup)(struct net_device *)`: callback to initialize device
- `unsigned int txqs`: the number of TX subqueues to allocate
- `unsigned int rxqs`: the number of RX subqueues to allocate

**Description**

Allocates a struct net_device with private data area for driver use
and performs basic initialization.  Also allocates subqueue structs
for each queue on the device.

#### <a id="c-free_netdev"></a>`free_netdev()`

```c
void free_netdev(struct net_device *dev)
```

free network device

**Parameters**

- `struct net_device *dev`: device

**Description**

This function does the last stage of destroying an allocated device
interface. The reference to the device object is released. If this
is the last reference then it will be freed.Must be called in process
context.

#### <a id="c-alloc_netdev_dummy"></a>`alloc_netdev_dummy()`

```c
struct net_device * alloc_netdev_dummy(int sizeof_priv)
```

Allocate and initialize a dummy net device.

**Parameters**

- `int sizeof_priv`: size of private data to allocate space for

**Return**

the allocated net_device on success, NULL otherwise

#### <a id="c-synchronize_net"></a>`synchronize_net()`

```c
void synchronize_net(void)
```

Synchronize with packet receive processing

**Parameters**

- `void`: no arguments

**Description**

Wait for packets currently being received to be done.
Does not block later packets from starting.

#### <a id="c-unregister_netdevice_queue"></a>`unregister_netdevice_queue()`

```c
void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
```

remove device from the kernel

**Parameters**

- `struct net_device *dev`: device
- `struct list_head *head`: list

**Description**

This function shuts down a device interface and removes it
from the kernel tables.
If head not NULL, device is queued to be unregistered later.

Callers must hold the rtnl semaphore.  You may want
[`unregister_netdev()`](#c-unregister_netdev) instead of this.

#### <a id="c-unregister_netdevice_many"></a>`unregister_netdevice_many()`

```c
void unregister_netdevice_many(struct list_head *head)
```

unregister many devices

**Parameters**

- `struct list_head *head`: list of devices

**Note**

- As most callers use a stack allocated list_head,

  we force a [`list_del()`](/kernel/internals/core-api/list.md#c-list_del) to make sure stack won't be corrupted later.

#### <a id="c-unregister_netdev"></a>`unregister_netdev()`

```c
void unregister_netdev(struct net_device *dev)
```

remove device from the kernel

**Parameters**

- `struct net_device *dev`: device

**Description**

This function shuts down a device interface and removes it
from the kernel tables.

This is just a wrapper for unregister_netdevice that takes
the rtnl semaphore.  In general you want to use this and not
unregister_netdevice.

#### <a id="c-netdev_increment_features"></a>`netdev_increment_features()`

```c
netdev_features_t netdev_increment_features(netdev_features_t all, netdev_features_t one, netdev_features_t mask)
```

increment feature set by one

**Parameters**

- `netdev_features_t all`: current feature set
- `netdev_features_t one`: new feature set
- `netdev_features_t mask`: mask feature set

**Description**

Computes a new feature set after adding a device with feature set
**one** to the master device with current feature set **all**.  Will not
enable anything that is off in **mask**. Returns the new feature set.

#### <a id="c-netdev_compute_master_upper_features"></a>`netdev_compute_master_upper_features()`

```c
void netdev_compute_master_upper_features(struct net_device *dev, bool update_header)
```

compute feature from lowers

**Parameters**

- `struct net_device *dev`: the upper device
- `bool update_header`: whether to update upper device's header_len/headroom/tailroom

**Description**

Recompute the upper device's feature based on all lower devices.



#### <a id="c-eth_header"></a>`eth_header()`

```c
int eth_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, const void *daddr, const void *saddr, unsigned int len)
```

create the Ethernet header

**Parameters**

- `struct sk_buff *skb`: buffer to alter
- `struct net_device *dev`: source device
- `unsigned short type`: Ethernet type field
- `const void *daddr`: destination address (NULL leave destination address)
- `const void *saddr`: source address (NULL use device source address)
- `unsigned int len`: packet length (\<= skb->len)

**Description**

Set the protocol type. For a packet of type ETH_P_802_3/2 we put the length
in here instead.

#### <a id="c-eth_get_headlen"></a>`eth_get_headlen()`

```c
u32 eth_get_headlen(const struct net_device *dev, const void *data, u32 len)
```

determine the length of header for an ethernet frame

**Parameters**

- `const struct net_device *dev`: pointer to network device
- `const void *data`: pointer to start of frame
- `u32 len`: total length of frame

**Description**

Make a best effort attempt to pull the length for all of the headers for
a given frame in a linear buffer.

#### <a id="c-eth_type_trans"></a>`eth_type_trans()`

```c
__be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev)
```

determine the packet's protocol ID.

**Parameters**

- `struct sk_buff *skb`: received socket data
- `struct net_device *dev`: receiving network device

**Description**

The rule here is that we
assume 802.3 if the type field is short enough to be a length.
This is normal practice and works for any 'now in use' protocol.

#### <a id="c-eth_header_cache"></a>`eth_header_cache()`

```c
int eth_header_cache(const struct neighbour *neigh, struct hh_cache *hh, __be16 type)
```

fill cache entry from neighbour

**Parameters**

- `const struct neighbour *neigh`: source neighbour
- `struct hh_cache *hh`: destination cache entry
- `__be16 type`: Ethernet type field

**Description**

Create an Ethernet header template from the neighbour.

#### <a id="c-eth_header_cache_update"></a>`eth_header_cache_update()`

```c
void eth_header_cache_update(struct hh_cache *hh, const struct net_device *dev, const unsigned char *haddr)
```

update cache entry

**Parameters**

- `struct hh_cache *hh`: destination cache entry
- `const struct net_device *dev`: network device
- `const unsigned char *haddr`: new hardware address

**Description**

Called by Address Resolution module to notify changes in address.

#### <a id="c-eth_header_parse_protocol"></a>`eth_header_parse_protocol()`

```c
__be16 eth_header_parse_protocol(const struct sk_buff *skb)
```

extract protocol from L2 header

**Parameters**

- `const struct sk_buff *skb`: packet to extract protocol from

#### <a id="c-eth_prepare_mac_addr_change"></a>`eth_prepare_mac_addr_change()`

```c
int eth_prepare_mac_addr_change(struct net_device *dev, void *p)
```

prepare for mac change

**Parameters**

- `struct net_device *dev`: network device
- `void *p`: socket address

#### <a id="c-eth_commit_mac_addr_change"></a>`eth_commit_mac_addr_change()`

```c
void eth_commit_mac_addr_change(struct net_device *dev, void *p)
```

commit mac change

**Parameters**

- `struct net_device *dev`: network device
- `void *p`: socket address

#### <a id="c-eth_mac_addr"></a>`eth_mac_addr()`

```c
int eth_mac_addr(struct net_device *dev, void *p)
```

set new Ethernet hardware address

**Parameters**

- `struct net_device *dev`: network device
- `void *p`: socket address

**Description**

Change hardware address of device.

This doesn't change hardware matching, so needs to be overridden
for most real devices.

#### <a id="c-ether_setup"></a>`ether_setup()`

```c
void ether_setup(struct net_device *dev)
```

setup Ethernet network device

**Parameters**

- `struct net_device *dev`: network device

**Description**

Fill in the fields of the device structure with Ethernet-generic values.

#### <a id="c-alloc_etherdev_mqs"></a>`alloc_etherdev_mqs()`

```c
struct net_device * alloc_etherdev_mqs(int sizeof_priv, unsigned int txqs, unsigned int rxqs)
```

Allocates and sets up an Ethernet device

**Parameters**

- `int sizeof_priv`: Size of additional driver-private structure to be allocated
  for this Ethernet device
- `unsigned int txqs`: The number of TX queues this device has.
- `unsigned int rxqs`: The number of RX queues this device has.

**Description**

Fill in the fields of the device structure with Ethernet-generic
values. Basically does everything except registering the device.

Constructs a new net device, complete with a private data area of
size (sizeof_priv).  A 32-byte (not bit) alignment is enforced for
this private data area.

#### <a id="c-platform_get_ethdev_address"></a>`platform_get_ethdev_address()`

```c
int platform_get_ethdev_address(struct device *dev, struct net_device *netdev)
```

Set netdev's MAC address from a given device

**Parameters**

- `struct device *dev`: Pointer to the device
- `struct net_device *netdev`: Pointer to netdev to write the address to

**Description**

Wrapper around `eth_platform_get_mac_address()` which writes the address
directly to netdev->dev_addr.

#### <a id="c-fwnode_get_mac_address"></a>`fwnode_get_mac_address()`

```c
int fwnode_get_mac_address(struct fwnode_handle *fwnode, char *addr)
```

Get the MAC from the firmware node

**Parameters**

- `struct fwnode_handle *fwnode`: Pointer to the firmware node
- `char *addr`: Address of buffer to store the MAC in

**Description**

Search the firmware node for the best MAC address to use.  'mac-address' is
checked first, because that is supposed to contain to "most recent" MAC
address. If that isn't set, then 'local-mac-address' is checked next,
because that is the default address.  If that isn't set, then the obsolete
'address' is checked, just in case we're using an old device tree.

Note that the 'address' property is supposed to contain a virtual address of
the register set, but some DTS files have redefined that property to be the
MAC address.

All-zero MAC addresses are rejected, because those could be properties that
exist in the firmware tables, but were not updated by the firmware.  For
example, the DTS could define 'mac-address' and 'local-mac-address', with
zero MAC addresses.  Some older U-Boots only initialized 'local-mac-address'.
In this case, the real MAC is in 'local-mac-address', and 'mac-address'
exists but is all zeros.

#### <a id="c-device_get_mac_address"></a>`device_get_mac_address()`

```c
int device_get_mac_address(struct device *dev, char *addr)
```

Get the MAC for a given device

**Parameters**

- `struct device *dev`: Pointer to the device
- `char *addr`: Address of buffer to store the MAC in

#### <a id="c-device_get_ethdev_address"></a>`device_get_ethdev_address()`

```c
int device_get_ethdev_address(struct device *dev, struct net_device *netdev)
```

Set netdev's MAC address from a given device

**Parameters**

- `struct device *dev`: Pointer to the device
- `struct net_device *netdev`: Pointer to netdev to write the address to

**Description**

Wrapper around [`device_get_mac_address()`](#c-device_get_mac_address) which writes the address
directly to netdev->dev_addr.



#### <a id="c-netif_carrier_on"></a>`netif_carrier_on()`

```c
void netif_carrier_on(struct net_device *dev)
```

set carrier

**Parameters**

- `struct net_device *dev`: network device

**Description**

Device has detected acquisition of carrier.

#### <a id="c-netif_carrier_off"></a>`netif_carrier_off()`

```c
void netif_carrier_off(struct net_device *dev)
```

clear carrier

**Parameters**

- `struct net_device *dev`: network device

**Description**

Device has detected loss of carrier.

#### <a id="c-netif_carrier_event"></a>`netif_carrier_event()`

```c
void netif_carrier_event(struct net_device *dev)
```

report carrier state event

**Parameters**

- `struct net_device *dev`: network device

**Description**

Device has detected a carrier event but the carrier state wasn't changed.
Use in drivers when querying carrier state asynchronously, to avoid missing
events (link flaps) if link recovers before it's queried.



#### <a id="c-is_link_local_ether_addr"></a>`is_link_local_ether_addr()`

```c
bool is_link_local_ether_addr(const u8 *addr)
```

Determine if given Ethernet address is link-local

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if address is link local reserved addr (01:80:c2:00:00:0X) per
IEEE 802.1Q 8.6.3 Frame filtering.

**Description**

Please note: addr must be aligned to u16.

#### <a id="c-is_zero_ether_addr"></a>`is_zero_ether_addr()`

```c
bool is_zero_ether_addr(const u8 *addr)
```

Determine if give Ethernet address is all zeros.

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if the address is all zeroes.

**Description**

Please note: addr must be aligned to u16.

#### <a id="c-is_multicast_ether_addr"></a>`is_multicast_ether_addr()`

```c
bool is_multicast_ether_addr(const u8 *addr)
```

Determine if the Ethernet address is a multicast.

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if the address is a multicast address.
By definition the broadcast address is also a multicast address.

#### <a id="c-is_local_ether_addr"></a>`is_local_ether_addr()`

```c
bool is_local_ether_addr(const u8 *addr)
```

Determine if the Ethernet address is locally-assigned one (IEEE 802).

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if the address is a local address.

#### <a id="c-is_broadcast_ether_addr"></a>`is_broadcast_ether_addr()`

```c
bool is_broadcast_ether_addr(const u8 *addr)
```

Determine if the Ethernet address is broadcast

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if the address is the broadcast address.

**Description**

Please note: addr must be aligned to u16.

#### <a id="c-is_unicast_ether_addr"></a>`is_unicast_ether_addr()`

```c
bool is_unicast_ether_addr(const u8 *addr)
```

Determine if the Ethernet address is unicast

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

true if the address is a unicast address.

#### <a id="c-is_valid_ether_addr"></a>`is_valid_ether_addr()`

```c
bool is_valid_ether_addr(const u8 *addr)
```

Determine if the given Ethernet address is valid

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Description**

Check that the Ethernet address (MAC) is not 00:00:00:00:00:00, is not
a multicast address, and is not FF:FF:FF:FF:FF:FF.

Please note: addr must be aligned to u16.

**Return**

true if the address is valid.

#### <a id="c-eth_proto_is_802_3"></a>`eth_proto_is_802_3()`

```c
bool eth_proto_is_802_3(__be16 proto)
```

Determine if a given Ethertype/length is a protocol

**Parameters**

- `__be16 proto`: Ethertype/length value to be tested

**Description**

Check that the value from the Ethertype/length field is a valid Ethertype.

**Return**

true if the valid is an 802.3 supported Ethertype.

#### <a id="c-eth_random_addr"></a>`eth_random_addr()`

```c
void eth_random_addr(u8 *addr)
```

Generate software assigned random Ethernet address

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Description**

Generate a random Ethernet address (MAC) that is not multicast
and has the local assigned bit set.

#### <a id="c-eth_broadcast_addr"></a>`eth_broadcast_addr()`

```c
void eth_broadcast_addr(u8 *addr)
```

Assign broadcast address

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Description**

Assign the broadcast address to the given address array.

#### <a id="c-eth_zero_addr"></a>`eth_zero_addr()`

```c
void eth_zero_addr(u8 *addr)
```

Assign zero address

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Description**

Assign the zero address to the given address array.

#### <a id="c-eth_hw_addr_random"></a>`eth_hw_addr_random()`

```c
void eth_hw_addr_random(struct net_device *dev)
```

Generate software assigned random Ethernet and set device flag

**Parameters**

- `struct net_device *dev`: pointer to net_device structure

**Description**

Generate a random Ethernet address (MAC) to be used by a net device
and set addr_assign_type so the state can be read by sysfs and be
used by userspace.

#### <a id="c-eth_hw_addr_crc"></a>`eth_hw_addr_crc()`

```c
u32 eth_hw_addr_crc(struct netdev_hw_addr *ha)
```

Calculate CRC from netdev_hw_addr

**Parameters**

- `struct netdev_hw_addr *ha`: pointer to hardware address

**Description**

Calculate CRC from a hardware address as basis for filter hashes.

#### <a id="c-ether_addr_copy"></a>`ether_addr_copy()`

```c
void ether_addr_copy(u8 *dst, const u8 *src)
```

Copy an Ethernet address

**Parameters**

- `u8 *dst`: Pointer to a six-byte array Ethernet address destination
- `const u8 *src`: Pointer to a six-byte array Ethernet address source

**Description**

Please note: dst & src must both be aligned to u16.

#### <a id="c-eth_hw_addr_set"></a>`eth_hw_addr_set()`

```c
void eth_hw_addr_set(struct net_device *dev, const u8 *addr)
```

Assign Ethernet address to a net_device

**Parameters**

- `struct net_device *dev`: pointer to net_device structure
- `const u8 *addr`: address to assign

**Description**

Assign given address to the net_device, addr_assign_type is not changed.

#### <a id="c-eth_hw_addr_inherit"></a>`eth_hw_addr_inherit()`

```c
void eth_hw_addr_inherit(struct net_device *dst, struct net_device *src)
```

Copy dev_addr from another net_device

**Parameters**

- `struct net_device *dst`: pointer to net_device to copy dev_addr to
- `struct net_device *src`: pointer to net_device to copy dev_addr from

**Description**

Copy the Ethernet address from one net_device to another along with
the address attributes (addr_assign_type).

#### <a id="c-ether_addr_equal"></a>`ether_addr_equal()`

```c
bool ether_addr_equal(const u8 *addr1, const u8 *addr2)
```

Compare two Ethernet addresses

**Parameters**

- `const u8 *addr1`: Pointer to a six-byte array containing the Ethernet address
- `const u8 *addr2`: Pointer other six-byte array containing the Ethernet address

**Description**

Compare two Ethernet addresses, returns true if equal

Please note: addr1 & addr2 must both be aligned to u16.

#### <a id="c-ether_addr_equal_64bits"></a>`ether_addr_equal_64bits()`

```c
bool ether_addr_equal_64bits(const u8 *addr1, const u8 *addr2)
```

Compare two Ethernet addresses

**Parameters**

- `const u8 *addr1`: Pointer to an array of 8 bytes
- `const u8 *addr2`: Pointer to an other array of 8 bytes

**Description**

Compare two Ethernet addresses, returns true if equal, false otherwise.

The function doesn't need any conditional branches and possibly uses
word memory accesses on CPU allowing cheap unaligned memory reads.
arrays = { byte1, byte2, byte3, byte4, byte5, byte6, pad1, pad2 }

Please note that alignment of addr1 & addr2 are only guaranteed to be 16 bits.

#### <a id="c-ether_addr_equal_unaligned"></a>`ether_addr_equal_unaligned()`

```c
bool ether_addr_equal_unaligned(const u8 *addr1, const u8 *addr2)
```

Compare two not u16 aligned Ethernet addresses

**Parameters**

- `const u8 *addr1`: Pointer to a six-byte array containing the Ethernet address
- `const u8 *addr2`: Pointer other six-byte array containing the Ethernet address

**Description**

Compare two Ethernet addresses, returns true if equal

Please note: Use only when any Ethernet address may not be u16 aligned.

#### <a id="c-ether_addr_equal_masked"></a>`ether_addr_equal_masked()`

```c
bool ether_addr_equal_masked(const u8 *addr1, const u8 *addr2, const u8 *mask)
```

Compare two Ethernet addresses with a mask

**Parameters**

- `const u8 *addr1`: Pointer to a six-byte array containing the 1st Ethernet address
- `const u8 *addr2`: Pointer to a six-byte array containing the 2nd Ethernet address
- `const u8 *mask`: Pointer to a six-byte array containing the Ethernet address bitmask

**Description**

Compare two Ethernet addresses with a mask, returns true if for every bit
set in the bitmask the equivalent bits in the ethernet addresses are equal.
Using a mask with all bits set is a slower ether_addr_equal.

#### <a id="c-ether_addr_to_u64"></a>`ether_addr_to_u64()`

```c
u64 ether_addr_to_u64(const u8 *addr)
```

Convert an Ethernet address into a u64 value.

**Parameters**

- `const u8 *addr`: Pointer to a six-byte array containing the Ethernet address

**Return**

a u64 value of the address

#### <a id="c-u64_to_ether_addr"></a>`u64_to_ether_addr()`

```c
void u64_to_ether_addr(u64 u, u8 *addr)
```

Convert a u64 to an Ethernet address.

**Parameters**

- `u64 u`: u64 to convert to an Ethernet MAC address
- `u8 *addr`: Pointer to a six-byte array to contain the Ethernet address

#### <a id="c-eth_addr_dec"></a>`eth_addr_dec()`

```c
void eth_addr_dec(u8 *addr)
```

Decrement the given MAC address

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing Ethernet address to decrement

#### <a id="c-eth_addr_inc"></a>`eth_addr_inc()`

```c
void eth_addr_inc(u8 *addr)
```

Increment the given MAC address.

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing Ethernet address to increment.

#### <a id="c-eth_addr_add"></a>`eth_addr_add()`

```c
void eth_addr_add(u8 *addr, long offset)
```

Add (or subtract) an offset to/from the given MAC address.

**Parameters**

- `u8 *addr`: Pointer to a six-byte array containing Ethernet address to increment.
- `long offset`: Offset to add.

#### <a id="c-is_etherdev_addr"></a>`is_etherdev_addr()`

```c
bool is_etherdev_addr(const struct net_device *dev, const u8 addr[6 + 2])
```

Tell if given Ethernet address belongs to the device.

**Parameters**

- `const struct net_device *dev`: Pointer to a device structure
- `const u8 addr[6 + 2]`: Pointer to a six-byte array containing the Ethernet address

**Description**

Compare passed address with all addresses of the device. Return true if the
address if one of the device addresses.

Note that this function calls [`ether_addr_equal_64bits()`](#c-ether_addr_equal_64bits) so take care of
the right padding.

#### <a id="c-compare_ether_header"></a>`compare_ether_header()`

```c
unsigned long compare_ether_header(const void *a, const void *b)
```

Compare two Ethernet headers

**Parameters**

- `const void *a`: Pointer to Ethernet header
- `const void *b`: Pointer to Ethernet header

**Description**

Compare two Ethernet headers, returns 0 if equal.
This assumes that the network header (i.e., IP header) is 4-byte
aligned OR the platform can handle unaligned access.  This is the
case for all packets coming into netif_receive_skb or similar
entry points.

#### <a id="c-eth_hw_addr_gen"></a>`eth_hw_addr_gen()`

```c
void eth_hw_addr_gen(struct net_device *dev, const u8 *base_addr, unsigned int id)
```

Generate and assign Ethernet address to a port

**Parameters**

- `struct net_device *dev`: pointer to port's net_device structure
- `const u8 *base_addr`: base Ethernet address
- `unsigned int id`: offset to add to the base address

**Description**

Generate a MAC address using a base address and an offset and assign it
to a net_device. Commonly used by switch drivers which need to compute
addresses for all their ports. addr_assign_type is not changed.

#### <a id="c-eth_skb_pkt_type"></a>`eth_skb_pkt_type()`

```c
void eth_skb_pkt_type(struct sk_buff *skb, const struct net_device *dev)
```

Assign packet type if destination address does not match

**Parameters**

- `struct sk_buff *skb`: Assigned a packet type if address does not match **dev** address
- `const struct net_device *dev`: Network device used to compare packet address against

**Description**

If the destination MAC address of the packet does not match the network
device address, assign an appropriate packet type.

#### <a id="c-eth_skb_pad"></a>`eth_skb_pad()`

```c
int eth_skb_pad(struct sk_buff *skb)
```

Pad buffer to minimum number of octets for Ethernet frame

**Parameters**

- `struct sk_buff *skb`: Buffer to pad

**Description**

An Ethernet frame should have a minimum size of 60 bytes.  This function
takes short frames and pads them with zeros up to the 60 byte limit.



#### <a id="c-struct-gro_node"></a>`struct gro_node`

structure to support Generic Receive Offload

**Definition**

```c
struct gro_node {
    unsigned long           bitmask;
    struct gro_list         hash[GRO_HASH_BUCKETS];
    struct list_head        rx_list;
    u32 rx_count;
    u32 cached_napi_id;
};
```

**Members**

- `bitmask`: bitmask to indicate used buckets in **hash**
- `hash`: hashtable of pending aggregated skbs, separated by flows
- `rx_list`: list of pending `GRO_NORMAL` skbs
- `rx_count`: cached current length of **rx_list**
- `cached_napi_id`: napi_struct::napi_id cached for hotpath, 0 for standalone

#### <a id="c-napi_is_scheduled"></a>`napi_is_scheduled()`

```c
bool napi_is_scheduled(struct napi_struct *n)
```

test if NAPI is scheduled

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

This check is "best-effort". With no locking implemented,
a NAPI can be scheduled or terminate right after this check
and produce not precise results.

NAPI_STATE_SCHED is an internal state, napi_is_scheduled
should not be used normally and napi_schedule should be
used instead.

Use only if the driver really needs to check if a NAPI
is scheduled for example in the context of delayed timer
that can be skipped if a NAPI is already scheduled.

**Return**

True if NAPI is scheduled, False otherwise.

#### <a id="c-napi_schedule"></a>`napi_schedule()`

```c
bool napi_schedule(struct napi_struct *n)
```

schedule NAPI poll

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

Schedule NAPI poll routine to be called if it is not already
running.

**Return**

true if we schedule a NAPI or false if not.
Refer to [`napi_schedule_prep()`](#c-napi_schedule_prep) for additional reason on why
a NAPI might not be scheduled.

#### <a id="c-napi_schedule_irqoff"></a>`napi_schedule_irqoff()`

```c
void napi_schedule_irqoff(struct napi_struct *n)
```

schedule NAPI poll

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

Variant of [`napi_schedule()`](#c-napi_schedule), assuming hard irqs are masked.

#### <a id="c-napi_complete_done"></a>`napi_complete_done()`

```c
bool napi_complete_done(struct napi_struct *n, int work_done)
```

NAPI processing complete

**Parameters**

- `struct napi_struct *n`: NAPI context
- `int work_done`: number of packets processed

**Description**

Mark NAPI processing as complete. Should only be called if poll budget
has not been completely consumed.
Prefer over `napi_complete()`.

**Return**

false if device should avoid rearming interrupts.

#### <a id="c-napi_synchronize"></a>`napi_synchronize()`

```c
void napi_synchronize(const struct napi_struct *n)
```

wait until NAPI is not running

**Parameters**

- `const struct napi_struct *n`: NAPI context

**Description**

Wait until NAPI is done being scheduled on this context.
Waits till any outstanding processing completes but
does not disable future activations.

#### <a id="c-napi_if_scheduled_mark_missed"></a>`napi_if_scheduled_mark_missed()`

```c
bool napi_if_scheduled_mark_missed(struct napi_struct *n)
```

if napi is running, set the NAPIF_STATE_MISSED

**Parameters**

- `struct napi_struct *n`: NAPI context

**Description**

If napi is running, set the NAPIF_STATE_MISSED, and return true if
NAPI is scheduled.

#### <a id="c-enum-netdev_priv_flags"></a>`enum netdev_priv_flags`

[`struct net_device`](#c-struct-net_device) priv_flags

**Constants**

- `IFF_802_1Q_VLAN`: 802.1Q VLAN device
- `IFF_EBRIDGE`: Ethernet bridging device
- `IFF_BONDING`: bonding master or slave
- `IFF_ISATAP`: ISATAP interface (RFC4214)
- `IFF_WAN_HDLC`: WAN HDLC device
- `IFF_XMIT_DST_RELEASE`: `dev_hard_start_xmit()` is allowed to
  release skb->dst
- `IFF_DONT_BRIDGE`: disallow bridging this ether dev
- `IFF_DISABLE_NETPOLL`: disable netpoll at run-time
- `IFF_MACVLAN_PORT`: device used as macvlan port
- `IFF_BRIDGE_PORT`: device used as bridge port
- `IFF_OVS_DATAPATH`: device used as Open vSwitch datapath port
- `IFF_TX_SKB_SHARING`: The interface supports sharing skbs on transmit
- `IFF_UNICAST_FLT`: Supports unicast filtering
- `IFF_TEAM_PORT`: device used as team port
- `IFF_SUPP_NOFCS`: device supports sending custom FCS
- `IFF_LIVE_ADDR_CHANGE`: device supports hardware address
  change when it's running
- `IFF_MACVLAN`: Macvlan device
- `IFF_XMIT_DST_RELEASE_PERM`: IFF_XMIT_DST_RELEASE not taking into account
  underlying stacked devices
- `IFF_L3MDEV_MASTER`: device is an L3 master device
- `IFF_NO_QUEUE`: device can run without qdisc attached
- `IFF_OPENVSWITCH`: device is a Open vSwitch master
- `IFF_L3MDEV_SLAVE`: device is enslaved to an L3 master device
- `IFF_TEAM`: device is a team device
- `IFF_RXFH_CONFIGURED`: device has had Rx Flow indirection table configured
- `IFF_PHONY_HEADROOM`: the headroom value is controlled by an external
  entity (i.e. the master device for bridged veth)
- `IFF_MACSEC`: device is a MACsec device
- `IFF_NO_RX_HANDLER`: device doesn't support the rx_handler hook
- `IFF_FAILOVER`: device is a failover master device
- `IFF_FAILOVER_SLAVE`: device is lower dev of a failover master device
- `IFF_L3MDEV_RX_HANDLER`: only invoke the rx handler of L3 master device
- `IFF_NO_ADDRCONF`: prevent ipv6 addrconf
- `IFF_TX_SKB_NO_LINEAR`: device/driver is capable of xmitting frames with
  skb_headlen(skb) == 0 (data starts from frag0)

**Description**

These are the [`struct net_device`](#c-struct-net_device), they are only set internally
by drivers and used in the kernel. These flags are invisible to
userspace; this means that the order of these flags can change
during any kernel release.

You should add bitfield booleans after either net_device::priv_flags
(hotpath) or ::threaded (slowpath) instead of extending these flags.

#### <a id="c-struct-net_device"></a>`struct net_device`

The DEVICE structure.

**Definition**

```c
struct net_device {
        unsigned long           priv_flags:32;
        unsigned long           lltx:1;
        unsigned long           netmem_tx:1;
        const struct net_device_ops *netdev_ops;
        const struct header_ops *header_ops;
        struct netdev_queue     *_tx;
        netdev_features_t gso_partial_features;
        unsigned int            real_num_tx_queues;
        unsigned int            gso_max_size;
        unsigned int            gso_ipv4_max_size;
        u16 gso_max_segs;
        s16 num_tc;
        unsigned int            mtu;
        unsigned short          needed_headroom;
        struct netdev_tc_txq    tc_to_txq[TC_MAX_QUEUE];
    #ifdef CONFIG_XPS;
        struct xps_dev_maps  *xps_maps[XPS_MAPS_MAX];
    #endif;
    #ifdef CONFIG_NETFILTER_EGRESS;
        struct nf_hook_entries  *nf_hooks_egress;
    #endif;
    #ifdef CONFIG_NET_XGRESS;
        struct bpf_mprog_entry  *tcx_egress;
    #endif;
        union {
            struct pcpu_lstats __percpu             *lstats;
            struct pcpu_sw_netstats __percpu        *tstats;
            struct pcpu_dstats __percpu             *dstats;
        };
        unsigned long           state;
        unsigned int            flags;
        unsigned short          hard_header_len;
        enum netdev_stat_type   pcpu_stat_type:8;
        netdev_features_t features;
        struct inet6_dev   *ip6_ptr;
        struct bpf_prog    *xdp_prog;
        struct list_head        ptype_specific;
        int ifindex;
        unsigned int            real_num_rx_queues;
        struct netdev_rx_queue  *_rx;
        unsigned int            gro_max_size;
        unsigned int            gro_ipv4_max_size;
        rx_handler_func_t *rx_handler;
        void *rx_handler_data;
        possible_net_t nd_net;
    #ifdef CONFIG_NETPOLL;
        struct netpoll_info        *npinfo;
    #endif;
    #ifdef CONFIG_NET_XGRESS;
        struct bpf_mprog_entry  *tcx_ingress;
    #endif;
        char name[IFNAMSIZ];
        struct netdev_name_node *name_node;
        struct dev_ifalias  *ifalias;
        unsigned long           mem_end;
        unsigned long           mem_start;
        unsigned long           base_addr;
        struct list_head        dev_list;
        struct list_head        napi_list;
        struct list_head        unreg_list;
        struct list_head        close_list;
        struct list_head        ptype_all;
        struct {
            struct list_head upper;
            struct list_head lower;
        } adj_list;
        xdp_features_t xdp_features;
        const struct xdp_metadata_ops *xdp_metadata_ops;
        const struct xsk_tx_metadata_ops *xsk_tx_metadata_ops;
        unsigned short          gflags;
        unsigned short          needed_tailroom;
        netdev_features_t hw_features;
        netdev_features_t wanted_features;
        netdev_features_t vlan_features;
        netdev_features_t hw_enc_features;
        netdev_features_t mpls_features;
        netdev_features_t mangleid_features;
        unsigned int            min_mtu;
        unsigned int            max_mtu;
        unsigned short          type;
        unsigned char           min_header_len;
        unsigned char           name_assign_type;
        int group;
        struct net_device_stats stats;
        struct net_device_core_stats __percpu *core_stats;
        atomic_t carrier_up_count;
        atomic_t carrier_down_count;
    #ifdef CONFIG_WIRELESS_EXT;
        const struct iw_handler_def *wireless_handlers;
    #endif;
        const struct ethtool_ops *ethtool_ops;
    #ifdef CONFIG_NET_L3_MASTER_DEV;
        const struct l3mdev_ops *l3mdev_ops;
    #endif;
    #if IS_ENABLED(CONFIG_IPV6);
        const struct ndisc_ops *ndisc_ops;
    #endif;
    #ifdef CONFIG_XFRM_OFFLOAD;
        const struct xfrmdev_ops *xfrmdev_ops;
    #endif;
    #if IS_ENABLED(CONFIG_TLS_DEVICE);
        const struct tlsdev_ops *tlsdev_ops;
    #endif;
        unsigned int            operstate;
        unsigned char           link_mode;
        unsigned char           if_port;
        unsigned char           dma;
        unsigned char           perm_addr[MAX_ADDR_LEN];
        unsigned char           addr_assign_type;
        unsigned char           addr_len;
        unsigned char           upper_level;
        unsigned char           lower_level;
        u8 threaded;
        unsigned short          neigh_priv_len;
        unsigned short          dev_id;
        unsigned short          dev_port;
        int irq;
        u32 priv_len;
        spinlock_t addr_list_lock;
        struct netdev_hw_addr_list      uc;
        struct netdev_hw_addr_list      mc;
        struct netdev_hw_addr_list      dev_addrs;
    #ifdef CONFIG_SYSFS;
        struct kset             *queues_kset;
    #endif;
    #ifdef CONFIG_LOCKDEP;
        struct list_head        unlink_list;
    #endif;
        unsigned int            promiscuity;
        unsigned int            allmulti;
        bool uc_promisc;
    #ifdef CONFIG_LOCKDEP;
        unsigned char           nested_level;
    #endif;
        struct in_device   *ip_ptr;
        struct hlist_head       fib_nh_head;
    #if IS_ENABLED(CONFIG_VLAN_8021Q);
        struct vlan_info   *vlan_info;
    #endif;
    #if IS_ENABLED(CONFIG_NET_DSA);
        struct dsa_port         *dsa_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_TIPC);
        struct tipc_bearer  *tipc_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_ATALK);
        void *atalk_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_AX25);
        struct ax25_dev    *ax25_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_CFG80211);
        struct wireless_dev     *ieee80211_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_IEEE802154) || IS_ENABLED(CONFIG_6LOWPAN);
        struct wpan_dev         *ieee802154_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_MPLS_ROUTING);
        struct mpls_dev    *mpls_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_MCTP);
        struct mctp_dev    *mctp_ptr;
    #endif;
    #if IS_ENABLED(CONFIG_INET_PSP);
        struct psp_dev     *psp_dev;
    #endif;
        const unsigned char     *dev_addr;
        unsigned int            num_rx_queues;
    #define GRO_LEGACY_MAX_SIZE     65536u;
    #define GRO_MAX_SIZE            (8 * 65535u);
        unsigned int            xdp_zc_max_segs;
        struct netdev_queue  *ingress_queue;
    #ifdef CONFIG_NETFILTER_INGRESS;
        struct nf_hook_entries  *nf_hooks_ingress;
    #endif;
        unsigned char           broadcast[MAX_ADDR_LEN];
    #ifdef CONFIG_RFS_ACCEL;
        struct cpu_rmap         *rx_cpu_rmap;
    #endif;
        struct hlist_node       index_hlist;
        unsigned int            num_tx_queues;
        struct Qdisc       *qdisc;
        unsigned int            tx_queue_len;
        spinlock_t tx_global_lock;
        struct xdp_dev_bulk_queue __percpu *xdp_bulkq;
    #ifdef CONFIG_NET_SCHED;
        unsigned long qdisc_hash[1 << ((4) - 1)];
    #endif;
        struct timer_list       watchdog_timer;
        int watchdog_timeo;
        u32 proto_down_reason;
        struct list_head        todo_list;
    #ifdef CONFIG_PCPU_DEV_REFCNT;
        int __percpu            *pcpu_refcnt;
    #else;
        refcount_t dev_refcnt;
    #endif;
        struct ref_tracker_dir  refcnt_tracker;
        struct list_head        link_watch_list;
        u8 reg_state;
        bool dismantle;
        bool moving_ns;
        bool rtnl_link_initializing;
        bool needs_free_netdev;
        void (*priv_destructor)(struct net_device *dev);
        void *ml_priv;
        enum netdev_ml_priv_type        ml_priv_type;
    #if IS_ENABLED(CONFIG_GARP);
        struct garp_port   *garp_port;
    #endif;
    #if IS_ENABLED(CONFIG_MRP);
        struct mrp_port    *mrp_port;
    #endif;
    #if IS_ENABLED(CONFIG_NET_DROP_MONITOR);
        struct dm_hw_stat_delta  *dm_private;
    #endif;
        struct device           dev;
        const struct attribute_group *sysfs_groups[5];
        const struct attribute_group *sysfs_rx_queue_group;
        const struct rtnl_link_ops *rtnl_link_ops;
        const struct netdev_stat_ops *stat_ops;
        const struct netdev_queue_mgmt_ops *queue_mgmt_ops;
    #define GSO_MAX_SEGS            65535u;
    #define GSO_LEGACY_MAX_SIZE     65536u;
    #define GSO_MAX_SIZE            (8 * GSO_MAX_SEGS);
    #define TSO_LEGACY_MAX_SIZE     65536;
    #define TSO_MAX_SIZE            UINT_MAX;
        unsigned int            tso_max_size;
    #define TSO_MAX_SEGS            U16_MAX;
        u16 tso_max_segs;
    #ifdef CONFIG_DCB;
        const struct dcbnl_rtnl_ops *dcbnl_ops;
    #endif;
        u8 prio_tc_map[TC_BITMASK + 1];
    #if IS_ENABLED(CONFIG_FCOE);
        unsigned int            fcoe_ddp_xid;
    #endif;
    #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO);
        struct netprio_map  *priomap;
    #endif;
        struct phy_link_topology        *link_topo;
        struct phy_device       *phydev;
        struct sfp_bus          *sfp_bus;
        struct lock_class_key   *qdisc_tx_busylock;
        bool proto_down;
        bool irq_affinity_auto;
        bool rx_cpu_rmap_auto;
        unsigned long           see_all_hwtstamp_requests:1;
        unsigned long           change_proto_down:1;
        unsigned long           netns_immutable:1;
        unsigned long           fcoe_mtu:1;
        struct list_head        net_notifier_list;
    #if IS_ENABLED(CONFIG_MACSEC);
        const struct macsec_ops *macsec_ops;
    #endif;
        const struct udp_tunnel_nic_info        *udp_tunnel_nic_info;
        struct udp_tunnel_nic   *udp_tunnel_nic;
        struct netdev_config    *cfg;
        struct netdev_config    *cfg_pending;
        struct ethtool_netdev_state *ethtool;
        struct bpf_xdp_entity   xdp_state[__MAX_XDP_MODE];
        u8 dev_addr_shadow[MAX_ADDR_LEN];
        netdevice_tracker linkwatch_dev_tracker;
        netdevice_tracker watchdog_dev_tracker;
        netdevice_tracker dev_registered_tracker;
        struct rtnl_hw_stats64  *offload_xstats_l3;
        struct devlink_port     *devlink_port;
    #if IS_ENABLED(CONFIG_DPLL);
        struct dpll_pin    *dpll_pin;
    #endif;
    #if IS_ENABLED(CONFIG_PAGE_POOL);
        struct hlist_head       page_pools;
    #endif;
        struct dim_irq_moder    *irq_moder;
        u64 max_pacing_offload_horizon;
        struct napi_config      *napi_config;
        u32 num_napi_configs;
        u32 napi_defer_hard_irqs;
        unsigned long           gro_flush_timeout;
        bool up;
        bool request_ops_lock;
        struct mutex            lock;
    #if IS_ENABLED(CONFIG_NET_SHAPER);
        struct net_shaper_hierarchy *net_shaper_hierarchy;
    #endif;
        struct hlist_head neighbours[NEIGH_NR_TABLES];
        struct hwtstamp_provider   *hwprov;
        u8 priv[]  ;
};
```

**Members**

- `priv_flags`: flags invisible to userspace defined as bits, see
  enum netdev_priv_flags for the definitions
- `lltx`: device supports lockless Tx. Deprecated for real HW
  drivers. Mainly used by logical interfaces, such as
  bonding and tunnels
- `netmem_tx`: device support netmem_tx.
- `netdev_ops`: Includes several pointers to callbacks,
  if one wants to override the ndo_*() functions
- `header_ops`: Includes callbacks for creating,parsing,caching,etc
  of Layer 2 headers.
- `_tx`: Array of TX queues
- `gso_partial_features`: value(s) from NETIF_F_GSO\*
- `real_num_tx_queues`: Number of TX queues currently active in device
- `gso_max_size`: Maximum size of generic segmentation offload
- `gso_ipv4_max_size`: Maximum size of generic segmentation offload,
  for IPv4.
- `gso_max_segs`: Maximum number of segments that can be passed to the
  NIC for GSO
- `num_tc`: Number of traffic classes in the net device
- `mtu`: Interface MTU value
- `needed_headroom`: Extra headroom the hardware may need, but not in all
  cases can this be guaranteed
- `tc_to_txq`: XXX: need comments on this one
- `xps_maps`: XXX: need comments on this one
- `nf_hooks_egress`: netfilter hooks executed for egress packets
- `tcx_egress`: BPF & clsact qdisc specific data for egress processing
- `{unnamed_union}`: anonymous
- `lstats`: Loopback statistics: packets, bytes
- `tstats`: Tunnel statistics: RX/TX packets, RX/TX bytes
- `dstats`: Dummy statistics: RX/TX/drop packets, RX/TX bytes
- `state`: Generic network queuing layer state, see netdev_state_t
- `flags`: Interface flags (a la BSD)
- `hard_header_len`: Maximum hardware header length.
- `pcpu_stat_type`: Type of device statistics which the core should
  allocate/free: none, lstats, tstats, dstats. none
  means the driver is handling statistics allocation/
  freeing internally.
- `features`: Currently active device features
- `ip6_ptr`: IPv6 specific data
- `xdp_prog`: XDP sockets filter program pointer
- `ptype_specific`: Device-specific, protocol-specific packet handlers
- `ifindex`: interface index
- `real_num_rx_queues`: Number of RX queues currently active in device
- `_rx`: Array of RX queues
- `gro_max_size`: Maximum size of aggregated packet in generic
  receive offload (GRO)
- `gro_ipv4_max_size`: Maximum size of aggregated packet in generic
  receive offload (GRO), for IPv4.
- `rx_handler`: handler for received packets
- `rx_handler_data`: XXX: need comments on this one
- `nd_net`: Network namespace this network device is inside
  protected by **lock**
- `npinfo`: XXX: need comments on this one
- `tcx_ingress`: BPF & clsact qdisc specific data for ingress processing
- `name`: This is the first field of the "visible" part of this structure
  (i.e. as seen by users in the "Space.c" file).  It is the name
  of the interface.
- `name_node`: Name hashlist node
- `ifalias`: SNMP alias
- `mem_end`: Shared memory end
- `mem_start`: Shared memory start
- `base_addr`: Device I/O address
- `dev_list`: The global list of network devices
- `napi_list`: List entry used for polling NAPI devices
- `unreg_list`: List entry  when we are unregistering the
  device; see the function unregister_netdev
- `close_list`: List entry used when we are closing the device
- `ptype_all`: Device-specific packet handlers for all protocols
- `adj_list`: Directly linked devices, like slaves for bonding
- `xdp_features`: XDP capability supported by the device
- `xdp_metadata_ops`: Includes pointers to XDP metadata callbacks.
- `xsk_tx_metadata_ops`: Includes pointers to AF_XDP TX metadata callbacks.
- `gflags`: Global flags ( kept as legacy )
- `needed_tailroom`: Extra tailroom the hardware may need, but not in all
  cases can this be guaranteed. Some cases also use
  LL_MAX_HEADER instead to allocate the skb
- `hw_features`: User-changeable features
- `wanted_features`: User-requested features
- `vlan_features`: Mask of features inheritable by VLAN devices
- `hw_enc_features`: Mask of features inherited by encapsulating devices
  This field indicates what encapsulation
  offloads the hardware is capable of doing,
  and drivers will need to set them appropriately.
- `mpls_features`: Mask of features inheritable by MPLS
- `mangleid_features`: Mask of features requiring MANGLEID, will be
  disabled together with the latter.
- `min_mtu`: Interface Minimum MTU value
- `max_mtu`: Interface Maximum MTU value
- `type`: Interface hardware type
- `min_header_len`: Minimum hardware header length
- `name_assign_type`: network interface name assignment type
- `group`: The group the device belongs to
- `stats`: Statistics struct, which was left as a legacy, use
  rtnl_link_stats64 instead
- `core_stats`: core networking counters,
  do not use this in drivers
- `carrier_up_count`: Number of times the carrier has been up
- `carrier_down_count`: Number of times the carrier has been down
- `wireless_handlers`: List of functions to handle Wireless Extensions,
  instead of ioctl,
  see \<net/iw_handler.h> for details.
- `ethtool_ops`: Management operations
- `l3mdev_ops`: Layer 3 master device operations
- `ndisc_ops`: Includes callbacks for different IPv6 neighbour
  discovery handling. Necessary for e.g. 6LoWPAN.
- `xfrmdev_ops`: Transformation offload operations
- `tlsdev_ops`: Transport Layer Security offload operations
- `operstate`: RFC2863 operstate
- `link_mode`: Mapping policy to operstate
- `if_port`: Selectable AUI, TP, ...
- `dma`: DMA channel
- `perm_addr`: Permanent hw address
- `addr_assign_type`: Hw address assignment type
- `addr_len`: Hardware address length
- `upper_level`: Maximum depth level of upper devices.
- `lower_level`: Maximum depth level of lower devices.
- `threaded`: napi threaded state.
- `neigh_priv_len`: Used in `neigh_alloc()`
- `dev_id`: Used to differentiate devices that share
  the same link layer address
- `dev_port`: Used to differentiate devices that share
  the same function
- `irq`: Device IRQ number
- `priv_len`: Size of the ->priv flexible array
- `addr_list_lock`: XXX: need comments on this one
- `uc`: unicast mac addresses
- `mc`: multicast mac addresses
- `dev_addrs`: list of device hw addresses
- `queues_kset`: Group of all Kobjects in the Tx and RX queues
- `unlink_list`: As `netif_addr_lock()` can be called recursively,
  keep a list of interfaces to be deleted.
- `promiscuity`: Number of times the NIC is told to work in
  promiscuous mode; if it becomes 0 the NIC will
  exit promiscuous mode
- `allmulti`: Counter, enables or disables allmulticast mode
- `uc_promisc`: Counter that indicates promiscuous mode
  has been enabled due to the need to listen to
  additional unicast addresses in a device that
  does not implement `ndo_set_rx_mode()`
- `nested_level`: Used as a parameter of `spin_lock_nested()` of
  dev->addr_list_lock.
- `ip_ptr`: IPv4 specific data
- `fib_nh_head`: nexthops associated with this netdev
- `vlan_info`: VLAN info
- `dsa_ptr`: dsa specific data
- `tipc_ptr`: TIPC specific data
- `atalk_ptr`: AppleTalk link
- `ax25_ptr`: AX.25 specific data
- `ieee80211_ptr`: IEEE 802.11 specific data, assign before registering
- `ieee802154_ptr`: IEEE 802.15.4 low-rate Wireless Personal Area Network
  device struct
- `mpls_ptr`: mpls_dev struct pointer
- `mctp_ptr`: MCTP specific data
- `psp_dev`: PSP crypto device registered for this netdev
- `dev_addr`: Hw address (before bcast,
  because most packets are unicast)
- `num_rx_queues`: Number of RX queues
  allocated at [`register_netdev()`](#c-register_netdev) time
- `xdp_zc_max_segs`: Maximum number of segments supported by AF_XDP
  zero copy driver
- `ingress_queue`: XXX: need comments on this one
- `nf_hooks_ingress`: netfilter hooks executed for ingress packets
- `broadcast`: hw bcast address
- `rx_cpu_rmap`: CPU reverse-mapping for RX completion interrupts,
  indexed by RX queue number. Assigned by driver.
  This must only be set if the ndo_rx_flow_steer
  operation is defined
- `index_hlist`: Device index hash chain
- `num_tx_queues`: Number of TX queues allocated at `alloc_netdev_mq()` time
- `qdisc`: Root qdisc from userspace point of view
- `tx_queue_len`: Max frames per queue allowed
- `tx_global_lock`: XXX: need comments on this one
- `xdp_bulkq`: XDP device bulk queue
- `qdisc_hash`: qdisc hash table
- `watchdog_timer`: List of timers
- `watchdog_timeo`: Represents the timeout that is used by
  the watchdog (see `dev_watchdog()`)
- `proto_down_reason`: reason a netdev interface is held down
- `todo_list`: Delayed register/unregister
- `pcpu_refcnt`: Number of references to this device
- `dev_refcnt`: Number of references to this device
- `refcnt_tracker`: Tracker directory for tracked references to this device
- `link_watch_list`: XXX: need comments on this one
- `reg_state`: Register/unregister state machine
- `dismantle`: Device is going to be freed
- `moving_ns`: device is changing netns, protected by **lock**
- `rtnl_link_initializing`: Device being created, suppress events
- `needs_free_netdev`: Should unregister perform free_netdev?
- `priv_destructor`: Called from unregister
- `ml_priv`: Mid-layer private
- `ml_priv_type`: Mid-layer private type
- `garp_port`: GARP
- `mrp_port`: MRP
- `dm_private`: Drop monitor private
- `dev`: Class/net/name entry
- `sysfs_groups`: Space for optional device, statistics and wireless
  sysfs groups
- `sysfs_rx_queue_group`: Space for optional per-rx queue attributes
- `rtnl_link_ops`: Rtnl_link_ops
- `stat_ops`: Optional ops for queue-aware statistics
- `queue_mgmt_ops`: Optional ops for queue management
- `tso_max_size`: Device (as in HW) limit on the max TSO request size
- `tso_max_segs`: Device (as in HW) limit on the max TSO segment count
- `dcbnl_ops`: Data Center Bridging netlink ops
- `prio_tc_map`: XXX: need comments on this one
- `fcoe_ddp_xid`: Max exchange id for FCoE LRO by ddp
- `priomap`: XXX: need comments on this one
- `link_topo`: Physical link topology tracking attached PHYs
- `phydev`: Physical device may attach itself
  for hardware timestamping
- `sfp_bus`: attached [`struct sfp_bus`](#c-struct-sfp_bus) structure.
- `qdisc_tx_busylock`: lockdep class annotating Qdisc->busylock spinlock
- `proto_down`: protocol port state information can be sent to the
  switch driver and used to set the phys state of the
  switch port.
- `irq_affinity_auto`: driver wants the core to store and re-assign the IRQ
  affinity. Set by `netif_enable_irq_affinity()`, then
  the driver must create a persistent napi by
  [`netif_napi_add_config()`](#c-netif_napi_add_config) and finally bind the napi to
  IRQ (via `netif_napi_set_irq()`).
- `rx_cpu_rmap_auto`: driver wants the core to manage the ARFS rmap.
  Set by calling `netif_enable_cpu_rmap()`.
- `see_all_hwtstamp_requests`: device wants to see calls to
  `ndo_hwtstamp_set()` for all timestamp requests
  regardless of source, even if those aren't
  HWTSTAMP_SOURCE_NETDEV
- `change_proto_down`: device supports setting carrier via IFLA_PROTO_DOWN
- `netns_immutable`: interface can't change network namespaces
- `fcoe_mtu`: device supports maximum FCoE MTU, 2158 bytes
- `net_notifier_list`: List of per-net netdev notifier block
  that follow this device when it is moved
  to another network namespace.
- `macsec_ops`: MACsec offloading ops
- `udp_tunnel_nic_info`: static structure describing the UDP tunnel
  offload capabilities of the device
- `udp_tunnel_nic`: UDP tunnel offload state
- `cfg`: net_device queue-related configuration
- `cfg_pending`:

  - same as **cfg** but when device is being actively

    reconfigured includes any changes to the configuration
    requested by the user, but which may or may not be rejected.
- `ethtool`: ethtool related state
- `xdp_state`: stores info on attached XDP BPF programs
- `dev_addr_shadow`: Copy of **dev_addr** to catch direct writes.
- `linkwatch_dev_tracker`: refcount tracker used by linkwatch.
- `watchdog_dev_tracker`: refcount tracker used by watchdog.
- `dev_registered_tracker`: tracker for reference held while
  registered
- `offload_xstats_l3`: L3 HW stats for this netdevice.
- `devlink_port`: Pointer to related devlink port structure.
  Assigned by a driver before netdev registration using
  SET_NETDEV_DEVLINK_PORT macro. This pointer is static
  during the time netdevice is registered.
- `dpll_pin`: Pointer to the SyncE source pin of a DPLL subsystem,
  where the clock is recovered.
- `page_pools`: page pools created for this netdevice
- `irq_moder`: dim parameters used if IS_ENABLED(CONFIG_DIMLIB).
- `max_pacing_offload_horizon`: max EDT offload horizon in nsec.
- `napi_config`: An array of napi_config structures containing per-NAPI
  settings.
- `num_napi_configs`: number of allocated NAPI config structs,
  always >= max(num_rx_queues, num_tx_queues).
- `napi_defer_hard_irqs`: If not zero, provides a counter that would
  allow to avoid NIC hard IRQ, on busy queues.
- `gro_flush_timeout`: timeout for GRO layer in NAPI
- `up`:

  - copy of **state**'s IFF_UP, but safe to read with just **lock**.

    May report false negatives while the device is being opened
    or closed (**lock** does not protect .ndo_open, or .ndo_close).
- `request_ops_lock`: request the core to run all **netdev_ops** and
  **ethtool_ops** under the **lock**.
- `lock`: netdev-scope lock, protects a small selection of fields.
  Should always be taken using `netdev_lock()` / `netdev_unlock()` helpers.
  Drivers are free to use it for other protection.

  For the drivers that implement shaper or queue API, the scope
  of this lock is expanded to cover most ndo/queue/ethtool/sysfs
  operations. Drivers may opt-in to this behavior by setting
  **request_ops_lock**.

  **lock** protection mixes with rtnl_lock in multiple ways, fields are
  either:

  - simply protected by the instance **lock**;

  - double protected - writers hold both locks, readers hold either;

  - ops protected - protected by the lock held around the NDOs
    and other callbacks, that is the instance lock on devices for
    which `netdev_need_ops_lock()` returns true, otherwise by rtnl_lock;

  - double ops protected - always protected by rtnl_lock but for
    devices for which `netdev_need_ops_lock()` returns true - also
    the instance lock.

  Simply protects:
  **gro_flush_timeout**, **napi_defer_hard_irqs**, **napi_list**,
  **net_shaper_hierarchy**, **reg_state**, **threaded**

  - Double protects:
    **up**, **moving_ns**, **nd_net**, **xdp_features**

  - Double ops protects:
    **real_num_rx_queues**, **real_num_tx_queues**

  - Also protects some fields in:
    struct napi_struct, struct netdev_queue, struct netdev_rx_queue

  Ordering: take after rtnl_lock.
- `net_shaper_hierarchy`:

  - data tracking the current shaper status

    see include/net/net_shapers.h
- `neighbours`: List heads pointing to this device's neighbours'
  dev_list, one per address-family.
- `hwprov`: Tracks which PTP performs hardware packet time stamping.
- `priv`: Flexible array containing private data

**Description**

Actually, this whole structure is a big mistake.  It mixes I/O
data with strictly "high-level" data, and it has to know about
almost every data structure used in the INET module.

interface address info:

FIXME: cleanup struct net_device such that network protocol info
moves out.

#### <a id="c-netdev_priv"></a>`netdev_priv()`

```c
void * netdev_priv(const struct net_device *dev)
```

access network device private data

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Get network device private data

#### <a id="c-netif_napi_add"></a>`netif_napi_add()`

```c
void netif_napi_add(struct net_device *dev, struct napi_struct *napi, int (*poll)(struct napi_struct *, int))
```

initialize a NAPI context

**Parameters**

- `struct net_device *dev`: network device
- `struct napi_struct *napi`: NAPI context
- `int (*poll)(struct napi_struct *, int)`: polling function

**Description**

[`netif_napi_add()`](#c-netif_napi_add) must be used to initialize a NAPI context prior to calling
*any* of the other NAPI-related functions.

#### <a id="c-netif_napi_add_config"></a>`netif_napi_add_config()`

```c
void netif_napi_add_config(struct net_device *dev, struct napi_struct *napi, int (*poll)(struct napi_struct *, int), int index)
```

initialize a NAPI context with persistent config

**Parameters**

- `struct net_device *dev`: network device
- `struct napi_struct *napi`: NAPI context
- `int (*poll)(struct napi_struct *, int)`: polling function
- `int index`: the NAPI index

#### <a id="c-netif_napi_add_tx"></a>`netif_napi_add_tx()`

```c
void netif_napi_add_tx(struct net_device *dev, struct napi_struct *napi, int (*poll)(struct napi_struct *, int))
```

initialize a NAPI context to be used for Tx only

**Parameters**

- `struct net_device *dev`: network device
- `struct napi_struct *napi`: NAPI context
- `int (*poll)(struct napi_struct *, int)`: polling function

**Description**

This variant of [`netif_napi_add()`](#c-netif_napi_add) should be used from drivers using NAPI
to exclusively poll a TX queue.
This will avoid we add it into napi_hash\[\], thus polluting this hash table.

#### <a id="c-__netif_napi_del"></a>`__netif_napi_del()`

```c
void __netif_napi_del(struct napi_struct *napi)
```

remove a NAPI context

**Parameters**

- `struct napi_struct *napi`: NAPI context

**Description**

Warning: caller must observe RCU grace period before freeing memory
containing **napi**. Drivers might want to call this helper to combine
all the needed RCU grace periods into a single one.

#### <a id="c-netif_napi_del"></a>`netif_napi_del()`

```c
void netif_napi_del(struct napi_struct *napi)
```

remove a NAPI context

**Parameters**

- `struct napi_struct *napi`: NAPI context

**Description**

[`netif_napi_del()`](#c-netif_napi_del) removes a NAPI context from the network device NAPI list

#### <a id="c-netif_start_queue"></a>`netif_start_queue()`

```c
void netif_start_queue(struct net_device *dev)
```

allow transmit

**Parameters**

- `struct net_device *dev`: network device

**Description**

Allow upper layers to call the device hard_start_xmit routine.

#### <a id="c-netif_wake_queue"></a>`netif_wake_queue()`

```c
void netif_wake_queue(struct net_device *dev)
```

restart transmit

**Parameters**

- `struct net_device *dev`: network device

**Description**

Allow upper layers to call the device hard_start_xmit routine.
Used for flow control when transmit resources are available.

#### <a id="c-netif_stop_queue"></a>`netif_stop_queue()`

```c
void netif_stop_queue(struct net_device *dev)
```

stop transmitted packets

**Parameters**

- `struct net_device *dev`: network device

**Description**

Stop upper layers calling the device hard_start_xmit routine.
Used for flow control when transmit resources are unavailable.

#### <a id="c-netif_queue_stopped"></a>`netif_queue_stopped()`

```c
bool netif_queue_stopped(const struct net_device *dev)
```

test if transmit queue is flowblocked

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Test if transmit queue on device is currently unable to send.

#### <a id="c-netdev_queue_set_dql_min_limit"></a>`netdev_queue_set_dql_min_limit()`

```c
void netdev_queue_set_dql_min_limit(struct netdev_queue *dev_queue, unsigned int min_limit)
```

set dql minimum limit

**Parameters**

- `struct netdev_queue *dev_queue`: pointer to transmit queue
- `unsigned int min_limit`: dql minimum limit

**Description**

Forces `xmit_more()` to return true until the minimum threshold
defined by **min_limit** is reached (or until the tx queue is
empty). Warning: to be use with care, misuse will impact the
latency.

#### <a id="c-netdev_txq_bql_enqueue_prefetchw"></a>`netdev_txq_bql_enqueue_prefetchw()`

```c
void netdev_txq_bql_enqueue_prefetchw(struct netdev_queue *dev_queue)
```

prefetch bql data for write

**Parameters**

- `struct netdev_queue *dev_queue`: pointer to transmit queue

**Description**

BQL enabled drivers might use this helper in their `ndo_start_xmit()`,
to give appropriate hint to the CPU.

#### <a id="c-netdev_txq_bql_complete_prefetchw"></a>`netdev_txq_bql_complete_prefetchw()`

```c
void netdev_txq_bql_complete_prefetchw(struct netdev_queue *dev_queue)
```

prefetch bql data for write

**Parameters**

- `struct netdev_queue *dev_queue`: pointer to transmit queue

**Description**

BQL enabled drivers might use this helper in their TX completion path,
to give appropriate hint to the CPU.

#### <a id="c-netdev_tx_sent_queue"></a>`netdev_tx_sent_queue()`

```c
void netdev_tx_sent_queue(struct netdev_queue *dev_queue, unsigned int bytes)
```

report the number of bytes queued to a given tx queue

**Parameters**

- `struct netdev_queue *dev_queue`: network device queue
- `unsigned int bytes`: number of bytes queued to the device queue

**Description**

Report the number of bytes queued for sending/completion to the network
device hardware queue. **bytes** should be a good approximation and should
exactly match [`netdev_completed_queue()`](#c-netdev_completed_queue) **bytes**.
This is typically called once per packet, from `ndo_start_xmit()`.

#### <a id="c-netdev_sent_queue"></a>`netdev_sent_queue()`

```c
void netdev_sent_queue(struct net_device *dev, unsigned int bytes)
```

report the number of bytes queued to hardware

**Parameters**

- `struct net_device *dev`: network device
- `unsigned int bytes`: number of bytes queued to the hardware device queue

**Description**

Report the number of bytes queued for sending/completion to the network
device hardware queue#0. **bytes** should be a good approximation and should
exactly match [`netdev_completed_queue()`](#c-netdev_completed_queue) **bytes**.
This is typically called once per packet, from `ndo_start_xmit()`.

#### <a id="c-netdev_tx_completed_queue"></a>`netdev_tx_completed_queue()`

```c
void netdev_tx_completed_queue(struct netdev_queue *dev_queue, unsigned int pkts, unsigned int bytes)
```

report number of packets/bytes at TX completion.

**Parameters**

- `struct netdev_queue *dev_queue`: network device queue
- `unsigned int pkts`: number of packets (currently ignored)
- `unsigned int bytes`: number of bytes dequeued from the device queue

**Description**

Must be called at most once per TX completion round (and not per
individual packet), so that BQL can adjust its limits appropriately.

#### <a id="c-netdev_completed_queue"></a>`netdev_completed_queue()`

```c
void netdev_completed_queue(struct net_device *dev, unsigned int pkts, unsigned int bytes)
```

report bytes and packets completed by device

**Parameters**

- `struct net_device *dev`: network device
- `unsigned int pkts`: actual number of packets sent over the medium
- `unsigned int bytes`: actual number of bytes sent over the medium

**Description**

Report the number of bytes and packets transmitted by the network device
hardware queue over the physical medium, **bytes** must exactly match the
**bytes** amount passed to [`netdev_sent_queue()`](#c-netdev_sent_queue)

#### <a id="c-netdev_tx_reset_subqueue"></a>`netdev_tx_reset_subqueue()`

```c
void netdev_tx_reset_subqueue(const struct net_device *dev, u32 qid)
```

reset the BQL stats and state of a netdev queue

**Parameters**

- `const struct net_device *dev`: network device
- `u32 qid`: stack index of the queue to reset

#### <a id="c-netdev_reset_queue"></a>`netdev_reset_queue()`

```c
void netdev_reset_queue(struct net_device *dev_queue)
```

reset the packets and bytes count of a network device

**Parameters**

- `struct net_device *dev_queue`: network device

**Description**

Reset the bytes and packet count of a network device and clear the
software flow control OFF bit for this network device

#### <a id="c-netdev_cap_txqueue"></a>`netdev_cap_txqueue()`

```c
u16 netdev_cap_txqueue(struct net_device *dev, u16 queue_index)
```

check if selected tx queue exceeds device queues

**Parameters**

- `struct net_device *dev`: network device
- `u16 queue_index`: given tx queue index

**Description**

Returns 0 if given tx queue index >= number of device tx queues,
otherwise returns the originally passed tx queue index.

#### <a id="c-netif_running"></a>`netif_running()`

```c
bool netif_running(const struct net_device *dev)
```

test if up

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Test if the device has been brought up.

#### <a id="c-netif_start_subqueue"></a>`netif_start_subqueue()`

```c
void netif_start_subqueue(struct net_device *dev, u16 queue_index)
```

allow sending packets on subqueue

**Parameters**

- `struct net_device *dev`: network device
- `u16 queue_index`: sub queue index

**Description**

Start individual transmit queue of a device with multiple transmit queues.

#### <a id="c-netif_stop_subqueue"></a>`netif_stop_subqueue()`

```c
void netif_stop_subqueue(struct net_device *dev, u16 queue_index)
```

stop sending packets on subqueue

**Parameters**

- `struct net_device *dev`: network device
- `u16 queue_index`: sub queue index

**Description**

Stop individual transmit queue of a device with multiple transmit queues.

#### <a id="c-__netif_subqueue_stopped"></a>`__netif_subqueue_stopped()`

```c
bool __netif_subqueue_stopped(const struct net_device *dev, u16 queue_index)
```

test status of subqueue

**Parameters**

- `const struct net_device *dev`: network device
- `u16 queue_index`: sub queue index

**Description**

Check individual transmit queue of a device with multiple transmit queues.

#### <a id="c-netif_subqueue_stopped"></a>`netif_subqueue_stopped()`

```c
bool netif_subqueue_stopped(const struct net_device *dev, struct sk_buff *skb)
```

test status of subqueue

**Parameters**

- `const struct net_device *dev`: network device
- `struct sk_buff *skb`: sub queue buffer pointer

**Description**

Check individual transmit queue of a device with multiple transmit queues.

#### <a id="c-netif_wake_subqueue"></a>`netif_wake_subqueue()`

```c
void netif_wake_subqueue(struct net_device *dev, u16 queue_index)
```

allow sending packets on subqueue

**Parameters**

- `struct net_device *dev`: network device
- `u16 queue_index`: sub queue index

**Description**

Resume individual transmit queue of a device with multiple transmit queues.

#### <a id="c-netif_attr_test_mask"></a>`netif_attr_test_mask()`

```c
bool netif_attr_test_mask(unsigned long j, const unsigned long *mask, unsigned int nr_bits)
```

Test a CPU or Rx queue set in a mask

**Parameters**

- `unsigned long j`: CPU/Rx queue index
- `const unsigned long *mask`: bitmask of all cpus/rx queues
- `unsigned int nr_bits`: number of bits in the bitmask

**Description**

Test if a CPU or Rx queue index is set in a mask of all CPU/Rx queues.

#### <a id="c-netif_attr_test_online"></a>`netif_attr_test_online()`

```c
bool netif_attr_test_online(unsigned long j, const unsigned long *online_mask, unsigned int nr_bits)
```

Test for online CPU/Rx queue

**Parameters**

- `unsigned long j`: CPU/Rx queue index
- `const unsigned long *online_mask`: bitmask for CPUs/Rx queues that are online
- `unsigned int nr_bits`: number of bits in the bitmask

**Return**

true if a CPU/Rx queue is online.

#### <a id="c-netif_attrmask_next"></a>`netif_attrmask_next()`

```c
unsigned int netif_attrmask_next(int n, const unsigned long *srcp, unsigned int nr_bits)
```

get the next CPU/Rx queue in a cpu/Rx queues mask

**Parameters**

- `int n`: CPU/Rx queue index
- `const unsigned long *srcp`: the cpumask/Rx queue mask pointer
- `unsigned int nr_bits`: number of bits in the bitmask

**Return**

next (after n) CPU/Rx queue index in the mask;
\>= nr_bits if no further CPUs/Rx queues set.

#### <a id="c-netif_attrmask_next_and"></a>`netif_attrmask_next_and()`

```c
int netif_attrmask_next_and(int n, const unsigned long *src1p, const unsigned long *src2p, unsigned int nr_bits)
```

get the next CPU/Rx queue in \*src1p & \*src2p

**Parameters**

- `int n`: CPU/Rx queue index
- `const unsigned long *src1p`: the first CPUs/Rx queues mask pointer
- `const unsigned long *src2p`: the second CPUs/Rx queues mask pointer
- `unsigned int nr_bits`: number of bits in the bitmask

**Return**

next (after n) CPU/Rx queue index set in both masks;
\>= nr_bits if no further CPUs/Rx queues set in both.

#### <a id="c-netif_is_multiqueue"></a>`netif_is_multiqueue()`

```c
bool netif_is_multiqueue(const struct net_device *dev)
```

test if device has multiple transmit queues

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if device has multiple transmit queues

#### <a id="c-dev_hold"></a>`dev_hold()`

```c
void dev_hold(struct net_device *dev)
```

get reference to device

**Parameters**

- `struct net_device *dev`: network device

**Description**

Hold reference to device to keep it from being freed.
Try using `netdev_hold()` instead.

#### <a id="c-dev_put"></a>`dev_put()`

```c
void dev_put(struct net_device *dev)
```

release reference to device

**Parameters**

- `struct net_device *dev`: network device

**Description**

Release reference to device to allow it to be freed.
Try using `netdev_put()` instead.

#### <a id="c-linkwatch_sync_dev"></a>`linkwatch_sync_dev()`

```c
void linkwatch_sync_dev(struct net_device *dev)
```

sync linkwatch for the given device

**Parameters**

- `struct net_device *dev`: network device to sync linkwatch for

**Description**

Sync linkwatch for the given device, removing it from the
pending work list (if queued).

#### <a id="c-netif_carrier_ok"></a>`netif_carrier_ok()`

```c
bool netif_carrier_ok(const struct net_device *dev)
```

test if carrier present

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if carrier is present on device

#### <a id="c-netif_dormant_on"></a>`netif_dormant_on()`

```c
void netif_dormant_on(struct net_device *dev)
```

mark device as dormant.

**Parameters**

- `struct net_device *dev`: network device

**Description**

Mark device as dormant (as per RFC2863).

The dormant state indicates that the relevant interface is not
actually in a condition to pass packets (i.e., it is not 'up') but is
in a "pending" state, waiting for some external event.  For "on-
demand" interfaces, this new state identifies the situation where the
interface is waiting for events to place it in the up state.

#### <a id="c-netif_dormant_off"></a>`netif_dormant_off()`

```c
void netif_dormant_off(struct net_device *dev)
```

set device as not dormant.

**Parameters**

- `struct net_device *dev`: network device

**Description**

Device is not in dormant state.

#### <a id="c-netif_dormant"></a>`netif_dormant()`

```c
bool netif_dormant(const struct net_device *dev)
```

test if device is dormant

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if device is dormant.

#### <a id="c-netif_testing_on"></a>`netif_testing_on()`

```c
void netif_testing_on(struct net_device *dev)
```

mark device as under test.

**Parameters**

- `struct net_device *dev`: network device

**Description**

Mark device as under test (as per RFC2863).

The testing state indicates that some test(s) must be performed on
the interface. After completion, of the test, the interface state
will change to up, dormant, or down, as appropriate.

#### <a id="c-netif_testing_off"></a>`netif_testing_off()`

```c
void netif_testing_off(struct net_device *dev)
```

set device as not under test.

**Parameters**

- `struct net_device *dev`: network device

**Description**

Device is not in testing state.

#### <a id="c-netif_testing"></a>`netif_testing()`

```c
bool netif_testing(const struct net_device *dev)
```

test if device is under test

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if device is under test

#### <a id="c-netif_oper_up"></a>`netif_oper_up()`

```c
bool netif_oper_up(const struct net_device *dev)
```

test if device is operational

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if carrier is operational

#### <a id="c-netif_device_present"></a>`netif_device_present()`

```c
bool netif_device_present(const struct net_device *dev)
```

is device available or removed

**Parameters**

- `const struct net_device *dev`: network device

**Description**

Check if device has not been removed from system.

#### <a id="c-netif_tx_lock"></a>`netif_tx_lock()`

```c
void netif_tx_lock(struct net_device *dev)
```

grab network device transmit lock

**Parameters**

- `struct net_device *dev`: network device

**Description**

Get network device transmit lock

#### <a id="c-__dev_uc_sync"></a>`__dev_uc_sync()`

```c
int __dev_uc_sync(struct net_device *dev, int (*sync)(struct net_device *, const unsigned char *), int (*unsync)(struct net_device *, const unsigned char *))
```

Synchronize device's unicast list

**Parameters**

- `struct net_device *dev`: device to sync
- `int (*sync)(struct net_device *, const unsigned char *)`: function to call if address should be added
- `int (*unsync)(struct net_device *, const unsigned char *)`: function to call if address should be removed

**Description**

Add newly added addresses to the interface, and release
addresses that have been deleted.

#### <a id="c-__dev_uc_unsync"></a>`__dev_uc_unsync()`

```c
void __dev_uc_unsync(struct net_device *dev, int (*unsync)(struct net_device *, const unsigned char *))
```

Remove synchronized addresses from device

**Parameters**

- `struct net_device *dev`: device to sync
- `int (*unsync)(struct net_device *, const unsigned char *)`: function to call if address should be removed

**Description**

Remove all addresses that were added to the device by `dev_uc_sync()`.

#### <a id="c-__dev_mc_sync"></a>`__dev_mc_sync()`

```c
int __dev_mc_sync(struct net_device *dev, int (*sync)(struct net_device *, const unsigned char *), int (*unsync)(struct net_device *, const unsigned char *))
```

Synchronize device's multicast list

**Parameters**

- `struct net_device *dev`: device to sync
- `int (*sync)(struct net_device *, const unsigned char *)`: function to call if address should be added
- `int (*unsync)(struct net_device *, const unsigned char *)`: function to call if address should be removed

**Description**

Add newly added addresses to the interface, and release
addresses that have been deleted.

#### <a id="c-__dev_mc_unsync"></a>`__dev_mc_unsync()`

```c
void __dev_mc_unsync(struct net_device *dev, int (*unsync)(struct net_device *, const unsigned char *))
```

Remove synchronized addresses from device

**Parameters**

- `struct net_device *dev`: device to sync
- `int (*unsync)(struct net_device *, const unsigned char *)`: function to call if address should be removed

**Description**

Remove all addresses that were added to the device by `dev_mc_sync()`.



#### <a id="c-struct-net_shaper"></a>`struct net_shaper`

represents a shaping node on the NIC H/W zeroed field are considered not set.

**Definition**

```c
struct net_shaper {
    struct net_shaper_handle parent;
    struct net_shaper_handle handle;
    enum net_shaper_metric metric;
    u64 bw_min;
    u64 bw_max;
    u64 burst;
    u32 priority;
    u32 weight;
};
```

**Members**

- `parent`: Unique identifier for the shaper parent, usually implied
- `handle`: Unique identifier for this shaper
- `metric`: Specify if the rate limits refers to PPS or BPS
- `bw_min`: Minimum guaranteed rate for this shaper
- `bw_max`: Maximum peak rate allowed for this shaper
- `burst`: Maximum burst for the peek rate of this shaper
- `priority`: Scheduling priority for this shaper
- `weight`: Scheduling weight for this shaper

#### <a id="c-struct-net_shaper_ops"></a>`struct net_shaper_ops`

Operations on device H/W shapers

**Definition**

```c
struct net_shaper_ops {
    int (*group)(struct net_shaper_binding *binding, int leaves_count, const struct net_shaper *leaves, const struct net_shaper *node, struct netlink_ext_ack *extack);
    int (*set)(struct net_shaper_binding *binding, const struct net_shaper *shaper, struct netlink_ext_ack *extack);
    int (*delete)(struct net_shaper_binding *binding, const struct net_shaper_handle *handle, struct netlink_ext_ack *extack);
    void (*capabilities)(struct net_shaper_binding *binding, enum net_shaper_scope scope, unsigned long *cap);
};
```

**Members**

- `group`: create the specified shapers scheduling group

  Nest the **leaves** shapers identified under the * **node** shaper.
  All the shapers belong to the device specified by **binding**.
  The **leaves** arrays size is specified by **leaves_count**.
  Create either the **leaves** and the **node** shaper; or if they already
  exists, links them together in the desired way.
  **leaves** scope must be NET_SHAPER_SCOPE_QUEUE.
- `set`: Updates the specified shaper

  Updates or creates the **shaper** on the device specified by **binding**.
- `delete`: Removes the specified shaper

  Removes the shaper configuration as identified by the given **handle**
  on the device specified by **binding**, restoring the default behavior.
- `capabilities`: get the shaper features supported by the device

  Fills the bitmask **cap** with the supported capabilities for the
  specified **scope** and device specified by **binding**.

**Description**

The operations applies to either net_device and devlink objects.
The initial shaping configuration at device initialization is empty:
does not constraint the rate in any way.
The network core keeps track of the applied user-configuration in
the net_device or devlink structure.
The operations are serialized via a per device lock.

Device not supporting any kind of nesting should not provide the
group operation.

Each shaper is uniquely identified within the device with a 'handle'
comprising the shaper scope and a scope-specific id.


<a id="rst-phy-support"></a>

### PHY Support


#### <a id="c-phy_print_status"></a>`phy_print_status()`

```c
void phy_print_status(struct phy_device *phydev)
```

Convenience function to print out the current phy status

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_get_rate_matching"></a>`phy_get_rate_matching()`

```c
int phy_get_rate_matching(struct phy_device *phydev, phy_interface_t iface)
```

determine if rate matching is supported

**Parameters**

- `struct phy_device *phydev`: The phy device to return rate matching for
- `phy_interface_t iface`: The interface mode to use

**Description**

This determines the type of rate matching (if any) that **phy** supports
using **iface**. **iface** may be `PHY_INTERFACE_MODE_NA` to determine if any
interface supports rate matching.

**Return**

The type of rate matching **phy** supports for **iface**, or
`RATE_MATCH_NONE`.

#### <a id="c-phy_restart_aneg"></a>`phy_restart_aneg()`

```c
int phy_restart_aneg(struct phy_device *phydev)
```

restart auto-negotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Restart the autonegotiation on **phydev**.  Returns >= 0 on success or
negative errno on error.

#### <a id="c-phy_aneg_done"></a>`phy_aneg_done()`

```c
int phy_aneg_done(struct phy_device *phydev)
```

return auto-negotiation status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Return the auto-negotiation status from this **phydev**
Returns > 0 on success or \< 0 on error. 0 means that auto-negotiation
is still pending.

#### <a id="c-phy_check_valid"></a>`phy_check_valid()`

```c
bool phy_check_valid(int speed, int duplex, unsigned long *features)
```

check if there is a valid PHY setting which matches speed, duplex, and feature mask

**Parameters**

- `int speed`: speed to match
- `int duplex`: duplex to match
- `unsigned long *features`: A mask of the valid settings

**Description**

Returns true if there is a valid setting, false otherwise.

#### <a id="c-phy_mii_ioctl"></a>`phy_mii_ioctl()`

```c
int phy_mii_ioctl(struct phy_device *phydev, struct ifreq *ifr, int cmd)
```

generic PHY MII ioctl interface

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct ifreq *ifr`: `struct ifreq` for socket ioctl's
- `int cmd`: ioctl cmd to execute

**Description**

Note that this function is currently incompatible with the
PHYCONTROL layer.  It changes registers without regard to
current state.  Use at own risk.

#### <a id="c-phy_do_ioctl"></a>`phy_do_ioctl()`

```c
int phy_do_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
```

generic ndo_eth_ioctl implementation

**Parameters**

- `struct net_device *dev`: the net_device struct
- `struct ifreq *ifr`: `struct ifreq` for socket ioctl's
- `int cmd`: ioctl cmd to execute

#### <a id="c-phy_do_ioctl_running"></a>`phy_do_ioctl_running()`

```c
int phy_do_ioctl_running(struct net_device *dev, struct ifreq *ifr, int cmd)
```

generic ndo_eth_ioctl implementation but test first

**Parameters**

- `struct net_device *dev`: the net_device struct
- `struct ifreq *ifr`: `struct ifreq` for socket ioctl's
- `int cmd`: ioctl cmd to execute

**Description**

Same as phy_do_ioctl, but ensures that net_device is running before
handling the ioctl.

#### <a id="c-phy_trigger_machine"></a>`phy_trigger_machine()`

```c
void phy_trigger_machine(struct phy_device *phydev)
```

Trigger the state machine to run now

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_ethtool_get_strings"></a>`phy_ethtool_get_strings()`

```c
int phy_ethtool_get_strings(struct phy_device *phydev, u8 *data)
```

Get the statistic counter names

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u8 *data`: Where to put the strings

#### <a id="c-phy_ethtool_get_sset_count"></a>`phy_ethtool_get_sset_count()`

```c
int phy_ethtool_get_sset_count(struct phy_device *phydev)
```

Get the number of statistic counters

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_ethtool_get_stats"></a>`phy_ethtool_get_stats()`

```c
int phy_ethtool_get_stats(struct phy_device *phydev, struct ethtool_stats *stats, u64 *data)
```

Get the statistic counters

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct ethtool_stats *stats`: What counters to get
- `u64 *data`: Where to store the counters

#### <a id="c-phy_start_cable_test"></a>`phy_start_cable_test()`

```c
int phy_start_cable_test(struct phy_device *phydev, struct netlink_ext_ack *extack)
```

Start a cable test

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct netlink_ext_ack *extack`: extack for reporting useful error messages

#### <a id="c-phy_start_cable_test_tdr"></a>`phy_start_cable_test_tdr()`

```c
int phy_start_cable_test_tdr(struct phy_device *phydev, struct netlink_ext_ack *extack, const struct phy_tdr_config *config)
```

Start a raw TDR cable test

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct netlink_ext_ack *extack`: extack for reporting useful error messages
- `const struct phy_tdr_config *config`: Configuration of the test to run

#### <a id="c-phy_inband_caps"></a>`phy_inband_caps()`

```c
unsigned int phy_inband_caps(struct phy_device *phydev, phy_interface_t interface)
```

query which in-band signalling modes are supported

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `phy_interface_t interface`: the interface mode for the PHY

**Description**

Returns zero if it is unknown what in-band signalling is supported by the
PHY (e.g. because the PHY driver doesn't implement the method.) Otherwise,
returns a bit mask of the LINK_INBAND_* values from
[`enum link_inband_signalling`](#c-enum-link_inband_signalling) to describe which inband modes are supported
by the PHY for this interface mode.

#### <a id="c-phy_config_inband"></a>`phy_config_inband()`

```c
int phy_config_inband(struct phy_device *phydev, unsigned int modes)
```

configure the desired PHY in-band mode

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `unsigned int modes`: in-band modes to configure

**Description**

- disables, enables or enables-with-bypass in-band signalling

  between the PHY and host system.

**Return**

zero on success, or negative errno value.

#### <a id="c-_phy_start_aneg"></a>`_phy_start_aneg()`

```c
int _phy_start_aneg(struct phy_device *phydev)
```

start auto-negotiation for this PHY device

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**Description**

- Sanitizes the settings (if we're not autonegotiating

  them), and then calls the driver's config_aneg function.
  If the PHYCONTROL Layer is operating, we change the state to
  reflect the beginning of Auto-negotiation or forcing.

#### <a id="c-phy_start_aneg"></a>`phy_start_aneg()`

```c
int phy_start_aneg(struct phy_device *phydev)
```

start auto-negotiation for this PHY device

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**Description**

- Sanitizes the settings (if we're not autonegotiating

  them), and then calls the driver's config_aneg function.
  If the PHYCONTROL Layer is operating, we change the state to
  reflect the beginning of Auto-negotiation or forcing.

#### <a id="c-phy_speed_down"></a>`phy_speed_down()`

```c
int phy_speed_down(struct phy_device *phydev, bool sync)
```

set speed to lowest speed supported by both link partners

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `bool sync`: perform action synchronously

**Description**

Typically used to save energy when waiting for a WoL packet

WARNING: Setting sync to false may cause the system being unable to suspend
in case the PHY generates an interrupt when finishing the autonegotiation.
This interrupt may wake up the system immediately after suspend.
Therefore use sync = false only if you're sure it's safe with the respective
network chip.

#### <a id="c-phy_speed_up"></a>`phy_speed_up()`

```c
int phy_speed_up(struct phy_device *phydev)
```

(re)set advertised speeds to all supported speeds

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**Description**

Used to revert the effect of phy_speed_down

#### <a id="c-phy_start_machine"></a>`phy_start_machine()`

```c
void phy_start_machine(struct phy_device *phydev)
```

start PHY state machine tracking

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**Description**

- The PHY infrastructure can run a state machine

  which tracks whether the PHY is starting up, negotiating,
  etc.  This function starts the delayed workqueue which tracks
  the state of the PHY. If you want to maintain your own state machine,
  do not call this function.

#### <a id="c-phy_error"></a>`phy_error()`

```c
void phy_error(struct phy_device *phydev)
```

enter ERROR state for this PHY device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Moves the PHY to the ERROR state in response to a read
or write error, and tells the controller the link is down.
Must be called with phydev->lock held.

#### <a id="c-phy_request_interrupt"></a>`phy_request_interrupt()`

```c
void phy_request_interrupt(struct phy_device *phydev)
```

request and enable interrupt for a PHY device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Request and enable the interrupt for the given PHY.

  If this fails, then we set irq to PHY_POLL.
  This should only be called with a valid IRQ number.

#### <a id="c-phy_free_interrupt"></a>`phy_free_interrupt()`

```c
void phy_free_interrupt(struct phy_device *phydev)
```

disable and free interrupt for a PHY device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Disable and free the interrupt for the given PHY.

  This should only be called with a valid IRQ number.

#### <a id="c-phy_stop"></a>`phy_stop()`

```c
void phy_stop(struct phy_device *phydev)
```

Bring down the PHY link, and stop checking the status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-phy_start"></a>`phy_start()`

```c
void phy_start(struct phy_device *phydev)
```

start or restart a PHY device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Indicates the attached device's readiness to

  handle PHY-related work.  Used during startup to start the
  PHY, and after a call to [`phy_stop()`](#c-phy_stop) to resume operation.
  Also used to indicate the MDIO bus has cleared an error
  condition.

#### <a id="c-phy_mac_interrupt"></a>`phy_mac_interrupt()`

```c
void phy_mac_interrupt(struct phy_device *phydev)
```

MAC says the link has changed

**Parameters**

- `struct phy_device *phydev`: phy_device struct with changed link

**Description**

The MAC layer is able to indicate there has been a change in the PHY link
status. Trigger the state machine and work a work queue.

#### <a id="c-phy_loopback"></a>`phy_loopback()`

```c
int phy_loopback(struct phy_device *phydev, bool enable, int speed)
```

Configure loopback mode of PHY

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool enable`: enable or disable loopback mode
- `int speed`: enable loopback mode with speed

**Description**

Configure loopback mode of PHY and signal link down and link up if speed is
changing.

**Return**

0 on success, negative error code on failure.

#### <a id="c-phy_eee_tx_clock_stop_capable"></a>`phy_eee_tx_clock_stop_capable()`

```c
int phy_eee_tx_clock_stop_capable(struct phy_device *phydev)
```

indicate whether the MAC can stop tx clock

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Indicate whether the MAC can disable the transmit xMII clock while in LPI
state. Returns 1 if the MAC may stop the transmit clock, 0 if the MAC must
not stop the transmit clock, or negative error.

#### <a id="c-phy_eee_rx_clock_stop"></a>`phy_eee_rx_clock_stop()`

```c
int phy_eee_rx_clock_stop(struct phy_device *phydev, bool clk_stop_enable)
```

configure PHY receive clock in LPI

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool clk_stop_enable`: flag to indicate whether the clock can be stopped

**Description**

Configure whether the PHY can disable its receive clock during LPI mode,
See IEEE 802.3 sections 22.2.2.2, 35.2.2.10, and 45.2.3.1.4.

**Return**

0 or negative error.

#### <a id="c-phy_init_eee"></a>`phy_init_eee()`

```c
int phy_init_eee(struct phy_device *phydev, bool clk_stop_enable)
```

init and check the EEE feature

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool clk_stop_enable`: PHY may stop the clock during LPI

**Description**

it checks if the Energy-Efficient Ethernet (EEE)
is supported by looking at the MMD registers 3.20 and 7.60/61
and it programs the MMD register 3.0 setting the "Clock stop enable"
bit if required.

#### <a id="c-phy_get_eee_err"></a>`phy_get_eee_err()`

```c
int phy_get_eee_err(struct phy_device *phydev)
```

report the EEE wake error count

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

it is to report the number of time where the PHY
failed to complete its normal wake sequence.

#### <a id="c-phy_ethtool_get_eee"></a>`phy_ethtool_get_eee()`

```c
int phy_ethtool_get_eee(struct phy_device *phydev, struct ethtool_keee *data)
```

get EEE supported and status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_keee *data`: ethtool_keee data

**Description**

get the current EEE settings, filling in all members of
**data**.

#### <a id="c-phy_ethtool_set_eee"></a>`phy_ethtool_set_eee()`

```c
int phy_ethtool_set_eee(struct phy_device *phydev, struct ethtool_keee *data)
```

set EEE supported and status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_keee *data`: ethtool_keee data

**Description**

it is to program the Advertisement EEE register.

#### <a id="c-phy_ethtool_set_wol"></a>`phy_ethtool_set_wol()`

```c
int phy_ethtool_set_wol(struct phy_device *phydev, struct ethtool_wolinfo *wol)
```

Configure Wake On LAN

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_wolinfo *wol`: Configuration requested

#### <a id="c-phy_ethtool_get_wol"></a>`phy_ethtool_get_wol()`

```c
void phy_ethtool_get_wol(struct phy_device *phydev, struct ethtool_wolinfo *wol)
```

Get the current Wake On LAN configuration

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_wolinfo *wol`: Store the current configuration here

#### <a id="c-phy_ethtool_nway_reset"></a>`phy_ethtool_nway_reset()`

```c
int phy_ethtool_nway_reset(struct net_device *ndev)
```

Restart auto negotiation

**Parameters**

- `struct net_device *ndev`: Network device to restart autoneg for



#### <a id="c-phy_config_interrupt"></a>`phy_config_interrupt()`

```c
int phy_config_interrupt(struct phy_device *phydev, bool interrupts)
```

configure the PHY device for the requested interrupts

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `bool interrupts`: interrupt flags to configure for this **phydev**

**Description**

Returns 0 on success or \< 0 on error.

#### <a id="c-phy_supported_speeds"></a>`phy_supported_speeds()`

```c
unsigned int phy_supported_speeds(struct phy_device *phy, unsigned int *speeds, unsigned int size)
```

return all speeds currently supported by a phy device

**Parameters**

- `struct phy_device *phy`: The phy device to return supported speeds of.
- `unsigned int *speeds`: buffer to store supported speeds in.
- `unsigned int size`: size of speeds buffer.

**Description**

Returns the number of supported speeds, and fills the speeds
buffer with the supported speeds. If speeds buffer is too small to contain
all currently supported speeds, will return as many speeds as can fit.

#### <a id="c-phy_sanitize_settings"></a>`phy_sanitize_settings()`

```c
void phy_sanitize_settings(struct phy_device *phydev)
```

make sure the PHY is set to supported speed and duplex

**Parameters**

- `struct phy_device *phydev`: the target phy_device struct

**Description**

- Make sure the PHY is set to supported speeds and

  duplexes.  Drop down by one in this order:  1000/FULL,
  1000/HALF, 100/FULL, 100/HALF, 10/FULL, 10/HALF.

#### <a id="c-__phy_hwtstamp_get"></a>`__phy_hwtstamp_get()`

```c
int __phy_hwtstamp_get(struct phy_device *phydev, struct kernel_hwtstamp_config *config)
```

Get hardware timestamping configuration from PHY

**Parameters**

- `struct phy_device *phydev`: the PHY device structure
- `struct kernel_hwtstamp_config *config`: structure holding the timestamping configuration

**Description**

Query the PHY device for its current hardware timestamping configuration.

#### <a id="c-__phy_hwtstamp_set"></a>`__phy_hwtstamp_set()`

```c
int __phy_hwtstamp_set(struct phy_device *phydev, struct kernel_hwtstamp_config *config, struct netlink_ext_ack *extack)
```

Modify PHY hardware timestamping configuration

**Parameters**

- `struct phy_device *phydev`: the PHY device structure
- `struct kernel_hwtstamp_config *config`: structure holding the timestamping configuration
- `struct netlink_ext_ack *extack`: netlink extended ack structure, for error reporting

#### <a id="c-phy_queue_state_machine"></a>`phy_queue_state_machine()`

```c
void phy_queue_state_machine(struct phy_device *phydev, unsigned long jiffies)
```

Trigger the state machine to run soon

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `unsigned long jiffies`: Run the state machine after these jiffies

#### <a id="c-__phy_ethtool_get_phy_stats"></a>`__phy_ethtool_get_phy_stats()`

```c
void __phy_ethtool_get_phy_stats(struct phy_device *phydev, struct ethtool_eth_phy_stats *phy_stats, struct ethtool_phy_stats *phydev_stats)
```

Retrieve standardized PHY statistics

**Parameters**

- `struct phy_device *phydev`: Pointer to the PHY device
- `struct ethtool_eth_phy_stats *phy_stats`: Pointer to ethtool_eth_phy_stats structure
- `struct ethtool_phy_stats *phydev_stats`: Pointer to ethtool_phy_stats structure

**Description**

Fetches PHY statistics using a kernel-defined interface for consistent
diagnostics. Unlike [`phy_ethtool_get_stats()`](#c-phy_ethtool_get_stats), which allows custom stats,
this function enforces a standardized format for better interoperability.

#### <a id="c-__phy_ethtool_get_link_ext_stats"></a>`__phy_ethtool_get_link_ext_stats()`

```c
void __phy_ethtool_get_link_ext_stats(struct phy_device *phydev, struct ethtool_link_ext_stats *link_stats)
```

Retrieve extended link statistics for a PHY

**Parameters**

- `struct phy_device *phydev`: Pointer to the PHY device
- `struct ethtool_link_ext_stats *link_stats`: Pointer to the structure to store extended link statistics

**Description**

Populates the ethtool_link_ext_stats structure with link down event counts
and additional driver-specific link statistics, if available.

#### <a id="c-phy_ethtool_get_plca_cfg"></a>`phy_ethtool_get_plca_cfg()`

```c
int phy_ethtool_get_plca_cfg(struct phy_device *phydev, struct phy_plca_cfg *plca_cfg)
```

Get PLCA RS configuration

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct phy_plca_cfg *plca_cfg`: where to store the retrieved configuration

**Description**

Retrieve the PLCA configuration from the PHY. Return 0 on success or a
negative value if an error occurred.

#### <a id="c-plca_check_valid"></a>`plca_check_valid()`

```c
int plca_check_valid(struct phy_device *phydev, const struct phy_plca_cfg *plca_cfg, struct netlink_ext_ack *extack)
```

Check PLCA configuration before enabling

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `const struct phy_plca_cfg *plca_cfg`: current PLCA configuration
- `struct netlink_ext_ack *extack`: extack for reporting useful error messages

**Description**

Checks whether the PLCA and PHY configuration are consistent and it is safe
to enable PLCA. Returns 0 on success or a negative value if the PLCA or PHY
configuration is not consistent.

#### <a id="c-phy_ethtool_set_plca_cfg"></a>`phy_ethtool_set_plca_cfg()`

```c
int phy_ethtool_set_plca_cfg(struct phy_device *phydev, const struct phy_plca_cfg *plca_cfg, struct netlink_ext_ack *extack)
```

Set PLCA RS configuration

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `const struct phy_plca_cfg *plca_cfg`: new PLCA configuration to apply
- `struct netlink_ext_ack *extack`: extack for reporting useful error messages

**Description**

Sets the PLCA configuration in the PHY. Return 0 on success or a
negative value if an error occurred.

#### <a id="c-phy_ethtool_get_plca_status"></a>`phy_ethtool_get_plca_status()`

```c
int phy_ethtool_get_plca_status(struct phy_device *phydev, struct phy_plca_status *plca_st)
```

Get PLCA RS status information

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `struct phy_plca_status *plca_st`: where to store the retrieved status information

**Description**

Retrieve the PLCA status information from the PHY. Return 0 on success or a
negative value if an error occurred.

#### <a id="c-phy_check_link_status"></a>`phy_check_link_status()`

```c
int phy_check_link_status(struct phy_device *phydev)
```

check link status and set state accordingly

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**Description**

Check for link and whether autoneg was triggered / is running
and set state accordingly

#### <a id="c-phy_stop_machine"></a>`phy_stop_machine()`

```c
void phy_stop_machine(struct phy_device *phydev)
```

stop the PHY state machine tracking

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Stops the state machine delayed workqueue, sets the

  state to UP (unless it wasn't up yet). This function must be
  called BEFORE phy_detach.

#### <a id="c-phy_disable_interrupts"></a>`phy_disable_interrupts()`

```c
int phy_disable_interrupts(struct phy_device *phydev)
```

Disable the PHY interrupts from the PHY side

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-phy_interrupt"></a>`phy_interrupt()`

```c
irqreturn_t phy_interrupt(int irq, void *phy_dat)
```

PHY interrupt handler

**Parameters**

- `int irq`: interrupt line
- `void *phy_dat`: phy_device pointer

**Description**

Handle PHY interrupt

#### <a id="c-phy_enable_interrupts"></a>`phy_enable_interrupts()`

```c
int phy_enable_interrupts(struct phy_device *phydev)
```

Enable the interrupts from the PHY side

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-phy_update_stats"></a>`phy_update_stats()`

```c
int phy_update_stats(struct phy_device *phydev)
```

Update PHY device statistics if supported.

**Parameters**

- `struct phy_device *phydev`: Pointer to the PHY device structure.

**Description**

If the PHY driver provides an update_stats callback, this function
invokes it to update the PHY statistics. If not, it returns 0.

**Return**

0 on success, or a negative error code if the callback fails.

#### <a id="c-phy_get_next_update_time"></a>`phy_get_next_update_time()`

```c
unsigned int phy_get_next_update_time(struct phy_device *phydev)
```

Determine the next PHY update time

**Parameters**

- `struct phy_device *phydev`: Pointer to the phy_device structure

**Description**

This function queries the PHY driver to get the time for the next polling
event. If the driver does not implement the callback, a default value is
used.

**Return**

The time for the next polling event in jiffies

#### <a id="c-phy_state_machine"></a>`phy_state_machine()`

```c
void phy_state_machine(struct work_struct *work)
```

Handle the state machine

**Parameters**

- `struct work_struct *work`: work_struct that describes the work to be done

#### <a id="c-phy_ethtool_set_eee_noneg"></a>`phy_ethtool_set_eee_noneg()`

```c
void phy_ethtool_set_eee_noneg(struct phy_device *phydev, const struct eee_config *old_cfg)
```

Adjusts MAC LPI configuration without PHY renegotiation

**Parameters**

- `struct phy_device *phydev`: pointer to the target PHY device structure
- `const struct eee_config *old_cfg`: pointer to the eee_config structure containing the old EEE settings

**Description**

This function updates the Energy Efficient Ethernet (EEE) configuration
for cases where only the MAC's Low Power Idle (LPI) configuration changes,
without triggering PHY renegotiation. It ensures that the MAC is properly
informed of the new LPI settings by cycling the link down and up, which
is necessary for the MAC to adopt the new configuration. This adjustment
is done only if there is a change in the tx_lpi_enabled or tx_lpi_timer
configuration.



#### <a id="c-phy_speed_to_str"></a>`phy_speed_to_str()`

```c
const char * phy_speed_to_str(int speed)
```

Return a string representing the PHY link speed

**Parameters**

- `int speed`: Speed of the link

#### <a id="c-phy_duplex_to_str"></a>`phy_duplex_to_str()`

```c
const char * phy_duplex_to_str(unsigned int duplex)
```

Return string describing the duplex

**Parameters**

- `unsigned int duplex`: Duplex setting to describe

#### <a id="c-phy_rate_matching_to_str"></a>`phy_rate_matching_to_str()`

```c
const char * phy_rate_matching_to_str(int rate_matching)
```

Return a string describing the rate matching

**Parameters**

- `int rate_matching`: Type of rate matching to describe

#### <a id="c-phy_fix_phy_mode_for_mac_delays"></a>`phy_fix_phy_mode_for_mac_delays()`

```c
phy_interface_t phy_fix_phy_mode_for_mac_delays(phy_interface_t interface, bool mac_txid, bool mac_rxid)
```

Convenience function for fixing PHY mode based on whether mac adds internal delay

**Parameters**

- `phy_interface_t interface`: The current interface mode of the port
- `bool mac_txid`: True if the mac adds internal tx delay
- `bool mac_rxid`: True if the mac adds internal rx delay

**Return**

fixed PHY mode, or PHY_INTERFACE_MODE_NA if the interface can
not apply the internal delay

#### <a id="c-phy_interface_num_ports"></a>`phy_interface_num_ports()`

```c
int phy_interface_num_ports(phy_interface_t interface)
```

Return the number of links that can be carried by a given MAC-PHY physical link. Returns 0 if this is unknown, the number of links else.

**Parameters**

- `phy_interface_t interface`: The interface mode we want to get the number of ports

#### <a id="c-phy_set_max_speed"></a>`phy_set_max_speed()`

```c
void phy_set_max_speed(struct phy_device *phydev, u32 max_speed)
```

Set the maximum speed the PHY should support

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `u32 max_speed`: Maximum speed

**Description**

The PHY might be more capable than the MAC. For example a Fast Ethernet
is connected to a 1G PHY. This function allows the MAC to indicate its
maximum speed, and so limit what the PHY will advertise.

#### <a id="c-phy_resolve_aneg_pause"></a>`phy_resolve_aneg_pause()`

```c
void phy_resolve_aneg_pause(struct phy_device *phydev)
```

Determine pause autoneg results

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

**Description**

Once autoneg has completed the local pause settings can be
resolved.  Determine if pause and asymmetric pause should be used
by the MAC.

#### <a id="c-phy_resolve_aneg_linkmode"></a>`phy_resolve_aneg_linkmode()`

```c
void phy_resolve_aneg_linkmode(struct phy_device *phydev)
```

resolve the advertisements into PHY settings

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

**Description**

Resolve our and the link partner advertisements into their corresponding
speed and duplex. If full duplex was negotiated, extract the pause mode
from the link partner mask.

#### <a id="c-__phy_read_mmd"></a>`__phy_read_mmd()`

```c
int __phy_read_mmd(struct phy_device *phydev, int devad, u32 regnum)
```

Convenience function for reading a register from an MMD on a given PHY.

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `int devad`: The MMD to read from (0..31)
- `u32 regnum`: The register on the MMD to read (0..65535)

**Description**

Same rules as for [`__phy_read()`](#c-__phy_read);

#### <a id="c-phy_read_mmd"></a>`phy_read_mmd()`

```c
int phy_read_mmd(struct phy_device *phydev, int devad, u32 regnum)
```

Convenience function for reading a register from an MMD on a given PHY.

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `int devad`: The MMD to read from
- `u32 regnum`: The register on the MMD to read

**Description**

Same rules as for [`phy_read()`](#c-phy_read);

#### <a id="c-__phy_write_mmd"></a>`__phy_write_mmd()`

```c
int __phy_write_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for writing a register on an MMD on a given PHY.

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `int devad`: The MMD to read from
- `u32 regnum`: The register on the MMD to read
- `u16 val`: value to write to **regnum**

**Description**

Same rules as for [`__phy_write()`](#c-__phy_write);

#### <a id="c-phy_write_mmd"></a>`phy_write_mmd()`

```c
int phy_write_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for writing a register on an MMD on a given PHY.

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `int devad`: The MMD to read from
- `u32 regnum`: The register on the MMD to read
- `u16 val`: value to write to **regnum**

**Description**

Same rules as for [`phy_write()`](#c-phy_write);

#### <a id="c-phy_modify_changed"></a>`phy_modify_changed()`

```c
int phy_modify_changed(struct phy_device *phydev, u32 regnum, u16 mask, u16 set)
```

Function for modifying a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

Returns negative errno, 0 if there was no change, and 1 in case of change

#### <a id="c-__phy_modify"></a>`__phy_modify()`

```c
int __phy_modify(struct phy_device *phydev, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-phy_modify"></a>`phy_modify()`

```c
int phy_modify(struct phy_device *phydev, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a given PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-__phy_modify_mmd_changed"></a>`__phy_modify_mmd_changed()`

```c
int __phy_modify_mmd_changed(struct phy_device *phydev, int devad, u32 regnum, u16 mask, u16 set)
```

Function for modifying a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**Description**

Unlocked helper function which allows a MMD register to be modified as
new register value = (old register value & ~mask) | set

Returns negative errno, 0 if there was no change, and 1 in case of change

#### <a id="c-phy_modify_mmd_changed"></a>`phy_modify_mmd_changed()`

```c
int phy_modify_mmd_changed(struct phy_device *phydev, int devad, u32 regnum, u16 mask, u16 set)
```

Function for modifying a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

Returns negative errno, 0 if there was no change, and 1 in case of change

#### <a id="c-__phy_modify_mmd"></a>`__phy_modify_mmd()`

```c
int __phy_modify_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-phy_modify_mmd"></a>`phy_modify_mmd()`

```c
int phy_modify_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: new value of bits set in mask to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-phy_save_page"></a>`phy_save_page()`

```c
int phy_save_page(struct phy_device *phydev)
```

take the bus lock and save the current page

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)

**Description**

Take the MDIO bus lock, and return the current page number. On error,
returns a negative errno. [`phy_restore_page()`](#c-phy_restore_page) must always be called
after this, irrespective of success or failure of this call.

#### <a id="c-phy_select_page"></a>`phy_select_page()`

```c
int phy_select_page(struct phy_device *phydev, int page)
```

take the bus lock, save the current page, and set a page

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int page`: desired page

**Description**

Take the MDIO bus lock to protect against concurrent access, save the
current PHY page, and set the current page.  On error, returns a
negative errno, otherwise returns the previous page number.
[`phy_restore_page()`](#c-phy_restore_page) must always be called after this, irrespective
of success or failure of this call.

#### <a id="c-phy_restore_page"></a>`phy_restore_page()`

```c
int phy_restore_page(struct phy_device *phydev, int oldpage, int ret)
```

restore the page register and release the bus lock

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int oldpage`: the old page, return value from [`phy_save_page()`](#c-phy_save_page) or [`phy_select_page()`](#c-phy_select_page)
- `int ret`: operation's return code

**Description**

Release the MDIO bus lock, restoring **oldpage** if it is a valid page.
This function propagates the earliest error code from the group of
operations.

**Return**

**oldpage** if it was a negative value, otherwise
**ret** if it was a negative errno value, otherwise
`phy_write_page()`'s negative value if it were in error, otherwise
**ret**.

#### <a id="c-phy_read_paged"></a>`phy_read_paged()`

```c
int phy_read_paged(struct phy_device *phydev, int page, u32 regnum)
```

Convenience function for reading a paged register

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int page`: the page for the phy
- `u32 regnum`: register number

**Description**

Same rules as for [`phy_read()`](#c-phy_read).

#### <a id="c-phy_write_paged"></a>`phy_write_paged()`

```c
int phy_write_paged(struct phy_device *phydev, int page, u32 regnum, u16 val)
```

Convenience function for writing a paged register

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int page`: the page for the phy
- `u32 regnum`: register number
- `u16 val`: value to write

**Description**

Same rules as for [`phy_write()`](#c-phy_write).

#### <a id="c-phy_modify_paged_changed"></a>`phy_modify_paged_changed()`

```c
int phy_modify_paged_changed(struct phy_device *phydev, int page, u32 regnum, u16 mask, u16 set)
```

Function for modifying a paged register

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int page`: the page for the phy
- `u32 regnum`: register number
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Description**

Returns negative errno, 0 if there was no change, and 1 in case of change

#### <a id="c-phy_modify_paged"></a>`phy_modify_paged()`

```c
int phy_modify_paged(struct phy_device *phydev, int page, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a paged register

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `int page`: the page for the phy
- `u32 regnum`: register number
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Description**

Same rules as for [`phy_read()`](#c-phy_read) and [`phy_write()`](#c-phy_write).



#### <a id="c-genphy_c45_pma_resume"></a>`genphy_c45_pma_resume()`

```c
int genphy_c45_pma_resume(struct phy_device *phydev)
```

wakes up the PMA module

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_pma_suspend"></a>`genphy_c45_pma_suspend()`

```c
int genphy_c45_pma_suspend(struct phy_device *phydev)
```

suspends the PMA module

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_pma_baset1_setup_master_slave"></a>`genphy_c45_pma_baset1_setup_master_slave()`

```c
int genphy_c45_pma_baset1_setup_master_slave(struct phy_device *phydev)
```

configures forced master/slave role of BaseT1 devices.

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_pma_setup_forced"></a>`genphy_c45_pma_setup_forced()`

```c
int genphy_c45_pma_setup_forced(struct phy_device *phydev)
```

configures a forced speed

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_an_config_aneg"></a>`genphy_c45_an_config_aneg()`

```c
int genphy_c45_an_config_aneg(struct phy_device *phydev)
```

configure advertisement registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Configure advertisement registers based on modes set in phydev->advertising

Returns negative errno code on failure, 0 if advertisement didn't change,
or 1 if advertised modes changed.

#### <a id="c-genphy_c45_an_disable_aneg"></a>`genphy_c45_an_disable_aneg()`

```c
int genphy_c45_an_disable_aneg(struct phy_device *phydev)
```

disable auto-negotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Disable auto-negotiation in the Clause 45 PHY. The link parameters
are controlled through the PMA/PMD MMD registers.

Returns zero on success, negative errno code on failure.

#### <a id="c-genphy_c45_restart_aneg"></a>`genphy_c45_restart_aneg()`

```c
int genphy_c45_restart_aneg(struct phy_device *phydev)
```

Enable and restart auto-negotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

This assumes that the auto-negotiation MMD is present.

Enable and restart auto-negotiation.

#### <a id="c-genphy_c45_check_and_restart_aneg"></a>`genphy_c45_check_and_restart_aneg()`

```c
int genphy_c45_check_and_restart_aneg(struct phy_device *phydev, bool restart)
```

Enable and restart auto-negotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool restart`: whether aneg restart is requested

**Description**

This assumes that the auto-negotiation MMD is present.

Check, and restart auto-negotiation if needed.

#### <a id="c-genphy_c45_aneg_done"></a>`genphy_c45_aneg_done()`

```c
int genphy_c45_aneg_done(struct phy_device *phydev)
```

return auto-negotiation complete status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

This assumes that the auto-negotiation MMD is present.

Reads the status register from the auto-negotiation MMD, returning:
- positive if auto-negotiation is complete
- negative errno code on error
- zero otherwise

#### <a id="c-genphy_c45_read_link"></a>`genphy_c45_read_link()`

```c
int genphy_c45_read_link(struct phy_device *phydev)
```

read the overall link status from the MMDs

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the link status from the specified MMDs, and if they all indicate
that the link is up, set phydev->link to 1.  If an error is encountered,
a negative errno will be returned, otherwise zero.

#### <a id="c-genphy_c45_read_lpa"></a>`genphy_c45_read_lpa()`

```c
int genphy_c45_read_lpa(struct phy_device *phydev)
```

read the link partner advertisement and pause

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the Clause 45 defined base (7.19) and 10G (7.33) status registers,
filling in the link partner advertisement, pause and asym_pause members
in **phydev**.  This assumes that the auto-negotiation MMD is present, and
the backplane bit (7.48.0) is clear.  Clause 45 PHY drivers are expected
to fill in the remainder of the link partner advert from vendor registers.

#### <a id="c-genphy_c45_pma_baset1_read_master_slave"></a>`genphy_c45_pma_baset1_read_master_slave()`

```c
int genphy_c45_pma_baset1_read_master_slave(struct phy_device *phydev)
```

read forced master/slave configuration

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_read_pma"></a>`genphy_c45_read_pma()`

```c
int genphy_c45_read_pma(struct phy_device *phydev)
```

read link speed etc from PMA

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_read_mdix"></a>`genphy_c45_read_mdix()`

```c
int genphy_c45_read_mdix(struct phy_device *phydev)
```

read mdix status from PMA

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_read_eee_abilities"></a>`genphy_c45_read_eee_abilities()`

```c
int genphy_c45_read_eee_abilities(struct phy_device *phydev)
```

read supported EEE link modes

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_an_config_eee_aneg"></a>`genphy_c45_an_config_eee_aneg()`

```c
int genphy_c45_an_config_eee_aneg(struct phy_device *phydev)
```

configure EEE advertisement

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_c45_pma_baset1_read_abilities"></a>`genphy_c45_pma_baset1_read_abilities()`

```c
int genphy_c45_pma_baset1_read_abilities(struct phy_device *phydev)
```

read supported baset1 link modes from PMA

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the supported link modes from the extended BASE-T1 ability register

#### <a id="c-genphy_c45_pma_read_ext_abilities"></a>`genphy_c45_pma_read_ext_abilities()`

```c
int genphy_c45_pma_read_ext_abilities(struct phy_device *phydev)
```

read supported link modes from PMA

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the supported link modes from the PMA/PMD extended ability register
(Register 1.11).

#### <a id="c-genphy_c45_pma_read_abilities"></a>`genphy_c45_pma_read_abilities()`

```c
int genphy_c45_pma_read_abilities(struct phy_device *phydev)
```

read supported link modes from PMA

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the supported link modes from the PMA Status 2 (1.8) register. If bit
1.8.9 is set, the list of supported modes is build using the values in the
PMA Extended Abilities (1.11) register, indicating 1000BASET an 10G related
modes. If bit 1.11.14 is set, then the list is also extended with the modes
in the 2.5G/5G PMA Extended register (1.21), indicating if 2.5GBASET and
5GBASET are supported.

#### <a id="c-genphy_c45_read_status"></a>`genphy_c45_read_status()`

```c
int genphy_c45_read_status(struct phy_device *phydev)
```

read PHY status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Reads status from PHY and sets phy_device members accordingly.

#### <a id="c-genphy_c45_config_aneg"></a>`genphy_c45_config_aneg()`

```c
int genphy_c45_config_aneg(struct phy_device *phydev)
```

restart auto-negotiation or forced setup

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- If auto-negotiation is enabled, we configure the

  advertising, and then restart auto-negotiation.  If it is not
  enabled, then we force a configuration.

#### <a id="c-genphy_c45_fast_retrain"></a>`genphy_c45_fast_retrain()`

```c
int genphy_c45_fast_retrain(struct phy_device *phydev, bool enable)
```

configure fast retrain registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool enable`: enable fast retrain or not

**Description**

- If fast-retrain is enabled, we configure PHY as

  advertising fast retrain capable and THP Bypass Request, then
  enable fast retrain. If it is not enabled, we configure fast
  retrain disabled.

#### <a id="c-genphy_c45_plca_get_cfg"></a>`genphy_c45_plca_get_cfg()`

```c
int genphy_c45_plca_get_cfg(struct phy_device *phydev, struct phy_plca_cfg *plca_cfg)
```

get PLCA configuration from standard registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct phy_plca_cfg *plca_cfg`: output structure to store the PLCA configuration

**Description**

- if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA

  Management Registers specifications, this function can be used to retrieve
  the current PLCA configuration from the standard registers in MMD 31.

#### <a id="c-genphy_c45_plca_set_cfg"></a>`genphy_c45_plca_set_cfg()`

```c
int genphy_c45_plca_set_cfg(struct phy_device *phydev, const struct phy_plca_cfg *plca_cfg)
```

set PLCA configuration using standard registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `const struct phy_plca_cfg *plca_cfg`: structure containing the PLCA configuration. Fields set to -1 are
  not to be changed.

**Description**

- if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA

  Management Registers specifications, this function can be used to modify
  the PLCA configuration using the standard registers in MMD 31.

#### <a id="c-genphy_c45_plca_get_status"></a>`genphy_c45_plca_get_status()`

```c
int genphy_c45_plca_get_status(struct phy_device *phydev, struct phy_plca_status *plca_st)
```

get PLCA status from standard registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct phy_plca_status *plca_st`: output structure to store the PLCA status

**Description**

- if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA

  Management Registers specifications, this function can be used to retrieve
  the current PLCA status information from the standard registers in MMD 31.

#### <a id="c-genphy_c45_eee_is_active"></a>`genphy_c45_eee_is_active()`

```c
int genphy_c45_eee_is_active(struct phy_device *phydev, unsigned long *lp)
```

get EEE status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `unsigned long *lp`: variable to store LP advertised linkmodes

**Description**

this function will read link partner PHY advertisement
and compare it to local advertisement to return current EEE state.

#### <a id="c-genphy_c45_ethtool_get_eee"></a>`genphy_c45_ethtool_get_eee()`

```c
int genphy_c45_ethtool_get_eee(struct phy_device *phydev, struct ethtool_keee *data)
```

get EEE supported and status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_keee *data`: ethtool_keee data

**Description**

it reports the Supported/Advertisement/LP Advertisement
capabilities.

#### <a id="c-genphy_c45_ethtool_set_eee"></a>`genphy_c45_ethtool_set_eee()`

```c
int genphy_c45_ethtool_set_eee(struct phy_device *phydev, struct ethtool_keee *data)
```

set EEE supported and status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `struct ethtool_keee *data`: ethtool_keee data

**Description**

sets the Supported/Advertisement/LP Advertisement
capabilities. If eee_enabled is false, no links modes are
advertised, but the previously advertised link modes are
retained. This allows EEE to be enabled/disabled in a
non-destructive way.
Returns either error code, 0 if there was no change, or positive
value if there was a change which triggered auto-neg.

#### <a id="c-genphy_c45_oatc14_cable_test_get_status"></a>`genphy_c45_oatc14_cable_test_get_status()`

```c
int genphy_c45_oatc14_cable_test_get_status(struct phy_device *phydev, bool *finished)
```

Get status of OATC14 10Base-T1S PHY cable test.

**Parameters**

- `struct phy_device *phydev`: pointer to the PHY device structure
- `bool *finished`: pointer to a boolean set true if the test is complete

**Description**

Retrieves the current status of the OATC14 10Base-T1S PHY cable test.
This function reads the OATC14 HDD register to determine whether the test
results are valid and whether the test has finished.

If the test is complete, the function reports the cable test result via
the ethtool cable test interface using `ethnl_cable_test_result()`, and then
clears the test control bit in the PHY register to reset the test state.

**Return**

0 on success, or a negative error code on failure (e.g. register
read/write error).

#### <a id="c-genphy_c45_oatc14_cable_test_start"></a>`genphy_c45_oatc14_cable_test_start()`

```c
int genphy_c45_oatc14_cable_test_start(struct phy_device *phydev)
```

Start a cable test on an OATC14 10Base-T1S PHY.

**Parameters**

- `struct phy_device *phydev`: Pointer to the PHY device structure

**Description**

This function initiates a cable diagnostic test on a Clause 45 OATC14
10Base-T1S capable PHY device. It first reads the PHY’s advanced diagnostic
capability register to check if High Definition Diagnostics (HDD) mode is
supported. If the PHY does not report HDD capability, cable testing is not
supported and the function returns -EOPNOTSUPP.

For PHYs that support HDD, the function sets the appropriate control bits in
the OATC14_HDD register to enable and start the cable diagnostic test.

**Return**

* 0 on success
* -EOPNOTSUPP if the PHY does not support HDD capability
* A negative error code on I/O or register access failures

#### <a id="c-genphy_c45_oatc14_get_sqi_max"></a>`genphy_c45_oatc14_get_sqi_max()`

```c
int genphy_c45_oatc14_get_sqi_max(struct phy_device *phydev)
```

Get maximum supported SQI or SQI+ level of OATC14 10Base-T1S PHY

**Parameters**

- `struct phy_device *phydev`: pointer to the PHY device structure

**Description**

This function returns the maximum supported Signal Quality Indicator (SQI) or
SQI+ level. The SQI capability is updated on first invocation if it has not
already been updated.

**Return**

* Maximum SQI/SQI+ level supported
* Negative errno on capability read failure

#### <a id="c-genphy_c45_oatc14_get_sqi"></a>`genphy_c45_oatc14_get_sqi()`

```c
int genphy_c45_oatc14_get_sqi(struct phy_device *phydev)
```

Get Signal Quality Indicator (SQI) from an OATC14 10Base-T1S PHY

**Parameters**

- `struct phy_device *phydev`: pointer to the PHY device structure

**Description**

This function reads the SQI+ or SQI value from an OATC14-compatible
10Base-T1S PHY. If SQI+ capability is supported, the function returns the
extended SQI+ value; otherwise, it returns the basic SQI value. The SQI
capability is updated on first invocation if it has not already been updated.

**Return**

* SQI/SQI+ value on success
* Negative errno on read failure



#### <a id="c-enum-phy_interface_t"></a>`enum phy_interface_t`

Interface Mode definitions

**Constants**

- `PHY_INTERFACE_MODE_NA`: Not Applicable - don't touch
- `PHY_INTERFACE_MODE_INTERNAL`: No interface, MAC and PHY combined
- `PHY_INTERFACE_MODE_MII`: Media-independent interface
- `PHY_INTERFACE_MODE_GMII`: Gigabit media-independent interface
- `PHY_INTERFACE_MODE_SGMII`: Serial gigabit media-independent interface
- `PHY_INTERFACE_MODE_TBI`: Ten Bit Interface
- `PHY_INTERFACE_MODE_REVMII`: Reverse Media Independent Interface
- `PHY_INTERFACE_MODE_RMII`: Reduced Media Independent Interface
- `PHY_INTERFACE_MODE_REVRMII`: Reduced Media Independent Interface in PHY role
- `PHY_INTERFACE_MODE_RGMII`: Reduced gigabit media-independent interface
- `PHY_INTERFACE_MODE_RGMII_ID`: RGMII with Internal RX+TX delay
- `PHY_INTERFACE_MODE_RGMII_RXID`: RGMII with Internal RX delay
- `PHY_INTERFACE_MODE_RGMII_TXID`: RGMII with Internal TX delay
- `PHY_INTERFACE_MODE_RTBI`: Reduced TBI
- `PHY_INTERFACE_MODE_SMII`: Serial MII
- `PHY_INTERFACE_MODE_XGMII`: 10 gigabit media-independent interface
- `PHY_INTERFACE_MODE_XLGMII`: 40 gigabit media-independent interface
- `PHY_INTERFACE_MODE_MOCA`: Multimedia over Coax
- `PHY_INTERFACE_MODE_PSGMII`: Penta SGMII
- `PHY_INTERFACE_MODE_QSGMII`: Quad SGMII
- `PHY_INTERFACE_MODE_TRGMII`: Turbo RGMII
- `PHY_INTERFACE_MODE_100BASEX`: 100 BaseX
- `PHY_INTERFACE_MODE_1000BASEX`: 1000 BaseX
- `PHY_INTERFACE_MODE_2500BASEX`: 2500 BaseX
- `PHY_INTERFACE_MODE_5GBASER`: 5G BaseR
- `PHY_INTERFACE_MODE_RXAUI`: Reduced XAUI
- `PHY_INTERFACE_MODE_XAUI`: 10 Gigabit Attachment Unit Interface
- `PHY_INTERFACE_MODE_10GBASER`: 10G BaseR
- `PHY_INTERFACE_MODE_25GBASER`: 25G BaseR
- `PHY_INTERFACE_MODE_USXGMII`: Universal Serial 10GE MII
- `PHY_INTERFACE_MODE_10GKR`: 10GBASE-KR - with Clause 73 AN
- `PHY_INTERFACE_MODE_QUSGMII`: Quad Universal SGMII
- `PHY_INTERFACE_MODE_1000BASEKX`: 1000Base-KX - with Clause 73 AN
- `PHY_INTERFACE_MODE_10G_QXGMII`: 10G-QXGMII - 4 ports over 10G USXGMII
- `PHY_INTERFACE_MODE_50GBASER`: 50GBase-R - with Clause 134 FEC
- `PHY_INTERFACE_MODE_LAUI`: 50 Gigabit Attachment Unit Interface
- `PHY_INTERFACE_MODE_100GBASEP`: 100GBase-P - with Clause 134 FEC
- `PHY_INTERFACE_MODE_MIILITE`: MII-Lite - MII without RXER TXER CRS COL
- `PHY_INTERFACE_MODE_MAX`: Book keeping

**Description**

Describes the interface between the MAC and PHY.

#### <a id="c-phy_modes"></a>`phy_modes()`

```c
const char * phy_modes(phy_interface_t interface)
```

map phy_interface_t enum to device tree binding of phy-mode

**Parameters**

- `phy_interface_t interface`: enum phy_interface_t value

**Description**

maps enum [`phy_interface_t`](#c-enum-phy_interface_t) defined in this file
into the device tree binding of 'phy-mode', so that Ethernet
device driver can get PHY interface from device tree.

#### <a id="c-rgmii_clock"></a>`rgmii_clock()`

```c
long rgmii_clock(int speed)
```

map link speed to the clock rate

**Parameters**

- `int speed`: link speed value

**Description**

maps RGMII supported link speeds into the clock rates.
This can also be used for MII, GMII, and RMII interface modes as the
clock rates are identical, but the caller must be aware that errors
for unsupported clock rates will not be signalled.

**Return**

clock rate or negative errno

#### <a id="c-struct-mdio_bus_stats"></a>`struct mdio_bus_stats`

Statistics counters for MDIO busses

**Definition**

```c
struct mdio_bus_stats {
    u64_stats_t transfers;
    u64_stats_t errors;
    u64_stats_t writes;
    u64_stats_t reads;
    struct u64_stats_sync syncp;
};
```

**Members**

- `transfers`: Total number of transfers, i.e. **writes** + **reads**
- `errors`: Number of MDIO transfers that returned an error
- `writes`: Number of write transfers
- `reads`: Number of read transfers
- `syncp`: Synchronisation for incrementing statistics

#### <a id="c-struct-mii_bus"></a>`struct mii_bus`

Represents an MDIO bus

**Definition**

```c
struct mii_bus {
        struct module *owner;
        const char *name;
        char id[MII_BUS_ID_SIZE];
        void *priv;
        int (*read)(struct mii_bus *bus, int addr, int regnum);
        int (*write)(struct mii_bus *bus, int addr, int regnum, u16 val);
        int (*read_c45)(struct mii_bus *bus, int addr, int devnum, int regnum);
        int (*write_c45)(struct mii_bus *bus, int addr, int devnum, int regnum, u16 val);
        int (*reset)(struct mii_bus *bus);
        struct mdio_bus_stats stats[PHY_MAX_ADDR];
        struct mutex mdio_lock;
        struct device *parent;
        enum {
            MDIOBUS_ALLOCATED = 1,
            MDIOBUS_REGISTERED,
            MDIOBUS_UNREGISTERED,
            MDIOBUS_RELEASED,
        } state;
        struct device dev;
        struct mdio_device *mdio_map[PHY_MAX_ADDR];
        u32 phy_mask;
        u32 phy_ignore_ta_mask;
        int irq[PHY_MAX_ADDR];
        int reset_delay_us;
        int reset_post_delay_us;
        struct gpio_desc *reset_gpiod;
        struct mutex shared_lock;
    #if IS_ENABLED(CONFIG_PHY_PACKAGE);
        struct phy_package_shared *shared[PHY_MAX_ADDR];
    #endif;
};
```

**Members**

- `owner`: Who owns this device
- `name`: User friendly name for this MDIO device, or driver name
- `id`: Unique identifier for this bus, typical from bus hierarchy
- `priv`: Driver private data
- `read`: Perform a read transfer on the bus
- `write`: Perform a write transfer on the bus
- `read_c45`: Perform a C45 read transfer on the bus
- `write_c45`: Perform a C45 write transfer on the bus
- `reset`: Perform a reset of the bus
- `stats`: Statistic counters per device on the bus
- `mdio_lock`: A lock to ensure that only one thing can read/write
  the MDIO bus at a time
- `parent`: Parent device of this bus
- `state`: State of bus structure
- `dev`: Kernel device representation
- `mdio_map`: list of all MDIO devices on bus
- `phy_mask`: PHY addresses to be ignored when probing
- `phy_ignore_ta_mask`: PHY addresses to ignore the TA/read failure
- `irq`: An array of interrupts, each PHY's interrupt at the index
  matching its address
- `reset_delay_us`: GPIO reset pulse width in microseconds
- `reset_post_delay_us`: GPIO reset deassert delay in microseconds
- `reset_gpiod`: Reset GPIO descriptor pointer
- `shared_lock`: protect access to the shared element
- `shared`: shared state across different PHYs

**Description**

The Bus class for PHYs.  Devices which provide access to
PHYs should register using this structure

#### <a id="c-mdiobus_alloc"></a>`mdiobus_alloc()`

```c
struct mii_bus * mdiobus_alloc(void)
```

Allocate an MDIO bus structure

**Parameters**

- `void`: no arguments

**Description**

The internal state of the MDIO bus will be set of MDIOBUS_ALLOCATED ready
for the driver to register the bus.

#### <a id="c-enum-phy_state"></a>`enum phy_state`

PHY state machine states:

**Constants**

- `PHY_DOWN`: PHY device and driver are not ready for anything.  probe
  should be called if and only if the PHY is in this state,
  given that the PHY device exists.
  - PHY driver probe function will set the state to **PHY_READY**
- `PHY_READY`: PHY is ready to send and receive packets, but the
  controller is not.  By default, PHYs which do not implement
  probe will be set to this state by [`phy_probe()`](#c-phy_probe).
  - start will set the state to UP
- `PHY_HALTED`: PHY is up, but no polling or interrupts are done.
  - phy_start moves to **PHY_UP**
- `PHY_ERROR`: PHY is up, but is in an error state.
  - phy_stop moves to **PHY_HALTED**
- `PHY_UP`: The PHY and attached device are ready to do work.
  Interrupts should be started here.
  - timer moves to **PHY_NOLINK** or **PHY_RUNNING**
- `PHY_RUNNING`: PHY is currently up, running, and possibly sending
  and/or receiving packets
  - irq or timer will set **PHY_NOLINK** if link goes down
  - phy_stop moves to **PHY_HALTED**
- `PHY_NOLINK`: PHY is up, but not currently plugged in.
  - irq or timer will set **PHY_RUNNING** if link comes back
  - phy_stop moves to **PHY_HALTED**
- `PHY_CABLETEST`: PHY is performing a cable test. Packet reception/sending
  is not expected to work, carrier will be indicated as down. PHY will be
  poll once per second, or on interrupt for it current state.
  Once complete, move to UP to restart the PHY.
  - phy_stop aborts the running test and moves to **PHY_HALTED**

#### <a id="c-struct-phy_c45_device_ids"></a>`struct phy_c45_device_ids`

802.3-c45 Device Identifiers

**Definition**

```c
struct phy_c45_device_ids {
    u32 devices_in_package;
    u32 mmds_present;
    u32 device_ids[MDIO_MMD_NUM];
};
```

**Members**

- `devices_in_package`: IEEE 802.3 devices in package register value.
- `mmds_present`: bit vector of MMDs present.
- `device_ids`: The device identifier for each present device.

#### <a id="c-struct-phy_oatc14_sqi_capability"></a>`struct phy_oatc14_sqi_capability`

SQI capability information for OATC14 10Base-T1S PHY

**Definition**

```c
struct phy_oatc14_sqi_capability {
    bool updated;
    int sqi_max;
    u8 sqiplus_bits;
};
```

**Members**

- `updated`: Indicates whether the SQI capability fields have been updated.
- `sqi_max`: Maximum supported Signal Quality Indicator (SQI) level reported by
  the PHY.
- `sqiplus_bits`: Bits for SQI+ levels supported by the PHY.
  0 - SQI+ is not supported
  3 - SQI+ is supported, using 3 bits (8 levels)
  4 - SQI+ is supported, using 4 bits (16 levels)
  5 - SQI+ is supported, using 5 bits (32 levels)
  6 - SQI+ is supported, using 6 bits (64 levels)
  7 - SQI+ is supported, using 7 bits (128 levels)
  8 - SQI+ is supported, using 8 bits (256 levels)

**Description**

This structure is used by the OATC14 10Base-T1S PHY driver to store the SQI
and SQI+ capability information retrieved from the PHY.

#### <a id="c-struct-phy_device"></a>`struct phy_device`

An instance of a PHY

**Definition**

```c
struct phy_device {
        struct mdio_device mdio;
        const struct phy_driver *drv;
        struct device_link *devlink;
        u32 phyindex;
        u32 phy_id;
        struct phy_c45_device_ids c45_ids;
        unsigned is_c45:1;
        unsigned is_internal:1;
        unsigned is_pseudo_fixed_link:1;
        unsigned is_gigabit_capable:1;
        unsigned has_fixups:1;
        unsigned suspended:1;
        unsigned suspended_by_mdio_bus:1;
        unsigned sysfs_links:1;
        unsigned loopback_enabled:1;
        unsigned downshifted_rate:1;
        unsigned is_on_sfp_module:1;
        unsigned mac_managed_pm:1;
        unsigned wol_enabled:1;
        unsigned is_genphy_driven:1;
        unsigned autoneg:1;
        unsigned link:1;
        unsigned autoneg_complete:1;
        bool pause:1;
        bool asym_pause:1;
        unsigned interrupts:1;
        unsigned irq_suspended:1;
        unsigned irq_rerun:1;
        unsigned default_timestamp:1;
        int rate_matching;
        enum phy_state state;
        u32 dev_flags;
        phy_interface_t interface;
        unsigned long possible_interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
        int speed;
        int duplex;
        int port;
        u8 master_slave_get;
        u8 master_slave_set;
        u8 master_slave_state;
        unsigned long supported[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long advertising[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long lp_advertising[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long adv_old[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long supported_eee[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long advertising_eee[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        unsigned long eee_disabled_modes[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
        bool enable_tx_lpi;
        bool eee_active;
        struct eee_config eee_cfg;
        unsigned long host_interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
    #ifdef CONFIG_LED_TRIGGER_PHY;
        struct phy_led_trigger *phy_led_triggers;
        unsigned int phy_num_led_triggers;
        struct phy_led_trigger *last_triggered;
        struct phy_led_trigger *led_link_trigger;
    #endif;
        struct list_head leds;
        int irq;
        void *priv;
    #if IS_ENABLED(CONFIG_PHY_PACKAGE);
        struct phy_package_shared *shared;
    #endif;
        struct sk_buff *skb;
        void *ehdr;
        struct nlattr *nest;
        struct delayed_work state_queue;
        struct mutex lock;
        bool sfp_bus_attached;
        struct sfp_bus *sfp_bus;
        struct phylink *phylink;
        struct net_device *attached_dev;
        struct mii_timestamper *mii_ts;
        struct pse_control *psec;
        struct list_head ports;
        int n_ports;
        int max_n_ports;
        u8 mdix;
        u8 mdix_ctrl;
        int pma_extable;
        unsigned int link_down_events;
        void (*phy_link_change)(struct phy_device *phydev, bool up);
        void (*adjust_link)(struct net_device *dev);
    #if IS_ENABLED(CONFIG_MACSEC);
        const struct macsec_ops *macsec_ops;
    #endif;
        struct phy_oatc14_sqi_capability oatc14_sqi_capability;
};
```

**Members**

- `mdio`: MDIO bus this PHY is on
- `drv`: Pointer to the driver for this PHY instance
- `devlink`: Create a link between phy dev and mac dev, if the external phy
  used by current mac interface is managed by another mac interface.
- `phyindex`: Unique id across the phy's parent tree of phys to address the PHY
  from userspace, similar to ifindex. A zero index means the PHY
  wasn't assigned an id yet.
- `phy_id`: UID for this device found during discovery
- `c45_ids`: 802.3-c45 Device Identifiers if is_c45.
- `is_c45`: Set to true if this PHY uses clause 45 addressing.
- `is_internal`: Set to true if this PHY is internal to a MAC.
- `is_pseudo_fixed_link`: Set to true if this PHY is an Ethernet switch, etc.
- `is_gigabit_capable`: Set to true if PHY supports 1000Mbps
- `has_fixups`: Set to true if this PHY has fixups/quirks.
- `suspended`: Set to true if this PHY has been suspended successfully.
- `suspended_by_mdio_bus`: Set to true if this PHY was suspended by MDIO bus.
- `sysfs_links`: Internal boolean tracking sysfs symbolic links setup/removal.
- `loopback_enabled`: Set true if this PHY has been loopbacked successfully.
- `downshifted_rate`: Set true if link speed has been downshifted.
- `is_on_sfp_module`: Set true if PHY is located on an SFP module.
- `mac_managed_pm`: Set true if MAC driver takes of suspending/resuming PHY
- `wol_enabled`: Set to true if the PHY or the attached MAC have Wake-on-LAN
  enabled.
- `is_genphy_driven`: PHY is driven by one of the generic PHY drivers
- `autoneg`: Flag autoneg being used
- `link`: Current link state
- `autoneg_complete`: Flag auto negotiation of the link has completed
- `pause`: Current pause
- `asym_pause`: Current asymmetric pause
- `interrupts`: Flag interrupts have been enabled
- `irq_suspended`: Flag indicating PHY is suspended and therefore interrupt
  handling shall be postponed until PHY has resumed
- `irq_rerun`: Flag indicating interrupts occurred while PHY was suspended,
  requiring a rerun of the interrupt handler after resume
- `default_timestamp`: Flag indicating whether we are using the phy
  timestamp as the default one
- `rate_matching`: Current rate matching mode
- `state`: State of the PHY for management purposes
- `dev_flags`: Device-specific flags used by the PHY driver.
- `interface`: enum phy_interface_t value
- `possible_interfaces`: bitmap if interface modes that the attached PHY
  will switch between depending on media speed.
- `speed`: Current link speed
- `duplex`: Current duplex
- `port`: Current port
- `master_slave_get`: Current master/slave advertisement
- `master_slave_set`: User requested master/slave configuration
- `master_slave_state`: Current master/slave configuration
- `supported`: Combined MAC/PHY supported linkmodes
- `advertising`: Currently advertised linkmodes
- `lp_advertising`: Current link partner advertised linkmodes
- `adv_old`: Saved advertised while power saving for WoL
- `supported_eee`: supported PHY EEE linkmodes
- `advertising_eee`: Currently advertised EEE linkmodes
- `eee_disabled_modes`: Energy efficient ethernet modes not to be advertised
- `enable_tx_lpi`: When True, MAC should transmit LPI to PHY
- `eee_active`: phylib private state, indicating that EEE has been negotiated
- `eee_cfg`: User configuration of EEE
- `host_interfaces`: PHY interface modes supported by host
- `phy_led_triggers`: Array of LED triggers
- `phy_num_led_triggers`: Number of triggers in **phy_led_triggers**
- `last_triggered`: last LED trigger for link speed
- `led_link_trigger`: LED trigger for link up/down
- `leds`: list of PHY LED structures
- `irq`: IRQ number of the PHY's interrupt (-1 if none)
- `priv`: Pointer to driver private data
- `shared`: Pointer to private data shared by phys in one package
- `skb`: Netlink message for cable diagnostics
- `ehdr`: nNtlink header for cable diagnostics
- `nest`: Netlink nest used for cable diagnostics
- `state_queue`: Work queue for state machine
- `lock`: Mutex for serialization access to PHY
- `sfp_bus_attached`: Flag indicating whether the SFP bus has been attached
- `sfp_bus`: SFP bus attached to this PHY's fiber port
- `phylink`: Pointer to phylink instance for this PHY
- `attached_dev`: The attached enet driver's device instance ptr
- `mii_ts`: Pointer to time stamper callbacks
- `psec`: Pointer to Power Sourcing Equipment control struct
- `ports`: List of PHY ports structures
- `n_ports`: Number of ports currently attached to the PHY
- `max_n_ports`: Max number of ports this PHY can expose
- `mdix`: Current crossover
- `mdix_ctrl`: User setting of crossover
- `pma_extable`: Cached value of PMA/PMD Extended Abilities Register
- `link_down_events`: Number of times link was lost
- `phy_link_change`: Callback for phylink for notification of link change
- `adjust_link`: Callback for the enet controller to respond to changes: in the
  link state.
- `macsec_ops`: MACsec offloading ops.
- `oatc14_sqi_capability`: SQI capability information for OATC14 10Base-T1S PHY

**Description**

- Bits \[15:0\] are free to use by the PHY driver to communicate
  driver specific behavior.
- Bits \[23:16\] are currently reserved for future use.
- Bits \[31:24\] are reserved for defining generic
  PHY driver behavior.

interrupts currently only supports enabled or disabled,
but could be changed in the future to support enabling
and disabling specific interrupts

Contains some infrastructure for polling and interrupt
handling, as well as handling shifts in PHY hardware state

#### <a id="c-struct-phy_tdr_config"></a>`struct phy_tdr_config`

Configuration of a TDR raw test

**Definition**

```c
struct phy_tdr_config {
    u32 first;
    u32 last;
    u32 step;
    s8 pair;
};
```

**Members**

- `first`: Distance for first data collection point
- `last`: Distance for last data collection point
- `step`: Step between data collection points
- `pair`: Bitmap of cable pairs to collect data for

**Description**

A structure containing possible configuration parameters
for a TDR cable test. The driver does not need to implement
all the parameters, but should report what is actually used.
All distances are in centimeters.

#### <a id="c-enum-link_inband_signalling"></a>`enum link_inband_signalling`

in-band signalling modes that are supported

**Constants**

- `LINK_INBAND_DISABLE`: in-band signalling can be disabled
- `LINK_INBAND_ENABLE`: in-band signalling can be enabled without bypass
- `LINK_INBAND_BYPASS`: in-band signalling can be enabled with bypass

**Description**

The possible and required bits can only be used if the valid bit is set.
If possible is clear, that means inband signalling can not be used.
Required is only valid when possible is set, and means that inband
signalling must be used.

#### <a id="c-struct-phy_plca_cfg"></a>`struct phy_plca_cfg`

Configuration of the PLCA (Physical Layer Collision Avoidance) Reconciliation Sublayer.

**Definition**

```c
struct phy_plca_cfg {
    int version;
    int enabled;
    int node_id;
    int node_cnt;
    int to_tmr;
    int burst_cnt;
    int burst_tmr;
};
```

**Members**

- `version`: read-only PLCA register map version. -1 = not available. Ignored
  when setting the configuration. Format is the same as reported by the PLCA
  IDVER register (31.CA00). -1 = not available.
- `enabled`: PLCA configured mode (enabled/disabled). -1 = not available / don't
  set. 0 = disabled, anything else = enabled.
- `node_id`: the PLCA local node identifier. -1 = not available / don't set.
  Allowed values \[0 .. 254\]. 255 = node disabled.
- `node_cnt`: the PLCA node count (maximum number of nodes having a TO). Only
  meaningful for the coordinator (node_id = 0). -1 = not available / don't
  set. Allowed values \[1 .. 255\].
- `to_tmr`: The value of the PLCA to_timer in bit-times, which determines the
  PLCA transmit opportunity window opening. See IEEE802.3 Clause 148 for
  more details. The to_timer shall be set equal over all nodes.
  -1 = not available / don't set. Allowed values \[0 .. 255\].
- `burst_cnt`: controls how many additional frames a node is allowed to send in
  single transmit opportunity (TO). The default value of 0 means that the
  node is allowed exactly one frame per TO. A value of 1 allows two frames
  per TO, and so on. -1 = not available / don't set.
  Allowed values \[0 .. 255\].
- `burst_tmr`: controls how many bit times to wait for the MAC to send a new
  frame before interrupting the burst. This value should be set to a value
  greater than the MAC inter-packet gap (which is typically 96 bits).
  -1 = not available / don't set. Allowed values \[0 .. 255\].

**Description**

A structure containing configuration parameters for setting/getting the PLCA
RS configuration. The driver does not need to implement all the parameters,
but should report what is actually used.

#### <a id="c-struct-phy_plca_status"></a>`struct phy_plca_status`

Status of the PLCA (Physical Layer Collision Avoidance) Reconciliation Sublayer.

**Definition**

```c
struct phy_plca_status {
    bool pst;
};
```

**Members**

- `pst`: The PLCA status as reported by the PST bit in the PLCA STATUS
  register(31.CA03), indicating BEACON activity.

**Description**

A structure containing status information of the PLCA RS configuration.
The driver does not need to implement all the parameters, but should report
what is actually used.

#### <a id="c-struct-phy_led"></a>`struct phy_led`

An LED driven by the PHY

**Definition**

```c
struct phy_led {
    struct list_head list;
    struct phy_device *phydev;
    struct led_classdev led_cdev;
    u8 index;
};
```

**Members**

- `list`: List of LEDs
- `phydev`: PHY this LED is attached to
- `led_cdev`: Standard LED class structure
- `index`: Number of the LED

#### <a id="c-struct-phy_mse_capability"></a>`struct phy_mse_capability`

Capabilities of Mean Square Error (MSE) measurement interface

**Definition**

```c
struct phy_mse_capability {
    u64 max_average_mse;
    u64 max_peak_mse;
    u64 refresh_rate_ps;
    u64 num_symbols;
    u32 supported_caps;
};
```

**Members**

- `max_average_mse`: The maximum value for an average MSE snapshot. This
  defines the scale for the measurement. If the PHY_MSE_CAP_AVG capability is
  supported, this value MUST be greater than 0. (vendor-specific units).
- `max_peak_mse`: The maximum value for a peak MSE snapshot. If either
  PHY_MSE_CAP_PEAK or PHY_MSE_CAP_WORST_PEAK is supported, this value MUST
  be greater than 0. (vendor-specific units).
- `refresh_rate_ps`: The typical interval, in picoseconds, between hardware
  updates of the MSE values. This is an estimate, and callers should not
  assume synchronous sampling. (vendor-specific units).
- `num_symbols`: The number of symbols aggregated per hardware sample to
  calculate the MSE. (vendor-specific units).
- `supported_caps`: A bitmask of PHY_MSE_CAP_* values indicating which
  measurement types (e.g., average, peak) and channels
  (e.g., per-pair or link-wide) are supported.

**Description**

Standardization notes:

- Presence of MSE/SQI/pMSE is defined by OPEN Alliance specs, but numeric
  scaling, refresh/update rate and aggregation windows are not fixed and
  are vendor-/product-specific. (OA 100BASE-T1 TC1 v1.0 6.1.*;
  OA 1000BASE-T1 TC12 v2.2 6.1.*)

- Typical recommendations: 2^16 symbols and 0..511 scaling for MSE; pMSE only
  defined for 100BASE-T1 (sliding window example), others are vendor
  extensions. Drivers must report actual scale/limits here.

Describes the MSE measurement capabilities for the current link mode. These
properties are dynamic and may change when link settings are modified.
Callers should re-query this capability after any link state change to
ensure they have the most up-to-date information.

Callers should only request measurements for channels and types that are
indicated as supported by the **supported_caps** bitmask. If **supported_caps**
is 0, the device provides no MSE diagnostics, and driver operations should
typically return -EOPNOTSUPP.

Snapshot values for average and peak MSE can be normalized to a 0..1 ratio
by dividing the raw snapshot by the corresponding **max_average_mse** or
**max_peak_mse** value.

#### <a id="c-struct-phy_mse_snapshot"></a>`struct phy_mse_snapshot`

A snapshot of Mean Square Error (MSE) diagnostics

**Definition**

```c
struct phy_mse_snapshot {
    u64 average_mse;
    u64 peak_mse;
    u64 worst_peak_mse;
};
```

**Members**

- `average_mse`: The average MSE value over the measurement window.
  OPEN Alliance references MSE as a DCQ metric; recommends 2^16 symbols and
  0..511 scaling. Exact scale and refresh are vendor-specific.
  (100BASE-T1 TC1 v1.0 6.1.1; 1000BASE-T1 TC12 v2.2 6.1.1).
- `peak_mse`: The peak MSE value observed within the measurement window.
  For 100BASE-T1, "pMSE" is optional and may be implemented via a sliding
  128-symbol window with periodic capture; not standardized for 1000BASE-T1.
  (100BASE-T1 TC1 v1.0 6.1.3, Table "DCQ.peakMSE").
- `worst_peak_mse`: A latched high-water mark of the peak MSE since last read
  (read-to-clear if implemented). OPEN Alliance shows a latched "worst case
  peak MSE" for 100BASE-T1 pMSE; availability/semantics outside that are
  vendor-specific. (100BASE-T1 TC1 v1.0 6.1.3, DCQ.peakMSE high byte;
  1000BASE-T1 TC12 v2.2 treats DCQ details as vendor-specific.)

**Description**

Holds a set of MSE diagnostic values that were all captured from a single
measurement window.

Values are raw, device-scaled and not normalized. Use struct
phy_mse_capability to interpret the scale and sampling window.

#### <a id="c-struct-phy_driver"></a>`struct phy_driver`

Driver structure for a particular PHY type

**Definition**

```c
struct phy_driver {
    struct mdio_driver_common mdiodrv;
    u32 phy_id;
    char *name;
    u32 phy_id_mask;
    const unsigned long * const features;
    u32 flags;
    const void *driver_data;
    int (*soft_reset)(struct phy_device *phydev);
    int (*config_init)(struct phy_device *phydev);
    int (*probe)(struct phy_device *phydev);
    int (*get_features)(struct phy_device *phydev);
    unsigned int (*inband_caps)(struct phy_device *phydev, phy_interface_t interface);
    int (*config_inband)(struct phy_device *phydev, unsigned int modes);
    int (*get_rate_matching)(struct phy_device *phydev, phy_interface_t iface);
    int (*suspend)(struct phy_device *phydev);
    int (*resume)(struct phy_device *phydev);
    int (*config_aneg)(struct phy_device *phydev);
    int (*aneg_done)(struct phy_device *phydev);
    int (*read_status)(struct phy_device *phydev);
    int (*config_intr)(struct phy_device *phydev);
    irqreturn_t (*handle_interrupt)(struct phy_device *phydev);
    void (*remove)(struct phy_device *phydev);
    int (*match_phy_device)(struct phy_device *phydev, const struct phy_driver *phydrv);
    int (*set_wol)(struct phy_device *dev, struct ethtool_wolinfo *wol);
    void (*get_wol)(struct phy_device *dev, struct ethtool_wolinfo *wol);
    void (*link_change_notify)(struct phy_device *dev);
    int (*read_mmd)(struct phy_device *dev, int devnum, u16 regnum);
    int (*write_mmd)(struct phy_device *dev, int devnum, u16 regnum, u16 val);
    int (*read_page)(struct phy_device *dev);
    int (*write_page)(struct phy_device *dev, int page);
    int (*module_info)(struct phy_device *dev, struct ethtool_modinfo *modinfo);
    int (*module_eeprom)(struct phy_device *dev, struct ethtool_eeprom *ee, u8 *data);
    int (*cable_test_start)(struct phy_device *dev);
    int (*cable_test_tdr_start)(struct phy_device *dev, const struct phy_tdr_config *config);
    int (*cable_test_get_status)(struct phy_device *dev, bool *finished);
    void (*get_phy_stats)(struct phy_device *dev, struct ethtool_eth_phy_stats *eth_stats, struct ethtool_phy_stats *stats);
    void (*get_link_stats)(struct phy_device *dev, struct ethtool_link_ext_stats *link_stats);
    int (*update_stats)(struct phy_device *dev);
    int (*get_sset_count)(struct phy_device *dev);
    void (*get_strings)(struct phy_device *dev, u8 *data);
    void (*get_stats)(struct phy_device *dev, struct ethtool_stats *stats, u64 *data);
    int (*get_tunable)(struct phy_device *dev, struct ethtool_tunable *tuna, void *data);
    int (*set_tunable)(struct phy_device *dev, struct ethtool_tunable *tuna, const void *data);
    int (*set_loopback)(struct phy_device *dev, bool enable, int speed);
    int (*get_sqi)(struct phy_device *dev);
    int (*get_sqi_max)(struct phy_device *dev);
    int (*get_mse_capability)(struct phy_device *dev, struct phy_mse_capability *cap);
    int (*get_mse_snapshot)(struct phy_device *dev, enum phy_mse_channel channel, struct phy_mse_snapshot *snapshot);
    int (*get_plca_cfg)(struct phy_device *dev, struct phy_plca_cfg *plca_cfg);
    int (*set_plca_cfg)(struct phy_device *dev, const struct phy_plca_cfg *plca_cfg);
    int (*get_plca_status)(struct phy_device *dev, struct phy_plca_status *plca_st);
    int (*led_brightness_set)(struct phy_device *dev, u8 index, enum led_brightness value);
    int (*led_blink_set)(struct phy_device *dev, u8 index, unsigned long *delay_on, unsigned long *delay_off);
    int (*led_hw_is_supported)(struct phy_device *dev, u8 index, unsigned long rules);
    int (*led_hw_control_set)(struct phy_device *dev, u8 index, unsigned long rules);
    int (*led_hw_control_get)(struct phy_device *dev, u8 index, unsigned long *rules);
    int (*led_polarity_set)(struct phy_device *dev, int index, unsigned long modes);
    unsigned int (*get_next_update_time)(struct phy_device *dev);
    int (*attach_mii_port)(struct phy_device *dev, struct phy_port *port);
    int (*attach_mdi_port)(struct phy_device *dev, struct phy_port *port);
};
```

**Members**

- `mdiodrv`: Data common to all MDIO devices
- `phy_id`: The result of reading the UID registers of this PHY
  type, and ANDing them with the phy_id_mask.  This driver
  only works for PHYs with IDs which match this field
- `name`: The friendly name of this PHY type
- `phy_id_mask`: Defines the important bits of the phy_id
- `features`: A mandatory list of features (speed, duplex, etc)
  supported by this PHY
- `flags`: A bitfield defining certain other features this PHY
  supports (like interrupts)
- `driver_data`: Static driver data
- `soft_reset`: Called to issue a PHY software reset
- `config_init`: Called to initialize the PHY,
  including after a reset
- `probe`: Called during discovery.  Used to set
  up device-specific structures, if any
- `get_features`: Probe the hardware to determine what
  abilities it has.  Should only set phydev->supported.
- `inband_caps`: query whether in-band is supported for the given PHY
  interface mode. Returns a bitmask of bits defined by enum
  link_inband_signalling.
- `config_inband`: configure in-band mode for the PHY
- `get_rate_matching`: Get the supported type of rate matching for a
  particular phy interface. This is used by phy consumers to determine
  whether to advertise lower-speed modes for that interface. It is
  assumed that if a rate matching mode is supported on an interface,
  then that interface's rate can be adapted to all slower link speeds
  supported by the phy. If the interface is not supported, this should
  return `RATE_MATCH_NONE`.
- `suspend`: Suspend the hardware, saving state if needed
- `resume`: Resume the hardware, restoring state if needed
- `config_aneg`: Configures the advertisement and resets
  autonegotiation if phydev->autoneg is on,
  forces the speed to the current settings in phydev
  if phydev->autoneg is off
- `aneg_done`: Determines the auto negotiation result
- `read_status`: Determines the negotiated speed and duplex
- `config_intr`: Enables or disables interrupts.
  It should also clear any pending interrupts prior to enabling the
  IRQs and after disabling them.
- `handle_interrupt`: Override default interrupt handling
- `remove`: Clears up any memory if needed
- `match_phy_device`: Returns true if this is a suitable
  driver for the given phydev.  If NULL, matching is based on
  phy_id and phy_id_mask.
- `set_wol`: Some devices (e.g. qnap TS-119P II) require PHY
  register changes to enable Wake on LAN, so set_wol is
  provided to be called in the ethernet driver's set_wol
  function.
- `get_wol`: See set_wol, but for checking whether Wake on LAN
  is enabled.
- `link_change_notify`: Called to inform a PHY device driver
  when the core is about to change the link state. This
  callback is supposed to be used as fixup hook for drivers
  that need to take action when the link state
  changes. Drivers are by no means allowed to mess with the
  PHY device structure in their implementations.
- `read_mmd`: PHY specific driver override for reading a MMD
  register.  This function is optional for PHY specific
  drivers.  When not provided, the default MMD read function
  will be used by [`phy_read_mmd()`](#c-phy_read_mmd), which will use either a
  direct read for Clause 45 PHYs or an indirect read for
  Clause 22 PHYs.  devnum is the MMD device number within the
  PHY device, regnum is the register within the selected MMD
  device.
- `write_mmd`: PHY specific driver override for writing a MMD
  register.  This function is optional for PHY specific
  drivers.  When not provided, the default MMD write function
  will be used by [`phy_write_mmd()`](#c-phy_write_mmd), which will use either a
  direct write for Clause 45 PHYs, or an indirect write for
  Clause 22 PHYs.  devnum is the MMD device number within the
  PHY device, regnum is the register within the selected MMD
  device.  val is the value to be written.
- `read_page`: Return the current PHY register page number
- `write_page`: Set the current PHY register page number
- `module_info`: Get the size and type of the eeprom contained
  within a plug-in module
- `module_eeprom`: Get the eeprom information from the plug-in
  module
- `cable_test_start`: Start a cable test
- `cable_test_tdr_start`: Start a raw TDR cable test
- `cable_test_get_status`: Once per second, or on interrupt,
  request the status of the test.
- `get_phy_stats`: Retrieve PHY statistics.
  **dev**: The PHY device for which the statistics are retrieved.
  **eth_stats**: structure where Ethernet PHY stats will be stored.
  **stats**: structure where additional PHY-specific stats will be stored.

  Retrieves the supported PHY statistics and populates the provided
  structures. The input structures are pre-initialized with
  `ETHTOOL_STAT_NOT_SET`, and the driver must only modify members
  corresponding to supported statistics. Unmodified members will remain
  set to `ETHTOOL_STAT_NOT_SET` and will not be returned to userspace.
- `get_link_stats`: Retrieve link statistics.
  **dev**: The PHY device for which the statistics are retrieved.
  **link_stats**: structure where link-specific stats will be stored.

  Retrieves link-related statistics for the given PHY device. The input
  structure is pre-initialized with `ETHTOOL_STAT_NOT_SET`, and the
  driver must only modify members corresponding to supported
  statistics. Unmodified members will remain set to
  `ETHTOOL_STAT_NOT_SET` and will not be returned to userspace.
- `update_stats`: Trigger periodic statistics updates.
  **dev**: The PHY device for which statistics updates are triggered.

  Periodically gathers statistics from the PHY device to update locally
  maintained 64-bit counters. This is necessary for PHYs that implement
  reduced-width counters (e.g., 16-bit or 32-bit) which can overflow
  more frequently compared to 64-bit counters. By invoking this
  callback, drivers can fetch the current counter values, handle
  overflow detection, and accumulate the results into local 64-bit
  counters for accurate reporting through the `get_phy_stats` and
  `get_link_stats` interfaces.

  Return: 0 on success or a negative error code on failure.
- `get_sset_count`: Number of statistic counters
- `get_strings`: Names of the statistic counters
- `get_stats`: Return the statistic counter values
- `get_tunable`: Return the value of a tunable
- `set_tunable`: Set the value of a tunable
- `set_loopback`: Set the loopback mode of the PHY
  enable selects if the loopback mode is enabled or disabled. If the
  loopback mode is enabled, then the speed of the loopback mode can be
  requested with the speed argument. If the speed argument is zero,
  then any speed can be selected. If the speed argument is > 0, then
  this speed shall be selected for the loopback mode or EOPNOTSUPP
  shall be returned if speed selection is not supported.
- `get_sqi`: Get the signal quality indication
- `get_sqi_max`: Get the maximum signal quality indication
- `get_mse_capability`: Get capabilities and scale of MSE measurement
  **dev**:    PHY device
  **cap**: Output (filled on success)

  Fill **cap** with the PHY's MSE capability for the current
  link mode: scale limits (max_average_mse, max_peak_mse), update
  interval (refresh_rate_ps), sample length (num_symbols) and the
  capability bitmask (supported_caps).

  Implementations may defer capability report until hardware has
  converged; in that case they should return -EAGAIN and allow the
  caller to retry later.

  Return: 0 on success. On failure, returns a negative errno code, such
  as -EOPNOTSUPP if MSE measurement is not supported by the PHY or in
  the current link mode, or -EAGAIN if the capability information is
  not yet available.
- `get_mse_snapshot`: Retrieve a snapshot of MSE diagnostic values
  **dev**:      PHY device
  **channel**:  Channel identifier (PHY_MSE_CHANNEL_*)
  **snapshot**: Output (filled on success)

  Fill **snapshot** with a correlated set of MSE values from the most
  recent measurement window.

  Callers must validate **channel** against supported_caps returned by
  `get_mse_capability()`. Drivers must not coerce **channel**; if the
  requested selector is not implemented by the device or current link
  mode, the operation must fail.

  worst_peak_mse is latched and must be treated as read-to-clear.

  Return: 0 on success. On failure, returns a negative errno code, such
  as -EOPNOTSUPP if MSE measurement is not supported by the PHY or in
  the current link mode, or -EAGAIN if measurements are not yet
  available.
- `get_plca_cfg`: Return the current PLCA configuration
- `set_plca_cfg`: Set the PLCA configuration
- `get_plca_status`: Return the current PLCA status info
- `led_brightness_set`: Set a PHY LED brightness. Index
  indicates which of the PHYs led should be set. Value
  follows the standard LED class meaning, e.g. LED_OFF,
  LED_HALF, LED_FULL.
- `led_blink_set`: Set a PHY LED blinking.  Index indicates
  which of the PHYs led should be configured to blink. Delays
  are in milliseconds and if both are zero then a sensible
  default should be chosen.  The call should adjust the
  timings in that case and if it can't match the values
  specified exactly.
- `led_hw_is_supported`: Can the HW support the given rules.
  **dev**: PHY device which has the LED
  **index**: Which LED of the PHY device
  **rules** The core is interested in these rules

  Return 0 if yes,  -EOPNOTSUPP if not, or an error code.
- `led_hw_control_set`: Set the HW to control the LED
  **dev**: PHY device which has the LED
  **index**: Which LED of the PHY device
  **rules** The rules used to control the LED

  Returns 0, or a an error code.
- `led_hw_control_get`: Get how the HW is controlling the LED
  **dev**: PHY device which has the LED
  **index**: Which LED of the PHY device
  **rules** Pointer to the rules used to control the LED

  Set **\*rules** to how the HW is currently blinking. Returns 0
  on success, or a error code if the current blinking cannot
  be represented in rules, or some other error happens.
- `led_polarity_set`: Set the LED polarity modes
  **dev**: PHY device which has the LED
  **index**: Which LED of the PHY device
  **modes**: bitmap of LED polarity modes

  Configure LED with all the required polarity modes in **modes**
  to make it correctly turn ON or OFF.

  Returns 0, or an error code.
- `get_next_update_time`: Get the time until the next update event
  **dev**: PHY device

  Callback to determine the time (in jiffies) until the next
  update event for the PHY state  machine. Allows PHY drivers to
  dynamically adjust polling intervals based on link state or other
  conditions.

  Returns the time in jiffies until the next update event.
- `attach_mii_port`: Attach the given MII port to the PHY device
  **dev**: PHY device to notify
  **port**: The port being added

  Called when an MII port that needs to be driven by the PHY is found.

  The port that is being passed may or may not be initialized. If it is
  already initialized, it is by the generic port representation from
  devicetree, which superseeds any strapping or vendor-specific
  properties.

  If the port isn't initialized, the port->mediums and port->lanes
  fields must be set, possibly according to strapping information.

  The PHY driver must set the port->interfaces field to indicate the
  possible MII modes that this PHY can output on the port.

  Returns 0, or an error code.
- `attach_mdi_port`: Attach the given MII port to the PHY device
  **dev**: PHY device to notify
  **port**: The port being added

  Called when a port that needs to be driven by the PHY is found. The
  number of time this will be called depends on phydev->max_n_ports,
  which the driver can change in .`probe()`.

  The port that is being passed may or may not be initialized. If it is
  already initialized, it is by the generic port representation from
  devicetree, which superseeds any strapping or vendor-specific
  properties.

  If the port isn't initialized, the port->mediums and port->lanes
  fields must be set, possibly according to strapping information.

  Returns 0, or an error code.

**Description**

All functions are optional. If config_aneg or read_status
are not implemented, the phy core uses the genphy versions.
Note that none of these functions should be called from
interrupt time. The goal is for the bus read/write functions
to be able to block when the bus transaction is happening,
and be freed up by an interrupt (The MPC85xx has this ability,
though it is not currently supported in the driver).

#### <a id="c-phy_id_compare"></a>`phy_id_compare()`

```c
bool phy_id_compare(u32 id1, u32 id2, u32 mask)
```

compare **id1** with **id2** taking account of **mask**

**Parameters**

- `u32 id1`: first PHY ID
- `u32 id2`: second PHY ID
- `u32 mask`: the PHY ID mask, set bits are significant in matching

**Description**

Return true if the bits from **id1** and **id2** specified by **mask** match.
This uses an equivalent test to (**id** & **mask**) == (**phy_id** & **mask**).

#### <a id="c-phy_id_compare_vendor"></a>`phy_id_compare_vendor()`

```c
bool phy_id_compare_vendor(u32 id, u32 vendor_mask)
```

compare **id** with **vendor** mask

**Parameters**

- `u32 id`: PHY ID
- `u32 vendor_mask`: PHY Vendor mask

**Return**

true if the bits from **id** match **vendor** using the
generic PHY Vendor mask.

#### <a id="c-phy_id_compare_model"></a>`phy_id_compare_model()`

```c
bool phy_id_compare_model(u32 id, u32 model_mask)
```

compare **id** with **model** mask

**Parameters**

- `u32 id`: PHY ID
- `u32 model_mask`: PHY Model mask

**Return**

true if the bits from **id** match **model** using the
generic PHY Model mask.

#### <a id="c-phydev_id_compare"></a>`phydev_id_compare()`

```c
bool phydev_id_compare(struct phy_device *phydev, u32 id)
```

compare **id** with the PHY's Clause 22 ID

**Parameters**

- `struct phy_device *phydev`: the PHY device
- `u32 id`: the PHY ID to be matched

**Description**

Compare the **phydev** clause 22 ID with the provided **id** and return true or
false depending whether it matches, using the bound driver mask. The
**phydev** must be bound to a driver.

#### <a id="c-phy_is_started"></a>`phy_is_started()`

```c
bool phy_is_started(struct phy_device *phydev)
```

Convenience function to check whether PHY is started

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

#### <a id="c-phy_driver_is_genphy"></a>`phy_driver_is_genphy()`

```c
bool phy_driver_is_genphy(struct phy_device *phydev)
```

Convenience function to check whether PHY is driven by one of the generic PHY drivers

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

**Return**

true if PHY is driven by one of the genphy drivers

#### <a id="c-phy_disable_eee_mode"></a>`phy_disable_eee_mode()`

```c
void phy_disable_eee_mode(struct phy_device *phydev, u32 link_mode)
```

Don't advertise an EEE mode.

**Parameters**

- `struct phy_device *phydev`: The phy_device struct
- `u32 link_mode`: The EEE mode to be disabled

#### <a id="c-phy_can_wakeup"></a>`phy_can_wakeup()`

```c
bool phy_can_wakeup(struct phy_device *phydev)
```

indicate whether PHY has driver model wakeup capabilities

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

**Return**

true/false depending on the PHY driver's `device_set_wakeup_capable()`
setting.

#### <a id="c-phy_may_wakeup"></a>`phy_may_wakeup()`

```c
bool phy_may_wakeup(struct phy_device *phydev)
```

indicate whether PHY has wakeup enabled

**Parameters**

- `struct phy_device *phydev`: The phy_device struct

**Return**

true/false depending on the PHY driver's `device_set_wakeup_enabled()`
setting if using the driver model, otherwise the legacy determination.

#### <a id="c-phy_read"></a>`phy_read()`

```c
int phy_read(struct phy_device *phydev, u32 regnum)
```

Convenience function for reading a given PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to read

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-__phy_read"></a>`__phy_read()`

```c
int __phy_read(struct phy_device *phydev, u32 regnum)
```

convenience function for reading a given PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to read

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-phy_write"></a>`phy_write()`

```c
int phy_write(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for writing a given PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-__phy_write"></a>`__phy_write()`

```c
int __phy_write(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for writing a given PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-__phy_modify_changed"></a>`__phy_modify_changed()`

```c
int __phy_modify_changed(struct phy_device *phydev, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a PHY register

**Parameters**

- `struct phy_device *phydev`: a pointer to a [`struct phy_device`](#c-struct-phy_device)
- `u32 regnum`: register number
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Description**

Unlocked helper function which allows a PHY register to be modified as
new register value = (old register value & ~mask) | set

Returns negative errno, 0 if there was no change, and 1 in case of change

#### <a id="c-phy_read_mmd_poll_timeout"></a>`phy_read_mmd_poll_timeout()`

```c
phy_read_mmd_poll_timeout(phydev, devaddr, regnum, val, cond, sleep_us, timeout_us, sleep_before_read)
```

Periodically poll a PHY register until a condition is met or a timeout occurs

**Parameters**

- `phydev`: The phy_device struct
- `devaddr`: The MMD to read from
- `regnum`: The register on the MMD to read
- `val`: Variable to read the register into
- `cond`: Break condition (usually involving **val**)
- `sleep_us`: Maximum time to sleep between reads in us (0 tight-loops). Please
  read [`usleep_range()`](/kernel/internals/timers/delay-sleep-functions.md#c-usleep_range) function description for details and
  limitations.
- `timeout_us`: Timeout in us, 0 means never timeout
- `sleep_before_read`: if it is true, sleep **sleep_us** before read.

**Return**

0 on success and -ETIMEDOUT upon a timeout. In either
case, the last read value at **args** is stored in **val**. Must not
be called from atomic context if sleep_us or timeout_us are used.

#### <a id="c-__phy_set_bits"></a>`__phy_set_bits()`

```c
int __phy_set_bits(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for setting bits in a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: bits to set

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-__phy_clear_bits"></a>`__phy_clear_bits()`

```c
int __phy_clear_bits(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for clearing bits in a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: bits to clear

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-phy_set_bits"></a>`phy_set_bits()`

```c
int phy_set_bits(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for setting bits in a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: bits to set

#### <a id="c-phy_clear_bits"></a>`phy_clear_bits()`

```c
int phy_clear_bits(struct phy_device *phydev, u32 regnum, u16 val)
```

Convenience function for clearing bits in a PHY register

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `u32 regnum`: register number to write
- `u16 val`: bits to clear

#### <a id="c-__phy_set_bits_mmd"></a>`__phy_set_bits_mmd()`

```c
int __phy_set_bits_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for setting bits in a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 val`: bits to set

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-__phy_clear_bits_mmd"></a>`__phy_clear_bits_mmd()`

```c
int __phy_clear_bits_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for clearing bits in a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 val`: bits to clear

**Description**

The caller must have taken the MDIO bus lock.

#### <a id="c-phy_set_bits_mmd"></a>`phy_set_bits_mmd()`

```c
int phy_set_bits_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for setting bits in a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 val`: bits to set

#### <a id="c-phy_clear_bits_mmd"></a>`phy_clear_bits_mmd()`

```c
int phy_clear_bits_mmd(struct phy_device *phydev, int devad, u32 regnum, u16 val)
```

Convenience function for clearing bits in a register on MMD

**Parameters**

- `struct phy_device *phydev`: the phy_device struct
- `int devad`: the MMD containing register to modify
- `u32 regnum`: register number to modify
- `u16 val`: bits to clear

#### <a id="c-phy_interrupt_is_valid"></a>`phy_interrupt_is_valid()`

```c
bool phy_interrupt_is_valid(struct phy_device *phydev)
```

Convenience function for testing a given PHY irq

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

**NOTE**

must be kept in sync with addition/removal of PHY_POLL and
PHY_MAC_INTERRUPT

#### <a id="c-phy_polling_mode"></a>`phy_polling_mode()`

```c
bool phy_polling_mode(struct phy_device *phydev)
```

Convenience function for testing whether polling is used to detect PHY status changes

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_has_hwtstamp"></a>`phy_has_hwtstamp()`

```c
bool phy_has_hwtstamp(struct phy_device *phydev)
```

Tests whether a PHY time stamp configuration.

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_has_rxtstamp"></a>`phy_has_rxtstamp()`

```c
bool phy_has_rxtstamp(struct phy_device *phydev)
```

Tests whether a PHY supports receive time stamping.

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_has_tsinfo"></a>`phy_has_tsinfo()`

```c
bool phy_has_tsinfo(struct phy_device *phydev)
```

Tests whether a PHY reports time stamping and/or PTP hardware clock capabilities.

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_has_txtstamp"></a>`phy_has_txtstamp()`

```c
bool phy_has_txtstamp(struct phy_device *phydev)
```

Tests whether a PHY supports transmit time stamping.

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_is_default_hwtstamp"></a>`phy_is_default_hwtstamp()`

```c
bool phy_is_default_hwtstamp(struct phy_device *phydev)
```

Is the PHY hwtstamp the default timestamp

**Parameters**

- `struct phy_device *phydev`: Pointer to phy_device

**Description**

This is used to get default timestamping device taking into account
the new API choice, which is selecting the timestamping from MAC by
default if the phydev does not have default_timestamp flag enabled.

**Return**

True if phy is the default hw timestamp, false otherwise.

#### <a id="c-phy_on_sfp"></a>`phy_on_sfp()`

```c
bool phy_on_sfp(struct phy_device *phydev)
```

Convenience function for testing if a PHY is on an SFP module

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_interface_mode_is_rgmii"></a>`phy_interface_mode_is_rgmii()`

```c
bool phy_interface_mode_is_rgmii(phy_interface_t mode)
```

Convenience function for testing if a PHY interface mode is RGMII (all variants)

**Parameters**

- `phy_interface_t mode`: the [`phy_interface_t`](#c-enum-phy_interface_t) enum

#### <a id="c-phy_interface_mode_is_8023z"></a>`phy_interface_mode_is_8023z()`

```c
bool phy_interface_mode_is_8023z(phy_interface_t mode)
```

does the PHY interface mode use 802.3z negotiation

**Parameters**

- `phy_interface_t mode`: one of [`enum phy_interface_t`](#c-enum-phy_interface_t)

**Description**

Returns true if the PHY interface mode uses the 16-bit negotiation
word as defined in 802.3z. (See 802.3-2015 37.2.1 Config_Reg encoding)

#### <a id="c-phy_interface_is_rgmii"></a>`phy_interface_is_rgmii()`

```c
bool phy_interface_is_rgmii(struct phy_device *phydev)
```

Convenience function for testing if a PHY interface is RGMII (all variants)

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_is_pseudo_fixed_link"></a>`phy_is_pseudo_fixed_link()`

```c
bool phy_is_pseudo_fixed_link(struct phy_device *phydev)
```

Convenience function for testing if this PHY is the CPU port facing side of an Ethernet switch, or similar.

**Parameters**

- `struct phy_device *phydev`: the phy_device struct

#### <a id="c-phy_module_driver"></a>`phy_module_driver()`

```c
phy_module_driver(__phy_drivers, __count)
```

Helper macro for registering PHY drivers

**Parameters**

- `__phy_drivers`: array of PHY drivers to register
- `__count`: Numbers of members in array

**Description**

Helper macro for PHY drivers which do not do anything special in module
init/exit. 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-genphy_match_phy_device"></a>`genphy_match_phy_device()`

```c
int genphy_match_phy_device(struct phy_device *phydev, const struct phy_driver *phydrv)
```

match a PHY device with a PHY driver

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `const struct phy_driver *phydrv`: target phy_driver struct

**Description**

Checks whether the given PHY device matches the specified
PHY driver. For Clause 45 PHYs, iterates over the available device
identifiers and compares them against the driver's expected PHY ID,
applying the provided mask. For Clause 22 PHYs, a direct ID comparison
is performed.

**Return**

1 if the PHY device matches the driver, 0 otherwise.

#### <a id="c-get_phy_device"></a>`get_phy_device()`

```c
struct phy_device * get_phy_device(struct mii_bus *bus, int addr, bool is_c45)
```

reads the specified PHY device and returns its **phy_device** struct

**Parameters**

- `struct mii_bus *bus`: the target MII bus
- `int addr`: PHY address on the MII bus
- `bool is_c45`: If true the PHY uses the 802.3 clause 45 protocol

**Description**

Probe for a PHY at **addr** on **bus**.

When probing for a clause 22 PHY, then read the ID registers. If we find
a valid ID, allocate and return a [`struct phy_device`](#c-struct-phy_device).

When probing for a clause 45 PHY, read the "devices in package" registers.
If the "devices in package" appears valid, read the ID registers for each
MMD, allocate and return a [`struct phy_device`](#c-struct-phy_device).

Returns an allocated [`struct phy_device`](#c-struct-phy_device) on success, `-ENODEV` if there is
no PHY present, or `-EIO` on bus access error.

#### <a id="c-phy_device_register"></a>`phy_device_register()`

```c
int phy_device_register(struct phy_device *phydev)
```

Register the phy device on the MDIO bus

**Parameters**

- `struct phy_device *phydev`: phy_device structure to be added to the MDIO bus

#### <a id="c-phy_device_remove"></a>`phy_device_remove()`

```c
void phy_device_remove(struct phy_device *phydev)
```

Remove a previously registered phy device from the MDIO bus

**Parameters**

- `struct phy_device *phydev`: phy_device structure to remove

**Description**

This doesn't free the phy_device itself, it merely reverses the effects
of [`phy_device_register()`](#c-phy_device_register). Use `phy_device_free()` to free the device
after calling this function.

#### <a id="c-phy_get_c45_ids"></a>`phy_get_c45_ids()`

```c
int phy_get_c45_ids(struct phy_device *phydev)
```

Read 802.3-c45 IDs for phy device.

**Parameters**

- `struct phy_device *phydev`: phy_device structure to read 802.3-c45 IDs

**Description**

Returns zero on success, `-EIO` on bus access error, or `-ENODEV` if
the "devices in package" is invalid.

#### <a id="c-phy_find_next"></a>`phy_find_next()`

```c
struct phy_device * phy_find_next(struct mii_bus *bus, struct phy_device *pos)
```

finds the next PHY device on the bus

**Parameters**

- `struct mii_bus *bus`: the target MII bus
- `struct phy_device *pos`: cursor

**Return**

next phy_device on the bus, or NULL

#### <a id="c-phy_connect_direct"></a>`phy_connect_direct()`

```c
int phy_connect_direct(struct net_device *dev, struct phy_device *phydev, void (*handler)(struct net_device *), phy_interface_t interface)
```

connect an ethernet device to a specific phy_device

**Parameters**

- `struct net_device *dev`: the network device to connect
- `struct phy_device *phydev`: the pointer to the phy device
- `void (*handler)(struct net_device *)`: callback function for state change notifications
- `phy_interface_t interface`: PHY device's interface

#### <a id="c-phy_connect"></a>`phy_connect()`

```c
struct phy_device * phy_connect(struct net_device *dev, const char *bus_id, void (*handler)(struct net_device *), phy_interface_t interface)
```

connect an ethernet device to a PHY device

**Parameters**

- `struct net_device *dev`: the network device to connect
- `const char *bus_id`: the id string of the PHY device to connect
- `void (*handler)(struct net_device *)`: callback function for state change notifications
- `phy_interface_t interface`: PHY device's interface

**Description**

- Convenience function for connecting ethernet

  devices to PHY devices.  The default behavior is for
  the PHY infrastructure to handle everything, and only notify
  the connected driver when the link status changes.  If you
  don't want, or can't use the provided functionality, you may
  choose to call only the subset of functions which provide
  the desired functionality.

#### <a id="c-phy_disconnect"></a>`phy_disconnect()`

```c
void phy_disconnect(struct phy_device *phydev)
```

disable interrupts, stop state machine, and detach a PHY device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-phy_attach_direct"></a>`phy_attach_direct()`

```c
int phy_attach_direct(struct net_device *dev, struct phy_device *phydev, u32 flags, phy_interface_t interface)
```

attach a network device to a given PHY device pointer

**Parameters**

- `struct net_device *dev`: network device to attach
- `struct phy_device *phydev`: Pointer to phy_device to attach
- `u32 flags`: PHY device's dev_flags
- `phy_interface_t interface`: PHY device's interface

**Description**

- Called by drivers to attach to a particular PHY

  device. The phy_device is found, and properly hooked up
  to the phy_driver.  If no driver is attached, then a
  generic driver is used.  The phy_device is given a ptr to
  the attaching device, and given a callback for link status
  change.  The phy_device is returned to the attaching driver.
  This function takes a reference on the phy device.

#### <a id="c-phy_attach"></a>`phy_attach()`

```c
struct phy_device * phy_attach(struct net_device *dev, const char *bus_id, phy_interface_t interface)
```

attach a network device to a particular PHY device

**Parameters**

- `struct net_device *dev`: network device to attach
- `const char *bus_id`: Bus ID of PHY device to attach
- `phy_interface_t interface`: PHY device's interface

**Description**

- Same as [`phy_attach_direct()`](#c-phy_attach_direct) except that a PHY bus_id

  string is passed instead of a pointer to a struct phy_device.

#### <a id="c-phy_detach"></a>`phy_detach()`

```c
void phy_detach(struct phy_device *phydev)
```

detach a PHY device from its network device

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

This detaches the phy device from its network device and the phy
driver, and drops the reference count taken in [`phy_attach_direct()`](#c-phy_attach_direct).

#### <a id="c-phy_reset_after_clk_enable"></a>`phy_reset_after_clk_enable()`

```c
int phy_reset_after_clk_enable(struct phy_device *phydev)
```

perform a PHY reset if needed

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Some PHYs are known to need a reset after their refclk was

  enabled. This function evaluates the flags and perform the reset if it's
  needed. Returns \< 0 on error, 0 if the phy wasn't reset and 1 if the phy
  was reset.

#### <a id="c-genphy_setup_forced"></a>`genphy_setup_forced()`

```c
int genphy_setup_forced(struct phy_device *phydev)
```

configures/forces speed/duplex from **phydev**

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Configures MII_BMCR to force speed/duplex

  to the values in phydev. Assumes that the values are valid.
  Please see [`phy_sanitize_settings()`](#c-phy_sanitize_settings).

#### <a id="c-genphy_restart_aneg"></a>`genphy_restart_aneg()`

```c
int genphy_restart_aneg(struct phy_device *phydev)
```

Enable and Restart Autonegotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

#### <a id="c-genphy_check_and_restart_aneg"></a>`genphy_check_and_restart_aneg()`

```c
int genphy_check_and_restart_aneg(struct phy_device *phydev, bool restart)
```

Enable and restart auto-negotiation

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool restart`: whether aneg restart is requested

**Description**

Check, and restart auto-negotiation if needed.

#### <a id="c-__genphy_config_aneg"></a>`__genphy_config_aneg()`

```c
int __genphy_config_aneg(struct phy_device *phydev, bool changed)
```

restart auto-negotiation or write BMCR

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool changed`: whether autoneg is requested

**Description**

- If auto-negotiation is enabled, we configure the

  advertising, and then restart auto-negotiation.  If it is not
  enabled, then we write the BMCR.

#### <a id="c-genphy_c37_config_aneg"></a>`genphy_c37_config_aneg()`

```c
int genphy_c37_config_aneg(struct phy_device *phydev)
```

restart auto-negotiation or write BMCR

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- If auto-negotiation is enabled, we configure the

  advertising, and then restart auto-negotiation.  If it is not
  enabled, then we write the BMCR. This function is intended
  for use with Clause 37 1000Base-X mode.

#### <a id="c-genphy_aneg_done"></a>`genphy_aneg_done()`

```c
int genphy_aneg_done(struct phy_device *phydev)
```

return auto-negotiation status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Reads the status register and returns 0 either if

  auto-negotiation is incomplete, or if there was an error.
  Returns BMSR_ANEGCOMPLETE if auto-negotiation is done.

#### <a id="c-genphy_update_link"></a>`genphy_update_link()`

```c
int genphy_update_link(struct phy_device *phydev)
```

update link status in **phydev**

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Update the value in phydev->link to reflect the

  current link value.  In order to do this, we need to read
  the status register twice, keeping the second value.

#### <a id="c-genphy_read_status_fixed"></a>`genphy_read_status_fixed()`

```c
int genphy_read_status_fixed(struct phy_device *phydev)
```

read the link parameters for !aneg mode

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Read the current duplex and speed state for a PHY operating with
autonegotiation disabled.

#### <a id="c-genphy_read_status"></a>`genphy_read_status()`

```c
int genphy_read_status(struct phy_device *phydev)
```

check the link status and update current link state

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Check the link, then figure out the current state

  by comparing what we advertise with what the link partner
  advertises.  Start by checking the gigabit possibilities,
  then move on to 10/100.

#### <a id="c-genphy_c37_read_status"></a>`genphy_c37_read_status()`

```c
int genphy_c37_read_status(struct phy_device *phydev, bool *changed)
```

check the link status and update current link state

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool *changed`: pointer where to store if link changed

**Description**

- Check the link, then figure out the current state

  by comparing what we advertise with what the link partner
  advertises. This function is for Clause 37 1000Base-X mode.

  If link has changed, **changed** is set to true, false otherwise.

#### <a id="c-genphy_soft_reset"></a>`genphy_soft_reset()`

```c
int genphy_soft_reset(struct phy_device *phydev)
```

software reset the PHY via BMCR_RESET bit

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Perform a software PHY reset using the standard
BMCR_RESET bit and poll for the reset bit to be cleared.

**Return**

0 on success, \< 0 on failure

#### <a id="c-genphy_read_abilities"></a>`genphy_read_abilities()`

```c
int genphy_read_abilities(struct phy_device *phydev)
```

read PHY abilities from Clause 22 registers

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Reads the PHY's abilities and populates
phydev->supported accordingly.

**Return**

0 on success, \< 0 on failure

#### <a id="c-phy_remove_link_mode"></a>`phy_remove_link_mode()`

```c
void phy_remove_link_mode(struct phy_device *phydev, u32 link_mode)
```

Remove a supported link mode

**Parameters**

- `struct phy_device *phydev`: phy_device structure to remove link mode from
- `u32 link_mode`: Link mode to be removed

**Description**

Some MACs don't support all link modes which the PHY
does.  e.g. a 1G MAC often does not support 1000Half. Add a helper
to remove a link mode.

#### <a id="c-phy_advertise_supported"></a>`phy_advertise_supported()`

```c
void phy_advertise_supported(struct phy_device *phydev)
```

Advertise all supported modes

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Called to advertise all supported modes, doesn't touch
pause mode advertising.

#### <a id="c-phy_advertise_eee_all"></a>`phy_advertise_eee_all()`

```c
void phy_advertise_eee_all(struct phy_device *phydev)
```

Advertise all supported EEE modes

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Per default phylib preserves the EEE advertising at the time of
phy probing, which might be a subset of the supported EEE modes. Use this
function when all supported EEE modes should be advertised. This does not
trigger auto-negotiation, so must be called before [`phy_start()`](#c-phy_start)/
[`phylink_start()`](#c-phylink_start) which will start auto-negotiation.

#### <a id="c-phy_support_eee"></a>`phy_support_eee()`

```c
void phy_support_eee(struct phy_device *phydev)
```

Set initial EEE policy configuration

**Parameters**

- `struct phy_device *phydev`: Target phy_device struct

**Description**

This function configures the initial policy for Energy Efficient Ethernet
(EEE) on the specified PHY device, influencing that EEE capabilities are
advertised before the link is established. It should be called during PHY
registration by the MAC driver and/or the PHY driver (for SmartEEE PHYs)
if MAC supports LPI or PHY is capable to compensate missing LPI functionality
of the MAC.

The function sets default EEE policy parameters, including preparing the PHY
to advertise EEE capabilities based on hardware support.

It also sets the expected configuration for Low Power Idle (LPI) in the MAC
driver. If the PHY framework determines that both local and remote
advertisements support EEE, and the negotiated link mode is compatible with
EEE, it will set enable_tx_lpi = true. The MAC driver is expected to act on
this setting by enabling the LPI timer if enable_tx_lpi is set.

#### <a id="c-phy_disable_eee"></a>`phy_disable_eee()`

```c
void phy_disable_eee(struct phy_device *phydev)
```

Disable EEE for the PHY

**Parameters**

- `struct phy_device *phydev`: Target phy_device struct

**Description**

This function is used by MAC drivers for MAC's which don't support EEE.
It disables EEE on the PHY layer.

#### <a id="c-phy_support_sym_pause"></a>`phy_support_sym_pause()`

```c
void phy_support_sym_pause(struct phy_device *phydev)
```

Enable support of symmetrical pause

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Called by the MAC to indicate is supports symmetrical
Pause, but not asym pause.

#### <a id="c-phy_support_asym_pause"></a>`phy_support_asym_pause()`

```c
void phy_support_asym_pause(struct phy_device *phydev)
```

Enable support of asym pause

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

Called by the MAC to indicate is supports Asym Pause.

#### <a id="c-phy_set_sym_pause"></a>`phy_set_sym_pause()`

```c
void phy_set_sym_pause(struct phy_device *phydev, bool rx, bool tx, bool autoneg)
```

Configure symmetric Pause

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool rx`: Receiver Pause is supported
- `bool tx`: Transmit Pause is supported
- `bool autoneg`: Auto neg should be used

**Description**

Configure advertised Pause support depending on if
receiver pause and pause auto neg is supported. Generally called
from the set_pauseparam .ndo.

#### <a id="c-phy_set_asym_pause"></a>`phy_set_asym_pause()`

```c
void phy_set_asym_pause(struct phy_device *phydev, bool rx, bool tx)
```

Configure Pause and Asym Pause

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `bool rx`: Receiver Pause is supported
- `bool tx`: Transmit Pause is supported

**Description**

Configure advertised Pause support depending on if
transmit and receiver pause is supported. If there has been a
change in adverting, trigger a new autoneg. Generally called from
the set_pauseparam .ndo.

#### <a id="c-phy_validate_pause"></a>`phy_validate_pause()`

```c
bool phy_validate_pause(struct phy_device *phydev, struct ethtool_pauseparam *pp)
```

Test if the PHY/MAC support the pause configuration

**Parameters**

- `struct phy_device *phydev`: phy_device struct
- `struct ethtool_pauseparam *pp`: requested pause configuration

**Description**

Test if the PHY/MAC combination supports the Pause
configuration the user is requesting. Returns True if it is
supported, false otherwise.

#### <a id="c-phy_get_pause"></a>`phy_get_pause()`

```c
void phy_get_pause(struct phy_device *phydev, bool *tx_pause, bool *rx_pause)
```

resolve negotiated pause modes

**Parameters**

- `struct phy_device *phydev`: phy_device struct
- `bool *tx_pause`: pointer to bool to indicate whether transmit pause should be
  enabled.
- `bool *rx_pause`: pointer to bool to indicate whether receive pause should be
  enabled.

**Description**

Resolve and return the flow control modes according to the negotiation
result. This includes checking that we are operating in full duplex mode.
See `linkmode_resolve_pause()` for further details.

#### <a id="c-phy_get_internal_delay"></a>`phy_get_internal_delay()`

```c
s32 phy_get_internal_delay(struct phy_device *phydev, const int *delay_values, int size, bool is_rx)
```

returns the index of the internal delay

**Parameters**

- `struct phy_device *phydev`: phy_device struct
- `const int *delay_values`: array of delays the PHY supports
- `int size`: the size of the delay array
- `bool is_rx`: boolean to indicate to get the rx internal delay

**Description**

Returns the index within the array of internal delay passed in.
If the device property is not present then the interface type is checked
if the interface defines use of internal delay then a 1 is returned otherwise
a 0 is returned.
The array must be in ascending order. If PHY does not have an ascending order
array then size = 0 and the value of the delay property is returned.
Return -EINVAL if the delay is invalid or cannot be found.

#### <a id="c-phy_get_tx_amplitude_gain"></a>`phy_get_tx_amplitude_gain()`

```c
int phy_get_tx_amplitude_gain(struct phy_device *phydev, struct device *dev, enum ethtool_link_mode_bit_indices linkmode, u32 *val)
```

stores tx amplitude gain in **val**

**Parameters**

- `struct phy_device *phydev`: phy_device struct
- `struct device *dev`: pointer to the devices device struct
- `enum ethtool_link_mode_bit_indices linkmode`: linkmode for which the tx amplitude gain should be retrieved
- `u32 *val`: tx amplitude gain

**Return**

0 on success, \< 0 on failure

#### <a id="c-phy_get_mac_termination"></a>`phy_get_mac_termination()`

```c
int phy_get_mac_termination(struct phy_device *phydev, struct device *dev, u32 *val)
```

stores MAC termination in **val**

**Parameters**

- `struct phy_device *phydev`: phy_device struct
- `struct device *dev`: pointer to the devices device struct
- `u32 *val`: MAC termination

**Return**

0 on success, \< 0 on failure

#### <a id="c-phy_get_sfp_port"></a>`phy_get_sfp_port()`

```c
struct phy_port * phy_get_sfp_port(struct phy_device *phydev)
```

Returns the first valid SFP port of a PHY

**Parameters**

- `struct phy_device *phydev`: pointer to the PHY device to get the SFP port from

**Return**

The first active SFP (serdes) port of a PHY device, NULL if none
exist.

#### <a id="c-fwnode_mdio_find_device"></a>`fwnode_mdio_find_device()`

```c
struct mdio_device * fwnode_mdio_find_device(struct fwnode_handle *fwnode)
```

Given a fwnode, find the mdio_device

**Parameters**

- `struct fwnode_handle *fwnode`: pointer to the mdio_device's fwnode

**Description**

If successful, returns a pointer to the mdio_device with the embedded
struct device refcount incremented by one, or NULL on failure.
The caller should call [`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device) on the mdio_device after its use.

#### <a id="c-fwnode_phy_find_device"></a>`fwnode_phy_find_device()`

```c
struct phy_device * fwnode_phy_find_device(struct fwnode_handle *phy_fwnode)
```

For provided phy_fwnode, find phy_device.

**Parameters**

- `struct fwnode_handle *phy_fwnode`: Pointer to the phy's fwnode.

**Description**

If successful, returns a pointer to the phy_device with the embedded
struct device refcount incremented by one, or NULL on failure.

#### <a id="c-fwnode_get_phy_node"></a>`fwnode_get_phy_node()`

```c
struct fwnode_handle * fwnode_get_phy_node(const struct fwnode_handle *fwnode)
```

Get the phy_node using the named reference.

**Parameters**

- `const struct fwnode_handle *fwnode`: Pointer to fwnode from which phy_node has to be obtained.

**Description**

Refer return conditions of `fwnode_find_reference()`.
For ACPI, only "phy-handle" is supported. Legacy DT properties "phy"
and "phy-device" are not supported in ACPI. DT supports all the three
named references to the phy node.



#### <a id="c-phy_uses_state_machine"></a>`phy_uses_state_machine()`

```c
bool phy_uses_state_machine(struct phy_device *phydev)
```

test whether consumer driver uses PAL state machine

**Parameters**

- `struct phy_device *phydev`: the target PHY device structure

**Description**

Ultimately, this aims to indirectly determine whether the PHY is attached
to a consumer which uses the state machine by calling [`phy_start()`](#c-phy_start) and
[`phy_stop()`](#c-phy_stop).

When the PHY driver consumer uses phylib, it must have previously called
[`phy_connect_direct()`](#c-phy_connect_direct) or one of its derivatives, so that [`phy_prepare_link()`](#c-phy_prepare_link)
has set up a hook for monitoring state changes.

When the PHY driver is used by the MAC driver consumer through phylink (the
only other provider of a `phy_link_change()` method), using the PHY state
machine is not optional.

**Return**

true if consumer calls [`phy_start()`](#c-phy_start) and [`phy_stop()`](#c-phy_stop), false otherwise.

#### <a id="c-phy_register_fixup"></a>`phy_register_fixup()`

```c
int phy_register_fixup(const char *bus_id, u32 phy_uid, u32 phy_uid_mask, int (*run)(struct phy_device *))
```

creates a new phy_fixup and adds it to the list

**Parameters**

- `const char *bus_id`: A string which matches phydev->mdio.dev.bus_id (or NULL)
- `u32 phy_uid`: Used to match against phydev->phy_id (the UID of the PHY)
- `u32 phy_uid_mask`: Applied to phydev->phy_id and fixup->phy_uid before
  comparison (or 0 to disable id-based matching)
- `int (*run)(struct phy_device *)`: The actual code to be run when a matching PHY is found

#### <a id="c-get_phy_c45_ids"></a>`get_phy_c45_ids()`

```c
int get_phy_c45_ids(struct mii_bus *bus, int addr, struct phy_c45_device_ids *c45_ids)
```

reads the specified addr for its 802.3-c45 IDs.

**Parameters**

- `struct mii_bus *bus`: the target MII bus
- `int addr`: PHY address on the MII bus
- `struct phy_c45_device_ids *c45_ids`: where to store the c45 ID information.

**Description**

Read the PHY "devices in package". If this appears to be valid, read
the PHY identifiers for each device. Return the "devices in package"
and identifiers in **c45_ids**.

Returns zero on success, `-EIO` on bus access error, or `-ENODEV` if
the "devices in package" is invalid or no device responds.

#### <a id="c-get_phy_c22_id"></a>`get_phy_c22_id()`

```c
int get_phy_c22_id(struct mii_bus *bus, int addr, u32 *phy_id)
```

reads the specified addr for its clause 22 ID.

**Parameters**

- `struct mii_bus *bus`: the target MII bus
- `int addr`: PHY address on the MII bus
- `u32 *phy_id`: where to store the ID retrieved.

**Description**

Read the 802.3 clause 22 PHY ID from the PHY at **addr** on the **bus**,
placing it in **phy_id**. Return zero on successful read and the ID is
valid, `-EIO` on bus access error, or `-ENODEV` if no device responds
or invalid ID.

#### <a id="c-phy_prepare_link"></a>`phy_prepare_link()`

```c
void phy_prepare_link(struct phy_device *phydev, void (*handler)(struct net_device *))
```

prepares the PHY layer to monitor link status

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `void (*handler)(struct net_device *)`: callback function for link status change notifications

**Description**

- Tells the PHY infrastructure to handle the

  gory details on monitoring link status (whether through
  polling or an interrupt), and to call back to the
  connected device driver when the link status changes.
  If you want to monitor your own link state, don't call
  this function.

#### <a id="c-phy_poll_reset"></a>`phy_poll_reset()`

```c
int phy_poll_reset(struct phy_device *phydev)
```

Safely wait until a PHY reset has properly completed

**Parameters**

- `struct phy_device *phydev`: The PHY device to poll

**Description**

- According to IEEE 802.3, Section 2, Subsection 22.2.4.1.1, as

  published in 2008, a PHY reset may take up to 0.5 seconds.  The MII BMCR
  register must be polled until the BMCR_RESET bit clears.

  Furthermore, any attempts to write to PHY registers may have no effect
  or even generate MDIO bus errors until this is complete.

  Some PHYs (such as the Marvell 88E1111) don't entirely conform to the
  standard and do not fully reset after the BMCR_RESET bit is set, and may
  even *REQUIRE* a soft-reset to properly restart autonegotiation.  In an
  effort to support such broken PHYs, this function is separate from the
  standard `phy_init_hw()` which will zero all the other bits in the BMCR
  and reapply all driver-specific and board-specific fixups.

#### <a id="c-phy_sfp_connect_phy"></a>`phy_sfp_connect_phy()`

```c
int phy_sfp_connect_phy(void *upstream, struct phy_device *phy)
```

Connect the SFP module's PHY to the upstream PHY

**Parameters**

- `void *upstream`: pointer to the upstream phy device
- `struct phy_device *phy`: pointer to the SFP module's phy device

**Description**

This helper allows keeping track of PHY devices on the link. It adds the
SFP module's phy to the phy namespace of the upstream phy

**Return**

0 on success, otherwise a negative error code.

#### <a id="c-phy_sfp_disconnect_phy"></a>`phy_sfp_disconnect_phy()`

```c
void phy_sfp_disconnect_phy(void *upstream, struct phy_device *phy)
```

Disconnect the SFP module's PHY from the upstream PHY

**Parameters**

- `void *upstream`: pointer to the upstream phy device
- `struct phy_device *phy`: pointer to the SFP module's phy device

**Description**

This helper allows keeping track of PHY devices on the link. It removes the
SFP module's phy to the phy namespace of the upstream phy. As the module phy
will be destroyed, re-inserting the same module will add a new phy with a
new index.

#### <a id="c-phy_sfp_attach"></a>`phy_sfp_attach()`

```c
void phy_sfp_attach(void *upstream, struct sfp_bus *bus)
```

attach the SFP bus to the PHY upstream network device

**Parameters**

- `void *upstream`: pointer to the phy device
- `struct sfp_bus *bus`: sfp bus representing cage being attached

**Description**

This is used to fill in the sfp_upstream_ops .attach member.

#### <a id="c-phy_sfp_detach"></a>`phy_sfp_detach()`

```c
void phy_sfp_detach(void *upstream, struct sfp_bus *bus)
```

detach the SFP bus from the PHY upstream network device

**Parameters**

- `void *upstream`: pointer to the phy device
- `struct sfp_bus *bus`: sfp bus representing cage being attached

**Description**

This is used to fill in the sfp_upstream_ops .detach member.

#### <a id="c-phy_sfp_probe"></a>`phy_sfp_probe()`

```c
int phy_sfp_probe(struct phy_device *phydev)
```

probe for a SFP cage attached to this PHY device

**Parameters**

- `struct phy_device *phydev`: Pointer to phy_device

#### <a id="c-genphy_config_advert"></a>`genphy_config_advert()`

```c
int genphy_config_advert(struct phy_device *phydev, const unsigned long *advert)
```

sanitize and advertise auto-negotiation parameters

**Parameters**

- `struct phy_device *phydev`: target phy_device struct
- `const unsigned long *advert`: auto-negotiation parameters to advertise

**Description**

- Writes MII_ADVERTISE with the appropriate values,

  after sanitizing the values to make sure we only advertise
  what is supported.  Returns \< 0 on error, 0 if the PHY's advertisement
  hasn't changed, and > 0 if it has changed.

#### <a id="c-genphy_c37_config_advert"></a>`genphy_c37_config_advert()`

```c
int genphy_c37_config_advert(struct phy_device *phydev)
```

sanitize and advertise auto-negotiation parameters

**Parameters**

- `struct phy_device *phydev`: target phy_device struct

**Description**

- Writes MII_ADVERTISE with the appropriate values,

  after sanitizing the values to make sure we only advertise
  what is supported.  Returns \< 0 on error, 0 if the PHY's advertisement
  hasn't changed, and > 0 if it has changed. This function is intended
  for Clause 37 1000Base-X mode.

#### <a id="c-phy_probe"></a>`phy_probe()`

```c
int phy_probe(struct device *dev)
```

probe and init a PHY device

**Parameters**

- `struct device *dev`: device to probe and init

**Description**

Take care of setting up the phy_device structure, set the state to READY.

#### <a id="c-phy_driver_register"></a>`phy_driver_register()`

```c
int phy_driver_register(struct phy_driver *new_driver, struct module *owner)
```

register a phy_driver with the PHY layer

**Parameters**

- `struct phy_driver *new_driver`: new phy_driver to register
- `struct module *owner`: module owning this PHY



#### <a id="c-mdio_find_bus"></a>`mdio_find_bus()`

```c
struct mii_bus * mdio_find_bus(const char *mdio_name)
```

Given the name of a mdiobus, find the mii_bus.

**Parameters**

- `const char *mdio_name`: The name of a mdiobus.

**Return**

a reference to the mii_bus, or NULL if none found. The
embedded struct device will have its reference count incremented,
and this must be put_deviced'ed once the bus is finished with.

#### <a id="c-of_mdio_find_bus"></a>`of_mdio_find_bus()`

```c
struct mii_bus * of_mdio_find_bus(struct device_node *mdio_bus_np)
```

Given an mii_bus node, find the mii_bus.

**Parameters**

- `struct device_node *mdio_bus_np`: Pointer to the mii_bus.

**Return**

a reference to the mii_bus, or NULL if none found. The
embedded struct device will have its reference count incremented,
and this must be put once the bus is finished with.

**Description**

Because the association of a device_node and mii_bus is made via
`of_mdiobus_register()`, the mii_bus cannot be found before it is
registered with `of_mdiobus_register()`.

#### <a id="c-__mdiobus_read"></a>`__mdiobus_read()`

```c
int __mdiobus_read(struct mii_bus *bus, int addr, u32 regnum)
```

Unlocked version of the mdiobus_read function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**Description**

Read a MDIO bus register. Caller must hold the mdio bus lock.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-__mdiobus_write"></a>`__mdiobus_write()`

```c
int __mdiobus_write(struct mii_bus *bus, int addr, u32 regnum, u16 val)
```

Unlocked version of the mdiobus_write function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**Description**

Write a MDIO bus register. Caller must hold the mdio bus lock.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-__mdiobus_modify_changed"></a>`__mdiobus_modify_changed()`

```c
int __mdiobus_modify_changed(struct mii_bus *bus, int addr, u32 regnum, u16 mask, u16 set)
```

Unlocked version of the mdiobus_modify function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

1 if the register was modified, 0 if no change was needed,
negative on any error condition

**Description**

Read, modify, and if any change, write the register value back to the
device.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-__mdiobus_c45_read"></a>`__mdiobus_c45_read()`

```c
int __mdiobus_c45_read(struct mii_bus *bus, int addr, int devad, u32 regnum)
```

Unlocked version of the mdiobus_c45_read function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**Description**

Read a MDIO bus register. Caller must hold the mdio bus lock.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-__mdiobus_c45_write"></a>`__mdiobus_c45_write()`

```c
int __mdiobus_c45_write(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 val)
```

Unlocked version of the mdiobus_write function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**Description**

Write a MDIO bus register. Caller must hold the mdio bus lock.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-mdiobus_read_nested"></a>`mdiobus_read_nested()`

```c
int mdiobus_read_nested(struct mii_bus *bus, int addr, u32 regnum)
```

Nested version of the mdiobus_read function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**Description**

In case of nested MDIO bus access avoid lockdep false positives by
using `mutex_lock_nested()`.

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_read"></a>`mdiobus_read()`

```c
int mdiobus_read(struct mii_bus *bus, int addr, u32 regnum)
```

Convenience function for reading a given MII mgmt register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_c45_read"></a>`mdiobus_c45_read()`

```c
int mdiobus_c45_read(struct mii_bus *bus, int addr, int devad, u32 regnum)
```

Convenience function for reading a given MII mgmt register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_c45_read_nested"></a>`mdiobus_c45_read_nested()`

```c
int mdiobus_c45_read_nested(struct mii_bus *bus, int addr, int devad, u32 regnum)
```

Nested version of the mdiobus_c45_read function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to read

**Return**

The register value if successful, negative error code on failure

**Description**

In case of nested MDIO bus access avoid lockdep false positives by
using `mutex_lock_nested()`.

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_write_nested"></a>`mdiobus_write_nested()`

```c
int mdiobus_write_nested(struct mii_bus *bus, int addr, u32 regnum, u16 val)
```

Nested version of the mdiobus_write function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**Description**

In case of nested MDIO bus access avoid lockdep false positives by
using `mutex_lock_nested()`.

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_write"></a>`mdiobus_write()`

```c
int mdiobus_write(struct mii_bus *bus, int addr, u32 regnum, u16 val)
```

Convenience function for writing a given MII mgmt register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_c45_write"></a>`mdiobus_c45_write()`

```c
int mdiobus_c45_write(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 val)
```

Convenience function for writing a given MII mgmt register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_c45_write_nested"></a>`mdiobus_c45_write_nested()`

```c
int mdiobus_c45_write_nested(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 val)
```

Nested version of the mdiobus_c45_write function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to write
- `u16 val`: value to write to **regnum**

**Return**

Zero if successful, negative error code on failure

**Description**

In case of nested MDIO bus access avoid lockdep false positives by
using `mutex_lock_nested()`.

**NOTE**

MUST NOT be called from interrupt context,
because the bus read/write functions may wait for an interrupt
to conclude the operation.

#### <a id="c-mdiobus_modify"></a>`mdiobus_modify()`

```c
int mdiobus_modify(struct mii_bus *bus, int addr, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a given mdio device register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to write
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

0 on success, negative on any error condition

#### <a id="c-mdiobus_c45_modify"></a>`mdiobus_c45_modify()`

```c
int mdiobus_c45_modify(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a given mdio device register

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to write
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

0 on success, negative on any error condition

#### <a id="c-mdiobus_modify_changed"></a>`mdiobus_modify_changed()`

```c
int mdiobus_modify_changed(struct mii_bus *bus, int addr, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a given mdio device register and returning if it changed

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `u32 regnum`: register number to write
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

1 if the register was modified, 0 if no change was needed,
negative on any error condition

#### <a id="c-mdiobus_c45_modify_changed"></a>`mdiobus_c45_modify_changed()`

```c
int mdiobus_c45_modify_changed(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 mask, u16 set)
```

Convenience function for modifying a given mdio device register and returning if it changed

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to write
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

1 if the register was modified, 0 if no change was needed,
negative on any error condition



#### <a id="c-mdiobus_release"></a>`mdiobus_release()`

```c
void mdiobus_release(struct device *d)
```

mii_bus device release callback

**Parameters**

- `struct device *d`: the target struct device that contains the mii_bus

**Description**

called when the last reference to an mii_bus is
dropped, to free the underlying memory.

#### <a id="c-__mdiobus_c45_modify_changed"></a>`__mdiobus_c45_modify_changed()`

```c
int __mdiobus_c45_modify_changed(struct mii_bus *bus, int addr, int devad, u32 regnum, u16 mask, u16 set)
```

Unlocked version of the mdiobus_modify function

**Parameters**

- `struct mii_bus *bus`: the mii_bus struct
- `int addr`: the phy address
- `int devad`: device address to read
- `u32 regnum`: register number to modify
- `u16 mask`: bit mask of bits to clear
- `u16 set`: bit mask of bits to set

**Return**

1 if the register was modified, 0 if no change was needed,
negative on any error condition

**Description**

Read, modify, and if any change, write the register value back to the
device. Any error returns a negative number.

**NOTE**

MUST NOT be called from interrupt context.

#### <a id="c-mdio_bus_match"></a>`mdio_bus_match()`

```c
int mdio_bus_match(struct device *dev, const struct device_driver *drv)
```

determine if given MDIO driver supports the given MDIO device

**Parameters**

- `struct device *dev`: target MDIO device
- `const struct device_driver *drv`: given MDIO driver

**Return**

1 if the driver supports the device, 0 otherwise

**Description**

- This may require calling the devices own match function,

  since different classes of MDIO devices have different match criteria.


<a id="rst-phylink"></a>

### PHYLINK

> PHYLINK interfaces traditional network drivers with PHYLIB, fixed-links, and SFF modules (eg, hot-pluggable SFP) that may contain PHYs.  PHYLINK provides management of the link state and link modes.


#### <a id="c-struct-phylink_link_state"></a>`struct phylink_link_state`

link state structure

**Definition**

```c
struct phylink_link_state {
    unsigned long advertising[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
    unsigned long lp_advertising[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
    phy_interface_t interface;
    int speed;
    int duplex;
    int pause;
    int rate_matching;
    unsigned int link:1;
    unsigned int an_complete:1;
};
```

**Members**

- `advertising`: ethtool bitmask containing advertised link modes
- `lp_advertising`: ethtool bitmask containing link partner advertised link
  modes
- `interface`: link `typedef phy_interface_t` mode
- `speed`: link speed, one of the SPEED_* constants.
- `duplex`: link duplex mode, one of DUPLEX_* constants.
- `pause`: link pause state, described by MLO_PAUSE_* constants.
- `rate_matching`: rate matching being performed, one of the RATE_MATCH_*
  constants. If rate matching is taking place, then the speed/duplex of
  the medium link mode (**speed** and **duplex**) and the speed/duplex of the phy
  interface mode (**interface**) are different.
- `link`: true if the link is up.
- `an_complete`: true if autonegotiation has completed.

#### <a id="c-struct-phylink_config"></a>`struct phylink_config`

PHYLINK configuration structure

**Definition**

```c
struct phylink_config {
    struct device *dev;
    enum phylink_op_type type;
    bool poll_fixed_state;
    bool mac_managed_pm;
    bool mac_requires_rxc;
    bool default_an_inband;
    bool eee_rx_clk_stop_enable;
    void (*get_fixed_state)(struct phylink_config *config, struct phylink_link_state *state);
    unsigned long supported_interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
    unsigned long lpi_interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
    unsigned long mac_capabilities;
    unsigned long lpi_capabilities;
    u32 lpi_timer_default;
    bool eee_enabled_default;
    bool wol_phy_legacy;
    bool wol_phy_speed_ctrl;
    u32 wol_mac_support;
};
```

**Members**

- `dev`: a pointer to a struct device associated with the MAC
- `type`: operation type of PHYLINK instance
- `poll_fixed_state`: if true, starts link_poll,
  if MAC link is at `MLO_AN_FIXED` mode.
- `mac_managed_pm`: if true, indicate the MAC driver is responsible for PHY PM.
- `mac_requires_rxc`: if true, the MAC always requires a receive clock from PHY.
  The PHY driver should start the clock signal as soon as
  possible and avoid stopping it during suspend events.
- `default_an_inband`: if true, defaults to MLO_AN_INBAND rather than
  MLO_AN_PHY. A fixed-link specification will override.
- `eee_rx_clk_stop_enable`: if true, PHY can stop the receive clock during LPI
- `get_fixed_state`: callback to execute to determine the fixed link state,
  if MAC link is at `MLO_AN_FIXED` mode.
- `supported_interfaces`: bitmap describing which PHY_INTERFACE_MODE_xxx
  are supported by the MAC/PCS.
- `lpi_interfaces`: bitmap describing which PHY interface modes can support
  LPI signalling.
- `mac_capabilities`: MAC pause/speed/duplex capabilities.
- `lpi_capabilities`: MAC speeds which can support LPI signalling
- `lpi_timer_default`: Default EEE LPI timer setting.
- `eee_enabled_default`: If set, EEE will be enabled by phylink at creation time
- `wol_phy_legacy`: Use Wake-on-Lan with PHY even if [`phy_can_wakeup()`](#c-phy_can_wakeup) is false
- `wol_phy_speed_ctrl`: Use phy speed control on suspend/resume
- `wol_mac_support`: Bitmask of MAC supported `WAKE_*` options

#### <a id="c-struct-phylink_mac_ops"></a>`struct phylink_mac_ops`

MAC operations structure.

**Definition**

```c
struct phylink_mac_ops {
    unsigned long (*mac_get_caps)(struct phylink_config *config, phy_interface_t interface);
    struct phylink_pcs *(*mac_select_pcs)(struct phylink_config *config, phy_interface_t interface);
    int (*mac_prepare)(struct phylink_config *config, unsigned int mode, phy_interface_t iface);
    void (*mac_config)(struct phylink_config *config, unsigned int mode, const struct phylink_link_state *state);
    int (*mac_finish)(struct phylink_config *config, unsigned int mode, phy_interface_t iface);
    void (*mac_link_down)(struct phylink_config *config, unsigned int mode, phy_interface_t interface);
    void (*mac_link_up)(struct phylink_config *config, struct phy_device *phy, unsigned int mode, phy_interface_t interface, int speed, int duplex, bool tx_pause, bool rx_pause);
    void (*mac_disable_tx_lpi)(struct phylink_config *config);
    int (*mac_enable_tx_lpi)(struct phylink_config *config, u32 timer, bool tx_clk_stop);
    int (*mac_wol_set)(struct phylink_config *config, u32 wolopts, const u8 *sopass);
};
```

**Members**

- `mac_get_caps`: Get MAC capabilities for interface mode.
- `mac_select_pcs`: Select a PCS for the interface mode.
- `mac_prepare`: prepare for a major reconfiguration of the interface.
- `mac_config`: configure the MAC for the selected mode and state.
- `mac_finish`: finish a major reconfiguration of the interface.
- `mac_link_down`: take the link down.
- `mac_link_up`: allow the link to come up.
- `mac_disable_tx_lpi`: disable LPI.
- `mac_enable_tx_lpi`: enable and configure LPI.
- `mac_wol_set`: configure Wake-on-Lan settings at the MAC.

**Description**

The individual methods are described more fully below.

#### <a id="c-mac_get_caps"></a>`mac_get_caps()`

```c
unsigned long mac_get_caps(struct phylink_config *config, phy_interface_t interface)
```

Get MAC capabilities for interface mode.

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `phy_interface_t interface`: PHY interface mode.

**Description**

Optional method. When not provided, config->mac_capabilities will be used.
When implemented, this returns the MAC capabilities for the specified
interface mode where there is some special handling required by the MAC
driver (e.g. not supporting half-duplex in certain interface modes.)

#### <a id="c-mac_select_pcs"></a>`mac_select_pcs()`

```c
struct phylink_pcs * mac_select_pcs(struct phylink_config *config, phy_interface_t interface)
```

Select a PCS for the interface mode.

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `phy_interface_t interface`: PHY interface mode for PCS

**Description**

Return the [`struct phylink_pcs`](#c-struct-phylink_pcs) for the specified interface mode, or
NULL if none is required, or an error pointer on error.

This must not modify any state. It is used to query which PCS should
be used. Phylink will use this during validation to ensure that the
configuration is valid, and when setting a configuration to internally
set the PCS that will be used.

#### <a id="c-mac_prepare"></a>`mac_prepare()`

```c
int mac_prepare(struct phylink_config *config, unsigned int mode, phy_interface_t iface)
```

prepare to change the PHY interface mode

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `unsigned int mode`: one of `MLO_AN_FIXED`, `MLO_AN_PHY`, `MLO_AN_INBAND`.
- `phy_interface_t iface`: interface mode to switch to

**Description**

phylink will call this method at the beginning of a full initialisation
of the link, which includes changing the interface mode or at initial
startup time. It may be called for the current mode. The MAC driver
should perform whatever actions are required, e.g. disabling the
Serdes PHY.

This will be the first call in the sequence:
- [`mac_prepare()`](#c-mac_prepare)
- [`mac_config()`](#c-mac_config)
- [`pcs_config()`](#c-pcs_config)
- possible [`pcs_an_restart()`](#c-pcs_an_restart)
- [`mac_finish()`](#c-mac_finish)

Returns zero on success, or negative errno on failure which will be
reported to the kernel log.

#### <a id="c-mac_config"></a>`mac_config()`

```c
void mac_config(struct phylink_config *config, unsigned int mode, const struct phylink_link_state *state)
```

configure the MAC for the selected mode and state

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `unsigned int mode`: one of `MLO_AN_FIXED`, `MLO_AN_PHY`, `MLO_AN_INBAND`.
- `const struct phylink_link_state *state`: a pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).

**Description**

Note - not all members of **state** are valid.  In particular,
**state->lp_advertising**, **state->link**, **state->an_complete** are never
guaranteed to be correct, and so any [`mac_config()`](#c-mac_config) implementation must
never reference these fields.

This will only be called to reconfigure the MAC for a "major" change in
e.g. interface mode. It will not be called for changes in speed, duplex
or pause modes or to change the in-band advertisement.

In all negotiation modes, as defined by **mode**, **state->pause** indicates the
pause settings which should be applied as follows. If `MLO_PAUSE_AN` is not
set, `MLO_PAUSE_TX` and `MLO_PAUSE_RX` indicate whether the MAC should send
pause frames and/or act on received pause frames respectively. Otherwise,
the results of in-band negotiation/status from the MAC PCS should be used
to control the MAC pause mode settings.

The action performed depends on the currently selected mode:

- `MLO_AN_FIXED`, `MLO_AN_PHY`:
  Configure for non-inband negotiation mode, where the link settings
  are completely communicated via [`mac_link_up()`](#c-mac_link_up).  The physical link
  protocol from the MAC is specified by **state->interface**.

  **state->advertising** may be used, but is not required.

  Older drivers (prior to the [`mac_link_up()`](#c-mac_link_up) change) may use **state->speed**,
  **state->duplex** and **state->pause** to configure the MAC, but this is
  deprecated; such drivers should be converted to use [`mac_link_up()`](#c-mac_link_up).

  Other members of **state** must be ignored.

  Valid state members: interface, advertising.
  Deprecated state members: speed, duplex, pause.

- `MLO_AN_INBAND`:
  place the link in an inband negotiation mode (such as 802.3z
  1000base-X or Cisco SGMII mode depending on the **state->interface**
  mode). In both cases, link state management (whether the link
  is up or not) is performed by the MAC, and reported via the
  [`pcs_get_state()`](#c-pcs_get_state) callback. Changes in link state must be made
  by calling [`phylink_mac_change()`](#c-phylink_mac_change).

  Interface mode specific details are mentioned below.

  If in 802.3z mode, the link speed is fixed, dependent on the
  **state->interface**. Duplex and pause modes are negotiated via
  the in-band configuration word. Advertised pause modes are set
  according to **state->advertising**. Beware of MACs which only
  support full duplex at gigabit and higher speeds.

  If in Cisco SGMII mode, the link speed and duplex mode are passed
  in the serial bitstream 16-bit configuration word, and the MAC
  should be configured to read these bits and acknowledge the
  configuration word. Nothing is advertised by the MAC. The MAC is
  responsible for reading the configuration word and configuring
  itself accordingly.

  Valid state members: interface, pause, advertising.

Implementations are expected to update the MAC to reflect the
requested settings - i.o.w., if nothing has changed between two
calls, no action is expected.  If only flow control settings have
changed, flow control should be updated *without* taking the link
down.  This "update" behaviour is critical to avoid bouncing the
link up status.

#### <a id="c-mac_finish"></a>`mac_finish()`

```c
int mac_finish(struct phylink_config *config, unsigned int mode, phy_interface_t iface)
```

finish a to change the PHY interface mode

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `unsigned int mode`: one of `MLO_AN_FIXED`, `MLO_AN_PHY`, `MLO_AN_INBAND`.
- `phy_interface_t iface`: interface mode to switch to

**Description**

phylink will call this if it called [`mac_prepare()`](#c-mac_prepare) to allow the MAC to
complete any necessary steps after the MAC and PCS have been configured
for the **mode** and **iface**. E.g. a MAC driver may wish to re-enable the
Serdes PHY here if it was previously disabled by [`mac_prepare()`](#c-mac_prepare).

Returns zero on success, or negative errno on failure which will be
reported to the kernel log.

#### <a id="c-mac_link_down"></a>`mac_link_down()`

```c
void mac_link_down(struct phylink_config *config, unsigned int mode, phy_interface_t interface)
```

notification that the link has gone down

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `unsigned int mode`: link autonegotiation mode
- `phy_interface_t interface`: link `typedef phy_interface_t` mode

**Description**

Notifies the MAC that the link has gone down. This will not be called
unless [`mac_link_up()`](#c-mac_link_up) has been previously called.

The MAC should stop processing packets for transmission and reception.
phylink will have called [`netif_carrier_off()`](#c-netif_carrier_off) to notify the networking
stack that the link has gone down, so MAC drivers should not make this
call.

If **mode** is `MLO_AN_INBAND`, then this function must not prevent the
link coming up.

#### <a id="c-mac_link_up"></a>`mac_link_up()`

```c
void mac_link_up(struct phylink_config *config, struct phy_device *phy, unsigned int mode, phy_interface_t interface, int speed, int duplex, bool tx_pause, bool rx_pause)
```

notification that the link has come up

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `struct phy_device *phy`: any attached phy (deprecated - please use LPI interfaces)
- `unsigned int mode`: link autonegotiation mode
- `phy_interface_t interface`: link `typedef phy_interface_t` mode
- `int speed`: link speed
- `int duplex`: link duplex
- `bool tx_pause`: link transmit pause enablement status
- `bool rx_pause`: link receive pause enablement status

**Description**

Notifies the MAC that the link has come up, and the parameters of the
link as seen from the MACs point of view. If [`mac_link_up()`](#c-mac_link_up) has been
called previously, there will be an intervening call to [`mac_link_down()`](#c-mac_link_down)
before this method will be subsequently called.

**speed**, **duplex**, **tx_pause** and **rx_pause** indicate the finalised link
settings, and should be used to configure the MAC block appropriately
where these settings are not automatically conveyed from the PCS block,
or if in-band negotiation (as defined by phylink_autoneg_inband(**mode**))
is disabled.

Note that when 802.3z in-band negotiation is in use, it is possible
that the user wishes to override the pause settings, and this should
be allowed when considering the implementation of this method.

Once configured, the MAC may begin to process packets for transmission
and reception.

Interface type selection must be done in [`mac_config()`](#c-mac_config).

#### <a id="c-mac_disable_tx_lpi"></a>`mac_disable_tx_lpi()`

```c
void mac_disable_tx_lpi(struct phylink_config *config)
```

disable LPI generation at the MAC

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).

**Description**

Disable generation of LPI at the MAC, effectively preventing the MAC
from indicating that it is idle.

#### <a id="c-mac_enable_tx_lpi"></a>`mac_enable_tx_lpi()`

```c
int mac_enable_tx_lpi(struct phylink_config *config, u32 timer, bool tx_clk_stop)
```

configure and enable LPI generation at the MAC

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `u32 timer`: LPI timeout in microseconds.
- `bool tx_clk_stop`: allow xMII transmit clock to be stopped during LPI

**Description**

Configure the LPI timeout accordingly. This will only be called when
the link is already up, to cater for situations where the hardware
needs to be programmed according to the link speed.

Enable LPI generation at the MAC, and configure whether the xMII transmit
clock may be stopped.

**Return**

0 on success. Please consult with rmk before returning an error.

#### <a id="c-mac_wol_set"></a>`mac_wol_set()`

```c
int mac_wol_set(struct phylink_config *config, u32 wolopts, const u8 *sopass)
```

configure the Wake-on-Lan parameters

**Parameters**

- `struct phylink_config *config`: a pointer to a [`struct phylink_config`](#c-struct-phylink_config).
- `u32 wolopts`: Bitmask of `WAKE_*` flags for enabled Wake-On-Lan modes.
- `const u8 *sopass`: SecureOn(tm) password; meaningful only for `WAKE_MAGICSECURE`

**Description**

Enable the specified Wake-on-Lan options at the MAC. Options that the
PHY can handle will have been removed from **wolopts**.

The presence of this method enables phylink-managed WoL support.

**Return**

0 on success.

#### <a id="c-struct-phylink_pcs"></a>`struct phylink_pcs`

PHYLINK PCS instance

**Definition**

```c
struct phylink_pcs {
    unsigned long supported_interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
    const struct phylink_pcs_ops *ops;
    struct phylink *phylink;
    bool poll;
    bool rxc_always_on;
};
```

**Members**

- `supported_interfaces`: describing which PHY_INTERFACE_MODE_xxx
  are supported by this PCS.
- `ops`: a pointer to the [`struct phylink_pcs_ops`](#c-struct-phylink_pcs_ops) structure
- `phylink`: pointer to [`struct phylink_config`](#c-struct-phylink_config)
- `poll`: poll the PCS for link changes
- `rxc_always_on`: The MAC driver requires the reference clock
  to always be on. Standalone PCS drivers which
  do not have access to a PHY device can check
  this instead of PHY_F_RXC_ALWAYS_ON.

**Description**

This structure is designed to be embedded within the PCS private data,
and will be passed between phylink and the PCS.

The **phylink** member is private to phylink and must not be touched by
the PCS driver.

#### <a id="c-struct-phylink_pcs_ops"></a>`struct phylink_pcs_ops`

MAC PCS operations structure.

**Definition**

```c
struct phylink_pcs_ops {
    int (*pcs_validate)(struct phylink_pcs *pcs, unsigned long *supported, const struct phylink_link_state *state);
    unsigned int (*pcs_inband_caps)(struct phylink_pcs *pcs, phy_interface_t interface);
    int (*pcs_enable)(struct phylink_pcs *pcs);
    void (*pcs_disable)(struct phylink_pcs *pcs);
    void (*pcs_pre_config)(struct phylink_pcs *pcs, phy_interface_t interface);
    int (*pcs_post_config)(struct phylink_pcs *pcs, phy_interface_t interface);
    void (*pcs_get_state)(struct phylink_pcs *pcs, unsigned int neg_mode, struct phylink_link_state *state);
    int (*pcs_config)(struct phylink_pcs *pcs, unsigned int neg_mode, phy_interface_t interface, const unsigned long *advertising, bool permit_pause_to_mac);
    void (*pcs_an_restart)(struct phylink_pcs *pcs);
    void (*pcs_link_up)(struct phylink_pcs *pcs, unsigned int neg_mode, phy_interface_t interface, int speed, int duplex);
    void (*pcs_disable_eee)(struct phylink_pcs *pcs);
    void (*pcs_enable_eee)(struct phylink_pcs *pcs);
    int (*pcs_pre_init)(struct phylink_pcs *pcs);
};
```

**Members**

- `pcs_validate`: validate the link configuration.
- `pcs_inband_caps`: query inband support for interface mode.
- `pcs_enable`: enable the PCS.
- `pcs_disable`: disable the PCS.
- `pcs_pre_config`: pre-mac_config method (for errata)
- `pcs_post_config`: post-mac_config method (for arrata)
- `pcs_get_state`: read the current MAC PCS link state from the hardware.
- `pcs_config`: configure the MAC PCS for the selected mode and state.
- `pcs_an_restart`: restart 802.3z BaseX autonegotiation.
- `pcs_link_up`: program the PCS for the resolved link configuration
  (where necessary).
- `pcs_disable_eee`: optional notification to PCS that EEE has been disabled
  at the MAC.
- `pcs_enable_eee`: optional notification to PCS that EEE will be enabled at
  the MAC.
- `pcs_pre_init`: configure PCS components necessary for MAC hardware
  initialization e.g. RX clock for stmmac.

#### <a id="c-pcs_validate"></a>`pcs_validate()`

```c
int pcs_validate(struct phylink_pcs *pcs, unsigned long *supported, const struct phylink_link_state *state)
```

validate the link configuration.

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).
- `unsigned long *supported`: ethtool bitmask for supported link modes.
- `const struct phylink_link_state *state`: a const pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).

**Description**

Validate the interface mode, and advertising's autoneg bit, removing any
media ethtool link modes that would not be supportable from the supported
mask. Phylink will propagate the changes to the advertising mask. See the
[`struct phylink_mac_ops`](#c-struct-phylink_mac_ops) `validate()` method.

Returns -EINVAL if the interface mode/autoneg mode is not supported.
Returns non-zero positive if the link state can be supported.

#### <a id="c-pcs_inband_caps"></a>`pcs_inband_caps()`

```c
unsigned int pcs_inband_caps(struct phylink_pcs *pcs, phy_interface_t interface)
```

query PCS in-band capabilities for interface mode.

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).
- `phy_interface_t interface`: interface mode to be queried

**Description**

Returns zero if it is unknown what in-band signalling is supported by the
PHY (e.g. because the PHY driver doesn't implement the method.) Otherwise,
returns a bit mask of the LINK_INBAND_* values from
[`enum link_inband_signalling`](#c-enum-link_inband_signalling) to describe which inband modes are supported
for this interface mode.

#### <a id="c-pcs_enable"></a>`pcs_enable()`

```c
int pcs_enable(struct phylink_pcs *pcs)
```

enable the PCS.

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).

#### <a id="c-pcs_disable"></a>`pcs_disable()`

```c
void pcs_disable(struct phylink_pcs *pcs)
```

disable the PCS.

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).

#### <a id="c-pcs_get_state"></a>`pcs_get_state()`

```c
void pcs_get_state(struct phylink_pcs *pcs, unsigned int neg_mode, struct phylink_link_state *state)
```

Read the current inband link state from the hardware

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).
- `unsigned int neg_mode`: link negotiation mode (PHYLINK_PCS_NEG_xxx)
- `struct phylink_link_state *state`: a pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).

**Description**

Read the current inband link state from the MAC PCS, reporting the
current speed in **state->speed**, duplex mode in **state->duplex**, pause
mode in **state->pause** using the `MLO_PAUSE_RX` and `MLO_PAUSE_TX` bits,
negotiation completion state in **state->an_complete**, and link up state
in **state->link**. If possible, **state->lp_advertising** should also be
populated.

Note that the **neg_mode** parameter is always the PHYLINK_PCS_NEG_xxx
state, not MLO_AN_xxx.

#### <a id="c-pcs_config"></a>`pcs_config()`

```c
int pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, phy_interface_t interface, const unsigned long *advertising, bool permit_pause_to_mac)
```

Configure the PCS mode and advertisement

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).
- `unsigned int neg_mode`: link negotiation mode (see below)
- `phy_interface_t interface`: interface mode to be used
- `const unsigned long *advertising`: adertisement ethtool link mode mask
- `bool permit_pause_to_mac`: permit forwarding pause resolution to MAC

**Description**

Configure the PCS for the operating mode, the interface mode, and set
the advertisement mask. **permit_pause_to_mac** indicates whether the
hardware may forward the pause mode resolution to the MAC.

When operating in `MLO_AN_INBAND`, inband should always be enabled,
otherwise inband should be disabled.

For SGMII, there is no advertisement from the MAC side, the PCS should
be programmed to acknowledge the inband word from the PHY.

For 1000BASE-X, the advertisement should be programmed into the PCS.

For most 10GBASE-R, there is no advertisement.

The `neg_mode` argument should be tested via the phylink_mode_*() family of
functions, or for PCS that set pcs->neg_mode true, should be tested
against the PHYLINK_PCS_NEG_* definitions.

[`pcs_config()`](#c-pcs_config) will be called when configuration of the PCS is required
or when the advertisement is possibly updated. It must not unnecessarily
disrupt an established link.

When an autonegotiation restart is required for 802.3z modes, .[`pcs_config()`](#c-pcs_config)
should return a positive non-zero integer (e.g. 1) to indicate to phylink
to call the [`pcs_an_restart()`](#c-pcs_an_restart) method.

#### <a id="c-pcs_an_restart"></a>`pcs_an_restart()`

```c
void pcs_an_restart(struct phylink_pcs *pcs)
```

restart 802.3z BaseX autonegotiation

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).

**Description**

When PCS ops are present, this overrides `mac_an_restart()` in [`struct phylink_mac_ops`](#c-struct-phylink_mac_ops).

#### <a id="c-pcs_link_up"></a>`pcs_link_up()`

```c
void pcs_link_up(struct phylink_pcs *pcs, unsigned int neg_mode, phy_interface_t interface, int speed, int duplex)
```

program the PCS for the resolved link configuration

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).
- `unsigned int neg_mode`: link negotiation mode (see below)
- `phy_interface_t interface`: link `typedef phy_interface_t` mode
- `int speed`: link speed
- `int duplex`: link duplex

**Description**

This call will be made just before [`mac_link_up()`](#c-mac_link_up) to inform the PCS of
the resolved link parameters. For example, a PCS operating in SGMII
mode without in-band AN needs to be manually configured for the link
and duplex setting. Otherwise, this should be a no-op.

The `mode` argument should be tested via the phylink_mode_*() family of
functions, or for PCS that set pcs->neg_mode true, should be tested
against the PHYLINK_PCS_NEG_* definitions.

#### <a id="c-pcs_disable_eee"></a>`pcs_disable_eee()`

```c
void pcs_disable_eee(struct phylink_pcs *pcs)
```

Disable EEE at the PCS

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs)

**Description**

Optional method informing the PCS that EEE has been disabled at the MAC.

#### <a id="c-pcs_enable_eee"></a>`pcs_enable_eee()`

```c
void pcs_enable_eee(struct phylink_pcs *pcs)
```

Enable EEE at the PCS

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs)

**Description**

Optional method informing the PCS that EEE is about to be enabled at the MAC.

#### <a id="c-pcs_pre_init"></a>`pcs_pre_init()`

```c
int pcs_pre_init(struct phylink_pcs *pcs)
```

Configure PCS components necessary for MAC initialization

**Parameters**

- `struct phylink_pcs *pcs`: a pointer to a [`struct phylink_pcs`](#c-struct-phylink_pcs).

**Description**

This function can be called by MAC drivers through the
`phylink_pcs_pre_init()` wrapper, before their hardware is initialized. It
should not be called after the link is brought up, as reconfiguring the PCS
at this point could break the link.

Some MAC devices require specific hardware initialization to be performed by
their associated PCS device before they can properly initialize their own
hardware. An example of this is the initialization of stmmac controllers,
which requires an active REF_CLK signal to be provided by the PHY/PCS.

By calling `phylink_pcs_pre_init()`, MAC drivers can ensure that the PCS is
setup in a way that allows for successful hardware initialization.

The specific configuration performed by [`pcs_pre_init()`](#c-pcs_pre_init) is dependent on the
model of PCS and the requirements of the MAC device attached to it. PCS
driver authors should consider whether their target device is to be used in
conjunction with a MAC device whose driver calls `phylink_pcs_pre_init()`. MAC
driver authors should document their requirements for the PCS
pre-initialization.

#### <a id="c-phylink_get_link_timer_ns"></a>`phylink_get_link_timer_ns()`

```c
int phylink_get_link_timer_ns(phy_interface_t interface)
```

return the PCS link timer value

**Parameters**

- `phy_interface_t interface`: link `typedef phy_interface_t` mode

**Description**

Return the PCS link timer setting in nanoseconds for the PHY **interface**
mode, or -EINVAL if not appropriate.

#### <a id="c-phylink_mac_implements_lpi"></a>`phylink_mac_implements_lpi()`

```c
bool phylink_mac_implements_lpi(const struct phylink_mac_ops *ops)
```

determine if MAC implements LPI ops

**Parameters**

- `const struct phylink_mac_ops *ops`: phylink_mac_ops structure

**Description**

Returns true if the phylink MAC operations structure indicates that the
LPI operations have been implemented, false otherwise.



#### <a id="c-struct-phylink"></a>`struct phylink`

internal data type for phylink

**Definition**

```c
struct phylink {
};
```

#### <a id="c-phylink_set_port_modes"></a>`phylink_set_port_modes()`

```c
void phylink_set_port_modes(unsigned long *mask)
```

set the port type modes in the ethtool mask

**Parameters**

- `unsigned long *mask`: ethtool link mode mask

**Description**

Sets all the port type modes in the ethtool mask.  MAC drivers should
use this in their 'validate' callback.

#### <a id="c-phylink_interface_max_speed"></a>`phylink_interface_max_speed()`

```c
int phylink_interface_max_speed(phy_interface_t interface)
```

get the maximum speed of a phy interface

**Parameters**

- `phy_interface_t interface`: phy interface mode defined by `typedef phy_interface_t`

**Description**

Determine the maximum speed of a phy interface. This is intended to help
determine the correct speed to pass to the MAC when the phy is performing
rate matching.

**Return**

The maximum speed of **interface**

#### <a id="c-phylink_caps_to_link_caps"></a>`phylink_caps_to_link_caps()`

```c
unsigned long phylink_caps_to_link_caps(unsigned long caps)
```

Convert a set of MAC capabilities LINK caps

**Parameters**

- `unsigned long caps`: A set of MAC capabilities

**Return**

The corresponding set of LINK_CAPA as defined in phy-caps.h

#### <a id="c-phylink_caps_to_linkmodes"></a>`phylink_caps_to_linkmodes()`

```c
void phylink_caps_to_linkmodes(unsigned long *linkmodes, unsigned long caps)
```

Convert capabilities to ethtool link modes

**Parameters**

- `unsigned long *linkmodes`: ethtool linkmode mask (must be already initialised)
- `unsigned long caps`: bitmask of MAC capabilities

**Description**

Set all possible pause, speed and duplex linkmodes in **linkmodes** that are
supported by the **caps**. **linkmodes** must have been initialised previously.

#### <a id="c-phylink_limit_mac_speed"></a>`phylink_limit_mac_speed()`

```c
void phylink_limit_mac_speed(struct phylink_config *config, u32 max_speed)
```

limit the phylink_config to a maximum speed

**Parameters**

- `struct phylink_config *config`: pointer to a [`struct phylink_config`](#c-struct-phylink_config)
- `u32 max_speed`: maximum speed

**Description**

Mask off MAC capabilities for speeds higher than the **max_speed** parameter.
Any further motifications of config.mac_capabilities will override this.

#### <a id="c-phylink_cap_from_speed_duplex"></a>`phylink_cap_from_speed_duplex()`

```c
unsigned long phylink_cap_from_speed_duplex(int speed, unsigned int duplex)
```

Get mac capability from speed/duplex

**Parameters**

- `int speed`: the speed to search for
- `unsigned int duplex`: the duplex to search for

**Description**

Find the mac capability for a given speed and duplex.

**Return**

A mask with the mac capability patching **speed** and **duplex**, or 0 if
there were no matches.

#### <a id="c-phylink_get_capabilities"></a>`phylink_get_capabilities()`

```c
unsigned long phylink_get_capabilities(phy_interface_t interface, unsigned long mac_capabilities, int rate_matching)
```

get capabilities for a given MAC

**Parameters**

- `phy_interface_t interface`: phy interface mode defined by `typedef phy_interface_t`
- `unsigned long mac_capabilities`: bitmask of MAC capabilities
- `int rate_matching`: type of rate matching being performed

**Description**

Get the MAC capabilities that are supported by the **interface** mode and
**mac_capabilities**.

#### <a id="c-phylink_validate_mask_caps"></a>`phylink_validate_mask_caps()`

```c
void phylink_validate_mask_caps(unsigned long *supported, struct phylink_link_state *state, unsigned long mac_capabilities)
```

Restrict link modes based on caps

**Parameters**

- `unsigned long *supported`: ethtool bitmask for supported link modes.
- `struct phylink_link_state *state`: pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).
- `unsigned long mac_capabilities`: bitmask of MAC capabilities

**Description**

Calculate the supported link modes based on **mac_capabilities**, and restrict
**supported** and **state** based on that. Use this function if your capabiliies
aren't constant, such as if they vary depending on the interface.

#### <a id="c-phylink_pcs_neg_mode"></a>`phylink_pcs_neg_mode()`

```c
void phylink_pcs_neg_mode(struct phylink *pl, struct phylink_pcs *pcs, phy_interface_t interface, const unsigned long *advertising)
```

helper to determine PCS inband mode

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct phylink_pcs *pcs`: a pointer to [`struct phylink_pcs`](#c-struct-phylink_pcs)
- `phy_interface_t interface`: interface mode to be used
- `const unsigned long *advertising`: adertisement ethtool link mode mask

**Description**

Determines the negotiation mode to be used by the PCS, and returns
one of:

- `PHYLINK_PCS_NEG_NONE`: interface mode does not support inband
- `PHYLINK_PCS_NEG_OUTBAND`: an out of band mode (e.g. reading the PHY)
  will be used.
- `PHYLINK_PCS_NEG_INBAND_DISABLED`: inband mode selected but autoneg
  disabled
- `PHYLINK_PCS_NEG_INBAND_ENABLED`: inband mode selected and autoneg enabled

**Note**

this is for cases where the PCS itself is involved in negotiation
(e.g. Clause 37, SGMII and similar) not Clause 73.

#### <a id="c-phylink_set_fixed_link"></a>`phylink_set_fixed_link()`

```c
int phylink_set_fixed_link(struct phylink *pl, const struct phylink_link_state *state)
```

set the fixed link

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `const struct phylink_link_state *state`: a pointer to a struct phylink_link_state.

**Description**

This function is used when the link parameters are known and do not change,
making it suitable for certain types of network connections.

**Return**

zero on success or negative error code.

#### <a id="c-phylink_create"></a>`phylink_create()`

```c
struct phylink * phylink_create(struct phylink_config *config, const struct fwnode_handle *fwnode, phy_interface_t iface, const struct phylink_mac_ops *mac_ops)
```

create a phylink instance

**Parameters**

- `struct phylink_config *config`: a pointer to the target [`struct phylink_config`](#c-struct-phylink_config)
- `const struct fwnode_handle *fwnode`: a pointer to a `struct fwnode_handle` describing the network
  interface
- `phy_interface_t iface`: the desired link mode defined by `typedef phy_interface_t`
- `const struct phylink_mac_ops *mac_ops`: a pointer to a [`struct phylink_mac_ops`](#c-struct-phylink_mac_ops) for the MAC.

**Description**

Create a new phylink instance, and parse the link parameters found in **np**.
This will parse in-band modes, fixed-link or SFP configuration.

**Note**

the rtnl lock must not be held when calling this function.

Returns a pointer to a [`struct phylink`](#c-struct-phylink), or an error-pointer value. Users
must use [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) to check for errors from this function.

#### <a id="c-phylink_destroy"></a>`phylink_destroy()`

```c
void phylink_destroy(struct phylink *pl)
```

cleanup and destroy the phylink instance

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Destroy a phylink instance. Any PHY that has been attached must have been
cleaned up via [`phylink_disconnect_phy()`](#c-phylink_disconnect_phy) prior to calling this function.

**Note**

the rtnl lock must not be held when calling this function.

#### <a id="c-phylink_expects_phy"></a>`phylink_expects_phy()`

```c
bool phylink_expects_phy(struct phylink *pl)
```

Determine if phylink expects a phy to be attached

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

When using fixed-link mode, or in-band mode with 1000base-X or 2500base-X,
no PHY is needed.

Returns true if phylink will be expecting a PHY.

#### <a id="c-phylink_connect_phy"></a>`phylink_connect_phy()`

```c
int phylink_connect_phy(struct phylink *pl, struct phy_device *phy)
```

connect a PHY to the phylink instance

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct phy_device *phy`: a pointer to a [`struct phy_device`](#c-struct-phy_device).

**Description**

Connect **phy** to the phylink instance specified by **pl** by calling
[`phy_attach_direct()`](#c-phy_attach_direct). Configure the **phy** according to the MAC driver's
capabilities, start the PHYLIB state machine and enable any interrupts
that the PHY supports.

This updates the phylink's ethtool supported and advertising link mode
masks.

Returns 0 on success or a negative errno.

#### <a id="c-phylink_of_phy_connect"></a>`phylink_of_phy_connect()`

```c
int phylink_of_phy_connect(struct phylink *pl, struct device_node *dn, u32 flags)
```

connect the PHY specified in the DT mode.

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct device_node *dn`: a pointer to a `struct device_node`.
- `u32 flags`: PHY-specific flags to communicate to the PHY device driver

**Description**

Connect the phy specified in the device node **dn** to the phylink instance
specified by **pl**. Actions specified in [`phylink_connect_phy()`](#c-phylink_connect_phy) will be
performed.

Returns 0 on success or a negative errno.

#### <a id="c-phylink_fwnode_phy_connect"></a>`phylink_fwnode_phy_connect()`

```c
int phylink_fwnode_phy_connect(struct phylink *pl, const struct fwnode_handle *fwnode, u32 flags)
```

connect the PHY specified in the fwnode.

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `const struct fwnode_handle *fwnode`: a pointer to a `struct fwnode_handle`.
- `u32 flags`: PHY-specific flags to communicate to the PHY device driver

**Description**

Connect the phy specified **fwnode** to the phylink instance specified
by **pl**.

Returns 0 on success or a negative errno.

#### <a id="c-phylink_disconnect_phy"></a>`phylink_disconnect_phy()`

```c
void phylink_disconnect_phy(struct phylink *pl)
```

disconnect any PHY attached to the phylink instance.

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Disconnect any current PHY from the phylink instance described by **pl**.

#### <a id="c-phylink_mac_change"></a>`phylink_mac_change()`

```c
void phylink_mac_change(struct phylink *pl, bool up)
```

notify phylink of a change in MAC state

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `bool up`: indicates whether the link is currently up.

**Description**

The MAC driver should call this driver when the state of its link
changes (eg, link failure, new negotiation results, etc.)

#### <a id="c-phylink_pcs_change"></a>`phylink_pcs_change()`

```c
void phylink_pcs_change(struct phylink_pcs *pcs, bool up)
```

notify phylink of a change to PCS link state

**Parameters**

- `struct phylink_pcs *pcs`: pointer to [`struct phylink_pcs`](#c-struct-phylink_pcs)
- `bool up`: indicates whether the link is currently up.

**Description**

The PCS driver should call this when the state of its link changes
(e.g. link failure, new negotiation results, etc.) Note: it should
not determine "up" by reading the BMSR. If in doubt about the link
state at interrupt time, then pass true if [`pcs_get_state()`](#c-pcs_get_state) returns
the latched link-down state, otherwise pass false.

#### <a id="c-phylink_start"></a>`phylink_start()`

```c
void phylink_start(struct phylink *pl)
```

start a phylink instance

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Start the phylink instance specified by **pl**, configuring the MAC for the
desired link mode(s) and negotiation style. This should be called from the
network device driver's `struct net_device_ops` `ndo_open()` method.

#### <a id="c-phylink_stop"></a>`phylink_stop()`

```c
void phylink_stop(struct phylink *pl)
```

stop a phylink instance

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Stop the phylink instance specified by **pl**. This should be called from the
network device driver's `struct net_device_ops` `ndo_stop()` method.  The
network device's carrier state should not be changed prior to calling this
function.

This will synchronously bring down the link if the link is not already
down (in other words, it will trigger a [`mac_link_down()`](#c-mac_link_down) method call.)

#### <a id="c-phylink_rx_clk_stop_block"></a>`phylink_rx_clk_stop_block()`

```c
void phylink_rx_clk_stop_block(struct phylink *pl)
```

block PHY ability to stop receive clock in LPI

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Disable the PHY's ability to stop the receive clock while the receive path
is in EEE LPI state, until the number of calls to [`phylink_rx_clk_stop_block()`](#c-phylink_rx_clk_stop_block)
are balanced by calls to [`phylink_rx_clk_stop_unblock()`](#c-phylink_rx_clk_stop_unblock).

#### <a id="c-phylink_rx_clk_stop_unblock"></a>`phylink_rx_clk_stop_unblock()`

```c
void phylink_rx_clk_stop_unblock(struct phylink *pl)
```

unblock PHY ability to stop receive clock

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

All calls to [`phylink_rx_clk_stop_block()`](#c-phylink_rx_clk_stop_block) must be balanced with a
corresponding call to [`phylink_rx_clk_stop_unblock()`](#c-phylink_rx_clk_stop_unblock) to restore the PHYs
ability to stop the receive clock when the receive path is in EEE LPI mode.

#### <a id="c-phylink_suspend"></a>`phylink_suspend()`

```c
void phylink_suspend(struct phylink *pl, bool mac_wol)
```

handle a network device suspend event

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `bool mac_wol`: true if the MAC needs to receive packets for Wake-on-Lan

**Description**

Handle a network device suspend event. There are several cases:

- If Wake-on-Lan is not active, we can bring down the link between
  the MAC and PHY by calling [`phylink_stop()`](#c-phylink_stop).
- If Wake-on-Lan is active, and being handled only by the PHY, we
  can also bring down the link between the MAC and PHY.
- If Wake-on-Lan is active, but being handled by the MAC, the MAC
  still needs to receive packets, so we can not bring the link down.

**Note**

when phylink managed Wake-on-Lan is in use, **mac_wol** is ignored.
(struct phylink_mac_ops.mac_set_wol populated.)

#### <a id="c-phylink_prepare_resume"></a>`phylink_prepare_resume()`

```c
void phylink_prepare_resume(struct phylink *pl)
```

prepare to resume a network device

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Optional, but if called must be called prior to [`phylink_resume()`](#c-phylink_resume).

Prepare to resume a network device, preparing the PHY as necessary.

#### <a id="c-phylink_resume"></a>`phylink_resume()`

```c
void phylink_resume(struct phylink *pl)
```

handle a network device resume event

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Undo the effects of [`phylink_suspend()`](#c-phylink_suspend), returning the link to an
operational state.

#### <a id="c-phylink_ethtool_get_wol"></a>`phylink_ethtool_get_wol()`

```c
void phylink_ethtool_get_wol(struct phylink *pl, struct ethtool_wolinfo *wol)
```

get the wake on lan parameters for the PHY

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_wolinfo *wol`: a pointer to `struct ethtool_wolinfo` to hold the read parameters

**Description**

Read the wake on lan parameters from the PHY attached to the phylink
instance specified by **pl**. If no PHY is currently attached, report no
support for wake on lan.

#### <a id="c-phylink_ethtool_set_wol"></a>`phylink_ethtool_set_wol()`

```c
int phylink_ethtool_set_wol(struct phylink *pl, struct ethtool_wolinfo *wol)
```

set wake on lan parameters

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_wolinfo *wol`: a pointer to `struct ethtool_wolinfo` for the desired parameters

**Description**

Set the wake on lan parameters for the PHY attached to the phylink
instance specified by **pl**. If no PHY is attached, returns `EOPNOTSUPP`
error.

Returns zero on success or negative errno code.

#### <a id="c-phylink_ethtool_ksettings_get"></a>`phylink_ethtool_ksettings_get()`

```c
int phylink_ethtool_ksettings_get(struct phylink *pl, struct ethtool_link_ksettings *kset)
```

get the current link settings

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_link_ksettings *kset`: a pointer to a `struct ethtool_link_ksettings` to hold link settings

**Description**

Read the current link settings for the phylink instance specified by **pl**.
This will be the link settings read from the MAC, PHY or fixed link
settings depending on the current negotiation mode.

#### <a id="c-phylink_ethtool_ksettings_set"></a>`phylink_ethtool_ksettings_set()`

```c
int phylink_ethtool_ksettings_set(struct phylink *pl, const struct ethtool_link_ksettings *kset)
```

set the link settings

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `const struct ethtool_link_ksettings *kset`: a pointer to a `struct ethtool_link_ksettings` for the desired modes

#### <a id="c-phylink_ethtool_nway_reset"></a>`phylink_ethtool_nway_reset()`

```c
int phylink_ethtool_nway_reset(struct phylink *pl)
```

restart negotiation

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Restart negotiation for the phylink instance specified by **pl**. This will
cause any attached phy to restart negotiation with the link partner, and
if the MAC is in a BaseX mode, the MAC will also be requested to restart
negotiation.

Returns zero on success, or negative error code.

#### <a id="c-phylink_ethtool_get_pauseparam"></a>`phylink_ethtool_get_pauseparam()`

```c
void phylink_ethtool_get_pauseparam(struct phylink *pl, struct ethtool_pauseparam *pause)
```

get the current pause parameters

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_pauseparam *pause`: a pointer to a `struct ethtool_pauseparam`

#### <a id="c-phylink_ethtool_set_pauseparam"></a>`phylink_ethtool_set_pauseparam()`

```c
int phylink_ethtool_set_pauseparam(struct phylink *pl, struct ethtool_pauseparam *pause)
```

set the current pause parameters

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_pauseparam *pause`: a pointer to a `struct ethtool_pauseparam`

#### <a id="c-phylink_get_eee_err"></a>`phylink_get_eee_err()`

```c
int phylink_get_eee_err(struct phylink *pl)
```

read the energy efficient ethernet error counter

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create).

**Description**

Read the Energy Efficient Ethernet error counter from the PHY associated
with the phylink instance specified by **pl**.

Returns positive error counter value, or negative error code.

#### <a id="c-phylink_ethtool_get_eee"></a>`phylink_ethtool_get_eee()`

```c
int phylink_ethtool_get_eee(struct phylink *pl, struct ethtool_keee *eee)
```

read the energy efficient ethernet parameters

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_keee *eee`: a pointer to a `struct ethtool_keee` for the read parameters

#### <a id="c-phylink_ethtool_set_eee"></a>`phylink_ethtool_set_eee()`

```c
int phylink_ethtool_set_eee(struct phylink *pl, struct ethtool_keee *eee)
```

set the energy efficient ethernet parameters

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ethtool_keee *eee`: a pointer to a `struct ethtool_keee` for the desired parameters

#### <a id="c-phylink_mii_ioctl"></a>`phylink_mii_ioctl()`

```c
int phylink_mii_ioctl(struct phylink *pl, struct ifreq *ifr, int cmd)
```

generic mii ioctl interface

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `struct ifreq *ifr`: a pointer to a `struct ifreq` for socket ioctls
- `int cmd`: ioctl cmd to execute

**Description**

Perform the specified MII ioctl on the PHY attached to the phylink instance
specified by **pl**. If no PHY is attached, emulate the presence of the PHY.

- `SIOCGMIIPHY`:
  read register from the current PHY.
- `SIOCGMIIREG`:
  read register from the specified PHY.
- `SIOCSMIIREG`:
  set a register on the specified PHY.

**Return**

zero on success or negative error code.

#### <a id="c-phylink_speed_down"></a>`phylink_speed_down()`

```c
int phylink_speed_down(struct phylink *pl, bool sync)
```

set the non-SFP PHY to lowest speed supported by both link partners

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)
- `bool sync`: perform action synchronously

**Description**

If we have a PHY that is not part of a SFP module, then set the speed
as described in the [`phy_speed_down()`](#c-phy_speed_down) function. Please see this function
for a description of the **sync** parameter.

Returns zero if there is no PHY, otherwise as per [`phy_speed_down()`](#c-phy_speed_down).

#### <a id="c-phylink_speed_up"></a>`phylink_speed_up()`

```c
int phylink_speed_up(struct phylink *pl)
```

restore the advertised speeds prior to the call to [`phylink_speed_down()`](#c-phylink_speed_down)

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

If we have a PHY that is not part of a SFP module, then restore the
PHY speeds as per [`phy_speed_up()`](#c-phy_speed_up).

Returns zero if there is no PHY, otherwise as per [`phy_speed_up()`](#c-phy_speed_up).

#### <a id="c-phylink_decode_usxgmii_word"></a>`phylink_decode_usxgmii_word()`

```c
void phylink_decode_usxgmii_word(struct phylink_link_state *state, uint16_t lpa)
```

decode the USXGMII word from a MAC PCS

**Parameters**

- `struct phylink_link_state *state`: a pointer to a struct phylink_link_state.
- `uint16_t lpa`: a 16 bit value which stores the USXGMII auto-negotiation word

**Description**

Helper for MAC PCS supporting the USXGMII protocol and the auto-negotiation
code word.  Decode the USXGMII code word and populate the corresponding fields
(speed, duplex) into the phylink_link_state structure.

#### <a id="c-phylink_decode_usgmii_word"></a>`phylink_decode_usgmii_word()`

```c
void phylink_decode_usgmii_word(struct phylink_link_state *state, uint16_t lpa)
```

decode the USGMII word from a MAC PCS

**Parameters**

- `struct phylink_link_state *state`: a pointer to a struct phylink_link_state.
- `uint16_t lpa`: a 16 bit value which stores the USGMII auto-negotiation word

**Description**

Helper for MAC PCS supporting the USGMII protocol and the auto-negotiation
code word.  Decode the USGMII code word and populate the corresponding fields
(speed, duplex) into the phylink_link_state structure. The structure for this
word is the same as the USXGMII word, except it only supports speeds up to
1Gbps.

#### <a id="c-phylink_mii_c22_pcs_decode_state"></a>`phylink_mii_c22_pcs_decode_state()`

```c
void phylink_mii_c22_pcs_decode_state(struct phylink_link_state *state, unsigned int neg_mode, u16 bmsr, u16 lpa)
```

Decode MAC PCS state from MII registers

**Parameters**

- `struct phylink_link_state *state`: a pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).
- `unsigned int neg_mode`: link negotiation mode (PHYLINK_PCS_NEG_xxx)
- `u16 bmsr`: The value of the `MII_BMSR` register
- `u16 lpa`: The value of the `MII_LPA` register

**Description**

Helper for MAC PCS supporting the 802.3 clause 22 register set for
clause 37 negotiation and/or SGMII control.

Parse the Clause 37 or Cisco SGMII link partner negotiation word into
the phylink **state** structure. This is suitable to be used for implementing
the [`pcs_get_state()`](#c-pcs_get_state) member of the struct phylink_pcs_ops structure if
accessing **bmsr** and **lpa** cannot be done with MDIO directly.

#### <a id="c-phylink_mii_c22_pcs_get_state"></a>`phylink_mii_c22_pcs_get_state()`

```c
void phylink_mii_c22_pcs_get_state(struct mdio_device *pcs, unsigned int neg_mode, struct phylink_link_state *state)
```

read the MAC PCS state

**Parameters**

- `struct mdio_device *pcs`: a pointer to a `struct mdio_device`.
- `unsigned int neg_mode`: link negotiation mode (PHYLINK_PCS_NEG_xxx)
- `struct phylink_link_state *state`: a pointer to a [`struct phylink_link_state`](#c-struct-phylink_link_state).

**Description**

Helper for MAC PCS supporting the 802.3 clause 22 register set for
clause 37 negotiation and/or SGMII control.

Read the MAC PCS state from the MII device configured in **config** and
parse the Clause 37 or Cisco SGMII link partner negotiation word into
the phylink **state** structure. This is suitable to be directly plugged
into the [`pcs_get_state()`](#c-pcs_get_state) member of the struct phylink_pcs_ops
structure.

#### <a id="c-phylink_mii_c22_pcs_encode_advertisement"></a>`phylink_mii_c22_pcs_encode_advertisement()`

```c
int phylink_mii_c22_pcs_encode_advertisement(phy_interface_t interface, const unsigned long *advertising)
```

configure the clause 37 PCS advertisement

**Parameters**

- `phy_interface_t interface`: the PHY interface mode being configured
- `const unsigned long *advertising`: the ethtool advertisement mask

**Description**

Helper for MAC PCS supporting the 802.3 clause 22 register set for
clause 37 negotiation and/or SGMII control.

Encode the clause 37 PCS advertisement as specified by **interface** and
**advertising**.

**Return**

The new value for **adv**, or `-EINVAL` if it should not be changed.

#### <a id="c-phylink_mii_c22_pcs_config"></a>`phylink_mii_c22_pcs_config()`

```c
int phylink_mii_c22_pcs_config(struct mdio_device *pcs, phy_interface_t interface, const unsigned long *advertising, unsigned int neg_mode)
```

configure clause 22 PCS

**Parameters**

- `struct mdio_device *pcs`: a pointer to a `struct mdio_device`.
- `phy_interface_t interface`: the PHY interface mode being configured
- `const unsigned long *advertising`: the ethtool advertisement mask
- `unsigned int neg_mode`: PCS negotiation mode

**Description**

Configure a Clause 22 PCS PHY with the appropriate negotiation
parameters for the **mode**, **interface** and **advertising** parameters.
Returns negative error number on failure, zero if the advertisement
has not changed, or positive if there is a change.

#### <a id="c-phylink_mii_c22_pcs_an_restart"></a>`phylink_mii_c22_pcs_an_restart()`

```c
void phylink_mii_c22_pcs_an_restart(struct mdio_device *pcs)
```

restart 802.3z autonegotiation

**Parameters**

- `struct mdio_device *pcs`: a pointer to a `struct mdio_device`.

**Description**

Helper for MAC PCS supporting the 802.3 clause 22 register set for
clause 37 negotiation.

Restart the clause 37 negotiation with the link partner. This is
suitable to be directly plugged into the [`pcs_get_state()`](#c-pcs_get_state) member
of the struct phylink_pcs_ops structure.

#### <a id="c-phylink_replay_link_begin"></a>`phylink_replay_link_begin()`

```c
void phylink_replay_link_begin(struct phylink *pl)
```

begin replay of link callbacks for driver which loses state

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Helper for MAC drivers which may perform a destructive reset at runtime.
Both the own driver's [`mac_link_down()`](#c-mac_link_down) method is called, as well as the
`pcs_link_down()` method of the split PCS (if any).

This is similar to [`phylink_stop()`](#c-phylink_stop), except it does not alter the state of
the phylib PHY (it is assumed that it is not affected by the MAC destructive
reset).

#### <a id="c-phylink_replay_link_end"></a>`phylink_replay_link_end()`

```c
void phylink_replay_link_end(struct phylink *pl)
```

end replay of link callbacks for driver which lost state

**Parameters**

- `struct phylink *pl`: a pointer to a [`struct phylink`](#c-struct-phylink) returned from [`phylink_create()`](#c-phylink_create)

**Description**

Helper for MAC drivers which may perform a destructive reset at runtime.
Both the own driver's [`mac_config()`](#c-mac_config) and [`mac_link_up()`](#c-mac_link_up) methods, as well as the
[`pcs_config()`](#c-pcs_config) and [`pcs_link_up()`](#c-pcs_link_up) method of the split PCS (if any), are called.

This is similar to [`phylink_start()`](#c-phylink_start), except it does not alter the state of
the phylib PHY.

One must call this method only within the same `rtnl_lock()` critical section
as a previous `phylink_replay_link_start()`.


<a id="rst-sfp-support"></a>

### SFP support


#### <a id="c-struct-sfp_bus"></a>`struct sfp_bus`

internal representation of a sfp bus

**Definition**

```c
struct sfp_bus {
};
```



#### <a id="c-struct-sfp_eeprom_id"></a>`struct sfp_eeprom_id`

raw SFP module identification information

**Definition**

```c
struct sfp_eeprom_id {
    struct sfp_eeprom_base base;
    struct sfp_eeprom_ext ext;
};
```

**Members**

- `base`: base SFP module identification structure
- `ext`: extended SFP module identification structure

**Description**

See the SFF-8472 specification and related documents for the definition
of these structure members. This can be obtained from
https://www.snia.org/technology-communities/sff/specifications

#### <a id="c-struct-sfp_module_caps"></a>`struct sfp_module_caps`

sfp module capabilities

**Definition**

```c
struct sfp_module_caps {
    unsigned long interfaces[BITS_TO_LONGS(PHY_INTERFACE_MODE_MAX)];
    unsigned long link_modes[BITS_TO_LONGS(__ETHTOOL_LINK_MODE_MASK_NBITS)];
    bool may_have_phy;
    u8 port;
};
```

**Members**

- `interfaces`: bitmap of interfaces that the module may support
- `link_modes`: bitmap of ethtool link modes that the module may support
- `may_have_phy`: indicate whether the module may have an ethernet PHY
  There is no way to be sure that a module has a PHY as the EEPROM
  doesn't contain this information. When set, this does not mean that
  the module definitely has a PHY.
- `port`: one of ethtool `PORT_*` definitions, parsed from the module
  EEPROM, or `PORT_OTHER` if the port type is not known.

#### <a id="c-struct-sfp_upstream_ops"></a>`struct sfp_upstream_ops`

upstream operations structure

**Definition**

```c
struct sfp_upstream_ops {
    void (*attach)(void *priv, struct sfp_bus *bus);
    void (*detach)(void *priv, struct sfp_bus *bus);
    int (*module_insert)(void *priv, const struct sfp_eeprom_id *id);
    void (*module_remove)(void *priv);
    int (*module_start)(void *priv);
    void (*module_stop)(void *priv);
    void (*link_down)(void *priv);
    void (*link_up)(void *priv);
    int (*connect_phy)(void *priv, struct phy_device *);
    void (*disconnect_phy)(void *priv, struct phy_device *);
};
```

**Members**

- `attach`: called when the sfp socket driver is bound to the upstream
  (mandatory).
- `detach`: called when the sfp socket driver is unbound from the upstream
  (mandatory).
- `module_insert`: called after a module has been detected to determine
  whether the module is supported for the upstream device.
- `module_remove`: called after the module has been removed.
- `module_start`: called after the PHY probe step
- `module_stop`: called before the PHY is removed
- `link_down`: called when the link is non-operational for whatever
  reason.
- `link_up`: called when the link is operational.
- `connect_phy`: called when an I2C accessible PHY has been detected
  on the module.
- `disconnect_phy`: called when a module with an I2C accessible PHY has
  been removed.



#### <a id="c-sfp_select_interface"></a>`sfp_select_interface()`

```c
phy_interface_t sfp_select_interface(struct sfp_bus *bus, const unsigned long *link_modes)
```

Select appropriate phy_interface_t mode

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module
- `const unsigned long *link_modes`: ethtool link modes mask

**Description**

Derive the phy_interface_t mode for the SFP module from the link
modes mask.

#### <a id="c-sfp_bus_put"></a>`sfp_bus_put()`

```c
void sfp_bus_put(struct sfp_bus *bus)
```

put a reference on the [`struct sfp_bus`](#c-struct-sfp_bus)

**Parameters**

- `struct sfp_bus *bus`: the [`struct sfp_bus`](#c-struct-sfp_bus) found via [`sfp_bus_find_fwnode()`](#c-sfp_bus_find_fwnode)

**Description**

Put a reference on the [`struct sfp_bus`](#c-struct-sfp_bus) and free the underlying structure
if this was the last reference.

#### <a id="c-sfp_get_module_info"></a>`sfp_get_module_info()`

```c
int sfp_get_module_info(struct sfp_bus *bus, struct ethtool_modinfo *modinfo)
```

Get the ethtool_modinfo for a SFP module

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module
- `struct ethtool_modinfo *modinfo`: a `struct ethtool_modinfo`

**Description**

Fill in the type and eeprom_len parameters in **modinfo** for a module on
the sfp bus specified by **bus**.

Returns 0 on success or a negative errno number.

#### <a id="c-sfp_get_module_eeprom"></a>`sfp_get_module_eeprom()`

```c
int sfp_get_module_eeprom(struct sfp_bus *bus, struct ethtool_eeprom *ee, u8 *data)
```

Read the SFP module EEPROM

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module
- `struct ethtool_eeprom *ee`: a `struct ethtool_eeprom`
- `u8 *data`: buffer to contain the EEPROM data (must be at least **ee->len** bytes)

**Description**

Read the EEPROM as specified by the supplied **ee**. See the documentation
for `struct ethtool_eeprom` for the region to be read.

Returns 0 on success or a negative errno number.

#### <a id="c-sfp_get_module_eeprom_by_page"></a>`sfp_get_module_eeprom_by_page()`

```c
int sfp_get_module_eeprom_by_page(struct sfp_bus *bus, const struct ethtool_module_eeprom *page, struct netlink_ext_ack *extack)
```

Read a page from the SFP module EEPROM

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module
- `const struct ethtool_module_eeprom *page`: a `struct ethtool_module_eeprom`
- `struct netlink_ext_ack *extack`: extack for reporting problems

**Description**

Read an EEPROM page as specified by the supplied **page**. See the
documentation for `struct ethtool_module_eeprom` for the page to be read.

Returns 0 on success or a negative errno number. More error
information might be provided via extack

#### <a id="c-sfp_upstream_start"></a>`sfp_upstream_start()`

```c
void sfp_upstream_start(struct sfp_bus *bus)
```

Inform the SFP that the network device is up

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module

**Description**

Inform the SFP socket that the network device is now up, so that the
module can be enabled by allowing TX_DISABLE to be deasserted. This
should be called from the network device driver's `struct net_device_ops`
`ndo_open()` method.

#### <a id="c-sfp_upstream_stop"></a>`sfp_upstream_stop()`

```c
void sfp_upstream_stop(struct sfp_bus *bus)
```

Inform the SFP that the network device is down

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module

**Description**

Inform the SFP socket that the network device is now up, so that the
module can be disabled by asserting TX_DISABLE, disabling the laser
in optical modules. This should be called from the network device
driver's `struct net_device_ops` `ndo_stop()` method.

#### <a id="c-sfp_upstream_set_signal_rate"></a>`sfp_upstream_set_signal_rate()`

```c
void sfp_upstream_set_signal_rate(struct sfp_bus *bus, unsigned int rate_kbd)
```

set data signalling rate

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module
- `unsigned int rate_kbd`: signalling rate in units of 1000 baud

**Description**

Configure the rate select settings on the SFP module for the signalling
rate (not the same as the data rate).

- Locks that may be held:
  Phylink's state_mutex
  rtnl lock
  SFP's sm_mutex

#### <a id="c-sfp_bus_find_fwnode"></a>`sfp_bus_find_fwnode()`

```c
struct sfp_bus * sfp_bus_find_fwnode(const struct fwnode_handle *fwnode)
```

parse and locate the SFP bus from fwnode

**Parameters**

- `const struct fwnode_handle *fwnode`: firmware node for the parent device (MAC or PHY)

**Description**

Parse the parent device's firmware node for a SFP bus, and locate
the sfp_bus structure, incrementing its reference count.  This must
be put via [`sfp_bus_put()`](#c-sfp_bus_put) when done.

- corresponding to the errors detailed for
  `fwnode_property_get_reference_args()`.
- `-ENOMEM` if we failed to allocate the bus.
- an error from the upstream's `connect_phy()` method.

**Return**

- on success, a pointer to the sfp_bus structure,
- `NULL` if no SFP is specified,
- on failure, an error pointer value:

#### <a id="c-sfp_bus_add_upstream"></a>`sfp_bus_add_upstream()`

```c
int sfp_bus_add_upstream(struct sfp_bus *bus, void *upstream, const struct sfp_upstream_ops *ops)
```

parse and register the neighbouring device

**Parameters**

- `struct sfp_bus *bus`: the [`struct sfp_bus`](#c-struct-sfp_bus) found via [`sfp_bus_find_fwnode()`](#c-sfp_bus_find_fwnode)
- `void *upstream`: the upstream private data
- `const struct sfp_upstream_ops *ops`: the upstream's [`struct sfp_upstream_ops`](#c-struct-sfp_upstream_ops)

**Description**

Add upstream driver for the SFP bus, and if the bus is complete, register
the SFP bus using `sfp_register_upstream()`.  This takes a reference on the
bus, so it is safe to put the bus after this call.

- corresponding to the errors detailed for
  `fwnode_property_get_reference_args()`.
- `-ENOMEM` if we failed to allocate the bus.
- an error from the upstream's `connect_phy()` method.

**Return**

- on success, a pointer to the sfp_bus structure,
- `NULL` if no SFP is specified,
- on failure, an error pointer value:

#### <a id="c-sfp_bus_del_upstream"></a>`sfp_bus_del_upstream()`

```c
void sfp_bus_del_upstream(struct sfp_bus *bus)
```

Delete a sfp bus

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module

**Description**

Delete a previously registered upstream connection for the SFP
module. **bus** should have been added by [`sfp_bus_add_upstream()`](#c-sfp_bus_add_upstream).

#### <a id="c-sfp_get_name"></a>`sfp_get_name()`

```c
const char * sfp_get_name(struct sfp_bus *bus)
```

Get the SFP device name

**Parameters**

- `struct sfp_bus *bus`: a pointer to the [`struct sfp_bus`](#c-struct-sfp_bus) structure for the sfp module

**Description**

Gets the SFP device's name, if **bus** has a registered socket. Callers must
hold RTNL, and the returned name is only valid until RTNL is released.

**Return**

- The name of the SFP device registered with `sfp_register_socket()`
- `NULL` if no device was registered on **bus**

---

# Kernel Connection Multiplexor

_Peios Kernel / Internals / Networking_

> Kernel Connection Multiplexor (KCM) is a mechanism that provides a message based interface over TCP for generic application protocols. With KCM an application can efficiently send and receive application protocol messages over TCP using…

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-kernel-connection-multiplexor"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Kernel Connection Multiplexor (KCM) is a mechanism that provides a message based interface over TCP for generic application protocols. With KCM an application can efficiently send and receive application protocol messages over TCP using datagram sockets.

KCM implements an NxM multiplexor in the kernel as diagrammed below:



```text
+------------+   +------------+   +------------+   +------------+
| KCM socket |   | KCM socket |   | KCM socket |   | KCM socket |
+------------+   +------------+   +------------+   +------------+
    |                 |               |                |
    +-----------+     |               |     +----------+
                |     |               |     |
            +----------------------------------+
            |           Multiplexor            |
            +----------------------------------+
                |   |           |           |  |
    +---------+   |           |           |  ------------+
    |             |           |           |              |
+----------+  +----------+  +----------+  +----------+ +----------+
|  Psock   |  |  Psock   |  |  Psock   |  |  Psock   | |  Psock   |
+----------+  +----------+  +----------+  +----------+ +----------+
    |              |           |            |             |
+----------+  +----------+  +----------+  +----------+ +----------+
| TCP sock |  | TCP sock |  | TCP sock |  | TCP sock | | TCP sock |
+----------+  +----------+  +----------+  +----------+ +----------+
```

<a id="rst-kcm-sockets"></a>

## KCM sockets

The KCM sockets provide the user interface to the multiplexor. All the KCM sockets bound to a multiplexor are considered to have equivalent function, and I/O operations in different sockets may be done in parallel without the need for synchronization between threads in userspace.

<a id="rst-multiplexor"></a>

## Multiplexor

The multiplexor provides the message steering. In the transmit path, messages written on a KCM socket are sent atomically on an appropriate TCP socket. Similarly, in the receive path, messages are constructed on each TCP socket (Psock) and complete messages are steered to a KCM socket.

<a id="rst-tcp-sockets-psocks"></a>

## TCP sockets &amp; Psocks

TCP sockets may be bound to a KCM multiplexor. A Psock structure is allocated for each bound TCP socket, this structure holds the state for constructing messages on receive as well as other connection specific information for KCM.

<a id="rst-connected-mode-semantics"></a>

## Connected mode semantics

Each multiplexor assumes that all attached TCP connections are to the same destination and can use the different connections for load balancing when transmitting. The normal send and recv calls (include sendmmsg and recvmmsg) can be used to send and receive messages from the KCM socket.

<a id="rst-socket-types"></a>

## Socket types

KCM supports SOCK_DGRAM and SOCK_SEQPACKET socket types.

<a id="rst-message-delineation"></a>

### Message delineation

Messages are sent over a TCP stream with some application protocol message format that typically includes a header which frames the messages. The length of a received message can be deduced from the application protocol header (often just a simple length field).

A TCP stream must be parsed to determine message boundaries. Berkeley Packet Filter (BPF) is used for this. When attaching a TCP socket to a multiplexor a BPF program must be specified. The program is called at the start of receiving a new message and is given an skbuff that contains the bytes received so far. It parses the message header and returns the length of the message. Given this information, KCM will construct the message of the stated length and deliver it to a KCM socket.

<a id="rst-tcp-socket-management"></a>

### TCP socket management

When a TCP socket is attached to a KCM multiplexor data ready (POLLIN) and write space available (POLLOUT) events are handled by the multiplexor. If there is a state change (disconnection) or other error on a TCP socket, an error is posted on the TCP socket so that a POLLERR event happens and KCM discontinues using the socket. When the application gets the error notification for a TCP socket, it should unattach the socket from KCM and then handle the error condition (the typical response is to close the socket and create a new connection if necessary).

KCM limits the maximum receive message size to be the size of the receive socket buffer on the attached TCP socket (the socket buffer size can be set by SO_RCVBUF). If the length of a new message reported by the BPF program is greater than this limit a corresponding error (EMSGSIZE) is posted on the TCP socket. The BPF program may also enforce a maximum messages size and report an error when it is exceeded.

A timeout may be set for assembling messages on a receive socket. The timeout value is taken from the receive timeout of the attached TCP socket (this is set by SO_RCVTIMEO). If the timer expires before assembly is complete an error (ETIMEDOUT) is posted on the socket.

<a id="rst-user-interface"></a>

## User interface

<a id="rst-creating-a-multiplexor"></a>

### Creating a multiplexor

A new multiplexor and initial KCM socket is created by a socket call:



```text
socket(AF_KCM, type, protocol)
```

- type is either SOCK_DGRAM or SOCK_SEQPACKET

- protocol is KCMPROTO_CONNECTED

<a id="rst-cloning-kcm-sockets"></a>

### Cloning KCM sockets

After the first KCM socket is created using the socket call as described above, additional sockets for the multiplexor can be created by cloning a KCM socket. This is accomplished by an ioctl on a KCM socket:



```text
/* From linux/kcm.h */
struct kcm_clone {
      int fd;
};

struct kcm_clone info;

memset(&info, 0, sizeof(info));

err = ioctl(kcmfd, SIOCKCMCLONE, &info);

if (!err)
  newkcmfd = info.fd;
```

<a id="rst-attach-transport-sockets"></a>

### Attach transport sockets

Attaching of transport sockets to a multiplexor is performed by calling an ioctl on a KCM socket for the multiplexor. e.g.:



```text
/* From linux/kcm.h */
struct kcm_attach {
      int fd;
      int bpf_fd;
};

struct kcm_attach info;

memset(&info, 0, sizeof(info));

info.fd = tcpfd;
info.bpf_fd = bpf_prog_fd;

ioctl(kcmfd, SIOCKCMATTACH, &info);
```

The kcm_attach structure contains:

> - fd: file descriptor for TCP socket being attached
>
> - bpf_prog_fd: file descriptor for compiled BPF program downloaded

<a id="rst-unattach-transport-sockets"></a>

### Unattach transport sockets

Unattaching a transport socket from a multiplexor is straightforward. An "unattach" ioctl is done with the kcm_unattach structure as the argument:



```text
/* From linux/kcm.h */
struct kcm_unattach {
      int fd;
};

struct kcm_unattach info;

memset(&info, 0, sizeof(info));

info.fd = cfd;

ioctl(fd, SIOCKCMUNATTACH, &info);
```

<a id="rst-disabling-receive-on-kcm-socket"></a>

### Disabling receive on KCM socket

A setsockopt is used to disable or enable receiving on a KCM socket. When receive is disabled, any pending messages in the socket's receive buffer are moved to other sockets. This feature is useful if an application thread knows that it will be doing a lot of work on a request and won't be able to service new messages for a while. Example use:



```text
int val = 1;

setsockopt(kcmfd, SOL_KCM, KCM_RECV_DISABLE, &val, sizeof(val))
```

<a id="rst-bpf-programs-for-message-delineation"></a>

### BPF programs for message delineation

BPF programs can be compiled using the BPF LLVM backend. For example, the BPF program for parsing Thrift is:



```text
#include "bpf.h" /* for __sk_buff */
#include "bpf_helpers.h" /* for load_word intrinsic */

SEC("socket_kcm")
int bpf_prog1(struct __sk_buff *skb)
{
     return load_word(skb, 0) + 4;
}

char _license[] SEC("license") = "GPL";
```

<a id="rst-use-in-applications"></a>

## Use in applications

KCM accelerates application layer protocols. Specifically, it allows applications to use a message based interface for sending and receiving messages. The kernel provides necessary assurances that messages are sent and received atomically. This relieves much of the burden applications have in mapping a message based protocol onto the TCP stream. KCM also make application layer messages a unit of work in the kernel for the purposes of steering and scheduling, which in turn allows a simpler networking model in multithreaded applications.

<a id="rst-configurations"></a>

### Configurations

In an Nx1 configuration, KCM logically provides multiple socket handles to the same TCP connection. This allows parallelism between in I/O operations on the TCP socket (for instance copyin and copyout of data is parallelized). In an application, a KCM socket can be opened for each processing thread and inserted into the epoll (similar to how SO_REUSEPORT is used to allow multiple listener sockets on the same port).

In a MxN configuration, multiple connections are established to the same destination. These are used for simple load balancing.

<a id="rst-message-batching"></a>

### Message batching

The primary purpose of KCM is load balancing between KCM sockets and hence threads in a nominal use case. Perfect load balancing, that is steering each received message to a different KCM socket or steering each sent message to a different TCP socket, can negatively impact performance since this doesn't allow for affinities to be established. Balancing based on groups, or batches of messages, can be beneficial for performance.

On transmit, there are three ways an application can batch (pipeline) messages on a KCM socket.

> 1. Send multiple messages in a single sendmmsg.
>
> 2. Send a group of messages each with a sendmsg call, where all messages except the last have MSG_BATCH in the flags of sendmsg call.
>
> 3. Create "super message" composed of multiple messages and send this with a single sendmsg.

On receive, the KCM module attempts to queue messages received on the same KCM socket during each TCP ready callback. The targeted KCM socket changes at each receive ready callback on the KCM socket. The application does not need to configure this.

<a id="rst-error-handling"></a>

### Error handling

An application should include a thread to monitor errors raised on the TCP connection. Normally, this will be done by placing each TCP socket attached to a KCM multiplexor in epoll set for POLLERR event. If an error occurs on an attached TCP socket, KCM sets an EPIPE on the socket thus waking up the application thread. When the application sees the error (which may just be a disconnect) it should unattach the socket from KCM and then close it. It is assumed that once an error is posted on the TCP socket the data stream is unrecoverable (i.e. an error may have occurred in the middle of receiving a message).

<a id="rst-tcp-connection-monitoring"></a>

### TCP connection monitoring

In KCM there is no means to correlate a message to the TCP socket that was used to send or receive the message (except in the case there is only one attached TCP socket). However, the application does retain an open file descriptor to the socket so it will be able to get statistics from the socket which can be used in detecting issues (such as high retransmissions on the socket).

---

# L2TP

_Peios Kernel / Internals / Networking_

> Layer 2 Tunneling Protocol (L2TP) allows L2 frames to be tunneled over an IP network.

<a id="rst-l2tp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Layer 2 Tunneling Protocol (L2TP) allows L2 frames to be tunneled over an IP network.

This document covers the kernel's L2TP subsystem. It documents kernel APIs for application developers who want to use the L2TP subsystem and it provides some technical details about the internal implementation which may be useful to kernel developers and maintainers.

<a id="rst-overview"></a>

## Overview

The kernel's L2TP subsystem implements the datapath for L2TPv2 and L2TPv3. L2TPv2 is carried over UDP. L2TPv3 is carried over UDP or directly over IP (protocol 115).

The L2TP RFCs define two basic kinds of L2TP packets: control packets (the "control plane"), and data packets (the "data plane"). The kernel deals only with data packets. The more complex control packets are handled by user space.

An L2TP tunnel carries one or more L2TP sessions. Each tunnel is associated with a socket. Each session is associated with a virtual netdevice, e.g. `pppN`, `l2tpethN`, through which data frames pass to/from L2TP. Fields in the L2TP header identify the tunnel or session and whether it is a control or data packet. When tunnels and sessions are set up using the Linux kernel API, we're just setting up the L2TP data path. All aspects of the control protocol are to be handled by user space.

This split in responsibilities leads to a natural sequence of operations when establishing tunnels and sessions. The procedure looks like this:

> 1. Create a tunnel socket. Exchange L2TP control protocol messages with the peer over that socket in order to establish a tunnel.
>
> 2. Create a tunnel context in the kernel, using information obtained from the peer using the control protocol messages.
>
> 3. Exchange L2TP control protocol messages with the peer over the tunnel socket in order to establish a session.
>
> 4. Create a session context in the kernel using information obtained from the peer using the control protocol messages.

<a id="rst-l2tp-apis"></a>

## L2TP APIs

This section documents each userspace API of the L2TP subsystem.

<a id="rst-tunnel-sockets"></a>

### Tunnel Sockets

L2TPv2 always uses UDP. L2TPv3 may use UDP or IP encapsulation.

To create a tunnel socket for use by L2TP, the standard POSIX socket API is used.

For example, for a tunnel using IPv4 addresses and UDP encapsulation:



```text
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
```

Or for a tunnel using IPv6 addresses and IP encapsulation:



```text
int sockfd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_L2TP);
```

UDP socket programming doesn't need to be covered here.

IPPROTO\_L2TP is an IP protocol type implemented by the kernel's L2TP subsystem. The L2TPIP socket address is defined in struct sockaddr\_l2tpip and struct sockaddr\_l2tpip6 at [include/uapi/linux/l2tp.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/l2tp.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>). The address includes the L2TP tunnel (connection) id. To use L2TP IP encapsulation, an L2TPv3 application should bind the L2TPIP socket using the locally assigned tunnel id. When the peer's tunnel id and IP address is known, a connect must be done.

If the L2TP application needs to handle L2TPv3 tunnel setup requests from peers using L2TPIP, it must open a dedicated L2TPIP socket to listen for those requests and bind the socket using tunnel id 0 since tunnel setup requests are addressed to tunnel id 0.

An L2TP tunnel and all of its sessions are automatically closed when its tunnel socket is closed.

<a id="rst-netlink-api"></a>

### Netlink API

L2TP applications use netlink to manage L2TP tunnel and session instances in the kernel. The L2TP netlink API is defined in [include/uapi/linux/l2tp.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/l2tp.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

L2TP uses [Generic Netlink](</kernel/internals/networking/generic-netlink.md>) (GENL). Several commands are defined: Create, Delete, Modify and Get for tunnel and session instances, e.g. `L2TP_CMD_TUNNEL_CREATE`. The API header lists the netlink attribute types that can be used with each command.

Tunnel and session instances are identified by a locally unique 32-bit id.  L2TP tunnel ids are given by `L2TP_ATTR_CONN_ID` and `L2TP_ATTR_PEER_CONN_ID` attributes and L2TP session ids are given by `L2TP_ATTR_SESSION_ID` and `L2TP_ATTR_PEER_SESSION_ID` attributes. If netlink is used to manage L2TPv2 tunnel and session instances, the L2TPv2 16-bit tunnel/session id is cast to a 32-bit value in these attributes.

In the `L2TP_CMD_TUNNEL_CREATE` command, `L2TP_ATTR_FD` tells the kernel the tunnel socket fd being used. If not specified, the kernel creates a kernel socket for the tunnel, using IP parameters set in `L2TP_ATTR_IP[6]_SADDR`, `L2TP_ATTR_IP[6]_DADDR`, `L2TP_ATTR_UDP_SPORT`, `L2TP_ATTR_UDP_DPORT` attributes. Kernel sockets are used to implement unmanaged L2TPv3 tunnels (iproute2's "ip l2tp" commands). If `L2TP_ATTR_FD` is given, it must be a socket fd that is already bound and connected. There is more information about unmanaged tunnels later in this document.

`L2TP_CMD_TUNNEL_CREATE` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



Sets the tunnel (connection) id.

</td>
</tr>
<tr>
<td>



PEER\_CONN\_ID

</td>
<td>



Y

</td>
<td>



Sets the peer tunnel (connection) id.

</td>
</tr>
<tr>
<td>



PROTO\_VERSION

</td>
<td>



Y

</td>
<td>



Protocol version. 2 or 3.

</td>
</tr>
<tr>
<td>



ENCAP\_TYPE

</td>
<td>



Y

</td>
<td>



Encapsulation type: UDP or IP.

</td>
</tr>
<tr>
<td>



FD

</td>
<td>



N

</td>
<td>



Tunnel socket file descriptor.

</td>
</tr>
<tr>
<td>



UDP\_CSUM

</td>
<td>



N

</td>
<td>



Enable IPv4 UDP checksums. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



UDP\_ZERO\_CSUM6\_TX

</td>
<td>



N

</td>
<td>



Zero IPv6 UDP checksum on transmit. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



UDP\_ZERO\_CSUM6\_RX

</td>
<td>



N

</td>
<td>



Zero IPv6 UDP checksum on receive. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



IP\_SADDR

</td>
<td>



N

</td>
<td>



IPv4 source address. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



IP\_DADDR

</td>
<td>



N

</td>
<td>



IPv4 destination address. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



UDP\_SPORT

</td>
<td>



N

</td>
<td>



UDP source port. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



UDP\_DPORT

</td>
<td>



N

</td>
<td>



UDP destination port. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



IP6\_SADDR

</td>
<td>



N

</td>
<td>



IPv6 source address. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



IP6\_DADDR

</td>
<td>



N

</td>
<td>



IPv6 destination address. Used only if FD is not set.

</td>
</tr>
<tr>
<td>



DEBUG

</td>
<td>



N

</td>
<td>



Debug flags.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_TUNNEL_DESTROY` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



Identifies the tunnel id to be destroyed.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_TUNNEL_MODIFY` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



Identifies the tunnel id to be modified.

</td>
</tr>
<tr>
<td>



DEBUG

</td>
<td>



N

</td>
<td>



Debug flags.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_TUNNEL_GET` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



N

</td>
<td>



Identifies the tunnel id to be queried. Ignored in DUMP requests.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_SESSION_CREATE` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



The parent tunnel id.

</td>
</tr>
<tr>
<td>



SESSION\_ID

</td>
<td>



Y

</td>
<td>



Sets the session id.

</td>
</tr>
<tr>
<td>



PEER\_SESSION\_ID

</td>
<td>



Y

</td>
<td>



Sets the parent session id.

</td>
</tr>
<tr>
<td>



PW\_TYPE

</td>
<td>



Y

</td>
<td>



Sets the pseudowire type.

</td>
</tr>
<tr>
<td>



DEBUG

</td>
<td>



N

</td>
<td>



Debug flags.

</td>
</tr>
<tr>
<td>



RECV\_SEQ

</td>
<td>



N

</td>
<td>



Enable rx data sequence numbers.

</td>
</tr>
<tr>
<td>



SEND\_SEQ

</td>
<td>



N

</td>
<td>



Enable tx data sequence numbers.

</td>
</tr>
<tr>
<td>



LNS\_MODE

</td>
<td>



N

</td>
<td>



Enable LNS mode (auto-enable data sequence numbers).

</td>
</tr>
<tr>
<td>



RECV\_TIMEOUT

</td>
<td>



N

</td>
<td>



Timeout to wait when reordering received packets.

</td>
</tr>
<tr>
<td>



L2SPEC\_TYPE

</td>
<td>



N

</td>
<td>



Sets layer2-specific-sublayer type (L2TPv3 only).

</td>
</tr>
<tr>
<td>



COOKIE

</td>
<td>



N

</td>
<td>



Sets optional cookie (L2TPv3 only).

</td>
</tr>
<tr>
<td>



PEER\_COOKIE

</td>
<td>



N

</td>
<td>



Sets optional peer cookie (L2TPv3 only).

</td>
</tr>
<tr>
<td>



IFNAME

</td>
<td>



N

</td>
<td>



Sets interface name (L2TPv3 only).

</td>
</tr>
</tbody>
</table>

For Ethernet session types, this will create an l2tpeth virtual interface which can then be configured as required. For PPP session types, a PPPoL2TP socket must also be opened and connected, mapping it onto the new session. This is covered in "PPPoL2TP Sockets" later.

`L2TP_CMD_SESSION_DESTROY` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



Identifies the parent tunnel id of the session to be destroyed.

</td>
</tr>
<tr>
<td>



SESSION\_ID

</td>
<td>



Y

</td>
<td>



Identifies the session id to be destroyed.

</td>
</tr>
<tr>
<td>



IFNAME

</td>
<td>



N

</td>
<td>



Identifies the session by interface name. If set, this overrides any CONN\_ID and SESSION\_ID attributes. Currently supported for L2TPv3 Ethernet sessions only.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_SESSION_MODIFY` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



Y

</td>
<td>



Identifies the parent tunnel id of the session to be modified.

</td>
</tr>
<tr>
<td>



SESSION\_ID

</td>
<td>



Y

</td>
<td>



Identifies the session id to be modified.

</td>
</tr>
<tr>
<td>



IFNAME

</td>
<td>



N

</td>
<td>



Identifies the session by interface name. If set, this overrides any CONN\_ID and SESSION\_ID attributes. Currently supported for L2TPv3 Ethernet sessions only.

</td>
</tr>
<tr>
<td>



DEBUG

</td>
<td>



N

</td>
<td>



Debug flags.

</td>
</tr>
<tr>
<td>



RECV\_SEQ

</td>
<td>



N

</td>
<td>



Enable rx data sequence numbers.

</td>
</tr>
<tr>
<td>



SEND\_SEQ

</td>
<td>



N

</td>
<td>



Enable tx data sequence numbers.

</td>
</tr>
<tr>
<td>



LNS\_MODE

</td>
<td>



N

</td>
<td>



Enable LNS mode (auto-enable data sequence numbers).

</td>
</tr>
<tr>
<td>



RECV\_TIMEOUT

</td>
<td>



N

</td>
<td>



Timeout to wait when reordering received packets.

</td>
</tr>
</tbody>
</table>

`L2TP_CMD_SESSION_GET` attributes:-


<table>
<thead>
<tr>
<th>



Attribute

</th>
<th>



Required

</th>
<th>



Use

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



CONN\_ID

</td>
<td>



N

</td>
<td>



Identifies the tunnel id to be queried. Ignored for DUMP requests.

</td>
</tr>
<tr>
<td>



SESSION\_ID

</td>
<td>



N

</td>
<td>



Identifies the session id to be queried. Ignored for DUMP requests.

</td>
</tr>
<tr>
<td>



IFNAME

</td>
<td>



N

</td>
<td>



Identifies the session by interface name. If set, this overrides any CONN\_ID and SESSION\_ID attributes. Ignored for DUMP requests. Currently supported for L2TPv3 Ethernet sessions only.

</td>
</tr>
</tbody>
</table>

Application developers should refer to [include/uapi/linux/l2tp.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/l2tp.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) for netlink command and attribute definitions.

Sample userspace code using [libmnl](<https://www.netfilter.org/projects/libmnl>):

> - Open L2TP netlink socket:
>
>
>
>   ```text
>   struct nl_sock *nl_sock;
>   int l2tp_nl_family_id;
>
>   nl_sock = nl_socket_alloc();
>   genl_connect(nl_sock);
>   genl_id = genl_ctrl_resolve(nl_sock, L2TP_GENL_NAME);
>   ```
>
> - Create a tunnel:
>
>
>
>   ```text
>   struct nlmsghdr *nlh;
>   struct genlmsghdr *gnlh;
>
>   nlh = mnl_nlmsg_put_header(buf);
>   nlh->nlmsg_type = genl_id; /* assigned to genl socket */
>   nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
>   nlh->nlmsg_seq = seq;
>
>   gnlh = mnl_nlmsg_put_extra_header(nlh, sizeof(*gnlh));
>   gnlh->cmd = L2TP_CMD_TUNNEL_CREATE;
>   gnlh->version = L2TP_GENL_VERSION;
>   gnlh->reserved = 0;
>
>   mnl_attr_put_u32(nlh, L2TP_ATTR_FD, tunl_sock_fd);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_CONN_ID, tid);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_PEER_CONN_ID, peer_tid);
>   mnl_attr_put_u8(nlh, L2TP_ATTR_PROTO_VERSION, protocol_version);
>   mnl_attr_put_u16(nlh, L2TP_ATTR_ENCAP_TYPE, encap);
>   ```
>
> - Create a session:
>
>
>
>   ```text
>   struct nlmsghdr *nlh;
>   struct genlmsghdr *gnlh;
>
>   nlh = mnl_nlmsg_put_header(buf);
>   nlh->nlmsg_type = genl_id; /* assigned to genl socket */
>   nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
>   nlh->nlmsg_seq = seq;
>
>   gnlh = mnl_nlmsg_put_extra_header(nlh, sizeof(*gnlh));
>   gnlh->cmd = L2TP_CMD_SESSION_CREATE;
>   gnlh->version = L2TP_GENL_VERSION;
>   gnlh->reserved = 0;
>
>   mnl_attr_put_u32(nlh, L2TP_ATTR_CONN_ID, tid);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_PEER_CONN_ID, peer_tid);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_SESSION_ID, sid);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_PEER_SESSION_ID, peer_sid);
>   mnl_attr_put_u16(nlh, L2TP_ATTR_PW_TYPE, pwtype);
>   /* there are other session options which can be set using netlink
>    * attributes during session creation -- see l2tp.h
>    */
>   ```
>
> - Delete a session:
>
>
>
>   ```text
>   struct nlmsghdr *nlh;
>   struct genlmsghdr *gnlh;
>
>   nlh = mnl_nlmsg_put_header(buf);
>   nlh->nlmsg_type = genl_id; /* assigned to genl socket */
>   nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
>   nlh->nlmsg_seq = seq;
>
>   gnlh = mnl_nlmsg_put_extra_header(nlh, sizeof(*gnlh));
>   gnlh->cmd = L2TP_CMD_SESSION_DELETE;
>   gnlh->version = L2TP_GENL_VERSION;
>   gnlh->reserved = 0;
>
>   mnl_attr_put_u32(nlh, L2TP_ATTR_CONN_ID, tid);
>   mnl_attr_put_u32(nlh, L2TP_ATTR_SESSION_ID, sid);
>   ```
>
> - Delete a tunnel and all of its sessions (if any):
>
>
>
>   ```text
>   struct nlmsghdr *nlh;
>   struct genlmsghdr *gnlh;
>
>   nlh = mnl_nlmsg_put_header(buf);
>   nlh->nlmsg_type = genl_id; /* assigned to genl socket */
>   nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
>   nlh->nlmsg_seq = seq;
>
>   gnlh = mnl_nlmsg_put_extra_header(nlh, sizeof(*gnlh));
>   gnlh->cmd = L2TP_CMD_TUNNEL_DELETE;
>   gnlh->version = L2TP_GENL_VERSION;
>   gnlh->reserved = 0;
>
>   mnl_attr_put_u32(nlh, L2TP_ATTR_CONN_ID, tid);
>   ```

<a id="rst-pppol2tp-session-socket-api"></a>

### PPPoL2TP Session Socket API

For PPP session types, a PPPoL2TP socket must be opened and connected to the L2TP session.

When creating PPPoL2TP sockets, the application provides information to the kernel about the tunnel and session in a socket connect() call. Source and destination tunnel and session ids are provided, as well as the file descriptor of a UDP or L2TPIP socket. See struct pppol2tp\_addr in [include/linux/if\_pppol2tp.h](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/include/uapi/linux/if_pppol2tp.h?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>). For historical reasons, there are unfortunately slightly different address structures for L2TPv2/L2TPv3 IPv4/IPv6 tunnels and userspace must use the appropriate structure that matches the tunnel socket type.

Userspace may control behavior of the tunnel or session using setsockopt and ioctl on the PPPoX socket. The following socket options are supported:-


<table>
<tbody>
<tr>
<td>



DEBUG

</td>
<td>



bitmask of debug message categories. See below.

</td>
</tr>
<tr>
<td>



SENDSEQ

</td>
<td>



- 0 =&gt; don't send packets with sequence numbers

- 1 =&gt; send packets with sequence numbers

</td>
</tr>
<tr>
<td>



RECVSEQ

</td>
<td>



- 0 =&gt; receive packet sequence numbers are optional

- 1 =&gt; drop receive packets without sequence numbers

</td>
</tr>
<tr>
<td>



LNSMODE

</td>
<td>



- 0 =&gt; act as LAC.

- 1 =&gt; act as LNS.

</td>
</tr>
<tr>
<td>



REORDERTO

</td>
<td>



reorder timeout (in millisecs). If 0, don't try to reorder.

</td>
</tr>
</tbody>
</table>

In addition to the standard PPP ioctls, a PPPIOCGL2TPSTATS is provided to retrieve tunnel and session statistics from the kernel using the PPPoX socket of the appropriate tunnel or session.

Sample userspace code:

> - Create session PPPoX data socket:
>
>
>
>   ```text
>   /* Input: the L2TP tunnel UDP socket `tunnel_fd`, which needs to be
>    * bound already (both sockname and peername), otherwise it will not be
>    * ready.
>    */
>
>   struct sockaddr_pppol2tp sax;
>   int session_fd;
>   int ret;
>
>   session_fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
>   if (session_fd < 0)
>           return -errno;
>
>   sax.sa_family = AF_PPPOX;
>   sax.sa_protocol = PX_PROTO_OL2TP;
>   sax.pppol2tp.fd = tunnel_fd;
>   sax.pppol2tp.addr.sin_addr.s_addr = addr->sin_addr.s_addr;
>   sax.pppol2tp.addr.sin_port = addr->sin_port;
>   sax.pppol2tp.addr.sin_family = AF_INET;
>   sax.pppol2tp.s_tunnel  = tunnel_id;
>   sax.pppol2tp.s_session = session_id;
>   sax.pppol2tp.d_tunnel  = peer_tunnel_id;
>   sax.pppol2tp.d_session = peer_session_id;
>
>   /* session_fd is the fd of the session's PPPoL2TP socket.
>    * tunnel_fd is the fd of the tunnel UDP / L2TPIP socket.
>    */
>   ret = connect(session_fd, (struct sockaddr *)&sax, sizeof(sax));
>   if (ret < 0 ) {
>           close(session_fd);
>           return -errno;
>   }
>
>   return session_fd;
>   ```

L2TP control packets will still be available for read on `tunnel_fd`.

> - Create PPP channel:
>
>
>
>   ```text
>   /* Input: the session PPPoX data socket `session_fd` which was created
>    * as described above.
>    */
>
>   int ppp_chan_fd;
>   int chindx;
>   int ret;
>
>   ret = ioctl(session_fd, PPPIOCGCHAN, &chindx);
>   if (ret < 0)
>           return -errno;
>
>   ppp_chan_fd = open("/dev/ppp", O_RDWR);
>   if (ppp_chan_fd < 0)
>           return -errno;
>
>   ret = ioctl(ppp_chan_fd, PPPIOCATTCHAN, &chindx);
>   if (ret < 0) {
>           close(ppp_chan_fd);
>           return -errno;
>   }
>
>   return ppp_chan_fd;
>   ```

LCP PPP frames will be available for read on `ppp_chan_fd`.

> - Create PPP interface:
>
>
>
>   ```text
>   /* Input: the PPP channel `ppp_chan_fd` which was created as described
>    * above.
>    */
>
>   int ifunit = -1;
>   int ppp_if_fd;
>   int ret;
>
>   ppp_if_fd = open("/dev/ppp", O_RDWR);
>   if (ppp_if_fd < 0)
>           return -errno;
>
>   ret = ioctl(ppp_if_fd, PPPIOCNEWUNIT, &ifunit);
>   if (ret < 0) {
>           close(ppp_if_fd);
>           return -errno;
>   }
>
>   ret = ioctl(ppp_chan_fd, PPPIOCCONNECT, &ifunit);
>   if (ret < 0) {
>           close(ppp_if_fd);
>           return -errno;
>   }
>
>   return ppp_if_fd;
>   ```

IPCP/IPv6CP PPP frames will be available for read on `ppp_if_fd`.

The ppp&lt;ifunit&gt; interface can then be configured as usual with netlink's RTM\_NEWLINK, RTM\_NEWADDR, RTM\_NEWROUTE, or ioctl's SIOCSIFMTU, SIOCSIFADDR, SIOCSIFDSTADDR, SIOCSIFNETMASK, SIOCSIFFLAGS, or with the `ip` command.

> - Bridging L2TP sessions which have PPP pseudowire types (this is also called L2TP tunnel switching or L2TP multihop) is supported by bridging the PPP channels of the two L2TP sessions to be bridged:
>
>
>
>   ```text
>   /* Input: the session PPPoX data sockets `session_fd1` and `session_fd2`
>    * which were created as described further above.
>    */
>
>   int ppp_chan_fd;
>   int chindx1;
>   int chindx2;
>   int ret;
>
>   ret = ioctl(session_fd1, PPPIOCGCHAN, &chindx1);
>   if (ret < 0)
>           return -errno;
>
>   ret = ioctl(session_fd2, PPPIOCGCHAN, &chindx2);
>   if (ret < 0)
>           return -errno;
>
>   ppp_chan_fd = open("/dev/ppp", O_RDWR);
>   if (ppp_chan_fd < 0)
>           return -errno;
>
>   ret = ioctl(ppp_chan_fd, PPPIOCATTCHAN, &chindx1);
>   if (ret < 0) {
>           close(ppp_chan_fd);
>           return -errno;
>   }
>
>   ret = ioctl(ppp_chan_fd, PPPIOCBRIDGECHAN, &chindx2);
>   close(ppp_chan_fd);
>   if (ret < 0)
>           return -errno;
>
>   return 0;
>   ```

It can be noted that when bridging PPP channels, the PPP session is not locally terminated, and no local PPP interface is created.  PPP frames arriving on one channel are directly passed to the other channel, and vice versa.

The PPP channel does not need to be kept open.  Only the session PPPoX data sockets need to be kept open.

More generally, it is also possible in the same way to e.g. bridge a PPPoL2TP PPP channel with other types of PPP channels, such as PPPoE.

See more details for the PPP side in [ppp\_generic.rst](/kernel/internals/networking/ppp-generic.md).

<a id="rst-old-l2tpv2-only-api"></a>

### Old L2TPv2-only API

When L2TP was first added to the Linux kernel in 2.6.23, it implemented only L2TPv2 and did not include a netlink API. Instead, tunnel and session instances in the kernel were managed directly using only PPPoL2TP sockets. The PPPoL2TP socket is used as described in section "PPPoL2TP Session Socket API" but tunnel and session instances are automatically created on a connect() of the socket instead of being created by a separate netlink request:

> - Tunnels are managed using a tunnel management socket which is a dedicated PPPoL2TP socket, connected to (invalid) session id 0. The L2TP tunnel instance is created when the PPPoL2TP tunnel management socket is connected and is destroyed when the socket is closed.
>
> - Session instances are created in the kernel when a PPPoL2TP socket is connected to a non-zero session id. Session parameters are set using setsockopt. The L2TP session instance is destroyed when the socket is closed.

This API is still supported but its use is discouraged. Instead, new L2TPv2 applications should use netlink to first create the tunnel and session, then create a PPPoL2TP socket for the session.

<a id="rst-unmanaged-l2tpv3-tunnels"></a>

### Unmanaged L2TPv3 tunnels

The kernel L2TP subsystem also supports static (unmanaged) L2TPv3 tunnels. Unmanaged tunnels have no userspace tunnel socket, and exchange no control messages with the peer to set up the tunnel; the tunnel is configured manually at each end of the tunnel. All configuration is done using netlink. There is no need for an L2TP userspace application in this case -- the tunnel socket is created by the kernel and configured using parameters sent in the `L2TP_CMD_TUNNEL_CREATE` netlink request. The `ip` utility of `iproute2` has commands for managing static L2TPv3 tunnels; do `ip l2tp help` for more information.

<a id="rst-debugging"></a>

### Debugging

The L2TP subsystem offers a range of debugging interfaces through the debugfs filesystem.

To access these interfaces, the debugfs filesystem must first be mounted:



```text
# mount -t debugfs debugfs /debug
```

Files under the l2tp directory can then be accessed, providing a summary of the current population of tunnel and session contexts existing in the kernel:



```text
# cat /debug/l2tp/tunnels
```

The debugfs files should not be used by applications to obtain L2TP state information because the file format is subject to change. It is implemented to provide extra debug information to help diagnose problems. Applications should instead use the netlink API.

In addition the L2TP subsystem implements tracepoints using the standard kernel event tracing API.  The available L2TP events can be reviewed as follows:



```text
# find /debug/tracing/events/l2tp
```

Finally, /proc/net/pppol2tp is also provided for backwards compatibility with the original pppol2tp code. It lists information about L2TPv2 tunnels and sessions only. Its use is discouraged.

<a id="rst-internal-implementation"></a>

## Internal Implementation

This section is for kernel developers and maintainers.

<a id="rst-sockets"></a>

### Sockets

UDP sockets are implemented by the networking core. When an L2TP tunnel is created using a UDP socket, the socket is set up as an encapsulated UDP socket by setting encap\_rcv and encap\_destroy callbacks on the UDP socket. l2tp\_udp\_encap\_recv is called when packets are received on the socket. l2tp\_udp\_encap\_destroy is called when userspace closes the socket.

L2TPIP sockets are implemented in [net/l2tp/l2tp\_ip.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/l2tp/l2tp_ip.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) and [net/l2tp/l2tp\_ip6.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/l2tp/l2tp_ip6.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

<a id="rst-tunnels"></a>

### Tunnels

The kernel keeps a struct l2tp\_tunnel context per L2TP tunnel. The l2tp\_tunnel is always associated with a UDP or L2TP/IP socket and keeps a list of sessions in the tunnel. When a tunnel is first registered with L2TP core, the reference count on the socket is increased. This ensures that the socket cannot be removed while L2TP's data structures reference it.

Tunnels are identified by a unique tunnel id. The id is 16-bit for L2TPv2 and 32-bit for L2TPv3. Internally, the id is stored as a 32-bit value.

Tunnels are kept in a per-net list, indexed by tunnel id. The tunnel id namespace is shared by L2TPv2 and L2TPv3.

Handling tunnel socket close is perhaps the most tricky part of the L2TP implementation. If userspace closes a tunnel socket, the L2TP tunnel and all of its sessions must be closed and destroyed. Since the tunnel context holds a ref on the tunnel socket, the socket's sk\_destruct won't be called until the tunnel sock\_put's its socket. For UDP sockets, when userspace closes the tunnel socket, the socket's encap\_destroy handler is invoked, which L2TP uses to initiate its tunnel close actions. For L2TPIP sockets, the socket's close handler initiates the same tunnel close actions. All sessions are first closed. Each session drops its tunnel ref. When the tunnel ref reaches zero, the tunnel drops its socket ref.

<a id="rst-sessions"></a>

### Sessions

The kernel keeps a struct l2tp\_session context for each session.  Each session has private data which is used for data specific to the session type. With L2TPv2, the session always carries PPP traffic. With L2TPv3, the session can carry Ethernet frames (Ethernet pseudowire) or other data types such as PPP, ATM, HDLC or Frame Relay. Linux currently implements only Ethernet and PPP session types.

Some L2TP session types also have a socket (PPP pseudowires) while others do not (Ethernet pseudowires).

Like tunnels, L2TP sessions are identified by a unique session id. Just as with tunnel ids, the session id is 16-bit for L2TPv2 and 32-bit for L2TPv3. Internally, the id is stored as a 32-bit value.

Sessions hold a ref on their parent tunnel to ensure that the tunnel stays extant while one or more sessions references it.

Sessions are kept in a per-net list. L2TPv2 sessions and L2TPv3 sessions are stored in separate lists. L2TPv2 sessions are keyed by a 32-bit key made up of the 16-bit tunnel ID and 16-bit session ID. L2TPv3 sessions are keyed by the 32-bit session ID, since L2TPv3 session ids are unique across all tunnels.

Although the L2TPv3 RFC specifies that L2TPv3 session ids are not scoped by the tunnel, the Linux implementation has historically allowed this. Such session id collisions are supported using a per-net hash table keyed by sk and session ID. When looking up L2TPv3 sessions, the list entry may link to multiple sessions with that session ID, in which case the session matching the given sk (tunnel) is used.

<a id="rst-ppp"></a>

### PPP

[net/l2tp/l2tp\_ppp.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/l2tp/l2tp_ppp.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) implements the PPPoL2TP socket family. Each PPP session has a PPPoL2TP socket.

The PPPoL2TP socket's sk\_user\_data references the l2tp\_session.

Userspace sends and receives PPP packets over L2TP using a PPPoL2TP socket. Only PPP control frames pass over this socket: PPP data packets are handled entirely by the kernel, passing between the L2TP session and its associated `pppN` netdev through the PPP channel interface of the kernel PPP subsystem.

The L2TP PPP implementation handles the closing of a PPPoL2TP socket by closing its corresponding L2TP session. This is complicated because it must consider racing with netlink session create/destroy requests and pppol2tp\_connect trying to reconnect with a session that is in the process of being closed. PPP sessions hold a ref on their associated socket in order that the socket remains extants while the session references it.

<a id="rst-ethernet"></a>

### Ethernet

[net/l2tp/l2tp\_eth.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/net/l2tp/l2tp_eth.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>) implements L2TPv3 Ethernet pseudowires. It manages a netdev for each session.

L2TP Ethernet sessions are created and destroyed by netlink request, or are destroyed when the tunnel is destroyed. Unlike PPP sessions, Ethernet sessions do not have an associated socket.

<a id="rst-miscellaneous"></a>

## Miscellaneous

<a id="rst-rfcs"></a>

### RFCs

The kernel code implements the datapath features specified in the following RFCs:


<table>
<tbody>
<tr>
<td>



RFC2661

</td>
<td>



L2TPv2

</td>
<td>



[https://tools.ietf.org/html/rfc2661](<https://tools.ietf.org/html/rfc2661>)

</td>
</tr>
<tr>
<td>



RFC3931

</td>
<td>



L2TPv3

</td>
<td>



[https://tools.ietf.org/html/rfc3931](<https://tools.ietf.org/html/rfc3931>)

</td>
</tr>
<tr>
<td>



RFC4719

</td>
<td>



L2TPv3 Ethernet

</td>
<td>



[https://tools.ietf.org/html/rfc4719](<https://tools.ietf.org/html/rfc4719>)

</td>
</tr>
</tbody>
</table>

<a id="rst-implementations"></a>

### Implementations

A number of open source applications use the L2TP kernel subsystem:


<table>
<tbody>
<tr>
<td>



iproute2

</td>
<td>



[https://github.com/shemminger/iproute2](<https://github.com/shemminger/iproute2>)

</td>
</tr>
<tr>
<td>



go-l2tp

</td>
<td>



[https://github.com/katalix/go-l2tp](<https://github.com/katalix/go-l2tp>)

</td>
</tr>
<tr>
<td>



tunneldigger

</td>
<td>



[https://github.com/wlanslovenija/tunneldigger](<https://github.com/wlanslovenija/tunneldigger>)

</td>
</tr>
<tr>
<td>



xl2tpd

</td>
<td>



[https://github.com/xelerance/xl2tpd](<https://github.com/xelerance/xl2tpd>)

</td>
</tr>
</tbody>
</table>

<a id="rst-limitations"></a>

### Limitations

The current implementation has a number of limitations:

> 1. Interfacing with openvswitch is not yet implemented. It may be useful to map OVS Ethernet and VLAN ports into L2TPv3 tunnels.
>
> 2. VLAN pseudowires are implemented using an `l2tpethN` interface configured with a VLAN sub-interface. Since L2TPv3 VLAN pseudowires carry one and only one VLAN, it may be better to use a single netdevice rather than an `l2tpethN` and `l2tpethN`:M pair per VLAN session. The netlink attribute `L2TP_ATTR_VLAN_ID` was added for this, but it was never implemented.

<a id="rst-testing"></a>

### Testing

Unmanaged L2TPv3 Ethernet features are tested by the kernel's built-in selftests. See [tools/testing/selftests/net/l2tp.sh](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/net/l2tp.sh?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>).

Another test suite, [l2tp-ktest](<https://github.com/katalix/l2tp-ktest>), covers all of the L2TP APIs and tunnel/session types. This may be integrated into the kernel's built-in L2TP selftests in the future.

<!-- Links -->

<a id="rst-generic-netlink"></a>



<a id="rst-libmnl"></a>



<a id="rst-include-uapi-linux-l2tp-h"></a>



<a id="rst-include-linux-if-pppol2tp-h"></a>



<a id="rst-net-l2tp-l2tp-ip-c"></a>



<a id="rst-net-l2tp-l2tp-ip6-c"></a>



<a id="rst-net-l2tp-l2tp-ppp-c"></a>



<a id="rst-net-l2tp-l2tp-eth-c"></a>



<a id="rst-tools-testing-selftests-net-l2tp-sh"></a>



<a id="rst-l2tp-ktest"></a>

---

# The Linux LAPB Module Interface

_Peios Kernel / Internals / Networking_

> Version 1.3

<a id="rst-the-linux-lapb-module-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Version 1.3

Jonathan Naylor 29.12.96

Changed (Henner Eisen, 2000-10-29): int return value for data_indication()

The LAPB module will be a separately compiled module for use by any parts of the Linux operating system that require a LAPB service. This document defines the interfaces to, and the services provided by this module. The term module in this context does not imply that the LAPB module is a separately loadable module, although it may be. The term module is used in its more standard meaning.

The interface to the LAPB module consists of functions to the module, callbacks from the module to indicate important state changes, and structures for getting and setting information about the module.

<a id="rst-structures"></a>

## Structures

Probably the most important structure is the skbuff structure for holding received and transmitted data, however it is beyond the scope of this document.

The two LAPB specific structures are the LAPB initialisation structure and the LAPB parameter structure. These will be defined in a standard header file, &lt;linux/lapb.h&gt;. The header file &lt;net/lapb.h&gt; is internal to the LAPB module and is not for use.

<a id="rst-lapb-initialisation-structure"></a>

## LAPB Initialisation Structure

This structure is used only once, in the call to lapb_register (see below). It contains information about the device driver that requires the services of the LAPB module:



```text
struct lapb_register_struct {
        void (*connect_confirmation)(int token, int reason);
        void (*connect_indication)(int token, int reason);
        void (*disconnect_confirmation)(int token, int reason);
        void (*disconnect_indication)(int token, int reason);
        int  (*data_indication)(int token, struct sk_buff *skb);
        void (*data_transmit)(int token, struct sk_buff *skb);
};
```

Each member of this structure corresponds to a function in the device driver that is called when a particular event in the LAPB module occurs. These will be described in detail below. If a callback is not required (\!\!) then a NULL may be substituted.

<a id="rst-lapb-parameter-structure"></a>

## LAPB Parameter Structure

This structure is used with the lapb_getparms and lapb_setparms functions (see below). They are used to allow the device driver to get and set the operational parameters of the LAPB implementation for a given connection:



```text
struct lapb_parms_struct {
        unsigned int t1;
        unsigned int t1timer;
        unsigned int t2;
        unsigned int t2timer;
        unsigned int n2;
        unsigned int n2count;
        unsigned int window;
        unsigned int state;
        unsigned int mode;
};
```

T1 and T2 are protocol timing parameters and are given in units of 100ms. N2 is the maximum number of tries on the link before it is declared a failure. The window size is the maximum number of outstanding data packets allowed to be unacknowledged by the remote end, the value of the window is between 1 and 7 for a standard LAPB link, and between 1 and 127 for an extended LAPB link.

The mode variable is a bit field used for setting (at present) three values. The bit fields have the following meanings:


<table>
<thead>
<tr>
<th>


Bit

</th>
<th>


Meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


LAPB operation (0=LAPB_STANDARD 1=LAPB_EXTENDED).

</td>
</tr>
<tr>
<td>


1

</td>
<td>


\[SM\]LP operation (0=LAPB_SLP 1=LAPB=MLP).

</td>
</tr>
<tr>
<td>


2

</td>
<td>


DTE/DCE operation (0=LAPB_DTE 1=LAPB_DCE)

</td>
</tr>
<tr>
<td>


3-31

</td>
<td>


Reserved, must be 0.

</td>
</tr>
</tbody>
</table>

Extended LAPB operation indicates the use of extended sequence numbers and consequently larger window sizes, the default is standard LAPB operation. MLP operation is the same as SLP operation except that the addresses used by LAPB are different to indicate the mode of operation, the default is Single Link Procedure. The difference between DCE and DTE operation is (i) the addresses used for commands and responses, and (ii) when the DCE is not connected, it sends DM without polls set, every T1. The upper case constant names will be defined in the public LAPB header file.

<a id="rst-functions"></a>

## Functions

The LAPB module provides a number of function entry points.



```text
int lapb_register(void *token, struct lapb_register_struct);
```

This must be called before the LAPB module may be used. If the call is successful then LAPB_OK is returned. The token must be a unique identifier generated by the device driver to allow for the unique identification of the instance of the LAPB link. It is returned by the LAPB module in all of the callbacks, and is used by the device driver in all calls to the LAPB module. For multiple LAPB links in a single device driver, multiple calls to lapb_register must be made. The format of the lapb_register_struct is given above. The return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB registered successfully.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Token is already registered.

</td>
</tr>
<tr>
<td>


LAPB_NOMEM

</td>
<td>


Out of memory

</td>
</tr>
</tbody>
</table>



```text
int lapb_unregister(void *token);
```

This releases all the resources associated with a LAPB link. Any current LAPB link will be abandoned without further messages being passed. After this call, the value of token is no longer valid for any calls to the LAPB function. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB unregistered successfully.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
</tbody>
</table>



```text
int lapb_getparms(void *token, struct lapb_parms_struct *parms);
```

This allows the device driver to get the values of the current LAPB variables, the lapb_parms_struct is described above. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB getparms was successful.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
</tbody>
</table>



```text
int lapb_setparms(void *token, struct lapb_parms_struct *parms);
```

This allows the device driver to set the values of the current LAPB variables, the lapb_parms_struct is described above. The values of t1timer, t2timer and n2count are ignored, likewise changing the mode bits when connected will be ignored. An error implies that none of the values have been changed. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB getparms was successful.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
<tr>
<td>


LAPB_INVALUE

</td>
<td>


One of the values was out of its allowable range.

</td>
</tr>
</tbody>
</table>



```text
int lapb_connect_request(void *token);
```

Initiate a connect using the current parameter settings. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB is starting to connect.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
<tr>
<td>


LAPB_CONNECTED

</td>
<td>


LAPB module is already connected.

</td>
</tr>
</tbody>
</table>



```text
int lapb_disconnect_request(void *token);
```

Initiate a disconnect. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB is starting to disconnect.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
<tr>
<td>


LAPB_NOTCONNECTED

</td>
<td>


LAPB module is not connected.

</td>
</tr>
</tbody>
</table>



```text
int lapb_data_request(void *token, struct sk_buff *skb);
```

Queue data with the LAPB module for transmitting over the link. If the call is successful then the skbuff is owned by the LAPB module and may not be used by the device driver again. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB has accepted the data.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
<tr>
<td>


LAPB_NOTCONNECTED

</td>
<td>


LAPB module is not connected.

</td>
</tr>
</tbody>
</table>



```text
int lapb_data_received(void *token, struct sk_buff *skb);
```

Queue data with the LAPB module which has been received from the device. It is expected that the data passed to the LAPB module has skb-&gt;data pointing to the beginning of the LAPB data. If the call is successful then the skbuff is owned by the LAPB module and may not be used by the device driver again. The valid return values are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


LAPB has accepted the data.

</td>
</tr>
<tr>
<td>


LAPB_BADTOKEN

</td>
<td>


Invalid/unknown LAPB token.

</td>
</tr>
</tbody>
</table>

<a id="rst-callbacks"></a>

## Callbacks

These callbacks are functions provided by the device driver for the LAPB module to call when an event occurs. They are registered with the LAPB module with lapb_register (see above) in the structure lapb_register_struct (see above).



```text
void (*connect_confirmation)(void *token, int reason);
```

This is called by the LAPB module when a connection is established after being requested by a call to lapb_connect_request (see above). The reason is always LAPB_OK.



```text
void (*connect_indication)(void *token, int reason);
```

This is called by the LAPB module when the link is established by the remote system. The value of reason is always LAPB_OK.



```text
void (*disconnect_confirmation)(void *token, int reason);
```

This is called by the LAPB module when an event occurs after the device driver has called lapb_disconnect_request (see above). The reason indicates what has happened. In all cases the LAPB link can be regarded as being terminated. The values for reason are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


The LAPB link was terminated normally.

</td>
</tr>
<tr>
<td>


LAPB_NOTCONNECTED

</td>
<td>


The remote system was not connected.

</td>
</tr>
<tr>
<td>


LAPB_TIMEDOUT

</td>
<td>


No response was received in N2 tries from the remote system.

</td>
</tr>
</tbody>
</table>



```text
void (*disconnect_indication)(void *token, int reason);
```

This is called by the LAPB module when the link is terminated by the remote system or another event has occurred to terminate the link. This may be returned in response to a lapb_connect_request (see above) if the remote system refused the request. The values for reason are:


<table>
<tbody>
<tr>
<td>


LAPB_OK

</td>
<td>


The LAPB link was terminated normally by the remote system.

</td>
</tr>
<tr>
<td>


LAPB_REFUSED

</td>
<td>


The remote system refused the connect request.

</td>
</tr>
<tr>
<td>


LAPB_NOTCONNECTED

</td>
<td>


The remote system was not connected.

</td>
</tr>
<tr>
<td>


LAPB_TIMEDOUT

</td>
<td>


No response was received in N2 tries from the remote system.

</td>
</tr>
</tbody>
</table>



```text
int (*data_indication)(void *token, struct sk_buff *skb);
```

This is called by the LAPB module when data has been received from the remote system that should be passed onto the next layer in the protocol stack. The skbuff becomes the property of the device driver and the LAPB module will not perform any more actions on it. The skb-&gt;data pointer will be pointing to the first byte of data after the LAPB header.

This method should return NET_RX_DROP (as defined in the header file include/linux/netdevice.h) if and only if the frame was dropped before it could be delivered to the upper layer.



```text
void (*data_transmit)(void *token, struct sk_buff *skb);
```

This is called by the LAPB module when data is to be transmitted to the remote system by the device driver. The skbuff becomes the property of the device driver and the LAPB module will not perform any more actions on it. The skb-&gt;data pointer will be pointing to the first byte of the LAPB header.

---

# How to use packet injection with mac80211

_Peios Kernel / Internals / Networking_

> mac80211 now allows arbitrary packets to be injected down any Monitor Mode interface from userland. The packet you inject needs to be composed in the following format:

<a id="rst-how-to-use-packet-injection-with-mac80211"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

mac80211 now allows arbitrary packets to be injected down any Monitor Mode interface from userland.  The packet you inject needs to be composed in the following format:



```text
[ radiotap header  ]
[ ieee80211 header ]
[ payload ]
```

The radiotap format is discussed in ./Documentation/networking/radiotap-headers.rst.

Despite many radiotap parameters being currently defined, most only make sense to appear on received packets.  The following information is parsed from the radiotap headers and used to control injection:

> - IEEE80211_RADIOTAP_FLAGS
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_F_FCS
>
>   </td>
>   <td>
>
>
>   FCS will be removed and recalculated
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_F_WEP
>
>   </td>
>   <td>
>
>
>   frame will be encrypted if key available
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_F_FRAG
>
>   </td>
>   <td>
>
>
>   frame will be fragmented if longer than the current fragmentation threshold.
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
> - IEEE80211_RADIOTAP_TX_FLAGS
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_F_TX_NOACK
>
>   </td>
>   <td>
>
>
>   frame should be sent without waiting for an ACK even if it is a unicast frame
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
> - IEEE80211_RADIOTAP_RATE
>
>   legacy rate for the transmission (only for devices without own rate control)
>
> - IEEE80211_RADIOTAP_MCS
>
>   HT rate for the transmission (only for devices without own rate control). Also some flags are parsed
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_MCS_SGI
>
>   </td>
>   <td>
>
>
>   use short guard interval
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   IEEE80211_RADIOTAP_MCS_BW_40
>
>   </td>
>   <td>
>
>
>   send in HT40 mode
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
> - IEEE80211_RADIOTAP_DATA_RETRIES
>
>   number of retries when either IEEE80211_RADIOTAP_RATE or IEEE80211_RADIOTAP_MCS was used
>
> - IEEE80211_RADIOTAP_VHT
>
>   VHT mcs and number of streams used in the transmission (only for devices without own rate control). Also other fields are parsed
>
>   - **flags field**
>
>     IEEE80211_RADIOTAP_VHT_FLAG_SGI: use short guard interval
>
>   - **bandwidth field**
>
>     - 1: send using 40MHz channel width
>
>     - 4: send using 80MHz channel width
>
>     - 11: send using 160MHz channel width

The injection code can also skip all other currently defined radiotap fields facilitating replay of captured radiotap headers directly.

Here is an example valid radiotap header defining some parameters:



```text
0x00, 0x00, // <-- radiotap version
0x0b, 0x00, // <- radiotap header length
0x04, 0x0c, 0x00, 0x00, // <-- bitmap
0x6c, // <-- rate
0x0c, //<-- tx power
0x01 //<-- antenna
```

The ieee80211 header follows immediately afterwards, looking for example like this:



```text
0x08, 0x01, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x13, 0x22, 0x33, 0x44, 0x55, 0x66,
0x13, 0x22, 0x33, 0x44, 0x55, 0x66,
0x10, 0x86
```

Then lastly there is the payload.

After composing the packet contents, it is sent by send()-ing it to a logical mac80211 interface that is in Monitor mode.  Libpcap can also be used, (which is easier than doing the work to bind the socket to the right interface), along the following lines::



```text
ppcap = pcap_open_live(szInterfaceName, 800, 1, 20, szErrbuf);
...
r = pcap_inject(ppcap, u8aSendBuffer, nLength);
```

You can also find a link to a complete inject application here:

[https://wireless.wiki.kernel.org/en/users/Documentation/packetspammer](<https://wireless.wiki.kernel.org/en/users/Documentation/packetspammer>)

Andy Green &lt;[andy@warmcat.com](<mailto:andy@warmcat.com>)&gt;

---

# Management Component Transport Protocol (MCTP)

_Peios Kernel / Internals / Networking_

> net/mctp/ contains protocol support for MCTP, as defined by DMTF standard DSP0236. Physical interface drivers ("bindings" in the specification) are provided in drivers/net/mctp/.

<a id="rst-management-component-transport-protocol-mctp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

net/mctp/ contains protocol support for MCTP, as defined by DMTF standard DSP0236. Physical interface drivers ("bindings" in the specification) are provided in drivers/net/mctp/.

The core code provides a socket-based interface to send and receive MCTP messages, through an AF_MCTP, SOCK_DGRAM socket.

<a id="rst-structure-interfaces-networks"></a>

## Structure: interfaces &amp; networks

The kernel models the local MCTP topology through two items: interfaces and networks.

An interface (or "link") is an instance of an MCTP physical transport binding (as defined by DSP0236, section 3.2.47), likely connected to a specific hardware device. This is represented as a `struct netdevice`.

A network defines a unique address space for MCTP endpoints by endpoint-ID (described by DSP0236, section 3.2.31). A network has a user-visible identifier to allow references from userspace. Route definitions are specific to one network.

Interfaces are associated with one network. A network may be associated with one or more interfaces.

If multiple networks are present, each may contain endpoint IDs (EIDs) that are also present on other networks.

<a id="rst-sockets-api"></a>

## Sockets API

<a id="rst-protocol-definitions"></a>

### Protocol definitions

MCTP uses `AF_MCTP` / `PF_MCTP` for the address- and protocol- families. Since MCTP is message-based, only `SOCK_DGRAM` sockets are supported.



```C
int sd = socket(AF_MCTP, SOCK_DGRAM, 0);
```

The only (current) value for the `protocol` argument is 0.

As with all socket address families, source and destination addresses are specified with a `sockaddr` type, with a single-byte endpoint address:



```C
typedef __u8                mctp_eid_t;

struct mctp_addr {
        mctp_eid_t          s_addr;
};

struct sockaddr_mctp {
        __kernel_sa_family_t smctp_family;
        unsigned int         smctp_network;
        struct mctp_addr     smctp_addr;
        __u8                 smctp_type;
        __u8                 smctp_tag;
};

#define MCTP_NET_ANY        0x0
#define MCTP_ADDR_ANY       0xff
```

<a id="rst-syscall-behaviour"></a>

### Syscall behaviour

The following sections describe the MCTP-specific behaviours of the standard socket system calls. These behaviours have been chosen to map closely to the existing sockets APIs.

<a id="rst-bind-set-local-socket-address"></a>

#### `bind()` : set local socket address

Sockets that receive incoming request packets will bind to a local address, using the `bind()` syscall.



```C
struct sockaddr_mctp addr;

addr.smctp_family = AF_MCTP;
addr.smctp_network = MCTP_NET_ANY;
addr.smctp_addr.s_addr = MCTP_ADDR_ANY;
addr.smctp_type = MCTP_TYPE_PLDM;
addr.smctp_tag = MCTP_TAG_OWNER;

int rc = bind(sd, (struct sockaddr *)&addr, sizeof(addr));
```

This establishes the local address of the socket. Incoming MCTP messages that match the network, address, and message type will be received by this socket. The reference to 'incoming' is important here; a bound socket will only receive messages with the TO bit set, to indicate an incoming request message, rather than a response.

The `smctp_tag` value will configure the tags accepted from the remote side of this socket. Given the above, the only valid value is `MCTP_TAG_OWNER`, which will result in remotely "owned" tags being routed to this socket. Since `MCTP_TAG_OWNER` is set, the 3 least-significant bits of `smctp_tag` are not used; callers must set them to zero.

A `smctp_network` value of `MCTP_NET_ANY` will configure the socket to receive incoming packets from any locally-connected network. A specific network value will cause the socket to only receive incoming messages from that network.

The `smctp_addr` field specifies a local address to bind to. A value of `MCTP_ADDR_ANY` configures the socket to receive messages addressed to any local destination EID.

The `smctp_type` field specifies which message types to receive. Only the lower 7 bits of the type is matched on incoming messages (ie., the most-significant IC bit is not part of the match). This results in the socket receiving packets with and without a message integrity check footer.

<a id="rst-sendto-sendmsg-send-transmit-an-mctp-message"></a>

#### `sendto()`, `sendmsg()`, `send()` : transmit an MCTP message

An MCTP message is transmitted using one of the `sendto()`, `sendmsg()` or `send()` syscalls. Using `sendto()` as the primary example:



```C
struct sockaddr_mctp addr;
char buf[14];
ssize_t len;

/* set message destination */
addr.smctp_family = AF_MCTP;
addr.smctp_network = 0;
addr.smctp_addr.s_addr = 8;
addr.smctp_tag = MCTP_TAG_OWNER;
addr.smctp_type = MCTP_TYPE_ECHO;

/* arbitrary message to send, with message-type header */
buf[0] = MCTP_TYPE_ECHO;
memcpy(buf + 1, "hello, world!", sizeof(buf) - 1);

len = sendto(sd, buf, sizeof(buf), 0,
                (struct sockaddr_mctp *)&addr, sizeof(addr));
```

The network and address fields of `addr` define the remote address to send to. If `smctp_tag` has the `MCTP_TAG_OWNER`, the kernel will ignore any bits set in `MCTP_TAG_VALUE`, and generate a tag value suitable for the destination EID. If `MCTP_TAG_OWNER` is not set, the message will be sent with the tag value as specified. If a tag value cannot be allocated, the system call will report an errno of `EAGAIN`.

The application must provide the message type byte as the first byte of the message buffer passed to `sendto()`. If a message integrity check is to be included in the transmitted message, it must also be provided in the message buffer, and the most-significant bit of the message type byte must be 1.

The `sendmsg()` system call allows a more compact argument interface, and the message buffer to be specified as a scatter-gather list. At present no ancillary message types (used for the `msg_control` data passed to `sendmsg()`) are defined.

Transmitting a message on an unconnected socket with `MCTP_TAG_OWNER` specified will cause an allocation of a tag, if no valid tag is already allocated for that destination. The (destination-eid,tag) tuple acts as an implicit local socket address, to allow the socket to receive responses to this outgoing message. If any previous allocation has been performed (to for a different remote EID), that allocation is lost.

Sockets will only receive responses to requests they have sent (with TO=1) and may only respond (with TO=0) to requests they have received.

<a id="rst-recvfrom-recvmsg-recv-receive-an-mctp-message"></a>

#### `recvfrom()`, `recvmsg()`, `recv()` : receive an MCTP message

An MCTP message can be received by an application using one of the `recvfrom()`, `recvmsg()`, or `recv()` system calls. Using `recvfrom()` as the primary example:



```C
struct sockaddr_mctp addr;
socklen_t addrlen;
char buf[14];
ssize_t len;

addrlen = sizeof(addr);

len = recvfrom(sd, buf, sizeof(buf), 0,
                (struct sockaddr_mctp *)&addr, &addrlen);

/* We can expect addr to describe an MCTP address */
assert(addrlen >= sizeof(buf));
assert(addr.smctp_family == AF_MCTP);

printf("received %zd bytes from remote EID %d\n", rc, addr.smctp_addr);
```

The address argument to `recvfrom` and `recvmsg` is populated with the remote address of the incoming message, including tag value (this will be needed in order to reply to the message).

The first byte of the message buffer will contain the message type byte. If an integrity check follows the message, it will be included in the received buffer.

The `recv()` system call behaves in a similar way, but does not provide a remote address to the application. Therefore, these are only useful if the remote address is already known, or the message does not require a reply.

Like the send calls, sockets will only receive responses to requests they have sent (TO=1) and may only respond (TO=0) to requests they have received.

<a id="rst-ioctl-siocmctpalloctag-and-ioctl-siocmctpdroptag"></a>

#### `ioctl(SIOCMCTPALLOCTAG)` and `ioctl(SIOCMCTPDROPTAG)`

These tags give applications more control over MCTP message tags, by allocating (and dropping) tag values explicitly, rather than the kernel automatically allocating a per-message tag at `sendmsg()` time.

In general, you will only need to use these ioctls if your MCTP protocol does not fit the usual request/response model. For example, if you need to persist tags across multiple requests, or a request may generate more than one response. In these cases, the ioctls allow you to decouple the tag allocation (and release) from individual message send and receive operations.

Both ioctls are passed a pointer to a `struct mctp_ioc_tag_ctl`:



```C
struct mctp_ioc_tag_ctl {
    mctp_eid_t      peer_addr;
    __u8            tag;
    __u16           flags;
};
```

`SIOCMCTPALLOCTAG` allocates a tag for a specific peer, which an application can use in future `sendmsg()` calls. The application populates the `peer_addr` member with the remote EID. Other fields must be zero.

On return, the `tag` member will be populated with the allocated tag value. The allocated tag will have the following tag bits set:

> - `MCTP_TAG_OWNER`: it only makes sense to allocate tags if you're the tag owner
>
> - `MCTP_TAG_PREALLOC`: to indicate to `sendmsg()` that this is a preallocated tag.
>
> - ... and the actual tag value, within the least-significant three bits (`MCTP_TAG_MASK`). Note that zero is a valid tag value.

The tag value should be used as-is for the `smctp_tag` member of `struct sockaddr_mctp`.

`SIOCMCTPDROPTAG` releases a tag that has been previously allocated by a `SIOCMCTPALLOCTAG` ioctl. The `peer_addr` must be the same as used for the allocation, and the `tag` value must match exactly the tag returned from the allocation (including the `MCTP_TAG_OWNER` and `MCTP_TAG_PREALLOC` bits). The `flags` field must be zero.

<a id="rst-kernel-internals"></a>

## Kernel internals

There are a few possible packet flows in the MCTP stack:

1. local TX to remote endpoint, message &lt;= MTU:



   ```text
   sendmsg()
    -> mctp_local_output()
       : route lookup
       -> rt->output() (== mctp_route_output)
          -> dev_queue_xmit()
   ```

2. local TX to remote endpoint, message &gt; MTU:



   ```text
   sendmsg()
   -> mctp_local_output()
       -> mctp_do_fragment_route()
          : creates packet-sized skbs. For each new skb:
          -> rt->output() (== mctp_route_output)
             -> dev_queue_xmit()
   ```

3. remote TX to local endpoint, single-packet message:



   ```text
   mctp_pkttype_receive()
   : route lookup
   -> rt->output() (== mctp_route_input)
      : sk_key lookup
      -> sock_queue_rcv_skb()
   ```

4. remote TX to local endpoint, multiple-packet message:



   ```text
   mctp_pkttype_receive()
   : route lookup
   -> rt->output() (== mctp_route_input)
      : sk_key lookup
      : stores skb in struct sk_key->reasm_head

   mctp_pkttype_receive()
   : route lookup
   -> rt->output() (== mctp_route_input)
      : sk_key lookup
      : finds existing reassembly in sk_key->reasm_head
      : appends new fragment
      -> sock_queue_rcv_skb()
   ```

<a id="rst-key-refcounts"></a>

### Key refcounts

> - keys are refed by:
>
>   - a skb: during route output, stored in `skb->cb`.
>
>   - netns and sock lists.
>
> - keys can be associated with a device, in which case they hold a reference to the dev (set through `key->dev`, counted through `dev->key_count`). Multiple keys can reference the device.

---

# MPLS Sysfs variables

_Peios Kernel / Internals / Networking_

> Number of entries in the platform label table. It is not possible to configure forwarding for label values equal to or greater than the number of platform labels.

<a id="rst-mpls-sysfs-variables"></a>

<a id="rst-proc-sys-net-mpls-variables"></a>

## /proc/sys/net/mpls/\* Variables:

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **platform_labels - INTEGER**

  Number of entries in the platform label table.  It is not possible to configure forwarding for label values equal to or greater than the number of platform labels.

  A dense utilization of the entries in the platform label table is possible and expected as the platform labels are locally allocated.

  If the number of platform label table entries is set to 0 no label will be recognized by the kernel and mpls forwarding will be disabled.

  Reducing this value will remove all label routing entries that no longer fit in the table.

  Possible values: 0 - 1048575

  Default: 0

- **ip_ttl_propagate - BOOL**

  Control whether TTL is propagated from the IPv4/IPv6 header to the MPLS header on imposing labels and propagated from the MPLS header to the IPv4/IPv6 header on popping the last label.

  If disabled, the MPLS transport network will appear as a single hop to transit traffic.

  - 0 - disabled / RFC 3443 \[Short\] Pipe Model

  - 1 - enabled / RFC 3443 Uniform Model (default)

- **default_ttl - INTEGER**

  Default TTL value to use for MPLS packets where it cannot be propagated from an IP header, either because one isn't present or ip_ttl_propagate has been disabled.

  Possible values: 1 - 255

  Default: 255

- **conf/&lt;interface&gt;/input - BOOL**

  Control whether packets can be input on this interface.

  If disabled, packets will be discarded without further processing.

  - 0 - disabled (default)

  - not 0 - enabled

---

# MPTCP Sysfs variables

_Peios Kernel / Internals / Networking_

> Set the maximum value of timeout after which an ADD_ADDR control message will be resent to an MPTCP peer that has not acknowledged a previous ADD_ADDR message. A dynamically estimated retransmission timeout based on the estimated…

> **Peios:** Interface availability and resource limits do not grant native access. Peios applies descriptor/handle checks, its sysfs write gate and mapped privilege checks where applicable. Read inherited privileged/unprivileged terminology with [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-mptcp-sysfs-variables"></a>

<a id="rst-proc-sys-net-mptcp-variables"></a>

## /proc/sys/net/mptcp/\* Variables

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **add_addr_timeout - INTEGER (seconds)**

  Set the maximum value of timeout after which an ADD_ADDR control message will be resent to an MPTCP peer that has not acknowledged a previous ADD_ADDR message. A dynamically estimated retransmission timeout based on the estimated connection round-trip-time is used if this value is lower than the maximum one.

  Do not retransmit if set to 0.

  The default value matches TCP_RTO_MAX. This is a per-namespace sysctl.

  Default: 120

- **allow_join_initial_addr_port - BOOLEAN**

  Allow peers to send join requests to the IP address and port number used by the initial subflow if the value is 1. This controls a flag that is sent to the peer at connection time, and whether such join requests are accepted or denied.

  Joins to addresses advertised with ADD_ADDR are not affected by this value.

  This is a per-namespace sysctl.

  Default: 1

- **available_path_managers - STRING**

  Shows the available path managers choices that are registered. More path managers may be available, but not loaded.

- **available_schedulers - STRING**

  Shows the available schedulers choices that are registered. More packet schedulers may be available, but not loaded.

- **blackhole_timeout - INTEGER (seconds)**

  Initial time period in second to disable MPTCP on active MPTCP sockets when a MPTCP firewall blackhole issue happens. This time period will grow exponentially when more blackhole issues get detected right after MPTCP is re-enabled and will reset to the initial value when the blackhole issue goes away.

  0 to disable the blackhole detection. This is a per-namespace sysctl.

  Default: 3600

- **checksum_enabled - BOOLEAN**

  Control whether DSS checksum can be enabled.

  DSS checksum can be enabled if the value is nonzero. This is a per-namespace sysctl.

  Default: 0

- **close_timeout - INTEGER (seconds)**

  Set the make-after-break timeout: in absence of any close or shutdown syscall, MPTCP sockets will maintain the status unchanged for such time, after the last subflow removal, before moving to TCP_CLOSE.

  The default value matches TCP_TIMEWAIT_LEN. This is a per-namespace sysctl.

  Default: 60

- **enabled - BOOLEAN**

  Control whether MPTCP sockets can be created.

  MPTCP sockets can be created if the value is 1. This is a per-namespace sysctl.

  Default: 1 (enabled)

- **path_manager - STRING**

  Set the default path manager name to use for each new MPTCP socket. In-kernel path management will control subflow connections and address advertisements according to per-namespace values configured over the MPTCP netlink API. Userspace path management puts per-MPTCP-connection subflow connection decisions and address advertisements under control of a privileged userspace program, at the cost of more netlink traffic to propagate all of the related events and commands.

  This is a per-namespace sysctl.

  - "kernel"          - In-kernel path manager

  - "userspace"       - Userspace path manager

  Default: "kernel"

- **pm_type - INTEGER**

  Set the default path manager type to use for each new MPTCP socket. In-kernel path management will control subflow connections and address advertisements according to per-namespace values configured over the MPTCP netlink API. Userspace path management puts per-MPTCP-connection subflow connection decisions and address advertisements under control of a privileged userspace program, at the cost of more netlink traffic to propagate all of the related events and commands.

  This is a per-namespace sysctl.

  Deprecated since v6.15, use path_manager instead.

  - 0 - In-kernel path manager

  - 1 - Userspace path manager

  Default: 0

- **scheduler - STRING**

  Select the scheduler of your choice.

  Support for selection of different schedulers. This is a per-namespace sysctl.

  Default: "default"

- **stale_loss_cnt - INTEGER**

  The number of MPTCP-level retransmission intervals with no traffic and pending outstanding data on a given subflow required to declare it stale. The packet scheduler ignores stale subflows. A low stale_loss_cnt  value allows for fast active-backup switch-over, an high value maximize links utilization on edge scenarios e.g. lossy link with high BER or peer pausing the data processing.

  This is a per-namespace sysctl.

  Default: 4

- **syn_retrans_before_tcp_fallback - INTEGER**

  The number of SYN + MP_CAPABLE retransmissions before falling back to TCP, i.e. dropping the MPTCP options. In other words, if all the packets are dropped on the way, there will be:

  - The initial SYN with MPTCP support

  - This number of SYN retransmitted with MPTCP support

  - The next SYN retransmissions will be without MPTCP support

  0 means the first retransmission will be done without MPTCP options. &gt;= 128 means that all SYN retransmissions will keep the MPTCP options. A lower number might increase false-positive MPTCP blackholes detections. This is a per-namespace sysctl.

  Default: 2

---

# Multipath TCP (MPTCP)

_Peios Kernel / Internals / Networking_

> Multipath TCP or MPTCP is an extension to the standard TCP and is described in RFC 8684 (MPTCPv1). It allows a device to make use of multiple interfaces at once to send and receive TCP packets over a single MPTCP connection. MPTCP can…

<a id="rst-multipath-tcp-mptcp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

Multipath TCP or MPTCP is an extension to the standard TCP and is described in [RFC 8684 (MPTCPv1)](<https://www.rfc-editor.org/rfc/rfc8684.html>)<a id="rst-rfc-8684-mptcpv1"></a>. It allows a device to make use of multiple interfaces at once to send and receive TCP packets over a single MPTCP connection. MPTCP can aggregate the bandwidth of multiple interfaces or prefer the one with the lowest latency. It also allows a fail-over if one path is down, and the traffic is seamlessly reinjected on other paths.

For more details about Multipath TCP in the Linux kernel, please see the official website: [mptcp.dev](<https://www.mptcp.dev>)<a id="rst-mptcp-dev"></a>.

<a id="rst-use-cases"></a>

## Use cases

Thanks to MPTCP, being able to use multiple paths in parallel or simultaneously brings new use-cases, compared to TCP:

- Seamless handovers: switching from one path to another while preserving established connections, e.g. to be used in mobility use-cases, like on smartphones.

- Best network selection: using the "best" available path depending on some conditions, e.g. latency, losses, cost, bandwidth, etc.

- Network aggregation: using multiple paths at the same time to have a higher throughput, e.g. to combine fixed and mobile networks to send files faster.

<a id="rst-concepts"></a>

## Concepts

Technically, when a new socket is created with the `IPPROTO_MPTCP` protocol (Linux-specific), a *subflow* (or *path*) is created. This *subflow* consists of a regular TCP connection that is used to transmit data through one interface. Additional *subflows* can be negotiated later between the hosts. For the remote host to be able to detect the use of MPTCP, a new field is added to the TCP *option* field of the underlying TCP *subflow*. This field contains, amongst other things, a `MP_CAPABLE` option that tells the other host to use MPTCP if it is supported. If the remote host or any middlebox in between does not support it, the returned `SYN+ACK` packet will not contain MPTCP options in the TCP *option* field. In that case, the connection will be "downgraded" to plain TCP, and it will continue with a single path.

This behavior is made possible by two internal components: the path manager, and the packet scheduler.

<a id="rst-path-manager"></a>

### Path Manager

The Path Manager is in charge of *subflows*, from creation to deletion, and also address announcements. Typically, it is the client side that initiates subflows, and the server side that announces additional addresses via the `ADD_ADDR` and `REMOVE_ADDR` options.

Path managers are controlled by the `net.mptcp.path_manager` sysctl knob -- see [mptcp-sysctl.rst](/kernel/internals/networking/mptcp-sysctl.md). There are two types: the in-kernel one (`kernel`) where the same rules are applied for all the connections (see: `ip mptcp`) ; and the userspace one (`userspace`), controlled by a userspace daemon (i.e. [mptcpd](<https://mptcpd.mptcp.dev/>)<a id="rst-mptcpd"></a>) where different rules can be applied for each connection. The path managers can be controlled via a Netlink API; see ../netlink/specs/mptcp_pm.rst.

To be able to use multiple IP addresses on a host to create multiple *subflows* (paths), the default in-kernel MPTCP path-manager needs to know which IP addresses can be used. This can be configured with `ip mptcp endpoint` for example.

<a id="rst-packet-scheduler"></a>

### Packet Scheduler

The Packet Scheduler is in charge of selecting which available *subflow(s)* to use to send the next data packet. It can decide to maximize the use of the available bandwidth, only to pick the path with the lower latency, or any other policy depending on the configuration.

Packet schedulers are controlled by the `net.mptcp.scheduler` sysctl knob -- see [mptcp-sysctl.rst](/kernel/internals/networking/mptcp-sysctl.md).

<a id="rst-sockets-api"></a>

## Sockets API

<a id="rst-creating-mptcp-sockets"></a>

### Creating MPTCP sockets

On Linux, MPTCP can be used by selecting MPTCP instead of TCP when creating the `socket`:



```C
int sd = socket(AF_INET(6), SOCK_STREAM, IPPROTO_MPTCP);
```

Note that `IPPROTO_MPTCP` is defined as `262`.

If MPTCP is not supported, `errno` will be set to:

- `EINVAL`: (*Invalid argument*): MPTCP is not available, on kernels &lt; 5.6.

- `EPROTONOSUPPORT` (*Protocol not supported*): MPTCP has not been compiled, on kernels &gt;= v5.6.

- `ENOPROTOOPT` (*Protocol not available*): MPTCP has been disabled using `net.mptcp.enabled` sysctl knob; see [mptcp-sysctl.rst](/kernel/internals/networking/mptcp-sysctl.md).

MPTCP is then opt-in: applications need to explicitly request it. Note that applications can be forced to use MPTCP with different techniques, e.g. `LD_PRELOAD` (see `mptcpize`), eBPF (see `mptcpify`), SystemTAP, `GODEBUG` (`GODEBUG=multipathtcp=1`), etc.

Switching to `IPPROTO_MPTCP` instead of `IPPROTO_TCP` should be as transparent as possible for the userspace applications.

<a id="rst-socket-options"></a>

### Socket options

MPTCP supports most socket options handled by TCP. It is possible some less common options are not supported, but contributions are welcome.

Generally, the same value is propagated to all subflows, including the ones created after the calls to `setsockopt()`. eBPF can be used to set different values per subflow.

There are some MPTCP specific socket options at the `SOL_MPTCP` (284) level to retrieve info. They fill the `optval` buffer of the `getsockopt()` system call:

- `MPTCP_INFO`: Uses `struct mptcp_info`.

- `MPTCP_TCPINFO`: Uses `struct mptcp_subflow_data`, followed by an array of `struct tcp_info`.

- `MPTCP_SUBFLOW_ADDRS`: Uses `struct mptcp_subflow_data`, followed by an array of `mptcp_subflow_addrs`.

- `MPTCP_FULL_INFO`: Uses `struct mptcp_full_info`, with one pointer to an array of `struct mptcp_subflow_info` (including the `struct mptcp_subflow_addrs`), and one pointer to an array of `struct tcp_info`, followed by the content of `struct mptcp_info`.

Note that at the TCP level, `TCP_IS_MPTCP` socket option can be used to know if MPTCP is currently being used: the value will be set to 1 if it is.

<a id="rst-design-choices"></a>

## Design choices

A new socket type has been added for MPTCP for the userspace-facing socket. The kernel is in charge of creating subflow sockets: they are TCP sockets where the behavior is modified using TCP-ULP.

MPTCP listen sockets will create "plain" *accepted* TCP sockets if the connection request from the client didn't ask for MPTCP, making the performance impact minimal when MPTCP is enabled by default.

---

# MSG_ZEROCOPY

_Peios Kernel / Internals / Networking_

> The MSG_ZEROCOPY flag enables copy avoidance for socket send calls. The feature is currently implemented for TCP, UDP and VSOCK (with virtio transport) sockets.

<a id="rst-msg-zerocopy"></a>

<a id="rst-intro"></a>

## Intro

The MSG_ZEROCOPY flag enables copy avoidance for socket send calls. The feature is currently implemented for TCP, UDP and VSOCK (with virtio transport) sockets.

<a id="rst-opportunity-and-caveats"></a>

### Opportunity and Caveats

Copying large buffers between user process and kernel can be expensive. Linux supports various interfaces that eschew copying, such as sendfile and splice. The MSG_ZEROCOPY flag extends the underlying copy avoidance mechanism to common socket send calls.

Copy avoidance is not a free lunch. As implemented, with page pinning, it replaces per byte copy cost with page accounting and completion notification overhead. As a result, MSG_ZEROCOPY is generally only effective at writes over around 10 KB.

Page pinning also changes system call semantics. It temporarily shares the buffer between process and network stack. Unlike with copying, the process cannot immediately overwrite the buffer after system call return without possibly modifying the data in flight. Kernel integrity is not affected, but a buggy program can possibly corrupt its own data stream.

The kernel returns a notification when it is safe to modify data. Converting an existing application to MSG_ZEROCOPY is not always as trivial as just passing the flag, then.

<a id="rst-more-info"></a>

### More Info

Much of this document was derived from a longer paper presented at netdev 2.1. For more in-depth information see that paper and talk, the excellent reporting over at LWN.net or read the original code.

> - **paper, slides, video**
>
>   [https://netdevconf.org/2.1/session.html?debruijn](<https://netdevconf.org/2.1/session.html?debruijn>)
>
> - **LWN article**
>
>   [https://lwn.net/Articles/726917/](<https://lwn.net/Articles/726917/>)
>
> - **patchset**
>
>   \[PATCH net-next v4 0/9\] socket sendmsg MSG_ZEROCOPY [https://lore.kernel.org/netdev/20170803202945.70750-1-willemdebruijn.kernel@gmail.com](<https://lore.kernel.org/netdev/20170803202945.70750-1-willemdebruijn.kernel@gmail.com>)

<a id="rst-interface"></a>

## Interface

Passing the MSG_ZEROCOPY flag is the most obvious step to enable copy avoidance, but not the only one.

<a id="rst-socket-setup"></a>

### Socket Setup

The kernel is permissive when applications pass undefined flags to the send system call. By default it simply ignores these. To avoid enabling copy avoidance mode for legacy processes that accidentally already pass this flag, a process must first signal intent by setting a socket option:



```text
if (setsockopt(fd, SOL_SOCKET, SO_ZEROCOPY, &one, sizeof(one)))
        error(1, errno, "setsockopt zerocopy");
```

<a id="rst-transmission"></a>

### Transmission

The change to send (or sendto, sendmsg, sendmmsg) itself is trivial. Pass the new flag.



```text
ret = send(fd, buf, sizeof(buf), MSG_ZEROCOPY);
```

A zerocopy failure will return -1 with errno ENOBUFS. This happens if the socket exceeds its optmem limit or the user exceeds their ulimit on locked pages.

<a id="rst-mixing-copy-avoidance-and-copying"></a>

#### Mixing copy avoidance and copying

Many workloads have a mixture of large and small buffers. Because copy avoidance is more expensive than copying for small packets, the feature is implemented as a flag. It is safe to mix calls with the flag with those without.

<a id="rst-notifications"></a>

### Notifications

The kernel has to notify the process when it is safe to reuse a previously passed buffer. It queues completion notifications on the socket error queue, akin to the transmit timestamping interface.

The notification itself is a simple scalar value. Each socket maintains an internal unsigned 32-bit counter. Each send call with MSG_ZEROCOPY that successfully sends data increments the counter. The counter is not incremented on failure or if called with length zero. The counter counts system call invocations, not bytes. It wraps after UINT_MAX calls.

<a id="rst-notification-reception"></a>

#### Notification Reception

The below snippet demonstrates the API. In the simplest case, each send syscall is followed by a poll and recvmsg on the error queue.

Reading from the error queue is always a non-blocking operation. The poll call is there to block until an error is outstanding. It will set POLLERR in its output flags. That flag does not have to be set in the events field. Errors are signaled unconditionally.



```text
pfd.fd = fd;
pfd.events = 0;
if (poll(&pfd, 1, -1) != 1 || pfd.revents & POLLERR == 0)
        error(1, errno, "poll");

ret = recvmsg(fd, &msg, MSG_ERRQUEUE);
if (ret == -1)
        error(1, errno, "recvmsg");

read_notification(msg);
```

The example is for demonstration purpose only. In practice, it is more efficient to not wait for notifications, but read without blocking every couple of send calls.

Notifications can be processed out of order with other operations on the socket. A socket that has an error queued would normally block other operations until the error is read. Zerocopy notifications have a zero error code, however, to not block send and recv calls.

<a id="rst-notification-batching"></a>

#### Notification Batching

Multiple outstanding packets can be read at once using the recvmmsg call. This is often not needed. In each message the kernel returns not a single value, but a range. It coalesces consecutive notifications while one is outstanding for reception on the error queue.

When a new notification is about to be queued, it checks whether the new value extends the range of the notification at the tail of the queue. If so, it drops the new notification packet and instead increases the range upper value of the outstanding notification.

For protocols that acknowledge data in-order, like TCP, each notification can be squashed into the previous one, so that no more than one notification is outstanding at any one point.

Ordered delivery is the common case, but not guaranteed. Notifications may arrive out of order on retransmission and socket teardown.

<a id="rst-notification-parsing"></a>

#### Notification Parsing

The below snippet demonstrates how to parse the control message: the read_notification() call in the previous snippet. A notification is encoded in the standard error format, sock_extended_err.

The level and type fields in the control data are protocol family specific, IP_RECVERR or IPV6_RECVERR (for TCP or UDP socket). For VSOCK socket, cmsg_level will be SOL_VSOCK and cmsg_type will be VSOCK_RECVERR.

Error origin is the new type SO_EE_ORIGIN_ZEROCOPY. ee_errno is zero, as explained before, to avoid blocking read and write system calls on the socket.

The 32-bit notification range is encoded as \[ee_info, ee_data\]. This range is inclusive. Other fields in the struct must be treated as undefined, bar for ee_code, as discussed below.



```text
struct sock_extended_err *serr;
struct cmsghdr *cm;

cm = CMSG_FIRSTHDR(msg);
if (cm->cmsg_level != SOL_IP &&
    cm->cmsg_type != IP_RECVERR)
        error(1, 0, "cmsg");

serr = (void *) CMSG_DATA(cm);
if (serr->ee_errno != 0 ||
    serr->ee_origin != SO_EE_ORIGIN_ZEROCOPY)
        error(1, 0, "serr");

printf("completed: %u..%u\n", serr->ee_info, serr->ee_data);
```

<a id="rst-deferred-copies"></a>

#### Deferred copies

Passing flag MSG_ZEROCOPY is a hint to the kernel to apply copy avoidance, and a contract that the kernel will queue a completion notification. It is not a guarantee that the copy is elided.

Copy avoidance is not always feasible. Devices that do not support scatter-gather I/O cannot send packets made up of kernel generated protocol headers plus zerocopy user data. A packet may need to be converted to a private copy of data deep in the stack, say to compute a checksum.

In all these cases, the kernel returns a completion notification when it releases its hold on the shared pages. That notification may arrive before the (copied) data is fully transmitted. A zerocopy completion notification is not a transmit completion notification, therefore.

Deferred copies can be more expensive than a copy immediately in the system call, if the data is no longer warm in the cache. The process also incurs notification processing cost for no benefit. For this reason, the kernel signals if data was completed with a copy, by setting flag SO_EE_CODE_ZEROCOPY_COPIED in field ee_code on return. A process may use this signal to stop passing flag MSG_ZEROCOPY on subsequent requests on the same socket.

<a id="rst-implementation"></a>

## Implementation

<a id="rst-loopback"></a>

### Loopback

For TCP and UDP: Data sent to local sockets can be queued indefinitely if the receive process does not read its socket. Unbound notification latency is not acceptable. For this reason all packets generated with MSG_ZEROCOPY that are looped to a local socket will incur a deferred copy. This includes looping onto packet sockets (e.g., tcpdump) and tun devices.

For VSOCK: Data path sent to local sockets is the same as for non-local sockets.

<a id="rst-testing"></a>

## Testing

More realistic example code can be found in the kernel source under tools/testing/selftests/net/msg_zerocopy.c.

Be cognizant of the loopback constraint. The test can be run between a pair of hosts. But if run between a local pair of processes, for instance when run with msg_zerocopy.sh between a veth pair across namespaces, the test will not show any improvement. For testing, the loopback restriction can be temporarily relaxed by making skb_orphan_frags_rx identical to skb_orphan_frags.

For VSOCK type of socket example can be found in tools/testing/vsock/vsock_test_zerocopy.c.

---

# Multi-PF Netdev

_Peios Kernel / Internals / Networking_

> Background

<a id="rst-multi-pf-netdev"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-contents"></a>

## Contents

- [Background](<#rst-background>)

- [Overview](<#rst-overview>)

- [mlx5 implementation](<#rst-mlx5-implementation>)

- [Channels distribution](<#rst-channels-distribution>)

- [Observability](<#rst-observability>)

- [Steering](<#rst-steering>)

- [Mutually exclusive features](<#rst-mutually-exclusive-features>)

<a id="rst-background"></a>

## Background

The Multi-PF NIC technology enables several CPUs within a multi-socket server to connect directly to the network, each through its own dedicated PCIe interface. Through either a connection harness that splits the PCIe lanes between two cards or by bifurcating a PCIe slot for a single card. This results in eliminating the network traffic traversing over the internal bus between the sockets, significantly reducing overhead and latency, in addition to reducing CPU utilization and increasing network throughput.

<a id="rst-overview"></a>

## Overview

The feature adds support for combining multiple PFs of the same port in a Multi-PF environment under one netdev instance. It is implemented in the netdev layer. Lower-layer instances like pci func, sysfs entry, and devlink are kept separate. Passing traffic through different devices belonging to different NUMA sockets saves cross-NUMA traffic and allows apps running on the same netdev from different NUMAs to still feel a sense of proximity to the device and achieve improved performance.

<a id="rst-mlx5-implementation"></a>

## mlx5 implementation

Multi-PF or Socket-direct in mlx5 is achieved by grouping PFs together which belong to the same NIC and has the socket-direct property enabled, once all PFs are probed, we create a single netdev to represent all of them, symmetrically, we destroy the netdev whenever any of the PFs is removed.

The netdev network channels are distributed between all devices, a proper configuration would utilize the correct close NUMA node when working on a certain app/CPU.

We pick one PF to be a primary (leader), and it fills a special role. The other devices (secondaries) are disconnected from the network at the chip level (set to silent mode). In silent mode, no south &lt;-&gt; north traffic flowing directly through a secondary PF. It needs the assistance of the leader PF (east &lt;-&gt; west traffic) to function. All Rx/Tx traffic is steered through the primary to/from the secondaries.

Currently, we limit the support to PFs only, and up to two PFs (sockets).

<a id="rst-channels-distribution"></a>

## Channels distribution

We distribute the channels between the different PFs to achieve local NUMA node performance on multiple NUMA nodes.

Each combined channel works against one specific PF, creating all its datapath queues against it. We distribute channels to PFs in a round-robin policy.



```text
Example for 2 PFs and 5 channels:
+--------+--------+
| ch idx | PF idx |
+--------+--------+
|    0   |    0   |
|    1   |    1   |
|    2   |    0   |
|    3   |    1   |
|    4   |    0   |
+--------+--------+
```

The reason we prefer round-robin is, it is less influenced by changes in the number of channels. The mapping between a channel index and a PF is fixed, no matter how many channels the user configures. As the channel stats are persistent across channel's closure, changing the mapping every single time would turn the accumulative stats less representing of the channel's history.

This is achieved by using the correct core device instance (mdev) in each channel, instead of them all using the same instance under "priv-&gt;mdev".

<a id="rst-observability"></a>

## Observability

The relation between PF, irq, napi, and queue can be observed via netlink spec:



```text
$ ./tools/net/ynl/pyynl/cli.py --spec Documentation/netlink/specs/netdev.yaml --dump queue-get --json='{"ifindex": 13}'
[{'id': 0, 'ifindex': 13, 'napi-id': 539, 'type': 'rx'},
 {'id': 1, 'ifindex': 13, 'napi-id': 540, 'type': 'rx'},
 {'id': 2, 'ifindex': 13, 'napi-id': 541, 'type': 'rx'},
 {'id': 3, 'ifindex': 13, 'napi-id': 542, 'type': 'rx'},
 {'id': 4, 'ifindex': 13, 'napi-id': 543, 'type': 'rx'},
 {'id': 0, 'ifindex': 13, 'napi-id': 539, 'type': 'tx'},
 {'id': 1, 'ifindex': 13, 'napi-id': 540, 'type': 'tx'},
 {'id': 2, 'ifindex': 13, 'napi-id': 541, 'type': 'tx'},
 {'id': 3, 'ifindex': 13, 'napi-id': 542, 'type': 'tx'},
 {'id': 4, 'ifindex': 13, 'napi-id': 543, 'type': 'tx'}]

$ ./tools/net/ynl/pyynl/cli.py --spec Documentation/netlink/specs/netdev.yaml --dump napi-get --json='{"ifindex": 13}'
[{'id': 543, 'ifindex': 13, 'irq': 42},
 {'id': 542, 'ifindex': 13, 'irq': 41},
 {'id': 541, 'ifindex': 13, 'irq': 40},
 {'id': 540, 'ifindex': 13, 'irq': 39},
 {'id': 539, 'ifindex': 13, 'irq': 36}]
```

Here you can clearly observe our channels distribution policy:



```text
$ ls /proc/irq/{36,39,40,41,42}/mlx5* -d -1
/proc/irq/36/mlx5_comp0@pci:0000:08:00.0
/proc/irq/39/mlx5_comp0@pci:0000:09:00.0
/proc/irq/40/mlx5_comp1@pci:0000:08:00.0
/proc/irq/41/mlx5_comp1@pci:0000:09:00.0
/proc/irq/42/mlx5_comp2@pci:0000:08:00.0
```

<a id="rst-steering"></a>

## Steering

Secondary PFs are set to "silent" mode, meaning they are disconnected from the network.

In Rx, the steering tables belong to the primary PF only, and it is its role to distribute incoming traffic to other PFs, via cross-vhca steering capabilities. Still maintain a single default RSS table, that is capable of pointing to the receive queues of a different PF.

In Tx, the primary PF creates a new Tx flow table, which is aliased by the secondaries, so they can go out to the network through it.

In addition, we set default XPS configuration that, based on the CPU, selects an SQ belonging to the PF on the same node as the CPU.

XPS default config example:

NUMA node(s):          2 NUMA node0 CPU(s):     0-11 NUMA node1 CPU(s):     12-23

PF0 on node0, PF1 on node1.

- /sys/class/net/eth2/queues/tx-0/xps_cpus:000001

- /sys/class/net/eth2/queues/tx-1/xps_cpus:001000

- /sys/class/net/eth2/queues/tx-2/xps_cpus:000002

- /sys/class/net/eth2/queues/tx-3/xps_cpus:002000

- /sys/class/net/eth2/queues/tx-4/xps_cpus:000004

- /sys/class/net/eth2/queues/tx-5/xps_cpus:004000

- /sys/class/net/eth2/queues/tx-6/xps_cpus:000008

- /sys/class/net/eth2/queues/tx-7/xps_cpus:008000

- /sys/class/net/eth2/queues/tx-8/xps_cpus:000010

- /sys/class/net/eth2/queues/tx-9/xps_cpus:010000

- /sys/class/net/eth2/queues/tx-10/xps_cpus:000020

- /sys/class/net/eth2/queues/tx-11/xps_cpus:020000

- /sys/class/net/eth2/queues/tx-12/xps_cpus:000040

- /sys/class/net/eth2/queues/tx-13/xps_cpus:040000

- /sys/class/net/eth2/queues/tx-14/xps_cpus:000080

- /sys/class/net/eth2/queues/tx-15/xps_cpus:080000

- /sys/class/net/eth2/queues/tx-16/xps_cpus:000100

- /sys/class/net/eth2/queues/tx-17/xps_cpus:100000

- /sys/class/net/eth2/queues/tx-18/xps_cpus:000200

- /sys/class/net/eth2/queues/tx-19/xps_cpus:200000

- /sys/class/net/eth2/queues/tx-20/xps_cpus:000400

- /sys/class/net/eth2/queues/tx-21/xps_cpus:400000

- /sys/class/net/eth2/queues/tx-22/xps_cpus:000800

- /sys/class/net/eth2/queues/tx-23/xps_cpus:800000

<a id="rst-mutually-exclusive-features"></a>

## Mutually exclusive features

The nature of Multi-PF, where different channels work with different PFs, conflicts with stateful features where the state is maintained in one of the PFs. For example, in the TLS device-offload feature, special context objects are created per connection and maintained in the PF.  Transitioning between different RQs/SQs would break the feature. Hence, we disable this combination for now.

---

# HOWTO for multiqueue network device support

_Peios Kernel / Internals / Networking_

> Kernel support for multiqueue devices is always present.

<a id="rst-howto-for-multiqueue-network-device-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-section-1-base-driver-requirements-for-implementing-multiqueue-support"></a>

## Section 1: Base driver requirements for implementing multiqueue support

<a id="rst-intro-kernel-support-for-multiqueue-devices"></a>

### Intro: Kernel support for multiqueue devices

Kernel support for multiqueue devices is always present.

Base drivers are required to use the new alloc_etherdev_mq() or alloc_netdev_mq() functions to allocate the subqueues for the device.  The underlying kernel API will take care of the allocation and deallocation of the subqueue memory, as well as netdev configuration of where the queues exist in memory.

The base driver will also need to manage the queues as it does the global netdev-&gt;queue_lock today.  Therefore base drivers should use the netif\_\{start\|stop\|wake\}\_subqueue() functions to manage each queue while the device is still operational.  netdev-&gt;queue_lock is still used when the device comes online or when it's completely shut down (unregister_netdev(), etc.).

<a id="rst-section-2-qdisc-support-for-multiqueue-devices"></a>

## Section 2: Qdisc support for multiqueue devices

Currently two qdiscs are optimized for multiqueue devices.  The first is the default pfifo_fast qdisc.  This qdisc supports one qdisc per hardware queue. A new round-robin qdisc, sch_multiq also supports multiple hardware queues. The qdisc is responsible for classifying the skb's and then directing the skb's to bands and queues based on the value in skb-&gt;queue_mapping.  Use this field in the base driver to determine which queue to send the skb to.

sch_multiq has been added for hardware that wishes to avoid head-of-line blocking.  It will cycle though the bands and verify that the hardware queue associated with the band is not stopped prior to dequeuing a packet.

On qdisc load, the number of bands is based on the number of queues on the hardware.  Once the association is made, any skb with skb-&gt;queue_mapping set, will be queued to the band associated with the hardware queue.

<a id="rst-section-3-brief-howto-using-multiq-for-multiqueue-devices"></a>

## Section 3: Brief howto using MULTIQ for multiqueue devices

The userspace command 'tc,' part of the iproute2 package, is used to configure qdiscs.  To add the MULTIQ qdisc to your network device, assuming the device is called eth0, run the following command:



```text
# tc qdisc add dev eth0 root handle 1: multiq
```

The qdisc will allocate the number of bands to equal the number of queues that the device reports, and bring the qdisc online.  Assuming eth0 has 4 Tx queues, the band mapping would look like:



```text
band 0 => queue 0
band 1 => queue 1
band 2 => queue 2
band 3 => queue 3
```

Traffic will begin flowing through each queue based on either the simple_tx_hash function or based on netdev-&gt;select_queue() if you have it defined.

The behavior of tc filters remains the same.  However a new tc action, skbedit, has been added.  Assuming you wanted to route all traffic to a specific host, for example 192.168.0.3, through a specific queue you could use this action and establish a filter such as:



```text
tc filter add dev eth0 parent 1: protocol ip prio 1 u32 \
        match ip dst 192.168.0.3 \
        action skbedit queue_mapping 3
```

**Author:** Alexander Duyck &lt;[alexander.h.duyck@intel.com](<mailto:alexander.h.duyck@intel.com>)&gt;

**Original Author:** Peter P. Waskiewicz Jr. &lt;[peter.p.waskiewicz.jr@intel.com](<mailto:peter.p.waskiewicz.jr@intel.com>)&gt;

---

# NAPI

_Peios Kernel / Internals / Networking_

> Duplicate implicit target name: "napi".

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-napi-1"></a>
<a id="rst-napi"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

NAPI is the event handling mechanism used by the Linux networking stack. The name NAPI no longer stands for anything in particular <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1).

In basic operation the device notifies the host about new events via an interrupt. The host then schedules a NAPI instance to process the events. The device may also be polled for events via NAPI without receiving interrupts first ([busy polling](<#rst-poll>)).

NAPI processing usually happens in the software interrupt context, but there is an option to use [separate kernel threads](<#rst-threaded>) for NAPI processing.

All in all NAPI abstracts away from the drivers the context and configuration of event (packet Rx and Tx) processing.

<a id="rst-driver-api"></a>

## Driver API

The two most important elements of NAPI are the struct napi_struct and the associated poll method. struct napi_struct holds the state of the NAPI instance while the method is the driver-specific event handler. The method will typically free Tx packets that have been transmitted and process newly received packets.

<a id="rst-control-api"></a>
<a id="rst-drv-ctrl"></a>

### Control API

netif_napi_add() and netif_napi_del() add/remove a NAPI instance from the system. The instances are attached to the netdevice passed as argument (and will be deleted automatically when netdevice is unregistered). Instances are added in a disabled state.

napi_enable() and napi_disable() manage the disabled state. A disabled NAPI can't be scheduled and its poll method is guaranteed to not be invoked. napi_disable() waits for ownership of the NAPI instance to be released.

The control APIs are not idempotent. Control API calls are safe against concurrent use of datapath APIs but an incorrect sequence of control API calls may result in crashes, deadlocks, or race conditions. For example, calling napi_disable() multiple times in a row will deadlock.

<a id="rst-datapath-api"></a>

### Datapath API

napi_schedule() is the basic method of scheduling a NAPI poll. Drivers should call this function in their interrupt handler (see [Scheduling and IRQ masking](<#rst-drv-sched>) for more info). A successful call to napi_schedule() will take ownership of the NAPI instance.

Later, after NAPI is scheduled, the driver's poll method will be called to process the events/packets. The method takes a `budget` argument - drivers can process completions for any number of Tx packets but should only process up to `budget` number of Rx packets. Rx processing is usually much more expensive.

In other words for Rx processing the `budget` argument limits how many packets driver can process in a single poll. Rx specific APIs like page pool or XDP cannot be used at all when `budget` is 0. skb Tx processing should happen regardless of the `budget`, but if the argument is 0 driver cannot call any XDP (or page pool) APIs.

> [!WARNING]
>
> The `budget` argument may be 0 if core tries to only process skb Tx completions and no Rx or XDP packets.

The poll method returns the amount of work done. If the driver still has outstanding work to do (e.g. `budget` was exhausted) the poll method should return exactly `budget`. In that case, the NAPI instance will be serviced/polled again (without the need to be scheduled).

If event processing has been completed (all outstanding packets processed) the poll method should call napi_complete_done() before returning. napi_complete_done() releases the ownership of the instance.

> [!WARNING]
>
> The case of finishing all events and using exactly `budget` must be handled carefully. There is no way to report this (rare) condition to the stack, so the driver must either not call napi_complete_done() and wait to be called again, or return `budget - 1`.
>
> If the `budget` is 0 napi_complete_done() should never be called.

<a id="rst-call-sequence"></a>

### Call sequence

Drivers should not make assumptions about the exact sequencing of calls. The poll method may be called without the driver scheduling the instance (unless the instance is disabled). Similarly, it's not guaranteed that the poll method will be called, even if napi_schedule() succeeded (e.g. if the instance gets disabled).

As mentioned in the [Control API](<#rst-drv-ctrl>) section - napi_disable() and subsequent calls to the poll method only wait for the ownership of the instance to be released, not for the poll method to exit. This means that drivers should avoid accessing any data structures after calling napi_complete_done().

<a id="rst-scheduling-and-irq-masking"></a>
<a id="rst-drv-sched"></a>

### Scheduling and IRQ masking

Drivers should keep the interrupts masked after scheduling the NAPI instance - until NAPI polling finishes any further interrupts are unnecessary.

Drivers which have to mask the interrupts explicitly (as opposed to IRQ being auto-masked by the device) should use the napi_schedule_prep() and \__napi_schedule() calls:



```c
if (napi_schedule_prep(&v->napi)) {
    mydrv_mask_rxtx_irq(v->idx);
    /* schedule after masking to avoid races */
    __napi_schedule(&v->napi);
}
```

IRQ should only be unmasked after a successful call to napi_complete_done():



```c
if (budget && napi_complete_done(&v->napi, work_done)) {
  mydrv_unmask_rxtx_irq(v->idx);
  return min(work_done, budget - 1);
}
```

napi_schedule_irqoff() is a variant of napi_schedule() which takes advantage of guarantees given by being invoked in IRQ context (no need to mask interrupts). napi_schedule_irqoff() will fall back to napi_schedule() if IRQs are threaded (such as if `PREEMPT_RT` is enabled).

<a id="rst-instance-to-queue-mapping"></a>

### Instance to queue mapping

Modern devices have multiple NAPI instances (struct napi_struct) per interface. There is no strong requirement on how the instances are mapped to queues and interrupts. NAPI is primarily a polling/processing abstraction without specific user-facing semantics. That said, most networking devices end up using NAPI in fairly similar ways.

NAPI instances most often correspond 1:1:1 to interrupts and queue pairs (queue pair is a set of a single Rx and single Tx queue).

In less common cases a NAPI instance may be used for multiple queues or Rx and Tx queues can be serviced by separate NAPI instances on a single core. Regardless of the queue assignment, however, there is usually still a 1:1 mapping between NAPI instances and interrupts.

It's worth noting that the ethtool API uses a "channel" terminology where each channel can be either `rx`, `tx` or `combined`. It's not clear what constitutes a channel; the recommended interpretation is to understand a channel as an IRQ/NAPI which services queues of a given type. For example, a configuration of 1 `rx`, 1 `tx` and 1 `combined` channel is expected to utilize 3 interrupts, 2 Rx and 2 Tx queues.

<a id="rst-persistent-napi-config"></a>

### Persistent NAPI config

Drivers often allocate and free NAPI instances dynamically. This leads to loss of NAPI-related user configuration each time NAPI instances are reallocated. The netif_napi_add_config() API prevents this loss of configuration by associating each NAPI instance with a persistent NAPI configuration based on a driver defined index value, like a queue number.

Using this API allows for persistent NAPI IDs (among other settings), which can be beneficial to userspace programs using `SO_INCOMING_NAPI_ID`. See the sections below for other NAPI configuration settings.

Drivers should try to use netif_napi_add_config() whenever possible.

<a id="rst-user-api"></a>

## User API

User interactions with NAPI depend on NAPI instance ID. The instance IDs are only visible to the user thru the `SO_INCOMING_NAPI_ID` socket option.

Users can query NAPI IDs for a device or device queue using netlink. This can be done programmatically in a user application or by using a script included in the kernel source tree: `tools/net/ynl/pyynl/cli.py`.

For example, using the script to dump all of the queues for a device (which will reveal each queue's NAPI ID):



```bash
$ kernel-source/tools/net/ynl/pyynl/cli.py \
          --spec Documentation/netlink/specs/netdev.yaml \
          --dump queue-get \
          --json='{"ifindex": 2}'
```

See `Documentation/netlink/specs/netdev.yaml` for more details on available operations and attributes.

<a id="rst-software-irq-coalescing"></a>

### Software IRQ coalescing

NAPI does not perform any explicit event coalescing by default. In most scenarios batching happens due to IRQ coalescing which is done by the device. There are cases where software coalescing is helpful.

NAPI can be configured to arm a repoll timer instead of unmasking the hardware interrupts as soon as all packets are processed. The `gro_flush_timeout` sysfs configuration of the netdevice is reused to control the delay of the timer, while `napi_defer_hard_irqs` controls the number of consecutive empty polls before NAPI gives up and goes back to using hardware IRQs.

The above parameters can also be set on a per-NAPI basis using netlink via netdev-genl. When used with netlink and configured on a per-NAPI basis, the parameters mentioned above use hyphens instead of underscores: `gro-flush-timeout` and `napi-defer-hard-irqs`.

Per-NAPI configuration can be done programmatically in a user application or by using a script included in the kernel source tree: `tools/net/ynl/pyynl/cli.py`.

For example, using the script:



```bash
$ kernel-source/tools/net/ynl/pyynl/cli.py \
          --spec Documentation/netlink/specs/netdev.yaml \
          --do napi-set \
          --json='{"id": 345,
                   "defer-hard-irqs": 111,
                   "gro-flush-timeout": 11111}'
```

Similarly, the parameter `irq-suspend-timeout` can be set using netlink via netdev-genl. There is no global sysfs parameter for this value.

`irq-suspend-timeout` is used to determine how long an application can completely suspend IRQs. It is used in combination with SO_PREFER_BUSY_POLL, which can be set on a per-epoll context basis with `EPIOCSPARAMS` ioctl.

<a id="rst-busy-polling"></a>
<a id="rst-poll"></a>

### Busy polling

Busy polling allows a user process to check for incoming packets before the device interrupt fires. As is the case with any busy polling it trades off CPU cycles for lower latency (production uses of NAPI busy polling are not well known).

Busy polling is enabled by either setting `SO_BUSY_POLL` on selected sockets or using the global `net.core.busy_poll` and `net.core.busy_read` sysctls. An io_uring API for NAPI busy polling also exists. Threaded polling of NAPI also has a mode to busy poll for packets ([threaded busy polling](<#rst-threaded-busy-poll>)) using the NAPI processing kthread.

<a id="rst-epoll-based-busy-polling"></a>

### epoll-based busy polling

It is possible to trigger packet processing directly from calls to `epoll_wait`. In order to use this feature, a user application must ensure all file descriptors which are added to an epoll context have the same NAPI ID.

If the application uses a dedicated acceptor thread, the application can obtain the NAPI ID of the incoming connection using SO_INCOMING_NAPI_ID and then distribute that file descriptor to a worker thread. The worker thread would add the file descriptor to its epoll context. This would ensure each worker thread has an epoll context with FDs that have the same NAPI ID.

Alternatively, if the application uses SO_REUSEPORT, a bpf or ebpf program can be inserted to distribute incoming connections to threads such that each thread is only given incoming connections with the same NAPI ID. Care must be taken to carefully handle cases where a system may have multiple NICs.

In order to enable busy polling, there are two choices:

1. `/proc/sys/net/core/busy_poll` can be set with a time in useconds to busy loop waiting for events. This is a system-wide setting and will cause all epoll-based applications to busy poll when they call epoll_wait. This may not be desirable as many applications may not have the need to busy poll.

2. Applications using recent kernels can issue an ioctl on the epoll context file descriptor to set (`EPIOCSPARAMS`) or get (`EPIOCGPARAMS`) `struct epoll_params`:, which user programs can define as follows:



```c
struct epoll_params {
    uint32_t busy_poll_usecs;
    uint16_t busy_poll_budget;
    uint8_t prefer_busy_poll;

    /* pad the struct to a multiple of 64bits */
    uint8_t __pad;
};
```

<a id="rst-irq-mitigation"></a>

### IRQ mitigation

While busy polling is supposed to be used by low latency applications, a similar mechanism can be used for IRQ mitigation.

Very high request-per-second applications (especially routing/forwarding applications and especially applications using AF_XDP sockets) may not want to be interrupted until they finish processing a request or a batch of packets.

Such applications can pledge to the kernel that they will perform a busy polling operation periodically, and the driver should keep the device IRQs permanently masked. This mode is enabled by using the `SO_PREFER_BUSY_POLL` socket option. To avoid system misbehavior the pledge is revoked if `gro_flush_timeout` passes without any busy poll call. For epoll-based busy polling applications, the `prefer_busy_poll` field of `struct epoll_params` can be set to 1 and the `EPIOCSPARAMS` ioctl can be issued to enable this mode. See the above section for more details.

The NAPI budget for busy polling is lower than the default (which makes sense given the low latency intention of normal busy polling). This is not the case with IRQ mitigation, however, so the budget can be adjusted with the `SO_BUSY_POLL_BUDGET` socket option. For epoll-based busy polling applications, the `busy_poll_budget` field can be adjusted to the desired value in `struct epoll_params` and set on a specific epoll context using the `EPIOCSPARAMS` ioctl. See the above section for more details.

It is important to note that choosing a large value for `gro_flush_timeout` will defer IRQs to allow for better batch processing, but will induce latency when the system is not fully loaded. Choosing a small value for `gro_flush_timeout` can cause interference of the user application which is attempting to busy poll by device IRQs and softirq processing. This value should be chosen carefully with these tradeoffs in mind. epoll-based busy polling applications may be able to mitigate how much user processing happens by choosing an appropriate value for `maxevents`.

Users may want to consider an alternate approach, IRQ suspension, to help deal with these tradeoffs.

<a id="rst-irq-suspension"></a>

### IRQ suspension

IRQ suspension is a mechanism wherein device IRQs are masked while epoll triggers NAPI packet processing.

While application calls to epoll_wait successfully retrieve events, the kernel will defer the IRQ suspension timer. If the kernel does not retrieve any events while busy polling (for example, because network traffic levels subsided), IRQ suspension is disabled and the IRQ mitigation strategies described above are engaged.

This allows users to balance CPU consumption with network processing efficiency.

To use this mechanism:

> 1. The per-NAPI config parameter `irq-suspend-timeout` should be set to the maximum time (in nanoseconds) the application can have its IRQs suspended. This is done using netlink, as described above. This timeout serves as a safety mechanism to restart IRQ driver interrupt processing if the application has stalled. This value should be chosen so that it covers the amount of time the user application needs to process data from its call to epoll_wait, noting that applications can control how much data they retrieve by setting `max_events` when calling epoll_wait.
>
> 2. The sysfs parameter or per-NAPI config parameters `gro_flush_timeout` and `napi_defer_hard_irqs` can be set to low values. They will be used to defer IRQs after busy poll has found no data.
>
> 3. The `prefer_busy_poll` flag must be set to true. This can be done using the `EPIOCSPARAMS` ioctl as described above.
>
> 4. The application uses epoll as described above to trigger NAPI packet processing.

As mentioned above, as long as subsequent calls to epoll_wait return events to userland, the `irq-suspend-timeout` is deferred and IRQs are disabled. This allows the application to process data without interference.

Once a call to epoll_wait results in no events being found, IRQ suspension is automatically disabled and the `gro_flush_timeout` and `napi_defer_hard_irqs` mitigation mechanisms take over.

It is expected that `irq-suspend-timeout` will be set to a value much larger than `gro_flush_timeout` as `irq-suspend-timeout` should suspend IRQs for the duration of one userland processing cycle.

While it is not strictly necessary to use `napi_defer_hard_irqs` and `gro_flush_timeout` to use IRQ suspension, their use is strongly recommended.

IRQ suspension causes the system to alternate between polling mode and irq-driven packet delivery. During busy periods, `irq-suspend-timeout` overrides `gro_flush_timeout` and keeps the system busy polling, but when epoll finds no events, the setting of `gro_flush_timeout` and `napi_defer_hard_irqs` determine the next step.

There are essentially three possible loops for network processing and packet delivery:

1. hardirq -&gt; softirq -&gt; napi poll; basic interrupt delivery

2. timer -&gt; softirq -&gt; napi poll; deferred irq processing

3. epoll -&gt; busy-poll -&gt; napi poll; busy looping

Loop 2 can take control from Loop 1, if `gro_flush_timeout` and `napi_defer_hard_irqs` are set.

If `gro_flush_timeout` and `napi_defer_hard_irqs` are set, Loops 2 and 3 "wrestle" with each other for control.

During busy periods, `irq-suspend-timeout` is used as timer in Loop 2, which essentially tilts network processing in favour of Loop 3.

If `gro_flush_timeout` and `napi_defer_hard_irqs` are not set, Loop 3 cannot take control from Loop 1.

Therefore, setting `gro_flush_timeout` and `napi_defer_hard_irqs` is the recommended usage, because otherwise setting `irq-suspend-timeout` might not have any discernible effect.

<a id="rst-threaded-napi-busy-polling"></a>
<a id="rst-threaded-busy-poll"></a>

### Threaded NAPI busy polling

Threaded NAPI busy polling extends threaded NAPI and adds support to do continuous busy polling of the NAPI. This can be useful for forwarding or AF_XDP applications.

Threaded NAPI busy polling can be enabled on per NIC queue basis using Netlink.

For example, using the following script:



```bash
$ ynl --family netdev --do napi-set \
          --json='{"id": 66, "threaded": "busy-poll"}'
```

The kernel will create a kthread that busy polls on this NAPI.

The user may elect to set the CPU affinity of this kthread to an unused CPU core to improve how often the NAPI is polled at the expense of wasted CPU cycles. Note that this will keep the CPU core busy with 100% usage.

Once threaded busy polling is enabled for a NAPI, PID of the kthread can be retrieved using Netlink so the affinity of the kthread can be set up.

For example, the following script can be used to fetch the PID:



```bash
$ ynl --family netdev --do napi-get --json='{"id": 66}'
```

This will output something like following, the pid `258` is the PID of the kthread that is polling this NAPI.



```bash
$ {'defer-hard-irqs': 0,
   'gro-flush-timeout': 0,
   'id': 66,
   'ifindex': 2,
   'irq-suspend-timeout': 0,
   'pid': 258,
   'threaded': 'busy-poll'}
```

<a id="rst-threaded-napi"></a>
<a id="rst-threaded"></a>

### Threaded NAPI

Threaded NAPI is an operating mode that uses dedicated kernel threads rather than software IRQ context for NAPI processing. Each threaded NAPI instance will spawn a separate thread (called `napi/${ifc-name}-${napi-id}`).

It is recommended to pin each kernel thread to a single CPU, the same CPU as the CPU which services the interrupt. Note that the mapping between IRQs and NAPI instances may not be trivial (and is driver dependent). The NAPI instance IDs will be assigned in the opposite order than the process IDs of the kernel threads.

Threaded NAPI is controlled by writing 0/1 to the `threaded` file in netdev's sysfs directory. It can also be enabled for a specific NAPI using netlink interface.

For example, using the script:



```bash
$ ynl --family netdev --do napi-set --json='{"id": 66, "threaded": 1}'
```

**Footnotes**

<a id="rst-footnote-1"></a>



**[1]** NAPI was originally referred to as New API in 2.4 Linux.

---

# Net DIM - Generic Network Dynamic Interrupt Moderation

_Peios Kernel / Internals / Networking_

> Assumptions

<a id="rst-net-dim-generic-network-dynamic-interrupt-moderation"></a>

**Author:** Tal Gilboa &lt;[talgi@mellanox.com](<mailto:talgi@mellanox.com>)&gt;

<a id="rst-contents"></a>



<a id="rst-assumptions"></a>

## Assumptions

This document assumes the reader has basic knowledge in network drivers and in general interrupt moderation.

<a id="rst-introduction"></a>

## Introduction

Dynamic Interrupt Moderation (DIM) (in networking) refers to changing the interrupt moderation configuration of a channel in order to optimize packet processing. The mechanism includes an algorithm which decides if and how to change moderation parameters for a channel, usually by performing an analysis on runtime data sampled from the system. Net DIM is such a mechanism. In each iteration of the algorithm, it analyses a given sample of the data, compares it to the previous sample and if required, it can decide to change some of the interrupt moderation configuration fields. The data sample is composed of data bandwidth, the number of packets and the number of events. The time between samples is also measured. Net DIM compares the current and the previous data and returns an adjusted interrupt moderation configuration object. In some cases, the algorithm might decide not to change anything. The configuration fields are the minimum duration (microseconds) allowed between events and the maximum number of wanted packets per event. The Net DIM algorithm ascribes importance to increase bandwidth over reducing interrupt rate.

<a id="rst-net-dim-algorithm"></a>

## Net DIM Algorithm

Each iteration of the Net DIM algorithm follows these steps:

1. Calculates new data sample.

2. Compares it to previous sample.

3. Makes a decision - suggests interrupt moderation configuration fields.

4. Applies a schedule work function, which applies suggested configuration.

The first two steps are straightforward, both the new and the previous data are supplied by the driver registered to Net DIM. The previous data is the new data supplied to the previous iteration. The comparison step checks the difference between the new and previous data and decides on the result of the last step. A step would result as "better" if bandwidth increases and as "worse" if bandwidth reduces. If there is no change in bandwidth, the packet rate is compared in a similar fashion - increase == "better" and decrease == "worse". In case there is no change in the packet rate as well, the interrupt rate is compared. Here the algorithm tries to optimize for lower interrupt rate so an increase in the interrupt rate is considered "worse" and a decrease is considered "better". Step \#2 has an optimization for avoiding false results: it only considers a difference between samples as valid if it is greater than a certain percentage. Also, since Net DIM does not measure anything by itself, it assumes the data provided by the driver is valid.

Step \#3 decides on the suggested configuration based on the result from step \#2 and the internal state of the algorithm. The states reflect the "direction" of the algorithm: is it going left (reducing moderation), right (increasing moderation) or standing still. Another optimization is that if a decision to stay still is made multiple times, the interval between iterations of the algorithm would increase in order to reduce calculation overhead. Also, after "parking" on one of the most left or most right decisions, the algorithm may decide to verify this decision by taking a step in the other direction. This is done in order to avoid getting stuck in a "deep sleep" scenario. Once a decision is made, an interrupt moderation configuration is selected from the predefined profiles.

The last step is to notify the registered driver that it should apply the suggested configuration. This is done by scheduling a work function, defined by the Net DIM API and provided by the registered driver.

As you can see, Net DIM itself does not actively interact with the system. It would have trouble making the correct decisions if the wrong data is supplied to it and it would be useless if the work function would not apply the suggested configuration. This does, however, allow the registered driver some room for manoeuvre as it may provide partial data or ignore the algorithm suggestion under some conditions.

<a id="rst-registering-a-network-device-to-dim"></a>

## Registering a Network Device to DIM

Net DIM API exposes the main function net_dim(). This function is the entry point to the Net DIM algorithm and has to be called every time the driver would like to check if it should change interrupt moderation parameters. The driver should provide two data structures: `struct dim <dim>` and `struct dim_sample <dim_sample>`. `struct dim <dim>` describes the state of DIM for a specific object (RX queue, TX queue, other queues, etc.). This includes the current selected profile, previous data samples, the callback function provided by the driver and more. `struct dim_sample <dim_sample>` describes a data sample, which will be compared to the data sample stored in `struct dim <dim>` in order to decide on the algorithm's next step. The sample should include bytes, packets and interrupts, measured by the driver.

In order to use Net DIM from a networking driver, the driver needs to call the main net_dim() function. The recommended method is to call net_dim() on each interrupt. Since Net DIM has a built-in moderation and it might decide to skip iterations under certain conditions, there is no need to moderate the net_dim() calls as well. As mentioned above, the driver needs to provide an object of type `struct dim <dim>` to the net_dim() function call. It is advised for each entity using Net DIM to hold a `struct dim <dim>` as part of its data structure and use it as the main Net DIM API object. The `struct dim_sample <dim_sample>` should hold the latest bytes, packets and interrupts count. No need to perform any calculations, just include the raw data.

The net_dim() call itself does not return anything. Instead Net DIM relies on the driver to provide a callback function, which is called when the algorithm decides to make a change in the interrupt moderation parameters. This callback will be scheduled and run in a separate thread in order not to add overhead to the data flow. After the work is done, Net DIM algorithm needs to be set to the proper state in order to move to the next iteration.

<a id="rst-example"></a>

## Example

The following code demonstrates how to register a driver to Net DIM. The actual usage is not complete but it should make the outline of the usage clear.



```c
#include <linux/dim.h>

/* Callback for net DIM to schedule on a decision to change moderation */
void my_driver_do_dim_work(struct work_struct *work)
{
      /* Get struct dim from struct work_struct */
      struct dim *dim = container_of(work, struct dim,
                                     work);
      /* Do interrupt moderation related stuff */
      ...

      /* Signal net DIM work is done and it should move to next iteration */
      dim->state = DIM_START_MEASURE;
}

/* My driver's interrupt handler */
int my_driver_handle_interrupt(struct my_driver_entity *my_entity, ...)
{
      ...
      /* A struct to hold current measured data */
      struct dim_sample dim_sample;
      ...
      /* Initiate data sample struct with current data */
      dim_update_sample(my_entity->events,
                        my_entity->packets,
                        my_entity->bytes,
                        &dim_sample);
      /* Call net DIM */
      net_dim(&my_entity->dim, &dim_sample);
      ...
}

/* My entity's initialization function (my_entity was already allocated) */
int my_driver_init_my_entity(struct my_driver_entity *my_entity, ...)
{
      ...
      /* Initiate struct work_struct with my driver's callback function */
      INIT_WORK(&my_entity->dim.work, my_driver_do_dim_work);
      ...
}
```

<a id="rst-tuning-dim"></a>

## Tuning DIM

Net DIM serves a range of network devices and delivers excellent acceleration benefits. Yet, it has been observed that some preset configurations of DIM may not align seamlessly with the varying specifications of network devices, and this discrepancy has been identified as a factor to the suboptimal performance outcomes of DIM-enabled network devices, related to a mismatch in profiles.

To address this issue, Net DIM introduces a per-device control to modify and access a device's `rx-profile` and `tx-profile` parameters: Assume that the target network device is named ethx, and ethx only declares support for RX profile setting and supports modification of `usec` field and `pkts` field (See the data structure: `struct dim_cq_moder <dim_cq_moder>`).

You can use ethtool to modify the current RX DIM profile where all values are 64:



```text
$ ethtool -C ethx rx-profile 1,1,n_2,2,n_3,n,n_n,4,n_n,n,n
```

`n` means do not modify this field, and `_` separates structure elements of the profile array.

Querying the current profiles using:



```text
$ ethtool -c ethx
...
rx-profile:
{.usec =   1, .pkts =   1, .comps = n/a,},
{.usec =   2, .pkts =   2, .comps = n/a,},
{.usec =   3, .pkts =  64, .comps = n/a,},
{.usec =  64, .pkts =   4, .comps = n/a,},
{.usec =  64, .pkts =  64, .comps = n/a,}
tx-profile:   n/a
```

If the network device does not support specific fields of DIM profiles, the corresponding `n/a` will display. If the `n/a` field is being modified, error messages will be reported.

<a id="rst-dynamic-interrupt-moderation-dim-library-api"></a>

## Dynamic Interrupt Moderation (DIM) library API


#### <a id="c-struct-dim_cq_moder"></a>`struct dim_cq_moder`

Structure for CQ moderation values. Used for communications between DIM and its consumer.

**Definition**

```c
struct dim_cq_moder {
    u16 usec;
    u16 pkts;
    u16 comps;
    u8 cq_period_mode;
    struct rcu_head rcu;
};
```

**Members**

- `usec`: CQ timer suggestion (by DIM)
- `pkts`: CQ packet counter suggestion (by DIM)
- `comps`: Completion counter
- `cq_period_mode`: CQ period count mode (from CQE/EQE)
- `rcu`: for asynchronous kfree_rcu

#### <a id="c-struct-dim_irq_moder"></a>`struct dim_irq_moder`

Structure for irq moderation information. Used to collect irq moderation related information.

**Definition**

```c
struct dim_irq_moder {
    u8 profile_flags;
    u8 coal_flags;
    u8 dim_rx_mode;
    u8 dim_tx_mode;
    struct dim_cq_moder  *rx_profile;
    struct dim_cq_moder  *tx_profile;
    void (*rx_dim_work)(struct work_struct *work);
    void (*tx_dim_work)(struct work_struct *work);
};
```

**Members**

- `profile_flags`: DIM_PROFILE_*
- `coal_flags`: DIM_COALESCE_* for Rx and Tx
- `dim_rx_mode`: Rx DIM period count mode: CQE or EQE
- `dim_tx_mode`: Tx DIM period count mode: CQE or EQE
- `rx_profile`: DIM profile list for Rx
- `tx_profile`: DIM profile list for Tx
- `rx_dim_work`: Rx DIM worker scheduled by [`net_dim()`](#c-net_dim)
- `tx_dim_work`: Tx DIM worker scheduled by [`net_dim()`](#c-net_dim)

#### <a id="c-struct-dim_sample"></a>`struct dim_sample`

Structure for DIM sample data. Used for communications between DIM and its consumer.

**Definition**

```c
struct dim_sample {
    ktime_t time;
    u32 pkt_ctr;
    u32 byte_ctr;
    u16 event_ctr;
    u32 comp_ctr;
};
```

**Members**

- `time`: Sample timestamp
- `pkt_ctr`: Number of packets
- `byte_ctr`: Number of bytes
- `event_ctr`: Number of events
- `comp_ctr`: Current completion counter

#### <a id="c-struct-dim_stats"></a>`struct dim_stats`

Structure for DIM stats. Used for holding current measured rates.

**Definition**

```c
struct dim_stats {
    int ppms;
    int bpms;
    int epms;
    int cpms;
    int cpe_ratio;
};
```

**Members**

- `ppms`: Packets per msec
- `bpms`: Bytes per msec
- `epms`: Events per msec
- `cpms`: Completions per msec
- `cpe_ratio`: Ratio of completions to events

#### <a id="c-struct-dim"></a>`struct dim`

Main structure for dynamic interrupt moderation (DIM). Used for holding all information about a specific DIM instance.

**Definition**

```c
struct dim {
    u8 state;
    struct dim_stats prev_stats;
    struct dim_sample start_sample;
    struct dim_sample measuring_sample;
    struct work_struct work;
    void *priv;
    u8 profile_ix;
    u8 mode;
    u8 tune_state;
    u8 steps_right;
    u8 steps_left;
    u8 tired;
};
```

**Members**

- `state`: Algorithm state (see below)
- `prev_stats`: Measured rates from previous iteration (for comparison)
- `start_sample`: Sampled data at start of current iteration
- `measuring_sample`: A [`dim_sample`](#c-struct-dim_sample) that is used to update the current events
- `work`: Work to perform on action required
- `priv`: A pointer to the struct that points to dim
- `profile_ix`: Current moderation profile
- `mode`: CQ period count mode
- `tune_state`: Algorithm tuning state (see below)
- `steps_right`: Number of steps taken towards higher moderation
- `steps_left`: Number of steps taken towards lower moderation
- `tired`: Parking depth counter

#### <a id="c-enum-dim_cq_period_mode"></a>`enum dim_cq_period_mode`

Modes for CQ period count

**Constants**

- `DIM_CQ_PERIOD_MODE_START_FROM_EQE`: Start counting from EQE
- `DIM_CQ_PERIOD_MODE_START_FROM_CQE`: Start counting from CQE (implies timer reset)
- `DIM_CQ_PERIOD_NUM_MODES`: Number of modes

#### <a id="c-enum-dim_state"></a>`enum dim_state`

DIM algorithm states

**Constants**

- `DIM_START_MEASURE`: This is the first iteration (also after applying a new profile)
- `DIM_MEASURE_IN_PROGRESS`: Algorithm is already in progress - check if
  need to perform an action
- `DIM_APPLY_NEW_PROFILE`: DIM consumer is currently applying a profile - no need to measure

**Description**

These will determine if the algorithm is in a valid state to start an iteration.

#### <a id="c-enum-dim_tune_state"></a>`enum dim_tune_state`

DIM algorithm tune states

**Constants**

- `DIM_PARKING_ON_TOP`: Algorithm found a local top point - exit on significant difference
- `DIM_PARKING_TIRED`: Algorithm found a deep top point - don't exit if tired > 0
- `DIM_GOING_RIGHT`: Algorithm is currently trying higher moderation levels
- `DIM_GOING_LEFT`: Algorithm is currently trying lower moderation levels

**Description**

These will determine which action the algorithm should perform.

#### <a id="c-enum-dim_stats_state"></a>`enum dim_stats_state`

DIM algorithm statistics states

**Constants**

- `DIM_STATS_WORSE`: Current iteration shows worse performance than before
- `DIM_STATS_SAME`: Current iteration shows same performance than before
- `DIM_STATS_BETTER`: Current iteration shows better performance than before

**Description**

These will determine the verdict of current iteration.

#### <a id="c-enum-dim_step_result"></a>`enum dim_step_result`

DIM algorithm step results

**Constants**

- `DIM_STEPPED`: Performed a regular step
- `DIM_TOO_TIRED`: Same kind of step was done multiple times - should go to
  tired parking
- `DIM_ON_EDGE`: Stepped to the most left/right profile

**Description**

These describe the result of a step.

#### <a id="c-net_dim_init_irq_moder"></a>`net_dim_init_irq_moder()`

```c
int net_dim_init_irq_moder(struct net_device *dev, u8 profile_flags, u8 coal_flags, u8 rx_mode, u8 tx_mode, void (*rx_dim_work)(struct work_struct *work), void (*tx_dim_work)(struct work_struct *work))
```

collect information to initialize irq moderation

**Parameters**

- `struct net_device *dev`: target network device
- `u8 profile_flags`: Rx or Tx profile modification capability
- `u8 coal_flags`: irq moderation params flags
- `u8 rx_mode`: CQ period mode for Rx
- `u8 tx_mode`: CQ period mode for Tx
- `void (*rx_dim_work)(struct work_struct *work)`: Rx worker called after dim decision
- `void (*tx_dim_work)(struct work_struct *work)`: Tx worker called after dim decision

**Return**

0 on success or a negative error code.

#### <a id="c-net_dim_free_irq_moder"></a>`net_dim_free_irq_moder()`

```c
void net_dim_free_irq_moder(struct net_device *dev)
```

free fields for irq moderation

**Parameters**

- `struct net_device *dev`: target network device

#### <a id="c-net_dim_setting"></a>`net_dim_setting()`

```c
void net_dim_setting(struct net_device *dev, struct dim *dim, bool is_tx)
```

initialize DIM's cq mode and schedule worker

**Parameters**

- `struct net_device *dev`: target network device
- `struct dim *dim`: DIM context
- `bool is_tx`: true indicates the tx direction, false indicates the rx direction

#### <a id="c-net_dim_work_cancel"></a>`net_dim_work_cancel()`

```c
void net_dim_work_cancel(struct dim *dim)
```

synchronously cancel dim's worker

**Parameters**

- `struct dim *dim`: DIM context

#### <a id="c-net_dim_get_rx_irq_moder"></a>`net_dim_get_rx_irq_moder()`

```c
struct dim_cq_moder net_dim_get_rx_irq_moder(struct net_device *dev, struct dim *dim)
```

get DIM rx results based on profile_ix

**Parameters**

- `struct net_device *dev`: target network device
- `struct dim *dim`: DIM context

**Return**

DIM irq moderation

#### <a id="c-net_dim_get_tx_irq_moder"></a>`net_dim_get_tx_irq_moder()`

```c
struct dim_cq_moder net_dim_get_tx_irq_moder(struct net_device *dev, struct dim *dim)
```

get DIM tx results based on profile_ix

**Parameters**

- `struct net_device *dev`: target network device
- `struct dim *dim`: DIM context

**Return**

DIM irq moderation

#### <a id="c-net_dim_set_rx_mode"></a>`net_dim_set_rx_mode()`

```c
void net_dim_set_rx_mode(struct net_device *dev, u8 rx_mode)
```

set DIM rx cq mode

**Parameters**

- `struct net_device *dev`: target network device
- `u8 rx_mode`: target rx cq mode

#### <a id="c-net_dim_set_tx_mode"></a>`net_dim_set_tx_mode()`

```c
void net_dim_set_tx_mode(struct net_device *dev, u8 tx_mode)
```

set DIM tx cq mode

**Parameters**

- `struct net_device *dev`: target network device
- `u8 tx_mode`: target tx cq mode

#### <a id="c-dim_on_top"></a>`dim_on_top()`

```c
bool dim_on_top(struct dim *dim)
```

check if current state is a good place to stop (top location)

**Parameters**

- `struct dim *dim`: DIM context

**Description**

Check if current profile is a good place to park at.
This will result in reducing the DIM checks frequency as we assume we
shouldn't probably change profiles, unless traffic pattern wasn't changed.

#### <a id="c-dim_turn"></a>`dim_turn()`

```c
void dim_turn(struct dim *dim)
```

change profile altering direction

**Parameters**

- `struct dim *dim`: DIM context

**Description**

Go left if we were going right and vice-versa.
Do nothing if currently parking.

#### <a id="c-dim_park_on_top"></a>`dim_park_on_top()`

```c
void dim_park_on_top(struct dim *dim)
```

enter a parking state on a top location

**Parameters**

- `struct dim *dim`: DIM context

**Description**

Enter parking state.
Clear all movement history.

#### <a id="c-dim_park_tired"></a>`dim_park_tired()`

```c
void dim_park_tired(struct dim *dim)
```

enter a tired parking state

**Parameters**

- `struct dim *dim`: DIM context

**Description**

Enter parking state.
Clear all movement history and cause DIM checks frequency to reduce.

#### <a id="c-dim_calc_stats"></a>`dim_calc_stats()`

```c
bool dim_calc_stats(const struct dim_sample *start, const struct dim_sample *end, struct dim_stats *curr_stats)
```

calculate the difference between two samples

**Parameters**

- `const struct dim_sample *start`: start sample
- `const struct dim_sample *end`: end sample
- `struct dim_stats *curr_stats`: delta between samples

**Description**

Calculate the delta between two samples (in data rates).
Takes into consideration counter wrap-around.
Returned boolean indicates whether curr_stats are reliable.

#### <a id="c-dim_update_sample"></a>`dim_update_sample()`

```c
void dim_update_sample(u16 event_ctr, u64 packets, u64 bytes, struct dim_sample *s)
```

set a sample's fields with given values

**Parameters**

- `u16 event_ctr`: number of events to set
- `u64 packets`: number of packets to set
- `u64 bytes`: number of bytes to set
- `struct dim_sample *s`: DIM sample

#### <a id="c-dim_update_sample_with_comps"></a>`dim_update_sample_with_comps()`

```c
void dim_update_sample_with_comps(u16 event_ctr, u64 packets, u64 bytes, u64 comps, struct dim_sample *s)
```

set a sample's fields with given values including the completion parameter

**Parameters**

- `u16 event_ctr`: number of events to set
- `u64 packets`: number of packets to set
- `u64 bytes`: number of bytes to set
- `u64 comps`: number of completions to set
- `struct dim_sample *s`: DIM sample

#### <a id="c-net_dim_get_rx_moderation"></a>`net_dim_get_rx_moderation()`

```c
struct dim_cq_moder net_dim_get_rx_moderation(u8 cq_period_mode, int ix)
```

provide a CQ moderation object for the given RX profile

**Parameters**

- `u8 cq_period_mode`: CQ period mode
- `int ix`: Profile index

#### <a id="c-net_dim_get_def_rx_moderation"></a>`net_dim_get_def_rx_moderation()`

```c
struct dim_cq_moder net_dim_get_def_rx_moderation(u8 cq_period_mode)
```

provide the default RX moderation

**Parameters**

- `u8 cq_period_mode`: CQ period mode

#### <a id="c-net_dim_get_tx_moderation"></a>`net_dim_get_tx_moderation()`

```c
struct dim_cq_moder net_dim_get_tx_moderation(u8 cq_period_mode, int ix)
```

provide a CQ moderation object for the given TX profile

**Parameters**

- `u8 cq_period_mode`: CQ period mode
- `int ix`: Profile index

#### <a id="c-net_dim_get_def_tx_moderation"></a>`net_dim_get_def_tx_moderation()`

```c
struct dim_cq_moder net_dim_get_def_tx_moderation(u8 cq_period_mode)
```

provide the default TX moderation

**Parameters**

- `u8 cq_period_mode`: CQ period mode

#### <a id="c-net_dim"></a>`net_dim()`

```c
void net_dim(struct dim *dim, const struct dim_sample *end_sample)
```

main DIM algorithm entry point

**Parameters**

- `struct dim *dim`: DIM instance information
- `const struct dim_sample *end_sample`: Current data measurement

**Description**

Called by the consumer.
This is the main logic of the algorithm, where data is processed in order
to decide on next required action.

#### <a id="c-rdma_dim"></a>`rdma_dim()`

```c
void rdma_dim(struct dim *dim, u64 completions)
```

Runs the adaptive moderation.

**Parameters**

- `struct dim *dim`: The moderation struct.
- `u64 completions`: The number of completions collected in this round.

**Description**

Each call to rdma_dim takes the latest amount of completions that
have been collected and counts them as a new event.
Once enough events have been collected the algorithm decides a new
moderation level.

---

# NET_FAILOVER

_Peios Kernel / Internals / Networking_

> The net_failover driver provides an automated failover mechanism via APIs to create and destroy a failover master netdev and manages a primary and standby slave netdevs that get registered via the generic failover infrastructure.

<a id="rst-net-failover"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The net_failover driver provides an automated failover mechanism via APIs to create and destroy a failover master netdev and manages a primary and standby slave netdevs that get registered via the generic failover infrastructure.

The failover netdev acts a master device and controls 2 slave devices. The original paravirtual interface is registered as 'standby' slave netdev and a passthru/vf device with the same MAC gets registered as 'primary' slave netdev. Both 'standby' and 'failover' netdevs are associated with the same 'pci' device. The user accesses the network interface via 'failover' netdev. The 'failover' netdev chooses 'primary' netdev as default for transmits when it is available with link up and running.

This can be used by paravirtual drivers to enable an alternate low latency datapath. It also enables hypervisor controlled live migration of a VM with direct attached VF by failing over to the paravirtual datapath when the VF is unplugged.

<a id="rst-virtio-net-accelerated-datapath-standby-mode"></a>

## virtio-net accelerated datapath: STANDBY mode

net_failover enables hypervisor controlled accelerated datapath to virtio-net enabled VMs in a transparent manner with no/minimal guest userspace changes.

To support this, the hypervisor needs to enable VIRTIO_NET_F_STANDBY feature on the virtio-net interface and assign the same MAC address to both virtio-net and VF interfaces.

Here is an example libvirt XML snippet that shows such configuration:



```text
<interface type='network'>
  <mac address='52:54:00:00:12:53'/>
  <source network='enp66s0f0_br'/>
  <target dev='tap01'/>
  <model type='virtio'/>
  <driver name='vhost' queues='4'/>
  <link state='down'/>
  <teaming type='persistent'/>
  <alias name='ua-backup0'/>
</interface>
<interface type='hostdev' managed='yes'>
  <mac address='52:54:00:00:12:53'/>
  <source>
    <address type='pci' domain='0x0000' bus='0x42' slot='0x02' function='0x5'/>
  </source>
  <teaming type='transient' persistent='ua-backup0'/>
</interface>
```

In this configuration, the first device definition is for the virtio-net interface and this acts as the 'persistent' device indicating that this interface will always be plugged in. This is specified by the 'teaming' tag with required attribute type having value 'persistent'. The link state for the virtio-net device is set to 'down' to ensure that the 'failover' netdev prefers the VF passthrough device for normal communication. The virtio-net device will be brought UP during live migration to allow uninterrupted communication.

The second device definition is for the VF passthrough interface. Here the 'teaming' tag is provided with type 'transient' indicating that this device may periodically be unplugged. A second attribute - 'persistent' is provided and points to the alias name declared for the virtio-net device.

Booting a VM with the above configuration will result in the following 3 interfaces created in the VM:



```text
4: ens10: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 52:54:00:00:12:53 brd ff:ff:ff:ff:ff:ff
    inet 192.168.12.53/24 brd 192.168.12.255 scope global dynamic ens10
       valid_lft 42482sec preferred_lft 42482sec
    inet6 fe80::97d8:db2:8c10:b6d6/64 scope link
       valid_lft forever preferred_lft forever
5: ens10nsby: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master ens10 state DOWN group default qlen 1000
    link/ether 52:54:00:00:12:53 brd ff:ff:ff:ff:ff:ff
7: ens11: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master ens10 state UP group default qlen 1000
    link/ether 52:54:00:00:12:53 brd ff:ff:ff:ff:ff:ff
```

Here, ens10 is the 'failover' master interface, ens10nsby is the slave 'standby' virtio-net interface, and ens11 is the slave 'primary' VF passthrough interface.

One point to note here is that some user space network configuration daemons like systemd-networkd, ifupdown, etc, do not understand the 'net_failover' device; and on the first boot, the VM might end up with both 'failover' device and VF acquiring IP addresses (either same or different) from the DHCP server. This will result in lack of connectivity to the VM. So some tweaks might be needed to these network configuration daemons to make sure that an IP is received only on the 'failover' device.

Below is the patch snippet used with 'cloud-ifupdown-helper' script found on Debian cloud images:



```text
@@ -27,6 +27,8 @@ do_setup() {
     local working="$cfgdir/.$INTERFACE"
     local final="$cfgdir/$INTERFACE"

+    if [ -d "/sys/class/net/${INTERFACE}/master" ]; then exit 0; fi
+
     if ifup --no-act "$INTERFACE" > /dev/null 2>&1; then
         # interface is already known to ifupdown, no need to generate cfg
         log "Skipping configuration generation for $INTERFACE"
```

<a id="rst-live-migration-of-a-vm-with-sr-iov-vf-virtio-net-in-standby-mode"></a>

## Live Migration of a VM with SR-IOV VF &amp; virtio-net in STANDBY mode

net_failover also enables hypervisor controlled live migration to be supported with VMs that have direct attached SR-IOV VF devices by automatic failover to the paravirtual datapath when the VF is unplugged.

Here is a sample script that shows the steps to initiate live migration from the source hypervisor. Note: It is assumed that the VM is connected to a software bridge 'br0' which has a single VF attached to it along with the vnet device to the VM. This is not the VF that was passthrough'd to the VM (seen in the vf.xml file).



```text
# cat vf.xml
<interface type='hostdev' managed='yes'>
  <mac address='52:54:00:00:12:53'/>
  <source>
    <address type='pci' domain='0x0000' bus='0x42' slot='0x02' function='0x5'/>
  </source>
  <teaming type='transient' persistent='ua-backup0'/>
</interface>

# Source Hypervisor migrate.sh
#!/bin/bash

DOMAIN=vm-01
PF=ens6np0
VF=ens6v1             # VF attached to the bridge.
VF_NUM=1
TAP_IF=vmtap01        # virtio-net interface in the VM.
VF_XML=vf.xml

MAC=52:54:00:00:12:53
ZERO_MAC=00:00:00:00:00:00

# Set the virtio-net interface up.
virsh domif-setlink $DOMAIN $TAP_IF up

# Remove the VF that was passthrough'd to the VM.
virsh detach-device --live --config $DOMAIN $VF_XML

ip link set $PF vf $VF_NUM mac $ZERO_MAC

# Add FDB entry for traffic to continue going to the VM via
# the VF -> br0 -> vnet interface path.
bridge fdb add $MAC dev $VF
bridge fdb add $MAC dev $TAP_IF master

# Migrate the VM
virsh migrate --live --persistent $DOMAIN qemu+ssh://$REMOTE_HOST/system

# Clean up FDB entries after migration completes.
bridge fdb del $MAC dev $VF
bridge fdb del $MAC dev $TAP_IF master
```

On the destination hypervisor, a shared bridge 'br0' is created before migration starts, and a VF from the destination PF is added to the bridge. Similarly an appropriate FDB entry is added.

The following script is executed on the destination hypervisor once migration completes, and it reattaches the VF to the VM and brings down the virtio-net interface:



```text
# reattach-vf.sh
#!/bin/bash

bridge fdb del 52:54:00:00:12:53 dev ens36v0
bridge fdb del 52:54:00:00:12:53 dev vmtap01 master
virsh attach-device --config --live vm01 vf.xml
virsh domif-setlink vm01 vmtap01 down
```

---

# Netconsole

_Peios Kernel / Internals / Networking_

> started by Ingo Molnar <mingo@redhat.com>, 2001.09.17

<a id="rst-netconsole"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

started by Ingo Molnar &lt;[mingo@redhat.com](<mailto:mingo@redhat.com>)&gt;, 2001.09.17

2.6 port and netpoll api by Matt Mackall &lt;[mpm@selenic.com](<mailto:mpm@selenic.com>)&gt;, Sep 9 2003

IPv6 support by Cong Wang &lt;[xiyou.wangcong@gmail.com](<mailto:xiyou.wangcong@gmail.com>)&gt;, Jan 1 2013

Extended console support by Tejun Heo &lt;[tj@kernel.org](<mailto:tj@kernel.org>)&gt;, May 1 2015

Release prepend support by Breno Leitao &lt;[leitao@debian.org](<mailto:leitao@debian.org>)&gt;, Jul 7 2023

Userdata append support by Matthew Wood &lt;[thepacketgeek@gmail.com](<mailto:thepacketgeek@gmail.com>)&gt;, Jan 22 2024

Sysdata append support by Breno Leitao &lt;[leitao@debian.org](<mailto:leitao@debian.org>)&gt;, Jan 15 2025

<a id="rst-introduction"></a>

## Introduction:

This module logs kernel printk messages over UDP allowing debugging of problem where disk logging fails and serial consoles are impractical.

It can be used either built-in or as a module. As a built-in, netconsole initializes immediately after NIC cards and will bring up the specified interface as soon as possible. While this doesn't allow capture of early kernel panics, it does capture most of the boot process.

<a id="rst-sender-and-receiver-configuration"></a>

## Sender and receiver configuration:

It takes a string configuration parameter "netconsole" in the following format:



```text
netconsole=[+][r][src-port]@[src-ip]/[<dev>],[tgt-port]@<tgt-ip>/[tgt-macaddr]

  where
       +             if present, enable extended console support
       r             if present, prepend kernel version (release) to the message
       src-port      source for UDP packets (defaults to 6665)
       src-ip        source IP to use (interface address)
       dev           network interface name (eth0) or MAC address
       tgt-port      port for logging agent (6666)
       tgt-ip        IP address for logging agent
       tgt-macaddr   ethernet MAC address for logging agent (broadcast)
```

Examples:



```text
linux netconsole=4444@10.0.0.1/eth1,9353@10.0.0.2/12:34:56:78:9a:bc
```

or:



```text
insmod netconsole netconsole=@/,@10.0.0.2/
```

or using IPv6:



```text
insmod netconsole netconsole=@/,@fd00:1:2:3::1/
```

or using a MAC address to select the egress interface:



```text
linux netconsole=4444@10.0.0.1/22:33:44:55:66:77,9353@10.0.0.2/12:34:56:78:9a:bc
```

It also supports logging to multiple remote agents by specifying parameters for the multiple agents separated by semicolons and the complete string enclosed in "quotes", thusly:



```text
modprobe netconsole netconsole="@/,@10.0.0.2/;@/eth1,6892@10.0.0.3/"
```

Built-in netconsole starts immediately after the TCP stack is initialized and attempts to bring up the supplied dev at the supplied address.

The remote host has several options to receive the kernel messages, for example:

1. syslogd

2. netcat

   On distributions using a BSD-based netcat version (e.g. Fedora, openSUSE and Ubuntu) the listening port must be specified without the -p switch:



   ```text
   nc -u -l -p <port>' / 'nc -u -l <port>
   ```

   or:



   ```text
   netcat -u -l -p <port>' / 'netcat -u -l <port>
   ```

3. socat



```text
socat udp-recv:<port> -
```

<a id="rst-dynamic-reconfiguration"></a>

## Dynamic reconfiguration:

Dynamic reconfigurability is a useful addition to netconsole that enables remote logging targets to be dynamically added, removed, or have their parameters reconfigured at runtime from a configfs-based userspace interface.

To include this feature, select CONFIG_NETCONSOLE_DYNAMIC when building the netconsole module (or kernel, if netconsole is built-in).

Some examples follow (where configfs is mounted at the /sys/kernel/config mountpoint).

To add a remote logging target (target names can be arbitrary):



```text
cd /sys/kernel/config/netconsole/
mkdir target1
```

Note that newly created targets have default parameter values (as mentioned above) and are disabled by default -- they must first be enabled by writing "1" to the "enabled" attribute (usually after setting parameters accordingly) as described below.

To remove a target:



```text
rmdir /sys/kernel/config/netconsole/othertarget/
```

The interface exposes these parameters of a netconsole target to userspace:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> enabled
>
> </td>
> <td>
>
>
> Is this target currently enabled?
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> extended
>
> </td>
> <td>
>
>
> Extended mode enabled
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> release
>
> </td>
> <td>
>
>
> Prepend kernel release to message
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> dev_name
>
> </td>
> <td>
>
>
> Local network interface name
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> local_port
>
> </td>
> <td>
>
>
> Source UDP port to use
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> remote_port
>
> </td>
> <td>
>
>
> Remote agent's UDP port
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> local_ip
>
> </td>
> <td>
>
>
> Source IP address to use
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> remote_ip
>
> </td>
> <td>
>
>
> Remote agent's IP address
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> local_mac
>
> </td>
> <td>
>
>
> Local interface's MAC address
>
> </td>
> <td>
>
>
> (read-only)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> remote_mac
>
> </td>
> <td>
>
>
> Remote agent's MAC address
>
> </td>
> <td>
>
>
> (read-write)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> transmit_errors
>
> </td>
> <td>
>
>
> Number of packet send errors
>
> </td>
> <td>
>
>
> (read-only)
>
> </td>
> </tr>
> </tbody>
> </table>

The "enabled" attribute is also used to control whether the parameters of a target can be updated or not -- you can modify the parameters of only disabled targets (i.e. if "enabled" is 0).

To update a target's parameters:



```text
cat enabled                            # check if enabled is 1
echo 0 > enabled                       # disable the target (if required)
echo eth2 > dev_name                   # set local interface
echo 10.0.0.4 > remote_ip              # update some parameter
echo cb:a9:87:65:43:21 > remote_mac    # update more parameters
echo 1 > enabled                       # enable target again
```

You can also update the local interface dynamically. This is especially useful if you want to use interfaces that have newly come up (and may not have existed when netconsole was loaded / initialized).

Netconsole targets defined at boot time (or module load time) with the `netconsole=` param are assigned the name `cmdline<index>`.  For example, the first target in the parameter is named `cmdline0`.  You can control and modify these targets by creating configfs directories with the matching name.

Let's suppose you have two netconsole targets defined at boot time:



```text
netconsole=4444@10.0.0.1/eth1,9353@10.0.0.2/12:34:56:78:9a:bc;4444@10.0.0.1/eth1,9353@10.0.0.3/12:34:56:78:9a:bc
```

You can modify these targets in runtime by creating the following targets:



```text
mkdir cmdline0
cat cmdline0/remote_ip
10.0.0.2

mkdir cmdline1
cat cmdline1/remote_ip
10.0.0.3
```

<a id="rst-append-user-data"></a>

### Append User Data

Custom user data can be appended to the end of messages with netconsole dynamic configuration enabled. User data entries can be modified without changing the "enabled" attribute of a target.

Directories (keys) under `userdata` are limited to 53 character length, and data in `userdata/<key>/value` are limited to 200 bytes:



```text
cd /sys/kernel/config/netconsole && mkdir cmdline0
cd cmdline0
mkdir userdata/foo
echo bar > userdata/foo/value
mkdir userdata/qux
echo baz > userdata/qux/value
```

Messages will now include this additional user data:



```text
echo "This is a message" > /dev/kmsg
```

Sends:



```text
12,607,22085407756,-;This is a message
 foo=bar
 qux=baz
```

Preview the userdata that will be appended with:



```text
cd /sys/kernel/config/netconsole/cmdline0/userdata
for f in `ls userdata`; do echo $f=$(cat userdata/$f/value); done
```

If a `userdata` entry is created but no data is written to the `value` file, the entry will be omitted from netconsole messages:



```text
cd /sys/kernel/config/netconsole && mkdir cmdline0
cd cmdline0
mkdir userdata/foo
echo bar > userdata/foo/value
mkdir userdata/qux
```

The `qux` key is omitted since it has no value:



```text
echo "This is a message" > /dev/kmsg
12,607,22085407756,-;This is a message
 foo=bar
```

Delete `userdata` entries with `rmdir`:



```text
rmdir /sys/kernel/config/netconsole/cmdline0/userdata/qux
```

> [!WARNING]
>
> When writing strings to user data values, input is broken up per line in configfs store calls and this can cause confusing behavior:
>
>
>
> ```text
> mkdir userdata/testing
> printf "val1\nval2" > userdata/testing/value
> # userdata store value is called twice, first with "val1\n" then "val2"
> # so "val2" is stored, being the last value stored
> cat userdata/testing/value
> val2
> ```
>
> It is recommended to not write user data values with newlines.

<a id="rst-task-name-auto-population-in-userdata"></a>

### Task name auto population in userdata

Inside the netconsole configfs hierarchy, there is a file called `taskname_enabled` under the `userdata` directory. This file is used to enable or disable the automatic task name population feature. This feature automatically populates the current task name that is scheduled in the CPU sneding the message.

To enable task name auto-population:



```text
echo 1 > /sys/kernel/config/netconsole/target1/userdata/taskname_enabled
```

When this option is enabled, the netconsole messages will include an additional line in the userdata field with the format `taskname=<task name>`. This allows the receiver of the netconsole messages to easily find which application was currently scheduled when that message was generated, providing extra context for kernel messages and helping to categorize them.

Example:



```text
echo "This is a message" > /dev/kmsg
12,607,22085407756,-;This is a message
 taskname=echo
```

In this example, the message was generated while "echo" was the current scheduled process.

<a id="rst-kernel-release-auto-population-in-userdata"></a>

### Kernel release auto population in userdata

Within the netconsole configfs hierarchy, there is a file named `release_enabled` located in the `userdata` directory. This file controls the kernel release (version) auto-population feature, which appends the kernel release information to userdata dictionary in every message sent.

To enable the release auto-population:



```text
echo 1 > /sys/kernel/config/netconsole/target1/userdata/release_enabled
```

Example:



```text
echo "This is a message" > /dev/kmsg
12,607,22085407756,-;This is a message
 release=6.14.0-rc6-01219-g3c027fbd941d
```

> [!NOTE]
>
> This feature provides the same data as the "release prepend" feature. However, in this case, the release information is appended to the userdata dictionary rather than being included in the message header.

<a id="rst-cpu-number-auto-population-in-userdata"></a>

### CPU number auto population in userdata

Inside the netconsole configfs hierarchy, there is a file called `cpu_nr` under the `userdata` directory. This file is used to enable or disable the automatic CPU number population feature. This feature automatically populates the CPU number that is sending the message.

To enable the CPU number auto-population:



```text
echo 1 > /sys/kernel/config/netconsole/target1/userdata/cpu_nr
```

When this option is enabled, the netconsole messages will include an additional line in the userdata field with the format `cpu=<cpu_number>`. This allows the receiver of the netconsole messages to easily differentiate and demultiplex messages originating from different CPUs, which is particularly useful when dealing with parallel log output.

Example:



```text
echo "This is a message" > /dev/kmsg
12,607,22085407756,-;This is a message
 cpu=42
```

In this example, the message was sent by CPU 42.

> [!NOTE]
>
> If the user has set a conflicting `cpu` key in the userdata dictionary, both keys will be reported, with the kernel-populated entry appearing after the user one. For example:
>
>
>
> ```text
> # User-defined CPU entry
> mkdir -p /sys/kernel/config/netconsole/target1/userdata/cpu
> echo "1" > /sys/kernel/config/netconsole/target1/userdata/cpu/value
> ```
>
> Output might look like:
>
>
>
> ```text
> 12,607,22085407756,-;This is a message
>  cpu=1
>  cpu=42    # kernel-populated value
> ```

<a id="rst-message-id-auto-population-in-userdata"></a>

### Message ID auto population in userdata

Within the netconsole configfs hierarchy, there is a file named `msgid_enabled` located in the `userdata` directory. This file controls the message ID auto-population feature, which assigns a numeric id to each message sent to a given target and appends the ID to userdata dictionary in every message sent.

The message ID is generated using a per-target 32 bit counter that is incremented for every message sent to the target. Note that this counter will eventually wrap around after reaching uint32_t max value, so the message ID is not globally unique over time. However, it can still be used by the target to detect if messages were dropped before reaching the target by identifying gaps in the sequence of IDs.

It is important to distinguish message IDs from the message &lt;sequnum&gt; field. Some kernel messages may never reach netconsole (for example, due to printk rate limiting). Thus, a gap in &lt;sequnum&gt; cannot be solely relied upon to indicate that a message was dropped during transmission, as it may never have been sent via netconsole. The message ID, on the other hand, is only assigned to messages that are actually transmitted via netconsole.

Example:



```text
echo "This is message #1" > /dev/kmsg
echo "This is message #2" > /dev/kmsg
13,434,54928466,-;This is message #1
 msgid=1
13,435,54934019,-;This is message #2
 msgid=2
```

<a id="rst-extended-console"></a>

## Extended console:

If '+' is prefixed to the configuration line or "extended" config file is set to 1, extended console support is enabled. An example boot param follows:



```text
linux netconsole=+4444@10.0.0.1/eth1,9353@10.0.0.2/12:34:56:78:9a:bc
```

Log messages are transmitted with extended metadata header in the following format which is the same as /dev/kmsg:



```text
<level>,<sequnum>,<timestamp>,<contflag>;<message text>
```

If 'r' (release) feature is enabled, the kernel release version is prepended to the start of the message. Example:



```text
6.4.0,6,444,501151268,-;netconsole: network logging started
```

Non printable characters in &lt;message text&gt; are escaped using "xff" notation. If the message contains optional dictionary, verbatim newline is used as the delimiter.

If a message doesn't fit in certain number of bytes (currently 1000), the message is split into multiple fragments by netconsole. These fragments are transmitted with "ncfrag" header field added:



```text
ncfrag=<byte-offset>/<total-bytes>
```

For example, assuming a lot smaller chunk size, a message "the first chunk, the 2nd chunk." may be split as follows:



```text
6,416,1758426,-,ncfrag=0/31;the first chunk,
6,416,1758426,-,ncfrag=16/31; the 2nd chunk.
```

<a id="rst-miscellaneous-notes"></a>

## Miscellaneous notes:

> [!WARNING]
>
> the default target ethernet setting uses the broadcast ethernet address to send packets, which can cause increased load on other systems on the same ethernet segment.

> [!TIP]
>
> some LAN switches may be configured to suppress ethernet broadcasts so it is advised to explicitly specify the remote agents' MAC addresses from the config parameters passed to netconsole.

> [!TIP]
>
> to find out the MAC address of, say, 10.0.0.2, you may try using:
>
>
>
> ```text
> ping -c 1 10.0.0.2 ; /sbin/arp -n | grep 10.0.0.2
> ```

> [!TIP]
>
> in case the remote logging agent is on a separate LAN subnet than the sender, it is suggested to try specifying the MAC address of the default gateway (you may use /sbin/route -n to find it out) as the remote MAC address instead.

> [!NOTE]
>
> the network device (eth1 in the above case) can run any kind of other network traffic, netconsole is not intrusive. Netconsole might cause slight delays in other traffic if the volume of kernel messages is high, but should have no other impact.

> [!NOTE]
>
> if you find that the remote logging agent is not receiving or printing all messages from the sender, it is likely that you have set the "console_loglevel" parameter (on the sender) to only send high priority messages to the console. You can change this at runtime using:
>
>
>
> ```text
> dmesg -n 8
> ```
>
> or by specifying "debug" on the kernel command line at boot, to send all kernel messages to the console. A specific value for this parameter can also be set using the "loglevel" kernel boot option. See the dmesg(8) man page and [Documentation/admin-guide/kernel-parameters.rst](/kernel/administration/admin-guide/boot/kernel-parameters.md) for details.

Netconsole was designed to be as instantaneous as possible, to enable the logging of even the most critical kernel bugs. It works from IRQ contexts as well, and does not enable interrupts while sending packets. Due to these unique needs, configuration cannot be more automatic, and some fundamental limitations will remain: only IP networks, UDP packets and ethernet devices are supported.

---

# Netdev features mess and how to get out from it alive

_Peios Kernel / Internals / Networking_

> Michał Mirosław <mirq-linux@rere.qmqm.pl>

<a id="rst-netdev-features-mess-and-how-to-get-out-from-it-alive"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Author:**

  Michał Mirosław &lt;[mirq-linux@rere.qmqm.pl](<mailto:mirq-linux@rere.qmqm.pl>)&gt;

<a id="rst-part-i-feature-sets"></a>

## Part I: Feature sets

Long gone are the days when a network card would just take and give packets verbatim.  Today's devices add multiple features and bugs (read: offloads) that relieve an OS of various tasks like generating and checking checksums, splitting packets, classifying them.  Those capabilities and their state are commonly referred to as netdev features in Linux kernel world.

There are currently three sets of features relevant to the driver, and one used internally by network core:

> 1. netdev-&gt;hw_features set contains features whose state may possibly be changed (enabled or disabled) for a particular device by user's request.  This set should be initialized in ndo_init callback and not changed later.
>
> 2. netdev-&gt;features set contains features which are currently enabled for a device.  This should be changed only by network core or in error paths of ndo_set_features callback.
>
> 3. netdev-&gt;vlan_features set contains features whose state is inherited by child VLAN devices (limits netdev-&gt;features set).  This is currently used for all VLAN devices whether tags are stripped or inserted in hardware or software.
>
> 4. netdev-&gt;wanted_features set contains feature set requested by user. This set is filtered by ndo_fix_features callback whenever it or some device-specific conditions change. This set is internal to networking core and should not be referenced in drivers.

<a id="rst-part-ii-controlling-enabled-features"></a>

## Part II: Controlling enabled features

When current feature set (netdev-&gt;features) is to be changed, new set is calculated and filtered by calling ndo_fix_features callback and netdev_fix_features(). If the resulting set differs from current set, it is passed to ndo_set_features callback and (if the callback returns success) replaces value stored in netdev-&gt;features. NETDEV_FEAT_CHANGE notification is issued after that whenever current set might have changed.

- **The following events trigger recalculation:**

  1. device's registration, after ndo_init returned success

  2. user requested changes in features state

  3. netdev_update_features() is called

ndo\_\*\_features callbacks are called with rtnl_lock held. Missing callbacks are treated as always returning success.

A driver that wants to trigger recalculation must do so by calling netdev_update_features() while holding rtnl_lock. This should not be done from ndo\_\*\_features callbacks. netdev-&gt;features should not be modified by driver except by means of ndo_fix_features callback.

<a id="rst-part-iii-implementation-hints"></a>

## Part III: Implementation hints

> - ndo_fix_features:

All dependencies between features should be resolved here. The resulting set can be reduced further by networking core imposed limitations (as coded in netdev_fix_features()). For this reason it is safer to disable a feature when its dependencies are not met instead of forcing the dependency on.

This callback should not modify hardware nor driver state (should be stateless).  It can be called multiple times between successive ndo_set_features calls.

Callback must not alter features contained in NETIF_F_SOFT_FEATURES or NETIF_F_NEVER_CHANGE sets. The exception is NETIF_F_VLAN_CHALLENGED but care must be taken as the change won't affect already configured VLANs.

> - ndo_set_features:

Hardware should be reconfigured to match passed feature set. The set should not be altered unless some error condition happens that can't be reliably detected in ndo_fix_features. In this case, the callback should update netdev-&gt;features to match resulting hardware state. Errors returned are not (and cannot be) propagated anywhere except dmesg. (Note: successful return is zero, &gt;0 means silent error.)

<a id="rst-part-iv-features"></a>

## Part IV: Features

For current list of features, see include/linux/netdev_features.h. This section describes semantics of some of them.

> - Transmit checksumming

For complete description, see comments near the top of include/linux/skbuff.h.

Note: NETIF_F_HW_CSUM is a superset of NETIF_F_IP_CSUM + NETIF_F_IPV6_CSUM. It means that device can fill TCP/UDP-like checksum anywhere in the packets whatever headers there might be.

> - Transmit TCP segmentation offload

NETIF_F_TSO_ECN means that hardware can properly split packets with CWR bit set, be it TCPv4 (when NETIF_F_TSO is enabled) or TCPv6 (NETIF_F_TSO6).

> - Transmit UDP segmentation offload

NETIF_F_GSO_UDP_L4 accepts a single UDP header with a payload that exceeds gso_size. On segmentation, it segments the payload on gso_size boundaries and replicates the network and UDP headers (fixing up the last one if less than gso_size).

> - Transmit DMA from high memory

On platforms where this is relevant, NETIF_F_HIGHDMA signals that ndo_start_xmit can handle skbs with frags in high memory.

> - Transmit scatter-gather

Those features say that ndo_start_xmit can handle fragmented skbs: NETIF_F_SG --- paged skbs (skb_shinfo()-&gt;frags), NETIF_F_FRAGLIST --- chained skbs (skb-&gt;next/prev list).

> - Software features

Features contained in NETIF_F_SOFT_FEATURES are features of networking stack. Driver should not change behaviour based on them.

> - VLAN challenged

NETIF_F_VLAN_CHALLENGED should be set for devices which can't cope with VLAN headers. Some drivers set this because the cards can't handle the bigger MTU. \[FIXME: Those cases could be fixed in VLAN code by allowing only reduced-MTU VLANs. This may be not useful, though.\]

- rx-fcs

This requests that the NIC append the Ethernet Frame Checksum (FCS) to the end of the skb data.  This allows sniffers and other tools to read the CRC recorded by the NIC on receipt of the packet.

- rx-all

This requests that the NIC receive all possible frames, including errored frames (such as bad FCS, etc).  This can be helpful when sniffing a link with bad packets on it.  Some NICs may receive more packets if also put into normal PROMISC mode.

- rx-gro-hw

This requests that the NIC enables Hardware GRO (generic receive offload). Hardware GRO is basically the exact reverse of TSO, and is generally stricter than Hardware LRO.  A packet stream merged by Hardware GRO must be re-segmentable by GSO or TSO back to the exact original packet stream. Hardware GRO is dependent on RXCSUM since every packet successfully merged by hardware must also have the checksum verified by hardware.

- hsr-tag-ins-offload

This should be set for devices which insert an HSR (High-availability Seamless Redundancy) or PRP (Parallel Redundancy Protocol) tag automatically.

- hsr-tag-rm-offload

This should be set for devices which remove HSR (High-availability Seamless Redundancy) or PRP (Parallel Redundancy Protocol) tags automatically.

- hsr-fwd-offload

This should be set for devices which forward HSR (High-availability Seamless Redundancy) frames from one port to another in hardware.

- hsr-dup-offload

This should be set for devices which duplicate outgoing HSR (High-availability Seamless Redundancy) or PRP (Parallel Redundancy Protocol) tags automatically frames in hardware.

- netmem-tx

This should be set for devices which support netmem TX. See [Documentation/networking/netmem.rst](/kernel/internals/networking/netmem.md)

---

# Network Devices, the Kernel, and You!

_Peios Kernel / Internals / Networking_

> The following is a random collection of documentation regarding network devices. It is intended for driver developers.

<a id="rst-network-devices-the-kernel-and-you"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The following is a random collection of documentation regarding network devices. It is intended for driver developers.

<a id="rst-struct-net-device-lifetime-rules"></a>

## struct net_device lifetime rules

Network device structures need to persist even after module is unloaded and must be allocated with alloc_netdev_mqs() and friends. If device has registered successfully, it will be freed on last use by free_netdev(). This is required to handle the pathological case cleanly (example: `rmmod mydriver </sys/class/net/myeth/mtu`)

alloc_netdev_mqs() / alloc_netdev() reserve extra space for driver private data which gets freed when the network device is freed. If separately allocated data is attached to the network device (netdev_priv()) then it is up to the module exit handler to free that.

There are two groups of APIs for registering struct net_device. First group can be used in normal contexts where `rtnl_lock` is not already held: register_netdev(), unregister_netdev(). Second group can be used when `rtnl_lock` is already held: register_netdevice(), unregister_netdevice(), free_netdevice().

<a id="rst-simple-drivers"></a>

### Simple drivers

Most drivers (especially device drivers) handle lifetime of struct net_device in context where `rtnl_lock` is not held (e.g. driver probe and remove paths).

In that case the struct net_device registration is done using the register_netdev(), and unregister_netdev() functions:



```c
int probe()
{
  struct my_device_priv *priv;
  int err;

  dev = alloc_netdev_mqs(...);
  if (!dev)
    return -ENOMEM;
  priv = netdev_priv(dev);

  /* ... do all device setup before calling register_netdev() ...
   */

  err = register_netdev(dev);
  if (err)
    goto err_undo;

  /* net_device is visible to the user! */

err_undo:
  /* ... undo the device setup ... */
  free_netdev(dev);
  return err;
}

void remove()
{
  unregister_netdev(dev);
  free_netdev(dev);
}
```

Note that after calling register_netdev() the device is visible in the system. Users can open it and start sending / receiving traffic immediately, or run any other callback, so all initialization must be done prior to registration.

unregister_netdev() closes the device and waits for all users to be done with it. The memory of struct net_device itself may still be referenced by sysfs but all operations on that device will fail.

free_netdev() can be called after unregister_netdev() returns or when register_netdev() failed.

<a id="rst-device-management-under-rtnl"></a>

### Device management under RTNL

Registering struct net_device while in context which already holds the `rtnl_lock` requires extra care. In those scenarios most drivers will want to make use of struct net_device's `needs_free_netdev` and `priv_destructor` members for freeing of state.

Example flow of netdev handling under `rtnl_lock`:



```c
static void my_setup(struct net_device *dev)
{
  dev->needs_free_netdev = true;
}

static void my_destructor(struct net_device *dev)
{
  some_obj_destroy(priv->obj);
  some_uninit(priv);
}

int create_link()
{
  struct my_device_priv *priv;
  int err;

  ASSERT_RTNL();

  dev = alloc_netdev(sizeof(*priv), "net%d", NET_NAME_UNKNOWN, my_setup);
  if (!dev)
    return -ENOMEM;
  priv = netdev_priv(dev);

  /* Implicit constructor */
  err = some_init(priv);
  if (err)
    goto err_free_dev;

  priv->obj = some_obj_create();
  if (!priv->obj) {
    err = -ENOMEM;
    goto err_some_uninit;
  }
  /* End of constructor, set the destructor: */
  dev->priv_destructor = my_destructor;

  err = register_netdevice(dev);
  if (err)
    /* register_netdevice() calls destructor on failure */
    goto err_free_dev;

  /* If anything fails now unregister_netdevice() (or unregister_netdev())
   * will take care of calling my_destructor and free_netdev().
   */

  return 0;

err_some_uninit:
  some_uninit(priv);
err_free_dev:
  free_netdev(dev);
  return err;
}
```

If struct net_device.priv_destructor is set it will be called by the core some time after unregister_netdevice(), it will also be called if register_netdevice() fails. The callback may be invoked with or without `rtnl_lock` held.

There is no explicit constructor callback, driver "constructs" the private netdev state after allocating it and before registration.

Setting struct net_device.needs_free_netdev makes core call free_netdevice() automatically after unregister_netdevice() when all references to the device are gone. It only takes effect after a successful call to register_netdevice() so if register_netdevice() fails driver is responsible for calling free_netdev().

free_netdev() is safe to call on error paths right after unregister_netdevice() or when register_netdevice() fails. Parts of netdev (de)registration process happen after `rtnl_lock` is released, therefore in those cases free_netdev() will defer some of the processing until `rtnl_lock` is released.

Devices spawned from struct rtnl_link_ops should never free the struct net_device directly.

<a id="rst-ndo-init-and-ndo-uninit"></a>

#### .ndo_init and .ndo_uninit

`.ndo_init` and `.ndo_uninit` callbacks are called during net_device registration and de-registration, under `rtnl_lock`. Drivers can use those e.g. when parts of their init process need to run under `rtnl_lock`.

`.ndo_init` runs before device is visible in the system, `.ndo_uninit` runs during de-registering after device is closed but other subsystems may still have outstanding references to the netdevice.

<a id="rst-mtu"></a>

## MTU

Each network device has a Maximum Transfer Unit. The MTU does not include any link layer protocol overhead. Upper layer protocols must not pass a socket buffer (skb) to a device to transmit with more data than the mtu. The MTU does not include link layer header overhead, so for example on Ethernet if the standard MTU is 1500 bytes used, the actual skb will contain up to 1514 bytes because of the Ethernet header. Devices should allow for the 4 byte VLAN header as well.

Segmentation Offload (GSO, TSO) is an exception to this rule.  The upper layer protocol may pass a large socket buffer to the device transmit routine, and the device will break that up into separate packets based on the current MTU.

MTU is symmetrical and applies both to receive and transmit. A device must be able to receive at least the maximum size packet allowed by the MTU. A network device may use the MTU as mechanism to size receive buffers, but the device should allow packets with VLAN header. With standard Ethernet mtu of 1500 bytes, the device should allow up to 1518 byte packets (1500 + 14 header + 4 tag).  The device may either: drop, truncate, or pass up oversize packets, but dropping oversize packets is preferred.

<a id="rst-struct-net-device-synchronization-rules"></a>

## struct net_device synchronization rules

- **ndo_open:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process

- **ndo_stop:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process Note: netif_running() is guaranteed false

- **ndo_do_ioctl:**

  Synchronization: rtnl_lock() semaphore.

  This is only called by network subsystems internally, not by user space calling ioctl as it was in before linux-5.14.

- **ndo_siocbond:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process

  Used by the bonding driver for the SIOCBOND family of ioctl commands.

- **ndo_siocwandev:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process

  Used by the drivers/net/wan framework to handle the SIOCWANDEV ioctl with the if_settings structure.

- **ndo_siocdevprivate:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process

  This is used to implement SIOCDEVPRIVATE ioctl helpers. These should not be added to new drivers, so don't use.

- **ndo_eth_ioctl:**

  Synchronization: rtnl_lock() semaphore. In addition, netdev instance lock if the driver implements queue management or shaper API. Context: process

- **ndo_get_stats:**

  Synchronization: RCU (can be called concurrently with the stats update path). Context: atomic (can't sleep under RCU)

- **ndo_start_xmit:**

  Synchronization: \__netif_tx_lock spinlock.

  When the driver sets dev-&gt;lltx this will be called without holding netif_tx_lock. In this case the driver has to lock by itself when needed. The locking there should also properly protect against set_rx_mode. WARNING: use of dev-&gt;lltx is deprecated. Don't use it for new drivers.

  - **Context: Process with BHs disabled or BH (timer),**

    will be called with interrupts disabled by netconsole.

  Return codes:

  - NETDEV_TX_OK everything ok.

  - NETDEV_TX_BUSY Cannot transmit packet, try later Usually a bug, means queue start/stop flow control is broken in the driver. Note: the driver must NOT put the skb in its DMA ring.

- **ndo_tx_timeout:**

  Synchronization: netif_tx_lock spinlock; all TX queues frozen. Context: BHs disabled Notes: netif_queue_stopped() is guaranteed true

- **ndo_set_rx_mode:**

  Synchronization: netif_addr_lock spinlock. Context: BHs disabled

- **ndo_setup_tc:**

  `TC_SETUP_BLOCK` and `TC_SETUP_FT` are running under NFT locks (i.e. no `rtnl_lock` and no device instance lock). The rest of `tc_setup_type` types run under netdev instance lock if the driver implements queue management or shaper API.

Most ndo callbacks not specified in the list above are running under `rtnl_lock`. In addition, netdev instance lock is taken as well if the driver implements queue management or shaper API.

<a id="rst-struct-napi-struct-synchronization-rules"></a>

## struct napi_struct synchronization rules

- **napi-&gt;poll:**

  - **Synchronization:**

    NAPI_STATE_SCHED bit in napi-&gt;state.  Device driver's ndo_stop method will invoke napi_disable() on all NAPI instances which will do a sleeping poll on the NAPI_STATE_SCHED napi-&gt;state bit, waiting for all pending NAPI activity to cease.

  - **Context:**

    softirq will be called with interrupts disabled by netconsole.

<a id="rst-netdev-instance-lock"></a>

## netdev instance lock

Historically, all networking control operations were protected by a single global lock known as `rtnl_lock`. There is an ongoing effort to replace this global lock with separate locks for each network namespace. Additionally, properties of individual netdev are increasingly protected by per-netdev locks.

For device drivers that implement shaping or queue management APIs, all control operations will be performed under the netdev instance lock. Drivers can also explicitly request instance lock to be held during ops by setting `request_ops_lock` to true. Code comments and docs refer to drivers which have ops called under the instance lock as "ops locked". See also the documentation of the `lock` member of struct net_device.

In the future, there will be an option for individual drivers to opt out of using `rtnl_lock` and instead perform their control operations directly under the netdev instance lock.

Device drivers are encouraged to rely on the instance lock where possible.

For the (mostly software) drivers that need to interact with the core stack, there are two sets of interfaces: `dev_xxx`/`netdev_xxx` and `netif_xxx` (e.g., `dev_set_mtu` and `netif_set_mtu`). The `dev_xxx`/`netdev_xxx` functions handle acquiring the instance lock themselves, while the `netif_xxx` functions assume that the driver has already acquired the instance lock.

<a id="rst-struct-net-device-ops"></a>

### struct net_device_ops

`ndos` are called without holding the instance lock for most drivers.

"Ops locked" drivers will have most of the `ndos` invoked under the instance lock.

<a id="rst-struct-ethtool-ops"></a>

### struct ethtool_ops

Similarly to `ndos` the instance lock is only held for select drivers. For "ops locked" drivers all ethtool ops without exceptions should be called under the instance lock.

<a id="rst-struct-netdev-stat-ops"></a>

### struct netdev_stat_ops

"qstat" ops are invoked under the instance lock for "ops locked" drivers, and under rtnl_lock for all other drivers.

<a id="rst-struct-net-shaper-ops"></a>

### struct net_shaper_ops

All net shaper callbacks are invoked while holding the netdev instance lock. `rtnl_lock` may or may not be held.

Note that supporting net shapers automatically enables "ops locking".

<a id="rst-struct-netdev-queue-mgmt-ops"></a>

### struct netdev_queue_mgmt_ops

All queue management callbacks are invoked while holding the netdev instance lock. `rtnl_lock` may or may not be held.

Note that supporting struct netdev_queue_mgmt_ops automatically enables "ops locking".

<a id="rst-notifiers-and-netdev-instance-lock"></a>

### Notifiers and netdev instance lock

For device drivers that implement shaping or queue management APIs, some of the notifiers (`enum netdev_cmd`) are running under the netdev instance lock.

The following netdev notifiers are always run under the instance lock: \* `NETDEV_XDP_FEAT_CHANGE`

For devices with locked ops, currently only the following notifiers are running under the lock: \* `NETDEV_CHANGE` \* `NETDEV_REGISTER` \* `NETDEV_UP`

The following notifiers are running without the lock: \* `NETDEV_UNREGISTER`

There are no clear expectations for the remaining notifiers. Notifiers not on the list may run with or without the instance lock, potentially even invoking the same notifier type with and without the lock from different code paths. The goal is to eventually ensure that all (or most, with a few documented exceptions) notifiers run under the instance lock. Please extend this documentation whenever you make explicit assumption about lock being held from a notifier.

<a id="rst-netdev-internal-symbol-namespace"></a>

## NETDEV_INTERNAL symbol namespace

Symbols exported as NETDEV_INTERNAL can only be used in networking core and drivers which exclusively flow via the main networking list and trees. Note that the inverse is not true, most symbols outside of NETDEV_INTERNAL are not expected to be used by random code outside netdev either. Symbols may lack the designation because they predate the namespaces, or simply due to an oversight.

---

# Netfilter Sysfs variables

_Peios Kernel / Internals / Networking_

> 0 - disabled (default)

<a id="rst-netfilter-sysfs-variables"></a>

<a id="rst-proc-sys-net-netfilter-variables"></a>

## /proc/sys/net/netfilter/\* Variables:

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **nf_log_all_netns - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  By default, only init_net namespace can log packets into kernel log with LOG target; this aims to prevent containers from flooding host kernel log. If enabled, this target also works in other network namespaces. This variable is only accessible from init_net.

---

# NETIF Msg Level

_Peios Kernel / Internals / Networking_

> The design of the network interface message level setting.

<a id="rst-netif-msg-level"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The design of the network interface message level setting.

<a id="rst-history"></a>

## History

> The design of the debugging message interface was guided and constrained by backwards compatibility previous practice.  It is useful to understand the history and evolution in order to understand current practice and relate it to older driver source code.
>
> From the beginning of Linux, each network device driver has had a local integer variable that controls the debug message level.  The message level ranged from 0 to 7, and monotonically increased in verbosity.
>
> The message level was not precisely defined past level 3, but were always implemented within +-1 of the specified level.  Drivers tended to shed the more verbose level messages as they matured.
>
> > - 0  Minimal messages, only essential information on fatal errors.
> >
> > - 1  Standard messages, initialization status.  No run-time messages
> >
> > - 2  Special media selection messages, generally timer-driver.
> >
> > - 3  Interface starts and stops, including normal status messages
> >
> > - 4  Tx and Rx frame error messages, and abnormal driver operation
> >
> > - 5  Tx packet queue information, interrupt events.
> >
> > - 6  Status on each completed Tx packet and received Rx packets
> >
> > - 7  Initial contents of Tx and Rx packets
>
> Initially this message level variable was uniquely named in each driver e.g. "lance_debug", so that a kernel symbolic debugger could locate and modify the setting.  When kernel modules became common, the variables were consistently renamed to "debug" and allowed to be set as a module parameter.
>
> This approach worked well.  However there is always a demand for additional features.  Over the years the following emerged as reasonable and easily implemented enhancements
>
> > - Using an ioctl() call to modify the level.
> >
> > - Per-interface rather than per-driver message level setting.
> >
> > - More selective control over the type of messages emitted.
>
> The netif_msg recommendation adds these features with only a minor complexity and code size increase.
>
> The recommendation is the following points
>
> > - Retaining the per-driver integer variable "debug" as a module parameter with a default level of '1'.
> >
> > - Adding a per-interface private variable named "msg_enable".  The variable is a bit map rather than a level, and is initialized as:
> >
> >
> >
> >   ```text
> >   1 << debug
> >   ```
> >
> >   Or more precisely:
> >
> >
> >
> >   ```text
> >   debug < 0 ? 0 : 1 << min(sizeof(int)-1, debug)
> >   ```
> >
> >   Messages should changes from:
> >
> >
> >
> >   ```text
> >   if (debug > 1)
> >        printk(MSG_DEBUG "%s: ...
> >   ```
> >
> >   to:
> >
> >
> >
> >   ```text
> >   if (np->msg_enable & NETIF_MSG_LINK)
> >        printk(MSG_DEBUG "%s: ...
> >   ```

The set of message levels is named

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Old level
>
> </th>
> <th>
>
>
> Name
>
> </th>
> <th>
>
>
> Bit position
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> NETIF_MSG_DRV
>
> </td>
> <td>
>
>
> 0x0001
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> NETIF_MSG_PROBE
>
> </td>
> <td>
>
>
> 0x0002
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> NETIF_MSG_LINK
>
> </td>
> <td>
>
>
> 0x0004
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> NETIF_MSG_TIMER
>
> </td>
> <td>
>
>
> 0x0004
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> NETIF_MSG_IFDOWN
>
> </td>
> <td>
>
>
> 0x0008
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> NETIF_MSG_IFUP
>
> </td>
> <td>
>
>
> 0x0008
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> NETIF_MSG_RX_ERR
>
> </td>
> <td>
>
>
> 0x0010
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> NETIF_MSG_TX_ERR
>
> </td>
> <td>
>
>
> 0x0010
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> NETIF_MSG_TX_QUEUED
>
> </td>
> <td>
>
>
> 0x0020
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 5
>
> </td>
> <td>
>
>
> NETIF_MSG_INTR
>
> </td>
> <td>
>
>
> 0x0020
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> NETIF_MSG_TX_DONE
>
> </td>
> <td>
>
>
> 0x0040
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 6
>
> </td>
> <td>
>
>
> NETIF_MSG_RX_STATUS
>
> </td>
> <td>
>
>
> 0x0040
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 7
>
> </td>
> <td>
>
>
> NETIF_MSG_PKTDATA
>
> </td>
> <td>
>
>
> 0x0080
>
> </td>
> </tr>
> </tbody>
> </table>

---

# Netmem Support for Network Drivers

_Peios Kernel / Internals / Networking_

> This document outlines the requirements for network drivers to support netmem, an abstract memory type that enables features like device memory TCP. By supporting netmem, drivers can work with various underlying memory types with little to…

<a id="rst-netmem-support-for-network-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document outlines the requirements for network drivers to support netmem, an abstract memory type that enables features like device memory TCP. By supporting netmem, drivers can work with various underlying memory types with little to no modification.

Benefits of Netmem :

- Flexibility: Netmem can be backed by different memory types (e.g., struct page, DMA-buf), allowing drivers to support various use cases such as device memory TCP.

- Future-proof: Drivers with netmem support are ready for upcoming features that rely on it.

- Simplified Development: Drivers interact with a consistent API, regardless of the underlying memory implementation.

<a id="rst-driver-rx-requirements"></a>

## Driver RX Requirements

1. The driver must support page_pool.

2. The driver must support the tcp-data-split ethtool option.

3. The driver must use the page_pool netmem APIs for payload memory. The netmem APIs currently 1-to-1 correspond with page APIs. Conversion to netmem should be achievable by switching the page APIs to netmem APIs and tracking memory via netmem_refs in the driver rather than struct page \* :

   - page_pool_alloc -&gt; page_pool_alloc_netmem

   - page_pool_get_dma_addr -&gt; page_pool_get_dma_addr_netmem

   - page_pool_put_page -&gt; page_pool_put_netmem

   Not all page APIs have netmem equivalents at the moment. If your driver relies on a missing netmem API, feel free to add and propose to netdev@, or reach out to the maintainers and/or [almasrymina@google.com](<mailto:almasrymina@google.com>) for help adding the netmem API.

4. The driver must use the following PP_FLAGS:

   - PP_FLAG_DMA_MAP: netmem is not dma-mappable by the driver. The driver must delegate the dma mapping to the page_pool, which knows when dma-mapping is (or is not) appropriate.

   - PP_FLAG_DMA_SYNC_DEV: netmem dma addr is not necessarily dma-syncable by the driver. The driver must delegate the dma syncing to the page_pool, which knows when dma-syncing is (or is not) appropriate.

   - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff tcp-data-split is enabled.

5. The driver must not assume the netmem is readable and/or backed by pages. The netmem returned by the page_pool may be unreadable, in which case netmem_address() will return NULL. The driver must correctly handle unreadable netmem, i.e. don't attempt to handle its contents when netmem_address() is NULL.

   Ideally, drivers should not have to check the underlying netmem type via helpers like netmem_is_net_iov() or convert the netmem to any of its underlying types via netmem_to_page() or netmem_to_net_iov(). In most cases, netmem or page_pool helpers that abstract this complexity are provided (and more can be added).

6. The driver must use page_pool_dma_sync_netmem_for_cpu() in lieu of dma_sync_single_range_for_cpu(). For some memory providers, dma_syncing for CPU will be done by the page_pool, for others (particularly dmabuf memory provider), dma syncing for CPU is the responsibility of the userspace using dmabuf APIs. The driver must delegate the entire dma-syncing operation to the page_pool which will do it correctly.

7. Avoid implementing driver-specific recycling on top of the page_pool. Drivers cannot hold onto a struct page to do their own recycling as the netmem may not be backed by a struct page. However, you may hold onto a page_pool reference with page_pool_fragment_netmem() or page_pool_ref_netmem() for that purpose, but be mindful that some netmem types might have longer circulation times, such as when userspace holds a reference in zerocopy scenarios.

<a id="rst-driver-tx-requirements"></a>

## Driver TX Requirements

1. The Driver must not pass the netmem dma_addr to any of the dma-mapping APIs directly. This is because netmem dma_addrs may come from a source like dma-buf that is not compatible with the dma-mapping APIs.

   Helpers like netmem_dma_unmap_page_attrs() &amp; netmem_dma_unmap_addr_set() should be used in lieu of dma_unmap_page\[\_attrs\](), dma_unmap_addr_set(). The netmem variants will handle netmem dma_addrs correctly regardless of the source, delegating to the dma-mapping APIs when appropriate.

   Not all dma-mapping APIs have netmem equivalents at the moment. If your driver relies on a missing netmem API, feel free to add and propose to netdev@, or reach out to the maintainers and/or [almasrymina@google.com](<mailto:almasrymina@google.com>) for help adding the netmem API.

2. Driver should declare support by setting `netdev->netmem_tx = true`

---

# Resilient Next-hop Groups

_Peios Kernel / Internals / Networking_

> Resilient groups are a type of next-hop group that is aimed at minimizing disruption in flow routing across changes to the group composition and weights of constituent next hops.

<a id="rst-resilient-next-hop-groups"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Resilient groups are a type of next-hop group that is aimed at minimizing disruption in flow routing across changes to the group composition and weights of constituent next hops.

The idea behind resilient hashing groups is best explained in contrast to the legacy multipath next-hop group, which uses the hash-threshold algorithm, described in RFC 2992.

To select a next hop, hash-threshold algorithm first assigns a range of hashes to each next hop in the group, and then selects the next hop by comparing the SKB hash with the individual ranges. When a next hop is removed from the group, the ranges are recomputed, which leads to reassignment of parts of hash space from one next hop to another. RFC 2992 illustrates it thus:



```text
+-------+-------+-------+-------+-------+
|   1   |   2   |   3   |   4   |   5   |
+-------+-+-----+---+---+-----+-+-------+
|    1    |    2    |    4    |    5    |
+---------+---------+---------+---------+

 Before and after deletion of next hop 3
 under the hash-threshold algorithm.
```

Note how next hop 2 gave up part of the hash space in favor of next hop 1, and 4 in favor of 5. While there will usually be some overlap between the previous and the new distribution, some traffic flows change the next hop that they resolve to.

If a multipath group is used for load-balancing between multiple servers, this hash space reassignment causes an issue that packets from a single flow suddenly end up arriving at a server that does not expect them. This can result in TCP connections being reset.

If a multipath group is used for load-balancing among available paths to the same server, the issue is that different latencies and reordering along the way causes the packets to arrive in the wrong order, resulting in degraded application performance.

To mitigate the above-mentioned flow redirection, resilient next-hop groups insert another layer of indirection between the hash space and its constituent next hops: a hash table. The selection algorithm uses SKB hash to choose a hash table bucket, then reads the next hop that this bucket contains, and forwards traffic there.

This indirection brings an important feature. In the hash-threshold algorithm, the range of hashes associated with a next hop must be continuous. With a hash table, mapping between the hash table buckets and the individual next hops is arbitrary. Therefore when a next hop is deleted the buckets that held it are simply reassigned to other next hops:



```text
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1|1|1|1|2|2|2|2|3|3|3|3|4|4|4|4|5|5|5|5|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                 v v v v
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1|1|1|1|2|2|2|2|1|2|4|5|4|4|4|4|5|5|5|5|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Before and after deletion of next hop 3
under the resilient hashing algorithm.
```

When weights of next hops in a group are altered, it may be possible to choose a subset of buckets that are currently not used for forwarding traffic, and use those to satisfy the new next-hop distribution demands, keeping the "busy" buckets intact. This way, established flows are ideally kept being forwarded to the same endpoints through the same paths as before the next-hop group change.

<a id="rst-algorithm"></a>

## Algorithm

In a nutshell, the algorithm works as follows. Each next hop deserves a certain number of buckets, according to its weight and the number of buckets in the hash table. In accordance with the source code, we will call this number a "wants count" of a next hop. In case of an event that might cause bucket allocation change, the wants counts for individual next hops are updated.

Next hops that have fewer buckets than their wants count, are called "underweight". Those that have more are "overweight". If there are no overweight (and therefore no underweight) next hops in the group, it is said to be "balanced".

Each bucket maintains a last-used timer. Every time a packet is forwarded through a bucket, this timer is updated to current jiffies value. One attribute of a resilient group is then the "idle timer", which is the amount of time that a bucket must not be hit by traffic in order for it to be considered "idle". Buckets that are not idle are busy.

After assigning wants counts to next hops, an "upkeep" algorithm runs. For buckets:

1. that have no assigned next hop, or

2. whose next hop has been removed, or

3. that are idle and their next hop is overweight,

upkeep changes the next hop that the bucket references to one of the underweight next hops. If, after considering all buckets in this manner, there are still underweight next hops, another upkeep run is scheduled to a future time.

There may not be enough "idle" buckets to satisfy the updated wants counts of all next hops. Another attribute of a resilient group is the "unbalanced timer". This timer can be set to 0, in which case the table will stay out of balance until idle buckets do appear, possibly never. If set to a non-zero value, the value represents the period of time that the table is permitted to stay out of balance.

With this in mind, we update the above list of conditions with one more item. Thus buckets:

4. whose next hop is overweight, and the amount of time that the table has been out of balance exceeds the unbalanced timer, if that is non-zero,

... are migrated as well.

<a id="rst-offloading-driver-feedback"></a>

## Offloading &amp; Driver Feedback

When offloading resilient groups, the algorithm that distributes buckets among next hops is still the one in SW. Drivers are notified of updates to next hop groups in the following three ways:

- Full group notification with the type `NH_NOTIFIER_INFO_TYPE_RES_TABLE`. This is used just after the group is created and buckets populated for the first time.

- Single-bucket notifications of the type `NH_NOTIFIER_INFO_TYPE_RES_BUCKET`, which is used for notifications of individual migrations within an already-established group.

- Pre-replace notification, `NEXTHOP_EVENT_RES_TABLE_PRE_REPLACE`. This is sent before the group is replaced, and is a way for the driver to veto the group before committing anything to the HW.

Some single-bucket notifications are forced, as indicated by the "force" flag in the notification. Those are used for the cases where e.g. the next hop associated with the bucket was removed, and the bucket really must be migrated.

Non-forced notifications can be overridden by the driver by returning an error code. The use case for this is that the driver notifies the HW that a bucket should be migrated, but the HW discovers that the bucket has in fact been hit by traffic.

A second way for the HW to report that a bucket is busy is through the `nexthop_res_grp_activity_update()` API. The buckets identified this way as busy are treated as if traffic hit them.

Offloaded buckets should be flagged as either "offload" or "trap". This is done through the `nexthop_bucket_set_hw_flags()` API.

<a id="rst-netlink-uapi"></a>

## Netlink UAPI

<a id="rst-resilient-group-replacement"></a>

### Resilient Group Replacement

Resilient groups are configured using the `RTM_NEWNEXTHOP` message in the same manner as other multipath groups. The following changes apply to the attributes passed in the netlink message:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_GROUP_TYPE`
>
> </td>
> <td>
>
>
> Should be `NEXTHOP_GRP_TYPE_RES` for resilient group.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_RES_GROUP`
>
> </td>
> <td>
>
>
> A nest that contains attributes specific to resilient groups.
>
> </td>
> </tr>
> </tbody>
> </table>

`NHA_RES_GROUP` payload:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_RES_GROUP_BUCKETS`
>
> </td>
> <td>
>
>
> Number of buckets in the hash table.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_RES_GROUP_IDLE_TIMER`
>
> </td>
> <td>
>
>
> Idle timer in units of clock_t.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_RES_GROUP_UNBALANCED_TIMER`
>
> </td>
> <td>
>
>
> Unbalanced timer in units of clock_t.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-next-hop-get"></a>

### Next Hop Get

Requests to get resilient next-hop groups use the `RTM_GETNEXTHOP` message in exactly the same way as other next hop get requests. The response attributes match the replacement attributes cited above, except `NHA_RES_GROUP` payload will include the following attribute:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_RES_GROUP_UNBALANCED_TIME`
>
> </td>
> <td>
>
>
> How long has the resilient group been out of balance, in units of clock_t.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-bucket-get"></a>

### Bucket Get

The message `RTM_GETNEXTHOPBUCKET` without the `NLM_F_DUMP` flag is used to request a single bucket. The attributes recognized at get requests are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_ID`
>
> </td>
> <td>
>
>
> ID of the next-hop group that the bucket belongs to.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_RES_BUCKET`
>
> </td>
> <td>
>
>
> A nest that contains attributes specific to bucket.
>
> </td>
> </tr>
> </tbody>
> </table>

`NHA_RES_BUCKET` payload:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_RES_BUCKET_INDEX`
>
> </td>
> <td>
>
>
> Index of bucket in the resilient table.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-bucket-dumps"></a>

### Bucket Dumps

The message `RTM_GETNEXTHOPBUCKET` with the `NLM_F_DUMP` flag is used to request a dump of matching buckets. The attributes recognized at dump requests are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_ID`
>
> </td>
> <td>
>
>
> If specified, limits the dump to just the next-hop group with this ID.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_OIF`
>
> </td>
> <td>
>
>
> If specified, limits the dump to buckets that contain next hops that use the device with this ifindex.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_MASTER`
>
> </td>
> <td>
>
>
> If specified, limits the dump to buckets that contain next hops that use a device in the VRF with this ifindex.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> `NHA_RES_BUCKET`
>
> </td>
> <td>
>
>
> A nest that contains attributes specific to bucket.
>
> </td>
> </tr>
> </tbody>
> </table>

`NHA_RES_BUCKET` payload:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> `NHA_RES_BUCKET_NH_ID`
>
> </td>
> <td>
>
>
> If specified, limits the dump to just the buckets that contain the next hop with this ID.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-usage"></a>

## Usage

To illustrate the usage, consider the following commands:



```text
# ip nexthop add id 1 via 192.0.2.2 dev eth0
# ip nexthop add id 2 via 192.0.2.3 dev eth0
# ip nexthop add id 10 group 1/2 type resilient \
        buckets 8 idle_timer 60 unbalanced_timer 300
```

The last command creates a resilient next-hop group. It will have 8 buckets (which is unusually low number, and used here for demonstration purposes only), each bucket will be considered idle when no traffic hits it for at least 60 seconds, and if the table remains out of balance for 300 seconds, it will be forcefully brought into balance.

Changing next-hop weights leads to change in bucket allocation:



```text
# ip nexthop replace id 10 group 1,3/2 type resilient
```

This can be confirmed by looking at individual buckets:



```text
# ip nexthop bucket show id 10
id 10 index 0 idle_time 5.59 nhid 1
id 10 index 1 idle_time 5.59 nhid 1
id 10 index 2 idle_time 8.74 nhid 2
id 10 index 3 idle_time 8.74 nhid 2
id 10 index 4 idle_time 8.74 nhid 1
id 10 index 5 idle_time 8.74 nhid 1
id 10 index 6 idle_time 8.74 nhid 1
id 10 index 7 idle_time 8.74 nhid 1
```

Note the two buckets that have a shorter idle time. Those are the ones that were migrated after the next-hop replace command to satisfy the new demand that next hop 1 be given 6 buckets instead of 4.

<a id="rst-netdevsim"></a>

## Netdevsim

The netdevsim driver implements a mock offload of resilient groups, and exposes debugfs interface that allows marking individual buckets as busy. For example, the following will mark bucket 23 in next-hop group 10 as active:



```text
# echo 10 23 > /sys/kernel/debug/netdevsim/netdevsim10/fib/nexthop_bucket_activity
```

In addition, another debugfs interface can be used to configure that the next attempt to migrate a bucket should fail:



```text
# echo 1 > /sys/kernel/debug/netdevsim/netdevsim10/fib/fail_nexthop_bucket_replace
```

Besides serving as an example, the interfaces that netdevsim exposes are useful in automated testing, and `tools/testing/selftests/drivers/net/netdevsim/nexthop.sh` makes use of them to test the algorithm.

---

# Netfilter Conntrack Sysfs variables

_Peios Kernel / Internals / Networking_

> 0 - disabled (default)

<a id="rst-netfilter-conntrack-sysfs-variables"></a>

<a id="rst-proc-sys-net-netfilter-nf-conntrack-variables"></a>

## /proc/sys/net/netfilter/nf_conntrack\_\* Variables:

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **nf_conntrack_acct - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  Enable connection tracking flow accounting. 64-bit byte and packet counters per flow are added.

- **nf_conntrack_buckets - INTEGER**

  Size of hash table. If not specified as parameter during module loading, the default size is calculated by dividing total memory by 16384 to determine the number of buckets. The hash table will never have fewer than 1024 and never more than 262144 buckets. This sysctl is only writeable in the initial net namespace.

- **nf_conntrack_checksum - BOOLEAN**

  - 0 - disabled

  - not 0 - enabled (default)

  Verify checksum of incoming packets. Packets with bad checksums are in INVALID state. If this is enabled, such packets will not be considered for connection tracking.

- **nf_conntrack_count - INTEGER (read-only)**

  Number of currently allocated flow entries.

- **nf_conntrack_events - BOOLEAN**

  - 0 - disabled

  - 1 - enabled

  - 2 - auto (default)

  If this option is enabled, the connection tracking code will provide userspace with connection tracking events via ctnetlink. The default allocates the extension if a userspace program is listening to ctnetlink events.

- **nf_conntrack_expect_max - INTEGER**

  Maximum size of expectation table.  Default value is nf_conntrack_buckets / 256. Minimum is 1.

- **nf_conntrack_frag6_high_thresh - INTEGER**

  default 262144

  Maximum memory used to reassemble IPv6 fragments.  When nf_conntrack_frag6_high_thresh bytes of memory is allocated for this purpose, the fragment handler will toss packets until nf_conntrack_frag6_low_thresh is reached.

- **nf_conntrack_frag6_low_thresh - INTEGER**

  default 196608

  See nf_conntrack_frag6_low_thresh

- **nf_conntrack_frag6_timeout - INTEGER (seconds)**

  default 60

  Time to keep an IPv6 fragment in memory.

- **nf_conntrack_generic_timeout - INTEGER (seconds)**

  default 600

  Default for generic timeout.  This refers to layer 4 unknown/unsupported protocols.

- **nf_conntrack_icmp_timeout - INTEGER (seconds)**

  default 30

  Default for ICMP timeout.

- **nf_conntrack_icmpv6_timeout - INTEGER (seconds)**

  default 30

  Default for ICMP6 timeout.

- **nf_conntrack_log_invalid - INTEGER**

  - 0   - disable (default)

  - 1   - log ICMP packets

  - 6   - log TCP packets

  - 17  - log UDP packets

  - 41  - log ICMPv6 packets

  - 136 - log UDPLITE packets

  - 255 - log packets of any protocol

  Log invalid packets of a type specified by value.

- **nf_conntrack_max - INTEGER**

  Maximum number of allowed connection tracking entries. This value is set to nf_conntrack_buckets by default. Note that connection tracking entries are added to the table twice -- once for the original direction and once for the reply direction (i.e., with the reversed address). This means that with default settings a maxed-out table will have a average hash chain length of 2, not 1.

- **nf_conntrack_tcp_be_liberal - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  Be conservative in what you do, be liberal in what you accept from others. If it's non-zero, we mark only out of window RST segments as INVALID.

- **nf_conntrack_tcp_ignore_invalid_rst - BOOLEAN**

  - 0 - disabled (default)

  - 1 - enabled

  If it's 1, we don't mark out of window RST segments as INVALID.

- **nf_conntrack_tcp_loose - BOOLEAN**

  - 0 - disabled

  - not 0 - enabled (default)

  If it is set to zero, we disable picking up already established connections.

- **nf_conntrack_tcp_max_retrans - INTEGER**

  default 3

  Maximum number of packets that can be retransmitted without received an (acceptable) ACK from the destination. If this number is reached, a shorter timer will be started.

- **nf_conntrack_tcp_timeout_close - INTEGER (seconds)**

  default 10

- **nf_conntrack_tcp_timeout_close_wait - INTEGER (seconds)**

  default 60

- **nf_conntrack_tcp_timeout_established - INTEGER (seconds)**

  default 432000 (5 days)

- **nf_conntrack_tcp_timeout_fin_wait - INTEGER (seconds)**

  default 120

- **nf_conntrack_tcp_timeout_last_ack - INTEGER (seconds)**

  default 30

- **nf_conntrack_tcp_timeout_max_retrans - INTEGER (seconds)**

  default 300

- **nf_conntrack_tcp_timeout_syn_recv - INTEGER (seconds)**

  default 60

- **nf_conntrack_tcp_timeout_syn_sent - INTEGER (seconds)**

  default 120

- **nf_conntrack_tcp_timeout_time_wait - INTEGER (seconds)**

  default 120

- **nf_conntrack_tcp_timeout_unacknowledged - INTEGER (seconds)**

  default 300

- **nf_conntrack_timestamp - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  Enable connection tracking flow timestamping.

- **nf_conntrack_sctp_timeout_closed - INTEGER (seconds)**

  default 10

- **nf_conntrack_sctp_timeout_cookie_wait - INTEGER (seconds)**

  default 3

- **nf_conntrack_sctp_timeout_cookie_echoed - INTEGER (seconds)**

  default 3

- **nf_conntrack_sctp_timeout_established - INTEGER (seconds)**

  default 210

  Default is set to (hb_interval \* path_max_retrans + rto_max)

- **nf_conntrack_sctp_timeout_shutdown_sent - INTEGER (seconds)**

  default 3

- **nf_conntrack_sctp_timeout_shutdown_recd - INTEGER (seconds)**

  default 3

- **nf_conntrack_sctp_timeout_shutdown_ack_sent - INTEGER (seconds)**

  default 3

- **nf_conntrack_sctp_timeout_heartbeat_sent - INTEGER (seconds)**

  default 30

  This timeout is used to setup conntrack entry on secondary paths. Default is set to hb_interval.

- **nf_conntrack_udp_timeout - INTEGER (seconds)**

  default 30

- **nf_conntrack_udp_timeout_stream - INTEGER (seconds)**

  default 120

  This extended timeout will be used in case there is an UDP stream detected.

- **nf_conntrack_gre_timeout - INTEGER (seconds)**

  default 30

- **nf_conntrack_gre_timeout_stream - INTEGER (seconds)**

  default 180

  This extended timeout will be used in case there is an GRE stream detected.

- **nf_hooks_lwtunnel - BOOLEAN**

  - 0 - disabled (default)

  - not 0 - enabled

  If this option is enabled, the lightweight tunnel netfilter hooks are enabled. This option cannot be disabled once it is enabled.

- **nf_flowtable_tcp_timeout - INTEGER (seconds)**

  default 30

  Control offload timeout for tcp connections. TCP connections may be offloaded from nf conntrack to nf flow table. Once aged, the connection is returned to nf conntrack.

- **nf_flowtable_udp_timeout - INTEGER (seconds)**

  default 30

  Control offload timeout for udp connections. UDP connections may be offloaded from nf conntrack to nf flow table. Once aged, the connection is returned to nf conntrack.

---

# Netfilter's flowtable infrastructure

_Peios Kernel / Internals / Networking_

> This documentation describes the Netfilter flowtable infrastructure which allows you to define a fastpath through the flowtable datapath. This infrastructure also provides hardware offload support. The flowtable supports for the layer 3…

> **Peios:** This describes an upstream interface disabled in the configured Peios kernel. Peios uses NTFE; nftables/iptables, IPVS and flow-table configuration are not enabled policy paths. Retained schemas and reference text do not imply runtime availability. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-netfilter-s-flowtable-infrastructure"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This documentation describes the Netfilter flowtable infrastructure which allows you to define a fastpath through the flowtable datapath. This infrastructure also provides hardware offload support. The flowtable supports for the layer 3 IPv4 and IPv6 and the layer 4 TCP and UDP protocols.

<a id="rst-overview"></a>

## Overview

Once the first packet of the flow successfully goes through the IP forwarding path, from the second packet on, you might decide to offload the flow to the flowtable through your ruleset. The flowtable infrastructure provides a rule action that allows you to specify when to add a flow to the flowtable.

A packet that finds a matching entry in the flowtable (ie. flowtable hit) is transmitted to the output netdevice via neigh_xmit(), hence, packets bypass the classic IP forwarding path (the visible effect is that you do not see these packets from any of the Netfilter hooks coming after ingress). In case that there is no matching entry in the flowtable (ie. flowtable miss), the packet follows the classic IP forwarding path.

The flowtable uses a resizable hashtable. Lookups are based on the following n-tuple selectors: layer 2 protocol encapsulation (VLAN and PPPoE), layer 3 source and destination, layer 4 source and destination ports and the input interface (useful in case there are several conntrack zones in place).

The 'flow add' action allows you to populate the flowtable, the user selectively specifies what flows are placed into the flowtable. Hence, packets follow the classic IP forwarding path unless the user explicitly instruct flows to use this new alternative forwarding path via policy.

The flowtable datapath is represented in Fig.1, which describes the classic IP forwarding path including the Netfilter hooks and the flowtable fastpath bypass.



```text
                                       userspace process
                                        ^              |
                                        |              |
                                   _____|____     ____\/___
                                  /          \   /         \
                                  |   input   |  |  output  |
                                  \__________/   \_________/
                                       ^               |
                                       |               |
    _________      __________      ---------     _____\/_____
   /         \    /          \     |Routing |   /            \
-->  ingress  ---> prerouting ---> |decision|   | postrouting |--> neigh_xmit
   \_________/    \__________/     ----------   \____________/          ^
     |      ^                          |               ^                |
 flowtable  |                     ____\/___            |                |
     |      |                    /         \           |                |
  __\/___   |                    | forward |------------                |
  |-----|   |                    \_________/                            |
  |-----|   |                 'flow offload' rule                       |
  |-----|   |                   adds entry to                           |
  |_____|   |                     flowtable                             |
     |      |                                                           |
    / \     |                                                           |
   /hit\_no_|                                                           |
   \ ? /                                                                |
    \ /                                                                 |
     |__yes_________________fastpath bypass ____________________________|

             Fig.1 Netfilter hooks and flowtable interactions
```

The flowtable entry also stores the NAT configuration, so all packets are mangled according to the NAT policy that is specified from the classic IP forwarding path. The TTL is decremented before calling neigh_xmit(). Fragmented traffic is passed up to follow the classic IP forwarding path given that the transport header is missing, in this case, flowtable lookups are not possible. TCP RST and FIN packets are also passed up to the classic IP forwarding path to release the flow gracefully. Packets that exceed the MTU are also passed up to the classic forwarding path to report packet-too-big ICMP errors to the sender.

<a id="rst-example-configuration"></a>

## Example configuration

Enabling the flowtable bypass is relatively easy, you only need to create a flowtable and add one rule to your forward chain:



```text
table inet x {
        flowtable f {
                hook ingress priority 0; devices = { eth0, eth1 };
        }
        chain y {
                type filter hook forward priority 0; policy accept;
                ip protocol tcp flow add @f
                counter packets 0 bytes 0
        }
}
```

This example adds the flowtable 'f' to the ingress hook of the eth0 and eth1 netdevices. You can create as many flowtables as you want in case you need to perform resource partitioning. The flowtable priority defines the order in which hooks are run in the pipeline, this is convenient in case you already have a nftables ingress chain (make sure the flowtable priority is smaller than the nftables ingress chain hence the flowtable runs before in the pipeline).

The 'flow offload' action from the forward chain 'y' adds an entry to the flowtable for the TCP syn-ack packet coming in the reply direction. Once the flow is offloaded, you will observe that the counter rule in the example above does not get updated for the packets that are being forwarded through the forwarding bypass.

You can identify offloaded flows through the \[OFFLOAD\] tag when listing your connection tracking table.



```text
# conntrack -L
tcp      6 src=10.141.10.2 dst=192.168.10.2 sport=52728 dport=5201 src=192.168.10.2 dst=192.168.10.1 sport=5201 dport=52728 [OFFLOAD] mark=0 use=2
```

<a id="rst-layer-2-encapsulation"></a>

## Layer 2 encapsulation

Since Linux kernel 5.13, the flowtable infrastructure discovers the real netdevice behind VLAN and PPPoE netdevices. The flowtable software datapath parses the VLAN and PPPoE layer 2 headers to extract the ethertype and the VLAN ID / PPPoE session ID which are used for the flowtable lookups. The flowtable datapath also deals with layer 2 decapsulation.

You do not need to add the PPPoE and the VLAN devices to your flowtable, instead the real device is sufficient for the flowtable to track your flows.

<a id="rst-bridge-and-ip-forwarding"></a>

## Bridge and IP forwarding

Since Linux kernel 5.13, you can add bridge ports to the flowtable. The flowtable infrastructure discovers the topology behind the bridge device. This allows the flowtable to define a fastpath bypass between the bridge ports (represented as eth1 and eth2 in the example figure below) and the gateway device (represented as eth0) in your switch/router.



```text
        fastpath bypass
 .-------------------------.
/                           \
|           IP forwarding   |
|          /             \ \/
|       br0               eth0 ..... eth0
.       / \                          *host B*
 -> eth1  eth2
     .           *switch/router*
     .
     .
   eth0
 *host A*
```

The flowtable infrastructure also supports for bridge VLAN filtering actions such as PVID and untagged. You can also stack a classic VLAN device on top of your bridge port.

If you would like that your flowtable defines a fastpath between your bridge ports and your IP forwarding path, you have to add your bridge ports (as represented by the real netdevice) to your flowtable definition.

<a id="rst-counters"></a>

## Counters

The flowtable can synchronize packet and byte counters with the existing connection tracking entry by specifying the counter statement in your flowtable definition, e.g.



```text
table inet x {
        flowtable f {
                hook ingress priority 0; devices = { eth0, eth1 };
                counter
        }
}
```

Counter support is available since Linux kernel 5.7.

<a id="rst-hardware-offload"></a>

## Hardware offload

If your network device provides hardware offload support, you can turn it on by means of the 'offload' flag in your flowtable definition, e.g.



```text
table inet x {
        flowtable f {
                hook ingress priority 0; devices = { eth0, eth1 };
                flags offload;
        }
}
```

There is a workqueue that adds the flows to the hardware. Note that a few packets might still run over the flowtable software path until the workqueue has a chance to offload the flow to the network device.

You can identify hardware offloaded flows through the \[HW_OFFLOAD\] tag when listing your connection tracking table. Please, note that the \[OFFLOAD\] tag refers to the software offload mode, so there is a distinction between \[OFFLOAD\] which refers to the software flowtable fastpath and \[HW_OFFLOAD\] which refers to the hardware offload datapath being used by the flow.

The flowtable hardware offload infrastructure also supports for the DSA (Distributed Switch Architecture).

<a id="rst-limitations"></a>

## Limitations

The flowtable behaves like a cache. The flowtable entries might get stale if either the destination MAC address or the egress netdevice that is used for transmission changes.

This might be a problem if:

- You run the flowtable in software mode and you combine bridge and IP forwarding in your setup.

- Hardware offload is enabled.

<a id="rst-more-reading"></a>

## More reading

This documentation is based on the LWN.net articles <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)<a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2). Rafal Milecki also made a very complete and comprehensive summary called "A state of network acceleration" that describes how things were before this infrastructure was mainlined <a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3) and it also makes a rough summary of this work <a id="rst-footnote-reference-4"></a>[4](#rst-footnote-4).

<a id="rst-footnote-1"></a>



**[1]** [https://lwn.net/Articles/738214/](<https://lwn.net/Articles/738214/>)

<a id="rst-footnote-2"></a>



**[2]** [https://lwn.net/Articles/742164/](<https://lwn.net/Articles/742164/>)

<a id="rst-footnote-3"></a>



**[3]** [http://lists.infradead.org/pipermail/lede-dev/2018-January/010830.html](<http://lists.infradead.org/pipermail/lede-dev/2018-January/010830.html>)

<a id="rst-footnote-4"></a>



**[4]** [http://lists.infradead.org/pipermail/lede-dev/2018-January/010829.html](<http://lists.infradead.org/pipermail/lede-dev/2018-January/010829.html>)

---

# Linux NFC subsystem

_Peios Kernel / Internals / Networking_

> The Near Field Communication (NFC) subsystem is required to standardize the NFC device drivers development and to create an unified userspace interface.

<a id="rst-linux-nfc-subsystem"></a>

The Near Field Communication (NFC) subsystem is required to standardize the NFC device drivers development and to create an unified userspace interface.

This document covers the architecture overview, the device driver interface description and the userspace interface description.

<a id="rst-architecture-overview"></a>

## Architecture overview

- **The NFC subsystem is responsible for:**

  - NFC adapters management;

  - Polling for targets;

  - Low-level data exchange;

The subsystem is divided in some parts. The 'core' is responsible for providing the device driver interface. On the other side, it is also responsible for providing an interface to control operations and low-level data exchange.

The control operations are available to userspace via generic netlink.

The low-level data exchange interface is provided by the new socket family PF_NFC. The NFC_SOCKPROTO_RAW performs raw communication with NFC targets.



```none
+--------------------------------------+
|              USER SPACE              |
+--------------------------------------+
    ^                       ^
    | low-level             | control
    | data exchange         | operations
    |                       |
    |                       v
    |                  +-----------+
    | AF_NFC           |  netlink  |
    | socket           +-----------+
    | raw                   ^
    |                       |
    v                       v
+---------+            +-----------+
| rawsock | <--------> |   core    |
+---------+            +-----------+
                            ^
                            |
                            v
                       +-----------+
                       |  driver   |
                       +-----------+
```

<a id="rst-device-driver-interface"></a>

## Device Driver Interface

When registering on the NFC subsystem, the device driver must inform the core of the set of supported NFC protocols and the set of ops callbacks. The ops callbacks that must be implemented are the following:

- start_poll - setup the device to poll for targets

- stop_poll - stop on progress polling operation

- activate_target - select and initialize one of the targets found

- deactivate_target - deselect and deinitialize the selected target

- data_exchange - send data and receive the response (transceive operation)

<a id="rst-userspace-interface"></a>

## Userspace interface

The userspace interface is divided in control operations and low-level data exchange operation.

<a id="rst-control-operations"></a>

### Control operations

Generic netlink is used to implement the interface to the control operations. The operations are composed by commands and events, all listed below:

- NFC_CMD_GET_DEVICE - get specific device info or dump the device list

- NFC_CMD_START_POLL - setup a specific device to polling for targets

- NFC_CMD_STOP_POLL - stop the polling operation in a specific device

- NFC_CMD_GET_TARGET - dump the list of targets found by a specific device

- NFC_EVENT_DEVICE_ADDED - reports an NFC device addition

- NFC_EVENT_DEVICE_REMOVED - reports an NFC device removal

- NFC_EVENT_TARGETS_FOUND - reports START_POLL results when 1 or more targets are found

The user must call START_POLL to poll for NFC targets, passing the desired NFC protocols through NFC_ATTR_PROTOCOLS attribute. The device remains in polling state until it finds any target. However, the user can stop the polling operation by calling STOP_POLL command. In this case, it will be checked if the requester of STOP_POLL is the same of START_POLL.

If the polling operation finds one or more targets, the event TARGETS_FOUND is sent (including the device id). The user must call GET_TARGET to get the list of all targets found by such device. Each reply message has target attributes with relevant information such as the supported NFC protocols.

All polling operations requested through one netlink socket are stopped when it's closed.

<a id="rst-low-level-data-exchange"></a>

### Low-level data exchange

The userspace must use PF_NFC sockets to perform any data communication with targets. All NFC sockets use AF_NFC:



```text
struct sockaddr_nfc {
       sa_family_t sa_family;
       __u32 dev_idx;
       __u32 target_idx;
       __u32 nfc_protocol;
};
```

To establish a connection with one target, the user must create an NFC_SOCKPROTO_RAW socket and call the 'connect' syscall with the sockaddr_nfc struct correctly filled. All information comes from NFC_EVENT_TARGETS_FOUND netlink event. As a target can support more than one NFC protocol, the user must inform which protocol it wants to use.

Internally, 'connect' will result in an activate_target call to the driver. When the socket is closed, the target is deactivated.

The data format exchanged through the sockets is NFC protocol dependent. For instance, when communicating with MIFARE tags, the data exchanged are MIFARE commands and their responses.

The first received package is the response to the first sent package and so on. In order to allow valid "empty" responses, every data received has a NULL header of 1 byte.

---

# OPEN Alliance 10BASE-T1x MAC-PHY Serial Interface (TC6) Framework Support

_Peios Kernel / Internals / Networking_

> The IEEE 802.3cg project defines two 10 Mbit/s PHYs operating over a single pair of conductors. The 10BASE-T1L (Clause 146) is a long reach PHY supporting full duplex point-to-point operation over 1 km of single balanced pair of…

<a id="rst-open-alliance-10base-t1x-mac-phy-serial-interface-tc6-framework-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-introduction"></a>

## Introduction

The IEEE 802.3cg project defines two 10 Mbit/s PHYs operating over a single pair of conductors. The 10BASE-T1L (Clause 146) is a long reach PHY supporting full duplex point-to-point operation over 1 km of single balanced pair of conductors. The 10BASE-T1S (Clause 147) is a short reach PHY supporting full / half duplex point-to-point operation over 15 m of single balanced pair of conductors, or half duplex multidrop bus operation over 25 m of single balanced pair of conductors.

Furthermore, the IEEE 802.3cg project defines the new Physical Layer Collision Avoidance (PLCA) Reconciliation Sublayer (Clause 148) meant to provide improved determinism to the CSMA/CD media access method. PLCA works in conjunction with the 10BASE-T1S PHY operating in multidrop mode.

The aforementioned PHYs are intended to cover the low-speed / low-cost applications in industrial and automotive environment. The large number of pins (16) required by the MII interface, which is specified by the IEEE 802.3 in Clause 22, is one of the major cost factors that need to be addressed to fulfil this objective.

The MAC-PHY solution integrates an IEEE Clause 4 MAC and a 10BASE-T1x PHY exposing a low pin count Serial Peripheral Interface (SPI) to the host microcontroller. This also enables the addition of Ethernet functionality to existing low-end microcontrollers which do not integrate a MAC controller.

<a id="rst-overview"></a>

## Overview

The MAC-PHY is specified to carry both data (Ethernet frames) and control (register access) transactions over a single full-duplex serial peripheral interface.

<a id="rst-protocol-overview"></a>

## Protocol Overview

Two types of transactions are defined in the protocol: data transactions for Ethernet frame transfers and control transactions for register read/write transfers. A chunk is the basic element of data transactions and is composed of 4 bytes of overhead plus 64 bytes of payload size for each chunk. Ethernet frames are transferred over one or more data chunks. Control transactions consist of one or more register read/write control commands.

SPI transactions are initiated by the SPI host with the assertion of CSn low to the MAC-PHY and ends with the deassertion of CSn high. In between each SPI transaction, the SPI host may need time for additional processing and to setup the next SPI data or control transaction.

SPI data transactions consist of an equal number of transmit (TX) and receive (RX) chunks. Chunks in both transmit and receive directions may or may not contain valid frame data independent from each other, allowing for the simultaneous transmission and reception of different length frames.

Each transmit data chunk begins with a 32-bit data header followed by a data chunk payload on MOSI. The data header indicates whether transmit frame data is present and provides the information to determine which bytes of the payload contain valid frame data.

In parallel, receive data chunks are received on MISO. Each receive data chunk consists of a data chunk payload ending with a 32-bit data footer. The data footer indicates if there is receive frame data present within the payload or not and provides the information to determine which bytes of the payload contain valid frame data.

<a id="rst-reference"></a>

## Reference

10BASE-T1x MAC-PHY Serial Interface Specification,

Link: [https://opensig.org/download/document/OPEN_Alliance_10BASET1x_MAC-PHY_Serial_Interface_V1.1.pdf](<https://opensig.org/download/document/OPEN_Alliance_10BASET1x_MAC-PHY_Serial_Interface_V1.1.pdf>)

<a id="rst-hardware-architecture"></a>

## Hardware Architecture



```none
+----------+      +-------------------------------------+
|          |      |                MAC-PHY              |
|          |<---->| +-----------+  +-------+  +-------+ |
| SPI Host |      | | SPI Slave |  |  MAC  |  |  PHY  | |
|          |      | +-----------+  +-------+  +-------+ |
+----------+      +-------------------------------------+
```

<a id="rst-software-architecture"></a>

## Software Architecture



```none
+----------------------------------------------------------+
|                 Networking Subsystem                     |
+----------------------------------------------------------+
          / \                             / \
           |                               |
           |                               |
          \ /                              |
+----------------------+     +-----------------------------+
|     MAC Driver       |<--->| OPEN Alliance TC6 Framework |
+----------------------+     +-----------------------------+
          / \                             / \
           |                               |
           |                               |
           |                              \ /
+----------------------------------------------------------+
|                    SPI Subsystem                         |
+----------------------------------------------------------+
                        / \
                         |
                         |
                        \ /
+----------------------------------------------------------+
|                10BASE-T1x MAC-PHY Device                 |
+----------------------------------------------------------+
```

<a id="rst-implementation"></a>

## Implementation

<a id="rst-mac-driver"></a>

### MAC Driver

- Probed by SPI subsystem.

- Initializes OA TC6 framework for the MAC-PHY.

- Registers and configures the network device.

- Sends the tx ethernet frames from n/w subsystem to OA TC6 framework.

<a id="rst-open-alliance-tc6-framework"></a>

### OPEN Alliance TC6 Framework

- Initializes PHYLIB interface.

- Registers mac-phy interrupt.

- Performs mac-phy register read/write operation using the control transaction protocol specified in the OPEN Alliance 10BASE-T1x MAC-PHY Serial Interface specification.

- Performs Ethernet frames transaction using the data transaction protocol for Ethernet frames specified in the OPEN Alliance 10BASE-T1x MAC-PHY Serial Interface specification.

- Forwards the received Ethernet frame from 10Base-T1x MAC-PHY to n/w subsystem.

<a id="rst-data-transaction"></a>

### Data Transaction

The Ethernet frames that are typically transferred from the SPI host to the MAC-PHY will be converted into multiple transmit data chunks. Each transmit data chunk will have a 4 bytes header which contains the information needed to determine the validity and the location of the transmit frame data within the 64 bytes data chunk payload.



```none
+---------------------------------------------------+
|                     Tx Chunk                      |
| +---------------------------+  +----------------+ |   MOSI
| | 64 bytes chunk payload    |  | 4 bytes header | |------------>
| +---------------------------+  +----------------+ |
+---------------------------------------------------+
```

4 bytes header contains the below fields,

- **DNC (Bit 31) - Data-Not-Control flag. This flag specifies the type of SPI**

  transaction. For TX data chunks, this bit shall be ’1’. 0 - Control command 1 - Data chunk

- **SEQ (Bit 30) - Data Chunk Sequence. This bit is used to indicate an**

  even/odd transmit data chunk sequence to the MAC-PHY.

- **NORX (Bit 29) - No Receive flag. The SPI host may set this bit to prevent**

  the MAC-PHY from conveying RX data on the MISO for the current chunk (DV = 0 in the footer), indicating that the host would not process it. Typically, the SPI host should set NORX = 0 indicating that it will accept and process any receive frame data within the current chunk.

RSVD (Bit 28..24) - Reserved: All reserved bits shall be ‘0’.

- **VS (Bit 23..22) - Vendor Specific. These bits are implementation specific.**

  If the MAC-PHY does not implement these bits, the host shall set them to ‘0’.

- **DV (Bit 21) - Data Valid flag. The SPI host uses this bit to indicate**

  whether the current chunk contains valid transmit frame data (DV = 1) or not (DV = 0). When ‘0’, the MAC-PHY ignores the chunk payload. Note that the receive path is unaffected by the setting of the DV bit in the data header.

- **SV (Bit 20) - Start Valid flag. The SPI host shall set this bit when the**

  beginning of an Ethernet frame is present in the current transmit data chunk payload. Otherwise, this bit shall be zero. This bit is not to be confused with the Start-of-Frame Delimiter (SFD) byte described in IEEE 802.3 \[2\].

- **SWO (Bit 19..16) - Start Word Offset. When SV = 1, this field shall**

  contain the 32-bit word offset into the transmit data chunk payload that points to the start of a new Ethernet frame to be transmitted. The host shall write this field as zero when SV = 0.

RSVD (Bit 15) - Reserved: All reserved bits shall be ‘0’.

- **EV (Bit 14) - End Valid flag. The SPI host shall set this bit when the end**

  of an Ethernet frame is present in the current transmit data chunk payload. Otherwise, this bit shall be zero.

- **EBO (Bit 13..8) - End Byte Offset. When EV = 1, this field shall contain**

  the byte offset into the transmit data chunk payload that points to the last byte of the Ethernet frame to transmit. This field shall be zero when EV = 0.

- **TSC (Bit 7..6) - Timestamp Capture. Request a timestamp capture when the**

  frame is transmitted onto the network. 00 - Do not capture a timestamp 01 - Capture timestamp into timestamp capture register A 10 - Capture timestamp into timestamp capture register B 11 - Capture timestamp into timestamp capture register C

RSVD (Bit 5..1) - Reserved: All reserved bits shall be ‘0’.

- **P (Bit 0) - Parity. Parity bit calculated over the transmit data header.**

  Method used is odd parity.

The number of buffers available in the MAC-PHY to store the incoming transmit data chunk payloads is represented as transmit credits. The available transmit credits in the MAC-PHY can be read either from the Buffer Status Register or footer (Refer below for the footer info) received from the MAC-PHY. The SPI host should not write more data chunks than the available transmit credits as this will lead to transmit buffer overflow error.

In case the previous data footer had no transmit credits available and once the transmit credits become available for transmitting transmit data chunks, the MAC-PHY interrupt is asserted to SPI host. On reception of the first data header this interrupt will be deasserted and the received footer for the first data chunk will have the transmit credits available information.

The Ethernet frames that are typically transferred from MAC-PHY to SPI host will be sent as multiple receive data chunks. Each receive data chunk will have 64 bytes of data chunk payload followed by 4 bytes footer which contains the information needed to determine the validity and the location of the receive frame data within the 64 bytes data chunk payload.



```none
+---------------------------------------------------+
|                     Rx Chunk                      |
| +----------------+  +---------------------------+ |   MISO
| | 4 bytes footer |  | 64 bytes chunk payload    | |------------>
| +----------------+  +---------------------------+ |
+---------------------------------------------------+
```

4 bytes footer contains the below fields,

- **EXST (Bit 31) - Extended Status. This bit is set when any bit in the**

  STATUS0 or STATUS1 registers are set and not masked.

- **HDRB (Bit 30) - Received Header Bad. When set, indicates that the MAC-PHY**

  received a control or data header with a parity error.

- **SYNC (Bit 29) - Configuration Synchronized flag. This bit reflects the**

  state of the SYNC bit in the CONFIG0 configuration register (see Table 12). A zero indicates that the MAC-PHY configuration may not be as expected by the SPI host. Following configuration, the SPI host sets the corresponding bitin the configuration register which is reflected in this field.

- **RCA (Bit 28..24) - Receive Chunks Available. The RCA field indicates to**

  the SPI host the minimum number of additional receive data chunks of frame data that are available for reading beyond the current receive data chunk. This field is zero when there is no receive frame data pending in the MAC-PHY’s buffer for reading.

- **VS (Bit 23..22) - Vendor Specific. These bits are implementation specific.**

  If not implemented, the MAC-PHY shall set these bits to ‘0’.

- **DV (Bit 21) - Data Valid flag. The MAC-PHY uses this bit to indicate**

  whether the current receive data chunk contains valid receive frame data (DV = 1) or not (DV = 0). When ‘0’, the SPI host shall ignore the chunk payload.

- **SV (Bit 20) - Start Valid flag. The MAC-PHY sets this bit when the current**

  chunk payload contains the start of an Ethernet frame. Otherwise, this bit is zero. The SV bit is not to be confused with the Start-of-Frame Delimiter (SFD) byte described in IEEE 802.3 \[2\].

- **SWO (Bit 19..16) - Start Word Offset. When SV = 1, this field contains the**

  32-bit word offset into the receive data chunk payload containing the first byte of a new received Ethernet frame. When a receive timestamp has been added to the beginning of the received Ethernet frame (RTSA = 1) then SWO points to the most significant byte of the timestamp. This field will be zero when SV = 0.

- **FD (Bit 15) - Frame Drop. When set, this bit indicates that the MAC has**

  detected a condition for which the SPI host should drop the received Ethernet frame. This bit is only valid at the end of a received Ethernet frame (EV = 1) and shall be zero at all other times.

- **EV (Bit 14) - End Valid flag. The MAC-PHY sets this bit when the end of a**

  received Ethernet frame is present in this receive data chunk payload.

- **EBO (Bit 13..8) - End Byte Offset: When EV = 1, this field contains the**

  byte offset into the receive data chunk payload that locates the last byte of the received Ethernet frame. This field is zero when EV = 0.

- **RTSA (Bit 7) - Receive Timestamp Added. This bit is set when a 32-bit or**

  64-bit timestamp has been added to the beginning of the received Ethernet frame. The MAC-PHY shall set this bit to zero when SV = 0.

- **RTSP (Bit 6) - Receive Timestamp Parity. Parity bit calculated over the**

  32-bit/64-bit timestamp added to the beginning of the received Ethernet frame. Method used is odd parity. The MAC-PHY shall set this bit to zero when RTSA = 0.

- **TXC (Bit 5..1) - Transmit Credits. This field contains the minimum number**

  of transmit data chunks of frame data that the SPI host can write in a single transaction without incurring a transmit buffer overflow error.

- **P (Bit 0) - Parity. Parity bit calculated over the receive data footer.**

  Method used is odd parity.

SPI host will initiate the data receive transaction based on the receive chunks available in the MAC-PHY which is provided in the receive chunk footer (RCA - Receive Chunks Available). SPI host will create data invalid transmit data chunks (empty chunks) or data valid transmit data chunks in case there are valid Ethernet frames to transmit to the MAC-PHY. The receive chunks available in MAC-PHY can be read either from the Buffer Status Register or footer.

In case the previous data footer had no receive data chunks available and once the receive data chunks become available again for reading, the MAC-PHY interrupt is asserted to SPI host. On reception of the first data header this interrupt will be deasserted and the received footer for the first data chunk will have the receive chunks available information.

<a id="rst-mac-phy-interrupt"></a>

### MAC-PHY Interrupt

The MAC-PHY interrupt is asserted when the following conditions are met.

Receive chunks available - This interrupt is asserted when the previous data footer had no receive data chunks available and once the receive data chunks become available for reading. On reception of the first data header this interrupt will be deasserted.

Transmit chunk credits available - This interrupt is asserted when the previous data footer indicated no transmit credits available and once the transmit credits become available for transmitting transmit data chunks. On reception of the first data header this interrupt will be deasserted.

Extended status event - This interrupt is asserted when the previous data footer indicated no extended status and once the extended event become available. In this case the host should read status \#0 register to know the corresponding error/event. On reception of the first data header this interrupt will be deasserted.

<a id="rst-control-transaction"></a>

### Control Transaction

4 bytes control header contains the below fields,

- **DNC (Bit 31) - Data-Not-Control flag. This flag specifies the type of SPI**

  transaction. For control commands, this bit shall be ‘0’. 0 - Control command 1 - Data chunk

- **HDRB (Bit 30) - Received Header Bad. When set by the MAC-PHY, indicates**

  that a header was received with a parity error. The SPI host should always clear this bit. The MAC-PHY ignores the HDRB value sent by the SPI host on MOSI.

- **WNR (Bit 29) - Write-Not-Read. This bit indicates if data is to be written**

  to registers (when set) or read from registers (when clear).

- **AID (Bit 28) - Address Increment Disable. When clear, the address will be**

  automatically post-incremented by one following each register read or write. When set, address auto increment is disabled allowing successive reads and writes to occur at the same register address.

- **MMS (Bit 27..24) - Memory Map Selector. This field selects the specific**

  register memory map to access.

- **ADDR (Bit 23..8) - Address. Address of the first register within the**

  selected memory map to access.

- **LEN (Bit 7..1) - Length. Specifies the number of registers to read/write.**

  This field is interpreted as the number of registers minus 1 allowing for up to 128 consecutive registers read or written starting at the address specified in ADDR. A length of zero shall read or write a single register.

- **P (Bit 0) - Parity. Parity bit calculated over the control command header.**

  Method used is odd parity.

Control transactions consist of one or more control commands. Control commands are used by the SPI host to read and write registers within the MAC-PHY. Each control commands are composed of a 4 bytes control command header followed by register write data in case of control write command.

The MAC-PHY ignores the final 4 bytes of data from the SPI host at the end of the control write command. The control write command is also echoed from the MAC-PHY back to the SPI host to identify which register write failed in case of any bus errors. The echoed Control write command will have the first 4 bytes unused value to be ignored by the SPI host followed by 4 bytes echoed control header followed by echoed register write data. Control write commands can write either a single register or multiple consecutive registers. When multiple consecutive registers are written, the address is automatically post-incremented by the MAC-PHY. Writing to any unimplemented or undefined registers shall be ignored and yield no effect.

The MAC-PHY ignores all data from the SPI host following the control header for the remainder of the control read command. The control read command is also echoed from the MAC-PHY back to the SPI host to identify which register read is failed in case of any bus errors. The echoed Control read command will have the first 4 bytes of unused value to be ignored by the SPI host followed by 4 bytes echoed control header followed by register read data. Control read commands can read either a single register or multiple consecutive registers. When multiple consecutive registers are read, the address is automatically post-incremented by the MAC-PHY. Reading any unimplemented or undefined registers shall return zero.

<a id="rst-device-drivers-api"></a>

#### Device drivers API

The include/linux/oa_tc6.h defines the following functions:





<a id="c-oa_tc6_init"></a>

```c
struct oa_tc6 *oa_tc6_init(struct spi_device *spi, \
struct net_device *netdev)
```

Initialize OA TC6 lib.





<a id="c-oa_tc6_exit"></a>

```c
void oa_tc6_exit(struct oa_tc6 *tc6)
```

Free allocated OA TC6 lib.





<a id="c-oa_tc6_write_register"></a>

```c
int oa_tc6_write_register(struct oa_tc6 *tc6, u32 address, \
u32 value)
```

Write a single register in the MAC-PHY.





<a id="c-oa_tc6_write_registers"></a>

```c
int oa_tc6_write_registers(struct oa_tc6 *tc6, u32 address, \
u32 value[], u8 length)
```

Writing multiple consecutive registers starting from @address in the MAC-PHY. Maximum of 128 consecutive registers can be written starting at @address.





<a id="c-oa_tc6_read_register"></a>

```c
int oa_tc6_read_register(struct oa_tc6 *tc6, u32 address, \
u32 *value)
```

Read a single register in the MAC-PHY.





<a id="c-oa_tc6_read_registers"></a>

```c
int oa_tc6_read_registers(struct oa_tc6 *tc6, u32 address, \
u32 value[], u8 length)
```

Reading multiple consecutive registers starting from @address in the MAC-PHY. Maximum of 128 consecutive registers can be read starting at @address.





<a id="c-oa_tc6_start_xmit"></a>

```c
netdev_tx_t oa_tc6_start_xmit(struct oa_tc6 *tc6, \
struct sk_buff *skb);
```

The transmit Ethernet frame in the skb is or going to be transmitted through the MAC-PHY.





<a id="c-oa_tc6_zero_align_receive_frame_enable"></a>

```c
int oa_tc6_zero_align_receive_frame_enable(struct oa_tc6 *tc6);
```

Zero align receive frame feature can be enabled to align all receive ethernet frames data to start at the beginning of any receive data chunk payload with a start word offset (SWO) of zero.

---

# Open vSwitch datapath developer documentation

_Peios Kernel / Internals / Networking_

> The Open vSwitch kernel module allows flexible userspace control over flow-level packet processing on selected network devices. It can be used to implement a plain Ethernet switch, network device bonding, VLAN processing, network access…

<a id="rst-open-vswitch-datapath-developer-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Open vSwitch kernel module allows flexible userspace control over flow-level packet processing on selected network devices.  It can be used to implement a plain Ethernet switch, network device bonding, VLAN processing, network access control, flow-based network control, and so on.

The kernel module implements multiple "datapaths" (analogous to bridges), each of which can have multiple "vports" (analogous to ports within a bridge).  Each datapath also has associated with it a "flow table" that userspace populates with "flows" that map from keys based on packet headers and metadata to sets of actions.  The most common action forwards the packet to another vport; other actions are also implemented.

When a packet arrives on a vport, the kernel module processes it by extracting its flow key and looking it up in the flow table.  If there is a matching flow, it executes the associated actions.  If there is no match, it queues the packet to userspace for processing (as part of its processing, userspace will likely set up a flow to handle further packets of the same type entirely in-kernel).

<a id="rst-flow-key-compatibility"></a>

## Flow key compatibility

Network protocols evolve over time.  New protocols become important and existing protocols lose their prominence.  For the Open vSwitch kernel module to remain relevant, it must be possible for newer versions to parse additional protocols as part of the flow key.  It might even be desirable, someday, to drop support for parsing protocols that have become obsolete.  Therefore, the Netlink interface to Open vSwitch is designed to allow carefully written userspace applications to work with any version of the flow key, past or future.

To support this forward and backward compatibility, whenever the kernel module passes a packet to userspace, it also passes along the flow key that it parsed from the packet.  Userspace then extracts its own notion of a flow key from the packet and compares it against the kernel-provided version:

> - If userspace's notion of the flow key for the packet matches the kernel's, then nothing special is necessary.
>
> - If the kernel's flow key includes more fields than the userspace version of the flow key, for example if the kernel decoded IPv6 headers but userspace stopped at the Ethernet type (because it does not understand IPv6), then again nothing special is necessary.  Userspace can still set up a flow in the usual way, as long as it uses the kernel-provided flow key to do it.
>
> - If the userspace flow key includes more fields than the kernel's, for example if userspace decoded an IPv6 header but the kernel stopped at the Ethernet type, then userspace can forward the packet manually, without setting up a flow in the kernel.  This case is bad for performance because every packet that the kernel considers part of the flow must go to userspace, but the forwarding behavior is correct.  (If userspace can determine that the values of the extra fields would not affect forwarding behavior, then it could set up a flow anyway.)

How flow keys evolve over time is important to making this work, so the following sections go into detail.

<a id="rst-flow-key-format"></a>

## Flow key format

A flow key is passed over a Netlink socket as a sequence of Netlink attributes.  Some attributes represent packet metadata, defined as any information about a packet that cannot be extracted from the packet itself, e.g. the vport on which the packet was received.  Most attributes, however, are extracted from headers within the packet, e.g. source and destination addresses from Ethernet, IP, or TCP headers.

The &lt;linux/openvswitch.h&gt; header file defines the exact format of the flow key attributes.  For informal explanatory purposes here, we write them as comma-separated strings, with parentheses indicating arguments and nesting.  For example, the following could represent a flow key corresponding to a TCP packet that arrived on vport 1:



```text
in_port(1), eth(src=e0:91:f5:21:d0:b2, dst=00:02:e3:0f:80:a4),
eth_type(0x0800), ipv4(src=172.16.0.20, dst=172.18.0.52, proto=17, tos=0,
frag=no), tcp(src=49163, dst=80)
```

Often we ellipsize arguments not important to the discussion, e.g.:



```text
in_port(1), eth(...), eth_type(0x0800), ipv4(...), tcp(...)
```

<a id="rst-wildcarded-flow-key-format"></a>

## Wildcarded flow key format

A wildcarded flow is described with two sequences of Netlink attributes passed over the Netlink socket. A flow key, exactly as described above, and an optional corresponding flow mask.

A wildcarded flow can represent a group of exact match flows. Each '1' bit in the mask specifies a exact match with the corresponding bit in the flow key. A '0' bit specifies a don't care bit, which will match either a '1' or '0' bit of a incoming packet. Using wildcarded flow can improve the flow set up rate by reduce the number of new flows need to be processed by the user space program.

Support for the mask Netlink attribute is optional for both the kernel and user space program. The kernel can ignore the mask attribute, installing an exact match flow, or reduce the number of don't care bits in the kernel to less than what was specified by the user space program. In this case, variations in bits that the kernel does not implement will simply result in additional flow setups. The kernel module will also work with user space programs that neither support nor supply flow mask attributes.

Since the kernel may ignore or modify wildcard bits, it can be difficult for the userspace program to know exactly what matches are installed. There are two possible approaches: reactively install flows as they miss the kernel flow table (and therefore not attempt to determine wildcard changes at all) or use the kernel's response messages to determine the installed wildcards.

When interacting with userspace, the kernel should maintain the match portion of the key exactly as originally installed. This will provides a handle to identify the flow for all future operations. However, when reporting the mask of an installed flow, the mask should include any restrictions imposed by the kernel.

The behavior when using overlapping wildcarded flows is undefined. It is the responsibility of the user space program to ensure that any incoming packet can match at most one flow, wildcarded or not. The current implementation performs best-effort detection of overlapping wildcarded flows and may reject some but not all of them. However, this behavior may change in future versions.

<a id="rst-unique-flow-identifiers"></a>

## Unique flow identifiers

An alternative to using the original match portion of a key as the handle for flow identification is a unique flow identifier, or "UFID". UFIDs are optional for both the kernel and user space program.

User space programs that support UFID are expected to provide it during flow setup in addition to the flow, then refer to the flow using the UFID for all future operations. The kernel is not required to index flows by the original flow key if a UFID is specified.

<a id="rst-basic-rule-for-evolving-flow-keys"></a>

## Basic rule for evolving flow keys

Some care is needed to really maintain forward and backward compatibility for applications that follow the rules listed under "Flow key compatibility" above.

The basic rule is obvious:



```text
==================================================================
New network protocol support must only supplement existing flow
key attributes.  It must not change the meaning of already defined
flow key attributes.
==================================================================
```

This rule does have less-obvious consequences so it is worth working through a few examples.  Suppose, for example, that the kernel module did not already implement VLAN parsing.  Instead, it just interpreted the 802.1Q TPID (0x8100) as the Ethertype then stopped parsing the packet.  The flow key for any packet with an 802.1Q header would look essentially like this, ignoring metadata:



```text
eth(...), eth_type(0x8100)
```

Naively, to add VLAN support, it makes sense to add a new "vlan" flow key attribute to contain the VLAN tag, then continue to decode the encapsulated headers beyond the VLAN tag using the existing field definitions.  With this change, a TCP packet in VLAN 10 would have a flow key much like this:



```text
eth(...), vlan(vid=10, pcp=0), eth_type(0x0800), ip(proto=6, ...), tcp(...)
```

But this change would negatively affect a userspace application that has not been updated to understand the new "vlan" flow key attribute. The application could, following the flow compatibility rules above, ignore the "vlan" attribute that it does not understand and therefore assume that the flow contained IP packets.  This is a bad assumption (the flow only contains IP packets if one parses and skips over the 802.1Q header) and it could cause the application's behavior to change across kernel versions even though it follows the compatibility rules.

The solution is to use a set of nested attributes.  This is, for example, why 802.1Q support uses nested attributes.  A TCP packet in VLAN 10 is actually expressed as:



```text
eth(...), eth_type(0x8100), vlan(vid=10, pcp=0), encap(eth_type(0x0800),
ip(proto=6, ...), tcp(...)))
```

Notice how the "eth_type", "ip", and "tcp" flow key attributes are nested inside the "encap" attribute.  Thus, an application that does not understand the "vlan" key will not see either of those attributes and therefore will not misinterpret them.  (Also, the outer eth_type is still 0x8100, not changed to 0x0800.)

<a id="rst-handling-malformed-packets"></a>

## Handling malformed packets

Don't drop packets in the kernel for malformed protocol headers, bad checksums, etc.  This would prevent userspace from implementing a simple Ethernet switch that forwards every packet.

Instead, in such a case, include an attribute with "empty" content. It doesn't matter if the empty content could be valid protocol values, as long as those values are rarely seen in practice, because userspace can always forward all packets with those values to userspace and handle them individually.

For example, consider a packet that contains an IP header that indicates protocol 6 for TCP, but which is truncated just after the IP header, so that the TCP header is missing.  The flow key for this packet would include a tcp attribute with all-zero src and dst, like this:



```text
eth(...), eth_type(0x0800), ip(proto=6, ...), tcp(src=0, dst=0)
```

As another example, consider a packet with an Ethernet type of 0x8100, indicating that a VLAN TCI should follow, but which is truncated just after the Ethernet type.  The flow key for this packet would include an all-zero-bits vlan and an empty encap attribute, like this:



```text
eth(...), eth_type(0x8100), vlan(0), encap()
```

Unlike a TCP packet with source and destination ports 0, an all-zero-bits VLAN TCI is not that rare, so the CFI bit (aka VLAN_TAG_PRESENT inside the kernel) is ordinarily set in a vlan attribute expressly to allow this situation to be distinguished. Thus, the flow key in this second example unambiguously indicates a missing or malformed VLAN TCI.

<a id="rst-other-rules"></a>

## Other rules

The other rules for flow keys are much less subtle:

> - Duplicate attributes are not allowed at a given nesting level.
>
> - Ordering of attributes is not significant.
>
> - When the kernel sends a given flow key to userspace, it always composes it the same way.  This allows userspace to hash and compare entire flow keys that it may not be able to fully interpret.

---

# Operational States

_Peios Kernel / Internals / Networking_

> Linux distinguishes between administrative and operational state of an interface. Administrative state is the result of "ip link set dev <dev> up or down" and reflects whether the administrator wants to use the device for traffic.

<a id="rst-operational-states"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## 1. Introduction

Linux distinguishes between administrative and operational state of an interface. Administrative state is the result of "ip link set dev &lt;dev&gt; up or down" and reflects whether the administrator wants to use the device for traffic.

However, an interface is not usable just because the admin enabled it - ethernet requires to be plugged into the switch and, depending on a site's networking policy and configuration, an 802.1X authentication to be performed before user data can be transferred. Operational state shows the ability of an interface to transmit this user data.

Thanks to 802.1X, userspace must be granted the possibility to influence operational state. To accommodate this, operational state is split into two parts: Two flags that can be set by the driver only, and a RFC2863 compatible state that is derived from these flags, a policy, and changeable from userspace under certain rules.

<a id="rst-querying-from-userspace"></a>

## 2. Querying from userspace

Both admin and operational state can be queried via the netlink operation RTM_GETLINK. It is also possible to subscribe to RTNLGRP_LINK to be notified of updates while the interface is admin up. This is important for setting from userspace.

These values contain interface state:

- **ifinfomsg::if_flags &amp; IFF_UP:**

  Interface is admin up

- **ifinfomsg::if_flags &amp; IFF_RUNNING:**

  Interface is in RFC2863 operational state UP or UNKNOWN. This is for backward compatibility, routing daemons, dhcp clients can use this flag to determine whether they should use the interface.

- **ifinfomsg::if_flags &amp; IFF_LOWER_UP:**

  Driver has signaled netif_carrier_on()

- **ifinfomsg::if_flags &amp; IFF_DORMANT:**

  Driver has signaled netif_dormant_on()

<a id="rst-tlv-ifla-operstate"></a>

### TLV IFLA_OPERSTATE

contains RFC2863 state of the interface in numeric representation:

- **IF_OPER_UNKNOWN (0):**

  Interface is in unknown state, neither driver nor userspace has set operational state. Interface must be considered for user data as setting operational state has not been implemented in every driver.

- **IF_OPER_NOTPRESENT (1):**

  Unused in current kernel (notpresent interfaces normally disappear), just a numerical placeholder.

- **IF_OPER_DOWN (2):**

  Interface is unable to transfer data on L1, f.e. ethernet is not plugged or interface is ADMIN down.

- **IF_OPER_LOWERLAYERDOWN (3):**

  Interfaces stacked on an interface that is IF_OPER_DOWN show this state (f.e. VLAN).

- **IF_OPER_TESTING (4):**

  Interface is in testing mode, for example executing driver self-tests or media (cable) test. It can't be used for normal traffic until tests complete.

- **IF_OPER_DORMANT (5):**

  Interface is L1 up, but waiting for an external event, f.e. for a protocol to establish. (802.1X)

- **IF_OPER_UP (6):**

  Interface is operational up and can be used.

This TLV can also be queried via sysfs.

<a id="rst-tlv-ifla-linkmode"></a>

### TLV IFLA_LINKMODE

contains link policy. This is needed for userspace interaction described below.

This TLV can also be queried via sysfs.

<a id="rst-kernel-driver-api"></a>

## 3. Kernel driver API

Kernel drivers have access to two flags that map to IFF_LOWER_UP and IFF_DORMANT. These flags can be set from everywhere, even from interrupts. It is guaranteed that only the driver has write access, however, if different layers of the driver manipulate the same flag, the driver has to provide the synchronisation needed.

\__LINK_STATE_NOCARRIER, maps to \!IFF_LOWER_UP:

The driver uses netif_carrier_on() to clear and netif_carrier_off() to set this flag. On netif_carrier_off(), the scheduler stops sending packets. The name 'carrier' and the inversion are historical, think of it as lower layer.

Note that for certain kind of soft-devices, which are not managing any real hardware, it is possible to set this bit from userspace.  One should use TLV IFLA_CARRIER to do so.

netif_carrier_ok() can be used to query that bit.

\__LINK_STATE_DORMANT, maps to IFF_DORMANT:

Set by the driver to express that the device cannot yet be used because some driver controlled protocol establishment has to complete. Corresponding functions are netif_dormant_on() to set the flag, netif_dormant_off() to clear it and netif_dormant() to query.

On device allocation, both flags \__LINK_STATE_NOCARRIER and \__LINK_STATE_DORMANT are cleared, so the effective state is equivalent to netif_carrier_ok() and \!netif_dormant().

Whenever the driver CHANGES one of these flags, a workqueue event is scheduled to translate the flag combination to IFLA_OPERSTATE as follows:

- **\!netif_carrier_ok():**

  IF_OPER_LOWERLAYERDOWN if the interface is stacked, IF_OPER_DOWN otherwise. Kernel can recognise stacked interfaces because their ifindex \!= iflink.

- **netif_carrier_ok() &amp;&amp; netif_dormant():**

  IF_OPER_DORMANT

- **netif_carrier_ok() &amp;&amp; \!netif_dormant():**

  IF_OPER_UP if userspace interaction is disabled. Otherwise IF_OPER_DORMANT with the possibility for userspace to initiate the IF_OPER_UP transition afterwards.

<a id="rst-setting-from-userspace"></a>

## 4. Setting from userspace

Applications have to use the netlink interface to influence the RFC2863 operational state of an interface. Setting IFLA_LINKMODE to 1 via RTM_SETLINK instructs the kernel that an interface should go to IF_OPER_DORMANT instead of IF_OPER_UP when the combination netif_carrier_ok() &amp;&amp; \!netif_dormant() is set by the driver. Afterwards, the userspace application can set IFLA_OPERSTATE to IF_OPER_DORMANT or IF_OPER_UP as long as the driver does not set netif_carrier_off() or netif_dormant_on(). Changes made by userspace are multicasted on the netlink group RTNLGRP_LINK.

So basically a 802.1X supplicant interacts with the kernel like this:

- subscribe to RTNLGRP_LINK

- set IFLA_LINKMODE to 1 via RTM_SETLINK

- query RTM_GETLINK once to get initial state

- if initial flags are not (IFF_LOWER_UP &amp;&amp; \!IFF_DORMANT), wait until netlink multicast signals this state

- do 802.1X, eventually abort if flags go down again

- send RTM_SETLINK to set operstate to IF_OPER_UP if authentication succeeds, IF_OPER_DORMANT otherwise

- see how operstate and IFF_RUNNING is echoed via netlink multicast

- set interface back to IF_OPER_DORMANT if 802.1X reauthentication fails

- restart if kernel changes IFF_LOWER_UP or IFF_DORMANT flag

if supplicant goes down, bring back IFLA_LINKMODE to 0 and IFLA_OPERSTATE to a sane value.

A routing daemon or dhcp client just needs to care for IFF_RUNNING or waiting for operstate to go IF_OPER_UP/IF_OPER_UNKNOWN before considering the interface / querying a DHCP address.

For technical questions and/or comments please e-mail to Stefan Rompf (stefan at loplof.de).

---

# Packet MMAP

_Peios Kernel / Internals / Networking_

> This file documents the mmap() facility available with the PACKET socket interface. This type of sockets is used for

<a id="rst-packet-mmap"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-abstract"></a>

## Abstract

This file documents the mmap() facility available with the PACKET socket interface. This type of sockets is used for

- **i)** capture network traffic with utilities like tcpdump,

- **ii)** transmit network traffic, or any other that needs raw access to network interface.

Howto can be found at:

> [https://web.archive.org/web/20220404160947/https://sites.google.com/site/packetmmap/](<https://web.archive.org/web/20220404160947/https://sites.google.com/site/packetmmap/>)

- **Please send your comments to**

  - Ulisses Alonso Camaró &lt;[uaca@i.hate.spam.alumni.uv.es](<mailto:uaca@i.hate.spam.alumni.uv.es>)&gt;

  - Johann Baudy

<a id="rst-why-use-packet-mmap"></a>

## Why use PACKET_MMAP

Non PACKET_MMAP capture process (plain AF_PACKET) is very inefficient. It uses very limited buffers and requires one system call to capture each packet, it requires two if you want to get packet's timestamp (like libpcap always does).

On the other hand PACKET_MMAP is very efficient. PACKET_MMAP provides a size configurable circular buffer mapped in user space that can be used to either send or receive packets. This way reading packets just needs to wait for them, most of the time there is no need to issue a single system call. Concerning transmission, multiple packets can be sent through one system call to get the highest bandwidth. By using a shared buffer between the kernel and the user also has the benefit of minimizing packet copies.

It's fine to use PACKET_MMAP to improve the performance of the capture and transmission process, but it isn't everything. At least, if you are capturing at high speeds (this is relative to the cpu speed), you should check if the device driver of your network interface card supports some sort of interrupt load mitigation or (even better) if it supports NAPI, also make sure it is enabled. For transmission, check the MTU (Maximum Transmission Unit) used and supported by devices of your network. CPU IRQ pinning of your network interface card can also be an advantage.

<a id="rst-how-to-use-mmap-to-improve-capture-process"></a>

## How to use mmap() to improve capture process

From the user standpoint, you should use the higher level libpcap library, which is a de facto standard, portable across nearly all operating systems including Win32.

Packet MMAP support was integrated into libpcap around the time of version 1.3.0; TPACKET_V3 support was added in version 1.5.0

<a id="rst-how-to-use-mmap-directly-to-improve-capture-process"></a>

## How to use mmap() directly to improve capture process

From the system calls stand point, the use of PACKET_MMAP involves the following process:



```text
[setup]     socket() -------> creation of the capture socket
            setsockopt() ---> allocation of the circular buffer (ring)
                              option: PACKET_RX_RING
            mmap() ---------> mapping of the allocated buffer to the
                              user process

[capture]   poll() ---------> to wait for incoming packets

[shutdown]  close() --------> destruction of the capture socket and
                              deallocation of all associated
                              resources.
```

socket creation and destruction is straight forward, and is done the same way with or without PACKET_MMAP:



```text
int fd = socket(PF_PACKET, mode, htons(ETH_P_ALL));
```

where mode is SOCK_RAW for the raw interface were link level information can be captured or SOCK_DGRAM for the cooked interface where link level information capture is not supported and a link level pseudo-header is provided by the kernel.

The destruction of the socket and all associated resources is done by a simple call to close(fd).

Similarly as without PACKET_MMAP, it is possible to use one socket for capture and transmission. This can be done by mapping the allocated RX and TX buffer ring with a single mmap() call. See "Mapping and use of the circular buffer (ring)".

Next I will describe PACKET_MMAP settings and its constraints, also the mapping of the circular buffer in the user process and the use of this buffer.

<a id="rst-how-to-use-mmap-directly-to-improve-transmission-process"></a>

## How to use mmap() directly to improve transmission process

Transmission process is similar to capture as shown below:



```text
[setup]         socket() -------> creation of the transmission socket
                setsockopt() ---> allocation of the circular buffer (ring)
                                  option: PACKET_TX_RING
                bind() ---------> bind transmission socket with a network interface
                mmap() ---------> mapping of the allocated buffer to the
                                  user process

[transmission]  poll() ---------> wait for free packets (optional)
                send() ---------> send all packets that are set as ready in
                                  the ring
                                  The flag MSG_DONTWAIT can be used to return
                                  before end of transfer.

[shutdown]      close() --------> destruction of the transmission socket and
                                  deallocation of all associated resources.
```

Socket creation and destruction is also straight forward, and is done the same way as in capturing described in the previous paragraph:



```text
int fd = socket(PF_PACKET, mode, 0);
```

The protocol can optionally be 0 in case we only want to transmit via this socket, which avoids an expensive call to packet_rcv(). In this case, you also need to bind(2) the TX_RING with sll_protocol = 0 set. Otherwise, htons(ETH_P_ALL) or any other protocol, for example.

Binding the socket to your network interface is mandatory (with zero copy) to know the header size of frames used in the circular buffer.

As capture, each frame contains two parts:



```text
   --------------------
   | struct tpacket_hdr | Header. It contains the status of
   |                    | of this frame
   |--------------------|
   | data buffer        |
   .                    .  Data that will be sent over the network interface.
   .                    .
   --------------------

bind() associates the socket to your network interface thanks to
sll_ifindex parameter of struct sockaddr_ll.

Initialization example::

   struct sockaddr_ll my_addr;
   struct ifreq s_ifr;
   ...

   strscpy_pad (s_ifr.ifr_name, "eth0", sizeof(s_ifr.ifr_name));

   /* get interface index of eth0 */
   ioctl(this->socket, SIOCGIFINDEX, &s_ifr);

   /* fill sockaddr_ll struct to prepare binding */
   my_addr.sll_family = AF_PACKET;
   my_addr.sll_protocol = htons(ETH_P_ALL);
   my_addr.sll_ifindex =  s_ifr.ifr_ifindex;

   /* bind socket to eth0 */
   bind(this->socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll));

A complete tutorial is available at:
https://web.archive.org/web/20220404160947/https://sites.google.com/site/packetmmap/
```

By default, the user should put data at:



```text
frame base + TPACKET_HDRLEN - sizeof(struct sockaddr_ll)
```

So, whatever you choose for the socket mode (SOCK_DGRAM or SOCK_RAW), the beginning of the user data will be at:



```text
frame base + TPACKET_ALIGN(sizeof(struct tpacket_hdr))
```

If you wish to put user data at a custom offset from the beginning of the frame (for payload alignment with SOCK_RAW mode for instance) you can set tp_net (with SOCK_DGRAM) or tp_mac (with SOCK_RAW). In order to make this work it must be enabled previously with setsockopt() and the PACKET_TX_HAS_OFF option.

<a id="rst-packet-mmap-settings"></a>

## PACKET_MMAP settings

To setup PACKET_MMAP from user level code is done with a call like

> - Capture process:
>
>
>
>   ```text
>   setsockopt(fd, SOL_PACKET, PACKET_RX_RING, (void *) &req, sizeof(req))
>   ```
>
> - Transmission process:
>
>
>
>   ```text
>   setsockopt(fd, SOL_PACKET, PACKET_TX_RING, (void *) &req, sizeof(req))
>   ```

The most significant argument in the previous call is the req parameter, this parameter must to have the following structure:



```text
struct tpacket_req
{
    unsigned int    tp_block_size;  /* Minimal size of contiguous block */
    unsigned int    tp_block_nr;    /* Number of blocks */
    unsigned int    tp_frame_size;  /* Size of frame */
    unsigned int    tp_frame_nr;    /* Total number of frames */
};
```

This structure is defined in /usr/include/linux/if_packet.h and establishes a circular buffer (ring) of unswappable memory. Being mapped in the capture process allows reading the captured frames and related meta-information like timestamps without requiring a system call.

Frames are grouped in blocks. Each block is a physically contiguous region of memory and holds tp_block_size/tp_frame_size frames. The total number of blocks is tp_block_nr. Note that tp_frame_nr is a redundant parameter because:



```text
frames_per_block = tp_block_size/tp_frame_size
```

indeed, packet_set_ring checks that the following condition is true:



```text
frames_per_block * tp_block_nr == tp_frame_nr
```

Lets see an example, with the following values:



```text
tp_block_size= 4096
tp_frame_size= 2048
tp_block_nr  = 4
tp_frame_nr  = 8
```

we will get the following buffer structure:



```text
        block #1                 block #2
+---------+---------+    +---------+---------+
| frame 1 | frame 2 |    | frame 3 | frame 4 |
+---------+---------+    +---------+---------+

        block #3                 block #4
+---------+---------+    +---------+---------+
| frame 5 | frame 6 |    | frame 7 | frame 8 |
+---------+---------+    +---------+---------+
```

A frame can be of any size with the only condition it can fit in a block. A block can only hold an integer number of frames, or in other words, a frame cannot be spawned across two blocks, so there are some details you have to take into account when choosing the frame_size. See "Mapping and use of the circular buffer (ring)".

<a id="rst-packet-mmap-setting-constraints"></a>

## PACKET_MMAP setting constraints

In kernel versions prior to 2.4.26 (for the 2.4 branch) and 2.6.5 (2.6 branch), the PACKET_MMAP buffer could hold only 32768 frames in a 32 bit architecture or 16384 in a 64 bit architecture.

<a id="rst-block-size-limit"></a>

### Block size limit

As stated earlier, each block is a contiguous physical region of memory. These memory regions are allocated with calls to the \__get_free_pages() function. As the name indicates, this function allocates pages of memory, and the second argument is "order" or a power of two number of pages, that is (for PAGE_SIZE == 4096) order=0 ==&gt; 4096 bytes, order=1 ==&gt; 8192 bytes, order=2 ==&gt; 16384 bytes, etc. The maximum size of a region allocated by \__get_free_pages is determined by the MAX_PAGE_ORDER macro. More precisely the limit can be calculated as:



```text
PAGE_SIZE << MAX_PAGE_ORDER

In a i386 architecture PAGE_SIZE is 4096 bytes
In a 2.4/i386 kernel MAX_PAGE_ORDER is 10
In a 2.6/i386 kernel MAX_PAGE_ORDER is 11
```

So get_free_pages can allocate as much as 4MB or 8MB in a 2.4/2.6 kernel respectively, with an i386 architecture.

User space programs can include /usr/include/sys/user.h and /usr/include/linux/mmzone.h to get PAGE_SIZE MAX_PAGE_ORDER declarations.

The pagesize can also be determined dynamically with the getpagesize (2) system call.

<a id="rst-block-number-limit"></a>

### Block number limit

To understand the constraints of PACKET_MMAP, we have to see the structure used to hold the pointers to each block.

Currently, this structure is a dynamically allocated vector with kmalloc called pg_vec, its size limits the number of blocks that can be allocated:



```text
+---+---+---+---+
| x | x | x | x |
+---+---+---+---+
  |   |   |   |
  |   |   |   v
  |   |   v  block #4
  |   v  block #3
  v  block #2
 block #1
```

kmalloc allocates any number of bytes of physically contiguous memory from a pool of pre-determined sizes. This pool of memory is maintained by the slab allocator which is at the end the responsible for doing the allocation and hence which imposes the maximum memory that kmalloc can allocate.

In a 2.4/2.6 kernel and the i386 architecture, the limit is 131072 bytes. The predetermined sizes that kmalloc uses can be checked in the "size-&lt;bytes&gt;" entries of /proc/slabinfo

In a 32 bit architecture, pointers are 4 bytes long, so the total number of pointers to blocks is:



```text
131072/4 = 32768 blocks
```

<a id="rst-packet-mmap-buffer-size-calculator"></a>

## PACKET_MMAP buffer size calculator

Definitions:


<table>
<tbody>
<tr>
<td>


&lt;size-max&gt;

</td>
<td>


is the maximum size of allocable with kmalloc (see /proc/slabinfo)

</td>
</tr>
<tr>
<td>


&lt;pointer size&gt;

</td>
<td>


depends on the architecture -- `sizeof(void *)`

</td>
</tr>
<tr>
<td>


&lt;page size&gt;

</td>
<td>


depends on the architecture -- PAGE_SIZE or getpagesize (2)

</td>
</tr>
<tr>
<td>


&lt;max-order&gt;

</td>
<td>


is the value defined with MAX_PAGE_ORDER

</td>
</tr>
<tr>
<td>


&lt;frame size&gt;

</td>
<td>


it's an upper bound of frame's capture size (more on this later)

</td>
</tr>
</tbody>
</table>

from these definitions we will derive:



```text
<block number> = <size-max>/<pointer size>
<block size> = <pagesize> << <max-order>
```

so, the max buffer size is:



```text
<block number> * <block size>
```

and, the number of frames be:



```text
<block number> * <block size> / <frame size>
```

Suppose the following parameters, which apply for 2.6 kernel and an i386 architecture:



```text
<size-max> = 131072 bytes
<pointer size> = 4 bytes
<pagesize> = 4096 bytes
<max-order> = 11
```

and a value for &lt;frame size&gt; of 2048 bytes. These parameters will yield:



```text
<block number> = 131072/4 = 32768 blocks
<block size> = 4096 << 11 = 8 MiB.
```

and hence the buffer will have a 262144 MiB size. So it can hold 262144 MiB / 2048 bytes = 134217728 frames

Actually, this buffer size is not possible with an i386 architecture. Remember that the memory is allocated in kernel space, in the case of an i386 kernel's memory size is limited to 1GiB.

All memory allocations are not freed until the socket is closed. The memory allocations are done with GFP_KERNEL priority, this basically means that the allocation can wait and swap other process' memory in order to allocate the necessary memory, so normally limits can be reached.

<a id="rst-other-constraints"></a>

### Other constraints

If you check the source code you will see that what I draw here as a frame is not only the link level frame. At the beginning of each frame there is a header called struct tpacket_hdr used in PACKET_MMAP to hold link level's frame meta information like timestamp. So what we draw here a frame it's really the following (from include/linux/if_packet.h):



```text
/*
  Frame structure:

  - Start. Frame must be aligned to TPACKET_ALIGNMENT=16
  - struct tpacket_hdr
  - pad to TPACKET_ALIGNMENT=16
  - struct sockaddr_ll
  - Gap, chosen so that packet data (Start+tp_net) aligns to
    TPACKET_ALIGNMENT=16
  - Start+tp_mac: [ Optional MAC header ]
  - Start+tp_net: Packet data, aligned to TPACKET_ALIGNMENT=16.
  - Pad to align to TPACKET_ALIGNMENT=16
*/
```

The following are conditions that are checked in packet_set_ring

> - tp_block_size must be a multiple of PAGE_SIZE (1)
>
> - tp_frame_size must be greater than TPACKET_HDRLEN (obvious)
>
> - tp_frame_size must be a multiple of TPACKET_ALIGNMENT
>
> - tp_frame_nr   must be exactly frames_per_block\*tp_block_nr

Note that tp_block_size should be chosen to be a power of two or there will be a waste of memory.

<a id="rst-mapping-and-use-of-the-circular-buffer-ring"></a>

### Mapping and use of the circular buffer (ring)

The mapping of the buffer in the user process is done with the conventional mmap function. Even the circular buffer is compound of several physically discontiguous blocks of memory, they are contiguous to the user space, hence just one call to mmap is needed:



```text
mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
```

If tp_frame_size is a divisor of tp_block_size frames will be contiguously spaced by tp_frame_size bytes. If not, each tp_block_size/tp_frame_size frames there will be a gap between the frames. This is because a frame cannot be spawn across two blocks.

To use one socket for capture and transmission, the mapping of both the RX and TX buffer ring has to be done with one call to mmap:



```text
...
setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &foo, sizeof(foo));
setsockopt(fd, SOL_PACKET, PACKET_TX_RING, &bar, sizeof(bar));
...
rx_ring = mmap(0, size * 2, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
tx_ring = rx_ring + size;
```

RX must be the first as the kernel maps the TX ring memory right after the RX one.

At the beginning of each frame there is an status field (see struct tpacket_hdr). If this field is 0 means that the frame is ready to be used for the kernel, If not, there is a frame the user can read and the following flags apply:

<a id="rst-capture-process"></a>

#### Capture process

From include/linux/if_packet.h:



```text
#define TP_STATUS_COPY          (1 << 1)
#define TP_STATUS_LOSING        (1 << 2)
#define TP_STATUS_CSUMNOTREADY  (1 << 3)
#define TP_STATUS_CSUM_VALID    (1 << 7)
```


<table>
<tbody>
<tr>
<td>


TP_STATUS_COPY

</td>
<td>


This flag indicates that the frame (and associated meta information) has been truncated because it's larger than tp_frame_size. This packet can be read entirely with recvfrom().

In order to make this work it must to be enabled previously with setsockopt() and the PACKET_COPY_THRESH option.

The number of frames that can be buffered to be read with recvfrom is limited like a normal socket. See the SO_RCVBUF option in the socket (7) man page.

</td>
</tr>
<tr>
<td>


TP_STATUS_LOSING

</td>
<td>


indicates there were packet drops from last time statistics where checked with getsockopt() and the PACKET_STATISTICS option.

</td>
</tr>
<tr>
<td>


TP_STATUS_CSUMNOTREADY

</td>
<td>


currently it's used for outgoing IP packets which its checksum will be done in hardware. So while reading the packet we should not try to check the checksum.

</td>
</tr>
<tr>
<td>


TP_STATUS_CSUM_VALID

</td>
<td>


This flag indicates that at least the transport header checksum of the packet has been already validated on the kernel side. If the flag is not set then we are free to check the checksum by ourselves provided that TP_STATUS_CSUMNOTREADY is also not set.

</td>
</tr>
</tbody>
</table>

for convenience there are also the following defines:



```text
#define TP_STATUS_KERNEL        0
#define TP_STATUS_USER          1
```

The kernel initializes all frames to TP_STATUS_KERNEL, when the kernel receives a packet it puts in the buffer and updates the status with at least the TP_STATUS_USER flag. Then the user can read the packet, once the packet is read the user must zero the status field, so the kernel can use again that frame buffer.

The user can use poll (any other variant should apply too) to check if new packets are in the ring:



```text
struct pollfd pfd;

pfd.fd = fd;
pfd.revents = 0;
pfd.events = POLLIN|POLLRDNORM|POLLERR;

if (status == TP_STATUS_KERNEL)
    retval = poll(&pfd, 1, timeout);
```

It doesn't incur in a race condition to first check the status value and then poll for frames.

<a id="rst-transmission-process"></a>

#### Transmission process

Those defines are also used for transmission:



```text
#define TP_STATUS_AVAILABLE        0 // Frame is available
#define TP_STATUS_SEND_REQUEST     1 // Frame will be sent on next send()
#define TP_STATUS_SENDING          2 // Frame is currently in transmission
#define TP_STATUS_WRONG_FORMAT     4 // Frame format is not correct
```

First, the kernel initializes all frames to TP_STATUS_AVAILABLE. To send a packet, the user fills a data buffer of an available frame, sets tp_len to current data buffer size and sets its status field to TP_STATUS_SEND_REQUEST. This can be done on multiple frames. Once the user is ready to transmit, it calls send(). Then all buffers with status equal to TP_STATUS_SEND_REQUEST are forwarded to the network device. The kernel updates each status of sent frames with TP_STATUS_SENDING until the end of transfer.

At the end of each transfer, buffer status returns to TP_STATUS_AVAILABLE.



```text
header->tp_len = in_i_size;
header->tp_status = TP_STATUS_SEND_REQUEST;
retval = send(this->socket, NULL, 0, 0);
```

The user can also use poll() to check if a buffer is available:

(status == TP_STATUS_SENDING)



```text
struct pollfd pfd;
pfd.fd = fd;
pfd.revents = 0;
pfd.events = POLLOUT;
retval = poll(&pfd, 1, timeout);
```

<a id="rst-what-tpacket-versions-are-available-and-when-to-use-them"></a>

## What TPACKET versions are available and when to use them?



```text
int val = tpacket_version;
setsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
getsockopt(fd, SOL_PACKET, PACKET_VERSION, &val, sizeof(val));
```

where 'tpacket_version' can be TPACKET_V1 (default), TPACKET_V2, TPACKET_V3.

- **TPACKET_V1:**

  - Default if not otherwise specified by setsockopt(2)

  - RX_RING, TX_RING available

- **TPACKET_V1 --&gt; TPACKET_V2:**

  - Made 64 bit clean due to unsigned long usage in TPACKET_V1 structures, thus this also works on 64 bit kernel with 32 bit userspace and the like

  - Timestamp resolution in nanoseconds instead of microseconds

  - RX_RING, TX_RING available

  - VLAN metadata information available for packets (TP_STATUS_VLAN_VALID, TP_STATUS_VLAN_TPID_VALID), in the tpacket2_hdr structure:

    > - TP_STATUS_VLAN_VALID bit being set into the tp_status field indicates that the tp_vlan_tci field has valid VLAN TCI value
    >
    > - TP_STATUS_VLAN_TPID_VALID bit being set into the tp_status field indicates that the tp_vlan_tpid field has valid VLAN TPID value

  - How to switch to TPACKET_V2:

    > 1. Replace struct tpacket_hdr by struct tpacket2_hdr
    >
    > 2. Query header len and save
    >
    > 3. Set protocol version to 2, set up ring as usual
    >
    > 4. For getting the sockaddr_ll, use `(void *)hdr + TPACKET_ALIGN(hdrlen)` instead of `(void *)hdr + TPACKET_ALIGN(sizeof(struct tpacket_hdr))`

- **TPACKET_V2 --&gt; TPACKET_V3:**

  - - **Flexible buffer implementation for RX_RING:**

      1. Blocks can be configured with non-static frame-size

      2. Read/poll is at a block-level (as opposed to packet-level)

      3. Added poll timeout to avoid indefinite user-space wait on idle links

      4. Added user-configurable knobs:

         > 4.1 block::timeout 4.2 tpkt_hdr::sk_rxhash

  - RX Hash data available in user space

  - TX_RING semantics are conceptually similar to TPACKET_V2; use tpacket3_hdr instead of tpacket2_hdr, and TPACKET3_HDRLEN instead of TPACKET2_HDRLEN. In the current implementation, the tp_next_offset field in the tpacket3_hdr MUST be set to zero, indicating that the ring does not hold variable sized frames. Packets with non-zero values of tp_next_offset will be dropped.

<a id="rst-af-packet-fanout-mode"></a>

## AF_PACKET fanout mode

In the AF_PACKET fanout mode, packet reception can be load balanced among processes. This also works in combination with mmap(2) on packet sockets.

Currently implemented fanout policies are:

> - PACKET_FANOUT_HASH: schedule to socket by skb's packet hash
>
> - PACKET_FANOUT_LB: schedule to socket by round-robin
>
> - PACKET_FANOUT_CPU: schedule to socket by CPU packet arrives on
>
> - PACKET_FANOUT_RND: schedule to socket by random selection
>
> - PACKET_FANOUT_ROLLOVER: if one socket is full, rollover to another
>
> - PACKET_FANOUT_QM: schedule to socket by skbs recorded queue_mapping

Minimal example code by David S. Miller (try things like "./test eth0 hash", "./test eth0 lb", etc.):



```text
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

#include <unistd.h>

#include <linux/if_ether.h>
#include <linux/if_packet.h>

#include <net/if.h>

static const char *device_name;
static int fanout_type;
static int fanout_id;

#ifndef PACKET_FANOUT
# define PACKET_FANOUT                      18
# define PACKET_FANOUT_HASH         0
# define PACKET_FANOUT_LB           1
#endif

static int setup_socket(void)
{
        int err, fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
        struct sockaddr_ll ll;
        struct ifreq ifr;
        int fanout_arg;

        if (fd < 0) {
                perror("socket");
                return EXIT_FAILURE;
        }

        memset(&ifr, 0, sizeof(ifr));
        strcpy(ifr.ifr_name, device_name);
        err = ioctl(fd, SIOCGIFINDEX, &ifr);
        if (err < 0) {
                perror("SIOCGIFINDEX");
                return EXIT_FAILURE;
        }

        memset(&ll, 0, sizeof(ll));
        ll.sll_family = AF_PACKET;
        ll.sll_ifindex = ifr.ifr_ifindex;
        err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
        if (err < 0) {
                perror("bind");
                return EXIT_FAILURE;
        }

        fanout_arg = (fanout_id | (fanout_type << 16));
        err = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,
                        &fanout_arg, sizeof(fanout_arg));
        if (err) {
                perror("setsockopt");
                return EXIT_FAILURE;
        }

        return fd;
}

static void fanout_thread(void)
{
        int fd = setup_socket();
        int limit = 10000;

        if (fd < 0)
                exit(fd);

        while (limit-- > 0) {
                char buf[1600];
                int err;

                err = read(fd, buf, sizeof(buf));
                if (err < 0) {
                        perror("read");
                        exit(EXIT_FAILURE);
                }
                if ((limit % 10) == 0)
                        fprintf(stdout, "(%d) \n", getpid());
        }

        fprintf(stdout, "%d: Received 10000 packets\n", getpid());

        close(fd);
        exit(0);
}

int main(int argc, char **argp)
{
        int fd, err;
        int i;

        if (argc != 3) {
                fprintf(stderr, "Usage: %s INTERFACE {hash|lb}\n", argp[0]);
                return EXIT_FAILURE;
        }

        if (!strcmp(argp[2], "hash"))
                fanout_type = PACKET_FANOUT_HASH;
        else if (!strcmp(argp[2], "lb"))
                fanout_type = PACKET_FANOUT_LB;
        else {
                fprintf(stderr, "Unknown fanout type [%s]\n", argp[2]);
                exit(EXIT_FAILURE);
        }

        device_name = argp[1];
        fanout_id = getpid() & 0xffff;

        for (i = 0; i < 4; i++) {
                pid_t pid = fork();

                switch (pid) {
                case 0:
                        fanout_thread();

                case -1:
                        perror("fork");
                        exit(EXIT_FAILURE);
                }
        }

        for (i = 0; i < 4; i++) {
                int status;

                wait(&status);
        }

        return 0;
}
```

<a id="rst-af-packet-tpacket-v3-example"></a>

## AF_PACKET TPACKET_V3 example

AF_PACKET's TPACKET_V3 ring buffer can be configured to use non-static frame sizes by doing its own memory management. It is based on blocks where polling works on a per block basis instead of per ring as in TPACKET_V2 and predecessor.

It is said that TPACKET_V3 brings the following benefits:

> - \~15% - 20% reduction in CPU-usage
>
> - \~20% increase in packet capture rate
>
> - \~2x increase in packet density
>
> - Port aggregation analysis
>
> - Non static frame size to capture entire packet payload

So it seems to be a good candidate to be used with packet fanout.

Minimal example code by Daniel Borkmann based on Chetan Loke's lolpcap (compile it with gcc -Wall -O2 blob.c, and try things like "./a.out eth0", etc.):



```text
/* Written from scratch, but kernel-to-user space API usage
* dissected from lolpcap:
*  Copyright 2011, Chetan Loke <loke.chetan@gmail.com>
*  License: GPL, version 2.0
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#include <unistd.h>
#include <signal.h>
#include <inttypes.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/ip.h>

#ifndef likely
# define likely(x)          __builtin_expect(!!(x), 1)
#endif
#ifndef unlikely
# define unlikely(x)                __builtin_expect(!!(x), 0)
#endif

struct block_desc {
        uint32_t version;
        uint32_t offset_to_priv;
        struct tpacket_hdr_v1 h1;
};

struct ring {
        struct iovec *rd;
        uint8_t *map;
        struct tpacket_req3 req;
};

static unsigned long packets_total = 0, bytes_total = 0;
static sig_atomic_t sigint = 0;

static void sighandler(int num)
{
        sigint = 1;
}

static int setup_socket(struct ring *ring, char *netdev)
{
        int err, i, fd, v = TPACKET_V3;
        struct sockaddr_ll ll;
        unsigned int blocksiz = 1 << 22, framesiz = 1 << 11;
        unsigned int blocknum = 64;

        fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
        if (fd < 0) {
                perror("socket");
                exit(1);
        }

        err = setsockopt(fd, SOL_PACKET, PACKET_VERSION, &v, sizeof(v));
        if (err < 0) {
                perror("setsockopt");
                exit(1);
        }

        memset(&ring->req, 0, sizeof(ring->req));
        ring->req.tp_block_size = blocksiz;
        ring->req.tp_frame_size = framesiz;
        ring->req.tp_block_nr = blocknum;
        ring->req.tp_frame_nr = (blocksiz * blocknum) / framesiz;
        ring->req.tp_retire_blk_tov = 60;
        ring->req.tp_feature_req_word = TP_FT_REQ_FILL_RXHASH;

        err = setsockopt(fd, SOL_PACKET, PACKET_RX_RING, &ring->req,
                        sizeof(ring->req));
        if (err < 0) {
                perror("setsockopt");
                exit(1);
        }

        ring->map = mmap(NULL, ring->req.tp_block_size * ring->req.tp_block_nr,
                        PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, 0);
        if (ring->map == MAP_FAILED) {
                perror("mmap");
                exit(1);
        }

        ring->rd = malloc(ring->req.tp_block_nr * sizeof(*ring->rd));
        assert(ring->rd);
        for (i = 0; i < ring->req.tp_block_nr; ++i) {
                ring->rd[i].iov_base = ring->map + (i * ring->req.tp_block_size);
                ring->rd[i].iov_len = ring->req.tp_block_size;
        }

        memset(&ll, 0, sizeof(ll));
        ll.sll_family = PF_PACKET;
        ll.sll_protocol = htons(ETH_P_ALL);
        ll.sll_ifindex = if_nametoindex(netdev);
        ll.sll_hatype = 0;
        ll.sll_pkttype = 0;
        ll.sll_halen = 0;

        err = bind(fd, (struct sockaddr *) &ll, sizeof(ll));
        if (err < 0) {
                perror("bind");
                exit(1);
        }

        return fd;
}

static void display(struct tpacket3_hdr *ppd)
{
        struct ethhdr *eth = (struct ethhdr *) ((uint8_t *) ppd + ppd->tp_mac);
        struct iphdr *ip = (struct iphdr *) ((uint8_t *) eth + ETH_HLEN);

        if (eth->h_proto == htons(ETH_P_IP)) {
                struct sockaddr_in ss, sd;
                char sbuff[NI_MAXHOST], dbuff[NI_MAXHOST];

                memset(&ss, 0, sizeof(ss));
                ss.sin_family = PF_INET;
                ss.sin_addr.s_addr = ip->saddr;
                getnameinfo((struct sockaddr *) &ss, sizeof(ss),
                            sbuff, sizeof(sbuff), NULL, 0, NI_NUMERICHOST);

                memset(&sd, 0, sizeof(sd));
                sd.sin_family = PF_INET;
                sd.sin_addr.s_addr = ip->daddr;
                getnameinfo((struct sockaddr *) &sd, sizeof(sd),
                            dbuff, sizeof(dbuff), NULL, 0, NI_NUMERICHOST);

                printf("%s -> %s, ", sbuff, dbuff);
        }

        printf("rxhash: 0x%x\n", ppd->hv1.tp_rxhash);
}

static void walk_block(struct block_desc *pbd, const int block_num)
{
        int num_pkts = pbd->h1.num_pkts, i;
        unsigned long bytes = 0;
        struct tpacket3_hdr *ppd;

        ppd = (struct tpacket3_hdr *) ((uint8_t *) pbd +
                                    pbd->h1.offset_to_first_pkt);
        for (i = 0; i < num_pkts; ++i) {
                bytes += ppd->tp_snaplen;
                display(ppd);

                ppd = (struct tpacket3_hdr *) ((uint8_t *) ppd +
                                            ppd->tp_next_offset);
        }

        packets_total += num_pkts;
        bytes_total += bytes;
}

static void flush_block(struct block_desc *pbd)
{
        pbd->h1.block_status = TP_STATUS_KERNEL;
}

static void teardown_socket(struct ring *ring, int fd)
{
        munmap(ring->map, ring->req.tp_block_size * ring->req.tp_block_nr);
        free(ring->rd);
        close(fd);
}

int main(int argc, char **argp)
{
        int fd, err;
        socklen_t len;
        struct ring ring;
        struct pollfd pfd;
        unsigned int block_num = 0, blocks = 64;
        struct block_desc *pbd;
        struct tpacket_stats_v3 stats;

        if (argc != 2) {
                fprintf(stderr, "Usage: %s INTERFACE\n", argp[0]);
                return EXIT_FAILURE;
        }

        signal(SIGINT, sighandler);

        memset(&ring, 0, sizeof(ring));
        fd = setup_socket(&ring, argp[argc - 1]);
        assert(fd > 0);

        memset(&pfd, 0, sizeof(pfd));
        pfd.fd = fd;
        pfd.events = POLLIN | POLLERR;
        pfd.revents = 0;

        while (likely(!sigint)) {
                pbd = (struct block_desc *) ring.rd[block_num].iov_base;

                if ((pbd->h1.block_status & TP_STATUS_USER) == 0) {
                        poll(&pfd, 1, -1);
                        continue;
                }

                walk_block(pbd, block_num);
                flush_block(pbd);
                block_num = (block_num + 1) % blocks;
        }

        len = sizeof(stats);
        err = getsockopt(fd, SOL_PACKET, PACKET_STATISTICS, &stats, &len);
        if (err < 0) {
                perror("getsockopt");
                exit(1);
        }

        fflush(stdout);
        printf("\nReceived %u packets, %lu bytes, %u dropped, freeze_q_cnt: %u\n",
            stats.tp_packets, bytes_total, stats.tp_drops,
            stats.tp_freeze_q_cnt);

        teardown_socket(&ring, fd);
        return 0;
}
```

<a id="rst-packet-qdisc-bypass"></a>

## PACKET_QDISC_BYPASS

If there is a requirement to load the network with many packets in a similar fashion as pktgen does, you might set the following option after socket creation:



```text
int one = 1;
setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one));
```

This has the side-effect, that packets sent through PF_PACKET will bypass the kernel's qdisc layer and are forcedly pushed to the driver directly. Meaning, packet are not buffered, tc disciplines are ignored, increased loss can occur and such packets are also not visible to other PF_PACKET sockets anymore. So, you have been warned; generally, this can be useful for stress testing various components of a system.

On default, PACKET_QDISC_BYPASS is disabled and needs to be explicitly enabled on PF_PACKET sockets.

<a id="rst-packet-timestamp"></a>

## PACKET_TIMESTAMP

The PACKET_TIMESTAMP setting determines the source of the timestamp in the packet meta information for mmap(2)ed RX_RING and TX_RINGs.  If your NIC is capable of timestamping packets in hardware, you can request those hardware timestamps to be used. Note: you may need to enable the generation of hardware timestamps with SIOCSHWTSTAMP (see related information from [Documentation/networking/timestamping.rst](/kernel/internals/networking/timestamping.md)).

PACKET_TIMESTAMP accepts the same integer bit field as SO_TIMESTAMPING:



```text
int req = SOF_TIMESTAMPING_RAW_HARDWARE;
setsockopt(fd, SOL_PACKET, PACKET_TIMESTAMP, (void *) &req, sizeof(req))
```

For the mmap(2)ed ring buffers, such timestamps are stored in the `tpacket{,2,3}_hdr` structure's tp_sec and `tp_{n,u}sec` members. To determine what kind of timestamp has been reported, the tp_status field is binary or'ed with the following possible bits ...



```text
TP_STATUS_TS_RAW_HARDWARE
TP_STATUS_TS_SOFTWARE
```

... that are equivalent to its `SOF_TIMESTAMPING_*` counterparts. For the RX_RING, if neither is set (i.e. PACKET_TIMESTAMP is not set), then a software fallback was invoked *within* PF_PACKET's processing code (less precise).

Getting timestamps for the TX_RING works as follows: i) fill the ring frames, ii) call sendto() e.g. in blocking mode, iii) wait for status of relevant frames to be updated resp. the frame handed over to the application, iv) walk through the frames to pick up the individual hw/sw timestamps.

Only (\!) if transmit timestamping is enabled, then these bits are combined with binary \| with TP_STATUS_AVAILABLE, so you must check for that in your application (e.g. \!(tp_status &amp; (TP_STATUS_SEND_REQUEST \| TP_STATUS_SENDING)) in a first step to see if the frame belongs to the application, and then one can extract the type of timestamp in a second step from tp_status)\!

If you don't care about them, thus having it disabled, checking for TP_STATUS_AVAILABLE resp. TP_STATUS_WRONG_FORMAT is sufficient. If in the TX_RING part only TP_STATUS_AVAILABLE is set, then the tp_sec and tp\_\{n,u\}sec members do not contain a valid value. For TX_RINGs, by default no timestamp is generated\!

See include/linux/net_tstamp.h and [Documentation/networking/timestamping.rst](/kernel/internals/networking/timestamping.md) for more information on hardware timestamps.

<a id="rst-miscellaneous-bits"></a>

## Miscellaneous bits

- Packet sockets work well together with Linux socket filters, thus you also might want to have a look at [Documentation/networking/filter.rst](/kernel/internals/networking/filter.md)

<a id="rst-thanks"></a>

## THANKS

> Jesse Brandeburg, for fixing my grammathical/spelling errors

---

# Page Pool API

_Peios Kernel / Internals / Networking_

> Information about page pools on the system can be accessed via the netdev genetlink family (see Documentation/netlink/specs/netdev.yaml).

<a id="rst-page-pool-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->


The page_pool allocator is optimized for recycling page or page fragment used
by skb packet and xdp frame.

Basic use involves replacing any [`alloc_pages()`](/kernel/internals/core-api/mm-api.md#c-alloc_pages) calls with `page_pool_alloc()`,
which allocate memory with or without page splitting depending on the
requested memory size.

If the driver knows that it always requires full pages or its allocations are
always smaller than half a page, it can use one of the more specific API
calls:

1. `page_pool_alloc_pages()`: allocate memory without page splitting when
driver knows that the memory it need is always bigger than half of the page
allocated from page pool. There is no cache line dirtying for 'struct page'
when a page is recycled back to the page pool.

2. `page_pool_alloc_frag()`: allocate memory with page splitting when driver
knows that the memory it need is always smaller than or equal to half of the
page allocated from page pool. Page splitting enables memory saving and thus
avoids TLB/cache miss for data access, but there also is some cost to
implement page splitting, mainly some cache line dirtying/bouncing for
'struct page' and atomic operation for page->pp_ref_count.

The API keeps track of in-flight pages, in order to let API users know when
it is safe to free a page_pool object, the API users must call
[`page_pool_put_page()`](#c-page_pool_put_page) or [`page_pool_free_va()`](#c-page_pool_free_va) to free the page_pool object, or
attach the page_pool object to a page_pool-aware object like skbs marked with
`skb_mark_for_recycle()`.

[`page_pool_put_page()`](#c-page_pool_put_page) may be called multiple times on the same page if a page
is split into multiple fragments. For the last fragment, it will either
recycle the page, or in case of page->_refcount > 1, it will release the DMA
mapping and in-flight state accounting.

`dma_sync_single_range_for_device()` is only called for the last fragment when
page_pool is created with PP_FLAG_DMA_SYNC_DEV flag, so it depends on the
last freed fragment to do the sync_for_device operation for all fragments in
the same page when a page is split. The API user must setup pool->p.max_len
and pool->p.offset correctly and ensure that [`page_pool_put_page()`](#c-page_pool_put_page) is called
with dma_sync_size being -1 for fragment API.


<a id="rst-architecture-overview"></a>

## Architecture overview



```none
+------------------+
|       Driver     |
+------------------+
        ^
        |
        |
        |
        v
+--------------------------------------------+
|                request memory              |
+--------------------------------------------+
    ^                                  ^
    |                                  |
    | Pool empty                       | Pool has entries
    |                                  |
    v                                  v
+-----------------------+     +------------------------+
| alloc (and map) pages |     |  get page from cache   |
+-----------------------+     +------------------------+
                                ^                    ^
                                |                    |
                                | cache available    | No entries, refill
                                |                    | from ptr-ring
                                |                    |
                                v                    v
                      +-----------------+     +------------------+
                      |   Fast cache    |     |  ptr-ring cache  |
                      +-----------------+     +------------------+
```

<a id="rst-monitoring"></a>

## Monitoring

Information about page pools on the system can be accessed via the netdev genetlink family (see Documentation/netlink/specs/netdev.yaml).

<a id="rst-api-interface"></a>

## API interface

The number of pools created **must** match the number of hardware queues unless hardware restrictions make that impossible. This would otherwise beat the purpose of page pool, which is allocate pages fast from cache without locking. This lockless guarantee naturally comes from running under a NAPI softirq. The protection doesn't strictly have to be NAPI, any guarantee that allocating a page will cause no race conditions is enough.


#### <a id="c-page_pool_create"></a>`page_pool_create()`

```c
struct page_pool * page_pool_create(const struct page_pool_params *params)
```

create a page pool

**Parameters**

- `const struct page_pool_params *params`: parameters, see struct page_pool_params



#### <a id="c-struct-page_pool_params"></a>`struct page_pool_params`

page pool parameters

**Definition**

```c
struct page_pool_params {
    struct page_pool_params_fast  fast;
    unsigned int    order;
    unsigned int    pool_size;
    int nid;
    struct device   *dev;
    struct napi_struct *napi;
    enum dma_data_direction dma_dir;
    unsigned int    max_len;
    unsigned int    offset;
    struct page_pool_params_slow  slow;
    STRUCT_GROUP( struct net_device *netdev;
    unsigned int queue_idx;
    unsigned int    flags;
};
```

**Members**

- `fast`: params accessed frequently on hotpath
- `order`: 2^order pages on allocation
- `pool_size`: size of the ptr_ring
- `nid`: NUMA node id to allocate from pages from
- `dev`: device, for DMA pre-mapping purposes
- `napi`: NAPI which is the sole consumer of pages, otherwise NULL
- `dma_dir`: DMA mapping direction
- `max_len`: max DMA sync memory size for PP_FLAG_DMA_SYNC_DEV
- `offset`: DMA sync address offset for PP_FLAG_DMA_SYNC_DEV
- `slow`: params with slowpath access only (initialization and Netlink)
- `netdev`: netdev this pool will serve (leave as NULL if none or multiple)
- `queue_idx`: queue idx this page_pool is being created for.
- `flags`: PP_FLAG_DMA_MAP, PP_FLAG_DMA_SYNC_DEV, PP_FLAG_SYSTEM_POOL,
  PP_FLAG_ALLOW_UNREADABLE_NETMEM.



#### <a id="c-page_pool_dev_alloc_pages"></a>`page_pool_dev_alloc_pages()`

```c
struct page * page_pool_dev_alloc_pages(struct page_pool *pool)
```

allocate a page.

**Parameters**

- `struct page_pool *pool`: pool from which to allocate

**Description**

Get a page from the page allocator or page_pool caches.

#### <a id="c-page_pool_dev_alloc_frag"></a>`page_pool_dev_alloc_frag()`

```c
struct page * page_pool_dev_alloc_frag(struct page_pool *pool, unsigned int *offset, unsigned int size)
```

allocate a page fragment.

**Parameters**

- `struct page_pool *pool`: pool from which to allocate
- `unsigned int *offset`: offset to the allocated page
- `unsigned int size`: requested size

**Description**

Get a page fragment from the page allocator or page_pool caches.

**Return**

allocated page fragment, otherwise return NULL.

#### <a id="c-page_pool_dev_alloc"></a>`page_pool_dev_alloc()`

```c
struct page * page_pool_dev_alloc(struct page_pool *pool, unsigned int *offset, unsigned int *size)
```

allocate a page or a page fragment.

**Parameters**

- `struct page_pool *pool`: pool from which to allocate
- `unsigned int *offset`: offset to the allocated page
- `unsigned int *size`: in as the requested size, out as the allocated size

**Description**

Get a page or a page fragment from the page allocator or page_pool caches
depending on the requested size in order to allocate memory with least memory
utilization and performance penalty.

**Return**

allocated page or page fragment, otherwise return NULL.

#### <a id="c-page_pool_dev_alloc_va"></a>`page_pool_dev_alloc_va()`

```c
void * page_pool_dev_alloc_va(struct page_pool *pool, unsigned int *size)
```

allocate a page or a page fragment and return its va.

**Parameters**

- `struct page_pool *pool`: pool from which to allocate
- `unsigned int *size`: in as the requested size, out as the allocated size

**Description**

This is just a thin wrapper around the `page_pool_alloc()` API, and
it returns va of the allocated page or page fragment.

**Return**

the va for the allocated page or page fragment, otherwise return NULL.

#### <a id="c-page_pool_get_dma_dir"></a>`page_pool_get_dma_dir()`

```c
enum dma_data_direction page_pool_get_dma_dir(const struct page_pool *pool)
```

Retrieve the stored DMA direction.

**Parameters**

- `const struct page_pool *pool`: pool from which page was allocated

**Description**

Get the stored dma direction. A driver might decide to store this locally
and avoid the extra cache line from page_pool to determine the direction.

#### <a id="c-page_pool_put_page"></a>`page_pool_put_page()`

```c
void page_pool_put_page(struct page_pool *pool, struct page *page, unsigned int dma_sync_size, bool allow_direct)
```

release a reference to a page pool page

**Parameters**

- `struct page_pool *pool`: pool from which page was allocated
- `struct page *page`: page to release a reference on
- `unsigned int dma_sync_size`: how much of the page may have been touched by the device
- `bool allow_direct`: released by the consumer, allow lockless caching

**Description**

The outcome of this depends on the page refcnt. If the driver bumps
the refcnt > 1 this will unmap the page. If the page refcnt is 1
the allocator owns the page and will try to recycle it in one of the pool
caches. If PP_FLAG_DMA_SYNC_DEV is set, the page will be synced for_device
using `dma_sync_single_range_for_device()`.

#### <a id="c-page_pool_put_full_page"></a>`page_pool_put_full_page()`

```c
void page_pool_put_full_page(struct page_pool *pool, struct page *page, bool allow_direct)
```

release a reference on a page pool page

**Parameters**

- `struct page_pool *pool`: pool from which page was allocated
- `struct page *page`: page to release a reference on
- `bool allow_direct`: released by the consumer, allow lockless caching

**Description**

Similar to [`page_pool_put_page()`](#c-page_pool_put_page), but will DMA sync the entire memory area
as configured in [`page_pool_params.max_len`](#c-struct-page_pool_params).

#### <a id="c-page_pool_recycle_direct"></a>`page_pool_recycle_direct()`

```c
void page_pool_recycle_direct(struct page_pool *pool, struct page *page)
```

release a reference on a page pool page

**Parameters**

- `struct page_pool *pool`: pool from which page was allocated
- `struct page *page`: page to release a reference on

**Description**

Similar to [`page_pool_put_full_page()`](#c-page_pool_put_full_page) but caller must guarantee safe context
(e.g NAPI), since it will recycle the page directly into the pool fast cache.

#### <a id="c-page_pool_free_va"></a>`page_pool_free_va()`

```c
void page_pool_free_va(struct page_pool *pool, void *va, bool allow_direct)
```

free a va into the page_pool

**Parameters**

- `struct page_pool *pool`: pool from which va was allocated
- `void *va`: va to be freed
- `bool allow_direct`: freed by the consumer, allow lockless caching

**Description**

Free a va allocated from `page_pool_allo_va()`.

#### <a id="c-page_pool_get_dma_addr"></a>`page_pool_get_dma_addr()`

```c
dma_addr_t page_pool_get_dma_addr(const struct page *page)
```

Retrieve the stored DMA address.

**Parameters**

- `const struct page *page`: page allocated from a page pool

**Description**

Fetch the DMA address of the page. The page pool to which the page belongs
must had been created with PP_FLAG_DMA_MAP.



#### <a id="c-page_pool_get_stats"></a>`page_pool_get_stats()`

```c
bool page_pool_get_stats(const struct page_pool *pool, struct page_pool_stats *stats)
```

fetch page pool stats

**Parameters**

- `const struct page_pool *pool`: pool from which page was allocated
- `struct page_pool_stats *stats`: struct page_pool_stats to fill in

**Description**

Retrieve statistics about the page_pool. This API is only available
if the kernel has been configured with `CONFIG_PAGE_POOL_STATS=y`.
A pointer to a caller allocated struct page_pool_stats structure
is passed to this API which is filled in. The caller can then report
those stats to the user (perhaps via ethtool, debugfs, etc.).


<a id="rst-dma-sync"></a>

### DMA sync

Driver is always responsible for syncing the pages for the CPU. Drivers may choose to take care of syncing for the device as well or set the `PP_FLAG_DMA_SYNC_DEV` flag to request that pages allocated from the page pool are already synced for the device.

If `PP_FLAG_DMA_SYNC_DEV` is set, the driver must inform the core what portion of the buffer has to be synced. This allows the core to avoid syncing the entire page when the drivers knows that the device only accessed a portion of the page.

Most drivers will reserve headroom in front of the frame. This part of the buffer is not touched by the device, so to avoid syncing it drivers can set the `offset` field in struct page_pool_params appropriately.

For pages recycled on the XDP xmit and skb paths the page pool will use the `max_len` member of struct page_pool_params to decide how much of the page needs to be synced (starting at `offset`). When directly freeing pages in the driver (page_pool_put_page()) the `dma_sync_size` argument specifies how much of the buffer needs to be synced.

If in doubt set `offset` to 0, `max_len` to `PAGE_SIZE` and pass -1 as `dma_sync_size`. That combination of arguments is always correct.

Note that the syncing parameters are for the entire page. This is important to remember when using fragments (`PP_FLAG_PAGE_FRAG`), where allocated buffers may be smaller than a full page. Unless the driver author really understands page pool internals it's recommended to always use `offset = 0`, `max_len = PAGE_SIZE` with fragmented page pools.

<a id="rst-stats-api-and-structures"></a>

### Stats API and structures

If the kernel is configured with `CONFIG_PAGE_POOL_STATS=y`, the API page_pool_get_stats() and structures described below are available. It takes a  pointer to a `struct page_pool` and a pointer to a struct page_pool_stats allocated by the caller.

Older drivers expose page pool statistics via ethtool or debugfs. The same statistics are accessible via the netlink netdev family in a driver-independent fashion.


#### <a id="c-struct-page_pool_alloc_stats"></a>`struct page_pool_alloc_stats`

allocation statistics

**Definition**

```c
struct page_pool_alloc_stats {
    u64 fast;
    u64 slow;
    u64 slow_high_order;
    u64 empty;
    u64 refill;
    u64 waive;
};
```

**Members**

- `fast`: successful fast path allocations
- `slow`: slow path order-0 allocations
- `slow_high_order`: slow path high order allocations
- `empty`: ptr ring is empty, so a slow path allocation was forced
- `refill`: an allocation which triggered a refill of the cache
- `waive`: pages obtained from the ptr ring that cannot be added to
  the cache due to a NUMA mismatch

#### <a id="c-struct-page_pool_recycle_stats"></a>`struct page_pool_recycle_stats`

recycling (freeing) statistics

**Definition**

```c
struct page_pool_recycle_stats {
    u64 cached;
    u64 cache_full;
    u64 ring;
    u64 ring_full;
    u64 released_refcnt;
};
```

**Members**

- `cached`: recycling placed page in the page pool cache
- `cache_full`: page pool cache was full
- `ring`: page placed into the ptr ring
- `ring_full`: page released from page pool because the ptr ring was full
- `released_refcnt`: page released (and not recycled) because refcnt > 1

#### <a id="c-struct-page_pool_stats"></a>`struct page_pool_stats`

combined page pool use statistics

**Definition**

```c
struct page_pool_stats {
    struct page_pool_alloc_stats alloc_stats;
    struct page_pool_recycle_stats recycle_stats;
};
```

**Members**

- `alloc_stats`: see struct page_pool_alloc_stats
- `recycle_stats`: see struct page_pool_recycle_stats

**Description**

Wrapper struct for combining page pool stats with different storage
requirements.


<a id="rst-coding-examples"></a>

## Coding examples

<a id="rst-registration"></a>

### Registration



```c
/* Page pool registration */
struct page_pool_params pp_params = { 0 };
struct xdp_rxq_info xdp_rxq;
int err;

pp_params.order = 0;
/* internal DMA mapping in page_pool */
pp_params.flags = PP_FLAG_DMA_MAP;
pp_params.pool_size = DESC_NUM;
pp_params.nid = NUMA_NO_NODE;
pp_params.dev = priv->dev;
pp_params.napi = napi; /* only if locking is tied to NAPI */
pp_params.dma_dir = xdp_prog ? DMA_BIDIRECTIONAL : DMA_FROM_DEVICE;
page_pool = page_pool_create(&pp_params);

err = xdp_rxq_info_reg(&xdp_rxq, ndev, 0);
if (err)
    goto err_out;

err = xdp_rxq_info_reg_mem_model(&xdp_rxq, MEM_TYPE_PAGE_POOL, page_pool);
if (err)
    goto err_out;
```

<a id="rst-napi-poller"></a>

### NAPI poller



```c
/* NAPI Rx poller */
enum dma_data_direction dma_dir;

dma_dir = page_pool_get_dma_dir(dring->page_pool);
while (done < budget) {
    if (some error)
        page_pool_recycle_direct(page_pool, page);
    if (packet_is_xdp) {
        if XDP_DROP:
            page_pool_recycle_direct(page_pool, page);
    } else (packet_is_skb) {
        skb_mark_for_recycle(skb);
        new_page = page_pool_dev_alloc_pages(page_pool);
    }
}
```

<a id="rst-stats"></a>

### Stats



```c
#ifdef CONFIG_PAGE_POOL_STATS
/* retrieve stats */
struct page_pool_stats stats = { 0 };
if (page_pool_get_stats(page_pool, &stats)) {
        /* perhaps the driver reports statistics with ethool */
        ethtool_print_allocation_stats(&stats.alloc_stats);
        ethtool_print_recycle_stats(&stats.recycle_stats);
}
#endif
```

<a id="rst-driver-unload"></a>

### Driver unload



```c
/* Driver unload */
page_pool_put_full_page(page_pool, page, false);
xdp_rxq_info_unreg(&xdp_rxq);
```

---

# Linux Phonet protocol family

_Peios Kernel / Internals / Networking_

> Phonet is a packet protocol used by Nokia cellular modems for both IPC and RPC. With the Linux Phonet socket family, Linux host processes can receive and send messages from/to the modem, or any other external device attached to the modem.…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-linux-phonet-protocol-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-introduction"></a>

## Introduction

Phonet is a packet protocol used by Nokia cellular modems for both IPC and RPC. With the Linux Phonet socket family, Linux host processes can receive and send messages from/to the modem, or any other external device attached to the modem. The modem takes care of routing.

Phonet packets can be exchanged through various hardware connections depending on the device, such as:

> - USB with the CDC Phonet interface,
>
> - infrared,
>
> - Bluetooth,
>
> - an RS232 serial port (with a dedicated "FBUS" line discipline),
>
> - the SSI bus with some TI OMAP processors.

<a id="rst-packets-format"></a>

## Packets format

Phonet packets have a common header as follows:



```text
struct phonethdr {
  uint8_t  pn_media;  /* Media type (link-layer identifier) */
  uint8_t  pn_rdev;   /* Receiver device ID */
  uint8_t  pn_sdev;   /* Sender device ID */
  uint8_t  pn_res;    /* Resource ID or function */
  uint16_t pn_length; /* Big-endian message byte length (minus 6) */
  uint8_t  pn_robj;   /* Receiver object ID */
  uint8_t  pn_sobj;   /* Sender object ID */
};
```

On Linux, the link-layer header includes the pn_media byte (see below). The next 7 bytes are part of the network-layer header.

The device ID is split: the 6 higher-order bits constitute the device address, while the 2 lower-order bits are used for multiplexing, as are the 8-bit object identifiers. As such, Phonet can be considered as a network layer with 6 bits of address space and 10 bits for transport protocol (much like port numbers in IP world).

The modem always has address number zero. All other device have a their own 6-bit address.

<a id="rst-link-layer"></a>

## Link layer

Phonet links are always point-to-point links. The link layer header consists of a single Phonet media type byte. It uniquely identifies the link through which the packet is transmitted, from the modem's perspective. Each Phonet network device shall prepend and set the media type byte as appropriate. For convenience, a common phonet_header_ops link-layer header operations structure is provided. It sets the media type according to the network device hardware address.

Linux Phonet network interfaces support a dedicated link layer packets type (ETH_P_PHONET) which is out of the Ethernet type range. They can only send and receive Phonet packets.

The virtual TUN tunnel device driver can also be used for Phonet. This requires IFF_TUN mode, \_without\_ the IFF_NO_PI flag. In this case, there is no link-layer header, so there is no Phonet media type byte.

Note that Phonet interfaces are not allowed to re-order packets, so only the (default) Linux FIFO qdisc should be used with them.

<a id="rst-network-layer"></a>

## Network layer

The Phonet socket address family maps the Phonet packet header:



```text
struct sockaddr_pn {
  sa_family_t spn_family;    /* AF_PHONET */
  uint8_t     spn_obj;       /* Object ID */
  uint8_t     spn_dev;       /* Device ID */
  uint8_t     spn_resource;  /* Resource or function */
  uint8_t     spn_zero[...]; /* Padding */
};
```

The resource field is only used when sending and receiving; It is ignored by bind() and getsockname().

<a id="rst-low-level-datagram-protocol"></a>

## Low-level datagram protocol

Applications can send Phonet messages using the Phonet datagram socket protocol from the PF_PHONET family. Each socket is bound to one of the 2^10 object IDs available, and can send and receive packets with any other peer.



```text
struct sockaddr_pn addr = { .spn_family = AF_PHONET, };
ssize_t len;
socklen_t addrlen = sizeof(addr);
int fd;

fd = socket(PF_PHONET, SOCK_DGRAM, 0);
bind(fd, (struct sockaddr *)&addr, sizeof(addr));
/* ... */

sendto(fd, msg, msglen, 0, (struct sockaddr *)&addr, sizeof(addr));
len = recvfrom(fd, buf, sizeof(buf), 0,
               (struct sockaddr *)&addr, &addrlen);
```

This protocol follows the SOCK_DGRAM connection-less semantics. However, connect() and getpeername() are not supported, as they did not seem useful with Phonet usages (could be added easily).

<a id="rst-resource-subscription"></a>

## Resource subscription

A Phonet datagram socket can be subscribed to any number of 8-bits Phonet resources, as follow:



```text
uint32_t res = 0xXX;
ioctl(fd, SIOCPNADDRESOURCE, &res);
```

Subscription is similarly cancelled using the SIOCPNDELRESOURCE I/O control request, or when the socket is closed.

Note that no more than one socket can be subscribed to any given resource at a time. If not, ioctl() will return EBUSY.

<a id="rst-phonet-pipe-protocol"></a>

## Phonet Pipe protocol

The Phonet Pipe protocol is a simple sequenced packets protocol with end-to-end congestion control. It uses the passive listening socket paradigm. The listening socket is bound to an unique free object ID. Each listening socket can handle up to 255 simultaneous connections, one per accept()'d socket.



```text
int lfd, cfd;

lfd = socket(PF_PHONET, SOCK_SEQPACKET, PN_PROTO_PIPE);
listen (lfd, INT_MAX);

/* ... */
cfd = accept(lfd, NULL, NULL);
for (;;)
{
  char buf[...];
  ssize_t len = read(cfd, buf, sizeof(buf));

  /* ... */

  write(cfd, msg, msglen);
}
```

Connections are traditionally established between two endpoints by a "third party" application. This means that both endpoints are passive.

As of Linux kernel version 2.6.39, it is also possible to connect two endpoints directly, using connect() on the active side. This is intended to support the newer Nokia Wireless Modem API, as found in e.g. the Nokia Slim Modem in the ST-Ericsson U8500 platform:



```text
struct sockaddr_spn spn;
int fd;

fd = socket(PF_PHONET, SOCK_SEQPACKET, PN_PROTO_PIPE);
memset(&spn, 0, sizeof(spn));
spn.spn_family = AF_PHONET;
spn.spn_obj = ...;
spn.spn_dev = ...;
spn.spn_resource = 0xD9;
connect(fd, (struct sockaddr *)&spn, sizeof(spn));
/* normal I/O here ... */
close(fd);
```

<!-- Warning:

When polling a connected pipe socket for writability, there is an
intrinsic race condition whereby writability might be lost between the
polling and the writing system calls. In this case, the socket will
block until write becomes possible again, unless non-blocking mode
is enabled. -->

The pipe protocol provides two socket options at the SOL_PNPIPE level:

> PNPIPE_ENCAP accepts one integer value (int) of:
>
> > - **PNPIPE_ENCAP_NONE:**
> >
> >   The socket operates normally (default).
> >
> > - **PNPIPE_ENCAP_IP:**
> >
> >   The socket is used as a backend for a virtual IP interface. This requires CAP_NET_ADMIN capability. GPRS data support on Nokia modems can use this. Note that the socket cannot be reliably poll()'d or read() from while in this mode.
>
> - **PNPIPE_IFINDEX**
>
>   is a read-only integer value. It contains the interface index of the network interface created by PNPIPE_ENCAP, or zero if encapsulation is off.
>
> - **PNPIPE_HANDLE**
>
>   is a read-only integer value. It contains the underlying identifier ("pipe handle") of the pipe. This is only defined for socket descriptors that are already connected or being connected.

<a id="rst-authors"></a>

## Authors

Linux Phonet was initially written by Sakari Ailus.

Other contributors include Mikä Liljeberg, Andras Domokos, Carlos Chinea and Rémi Denis-Courmont.

Copyright © 2008 Nokia Corporation.

---

# PHY link topology

_Peios Kernel / Internals / Networking_

> The PHY link topology representation in the networking stack aims at representing the hardware layout for any given Ethernet link.

<a id="rst-phy-link-topology-1"></a>
<a id="rst-phy-link-topology"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The PHY link topology representation in the networking stack aims at representing the hardware layout for any given Ethernet link.

An Ethernet interface from userspace's point of view is nothing but a `struct net_device <net_device>`, which exposes configuration options through the legacy ioctls and the ethtool netlink commands. The base assumption when designing these configuration APIs were that the link looks something like



```text
+-----------------------+        +----------+      +--------------+
| Ethernet Controller / |        | Ethernet |      | Connector /  |
|       MAC             | ------ |   PHY    | ---- |    Port      | ---... to LP
+-----------------------+        +----------+      +--------------+
struct net_device               struct phy_device
```

Commands that needs to configure the PHY will go through the net_device.phydev field to reach the PHY and perform the relevant configuration.

This assumption falls apart in more complex topologies that can arise when, for example, using SFP transceivers (although that's not the only specific case).

Here, we have 2 basic scenarios. Either the MAC is able to output a serialized interface, that can directly be fed to an SFP cage, such as SGMII, 1000BaseX, 10GBaseR, etc.

The link topology then looks like this (when an SFP module is inserted)



```text
+-----+  SGMII  +------------+
| MAC | ------- | SFP Module |
+-----+         +------------+
```

Knowing that some modules embed a PHY, the actual link is more like



```text
+-----+  SGMII   +--------------+
| MAC | -------- | PHY (on SFP) |
+-----+          +--------------+
```

In this case, the SFP PHY is handled by phylib, and registered by phylink through its SFP upstream ops.

Now some Ethernet controllers aren't able to output a serialized interface, so we can't directly connect them to an SFP cage. However, some PHYs can be used as media-converters, to translate the non-serialized MAC MII interface to a serialized MII interface fed to the SFP



```text
+-----+  RGMII  +-----------------------+  SGMII  +--------------+
| MAC | ------- | PHY (media converter) | ------- | PHY (on SFP) |
+-----+         +-----------------------+         +--------------+
```

This is where the model of having a single net_device.phydev pointer shows its limitations, as we now have 2 PHYs on the link.

The phy_link topology framework aims at providing a way to keep track of every PHY on the link, for use by both kernel drivers and subsystems, but also to report the topology to userspace, allowing to target individual PHYs in configuration commands.

<a id="rst-api"></a>

## API

The `struct phy_link_topology <phy_link_topology>` is a per-netdevice resource, that gets initialized at netdevice creation. Once it's initialized, it is then possible to register PHYs to the topology through :

`phy_link_topo_add_phy()`

Besides registering the PHY to the topology, this call will also assign a unique index to the PHY, which can then be reported to userspace to refer to this PHY (akin to the ifindex). This index is a u32, ranging from 1 to U32_MAX. The value 0 is reserved to indicate the PHY doesn't belong to any topology yet.

The PHY can then be removed from the topology through

`phy_link_topo_del_phy()`

These function are already hooked into the phylib subsystem, so all PHYs that are linked to a net_device through `phy_attach_direct()` will automatically join the netdev's topology.

PHYs that are on a SFP module will also be automatically registered IF the SFP upstream is phylink (so, no media-converter).

PHY drivers that can be used as SFP upstream need to call `phy_sfp_attach_phy()` and `phy_sfp_detach_phy()`, which can be used as a .attach_phy / .detach_phy implementation for the `struct sfp_upstream_ops <sfp_upstream_ops>`.

<a id="rst-uapi"></a>

## UAPI

There exist a set of netlink commands to query the link topology from userspace, see `Documentation/networking/ethtool-netlink.rst`.

The whole point of having a topology representation is to assign the phyindex field in `struct phy_device <phy_device>`. This index is reported to userspace using the `ETHTOOL_MSG_PHY_GET` ethtnl command. Performing a DUMP operation will result in all PHYs from all net_device being listed. The DUMP command accepts either a `ETHTOOL_A_HEADER_DEV_INDEX` or `ETHTOOL_A_HEADER_DEV_NAME` to be passed in the request to filter the DUMP to a single net_device.

The retrieved index can then be passed as a request parameter using the `ETHTOOL_A_HEADER_PHY_INDEX` field in the following ethnl commands :

- `ETHTOOL_MSG_STRSET_GET` to get the stats string set from a given PHY

- `ETHTOOL_MSG_CABLE_TEST_ACT` and `ETHTOOL_MSG_CABLE_TEST_ACT`, to perform cable testing on a given PHY on the link (most likely the outermost PHY)

- `ETHTOOL_MSG_PSE_SET` and `ETHTOOL_MSG_PSE_GET` for PHY-controlled PoE and PSE settings

- `ETHTOOL_MSG_PLCA_GET_CFG`, `ETHTOOL_MSG_PLCA_SET_CFG` and `ETHTOOL_MSG_PLCA_GET_STATUS` to set the PLCA (Physical Layer Collision Avoidance) parameters

Note that the PHY index can be passed to other requests, which will silently ignore it if present and irrelevant.

---

# Ethernet ports

_Peios Kernel / Internals / Networking_

> This document is a basic description of the phy_port infrastructure, introduced to represent physical interfaces of Ethernet devices.

<a id="rst-ethernet-ports"></a>
<a id="rst-phy-port"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document is a basic description of the phy_port infrastructure, introduced to represent physical interfaces of Ethernet devices.

Without phy_port, we already have quite a lot of information about what the media-facing interface of a NIC can do and looks like, through the `struct ethtool_link_ksettings <ethtool_link_ksettings>` attributes, which includes :

> - What the NIC can do through the `supported` field
>
> - What the Link Partner advertises through `lp_advertising`
>
> - Which features we're advertising through `advertising`

We also have info about the number of pairs and the PORT type. These settings are built by aggregating together information reported by various devices that are sitting on the link :

> - The NIC itself, through the `get_link_ksettings` callback
>
> - Precise information from the MAC and PCS by using phylink in the MAC driver
>
> - Information reported by the PHY device
>
> - Information reported by an SFP module (which can itself include a PHY)

This model however starts showing its limitations when we consider devices that have more than one media interface. In such a case, only information about the actively used interface is reported, and it's not possible to know what the other interfaces can do. In fact, we have very little information about whether or not there are any other media interfaces.

The goal of the phy_port representation is to provide a way of representing a physical interface of a NIC, regardless of what is driving the port (NIC through a firmware, SFP module, Ethernet PHY).

<a id="rst-multi-port-interfaces-examples"></a>

## Multi-port interfaces examples

Several cases of multi-interface NICs have been observed so far :

Internal MII Mux:



```text
+------------------+
| SoC              |
|          +-----+ |           +-----+
| +-----+  |     |-------------| PHY |
| | MAC |--| Mux | |   +-----+ +-----+
| +-----+  |     |-----| SFP |
|          +-----+ |   +-----+
+------------------+
```

Internal Mux with internal PHY:



```text
+------------------------+
| SoC                    |
|          +-----+ +-----+
| +-----+  |     |-| PHY |
| | MAC |--| Mux | +-----+   +-----+
| +-----+  |     |-----------| SFP |
|          +-----+       |   +-----+
+------------------------+
```

External Mux:



```text
+---------+
| SoC     |  +-----+  +-----+
|         |  |     |--| PHY |
| +-----+ |  |     |  +-----+
| | MAC |----| Mux |  +-----+
| +-----+ |  |     |--| PHY |
|         |  +-----+  +-----+
|         |     |
|    GPIO-------+
+---------+
```

Double-port PHY:



```text
+---------+
| SoC     | +-----+
|         | |     |--- RJ45
| +-----+ | |     |
| | MAC |---| PHY |   +-----+
| +-----+ | |     |---| SFP |
+---------+ +-----+   +-----+
```

phy_port aims at providing a path to support all the above topologies, by representing the media interfaces in a way that's agnostic to what's driving the interface. the struct phy_port object has its own set of callback ops, and will eventually be able to report its own ksettings:



```text
            _____      +------+
           (     )-----| Port |
+-----+   (       )    +------+
| MAC |--(   ???   )
+-----+   (       )    +------+
           (_____)-----| Port |
                       +------+
```

<a id="rst-next-steps"></a>

## Next steps

As of writing this documentation, only ports controlled by PHY devices are supported. The next steps will be to add the Netlink API to expose these to userspace and add support for raw ports (controlled by some firmware, and directly managed by the NIC driver).

Another parallel task is the introduction of a MII muxing framework to allow the control of non-PHY driver multi-port setups.

---

# PHY Abstraction Layer

_Peios Kernel / Internals / Networking_

> Most network devices consist of set of registers which provide an interface to a MAC layer, which communicates with the physical connection through a PHY. The PHY concerns itself with negotiating link parameters with the link partner on…

<a id="rst-phy-abstraction-layer"></a>

<a id="rst-purpose"></a>

## Purpose

Most network devices consist of set of registers which provide an interface to a MAC layer, which communicates with the physical connection through a PHY.  The PHY concerns itself with negotiating link parameters with the link partner on the other side of the network connection (typically, an ethernet cable), and provides a register interface to allow drivers to determine what settings were chosen, and to configure what settings are allowed.

While these devices are distinct from the network devices, and conform to a standard layout for the registers, it has been common practice to integrate the PHY management code with the network driver.  This has resulted in large amounts of redundant code.  Also, on embedded systems with multiple (and sometimes quite different) ethernet controllers connected to the same management bus, it is difficult to ensure safe use of the bus.

Since the PHYs are devices, and the management busses through which they are accessed are, in fact, busses, the PHY Abstraction Layer (PAL) treats them as such. In doing so, it has these goals:

1. Increase code-reuse

2. Increase overall code-maintainability

3. Speed development time for new network drivers, and for new systems

Basically, this layer is meant to provide an interface to PHY devices which allows network driver writers to write as little code as possible, while still providing a full feature set.

<a id="rst-the-mdio-bus"></a>

## The MDIO bus

Most network devices are connected to a PHY by means of a management bus. Different devices use different busses (though some share common interfaces). In order to take advantage of the PAL, each bus interface needs to be registered as a distinct device.

1. read and write functions must be implemented. Their prototypes are:



   ```text
   int write(struct mii_bus *bus, int mii_id, int regnum, u16 value);
   int read(struct mii_bus *bus, int mii_id, int regnum);
   ```

   mii_id is the address on the bus for the PHY, and regnum is the register number.  These functions are guaranteed not to be called from interrupt time, so it is safe for them to block, waiting for an interrupt to signal the operation is complete

2. A reset function is optional. This is used to return the bus to an initialized state.

3. A probe function is needed.  This function should set up anything the bus driver needs, setup the mii_bus structure, and register with the PAL using mdiobus_register.  Similarly, there's a remove function to undo all of that (use mdiobus_unregister).

4. Like any driver, the device_driver structure must be configured, and init exit functions are used to register the driver.

5. The bus must also be declared somewhere as a device, and registered.

As an example for how one driver implemented an mdio bus driver, see drivers/net/ethernet/freescale/fsl_pq_mdio.c and an associated DTS file for one of the users. (e.g. "git grep fsl,.\*-mdio arch/powerpc/boot/dts/")

<a id="rst-rg-mii-electrical-interface-considerations"></a>

## (RG)MII/electrical interface considerations

The Reduced Gigabit Medium Independent Interface (RGMII) is a 12-pin electrical signal interface using a synchronous 125Mhz clock signal and several data lines. Due to this design decision, a 1.5ns to 2ns delay must be added between the clock line (RXC or TXC) and the data lines to let the PHY (clock sink) have a large enough setup and hold time to sample the data lines correctly. The PHY library offers different types of PHY_INTERFACE_MODE_RGMII\* values to let the PHY driver and optionally the MAC driver, implement the required delay. The values of phy_interface_t must be understood from the perspective of the PHY device itself, leading to the following:

- PHY_INTERFACE_MODE_RGMII: the PHY is not responsible for inserting any internal delay by itself, it assumes that either the Ethernet MAC (if capable) or the PCB traces insert the correct 1.5-2ns delay

- PHY_INTERFACE_MODE_RGMII_TXID: the PHY should insert an internal delay for the transmit data lines (TXD\[3:0\]) processed by the PHY device

- PHY_INTERFACE_MODE_RGMII_RXID: the PHY should insert an internal delay for the receive data lines (RXD\[3:0\]) processed by the PHY device

- PHY_INTERFACE_MODE_RGMII_ID: the PHY should insert internal delays for both transmit AND receive data lines from/to the PHY device

Whenever possible, use the PHY side RGMII delay for these reasons:

- PHY devices may offer sub-nanosecond granularity in how they allow a receiver/transmitter side delay (e.g: 0.5, 1.0, 1.5ns) to be specified. Such precision may be required to account for differences in PCB trace lengths

- PHY devices are typically qualified for a large range of applications (industrial, medical, automotive...), and they provide a constant and reliable delay across temperature/pressure/voltage ranges

- PHY device drivers in PHYLIB being reusable by nature, being able to configure correctly a specified delay enables more designs with similar delay requirements to be operated correctly

For cases where the PHY is not capable of providing this delay, but the Ethernet MAC driver is capable of doing so, the correct phy_interface_t value should be PHY_INTERFACE_MODE_RGMII, and the Ethernet MAC driver should be configured correctly in order to provide the required transmit and/or receive side delay from the perspective of the PHY device. Conversely, if the Ethernet MAC driver looks at the phy_interface_t value, for any other mode but PHY_INTERFACE_MODE_RGMII, it should make sure that the MAC-level delays are disabled.

In case neither the Ethernet MAC, nor the PHY are capable of providing the required delays, as defined per the RGMII standard, several options may be available:

- Some SoCs may offer a pin pad/mux/controller capable of configuring a given set of pins' strength, delays, and voltage; and it may be a suitable option to insert the expected 2ns RGMII delay.

- Modifying the PCB design to include a fixed delay (e.g: using a specifically designed serpentine), which may not require software configuration at all.

<a id="rst-common-problems-with-rgmii-delay-mismatch"></a>

### Common problems with RGMII delay mismatch

When there is a RGMII delay mismatch between the Ethernet MAC and the PHY, this will most likely result in the clock and data line signals to be unstable when the PHY or MAC take a snapshot of these signals to translate them into logical 1 or 0 states and reconstruct the data being transmitted/received. Typical symptoms include:

- Transmission/reception partially works, and there is frequent or occasional packet loss observed

- Ethernet MAC may report some or all packets ingressing with a FCS/CRC error, or just discard them all

- Switching to lower speeds such as 10/100Mbits/sec makes the problem go away (since there is enough setup/hold time in that case)

<a id="rst-connecting-to-a-phy"></a>

## Connecting to a PHY

Sometime during startup, the network driver needs to establish a connection between the PHY device, and the network device.  At this time, the PHY's bus and drivers need to all have been loaded, so it is ready for the connection. At this point, there are several ways to connect to the PHY:

1. The PAL handles everything, and only calls the network driver when the link state changes, so it can react.

2. The PAL handles everything except interrupts (usually because the controller has the interrupt registers).

3. The PAL handles everything, but checks in with the driver every second, allowing the network driver to react first to any changes before the PAL does.

4. The PAL serves only as a library of functions, with the network device manually calling functions to update status, and configure the PHY

<a id="rst-letting-the-phy-abstraction-layer-do-everything"></a>

## Letting the PHY Abstraction Layer do Everything

If you choose option 1 (The hope is that every driver can, but to still be useful to drivers that can't), connecting to the PHY is simple:

First, you need a function to react to changes in the link state.  This function follows this protocol:



```text
static void adjust_link(struct net_device *dev);
```

Next, you need to know the device name of the PHY connected to this device. The name will look something like, "0:00", where the first number is the bus id, and the second is the PHY's address on that bus.  Typically, the bus is responsible for making its ID unique.

Now, to connect, just call this function:



```text
phydev = phy_connect(dev, phy_name, &adjust_link, interface);
```

*phydev* is a pointer to the phy_device structure which represents the PHY. If phy_connect is successful, it will return the pointer.  dev, here, is the pointer to your net_device.  Once done, this function will have started the PHY's software state machine, and registered for the PHY's interrupt, if it has one.  The phydev structure will be populated with information about the current state, though the PHY will not yet be truly operational at this point.

PHY-specific flags should be set in phydev-&gt;dev_flags prior to the call to phy_connect() such that the underlying PHY driver can check for flags and perform specific operations based on them. This is useful if the system has put hardware restrictions on the PHY/controller, of which the PHY needs to be aware.

*interface* is a u32 which specifies the connection type used between the controller and the PHY.  Examples are GMII, MII, RGMII, and SGMII.  See "PHY interface mode" below.  For a full list, see include/linux/phy.h

Now just make sure that phydev-&gt;supported and phydev-&gt;advertising have any values pruned from them which don't make sense for your controller (a 10/100 controller may be connected to a gigabit capable PHY, so you would need to mask off SUPPORTED_1000baseT\*).  See include/linux/ethtool.h for definitions for these bitfields. Note that you should not SET any bits, except the SUPPORTED_Pause and SUPPORTED_AsymPause bits (see below), or the PHY may get put into an unsupported state.

Lastly, once the controller is ready to handle network traffic, you call phy_start(phydev).  This tells the PAL that you are ready, and configures the PHY to connect to the network. If the MAC interrupt of your network driver also handles PHY status changes, just set phydev-&gt;irq to PHY_MAC_INTERRUPT before you call phy_start and use phy_mac_interrupt() from the network driver. If you don't want to use interrupts, set phydev-&gt;irq to PHY_POLL. phy_start() enables the PHY interrupts (if applicable) and starts the phylib state machine.

When you want to disconnect from the network (even if just briefly), you call phy_stop(phydev). This function also stops the phylib state machine and disables PHY interrupts.

<a id="rst-phy-interface-modes"></a>

## PHY interface modes

The PHY interface mode supplied in the phy_connect() family of functions defines the initial operating mode of the PHY interface.  This is not guaranteed to remain constant; there are PHYs which dynamically change their interface mode without software interaction depending on the negotiation results.

Some of the interface modes are described below:

- **`PHY_INTERFACE_MODE_SMII`**

  This is serial MII, clocked at 125MHz, supporting 100M and 10M speeds. Some details can be found in [https://opencores.org/ocsvn/smii/smii/trunk/doc/SMII.pdf](<https://opencores.org/ocsvn/smii/smii/trunk/doc/SMII.pdf>)

- **`PHY_INTERFACE_MODE_1000BASEX`**

  This defines the 1000BASE-X single-lane serdes link as defined by the 802.3 standard section 36.  The link operates at a fixed bit rate of 1.25Gbaud using a 10B/8B encoding scheme, resulting in an underlying data rate of 1Gbps.  Embedded in the data stream is a 16-bit control word which is used to negotiate the duplex and pause modes with the remote end.  This does not include "up-clocked" variants such as 2.5Gbps speeds (see below.)

- **`PHY_INTERFACE_MODE_2500BASEX`**

  This defines a variant of 1000BASE-X which is clocked 2.5 times as fast as the 802.3 standard, giving a fixed bit rate of 3.125Gbaud.

- **`PHY_INTERFACE_MODE_SGMII`**

  This is used for Cisco SGMII, which is a modification of 1000BASE-X as defined by the 802.3 standard.  The SGMII link consists of a single serdes lane running at a fixed bit rate of 1.25Gbaud with 10B/8B encoding.  The underlying data rate is 1Gbps, with the slower speeds of 100Mbps and 10Mbps being achieved through replication of each data symbol. The 802.3 control word is re-purposed to send the negotiated speed and duplex information from to the MAC, and for the MAC to acknowledge receipt.  This does not include "up-clocked" variants such as 2.5Gbps speeds.

  Note: mismatched SGMII vs 1000BASE-X configuration on a link can successfully pass data in some circumstances, but the 16-bit control word will not be correctly interpreted, which may cause mismatches in duplex, pause or other settings.  This is dependent on the MAC and/or PHY behaviour.

- **`PHY_INTERFACE_MODE_5GBASER`**

  This is the IEEE 802.3 Clause 129 defined 5GBASE-R protocol. It is identical to the 10GBASE-R protocol defined in Clause 49, with the exception that it operates at half the frequency. Please refer to the IEEE standard for the definition.

- **`PHY_INTERFACE_MODE_10GBASER`**

  This is the IEEE 802.3 Clause 49 defined 10GBASE-R protocol used with various different mediums. Please refer to the IEEE standard for a definition of this.

  Note: 10GBASE-R is just one protocol that can be used with XFI and SFI. XFI and SFI permit multiple protocols over a single SERDES lane, and also defines the electrical characteristics of the signals with a host compliance board plugged into the host XFP/SFP connector. Therefore, XFI and SFI are not PHY interface types in their own right.

- **`PHY_INTERFACE_MODE_10GKR`**

  This is the IEEE 802.3 Clause 49 defined 10GBASE-R with Clause 73 autonegotiation. Please refer to the IEEE standard for further information.

  Note: due to legacy usage, some 10GBASE-R usage incorrectly makes use of this definition.

- **`PHY_INTERFACE_MODE_25GBASER`**

  This is the IEEE 802.3 PCS Clause 107 defined 25GBASE-R protocol. The PCS is identical to 10GBASE-R, i.e. 64B/66B encoded running 2.5 as fast, giving a fixed bit rate of 25.78125 Gbaud. Please refer to the IEEE standard for further information.

- **`PHY_INTERFACE_MODE_100BASEX`**

  This defines IEEE 802.3 Clause 24.  The link operates at a fixed data rate of 125Mpbs using a 4B/5B encoding scheme, resulting in an underlying data rate of 100Mpbs.

- **`PHY_INTERFACE_MODE_QUSGMII`**

  This defines the Cisco the Quad USGMII mode, which is the Quad variant of the USGMII (Universal SGMII) link. It's very similar to QSGMII, but uses a Packet Control Header (PCH) instead of the 7 bytes preamble to carry not only the port id, but also so-called "extensions". The only documented extension so-far in the specification is the inclusion of timestamps, for PTP-enabled PHYs. This mode isn't compatible with QSGMII, but offers the same capabilities in terms of link speed and negotiation.

- **`PHY_INTERFACE_MODE_1000BASEKX`**

  This is 1000BASE-X as defined by IEEE 802.3 Clause 36 with Clause 73 autonegotiation. Generally, it will be used with a Clause 70 PMD. To contrast with the 1000BASE-X phy mode used for Clause 38 and 39 PMDs, this interface mode has different autonegotiation and only supports full duplex.

- **`PHY_INTERFACE_MODE_PSGMII`**

  This is the Penta SGMII mode, it is similar to QSGMII but it combines 5 SGMII lines into a single link compared to 4 on QSGMII.

- **`PHY_INTERFACE_MODE_10G_QXGMII`**

  Represents the 10G-QXGMII PHY-MAC interface as defined by the Cisco USXGMII Multiport Copper Interface document. It supports 4 ports over a 10.3125 GHz SerDes lane, each port having speeds of 2.5G / 1G / 100M / 10M achieved through symbol replication. The PCS expects the standard USXGMII code word.

- **`PHY_INTERFACE_MODE_MIILITE`**

  Non-standard, simplified MII mode, without TXER, RXER, CRS and COL signals as defined for the MII. The absence of COL signal makes half-duplex link modes impossible but does not interfere with BroadR-Reach link modes on Broadcom (and other two-wire Ethernet) PHYs, because they are full-duplex only.

<a id="rst-pause-frames-flow-control"></a>

## Pause frames / flow control

The PHY does not participate directly in flow control/pause frames except by making sure that the SUPPORTED_Pause and SUPPORTED_AsymPause bits are set in MII_ADVERTISE to indicate towards the link partner that the Ethernet MAC controller supports such a thing. Since flow control/pause frames generation involves the Ethernet MAC driver, it is recommended that this driver takes care of properly indicating advertisement and support for such features by setting the SUPPORTED_Pause and SUPPORTED_AsymPause bits accordingly. This can be done either before or after phy_connect() and/or as a result of implementing the ethtool::set_pauseparam feature.

<a id="rst-keeping-close-tabs-on-the-pal"></a>

## Keeping Close Tabs on the PAL

It is possible that the PAL's built-in state machine needs a little help to keep your network device and the PHY properly in sync.  If so, you can register a helper function when connecting to the PHY, which will be called every second before the state machine reacts to any changes.  To do this, you need to manually call phy_attach() and phy_prepare_link(), and then call phy_start_machine() with the second argument set to point to your special handler.

Currently there are no examples of how to use this functionality, and testing on it has been limited because the author does not have any drivers which use it (they all use option 1).  So Caveat Emptor.

<a id="rst-doing-it-all-yourself"></a>

## Doing it all yourself

There's a remote chance that the PAL's built-in state machine cannot track the complex interactions between the PHY and your network device.  If this is so, you can simply call phy_attach(), and not call phy_start_machine or phy_prepare_link().  This will mean that phydev-&gt;state is entirely yours to handle (phy_start and phy_stop toggle between some of the states, so you might need to avoid them).

An effort has been made to make sure that useful functionality can be accessed without the state-machine running, and most of these functions are descended from functions which did not interact with a complex state-machine. However, again, no effort has been made so far to test running without the state machine, so tryer beware.

Here is a brief rundown of the functions:



```text
int phy_read(struct phy_device *phydev, u16 regnum);
int phy_write(struct phy_device *phydev, u16 regnum, u16 val);
```

Simple read/write primitives.  They invoke the bus's read/write function pointers.



```text
void phy_print_status(struct phy_device *phydev);
```

A convenience function to print out the PHY status neatly.



```text
void phy_request_interrupt(struct phy_device *phydev);
```

Requests the IRQ for the PHY interrupts.



```text
struct phy_device * phy_attach(struct net_device *dev, const char *phy_id,
                               phy_interface_t interface);
```

Attaches a network device to a particular PHY, binding the PHY to a generic driver if none was found during bus initialization.



```text
int phy_start_aneg(struct phy_device *phydev);
```

Using variables inside the phydev structure, either configures advertising and resets autonegotiation, or disables autonegotiation, and configures forced settings.



```text
static inline int phy_read_status(struct phy_device *phydev);
```

Fills the phydev structure with up-to-date information about the current settings in the PHY.



```text
int phy_ethtool_ksettings_set(struct phy_device *phydev,
                              const struct ethtool_link_ksettings *cmd);
```

Ethtool convenience functions.



```text
int phy_mii_ioctl(struct phy_device *phydev,
                  struct mii_ioctl_data *mii_data, int cmd);
```

The MII ioctl.  Note that this function will completely screw up the state machine if you write registers like BMCR, BMSR, ADVERTISE, etc.  Best to use this only to write registers which are not standard, and don't set off a renegotiation.

<a id="rst-phy-device-drivers"></a>

## PHY Device Drivers

With the PHY Abstraction Layer, adding support for new PHYs is quite easy. In some cases, no work is required at all\! However, many PHYs require a little hand-holding to get up-and-running.

<a id="rst-generic-phy-driver"></a>

### Generic PHY driver

If the desired PHY doesn't have any errata, quirks, or special features you want to support, then it may be best to not add support, and let the PHY Abstraction Layer's Generic PHY Driver do all of the work.

<a id="rst-writing-a-phy-driver"></a>

### Writing a PHY driver

If you do need to write a PHY driver, the first thing to do is make sure it can be matched with an appropriate PHY device. This is done during bus initialization by reading the device's UID (stored in registers 2 and 3), then comparing it to each driver's phy_id field by ANDing it with each driver's phy_id_mask field.  Also, it needs a name.  Here's an example:



```text
static struct phy_driver dm9161_driver = {
      .phy_id         = 0x0181b880,
      .name           = "Davicom DM9161E",
      .phy_id_mask    = 0x0ffffff0,
      ...
}
```

Next, you need to specify what features (speed, duplex, autoneg, etc) your PHY device and driver support.  Most PHYs support PHY_BASIC_FEATURES, but you can look in include/mii.h for other features.

Each driver consists of a number of function pointers, documented in include/linux/phy.h under the phy_driver structure.

Of these, only config_aneg and read_status are required to be assigned by the driver code.  The rest are optional.  Also, it is preferred to use the generic phy driver's versions of these two functions if at all possible: genphy_read_status and genphy_config_aneg.  If this is not possible, it is likely that you only need to perform some actions before and after invoking these functions, and so your functions will wrap the generic ones.

Feel free to look at the Marvell, Cicada, and Davicom drivers in drivers/net/phy/ for examples (the lxt and qsemi drivers have not been tested as of this writing).

The PHY's MMD register accesses are handled by the PAL framework by default, but can be overridden by a specific PHY driver if required. This could be the case if a PHY was released for manufacturing before the MMD PHY register definitions were standardized by the IEEE. Most modern PHYs will be able to use the generic PAL framework for accessing the PHY's MMD registers. An example of such usage is for Energy Efficient Ethernet support, implemented in the PAL. This support uses the PAL to access MMD registers for EEE query and configuration if the PHY supports the IEEE standard access mechanisms, or can use the PHY's specific access interfaces if overridden by the specific PHY driver. See the Micrel driver in drivers/net/phy/ for an example of how this can be implemented.

<a id="rst-board-fixups"></a>

## Board Fixups

Sometimes the specific interaction between the platform and the PHY requires special handling.  For instance, to change where the PHY's clock input is, or to add a delay to account for latency issues in the data path.  In order to support such contingencies, the PHY Layer allows platform code to register fixups to be run when the PHY is brought up (or subsequently reset).

When the PHY Layer brings up a PHY it checks to see if there are any fixups registered for it, matching based on UID (contained in the PHY device's phy_id field) and the bus identifier (contained in phydev-&gt;dev.bus_id).  Both must match, however two constants, PHY_ANY_ID and PHY_ANY_UID, are provided as wildcards for the bus ID and UID, respectively.

When a match is found, the PHY layer will invoke the run function associated with the fixup.  This function is passed a pointer to the phy_device of interest.  It should therefore only operate on that PHY.

The platform code can register the fixup using one of:



```text
int phy_register_fixup_for_uid(u32 phy_uid, u32 phy_uid_mask,
               int (*run)(struct phy_device *));
int phy_register_fixup_for_id(const char *phy_id,
               int (*run)(struct phy_device *));
```

<a id="rst-standards"></a>

## Standards

IEEE Standard 802.3: CSMA/CD Access Method and Physical Layer Specifications, Section Two: [http://standards.ieee.org/getieee802/download/802.3-2008_section2.pdf](<http://standards.ieee.org/getieee802/download/802.3-2008_section2.pdf>)

RGMII v1.3: [http://web.archive.org/web/20160303212629/http://www.hp.com/rnd/pdfs/RGMIIv1_3.pdf](<http://web.archive.org/web/20160303212629/http://www.hp.com/rnd/pdfs/RGMIIv1_3.pdf>)

RGMII v2.0: [http://web.archive.org/web/20160303171328/http://www.hp.com/rnd/pdfs/RGMIIv2_0_final_hp.pdf](<http://web.archive.org/web/20160303171328/http://www.hp.com/rnd/pdfs/RGMIIv2_0_final_hp.pdf>)

---

# HOWTO for the linux packet generator

_Peios Kernel / Internals / Networking_

> Enable CONFIG_NET_PKTGEN to compile and build pktgen either in-kernel or as a module. A module is preferred; modprobe pktgen if needed. Once running, pktgen creates a thread for each CPU with affinity to that CPU. Monitoring and…

<a id="rst-howto-for-the-linux-packet-generator"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Enable CONFIG_NET_PKTGEN to compile and build pktgen either in-kernel or as a module.  A module is preferred; modprobe pktgen if needed.  Once running, pktgen creates a thread for each CPU with affinity to that CPU. Monitoring and controlling is done via /proc.  It is easiest to select a suitable sample script and configure that.

On a dual CPU:



```text
ps aux | grep pkt
root       129  0.3  0.0     0    0 ?        SW    2003 523:20 [kpktgend_0]
root       130  0.3  0.0     0    0 ?        SW    2003 509:50 [kpktgend_1]
```

For monitoring and control pktgen creates:



```text
/proc/net/pktgen/pgctrl
/proc/net/pktgen/kpktgend_X
/proc/net/pktgen/ethX
```

<a id="rst-tuning-nic-for-max-performance"></a>

## Tuning NIC for max performance

The default NIC settings are (likely) not tuned for pktgen's artificial overload type of benchmarking, as this could hurt the normal use-case.

Specifically increasing the TX ring buffer in the NIC:



```text
# ethtool -G ethX tx 1024
```

A larger TX ring can improve pktgen's performance, while it can hurt in the general case, 1) because the TX ring buffer might get larger than the CPU's L1/L2 cache, 2) because it allows more queueing in the NIC HW layer (which is bad for bufferbloat).

One should hesitate to conclude that packets/descriptors in the HW TX ring cause delay.  Drivers usually delay cleaning up the ring-buffers for various performance reasons, and packets stalling the TX ring might just be waiting for cleanup.

This cleanup issue is specifically the case for the driver ixgbe (Intel 82599 chip).  This driver (ixgbe) combines TX+RX ring cleanups, and the cleanup interval is affected by the ethtool --coalesce setting of parameter "rx-usecs".

For ixgbe use e.g. "30" resulting in approx 33K interrupts/sec (1/30\*10^6):



```text
# ethtool -C ethX rx-usecs 30
```

<a id="rst-kernel-threads"></a>

## Kernel threads

Pktgen creates a thread for each CPU with affinity to that CPU. Which is controlled through procfile /proc/net/pktgen/kpktgend_X.

Example: /proc/net/pktgen/kpktgend_0:



```text
Running:
Stopped: eth4@0
Result: OK: add_device=eth4@0
```

Most important are the devices assigned to the thread.

The two basic thread commands are:

> - add_device [DEVICE@NAME](<mailto:DEVICE@NAME>) -- adds a single device
>
> - rem_device_all         -- remove all associated devices

When adding a device to a thread, a corresponding procfile is created which is used for configuring this device. Thus, device names need to be unique.

To support adding the same device to multiple threads, which is useful with multi queue NICs, the device naming scheme is extended with "@": [device@something](<mailto:device@something>)

The part after "@" can be anything, but it is custom to use the thread number.

<a id="rst-viewing-devices"></a>

## Viewing devices

The Params section holds configured information.  The Current section holds running statistics.  The Result is printed after a run or after interruption.  Example:



```text
/proc/net/pktgen/eth4@0

Params: count 100000  min_pkt_size: 60  max_pkt_size: 60
    frags: 0  delay: 0  clone_skb: 64  ifname: eth4@0
    flows: 0 flowlen: 0
    queue_map_min: 0  queue_map_max: 0
    dst_min: 192.168.81.2  dst_max:
    src_min:   src_max:
    src_mac: 90:e2:ba:0a:56:b4 dst_mac: 00:1b:21:3c:9d:f8
    udp_src_min: 9  udp_src_max: 109  udp_dst_min: 9  udp_dst_max: 9
    src_mac_count: 0  dst_mac_count: 0
    Flags: UDPSRC_RND  NO_TIMESTAMP  QUEUE_MAP_CPU
Current:
    pkts-sofar: 100000  errors: 0
    started: 623913381008us  stopped: 623913396439us idle: 25us
    seq_num: 100001  cur_dst_mac_offset: 0  cur_src_mac_offset: 0
    cur_saddr: 192.168.8.3  cur_daddr: 192.168.81.2
    cur_udp_dst: 9  cur_udp_src: 42
    cur_queue_map: 0
    flows: 0
Result: OK: 15430(c15405+d25) usec, 100000 (60byte,0frags)
6480562pps 3110Mb/sec (3110669760bps) errors: 0
```

<a id="rst-configuring-devices"></a>

## Configuring devices

This is done via the /proc interface, and most easily done via pgset as defined in the sample scripts. You need to specify PGDEV environment variable to use functions from sample scripts, i.e.:



```text
export PGDEV=/proc/net/pktgen/eth4@0
source samples/pktgen/functions.sh
```

Examples:



```text
pg_ctrl start           starts injection.
pg_ctrl stop            aborts injection. Also, ^C aborts generator.

pgset "clone_skb 1"     sets the number of copies of the same packet
pgset "clone_skb 0"     use single SKB for all transmits
pgset "burst 8"         uses xmit_more API to queue 8 copies of the same
                        packet and update HW tx queue tail pointer once.
                        "burst 1" is the default
pgset "pkt_size 9014"   sets packet size to 9014
pgset "frags 5"         packet will consist of 5 fragments
pgset "count 200000"    sets number of packets to send, set to zero
                        for continuous sends until explicitly stopped.

pgset "delay 5000"      adds delay to hard_start_xmit(). nanoseconds

pgset "dst 10.0.0.1"    sets IP destination address
                        (BEWARE! This generator is very aggressive!)

pgset "dst_min 10.0.0.1"            Same as dst
pgset "dst_max 10.0.0.254"          Set the maximum destination IP.
pgset "src_min 10.0.0.1"            Set the minimum (or only) source IP.
pgset "src_max 10.0.0.254"          Set the maximum source IP.
pgset "dst6 fec0::1"     IPV6 destination address
pgset "src6 fec0::2"     IPV6 source address
pgset "dstmac 00:00:00:00:00:00"    sets MAC destination address
pgset "srcmac 00:00:00:00:00:00"    sets MAC source address

pgset "queue_map_min 0" Sets the min value of tx queue interval
pgset "queue_map_max 7" Sets the max value of tx queue interval, for multiqueue devices
                        To select queue 1 of a given device,
                        use queue_map_min=1 and queue_map_max=1

pgset "src_mac_count 1" Sets the number of MACs we'll range through.
                        The 'minimum' MAC is what you set with srcmac.

pgset "dst_mac_count 1" Sets the number of MACs we'll range through.
                        The 'minimum' MAC is what you set with dstmac.

pgset "flag [name]"     Set a flag to determine behaviour.  Current flags
                        are: IPSRC_RND # IP source is random (between min/max)
                             IPDST_RND # IP destination is random
                             UDPSRC_RND, UDPDST_RND,
                             MACSRC_RND, MACDST_RND
                             TXSIZE_RND, IPV6,
                             MPLS_RND, VID_RND, SVID_RND
                             FLOW_SEQ,
                             QUEUE_MAP_RND # queue map random
                             QUEUE_MAP_CPU # queue map mirrors smp_processor_id()
                             UDPCSUM,
                             IPSEC # IPsec encapsulation (needs CONFIG_XFRM)
                             NODE_ALLOC # node specific memory allocation
                             NO_TIMESTAMP # disable timestamping
                             SHARED # enable shared SKB
pgset 'flag ![name]'    Clear a flag to determine behaviour.
                        Note that you might need to use single quote in
                        interactive mode, so that your shell wouldn't expand
                        the specified flag as a history command.

pgset "spi [SPI_VALUE]" Set specific SA used to transform packet.

pgset "udp_src_min 9"   set UDP source port min, If < udp_src_max, then
                        cycle through the port range.

pgset "udp_src_max 9"   set UDP source port max.
pgset "udp_dst_min 9"   set UDP destination port min, If < udp_dst_max, then
                        cycle through the port range.
pgset "udp_dst_max 9"   set UDP destination port max.

pgset "mpls 0001000a,0002000a,0000000a" set MPLS labels (in this example
                                        outer label=16,middle label=32,
                                        inner label=0 (IPv4 NULL)) Note that
                                        there must be no spaces between the
                                        arguments. Leading zeros are required.
                                        Do not set the bottom of stack bit,
                                        that's done automatically. If you do
                                        set the bottom of stack bit, that
                                        indicates that you want to randomly
                                        generate that address and the flag
                                        MPLS_RND will be turned on. You
                                        can have any mix of random and fixed
                                        labels in the label stack.

pgset "mpls 0"           turn off mpls (or any invalid argument works too!)

pgset "vlan_id 77"       set VLAN ID 0-4095
pgset "vlan_p 3"         set priority bit 0-7 (default 0)
pgset "vlan_cfi 0"       set canonical format identifier 0-1 (default 0)

pgset "svlan_id 22"      set SVLAN ID 0-4095
pgset "svlan_p 3"        set priority bit 0-7 (default 0)
pgset "svlan_cfi 0"      set canonical format identifier 0-1 (default 0)

pgset "vlan_id 9999"     > 4095 remove vlan and svlan tags
pgset "svlan 9999"       > 4095 remove svlan tag


pgset "tos XX"           set former IPv4 TOS field (e.g. "tos 28" for AF11 no ECN, default 00)
pgset "traffic_class XX" set former IPv6 TRAFFIC CLASS (e.g. "traffic_class B8" for EF no ECN, default 00)

pgset "rate 300M"        set rate to 300 Mb/s
pgset "ratep 1000000"    set rate to 1Mpps

pgset "xmit_mode netif_receive"  RX inject into stack netif_receive_skb()
                                 Works with "burst" but not with "clone_skb".
                                 Default xmit_mode is "start_xmit".
```

<a id="rst-sample-scripts"></a>

## Sample scripts

A collection of tutorial scripts and helpers for pktgen is in the samples/pktgen directory. The helper parameters.sh file support easy and consistent parameter parsing across the sample scripts.

Usage example and help:



```text
./pktgen_sample01_simple.sh -i eth4 -m 00:1B:21:3C:9D:F8 -d 192.168.8.2
```

Usage::



```text
./pktgen_sample01_simple.sh [-vx] -i ethX

-i : ($DEV)       output interface/device (required)
-s : ($PKT_SIZE)  packet size
-d : ($DEST_IP)   destination IP. CIDR (e.g. 198.18.0.0/15) is also allowed
-m : ($DST_MAC)   destination MAC-addr
-p : ($DST_PORT)  destination PORT range (e.g. 433-444) is also allowed
-t : ($THREADS)   threads to start
-f : ($F_THREAD)  index of first thread (zero indexed CPU number)
-c : ($SKB_CLONE) SKB clones send before alloc new SKB
-n : ($COUNT)     num messages to send per thread, 0 means indefinitely
-b : ($BURST)     HW level bursting of SKBs
-v : ($VERBOSE)   verbose
-x : ($DEBUG)     debug
-6 : ($IP6)       IPv6
-w : ($DELAY)     Tx Delay value (ns)
-a : ($APPEND)    Script will not reset generator's state, but will append its config
```

The global variables being set are also listed.  E.g. the required interface/device parameter "-i" sets variable $DEV.  Copy the pktgen_sampleXX scripts and modify them to fit your own needs.

<a id="rst-interrupt-affinity"></a>

## Interrupt affinity

Note that when adding devices to a specific CPU it is a good idea to also assign /proc/irq/XX/smp_affinity so that the TX interrupts are bound to the same CPU.  This reduces cache bouncing when freeing skbs.

Plus using the device flag QUEUE_MAP_CPU, which maps the SKBs TX queue to the running threads CPU (directly from smp_processor_id()).

<a id="rst-enable-ipsec"></a>

## Enable IPsec

Default IPsec transformation with ESP encapsulation plus transport mode can be enabled by simply setting:



```text
pgset "flag IPSEC"
pgset "flows 1"
```

To avoid breaking existing testbed scripts for using AH type and tunnel mode, you can use "pgset spi SPI_VALUE" to specify which transformation mode to employ.

<a id="rst-disable-shared-skb"></a>

## Disable shared SKB

By default, SKBs sent by pktgen are shared (user count &gt; 1). To test with non-shared SKBs, remove the "SHARED" flag by simply setting:



```text
pg_set "flag !SHARED"
```

However, if the "clone_skb" or "burst" parameters are configured, the skb still needs to be held by pktgen for further access. Hence the skb must be shared.

<a id="rst-current-commands-and-configuration-options"></a>

## Current commands and configuration options

**Pgcontrol commands**:



```text
start
stop
reset
```

**Thread commands**:



```text
add_device
rem_device_all
```

**Device commands**:



```text
count
clone_skb
burst
debug

frags
delay

src_mac_count
dst_mac_count

pkt_size
min_pkt_size
max_pkt_size

queue_map_min
queue_map_max
skb_priority

tos           (ipv4)
traffic_class (ipv6)

mpls

udp_src_min
udp_src_max

udp_dst_min
udp_dst_max

node

flag
IPSRC_RND
IPDST_RND
UDPSRC_RND
UDPDST_RND
MACSRC_RND
MACDST_RND
TXSIZE_RND
IPV6
MPLS_RND
VID_RND
SVID_RND
FLOW_SEQ
QUEUE_MAP_RND
QUEUE_MAP_CPU
UDPCSUM
IPSEC
NODE_ALLOC
NO_TIMESTAMP
SHARED

spi (ipsec)

dst_min
dst_max

src_min
src_max

dst_mac
src_mac

clear_counters

src6
dst6
dst6_max
dst6_min

flows
flowlen

rate
ratep

xmit_mode <start_xmit|netif_receive>

vlan_cfi
vlan_id
vlan_p

svlan_cfi
svlan_id
svlan_p
```

References:

- [ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/](<ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/>)

- [ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/examples/](<ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/examples/>)

Paper from Linux-Kongress in Erlangen 2004. - [ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/pktgen_paper.pdf](<ftp://robur.slu.se/pub/Linux/net-development/pktgen-testing/pktgen_paper.pdf>)

Thanks to:

Grant Grundler for testing on IA-64 and parisc, Harald Welte,  Lennert Buytenhek Stephen Hemminger, Andi Kleen, Dave Miller and many others.

Good luck with the linux net-development.

---

# PLIP: The Parallel Line Internet Protocol Device

_Peios Kernel / Internals / Networking_

> Donald Becker (becker@super.org) I.D.A. Supercomputing Research Center, Bowie MD 20715

<a id="rst-plip-the-parallel-line-internet-protocol-device"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Donald Becker ([becker@super.org](<mailto:becker@super.org>)) I.D.A. Supercomputing Research Center, Bowie MD 20715

At some point T. Thorn will probably contribute text, Tommy Thorn ([tthorn@daimi.aau.dk](<mailto:tthorn@daimi.aau.dk>))

<a id="rst-plip-introduction"></a>

## PLIP Introduction

This document describes the parallel port packet pusher for Net/LGX. This device interface allows a point-to-point connection between two parallel ports to appear as a IP network interface.

<a id="rst-what-is-plip"></a>

### What is PLIP?

PLIP is Parallel Line IP, that is, the transportation of IP packages over a parallel port. In the case of a PC, the obvious choice is the printer port.  PLIP is a non-standard, but \[can use\] uses the standard LapLink null-printer cable \[can also work in turbo mode, with a PLIP cable\]. \[The protocol used to pack IP packages, is a simple one initiated by Crynwr.\]

<a id="rst-advantages-of-plip"></a>

### Advantages of PLIP

It's cheap, it's available everywhere, and it's easy.

The PLIP cable is all that's needed to connect two Linux boxes, and it can be built for very few bucks.

Connecting two Linux boxes takes only a second's decision and a few minutes' work, no need to search for a \[supported\] netcard. This might even be especially important in the case of notebooks, where netcards are not easily available.

Not requiring a netcard also means that apart from connecting the cables, everything else is software configuration \[which in principle could be made very easy.\]

<a id="rst-disadvantages-of-plip"></a>

### Disadvantages of PLIP

Doesn't work over a modem, like SLIP and PPP. Limited range, 15 m. Can only be used to connect three (?) Linux boxes. Doesn't connect to an existing Ethernet. Isn't standard (not even de facto standard, like SLIP).

<a id="rst-performance"></a>

### Performance

PLIP easily outperforms Ethernet cards....(ups, I was dreaming, but it *is* getting late. EOB)

<a id="rst-plip-driver-details"></a>

## PLIP driver details

The Linux PLIP driver is an implementation of the original Crynwr protocol, that uses the parallel port subsystem of the kernel in order to properly share parallel ports between PLIP and other services.

<a id="rst-irqs-and-trigger-timeouts"></a>

### IRQs and trigger timeouts

When a parallel port used for a PLIP driver has an IRQ configured to it, the PLIP driver is signaled whenever data is sent to it via the cable, such that when no data is available, the driver isn't being used.

However, on some machines it is hard, if not impossible, to configure an IRQ to a certain parallel port, mainly because it is used by some other device. On these machines, the PLIP driver can be used in IRQ-less mode, where the PLIP driver would constantly poll the parallel port for data waiting, and if such data is available, process it. This mode is less efficient than the IRQ mode, because the driver has to check the parallel port many times per second, even when no data at all is sent. Some rough measurements indicate that there isn't a noticeable performance drop when using IRQ-less mode as compared to IRQ mode as far as the data transfer speed is involved. There is a performance drop on the machine hosting the driver.

When the PLIP driver is used in IRQ mode, the timeout used for triggering a data transfer (the maximal time the PLIP driver would allow the other side before announcing a timeout, when trying to handshake a transfer of some data) is, by default, 500usec. As IRQ delivery is more or less immediate, this timeout is quite sufficient.

When in IRQ-less mode, the PLIP driver polls the parallel port HZ times per second (where HZ is typically 100 on most platforms, and 1024 on an Alpha, as of this writing). Between two such polls, there are 10^6/HZ usecs. On an i386, for example, 10^6/100 = 10000usec. It is easy to see that it is quite possible for the trigger timeout to expire between two such polls, as the timeout is only 500usec long. As a result, it is required to change the trigger timeout on the *other* side of a PLIP connection, to about 10^6/HZ usecs. If both sides of a PLIP connection are used in IRQ-less mode, this timeout is required on both sides.

It appears that in practice, the trigger timeout can be shorter than in the above calculation. It isn't an important issue, unless the wire is faulty, in which case a long timeout would stall the machine when, for whatever reason, bits are dropped.

A utility that can perform this change in Linux is plipconfig, which is part of the net-tools package (its location can be found in the Documentation/Changes file). An example command would be 'plipconfig plipX trigger 10000', where plipX is the appropriate PLIP device.

<a id="rst-plip-hardware-interconnection"></a>

## PLIP hardware interconnection

PLIP uses several different data transfer methods.  The first (and the only one implemented in the early version of the code) uses a standard printer "null" cable to transfer data four bits at a time using data bit outputs connected to status bit inputs.

The second data transfer method relies on both machines having bi-directional parallel ports, rather than output-only `printer` ports.  This allows byte-wide transfers and avoids reconstructing nibbles into bytes, leading to much faster transfers.

<a id="rst-parallel-transfer-mode-0-cable"></a>

### Parallel Transfer Mode 0 Cable

The cable for the first transfer mode is a standard printer "null" cable which transfers data four bits at a time using data bit outputs of the first port (machine T) connected to the status bit inputs of the second port (machine R).  There are five status inputs, and they are used as four data inputs and a clock (data strobe) input, arranged so that the data input bits appear as contiguous bits with standard status register implementation.

A cable that implements this protocol is available commercially as a "Null Printer" or "Turbo Laplink" cable.  It can be constructed with two DB-25 male connectors symmetrically connected as follows:



```text
STROBE output       1*
D0->ERROR   2 - 15          15 - 2
D1->SLCT    3 - 13          13 - 3
D2->PAPOUT  4 - 12          12 - 4
D3->ACK     5 - 10          10 - 5
D4->BUSY    6 - 11          11 - 6
D5,D6,D7 are   7*, 8*, 9*
AUTOFD output 14*
INIT   output 16*
SLCTIN      17 - 17
extra grounds are 18*,19*,20*,21*,22*,23*,24*
GROUND      25 - 25

* Do not connect these pins on either end
```

If the cable you are using has a metallic shield it should be connected to the metallic DB-25 shell at one end only.

<a id="rst-parallel-transfer-mode-1"></a>

### Parallel Transfer Mode 1

The second data transfer method relies on both machines having bi-directional parallel ports, rather than output-only `printer` ports.  This allows byte-wide transfers, and avoids reconstructing nibbles into bytes.  This cable should not be used on unidirectional `printer` (as opposed to `parallel`) ports or when the machine isn't configured for PLIP, as it will result in output driver conflicts and the (unlikely) possibility of damage.

The cable for this transfer mode should be constructed as follows:



```text
STROBE->BUSY 1 - 11
D0->D0      2 - 2
D1->D1      3 - 3
D2->D2      4 - 4
D3->D3      5 - 5
D4->D4      6 - 6
D5->D5      7 - 7
D6->D6      8 - 8
D7->D7      9 - 9
INIT -> ACK  16 - 10
AUTOFD->PAPOUT 14 - 12
SLCT->SLCTIN 13 - 17
GND->ERROR  18 - 15
extra grounds are 19*,20*,21*,22*,23*,24*
GROUND      25 - 25

* Do not connect these pins on either end
```

Once again, if the cable you are using has a metallic shield it should be connected to the metallic DB-25 shell at one end only.

<a id="rst-plip-mode-0-transfer-protocol"></a>

### PLIP Mode 0 transfer protocol

The PLIP driver is compatible with the "Crynwr" parallel port transfer standard in Mode 0.  That standard specifies the following protocol:



```text
send header nibble '0x8'
count-low octet
count-high octet
... data octets
checksum octet
```

Each octet is sent as:



```text
<wait for rx. '0x1?'>   <send 0x10+(octet&0x0F)>
<wait for rx. '0x0?'>   <send 0x00+((octet>>4)&0x0F)>
```

To start a transfer the transmitting machine outputs a nibble 0x08. That raises the ACK line, triggering an interrupt in the receiving machine.  The receiving machine disables interrupts and raises its own ACK line.

Restated:



```text
(OUT is bit 0-4, OUT.j is bit j from OUT. IN likewise)
Send_Byte:
   OUT := low nibble, OUT.4 := 1
   WAIT FOR IN.4 = 1
   OUT := high nibble, OUT.4 := 0
   WAIT FOR IN.4 = 0
```

---

# PPP Generic Driver and Channel Interface

_Peios Kernel / Internals / Networking_

> Paul Mackerras paulus@samba.org

<a id="rst-ppp-generic-driver-and-channel-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> Paul Mackerras [paulus@samba.org](<mailto:paulus@samba.org>)
>
> > 7 Feb 2002

The generic PPP driver in linux-2.4 provides an implementation of the functionality which is of use in any PPP implementation, including:

- the network interface unit (ppp0 etc.)

- the interface to the networking code

- PPP multilink: splitting datagrams between multiple links, and ordering and combining received fragments

- the interface to pppd, via a /dev/ppp character device

- packet compression and decompression

- TCP/IP header compression and decompression

- detecting network traffic for demand dialling and for idle timeouts

- simple packet filtering

For sending and receiving PPP frames, the generic PPP driver calls on the services of PPP `channels`.  A PPP channel encapsulates a mechanism for transporting PPP frames from one machine to another.  A PPP channel implementation can be arbitrarily complex internally but has a very simple interface with the generic PPP code: it merely has to be able to send PPP frames, receive PPP frames, and optionally handle ioctl requests.  Currently there are PPP channel implementations for asynchronous serial ports, synchronous serial ports, and for PPP over ethernet.

This architecture makes it possible to implement PPP multilink in a natural and straightforward way, by allowing more than one channel to be linked to each ppp network interface unit.  The generic layer is responsible for splitting datagrams on transmit and recombining them on receive.

<a id="rst-ppp-channel-api"></a>

## PPP channel API

See include/linux/ppp_channel.h for the declaration of the types and functions used to communicate between the generic PPP layer and PPP channels.

Each channel has to provide two functions to the generic PPP layer, via the ppp_channel.ops pointer:

- start_xmit() is called by the generic layer when it has a frame to send.  The channel has the option of rejecting the frame for flow-control reasons.  In this case, start_xmit() should return 0 and the channel should call the ppp_output_wakeup() function at a later time when it can accept frames again, and the generic layer will then attempt to retransmit the rejected frame(s).  If the frame is accepted, the start_xmit() function should return 1.

- ioctl() provides an interface which can be used by a user-space program to control aspects of the channel's behaviour.  This procedure will be called when a user-space program does an ioctl system call on an instance of /dev/ppp which is bound to the channel.  (Usually it would only be pppd which would do this.)

The generic PPP layer provides seven functions to channels:

- ppp_register_channel() is called when a channel has been created, to notify the PPP generic layer of its presence.  For example, setting a serial port to the PPPDISC line discipline causes the ppp_async channel code to call this function.

- ppp_unregister_channel() is called when a channel is to be destroyed.  For example, the ppp_async channel code calls this when a hangup is detected on the serial port.

- ppp_output_wakeup() is called by a channel when it has previously rejected a call to its start_xmit function, and can now accept more packets.

- ppp_input() is called by a channel when it has received a complete PPP frame.

- ppp_input_error() is called by a channel when it has detected that a frame has been lost or dropped (for example, because of a FCS (frame check sequence) error).

- ppp_channel_index() returns the channel index assigned by the PPP generic layer to this channel.  The channel should provide some way (e.g. an ioctl) to transmit this back to user-space, as user-space will need it to attach an instance of /dev/ppp to this channel.

- ppp_unit_number() returns the unit number of the ppp network interface to which this channel is connected, or -1 if the channel is not connected.

Connecting a channel to the ppp generic layer is initiated from the channel code, rather than from the generic layer.  The channel is expected to have some way for a user-level process to control it independently of the ppp generic layer.  For example, with the ppp_async channel, this is provided by the file descriptor to the serial port.

Generally a user-level process will initialize the underlying communications medium and prepare it to do PPP.  For example, with an async tty, this can involve setting the tty speed and modes, issuing modem commands, and then going through some sort of dialog with the remote system to invoke PPP service there.  We refer to this process as `discovery`.  Then the user-level process tells the medium to become a PPP channel and register itself with the generic PPP layer. The channel then has to report the channel number assigned to it back to the user-level process.  From that point, the PPP negotiation code in the PPP daemon (pppd) can take over and perform the PPP negotiation, accessing the channel through the /dev/ppp interface.

At the interface to the PPP generic layer, PPP frames are stored in skbuff structures and start with the two-byte PPP protocol number. The frame does *not* include the 0xff `address` byte or the 0x03 `control` byte that are optionally used in async PPP.  Nor is there any escaping of control characters, nor are there any FCS or framing characters included.  That is all the responsibility of the channel code, if it is needed for the particular medium.  That is, the skbuffs presented to the start_xmit() function contain only the 2-byte protocol number and the data, and the skbuffs presented to ppp_input() must be in the same format.

The channel must provide an instance of a ppp_channel struct to represent the channel.  The channel is free to use the `private` field however it wishes.  The channel should initialize the `mtu` and `hdrlen` fields before calling ppp_register_channel() and not change them until after ppp_unregister_channel() returns.  The `mtu` field represents the maximum size of the data part of the PPP frames, that is, it does not include the 2-byte protocol number.

If the channel needs some headroom in the skbuffs presented to it for transmission (i.e., some space free in the skbuff data area before the start of the PPP frame), it should set the `hdrlen` field of the ppp_channel struct to the amount of headroom required.  The generic PPP layer will attempt to provide that much headroom but the channel should still check if there is sufficient headroom and copy the skbuff if there isn't.

On the input side, channels should ideally provide at least 2 bytes of headroom in the skbuffs presented to ppp_input().  The generic PPP code does not require this but will be more efficient if this is done.

<a id="rst-buffering-and-flow-control"></a>

## Buffering and flow control

The generic PPP layer has been designed to minimize the amount of data that it buffers in the transmit direction.  It maintains a queue of transmit packets for the PPP unit (network interface device) plus a queue of transmit packets for each attached channel.  Normally the transmit queue for the unit will contain at most one packet; the exceptions are when pppd sends packets by writing to /dev/ppp, and when the core networking code calls the generic layer's start_xmit() function with the queue stopped, i.e. when the generic layer has called netif_stop_queue(), which only happens on a transmit timeout. The start_xmit function always accepts and queues the packet which it is asked to transmit.

Transmit packets are dequeued from the PPP unit transmit queue and then subjected to TCP/IP header compression and packet compression (Deflate or BSD-Compress compression), as appropriate.  After this point the packets can no longer be reordered, as the decompression algorithms rely on receiving compressed packets in the same order that they were generated.

If multilink is not in use, this packet is then passed to the attached channel's start_xmit() function.  If the channel refuses to take the packet, the generic layer saves it for later transmission.  The generic layer will call the channel's start_xmit() function again when the channel calls  ppp_output_wakeup() or when the core networking code calls the generic layer's start_xmit() function again.  The generic layer contains no timeout and retransmission logic; it relies on the core networking code for that.

If multilink is in use, the generic layer divides the packet into one or more fragments and puts a multilink header on each fragment.  It decides how many fragments to use based on the length of the packet and the number of channels which are potentially able to accept a fragment at the moment.  A channel is potentially able to accept a fragment if it doesn't have any fragments currently queued up for it to transmit.  The channel may still refuse a fragment; in this case the fragment is queued up for the channel to transmit later.  This scheme has the effect that more fragments are given to higher- bandwidth channels.  It also means that under light load, the generic layer will tend to fragment large packets across all the channels, thus reducing latency, while under heavy load, packets will tend to be transmitted as single fragments, thus reducing the overhead of fragmentation.

<a id="rst-smp-safety"></a>

## SMP safety

The PPP generic layer has been designed to be SMP-safe.  Locks are used around accesses to the internal data structures where necessary to ensure their integrity.  As part of this, the generic layer requires that the channels adhere to certain requirements and in turn provides certain guarantees to the channels.  Essentially the channels are required to provide the appropriate locking on the ppp_channel structures that form the basis of the communication between the channel and the generic layer.  This is because the channel provides the storage for the ppp_channel structure, and so the channel is required to provide the guarantee that this storage exists and is valid at the appropriate times.

The generic layer requires these guarantees from the channel:

- The ppp_channel object must exist from the time that ppp_register_channel() is called until after the call to ppp_unregister_channel() returns.

- No thread may be in a call to any of ppp_input(), ppp_input_error(), ppp_output_wakeup(), ppp_channel_index() or ppp_unit_number() for a channel at the time that ppp_unregister_channel() is called for that channel.

- ppp_register_channel() and ppp_unregister_channel() must be called from process context, not interrupt or softirq/BH context.

- The remaining generic layer functions may be called at softirq/BH level but must not be called from a hardware interrupt handler.

- The generic layer may call the channel start_xmit() function at softirq/BH level but will not call it at interrupt level.  Thus the start_xmit() function may not block.

- The generic layer will only call the channel ioctl() function in process context.

The generic layer provides these guarantees to the channels:

- The generic layer will not call the start_xmit() function for a channel while any thread is already executing in that function for that channel.

- The generic layer will not call the ioctl() function for a channel while any thread is already executing in that function for that channel.

- By the time a call to ppp_unregister_channel() returns, no thread will be executing in a call from the generic layer to that channel's start_xmit() or ioctl() function, and the generic layer will not call either of those functions subsequently.

<a id="rst-interface-to-pppd"></a>

## Interface to pppd

The PPP generic layer exports a character device interface called /dev/ppp.  This is used by pppd to control PPP interface units and channels.  Although there is only one /dev/ppp, each open instance of /dev/ppp acts independently and can be attached either to a PPP unit or a PPP channel.  This is achieved using the file-&gt;private_data field to point to a separate object for each open instance of /dev/ppp.  In this way an effect similar to Solaris' clone open is obtained, allowing us to control an arbitrary number of PPP interfaces and channels without having to fill up /dev with hundreds of device names.

When /dev/ppp is opened, a new instance is created which is initially unattached.  Using an ioctl call, it can then be attached to an existing unit, attached to a newly-created unit, or attached to an existing channel.  An instance attached to a unit can be used to send and receive PPP control frames, using the read() and write() system calls, along with poll() if necessary.  Similarly, an instance attached to a channel can be used to send and receive PPP frames on that channel.

In multilink terms, the unit represents the bundle, while the channels represent the individual physical links.  Thus, a PPP frame sent by a write to the unit (i.e., to an instance of /dev/ppp attached to the unit) will be subject to bundle-level compression and to fragmentation across the individual links (if multilink is in use).  In contrast, a PPP frame sent by a write to the channel will be sent as-is on that channel, without any multilink header.

A channel is not initially attached to any unit.  In this state it can be used for PPP negotiation but not for the transfer of data packets. It can then be connected to a PPP unit with an ioctl call, which makes it available to send and receive data packets for that unit.

The ioctl calls which are available on an instance of /dev/ppp depend on whether it is unattached, attached to a PPP interface, or attached to a PPP channel.  The ioctl calls which are available on an unattached instance are:

- PPPIOCNEWUNIT creates a new PPP interface and makes this /dev/ppp instance the "owner" of the interface.  The argument should point to an int which is the desired unit number if &gt;= 0, or -1 to assign the lowest unused unit number.  Being the owner of the interface means that the interface will be shut down if this instance of /dev/ppp is closed.

- PPPIOCATTACH attaches this instance to an existing PPP interface. The argument should point to an int containing the unit number. This does not make this instance the owner of the PPP interface.

- PPPIOCATTCHAN attaches this instance to an existing PPP channel. The argument should point to an int containing the channel number.

The ioctl calls available on an instance of /dev/ppp attached to a channel are:

- PPPIOCCONNECT connects this channel to a PPP interface.  The argument should point to an int containing the interface unit number.  It will return an EINVAL error if the channel is already connected to an interface, or ENXIO if the requested interface does not exist.

- PPPIOCDISCONN disconnects this channel from the PPP interface that it is connected to.  It will return an EINVAL error if the channel is not connected to an interface.

- PPPIOCBRIDGECHAN bridges a channel with another. The argument should point to an int containing the channel number of the channel to bridge to. Once two channels are bridged, frames presented to one channel by ppp_input() are passed to the bridge instance for onward transmission. This allows frames to be switched from one channel into another: for example, to pass PPPoE frames into a PPPoL2TP session. Since channel bridging interrupts the normal ppp_input() path, a given channel may not be part of a bridge at the same time as being part of a unit. This ioctl will return an EALREADY error if the channel is already part of a bridge or unit, or ENXIO if the requested channel does not exist.

- PPPIOCUNBRIDGECHAN performs the inverse of PPPIOCBRIDGECHAN, unbridging a channel pair.  This ioctl will return an EINVAL error if the channel does not form part of a bridge.

- All other ioctl commands are passed to the channel ioctl() function.

The ioctl calls that are available on an instance that is attached to an interface unit are:

- PPPIOCSMRU sets the MRU (maximum receive unit) for the interface. The argument should point to an int containing the new MRU value.

- PPPIOCSFLAGS sets flags which control the operation of the interface.  The argument should be a pointer to an int containing the new flags value.  The bits in the flags value that can be set are:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > SC_COMP_TCP
  >
  > </td>
  > <td>
  >
  >
  > enable transmit TCP header compression
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_NO_TCP_CCID
  >
  > </td>
  > <td>
  >
  >
  > disable connection-id compression for TCP header compression
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_REJ_COMP_TCP
  >
  > </td>
  > <td>
  >
  >
  > disable receive TCP header decompression
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_CCP_OPEN
  >
  > </td>
  > <td>
  >
  >
  > Compression Control Protocol (CCP) is open, so inspect CCP packets
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_CCP_UP
  >
  > </td>
  > <td>
  >
  >
  > CCP is up, may (de)compress packets
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_LOOP_TRAFFIC
  >
  > </td>
  > <td>
  >
  >
  > send IP traffic to pppd
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_MULTILINK
  >
  > </td>
  > <td>
  >
  >
  > enable PPP multilink fragmentation on transmitted packets
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_MP_SHORTSEQ
  >
  > </td>
  > <td>
  >
  >
  > expect short multilink sequence numbers on received multilink fragments
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_MP_XSHORTSEQ
  >
  > </td>
  > <td>
  >
  >
  > transmit short multilink sequence nos.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  The values of these flags are defined in &lt;linux/ppp-ioctl.h&gt;.  Note that the values of the SC_MULTILINK, SC_MP_SHORTSEQ and SC_MP_XSHORTSEQ bits are ignored if the CONFIG_PPP_MULTILINK option is not selected.

- PPPIOCGFLAGS returns the value of the status/control flags for the interface unit.  The argument should point to an int where the ioctl will store the flags value.  As well as the values listed above for PPPIOCSFLAGS, the following bits may be set in the returned value:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > SC_COMP_RUN
  >
  > </td>
  > <td>
  >
  >
  > CCP compressor is running
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_DECOMP_RUN
  >
  > </td>
  > <td>
  >
  >
  > CCP decompressor is running
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_DC_ERROR
  >
  > </td>
  > <td>
  >
  >
  > CCP decompressor detected non-fatal error
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > SC_DC_FERROR
  >
  > </td>
  > <td>
  >
  >
  > CCP decompressor detected fatal error
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

- PPPIOCSCOMPRESS sets the parameters for packet compression or decompression.  The argument should point to a ppp_option_data structure (defined in &lt;linux/ppp-ioctl.h&gt;), which contains a pointer/length pair which should describe a block of memory containing a CCP option specifying a compression method and its parameters.  The ppp_option_data struct also contains a `transmit` field.  If this is 0, the ioctl will affect the receive path, otherwise the transmit path.

- PPPIOCGUNIT returns, in the int pointed to by the argument, the unit number of this interface unit.

- PPPIOCSDEBUG sets the debug flags for the interface to the value in the int pointed to by the argument.  Only the least significant bit is used; if this is 1 the generic layer will print some debug messages during its operation.  This is only intended for debugging the generic PPP layer code; it is generally not helpful for working out why a PPP connection is failing.

- PPPIOCGDEBUG returns the debug flags for the interface in the int pointed to by the argument.

- PPPIOCGIDLE returns the time, in seconds, since the last data packets were sent and received.  The argument should point to a ppp_idle structure (defined in &lt;linux/ppp_defs.h&gt;).  If the CONFIG_PPP_FILTER option is enabled, the set of packets which reset the transmit and receive idle timers is restricted to those which pass the `active` packet filter. Two versions of this command exist, to deal with user space expecting times as either 32-bit or 64-bit time_t seconds.

- PPPIOCSMAXCID sets the maximum connection-ID parameter (and thus the number of connection slots) for the TCP header compressor and decompressor.  The lower 16 bits of the int pointed to by the argument specify the maximum connection-ID for the compressor.  If the upper 16 bits of that int are non-zero, they specify the maximum connection-ID for the decompressor, otherwise the decompressor's maximum connection-ID is set to 15.

- PPPIOCSNPMODE sets the network-protocol mode for a given network protocol.  The argument should point to an npioctl struct (defined in &lt;linux/ppp-ioctl.h&gt;).  The `protocol` field gives the PPP protocol number for the protocol to be affected, and the `mode` field specifies what to do with packets for that protocol:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > NPMODE_PASS
  >
  > </td>
  > <td>
  >
  >
  > normal operation, transmit and receive packets
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > NPMODE_DROP
  >
  > </td>
  > <td>
  >
  >
  > silently drop packets for this protocol
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > NPMODE_ERROR
  >
  > </td>
  > <td>
  >
  >
  > drop packets and return an error on transmit
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > NPMODE_QUEUE
  >
  > </td>
  > <td>
  >
  >
  > queue up packets for transmit, drop received packets
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  At present NPMODE_ERROR and NPMODE_QUEUE have the same effect as NPMODE_DROP.

- PPPIOCGNPMODE returns the network-protocol mode for a given protocol.  The argument should point to an npioctl struct with the `protocol` field set to the PPP protocol number for the protocol of interest.  On return the `mode` field will be set to the network- protocol mode for that protocol.

- PPPIOCSPASS and PPPIOCSACTIVE set the `pass` and `active` packet filters.  These ioctls are only available if the CONFIG_PPP_FILTER option is selected.  The argument should point to a sock_fprog structure (defined in &lt;linux/filter.h&gt;) containing the compiled BPF instructions for the filter.  Packets are dropped if they fail the `pass` filter; otherwise, if they fail the `active` filter they are passed but they do not reset the transmit or receive idle timer.

- PPPIOCSMRRU enables or disables multilink processing for received packets and sets the multilink MRRU (maximum reconstructed receive unit).  The argument should point to an int containing the new MRRU value.  If the MRRU value is 0, processing of received multilink fragments is disabled.  This ioctl is only available if the CONFIG_PPP_MULTILINK option is selected.

Last modified: 7-feb-2002

---

# The proc/net/tcp and proc/net/tcp6 variables

_Peios Kernel / Internals / Networking_

> This document describes the interfaces /proc/net/tcp and /proc/net/tcp6. Note that these interfaces are deprecated in favor of tcp_diag.

<a id="rst-the-proc-net-tcp-and-proc-net-tcp6-variables"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the interfaces /proc/net/tcp and /proc/net/tcp6. Note that these interfaces are deprecated in favor of tcp_diag.

These /proc interfaces provide information about currently active TCP connections, and are implemented by tcp4_seq_show() in net/ipv4/tcp_ipv4.c and tcp6_seq_show() in net/ipv6/tcp_ipv6.c, respectively.

It will first list all listening TCP sockets, and next list all established TCP connections. A typical entry of /proc/net/tcp would look like this (split up into 3 parts because of the length of the line):



```text
46: 010310AC:9C4C 030310AC:1770 01
|      |      |      |      |   |--> connection state
|      |      |      |      |------> remote TCP port number
|      |      |      |-------------> remote IPv4 address
|      |      |--------------------> local TCP port number
|      |---------------------------> local IPv4 address
|----------------------------------> number of entry

00000150:00000000 01:00000019 00000000
   |        |     |     |       |--> number of unrecovered RTO timeouts
   |        |     |     |----------> number of jiffies until timer expires
   |        |     |----------------> timer_active (see below)
   |        |----------------------> receive-queue
   |-------------------------------> transmit-queue

1000        0 54165785 4 cd1e6040 25 4 27 3 -1
 |          |    |     |    |     |  | |  | |--> slow start size threshold,
 |          |    |     |    |     |  | |  |      or -1 if the threshold
 |          |    |     |    |     |  | |  |      is >= 0xFFFF
 |          |    |     |    |     |  | |  |----> sending congestion window
 |          |    |     |    |     |  | |-------> (ack.quick<<1)|ack.pingpong
 |          |    |     |    |     |  |---------> Predicted tick of soft clock
 |          |    |     |    |     |              (delayed ACK control data)
 |          |    |     |    |     |------------> retransmit timeout
 |          |    |     |    |------------------> location of socket in memory
 |          |    |     |-----------------------> socket reference count
 |          |    |-----------------------------> inode
 |          |----------------------------------> unanswered 0-window probes
 |---------------------------------------------> uid
```

timer_active:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> no timer is pending
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1
>
> </td>
> <td>
>
>
> retransmit-timer is pending
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 2
>
> </td>
> <td>
>
>
> another timer (e.g. delayed ack or keepalive) is pending
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 3
>
> </td>
> <td>
>
>
> this is a socket in TIME_WAIT state. Not all fields will contain data (or even exist)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 4
>
> </td>
> <td>
>
>
> zero window probe timer is pending
>
> </td>
> </tr>
> </tbody>
> </table>

---

# PSP Security Protocol

_Peios Kernel / Internals / Networking_

> PSP Security Protocol (PSP) was defined at Google and published in:

<a id="rst-psp-security-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<a id="rst-protocol"></a>

## Protocol

PSP Security Protocol (PSP) was defined at Google and published in:

[https://raw.githubusercontent.com/google/psp/main/doc/PSP_Arch_Spec.pdf](<https://raw.githubusercontent.com/google/psp/main/doc/PSP_Arch_Spec.pdf>)

This section briefly covers protocol aspects crucial for understanding the kernel API. Refer to the protocol specification for further details.

Note that the kernel implementation and documentation uses the term "device key" in place of "master key", it is both less confusing to an average developer and is less likely to run afoul any naming guidelines.

<a id="rst-derived-rx-keys"></a>

### Derived Rx keys

PSP borrows some terms and mechanisms from IPsec. PSP was designed with HW offloads in mind. The key feature of PSP is that Rx keys for every connection do not have to be stored by the receiver but can be derived from device key and information present in packet headers. This makes it possible to implement receivers which require a constant amount of memory regardless of the number of connections (`O(1)` scaling).

Tx keys have to be stored like with any other protocol, but Tx is much less latency sensitive than Rx, and delays in fetching keys from slow memory is less likely to cause packet drops. Preferably, the Tx keys should be provided with the packet (e.g. as part of the descriptors).

<a id="rst-key-rotation"></a>

### Key rotation

The device key known only to the receiver is fundamental to the design. Per specification this state cannot be directly accessible (it must be impossible to read it out of the hardware of the receiver NIC). Moreover, it has to be "rotated" periodically (usually daily). Rotation means that new device key gets generated (by a random number generator of the device), and used for all new connections. To avoid disrupting old connections the old device key remains in the NIC. A phase bit carried in the packet headers indicates which generation of device key the packet has been encrypted with.

<a id="rst-user-facing-api"></a>

## User facing API

PSP is designed primarily for hardware offloads. There is currently no software fallback for systems which do not have PSP capable NICs. There is also no standard (or otherwise defined) way of establishing a PSP-secured connection or exchanging the symmetric keys.

The expectation is that higher layer protocols will take care of protocol and key negotiation. For example one may use TLS key exchange, announce the PSP capability, and switch to PSP if both endpoints are PSP-capable.

All configuration of PSP is performed via the PSP netlink family.

<a id="rst-device-discovery"></a>

### Device discovery

The PSP netlink family defines operations to retrieve information about the PSP devices available on the system, configure them and access PSP related statistics.

<a id="rst-securing-a-connection"></a>

### Securing a connection

PSP encryption is currently only supported for TCP connections. Rx and Tx keys are allocated separately. First the `rx-assoc` Netlink command needs to be issued, specifying a target TCP socket. Kernel will allocate a new PSP Rx key from the NIC and associate it with given socket. At this stage socket will accept both PSP-secured and plain text TCP packets.

Tx keys are installed using the `tx-assoc` Netlink command. Once the Tx keys are installed, all data read from the socket will be PSP-secured. In other words act of installing Tx keys has a secondary effect on the Rx direction.

There is an intermediate period after `tx-assoc` successfully returns and before the TCP socket encounters it's first PSP authenticated packet, where the TCP stack will allow certain nondata packets, i.e. ACKs, FINs, and RSTs, to enter TCP receive processing even if not PSP authenticated. During the `tx-assoc` call, the TCP socket's `rcv_nxt` field is recorded. At this point, ACKs and RSTs will be accepted with any sequence number, while FINs will only be accepted at the latched value of `rcv_nxt`. Once the TCP stack encounters the first TCP packet containing PSP authenticated data, the other end of the connection must have executed the `tx-assoc` command, so any TCP packet, including those without data, will be dropped before receive processing if it is not successfully authenticated. This is summarized in the table below. The aforementioned state of rejecting all non-PSP packets is labeled "PSP Full".


<table>
<thead>
<tr>
<th>


Event

</th>
<th>


Normal TCP

</th>
<th>


Rx PSP

</th>
<th>


Tx PSP

</th>
<th>


PSP Full

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Rx plain (data)

</td>
<td>


accept

</td>
<td>


accept

</td>
<td>


drop

</td>
<td>


drop

</td>
</tr>
<tr>
<td>


Rx plain (ACK\|FIN\|RST)

</td>
<td>


accept

</td>
<td>


accept

</td>
<td>


accept

</td>
<td>


drop

</td>
</tr>
<tr>
<td>


Rx PSP (good)

</td>
<td>


drop

</td>
<td>


accept

</td>
<td>


accept

</td>
<td>


accept

</td>
</tr>
<tr>
<td>


Rx PSP (bad crypt, \!=SPI)

</td>
<td>


drop

</td>
<td>


drop

</td>
<td>


drop

</td>
<td>


drop

</td>
</tr>
<tr>
<td>


Tx

</td>
<td>


plain text

</td>
<td>


plain text

</td>
<td>


encrypted (excl. rtx)

</td>
<td>


encrypted (excl. rtx)

</td>
</tr>
</tbody>
</table>

To ensure that any data read from the socket after the `tx-assoc` call returns success has been authenticated, the kernel will scan the receive and ofo queues of the socket at `tx-assoc` time. If any enqueued packet was received in clear text, the Tx association will fail, and the application should retry installing the Tx key after draining the socket (this should not be necessary if both endpoints are well behaved).

Because TCP sequence numbers are not integrity protected prior to upgrading to PSP, it is possible that a MITM could offset sequence numbers in a way that deletes a prefix of the PSP protected part of the TCP stream. If userspace cares to mitigate this type of attack, a special "start of PSP" message should be exchanged after `tx-assoc`.

<a id="rst-rotation-notifications"></a>

### Rotation notifications

The rotations of device key happen asynchronously and are usually performed by management daemons, not under application control. The PSP netlink family will generate a notification whenever keys are rotated. The applications are expected to re-establish connections before keys are rotated again.

<a id="rst-kernel-implementation"></a>

## Kernel implementation

<a id="rst-driver-notes"></a>

### Driver notes

Drivers are expected to start with no PSP enabled (`psp-versions-ena` in `dev-get` set to `0`) whenever possible. The user space should not depend on this behavior, as future extension may necessitate creation of devices with PSP already enabled, nonetheless drivers should not enable PSP by default. Enabling PSP should be the responsibility of the system component which also takes care of key rotation.

Note that `psp-versions-ena` is expected to be used only for enabling receive processing. The device is not expected to reject transmit requests after `psp-versions-ena` has been disabled. User may also disable `psp-versions-ena` while there are active associations, which will break all PSP Rx processing.

Drivers are expected to ensure that a device key is usable and secure upon init, without explicit key rotation by the user space. It must be possible to allocate working keys, and that no duplicate keys must be generated. If the device allows the host to request the key for an arbitrary SPI - driver should discard both device keys (rotate the device key twice), to avoid potentially using a SPI+key which previous OS instance already had access to.

Drivers must use `psp_skb_get_assoc_rcu()` to check if PSP Tx offload was requested for given skb. On Rx drivers should allocate and populate the `SKB_EXT_PSP` skb extension, and set the skb-&gt;decrypted bit to 1.

<a id="rst-kernel-implementation-notes"></a>

### Kernel implementation notes

PSP implementation follows the TLS offload more closely than the IPsec offload, with per-socket state, and the use of skb-&gt;decrypted to prevent clear text leaks.

PSP device is separate from netdev, to make it possible to "delegate" PSP offload capabilities to software devices (e.g. `veth`).

---

# How to use radiotap headers

_Peios Kernel / Internals / Networking_

> Radiotap headers are variable-length and extensible, you can get most of the information you need to know on them from:

<a id="rst-how-to-use-radiotap-headers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-pointer-to-the-radiotap-include-file"></a>

## Pointer to the radiotap include file

Radiotap headers are variable-length and extensible, you can get most of the information you need to know on them from:



```text
./include/net/ieee80211_radiotap.h
```

This document gives an overview and warns on some corner cases.

<a id="rst-structure-of-the-header"></a>

## Structure of the header

There is a fixed portion at the start which contains a u32 bitmap that defines if the possible argument associated with that bit is present or not.  So if b0 of the it_present member of ieee80211_radiotap_header is set, it means that the header for argument index 0 (IEEE80211_RADIOTAP_TSFT) is present in the argument area.



```text
< 8-byte ieee80211_radiotap_header >
[ <possible argument bitmap extensions ... > ]
[ <argument> ... ]
```

At the moment there are only 13 possible argument indexes defined, but in case we run out of space in the u32 it_present member, it is defined that b31 set indicates that there is another u32 bitmap following (shown as "possible argument bitmap extensions..." above), and the start of the arguments is moved forward 4 bytes each time.

Note also that the it_len member \__le16 is set to the total number of bytes covered by the ieee80211_radiotap_header and any arguments following.

<a id="rst-requirements-for-arguments"></a>

## Requirements for arguments

After the fixed part of the header, the arguments follow for each argument index whose matching bit is set in the it_present member of ieee80211_radiotap_header.

> - the arguments are all stored little-endian\!
>
> - the argument payload for a given argument index has a fixed size.  So IEEE80211_RADIOTAP_TSFT being present always indicates an 8-byte argument is present.  See the comments in ./include/net/ieee80211_radiotap.h for a nice breakdown of all the argument sizes
>
> - the arguments must be aligned to a boundary of the argument size using padding.  So a u16 argument must start on the next u16 boundary if it isn't already on one, a u32 must start on the next u32 boundary and so on.
>
> - "alignment" is relative to the start of the ieee80211_radiotap_header, ie, the first byte of the radiotap header.  The absolute alignment of that first byte isn't defined.  So even if the whole radiotap header is starting at, eg, address 0x00000003, still the first byte of the radiotap header is treated as 0 for alignment purposes.
>
> - the above point that there may be no absolute alignment for multibyte entities in the fixed radiotap header or the argument region means that you have to take special evasive action when trying to access these multibyte entities.  Some arches like Blackfin cannot deal with an attempt to dereference, eg, a u16 pointer that is pointing to an odd address.  Instead you have to use a kernel API get_unaligned() to dereference the pointer, which will do it bytewise on the arches that require that.
>
> - The arguments for a given argument index can be a compound of multiple types together.  For example IEEE80211_RADIOTAP_CHANNEL has an argument payload consisting of two u16s of total length 4.  When this happens, the padding rule is applied dealing with a u16, NOT dealing with a 4-byte single entity.

<a id="rst-example-valid-radiotap-header"></a>

## Example valid radiotap header



```text
0x00, 0x00, // <-- radiotap version + pad byte
0x0b, 0x00, // <- radiotap header length
0x04, 0x0c, 0x00, 0x00, // <-- bitmap
0x6c, // <-- rate (in 500kHz units)
0x0c, //<-- tx power
0x01 //<-- antenna
```

<a id="rst-using-the-radiotap-parser"></a>

## Using the Radiotap Parser

If you are having to parse a radiotap struct, you can radically simplify the job by using the radiotap parser that lives in net/wireless/radiotap.c and has its prototypes available in include/net/cfg80211.h.  You use it like this:



```text
#include <net/cfg80211.h>

/* buf points to the start of the radiotap header part */

int MyFunction(u8 * buf, int buflen)
{
        int pkt_rate_100kHz = 0, antenna = 0, pwr = 0;
        struct ieee80211_radiotap_iterator iterator;
        int ret = ieee80211_radiotap_iterator_init(&iterator, buf, buflen);

        while (!ret) {

                ret = ieee80211_radiotap_iterator_next(&iterator);

                if (ret)
                        continue;

                /* see if this argument is something we can use */

                switch (iterator.this_arg_index) {
                /*
                * You must take care when dereferencing iterator.this_arg
                * for multibyte types... the pointer is not aligned.  Use
                * get_unaligned((type *)iterator.this_arg) to dereference
                * iterator.this_arg for type "type" safely on all arches.
                */
                case IEEE80211_RADIOTAP_RATE:
                        /* radiotap "rate" u8 is in
                        * 500kbps units, eg, 0x02=1Mbps
                        */
                        pkt_rate_100kHz = (*iterator.this_arg) * 5;
                        break;

                case IEEE80211_RADIOTAP_ANTENNA:
                        /* radiotap uses 0 for 1st ant */
                        antenna = *iterator.this_arg);
                        break;

                case IEEE80211_RADIOTAP_DBM_TX_POWER:
                        pwr = *iterator.this_arg;
                        break;

                default:
                        break;
                }
        }  /* while more rt headers */

        if (ret != -ENOENT)
                return TXRX_DROP;

        /* discard the radiotap header part */
        buf += iterator.max_length;
        buflen -= iterator.max_length;

        ...

}
```

Andy Green &lt;[andy@warmcat.com](<mailto:andy@warmcat.com>)&gt;

---

# RDS

_Peios Kernel / Internals / Networking_

> This readme tries to provide some background on the hows and whys of RDS, and will hopefully help you find your way around the code.

<a id="rst-rds"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

This readme tries to provide some background on the hows and whys of RDS, and will hopefully help you find your way around the code.

In addition, please see this email about RDS origins: [http://oss.oracle.com/pipermail/rds-devel/2007-November/000228.html](<http://oss.oracle.com/pipermail/rds-devel/2007-November/000228.html>)

<a id="rst-rds-architecture"></a>

## RDS Architecture

RDS provides reliable, ordered datagram delivery by using a single reliable connection between any two nodes in the cluster. This allows applications to use a single socket to talk to any other process in the cluster - so in a cluster with N processes you need N sockets, in contrast to N\*N if you use a connection-oriented socket transport like TCP.

RDS is not Infiniband-specific; it was designed to support different transports.  The current implementation used to support RDS over TCP as well as IB.

The high-level semantics of RDS from the application's point of view are

> - Addressing
>
>   RDS uses IPv4 addresses and 16bit port numbers to identify the end point of a connection. All socket operations that involve passing addresses between kernel and user space generally use a struct sockaddr_in.
>
>   The fact that IPv4 addresses are used does not mean the underlying transport has to be IP-based. In fact, RDS over IB uses a reliable IB connection; the IP address is used exclusively to locate the remote node's GID (by ARPing for the given IP).
>
>   The port space is entirely independent of UDP, TCP or any other protocol.
>
> - Socket interface
>
>   RDS sockets work *mostly* as you would expect from a BSD socket. The next section will cover the details. At any rate, all I/O is performed through the standard BSD socket API. Some additions like zerocopy support are implemented through control messages, while other extensions use the getsockopt/ setsockopt calls.
>
>   Sockets must be bound before you can send or receive data. This is needed because binding also selects a transport and attaches it to the socket. Once bound, the transport assignment does not change. RDS will tolerate IPs moving around (eg in a active-active HA scenario), but only as long as the address doesn't move to a different transport.
>
> - sysctls
>
>   RDS supports a number of sysctls in /proc/sys/net/rds

<a id="rst-socket-interface"></a>

## Socket Interface

> - **AF_RDS, PF_RDS, SOL_RDS**
>
>   AF_RDS and PF_RDS are the domain type to be used with socket(2) to create RDS sockets. SOL_RDS is the socket-level to be used with setsockopt(2) and getsockopt(2) for RDS specific socket options.
>
> - **fd = socket(PF_RDS, SOCK_SEQPACKET, 0);**
>
>   This creates a new, unbound RDS socket.
>
> - **setsockopt(SOL_SOCKET): send and receive buffer size**
>
>   RDS honors the send and receive buffer size socket options. You are not allowed to queue more than SO_SNDSIZE bytes to a socket. A message is queued when sendmsg is called, and it leaves the queue when the remote system acknowledges its arrival.
>
>   The SO_RCVSIZE option controls the maximum receive queue length. This is a soft limit rather than a hard limit - RDS will continue to accept and queue incoming messages, even if that takes the queue length over the limit. However, it will also mark the port as "congested" and send a congestion update to the source node. The source node is supposed to throttle any processes sending to this congested port.
>
> - **bind(fd, &amp;sockaddr_in, ...)**
>
>   This binds the socket to a local IP address and port, and a transport, if one has not already been selected via the SO_RDS_TRANSPORT socket option
>
> - **sendmsg(fd, ...)**
>
>   Sends a message to the indicated recipient. The kernel will transparently establish the underlying reliable connection if it isn't up yet.
>
>   An attempt to send a message that exceeds SO_SNDSIZE will return with -EMSGSIZE
>
>   An attempt to send a message that would take the total number of queued bytes over the SO_SNDSIZE threshold will return EAGAIN.
>
>   An attempt to send a message to a destination that is marked as "congested" will return ENOBUFS.
>
> - **recvmsg(fd, ...)**
>
>   Receives a message that was queued to this socket. The sockets recv queue accounting is adjusted, and if the queue length drops below SO_SNDSIZE, the port is marked uncongested, and a congestion update is sent to all peers.
>
>   Applications can ask the RDS kernel module to receive notifications via control messages (for instance, there is a notification when a congestion update arrived, or when a RDMA operation completes). These notifications are received through the msg.msg_control buffer of struct msghdr. The format of the messages is described in manpages.
>
> - **poll(fd)**
>
>   RDS supports the poll interface to allow the application to implement async I/O.
>
>   POLLIN handling is pretty straightforward. When there's an incoming message queued to the socket, or a pending notification, we signal POLLIN.
>
>   POLLOUT is a little harder. Since you can essentially send to any destination, RDS will always signal POLLOUT as long as there's room on the send queue (ie the number of bytes queued is less than the sendbuf size).
>
>   However, the kernel will refuse to accept messages to a destination marked congested - in this case you will loop forever if you rely on poll to tell you what to do. This isn't a trivial problem, but applications can deal with this - by using congestion notifications, and by checking for ENOBUFS errors returned by sendmsg.
>
> - **setsockopt(SOL_RDS, RDS_CANCEL_SENT_TO, &amp;sockaddr_in)**
>
>   This allows the application to discard all messages queued to a specific destination on this particular socket.
>
>   This allows the application to cancel outstanding messages if it detects a timeout. For instance, if it tried to send a message, and the remote host is unreachable, RDS will keep trying forever. The application may decide it's not worth it, and cancel the operation. In this case, it would use RDS_CANCEL_SENT_TO to nuke any pending messages.
>
> - **`setsockopt(fd, SOL_RDS, SO_RDS_TRANSPORT, (int *)&transport ..), getsockopt(fd, SOL_RDS, SO_RDS_TRANSPORT, (int *)&transport ..)`**
>
>   Set or read an integer defining  the underlying encapsulating transport to be used for RDS packets on the socket. When setting the option, integer argument may be one of RDS_TRANS_TCP or RDS_TRANS_IB. When retrieving the value, RDS_TRANS_NONE will be returned on an unbound socket. This socket option may only be set exactly once on the socket, prior to binding it via the bind(2) system call. Attempts to set SO_RDS_TRANSPORT on a socket for which the transport has been previously attached explicitly (by SO_RDS_TRANSPORT) or implicitly (via bind(2)) will return an error of EOPNOTSUPP. An attempt to set SO_RDS_TRANSPORT to RDS_TRANS_NONE will always return EINVAL.

<a id="rst-rdma-for-rds"></a>

## RDMA for RDS

> see rds-rdma(7) manpage (available in rds-tools)

<a id="rst-congestion-notifications"></a>

## Congestion Notifications

> see rds(7) manpage

<a id="rst-rds-protocol"></a>

## RDS Protocol

> Message header
>
> > The message header is a 'struct rds_header' (see rds.h):
> >
> > Fields:
> >
> > > - **h_sequence:**
> > >
> > >   per-packet sequence number
> > >
> > > - **h_ack:**
> > >
> > >   piggybacked acknowledgment of last packet received
> > >
> > > - **h_len:**
> > >
> > >   length of data, not including header
> > >
> > > - **h_sport:**
> > >
> > >   source port
> > >
> > > - **h_dport:**
> > >
> > >   destination port
> > >
> > > - **h_flags:**
> > >
> > >   Can be:
> > >
> > >
> > >   <table>
> > >   <tbody>
> > >   <tr>
> > >   <td>
> > >
> > >
> > >   CONG_BITMAP
> > >
> > >   </td>
> > >   <td>
> > >
> > >
> > >   this is a congestion update bitmap
> > >
> > >   </td>
> > >   </tr>
> > >   <tr>
> > >   <td>
> > >
> > >
> > >   ACK_REQUIRED
> > >
> > >   </td>
> > >   <td>
> > >
> > >
> > >   receiver must ack this packet
> > >
> > >   </td>
> > >   </tr>
> > >   <tr>
> > >   <td>
> > >
> > >
> > >   RETRANSMITTED
> > >
> > >   </td>
> > >   <td>
> > >
> > >
> > >   packet has previously been sent
> > >
> > >   </td>
> > >   </tr>
> > >   </tbody>
> > >   </table>
> > >
> > > - **h_credit:**
> > >
> > >   indicate to other end of connection that it has more credits available (i.e. there is more send room)
> > >
> > > - **h_padding\[4\]:**
> > >
> > >   unused, for future use
> > >
> > > - **h_csum:**
> > >
> > >   header checksum
> > >
> > > - **h_exthdr:**
> > >
> > >   optional data can be passed here. This is currently used for passing RDMA-related information.
>
> ACK and retransmit handling
>
> > One might think that with reliable IB connections you wouldn't need to ack messages that have been received.  The problem is that IB hardware generates an ack message before it has DMAed the message into memory.  This creates a potential message loss if the HCA is disabled for any reason between when it sends the ack and before the message is DMAed and processed.  This is only a potential issue if another HCA is available for fail-over.
> >
> > Sending an ack immediately would allow the sender to free the sent message from their send queue quickly, but could cause excessive traffic to be used for acks. RDS piggybacks acks on sent data packets.  Ack-only packets are reduced by only allowing one to be in flight at a time, and by the sender only asking for acks when its send buffers start to fill up. All retransmissions are also acked.
>
> Flow Control
>
> > RDS's IB transport uses a credit-based mechanism to verify that there is space in the peer's receive buffers for more data. This eliminates the need for hardware retries on the connection.
>
> Congestion
>
> > Messages waiting in the receive queue on the receiving socket are accounted against the sockets SO_RCVBUF option value.  Only the payload bytes in the message are accounted for.  If the number of bytes queued equals or exceeds rcvbuf then the socket is congested.  All sends attempted to this socket's address should return block or return -EWOULDBLOCK.
> >
> > Applications are expected to be reasonably tuned such that this situation very rarely occurs.  An application encountering this "back-pressure" is considered a bug.
> >
> > This is implemented by having each node maintain bitmaps which indicate which ports on bound addresses are congested.  As the bitmap changes it is sent through all the connections which terminate in the local address of the bitmap which changed.
> >
> > The bitmaps are allocated as connections are brought up.  This avoids allocation in the interrupt handling path which queues messages on sockets.  The dense bitmaps let transports send the entire bitmap on any bitmap change reasonably efficiently.  This is much easier to implement than some finer-grained communication of per-port congestion.  The sender does a very inexpensive bit test to test if the port it's about to send to is congested or not.

<a id="rst-rds-transport-layer"></a>

## RDS Transport Layer

> As mentioned above, RDS is not IB-specific. Its code is divided into a general RDS layer and a transport layer.
>
> The general layer handles the socket API, congestion handling, loopback, stats, usermem pinning, and the connection state machine.
>
> The transport layer handles the details of the transport. The IB transport, for example, handles all the queue pairs, work requests, CM event handlers, and other Infiniband details.

<a id="rst-rds-kernel-structures"></a>

## RDS Kernel Structures

> - **struct rds_message**
>
>   aka possibly "rds_outgoing", the generic RDS layer copies data to be sent and sets header fields as needed, based on the socket API. This is then queued for the individual connection and sent by the connection's transport.
>
> - **struct rds_incoming**
>
>   a generic struct referring to incoming data that can be handed from the transport to the general code and queued by the general code while the socket is awoken. It is then passed back to the transport code to handle the actual copy-to-user.
>
> - **struct rds_socket**
>
>   per-socket information
>
> - **struct rds_connection**
>
>   per-connection information
>
> - **struct rds_transport**
>
>   pointers to transport-specific functions
>
> - **struct rds_statistics**
>
>   non-transport-specific statistics
>
> - **struct rds_cong_map**
>
>   wraps the raw congestion bitmap, contains rbnode, waitq, etc.

<a id="rst-connection-management"></a>

## Connection management

> Connections may be in UP, DOWN, CONNECTING, DISCONNECTING, and ERROR states.
>
> The first time an attempt is made by an RDS socket to send data to a node, a connection is allocated and connected. That connection is then maintained forever -- if there are transport errors, the connection will be dropped and re-established.
>
> Dropping a connection while packets are queued will cause queued or partially-sent datagrams to be retransmitted when the connection is re-established.

<a id="rst-the-send-path"></a>

## The send path

> - **rds_sendmsg()**
>
>   - struct rds_message built from incoming data
>
>   - CMSGs parsed (e.g. RDMA ops)
>
>   - transport connection allocated and connected if not already
>
>   - rds_message placed on send queue
>
>   - send worker awoken
>
> - **rds_send_worker()**
>
>   - calls rds_send_xmit() until queue is empty
>
> - **rds_send_xmit()**
>
>   - transmits congestion map if one is pending
>
>   - may set ACK_REQUIRED
>
>   - calls transport to send either non-RDMA or RDMA message (RDMA ops never retransmitted)
>
> - **rds_ib_xmit()**
>
>   - allocs work requests from send ring
>
>   - adds any new send credits available to peer (h_credits)
>
>   - maps the rds_message's sg list
>
>   - piggybacks ack
>
>   - populates work requests
>
>   - post send to connection's queue pair

<a id="rst-the-recv-path"></a>

## The recv path

> - **rds_ib_recv_cq_comp_handler()**
>
>   - looks at write completions
>
>   - unmaps recv buffer from device
>
>   - no errors, call rds_ib_process_recv()
>
>   - refill recv ring
>
> - **rds_ib_process_recv()**
>
>   - validate header checksum
>
>   - copy header to rds_ib_incoming struct if start of a new datagram
>
>   - add to ibinc's fraglist
>
>   - - **if completed datagram:**
>
>       - update cong map if datagram was cong update
>
>       - call rds_recv_incoming() otherwise
>
>       - note if ack is required
>
> - **rds_recv_incoming()**
>
>   - drop duplicate packets
>
>   - respond to pings
>
>   - find the sock associated with this datagram
>
>   - add to sock queue
>
>   - wake up sock
>
>   - do some congestion calculations
>
> - **rds_recvmsg**
>
>   - copy data into user iovec
>
>   - handle CMSGs
>
>   - return to application

<a id="rst-multipath-rds-mprds"></a>

## Multipath RDS (mprds)

> Mprds is multipathed-RDS, primarily intended for RDS-over-TCP (though the concept can be extended to other transports). The classical implementation of RDS-over-TCP is implemented by demultiplexing multiple PF_RDS sockets between any 2 endpoints (where endpoint == \[IP address, port\]) over a single TCP socket between the 2 IP addresses involved. This has the limitation that it ends up funneling multiple RDS flows over a single TCP flow, thus it is (a) upper-bounded to the single-flow bandwidth, (b) suffers from head-of-line blocking for all the RDS sockets.
>
> Better throughput (for a fixed small packet size, MTU) can be achieved by having multiple TCP/IP flows per rds/tcp connection, i.e., multipathed RDS (mprds).  Each such TCP/IP flow constitutes a path for the rds/tcp connection. RDS sockets will be attached to a path based on some hash (e.g., of local address and RDS port number) and packets for that RDS socket will be sent over the attached path using TCP to segment/reassemble RDS datagrams on that path.
>
> Multipathed RDS is implemented by splitting the struct rds_connection into a common (to all paths) part, and a per-path struct rds_conn_path. All I/O workqs and reconnect threads are driven from the rds_conn_path. Transports such as TCP that are multipath capable may then set up a TCP socket per rds_conn_path, and this is managed by the transport via the transport private cp_transport_data pointer.
>
> Transports announce themselves as multipath capable by setting the t_mp_capable bit during registration with the rds core module. When the transport is multipath-capable, rds_sendmsg() hashes outgoing traffic across multiple paths. The outgoing hash is computed based on the local address and port that the PF_RDS socket is bound to.
>
> Additionally, even if the transport is MP capable, we may be peering with some node that does not support mprds, or supports a different number of paths. As a result, the peering nodes need to agree on the number of paths to be used for the connection. This is done by sending out a control packet exchange before the first data packet. The control packet exchange must have completed prior to outgoing hash completion in rds_sendmsg() when the transport is multipath capable.
>
> The control packet is an RDS ping packet (i.e., packet to rds dest port 0) with the ping packet having a rds extension header option  of type RDS_EXTHDR_NPATHS, length 2 bytes, and the value is the number of paths supported by the sender. The "probe" ping packet will get sent from some reserved port, RDS_FLAG_PROBE_PORT (in &lt;linux/rds.h&gt;) The receiver of a ping from RDS_FLAG_PROBE_PORT will thus immediately be able to compute the min(sender_paths, rcvr_paths). The pong sent in response to a probe-ping should contain the rcvr's npaths when the rcvr is mprds-capable.
>
> If the rcvr is not mprds-capable, the exthdr in the ping will be ignored.  In this case the pong will not have any exthdrs, so the sender of the probe-ping can default to single-path mprds.

---

# Linux wireless regulatory documentation

_Peios Kernel / Internals / Networking_

> This document gives a brief review over how the Linux wireless regulatory infrastructure works.

<a id="rst-linux-wireless-regulatory-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document gives a brief review over how the Linux wireless regulatory infrastructure works.

More up to date information can be obtained at the project's web page:

[https://wireless.wiki.kernel.org/en/developers/Regulatory](<https://wireless.wiki.kernel.org/en/developers/Regulatory>)

<a id="rst-keeping-regulatory-domains-in-userspace"></a>

## Keeping regulatory domains in userspace

Due to the dynamic nature of regulatory domains we keep them in userspace and provide a framework for userspace to upload to the kernel one regulatory domain to be used as the central core regulatory domain all wireless devices should adhere to.

<a id="rst-how-to-get-regulatory-domains-to-the-kernel"></a>

## How to get regulatory domains to the kernel

When the regulatory domain is first set up, the kernel will request a database file (regulatory.db) containing all the regulatory rules. It will then use that database when it needs to look up the rules for a given country.

<a id="rst-how-to-get-regulatory-domains-to-the-kernel-old-crda-solution"></a>

## How to get regulatory domains to the kernel (old CRDA solution)

Userspace gets a regulatory domain in the kernel by having a userspace agent build it and send it via nl80211. Only expected regulatory domains will be respected by the kernel.

A currently available userspace agent which can accomplish this is CRDA - central regulatory domain agent. Its documented here:

[https://wireless.wiki.kernel.org/en/developers/Regulatory/CRDA](<https://wireless.wiki.kernel.org/en/developers/Regulatory/CRDA>)

Essentially the kernel will send a udev event when it knows it needs a new regulatory domain. A udev rule can be put in place to trigger crda to send the respective regulatory domain for a specific ISO/IEC 3166 alpha2.

Below is an example udev rule which can be used:

\# Example file, should be put in /etc/udev/rules.d/regulatory.rules KERNEL=="regulatory\*", ACTION=="change", SUBSYSTEM=="platform", RUN+="/sbin/crda"

The alpha2 is passed as an environment variable under the variable COUNTRY.

<a id="rst-who-asks-for-regulatory-domains"></a>

## Who asks for regulatory domains?

- Users

Users can use iw:

[https://wireless.wiki.kernel.org/en/users/Documentation/iw](<https://wireless.wiki.kernel.org/en/users/Documentation/iw>)

An example:



```text
# set regulatory domain to "Costa Rica"
iw reg set CR
```

This will request the kernel to set the regulatory domain to the specified alpha2. The kernel in turn will then ask userspace to provide a regulatory domain for the alpha2 specified by the user by sending a uevent.

- Wireless subsystems for Country Information elements

The kernel will send a uevent to inform userspace a new regulatory domain is required. More on this to be added as its integration is added.

- Drivers

If drivers determine they need a specific regulatory domain set they can inform the wireless core using regulatory_hint(). They have two options -- they either provide an alpha2 so that crda can provide back a regulatory domain for that country or they can build their own regulatory domain based on internal custom knowledge so the wireless core can respect it.

*Most* drivers will rely on the first mechanism of providing a regulatory hint with an alpha2. For these drivers there is an additional check that can be used to ensure compliance based on custom EEPROM regulatory data. This additional check can be used by drivers by registering on its struct wiphy a reg_notifier() callback. This notifier is called when the core's regulatory domain has been changed. The driver can use this to review the changes made and also review who made them (driver, user, country IE) and determine what to allow based on its internal EEPROM data. Devices drivers wishing to be capable of world roaming should use this callback. More on world roaming will be added to this document when its support is enabled.

Device drivers who provide their own built regulatory domain do not need a callback as the channels registered by them are the only ones that will be allowed and therefore *additional* channels cannot be enabled.

<a id="rst-example-code-drivers-hinting-an-alpha2"></a>

## Example code - drivers hinting an alpha2:

This example comes from the zd1211rw device driver. You can start by having a mapping of your device's EEPROM country/regulatory domain value to a specific alpha2 as follows:



```text
static struct zd_reg_alpha2_map reg_alpha2_map[] = {
      { ZD_REGDOMAIN_FCC, "US" },
      { ZD_REGDOMAIN_IC, "CA" },
      { ZD_REGDOMAIN_ETSI, "DE" }, /* Generic ETSI, use most restrictive */
      { ZD_REGDOMAIN_JAPAN, "JP" },
      { ZD_REGDOMAIN_JAPAN_ADD, "JP" },
      { ZD_REGDOMAIN_SPAIN, "ES" },
      { ZD_REGDOMAIN_FRANCE, "FR" },
```

Then you can define a routine to map your read EEPROM value to an alpha2, as follows:



```text
static int zd_reg2alpha2(u8 regdomain, char *alpha2)
{
      unsigned int i;
      struct zd_reg_alpha2_map *reg_map;
              for (i = 0; i < ARRAY_SIZE(reg_alpha2_map); i++) {
                      reg_map = &reg_alpha2_map[i];
                      if (regdomain == reg_map->reg) {
                      alpha2[0] = reg_map->alpha2[0];
                      alpha2[1] = reg_map->alpha2[1];
                      return 0;
              }
      }
      return 1;
}
```

Lastly, you can then hint to the core of your discovered alpha2, if a match was found. You need to do this after you have registered your wiphy. You are expected to do this during initialization.



```text
r = zd_reg2alpha2(mac->regdomain, alpha2);
if (!r)
        regulatory_hint(hw->wiphy, alpha2);
```

<a id="rst-example-code-drivers-providing-a-built-in-regulatory-domain"></a>

## Example code - drivers providing a built in regulatory domain:

\[NOTE: This API is not currently available, it can be added when required\]

If you have regulatory information you can obtain from your driver and you *need* to use this we let you build a regulatory domain structure and pass it to the wireless core. To do this you should kmalloc() a structure big enough to hold your regulatory domain structure and you should then fill it with your data. Finally you simply call regulatory_hint() with the regulatory domain structure in it.

Below is a simple example, with a regulatory domain cached using the stack. Your implementation may vary (read EEPROM cache instead, for example).

Example cache of some regulatory domain:



```text
struct ieee80211_regdomain mydriver_jp_regdom = {
      .n_reg_rules = 3,
      .alpha2 =  "JP",
      //.alpha2 =  "99", /* If I have no alpha2 to map it to */
      .reg_rules = {
              /* IEEE 802.11b/g, channels 1..14 */
              REG_RULE(2412-10, 2484+10, 40, 6, 20, 0),
              /* IEEE 802.11a, channels 34..48 */
              REG_RULE(5170-10, 5240+10, 40, 6, 20,
                      NL80211_RRF_NO_IR),
              /* IEEE 802.11a, channels 52..64 */
              REG_RULE(5260-10, 5320+10, 40, 6, 20,
                      NL80211_RRF_NO_IR|
                      NL80211_RRF_DFS),
      }
};
```

Then in some part of your code after your wiphy has been registered:



```text
struct ieee80211_regdomain *rd;
int size_of_regd;
int num_rules = mydriver_jp_regdom.n_reg_rules;
unsigned int i;

size_of_regd = sizeof(struct ieee80211_regdomain) +
        (num_rules * sizeof(struct ieee80211_reg_rule));

rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd)
        return -ENOMEM;

memcpy(rd, &mydriver_jp_regdom, sizeof(struct ieee80211_regdomain));

for (i=0; i < num_rules; i++)
        memcpy(&rd->reg_rules[i],
               &mydriver_jp_regdom.reg_rules[i],
               sizeof(struct ieee80211_reg_rule));
regulatory_struct_hint(rd);
```

<a id="rst-statically-compiled-regulatory-database"></a>

## Statically compiled regulatory database

When a database should be fixed into the kernel, it can be provided as a firmware file at build time that is then linked into the kernel.

---

# Network Function Representors

_Peios Kernel / Internals / Networking_

> This document describes the semantics and usage of representor netdevices, as used to control internal switching on SmartNICs. For the closely-related port representors on physical (multi-port) switches, see…

<a id="rst-network-function-representors"></a>
<a id="rst-representors"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the semantics and usage of representor netdevices, as used to control internal switching on SmartNICs.  For the closely-related port representors on physical (multi-port) switches, see [Documentation/networking/switchdev.rst](</kernel/internals/networking/switchdev.md#rst-switchdev>).

<a id="rst-motivation"></a>

## Motivation

Since the mid-2010s, network cards have started offering more complex virtualisation capabilities than the legacy SR-IOV approach (with its simple MAC/VLAN-based switching model) can support.  This led to a desire to offload software-defined networks (such as OpenVSwitch) to these NICs to specify the network connectivity of each function.  The resulting designs are variously called SmartNICs or DPUs.

Network function representors bring the standard Linux networking stack to virtual switches and IOV devices.  Just as each physical port of a Linux- controlled switch has a separate netdev, so does each virtual port of a virtual switch. When the system boots, and before any offload is configured, all packets from the virtual functions appear in the networking stack of the PF via the representors.  The PF can thus always communicate freely with the virtual functions. The PF can configure standard Linux forwarding between representors, the uplink or any other netdev (routing, bridging, TC classifiers).

Thus, a representor is both a control plane object (representing the function in administrative commands) and a data plane object (one end of a virtual pipe). As a virtual link endpoint, the representor can be configured like any other netdevice; in some cases (e.g. link state) the representee will follow the representor's configuration, while in others there are separate APIs to configure the representee.

<a id="rst-definitions"></a>

## Definitions

This document uses the term "switchdev function" to refer to the PCIe function which has administrative control over the virtual switch on the device. Typically, this will be a PF, but conceivably a NIC could be configured to grant these administrative privileges instead to a VF or SF (subfunction). Depending on NIC design, a multi-port NIC might have a single switchdev function for the whole device or might have a separate virtual switch, and hence switchdev function, for each physical network port. If the NIC supports nested switching, there might be separate switchdev functions for each nested switch, in which case each switchdev function should only create representors for the ports on the (sub-)switch it directly administers.

A "representee" is the object that a representor represents.  So for example in the case of a VF representor, the representee is the corresponding VF.

<a id="rst-what-does-a-representor-do"></a>

## What does a representor do?

A representor has three main roles.

1. It is used to configure the network connection the representee sees, e.g. link up/down, MTU, etc.  For instance, bringing the representor administratively UP should cause the representee to see a link up / carrier on event.

2. It provides the slow path for traffic which does not hit any offloaded fast-path rules in the virtual switch.  Packets transmitted on the representor netdevice should be delivered to the representee; packets transmitted by the representee which fail to match any switching rule should be received on the representor netdevice.  (That is, there is a virtual pipe connecting the representor to the representee, similar in concept to a veth pair.) This allows software switch implementations (such as OpenVSwitch or a Linux bridge) to forward packets between representees and the rest of the network.

3. It acts as a handle by which switching rules (such as TC filters) can refer to the representee, allowing these rules to be offloaded.

The combination of 2) and 3) means that the behaviour (apart from performance) should be the same whether a TC filter is offloaded or not.  E.g. a TC rule on a VF representor applies in software to packets received on that representor netdevice, while in hardware offload it would apply to packets transmitted by the representee VF.  Conversely, a mirred egress redirect to a VF representor corresponds in hardware to delivery directly to the representee VF.

<a id="rst-what-functions-should-have-a-representor"></a>

## What functions should have a representor?

Essentially, for each virtual port on the device's internal switch, there should be a representor. Some vendors have chosen to omit representors for the uplink and the physical network port, which can simplify usage (the uplink netdev becomes in effect the physical port's representor) but does not generalise to devices with multiple ports or uplinks.

Thus, the following should all have representors:

> - VFs belonging to the switchdev function.
>
> - Other PFs on the local PCIe controller, and any VFs belonging to them.
>
> - PFs and VFs on external PCIe controllers on the device (e.g. for any embedded System-on-Chip within the SmartNIC).
>
> - PFs and VFs with other personalities, including network block devices (such as a vDPA virtio-blk PF backed by remote/distributed storage), if (and only if) their network access is implemented through a virtual switch port. <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1) Note that such functions can require a representor despite the representee not having a netdev.
>
> - Subfunctions (SFs) belonging to any of the above PFs or VFs, if they have their own port on the switch (as opposed to using their parent PF's port).
>
> - Any accelerators or plugins on the device whose interface to the network is through a virtual switch port, even if they do not have a corresponding PCIe PF or VF.

This allows the entire switching behaviour of the NIC to be controlled through representor TC rules.

It is a common misunderstanding to conflate virtual ports with PCIe virtual functions or their netdevs.  While in simple cases there will be a 1:1 correspondence between VF netdevices and VF representors, more advanced device configurations may not follow this. A PCIe function which does not have network access through the internal switch (not even indirectly through the hardware implementation of whatever services the function provides) should *not* have a representor (even if it has a netdev). Such a function has no switch virtual port for the representor to configure or to be the other end of the virtual pipe. The representor represents the virtual port, not the PCIe function nor the 'end user' netdevice.

<a id="rst-footnote-1"></a>



**[1]** The concept here is that a hardware IP stack in the device performs the translation between block DMA requests and network packets, so that only network packets pass through the virtual port onto the switch.  The network access that the IP stack "sees" would then be configurable through tc rules; e.g. its traffic might all be wrapped in a specific VLAN or VxLAN.  However, any needed configuration of the block device *qua* block device, not being a networking entity, would not be appropriate for the representor and would thus use some other channel such as devlink. Contrast this with the case of a virtio-blk implementation which forwards the DMA requests unchanged to another PF whose driver then initiates and terminates IP traffic in software; in that case the DMA traffic would *not* run over the virtual switch and the virtio-blk PF should thus *not* have a representor.

<a id="rst-how-are-representors-created"></a>

## How are representors created?

The driver instance attached to the switchdev function should, for each virtual port on the switch, create a pure-software netdevice which has some form of in-kernel reference to the switchdev function's own netdevice or driver private data (`netdev_priv()`). This may be by enumerating ports at probe time, reacting dynamically to the creation and destruction of ports at run time, or a combination of the two.

The operations of the representor netdevice will generally involve acting through the switchdev function.  For example, `ndo_start_xmit()` might send the packet through a hardware TX queue attached to the switchdev function, with either packet metadata or queue configuration marking it for delivery to the representee.

<a id="rst-how-are-representors-identified"></a>

## How are representors identified?

The representor netdevice should *not* directly refer to a PCIe device (e.g. through `net_dev->dev.parent` / `SET_NETDEV_DEV()`), either of the representee or of the switchdev function. Instead, the driver should use the `SET_NETDEV_DEVLINK_PORT` macro to assign a devlink port instance to the netdevice before registering the netdevice; the kernel uses the devlink port to provide the `phys_switch_id` and `phys_port_name` sysfs nodes. (Some legacy drivers implement `ndo_get_port_parent_id()` and `ndo_get_phys_port_name()` directly, but this is deprecated.)  See [Documentation/networking/devlink/devlink-port.rst](</kernel/internals/networking/devlink/devlink-port.md#rst-devlink-port>) for the details of this API.

It is expected that userland will use this information (e.g. through udev rules) to construct an appropriately informative name or alias for the netdevice.  For instance if the switchdev function is `eth4` then a representor with a `phys_port_name` of `p0pf1vf2` might be renamed `eth4pf1vf2rep`.

There are as yet no established conventions for naming representors which do not correspond to PCIe functions (e.g. accelerators and plugins).

<a id="rst-how-do-representors-interact-with-tc-rules"></a>

## How do representors interact with TC rules?

Any TC rule on a representor applies (in software TC) to packets received by that representor netdevice.  Thus, if the delivery part of the rule corresponds to another port on the virtual switch, the driver may choose to offload it to hardware, applying it to packets transmitted by the representee.

Similarly, since a TC mirred egress action targeting the representor would (in software) send the packet through the representor (and thus indirectly deliver it to the representee), hardware offload should interpret this as delivery to the representee.

As a simple example, if `PORT_DEV` is the physical port representor and `REP_DEV` is a VF representor, the following rules:



```text
tc filter add dev $REP_DEV parent ffff: protocol ipv4 flower \
    action mirred egress redirect dev $PORT_DEV
tc filter add dev $PORT_DEV parent ffff: protocol ipv4 flower skip_sw \
    action mirred egress mirror dev $REP_DEV
```

would mean that all IPv4 packets from the VF are sent out the physical port, and all IPv4 packets received on the physical port are delivered to the VF in addition to `PORT_DEV`.  (Note that without `skip_sw` on the second rule, the VF would get two copies, as the packet reception on `PORT_DEV` would trigger the TC rule again and mirror the packet to `REP_DEV`.)

On devices without separate port and uplink representors, `PORT_DEV` would instead be the switchdev function's own uplink netdevice.

Of course the rules can (if supported by the NIC) include packet-modifying actions (e.g. VLAN push/pop), which should be performed by the virtual switch.

Tunnel encapsulation and decapsulation are rather more complicated, as they involve a third netdevice (a tunnel netdev operating in metadata mode, such as a VxLAN device created with `ip link add vxlan0 type vxlan external`) and require an IP address to be bound to the underlay device (e.g. switchdev function uplink netdev or port representor).  TC rules such as:



```text
tc filter add dev $REP_DEV parent ffff: flower \
    action tunnel_key set id $VNI src_ip $LOCAL_IP dst_ip $REMOTE_IP \
                          dst_port 4789 \
    action mirred egress redirect dev vxlan0
tc filter add dev vxlan0 parent ffff: flower enc_src_ip $REMOTE_IP \
    enc_dst_ip $LOCAL_IP enc_key_id $VNI enc_dst_port 4789 \
    action tunnel_key unset action mirred egress redirect dev $REP_DEV
```

where `LOCAL_IP` is an IP address bound to `PORT_DEV`, and `REMOTE_IP` is another IP address on the same subnet, mean that packets sent by the VF should be VxLAN encapsulated and sent out the physical port (the driver has to deduce this by a route lookup of `LOCAL_IP` leading to `PORT_DEV`, and also perform an ARP/neighbour table lookup to find the MAC addresses to use in the outer Ethernet frame), while UDP packets received on the physical port with UDP port 4789 should be parsed as VxLAN and, if their VSID matches `$VNI`, decapsulated and forwarded to the VF.

If this all seems complicated, just remember the 'golden rule' of TC offload: the hardware should ensure the same final results as if the packets were processed through the slow path, traversed software TC (except ignoring any `skip_hw` rules and applying any `skip_sw` rules) and were transmitted or received through the representor netdevices.

<a id="rst-configuring-the-representee-s-mac"></a>

## Configuring the representee's MAC

The representee's link state is controlled through the representor.  Setting the representor administratively UP or DOWN should cause carrier ON or OFF at the representee.

Setting an MTU on the representor should cause that same MTU to be reported to the representee. (On hardware that allows configuring separate and distinct MTU and MRU values, the representor MTU should correspond to the representee's MRU and vice-versa.)

Currently there is no way to use the representor to set the station permanent MAC address of the representee; other methods available to do this include:

> - legacy SR-IOV (`ip link set DEVICE vf NUM mac LLADDR`)
>
> - devlink port function (see **devlink-port(8)** and [Documentation/networking/devlink/devlink-port.rst](</kernel/internals/networking/devlink/devlink-port.md#rst-devlink-port>))

---

# RxRPC Network Protocol

_Peios Kernel / Internals / Networking_

> The RxRPC protocol driver provides a reliable two-phase transport on top of UDP that can be used to perform RxRPC remote operations. This is done over sockets of AF_RXRPC family, using sendmsg() and recvmsg() with control data to send and…

<a id="rst-rxrpc-network-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The RxRPC protocol driver provides a reliable two-phase transport on top of UDP that can be used to perform RxRPC remote operations.  This is done over sockets of AF_RXRPC family, using sendmsg() and recvmsg() with control data to send and receive data, aborts and errors.

Contents of this document:

> 1. Overview.
>
> 2. RxRPC protocol summary.
>
> 3. AF_RXRPC driver model.
>
> 4. Control messages.
>
> 5. Socket options.
>
> 6. Security.
>
> 7. Example client usage.
>
> 8. Example server usage.
>
> 9. AF_RXRPC kernel interface.
>
> 10. Configurable parameters.

<a id="rst-overview"></a>

## Overview

RxRPC is a two-layer protocol.  There is a session layer which provides reliable virtual connections using UDP over IPv4 (or IPv6) as the transport layer, but implements a real network protocol; and there's the presentation layer which renders structured data to binary blobs and back again using XDR (as does SunRPC):



```text
+-------------+
| Application |
+-------------+
|     XDR     |         Presentation
+-------------+
|    RxRPC    |         Session
+-------------+
|     UDP     |         Transport
+-------------+
```

AF_RXRPC provides:

> 1. Part of an RxRPC facility for both kernel and userspace applications by making the session part of it a Linux network protocol (AF_RXRPC).
>
> 2. A two-phase protocol.  The client transmits a blob (the request) and then receives a blob (the reply), and the server receives the request and then transmits the reply.
>
> 3. Retention of the reusable bits of the transport system set up for one call to speed up subsequent calls.
>
> 4. A secure protocol, using the Linux kernel's key retention facility to manage security on the client end.  The server end must of necessity be more active in security negotiations.

AF_RXRPC does not provide XDR marshalling/presentation facilities.  That is left to the application.  AF_RXRPC only deals in blobs.  Even the operation ID is just the first four bytes of the request blob, and as such is beyond the kernel's interest.

Sockets of AF_RXRPC family are:

> 1. created as type SOCK_DGRAM;
>
> 2. provided with a protocol of the type of underlying transport they're going to use - currently only PF_INET is supported.

The Andrew File System (AFS) is an example of an application that uses this and that has both kernel (filesystem) and userspace (utility) components.

<a id="rst-rxrpc-protocol-summary"></a>

## RxRPC Protocol Summary

An overview of the RxRPC protocol:

> 1. RxRPC sits on top of another networking protocol (UDP is the only option currently), and uses this to provide network transport.  UDP ports, for example, provide transport endpoints.
>
> 2. RxRPC supports multiple virtual "connections" from any given transport endpoint, thus allowing the endpoints to be shared, even to the same remote endpoint.
>
> 3. Each connection goes to a particular "service".  A connection may not go to multiple services.  A service may be considered the RxRPC equivalent of a port number.  AF_RXRPC permits multiple services to share an endpoint.
>
> 4. Client-originating packets are marked, thus a transport endpoint can be shared between client and server connections (connections have a direction).
>
> 5. Up to a billion connections may be supported concurrently between one local transport endpoint and one service on one remote endpoint.  An RxRPC connection is described by seven numbers:
>
>
>
>    ```text
>    Local address   }
>    Local port      } Transport (UDP) address
>    Remote address  }
>    Remote port     }
>    Direction
>    Connection ID
>    Service ID
>    ```
>
> 6. Each RxRPC operation is a "call".  A connection may make up to four billion calls, but only up to four calls may be in progress on a connection at any one time.
>
> 7. Calls are two-phase and asymmetric: the client sends its request data, which the service receives; then the service transmits the reply data which the client receives.
>
> 8. The data blobs are of indefinite size, the end of a phase is marked with a flag in the packet.  The number of packets of data making up one blob may not exceed 4 billion, however, as this would cause the sequence number to wrap.
>
> 9. The first four bytes of the request data are the service operation ID.
>
> 10. Security is negotiated on a per-connection basis.  The connection is initiated by the first data packet on it arriving.  If security is requested, the server then issues a "challenge" and then the client replies with a "response".  If the response is successful, the security is set for the lifetime of that connection, and all subsequent calls made upon it use that same security.  In the event that the server lets a connection lapse before the client, the security will be renegotiated if the client uses the connection again.
>
> 11. Calls use ACK packets to handle reliability.  Data packets are also explicitly sequenced per call.
>
> 12. There are two types of positive acknowledgment: hard-ACKs and soft-ACKs. A hard-ACK indicates to the far side that all the data received to a point has been received and processed; a soft-ACK indicates that the data has been received but may yet be discarded and re-requested.  The sender may not discard any transmittable packets until they've been hard-ACK'd.
>
> 13. Reception of a reply data packet implicitly hard-ACK's all the data packets that make up the request.
>
> 14. An call is complete when the request has been sent, the reply has been received and the final hard-ACK on the last packet of the reply has reached the server.
>
> 15. An call may be aborted by either end at any time up to its completion.

<a id="rst-af-rxrpc-driver-model"></a>

## AF_RXRPC Driver Model

About the AF_RXRPC driver:

> 1. The AF_RXRPC protocol transparently uses internal sockets of the transport protocol to represent transport endpoints.
>
> 2. AF_RXRPC sockets map onto RxRPC connection bundles.  Actual RxRPC connections are handled transparently.  One client socket may be used to make multiple simultaneous calls to the same service.  One server socket may handle calls from many clients.
>
> 3. Additional parallel client connections will be initiated to support extra concurrent calls, up to a tunable limit.
>
> 4. Each connection is retained for a certain amount of time \[tunable\] after the last call currently using it has completed in case a new call is made that could reuse it.
>
> 5. Each internal UDP socket is retained \[tunable\] for a certain amount of time \[tunable\] after the last connection using it discarded, in case a new connection is made that could use it.
>
> 6. A client-side connection is only shared between calls if they have the same key struct describing their security (and assuming the calls would otherwise share the connection).  Non-secured calls would also be able to share connections with each other.
>
> 7. A server-side connection is shared if the client says it is.
>
> 8. ACK'ing is handled by the protocol driver automatically, including ping replying.
>
> 9. SO_KEEPALIVE automatically pings the other side to keep the connection alive \[TODO\].
>
> 10. If an ICMP error is received, all calls affected by that error will be aborted with an appropriate network error passed through recvmsg().

Interaction with the user of the RxRPC socket:

> 1. A socket is made into a server socket by binding an address with a non-zero service ID.
>
> 2. In the client, sending a request is achieved with one or more sendmsgs, followed by the reply being received with one or more recvmsgs.
>
> 3. The first sendmsg for a request to be sent from a client contains a tag to be used in all other sendmsgs or recvmsgs associated with that call.  The tag is carried in the control data.
>
> 4. connect() is used to supply a default destination address for a client socket.  This may be overridden by supplying an alternate address to the first sendmsg() of a call (struct msghdr::msg_name).
>
> 5. If connect() is called on an unbound client, a random local port will bound before the operation takes place.
>
> 6. A server socket may also be used to make client calls.  To do this, the first sendmsg() of the call must specify the target address.  The server's transport endpoint is used to send the packets.
>
> 7. Once the application has received the last message associated with a call, the tag is guaranteed not to be seen again, and so it can be used to pin client resources.  A new call can then be initiated with the same tag without fear of interference.
>
> 8. In the server, a request is received with one or more recvmsgs, then the the reply is transmitted with one or more sendmsgs, and then the final ACK is received with a last recvmsg.
>
> 9. When sending data for a call, sendmsg is given MSG_MORE if there's more data to come on that call.
>
> 10. When receiving data for a call, recvmsg flags MSG_MORE if there's more data to come for that call.
>
> 11. When receiving data or messages for a call, MSG_EOR is flagged by recvmsg to indicate the terminal message for that call.
>
> 12. A call may be aborted by adding an abort control message to the control data.  Issuing an abort terminates the kernel's use of that call's tag. Any messages waiting in the receive queue for that call will be discarded.
>
> 13. Aborts, busy notifications and challenge packets are delivered by recvmsg, and control data messages will be set to indicate the context.  Receiving an abort or a busy message terminates the kernel's use of that call's tag.
>
> 14. The control data part of the msghdr struct is used for a number of things:
>
>     1. The tag of the intended or affected call.
>
>     2. Sending or receiving errors, aborts and busy notifications.
>
>     3. Notifications of incoming calls.
>
>     4. Sending debug requests and receiving debug replies \[TODO\].
>
> 15. When the kernel has received and set up an incoming call, it sends a message to server application to let it know there's a new call awaiting its acceptance \[recvmsg reports a special control message\].  The server application then uses sendmsg to assign a tag to the new call.  Once that is done, the first part of the request data will be delivered by recvmsg.
>
> 16. The server application has to provide the server socket with a keyring of secret keys corresponding to the security types it permits.  When a secure connection is being set up, the kernel looks up the appropriate secret key in the keyring and then sends a challenge packet to the client and receives a response packet.  The kernel then checks the authorisation of the packet and either aborts the connection or sets up the security.
>
> 17. The name of the key a client will use to secure its communications is nominated by a socket option.

Notes on sendmsg:

> 1. MSG_WAITALL can be set to tell sendmsg to ignore signals if the peer is making progress at accepting packets within a reasonable time such that we manage to queue up all the data for transmission.  This requires the client to accept at least one packet per 2\*RTT time period.
>
>    If this isn't set, sendmsg() will return immediately, either returning EINTR/ERESTARTSYS if nothing was consumed or returning the amount of data consumed.

Notes on recvmsg:

> 1. If there's a sequence of data messages belonging to a particular call on the receive queue, then recvmsg will keep working through them until:
>
>    - **(a)** it meets the end of that call's received data,
>
>    - **(b)** it meets a non-data message,
>
>    - **(c)** it meets a message belonging to a different call, or
>
>    - **(d)** it fills the user buffer.
>
>    If recvmsg is called in blocking mode, it will keep sleeping, awaiting the reception of further data, until one of the above four conditions is met.
>
> 2. MSG_PEEK operates similarly, but will return immediately if it has put any data in the buffer rather than sleeping until it can fill the buffer.
>
> 3. If a data message is only partially consumed in filling a user buffer, then the remainder of that message will be left on the front of the queue for the next taker.  MSG_TRUNC will never be flagged.
>
> 4. If there is more data to be had on a call (it hasn't copied the last byte of the last data message in that phase yet), then MSG_MORE will be flagged.

<a id="rst-control-messages"></a>

## Control Messages

AF_RXRPC makes use of control messages in sendmsg() and recvmsg() to multiplex calls, to invoke certain actions and to report certain conditions.  These are:

> >
> > <table>
> > <thead>
> > <tr>
> > <th>
> >
> >
> > MESSAGE ID
> >
> > </th>
> > <th>
> >
> >
> > SRT
> >
> > </th>
> > <th>
> >
> >
> > DATA
> >
> > </th>
> > <th>
> >
> >
> > MEANING
> >
> > </th>
> > </tr>
> > </thead>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > RXRPC_USER_CALL_ID
> >
> > </td>
> > <td>
> >
> >
> > sr-
> >
> > </td>
> > <td>
> >
> >
> > User ID
> >
> > </td>
> > <td>
> >
> >
> > App's call specifier
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_ABORT
> >
> > </td>
> > <td>
> >
> >
> > srt
> >
> > </td>
> > <td>
> >
> >
> > Abort code
> >
> > </td>
> > <td>
> >
> >
> > Abort code to issue/received
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_ACK
> >
> > </td>
> > <td>
> >
> >
> > -rt
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > Final ACK received
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_NET_ERROR
> >
> > </td>
> > <td>
> >
> >
> > -rt
> >
> > </td>
> > <td>
> >
> >
> > error num
> >
> > </td>
> > <td>
> >
> >
> > Network error on call
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_BUSY
> >
> > </td>
> > <td>
> >
> >
> > -rt
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > Call rejected (server busy)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_LOCAL_ERROR
> >
> > </td>
> > <td>
> >
> >
> > -rt
> >
> > </td>
> > <td>
> >
> >
> > error num
> >
> > </td>
> > <td>
> >
> >
> > Local error encountered
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_NEW_CALL
> >
> > </td>
> > <td>
> >
> >
> > -r-
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > New call received
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_ACCEPT
> >
> > </td>
> > <td>
> >
> >
> > s--
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > Accept new call
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_EXCLUSIVE_CALL
> >
> > </td>
> > <td>
> >
> >
> > s--
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > Make an exclusive client call
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_UPGRADE_SERVICE
> >
> > </td>
> > <td>
> >
> >
> > s--
> >
> > </td>
> > <td>
> >
> >
> > n/a
> >
> > </td>
> > <td>
> >
> >
> > Client call can be upgraded
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > RXRPC_TX_LENGTH
> >
> > </td>
> > <td>
> >
> >
> > s--
> >
> > </td>
> > <td>
> >
> >
> > data len
> >
> > </td>
> > <td>
> >
> >
> > Total length of Tx data
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
> >
> > (SRT = usable in Sendmsg / delivered by Recvmsg / Terminal message)
>
> 1. RXRPC_USER_CALL_ID
>
>    This is used to indicate the application's call ID.  It's an unsigned long that the app specifies in the client by attaching it to the first data message or in the server by passing it in association with an RXRPC_ACCEPT message.  recvmsg() passes it in conjunction with all messages except those of the RXRPC_NEW_CALL message.
>
> 2. RXRPC_ABORT
>
>    This is can be used by an application to abort a call by passing it to sendmsg, or it can be delivered by recvmsg to indicate a remote abort was received.  Either way, it must be associated with an RXRPC_USER_CALL_ID to specify the call affected.  If an abort is being sent, then error EBADSLT will be returned if there is no call with that user ID.
>
> 3. RXRPC_ACK
>
>    This is delivered to a server application to indicate that the final ACK of a call was received from the client.  It will be associated with an RXRPC_USER_CALL_ID to indicate the call that's now complete.
>
> 4. RXRPC_NET_ERROR
>
>    This is delivered to an application to indicate that an ICMP error message was encountered in the process of trying to talk to the peer.  An errno-class integer value will be included in the control message data indicating the problem, and an RXRPC_USER_CALL_ID will indicate the call affected.
>
> 5. RXRPC_BUSY
>
>    This is delivered to a client application to indicate that a call was rejected by the server due to the server being busy.  It will be associated with an RXRPC_USER_CALL_ID to indicate the rejected call.
>
> 6. RXRPC_LOCAL_ERROR
>
>    This is delivered to an application to indicate that a local error was encountered and that a call has been aborted because of it.  An errno-class integer value will be included in the control message data indicating the problem, and an RXRPC_USER_CALL_ID will indicate the call affected.
>
> 7. RXRPC_NEW_CALL
>
>    This is delivered to indicate to a server application that a new call has arrived and is awaiting acceptance.  No user ID is associated with this, as a user ID must subsequently be assigned by doing an RXRPC_ACCEPT.
>
> 8. RXRPC_ACCEPT
>
>    This is used by a server application to attempt to accept a call and assign it a user ID.  It should be associated with an RXRPC_USER_CALL_ID to indicate the user ID to be assigned.  If there is no call to be accepted (it may have timed out, been aborted, etc.), then sendmsg will return error ENODATA.  If the user ID is already in use by another call, then error EBADSLT will be returned.
>
> 9. RXRPC_EXCLUSIVE_CALL
>
>    This is used to indicate that a client call should be made on a one-off connection.  The connection is discarded once the call has terminated.
>
> 10. RXRPC_UPGRADE_SERVICE
>
>     This is used to make a client call to probe if the specified service ID may be upgraded by the server.  The caller must check msg_name returned to recvmsg() for the service ID actually in use.  The operation probed must be one that takes the same arguments in both services.
>
>     Once this has been used to establish the upgrade capability (or lack thereof) of the server, the service ID returned should be used for all future communication to that server and RXRPC_UPGRADE_SERVICE should no longer be set.
>
> 11. RXRPC_TX_LENGTH
>
>     This is used to inform the kernel of the total amount of data that is going to be transmitted by a call (whether in a client request or a service response).  If given, it allows the kernel to encrypt from the userspace buffer directly to the packet buffers, rather than copying into the buffer and then encrypting in place.  This may only be given with the first sendmsg() providing data for a call.  EMSGSIZE will be generated if the amount of data actually given is different.
>
>     This takes a parameter of \__s64 type that indicates how much will be transmitted.  This may not be less than zero.

The symbol RXRPC__SUPPORTED is defined as one more than the highest control message type supported.  At run time this can be queried by means of the RXRPC_SUPPORTED_CMSG socket option (see below).

<a id="rst-socket-options"></a>

## Socket Options

AF_RXRPC sockets support a few socket options at the SOL_RXRPC level:

> 1. RXRPC_SECURITY_KEY
>
>    This is used to specify the description of the key to be used.  The key is extracted from the calling process's keyrings with request_key() and should be of "rxrpc" type.
>
>    The optval pointer points to the description string, and optlen indicates how long the string is, without the NUL terminator.
>
> 2. RXRPC_SECURITY_KEYRING
>
>    Similar to above but specifies a keyring of server secret keys to use (key type "keyring").  See the "Security" section.
>
> 3. RXRPC_EXCLUSIVE_CONNECTION
>
>    This is used to request that new connections should be used for each call made subsequently on this socket.  optval should be NULL and optlen 0.
>
> 4. RXRPC_MIN_SECURITY_LEVEL
>
>    This is used to specify the minimum security level required for calls on this socket.  optval must point to an int containing one of the following values:
>
>    - **(a)** RXRPC_SECURITY_PLAIN
>
>      Encrypted checksum only.
>
>    - **(b)** RXRPC_SECURITY_AUTH
>
>      Encrypted checksum plus packet padded and first eight bytes of packet encrypted - which includes the actual packet length.
>
>    - **(c)** RXRPC_SECURITY_ENCRYPT
>
>      Encrypted checksum plus entire packet padded and encrypted, including actual packet length.
>
> 5. RXRPC_UPGRADEABLE_SERVICE
>
>    This is used to indicate that a service socket with two bindings may upgrade one bound service to the other if requested by the client.  optval must point to an array of two unsigned short ints.  The first is the service ID to upgrade from and the second the service ID to upgrade to.
>
> 6. RXRPC_SUPPORTED_CMSG
>
>    This is a read-only option that writes an int into the buffer indicating the highest control message type supported.

<a id="rst-security"></a>

## Security

Currently, only the kerberos 4 equivalent protocol has been implemented (security index 2 - rxkad).  This requires the rxkad module to be loaded and, on the client, tickets of the appropriate type to be obtained from the AFS kaserver or the kerberos server and installed as "rxrpc" type keys.  This is normally done using the klog program.  An example simple klog program can be found at:

> [http://people.redhat.com/\~dhowells/rxrpc/klog.c](<http://people.redhat.com/~dhowells/rxrpc/klog.c>)

The payload provided to add_key() on the client should be of the following form:



```text
struct rxrpc_key_sec2_v1 {
        uint16_t        security_index; /* 2 */
        uint16_t        ticket_length;  /* length of ticket[] */
        uint32_t        expiry;         /* time at which expires */
        uint8_t         kvno;           /* key version number */
        uint8_t         __pad[3];
        uint8_t         session_key[8]; /* DES session key */
        uint8_t         ticket[0];      /* the encrypted ticket */
};
```

Where the ticket blob is just appended to the above structure.

For the server, keys of type "rxrpc_s" must be made available to the server. They have a description of "&lt;serviceID&gt;:&lt;securityIndex&gt;" (eg: "52:2" for an rxkad key for the AFS VL service).  When such a key is created, it should be given the server's secret key as the instantiation data (see the example below).

> add_key("rxrpc_s", "52:2", secret_key, 8, keyring);

A keyring is passed to the server socket by naming it in a sockopt.  The server socket then looks the server secret keys up in this keyring when secure incoming connections are made.  This can be seen in an example program that can be found at:

> [http://people.redhat.com/\~dhowells/rxrpc/listen.c](<http://people.redhat.com/~dhowells/rxrpc/listen.c>)

<a id="rst-example-client-usage"></a>

## Example Client Usage

A client would issue an operation by:

> 1. An RxRPC socket is set up by:
>
>
>
>    ```text
>    client = socket(AF_RXRPC, SOCK_DGRAM, PF_INET);
>    ```
>
>    Where the third parameter indicates the protocol family of the transport socket used - usually IPv4 but it can also be IPv6 \[TODO\].
>
> 2. A local address can optionally be bound:
>
>
>
>    ```text
>    struct sockaddr_rxrpc srx = {
>            .srx_family     = AF_RXRPC,
>            .srx_service    = 0,  /* we're a client */
>            .transport_type = SOCK_DGRAM,   /* type of transport socket */
>            .transport.sin_family   = AF_INET,
>            .transport.sin_port     = htons(7000), /* AFS callback */
>            .transport.sin_address  = 0,  /* all local interfaces */
>    };
>    bind(client, &srx, sizeof(srx));
>    ```
>
>    This specifies the local UDP port to be used.  If not given, a random non-privileged port will be used.  A UDP port may be shared between several unrelated RxRPC sockets.  Security is handled on a basis of per-RxRPC virtual connection.
>
> 3. The security is set:
>
>
>
>    ```text
>    const char *key = "AFS:cambridge.redhat.com";
>    setsockopt(client, SOL_RXRPC, RXRPC_SECURITY_KEY, key, strlen(key));
>    ```
>
>    This issues a request_key() to get the key representing the security context.  The minimum security level can be set:
>
>
>
>    ```text
>    unsigned int sec = RXRPC_SECURITY_ENCRYPT;
>    setsockopt(client, SOL_RXRPC, RXRPC_MIN_SECURITY_LEVEL,
>               &sec, sizeof(sec));
>    ```
>
> 4. The server to be contacted can then be specified (alternatively this can be done through sendmsg):
>
>
>
>    ```text
>    struct sockaddr_rxrpc srx = {
>            .srx_family     = AF_RXRPC,
>            .srx_service    = VL_SERVICE_ID,
>            .transport_type = SOCK_DGRAM,   /* type of transport socket */
>            .transport.sin_family   = AF_INET,
>            .transport.sin_port     = htons(7005), /* AFS volume manager */
>            .transport.sin_address  = ...,
>    };
>    connect(client, &srx, sizeof(srx));
>    ```
>
> 5. The request data should then be posted to the server socket using a series of sendmsg() calls, each with the following control message attached:
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_USER_CALL_ID
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > specifies the user ID for this call
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    MSG_MORE should be set in msghdr::msg_flags on all but the last part of the request.  Multiple requests may be made simultaneously.
>
>    An RXRPC_TX_LENGTH control message can also be specified on the first sendmsg() call.
>
>    If a call is intended to go to a destination other than the default specified through connect(), then msghdr::msg_name should be set on the first request message of that call.
>
> 6. The reply data will then be posted to the server socket for recvmsg() to pick up.  MSG_MORE will be flagged by recvmsg() if there's more reply data for a particular call to be read.  MSG_EOR will be set on the terminal read for a call.
>
>    All data will be delivered with the following control message attached:
>
>    > RXRPC_USER_CALL_ID      - specifies the user ID for this call
>
>    If an abort or error occurred, this will be returned in the control data buffer instead, and MSG_EOR will be flagged to indicate the end of that call.

A client may ask for a service ID it knows and ask that this be upgraded to a better service if one is available by supplying RXRPC_UPGRADE_SERVICE on the first sendmsg() of a call.  The client should then check srx_service in the msg_name filled in by recvmsg() when collecting the result.  srx_service will hold the same value as given to sendmsg() if the upgrade request was ignored by the service - otherwise it will be altered to indicate the service ID the server upgraded to.  Note that the upgraded service ID is chosen by the server. The caller has to wait until it sees the service ID in the reply before sending any more calls (further calls to the same destination will be blocked until the probe is concluded).

<a id="rst-example-server-usage"></a>

## Example Server Usage

A server would be set up to accept operations in the following manner:

> 1. An RxRPC socket is created by:
>
>
>
>    ```text
>    server = socket(AF_RXRPC, SOCK_DGRAM, PF_INET);
>    ```
>
>    Where the third parameter indicates the address type of the transport socket used - usually IPv4.
>
> 2. Security is set up if desired by giving the socket a keyring with server secret keys in it:
>
>
>
>    ```text
>    keyring = add_key("keyring", "AFSkeys", NULL, 0,
>                      KEY_SPEC_PROCESS_KEYRING);
>
>    const char secret_key[8] = {
>            0xa7, 0x83, 0x8a, 0xcb, 0xc7, 0x83, 0xec, 0x94 };
>    add_key("rxrpc_s", "52:2", secret_key, 8, keyring);
>
>    setsockopt(server, SOL_RXRPC, RXRPC_SECURITY_KEYRING, "AFSkeys", 7);
>    ```
>
>    The keyring can be manipulated after it has been given to the socket. This permits the server to add more keys, replace keys, etc. while it is live.
>
> 3. A local address must then be bound:
>
>
>
>    ```text
>    struct sockaddr_rxrpc srx = {
>            .srx_family     = AF_RXRPC,
>            .srx_service    = VL_SERVICE_ID, /* RxRPC service ID */
>            .transport_type = SOCK_DGRAM,   /* type of transport socket */
>            .transport.sin_family   = AF_INET,
>            .transport.sin_port     = htons(7000), /* AFS callback */
>            .transport.sin_address  = 0,  /* all local interfaces */
>    };
>    bind(server, &srx, sizeof(srx));
>    ```
>
>    More than one service ID may be bound to a socket, provided the transport parameters are the same.  The limit is currently two.  To do this, bind() should be called twice.
>
> 4. If service upgrading is required, first two service IDs must have been bound and then the following option must be set:
>
>
>
>    ```text
>    unsigned short service_ids[2] = { from_ID, to_ID };
>    setsockopt(server, SOL_RXRPC, RXRPC_UPGRADEABLE_SERVICE,
>               service_ids, sizeof(service_ids));
>    ```
>
>    This will automatically upgrade connections on service from_ID to service to_ID if they request it.  This will be reflected in msg_name obtained through recvmsg() when the request data is delivered to userspace.
>
> 5. The server is then set to listen out for incoming calls:
>
>
>
>    ```text
>    listen(server, 100);
>    ```
>
> 6. The kernel notifies the server of pending incoming connections by sending it a message for each.  This is received with recvmsg() on the server socket.  It has no data, and has a single dataless control message attached:
>
>
>
>    ```text
>    RXRPC_NEW_CALL
>    ```
>
>    The address that can be passed back by recvmsg() at this point should be ignored since the call for which the message was posted may have gone by the time it is accepted - in which case the first call still on the queue will be accepted.
>
> 7. The server then accepts the new call by issuing a sendmsg() with two pieces of control data and no actual data:
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_ACCEPT
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > indicate connection acceptance
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_USER_CALL_ID
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > specify user ID for this call
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
> 8. The first request data packet will then be posted to the server socket for recvmsg() to pick up.  At that point, the RxRPC address for the call can be read from the address fields in the msghdr struct.
>
>    Subsequent request data will be posted to the server socket for recvmsg() to collect as it arrives.  All but the last piece of the request data will be delivered with MSG_MORE flagged.
>
>    All data will be delivered with the following control message attached:
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_USER_CALL_ID
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > specifies the user ID for this call
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
> 9. The reply data should then be posted to the server socket using a series of sendmsg() calls, each with the following control messages attached:
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_USER_CALL_ID
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > specifies the user ID for this call
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    MSG_MORE should be set in msghdr::msg_flags on all but the last message for a particular call.

10. The final ACK from the client will be posted for retrieval by recvmsg() when it is received.  It will take the form of a dataless message with two control messages attached:

    >
    > <table>
    > <tbody>
    > <tr>
    > <td>
    >
    >
    > RXRPC_USER_CALL_ID
    >
    > </td>
    > <td>
    >
    >
    > specifies the user ID for this call
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > RXRPC_ACK
    >
    > </td>
    > <td>
    >
    >
    > indicates final ACK (no data)
    >
    > </td>
    > </tr>
    > </tbody>
    > </table>

    MSG_EOR will be flagged to indicate that this is the final message for this call.

11. Up to the point the final packet of reply data is sent, the call can be aborted by calling sendmsg() with a dataless message with the following control messages attached:

    >
    > <table>
    > <tbody>
    > <tr>
    > <td>
    >
    >
    > RXRPC_USER_CALL_ID
    >
    > </td>
    > <td>
    >
    >
    > specifies the user ID for this call
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > RXRPC_ABORT
    >
    > </td>
    > <td>
    >
    >
    > indicates abort code (4 byte data)
    >
    > </td>
    > </tr>
    > </tbody>
    > </table>

    Any packets waiting in the socket's receive queue will be discarded if this is issued.

Note that all the communications for a particular service take place through the one server socket, using control messages on sendmsg() and recvmsg() to determine the call affected.

<a id="rst-af-rxrpc-kernel-interface"></a>

## AF_RXRPC Kernel Interface

The AF_RXRPC module also provides an interface for use by in-kernel utilities such as the AFS filesystem.  This permits such a utility to:

> 1. Use different keys directly on individual client calls on one socket rather than having to open a whole slew of sockets, one for each key it might want to use.
>
> 2. Avoid having RxRPC call request_key() at the point of issue of a call or opening of a socket.  Instead the utility is responsible for requesting a key at the appropriate point.  AFS, for instance, would do this during VFS operations such as open() or unlink().  The key is then handed through when the call is initiated.
>
> 3. Request the use of something other than GFP_KERNEL to allocate memory.
>
> 4. Avoid the overhead of using the recvmsg() call.  RxRPC messages can be intercepted before they get put into the socket Rx queue and the socket buffers manipulated directly.

To use the RxRPC facility, a kernel utility must still open an AF_RXRPC socket, bind an address as appropriate and listen if it's to be a server socket, but then it passes this to the kernel interface functions.

The kernel interface functions are as follows:

> 1. Begin a new client call:
>
>
>
>    ```text
>    struct rxrpc_call *
>    rxrpc_kernel_begin_call(struct socket *sock,
>                            struct sockaddr_rxrpc *srx,
>                            struct key *key,
>                            unsigned long user_call_ID,
>                            s64 tx_total_len,
>                            gfp_t gfp,
>                            rxrpc_notify_rx_t notify_rx,
>                            bool upgrade,
>                            bool intr,
>                            unsigned int debug_id);
>    ```
>
>    This allocates the infrastructure to make a new RxRPC call and assigns call and connection numbers.  The call will be made on the UDP port that the socket is bound to.  The call will go to the destination address of a connected client socket unless an alternative is supplied (srx is non-NULL).
>
>    If a key is supplied then this will be used to secure the call instead of the key bound to the socket with the RXRPC_SECURITY_KEY sockopt.  Calls secured in this way will still share connections if at all possible.
>
>    The user_call_ID is equivalent to that supplied to sendmsg() in the control data buffer.  It is entirely feasible to use this to point to a kernel data structure.
>
>    tx_total_len is the amount of data the caller is intending to transmit with this call (or -1 if unknown at this point).  Setting the data size allows the kernel to encrypt directly to the packet buffers, thereby saving a copy.  The value may not be less than -1.
>
>    notify_rx is a pointer to a function to be called when events such as incoming data packets or remote aborts happen.
>
>    upgrade should be set to true if a client operation should request that the server upgrade the service to a better one.  The resultant service ID is returned by rxrpc_kernel_recv_data().
>
>    intr should be set to true if the call should be interruptible.  If this is not set, this function may not return until a channel has been allocated; if it is set, the function may return -ERESTARTSYS.
>
>    debug_id is the call debugging ID to be used for tracing.  This can be obtained by atomically incrementing rxrpc_debug_id.
>
>    If this function is successful, an opaque reference to the RxRPC call is returned.  The caller now holds a reference on this and it must be properly ended.
>
> 2. Shut down a client call:
>
>
>
>    ```text
>    void rxrpc_kernel_shutdown_call(struct socket *sock,
>                                    struct rxrpc_call *call);
>    ```
>
>    This is used to shut down a previously begun call.  The user_call_ID is expunged from AF_RXRPC's knowledge and will not be seen again in association with the specified call.
>
> 3. Release the ref on a client call:
>
>
>
>    ```text
>    void rxrpc_kernel_put_call(struct socket *sock,
>                               struct rxrpc_call *call);
>    ```
>
>    This is used to release the caller's ref on an rxrpc call.
>
> 4. Send data through a call:
>
>
>
>    ```text
>    typedef void (*rxrpc_notify_end_tx_t)(struct sock *sk,
>                                          unsigned long user_call_ID,
>                                          struct sk_buff *skb);
>
>    int rxrpc_kernel_send_data(struct socket *sock,
>                               struct rxrpc_call *call,
>                               struct msghdr *msg,
>                               size_t len,
>                               rxrpc_notify_end_tx_t notify_end_rx);
>    ```
>
>    This is used to supply either the request part of a client call or the reply part of a server call.  msg.msg_iovlen and msg.msg_iov specify the data buffers to be used.  msg_iov may not be NULL and must point exclusively to in-kernel virtual addresses.  msg.msg_flags may be given MSG_MORE if there will be subsequent data sends for this call.
>
>    The msg must not specify a destination address, control data or any flags other than MSG_MORE.  len is the total amount of data to transmit.
>
>    notify_end_rx can be NULL or it can be used to specify a function to be called when the call changes state to end the Tx phase.  This function is called with a spinlock held to prevent the last DATA packet from being transmitted until the function returns.
>
> 5. Receive data from a call:
>
>
>
>    ```text
>      int rxrpc_kernel_recv_data(struct socket *sock,
>                                 struct rxrpc_call *call,
>                                 void *buf,
>                                 size_t size,
>                                 size_t *_offset,
>                                 bool want_more,
>                                 u32 *_abort,
>                                 u16 *_service)
>
>    This is used to receive data from either the reply part of a client call
>    or the request part of a service call.  buf and size specify how much
>    data is desired and where to store it.  *_offset is added on to buf and
>    subtracted from size internally; the amount copied into the buffer is
>    added to *_offset before returning.
>
>    want_more should be true if further data will be required after this is
>    satisfied and false if this is the last item of the receive phase.
>
>    There are three normal returns: 0 if the buffer was filled and want_more
>    was true; 1 if the buffer was filled, the last DATA packet has been
>    emptied and want_more was false; and -EAGAIN if the function needs to be
>    called again.
>
>    If the last DATA packet is processed but the buffer contains less than
>    the amount requested, EBADMSG is returned.  If want_more wasn't set, but
>    more data was available, EMSGSIZE is returned.
>
>    If a remote ABORT is detected, the abort code received will be stored in
>    ``*_abort`` and ECONNABORTED will be returned.
>
>    The service ID that the call ended up with is returned into *_service.
>    This can be used to see if a call got a service upgrade.
>    ```
>
> 6. Abort a call??
>
>
>
>    ```text
>    void rxrpc_kernel_abort_call(struct socket *sock,
>                                 struct rxrpc_call *call,
>                                 u32 abort_code);
>    ```
>
>    This is used to abort a call if it's still in an abortable state.  The abort code specified will be placed in the ABORT message sent.
>
> 7. Intercept received RxRPC messages:
>
>
>
>    ```text
>    typedef void (*rxrpc_interceptor_t)(struct sock *sk,
>                                        unsigned long user_call_ID,
>                                        struct sk_buff *skb);
>
>    void
>    rxrpc_kernel_intercept_rx_messages(struct socket *sock,
>                                       rxrpc_interceptor_t interceptor);
>    ```
>
>    This installs an interceptor function on the specified AF_RXRPC socket. All messages that would otherwise wind up in the socket's Rx queue are then diverted to this function.  Note that care must be taken to process the messages in the right order to maintain DATA message sequentiality.
>
>    The interceptor function itself is provided with the address of the socket and handling the incoming message, the ID assigned by the kernel utility to the call and the socket buffer containing the message.
>
>    The skb-&gt;mark field indicates the type of message:
>
>    >
>    > <table>
>    > <thead>
>    > <tr>
>    > <th>
>    >
>    >
>    > Mark
>    >
>    > </th>
>    > <th>
>    >
>    >
>    > Meaning
>    >
>    > </th>
>    > </tr>
>    > </thead>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_DATA
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Data message
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_FINAL_ACK
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Final ACK received for an incoming call
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_BUSY
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Client call rejected as server busy
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_REMOTE_ABORT
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Call aborted by peer
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_NET_ERROR
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Network error detected
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_LOCAL_ERROR
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > Local error encountered
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > RXRPC_SKB_MARK_NEW_CALL
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > New incoming call awaiting acceptance
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    The remote abort message can be probed with rxrpc_kernel_get_abort_code(). The two error messages can be probed with rxrpc_kernel_get_error_number(). A new call can be accepted with rxrpc_kernel_accept_call().
>
>    Data messages can have their contents extracted with the usual bunch of socket buffer manipulation functions.  A data message can be determined to be the last one in a sequence with rxrpc_kernel_is_data_last().  When a data message has been used up, rxrpc_kernel_data_consumed() should be called on it.
>
>    Messages should be handled to rxrpc_kernel_free_skb() to dispose of.  It is possible to get extra refs on all types of message for later freeing, but this may pin the state of a call until the message is finally freed.
>
> 8. Accept an incoming call:
>
>
>
>    ```text
>    struct rxrpc_call *
>    rxrpc_kernel_accept_call(struct socket *sock,
>                             unsigned long user_call_ID);
>    ```
>
>    This is used to accept an incoming call and to assign it a call ID.  This function is similar to rxrpc_kernel_begin_call() and calls accepted must be ended in the same way.
>
>    If this function is successful, an opaque reference to the RxRPC call is returned.  The caller now holds a reference on this and it must be properly ended.
>
> 9. Reject an incoming call:
>
>
>
>    ```text
>    int rxrpc_kernel_reject_call(struct socket *sock);
>    ```
>
>    This is used to reject the first incoming call on the socket's queue with a BUSY message.  -ENODATA is returned if there were no incoming calls. Other errors may be returned if the call had been aborted (-ECONNABORTED) or had timed out (-ETIME).
>
> 10. Allocate a null key for doing anonymous security:
>
>
>
>     ```text
>     struct key *rxrpc_get_null_key(const char *keyname);
>     ```
>
>     This is used to allocate a null RxRPC key that can be used to indicate anonymous security for a particular domain.
>
> 11. Get the peer address of a call:
>
>
>
>     ```text
>     void rxrpc_kernel_get_peer(struct socket *sock, struct rxrpc_call *call,
>                                struct sockaddr_rxrpc *_srx);
>     ```
>
>     This is used to find the remote peer address of a call.
>
> 12. Set the total transmit data size on a call:
>
>
>
>     ```text
>     void rxrpc_kernel_set_tx_length(struct socket *sock,
>                                     struct rxrpc_call *call,
>                                     s64 tx_total_len);
>     ```
>
>     This sets the amount of data that the caller is intending to transmit on a call.  It's intended to be used for setting the reply size as the request size should be set when the call is begun.  tx_total_len may not be less than zero.
>
> 13. Get call RTT:
>
>
>
>     ```text
>     u64 rxrpc_kernel_get_rtt(struct socket *sock, struct rxrpc_call *call);
>     ```
>
>     Get the RTT time to the peer in use by a call.  The value returned is in nanoseconds.
>
> 14. Check call still alive:
>
>
>
>     ```text
>     bool rxrpc_kernel_check_life(struct socket *sock,
>                                  struct rxrpc_call *call,
>                                  u32 *_life);
>     void rxrpc_kernel_probe_life(struct socket *sock,
>                                  struct rxrpc_call *call);
>     ```
>
>     The first function passes back in `*_life` a number that is updated when ACKs are received from the peer (notably including PING RESPONSE ACKs which we can elicit by sending PING ACKs to see if the call still exists on the server).  The caller should compare the numbers of two calls to see if the call is still alive after waiting for a suitable interval.  It also returns true as long as the call hasn't yet reached the completed state.
>
>     This allows the caller to work out if the server is still contactable and if the call is still alive on the server while waiting for the server to process a client operation.
>
>     The second function causes a ping ACK to be transmitted to try to provoke the peer into responding, which would then cause the value returned by the first function to change.  Note that this must be called in TASK_RUNNING state.
>
> 15. Apply the RXRPC_MIN_SECURITY_LEVEL sockopt to a socket from within in the kernel:
>
>
>
>     ```text
>     int rxrpc_sock_set_min_security_level(struct sock *sk,
>                                           unsigned int val);
>     ```
>
>     This specifies the minimum security level required for calls on this socket.

<a id="rst-configurable-parameters"></a>

## Configurable Parameters

The RxRPC protocol driver has a number of configurable parameters that can be adjusted through sysctls in /proc/net/rxrpc/:

> 1. req_ack_delay
>
>    The amount of time in milliseconds after receiving a packet with the request-ack flag set before we honour the flag and actually send the requested ack.
>
>    Usually the other side won't stop sending packets until the advertised reception window is full (to a maximum of 255 packets), so delaying the ACK permits several packets to be ACK'd in one go.
>
> 2. soft_ack_delay
>
>    The amount of time in milliseconds after receiving a new packet before we generate a soft-ACK to tell the sender that it doesn't need to resend.
>
> 3. idle_ack_delay
>
>    The amount of time in milliseconds after all the packets currently in the received queue have been consumed before we generate a hard-ACK to tell the sender it can free its buffers, assuming no other reason occurs that we would send an ACK.
>
> 4. resend_timeout
>
>    The amount of time in milliseconds after transmitting a packet before we transmit it again, assuming no ACK is received from the receiver telling us they got it.
>
> 5. max_call_lifetime
>
>    The maximum amount of time in seconds that a call may be in progress before we preemptively kill it.
>
> 6. dead_call_expiry
>
>    The amount of time in seconds before we remove a dead call from the call list.  Dead calls are kept around for a little while for the purpose of repeating ACK and ABORT packets.
>
> 7. connection_expiry
>
>    The amount of time in seconds after a connection was last used before we remove it from the connection list.  While a connection is in existence, it serves as a placeholder for negotiated security; when it is deleted, the security must be renegotiated.
>
> 8. transport_expiry
>
>    The amount of time in seconds after a transport was last used before we remove it from the transport list.  While a transport is in existence, it serves to anchor the peer data and keeps the connection ID counter.
>
> 9. rxrpc_rx_window_size
>
>    The size of the receive window in packets.  This is the maximum number of unconsumed received packets we're willing to hold in memory for any particular call.
>
> 10. rxrpc_rx_mtu
>
>     The maximum packet MTU size that we're willing to receive in bytes.  This indicates to the peer whether we're willing to accept jumbo packets.
>
> 11. rxrpc_rx_jumbo_max
>
>     The maximum number of packets that we're willing to accept in a jumbo packet.  Non-terminal packets in a jumbo packet must contain a four byte header plus exactly 1412 bytes of data.  The terminal packet must contain a four byte header plus any amount of data.  In any event, a jumbo packet may not exceed rxrpc_rx_mtu in size.

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-rxrpc_kernel_lookup_peer"></a>`rxrpc_kernel_lookup_peer()`

```c
struct rxrpc_peer * rxrpc_kernel_lookup_peer(struct socket *sock, struct sockaddr_rxrpc *srx, gfp_t gfp)
```

Obtain remote transport endpoint for an address

**Parameters**

- `struct socket *sock`: The socket through which it will be accessed
- `struct sockaddr_rxrpc *srx`: The network address
- `gfp_t gfp`: Allocation flags

**Description**

Lookup or create a remote transport endpoint record for the specified
address.

**Return**

The peer record found with a reference or a negative error code if
the address is invalid or unsupported.

#### <a id="c-rxrpc_kernel_get_peer"></a>`rxrpc_kernel_get_peer()`

```c
struct rxrpc_peer * rxrpc_kernel_get_peer(struct rxrpc_peer *peer)
```

Get a reference on a peer

**Parameters**

- `struct rxrpc_peer *peer`: The peer to get a reference on (may be NULL).

**Description**

Get a reference for a remote peer record (if not NULL).

**Return**

The **peer** argument.

#### <a id="c-rxrpc_kernel_put_peer"></a>`rxrpc_kernel_put_peer()`

```c
void rxrpc_kernel_put_peer(struct rxrpc_peer *peer)
```

Allow a kernel app to drop a peer reference

**Parameters**

- `struct rxrpc_peer *peer`: The peer to drop a ref on

**Description**

Drop a reference on a peer record.

#### <a id="c-rxrpc_kernel_begin_call"></a>`rxrpc_kernel_begin_call()`

```c
struct rxrpc_call * rxrpc_kernel_begin_call(struct socket *sock, struct rxrpc_peer *peer, struct key *key, unsigned long user_call_ID, s64 tx_total_len, u32 hard_timeout, gfp_t gfp, rxrpc_notify_rx_t notify_rx, u16 service_id, bool upgrade, enum rxrpc_interruptibility interruptibility, unsigned int debug_id)
```

Allow a kernel service to begin a call

**Parameters**

- `struct socket *sock`: The socket on which to make the call
- `struct rxrpc_peer *peer`: The peer to contact
- `struct key *key`: The security context to use (defaults to socket setting)
- `unsigned long user_call_ID`: The ID to use
- `s64 tx_total_len`: Total length of data to transmit during the call (or -1)
- `u32 hard_timeout`: The maximum lifespan of the call in sec
- `gfp_t gfp`: The allocation constraints
- `rxrpc_notify_rx_t notify_rx`: Where to send notifications instead of socket queue
- `u16 service_id`: The ID of the service to contact
- `bool upgrade`: Request service upgrade for call
- `enum rxrpc_interruptibility interruptibility`: The call is interruptible, or can be canceled.
- `unsigned int debug_id`: The debug ID for tracing to be assigned to the call

**Description**

Allow a kernel service to begin a call on the nominated socket.  This just
sets up all the internal tracking structures and allocates connection and
call IDs as appropriate.

The default socket destination address and security may be overridden by
supplying **srx** and **key**.

**Return**

The new call or an error code.

#### <a id="c-rxrpc_kernel_shutdown_call"></a>`rxrpc_kernel_shutdown_call()`

```c
void rxrpc_kernel_shutdown_call(struct socket *sock, struct rxrpc_call *call)
```

Allow a kernel service to shut down a call it was using

**Parameters**

- `struct socket *sock`: The socket the call is on
- `struct rxrpc_call *call`: The call to end

**Description**

Allow a kernel service to shut down a call it was using.  The call must be
complete before this is called (the call should be aborted if necessary).

#### <a id="c-rxrpc_kernel_put_call"></a>`rxrpc_kernel_put_call()`

```c
void rxrpc_kernel_put_call(struct socket *sock, struct rxrpc_call *call)
```

Release a reference to a call

**Parameters**

- `struct socket *sock`: The socket the call is on
- `struct rxrpc_call *call`: The call to put

**Description**

Drop the application's ref on an rxrpc call.

#### <a id="c-rxrpc_kernel_check_life"></a>`rxrpc_kernel_check_life()`

```c
bool rxrpc_kernel_check_life(const struct socket *sock, const struct rxrpc_call *call)
```

Check to see whether a call is still alive

**Parameters**

- `const struct socket *sock`: The socket the call is on
- `const struct rxrpc_call *call`: The call to check

**Description**

Allow a kernel service to find out whether a call is still alive - whether
it has completed successfully and all received data has been consumed.

**Return**

`true` if the call is still ongoing and `false` if it has completed.

#### <a id="c-rxrpc_kernel_set_notifications"></a>`rxrpc_kernel_set_notifications()`

```c
void rxrpc_kernel_set_notifications(struct socket *sock, const struct rxrpc_kernel_ops *app_ops)
```

Set table of callback operations

**Parameters**

- `struct socket *sock`: The socket to install table upon
- `const struct rxrpc_kernel_ops *app_ops`: Callback operation table to set

**Description**

Allow a kernel service to set a table of event notifications on a socket.



#### <a id="c-rxrpc_kernel_query_call_security"></a>`rxrpc_kernel_query_call_security()`

```c
u8 rxrpc_kernel_query_call_security(struct rxrpc_call *call, u16 *_service_id, u32 *_enctype)
```

Query call's security parameters

**Parameters**

- `struct rxrpc_call *call`: The call to query
- `u16 *_service_id`: Where to return the service ID
- `u32 *_enctype`: Where to return the "encoding type"

**Description**

This queries the security parameters of a call, setting **\*_service_id** and
**\*_enctype** and returning the security class.

**Return**

The security class protocol number.



#### <a id="c-rxrpc_get_null_key"></a>`rxrpc_get_null_key()`

```c
struct key * rxrpc_get_null_key(const char *keyname)
```

Generate a null RxRPC key

**Parameters**

- `const char *keyname`: The name to give the key.

**Description**

Generate a null RxRPC key that can be used to indicate anonymous security is
required for a particular domain.

**Return**

The new key or a negative error code.



#### <a id="c-rxrpc_kernel_query_oob"></a>`rxrpc_kernel_query_oob()`

```c
enum rxrpc_oob_type rxrpc_kernel_query_oob(struct sk_buff *oob, struct rxrpc_peer **_peer, unsigned long *_peer_appdata)
```

Query the parameters of an out-of-band message

**Parameters**

- `struct sk_buff *oob`: The message to query
- `struct rxrpc_peer **_peer`: Where to return the peer record
- `unsigned long *_peer_appdata`: The application data attached to a peer record

**Description**

Extract useful parameters from an out-of-band message.  The source peer
parameters are returned through the argument list and the message type is
returned.

**Return**

* `RXRPC_OOB_CHALLENGE` - Challenge wanting a response.

#### <a id="c-rxrpc_kernel_dequeue_oob"></a>`rxrpc_kernel_dequeue_oob()`

```c
struct sk_buff * rxrpc_kernel_dequeue_oob(struct socket *sock, enum rxrpc_oob_type *_type)
```

Dequeue and return the front OOB message

**Parameters**

- `struct socket *sock`: The socket to query
- `enum rxrpc_oob_type *_type`: Where to return the message type

**Description**

Dequeue the front OOB message, if there is one, and return it and
its type.

**Return**

The sk_buff representing the OOB message or `NULL` if the queue was
empty.

#### <a id="c-rxrpc_kernel_free_oob"></a>`rxrpc_kernel_free_oob()`

```c
void rxrpc_kernel_free_oob(struct sk_buff *oob)
```

Free an out-of-band message

**Parameters**

- `struct sk_buff *oob`: The OOB message to free

**Description**

Free an OOB message along with any resources it holds.

#### <a id="c-rxrpc_kernel_query_challenge"></a>`rxrpc_kernel_query_challenge()`

```c
void rxrpc_kernel_query_challenge(struct sk_buff *challenge, struct rxrpc_peer **_peer, unsigned long *_peer_appdata, u16 *_service_id, u8 *_security_index)
```

Query the parameters of a challenge

**Parameters**

- `struct sk_buff *challenge`: The challenge to query
- `struct rxrpc_peer **_peer`: Where to return the peer record
- `unsigned long *_peer_appdata`: The application data attached to a peer record
- `u16 *_service_id`: Where to return the connection service ID
- `u8 *_security_index`: Where to return the connection security index

**Description**

Extract useful parameters from a CHALLENGE message.

#### <a id="c-rxrpc_kernel_reject_challenge"></a>`rxrpc_kernel_reject_challenge()`

```c
int rxrpc_kernel_reject_challenge(struct sk_buff *challenge, u32 abort_code, int error, enum rxrpc_abort_reason why)
```

Allow a kernel service to reject a challenge

**Parameters**

- `struct sk_buff *challenge`: The challenge to be rejected
- `u32 abort_code`: The abort code to stick into the ABORT packet
- `int error`: Local error value
- `enum rxrpc_abort_reason why`: Indication as to why.

**Description**

Allow a kernel service to reject a challenge by aborting the connection if
it's still in an abortable state.  The error is returned so this function
can be used with a return statement.

**Return**

The `error` parameter.



#### <a id="c-rxrpc_kernel_get_call_peer"></a>`rxrpc_kernel_get_call_peer()`

```c
struct rxrpc_peer * rxrpc_kernel_get_call_peer(struct socket *sock, struct rxrpc_call *call)
```

Get the peer address of a call

**Parameters**

- `struct socket *sock`: The socket on which the call is in progress.
- `struct rxrpc_call *call`: The call to query

**Description**

Get a record for the remote peer in a call.

**Return**

The call's peer record.

#### <a id="c-rxrpc_kernel_get_srtt"></a>`rxrpc_kernel_get_srtt()`

```c
unsigned int rxrpc_kernel_get_srtt(const struct rxrpc_peer *peer)
```

Get a call's peer smoothed RTT

**Parameters**

- `const struct rxrpc_peer *peer`: The peer to query

**Description**

Get the call's peer smoothed RTT.

**Return**

The RTT in uS or `UINT_MAX` if we have no samples.

#### <a id="c-rxrpc_kernel_remote_srx"></a>`rxrpc_kernel_remote_srx()`

```c
const struct sockaddr_rxrpc * rxrpc_kernel_remote_srx(const struct rxrpc_peer *peer)
```

Get the address of a peer

**Parameters**

- `const struct rxrpc_peer *peer`: The peer to query

**Description**

Get a pointer to the address from a peer record.  The caller is responsible
for making sure that the address is not deallocated.  A fake address will be
substituted if `peer` in NULL.

**Return**

The rxrpc address record or a fake record.

#### <a id="c-rxrpc_kernel_remote_addr"></a>`rxrpc_kernel_remote_addr()`

```c
const struct sockaddr * rxrpc_kernel_remote_addr(const struct rxrpc_peer *peer)
```

Get the peer transport address of a call

**Parameters**

- `const struct rxrpc_peer *peer`: The peer to query

**Description**

Get a pointer to the transport address from a peer record.  The caller is
responsible for making sure that the address is not deallocated.  A fake
address will be substituted if `peer` in NULL.

**Return**

The transport address record or a fake record.

#### <a id="c-rxrpc_kernel_set_peer_data"></a>`rxrpc_kernel_set_peer_data()`

```c
unsigned long rxrpc_kernel_set_peer_data(struct rxrpc_peer *peer, unsigned long app_data)
```

Set app-specific data on a peer.

**Parameters**

- `struct rxrpc_peer *peer`: The peer to alter
- `unsigned long app_data`: The data to set

**Description**

Set the app-specific data on a peer.  AF_RXRPC makes no effort to retain
anything the data might refer to.

**Return**

The previous app_data.

#### <a id="c-rxrpc_kernel_get_peer_data"></a>`rxrpc_kernel_get_peer_data()`

```c
unsigned long rxrpc_kernel_get_peer_data(const struct rxrpc_peer *peer)
```

Get app-specific data from a peer.

**Parameters**

- `const struct rxrpc_peer *peer`: The peer to query

**Description**

Retrieve the app-specific data from a peer.

**Return**

The peer's app data.



#### <a id="c-rxrpc_kernel_recv_data"></a>`rxrpc_kernel_recv_data()`

```c
int rxrpc_kernel_recv_data(struct socket *sock, struct rxrpc_call *call, struct iov_iter *iter, size_t *_len, bool want_more, u32 *_abort, u16 *_service)
```

Allow a kernel service to receive data/info

**Parameters**

- `struct socket *sock`: The socket that the call exists on
- `struct rxrpc_call *call`: The call to send data through
- `struct iov_iter *iter`: The buffer to receive into
- `size_t *_len`: The amount of data we want to receive (decreased on return)
- `bool want_more`: True if more data is expected to be read
- `u32 *_abort`: Where the abort code is stored if -ECONNABORTED is returned
- `u16 *_service`: Where to store the actual service ID (may be upgraded)

**Description**

Allow a kernel service to receive data and pick up information about the
state of a call.  Note that **\*_abort** should also be initialised to `0`.

Note that we may return `-EAGAIN` to drain empty packets at the end
of the data, even if we've already copied over the requested data.

**Return**

`0` if got what was asked for and there's more available, `1`
if we got what was asked for and we're at the end of the data and
`-EAGAIN` if we need more data.



#### <a id="c-rxgk_kernel_query_challenge"></a>`rxgk_kernel_query_challenge()`

```c
u32 rxgk_kernel_query_challenge(struct sk_buff *challenge)
```

Query RxGK-specific challenge parameters

**Parameters**

- `struct sk_buff *challenge`: The challenge packet to query

**Return**

The Kerberos 5 encoding type for the challenged connection.

#### <a id="c-rxgk_kernel_respond_to_challenge"></a>`rxgk_kernel_respond_to_challenge()`

```c
int rxgk_kernel_respond_to_challenge(struct sk_buff *challenge, struct krb5_buffer *appdata)
```

Respond to a challenge with appdata

**Parameters**

- `struct sk_buff *challenge`: The challenge to respond to
- `struct krb5_buffer *appdata`: The application data to include in the RESPONSE authenticator

**Description**

Allow a kernel application to respond to a CHALLENGE with application data
to be included in the RxGK RESPONSE Authenticator.

**Return**

`0` if successful and a negative error code otherwise.



#### <a id="c-rxkad_kernel_respond_to_challenge"></a>`rxkad_kernel_respond_to_challenge()`

```c
int rxkad_kernel_respond_to_challenge(struct sk_buff *challenge)
```

Respond to a challenge with appdata

**Parameters**

- `struct sk_buff *challenge`: The challenge to respond to

**Description**

Allow a kernel application to respond to a CHALLENGE.

**Return**

`0` if successful and a negative error code otherwise.



#### <a id="c-rxrpc_kernel_send_data"></a>`rxrpc_kernel_send_data()`

```c
int rxrpc_kernel_send_data(struct socket *sock, struct rxrpc_call *call, struct msghdr *msg, size_t len, rxrpc_notify_end_tx_t notify_end_tx)
```

Allow a kernel service to send data on a call

**Parameters**

- `struct socket *sock`: The socket the call is on
- `struct rxrpc_call *call`: The call to send data through
- `struct msghdr *msg`: The data to send
- `size_t len`: The amount of data to send
- `rxrpc_notify_end_tx_t notify_end_tx`: Notification that the last packet is queued.

**Description**

Allow a kernel service to send data on a call.  The call must be in an state
appropriate to sending data.  No control data should be supplied in **msg**,
nor should an address be supplied.  MSG_MORE should be flagged if there's
more data to come, otherwise this data will end the transmission phase.

**Return**

`0` if successful and a negative error code otherwise.

#### <a id="c-rxrpc_kernel_abort_call"></a>`rxrpc_kernel_abort_call()`

```c
bool rxrpc_kernel_abort_call(struct socket *sock, struct rxrpc_call *call, u32 abort_code, int error, enum rxrpc_abort_reason why)
```

Allow a kernel service to abort a call

**Parameters**

- `struct socket *sock`: The socket the call is on
- `struct rxrpc_call *call`: The call to be aborted
- `u32 abort_code`: The abort code to stick into the ABORT packet
- `int error`: Local error value
- `enum rxrpc_abort_reason why`: Indication as to why.

**Description**

Allow a kernel service to abort a call if it's still in an abortable state.

**Return**

`true` if the call was aborted, `false` if it was already complete.

#### <a id="c-rxrpc_kernel_set_tx_length"></a>`rxrpc_kernel_set_tx_length()`

```c
void rxrpc_kernel_set_tx_length(struct socket *sock, struct rxrpc_call *call, s64 tx_total_len)
```

Set the total Tx length on a call

**Parameters**

- `struct socket *sock`: The socket the call is on
- `struct rxrpc_call *call`: The call to be informed
- `s64 tx_total_len`: The amount of data to be transmitted for this call

**Description**

Allow a kernel service to set the total transmit length on a call.  This
allows buffer-to-packet encrypt-and-copy to be performed.

This function is primarily for use for setting the reply length since the
request length can be set when beginning the call.



#### <a id="c-rxrpc_sock_set_security_keyring"></a>`rxrpc_sock_set_security_keyring()`

```c
int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)
```

Set the security keyring for a kernel service

**Parameters**

- `struct sock *sk`: The socket to set the keyring on
- `struct key *keyring`: The keyring to set

**Description**

Set the server security keyring on an rxrpc socket.  This is used to provide
the encryption keys for a kernel service.

**Return**

`0` if successful and a negative error code otherwise.

#### <a id="c-rxrpc_sock_set_manage_response"></a>`rxrpc_sock_set_manage_response()`

```c
int rxrpc_sock_set_manage_response(struct sock *sk, bool set)
```

Set the manage-response flag for a kernel service

**Parameters**

- `struct sock *sk`: The socket to set the keyring on
- `bool set`: True to set, false to clear the flag

**Description**

Set the flag on an rxrpc socket to say that the caller wants to manage the
RESPONSE packet and the user-defined data it may contain.  Setting this
means that `recvmsg()` will return messages with RXRPC_CHALLENGED in the
control message buffer containing information about the challenge.

The user should respond to the challenge by passing RXRPC_RESPOND or
RXRPC_RESPOND_ABORT control messages with `sendmsg()` to the same call.
Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be
included to indicate the parts the user wants to supply.

The server will be passed the response data with a RXRPC_RESPONDED control
message when it gets the first data from each call.

Note that this is only honoured by security classes that need auxiliary data
(e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond
without consulting userspace.

**Return**

The previous setting.

---

# Scaling in the Linux Networking Stack

_Peios Kernel / Internals / Networking_

> This document describes a set of complementary techniques in the Linux networking stack to increase parallelism and improve performance for multi-processor systems.

<a id="rst-scaling-in-the-linux-networking-stack"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This document describes a set of complementary techniques in the Linux networking stack to increase parallelism and improve performance for multi-processor systems.

The following technologies are described:

- RSS: Receive Side Scaling

- RPS: Receive Packet Steering

- RFS: Receive Flow Steering

- Accelerated Receive Flow Steering

- XPS: Transmit Packet Steering

<a id="rst-rss-receive-side-scaling"></a>

## RSS: Receive Side Scaling

Contemporary NICs support multiple receive and transmit descriptor queues (multi-queue). On reception, a NIC can send different packets to different queues to distribute processing among CPUs. The NIC distributes packets by applying a filter to each packet that assigns it to one of a small number of logical flows. Packets for each flow are steered to a separate receive queue, which in turn can be processed by separate CPUs. This mechanism is generally known as “Receive-side Scaling” (RSS). The goal of RSS and the other scaling techniques is to increase performance uniformly. Multi-queue distribution can also be used for traffic prioritization, but that is not the focus of these techniques.

The filter used in RSS is typically a hash function over the network and/or transport layer headers-- for example, a 4-tuple hash over IP addresses and TCP ports of a packet. The most common hardware implementation of RSS uses an indirection table where each entry stores a queue number. The receive queue for a packet is determined by indexing the indirection table with the low order bits of the computed hash for the packet (usually a Toeplitz hash).

The indirection table helps even out the traffic distribution when queue count is not a power of two. NICs should provide an indirection table at least 4 times larger than the queue count. 4x table results in \~16% imbalance between the queues, which is acceptable for most applications.

Some NICs support symmetric RSS hashing where, if the IP (source address, destination address) and TCP/UDP (source port, destination port) tuples are swapped, the computed hash is the same. This is beneficial in some applications that monitor TCP/IP flows (IDS, firewalls, ...etc) and need both directions of the flow to land on the same Rx queue (and CPU). The "Symmetric-XOR" and "Symmetric-OR-XOR" are types of RSS algorithms that achieve this hash symmetry by XOR/ORing the input source and destination fields of the IP and/or L4 protocols. This, however, results in reduced input entropy and could potentially be exploited.

Specifically, the "Symmetric-XOR" algorithm XORs the input as follows:



```text
# (SRC_IP ^ DST_IP, SRC_IP ^ DST_IP, SRC_PORT ^ DST_PORT, SRC_PORT ^ DST_PORT)
```

The "Symmetric-OR-XOR" algorithm, on the other hand, transforms the input as follows:



```text
# (SRC_IP | DST_IP, SRC_IP ^ DST_IP, SRC_PORT | DST_PORT, SRC_PORT ^ DST_PORT)
```

The result is then fed to the underlying RSS algorithm.

Some advanced NICs allow steering packets to queues based on programmable filters. For example, webserver bound TCP port 80 packets can be directed to their own receive queue. Such “n-tuple” filters can be configured from ethtool (--config-ntuple).

<a id="rst-rss-configuration"></a>

### RSS Configuration

The driver for a multi-queue capable NIC typically provides a kernel module parameter for specifying the number of hardware queues to configure. In the bnx2x driver, for instance, this parameter is called num_queues. A typical RSS configuration would be to have one receive queue for each CPU if the device supports enough queues, or otherwise at least one for each memory domain, where a memory domain is a set of CPUs that share a particular memory level (L1, L2, NUMA node, etc.).

The indirection table of an RSS device, which resolves a queue by masked hash, is usually programmed by the driver at initialization. The default mapping is to distribute the queues evenly in the table, but the indirection table can be retrieved and modified at runtime using ethtool commands (--show-rxfh-indir and --set-rxfh-indir). Modifying the indirection table could be done to give different queues different relative weights.

<a id="rst-rss-irq-configuration"></a>

#### RSS IRQ Configuration

Each receive queue has a separate IRQ associated with it. The NIC triggers this to notify a CPU when new packets arrive on the given queue. The signaling path for PCIe devices uses message signaled interrupts (MSI-X), that can route each interrupt to a particular CPU. The active mapping of queues to IRQs can be determined from /proc/interrupts. By default, an IRQ may be handled on any CPU. Because a non-negligible part of packet processing takes place in receive interrupt handling, it is advantageous to spread receive interrupts between CPUs. To manually adjust the IRQ affinity of each interrupt see [Documentation/core-api/irq/irq-affinity.rst](/kernel/internals/core-api/irq/irq-affinity.md). Some systems will be running irqbalance, a daemon that dynamically optimizes IRQ assignments and as a result may override any manual settings.

<a id="rst-suggested-configuration"></a>

#### Suggested Configuration

RSS should be enabled when latency is a concern or whenever receive interrupt processing forms a bottleneck. Spreading load between CPUs decreases queue length. For low latency networking, the optimal setting is to allocate as many queues as there are CPUs in the system (or the NIC maximum, if lower). The most efficient high-rate configuration is likely the one with the smallest number of receive queues where no receive queue overflows due to a saturated CPU, because in default mode with interrupt coalescing enabled, the aggregate number of interrupts (and thus work) grows with each additional queue.

Per-cpu load can be observed using the mpstat utility, but note that on processors with hyperthreading (HT), each hyperthread is represented as a separate CPU. For interrupt handling, HT has shown no benefit in initial tests, so limit the number of queues to the number of CPU cores in the system.

<a id="rst-dedicated-rss-contexts"></a>

#### Dedicated RSS contexts

Modern NICs support creating multiple co-existing RSS configurations which are selected based on explicit matching rules. This can be very useful when application wants to constrain the set of queues receiving traffic for e.g. a particular destination port or IP address. The example below shows how to direct all traffic to TCP port 22 to queues 0 and 1.

To create an additional RSS context use:



```text
# ethtool -X eth0 hfunc toeplitz context new
New RSS context is 1
```

Kernel reports back the ID of the allocated context (the default, always present RSS context has ID of 0). The new context can be queried and modified using the same APIs as the default context:



```text
# ethtool -x eth0 context 1
RX flow hash indirection table for eth0 with 13 RX ring(s):
  0:      0     1     2     3     4     5     6     7
  8:      8     9    10    11    12     0     1     2
[...]
# ethtool -X eth0 equal 2 context 1
# ethtool -x eth0 context 1
RX flow hash indirection table for eth0 with 13 RX ring(s):
  0:      0     1     0     1     0     1     0     1
  8:      0     1     0     1     0     1     0     1
[...]
```

To make use of the new context direct traffic to it using an n-tuple filter:



```text
# ethtool -N eth0 flow-type tcp6 dst-port 22 context 1
Added rule with ID 1023
```

When done, remove the context and the rule:



```text
# ethtool -N eth0 delete 1023
# ethtool -X eth0 context 1 delete
```

<a id="rst-rps-receive-packet-steering"></a>

## RPS: Receive Packet Steering

Receive Packet Steering (RPS) is logically a software implementation of RSS. Being in software, it is necessarily called later in the datapath. Whereas RSS selects the queue and hence CPU that will run the hardware interrupt handler, RPS selects the CPU to perform protocol processing above the interrupt handler. This is accomplished by placing the packet on the desired CPU’s backlog queue and waking up the CPU for processing. RPS has some advantages over RSS:

1. it can be used with any NIC

2. software filters can easily be added to hash over new protocols

3. it does not increase hardware device interrupt rate (although it does introduce inter-processor interrupts (IPIs))

RPS is called during bottom half of the receive interrupt handler, when a driver sends a packet up the network stack with netif_rx() or netif_receive_skb(). These call the get_rps_cpu() function, which selects the queue that should process a packet.

The first step in determining the target CPU for RPS is to calculate a flow hash over the packet’s addresses or ports (2-tuple or 4-tuple hash depending on the protocol). This serves as a consistent hash of the associated flow of the packet. The hash is either provided by hardware or will be computed in the stack. Capable hardware can pass the hash in the receive descriptor for the packet; this would usually be the same hash used for RSS (e.g. computed Toeplitz hash). The hash is saved in skb-&gt;hash and can be used elsewhere in the stack as a hash of the packet’s flow.

Each receive hardware queue has an associated list of CPUs to which RPS may enqueue packets for processing. For each received packet, an index into the list is computed from the flow hash modulo the size of the list. The indexed CPU is the target for processing the packet, and the packet is queued to the tail of that CPU’s backlog queue. At the end of the bottom half routine, IPIs are sent to any CPUs for which packets have been queued to their backlog queue. The IPI wakes backlog processing on the remote CPU, and any queued packets are then processed up the networking stack.

<a id="rst-rps-configuration"></a>

### RPS Configuration

RPS requires a kernel compiled with the CONFIG_RPS kconfig symbol (on by default for SMP). Even when compiled in, RPS remains disabled until explicitly configured. The list of CPUs to which RPS may forward traffic can be configured for each receive queue using a sysfs file entry:



```text
/sys/class/net/<dev>/queues/rx-<n>/rps_cpus
```

This file implements a bitmap of CPUs. RPS is disabled when it is zero (the default), in which case packets are processed on the interrupting CPU. [Documentation/core-api/irq/irq-affinity.rst](/kernel/internals/core-api/irq/irq-affinity.md) explains how CPUs are assigned to the bitmap.

<a id="rst-suggested-configuration-1"></a>

#### Suggested Configuration

For a single queue device, a typical RPS configuration would be to set the rps_cpus to the CPUs in the same memory domain of the interrupting CPU. If NUMA locality is not an issue, this could also be all CPUs in the system. At high interrupt rate, it might be wise to exclude the interrupting CPU from the map since that already performs much work.

For a multi-queue system, if RSS is configured so that a hardware receive queue is mapped to each CPU, then RPS is probably redundant and unnecessary. If there are fewer hardware queues than CPUs, then RPS might be beneficial if the rps_cpus for each queue are the ones that share the same memory domain as the interrupting CPU for that queue.

<a id="rst-rps-flow-limit"></a>

### RPS Flow Limit

RPS scales kernel receive processing across CPUs without introducing reordering. The trade-off to sending all packets from the same flow to the same CPU is CPU load imbalance if flows vary in packet rate. In the extreme case a single flow dominates traffic. Especially on common server workloads with many concurrent connections, such behavior indicates a problem such as a misconfiguration or spoofed source Denial of Service attack.

Flow Limit is an optional RPS feature that prioritizes small flows during CPU contention by dropping packets from large flows slightly ahead of those from small flows. It is active only when an RPS or RFS destination CPU approaches saturation.  Once a CPU's input packet queue exceeds half the maximum queue length (as set by sysctl net.core.netdev_max_backlog), the kernel starts a per-flow packet count over the last 256 packets. If a flow exceeds a set ratio (by default, half) of these packets when a new packet arrives, then the new packet is dropped. Packets from other flows are still only dropped once the input packet queue reaches netdev_max_backlog. No packets are dropped when the input packet queue length is below the threshold, so flow limit does not sever connections outright: even large flows maintain connectivity.

<a id="rst-interface"></a>

#### Interface

Flow limit is compiled in by default (CONFIG_NET_FLOW_LIMIT), but not turned on. It is implemented for each CPU independently (to avoid lock and cache contention) and toggled per CPU by setting the relevant bit in sysctl net.core.flow_limit_cpu_bitmap. It exposes the same CPU bitmap interface as rps_cpus (see above) when called from procfs:



```text
/proc/sys/net/core/flow_limit_cpu_bitmap
```

Per-flow rate is calculated by hashing each packet into a hashtable bucket and incrementing a per-bucket counter. The hash function is the same that selects a CPU in RPS, but as the number of buckets can be much larger than the number of CPUs, flow limit has finer-grained identification of large flows and fewer false positives. The default table has 4096 buckets. This value can be modified through sysctl:



```text
net.core.flow_limit_table_len
```

The value is only consulted when a new table is allocated. Modifying it does not update active tables.

<a id="rst-suggested-configuration-2"></a>

#### Suggested Configuration

Flow limit is useful on systems with many concurrent connections, where a single connection taking up 50% of a CPU indicates a problem. In such environments, enable the feature on all CPUs that handle network rx interrupts (as set in /proc/irq/N/smp_affinity).

The feature depends on the input packet queue length to exceed the flow limit threshold (50%) + the flow history length (256). Setting net.core.netdev_max_backlog to either 1000 or 10000 performed well in experiments.

<a id="rst-rfs-receive-flow-steering"></a>

## RFS: Receive Flow Steering

While RPS steers packets solely based on hash, and thus generally provides good load distribution, it does not take into account application locality. This is accomplished by Receive Flow Steering (RFS). The goal of RFS is to increase datacache hitrate by steering kernel processing of packets to the CPU where the application thread consuming the packet is running. RFS relies on the same RPS mechanisms to enqueue packets onto the backlog of another CPU and to wake up that CPU.

In RFS, packets are not forwarded directly by the value of their hash, but the hash is used as index into a flow lookup table. This table maps flows to the CPUs where those flows are being processed. The flow hash (see RPS section above) is used to calculate the index into this table. The CPU recorded in each entry is the one which last processed the flow. If an entry does not hold a valid CPU, then packets mapped to that entry are steered using plain RPS. Multiple table entries may point to the same CPU. Indeed, with many flows and few CPUs, it is very likely that a single application thread handles flows with many different flow hashes.

rps_sock_flow_table is a global flow table that contains the *desired* CPU for flows: the CPU that is currently processing the flow in userspace. Each table value is a CPU index that is updated during calls to recvmsg and sendmsg (specifically, inet_recvmsg(), inet_sendmsg() and tcp_splice_read()).

When the scheduler moves a thread to a new CPU while it has outstanding receive packets on the old CPU, packets may arrive out of order. To avoid this, RFS uses a second flow table to track outstanding packets for each flow: rps_dev_flow_table is a table specific to each hardware receive queue of each device. Each table value stores a CPU index and a counter. The CPU index represents the *current* CPU onto which packets for this flow are enqueued for further kernel processing. Ideally, kernel and userspace processing occur on the same CPU, and hence the CPU index in both tables is identical. This is likely false if the scheduler has recently migrated a userspace thread while the kernel still has packets enqueued for kernel processing on the old CPU.

The counter in rps_dev_flow_table values records the length of the current CPU's backlog when a packet in this flow was last enqueued. Each backlog queue has a head counter that is incremented on dequeue. A tail counter is computed as head counter + queue length. In other words, the counter in rps_dev_flow\[i\] records the last element in flow i that has been enqueued onto the currently designated CPU for flow i (of course, entry i is actually selected by hash and multiple flows may hash to the same entry i).

And now the trick for avoiding out of order packets: when selecting the CPU for packet processing (from get_rps_cpu()) the rps_sock_flow table and the rps_dev_flow table of the queue that the packet was received on are compared. If the desired CPU for the flow (found in the rps_sock_flow table) matches the current CPU (found in the rps_dev_flow table), the packet is enqueued onto that CPU’s backlog. If they differ, the current CPU is updated to match the desired CPU if one of the following is true:

> - The current CPU's queue head counter &gt;= the recorded tail counter value in rps_dev_flow\[i\]
>
> - The current CPU is unset (&gt;= nr_cpu_ids)
>
> - The current CPU is offline

After this check, the packet is sent to the (possibly updated) current CPU. These rules aim to ensure that a flow only moves to a new CPU when there are no packets outstanding on the old CPU, as the outstanding packets could arrive later than those about to be processed on the new CPU.

<a id="rst-rfs-configuration"></a>

### RFS Configuration

RFS is only available if the kconfig symbol CONFIG_RPS is enabled (on by default for SMP). The functionality remains disabled until explicitly configured. The number of entries in the global flow table is set through:



```text
/proc/sys/net/core/rps_sock_flow_entries
```

The number of entries in the per-queue flow table are set through:



```text
/sys/class/net/<dev>/queues/rx-<n>/rps_flow_cnt
```

<a id="rst-suggested-configuration-3"></a>

#### Suggested Configuration

Both of these need to be set before RFS is enabled for a receive queue. Values for both are rounded up to the nearest power of two. The suggested flow count depends on the expected number of active connections at any given time, which may be significantly less than the number of open connections. We have found that a value of 32768 for rps_sock_flow_entries works fairly well on a moderately loaded server.

For a single queue device, the rps_flow_cnt value for the single queue would normally be configured to the same value as rps_sock_flow_entries. For a multi-queue device, the rps_flow_cnt for each queue might be configured as rps_sock_flow_entries / N, where N is the number of queues. So for instance, if rps_sock_flow_entries is set to 32768 and there are 16 configured receive queues, rps_flow_cnt for each queue might be configured as 2048.

<a id="rst-accelerated-rfs"></a>

## Accelerated RFS

Accelerated RFS is to RFS what RSS is to RPS: a hardware-accelerated load balancing mechanism that uses soft state to steer flows based on where the application thread consuming the packets of each flow is running. Accelerated RFS should perform better than RFS since packets are sent directly to a CPU local to the thread consuming the data. The target CPU will either be the same CPU where the application runs, or at least a CPU which is local to the application thread’s CPU in the cache hierarchy.

To enable accelerated RFS, the networking stack calls the ndo_rx_flow_steer driver function to communicate the desired hardware queue for packets matching a particular flow. The network stack automatically calls this function every time a flow entry in rps_dev_flow_table is updated. The driver in turn uses a device specific method to program the NIC to steer the packets.

The hardware queue for a flow is derived from the CPU recorded in rps_dev_flow_table. The stack consults a CPU to hardware queue map which is maintained by the NIC driver. This is an auto-generated reverse map of the IRQ affinity table shown by /proc/interrupts. Drivers can use functions in the cpu_rmap (“CPU affinity reverse map”) kernel library to populate the map. Alternatively, drivers can delegate the cpu_rmap management to the Kernel by calling netif_enable_cpu_rmap(). For each CPU, the corresponding queue in the map is set to be one whose processing CPU is closest in cache locality.

<a id="rst-accelerated-rfs-configuration"></a>

### Accelerated RFS Configuration

Accelerated RFS is only available if the kernel is compiled with CONFIG_RFS_ACCEL and support is provided by the NIC device and driver. It also requires that ntuple filtering is enabled via ethtool. The map of CPU to queues is automatically deduced from the IRQ affinities configured for each receive queue by the driver, so no additional configuration should be necessary.

<a id="rst-suggested-configuration-4"></a>

#### Suggested Configuration

This technique should be enabled whenever one wants to use RFS and the NIC supports hardware acceleration.

<a id="rst-xps-transmit-packet-steering"></a>

## XPS: Transmit Packet Steering

Transmit Packet Steering is a mechanism for intelligently selecting which transmit queue to use when transmitting a packet on a multi-queue device. This can be accomplished by recording two kinds of maps, either a mapping of CPU to hardware queue(s) or a mapping of receive queue(s) to hardware transmit queue(s).

1. XPS using CPUs map

The goal of this mapping is usually to assign queues exclusively to a subset of CPUs, where the transmit completions for these queues are processed on a CPU within this set. This choice provides two benefits. First, contention on the device queue lock is significantly reduced since fewer CPUs contend for the same queue (contention can be eliminated completely if each CPU has its own transmit queue). Secondly, cache miss rate on transmit completion is reduced, in particular for data cache lines that hold the sk_buff structures.

2. XPS using receive queues map

This mapping is used to pick transmit queue based on the receive queue(s) map configuration set by the administrator. A set of receive queues can be mapped to a set of transmit queues (many:many), although the common use case is a 1:1 mapping. This will enable sending packets on the same queue associations for transmit and receive. This is useful for busy polling multi-threaded workloads where there are challenges in associating a given CPU to a given application thread. The application threads are not pinned to CPUs and each thread handles packets received on a single queue. The receive queue number is cached in the socket for the connection. In this model, sending the packets on the same transmit queue corresponding to the associated receive queue has benefits in keeping the CPU overhead low. Transmit completion work is locked into the same queue-association that a given application is polling on. This avoids the overhead of triggering an interrupt on another CPU. When the application cleans up the packets during the busy poll, transmit completion may be processed along with it in the same thread context and so result in reduced latency.

XPS is configured per transmit queue by setting a bitmap of CPUs/receive-queues that may use that queue to transmit. The reverse mapping, from CPUs to transmit queues or from receive-queues to transmit queues, is computed and maintained for each network device. When transmitting the first packet in a flow, the function get_xps_queue() is called to select a queue. This function uses the ID of the receive queue for the socket connection for a match in the receive queue-to-transmit queue lookup table. Alternatively, this function can also use the ID of the running CPU as a key into the CPU-to-queue lookup table. If the ID matches a single queue, that is used for transmission. If multiple queues match, one is selected by using the flow hash to compute an index into the set. When selecting the transmit queue based on receive queue(s) map, the transmit device is not validated against the receive device as it requires expensive lookup operation in the datapath.

The queue chosen for transmitting a particular flow is saved in the corresponding socket structure for the flow (e.g. a TCP connection). This transmit queue is used for subsequent packets sent on the flow to prevent out of order (ooo) packets. The choice also amortizes the cost of calling get_xps_queues() over all packets in the flow. To avoid ooo packets, the queue for a flow can subsequently only be changed if skb-&gt;ooo_okay is set for a packet in the flow. This flag indicates that there are no outstanding packets in the flow, so the transmit queue can change without the risk of generating out of order packets. The transport layer is responsible for setting ooo_okay appropriately. TCP, for instance, sets the flag when all data for a connection has been acknowledged.

<a id="rst-xps-configuration"></a>

### XPS Configuration

XPS is only available if the kconfig symbol CONFIG_XPS is enabled (on by default for SMP). If compiled in, it is driver dependent whether, and how, XPS is configured at device init. The mapping of CPUs/receive-queues to transmit queue can be inspected and configured using sysfs:

For selection based on CPUs map:



```text
/sys/class/net/<dev>/queues/tx-<n>/xps_cpus
```

For selection based on receive-queues map:



```text
/sys/class/net/<dev>/queues/tx-<n>/xps_rxqs
```

<a id="rst-suggested-configuration-5"></a>

#### Suggested Configuration

For a network device with a single transmission queue, XPS configuration has no effect, since there is no choice in this case. In a multi-queue system, XPS is preferably configured so that each CPU maps onto one queue. If there are as many queues as there are CPUs in the system, then each queue can also map onto one CPU, resulting in exclusive pairings that experience no contention. If there are fewer queues than CPUs, then the best CPUs to share a given queue are probably those that share the cache with the CPU that processes transmit completions for that queue (transmit interrupts).

For transmit queue selection based on receive queue(s), XPS has to be explicitly configured mapping receive-queue(s) to transmit queue(s). If the user configuration for receive-queue map does not apply, then the transmit queue is selected based on the CPUs map.

<a id="rst-per-tx-queue-rate-limitation"></a>

## Per TX Queue rate limitation

These are rate-limitation mechanisms implemented by HW, where currently a max-rate attribute is supported, by setting a Mbps value to:



```text
/sys/class/net/<dev>/queues/tx-<n>/tx_maxrate
```

A value of zero means disabled, and this is the default.

<a id="rst-further-information"></a>

## Further Information

RPS and RFS were introduced in kernel 2.6.35. XPS was incorporated into 2.6.38. Original patches were submitted by Tom Herbert ([therbert@google.com](<mailto:therbert@google.com>))

Accelerated RFS was introduced in 2.6.35. Original patches were submitted by Ben Hutchings ([bwh@kernel.org](<mailto:bwh@kernel.org>))

Authors:

- Tom Herbert ([therbert@google.com](<mailto:therbert@google.com>))

- Willem de Bruijn ([willemb@google.com](<mailto:willemb@google.com>))

---

# Linux Kernel SCTP

_Peios Kernel / Internals / Networking_

> This is the current BETA release of the Linux Kernel SCTP reference implementation.

<a id="rst-linux-kernel-sctp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This is the current BETA release of the Linux Kernel SCTP reference implementation.

SCTP (Stream Control Transmission Protocol) is a IP based, message oriented, reliable transport protocol, with congestion control, support for transparent multi-homing, and multiple ordered streams of messages. RFC2960 defines the core protocol.  The IETF SIGTRAN working group originally developed the SCTP protocol and later handed the protocol over to the Transport Area (TSVWG) working group for the continued evolvement of SCTP as a general purpose transport.

See the IETF website ([http://www.ietf.org](<http://www.ietf.org>)) for further documents on SCTP. See [http://www.ietf.org/rfc/rfc2960.txt](<http://www.ietf.org/rfc/rfc2960.txt>)

The initial project goal is to create an Linux kernel reference implementation of SCTP that is RFC 2960 compliant and provides an programming interface referred to as the  UDP-style API of the Sockets Extensions for SCTP, as proposed in IETF Internet-Drafts.

<a id="rst-caveats"></a>

## Caveats

- lksctp can be built as statically or as a module.  However, be aware that module removal of lksctp is not yet a safe activity.

- There is tentative support for IPv6, but most work has gone towards implementation and testing lksctp on IPv4.

For more information, please visit the lksctp project website:

> [http://www.sf.net/projects/lksctp](<http://www.sf.net/projects/lksctp>)

Or contact the lksctp developers through the mailing list:

> &lt;[linux-sctp@vger.kernel.org](<mailto:linux-sctp@vger.kernel.org>)&gt;

---

# LSM/SeLinux secid

_Peios Kernel / Internals / Networking_

> flowi structure:

> **Peios:** The LSM examples here describe upstream interfaces and implementation choices. Peios configures `landlock,lockdown,integrity,pkm`; SELinux, Smack, AppArmor and their attribute/policy interfaces are not the active native access model. Use the native token/SD interfaces for Peios authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-lsm-selinux-secid"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

flowi structure:

The secid member in the flow structure is used in LSMs (e.g. SELinux) to indicate the label of the flow. This label of the flow is currently used in selecting matching labeled xfrm(s).

If this is an outbound flow, the label is derived from the socket, if any, or the incoming packet this flow is being generated as a response to (e.g. tcp resets, timewait ack, etc.). It is also conceivable that the label could be derived from other sources such as process context, device, etc., in special cases, as may be appropriate.

If this is an inbound flow, the label is derived from the IPSec security associations, if any, used by the packet.

---

# Seg6 Sysfs variables

_Peios Kernel / Internals / Networking_

> Accept or drop SR-enabled IPv6 packets on this interface.

<a id="rst-seg6-sysfs-variables"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-proc-sys-net-conf-iface-seg6-variables"></a>

## /proc/sys/net/conf/&lt;iface&gt;/seg6\_\* variables:

- **seg6_enabled - BOOL**

  Accept or drop SR-enabled IPv6 packets on this interface.

  Relevant packets are those with SRH present and DA = local.

  - 0 - disabled (default)

  - not 0 - enabled

- **seg6_require_hmac - INTEGER**

  Define HMAC policy for ingress SR-enabled packets on this interface.

  - -1 - Ignore HMAC field

  - 0 - Accept SR packets without HMAC, validate SR packets with HMAC

  - 1 - Drop SR packets without HMAC, validate SR packets with HMAC

  Default is 0.

<a id="rst-proc-sys-net-ipv6-seg6-variables"></a>

## /proc/sys/net/ipv6/seg6\_\* variables:

- **seg6_flowlabel - INTEGER**

  Controls the behaviour of computing the flowlabel of outer IPv6 header in case of SR T.encaps

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -1
  >
  > </td>
  > <td>
  >
  >
  > set flowlabel to zero.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 0
  >
  > </td>
  > <td>
  >
  >
  > copy flowlabel from Inner packet in case of Inner IPv6 (Set flowlabel to 0 in case IPv4/L2)
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > 1
  >
  > </td>
  > <td>
  >
  >
  > Compute the flowlabel using seg6_make_flowlabel()
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  Default is 0.

---

# Segmentation Offloads

_Peios Kernel / Internals / Networking_

> This document describes a set of techniques in the Linux networking stack to take advantage of segmentation offload capabilities of various NICs.

<a id="rst-segmentation-offloads"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This document describes a set of techniques in the Linux networking stack to take advantage of segmentation offload capabilities of various NICs.

- **The following technologies are described:**

  - TCP Segmentation Offload - TSO

  - UDP Fragmentation Offload - UFO

  - IPIP, SIT, GRE, and UDP Tunnel Offloads

  - Generic Segmentation Offload - GSO

  - Generic Receive Offload - GRO

  - Partial Generic Segmentation Offload - GSO_PARTIAL

  - SCTP acceleration with GSO - GSO_BY_FRAGS

<a id="rst-tcp-segmentation-offload"></a>

## TCP Segmentation Offload

TCP segmentation allows a device to segment a single frame into multiple frames with a data payload size specified in skb_shinfo()-&gt;gso_size. When TCP segmentation requested the bit for either SKB_GSO_TCPV4 or SKB_GSO_TCPV6 should be set in skb_shinfo()-&gt;gso_type and skb_shinfo()-&gt;gso_size should be set to a non-zero value.

TCP segmentation is dependent on support for the use of partial checksum offload.  For this reason TSO is normally disabled if the Tx checksum offload for a given device is disabled.

In order to support TCP segmentation offload it is necessary to populate the network and transport header offsets of the skbuff so that the device drivers will be able determine the offsets of the IP or IPv6 header and the TCP header.  In addition as CHECKSUM_PARTIAL is required csum_start should also point to the TCP header of the packet.

For IPv4 segmentation we support one of two types in terms of the IP ID. The default behavior is to increment the IP ID with every segment.  If the GSO type SKB_GSO_TCP_FIXEDID is specified then we will not increment the IP ID and all segments will use the same IP ID.

For encapsulated packets, SKB_GSO_TCP_FIXEDID refers only to the outer header. SKB_GSO_TCP_FIXEDID_INNER can be used to specify the same for the inner header. Any combination of these two GSO types is allowed.

If a device has NETIF_F_TSO_MANGLEID set then the IP ID can be ignored when performing TSO and we will either increment the IP ID for all frames, or leave it at a static value based on driver preference.  For encapsulated packets, NETIF_F_TSO_MANGLEID is relevant for both outer and inner headers, unless the DF bit is not set on the outer header, in which case the device driver must guarantee that the IP ID field is incremented in the outer header with every segment.

<a id="rst-udp-fragmentation-offload"></a>

## UDP Fragmentation Offload

UDP fragmentation offload allows a device to fragment an oversized UDP datagram into multiple IPv4 fragments.  Many of the requirements for UDP fragmentation offload are the same as TSO.  However the IPv4 ID for fragments should not increment as a single IPv4 datagram is fragmented.

UFO is deprecated: modern kernels will no longer generate UFO skbs, but can still receive them from tuntap and similar devices. Offload of UDP-based tunnel protocols is still supported.

<a id="rst-ipip-sit-gre-udp-tunnel-and-remote-checksum-offloads"></a>

## IPIP, SIT, GRE, UDP Tunnel, and Remote Checksum Offloads

In addition to the offloads described above it is possible for a frame to contain additional headers such as an outer tunnel.  In order to account for such instances an additional set of segmentation offload types were introduced including SKB_GSO_IPXIP4, SKB_GSO_IPXIP6, SKB_GSO_GRE, and SKB_GSO_UDP_TUNNEL.  These extra segmentation types are used to identify cases where there are more than just 1 set of headers.  For example in the case of IPIP and SIT we should have the network and transport headers moved from the standard list of headers to "inner" header offsets.

Currently only two levels of headers are supported.  The convention is to refer to the tunnel headers as the outer headers, while the encapsulated data is normally referred to as the inner headers.  Below is the list of calls to access the given headers:

IPIP/SIT Tunnel:



```text
           Outer                  Inner
MAC        skb_mac_header
Network    skb_network_header     skb_inner_network_header
Transport  skb_transport_header
```

UDP/GRE Tunnel:



```text
           Outer                  Inner
MAC        skb_mac_header         skb_inner_mac_header
Network    skb_network_header     skb_inner_network_header
Transport  skb_transport_header   skb_inner_transport_header
```

In addition to the above tunnel types there are also SKB_GSO_GRE_CSUM and SKB_GSO_UDP_TUNNEL_CSUM.  These two additional tunnel types reflect the fact that the outer header also requests to have a non-zero checksum included in the outer header.

Finally there is SKB_GSO_TUNNEL_REMCSUM which indicates that a given tunnel header has requested a remote checksum offload.  In this case the inner headers will be left with a partial checksum and only the outer header checksum will be computed.

<a id="rst-generic-segmentation-offload"></a>

## Generic Segmentation Offload

Generic segmentation offload is a pure software offload that is meant to deal with cases where device drivers cannot perform the offloads described above.  What occurs in GSO is that a given skbuff will have its data broken out over multiple skbuffs that have been resized to match the MSS provided via skb_shinfo()-&gt;gso_size.

Before enabling any hardware segmentation offload a corresponding software offload is required in GSO.  Otherwise it becomes possible for a frame to be re-routed between devices and end up being unable to be transmitted.

<a id="rst-generic-receive-offload"></a>

## Generic Receive Offload

Generic receive offload is the complement to GSO.  Ideally any frame assembled by GRO should be segmented to create an identical sequence of frames using GSO, and any sequence of frames segmented by GSO should be able to be reassembled back to the original by GRO.

<a id="rst-partial-generic-segmentation-offload"></a>

## Partial Generic Segmentation Offload

Partial generic segmentation offload is a hybrid between TSO and GSO.  What it effectively does is take advantage of certain traits of TCP and tunnels so that instead of having to rewrite the packet headers for each segment only the inner-most transport header and possibly the outer-most network header need to be updated.  This allows devices that do not support tunnel offloads or tunnel offloads with checksum to still make use of segmentation.

With the partial offload what occurs is that all headers excluding the inner transport header are updated such that they will contain the correct values for if the header was simply duplicated.  The one exception to this is the outer IPv4 ID field.  It is up to the device drivers to guarantee that the IPv4 ID field is incremented in the case that a given header does not have the DF bit set.

<a id="rst-sctp-acceleration-with-gso"></a>

## SCTP acceleration with GSO

SCTP - despite the lack of hardware support - can still take advantage of GSO to pass one large packet through the network stack, rather than multiple small packets.

This requires a different approach to other offloads, as SCTP packets cannot be just segmented to (P)MTU. Rather, the chunks must be contained in IP segments, padding respected. So unlike regular GSO, SCTP can't just generate a big skb, set gso_size to the fragmentation point and deliver it to IP layer.

Instead, the SCTP protocol layer builds an skb with the segments correctly padded and stored as chained skbs, and skb_segment() splits based on those. To signal this, gso_size is set to the special value GSO_BY_FRAGS.

Therefore, any code in the core networking stack must be aware of the possibility that gso_size will be GSO_BY_FRAGS and handle that case appropriately.

There are some helpers to make this easier:

- skb_is_gso(skb) &amp;&amp; skb_is_gso_sctp(skb) is the best way to see if an skb is an SCTP GSO skb.

- For size checks, the skb_gso_validate\_\*\_len family of helpers correctly considers GSO_BY_FRAGS.

- For manipulating packets, skb_increase_gso_size and skb_decrease_gso_size will check for GSO_BY_FRAGS and WARN if asked to manipulate these skbs.

This also affects drivers with the NETIF_F_FRAGLIST &amp; NETIF_F_GSO_SCTP bits set. Note also that NETIF_F_GSO_SCTP is included in NETIF_F_GSO_SOFTWARE.

---

# phylink

_Peios Kernel / Internals / Networking_

> phylink is a mechanism to support hot-pluggable networking modules directly connected to a MAC without needing to re-initialise the adapter on hot-plug events.

<a id="rst-phylink"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

phylink is a mechanism to support hot-pluggable networking modules directly connected to a MAC without needing to re-initialise the adapter on hot-plug events.

phylink supports conventional phylib-based setups, fixed link setups and SFP (Small Formfactor Pluggable) modules at present.

<a id="rst-modes-of-operation"></a>

## Modes of operation

phylink has several modes of operation, which depend on the firmware settings.

1. PHY mode

   In PHY mode, we use phylib to read the current link settings from the PHY, and pass them to the MAC driver.  We expect the MAC driver to configure exactly the modes that are specified without any negotiation being enabled on the link.

2. Fixed mode

   Fixed mode is the same as PHY mode as far as the MAC driver is concerned.

3. In-band mode

   In-band mode is used with 802.3z, SGMII and similar interface modes, and we are expecting to use and honor the in-band negotiation or control word sent across the serdes channel.

By example, what this means is that:



```none
&eth {
  phy = <&phy>;
  phy-mode = "sgmii";
};
```

does not use in-band SGMII signalling.  The PHY is expected to follow exactly the settings given to it in its `mac_config()` function. The link should be forced up or down appropriately in the `mac_link_up()` and `mac_link_down()` functions.



```none
&eth {
  managed = "in-band-status";
  phy = <&phy>;
  phy-mode = "sgmii";
};
```

uses in-band mode, where results from the PHY's negotiation are passed to the MAC through the SGMII control word, and the MAC is expected to acknowledge the control word.  The `mac_link_up()` and `mac_link_down()` functions must not force the MAC side link up and down.

<a id="rst-rough-guide-to-converting-a-network-driver-to-sfp-phylink"></a>

## Rough guide to converting a network driver to sfp/phylink

This guide briefly describes how to convert a network driver from phylib to the sfp/phylink support.  Please send patches to improve this documentation.

1. Optionally split the network driver's phylib update function into two parts dealing with link-down and link-up. This can be done as a separate preparation commit.

   An older example of this preparation can be found in git commit fc548b991fb0, although this was splitting into three parts; the link-up part now includes configuring the MAC for the link settings. Please see `mac_link_up()` for more information on this.

2. Replace:



   ```text
   select FIXED_PHY
   select PHYLIB
   ```

   with:



   ```text
   select PHYLINK
   ```

   in the driver's Kconfig stanza.

3. Add:



   ```text
   #include <linux/phylink.h>
   ```

   to the driver's list of header files.

4. Add:



   ```text
   struct phylink *phylink;
   struct phylink_config phylink_config;
   ```

   to the driver's private data structure.  We shall refer to the driver's private data pointer as `priv` below, and the driver's private data structure as `struct foo_priv`.

5. Replace the following functions:


   <table>
   <thead>
   <tr>
   <th>


   Original function

   </th>
   <th>


   Replacement function

   </th>
   </tr>
   </thead>
   <tbody>
   <tr>
   <td>


   phy_start(phydev)

   </td>
   <td>


   phylink_start(priv-&gt;phylink)

   </td>
   </tr>
   <tr>
   <td>


   phy_stop(phydev)

   </td>
   <td>


   phylink_stop(priv-&gt;phylink)

   </td>
   </tr>
   <tr>
   <td>


   phy_mii_ioctl(phydev, ifr, cmd)

   </td>
   <td>


   phylink_mii_ioctl(priv-&gt;phylink, ifr, cmd)

   </td>
   </tr>
   <tr>
   <td>


   phy_ethtool_get_wol(phydev, wol)

   </td>
   <td>


   phylink_ethtool_get_wol(priv-&gt;phylink, wol)

   </td>
   </tr>
   <tr>
   <td>


   phy_ethtool_set_wol(phydev, wol)

   </td>
   <td>


   phylink_ethtool_set_wol(priv-&gt;phylink, wol)

   </td>
   </tr>
   <tr>
   <td>


   phy_disconnect(phydev)

   </td>
   <td>


   phylink_disconnect_phy(priv-&gt;phylink)

   </td>
   </tr>
   </tbody>
   </table>

   Please note that some of these functions must be called under the rtnl lock, and will warn if not. This will normally be the case, except if these are called from the driver suspend/resume paths.

6. Add/replace ksettings get/set methods with:



   ```c
   static int foo_ethtool_set_link_ksettings(struct net_device *dev,
                                             const struct ethtool_link_ksettings *cmd)
   {
           struct foo_priv *priv = netdev_priv(dev);

           return phylink_ethtool_ksettings_set(priv->phylink, cmd);
   }

   static int foo_ethtool_get_link_ksettings(struct net_device *dev,
                                             struct ethtool_link_ksettings *cmd)
   {
           struct foo_priv *priv = netdev_priv(dev);

           return phylink_ethtool_ksettings_get(priv->phylink, cmd);
   }
   ```

7. Replace the call to:



   ```text
   phy_dev = of_phy_connect(dev, node, link_func, flags, phy_interface);
   ```

   and associated code with a call to:



   ```text
   err = phylink_of_phy_connect(priv->phylink, node, flags);
   ```

   For the most part, `flags` can be zero; these flags are passed to the phy_attach_direct() inside this function call if a PHY is specified in the DT node `node`.

   `node` should be the DT node which contains the network phy property, fixed link properties, and will also contain the sfp property.

   The setup of fixed links should also be removed; these are handled internally by phylink.

   of_phy_connect() was also passed a function pointer for link updates. This function is replaced by a different form of MAC updates described below in (8).

   Manipulation of the PHY's supported/advertised happens within phylink based on the validate callback, see below in (8).

   Note that the driver no longer needs to store the `phy_interface`, and also note that `phy_interface` becomes a dynamic property, just like the speed, duplex etc. settings.

   Finally, note that the MAC driver has no direct access to the PHY anymore; that is because in the phylink model, the PHY can be dynamic.

8. Add a `struct phylink_mac_ops <phylink_mac_ops>` instance to the driver, which is a table of function pointers, and implement these functions. The old link update function for `of_phy_connect()` becomes three methods: `mac_link_up()`, `mac_link_down()`, and `mac_config()`. If step 1 was performed, then the functionality will have been split there.

   It is important that if in-band negotiation is used, `mac_link_up()` and `mac_link_down()` do not prevent the in-band negotiation from completing, since these functions are called when the in-band link state changes - otherwise the link will never come up.

   The `mac_get_caps()` method is optional, and if provided should return the phylink MAC capabilities that are supported for the passed `interface` mode. In general, there is no need to implement this method. Phylink will use these capabilities in combination with permissible capabilities for `interface` to determine the allowable ethtool link modes.

   The `mac_link_state()` method is used to read the link state from the MAC, and report back the settings that the MAC is currently using. This is particularly important for in-band negotiation methods such as 1000base-X and SGMII.

   The `mac_link_up()` method is used to inform the MAC that the link has come up. The call includes the negotiation mode and interface for reference only. The finalised link parameters are also supplied (speed, duplex and flow control/pause enablement settings) which should be used to configure the MAC when the MAC and PCS are not tightly integrated, or when the settings are not coming from in-band negotiation.

   The `mac_config()` method is used to update the MAC with the requested state, and must avoid unnecessarily taking the link down when making changes to the MAC configuration.  This means the function should modify the state and only take the link down when absolutely necessary to change the MAC configuration.  An example of how to do this can be found in `mvneta_mac_config()` in `drivers/net/ethernet/marvell/mvneta.c`.

   For further information on these methods, please see the inline documentation in `struct phylink_mac_ops <phylink_mac_ops>`.

9. Fill-in the `struct phylink_config <phylink_config>` fields with a reference to the `struct device <device>` associated to your `struct net_device <net_device>`:



   ```c
   priv->phylink_config.dev = &dev.dev;
   priv->phylink_config.type = PHYLINK_NETDEV;
   ```

   Fill-in the various speeds, pause and duplex modes your MAC can handle:



   ```c
   priv->phylink_config.mac_capabilities = MAC_SYM_PAUSE | MAC_10 | MAC_100 | MAC_1000FD;
   ```

10. Some Ethernet controllers work in pair with a PCS (Physical Coding Sublayer) block, that can handle among other things the encoding/decoding, link establishment detection and autonegotiation. While some MACs have internal PCS whose operation is transparent, some other require dedicated PCS configuration for the link to become functional. In that case, phylink provides a PCS abstraction through `struct phylink_pcs <phylink_pcs>`.

    Identify if your driver has one or more internal PCS blocks, and/or if your controller can use an external PCS block that might be internally connected to your controller.

    If your controller doesn't have any internal PCS, you can go to step 11.

    If your Ethernet controller contains one or several PCS blocks, create one `struct phylink_pcs <phylink_pcs>` instance per PCS block within your driver's private data structure:



    ```c
    struct phylink_pcs pcs;
    ```

    Populate the relevant `struct phylink_pcs_ops <phylink_pcs_ops>` to configure your PCS. Create a `pcs_get_state()` function that reports the inband link state, a `pcs_config()` function to configure your PCS according to phylink-provided parameters, and a `pcs_validate()` function that report to phylink all accepted configuration parameters for your PCS:



    ```c
    struct phylink_pcs_ops foo_pcs_ops = {
            .pcs_validate = foo_pcs_validate,
            .pcs_get_state = foo_pcs_get_state,
            .pcs_config = foo_pcs_config,
    };
    ```

    Arrange for PCS link state interrupts to be forwarded into phylink, via:



    ```c
    phylink_pcs_change(pcs, link_is_up);
    ```

    where `link_is_up` is true if the link is currently up or false otherwise. If a PCS is unable to provide these interrupts, then it should set `pcs->pcs_poll = true;` when creating the PCS.

11. If your controller relies on, or accepts the presence of an external PCS controlled through its own driver, add a pointer to a phylink_pcs instance in your driver private data structure:



    ```c
    struct phylink_pcs *pcs;
    ```

    The way of getting an instance of the actual PCS depends on the platform, some PCS sit on an MDIO bus and are grabbed by passing a pointer to the corresponding `struct mii_bus <mii_bus>` and the PCS's address on that bus. In this example, we assume the controller attaches to a Lynx PCS instance:



    ```c
    priv->pcs = lynx_pcs_create_mdiodev(bus, 0);
    ```

    Some PCS can be recovered based on firmware information:



    ```c
    priv->pcs = lynx_pcs_create_fwnode(of_fwnode_handle(node));
    ```

12. Populate the `mac_select_pcs()` callback and add it to your `struct phylink_mac_ops <phylink_mac_ops>` set of ops. This function must return a pointer to the relevant `struct phylink_pcs <phylink_pcs>` that will be used for the requested link configuration:



    ```c
    static struct phylink_pcs *foo_select_pcs(struct phylink_config *config,
                                              phy_interface_t interface)
    {
            struct foo_priv *priv = container_of(config, struct foo_priv,
                                                 phylink_config);

            if ( /* 'interface' needs a PCS to function */ )
                    return priv->pcs;

            return NULL;
    }
    ```

    See `mvpp2_select_pcs()` for an example of a driver that has multiple internal PCS.

13. Fill-in all the `phy_interface_t <phy_interface_t>` (i.e. all MAC to PHY link modes) that your MAC can output. The following example shows a configuration for a MAC that can handle all RGMII modes, SGMII and 1000BaseX. You must adjust these according to what your MAC and all PCS associated with this MAC are capable of, and not just the interface you wish to use:



    ```c
    phy_interface_set_rgmii(priv->phylink_config.supported_interfaces);
     __set_bit(PHY_INTERFACE_MODE_SGMII,
               priv->phylink_config.supported_interfaces);
     __set_bit(PHY_INTERFACE_MODE_1000BASEX,
               priv->phylink_config.supported_interfaces);
    ```

14. Remove calls to of_parse_phandle() for the PHY, of_phy_register_fixed_link() for fixed links etc. from the probe function, and replace with:



    ```c
    struct phylink *phylink;

    phylink = phylink_create(&priv->phylink_config, node, phy_mode, &phylink_ops);
    if (IS_ERR(phylink)) {
            err = PTR_ERR(phylink);
            fail probe;
    }

    priv->phylink = phylink;
    ```

    and arrange to destroy the phylink in the probe failure path as appropriate and the removal path too by calling:



    ```c
    phylink_destroy(priv->phylink);
    ```

15. Arrange for MAC link state interrupts to be forwarded into phylink, via:



    ```c
    phylink_mac_change(priv->phylink, link_is_up);
    ```

    where `link_is_up` is true if the link is currently up or false otherwise.

16. Verify that the driver does not call:



    ```text
    netif_carrier_on()
    netif_carrier_off()
    ```

    as these will interfere with phylink's tracking of the link state, and cause phylink to omit calls via the `mac_link_up()` and `mac_link_down()` methods.

Network drivers should call phylink_stop() and phylink_start() via their suspend/resume paths, which ensures that the appropriate `struct phylink_mac_ops <phylink_mac_ops>` methods are called as necessary.

For information describing the SFP cage in DT, please see the binding documentation in the kernel source tree `Documentation/devicetree/bindings/net/sff,sfp.yaml`.

---

# struct sk_buff

_Peios Kernel / Internals / Networking_

> sk_buff is the main networking structure representing a packet.

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-struct-sk-buff"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`sk_buff` is the main networking structure representing a packet.

<a id="rst-basic-sk-buff-geometry"></a>

## Basic sk_buff geometry


struct sk_buff itself is a metadata structure and does not hold any packet
data. All the data is held in associated buffers.

[`sk_buff.head`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) points to the main "head" buffer. The head buffer is divided
into two parts:

- data buffer, containing headers and sometimes payload;
  this is the part of the skb operated on by the common helpers
  such as [`skb_put()`](/kernel/internals/networking/kapi.md#c-skb_put) or [`skb_pull()`](/kernel/internals/networking/kapi.md#c-skb_pull);
- shared info (struct skb_shared_info) which holds an array of pointers
  to read-only data in the (page, offset, length) format.

Optionally `skb_shared_info.frag_list` may point to another skb.

Basic diagram may look like this:

```text
                                ---------------
                               | sk_buff       |
                                ---------------
   ,---------------------------  + head
  /          ,-----------------  + data
 /          /      ,-----------  + tail
|          |      |            , + end
|          |      |           |
v          v      v           v
 -----------------------------------------------
| headroom | data |  tailroom | skb_shared_info |
 -----------------------------------------------
                               + [page frag]
                               + [page frag]
                               + [page frag]
                               + [page frag]       ---------
                               + frag_list    --> | sk_buff |
                                                   ---------
```


<a id="rst-shared-skbs-and-skb-clones"></a>

## Shared skbs and skb clones

`sk_buff.users` is a simple refcount allowing multiple entities to keep a struct sk_buff alive. skbs with a `sk_buff.users != 1` are referred to as shared skbs (see skb_shared()).

skb_clone() allows for fast duplication of skbs. None of the data buffers get copied, but caller gets a new metadata struct (struct sk_buff). &amp;skb_shared_info.refcount indicates the number of skbs pointing at the same packet data (i.e. clones).

<a id="rst-dataref-and-headerless-skbs"></a>

## dataref and headerless skbs


Transport layers send out clones of payload skbs they hold for
retransmissions. To allow lower layers of the stack to prepend their headers
we split `skb_shared_info.dataref` into two halves.
The lower 16 bits count the overall number of references.
The higher 16 bits indicate how many of the references are payload-only.
[`skb_header_cloned()`](/kernel/internals/networking/kapi.md#c-skb_header_cloned) checks if skb is allowed to add / write the headers.

The creator of the skb (e.g. TCP) marks its skb as [`sk_buff.nohdr`](/kernel/internals/networking/kapi.md#c-struct-sk_buff)
(via [`__skb_header_release()`](/kernel/internals/networking/kapi.md#c-__skb_header_release)). Any clone created from marked skb will get
[`sk_buff.hdr_len`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) populated with the available headroom.
If there's the only clone in existence it's able to modify the headroom
at will. The sequence of calls inside the transport layer is:

```text
<alloc skb>
skb_reserve()
__skb_header_release()
skb_clone()
// send the clone down the stack
```

This is not a very generic construct and it depends on the transport layers
doing the right thing. In practice there's usually only one payload-only skb.
Having multiple payload-only skbs with different lengths of hdr_len is not
possible. The payload-only skbs should never leave their owner.


<a id="rst-checksum-information"></a>

## Checksum information


The interface for checksum offload between the stack and networking drivers
is as follows...

**IP checksum related features**

Drivers advertise checksum offload capabilities in the features of a device.
From the stack's point of view these are capabilities offered by the driver.
A driver typically only advertises features that it is capable of offloading
to its device.

<table>
<caption>Checksum related device features</caption>
<tbody>
<tr>
<td>

`NETIF_F_HW_CSUM`

</td>
<td>

The driver (or its device) is able to compute one
IP (one's complement) checksum for any combination
of protocols or protocol layering. The checksum is
computed and set in a packet per the CHECKSUM_PARTIAL
interface (see below).

</td>
</tr>
<tr>
<td>

`NETIF_F_IP_CSUM`

</td>
<td>

Driver (device) is only able to checksum plain
TCP or UDP packets over IPv4. These are specifically
unencapsulated packets of the form IPv4|TCP or
IPv4|UDP where the Protocol field in the IPv4 header
is TCP or UDP. The IPv4 header may contain IP options.
This feature cannot be set in features for a device
with NETIF_F_HW_CSUM also set. This feature is being
DEPRECATED (see below).

</td>
</tr>
<tr>
<td>

`NETIF_F_IPV6_CSUM`

</td>
<td>

Driver (device) is only able to checksum plain
TCP or UDP packets over IPv6. These are specifically
unencapsulated packets of the form IPv6|TCP or
IPv6|UDP where the Next Header field in the IPv6
header is either TCP or UDP. IPv6 extension headers
are not supported with this feature. This feature
cannot be set in features for a device with
NETIF_F_HW_CSUM also set. This feature is being
DEPRECATED (see below).

</td>
</tr>
<tr>
<td>

`NETIF_F_RXCSUM`

</td>
<td>

Driver (device) performs receive checksum offload.
This flag is only used to disable the RX checksum
feature for a device. The stack will accept receive
checksum indication in packets received on a device
regardless of whether NETIF_F_RXCSUM is set.

</td>
</tr>
</tbody>
</table>

**Checksumming of received packets by device**

Indication of checksum verification is set in [`sk_buff.ip_summed`](/kernel/internals/networking/kapi.md#c-struct-sk_buff).
Possible values are:

- `CHECKSUM_NONE`

  Device did not checksum this packet e.g. due to lack of capabilities.
  The packet contains full (though not verified) checksum in packet but
  not in skb->csum. Thus, skb->csum is undefined in this case.

- `CHECKSUM_UNNECESSARY`

  The hardware you're dealing with doesn't calculate the full checksum
  (as in `CHECKSUM_COMPLETE`), but it does parse headers and verify checksums
  for specific protocols. For such packets it will set `CHECKSUM_UNNECESSARY`
  if their checksums are okay. [`sk_buff.csum`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) is still undefined in this case
  though. A driver or device must never modify the checksum field in the
  packet even if checksum is verified.

  `CHECKSUM_UNNECESSARY` is applicable to following protocols:

  - TCP: IPv6 and IPv4.
  - UDP: IPv4 and IPv6. A device may apply CHECKSUM_UNNECESSARY to a
    zero UDP checksum for either IPv4 or IPv6, the networking stack
    may perform further validation in this case.
  - GRE: only if the checksum is present in the header.
  - SCTP: indicates the CRC in SCTP header has been validated.
  - FCOE: indicates the CRC in FC frame has been validated.

  [`sk_buff.csum_level`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) indicates the number of consecutive checksums found in
  the packet minus one that have been verified as `CHECKSUM_UNNECESSARY`.
  For instance if a device receives an IPv6->UDP->GRE->IPv4->TCP packet
  and a device is able to verify the checksums for UDP (possibly zero),
  GRE (checksum flag is set) and TCP, [`sk_buff.csum_level`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) would be set to
  two. If the device were only able to verify the UDP checksum and not
  GRE, either because it doesn't support GRE checksum or because GRE
  checksum is bad, skb->csum_level would be set to zero (TCP checksum is
  not considered in this case).

- `CHECKSUM_COMPLETE`

  This is the most generic way. The device supplied checksum of the _whole_
  packet as seen by [`netif_rx()`](/kernel/internals/networking/kapi.md#c-netif_rx) and fills in [`sk_buff.csum`](/kernel/internals/networking/kapi.md#c-struct-sk_buff). This means the
  hardware doesn't need to parse L3/L4 headers to implement this.

  Notes:

  - Even if device supports only some protocols, but is able to produce
    skb->csum, it MUST use CHECKSUM_COMPLETE, not CHECKSUM_UNNECESSARY.
  - CHECKSUM_COMPLETE is not applicable to SCTP and FCoE protocols.

- `CHECKSUM_PARTIAL`

  A checksum is set up to be offloaded to a device as described in the
  output description for CHECKSUM_PARTIAL. This may occur on a packet
  received directly from another Linux OS, e.g., a virtualized Linux kernel
  on the same host, or it may be set in the input path in GRO or remote
  checksum offload. For the purposes of checksum verification, the checksum
  referred to by skb->csum_start + skb->csum_offset and any preceding
  checksums in the packet are considered verified. Any checksums in the
  packet that are after the checksum being offloaded are not considered to
  be verified.

**Checksumming on transmit for non-GSO**

The stack requests checksum offload in the [`sk_buff.ip_summed`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) for a packet.
Values are:

- `CHECKSUM_PARTIAL`

  The driver is required to checksum the packet as seen by `hard_start_xmit()`
  from [`sk_buff.csum_start`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) up to the end, and to record/write the checksum at
  offset [`sk_buff.csum_start`](/kernel/internals/networking/kapi.md#c-struct-sk_buff) + [`sk_buff.csum_offset`](/kernel/internals/networking/kapi.md#c-struct-sk_buff).
  A driver may verify that the
  csum_start and csum_offset values are valid values given the length and
  offset of the packet, but it should not attempt to validate that the
  checksum refers to a legitimate transport layer checksum -- it is the
  purview of the stack to validate that csum_start and csum_offset are set
  correctly.

  When the stack requests checksum offload for a packet, the driver MUST
  ensure that the checksum is set correctly. A driver can either offload the
  checksum calculation to the device, or call skb_checksum_help (in the case
  that the device does not support offload for a particular checksum).

  `NETIF_F_IP_CSUM` and `NETIF_F_IPV6_CSUM` are being deprecated in favor of
  `NETIF_F_HW_CSUM`. New devices should use `NETIF_F_HW_CSUM` to indicate
  checksum offload capability.
  `skb_csum_hwoffload_help()` can be called to resolve `CHECKSUM_PARTIAL` based
  on network device checksumming capabilities: if a packet does not match
  them, `skb_checksum_help()` or `skb_crc32c_help()` (depending on the value of
  [`sk_buff.csum_not_inet`](/kernel/internals/networking/kapi.md#c-struct-sk_buff), see crc)
  is called to resolve the checksum.

- `CHECKSUM_NONE`

  The skb was already checksummed by the protocol, or a checksum is not
  required.

- `CHECKSUM_UNNECESSARY`

  This has the same meaning as CHECKSUM_NONE for checksum offload on
  output.

- `CHECKSUM_COMPLETE`

  Not used in checksum output. If a driver observes a packet with this value
  set in skbuff, it should treat the packet as if `CHECKSUM_NONE` were set.

**Non-IP checksum (CRC) offloads**

<table>
<tbody>
<tr>
<td>

`NETIF_F_SCTP_CRC`

</td>
<td>

This feature indicates that a device is capable of
offloading the SCTP CRC in a packet. To perform this offload the stack
will set csum_start and csum_offset accordingly, set ip_summed to
`CHECKSUM_PARTIAL` and set csum_not_inet to 1, to provide an indication
in the skbuff that the `CHECKSUM_PARTIAL` refers to CRC32c.
A driver that supports both IP checksum offload and SCTP CRC32c offload
must verify which offload is configured for a packet by testing the
value of [`sk_buff.csum_not_inet`](/kernel/internals/networking/kapi.md#c-struct-sk_buff); `skb_crc32c_csum_help()` is provided to
resolve `CHECKSUM_PARTIAL` on skbs where csum_not_inet is set to 1.

</td>
</tr>
<tr>
<td>

`NETIF_F_FCOE_CRC`

</td>
<td>

This feature indicates that a device is capable of offloading the FCOE
CRC in a packet. To perform this offload the stack will set ip_summed
to `CHECKSUM_PARTIAL` and set csum_start and csum_offset
accordingly. Note that there is no indication in the skbuff that the
`CHECKSUM_PARTIAL` refers to an FCOE checksum, so a driver that supports
both IP checksum offload and FCOE CRC offload must verify which offload
is configured for a packet, presumably by inspecting packet headers.

</td>
</tr>
</tbody>
</table>

**Checksumming on output with GSO**

In the case of a GSO packet (`skb_is_gso()` is true), checksum offload
is implied by the SKB_GSO_* flags in gso_type. Most obviously, if the
gso_type is `SKB_GSO_TCPV4` or `SKB_GSO_TCPV6`, TCP checksum offload as
part of the GSO operation is implied. If a checksum is being offloaded
with GSO then ip_summed is `CHECKSUM_PARTIAL`, and both csum_start and
csum_offset are set to refer to the outermost checksum being offloaded
(two offloaded checksums are possible with UDP encapsulation).

---

# SMC Sysctl

_Peios Kernel / Internals / Networking_

> Setting SMC auto corking size: SMC auto corking is like TCP auto corking from the application's perspective of view. When applications do consecutive small write()/sendmsg() system calls, we try to coalesce these small writes as much as…

<a id="rst-smc-sysctl"></a>

<a id="rst-proc-sys-net-smc-variables"></a>

## /proc/sys/net/smc/\* Variables

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **autocorking_size - INTEGER**

  Setting SMC auto corking size: SMC auto corking is like TCP auto corking from the application's perspective of view. When applications do consecutive small write()/sendmsg() system calls, we try to coalesce these small writes as much as possible, to lower total amount of CDC and RDMA Write been sent. autocorking_size limits the maximum corked bytes that can be sent to the under device in 1 single sending. If set to 0, the SMC auto corking is disabled. Applications can still use TCP_CORK for optimal behavior when they know how/when to uncork their sockets.

  Default: 64K

- **smcr_buf_type - INTEGER**

  Controls which type of sndbufs and RMBs to use in later newly created SMC-R link group. Only for SMC-R.

  Default: 0 (physically contiguous sndbufs and RMBs)

  Possible values:

  - 0 - Use physically contiguous buffers

  - 1 - Use virtually contiguous buffers

  - 2 - Mixed use of the two types. Try physically contiguous buffers first. If not available, use virtually contiguous buffers then.

- **smcr_testlink_time - INTEGER**

  How frequently SMC-R link sends out TEST_LINK LLC messages to confirm viability, after the last activity of connections on it. Value 0 means disabling TEST_LINK.

  Default: 30 seconds.

- **wmem - INTEGER**

  Initial size of send buffer used by SMC sockets.

  The minimum value is 16KiB and there is no hard limit for max value, but only allowed 512KiB for SMC-R and 1MiB for SMC-D.

  Default: 64KiB

- **rmem - INTEGER**

  Initial size of receive buffer (RMB) used by SMC sockets.

  The minimum value is 16KiB and there is no hard limit for max value, but only allowed 512KiB for SMC-R and 1MiB for SMC-D.

  Default: 64KiB

- **smcr_max_links_per_lgr - INTEGER**

  Controls the max number of links can be added to a SMC-R link group. Notice that the actual number of the links added to a SMC-R link group depends on the number of RDMA devices exist in the system. The acceptable value ranges from 1 to 2. Only for SMC-R v2.1 and later.

  Default: 2

- **smcr_max_conns_per_lgr - INTEGER**

  Controls the max number of connections can be added to a SMC-R link group. The acceptable value ranges from 16 to 255. Only for SMC-R v2.1 and later.

  Default: 255

- **smcr_max_send_wr - INTEGER**

  So-called work request buffers are SMCR link (and RDMA queue pair) level resources necessary for performing RDMA operations. Since up to 255 connections can share a link group and thus also a link and the number of the work request buffers is decided when the link is allocated, depending on the workload it can be a bottleneck in a sense that threads have to wait for work request buffers to become available. Before the introduction of this control the maximal number of work request buffers available on the send path used to be hard coded to 16. With this control it becomes configurable. The acceptable range is between 2 and 2048.

  Please be aware that all the buffers need to be allocated as a physically continuous array in which each element is a single buffer and has the size of SMC_WR_BUF_SIZE (48) bytes. If the allocation fails, we keep retrying with half of the buffer count until it is ether successful or (unlikely) we dip below the old hard coded value which is 16 where we give up much like before having this control.

  Default: 16

- **smcr_max_recv_wr - INTEGER**

  So-called work request buffers are SMCR link (and RDMA queue pair) level resources necessary for performing RDMA operations. Since up to 255 connections can share a link group and thus also a link and the number of the work request buffers is decided when the link is allocated, depending on the workload it can be a bottleneck in a sense that threads have to wait for work request buffers to become available. Before the introduction of this control the maximal number of work request buffers available on the receive path used to be hard coded to 16. With this control it becomes configurable. The acceptable range is between 2 and 2048.

  Please be aware that all the buffers need to be allocated as a physically continuous array in which each element is a single buffer and has the size of SMC_WR_BUF_SIZE (48) bytes. If the allocation fails, we keep retrying with half of the buffer count until it is ether successful or (unlikely) we dip below the old hard coded value which is 16 where we give up much like before having this control.

  Default: 48

---

# SNMP counter

_Peios Kernel / Internals / Networking_

> This document explains the meaning of SNMP counters.

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-snmp-counter"></a>

This document explains the meaning of SNMP counters.

<a id="rst-general-ipv4-counters"></a>

## General IPv4 counters

All layer 4 packets and ICMP packets will change these counters, but these counters won't be changed by layer 2 packets (such as STP) or ARP packets.

- IpInReceives

Defined in [RFC1213 ipInReceives](<https://tools.ietf.org/html/rfc1213#page-26>)

<a id="rst-rfc1213-ipinreceives"></a>



The number of packets received by the IP layer. It gets increasing at the beginning of ip\_rcv function, always be updated together with IpExtInOctets. It will be increased even if the packet is dropped later (e.g. due to the IP header is invalid or the checksum is wrong and so on).  It indicates the number of aggregated segments after GRO/LRO.

- IpInDelivers

Defined in [RFC1213 ipInDelivers](<https://tools.ietf.org/html/rfc1213#page-28>)

<a id="rst-rfc1213-ipindelivers"></a>



The number of packets delivers to the upper layer protocols. E.g. TCP, UDP, ICMP and so on. If no one listens on a raw socket, only kernel supported protocols will be delivered, if someone listens on the raw socket, all valid IP packets will be delivered.

- IpOutRequests

Defined in [RFC1213 ipOutRequests](<https://tools.ietf.org/html/rfc1213#page-28>)

<a id="rst-rfc1213-ipoutrequests"></a>



The number of packets sent via IP layer, for both single cast and multicast packets, and would always be updated together with IpExtOutOctets.

- IpExtInOctets and IpExtOutOctets

They are Linux kernel extensions, no RFC definitions. Please note, RFC1213 indeed defines ifInOctets  and ifOutOctets, but they are different things. The ifInOctets and ifOutOctets include the MAC layer header size but IpExtInOctets and IpExtOutOctets don't, they only include the IP layer header and the IP layer data.

- IpExtInNoECTPkts, IpExtInECT1Pkts, IpExtInECT0Pkts, IpExtInCEPkts

They indicate the number of four kinds of ECN IP packets, please refer [Explicit Congestion Notification](<https://tools.ietf.org/html/rfc3168#page-6>) for more details.

<a id="rst-explicit-congestion-notification"></a>



These 4 counters calculate how many packets received per ECN status. They count the real frame number regardless the LRO/GRO. So for the same packet, you might find that IpInReceives count 1, but IpExtInNoECTPkts counts 2 or more.

- IpInHdrErrors

Defined in [RFC1213 ipInHdrErrors](<https://tools.ietf.org/html/rfc1213#page-27>). It indicates the packet is dropped due to the IP header error. It might happen in both IP input and IP forward paths.

<a id="rst-rfc1213-ipinhdrerrors"></a>



- IpInAddrErrors

Defined in [RFC1213 ipInAddrErrors](<https://tools.ietf.org/html/rfc1213#page-27>). It will be increased in two scenarios: (1) The IP address is invalid. (2) The destination IP address is not a local address and IP forwarding is not enabled

<a id="rst-rfc1213-ipinaddrerrors"></a>



- IpExtInNoRoutes

This counter means the packet is dropped when the IP stack receives a packet and can't find a route for it from the route table. It might happen when IP forwarding is enabled and the destination IP address is not a local address and there is no route for the destination IP address.

- IpInUnknownProtos

Defined in [RFC1213 ipInUnknownProtos](<https://tools.ietf.org/html/rfc1213#page-27>). It will be increased if the layer 4 protocol is unsupported by kernel. If an application is using raw socket, kernel will always deliver the packet to the raw socket and this counter won't be increased.

<a id="rst-rfc1213-ipinunknownprotos"></a>



- IpExtInTruncatedPkts

For IPv4 packet, it means the actual data size is smaller than the "Total Length" field in the IPv4 header.

- IpInDiscards

Defined in [RFC1213 ipInDiscards](<https://tools.ietf.org/html/rfc1213#page-28>). It indicates the packet is dropped in the IP receiving path and due to kernel internal reasons (e.g. no enough memory).

<a id="rst-rfc1213-ipindiscards"></a>



- IpOutDiscards

Defined in [RFC1213 ipOutDiscards](<https://tools.ietf.org/html/rfc1213#page-28>). It indicates the packet is dropped in the IP sending path and due to kernel internal reasons.

<a id="rst-rfc1213-ipoutdiscards"></a>



- IpOutNoRoutes

Defined in [RFC1213 ipOutNoRoutes](<https://tools.ietf.org/html/rfc1213#page-29>). It indicates the packet is dropped in the IP sending path and no route is found for it.

<a id="rst-rfc1213-ipoutnoroutes"></a>



<a id="rst-icmp-counters"></a>

## ICMP counters

- IcmpInMsgs and IcmpOutMsgs

Defined by [RFC1213 icmpInMsgs](<https://tools.ietf.org/html/rfc1213#page-41>) and [RFC1213 icmpOutMsgs](<https://tools.ietf.org/html/rfc1213#page-43>)

<a id="rst-rfc1213-icmpinmsgs"></a>



<a id="rst-rfc1213-icmpoutmsgs"></a>



As mentioned in the RFC1213, these two counters include errors, they would be increased even if the ICMP packet has an invalid type. The ICMP output path will check the header of a raw socket, so the IcmpOutMsgs would still be updated if the IP header is constructed by a userspace program.

- ICMP named types

These counters include most of common ICMP types, they are:  
IcmpInDestUnreachs: [RFC1213 icmpInDestUnreachs](<https://tools.ietf.org/html/rfc1213#page-41>)  
IcmpInTimeExcds: [RFC1213 icmpInTimeExcds](<https://tools.ietf.org/html/rfc1213#page-41>)  
IcmpInParmProbs: [RFC1213 icmpInParmProbs](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInSrcQuenchs: [RFC1213 icmpInSrcQuenchs](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInRedirects: [RFC1213 icmpInRedirects](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInEchos: [RFC1213 icmpInEchos](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInEchoReps: [RFC1213 icmpInEchoReps](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInTimestamps: [RFC1213 icmpInTimestamps](<https://tools.ietf.org/html/rfc1213#page-42>)  
IcmpInTimestampReps: [RFC1213 icmpInTimestampReps](<https://tools.ietf.org/html/rfc1213#page-43>)  
IcmpInAddrMasks: [RFC1213 icmpInAddrMasks](<https://tools.ietf.org/html/rfc1213#page-43>)  
IcmpInAddrMaskReps: [RFC1213 icmpInAddrMaskReps](<https://tools.ietf.org/html/rfc1213#page-43>)  
IcmpOutDestUnreachs: [RFC1213 icmpOutDestUnreachs](<https://tools.ietf.org/html/rfc1213#page-44>)  
IcmpOutTimeExcds: [RFC1213 icmpOutTimeExcds](<https://tools.ietf.org/html/rfc1213#page-44>)  
IcmpOutParmProbs: [RFC1213 icmpOutParmProbs](<https://tools.ietf.org/html/rfc1213#page-44>)  
IcmpOutSrcQuenchs: [RFC1213 icmpOutSrcQuenchs](<https://tools.ietf.org/html/rfc1213#page-44>)  
IcmpOutRedirects: [RFC1213 icmpOutRedirects](<https://tools.ietf.org/html/rfc1213#page-44>)  
IcmpOutEchos: [RFC1213 icmpOutEchos](<https://tools.ietf.org/html/rfc1213#page-45>)  
IcmpOutEchoReps: [RFC1213 icmpOutEchoReps](<https://tools.ietf.org/html/rfc1213#page-45>)  
IcmpOutTimestamps: [RFC1213 icmpOutTimestamps](<https://tools.ietf.org/html/rfc1213#page-45>)  
IcmpOutTimestampReps: [RFC1213 icmpOutTimestampReps](<https://tools.ietf.org/html/rfc1213#page-45>)  
IcmpOutAddrMasks: [RFC1213 icmpOutAddrMasks](<https://tools.ietf.org/html/rfc1213#page-45>)  
IcmpOutAddrMaskReps: [RFC1213 icmpOutAddrMaskReps](<https://tools.ietf.org/html/rfc1213#page-46>)

<a id="rst-rfc1213-icmpindestunreachs"></a>



<a id="rst-rfc1213-icmpintimeexcds"></a>



<a id="rst-rfc1213-icmpinparmprobs"></a>



<a id="rst-rfc1213-icmpinsrcquenchs"></a>



<a id="rst-rfc1213-icmpinredirects"></a>



<a id="rst-rfc1213-icmpinechos"></a>



<a id="rst-rfc1213-icmpinechoreps"></a>



<a id="rst-rfc1213-icmpintimestamps"></a>



<a id="rst-rfc1213-icmpintimestampreps"></a>



<a id="rst-rfc1213-icmpinaddrmasks"></a>



<a id="rst-rfc1213-icmpinaddrmaskreps"></a>



<a id="rst-rfc1213-icmpoutdestunreachs"></a>



<a id="rst-rfc1213-icmpouttimeexcds"></a>



<a id="rst-rfc1213-icmpoutparmprobs"></a>



<a id="rst-rfc1213-icmpoutsrcquenchs"></a>



<a id="rst-rfc1213-icmpoutredirects"></a>



<a id="rst-rfc1213-icmpoutechos"></a>



<a id="rst-rfc1213-icmpoutechoreps"></a>



<a id="rst-rfc1213-icmpouttimestamps"></a>



<a id="rst-rfc1213-icmpouttimestampreps"></a>



<a id="rst-rfc1213-icmpoutaddrmasks"></a>



<a id="rst-rfc1213-icmpoutaddrmaskreps"></a>



Every ICMP type has two counters: 'In' and 'Out'. E.g., for the ICMP Echo packet, they are IcmpInEchos and IcmpOutEchos. Their meanings are straightforward. The 'In' counter means kernel receives such a packet and the 'Out' counter means kernel sends such a packet.

- ICMP numeric types

They are IcmpMsgInType\[N\] and IcmpMsgOutType\[N\], the \[N\] indicates the ICMP type number. These counters track all kinds of ICMP packets. The ICMP type number definition could be found in the [ICMP parameters](<https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml>) document.

<a id="rst-icmp-parameters"></a>



For example, if the Linux kernel sends an ICMP Echo packet, the IcmpMsgOutType8 would increase 1. And if kernel gets an ICMP Echo Reply packet, IcmpMsgInType0 would increase 1.

- IcmpInCsumErrors

This counter indicates the checksum of the ICMP packet is wrong. Kernel verifies the checksum after updating the IcmpInMsgs and before updating IcmpMsgInType\[N\]. If a packet has bad checksum, the IcmpInMsgs would be updated but none of IcmpMsgInType\[N\] would be updated.

- IcmpInErrors and IcmpOutErrors

Defined by [RFC1213 icmpInErrors](<https://tools.ietf.org/html/rfc1213#page-41>) and [RFC1213 icmpOutErrors](<https://tools.ietf.org/html/rfc1213#page-43>)

<a id="rst-rfc1213-icmpinerrors"></a>



<a id="rst-rfc1213-icmpouterrors"></a>



When an error occurs in the ICMP packet handler path, these two counters would be updated. The receiving packet path use IcmpInErrors and the sending packet path use IcmpOutErrors. When IcmpInCsumErrors is increased, IcmpInErrors would always be increased too.

<a id="rst-relationship-of-the-icmp-counters"></a>

### relationship of the ICMP counters

The sum of IcmpMsgOutType\[N\] is always equal to IcmpOutMsgs, as they are updated at the same time. The sum of IcmpMsgInType\[N\] plus IcmpInErrors should be equal or larger than IcmpInMsgs. When kernel receives an ICMP packet, kernel follows below logic:

1. increase IcmpInMsgs

2. if has any error, update IcmpInErrors and finish the process

3. update IcmpMsgOutType\[N\]

4. handle the packet depending on the type, if has any error, update IcmpInErrors and finish the process

So if all errors occur in step (2), IcmpInMsgs should be equal to the sum of IcmpMsgOutType\[N\] plus IcmpInErrors. If all errors occur in step (4), IcmpInMsgs should be equal to the sum of IcmpMsgOutType\[N\]. If the errors occur in both step (2) and step (4), IcmpInMsgs should be less than the sum of IcmpMsgOutType\[N\] plus IcmpInErrors.

<a id="rst-general-tcp-counters"></a>

## General TCP counters

- TcpInSegs

Defined in [RFC1213 tcpInSegs](<https://tools.ietf.org/html/rfc1213#page-48>)

<a id="rst-rfc1213-tcpinsegs"></a>



The number of packets received by the TCP layer. As mentioned in RFC1213, it includes the packets received in error, such as checksum error, invalid TCP header and so on. Only one error won't be included: if the layer 2 destination address is not the NIC's layer 2 address. It might happen if the packet is a multicast or broadcast packet, or the NIC is in promiscuous mode. In these situations, the packets would be delivered to the TCP layer, but the TCP layer will discard these packets before increasing TcpInSegs. The TcpInSegs counter isn't aware of GRO. So if two packets are merged by GRO, the TcpInSegs counter would only increase 1.

- TcpOutSegs

Defined in [RFC1213 tcpOutSegs](<https://tools.ietf.org/html/rfc1213#page-48>)

<a id="rst-rfc1213-tcpoutsegs"></a>



The number of packets sent by the TCP layer. As mentioned in RFC1213, it excludes the retransmitted packets. But it includes the SYN, ACK and RST packets. Doesn't like TcpInSegs, the TcpOutSegs is aware of GSO, so if a packet would be split to 2 by GSO, TcpOutSegs will increase 2.

- TcpActiveOpens

Defined in [RFC1213 tcpActiveOpens](<https://tools.ietf.org/html/rfc1213#page-47>)

<a id="rst-rfc1213-tcpactiveopens"></a>



It means the TCP layer sends a SYN, and come into the SYN-SENT state. Every time TcpActiveOpens increases 1, TcpOutSegs should always increase 1.

- TcpPassiveOpens

Defined in [RFC1213 tcpPassiveOpens](<https://tools.ietf.org/html/rfc1213#page-47>)

<a id="rst-rfc1213-tcppassiveopens"></a>



It means the TCP layer receives a SYN, replies a SYN+ACK, come into the SYN-RCVD state.

- TcpExtTCPRcvCoalesce

When packets are received by the TCP layer and are not be read by the application, the TCP layer will try to merge them. This counter indicate how many packets are merged in such situation. If GRO is enabled, lots of packets would be merged by GRO, these packets wouldn't be counted to TcpExtTCPRcvCoalesce.

- TcpExtTCPAutoCorking

When sending packets, the TCP layer will try to merge small packets to a bigger one. This counter increase 1 for every packet merged in such situation. Please refer to the LWN article for more details: [https://lwn.net/Articles/576263/](<https://lwn.net/Articles/576263/>)

- TcpExtTCPOrigDataSent

This counter is explained by kernel commit f19c29e3e391, I pasted the explanation below:



```text
TCPOrigDataSent: number of outgoing packets with original data (excluding
retransmission but including data-in-SYN). This counter is different from
TcpOutSegs because TcpOutSegs also tracks pure ACKs. TCPOrigDataSent is
more useful to track the TCP retransmission rate.
```

- TCPSynRetrans

This counter is explained by kernel commit f19c29e3e391, I pasted the explanation below:



```text
TCPSynRetrans: number of SYN and SYN/ACK retransmits to break down
retransmissions into SYN, fast-retransmits, timeout retransmits, etc.
```

- TCPFastOpenActiveFail

This counter is explained by kernel commit f19c29e3e391, I pasted the explanation below:



```text
TCPFastOpenActiveFail: Fast Open attempts (SYN/data) failed because
the remote does not accept it or the attempts timed out.
```

- TcpExtListenOverflows and TcpExtListenDrops

When kernel receives a SYN from a client, and if the TCP accept queue is full, kernel will drop the SYN and add 1 to TcpExtListenOverflows. At the same time kernel will also add 1 to TcpExtListenDrops. When a TCP socket is in LISTEN state, and kernel need to drop a packet, kernel would always add 1 to TcpExtListenDrops. So increase TcpExtListenOverflows would let TcpExtListenDrops increasing at the same time, but TcpExtListenDrops would also increase without TcpExtListenOverflows increasing, e.g. a memory allocation fail would also let TcpExtListenDrops increase.

Note: The above explanation is based on kernel 4.10 or above version, on an old kernel, the TCP stack has different behavior when TCP accept queue is full. On the old kernel, TCP stack won't drop the SYN, it would complete the 3-way handshake. As the accept queue is full, TCP stack will keep the socket in the TCP half-open queue. As it is in the half open queue, TCP stack will send SYN+ACK on an exponential backoff timer, after client replies ACK, TCP stack checks whether the accept queue is still full, if it is not full, moves the socket to the accept queue, if it is full, keeps the socket in the half-open queue, at next time client replies ACK, this socket will get another chance to move to the accept queue.

<a id="rst-tcp-fast-open"></a>

## TCP Fast Open

- TcpEstabResets

Defined in [RFC1213 tcpEstabResets](<https://tools.ietf.org/html/rfc1213#page-48>).

<a id="rst-rfc1213-tcpestabresets"></a>



- TcpAttemptFails

Defined in [RFC1213 tcpAttemptFails](<https://tools.ietf.org/html/rfc1213#page-48>).

<a id="rst-rfc1213-tcpattemptfails"></a>



- TcpOutRsts

Defined in [RFC1213 tcpOutRsts](<https://tools.ietf.org/html/rfc1213#page-52>). The RFC says this counter indicates the 'segments sent containing the RST flag', but in linux kernel, this counter indicates the segments kernel tried to send. The sending process might be failed due to some errors (e.g. memory alloc failed).

<a id="rst-rfc1213-tcpoutrsts"></a>



- TcpExtTCPSpuriousRtxHostQueues

When the TCP stack wants to retransmit a packet, and finds that packet is not lost in the network, but the packet is not sent yet, the TCP stack would give up the retransmission and update this counter. It might happen if a packet stays too long time in a qdisc or driver queue.

- TcpEstabResets

The socket receives a RST packet in Establish or CloseWait state.

- TcpExtTCPKeepAlive

This counter indicates many keepalive packets were sent. The keepalive won't be enabled by default. A userspace program could enable it by setting the SO\_KEEPALIVE socket option.

- TcpExtTCPSpuriousRTOs

The spurious retransmission timeout detected by the [F-RTO](<https://tools.ietf.org/html/rfc5682>) algorithm.

<a id="rst-f-rto"></a>



<a id="rst-tcp-fast-path"></a>

## TCP Fast Path

When kernel receives a TCP packet, it has two paths to handler the packet, one is fast path, another is slow path. The comment in kernel code provides a good explanation of them, I pasted them below:



```text
It is split into a fast path and a slow path. The fast path is
disabled when:

- A zero window was announced from us
- zero window probing
  is only handled properly on the slow path.
- Out of order segments arrived.
- Urgent data is expected.
- There is no buffer space left
- Unexpected TCP flags/window values/header lengths are received
  (detected by checking the TCP header against pred_flags)
- Data is sent in both directions. The fast path only supports pure senders
  or pure receivers (this means either the sequence number or the ack
  value must stay constant)
- Unexpected TCP option.
```

Kernel will try to use fast path unless any of the above conditions are satisfied. If the packets are out of order, kernel will handle them in slow path, which means the performance might be not very good. Kernel would also come into slow path if the "Delayed ack" is used, because when using "Delayed ack", the data is sent in both directions. When the TCP window scale option is not used, kernel will try to enable fast path immediately when the connection comes into the established state, but if the TCP window scale option is used, kernel will disable the fast path at first, and try to enable it after kernel receives packets.

- TcpExtTCPPureAcks and TcpExtTCPHPAcks

If a packet set ACK flag and has no data, it is a pure ACK packet, if kernel handles it in the fast path, TcpExtTCPHPAcks will increase 1, if kernel handles it in the slow path, TcpExtTCPPureAcks will increase 1.

- TcpExtTCPHPHits

If a TCP packet has data (which means it is not a pure ACK packet), and this packet is handled in the fast path, TcpExtTCPHPHits will increase 1.

<a id="rst-tcp-abort"></a>

## TCP abort

- TcpExtTCPAbortOnData

It means TCP layer has data in flight, but need to close the connection. So TCP layer sends a RST to the other side, indicate the connection is not closed very graceful. An easy way to increase this counter is using the SO\_LINGER option. Please refer to the SO\_LINGER section of the [socket man page](<http://man7.org/linux/man-pages/man7/socket.7.html>):

<a id="rst-socket-man-page"></a>



By default, when an application closes a connection, the close function will return immediately and kernel will try to send the in-flight data async. If you use the SO\_LINGER option, set l\_onoff to 1, and l\_linger to a positive number, the close function won't return immediately, but wait for the in-flight data are acked by the other side, the max wait time is l\_linger seconds. If set l\_onoff to 1 and set l\_linger to 0, when the application closes a connection, kernel will send a RST immediately and increase the TcpExtTCPAbortOnData counter.

- TcpExtTCPAbortOnClose

This counter means the application has unread data in the TCP layer when the application wants to close the TCP connection. In such a situation, kernel will send a RST to the other side of the TCP connection.

- TcpExtTCPAbortOnMemory

When an application closes a TCP connection, kernel still need to track the connection, let it complete the TCP disconnect process. E.g. an app calls the close method of a socket, kernel sends fin to the other side of the connection, then the app has no relationship with the socket any more, but kernel need to keep the socket, this socket becomes an orphan socket, kernel waits for the reply of the other side, and would come to the TIME\_WAIT state finally. When kernel has no enough memory to keep the orphan socket, kernel would send an RST to the other side, and delete the socket, in such situation, kernel will increase 1 to the TcpExtTCPAbortOnMemory. Two conditions would trigger TcpExtTCPAbortOnMemory:

1\. the memory used by the TCP protocol is higher than the third value of the tcp\_mem. Please refer the tcp\_mem section in the [TCP man page](<http://man7.org/linux/man-pages/man7/tcp.7.html>):

<a id="rst-tcp-man-page"></a>



2. the orphan socket count is higher than net.ipv4.tcp\_max\_orphans

- TcpExtTCPAbortOnTimeout

This counter will increase when any of the TCP timers expire. In such situation, kernel won't send RST, just give up the connection.

- TcpExtTCPAbortOnLinger

When a TCP connection comes into FIN\_WAIT\_2 state, instead of waiting for the fin packet from the other side, kernel could send a RST and delete the socket immediately. This is not the default behavior of Linux kernel TCP stack. By configuring the TCP\_LINGER2 socket option, you could let kernel follow this behavior.

- TcpExtTCPAbortFailed

The kernel TCP layer will send RST if the [RFC2525 2.17 section](<https://tools.ietf.org/html/rfc2525#page-50>) is satisfied. If an internal error occurs during this process, TcpExtTCPAbortFailed will be increased.

<a id="rst-rfc2525-2-17-section"></a>



<a id="rst-tcp-hybrid-slow-start"></a>

## TCP Hybrid Slow Start

The Hybrid Slow Start algorithm is an enhancement of the traditional TCP congestion window Slow Start algorithm. It uses two pieces of information to detect whether the max bandwidth of the TCP path is approached. The two pieces of information are ACK train length and increase in packet delay. For detail information, please refer the [Hybrid Slow Start paper](<https://pdfs.semanticscholar.org/25e9/ef3f03315782c7f1cbcd31b587857adae7d1.pdf>). Either ACK train length or packet delay hits a specific threshold, the congestion control algorithm will come into the Congestion Avoidance state. Until v4.20, two congestion control algorithms are using Hybrid Slow Start, they are cubic (the default congestion control algorithm) and cdg. Four snmp counters relate with the Hybrid Slow Start algorithm.

<a id="rst-hybrid-slow-start-paper"></a>



- TcpExtTCPHystartTrainDetect

How many times the ACK train length threshold is detected

- TcpExtTCPHystartTrainCwnd

The sum of CWND detected by ACK train length. Dividing this value by TcpExtTCPHystartTrainDetect is the average CWND which detected by the ACK train length.

- TcpExtTCPHystartDelayDetect

How many times the packet delay threshold is detected.

- TcpExtTCPHystartDelayCwnd

The sum of CWND detected by packet delay. Dividing this value by TcpExtTCPHystartDelayDetect is the average CWND which detected by the packet delay.

<a id="rst-tcp-retransmission-and-congestion-control"></a>

## TCP retransmission and congestion control

The TCP protocol has two retransmission mechanisms: SACK and fast recovery. They are exclusive with each other. When SACK is enabled, the kernel TCP stack would use SACK, or kernel would use fast recovery. The SACK is a TCP option, which is defined in [RFC2018](<https://tools.ietf.org/html/rfc2018>), the fast recovery is defined in [RFC6582](<https://tools.ietf.org/html/rfc6582>), which is also called 'Reno'.

The TCP congestion control is a big and complex topic. To understand the related snmp counter, we need to know the states of the congestion control state machine. There are 5 states: Open, Disorder, CWR, Recovery and Loss. For details about these states, please refer page 5 and page 6 of this document: [https://pdfs.semanticscholar.org/0e9c/968d09ab2e53e24c4dca5b2d67c7f7140f8e.pdf](<https://pdfs.semanticscholar.org/0e9c/968d09ab2e53e24c4dca5b2d67c7f7140f8e.pdf>)

<a id="rst-rfc2018"></a>



<a id="rst-rfc6582"></a>



- TcpExtTCPRenoRecovery and TcpExtTCPSackRecovery

When the congestion control comes into Recovery state, if sack is used, TcpExtTCPSackRecovery increases 1, if sack is not used, TcpExtTCPRenoRecovery increases 1. These two counters mean the TCP stack begins to retransmit the lost packets.

- TcpExtTCPSACKReneging

A packet was acknowledged by SACK, but the receiver has dropped this packet, so the sender needs to retransmit this packet. In this situation, the sender adds 1 to TcpExtTCPSACKReneging. A receiver could drop a packet which has been acknowledged by SACK, although it is unusual, it is allowed by the TCP protocol. The sender doesn't really know what happened on the receiver side. The sender just waits until the RTO expires for this packet, then the sender assumes this packet has been dropped by the receiver.

- TcpExtTCPRenoReorder

The reorder packet is detected by fast recovery. It would only be used if SACK is disabled. The fast recovery algorithm detects recorder by the duplicate ACK number. E.g., if retransmission is triggered, and the original retransmitted packet is not lost, it is just out of order, the receiver would acknowledge multiple times, one for the retransmitted packet, another for the arriving of the original out of order packet. Thus the sender would find more ACks than its expectation, and the sender knows out of order occurs.

- TcpExtTCPTSReorder

The reorder packet is detected when a hole is filled. E.g., assume the sender sends packet 1,2,3,4,5, and the receiving order is 1,2,4,5,3. When the sender receives the ACK of packet 3 (which will fill the hole), two conditions will let TcpExtTCPTSReorder increase 1: (1) if the packet 3 is not re-retransmitted yet. (2) if the packet 3 is retransmitted but the timestamp of the packet 3's ACK is earlier than the retransmission timestamp.

- TcpExtTCPSACKReorder

The reorder packet detected by SACK. The SACK has two methods to detect reorder: (1) DSACK is received by the sender. It means the sender sends the same packet more than one times. And the only reason is the sender believes an out of order packet is lost so it sends the packet again. (2) Assume packet 1,2,3,4,5 are sent by the sender, and the sender has received SACKs for packet 2 and 5, now the sender receives SACK for packet 4 and the sender doesn't retransmit the packet yet, the sender would know packet 4 is out of order. The TCP stack of kernel will increase TcpExtTCPSACKReorder for both of the above scenarios.

- TcpExtTCPSlowStartRetrans

The TCP stack wants to retransmit a packet and the congestion control state is 'Loss'.

- TcpExtTCPFastRetrans

The TCP stack wants to retransmit a packet and the congestion control state is not 'Loss'.

- TcpExtTCPLostRetransmit

A SACK points out that a retransmission packet is lost again.

- TcpExtTCPRetransFail

The TCP stack tries to deliver a retransmission packet to lower layers but the lower layers return an error.

- TcpExtTCPSynRetrans

The TCP stack retransmits a SYN packet.

<a id="rst-dsack"></a>

## DSACK

The DSACK is defined in [RFC2883](<https://tools.ietf.org/html/rfc2883>). The receiver uses DSACK to report duplicate packets to the sender. There are two kinds of duplications: (1) a packet which has been acknowledged is duplicate. (2) an out of order packet is duplicate. The TCP stack counts these two kinds of duplications on both receiver side and sender side.

<a id="rst-rfc2883"></a>



- TcpExtTCPDSACKOldSent

The TCP stack receives a duplicate packet which has been acked, so it sends a DSACK to the sender.

- TcpExtTCPDSACKOfoSent

The TCP stack receives an out of order duplicate packet, so it sends a DSACK to the sender.

- TcpExtTCPDSACKRecv

The TCP stack receives a DSACK, which indicates an acknowledged duplicate packet is received.

- TcpExtTCPDSACKOfoRecv

The TCP stack receives a DSACK, which indicate an out of order duplicate packet is received.

<a id="rst-invalid-sack-and-dsack"></a>

## invalid SACK and DSACK

When a SACK (or DSACK) block is invalid, a corresponding counter would be updated. The validation method is base on the start/end sequence number of the SACK block. For more details, please refer the comment of the function tcp\_is\_sackblock\_valid in the kernel source code. A SACK option could have up to 4 blocks, they are checked individually. E.g., if 3 blocks of a SACk is invalid, the corresponding counter would be updated 3 times. The comment of commit 18f02545a9a1 ("\[TCP\] MIB: Add counters for discarded SACK blocks") has additional explanation:

- TcpExtTCPSACKDiscard

This counter indicates how many SACK blocks are invalid. If the invalid SACK block is caused by ACK recording, the TCP stack will only ignore it and won't update this counter.

- TcpExtTCPDSACKIgnoredOld and TcpExtTCPDSACKIgnoredNoUndo

When a DSACK block is invalid, one of these two counters would be updated. Which counter will be updated depends on the undo\_marker flag of the TCP socket. If the undo\_marker is not set, the TCP stack isn't likely to re-transmit any packets, and we still receive an invalid DSACK block, the reason might be that the packet is duplicated in the middle of the network. In such scenario, TcpExtTCPDSACKIgnoredNoUndo will be updated. If the undo\_marker is set, TcpExtTCPDSACKIgnoredOld will be updated. As implied in its name, it might be an old packet.

<a id="rst-sack-shift"></a>

## SACK shift

The linux networking stack stores data in sk\_buff struct (skb for short). If a SACK block acrosses multiple skb, the TCP stack will try to re-arrange data in these skb. E.g. if a SACK block acknowledges seq 10 to 15, skb1 has seq 10 to 13, skb2 has seq 14 to 20. The seq 14 and 15 in skb2 would be moved to skb1. This operation is 'shift'. If a SACK block acknowledges seq 10 to 20, skb1 has seq 10 to 13, skb2 has seq 14 to 20. All data in skb2 will be moved to skb1, and skb2 will be discard, this operation is 'merge'.

- TcpExtTCPSackShifted

A skb is shifted

- TcpExtTCPSackMerged

A skb is merged

- TcpExtTCPSackShiftFallback

A skb should be shifted or merged, but the TCP stack doesn't do it for some reasons.

<a id="rst-tcp-out-of-order"></a>

## TCP out of order

- TcpExtTCPOFOQueue

The TCP layer receives an out of order packet and has enough memory to queue it.

- TcpExtTCPOFODrop

The TCP layer receives an out of order packet but doesn't have enough memory, so drops it. Such packets won't be counted into TcpExtTCPOFOQueue.

- TcpExtTCPOFOMerge

The received out of order packet has an overlay with the previous packet. the overlay part will be dropped. All of TcpExtTCPOFOMerge packets will also be counted into TcpExtTCPOFOQueue.

<a id="rst-tcp-paws"></a>

## TCP PAWS

PAWS (Protection Against Wrapped Sequence numbers) is an algorithm which is used to drop old packets. It depends on the TCP timestamps. For detail information, please refer the [timestamp wiki](<https://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_timestamps>) and the [RFC of PAWS](<https://tools.ietf.org/html/rfc1323#page-17>).

<a id="rst-rfc-of-paws"></a>



<a id="rst-timestamp-wiki"></a>



- TcpExtPAWSActive

Packets are dropped by PAWS in Syn-Sent status.

- TcpExtPAWSEstab

Packets are dropped by PAWS in any status other than Syn-Sent.

<a id="rst-tcp-ack-skip"></a>

## TCP ACK skip

In some scenarios, kernel would avoid sending duplicate ACKs too frequently. Please find more details in the tcp\_invalid\_ratelimit section of the [sysctl document](<https://www.kernel.org/doc/Documentation/networking/ip-sysctl.rst>). When kernel decides to skip an ACK due to tcp\_invalid\_ratelimit, kernel would update one of below counters to indicate the ACK is skipped in which scenario. The ACK would only be skipped if the received packet is either a SYN packet or it has no data.

<a id="rst-sysctl-document"></a>



- TcpExtTCPACKSkippedSynRecv

The ACK is skipped in Syn-Recv status. The Syn-Recv status means the TCP stack receives a SYN and replies SYN+ACK. Now the TCP stack is waiting for an ACK. Generally, the TCP stack doesn't need to send ACK in the Syn-Recv status. But in several scenarios, the TCP stack need to send an ACK. E.g., the TCP stack receives the same SYN packet repeately, the received packet does not pass the PAWS check, or the received packet sequence number is out of window. In these scenarios, the TCP stack needs to send ACK. If the ACk sending frequency is higher than tcp\_invalid\_ratelimit allows, the TCP stack will skip sending ACK and increase TcpExtTCPACKSkippedSynRecv.

- TcpExtTCPACKSkippedPAWS

The ACK is skipped due to PAWS (Protect Against Wrapped Sequence numbers) check fails. If the PAWS check fails in Syn-Recv, Fin-Wait-2 or Time-Wait statuses, the skipped ACK would be counted to TcpExtTCPACKSkippedSynRecv, TcpExtTCPACKSkippedFinWait2 or TcpExtTCPACKSkippedTimeWait. In all other statuses, the skipped ACK would be counted to TcpExtTCPACKSkippedPAWS.

- TcpExtTCPACKSkippedSeq

The sequence number is out of window and the timestamp passes the PAWS check and the TCP status is not Syn-Recv, Fin-Wait-2, and Time-Wait.

- TcpExtTCPACKSkippedFinWait2

The ACK is skipped in Fin-Wait-2 status, the reason would be either PAWS check fails or the received sequence number is out of window.

- TcpExtTCPACKSkippedTimeWait

The ACK is skipped in Time-Wait status, the reason would be either PAWS check failed or the received sequence number is out of window.

- TcpExtTCPACKSkippedChallenge

The ACK is skipped if the ACK is a challenge ACK. The RFC 5961 defines 3 kind of challenge ACK, please refer [RFC 5961 section 3.2](<https://tools.ietf.org/html/rfc5961#page-7>), [RFC 5961 section 4.2](<https://tools.ietf.org/html/rfc5961#page-9>) and [RFC 5961 section 5.2](<https://tools.ietf.org/html/rfc5961#page-11>). Besides these three scenarios, In some TCP status, the linux TCP stack would also send challenge ACKs if the ACK number is before the first unacknowledged number (more strict than [RFC 5961 section 5.2](<https://tools.ietf.org/html/rfc5961#page-11>)).

<a id="rst-rfc-5961-section-3-2"></a>



<a id="rst-rfc-5961-section-4-2"></a>



<a id="rst-rfc-5961-section-5-2"></a>



<a id="rst-tcp-receive-window"></a>

## TCP receive window

- TcpExtTCPWantZeroWindowAdv

Depending on current memory usage, the TCP stack tries to set receive window to zero. But the receive window might still be a no-zero value. For example, if the previous window size is 10, and the TCP stack receives 3 bytes, the current window size would be 7 even if the window size calculated by the memory usage is zero.

- TcpExtTCPToZeroWindowAdv

The TCP receive window is set to zero from a no-zero value.

- TcpExtTCPFromZeroWindowAdv

The TCP receive window is set to no-zero value from zero.

<a id="rst-delayed-ack"></a>

## Delayed ACK

The TCP Delayed ACK is a technique which is used for reducing the packet count in the network. For more details, please refer the [Delayed ACK wiki](<https://en.wikipedia.org/wiki/TCP_delayed_acknowledgment>)

<a id="rst-delayed-ack-wiki"></a>



- TcpExtDelayedACKs

A delayed ACK timer expires. The TCP stack will send a pure ACK packet and exit the delayed ACK mode.

- TcpExtDelayedACKLocked

A delayed ACK timer expires, but the TCP stack can't send an ACK immediately due to the socket is locked by a userspace program. The TCP stack will send a pure ACK later (after the userspace program unlock the socket). When the TCP stack sends the pure ACK later, the TCP stack will also update TcpExtDelayedACKs and exit the delayed ACK mode.

- TcpExtDelayedACKLost

It will be updated when the TCP stack receives a packet which has been ACKed. A Delayed ACK loss might cause this issue, but it would also be triggered by other reasons, such as a packet is duplicated in the network.

<a id="rst-tail-loss-probe-tlp"></a>

## Tail Loss Probe (TLP)

TLP is an algorithm which is used to detect TCP packet loss. For more details, please refer the [TLP paper](<https://tools.ietf.org/html/draft-dukkipati-tcpm-tcp-loss-probe-01>).

<a id="rst-tlp-paper"></a>



- TcpExtTCPLossProbes

A TLP probe packet is sent.

- TcpExtTCPLossProbeRecovery

A packet loss is detected and recovered by TLP.

<a id="rst-tcp-fast-open-description"></a>

## TCP Fast Open description

TCP Fast Open is a technology which allows data transfer before the 3-way handshake complete. Please refer the [TCP Fast Open wiki](<https://en.wikipedia.org/wiki/TCP_Fast_Open>) for a general description.

<a id="rst-tcp-fast-open-wiki"></a>



- TcpExtTCPFastOpenActive

When the TCP stack receives an ACK packet in the SYN-SENT status, and the ACK packet acknowledges the data in the SYN packet, the TCP stack understand the TFO cookie is accepted by the other side, then it updates this counter.

- TcpExtTCPFastOpenActiveFail

This counter indicates that the TCP stack initiated a TCP Fast Open, but it failed. This counter would be updated in three scenarios: (1) the other side doesn't acknowledge the data in the SYN packet. (2) The SYN packet which has the TFO cookie is timeout at least once. (3) after the 3-way handshake, the retransmission timeout happens net.ipv4.tcp\_retries1 times, because some middle-boxes may black-hole fast open after the handshake.

- TcpExtTCPFastOpenPassive

This counter indicates how many times the TCP stack accepts the fast open request.

- TcpExtTCPFastOpenPassiveFail

This counter indicates how many times the TCP stack rejects the fast open request. It is caused by either the TFO cookie is invalid or the TCP stack finds an error during the socket creating process.

- TcpExtTCPFastOpenListenOverflow

When the pending fast open request number is larger than fastopenq-&gt;max\_qlen, the TCP stack will reject the fast open request and update this counter. When this counter is updated, the TCP stack won't update TcpExtTCPFastOpenPassive or TcpExtTCPFastOpenPassiveFail. The fastopenq-&gt;max\_qlen is set by the TCP\_FASTOPEN socket operation and it could not be larger than net.core.somaxconn. For example:

setsockopt(sfd, SOL\_TCP, TCP\_FASTOPEN, &amp;qlen, sizeof(qlen));

- TcpExtTCPFastOpenCookieReqd

This counter indicates how many times a client wants to request a TFO cookie.

<a id="rst-syn-cookies"></a>

## SYN cookies

SYN cookies are used to mitigate SYN flood, for details, please refer the [SYN cookies wiki](<https://en.wikipedia.org/wiki/SYN_cookies>).

<a id="rst-syn-cookies-wiki"></a>



- TcpExtSyncookiesSent

It indicates how many SYN cookies are sent.

- TcpExtSyncookiesRecv

How many reply packets of the SYN cookies the TCP stack receives.

- TcpExtSyncookiesFailed

The MSS decoded from the SYN cookie is invalid. When this counter is updated, the received packet won't be treated as a SYN cookie and the TcpExtSyncookiesRecv counter won't be updated.

<a id="rst-challenge-ack"></a>

## Challenge ACK

For details of challenge ACK, please refer the explanation of TcpExtTCPACKSkippedChallenge.

- TcpExtTCPChallengeACK

The number of challenge acks sent.

- TcpExtTCPSYNChallenge

The number of challenge acks sent in response to SYN packets. After updates this counter, the TCP stack might send a challenge ACK and update the TcpExtTCPChallengeACK counter, or it might also skip to send the challenge and update the TcpExtTCPACKSkippedChallenge.

<a id="rst-prune"></a>

## prune

When a socket is under memory pressure, the TCP stack will try to reclaim memory from the receiving queue and out of order queue. One of the reclaiming method is 'collapse', which means allocate a big skb, copy the contiguous skbs to the single big skb, and free these contiguous skbs.

- TcpExtPruneCalled

The TCP stack tries to reclaim memory for a socket. After updates this counter, the TCP stack will try to collapse the out of order queue and the receiving queue. If the memory is still not enough, the TCP stack will try to discard packets from the out of order queue (and update the TcpExtOfoPruned counter)

- TcpExtOfoPruned

The TCP stack tries to discard packet on the out of order queue.

- TcpExtRcvPruned

After 'collapse' and discard packets from the out of order queue, if the actually used memory is still larger than the max allowed memory, this counter will be updated. It means the 'prune' fails.

- TcpExtTCPRcvCollapsed

This counter indicates how many skbs are freed during 'collapse'.

<a id="rst-examples"></a>

## examples

<a id="rst-ping-test"></a>

### ping test

Run the ping command against the public dns server 8.8.8.8:



```text
nstatuser@nstat-a:~$ ping 8.8.8.8 -c 1
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=17.8 ms

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 17.875/17.875/17.875/0.000 ms
```

The nstayt result:



```text
nstatuser@nstat-a:~$ nstat
#kernel
IpInReceives                    1                  0.0
IpInDelivers                    1                  0.0
IpOutRequests                   1                  0.0
IcmpInMsgs                      1                  0.0
IcmpInEchoReps                  1                  0.0
IcmpOutMsgs                     1                  0.0
IcmpOutEchos                    1                  0.0
IcmpMsgInType0                  1                  0.0
IcmpMsgOutType8                 1                  0.0
IpExtInOctets                   84                 0.0
IpExtOutOctets                  84                 0.0
IpExtInNoECTPkts                1                  0.0
```

The Linux server sent an ICMP Echo packet, so IpOutRequests, IcmpOutMsgs, IcmpOutEchos and IcmpMsgOutType8 were increased 1. The server got ICMP Echo Reply from 8.8.8.8, so IpInReceives, IcmpInMsgs, IcmpInEchoReps and IcmpMsgInType0 were increased 1. The ICMP Echo Reply was passed to the ICMP layer via IP layer, so IpInDelivers was increased 1. The default ping data size is 48, so an ICMP Echo packet and its corresponding Echo Reply packet are constructed by:

- 14 bytes MAC header

- 20 bytes IP header

- 16 bytes ICMP header

- 48 bytes data (default value of the ping command)

So the IpExtInOctets and IpExtOutOctets are 20+16+48=84.

<a id="rst-tcp-3-way-handshake"></a>

### tcp 3-way handshake

On server side, we run:



```text
nstatuser@nstat-b:~$ nc -lknv 0.0.0.0 9000
Listening on [0.0.0.0] (family 0, port 9000)
```

On client side, we run:



```text
nstatuser@nstat-a:~$ nc -nv 192.168.122.251 9000
Connection to 192.168.122.251 9000 port [tcp/*] succeeded!
```

The server listened on tcp 9000 port, the client connected to it, they completed the 3-way handshake.

On server side, we can find below nstat output:



```text
nstatuser@nstat-b:~$ nstat | grep -i tcp
TcpPassiveOpens                 1                  0.0
TcpInSegs                       2                  0.0
TcpOutSegs                      1                  0.0
TcpExtTCPPureAcks               1                  0.0
```

On client side, we can find below nstat output:



```text
nstatuser@nstat-a:~$ nstat | grep -i tcp
TcpActiveOpens                  1                  0.0
TcpInSegs                       1                  0.0
TcpOutSegs                      2                  0.0
```

When the server received the first SYN, it replied a SYN+ACK, and came into SYN-RCVD state, so TcpPassiveOpens increased 1. The server received SYN, sent SYN+ACK, received ACK, so server sent 1 packet, received 2 packets, TcpInSegs increased 2, TcpOutSegs increased 1. The last ACK of the 3-way handshake is a pure ACK without data, so TcpExtTCPPureAcks increased 1.

When the client sent SYN, the client came into the SYN-SENT state, so TcpActiveOpens increased 1, the client sent SYN, received SYN+ACK, sent ACK, so client sent 2 packets, received 1 packet, TcpInSegs increased 1, TcpOutSegs increased 2.

<a id="rst-tcp-normal-traffic"></a>

### TCP normal traffic

Run nc on server:



```text
nstatuser@nstat-b:~$ nc -lkv 0.0.0.0 9000
Listening on [0.0.0.0] (family 0, port 9000)
```

Run nc on client:



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!
```

Input a string in the nc client ('hello' in our example):



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!
hello
```

The client side nstat output:



```text
nstatuser@nstat-a:~$ nstat
#kernel
IpInReceives                    1                  0.0
IpInDelivers                    1                  0.0
IpOutRequests                   1                  0.0
TcpInSegs                       1                  0.0
TcpOutSegs                      1                  0.0
TcpExtTCPPureAcks               1                  0.0
TcpExtTCPOrigDataSent           1                  0.0
IpExtInOctets                   52                 0.0
IpExtOutOctets                  58                 0.0
IpExtInNoECTPkts                1                  0.0
```

The server side nstat output:



```text
nstatuser@nstat-b:~$ nstat
#kernel
IpInReceives                    1                  0.0
IpInDelivers                    1                  0.0
IpOutRequests                   1                  0.0
TcpInSegs                       1                  0.0
TcpOutSegs                      1                  0.0
IpExtInOctets                   58                 0.0
IpExtOutOctets                  52                 0.0
IpExtInNoECTPkts                1                  0.0
```

Input a string in nc client side again ('world' in our example):



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!
hello
world
```

Client side nstat output:



```text
nstatuser@nstat-a:~$ nstat
#kernel
IpInReceives                    1                  0.0
IpInDelivers                    1                  0.0
IpOutRequests                   1                  0.0
TcpInSegs                       1                  0.0
TcpOutSegs                      1                  0.0
TcpExtTCPHPAcks                 1                  0.0
TcpExtTCPOrigDataSent           1                  0.0
IpExtInOctets                   52                 0.0
IpExtOutOctets                  58                 0.0
IpExtInNoECTPkts                1                  0.0
```

Server side nstat output:



```text
nstatuser@nstat-b:~$ nstat
#kernel
IpInReceives                    1                  0.0
IpInDelivers                    1                  0.0
IpOutRequests                   1                  0.0
TcpInSegs                       1                  0.0
TcpOutSegs                      1                  0.0
TcpExtTCPHPHits                 1                  0.0
IpExtInOctets                   58                 0.0
IpExtOutOctets                  52                 0.0
IpExtInNoECTPkts                1                  0.0
```

Compare the first client-side nstat and the second client-side nstat, we could find one difference: the first one had a 'TcpExtTCPPureAcks', but the second one had a 'TcpExtTCPHPAcks'. The first server-side nstat and the second server-side nstat had a difference too: the second server-side nstat had a TcpExtTCPHPHits, but the first server-side nstat didn't have it. The network traffic patterns were exactly the same: the client sent a packet to the server, the server replied an ACK. But kernel handled them in different ways. When the TCP window scale option is not used, kernel will try to enable fast path immediately when the connection comes into the established state, but if the TCP window scale option is used, kernel will disable the fast path at first, and try to enable it after kernel receives packets. We could use the 'ss' command to verify whether the window scale option is used. e.g. run below command on either server or client:



```text
nstatuser@nstat-a:~$ ss -o state established -i '( dport = :9000 or sport = :9000 )
Netid    Recv-Q     Send-Q            Local Address:Port             Peer Address:Port
tcp      0          0               192.168.122.250:40654         192.168.122.251:9000
           ts sack cubic wscale:7,7 rto:204 rtt:0.98/0.49 mss:1448 pmtu:1500 rcvmss:536 advmss:1448 cwnd:10 bytes_acked:1 segs_out:2 segs_in:1 send 118.2Mbps lastsnd:46572 lastrcv:46572 lastack:46572 pacing_rate 236.4Mbps rcv_space:29200 rcv_ssthresh:29200 minrtt:0.98
```

The 'wscale:7,7' means both server and client set the window scale option to 7. Now we could explain the nstat output in our test:

In the first nstat output of client side, the client sent a packet, server reply an ACK, when kernel handled this ACK, the fast path was not enabled, so the ACK was counted into 'TcpExtTCPPureAcks'.

In the second nstat output of client side, the client sent a packet again, and received another ACK from the server, in this time, the fast path is enabled, and the ACK was qualified for fast path, so it was handled by the fast path, so this ACK was counted into TcpExtTCPHPAcks.

In the first nstat output of server side, fast path was not enabled, so there was no 'TcpExtTCPHPHits'.

In the second nstat output of server side, the fast path was enabled, and the packet received from client qualified for fast path, so it was counted into 'TcpExtTCPHPHits'.

<a id="rst-tcpexttcpabortonclose"></a>

### TcpExtTCPAbortOnClose

On the server side, we run below python script:



```text
import socket
import time

port = 9000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', port))
s.listen(1)
sock, addr = s.accept()
while True:
    time.sleep(9999999)
```

This python script listen on 9000 port, but doesn't read anything from the connection.

On the client side, we send the string "hello" by nc:



```text
nstatuser@nstat-a:~$ echo "hello" | nc nstat-b 9000
```

Then, we come back to the server side, the server has received the "hello" packet, and the TCP layer has acked this packet, but the application didn't read it yet. We type Ctrl-C to terminate the server script. Then we could find TcpExtTCPAbortOnClose increased 1 on the server side:



```text
nstatuser@nstat-b:~$ nstat | grep -i abort
TcpExtTCPAbortOnClose           1                  0.0
```

If we run tcpdump on the server side, we could find the server sent a RST after we type Ctrl-C.

<a id="rst-tcpexttcpabortonmemory-and-tcpexttcpabortontimeout"></a>

### TcpExtTCPAbortOnMemory and TcpExtTCPAbortOnTimeout

Below is an example which let the orphan socket count be higher than net.ipv4.tcp\_max\_orphans. Change tcp\_max\_orphans to a smaller value on client:



```text
sudo bash -c "echo 10 > /proc/sys/net/ipv4/tcp_max_orphans"
```

Client code (create 64 connection to server):



```text
nstatuser@nstat-a:~$ cat client_orphan.py
import socket
import time

server = 'nstat-b' # server address
port = 9000

count = 64

connection_list = []

for i in range(64):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((server, port))
    connection_list.append(s)
    print("connection_count: %d" % len(connection_list))

while True:
    time.sleep(99999)
```

Server code (accept 64 connection from client):



```text
nstatuser@nstat-b:~$ cat server_orphan.py
import socket
import time

port = 9000
count = 64

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', port))
s.listen(count)
connection_list = []
while True:
    sock, addr = s.accept()
    connection_list.append((sock, addr))
    print("connection_count: %d" % len(connection_list))
```

Run the python scripts on server and client.

On server:



```text
python3 server_orphan.py
```

On client:



```text
python3 client_orphan.py
```

Run iptables on server:



```text
sudo iptables -A INPUT -i ens3 -p tcp --destination-port 9000 -j DROP
```

Type Ctrl-C on client, stop client\_orphan.py.

Check TcpExtTCPAbortOnMemory on client:



```text
nstatuser@nstat-a:~$ nstat | grep -i abort
TcpExtTCPAbortOnMemory          54                 0.0
```

Check orphaned socket count on client:



```text
nstatuser@nstat-a:~$ ss -s
Total: 131 (kernel 0)
TCP:   14 (estab 1, closed 0, orphaned 10, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -
RAW       1         0         1
UDP       1         1         0
TCP       14        13        1
INET      16        14        2
FRAG      0         0         0
```

The explanation of the test: after run server\_orphan.py and client\_orphan.py, we set up 64 connections between server and client. Run the iptables command, the server will drop all packets from the client, type Ctrl-C on client\_orphan.py, the system of the client would try to close these connections, and before they are closed gracefully, these connections became orphan sockets. As the iptables of the server blocked packets from the client, the server won't receive fin from the client, so all connection on clients would be stuck on FIN\_WAIT\_1 stage, so they will keep as orphan sockets until timeout. We have echo 10 to /proc/sys/net/ipv4/tcp\_max\_orphans, so the client system would only keep 10 orphan sockets, for all other orphan sockets, the client system sent RST for them and delete them. We have 64 connections, so the 'ss -s' command shows the system has 10 orphan sockets, and the value of TcpExtTCPAbortOnMemory was 54.

An additional explanation about orphan socket count: You could find the exactly orphan socket count by the 'ss -s' command, but when kernel decide whither increases TcpExtTCPAbortOnMemory and sends RST, kernel doesn't always check the exactly orphan socket count. For increasing performance, kernel checks an approximate count firstly, if the approximate count is more than tcp\_max\_orphans, kernel checks the exact count again. So if the approximate count is less than tcp\_max\_orphans, but exactly count is more than tcp\_max\_orphans, you would find TcpExtTCPAbortOnMemory is not increased at all. If tcp\_max\_orphans is large enough, it won't occur, but if you decrease tcp\_max\_orphans to a small value like our test, you might find this issue. So in our test, the client set up 64 connections although the tcp\_max\_orphans is 10. If the client only set up 11 connections, we can't find the change of TcpExtTCPAbortOnMemory.

Continue the previous test, we wait for several minutes. Because of the iptables on the server blocked the traffic, the server wouldn't receive fin, and all the client's orphan sockets would timeout on the FIN\_WAIT\_1 state finally. So we wait for a few minutes, we could find 10 timeout on the client:



```text
nstatuser@nstat-a:~$ nstat | grep -i abort
TcpExtTCPAbortOnTimeout         10                 0.0
```

<a id="rst-tcpexttcpabortonlinger"></a>

### TcpExtTCPAbortOnLinger

The server side code:



```text
nstatuser@nstat-b:~$ cat server_linger.py
import socket
import time

port = 9000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', port))
s.listen(1)
sock, addr = s.accept()
while True:
    time.sleep(9999999)
```

The client side code:



```text
nstatuser@nstat-a:~$ cat client_linger.py
import socket
import struct

server = 'nstat-b' # server address
port = 9000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 10))
s.setsockopt(socket.SOL_TCP, socket.TCP_LINGER2, struct.pack('i', -1))
s.connect((server, port))
s.close()
```

Run server\_linger.py on server:



```text
nstatuser@nstat-b:~$ python3 server_linger.py
```

Run client\_linger.py on client:



```text
nstatuser@nstat-a:~$ python3 client_linger.py
```

After run client\_linger.py, check the output of nstat:



```text
nstatuser@nstat-a:~$ nstat | grep -i abort
TcpExtTCPAbortOnLinger          1                  0.0
```

<a id="rst-tcpexttcprcvcoalesce"></a>

### TcpExtTCPRcvCoalesce

On the server, we run a program which listen on TCP port 9000, but doesn't read any data:



```text
import socket
import time
port = 9000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', port))
s.listen(1)
sock, addr = s.accept()
while True:
    time.sleep(9999999)
```

Save the above code as server\_coalesce.py, and run:



```text
python3 server_coalesce.py
```

On the client, save below code as client\_coalesce.py:



```text
import socket
server = 'nstat-b'
port = 9000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, port))
```

Run:



```text
nstatuser@nstat-a:~$ python3 -i client_coalesce.py
```

We use '-i' to come into the interactive mode, then a packet:



```text
>>> s.send(b'foo')
3
```

Send a packet again:



```text
>>> s.send(b'bar')
3
```

On the server, run nstat:



```text
ubuntu@nstat-b:~$ nstat
#kernel
IpInReceives                    2                  0.0
IpInDelivers                    2                  0.0
IpOutRequests                   2                  0.0
TcpInSegs                       2                  0.0
TcpOutSegs                      2                  0.0
TcpExtTCPRcvCoalesce            1                  0.0
IpExtInOctets                   110                0.0
IpExtOutOctets                  104                0.0
IpExtInNoECTPkts                2                  0.0
```

The client sent two packets, server didn't read any data. When the second packet arrived at server, the first packet was still in the receiving queue. So the TCP layer merged the two packets, and we could find the TcpExtTCPRcvCoalesce increased 1.

<a id="rst-tcpextlistenoverflows-and-tcpextlistendrops"></a>

### TcpExtListenOverflows and TcpExtListenDrops

On server, run the nc command, listen on port 9000:



```text
nstatuser@nstat-b:~$ nc -lkv 0.0.0.0 9000
Listening on [0.0.0.0] (family 0, port 9000)
```

On client, run 3 nc commands in different terminals:



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!
```

The nc command only accepts 1 connection, and the accept queue length is 1. On current linux implementation, set queue length to n means the actual queue length is n+1. Now we create 3 connections, 1 is accepted by nc, 2 in accepted queue, so the accept queue is full.

Before running the 4th nc, we clean the nstat history on the server:



```text
nstatuser@nstat-b:~$ nstat -n
```

Run the 4th nc on the client:



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
```

If the nc server is running on kernel 4.10 or higher version, you won't see the "Connection to ... succeeded\!" string, because kernel will drop the SYN if the accept queue is full. If the nc client is running on an old kernel, you would see that the connection is succeeded, because kernel would complete the 3 way handshake and keep the socket on half open queue. I did the test on kernel 4.15. Below is the nstat on the server:



```text
nstatuser@nstat-b:~$ nstat
#kernel
IpInReceives                    4                  0.0
IpInDelivers                    4                  0.0
TcpInSegs                       4                  0.0
TcpExtListenOverflows           4                  0.0
TcpExtListenDrops               4                  0.0
IpExtInOctets                   240                0.0
IpExtInNoECTPkts                4                  0.0
```

Both TcpExtListenOverflows and TcpExtListenDrops were 4. If the time between the 4th nc and the nstat was longer, the value of TcpExtListenOverflows and TcpExtListenDrops would be larger, because the SYN of the 4th nc was dropped, the client was retrying.

<a id="rst-ipinaddrerrors-ipextinnoroutes-and-ipoutnoroutes"></a>

### IpInAddrErrors, IpExtInNoRoutes and IpOutNoRoutes

server A IP address: 192.168.122.250 server B IP address: 192.168.122.251 Prepare on server A, add a route to server B:



```text
$ sudo ip route add 8.8.8.8/32 via 192.168.122.251
```

Prepare on server B, disable send\_redirects for all interfaces:



```text
$ sudo sysctl -w net.ipv4.conf.all.send_redirects=0
$ sudo sysctl -w net.ipv4.conf.ens3.send_redirects=0
$ sudo sysctl -w net.ipv4.conf.lo.send_redirects=0
$ sudo sysctl -w net.ipv4.conf.default.send_redirects=0
```

We want to let sever A send a packet to 8.8.8.8, and route the packet to server B. When server B receives such packet, it might send a ICMP Redirect message to server A, set send\_redirects to 0 will disable this behavior.

First, generate InAddrErrors. On server B, we disable IP forwarding:



```text
$ sudo sysctl -w net.ipv4.conf.all.forwarding=0
```

On server A, we send packets to 8.8.8.8:



```text
$ nc -v 8.8.8.8 53
```

On server B, we check the output of nstat:



```text
$ nstat
#kernel
IpInReceives                    3                  0.0
IpInAddrErrors                  3                  0.0
IpExtInOctets                   180                0.0
IpExtInNoECTPkts                3                  0.0
```

As we have let server A route 8.8.8.8 to server B, and we disabled IP forwarding on server B, Server A sent packets to server B, then server B dropped packets and increased IpInAddrErrors. As the nc command would re-send the SYN packet if it didn't receive a SYN+ACK, we could find multiple IpInAddrErrors.

Second, generate IpExtInNoRoutes. On server B, we enable IP forwarding:



```text
$ sudo sysctl -w net.ipv4.conf.all.forwarding=1
```

Check the route table of server B and remove the default route:



```text
$ ip route show
default via 192.168.122.1 dev ens3 proto static
192.168.122.0/24 dev ens3 proto kernel scope link src 192.168.122.251
$ sudo ip route delete default via 192.168.122.1 dev ens3 proto static
```

On server A, we contact 8.8.8.8 again:



```text
$ nc -v 8.8.8.8 53
nc: connect to 8.8.8.8 port 53 (tcp) failed: Network is unreachable
```

On server B, run nstat:



```text
$ nstat
#kernel
IpInReceives                    1                  0.0
IpOutRequests                   1                  0.0
IcmpOutMsgs                     1                  0.0
IcmpOutDestUnreachs             1                  0.0
IcmpMsgOutType3                 1                  0.0
IpExtInNoRoutes                 1                  0.0
IpExtInOctets                   60                 0.0
IpExtOutOctets                  88                 0.0
IpExtInNoECTPkts                1                  0.0
```

We enabled IP forwarding on server B, when server B received a packet which destination IP address is 8.8.8.8, server B will try to forward this packet. We have deleted the default route, there was no route for 8.8.8.8, so server B increase IpExtInNoRoutes and sent the "ICMP Destination Unreachable" message to server A.

Third, generate IpOutNoRoutes. Run ping command on server B:



```text
$ ping -c 1 8.8.8.8
connect: Network is unreachable
```

Run nstat on server B:



```text
$ nstat
#kernel
IpOutNoRoutes                   1                  0.0
```

We have deleted the default route on server B. Server B couldn't find a route for the 8.8.8.8 IP address, so server B increased IpOutNoRoutes.

<a id="rst-tcpexttcpackskippedsynrecv"></a>

### TcpExtTCPACKSkippedSynRecv

In this test, we send 3 same SYN packets from client to server. The first SYN will let server create a socket, set it to Syn-Recv status, and reply a SYN/ACK. The second SYN will let server reply the SYN/ACK again, and record the reply time (the duplicate ACK reply time). The third SYN will let server check the previous duplicate ACK reply time, and decide to skip the duplicate ACK, then increase the TcpExtTCPACKSkippedSynRecv counter.

Run tcpdump to capture a SYN packet:



```text
nstatuser@nstat-a:~$ sudo tcpdump -c 1 -w /tmp/syn.pcap port 9000
tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes
```

Open another terminal, run nc command:



```text
nstatuser@nstat-a:~$ nc nstat-b 9000
```

As the nstat-b didn't listen on port 9000, it should reply a RST, and the nc command exited immediately. It was enough for the tcpdump command to capture a SYN packet. A linux server might use hardware offload for the TCP checksum, so the checksum in the /tmp/syn.pcap might be not correct. We call tcprewrite to fix it:



```text
nstatuser@nstat-a:~$ tcprewrite --infile=/tmp/syn.pcap --outfile=/tmp/syn_fixcsum.pcap --fixcsum
```

On nstat-b, we run nc to listen on port 9000:



```text
nstatuser@nstat-b:~$ nc -lkv 9000
Listening on [0.0.0.0] (family 0, port 9000)
```

On nstat-a, we blocked the packet from port 9000, or nstat-a would send RST to nstat-b:



```text
nstatuser@nstat-a:~$ sudo iptables -A INPUT -p tcp --sport 9000 -j DROP
```

Send 3 SYN repeatedly to nstat-b:



```text
nstatuser@nstat-a:~$ for i in {1..3}; do sudo tcpreplay -i ens3 /tmp/syn_fixcsum.pcap; done
```

Check snmp counter on nstat-b:



```text
nstatuser@nstat-b:~$ nstat | grep -i skip
TcpExtTCPACKSkippedSynRecv      1                  0.0
```

As we expected, TcpExtTCPACKSkippedSynRecv is 1.

<a id="rst-tcpexttcpackskippedpaws"></a>

### TcpExtTCPACKSkippedPAWS

To trigger PAWS, we could send an old SYN.

On nstat-b, let nc listen on port 9000:



```text
nstatuser@nstat-b:~$ nc -lkv 9000
Listening on [0.0.0.0] (family 0, port 9000)
```

On nstat-a, run tcpdump to capture a SYN:



```text
nstatuser@nstat-a:~$ sudo tcpdump -w /tmp/paws_pre.pcap -c 1 port 9000
tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes
```

On nstat-a, run nc as a client to connect nstat-b:



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!
```

Now the tcpdump has captured the SYN and exit. We should fix the checksum:



```text
nstatuser@nstat-a:~$ tcprewrite --infile /tmp/paws_pre.pcap --outfile /tmp/paws.pcap --fixcsum
```

Send the SYN packet twice:



```text
nstatuser@nstat-a:~$ for i in {1..2}; do sudo tcpreplay -i ens3 /tmp/paws.pcap; done
```

On nstat-b, check the snmp counter:



```text
nstatuser@nstat-b:~$ nstat | grep -i skip
TcpExtTCPACKSkippedPAWS         1                  0.0
```

We sent two SYN via tcpreplay, both of them would let PAWS check failed, the nstat-b replied an ACK for the first SYN, skipped the ACK for the second SYN, and updated TcpExtTCPACKSkippedPAWS.

<a id="rst-tcpexttcpackskippedseq"></a>

### TcpExtTCPACKSkippedSeq

To trigger TcpExtTCPACKSkippedSeq, we send packets which have valid timestamp (to pass PAWS check) but the sequence number is out of window. The linux TCP stack would avoid to skip if the packet has data, so we need a pure ACK packet. To generate such a packet, we could create two sockets: one on port 9000, another on port 9001. Then we capture an ACK on port 9001, change the source/destination port numbers to match the port 9000 socket. Then we could trigger TcpExtTCPACKSkippedSeq via this packet.

On nstat-b, open two terminals, run two nc commands to listen on both port 9000 and port 9001:



```text
nstatuser@nstat-b:~$ nc -lkv 9000
Listening on [0.0.0.0] (family 0, port 9000)

nstatuser@nstat-b:~$ nc -lkv 9001
Listening on [0.0.0.0] (family 0, port 9001)
```

On nstat-a, run two nc clients:



```text
nstatuser@nstat-a:~$ nc -v nstat-b 9000
Connection to nstat-b 9000 port [tcp/*] succeeded!

nstatuser@nstat-a:~$ nc -v nstat-b 9001
Connection to nstat-b 9001 port [tcp/*] succeeded!
```

On nstat-a, run tcpdump to capture an ACK:



```text
nstatuser@nstat-a:~$ sudo tcpdump -w /tmp/seq_pre.pcap -c 1 dst port 9001
tcpdump: listening on ens3, link-type EN10MB (Ethernet), capture size 262144 bytes
```

On nstat-b, send a packet via the port 9001 socket. E.g. we sent a string 'foo' in our example:



```text
nstatuser@nstat-b:~$ nc -lkv 9001
Listening on [0.0.0.0] (family 0, port 9001)
Connection from nstat-a 42132 received!
foo
```

On nstat-a, the tcpdump should have captured the ACK. We should check the source port numbers of the two nc clients:



```text
nstatuser@nstat-a:~$ ss -ta '( dport = :9000 || dport = :9001 )' | tee
State  Recv-Q   Send-Q         Local Address:Port           Peer Address:Port
ESTAB  0        0            192.168.122.250:50208       192.168.122.251:9000
ESTAB  0        0            192.168.122.250:42132       192.168.122.251:9001
```

Run tcprewrite, change port 9001 to port 9000, change port 42132 to port 50208:



```text
nstatuser@nstat-a:~$ tcprewrite --infile /tmp/seq_pre.pcap --outfile /tmp/seq.pcap -r 9001:9000 -r 42132:50208 --fixcsum
```

Now the /tmp/seq.pcap is the packet we need. Send it to nstat-b:



```text
nstatuser@nstat-a:~$ for i in {1..2}; do sudo tcpreplay -i ens3 /tmp/seq.pcap; done
```

Check TcpExtTCPACKSkippedSeq on nstat-b:



```text
nstatuser@nstat-b:~$ nstat | grep -i skip
TcpExtTCPACKSkippedSeq          1                  0.0
```

---

# NIC SR-IOV APIs

_Peios Kernel / Internals / Networking_

> Modern NICs are strongly encouraged to focus on implementing the switchdev model (see switchdev) to configure forwarding and security of SR-IOV functionality.

<a id="rst-nic-sr-iov-apis"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Modern NICs are strongly encouraged to focus on implementing the `switchdev` model (see [Ethernet switch device driver model (switchdev)](</kernel/internals/networking/switchdev.md#rst-switchdev>)) to configure forwarding and security of SR-IOV functionality.

<a id="rst-legacy-api"></a>

## Legacy API

The old SR-IOV API is implemented in `rtnetlink` Netlink family as part of the `RTM_GETLINK` and `RTM_SETLINK` commands. On the driver side it consists of a number of `ndo_set_vf_*` and `ndo_get_vf_*` callbacks.

Since the legacy APIs do not integrate well with the rest of the stack the API is considered frozen; no new functionality or extensions will be accepted. New drivers should not implement the uncommon callbacks; namely the following callbacks are off limits:

> - `ndo_get_vf_port`
>
> - `ndo_set_vf_port`
>
> - `ndo_set_vf_rss_query_en`

---

# Interface statistics

_Peios Kernel / Internals / Networking_

> This document is a guide to Linux network interface statistics.

<a id="rst-interface-statistics"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

This document is a guide to Linux network interface statistics.

There are three main sources of interface statistics in Linux:

> - standard interface statistics based on `struct rtnl_link_stats64 <rtnl_link_stats64>`;
>
> - protocol-specific statistics; and
>
> - driver-defined statistics available via ethtool.

<a id="rst-standard-interface-statistics"></a>

### Standard interface statistics

There are multiple interfaces to reach the standard statistics. Most commonly used is the `ip` command from `iproute2`:



```text
$ ip -s -s link show dev ens4u1u1
6: ens4u1u1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP mode DEFAULT group default qlen 1000
  link/ether 48:2a:e3:4c:b1:d1 brd ff:ff:ff:ff:ff:ff
  RX: bytes  packets  errors  dropped overrun mcast
  74327665117 69016965 0       0       0       0
  RX errors: length   crc     frame   fifo    missed
             0        0       0       0       0
  TX: bytes  packets  errors  dropped carrier collsns
  21405556176 44608960 0       0       0       0
  TX errors: aborted  fifo   window heartbeat transns
             0        0       0       0       128
  altname enp58s0u1u1
```

Note that `-s` has been specified twice to see all members of `struct rtnl_link_stats64 <rtnl_link_stats64>`. If `-s` is specified once the detailed errors won't be shown.

`ip` supports JSON formatting via the `-j` option.

<a id="rst-queue-statistics"></a>

#### Queue statistics

Queue statistics are accessible via the netdev netlink family.

Currently no widely distributed CLI exists to access those statistics. Kernel development tools (ynl) can be used to experiment with them, see `Documentation/userspace-api/netlink/intro-specs.rst`.

<a id="rst-protocol-specific-statistics"></a>

### Protocol-specific statistics

Protocol-specific statistics are exposed via relevant interfaces, the same interfaces as are used to configure them.

<a id="rst-ethtool"></a>

#### ethtool

Ethtool exposes common low-level statistics. All the standard statistics are expected to be maintained by the device, not the driver (as opposed to driver-defined stats described in the next section which mix software and hardware stats). For devices which contain unmanaged switches (e.g. legacy SR-IOV or multi-host NICs) the events counted may not pertain exclusively to the packets destined to the local host interface. In other words the events may be counted at the network port (MAC/PHY blocks) without separation for different host side (PCIe) devices. Such ambiguity must not be present when internal switch is managed by Linux (so called switchdev mode for NICs).

Standard ethtool statistics can be accessed via the interfaces used for configuration. For example ethtool interface used to configure pause frames can report corresponding hardware counters:



```text
$ ethtool --include-statistics -a eth0
Pause parameters for eth0:
Autonegotiate:        on
RX:                   on
TX:                   on
Statistics:
  tx_pause_frames: 1
  rx_pause_frames: 1
```

General Ethernet statistics not associated with any particular functionality are exposed via `ethtool -S $ifc` by specifying the `--groups` parameter:



```text
$ ethtool -S eth0 --groups eth-phy eth-mac eth-ctrl rmon
Stats for eth0:
eth-phy-SymbolErrorDuringCarrier: 0
eth-mac-FramesTransmittedOK: 1
eth-mac-FrameTooLongErrors: 1
eth-ctrl-MACControlFramesTransmitted: 1
eth-ctrl-MACControlFramesReceived: 0
eth-ctrl-UnsupportedOpcodesReceived: 1
rmon-etherStatsUndersizePkts: 1
rmon-etherStatsJabbers: 0
rmon-rx-etherStatsPkts64Octets: 1
rmon-rx-etherStatsPkts65to127Octets: 0
rmon-rx-etherStatsPkts128to255Octets: 0
rmon-tx-etherStatsPkts64Octets: 2
rmon-tx-etherStatsPkts65to127Octets: 3
rmon-tx-etherStatsPkts128to255Octets: 0
```

<a id="rst-driver-defined-statistics"></a>

### Driver-defined statistics

Driver-defined ethtool statistics can be dumped using `ethtool -S $ifc`, e.g.:



```text
$ ethtool -S ens4u1u1
NIC statistics:
   tx_single_collisions: 0
   tx_multi_collisions: 0
```

<a id="rst-uapis"></a>

## uAPIs

<a id="rst-procfs"></a>

### procfs

The historical `/proc/net/dev` text interface gives access to the list of interfaces as well as their statistics.

Note that even though this interface is using `struct rtnl_link_stats64 <rtnl_link_stats64>` internally it combines some of the fields.

<a id="rst-sysfs"></a>

### sysfs

Each device directory in sysfs contains a `statistics` directory (e.g. `/sys/class/net/lo/statistics/`) with files corresponding to members of `struct rtnl_link_stats64 <rtnl_link_stats64>`.

This simple interface is convenient especially in constrained/embedded environments without access to tools. However, it's inefficient when reading multiple stats as it internally performs a full dump of `struct rtnl_link_stats64 <rtnl_link_stats64>` and reports only the stat corresponding to the accessed file.

Sysfs files are documented in Documentation/ABI/testing/sysfs-class-net-statistics.

<a id="rst-netlink"></a>

### netlink

`rtnetlink` (`NETLINK_ROUTE`) is the preferred method of accessing `struct rtnl_link_stats64 <rtnl_link_stats64>` stats.

Statistics are reported both in the responses to link information requests (`RTM_GETLINK`) and statistic requests (`RTM_GETSTATS`, when `IFLA_STATS_LINK_64` bit is set in the `.filter_mask` of the request).

<a id="rst-netdev-netlink"></a>

#### netdev (netlink)

`netdev` generic netlink family allows accessing page pool and per queue statistics.

<a id="rst-ethtool-1"></a>

### ethtool

Ethtool IOCTL interface allows drivers to report implementation specific statistics. Historically it has also been used to report statistics for which other APIs did not exist, like per-device-queue statistics, or standard-based statistics (e.g. RFC 2863).

Statistics and their string identifiers are retrieved separately. Identifiers via `ETHTOOL_GSTRINGS` with `string_set` set to `ETH_SS_STATS`, and values via `ETHTOOL_GSTATS`. User space should use `ETHTOOL_GDRVINFO` to retrieve the number of statistics (`.n_stats`).

<a id="rst-ethtool-netlink"></a>

### ethtool-netlink

Ethtool netlink is a replacement for the older IOCTL interface.

Protocol-related statistics can be requested in get commands by setting the `ETHTOOL_FLAG_STATS` flag in `ETHTOOL_A_HEADER_FLAGS`. Currently statistics are supported in the following commands:

> - `ETHTOOL_MSG_FEC_GET`
>
> - `ETHTOOL_MSG_LINKSTATE_GET`
>
> - `ETHTOOL_MSG_MM_GET`
>
> - `ETHTOOL_MSG_PAUSE_GET`
>
> - `ETHTOOL_MSG_TSINFO_GET`

<a id="rst-debugfs"></a>

### debugfs

Some drivers expose extra statistics via `debugfs`.

<a id="rst-struct-rtnl-link-stats64"></a>

## struct rtnl_link_stats64


#### <a id="c-struct-rtnl_link_stats64"></a>`struct rtnl_link_stats64`

The main device statistics structure.

**Definition**

```c
struct rtnl_link_stats64 {
    __u64 rx_packets;
    __u64 tx_packets;
    __u64 rx_bytes;
    __u64 tx_bytes;
    __u64 rx_errors;
    __u64 tx_errors;
    __u64 rx_dropped;
    __u64 tx_dropped;
    __u64 multicast;
    __u64 collisions;
    __u64 rx_length_errors;
    __u64 rx_over_errors;
    __u64 rx_crc_errors;
    __u64 rx_frame_errors;
    __u64 rx_fifo_errors;
    __u64 rx_missed_errors;
    __u64 tx_aborted_errors;
    __u64 tx_carrier_errors;
    __u64 tx_fifo_errors;
    __u64 tx_heartbeat_errors;
    __u64 tx_window_errors;
    __u64 rx_compressed;
    __u64 tx_compressed;
    __u64 rx_nohandler;
    __u64 rx_otherhost_dropped;
};
```

**Members**

- `rx_packets`: Number of good packets received by the interface.
  For hardware interfaces counts all good packets received from the device
  by the host, including packets which host had to drop at various stages
  of processing (even in the driver).
- `tx_packets`: Number of packets successfully transmitted.
  For hardware interfaces counts packets which host was able to successfully
  hand over to the device, which does not necessarily mean that packets
  had been successfully transmitted out of the device, only that device
  acknowledged it copied them out of host memory.
- `rx_bytes`: Number of good received bytes, corresponding to **rx_packets**.
- `tx_bytes`: Number of good transmitted bytes, corresponding to **tx_packets**.
- `rx_errors`: Total number of bad packets received on this network device.
  This counter must include events counted by **rx_length_errors**,
  **rx_crc_errors**, **rx_frame_errors** and other errors not otherwise
  counted.
- `tx_errors`: Total number of transmit problems.
  This counter must include events counter by **tx_aborted_errors**,
  **tx_carrier_errors**, **tx_fifo_errors**, **tx_heartbeat_errors**,
  **tx_window_errors** and other errors not otherwise counted.
- `rx_dropped`: Number of packets received but not processed,
  e.g. due to lack of resources or unsupported protocol.
  For hardware interfaces this counter may include packets discarded
  due to L2 address filtering but should not include packets dropped
  by the device due to buffer exhaustion which are counted separately in
  **rx_missed_errors** (since procfs folds those two counters together).
- `tx_dropped`: Number of packets dropped on their way to transmission,
  e.g. due to lack of resources.
- `multicast`: Multicast packets received.
  For hardware interfaces this statistic is commonly calculated
  at the device level (unlike **rx_packets**) and therefore may include
  packets which did not reach the host.
- `collisions`: Number of collisions during packet transmissions.
- `rx_length_errors`: Number of packets dropped due to invalid length.
  Part of aggregate "frame" errors in `/proc/net/dev`.
- `rx_over_errors`: Receiver FIFO overflow event counter.
- `rx_crc_errors`: Number of packets received with a CRC error.
  Part of aggregate "frame" errors in `/proc/net/dev`.
- `rx_frame_errors`: Receiver frame alignment errors.
  Part of aggregate "frame" errors in `/proc/net/dev`.
- `rx_fifo_errors`: Receiver FIFO error counter.
- `rx_missed_errors`: Count of packets missed by the host.
  Folded into the "drop" counter in `/proc/net/dev`.
- `tx_aborted_errors`: Part of aggregate "carrier" errors in `/proc/net/dev`.
  For IEEE 802.3 devices capable of half-duplex operation this counter
  must be equivalent to:
- `tx_carrier_errors`: Number of frame transmission errors due to loss
  of carrier during transmission.
  Part of aggregate "carrier" errors in `/proc/net/dev`.
- `tx_fifo_errors`: Number of frame transmission errors due to device
  FIFO underrun / underflow. This condition occurs when the device
  begins transmission of a frame but is unable to deliver the
  entire frame to the transmitter in time for transmission.
  Part of aggregate "carrier" errors in `/proc/net/dev`.
- `tx_heartbeat_errors`: Number of Heartbeat / SQE Test errors for
  old half-duplex Ethernet.
  Part of aggregate "carrier" errors in `/proc/net/dev`.
- `tx_window_errors`: Number of frame transmission errors due
  to late collisions (for Ethernet - after the first 64B of transmission).
  Part of aggregate "carrier" errors in `/proc/net/dev`.
- `rx_compressed`: Number of correctly received compressed packets.
  This counters is only meaningful for interfaces which support
  packet compression (e.g. CSLIP, PPP).
- `tx_compressed`: Number of transmitted compressed packets.
  This counters is only meaningful for interfaces which support
  packet compression (e.g. CSLIP, PPP).
- `rx_nohandler`: Number of packets received on the interface
  but dropped by the networking stack because the device is
  not designated to receive packets (e.g. backup link in a bond).
- `rx_otherhost_dropped`: Number of packets dropped due to mismatch
  in destination MAC address.

**Description**

For IEEE 802.3 devices should count the length of Ethernet Frames
excluding the FCS.

For IEEE 802.3 devices should count the length of Ethernet Frames
excluding the FCS.

For IEEE 802.3 devices this counter may be equivalent to:

- 30.3.1.1.21 aMulticastFramesReceivedOK

For IEEE 802.3 devices this counter should be equivalent to a sum
of the following attributes:

- 30.3.1.1.23 aInRangeLengthErrors
- 30.3.1.1.24 aOutOfRangeLengthField
- 30.3.1.1.25 aFrameTooLongErrors

Historically the count of overflow events. Such events may be
reported in the receive descriptors or via interrupts, and may
not correspond one-to-one with dropped packets.

The recommended interpretation for high speed interfaces is -
number of packets dropped because they did not fit into buffers
provided by the host, e.g. packets larger than MTU or next buffer
in the ring was not available for a scatter transfer.

Part of aggregate "frame" errors in `/proc/net/dev`.

This statistics was historically used interchangeably with
**rx_fifo_errors**.

This statistic corresponds to hardware events and is not commonly used
on software devices.

For IEEE 802.3 devices this counter must be equivalent to:

- 30.3.1.1.6 aFrameCheckSequenceErrors

For IEEE 802.3 devices this counter should be equivalent to:

- 30.3.1.1.7 aAlignmentErrors

Historically the count of overflow events. Those events may be
reported in the receive descriptors or via interrupts, and may
not correspond one-to-one with dropped packets.

This statistics was used interchangeably with **rx_over_errors**.
Not recommended for use in drivers for high speed interfaces.

This statistic is used on software devices, e.g. to count software
packet queue overflow (can) or sequencing errors (GRE).

Counts number of packets dropped by the device due to lack
of buffer space. This usually indicates that the host interface
is slower than the network interface, or host is not keeping up
with the receive packet rate.

This statistic corresponds to hardware events and is not used
on software devices.

- 30.3.1.1.11 aFramesAbortedDueToXSColls

High speed interfaces may use this counter as a general device
discard counter.

For IEEE 802.3 devices this counter must be equivalent to:

- 30.3.1.1.13 aCarrierSenseErrors

For IEEE 802.3 devices possibly equivalent to:

- 30.3.2.1.4 aSQETestErrors

For IEEE 802.3 devices this counter must be equivalent to:

- 30.3.1.1.10 aLateCollisions


<a id="rst-notes-for-driver-authors"></a>

## Notes for driver authors

Drivers should report all statistics which have a matching member in `struct rtnl_link_stats64 <rtnl_link_stats64>` exclusively via `.ndo_get_stats64`. Reporting such standard stats via ethtool or debugfs will not be accepted.

Drivers must ensure best possible compliance with `struct rtnl_link_stats64 <rtnl_link_stats64>`. Please note for example that detailed error statistics must be added into the general `rx_error` / `tx_error` counters.

The `.ndo_get_stats64` callback can not sleep because of accesses via `/proc/net/dev`. If driver may sleep when retrieving the statistics from the device it should do so periodically asynchronously and only return a recent copy from `.ndo_get_stats64`. Ethtool interrupt coalescing interface allows setting the frequency of refreshing statistics, if needed.

Retrieving ethtool statistics is a multi-syscall process, drivers are advised to keep the number of statistics constant to avoid race conditions with user space trying to read them.

Statistics must persist across routine operations like bringing the interface down and up.

<a id="rst-kernel-internal-data-structures"></a>

### Kernel-internal data structures

The following structures are internal to the kernel, their members are translated to netlink attributes when dumped. Drivers must not overwrite the statistics they don't report with 0.

- ethtool_pause_stats()

- ethtool_fec_stats()

---

# Stream Parser (strparser)

_Peios Kernel / Internals / Networking_

> The stream parser (strparser) is a utility that parses messages of an application layer protocol running over a data stream. The stream parser works in conjunction with an upper layer in the kernel to provide kernel support for application…

<a id="rst-stream-parser-strparser"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The stream parser (strparser) is a utility that parses messages of an application layer protocol running over a data stream. The stream parser works in conjunction with an upper layer in the kernel to provide kernel support for application layer messages. For instance, Kernel Connection Multiplexor (KCM) uses the Stream Parser to parse messages using a BPF program.

The strparser works in one of two modes: receive callback or general mode.

In receive callback mode, the strparser is called from the data_ready callback of a TCP socket. Messages are parsed and delivered as they are received on the socket.

In general mode, a sequence of skbs are fed to strparser from an outside source. Message are parsed and delivered as the sequence is processed. This modes allows strparser to be applied to arbitrary streams of data.

<a id="rst-interface"></a>

## Interface

The API includes a context structure, a set of callbacks, utility functions, and a data_ready function for receive callback mode. The callbacks include a parse_msg function that is called to perform parsing (e.g.  BPF parsing in case of KCM), and a rcv_msg function that is called when a full message has been completed.

<a id="rst-functions"></a>

## Functions

> >
> >
> > ```text
> > strp_init(struct strparser *strp, struct sock *sk,
> >         const struct strp_callbacks *cb)
> > ```
> >
> > Called to initialize a stream parser. strp is a struct of type strparser that is allocated by the upper layer. sk is the TCP socket associated with the stream parser for use with receive callback mode; in general mode this is set to NULL. Callbacks are called by the stream parser (the callbacks are listed below).
> >
> >
> >
> > ```text
> > void strp_pause(struct strparser *strp)
> > ```
> >
> > Temporarily pause a stream parser. Message parsing is suspended and no new messages are delivered to the upper layer.
> >
> >
> >
> > ```text
> > void strp_unpause(struct strparser *strp)
> > ```
> >
> > Unpause a paused stream parser.
> >
> >
> >
> > ```text
> > void strp_stop(struct strparser *strp);
> > ```
> >
> > strp_stop is called to completely stop stream parser operations. This is called internally when the stream parser encounters an error, and it is called from the upper layer to stop parsing operations.
> >
> >
> >
> > ```text
> > void strp_done(struct strparser *strp);
> > ```
> >
> > strp_done is called to release any resources held by the stream parser instance. This must be called after the stream processor has been stopped.
> >
> >
> >
> > ```text
> > int strp_process(struct strparser *strp, struct sk_buff *orig_skb,
> >                  unsigned int orig_offset, size_t orig_len,
> >                  size_t max_msg_size, long timeo)
> > ```
>
> strp_process is called in general mode for a stream parser to parse an sk_buff. The number of bytes processed or a negative error number is returned. Note that strp_process does not consume the sk_buff. max_msg_size is maximum size the stream parser will parse. timeo is timeout for completing a message.
>
>
>
> ```text
> void strp_data_ready(struct strparser *strp);
> ```
>
> The upper layer calls strp_tcp_data_ready when data is ready on the lower socket for strparser to process. This should be called from a data_ready callback that is set on the socket. Note that maximum messages size is the limit of the receive socket buffer and message timeout is the receive timeout for the socket.
>
>
>
> ```text
> void strp_check_rcv(struct strparser *strp);
> ```
>
> strp_check_rcv is called to check for new messages on the socket. This is normally called at initialization of a stream parser instance or after strp_unpause.

<a id="rst-callbacks"></a>

## Callbacks

There are seven callbacks:

>
>
> ```text
> int (*parse_msg)(struct strparser *strp, struct sk_buff *skb);
> ```
>
> parse_msg is called to determine the length of the next message in the stream. The upper layer must implement this function. It should parse the sk_buff as containing the headers for the next application layer message in the stream.
>
> The skb-&gt;cb in the input skb is a struct strp_msg. Only the offset field is relevant in parse_msg and gives the offset where the message starts in the skb.
>
> The return values of this function are:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> &gt;0
>
> </td>
> <td>
>
>
> indicates length of successfully parsed message
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> indicates more data must be received to parse the message
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ESTRPIPE
>
> </td>
> <td>
>
>
> current message should not be processed by the kernel, return control of the socket to userspace which can proceed to read the messages itself
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> other &lt; 0
>
> </td>
> <td>
>
>
> Error in parsing, give control back to userspace assuming that synchronization is lost and the stream is unrecoverable (application expected to close TCP socket)
>
> </td>
> </tr>
> </tbody>
> </table>
>
> In the case that an error is returned (return value is less than zero) and the parser is in receive callback mode, then it will set the error on TCP socket and wake it up. If parse_msg returned -ESTRPIPE and the stream parser had previously read some bytes for the current message, then the error set on the attached socket is ENODATA since the stream is unrecoverable in that case.
>
>
>
> ```text
> void (*lock)(struct strparser *strp)
> ```
>
> The lock callback is called to lock the strp structure when the strparser is performing an asynchronous operation (such as processing a timeout). In receive callback mode the default function is to lock_sock for the associated socket. In general mode the callback must be set appropriately.
>
>
>
> ```text
> void (*unlock)(struct strparser *strp)
> ```
>
> The unlock callback is called to release the lock obtained by the lock callback. In receive callback mode the default function is release_sock for the associated socket. In general mode the callback must be set appropriately.
>
>
>
> ```text
> void (*rcv_msg)(struct strparser *strp, struct sk_buff *skb);
> ```
>
> rcv_msg is called when a full message has been received and is queued. The callee must consume the sk_buff; it can call strp_pause to prevent any further messages from being received in rcv_msg (see strp_pause above). This callback must be set.
>
> The skb-&gt;cb in the input skb is a struct strp_msg. This struct contains two fields: offset and full_len. Offset is where the message starts in the skb, and full_len is the the length of the message. skb-&gt;len - offset may be greater than full_len since strparser does not trim the skb.
>
>
>
> ```text
> int (*read_sock)(struct strparser *strp, read_descriptor_t *desc,
>              sk_read_actor_t recv_actor);
> ```
>
> The read_sock callback is used by strparser instead of sock-&gt;ops-&gt;read_sock, if provided.
>
>
>
> ```text
>    int (*read_sock_done)(struct strparser *strp, int err);
>
> read_sock_done is called when the stream parser is done reading
> the TCP socket in receive callback mode. The stream parser may
> read multiple messages in a loop and this function allows cleanup
> to occur when exiting the loop. If the callback is not set (NULL
> in strp_init) a default function is used.
>
> ::
>
>    void (*abort_parser)(struct strparser *strp, int err);
>
> This function is called when stream parser encounters an error
> in parsing. The default function stops the stream parser and
> sets the error in the socket if the parser is in receive callback
> mode. The default function can be changed by setting the callback
> to non-NULL in strp_init.
> ```

<a id="rst-statistics"></a>

## Statistics

Various counters are kept for each stream parser instance. These are in the strp_stats structure. strp_aggr_stats is a convenience structure for accumulating statistics for multiple stream parser instances. save_strp_stats and aggregate_strp_stats are helper functions to save and aggregate statistics.

<a id="rst-message-assembly-limits"></a>

## Message assembly limits

The stream parser provide mechanisms to limit the resources consumed by message assembly.

A timer is set when assembly starts for a new message. In receive callback mode the message timeout is taken from rcvtime for the associated TCP socket. In general mode, the timeout is passed as an argument in strp_process. If the timer fires before assembly completes the stream parser is aborted and the ETIMEDOUT error is set on the TCP socket if in receive callback mode.

In receive callback mode, message length is limited to the receive buffer size of the associated TCP socket. If the length returned by parse_msg is greater than the socket buffer size then the stream parser is aborted with EMSGSIZE error set on the TCP socket. Note that this makes the maximum size of receive skbuffs for a socket with a stream parser to be 2\*sk_rcvbuf of the TCP socket.

In general mode the message length limit is passed in as an argument to strp_process.

<a id="rst-author"></a>

## Author

Tom Herbert ([tom@quantonium.net](<mailto:tom@quantonium.net>))

---

# Ethernet switch device driver model (switchdev)

_Peios Kernel / Internals / Networking_

> Copyright © 2014 Jiri Pirko <jiri@resnulli.us>

<a id="rst-ethernet-switch-device-driver-model-switchdev"></a>
<a id="rst-switchdev"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © 2014 Jiri Pirko &lt;[jiri@resnulli.us](<mailto:jiri@resnulli.us>)&gt;

Copyright © 2014-2015 Scott Feldman &lt;[sfeldma@gmail.com](<mailto:sfeldma@gmail.com>)&gt;

The Ethernet switch device driver model (switchdev) is an in-kernel driver model for switch devices which offload the forwarding (data) plane from the kernel.

Figure 1 is a block diagram showing the components of the switchdev model for an example setup using a data-center-class switch ASIC chip.  Other setups with SR-IOV or soft switches, such as OVS, are possible.



```text
                       User-space tools

 user space                   |
+-------------------------------------------------------------------+
 kernel                       | Netlink
                              |
               +--------------+-------------------------------+
               |         Network stack                        |
               |           (Linux)                            |
               |                                              |
               +----------------------------------------------+

                     sw1p2     sw1p4     sw1p6
                sw1p1  +  sw1p3  +  sw1p5  +          eth1
                  +    |    +    |    +    |            +
                  |    |    |    |    |    |            |
               +--+----+----+----+----+----+---+  +-----+-----+
               |         Switch driver         |  |    mgmt   |
               |        (this document)        |  |   driver  |
               |                               |  |           |
               +--------------+----------------+  +-----------+
                              |
 kernel                       | HW bus (eg PCI)
+-------------------------------------------------------------------+
 hardware                     |
               +--------------+----------------+
               |         Switch device (sw1)   |
               |  +----+                       +--------+
               |  |    v offloaded data path   | mgmt port
               |  |    |                       |
               +--|----|----+----+----+----+---+
                  |    |    |    |    |    |
                  +    +    +    +    +    +
                 p1   p2   p3   p4   p5   p6

                       front-panel ports


                              Fig 1.
```

<a id="rst-include-files"></a>

## Include Files



```text
#include <linux/netdevice.h>
#include <net/switchdev.h>
```

<a id="rst-configuration"></a>

## Configuration

Use "depends NET_SWITCHDEV" in driver's Kconfig to ensure switchdev model support is built for driver.

<a id="rst-switch-ports"></a>

## Switch Ports

On switchdev driver initialization, the driver will allocate and register a struct net_device (using register_netdev()) for each enumerated physical switch port, called the port netdev.  A port netdev is the software representation of the physical port and provides a conduit for control traffic to/from the controller (the kernel) and the network, as well as an anchor point for higher level constructs such as bridges, bonds, VLANs, tunnels, and L3 routers.  Using standard netdev tools (iproute2, ethtool, etc), the port netdev can also provide to the user access to the physical properties of the switch port such as PHY link state and I/O statistics.

There is (currently) no higher-level kernel object for the switch beyond the port netdevs.  All of the switchdev driver ops are netdev ops or switchdev ops.

A switch management port is outside the scope of the switchdev driver model. Typically, the management port is not participating in offloaded data plane and is loaded with a different driver, such as a NIC driver, on the management port device.

<a id="rst-switch-id"></a>

### Switch ID

The switchdev driver must implement the net_device operation ndo_get_port_parent_id for each port netdev, returning the same physical ID for each port of a switch. The ID must be unique between switches on the same system. The ID does not need to be unique between switches on different systems.

The switch ID is used to locate ports on a switch and to know if aggregated ports belong to the same switch.

<a id="rst-port-netdev-naming"></a>

### Port Netdev Naming

Udev rules should be used for port netdev naming, using some unique attribute of the port as a key, for example the port MAC address or the port PHYS name. Hard-coding of kernel netdev names within the driver is discouraged; let the kernel pick the default netdev name, and let udev set the final name based on a port attribute.

Using port PHYS name (ndo_get_phys_port_name) for the key is particularly useful for dynamically-named ports where the device names its ports based on external configuration.  For example, if a physical 40G port is split logically into 4 10G ports, resulting in 4 port netdevs, the device can give a unique name for each port using port PHYS name.  The udev rule would be:



```text
SUBSYSTEM=="net", ACTION=="add", ATTR{phys_switch_id}=="<phys_switch_id>", \
        ATTR{phys_port_name}!="", NAME="swX$attr{phys_port_name}"
```

Suggested naming convention is "swXpYsZ", where X is the switch name or ID, Y is the port name or ID, and Z is the sub-port name or ID.  For example, sw1p1s0 would be sub-port 0 on port 1 on switch 1.

<a id="rst-port-features"></a>

### Port Features

dev-&gt;netns_immutable

If the switchdev driver (and device) only supports offloading of the default network namespace (netns), the driver should set this private flag to prevent the port netdev from being moved out of the default netns.  A netns-aware driver/device would not set this flag and be responsible for partitioning hardware to preserve netns containment.  This means hardware cannot forward traffic from a port in one namespace to another port in another namespace.

<a id="rst-port-topology"></a>

### Port Topology

The port netdevs representing the physical switch ports can be organized into higher-level switching constructs.  The default construct is a standalone router port, used to offload L3 forwarding.  Two or more ports can be bonded together to form a LAG.  Two or more ports (or LAGs) can be bridged to bridge L2 networks.  VLANs can be applied to sub-divide L2 networks.  L2-over-L3 tunnels can be built on ports.  These constructs are built using standard Linux tools such as the bridge driver, the bonding/team drivers, and netlink-based tools such as iproute2.

The switchdev driver can know a particular port's position in the topology by monitoring NETDEV_CHANGEUPPER notifications.  For example, a port moved into a bond will see its upper master change.  If that bond is moved into a bridge, the bond's upper master will change.  And so on.  The driver will track such movements to know what position a port is in in the overall topology by registering for netdevice events and acting on NETDEV_CHANGEUPPER.

<a id="rst-l2-forwarding-offload"></a>

## L2 Forwarding Offload

The idea is to offload the L2 data forwarding (switching) path from the kernel to the switchdev device by mirroring bridge FDB entries down to the device.  An FDB entry is the \{port, MAC, VLAN\} tuple forwarding destination.

To offloading L2 bridging, the switchdev driver/device should support:

> - Static FDB entries installed on a bridge port
>
> - Notification of learned/forgotten src mac/vlans from device
>
> - STP state changes on the port
>
> - VLAN flooding of multicast/broadcast and unknown unicast packets

<a id="rst-static-fdb-entries"></a>

### Static FDB Entries

A driver which implements the `ndo_fdb_add`, `ndo_fdb_del` and `ndo_fdb_dump` operations is able to support the command below, which adds a static bridge FDB entry:



```text
bridge fdb add dev DEV ADDRESS [vlan VID] [self] static
```

(the "static" keyword is non-optional: if not specified, the entry defaults to being "local", which means that it should not be forwarded)

The "self" keyword (optional because it is implicit) has the role of instructing the kernel to fulfill the operation through the `ndo_fdb_add` implementation of the `DEV` device itself. If `DEV` is a bridge port, this will bypass the bridge and therefore leave the software database out of sync with the hardware one.

To avoid this, the "master" keyword can be used:



```text
bridge fdb add dev DEV ADDRESS [vlan VID] master static
```

The above command instructs the kernel to search for a master interface of `DEV` and fulfill the operation through the `ndo_fdb_add` method of that. This time, the bridge generates a `SWITCHDEV_FDB_ADD_TO_DEVICE` notification which the port driver can handle and use it to program its hardware table. This way, the software and the hardware database will both contain this static FDB entry.

Note: for new switchdev drivers that offload the Linux bridge, implementing the `ndo_fdb_add` and `ndo_fdb_del` bridge bypass methods is strongly discouraged: all static FDB entries should be added on a bridge port using the "master" flag. The `ndo_fdb_dump` is an exception and can be implemented to visualize the hardware tables, if the device does not have an interrupt for notifying the operating system of newly learned/forgotten dynamic FDB addresses. In that case, the hardware FDB might end up having entries that the software FDB does not, and implementing `ndo_fdb_dump` is the only way to see them.

Note: by default, the bridge does not filter on VLAN and only bridges untagged traffic.  To enable VLAN support, turn on VLAN filtering:



```text
echo 1 >/sys/class/net/<bridge>/bridge/vlan_filtering
```

<a id="rst-notification-of-learned-forgotten-source-mac-vlans"></a>

### Notification of Learned/Forgotten Source MAC/VLANs

The switch device will learn/forget source MAC address/VLAN on ingress packets and notify the switch driver of the mac/vlan/port tuples.  The switch driver, in turn, will notify the bridge driver using the switchdev notifier call:



```text
err = call_switchdev_notifiers(val, dev, info, extack);
```

Where val is SWITCHDEV_FDB_ADD when learning and SWITCHDEV_FDB_DEL when forgetting, and info points to a struct switchdev_notifier_fdb_info.  On SWITCHDEV_FDB_ADD, the bridge driver will install the FDB entry into the bridge's FDB and mark the entry as NTF_EXT_LEARNED.  The iproute2 bridge command will label these entries "offload":



```text
$ bridge fdb
52:54:00:12:35:01 dev sw1p1 master br0 permanent
00:02:00:00:02:00 dev sw1p1 master br0 offload
00:02:00:00:02:00 dev sw1p1 self
52:54:00:12:35:02 dev sw1p2 master br0 permanent
00:02:00:00:03:00 dev sw1p2 master br0 offload
00:02:00:00:03:00 dev sw1p2 self
33:33:00:00:00:01 dev eth0 self permanent
01:00:5e:00:00:01 dev eth0 self permanent
33:33:ff:00:00:00 dev eth0 self permanent
01:80:c2:00:00:0e dev eth0 self permanent
33:33:00:00:00:01 dev br0 self permanent
01:00:5e:00:00:01 dev br0 self permanent
33:33:ff:12:35:01 dev br0 self permanent
```

Learning on the port should be disabled on the bridge using the bridge command:



```text
bridge link set dev DEV learning off
```

Learning on the device port should be enabled, as well as learning_sync:



```text
bridge link set dev DEV learning on self
bridge link set dev DEV learning_sync on self
```

Learning_sync attribute enables syncing of the learned/forgotten FDB entry to the bridge's FDB.  It's possible, but not optimal, to enable learning on the device port and on the bridge port, and disable learning_sync.

To support learning, the driver implements switchdev op switchdev_port_attr_set for SWITCHDEV_ATTR_PORT_ID\_\{PRE\}\_BRIDGE_FLAGS.

<a id="rst-fdb-ageing"></a>

### FDB Ageing

The bridge will skip ageing FDB entries marked with NTF_EXT_LEARNED and it is the responsibility of the port driver/device to age out these entries.  If the port device supports ageing, when the FDB entry expires, it will notify the driver which in turn will notify the bridge with SWITCHDEV_FDB_DEL.  If the device does not support ageing, the driver can simulate ageing using a garbage collection timer to monitor FDB entries.  Expired entries will be notified to the bridge using SWITCHDEV_FDB_DEL.  See rocker driver for example of driver running ageing timer.

To keep an NTF_EXT_LEARNED entry "alive", the driver should refresh the FDB entry by calling call_switchdev_notifiers(SWITCHDEV_FDB_ADD, ...).  The notification will reset the FDB entry's last-used time to now.  The driver should rate limit refresh notifications, for example, no more than once a second.  (The last-used time is visible using the bridge -s fdb option).

<a id="rst-stp-state-change-on-port"></a>

### STP State Change on Port

Internally or with a third-party STP protocol implementation (e.g. mstpd), the bridge driver maintains the STP state for ports, and will notify the switch driver of STP state change on a port using the switchdev op switchdev_attr_port_set for SWITCHDEV_ATTR_PORT_ID_STP_UPDATE.

State is one of BR_STATE\_\*.  The switch driver can use STP state updates to update ingress packet filter list for the port.  For example, if port is DISABLED, no packets should pass, but if port moves to BLOCKED, then STP BPDUs and other IEEE 01:80:c2:xx:xx:xx link-local multicast packets can pass.

Note that STP BDPUs are untagged and STP state applies to all VLANs on the port so packet filters should be applied consistently across untagged and tagged VLANs on the port.

<a id="rst-flooding-l2-domain"></a>

### Flooding L2 domain

For a given L2 VLAN domain, the switch device should flood multicast/broadcast and unknown unicast packets to all ports in domain, if allowed by port's current STP state.  The switch driver, knowing which ports are within which vlan L2 domain, can program the switch device for flooding.  The packet may be sent to the port netdev for processing by the bridge driver.  The bridge should not reflood the packet to the same ports the device flooded, otherwise there will be duplicate packets on the wire.

To avoid duplicate packets, the switch driver should mark a packet as already forwarded by setting the skb-&gt;offload_fwd_mark bit. The bridge driver will mark the skb using the ingress bridge port's mark and prevent it from being forwarded through any bridge port with the same mark.

It is possible for the switch device to not handle flooding and push the packets up to the bridge driver for flooding.  This is not ideal as the number of ports scale in the L2 domain as the device is much more efficient at flooding packets that software.

If supported by the device, flood control can be offloaded to it, preventing certain netdevs from flooding unicast traffic for which there is no FDB entry.

<a id="rst-igmp-snooping"></a>

### IGMP Snooping

In order to support IGMP snooping, the port netdevs should trap to the bridge driver all IGMP join and leave messages. The bridge multicast module will notify port netdevs on every multicast group changed whether it is static configured or dynamically joined/leave. The hardware implementation should be forwarding all registered multicast traffic groups only to the configured ports.

<a id="rst-l3-routing-offload"></a>

## L3 Routing Offload

Offloading L3 routing requires that device be programmed with FIB entries from the kernel, with the device doing the FIB lookup and forwarding.  The device does a longest prefix match (LPM) on FIB entries matching route prefix and forwards the packet to the matching FIB entry's nexthop(s) egress ports.

To program the device, the driver has to register a FIB notifier handler using register_fib_notifier. The following events are available:


<table>
<tbody>
<tr>
<td>


FIB_EVENT_ENTRY_ADD

</td>
<td>


used for both adding a new FIB entry to the device, or modifying an existing entry on the device.

</td>
</tr>
<tr>
<td>


FIB_EVENT_ENTRY_DEL

</td>
<td>


used for removing a FIB entry

</td>
</tr>
<tr>
<td>


FIB_EVENT_RULE_ADD,

</td>
<td>




</td>
</tr>
<tr>
<td>


FIB_EVENT_RULE_DEL

</td>
<td>


used to propagate FIB rule changes

</td>
</tr>
</tbody>
</table>

FIB_EVENT_ENTRY_ADD and FIB_EVENT_ENTRY_DEL events pass:



```text
struct fib_entry_notifier_info {
        struct fib_notifier_info info; /* must be first */
        u32 dst;
        int dst_len;
        struct fib_info *fi;
        u8 tos;
        u8 type;
        u32 tb_id;
        u32 nlflags;
};
```

to add/modify/delete IPv4 dst/dest_len prefix on table tb_id.  The `*fi` structure holds details on the route and route's nexthops.  `*dev` is one of the port netdevs mentioned in the route's next hop list.

Routes offloaded to the device are labeled with "offload" in the ip route listing:



```text
$ ip route show
default via 192.168.0.2 dev eth0
11.0.0.0/30 dev sw1p1  proto kernel  scope link  src 11.0.0.2 offload
11.0.0.4/30 via 11.0.0.1 dev sw1p1  proto zebra  metric 20 offload
11.0.0.8/30 dev sw1p2  proto kernel  scope link  src 11.0.0.10 offload
11.0.0.12/30 via 11.0.0.9 dev sw1p2  proto zebra  metric 20 offload
12.0.0.2  proto zebra  metric 30 offload
        nexthop via 11.0.0.1  dev sw1p1 weight 1
        nexthop via 11.0.0.9  dev sw1p2 weight 1
12.0.0.3 via 11.0.0.1 dev sw1p1  proto zebra  metric 20 offload
12.0.0.4 via 11.0.0.9 dev sw1p2  proto zebra  metric 20 offload
192.168.0.0/24 dev eth0  proto kernel  scope link  src 192.168.0.15
```

The "offload" flag is set in case at least one device offloads the FIB entry.

XXX: add/mod/del IPv6 FIB API

<a id="rst-nexthop-resolution"></a>

### Nexthop Resolution

The FIB entry's nexthop list contains the nexthop tuple (gateway, dev), but for the switch device to forward the packet with the correct dst mac address, the nexthop gateways must be resolved to the neighbor's mac address.  Neighbor mac address discovery comes via the ARP (or ND) process and is available via the arp_tbl neighbor table.  To resolve the routes nexthop gateways, the driver should trigger the kernel's neighbor resolution process.  See the rocker driver's rocker_port_ipv4_resolve() for an example.

The driver can monitor for updates to arp_tbl using the netevent notifier NETEVENT_NEIGH_UPDATE.  The device can be programmed with resolved nexthops for the routes as arp_tbl updates.  The driver implements ndo_neigh_destroy to know when arp_tbl neighbor entries are purged from the port.

<a id="rst-device-driver-expected-behavior"></a>

## Device driver expected behavior

Below is a set of defined behavior that switchdev enabled network devices must adhere to.

<a id="rst-configuration-less-state"></a>

### Configuration-less state

Upon driver bring up, the network devices must be fully operational, and the backing driver must configure the network device such that it is possible to send and receive traffic to this network device and it is properly separated from other network devices/ports (e.g.: as is frequent with a switch ASIC). How this is achieved is heavily hardware dependent, but a simple solution can be to use per-port VLAN identifiers unless a better mechanism is available (proprietary metadata for each network port for instance).

The network device must be capable of running a full IP protocol stack including multicast, DHCP, IPv4/6, etc. If necessary, it should program the appropriate filters for VLAN, multicast, unicast etc. The underlying device driver must effectively be configured in a similar fashion to what it would do when IGMP snooping is enabled for IP multicast over these switchdev network devices and unsolicited multicast must be filtered as early as possible in the hardware.

When configuring VLANs on top of the network device, all VLANs must be working, irrespective of the state of other network devices (e.g.: other ports being part of a VLAN-aware bridge doing ingress VID checking). See below for details.

If the device implements e.g.: VLAN filtering, putting the interface in promiscuous mode should allow the reception of all VLAN tags (including those not present in the filter(s)).

<a id="rst-bridged-switch-ports"></a>

### Bridged switch ports

When a switchdev enabled network device is added as a bridge member, it should not disrupt any functionality of non-bridged network devices and they should continue to behave as normal network devices. Depending on the bridge configuration knobs below, the expected behavior is documented.

<a id="rst-bridge-vlan-filtering"></a>

### Bridge VLAN filtering

The Linux bridge allows the configuration of a VLAN filtering mode (statically, at device creation time, and dynamically, during run time) which must be observed by the underlying switchdev network device/hardware:

- with VLAN filtering turned off: the bridge is strictly VLAN unaware and its data path will process all Ethernet frames as if they are VLAN-untagged. The bridge VLAN database can still be modified, but the modifications should have no effect while VLAN filtering is turned off. Frames ingressing the device with a VID that is not programmed into the bridge/switch's VLAN table must be forwarded and may be processed using a VLAN device (see below).

- with VLAN filtering turned on: the bridge is VLAN-aware and frames ingressing the device with a VID that is not programmed into the bridges/switch's VLAN table must be dropped (strict VID checking).

When there is a VLAN device (e.g: sw0p1.100) configured on top of a switchdev network device which is a bridge port member, the behavior of the software network stack must be preserved, or the configuration must be refused if that is not possible.

- with VLAN filtering turned off, the bridge will process all ingress traffic for the port, except for the traffic tagged with a VLAN ID destined for a VLAN upper. The VLAN upper interface (which consumes the VLAN tag) can even be added to a second bridge, which includes other switch ports or software interfaces. Some approaches to ensure that the forwarding domain for traffic belonging to the VLAN upper interfaces are managed properly:

  > - If forwarding destinations can be managed per VLAN, the hardware could be configured to map all traffic, except the packets tagged with a VID belonging to a VLAN upper interface, to an internal VID corresponding to untagged packets. This internal VID spans all ports of the VLAN-unaware bridge. The VID corresponding to the VLAN upper interface spans the physical port of that VLAN interface, as well as the other ports that might be bridged with it.
  >
  > - Treat bridge ports with VLAN upper interfaces as standalone, and let forwarding be handled in the software data path.

- with VLAN filtering turned on, these VLAN devices can be created as long as the bridge does not have an existing VLAN entry with the same VID on any bridge port. These VLAN devices cannot be enslaved into the bridge since they duplicate functionality/use case with the bridge's VLAN data path processing.

Non-bridged network ports of the same switch fabric must not be disturbed in any way by the enabling of VLAN filtering on the bridge device(s). If the VLAN filtering setting is global to the entire chip, then the standalone ports should indicate to the network stack that VLAN filtering is required by setting 'rx-vlan-filter: on \[fixed\]' in the ethtool features.

Because VLAN filtering can be turned on/off at runtime, the switchdev driver must be able to reconfigure the underlying hardware on the fly to honor the toggling of that option and behave appropriately. If that is not possible, the switchdev driver can also refuse to support dynamic toggling of the VLAN filtering knob at runtime and require a destruction of the bridge device(s) and creation of new bridge device(s) with a different VLAN filtering value to ensure VLAN awareness is pushed down to the hardware.

Even when VLAN filtering in the bridge is turned off, the underlying switch hardware and driver may still configure itself in a VLAN-aware mode provided that the behavior described above is observed.

The VLAN protocol of the bridge plays a role in deciding whether a packet is treated as tagged or not: a bridge using the 802.1ad protocol must treat both VLAN-untagged packets, as well as packets tagged with 802.1Q headers, as untagged.

The 802.1p (VID 0) tagged packets must be treated in the same way by the device as untagged packets, since the bridge device does not allow the manipulation of VID 0 in its database.

When the bridge has VLAN filtering enabled and a PVID is not configured on the ingress port, untagged and 802.1p tagged packets must be dropped. When the bridge has VLAN filtering enabled and a PVID exists on the ingress port, untagged and priority-tagged packets must be accepted and forwarded according to the bridge's port membership of the PVID VLAN. When the bridge has VLAN filtering disabled, the presence/lack of a PVID should not influence the packet forwarding decision.

<a id="rst-bridge-igmp-snooping"></a>

### Bridge IGMP snooping

The Linux bridge allows the configuration of IGMP snooping (statically, at interface creation time, or dynamically, during runtime) which must be observed by the underlying switchdev network device/hardware in the following way:

- when IGMP snooping is turned off, multicast traffic must be flooded to all ports within the same bridge that have mcast_flood=true. The CPU/management port should ideally not be flooded (unless the ingress interface has IFF_ALLMULTI or IFF_PROMISC) and continue to learn multicast traffic through the network stack notifications. If the hardware is not capable of doing that then the CPU/management port must also be flooded and multicast filtering happens in software.

- when IGMP snooping is turned on, multicast traffic must selectively flow to the appropriate network ports (including CPU/management port). Flooding of unknown multicast should be only towards the ports connected to a multicast router (the local device may also act as a multicast router).

The switch must adhere to RFC 4541 and flood multicast traffic accordingly since that is what the Linux bridge implementation does.

Because IGMP snooping can be turned on/off at runtime, the switchdev driver must be able to reconfigure the underlying hardware on the fly to honor the toggling of that option and behave appropriately.

A switchdev driver can also refuse to support dynamic toggling of the multicast snooping knob at runtime and require the destruction of the bridge device(s) and creation of a new bridge device(s) with a different multicast snooping value.

---

# Sysfs tagging

_Peios Kernel / Internals / Networking_

> (Taken almost verbatim from Eric Biederman's netns tagging patch commit msg)

<a id="rst-sysfs-tagging"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

(Taken almost verbatim from Eric Biederman's netns tagging patch commit msg)

The problem.  Network devices show up in sysfs and with the network namespace active multiple devices with the same name can show up in the same directory, ouch\!

To avoid that problem and allow existing applications in network namespaces to see the same interface that is currently presented in sysfs, sysfs now has tagging directory support.

By using the network namespace pointers as tags to separate out the sysfs directory entries we ensure that we don't have conflicts in the directories and applications only see a limited set of the network devices.

Each sysfs directory entry may be tagged with a namespace via the `void *ns member` of its `kernfs_node`.  If a directory entry is tagged, then `kernfs_node->flags` will have a flag between KOBJ_NS_TYPE_NONE and KOBJ_NS_TYPES, and ns will point to the namespace to which it belongs.

Each sysfs superblock's kernfs_super_info contains an array `void *ns[KOBJ_NS_TYPES]`.  When a task in a tagging namespace kobj_nstype first mounts sysfs, a new superblock is created.  It will be differentiated from other sysfs mounts by having its `s_fs_info->ns[kobj_nstype]` set to the new namespace.  Note that through bind mounting and mounts propagation, a task can easily view the contents of other namespaces' sysfs mounts.  Therefore, when a namespace exits, it will call kobj_ns_exit() to invalidate any kernfs_node-&gt;ns pointers pointing to it.

Users of this interface:

- define a type in the `kobj_ns_type` enumeration.

- call kobj_ns_type_register() with its `kobj_ns_type_operations` which has

  - current_ns() which returns current's namespace

  - netlink_ns() which returns a socket's namespace

  - initial_ns() which returns the initial namespace

- call kobj_ns_exit() when an individual tag is no longer valid

---

# TC Actions - Environmental Rules

_Peios Kernel / Internals / Networking_

> The "environmental" rules for authors of any new tc actions are:

<a id="rst-tc-actions-environmental-rules"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The "environmental" rules for authors of any new tc actions are:

1. If you stealeth or borroweth any packet thou shalt be branching from the righteous path and thou shalt cloneth.

   For example if your action queues a packet to be processed later, or intentionally branches by redirecting a packet, then you need to clone the packet.

2. If you munge any packet thou shalt call pskb_expand_head in the case someone else is referencing the skb. After that you "own" the skb.

3. Dropping packets you don't own is a no-no. You simply return TC_ACT_SHOT to the caller and they will drop it.

The "environmental" rules for callers of actions (qdiscs etc) are:

1. Thou art responsible for freeing anything returned as being TC_ACT_SHOT/STOLEN/QUEUED. If none of TC_ACT_SHOT/STOLEN/QUEUED is returned, then all is great and you don't need to do anything.

Post on netdev if something is unclear.

---

# TC queue based filtering

_Peios Kernel / Internals / Networking_

> TC can be used for directing traffic to either a set of queues or to a single queue on both the transmit and receive side.

<a id="rst-tc-queue-based-filtering"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

TC can be used for directing traffic to either a set of queues or to a single queue on both the transmit and receive side.

On the transmit side:

1. TC filter directing traffic to a set of queues is achieved using the action skbedit priority for Tx priority selection, the priority maps to a traffic class (set of queues) when the queue-sets are configured using mqprio.

2. TC filter directs traffic to a transmit queue with the action skbedit queue_mapping $tx_qid. The action skbedit queue_mapping for transmit queue is executed in software only and cannot be offloaded.

Likewise, on the receive side, the two filters for selecting set of queues and/or a single queue are supported as below:

1. TC flower filter directs incoming traffic to a set of queues using the 'hw_tc' option. hw_tc $TCID - Specify a hardware traffic class to pass matching packets on to. TCID is in the range 0 through 15.

2. TC filter with action skbedit queue_mapping $rx_qid selects a receive queue. The action skbedit queue_mapping for receive queue is supported only in hardware. Multiple filters may compete in the hardware for queue selection. In such case, the hardware pipeline resolves conflicts based on priority. On Intel E810 devices, TC filter directing traffic to a queue have higher priority over flow director filter assigning a queue. The hash filter has lowest priority.

---

# Thin-streams and TCP

_Peios Kernel / Internals / Networking_

> A wide range of Internet-based services that use reliable transport protocols display what we call thin-stream properties. This means that the application sends data with such a low rate that the retransmission mechanisms of the transport…

<a id="rst-thin-streams-and-tcp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

A wide range of Internet-based services that use reliable transport protocols display what we call thin-stream properties. This means that the application sends data with such a low rate that the retransmission mechanisms of the transport protocol are not fully effective. In time-dependent scenarios (like online games, control systems, stock trading etc.) where the user experience depends on the data delivery latency, packet loss can be devastating for the service quality. Extreme latencies are caused by TCP's dependency on the arrival of new data from the application to trigger retransmissions effectively through fast retransmit instead of waiting for long timeouts.

After analysing a large number of time-dependent interactive applications, we have seen that they often produce thin streams and also stay with this traffic pattern throughout its entire lifespan. The combination of time-dependency and the fact that the streams provoke high latencies when using TCP is unfortunate.

In order to reduce application-layer latency when packets are lost, a set of mechanisms has been made, which address these latency issues for thin streams. In short, if the kernel detects a thin stream, the retransmission mechanisms are modified in the following manner:

1. If the stream is thin, fast retransmit on the first dupACK.

2. If the stream is thin, do not apply exponential backoff.

These enhancements are applied only if the stream is detected as thin. This is accomplished by defining a threshold for the number of packets in flight. If there are less than 4 packets in flight, fast retransmissions can not be triggered, and the stream is prone to experience high retransmission latencies.

Since these mechanisms are targeted at time-dependent applications, they must be specifically activated by the application using the TCP_THIN_LINEAR_TIMEOUTS and TCP_THIN_DUPACK IOCTLS or the tcp_thin_linear_timeouts and tcp_thin_dupack sysctls. Both modifications are turned off by default.

<a id="rst-references"></a>

## References

More information on the modifications, as well as a wide range of experimental data can be found here:

"Improving latency for interactive, thin-stream applications over reliable transport" [http://simula.no/research/nd/publications/Simula.nd.477/simula_pdf_file](<http://simula.no/research/nd/publications/Simula.nd.477/simula_pdf_file>)

---

# TCP Authentication Option Linux implementation (RFC5925)

_Peios Kernel / Internals / Networking_

> TCP Authentication Option (TCP-AO) provides a TCP extension aimed at verifying segments between trusted peers. It adds a new TCP header option with a Message Authentication Code (MAC). MACs are produced from the content of a TCP segment…

<a id="rst-tcp-authentication-option-linux-implementation-rfc5925"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

TCP Authentication Option (TCP-AO) provides a TCP extension aimed at verifying segments between trusted peers. It adds a new TCP header option with a Message Authentication Code (MAC). MACs are produced from the content of a TCP segment using a hashing function with a password known to both peers. The intent of TCP-AO is to deprecate TCP-MD5 providing better security, key rotation and support for a variety of hashing algorithms.

<a id="rst-introduction"></a>

## 1. Introduction


<table>
<caption>Short and Limited Comparison of TCP-AO and TCP-MD5</caption>
<thead>
<tr>
<th>




</th>
<th>


TCP-MD5

</th>
<th>


TCP-AO

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Supported hashing algorithms

</td>
<td>


MD5 (cryptographically weak)

</td>
<td>


Must support HMAC-SHA1 (chosen-prefix attacks) and CMAC-AES-128 (only side-channel attacks). May support any hashing algorithm.

</td>
</tr>
<tr>
<td>


Length of MACs (bytes)

</td>
<td>


16

</td>
<td>


Typically 12-16. Other variants that fit TCP header permitted.

</td>
</tr>
<tr>
<td>


Number of keys per TCP connection

</td>
<td>


1

</td>
<td>


Many

</td>
</tr>
<tr>
<td>


Possibility to change an active key

</td>
<td>


Non-practical (both peers have to change them during MSL)

</td>
<td>


Supported by protocol

</td>
</tr>
<tr>
<td>


Protection against ICMP 'hard errors'

</td>
<td>


No

</td>
<td>


Yes: ignoring them by default on established connections

</td>
</tr>
<tr>
<td>


Protection against traffic-crossing attack

</td>
<td>


No

</td>
<td>


Yes: pseudo-header includes TCP ports.

</td>
</tr>
<tr>
<td>


Protection against replayed TCP segments

</td>
<td>


No

</td>
<td>


Sequence Number Extension (SNE) and Initial Sequence Numbers (ISNs)

</td>
</tr>
<tr>
<td>


Supports Connectionless Resets

</td>
<td>


Yes

</td>
<td>


No. ISNs+SNE are needed to correctly sign RST.

</td>
</tr>
<tr>
<td>


Standards

</td>
<td>


RFC 2385

</td>
<td>


RFC 5925, RFC 5926

</td>
</tr>
</tbody>
</table>

<a id="rst-frequently-asked-questions-faq-with-references-to-rfc-5925"></a>

### 1.1 Frequently Asked Questions (FAQ) with references to RFC 5925

Q: Can either SendID or RecvID be non-unique for the same 4-tuple (srcaddr, srcport, dstaddr, dstport)?

A: No \[3.1\]:



```text
>> The IDs of MKTs MUST NOT overlap where their TCP connection
identifiers overlap.
```

Q: Can Master Key Tuple (MKT) for an active connection be removed?

A: No, unless it's copied to Transport Control Block (TCB) \[3.1\]:



```text
It is presumed that an MKT affecting a particular connection cannot
be destroyed during an active connection -- or, equivalently, that
its parameters are copied to an area local to the connection (i.e.,
instantiated) and so changes would affect only new connections.
```

Q: If an old MKT needs to be deleted, how should it be done in order to not remove it for an active connection? (As it can be still in use at any moment later)

A: Not specified by RFC 5925, seems to be a problem for key management to ensure that no one uses such MKT before trying to remove it.

Q: Can an old MKT exist forever and be used by another peer?

A: It can, it's a key management task to decide when to remove an old key \[6.1\]:



```text
Deciding when to start using a key is a performance issue. Deciding
when to remove an MKT is a security issue. Invalid MKTs are expected
to be removed. TCP-AO provides no mechanism to coordinate their removal,
as we consider this a key management operation.
```

also \[6.1\]:



```text
The only way to avoid reuse of previously used MKTs is to remove the MKT
when it is no longer considered permitted.
```

Linux TCP-AO will try its best to prevent you from removing a key that's being used, considering it a key management failure. But since keeping an outdated key may become a security issue and as a peer may unintentionally prevent the removal of an old key by always setting it as RNextKeyID - a forced key removal mechanism is provided, where userspace has to supply KeyID to use instead of the one that's being removed and the kernel will atomically delete the old key, even if the peer is still requesting it. There are no guarantees for force-delete as the peer may yet not have the new key - the TCP connection may just break. Alternatively, one may choose to shut down the socket.

Q: What happens when a packet is received on a new connection with no known MKT's RecvID?

A: RFC 5925 specifies that by default it is accepted with a warning logged, but the behaviour can be configured by the user \[7.5.1.a\]:



```text
If the segment is a SYN, then this is the first segment of a new
connection. Find the matching MKT for this segment, using the segment's
socket pair and its TCP-AO KeyID, matched against the MKT's TCP connection
identifier and the MKT's RecvID.

   i. If there is no matching MKT, remove TCP-AO from the segment.
      Proceed with further TCP handling of the segment.
      NOTE: this presumes that connections that do not match any MKT
      should be silently accepted, as noted in Section 7.3.
```

\[7.3\]:



```text
>> A TCP-AO implementation MUST allow for configuration of the behavior
of segments with TCP-AO but that do not match an MKT. The initial default
of this configuration SHOULD be to silently accept such connections.
If this is not the desired case, an MKT can be included to match such
connections, or the connection can indicate that TCP-AO is required.
Alternately, the configuration can be changed to discard segments with
the AO option not matching an MKT.
```

\[10.2.b\]:



```text
Connections not matching any MKT do not require TCP-AO. Further, incoming
segments with TCP-AO are not discarded solely because they include
the option, provided they do not match any MKT.
```

Note that Linux TCP-AO implementation differs in this aspect. Currently, TCP-AO segments with unknown key signatures are discarded with warnings logged.

Q: Does the RFC imply centralized kernel key management in any way? (i.e. that a key on all connections MUST be rotated at the same time?)

A: Not specified. MKTs can be managed in userspace, the only relevant part to key changes is \[7.3\]:



```text
>> All TCP segments MUST be checked against the set of MKTs for matching
TCP connection identifiers.
```

Q: What happens when RNextKeyID requested by a peer is unknown? Should the connection be reset?

A: It should not, no action needs to be performed \[7.5.2.e\]:



```text
ii. If they differ, determine whether the RNextKeyID MKT is ready.

    1. If the MKT corresponding to the segment’s socket pair and RNextKeyID
    is not available, no action is required (RNextKeyID of a received
    segment needs to match the MKT’s SendID).
```

Q: How is current_key set, and when does it change? Is it a user-triggered change, or is it triggered by a request from the remote peer? Is it set by the user explicitly, or by a matching rule?

A: current_key is set by RNextKeyID \[6.1\]:



```text
Rnext_key is changed only by manual user intervention or MKT management
protocol operation. It is not manipulated by TCP-AO. Current_key is updated
by TCP-AO when processing received TCP segments as discussed in the segment
processing description in Section 7.5. Note that the algorithm allows
the current_key to change to a new MKT, then change back to a previously
used MKT (known as "backing up"). This can occur during an MKT change when
segments are received out of order, and is considered a feature of TCP-AO,
because reordering does not result in drops.
```

\[7.5.2.e.ii\]:



```text
2. If the matching MKT corresponding to the segment’s socket pair and
RNextKeyID is available:

   a. Set current_key to the RNextKeyID MKT.
```

Q: If both peers have multiple MKTs matching the connection's socket pair (with different KeyIDs), how should the sender/receiver pick KeyID to use?

A: Some mechanism should pick the "desired" MKT \[3.3\]:



```text
Multiple MKTs may match a single outgoing segment, e.g., when MKTs
are being changed. Those MKTs cannot have conflicting IDs (as noted
elsewhere), and some mechanism must determine which MKT to use for each
given outgoing segment.

>> An outgoing TCP segment MUST match at most one desired MKT, indicated
by the segment’s socket pair. The segment MAY match multiple MKTs, provided
that exactly one MKT is indicated as desired. Other information in
the segment MAY be used to determine the desired MKT when multiple MKTs
match; such information MUST NOT include values in any TCP option fields.
```

Q: Can TCP-MD5 connection migrate to TCP-AO (and vice-versa):

A: No \[1\]:



```text
TCP MD5-protected connections cannot be migrated to TCP-AO because TCP MD5
does not support any changes to a connection’s security algorithm
once established.
```

Q: If all MKTs are removed on a connection, can it become a non-TCP-AO signed connection?

A: \[7.5.2\] doesn't have the same choice as SYN packet handling in \[7.5.1.i\] that would allow accepting segments without a sign (which would be insecure). While switching to non-TCP-AO connection is not prohibited directly, it seems what the RFC means. Also, there's a requirement for TCP-AO connections to always have one current_key \[3.3\]:



```text
TCP-AO requires that every protected TCP segment match exactly one MKT.
```

\[3.3\]:



```text
>> An incoming TCP segment including TCP-AO MUST match exactly one MKT,
indicated solely by the segment’s socket pair and its TCP-AO KeyID.
```

\[4.4\]:



```text
One or more MKTs. These are the MKTs that match this connection’s
socket pair.
```

Q: Can a non-TCP-AO connection become a TCP-AO-enabled one?

A: No: for an already established non-TCP-AO connection it would be impossible to switch to using TCP-AO, as the traffic key generation requires the initial sequence numbers. Paraphrasing, starting using TCP-AO would require re-establishing the TCP connection.

<a id="rst-in-kernel-mkts-database-vs-database-in-userspace"></a>

## 2. In-kernel MKTs database vs database in userspace

Linux TCP-AO support is implemented using `setsockopt()s`, in a similar way to TCP-MD5. It means that a userspace application that wants to use TCP-AO should perform `setsockopt()` on a TCP socket when it wants to add, remove or rotate MKTs. This approach moves the key management responsibility to userspace as well as decisions on corner cases, i.e. what to do if the peer doesn't respect RNextKeyID; moving more code to userspace, especially responsible for the policy decisions. Besides, it's flexible and scales well (with less locking needed than in the case of an in-kernel database). One also should keep in mind that mainly intended users are BGP processes, not any random applications, which means that compared to IPsec tunnels, no transparency is really needed and modern BGP daemons already have `setsockopt()s` for TCP-MD5 support.


<table>
<caption>Considered pros and cons of the approaches</caption>
<thead>
<tr>
<th>




</th>
<th>


`setsockopt()`

</th>
<th>


in-kernel DB

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Extendability

</td>
<td>


`setsockopt()` commands should be extendable syscalls

</td>
<td>


Netlink messages are simple and extendable

</td>
</tr>
<tr>
<td>


Required userspace changes

</td>
<td>


BGP or any application that wants TCP-AO needs to perform `setsockopt()s` and do key management

</td>
<td>


could be transparent as tunnels, providing something like `ip tcpao add key` (delete/show/rotate)

</td>
</tr>
<tr>
<td>


MKTs removal or adding

</td>
<td>


harder for userspace

</td>
<td>


harder for kernel

</td>
</tr>
<tr>
<td>


Dump-ability

</td>
<td>


`getsockopt()`

</td>
<td>


Netlink .dump() callback

</td>
</tr>
<tr>
<td>


Limits on kernel resources/memory

</td>
<td colspan="2">


equal

</td>
</tr>
<tr>
<td>


Scalability

</td>
<td>


contention on `TCP_LISTEN` sockets

</td>
<td>


contention on the whole database

</td>
</tr>
<tr>
<td>


Monitoring &amp; warnings

</td>
<td>


`TCP_DIAG`

</td>
<td>


same Netlink socket

</td>
</tr>
<tr>
<td>


Matching of MKTs

</td>
<td>


half-problem: only listen sockets

</td>
<td>


hard

</td>
</tr>
</tbody>
</table>

<a id="rst-uapi"></a>

## 3. uAPI

Linux provides a set of `setsockopt()s` and `getsockopt()s` that let userspace manage TCP-AO on a per-socket basis. In order to add/delete MKTs `TCP_AO_ADD_KEY` and `TCP_AO_DEL_KEY` TCP socket options must be used. It is not allowed to add a key on an established non-TCP-AO connection as well as to remove the last key from TCP-AO connection.

`setsockopt(TCP_AO_DEL_KEY)` command may specify `tcp_ao_del::current_key` + `tcp_ao_del::set_current` and/or `tcp_ao_del::rnext` + `tcp_ao_del::set_rnext` which makes such delete "forced": it provides userspace a way to delete a key that's being used and atomically set another one instead. This is not intended for normal use and should be used only when the peer ignores RNextKeyID and keeps requesting/using an old key. It provides a way to force-delete a key that's not trusted but may break the TCP-AO connection.

The usual/normal key-rotation can be performed with `setsockopt(TCP_AO_INFO)`. It also provides a uAPI to change per-socket TCP-AO settings, such as ignoring ICMPs, as well as clear per-socket TCP-AO packet counters. The corresponding `getsockopt(TCP_AO_INFO)` can be used to get those per-socket TCP-AO settings.

Another useful command is `getsockopt(TCP_AO_GET_KEYS)`. One can use it to list all MKTs on a TCP socket or use a filter to get keys for a specific peer and/or sndid/rcvid, VRF L3 interface or get current_key/rnext_key.

To repair TCP-AO connections `setsockopt(TCP_AO_REPAIR)` is available, provided that the user previously has checkpointed/dumped the socket with `getsockopt(TCP_AO_REPAIR)`.

A tip here for scaled TCP_LISTEN sockets, that may have some thousands TCP-AO keys, is: use filters in `getsockopt(TCP_AO_GET_KEYS)` and asynchronous delete with `setsockopt(TCP_AO_DEL_KEY)`.

Linux TCP-AO also provides a bunch of segment counters that can be helpful with troubleshooting/debugging issues. Every MKT has good/bad counters that reflect how many packets passed/failed verification. Each TCP-AO socket has the following counters: - for good segments (properly signed) - for bad segments (failed TCP-AO verification) - for segments with unknown keys - for segments where an AO signature was expected, but wasn't found - for the number of ignored ICMPs

TCP-AO per-socket counters are also duplicated with per-netns counters, exposed with SNMP. Those are `TCPAOGood`, `TCPAOBad`, `TCPAOKeyNotFound`, `TCPAORequired` and `TCPAODroppedIcmps`.

For monitoring purposes, there are following TCP-AO trace events: `tcp_hash_bad_header`, `tcp_hash_ao_required`, `tcp_ao_handshake_failure`, `tcp_ao_wrong_maclen`, `tcp_ao_wrong_maclen`, `tcp_ao_key_not_found`, `tcp_ao_rnext_request`, `tcp_ao_synack_no_key`, `tcp_ao_snd_sne_update`, `tcp_ao_rcv_sne_update`. It's possible to separately enable any of them and one can filter them by net-namespace, 4-tuple, family, L3 index, and TCP header flags. If a segment has a TCP-AO header, the filters may also include keyid, rnext, and maclen. SNE updates include the rolled-over numbers.

RFC 5925 very permissively specifies how TCP port matching can be done for MKTs:



```text
TCP connection identifier. A TCP socket pair, i.e., a local IP
address, a remote IP address, a TCP local port, and a TCP remote port.
Values can be partially specified using ranges (e.g., 2-30), masks
(e.g., 0xF0), wildcards (e.g., "*"), or any other suitable indication.
```

Currently Linux TCP-AO implementation doesn't provide any TCP port matching. Probably, port ranges are the most flexible for uAPI, but so far not implemented.

<a id="rst-setsockopt-vs-accept-race"></a>

## 4. `setsockopt()` vs `accept()` race

In contrast with an established TCP-MD5 connection which has just one key, TCP-AO connections may have many keys, which means that accepted connections on a listen socket may have any amount of keys as well. As copying all those keys on a first properly signed SYN would make the request socket bigger, that would be undesirable. Currently, the implementation doesn't copy keys to request sockets, but rather look them up on the "parent" listener socket.

The result is that when userspace removes TCP-AO keys, that may break not-yet-established connections on request sockets as well as not removing keys from sockets that were already established, but not yet `accept()`'ed, hanging in the accept queue.

The reverse is valid as well: if userspace adds a new key for a peer on a listener socket, the established sockets in the accept queue won't have the new keys.

At this moment, the resolution for the two races: `setsockopt(TCP_AO_ADD_KEY)` vs `accept()` and `setsockopt(TCP_AO_DEL_KEY)` vs `accept()` is delegated to userspace. This means that it's expected that userspace would check the MKTs on the socket that was returned by `accept()` to verify that any key rotation that happened on the listen socket is reflected on the newly established connection.

This is a similar "do-nothing" approach to TCP-MD5 from the kernel side and may be changed later by introducing new flags to `tcp_ao_add` and `tcp_ao_del`.

Note that this race is rare for it needs TCP-AO key rotation to happen during the 3-way handshake for the new TCP connection.

<a id="rst-interaction-with-tcp-md5"></a>

## 5. Interaction with TCP-MD5

A TCP connection can not migrate between TCP-AO and TCP-MD5 options. The established sockets that have either AO or MD5 keys are restricted for adding keys of the other option.

For listening sockets the picture is different: BGP server may want to receive both TCP-AO and (deprecated) TCP-MD5 clients. As a result, both types of keys may be added to TCP_CLOSED or TCP_LISTEN sockets. It's not allowed to add different types of keys for the same peer.

<a id="rst-sne-linux-implementation"></a>

## 6. SNE Linux implementation

RFC 5925 \[6.2\] describes the algorithm of how to extend TCP sequence numbers with SNE.  In short: TCP has to track the previous sequence numbers and set sne_flag when the current SEQ number rolls over. The flag is cleared when both current and previous SEQ numbers cross 0x7fff, which is 32Kb.

In times when sne_flag is set, the algorithm compares SEQ for each packet with 0x7fff and if it's higher than 32Kb, it assumes that the packet should be verified with SNE before the increment. As a result, there's this \[0; 32Kb\] window, when packets with (SNE - 1) can be accepted.

Linux implementation simplifies this a bit: as the network stack already tracks the first SEQ byte that ACK is wanted for (snd_una) and the next SEQ byte that is wanted (rcv_nxt) - that's enough information for a rough estimation on where in the 4GB SEQ number space both sender and receiver are. When they roll over to zero, the corresponding SNE gets incremented.

tcp_ao_compute_sne() is called for each TCP-AO segment. It compares SEQ numbers from the segment with snd_una or rcv_nxt and fits the result into a 2GB window around them, detecting SEQ numbers rolling over. That simplifies the code a lot and only requires SNE numbers to be stored on every TCP-AO socket.

The 2GB window at first glance seems much more permissive compared to RFC 5926. But that is only used to pick the correct SNE before/after a rollover. It allows more TCP segment replays, but yet all regular TCP checks in tcp_sequence() are applied on the verified segment. So, it trades a bit more permissive acceptance of replayed/retransmitted segments for the simplicity of the algorithm and what seems better behaviour for large TCP windows.

<a id="rst-links"></a>

## 7. Links

- **RFC 5925 The TCP Authentication Option**

  [https://www.rfc-editor.org/rfc/pdfrfc/rfc5925.txt.pdf](<https://www.rfc-editor.org/rfc/pdfrfc/rfc5925.txt.pdf>)

- **RFC 5926 Cryptographic Algorithms for the TCP Authentication Option (TCP-AO)**

  [https://www.rfc-editor.org/rfc/pdfrfc/rfc5926.txt.pdf](<https://www.rfc-editor.org/rfc/pdfrfc/rfc5926.txt.pdf>)

- **Draft "SHA-2 Algorithm for the TCP Authentication Option (TCP-AO)"**

  [https://datatracker.ietf.org/doc/html/draft-nayak-tcp-sha2-03](<https://datatracker.ietf.org/doc/html/draft-nayak-tcp-sha2-03>)

- **RFC 2385 Protection of BGP Sessions via the TCP MD5 Signature Option**

  [https://www.rfc-editor.org/rfc/pdfrfc/rfc2385.txt.pdf](<https://www.rfc-editor.org/rfc/pdfrfc/rfc2385.txt.pdf>)

**Author:** Dmitry Safonov &lt;[dima@arista.com](<mailto:dima@arista.com>)&gt;

---

# Team

_Peios Kernel / Internals / Networking_

> https://github.com/jpirko/libteam

<a id="rst-team"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Team devices are driven from userspace via libteam library which is here:**

  [https://github.com/jpirko/libteam](<https://github.com/jpirko/libteam>)

---

# Timestamping

_Peios Kernel / Internals / Networking_

> The interfaces for receiving network packages timestamps are:

<a id="rst-timestamping"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-control-interfaces"></a>

## 1. Control Interfaces

The interfaces for receiving network packages timestamps are:

- **SO_TIMESTAMP**

  Generates a timestamp for each incoming packet in (not necessarily monotonic) system time. Reports the timestamp via recvmsg() in a control message in usec resolution. SO_TIMESTAMP is defined as SO_TIMESTAMP_NEW or SO_TIMESTAMP_OLD based on the architecture type and time_t representation of libc. Control message format is in struct \__kernel_old_timeval for SO_TIMESTAMP_OLD and in struct \__kernel_sock_timeval for SO_TIMESTAMP_NEW options respectively.

- **SO_TIMESTAMPNS**

  Same timestamping mechanism as SO_TIMESTAMP, but reports the timestamp as struct timespec in nsec resolution. SO_TIMESTAMPNS is defined as SO_TIMESTAMPNS_NEW or SO_TIMESTAMPNS_OLD based on the architecture type and time_t representation of libc. Control message format is in struct timespec for SO_TIMESTAMPNS_OLD and in struct \__kernel_timespec for SO_TIMESTAMPNS_NEW options respectively.

- **IP_MULTICAST_LOOP + SO_TIMESTAMP\[NS\]**

  Only for multicast:approximate transmit timestamp obtained by reading the looped packet receive timestamp.

- **SO_TIMESTAMPING**

  Generates timestamps on reception, transmission or both. Supports multiple timestamp sources, including hardware. Supports generating timestamps for stream sockets.

<a id="rst-so-timestamp-also-so-timestamp-old-and-so-timestamp-new"></a>

### 1.1 SO_TIMESTAMP (also SO_TIMESTAMP_OLD and SO_TIMESTAMP_NEW)

This socket option enables timestamping of datagrams on the reception path. Because the destination socket, if any, is not known early in the network stack, the feature has to be enabled for all packets. The same is true for all early receive timestamp options.

For interface details, see `man 7 socket`.

Always use SO_TIMESTAMP_NEW timestamp to always get timestamp in struct \__kernel_sock_timeval format.

SO_TIMESTAMP_OLD returns incorrect timestamps after the year 2038 on 32 bit machines.

<a id="rst-so-timestampns-also-so-timestampns-old-and-so-timestampns-new"></a>

### 1.2 SO_TIMESTAMPNS (also SO_TIMESTAMPNS_OLD and SO_TIMESTAMPNS_NEW)

This option is identical to SO_TIMESTAMP except for the returned data type. Its struct timespec allows for higher resolution (ns) timestamps than the timeval of SO_TIMESTAMP (ms).

Always use SO_TIMESTAMPNS_NEW timestamp to always get timestamp in struct \__kernel_timespec format.

SO_TIMESTAMPNS_OLD returns incorrect timestamps after the year 2038 on 32 bit machines.

<a id="rst-so-timestamping-also-so-timestamping-old-and-so-timestamping-new"></a>

### 1.3 SO_TIMESTAMPING (also SO_TIMESTAMPING_OLD and SO_TIMESTAMPING_NEW)

Supports multiple types of timestamp requests. As a result, this socket option takes a bitmap of flags, not a boolean. In:



```text
err = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING, &val, sizeof(val));
```

val is an integer with any of the following bits set. Setting other bit returns EINVAL and does not change the current state.

The socket option configures timestamp generation for individual sk_buffs (1.3.1), timestamp reporting to the socket's error queue (1.3.2) and options (1.3.3). Timestamp generation can also be enabled for individual sendmsg calls using cmsg (1.3.4).

<a id="rst-timestamp-generation"></a>

#### 1.3.1 Timestamp Generation

Some bits are requests to the stack to try to generate timestamps. Any combination of them is valid. Changes to these bits apply to newly created packets, not to packets already in the stack. As a result, it is possible to selectively request timestamps for a subset of packets (e.g., for sampling) by embedding an send() call within two setsockopt calls, one to enable timestamp generation and one to disable it. Timestamps may also be generated for reasons other than being requested by a particular socket, such as when receive timestamping is enabled system wide, as explained earlier.

- **SOF_TIMESTAMPING_RX_HARDWARE:**

  Request rx timestamps generated by the network adapter.

- **SOF_TIMESTAMPING_RX_SOFTWARE:**

  Request rx timestamps when data enters the kernel. These timestamps are generated just after a device driver hands a packet to the kernel receive stack.

- **SOF_TIMESTAMPING_TX_HARDWARE:**

  Request tx timestamps generated by the network adapter. This flag can be enabled via both socket options and control messages.

- **SOF_TIMESTAMPING_TX_SOFTWARE:**

  Request tx timestamps when data leaves the kernel. These timestamps are generated in the device driver as close as possible, but always prior to, passing the packet to the network interface. Hence, they require driver support and may not be available for all devices. This flag can be enabled via both socket options and control messages.

- **SOF_TIMESTAMPING_TX_SCHED:**

  Request tx timestamps prior to entering the packet scheduler. Kernel transmit latency is, if long, often dominated by queuing delay. The difference between this timestamp and one taken at SOF_TIMESTAMPING_TX_SOFTWARE will expose this latency independent of protocol processing. The latency incurred in protocol processing, if any, can be computed by subtracting a userspace timestamp taken immediately before send() from this timestamp. On machines with virtual devices where a transmitted packet travels through multiple devices and, hence, multiple packet schedulers, a timestamp is generated at each layer. This allows for fine grained measurement of queuing delay. This flag can be enabled via both socket options and control messages.

- **SOF_TIMESTAMPING_TX_ACK:**

  Request tx timestamps when all data in the send buffer has been acknowledged. This only makes sense for reliable protocols. It is currently only implemented for TCP. For that protocol, it may over-report measurement, because the timestamp is generated when all data up to and including the buffer at send() was acknowledged: the cumulative acknowledgment. The mechanism ignores SACK and FACK. This flag can be enabled via both socket options and control messages.

- **SOF_TIMESTAMPING_TX_COMPLETION:**

  Request tx timestamps on packet tx completion.  The completion timestamp is generated by the kernel when it receives packet a completion report from the hardware. Hardware may report multiple packets at once, and completion timestamps reflect the timing of the report and not actual tx time. This flag can be enabled via both socket options and control messages.

<a id="rst-timestamp-reporting"></a>

#### 1.3.2 Timestamp Reporting

The other three bits control which timestamps will be reported in a generated control message. Changes to the bits take immediate effect at the timestamp reporting locations in the stack. Timestamps are only reported for packets that also have the relevant timestamp generation request set.

- **SOF_TIMESTAMPING_SOFTWARE:**

  Report any software timestamps when available.

- **SOF_TIMESTAMPING_SYS_HARDWARE:**

  This option is deprecated and ignored.

- **SOF_TIMESTAMPING_RAW_HARDWARE:**

  Report hardware timestamps as generated by SOF_TIMESTAMPING_TX_HARDWARE or SOF_TIMESTAMPING_RX_HARDWARE when available.

<a id="rst-timestamp-options"></a>

#### 1.3.3 Timestamp Options

The interface supports the options

- **SOF_TIMESTAMPING_OPT_ID:**

  Generate a unique identifier along with each packet. A process can have multiple concurrent timestamping requests outstanding. Packets can be reordered in the transmit path, for instance in the packet scheduler. In that case timestamps will be queued onto the error queue out of order from the original send() calls. It is not always possible to uniquely match timestamps to the original send() calls based on timestamp order or payload inspection alone, then.

  This option associates each packet at send() with a unique identifier and returns that along with the timestamp. The identifier is derived from a per-socket u32 counter (that wraps). For datagram sockets, the counter increments with each sent packet. For stream sockets, it increments with every byte. For stream sockets, also set SOF_TIMESTAMPING_OPT_ID_TCP, see the section below.

  The counter starts at zero. It is initialized the first time that the socket option is enabled. It is reset each time the option is enabled after having been disabled. Resetting the counter does not change the identifiers of existing packets in the system.

  This option is implemented only for transmit timestamps. There, the timestamp is always looped along with a struct sock_extended_err. The option modifies field ee_data to pass an id that is unique among all possibly concurrently outstanding timestamp requests for that socket.

  The process can optionally override the default generated ID, by passing a specific ID with control message SCM_TS_OPT_ID (not supported for TCP sockets):



  ```text
  struct msghdr *msg;
  ...
  cmsg                         = CMSG_FIRSTHDR(msg);
  cmsg->cmsg_level             = SOL_SOCKET;
  cmsg->cmsg_type              = SCM_TS_OPT_ID;
  cmsg->cmsg_len               = CMSG_LEN(sizeof(__u32));
  *((__u32 *) CMSG_DATA(cmsg)) = opt_id;
  err = sendmsg(fd, msg, 0);
  ```

- **SOF_TIMESTAMPING_OPT_ID_TCP:**

  Pass this modifier along with SOF_TIMESTAMPING_OPT_ID for new TCP timestamping applications. SOF_TIMESTAMPING_OPT_ID defines how the counter increments for stream sockets, but its starting point is not entirely trivial. This option fixes that.

  For stream sockets, if SOF_TIMESTAMPING_OPT_ID is set, this should always be set too. On datagram sockets the option has no effect.

  A reasonable expectation is that the counter is reset to zero with the system call, so that a subsequent write() of N bytes generates a timestamp with counter N-1. SOF_TIMESTAMPING_OPT_ID_TCP implements this behavior under all conditions.

  SOF_TIMESTAMPING_OPT_ID without modifier often reports the same, especially when the socket option is set when no data is in transmission. If data is being transmitted, it may be off by the length of the output queue (SIOCOUTQ).

  The difference is due to being based on snd_una versus write_seq. snd_una is the offset in the stream acknowledged by the peer. This depends on factors outside of process control, such as network RTT. write_seq is the last byte written by the process. This offset is not affected by external inputs.

  The difference is subtle and unlikely to be noticed when configured at initial socket creation, when no data is queued or sent. But SOF_TIMESTAMPING_OPT_ID_TCP behavior is more robust regardless of when the socket option is set.

- **SOF_TIMESTAMPING_OPT_CMSG:**

  Support recv() cmsg for all timestamped packets. Control messages are already supported unconditionally on all packets with receive timestamps and on IPv6 packets with transmit timestamp. This option extends them to IPv4 packets with transmit timestamp. One use case is to correlate packets with their egress device, by enabling socket option IP_PKTINFO simultaneously.

- **SOF_TIMESTAMPING_OPT_TSONLY:**

  Applies to transmit timestamps only. Makes the kernel return the timestamp as a cmsg alongside an empty packet, as opposed to alongside the original packet. This reduces the amount of memory charged to the socket's receive budget (SO_RCVBUF) and delivers the timestamp even if sysctl net.core.tstamp_allow_data is 0. This option disables SOF_TIMESTAMPING_OPT_CMSG.

- **SOF_TIMESTAMPING_OPT_STATS:**

  Optional stats that are obtained along with the transmit timestamps. It must be used together with SOF_TIMESTAMPING_OPT_TSONLY. When the transmit timestamp is available, the stats are available in a separate control message of type SCM_TIMESTAMPING_OPT_STATS, as a list of TLVs (struct nlattr) of types. These stats allow the application to associate various transport layer stats with the transmit timestamps, such as how long a certain block of data was limited by peer's receiver window.

- **SOF_TIMESTAMPING_OPT_PKTINFO:**

  Enable the SCM_TIMESTAMPING_PKTINFO control message for incoming packets with hardware timestamps. The message contains struct scm_ts_pktinfo, which supplies the index of the real interface which received the packet and its length at layer 2. A valid (non-zero) interface index will be returned only if CONFIG_NET_RX_BUSY_POLL is enabled and the driver is using NAPI. The struct contains also two other fields, but they are reserved and undefined.

- **SOF_TIMESTAMPING_OPT_TX_SWHW:**

  Request both hardware and software timestamps for outgoing packets when SOF_TIMESTAMPING_TX_HARDWARE and SOF_TIMESTAMPING_TX_SOFTWARE are enabled at the same time. If both timestamps are generated, two separate messages will be looped to the socket's error queue, each containing just one timestamp.

- **SOF_TIMESTAMPING_OPT_RX_FILTER:**

  Filter out spurious receive timestamps: report a receive timestamp only if the matching timestamp generation flag is enabled.

  Receive timestamps are generated early in the ingress path, before a packet's destination socket is known. If any socket enables receive timestamps, packets for all socket will receive timestamped packets. Including those that request timestamp reporting with SOF_TIMESTAMPING_SOFTWARE and/or SOF_TIMESTAMPING_RAW_HARDWARE, but do not request receive timestamp generation. This can happen when requesting transmit timestamps only.

  Receiving spurious timestamps is generally benign. A process can ignore the unexpected non-zero value. But it makes behavior subtly dependent on other sockets. This flag isolates the socket for more deterministic behavior.

New applications are encouraged to pass SOF_TIMESTAMPING_OPT_ID to disambiguate timestamps and SOF_TIMESTAMPING_OPT_TSONLY to operate regardless of the setting of sysctl net.core.tstamp_allow_data.

An exception is when a process needs additional cmsg data, for instance SOL_IP/IP_PKTINFO to detect the egress network interface. Then pass option SOF_TIMESTAMPING_OPT_CMSG. This option depends on having access to the contents of the original packet, so cannot be combined with SOF_TIMESTAMPING_OPT_TSONLY.

<a id="rst-enabling-timestamps-via-control-messages"></a>

#### 1.3.4. Enabling timestamps via control messages

In addition to socket options, timestamp generation can be requested per write via cmsg, only for SOF_TIMESTAMPING_TX\_\* (see Section 1.3.1). Using this feature, applications can sample timestamps per sendmsg() without paying the overhead of enabling and disabling timestamps via setsockopt:



```text
struct msghdr *msg;
...
cmsg                         = CMSG_FIRSTHDR(msg);
cmsg->cmsg_level             = SOL_SOCKET;
cmsg->cmsg_type              = SO_TIMESTAMPING;
cmsg->cmsg_len               = CMSG_LEN(sizeof(__u32));
*((__u32 *) CMSG_DATA(cmsg)) = SOF_TIMESTAMPING_TX_SCHED |
                               SOF_TIMESTAMPING_TX_SOFTWARE |
                               SOF_TIMESTAMPING_TX_ACK;
err = sendmsg(fd, msg, 0);
```

The SOF_TIMESTAMPING_TX\_\* flags set via cmsg will override the SOF_TIMESTAMPING_TX\_\* flags set via setsockopt.

Moreover, applications must still enable timestamp reporting via setsockopt to receive timestamps:



```text
__u32 val = SOF_TIMESTAMPING_SOFTWARE |
            SOF_TIMESTAMPING_OPT_ID /* or any other flag */;
err = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING, &val, sizeof(val));
```

<a id="rst-bytestream-timestamps"></a>

### 1.4 Bytestream Timestamps

The SO_TIMESTAMPING interface supports timestamping of bytes in a bytestream. Each request is interpreted as a request for when the entire contents of the buffer has passed a timestamping point. That is, for streams option SOF_TIMESTAMPING_TX_SOFTWARE will record when all bytes have reached the device driver, regardless of how many packets the data has been converted into.

In general, bytestreams have no natural delimiters and therefore correlating a timestamp with data is non-trivial. A range of bytes may be split across segments, any segments may be merged (possibly coalescing sections of previously segmented buffers associated with independent send() calls). Segments can be reordered and the same byte range can coexist in multiple segments for protocols that implement retransmissions.

It is essential that all timestamps implement the same semantics, regardless of these possible transformations, as otherwise they are incomparable. Handling "rare" corner cases differently from the simple case (a 1:1 mapping from buffer to skb) is insufficient because performance debugging often needs to focus on such outliers.

In practice, timestamps can be correlated with segments of a bytestream consistently, if both semantics of the timestamp and the timing of measurement are chosen correctly. This challenge is no different from deciding on a strategy for IP fragmentation. There, the definition is that only the first fragment is timestamped. For bytestreams, we chose that a timestamp is generated only when all bytes have passed a point. SOF_TIMESTAMPING_TX_ACK as defined is easy to implement and reason about. An implementation that has to take into account SACK would be more complex due to possible transmission holes and out of order arrival.

On the host, TCP can also break the simple 1:1 mapping from buffer to skbuff as a result of Nagle, cork, autocork, segmentation and GSO. The implementation ensures correctness in all cases by tracking the individual last byte passed to send(), even if it is no longer the last byte after an skbuff extend or merge operation. It stores the relevant sequence number in skb_shinfo(skb)-&gt;tskey. Because an skbuff has only one such field, only one timestamp can be generated.

In rare cases, a timestamp request can be missed if two requests are collapsed onto the same skb. A process can detect this situation by enabling SOF_TIMESTAMPING_OPT_ID and comparing the byte offset at send time with the value returned for each timestamp. It can prevent the situation by always flushing the TCP stack in between requests, for instance by enabling TCP_NODELAY and disabling TCP_CORK and autocork. After linux-4.7, a better way to prevent coalescing is to use MSG_EOR flag at sendmsg() time.

These precautions ensure that the timestamp is generated only when all bytes have passed a timestamp point, assuming that the network stack itself does not reorder the segments. The stack indeed tries to avoid reordering. The one exception is under administrator control: it is possible to construct a packet scheduler configuration that delays segments from the same stream differently. Such a setup would be unusual.

<a id="rst-data-interfaces"></a>

## 2 Data Interfaces

Timestamps are read using the ancillary data feature of recvmsg(). See `man 3 cmsg` for details of this interface. The socket manual page (`man 7 socket`) describes how timestamps generated with SO_TIMESTAMP and SO_TIMESTAMPNS records can be retrieved.

<a id="rst-scm-timestamping-records"></a>

### 2.1 SCM_TIMESTAMPING records

These timestamps are returned in a control message with cmsg_level SOL_SOCKET, cmsg_type SCM_TIMESTAMPING, and payload of type

For SO_TIMESTAMPING_OLD:



```text
struct scm_timestamping {
        struct timespec ts[3];
};
```

For SO_TIMESTAMPING_NEW:



```text
struct scm_timestamping64 {
        struct __kernel_timespec ts[3];
```

Always use SO_TIMESTAMPING_NEW timestamp to always get timestamp in struct scm_timestamping64 format.

SO_TIMESTAMPING_OLD returns incorrect timestamps after the year 2038 on 32 bit machines.

The structure can return up to three timestamps. This is a legacy feature. At least one field is non-zero at any time. Most timestamps are passed in ts\[0\]. Hardware timestamps are passed in ts\[2\].

ts\[1\] used to hold hardware timestamps converted to system time. Instead, expose the hardware clock device on the NIC directly as a HW PTP clock source, to allow time conversion in userspace and optionally synchronize system time with a userspace PTP stack such as linuxptp. For the PTP clock API, see [Documentation/driver-api/ptp.rst](/kernel/hardware/driver-api/services/ptp.md).

Note that if the SO_TIMESTAMP or SO_TIMESTAMPNS option is enabled together with SO_TIMESTAMPING using SOF_TIMESTAMPING_SOFTWARE, a false software timestamp will be generated in the recvmsg() call and passed in ts\[0\] when a real software timestamp is missing. This happens also on hardware transmit timestamps.

<a id="rst-transmit-timestamps-with-msg-errqueue"></a>

#### 2.1.1 Transmit timestamps with MSG_ERRQUEUE

For transmit timestamps the outgoing packet is looped back to the socket's error queue with the send timestamp(s) attached. A process receives the timestamps by calling recvmsg() with flag MSG_ERRQUEUE set and with a msg_control buffer sufficiently large to receive the relevant metadata structures. The recvmsg call returns the original outgoing data packet with two ancillary messages attached.

A message of cm_level SOL_IP(V6) and cm_type IP(V6)\_RECVERR embeds a struct sock_extended_err. This defines the error type. For timestamps, the ee_errno field is ENOMSG. The other ancillary message will have cm_level SOL_SOCKET and cm_type SCM_TIMESTAMPING. This embeds the struct scm_timestamping.

<a id="rst-timestamp-types"></a>

##### 2.1.1.2 Timestamp types

The semantics of the three struct timespec are defined by field ee_info in the extended error structure. It contains a value of type SCM_TSTAMP\_\* to define the actual timestamp passed in scm_timestamping.

The SCM_TSTAMP\_\* types are 1:1 matches to the SOF_TIMESTAMPING\_\* control fields discussed previously, with one exception. For legacy reasons, SCM_TSTAMP_SND is equal to zero and can be set for both SOF_TIMESTAMPING_TX_HARDWARE and SOF_TIMESTAMPING_TX_SOFTWARE. It is the first if ts\[2\] is non-zero, the second otherwise, in which case the timestamp is stored in ts\[0\].

<a id="rst-fragmentation"></a>

##### 2.1.1.3 Fragmentation

Fragmentation of outgoing datagrams is rare, but is possible, e.g., by explicitly disabling PMTU discovery. If an outgoing packet is fragmented, then only the first fragment is timestamped and returned to the sending socket.

<a id="rst-packet-payload"></a>

##### 2.1.1.4 Packet Payload

The calling application is often not interested in receiving the whole packet payload that it passed to the stack originally: the socket error queue mechanism is just a method to piggyback the timestamp on. In this case, the application can choose to read datagrams with a smaller buffer, possibly even of length 0. The payload is truncated accordingly. Until the process calls recvmsg() on the error queue, however, the full packet is queued, taking up budget from SO_RCVBUF.

<a id="rst-blocking-read"></a>

##### 2.1.1.5 Blocking Read

Reading from the error queue is always a non-blocking operation. To block waiting on a timestamp, use poll or select. poll() will return POLLERR in pollfd.revents if any data is ready on the error queue. There is no need to pass this flag in pollfd.events. This flag is ignored on request. See also `man 2 poll`.

<a id="rst-receive-timestamps"></a>

#### 2.1.2 Receive timestamps

On reception, there is no reason to read from the socket error queue. The SCM_TIMESTAMPING ancillary data is sent along with the packet data on a normal recvmsg(). Since this is not a socket error, it is not accompanied by a message SOL_IP(V6)/IP(V6)\_RECVERROR. In this case, the meaning of the three fields in struct scm_timestamping is implicitly defined. ts\[0\] holds a software timestamp if set, ts\[1\] is again deprecated and ts\[2\] holds a hardware timestamp if set.

<a id="rst-hardware-timestamping-configuration-ethtool-msg-tsconfig-set-get"></a>

## 3. Hardware Timestamping configuration: ETHTOOL_MSG_TSCONFIG_SET/GET

Hardware time stamping must also be initialized for each device driver that is expected to do hardware time stamping. The parameter is defined in include/uapi/linux/net_tstamp.h as:



```text
struct hwtstamp_config {
        int flags;      /* no flags defined right now, must be zero */
        int tx_type;    /* HWTSTAMP_TX_* */
        int rx_filter;  /* HWTSTAMP_FILTER_* */
};
```

Desired behavior is passed into the kernel and to a specific device by calling the tsconfig netlink socket `ETHTOOL_MSG_TSCONFIG_SET`. The `ETHTOOL_A_TSCONFIG_TX_TYPES`, `ETHTOOL_A_TSCONFIG_RX_FILTERS` and `ETHTOOL_A_TSCONFIG_HWTSTAMP_FLAGS` netlink attributes are then used to set the struct hwtstamp_config accordingly.

The `ETHTOOL_A_TSCONFIG_HWTSTAMP_PROVIDER` netlink nested attribute is used to select the source of the hardware time stamping. It is composed of an index for the device source and a qualifier for the type of time stamping.

Drivers are free to use a more permissive configuration than the requested configuration. It is expected that drivers should only implement directly the most generic mode that can be supported. For example if the hardware can support HWTSTAMP_FILTER_PTP_V2_EVENT, then it should generally always upscale HWTSTAMP_FILTER_PTP_V2_L2_SYNC, and so forth, as HWTSTAMP_FILTER_PTP_V2_EVENT is more generic (and more useful to applications).

A driver which supports hardware time stamping shall update the struct with the actual, possibly more permissive configuration. If the requested packets cannot be time stamped, then nothing should be changed and ERANGE shall be returned (in contrast to EINVAL, which indicates that SIOCSHWTSTAMP is not supported at all).

Only a processes with admin rights may change the configuration. User space is responsible to ensure that multiple processes don't interfere with each other and that the settings are reset.

Any process can read the actual configuration by requesting tsconfig netlink socket `ETHTOOL_MSG_TSCONFIG_GET`.

The legacy configuration is the use of the ioctl(SIOCSHWTSTAMP) with a pointer to a struct ifreq whose ifr_data points to a struct hwtstamp_config. The tx_type and rx_filter are hints to the driver what it is expected to do. If the requested fine-grained filtering for incoming packets is not supported, the driver may time stamp more than just the requested types of packets. ioctl(SIOCGHWTSTAMP) is used in the same way as the ioctl(SIOCSHWTSTAMP). However, this has not been implemented in all drivers.



```text
/* possible values for hwtstamp_config->tx_type */
enum {
        /*
        * no outgoing packet will need hardware time stamping;
        * should a packet arrive which asks for it, no hardware
        * time stamping will be done
        */
        HWTSTAMP_TX_OFF,

        /*
        * enables hardware time stamping for outgoing packets;
        * the sender of the packet decides which are to be
        * time stamped by setting SOF_TIMESTAMPING_TX_SOFTWARE
        * before sending the packet
        */
        HWTSTAMP_TX_ON,
};

/* possible values for hwtstamp_config->rx_filter */
enum {
        /* time stamp no incoming packet at all */
        HWTSTAMP_FILTER_NONE,

        /* time stamp any incoming packet */
        HWTSTAMP_FILTER_ALL,

        /* return value: time stamp all packets requested plus some others */
        HWTSTAMP_FILTER_SOME,

        /* PTP v1, UDP, any kind of event packet */
        HWTSTAMP_FILTER_PTP_V1_L4_EVENT,

        /* for the complete list of values, please check
        * the include file include/uapi/linux/net_tstamp.h
        */
};
```

<a id="rst-hardware-timestamping-implementation-device-drivers"></a>

### 3.1 Hardware Timestamping Implementation: Device Drivers

A driver which supports hardware time stamping must support the ndo_hwtstamp_set NDO and update the supplied struct hwtstamp_config with the actual values as described in the section on SIOCSHWTSTAMP. It should also support ndo_hwtstamp_get NDO to retrieve configuration.

Time stamps for received packets must be stored in the skb. To get a pointer to the shared time stamp structure of the skb call skb_hwtstamps(). Then set the time stamps in the structure:



```text
struct skb_shared_hwtstamps {
        /* hardware time stamp transformed into duration
        * since arbitrary point in time
        */
        ktime_t     hwtstamp;
};
```

Time stamps for outgoing packets are to be generated as follows:

- In hard_start_xmit(), check if (skb_shinfo(skb)-&gt;tx_flags &amp; SKBTX_HW_TSTAMP) is set no-zero. If yes, then the driver is expected to do hardware time stamping.

- If this is possible for the skb and requested, then declare that the driver is doing the time stamping by setting the flag SKBTX_IN_PROGRESS in skb_shinfo(skb)-&gt;tx_flags , e.g. with:



  ```text
  skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
  ```

  You might want to keep a pointer to the associated skb for the next step and not free the skb. A driver not supporting hardware time stamping doesn't do that. A driver must never touch sk_buff::tstamp\! It is used to store software generated time stamps by the network subsystem.

- Driver should call skb_tx_timestamp() as close to passing sk_buff to hardware as possible. skb_tx_timestamp() provides a software time stamp if requested and hardware timestamping is not possible (SKBTX_IN_PROGRESS not set).

- As soon as the driver has sent the packet and/or obtained a hardware time stamp for it, it passes the time stamp back by calling skb_tstamp_tx() with the original skb, the raw hardware time stamp. skb_tstamp_tx() clones the original skb and adds the timestamps, therefore the original skb has to be freed now. If obtaining the hardware time stamp somehow fails, then the driver should not fall back to software time stamping. The rationale is that this would occur at a later time in the processing pipeline than other software time stamping and therefore could lead to unexpected deltas between time stamps.

<a id="rst-special-considerations-for-stacked-ptp-hardware-clocks"></a>

### 3.2 Special considerations for stacked PTP Hardware Clocks

There are situations when there may be more than one PHC (PTP Hardware Clock) in the data path of a packet. The kernel has no explicit mechanism to allow the user to select which PHC to use for timestamping Ethernet frames. Instead, the assumption is that the outermost PHC is always the most preferable, and that kernel drivers collaborate towards achieving that goal. Currently there are 3 cases of stacked PHCs, detailed below:

<a id="rst-dsa-distributed-switch-architecture-switches"></a>

#### 3.2.1 DSA (Distributed Switch Architecture) switches

These are Ethernet switches which have one of their ports connected to an (otherwise completely unaware) host Ethernet interface, and perform the role of a port multiplier with optional forwarding acceleration features.  Each DSA switch port is visible to the user as a standalone (virtual) network interface, and its network I/O is performed, under the hood, indirectly through the host interface (redirecting to the host port on TX, and intercepting frames on RX).

When a DSA switch is attached to a host port, PTP synchronization has to suffer, since the switch's variable queuing delay introduces a path delay jitter between the host port and its PTP partner. For this reason, some DSA switches include a timestamping clock of their own, and have the ability to perform network timestamping on their own MAC, such that path delays only measure wire and PHY propagation latencies. Timestamping DSA switches are supported in Linux and expose the same ABI as any other network interface (save for the fact that the DSA interfaces are in fact virtual in terms of network I/O, they do have their own PHC).  It is typical, but not mandatory, for all interfaces of a DSA switch to share the same PHC.

By design, PTP timestamping with a DSA switch does not need any special handling in the driver for the host port it is attached to.  However, when the host port also supports PTP timestamping, DSA will take care of intercepting the `.ndo_eth_ioctl` calls towards the host port, and block attempts to enable hardware timestamping on it. This is because the SO_TIMESTAMPING API does not allow the delivery of multiple hardware timestamps for the same packet, so anybody else except for the DSA switch port must be prevented from doing so.

In the generic layer, DSA provides the following infrastructure for PTP timestamping:

- `.port_txtstamp()`: a hook called prior to the transmission of packets with a hardware TX timestamping request from user space. This is required for two-step timestamping, since the hardware timestamp becomes available after the actual MAC transmission, so the driver must be prepared to correlate the timestamp with the original packet so that it can re-enqueue the packet back into the socket's error queue. To save the packet for when the timestamp becomes available, the driver can call `skb_clone_sk` , save the clone pointer in skb-&gt;cb and enqueue a tx skb queue. Typically, a switch will have a PTP TX timestamp register (or sometimes a FIFO) where the timestamp becomes available. In case of a FIFO, the hardware might store key-value pairs of PTP sequence ID/message type/domain number and the actual timestamp. To perform the correlation correctly between the packets in a queue waiting for timestamping and the actual timestamps, drivers can use a BPF classifier (`ptp_classify_raw`) to identify the PTP transport type, and `ptp_parse_header` to interpret the PTP header fields. There may be an IRQ that is raised upon this timestamp's availability, or the driver might have to poll after invoking `dev_queue_xmit()` towards the host interface. One-step TX timestamping do not require packet cloning, since there is no follow-up message required by the PTP protocol (because the TX timestamp is embedded into the packet by the MAC), and therefore user space does not expect the packet annotated with the TX timestamp to be re-enqueued into its socket's error queue.

- `.port_rxtstamp()`: On RX, the BPF classifier is run by DSA to identify PTP event messages (any other packets, including PTP general messages, are not timestamped). The original (and only) timestampable skb is provided to the driver, for it to annotate it with a timestamp, if that is immediately available, or defer to later. On reception, timestamps might either be available in-band (through metadata in the DSA header, or attached in other ways to the packet), or out-of-band (through another RX timestamping FIFO). Deferral on RX is typically necessary when retrieving the timestamp needs a sleepable context. In that case, it is the responsibility of the DSA driver to call `netif_rx()` on the freshly timestamped skb.

<a id="rst-ethernet-phys"></a>

#### 3.2.2 Ethernet PHYs

These are devices that typically fulfill a Layer 1 role in the network stack, hence they do not have a representation in terms of a network interface as DSA switches do. However, PHYs may be able to detect and timestamp PTP packets, for performance reasons: timestamps taken as close as possible to the wire have the potential to yield a more stable and precise synchronization.

A PHY driver that supports PTP timestamping must create a `struct mii_timestamper` and add a pointer to it in `phydev->mii_ts`. The presence of this pointer will be checked by the networking stack.

Since PHYs do not have network interface representations, the timestamping and ethtool ioctl operations for them need to be mediated by their respective MAC driver.  Therefore, as opposed to DSA switches, modifications need to be done to each individual MAC driver for PHY timestamping support. This entails:

- Checking, in `.ndo_eth_ioctl`, whether `phy_has_hwtstamp(netdev->phydev)` is true or not. If it is, then the MAC driver should not process this request but instead pass it on to the PHY using `phy_mii_ioctl()`.

- On RX, special intervention may or may not be needed, depending on the function used to deliver skb's up the network stack. In the case of plain `netif_rx()` and similar, MAC drivers must check whether `skb_defer_rx_timestamp(skb)` is necessary or not - and if it is, don't call `netif_rx()` at all.  If `CONFIG_NETWORK_PHY_TIMESTAMPING` is enabled, and `skb->dev->phydev->mii_ts` exists, its `.rxtstamp()` hook will be called now, to determine, using logic very similar to DSA, whether deferral for RX timestamping is necessary.  Again like DSA, it becomes the responsibility of the PHY driver to send the packet up the stack when the timestamp is available.

  For other skb receive functions, such as `napi_gro_receive` and `netif_receive_skb`, the stack automatically checks whether `skb_defer_rx_timestamp()` is necessary, so this check is not needed inside the driver.

- On TX, again, special intervention might or might not be needed.  The function that calls the `mii_ts->txtstamp()` hook is named `skb_clone_tx_timestamp()`. This function can either be called directly (case in which explicit MAC driver support is indeed needed), but the function also piggybacks from the `skb_tx_timestamp()` call, which many MAC drivers already perform for software timestamping purposes. Therefore, if a MAC supports software timestamping, it does not need to do anything further at this stage.

<a id="rst-mii-bus-snooping-devices"></a>

#### 3.2.3 MII bus snooping devices

These perform the same role as timestamping Ethernet PHYs, save for the fact that they are discrete devices and can therefore be used in conjunction with any PHY even if it doesn't support timestamping. In Linux, they are discoverable and attachable to a `struct phy_device` through Device Tree, and for the rest, they use the same mii_ts infrastructure as those. See [Documentation/devicetree/bindings/ptp/timestamper.txt](/kernel/hardware/devicetree/bindings-ptp/timestamper.md) for more details.

<a id="rst-other-caveats-for-mac-drivers"></a>

#### 3.2.4 Other caveats for MAC drivers

The use of stacked PHCs may uncover MAC driver bugs which were impossible to trigger without them. One example has to do with this line of code, already presented earlier:



```text
skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
```

Any TX timestamping logic, be it a plain MAC driver, a DSA switch driver, a PHY driver or a MII bus snooping device driver, should set this flag. But a MAC driver that is unaware of PHC stacking might get tripped up by somebody other than itself setting this flag, and deliver a duplicate timestamp. For example, a typical driver design for TX timestamping might be to split the transmission part into 2 portions:

1. "TX": checks whether PTP timestamping has been previously enabled through the `.ndo_eth_ioctl` ("`priv->hwtstamp_tx_enabled == true`") and the current skb requires a TX timestamp ("`skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP`"). If this is true, it sets the "`skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS`" flag. Note: as described above, in the case of a stacked PHC system, this condition should never trigger, as this MAC is certainly not the outermost PHC. But this is not where the typical issue is.  Transmission proceeds with this packet.

2. "TX confirmation": Transmission has finished. The driver checks whether it is necessary to collect any TX timestamp for it. Here is where the typical issues are: the MAC driver takes a shortcut and only checks whether "`skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS`" was set. With a stacked PHC system, this is incorrect because this MAC driver is not the only entity in the TX data path who could have enabled SKBTX_IN_PROGRESS in the first place.

The correct solution for this problem is for MAC drivers to have a compound check in their "TX confirmation" portion, not only for "`skb_shinfo(skb)->tx_flags & SKBTX_IN_PROGRESS`", but also for "`priv->hwtstamp_tx_enabled == true`". Because the rest of the system ensures that PTP timestamping is not enabled for anything other than the outermost PHC, this enhanced check will avoid delivering a duplicated TX timestamp to user space.

---

# Linux Kernel TIPC

_Peios Kernel / Internals / Networking_

> TIPC (Transparent Inter Process Communication) is a protocol that is specially designed for intra-cluster communication. It can be configured to transmit messages either on UDP or directly across Ethernet. Message delivery is sequence…

<a id="rst-linux-kernel-tipc"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

TIPC (Transparent Inter Process Communication) is a protocol that is specially designed for intra-cluster communication. It can be configured to transmit messages either on UDP or directly across Ethernet. Message delivery is sequence guaranteed, loss free and flow controlled. Latency times are shorter than with any other known protocol, while maximal throughput is comparable to that of TCP.

<a id="rst-tipc-features"></a>

### TIPC Features

- Cluster wide IPC service

  Have you ever wished you had the convenience of Unix Domain Sockets even when transmitting data between cluster nodes? Where you yourself determine the addresses you want to bind to and use? Where you don't have to perform DNS lookups and worry about IP addresses? Where you don't have to start timers to monitor the continuous existence of peer sockets? And yet without the downsides of that socket type, such as the risk of lingering inodes?

  Welcome to the Transparent Inter Process Communication service, TIPC in short, which gives you all of this, and a lot more.

- Service Addressing

  A fundamental concept in TIPC is that of Service Addressing which makes it possible for a programmer to chose his own address, bind it to a server socket and let client programs use only that address for sending messages.

- Service Tracking

  A client wanting to wait for the availability of a server, uses the Service Tracking mechanism to subscribe for binding and unbinding/close events for sockets with the associated service address.

  The service tracking mechanism can also be used for Cluster Topology Tracking, i.e., subscribing for availability/non-availability of cluster nodes.

  Likewise, the service tracking mechanism can be used for Cluster Connectivity Tracking, i.e., subscribing for up/down events for individual links between cluster nodes.

- Transmission Modes

  Using a service address, a client can send datagram messages to a server socket.

  Using the same address type, it can establish a connection towards an accepting server socket.

  It can also use a service address to create and join a Communication Group, which is the TIPC manifestation of a brokerless message bus.

  Multicast with very good performance and scalability is available both in datagram mode and in communication group mode.

- Inter Node Links

  Communication between any two nodes in a cluster is maintained by one or two Inter Node Links, which both guarantee data traffic integrity and monitor the peer node's availability.

- Cluster Scalability

  By applying the Overlapping Ring Monitoring algorithm on the inter node links it is possible to scale TIPC clusters up to 1000 nodes with a maintained neighbor failure discovery time of 1-2 seconds. For smaller clusters this time can be made much shorter.

- Neighbor Discovery

  Neighbor Node Discovery in the cluster is done by Ethernet broadcast or UDP multicast, when any of those services are available. If not, configured peer IP addresses can be used.

- Configuration

  When running TIPC in single node mode no configuration whatsoever is needed. When running in cluster mode TIPC must as a minimum be given a node address (before Linux 4.17) and told which interface to attach to. The "tipc" configuration tool makes is possible to add and maintain many more configuration parameters.

- Performance

  TIPC message transfer latency times are better than in any other known protocol. Maximal byte throughput for inter-node connections is still somewhat lower than for TCP, while they are superior for intra-node and inter-container throughput on the same host.

- Language Support

  The TIPC user API has support for C, Python, Perl, Ruby, D and Go.

<a id="rst-more-information"></a>

### More Information

- How to set up TIPC:

  [http://tipc.io/getting_started.html](<http://tipc.io/getting_started.html>)

- How to program with TIPC:

  [http://tipc.io/programming.html](<http://tipc.io/programming.html>)

- How to contribute to TIPC:

  [http://tipc.io/contacts.html](<http://tipc.io/contacts.html>)

- More details about TIPC specification:

  [http://tipc.io/protocol.html](<http://tipc.io/protocol.html>)

<a id="rst-implementation"></a>

## Implementation

TIPC is implemented as a kernel module in net/tipc/ directory.

<a id="rst-tipc-base-types"></a>

### TIPC Base Types


#### <a id="c-struct-tipc_subscription"></a>`struct tipc_subscription`

TIPC network topology subscription object

**Definition**

```c
struct tipc_subscription {
    struct tipc_subscr s;
    struct tipc_event evt;
    struct kref kref;
    struct net *net;
    struct timer_list timer;
    struct list_head service_list;
    struct list_head sub_list;
    int conid;
    bool inactive;
    spinlock_t lock;
};
```

**Members**

- `s`: host-endian copy of the user subscription
- `evt`: template for events generated by subscription
- `kref`: reference count for this subscription
- `net`: network namespace associated with subscription
- `timer`: timer governing subscription duration (optional)
- `service_list`: adjacent subscriptions in name sequence's subscription list
- `sub_list`: adjacent subscriptions in subscriber's subscription list
- `conid`: connection identifier of topology server
- `inactive`: true if this subscription is inactive
- `lock`: serialize up/down and timer events



#### <a id="c-struct-tipc_media_addr"></a>`struct tipc_media_addr`

destination address used by TIPC bearers

**Definition**

```c
struct tipc_media_addr {
    u8 value[TIPC_MEDIA_INFO_SIZE];
    u8 media_id;
    u8 broadcast;
};
```

**Members**

- `value`: address info (format defined by media)
- `media_id`: TIPC media type identifier
- `broadcast`: non-zero if address is a broadcast address

#### <a id="c-struct-tipc_media"></a>`struct tipc_media`

Media specific info exposed to generic bearer layer

**Definition**

```c
struct tipc_media {
    int (*send_msg)(struct net *net, struct sk_buff *buf, struct tipc_bearer *b, struct tipc_media_addr *dest);
    int (*enable_media)(struct net *net, struct tipc_bearer *b, struct nlattr *attr[]);
    void (*disable_media)(struct tipc_bearer *b);
    int (*addr2str)(struct tipc_media_addr *addr, char *strbuf, int bufsz);
    int (*addr2msg)(char *msg, struct tipc_media_addr *addr);
    int (*msg2addr)(struct tipc_bearer *b, struct tipc_media_addr *addr, char *msg);
    int (*raw2addr)(struct tipc_bearer *b, struct tipc_media_addr *addr, const char *raw);
    u32 priority;
    u32 tolerance;
    u32 min_win;
    u32 max_win;
    u32 mtu;
    u32 type_id;
    u32 hwaddr_len;
    char name[TIPC_MAX_MEDIA_NAME];
};
```

**Members**

- `send_msg`: routine which handles buffer transmission
- `enable_media`: routine which enables a media
- `disable_media`: routine which disables a media
- `addr2str`: convert media address format to string
- `addr2msg`: convert from media addr format to discovery msg addr format
- `msg2addr`: convert from discovery msg addr format to media addr format
- `raw2addr`: convert from raw addr format to media addr format
- `priority`: default link (and bearer) priority
- `tolerance`: default time (in ms) before declaring link failure
- `min_win`: minimum window (in packets) before declaring link congestion
- `max_win`: maximum window (in packets) before declaring link congestion
- `mtu`: max packet size bearer can support for media type not dependent on
  underlying device MTU
- `type_id`: TIPC media identifier
- `hwaddr_len`: TIPC media address len
- `name`: media name

#### <a id="c-struct-tipc_bearer"></a>`struct tipc_bearer`

Generic TIPC bearer structure

**Definition**

```c
struct tipc_bearer {
    void *media_ptr;
    u32 mtu;
    struct tipc_media_addr addr;
    char name[TIPC_MAX_BEARER_NAME];
    struct tipc_media *media;
    struct tipc_media_addr bcast_addr;
    struct packet_type pt;
    struct rcu_head rcu;
    u32 priority;
    u32 min_win;
    u32 max_win;
    u32 tolerance;
    u32 domain;
    u32 identity;
    struct tipc_discoverer *disc;
    char net_plane;
    u16 encap_hlen;
    unsigned long up;
    refcount_t refcnt;
};
```

**Members**

- `media_ptr`: pointer to additional media-specific information about bearer
- `mtu`: max packet size bearer can support
- `addr`: media-specific address associated with bearer
- `name`: bearer name (format = media:interface)
- `media`: ptr to media structure associated with bearer
- `bcast_addr`: media address used in broadcasting
- `pt`: packet type for bearer
- `rcu`: rcu struct for tipc_bearer
- `priority`: default link priority for bearer
- `min_win`: minimum window (in packets) before declaring link congestion
- `max_win`: maximum window (in packets) before declaring link congestion
- `tolerance`: default link tolerance for bearer
- `domain`: network domain to which links can be established
- `identity`: array index of this bearer within TIPC bearer array
- `disc`: ptr to link setup request
- `net_plane`: network plane ('A' through 'H') currently associated with bearer
- `encap_hlen`: encap headers length
- `up`: bearer up flag (bit 0)
- `refcnt`: tipc_bearer reference counter

**Note**

media-specific code is responsible for initialization of the fields
indicated below when a bearer is enabled; TIPC's generic bearer code takes
care of initializing all other fields.



#### <a id="c-struct-publication"></a>`struct publication`

info about a published service address or range

**Definition**

```c
struct publication {
    struct tipc_service_range sr;
    struct tipc_socket_addr sk;
    u16 scope;
    u32 key;
    u32 id;
    struct list_head binding_node;
    struct list_head binding_sock;
    struct list_head local_publ;
    struct list_head all_publ;
    struct list_head list;
    struct rcu_head rcu;
};
```

**Members**

- `sr`: service range represented by this publication
- `sk`: address of socket bound to this publication
- `scope`: scope of publication, TIPC_NODE_SCOPE or TIPC_CLUSTER_SCOPE
- `key`: publication key, unique across the cluster
- `id`: publication id
- `binding_node`: all publications from the same node which bound this one
  - Remote publications: in node->publ_list;
  Used by node/name distr to withdraw publications when node is lost
  - Local/node scope publications: in name_table->node_scope list
  - Local/cluster scope publications: in name_table->cluster_scope list
- `binding_sock`: all publications from the same socket which bound this one
  Used by socket to withdraw publications when socket is unbound/released
- `local_publ`: list of identical publications made from this node
  Used by closest_first and multicast receive lookup algorithms
- `all_publ`: all publications identical to this one, whatever node and scope
  Used by round-robin lookup algorithm
- `list`: to form a list of publications in temporal order
- `rcu`: RCU callback head used for deferred freeing

#### <a id="c-struct-name_table"></a>`struct name_table`

table containing all existing port name publications

**Definition**

```c
struct name_table {
    struct rcu_head rcu;
    struct hlist_head services[TIPC_NAMETBL_SIZE];
    struct list_head node_scope;
    struct list_head cluster_scope;
    rwlock_t cluster_scope_lock;
    u32 local_publ_count;
    u32 rc_dests;
    u32 snd_nxt;
};
```

**Members**

- `rcu`: RCU callback head used for deferred freeing
- `services`: name sequence hash lists
- `node_scope`: all local publications with node scope
  - used by name_distr during re-init of name table
- `cluster_scope`: all local publications with cluster scope
  - used by name_distr to send bulk updates to new nodes
  - used by name_distr during re-init of name table
- `cluster_scope_lock`: lock for accessing **cluster_scope**
- `local_publ_count`: number of publications issued by this node
- `rc_dests`: destination node counter
- `snd_nxt`: next sequence number to be used



#### <a id="c-struct-distr_item"></a>`struct distr_item`

publication info distributed to other nodes

**Definition**

```c
struct distr_item {
    __be32 type;
    __be32 lower;
    __be32 upper;
    __be32 port;
    __be32 key;
};
```

**Members**

- `type`: name sequence type
- `lower`: name sequence lower bound
- `upper`: name sequence upper bound
- `port`: publishing port reference
- `key`: publication key

**Description**

===> All fields are stored in network byte order. \<===

First 3 fields identify (name or) name sequence being published.
Reference field uniquely identifies port that published name sequence.
Key field uniquely identifies publication, in the event a port has
multiple publications of the same name sequence.

**Note**

There is no field that identifies the publishing node because it is
the same for all items contained within a publication message.



#### <a id="c-struct-tipc_bc_base"></a>`struct tipc_bc_base`

base structure for keeping broadcast send state

**Definition**

```c
struct tipc_bc_base {
    struct tipc_link *link;
    struct sk_buff_head inputq;
    int dests[MAX_BEARERS];
    int primary_bearer;
    bool bcast_support;
    bool force_bcast;
    bool rcast_support;
    bool force_rcast;
    int rc_ratio;
    int bc_threshold;
};
```

**Members**

- `link`: broadcast send link structure
- `inputq`: data input queue; will only carry SOCK_WAKEUP messages
- `dests`: array keeping number of reachable destinations per bearer
- `primary_bearer`: a bearer having links to all broadcast destinations, if any
- `bcast_support`: indicates if primary bearer, if any, supports broadcast
- `force_bcast`: forces broadcast for multicast traffic
- `rcast_support`: indicates if all peer nodes support replicast
- `force_rcast`: forces replicast for multicast traffic
- `rc_ratio`: dest count as percentage of cluster size where send method changes
- `bc_threshold`: calculated from rc_ratio; if dests > threshold use broadcast


<a id="rst-tipc-bearer-interfaces"></a>

### TIPC Bearer Interfaces


#### <a id="c-tipc_media_find"></a>`tipc_media_find()`

```c
struct tipc_media * tipc_media_find(const char *name)
```

locates specified media object by name

**Parameters**

- `const char *name`: name to locate

#### <a id="c-media_find_id"></a>`media_find_id()`

```c
struct tipc_media * media_find_id(u8 type)
```

locates specified media object by type identifier

**Parameters**

- `u8 type`: type identifier to locate

#### <a id="c-tipc_media_addr_printf"></a>`tipc_media_addr_printf()`

```c
int tipc_media_addr_printf(char *buf, int len, struct tipc_media_addr *a)
```

record media address in print buffer

**Parameters**

- `char *buf`: output buffer
- `int len`: output buffer size remaining
- `struct tipc_media_addr *a`: input media address

#### <a id="c-bearer_name_validate"></a>`bearer_name_validate()`

```c
int bearer_name_validate(const char *name, struct tipc_bearer_names *name_parts)
```

validate & (optionally) deconstruct bearer name

**Parameters**

- `const char *name`: ptr to bearer name string
- `struct tipc_bearer_names *name_parts`: ptr to area for bearer name components (or NULL if not needed)

**Return**

1 if bearer name is valid, otherwise 0.

#### <a id="c-tipc_bearer_find"></a>`tipc_bearer_find()`

```c
struct tipc_bearer * tipc_bearer_find(struct net *net, const char *name)
```

locates bearer object with matching bearer name

**Parameters**

- `struct net *net`: the applicable net namespace
- `const char *name`: bearer name to locate

#### <a id="c-tipc_enable_bearer"></a>`tipc_enable_bearer()`

```c
int tipc_enable_bearer(struct net *net, const char *name, u32 disc_domain, u32 prio, struct nlattr *attr[], struct netlink_ext_ack *extack)
```

enable bearer with the given name

**Parameters**

- `struct net *net`: the applicable net namespace
- `const char *name`: bearer name to enable
- `u32 disc_domain`: bearer domain
- `u32 prio`: bearer priority
- `struct nlattr *attr[]`: nlattr array
- `struct netlink_ext_ack *extack`: netlink extended ack

#### <a id="c-tipc_reset_bearer"></a>`tipc_reset_bearer()`

```c
int tipc_reset_bearer(struct net *net, struct tipc_bearer *b)
```

Reset all links established over this bearer

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct tipc_bearer *b`: the target bearer

#### <a id="c-bearer_disable"></a>`bearer_disable()`

```c
void bearer_disable(struct net *net, struct tipc_bearer *b)
```

disable this bearer

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct tipc_bearer *b`: the bearer to disable

**Note**

This routine assumes caller holds RTNL lock.

#### <a id="c-tipc_l2_send_msg"></a>`tipc_l2_send_msg()`

```c
int tipc_l2_send_msg(struct net *net, struct sk_buff *skb, struct tipc_bearer *b, struct tipc_media_addr *dest)
```

send a TIPC packet out over an L2 interface

**Parameters**

- `struct net *net`: the associated network namespace
- `struct sk_buff *skb`: the packet to be sent
- `struct tipc_bearer *b`: the bearer through which the packet is to be sent
- `struct tipc_media_addr *dest`: peer destination address

#### <a id="c-tipc_l2_rcv_msg"></a>`tipc_l2_rcv_msg()`

```c
int tipc_l2_rcv_msg(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
```

handle incoming TIPC message from an interface

**Parameters**

- `struct sk_buff *skb`: the received message
- `struct net_device *dev`: the net device that the packet was received on
- `struct packet_type *pt`: the packet_type structure which was used to register this handler
- `struct net_device *orig_dev`: the original receive net device in case the device is a bond

**Description**

Accept only packets explicitly sent to this node, or broadcast packets;
ignores packets sent using interface multicast, and traffic sent to other
nodes (which can happen if interface is running in promiscuous mode).

#### <a id="c-tipc_l2_device_event"></a>`tipc_l2_device_event()`

```c
int tipc_l2_device_event(struct notifier_block *nb, unsigned long evt, void *ptr)
```

handle device events from network device

**Parameters**

- `struct notifier_block *nb`: the context of the notification
- `unsigned long evt`: the type of event
- `void *ptr`: the net device that the event was on

**Description**

This function is called by the Ethernet driver in case of link
change event.



#### <a id="c-struct-udp_media_addr"></a>`struct udp_media_addr`

IP/UDP addressing information

**Definition**

```c
struct udp_media_addr {
    __be16 proto;
    __be16 port;
    union {
        struct in_addr ipv4;
        struct in6_addr ipv6;
    };
};
```

**Members**

- `proto`: Ethernet protocol in use
- `port`: port being used
- `{unnamed_union}`: anonymous
- `ipv4`: IPv4 address of neighbor
- `ipv6`: IPv6 address of neighbor

**Description**

This is the bearer level originating address used in neighbor discovery
messages, and all fields should be in network byte order

#### <a id="c-struct-udp_bearer"></a>`struct udp_bearer`

ip/udp bearer data structure

**Definition**

```c
struct udp_bearer {
    struct tipc_bearer  *bearer;
    struct socket *ubsock;
    u32 ifindex;
    struct work_struct work;
    struct udp_replicast rcast;
};
```

**Members**

- `bearer`: associated generic tipc bearer
- `ubsock`: bearer associated socket
- `ifindex`: local address scope
- `work`: used to schedule deferred work on a bearer
- `rcast`: associated udp_replicast container

#### <a id="c-tipc_parse_udp_addr"></a>`tipc_parse_udp_addr()`

```c
int tipc_parse_udp_addr(struct nlattr *nla, struct udp_media_addr *addr, u32 *scope_id)
```

build udp media address from netlink data

**Parameters**

- `struct nlattr *nla`: netlink attribute containing sockaddr storage aligned address
- `struct udp_media_addr *addr`: tipc media address to fill with address, port and protocol type
- `u32 *scope_id`: IPv6 scope id pointer, not NULL indicates it's required

#### <a id="c-tipc_udp_enable"></a>`tipc_udp_enable()`

```c
int tipc_udp_enable(struct net *net, struct tipc_bearer *b, struct nlattr *attrs[])
```

callback to create a new udp bearer instance

**Parameters**

- `struct net *net`: network namespace
- `struct tipc_bearer *b`: pointer to generic tipc_bearer
- `struct nlattr *attrs[]`: netlink bearer configuration

**Description**

validate the bearer parameters and initialize the udp bearer
rtnl_lock should be held


<a id="rst-tipc-crypto-interfaces"></a>

### TIPC Crypto Interfaces


#### <a id="c-struct-tipc_tfm"></a>`struct tipc_tfm`

TIPC TFM structure to form a list of TFMs

**Definition**

```c
struct tipc_tfm {
    struct crypto_aead *tfm;
    struct list_head list;
};
```

**Members**

- `tfm`: cipher handle/key
- `list`: linked list of TFMs

#### <a id="c-struct-tipc_aead"></a>`struct tipc_aead`

TIPC AEAD key structure

**Definition**

```c
struct tipc_aead {
    #define TIPC_AEAD_HINT_LEN (5);
        struct tipc_tfm * __percpu *tfm_entry;
        struct tipc_crypto *crypto;
        struct tipc_aead *cloned;
        atomic_t users;
        u32 salt;
        u8 authsize;
        u8 mode;
        char hint[2 * TIPC_AEAD_HINT_LEN + 1];
        struct rcu_head rcu;
        struct tipc_aead_key *key;
        u16 gen;
        atomic64_t seqno ;
        refcount_t refcnt ;
};
```

**Members**

- `tfm_entry`: per-cpu pointer to one entry in TFM list
- `crypto`: TIPC crypto owns this key
- `cloned`: reference to the source key in case cloning
- `users`: the number of the key users (TX/RX)
- `salt`: the key's SALT value
- `authsize`: authentication tag size (max = 16)
- `mode`: crypto mode is applied to the key
- `hint`: a hint for user key
- `rcu`: struct rcu_head
- `key`: the aead key
- `gen`: the key's generation
- `seqno`: the key seqno (cluster scope)
- `refcnt`: the key reference counter

#### <a id="c-struct-tipc_crypto_stats"></a>`struct tipc_crypto_stats`

TIPC Crypto statistics

**Definition**

```c
struct tipc_crypto_stats {
    unsigned int stat[MAX_STATS];
};
```

**Members**

- `stat`: array of crypto statistics

#### <a id="c-struct-tipc_crypto"></a>`struct tipc_crypto`

TIPC TX/RX crypto structure

**Definition**

```c
struct tipc_crypto {
        struct net *net;
        struct tipc_node *node;
        struct tipc_aead  *aead[KEY_MAX + 1];
        atomic_t peer_rx_active;
        u16 key_gen;
        struct tipc_key key;
        u8 skey_mode;
        struct tipc_aead_key *skey;
        struct workqueue_struct *wq;
        struct delayed_work work;
    #define KEY_DISTR_SCHED         1;
    #define KEY_DISTR_COMPL         2;
        atomic_t key_distr;
        u32 rekeying_intv;
        struct tipc_crypto_stats __percpu *stats;
        char name[48];
        atomic64_t sndnxt ;
        unsigned long timer1;
        unsigned long timer2;
        union {
            struct {
                u8 working:1;
                u8 key_master:1;
                u8 legacy_user:1;
                u8 nokey: 1;
            };
            u8 flags;
        };
        spinlock_t lock;
};
```

**Members**

- `net`: struct net
- `node`: TIPC node (RX)
- `aead`: array of pointers to AEAD keys for encryption/decryption
- `peer_rx_active`: replicated peer RX active key index
- `key_gen`: TX/RX key generation
- `key`: the key states
- `skey_mode`: session key's mode
- `skey`: received session key
- `wq`: common workqueue on TX crypto
- `work`: delayed work sched for TX/RX
- `key_distr`: key distributing state
- `rekeying_intv`: rekeying interval (in minutes)
- `stats`: the crypto statistics
- `name`: the crypto name
- `sndnxt`: the per-peer sndnxt (TX)
- `timer1`: general timer 1 (jiffies)
- `timer2`: general timer 2 (jiffies)
- `{unnamed_union}`: anonymous
- `{unnamed_struct}`: anonymous
- `working`: the crypto is working or not
- `key_master`: flag indicates if master key exists
- `legacy_user`: flag indicates if a peer joins w/o master key (for bwd comp.)
- `nokey`: no key indication
- `flags`: combined flags field
- `lock`: tipc_key lock

#### <a id="c-tipc_aead_key_validate"></a>`tipc_aead_key_validate()`

```c
int tipc_aead_key_validate(struct tipc_aead_key *ukey, struct genl_info *info)
```

Validate a AEAD user key

**Parameters**

- `struct tipc_aead_key *ukey`: pointer to user key data
- `struct genl_info *info`: netlink info pointer

#### <a id="c-tipc_aead_key_generate"></a>`tipc_aead_key_generate()`

```c
int tipc_aead_key_generate(struct tipc_aead_key *skey)
```

Generate new session key

**Parameters**

- `struct tipc_aead_key *skey`: input/output key with new content

**Return**

0 in case of success, otherwise \< 0

#### <a id="c-tipc_aead_free"></a>`tipc_aead_free()`

```c
void tipc_aead_free(struct rcu_head *rp)
```

Release AEAD key incl. all the TFMs in the list

**Parameters**

- `struct rcu_head *rp`: rcu head pointer

#### <a id="c-tipc_aead_tfm_next"></a>`tipc_aead_tfm_next()`

```c
struct crypto_aead * tipc_aead_tfm_next(struct tipc_aead *aead)
```

Move TFM entry to the next one in list and return it

**Parameters**

- `struct tipc_aead *aead`: the AEAD key pointer

#### <a id="c-tipc_aead_init"></a>`tipc_aead_init()`

```c
int tipc_aead_init(struct tipc_aead **aead, struct tipc_aead_key *ukey, u8 mode)
```

Initiate TIPC AEAD

**Parameters**

- `struct tipc_aead **aead`: returned new TIPC AEAD key handle pointer
- `struct tipc_aead_key *ukey`: pointer to user key data
- `u8 mode`: the key mode

**Description**

Allocate a (list of) new cipher transformation (TFM) with the specific user
key data if valid. The number of the allocated TFMs can be set via the sysfs
"net/tipc/max_tfms" first.
Also, all the other AEAD data are also initialized.

**Return**

0 if the initiation is successful, otherwise: \< 0

#### <a id="c-tipc_aead_clone"></a>`tipc_aead_clone()`

```c
int tipc_aead_clone(struct tipc_aead **dst, struct tipc_aead *src)
```

Clone a TIPC AEAD key

**Parameters**

- `struct tipc_aead **dst`: dest key for the cloning
- `struct tipc_aead *src`: source key to clone from

**Description**

Make a "copy" of the source AEAD key data to the dest, the TFMs list is
common for the keys.
A reference to the source is hold in the "cloned" pointer for the later
freeing purposes.

**Note**

this must be done in cluster-key mode only!

**Return**

0 in case of success, otherwise \< 0

#### <a id="c-tipc_aead_mem_alloc"></a>`tipc_aead_mem_alloc()`

```c
void * tipc_aead_mem_alloc(struct crypto_aead *tfm, unsigned int crypto_ctx_size, u8 **iv, struct aead_request **req, struct scatterlist **sg, int nsg)
```

Allocate memory for AEAD request operations

**Parameters**

- `struct crypto_aead *tfm`: cipher handle to be registered with the request
- `unsigned int crypto_ctx_size`: size of crypto context for callback
- `u8 **iv`: returned pointer to IV data
- `struct aead_request **req`: returned pointer to AEAD request data
- `struct scatterlist **sg`: returned pointer to SG lists
- `int nsg`: number of SG lists to be allocated

**Description**

Allocate memory to store the crypto context data, AEAD request, IV and SG
lists, the memory layout is as follows:
crypto_ctx || iv || aead_req || sg\[\]

**Return**

the pointer to the memory areas in case of success, otherwise NULL

#### <a id="c-tipc_aead_encrypt"></a>`tipc_aead_encrypt()`

```c
int tipc_aead_encrypt(struct tipc_aead *aead, struct sk_buff *skb, struct tipc_bearer *b, struct tipc_media_addr *dst, struct tipc_node *__dnode)
```

Encrypt a message

**Parameters**

- `struct tipc_aead *aead`: TIPC AEAD key for the message encryption
- `struct sk_buff *skb`: the input/output skb
- `struct tipc_bearer *b`: TIPC bearer where the message will be delivered after the encryption
- `struct tipc_media_addr *dst`: the destination media address
- `struct tipc_node *__dnode`: TIPC dest node if "known"

**Return**

* 0                   : if the encryption has completed
* -EINPROGRESS/-EBUSY : if a callback will be performed
* \< 0                 : the encryption has failed

#### <a id="c-tipc_aead_decrypt"></a>`tipc_aead_decrypt()`

```c
int tipc_aead_decrypt(struct net *net, struct tipc_aead *aead, struct sk_buff *skb, struct tipc_bearer *b)
```

Decrypt an encrypted message

**Parameters**

- `struct net *net`: struct net
- `struct tipc_aead *aead`: TIPC AEAD for the message decryption
- `struct sk_buff *skb`: the input/output skb
- `struct tipc_bearer *b`: TIPC bearer where the message has been received

**Return**

* 0                   : if the decryption has completed
* -EINPROGRESS/-EBUSY : if a callback will be performed
* \< 0                 : the decryption has failed

#### <a id="c-tipc_ehdr_validate"></a>`tipc_ehdr_validate()`

```c
bool tipc_ehdr_validate(struct sk_buff *skb)
```

Validate an encryption message

**Parameters**

- `struct sk_buff *skb`: the message buffer

**Return**

"true" if this is a valid encryption message, otherwise "false"

#### <a id="c-tipc_ehdr_build"></a>`tipc_ehdr_build()`

```c
int tipc_ehdr_build(struct net *net, struct tipc_aead *aead, u8 tx_key, struct sk_buff *skb, struct tipc_crypto *__rx)
```

Build TIPC encryption message header

**Parameters**

- `struct net *net`: struct net
- `struct tipc_aead *aead`: TX AEAD key to be used for the message encryption
- `u8 tx_key`: key id used for the message encryption
- `struct sk_buff *skb`: input/output message skb
- `struct tipc_crypto *__rx`: RX crypto handle if dest is "known"

**Return**

the header size if the building is successful, otherwise \< 0

#### <a id="c-tipc_crypto_key_init"></a>`tipc_crypto_key_init()`

```c
int tipc_crypto_key_init(struct tipc_crypto *c, struct tipc_aead_key *ukey, u8 mode, bool master_key)
```

Initiate a new user / AEAD key

**Parameters**

- `struct tipc_crypto *c`: TIPC crypto to which new key is attached
- `struct tipc_aead_key *ukey`: the user key
- `u8 mode`: the key mode (CLUSTER_KEY or PER_NODE_KEY)
- `bool master_key`: specify this is a cluster master key

**Description**

A new TIPC AEAD key will be allocated and initiated with the specified user
key, then attached to the TIPC crypto.

**Return**

new key id in case of success, otherwise: \< 0

#### <a id="c-tipc_crypto_key_attach"></a>`tipc_crypto_key_attach()`

```c
int tipc_crypto_key_attach(struct tipc_crypto *c, struct tipc_aead *aead, u8 pos, bool master_key)
```

Attach a new AEAD key to TIPC crypto

**Parameters**

- `struct tipc_crypto *c`: TIPC crypto to which the new AEAD key is attached
- `struct tipc_aead *aead`: the new AEAD key pointer
- `u8 pos`: desired slot in the crypto key array, = 0 if any!
- `bool master_key`: specify this is a cluster master key

**Return**

new key id in case of success, otherwise: -EBUSY

#### <a id="c-tipc_crypto_key_try_align"></a>`tipc_crypto_key_try_align()`

```c
bool tipc_crypto_key_try_align(struct tipc_crypto *rx, u8 new_pending)
```

Align RX keys if possible

**Parameters**

- `struct tipc_crypto *rx`: RX crypto handle
- `u8 new_pending`: new pending slot if aligned (= TX key from peer)

**Description**

Peer has used an unknown key slot, this only happens when peer has left and
rejoned, or we are newcomer.
That means, there must be no active key but a pending key at unaligned slot.
If so, we try to move the pending key to the new slot.

**Note**

A potential passive key can exist, it will be shifted correspondingly!

**Return**

"true" if key is successfully aligned, otherwise "false"

#### <a id="c-tipc_crypto_key_pick_tx"></a>`tipc_crypto_key_pick_tx()`

```c
struct tipc_aead * tipc_crypto_key_pick_tx(struct tipc_crypto *tx, struct tipc_crypto *rx, struct sk_buff *skb, u8 tx_key)
```

Pick one TX key for message decryption

**Parameters**

- `struct tipc_crypto *tx`: TX crypto handle
- `struct tipc_crypto *rx`: RX crypto handle (can be NULL)
- `struct sk_buff *skb`: the message skb which will be decrypted later
- `u8 tx_key`: peer TX key id

**Description**

This function looks up the existing TX keys and pick one which is suitable
for the message decryption, that must be a cluster key and not used before
on the same message (i.e. recursive).

**Return**

the TX AEAD key handle in case of success, otherwise NULL

#### <a id="c-tipc_crypto_key_synch"></a>`tipc_crypto_key_synch()`

```c
void tipc_crypto_key_synch(struct tipc_crypto *rx, struct sk_buff *skb)
```

Synch own key data according to peer key status

**Parameters**

- `struct tipc_crypto *rx`: RX crypto handle
- `struct sk_buff *skb`: TIPCv2 message buffer (incl. the ehdr from peer)

**Description**

This function updates the peer node related data as the peer RX active key
has changed, so the number of TX keys' users on this node are increased and
decreased correspondingly.

It also considers if peer has no key, then we need to make own master key
(if any) taking over i.e. starting grace period and also trigger key
distributing process.

The "per-peer" sndnxt is also reset when the peer key has switched.

#### <a id="c-tipc_crypto_xmit"></a>`tipc_crypto_xmit()`

```c
int tipc_crypto_xmit(struct net *net, struct sk_buff **skb, struct tipc_bearer *b, struct tipc_media_addr *dst, struct tipc_node *__dnode)
```

Build & encrypt TIPC message for xmit

**Parameters**

- `struct net *net`: struct net
- `struct sk_buff **skb`: input/output message skb pointer
- `struct tipc_bearer *b`: bearer used for xmit later
- `struct tipc_media_addr *dst`: destination media address
- `struct tipc_node *__dnode`: destination node for reference if any

**Description**

First, build an encryption message header on the top of the message, then
encrypt the original TIPC message by using the pending, master or active
key with this preference order.
If the encryption is successful, the encrypted skb is returned directly or
via the callback.
Otherwise, the skb is freed!

**Return**

* 0                   : the encryption has succeeded (or no encryption)
* -EINPROGRESS/-EBUSY : the encryption is ongoing, a callback will be made
* -ENOKEK             : the encryption has failed due to no key
* -EKEYREVOKED        : the encryption has failed due to key revoked
* -ENOMEM             : the encryption has failed due to no memory
* \< 0                 : the encryption has failed due to other reasons

#### <a id="c-tipc_crypto_rcv"></a>`tipc_crypto_rcv()`

```c
int tipc_crypto_rcv(struct net *net, struct tipc_crypto *rx, struct sk_buff **skb, struct tipc_bearer *b)
```

Decrypt an encrypted TIPC message from peer

**Parameters**

- `struct net *net`: struct net
- `struct tipc_crypto *rx`: RX crypto handle
- `struct sk_buff **skb`: input/output message skb pointer
- `struct tipc_bearer *b`: bearer where the message has been received

**Description**

If the decryption is successful, the decrypted skb is returned directly or
as the callback, the encryption header and auth tag will be trimmed out
before forwarding to [`tipc_rcv()`](#c-tipc_rcv) via the `tipc_crypto_rcv_complete()`.
Otherwise, the skb will be freed!

**Note**

RX key(s) can be re-aligned, or in case of no key suitable, TX
cluster key(s) can be taken for decryption (- recursive).

**Return**

* 0                   : the decryption has successfully completed
* -EINPROGRESS/-EBUSY : the decryption is ongoing, a callback will be made
* -ENOKEY             : the decryption has failed due to no key
* -EBADMSG            : the decryption has failed due to bad message
* -ENOMEM             : the decryption has failed due to no memory
* \< 0                 : the decryption has failed due to other reasons

#### <a id="c-tipc_crypto_msg_rcv"></a>`tipc_crypto_msg_rcv()`

```c
void tipc_crypto_msg_rcv(struct net *net, struct sk_buff *skb)
```

Common 'MSG_CRYPTO' processing point

**Parameters**

- `struct net *net`: the struct net
- `struct sk_buff *skb`: the receiving message buffer

#### <a id="c-tipc_crypto_key_distr"></a>`tipc_crypto_key_distr()`

```c
int tipc_crypto_key_distr(struct tipc_crypto *tx, u8 key, struct tipc_node *dest)
```

Distribute a TX key

**Parameters**

- `struct tipc_crypto *tx`: the TX crypto
- `u8 key`: the key's index
- `struct tipc_node *dest`: the destination tipc node, = NULL if distributing to all nodes

**Return**

0 in case of success, otherwise \< 0

#### <a id="c-tipc_crypto_key_xmit"></a>`tipc_crypto_key_xmit()`

```c
int tipc_crypto_key_xmit(struct net *net, struct tipc_aead_key *skey, u16 gen, u8 mode, u32 dnode)
```

Send a session key

**Parameters**

- `struct net *net`: the struct net
- `struct tipc_aead_key *skey`: the session key to be sent
- `u16 gen`: the key's generation
- `u8 mode`: the key's mode
- `u32 dnode`: the destination node address, = 0 if broadcasting to all nodes

**Description**

The session key 'skey' is packed in a TIPC v2 'MSG_CRYPTO/KEY_DISTR_MSG'
as its data section, then xmit-ed through the uc/bc link.

**Return**

0 in case of success, otherwise \< 0

#### <a id="c-tipc_crypto_key_rcv"></a>`tipc_crypto_key_rcv()`

```c
bool tipc_crypto_key_rcv(struct tipc_crypto *rx, struct tipc_msg *hdr)
```

Receive a session key

**Parameters**

- `struct tipc_crypto *rx`: the RX crypto
- `struct tipc_msg *hdr`: the TIPC v2 message incl. the receiving session key in its data

**Description**

This function retrieves the session key in the message from peer, then
schedules a RX work to attach the key to the corresponding RX crypto.

**Return**

"true" if the key has been scheduled for attaching, otherwise
"false".

#### <a id="c-tipc_crypto_work_rx"></a>`tipc_crypto_work_rx()`

```c
void tipc_crypto_work_rx(struct work_struct *work)
```

Scheduled RX works handler

**Parameters**

- `struct work_struct *work`: the struct RX work

**Description**

The function processes the previous scheduled works i.e. distributing TX key
or attaching a received session key on RX crypto.

#### <a id="c-tipc_crypto_rekeying_sched"></a>`tipc_crypto_rekeying_sched()`

```c
void tipc_crypto_rekeying_sched(struct tipc_crypto *tx, bool changed, u32 new_intv)
```

(Re)schedule rekeying w/o new interval

**Parameters**

- `struct tipc_crypto *tx`: TX crypto
- `bool changed`: if the rekeying needs to be rescheduled with new interval
- `u32 new_intv`: new rekeying interval (when "changed" = true)

#### <a id="c-tipc_crypto_work_tx"></a>`tipc_crypto_work_tx()`

```c
void tipc_crypto_work_tx(struct work_struct *work)
```

Scheduled TX works handler

**Parameters**

- `struct work_struct *work`: the struct TX work

**Description**

The function processes the previous scheduled work, i.e. key rekeying, by
generating a new session key based on current one, then attaching it to the
TX crypto and finally distributing it to peers. It also re-schedules the
rekeying if needed.


<a id="rst-tipc-discoverer-interfaces"></a>

### TIPC Discoverer Interfaces


#### <a id="c-struct-tipc_discoverer"></a>`struct tipc_discoverer`

information about an ongoing link setup request

**Definition**

```c
struct tipc_discoverer {
    u32 bearer_id;
    struct tipc_media_addr dest;
    struct net *net;
    u32 domain;
    int num_nodes;
    spinlock_t lock;
    struct sk_buff *skb;
    struct timer_list timer;
    unsigned long timer_intv;
};
```

**Members**

- `bearer_id`: identity of bearer issuing requests
- `dest`: destination address for request messages
- `net`: network namespace instance
- `domain`: network domain to which links can be established
- `num_nodes`: number of nodes currently discovered (i.e. with an active link)
- `lock`: spinlock for controlling access to requests
- `skb`: request message to be (repeatedly) sent
- `timer`: timer governing period between requests
- `timer_intv`: current interval between requests (in ms)

#### <a id="c-tipc_disc_init_msg"></a>`tipc_disc_init_msg()`

```c
void tipc_disc_init_msg(struct net *net, struct sk_buff *skb, u32 mtyp, struct tipc_bearer *b)
```

initialize a link setup message

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct sk_buff *skb`: buffer containing message
- `u32 mtyp`: message type (request or response)
- `struct tipc_bearer *b`: ptr to bearer issuing message

#### <a id="c-disc_dupl_alert"></a>`disc_dupl_alert()`

```c
void disc_dupl_alert(struct tipc_bearer *b, u32 node_addr, struct tipc_media_addr *media_addr)
```

issue node address duplication alert

**Parameters**

- `struct tipc_bearer *b`: pointer to bearer detecting duplication
- `u32 node_addr`: duplicated node address
- `struct tipc_media_addr *media_addr`: media address advertised by duplicated node

#### <a id="c-tipc_disc_rcv"></a>`tipc_disc_rcv()`

```c
void tipc_disc_rcv(struct net *net, struct sk_buff *skb, struct tipc_bearer *b)
```

handle incoming discovery message (request or response)

**Parameters**

- `struct net *net`: applicable net namespace
- `struct sk_buff *skb`: buffer containing message
- `struct tipc_bearer *b`: bearer that message arrived on

#### <a id="c-tipc_disc_create"></a>`tipc_disc_create()`

```c
int tipc_disc_create(struct net *net, struct tipc_bearer *b, struct tipc_media_addr *dest, struct sk_buff **skb)
```

create object to send periodic link setup requests

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct tipc_bearer *b`: ptr to bearer issuing requests
- `struct tipc_media_addr *dest`: destination address for request messages
- `struct sk_buff **skb`: pointer to created frame

**Return**

0 if successful, otherwise -errno.

#### <a id="c-tipc_disc_delete"></a>`tipc_disc_delete()`

```c
void tipc_disc_delete(struct tipc_discoverer *d)
```

destroy object sending periodic link setup requests

**Parameters**

- `struct tipc_discoverer *d`: ptr to link dest structure

#### <a id="c-tipc_disc_reset"></a>`tipc_disc_reset()`

```c
void tipc_disc_reset(struct net *net, struct tipc_bearer *b)
```

reset object to send periodic link setup requests

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct tipc_bearer *b`: ptr to bearer issuing requests


<a id="rst-tipc-link-interfaces"></a>

### TIPC Link Interfaces


#### <a id="c-struct-tipc_link"></a>`struct tipc_link`

TIPC link data structure

**Definition**

```c
struct tipc_link {
    u32 addr;
    char name[TIPC_MAX_LINK_NAME];
    struct net *net;
    u16 peer_session;
    u16 session;
    u16 snd_nxt_state;
    u16 rcv_nxt_state;
    u32 peer_bearer_id;
    u32 bearer_id;
    u32 tolerance;
    u32 abort_limit;
    u32 state;
    u16 peer_caps;
    bool in_session;
    bool active;
    u32 silent_intv_cnt;
    char if_name[TIPC_MAX_IF_NAME];
    u32 priority;
    char net_plane;
    struct tipc_mon_state mon_state;
    u16 rst_cnt;
    u16 drop_point;
    struct sk_buff *failover_reasm_skb;
    struct sk_buff_head failover_deferdq;
    u16 mtu;
    u16 advertised_mtu;
    struct sk_buff_head transmq;
    struct sk_buff_head backlogq;
    struct {
        u16 len;
        u16 limit;
        struct sk_buff *target_bskb;
    } backlog[5];
    u16 snd_nxt;
    u16 rcv_nxt;
    u32 rcv_unacked;
    struct sk_buff_head deferdq;
    struct sk_buff_head *inputq;
    struct sk_buff_head *namedq;
    struct sk_buff_head wakeupq;
    u16 window;
    u16 min_win;
    u16 ssthresh;
    u16 max_win;
    u16 cong_acks;
    u16 checkpoint;
    struct sk_buff *reasm_buf;
    struct sk_buff *reasm_tnlmsg;
    u16 ackers;
    u16 acked;
    u16 last_gap;
    struct tipc_gap_ack_blks *last_ga;
    struct tipc_link *bc_rcvlink;
    struct tipc_link *bc_sndlink;
    u8 nack_state;
    bool bc_peer_is_up;
    struct tipc_stats stats;
};
```

**Members**

- `addr`: network address of link's peer node
- `name`: link name character string
- `net`: pointer to namespace struct
- `peer_session`: link session # being used by peer end of link
- `session`: session to be used by link
- `snd_nxt_state`: next send seq number
- `rcv_nxt_state`: next rcv seq number
- `peer_bearer_id`: bearer id used by link's peer endpoint
- `bearer_id`: local bearer id used by link
- `tolerance`: minimum link continuity loss needed to reset link \[in ms\]
- `abort_limit`: \# of unacknowledged continuity probes needed to reset link
- `state`: current state of link FSM
- `peer_caps`: bitmap describing capabilities of peer node
- `in_session`: have received ACTIVATE_MSG from peer
- `active`: link is active
- `silent_intv_cnt`: \# of timer intervals without any reception from peer
- `if_name`: associated interface name
- `priority`: current link priority
- `net_plane`: current link network plane ('A' through 'H')
- `mon_state`: cookie with information needed by link monitor
- `rst_cnt`: link reset counter
- `drop_point`: seq number for failover handling (FIXME)
- `failover_reasm_skb`: saved failover msg ptr (FIXME)
- `failover_deferdq`: deferred message queue for failover processing (FIXME)
- `mtu`: current maximum packet size for this link
- `advertised_mtu`: advertised own mtu when link is being established
- `transmq`: the link's transmit queue
- `backlogq`: queue for messages waiting to be sent
- `backlog`: link's backlog by priority (importance)
- `snd_nxt`: next sequence number to be used
- `rcv_nxt`: next sequence number to expect for inbound messages
- `rcv_unacked`: \# messages read by user, but not yet acked back to peer
- `deferdq`: deferred receive queue
- `inputq`: buffer queue for messages to be delivered upwards
- `namedq`: buffer queue for name table messages to be delivered upwards
- `wakeupq`: linked list of wakeup msgs waiting for link congestion to abate
- `window`: sliding window size for congestion handling
- `min_win`: minimal send window to be used by link
- `ssthresh`: slow start threshold for congestion handling
- `max_win`: maximal send window to be used by link
- `cong_acks`: congestion acks for congestion avoidance (FIXME)
- `checkpoint`: seq number for congestion window size handling
- `reasm_buf`: head of partially reassembled inbound message fragments
- `reasm_tnlmsg`: fragmentation/reassembly area for tunnel protocol message
- `ackers`: \# of peers that needs to ack each packet before it can be released
- `acked`: \# last packet acked by a certain peer. Used for broadcast.
- `last_gap`: last gap ack blocks for bcast (FIXME)
- `last_ga`: ptr to gap ack blocks
- `bc_rcvlink`: the peer specific link used for broadcast reception
- `bc_sndlink`: the namespace global link used for broadcast sending
- `nack_state`: bcast nack state
- `bc_peer_is_up`: peer has acked the bcast init msg
- `stats`: collects statistics regarding link activity

#### <a id="c-tipc_link_create"></a>`tipc_link_create()`

```c
bool tipc_link_create(struct net *net, char *if_name, int bearer_id, int tolerance, char net_plane, u32 mtu, int priority, u32 min_win, u32 max_win, u32 session, u32 self, u32 peer, u8 *peer_id, u16 peer_caps, struct tipc_link *bc_sndlink, struct tipc_link *bc_rcvlink, struct sk_buff_head *inputq, struct sk_buff_head *namedq, struct tipc_link **link)
```

create a new link

**Parameters**

- `struct net *net`: pointer to associated network namespace
- `char *if_name`: associated interface name
- `int bearer_id`: id (index) of associated bearer
- `int tolerance`: link tolerance to be used by link
- `char net_plane`: network plane (A,B,c..) this link belongs to
- `u32 mtu`: mtu to be advertised by link
- `int priority`: priority to be used by link
- `u32 min_win`: minimal send window to be used by link
- `u32 max_win`: maximal send window to be used by link
- `u32 session`: session to be used by link
- `u32 self`: local unicast link id
- `u32 peer`: node id of peer node
- `u8 *peer_id`: 128-bit ID of peer
- `u16 peer_caps`: bitmap describing peer node capabilities
- `struct tipc_link *bc_sndlink`: the namespace global link used for broadcast sending
- `struct tipc_link *bc_rcvlink`: the peer specific link used for broadcast reception
- `struct sk_buff_head *inputq`: queue to put messages ready for delivery
- `struct sk_buff_head *namedq`: queue to put binding table update messages ready for delivery
- `struct tipc_link **link`: return value, pointer to put the created link

**Return**

true if link was created, otherwise false

#### <a id="c-tipc_link_bc_create"></a>`tipc_link_bc_create()`

```c
bool tipc_link_bc_create(struct net *net, u32 ownnode, u32 peer, u8 *peer_id, int mtu, u32 min_win, u32 max_win, u16 peer_caps, struct sk_buff_head *inputq, struct sk_buff_head *namedq, struct tipc_link *bc_sndlink, struct tipc_link **link)
```

create new link to be used for broadcast

**Parameters**

- `struct net *net`: pointer to associated network namespace
- `u32 ownnode`: identity of own node
- `u32 peer`: node id of peer node
- `u8 *peer_id`: 128-bit ID of peer
- `int mtu`: mtu to be used initially if no peers
- `u32 min_win`: minimal send window to be used by link
- `u32 max_win`: maximal send window to be used by link
- `u16 peer_caps`: bitmap describing peer node capabilities
- `struct sk_buff_head *inputq`: queue to put messages ready for delivery
- `struct sk_buff_head *namedq`: queue to put binding table update messages ready for delivery
- `struct tipc_link *bc_sndlink`: the namespace global link used for broadcast sending
- `struct tipc_link **link`: return value, pointer to put the created link

**Return**

true if link was created, otherwise false

#### <a id="c-tipc_link_fsm_evt"></a>`tipc_link_fsm_evt()`

```c
int tipc_link_fsm_evt(struct tipc_link *l, int evt)
```

link finite state machine

**Parameters**

- `struct tipc_link *l`: pointer to link
- `int evt`: state machine event to be processed

#### <a id="c-tipc_link_too_silent"></a>`tipc_link_too_silent()`

```c
bool tipc_link_too_silent(struct tipc_link *l)
```

check if link is "too silent"

**Parameters**

- `struct tipc_link *l`: tipc link to be checked

**Return**

true if the link 'silent_intv_cnt' is about to reach the
'abort_limit' value, otherwise false

#### <a id="c-link_schedule_user"></a>`link_schedule_user()`

```c
int link_schedule_user(struct tipc_link *l, struct tipc_msg *hdr)
```

schedule a message sender for wakeup after congestion

**Parameters**

- `struct tipc_link *l`: congested link
- `struct tipc_msg *hdr`: header of message that is being sent
  Create pseudo msg to send back to user when congestion abates

#### <a id="c-link_prepare_wakeup"></a>`link_prepare_wakeup()`

```c
void link_prepare_wakeup(struct tipc_link *l)
```

prepare users for wakeup after congestion

**Parameters**

- `struct tipc_link *l`: congested link
  Wake up a number of waiting users, as permitted by available space
  in the send queue

#### <a id="c-tipc_link_set_skb_retransmit_time"></a>`tipc_link_set_skb_retransmit_time()`

```c
void tipc_link_set_skb_retransmit_time(struct sk_buff *skb, struct tipc_link *l)
```

set the time at which retransmission of the given skb should be next attempted

**Parameters**

- `struct sk_buff *skb`: skb to set a future retransmission time for
- `struct tipc_link *l`: link the skb will be transmitted on

#### <a id="c-tipc_link_xmit"></a>`tipc_link_xmit()`

```c
int tipc_link_xmit(struct tipc_link *l, struct sk_buff_head *list, struct sk_buff_head *xmitq)
```

enqueue buffer list according to queue situation

**Parameters**

- `struct tipc_link *l`: link to use
- `struct sk_buff_head *list`: chain of buffers containing message
- `struct sk_buff_head *xmitq`: returned list of packets to be sent by caller

**Description**

Consumes the buffer chain.
Messages at TIPC_SYSTEM_IMPORTANCE are always accepted

**Return**

0 if success, or errno: -ELINKCONG, -EMSGSIZE or -ENOBUFS

#### <a id="c-link_retransmit_failure"></a>`link_retransmit_failure()`

```c
bool link_retransmit_failure(struct tipc_link *l, struct tipc_link *r, int *rc)
```

Detect repeated retransmit failures

**Parameters**

- `struct tipc_link *l`: tipc link sender
- `struct tipc_link *r`: tipc link receiver (= l in case of unicast)
- `int *rc`: returned code

**Return**

true if the repeated retransmit failures happens, otherwise
false

#### <a id="c-tipc_get_gap_ack_blks"></a>`tipc_get_gap_ack_blks()`

```c
u16 tipc_get_gap_ack_blks(struct tipc_gap_ack_blks **ga, struct tipc_link *l, struct tipc_msg *hdr, bool uc)
```

get Gap ACK blocks from PROTOCOL/STATE_MSG

**Parameters**

- `struct tipc_gap_ack_blks **ga`: returned pointer to the Gap ACK blocks if any
- `struct tipc_link *l`: the tipc link
- `struct tipc_msg *hdr`: the PROTOCOL/STATE_MSG header
- `bool uc`: desired Gap ACK blocks type, i.e. unicast (= 1) or broadcast (= 0)

**Return**

the total Gap ACK blocks size

#### <a id="c-tipc_link_failover_prepare"></a>`tipc_link_failover_prepare()`

```c
void tipc_link_failover_prepare(struct tipc_link *l, struct tipc_link *tnl, struct sk_buff_head *xmitq)
```

prepare tnl for link failover

**Parameters**

- `struct tipc_link *l`: failover link
- `struct tipc_link *tnl`: tunnel link
- `struct sk_buff_head *xmitq`: queue for messages to be xmited

**Description**

This is a special version of the precursor - `tipc_link_tnl_prepare()`,
see the [`tipc_node_link_failover()`](#c-tipc_node_link_failover) for details

#### <a id="c-tipc_link_reset_stats"></a>`tipc_link_reset_stats()`

```c
void tipc_link_reset_stats(struct tipc_link *l)
```

reset link statistics

**Parameters**

- `struct tipc_link *l`: pointer to link

#### <a id="c-tipc_link_dump"></a>`tipc_link_dump()`

```c
int tipc_link_dump(struct tipc_link *l, u16 dqueues, char *buf)
```

dump TIPC link data

**Parameters**

- `struct tipc_link *l`: tipc link to be dumped
- `u16 dqueues`: bitmask to decide if any link queue to be dumped?
  - TIPC_DUMP_NONE: don't dump link queues
  - TIPC_DUMP_TRANSMQ: dump link transmq queue
  - TIPC_DUMP_BACKLOGQ: dump link backlog queue
  - TIPC_DUMP_DEFERDQ: dump link deferd queue
  - TIPC_DUMP_INPUTQ: dump link input queue
  - TIPC_DUMP_WAKEUP: dump link wakeup queue
  - TIPC_DUMP_ALL: dump all the link queues above
- `char *buf`: returned buffer of dump data in format


<a id="rst-tipc-msg-interfaces"></a>

### TIPC msg Interfaces


#### <a id="c-tipc_buf_acquire"></a>`tipc_buf_acquire()`

```c
struct sk_buff * tipc_buf_acquire(u32 size, gfp_t gfp)
```

creates a TIPC message buffer

**Parameters**

- `u32 size`: message size (including TIPC header)
- `gfp_t gfp`: memory allocation flags

**Return**

a new buffer with data pointers set to the specified size.

**NOTE**

Headroom is reserved to allow prepending of a data link header.
There may also be unrequested tailroom present at the buffer's end.

#### <a id="c-tipc_msg_append"></a>`tipc_msg_append()`

```c
int tipc_msg_append(struct tipc_msg *_hdr, struct msghdr *m, int dlen, int mss, struct sk_buff_head *txq)
```

Append data to tail of an existing buffer queue

**Parameters**

- `struct tipc_msg *_hdr`: header to be used
- `struct msghdr *m`: the data to be appended
- `int dlen`: size of data to be appended
- `int mss`: max allowable size of buffer
- `struct sk_buff_head *txq`: queue to append to

**Return**

the number of 1k blocks appended or errno value

#### <a id="c-tipc_msg_fragment"></a>`tipc_msg_fragment()`

```c
int tipc_msg_fragment(struct sk_buff *skb, const struct tipc_msg *hdr, int pktmax, struct sk_buff_head *frags)
```

build a fragment skb list for TIPC message

**Parameters**

- `struct sk_buff *skb`: TIPC message skb
- `const struct tipc_msg *hdr`: internal msg header to be put on the top of the fragments
- `int pktmax`: max size of a fragment incl. the header
- `struct sk_buff_head *frags`: returned fragment skb list

**Return**

0 if the fragmentation is successful, otherwise: -EINVAL
or -ENOMEM

#### <a id="c-tipc_msg_build"></a>`tipc_msg_build()`

```c
int tipc_msg_build(struct tipc_msg *mhdr, struct msghdr *m, int offset, int dsz, int pktmax, struct sk_buff_head *list)
```

create buffer chain containing specified header and data

**Parameters**

- `struct tipc_msg *mhdr`: Message header, to be prepended to data
- `struct msghdr *m`: User message
- `int offset`: buffer offset for fragmented messages (FIXME)
- `int dsz`: Total length of user data
- `int pktmax`: Max packet size that can be used
- `struct sk_buff_head *list`: Buffer or chain of buffers to be returned to caller

**Description**

Note that the recursive call we are making here is safe, since it can
logically go only one further level down.

**Return**

message data size or errno: -ENOMEM, -EFAULT

#### <a id="c-tipc_msg_bundle"></a>`tipc_msg_bundle()`

```c
bool tipc_msg_bundle(struct sk_buff *bskb, struct tipc_msg *msg, u32 max)
```

Append contents of a buffer to tail of an existing one

**Parameters**

- `struct sk_buff *bskb`: the bundle buffer to append to
- `struct tipc_msg *msg`: message to be appended
- `u32 max`: max allowable size for the bundle buffer

**Return**

"true" if bundling has been performed, otherwise "false"

#### <a id="c-tipc_msg_try_bundle"></a>`tipc_msg_try_bundle()`

```c
bool tipc_msg_try_bundle(struct sk_buff *tskb, struct sk_buff **skb, u32 mss, u32 dnode, bool *new_bundle)
```

Try to bundle a new message to the last one

**Parameters**

- `struct sk_buff *tskb`: the last/target message to which the new one will be appended
- `struct sk_buff **skb`: the new message skb pointer
- `u32 mss`: max message size (header inclusive)
- `u32 dnode`: destination node for the message
- `bool *new_bundle`: if this call made a new bundle or not

**Return**

"true" if the new message skb is potential for bundling this time or
later, in the case a bundling has been done this time, the skb is consumed
(the skb pointer = NULL).
Otherwise, "false" if the skb cannot be bundled at all.

#### <a id="c-tipc_msg_extract"></a>`tipc_msg_extract()`

```c
bool tipc_msg_extract(struct sk_buff *skb, struct sk_buff **iskb, int *pos)
```

extract bundled inner packet from buffer

**Parameters**

- `struct sk_buff *skb`: buffer to be extracted from.
- `struct sk_buff **iskb`: extracted inner buffer, to be returned
- `int *pos`: position in outer message of msg to be extracted.
  Returns position of next msg.
  Consumes outer buffer when last packet extracted

**Return**

true when there is an extracted buffer, otherwise false

#### <a id="c-tipc_msg_reverse"></a>`tipc_msg_reverse()`

```c
bool tipc_msg_reverse(u32 own_node, struct sk_buff **skb, int err)
```

swap source and destination addresses and add error code

**Parameters**

- `u32 own_node`: originating node id for reversed message
- `struct sk_buff **skb`: buffer containing message to be reversed; will be consumed
- `int err`: error code to be set in message, if any
  Replaces consumed buffer with new one when successful

**Return**

true if success, otherwise false

#### <a id="c-tipc_msg_lookup_dest"></a>`tipc_msg_lookup_dest()`

```c
bool tipc_msg_lookup_dest(struct net *net, struct sk_buff *skb, int *err)
```

try to find new destination for named message

**Parameters**

- `struct net *net`: pointer to associated network namespace
- `struct sk_buff *skb`: the buffer containing the message.
- `int *err`: error code to be used by caller if lookup fails
  Does not consume buffer

**Return**

true if a destination is found, false otherwise


<a id="rst-tipc-name-interfaces"></a>

### TIPC Name Interfaces


#### <a id="c-struct-service_range"></a>`struct service_range`

container for all bindings of a service range

**Definition**

```c
struct service_range {
    u32 lower;
    u32 upper;
    struct rb_node tree_node;
    u32 max;
    struct list_head local_publ;
    struct list_head all_publ;
};
```

**Members**

- `lower`: service range lower bound
- `upper`: service range upper bound
- `tree_node`: member of service range RB tree
- `max`: largest 'upper' in this node subtree
- `local_publ`: list of identical publications made from this node
  Used by closest_first lookup and multicast lookup algorithm
- `all_publ`: all publications identical to this one, whatever node and scope
  Used by round-robin lookup algorithm

#### <a id="c-struct-tipc_service"></a>`struct tipc_service`

container for all published instances of a service type

**Definition**

```c
struct tipc_service {
    u32 type;
    u32 publ_cnt;
    struct rb_root ranges;
    struct hlist_node service_list;
    struct list_head subscriptions;
    spinlock_t lock;
    struct rcu_head rcu;
};
```

**Members**

- `type`: 32 bit 'type' value for service
- `publ_cnt`: increasing counter for publications in this service
- `ranges`: rb tree containing all service ranges for this service
- `service_list`: links to adjacent name ranges in hash chain
- `subscriptions`: list of subscriptions for this service type
- `lock`: spinlock controlling access to pertaining service ranges/publications
- `rcu`: RCU callback head used for deferred freeing

#### <a id="c-service_range_foreach_match"></a>`service_range_foreach_match()`

```c
service_range_foreach_match(sr, sc, start, end)
```

iterate over tipc service rbtree for each range match

**Parameters**

- `sr`: the service range pointer as a loop cursor
- `sc`: the pointer to tipc service which holds the service range rbtree
- `start`: beginning of the search range (end >= start) for matching
- `end`: end of the search range (end >= start) for matching

#### <a id="c-service_range_match_first"></a>`service_range_match_first()`

```c
struct service_range * service_range_match_first(struct rb_node *n, u32 start, u32 end)
```

find first service range matching a range

**Parameters**

- `struct rb_node *n`: the root node of service range rbtree for searching
- `u32 start`: beginning of the search range (end >= start) for matching
- `u32 end`: end of the search range (end >= start) for matching

**Return**

the leftmost service range node in the rbtree that overlaps the
specific range if any. Otherwise, returns NULL.

#### <a id="c-service_range_match_next"></a>`service_range_match_next()`

```c
struct service_range * service_range_match_next(struct rb_node *n, u32 start, u32 end)
```

find next service range matching a range

**Parameters**

- `struct rb_node *n`: a node in service range rbtree from which the searching starts
- `u32 start`: beginning of the search range (end >= start) for matching
- `u32 end`: end of the search range (end >= start) for matching

**Return**

the next service range node to the given node in the rbtree that
overlaps the specific range if any. Otherwise, returns NULL.

#### <a id="c-tipc_publ_create"></a>`tipc_publ_create()`

```c
struct publication * tipc_publ_create(struct tipc_uaddr *ua, struct tipc_socket_addr *sk, u32 key)
```

create a publication structure

**Parameters**

- `struct tipc_uaddr *ua`: the service range the user is binding to
- `struct tipc_socket_addr *sk`: the address of the socket that is bound
- `u32 key`: publication key

#### <a id="c-tipc_service_create"></a>`tipc_service_create()`

```c
struct tipc_service * tipc_service_create(struct net *net, struct tipc_uaddr *ua)
```

create a service structure for the specified 'type'

**Parameters**

- `struct net *net`: network namespace
- `struct tipc_uaddr *ua`: address representing the service to be bound

**Description**

Allocates a single range structure and sets it to all 0's.

#### <a id="c-tipc_service_remove_publ"></a>`tipc_service_remove_publ()`

```c
struct publication * tipc_service_remove_publ(struct service_range *r, struct tipc_socket_addr *sk, u32 key)
```

remove a publication from a service

**Parameters**

- `struct service_range *r`: service_range to remove publication from
- `struct tipc_socket_addr *sk`: address publishing socket
- `u32 key`: target publication key

#### <a id="c-tipc_service_subscribe"></a>`tipc_service_subscribe()`

```c
void tipc_service_subscribe(struct tipc_service *service, struct tipc_subscription *sub)
```

attach a subscription, and optionally issue the prescribed number of events if there is any service range overlapping with the requested range

**Parameters**

- `struct tipc_service *service`: the tipc_service to attach the **sub** to
- `struct tipc_subscription *sub`: the subscription to attach

#### <a id="c-tipc_nametbl_lookup_anycast"></a>`tipc_nametbl_lookup_anycast()`

```c
bool tipc_nametbl_lookup_anycast(struct net *net, struct tipc_uaddr *ua, struct tipc_socket_addr *sk)
```

perform service instance to socket translation

**Parameters**

- `struct net *net`: network namespace
- `struct tipc_uaddr *ua`: service address to look up
- `struct tipc_socket_addr *sk`: address to socket we want to find

**Description**

On entry, a non-zero 'sk->node' indicates the node where we want lookup to be
performed, which may not be this one.

On exit:

- If lookup is deferred to another node, leave 'sk->node' unchanged and
  return 'true'.
- If lookup is successful, set the 'sk->node' and 'sk->ref' (== portid) which
  represent the bound socket and return 'true'.
- If lookup fails, return 'false'

Note that for legacy users (node configured with Z.C.N address format) the
'closest-first' lookup algorithm must be maintained, i.e., if sk.node is 0
we must look in the local binding list first

#### <a id="c-tipc_nametbl_withdraw"></a>`tipc_nametbl_withdraw()`

```c
void tipc_nametbl_withdraw(struct net *net, struct tipc_uaddr *ua, struct tipc_socket_addr *sk, u32 key)
```

withdraw a service binding

**Parameters**

- `struct net *net`: network namespace
- `struct tipc_uaddr *ua`: service address/range being unbound
- `struct tipc_socket_addr *sk`: address of the socket being unbound from
- `u32 key`: target publication key

#### <a id="c-tipc_nametbl_subscribe"></a>`tipc_nametbl_subscribe()`

```c
bool tipc_nametbl_subscribe(struct tipc_subscription *sub)
```

add a subscription object to the name table

**Parameters**

- `struct tipc_subscription *sub`: subscription to add

#### <a id="c-tipc_nametbl_unsubscribe"></a>`tipc_nametbl_unsubscribe()`

```c
void tipc_nametbl_unsubscribe(struct tipc_subscription *sub)
```

remove a subscription object from name table

**Parameters**

- `struct tipc_subscription *sub`: subscription to remove

#### <a id="c-tipc_service_delete"></a>`tipc_service_delete()`

```c
void tipc_service_delete(struct net *net, struct tipc_service *sc)
```

purge all publications for a service and delete it

**Parameters**

- `struct net *net`: the associated network namespace
- `struct tipc_service *sc`: tipc_service to delete



#### <a id="c-publ_to_item"></a>`publ_to_item()`

```c
void publ_to_item(struct distr_item *i, struct publication *p)
```

add publication info to a publication message

**Parameters**

- `struct distr_item *i`: location of item in the message
- `struct publication *p`: publication info

#### <a id="c-named_prepare_buf"></a>`named_prepare_buf()`

```c
struct sk_buff * named_prepare_buf(struct net *net, u32 type, u32 size, u32 dest)
```

allocate & initialize a publication message

**Parameters**

- `struct net *net`: the associated network namespace
- `u32 type`: message type
- `u32 size`: payload size
- `u32 dest`: destination node

**Description**

The buffer returned is of size INT_H_SIZE + payload size

#### <a id="c-tipc_named_publish"></a>`tipc_named_publish()`

```c
struct sk_buff * tipc_named_publish(struct net *net, struct publication *p)
```

tell other nodes about a new publication by this node

**Parameters**

- `struct net *net`: the associated network namespace
- `struct publication *p`: the new publication

#### <a id="c-tipc_named_withdraw"></a>`tipc_named_withdraw()`

```c
struct sk_buff * tipc_named_withdraw(struct net *net, struct publication *p)
```

tell other nodes about a withdrawn publication by this node

**Parameters**

- `struct net *net`: the associated network namespace
- `struct publication *p`: the withdrawn publication

#### <a id="c-named_distribute"></a>`named_distribute()`

```c
void named_distribute(struct net *net, struct sk_buff_head *list, u32 dnode, struct list_head *pls, u16 seqno)
```

prepare name info for bulk distribution to another node

**Parameters**

- `struct net *net`: the associated network namespace
- `struct sk_buff_head *list`: list of messages (buffers) to be returned from this function
- `u32 dnode`: node to be updated
- `struct list_head *pls`: linked list of publication items to be packed into buffer chain
- `u16 seqno`: sequence number for this message

#### <a id="c-tipc_named_node_up"></a>`tipc_named_node_up()`

```c
void tipc_named_node_up(struct net *net, u32 dnode, u16 capabilities)
```

tell specified node about all publications by this node

**Parameters**

- `struct net *net`: the associated network namespace
- `u32 dnode`: destination node
- `u16 capabilities`: peer node's capabilities

#### <a id="c-tipc_publ_purge"></a>`tipc_publ_purge()`

```c
void tipc_publ_purge(struct net *net, struct publication *p, u32 addr)
```

remove publication associated with a failed node

**Parameters**

- `struct net *net`: the associated network namespace
- `struct publication *p`: the publication to remove
- `u32 addr`: failed node's address

**Description**

Invoked for each publication issued by a newly failed node.
Removes publication structure from name table & deletes it.

#### <a id="c-tipc_update_nametbl"></a>`tipc_update_nametbl()`

```c
bool tipc_update_nametbl(struct net *net, struct distr_item *i, u32 node, u32 dtype)
```

try to process a nametable update and notify subscribers

**Parameters**

- `struct net *net`: the associated network namespace
- `struct distr_item *i`: location of item in the message
- `u32 node`: node address
- `u32 dtype`: name distributor message type

**Description**

tipc_nametbl_lock must be held.

**Return**

the publication item if successful, otherwise NULL.

#### <a id="c-tipc_named_rcv"></a>`tipc_named_rcv()`

```c
void tipc_named_rcv(struct net *net, struct sk_buff_head *namedq, u16 *rcv_nxt, bool *open)
```

process name table update messages sent by another node

**Parameters**

- `struct net *net`: the associated network namespace
- `struct sk_buff_head *namedq`: queue to receive from
- `u16 *rcv_nxt`: store last received seqno here
- `bool *open`: last bulk msg was received (FIXME)

#### <a id="c-tipc_named_reinit"></a>`tipc_named_reinit()`

```c
void tipc_named_reinit(struct net *net)
```

re-initialize local publications

**Parameters**

- `struct net *net`: the associated network namespace

**Description**

This routine is called whenever TIPC networking is enabled.
All name table entries published by this node are updated to reflect
the node's new network address.


<a id="rst-tipc-node-management-interfaces"></a>

### TIPC Node Management Interfaces


#### <a id="c-struct-tipc_node"></a>`struct tipc_node`

TIPC node structure

**Definition**

```c
struct tipc_node {
        u32 addr;
        struct kref kref;
        rwlock_t lock;
        struct net *net;
        struct hlist_node hash;
        int active_links[2];
        struct tipc_link_entry links[MAX_BEARERS];
        struct tipc_bclink_entry bc_entry;
        int action_flags;
        struct list_head list;
        int state;
        bool preliminary;
        bool failover_sent;
        u16 sync_point;
        int link_cnt;
        u16 working_links;
        u16 capabilities;
        u32 signature;
        u32 link_id;
        u8 peer_id[16];
        char peer_id_string[NODE_ID_STR_LEN];
        struct list_head publ_list;
        struct list_head conn_sks;
        unsigned long keepalive_intv;
        struct timer_list timer;
        struct rcu_head rcu;
        unsigned long delete_at;
        struct net *peer_net;
        u32 peer_hash_mix;
    #ifdef CONFIG_TIPC_CRYPTO;
        struct tipc_crypto *crypto_rx;
    #endif;
};
```

**Members**

- `addr`: network address of node
- `kref`: reference counter to node object
- `lock`: rwlock governing access to structure
- `net`: the applicable net namespace
- `hash`: links to adjacent nodes in unsorted hash chain
- `active_links`: bearer ids of active links, used as index into links\[\] array
- `links`: array containing references to all links to node
- `bc_entry`: broadcast link entry
- `action_flags`: bit mask of different types of node actions
- `list`: links to adjacent nodes in sorted list of cluster's nodes
- `state`: connectivity state vs peer node
- `preliminary`: a preliminary node or not
- `failover_sent`: failover sent or not
- `sync_point`: sequence number where synch/failover is finished
- `link_cnt`: number of links to node
- `working_links`: number of working links to node (both active and standby)
- `capabilities`: bitmap, indicating peer node's functional capabilities
- `signature`: node instance identifier
- `link_id`: local and remote bearer ids of changing link, if any
- `peer_id`: 128-bit ID of peer
- `peer_id_string`: ID string of peer
- `publ_list`: list of publications
- `conn_sks`: list of connections (FIXME)
- `keepalive_intv`: keepalive interval in milliseconds
- `timer`: node's keepalive timer
- `rcu`: rcu struct for tipc_node
- `delete_at`: indicates the time for deleting a down node
- `peer_net`: peer's net namespace
- `peer_hash_mix`: hash for this peer (FIXME)
- `crypto_rx`: RX crypto handler

#### <a id="c-tipc_node_crypto_rx"></a>`tipc_node_crypto_rx()`

```c
struct tipc_crypto * tipc_node_crypto_rx(struct tipc_node *__n)
```

Retrieve crypto RX handle from node

**Parameters**

- `struct tipc_node *__n`: target tipc_node

**Note**

node ref counter must be held first!

#### <a id="c-__tipc_node_link_up"></a>`__tipc_node_link_up()`

```c
void __tipc_node_link_up(struct tipc_node *n, int bearer_id, struct sk_buff_head *xmitq)
```

handle addition of link

**Parameters**

- `struct tipc_node *n`: target tipc_node
- `int bearer_id`: id of the bearer
- `struct sk_buff_head *xmitq`: queue for messages to be xmited on
  Node lock must be held by caller
  Link becomes active (alone or shared) or standby, depending on its priority.

#### <a id="c-tipc_node_link_up"></a>`tipc_node_link_up()`

```c
void tipc_node_link_up(struct tipc_node *n, int bearer_id, struct sk_buff_head *xmitq)
```

handle addition of link

**Parameters**

- `struct tipc_node *n`: target tipc_node
- `int bearer_id`: id of the bearer
- `struct sk_buff_head *xmitq`: queue for messages to be xmited on

**Description**

Link becomes active (alone or shared) or standby, depending on its priority.

#### <a id="c-tipc_node_link_failover"></a>`tipc_node_link_failover()`

```c
void tipc_node_link_failover(struct tipc_node *n, struct tipc_link *l, struct tipc_link *tnl, struct sk_buff_head *xmitq)
```

start failover in case "half-failover"

**Parameters**

- `struct tipc_node *n`: tipc node structure
- `struct tipc_link *l`: link peer endpoint failingover (- can be NULL)
- `struct tipc_link *tnl`: tunnel link
- `struct sk_buff_head *xmitq`: queue for messages to be xmited on tnl link later

**Description**

This function is only called in a very special situation where link
failover can be already started on peer node but not on this node.
This can happen when e.g.:

```text
1. Both links <1A-2A>, <1B-2B> down
2. Link endpoint 2A up, but 1A still down (e.g. due to network
disturbance, wrong session, etc.)
3. Link <1B-2B> up
4. Link endpoint 2A down (e.g. due to link tolerance timeout)
5. Node 2 starts failover onto link <1B-2B>

==> Node 1 does never start link/node failover!
```

#### <a id="c-__tipc_node_link_down"></a>`__tipc_node_link_down()`

```c
void __tipc_node_link_down(struct tipc_node *n, int *bearer_id, struct sk_buff_head *xmitq, struct tipc_media_addr **maddr)
```

handle loss of link

**Parameters**

- `struct tipc_node *n`: target tipc_node
- `int *bearer_id`: id of the bearer
- `struct sk_buff_head *xmitq`: queue for messages to be xmited on
- `struct tipc_media_addr **maddr`: output media address of the bearer

#### <a id="c-tipc_node_get_linkname"></a>`tipc_node_get_linkname()`

```c
int tipc_node_get_linkname(struct net *net, u32 bearer_id, u32 addr, char *linkname, size_t len)
```

get the name of a link

**Parameters**

- `struct net *net`: the applicable net namespace
- `u32 bearer_id`: id of the bearer
- `u32 addr`: peer node address
- `char *linkname`: link name output buffer
- `size_t len`: size of **linkname** output buffer

**Return**

0 on success

#### <a id="c-tipc_node_xmit"></a>`tipc_node_xmit()`

```c
int tipc_node_xmit(struct net *net, struct sk_buff_head *list, u32 dnode, int selector)
```

general link level function for message sending

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct sk_buff_head *list`: chain of buffers containing message
- `u32 dnode`: address of destination node
- `int selector`: a number used for deterministic link selection
  Consumes the buffer chain.

**Return**

0 if success, otherwise: -ELINKCONG,-EHOSTUNREACH,-EMSGSIZE,-ENOBUF

#### <a id="c-tipc_node_bc_rcv"></a>`tipc_node_bc_rcv()`

```c
void tipc_node_bc_rcv(struct net *net, struct sk_buff *skb, int bearer_id)
```

process TIPC broadcast packet arriving from off-node

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct sk_buff *skb`: TIPC packet
- `int bearer_id`: id of bearer message arrived on

**Description**

Invoked with no locks held.

#### <a id="c-tipc_node_check_state"></a>`tipc_node_check_state()`

```c
bool tipc_node_check_state(struct tipc_node *n, struct sk_buff *skb, int bearer_id, struct sk_buff_head *xmitq)
```

check and if necessary update node state

**Parameters**

- `struct tipc_node *n`: target tipc_node
- `struct sk_buff *skb`: TIPC packet
- `int bearer_id`: identity of bearer delivering the packet
- `struct sk_buff_head *xmitq`: queue for messages to be xmited on

**Return**

true if state and msg are ok, otherwise false

#### <a id="c-tipc_rcv"></a>`tipc_rcv()`

```c
void tipc_rcv(struct net *net, struct sk_buff *skb, struct tipc_bearer *b)
```

process TIPC packets/messages arriving from off-node

**Parameters**

- `struct net *net`: the applicable net namespace
- `struct sk_buff *skb`: TIPC packet
- `struct tipc_bearer *b`: pointer to bearer message arrived on

**Description**

Invoked with no locks held. Bearer pointer must point to a valid bearer
structure (i.e. cannot be NULL), but bearer can be inactive.

#### <a id="c-tipc_node_dump"></a>`tipc_node_dump()`

```c
int tipc_node_dump(struct tipc_node *n, bool more, char *buf)
```

dump TIPC node data

**Parameters**

- `struct tipc_node *n`: tipc node to be dumped
- `bool more`: dump more?
  - false: dump only tipc node data
  - true: dump node link data as well
- `char *buf`: returned buffer of dump data in format


<a id="rst-tipc-socket-interfaces"></a>

### TIPC Socket Interfaces


#### <a id="c-struct-tipc_sock"></a>`struct tipc_sock`

TIPC socket structure

**Definition**

```c
struct tipc_sock {
    struct sock sk;
    u32 max_pkt;
    u32 maxnagle;
    u32 portid;
    struct tipc_msg phdr;
    struct list_head cong_links;
    struct list_head publications;
    u32 pub_count;
    atomic_t dupl_rcvcnt;
    u16 conn_timeout;
    bool probe_unacked;
    u16 cong_link_cnt;
    u16 snt_unacked;
    u16 snd_win;
    u16 peer_caps;
    u16 rcv_unacked;
    u16 rcv_win;
    struct sockaddr_tipc peer;
    struct rhash_head node;
    struct tipc_mc_method mc_method;
    struct rcu_head rcu;
    struct tipc_group *group;
    u32 oneway;
    u32 nagle_start;
    u16 snd_backlog;
    u16 msg_acc;
    u16 pkt_cnt;
    bool expect_ack;
    bool nodelay;
    bool group_is_open;
    bool published;
    u8 conn_addrtype;
};
```

**Members**

- `sk`: socket - interacts with 'port' and with user via the socket API
- `max_pkt`: maximum packet size "hint" used when building messages sent by port
- `maxnagle`: maximum size of msg which can be subject to nagle
- `portid`: unique port identity in TIPC socket hash table
- `phdr`: preformatted message header used when sending messages
- `cong_links`: list of congested links
- `publications`: list of publications for port
- `pub_count`: total # of publications port has made during its lifetime
- `dupl_rcvcnt`: number of bytes counted twice, in both backlog and rcv queue
- `conn_timeout`: the time we can wait for an unresponded setup request
- `probe_unacked`: probe has not received ack yet
- `cong_link_cnt`: number of congested links
- `snt_unacked`: \# messages sent by socket, and not yet acked by peer
- `snd_win`: send window size
- `peer_caps`: peer capabilities mask
- `rcv_unacked`: \# messages read by user, but not yet acked back to peer
- `rcv_win`: receive window size
- `peer`: 'connected' peer for dgram/rdm
- `node`: hash table node
- `mc_method`: cookie for use between socket and broadcast layer
- `rcu`: rcu struct for tipc_sock
- `group`: TIPC communications group
- `oneway`: message count in one direction (FIXME)
- `nagle_start`: current nagle value
- `snd_backlog`: send backlog count
- `msg_acc`: messages accepted; used in managing backlog and nagle
- `pkt_cnt`: TIPC socket packet count
- `expect_ack`: whether this TIPC socket is expecting an ack
- `nodelay`: `setsockopt()` TIPC_NODELAY setting
- `group_is_open`: TIPC socket group is fully open (FIXME)
- `published`: true if port has one or more associated names
- `conn_addrtype`: address type used when establishing connection

#### <a id="c-tsk_advance_rx_queue"></a>`tsk_advance_rx_queue()`

```c
void tsk_advance_rx_queue(struct sock *sk)
```

discard first buffer in socket receive queue

**Parameters**

- `struct sock *sk`: network socket

**Description**

Caller must hold socket lock

#### <a id="c-tsk_rej_rx_queue"></a>`tsk_rej_rx_queue()`

```c
void tsk_rej_rx_queue(struct sock *sk, int error)
```

reject all buffers in socket receive queue

**Parameters**

- `struct sock *sk`: network socket
- `int error`: response error code

**Description**

Caller must hold socket lock

#### <a id="c-tipc_sk_create"></a>`tipc_sk_create()`

```c
int tipc_sk_create(struct net *net, struct socket *sock, int protocol, int kern)
```

create a TIPC socket

**Parameters**

- `struct net *net`: network namespace (must be default network)
- `struct socket *sock`: pre-allocated socket structure
- `int protocol`: protocol indicator (must be 0)
- `int kern`: caused by kernel or by userspace?

**Description**

This routine creates additional data structures used by the TIPC socket,
initializes them, and links them together.

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_release"></a>`tipc_release()`

```c
int tipc_release(struct socket *sock)
```

destroy a TIPC socket

**Parameters**

- `struct socket *sock`: socket to destroy

**Description**

This routine cleans up any messages that are still queued on the socket.
For DGRAM and RDM socket types, all queued messages are rejected.
For SEQPACKET and STREAM socket types, the first message is rejected
and any others are discarded.  (If the first message on a STREAM socket
is partially-read, it is discarded and the next one is rejected instead.)

**NOTE**

Rejected messages are not necessarily returned to the sender!  They
are returned or discarded according to the "destination droppable" setting
specified for the message by the sender.

**Return**

0 on success, errno otherwise

#### <a id="c-__tipc_bind"></a>`__tipc_bind()`

```c
int __tipc_bind(struct socket *sock, struct sockaddr *skaddr, int alen)
```

associate or disassociate TIPC name(s) with a socket

**Parameters**

- `struct socket *sock`: socket structure
- `struct sockaddr *skaddr`: socket address describing name(s) and desired operation
- `int alen`: size of socket address data structure

**Description**

Name and name sequence binding are indicated using a positive scope value;
a negative scope value unbinds the specified name.  Specifying no name
(i.e. a socket address length of 0) unbinds all names from the socket.

**Return**

0 on success, errno otherwise

**NOTE**

- This routine doesn't need to take the socket lock since it doesn't

  access any non-constant socket information.

#### <a id="c-tipc_getname"></a>`tipc_getname()`

```c
int tipc_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
```

get port ID of socket or peer socket

**Parameters**

- `struct socket *sock`: socket structure
- `struct sockaddr *uaddr`: area for returned socket address
- `int peer`: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID

**Return**

0 on success, errno otherwise

**NOTE**

- This routine doesn't need to take the socket lock since it only

  accesses socket information that is unchanging (or which changes in
  a completely predictable manner).

#### <a id="c-tipc_poll"></a>`tipc_poll()`

```c
__poll_t tipc_poll(struct file *file, struct socket *sock, poll_table *wait)
```

read and possibly block on pollmask

**Parameters**

- `struct file *file`: file structure associated with the socket
- `struct socket *sock`: socket for which to calculate the poll bits
- `poll_table *wait`: \???

**Return**

pollmask value

**Description**

COMMENTARY:
It appears that the usual socket locking mechanisms are not useful here
since the pollmask info is potentially out-of-date the moment this routine
exits.  TCP and other protocols seem to rely on higher level poll routines
to handle any preventable race conditions, so TIPC will do the same ...

IMPORTANT: The fact that a read or write operation is indicated does NOT
imply that the operation will succeed, merely that it should be performed
and will not block.

#### <a id="c-tipc_sendmcast"></a>`tipc_sendmcast()`

```c
int tipc_sendmcast(struct socket *sock, struct tipc_uaddr *ua, struct msghdr *msg, size_t dlen, long timeout)
```

send multicast message

**Parameters**

- `struct socket *sock`: socket structure
- `struct tipc_uaddr *ua`: destination address struct
- `struct msghdr *msg`: message to send
- `size_t dlen`: length of data to send
- `long timeout`: timeout to wait for wakeup

**Description**

Called from function [`tipc_sendmsg()`](#c-tipc_sendmsg), which has done all sanity checks

**Return**

the number of bytes sent on success, or errno

#### <a id="c-tipc_send_group_msg"></a>`tipc_send_group_msg()`

```c
int tipc_send_group_msg(struct net *net, struct tipc_sock *tsk, struct msghdr *m, struct tipc_member *mb, u32 dnode, u32 dport, int dlen)
```

send a message to a member in the group

**Parameters**

- `struct net *net`: network namespace
- `struct tipc_sock *tsk`: tipc socket
- `struct msghdr *m`: message to send
- `struct tipc_member *mb`: group member
- `u32 dnode`: destination node
- `u32 dport`: destination port
- `int dlen`: total length of message data

#### <a id="c-tipc_send_group_unicast"></a>`tipc_send_group_unicast()`

```c
int tipc_send_group_unicast(struct socket *sock, struct msghdr *m, int dlen, long timeout)
```

send message to a member in the group

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `int dlen`: total length of message data
- `long timeout`: timeout to wait for wakeup

**Description**

Called from function [`tipc_sendmsg()`](#c-tipc_sendmsg), which has done all sanity checks

**Return**

the number of bytes sent on success, or errno

#### <a id="c-tipc_send_group_anycast"></a>`tipc_send_group_anycast()`

```c
int tipc_send_group_anycast(struct socket *sock, struct msghdr *m, int dlen, long timeout)
```

send message to any member with given identity

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `int dlen`: total length of message data
- `long timeout`: timeout to wait for wakeup

**Description**

Called from function [`tipc_sendmsg()`](#c-tipc_sendmsg), which has done all sanity checks

**Return**

the number of bytes sent on success, or errno

#### <a id="c-tipc_send_group_bcast"></a>`tipc_send_group_bcast()`

```c
int tipc_send_group_bcast(struct socket *sock, struct msghdr *m, int dlen, long timeout)
```

send message to all members in communication group

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `int dlen`: total length of message data
- `long timeout`: timeout to wait for wakeup

**Description**

Called from function [`tipc_sendmsg()`](#c-tipc_sendmsg), which has done all sanity checks

**Return**

the number of bytes sent on success, or errno

#### <a id="c-tipc_send_group_mcast"></a>`tipc_send_group_mcast()`

```c
int tipc_send_group_mcast(struct socket *sock, struct msghdr *m, int dlen, long timeout)
```

send message to all members with given identity

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `int dlen`: total length of message data
- `long timeout`: timeout to wait for wakeup

**Description**

Called from function [`tipc_sendmsg()`](#c-tipc_sendmsg), which has done all sanity checks

**Return**

the number of bytes sent on success, or errno

#### <a id="c-tipc_sk_mcast_rcv"></a>`tipc_sk_mcast_rcv()`

```c
void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq, struct sk_buff_head *inputq)
```

Deliver multicast messages to all destination sockets

**Parameters**

- `struct net *net`: the associated network namespace
- `struct sk_buff_head *arrvq`: queue with arriving messages, to be cloned after destination lookup
- `struct sk_buff_head *inputq`: queue with cloned messages, delivered to socket after dest lookup

**Description**

Multi-threaded: parallel calls with reference to same queues may occur

#### <a id="c-tipc_sk_conn_proto_rcv"></a>`tipc_sk_conn_proto_rcv()`

```c
void tipc_sk_conn_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb, struct sk_buff_head *inputq, struct sk_buff_head *xmitq)
```

receive a connection mng protocol message

**Parameters**

- `struct tipc_sock *tsk`: receiving socket
- `struct sk_buff *skb`: pointer to message buffer.
- `struct sk_buff_head *inputq`: buffer list containing the buffers
- `struct sk_buff_head *xmitq`: output message area

#### <a id="c-tipc_sendmsg"></a>`tipc_sendmsg()`

```c
int tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz)
```

send message in connectionless manner

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `size_t dsz`: amount of user data to be sent

**Description**

Message must have an destination specified explicitly.
Used for SOCK_RDM and SOCK_DGRAM messages,
and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
(Note: 'SYN+' is prohibited on SOCK_STREAM.)

**Return**

the number of bytes sent on success, or errno otherwise

#### <a id="c-tipc_sendstream"></a>`tipc_sendstream()`

```c
int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
```

send stream-oriented data

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: data to send
- `size_t dsz`: total length of data to be transmitted

**Description**

Used for SOCK_STREAM data.

**Return**

the number of bytes sent on success (or partial success),
or errno if no data sent

#### <a id="c-tipc_send_packet"></a>`tipc_send_packet()`

```c
int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
```

send a connection-oriented message

**Parameters**

- `struct socket *sock`: socket structure
- `struct msghdr *m`: message to send
- `size_t dsz`: length of data to be transmitted

**Description**

Used for SOCK_SEQPACKET messages.

**Return**

the number of bytes sent on success, or errno otherwise

#### <a id="c-tipc_sk_set_orig_addr"></a>`tipc_sk_set_orig_addr()`

```c
void tipc_sk_set_orig_addr(struct msghdr *m, struct sk_buff *skb)
```

capture sender's address for received message

**Parameters**

- `struct msghdr *m`: descriptor for message info
- `struct sk_buff *skb`: received message

**Note**

Address is not captured if not requested by receiver.

#### <a id="c-tipc_sk_anc_data_recv"></a>`tipc_sk_anc_data_recv()`

```c
int tipc_sk_anc_data_recv(struct msghdr *m, struct sk_buff *skb, struct tipc_sock *tsk)
```

optionally capture ancillary data for received message

**Parameters**

- `struct msghdr *m`: descriptor for message info
- `struct sk_buff *skb`: received message buffer
- `struct tipc_sock *tsk`: TIPC port associated with message

**Note**

Ancillary data is not captured if not requested by receiver.

**Return**

0 if successful, otherwise errno

#### <a id="c-tipc_recvmsg"></a>`tipc_recvmsg()`

```c
int tipc_recvmsg(struct socket *sock, struct msghdr *m, size_t buflen, int flags)
```

receive packet-oriented message

**Parameters**

- `struct socket *sock`: network socket
- `struct msghdr *m`: descriptor for message info
- `size_t buflen`: length of user buffer area
- `int flags`: receive flags

**Description**

Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
If the complete message doesn't fit in user area, truncate it.

**Return**

size of returned message data, errno otherwise

#### <a id="c-tipc_recvstream"></a>`tipc_recvstream()`

```c
int tipc_recvstream(struct socket *sock, struct msghdr *m, size_t buflen, int flags)
```

receive stream-oriented data

**Parameters**

- `struct socket *sock`: network socket
- `struct msghdr *m`: descriptor for message info
- `size_t buflen`: total size of user buffer area
- `int flags`: receive flags

**Description**

Used for SOCK_STREAM messages only.  If not enough data is available
will optionally wait for more; never truncates data.

**Return**

size of returned message data, errno otherwise

#### <a id="c-tipc_write_space"></a>`tipc_write_space()`

```c
void tipc_write_space(struct sock *sk)
```

wake up thread if port congestion is released

**Parameters**

- `struct sock *sk`: socket

#### <a id="c-tipc_data_ready"></a>`tipc_data_ready()`

```c
void tipc_data_ready(struct sock *sk)
```

wake up threads to indicate messages have been received

**Parameters**

- `struct sock *sk`: socket

#### <a id="c-tipc_sk_filter_connect"></a>`tipc_sk_filter_connect()`

```c
bool tipc_sk_filter_connect(struct tipc_sock *tsk, struct sk_buff *skb, struct sk_buff_head *xmitq)
```

check incoming message for a connection-based socket

**Parameters**

- `struct tipc_sock *tsk`: TIPC socket
- `struct sk_buff *skb`: pointer to message buffer.
- `struct sk_buff_head *xmitq`: for Nagle ACK if any

**Return**

true if message should be added to receive queue, false otherwise

#### <a id="c-rcvbuf_limit"></a>`rcvbuf_limit()`

```c
unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
```

get proper overload limit of socket receive queue

**Parameters**

- `struct sock *sk`: socket
- `struct sk_buff *skb`: message

**Description**

For connection oriented messages, irrespective of importance,
default queue limit is 2 MB.

For connectionless messages, queue limits are based on message
importance as follows:

TIPC_LOW_IMPORTANCE       (2 MB)
TIPC_MEDIUM_IMPORTANCE    (4 MB)
TIPC_HIGH_IMPORTANCE      (8 MB)
TIPC_CRITICAL_IMPORTANCE  (16 MB)

**Return**

overload limit according to corresponding message importance

#### <a id="c-tipc_sk_filter_rcv"></a>`tipc_sk_filter_rcv()`

```c
void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *xmitq)
```

validate incoming message

**Parameters**

- `struct sock *sk`: socket
- `struct sk_buff *skb`: pointer to message.
- `struct sk_buff_head *xmitq`: output message area (FIXME)

**Description**

Enqueues message on receive queue if acceptable; optionally handles
disconnect indication for a connected socket.

Called with socket lock already taken

#### <a id="c-tipc_sk_backlog_rcv"></a>`tipc_sk_backlog_rcv()`

```c
int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
```

handle incoming message from backlog queue

**Parameters**

- `struct sock *sk`: socket
- `struct sk_buff *skb`: message

**Description**

Caller must hold socket lock

#### <a id="c-tipc_sk_enqueue"></a>`tipc_sk_enqueue()`

```c
void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk, u32 dport, struct sk_buff_head *xmitq)
```

extract all buffers with destination 'dport' from inputq and try adding them to socket or backlog queue

**Parameters**

- `struct sk_buff_head *inputq`: list of incoming buffers with potentially different destinations
- `struct sock *sk`: socket where the buffers should be enqueued
- `u32 dport`: port number for the socket
- `struct sk_buff_head *xmitq`: output queue

**Description**

Caller must hold socket lock

#### <a id="c-tipc_sk_rcv"></a>`tipc_sk_rcv()`

```c
void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
```

handle a chain of incoming buffers

**Parameters**

- `struct net *net`: the associated network namespace
- `struct sk_buff_head *inputq`: buffer list containing the buffers
  Consumes all buffers in list until inputq is empty

**Note**

may be called in multiple threads referring to the same queue

#### <a id="c-tipc_connect"></a>`tipc_connect()`

```c
int tipc_connect(struct socket *sock, struct sockaddr_unsized *dest, int destlen, int flags)
```

establish a connection to another TIPC port

**Parameters**

- `struct socket *sock`: socket structure
- `struct sockaddr_unsized *dest`: socket address for destination port
- `int destlen`: size of socket address data structure
- `int flags`: file-related flags associated with socket

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_listen"></a>`tipc_listen()`

```c
int tipc_listen(struct socket *sock, int len)
```

allow socket to listen for incoming connections

**Parameters**

- `struct socket *sock`: socket structure
- `int len`: (unused)

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_accept"></a>`tipc_accept()`

```c
int tipc_accept(struct socket *sock, struct socket *new_sock, struct proto_accept_arg *arg)
```

wait for connection request

**Parameters**

- `struct socket *sock`: listening socket
- `struct socket *new_sock`: new socket that is to be connected
- `struct proto_accept_arg *arg`: arguments for accept

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_shutdown"></a>`tipc_shutdown()`

```c
int tipc_shutdown(struct socket *sock, int how)
```

shutdown socket connection

**Parameters**

- `struct socket *sock`: socket structure
- `int how`: direction to close (must be SHUT_RDWR)

**Description**

Terminates connection (if necessary), then purges socket's receive queue.

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_setsockopt"></a>`tipc_setsockopt()`

```c
int tipc_setsockopt(struct socket *sock, int lvl, int opt, sockptr_t ov, unsigned int ol)
```

set socket option

**Parameters**

- `struct socket *sock`: socket structure
- `int lvl`: option level
- `int opt`: option identifier
- `sockptr_t ov`: pointer to new option value
- `unsigned int ol`: length of option value

**Description**

For stream sockets only, accepts and ignores all IPPROTO_TCP options
(to ease compatibility).

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_getsockopt"></a>`tipc_getsockopt()`

```c
int tipc_getsockopt(struct socket *sock, int lvl, int opt, char __user *ov, int __user *ol)
```

get socket option

**Parameters**

- `struct socket *sock`: socket structure
- `int lvl`: option level
- `int opt`: option identifier
- `char __user *ov`: receptacle for option value
- `int __user *ol`: receptacle for length of option value

**Description**

For stream sockets only, returns 0 length result for all IPPROTO_TCP options
(to ease compatibility).

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_socket_init"></a>`tipc_socket_init()`

```c
int tipc_socket_init(void)
```

initialize TIPC socket interface

**Parameters**

- `void`: no arguments

**Return**

0 on success, errno otherwise

#### <a id="c-tipc_socket_stop"></a>`tipc_socket_stop()`

```c
void tipc_socket_stop(void)
```

stop TIPC socket interface

**Parameters**

- `void`: no arguments

#### <a id="c-tipc_sk_filtering"></a>`tipc_sk_filtering()`

```c
bool tipc_sk_filtering(struct sock *sk)
```

check if a socket should be traced

**Parameters**

- `struct sock *sk`: the socket to be examined

**Description**

**sysctl_tipc_sk_filter** is used as the socket tuple for filtering:
(portid, sock type, name type, name lower, name upper)

**Return**

true if the socket meets the socket tuple data
(value 0 = 'any') or when there is no tuple set (all = 0),
otherwise false

#### <a id="c-tipc_sk_overlimit1"></a>`tipc_sk_overlimit1()`

```c
bool tipc_sk_overlimit1(struct sock *sk, struct sk_buff *skb)
```

check if socket rx queue is about to be overloaded, both the rcv and backlog queues are considered

**Parameters**

- `struct sock *sk`: tipc sk to be checked
- `struct sk_buff *skb`: tipc msg to be checked

**Return**

true if the socket rx queue allocation is > 90%, otherwise false

#### <a id="c-tipc_sk_overlimit2"></a>`tipc_sk_overlimit2()`

```c
bool tipc_sk_overlimit2(struct sock *sk, struct sk_buff *skb)
```

check if socket rx queue is about to be overloaded, only the rcv queue is considered

**Parameters**

- `struct sock *sk`: tipc sk to be checked
- `struct sk_buff *skb`: tipc msg to be checked

**Return**

true if the socket rx queue allocation is > 90%, otherwise false

#### <a id="c-tipc_sk_dump"></a>`tipc_sk_dump()`

```c
int tipc_sk_dump(struct sock *sk, u16 dqueues, char *buf)
```

dump TIPC socket

**Parameters**

- `struct sock *sk`: tipc sk to be dumped
- `u16 dqueues`: bitmask to decide if any socket queue to be dumped?
  - TIPC_DUMP_NONE: don't dump socket queues
  - TIPC_DUMP_SK_SNDQ: dump socket send queue
  - TIPC_DUMP_SK_RCVQ: dump socket rcv queue
  - TIPC_DUMP_SK_BKLGQ: dump socket backlog queue
  - TIPC_DUMP_ALL: dump all the socket queues above
- `char *buf`: returned buffer of dump data in format


<a id="rst-tipc-network-topology-interfaces"></a>

### TIPC Network Topology Interfaces


#### <a id="c-tipc_sub_check_overlap"></a>`tipc_sub_check_overlap()`

```c
bool tipc_sub_check_overlap(struct tipc_service_range *subscribed, struct tipc_service_range *found)
```

test for subscription overlap with the given values

**Parameters**

- `struct tipc_service_range *subscribed`: the service range subscribed for
- `struct tipc_service_range *found`: the service range we are checking for match

**Description**

Returns true if there is overlap, otherwise false.


<a id="rst-tipc-server-interfaces"></a>

### TIPC Server Interfaces


#### <a id="c-struct-tipc_topsrv"></a>`struct tipc_topsrv`

TIPC server structure

**Definition**

```c
struct tipc_topsrv {
    struct idr conn_idr;
    spinlock_t idr_lock;
    int idr_in_use;
    struct net *net;
    struct work_struct awork;
    struct workqueue_struct *rcv_wq;
    struct workqueue_struct *send_wq;
    struct socket *listener;
    char name[TIPC_SERVER_NAME_LEN];
};
```

**Members**

- `conn_idr`: identifier set of connection
- `idr_lock`: protect the connection identifier set
- `idr_in_use`: amount of allocated identifier entry
- `net`: network namespace instance
- `awork`: accept work item
- `rcv_wq`: receive workqueue
- `send_wq`: send workqueue
- `listener`: topsrv listener socket
- `name`: server name

#### <a id="c-struct-tipc_conn"></a>`struct tipc_conn`

TIPC connection structure

**Definition**

```c
struct tipc_conn {
    struct kref kref;
    int conid;
    struct socket *sock;
    unsigned long flags;
    struct tipc_topsrv *server;
    struct list_head sub_list;
    spinlock_t sub_lock;
    struct work_struct rwork;
    struct list_head outqueue;
    spinlock_t outqueue_lock;
    struct work_struct swork;
};
```

**Members**

- `kref`: reference counter to connection object
- `conid`: connection identifier
- `sock`: socket handler associated with connection
- `flags`: indicates connection state
- `server`: pointer to connected server
- `sub_list`: list to all pertaining subscriptions
- `sub_lock`: lock protecting the subscription list
- `rwork`: receive work item
- `outqueue`: pointer to first outbound message in queue
- `outqueue_lock`: control access to the outqueue
- `swork`: send work item


<a id="rst-tipc-trace-interfaces"></a>

### TIPC Trace Interfaces


#### <a id="c-tipc_skb_dump"></a>`tipc_skb_dump()`

```c
int tipc_skb_dump(struct sk_buff *skb, bool more, char *buf)
```

dump TIPC skb data

**Parameters**

- `struct sk_buff *skb`: skb to be dumped
- `bool more`: dump more?
  - false: dump only tipc msg data
  - true: dump kernel-related skb data and tipc cb\[\] array as well
- `char *buf`: returned buffer of dump data in format

#### <a id="c-tipc_list_dump"></a>`tipc_list_dump()`

```c
int tipc_list_dump(struct sk_buff_head *list, bool more, char *buf)
```

dump TIPC skb list/queue

**Parameters**

- `struct sk_buff_head *list`: list of skbs to be dumped
- `bool more`: dump more?
  - false: dump only the head & tail skbs
  - true: dump the first & last 5 skbs
- `char *buf`: returned buffer of dump data in format

---

# In-Kernel TLS Handshake

_Peios Kernel / Internals / Networking_

> Transport Layer Security (TLS) is a Upper Layer Protocol (ULP) that runs over TCP. TLS provides end-to-end data integrity and confidentiality in addition to peer authentication.

<a id="rst-in-kernel-tls-handshake"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

Transport Layer Security (TLS) is a Upper Layer Protocol (ULP) that runs over TCP. TLS provides end-to-end data integrity and confidentiality in addition to peer authentication.

The kernel's kTLS implementation handles the TLS record subprotocol, but does not handle the TLS handshake subprotocol which is used to establish a TLS session. Kernel consumers can use the API described here to request TLS session establishment.

There are several possible ways to provide a handshake service in the kernel. The API described here is designed to hide the details of those implementations so that in-kernel TLS consumers do not need to be aware of how the handshake gets done.

<a id="rst-user-handshake-agent"></a>

## User handshake agent

As of this writing, there is no TLS handshake implementation in the Linux kernel. To provide a handshake service, a handshake agent (typically in user space) is started in each network namespace where a kernel consumer might require a TLS handshake. Handshake agents listen for events sent from the kernel that indicate a handshake request is waiting.

An open socket is passed to a handshake agent via a netlink operation, which creates a socket descriptor in the agent's file descriptor table. If the handshake completes successfully, the handshake agent promotes the socket to use the TLS ULP and sets the session information using the SOL_TLS socket options. The handshake agent returns the socket to the kernel via a second netlink operation.

<a id="rst-kernel-handshake-api"></a>

## Kernel Handshake API

A kernel TLS consumer initiates a client-side TLS handshake on an open socket by invoking one of the tls_client_hello() functions. First, it fills in a structure that contains the parameters of the request:



```c
struct tls_handshake_args {
      struct socket   *ta_sock;
      tls_done_func_t ta_done;
      void            *ta_data;
      const char      *ta_peername;
      unsigned int    ta_timeout_ms;
      key_serial_t    ta_keyring;
      key_serial_t    ta_my_cert;
      key_serial_t    ta_my_privkey;
      unsigned int    ta_num_peerids;
      key_serial_t    ta_my_peerids[5];
};
```

The @ta_sock field references an open and connected socket. The consumer must hold a reference on the socket to prevent it from being destroyed while the handshake is in progress. The consumer must also have instantiated a struct file in sock-&gt;file.

@ta_done contains a callback function that is invoked when the handshake has completed. Further explanation of this function is in the "Handshake Completion" sesction below.

The consumer can provide a NUL-terminated hostname in the @ta_peername field that is sent as part of ClientHello. If no peername is provided, the DNS hostname associated with the server's IP address is used instead.

The consumer can fill in the @ta_timeout_ms field to force the servicing handshake agent to exit after a number of milliseconds. This enables the socket to be fully closed once both the kernel and the handshake agent have closed their endpoints.

Authentication material such as x.509 certificates, private certificate keys, and pre-shared keys are provided to the handshake agent in keys that are instantiated by the consumer before making the handshake request. The consumer can provide a private keyring that is linked into the handshake agent's process keyring in the @ta_keyring field to prevent access of those keys by other subsystems.

To request an x.509-authenticated TLS session, the consumer fills in the @ta_my_cert and @ta_my_privkey fields with the serial numbers of keys containing an x.509 certificate and the private key for that certificate. Then, it invokes this function:



```c
ret = tls_client_hello_x509(args, gfp_flags);
```

The function returns zero when the handshake request is under way. A zero return guarantees the callback function @ta_done will be invoked for this socket. The function returns a negative errno if the handshake could not be started. A negative errno guarantees the callback function @ta_done will not be invoked on this socket.

To initiate a client-side TLS handshake with a pre-shared key, use:



```c
ret = tls_client_hello_psk(args, gfp_flags);
```

However, in this case, the consumer fills in the @ta_my_peerids array with serial numbers of keys containing the peer identities it wishes to offer, and the @ta_num_peerids field with the number of array entries it has filled in. The other fields are filled in as above.

To initiate an anonymous client-side TLS handshake use:



```c
ret = tls_client_hello_anon(args, gfp_flags);
```

The handshake agent presents no peer identity information to the remote during this type of handshake. Only server authentication (ie the client verifies the server's identity) is performed during the handshake. Thus the established session uses encryption only.

Consumers that are in-kernel servers use:



```c
ret = tls_server_hello_x509(args, gfp_flags);
```

or



```c
ret = tls_server_hello_psk(args, gfp_flags);
```

The argument structure is filled in as above.

If the consumer needs to cancel the handshake request, say, due to a ^C or other exigent event, the consumer can invoke:



```c
bool tls_handshake_cancel(sock);
```

This function returns true if the handshake request associated with @sock has been canceled. The consumer's handshake completion callback will not be invoked. If this function returns false, then the consumer's completion callback has already been invoked.

<a id="rst-handshake-completion"></a>

## Handshake Completion

When the handshake agent has completed processing, it notifies the kernel that the socket may be used by the consumer again. At this point, the consumer's handshake completion callback, provided in the @ta_done field in the tls_handshake_args structure, is invoked.

The synopsis of this function is:



```c
typedef void  (*tls_done_func_t)(void *data, int status,
                                 key_serial_t peerid);
```

The consumer provides a cookie in the @ta_data field of the tls_handshake_args structure that is returned in the @data parameter of this callback. The consumer uses the cookie to match the callback to the thread waiting for the handshake to complete.

The success status of the handshake is returned via the @status parameter:


<table>
<thead>
<tr>
<th>


status

</th>
<th>


meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


TLS session established successfully

</td>
</tr>
<tr>
<td>


-EACCESS

</td>
<td>


Remote peer rejected the handshake or authentication failed

</td>
</tr>
<tr>
<td>


-ENOMEM

</td>
<td>


Temporary resource allocation failure

</td>
</tr>
<tr>
<td>


-EINVAL

</td>
<td>


Consumer provided an invalid argument

</td>
</tr>
<tr>
<td>


-ENOKEY

</td>
<td>


Missing authentication material

</td>
</tr>
<tr>
<td>


-EIO

</td>
<td>


An unexpected fault occurred

</td>
</tr>
</tbody>
</table>

The @peerid parameter contains the serial number of a key containing the remote peer's identity or the value TLS_NO_PEERID if the session is not authenticated.

A best practice is to close and destroy the socket immediately if the handshake failed.

<a id="rst-other-considerations"></a>

### Other considerations

While a handshake is under way, the kernel consumer must alter the socket's sk_data_ready callback function to ignore all incoming data. Once the handshake completion callback function has been invoked, normal receive operation can be resumed.

Once a TLS session is established, the consumer must provide a buffer for and then examine the control message (CMSG) that is part of every subsequent sock_recvmsg(). Each control message indicates whether the received message data is TLS record data or session metadata.

See [tls.rst](/kernel/internals/networking/tls.md) for details on how a kTLS consumer recognizes incoming (decrypted) application data, alerts, and handshake packets once the socket has been promoted to use the TLS ULP.

---

# Kernel TLS offload

_Peios Kernel / Internals / Networking_

> Linux kernel provides TLS connection offload infrastructure. Once a TCP connection is in ESTABLISHED state user space can enable the TLS Upper Layer Protocol (ULP) and install the cryptographic connection state. For details regarding the…

<a id="rst-kernel-tls-offload"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

<a id="rst-kernel-tls-operation"></a>

## Kernel TLS operation

Linux kernel provides TLS connection offload infrastructure. Once a TCP connection is in `ESTABLISHED` state user space can enable the TLS Upper Layer Protocol (ULP) and install the cryptographic connection state. For details regarding the user-facing interface refer to the TLS documentation in [Documentation/networking/tls.rst](</kernel/internals/networking/tls.md#rst-kernel-tls>).

`ktls` can operate in three modes:

> - Software crypto mode (`TLS_SW`) - CPU handles the cryptography. In most basic cases only crypto operations synchronous with the CPU can be used, but depending on calling context CPU may utilize asynchronous crypto accelerators. The use of accelerators introduces extra latency on socket reads (decryption only starts when a read syscall is made) and additional I/O load on the system.
>
> - Packet-based NIC offload mode (`TLS_HW`) - the NIC handles crypto on a packet by packet basis, provided the packets arrive in order. This mode integrates best with the kernel stack and is described in detail in the remaining part of this document (`ethtool` flags `tls-hw-tx-offload` and `tls-hw-rx-offload`).
>
> - Full TCP NIC offload mode (`TLS_HW_RECORD`) - mode of operation where NIC driver and firmware replace the kernel networking stack with its own TCP handling, it is not usable in production environments making use of the Linux networking stack for example any firewalling abilities or QoS and packet scheduling (`ethtool` flag `tls-hw-record`).

The operation mode is selected automatically based on device configuration, offload opt-in or opt-out on per-connection basis is not currently supported.

<a id="rst-tx"></a>

### TX

At a high level user write requests are turned into a scatter list, the TLS ULP intercepts them, inserts record framing, performs encryption (in `TLS_SW` mode) and then hands the modified scatter list to the TCP layer. From this point on the TCP stack proceeds as normal.

In `TLS_HW` mode the encryption is not performed in the TLS ULP. Instead packets reach a device driver, the driver will mark the packets for crypto offload based on the socket the packet is attached to, and send them to the device for encryption and transmission.

<a id="rst-rx"></a>

### RX

On the receive side, if the device handled decryption and authentication successfully, the driver will set the decrypted bit in the associated `struct sk_buff <sk_buff>`. The packets reach the TCP stack and are handled normally. `ktls` is informed when data is queued to the socket and the `strparser` mechanism is used to delineate the records. Upon read request, records are retrieved from the socket and passed to decryption routine. If device decrypted all the segments of the record the decryption is skipped, otherwise software path handles decryption.

![TLS offload layers](/kernel/internals/networking/asset-81ee943a514e-tls-offload-layers.svg)

Layers of Kernel TLS stack

<a id="rst-device-configuration"></a>

## Device configuration

During driver initialization device sets the `NETIF_F_HW_TLS_RX` and `NETIF_F_HW_TLS_TX` features and installs its `struct tlsdev_ops <tlsdev_ops>` pointer in the `tlsdev_ops` member of the `struct net_device <net_device>`.

When TLS cryptographic connection state is installed on a `ktls` socket (note that it is done twice, once for RX and once for TX direction, and the two are completely independent), the kernel checks if the underlying network device is offload-capable and attempts the offload. In case offload fails the connection is handled entirely in software using the same mechanism as if the offload was never tried.

Offload request is performed via the `tls_dev_add` callback of `struct tlsdev_ops <tlsdev_ops>`:



```c
int (*tls_dev_add)(struct net_device *netdev, struct sock *sk,
                   enum tls_offload_ctx_dir direction,
                   struct tls_crypto_info *crypto_info,
                   u32 start_offload_tcp_sn);
```

`direction` indicates whether the cryptographic information is for the received or transmitted packets. Driver uses the `sk` parameter to retrieve the connection 5-tuple and socket family (IPv4 vs IPv6). Cryptographic information in `crypto_info` includes the key, iv, salt as well as TLS record sequence number. `start_offload_tcp_sn` indicates which TCP sequence number corresponds to the beginning of the record with sequence number from `crypto_info`. The driver can add its state at the end of kernel structures (see `driver_state` members in `include/net/tls.h`) to avoid additional allocations and pointer dereferences.

<a id="rst-tx-1"></a>

### TX

After TX state is installed, the stack guarantees that the first segment of the stream will start exactly at the `start_offload_tcp_sn` sequence number, simplifying TCP sequence number matching.

TX offload being fully initialized does not imply that all segments passing through the driver and which belong to the offloaded socket will be after the expected sequence number and will have kernel record information. In particular, already encrypted data may have been queued to the socket before installing the connection state in the kernel.

<a id="rst-rx-1"></a>

### RX

In the RX direction, the local networking stack has little control over segmentation, so the initial records' TCP sequence number may be anywhere inside the segment.

<a id="rst-normal-operation"></a>

## Normal operation

At the minimum the device maintains the following state for each connection, in each direction:

> - crypto secrets (key, iv, salt)
>
> - crypto processing state (partial blocks, partial authentication tag, etc.)
>
> - record metadata (sequence number, processing offset and length)
>
> - expected TCP sequence number

There are no guarantees on record length or record segmentation. In particular segments may start at any point of a record and contain any number of records. Assuming segments are received in order, the device should be able to perform crypto operations and authentication regardless of segmentation. For this to be possible, the device has to keep a small amount of segment-to-segment state. This includes at least:

> - partial headers (if a segment carried only a part of the TLS header)
>
> - partial data block
>
> - partial authentication tag (all data had been seen but part of the authentication tag has to be written or read from the subsequent segment)

Record reassembly is not necessary for TLS offload. If the packets arrive in order the device should be able to handle them separately and make forward progress.

<a id="rst-tx-2"></a>

### TX

The kernel stack performs record framing reserving space for the authentication tag and populating all other TLS header and tailer fields.

Both the device and the driver maintain expected TCP sequence numbers due to the possibility of retransmissions and the lack of software fallback once the packet reaches the device. For segments passed in order, the driver marks the packets with a connection identifier (note that a 5-tuple lookup is insufficient to identify packets requiring HW offload, see the [5-tuple matching limitations](<#rst-tuple-problems>) section) and hands them to the device. The device identifies the packet as requiring TLS handling and confirms the sequence number matches its expectation. The device performs encryption and authentication of the record data. It replaces the authentication tag and TCP checksum with correct values.

<a id="rst-rx-2"></a>

### RX

Before a packet is DMAed to the host (but after NIC's embedded switching and packet transformation functions) the device validates the Layer 4 checksum and performs a 5-tuple lookup to find any TLS connection the packet may belong to (technically a 4-tuple lookup is sufficient - IP addresses and TCP port numbers, as the protocol is always TCP). If the packet is matched to a connection, the device confirms if the TCP sequence number is the expected one and proceeds to TLS handling (record delineation, decryption, authentication for each record in the packet). The device leaves the record framing unmodified, the stack takes care of record decapsulation. Device indicates successful handling of TLS offload in the per-packet context (descriptor) passed to the host.

Upon reception of a TLS offloaded packet, the driver sets the `decrypted` mark in `struct sk_buff <sk_buff>` corresponding to the segment. Networking stack makes sure decrypted and non-decrypted segments do not get coalesced (e.g. by GRO or socket layer) and takes care of partial decryption.

<a id="rst-resync-handling"></a>

## Resync handling

In presence of packet drops or network packet reordering, the device may lose synchronization with the TLS stream, and require a resync with the kernel's TCP stack.

Note that resync is only attempted for connections which were successfully added to the device table and are in TLS_HW mode. For example, if the table was full when cryptographic state was installed in the kernel, such connection will never get offloaded. Therefore the resync request does not carry any cryptographic connection state.

<a id="rst-tx-3"></a>

### TX

Segments transmitted from an offloaded socket can get out of sync in similar ways to the receive side-retransmissions - local drops are possible, though network reorders are not. There are currently two mechanisms for dealing with out of order segments.

<a id="rst-crypto-state-rebuilding"></a>

#### Crypto state rebuilding

Whenever an out of order segment is transmitted the driver provides the device with enough information to perform cryptographic operations. This means most likely that the part of the record preceding the current segment has to be passed to the device as part of the packet context, together with its TCP sequence number and TLS record number. The device can then initialize its crypto state, process and discard the preceding data (to be able to insert the authentication tag) and move onto handling the actual packet.

In this mode depending on the implementation the driver can either ask for a continuation with the crypto state and the new sequence number (next expected segment is the one after the out of order one), or continue with the previous stream state - assuming that the out of order segment was just a retransmission. The former is simpler, and does not require retransmission detection therefore it is the recommended method until such time it is proven inefficient.

<a id="rst-next-record-sync"></a>

#### Next record sync

Whenever an out of order segment is detected the driver requests that the `ktls` software fallback code encrypt it. If the segment's sequence number is lower than expected the driver assumes retransmission and doesn't change device state. If the segment is in the future, it may imply a local drop, the driver asks the stack to sync the device to the next record state and falls back to software.

Resync request is indicated with:



```c
void tls_offload_tx_resync_request(struct sock *sk, u32 got_seq, u32 exp_seq)
```

Until resync is complete driver should not access its expected TCP sequence number (as it will be updated from a different context). Following helper should be used to test if resync is complete:



```c
bool tls_offload_tx_resync_pending(struct sock *sk)
```

Next time `ktls` pushes a record it will first send its TCP sequence number and TLS record number to the driver. Stack will also make sure that the new record will start on a segment boundary (like it does when the connection is initially added).

<a id="rst-rx-3"></a>

### RX

A small amount of RX reorder events may not require a full resynchronization. In particular the device should not lose synchronization when record boundary can be recovered:

![reorder of non-header segment](/kernel/internals/networking/asset-53e362248b21-tls-offload-reorder-good.svg)

Reorder of non-header segment

Green segments are successfully decrypted, blue ones are passed as received on wire, red stripes mark start of new records.

In above case segment 1 is received and decrypted successfully. Segment 2 was dropped so 3 arrives out of order. The device knows the next record starts inside 3, based on record length in segment 1. Segment 3 is passed untouched, because due to lack of data from segment 2 the remainder of the previous record inside segment 3 cannot be handled. The device can, however, collect the authentication algorithm's state and partial block from the new record in segment 3 and when 4 and 5 arrive continue decryption. Finally when 2 arrives it's completely outside of expected window of the device so it's passed as is without special handling. `ktls` software fallback handles the decryption of record spanning segments 1, 2 and 3. The device did not get out of sync, even though two segments did not get decrypted.

Kernel synchronization may be necessary if the lost segment contained a record header and arrived after the next record header has already passed:

![reorder of header segment](/kernel/internals/networking/asset-221178a04a31-tls-offload-reorder-bad.svg)

Reorder of segment with a TLS header

In this example segment 2 gets dropped, and it contains a record header. Device can only detect that segment 4 also contains a TLS header if it knows the length of the previous record from segment 2. In this case the device will lose synchronization with the stream.

<a id="rst-stream-scan-resynchronization"></a>

#### Stream scan resynchronization

When the device gets out of sync and the stream reaches TCP sequence numbers more than a max size record past the expected TCP sequence number, the device starts scanning for a known header pattern. For example for TLS 1.2 and TLS 1.3 subsequent bytes of value `0x03 0x03` occur in the SSL/TLS version field of the header. Once pattern is matched the device continues attempting parsing headers at expected locations (based on the length fields at guessed locations). Whenever the expected location does not contain a valid header the scan is restarted.

When the header is matched the device sends a confirmation request to the kernel, asking if the guessed location is correct (if a TLS record really starts there), and which record sequence number the given header had.

The asynchronous resync process is coordinated on the kernel side using struct tls_offload_resync_async, which tracks and manages the resync request.

Helper functions to manage struct tls_offload_resync_async:

`tls_offload_rx_resync_async_request_start()` Initializes an asynchronous resync attempt by specifying the sequence range to monitor and resetting internal state in the struct.

`tls_offload_rx_resync_async_request_end()` Retains the device's guessed TCP sequence number for comparison with current or future logged ones. It also clears the RESYNC_REQ_ASYNC flag from the resync request, indicating that the device has submitted its guessed sequence number.

`tls_offload_rx_resync_async_request_cancel()` Cancels any in-progress resync attempt, clearing the request state.

When the kernel processes an RX segment that begins a new TLS record, it examines the current status of the asynchronous resynchronization request.

If the device is still waiting to provide its guessed TCP sequence number (the async state), the kernel records the sequence number of this segment so that it can later be compared once the device's guess becomes available.

If the device has already submitted its guessed sequence number (the non-async state), the kernel now tries to match that guess against the sequence numbers of all TLS record headers that have been logged since the resync request started.

The kernel confirms the guessed location was correct and tells the device the record sequence number. Meanwhile, the device had been parsing and counting all records since the just-confirmed one, it adds the number of records it had seen to the record number provided by the kernel. At this point the device is in sync and can resume decryption at next segment boundary.

In a pathological case the device may latch onto a sequence of matching headers and never hear back from the kernel (there is no negative confirmation from the kernel). The implementation may choose to periodically restart scan. Given how unlikely falsely-matching stream is, however, periodic restart is not deemed necessary.

Special care has to be taken if the confirmation request is passed asynchronously to the packet stream and record may get processed by the kernel before the confirmation request.

<a id="rst-stack-driven-resynchronization"></a>

#### Stack-driven resynchronization

The driver may also request the stack to perform resynchronization whenever it sees the records are no longer getting decrypted. If the connection is configured in this mode the stack automatically schedules resynchronization after it has received two completely encrypted records.

The stack waits for the socket to drain and informs the device about the next expected record number and its TCP sequence number. If the records continue to be received fully encrypted stack retries the synchronization with an exponential back off (first after 2 encrypted records, then after 4 records, after 8, after 16... up until every 128 records).

<a id="rst-error-handling"></a>

## Error handling

<a id="rst-tx-4"></a>

### TX

Packets may be redirected or rerouted by the stack to a different device than the selected TLS offload device. The stack will handle such condition using the `sk_validate_xmit_skb()` helper (TLS offload code installs `tls_validate_xmit_skb()` at this hook). Offload maintains information about all records until the data is fully acknowledged, so if skbs reach the wrong device they can be handled by software fallback.

Any device TLS offload handling error on the transmission side must result in the packet being dropped. For example if a packet got out of order due to a bug in the stack or the device, reached the device and can't be encrypted such packet must be dropped.

<a id="rst-rx-4"></a>

### RX

If the device encounters any problems with TLS offload on the receive side it should pass the packet to the host's networking stack as it was received on the wire.

For example authentication failure for any record in the segment should result in passing the unmodified packet to the software fallback. This means packets should not be modified "in place". Splitting segments to handle partial decryption is not advised. In other words either all records in the packet had been handled successfully and authenticated or the packet has to be passed to the host's stack as it was on the wire (recovering original packet in the driver if device provides precise error is sufficient).

The Linux networking stack does not provide a way of reporting per-packet decryption and authentication errors, packets with errors must simply not have the `decrypted` mark set.

A packet should also not be handled by the TLS offload if it contains incorrect checksums.

<a id="rst-performance-metrics"></a>

## Performance metrics

TLS offload can be characterized by the following basic metrics:

> - max connection count
>
> - connection installation rate
>
> - connection installation latency
>
> - total cryptographic performance

Note that each TCP connection requires a TLS session in both directions, the performance may be reported treating each direction separately.

<a id="rst-max-connection-count"></a>

### Max connection count

The number of connections device can support can be exposed via `devlink resource` API.

<a id="rst-total-cryptographic-performance"></a>

### Total cryptographic performance

Offload performance may depend on segment and record size.

Overload of the cryptographic subsystem of the device should not have significant performance impact on non-offloaded streams.

<a id="rst-statistics"></a>

## Statistics

Following minimum set of TLS-related statistics should be reported by the driver:

> - `rx_tls_decrypted_packets` - number of successfully decrypted RX packets which were part of a TLS stream.
>
> - `rx_tls_decrypted_bytes` - number of TLS payload bytes in RX packets which were successfully decrypted.
>
> - `rx_tls_ctx` - number of TLS RX HW offload contexts added to device for decryption.
>
> - `rx_tls_del` - number of TLS RX HW offload contexts deleted from device (connection has finished).
>
> - - **`rx_tls_resync_req_pkt` - number of received TLS packets with a resync**
>
>     request.
>
> - - **`rx_tls_resync_req_start` - number of times the TLS async resync request**
>
>     was started.
>
> - - **`rx_tls_resync_req_end` - number of times the TLS async resync request**
>
>     properly ended with providing the HW tracked tcp-seq.
>
> - - **`rx_tls_resync_req_skip` - number of times the TLS async resync request**
>
>     procedure was started but not properly ended.
>
> - - **`rx_tls_resync_res_ok` - number of times the TLS resync response call to**
>
>     the driver was successfully handled.
>
> - - **`rx_tls_resync_res_skip` - number of times the TLS resync response call to**
>
>     the driver was terminated unsuccessfully.
>
> - `rx_tls_err` - number of RX packets which were part of a TLS stream but were not decrypted due to unexpected error in the state machine.
>
> - `tx_tls_encrypted_packets` - number of TX packets passed to the device for encryption of their TLS payload.
>
> - `tx_tls_encrypted_bytes` - number of TLS payload bytes in TX packets passed to the device for encryption.
>
> - `tx_tls_ctx` - number of TLS TX HW offload contexts added to device for encryption.
>
> - `tx_tls_ooo` - number of TX packets which were part of a TLS stream but did not arrive in the expected order.
>
> - `tx_tls_skip_no_sync_data` - number of TX packets which were part of a TLS stream and arrived out-of-order, but skipped the HW offload routine and went to the regular transmit flow as they were retransmissions of the connection handshake.
>
> - `tx_tls_drop_no_sync_data` - number of TX packets which were part of a TLS stream dropped, because they arrived out of order and associated record could not be found.
>
> - `tx_tls_drop_bypass_req` - number of TX packets which were part of a TLS stream dropped, because they contain both data that has been encrypted by software and data that expects hardware crypto offload.

<a id="rst-notable-corner-cases-exceptions-and-additional-requirements"></a>

## Notable corner cases, exceptions and additional requirements

<a id="rst-tuple-matching-limitations"></a>
<a id="rst-tuple-problems"></a>

### 5-tuple matching limitations

The device can only recognize received packets based on the 5-tuple of the socket. Current `ktls` implementation will not offload sockets routed through software interfaces such as those used for tunneling or virtual networking. However, many packet transformations performed by the networking stack (most notably any BPF logic) do not require any intermediate software device, therefore a 5-tuple match may consistently miss at the device level. In such cases the device should still be able to perform TX offload (encryption) and should fallback cleanly to software decryption (RX).

<a id="rst-out-of-order"></a>

### Out of order

Introducing extra processing in NICs should not cause packets to be transmitted or received out of order, for example pure ACK packets should not be reordered with respect to data segments.

<a id="rst-ingress-reorder"></a>

### Ingress reorder

A device is permitted to perform packet reordering for consecutive TCP segments (i.e. placing packets in the correct order) but any form of additional buffering is disallowed.

<a id="rst-coexistence-with-standard-networking-offload-features"></a>

### Coexistence with standard networking offload features

Offloaded `ktls` sockets should support standard TCP stack features transparently. Enabling device TLS offload should not cause any difference in packets as seen on the wire.

<a id="rst-transport-layer-transparency"></a>

### Transport layer transparency

For the purpose of simplifying TLS offload, the device should not modify any packet headers.

The device should not depend on any packet headers beyond what is strictly necessary for TLS offload.

<a id="rst-segment-drops"></a>

### Segment drops

Dropping packets is acceptable only in the event of catastrophic system errors and should never be used as an error handling mechanism in cases arising from normal operation. In other words, reliance on TCP retransmissions to handle corner cases is not acceptable.

<a id="rst-tls-device-features"></a>

### TLS device features

Drivers should ignore the changes to the TLS device feature flags. These flags will be acted upon accordingly by the core `ktls` code. TLS device feature flags only control adding of new TLS connection offloads, old connections will remain active after flags are cleared.

TLS encryption cannot be offloaded to devices without checksum calculation offload. Hence, TLS TX device feature flag requires TX csum offload being set. Disabling the latter implies clearing the former. Disabling TX checksum offload should not affect old connections, and drivers should make sure checksum calculation does not break for them. Similarly, device-offloaded TLS decryption implies doing RXCSUM. If the user does not want to enable RX csum offload, TLS RX device feature is disabled as well.

---

# Kernel TLS

_Peios Kernel / Internals / Networking_

> Transport Layer Security (TLS) is a Upper Layer Protocol (ULP) that runs over TCP. TLS provides end-to-end data integrity and confidentiality.

<a id="rst-kernel-tls-1"></a>
<a id="rst-kernel-tls"></a>

<a id="rst-overview"></a>

## Overview

Transport Layer Security (TLS) is a Upper Layer Protocol (ULP) that runs over TCP. TLS provides end-to-end data integrity and confidentiality.

<a id="rst-user-interface"></a>

## User interface

<a id="rst-creating-a-tls-connection"></a>

### Creating a TLS connection

First create a new TCP socket and once the connection is established set the TLS ULP.



```c
sock = socket(AF_INET, SOCK_STREAM, 0);
connect(sock, addr, addrlen);
setsockopt(sock, SOL_TCP, TCP_ULP, "tls", sizeof("tls"));
```

Setting the TLS ULP allows us to set/get TLS socket options. Currently only the symmetric encryption is handled in the kernel.  After the TLS handshake is complete, we have all the parameters required to move the data-path to the kernel. There is a separate socket option for moving the transmit and the receive into the kernel.



```c
/* From linux/tls.h */
struct tls_crypto_info {
        unsigned short version;
        unsigned short cipher_type;
};

struct tls12_crypto_info_aes_gcm_128 {
        struct tls_crypto_info info;
        unsigned char iv[TLS_CIPHER_AES_GCM_128_IV_SIZE];
        unsigned char key[TLS_CIPHER_AES_GCM_128_KEY_SIZE];
        unsigned char salt[TLS_CIPHER_AES_GCM_128_SALT_SIZE];
        unsigned char rec_seq[TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE];
};


struct tls12_crypto_info_aes_gcm_128 crypto_info;

crypto_info.info.version = TLS_1_2_VERSION;
crypto_info.info.cipher_type = TLS_CIPHER_AES_GCM_128;
memcpy(crypto_info.iv, iv_write, TLS_CIPHER_AES_GCM_128_IV_SIZE);
memcpy(crypto_info.rec_seq, seq_number_write,
                                      TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE);
memcpy(crypto_info.key, cipher_key_write, TLS_CIPHER_AES_GCM_128_KEY_SIZE);
memcpy(crypto_info.salt, implicit_iv_write, TLS_CIPHER_AES_GCM_128_SALT_SIZE);

setsockopt(sock, SOL_TLS, TLS_TX, &crypto_info, sizeof(crypto_info));
```

Transmit and receive are set separately, but the setup is the same, using either TLS_TX or TLS_RX.

<a id="rst-sending-tls-application-data"></a>

### Sending TLS application data

After setting the TLS_TX socket option all application data sent over this socket is encrypted using TLS and the parameters provided in the socket option. For example, we can send an encrypted hello world record as follows:



```c
const char *msg = "hello world\n";
send(sock, msg, strlen(msg));
```

send() data is directly encrypted from the userspace buffer provided to the encrypted kernel send buffer if possible.

The sendfile system call will send the file's data over TLS records of maximum length (2^14).



```c
file = open(filename, O_RDONLY);
fstat(file, &stat);
sendfile(sock, file, &offset, stat.st_size);
```

TLS records are created and sent after each send() call, unless MSG_MORE is passed.  MSG_MORE will delay creation of a record until MSG_MORE is not passed, or the maximum record size is reached.

The kernel will need to allocate a buffer for the encrypted data. This buffer is allocated at the time send() is called, such that either the entire send() call will return -ENOMEM (or block waiting for memory), or the encryption will always succeed.  If send() returns -ENOMEM and some data was left on the socket buffer from a previous call using MSG_MORE, the MSG_MORE data is left on the socket buffer.

<a id="rst-receiving-tls-application-data"></a>

### Receiving TLS application data

After setting the TLS_RX socket option, all recv family socket calls are decrypted using TLS parameters provided.  A full TLS record must be received before decryption can happen.



```c
char buffer[16384];
recv(sock, buffer, 16384);
```

Received data is decrypted directly in to the user buffer if it is large enough, and no additional allocations occur.  If the userspace buffer is too small, data is decrypted in the kernel and copied to userspace.

`EINVAL` is returned if the TLS version in the received message does not match the version passed in setsockopt.

`EMSGSIZE` is returned if the received message is too big.

`EBADMSG` is returned if decryption failed for any other reason.

<a id="rst-send-tls-control-messages"></a>

### Send TLS control messages

Other than application data, TLS has control messages such as alert messages (record type 21) and handshake messages (record type 22), etc. These messages can be sent over the socket by providing the TLS record type via a CMSG. For example the following function sends @data of @length bytes using a record of type @record_type.



```c
/* send TLS control message using record_type */
static int klts_send_ctrl_message(int sock, unsigned char record_type,
                                  void *data, size_t length)
{
      struct msghdr msg = {0};
      int cmsg_len = sizeof(record_type);
      struct cmsghdr *cmsg;
      char buf[CMSG_SPACE(cmsg_len)];
      struct iovec msg_iov;   /* Vector of data to send/receive into.  */

      msg.msg_control = buf;
      msg.msg_controllen = sizeof(buf);
      cmsg = CMSG_FIRSTHDR(&msg);
      cmsg->cmsg_level = SOL_TLS;
      cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
      cmsg->cmsg_len = CMSG_LEN(cmsg_len);
      *CMSG_DATA(cmsg) = record_type;
      msg.msg_controllen = cmsg->cmsg_len;

      msg_iov.iov_base = data;
      msg_iov.iov_len = length;
      msg.msg_iov = &msg_iov;
      msg.msg_iovlen = 1;

      return sendmsg(sock, &msg, 0);
}
```

Control message data should be provided unencrypted, and will be encrypted by the kernel.

<a id="rst-receiving-tls-control-messages"></a>

### Receiving TLS control messages

TLS control messages are passed in the userspace buffer, with message type passed via cmsg.  If no cmsg buffer is provided, an error is returned if a control message is received.  Data messages may be received without a cmsg buffer set.



```c
char buffer[16384];
char cmsg[CMSG_SPACE(sizeof(unsigned char))];
struct msghdr msg = {0};
msg.msg_control = cmsg;
msg.msg_controllen = sizeof(cmsg);

struct iovec msg_iov;
msg_iov.iov_base = buffer;
msg_iov.iov_len = 16384;

msg.msg_iov = &msg_iov;
msg.msg_iovlen = 1;

int ret = recvmsg(sock, &msg, 0 /* flags */);

struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg->cmsg_level == SOL_TLS &&
    cmsg->cmsg_type == TLS_GET_RECORD_TYPE) {
    int record_type = *((unsigned char *)CMSG_DATA(cmsg));
    // Do something with record_type, and control message data in
    // buffer.
    //
    // Note that record_type may be == to application data (23).
} else {
    // Buffer contains application data.
}
```

recv will never return data from mixed types of TLS records.

<a id="rst-tls-1-3-key-updates"></a>

### TLS 1.3 Key Updates

In TLS 1.3, KeyUpdate handshake messages signal that the sender is updating its TX key. Any message sent after a KeyUpdate will be encrypted using the new key. The userspace library can pass the new key to the kernel using the TLS_TX and TLS_RX socket options, as for the initial keys. TLS version and cipher cannot be changed.

To prevent attempting to decrypt incoming records using the wrong key, decryption will be paused when a KeyUpdate message is received by the kernel, until the new key has been provided using the TLS_RX socket option. Any read occurring after the KeyUpdate has been read and before the new key is provided will fail with EKEYEXPIRED. poll() will not report any read events from the socket until the new key is provided. There is no pausing on the transmit side.

Userspace should make sure that the crypto_info provided has been set properly. In particular, the kernel will not check for key/nonce reuse.

The number of successful and failed key updates is tracked in the `TlsTxRekeyOk`, `TlsRxRekeyOk`, `TlsTxRekeyError`, `TlsRxRekeyError` statistics. The `TlsRxRekeyReceived` statistic counts KeyUpdate handshake messages that have been received.

<a id="rst-integrating-in-to-userspace-tls-library"></a>

### Integrating in to userspace TLS library

At a high level, the kernel TLS ULP is a replacement for the record layer of a userspace TLS library.

A patchset to OpenSSL to use ktls as the record layer is [here](<https://github.com/Mellanox/openssl/commits/tls_rx2>)<a id="rst-here"></a>.

[An example](<https://github.com/ktls/af_ktls-tool/commits/RX>)<a id="rst-an-example"></a> of calling send directly after a handshake using gnutls. Since it doesn't implement a full record layer, control messages are not supported.

<a id="rst-optional-optimizations"></a>

### Optional optimizations

There are certain condition-specific optimizations the TLS ULP can make, if requested. Those optimizations are either not universally beneficial or may impact correctness, hence they require an opt-in. All options are set per-socket using setsockopt(), and their state can be checked using getsockopt() and via socket diag (`ss`).

<a id="rst-tls-tx-zerocopy-ro"></a>

#### TLS_TX_ZEROCOPY_RO

For device offload only. Allow sendfile() data to be transmitted directly to the NIC without making an in-kernel copy. This allows true zero-copy behavior when device offload is enabled.

The application must make sure that the data is not modified between being submitted and transmission completing. In other words this is mostly applicable if the data sent on a socket via sendfile() is read-only.

Modifying the data may result in different versions of the data being used for the original TCP transmission and TCP retransmissions. To the receiver this will look like TLS records had been tampered with and will result in record authentication failures.

<a id="rst-tls-rx-expect-no-pad"></a>

#### TLS_RX_EXPECT_NO_PAD

TLS 1.3 only. Expect the sender to not pad records. This allows the data to be decrypted directly into user space buffers with TLS 1.3.

This optimization is safe to enable only if the remote end is trusted, otherwise it is an attack vector to doubling the TLS processing cost.

If the record decrypted turns out to had been padded or is not a data record it will be decrypted again into a kernel buffer without zero copy. Such events are counted in the `TlsDecryptRetry` statistic.

<a id="rst-tls-tx-max-payload-len"></a>

#### TLS_TX_MAX_PAYLOAD_LEN

Specifies the maximum size of the plaintext payload for transmitted TLS records.

When this option is set, the kernel enforces the specified limit on all outgoing TLS records. No plaintext fragment will exceed this size. This option can be used to implement the TLS Record Size Limit extension \[1\].

- For TLS 1.2, the value corresponds directly to the record size limit.

- For TLS 1.3, the value should be set to record_size_limit - 1, since the record size limit includes one additional byte for the ContentType field.

The valid range for this option is 64 to 16384 bytes for TLS 1.2, and 63 to 16384 bytes for TLS 1.3. The lower minimum for TLS 1.3 accounts for the extra byte used by the ContentType field.

\[1\] [https://datatracker.ietf.org/doc/html/rfc8449](<https://datatracker.ietf.org/doc/html/rfc8449>)

<a id="rst-statistics"></a>

## Statistics

TLS implementation exposes the following per-namespace statistics (`/proc/net/tls_stat`):

- `TlsCurrTxSw`, `TlsCurrRxSw` - number of TX and RX sessions currently installed where host handles cryptography

- `TlsCurrTxDevice`, `TlsCurrRxDevice` - number of TX and RX sessions currently installed where NIC handles cryptography

- `TlsTxSw`, `TlsRxSw` - number of TX and RX sessions opened with host cryptography

- `TlsTxDevice`, `TlsRxDevice` - number of TX and RX sessions opened with NIC cryptography

- `TlsDecryptError` - record decryption failed (e.g. due to incorrect authentication tag)

- `TlsDeviceRxResync` - number of RX resyncs sent to NICs handling cryptography

- `TlsDecryptRetry` - number of RX records which had to be re-decrypted due to `TLS_RX_EXPECT_NO_PAD` mis-prediction. Note that this counter will also increment for non-data records.

- `TlsRxNoPadViolation` - number of data RX records which had to be re-decrypted due to `TLS_RX_EXPECT_NO_PAD` mis-prediction.

- `TlsTxRekeyOk`, `TlsRxRekeyOk` - number of successful rekeys on existing sessions for TX and RX

- `TlsTxRekeyError`, `TlsRxRekeyError` - number of failed rekeys on existing sessions for TX and RX

- `TlsRxRekeyReceived` - number of received KeyUpdate handshake messages, requiring userspace to provide a new RX key

---

# Transparent proxy support

_Peios Kernel / Internals / Networking_

> This feature adds Linux 2.2-like transparent proxy support to current kernels. To use it, enable the socket match and the TPROXY target in your kernel config. You will need policy routing too, so be sure to enable that as well.

> **Peios:** This describes an upstream interface disabled in the configured Peios kernel. Peios uses NTFE; nftables/iptables, IPVS and flow-table configuration are not enabled policy paths. Retained schemas and reference text do not imply runtime availability. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-transparent-proxy-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This feature adds Linux 2.2-like transparent proxy support to current kernels. To use it, enable the socket match and the TPROXY target in your kernel config. You will need policy routing too, so be sure to enable that as well.

From Linux 4.18 transparent proxy support is also available in nf_tables.

<a id="rst-making-non-local-sockets-work"></a>

## 1. Making non-local sockets work

The idea is that you identify packets with destination address matching a local socket on your box, set the packet mark to a certain value:



```text
# iptables -t mangle -N DIVERT
# iptables -t mangle -A PREROUTING -p tcp -m socket --transparent -j DIVERT
# iptables -t mangle -A DIVERT -j MARK --set-mark 1
# iptables -t mangle -A DIVERT -j ACCEPT
```

Alternatively you can do this in nft with the following commands:



```text
# nft add table filter
# nft add chain filter divert "{ type filter hook prerouting priority -150; }"
# nft add rule filter divert meta l4proto tcp socket transparent 1 meta mark set 1 accept
```

And then match on that value using policy routing to have those packets delivered locally:



```text
# ip rule add fwmark 1 lookup 100
# ip route add local 0.0.0.0/0 dev lo table 100
```

Because of certain restrictions in the IPv4 routing output code you'll have to modify your application to allow it to send datagrams \_from\_ non-local IP addresses. All you have to do is enable the (SOL_IP, IP_TRANSPARENT) socket option before calling bind:



```text
fd = socket(AF_INET, SOCK_STREAM, 0);
/* - 8< -*/
int value = 1;
setsockopt(fd, SOL_IP, IP_TRANSPARENT, &value, sizeof(value));
/* - 8< -*/
name.sin_family = AF_INET;
name.sin_port = htons(0xCAFE);
name.sin_addr.s_addr = htonl(0xDEADBEEF);
bind(fd, &name, sizeof(name));
```

A trivial patch for netcat is available here: [http://people.netfilter.org/hidden/tproxy/netcat-ip_transparent-support.patch](<http://people.netfilter.org/hidden/tproxy/netcat-ip_transparent-support.patch>)

<a id="rst-redirecting-traffic"></a>

## 2. Redirecting traffic

Transparent proxying often involves "intercepting" traffic on a router. This is usually done with the iptables REDIRECT target; however, there are serious limitations of that method. One of the major issues is that it actually modifies the packets to change the destination address -- which might not be acceptable in certain situations. (Think of proxying UDP for example: you won't be able to find out the original destination address. Even in case of TCP getting the original destination address is racy.)

The 'TPROXY' target provides similar functionality without relying on NAT. Simply add rules like this to the iptables ruleset above:



```text
# iptables -t mangle -A PREROUTING -p tcp --dport 80 -j TPROXY \
  --tproxy-mark 0x1/0x1 --on-port 50080
```

Or the following rule to nft:



```text
# nft add rule filter divert tcp dport 80 tproxy to :50080 meta mark set 1 accept
```

Note that for this to work you'll have to modify the proxy to enable (SOL_IP, IP_TRANSPARENT) for the listening socket.

As an example implementation, tcprdr is available here: [https://git.breakpoint.cc/cgit/fw/tcprdr.git/](<https://git.breakpoint.cc/cgit/fw/tcprdr.git/>) This tool is written by Florian Westphal and it was used for testing during the nf_tables implementation.

<a id="rst-iptables-and-nf-tables-extensions"></a>

## 3. Iptables and nf_tables extensions

To use tproxy you'll need to have the following modules compiled for iptables:

> - NETFILTER_XT_MATCH_SOCKET
>
> - NETFILTER_XT_TARGET_TPROXY

Or the floowing modules for nf_tables:

> - NFT_SOCKET
>
> - NFT_TPROXY

<a id="rst-application-support"></a>

## 4. Application support

<a id="rst-squid"></a>

### 4.1. Squid

Squid 3.HEAD has support built-in. To use it, pass '--enable-linux-netfilter' to configure and set the 'tproxy' option on the HTTP listener you redirect traffic to with the TPROXY iptables target.

For more information please consult the following page on the Squid wiki: [http://wiki.squid-cache.org/Features/Tproxy4](<http://wiki.squid-cache.org/Features/Tproxy4>)

---

# Universal TUN/TAP device driver

_Peios Kernel / Internals / Networking_

> Copyright © 1999-2000 Maxim Krasnyansky <max_mk@yahoo.com>

> **Peios:** The device needs native access authorization; `chmod 666 /dev/net/tun` alone does not grant it. `CAP_NET_ADMIN` maps to enabled `SeTcbPrivilege`. Existing driver ownership and network-namespace checks remain additional constraints. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-universal-tun-tap-device-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © 1999-2000 Maxim Krasnyansky &lt;[max_mk@yahoo.com](<mailto:max_mk@yahoo.com>)&gt;

> Linux, Solaris drivers Copyright © 1999-2000 Maxim Krasnyansky &lt;[max_mk@yahoo.com](<mailto:max_mk@yahoo.com>)&gt;
>
> FreeBSD TAP driver Copyright © 1999-2000 Maksim Yevmenkin &lt;[m_evmenkin@yahoo.com](<mailto:m_evmenkin@yahoo.com>)&gt;
>
> Revision of this document 2002 by Florian Thiel &lt;[florian.thiel@gmx.net](<mailto:florian.thiel@gmx.net>)&gt;

<a id="rst-description"></a>

## 1. Description

> TUN/TAP provides packet reception and transmission for user space programs. It can be seen as a simple Point-to-Point or Ethernet device, which, instead of receiving packets from physical media, receives them from user space program and instead of sending packets via physical media writes them to the user space program.
>
> In order to use the driver a program has to open /dev/net/tun and issue a corresponding ioctl() to register a network device with the kernel. A network device will appear as tunXX or tapXX, depending on the options chosen. When the program closes the file descriptor, the network device and all corresponding routes will disappear.
>
> Depending on the type of device chosen the userspace program has to read/write IP packets (with tun) or ethernet frames (with tap). Which one is being used depends on the flags given with the ioctl().
>
> The package from [http://vtun.sourceforge.net/tun](<http://vtun.sourceforge.net/tun>) contains two simple examples for how to use tun and tap devices. Both programs work like a bridge between two network interfaces. br_select.c - bridge based on select system call. br_sigio.c  - bridge based on async io and SIGIO signal. However, the best example is VTun [http://vtun.sourceforge.net](<http://vtun.sourceforge.net>) :))

<a id="rst-configuration"></a>

## 2. Configuration

> Create device node:
>
>
>
> ```text
> mkdir /dev/net (if it doesn't exist already)
> mknod /dev/net/tun c 10 200
> ```
>
> Set permissions:
>
>
>
> ```text
> e.g. chmod 0666 /dev/net/tun
> ```
>
> There's no harm in allowing the device to be accessible by non-root users, since CAP_NET_ADMIN is required for creating network devices or for connecting to network devices which aren't owned by the user in question. If you want to create persistent devices and give ownership of them to unprivileged users, then you need the /dev/net/tun device to be usable by those users.
>
> Driver module autoloading
>
> > Make sure that "Kernel module loader" - module auto-loading support is enabled in your kernel.  The kernel should load it on first access.
>
> Manual loading
>
> > insert the module by hand:
> >
> >
> >
> > ```text
> > modprobe tun
> > ```
>
> If you do it the latter way, you have to load the module every time you need it, if you do it the other way it will be automatically loaded when /dev/net/tun is being opened.

<a id="rst-program-interface"></a>

## 3. Program interface

<a id="rst-network-device-allocation"></a>

### 3.1 Network device allocation

`char *dev` should be the name of the device with a format string (e.g. "tun%d"), but (as far as I can see) this can be any valid network device name. Note that the character pointer becomes overwritten with the real device name (e.g. "tun0"):



```text
#include <linux/if.h>
#include <linux/if_tun.h>

int tun_alloc(char *dev)
{
    struct ifreq ifr;
    int fd, err;

    if( (fd = open("/dev/net/tun", O_RDWR)) < 0 )
       return tun_alloc_old(dev);

    memset(&ifr, 0, sizeof(ifr));

    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *
     *        IFF_NO_PI - Do not provide packet information
     */
    ifr.ifr_flags = IFF_TUN;
    if( *dev )
       strscpy_pad(ifr.ifr_name, dev, IFNAMSIZ);

    if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
       close(fd);
       return err;
    }
    strcpy(dev, ifr.ifr_name);
    return fd;
}
```

<a id="rst-frame-format"></a>

### 3.2 Frame format

If flag IFF_NO_PI is not set each frame format is:



```text
Flags [2 bytes]
Proto [2 bytes]
Raw protocol(IP, IPv6, etc) frame.
```

<a id="rst-multiqueue-tuntap-interface"></a>

### 3.3 Multiqueue tuntap interface

From version 3.8, Linux supports multiqueue tuntap which can uses multiple file descriptors (queues) to parallelize packets sending or receiving. The device allocation is the same as before, and if user wants to create multiple queues, TUNSETIFF with the same device name must be called many times with IFF_MULTI_QUEUE flag.

`char *dev` should be the name of the device, queues is the number of queues to be created, fds is used to store and return the file descriptors (queues) created to the caller. Each file descriptor were served as the interface of a queue which could be accessed by userspace.



```text
#include <linux/if.h>
#include <linux/if_tun.h>

int tun_alloc_mq(char *dev, int queues, int *fds)
{
    struct ifreq ifr;
    int fd, err, i;

    if (!dev)
        return -1;

    memset(&ifr, 0, sizeof(ifr));
    /* Flags: IFF_TUN   - TUN device (no Ethernet headers)
     *        IFF_TAP   - TAP device
     *
     *        IFF_NO_PI - Do not provide packet information
     *        IFF_MULTI_QUEUE - Create a queue of multiqueue device
     */
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_MULTI_QUEUE;
    strcpy(ifr.ifr_name, dev);

    for (i = 0; i < queues; i++) {
        if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
           goto err;
        err = ioctl(fd, TUNSETIFF, (void *)&ifr);
        if (err) {
           close(fd);
           goto err;
        }
        fds[i] = fd;
    }

    return 0;
err:
    for (--i; i >= 0; i--)
        close(fds[i]);
    return err;
}
```

A new ioctl(TUNSETQUEUE) were introduced to enable or disable a queue. When calling it with IFF_DETACH_QUEUE flag, the queue were disabled. And when calling it with IFF_ATTACH_QUEUE flag, the queue were enabled. The queue were enabled by default after it was created through TUNSETIFF.

fd is the file descriptor (queue) that we want to enable or disable, when enable is true we enable it, otherwise we disable it:



```text
#include <linux/if.h>
#include <linux/if_tun.h>

int tun_set_queue(int fd, int enable)
{
    struct ifreq ifr;

    memset(&ifr, 0, sizeof(ifr));

    if (enable)
       ifr.ifr_flags = IFF_ATTACH_QUEUE;
    else
       ifr.ifr_flags = IFF_DETACH_QUEUE;

    return ioctl(fd, TUNSETQUEUE, (void *)&ifr);
}
```

<a id="rst-universal-tun-tap-device-driver-frequently-asked-question"></a>

## Universal TUN/TAP device driver Frequently Asked Question

1. What platforms are supported by TUN/TAP driver ?

Currently driver has been written for 3 Unices:

> - Linux kernels 2.2.x, 2.4.x
>
> - FreeBSD 3.x, 4.x, 5.x
>
> - Solaris 2.6, 7.0, 8.0

2. What is TUN/TAP driver used for?

As mentioned above, main purpose of TUN/TAP driver is tunneling. It is used by VTun ([http://vtun.sourceforge.net](<http://vtun.sourceforge.net>)).

Another interesting application using TUN/TAP is pipsecd ([http://perso.enst.fr/\~beyssac/pipsec/](<http://perso.enst.fr/~beyssac/pipsec/>)), a userspace IPSec implementation that can use complete kernel routing (unlike FreeS/WAN).

3. How does Virtual network device actually work ?

Virtual network device can be viewed as a simple Point-to-Point or Ethernet device, which instead of receiving packets from a physical media, receives them from user space program and instead of sending packets via physical media sends them to the user space program.

Let's say that you configured IPv6 on the tap0, then whenever the kernel sends an IPv6 packet to tap0, it is passed to the application (VTun for example). The application encrypts, compresses and sends it to the other side over TCP or UDP. The application on the other side decompresses and decrypts the data received and writes the packet to the TAP device, the kernel handles the packet like it came from real physical device.

4. What is the difference between TUN driver and TAP driver?

TUN works with IP frames. TAP works with Ethernet frames.

This means that you have to read/write IP packets when you are using tun and ethernet frames when using tap.

5. What is the difference between BPF and TUN/TAP driver?

BPF is an advanced packet filter. It can be attached to existing network interface. It does not provide a virtual network interface. A TUN/TAP driver does provide a virtual network interface and it is possible to attach BPF to this interface.

6. Does TAP driver support kernel Ethernet bridging?

Yes. Linux and FreeBSD drivers support Ethernet bridging.

---

# The UDP-Lite protocol (RFC 3828)

_Peios Kernel / Internals / Networking_

> UDP-Lite is a Standards-Track IETF transport protocol whose characteristic is a variable-length checksum. This has advantages for transport of multimedia (video, VoIP) over wireless networks, as partly damaged packets can still be fed into…

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-the-udp-lite-protocol-rfc-3828"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> UDP-Lite is a Standards-Track IETF transport protocol whose characteristic is a variable-length checksum. This has advantages for transport of multimedia (video, VoIP) over wireless networks, as partly damaged packets can still be fed into the codec instead of being discarded due to a failed checksum test.
>
> This file briefly describes the existing kernel support and the socket API. For in-depth information, you can consult:
>
> > - The UDP-Lite Homepage: [http://web.archive.org/web/%2E/http://www.erg.abdn.ac.uk/users/gerrit/udp-lite/](<http://web.archive.org/web/%2E/http://www.erg.abdn.ac.uk/users/gerrit/udp-lite/>)
> >
> >   From here you can also download some example application source code.
> >
> > - The UDP-Lite HOWTO on [http://web.archive.org/web/%2E/http://www.erg.abdn.ac.uk/users/gerrit/udp-lite/files/UDP-Lite-HOWTO.txt](<http://web.archive.org/web/%2E/http://www.erg.abdn.ac.uk/users/gerrit/udp-lite/files/UDP-Lite-HOWTO.txt>)
> >
> > - The Wireshark UDP-Lite WiKi (with capture files): [https://wiki.wireshark.org/Lightweight_User_Datagram_Protocol](<https://wiki.wireshark.org/Lightweight_User_Datagram_Protocol>)
> >
> > - The Protocol Spec, RFC 3828, [http://www.ietf.org/rfc/rfc3828.txt](<http://www.ietf.org/rfc/rfc3828.txt>)

<a id="rst-applications"></a>

## 1. Applications

> Several applications have been ported successfully to UDP-Lite. Ethereal (now called wireshark) has UDP-Litev4/v6 support by default.
>
> Porting applications to UDP-Lite is straightforward: only socket level and IPPROTO need to be changed; senders additionally set the checksum coverage length (default = header length = 8). Details are in the next section.

<a id="rst-programming-api"></a>

## 2. Programming API

> UDP-Lite provides a connectionless, unreliable datagram service and hence uses the same socket type as UDP. In fact, porting from UDP to UDP-Lite is very easy: simply add `IPPROTO_UDPLITE` as the last argument of the socket(2) call so that the statement looks like:
>
>
>
> ```text
> s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDPLITE);
> ```
>
> or, respectively,
>
>
>
> ```text
> s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE);
> ```
>
> With just the above change you are able to run UDP-Lite services or connect to UDP-Lite servers. The kernel will assume that you are not interested in using partial checksum coverage and so emulate UDP mode (full coverage).
>
> To make use of the partial checksum coverage facilities requires setting a single socket option, which takes an integer specifying the coverage length:
>
> > - Sender checksum coverage: UDPLITE_SEND_CSCOV
> >
> >   For example:
> >
> >
> >
> >   ```text
> >   int val = 20;
> >   setsockopt(s, SOL_UDPLITE, UDPLITE_SEND_CSCOV, &val, sizeof(int));
> >   ```
> >
> >   sets the checksum coverage length to 20 bytes (12b data + 8b header). Of each packet only the first 20 bytes (plus the pseudo-header) will be checksummed. This is useful for RTP applications which have a 12-byte base header.
> >
> > - Receiver checksum coverage: UDPLITE_RECV_CSCOV
> >
> >   This option is the receiver-side analogue. It is truly optional, i.e. not required to enable traffic with partial checksum coverage. Its function is that of a traffic filter: when enabled, it instructs the kernel to drop all packets which have a coverage \_less\_ than this value. For example, if RTP and UDP headers are to be protected, a receiver can enforce that only packets with a minimum coverage of 20 are admitted:
> >
> >
> >
> >   ```text
> >   int min = 20;
> >   setsockopt(s, SOL_UDPLITE, UDPLITE_RECV_CSCOV, &min, sizeof(int));
> >   ```
>
> The calls to getsockopt(2) are analogous. Being an extension and not a stand- alone protocol, all socket options known from UDP can be used in exactly the same manner as before, e.g. UDP_CORK or UDP_ENCAP.
>
> A detailed discussion of UDP-Lite checksum coverage options is in section IV.

<a id="rst-header-files"></a>

## 3. Header Files

> The socket API requires support through header files in /usr/include:
>
> > - /usr/include/netinet/in.h to define IPPROTO_UDPLITE
> >
> > - /usr/include/netinet/udplite.h for UDP-Lite header fields and protocol constants
>
> For testing purposes, the following can serve as a `mini` header file:
>
>
>
> ```text
> #define IPPROTO_UDPLITE       136
> #define SOL_UDPLITE           136
> #define UDPLITE_SEND_CSCOV     10
> #define UDPLITE_RECV_CSCOV     11
> ```
>
> Ready-made header files for various distros are in the UDP-Lite tarball.

<a id="rst-kernel-behaviour-with-regards-to-the-various-socket-options"></a>

## 4. Kernel Behaviour with Regards to the Various Socket Options

> To enable debugging messages, the log level need to be set to 8, as most messages use the KERN_DEBUG level (7).
>
> 1. Sender Socket Options
>
> If the sender specifies a value of 0 as coverage length, the module assumes full coverage, transmits a packet with coverage length of 0 and according checksum.  If the sender specifies a coverage &lt; 8 and different from 0, the kernel assumes 8 as default value.  Finally, if the specified coverage length exceeds the packet length, the packet length is used instead as coverage length.
>
> 2. Receiver Socket Options
>
> The receiver specifies the minimum value of the coverage length it is willing to accept.  A value of 0 here indicates that the receiver always wants the whole of the packet covered. In this case, all partially covered packets are dropped and an error is logged.
>
> It is not possible to specify illegal values (&lt;0 and &lt;8); in these cases the default of 8 is assumed.
>
> All packets arriving with a coverage value less than the specified threshold are discarded, these events are also logged.
>
> 3. Disabling the Checksum Computation
>
> On both sender and receiver, checksumming will always be performed and cannot be disabled using SO_NO_CHECK. Thus:
>
>
>
> ```text
> setsockopt(sockfd, SOL_SOCKET, SO_NO_CHECK,  ... );
> ```
>
> will always will be ignored, while the value of:
>
>
>
> ```text
> getsockopt(sockfd, SOL_SOCKET, SO_NO_CHECK, &value, ...);
> ```
>
> is meaningless (as in TCP). Packets with a zero checksum field are illegal (cf. RFC 3828, sec. 3.1) and will be silently discarded.
>
> 4. Fragmentation
>
> The checksum computation respects both buffersize and MTU. The size of UDP-Lite packets is determined by the size of the send buffer. The minimum size of the send buffer is 2048 (defined as SOCK_MIN_SNDBUF in include/net/sock.h), the default value is configurable as net.core.wmem_default or via setting the SO_SNDBUF socket(7) option. The maximum upper bound for the send buffer is determined by net.core.wmem_max.
>
> Given a payload size larger than the send buffer size, UDP-Lite will split the payload into several individual packets, filling up the send buffer size in each case.
>
> The precise value also depends on the interface MTU. The interface MTU, in turn, may trigger IP fragmentation. In this case, the generated UDP-Lite packet is split into several IP packets, of which only the first one contains the L4 header.
>
> The send buffer size has implications on the checksum coverage length. Consider the following example:
>
>
>
> ```text
> Payload: 1536 bytes          Send Buffer:     1024 bytes
> MTU:     1500 bytes          Coverage Length:  856 bytes
> ```
>
> UDP-Lite will ship the 1536 bytes in two separate packets:
>
>
>
> ```text
> Packet 1: 1024 payload + 8 byte header + 20 byte IP header = 1052 bytes
> Packet 2:  512 payload + 8 byte header + 20 byte IP header =  540 bytes
> ```
>
> The coverage packet covers the UDP-Lite header and 848 bytes of the payload in the first packet, the second packet is fully covered. Note that for the second packet, the coverage length exceeds the packet length. The kernel always re-adjusts the coverage length to the packet length in such cases.
>
> As an example of what happens when one UDP-Lite packet is split into several tiny fragments, consider the following example:
>
>
>
> ```text
> Payload: 1024 bytes            Send buffer size: 1024 bytes
> MTU:      300 bytes            Coverage length:   575 bytes
>
> +-+-----------+--------------+--------------+--------------+
> |8|    272    |      280     |     280      |     280      |
> +-+-----------+--------------+--------------+--------------+
>             280            560            840           1032
>                                     ^
> *****checksum coverage*************
> ```
>
> The UDP-Lite module generates one 1032 byte packet (1024 + 8 byte header). According to the interface MTU, these are split into 4 IP packets (280 byte IP payload + 20 byte IP header). The kernel module sums the contents of the entire first two packets, plus 15 bytes of the last packet before releasing the fragments to the IP module.
>
> To see the analogous case for IPv6 fragmentation, consider a link MTU of 1280 bytes and a write buffer of 3356 bytes. If the checksum coverage is less than 1232 bytes (MTU minus IPv6/fragment header lengths), only the first fragment needs to be considered. When using larger checksum coverage lengths, each eligible fragment needs to be checksummed. Suppose we have a checksum coverage of 3062. The buffer of 3356 bytes will be split into the following fragments:
>
>
>
> ```text
> Fragment 1: 1280 bytes carrying  1232 bytes of UDP-Lite data
> Fragment 2: 1280 bytes carrying  1232 bytes of UDP-Lite data
> Fragment 3:  948 bytes carrying   900 bytes of UDP-Lite data
> ```
>
> The first two fragments have to be checksummed in full, of the last fragment only 598 (= 3062 - 2\*1232) bytes are checksummed.
>
> While it is important that such cases are dealt with correctly, they are (annoyingly) rare: UDP-Lite is designed for optimising multimedia performance over wireless (or generally noisy) links and thus smaller coverage lengths are likely to be expected.

<a id="rst-udp-lite-runtime-statistics-and-their-meaning"></a>

## 5. UDP-Lite Runtime Statistics and their Meaning

> Exceptional and error conditions are logged to syslog at the KERN_DEBUG level.  Live statistics about UDP-Lite are available in /proc/net/snmp and can (with newer versions of netstat) be viewed using:
>
>
>
> ```text
> netstat -svu
> ```
>
> This displays UDP-Lite statistics variables, whose meaning is as follows.
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > InDatagrams
> >
> > </td>
> > <td>
> >
> >
> > The total number of datagrams delivered to users.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > NoPorts
> >
> > </td>
> > <td>
> >
> >
> > Number of packets received to an unknown port. These cases are counted separately (not as InErrors).
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > InErrors
> >
> > </td>
> > <td>
> >
> >
> > Number of erroneous UDP-Lite packets. Errors include:
> >
> > > - internal socket queue receive errors
> > >
> > > - packet too short (less than 8 bytes or stated coverage length exceeds received length)
> > >
> > > - xfrm4_policy_check() returned with error
> > >
> > > - application has specified larger min. coverage length than that of incoming packet
> > >
> > > - checksum coverage violated
> > >
> > > - bad checksum
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > OutDatagrams
> >
> > </td>
> > <td>
> >
> >
> > Total number of sent datagrams.
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
> >
> > These statistics derive from the UDP MIB (RFC 2013).

<a id="rst-iptables"></a>

## 6. IPtables

> There is packet match support for UDP-Lite as well as support for the LOG target. If you copy and paste the following line into /etc/protocols:
>
>
>
> ```text
> udplite 136     UDP-Lite        # UDP-Lite [RFC 3828]
> ```
>
> then:
>
>
>
> ```text
> iptables -A INPUT -p udplite -j LOG
> ```
>
> will produce logging output to syslog. Dropping and rejecting packets also works.

<a id="rst-maintainer-address"></a>

## 7. Maintainer Address

> The UDP-Lite patch was developed at
>
> > University of Aberdeen Electronics Research Group Department of Engineering Fraser Noble Building Aberdeen AB24 3UE; UK
>
> The current maintainer is Gerrit Renker, &lt;[gerrit@erg.abdn.ac.uk](<mailto:gerrit@erg.abdn.ac.uk>)&gt;. Initial code was developed by William  Stanislaus, &lt;[william@erg.abdn.ac.uk](<mailto:william@erg.abdn.ac.uk>)&gt;.

---

# Virtual Routing and Forwarding (VRF)

_Peios Kernel / Internals / Networking_

> The VRF device combined with ip rules provides the ability to create virtual routing and forwarding domains (aka VRFs, VRF-lite to be specific) in the Linux network stack. One use case is the multi-tenancy problem where each tenant has…

<a id="rst-virtual-routing-and-forwarding-vrf"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-the-vrf-device"></a>

## The VRF Device

The VRF device combined with ip rules provides the ability to create virtual routing and forwarding domains (aka VRFs, VRF-lite to be specific) in the Linux network stack. One use case is the multi-tenancy problem where each tenant has their own unique routing tables and in the very least need different default gateways.

Processes can be "VRF aware" by binding a socket to the VRF device. Packets through the socket then use the routing table associated with the VRF device. An important feature of the VRF device implementation is that it impacts only Layer 3 and above so L2 tools (e.g., LLDP) are not affected (ie., they do not need to be run in each VRF). The design also allows the use of higher priority ip rules (Policy Based Routing, PBR) to take precedence over the VRF device rules directing specific traffic as desired.

In addition, VRF devices allow VRFs to be nested within namespaces. For example network namespaces provide separation of network interfaces at the device layer, VLANs on the interfaces within a namespace provide L2 separation and then VRF devices provide L3 separation.

<a id="rst-design"></a>

### Design

A VRF device is created with an associated route table. Network interfaces are then enslaved to a VRF device:



```text
+-----------------------------+
|           vrf-blue          |  ===> route table 10
+-----------------------------+
   |        |            |
+------+ +------+     +-------------+
| eth1 | | eth2 | ... |    bond1    |
+------+ +------+     +-------------+
                         |       |
                     +------+ +------+
                     | eth8 | | eth9 |
                     +------+ +------+
```

Packets received on an enslaved device and are switched to the VRF device in the IPv4 and IPv6 processing stacks giving the impression that packets flow through the VRF device. Similarly on egress routing rules are used to send packets to the VRF device driver before getting sent out the actual interface. This allows tcpdump on a VRF device to capture all packets into and out of the VRF as a whole<a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1). Similarly, netfilter<a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) and tc rules can be applied using the VRF device to specify rules that apply to the VRF domain as a whole.

<a id="rst-footnote-1"></a>



**[1]** Packets in the forwarded state do not flow through the device, so those packets are not seen by tcpdump. Will revisit this limitation in a future release.

<a id="rst-footnote-2"></a>



**[2]** Iptables on ingress supports PREROUTING with skb-&gt;dev set to the real ingress device and both INPUT and PREROUTING rules with skb-&gt;dev set to the VRF device. For egress POSTROUTING and OUTPUT rules can be written using either the VRF device or real egress device.

<a id="rst-setup"></a>

### Setup

1. VRF device is created with an association to a FIB table. e.g,:



   ```text
   ip link add vrf-blue type vrf table 10
   ip link set dev vrf-blue up
   ```

2. An l3mdev FIB rule directs lookups to the table associated with the device. A single l3mdev rule is sufficient for all VRFs. The VRF device adds the l3mdev rule for IPv4 and IPv6 when the first device is created with a default preference of 1000. Users may delete the rule if desired and add with a different priority or install per-VRF rules.

   Prior to the v4.8 kernel iif and oif rules are needed for each VRF device:



   ```text
   ip ru add oif vrf-blue table 10
   ip ru add iif vrf-blue table 10
   ```

3. Set the default route for the table (and hence default route for the VRF):



   ```text
   ip route add table 10 unreachable default metric 4278198272
   ```

   This high metric value ensures that the default unreachable route can be overridden by a routing protocol suite.  FRRouting interprets kernel metrics as a combined admin distance (upper byte) and priority (lower 3 bytes).  Thus the above metric translates to \[255/8192\].

4. Enslave L3 interfaces to a VRF device:



   ```text
   ip link set dev eth1 master vrf-blue
   ```

   Local and connected routes for enslaved devices are automatically moved to the table associated with VRF device. Any additional routes depending on the enslaved device are dropped and will need to be reinserted to the VRF FIB table following the enslavement.

   The IPv6 sysctl option keep_addr_on_down can be enabled to keep IPv6 global addresses as VRF enslavement changes:



   ```text
   sysctl -w net.ipv6.conf.all.keep_addr_on_down=1
   ```

5. Additional VRF routes are added to associated table:



   ```text
   ip route add table 10 ...
   ```

<a id="rst-applications"></a>

### Applications

Applications that are to work within a VRF need to bind their socket to the VRF device:



```text
setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, dev, strlen(dev)+1);
```

or to specify the output device using cmsg and IP_PKTINFO.

By default the scope of the port bindings for unbound sockets is limited to the default VRF. That is, it will not be matched by packets arriving on interfaces enslaved to an l3mdev and processes may bind to the same port if they bind to an l3mdev.

TCP &amp; UDP services running in the default VRF context (ie., not bound to any VRF device) can work across all VRF domains by enabling the tcp_l3mdev_accept and udp_l3mdev_accept sysctl options:



```text
sysctl -w net.ipv4.tcp_l3mdev_accept=1
sysctl -w net.ipv4.udp_l3mdev_accept=1
```

These options are disabled by default so that a socket in a VRF is only selected for packets in that VRF. There is a similar option for RAW sockets, which is enabled by default for reasons of backwards compatibility. This is so as to specify the output device with cmsg and IP_PKTINFO, but using a socket not bound to the corresponding VRF. This allows e.g. older ping implementations to be run with specifying the device but without executing it in the VRF. This option can be disabled so that packets received in a VRF context are only handled by a raw socket bound to the VRF, and packets in the default VRF are only handled by a socket not bound to any VRF:



```text
sysctl -w net.ipv4.raw_l3mdev_accept=0
```

netfilter rules on the VRF device can be used to limit access to services running in the default VRF context as well.

Using VRF-aware applications (applications which simultaneously create sockets outside and inside VRFs) in conjunction with `net.ipv4.tcp_l3mdev_accept=1` is possible but may lead to problems in some situations. With that sysctl value, it is unspecified which listening socket will be selected to handle connections for VRF traffic; ie. either a socket bound to the VRF or an unbound socket may be used to accept new connections from a VRF. This somewhat unexpected behavior can lead to problems if sockets are configured with extra options (ex. TCP MD5 keys) with the expectation that VRF traffic will exclusively be handled by sockets bound to VRFs, as would be the case with `net.ipv4.tcp_l3mdev_accept=0`. Finally and as a reminder, regardless of which listening socket is selected, established sockets will be created in the VRF based on the ingress interface, as documented earlier.

---

<a id="rst-using-iproute2-for-vrfs"></a>

## Using iproute2 for VRFs

iproute2 supports the vrf keyword as of v4.7. For backwards compatibility this section lists both commands where appropriate -- with the vrf keyword and the older form without it.

1. Create a VRF

   To instantiate a VRF device and associate it with a table:



   ```text
   $ ip link add dev NAME type vrf table ID
   ```

   As of v4.8 the kernel supports the l3mdev FIB rule where a single rule covers all VRFs. The l3mdev rule is created for IPv4 and IPv6 on first device create.

2. List VRFs

   To list VRFs that have been created:



   ```text
   $ ip [-d] link show type vrf
     NOTE: The -d option is needed to show the table id
   ```

   For example:



   ```text
   $ ip -d link show type vrf
   11: mgmt: <NOARP,MASTER,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
       link/ether 72:b3:ba:91:e2:24 brd ff:ff:ff:ff:ff:ff promiscuity 0
       vrf table 1 addrgenmode eui64
   12: red: <NOARP,MASTER,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
       link/ether b6:6f:6e:f6:da:73 brd ff:ff:ff:ff:ff:ff promiscuity 0
       vrf table 10 addrgenmode eui64
   13: blue: <NOARP,MASTER,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
       link/ether 36:62:e8:7d:bb:8c brd ff:ff:ff:ff:ff:ff promiscuity 0
       vrf table 66 addrgenmode eui64
   14: green: <NOARP,MASTER,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
       link/ether e6:28:b8:63:70:bb brd ff:ff:ff:ff:ff:ff promiscuity 0
       vrf table 81 addrgenmode eui64
   ```

   Or in brief output:



   ```text
   $ ip -br link show type vrf
   mgmt         UP             72:b3:ba:91:e2:24 <NOARP,MASTER,UP,LOWER_UP>
   red          UP             b6:6f:6e:f6:da:73 <NOARP,MASTER,UP,LOWER_UP>
   blue         UP             36:62:e8:7d:bb:8c <NOARP,MASTER,UP,LOWER_UP>
   green        UP             e6:28:b8:63:70:bb <NOARP,MASTER,UP,LOWER_UP>
   ```

3. Assign a Network Interface to a VRF

   Network interfaces are assigned to a VRF by enslaving the netdevice to a VRF device:



   ```text
   $ ip link set dev NAME master NAME
   ```

   On enslavement connected and local routes are automatically moved to the table associated with the VRF device.

   For example:



   ```text
   $ ip link set dev eth0 master mgmt
   ```

4. Show Devices Assigned to a VRF

   To show devices that have been assigned to a specific VRF add the master option to the ip command:



   ```text
   $ ip link show vrf NAME
   $ ip link show master NAME
   ```

   For example:



   ```text
   $ ip link show vrf red
   3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master red state UP mode DEFAULT group default qlen 1000
       link/ether 02:00:00:00:02:02 brd ff:ff:ff:ff:ff:ff
   4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master red state UP mode DEFAULT group default qlen 1000
       link/ether 02:00:00:00:02:03 brd ff:ff:ff:ff:ff:ff
   7: eth5: <BROADCAST,MULTICAST> mtu 1500 qdisc noop master red state DOWN mode DEFAULT group default qlen 1000
       link/ether 02:00:00:00:02:06 brd ff:ff:ff:ff:ff:ff
   ```

   Or using the brief output:



   ```text
   $ ip -br link show vrf red
   eth1             UP             02:00:00:00:02:02 <BROADCAST,MULTICAST,UP,LOWER_UP>
   eth2             UP             02:00:00:00:02:03 <BROADCAST,MULTICAST,UP,LOWER_UP>
   eth5             DOWN           02:00:00:00:02:06 <BROADCAST,MULTICAST>
   ```

5. Show Neighbor Entries for a VRF

   To list neighbor entries associated with devices enslaved to a VRF device add the master option to the ip command:



   ```text
   $ ip [-6] neigh show vrf NAME
   $ ip [-6] neigh show master NAME
   ```

   For example:



   ```text
   $  ip neigh show vrf red
   10.2.1.254 dev eth1 lladdr a6:d9:c7:4f:06:23 REACHABLE
   10.2.2.254 dev eth2 lladdr 5e:54:01:6a:ee:80 REACHABLE

   $ ip -6 neigh show vrf red
   2002:1::64 dev eth1 lladdr a6:d9:c7:4f:06:23 REACHABLE
   ```

6. Show Addresses for a VRF

   To show addresses for interfaces associated with a VRF add the master option to the ip command:



   ```text
   $ ip addr show vrf NAME
   $ ip addr show master NAME
   ```

   For example:



   ```text
   $ ip addr show vrf red
   3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master red state UP group default qlen 1000
       link/ether 02:00:00:00:02:02 brd ff:ff:ff:ff:ff:ff
       inet 10.2.1.2/24 brd 10.2.1.255 scope global eth1
          valid_lft forever preferred_lft forever
       inet6 2002:1::2/120 scope global
          valid_lft forever preferred_lft forever
       inet6 fe80::ff:fe00:202/64 scope link
          valid_lft forever preferred_lft forever
   4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast master red state UP group default qlen 1000
       link/ether 02:00:00:00:02:03 brd ff:ff:ff:ff:ff:ff
       inet 10.2.2.2/24 brd 10.2.2.255 scope global eth2
          valid_lft forever preferred_lft forever
       inet6 2002:2::2/120 scope global
          valid_lft forever preferred_lft forever
       inet6 fe80::ff:fe00:203/64 scope link
          valid_lft forever preferred_lft forever
   7: eth5: <BROADCAST,MULTICAST> mtu 1500 qdisc noop master red state DOWN group default qlen 1000
       link/ether 02:00:00:00:02:06 brd ff:ff:ff:ff:ff:ff
   ```

   Or in brief format:



   ```text
   $ ip -br addr show vrf red
   eth1             UP             10.2.1.2/24 2002:1::2/120 fe80::ff:fe00:202/64
   eth2             UP             10.2.2.2/24 2002:2::2/120 fe80::ff:fe00:203/64
   eth5             DOWN
   ```

7. Show Routes for a VRF

   To show routes for a VRF use the ip command to display the table associated with the VRF device:



   ```text
   $ ip [-6] route show vrf NAME
   $ ip [-6] route show table ID
   ```

   For example:



   ```text
   $ ip route show vrf red
   unreachable default  metric 4278198272
   broadcast 10.2.1.0 dev eth1  proto kernel  scope link  src 10.2.1.2
   10.2.1.0/24 dev eth1  proto kernel  scope link  src 10.2.1.2
   local 10.2.1.2 dev eth1  proto kernel  scope host  src 10.2.1.2
   broadcast 10.2.1.255 dev eth1  proto kernel  scope link  src 10.2.1.2
   broadcast 10.2.2.0 dev eth2  proto kernel  scope link  src 10.2.2.2
   10.2.2.0/24 dev eth2  proto kernel  scope link  src 10.2.2.2
   local 10.2.2.2 dev eth2  proto kernel  scope host  src 10.2.2.2
   broadcast 10.2.2.255 dev eth2  proto kernel  scope link  src 10.2.2.2

   $ ip -6 route show vrf red
   local 2002:1:: dev lo  proto none  metric 0  pref medium
   local 2002:1::2 dev lo  proto none  metric 0  pref medium
   2002:1::/120 dev eth1  proto kernel  metric 256  pref medium
   local 2002:2:: dev lo  proto none  metric 0  pref medium
   local 2002:2::2 dev lo  proto none  metric 0  pref medium
   2002:2::/120 dev eth2  proto kernel  metric 256  pref medium
   local fe80:: dev lo  proto none  metric 0  pref medium
   local fe80:: dev lo  proto none  metric 0  pref medium
   local fe80::ff:fe00:202 dev lo  proto none  metric 0  pref medium
   local fe80::ff:fe00:203 dev lo  proto none  metric 0  pref medium
   fe80::/64 dev eth1  proto kernel  metric 256  pref medium
   fe80::/64 dev eth2  proto kernel  metric 256  pref medium
   ff00::/8 dev red  metric 256  pref medium
   ff00::/8 dev eth1  metric 256  pref medium
   ff00::/8 dev eth2  metric 256  pref medium
   unreachable default dev lo  metric 4278198272  error -101 pref medium
   ```

8. Route Lookup for a VRF

   A test route lookup can be done for a VRF:



   ```text
   $ ip [-6] route get vrf NAME ADDRESS
   $ ip [-6] route get oif NAME ADDRESS
   ```

   For example:



   ```text
   $ ip route get 10.2.1.40 vrf red
   10.2.1.40 dev eth1  table red  src 10.2.1.2
       cache

   $ ip -6 route get 2002:1::32 vrf red
   2002:1::32 from :: dev eth1  table red  proto kernel  src 2002:1::2  metric 256  pref medium
   ```

9. Removing Network Interface from a VRF

   Network interfaces are removed from a VRF by breaking the enslavement to the VRF device:



   ```text
   $ ip link set dev NAME nomaster
   ```

   Connected routes are moved back to the default table and local entries are moved to the local table.

   For example:



   ```text
   $ ip link set dev eth0 nomaster
   ```

---

Commands used in this example:



```text
cat >> /etc/iproute2/rt_tables.d/vrf.conf <<EOF
1  mgmt
10 red
66 blue
81 green
EOF

function vrf_create
{
    VRF=$1
    TBID=$2

    # create VRF device
    ip link add ${VRF} type vrf table ${TBID}

    if [ "${VRF}" != "mgmt" ]; then
        ip route add table ${TBID} unreachable default metric 4278198272
    fi
    ip link set dev ${VRF} up
}

vrf_create mgmt 1
ip link set dev eth0 master mgmt

vrf_create red 10
ip link set dev eth1 master red
ip link set dev eth2 master red
ip link set dev eth5 master red

vrf_create blue 66
ip link set dev eth3 master blue

vrf_create green 81
ip link set dev eth4 master green


Interface addresses from /etc/network/interfaces:
auto eth0
iface eth0 inet static
      address 10.0.0.2
      netmask 255.255.255.0
      gateway 10.0.0.254

iface eth0 inet6 static
      address 2000:1::2
      netmask 120

auto eth1
iface eth1 inet static
      address 10.2.1.2
      netmask 255.255.255.0

iface eth1 inet6 static
      address 2002:1::2
      netmask 120

auto eth2
iface eth2 inet static
      address 10.2.2.2
      netmask 255.255.255.0

iface eth2 inet6 static
      address 2002:2::2
      netmask 120

auto eth3
iface eth3 inet static
      address 10.2.3.2
      netmask 255.255.255.0

iface eth3 inet6 static
      address 2002:3::2
      netmask 120

auto eth4
iface eth4 inet static
      address 10.2.4.2
      netmask 255.255.255.0

iface eth4 inet6 static
      address 2002:4::2
      netmask 120
```

---

# Virtual eXtensible Local Area Networking documentation

_Peios Kernel / Internals / Networking_

> The VXLAN protocol is a tunnelling protocol designed to solve the problem of limited VLAN IDs (4096) in IEEE 802.1q. With VXLAN the size of the identifier is expanded to 24 bits (16777216).

<a id="rst-virtual-extensible-local-area-networking-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The VXLAN protocol is a tunnelling protocol designed to solve the problem of limited VLAN IDs (4096) in IEEE 802.1q.  With VXLAN the size of the identifier is expanded to 24 bits (16777216).

VXLAN is described by IETF RFC 7348, and has been implemented by a number of vendors.  The protocol runs over UDP using a single destination port.  This document describes the Linux kernel tunnel device, there is also a separate implementation of VXLAN for Openvswitch.

Unlike most tunnels, a VXLAN is a 1 to N network, not just point to point. A VXLAN device can learn the IP address of the other endpoint either dynamically in a manner similar to a learning bridge, or make use of statically-configured forwarding entries.

The management of vxlan is done in a manner similar to its two closest neighbors GRE and VLAN. Configuring VXLAN requires the version of iproute2 that matches the kernel release where VXLAN was first merged upstream.

1. Create vxlan device:



   ```text
   # ip link add vxlan0 type vxlan id 42 group 239.1.1.1 dev eth1 dstport 4789
   ```

This creates a new device named vxlan0.  The device uses the multicast group 239.1.1.1 over eth1 to handle traffic for which there is no entry in the forwarding table.  The destination port number is set to the IANA-assigned value of 4789.  The Linux implementation of VXLAN pre-dates the IANA's selection of a standard destination port number and uses the Linux-selected value by default to maintain backwards compatibility.

2. Delete vxlan device:



   ```text
   # ip link delete vxlan0
   ```

3. Show vxlan info:



   ```text
   # ip -d link show vxlan0
   ```

It is possible to create, destroy and display the vxlan forwarding table using the new bridge command.

1. Create forwarding table entry:



   ```text
   # bridge fdb add to 00:17:42:8a:b4:05 dst 192.19.0.2 dev vxlan0
   ```

2. Delete forwarding table entry:



   ```text
   # bridge fdb delete 00:17:42:8a:b4:05 dev vxlan0
   ```

3. Show forwarding table:



   ```text
   # bridge fdb show dev vxlan0
   ```

The following NIC features may indicate support for UDP tunnel-related offloads (most commonly VXLAN features, but support for a particular encapsulation protocol is NIC specific):

> - `tx-udp_tnl-segmentation`
>
> - - **`tx-udp_tnl-csum-segmentation`**
>
>     ability to perform TCP segmentation offload of UDP encapsulated frames
>
> - - **`rx-udp_tunnel-port-offload`**
>
>     receive side parsing of UDP encapsulated frames which allows NICs to perform protocol-aware offloads, like checksum validation offload of inner frames (only needed by NICs without protocol-agnostic offloads)

For devices supporting `rx-udp_tunnel-port-offload` the list of currently offloaded ports can be interrogated with `ethtool`:



```text
$ ethtool --show-tunnels eth0
Tunnel information for eth0:
  UDP port table 0:
    Size: 4
    Types: vxlan
    No entries
  UDP port table 1:
    Size: 4
    Types: geneve, vxlan-gpe
    Entries (1):
        port 1230, vxlan-gpe
```

---

# X.25 Device Driver Interface

_Peios Kernel / Internals / Networking_

> Version 1.1

<a id="rst-x-25-device-driver-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Version 1.1

> Jonathan Naylor 26.12.96

This is a description of the messages to be passed between the X.25 Packet Layer and the X.25 device driver. They are designed to allow for the easy setting of the LAPB mode from within the Packet Layer.

The X.25 device driver will be coded normally as per the Linux device driver standards. Most X.25 device drivers will be moderately similar to the already existing Ethernet device drivers. However unlike those drivers, the X.25 device driver has a state associated with it, and this information needs to be passed to and from the Packet Layer for proper operation.

All messages are held in sk_buff's just like real data to be transmitted over the LAPB link. The first byte of the skbuff indicates the meaning of the rest of the skbuff, if any more information does exist.

<a id="rst-packet-layer-to-device-driver"></a>

## Packet Layer to Device Driver

First Byte = 0x00 (X25_IFACE_DATA)

This indicates that the rest of the skbuff contains data to be transmitted over the LAPB link. The LAPB link should already exist before any data is passed down.

First Byte = 0x01 (X25_IFACE_CONNECT)

Establish the LAPB link. If the link is already established then the connect confirmation message should be returned as soon as possible.

First Byte = 0x02 (X25_IFACE_DISCONNECT)

Terminate the LAPB link. If it is already disconnected then the disconnect confirmation message should be returned as soon as possible.

First Byte = 0x03 (X25_IFACE_PARAMS)

LAPB parameters. To be defined.

<a id="rst-device-driver-to-packet-layer"></a>

## Device Driver to Packet Layer

First Byte = 0x00 (X25_IFACE_DATA)

This indicates that the rest of the skbuff contains data that has been received over the LAPB link.

First Byte = 0x01 (X25_IFACE_CONNECT)

LAPB link has been established. The same message is used for both a LAPB link connect_confirmation and a connect_indication.

First Byte = 0x02 (X25_IFACE_DISCONNECT)

LAPB link has been terminated. This same message is used for both a LAPB link disconnect_confirmation and a disconnect_indication.

First Byte = 0x03 (X25_IFACE_PARAMS)

LAPB parameters. To be defined.

<a id="rst-requirements-for-the-device-driver"></a>

## Requirements for the device driver

Packets should not be reordered or dropped when delivering between the Packet Layer and the device driver.

To avoid packets from being reordered or dropped when delivering from the device driver to the Packet Layer, the device driver should not call "netif_rx" to deliver the received packets. Instead, it should call "netif_receive_skb_core" from softirq context to deliver them.

---

# Linux X.25 Project

_Peios Kernel / Internals / Networking_

> As my third year dissertation at University I have taken it upon myself to write an X.25 implementation for Linux. My aim is to provide a complete X.25 Packet Layer and a LAPB module to allow for "normal" X.25 to be run using Linux. There…

<a id="rst-linux-x-25-project"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

As my third year dissertation at University I have taken it upon myself to write an X.25 implementation for Linux. My aim is to provide a complete X.25 Packet Layer and a LAPB module to allow for "normal" X.25 to be run using Linux. There are two sorts of X.25 cards available, intelligent ones that implement LAPB on the card itself, and unintelligent ones that simply do framing, bit-stuffing and checksumming. These both need to be handled by the system.

I therefore decided to write the implementation such that as far as the Packet Layer is concerned, the link layer was being performed by a lower layer of the Linux kernel and therefore it did not concern itself with implementation of LAPB. Therefore the LAPB modules would be called by unintelligent X.25 card drivers and not by intelligent ones, this would provide a uniform device driver interface, and simplify configuration.

To confuse matters a little, an 802.2 LLC implementation is also possible which could allow X.25 to be run over an Ethernet (or Token Ring) and conform with the JNT "Pink Book", this would have a different interface to the Packet Layer but there would be no confusion since the class of device being served by the LLC would be completely separate from LAPB.

Just when you thought that it could not become more confusing, another option appeared, XOT. This allows X.25 Packet Layer frames to operate over the Internet using TCP/IP as a reliable link layer. RFC1613 specifies the format and behaviour of the protocol. If time permits this option will also be actively considered.

A linux-x25 mailing list has been created at vger.kernel.org to support the development and use of Linux X.25. It is early days yet, but interested parties are welcome to subscribe to it. Just send a message to [majordomo@vger.kernel.org](<mailto:majordomo@vger.kernel.org>) with the following in the message body:

subscribe linux-x25 end

The contents of the Subject line are ignored.

Jonathan

[g4klx@g4klx.demon.co.uk](<mailto:g4klx@g4klx.demon.co.uk>)

---

# XDP RX Metadata

_Peios Kernel / Internals / Networking_

> This document describes how an eXpress Data Path (XDP) program can access hardware metadata related to a packet using a set of helper functions, and how it can pass that metadata on to other consumers.

<a id="rst-xdp-rx-metadata"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes how an eXpress Data Path (XDP) program can access hardware metadata related to a packet using a set of helper functions, and how it can pass that metadata on to other consumers.

<a id="rst-general-design"></a>

## General Design

XDP has access to a set of kfuncs to manipulate the metadata in an XDP frame. Every device driver that wishes to expose additional packet metadata can implement these kfuncs. The set of kfuncs is declared in `include/net/xdp.h` via `XDP_METADATA_KFUNC_xxx`.

Currently, the following kfuncs are supported. In the future, as more metadata is supported, this set will grow:


#### <a id="c-bpf_xdp_metadata_rx_timestamp"></a>`bpf_xdp_metadata_rx_timestamp()`

```c
__bpf_kfunc int bpf_xdp_metadata_rx_timestamp(const struct xdp_md *ctx, u64 *timestamp)
```

Read XDP frame RX timestamp.

**Parameters**

- `const struct xdp_md *ctx`: XDP context pointer.
- `u64 *timestamp`: Return value pointer.

**Return**

* Returns 0 on success or `-errno` on error.
* `-EOPNOTSUPP` : means device driver does not implement kfunc
* `-ENODATA`    : means no RX-timestamp available for this frame



#### <a id="c-bpf_xdp_metadata_rx_hash"></a>`bpf_xdp_metadata_rx_hash()`

```c
__bpf_kfunc int bpf_xdp_metadata_rx_hash(const struct xdp_md *ctx, u32 *hash, enum xdp_rss_hash_type *rss_type)
```

Read XDP frame RX hash.

**Parameters**

- `const struct xdp_md *ctx`: XDP context pointer.
- `u32 *hash`: Return value pointer.
- `enum xdp_rss_hash_type *rss_type`: Return value pointer for RSS type.

**Description**

The RSS hash type (**rss_type**) specifies what portion of packet headers NIC
hardware used when calculating RSS hash value.  The RSS type can be decoded
via `enum xdp_rss_hash_type` either matching on individual L3/L4 bits
`XDP_RSS_L*` or by combined traditional *RSS Hashing Types*
`XDP_RSS_TYPE_L*`.

**Return**

* Returns 0 on success or `-errno` on error.
* `-EOPNOTSUPP` : means device driver doesn't implement kfunc
* `-ENODATA`    : means no RX-hash available for this frame



#### <a id="c-bpf_xdp_metadata_rx_vlan_tag"></a>`bpf_xdp_metadata_rx_vlan_tag()`

```c
__bpf_kfunc int bpf_xdp_metadata_rx_vlan_tag(const struct xdp_md *ctx, __be16 *vlan_proto, u16 *vlan_tci)
```

Get XDP packet outermost VLAN tag

**Parameters**

- `const struct xdp_md *ctx`: XDP context pointer.
- `__be16 *vlan_proto`: Destination pointer for VLAN Tag protocol identifier (TPID).
- `u16 *vlan_tci`: Destination pointer for VLAN TCI (VID + DEI + PCP)

**Description**

In case of success, `vlan_proto` contains *Tag protocol identifier (TPID)*,
usually `ETH_P_8021Q` or `ETH_P_8021AD`, but some networks can use
custom TPIDs. `vlan_proto` is stored in **network byte order (BE)**
and should be used as follows:
`if (vlan_proto == bpf_htons(ETH_P_8021Q)) do_something();`

`vlan_tci` contains the remaining 16 bits of a VLAN tag.
Driver is expected to provide those in **host byte order (usually LE)**,
so the bpf program should not perform byte conversion.
According to 802.1Q standard, *VLAN TCI (Tag control information)*
is a bit field that contains:
*VLAN identifier (VID)* that can be read with `vlan_tci & 0xfff`,
*Drop eligible indicator (DEI)* - 1 bit,
*Priority code point (PCP)* - 3 bits.
For detailed meaning of DEI and PCP, please refer to other sources.

**Return**

* Returns 0 on success or `-errno` on error.
* `-EOPNOTSUPP` : device driver doesn't implement kfunc
* `-ENODATA`    : VLAN tag was not stripped or is not available


An XDP program can use these kfuncs to read the metadata into stack variables for its own consumption. Or, to pass the metadata on to other consumers, an XDP program can store it into the metadata area carried ahead of the packet. Not all packets will necessary have the requested metadata available in which case the driver returns `-ENODATA`.

Not all kfuncs have to be implemented by the device driver; when not implemented, the default ones that return `-EOPNOTSUPP` will be used to indicate the device driver have not implemented this kfunc.

Within an XDP frame, the metadata layout (accessed via `xdp_buff`) is as follows:



```text
+----------+-----------------+------+
| headroom | custom metadata | data |
+----------+-----------------+------+
           ^                 ^
           |                 |
 xdp_buff->data_meta   xdp_buff->data
```

An XDP program can store individual metadata items into this `data_meta` area in whichever format it chooses. Later consumers of the metadata will have to agree on the format by some out of band contract (like for the AF_XDP use case, see below).

<a id="rst-af-xdp"></a>

## AF_XDP

[AF_XDP](</kernel/internals/networking/af-xdp.md>) use-case implies that there is a contract between the BPF program that redirects XDP frames into the `AF_XDP` socket (`XSK`) and the final consumer. Thus the BPF program manually allocates a fixed number of bytes out of metadata via `bpf_xdp_adjust_meta` and calls a subset of kfuncs to populate it. The userspace `XSK` consumer computes `xsk_umem__get_data() - METADATA_SIZE` to locate that metadata. Note, `xsk_umem__get_data` is defined in `libxdp` and `METADATA_SIZE` is an application-specific constant (`AF_XDP` receive descriptor does \_not\_ explicitly carry the size of the metadata).

Here is the `AF_XDP` consumer layout (note missing `data_meta` pointer):



```text
+----------+-----------------+------+
| headroom | custom metadata | data |
+----------+-----------------+------+
                             ^
                             |
                      rx_desc->address
```

<a id="rst-xdp-pass"></a>

## XDP_PASS

This is the path where the packets processed by the XDP program are passed into the kernel. The kernel creates the `skb` out of the `xdp_buff` contents. Currently, every driver has custom kernel code to parse the descriptors and populate `skb` metadata when doing this `xdp_buff->skb` conversion, and the XDP metadata is not used by the kernel when building `skbs`. However, TC-BPF programs can access the XDP metadata area using the `data_meta` pointer.

In the future, we'd like to support a case where an XDP program can override some of the metadata used for building `skbs`.

<a id="rst-bpf-redirect-map"></a>

## bpf_redirect_map

`bpf_redirect_map` can redirect the frame to a different device. Some devices (like virtual ethernet links) support running a second XDP program after the redirect. However, the final consumer doesn't have access to the original hardware descriptor and can't access any of the original metadata. The same applies to XDP programs installed into devmaps and cpumaps.

This means that for redirected packets only custom metadata is currently supported, which has to be prepared by the initial XDP program before redirect. If the frame is eventually passed to the kernel, the `skb` created from such a frame won't have any hardware metadata populated in its `skb`. If such a packet is later redirected into an `XSK`, that will also only have access to the custom metadata.

<a id="rst-bpf-tail-call"></a>

## bpf_tail_call

Adding programs that access metadata kfuncs to the `BPF_MAP_TYPE_PROG_ARRAY` is currently not supported.

<a id="rst-supported-devices"></a>

## Supported Devices

It is possible to query which kfunc the particular netdev implements via netlink. See `xdp-rx-metadata-features` attribute set in `Documentation/netlink/specs/netdev.yaml`.

<a id="rst-driver-implementation"></a>

## Driver Implementation

Certain devices may prepend metadata to received packets. However, as of now, `AF_XDP` lacks the ability to communicate the size of the `data_meta` area to the consumer. Therefore, it is the responsibility of the driver to copy any device-reserved metadata out from the metadata area and ensure that `xdp_buff->data_meta` is pointing to `xdp_buff->data` before presenting the frame to the XDP program. This is necessary so that, after the XDP program adjusts the metadata area, the consumer can reliably retrieve the metadata address using `METADATA_SIZE` offset.

The following diagram shows how custom metadata is positioned relative to the packet data and how pointers are adjusted for metadata access:



```text
            |<-- bpf_xdp_adjust_meta(xdp_buff, -METADATA_SIZE) --|
new xdp_buff->data_meta                              old xdp_buff->data_meta
            |                                                    |
            |                                            xdp_buff->data
            |                                                    |
 +----------+----------------------------------------------------+------+
 | headroom |                  custom metadata                   | data |
 +----------+----------------------------------------------------+------+
            |                                                    |
            |                                            xdp_desc->addr
            |<------ xsk_umem__get_data() - METADATA_SIZE -------|
```

`bpf_xdp_adjust_meta` ensures that `METADATA_SIZE` is aligned to 4 bytes, does not exceed 252 bytes, and leaves sufficient space for building the xdp_frame. If these conditions are not met, it returns a negative error. In this case, the BPF program should not proceed to populate data into the `data_meta` area.

<a id="rst-example"></a>

## Example

See `tools/testing/selftests/bpf/progs/xdp_metadata.c` and `tools/testing/selftests/bpf/prog_tests/xdp_metadata.c` for an example of BPF program that handles XDP metadata.

---

# AF_XDP TX Metadata

_Peios Kernel / Internals / Networking_

> This document describes how to enable offloads when transmitting packets via af_xdp. Refer to xdp-rx-metadata on how to access similar metadata on the receive side.

<a id="rst-af-xdp-tx-metadata"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes how to enable offloads when transmitting packets via [AF_XDP](</kernel/internals/networking/af-xdp.md>). Refer to [XDP RX Metadata](</kernel/internals/networking/xdp-rx-metadata.md>) on how to access similar metadata on the receive side.

<a id="rst-general-design"></a>

## General Design

The headroom for the metadata is reserved via `tx_metadata_len` and `XDP_UMEM_TX_METADATA_LEN` flag in `struct xdp_umem_reg`. The metadata length is therefore the same for every socket that shares the same umem. The metadata layout is a fixed UAPI, refer to `union xsk_tx_metadata` in `include/uapi/linux/if_xdp.h`. Thus, generally, the `tx_metadata_len` field above should contain `sizeof(union xsk_tx_metadata)`.

Note that in the original implementation the `XDP_UMEM_TX_METADATA_LEN` flag was not required. Applications might attempt to create a umem with a flag first and if it fails, do another attempt without a flag.

The headroom and the metadata itself should be located right before `xdp_desc->addr` in the umem frame. Within a frame, the metadata layout is as follows:



```text
       tx_metadata_len
 /                         \
+-----------------+---------+----------------------------+
| xsk_tx_metadata | padding |          payload           |
+-----------------+---------+----------------------------+
                            ^
                            |
                      xdp_desc->addr
```

An AF_XDP application can request headrooms larger than `sizeof(struct xsk_tx_metadata)`. The kernel will ignore the padding (and will still use `xdp_desc->addr - tx_metadata_len` to locate the `xsk_tx_metadata`). For the frames that shouldn't carry any metadata (i.e., the ones that don't have `XDP_TX_METADATA` option), the metadata area is ignored by the kernel as well.

The flags field enables the particular offload:

- `XDP_TXMD_FLAGS_TIMESTAMP`: requests the device to put transmission timestamp into `tx_timestamp` field of `union xsk_tx_metadata`.

- `XDP_TXMD_FLAGS_CHECKSUM`: requests the device to calculate L4 checksum. `csum_start` specifies byte offset of where the checksumming should start and `csum_offset` specifies byte offset where the device should store the computed checksum.

- `XDP_TXMD_FLAGS_LAUNCH_TIME`: requests the device to schedule the packet for transmission at a pre-determined time called launch time. The value of launch time is indicated by `launch_time` field of `union xsk_tx_metadata`.

Besides the flags above, in order to trigger the offloads, the first packet's `struct xdp_desc` descriptor should set `XDP_TX_METADATA` bit in the `options` field. Also note that in a multi-buffer packet only the first chunk should carry the metadata.

<a id="rst-software-tx-checksum"></a>

## Software TX Checksum

For development and testing purposes its possible to pass `XDP_UMEM_TX_SW_CSUM` flag to `XDP_UMEM_REG` UMEM registration call. In this case, when running in `XDK_COPY` mode, the TX checksum is calculated on the CPU. Do not enable this option in production because it will negatively affect performance.

<a id="rst-launch-time"></a>

## Launch Time

The value of the requested launch time should be based on the device's PTP Hardware Clock (PHC) to ensure accuracy. AF_XDP takes a different data path compared to the ETF queuing discipline, which organizes packets and delays their transmission. Instead, AF_XDP immediately hands off the packets to the device driver without rearranging their order or holding them prior to transmission. Since the driver maintains FIFO behavior and does not perform packet reordering, a packet with a launch time request will block other packets in the same Tx Queue until it is sent. Therefore, it is recommended to allocate separate queue for scheduling traffic that is intended for future transmission.

In scenarios where the launch time offload feature is disabled, the device driver is expected to disregard the launch time request. For correct interpretation and meaningful operation, the launch time should never be set to a value larger than the farthest programmable time in the future (the horizon). Different devices have different hardware limitations on the launch time offload feature.

<a id="rst-stmmac-driver"></a>

### stmmac driver

For stmmac, TSO and launch time (TBS) features are mutually exclusive for each individual Tx Queue. By default, the driver configures Tx Queue 0 to support TSO and the rest of the Tx Queues to support TBS. The launch time hardware offload feature can be enabled or disabled by using the tc-etf command to call the driver's ndo_setup_tc() callback.

The value of the launch time that is programmed in the Enhanced Normal Transmit Descriptors is a 32-bit value, where the most significant 8 bits represent the time in seconds and the remaining 24 bits represent the time in 256 ns increments. The programmed launch time is compared against the PTP time (bits\[39:8\]) and rolls over after 256 seconds. Therefore, the horizon of the launch time for dwmac4 and dwxlgmac2 is 128 seconds in the future.

<a id="rst-igc-driver"></a>

### igc driver

For igc, all four Tx Queues support the launch time feature. The launch time hardware offload feature can be enabled or disabled by using the tc-etf command to call the driver's ndo_setup_tc() callback. When entering TSN mode, the igc driver will reset the device and create a default Qbv schedule with a 1-second cycle time, with all Tx Queues open at all times.

The value of the launch time that is programmed in the Advanced Transmit Context Descriptor is a relative offset to the starting time of the Qbv transmission window of the queue. The Frst flag of the descriptor can be set to schedule the packet for the next Qbv cycle. Therefore, the horizon of the launch time for i225 and i226 is the ending time of the next cycle of the Qbv transmission window of the queue. For example, when the Qbv cycle time is set to 1 second, the horizon of the launch time ranges from 1 second to 2 seconds, depending on where the Qbv cycle is currently running.

<a id="rst-querying-device-capabilities"></a>

## Querying Device Capabilities

Every devices exports its offloads capabilities via netlink netdev family. Refer to `xsk-flags` features bitmask in `Documentation/netlink/specs/netdev.yaml`.

- `tx-timestamp`: device supports `XDP_TXMD_FLAGS_TIMESTAMP`

- `tx-checksum`: device supports `XDP_TXMD_FLAGS_CHECKSUM`

- `tx-launch-time-fifo`: device supports `XDP_TXMD_FLAGS_LAUNCH_TIME`

See `tools/net/ynl/samples/netdev.c` on how to query this information.

<a id="rst-example"></a>

## Example

See `tools/testing/selftests/bpf/xdp_hw_metadata.c` for an example program that handles TX metadata. Also see [https://github.com/fomichev/xskgen](<https://github.com/fomichev/xskgen>) for a more bare-bones example.

---

# CAIF

_Peios Kernel / Internals / Networking / caif_

> Contents:

<a id="rst-caif"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Contents:

- [Linux CAIF](</kernel/internals/networking/caif/linux-caif.md>)
- [Using Linux CAIF](</kernel/internals/networking/caif/caif.md>)

---

# Using Linux CAIF

_Peios Kernel / Internals / Networking / caif_

> If you have compiled CAIF for modules do:

<a id="rst-using-linux-caif"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © ST-Ericsson AB 2010

**Author:** Sjur Brendeland/ [sjur.brandeland@stericsson.com](<mailto:sjur.brandeland@stericsson.com>)

<a id="rst-start"></a>

## Start

If you have compiled CAIF for modules do:



```text
$modprobe crc_ccitt
$modprobe caif
$modprobe caif_socket
$modprobe chnl_net
```

<a id="rst-preparing-the-setup-with-a-ste-modem"></a>

## Preparing the setup with a STE modem

If you are working on integration of CAIF you should make sure that the kernel is built with module support.

There are some things that need to be tweaked to get the host TTY correctly set up to talk to the modem. Since the CAIF stack is running in the kernel and we want to use the existing TTY, we are installing our physical serial driver as a line discipline above the TTY device.

To achieve this we need to install the N_CAIF ldisc from user space. The benefit is that we can hook up to any TTY.

The use of Start-of-frame-extension (STX) must also be set as module parameter "ser_use_stx".

Normally Frame Checksum is always used on UART, but this is also provided as a module parameter "ser_use_fcs".



```text
$ modprobe caif_serial ser_ttyname=/dev/ttyS0 ser_use_stx=yes
$ ifconfig caif_ttyS0 up
```

- **PLEASE NOTE:**

  There is a limitation in Android shell. It only accepts one argument to insmod/modprobe\!

<a id="rst-trouble-shooting"></a>

## Trouble shooting

There are debugfs parameters provided for serial communication. /sys/kernel/debug/caif_serial/&lt;tty-name&gt;/

- ser_state:   Prints the bit-mask status where

  - 0x02 means SENDING, this is a transient state.

  - 0x10 means FLOW_OFF_SENT, i.e. the previous frame has not been sent and is blocking further send operation. Flow OFF has been propagated to all CAIF Channels using this TTY.

- tty_status: Prints the bit-mask tty status information

  - 0x01 - tty-&gt;warned is on.

  - 0x04 - tty-&gt;packed is on.

  - 0x08 - tty-&gt;flow.tco_stopped is on.

  - 0x10 - tty-&gt;hw_stopped is on.

  - 0x20 - tty-&gt;flow.stopped is on.

- last_tx_msg: Binary blob Prints the last transmitted frame.

  This can be printed with:



  ```text
  $od --format=x1 /sys/kernel/debug/caif_serial/<tty>/last_rx_msg.
  ```

  The first two tx messages sent look like this. Note: The initial byte 02 is start of frame extension (STX) used for re-syncing upon errors.

  - Enumeration:



    ```text
    0000000  02 05 00 00 03 01 d2 02
             |  |     |  |  |  |
             STX(1)   |  |  |  |
                Length(2)|  |  |
                      Control Channel(1)
                         Command:Enumeration(1)
                            Link-ID(1)
                                Checksum(2)
    ```

  - Channel Setup:



    ```text
    0000000  02 07 00 00 00 21 a1 00 48 df
             |  |     |  |  |  |  |  |
             STX(1)   |  |  |  |  |  |
                Length(2)|  |  |  |  |
                      Control Channel(1)
                         Command:Channel Setup(1)
                            Channel Type(1)
                                Priority and Link-ID(1)
                                  Endpoint(1)
                                      Checksum(2)
    ```

- last_rx_msg: Prints the last transmitted frame.

  The RX messages for LinkSetup look almost identical but they have the bit 0x20 set in the command bit, and Channel Setup has added one byte before Checksum containing Channel ID.

  - **NOTE:**

    Several CAIF Messages might be concatenated. The maximum debug buffer size is 128 bytes.

<a id="rst-error-scenarios"></a>

## Error Scenarios

- last_tx_msg contains channel setup message and last_rx_msg is empty -&gt; The host seems to be able to send over the UART, at least the CAIF ldisc get notified that sending is completed.

- last_tx_msg contains enumeration message and last_rx_msg is empty -&gt; The host is not able to send the message from UART, the tty has not been able to complete the transmit operation.

- if /sys/kernel/debug/caif_serial/&lt;tty&gt;/tty_status is non-zero there might be problems transmitting over UART.

  E.g. host and modem wiring is not correct you will typically see tty_status = 0x10 (hw_stopped) and ser_state = 0x10 (FLOW_OFF_SENT).

  You will probably see the enumeration message in last_tx_message and empty last_rx_message.

---

# Linux CAIF

_Peios Kernel / Internals / Networking / caif_

> Copyright © ST-Ericsson AB 2010

<a id="rst-linux-caif"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © ST-Ericsson AB 2010

**Author:** Sjur Brendeland/ [sjur.brandeland@stericsson.com](<mailto:sjur.brandeland@stericsson.com>)

**License terms:** GNU General Public License (GPL) version 2

<a id="rst-introduction"></a>

## Introduction

CAIF is a MUX protocol used by ST-Ericsson cellular modems for communication between Modem and host. The host processes can open virtual AT channels, initiate GPRS Data connections, Video channels and Utility Channels. The Utility Channels are general purpose pipes between modem and host.

ST-Ericsson modems support a number of transports between modem and host. Currently, UART and Loopback are available for Linux.

<a id="rst-architecture"></a>

## Architecture

The implementation of CAIF is divided into:

- CAIF Socket Layer and GPRS IP Interface.

- CAIF Core Protocol Implementation

- CAIF Link Layer, implemented as NET devices.



```text
RTNL
 !
 !          +------+   +------+
 !         +------+!  +------+!
 !         !  IP  !!  !Socket!!
 +-------> !interf!+  ! API  !+       <- CAIF Client APIs
 !         +------+   +------!
 !            !           !
 !            +-----------+
 !                  !
 !               +------+             <- CAIF Core Protocol
 !               ! CAIF !
 !               ! Core !
 !               +------+
 !       +----------!---------+
 !       !          !         !
 !    +------+   +-----+   +------+
 +--> ! HSI  !   ! TTY !   ! USB  !   <- Link Layer (Net Devices)
      +------+   +-----+   +------+
```

<a id="rst-implementation"></a>

## Implementation

<a id="rst-caif-core-protocol-layer"></a>

### CAIF Core Protocol Layer

CAIF Core layer implements the CAIF protocol as defined by ST-Ericsson. It implements the CAIF protocol stack in a layered approach, where each layer described in the specification is implemented as a separate layer. The architecture is inspired by the design patterns "Protocol Layer" and "Protocol Packet".

<a id="rst-caif-structure"></a>

#### CAIF structure

The Core CAIF implementation contains:

> - Simple implementation of CAIF.
>
> - Layered architecture (a la Streams), each layer in the CAIF specification is implemented in a separate c-file.
>
> - Clients must call configuration function to add PHY layer.
>
> - Clients must implement CAIF layer to consume/produce CAIF payload with receive and transmit functions.
>
> - Clients must call configuration function to add and connect the Client layer.
>
> - When receiving / transmitting CAIF Packets (cfpkt), ownership is passed to the called function (except for framing layers' receive function)

<a id="rst-layered-architecture"></a>

## Layered Architecture

The CAIF protocol can be divided into two parts: Support functions and Protocol Implementation. The support functions include:

> - CFPKT CAIF Packet. Implementation of CAIF Protocol Packet. The CAIF Packet has functions for creating, destroying and adding content and for adding/extracting header and trailers to protocol packets.

The CAIF Protocol implementation contains:

> - CFCNFG CAIF Configuration layer. Configures the CAIF Protocol Stack and provides a Client interface for adding Link-Layer and Driver interfaces on top of the CAIF Stack.
>
> - CFCTRL CAIF Control layer. Encodes and Decodes control messages such as enumeration and channel setup. Also matches request and response messages.
>
> - CFSERVL General CAIF Service Layer functionality; handles flow control and remote shutdown requests.
>
> - CFVEI CAIF VEI layer. Handles CAIF AT Channels on VEI (Virtual External Interface). This layer encodes/decodes VEI frames.
>
> - CFDGML CAIF Datagram layer. Handles CAIF Datagram layer (IP traffic), encodes/decodes Datagram frames.
>
> - CFMUX CAIF Mux layer. Handles multiplexing between multiple physical bearers and multiple channels such as VEI, Datagram, etc. The MUX keeps track of the existing CAIF Channels and Physical Instances and selects the appropriate instance based on Channel-Id and Physical-ID.
>
> - CFFRML CAIF Framing layer. Handles Framing i.e. Frame length and frame checksum.
>
> - CFSERL CAIF Serial layer. Handles concatenation/split of frames into CAIF Frames with correct length.



```text
                +---------+
                | Config  |
                | CFCNFG  |
                +---------+
                     !
+---------+     +---------+     +---------+
|   AT    |     | Control |     | Datagram|
| CFVEIL  |     | CFCTRL  |     | CFDGML  |
+---------+     +---------+     +---------+
       \_____________!______________/
                     !
                +---------+
                |   MUX   |
                |         |
                +---------+
                _____!_____
               /           \
        +---------+     +---------+
        | CFFRML  |     | CFFRML  |
        | Framing |     | Framing |
        +---------+     +---------+
             !              !
        +---------+     +---------+
        |         |     | Serial  |
        |         |     | CFSERL  |
        +---------+     +---------+
```

In this layered approach the following "rules" apply.

> - All layers embed the same structure "struct cflayer"
>
> - A layer does not depend on any other layer's private data.
>
> - Layers are stacked by setting the pointers:
>
>
>
>   ```text
>   layer->up , layer->dn
>   ```
>
> - In order to send data upwards, each layer should do:
>
>
>
>   ```text
>   layer->up->receive(layer->up, packet);
>   ```
>
> - In order to send data downwards, each layer should do:
>
>
>
>   ```text
>   layer->dn->transmit(layer->dn, packet);
>   ```

<a id="rst-caif-socket-and-ip-interface"></a>

## CAIF Socket and IP interface

The IP interface and CAIF socket API are implemented on top of the CAIF Core protocol. The IP Interface and CAIF socket have an instance of 'struct cflayer', just like the CAIF Core protocol stack. Net device and Socket implement the 'receive()' function defined by 'struct cflayer', just like the rest of the CAIF stack. In this way, transmit and receive of packets is handled as by the rest of the layers: the 'dn-&gt;transmit()' function is called in order to transmit data.

<a id="rst-configuration-of-link-layer"></a>

### Configuration of Link Layer

The Link Layer is implemented as Linux network devices (struct net_device). Payload handling and registration is done using standard Linux mechanisms.

The CAIF Protocol relies on a loss-less link layer without implementing retransmission. This implies that packet drops must not happen. Therefore a flow-control mechanism is implemented where the physical interface can initiate flow stop for all CAIF Channels.

---

# Hardware Device Drivers

_Peios Kernel / Internals / Networking / device_drivers_

> Contents:

<a id="rst-hardware-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [Asynchronous Transfer Mode (ATM) Device Drivers](</kernel/internals/networking/device-drivers-atm/index.md>)
- [Controller Area Network (CAN) Device Drivers](</kernel/internals/networking/device-drivers-can/index.md>)
- [Cellular Modem Device Drivers](</kernel/internals/networking/device-drivers-cellular/index.md>)
- [Ethernet Device Drivers](</kernel/internals/networking/device-drivers-ethernet/index.md>)
- [Fiber Distributed Data Interface (FDDI) Device Drivers](</kernel/internals/networking/device-drivers-fddi/index.md>)
- [Amateur Radio Device Drivers](</kernel/internals/networking/device-drivers-hamradio/index.md>)
- [Wi-Fi Device Drivers](</kernel/internals/networking/device-drivers-wifi/index.md>)
- [WWAN Device Drivers](</kernel/internals/networking/device-drivers-wwan/index.md>)

---

# Asynchronous Transfer Mode (ATM) Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / atm_

> Contents:

<a id="rst-asynchronous-transfer-mode-atm-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [ATM cxacru device driver](</kernel/internals/networking/device-drivers-atm/cxacru.md>)
- [FORE Systems PCA-200E/SBA-200E ATM NIC driver](</kernel/internals/networking/device-drivers-atm/fore200e.md>)
- [ATM (i)Chip IA Linux Driver Source](</kernel/internals/networking/device-drivers-atm/iphase.md>)

---

# ATM cxacru device driver

_Peios Kernel / Internals / Networking / device_drivers / atm_

> Firmware is required for this device: http://accessrunner.sourceforge.net/

<a id="rst-atm-cxacru-device-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Firmware is required for this device: [http://accessrunner.sourceforge.net/](<http://accessrunner.sourceforge.net/>)

While it is capable of managing/maintaining the ADSL connection without the module loaded, the device will sometimes stop responding after unloading the driver and it is necessary to unplug/remove power to the device to fix this.

Note: support for cxacru-cf.bin has been removed. It was not loaded correctly so it had no effect on the device configuration. Fixing it could have stopped existing devices working when an invalid configuration is supplied.

There is a script cxacru-cf.py to convert an existing file to the sysfs form.

Detected devices will appear as ATM devices named "cxacru". In /sys/class/atm/ these are directories named cxacruN where N is the device number. A symlink named device points to the USB interface device's directory which contains several sysfs attribute files for retrieving device statistics:

- adsl_controller_version

- adsl_headend

- adsl_headend_environment

  > - Information about the remote headend.

- adsl_config

  > - Configuration writing interface.
  >
  > - Write parameters in hexadecimal format &lt;index&gt;=&lt;value&gt;, separated by whitespace, e.g.:
  >
  >   > "1=0 a=5"
  >
  > - Up to 7 parameters at a time will be sent and the modem will restart the ADSL connection when any value is set. These are logged for future reference.

- downstream_attenuation (dB)

- downstream_bits_per_frame

- downstream_rate (kbps)

- downstream_snr_margin (dB)

  > - Downstream stats.

- upstream_attenuation (dB)

- upstream_bits_per_frame

- upstream_rate (kbps)

- upstream_snr_margin (dB)

- transmitter_power (dBm/Hz)

  > - Upstream stats.

- downstream_crc_errors

- downstream_fec_errors

- downstream_hec_errors

- upstream_crc_errors

- upstream_fec_errors

- upstream_hec_errors

  > - Error counts.

- line_startable

  > - Indicates that ADSL support on the device is/can be enabled, see adsl_start.

- line_status

  > > - "initialising"
  > >
  > > - "down"
  > >
  > > - "attempting to activate"
  > >
  > > - "training"
  > >
  > > - "channel analysis"
  > >
  > > - "exchange"
  > >
  > > - "waiting"
  > >
  > > - "up"
  >
  > Changes between "down" and "attempting to activate" if there is no signal.

- link_status

  > - "not connected"
  >
  > - "connected"
  >
  > - "lost"

- mac_address

- modulation

  > - "" (when not connected)
  >
  > - "ANSI T1.413"
  >
  > - "ITU-T G.992.1 (G.DMT)"
  >
  > - "ITU-T G.992.2 (G.LITE)"

- startup_attempts

  > - Count of total attempts to initialise ADSL.

To enable/disable ADSL, the following can be written to the adsl_state file:

> - "start"
>
> - "stop
>
> - "restart" (stops, waits 1.5s, then starts)
>
> - "poll" (used to resume status polling if it was disabled due to failure)

Changes in adsl/line state are reported via kernel log messages:



```text
[4942145.150704] ATM dev 0: ADSL state: running
[4942243.663766] ATM dev 0: ADSL line: down
[4942249.665075] ATM dev 0: ADSL line: attempting to activate
[4942253.654954] ATM dev 0: ADSL line: training
[4942255.666387] ATM dev 0: ADSL line: channel analysis
[4942259.656262] ATM dev 0: ADSL line: exchange
[2635357.696901] ATM dev 0: ADSL line: up (8128 kb/s down | 832 kb/s up)
```

---

# FORE Systems PCA-200E/SBA-200E ATM NIC driver

_Peios Kernel / Internals / Networking / device_drivers / atm_

> This driver adds support for the FORE Systems 200E-series ATM adapters to the Linux operating system. It is based on the earlier PCA-200E driver written by Uwe Dannowski.

<a id="rst-fore-systems-pca-200e-sba-200e-atm-nic-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This driver adds support for the FORE Systems 200E-series ATM adapters to the Linux operating system. It is based on the earlier PCA-200E driver written by Uwe Dannowski.

The driver simultaneously supports PCA-200E and SBA-200E adapters on i386, alpha (untested), powerpc, sparc and sparc64 archs.

The intent is to enable the use of different models of FORE adapters at the same time, by hosts that have several bus interfaces (such as PCI+SBUS, or PCI+EISA).

Only PCI and SBUS devices are currently supported by the driver, but support for other bus interfaces such as EISA should not be too hard to add.

<a id="rst-firmware-copyright-notice"></a>

## Firmware Copyright Notice

Please read the fore200e_firmware_copyright file present in the linux/drivers/atm directory for details and restrictions.

<a id="rst-firmware-updates"></a>

## Firmware Updates

The FORE Systems 200E-series driver is shipped with firmware data being uploaded to the ATM adapters at system boot time or at module loading time. The supplied firmware images should work with all adapters.

However, if you encounter problems (the firmware doesn't start or the driver is unable to read the PROM data), you may consider trying another firmware version. Alternative binary firmware images can be found somewhere on the ForeThought CD-ROM supplied with your adapter by FORE Systems.

You can also get the latest firmware images from FORE Systems at [https://en.wikipedia.org/wiki/FORE_Systems](<https://en.wikipedia.org/wiki/FORE_Systems>). Register TACTics Online and go to the 'software updates' pages. The firmware binaries are part of the various ForeThought software distributions.

Notice that different versions of the PCA-200E firmware exist, depending on the endianness of the host architecture. The driver is shipped with both little and big endian PCA firmware images.

Name and location of the new firmware images can be set at kernel configuration time:

1. Copy the new firmware binary files (with .bin, .bin1 or .bin2 suffix) to some directory, such as linux/drivers/atm.

2. Reconfigure your kernel to set the new firmware name and location. Expected pathnames are absolute or relative to the drivers/atm directory.

3. Rebuild and re-install your kernel or your module.

<a id="rst-feedback"></a>

## Feedback

Feedback is welcome. Please send success stories/bug reports/ patches/improvement/comments/flames to &lt;[lizzi@cnam.fr](<mailto:lizzi@cnam.fr>)&gt;.

---

# ATM (i)Chip IA Linux Driver Source

_Peios Kernel / Internals / Networking / device_drivers / atm_

> READ ME FIRST

<a id="rst-atm-i-chip-ia-linux-driver-source"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> READ ME FIRST

---

> Read This Before You Begin\!

---

<a id="rst-description"></a>

## Description

This is the README file for the Interphase PCI ATM (i)Chip IA Linux driver source release.

The features and limitations of this driver are as follows:

> - A single VPI (VPI value of 0) is supported.
>
> - Supports 4K VCs for the server board (with 512K control memory) and 1K VCs for the client board (with 128K control memory).
>
> - UBR, ABR and CBR service categories are supported.
>
> - Only AAL5 is supported.
>
> - Supports setting of PCR on the VCs.
>
> - Multiple adapters in a system are supported.
>
> - All variants of Interphase ATM PCI (i)Chip adapter cards are supported, including x575 (OC3, control memory 128K , 512K and packet memory 128K, 512K and 1M), x525 (UTP25) and x531 (DS3 and E3). See [http://www.iphase.com/](<http://www.iphase.com/>) for details.
>
> - Only x86 platforms are supported.
>
> - SMP is supported.

<a id="rst-before-you-start"></a>

## Before You Start

<a id="rst-installation"></a>

### Installation

1. Installing the adapters in the system

   To install the ATM adapters in the system, follow the steps below.

   > - **a.** Login as root.
   >
   > - **b.** Shut down the system and power off the system.
   >
   > - **c.** Install one or more ATM adapters in the system.
   >
   > - **d.** Connect each adapter to a port on an ATM switch. The green 'Link' LED on the front panel of the adapter will be on if the adapter is connected to the switch properly when the system is powered up.
   >
   > - **e.** Power on and boot the system.

2. \[ Removed \]

3. Rebuild kernel with ABR support

   \[ a. and b. removed \]

   > - **c.** Reconfigure the kernel, choose the Interphase ia driver through "make menuconfig" or "make xconfig".
   >
   > - **d.** Rebuild the kernel, loadable modules and the atm tools.
   >
   > - **e.** Install the new built kernel and modules and reboot.

4. Load the adapter hardware driver (ia driver) if it is built as a module

   > - **a.** Login as root.
   >
   > - **b.** Change directory to /lib/modules/&lt;kernel-version&gt;/atm.
   >
   > - **c.** Run "insmod suni.o;insmod iphase.o" The yellow 'status' LED on the front panel of the adapter will blink while the driver is loaded in the system.
   >
   > - **d.** To verify that the 'ia' driver is loaded successfully, run the following command:
   >
   >
   >
   >   ```text
   >   cat /proc/atm/devices
   >   ```
   >
   >   If the driver is loaded successfully, the output of the command will be similar to the following lines:
   >
   >
   >
   >   ```text
   >   Itf Type    ESI/"MAC"addr AAL(TX,err,RX,err,drop) ...
   >   0   ia      xxxxxxxxx  0 ( 0 0 0 0 0 )  5 ( 0 0 0 0 0 )
   >   ```
   >
   >   You can also check the system log file /var/log/messages for messages related to the ATM driver.

5. Ia Driver Configuration

- **5.1 Configuration of adapter buffers**

  The (i)Chip boards have 3 different packet RAM size variants: 128K, 512K and 1M. The RAM size decides the number of buffers and buffer size. The default size and number of buffers are set as following:

  > >
  > > <table>
  > > <thead>
  > > <tr>
  > > <th>
  > >
  > >
  > > Total
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Rx RAM
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Tx RAM
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Rx Buf
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Tx Buf
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Rx buf
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > Tx buf
  > >
  > > </th>
  > > </tr>
  > > <tr>
  > > <th>
  > >
  > >
  > > RAM size
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > size
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > size
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > size
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > size
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > cnt
  > >
  > > </th>
  > > <th>
  > >
  > >
  > > cnt
  > >
  > > </th>
  > > </tr>
  > > </thead>
  > > <tbody>
  > > <tr>
  > > <td>
  > >
  > >
  > > 128K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 64K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 64K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 6
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 6
  > >
  > > </td>
  > > </tr>
  > > <tr>
  > > <td>
  > >
  > >
  > > 512K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 256K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 256K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 25
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 25
  > >
  > > </td>
  > > </tr>
  > > <tr>
  > > <td>
  > >
  > >
  > > 1M
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 512K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 512K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 10K
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 51
  > >
  > > </td>
  > > <td>
  > >
  > >
  > > 51
  > >
  > > </td>
  > > </tr>
  > > </tbody>
  > > </table>
  >
  > These setting should work well in most environments, but can be changed by typing the following command:
  >
  >
  >
  > ```text
  > insmod <IA_DIR>/ia.o IA_RX_BUF=<RX_CNT> IA_RX_BUF_SZ=<RX_SIZE> \
  >         IA_TX_BUF=<TX_CNT> IA_TX_BUF_SZ=<TX_SIZE>
  > ```
  >
  > Where:
  >
  > > - RX_CNT = number of receive buffers in the range (1-128)
  > >
  > > - RX_SIZE = size of receive buffers in the range (48-64K)
  > >
  > > - TX_CNT = number of transmit buffers in the range (1-128)
  > >
  > > - TX_SIZE = size of transmit buffers in the range (48-64K)
  > >
  > > 1. Transmit and receive buffer size must be a multiple of 4.
  > >
  > > 2. Care should be taken so that the memory required for the transmit and receive buffers is less than or equal to the total adapter packet memory.

5.2 Turn on ia debug trace

> When the ia driver is built with the CONFIG_ATM_IA_DEBUG flag, the driver can provide more debug trace if needed. There is a bit mask variable, IADebugFlag, which controls the output of the traces. You can find the bit map of the IADebugFlag in iphase.h. The debug trace can be turn on through the insmod command line option, for example, "insmod iphase.o IADebugFlag=0xffffffff" can turn on all the debug traces together with loading the driver.

6. Ia Driver Test Using ttcp_atm and PVC

   For the PVC setup, the test machines can either be connected back-to-back or through a switch. If connected through the switch, the switch must be configured for the PVC(s).

   - **a.** For UBR test:

     At the test machine intended to receive data, type:



     ```text
     ttcp_atm -r -a -s 0.100
     ```

     At the other test machine, type:



     ```text
     ttcp_atm -t -a -s 0.100 -n 10000
     ```

     Run "ttcp_atm -h" to display more options of the ttcp_atm tool.

   - **b.** For ABR test:

     It is the same as the UBR testing, but with an extra command option:



     ```text
     -Pabr:max_pcr=<xxx>
     ```

     where:

     > xxx = the maximum peak cell rate, from 170 - 353207.

     This option must be set on both the machines.

   - **c.** For CBR test:

     It is the same as the UBR testing, but with an extra command option:



     ```text
     -Pcbr:max_pcr=<xxx>
     ```

     where:

     > xxx = the maximum peak cell rate, from 170 - 353207.

     This option may only be set on the transmit machine.

<a id="rst-outstanding-issues"></a>

## Outstanding Issues

<a id="rst-contact-information"></a>

### Contact Information



```text
Customer Support:
    United States: Telephone:      (214) 654-5555
                   Fax:            (214) 654-5500
                   E-Mail:         intouch@iphase.com
    Europe:        Telephone:      33 (0)1 41 15 44 00
                   Fax:            33 (0)1 41 15 12 13
World Wide Web:    http://www.iphase.com
Anonymous FTP:     ftp.iphase.com
```

---

# Conexant AccessRunner configuration converter

_Peios Kernel / Internals / Networking / device_drivers / atm_

> Converts packed little-endian configuration values into the string accepted by the adsl_config sysfs attribute. Original format caveats remain in the source.

Converts packed little-endian configuration values into the string accepted by the adsl_config sysfs attribute. Original format caveats remain in the source.


```python
#!/usr/bin/env python
# Copyright 2009 Simon Arlott
#
# 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.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# Usage: cxacru-cf.py < cxacru-cf.bin
# Output: values string suitable for the sysfs adsl_config attribute
#
# Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110
# contains mis-aligned values which will stop the modem from being able
# to make a connection. If the first and last two bytes are removed then
# the values become valid, but the modulation will be forced to ANSI
# T1.413 only which may not be appropriate.
#
# The original binary format is a packed list of le32 values.

import sys
import struct

i = 0
while True:
	buf = sys.stdin.read(4)

	if len(buf) == 0:
		break
	elif len(buf) != 4:
		sys.stdout.write("\n")
		sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf)))
		sys.exit(1)

	if i > 0:
		sys.stdout.write(" ")
	sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0]))
	i += 1

sys.stdout.write("\n")

```

---

# Controller Area Network (CAN) Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / can_

> Device drivers for CAN devices.

<a id="rst-controller-area-network-can-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Device drivers for CAN devices.

Contents:

- [can327: ELM327 driver for Linux SocketCAN](</kernel/internals/networking/device-drivers-can/can327.md>)
- [CTU CAN FD Driver](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/can/ctu/ctucanfd-driver.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Flexcan CAN Controller driver](</kernel/internals/networking/device-drivers-can-freescale/flexcan.md>)

---

# can327: ELM327 driver for Linux SocketCAN

_Peios Kernel / Internals / Networking / device_drivers / can_

> Max Staudt <max@enpas.org>

<a id="rst-can327-elm327-driver-for-linux-socketcan"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause) -->

<a id="rst-authors"></a>

## Authors

Max Staudt &lt;[max@enpas.org](<mailto:max@enpas.org>)&gt;

<a id="rst-motivation"></a>

## Motivation

This driver aims to lower the initial cost for hackers interested in working with CAN buses.

CAN adapters are expensive, few, and far between. ELM327 interfaces are cheap and plentiful. Let's use ELM327s as CAN adapters.

<a id="rst-introduction"></a>

## Introduction

This driver is an effort to turn abundant ELM327 based OBD interfaces into full fledged (as far as possible) CAN interfaces.

Since the ELM327 was never meant to be a stand alone CAN controller, the driver has to switch between its modes as quickly as possible in order to fake full-duplex operation.

As such, can327 is a best effort driver. However, this is more than enough to implement simple request-response protocols (such as OBD II), and to monitor broadcast messages on a bus (such as in a vehicle).

Most ELM327s come as nondescript serial devices, attached via USB or Bluetooth. The driver cannot recognize them by itself, and as such it is up to the user to attach it in form of a TTY line discipline (similar to PPP, SLIP, slcan, ...).

This driver is meant for ELM327 versions 1.4b and up, see below for known limitations in older controllers and clones.

<a id="rst-data-sheet"></a>

## Data sheet

The official data sheets can be found at ELM electronics' home page:

> [https://www.elmelectronics.com/](<https://www.elmelectronics.com/>)

<a id="rst-how-to-attach-the-line-discipline"></a>

## How to attach the line discipline

Every ELM327 chip is factory programmed to operate at a serial setting of 38400 baud/s, 8 data bits, no parity, 1 stopbit.

If you have kept this default configuration, the line discipline can be attached on a command prompt as follows:



```text
sudo ldattach \
       --debug \
       --speed 38400 \
       --eightbits \
       --noparity \
       --onestopbit \
       --iflag -ICRNL,INLCR,-IXOFF \
       30 \
       /dev/ttyUSB0
```

To change the ELM327's serial settings, please refer to its data sheet. This needs to be done before attaching the line discipline.

Once the ldisc is attached, the CAN interface starts out unconfigured. Set the speed before starting it:



```text
# The interface needs to be down to change parameters
sudo ip link set can0 down
sudo ip link set can0 type can bitrate 500000
sudo ip link set can0 up
```

500000 bit/s is a common rate for OBD-II diagnostics. If you're connecting straight to a car's OBD port, this is the speed that most cars (but not all\!) expect.

After this, you can set out as usual with candump, cansniffer, etc.

<a id="rst-how-to-check-the-controller-version"></a>

## How to check the controller version

Use a terminal program to attach to the controller.

After issuing the "`AT WS`" command, the controller will respond with its version:



```text
>AT WS


ELM327 v1.4b

>
```

Note that clones may claim to be any version they like. It is not indicative of their actual feature set.

<a id="rst-communication-example"></a>

## Communication example

This is a short and incomplete introduction on how to talk to an ELM327. It is here to guide understanding of the controller's and the driver's limitation (listed below) as well as manual testing.

The ELM327 has two modes:

- Command mode

- Reception mode

In command mode, it expects one command per line, terminated by CR. By default, the prompt is a "`>`", after which a command can be entered:



```text
>ATE1
OK
>
```

The init script in the driver switches off several configuration options that are only meaningful in the original OBD scenario the chip is meant for, and are actually a hindrance for can327.

When a command is not recognized, such as by an older version of the ELM327, a question mark is printed as a response instead of OK:



```text
>ATUNKNOWN
?
>
```

At present, can327 does not evaluate this response. See the section below on known limitations for details.

When a CAN frame is to be sent, the target address is configured, after which the frame is sent as a command that consists of the data's hex dump:



```text
>ATSH123
OK
>DEADBEEF12345678
OK
>
```

The above interaction sends the SFF frame "`DE AD BE EF 12 34 56 78`" with (11 bit) CAN ID `0x123`. For this to function, the controller must be configured for SFF sending mode (using "`AT PB`", see code or datasheet).

Once a frame has been sent and wait-for-reply mode is on (`ATR1`, configured on `listen-only=off`), or when the reply timeout expires and the driver sets the controller into monitoring mode (`ATMA`), the ELM327 will send one line for each received CAN frame, consisting of CAN ID, DLC, and data:



```text
123 8 DEADBEEF12345678
```

For EFF (29 bit) CAN frames, the address format is slightly different, which can327 uses to tell the two apart:



```text
12 34 56 78 8 DEADBEEF12345678
```

The ELM327 will receive both SFF and EFF frames - the current CAN config (`ATPB`) does not matter.

If the ELM327's internal UART sending buffer runs full, it will abort the monitoring mode, print "BUFFER FULL" and drop back into command mode. Note that in this case, unlike with other error messages, the error message may appear on the same line as the last (usually incomplete) data frame:



```text
12 34 56 78 8 DEADBEEF123 BUFFER FULL
```

<a id="rst-known-limitations-of-the-controller"></a>

## Known limitations of the controller

- Clone devices ("v1.5" and others)

  Sending RTR frames is not supported and will be dropped silently.

  Receiving RTR with DLC 8 will appear to be a regular frame with the last received frame's DLC and payload.

  "`AT CSM`" (CAN Silent Monitoring, i.e. don't send CAN ACKs) is not supported, and is hard coded to ON. Thus, frames are not ACKed while listening: "`AT MA`" (Monitor All) will always be "silent". However, immediately after sending a frame, the ELM327 will be in "receive reply" mode, in which it *does* ACK any received frames. Once the bus goes silent, or an error occurs (such as BUFFER FULL), or the receive reply timeout runs out, the ELM327 will end reply reception mode on its own and can327 will fall back to "`AT MA`" in order to keep monitoring the bus.

  Other limitations may apply, depending on the clone and the quality of its firmware.

- All versions

  No full duplex operation is supported. The driver will switch between input/output mode as quickly as possible.

  The length of outgoing RTR frames cannot be set. In fact, some clones (tested with one identifying as "`v1.5`") are unable to send RTR frames at all.

  We don't have a way to get real-time notifications on CAN errors. While there is a command (`AT CS`) to retrieve some basic stats, we don't poll it as it would force us to interrupt reception mode.

- Versions prior to 1.4b

  These versions do not send CAN ACKs when in monitoring mode (AT MA). However, they do send ACKs while waiting for a reply immediately after sending a frame. The driver maximizes this time to make the controller as useful as possible.

  Starting with version 1.4b, the ELM327 supports the "`AT CSM`" command, and the "listen-only" CAN option will take effect.

- Versions prior to 1.4

  These chips do not support the "`AT PB`" command, and thus cannot change bitrate or SFF/EFF mode on-the-fly. This will have to be programmed by the user before attaching the line discipline. See the data sheet for details.

- Versions prior to 1.3

  These chips cannot be used at all with can327. They do not support the "`AT D1`" command, which is necessary to avoid parsing conflicts on incoming data, as well as distinction of RTR frame lengths.

  Specifically, this allows for easy distinction of SFF and EFF frames, and to check whether frames are complete. While it is possible to deduce the type and length from the length of the line the ELM327 sends us, this method fails when the ELM327's UART output buffer overruns. It may abort sending in the middle of the line, which will then be mistaken for something else.

<a id="rst-known-limitations-of-the-driver"></a>

## Known limitations of the driver

- No 8/7 timing.

  ELM327 can only set CAN bitrates that are of the form 500000/n, where n is an integer divisor. However there is an exception: With a separate flag, it may set the speed to be 8/7 of the speed indicated by the divisor. This mode is not currently implemented.

- No evaluation of command responses.

  The ELM327 will reply with OK when a command is understood, and with ? when it is not. The driver does not currently check this, and simply assumes that the chip understands every command. The driver is built such that functionality degrades gracefully nevertheless. See the section on known limitations of the controller.

- No use of hardware CAN ID filtering

  An ELM327's UART sending buffer will easily overflow on heavy CAN bus load, resulting in the "`BUFFER FULL`" message. Using the hardware filters available through "`AT CF xxx`" and "`AT CM xxx`" would be helpful here, however SocketCAN does not currently provide a facility to make use of such hardware features.

<a id="rst-rationale-behind-the-chosen-configuration"></a>

## Rationale behind the chosen configuration

- **`AT E1`**

  Echo on

  We need this to be able to get a prompt reliably.

- **`AT S1`**

  Spaces on

  We need this to distinguish 11/29 bit CAN addresses received.

  Note: We can usually do this using the line length (odd/even), but this fails if the line is not transmitted fully to the host (BUFFER FULL).

- **`AT D1`**

  DLC on

  We need this to tell the "length" of RTR frames.

<a id="rst-a-note-on-can-bus-termination"></a>

## A note on CAN bus termination

Your adapter may have resistors soldered in which are meant to terminate the bus. This is correct when it is plugged into a OBD-II socket, but not helpful when trying to tap into the middle of an existing CAN bus.

If communications don't work with the adapter connected, check for the termination resistors on its PCB and try removing them.

---

# CTU CAN FD Driver

_Peios Kernel / Internals / Networking / device_drivers / can / ctu_

> Author: Martin Jerabek <martin.jerabek01@gmail.com>

<a id="rst-ctu-can-fd-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

Author: Martin Jerabek &lt;[martin.jerabek01@gmail.com](<mailto:martin.jerabek01@gmail.com>)&gt;

<a id="rst-about-ctu-can-fd-ip-core"></a>

## About CTU CAN FD IP Core

[CTU CAN FD](<https://gitlab.fel.cvut.cz/canbus/ctucanfd_ip_core>)<a id="rst-ctu-can-fd"></a> is an open source soft core written in VHDL. It originated in 2015 as Ondrej Ille's project at the [Department of Measurement](<https://meas.fel.cvut.cz/>)<a id="rst-department-of-measurement"></a> of [FEE](<http://www.fel.cvut.cz/en/>)<a id="rst-fee"></a> at [CTU](<https://www.cvut.cz/en>)<a id="rst-ctu"></a>.

The SocketCAN driver for Xilinx Zynq SoC based MicroZed board [Vivado integration](<https://gitlab.fel.cvut.cz/canbus/zynq/zynq-can-sja1000-top>)<a id="rst-vivado-integration"></a> and Intel Cyclone V 5CSEMA4U23C6 based DE0-Nano-SoC Terasic board [QSys integration](<https://gitlab.fel.cvut.cz/canbus/intel-soc-ctucanfd>)<a id="rst-qsys-integration"></a> has been developed as well as support for [PCIe integration](<https://gitlab.fel.cvut.cz/canbus/pcie-ctucanfd>)<a id="rst-pcie-integration"></a> of the core.

In the case of Zynq, the core is connected via the APB system bus, which does not have enumeration support, and the device must be specified in Device Tree. This kind of devices is called platform device in the kernel and is handled by a platform device driver.

The basic functional model of the CTU CAN FD peripheral has been accepted into QEMU mainline. See QEMU [CAN emulation support](<https://www.qemu.org/docs/master/system/devices/can.html>)<a id="rst-can-emulation-support"></a> for CAN FD buses, host connection and CTU CAN FD core emulation. The development version of emulation support can be cloned from ctu-canfd branch of QEMU local development [repository](<https://gitlab.fel.cvut.cz/canbus/qemu-canbus>)<a id="rst-repository"></a>.

<a id="rst-about-socketcan"></a>

## About SocketCAN

SocketCAN is a standard common interface for CAN devices in the Linux kernel. As the name suggests, the bus is accessed via sockets, similarly to common network devices. The reasoning behind this is in depth described in [Linux SocketCAN](<https://www.kernel.org/doc/html/latest/networking/can.html>)<a id="rst-linux-socketcan"></a>. In short, it offers a natural way to implement and work with higher layer protocols over CAN, in the same way as, e.g., UDP/IP over Ethernet.

<a id="rst-device-probe"></a>

### Device probe

Before going into detail about the structure of a CAN bus device driver, let's reiterate how the kernel gets to know about the device at all. Some buses, like PCI or PCIe, support device enumeration. That is, when the system boots, it discovers all the devices on the bus and reads their configuration. The kernel identifies the device via its vendor ID and device ID, and if there is a driver registered for this identifier combination, its probe method is invoked to populate the driver's instance for the given hardware. A similar situation goes with USB, only it allows for device hot-plug.

The situation is different for peripherals which are directly embedded in the SoC and connected to an internal system bus (AXI, APB, Avalon, and others). These buses do not support enumeration, and thus the kernel has to learn about the devices from elsewhere. This is exactly what the Device Tree was made for.

<a id="rst-device-tree"></a>

### Device tree

An entry in device tree states that a device exists in the system, how it is reachable (on which bus it resides) and its configuration – registers address, interrupts and so on. An example of such a device tree is given in .



```text
/ {
    /* ... */
    amba: amba {
        #address-cells = <1>;
        #size-cells = <1>;
        compatible = "simple-bus";

        CTU_CAN_FD_0: CTU_CAN_FD@43c30000 {
            compatible = "ctu,ctucanfd";
            interrupt-parent = <&intc>;
            interrupts = <0 30 4>;
            clocks = <&clkc 15>;
            reg = <0x43c30000 0x10000>;
        };
    };
};
```

<a id="rst-driver-structure"></a>
<a id="rst-sec-socketcan-drv"></a>

### Driver structure

The driver can be divided into two parts – platform-dependent device discovery and set up, and platform-independent CAN network device implementation.

<a id="rst-platform-device-driver"></a>
<a id="rst-sec-socketcan-platdev"></a>

#### Platform device driver

In the case of Zynq, the core is connected via the AXI system bus, which does not have enumeration support, and the device must be specified in Device Tree. This kind of devices is called <em>platform device</em> in the kernel and is handled by a <em>platform device driver</em> <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1).

A platform device driver provides the following things:

- A <em>probe</em> function

- A <em>remove</em> function

- A table of <em>compatible</em> devices that the driver can handle

The <em>probe</em> function is called exactly once when the device appears (or the driver is loaded, whichever happens later). If there are more devices handled by the same driver, the <em>probe</em> function is called for each one of them. Its role is to allocate and initialize resources required for handling the device, as well as set up low-level functions for the platform-independent layer, e.g., <em>read\_reg</em> and <em>write\_reg</em>. After that, the driver registers the device to a higher layer, in our case as a <em>network device</em>.

The <em>remove</em> function is called when the device disappears, or the driver is about to be unloaded. It serves to free the resources allocated in <em>probe</em> and to unregister the device from higher layers.

Finally, the table of <em>compatible</em> devices states which devices the driver can handle. The Device Tree entry `compatible` is matched against the tables of all <em>platform drivers</em>.



```c
/* Match table for OF platform binding */
static const struct of_device_id ctucan_of_match[] = {
    { .compatible = "ctu,canfd-2", },
    { .compatible = "ctu,ctucanfd", },
    { /* end of list */ },
};
MODULE_DEVICE_TABLE(of, ctucan_of_match);

static int ctucan_probe(struct platform_device *pdev);
static int ctucan_remove(struct platform_device *pdev);

static struct platform_driver ctucanfd_driver = {
    .probe  = ctucan_probe,
    .remove = ctucan_remove,
    .driver = {
        .name = DRIVER_NAME,
        .of_match_table = ctucan_of_match,
    },
};
module_platform_driver(ctucanfd_driver);
```

<a id="rst-network-device-driver"></a>
<a id="rst-sec-socketcan-netdev"></a>

#### Network device driver

Each network device must support at least these operations:

- Bring the device up: `ndo_open`

- Bring the device down: `ndo_close`

- Submit TX frames to the device: `ndo_start_xmit`

- Signal TX completion and errors to the network subsystem: ISR

- Submit RX frames to the network subsystem: ISR and NAPI

There are two possible event sources: the device and the network subsystem. Device events are usually signaled via an interrupt, handled in an Interrupt Service Routine (ISR). Handlers for the events originating in the network subsystem are then specified in `struct net_device_ops`.

When the device is brought up, e.g., by calling `ip link set can0 up`, the driver’s function `ndo_open` is called. It should validate the interface configuration and configure and enable the device. The analogous opposite is `ndo_close`, called when the device is being brought down, be it explicitly or implicitly.

When the system should transmit a frame, it does so by calling `ndo_start_xmit`, which enqueues the frame into the device. If the device HW queue (FIFO, mailboxes or whatever the implementation is) becomes full, the `ndo_start_xmit` implementation informs the network subsystem that it should stop the TX queue (via `netif_stop_queue`). It is then re-enabled later in ISR when the device has some space available again and is able to enqueue another frame.

All the device events are handled in ISR, namely:

1. <strong>TX completion</strong>. When the device successfully finishes transmitting a frame, the frame is echoed locally. On error, an informative error frame <a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) is sent to the network subsystem instead. In both cases, the software TX queue is resumed so that more frames may be sent.

2. <strong>Error condition</strong>. If something goes wrong (e.g., the device goes bus-off or RX overrun happens), error counters are updated, and informative error frames are enqueued to SW RX queue.

3. <strong>RX buffer not empty</strong>. In this case, read the RX frames and enqueue them to SW RX queue. Usually NAPI is used as a middle layer (see ).

<a id="rst-napi"></a>
<a id="rst-sec-socketcan-napi"></a>

### NAPI

The frequency of incoming frames can be high and the overhead to invoke the interrupt service routine for each frame can cause significant system load. There are multiple mechanisms in the Linux kernel to deal with this situation. They evolved over the years of Linux kernel development and enhancements. For network devices, the current standard is NAPI – <em>the New API</em>. It is similar to classical top-half/bottom-half interrupt handling in that it only acknowledges the interrupt in the ISR and signals that the rest of the processing should be done in softirq context. On top of that, it offers the possibility to <em>poll</em> for new frames for a while. This has a potential to avoid the costly round of enabling interrupts, handling an incoming IRQ in ISR, re-enabling the softirq and switching context back to softirq.

See [Documentation/networking/napi.rst](<#rst-napi>) for more information.

<a id="rst-integrating-the-core-to-xilinx-zynq"></a>

## Integrating the core to Xilinx Zynq

The core interfaces a simple subset of the Avalon (search for Intel <strong>Avalon Interface Specifications</strong>) bus as it was originally used on Alterra FPGA chips, yet Xilinx natively interfaces with AXI (search for ARM <strong>AMBA AXI and ACE Protocol Specification AXI3, AXI4, and AXI4-Lite, ACE and ACE-Lite</strong>). The most obvious solution would be to use an Avalon/AXI bridge or implement some simple conversion entity. However, the core’s interface is half-duplex with no handshake signaling, whereas AXI is full duplex with two-way signaling. Moreover, even AXI-Lite slave interface is quite resource-intensive, and the flexibility and speed of AXI are not required for a CAN core.

Thus a much simpler bus was chosen – APB (Advanced Peripheral Bus) (search for ARM <strong>AMBA APB Protocol Specification</strong>). APB-AXI bridge is directly available in Xilinx Vivado, and the interface adaptor entity is just a few simple combinatorial assignments.

Finally, to be able to include the core in a block diagram as a custom IP, the core, together with the APB interface, has been packaged as a Vivado component.

<a id="rst-ctu-can-fd-driver-design"></a>

## CTU CAN FD Driver design

The general structure of a CAN device driver has already been examined in . The next paragraphs provide a more detailed description of the CTU CAN FD core driver in particular.

<a id="rst-low-level-driver"></a>

### Low-level driver

The core is not intended to be used solely with SocketCAN, and thus it is desirable to have an OS-independent low-level driver. This low-level driver can then be used in implementations of OS driver or directly either on bare metal or in a user-space application. Another advantage is that if the hardware slightly changes, only the low-level driver needs to be modified.

The code <a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3) is in part automatically generated and in part written manually by the core author, with contributions of the thesis’ author. The low-level driver supports operations such as: set bit timing, set controller mode, enable/disable, read RX frame, write TX frame, and so on.

<a id="rst-configuring-bit-timing"></a>

### Configuring bit timing

On CAN, each bit is divided into four segments: SYNC, PROP, PHASE1, and PHASE2. Their duration is expressed in multiples of a Time Quantum (details in [CAN Specification, Version 2.0](<http://esd.cs.ucr.edu/webres/can20.pdf>)<a id="rst-can-specification-version-2-0"></a>, chapter 8). When configuring bitrate, the durations of all the segments (and time quantum) must be computed from the bitrate and Sample Point. This is performed independently for both the Nominal bitrate and Data bitrate for CAN FD.

SocketCAN is fairly flexible and offers either highly customized configuration by setting all the segment durations manually, or a convenient configuration by setting just the bitrate and sample point (and even that is chosen automatically per Bosch recommendation if not specified). However, each CAN controller may have different base clock frequency and different width of segment duration registers. The algorithm thus needs the minimum and maximum values for the durations (and clock prescaler) and tries to optimize the numbers to fit both the constraints and the requested parameters.



```c
struct can_bittiming_const {
    char name[16];      /* Name of the CAN controller hardware */
    __u32 tseg1_min;    /* Time segment 1 = prop_seg + phase_seg1 */
    __u32 tseg1_max;
    __u32 tseg2_min;    /* Time segment 2 = phase_seg2 */
    __u32 tseg2_max;
    __u32 sjw_max;      /* Synchronisation jump width */
    __u32 brp_min;      /* Bit-rate prescaler */
    __u32 brp_max;
    __u32 brp_inc;
};
```

\[lst:can\_bittiming\_const\]

A curious reader will notice that the durations of the segments PROP\_SEG and PHASE\_SEG1 are not determined separately but rather combined and then, by default, the resulting TSEG1 is evenly divided between PROP\_SEG and PHASE\_SEG1. In practice, this has virtually no consequences as the sample point is between PHASE\_SEG1 and PHASE\_SEG2. In CTU CAN FD, however, the duration registers `PROP` and `PH1` have different widths (6 and 7 bits, respectively), so the auto-computed values might overflow the shorter register and must thus be redistributed among the two <a id="rst-footnote-reference-4"></a>[4](#rst-footnote-4).

<a id="rst-handling-rx"></a>

### Handling RX

Frame reception is handled in NAPI queue, which is enabled from ISR when the RXNE (RX FIFO Not Empty) bit is set. Frames are read one by one until either no frame is left in the RX FIFO or the maximum work quota has been reached for the NAPI poll run (see ). Each frame is then passed to the network interface RX queue.

An incoming frame may be either a CAN 2.0 frame or a CAN FD frame. The way to distinguish between these two in the kernel is to allocate either `struct can_frame` or `struct canfd_frame`, the two having different sizes. In the controller, the information about the frame type is stored in the first word of RX FIFO.

This brings us a chicken-egg problem: we want to allocate the `skb` for the frame, and only if it succeeds, fetch the frame from FIFO; otherwise keep it there for later. But to be able to allocate the correct `skb`, we have to fetch the first work of FIFO. There are several possible solutions:

1. Read the word, then allocate. If it fails, discard the rest of the frame. When the system is low on memory, the situation is bad anyway.

2. Always allocate `skb` big enough for an FD frame beforehand. Then tweak the `skb` internals to look like it has been allocated for the smaller CAN 2.0 frame.

3. Add option to peek into the FIFO instead of consuming the word.

4. If the allocation fails, store the read word into driver’s data. On the next try, use the stored word instead of reading it again.

Option 1 is simple enough, but not very satisfying if we could do better. Option 2 is not acceptable, as it would require modifying the private state of an integral kernel structure. The slightly higher memory consumption is just a virtual cherry on top of the “cake”. Option 3 requires non-trivial HW changes and is not ideal from the HW point of view.

Option 4 seems like a good compromise, with its disadvantage being that a partial frame may stay in the FIFO for a prolonged time. Nonetheless, there may be just one owner of the RX FIFO, and thus no one else should see the partial frame (disregarding some exotic debugging scenarios). Basides, the driver resets the core on its initialization, so the partial frame cannot be “adopted” either. In the end, option 4 was selected <a id="rst-footnote-reference-5"></a>[5](#rst-footnote-5).

<a id="rst-timestamping-rx-frames"></a>
<a id="rst-subsec-ctucanfd-rxtimestamp"></a>

#### Timestamping RX frames

The CTU CAN FD core reports the exact timestamp when the frame has been received. The timestamp is by default captured at the sample point of the last bit of EOF but is configurable to be captured at the SOF bit. The timestamp source is external to the core and may be up to 64 bits wide. At the time of writing, passing the timestamp from kernel to userspace is not yet implemented, but is planned in the future.

<a id="rst-handling-tx"></a>

### Handling TX

The CTU CAN FD core has 4 independent TX buffers, each with its own state and priority. When the core wants to transmit, a TX buffer in Ready state with the highest priority is selected.

The priorities are 3bit numbers in register TX\_PRIORITY (nibble-aligned). This should be flexible enough for most use cases. SocketCAN, however, supports only one FIFO queue for outgoing frames <a id="rst-footnote-reference-6"></a>[6](#rst-footnote-6). The buffer priorities may be used to simulate the FIFO behavior by assigning each buffer a distinct priority and <em>rotating</em> the priorities after a frame transmission is completed.

In addition to priority rotation, the SW must maintain head and tail pointers into the FIFO formed by the TX buffers to be able to determine which buffer should be used for next frame (`txb_head`) and which should be the first completed one (`txb_tail`). The actual buffer indices are (obviously) modulo 4 (number of TX buffers), but the pointers must be at least one bit wider to be able to distinguish between FIFO full and FIFO empty – in this situation, $`txb\_head \equiv txb\_tail\ (\textrm{mod}\ 4)`$. An example of how the FIFO is maintained, together with priority rotation, is depicted in


<table>
<thead>
<tr>
<th>



TXB\#

</th>
<th>



0

</th>
<th>



1

</th>
<th>



2

</th>
<th>



3

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



Seq

</td>
<td>



A

</td>
<td>



B

</td>
<td>



C

</td>
<td>





</td>
</tr>
<tr>
<td>



Prio

</td>
<td>



7

</td>
<td>



6

</td>
<td>



5

</td>
<td>



4

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>



T

</td>
<td>





</td>
<td>



H

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>



TXB\#

</th>
<th>



0

</th>
<th>



1

</th>
<th>



2

</th>
<th>



3

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



Seq

</td>
<td>





</td>
<td>



B

</td>
<td>



C

</td>
<td>





</td>
</tr>
<tr>
<td>



Prio

</td>
<td>



4

</td>
<td>



7

</td>
<td>



6

</td>
<td>



5

</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>



T

</td>
<td>





</td>
<td>



H

</td>
</tr>
</tbody>
</table>


<table>
<thead>
<tr>
<th>



TXB\#

</th>
<th>



0

</th>
<th>



1

</th>
<th>



2

</th>
<th>



3

</th>
<th>



0’

</th>
</tr>
</thead>
<tbody>
<tr>
<td>



Seq

</td>
<td>



E

</td>
<td>



B

</td>
<td>



C

</td>
<td>



D

</td>
<td>





</td>
</tr>
<tr>
<td>



Prio

</td>
<td>



4

</td>
<td>



7

</td>
<td>



6

</td>
<td>



5

</td>
<td>





</td>
</tr>
<tr>
<td>





</td>
<td>





</td>
<td>



T

</td>
<td>





</td>
<td>





</td>
<td>



H

</td>
</tr>
</tbody>
</table>

![](/kernel/internals/networking/device-drivers-can-ctu/asset-8dd006b482cb-fsm-txt-buffer-user.svg)

TX Buffer states with possible transitions

<a id="rst-timestamping-tx-frames"></a>
<a id="rst-subsec-ctucanfd-txtimestamp"></a>

#### Timestamping TX frames

When submitting a frame to a TX buffer, one may specify the timestamp at which the frame should be transmitted. The frame transmission may start later, but not sooner. Note that the timestamp does not participate in buffer prioritization – that is decided solely by the mechanism described above.

Support for time-based packet transmission was recently merged to Linux v4.19 [Time-based packet transmission](<https://lwn.net/Articles/748879/>)<a id="rst-time-based-packet-transmission"></a>, but it remains yet to be researched whether this functionality will be practical for CAN.

Also similarly to retrieving the timestamp of RX frames, the core supports retrieving the timestamp of TX frames – that is the time when the frame was successfully delivered. The particulars are very similar to timestamping RX frames and are described in .

<a id="rst-handling-rx-buffer-overrun"></a>

### Handling RX buffer overrun

When a received frame does no more fit into the hardware RX FIFO in its entirety, RX FIFO overrun flag (STATUS\[DOR\]) is set and Data Overrun Interrupt (DOI) is triggered. When servicing the interrupt, care must be taken first to clear the DOR flag (via COMMAND\[CDO\]) and after that clear the DOI interrupt flag. Otherwise, the interrupt would be immediately <a id="rst-footnote-reference-7"></a>[7](#rst-footnote-7) rearmed.

<strong>Note</strong>: During development, it was discussed whether the internal HW pipelining cannot disrupt this clear sequence and whether an additional dummy cycle is necessary between clearing the flag and the interrupt. On the Avalon interface, it indeed proved to be the case, but APB being safe because it uses 2-cycle transactions. Essentially, the DOR flag would be cleared, but DOI register’s Preset input would still be high the cycle when the DOI clear request would also be applied (by setting the register’s Reset input high). As Set had higher priority than Reset, the DOI flag would not be reset. This has been already fixed by swapping the Set/Reset priority (see issue \#187).

<a id="rst-reporting-error-passive-and-bus-off-conditions"></a>

### Reporting Error Passive and Bus Off conditions

It may be desirable to report when the node reaches <em>Error Passive</em>, <em>Error Warning</em>, and <em>Bus Off</em> conditions. The driver is notified about error state change by an interrupt (EPI, EWLI), and then proceeds to determine the core’s error state by reading its error counters.

There is, however, a slight race condition here – there is a delay between the time when the state transition occurs (and the interrupt is triggered) and when the error counters are read. When EPI is received, the node may be either <em>Error Passive</em> or <em>Bus Off</em>. If the node goes <em>Bus Off</em>, it obviously remains in the state until it is reset. Otherwise, the node is <em>or was</em> <em>Error Passive</em>. However, it may happen that the read state is <em>Error Warning</em> or even <em>Error Active</em>. It may be unclear whether and what exactly to report in that case, but I personally entertain the idea that the past error condition should still be reported. Similarly, when EWLI is received but the state is later detected to be <em>Error Passive</em>, <em>Error Passive</em> should be reported.

<a id="rst-ctu-can-fd-driver-sources-reference"></a>

## CTU CAN FD Driver Sources Reference


#### <a id="c-ctucan_probe_common"></a>`ctucan_probe_common()`

```c
int ctucan_probe_common(struct device *dev, void __iomem *addr, int irq, unsigned int ntxbufs, unsigned long can_clk_rate, int pm_enable_call, void (*set_drvdata_fnc)(struct device *dev, struct net_device *ndev))
```

Device type independent registration call

**Parameters**

- `struct device *dev`: Handle to the generic device structure
- `void __iomem *addr`: Base address of CTU CAN FD core address
- `int irq`: Interrupt number
- `unsigned int ntxbufs`: Number of implemented Tx buffers
- `unsigned long can_clk_rate`: Clock rate, if 0 then clock are taken from device node
- `int pm_enable_call`: Whether pm_runtime_enable should be called
- `void (*set_drvdata_fnc)(struct device *dev, struct net_device *ndev)`: Function to set network driver data for physical device

**Description**

This function does all the memory allocation and registration for the CAN
device.

**Return**

0 on success and failure value on error



#### <a id="c-ctucan_state_to_str"></a>`ctucan_state_to_str()`

```c
const char * ctucan_state_to_str(enum can_state state)
```

Converts CAN controller state code to corresponding text

**Parameters**

- `enum can_state state`: CAN controller state code

**Return**

Pointer to string representation of the error state

#### <a id="c-ctucan_reset"></a>`ctucan_reset()`

```c
int ctucan_reset(struct net_device *ndev)
```

Issues software reset request to CTU CAN FD

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Return**

0 for success, -`ETIMEDOUT` if CAN controller does not leave reset

#### <a id="c-ctucan_set_btr"></a>`ctucan_set_btr()`

```c
int ctucan_set_btr(struct net_device *ndev, struct can_bittiming *bt, bool nominal)
```

Sets CAN bus bit timing in CTU CAN FD

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure
- `struct can_bittiming *bt`: Pointer to Bit timing structure
- `bool nominal`: True - Nominal bit timing, False - Data bit timing

**Return**

0 - OK, -`EPERM` if controller is enabled

#### <a id="c-ctucan_set_bittiming"></a>`ctucan_set_bittiming()`

```c
int ctucan_set_bittiming(struct net_device *ndev)
```

CAN set nominal bit timing routine

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Return**

0 on success, -`EPERM` on error

#### <a id="c-ctucan_set_data_bittiming"></a>`ctucan_set_data_bittiming()`

```c
int ctucan_set_data_bittiming(struct net_device *ndev)
```

CAN set data bit timing routine

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Return**

0 on success, -`EPERM` on error

#### <a id="c-ctucan_set_secondary_sample_point"></a>`ctucan_set_secondary_sample_point()`

```c
int ctucan_set_secondary_sample_point(struct net_device *ndev)
```

Sets secondary sample point in CTU CAN FD

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Return**

0 on success, -`EPERM` if controller is enabled

#### <a id="c-ctucan_set_mode"></a>`ctucan_set_mode()`

```c
void ctucan_set_mode(struct ctucan_priv *priv, const struct can_ctrlmode *mode)
```

Sets CTU CAN FDs mode

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `const struct can_ctrlmode *mode`: Pointer to controller modes to be set

#### <a id="c-ctucan_chip_start"></a>`ctucan_chip_start()`

```c
int ctucan_chip_start(struct net_device *ndev)
```

This routine starts the driver

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Description**

Routine expects that chip is in reset state. It setups initial
Tx buffers for FIFO priorities, sets bittiming, enables interrupts,
switches core to operational mode and changes controller
state to `CAN_STATE_STOPPED`.

**Return**

0 on success and failure value on error

#### <a id="c-ctucan_do_set_mode"></a>`ctucan_do_set_mode()`

```c
int ctucan_do_set_mode(struct net_device *ndev, enum can_mode mode)
```

Sets mode of the driver

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure
- `enum can_mode mode`: Tells the mode of the driver

**Description**

This check the drivers state and calls the corresponding modes to set.

**Return**

0 on success and failure value on error

#### <a id="c-ctucan_get_tx_status"></a>`ctucan_get_tx_status()`

```c
enum ctucan_txtb_status ctucan_get_tx_status(struct ctucan_priv *priv, u8 buf)
```

Gets status of TXT buffer

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `u8 buf`: Buffer index (0-based)

**Return**

Status of TXT buffer

#### <a id="c-ctucan_is_txt_buf_writable"></a>`ctucan_is_txt_buf_writable()`

```c
bool ctucan_is_txt_buf_writable(struct ctucan_priv *priv, u8 buf)
```

Checks if frame can be inserted to TXT Buffer

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `u8 buf`: Buffer index (0-based)

**Return**

True - Frame can be inserted to TXT Buffer, False - If attempted, frame will not be
inserted to TXT Buffer

#### <a id="c-ctucan_insert_frame"></a>`ctucan_insert_frame()`

```c
bool ctucan_insert_frame(struct ctucan_priv *priv, const struct canfd_frame *cf, u8 buf, bool isfdf)
```

Inserts frame to TXT buffer

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `const struct canfd_frame *cf`: Pointer to CAN frame to be inserted
- `u8 buf`: TXT Buffer index to which frame is inserted (0-based)
- `bool isfdf`: True - CAN FD Frame, False - CAN 2.0 Frame

**Return**

* True - Frame inserted successfully
* False - Frame was not inserted due to one of:
  1. TXT Buffer is not writable (it is in wrong state)
  2. Invalid TXT buffer index
  3. Invalid frame length

#### <a id="c-ctucan_give_txtb_cmd"></a>`ctucan_give_txtb_cmd()`

```c
void ctucan_give_txtb_cmd(struct ctucan_priv *priv, enum ctucan_txtb_command cmd, u8 buf)
```

Applies command on TXT buffer

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `enum ctucan_txtb_command cmd`: Command to give
- `u8 buf`: Buffer index (0-based)

#### <a id="c-ctucan_start_xmit"></a>`ctucan_start_xmit()`

```c
netdev_tx_t ctucan_start_xmit(struct sk_buff *skb, struct net_device *ndev)
```

Starts the transmission

**Parameters**

- `struct sk_buff *skb`: sk_buff pointer that contains data to be Txed
- `struct net_device *ndev`: Pointer to net_device structure

**Description**

Invoked from upper layers to initiate transmission. Uses the next available free TXT Buffer and
populates its fields to start the transmission.

**Return**

`NETDEV_TX_OK` on success, `NETDEV_TX_BUSY` when no free TXT buffer is available,
negative return values reserved for error cases

#### <a id="c-ctucan_read_rx_frame"></a>`ctucan_read_rx_frame()`

```c
void ctucan_read_rx_frame(struct ctucan_priv *priv, struct canfd_frame *cf, u32 ffw)
```

Reads frame from RX FIFO

**Parameters**

- `struct ctucan_priv *priv`: Pointer to CTU CAN FD's private data
- `struct canfd_frame *cf`: Pointer to CAN frame struct
- `u32 ffw`: Previously read frame format word

**Note**

Frame format word must be read separately and provided in 'ffw'.

#### <a id="c-ctucan_rx"></a>`ctucan_rx()`

```c
int ctucan_rx(struct net_device *ndev)
```

Called from CAN ISR to complete the received frame processing

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Description**

This function is invoked from the CAN isr(poll) to process the Rx frames. It does minimal
processing and invokes "netif_receive_skb" to complete further processing.

**Return**

1 when frame is passed to the network layer, 0 when the first frame word is read but
system is out of free SKBs temporally and left code to resolve SKB allocation later,
-`EAGAIN` in a case of empty Rx FIFO.

#### <a id="c-ctucan_read_fault_state"></a>`ctucan_read_fault_state()`

```c
enum can_state ctucan_read_fault_state(struct ctucan_priv *priv)
```

Reads CTU CAN FDs fault confinement state.

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data

**Return**

Fault confinement state of controller

#### <a id="c-ctucan_get_rec_tec"></a>`ctucan_get_rec_tec()`

```c
void ctucan_get_rec_tec(struct ctucan_priv *priv, struct can_berr_counter *bec)
```

Reads REC/TEC counter values from controller

**Parameters**

- `struct ctucan_priv *priv`: Pointer to private data
- `struct can_berr_counter *bec`: Pointer to Error counter structure

#### <a id="c-ctucan_err_interrupt"></a>`ctucan_err_interrupt()`

```c
void ctucan_err_interrupt(struct net_device *ndev, u32 isr)
```

Error frame ISR

**Parameters**

- `struct net_device *ndev`: net_device pointer
- `u32 isr`: interrupt status register value

**Description**

This is the CAN error interrupt and it will check the type of error and forward the error
frame to upper layers.

#### <a id="c-ctucan_rx_poll"></a>`ctucan_rx_poll()`

```c
int ctucan_rx_poll(struct napi_struct *napi, int quota)
```

Poll routine for rx packets (NAPI)

**Parameters**

- `struct napi_struct *napi`: NAPI structure pointer
- `int quota`: Max number of rx packets to be processed.

**Description**

This is the poll routine for rx part. It will process the packets maximux quota value.

**Return**

Number of packets received

#### <a id="c-ctucan_rotate_txb_prio"></a>`ctucan_rotate_txb_prio()`

```c
void ctucan_rotate_txb_prio(struct net_device *ndev)
```

Rotates priorities of TXT Buffers

**Parameters**

- `struct net_device *ndev`: net_device pointer

#### <a id="c-ctucan_tx_interrupt"></a>`ctucan_tx_interrupt()`

```c
void ctucan_tx_interrupt(struct net_device *ndev)
```

Tx done Isr

**Parameters**

- `struct net_device *ndev`: net_device pointer

#### <a id="c-ctucan_interrupt"></a>`ctucan_interrupt()`

```c
irqreturn_t ctucan_interrupt(int irq, void *dev_id)
```

CAN Isr

**Parameters**

- `int irq`: irq number
- `void *dev_id`: device id pointer

**Description**

This is the CTU CAN FD ISR. It checks for the type of interrupt
and invokes the corresponding ISR.

**Return**

IRQ_NONE - If CAN device is in sleep mode, IRQ_HANDLED otherwise

#### <a id="c-ctucan_chip_stop"></a>`ctucan_chip_stop()`

```c
void ctucan_chip_stop(struct net_device *ndev)
```

Driver stop routine

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Description**

This is the drivers stop routine. It will disable the
interrupts and disable the controller.

#### <a id="c-ctucan_open"></a>`ctucan_open()`

```c
int ctucan_open(struct net_device *ndev)
```

Driver open routine

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Description**

This is the driver open routine.

**Return**

0 on success and failure value on error

#### <a id="c-ctucan_close"></a>`ctucan_close()`

```c
int ctucan_close(struct net_device *ndev)
```

Driver close routine

**Parameters**

- `struct net_device *ndev`: Pointer to net_device structure

**Return**

0 always

#### <a id="c-ctucan_get_berr_counter"></a>`ctucan_get_berr_counter()`

```c
int ctucan_get_berr_counter(const struct net_device *ndev, struct can_berr_counter *bec)
```

error counter routine

**Parameters**

- `const struct net_device *ndev`: Pointer to net_device structure
- `struct can_berr_counter *bec`: Pointer to can_berr_counter structure

**Description**

This is the driver error counter routine.

**Return**

0 on success and failure value on error



#### <a id="c-ctucan_pci_probe"></a>`ctucan_pci_probe()`

```c
int ctucan_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
```

PCI registration call

**Parameters**

- `struct pci_dev *pdev`: Handle to the pci device structure
- `const struct pci_device_id *ent`: Pointer to the entry from ctucan_pci_tbl

**Description**

This function does all the memory allocation and registration for the CAN
device.

**Return**

0 on success and failure value on error

#### <a id="c-ctucan_pci_remove"></a>`ctucan_pci_remove()`

```c
void ctucan_pci_remove(struct pci_dev *pdev)
```

Unregister the device after releasing the resources

**Parameters**

- `struct pci_dev *pdev`: Handle to the pci device structure

**Description**

This function frees all the resources allocated to the device.

**Return**

0 always



#### <a id="c-ctucan_platform_probe"></a>`ctucan_platform_probe()`

```c
int ctucan_platform_probe(struct platform_device *pdev)
```

Platform registration call

**Parameters**

- `struct platform_device *pdev`: Handle to the platform device structure

**Description**

This function does all the memory allocation and registration for the CAN
device.

**Return**

0 on success and failure value on error

#### <a id="c-ctucan_platform_remove"></a>`ctucan_platform_remove()`

```c
void ctucan_platform_remove(struct platform_device *pdev)
```

Unregister the device after releasing the resources

**Parameters**

- `struct platform_device *pdev`: Handle to the platform device structure

**Description**

This function frees all the resources allocated to the device.

**Return**

0 always


<a id="rst-ctu-can-fd-ip-core-and-driver-development-acknowledgment"></a>

## CTU CAN FD IP Core and Driver Development Acknowledgment

- Odrej Ille &lt;[ondrej.ille@gmail.com](<mailto:ondrej.ille@gmail.com>)&gt;

  - started the project as student at Department of Measurement, FEE, CTU

  - invested great amount of personal time and enthusiasm to the project over years

  - worked on more funded tasks

- [Department of Measurement](<https://meas.fel.cvut.cz/>)<a id="rst-department-of-measurement-1"></a>, [Faculty of Electrical Engineering](<http://www.fel.cvut.cz/en/>)<a id="rst-faculty-of-electrical-engineering"></a>, [Czech Technical University](<https://www.cvut.cz/en>)<a id="rst-czech-technical-university"></a>

  - is the main investor into the project over many years

  - uses project in their CAN/CAN FD diagnostics framework for [Skoda Auto](<https://www.skoda-auto.cz/>)<a id="rst-skoda-auto"></a>

- [Digiteq Automotive](<https://www.digiteqautomotive.com/en>)<a id="rst-digiteq-automotive"></a>

  - funding of the project CAN FD Open Cores Support Linux Kernel Based Systems

  - negotiated and paid CTU to allow public access to the project

  - provided additional funding of the work

- [Department of Control Engineering](<https://control.fel.cvut.cz/en>)<a id="rst-department-of-control-engineering"></a>, [Faculty of Electrical Engineering](<http://www.fel.cvut.cz/en/>)<a id="rst-faculty-of-electrical-engineering-1"></a>, [Czech Technical University](<https://www.cvut.cz/en>)<a id="rst-czech-technical-university-1"></a>

  - solving the project CAN FD Open Cores Support Linux Kernel Based Systems

  - providing GitLab management

  - virtual servers and computational power for continuous integration

  - providing hardware for HIL continuous integration tests

- [PiKRON Ltd.](<http://pikron.com/>)<a id="rst-pikron-ltd"></a>

  - minor funding to initiate preparation of the project open-sourcing

- Petr Porazil &lt;[porazil@pikron.com](<mailto:porazil@pikron.com>)&gt;

  - design of PCIe transceiver addon board and assembly of boards

  - design and assembly of MZ\_APO baseboard for MicroZed/Zynq based system

- Martin Jerabek &lt;[martin.jerabek01@gmail.com](<mailto:martin.jerabek01@gmail.com>)&gt;

  - Linux driver development

  - continuous integration platform architect and GHDL updates

  - thesis [Open-source and Open-hardware CAN FD Protocol Support](<https://dspace.cvut.cz/bitstream/handle/10467/80366/F3-DP-2019-Jerabek-Martin-Jerabek-thesis-2019-canfd.pdf>)<a id="rst-open-source-and-open-hardware-can-fd-protocol-support"></a>

- Jiri Novak &lt;[jnovak@fel.cvut.cz](<mailto:jnovak@fel.cvut.cz>)&gt;

  - project initiation, management and use at Department of Measurement, FEE, CTU

- Pavel Pisa &lt;[pisa@cmp.felk.cvut.cz](<mailto:pisa@cmp.felk.cvut.cz>)&gt;

  - initiate open-sourcing, project coordination, management at Department of Control Engineering, FEE, CTU

- Jaroslav Beran&lt;[jara.beran@gmail.com](<mailto:jara.beran@gmail.com>)&gt;

> - system integration for Intel SoC, core and driver testing and updates

- Carsten Emde ([OSADL](<https://www.osadl.org/>)<a id="rst-osadl"></a>)

> - provided OSADL expertise to discuss IP core licensing
>
> - pointed to possible deadlock for LGPL and CAN bus possible patent case which lead to relicense IP core design to BSD like license

- Reiner Zitzmann and Holger Zeltwanger ([CAN in Automation](<https://www.can-cia.org/>)<a id="rst-can-in-automation"></a>)

> - provided suggestions and help to inform community about the project and invited us to events focused on CAN bus future development directions

- Jan Charvat

> - implemented CTU CAN FD functional model for QEMU which has been integrated into QEMU mainline ([docs/system/devices/can.rst](<https://www.qemu.org/docs/master/system/devices/can.html>)<a id="rst-docs-system-devices-can-rst"></a>)
>
> - Bachelor thesis Model of CAN FD Communication Controller for QEMU Emulator

<a id="rst-notes"></a>

## Notes

<a id="rst-footnote-1"></a>



**[1]** Other buses have their own specific driver interface to set up the device.

<a id="rst-footnote-2"></a>



**[2]** Not to be mistaken with CAN Error Frame. This is a `can_frame` with `CAN_ERR_FLAG` set and some error info in its `data` field.

<a id="rst-footnote-3"></a>



**[3]** Available in CTU CAN FD repository [https://gitlab.fel.cvut.cz/canbus/ctucanfd\_ip\_core](<https://gitlab.fel.cvut.cz/canbus/ctucanfd_ip_core>)<a id="rst-https-gitlab-fel-cvut-cz-canbus-ctucanfd-ip-core"></a>

<a id="rst-footnote-4"></a>



**[4]** As is done in the low-level driver functions `ctucan_hw_set_nom_bittiming` and `ctucan_hw_set_data_bittiming`.

<a id="rst-footnote-5"></a>



**[5]** At the time of writing this thesis, option 1 is still being used and the modification is queued in gitlab issue \#222

<a id="rst-footnote-6"></a>



**[6]** Strictly speaking, multiple CAN TX queues are supported since v4.19 [can: enable multi-queue for SocketCAN devices](<https://lore.kernel.org/patchwork/patch/913526/>)<a id="rst-can-enable-multi-queue-for-socketcan-devices"></a> but no mainline driver is using them yet.

<a id="rst-footnote-7"></a>



**[7]** Or rather in the next clock cycle

---

# Flexcan CAN Controller driver

_Peios Kernel / Internals / Networking / device_drivers / can / freescale_

> Authors: Marc Kleine-Budde <mkl@pengutronix.de>, Dario Binacchi <dario.binacchi@amarulasolutions.com>

<a id="rst-flexcan-can-controller-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Authors: Marc Kleine-Budde &lt;[mkl@pengutronix.de](<mailto:mkl@pengutronix.de>)&gt;, Dario Binacchi &lt;[dario.binacchi@amarulasolutions.com](<mailto:dario.binacchi@amarulasolutions.com>)&gt;

<a id="rst-on-off-rtr-frames-reception"></a>

## On/off RTR frames reception

For most flexcan IP cores the driver supports 2 RX modes:

- FIFO

- mailbox

The older flexcan cores (integrated into the i.MX25, i.MX28, i.MX35 and i.MX53 SOCs) only receive RTR frames if the controller is configured for RX-FIFO mode.

The RX FIFO mode uses a hardware FIFO with a depth of 6 CAN frames, while the mailbox mode uses a software FIFO with a depth of up to 62 CAN frames. With the help of the bigger buffer, the mailbox mode performs better under high system load situations.

As reception of RTR frames is part of the CAN standard, all flexcan cores come up in a mode where RTR reception is possible.

With the "rx-rtr" private flag the ability to receive RTR frames can be waived at the expense of losing the ability to receive RTR messages. This trade off is beneficial in certain use cases.

- **"rx-rtr" on**

  Receive RTR frames. (default)

  The CAN controller can and will receive RTR frames.

  On some IP cores the controller cannot receive RTR frames in the more performant "RX mailbox" mode and will use "RX FIFO" mode instead.

"rx-rtr" off

> Waive ability to receive RTR frames. (not supported on all IP cores)
>
> This mode activates the "RX mailbox mode" for better performance, on some IP cores RTR frames cannot be received anymore.

The setting can only be changed if the interface is down:



```text
ip link set dev can0 down
ethtool --set-priv-flags can0 rx-rtr {off|on}
ip link set dev can0 up
```

---

# Cellular Modem Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / cellular_

> Contents:

<a id="rst-cellular-modem-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [Rmnet Driver](</kernel/internals/networking/device-drivers-cellular-qualcomm/rmnet.md>)

---

# Rmnet Driver

_Peios Kernel / Internals / Networking / device_drivers / cellular / qualcomm_

> rmnet driver is used for supporting the Multiplexing and aggregation Protocol (MAP). This protocol is used by all recent chipsets using Qualcomm Technologies, Inc. modems.

<a id="rst-rmnet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## 1. Introduction

rmnet driver is used for supporting the Multiplexing and aggregation Protocol (MAP). This protocol is used by all recent chipsets using Qualcomm Technologies, Inc. modems.

This driver can be used to register onto any physical network device in IP mode. Physical transports include USB, HSIC, PCIe and IP accelerator.

Multiplexing allows for creation of logical netdevices (rmnet devices) to handle multiple private data networks (PDN) like a default internet, tethering, multimedia messaging service (MMS) or IP media subsystem (IMS). Hardware sends packets with MAP headers to rmnet. Based on the multiplexer id, rmnet routes to the appropriate PDN after removing the MAP header.

Aggregation is required to achieve high data rates. This involves hardware sending aggregated bunch of MAP frames. rmnet driver will de-aggregate these MAP frames and send them to appropriate PDN's.

<a id="rst-packet-format"></a>

## 2. Packet format

<a id="rst-a-map-packet-v1-data-control"></a>

### a. MAP packet v1 (data / control)

MAP header fields are in big endian format.

Packet format:



```text
Bit             0             1           2-7      8-15           16-31
Function   Command / Data   Reserved     Pad   Multiplexer ID    Payload length

Bit            32-x
Function      Raw bytes
```

Command (1)/ Data (0) bit value is to indicate if the packet is a MAP command or data packet. Command packet is used for transport level flow control. Data packets are standard IP packets.

Reserved bits must be zero when sent and ignored when received.

Padding is the number of bytes to be appended to the payload to ensure 4 byte alignment.

Multiplexer ID is to indicate the PDN on which data has to be sent.

Payload length includes the padding length but does not include MAP header length.

<a id="rst-b-map-packet-v4-data-control"></a>

### b. Map packet v4 (data / control)

MAP header fields are in big endian format.

Packet format:



```text
Bit             0             1           2-7      8-15           16-31
Function   Command / Data   Reserved     Pad   Multiplexer ID    Payload length

Bit            32-(x-33)      (x-32)-x
Function      Raw bytes      Checksum offload header
```

Command (1)/ Data (0) bit value is to indicate if the packet is a MAP command or data packet. Command packet is used for transport level flow control. Data packets are standard IP packets.

Reserved bits must be zero when sent and ignored when received.

Padding is the number of bytes to be appended to the payload to ensure 4 byte alignment.

Multiplexer ID is to indicate the PDN on which data has to be sent.

Payload length includes the padding length but does not include MAP header length.

Checksum offload header, has the information about the checksum processing done by the hardware.Checksum offload header fields are in big endian format.

Packet format:



```text
Bit             0-14        15              16-31
Function      Reserved   Valid     Checksum start offset

Bit                31-47                    48-64
Function      Checksum length           Checksum value
```

Reserved bits must be zero when sent and ignored when received.

Valid bit indicates whether the partial checksum is calculated and is valid. Set to 1, if its is valid. Set to 0 otherwise.

Padding is the number of bytes to be appended to the payload to ensure 4 byte alignment.

Checksum start offset, Indicates the offset in bytes from the beginning of the IP header, from which modem computed checksum.

Checksum length is the Length in bytes starting from CKSUM_START_OFFSET, over which checksum is computed.

Checksum value, indicates the checksum computed.

<a id="rst-c-map-packet-v5-data-control"></a>

### c. MAP packet v5 (data / control)

MAP header fields are in big endian format.

Packet format:



```text
Bit             0             1         2-7      8-15           16-31
Function   Command / Data  Next header  Pad   Multiplexer ID   Payload length

Bit            32-x
Function      Raw bytes
```

Command (1)/ Data (0) bit value is to indicate if the packet is a MAP command or data packet. Command packet is used for transport level flow control. Data packets are standard IP packets.

Next header is used to indicate the presence of another header, currently is limited to checksum header.

Padding is the number of bytes to be appended to the payload to ensure 4 byte alignment.

Multiplexer ID is to indicate the PDN on which data has to be sent.

Payload length includes the padding length but does not include MAP header length.

<a id="rst-d-checksum-offload-header-v5"></a>

### d. Checksum offload header v5

Checksum offload header fields are in big endian format.

Packet format:



```text
Bit            0 - 6          7               8-15              16-31
Function     Header Type    Next Header     Checksum Valid    Reserved
```

Header Type is to indicate the type of header, this usually is set to CHECKSUM

Header types


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


Reserved

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Reserved

</td>
</tr>
<tr>
<td>


2

</td>
<td>


checksum header

</td>
</tr>
</tbody>
</table>

Checksum Valid is to indicate whether the header checksum is valid. Value of 1 implies that checksum is calculated on this packet and is valid, value of 0 indicates that the calculated packet checksum is invalid.

Reserved bits must be zero when sent and ignored when received.

<a id="rst-e-map-packet-v1-v5-command-specific"></a>

### e. MAP packet v1/v5 (command specific)

Packet format:



```text
Bit             0             1         2-7      8 - 15           16 - 31
Function   Command         Reserved     Pad   Multiplexer ID    Payload length
Bit          32 - 39        40 - 45    46 - 47       48 - 63
Function   Command name    Reserved   Command Type   Reserved
Bit          64 - 95
Function   Transaction ID
Bit          96 - 127
Function   Command data
```

Command 1 indicates disabling flow while 2 is enabling flow

Command types


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


for MAP command request

</td>
</tr>
<tr>
<td>


1

</td>
<td>


is to acknowledge the receipt of a command

</td>
</tr>
<tr>
<td>


2

</td>
<td>


is for unsupported commands

</td>
</tr>
<tr>
<td>


3

</td>
<td>


is for error during processing of commands

</td>
</tr>
</tbody>
</table>

<a id="rst-f-aggregation"></a>

### f. Aggregation

Aggregation is multiple MAP packets (can be data or command) delivered to rmnet in a single linear skb. rmnet will process the individual packets and either ACK the MAP command or deliver the IP packet to the network stack as needed

Packet format:



```text
MAP header|IP Packet|Optional padding|MAP header|IP Packet|Optional padding....

MAP header|IP Packet|Optional padding|MAP header|Command Packet|Optional pad...
```

<a id="rst-userspace-configuration"></a>

## 3. Userspace configuration

rmnet userspace configuration is done through netlink using iproute2 [https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/](<https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/>)

The driver uses rtnl_link_ops for communication.

---

# Ethernet Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / ethernet_

> Device drivers for Ethernet and Ethernet-based virtual function devices.

<a id="rst-ethernet-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Device drivers for Ethernet and Ethernet-based virtual function devices.

Contents:

- [Linux and the 3Com EtherLink III Series Ethercards (driver v1.18c and higher)](</kernel/internals/networking/device-drivers-ethernet-3com/3c509.md>)
- [3Com Vortex device driver](</kernel/internals/networking/device-drivers-ethernet-3com/vortex.md>)
- [Linux kernel driver for Elastic Network Adapter (ENA) family](</kernel/internals/networking/device-drivers-ethernet-amazon/ena.md>)
- [Altera Triple-Speed Ethernet MAC driver](</kernel/internals/networking/device-drivers-ethernet-altera/altera-tse.md>)
- [Linux Driver for the AMD/Pensando(R) DSC adapter family](</kernel/internals/networking/device-drivers-ethernet-amd/pds-core.md>)
- [PCI vDPA driver for the AMD/Pensando(R) DSC adapter family](</kernel/internals/networking/device-drivers-ethernet-amd/pds-vdpa.md>)
- [PCI VFIO driver for the AMD/Pensando(R) DSC adapter family](</kernel/internals/networking/device-drivers-ethernet-amd/pds-vfio-pci.md>)
- [Marvell(Aquantia) AQtion Driver](</kernel/internals/networking/device-drivers-ethernet-aquantia/atlantic.md>)
- [Chelsio N210 10Gb Ethernet Network Controller](</kernel/internals/networking/device-drivers-ethernet-chelsio/cxgb.md>)
- [Cirrus Logic LAN CS8900/CS8920 Ethernet Adapters](</kernel/internals/networking/device-drivers-ethernet-cirrus/cs89x0.md>)
- [D-Link DL2000-based Gigabit Ethernet Adapter Installation](</kernel/internals/networking/device-drivers-ethernet-dlink/dl2k.md>)
- [DM9000 Network driver](</kernel/internals/networking/device-drivers-ethernet-davicom/dm9000.md>)
- [Davicom DM9102(A)/DM9132/DM9801 fast ethernet driver for Linux](</kernel/internals/networking/device-drivers-ethernet-dec/dmfe.md>)
- [The QorIQ DPAA Ethernet Driver](</kernel/internals/networking/device-drivers-ethernet-freescale/dpaa.md>)
- [DPAA2 Documentation](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/index.md>)
- [The Gianfar Ethernet Driver](</kernel/internals/networking/device-drivers-ethernet-freescale/gianfar.md>)
- [Linux kernel driver for Compute Engine Virtual Ethernet (gve):](</kernel/internals/networking/device-drivers-ethernet-google/gve.md>)
- [Linux Kernel Driver for Huawei Intelligent NIC(HiNIC) family](</kernel/internals/networking/device-drivers-ethernet-huawei/hinic.md>)
- [Linux kernel driver for Huawei Ethernet Device Driver (hinic3) family](</kernel/internals/networking/device-drivers-ethernet-huawei/hinic3.md>)
- [Linux Base Driver for the Intel(R) PRO/100 Family of Adapters](</kernel/internals/networking/device-drivers-ethernet-intel/e100.md>)
- [Linux Base Driver for Intel(R) Ethernet Network Connection](</kernel/internals/networking/device-drivers-ethernet-intel/e1000.md>)
- [Linux Driver for Intel(R) Ethernet Network Connection](</kernel/internals/networking/device-drivers-ethernet-intel/e1000e.md>)
- [Linux Base Driver for Intel(R) Ethernet Multi-host Controller](</kernel/internals/networking/device-drivers-ethernet-intel/fm10k.md>)
- [idpf Linux\* Base Driver for the Intel(R) Infrastructure Data Path Function](</kernel/internals/networking/device-drivers-ethernet-intel/idpf.md>)
- [Linux Base Driver for Intel(R) Ethernet Network Connection](</kernel/internals/networking/device-drivers-ethernet-intel/igb.md>)
- [Linux Base Virtual Function Driver for Intel(R) 1G Ethernet](</kernel/internals/networking/device-drivers-ethernet-intel/igbvf.md>)
- [Linux Base Driver for the Intel(R) Ethernet 10 Gigabit PCI Express Adapters](</kernel/internals/networking/device-drivers-ethernet-intel/ixgbe.md>)
- [Linux Base Virtual Function Driver for Intel(R) 10G Ethernet](</kernel/internals/networking/device-drivers-ethernet-intel/ixgbevf.md>)
- [Linux Base Driver for the Intel(R) Ethernet Controller 700 Series](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/ethernet/intel/i40e.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Linux Base Driver for Intel(R) Ethernet Adaptive Virtual Function](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/ethernet/intel/iavf.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Linux Base Driver for the Intel(R) Ethernet Controller 800 Series](</kernel/internals/networking/device-drivers-ethernet-intel/ice.md>)
- [Marvell OcteonTx2 RVU Kernel Drivers](</kernel/internals/networking/device-drivers-ethernet-marvell/octeontx2.md>)
- [Linux kernel networking driver for Marvell's Octeon PCI Endpoint NIC](</kernel/internals/networking/device-drivers-ethernet-marvell/octeon-ep.md>)
- [Linux kernel networking driver for Marvell's Octeon PCI Endpoint NIC VF](</kernel/internals/networking/device-drivers-ethernet-marvell/octeon-ep-vf.md>)
- [Mellanox ConnectX(R) mlx5 core VPI Network Driver](</kernel/internals/networking/device-drivers-ethernet-mellanox-mlx5/index.md>)
- [Meta Platforms Host Network Interface](</kernel/internals/networking/device-drivers-ethernet-meta/fbnic.md>)
- [Hyper-V network driver](</kernel/internals/networking/device-drivers-ethernet-microsoft/netvsc.md>)
- [Linux Base Driver for MUCSE(R) Gigabit PCI Express Adapters](</kernel/internals/networking/device-drivers-ethernet-mucse/rnpgbe.md>)
- [Network Flow Processor (NFP) Kernel Drivers](</kernel/internals/networking/device-drivers-ethernet-netronome/nfp.md>)
- [Linux Driver for the Pensando(R) Ethernet adapter family](</kernel/internals/networking/device-drivers-ethernet-pensando/ionic.md>)
- [RDMA Driver for the AMD Pensando(R) Ethernet adapter family](</kernel/internals/networking/device-drivers-ethernet-pensando/ionic-rdma.md>)
- [PPE Ethernet Driver for Qualcomm IPQ SoC Family](</kernel/internals/networking/device-drivers-ethernet-qualcomm-ppe/ppe.md>)
- [SMC 9xxxx Driver](</kernel/internals/networking/device-drivers-ethernet-smsc/smc9.md>)
- [Linux Driver for the Synopsys(R) Ethernet Controllers "stmmac"](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/ethernet/stmicro/stmmac.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Texas Instruments CPSW ethernet driver](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/ethernet/ti/cpsw.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Texas Instruments CPSW switchdev based ethernet driver](</kernel/internals/networking/device-drivers-ethernet-ti/cpsw-switchdev.md>)
- [Texas Instruments K3 AM65 CPSW NUSS switchdev based ethernet driver](</kernel/internals/networking/device-drivers-ethernet-ti/am65-nuss-cpsw-switchdev.md>)
- [TLAN driver for Linux](</kernel/internals/networking/device-drivers-ethernet-ti/tlan.md>)
- [Texas Instruments ICSSG PRUETH ethernet driver](</kernel/internals/networking/device-drivers-ethernet-ti/icssg-prueth.md>)
- [Linux Base Driver for WangXun(R) 10 Gigabit PCI Express Adapters](</kernel/internals/networking/device-drivers-ethernet-wangxun/txgbe.md>)
- [Linux Base Virtual Function Driver for Wangxun(R) 10/25/40 Gigabit Ethernet](</kernel/internals/networking/device-drivers-ethernet-wangxun/txgbevf.md>)
- [Linux Base Driver for WangXun(R) Gigabit PCI Express Adapters](</kernel/internals/networking/device-drivers-ethernet-wangxun/ngbe.md>)
- [Linux Base Virtual Function Driver for Wangxun(R) Gigabit Ethernet](</kernel/internals/networking/device-drivers-ethernet-wangxun/ngbevf.md>)

---

# Linux and the 3Com EtherLink III Series Ethercards (driver v1.18c and higher)

_Peios Kernel / Internals / Networking / device_drivers / ethernet / 3com_

> This file contains the instructions and caveats for v1.18c and higher versions of the 3c509 driver. You should not use the driver without reading this file.

<a id="rst-linux-and-the-3com-etherlink-iii-series-ethercards-driver-v1-18c-and-higher"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This file contains the instructions and caveats for v1.18c and higher versions of the 3c509 driver. You should not use the driver without reading this file.

release 1.0

28 February 2002

- **Current maintainer (corrections to):**

  David Ruggiero &lt;[jdr@farfalle.com](<mailto:jdr@farfalle.com>)&gt;

<a id="rst-introduction"></a>

## Introduction

The following are notes and information on using the 3Com EtherLink III series ethercards in Linux. These cards are commonly known by the most widely-used card's 3Com model number, 3c509. They are all 10mb/s ISA-bus cards and shouldn't be (but sometimes are) confused with the similarly-numbered PCI-bus "3c905" (aka "Vortex" or "Boomerang") series.  Kernel support for the 3c509 family is provided by the module 3c509.c, which has code to support all of the following models:

> - 3c509 (original ISA card)
>
> - 3c509B (later revision of the ISA card; supports full-duplex)
>
> - 3c589 (PCMCIA)
>
> - 3c589B (later revision of the 3c589; supports full-duplex)
>
> - 3c579 (EISA)

Large portions of this documentation were heavily borrowed from the guide written the original author of the 3c509 driver, Donald Becker. The master copy of that document, which contains notes on older versions of the driver, currently resides on Scyld web server: [http://www.scyld.com/](<http://www.scyld.com/>).

<a id="rst-special-driver-features"></a>

## Special Driver Features

Overriding card settings

The driver allows boot- or load-time overriding of the card's detected IOADDR, IRQ, and transceiver settings, although this capability shouldn't generally be needed except to enable full-duplex mode (see below). An example of the syntax for LILO parameters for doing this:



```text
ether=10,0x310,3,0x3c509,eth0
```

This configures the first found 3c509 card for IRQ 10, base I/O 0x310, and transceiver type 3 (10base2). The flag "0x3c509" must be set to avoid conflicts with other card types when overriding the I/O address. When the driver is loaded as a module, only the IRQ may be overridden. For example, setting two cards to IRQ10 and IRQ11 is done by using the irq module option:



```text
options 3c509 irq=10,11
```

<a id="rst-full-duplex-mode"></a>

## Full-duplex mode

The v1.18c driver added support for the 3c509B's full-duplex capabilities. In order to enable and successfully use full-duplex mode, three conditions must be met:

(a) You must have a Etherlink III card model whose hardware supports full- duplex operations. Currently, the only members of the 3c509 family that are positively known to support full-duplex are the 3c509B (ISA bus) and 3c589B (PCMCIA) cards. Cards without the "B" model designation do *not* support full-duplex mode; these include the original 3c509 (no "B"), the original 3c589, the 3c529 (MCA bus), and the 3c579 (EISA bus).

(b) You must be using your card's 10baseT transceiver (i.e., the RJ-45 connector), not its AUI (thick-net) or 10base2 (thin-net/coax) interfaces. AUI and 10base2 network cabling is physically incapable of full-duplex operation.

(c) Most importantly, your 3c509B must be connected to a link partner that is itself full-duplex capable. This is almost certainly one of two things: a full- duplex-capable  Ethernet switch (*not* a hub), or a full-duplex-capable NIC on another system that's connected directly to the 3c509B via a crossover cable.

Full-duplex mode can be enabled using 'ethtool'.

> [!WARNING]
>
> Extremely important caution concerning full-duplex mode
>
> Understand that the 3c509B's hardware's full-duplex support is much more limited than that provide by more modern network interface cards. Although at the physical layer of the network it fully supports full-duplex operation, the card was designed before the current Ethernet auto-negotiation (N-way) spec was written. This means that the 3c509B family **\*cannot and will not auto-negotiate a full-duplex connection with its link partner under any circumstances, no matter how it is initialized\***. If the full-duplex mode of the 3c509B is enabled, its link partner will very likely need to be independently \_forced\_ into full-duplex mode as well; otherwise various nasty failures will occur - at the very least, you'll see massive numbers of packet collisions. This is one of very rare circumstances where disabling auto- negotiation and forcing the duplex mode of a network interface card or switch would ever be necessary or desirable.

<a id="rst-available-transceiver-types"></a>

## Available Transceiver Types

For versions of the driver v1.18c and above, the available transceiver types are:


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


transceiver type from EEPROM config (normally 10baseT); force half-duplex

</td>
</tr>
<tr>
<td>


1

</td>
<td>


AUI (thick-net / DB15 connector)

</td>
</tr>
<tr>
<td>


2

</td>
<td>


(undefined)

</td>
</tr>
<tr>
<td>


3

</td>
<td>


10base2 (thin-net == coax / BNC connector)

</td>
</tr>
<tr>
<td>


4

</td>
<td>


10baseT (RJ-45 connector); force half-duplex mode

</td>
</tr>
<tr>
<td>


8

</td>
<td>


transceiver type and duplex mode taken from card's EEPROM config settings

</td>
</tr>
<tr>
<td>


12

</td>
<td>


10baseT (RJ-45 connector); force full-duplex mode

</td>
</tr>
</tbody>
</table>

Prior to driver version 1.18c, only transceiver codes 0-4 were supported. Note that the new transceiver codes 8 and 12 are the *only* ones that will enable full-duplex mode, no matter what the card's detected EEPROM settings might be. This insured that merely upgrading the driver from an earlier version would never automatically enable full-duplex mode in an existing installation; it must always be explicitly enabled via one of these code in order to be activated.

The transceiver type can be changed using 'ethtool'.

<a id="rst-interpretation-of-error-messages-and-common-problems"></a>

### Interpretation of error messages and common problems

<a id="rst-error-messages"></a>

#### Error Messages

eth0: Infinite loop in interrupt, status 2011. These are "mostly harmless" message indicating that the driver had too much work during that interrupt cycle. With a status of 0x2011 you are receiving packets faster than they can be removed from the card. This should be rare or impossible in normal operation. Possible causes of this error report are:

> - a "green" mode enabled that slows the processor down when there is no keyboard activity.
>
> - some other device or device driver hogging the bus or disabling interrupts. Check /proc/interrupts for excessive interrupt counts. The timer tick interrupt should always be incrementing faster than the others.

<a id="rst-no-received-packets"></a>

#### No received packets

If a 3c509, 3c562 or 3c589 can successfully transmit packets, but never receives packets (as reported by /proc/net/dev or 'ifconfig') you likely have an interrupt line problem. Check /proc/interrupts to verify that the card is actually generating interrupts. If the interrupt count is not increasing you likely have a physical conflict with two devices trying to use the same ISA IRQ line. The common conflict is with a sound card on IRQ10 or IRQ5, and the easiest solution is to move the 3c509 to a different interrupt line. If the device is receiving packets but 'ping' doesn't work, you have a routing problem.

<a id="rst-tx-carrier-errors-reported-in-proc-net-dev"></a>

#### Tx Carrier Errors Reported in /proc/net/dev

If an EtherLink III appears to transmit packets, but the "Tx carrier errors" field in /proc/net/dev increments as quickly as the Tx packet count, you likely have an unterminated network or the incorrect media transceiver selected.

<a id="rst-c509b-card-is-not-detected-on-machines-with-an-isa-pnp-bios"></a>

#### 3c509B card is not detected on machines with an ISA PnP BIOS.

While the updated driver works with most PnP BIOS programs, it does not work with all. This can be fixed by disabling PnP support using the 3Com-supplied setup program.

<a id="rst-c509-card-is-not-detected-on-overclocked-machines"></a>

#### 3c509 card is not detected on overclocked machines

Increase the delay time in id_read_eeprom() from the current value, 500, to an absurdly high value, such as 5000.

<a id="rst-decoding-status-and-error-messages"></a>

### Decoding Status and Error Messages

The bits in the main status register are:


<table>
<thead>
<tr>
<th>


value

</th>
<th>


description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x01

</td>
<td>


Interrupt latch

</td>
</tr>
<tr>
<td>


0x02

</td>
<td>


Tx overrun, or Rx underrun

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Tx complete

</td>
</tr>
<tr>
<td>


0x08

</td>
<td>


Tx FIFO room available

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


A complete Rx packet has arrived

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


A Rx packet has started to arrive

</td>
</tr>
<tr>
<td>


0x40

</td>
<td>


The driver has requested an interrupt

</td>
</tr>
<tr>
<td>


0x80

</td>
<td>


Statistics counter nearly full

</td>
</tr>
</tbody>
</table>

The bits in the transmit (Tx) status word are:


<table>
<thead>
<tr>
<th>


value

</th>
<th>


description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x02

</td>
<td>


Out-of-window collision.

</td>
</tr>
<tr>
<td>


0x04

</td>
<td>


Status stack overflow (normally impossible).

</td>
</tr>
<tr>
<td>


0x08

</td>
<td>


16 collisions.

</td>
</tr>
<tr>
<td>


0x10

</td>
<td>


Tx underrun (not enough PCI bus bandwidth).

</td>
</tr>
<tr>
<td>


0x20

</td>
<td>


Tx jabber.

</td>
</tr>
<tr>
<td>


0x40

</td>
<td>


Tx interrupt requested.

</td>
</tr>
<tr>
<td>


0x80

</td>
<td>


Status is valid (this should always be set).

</td>
</tr>
</tbody>
</table>

When a transmit error occurs the driver produces a status message such as:



```text
eth0: Transmit error, Tx status register 82
```

The two values typically seen here are:

<a id="rst-x82"></a>

#### 0x82

Out of window collision. This typically occurs when some other Ethernet host is incorrectly set to full duplex on a half duplex network.

<a id="rst-x88"></a>

#### 0x88

16 collisions. This typically occurs when the network is exceptionally busy or when another host doesn't correctly back off after a collision. If this error is mixed with 0x82 errors it is the result of a host incorrectly set to full duplex (see above).

Both of these errors are the result of network problems that should be corrected. They do not represent driver malfunction.

<a id="rst-revision-history-this-file"></a>

## Revision history (this file)

28Feb02 v1.0  DR   New; major portions based on Becker original 3c509 docs

---

# 3Com Vortex device driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / 3com_

> Andrew Morton

<a id="rst-com-vortex-device-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Andrew Morton

30 April 2000

This document describes the usage and errata of the 3Com "Vortex" device driver for Linux, 3c59x.c.

The driver was written by Donald Becker &lt;[becker@scyld.com](<mailto:becker@scyld.com>)&gt;

Don is no longer the prime maintainer of this version of the driver. Please report problems to one or more of:

- Andrew Morton

- Netdev mailing list &lt;[netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>)&gt;

- Linux kernel mailing list &lt;[linux-kernel@vger.kernel.org](<mailto:linux-kernel@vger.kernel.org>)&gt;

Please note the 'Reporting and Diagnosing Problems' section at the end of this file.

Since kernel 2.3.99-pre6, this driver incorporates the support for the 3c575-series Cardbus cards which used to be handled by 3c575_cb.c.

This driver supports the following hardware:

> - 3c590 Vortex 10Mbps
>
> - 3c592 EISA 10Mbps Demon/Vortex
>
> - 3c597 EISA Fast Demon/Vortex
>
> - 3c595 Vortex 100baseTx
>
> - 3c595 Vortex 100baseT4
>
> - 3c595 Vortex 100base-MII
>
> - 3c900 Boomerang 10baseT
>
> - 3c900 Boomerang 10Mbps Combo
>
> - 3c900 Cyclone 10Mbps TPO
>
> - 3c900 Cyclone 10Mbps Combo
>
> - 3c900 Cyclone 10Mbps TPC
>
> - 3c900B-FL Cyclone 10base-FL
>
> - 3c905 Boomerang 100baseTx
>
> - 3c905 Boomerang 100baseT4
>
> - 3c905B Cyclone 100baseTx
>
> - 3c905B Cyclone 10/100/BNC
>
> - 3c905B-FX Cyclone 100baseFx
>
> - 3c905C Tornado
>
> - 3c920B-EMB-WNM (ATI Radeon 9100 IGP)
>
> - 3c980 Cyclone
>
> - 3c980C Python-T
>
> - 3cSOHO100-TX Hurricane
>
> - 3c555 Laptop Hurricane
>
> - 3c556 Laptop Tornado
>
> - 3c556B Laptop Hurricane
>
> - 3c575 \[Megahertz\] 10/100 LAN  CardBus
>
> - 3c575 Boomerang CardBus
>
> - 3CCFE575BT Cyclone CardBus
>
> - 3CCFE575CT Tornado CardBus
>
> - 3CCFE656 Cyclone CardBus
>
> - 3CCFEM656B Cyclone+Winmodem CardBus
>
> - 3CXFEM656C Tornado+Winmodem CardBus
>
> - 3c450 HomePNA Tornado
>
> - 3c920 Tornado
>
> - 3c982 Hydra Dual Port A
>
> - 3c982 Hydra Dual Port B
>
> - 3c905B-T4
>
> - 3c920B-EMB-WNM Tornado

<a id="rst-module-parameters"></a>

## Module parameters

There are several parameters which may be provided to the driver when its module is loaded.  These are usually placed in `/etc/modprobe.d/*.conf` configuration files.  Example:



```text
options 3c59x debug=3 rx_copybreak=300
```

If you are using the PCMCIA tools (cardmgr) then the options may be placed in /etc/pcmcia/config.opts:



```text
module "3c59x" opts "debug=3 rx_copybreak=300"
```

The supported parameters are:

debug=N

> Where N is a number from 0 to 7.  Anything above 3 produces a lot of output in your system logs.  debug=1 is default.

options=N1,N2,N3,...

> Each number in the list provides an option to the corresponding network card.  So if you have two 3c905's and you wish to provide them with option 0x204 you would use:
>
>
>
> ```text
> options=0x204,0x204
> ```
>
> The individual options are composed of a number of bitfields which have the following meanings:
>
> Possible media type settings
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > 0
> >
> > </td>
> > <td>
> >
> >
> > 10baseT
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 1
> >
> > </td>
> > <td>
> >
> >
> > 10Mbs AUI
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 2
> >
> > </td>
> > <td>
> >
> >
> > undefined
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 3
> >
> > </td>
> > <td>
> >
> >
> > 10base2 (BNC)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 4
> >
> > </td>
> > <td>
> >
> >
> > 100base-TX
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 5
> >
> > </td>
> > <td>
> >
> >
> > 100base-FX
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 6
> >
> > </td>
> > <td>
> >
> >
> > MII (Media Independent Interface)
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 7
> >
> > </td>
> > <td>
> >
> >
> > Use default setting from EEPROM
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 8
> >
> > </td>
> > <td>
> >
> >
> > Autonegotiate
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 9
> >
> > </td>
> > <td>
> >
> >
> > External MII
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > 10
> >
> > </td>
> > <td>
> >
> >
> > Use default setting from EEPROM
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>
>
> When generating a value for the 'options' setting, the above media selection values may be OR'ed (or added to) the following:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 0x8000
>
> </td>
> <td>
>
>
> Set driver debugging level to 7
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x4000
>
> </td>
> <td>
>
>
> Set driver debugging level to 2
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0400
>
> </td>
> <td>
>
>
> Enable Wake-on-LAN
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0200
>
> </td>
> <td>
>
>
> Force full duplex mode.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0010
>
> </td>
> <td>
>
>
> Bus-master enable bit (Old Vortex cards only)
>
> </td>
> </tr>
> </tbody>
> </table>
>
> For example:
>
>
>
> ```text
> insmod 3c59x options=0x204
> ```
>
> will force full-duplex 100base-TX, rather than allowing the usual autonegotiation.

global_options=N

> Sets the `options` parameter for all 3c59x NICs in the machine. Entries in the `options` array above will override any setting of this.

full_duplex=N1,N2,N3...

> Similar to bit 9 of 'options'.  Forces the corresponding card into full-duplex mode.  Please use this in preference to the `options` parameter.
>
> In fact, please don't use this at all\! You're better off getting autonegotiation working properly.

global_full_duplex=N1

> Sets full duplex mode for all 3c59x NICs in the machine.  Entries in the `full_duplex` array above will override any setting of this.

flow_ctrl=N1,N2,N3...

> Use 802.3x MAC-layer flow control.  The 3com cards only support the PAUSE command, which means that they will stop sending packets for a short period if they receive a PAUSE frame from the link partner.
>
> The driver only allows flow control on a link which is operating in full duplex mode.
>
> This feature does not appear to work on the 3c905 - only 3c905B and 3c905C have been tested.
>
> The 3com cards appear to only respond to PAUSE frames which are sent to the reserved destination address of 01:80:c2:00:00:01.  They do not honour PAUSE frames which are sent to the station MAC address.

rx_copybreak=M

> The driver preallocates 32 full-sized (1536 byte) network buffers for receiving.  When a packet arrives, the driver has to decide whether to leave the packet in its full-sized buffer, or to allocate a smaller buffer and copy the packet across into it.
>
> This is a speed/space tradeoff.
>
> The value of rx_copybreak is used to decide when to make the copy. If the packet size is less than rx_copybreak, the packet is copied. The default value for rx_copybreak is 200 bytes.

max_interrupt_work=N

> The driver's interrupt service routine can handle many receive and transmit packets in a single invocation.  It does this in a loop. The value of max_interrupt_work governs how many times the interrupt service routine will loop.  The default value is 32 loops.  If this is exceeded the interrupt service routine gives up and generates a warning message "eth0: Too much work in interrupt".

hw_checksums=N1,N2,N3,...

> Recent 3com NICs are able to generate IPv4, TCP and UDP checksums in hardware.  Linux has used the Rx checksumming for a long time. The "zero copy" patch which is planned for the 2.4 kernel series allows you to make use of the NIC's DMA scatter/gather and transmit checksumming as well.
>
> The driver is set up so that, when the zerocopy patch is applied, all Tornado and Cyclone devices will use S/G and Tx checksums.
>
> This module parameter has been provided so you can override this decision.  If you think that Tx checksums are causing a problem, you may disable the feature with `hw_checksums=0`.
>
> If you think your NIC should be performing Tx checksumming and the driver isn't enabling it, you can force the use of hardware Tx checksumming with `hw_checksums=1`.
>
> The driver drops a message in the logfiles to indicate whether or not it is using hardware scatter/gather and hardware Tx checksums.
>
> Scatter/gather and hardware checksums provide considerable performance improvement for the sendfile() system call, but a small decrease in throughput for send().  There is no effect upon receive efficiency.

compaq_ioaddr=N, compaq_irq=N, compaq_device_id=N

> "Variables to work-around the Compaq PCI BIOS32 problem"....

watchdog=N

> Sets the time duration (in milliseconds) after which the kernel decides that the transmitter has become stuck and needs to be reset. This is mainly for debugging purposes, although it may be advantageous to increase this value on LANs which have very high collision rates. The default value is 5000 (5.0 seconds).

enable_wol=N1,N2,N3,...

> Enable Wake-on-LAN support for the relevant interface.  Donald Becker's `ether-wake` application may be used to wake suspended machines.
>
> Also enables the NIC's power management support.

global_enable_wol=N

> Sets enable_wol mode for all 3c59x NICs in the machine.  Entries in the `enable_wol` array above will override any setting of this.

<a id="rst-media-selection"></a>

### Media selection

A number of the older NICs such as the 3c590 and 3c900 series have 10base2 and AUI interfaces.

Prior to January, 2001 this driver would autoselect the 10base2 or AUI port if it didn't detect activity on the 10baseT port.  It would then get stuck on the 10base2 port and a driver reload was necessary to switch back to 10baseT.  This behaviour could not be prevented with a module option override.

Later (current) versions of the driver \_do\_ support locking of the media type.  So if you load the driver module with

> modprobe 3c59x options=0

it will permanently select the 10baseT port.  Automatic selection of other media types does not occur.

<a id="rst-transmit-error-tx-status-register-82"></a>

### Transmit error, Tx status register 82

This is a common error which is almost always caused by another host on the same network being in full-duplex mode, while this host is in half-duplex mode.  You need to find that other host and make it run in half-duplex mode or fix this host to run in full-duplex mode.

As a last resort, you can force the 3c59x driver into full-duplex mode with

> options 3c59x full_duplex=1

but this has to be viewed as a workaround for broken network gear and should only really be used for equipment which cannot autonegotiate.

<a id="rst-additional-resources"></a>

### Additional resources

Details of the device driver implementation are at the top of the source file.

Additional documentation is available at Don Becker's Linux Drivers site:

> [http://www.scyld.com/vortex.html](<http://www.scyld.com/vortex.html>)

Donald Becker's driver development site:

> [http://www.scyld.com/network.html](<http://www.scyld.com/network.html>)

Donald's vortex-diag program is useful for inspecting the NIC's state:

> [http://www.scyld.com/ethercard_diag.html](<http://www.scyld.com/ethercard_diag.html>)

Donald's mii-diag program may be used for inspecting and manipulating the NIC's Media Independent Interface subsystem:

> [http://www.scyld.com/ethercard_diag.html\#mii-diag](<http://www.scyld.com/ethercard_diag.html#mii-diag>)

Donald's wake-on-LAN page:

> [http://www.scyld.com/wakeonlan.html](<http://www.scyld.com/wakeonlan.html>)

3Com's DOS-based application for setting up the NICs EEPROMs:

> [ftp://ftp.3com.com/pub/nic/3c90x/3c90xx2.exe](<ftp://ftp.3com.com/pub/nic/3c90x/3c90xx2.exe>)

<a id="rst-autonegotiation-notes"></a>

### Autonegotiation notes

> The driver uses a one-minute heartbeat for adapting to changes in the external LAN environment if link is up and 5 seconds if link is down. This means that when, for example, a machine is unplugged from a hubbed 10baseT LAN plugged into a  switched 100baseT LAN, the throughput will be quite dreadful for up to sixty seconds.  Be patient.
>
> Cisco interoperability note from Walter Wong &lt;[wcw+@CMU.EDU](<mailto:wcw+@CMU.EDU>)&gt;:
>
> On a side note, adding HAS_NWAY seems to share a problem with the Cisco 6509 switch.  Specifically, you need to change the spanning tree parameter for the port the machine is plugged into to 'portfast' mode.  Otherwise, the negotiation fails.  This has been an issue we've noticed for a while but haven't had the time to track down.
>
> Cisco switches    (Jeff Busch &lt;[jbusch@deja.com](<mailto:jbusch@deja.com>)&gt;)
>
> > My "standard config" for ports to which PC's/servers connect directly:
> >
> >
> >
> > ```text
> > interface FastEthernet0/N
> > description machinename
> > load-interval 30
> > spanning-tree portfast
> > ```
> >
> > If autonegotiation is a problem, you may need to specify "speed 100" and "duplex full" as well (or "speed 10" and "duplex half").
> >
> > WARNING: DO NOT hook up hubs/switches/bridges to these specially-configured ports\! The switch will become very confused.

<a id="rst-reporting-and-diagnosing-problems"></a>

### Reporting and diagnosing problems

Maintainers find that accurate and complete problem reports are invaluable in resolving driver problems.  We are frequently not able to reproduce problems and must rely on your patience and efforts to get to the bottom of the problem.

If you believe you have a driver problem here are some of the steps you should take:

- Is it really a driver problem?

  > Eliminate some variables: try different cards, different computers, different cables, different ports on the switch/hub, different versions of the kernel or of the driver, etc.

- OK, it's a driver problem.

  > You need to generate a report.  Typically this is an email to the maintainer and/or [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>).  The maintainer's email address will be in the driver source or in the MAINTAINERS file.

- The contents of your report will vary a lot depending upon the problem.  If it's a kernel crash then you should refer to '[Documentation/admin-guide/reporting-issues.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/admin-guide/reporting-issues.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)'.

  But for most problems it is useful to provide the following:

  > - Kernel version, driver version
  >
  > - A copy of the banner message which the driver generates when it is initialised.  For example:
  >
  >   eth0: 3Com PCI 3c905C Tornado at 0xa400,  00:50:da:6a:88:f0, IRQ 19 8K byte-wide RAM 5:3 Rx:Tx split, autoselect/Autonegotiate interface. MII transceiver found at address 24, status 782d. Enabling bus-master transmits and whole-frame receives.
  >
  >   NOTE: You must provide the `debug=2` modprobe option to generate a full detection message.  Please do this:
  >
  >
  >
  >   ```text
  >   modprobe 3c59x debug=2
  >   ```
  >
  > - If it is a PCI device, the relevant output from 'lspci -vx', eg:
  >
  >
  >
  >   ```text
  >   00:09.0 Ethernet controller: 3Com Corporation 3c905C-TX [Fast Etherlink] (rev 74)
  >           Subsystem: 3Com Corporation: Unknown device 9200
  >           Flags: bus master, medium devsel, latency 32, IRQ 19
  >           I/O ports at a400 [size=128]
  >           Memory at db000000 (32-bit, non-prefetchable) [size=128]
  >           Expansion ROM at <unassigned> [disabled] [size=128K]
  >           Capabilities: [dc] Power Management version 2
  >   00: b7 10 00 92 07 00 10 02 74 00 00 02 08 20 00 00
  >   10: 01 a4 00 00 00 00 00 db 00 00 00 00 00 00 00 00
  >   20: 00 00 00 00 00 00 00 00 00 00 00 00 b7 10 00 10
  >   30: 00 00 00 00 dc 00 00 00 00 00 00 00 05 01 0a 0a
  >   ```
  >
  > - A description of the environment: 10baseT? 100baseT? full/half duplex? switched or hubbed?
  >
  > - Any additional module parameters which you may be providing to the driver.
  >
  > - Any kernel logs which are produced.  The more the merrier. If this is a large file and you are sending your report to a mailing list, mention that you have the logfile, but don't send it.  If you're reporting direct to the maintainer then just send it.
  >
  >   To ensure that all kernel logs are available, add the following line to /etc/syslog.conf:
  >
  >
  >
  >   ```text
  >   kern.* /var/log/messages
  >   ```
  >
  >   Then restart syslogd with:
  >
  >
  >
  >   ```text
  >   /etc/rc.d/init.d/syslog restart
  >   ```
  >
  >   (The above may vary, depending upon which Linux distribution you use).
  >
  > > - If your problem is reproducible then that's great.  Try the following:
  > >
  > >   1. Increase the debug level.  Usually this is done via:
  > >
  > >      - **a)** modprobe driver debug=7
  > >
  > >      - **b)** In /etc/modprobe.d/driver.conf: options driver debug=7
  > >
  > >   2. Recreate the problem with the higher debug level, send all logs to the maintainer.
  > >
  > >   3. Download you card's diagnostic tool from Donald Becker's website &lt;[http://www.scyld.com/ethercard_diag.html](<http://www.scyld.com/ethercard_diag.html>)&gt;. Download mii-diag.c as well.  Build these.
  > >
  > >      - **a)** Run 'vortex-diag -aaee' and 'mii-diag -v' when the card is working correctly.  Save the output.
  > >
  > >      - **b)** Run the above commands when the card is malfunctioning.  Send both sets of output.

Finally, please be patient and be prepared to do some work.  You may end up working on this problem for a week or more as the maintainer asks more questions, asks for more tests, asks for patches to be applied, etc.  At the end of it all, the problem may even remain unresolved.

---

# Altera Triple-Speed Ethernet MAC driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / altera_

> Copyright © 2008-2014 Altera Corporation

<a id="rst-altera-triple-speed-ethernet-mac-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Copyright © 2008-2014 Altera Corporation

This is the driver for the Altera Triple-Speed Ethernet (TSE) controllers using the SGDMA and MSGDMA soft DMA IP components. The driver uses the platform bus to obtain component resources. The designs used to test this driver were built for a Cyclone(R) V SOC FPGA board, a Cyclone(R) V FPGA board, and tested with ARM and NIOS processor hosts separately. The anticipated use cases are simple communications between an embedded system and an external peer for status and simple configuration of the embedded system.

For more information visit www.altera.com and www.rocketboards.org. Support forums for the driver may be found on www.rocketboards.org, and a design used to test this driver may be found there as well. Support is also available from the maintainer of this driver, found in MAINTAINERS.

The Triple-Speed Ethernet, SGDMA, and MSGDMA components are all soft IP components that can be assembled and built into an FPGA using the Altera Quartus toolchain. Quartus 13.1 and 14.0 were used to build the design that this driver was tested against. The sopc2dts tool is used to create the device tree for the driver, and may be found at rocketboards.org.

The driver probe function examines the device tree and determines if the Triple-Speed Ethernet instance is using an SGDMA or MSGDMA component. The probe function then installs the appropriate set of DMA routines to initialize, setup transmits, receives, and interrupt handling primitives for the respective configurations.

The SGDMA component is to be deprecated in the near future (over the next 1-2 years as of this writing in early 2014) in favor of the MSGDMA component. SGDMA support is included for existing designs and reference in case a developer wishes to support their own soft DMA logic and driver support. Any new designs should not use the SGDMA.

The SGDMA supports only a single transmit or receive operation at a time, and therefore will not perform as well compared to the MSGDMA soft IP. Please visit www.altera.com for known, documented SGDMA errata.

Scatter-gather DMA is not supported by the SGDMA or MSGDMA at this time. Scatter-gather DMA will be added to a future maintenance update to this driver.

Jumbo frames are not supported at this time.

The driver limits PHY operations to 10/100Mbps, and has not yet been fully tested for 1Gbps. This support will be added in a future maintenance update.

<a id="rst-kernel-configuration"></a>

## 1. Kernel Configuration

The kernel configuration option is ALTERA_TSE:

> Device Drivers ---&gt; Network device support ---&gt; Ethernet driver support ---&gt; Altera Triple-Speed Ethernet MAC support (ALTERA_TSE)

<a id="rst-driver-parameters-list"></a>

## 2. Driver parameters list

> - debug: message level (0: no output, 16: all);
>
> - dma_rx_num: Number of descriptors in the RX list (default is 64);
>
> - dma_tx_num: Number of descriptors in the TX list (default is 64).

<a id="rst-command-line-options"></a>

## 3. Command line options

Driver parameters can be also passed in command line by using:



```text
altera_tse=dma_rx_num:128,dma_tx_num:512
```

<a id="rst-driver-information-and-notes"></a>

## 4. Driver information and notes

<a id="rst-transmit-process"></a>

### 4.1. Transmit process

When the driver's transmit routine is called by the kernel, it sets up a transmit descriptor by calling the underlying DMA transmit routine (SGDMA or MSGDMA), and initiates a transmit operation. Once the transmit is complete, an interrupt is driven by the transmit DMA logic. The driver handles the transmit completion in the context of the interrupt handling chain by recycling resource required to send and track the requested transmit operation.

<a id="rst-receive-process"></a>

### 4.2. Receive process

The driver will post receive buffers to the receive DMA logic during driver initialization. Receive buffers may or may not be queued depending upon the underlying DMA logic (MSGDMA is able queue receive buffers, SGDMA is not able to queue receive buffers to the SGDMA receive logic). When a packet is received, the DMA logic generates an interrupt. The driver handles a receive interrupt by obtaining the DMA receive logic status, reaping receive completions until no more receive completions are available.

<a id="rst-interrupt-mitigation"></a>

### 4.3. Interrupt Mitigation

The driver is able to mitigate the number of its DMA interrupts using NAPI for receive operations. Interrupt mitigation is not yet supported for transmit operations, but will be added in a future maintenance release.

<a id="rst-ethtool-support"></a>

### 4.4) Ethtool support

Ethtool is supported. Driver statistics and internal errors can be taken using: ethtool -S ethX command. It is possible to dump registers etc.

<a id="rst-phy-support"></a>

### 4.5) PHY Support

The driver is compatible with PAL to work with PHY and GPHY devices.

<a id="rst-list-of-source-files"></a>

### 4.7) List of source files:

> - Kconfig
>
> - Makefile
>
> - altera_tse_main.c: main network device driver
>
> - altera_tse_ethtool.c: ethtool support
>
> - altera_tse.h: private driver structure and common definitions
>
> - altera_msgdma.h: MSGDMA implementation function definitions
>
> - altera_sgdma.h: SGDMA implementation function definitions
>
> - altera_msgdma.c: MSGDMA implementation
>
> - altera_sgdma.c: SGDMA implementation
>
> - altera_sgdmahw.h: SGDMA register and descriptor definitions
>
> - altera_msgdmahw.h: MSGDMA register and descriptor definitions
>
> - altera_utils.c: Driver utility functions
>
> - altera_utils.h: Driver utility function definitions

<a id="rst-debug-information"></a>

## 5. Debug Information

The driver exports debug information such as internal statistics, debug information, MAC and DMA registers etc.

A user may use the ethtool support to get statistics: e.g. using: ethtool -S ethX (that shows the statistics counters) or sees the MAC registers: e.g. using: ethtool -d ethX

The developer can also use the "debug" module parameter to get further debug information.

<a id="rst-statistics-support"></a>

## 6. Statistics Support

The controller and driver support a mix of IEEE standard defined statistics, RFC defined statistics, and driver or Altera defined statistics. The four specifications containing the standard definitions for these statistics are as follows:

> - IEEE 802.3-2012 - IEEE Standard for Ethernet.
>
> - RFC 2863 found at [http://www.rfc-editor.org/rfc/rfc2863.txt](<http://www.rfc-editor.org/rfc/rfc2863.txt>).
>
> - RFC 2819 found at [http://www.rfc-editor.org/rfc/rfc2819.txt](<http://www.rfc-editor.org/rfc/rfc2819.txt>).
>
> - Altera Triple Speed Ethernet User Guide, found at [http://www.altera.com](<http://www.altera.com>)

The statistics supported by the TSE and the device driver are as follows:

"tx_packets" is equivalent to aFramesTransmittedOK defined in IEEE 802.3-2012, Section 5.2.2.1.2. This statistics is the count of frames that are successfully transmitted.

"rx_packets" is equivalent to aFramesReceivedOK defined in IEEE 802.3-2012, Section 5.2.2.1.5. This statistic is the count of frames that are successfully received. This count does not include any error packets such as CRC errors, length errors, or alignment errors.

"rx_crc_errors" is equivalent to aFrameCheckSequenceErrors defined in IEEE 802.3-2012, Section 5.2.2.1.6. This statistic is the count of frames that are an integral number of bytes in length and do not pass the CRC test as the frame is received.

"rx_align_errors" is equivalent to aAlignmentErrors defined in IEEE 802.3-2012, Section 5.2.2.1.7. This statistic is the count of frames that are not an integral number of bytes in length and do not pass the CRC test as the frame is received.

"tx_bytes" is equivalent to aOctetsTransmittedOK defined in IEEE 802.3-2012, Section 5.2.2.1.8. This statistic is the count of data and pad bytes successfully transmitted from the interface.

"rx_bytes" is equivalent to aOctetsReceivedOK defined in IEEE 802.3-2012, Section 5.2.2.1.14. This statistic is the count of data and pad bytes successfully received by the controller.

"tx_pause" is equivalent to aPAUSEMACCtrlFramesTransmitted defined in IEEE 802.3-2012, Section 30.3.4.2. This statistic is a count of PAUSE frames transmitted from the network controller.

"rx_pause" is equivalent to aPAUSEMACCtrlFramesReceived defined in IEEE 802.3-2012, Section 30.3.4.3. This statistic is a count of PAUSE frames received by the network controller.

"rx_errors" is equivalent to ifInErrors defined in RFC 2863. This statistic is a count of the number of packets received containing errors that prevented the packet from being delivered to a higher level protocol.

"tx_errors" is equivalent to ifOutErrors defined in RFC 2863. This statistic is a count of the number of packets that could not be transmitted due to errors.

"rx_unicast" is equivalent to ifInUcastPkts defined in RFC 2863. This statistic is a count of the number of packets received that were not addressed to the broadcast address or a multicast group.

"rx_multicast" is equivalent to ifInMulticastPkts defined in RFC 2863. This statistic is a count of the number of packets received that were addressed to a multicast address group.

"rx_broadcast" is equivalent to ifInBroadcastPkts defined in RFC 2863. This statistic is a count of the number of packets received that were addressed to the broadcast address.

"tx_discards" is equivalent to ifOutDiscards defined in RFC 2863. This statistic is the number of outbound packets not transmitted even though an error was not detected. An example of a reason this might occur is to free up internal buffer space.

"tx_unicast" is equivalent to ifOutUcastPkts defined in RFC 2863. This statistic counts the number of packets transmitted that were not addressed to a multicast group or broadcast address.

"tx_multicast" is equivalent to ifOutMulticastPkts defined in RFC 2863. This statistic counts the number of packets transmitted that were addressed to a multicast group.

"tx_broadcast" is equivalent to ifOutBroadcastPkts defined in RFC 2863. This statistic counts the number of packets transmitted that were addressed to a broadcast address.

"ether_drops" is equivalent to etherStatsDropEvents defined in RFC 2819. This statistic counts the number of packets dropped due to lack of internal controller resources.

"rx_total_bytes" is equivalent to etherStatsOctets defined in RFC 2819. This statistic counts the total number of bytes received by the controller, including error and discarded packets.

"rx_total_packets" is equivalent to etherStatsPkts defined in RFC 2819. This statistic counts the total number of packets received by the controller, including error, discarded, unicast, multicast, and broadcast packets.

"rx_undersize" is equivalent to etherStatsUndersizePkts defined in RFC 2819. This statistic counts the number of correctly formed packets received less than 64 bytes long.

"rx_oversize" is equivalent to etherStatsOversizePkts defined in RFC 2819. This statistic counts the number of correctly formed packets greater than 1518 bytes long.

"rx_64_bytes" is equivalent to etherStatsPkts64Octets defined in RFC 2819. This statistic counts the total number of packets received that were 64 octets in length.

"rx_65_127_bytes" is equivalent to etherStatsPkts65to127Octets defined in RFC 2819. This statistic counts the total number of packets received that were between 65 and 127 octets in length inclusive.

"rx_128_255_bytes" is equivalent to etherStatsPkts128to255Octets defined in RFC 2819. This statistic is the total number of packets received that were between 128 and 255 octets in length inclusive.

"rx_256_511_bytes" is equivalent to etherStatsPkts256to511Octets defined in RFC 2819. This statistic is the total number of packets received that were between 256 and 511 octets in length inclusive.

"rx_512_1023_bytes" is equivalent to etherStatsPkts512to1023Octets defined in RFC 2819. This statistic is the total number of packets received that were between 512 and 1023 octets in length inclusive.

"rx_1024_1518_bytes" is equivalent to etherStatsPkts1024to1518Octets define in RFC 2819. This statistic is the total number of packets received that were between 1024 and 1518 octets in length inclusive.

"rx_gte_1519_bytes" is a statistic defined specific to the behavior of the Altera TSE. This statistics counts the number of received good and errored frames between the length of 1519 and the maximum frame length configured in the frm_length register. See the Altera TSE User Guide for More details.

"rx_jabbers" is equivalent to etherStatsJabbers defined in RFC 2819. This statistic is the total number of packets received that were longer than 1518 octets, and had either a bad CRC with an integral number of octets (CRC Error) or a bad CRC with a non-integral number of octets (Alignment Error).

"rx_runts" is equivalent to etherStatsFragments defined in RFC 2819. This statistic is the total number of packets received that were less than 64 octets in length and had either a bad CRC with an integral number of octets (CRC error) or a bad CRC with a non-integral number of octets (Alignment Error).

---

# Linux kernel driver for Elastic Network Adapter (ENA) family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / amazon_

> ENA is a networking interface designed to make good use of modern CPU features and system architectures.

<a id="rst-linux-kernel-driver-for-elastic-network-adapter-ena-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

ENA is a networking interface designed to make good use of modern CPU features and system architectures.

The ENA device exposes a lightweight management interface with a minimal set of memory mapped registers and extendible command set through an Admin Queue.

The driver supports a range of ENA devices, is link-speed independent (i.e., the same driver is used for 10GbE, 25GbE, 40GbE, etc), and has a negotiated and extendible feature set.

Some ENA devices support SR-IOV. This driver is used for both the SR-IOV Physical Function (PF) and Virtual Function (VF) devices.

ENA devices enable high speed and low overhead network traffic processing by providing multiple Tx/Rx queue pairs (the maximum number is advertised by the device via the Admin Queue), a dedicated MSI-X interrupt vector per Tx/Rx queue pair, adaptive interrupt moderation, and CPU cacheline optimized data placement.

The ENA driver supports industry standard TCP/IP offload features such as checksum offload. Receive-side scaling (RSS) is supported for multi-core scaling.

The ENA driver and its corresponding devices implement health monitoring mechanisms such as watchdog, enabling the device and driver to recover in a manner transparent to the application, as well as debug logs.

Some of the ENA devices support a working mode called Low-latency Queue (LLQ), which saves several more microseconds.

<a id="rst-ena-source-code-directory-structure"></a>

## ENA Source Code Directory Structure


<table>
<tbody>
<tr>
<td>


ena_com.\[ch\]

</td>
<td>


Management communication layer. This layer is responsible for the handling all the management (admin) communication between the device and the driver.

</td>
</tr>
<tr>
<td>


ena_eth_com.\[ch\]

</td>
<td>


Tx/Rx data path.

</td>
</tr>
<tr>
<td>


ena_admin_defs.h

</td>
<td>


Definition of ENA management interface.

</td>
</tr>
<tr>
<td>


ena_eth_io_defs.h

</td>
<td>


Definition of ENA data path interface.

</td>
</tr>
<tr>
<td>


ena_common_defs.h

</td>
<td>


Common definitions for ena_com layer.

</td>
</tr>
<tr>
<td>


ena_regs_defs.h

</td>
<td>


Definition of ENA PCI memory-mapped (MMIO) registers.

</td>
</tr>
<tr>
<td>


ena_netdev.\[ch\]

</td>
<td>


Main Linux kernel driver.

</td>
</tr>
<tr>
<td>


ena_ethtool.c

</td>
<td>


ethtool callbacks.

</td>
</tr>
<tr>
<td>


ena_xdp.\[ch\]

</td>
<td>


XDP files

</td>
</tr>
<tr>
<td>


ena_pci_id_tbl.h

</td>
<td>


Supported device IDs.

</td>
</tr>
<tr>
<td>


ena_phc.\[ch\]

</td>
<td>


PTP hardware clock infrastructure (see [PHC](<#rst-phc>) for more info)

</td>
</tr>
<tr>
<td>


ena_devlink.\[ch\]

</td>
<td>


devlink files.

</td>
</tr>
<tr>
<td>


ena_debugfs.\[ch\]

</td>
<td>


debugfs files.

</td>
</tr>
</tbody>
</table>

<a id="rst-management-interface"></a>

## Management Interface:

ENA management interface is exposed by means of:

- PCIe Configuration Space

- Device Registers

- Admin Queue (AQ) and Admin Completion Queue (ACQ)

- Asynchronous Event Notification Queue (AENQ)

ENA device MMIO Registers are accessed only during driver initialization and are not used during further normal device operation.

AQ is used for submitting management commands, and the results/responses are reported asynchronously through ACQ.

ENA introduces a small set of management commands with room for vendor-specific extensions. Most of the management operations are framed in a generic Get/Set feature command.

The following admin queue commands are supported:

- Create I/O submission queue

- Create I/O completion queue

- Destroy I/O submission queue

- Destroy I/O completion queue

- Get feature

- Set feature

- Configure AENQ

- Get statistics

Refer to ena_admin_defs.h for the list of supported Get/Set Feature properties.

The Asynchronous Event Notification Queue (AENQ) is a uni-directional queue used by the ENA device to send to the driver events that cannot be reported using ACQ. AENQ events are subdivided into groups. Each group may have multiple syndromes, as shown below

The events are:


<table>
<thead>
<tr>
<th>


Group

</th>
<th>


Syndrome

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Link state change

</td>
<td>


**X**

</td>
</tr>
<tr>
<td>


Fatal error

</td>
<td>


**X**

</td>
</tr>
<tr>
<td>


Notification

</td>
<td>


Suspend traffic

</td>
</tr>
<tr>
<td>


Notification

</td>
<td>


Resume traffic

</td>
</tr>
<tr>
<td>


Keep-Alive

</td>
<td>


**X**

</td>
</tr>
</tbody>
</table>

ACQ and AENQ share the same MSI-X vector.

Keep-Alive is a special mechanism that allows monitoring the device's health. A Keep-Alive event is delivered by the device every second. The driver maintains a watchdog (WD) handler which logs the current state and statistics. If the keep-alive events aren't delivered as expected the WD resets the device and the driver.

<a id="rst-data-path-interface"></a>

## Data Path Interface

I/O operations are based on Tx and Rx Submission Queues (Tx SQ and Rx SQ correspondingly). Each SQ has a completion queue (CQ) associated with it.

The SQs and CQs are implemented as descriptor rings in contiguous physical memory.

The ENA driver supports two Queue Operation modes for Tx SQs:

- **Regular mode:** In this mode the Tx SQs reside in the host's memory. The ENA device fetches the ENA Tx descriptors and packet data from host memory.

- **Low Latency Queue (LLQ) mode or "push-mode":** In this mode the driver pushes the transmit descriptors and the first 96 bytes of the packet directly to the ENA device memory space. The rest of the packet payload is fetched by the device. For this operation mode, the driver uses a dedicated PCI device memory BAR, which is mapped with write-combine capability.

  **Note that** not all ENA devices support LLQ, and this feature is negotiated with the device upon initialization. If the ENA device does not support LLQ mode, the driver falls back to the regular mode.

The Rx SQs support only the regular mode.

The driver supports multi-queue for both Tx and Rx. This has various benefits:

- Reduced CPU/thread/process contention on a given Ethernet interface.

- Cache miss rate on completion is reduced, particularly for data cache lines that hold the sk_buff structures.

- Increased process-level parallelism when handling received packets.

- Increased data cache hit rate, by steering kernel processing of packets to the CPU, where the application thread consuming the packet is running.

- In hardware interrupt re-direction.

<a id="rst-interrupt-modes"></a>

## Interrupt Modes

The driver assigns a single MSI-X vector per queue pair (for both Tx and Rx directions). The driver assigns an additional dedicated MSI-X vector for management (for ACQ and AENQ).

Management interrupt registration is performed when the Linux kernel probes the adapter, and it is de-registered when the adapter is removed. I/O queue interrupt registration is performed when the Linux interface of the adapter is opened, and it is de-registered when the interface is closed.

The management interrupt is named:



```text
ena-mgmnt@pci:<PCI domain:bus:slot.function>
```

and for each queue pair, an interrupt is named:



```text
<interface name>-Tx-Rx-<queue index>
```

The ENA device operates in auto-mask and auto-clear interrupt modes. That is, once MSI-X is delivered to the host, its Cause bit is automatically cleared and the interrupt is masked. The interrupt is unmasked by the driver after NAPI processing is complete.

<a id="rst-interrupt-moderation"></a>

## Interrupt Moderation

ENA driver and device can operate in conventional or adaptive interrupt moderation mode.

**In conventional mode** the driver instructs device to postpone interrupt posting according to static interrupt delay value. The interrupt delay value can be configured through `ethtool(8)`. The following `ethtool` parameters are supported by the driver: `tx-usecs`, `rx-usecs`

**In adaptive interrupt** moderation mode the interrupt delay value is updated by the driver dynamically and adjusted every NAPI cycle according to the traffic nature.

Adaptive coalescing can be switched on/off through `ethtool(8)`'s `adaptive_rx on|off` parameter.

More information about Adaptive Interrupt Moderation (DIM) can be found in [Documentation/networking/net_dim.rst](/kernel/internals/networking/net-dim.md)

<a id="rst-rx-copybreak-1"></a>
<a id="rst-rx-copybreak"></a>

## RX copybreak

The rx_copybreak is initialized by default to ENA_DEFAULT_RX_COPYBREAK and can be configured by the ETHTOOL_STUNABLE command of the SIOCETHTOOL ioctl.

This option controls the maximum packet length for which the RX descriptor it was received on would be recycled. When a packet smaller than RX copybreak bytes is received, it is copied into a new memory buffer and the RX descriptor is returned to HW.

<a id="rst-ptp-hardware-clock-phc"></a>
<a id="rst-phc"></a>

## PTP Hardware Clock (PHC)

<a id="rst-ptp-userspace-api"></a>



<a id="rst-testptp"></a>



ENA Linux driver supports PTP hardware clock providing timestamp reference to achieve nanosecond resolution.

**PHC support**

PHC depends on the PTP module, which needs to be either loaded as a module or compiled into the kernel.

Verify if the PTP module is present:



```shell
grep -w '^CONFIG_PTP_1588_CLOCK=[ym]' /boot/config-`uname -r`
```

- If no output is provided, the ENA driver cannot be loaded with PHC support.

**PHC activation**

The feature is turned off by default, in order to turn the feature on, the ENA driver can be loaded in the following way:

- devlink:



```shell
sudo devlink dev param set pci/<domain:bus:slot.function> name enable_phc value true cmode driverinit
sudo devlink dev reload pci/<domain:bus:slot.function>
# for example:
sudo devlink dev param set pci/0000:00:06.0 name enable_phc value true cmode driverinit
sudo devlink dev reload pci/0000:00:06.0
```

All available PTP clock sources can be tracked here:



```shell
ls /sys/class/ptp
```

PHC support and capabilities can be verified using ethtool:



```shell
ethtool -T <interface>
```

**PHC timestamp**

To retrieve PHC timestamp, use [ptp-userspace-api](<https://docs.kernel.org/driver-api/ptp.html#ptp-hardware-clock-user-space-api>), usage example using [testptp](<https://elixir.bootlin.com/linux/latest/source/tools/testing/selftests/ptp/testptp.c>):



```shell
testptp -d /dev/ptp$(ethtool -T <interface> | awk '/PTP Hardware Clock:/ {print $NF}') -k 1
```

PHC get time requests should be within reasonable bounds, avoid excessive utilization to ensure optimal performance and efficiency. The ENA device restricts the frequency of PHC get time requests to a maximum of 125 requests per second. If this limit is surpassed, the get time request will fail, leading to an increment in the phc_err_ts statistic.

**PHC statistics**

PHC can be monitored using debugfs (if mounted):



```shell
sudo cat /sys/kernel/debug/<domain:bus:slot.function>/phc_stats

# for example:
sudo cat /sys/kernel/debug/0000:00:06.0/phc_stats
```

PHC errors must remain below 1% of all PHC requests to maintain the desired level of accuracy and reliability


<table>
<tbody>
<tr>
<td>


**phc_cnt**

</td>
<td>


Number of successful retrieved timestamps (below expire timeout).

</td>
</tr>
<tr>
<td>


**phc_exp**

</td>
<td>


Number of expired retrieved timestamps (above expire timeout).

</td>
</tr>
<tr>
<td>


**phc_skp**

</td>
<td>


Number of skipped get time attempts (during block period).

</td>
</tr>
<tr>
<td>


**phc_err_dv**

</td>
<td>


Number of failed get time attempts due to device errors (entering into block state).

</td>
</tr>
<tr>
<td>


**phc_err_ts**

</td>
<td>


Number of failed get time attempts due to timestamp errors (entering into block state),  
This occurs if driver exceeded the request limit or device received an invalid timestamp.

</td>
</tr>
</tbody>
</table>

PHC timeouts:


<table>
<tbody>
<tr>
<td>


**expire**

</td>
<td>


Max time for a valid timestamp retrieval, passing this threshold will fail  
the get time request and block new requests until block timeout.

</td>
</tr>
<tr>
<td>


**block**

</td>
<td>


Blocking period starts once get time request expires or fails,  
all get time requests during block period will be skipped.

</td>
</tr>
</tbody>
</table>

<a id="rst-statistics"></a>

## Statistics

The user can obtain ENA device and driver statistics using `ethtool`. The driver can collect regular or extended statistics (including per-queue stats) from the device.

In addition the driver logs the stats to syslog upon device reset.

On supported instance types, the statistics will also include the ENA Express data (fields prefixed with `ena_srd`). For a complete documentation of ENA Express data refer to [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html\#ena-express-monitor](<https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html#ena-express-monitor>)

<a id="rst-mtu"></a>

## MTU

The driver supports an arbitrarily large MTU with a maximum that is negotiated with the device. The driver configures MTU using the SetFeature command (ENA_ADMIN_MTU property). The user can change MTU via `ip(8)` and similar legacy tools.

<a id="rst-stateless-offloads"></a>

## Stateless Offloads

The ENA driver supports:

- IPv4 header checksum offload

- TCP/UDP over IPv4/IPv6 checksum offloads

<a id="rst-rss"></a>

## RSS

- The ENA device supports RSS that allows flexible Rx traffic steering.

- Toeplitz and CRC32 hash functions are supported.

- Different combinations of L2/L3/L4 fields can be configured as inputs for hash functions.

- The driver configures RSS settings using the AQ SetFeature command (ENA_ADMIN_RSS_HASH_FUNCTION, ENA_ADMIN_RSS_HASH_INPUT and ENA_ADMIN_RSS_INDIRECTION_TABLE_CONFIG properties).

- If the NETIF_F_RXHASH flag is set, the 32-bit result of the hash function delivered in the Rx CQ descriptor is set in the received SKB.

- The user can provide a hash key, hash function, and configure the indirection table through `ethtool(8)`.

<a id="rst-devlink-support"></a>

## DEVLINK SUPPORT

<a id="rst-devlink"></a>



[devlink](<https://www.kernel.org/doc/html/latest/networking/devlink/index.html>) supports reloading the driver and initiating re-negotiation with the ENA device



```shell
sudo devlink dev reload pci/<domain:bus:slot.function>
# for example:
sudo devlink dev reload pci/0000:00:06.0
```

<a id="rst-data-path"></a>

## DATA PATH

<a id="rst-tx"></a>

### Tx

`ena_start_xmit()` is called by the stack. This function does the following:

- Maps data buffers (`skb->data` and frags).

- Populates `ena_buf` for the push buffer (if the driver and device are in push mode).

- Prepares ENA bufs for the remaining frags.

- Allocates a new request ID from the empty `req_id` ring. The request ID is the index of the packet in the Tx info. This is used for out-of-order Tx completions.

- Adds the packet to the proper place in the Tx ring.

- Calls `ena_com_prepare_tx()`, an ENA communication layer that converts the `ena_bufs` to ENA descriptors (and adds meta ENA descriptors as needed).

  - This function also copies the ENA descriptors and the push buffer to the Device memory space (if in push mode).

- Writes a doorbell to the ENA device.

- When the ENA device finishes sending the packet, a completion interrupt is raised.

- The interrupt handler schedules NAPI.

- The `ena_clean_tx_irq()` function is called. This function handles the completion descriptors generated by the ENA, with a single completion descriptor per completed packet.

  - `req_id` is retrieved from the completion descriptor. The `tx_info` of the packet is retrieved via the `req_id`. The data buffers are unmapped and `req_id` is returned to the empty `req_id` ring.

  - The function stops when the completion descriptors are completed or the budget is reached.

<a id="rst-rx"></a>

### Rx

- When a packet is received from the ENA device.

- The interrupt handler schedules NAPI.

- The `ena_clean_rx_irq()` function is called. This function calls `ena_com_rx_pkt()`, an ENA communication layer function, which returns the number of descriptors used for a new packet, and zero if no new packet is found.

- `ena_rx_skb()` checks packet length:

  - If the packet is small (len &lt; rx_copybreak), the driver allocates a SKB for the new packet, and copies the packet payload into the SKB data buffer.

    - In this way the original data buffer is not passed to the stack and is reused for future Rx packets.

  - Otherwise the function unmaps the Rx buffer, sets the first descriptor as `skb`'s linear part and the other descriptors as the `skb`'s frags.

- The new SKB is updated with the necessary information (protocol, checksum hw verify result, etc), and then passed to the network stack, using the NAPI interface function `napi_gro_receive()`.

<a id="rst-dynamic-rx-buffers-drb"></a>

### Dynamic RX Buffers (DRB)

Each RX descriptor in the RX ring is a single memory page (which is either 4KB or 16KB long depending on system's configurations). To reduce the memory allocations required when dealing with a high rate of small packets, the driver tries to reuse the remaining RX descriptor's space if more than 2KB of this page remain unused.

A simple example of this mechanism is the following sequence of events:



```text
1. Driver allocates page-sized RX buffer and passes it to hardware
        +----------------------+
        |4KB RX Buffer         |
        +----------------------+

2. A 300Bytes packet is received on this buffer

3. The driver increases the ref count on this page and returns it back to
   HW as an RX buffer of size 4KB - 300Bytes = 3796 Bytes
       +----+--------------------+
       |****|3796 Bytes RX Buffer|
       +----+--------------------+
```

This mechanism isn't used when an XDP program is loaded, or when the RX packet is less than rx_copybreak bytes (in which case the packet is copied out of the RX buffer into the linear part of a new skb allocated for it and the RX buffer remains the same size, see [RX copybreak](<#rst-rx-copybreak>)).

---

# Linux Driver for the AMD/Pensando(R) DSC adapter family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / amd_

> Copyright(c) 2023 Advanced Micro Devices, Inc

<a id="rst-linux-driver-for-the-amd-pensando-r-dsc-adapter-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Copyright(c) 2023 Advanced Micro Devices, Inc

<a id="rst-identifying-the-adapter"></a>

## Identifying the Adapter

To find if one or more AMD/Pensando PCI Core devices are installed on the host, check for the PCI devices:



```text
# lspci -d 1dd8:100c
b5:00.0 Processing accelerators: Pensando Systems Device 100c
b6:00.0 Processing accelerators: Pensando Systems Device 100c
```

If such devices are listed as above, then the pds_core.ko driver should find and configure them for use.  There should be log entries in the kernel messages such as these:



```text
$ dmesg | grep pds_core
pds_core 0000:b5:00.0: 252.048 Gb/s available PCIe bandwidth (16.0 GT/s PCIe x16 link)
pds_core 0000:b5:00.0: FW: 1.60.0-73
pds_core 0000:b6:00.0: 252.048 Gb/s available PCIe bandwidth (16.0 GT/s PCIe x16 link)
pds_core 0000:b6:00.0: FW: 1.60.0-73
```

Driver and firmware version information can be gathered with devlink:



```text
$ devlink dev info pci/0000:b5:00.0
pci/0000:b5:00.0:
  driver pds_core
  serial_number FLM18420073
  versions:
      fixed:
        asic.id 0x0
        asic.rev 0x0
      running:
        fw 1.51.0-73
      stored:
        fw.goldfw 1.15.9-C-22
        fw.mainfwa 1.60.0-73
        fw.mainfwb 1.60.0-57
```

<a id="rst-info-versions"></a>

## Info versions

The `pds_core` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Version of firmware running on the device

</td>
</tr>
<tr>
<td>


`fw.goldfw`

</td>
<td>


stored

</td>
<td>


Version of firmware stored in the goldfw slot

</td>
</tr>
<tr>
<td>


`fw.mainfwa`

</td>
<td>


stored

</td>
<td>


Version of firmware stored in the mainfwa slot

</td>
</tr>
<tr>
<td>


`fw.mainfwb`

</td>
<td>


stored

</td>
<td>


Version of firmware stored in the mainfwb slot

</td>
</tr>
<tr>
<td>


`asic.id`

</td>
<td>


fixed

</td>
<td>


The ASIC type for this device

</td>
</tr>
<tr>
<td>


`asic.rev`

</td>
<td>


fixed

</td>
<td>


The revision of the ASIC for this device

</td>
</tr>
</tbody>
</table>

<a id="rst-parameters"></a>

## Parameters

The `pds_core` driver implements the following generic parameters for controlling the functionality to be made available as auxiliary_bus devices.


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`enable_vnet`

</td>
<td>


runtime

</td>
<td>


Boolean

</td>
<td>


Enables vDPA functionality through an auxiliary_bus device

</td>
</tr>
</tbody>
</table>

<a id="rst-firmware-management"></a>

## Firmware Management

The `flash` command can update a the DSC firmware.  The downloaded firmware will be saved into either of firmware bank 1 or bank 2, whichever is not currently in use, and that bank will used for the next boot:



```text
# devlink dev flash pci/0000:b5:00.0 \
          file pensando/dsc_fw_1.63.0-22.tar
```

<a id="rst-health-reporters"></a>

## Health Reporters

The driver supports a devlink health reporter for FW status:



```text
# devlink health show pci/0000:2b:00.0 reporter fw
pci/0000:2b:00.0:
  reporter fw
    state healthy error 0 recover 0
# devlink health diagnose pci/0000:2b:00.0 reporter fw
 Status: healthy State: 1 Generation: 0 Recoveries: 0
```

<a id="rst-enabling-the-driver"></a>

## Enabling the driver

The driver is enabled via the standard kernel configuration system, using the make command:



```text
make oldconfig/menuconfig/etc.
```

The driver is located in the menu structure at:

> - **-&gt; Device Drivers**
>
>   - **-&gt; Network device support (NETDEVICES \[=y\])**
>
>     - **-&gt; Ethernet driver support**
>
>       - **-&gt; AMD devices**
>
>         -&gt; AMD/Pensando Ethernet PDS_CORE Support

<a id="rst-support"></a>

## Support

For general Linux networking support, please use the netdev mailing list, which is monitored by AMD/Pensando personnel:



```text
netdev@vger.kernel.org
```

---

# PCI vDPA driver for the AMD/Pensando(R) DSC adapter family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / amd_

> AMD/Pensando vDPA VF Device Driver

<a id="rst-pci-vdpa-driver-for-the-amd-pensando-r-dsc-adapter-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<!-- note: can be edited and viewed with /usr/bin/formiko-vim -->

AMD/Pensando vDPA VF Device Driver

Copyright(c) 2023 Advanced Micro Devices, Inc

<a id="rst-overview"></a>

## Overview

The `pds_vdpa` driver is an auxiliary bus driver that supplies a vDPA device for use by the virtio network stack.  It is used with the Pensando Virtual Function devices that offer vDPA and virtio queue services.  It depends on the `pds_core` driver and hardware for the PF and VF PCI handling as well as for device configuration services.

<a id="rst-using-the-device"></a>

## Using the device

The `pds_vdpa` device is enabled via multiple configuration steps and depends on the `pds_core` driver to create and enable SR-IOV Virtual Function devices.  After the VFs are enabled, we enable the vDPA service in the `pds_core` device to create the auxiliary devices used by pds_vdpa.

Example steps:



```bash
#!/bin/bash

modprobe pds_core
modprobe vdpa
modprobe pds_vdpa

PF_BDF=`ls /sys/module/pds_core/drivers/pci\:pds_core/*/sriov_numvfs | awk -F / '{print $7}'`

# Enable vDPA VF auxiliary device(s) in the PF
devlink dev param set pci/$PF_BDF name enable_vnet cmode runtime value true

# Create a VF for vDPA use
echo 1 > /sys/bus/pci/drivers/pds_core/$PF_BDF/sriov_numvfs

# Find the vDPA services/devices available
PDS_VDPA_MGMT=`vdpa mgmtdev show | grep vDPA | head -1 | cut -d: -f1`

# Create a vDPA device for use in virtio network configurations
vdpa dev add name vdpa1 mgmtdev $PDS_VDPA_MGMT mac 00:11:22:33:44:55

# Set up an ethernet interface on the vdpa device
modprobe virtio_vdpa
```

<a id="rst-enabling-the-driver"></a>

## Enabling the driver

The driver is enabled via the standard kernel configuration system, using the make command:



```text
make oldconfig/menuconfig/etc.
```

The driver is located in the menu structure at:

> - **-&gt; Device Drivers**
>
>   - **-&gt; Network device support (NETDEVICES \[=y\])**
>
>     - **-&gt; Ethernet driver support**
>
>       - **-&gt; Pensando devices**
>
>         -&gt; Pensando Ethernet PDS_VDPA Support

<a id="rst-support"></a>

## Support

For general Linux networking support, please use the netdev mailing list, which is monitored by Pensando personnel:



```text
netdev@vger.kernel.org
```

For more specific support needs, please use the Pensando driver support email:



```text
drivers@pensando.io
```

---

# PCI VFIO driver for the AMD/Pensando(R) DSC adapter family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / amd_

> AMD/Pensando Linux VFIO PCI Device Driver Copyright(c) 2023 Advanced Micro Devices, Inc.

<a id="rst-pci-vfio-driver-for-the-amd-pensando-r-dsc-adapter-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<!-- note: can be edited and viewed with /usr/bin/formiko-vim -->

AMD/Pensando Linux VFIO PCI Device Driver Copyright(c) 2023 Advanced Micro Devices, Inc.

<a id="rst-overview"></a>

## Overview

The `pds-vfio-pci` module is a PCI driver that supports Live Migration capable Virtual Function (VF) devices in the DSC hardware.

<a id="rst-using-the-device"></a>

## Using the device

The pds-vfio-pci device is enabled via multiple configuration steps and depends on the `pds_core` driver to create and enable SR-IOV Virtual Function devices.

Shown below are the steps to bind the driver to a VF and also to the associated auxiliary device created by the `pds_core` driver. This example assumes the pds_core and pds-vfio-pci modules are already loaded.

<a id="rst-example-setup-script"></a>



```bash
#!/bin/bash

PF_BUS="0000:60"
PF_BDF="0000:60:00.0"
VF_BDF="0000:60:00.1"

# Prevent non-vfio VF driver from probing the VF device
echo 0 > /sys/class/pci_bus/$PF_BUS/device/$PF_BDF/sriov_drivers_autoprobe

# Create single VF for Live Migration via pds_core
echo 1 > /sys/bus/pci/drivers/pds_core/$PF_BDF/sriov_numvfs

# Allow the VF to be bound to the pds-vfio-pci driver
echo "pds-vfio-pci" > /sys/class/pci_bus/$PF_BUS/device/$VF_BDF/driver_override

# Bind the VF to the pds-vfio-pci driver
echo "$VF_BDF" > /sys/bus/pci/drivers/pds-vfio-pci/bind
```

After performing the steps above, a file in /dev/vfio/&lt;iommu_group&gt; should have been created.

<a id="rst-enabling-the-driver"></a>

## Enabling the driver

The driver is enabled via the standard kernel configuration system, using the make command:



```text
make oldconfig/menuconfig/etc.
```

The driver is located in the menu structure at:

> - **-&gt; Device Drivers**
>
>   - **-&gt; VFIO Non-Privileged userspace driver framework**
>
>     -&gt; VFIO support for PDS PCI devices

<a id="rst-support"></a>

## Support

For general Linux networking support, please use the netdev mailing list, which is monitored by Pensando personnel:



```text
netdev@vger.kernel.org
```

For more specific support needs, please use the Pensando driver support email:



```text
drivers@pensando.io
```

---

# Marvell(Aquantia) AQtion Driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / aquantia_

> For the aQuantia Multi-Gigabit PCI Express Family of Ethernet Adapters

<a id="rst-marvell-aquantia-aqtion-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

For the aQuantia Multi-Gigabit PCI Express Family of Ethernet Adapters

<!-- Contents

- Identifying Your Adapter
- Configuration
- Supported ethtool options
- Command Line Parameters
- Config file parameters
- Support
- License -->

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver in this release is compatible with AQC-100, AQC-107, AQC-108 based ethernet adapters.

<a id="rst-sfp-devices-for-aqc-100-based-adapters"></a>

### SFP+ Devices (for AQC-100 based adapters)

This release tested with passive Direct Attach Cables (DAC) and SFP+/LC Optical Transceiver.

<a id="rst-configuration"></a>

## Configuration

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

> Link messages will not be displayed to the console if the distribution is restricting system messages. In order to see network driver link messages on your console, set dmesg to eight by entering the following:
>
>
>
> ```text
> dmesg -n 8
> ```
>
> > [!NOTE]
> >
> > This setting is not saved across reboots.

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

> The driver supports Jumbo Frames for all adapters. Jumbo Frames support is enabled by changing the MTU to a value larger than the default of 1500. The maximum value for the MTU is 16000.  Use the `ip` command to increase the MTU size.  For example:
>
>
>
> ```text
> ip link set mtu 16000 dev enp1s0
> ```

<a id="rst-ethtool"></a>

### ethtool

> The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality.

<a id="rst-napi"></a>

### NAPI

> NAPI (Rx polling mode) is supported in the atlantic driver.

<a id="rst-supported-ethtool-options"></a>

## Supported ethtool options

<a id="rst-viewing-adapter-settings"></a>

### Viewing adapter settings

>
>
> ```text
> ethtool <ethX>
> ```
>
> Output example:
>
>
>
> ```text
> Settings for enp1s0:
>   Supported ports: [ TP ]
>   Supported link modes:   100baseT/Full
>                           1000baseT/Full
>                           10000baseT/Full
>                           2500baseT/Full
>                           5000baseT/Full
>   Supported pause frame use: Symmetric
>   Supports auto-negotiation: Yes
>   Supported FEC modes: Not reported
>   Advertised link modes:  100baseT/Full
>                           1000baseT/Full
>                           10000baseT/Full
>                           2500baseT/Full
>                           5000baseT/Full
>   Advertised pause frame use: Symmetric
>   Advertised auto-negotiation: Yes
>   Advertised FEC modes: Not reported
>   Speed: 10000Mb/s
>   Duplex: Full
>   Port: Twisted Pair
>   PHYAD: 0
>   Transceiver: internal
>   Auto-negotiation: on
>   MDI-X: Unknown
>   Supports Wake-on: g
>   Wake-on: d
>   Link detected: yes
> ```
>
> > [!NOTE]
> >
> > AQrate speeds (2.5/5 Gb/s) will be displayed only with linux kernels &gt; 4.10. But you can still use these speeds:
> >
> >
> >
> > ```text
> > ethtool -s eth0 autoneg off speed 2500
> > ```

<a id="rst-viewing-adapter-information"></a>

### Viewing adapter information

>
>
> ```text
> ethtool -i <ethX>
> ```
>
> Output example:
>
>
>
> ```text
> driver: atlantic
> version: 5.2.0-050200rc5-generic-kern
> firmware-version: 3.1.78
> expansion-rom-version:
> bus-info: 0000:01:00.0
> supports-statistics: yes
> supports-test: no
> supports-eeprom-access: no
> supports-register-dump: yes
> supports-priv-flags: no
> ```

<a id="rst-viewing-ethernet-adapter-statistics"></a>

### Viewing Ethernet adapter statistics

>
>
> ```text
> ethtool -S <ethX>
> ```
>
> Output example:
>
>
>
> ```text
> NIC statistics:
>    InPackets: 13238607
>    InUCast: 13293852
>    InMCast: 52
>    InBCast: 3
>    InErrors: 0
>    OutPackets: 23703019
>    OutUCast: 23704941
>    OutMCast: 67
>    OutBCast: 11
>    InUCastOctects: 213182760
>    OutUCastOctects: 22698443
>    InMCastOctects: 6600
>    OutMCastOctects: 8776
>    InBCastOctects: 192
>    OutBCastOctects: 704
>    InOctects: 2131839552
>    OutOctects: 226938073
>    InPacketsDma: 95532300
>    OutPacketsDma: 59503397
>    InOctetsDma: 1137102462
>    OutOctetsDma: 2394339518
>    InDroppedDma: 0
>    Queue[0] InPackets: 23567131
>    Queue[0] OutPackets: 20070028
>    Queue[0] InJumboPackets: 0
>    Queue[0] InLroPackets: 0
>    Queue[0] InErrors: 0
>    Queue[1] InPackets: 45428967
>    Queue[1] OutPackets: 11306178
>    Queue[1] InJumboPackets: 0
>    Queue[1] InLroPackets: 0
>    Queue[1] InErrors: 0
>    Queue[2] InPackets: 3187011
>    Queue[2] OutPackets: 13080381
>    Queue[2] InJumboPackets: 0
>    Queue[2] InLroPackets: 0
>    Queue[2] InErrors: 0
>    Queue[3] InPackets: 23349136
>    Queue[3] OutPackets: 15046810
>    Queue[3] InJumboPackets: 0
>    Queue[3] InLroPackets: 0
>    Queue[3] InErrors: 0
> ```

<a id="rst-interrupt-coalescing-support"></a>

### Interrupt coalescing support

> ITR mode, TX/RX coalescing timings could be viewed with:
>
>
>
> ```text
> ethtool -c <ethX>
> ```
>
> and changed with:
>
>
>
> ```text
> ethtool -C <ethX> tx-usecs <usecs> rx-usecs <usecs>
> ```
>
> To disable coalescing:
>
>
>
> ```text
> ethtool -C <ethX> tx-usecs 0 rx-usecs 0 tx-max-frames 1 tx-max-frames 1
> ```

<a id="rst-wake-on-lan-support"></a>

### Wake on LAN support

> WOL support by magic packet:
>
>
>
> ```text
> ethtool -s <ethX> wol g
> ```
>
> To disable WOL:
>
>
>
> ```text
> ethtool -s <ethX> wol d
> ```

<a id="rst-set-and-check-the-driver-message-level"></a>

### Set and check the driver message level

> Set message level
>
>
>
> ```text
> ethtool -s <ethX> msglvl <level>
> ```
>
> Level values:
>
>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 0x0001
>
> </td>
> <td>
>
>
> general driver status.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0002
>
> </td>
> <td>
>
>
> hardware probing.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0004
>
> </td>
> <td>
>
>
> link state.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0008
>
> </td>
> <td>
>
>
> periodic status check.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0010
>
> </td>
> <td>
>
>
> interface being brought down.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0020
>
> </td>
> <td>
>
>
> interface being brought up.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0040
>
> </td>
> <td>
>
>
> receive error.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0080
>
> </td>
> <td>
>
>
> transmit error.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0200
>
> </td>
> <td>
>
>
> interrupt handling.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0400
>
> </td>
> <td>
>
>
> transmit completion.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x0800
>
> </td>
> <td>
>
>
> receive completion.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x1000
>
> </td>
> <td>
>
>
> packet contents.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x2000
>
> </td>
> <td>
>
>
> hardware status.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0x4000
>
> </td>
> <td>
>
>
> Wake-on-LAN status.
>
> </td>
> </tr>
> </tbody>
> </table>
>
> By default, the level of debugging messages is set 0x0001(general driver status).
>
> Check message level
>
>
>
> ```text
> ethtool <ethX> | grep "Current message level"
> ```
>
> If you want to disable the output of messages:
>
>
>
> ```text
> ethtool -s <ethX> msglvl 0
> ```

<a id="rst-rx-flow-rules-ntuple-filters"></a>

### RX flow rules (ntuple filters)

> There are separate rules supported, that applies in that order:
>
> 1. 16 VLAN ID rules
>
> 2. 16 L2 EtherType rules
>
> 3. 8 L3/L4 5-Tuple rules
>
> The driver utilizes the ethtool interface for configuring ntuple filters, via `ethtool -N <device> <filter>`.
>
> To enable or disable the RX flow rules:
>
>
>
> ```text
> ethtool -K ethX ntuple <on|off>
> ```
>
> When disabling ntuple filters, all the user programmed filters are flushed from the driver cache and hardware. All needed filters must be re-added when ntuple is re-enabled.
>
> Because of the fixed order of the rules, the location of filters is also fixed:
>
> - Locations 0 - 15 for VLAN ID filters
>
> - Locations 16 - 31 for L2 EtherType filters
>
> - Locations 32 - 39 for L3/L4 5-tuple filters (locations 32, 36 for IPv6)
>
> The L3/L4 5-tuple (protocol, source and destination IP address, source and destination TCP/UDP/SCTP port) is compared against 8 filters. For IPv4, up to 8 source and destination addresses can be matched. For IPv6, up to 2 pairs of addresses can be supported. Source and destination ports are only compared for TCP/UDP/SCTP packets.
>
> To add a filter that directs packet to queue 5, use `<-N|-U|--config-nfc|--config-ntuple>` switch:
>
>
>
> ```text
> ethtool -N <ethX> flow-type udp4 src-ip 10.0.0.1 dst-ip 10.0.0.2 src-port 2000 dst-port 2001 action 5 <loc 32>
> ```
>
> - action is the queue number.
>
> - loc is the rule number.
>
> For `flow-type ip4|udp4|tcp4|sctp4|ip6|udp6|tcp6|sctp6` you must set the loc number within 32 - 39. For `flow-type ip4|udp4|tcp4|sctp4|ip6|udp6|tcp6|sctp6` you can set 8 rules for traffic IPv4 or you can set 2 rules for traffic IPv6. Loc number traffic IPv6 is 32 and 36. At the moment you can not use IPv4 and IPv6 filters at the same time.
>
> Example filter for IPv6 filter traffic:
>
>
>
> ```text
> sudo ethtool -N <ethX> flow-type tcp6 src-ip 2001:db8:0:f101::1 dst-ip 2001:db8:0:f101::2 action 1 loc 32
> sudo ethtool -N <ethX> flow-type ip6 src-ip 2001:db8:0:f101::2 dst-ip 2001:db8:0:f101::5 action -1 loc 36
> ```
>
> Example filter for IPv4 filter traffic:
>
>
>
> ```text
> sudo ethtool -N <ethX> flow-type udp4 src-ip 10.0.0.4 dst-ip 10.0.0.7 src-port 2000 dst-port 2001 loc 32
> sudo ethtool -N <ethX> flow-type tcp4 src-ip 10.0.0.3 dst-ip 10.0.0.9 src-port 2000 dst-port 2001 loc 33
> sudo ethtool -N <ethX> flow-type ip4 src-ip 10.0.0.6 dst-ip 10.0.0.4 loc 34
> ```
>
> If you set action -1, then all traffic corresponding to the filter will be discarded.
>
> The maximum value action is 31.
>
> The VLAN filter (VLAN id) is compared against 16 filters. VLAN id must be accompanied by mask 0xF000. That is to distinguish VLAN filter from L2 Ethertype filter with UserPriority since both User Priority and VLAN ID are passed in the same 'vlan' parameter.
>
> To add a filter that directs packets from VLAN 2001 to queue 5:
>
>
>
> ```text
> ethtool -N <ethX> flow-type ip4 vlan 2001 m 0xF000 action 1 loc 0
> ```
>
> L2 EtherType filters allows filter packet by EtherType field or both EtherType and User Priority (PCP) field of 802.1Q. UserPriority (vlan) parameter must be accompanied by mask 0x1FFF. That is to distinguish VLAN filter from L2 Ethertype filter with UserPriority since both User Priority and VLAN ID are passed in the same 'vlan' parameter.
>
> To add a filter that directs IP4 packess of priority 3 to queue 3:
>
>
>
> ```text
> ethtool -N <ethX> flow-type ether proto 0x800 vlan 0x600 m 0x1FFF action 3 loc 16
> ```
>
> To see the list of filters currently present:
>
>
>
> ```text
> ethtool <-u|-n|--show-nfc|--show-ntuple> <ethX>
> ```
>
> Rules may be deleted from the table itself. This is done using:
>
>
>
> ```text
> sudo ethtool <-N|-U|--config-nfc|--config-ntuple> <ethX> delete <loc>
> ```
>
> - loc is the rule number to be deleted.
>
> Rx filters is an interface to load the filter table that funnels all flow into queue 0 unless an alternative queue is specified using "action". In that case, any flow that matches the filter criteria will be directed to the appropriate queue. RX filters is supported on all kernels 2.6.30 and later.

<a id="rst-rss-for-udp"></a>

### RSS for UDP

> Currently, NIC does not support RSS for fragmented IP packets, which leads to incorrect working of RSS for fragmented UDP traffic. To disable RSS for UDP the RX Flow L3/L4 rule may be used.
>
> Example:
>
>
>
> ```text
> ethtool -N eth0 flow-type udp4 action 0 loc 32
> ```

<a id="rst-udp-gso-hardware-offload"></a>

### UDP GSO hardware offload

> UDP GSO allows to boost UDP tx rates by offloading UDP headers allocation into hardware. A special userspace socket option is required for this, could be validated with /kernel/tools/testing/selftests/net/:
>
>
>
> ```text
> udpgso_bench_tx -u -4 -D 10.0.1.1 -s 6300 -S 100
> ```
>
> Will cause sending out of 100 byte sized UDP packets formed from single 6300 bytes user buffer.
>
> UDP GSO is configured by:
>
>
>
> ```text
> ethtool -K eth0 tx-udp-segmentation on
> ```

<a id="rst-private-flags-testing"></a>

### Private flags (testing)

> Atlantic driver supports private flags for hardware custom features:
>
>
>
> ```text
> $ ethtool --show-priv-flags ethX
>
> Private flags for ethX:
> DMASystemLoopback  : off
> PKTSystemLoopback  : off
> DMANetworkLoopback : off
> PHYInternalLoopback: off
> PHYExternalLoopback: off
> ```
>
> Example:
>
>
>
> ```text
> $ ethtool --set-priv-flags ethX DMASystemLoopback on
> ```
>
> DMASystemLoopback:   DMA Host loopback. PKTSystemLoopback:   Packet buffer host loopback. DMANetworkLoopback:  Network side loopback on DMA block. PHYInternalLoopback: Internal loopback on Phy. PHYExternalLoopback: External loopback on Phy (with loopback ethernet cable).

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

The following command line parameters are available on atlantic driver:

<a id="rst-aq-itr-interrupt-throttling-mode"></a>

### aq_itr -Interrupt throttling mode

Accepted values: 0, 1, 0xFFFF

Default value: 0xFFFF


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


Disable interrupt throttling.

</td>
</tr>
<tr>
<td>


1

</td>
<td>


Enable interrupt throttling and use specified tx and rx rates.

</td>
</tr>
<tr>
<td>


0xFFFF

</td>
<td>


Auto throttling mode. Driver will choose the best RX and TX interrupt throttling settings based on link speed.

</td>
</tr>
</tbody>
</table>

<a id="rst-aq-itr-tx-tx-interrupt-throttle-rate"></a>

### aq_itr_tx - TX interrupt throttle rate

Accepted values: 0 - 0x1FF

Default value: 0

TX side throttling in microseconds. Adapter will setup maximum interrupt delay to this value. Minimum interrupt delay will be a half of this value

<a id="rst-aq-itr-rx-rx-interrupt-throttle-rate"></a>

### aq_itr_rx - RX interrupt throttle rate

Accepted values: 0 - 0x1FF

Default value: 0

RX side throttling in microseconds. Adapter will setup maximum interrupt delay to this value. Minimum interrupt delay will be a half of this value

> [!NOTE]
>
> ITR settings could be changed in runtime by ethtool -c means (see below)

<a id="rst-config-file-parameters"></a>

## Config file parameters

For some fine tuning and performance optimizations, some parameters can be changed in the \{source_dir\}/aq_cfg.h file.

<a id="rst-aq-cfg-rx-pageorder"></a>

### AQ_CFG_RX_PAGEORDER

Default value: 0

RX page order override. That's a power of 2 number of RX pages allocated for each descriptor. Received descriptor size is still limited by AQ_CFG_RX_FRAME_MAX.

Increasing pageorder makes page reuse better (actual on iommu enabled systems).

<a id="rst-aq-cfg-rx-refill-thres"></a>

### AQ_CFG_RX_REFILL_THRES

Default value: 32

RX refill threshold. RX path will not refill freed descriptors until the specified number of free descriptors is observed. Larger values may help better page reuse but may lead to packet drops as well.

<a id="rst-aq-cfg-vecs-def"></a>

### AQ_CFG_VECS_DEF

Number of queues

Valid Range: 0 - 8 (up to AQ_CFG_VECS_MAX)

Default value: 8

Notice this value will be capped by the number of cores available on the system.

<a id="rst-aq-cfg-is-rss-def"></a>

### AQ_CFG_IS_RSS_DEF

Enable/disable Receive Side Scaling

This feature allows the adapter to distribute receive processing across multiple CPU-cores and to prevent from overloading a single CPU core.

Valid values


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


disabled

</td>
</tr>
<tr>
<td>


1

</td>
<td>


enabled

</td>
</tr>
</tbody>
</table>

Default value: 1

<a id="rst-aq-cfg-num-rss-queues-def"></a>

### AQ_CFG_NUM_RSS_QUEUES_DEF

Number of queues for Receive Side Scaling

Valid Range: 0 - 8 (up to AQ_CFG_VECS_DEF)

Default value: AQ_CFG_VECS_DEF

<a id="rst-aq-cfg-is-lro-def"></a>

### AQ_CFG_IS_LRO_DEF

Enable/disable Large Receive Offload

This offload enables the adapter to coalesce multiple TCP segments and indicate them as a single coalesced unit to the OS networking subsystem.

The system consumes less energy but it also introduces more latency in packets processing.

Valid values


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


disabled

</td>
</tr>
<tr>
<td>


1

</td>
<td>


enabled

</td>
</tr>
</tbody>
</table>

Default value: 1

<a id="rst-aq-cfg-tx-clean-budget"></a>

### AQ_CFG_TX_CLEAN_BUDGET

Maximum descriptors to cleanup on TX at once.

Default value: 256

After the aq_cfg.h file changed the driver must be rebuilt to take effect.

<a id="rst-support"></a>

## Support

If an issue is identified with the released source code on the supported kernel with a supported adapter, email the specific information related to the issue to [aqn_support@marvell.com](<mailto:aqn_support@marvell.com>)

<a id="rst-license"></a>

## License

aQuantia Corporation Network Driver

Copyright © 2014 - 2019 aQuantia Corporation.

This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation.

---

# Chelsio N210 10Gb Ethernet Network Controller

_Peios Kernel / Internals / Networking / device_drivers / ethernet / chelsio_

> Driver Release Notes for Linux

<a id="rst-chelsio-n210-10gb-ethernet-network-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Driver Release Notes for Linux

Version 2.1.1

June 20, 2005

<!-- Contents

INTRODUCTION
FEATURES
PERFORMANCE
DRIVER MESSAGES
KNOWN ISSUES
SUPPORT -->

<a id="rst-introduction"></a>

## Introduction

> This document describes the Linux driver for Chelsio 10Gb Ethernet Network Controller. This driver supports the Chelsio N210 NIC and is backward compatible with the Chelsio N110 model 10Gb NICs.

<a id="rst-features"></a>

## Features

<a id="rst-adaptive-interrupts-adaptive-rx"></a>

### Adaptive Interrupts (adaptive-rx)

> This feature provides an adaptive algorithm that adjusts the interrupt coalescing parameters, allowing the driver to dynamically adapt the latency settings to achieve the highest performance during various types of network load.
>
> The interface used to control this feature is ethtool. Please see the ethtool manpage for additional usage information.
>
> By default, adaptive-rx is disabled. To enable adaptive-rx:
>
>
>
> ```text
> ethtool -C <interface> adaptive-rx on
> ```
>
> To disable adaptive-rx, use ethtool:
>
>
>
> ```text
> ethtool -C <interface> adaptive-rx off
> ```
>
> After disabling adaptive-rx, the timer latency value will be set to 50us. You may set the timer latency after disabling adaptive-rx:
>
>
>
> ```text
> ethtool -C <interface> rx-usecs <microseconds>
> ```
>
> An example to set the timer latency value to 100us on eth0:
>
>
>
> ```text
> ethtool -C eth0 rx-usecs 100
> ```
>
> You may also provide a timer latency value while disabling adaptive-rx:
>
>
>
> ```text
> ethtool -C <interface> adaptive-rx off rx-usecs <microseconds>
> ```
>
> If adaptive-rx is disabled and a timer latency value is specified, the timer will be set to the specified value until changed by the user or until adaptive-rx is enabled.
>
> To view the status of the adaptive-rx and timer latency values:
>
>
>
> ```text
> ethtool -c <interface>
> ```

<a id="rst-tcp-segmentation-offloading-tso-support"></a>

### TCP Segmentation Offloading (TSO) Support

> This feature, also known as "large send", enables a system's protocol stack to offload portions of outbound TCP processing to a network interface card thereby reducing system CPU utilization and enhancing performance.
>
> The interface used to control this feature is ethtool version 1.8 or higher. Please see the ethtool manpage for additional usage information.
>
> By default, TSO is enabled. To disable TSO:
>
>
>
> ```text
> ethtool -K <interface> tso off
> ```
>
> To enable TSO:
>
>
>
> ```text
> ethtool -K <interface> tso on
> ```
>
> To view the status of TSO:
>
>
>
> ```text
> ethtool -k <interface>
> ```

<a id="rst-performance"></a>

## Performance

> The following information is provided as an example of how to change system parameters for "performance tuning" an what value to use. You may or may not want to change these system parameters, depending on your server/workstation application. Doing so is not warranted in any way by Chelsio Communications, and is done at "YOUR OWN RISK". Chelsio will not be held responsible for loss of data or damage to equipment.
>
> Your distribution may have a different way of doing things, or you may prefer a different method. These commands are shown only to provide an example of what to do and are by no means definitive.
>
> Making any of the following system changes will only last until you reboot your system. You may want to write a script that runs at boot-up which includes the optimal settings for your system.
>
> > Setting PCI Latency Timer:
> >
> >
> >
> > ```text
> > setpci -d 1425::
> > ```

- 0x0c.l=0x0000F800

  Disabling TCP timestamp:



  ```text
  sysctl -w net.ipv4.tcp_timestamps=0
  ```

  Disabling SACK:



  ```text
  sysctl -w net.ipv4.tcp_sack=0
  ```

  Setting large number of incoming connection requests:



  ```text
  sysctl -w net.ipv4.tcp_max_syn_backlog=3000
  ```

  Setting maximum receive socket buffer size:



  ```text
  sysctl -w net.core.rmem_max=1024000
  ```

  Setting maximum send socket buffer size:



  ```text
  sysctl -w net.core.wmem_max=1024000
  ```

  Set smp_affinity (on a multiprocessor system) to a single CPU:



  ```text
  echo 1 > /proc/irq/<interrupt_number>/smp_affinity
  ```

  Setting default receive socket buffer size:



  ```text
  sysctl -w net.core.rmem_default=524287
  ```

  Setting default send socket buffer size:



  ```text
  sysctl -w net.core.wmem_default=524287
  ```

  Setting maximum option memory buffers:



  ```text
  sysctl -w net.core.optmem_max=524287
  ```

  Setting maximum backlog (\# of unprocessed packets before kernel drops):



  ```text
  sysctl -w net.core.netdev_max_backlog=300000
  ```

  Setting TCP read buffers (min/default/max):



  ```text
  sysctl -w net.ipv4.tcp_rmem="10000000 10000000 10000000"
  ```

  Setting TCP write buffers (min/pressure/max):



  ```text
  sysctl -w net.ipv4.tcp_wmem="10000000 10000000 10000000"
  ```

  Setting TCP buffer space (min/pressure/max):



  ```text
  sysctl -w net.ipv4.tcp_mem="10000000 10000000 10000000"
  ```

  TCP window size for single connections:

  > The receive buffer (RX_WINDOW) size must be at least as large as the Bandwidth-Delay Product of the communication link between the sender and receiver. Due to the variations of RTT, you may want to increase the buffer size up to 2 times the Bandwidth-Delay Product. Reference page 289 of "TCP/IP Illustrated, Volume 1, The Protocols" by W. Richard Stevens.
  >
  > At 10Gb speeds, use the following formula:
  >
  >
  >
  > ```text
  > RX_WINDOW >= 1.25MBytes * RTT(in milliseconds)
  > Example for RTT with 100us: RX_WINDOW = (1,250,000 * 0.1) = 125,000
  > ```
  >
  > RX_WINDOW sizes of 256KB - 512KB should be sufficient.
  >
  > Setting the min, max, and default receive buffer (RX_WINDOW) size:
  >
  >
  >
  > ```text
  > sysctl -w net.ipv4.tcp_rmem="<min> <default> <max>"
  > ```

  - **TCP window size for multiple connections:**

    The receive buffer (RX_WINDOW) size may be calculated the same as single connections, but should be divided by the number of connections. The smaller window prevents congestion and facilitates better pacing, especially if/when MAC level flow control does not work well or when it is not supported on the machine. Experimentation may be necessary to attain the correct value. This method is provided as a starting point for the correct receive buffer size.

    Setting the min, max, and default receive buffer (RX_WINDOW) size is performed in the same manner as single connection.

<a id="rst-driver-messages"></a>

## Driver Messages

> The following messages are the most common messages logged by syslog. These may be found in /var/log/messages.
>
> > Driver up:
> >
> >
> >
> > ```text
> > Chelsio Network Driver - version 2.1.1
> > ```
> >
> > NIC detected:
> >
> >
> >
> > ```text
> > eth#: Chelsio N210 1x10GBaseX NIC (rev #), PCIX 133MHz/64-bit
> > ```
> >
> > Link up:
> >
> >
> >
> > ```text
> > eth#: link is up at 10 Gbps, full duplex
> > ```
> >
> > Link down:
> >
> >
> >
> > ```text
> > eth#: link is down
> > ```

<a id="rst-known-issues"></a>

## Known Issues

> These issues have been identified during testing. The following information is provided as a workaround to the problem. In some cases, this problem is inherent to Linux or to a particular Linux Distribution and/or hardware platform.
>
> > 1. Large number of TCP retransmits on a multiprocessor (SMP) system.
> >
> >    > On a system with multiple CPUs, the interrupt (IRQ) for the network controller may be bound to more than one CPU. This will cause TCP retransmits if the packet data were to be split across different CPUs and re-assembled in a different order than expected.
> >    >
> >    > To eliminate the TCP retransmits, set smp_affinity on the particular interrupt to a single CPU. You can locate the interrupt (IRQ) used on the N110/N210 by using ifconfig:
> >    >
> >    >
> >    >
> >    > ```text
> >    > ifconfig <dev_name> | grep Interrupt
> >    > ```
> >    >
> >    > Set the smp_affinity to a single CPU:
> >    >
> >    >
> >    >
> >    > ```text
> >    > echo 1 > /proc/irq/<interrupt_number>/smp_affinity
> >    > ```
> >    >
> >    > It is highly suggested that you do not run the irqbalance daemon on your system, as this will change any smp_affinity setting you have applied. The irqbalance daemon runs on a 10 second interval and binds interrupts to the least loaded CPU determined by the daemon. To disable this daemon:
> >    >
> >    >
> >    >
> >    > ```text
> >    > chkconfig --level 2345 irqbalance off
> >    > ```
> >    >
> >    > By default, some Linux distributions enable the kernel feature, irqbalance, which performs the same function as the daemon. To disable this feature, add the following line to your bootloader:
> >    >
> >    >
> >    >
> >    > ```text
> >    > noirqbalance
> >    >
> >    > Example using the Grub bootloader::
> >    >
> >    >     title Red Hat Enterprise Linux AS (2.4.21-27.ELsmp)
> >    >     root (hd0,0)
> >    >     kernel /vmlinuz-2.4.21-27.ELsmp ro root=/dev/hda3 noirqbalance
> >    >     initrd /initrd-2.4.21-27.ELsmp.img
> >    > ```
> >
> > 2. After running insmod, the driver is loaded and the incorrect network interface is brought up without running ifup.
> >
> >    > When using 2.4.x kernels, including RHEL kernels, the Linux kernel invokes a script named "hotplug". This script is primarily used to automatically bring up USB devices when they are plugged in, however, the script also attempts to automatically bring up a network interface after loading the kernel module. The hotplug script does this by scanning the ifcfg-eth\# config files in /etc/sysconfig/network-scripts, looking for HWADDR=&lt;mac_address&gt;.
> >    >
> >    > If the hotplug script does not find the HWADDRR within any of the ifcfg-eth\# files, it will bring up the device with the next available interface name. If this interface is already configured for a different network card, your new interface will have incorrect IP address and network settings.
> >    >
> >    > To solve this issue, you can add the HWADDR=&lt;mac_address&gt; key to the interface config file of your network controller.
> >    >
> >    > To disable this "hotplug" feature, you may add the driver (module name) to the "blacklist" file located in /etc/hotplug. It has been noted that this does not work for network devices because the net.agent script does not use the blacklist file. Simply remove, or rename, the net.agent script located in /etc/hotplug to disable this feature.
> >
> > 3. Transport Protocol (TP) hangs when running heavy multi-connection traffic on an AMD Opteron system with HyperTransport PCI-X Tunnel chipset.
> >
> >    > If your AMD Opteron system uses the AMD-8131 HyperTransport PCI-X Tunnel chipset, you may experience the "133-Mhz Mode Split Completion Data Corruption" bug identified by AMD while using a 133Mhz PCI-X card on the bus PCI-X bus.
> >    >
> >    > AMD states, "Under highly specific conditions, the AMD-8131 PCI-X Tunnel can provide stale data via split completion cycles to a PCI-X card that is operating at 133 Mhz", causing data corruption.
> >    >
> >    > AMD's provides three workarounds for this problem, however, Chelsio recommends the first option for best performance with this bug:
> >    >
> >    > > For 133Mhz secondary bus operation, limit the transaction length and the number of outstanding transactions, via BIOS configuration programming of the PCI-X card, to the following:
> >    > >
> >    > > > Data Length (bytes): 1k
> >    > > >
> >    > > > Total allowed outstanding transactions: 2
> >    >
> >    > Please refer to AMD 8131-HT/PCI-X Errata 26310 Rev 3.08 August 2004, section 56, "133-MHz Mode Split Completion Data Corruption" for more details with this bug and workarounds suggested by AMD.
> >    >
> >    > It may be possible to work outside AMD's recommended PCI-X settings, try increasing the Data Length to 2k bytes for increased performance. If you have issues with these settings, please revert to the "safe" settings and duplicate the problem before submitting a bug or asking for support.
> >    >
> >    > > [!NOTE]
> >    > >
> >    > > The default setting on most systems is 8 outstanding transactions and 2k bytes data length.
> >
> > 4. On multiprocessor systems, it has been noted that an application which is handling 10Gb networking can switch between CPUs causing degraded and/or unstable performance.
> >
> >    > If running on an SMP system and taking performance measurements, it is suggested you either run the latest netperf-2.4.0+ or use a binding tool such as Tim Hockin's procstate utilities (runon) &lt;[http://www.hockin.org/\~thockin/procstate/](<http://www.hockin.org/~thockin/procstate/>)&gt;.
> >    >
> >    > Binding netserver and netperf (or other applications) to particular CPUs will have a significant difference in performance measurements. You may need to experiment which CPU to bind the application to in order to achieve the best performance for your system.
> >    >
> >    > If you are developing an application designed for 10Gb networking, please keep in mind you may want to look at kernel functions sched_setaffinity &amp; sched_getaffinity to bind your application.
> >    >
> >    > If you are just running user-space applications such as ftp, telnet, etc., you may want to try the runon tool provided by Tim Hockin's procstate utility. You could also try binding the interface to a particular CPU: runon 0 ifup eth0

<a id="rst-support"></a>

## Support

> If you have problems with the software or hardware, please contact our customer support team via email at [support@chelsio.com](<mailto:support@chelsio.com>) or check our website at [http://www.chelsio.com](<http://www.chelsio.com>)

---



```text
Chelsio Communications
370 San Aleso Ave.
Suite 100
Sunnyvale, CA 94085
http://www.chelsio.com
```

This program 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.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

THIS SOFTWARE IS PROVIDED `AS IS` AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

Copyright © 2003-2005 Chelsio Communications. All rights reserved.

---

# Cirrus Logic LAN CS8900/CS8920 Ethernet Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / cirrus_

> Cirrus make a copy of this driver available at their website, as described below. In general, you should use the driver version which comes with your Linux distribution.

<a id="rst-cirrus-logic-lan-cs8900-cs8920-ethernet-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> This document was contributed by Cirrus Logic for kernel 2.2.5.  This version has been updated for 2.3.48 by Andrew Morton.
>
> Still, this is too outdated\! A major cleanup is needed here.

Cirrus make a copy of this driver available at their website, as described below.  In general, you should use the driver version which comes with your Linux distribution.

Linux Network Interface Driver ver. 2.00 &lt;kernel 2.3.48&gt;

<!-- TABLE OF CONTENTS

1.0 CIRRUS LOGIC LAN CS8900/CS8920 ETHERNET ADAPTERS
     1.1 Product Overview
     1.2 Driver Description
         1.2.1 Driver Name
         1.2.2 File in the Driver Package
     1.3 System Requirements
     1.4 Licensing Information

2.0 ADAPTER INSTALLATION and CONFIGURATION
     2.1 CS8900-based Adapter Configuration
     2.2 CS8920-based Adapter Configuration

3.0 LOADING THE DRIVER AS A MODULE

4.0 COMPILING THE DRIVER
     4.1 Compiling the Driver as a Loadable Module
     4.2 Compiling the driver to support memory mode
     4.3 Compiling the driver to support Rx DMA

5.0 TESTING AND TROUBLESHOOTING
     5.1 Known Defects and Limitations
     5.2 Testing the Adapter
         5.2.1 Diagnostic Self-Test
         5.2.2 Diagnostic Network Test
     5.3 Using the Adapter's LEDs
     5.4 Resolving I/O Conflicts

6.0 TECHNICAL SUPPORT
     6.1 Contacting Cirrus Logic's Technical Support
     6.2 Information Required Before Contacting Technical Support
     6.3 Obtaining the Latest Driver Version
     6.4 Current maintainer
     6.5 Kernel boot parameters -->

<a id="rst-cirrus-logic-lan-cs8900-cs8920-ethernet-adapters-1"></a>

## 1. Cirrus Logic LAN CS8900/CS8920 Ethernet Adapters

<a id="rst-product-overview"></a>

## 1.1. Product Overview

The CS8900-based ISA Ethernet Adapters from Cirrus Logic follow IEEE 802.3 standards and support half or full-duplex operation in ISA bus computers on 10 Mbps Ethernet networks.  The adapters are designed for operation in 16-bit ISA or EISA bus expansion slots and are available in 10BaseT-only or 3-media configurations (10BaseT, 10Base2, and AUI for 10Base-5 or fiber networks).

CS8920-based adapters are similar to the CS8900-based adapter with additional features for Plug and Play (PnP) support and Wakeup Frame recognition.  As such, the configuration procedures differ somewhat between the two types of adapters.  Refer to the "Adapter Configuration" section for details on configuring both types of adapters.

<a id="rst-driver-description"></a>

## 1.2. Driver Description

The CS8900/CS8920 Ethernet Adapter driver for Linux supports the Linux v2.3.48 or greater kernel.  It can be compiled directly into the kernel or loaded at run-time as a device driver module.

1.2.1 Driver Name: cs89x0

1.2.2 Files in the Driver Archive:

The files in the driver at Cirrus' website include:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> readme.txt
>
> </td>
> <td>
>
>
> this file
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> build
>
> </td>
> <td>
>
>
> batch file to compile cs89x0.c.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cs89x0.c
>
> </td>
> <td>
>
>
> driver C code
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cs89x0.h
>
> </td>
> <td>
>
>
> driver header file
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> cs89x0.o
>
> </td>
> <td>
>
>
> pre-compiled module (for v2.2.5 kernel)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> config/Config.in
>
> </td>
> <td>
>
>
> sample file to include cs89x0 driver in the kernel.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> config/Makefile
>
> </td>
> <td>
>
>
> sample file to include cs89x0 driver in the kernel.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> config/Space.c
>
> </td>
> <td>
>
>
> sample file to include cs89x0 driver in the kernel.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-system-requirements"></a>

### 1.3. System Requirements

The following hardware is required:

> - Cirrus Logic LAN (CS8900/20-based) Ethernet ISA Adapter
>
> - IBM or IBM-compatible PC with: \* An 80386 or higher processor \* 16 bytes of contiguous IO space available between 210h - 370h \* One available IRQ (5,10,11,or 12 for the CS8900, 3-7,9-15 for CS8920).
>
> - Appropriate cable (and connector for AUI, 10BASE-2) for your network topology.

The following software is required:

- LINUX kernel version 2.3.48 or higher

  > - CS8900/20 Setup Utility (DOS-based)
  >
  > - LINUX kernel sources for your kernel (if compiling into kernel)
  >
  > - GNU Toolkit (gcc and make) v2.6 or above (if compiling into kernel or a module)

<a id="rst-licensing-information"></a>

### 1.4. Licensing Information

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, version 1.

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.

For a full copy of the GNU General Public License, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

<a id="rst-adapter-installation-and-configuration"></a>

## 2. Adapter Installation and Configuration

Both the CS8900 and CS8920-based adapters can be configured using parameters stored in an on-board EEPROM. You must use the DOS-based CS8900/20 Setup Utility if you want to change the adapter's configuration in EEPROM.

When loading the driver as a module, you can specify many of the adapter's configuration parameters on the command-line to override the EEPROM's settings or for interface configuration when an EEPROM is not used. (CS8920-based adapters must use an EEPROM.) See Section 3.0 LOADING THE DRIVER AS A MODULE.

Since the CS8900/20 Setup Utility is a DOS-based application, you must install and configure the adapter in a DOS-based system using the CS8900/20 Setup Utility before installation in the target LINUX system.  (Not required if installing a CS8900-based adapter and the default configuration is acceptable.)

<a id="rst-cs8900-based-adapter-configuration"></a>

### 2.1. CS8900-based Adapter Configuration

CS8900-based adapters shipped from Cirrus Logic have been configured with the following "default" settings:



```text
Operation Mode:      Memory Mode
IRQ:                 10
Base I/O Address:    300
Memory Base Address: D0000
Optimization:        DOS Client
Transmission Mode:   Half-duplex
BootProm:            None
Media Type:          Autodetect (3-media cards) or
                     10BASE-T (10BASE-T only adapter)
```

You should only change the default configuration settings if conflicts with another adapter exists. To change the adapter's configuration, run the CS8900/20 Setup Utility.

<a id="rst-cs8920-based-adapter-configuration"></a>

### 2.2. CS8920-based Adapter Configuration

CS8920-based adapters are shipped from Cirrus Logic configured as Plug and Play (PnP) enabled.  However, since the cs89x0 driver does NOT support PnP, you must install the CS8920 adapter in a DOS-based PC and run the CS8900/20 Setup Utility to disable PnP and configure the adapter before installation in the target Linux system.  Failure to do this will leave the adapter inactive and the driver will be unable to communicate with the adapter.



```text
****************************************************************
*                    CS8920-BASED ADAPTERS:                    *
*                                                              *
* CS8920-BASED ADAPTERS ARE PLUG and PLAY ENABLED BY DEFAULT.  *
* THE CS89X0 DRIVER DOES NOT SUPPORT PnP. THEREFORE, YOU MUST  *
* RUN THE CS8900/20 SETUP UTILITY TO DISABLE PnP SUPPORT AND   *
* TO ACTIVATE THE ADAPTER.                                     *
****************************************************************
```

<a id="rst-loading-the-driver-as-a-module"></a>

## 3. Loading the Driver as a Module

If the driver is compiled as a loadable module, you can load the driver module with the 'modprobe' command.  Many of the adapter's configuration parameters can be specified as command-line arguments to the load command.  This facility provides a means to override the EEPROM's settings or for interface configuration when an EEPROM is not used.

Example:



```text
insmod cs89x0.o io=0x200 irq=0xA media=aui
```

This example loads the module and configures the adapter to use an IO port base address of 200h, interrupt 10, and use the AUI media connection.  The following configuration options are available on the command line:



```text
io=###               - specify IO address (200h-360h)
irq=##               - specify interrupt level
use_dma=1            - Enable DMA
dma=#                - specify dma channel (Driver is compiled to support
                       Rx DMA only)
dmasize=# (16 or 64) - DMA size 16K or 64K.  Default value is set to 16.
media=rj45           - specify media type
 or media=bnc
 or media=aui
 or media=auto
duplex=full          - specify forced half/full/autonegotiate duplex
 or duplex=half
 or duplex=auto
debug=#              - debug level (only available if the driver was compiled
                       for debugging)
```

**Notes:**

- **a)** If an EEPROM is present, any specified command-line parameter will override the corresponding configuration value stored in EEPROM.

- **b)** The "io" parameter must be specified on the command-line.

- **c)** The driver's hardware probe routine is designed to avoid writing to I/O space until it knows that there is a cs89x0 card at the written addresses.  This could cause problems with device probing.  To avoid this behaviour, add one to the `io=` module parameter.  This doesn't actually change the I/O address, but it is a flag to tell the driver to partially initialise the hardware before trying to identify the card.  This could be dangerous if you are not sure that there is a cs89x0 card at the provided address.

  For example, to scan for an adapter located at IO base 0x300, specify an IO address of 0x301.

- **d)** The "duplex=auto" parameter is only supported for the CS8920.

- **e)** The minimum command-line configuration required if an EEPROM is not present is:

  io irq media type (no autodetect)

- **f)** The following additional parameters are CS89XX defaults (values used with no EEPROM or command-line argument).

  - DMA Burst = enabled

  - IOCHRDY Enabled = enabled

  - UseSA = enabled

  - CS8900 defaults to half-duplex if not specified on command-line

  - CS8920 defaults to autoneg if not specified on command-line

  - Use reset defaults for other config parameters

  - dma_mode = 0

- **g)** You can use ifconfig to set the adapter's Ethernet address.

- **h)** Many Linux distributions use the 'modprobe' command to load modules.  This program uses the '/etc/conf.modules' file to determine configuration information which is passed to a driver module when it is loaded.  All the configuration options which are described above may be placed within /etc/conf.modules.

  For example:



  ```text
  > cat /etc/conf.modules
  ...
  alias eth0 cs89x0
  options cs89x0 io=0x0200 dma=5 use_dma=1
  ...
  ```

  In this example we are telling the module system that the ethernet driver for this machine should use the cs89x0 driver.  We are asking 'modprobe' to pass the 'io', 'dma' and 'use_dma' arguments to the driver when it is loaded.

- **i)** Cirrus recommend that the cs89x0 use the ISA DMA channels 5, 6 or 7.  You will probably find that other DMA channels will not work.

- **j)** The cs89x0 supports DMA for receiving only.  DMA mode is significantly more efficient.  Flooding a 400 MHz Celeron machine with large ping packets consumes 82% of its CPU capacity in non-DMA mode.  With DMA this is reduced to 45%.

- **k)** If your Linux kernel was compiled with inbuilt plug-and-play support you will be able to find information about the cs89x0 card with the command:



  ```text
  cat /proc/isapnp
  ```

- **l)** If during DMA operation you find erratic behavior or network data corruption you should use your PC's BIOS to slow the EISA bus clock.

- **m)** If the cs89x0 driver is compiled directly into the kernel (non-modular) then its I/O address is automatically determined by ISA bus probing.  The IRQ number, media options, etc are determined from the card's EEPROM.

- **n)** If the cs89x0 driver is compiled directly into the kernel, DMA mode may be selected by providing the kernel with a boot option 'cs89x0_dma=N' where 'N' is the desired DMA channel number (5, 6 or 7).

  Kernel boot options may be provided on the LILO command line:



  ```text
  LILO boot: linux cs89x0_dma=5
  ```

  or they may be placed in /etc/lilo.conf:



  ```text
  image=/boot/bzImage-2.3.48
    append="cs89x0_dma=5"
    label=linux
    root=/dev/hda5
    read-only
  ```

  The DMA Rx buffer size is hardwired to 16 kbytes in this mode. (64k mode is not available).

<a id="rst-compiling-the-driver"></a>

## 4. Compiling the Driver

The cs89x0 driver can be compiled directly into the kernel or compiled into a loadable device driver module.

Just use the standard way to configure the driver and compile the Kernel.

<a id="rst-compiling-the-driver-to-support-rx-dma"></a>

### 4.1. Compiling the Driver to Support Rx DMA

The compile-time optionality for DMA was removed in the 2.3 kernel series.  DMA support is now unconditionally part of the driver.  It is enabled by the 'use_dma=1' module option.

<a id="rst-testing-and-troubleshooting"></a>

## 5. Testing and Troubleshooting

<a id="rst-known-defects-and-limitations"></a>

### 5.1. Known Defects and Limitations

Refer to the RELEASE.TXT file distributed as part of this archive for a list of known defects, driver limitations, and work arounds.

<a id="rst-testing-the-adapter"></a>

### 5.2. Testing the Adapter

Once the adapter has been installed and configured, the diagnostic option of the CS8900/20 Setup Utility can be used to test the functionality of the adapter and its network connection.  Use the diagnostics 'Self Test' option to test the functionality of the adapter with the hardware configuration you have assigned. You can use the diagnostics 'Network Test' to test the ability of the adapter to communicate across the Ethernet with another PC equipped with a CS8900/20-based adapter card (it must also be running the CS8900/20 Setup Utility).

> [!NOTE]
>
> The Setup Utility's diagnostics are designed to run in a DOS-only operating system environment.  DO NOT run the diagnostics from a DOS or command prompt session under Windows 95, Windows NT, OS/2, or other operating system.

To run the diagnostics tests on the CS8900/20 adapter:

> 1. Boot DOS on the PC and start the CS8900/20 Setup Utility.
>
> 2. The adapter's current configuration is displayed.  Hit the ENTER key to get to the main menu.
>
> 4. Select 'Diagnostics' (ALT-G) from the main menu. \* Select 'Self-Test' to test the adapter's basic functionality. \* Select 'Network Test' to test the network connection and cabling.

<a id="rst-diagnostic-self-test"></a>

#### 5.2.1. Diagnostic Self-test

The diagnostic self-test checks the adapter's basic functionality as well as its ability to communicate across the ISA bus based on the system resources assigned during hardware configuration.  The following tests are performed:

> - IO Register Read/Write Test
>
>   The IO Register Read/Write test insures that the CS8900/20 can be accessed in IO mode, and that the IO base address is correct.
>
> - Shared Memory Test
>
>   The Shared Memory test insures the CS8900/20 can be accessed in memory mode and that the range of memory addresses assigned does not conflict with other devices in the system.
>
> - Interrupt Test
>
>   The Interrupt test insures there are no conflicts with the assigned IRQ signal.
>
> - EEPROM Test
>
>   The EEPROM test insures the EEPROM can be read.
>
> - Chip RAM Test
>
>   The Chip RAM test insures the 4K of memory internal to the CS8900/20 is working properly.
>
> - Internal Loop-back Test
>
>   The Internal Loop Back test insures the adapter's transmitter and receiver are operating properly.  If this test fails, make sure the adapter's cable is connected to the network (check for LED activity for example).
>
> - Boot PROM Test
>
>   The Boot PROM  test insures the Boot PROM is present, and can be read. Failure indicates the Boot PROM  was not successfully read due to a hardware problem or due to a conflicts on the Boot PROM address assignment. (Test only applies if the adapter is configured to use the Boot PROM option.)

Failure of a test item indicates a possible system resource conflict with another device on the ISA bus.  In this case, you should use the Manual Setup option to reconfigure the adapter by selecting a different value for the system resource that failed.

<a id="rst-diagnostic-network-test"></a>

#### 5.2.2. Diagnostic Network Test

The Diagnostic Network Test verifies a working network connection by transferring data between two CS8900/20 adapters installed in different PCs on the same network. (Note: the diagnostic network test should not be run between two nodes across a router.)

This test requires that each of the two PCs have a CS8900/20-based adapter installed and have the CS8900/20 Setup Utility running.  The first PC is configured as a Responder and the other PC is configured as an Initiator. Once the Initiator is started, it sends data frames to the Responder which returns the frames to the Initiator.

The total number of frames received and transmitted are displayed on the Initiator's display, along with a count of the number of frames received and transmitted OK or in error.  The test can be terminated anytime by the user at either PC.

To setup the Diagnostic Network Test:

> 1. Select a PC with a CS8900/20-based adapter and a known working network connection to act as the Responder.  Run the CS8900/20 Setup Utility and select 'Diagnostics -&gt; Network Test -&gt; Responder' from the main menu.  Hit ENTER to start the Responder.
>
> 2. Return to the PC with the CS8900/20-based adapter you want to test and start the CS8900/20 Setup Utility.
>
> 3. From the main menu, Select 'Diagnostic -&gt; Network Test -&gt; Initiator'. Hit ENTER to start the test.

You may stop the test on the Initiator at any time while allowing the Responder to continue running.  In this manner, you can move to additional PCs and test them by starting the Initiator on another PC without having to stop/start the Responder.

<a id="rst-using-the-adapter-s-leds"></a>

### 5.3. Using the Adapter's LEDs

The 2 and 3-media adapters have two LEDs visible on the back end of the board located near the 10Base-T connector.

Link Integrity LED: A "steady" ON of the green LED indicates a valid 10Base-T connection.  (Only applies to 10Base-T.  The green LED has no significance for a 10Base-2 or AUI connection.)

TX/RX LED: The yellow LED lights briefly each time the adapter transmits or receives data. (The yellow LED will appear to "flicker" on a typical network.)

<a id="rst-resolving-i-o-conflicts"></a>

### 5.4. Resolving I/O Conflicts

An IO conflict occurs when two or more adapter use the same ISA resource (IO address, memory address or IRQ).  You can usually detect an IO conflict in one of four ways after installing and or configuring the CS8900/20-based adapter:

> 1. The system does not boot properly (or at all).
>
> 2. The driver cannot communicate with the adapter, reporting an "Adapter not found" error message.
>
> 3. You cannot connect to the network or the driver will not load.
>
> 4. If you have configured the adapter to run in memory mode but the driver reports it is using IO mode when loading, this is an indication of a memory address conflict.

If an IO conflict occurs, run the CS8900/20 Setup Utility and perform a diagnostic self-test.  Normally, the ISA resource in conflict will fail the self-test.  If so, reconfigure the adapter selecting another choice for the resource in conflict.  Run the diagnostics again to check for further IO conflicts.

In some cases, such as when the PC will not boot, it may be necessary to remove the adapter and reconfigure it by installing it in another PC to run the CS8900/20 Setup Utility.  Once reinstalled in the target system, run the diagnostics self-test to ensure the new configuration is free of conflicts before loading the driver again.

When manually configuring the adapter, keep in mind the typical ISA system resource usage as indicated in the tables below.



```text
I/O Address           Device                        IRQ      Device
-----------           --------                      ---      --------
   200-20F            Game I/O adapter               3       COM2, Bus Mouse
   230-23F            Bus Mouse                      4       COM1
   270-27F            LPT3: third parallel port      5       LPT2
   2F0-2FF            COM2: second serial port       6       Floppy Disk controller
   320-32F            Fixed disk controller          7       LPT1
                                                       8       Real-time Clock
                                                   9       EGA/VGA display adapter
                                                  12       Mouse (PS/2)
Memory Address  Device                          13       Math Coprocessor
--------------  ---------------------           14       Hard Disk controller
A000-BFFF     EGA Graphics Adapter
A000-C7FF     VGA Graphics Adapter
B000-BFFF     Mono Graphics Adapter
B800-BFFF     Color Graphics Adapter
E000-FFFF     AT BIOS
```

<a id="rst-technical-support"></a>

## 6. Technical Support

<a id="rst-contacting-cirrus-logic-s-technical-support"></a>

### 6.1. Contacting Cirrus Logic's Technical Support

Cirrus Logic's CS89XX Technical Application Support can be reached at:



```text
Telephone  :(800) 888-5016 (from inside U.S. and Canada)
           :(512) 442-7555 (from outside the U.S. and Canada)
Fax        :(512) 912-3871
Email      :ethernet@crystal.cirrus.com
WWW        :http://www.cirrus.com
```

<a id="rst-information-required-before-contacting-technical-support"></a>

### 6.2. Information Required before Contacting Technical Support

Before contacting Cirrus Logic for technical support, be prepared to provide as Much of the following information as possible.

1.) Adapter type (CRD8900, CDB8900, CDB8920, etc.)

2.) Adapter configuration

> - IO Base, Memory Base, IO or memory mode enabled, IRQ, DMA channel
>
> - Plug and Play enabled/disabled (CS8920-based adapters only)
>
> - Configured for media auto-detect or specific media type (which type).

3.) PC System's Configuration

> - Plug and Play system (yes/no)
>
> - BIOS (make and version)
>
> - System make and model
>
> - CPU (type and speed)
>
> - System RAM
>
> - SCSI Adapter

4.) Software

> - CS89XX driver and version
>
> - Your network operating system and version
>
> - Your system's OS version
>
> - Version of all protocol support files

5.) Any Error Message displayed.

<a id="rst-obtaining-the-latest-driver-version"></a>

### 6.3 Obtaining the Latest Driver Version

You can obtain the latest CS89XX drivers and support software from Cirrus Logic's Web site.  You can also contact Cirrus Logic's Technical Support (email: [ethernet@crystal.cirrus.com](<mailto:ethernet@crystal.cirrus.com>)) and request that you be registered for automatic software-update notification.

Cirrus Logic maintains a web page at [http://www.cirrus.com](<http://www.cirrus.com>) with the latest drivers and technical publications.

<a id="rst-current-maintainer"></a>

### 6.4. Current maintainer

In February 2000 the maintenance of this driver was assumed by Andrew Morton.

<a id="rst-kernel-module-parameters"></a>

### 6.5 Kernel module parameters

For use in embedded environments with no cs89x0 EEPROM, the kernel boot parameter `cs89x0_media=` has been implemented.  Usage is:



```text
cs89x0_media=rj45    or
cs89x0_media=aui     or
cs89x0_media=bnc
```

---

# DM9000 Network driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / davicom_

> Copyright 2008 Simtec Electronics,

<a id="rst-dm9000-network-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Copyright 2008 Simtec Electronics,

> Ben Dooks &lt;[ben@simtec.co.uk](<mailto:ben@simtec.co.uk>)&gt; &lt;[ben-linux@fluff.org](<mailto:ben-linux@fluff.org>)&gt;

<a id="rst-introduction"></a>

## Introduction

This file describes how to use the DM9000 platform-device based network driver that is contained in the files drivers/net/dm9000.c and drivers/net/dm9000.h.

The driver supports three DM9000 variants, the DM9000E which is the first chip supported as well as the newer DM9000A and DM9000B devices. It is currently maintained and tested by Ben Dooks, who should be CC: to any patches for this driver.

<a id="rst-defining-the-platform-device"></a>

## Defining the platform device

The minimum set of resources attached to the platform device are as follows:

> 1. The physical address of the address register
>
> 2. The physical address of the data register
>
> 3. The IRQ line the device's interrupt pin is connected to.

These resources should be specified in that order, as the ordering of the two address regions is important (the driver expects these to be address and then data).

An example from arch/arm/mach-s3c/mach-bast.c is:



```text
static struct resource bast_dm9k_resource[] = {
      [0] = {
              .start = S3C2410_CS5 + BAST_PA_DM9000,
              .end   = S3C2410_CS5 + BAST_PA_DM9000 + 3,
              .flags = IORESOURCE_MEM,
      },
      [1] = {
              .start = S3C2410_CS5 + BAST_PA_DM9000 + 0x40,
              .end   = S3C2410_CS5 + BAST_PA_DM9000 + 0x40 + 0x3f,
              .flags = IORESOURCE_MEM,
      },
      [2] = {
              .start = IRQ_DM9000,
              .end   = IRQ_DM9000,
              .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
      }
};

static struct platform_device bast_device_dm9k = {
      .name           = "dm9000",
      .id             = 0,
      .num_resources  = ARRAY_SIZE(bast_dm9k_resource),
      .resource       = bast_dm9k_resource,
};
```

Note the setting of the IRQ trigger flag in bast_dm9k_resource\[2\].flags, as this will generate a warning if it is not present. The trigger from the flags field will be passed to request_irq() when registering the IRQ handler to ensure that the IRQ is setup correctly.

This shows a typical platform device, without the optional configuration platform data supplied. The next example uses the same resources, but adds the optional platform data to pass extra configuration data:



```text
static struct dm9000_plat_data bast_dm9k_platdata = {
      .flags          = DM9000_PLATF_16BITONLY,
};

static struct platform_device bast_device_dm9k = {
      .name           = "dm9000",
      .id             = 0,
      .num_resources  = ARRAY_SIZE(bast_dm9k_resource),
      .resource       = bast_dm9k_resource,
      .dev            = {
              .platform_data = &bast_dm9k_platdata,
      }
};
```

The platform data is defined in include/linux/dm9000.h and described below.

<a id="rst-platform-data"></a>

## Platform data

Extra platform data for the DM9000 can describe the IO bus width to the device, whether or not an external PHY is attached to the device and the availability of an external configuration EEPROM.

The flags for the platform data .flags field are as follows:

DM9000_PLATF_8BITONLY

> The IO should be done with 8bit operations.

DM9000_PLATF_16BITONLY

> The IO should be done with 16bit operations.

DM9000_PLATF_32BITONLY

> The IO should be done with 32bit operations.

DM9000_PLATF_EXT_PHY

> The chip is connected to an external PHY.

DM9000_PLATF_NO_EEPROM

> This can be used to signify that the board does not have an EEPROM, or that the EEPROM should be hidden from the user.

DM9000_PLATF_SIMPLE_PHY

> Switch to using the simpler PHY polling method which does not try and read the MII PHY state regularly. This is only available when using the internal PHY. See the section on link state polling for more information.
>
> The config symbol DM9000_FORCE_SIMPLE_PHY_POLL, Kconfig entry "Force simple NSR based PHY polling" allows this flag to be forced on at build time.

<a id="rst-phy-link-state-polling"></a>

## PHY Link state polling

The driver keeps track of the link state and informs the network core about link (carrier) availability. This is managed by several methods depending on the version of the chip and on which PHY is being used.

For the internal PHY, the original (and currently default) method is to read the MII state, either when the status changes if we have the necessary interrupt support in the chip or every two seconds via a periodic timer.

To reduce the overhead for the internal PHY, there is now the option of using the DM9000_FORCE_SIMPLE_PHY_POLL config, or DM9000_PLATF_SIMPLE_PHY platform data option to read the summary information without the expensive MII accesses. This method is faster, but does not print as much information.

When using an external PHY, the driver currently has to poll the MII link status as there is no method for getting an interrupt on link change.

<a id="rst-dm9000a-dm9000b"></a>

## DM9000A / DM9000B

These chips are functionally similar to the DM9000E and are supported easily by the same driver. The features are:

> 1. Interrupt on internal PHY state change. This means that the periodic polling of the PHY status may be disabled on these devices when using the internal PHY.
>
> 2. TCP/UDP checksum offloading, which the driver does not currently support.

<a id="rst-ethtool"></a>

## ethtool

The driver supports the ethtool interface for access to the driver state information, the PHY state and the EEPROM.

---

# Davicom DM9102(A)/DM9132/DM9801 fast ethernet driver for Linux

_Peios Kernel / Internals / Networking / device_drivers / ethernet / dec_

> Note: This driver doesn't have a maintainer.

<a id="rst-davicom-dm9102-a-dm9132-dm9801-fast-ethernet-driver-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Note: This driver doesn't have a maintainer.

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.

This driver provides kernel support for Davicom DM9102(A)/DM9132/DM9801 ethernet cards ( CNET 10/100 ethernet cards uses Davicom chipset too, so this driver supports CNET cards too ).If you didn't compile this driver as a module, it will automatically load itself on boot and print a line similar to:



```text
dmfe: Davicom DM9xxx net driver, version 1.36.4 (2002-01-17)
```

If you compiled this driver as a module, you have to load it on boot.You can load it with command:



```text
insmod dmfe
```

This way it will autodetect the device mode.This is the suggested way to load the module.Or you can pass a mode= setting to module while loading, like:



```text
insmod dmfe mode=0 # Force 10M Half Duplex
insmod dmfe mode=1 # Force 100M Half Duplex
insmod dmfe mode=4 # Force 10M Full Duplex
insmod dmfe mode=5 # Force 100M Full Duplex
```

Next you should configure your network interface with a command similar to:



```text
ifconfig eth0 172.22.3.18
              ^^^^^^^^^^^
             Your IP Address
```

Then you may have to modify the default routing table with command:



```text
route add default eth0
```

Now your ethernet card should be up and running.

TODO:

- Implement pci_driver::suspend() and pci_driver::resume() power management methods.

- Check on 64 bit boxes.

- Check and fix on big endian boxes.

- Test and make sure PCI latency is now correct for all cases.

Authors:

Sten Wang &lt;[sten_wang@davicom.com.tw](<mailto:sten_wang@davicom.com.tw>) &gt;   : Original Author

Contributors:

- Marcelo Tosatti &lt;[marcelo@conectiva.com.br](<mailto:marcelo@conectiva.com.br>)&gt;

- Alan Cox &lt;[alan@lxorguk.ukuu.org.uk](<mailto:alan@lxorguk.ukuu.org.uk>)&gt;

- Jeff Garzik &lt;[jgarzik@pobox.com](<mailto:jgarzik@pobox.com>)&gt;

- Vojtech Pavlik &lt;[vojtech@suse.cz](<mailto:vojtech@suse.cz>)&gt;

---

# D-Link DL2000-based Gigabit Ethernet Adapter Installation

_Peios Kernel / Internals / Networking / device_drivers / ethernet / dlink_

> May 23, 2002

<a id="rst-d-link-dl2000-based-gigabit-ethernet-adapter-installation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

May 23, 2002

<!-- Contents

- Compatibility List
- Quick Install
- Compiling the Driver
- Installing the Driver
- Option parameter
- Configuration Script Sample
- Troubleshooting -->

<a id="rst-compatibility-list"></a>

## Compatibility List

Adapter Support:

- D-Link DGE-550T Gigabit Ethernet Adapter.

- D-Link DGE-550SX Gigabit Ethernet Adapter.

- D-Link DL2000-based Gigabit Ethernet Adapter.

The driver support Linux kernel 2.4.7 later. We had tested it on the environments below.

> . Red Hat v6.2 (update kernel to 2.4.7) . Red Hat v7.0 (update kernel to 2.4.7) . Red Hat v7.1 (kernel 2.4.7) . Red Hat v7.2 (kernel 2.4.7-10)

<a id="rst-quick-install"></a>

## Quick Install

Install linux driver as following command:



```text
1. make all
2. insmod dl2k.ko
3. ifconfig eth0 up 10.xxx.xxx.xxx netmask 255.0.0.0
                    ^^^^^^^^^^^^^^^\            ^^^^^^^^\
                                    IP                   NETMASK
```

Now eth0 should active, you can test it by "ping" or get more information by "ifconfig". If tested ok, continue the next step.

4. ``cp dl2k.ko /lib/modules/`uname -r`/kernel/drivers/net``

5. Add the following line to /etc/modprobe.d/dl2k.conf:



   ```text
   alias eth0 dl2k
   ```

6. Run `depmod` to updated module indexes.

7. Run `netconfig` or `netconf` to create configuration script ifcfg-eth0 located at /etc/sysconfig/network-scripts or create it manually.

   \[see - Configuration Script Sample\]

8. Driver will automatically load and configure at next boot time.

<a id="rst-compiling-the-driver"></a>

## Compiling the Driver

In Linux, NIC drivers are most commonly configured as loadable modules. The approach of building a monolithic kernel has become obsolete. The driver can be compiled as part of a monolithic kernel, but is strongly discouraged. The remainder of this section assumes the driver is built as a loadable module. In the Linux environment, it is a good idea to rebuild the driver from the source instead of relying on a precompiled version. This approach provides better reliability since a precompiled driver might depend on libraries or kernel features that are not present in a given Linux installation.

The 3 files necessary to build Linux device driver are dl2k.c, dl2k.h and Makefile. To compile, the Linux installation must include the gcc compiler, the kernel source, and the kernel headers. The Linux driver supports Linux Kernels 2.4.7. Copy the files to a directory and enter the following command to compile and link the driver:

<a id="rst-cd-rom-drive"></a>

### CD-ROM drive



```text
[root@XXX /] mkdir cdrom
[root@XXX /] mount -r -t iso9660 -o conv=auto /dev/cdrom /cdrom
[root@XXX /] cd root
[root@XXX /root] mkdir dl2k
[root@XXX /root] cd dl2k
[root@XXX dl2k] cp /cdrom/linux/dl2k.tgz /root/dl2k
[root@XXX dl2k] tar xfvz dl2k.tgz
[root@XXX dl2k] make all
```

<a id="rst-floppy-disc-drive"></a>

### Floppy disc drive



```text
[root@XXX /] cd root
[root@XXX /root] mkdir dl2k
[root@XXX /root] cd dl2k
[root@XXX dl2k] mcopy a:/linux/dl2k.tgz /root/dl2k
[root@XXX dl2k] tar xfvz dl2k.tgz
[root@XXX dl2k] make all
```

<a id="rst-installing-the-driver"></a>

## Installing the Driver

<a id="rst-manual-installation"></a>

### Manual Installation

> Once the driver has been compiled, it must be loaded, enabled, and bound to a protocol stack in order to establish network connectivity. To load a module enter the command:
>
>
>
> ```text
> insmod dl2k.o
> ```
>
> or:
>
>
>
> ```text
> insmod dl2k.o <optional parameter>  ; add parameter
> ```

---

> example:
>
>
>
> ```text
>  insmod dl2k.o media=100mbps_hd
>
> or::
>
>  insmod dl2k.o media=3
>
> or::
>
>  insmod dl2k.o media=3,2     ; for 2 cards
> ```

---

> Please reference the list of the command line parameters supported by the Linux device driver below.
>
> The insmod command only loads the driver and gives it a name of the form eth0, eth1, etc. To bring the NIC into an operational state, it is necessary to issue the following command:
>
>
>
> ```text
> ifconfig eth0 up
> ```
>
> Finally, to bind the driver to the active protocol (e.g., TCP/IP with Linux), enter the following command:
>
>
>
> ```text
> ifup eth0
> ```
>
> Note that this is meaningful only if the system can find a configuration script that contains the necessary network information. A sample will be given in the next paragraph.
>
> The commands to unload a driver are as follows:
>
>
>
> ```text
> ifdown eth0
> ifconfig eth0 down
> rmmod dl2k.o
> ```
>
> The following are the commands to list the currently loaded modules and to see the current network configuration:
>
>
>
> ```text
> lsmod
> ifconfig
> ```

<a id="rst-automated-installation"></a>

### Automated Installation

> This section describes how to install the driver such that it is automatically loaded and configured at boot time. The following description is based on a Red Hat 6.0/7.0 distribution, but it can easily be ported to other distributions as well.

<a id="rst-red-hat-v6-x-v7-x"></a>

### Red Hat v6.x/v7.x

> 1. Copy dl2k.o to the network modules directory, typically /lib/modules/2.x.x-xx/net or /lib/modules/2.x.x/kernel/drivers/net.
>
> 2. Locate the boot module configuration file, most commonly in the /etc/modprobe.d/ directory. Add the following lines:
>
>
>
>    ```text
>    alias ethx dl2k
>    options dl2k <optional parameters>
>    ```
>
>    where ethx will be eth0 if the NIC is the only ethernet adapter, eth1 if one other ethernet adapter is installed, etc. Refer to the table in the previous section for the list of optional parameters.
>
> 3. Locate the network configuration scripts, normally the /etc/sysconfig/network-scripts directory, and create a configuration script named ifcfg-ethx that contains network information.
>
> 4. Note that for most Linux distributions, Red Hat included, a configuration utility with a graphical user interface is provided to perform steps 2 and 3 above.

<a id="rst-parameter-description"></a>

## Parameter Description

You can install this driver without any additional parameter. However, if you are going to have extensive functions then it is necessary to set extra parameter. Below is a list of the command line parameters supported by the Linux device driver.


<table>
<tbody>
<tr>
<td>


mtu=packet_size

</td>
<td>


Specifies the maximum packet size. default is 1500.

</td>
</tr>
<tr>
<td>


media=media_type

</td>
<td>


Specifies the media type the NIC operates at. autosense     Autosensing active media.


<table>
<tbody>
<tr>
<td>


10mbps_hd

</td>
<td>


10Mbps half duplex.

</td>
</tr>
<tr>
<td>


10mbps_fd

</td>
<td>


10Mbps full duplex.

</td>
</tr>
<tr>
<td>


100mbps_hd

</td>
<td>


100Mbps half duplex.

</td>
</tr>
<tr>
<td>


100mbps_fd

</td>
<td>


100Mbps full duplex.

</td>
</tr>
<tr>
<td>


1000mbps_fd

</td>
<td>


1000Mbps full duplex.

</td>
</tr>
<tr>
<td>


1000mbps_hd

</td>
<td>


1000Mbps half duplex.

</td>
</tr>
<tr>
<td>


0

</td>
<td>


Autosensing active media.

</td>
</tr>
<tr>
<td>


1

</td>
<td>


10Mbps half duplex.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


10Mbps full duplex.

</td>
</tr>
<tr>
<td>


3

</td>
<td>


100Mbps half duplex.

</td>
</tr>
<tr>
<td>


4

</td>
<td>


100Mbps full duplex.

</td>
</tr>
<tr>
<td>


5

</td>
<td>


1000Mbps half duplex.

</td>
</tr>
<tr>
<td>


6

</td>
<td>


1000Mbps full duplex.

</td>
</tr>
</tbody>
</table>

By default, the NIC operates at autosense. 1000mbps_fd and 1000mbps_hd types are only available for fiber adapter.

</td>
</tr>
<tr>
<td>


vlan=n

</td>
<td>


Specifies the VLAN ID. If vlan=0, the Virtual Local Area Network (VLAN) function is disable.

</td>
</tr>
<tr>
<td>


jumbo=\[0\|1\]

</td>
<td>


Specifies the jumbo frame support. If jumbo=1, the NIC accept jumbo frames. By default, this function is disabled. Jumbo frame usually improve the performance int gigabit. This feature need jumbo frame compatible remote.

</td>
</tr>
<tr>
<td>


rx_coalesce=m

</td>
<td>


Number of rx frame handled each interrupt.

</td>
</tr>
<tr>
<td>


rx_timeout=n

</td>
<td>


Rx DMA wait time for an interrupt. If set rx_coalesce &gt; 0, hardware only assert an interrupt for m frames. Hardware won't assert rx interrupt until m frames received or reach timeout of n \* 640 nano seconds. Set proper rx_coalesce and rx_timeout can reduce congestion collapse and overload which has been a bottleneck for high speed network.

For example, rx_coalesce=10 rx_timeout=800. that is, hardware assert only 1 interrupt for 10 frames received or timeout of 512 us.

</td>
</tr>
<tr>
<td>


tx_coalesce=n

</td>
<td>


Number of tx frame handled each interrupt. Set n &gt; 1 can reduce the interrupts congestion usually lower performance of high speed network card. Default is 16.

</td>
</tr>
<tr>
<td>


tx_flow=\[1\|0\]

</td>
<td>


Specifies the Tx flow control. If tx_flow=0, the Tx flow control disable else driver autodetect.

</td>
</tr>
<tr>
<td>


rx_flow=\[1\|0\]

</td>
<td>


Specifies the Rx flow control. If rx_flow=0, the Rx flow control enable else driver autodetect.

</td>
</tr>
</tbody>
</table>

<a id="rst-configuration-script-sample"></a>

## Configuration Script Sample

Here is a sample of a simple configuration script:



```text
DEVICE=eth0
USERCTL=no
ONBOOT=yes
POOTPROTO=none
BROADCAST=207.200.5.255
NETWORK=207.200.5.0
NETMASK=255.255.255.0
IPADDR=207.200.5.2
```

<a id="rst-troubleshooting"></a>

## Troubleshooting

Q1. Source files contain ^ M behind every line.

> Make sure all files are Unix file format (no LF). Try the following shell command to convert files:
>
>
>
> ```text
> cat dl2k.c | col -b > dl2k.tmp
> mv dl2k.tmp dl2k.c
> ```
>
> OR:
>
>
>
> ```text
> cat dl2k.c | tr -d "\r" > dl2k.tmp
> mv dl2k.tmp dl2k.c
> ```

Q2: Could not find header files (`*.h`)?

> To compile the driver, you need kernel header files. After installing the kernel source, the header files are usually located in /usr/src/linux/include, which is the default include directory configured in Makefile. For some distributions, there is a copy of header files in /usr/src/include/linux and /usr/src/include/asm, that you can change the INCLUDEDIR in Makefile to /usr/include without installing kernel source.
>
> Note that RH 7.0 didn't provide correct header files in /usr/include, including those files will make a wrong version driver.

---

# The QorIQ DPAA Ethernet Driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale_

> Authors: - Madalin Bucur <madalin.bucur@nxp.com> - Camelia Groza <camelia.groza@nxp.com>

<a id="rst-the-qoriq-dpaa-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Authors: - Madalin Bucur &lt;[madalin.bucur@nxp.com](<mailto:madalin.bucur@nxp.com>)&gt; - Camelia Groza &lt;[camelia.groza@nxp.com](<mailto:camelia.groza@nxp.com>)&gt;

<!-- Contents

- DPAA Ethernet Overview
- DPAA Ethernet Supported SoCs
- Configuring DPAA Ethernet in your kernel
- DPAA Ethernet Frame Processing
- DPAA Ethernet Features
- DPAA IRQ Affinity and Receive Side Scaling
- Debugging -->

<a id="rst-dpaa-ethernet-overview"></a>

## DPAA Ethernet Overview

DPAA stands for Data Path Acceleration Architecture and it is a set of networking acceleration IPs that are available on several generations of SoCs, both on PowerPC and ARM64.

The Freescale DPAA architecture consists of a series of hardware blocks that support Ethernet connectivity. The Ethernet driver depends upon the following drivers in the Linux kernel:

> - - **Peripheral Access Memory Unit (PAMU) (\* needed only for PPC platforms)**
>
>     drivers/iommu/fsl\_\*
>
> - - **Frame Manager (FMan)**
>
>     drivers/net/ethernet/freescale/fman
>
> - - **Queue Manager (QMan), Buffer Manager (BMan)**
>
>     drivers/soc/fsl/qbman

A simplified view of the dpaa_eth interfaces mapped to FMan MACs:



```text
dpaa_eth       /eth0\     ...       /ethN\
driver        |      |             |      |
-------------   ----   -----------   ----   -------------
     -Ports  / Tx  Rx \    ...    / Tx  Rx \
FMan        |          |         |          |
     -MACs  |   MAC0   |         |   MACN   |
           /   dtsec0   \  ...  /   dtsecN   \ (or tgec)
          /              \     /              \(or memac)
---------  --------------  ---  --------------  ---------
    FMan, FMan Port, FMan SP, FMan MURAM drivers
---------------------------------------------------------
    FMan HW blocks: MURAM, MACs, Ports, SP
---------------------------------------------------------
```

The dpaa_eth relation to the QMan, BMan and FMan:



```text
            ________________________________
dpaa_eth   /            eth0                \
driver    /                                  \
---------   -^-   -^-   -^-   ---    ---------
QMan driver / \   / \   / \  \   /  | BMan    |
           |Rx | |Rx | |Tx | |Tx |  | driver  |
---------  |Dfl| |Err| |Cnf| |FQs|  |         |
QMan HW    |FQ | |FQ | |FQs| |   |  |         |
           /   \ /   \ /   \  \ /   |         |
---------   ---   ---   ---   -v-    ---------
          |        FMan QMI         |         |
          | FMan HW       FMan BMI  | BMan HW |
            -----------------------   --------
```

where the acronyms used above (and in the code) are:


<table>
<tbody>
<tr>
<td>


DPAA

</td>
<td>


Data Path Acceleration Architecture

</td>
</tr>
<tr>
<td>


FMan

</td>
<td>


DPAA Frame Manager

</td>
</tr>
<tr>
<td>


QMan

</td>
<td>


DPAA Queue Manager

</td>
</tr>
<tr>
<td>


BMan

</td>
<td>


DPAA Buffers Manager

</td>
</tr>
<tr>
<td>


QMI

</td>
<td>


QMan interface in FMan

</td>
</tr>
<tr>
<td>


BMI

</td>
<td>


BMan interface in FMan

</td>
</tr>
<tr>
<td>


FMan SP

</td>
<td>


FMan Storage Profiles

</td>
</tr>
<tr>
<td>


MURAM

</td>
<td>


Multi-user RAM in FMan

</td>
</tr>
<tr>
<td>


FQ

</td>
<td>


QMan Frame Queue

</td>
</tr>
<tr>
<td>


Rx Dfl FQ

</td>
<td>


default reception FQ

</td>
</tr>
<tr>
<td>


Rx Err FQ

</td>
<td>


Rx error frames FQ

</td>
</tr>
<tr>
<td>


Tx Cnf FQ

</td>
<td>


Tx confirmation FQs

</td>
</tr>
<tr>
<td>


Tx FQs

</td>
<td>


transmission frame queues

</td>
</tr>
<tr>
<td>


dtsec

</td>
<td>


datapath three speed Ethernet controller (10/100/1000 Mbps)

</td>
</tr>
<tr>
<td>


tgec

</td>
<td>


ten gigabit Ethernet controller (10 Gbps)

</td>
</tr>
<tr>
<td>


memac

</td>
<td>


multirate Ethernet MAC (10/100/1000/10000)

</td>
</tr>
</tbody>
</table>

<a id="rst-dpaa-ethernet-supported-socs"></a>

## DPAA Ethernet Supported SoCs

The DPAA drivers enable the Ethernet controllers present on the following SoCs:

PPC - P1023 - P2041 - P3041 - P4080 - P5020 - P5040 - T1023 - T1024 - T1040 - T1042 - T2080 - T4240 - B4860

ARM - LS1043A - LS1046A

<a id="rst-configuring-dpaa-ethernet-in-your-kernel"></a>

## Configuring DPAA Ethernet in your kernel

To enable the DPAA Ethernet driver, the following Kconfig options are required:



```text
# common for arch/arm64 and arch/powerpc platforms
CONFIG_FSL_DPAA=y
CONFIG_FSL_FMAN=y
CONFIG_FSL_DPAA_ETH=y
CONFIG_FSL_XGMAC_MDIO=y

# for arch/powerpc only
CONFIG_FSL_PAMU=y

# common options needed for the PHYs used on the RDBs
CONFIG_VITESSE_PHY=y
CONFIG_REALTEK_PHY=y
CONFIG_AQUANTIA_PHY=y
```

<a id="rst-dpaa-ethernet-frame-processing"></a>

## DPAA Ethernet Frame Processing

On Rx, buffers for the incoming frames are retrieved from the buffers found in the dedicated interface buffer pool. The driver initializes and seeds these with one page buffers.

On Tx, all transmitted frames are returned to the driver through Tx confirmation frame queues. The driver is then responsible for freeing the buffers. In order to do this properly, a backpointer is added to the buffer before transmission that points to the skb. When the buffer returns to the driver on a confirmation FQ, the skb can be correctly consumed.

<a id="rst-dpaa-ethernet-features"></a>

## DPAA Ethernet Features

Currently the DPAA Ethernet driver enables the basic features required for a Linux Ethernet driver. The support for advanced features will be added gradually.

The driver has Rx and Tx checksum offloading for UDP and TCP. Currently the Rx checksum offload feature is enabled by default and cannot be controlled through ethtool. Also, rx-flow-hash and rx-hashing was added. The addition of RSS provides a big performance boost for the forwarding scenarios, allowing different traffic flows received by one interface to be processed by different CPUs in parallel.

The driver has support for multiple prioritized Tx traffic classes. Priorities range from 0 (lowest) to 3 (highest). These are mapped to HW workqueues with strict priority levels. Each traffic class contains NR_CPU TX queues. By default, only one traffic class is enabled and the lowest priority Tx queues are used. Higher priority traffic classes can be enabled with the mqprio qdisc. For example, all four traffic classes are enabled on an interface with the following command. Furthermore, skb priority levels are mapped to traffic classes as follows:

> - priorities 0 to 3 - traffic class 0 (low priority)
>
> - priorities 4 to 7 - traffic class 1 (medium-low priority)
>
> - priorities 8 to 11 - traffic class 2 (medium-high priority)
>
> - priorities 12 to 15 - traffic class 3 (high priority)



```text
tc qdisc add dev <int> root handle 1: \
       mqprio num_tc 4 map 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 hw 1
```

<a id="rst-dpaa-irq-affinity-and-receive-side-scaling"></a>

## DPAA IRQ Affinity and Receive Side Scaling

Traffic coming on the DPAA Rx queues or on the DPAA Tx confirmation queues is seen by the CPU as ingress traffic on a certain portal. The DPAA QMan portal interrupts are affined each to a certain CPU. The same portal interrupt services all the QMan portal consumers.

By default the DPAA Ethernet driver enables RSS, making use of the DPAA FMan Parser and Keygen blocks to distribute traffic on 128 hardware frame queues using a hash on IP v4/v6 source and destination and L4 source and destination ports, in present in the received frame. When RSS is disabled, all traffic received by a certain interface is received on the default Rx frame queue. The default DPAA Rx frame queues are configured to put the received traffic into a pool channel that allows any available CPU portal to dequeue the ingress traffic. The default frame queues have the HOLDACTIVE option set, ensuring that traffic bursts from a certain queue are serviced by the same CPU. This ensures a very low rate of frame reordering. A drawback of this is that only one CPU at a time can service the traffic received by a certain interface when RSS is not enabled.

To implement RSS, the DPAA Ethernet driver allocates an extra set of 128 Rx frame queues that are configured to dedicated channels, in a round-robin manner. The mapping of the frame queues to CPUs is now hardcoded, there is no indirection table to move traffic for a certain FQ (hash result) to another CPU. The ingress traffic arriving on one of these frame queues will arrive at the same portal and will always be processed by the same CPU. This ensures intra-flow order preservation and workload distribution for multiple traffic flows.

RSS can be turned off for a certain interface using ethtool, i.e.:



```text
# ethtool -N fm1-mac9 rx-flow-hash tcp4 ""
```

To turn it back on, one needs to set rx-flow-hash for tcp4/6 or udp4/6:



```text
# ethtool -N fm1-mac9 rx-flow-hash udp4 sfdn
```

There is no independent control for individual protocols, any command run for one of tcp4\|udp4\|ah4\|esp4\|sctp4\|tcp6\|udp6\|ah6\|esp6\|sctp6 is going to control the rx-flow-hashing for all protocols on that interface.

Besides using the FMan Keygen computed hash for spreading traffic on the 128 Rx FQs, the DPAA Ethernet driver also sets the skb hash value when the NETIF_F_RXHASH feature is on (active by default). This can be turned on or off through ethtool, i.e.:



```text
# ethtool -K fm1-mac9 rx-hashing off
# ethtool -k fm1-mac9 | grep hash
receive-hashing: off
# ethtool -K fm1-mac9 rx-hashing on
Actual changes:
receive-hashing: on
# ethtool -k fm1-mac9 | grep hash
receive-hashing: on
```

Please note that Rx hashing depends upon the rx-flow-hashing being on for that interface - turning off rx-flow-hashing will also disable the rx-hashing (without ethtool reporting it as off as that depends on the NETIF_F_RXHASH feature flag).

<a id="rst-debugging"></a>

## Debugging

The following statistics are exported for each interface through ethtool:

> - interrupt count per CPU
>
> - Rx packets count per CPU
>
> - Tx packets count per CPU
>
> - Tx confirmed packets count per CPU
>
> - Tx S/G frames count per CPU
>
> - Tx error count per CPU
>
> - Rx error count per CPU
>
> - Rx error count per type
>
> - congestion related statistics:
>
>   > - congestion status
>   >
>   > - time spent in congestion
>   >
>   > - number of time the device entered congestion
>   >
>   > - dropped packets count per cause

The driver also exports the following information in sysfs:

> - the FQ IDs for each FQ type /sys/devices/platform/soc/&lt;addr&gt;.fman/&lt;addr&gt;.ethernet/dpaa-ethernet.&lt;id&gt;/net/fm&lt;nr&gt;-mac&lt;nr&gt;/fqids
>
> - the ID of the buffer pool in use /sys/devices/platform/soc/&lt;addr&gt;.fman/&lt;addr&gt;.ethernet/dpaa-ethernet.&lt;id&gt;/net/fm&lt;nr&gt;-mac&lt;nr&gt;/bpids

---

# The Gianfar Ethernet Driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale_

> The eTSEC controller (first included in parts from late 2005 like the 8548) has the ability to perform TCP, UDP, and IP checksums in hardware. The Linux kernel only offloads the TCP and UDP checksums (and always performs the pseudo header…

<a id="rst-the-gianfar-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Andy Fleming &lt;[afleming@freescale.com](<mailto:afleming@freescale.com>)&gt;

**Updated:** 2005-07-28

<a id="rst-checksum-offloading"></a>

## Checksum Offloading

The eTSEC controller (first included in parts from late 2005 like the 8548) has the ability to perform TCP, UDP, and IP checksums in hardware.  The Linux kernel only offloads the TCP and UDP checksums (and always performs the pseudo header checksums), so the driver only supports checksumming for TCP/IP and UDP/IP packets.  Use ethtool to enable or disable this feature for RX and TX.

<a id="rst-vlan"></a>

## VLAN

In order to use VLAN, please consult Linux documentation on configuring VLANs.  The gianfar driver supports hardware insertion and extraction of VLAN headers, but not filtering.  Filtering will be done by the kernel.

<a id="rst-multicasting"></a>

## Multicasting

The gianfar driver supports using the group hash table on the TSEC (and the extended hash table on the eTSEC) for multicast filtering.  On the eTSEC, the exact-match MAC registers are used before the hash tables.  See Linux documentation on how to join multicast groups.

<a id="rst-padding"></a>

## Padding

The gianfar driver supports padding received frames with 2 bytes to align the IP header to a 16-byte boundary, when supported by hardware.

<a id="rst-ethtool"></a>

## Ethtool

The gianfar driver supports the use of ethtool for many configuration options.  You must run ethtool only on currently open interfaces.  See ethtool documentation for details.

---

# DPAA2 Documentation

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> Reference for DPAA2 Documentation.

<a id="rst-dpaa2-documentation"></a>

- [DPAA2 (Data Path Acceleration Architecture Gen2) Overview](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/overview.md>)
- [DPAA2 DPIO (Data Path I/O) Overview](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/dpio-driver.md>)
- [DPAA2 Ethernet driver](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/ethernet-driver.md>)
- [DPAA2 MAC / PHY support](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/mac-phy-support.md>)
- [DPAA2 Switch driver](</kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/switch-driver.md>)

---

# DPAA2 DPIO (Data Path I/O) Overview

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> This document provides an overview of the Freescale DPAA2 DPIO drivers

<a id="rst-dpaa2-dpio-data-path-i-o-overview"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2016-2018 NXP

This document provides an overview of the Freescale DPAA2 DPIO drivers

<a id="rst-introduction"></a>

## Introduction

A DPAA2 DPIO (Data Path I/O) is a hardware object that provides interfaces to enqueue and dequeue frames to/from network interfaces and other accelerators.  A DPIO also provides hardware buffer pool management for network interfaces.

This document provides an overview the Linux DPIO driver, its subcomponents, and its APIs.

See [Documentation/networking/device_drivers/ethernet/freescale/dpaa2/overview.rst](/kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/overview.md) for a general overview of DPAA2 and the general DPAA2 driver architecture in Linux.

<a id="rst-driver-overview"></a>

### Driver Overview

The DPIO driver is bound to DPIO objects discovered on the fsl-mc bus and provides services that:

> - **A.** allow other drivers, such as the Ethernet driver, to enqueue and dequeue frames for their respective objects
>
> - **B.** allow drivers to register callbacks for data availability notifications when data becomes available on a queue or channel
>
> - **C.** allow drivers to manage hardware buffer pools

- **The Linux DPIO driver consists of 3 primary components--**

  DPIO object driver-- fsl-mc driver that manages the DPIO object

  DPIO service-- provides APIs to other Linux drivers for services

  QBman portal interface-- sends portal commands, gets responses:



  ```text
    fsl-mc          other
     bus           drivers
      |               |
  +---+----+   +------+-----+
  |DPIO obj|   |DPIO service|
  | driver |---|  (DPIO)    |
  +--------+   +------+-----+
                      |
               +------+-----+
               |    QBman   |
               | portal i/f |
               +------------+
                      |
                   hardware
  ```

The diagram below shows how the DPIO driver components fit with the other DPAA2 Linux driver components:



```text
                                                  +------------+
                                                  | OS Network |
                                                  |   Stack    |
                +------------+                    +------------+
                | Allocator  |. . . . . . .       |  Ethernet  |
                |(DPMCP,DPBP)|                    |   (DPNI)   |
                +-.----------+                    +---+---+----+
                 .          .                         ^   |
                .            .           <data avail, |   |<enqueue,
               .              .           tx confirm> |   | dequeue>
   +-------------+             .                      |   |
   | DPRC driver |              .    +--------+ +------------+
   |   (DPRC)    |               . . |DPIO obj| |DPIO service|
   +----------+--+                   | driver |-|  (DPIO)    |
              |                      +--------+ +------+-----+
              |<dev add/remove>                 +------|-----+
              |                                 |   QBman    |
         +----+--------------+                  | portal i/f |
         |   MC-bus driver   |                  +------------+
         |                   |                     |
         | /soc/fsl-mc       |                     |
         +-------------------+                     |
                                                   |
=========================================|=========|========================
                                       +-+--DPIO---|-----------+
                                       |           |           |
                                       |        QBman Portal   |
                                       +-----------------------+

============================================================================
```

<a id="rst-dpio-object-driver-dpio-driver-c"></a>

### DPIO Object Driver (dpio-driver.c)

> The dpio-driver component registers with the fsl-mc bus to handle objects of type "dpio".  The implementation of probe() handles basic initialization of the DPIO including mapping of the DPIO regions (the QBman SW portal) and initializing interrupts and registering irq handlers.  The dpio-driver registers the probed DPIO with dpio-service.

<a id="rst-dpio-service-dpio-service-c-dpaa2-io-h"></a>

### DPIO service  (dpio-service.c, dpaa2-io.h)

> The dpio service component provides queuing, notification, and buffers management services to DPAA2 drivers, such as the Ethernet driver.  A system will typically allocate 1 DPIO object per CPU to allow queuing operations to happen simultaneously across all CPUs.
>
> - **Notification handling**
>
>   dpaa2_io_service_register()
>
>   dpaa2_io_service_deregister()
>
>   dpaa2_io_service_rearm()
>
> - **Queuing**
>
>   dpaa2_io_service_pull_fq()
>
>   dpaa2_io_service_pull_channel()
>
>   dpaa2_io_service_enqueue_fq()
>
>   dpaa2_io_service_enqueue_qd()
>
>   dpaa2_io_store_create()
>
>   dpaa2_io_store_destroy()
>
>   dpaa2_io_store_next()
>
> - **Buffer pool management**
>
>   dpaa2_io_service_release()
>
>   dpaa2_io_service_acquire()

<a id="rst-qbman-portal-interface-qbman-portal-c"></a>

### QBman portal interface (qbman-portal.c)

> The qbman-portal component provides APIs to do the low level hardware bit twiddling for operations such as:
>
> > - initializing Qman software portals
> >
> > - building and sending portal commands
> >
> > - portal interrupt configuration and processing
>
> The qbman-portal APIs are not public to other drivers, and are only used by dpio-service.

<a id="rst-other-dpaa2-fd-h-dpaa2-global-h"></a>

### Other (dpaa2-fd.h, dpaa2-global.h)

> Frame descriptor and scatter-gather definitions and the APIs used to manipulate them are defined in dpaa2-fd.h.
>
> Dequeue result struct and parsing APIs are defined in dpaa2-global.h.

---

# DPAA2 Ethernet driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> This file provides documentation for the Freescale DPAA2 Ethernet driver.

<a id="rst-dpaa2-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2017-2018 NXP

This file provides documentation for the Freescale DPAA2 Ethernet driver.

<a id="rst-supported-platforms"></a>

## Supported Platforms

This driver provides networking support for Freescale DPAA2 SoCs, e.g. LS2080A, LS2088A, LS1088A.

<a id="rst-architecture-overview"></a>

## Architecture Overview

Unlike regular NICs, in the DPAA2 architecture there is no single hardware block representing network interfaces; instead, several separate hardware resources concur to provide the networking functionality:

- network interfaces

- queues, channels

- buffer pools

- MAC/PHY

All hardware resources are allocated and configured through the Management Complex (MC) portals. MC abstracts most of these resources as DPAA2 objects and exposes ABIs through which they can be configured and controlled. A few hardware resources, like queues, do not have a corresponding MC object and are treated as internal resources of other objects.

For a more detailed description of the DPAA2 architecture and its object abstractions see *[Documentation/networking/device_drivers/ethernet/freescale/dpaa2/overview.rst](/kernel/internals/networking/device-drivers-ethernet-freescale-dpaa2/overview.md)*.

Each Linux net device is built on top of a Datapath Network Interface (DPNI) object and uses Buffer Pools (DPBPs), I/O Portals (DPIOs) and Concentrators (DPCONs).

Configuration interface:



```text
             -----------------------
            | DPAA2 Ethernet Driver |
             -----------------------
                 .      .      .
                 .      .      .
         . . . . .      .      . . . . . .
         .              .                .
         .              .                .
     ----------     ----------      -----------
    | DPBP API |   | DPNI API |    | DPCON API |
     ----------     ----------      -----------
         .              .                .             software
=======  .  ==========  .  ============  .  ===================
         .              .                .             hardware
     ------------------------------------------
    |            MC hardware portals           |
     ------------------------------------------
         .              .                .
         .              .                .
      ------         ------            -------
     | DPBP |       | DPNI |          | DPCON |
      ------         ------            -------
```

The DPNIs are network interfaces without a direct one-on-one mapping to PHYs. DPBPs represent hardware buffer pools. Packet I/O is performed in the context of DPCON objects, using DPIO portals for managing and communicating with the hardware resources.

Datapath (I/O) interface:



```text
        -----------------------------------------------
       |           DPAA2 Ethernet Driver               |
        -----------------------------------------------
         |          ^        ^         |            |
         |          |        |         |            |
  enqueue|   dequeue|   data |  dequeue|       seed |
   (Tx)  | (Rx, TxC)|  avail.|  request|     buffers|
         |          |  notify|         |            |
         |          |        |         |            |
         V          |        |         V            V
        -----------------------------------------------
       |                 DPIO Driver                   |
        -----------------------------------------------
         |          |        |         |            |          software
         |          |        |         |            |  ================
         |          |        |         |            |          hardware
        -----------------------------------------------
       |               I/O hardware portals            |
        -----------------------------------------------
         |          ^        ^         |            |
         |          |        |         |            |
         |          |        |         V            |
         V          |    ================           V
       ----------------------           |      -------------
queues  ----------------------          |     | Buffer pool |
         ----------------------         |      -------------
                  =======================
                               Channel
```

Datapath I/O (DPIO) portals provide enqueue and dequeue services, data availability notifications and buffer pool management. DPIOs are shared between all DPAA2 objects (and implicitly all DPAA2 kernel drivers) that work with data frames, but must be affine to the CPUs for the purpose of traffic distribution.

Frames are transmitted and received through hardware frame queues, which can be grouped in channels for the purpose of hardware scheduling. The Ethernet driver enqueues TX frames on egress queues and after transmission is complete a TX confirmation frame is sent back to the CPU.

When frames are available on ingress queues, a data availability notification is sent to the CPU; notifications are raised per channel, so even if multiple queues in the same channel have available frames, only one notification is sent. After a channel fires a notification, is must be explicitly rearmed.

Each network interface can have multiple Rx, Tx and confirmation queues affined to CPUs, and one channel (DPCON) for each CPU that services at least one queue. DPCONs are used to distribute ingress traffic to different CPUs via the cores' affine DPIOs.

The role of hardware buffer pools is storage of ingress frame data. Each network interface has a privately owned buffer pool which it seeds with kernel allocated buffers.

DPNIs are decoupled from PHYs; a DPNI can be connected to a PHY through a DPMAC object or to another DPNI through an internal link, but the connection is managed by MC and completely transparent to the Ethernet driver.



```text
 ---------     ---------     ---------
| eth if1 |   | eth if2 |   | eth ifn |
 ---------     ---------     ---------
      .           .          .
      .           .          .
      .           .          .
     ---------------------------
    |   DPAA2 Ethernet Driver   |
     ---------------------------
      .           .          .
      .           .          .
      .           .          .
   ------      ------      ------            -------
  | DPNI |    | DPNI |    | DPNI |          | DPMAC |----+
   ------      ------      ------            -------     |
     |           |           |                  |        |
     |           |           |                  |      -----
      ===========             ==================      | PHY |
                                                       -----
```

<a id="rst-creating-a-network-interface"></a>

## Creating a Network Interface

A net device is created for each DPNI object probed on the MC bus. Each DPNI has a number of properties which determine the network interface configuration options and associated hardware resources.

DPNI objects (and the other DPAA2 objects needed for a network interface) can be added to a container on the MC bus in one of two ways: statically, through a Datapath Layout Binary file (DPL) that is parsed by MC at boot time; or created dynamically at runtime, via the DPAA2 objects APIs.

<a id="rst-features-offloads"></a>

## Features &amp; Offloads

Hardware checksum offloading is supported for TCP and UDP over IPv4/6 frames. The checksum offloads can be independently configured on RX and TX through ethtool.

Hardware offload of unicast and multicast MAC filtering is supported on the ingress path and permanently enabled.

Scatter-gather frames are supported on both RX and TX paths. On TX, SG support is configurable via ethtool; on RX it is always enabled.

The DPAA2 hardware can process jumbo Ethernet frames of up to 10K bytes.

The Ethernet driver defines a static flow hashing scheme that distributes traffic based on a 5-tuple key: src IP, dst IP, IP proto, L4 src port, L4 dst port. No user configuration is supported for now.

Hardware specific statistics for the network interface as well as some non-standard driver stats can be consulted through ethtool -S option.

---

# DPAA2 MAC / PHY support

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> The DPAA2 MAC / PHY support consists of a set of APIs that help DPAA2 network drivers (dpaa2-eth, dpaa2-ethsw) interact with the PHY library.

<a id="rst-dpaa2-mac-phy-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2019 NXP

<a id="rst-overview"></a>

## Overview

The DPAA2 MAC / PHY support consists of a set of APIs that help DPAA2 network drivers (dpaa2-eth, dpaa2-ethsw) interact with the PHY library.

<a id="rst-dpaa2-software-architecture"></a>

## DPAA2 Software Architecture

Among other DPAA2 objects, the fsl-mc bus exports DPNI objects (abstracting a network interface) and DPMAC objects (abstracting a MAC). The dpaa2-eth driver probes on the DPNI object and connects to and configures a DPMAC object with the help of phylink.

Data connections may be established between a DPNI and a DPMAC, or between two DPNIs. Depending on the connection type, the netif_carrier\_\[on/off\] is handled directly by the dpaa2-eth driver or by phylink.



```none
Sources of abstracted link state information presented by the MC firmware

                                             +--------------------------------------+
+------------+                  +---------+  |                           xgmac_mdio |
| net_device |                  | phylink |--|  +-----+  +-----+  +-----+  +-----+  |
+------------+                  +---------+  |  | PHY |  | PHY |  | PHY |  | PHY |  |
      |                             |        |  +-----+  +-----+  +-----+  +-----+  |
    +------------------------------------+   |                    External MDIO bus |
    |            dpaa2-eth               |   +--------------------------------------+
    +------------------------------------+
      |                             |                                           Linux
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                             |                                     MC firmware
      |              /|             V
+----------+        / |       +----------+
|          |       /  |       |          |
|          |       |  |       |          |
|   DPNI   |<------|  |<------|   DPMAC  |
|          |       |  |       |          |
|          |       \  |<---+  |          |
+----------+        \ |    |  +----------+
                     \|    |
                           |
         +--------------------------------------+
         | MC firmware polling MAC PCS for link |
         |  +-----+  +-----+  +-----+  +-----+  |
         |  | PCS |  | PCS |  | PCS |  | PCS |  |
         |  +-----+  +-----+  +-----+  +-----+  |
         |                    Internal MDIO bus |
         +--------------------------------------+
```

Depending on an MC firmware configuration setting, each MAC may be in one of two modes:

- DPMAC_LINK_TYPE_FIXED: the link state management is handled exclusively by the MC firmware by polling the MAC PCS. Without the need to register a phylink instance, the dpaa2-eth driver will not bind to the connected dpmac object at all.

- DPMAC_LINK_TYPE_PHY: The MC firmware is left waiting for link state update events, but those are in fact passed strictly between the dpaa2-mac (based on phylink) and its attached net_device driver (dpaa2-eth, dpaa2-ethsw), effectively bypassing the firmware.

<a id="rst-implementation"></a>

## Implementation

At probe time or when a DPNI's endpoint is dynamically changed, the dpaa2-eth is responsible to find out if the peer object is a DPMAC and if this is the case, to integrate it with PHYLINK using the dpaa2_mac_connect() API, which will do the following:

> - look up the device tree for PHYLINK-compatible of binding (phy-handle)
>
> - will create a PHYLINK instance associated with the received net_device
>
> - connect to the PHY using phylink_of_phy_connect()

The following phylink_mac_ops callback are implemented:

> - .validate() will populate the supported linkmodes with the MAC capabilities only when the phy_interface_t is RGMII\_\* (at the moment, this is the only link type supported by the driver).
>
> - .mac_config() will configure the MAC in the new configuration using the dpmac_set_link_state() MC firmware API.
>
> - .mac_link_up() / .mac_link_down() will update the MAC link using the same API described above.

At driver unbind() or when the DPNI object is disconnected from the DPMAC, the dpaa2-eth driver calls dpaa2_mac_disconnect() which will, in turn, disconnect from the PHY and destroy the PHYLINK instance.

In case of a DPNI-DPMAC connection, an 'ip link set dev eth0 up' would start the following sequence of operations:

1. phylink_start() called from .dev_open().

2. The .mac_config() and .mac_link_up() callbacks are called by PHYLINK.

3. In order to configure the HW MAC, the MC Firmware API dpmac_set_link_state() is called.

4. The firmware will eventually setup the HW MAC in the new configuration.

5. A netif_carrier_on() call is made directly from PHYLINK on the associated net_device.

6. The dpaa2-eth driver handles the LINK_STATE_CHANGE irq in order to enable/disable Rx taildrop based on the pause frame settings.



```none
+---------+               +---------+
| PHYLINK |-------------->|  eth0   |
+---------+           (5) +---------+
(1) ^  |
    |  |
    |  v (2)
+-----------------------------------+
|             dpaa2-eth             |
+-----------------------------------+
       |                    ^ (6)
       |                    |
       v (3)                |
+---------+---------------+---------+
|  DPMAC  |               |  DPNI   |
+---------+               +---------+
|            MC Firmware            |
+-----------------------------------+
       |
       |
       v (4)
+-----------------------------------+
|             HW MAC                |
+-----------------------------------+
```

In case of a DPNI-DPNI connection, a usual sequence of operations looks like the following:

1. ip link set dev eth0 up

2. The dpni_enable() MC API called on the associated fsl_mc_device.

3. ip link set dev eth1 up

4. The dpni_enable() MC API called on the associated fsl_mc_device.

5. The LINK_STATE_CHANGED irq is received by both instances of the dpaa2-eth driver because now the operational link state is up.

6. The netif_carrier_on() is called on the exported net_device from link_state_update().



```none
+---------+               +---------+
|  eth0   |               |  eth1   |
+---------+               +---------+
    |  ^                     ^  |
    |  |                     |  |
(1) v  | (6)             (6) |  v (3)
+---------+               +---------+
|dpaa2-eth|               |dpaa2-eth|
+---------+               +---------+
    |  ^                     ^  |
    |  |                     |  |
(2) v  | (5)             (5) |  v (4)
+---------+---------------+---------+
|  DPNI   |               |  DPNI   |
+---------+               +---------+
|            MC Firmware            |
+-----------------------------------+
```

<a id="rst-exported-api"></a>

## Exported API

Any DPAA2 driver that drivers endpoints of DPMAC objects should service its \_EVENT_ENDPOINT_CHANGED irq and connect/disconnect from the associated DPMAC when necessary using the below listed API:



```text
- int dpaa2_mac_connect(struct dpaa2_mac *mac);
- void dpaa2_mac_disconnect(struct dpaa2_mac *mac);
```

A phylink integration is necessary only when the partner DPMAC is not of `TYPE_FIXED`. This means it is either of `TYPE_PHY`, or of `TYPE_BACKPLANE` (the difference being the two that in the `TYPE_BACKPLANE` mode, the MC firmware does not access the PCS registers). One can check for this condition using the following helper:



```text
- static inline bool dpaa2_mac_is_type_phy(struct dpaa2_mac *mac);
```

Before connection to a MAC, the caller must allocate and populate the dpaa2_mac structure with the associated net_device, a pointer to the MC portal to be used and the actual fsl_mc_device structure of the DPMAC.

---

# DPAA2 (Data Path Acceleration Architecture Gen2) Overview

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> This document provides an overview of the Freescale DPAA2 architecture and how it is integrated into the Linux kernel.

<a id="rst-dpaa2-data-path-acceleration-architecture-gen2-overview"></a>

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2015 Freescale Semiconductor Inc.

**Copyright:** © 2018 NXP

This document provides an overview of the Freescale DPAA2 architecture and how it is integrated into the Linux kernel.

<a id="rst-introduction"></a>

## Introduction

DPAA2 is a hardware architecture designed for high-speeed network packet processing.  DPAA2 consists of sophisticated mechanisms for processing Ethernet packets, queue management, buffer management, autonomous L2 switching, virtual Ethernet bridging, and accelerator (e.g. crypto) sharing.

A DPAA2 hardware component called the Management Complex (or MC) manages the DPAA2 hardware resources.  The MC provides an object-based abstraction for software drivers to use the DPAA2 hardware. The MC uses DPAA2 hardware resources such as queues, buffer pools, and network ports to create functional objects/devices such as network interfaces, an L2 switch, or accelerator instances. The MC provides memory-mapped I/O command interfaces (MC portals) which DPAA2 software drivers use to operate on DPAA2 objects.

The diagram below shows an overview of the DPAA2 resource management architecture:



```text
+--------------------------------------+
|                  OS                  |
|                        DPAA2 drivers |
|                             |        |
+-----------------------------|--------+
                              |
                              | (create,discover,connect
                              |  config,use,destroy)
                              |
                 DPAA2        |
+------------------------| mc portal |-+
|                             |        |
|   +- - - - - - - - - - - - -V- - -+  |
|   |                               |  |
|   |   Management Complex (MC)     |  |
|   |                               |  |
|   +- - - - - - - - - - - - - - - -+  |
|                                      |
| Hardware                  Hardware   |
| Resources                 Objects    |
| ---------                 -------    |
| -queues                   -DPRC      |
| -buffer pools             -DPMCP     |
| -Eth MACs/ports           -DPIO      |
| -network interface        -DPNI      |
|  profiles                 -DPMAC     |
| -queue portals            -DPBP      |
| -MC portals                ...       |
|  ...                                 |
|                                      |
+--------------------------------------+
```

The MC mediates operations such as create, discover, connect, configuration, and destroy.  Fast-path operations on data, such as packet transmit/receive, are not mediated by the MC and are done directly using memory mapped regions in DPIO objects.

<a id="rst-overview-of-dpaa2-objects"></a>

## Overview of DPAA2 Objects

The section provides a brief overview of some key DPAA2 objects. A simple scenario is described illustrating the objects involved in creating a network interfaces.

<a id="rst-dprc-datapath-resource-container"></a>

### DPRC (Datapath Resource Container)

A DPRC is a container object that holds all the other types of DPAA2 objects.  In the example diagram below there are 8 objects of 5 types (DPMCP, DPIO, DPBP, DPNI, and DPMAC) in the container.



```text
+---------------------------------------------------------+
| DPRC                                                    |
|                                                         |
|  +-------+  +-------+  +-------+  +-------+  +-------+  |
|  | DPMCP |  | DPIO  |  | DPBP  |  | DPNI  |  | DPMAC |  |
|  +-------+  +-------+  +-------+  +---+---+  +---+---+  |
|  | DPMCP |  | DPIO  |                                   |
|  +-------+  +-------+                                   |
|  | DPMCP |                                              |
|  +-------+                                              |
|                                                         |
+---------------------------------------------------------+
```

From the point of view of an OS, a DPRC behaves similar to a plug and play bus, like PCI.  DPRC commands can be used to enumerate the contents of the DPRC, discover the hardware objects present (including mappable regions and interrupts).



```text
DPRC.1 (bus)
   |
   +--+--------+-------+-------+-------+
      |        |       |       |       |
    DPMCP.1  DPIO.1  DPBP.1  DPNI.1  DPMAC.1
    DPMCP.2  DPIO.2
    DPMCP.3
```

Hardware objects can be created and destroyed dynamically, providing the ability to hot plug/unplug objects in and out of the DPRC.

A DPRC has a mappable MMIO region (an MC portal) that can be used to send MC commands.  It has an interrupt for status events (like hotplug). All objects in a container share the same hardware "isolation context". This means that with respect to an IOMMU the isolation granularity is at the DPRC (container) level, not at the individual object level.

DPRCs can be defined statically and populated with objects via a config file passed to the MC when firmware starts it.

<a id="rst-dpaa2-objects-for-an-ethernet-network-interface"></a>

### DPAA2 Objects for an Ethernet Network Interface

A typical Ethernet NIC is monolithic-- the NIC device contains TX/RX queuing mechanisms, configuration mechanisms, buffer management, physical ports, and interrupts.  DPAA2 uses a more granular approach utilizing multiple hardware objects.  Each object provides specialized functions. Groups of these objects are used by software to provide Ethernet network interface functionality.  This approach provides efficient use of finite hardware resources, flexibility, and performance advantages.

The diagram below shows the objects needed for a simple network interface configuration on a system with 2 CPUs.



```text
+---+---+ +---+---+
   CPU0     CPU1
+---+---+ +---+---+
    |         |
+---+---+ +---+---+
   DPIO     DPIO
+---+---+ +---+---+
    \     /
     \   /
      \ /
   +---+---+
      DPNI  --- DPBP,DPMCP
   +---+---+
       |
       |
   +---+---+
     DPMAC
   +---+---+
       |
   port/PHY
```

Below the objects are described.  For each object a brief description is provided along with a summary of the kinds of operations the object supports and a summary of key resources of the object (MMIO regions and IRQs).

<a id="rst-dpmac-datapath-ethernet-mac"></a>

#### DPMAC (Datapath Ethernet MAC)

Represents an Ethernet MAC, a hardware device that connects to an Ethernet PHY and allows physical transmission and reception of Ethernet frames.

- MMIO regions: none

- IRQs: DPNI link change

- commands: set link up/down, link config, get stats, IRQ config, enable, reset

<a id="rst-dpni-datapath-network-interface"></a>

#### DPNI (Datapath Network Interface)

Contains TX/RX queues, network interface configuration, and RX buffer pool configuration mechanisms.  The TX/RX queues are in memory and are identified by queue number.

- MMIO regions: none

- IRQs: link state

- commands: port config, offload config, queue config, parse/classify config, IRQ config, enable, reset

<a id="rst-dpio-datapath-i-o"></a>

#### DPIO (Datapath I/O)

Provides interfaces to enqueue and dequeue packets and do hardware buffer pool management operations.  The DPAA2 architecture separates the mechanism to access queues (the DPIO object) from the queues themselves.  The DPIO provides an MMIO interface to enqueue/dequeue packets.  To enqueue something a descriptor is written to the DPIO MMIO region, which includes the target queue number. There will typically be one DPIO assigned to each CPU.  This allows all CPUs to simultaneously perform enqueue/dequeued operations.  DPIOs are expected to be shared by different DPAA2 drivers.

- MMIO regions: queue operations, buffer management

- IRQs: data availability, congestion notification, buffer pool depletion

- commands: IRQ config, enable, reset

<a id="rst-dpbp-datapath-buffer-pool"></a>

#### DPBP (Datapath Buffer Pool)

Represents a hardware buffer pool.

- MMIO regions: none

- IRQs: none

- commands: enable, reset

<a id="rst-dpmcp-datapath-mc-portal"></a>

#### DPMCP (Datapath MC Portal)

Provides an MC command portal. Used by drivers to send commands to the MC to manage objects.

- MMIO regions: MC command portal

- IRQs: command completion

- commands: IRQ config, enable, reset

<a id="rst-object-connections"></a>

## Object Connections

Some objects have explicit relationships that must be configured:

- DPNI &lt;--&gt; DPMAC

- DPNI &lt;--&gt; DPNI

- DPNI &lt;--&gt; L2-switch-port

  > A DPNI must be connected to something such as a DPMAC, another DPNI, or L2 switch port.  The DPNI connection is made via a DPRC command.



```text
+-------+  +-------+
| DPNI  |  | DPMAC |
+---+---+  +---+---+
    |          |
    +==========+
```

- DPNI &lt;--&gt; DPBP

  > A network interface requires a 'buffer pool' (DPBP object) which provides a list of pointers to memory where received Ethernet data is to be copied.  The Ethernet driver configures the DPBPs associated with the network interface.

<a id="rst-interrupts"></a>

## Interrupts

All interrupts generated by DPAA2 objects are message interrupts.  At the hardware level message interrupts generated by devices will normally have 3 components-- 1) a non-spoofable 'device-id' expressed on the hardware bus, 2) an address, 3) a data value.

In the case of DPAA2 devices/objects, all objects in the same container/DPRC share the same 'device-id'. For ARM-based SoC this is the same as the stream ID.

<a id="rst-dpaa2-linux-drivers-overview"></a>

## DPAA2 Linux Drivers Overview

This section provides an overview of the Linux kernel drivers for DPAA2-- 1) the bus driver and associated "DPAA2 infrastructure" drivers and 2) functional object drivers (such as Ethernet).

As described previously, a DPRC is a container that holds the other types of DPAA2 objects.  It is functionally similar to a plug-and-play bus controller. Each object in the DPRC is a Linux "device" and is bound to a driver. The diagram below shows the Linux drivers involved in a networking scenario and the objects bound to each driver.  A brief description of each driver follows.



```text
                                     +------------+
                                     | OS Network |
                                     |   Stack    |
         +------------+              +------------+
         | Allocator  |. . . . . . . |  Ethernet  |
         |(DPMCP,DPBP)|              |   (DPNI)   |
         +-.----------+              +---+---+----+
          .          .                   ^   |
         .            .     <data avail, |   | <enqueue,
        .              .     tx confirm> |   | dequeue>
+-------------+         .                |   |
| DPRC driver |          .           +---+---V----+     +---------+
|   (DPRC)    |           . . . . . .| DPIO driver|     |   MAC   |
+----------+--+                      |  (DPIO)    |     | (DPMAC) |
           |                         +------+-----+     +-----+---+
           |<dev add/remove>                |                 |
           |                                |                 |
  +--------+----------+                     |              +--+---+
  |   MC-bus driver   |                     |              | PHY  |
  |                   |                     |              |driver|
  |   /bus/fsl-mc     |                     |              +--+---+
  +-------------------+                     |                 |
                                            |                 |
========================= HARDWARE =========|=================|======
                                          DPIO                |
                                            |                 |
                                          DPNI---DPBP         |
                                            |                 |
                                          DPMAC               |
                                            |                 |
                                           PHY ---------------+
============================================|========================
```

A brief description of each driver is provided below.

<a id="rst-mc-bus-driver"></a>

### MC-bus driver

The MC-bus driver is a platform driver and is probed from a node in the device tree (compatible "fsl,qoriq-mc") passed in by boot firmware.  It is responsible for bootstrapping the DPAA2 kernel infrastructure. Key functions include:

- registering a new bus type named "fsl-mc" with the kernel, and implementing bus call-backs (e.g. match/uevent/dev_groups)

- implementing APIs for DPAA2 driver registration and for device add/remove

- creates an MSI IRQ domain

- doing a 'device add' to expose the 'root' DPRC, in turn triggering a bind of the root DPRC to the DPRC driver

The binding for the MC-bus device-tree node can be consulted at *Documentation/devicetree/bindings/misc/fsl,qoriq-mc.yaml*. The sysfs bind/unbind interfaces for the MC-bus can be consulted at *Documentation/ABI/testing/sysfs-bus-fsl-mc*.

<a id="rst-dprc-driver"></a>

### DPRC driver

The DPRC driver is bound to DPRC objects and does runtime management of a bus instance.  It performs the initial bus scan of the DPRC and handles interrupts for container events such as hot plug by re-scanning the DPRC.

<a id="rst-allocator"></a>

### Allocator

Certain objects such as DPMCP and DPBP are generic and fungible, and are intended to be used by other drivers.  For example, the DPAA2 Ethernet driver needs:

- DPMCPs to send MC commands, to configure network interfaces

- DPBPs for network buffer pools

The allocator driver registers for these allocatable object types and those objects are bound to the allocator when the bus is probed. The allocator maintains a pool of objects that are available for allocation by other DPAA2 drivers.

<a id="rst-dpio-driver"></a>

### DPIO driver

The DPIO driver is bound to DPIO objects and provides services that allow other drivers such as the Ethernet driver to enqueue and dequeue data for their respective objects. Key services include:

- data availability notifications

- hardware queuing operations (enqueue and dequeue of data)

- hardware buffer pool management

To transmit a packet the Ethernet driver puts data on a queue and invokes a DPIO API.  For receive, the Ethernet driver registers a data availability notification callback.  To dequeue a packet a DPIO API is used. There is typically one DPIO object per physical CPU for optimum performance, allowing different CPUs to simultaneously enqueue and dequeue data.

The DPIO driver operates on behalf of all DPAA2 drivers active in the kernel--  Ethernet, crypto, compression, etc.

<a id="rst-ethernet-driver"></a>

### Ethernet driver

The Ethernet driver is bound to a DPNI and implements the kernel interfaces needed to connect the DPAA2 network interface to the network stack. Each DPNI corresponds to a Linux network interface.

<a id="rst-mac-driver"></a>

### MAC driver

An Ethernet PHY is an off-chip, board specific component and is managed by the appropriate PHY driver via an mdio bus.  The MAC driver plays a role of being a proxy between the PHY driver and the MC.  It does this proxy via the MC commands to a DPMAC object. If the PHY driver signals a link change, the MAC driver notifies the MC via a DPMAC command.  If a network interface is brought up or down, the MC notifies the DPMAC driver via an interrupt and the driver can take appropriate action.

---

# DPAA2 Switch driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / freescale / dpaa2_

> The DPAA2 Switch driver probes on the Datapath Switch (DPSW) object which can be instantiated on the following DPAA2 SoCs and their variants: LS2088A and LX2160A.

<a id="rst-dpaa2-switch-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2021 NXP

The DPAA2 Switch driver probes on the Datapath Switch (DPSW) object which can be instantiated on the following DPAA2 SoCs and their variants: LS2088A and LX2160A.

The driver uses the switch device driver model and exposes each switch port as a network interface, which can be included in a bridge or used as a standalone interface. Traffic switched between ports is offloaded into the hardware.

The DPSW can have ports connected to DPNIs or to DPMACs for external access.



```text
  [ethA]     [ethB]      [ethC]     [ethD]     [ethE]     [ethF]
     :          :          :          :          :          :
     :          :          :          :          :          :
[dpaa2-eth]  [dpaa2-eth]  [              dpaa2-switch              ]
     :          :          :          :          :          :        kernel
=============================================================================
     :          :          :          :          :          :        hardware
  [DPNI]      [DPNI]     [============= DPSW =================]
     |          |          |          |          |          |
     |           ----------           |       [DPMAC]    [DPMAC]
      -------------------------------            |          |
                                                 |          |
                                               [PHY]      [PHY]
```

<a id="rst-creating-an-ethernet-switch"></a>

## Creating an Ethernet Switch

The dpaa2-switch driver probes on DPSW devices found on the fsl-mc bus. These devices can be either created statically through the boot time configuration file - DataPath Layout (DPL) - or at runtime using the DPAA2 object APIs (incorporated already into the restool userspace tool).

At the moment, the dpaa2-switch driver imposes the following restrictions on the DPSW object that it will probe:

> - The minimum number of FDBs should be at least equal to the number of switch interfaces. This is necessary so that separation of switch ports can be done, ie when not under a bridge, each switch port will have its own FDB.
>
>
>
>   ```text
>   fsl_dpaa2_switch dpsw.0: The number of FDBs is lower than the number of ports, cannot probe
>   ```
>
> - Both the broadcast and flooding configuration should be per FDB. This enables the driver to restrict the broadcast and flooding domains of each FDB depending on the switch ports that are sharing it (aka are under the same bridge).
>
>
>
>   ```text
>   fsl_dpaa2_switch dpsw.0: Flooding domain is not per FDB, cannot probe
>   fsl_dpaa2_switch dpsw.0: Broadcast domain is not per FDB, cannot probe
>   ```
>
> - The control interface of the switch should not be disabled (DPSW_OPT_CTRL_IF_DIS not passed as a create time option). Without the control interface, the driver is not capable to provide proper Rx/Tx traffic support on the switch port netdevices.
>
>
>
>   ```text
>   fsl_dpaa2_switch dpsw.0: Control Interface is disabled, cannot probe
>   ```

Besides the configuration of the actual DPSW object, the dpaa2-switch driver will need the following DPAA2 objects:

> - 1 DPMCP - A Management Command Portal object is needed for any interaction with the MC firmware.
>
> - 1 DPBP - A Buffer Pool is used for seeding buffers intended for the Rx path on the control interface.
>
> - Access to at least one DPIO object (Software Portal) is needed for any enqueue/dequeue operation to be performed on the control interface queues. The DPIO object will be shared, no need for a private one.

<a id="rst-switching-features"></a>

## Switching features

The driver supports the configuration of L2 forwarding rules in hardware for port bridging as well as standalone usage of the independent switch interfaces.

The hardware is not configurable with respect to VLAN awareness, thus any DPAA2 switch port should be used only in usecases with a VLAN aware bridge:



```text
$ ip link add dev br0 type bridge vlan_filtering 1

$ ip link add dev br1 type bridge
$ ip link set dev ethX master br1
Error: fsl_dpaa2_switch: Cannot join a VLAN-unaware bridge
```

Topology and loop detection through STP is supported when `stp_state 1` is used at bridge create



```text
$ ip link add dev br0 type bridge vlan_filtering 1 stp_state 1
```

L2 FDB manipulation (add/delete/dump) is supported.

HW FDB learning can be configured on each switch port independently through bridge commands. When the HW learning is disabled, a fast age procedure will be run and any previously learnt addresses will be removed.



```text
$ bridge link set dev ethX learning off
$ bridge link set dev ethX learning on
```

Restricting the unknown unicast and multicast flooding domain is supported, but not independently of each other:



```text
$ ip link set dev ethX type bridge_slave flood off mcast_flood off
$ ip link set dev ethX type bridge_slave flood off mcast_flood on
Error: fsl_dpaa2_switch: Cannot configure multicast flooding independently of unicast.
```

Broadcast flooding on a switch port can be disabled/enabled through the brport sysfs:



```text
$ echo 0 > /sys/bus/fsl-mc/devices/dpsw.Y/net/ethX/brport/broadcast_flood
```

<a id="rst-offloads"></a>

## Offloads

<a id="rst-routing-actions-redirect-trap-drop"></a>

### Routing actions (redirect, trap, drop)

The DPAA2 switch is able to offload flow-based redirection of packets making use of ACL tables. Shared filter blocks are supported by sharing a single ACL table between multiple ports.

The following flow keys are supported:

> - Ethernet: dst_mac/src_mac
>
> - IPv4: dst_ip/src_ip/ip_proto/tos
>
> - VLAN: vlan_id/vlan_prio/vlan_tpid/vlan_dei
>
> - L4: dst_port/src_port

Also, the matchall filter can be used to redirect the entire traffic received on a port.

As per flow actions, the following are supported:

> - drop
>
> - mirred egress redirect
>
> - trap

Each ACL entry (filter) can be setup with only one of the listed actions.

Example 1: send frames received on eth4 with a SA of 00:01:02:03:04:05 to the CPU:



```text
$ tc qdisc add dev eth4 clsact
$ tc filter add dev eth4 ingress flower src_mac 00:01:02:03:04:05 skip_sw action trap
```

Example 2: drop frames received on eth4 with VID 100 and PCP of 3:



```text
$ tc filter add dev eth4 ingress protocol 802.1q flower skip_sw vlan_id 100 vlan_prio 3 action drop
```

Example 3: redirect all frames received on eth4 to eth1:



```text
$ tc filter add dev eth4 ingress matchall action mirred egress redirect dev eth1
```

Example 4: Use a single shared filter block on both eth5 and eth6:



```text
$ tc qdisc add dev eth5 ingress_block 1 clsact
$ tc qdisc add dev eth6 ingress_block 1 clsact
$ tc filter add block 1 ingress flower dst_mac 00:01:02:03:04:04 skip_sw \
        action trap
$ tc filter add block 1 ingress protocol ipv4 flower src_ip 192.168.1.1 skip_sw \
        action mirred egress redirect dev eth3
```

<a id="rst-mirroring"></a>

#### Mirroring

The DPAA2 switch supports only per port mirroring and per VLAN mirroring. Adding mirroring filters in shared blocks is also supported.

When using the tc-flower classifier with the 802.1q protocol, only the ''vlan_id'' key will be accepted. Mirroring based on any other fields from the 802.1q protocol will be rejected:



```text
$ tc qdisc add dev eth8 ingress_block 1 clsact
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_prio 3 action mirred egress mirror dev eth6
Error: fsl_dpaa2_switch: Only matching on VLAN ID supported.
We have an error talking to the kernel
```

If a mirroring VLAN filter is requested on a port, the VLAN must to be installed on the switch port in question either using ''bridge'' or by creating a VLAN upper device if the switch port is used as a standalone interface:



```text
$ tc qdisc add dev eth8 ingress_block 1 clsact
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_id 200 action mirred egress mirror dev eth6
Error: VLAN must be installed on the switch port.
We have an error talking to the kernel

$ bridge vlan add vid 200 dev eth8
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_id 200 action mirred egress mirror dev eth6

$ ip link add link eth8 name eth8.200 type vlan id 200
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_id 200 action mirred egress mirror dev eth6
```

Also, it should be noted that the mirrored traffic will be subject to the same egress restrictions as any other traffic. This means that when a mirrored packet will reach the mirror port, if the VLAN found in the packet is not installed on the port it will get dropped.

The DPAA2 switch supports only a single mirroring destination, thus multiple mirror rules can be installed but their ''to'' port has to be the same:



```text
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_id 200 action mirred egress mirror dev eth6
$ tc filter add block 1 ingress protocol 802.1q flower skip_sw vlan_id 100 action mirred egress mirror dev eth7
Error: fsl_dpaa2_switch: Multiple mirror ports not supported.
We have an error talking to the kernel
```

---

# Linux kernel driver for Compute Engine Virtual Ethernet (gve):

_Peios Kernel / Internals / Networking / device_drivers / ethernet / google_

> The GVE driver binds to a single PCI device id used by the virtual Ethernet device found in some Compute Engine VMs.

<a id="rst-linux-kernel-driver-for-compute-engine-virtual-ethernet-gve"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-supported-hardware"></a>

## Supported Hardware

The GVE driver binds to a single PCI device id used by the virtual Ethernet device found in some Compute Engine VMs.


<table>
<thead>
<tr>
<th>


Field

</th>
<th>


Value

</th>
<th>


Comments

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Vendor ID

</td>
<td>


`0x1AE0`

</td>
<td>


Google

</td>
</tr>
<tr>
<td>


Device ID

</td>
<td>


`0x0042`

</td>
<td>




</td>
</tr>
<tr>
<td>


Sub-vendor ID

</td>
<td>


`0x1AE0`

</td>
<td>


Google

</td>
</tr>
<tr>
<td>


Sub-device ID

</td>
<td>


`0x0058`

</td>
<td>




</td>
</tr>
<tr>
<td>


Revision ID

</td>
<td>


`0x0`

</td>
<td>




</td>
</tr>
<tr>
<td>


Device Class

</td>
<td>


`0x200`

</td>
<td>


Ethernet

</td>
</tr>
</tbody>
</table>

<a id="rst-pci-bars"></a>

## PCI Bars

The gVNIC PCI device exposes three 32-bit memory BARS: - Bar0 - Device configuration and status registers. - Bar1 - MSI-X vector table - Bar2 - IRQ, RX and TX doorbells

<a id="rst-device-interactions"></a>

## Device Interactions

- **The driver interacts with the device in the following ways:**

  - - **Registers**

      - A block of MMIO registers

      - See gve_register.h for more detail

  - - **Admin Queue**

      - See description below

  - - **Reset**

      - At any time the device can be reset

  - - **Interrupts**

      - See supported interrupts below

  - - **Transmit and Receive Queues**

      - See description below

<a id="rst-descriptor-formats"></a>

### Descriptor Formats

GVE supports two descriptor formats: GQI and DQO. These two formats have entirely different descriptors, which will be described below.

<a id="rst-addressing-mode"></a>

### Addressing Mode

GVE supports two addressing modes: QPL and RDA. QPL ("queue-page-list") mode communicates data through a set of pre-registered pages.

For RDA ("raw DMA addressing") mode, the set of pages is dynamic. Therefore, the packet buffers can be anywhere in guest memory.

<a id="rst-registers"></a>

### Registers

All registers are MMIO.

The registers are used for initializing and configuring the device as well as querying device status in response to management interrupts.

<a id="rst-endianness"></a>

### Endianness

- Admin Queue messages and registers are all Big Endian.

- GQI descriptors and datapath registers are Big Endian.

- DQO descriptors and datapath registers are Little Endian.

<a id="rst-admin-queue-aq"></a>

### Admin Queue (AQ)

The Admin Queue is a PAGE_SIZE memory block, treated as an array of AQ commands, used by the driver to issue commands to the device and set up resources.The driver and the device maintain a count of how many commands have been submitted and executed. To issue AQ commands, the driver must do the following (with proper locking):

1. Copy new commands into next available slots in the AQ array

2. Increment its counter by he number of new commands

3. Write the counter into the GVE_ADMIN_QUEUE_DOORBELL register

4. Poll the ADMIN_QUEUE_EVENT_COUNTER register until it equals the value written to the doorbell, or until a timeout.

The device will update the status field in each AQ command reported as executed through the ADMIN_QUEUE_EVENT_COUNTER register.

<a id="rst-device-resets"></a>

### Device Resets

A device reset is triggered by writing 0x0 to the AQ PFN register. This causes the device to release all resources allocated by the driver, including the AQ itself.

<a id="rst-interrupts"></a>

### Interrupts

The following interrupts are supported by the driver:

<a id="rst-management-interrupt"></a>

#### Management Interrupt

The management interrupt is used by the device to tell the driver to look at the GVE_DEVICE_STATUS register.

The handler for the management irq simply queues the service task in the workqueue to check the register and acks the irq.

<a id="rst-notification-block-interrupts"></a>

#### Notification Block Interrupts

The notification block interrupts are used to tell the driver to poll the queues associated with that interrupt.

The handler for these irqs schedule the napi for that block to run and poll the queues.

<a id="rst-gqi-traffic-queues"></a>

### GQI Traffic Queues

GQI queues are composed of a descriptor ring and a buffer and are assigned to a notification block.

The descriptor rings are power-of-two-sized ring buffers consisting of fixed-size descriptors. They advance their head pointer using a \__be32 doorbell located in Bar2. The tail pointers are advanced by consuming descriptors in-order and updating a \__be32 counter. Both the doorbell and the counter overflow to zero.

Each queue's buffers must be registered in advance with the device as a queue page list, and packet data can only be put in those pages.

<a id="rst-transmit"></a>

#### Transmit

gve maps the buffers for transmit rings into a FIFO and copies the packets into the FIFO before sending them to the NIC.

<a id="rst-receive"></a>

#### Receive

The buffers for receive rings are put into a data ring that is the same length as the descriptor ring and the head and tail pointers advance over the rings together.

<a id="rst-dqo-traffic-queues"></a>

### DQO Traffic Queues

- Every TX and RX queue is assigned a notification block.

- TX and RX buffers queues, which send descriptors to the device, use MMIO doorbells to notify the device of new descriptors.

- RX and TX completion queues, which receive descriptors from the device, use a "generation bit" to know when a descriptor was populated by the device. The driver initializes all bits with the "current generation". The device will populate received descriptors with the "next generation" which is inverted from the current generation. When the ring wraps, the current/next generation are swapped.

- It's the driver's responsibility to ensure that the RX and TX completion queues are not overrun. This can be accomplished by limiting the number of descriptors posted to HW.

- TX packets have a 16 bit completion_tag and RX buffers have a 16 bit buffer_id. These will be returned on the TX completion and RX queues respectively to let the driver know which packet/buffer was completed.

<a id="rst-transmit-1"></a>

#### Transmit

A packet's buffers are DMA mapped for the device to access before transmission. After the packet was successfully transmitted, the buffers are unmapped.

<a id="rst-receive-1"></a>

#### Receive

The driver posts fixed sized buffers to HW on the RX buffer queue. The packet received on the associated RX queue may span multiple descriptors.

---

# Linux Kernel Driver for Huawei Intelligent NIC(HiNIC) family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / huawei_

> HiNIC is a network interface card for the Data Center Area.

<a id="rst-linux-kernel-driver-for-huawei-intelligent-nic-hinic-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview:

HiNIC is a network interface card for the Data Center Area.

The driver supports a range of link-speed devices (10GbE, 25GbE, 40GbE, etc.). The driver supports also a negotiated and extendable feature set.

Some HiNIC devices support SR-IOV. This driver is used for Physical Function (PF).

HiNIC devices support MSI-X interrupt vector for each Tx/Rx queue and adaptive interrupt moderation.

HiNIC devices support also various offload features such as checksum offload, TCP Transmit Segmentation Offload(TSO), Receive-Side Scaling(RSS) and LRO(Large Receive Offload).

<a id="rst-supported-pci-vendor-id-device-ids"></a>

## Supported PCI vendor ID/device IDs:

19e5:1822 - HiNIC PF

<a id="rst-driver-architecture-and-source-code"></a>

## Driver Architecture and Source Code:

hinic_dev - Implement a Logical Network device that is independent from specific HW details about HW data structure formats.

hinic_hwdev - Implement the HW details of the device and include the components for accessing the PCI NIC.

<a id="rst-hinic-hwdev-contains-the-following-components"></a>

## hinic_hwdev contains the following components:

<a id="rst-hw-interface"></a>

## HW Interface:

The interface for accessing the pci device (DMA memory and PCI BARs). (hinic_hw_if.c, hinic_hw_if.h)

Configuration Status Registers Area that describes the HW Registers on the configuration and status BAR0. (hinic_hw_csr.h)

<a id="rst-mgmt-components"></a>

## MGMT components:

Asynchronous Event Queues(AEQs) - The event queues for receiving messages from the MGMT modules on the cards. (hinic_hw_eqs.c, hinic_hw_eqs.h)

Application Programmable Interface commands(API CMD) - Interface for sending MGMT commands to the card. (hinic_hw_api_cmd.c, hinic_hw_api_cmd.h)

Management (MGMT) - the PF to MGMT channel that uses API CMD for sending MGMT commands to the card and receives notifications from the MGMT modules on the card by AEQs. Also set the addresses of the IO CMDQs in HW. (hinic_hw_mgmt.c, hinic_hw_mgmt.h)

<a id="rst-io-components"></a>

## IO components:

Completion Event Queues(CEQs) - The completion Event Queues that describe IO tasks that are finished. (hinic_hw_eqs.c, hinic_hw_eqs.h)

Work Queues(WQ) - Contain the memory and operations for use by CMD queues and the Queue Pairs. The WQ is a Memory Block in a Page. The Block contains pointers to Memory Areas that are the Memory for the Work Queue Elements(WQEs). (hinic_hw_wq.c, hinic_hw_wq.h)

Command Queues(CMDQ) - The queues for sending commands for IO management and is used to set the QPs addresses in HW. The commands completion events are accumulated on the CEQ that is configured to receive the CMDQ completion events. (hinic_hw_cmdq.c, hinic_hw_cmdq.h)

Queue Pairs(QPs) - The HW Receive and Send queues for Receiving and Transmitting Data. (hinic_hw_qp.c, hinic_hw_qp.h, hinic_hw_qp_ctxt.h)

IO - de/constructs all the IO components. (hinic_hw_io.c, hinic_hw_io.h)

<a id="rst-hw-device"></a>

## HW device:

HW device - de/constructs the HW Interface, the MGMT components on the initialization of the driver and the IO components on the case of Interface UP/DOWN Events. (hinic_hw_dev.c, hinic_hw_dev.h)

<a id="rst-hinic-dev-contains-the-following-components"></a>

## hinic_dev contains the following components:

PCI ID table - Contains the supported PCI Vendor/Device IDs. (hinic_pci_tbl.h)

Port Commands - Send commands to the HW device for port management (MAC, Vlan, MTU, ...). (hinic_port.c, hinic_port.h)

Tx Queues - Logical Tx Queues that use the HW Send Queues for transmit. The Logical Tx queue is not dependent on the format of the HW Send Queue. (hinic_tx.c, hinic_tx.h)

Rx Queues - Logical Rx Queues that use the HW Receive Queues for receive. The Logical Rx queue is not dependent on the format of the HW Receive Queue. (hinic_rx.c, hinic_rx.h)

hinic_dev - de/constructs the Logical Tx and Rx Queues. (hinic_main.c, hinic_dev.h)

<a id="rst-miscellaneous"></a>

## Miscellaneous

Common functions that are used by HW and Logical Device. (hinic_common.c, hinic_common.h)

<a id="rst-support"></a>

## Support

If an issue is identified with the released source code on the supported kernel with a supported adapter, email the specific information related to the issue to [aviad.krawczyk@huawei.com](<mailto:aviad.krawczyk@huawei.com>).

---

# Linux kernel driver for Huawei Ethernet Device Driver (hinic3) family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / huawei_

> The hinic3 is a network interface card (NIC) for Data Center. It supports a range of link-speed devices (10GE, 25GE, 100GE, etc.). The hinic3 devices can have multiple physical forms: LOM (Lan on Motherboard) NIC, PCIe standard NIC, OCP…

<a id="rst-linux-kernel-driver-for-huawei-ethernet-device-driver-hinic3-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The hinic3 is a network interface card (NIC) for Data Center. It supports a range of link-speed devices (10GE, 25GE, 100GE, etc.). The hinic3 devices can have multiple physical forms: LOM (Lan on Motherboard) NIC, PCIe standard NIC, OCP (Open Compute Project) NIC, etc.

The hinic3 driver supports the following features: - IPv4/IPv6 TCP/UDP checksum offload - TSO (TCP Segmentation Offload), LRO (Large Receive Offload) - RSS (Receive Side Scaling) - MSI-X interrupt aggregation configuration and interrupt adaptation. - SR-IOV (Single Root I/O Virtualization).

<a id="rst-content"></a>

## Content

- Supported PCI vendor ID/device IDs

- Source Code Structure of Hinic3 Driver

- Management Interface

<a id="rst-supported-pci-vendor-id-device-ids"></a>

## Supported PCI vendor ID/device IDs

19e5:0222 - hinic3 PF/PPF 19e5:375F - hinic3 VF

Prime Physical Function (PPF) is responsible for the management of the whole NIC card. For example, clock synchronization between the NIC and the host. Any PF may serve as a PPF. The PPF is selected dynamically.

<a id="rst-source-code-structure-of-hinic3-driver"></a>

## Source Code Structure of Hinic3 Driver


<table>
<tbody>
<tr>
<td>


hinic3_pci_id_tbl.h

</td>
<td>


Supported device IDs

</td>
</tr>
<tr>
<td>


hinic3_hw_intf.h

</td>
<td>


Interface between HW and driver

</td>
</tr>
<tr>
<td>


hinic3_queue_common.\[ch\]

</td>
<td>


Common structures and methods for NIC queues

</td>
</tr>
<tr>
<td>


hinic3_common.\[ch\]

</td>
<td>


Encapsulation of memory operations in Linux

</td>
</tr>
<tr>
<td>


hinic3_csr.h

</td>
<td>


Register definitions in the BAR

</td>
</tr>
<tr>
<td>


hinic3_hwif.\[ch\]

</td>
<td>


Interface for BAR

</td>
</tr>
<tr>
<td>


hinic3_eqs.\[ch\]

</td>
<td>


Interface for AEQs and CEQs

</td>
</tr>
<tr>
<td>


hinic3_mbox.\[ch\]

</td>
<td>


Interface for mailbox

</td>
</tr>
<tr>
<td>


hinic3_mgmt.\[ch\]

</td>
<td>


Management interface based on mailbox and AEQ

</td>
</tr>
<tr>
<td>


hinic3_wq.\[ch\]

</td>
<td>


Work queue data structures and interface

</td>
</tr>
<tr>
<td>


hinic3_cmdq.\[ch\]

</td>
<td>


Command queue is used to post command to HW

</td>
</tr>
<tr>
<td>


hinic3_hwdev.\[ch\]

</td>
<td>


HW structures and methods abstractions

</td>
</tr>
<tr>
<td>


hinic3_lld.\[ch\]

</td>
<td>


Auxiliary driver adaptation layer

</td>
</tr>
<tr>
<td>


hinic3_hw_comm.\[ch\]

</td>
<td>


Interface for common HW operations

</td>
</tr>
<tr>
<td>


hinic3_mgmt_interface.h

</td>
<td>


Interface between firmware and driver

</td>
</tr>
<tr>
<td>


hinic3_hw_cfg.\[ch\]

</td>
<td>


Interface for HW configuration

</td>
</tr>
<tr>
<td>


hinic3_irq.c

</td>
<td>


Interrupt request

</td>
</tr>
<tr>
<td>


hinic3_netdev_ops.c

</td>
<td>


Operations registered to Linux kernel stack

</td>
</tr>
<tr>
<td>


hinic3_nic_dev.h

</td>
<td>


NIC structures and methods abstractions

</td>
</tr>
<tr>
<td>


hinic3_main.c

</td>
<td>


Main Linux kernel driver

</td>
</tr>
<tr>
<td>


hinic3_nic_cfg.\[ch\]

</td>
<td>


NIC service configuration

</td>
</tr>
<tr>
<td>


hinic3_nic_io.\[ch\]

</td>
<td>


Management plane interface for TX and RX

</td>
</tr>
<tr>
<td>


hinic3_rss.\[ch\]

</td>
<td>


Interface for Receive Side Scaling (RSS)

</td>
</tr>
<tr>
<td>


hinic3_rx.\[ch\]

</td>
<td>


Interface for transmit

</td>
</tr>
<tr>
<td>


hinic3_tx.\[ch\]

</td>
<td>


Interface for receive

</td>
</tr>
<tr>
<td>


hinic3_ethtool.c

</td>
<td>


Interface for ethtool operations (ops)

</td>
</tr>
<tr>
<td>


hinic3_filter.c

</td>
<td>


Interface for MAC address

</td>
</tr>
</tbody>
</table>

<a id="rst-management-interface"></a>

## Management Interface

<a id="rst-asynchronous-event-queue-aeq"></a>

### Asynchronous Event Queue (AEQ)

AEQ receives high priority events from the HW over a descriptor queue. Every descriptor is a fixed size of 64 bytes. AEQ can receive solicited or unsolicited events. Every device, VF or PF, can have up to 4 AEQs. Every AEQ is associated to a dedicated IRQ. AEQ can receive multiple types of events, but in practice the hinic3 driver ignores all events except for 2 mailbox related events.

<a id="rst-mailbox"></a>

### Mailbox

Mailbox is a communication mechanism between the hinic3 driver and the HW. Each device has an independent mailbox. Driver can use the mailbox to send requests to management. Driver receives mailbox messages, such as responses to requests, over the AEQ (using event HINIC3_AEQ_FOR_MBOX). Due to the limited size of mailbox data register, mailbox messages are sent segment-by-segment.

Every device can use its mailbox to post request to firmware. The mailbox can also be used to post requests and responses between the PF and its VFs.

<a id="rst-completion-event-queue-ceq"></a>

### Completion Event Queue (CEQ)

The implementation of CEQ is the same as AEQ. It receives completion events from HW over a fixed size descriptor of 32 bits. Every device can have up to 32 CEQs. Every CEQ has a dedicated IRQ. CEQ only receives solicited events that are responses to requests from the driver. CEQ can receive multiple types of events, but in practice the hinic3 driver ignores all events except for HINIC3_CMDQ that represents completion of previously posted commands on a cmdq.

<a id="rst-command-queue-cmdq"></a>

### Command Queue (cmdq)

Every cmdq has a dedicated work queue on which commands are posted. Commands on the work queue are fixed size descriptor of size 64 bytes. Completion of a command will be indicated using ctrl bits in the descriptor that carried the command. Notification of command completions will also be provided via event on CEQ. Every device has 4 command queues that are initialized as a set (called cmdqs), each with its own type. Hinic3 driver only uses type HINIC3_CMDQ_SYNC.

<a id="rst-work-queues-wq"></a>

### Work Queues(WQ)

Work queues are logical arrays of fixed size WQEs. The array may be spread over multiple non-contiguous pages using indirection table. Work queues are used by I/O queues and command queues.

<a id="rst-global-function-id"></a>

### Global function ID

Every function, PF or VF, has a unique ordinal identification within the device. Many management commands (mbox or cmdq) contain this ID so HW can apply the command effect to the right function.

PF is allowed to post management commands to a subordinate VF by specifying the VFs ID. A VF must provide its own ID. Anti-spoofing in the HW will cause command from a VF to fail if it contains the wrong ID.

---

# Linux Base Driver for the Intel(R) PRO/100 Family of Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> June 1, 2018

<a id="rst-linux-base-driver-for-the-intel-r-pro-100-family-of-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

June 1, 2018

<a id="rst-contents"></a>

## Contents

- In This Release

- Identifying Your Adapter

- Building and Installation

- Driver Configuration Parameters

- Additional Configurations

- Known Issues

- Support

<a id="rst-in-this-release"></a>

## In This Release

This file describes the Linux Base Driver for the Intel(R) PRO/100 Family of Adapters. This driver includes support for Itanium(R)2-based systems.

For questions related to hardware requirements, refer to the documentation supplied with your Intel PRO/100 adapter.

- **The following features are now available in supported kernels:**

  - Native VLANs

  - Channel Bonding (teaming)

  - SNMP

Channel Bonding documentation can be found in the Linux kernel source: /Documentation/networking/bonding.rst

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-driver-configuration-parameters"></a>

## Driver Configuration Parameters

The default value for each parameter is generally the recommended setting, unless otherwise noted.

- **Rx Descriptors:**

  Number of receive descriptors. A receive descriptor is a data structure that describes a receive buffer and its attributes to the network controller. The data in the descriptor is used by the controller to write data from the controller to host memory. In the 3.x.x driver the valid range for this parameter is 64-256. The default value is 256. This parameter can be changed using the command:



  ```text
  ethtool -G eth? rx n
  ```

  Where n is the number of desired Rx descriptors.

- **Tx Descriptors:**

  Number of transmit descriptors. A transmit descriptor is a data structure that describes a transmit buffer and its attributes to the network controller. The data in the descriptor is used by the controller to read data from the host memory to the controller. In the 3.x.x driver the valid range for this parameter is 64-256. The default value is 128. This parameter can be changed using the command:



  ```text
  ethtool -G eth? tx n
  ```

  Where n is the number of desired Tx descriptors.

- **Speed/Duplex:**

  The driver auto-negotiates the link speed and duplex settings by default. The ethtool utility can be used as follows to force speed/duplex.:



  ```text
  ethtool -s eth?  autoneg off speed {10|100} duplex {full|half}
  ```

  NOTE: setting the speed/duplex to incorrect values will cause the link to fail.

- **Event Log Message Level:**

  The driver uses the message level flag to log events to syslog. The message level can be set at driver load time. It can also be set using the command:



  ```text
  ethtool -s eth? msglvl n
  ```

<a id="rst-additional-configurations"></a>

## Additional Configurations

<a id="rst-configuring-the-driver-on-different-distributions"></a>

### Configuring the Driver on Different Distributions

Configuring a network driver to load properly when the system is started is distribution dependent.  Typically, the configuration process involves adding an alias line to `/etc/modprobe.d/*.conf` as well as editing other system startup scripts and/or configuration files.  Many popular Linux distributions ship with tools to make these changes for you.  To learn the proper way to configure a network device for your system, refer to your distribution documentation.  If during this process you are asked for the driver or module name, the name for the Linux Base Driver for the Intel PRO/100 Family of Adapters is e100.

As an example, if you install the e100 driver for two PRO/100 adapters (eth0 and eth1), add the following to a configuration file in /etc/modprobe.d/:



```text
alias eth0 e100
alias eth1 e100
```

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

In order to see link messages and other Intel driver information on your console, you must set the dmesg level up to six.  This can be done by entering the following on the command line before loading the e100 driver:



```text
dmesg -n 6
```

If you wish to see all messages issued by the driver, including debug messages, set the dmesg level to eight.

NOTE: This setting is not saved across reboots.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information.  The ethtool version 1.6 or later is required for this functionality.

The latest release of ethtool can be found from [https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-enabling-wake-on-lan-wol"></a>

### Enabling Wake on LAN (WoL)

WoL is provided through the ethtool utility.  For instructions on enabling WoL with ethtool, refer to the ethtool man page.  WoL will be enabled on the system during the next shut down or reboot.  For this driver version, in order to enable WoL, the e100 driver must be loaded when shutting down or rebooting the system.

<a id="rst-napi"></a>

### NAPI

NAPI (Rx polling mode) is supported in the e100 driver.

See [Documentation/networking/napi.rst](<#rst-napi>) for more information.

<a id="rst-multiple-interfaces-on-same-ethernet-broadcast-network"></a>

### Multiple Interfaces on Same Ethernet Broadcast Network

Due to the default ARP behavior on Linux, it is not possible to have one system on two IP networks in the same Ethernet broadcast domain (non-partitioned switch) behave as expected.  All Ethernet interfaces will respond to IP traffic for any IP address assigned to the system. This results in unbalanced receive traffic.

If you have multiple interfaces in a server, either turn on ARP filtering by

1. entering:



   ```text
   echo 1 > /proc/sys/net/ipv4/conf/all/arp_filter
   ```

   (this only works if your kernel's version is higher than 2.4.5), or

2. installing the interfaces in separate broadcast domains (either in different switches or in a switch partitioned to VLANs).

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for Intel(R) Ethernet Network Connection

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel Gigabit Linux driver. Copyright(c) 1999 - 2013 Intel Corporation.

<a id="rst-linux-base-driver-for-intel-r-ethernet-network-connection"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel Gigabit Linux driver. Copyright(c) 1999 - 2013 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Command Line Parameters

- Speed and Duplex Configuration

- Additional Configurations

- Support

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For more information on how to identify your adapter, go to the Adapter &amp; Driver ID Guide at:

> [http://support.intel.com/support/go/network/adapter/idguide.htm](<http://support.intel.com/support/go/network/adapter/idguide.htm>)

For the latest Intel network drivers for Linux, refer to the following website.  In the search field, enter your adapter name or type, or use the networking link on the left to search for your adapter:

> [http://support.intel.com/support/go/network/adapter/home.htm](<http://support.intel.com/support/go/network/adapter/home.htm>)

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

The default value for each parameter is generally the recommended setting, unless otherwise noted.

- **NOTES:**

  For more information about the AutoNeg, Duplex, and Speed parameters, see the "Speed and Duplex Configuration" section in this document.

  For more information about the InterruptThrottleRate, RxIntDelay, TxIntDelay, RxAbsIntDelay, and TxAbsIntDelay parameters, see the application note at: [http://www.intel.com/design/network/applnots/ap450.htm](<http://www.intel.com/design/network/applnots/ap450.htm>)

<a id="rst-autoneg"></a>

### AutoNeg

(Supported only on adapters with copper connections)

**Valid Range:** 0x01-0x0F, 0x20-0x2F

**Default Value:** 0x2F

This parameter is a bit-mask that specifies the speed and duplex settings advertised by the adapter.  When this parameter is used, the Speed and Duplex parameters must not be specified.

- **NOTE:**

  Refer to the Speed and Duplex section of this readme for more information on the AutoNeg parameter.

<a id="rst-duplex"></a>

### Duplex

(Supported only on adapters with copper connections)

**Valid Range:** 0-2 (0=auto-negotiate, 1=half, 2=full)

**Default Value:** 0

This defines the direction in which data is allowed to flow.  Can be either one or two-directional.  If both Duplex and the link partner are set to auto-negotiate, the board auto-detects the correct duplex.  If the link partner is forced (either full or half), Duplex defaults to half- duplex.

<a id="rst-flowcontrol"></a>

### FlowControl

**Valid Range:** 0-3 (0=none, 1=Rx only, 2=Tx only, 3=Rx&amp;Tx)

**Default Value:** Reads flow control settings from the EEPROM

This parameter controls the automatic generation(Tx) and response(Rx) to Ethernet PAUSE frames.

<a id="rst-interruptthrottlerate"></a>

### InterruptThrottleRate

(not supported on Intel(R) 82542, 82543 or 82544-based adapters)

**Valid Range:** 0,1,3,4,100-100000 (0=off, 1=dynamic, 3=dynamic conservative, 4=simplified balancing)

**Default Value:** 3

The driver can limit the amount of interrupts per second that the adapter will generate for incoming packets. It does this by writing a value to the adapter that is based on the maximum amount of interrupts that the adapter will generate per second.

Setting InterruptThrottleRate to a value greater or equal to 100 will program the adapter to send out a maximum of that many interrupts per second, even if more packets have come in. This reduces interrupt load on the system and can lower CPU utilization under heavy load, but will increase latency as packets are not processed as quickly.

The default behaviour of the driver previously assumed a static InterruptThrottleRate value of 8000, providing a good fallback value for all traffic types,but lacking in small packet performance and latency. The hardware can handle many more small packets per second however, and for this reason an adaptive interrupt moderation algorithm was implemented.

Since 7.3.x, the driver has two adaptive modes (setting 1 or 3) in which it dynamically adjusts the InterruptThrottleRate value based on the traffic that it receives. After determining the type of incoming traffic in the last timeframe, it will adjust the InterruptThrottleRate to an appropriate value for that traffic.

The algorithm classifies the incoming traffic every interval into classes.  Once the class is determined, the InterruptThrottleRate value is adjusted to suit that traffic type the best. There are three classes defined: "Bulk traffic", for large amounts of packets of normal size; "Low latency", for small amounts of traffic and/or a significant percentage of small packets; and "Lowest latency", for almost completely small packets or minimal traffic.

In dynamic conservative mode, the InterruptThrottleRate value is set to 4000 for traffic that falls in class "Bulk traffic". If traffic falls in the "Low latency" or "Lowest latency" class, the InterruptThrottleRate is increased stepwise to 20000. This default mode is suitable for most applications.

For situations where low latency is vital such as cluster or grid computing, the algorithm can reduce latency even more when InterruptThrottleRate is set to mode 1. In this mode, which operates the same as mode 3, the InterruptThrottleRate will be increased stepwise to 70000 for traffic in class "Lowest latency".

In simplified mode the interrupt rate is based on the ratio of TX and RX traffic.  If the bytes per second rate is approximately equal, the interrupt rate will drop as low as 2000 interrupts per second.  If the traffic is mostly transmit or mostly receive, the interrupt rate could be as high as 8000.

Setting InterruptThrottleRate to 0 turns off any interrupt moderation and may improve small packet latency, but is generally not suitable for bulk throughput traffic.

- **NOTE:**

  InterruptThrottleRate takes precedence over the TxAbsIntDelay and RxAbsIntDelay parameters.  In other words, minimizing the receive and/or transmit absolute delays does not force the controller to generate more interrupts than what the Interrupt Throttle Rate allows.

- **CAUTION:**

  If you are using the Intel(R) PRO/1000 CT Network Connection (controller 82547), setting InterruptThrottleRate to a value greater than 75,000, may hang (stop transmitting) adapters under certain network conditions.  If this occurs a NETDEV WATCHDOG message is logged in the system event log.  In addition, the controller is automatically reset, restoring the network connection.  To eliminate the potential for the hang, ensure that InterruptThrottleRate is set no greater than 75,000 and is not set to 0.

- **NOTE:**

  When e1000 is loaded with default settings and multiple adapters are in use simultaneously, the CPU utilization may increase non- linearly.  In order to limit the CPU utilization without impacting the overall throughput, we recommend that you load the driver as follows:



  ```text
  modprobe e1000 InterruptThrottleRate=3000,3000,3000
  ```

  This sets the InterruptThrottleRate to 3000 interrupts/sec for the first, second, and third instances of the driver.  The range of 2000 to 3000 interrupts per second works on a majority of systems and is a good starting point, but the optimal value will be platform-specific.  If CPU utilization is not a concern, use RX_POLLING (NAPI) and default driver settings.

<a id="rst-rxdescriptors"></a>

### RxDescriptors

**Valid Range:** - 48-256 for 82542 and 82543-based adapters

- 48-4096 for all other supported adapters

**Default Value:** 256

This value specifies the number of receive buffer descriptors allocated by the driver.  Increasing this value allows the driver to buffer more incoming packets, at the expense of increased system memory utilization.

Each descriptor is 16 bytes.  A receive buffer is also allocated for each descriptor and can be either 2048, 4096, 8192, or 16384 bytes, depending on the MTU setting. The maximum MTU size is 16110.

- **NOTE:**

  MTU designates the frame size.  It only needs to be set for Jumbo Frames.  Depending on the available system resources, the request for a higher number of receive descriptors may be denied.  In this case, use a lower number.

<a id="rst-rxintdelay"></a>

### RxIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 0

This value delays the generation of receive interrupts in units of 1.024 microseconds.  Receive interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic.  Increasing this value adds extra latency to frame reception and can end up decreasing the throughput of TCP traffic.  If the system is reporting dropped receives, this value may be set too high, causing the driver to run out of available receive descriptors.

- **CAUTION:**

  When setting RxIntDelay to a value other than 0, adapters may hang (stop transmitting) under certain network conditions.  If this occurs a NETDEV WATCHDOG message is logged in the system event log.  In addition, the controller is automatically reset, restoring the network connection.  To eliminate the potential for the hang ensure that RxIntDelay is set to 0.

<a id="rst-rxabsintdelay"></a>

### RxAbsIntDelay

(This parameter is supported only on 82540, 82545 and later adapters.)

**Valid Range:** 0-65535 (0=off)

**Default Value:** 128

This value, in units of 1.024 microseconds, limits the delay in which a receive interrupt is generated.  Useful only if RxIntDelay is non-zero, this value ensures that an interrupt is generated after the initial packet is received within the set amount of time.  Proper tuning, along with RxIntDelay, may improve traffic throughput in specific network conditions.

<a id="rst-speed"></a>

### Speed

(This parameter is supported only on adapters with copper connections.)

**Valid Settings:** 0, 10, 100, 1000

**Default Value:** 0 (auto-negotiate at all supported speeds)

Speed forces the line speed to the specified value in megabits per second (Mbps).  If this parameter is not specified or is set to 0 and the link partner is set to auto-negotiate, the board will auto-detect the correct speed.  Duplex should also be set when Speed is set to either 10 or 100.

<a id="rst-txdescriptors"></a>

### TxDescriptors

**Valid Range:** - 48-256 for 82542 and 82543-based adapters

- 48-4096 for all other supported adapters

**Default Value:** 256

This value is the number of transmit descriptors allocated by the driver. Increasing this value allows the driver to queue more transmits.  Each descriptor is 16 bytes.

- **NOTE:**

  Depending on the available system resources, the request for a higher number of transmit descriptors may be denied.  In this case, use a lower number.

<a id="rst-txintdelay"></a>

### TxIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 8

This value delays the generation of transmit interrupts in units of 1.024 microseconds.  Transmit interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic.  If the system is reporting dropped transmits, this value may be set too high causing the driver to run out of available transmit descriptors.

<a id="rst-txabsintdelay"></a>

### TxAbsIntDelay

(This parameter is supported only on 82540, 82545 and later adapters.)

**Valid Range:** 0-65535 (0=off)

**Default Value:** 32

This value, in units of 1.024 microseconds, limits the delay in which a transmit interrupt is generated.  Useful only if TxIntDelay is non-zero, this value ensures that an interrupt is generated after the initial packet is sent on the wire within the set amount of time.  Proper tuning, along with TxIntDelay, may improve traffic throughput in specific network conditions.

<a id="rst-xsumrx"></a>

### XsumRX

(This parameter is NOT supported on the 82542-based adapter.)

**Valid Range:** 0-1

**Default Value:** 1

A value of '1' indicates that the driver should enable IP checksum offload for received packets (both UDP and TCP) to the adapter hardware.

<a id="rst-copybreak"></a>

### Copybreak

**Valid Range:** 0-xxxxxxx (0=off)

**Default Value:** 256

**Usage:** modprobe e1000.ko copybreak=128

Driver copies all packets below or equaling this size to a fresh RX buffer before handing it up the stack.

This parameter is different than other parameters, in that it is a single (not 1,1,1 etc.) parameter applied to all driver instances and it is also available during runtime at /sys/module/e1000/parameters/copybreak

<a id="rst-smartpowerdownenable"></a>

### SmartPowerDownEnable

**Valid Range:** 0-1

**Default Value:** 0 (disabled)

Allows PHY to turn off in lower power states. The user can turn off this parameter in supported chipsets.

<a id="rst-speed-and-duplex-configuration"></a>

## Speed and Duplex Configuration

Three keywords are used to control the speed and duplex configuration. These keywords are Speed, Duplex, and AutoNeg.

If the board uses a fiber interface, these keywords are ignored, and the fiber interface board only links at 1000 Mbps full-duplex.

For copper-based boards, the keywords interact as follows:

- The default operation is auto-negotiate.  The board advertises all supported speed and duplex combinations, and it links at the highest common speed and duplex mode IF the link partner is set to auto-negotiate.

- If Speed = 1000, limited auto-negotiation is enabled and only 1000 Mbps is advertised (The 1000BaseT spec requires auto-negotiation.)

- If Speed = 10 or 100, then both Speed and Duplex should be set.  Auto- negotiation is disabled, and the AutoNeg parameter is ignored.  Partner SHOULD also be forced.

The AutoNeg parameter is used when more control is required over the auto-negotiation process.  It should be used when you wish to control which speed and duplex combinations are advertised during the auto-negotiation process.

The parameter may be specified as either a decimal or hexadecimal value as determined by the bitmap below.


<table>
<tbody>
<tr>
<td>


Bit position

</td>
<td>


7

</td>
<td>


6

</td>
<td>


5

</td>
<td>


4

</td>
<td>


3

</td>
<td>


2

</td>
<td>


1

</td>
<td>


0

</td>
</tr>
<tr>
<td>


Decimal Value

</td>
<td>


128

</td>
<td>


64

</td>
<td>


32

</td>
<td>


16

</td>
<td>


8

</td>
<td>


4

</td>
<td>


2

</td>
<td>


1

</td>
</tr>
<tr>
<td>


Hex value

</td>
<td>


80

</td>
<td>


40

</td>
<td>


20

</td>
<td>


10

</td>
<td>


8

</td>
<td>


4

</td>
<td>


2

</td>
<td>


1

</td>
</tr>
<tr>
<td>


Speed (Mbps)

</td>
<td>


N/A

</td>
<td>


N/A

</td>
<td>


1000

</td>
<td>


N/A

</td>
<td>


100

</td>
<td>


100

</td>
<td>


10

</td>
<td>


10

</td>
</tr>
<tr>
<td>


Duplex

</td>
<td>




</td>
<td>




</td>
<td>


Full

</td>
<td>




</td>
<td>


Full

</td>
<td>


Half

</td>
<td>


Full

</td>
<td>


Half

</td>
</tr>
</tbody>
</table>

Some examples of using AutoNeg:



```text
modprobe e1000 AutoNeg=0x01 (Restricts autonegotiation to 10 Half)
modprobe e1000 AutoNeg=1 (Same as above)
modprobe e1000 AutoNeg=0x02 (Restricts autonegotiation to 10 Full)
modprobe e1000 AutoNeg=0x03 (Restricts autonegotiation to 10 Half or 10 Full)
modprobe e1000 AutoNeg=0x04 (Restricts autonegotiation to 100 Half)
modprobe e1000 AutoNeg=0x05 (Restricts autonegotiation to 10 Half or 100
Half)
modprobe e1000 AutoNeg=0x020 (Restricts autonegotiation to 1000 Full)
modprobe e1000 AutoNeg=32 (Same as above)
```

Note that when this parameter is used, Speed and Duplex must not be specified.

If the link partner is forced to a specific speed and duplex, then this parameter should not be used.  Instead, use the Speed and Duplex parameters previously mentioned to force the adapter to the same speed and duplex.

<a id="rst-additional-configurations"></a>

## Additional Configurations

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

> Jumbo Frames support is enabled by changing the MTU to a value larger than the default of 1500.  Use the ifconfig command to increase the MTU size. For example:
>
>
>
> ```text
> ifconfig eth<x> mtu 9000 up
> ```
>
> This setting is not saved across reboots.  It can be made permanent if you add:
>
>
>
> ```text
> MTU=9000
> ```
>
> to the file /etc/sysconfig/network-scripts/ifcfg-eth&lt;x&gt;.  This example applies to the Red Hat distributions; other distributions may store this setting in a different location.

- **Notes:**

  Degradation in throughput performance may be observed in some Jumbo frames environments. If this is observed, increasing the application's socket buffer size and/or increasing the /proc/sys/net/ipv4/tcp\_\*mem entry values may help. See the specific application manual and /usr/src/linux\*/Documentation/ networking/ip-sysctl.txt for more details.

  - The maximum MTU setting for Jumbo Frames is 16110.  This value coincides with the maximum Jumbo Frames size of 16128.

  - Using Jumbo frames at 10 or 100 Mbps is not supported and may result in poor performance or loss of link.

  - Adapters based on the Intel(R) 82542 and 82573V/E controller do not support Jumbo Frames. These correspond to the following product names:



    ```text
    Intel(R) PRO/1000 Gigabit Server Adapter
    Intel(R) PRO/1000 PM Network Connection
    ```

<a id="rst-ethtool"></a>

### ethtool

> The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information.  The ethtool version 1.6 or later is required for this functionality.
>
> The latest release of ethtool can be found from [https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-enabling-wake-on-lan-wol"></a>

### Enabling Wake on LAN (WoL)

> WoL is configured through the ethtool utility.
>
> WoL will be enabled on the system during the next shut down or reboot. For this driver version, in order to enable WoL, the e1000 driver must be loaded when shutting down or rebooting the system.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [http://support.intel.com](<http://support.intel.com>)

If an issue is identified with the released source code on the supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Driver for Intel(R) Ethernet Network Connection

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel Gigabit Linux driver. Copyright(c) 2008-2018 Intel Corporation.

<a id="rst-linux-driver-for-intel-r-ethernet-network-connection"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel Gigabit Linux driver. Copyright(c) 2008-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Command Line Parameters

- Additional Configurations

- Support

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

If the driver is built as a module, the following optional parameters are used by entering them on the command line with the modprobe command using this syntax:



```text
modprobe e1000e [<option>=<VAL1>,<VAL2>,...]
```

There needs to be a &lt;VAL\#&gt; for each network port in the system supported by this driver. The values will be applied to each instance, in function order. For example:



```text
modprobe e1000e InterruptThrottleRate=16000,16000
```

In this case, there are two network ports supported by e1000e in the system. The default value for each parameter is generally the recommended setting, unless otherwise noted.

NOTE: A descriptor describes a data buffer and attributes related to the data buffer. This information is accessed by the hardware.

<a id="rst-interruptthrottlerate"></a>

### InterruptThrottleRate

**Valid Range:** 0,1,3,4,100-100000

**Default Value:** 3

Interrupt Throttle Rate controls the number of interrupts each interrupt vector can generate per second. Increasing ITR lowers latency at the cost of increased CPU utilization, though it may help throughput in some circumstances.

Setting InterruptThrottleRate to a value greater or equal to 100 will program the adapter to send out a maximum of that many interrupts per second, even if more packets have come in. This reduces interrupt load on the system and can lower CPU utilization under heavy load, but will increase latency as packets are not processed as quickly.

The default behaviour of the driver previously assumed a static InterruptThrottleRate value of 8000, providing a good fallback value for all traffic types, but lacking in small packet performance and latency. The hardware can handle many more small packets per second however, and for this reason an adaptive interrupt moderation algorithm was implemented.

The driver has two adaptive modes (setting 1 or 3) in which it dynamically adjusts the InterruptThrottleRate value based on the traffic that it receives. After determining the type of incoming traffic in the last timeframe, it will adjust the InterruptThrottleRate to an appropriate value for that traffic.

The algorithm classifies the incoming traffic every interval into classes.  Once the class is determined, the InterruptThrottleRate value is adjusted to suit that traffic type the best. There are three classes defined: "Bulk traffic", for large amounts of packets of normal size; "Low latency", for small amounts of traffic and/or a significant percentage of small packets; and "Lowest latency", for almost completely small packets or minimal traffic.

> - - **0: Off**
>
>     Turns off any interrupt moderation and may improve small packet latency. However, this is generally not suitable for bulk throughput traffic due to the increased CPU utilization of the higher interrupt rate.
>
> - - **1: Dynamic mode**
>
>     This mode attempts to moderate interrupts per vector while maintaining very low latency. This can sometimes cause extra CPU utilization. If planning on deploying e1000e in a latency sensitive environment, this parameter should be considered.
>
> - - **3: Dynamic Conservative mode (default)**
>
>     In dynamic conservative mode, the InterruptThrottleRate value is set to 4000 for traffic that falls in class "Bulk traffic". If traffic falls in the "Low latency" or "Lowest latency" class, the InterruptThrottleRate is increased stepwise to 20000. This default mode is suitable for most applications.
>
> - - **4: Simplified Balancing mode**
>
>     In simplified mode the interrupt rate is based on the ratio of TX and RX traffic.  If the bytes per second rate is approximately equal, the interrupt rate will drop as low as 2000 interrupts per second.  If the traffic is mostly transmit or mostly receive, the interrupt rate could be as high as 8000.
>
> - - **100-100000:**
>
>     Setting InterruptThrottleRate to a value greater or equal to 100 will program the adapter to send at most that many interrupts per second, even if more packets have come in. This reduces interrupt load on the system and can lower CPU utilization under heavy load, but will increase latency as packets are not processed as quickly.

NOTE: InterruptThrottleRate takes precedence over the TxAbsIntDelay and RxAbsIntDelay parameters. In other words, minimizing the receive and/or transmit absolute delays does not force the controller to generate more interrupts than what the Interrupt Throttle Rate allows.

<a id="rst-rxintdelay"></a>

### RxIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 0

This value delays the generation of receive interrupts in units of 1.024 microseconds. Receive interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic. Increasing this value adds extra latency to frame reception and can end up decreasing the throughput of TCP traffic. If the system is reporting dropped receives, this value may be set too high, causing the driver to run out of available receive descriptors.

CAUTION: When setting RxIntDelay to a value other than 0, adapters may hang (stop transmitting) under certain network conditions. If this occurs a NETDEV WATCHDOG message is logged in the system event log. In addition, the controller is automatically reset, restoring the network connection. To eliminate the potential for the hang ensure that RxIntDelay is set to 0.

<a id="rst-rxabsintdelay"></a>

### RxAbsIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 8

This value, in units of 1.024 microseconds, limits the delay in which a receive interrupt is generated. This value ensures that an interrupt is generated after the initial packet is received within the set amount of time, which is useful only if RxIntDelay is non-zero. Proper tuning, along with RxIntDelay, may improve traffic throughput in specific network conditions.

<a id="rst-txintdelay"></a>

### TxIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 8

This value delays the generation of transmit interrupts in units of 1.024 microseconds. Transmit interrupt reduction can improve CPU efficiency if properly tuned for specific network traffic. If the system is reporting dropped transmits, this value may be set too high causing the driver to run out of available transmit descriptors.

<a id="rst-txabsintdelay"></a>

### TxAbsIntDelay

**Valid Range:** 0-65535 (0=off)

**Default Value:** 32

This value, in units of 1.024 microseconds, limits the delay in which a transmit interrupt is generated. It is useful only if TxIntDelay is non-zero. It ensures that an interrupt is generated after the initial Packet is sent on the wire within the set amount of time. Proper tuning, along with TxIntDelay, may improve traffic throughput in specific network conditions.

<a id="rst-copybreak"></a>

### copybreak

**Valid Range:** 0-xxxxxxx (0=off)

**Default Value:** 256

The driver copies all packets below or equaling this size to a fresh receive buffer before handing it up the stack. This parameter differs from other parameters because it is a single (not 1,1,1 etc.) parameter applied to all driver instances and it is also available during runtime at /sys/module/e1000e/parameters/copybreak.

To use copybreak, type:



```text
modprobe e1000e.ko copybreak=128
```

<a id="rst-smartpowerdownenable"></a>

### SmartPowerDownEnable

**Valid Range:** 0,1

**Default Value:** 0 (disabled)

Allows the PHY to turn off in lower power states. The user can turn off this parameter in supported chipsets.

<a id="rst-kumeranlockloss"></a>

### KumeranLockLoss

**Valid Range:** 0,1

**Default Value:** 1 (enabled)

This workaround skips resetting the PHY at shutdown for the initial silicon releases of ICH8 systems.

<a id="rst-intmode"></a>

### IntMode

**Valid Range:** 0-2

**Default Value:** 0


<table>
<thead>
<tr>
<th>


Value

</th>
<th>


Interrupt Mode

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


Legacy

</td>
</tr>
<tr>
<td>


1

</td>
<td>


MSI

</td>
</tr>
<tr>
<td>


2

</td>
<td>


MSI-X

</td>
</tr>
</tbody>
</table>

IntMode allows load time control over the type of interrupt registered for by the driver. MSI-X is required for multiple queue support, and some kernels and combinations of kernel .config options will force a lower level of interrupt support.

This command will show different values for each type of interrupt:



```text
cat /proc/interrupts
```

<a id="rst-crcstripping"></a>

### CrcStripping

**Valid Range:** 0,1

**Default Value:** 1 (enabled)

Strip the CRC from received packets before sending up the network stack. If you have a machine with a BMC enabled but cannot receive IPMI traffic after loading or enabling the driver, try disabling this feature.

<a id="rst-writeprotectnvm"></a>

### WriteProtectNVM

**Valid Range:** 0,1

**Default Value:** 1 (enabled)

If set to 1, configure the hardware to ignore all write/erase cycles to the GbE region in the ICHx NVM (in order to prevent accidental corruption of the NVM). This feature can be disabled by setting the parameter to 0 during initial driver load.

NOTE: The machine must be power cycled (full off/on) when enabling NVM writes via setting the parameter to zero. Once the NVM has been locked (via the parameter at 1 when the driver loads) it cannot be unlocked except via power cycle.

<a id="rst-debug"></a>

### Debug

**Valid Range:** 0-16 (0=none,...,16=all)

**Default Value:** 0

This parameter adjusts the level of debug messages displayed in the system logs.

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;x&gt; is the interface number:



```text
ifconfig eth<x> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
ip link set mtu 9000 dev eth<x>
ip link set up dev eth<x>
```

This setting is not saved across reboots. The setting change can be made permanent by adding 'MTU=9000' to the file:

- For RHEL: /etc/sysconfig/network-scripts/ifcfg-eth&lt;x&gt;

- For SLES: /etc/sysconfig/network/&lt;config_file&gt;

NOTE: The maximum MTU setting for Jumbo Frames is 8996. This value coincides with the maximum Jumbo Frames size of 9018 bytes.

NOTE: Using Jumbo frames at 10 or 100 Mbps is not supported and may result in poor performance or loss of link.

NOTE: The following adapters limit Jumbo Frames sized packets to a maximum of 4088 bytes:

> - Intel(R) 82578DM Gigabit Network Connection
>
> - Intel(R) 82577LM Gigabit Network Connection

The following adapters do not support Jumbo Frames:

> - Intel(R) PRO/1000 Gigabit Server Adapter
>
> - Intel(R) PRO/1000 PM Network Connection
>
> - Intel(R) 82562G 10/100 Network Connection
>
> - Intel(R) 82562G-2 10/100 Network Connection
>
> - Intel(R) 82562GT 10/100 Network Connection
>
> - Intel(R) 82562GT-2 10/100 Network Connection
>
> - Intel(R) 82562V 10/100 Network Connection
>
> - Intel(R) 82562V-2 10/100 Network Connection
>
> - Intel(R) 82566DC Gigabit Network Connection
>
> - Intel(R) 82566DC-2 Gigabit Network Connection
>
> - Intel(R) 82566DM Gigabit Network Connection
>
> - Intel(R) 82566MC Gigabit Network Connection
>
> - Intel(R) 82566MM Gigabit Network Connection
>
> - Intel(R) 82567V-3 Gigabit Network Connection
>
> - Intel(R) 82577LC Gigabit Network Connection
>
> - Intel(R) 82578DC Gigabit Network Connection

NOTE: Jumbo Frames cannot be configured on an 82579-based Network device if MACSec is enabled on the system.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at:

[https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

NOTE: When validating enable/disable tests on some parts (for example, 82578), it is necessary to add a few seconds between tests when working with ethtool.

<a id="rst-speed-and-duplex-configuration"></a>

### Speed and Duplex Configuration

In addressing speed and duplex configuration issues, you need to distinguish between copper-based adapters and fiber-based adapters.

In the default mode, an Intel(R) Ethernet Network Adapter using copper connections will attempt to auto-negotiate with its link partner to determine the best setting. If the adapter cannot establish link with the link partner using auto-negotiation, you may need to manually configure the adapter and link partner to identical settings to establish link and pass packets. This should only be needed when attempting to link with an older switch that does not support auto-negotiation or one that has been forced to a specific speed or duplex mode. Your link partner must match the setting you choose. 1 Gbps speeds and higher cannot be forced. Use the autonegotiation advertising setting to manually set devices for 1 Gbps and higher.

Speed, duplex, and autonegotiation advertising are configured through the ethtool utility.

Caution: Only experienced network administrators should force speed and duplex or change autonegotiation advertising manually. The settings at the switch must always match the adapter settings. Adapter performance may suffer or your adapter may not operate if you configure the adapter differently from your switch.

An Intel(R) Ethernet Network Adapter using fiber-based connections, however, will not attempt to auto-negotiate with its link partner since those adapters operate only in full duplex and only at their native speed.

<a id="rst-enabling-wake-on-lan-wol"></a>

### Enabling Wake on LAN (WoL)

WoL is configured through the ethtool utility.

WoL will be enabled on the system during the next shut down or reboot. For this driver version, in order to enable WoL, the e1000e driver must be loaded prior to shutting down or suspending the system.

NOTE: Wake on LAN is only supported on port A for the following devices: - Intel(R) PRO/1000 PT Dual Port Network Connection - Intel(R) PRO/1000 PT Dual Port Server Connection - Intel(R) PRO/1000 PT Dual Port Server Adapter - Intel(R) PRO/1000 PF Dual Port Server Adapter - Intel(R) PRO/1000 PT Quad Port Server Adapter - Intel(R) Gigabit PT Quad Port Server ExpressModule

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for Intel(R) Ethernet Multi-host Controller

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> August 20, 2018 Copyright(c) 2015-2018 Intel Corporation.

<a id="rst-linux-base-driver-for-intel-r-ethernet-multi-host-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

August 20, 2018 Copyright(c) 2015-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Additional Configurations

- Performance Tuning

- Known Issues

- Support

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver in this release is compatible with devices based on the Intel(R) Ethernet Multi-host Controller.

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-flow-control"></a>

### Flow Control

The Intel(R) Ethernet Switch Host Interface Driver does not support Flow Control. It will not send pause frames. This may result in dropped frames.

<a id="rst-virtual-functions-vfs"></a>

### Virtual Functions (VFs)

Use sysfs to enable VFs. Valid Range: 0-64

For example:



```text
echo $num_vf_enabled > /sys/class/net/$dev/device/sriov_numvfs //enable VFs
echo 0 > /sys/class/net/$dev/device/sriov_numvfs //disable VFs
```

NOTE: Neither the device nor the driver control how VFs are mapped into config space. Bus layout will vary by operating system. On operating systems that support it, you can check sysfs to find the mapping.

NOTE: When SR-IOV mode is enabled, hardware VLAN filtering and VLAN tag stripping/insertion will remain enabled. Please remove the old VLAN filter before the new VLAN filter is added. For example:



```text
ip link set eth0 vf 0 vlan 100      // set vlan 100 for VF 0
ip link set eth0 vf 0 vlan 0        // Delete vlan 100
ip link set eth0 vf 0 vlan 200      // set a new vlan 200 for VF 0
```

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;x&gt; is the interface number:



```text
ifconfig eth<x> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
ip link set mtu 9000 dev eth<x>
ip link set up dev eth<x>
```

This setting is not saved across reboots. The setting change can be made permanent by adding 'MTU=9000' to the file:

- For RHEL: /etc/sysconfig/network-scripts/ifcfg-eth&lt;x&gt;

- For SLES: /etc/sysconfig/network/&lt;config_file&gt;

NOTE: The maximum MTU setting for Jumbo Frames is 15342. This value coincides with the maximum Jumbo Frames size of 15364 bytes.

NOTE: This driver will attempt to use multiple page sized buffers to receive each jumbo packet. This should help to avoid buffer starvation issues when allocating receive packets.

<a id="rst-generic-receive-offload-aka-gro"></a>

### Generic Receive Offload, aka GRO

The driver supports the in-kernel software implementation of GRO. GRO has shown that by coalescing Rx traffic into larger chunks of data, CPU utilization can be significantly reduced when under large Rx load. GRO is an evolution of the previously-used LRO interface. GRO is able to coalesce other protocols besides TCP. It's also safe to use with configurations that are problematic for LRO, namely bridging and iSCSI.

<a id="rst-supported-ethtool-commands-and-options-for-filtering"></a>

### Supported ethtool Commands and Options for Filtering

- **-n --show-nfc**

  Retrieves the receive network flow classification configurations.

- **rx-flow-hash tcp4\|udp4\|ah4\|esp4\|sctp4\|tcp6\|udp6\|ah6\|esp6\|sctp6**

  Retrieves the hash options for the specified network traffic type.

- **-N --config-nfc**

  Configures the receive network flow classification.

- **rx-flow-hash tcp4\|udp4\|ah4\|esp4\|sctp4\|tcp6\|udp6\|ah6\|esp6\|sctp6 m\|v\|t\|s\|d\|f\|n\|r**

  Configures the hash options for the specified network traffic type.

- udp4: UDP over IPv4

- udp6: UDP over IPv6

- f Hash on bytes 0 and 1 of the Layer 4 header of the rx packet.

- n Hash on bytes 2 and 3 of the Layer 4 header of the rx packet.

<a id="rst-known-issues-troubleshooting"></a>

## Known Issues/Troubleshooting

<a id="rst-enabling-sr-iov-in-a-64-bit-microsoft-windows-server-2012-r2-guest-os-under-linux-kvm"></a>

### Enabling SR-IOV in a 64-bit Microsoft Windows Server 2012/R2 guest OS under Linux KVM

KVM Hypervisor/VMM supports direct assignment of a PCIe device to a VM. This includes traditional PCIe devices, as well as SR-IOV-capable devices based on the Intel Ethernet Controller XL710.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for the Intel(R) Ethernet Controller 700 Series

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel 40 Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-linux-base-driver-for-the-intel-r-ethernet-controller-700-series"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel 40 Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Overview

- Identifying Your Adapter

- Intel(R) Ethernet Flow Director

- Additional Configurations

- Known Issues

- Support

Driver information can be obtained using ethtool, lspci, and ifconfig. Instructions on updating ethtool can be found in the section Additional Configurations later in this document.

For questions related to hardware requirements, refer to the documentation supplied with your Intel adapter. All hardware requirements listed apply to use with Linux.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver is compatible with devices based on the following:

> - Intel(R) Ethernet Controller X710
>
> - Intel(R) Ethernet Controller XL710
>
> - Intel(R) Ethernet Network Connection X722
>
> - Intel(R) Ethernet Controller XXV710

For the best performance, make sure the latest NVM/FW is installed on your device.

For information on how to identify your adapter, and for the latest NVM/FW images and Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-sfp-and-qsfp-devices"></a>

### SFP+ and QSFP+ Devices

For information about supported media, refer to this document: [https://www.intel.com/content/dam/www/public/us/en/documents/release-notes/xl710-ethernet-controller-feature-matrix.pdf](<https://www.intel.com/content/dam/www/public/us/en/documents/release-notes/xl710-ethernet-controller-feature-matrix.pdf>)

NOTE: Some adapters based on the Intel(R) Ethernet Controller 700 Series only support Intel Ethernet Optics modules. On these adapters, other modules are not supported and will not function.  In all cases Intel recommends using Intel Ethernet Optics; other modules may function but are not validated by Intel. Contact Intel for supported media types.

NOTE: For connections based on Intel(R) Ethernet Controller 700 Series, support is dependent on your system board. Please see your vendor for details.

NOTE: In systems that do not have adequate airflow to cool the adapter and optical modules, you must use high temperature optical modules.

<a id="rst-virtual-functions-vfs"></a>

### Virtual Functions (VFs)

Use sysfs to enable VFs. For example:



```text
#echo $num_vf_enabled > /sys/class/net/$dev/device/sriov_numvfs #enable VFs
#echo 0 > /sys/class/net/$dev/device/sriov_numvfs #disable VFs
```

For example, the following instructions will configure PF eth0 and the first VF on VLAN 10:



```text
$ ip link set dev eth0 vf 0 vlan 10
```

<a id="rst-vlan-tag-packet-steering"></a>

### VLAN Tag Packet Steering

Allows you to send all packets with a specific VLAN tag to a particular SR-IOV virtual function (VF). Further, this feature allows you to designate a particular VF as trusted, and allows that trusted VF to request selective promiscuous mode on the Physical Function (PF).

To set a VF as trusted or untrusted, enter the following command in the Hypervisor:



```text
# ip link set dev eth0 vf 1 trust [on|off]
```

Once the VF is designated as trusted, use the following commands in the VM to set the VF to promiscuous mode.



```text
For promiscuous all:
#ip link set eth2 promisc on
Where eth2 is a VF interface in the VM

For promiscuous Multicast:
#ip link set eth2 allmulticast on
Where eth2 is a VF interface in the VM
```

NOTE: By default, the ethtool priv-flag vf-true-promisc-support is set to "off",meaning that promiscuous mode for the VF will be limited. To set the promiscuous mode for the VF to true promiscuous and allow the VF to see all ingress traffic, use the following command:



```text
#ethtool -set-priv-flags p261p1 vf-true-promisc-support on
```

The vf-true-promisc-support priv-flag does not enable promiscuous mode; rather, it designates which type of promiscuous mode (limited or true) you will get when you enable promiscuous mode using the ip link commands above. Note that this is a global setting that affects the entire device. However,the vf-true-promisc-support priv-flag is only exposed to the first PF of the device. The PF remains in limited promiscuous mode (unless it is in MFP mode) regardless of the vf-true-promisc-support setting.

Now add a VLAN interface on the VF interface:



```text
#ip link add link eth2 name eth2.100 type vlan id 100
```

Note that the order in which you set the VF to promiscuous mode and add the VLAN interface does not matter (you can do either first). The end result in this example is that the VF will get all traffic that is tagged with VLAN 100.

<a id="rst-intel-r-ethernet-flow-director"></a>

### Intel(R) Ethernet Flow Director

The Intel Ethernet Flow Director performs the following tasks:

- Directs receive packets according to their flows to different queues.

- Enables tight control on routing a flow in the platform.

- Matches flows and CPU cores for flow affinity.

- Supports multiple parameters for flexible flow classification and load balancing (in SFP mode only).

NOTE: The Linux i40e driver supports the following flow types: IPv4, TCPv4, and UDPv4. For a given flow type, it supports valid combinations of IP addresses (source or destination) and UDP/TCP ports (source and destination). For example, you can supply only a source IP address, a source IP address and a destination port, or any combination of one or more of these four parameters.

NOTE: The Linux i40e driver allows you to filter traffic based on a user-defined flexible two-byte pattern and offset by using the ethtool user-def and mask fields. Only L3 and L4 flow types are supported for user-defined flexible filters. For a given flow type, you must clear all Intel Ethernet Flow Director filters before changing the input set (for that flow type).

To enable or disable the Intel Ethernet Flow Director:



```text
# ethtool -K ethX ntuple <on|off>
```

When disabling ntuple filters, all the user programmed filters are flushed from the driver cache and hardware. All needed filters must be re-added when ntuple is re-enabled.

To add a filter that directs packet to queue 2, use -U or -N switch:



```text
# ethtool -N ethX flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 src-port 2000 dst-port 2001 action 2 [loc 1]
```

To set a filter using only the source and destination IP address:



```text
# ethtool -N ethX flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 action 2 [loc 1]
```

To see the list of filters currently present:



```text
# ethtool <-u|-n> ethX
```

<a id="rst-application-targeted-routing-atr-perfect-filters"></a>

### Application Targeted Routing (ATR) Perfect Filters

ATR is enabled by default when the kernel is in multiple transmit queue mode. An ATR Intel Ethernet Flow Director filter rule is added when a TCP-IP flow starts and is deleted when the flow ends. When a TCP-IP Intel Ethernet Flow Director rule is added from ethtool (Sideband filter), ATR is turned off by the driver. To re-enable ATR, the sideband can be disabled with the ethtool -K option. For example:



```text
ethtool -K [adapter] ntuple [off|on]
```

If sideband is re-enabled after ATR is re-enabled, ATR remains enabled until a TCP-IP flow is added. When all TCP-IP sideband rules are deleted, ATR is automatically re-enabled.

Packets that match the ATR rules are counted in fdir\_atr\_match stats in ethtool, which also can be used to verify whether ATR rules still exist.

<a id="rst-sideband-perfect-filters"></a>

### Sideband Perfect Filters

Sideband Perfect Filters are used to direct traffic that matches specified characteristics. They are enabled through ethtool's ntuple interface. To add a new filter use the following command:



```text
ethtool -U <device> flow-type <type> src-ip <ip> dst-ip <ip> src-port <port> \
dst-port <port> action <queue>
```

- **Where:**

  &lt;device&gt; - the ethernet device to program &lt;type&gt; - can be ip4, tcp4, udp4, or sctp4 &lt;ip&gt; - the ip address to match on &lt;port&gt; - the port number to match on &lt;queue&gt; - the queue to direct traffic towards (-1 discards matching traffic)

Use the following command to display all of the active filters:



```text
ethtool -u <device>
```

Use the following command to delete a filter:



```text
ethtool -U <device> delete <N>
```

Where &lt;N&gt; is the filter id displayed when printing all the active filters, and may also have been specified using "loc &lt;N&gt;" when adding the filter.

The following example matches TCP traffic sent from 192.168.0.1, port 5300, directed to 192.168.0.5, port 80, and sends it to queue 7:



```text
ethtool -U enp130s0 flow-type tcp4 src-ip 192.168.0.1 dst-ip 192.168.0.5 \
src-port 5300 dst-port 80 action 7
```

For each flow-type, the programmed filters must all have the same matching input set. For example, issuing the following two commands is acceptable:



```text
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.5 src-port 55 action 10
```

Issuing the next two commands, however, is not acceptable, since the first specifies src-ip and the second specifies dst-ip:



```text
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
ethtool -U enp130s0 flow-type ip4 dst-ip 192.168.0.5 src-port 55 action 10
```

The second command will fail with an error. You may program multiple filters with the same fields, using different values, but, on one device, you may not program two tcp4 filters with different matching fields.

Matching on a sub-portion of a field is not supported by the i40e driver, thus partial mask fields are not supported.

The driver also supports matching user-defined data within the packet payload. This flexible data is specified using the "user-def" field of the ethtool command in the following way:


<table>
<tbody>
<tr>
<td>


31    28    24    20    16

</td>
<td>


15    12    8    4    0

</td>
</tr>
<tr>
<td>


offset into packet payload

</td>
<td>


2 bytes of flexible data

</td>
</tr>
</tbody>
</table>

For example,



```text
... user-def 0x4FFFF ...
```

tells the filter to look 4 bytes into the payload and match that value against 0xFFFF. The offset is based on the beginning of the payload, and not the beginning of the packet. Thus



```text
flow-type tcp4 ... user-def 0x8BEAF ...
```

would match TCP/IPv4 packets which have the value 0xBEAF 8 bytes into the TCP/IPv4 payload.

Note that ICMP headers are parsed as 4 bytes of header and 4 bytes of payload. Thus to match the first byte of the payload, you must actually add 4 bytes to the offset. Also note that ip4 filters match both ICMP frames as well as raw (unknown) ip4 frames, where the payload will be the L3 payload of the IP4 frame.

The maximum offset is 64. The hardware will only read up to 64 bytes of data from the payload. The offset must be even because the flexible data is 2 bytes long and must be aligned to byte 0 of the packet payload.

The user-defined flexible offset is also considered part of the input set and cannot be programmed separately for multiple filters of the same type. However, the flexible data is not part of the input set and multiple filters may use the same offset but match against different data.

To create filters that direct traffic to a specific Virtual Function, use the "action" parameter. Specify the action as a 64 bit value, where the lower 32 bits represents the queue number, while the next 8 bits represent which VF. Note that 0 is the PF, so the VF identifier is offset by 1. For example:



```text
... action 0x800000002 ...
```

specifies to direct traffic to Virtual Function 7 (8 minus 1) into queue 2 of that VF.

Note that these filters will not break internal routing rules, and will not route traffic that otherwise would not have been sent to the specified Virtual Function.

<a id="rst-setting-the-link-down-on-close-private-flag"></a>

### Setting the link-down-on-close Private Flag

When the link-down-on-close private flag is set to "on", the port's link will go down when the interface is brought down using the ifconfig ethX down command.

Use ethtool to view and set link-down-on-close, as follows:



```text
ethtool --show-priv-flags ethX
ethtool --set-priv-flags ethX link-down-on-close [on|off]
```

<a id="rst-setting-the-mdd-auto-reset-vf-private-flag"></a>

### Setting the mdd-auto-reset-vf Private Flag

When the mdd-auto-reset-vf private flag is set to "on", the problematic VF will be automatically reset if a malformed descriptor is detected. If the flag is set to "off", the problematic VF will be disabled.

Use ethtool to view and set mdd-auto-reset-vf, as follows:



```text
ethtool --show-priv-flags ethX
ethtool --set-priv-flags ethX mdd-auto-reset-vf [on|off]
```

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

Link messages will not be displayed to the console if the distribution is restricting system messages. In order to see network driver link messages on your console, set dmesg to eight by entering the following:



```text
dmesg -n 8
```

NOTE: This setting is not saved across reboots.

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;x&gt; is the interface number:



```text
ifconfig eth<x> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
ip link set mtu 9000 dev eth<x>
ip link set up dev eth<x>
```

This setting is not saved across reboots. The setting change can be made permanent by adding 'MTU=9000' to the file:



```text
/etc/sysconfig/network-scripts/ifcfg-eth<x> // for RHEL
/etc/sysconfig/network/<config_file> // for SLES
```

NOTE: The maximum MTU setting for Jumbo Frames is 9702. This value coincides with the maximum Jumbo Frames size of 9728 bytes.

NOTE: This driver will attempt to use multiple page sized buffers to receive each jumbo packet. This should help to avoid buffer starvation issues when allocating receive packets.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at: [https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-supported-ethtool-commands-and-options-for-filtering"></a>

### Supported ethtool Commands and Options for Filtering

- **-n --show-nfc**

  Retrieves the receive network flow classification configurations.

- **rx-flow-hash tcp4\|udp4\|ah4\|esp4\|sctp4\|tcp6\|udp6\|ah6\|esp6\|sctp6**

  Retrieves the hash options for the specified network traffic type.

- **-N --config-nfc**

  Configures the receive network flow classification.

- **rx-flow-hash tcp4\|udp4\|ah4\|esp4\|sctp4\|tcp6\|udp6\|ah6\|esp6\|sctp6 m\|v\|t\|s\|d\|f\|n\|r...**

  Configures the hash options for the specified network traffic type.

udp4 UDP over IPv4 udp6 UDP over IPv6

f Hash on bytes 0 and 1 of the Layer 4 header of the Rx packet. n Hash on bytes 2 and 3 of the Layer 4 header of the Rx packet.

<a id="rst-speed-and-duplex-configuration"></a>

### Speed and Duplex Configuration

In addressing speed and duplex configuration issues, you need to distinguish between copper-based adapters and fiber-based adapters.

In the default mode, an Intel(R) Ethernet Network Adapter using copper connections will attempt to auto-negotiate with its link partner to determine the best setting. If the adapter cannot establish link with the link partner using auto-negotiation, you may need to manually configure the adapter and link partner to identical settings to establish link and pass packets. This should only be needed when attempting to link with an older switch that does not support auto-negotiation or one that has been forced to a specific speed or duplex mode. Your link partner must match the setting you choose. 1 Gbps speeds and higher cannot be forced. Use the autonegotiation advertising setting to manually set devices for 1 Gbps and higher.

NOTE: You cannot set the speed for devices based on the Intel(R) Ethernet Network Adapter XXV710 based devices.

Speed, duplex, and autonegotiation advertising are configured through the ethtool utility.

Caution: Only experienced network administrators should force speed and duplex or change autonegotiation advertising manually. The settings at the switch must always match the adapter settings. Adapter performance may suffer or your adapter may not operate if you configure the adapter differently from your switch.

An Intel(R) Ethernet Network Adapter using fiber-based connections, however, will not attempt to auto-negotiate with its link partner since those adapters operate only in full duplex and only at their native speed.

<a id="rst-napi"></a>

### NAPI

NAPI (Rx polling mode) is supported in the i40e driver.

See [Documentation/networking/napi.rst](<#rst-napi>) for more information.

<a id="rst-flow-control"></a>

### Flow Control

Ethernet Flow Control (IEEE 802.3x) can be configured with ethtool to enable receiving and transmitting pause frames for i40e. When transmit is enabled, pause frames are generated when the receive packet buffer crosses a predefined threshold. When receive is enabled, the transmit unit will halt for the time delay specified when a pause frame is received.

NOTE: You must have a flow control capable link partner.

Flow Control is on by default.

Use ethtool to change the flow control settings.

To enable or disable Rx or Tx Flow Control:



```text
ethtool -A eth? rx <on|off> tx <on|off>
```

Note: This command only enables or disables Flow Control if auto-negotiation is disabled. If auto-negotiation is enabled, this command changes the parameters used for auto-negotiation with the link partner.

To enable or disable auto-negotiation:



```text
ethtool -s eth? autoneg <on|off>
```

Note: Flow Control auto-negotiation is part of link auto-negotiation. Depending on your device, you may not be able to change the auto-negotiation setting.

<a id="rst-rss-hash-flow"></a>

### RSS Hash Flow

Allows you to set the hash bytes per flow type and any combination of one or more options for Receive Side Scaling (RSS) hash byte configuration.



```text
# ethtool -N <dev> rx-flow-hash <type> <option>
```

- **Where &lt;type&gt; is:**

  tcp4  signifying TCP over IPv4 udp4  signifying UDP over IPv4 tcp6  signifying TCP over IPv6 udp6  signifying UDP over IPv6

- **And &lt;option&gt; is one or more of:**

  s     Hash on the IP source address of the Rx packet. d     Hash on the IP destination address of the Rx packet. f     Hash on bytes 0 and 1 of the Layer 4 header of the Rx packet. n     Hash on bytes 2 and 3 of the Layer 4 header of the Rx packet.

<a id="rst-mac-and-vlan-anti-spoofing-feature"></a>

### MAC and VLAN anti-spoofing feature

When a malicious driver attempts to send a spoofed packet, it is dropped by the hardware and not transmitted. NOTE: This feature can be disabled for a specific Virtual Function (VF):



```text
ip link set <pf dev> vf <vf id> spoofchk {off|on}
```

<a id="rst-ieee-1588-precision-time-protocol-ptp-hardware-clock-phc"></a>

### IEEE 1588 Precision Time Protocol (PTP) Hardware Clock (PHC)

Precision Time Protocol (PTP) is used to synchronize clocks in a computer network. PTP support varies among Intel devices that support this driver. Use "ethtool -T &lt;netdev name&gt;" to get a definitive list of PTP capabilities supported by the device.

<a id="rst-ieee-802-1ad-qinq-support"></a>

### IEEE 802.1ad (QinQ) Support

The IEEE 802.1ad standard, informally known as QinQ, allows for multiple VLAN IDs within a single Ethernet frame. VLAN IDs are sometimes referred to as "tags," and multiple VLAN IDs are thus referred to as a "tag stack." Tag stacks allow L2 tunneling and the ability to segregate traffic within a particular VLAN ID, among other uses.

The following are examples of how to configure 802.1ad (QinQ):



```text
ip link add link eth0 eth0.24 type vlan proto 802.1ad id 24
ip link add link eth0.24 eth0.24.371 type vlan proto 802.1Q id 371
```

Where "24" and "371" are example VLAN IDs.

- **NOTES:**

  Receive checksum offloads, cloud filters, and VLAN acceleration are not supported for 802.1ad (QinQ) packets.

<a id="rst-vxlan-and-geneve-overlay-hw-offloading"></a>

### VXLAN and GENEVE Overlay HW Offloading

Virtual Extensible LAN (VXLAN) allows you to extend an L2 network over an L3 network, which may be useful in a virtualized or cloud environment. Some Intel(R) Ethernet Network devices perform VXLAN processing, offloading it from the operating system. This reduces CPU utilization.

VXLAN offloading is controlled by the Tx and Rx checksum offload options provided by ethtool. That is, if Tx checksum offload is enabled, and the adapter has the capability, VXLAN offloading is also enabled.

Support for VXLAN and GENEVE HW offloading is dependent on kernel support of the HW offloading features.

<a id="rst-multiple-functions-per-port"></a>

### Multiple Functions per Port

Some adapters based on the Intel Ethernet Controller X710/XL710 support multiple functions on a single physical port. Configure these functions through the System Setup/BIOS.

Minimum TX Bandwidth is the guaranteed minimum data transmission bandwidth, as a percentage of the full physical port link speed, that the partition will receive. The bandwidth the partition is awarded will never fall below the level you specify.

The range for the minimum bandwidth values is: 1 to ((100 minus \# of partitions on the physical port) plus 1) For example, if a physical port has 4 partitions, the range would be: 1 to ((100 - 4) + 1 = 97)

The Maximum Bandwidth percentage represents the maximum transmit bandwidth allocated to the partition as a percentage of the full physical port link speed. The accepted range of values is 1-100. The value is used as a limiter, should you chose that any one particular function not be able to consume 100% of a port's bandwidth (should it be available). The sum of all the values for Maximum Bandwidth is not restricted, because no more than 100% of a port's bandwidth can ever be used.

NOTE: X710/XXV710 devices fail to enable Max VFs (64) when Multiple Functions per Port (MFP) and SR-IOV are enabled. An error from i40e is logged that says "add vsi failed for VF N, aq\_err 16". To workaround the issue, enable less than 64 virtual functions (VFs).

<a id="rst-data-center-bridging-dcb"></a>

### Data Center Bridging (DCB)

DCB is a configuration Quality of Service implementation in hardware. It uses the VLAN priority tag (802.1p) to filter traffic. That means that there are 8 different priorities that traffic can be filtered into. It also enables priority flow control (802.1Qbb) which can limit or eliminate the number of dropped packets during network stress. Bandwidth can be allocated to each of these priorities, which is enforced at the hardware level (802.1Qaz).

Adapter firmware implements LLDP and DCBX protocol agents as per 802.1AB and 802.1Qaz respectively. The firmware based DCBX agent runs in willing mode only and can accept settings from a DCBX capable peer. Software configuration of DCBX parameters via dcbtool/lldptool are not supported.

NOTE: Firmware LLDP can be disabled by setting the private flag disable-fw-lldp.

The i40e driver implements the DCB netlink interface layer to allow user-space to communicate with the driver and query DCB configuration for the port.

NOTE: The kernel assumes that TC0 is available, and will disable Priority Flow Control (PFC) on the device if TC0 is not available. To fix this, ensure TC0 is enabled when setting up DCB on your switch.

<a id="rst-interrupt-rate-limiting"></a>

### Interrupt Rate Limiting

**Valid Range:** 0-235 (0=no limit)

The Intel(R) Ethernet Controller XL710 family supports an interrupt rate limiting mechanism. The user can control, via ethtool, the number of microseconds between interrupts.

Syntax:



```text
# ethtool -C ethX rx-usecs-high N
```

The range of 0-235 microseconds provides an effective range of 4,310 to 250,000 interrupts per second. The value of rx-usecs-high can be set independently of rx-usecs and tx-usecs in the same ethtool command, and is also independent of the adaptive interrupt moderation algorithm. The underlying hardware supports granularity in 4-microsecond intervals, so adjacent values may result in the same interrupt rate.

One possible use case is the following:



```text
# ethtool -C ethX adaptive-rx off adaptive-tx off rx-usecs-high 20 rx-usecs \
  5 tx-usecs 5
```

The above command would disable adaptive interrupt moderation, and allow a maximum of 5 microseconds before indicating a receive or transmit was complete. However, instead of resulting in as many as 200,000 interrupts per second, it limits total interrupts per second to 50,000 via the rx-usecs-high parameter.

<a id="rst-performance-optimization"></a>

## Performance Optimization

Driver defaults are meant to fit a wide variety of workloads, but if further optimization is required we recommend experimenting with the following settings.

NOTE: For better performance when processing small (64B) frame sizes, try enabling Hyper threading in the BIOS in order to increase the number of logical cores in the system and subsequently increase the number of queues available to the adapter.

<a id="rst-virtualized-environments"></a>

### Virtualized Environments

1\. Disable XPS on both ends by using the included virt\_perf\_default script or by running the following command as root:



```text
for file in `ls /sys/class/net/<ethX>/queues/tx-*/xps_cpus`;
do echo 0 > $file; done
```

2\. Using the appropriate mechanism (vcpupin) in the vm, pin the cpu's to individual lcpu's, making sure to use a set of cpu's included in the device's local\_cpulist: /sys/class/net/&lt;ethX&gt;/device/local\_cpulist.

3\. Configure as many Rx/Tx queues in the VM as available. Do not rely on the default setting of 1.

<a id="rst-non-virtualized-environments"></a>

### Non-virtualized Environments

Pin the adapter's IRQs to specific cores by disabling the irqbalance service and using the included set\_irq\_affinity script. Please see the script's help text for further options.

- The following settings will distribute the IRQs across all the cores evenly:



  ```text
  # scripts/set_irq_affinity -x all <interface1> , [ <interface2>, ... ]
  ```

- The following settings will distribute the IRQs across all the cores that are local to the adapter (same NUMA node):



  ```text
  # scripts/set_irq_affinity -x local <interface1> ,[ <interface2>, ... ]
  ```

For very CPU intensive workloads, we recommend pinning the IRQs to all cores.

For IP Forwarding: Disable Adaptive ITR and lower Rx and Tx interrupts per queue using ethtool.

- Setting rx-usecs and tx-usecs to 125 will limit interrupts to about 8000 interrupts per second per queue.



```text
# ethtool -C <interface> adaptive-rx off adaptive-tx off rx-usecs 125 \
  tx-usecs 125
```

For lower CPU utilization: Disable Adaptive ITR and lower Rx and Tx interrupts per queue using ethtool.

- Setting rx-usecs and tx-usecs to 250 will limit interrupts to about 4000 interrupts per second per queue.



```text
# ethtool -C <interface> adaptive-rx off adaptive-tx off rx-usecs 250 \
  tx-usecs 250
```

For lower latency: Disable Adaptive ITR and ITR by setting Rx and Tx to 0 using ethtool.



```text
# ethtool -C <interface> adaptive-rx off adaptive-tx off rx-usecs 0 \
  tx-usecs 0
```

<a id="rst-application-device-queues-adq"></a>

### Application Device Queues (ADq)

Application Device Queues (ADq) allows you to dedicate one or more queues to a specific application. This can reduce latency for the specified application, and allow Tx traffic to be rate limited per application. Follow the steps below to set ADq.

1\. Create traffic classes (TCs). Maximum of 8 TCs can be created per interface. The shaper bw\_rlimit parameter is optional.

Example: Sets up two tcs, tc0 and tc1, with 16 queues each and max tx rate set to 1Gbit for tc0 and 3Gbit for tc1.



```text
# tc qdisc add dev <interface> root mqprio num_tc 2 map 0 0 0 0 1 1 1 1
queues 16@0 16@16 hw 1 mode channel shaper bw_rlimit min_rate 1Gbit 2Gbit
max_rate 1Gbit 3Gbit
```

map: priority mapping for up to 16 priorities to tcs (e.g. map 0 0 0 0 1 1 1 1 sets priorities 0-3 to use tc0 and 4-7 to use tc1)

queues: for each tc, &lt;num queues&gt;@&lt;offset&gt; (e.g. queues 16@0 [16@16](<mailto:16@16>) assigns 16 queues to tc0 at offset 0 and 16 queues to tc1 at offset 16. Max total number of queues for all tcs is 64 or number of cores, whichever is lower.)

hw 1 mode channel: ‘channel’ with ‘hw’ set to 1 is a new new hardware offload mode in mqprio that makes full use of the mqprio options, the TCs, the queue configurations, and the QoS parameters.

shaper bw\_rlimit: for each tc, sets minimum and maximum bandwidth rates. Totals must be equal or less than port speed.

For example: min\_rate 1Gbit 3Gbit: Verify bandwidth limit using network monitoring tools such as `ifstat` or `sar -n DEV [interval] [number of samples]`

2. Enable HW TC offload on interface:



   ```text
   # ethtool -K <interface> hw-tc-offload on
   ```

3. Apply TCs to ingress (RX) flow of interface:



   ```text
   # tc qdisc add dev <interface> ingress
   ```

- **NOTES:**

  - Run all tc commands from the iproute2 &lt;pathtoiproute2&gt;/tc/ directory.

  - ADq is not compatible with cloud filters.

  - Setting up channels via ethtool (ethtool -L) is not supported when the TCs are configured using mqprio.

  - You must have iproute2 latest version

  - NVM version 6.01 or later is required.

  - ADq cannot be enabled when any the following features are enabled: Data Center Bridging (DCB), Multiple Functions per Port (MFP), or Sideband Filters.

  - If another driver (for example, DPDK) has set cloud filters, you cannot enable ADq.

  - Tunnel filters are not supported in ADq. If encapsulated packets do arrive in non-tunnel mode, filtering will be done on the inner headers. For example, for VXLAN traffic in non-tunnel mode, PCTYPE is identified as a VXLAN encapsulated packet, outer headers are ignored. Therefore, inner headers are matched.

  - If a TC filter on a PF matches traffic over a VF (on the PF), that traffic will be routed to the appropriate queue of the PF, and will not be passed on the VF. Such traffic will end up getting dropped higher up in the TCP/IP stack as it does not match PF address data.

  - If traffic matches multiple TC filters that point to different TCs, that traffic will be duplicated and sent to all matching TC queues. The hardware switch mirrors the packet to a VSI list when multiple filters are matched.

<a id="rst-known-issues-troubleshooting"></a>

## Known Issues/Troubleshooting

NOTE: 1 Gb devices based on the Intel(R) Ethernet Network Connection X722 do not support the following features:

> - Data Center Bridging (DCB)
>
> - QOS
>
> - VMQ
>
> - SR-IOV
>
> - Task Encapsulation offload (VXLAN, NVGRE)
>
> - Energy Efficient Ethernet (EEE)
>
> - Auto-media detect

<a id="rst-unexpected-issues-when-the-device-driver-and-dpdk-share-a-device"></a>

### Unexpected Issues when the device driver and DPDK share a device

Unexpected issues may result when an i40e device is in multi driver mode and the kernel driver and DPDK driver are sharing the device. This is because access to the global NIC resources is not synchronized between multiple drivers. Any change to the global NIC configuration (writing to a global register, setting global configuration by AQ, or changing switch modes) will affect all ports and drivers on the device. Loading DPDK with the "multi-driver" module parameter may mitigate some of the issues.

<a id="rst-tc0-must-be-enabled-when-setting-up-dcb-on-a-switch"></a>

### TC0 must be enabled when setting up DCB on a switch

The kernel assumes that TC0 is available, and will disable Priority Flow Control (PFC) on the device if TC0 is not available. To fix this, ensure TC0 is enabled when setting up DCB on your switch.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for Intel(R) Ethernet Adaptive Virtual Function

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel Ethernet Adaptive Virtual Function Linux driver. Copyright(c) 2013-2018 Intel Corporation.

<a id="rst-linux-base-driver-for-intel-r-ethernet-adaptive-virtual-function"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel Ethernet Adaptive Virtual Function Linux driver. Copyright(c) 2013-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Overview

- Identifying Your Adapter

- Additional Configurations

- Known Issues/Troubleshooting

- Support

<a id="rst-overview"></a>

## Overview

This file describes the iavf Linux Base Driver. This driver was formerly called i40evf.

The iavf driver supports the below mentioned virtual function devices and can only be activated on kernels running the i40e or newer Physical Function (PF) driver compiled with CONFIG\_PCI\_IOV.  The iavf driver requires CONFIG\_PCI\_MSI to be enabled.

The guest OS loading the iavf driver must support MSI-X interrupts.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

- **The driver in this kernel is compatible with devices based on the following:**

  - Intel(R) XL710 X710 Virtual Function

  - Intel(R) X722 Virtual Function

  - Intel(R) XXV710 Virtual Function

  - Intel(R) Ethernet Adaptive Virtual Function

For the best performance, make sure the latest NVM/FW is installed on your device.

For information on how to identify your adapter, and for the latest NVM/FW images and Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

Link messages will not be displayed to the console if the distribution is restricting system messages. In order to see network driver link messages on your console, set dmesg to eight by entering the following:



```text
# dmesg -n 8
```

- **NOTE:**

  This setting is not saved across reboots.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at: [https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-setting-vlan-tag-stripping"></a>

### Setting VLAN Tag Stripping

If you have applications that require Virtual Functions (VFs) to receive packets with VLAN tags, you can disable VLAN tag stripping for the VF. The Physical Function (PF) processes requests issued from the VF to enable or disable VLAN tag stripping. Note that if the PF has assigned a VLAN to a VF, then requests from that VF to set VLAN tag stripping will be ignored.

To enable/disable VLAN tag stripping for a VF, issue the following command from inside the VM in which you are running the VF:



```text
# ethtool -K <if_name> rxvlan on/off
```

or alternatively:



```text
# ethtool --offload <if_name> rxvlan on/off
```

<a id="rst-adaptive-virtual-function"></a>

### Adaptive Virtual Function

Adaptive Virtual Function (AVF) allows the virtual function driver, or VF, to adapt to changing feature sets of the physical function driver (PF) with which it is associated. This allows system administrators to update a PF without having to update all the VFs associated with it. All AVFs have a single common device ID and branding string.

AVFs have a minimum set of features known as "base mode," but may provide additional features depending on what features are available in the PF with which the AVF is associated. The following are base mode features:

- 4 Queue Pairs (QP) and associated Configuration Status Registers (CSRs) for Tx/Rx

- i40e descriptors and ring format

- Descriptor write-back completion

- 1 control queue, with i40e descriptors, CSRs and ring format

- 5 MSI-X interrupt vectors and corresponding i40e CSRs

- 1 Interrupt Throttle Rate (ITR) index

- 1 Virtual Station Interface (VSI) per VF

- 1 Traffic Class (TC), TC0

- Receive Side Scaling (RSS) with 64 entry indirection table and key, configured through the PF

- 1 unicast MAC address reserved per VF

- 16 MAC address filters for each VF

- Stateless offloads - non-tunneled checksums

- AVF device ID

- HW mailbox is used for VF to PF communications (including on Windows)

<a id="rst-ieee-802-1ad-qinq-support"></a>

### IEEE 802.1ad (QinQ) Support

The IEEE 802.1ad standard, informally known as QinQ, allows for multiple VLAN IDs within a single Ethernet frame. VLAN IDs are sometimes referred to as "tags," and multiple VLAN IDs are thus referred to as a "tag stack." Tag stacks allow L2 tunneling and the ability to segregate traffic within a particular VLAN ID, among other uses.

The following are examples of how to configure 802.1ad (QinQ):



```text
# ip link add link eth0 eth0.24 type vlan proto 802.1ad id 24
# ip link add link eth0.24 eth0.24.371 type vlan proto 802.1Q id 371
```

Where "24" and "371" are example VLAN IDs.

- **NOTES:**

  Receive checksum offloads, cloud filters, and VLAN acceleration are not supported for 802.1ad (QinQ) packets.

<a id="rst-application-device-queues-adq"></a>

### Application Device Queues (ADq)

Application Device Queues (ADq) allows you to dedicate one or more queues to a specific application. This can reduce latency for the specified application, and allow Tx traffic to be rate limited per application. Follow the steps below to set ADq.

Requirements:

- The sch\_mqprio, act\_mirred and cls\_flower modules must be loaded

- The latest version of iproute2

- If another driver (for example, DPDK) has set cloud filters, you cannot enable ADQ

- Depending on the underlying PF device, ADQ cannot be enabled when the following features are enabled:

  - Data Center Bridging (DCB)

  - Multiple Functions per Port (MFP)

  - Sideband Filters

1\. Create traffic classes (TCs). Maximum of 8 TCs can be created per interface. The shaper bw\_rlimit parameter is optional.

Example: Sets up two tcs, tc0 and tc1, with 16 queues each and max tx rate set to 1Gbit for tc0 and 3Gbit for tc1.



```text
tc qdisc add dev <interface> root mqprio num_tc 2 map 0 0 0 0 1 1 1 1
queues 16@0 16@16 hw 1 mode channel shaper bw_rlimit min_rate 1Gbit 2Gbit
max_rate 1Gbit 3Gbit
```

map: priority mapping for up to 16 priorities to tcs (e.g. map 0 0 0 0 1 1 1 1 sets priorities 0-3 to use tc0 and 4-7 to use tc1)

queues: for each tc, &lt;num queues&gt;@&lt;offset&gt; (e.g. queues 16@0 [16@16](<mailto:16@16>) assigns 16 queues to tc0 at offset 0 and 16 queues to tc1 at offset 16. Max total number of queues for all tcs is 64 or number of cores, whichever is lower.)

hw 1 mode channel: ‘channel’ with ‘hw’ set to 1 is a new new hardware offload mode in mqprio that makes full use of the mqprio options, the TCs, the queue configurations, and the QoS parameters.

shaper bw\_rlimit: for each tc, sets minimum and maximum bandwidth rates. Totals must be equal or less than port speed.

For example: min\_rate 1Gbit 3Gbit: Verify bandwidth limit using network monitoring tools such as `ifstat` or `sar -n DEV [interval] [number of samples]`

- **NOTE:**

  Setting up channels via ethtool (ethtool -L) is not supported when the TCs are configured using mqprio.

2. Enable HW TC offload on interface:



   ```text
   # ethtool -K <interface> hw-tc-offload on
   ```

3. Apply TCs to ingress (RX) flow of interface:



   ```text
   # tc qdisc add dev <interface> ingress
   ```

- **NOTES:**

  - Run all tc commands from the iproute2 &lt;pathtoiproute2&gt;/tc/ directory

  - ADq is not compatible with cloud filters

  - Setting up channels via ethtool (ethtool -L) is not supported when the TCs are configured using mqprio

  - You must have iproute2 latest version

  - NVM version 6.01 or later is required

  - ADq cannot be enabled when any the following features are enabled: Data Center Bridging (DCB), Multiple Functions per Port (MFP), or Sideband Filters

  - If another driver (for example, DPDK) has set cloud filters, you cannot enable ADq

  - Tunnel filters are not supported in ADq. If encapsulated packets do arrive in non-tunnel mode, filtering will be done on the inner headers.  For example, for VXLAN traffic in non-tunnel mode, PCTYPE is identified as a VXLAN encapsulated packet, outer headers are ignored. Therefore, inner headers are matched.

  - If a TC filter on a PF matches traffic over a VF (on the PF), that traffic will be routed to the appropriate queue of the PF, and will not be passed on the VF. Such traffic will end up getting dropped higher up in the TCP/IP stack as it does not match PF address data.

  - If traffic matches multiple TC filters that point to different TCs, that traffic will be duplicated and sent to all matching TC queues.  The hardware switch mirrors the packet to a VSI list when multiple filters are matched.

<a id="rst-known-issues-troubleshooting"></a>

## Known Issues/Troubleshooting

<a id="rst-bonding-fails-with-vfs-bound-to-an-intel-r-ethernet-controller-700-series-device"></a>

### Bonding fails with VFs bound to an Intel(R) Ethernet Controller 700 series device

If you bind Virtual Functions (VFs) to an Intel(R) Ethernet Controller 700 series based device, the VF slaves may fail when they become the active slave. If the MAC address of the VF is set by the PF (Physical Function) of the device, when you add a slave, or change the active-backup slave, Linux bonding tries to sync the backup slave's MAC address to the same MAC address as the active slave. Linux bonding will fail at this point. This issue will not occur if the VF's MAC address is not set by the PF.

<a id="rst-traffic-is-not-being-passed-between-vm-and-client"></a>

### Traffic Is Not Being Passed Between VM and Client

You may not be able to pass traffic between a client system and a Virtual Machine (VM) running on a separate host if the Virtual Function (VF, or Virtual NIC) is not in trusted mode and spoof checking is enabled on the VF. Note that this situation can occur in any combination of client, host, and guest operating system. For information on how to set the VF to trusted mode, refer to the section "VLAN Tag Packet Steering" in this readme document. For information on setting spoof checking, refer to the section "MAC and VLAN anti-spoofing feature" in this readme document.

<a id="rst-do-not-unload-port-driver-if-vf-with-active-vm-is-bound-to-it"></a>

### Do not unload port driver if VF with active VM is bound to it

Do not unload a port's driver if a Virtual Function (VF) with an active Virtual Machine (VM) is bound to it. Doing so will cause the port to appear to hang. Once the VM shuts down, or otherwise releases the VF, the command will complete.

<a id="rst-using-four-traffic-classes-fails"></a>

### Using four traffic classes fails

Do not try to reserve more than three traffic classes in the iavf driver. Doing so will fail to set any traffic classes and will cause the driver to write errors to stdout. Use a maximum of three queues to avoid this issue.

<a id="rst-multiple-log-error-messages-on-iavf-driver-removal"></a>

### Multiple log error messages on iavf driver removal

If you have several VFs and you remove the iavf driver, several instances of the following log errors are written to the log:



```text
Unable to send opcode 2 to PF, err I40E_ERR_QUEUE_EMPTY, aq_err ok
Unable to send the message to VF 2 aq_err 12
ARQ Overflow Error detected
```

<a id="rst-virtual-machine-does-not-get-link"></a>

### Virtual machine does not get link

If the virtual machine has more than one virtual port assigned to it, and those virtual ports are bound to different physical ports, you may not get link on all of the virtual ports. The following command may work around the issue:



```text
# ethtool -r <PF>
```

Where &lt;PF&gt; is the PF interface in the host, for example: p5p1. You may need to run the command more than once to get link on all virtual ports.

<a id="rst-mac-address-of-virtual-function-changes-unexpectedly"></a>

### MAC address of Virtual Function changes unexpectedly

If a Virtual Function's MAC address is not assigned in the host, then the VF (virtual function) driver will use a random MAC address. This random MAC address may change each time the VF driver is reloaded. You can assign a static MAC address in the host machine. This static MAC address will survive a VF driver reload.

<a id="rst-driver-buffer-overflow-fix"></a>

### Driver Buffer Overflow Fix

The fix to resolve CVE-2016-8105, referenced in Intel SA-00069 [https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00069.html](<https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00069.html>) is included in this and future versions of the driver.

<a id="rst-multiple-interfaces-on-same-ethernet-broadcast-network"></a>

### Multiple Interfaces on Same Ethernet Broadcast Network

Due to the default ARP behavior on Linux, it is not possible to have one system on two IP networks in the same Ethernet broadcast domain (non-partitioned switch) behave as expected. All Ethernet interfaces will respond to IP traffic for any IP address assigned to the system. This results in unbalanced receive traffic.

If you have multiple interfaces in a server, either turn on ARP filtering by entering:



```text
# echo 1 > /proc/sys/net/ipv4/conf/all/arp_filter
```

- **NOTE:**

  This setting is not saved across reboots. The configuration change can be made permanent by adding the following line to the file /etc/sysctl.conf:



  ```text
  net.ipv4.conf.all.arp_filter = 1
  ```

Another alternative is to install the interfaces in separate broadcast domains (either in different switches or in a switch partitioned to VLANs).

<a id="rst-rx-page-allocation-errors"></a>

### Rx Page Allocation Errors

'Page allocation failure. order:0' errors may occur under stress. This is caused by the way the Linux kernel reports this stressed condition.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://support.intel.com](<https://support.intel.com>)

If an issue is identified with the released source code on the supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for the Intel(R) Ethernet Controller 800 Series

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel ice Linux driver. Copyright(c) 2018-2021 Intel Corporation.

<a id="rst-linux-base-driver-for-the-intel-r-ethernet-controller-800-series"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel ice Linux driver. Copyright(c) 2018-2021 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Overview

- Identifying Your Adapter

- Important Notes

- Additional Features &amp; Configurations

- Performance Optimization

The associated Virtual Function (VF) driver for this driver is iavf.

Driver information can be obtained using ethtool and lspci.

For questions related to hardware requirements, refer to the documentation supplied with your Intel adapter. All hardware requirements listed apply to use with Linux.

This driver supports XDP (Express Data Path) and AF_XDP zero-copy. Note that XDP is blocked for frame sizes larger than 3KB.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-important-notes"></a>

## Important Notes

<a id="rst-packet-drops-may-occur-under-receive-stress"></a>

### Packet drops may occur under receive stress

Devices based on the Intel(R) Ethernet Controller 800 Series are designed to tolerate a limited amount of system latency during PCIe and DMA transactions. If these transactions take longer than the tolerated latency, it can impact the length of time the packets are buffered in the device and associated memory, which may result in dropped packets. These packets drops typically do not have a noticeable impact on throughput and performance under standard workloads.

If these packet drops appear to affect your workload, the following may improve the situation:

1. Make sure that your system's physical memory is in a high-performance configuration, as recommended by the platform vendor. A common recommendation is for all channels to be populated with a single DIMM module.

2. In your system's BIOS/UEFI settings, select the "Performance" profile.

3. Your distribution may provide tools like "tuned," which can help tweak kernel settings to achieve better standard settings for different workloads.

<a id="rst-configuring-sr-iov-for-improved-network-security"></a>

### Configuring SR-IOV for improved network security

In a virtualized environment, on Intel(R) Ethernet Network Adapters that support SR-IOV, the virtual function (VF) may be subject to malicious behavior. Software-generated layer two frames, like IEEE 802.3x (link flow control), IEEE 802.1Qbb (priority based flow-control), and others of this type, are not expected and can throttle traffic between the host and the virtual switch, reducing performance. To resolve this issue, and to ensure isolation from unintended traffic streams, configure all SR-IOV enabled ports for VLAN tagging from the administrative interface on the PF. This configuration allows unexpected, and potentially malicious, frames to be dropped.

See "Configuring VLAN Tagging on SR-IOV Enabled Adapter Ports" later in this README for configuration instructions.

<a id="rst-do-not-unload-port-driver-if-vf-with-active-vm-is-bound-to-it"></a>

### Do not unload port driver if VF with active VM is bound to it

Do not unload a port's driver if a Virtual Function (VF) with an active Virtual Machine (VM) is bound to it. Doing so will cause the port to appear to hang. Once the VM shuts down, or otherwise releases the VF, the command will complete.

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at: [https://kernel.org/pub/software/network/ethtool/](<https://kernel.org/pub/software/network/ethtool/>)

NOTE: The rx_bytes value of ethtool does not match the rx_bytes value of Netdev, due to the 4-byte CRC being stripped by the device. The difference between the two rx_bytes values will be 4 x the number of Rx packets. For example, if Rx packets are 10 and Netdev (software statistics) displays rx_bytes as "X", then ethtool (hardware statistics) will display rx_bytes as "X+40" (4 bytes CRC x 10 packets).

<a id="rst-ethtool-reset"></a>

### ethtool reset

The driver supports 3 types of resets:

- PF reset - resets only components associated with the given PF, does not impact other PFs

- CORE reset - whole adapter is affected, reset all PFs

- GLOBAL reset - same as CORE but mac and phy components are also reinitialized

These are mapped to ethtool reset flags as follow:

- PF reset:

  \# ethtool --reset &lt;ethX&gt; irq dma filter offload

- CORE reset:

  \# ethtool --reset &lt;ethX&gt; irq-shared dma-shared filter-shared offload-shared ram-shared

- GLOBAL reset:

  \# ethtool --reset &lt;ethX&gt; irq-shared dma-shared filter-shared offload-shared mac-shared phy-shared ram-shared

In switchdev mode you can reset a VF using port representor:

> \# ethtool --reset &lt;repr&gt; irq dma filter offload

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

Link messages will not be displayed to the console if the distribution is restricting system messages. In order to see network driver link messages on your console, set dmesg to eight by entering the following:



```text
# dmesg -n 8
```

NOTE: This setting is not saved across reboots.

<a id="rst-dynamic-device-personalization"></a>

### Dynamic Device Personalization

Dynamic Device Personalization (DDP) allows you to change the packet processing pipeline of a device by applying a profile package to the device at runtime. Profiles can be used to, for example, add support for new protocols, change existing protocols, or change default settings. DDP profiles can also be rolled back without rebooting the system.

The DDP package loads during device initialization. The driver looks for `intel/ice/ddp/ice.pkg` in your firmware root (typically `/lib/firmware/` or `/lib/firmware/updates/`) and checks that it contains a valid DDP package file.

NOTE: Your distribution should likely have provided the latest DDP file, but if ice.pkg is missing, you can find it in the linux-firmware repository or from intel.com.

If the driver is unable to load the DDP package, the device will enter Safe Mode. Safe Mode disables advanced and performance features and supports only basic traffic and minimal functionality, such as updating the NVM or downloading a new driver or DDP package. Safe Mode only applies to the affected physical function and does not impact any other PFs. See the "Intel(R) Ethernet Adapters and Devices User Guide" for more details on DDP and Safe Mode.

NOTES:

- If you encounter issues with the DDP package file, you may need to download an updated driver or DDP package file. See the log messages for more information.

- The ice.pkg file is a symbolic link to the default DDP package file.

- You cannot update the DDP package if any PF drivers are already loaded. To overwrite a package, unload all PFs and then reload the driver with the new package.

- Only the first loaded PF per device can download a package for that device.

You can install specific DDP package files for different physical devices in the same system. To install a specific DDP package file:

1. Download the DDP package file you want for your device.

2. Rename the file ice-xxxxxxxxxxxxxxxx.pkg, where 'xxxxxxxxxxxxxxxx' is the unique 64-bit PCI Express device serial number (in hex) of the device you want the package downloaded on. The filename must include the complete serial number (including leading zeros) and be all lowercase. For example, if the 64-bit serial number is b887a3ffffca0568, then the file name would be ice-b887a3ffffca0568.pkg.

   To find the serial number from the PCI bus address, you can use the following command:



   ```text
   # lspci -vv -s af:00.0 | grep -i Serial
   Capabilities: [150 v1] Device Serial Number b8-87-a3-ff-ff-ca-05-68
   ```

   You can use the following command to format the serial number without the dashes:



   ```text
   # lspci -vv -s af:00.0 | grep -i Serial | awk '{print $7}' | sed s/-//g
   b887a3ffffca0568
   ```

3. Copy the renamed DDP package file to `/lib/firmware/updates/intel/ice/ddp/`. If the directory does not yet exist, create it before copying the file.

4. Unload all of the PFs on the device.

5. Reload the driver with the new package.

NOTE: The presence of a device-specific DDP package file overrides the loading of the default DDP package file (ice.pkg).

<a id="rst-intel-r-ethernet-flow-director"></a>

### Intel(R) Ethernet Flow Director

The Intel Ethernet Flow Director performs the following tasks:

- Directs receive packets according to their flows to different queues

- Enables tight control on routing a flow in the platform

- Matches flows and CPU cores for flow affinity

NOTE: This driver supports the following flow types:

- IPv4

- TCPv4

- UDPv4

- SCTPv4

- IPv6

- TCPv6

- UDPv6

- SCTPv6

Each flow type supports valid combinations of IP addresses (source or destination) and UDP/TCP/SCTP ports (source and destination). You can supply only a source IP address, a source IP address and a destination port, or any combination of one or more of these four parameters.

NOTE: This driver allows you to filter traffic based on a user-defined flexible two-byte pattern and offset by using the ethtool user-def and mask fields. Only L3 and L4 flow types are supported for user-defined flexible filters. For a given flow type, you must clear all Intel Ethernet Flow Director filters before changing the input set (for that flow type).

<a id="rst-flow-director-filters"></a>

### Flow Director Filters

Flow Director filters are used to direct traffic that matches specified characteristics. They are enabled through ethtool's ntuple interface. To enable or disable the Intel Ethernet Flow Director and these filters:



```text
# ethtool -K <ethX> ntuple <off|on>
```

NOTE: When you disable ntuple filters, all the user programmed filters are flushed from the driver cache and hardware. All needed filters must be re-added when ntuple is re-enabled.

To display all of the active filters:



```text
# ethtool -u <ethX>
```

To add a new filter:



```text
# ethtool -U <ethX> flow-type <type> src-ip <ip> [m <ip_mask>] dst-ip <ip>
[m <ip_mask>] src-port <port> [m <port_mask>] dst-port <port> [m <port_mask>]
action <queue>

Where:
  <ethX> - the Ethernet device to program
  <type> - can be ip4, tcp4, udp4, sctp4, ip6, tcp6, udp6, sctp6
  <ip> - the IP address to match on
  <ip_mask> - the IPv4 address to mask on
            NOTE: These filters use inverted masks.
  <port> - the port number to match on
  <port_mask> - the 16-bit integer for masking
            NOTE: These filters use inverted masks.
  <queue> - the queue to direct traffic toward (-1 discards the
            matched traffic)
```

To delete a filter:



```text
# ethtool -U <ethX> delete <N>

Where <N> is the filter ID displayed when printing all the active filters,
and may also have been specified using "loc <N>" when adding the filter.
```

EXAMPLES:

To add a filter that directs packet to queue 2:



```text
# ethtool -U <ethX> flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 src-port 2000 dst-port 2001 action 2 [loc 1]
```

To set a filter using only the source and destination IP address:



```text
# ethtool -U <ethX> flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 action 2 [loc 1]
```

To set a filter based on a user-defined pattern and offset:



```text
# ethtool -U <ethX> flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 user-def 0x4FFFF action 2 [loc 1]

where the value of the user-def field contains the offset (4 bytes) and
the pattern (0xffff).
```

To match TCP traffic sent from 192.168.0.1, port 5300, directed to 192.168.0.5, port 80, and then send it to queue 7:



```text
# ethtool -U enp130s0 flow-type tcp4 src-ip 192.168.0.1 dst-ip 192.168.0.5
src-port 5300 dst-port 80 action 7
```

To add a TCPv4 filter with a partial mask for a source IP subnet:



```text
# ethtool -U <ethX> flow-type tcp4 src-ip 192.168.0.0 m 0.255.255.255 dst-ip
192.168.5.12 src-port 12600 dst-port 31 action 12
```

NOTES:

For each flow-type, the programmed filters must all have the same matching input set. For example, issuing the following two commands is acceptable:



```text
# ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
# ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.5 src-port 55 action 10
```

Issuing the next two commands, however, is not acceptable, since the first specifies src-ip and the second specifies dst-ip:



```text
# ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
# ethtool -U enp130s0 flow-type ip4 dst-ip 192.168.0.5 src-port 55 action 10
```

The second command will fail with an error. You may program multiple filters with the same fields, using different values, but, on one device, you may not program two tcp4 filters with different matching fields.

The ice driver does not support matching on a subportion of a field, thus partial mask fields are not supported.

<a id="rst-flex-byte-flow-director-filters"></a>

### Flex Byte Flow Director Filters

The driver also supports matching user-defined data within the packet payload. This flexible data is specified using the "user-def" field of the ethtool command in the following way:


<table>
<tbody>
<tr>
<td>


`31    28    24    20    16`

</td>
<td>


`15    12    8    4    0`

</td>
</tr>
<tr>
<td>


`offset into packet payload`

</td>
<td>


`2 bytes of flexible data`

</td>
</tr>
</tbody>
</table>

For example,



```text
... user-def 0x4FFFF ...
```

tells the filter to look 4 bytes into the payload and match that value against 0xFFFF. The offset is based on the beginning of the payload, and not the beginning of the packet. Thus



```text
flow-type tcp4 ... user-def 0x8BEAF ...
```

would match TCP/IPv4 packets which have the value 0xBEAF 8 bytes into the TCP/IPv4 payload.

Note that ICMP headers are parsed as 4 bytes of header and 4 bytes of payload. Thus to match the first byte of the payload, you must actually add 4 bytes to the offset. Also note that ip4 filters match both ICMP frames as well as raw (unknown) ip4 frames, where the payload will be the L3 payload of the IP4 frame.

The maximum offset is 64. The hardware will only read up to 64 bytes of data from the payload. The offset must be even because the flexible data is 2 bytes long and must be aligned to byte 0 of the packet payload.

The user-defined flexible offset is also considered part of the input set and cannot be programmed separately for multiple filters of the same type. However, the flexible data is not part of the input set and multiple filters may use the same offset but match against different data.

<a id="rst-rss-hash-flow"></a>

### RSS Hash Flow

Allows you to set the hash bytes per flow type and any combination of one or more options for Receive Side Scaling (RSS) hash byte configuration.



```text
# ethtool -N <ethX> rx-flow-hash <type> <option>

Where <type> is:
  tcp4    signifying TCP over IPv4
  udp4    signifying UDP over IPv4
  gtpc4   signifying GTP-C over IPv4
  gtpc4t  signifying GTP-C (include TEID) over IPv4
  gtpu4   signifying GTP-U over IPV4
  gtpu4e  signifying GTP-U and Extension Header over IPV4
  gtpu4u  signifying GTP-U PSC Uplink over IPV4
  gtpu4d  signifying GTP-U PSC Downlink over IPV4
  tcp6    signifying TCP over IPv6
  udp6    signifying UDP over IPv6
  gtpc6   signifying GTP-C over IPv6
  gtpc6t  signifying GTP-C (include TEID) over IPv6
  gtpu6   signifying GTP-U over IPV6
  gtpu6e  signifying GTP-U and Extension Header over IPV6
  gtpu6u  signifying GTP-U PSC Uplink over IPV6
  gtpu6d  signifying GTP-U PSC Downlink over IPV6
And <option> is one or more of:
  s     Hash on the IP source address of the Rx packet.
  d     Hash on the IP destination address of the Rx packet.
  f     Hash on bytes 0 and 1 of the Layer 4 header of the Rx packet.
  n     Hash on bytes 2 and 3 of the Layer 4 header of the Rx packet.
  e     Hash on GTP Packet on TEID (4bytes) of the Rx packet.
```

<a id="rst-accelerated-receive-flow-steering-arfs"></a>

### Accelerated Receive Flow Steering (aRFS)

Devices based on the Intel(R) Ethernet Controller 800 Series support Accelerated Receive Flow Steering (aRFS) on the PF. aRFS is a load-balancing mechanism that allows you to direct packets to the same CPU where an application is running or consuming the packets in that flow.

NOTES:

- aRFS requires that ntuple filtering is enabled via ethtool.

- aRFS support is limited to the following packet types:

  > - TCP over IPv4 and IPv6
  >
  > - UDP over IPv4 and IPv6
  >
  > - Nonfragmented packets

- aRFS only supports Flow Director filters, which consist of the source/destination IP addresses and source/destination ports.

- aRFS and ethtool's ntuple interface both use the device's Flow Director. aRFS and ntuple features can coexist, but you may encounter unexpected results if there's a conflict between aRFS and ntuple requests. See "Intel(R) Ethernet Flow Director" for additional information.

To set up aRFS:

1. Enable the Intel Ethernet Flow Director and ntuple filters using ethtool.



```text
# ethtool -K <ethX> ntuple on
```

2. Set up the number of entries in the global flow table. For example:



```text
# NUM_RPS_ENTRIES=16384
# echo $NUM_RPS_ENTRIES > /proc/sys/net/core/rps_sock_flow_entries
```

3. Set up the number of entries in the per-queue flow table. For example:



```text
# NUM_RX_QUEUES=64
# for file in /sys/class/net/$IFACE/queues/rx-*/rps_flow_cnt; do
# echo $(($NUM_RPS_ENTRIES/$NUM_RX_QUEUES)) > $file;
# done
```

4. Disable the IRQ balance daemon (this is only a temporary stop of the service until the next reboot).



```text
# systemctl stop irqbalance
```

5. Configure the interrupt affinity.

   See `/Documentation/core-api/irq/irq-affinity.rst`

To disable aRFS using ethtool:



```text
# ethtool -K <ethX> ntuple off
```

NOTE: This command will disable ntuple filters and clear any aRFS filters in software and hardware.

Example Use Case:

1. Set the server application on the desired CPU (e.g., CPU 4).



```text
# taskset -c 4 netserver
```

2. Use netperf to route traffic from the client to CPU 4 on the server with aRFS configured. This example uses TCP over IPv4.



```text
# netperf -H <Host IPv4 Address> -t TCP_STREAM
```

<a id="rst-enabling-virtual-functions-vfs"></a>

### Enabling Virtual Functions (VFs)

Use sysfs to enable virtual functions (VF).

For example, you can create 4 VFs as follows:



```text
# echo 4 > /sys/class/net/<ethX>/device/sriov_numvfs
```

To disable VFs, write 0 to the same file:



```text
# echo 0 > /sys/class/net/<ethX>/device/sriov_numvfs
```

The maximum number of VFs for the ice driver is 256 total (all ports). To check how many VFs each PF supports, use the following command:



```text
# cat /sys/class/net/<ethX>/device/sriov_totalvfs
```

Note: You cannot use SR-IOV when link aggregation (LAG)/bonding is active, and vice versa. To enforce this, the driver checks for this mutual exclusion.

<a id="rst-displaying-vf-statistics-on-the-pf"></a>

### Displaying VF Statistics on the PF

Use the following command to display the statistics for the PF and its VFs:



```text
# ip -s link show dev <ethX>
```

NOTE: The output of this command can be very large due to the maximum number of possible VFs.

The PF driver will display a subset of the statistics for the PF and for all VFs that are configured. The PF will always print a statistics block for each of the possible VFs, and it will show zero for all unconfigured VFs.

<a id="rst-configuring-vlan-tagging-on-sr-iov-enabled-adapter-ports"></a>

### Configuring VLAN Tagging on SR-IOV Enabled Adapter Ports

To configure VLAN tagging for the ports on an SR-IOV enabled adapter, use the following command. The VLAN configuration should be done before the VF driver is loaded or the VM is booted. The VF is not aware of the VLAN tag being inserted on transmit and removed on received frames (sometimes called "port VLAN" mode).



```text
# ip link set dev <ethX> vf <id> vlan <vlan id>
```

For example, the following will configure PF eth0 and the first VF on VLAN 10:



```text
# ip link set dev eth0 vf 0 vlan 10
```

<a id="rst-enabling-a-vf-link-if-the-port-is-disconnected"></a>

### Enabling a VF link if the port is disconnected

If the physical function (PF) link is down, you can force link up (from the host PF) on any virtual functions (VF) bound to the PF.

For example, to force link up on VF 0 bound to PF eth0:



```text
# ip link set eth0 vf 0 state enable
```

Note: If the command does not work, it may not be supported by your system.

<a id="rst-setting-the-mac-address-for-a-vf"></a>

### Setting the MAC Address for a VF

To change the MAC address for the specified VF:



```text
# ip link set <ethX> vf 0 mac <address>
```

For example:



```text
# ip link set <ethX> vf 0 mac 00:01:02:03:04:05
```

This setting lasts until the PF is reloaded.

NOTE: Assigning a MAC address for a VF from the host will disable any subsequent requests to change the MAC address from within the VM. This is a security feature. The VM is not aware of this restriction, so if this is attempted in the VM, it will trigger MDD events.

<a id="rst-trusted-vfs-and-vf-promiscuous-mode"></a>

### Trusted VFs and VF Promiscuous Mode

This feature allows you to designate a particular VF as trusted and allows that trusted VF to request selective promiscuous mode on the Physical Function (PF).

To set a VF as trusted or untrusted, enter the following command in the Hypervisor:



```text
# ip link set dev <ethX> vf 1 trust [on|off]
```

NOTE: It's important to set the VF to trusted before setting promiscuous mode. If the VM is not trusted, the PF will ignore promiscuous mode requests from the VF. If the VM becomes trusted after the VF driver is loaded, you must make a new request to set the VF to promiscuous.

Once the VF is designated as trusted, use the following commands in the VM to set the VF to promiscuous mode.

For promiscuous all:



```text
# ip link set <ethX> promisc on
Where <ethX> is a VF interface in the VM
```

For promiscuous Multicast:



```text
# ip link set <ethX> allmulticast on
Where <ethX> is a VF interface in the VM
```

NOTE: By default, the ethtool private flag vf-true-promisc-support is set to "off," meaning that promiscuous mode for the VF will be limited. To set the promiscuous mode for the VF to true promiscuous and allow the VF to see all ingress traffic, use the following command:



```text
# ethtool --set-priv-flags <ethX> vf-true-promisc-support on
```

The vf-true-promisc-support private flag does not enable promiscuous mode; rather, it designates which type of promiscuous mode (limited or true) you will get when you enable promiscuous mode using the ip link commands above. Note that this is a global setting that affects the entire device. However, the vf-true-promisc-support private flag is only exposed to the first PF of the device. The PF remains in limited promiscuous mode regardless of the vf-true-promisc-support setting.

Next, add a VLAN interface on the VF interface. For example:



```text
# ip link add link eth2 name eth2.100 type vlan id 100
```

Note that the order in which you set the VF to promiscuous mode and add the VLAN interface does not matter (you can do either first). The result in this example is that the VF will get all traffic that is tagged with VLAN 100.

<a id="rst-malicious-driver-detection-mdd-for-vfs"></a>

### Malicious Driver Detection (MDD) for VFs

Some Intel Ethernet devices use Malicious Driver Detection (MDD) to detect malicious traffic from the VF and disable Tx/Rx queues or drop the offending packet until a VF driver reset occurs. You can view MDD messages in the PF's system log using the dmesg command.

- If the PF driver logs MDD events from the VF, confirm that the correct VF driver is installed.

- To restore functionality, you can manually reload the VF or VM or enable automatic VF resets.

- When automatic VF resets are enabled, the PF driver will immediately reset the VF and reenable queues when it detects MDD events on the receive path.

- If automatic VF resets are disabled, the PF will not automatically reset the VF when it detects MDD events.

To enable or disable automatic VF resets, use the following command:



```text
# ethtool --set-priv-flags <ethX> mdd-auto-reset-vf on|off
```

<a id="rst-mac-and-vlan-anti-spoofing-feature-for-vfs"></a>

### MAC and VLAN Anti-Spoofing Feature for VFs

When a malicious driver on a Virtual Function (VF) interface attempts to send a spoofed packet, it is dropped by the hardware and not transmitted.

NOTE: This feature can be disabled for a specific VF:



```text
# ip link set <ethX> vf <vf id> spoofchk {off|on}
```

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;ethX&gt; is the interface number:



```text
# ifconfig <ethX> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
# ip link set mtu 9000 dev <ethX>
# ip link set up dev <ethX>
```

This setting is not saved across reboots.

NOTE: The maximum MTU setting for jumbo frames is 9702. This corresponds to the maximum jumbo frame size of 9728 bytes.

NOTE: This driver will attempt to use multiple page sized buffers to receive each jumbo packet. This should help to avoid buffer starvation issues when allocating receive packets.

NOTE: Packet loss may have a greater impact on throughput when you use jumbo frames. If you observe a drop in performance after enabling jumbo frames, enabling flow control may mitigate the issue.

<a id="rst-speed-and-duplex-configuration"></a>

### Speed and Duplex Configuration

In addressing speed and duplex configuration issues, you need to distinguish between copper-based adapters and fiber-based adapters.

In the default mode, an Intel(R) Ethernet Network Adapter using copper connections will attempt to auto-negotiate with its link partner to determine the best setting. If the adapter cannot establish link with the link partner using auto-negotiation, you may need to manually configure the adapter and link partner to identical settings to establish link and pass packets. This should only be needed when attempting to link with an older switch that does not support auto-negotiation or one that has been forced to a specific speed or duplex mode. Your link partner must match the setting you choose. 1 Gbps speeds and higher cannot be forced. Use the autonegotiation advertising setting to manually set devices for 1 Gbps and higher.

Speed, duplex, and autonegotiation advertising are configured through the ethtool utility. For the latest version, download and install ethtool from the following website:

> [https://kernel.org/pub/software/network/ethtool/](<https://kernel.org/pub/software/network/ethtool/>)

To see the speed configurations your device supports, run the following:



```text
# ethtool <ethX>
```

Caution: Only experienced network administrators should force speed and duplex or change autonegotiation advertising manually. The settings at the switch must always match the adapter settings. Adapter performance may suffer or your adapter may not operate if you configure the adapter differently from your switch.

<a id="rst-data-center-bridging-dcb"></a>

### Data Center Bridging (DCB)

NOTE: The kernel assumes that TC0 is available, and will disable Priority Flow Control (PFC) on the device if TC0 is not available. To fix this, ensure TC0 is enabled when setting up DCB on your switch.

DCB is a configuration Quality of Service implementation in hardware. It uses the VLAN priority tag (802.1p) to filter traffic. That means that there are 8 different priorities that traffic can be filtered into. It also enables priority flow control (802.1Qbb) which can limit or eliminate the number of dropped packets during network stress. Bandwidth can be allocated to each of these priorities, which is enforced at the hardware level (802.1Qaz).

DCB is normally configured on the network using the DCBX protocol (802.1Qaz), a specialization of LLDP (802.1AB). The ice driver supports the following mutually exclusive variants of DCBX support:

1. Firmware-based LLDP Agent

2. Software-based LLDP Agent

In firmware-based mode, firmware intercepts all LLDP traffic and handles DCBX negotiation transparently for the user. In this mode, the adapter operates in "willing" DCBX mode, receiving DCB settings from the link partner (typically a switch). The local user can only query the negotiated DCB configuration. For information on configuring DCBX parameters on a switch, please consult the switch manufacturer's documentation.

In software-based mode, LLDP traffic is forwarded to the network stack and user space, where a software agent can handle it. In this mode, the adapter can operate in either "willing" or "nonwilling" DCBX mode and DCB configuration can be both queried and set locally. This mode requires the FW-based LLDP Agent to be disabled.

NOTE:

- You can enable and disable the firmware-based LLDP Agent using an ethtool private flag. Refer to the "FW-LLDP (Firmware Link Layer Discovery Protocol)" section in this README for more information.

- In software-based DCBX mode, you can configure DCB parameters using software LLDP/DCBX agents that interface with the Linux kernel's DCB Netlink API. We recommend using OpenLLDP as the DCBX agent when running in software mode. For more information, see the OpenLLDP man pages and [https://github.com/intel/openlldp](<https://github.com/intel/openlldp>).

- The driver implements the DCB netlink interface layer to allow the user space to communicate with the driver and query DCB configuration for the port.

- iSCSI with DCB is not supported.

<a id="rst-fw-lldp-firmware-link-layer-discovery-protocol"></a>

### FW-LLDP (Firmware Link Layer Discovery Protocol)

Use ethtool to change FW-LLDP settings. The FW-LLDP setting is per port and persists across boots.

To enable LLDP:



```text
# ethtool --set-priv-flags <ethX> fw-lldp-agent on
```

To disable LLDP:



```text
# ethtool --set-priv-flags <ethX> fw-lldp-agent off
```

To check the current LLDP setting:



```text
# ethtool --show-priv-flags <ethX>
```

NOTE: You must enable the UEFI HII "LLDP Agent" attribute for this setting to take effect. If "LLDP AGENT" is set to disabled, you cannot enable it from the OS.

<a id="rst-flow-control"></a>

### Flow Control

Ethernet Flow Control (IEEE 802.3x) can be configured with ethtool to enable receiving and transmitting pause frames for ice. When transmit is enabled, pause frames are generated when the receive packet buffer crosses a predefined threshold. When receive is enabled, the transmit unit will halt for the time delay specified when a pause frame is received.

NOTE: You must have a flow control capable link partner.

Flow Control is disabled by default.

Use ethtool to change the flow control settings.

To enable or disable Rx or Tx Flow Control:



```text
# ethtool -A <ethX> rx <on|off> tx <on|off>
```

Note: This command only enables or disables Flow Control if auto-negotiation is disabled. If auto-negotiation is enabled, this command changes the parameters used for auto-negotiation with the link partner.

Note: Flow Control auto-negotiation is part of link auto-negotiation. Depending on your device, you may not be able to change the auto-negotiation setting.

NOTE:

- The ice driver requires flow control on both the port and link partner. If flow control is disabled on one of the sides, the port may appear to hang on heavy traffic.

- You may encounter issues with link-level flow control (LFC) after disabling DCB. The LFC status may show as enabled but traffic is not paused. To resolve this issue, disable and reenable LFC using ethtool:



  ```text
  # ethtool -A <ethX> rx off tx off
  # ethtool -A <ethX> rx on tx on
  ```

<a id="rst-napi"></a>

### NAPI

This driver supports NAPI (Rx polling mode).

See [Documentation/networking/napi.rst](<#rst-napi>) for more information.

<a id="rst-macvlan"></a>

### MACVLAN

This driver supports MACVLAN. Kernel support for MACVLAN can be tested by checking if the MACVLAN driver is loaded. You can run 'lsmod \| grep macvlan' to see if the MACVLAN driver is loaded or run 'modprobe macvlan' to try to load the MACVLAN driver.

NOTE:

- In passthru mode, you can only set up one MACVLAN device. It will inherit the MAC address of the underlying PF (Physical Function) device.

<a id="rst-ieee-802-1ad-qinq-support"></a>

### IEEE 802.1ad (QinQ) Support

The IEEE 802.1ad standard, informally known as QinQ, allows for multiple VLAN IDs within a single Ethernet frame. VLAN IDs are sometimes referred to as "tags," and multiple VLAN IDs are thus referred to as a "tag stack." Tag stacks allow L2 tunneling and the ability to segregate traffic within a particular VLAN ID, among other uses.

NOTES:

- Receive checksum offloads and VLAN acceleration are not supported for 802.1ad (QinQ) packets.

- 0x88A8 traffic will not be received unless VLAN stripping is disabled with the following command:



  ```text
  # ethtool -K <ethX> rxvlan off
  ```

- 0x88A8/0x8100 double VLANs cannot be used with 0x8100 or 0x8100/0x8100 VLANS configured on the same port. 0x88a8/0x8100 traffic will not be received if 0x8100 VLANs are configured.

- The VF can only transmit 0x88A8/0x8100 (i.e., 802.1ad/802.1Q) traffic if:

  > 1. The VF is not assigned a port VLAN.
  >
  > 2. spoofchk is disabled from the PF. If you enable spoofchk, the VF will not transmit 0x88A8/0x8100 traffic.

- The VF may not receive all network traffic based on the Inner VLAN header when VF true promiscuous mode (vf-true-promisc-support) and double VLANs are enabled in SR-IOV mode.

The following are examples of how to configure 802.1ad (QinQ):



```text
# ip link add link eth0 eth0.24 type vlan proto 802.1ad id 24
# ip link add link eth0.24 eth0.24.371 type vlan proto 802.1Q id 371

Where "24" and "371" are example VLAN IDs.
```

<a id="rst-tunnel-overlay-stateless-offloads"></a>

### Tunnel/Overlay Stateless Offloads

Supported tunnels and overlays include VXLAN, GENEVE, and others depending on hardware and software configuration. Stateless offloads are enabled by default.

To view the current state of all offloads:



```text
# ethtool -k <ethX>
```

<a id="rst-udp-segmentation-offload"></a>

### UDP Segmentation Offload

Allows the adapter to offload transmit segmentation of UDP packets with payloads up to 64K into valid Ethernet frames. Because the adapter hardware is able to complete data segmentation much faster than operating system software, this feature may improve transmission performance. In addition, the adapter may use fewer CPU resources.

NOTE:

- The application sending UDP packets must support UDP segmentation offload.

To enable/disable UDP Segmentation Offload, issue the following command:



```text
# ethtool -K <ethX> tx-udp-segmentation [off|on]
```

<a id="rst-ptp-pin-interface"></a>

### PTP pin interface

All adapters support standard PTP pin interface. SDPs (Software Definable Pin) are single ended pins with both periodic output and external timestamp supported. There are also specific differential input/output pins (TIME_SYNC, 1PPS) with only one of the functions supported.

There are adapters with DPLL, where pins are connected to the DPLL instead of being exposed on the board. You have to be aware that in those configurations, only SDP pins are exposed and each pin has its own fixed direction. To see input signal on those PTP pins, you need to configure DPLL properly. Output signal is only visible on DPLL and to send it to the board SMA/U.FL pins, DPLL output pins have to be manually configured.

<a id="rst-gnss-module"></a>

### GNSS module

Requires kernel compiled with CONFIG_GNSS=y or CONFIG_GNSS=m. Allows user to read messages from the GNSS hardware module and write supported commands. If the module is physically present, a GNSS device is spawned: `/dev/gnss<id>`. The protocol of write command is dependent on the GNSS hardware module as the driver writes raw bytes by the GNSS object to the receiver through i2c. Please refer to the hardware GNSS module documentation for configuration details.

<a id="rst-firmware-fw-logging"></a>

### Firmware (FW) logging

The driver supports FW logging via the debugfs interface on PF 0 only. The FW running on the NIC must support FW logging; if the FW doesn't support FW logging the 'fwlog' file will not get created in the ice debugfs directory.

<a id="rst-module-configuration"></a>

#### Module configuration

Firmware logging is configured on a per module basis. Each module can be set to a value independent of the other modules (unless the module 'all' is specified). The modules will be instantiated under the 'fwlog/modules' directory.

The user can set the log level for a module by writing to the module file like this:



```text
# echo <log_level> > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/<module>
```

where

- log_level is a name as described below. Each level includes the messages from the previous/lower level

  > - none
  >
  > - error
  >
  > - warning
  >
  > - normal
  >
  > - verbose

- module is a name that represents the module to receive events for. The module names are

  > - general
  >
  > - ctrl
  >
  > - link
  >
  > - link_topo
  >
  > - dnl
  >
  > - i2c
  >
  > - sdp
  >
  > - mdio
  >
  > - adminq
  >
  > - hdma
  >
  > - lldp
  >
  > - dcbx
  >
  > - dcb
  >
  > - xlr
  >
  > - nvm
  >
  > - auth
  >
  > - vpd
  >
  > - iosf
  >
  > - parser
  >
  > - sw
  >
  > - scheduler
  >
  > - txq
  >
  > - rsvd
  >
  > - post
  >
  > - watchdog
  >
  > - task_dispatch
  >
  > - mng
  >
  > - synce
  >
  > - health
  >
  > - tsdrv
  >
  > - pfreg
  >
  > - mdlver
  >
  > - all

The name 'all' is special and allows the user to set all of the modules to the specified log_level or to read the log_level of all of the modules.

<a id="rst-example-usage-to-configure-the-modules"></a>

##### Example usage to configure the modules

To set a single module to 'verbose':



```text
# echo verbose > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/link
```

To set multiple modules then issue the command multiple times:



```text
# echo verbose > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/link
# echo warning > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/ctrl
# echo none > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/dcb
```

To set all the modules to the same value:



```text
# echo normal > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/all
```

To read the log_level of a specific module (e.g. module 'general'):



```text
# cat /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/general
```

To read the log_level of all the modules:



```text
# cat /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/modules/all
```

<a id="rst-enabling-fw-log"></a>

#### Enabling FW log

Configuring the modules indicates to the FW that the configured modules should generate events that the driver is interested in, but it **does not** send the events to the driver until the enable message is sent to the FW. To do this the user can write a 1 (enable) or 0 (disable) to 'fwlog/enable'. An example is:



```text
# echo 1 > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/enable
```

<a id="rst-retrieving-fw-log-data"></a>

#### Retrieving FW log data

The FW log data can be retrieved by reading from 'fwlog/data'. The user can write any value to 'fwlog/data' to clear the data. The data can only be cleared when FW logging is disabled. The FW log data is a binary file that is sent to Intel and used to help debug user issues.

An example to read the data is:



```text
# cat /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/data > fwlog.bin
```

An example to clear the data is:



```text
# echo 0 > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/data
```

<a id="rst-changing-how-often-the-log-events-are-sent-to-the-driver"></a>

#### Changing how often the log events are sent to the driver

The driver receives FW log data from the Admin Receive Queue (ARQ). The frequency that the FW sends the ARQ events can be configured by writing to 'fwlog/nr_messages'. The range is 1-128 (1 means push every log message, 128 means push only when the max AQ command buffer is full). The suggested value is 10. The user can see what the value is configured to by reading 'fwlog/nr_messages'. An example to set the value is:



```text
# echo 50 > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/nr_messages
```

<a id="rst-configuring-the-amount-of-memory-used-to-store-fw-log-data"></a>

#### Configuring the amount of memory used to store FW log data

The driver stores FW log data within the driver. The default size of the memory used to store the data is 1MB. Some use cases may require more or less data so the user can change the amount of memory that is allocated for FW log data. To change the amount of memory then write to 'fwlog/log_size'. The value must be one of: 128K, 256K, 512K, 1M, or 2M. FW logging must be disabled to change the value. An example of changing the value is:



```text
# echo 128K > /sys/kernel/debug/ice/0000\:18\:00.0/fwlog/log_size
```

<a id="rst-performance-optimization"></a>

## Performance Optimization

Driver defaults are meant to fit a wide variety of workloads, but if further optimization is required, we recommend experimenting with the following settings.

<a id="rst-rx-descriptor-ring-size"></a>

### Rx Descriptor Ring Size

To reduce the number of Rx packet discards, increase the number of Rx descriptors for each Rx ring using ethtool.

> Check if the interface is dropping Rx packets due to buffers being full (rx_dropped.nic can mean that there is no PCIe bandwidth):
>
>
>
> ```text
> # ethtool -S <ethX> | grep "rx_dropped"
> ```
>
> If the previous command shows drops on queues, it may help to increase the number of descriptors using 'ethtool -G':
>
>
>
> ```text
> # ethtool -G <ethX> rx <N>
> Where <N> is the desired number of ring entries/descriptors
> ```
>
> This can provide temporary buffering for issues that create latency while the CPUs process descriptors.

<a id="rst-interrupt-rate-limiting"></a>

### Interrupt Rate Limiting

This driver supports an adaptive interrupt throttle rate (ITR) mechanism that is tuned for general workloads. The user can customize the interrupt rate control for specific workloads, via ethtool, adjusting the number of microseconds between interrupts.

To set the interrupt rate manually, you must disable adaptive mode:



```text
# ethtool -C <ethX> adaptive-rx off adaptive-tx off
```

For lower CPU utilization:

> Disable adaptive ITR and lower Rx and Tx interrupts. The examples below affect every queue of the specified interface.
>
> Setting rx-usecs and tx-usecs to 80 will limit interrupts to about 12,500 interrupts per second per queue:
>
>
>
> ```text
> # ethtool -C <ethX> adaptive-rx off adaptive-tx off rx-usecs 80 tx-usecs 80
> ```

For reduced latency:

> Disable adaptive ITR and ITR by setting rx-usecs and tx-usecs to 0 using ethtool:
>
>
>
> ```text
> # ethtool -C <ethX> adaptive-rx off adaptive-tx off rx-usecs 0 tx-usecs 0
> ```

Per-queue interrupt rate settings:

> The following examples are for queues 1 and 3, but you can adjust other queues.
>
> To disable Rx adaptive ITR and set static Rx ITR to 10 microseconds or about 100,000 interrupts/second, for queues 1 and 3:
>
>
>
> ```text
> # ethtool --per-queue <ethX> queue_mask 0xa --coalesce adaptive-rx off
> rx-usecs 10
> ```
>
> To show the current coalesce settings for queues 1 and 3:
>
>
>
> ```text
> # ethtool --per-queue <ethX> queue_mask 0xa --show-coalesce
> ```

Bounding interrupt rates using rx-usecs-high:

> **Valid Range:** 0-236 (0=no limit)
>
> The range of 0-236 microseconds provides an effective range of 4,237 to 250,000 interrupts per second. The value of rx-usecs-high can be set independently of rx-usecs and tx-usecs in the same ethtool command, and is also independent of the adaptive interrupt moderation algorithm. The underlying hardware supports granularity in 4-microsecond intervals, so adjacent values may result in the same interrupt rate.
>
> The following command would disable adaptive interrupt moderation, and allow a maximum of 5 microseconds before indicating a receive or transmit was complete. However, instead of resulting in as many as 200,000 interrupts per second, it limits total interrupts per second to 50,000 via the rx-usecs-high parameter.
>
>
>
> ```text
> # ethtool -C <ethX> adaptive-rx off adaptive-tx off rx-usecs-high 20
> rx-usecs 5 tx-usecs 5
> ```

<a id="rst-virtualized-environments"></a>

### Virtualized Environments

In addition to the other suggestions in this section, the following may be helpful to optimize performance in VMs.

> Using the appropriate mechanism (vcpupin) in the VM, pin the CPUs to individual LCPUs, making sure to use a set of CPUs included in the device's local_cpulist: `/sys/class/net/<ethX>/device/local_cpulist`.
>
> Configure as many Rx/Tx queues in the VM as available. (See the iavf driver documentation for the number of queues supported.) For example:
>
>
>
> ```text
> # ethtool -L <virt_interface> rx <max> tx <max>
> ```

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

<a id="rst-trademarks"></a>

## Trademarks

Intel is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United States and/or other countries.

- Other names and brands may be claimed as the property of others.

---

# idpf Linux* Base Driver for the Intel(R) Infrastructure Data Path Function

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel idpf Linux driver. Copyright(C) 2023 Intel Corporation.

<a id="rst-idpf-linux-base-driver-for-the-intel-r-infrastructure-data-path-function"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel idpf Linux driver. Copyright(C) 2023 Intel Corporation.

<a id="rst-contents"></a>



The idpf driver serves as both the Physical Function (PF) and Virtual Function (VF) driver for the Intel(R) Infrastructure Data Path Function.

Driver information can be obtained using ethtool, lspci, and ip.

For questions related to hardware requirements, refer to the documentation supplied with your Intel adapter. All hardware requirements listed apply to use with Linux.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [http://www.intel.com/support](<http://www.intel.com/support>)

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. If you don't have one yet, you can obtain it at: [https://kernel.org/pub/software/network/ethtool/](<https://kernel.org/pub/software/network/ethtool/>)

<a id="rst-viewing-link-messages"></a>

### Viewing Link Messages

Link messages will not be displayed to the console if the distribution is restricting system messages. In order to see network driver link messages on your console, set dmesg to eight by entering the following:



```text
# dmesg -n 8
```

> [!NOTE]
>
> This setting is not saved across reboots.

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ip command to increase the MTU size. For example, enter the following where &lt;ethX&gt; is the interface number:



```text
# ip link set mtu 9000 dev <ethX>
# ip link set up dev <ethX>
```

> [!NOTE]
>
> The maximum MTU setting for jumbo frames is 9706. This corresponds to the maximum jumbo frame size of 9728 bytes.

> [!NOTE]
>
> This driver will attempt to use multiple page sized buffers to receive each jumbo packet. This should help to avoid buffer starvation issues when allocating receive packets.

> [!NOTE]
>
> Packet loss may have a greater impact on throughput when you use jumbo frames. If you observe a drop in performance after enabling jumbo frames, enabling flow control may mitigate the issue.

<a id="rst-performance-optimization"></a>

## Performance Optimization

Driver defaults are meant to fit a wide variety of workloads, but if further optimization is required, we recommend experimenting with the following settings.

<a id="rst-interrupt-rate-limiting"></a>

### Interrupt Rate Limiting

This driver supports an adaptive interrupt throttle rate (ITR) mechanism that is tuned for general workloads. The user can customize the interrupt rate control for specific workloads, via ethtool, adjusting the number of microseconds between interrupts.

To set the interrupt rate manually, you must disable adaptive mode:



```text
# ethtool -C <ethX> adaptive-rx off adaptive-tx off
```

- **For lower CPU utilization:**

  - Disable adaptive ITR and lower Rx and Tx interrupts. The examples below affect every queue of the specified interface.

  - Setting rx-usecs and tx-usecs to 80 will limit interrupts to about 12,500 interrupts per second per queue:



    ```text
    # ethtool -C <ethX> adaptive-rx off adaptive-tx off rx-usecs 80
    tx-usecs 80
    ```

- **For reduced latency:**

  - Disable adaptive ITR and ITR by setting rx-usecs and tx-usecs to 0 using ethtool:



    ```text
    # ethtool -C <ethX> adaptive-rx off adaptive-tx off rx-usecs 0
    tx-usecs 0
    ```

- **Per-queue interrupt rate settings:**

  - The following examples are for queues 1 and 3, but you can adjust other queues.

  - To disable Rx adaptive ITR and set static Rx ITR to 10 microseconds or about 100,000 interrupts/second, for queues 1 and 3:



    ```text
    # ethtool --per-queue <ethX> queue_mask 0xa --coalesce adaptive-rx off
    rx-usecs 10
    ```

  - To show the current coalesce settings for queues 1 and 3:



    ```text
    # ethtool --per-queue <ethX> queue_mask 0xa --show-coalesce
    ```

<a id="rst-virtualized-environments"></a>

### Virtualized Environments

In addition to the other suggestions in this section, the following may be helpful to optimize performance in VMs.

> - Using the appropriate mechanism (vcpupin) in the VM, pin the CPUs to individual LCPUs, making sure to use a set of CPUs included in the device's local_cpulist: /sys/class/net/&lt;ethX&gt;/device/local_cpulist.
>
> - Configure as many Rx/Tx queues in the VM as available. (See the idpf driver documentation for the number of queues supported.) For example:
>
>
>
>   ```text
>   # ethtool -L <virt_interface> rx <max> tx <max>
>   ```

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [http://www.intel.com/support/](<http://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

<a id="rst-trademarks"></a>

## Trademarks

Intel is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United States and/or other countries.

- Other names and brands may be claimed as the property of others.

---

# Linux Base Driver for Intel(R) Ethernet Network Connection

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-linux-base-driver-for-intel-r-ethernet-network-connection"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Command Line Parameters

- Additional Configurations

- Support

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

If the driver is built as a module, the following optional parameters are used by entering them on the command line with the modprobe command using this syntax:



```text
modprobe igb [<option>=<VAL1>,<VAL2>,...]
```

There needs to be a &lt;VAL\#&gt; for each network port in the system supported by this driver. The values will be applied to each instance, in function order. For example:



```text
modprobe igb max_vfs=2,4
```

In this case, there are two network ports supported by igb in the system.

NOTE: A descriptor describes a data buffer and attributes related to the data buffer. This information is accessed by the hardware.

<a id="rst-max-vfs"></a>

### max_vfs

**Valid Range:** 0-7

This parameter adds support for SR-IOV. It causes the driver to spawn up to max_vfs worth of virtual functions.  If the value is greater than 0 it will also force the VMDq parameter to be 1 or more.

The parameters for the driver are referenced by position. Thus, if you have a dual port adapter, or more than one adapter in your system, and want N virtual functions per port, you must specify a number for each port with each parameter separated by a comma. For example:



```text
modprobe igb max_vfs=4
```

This will spawn 4 VFs on the first port.



```text
modprobe igb max_vfs=2,4
```

This will spawn 2 VFs on the first port and 4 VFs on the second port.

NOTE: Caution must be used in loading the driver with these parameters. Depending on your system configuration, number of slots, etc., it is impossible to predict in all cases where the positions would be on the command line.

NOTE: Neither the device nor the driver control how VFs are mapped into config space. Bus layout will vary by operating system. On operating systems that support it, you can check sysfs to find the mapping.

NOTE: When either SR-IOV mode or VMDq mode is enabled, hardware VLAN filtering and VLAN tag stripping/insertion will remain enabled. Please remove the old VLAN filter before the new VLAN filter is added. For example:



```text
ip link set eth0 vf 0 vlan 100      // set vlan 100 for VF 0
ip link set eth0 vf 0 vlan 0        // Delete vlan 100
ip link set eth0 vf 0 vlan 200      // set a new vlan 200 for VF 0
```

<a id="rst-debug"></a>

### Debug

**Valid Range:** 0-16 (0=none,...,16=all)

**Default Value:** 0

This parameter adjusts the level debug messages displayed in the system logs.

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;x&gt; is the interface number:



```text
ifconfig eth<x> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
ip link set mtu 9000 dev eth<x>
ip link set up dev eth<x>
```

This setting is not saved across reboots. The setting change can be made permanent by adding 'MTU=9000' to the file:

- For RHEL: /etc/sysconfig/network-scripts/ifcfg-eth&lt;x&gt;

- For SLES: /etc/sysconfig/network/&lt;config_file&gt;

NOTE: The maximum MTU setting for Jumbo Frames is 9216. This value coincides with the maximum Jumbo Frames size of 9234 bytes.

NOTE: Using Jumbo frames at 10 or 100 Mbps is not supported and may result in poor performance or loss of link.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at:

[https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-enabling-wake-on-lan-wol"></a>

### Enabling Wake on LAN (WoL)

WoL is configured through the ethtool utility.

WoL will be enabled on the system during the next shut down or reboot. For this driver version, in order to enable WoL, the igb driver must be loaded prior to shutting down or suspending the system.

NOTE: Wake on LAN is only supported on port A of multi-port devices.  Also Wake On LAN is not supported for the following device: - Intel(R) Gigabit VT Quad Port Server Adapter

<a id="rst-multiqueue"></a>

### Multiqueue

In this mode, a separate MSI-X vector is allocated for each queue and one for "other" interrupts such as link status change and errors. All interrupts are throttled via interrupt moderation. Interrupt moderation must be used to avoid interrupt storms while the driver is processing one interrupt. The moderation value should be at least as large as the expected time for the driver to process an interrupt. Multiqueue is off by default.

REQUIREMENTS: MSI-X support is required for Multiqueue. If MSI-X is not found, the system will fallback to MSI or to Legacy interrupts. This driver supports receive multiqueue on all kernels that support MSI-X.

NOTE: On some kernels a reboot is required to switch between single queue mode and multiqueue mode or vice-versa.

<a id="rst-mac-and-vlan-anti-spoofing-feature"></a>

### MAC and VLAN anti-spoofing feature

When a malicious driver attempts to send a spoofed packet, it is dropped by the hardware and not transmitted.

An interrupt is sent to the PF driver notifying it of the spoof attempt. When a spoofed packet is detected, the PF driver will send the following message to the system log (displayed by the "dmesg" command): Spoof event(s) detected on VF(n), where n = the VF that attempted to do the spoofing

<a id="rst-setting-mac-address-vlan-and-rate-limit-using-iproute2-tool"></a>

### Setting MAC Address, VLAN and Rate Limit Using IProute2 Tool

You can set a MAC address of a Virtual Function (VF), a default VLAN and the rate limit using the IProute2 tool. Download the latest version of the IProute2 tool from Sourceforge if your version does not have all the features you require.

<a id="rst-credit-based-shaper-qav-mode"></a>

### Credit Based Shaper (Qav Mode)

When enabling the CBS qdisc in the hardware offload mode, traffic shaping using the CBS (described in the IEEE 802.1Q-2018 Section 8.6.8.2 and discussed in the Annex L) algorithm will run in the i210 controller, so it's more accurate and uses less CPU.

When using offloaded CBS, and the traffic rate obeys the configured rate (doesn't go above it), CBS should have little to no effect in the latency.

The offloaded version of the algorithm has some limits, caused by how the idle slope is expressed in the adapter's registers. It can only represent idle slopes in 16.38431 kbps units, which means that if a idle slope of 2576kbps is requested, the controller will be configured to use a idle slope of \~2589 kbps, because the driver rounds the value up. For more details, see the comments on `igb_config_tx_modes()`.

NOTE: This feature is exclusive to i210 models.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Virtual Function Driver for Intel(R) 1G Ethernet

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel Gigabit Virtual Function Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-linux-base-virtual-function-driver-for-intel-r-1g-ethernet"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel Gigabit Virtual Function Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Additional Configurations

- Support

This driver supports Intel 82576-based virtual function devices-based virtual function devices that can only be activated on kernels that support SR-IOV.

SR-IOV requires the correct platform and OS support.

The guest OS loading this driver must support MSI-X interrupts.

For questions related to hardware requirements, refer to the documentation supplied with your Intel adapter. All hardware requirements listed apply to use with Linux.

Driver information can be obtained using ethtool, lspci, and ifconfig. Instructions on updating ethtool can be found in the section Additional Configurations later in this document.

NOTE: There is a limit of a total of 32 shared VLANs to 1 or more VFs.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at:

[https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Driver for the Intel(R) Ethernet 10 Gigabit PCI Express Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel 10 Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-linux-base-driver-for-the-intel-r-ethernet-10-gigabit-pci-express-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel 10 Gigabit Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Command Line Parameters

- Additional Configurations

- Known Issues

- Support

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver is compatible with devices based on the following:

> - Intel(R) Ethernet Controller 82598
>
> - Intel(R) Ethernet Controller 82599
>
> - Intel(R) Ethernet Controller X520
>
> - Intel(R) Ethernet Controller X540
>
> - Intel(R) Ethernet Controller x550
>
> - Intel(R) Ethernet Controller X552
>
> - Intel(R) Ethernet Controller X553

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-sfp-devices-with-pluggable-optics"></a>

### SFP+ Devices with Pluggable Optics

<a id="rst-based-adapters"></a>

#### 82599-BASED ADAPTERS

NOTES: - If your 82599-based Intel(R) Network Adapter came with Intel optics or is an Intel(R) Ethernet Server Adapter X520-2, then it only supports Intel optics and/or the direct attach cables listed below. - When 82599-based SFP+ devices are connected back to back, they should be set to the same Speed setting via ethtool. Results may vary if you mix speed settings.


<table>
<thead>
<tr>
<th>


Supplier

</th>
<th>


Type

</th>
<th>


Part Numbers

</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3">


SR Modules

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ SR (bailed)

</td>
<td>


FTLX8571D3BCV-IT

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ SR (bailed)

</td>
<td>


AFBR-703SDZ-IN2

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ SR (bailed)

</td>
<td>


AFBR-703SDDZ-IN1

</td>
</tr>
<tr>
<td colspan="3">


LR Modules

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ LR (bailed)

</td>
<td>


FTLX1471D3BCV-IT

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ LR (bailed)

</td>
<td>


AFCT-701SDZ-IN2

</td>
</tr>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G SFP+ LR (bailed)

</td>
<td>


AFCT-701SDDZ-IN1

</td>
</tr>
</tbody>
</table>

The following is a list of 3rd party SFP+ modules that have received some testing. Not all modules are applicable to all devices.


<table>
<thead>
<tr>
<th>


Supplier

</th>
<th>


Type

</th>
<th>


Part Numbers

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Finisar

</td>
<td>


SFP+ SR bailed, 10g single rate

</td>
<td>


FTLX8571D3BCL

</td>
</tr>
<tr>
<td>


Avago

</td>
<td>


SFP+ SR bailed, 10g single rate

</td>
<td>


AFBR-700SDZ

</td>
</tr>
<tr>
<td>


Finisar

</td>
<td>


SFP+ LR bailed, 10g single rate

</td>
<td>


FTLX1471D3BCL

</td>
</tr>
<tr>
<td>


Finisar

</td>
<td>


DUAL RATE 1G/10G SFP+ SR (No Bail)

</td>
<td>


FTLX8571D3QCV-IT

</td>
</tr>
<tr>
<td>


Avago

</td>
<td>


DUAL RATE 1G/10G SFP+ SR (No Bail)

</td>
<td>


AFBR-703SDZ-IN1

</td>
</tr>
<tr>
<td>


Finisar

</td>
<td>


DUAL RATE 1G/10G SFP+ LR (No Bail)

</td>
<td>


FTLX1471D3QCV-IT

</td>
</tr>
<tr>
<td>


Avago

</td>
<td>


DUAL RATE 1G/10G SFP+ LR (No Bail)

</td>
<td>


AFCT-701SDZ-IN1

</td>
</tr>
<tr>
<td>


Finisar

</td>
<td>


1000BASE-T SFP

</td>
<td>


FCLF8522P2BTL

</td>
</tr>
<tr>
<td>


Avago

</td>
<td>


1000BASE-T

</td>
<td>


ABCU-5710RZ

</td>
</tr>
<tr>
<td>


HP

</td>
<td>


1000BASE-SX SFP

</td>
<td>


453153-001

</td>
</tr>
</tbody>
</table>

82599-based adapters support all passive and active limiting direct attach cables that comply with SFF-8431 v4.1 and SFF-8472 v10.4 specifications.

<a id="rst-laser-turns-off-for-sfp-when-ifconfig-ethx-down"></a>

#### Laser turns off for SFP+ when ifconfig ethX down

"ifconfig ethX down" turns off the laser for 82599-based SFP+ fiber adapters. "ifconfig ethX up" turns on the laser. Alternatively, you can use "ip link set \[down/up\] dev ethX" to turn the laser off and on.

<a id="rst-based-qsfp-adapters"></a>

#### 82599-based QSFP+ Adapters

NOTES: - If your 82599-based Intel(R) Network Adapter came with Intel optics, it only supports Intel optics. - 82599-based QSFP+ adapters only support 4x10 Gbps connections.  1x40 Gbps connections are not supported. QSFP+ link partners must be configured for 4x10 Gbps. - 82599-based QSFP+ adapters do not support automatic link speed detection. The link speed must be configured to either 10 Gbps or 1 Gbps to match the link partners speed capabilities. Incorrect speed configurations will result in failure to link. - Intel(R) Ethernet Converged Network Adapter X520-Q1 only supports the optics and direct attach cables listed below.


<table>
<thead>
<tr>
<th>


Supplier

</th>
<th>


Type

</th>
<th>


Part Numbers

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Intel

</td>
<td>


DUAL RATE 1G/10G QSFP+ SRL (bailed)

</td>
<td>


E10GQSFPSR

</td>
</tr>
</tbody>
</table>

82599-based QSFP+ adapters support all passive and active limiting QSFP+ direct attach cables that comply with SFF-8436 v4.1 specifications.

<a id="rst-based-adapters-1"></a>

#### 82598-BASED ADAPTERS

NOTES: - Intel(r) Ethernet Network Adapters that support removable optical modules only support their original module type (for example, the Intel(R) 10 Gigabit SR Dual Port Express Module only supports SR optical modules). If you plug in a different type of module, the driver will not load. - Hot Swapping/hot plugging optical modules is not supported. - Only single speed, 10 gigabit modules are supported. - LAN on Motherboard (LOMs) may support DA, SR, or LR modules. Other module types are not supported. Please see your system documentation for details.

The following is a list of SFP+ modules and direct attach cables that have received some testing. Not all modules are applicable to all devices.


<table>
<thead>
<tr>
<th>


Supplier

</th>
<th>


Type

</th>
<th>


Part Numbers

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Finisar

</td>
<td>


SFP+ SR bailed, 10g single rate

</td>
<td>


FTLX8571D3BCL

</td>
</tr>
<tr>
<td>


Avago

</td>
<td>


SFP+ SR bailed, 10g single rate

</td>
<td>


AFBR-700SDZ

</td>
</tr>
<tr>
<td>


Finisar

</td>
<td>


SFP+ LR bailed, 10g single rate

</td>
<td>


FTLX1471D3BCL

</td>
</tr>
</tbody>
</table>

82598-based adapters support all passive direct attach cables that comply with SFF-8431 v4.1 and SFF-8472 v10.4 specifications. Active direct attach cables are not supported.

Third party optic modules and cables referred to above are listed only for the purpose of highlighting third party specifications and potential compatibility, and are not recommendations or endorsements or sponsorship of any third party's product by Intel. Intel is not endorsing or promoting products made by any third party and the third party reference is provided only to share information regarding certain optic modules and cables with the above specifications. There may be other manufacturers or suppliers, producing or supplying optic modules and cables with similar or matching descriptions. Customers must use their own discretion and diligence to purchase optic modules and cables from any third party of their choice. Customers are solely responsible for assessing the suitability of the product and/or devices and for the selection of the vendor for purchasing any product. THE OPTIC MODULES AND CABLES REFERRED TO ABOVE ARE NOT WARRANTED OR SUPPORTED BY INTEL. INTEL ASSUMES NO LIABILITY WHATSOEVER, AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF SUCH THIRD PARTY PRODUCTS OR SELECTION OF VENDOR BY CUSTOMERS.

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

<a id="rst-max-vfs"></a>

### max_vfs

**Valid Range:** 1-63

This parameter adds support for SR-IOV. It causes the driver to spawn up to max_vfs worth of virtual functions. If the value is greater than 0 it will also force the VMDq parameter to be 1 or more.

NOTE: This parameter is only used on kernel 3.7.x and below. On kernel 3.8.x and above, use sysfs to enable VFs. Also, for Red Hat distributions, this parameter is only used on version 6.6 and older. For version 6.7 and newer, use sysfs. For example:



```text
#echo $num_vf_enabled > /sys/class/net/$dev/device/sriov_numvfs // enable VFs
#echo 0 > /sys/class/net/$dev/device/sriov_numvfs               //disable VFs
```

The parameters for the driver are referenced by position. Thus, if you have a dual port adapter, or more than one adapter in your system, and want N virtual functions per port, you must specify a number for each port with each parameter separated by a comma. For example:



```text
modprobe ixgbe max_vfs=4
```

This will spawn 4 VFs on the first port.



```text
modprobe ixgbe max_vfs=2,4
```

This will spawn 2 VFs on the first port and 4 VFs on the second port.

NOTE: Caution must be used in loading the driver with these parameters. Depending on your system configuration, number of slots, etc., it is impossible to predict in all cases where the positions would be on the command line.

NOTE: Neither the device nor the driver control how VFs are mapped into config space. Bus layout will vary by operating system. On operating systems that support it, you can check sysfs to find the mapping.

NOTE: When either SR-IOV mode or VMDq mode is enabled, hardware VLAN filtering and VLAN tag stripping/insertion will remain enabled. Please remove the old VLAN filter before the new VLAN filter is added. For example,



```text
ip link set eth0 vf 0 vlan 100 // set VLAN 100 for VF 0
ip link set eth0 vf 0 vlan 0   // Delete VLAN 100
ip link set eth0 vf 0 vlan 200 // set a new VLAN 200 for VF 0
```

With kernel 3.6, the driver supports the simultaneous usage of max_vfs and DCB features, subject to the constraints described below. Prior to kernel 3.6, the driver did not support the simultaneous operation of max_vfs greater than 0 and the DCB features (multiple traffic classes utilizing Priority Flow Control and Extended Transmission Selection).

When DCB is enabled, network traffic is transmitted and received through multiple traffic classes (packet buffers in the NIC). The traffic is associated with a specific class based on priority, which has a value of 0 through 7 used in the VLAN tag. When SR-IOV is not enabled, each traffic class is associated with a set of receive/transmit descriptor queue pairs. The number of queue pairs for a given traffic class depends on the hardware configuration. When SR-IOV is enabled, the descriptor queue pairs are grouped into pools. The Physical Function (PF) and each Virtual Function (VF) is allocated a pool of receive/transmit descriptor queue pairs. When multiple traffic classes are configured (for example, DCB is enabled), each pool contains a queue pair from each traffic class. When a single traffic class is configured in the hardware, the pools contain multiple queue pairs from the single traffic class.

The number of VFs that can be allocated depends on the number of traffic classes that can be enabled. The configurable number of traffic classes for each enabled VF is as follows: 0 - 15 VFs = Up to 8 traffic classes, depending on device support 16 - 31 VFs = Up to 4 traffic classes 32 - 63 VFs = 1 traffic class

When VFs are configured, the PF is allocated one pool as well. The PF supports the DCB features with the constraint that each traffic class will only use a single queue pair. When zero VFs are configured, the PF can support multiple queue pairs per traffic class.

<a id="rst-allow-unsupported-sfp"></a>

### allow_unsupported_sfp

**Valid Range:** 0,1

**Default Value:** 0 (disabled)

This parameter allows unsupported and untested SFP+ modules on 82599-based adapters, as long as the type of module is known to the driver.

<a id="rst-debug"></a>

### debug

**Valid Range:** 0-16 (0=none,...,16=all)

**Default Value:** 0

This parameter adjusts the level of debug messages displayed in the system logs.

<a id="rst-additional-features-and-configurations"></a>

## Additional Features and Configurations

<a id="rst-flow-control"></a>

### Flow Control

Ethernet Flow Control (IEEE 802.3x) can be configured with ethtool to enable receiving and transmitting pause frames for ixgbe. When transmit is enabled, pause frames are generated when the receive packet buffer crosses a predefined threshold. When receive is enabled, the transmit unit will halt for the time delay specified when a pause frame is received.

NOTE: You must have a flow control capable link partner.

Flow Control is enabled by default.

Use ethtool to change the flow control settings. To enable or disable Rx or Tx Flow Control:



```text
ethtool -A eth? rx <on|off> tx <on|off>
```

Note: This command only enables or disables Flow Control if auto-negotiation is disabled. If auto-negotiation is enabled, this command changes the parameters used for auto-negotiation with the link partner.

To enable or disable auto-negotiation:



```text
ethtool -s eth? autoneg <on|off>
```

Note: Flow Control auto-negotiation is part of link auto-negotiation. Depending on your device, you may not be able to change the auto-negotiation setting.

NOTE: For 82598 backplane cards entering 1 gigabit mode, flow control default behavior is changed to off. Flow control in 1 gigabit mode on these devices can lead to transmit hangs.

<a id="rst-intel-r-ethernet-flow-director"></a>

### Intel(R) Ethernet Flow Director

The Intel Ethernet Flow Director performs the following tasks:

- Directs receive packets according to their flows to different queues.

- Enables tight control on routing a flow in the platform.

- Matches flows and CPU cores for flow affinity.

- Supports multiple parameters for flexible flow classification and load balancing (in SFP mode only).

NOTE: Intel Ethernet Flow Director masking works in the opposite manner from subnet masking. In the following command:



```text
#ethtool -N eth11 flow-type ip4 src-ip 172.4.1.2 m 255.0.0.0 dst-ip \
172.21.1.1 m 255.128.0.0 action 31
```

The src-ip value that is written to the filter will be 0.4.1.2, not 172.0.0.0 as might be expected. Similarly, the dst-ip value written to the filter will be 0.21.1.1, not 172.0.0.0.

To enable or disable the Intel Ethernet Flow Director:



```text
# ethtool -K ethX ntuple <on|off>
```

When disabling ntuple filters, all the user programmed filters are flushed from the driver cache and hardware. All needed filters must be re-added when ntuple is re-enabled.

To add a filter that directs packet to queue 2, use -U or -N switch:



```text
# ethtool -N ethX flow-type tcp4 src-ip 192.168.10.1 dst-ip \
192.168.10.2 src-port 2000 dst-port 2001 action 2 [loc 1]
```

To see the list of filters currently present:



```text
# ethtool <-u|-n> ethX
```

<a id="rst-sideband-perfect-filters"></a>

### Sideband Perfect Filters

Sideband Perfect Filters are used to direct traffic that matches specified characteristics. They are enabled through ethtool's ntuple interface. To add a new filter use the following command:



```text
ethtool -U <device> flow-type <type> src-ip <ip> dst-ip <ip> src-port <port> \
dst-port <port> action <queue>
```

- **Where:**

  &lt;device&gt; - the ethernet device to program &lt;type&gt; - can be ip4, tcp4, udp4, or sctp4 &lt;ip&gt; - the IP address to match on &lt;port&gt; - the port number to match on &lt;queue&gt; - the queue to direct traffic towards (-1 discards the matched traffic)

Use the following command to delete a filter:



```text
ethtool -U <device> delete <N>
```

Where &lt;N&gt; is the filter id displayed when printing all the active filters, and may also have been specified using "loc &lt;N&gt;" when adding the filter.

The following example matches TCP traffic sent from 192.168.0.1, port 5300, directed to 192.168.0.5, port 80, and sends it to queue 7:



```text
ethtool -U enp130s0 flow-type tcp4 src-ip 192.168.0.1 dst-ip 192.168.0.5 \
src-port 5300 dst-port 80 action 7
```

For each flow-type, the programmed filters must all have the same matching input set. For example, issuing the following two commands is acceptable:



```text
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.5 src-port 55 action 10
```

Issuing the next two commands, however, is not acceptable, since the first specifies src-ip and the second specifies dst-ip:



```text
ethtool -U enp130s0 flow-type ip4 src-ip 192.168.0.1 src-port 5300 action 7
ethtool -U enp130s0 flow-type ip4 dst-ip 192.168.0.5 src-port 55 action 10
```

The second command will fail with an error. You may program multiple filters with the same fields, using different values, but, on one device, you may not program two TCP4 filters with different matching fields.

Matching on a sub-portion of a field is not supported by the ixgbe driver, thus partial mask fields are not supported.

To create filters that direct traffic to a specific Virtual Function, use the "user-def" parameter. Specify the user-def as a 64 bit value, where the lower 32 bits represents the queue number, while the next 8 bits represent which VF. Note that 0 is the PF, so the VF identifier is offset by 1. For example:



```text
... user-def 0x800000002 ...
```

specifies to direct traffic to Virtual Function 7 (8 minus 1) into queue 2 of that VF.

Note that these filters will not break internal routing rules, and will not route traffic that otherwise would not have been sent to the specified Virtual Function.

<a id="rst-jumbo-frames"></a>

### Jumbo Frames

Jumbo Frames support is enabled by changing the Maximum Transmission Unit (MTU) to a value larger than the default value of 1500.

Use the ifconfig command to increase the MTU size. For example, enter the following where &lt;x&gt; is the interface number:



```text
ifconfig eth<x> mtu 9000 up
```

Alternatively, you can use the ip command as follows:



```text
ip link set mtu 9000 dev eth<x>
ip link set up dev eth<x>
```

This setting is not saved across reboots. The setting change can be made permanent by adding 'MTU=9000' to the file:



```text
/etc/sysconfig/network-scripts/ifcfg-eth<x> // for RHEL
/etc/sysconfig/network/<config_file> // for SLES
```

NOTE: The maximum MTU setting for Jumbo Frames is 9710. This value coincides with the maximum Jumbo Frames size of 9728 bytes.

NOTE: This driver will attempt to use multiple page sized buffers to receive each jumbo packet. This should help to avoid buffer starvation issues when allocating receive packets.

NOTE: For 82599-based network connections, if you are enabling jumbo frames in a virtual function (VF), jumbo frames must first be enabled in the physical function (PF). The VF MTU setting cannot be larger than the PF MTU.

<a id="rst-nbase-t-support"></a>

### NBASE-T Support

The ixgbe driver supports NBASE-T on some devices. However, the advertisement of NBASE-T speeds is suppressed by default, to accommodate broken network switches which cannot cope with advertised NBASE-T speeds. Use the ethtool command to enable advertising NBASE-T speeds on devices which support it:



```text
ethtool -s eth? advertise 0x1800000001028
```

On Linux systems with INTERFACES(5), this can be specified as a pre-up command in /etc/network/interfaces so that the interface is always brought up with NBASE-T support, e.g.:



```text
iface eth? inet dhcp
     pre-up ethtool -s eth? advertise 0x1800000001028 || true
```

<a id="rst-generic-receive-offload-aka-gro"></a>

### Generic Receive Offload, aka GRO

The driver supports the in-kernel software implementation of GRO. GRO has shown that by coalescing Rx traffic into larger chunks of data, CPU utilization can be significantly reduced when under large Rx load. GRO is an evolution of the previously-used LRO interface. GRO is able to coalesce other protocols besides TCP. It's also safe to use with configurations that are problematic for LRO, namely bridging and iSCSI.

<a id="rst-data-center-bridging-dcb"></a>

### Data Center Bridging (DCB)

NOTE: The kernel assumes that TC0 is available, and will disable Priority Flow Control (PFC) on the device if TC0 is not available. To fix this, ensure TC0 is enabled when setting up DCB on your switch.

DCB is a configuration Quality of Service implementation in hardware. It uses the VLAN priority tag (802.1p) to filter traffic. That means that there are 8 different priorities that traffic can be filtered into. It also enables priority flow control (802.1Qbb) which can limit or eliminate the number of dropped packets during network stress. Bandwidth can be allocated to each of these priorities, which is enforced at the hardware level (802.1Qaz).

Adapter firmware implements LLDP and DCBX protocol agents as per 802.1AB and 802.1Qaz respectively. The firmware based DCBX agent runs in willing mode only and can accept settings from a DCBX capable peer. Software configuration of DCBX parameters via dcbtool/lldptool are not supported.

The ixgbe driver implements the DCB netlink interface layer to allow user-space to communicate with the driver and query DCB configuration for the port.

<a id="rst-ethtool"></a>

### ethtool

The driver utilizes the ethtool interface for driver configuration and diagnostics, as well as displaying statistical information. The latest ethtool version is required for this functionality. Download it at: [https://www.kernel.org/pub/software/network/ethtool/](<https://www.kernel.org/pub/software/network/ethtool/>)

<a id="rst-fcoe"></a>

### FCoE

The ixgbe driver supports Fiber Channel over Ethernet (FCoE) and Data Center Bridging (DCB). This code has no default effect on the regular driver operation. Configuring DCB and FCoE is outside the scope of this README. Refer to [http://www.open-fcoe.org/](<http://www.open-fcoe.org/>) for FCoE project information and contact [ixgbe-eedc@lists.sourceforge.net](<mailto:ixgbe-eedc@lists.sourceforge.net>) for DCB information.

<a id="rst-mac-and-vlan-anti-spoofing-feature"></a>

### MAC and VLAN anti-spoofing feature

When a malicious driver attempts to send a spoofed packet, it is dropped by the hardware and not transmitted.

An interrupt is sent to the PF driver notifying it of the spoof attempt. When a spoofed packet is detected, the PF driver will send the following message to the system log (displayed by the "dmesg" command):



```text
ixgbe ethX: ixgbe_spoof_check: n spoofed packets detected
```

where "x" is the PF interface number; and "n" is number of spoofed packets. NOTE: This feature can be disabled for a specific Virtual Function (VF):



```text
ip link set <pf dev> vf <vf id> spoofchk {off|on}
```

<a id="rst-ipsec-offload"></a>

### IPsec Offload

The ixgbe driver supports IPsec Hardware Offload.  When creating Security Associations with "ip xfrm ..." the 'offload' tag option can be used to register the IPsec SA with the driver in order to get higher throughput in the secure communications.

The offload is also supported for ixgbe's VFs, but the VF must be set as 'trusted' and the support must be enabled with:



```text
ethtool --set-priv-flags eth<x> vf-ipsec on
ip link set eth<x> vf <y> trust on
```

<a id="rst-known-issues-troubleshooting"></a>

## Known Issues/Troubleshooting

<a id="rst-enabling-sr-iov-in-a-64-bit-microsoft-windows-server-2012-r2-guest-os"></a>

### Enabling SR-IOV in a 64-bit Microsoft Windows Server 2012/R2 guest OS

Linux KVM Hypervisor/VMM supports direct assignment of a PCIe device to a VM. This includes traditional PCIe devices, as well as SR-IOV-capable devices based on the Intel Ethernet Controller XL710.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux Base Virtual Function Driver for Intel(R) 10G Ethernet

_Peios Kernel / Internals / Networking / device_drivers / ethernet / intel_

> Intel 10 Gigabit Virtual Function Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-linux-base-virtual-function-driver-for-intel-r-10g-ethernet"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Intel 10 Gigabit Virtual Function Linux driver. Copyright(c) 1999-2018 Intel Corporation.

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

- Known Issues

- Support

This driver supports 82599, X540, X550, and X552-based virtual function devices that can only be activated on kernels that support SR-IOV.

For questions related to hardware requirements, refer to the documentation supplied with your Intel adapter. All hardware requirements listed apply to use with Linux.

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver is compatible with devices based on the following:

> - Intel(R) Ethernet Controller 82598
>
> - Intel(R) Ethernet Controller 82599
>
> - Intel(R) Ethernet Controller X520
>
> - Intel(R) Ethernet Controller X540
>
> - Intel(R) Ethernet Controller x550
>
> - Intel(R) Ethernet Controller X552
>
> - Intel(R) Ethernet Controller X553

For information on how to identify your adapter, and for the latest Intel network drivers, refer to the Intel Support website: [https://www.intel.com/support](<https://www.intel.com/support>)

<a id="rst-known-issues-troubleshooting"></a>

## Known Issues/Troubleshooting

SR-IOV requires the correct platform and OS support.

The guest OS loading this driver must support MSI-X interrupts.

This driver is only supported as a loadable module at this time. Intel is not supplying patches against the kernel source to allow for static linking of the drivers.

VLANs: There is a limit of a total of 64 shared VLANs to 1 or more VFs.

<a id="rst-support"></a>

## Support

For general information, go to the Intel support website at: [https://www.intel.com/support/](<https://www.intel.com/support/>)

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [intel-wired-lan@lists.osuosl.org](<mailto:intel-wired-lan@lists.osuosl.org>).

---

# Linux kernel networking driver for Marvell's Octeon PCI Endpoint NIC

_Peios Kernel / Internals / Networking / device_drivers / ethernet / marvell_

> Network driver for Marvell's Octeon PCI EndPoint NIC. Copyright (c) 2020 Marvell International Ltd.

<a id="rst-linux-kernel-networking-driver-for-marvell-s-octeon-pci-endpoint-nic"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Network driver for Marvell's Octeon PCI EndPoint NIC. Copyright (c) 2020 Marvell International Ltd.

<a id="rst-contents"></a>

## Contents

- [Overview](<#rst-overview>)

- [Supported Devices](<#rst-supported-devices>)

- [Interface Control](<#rst-interface-control>)

<a id="rst-overview"></a>

## Overview

This driver implements networking functionality of Marvell's Octeon PCI EndPoint NIC.

<a id="rst-supported-devices"></a>

## Supported Devices

- **Currently, this driver support following devices:**

  - Network controller: Cavium, Inc. Device b100

  - Network controller: Cavium, Inc. Device b200

  - Network controller: Cavium, Inc. Device b400

  - Network controller: Cavium, Inc. Device b900

  - Network controller: Cavium, Inc. Device ba00

  - Network controller: Cavium, Inc. Device bc00

  - Network controller: Cavium, Inc. Device bd00

<a id="rst-interface-control"></a>

## Interface Control

Network Interface control like changing mtu, link speed, link down/up are done by writing command to mailbox command queue, a mailbox interface implemented through a reserved region in BAR4. This driver writes the commands into the mailbox and the firmware on the Octeon device processes them. The firmware also sends unsolicited notifications to driver for events suchs as link change, through notification queue implemented as part of mailbox interface.

---

# Linux kernel networking driver for Marvell's Octeon PCI Endpoint NIC VF

_Peios Kernel / Internals / Networking / device_drivers / ethernet / marvell_

> Network driver for Marvell's Octeon PCI EndPoint NIC VF. Copyright (c) 2020 Marvell International Ltd.

<a id="rst-linux-kernel-networking-driver-for-marvell-s-octeon-pci-endpoint-nic-vf"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Network driver for Marvell's Octeon PCI EndPoint NIC VF. Copyright (c) 2020 Marvell International Ltd.

<a id="rst-overview"></a>

## Overview

This driver implements networking functionality of Marvell's Octeon PCI EndPoint NIC VF.

<a id="rst-supported-devices"></a>

## Supported Devices

- **Currently, this driver support following devices:**

  - Network controller: Cavium, Inc. Device b203

  - Network controller: Cavium, Inc. Device b403

  - Network controller: Cavium, Inc. Device b103

  - Network controller: Cavium, Inc. Device b903

  - Network controller: Cavium, Inc. Device ba03

  - Network controller: Cavium, Inc. Device bc03

  - Network controller: Cavium, Inc. Device bd03

---

# Marvell OcteonTx2 RVU Kernel Drivers

_Peios Kernel / Internals / Networking / device_drivers / ethernet / marvell_

> Copyright (c) 2020 Marvell International Ltd.

<a id="rst-marvell-octeontx2-rvu-kernel-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Copyright (c) 2020 Marvell International Ltd.

<a id="rst-contents"></a>

## Contents

- [Overview](<#rst-overview>)

- [Drivers](<#rst-drivers>)

- [Basic packet flow](<#rst-basic-packet-flow>)

- [Devlink health reporters](<#rst-devlink-health-reporters>)

- [Quality of service](<#rst-quality-of-service>)

- [RVU representors](<#rst-rvu-representors>)

<a id="rst-overview"></a>

## Overview

Resource virtualization unit (RVU) on Marvell's OcteonTX2 SOC maps HW resources from the network, crypto and other functional blocks into PCI-compatible physical and virtual functions. Each functional block again has multiple local functions (LFs) for provisioning to PCI devices. RVU supports multiple PCIe SRIOV physical functions (PFs) and virtual functions (VFs). PF0 is called the administrative / admin function (AF) and has privileges to provision RVU functional block's LFs to each of the PF/VF.

- **RVU managed networking functional blocks**

  - Network pool or buffer allocator (NPA)

  - Network interface controller (NIX)

  - Network parser CAM (NPC)

  - Schedule/Synchronize/Order unit (SSO)

  - Loopback interface (LBK)

- **RVU managed non-networking functional blocks**

  - Crypto accelerator (CPT)

  - Scheduled timers unit (TIM)

  - Schedule/Synchronize/Order unit (SSO) Used for both networking and non networking usecases

- **Resource provisioning examples**

  - A PF/VF with NIX-LF &amp; NPA-LF resources works as a pure network device

  - A PF/VF with CPT-LF resource works as a pure crypto offload device.

RVU functional blocks are highly configurable as per software requirements.

- **Firmware setups following stuff before kernel boots**

  - Enables required number of RVU PFs based on number of physical links.

  - Number of VFs per PF are either static or configurable at compile time. Based on config, firmware assigns VFs to each of the PFs.

  - Also assigns MSIX vectors to each of PF and VFs.

  - These are not changed after kernel boot.

<a id="rst-drivers"></a>

## Drivers

Linux kernel will have multiple drivers registering to different PF and VFs of RVU. Wrt networking there will be 3 flavours of drivers.

<a id="rst-admin-function-driver"></a>

### Admin Function driver

As mentioned above RVU PF0 is called the admin function (AF), this driver supports resource provisioning and configuration of functional blocks. Doesn't handle any I/O. It sets up few basic stuff but most of the functionality is achieved via configuration requests from PFs and VFs.

PF/VFs communicates with AF via a shared memory region (mailbox). Upon receiving requests AF does resource provisioning and other HW configuration. AF is always attached to host kernel, but PFs and their VFs may be used by host kernel itself, or attached to VMs or to userspace applications like DPDK etc. So AF has to handle provisioning/configuration requests sent by any device from any domain.

- **AF driver also interacts with underlying firmware to**

  - Manage physical ethernet links ie CGX LMACs.

  - Retrieve information like speed, duplex, autoneg etc

  - Retrieve PHY EEPROM and stats.

  - Configure FEC, PAM modes

  - etc

- **From pure networking side AF driver supports following functionality.**

  - Map a physical link to a RVU PF to which a netdev is registered.

  - Attach NIX and NPA block LFs to RVU PF/VF which provide buffer pools, RQs, SQs for regular networking functionality.

  - Flow control (pause frames) enable/disable/config.

  - HW PTP timestamping related config.

  - NPC parser profile config, basically how to parse pkt and what info to extract.

  - NPC extract profile config, what to extract from the pkt to match data in MCAM entries.

  - Manage NPC MCAM entries, upon request can frame and install requested packet forwarding rules.

  - Defines receive side scaling (RSS) algorithms.

  - Defines segmentation offload algorithms (eg TSO)

  - VLAN stripping, capture and insertion config.

  - SSO and TIM blocks config which provide packet scheduling support.

  - Debugfs support, to check current resource provising, current status of NPA pools, NIX RQ, SQ and CQs, various stats etc which helps in debugging issues.

  - And many more.

<a id="rst-physical-function-driver"></a>

### Physical Function driver

This RVU PF handles IO, is mapped to a physical ethernet link and this driver registers a netdev. This supports SR-IOV. As said above this driver communicates with AF with a mailbox. To retrieve information from physical links this driver talks to AF and AF gets that info from firmware and responds back ie cannot talk to firmware directly.

Supports ethtool for configuring links, RSS, queue count, queue size, flow control, ntuple filters, dump PHY EEPROM, config FEC etc.

<a id="rst-virtual-function-driver"></a>

### Virtual Function driver

There are two types VFs, VFs that share the physical link with their parent SR-IOV PF and the VFs which work in pairs using internal HW loopback channels (LBK).

- **Type1:**

  - These VFs and their parent PF share a physical link and used for outside communication.

  - VFs cannot communicate with AF directly, they send mbox message to PF and PF forwards that to AF. AF after processing, responds back to PF and PF forwards the reply to VF.

  - From functionality point of view there is no difference between PF and VF as same type HW resources are attached to both. But user would be able to configure few stuff only from PF as PF is treated as owner/admin of the link.

- **Type2:**

  - RVU PF0 ie admin function creates these VFs and maps them to loopback block's channels.

  - A set of two VFs (VF0 &amp; VF1, VF2 &amp; VF3 .. so on) works as a pair ie pkts sent out of VF0 will be received by VF1 and vice versa.

  - These VFs can be used by applications or virtual machines to communicate between them without sending traffic outside. There is no switch present in HW, hence the support for loopback VFs.

  - These communicate directly with AF (PF0) via mbox.

Except for the IO channels or links used for packet reception and transmission there is no other difference between these VF types. AF driver takes care of IO channel mapping, hence same VF driver works for both types of devices.

<a id="rst-basic-packet-flow"></a>

## Basic packet flow

<a id="rst-ingress"></a>

### Ingress

1. CGX LMAC receives packet.

2. Forwards the packet to the NIX block.

3. Then submitted to NPC block for parsing and then MCAM lookup to get the destination RVU device.

4. NIX LF attached to the destination RVU device allocates a buffer from RQ mapped buffer pool of NPA block LF.

5. RQ may be selected by RSS or by configuring MCAM rule with a RQ number.

6. Packet is DMA'ed and driver is notified.

<a id="rst-egress"></a>

### Egress

1. Driver prepares a send descriptor and submits to SQ for transmission.

2. The SQ is already configured (by AF) to transmit on a specific link/channel.

3. The SQ descriptor ring is maintained in buffers allocated from SQ mapped pool of NPA block LF.

4. NIX block transmits the pkt on the designated channel.

5. NPC MCAM entries can be installed to divert pkt onto a different channel.

<a id="rst-devlink-health-reporters"></a>

## Devlink health reporters

<a id="rst-npa-reporters"></a>

### NPA Reporters

The NPA reporters are responsible for reporting and recovering the following group of errors:

1. GENERAL events

   - Error due to operation of unmapped PF.

   - Error due to disabled alloc/free for other HW blocks (NIX, SSO, TIM, DPI and AURA).

2. ERROR events

   - Fault due to NPA_AQ_INST_S read or NPA_AQ_RES_S write.

   - AQ Doorbell Error.

3. RAS events

   - RAS Error Reporting for NPA_AQ_INST_S/NPA_AQ_RES_S.

4. RVU events

   - Error due to unmapped slot.

Sample Output:



```text
~# devlink health
pci/0002:01:00.0:
  reporter hw_npa_intr
      state healthy error 2872 recover 2872 last_dump_date 2020-12-10 last_dump_time 09:39:09 grace_period 0 auto_recover true auto_dump true
  reporter hw_npa_gen
      state healthy error 2872 recover 2872 last_dump_date 2020-12-11 last_dump_time 04:43:04 grace_period 0 auto_recover true auto_dump true
  reporter hw_npa_err
      state healthy error 2871 recover 2871 last_dump_date 2020-12-10 last_dump_time 09:39:17 grace_period 0 auto_recover true auto_dump true
   reporter hw_npa_ras
      state healthy error 0 recover 0 last_dump_date 2020-12-10 last_dump_time 09:32:40 grace_period 0 auto_recover true auto_dump true
```

Each reporter dumps the

> - Error Type
>
> - Error Register value
>
> - Reason in words

For example:



```text
~# devlink health dump show  pci/0002:01:00.0 reporter hw_npa_gen
 NPA_AF_GENERAL:
         NPA General Interrupt Reg : 1
         NIX0: free disabled RX
~# devlink health dump show  pci/0002:01:00.0 reporter hw_npa_intr
 NPA_AF_RVU:
         NPA RVU Interrupt Reg : 1
         Unmap Slot Error
~# devlink health dump show  pci/0002:01:00.0 reporter hw_npa_err
 NPA_AF_ERR:
        NPA Error Interrupt Reg : 4096
        AQ Doorbell Error
```

<a id="rst-nix-reporters"></a>

### NIX Reporters

The NIX reporters are responsible for reporting and recovering the following group of errors:

1. GENERAL events

   - Receive mirror/multicast packet drop due to insufficient buffer.

   - SMQ Flush operation.

2. ERROR events

   - Memory Fault due to WQE read/write from multicast/mirror buffer.

   - Receive multicast/mirror replication list error.

   - Receive packet on an unmapped PF.

   - Fault due to NIX_AQ_INST_S read or NIX_AQ_RES_S write.

   - AQ Doorbell Error.

3. RAS events

   - RAS Error Reporting for NIX Receive Multicast/Mirror Entry Structure.

   - RAS Error Reporting for WQE/Packet Data read from Multicast/Mirror Buffer..

   - RAS Error Reporting for NIX_AQ_INST_S/NIX_AQ_RES_S.

4. RVU events

   - Error due to unmapped slot.

Sample Output:



```text
~# ./devlink health
pci/0002:01:00.0:
  reporter hw_npa_intr
    state healthy error 0 recover 0 grace_period 0 auto_recover true auto_dump true
  reporter hw_npa_gen
    state healthy error 0 recover 0 grace_period 0 auto_recover true auto_dump true
  reporter hw_npa_err
    state healthy error 0 recover 0 grace_period 0 auto_recover true auto_dump true
  reporter hw_npa_ras
    state healthy error 0 recover 0 grace_period 0 auto_recover true auto_dump true
  reporter hw_nix_intr
    state healthy error 1121 recover 1121 last_dump_date 2021-01-19 last_dump_time 05:42:26 grace_period 0 auto_recover true auto_dump true
  reporter hw_nix_gen
    state healthy error 949 recover 949 last_dump_date 2021-01-19 last_dump_time 05:42:43 grace_period 0 auto_recover true auto_dump true
  reporter hw_nix_err
    state healthy error 1147 recover 1147 last_dump_date 2021-01-19 last_dump_time 05:42:59 grace_period 0 auto_recover true auto_dump true
  reporter hw_nix_ras
    state healthy error 409 recover 409 last_dump_date 2021-01-19 last_dump_time 05:43:16 grace_period 0 auto_recover true auto_dump true
```

Each reporter dumps the

> - Error Type
>
> - Error Register value
>
> - Reason in words

For example:



```text
~# devlink health dump show pci/0002:01:00.0 reporter hw_nix_intr
 NIX_AF_RVU:
        NIX RVU Interrupt Reg : 1
        Unmap Slot Error
~# devlink health dump show pci/0002:01:00.0 reporter hw_nix_gen
 NIX_AF_GENERAL:
        NIX General Interrupt Reg : 1
        Rx multicast pkt drop
~# devlink health dump show pci/0002:01:00.0 reporter hw_nix_err
 NIX_AF_ERR:
        NIX Error Interrupt Reg : 64
        Rx on unmapped PF_FUNC
```

<a id="rst-quality-of-service"></a>

## Quality of service

<a id="rst-hardware-algorithms-used-in-scheduling"></a>

### Hardware algorithms used in scheduling

octeontx2 silicon and CN10K transmit interface consists of five transmit levels starting from SMQ/MDQ, TL4 to TL1. Each packet will traverse MDQ, TL4 to TL1 levels. Each level contains an array of queues to support scheduling and shaping. The hardware uses the below algorithms depending on the priority of scheduler queues. once the usercreates tc classes with different priorities, the driver configures schedulers allocated to the class with specified priority along with rate-limiting configuration.

1. Strict Priority

   > - Once packets are submitted to MDQ, hardware picks all active MDQs having different priority using strict priority.

2. Round Robin

   > - Active MDQs having the same priority level are chosen using round robin.

<a id="rst-setup-htb-offload"></a>

### Setup HTB offload

1. Enable HW TC offload on the interface:



   ```text
   # ethtool -K <interface> hw-tc-offload on
   ```

2. Crate htb root:



   ```text
   # tc qdisc add dev <interface> clsact
   # tc qdisc replace dev <interface> root handle 1: htb offload
   ```

3. Create tc classes with different priorities:



   ```text
   # tc class add dev <interface> parent 1: classid 1:1 htb rate 10Gbit prio 1

   # tc class add dev <interface> parent 1: classid 1:2 htb rate 10Gbit prio 7
   ```

4. Create tc classes with same priorities and different quantum:



   ```text
   # tc class add dev <interface> parent 1: classid 1:1 htb rate 10Gbit prio 2 quantum 409600

   # tc class add dev <interface> parent 1: classid 1:2 htb rate 10Gbit prio 2 quantum 188416

   # tc class add dev <interface> parent 1: classid 1:3 htb rate 10Gbit prio 2 quantum 32768
   ```

<a id="rst-rvu-representors"></a>

## RVU Representors

RVU representor driver adds support for creation of representor devices for RVU PFs' VFs in the system. Representor devices are created when user enables the switchdev mode. Switchdev mode can be enabled either before or after setting up SRIOV numVFs. All representor devices share a single NIXLF but each has a dedicated Rx/Tx queues. RVU PF representor driver registers a separate netdev for each Rx/Tx queue pair.

Current HW does not support built-in switch which can do L2 learning and forwarding packets between representee and representor. Hence, packet path between representee and it's representor is achieved by setting up appropriate NPC MCAM filters. Transmit packets matching these filters will be loopbacked through hardware loopback channel/interface (i.e, instead of sending them out of MAC interface). Which will again match the installed filters and will be forwarded. This way representee =&gt; representor and representor =&gt; representee packet path is achieved. These rules get installed when representors are created and gets active/deactivate based on the representor/representee interface state.

Usage example:

> - Change device to switchdev mode:
>
>
>
>   ```text
>   # devlink dev eswitch set pci/0002:1c:00.0 mode switchdev
>   ```
>
> - List of representor devices on the system:
>
>
>
>   ```text
>   # ip link show
>   Rpf1vf0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether f6:43:83:ee:26:21 brd ff:ff:ff:ff:ff:ff
>   Rpf1vf1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether 12:b2:54:0e:24:54 brd ff:ff:ff:ff:ff:ff
>   Rpf1vf2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether 4a:12:c4:4c:32:62 brd ff:ff:ff:ff:ff:ff
>   Rpf1vf3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether ca:cb:68:0e:e2:6e brd ff:ff:ff:ff:ff:ff
>   Rpf2vf0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000 link/ether 06:cc:ad:b4:f0:93 brd ff:ff:ff:ff:ff:ff
>   ```

To delete the representors devices from the system. Change the device to legacy mode.

> - Change device to legacy mode:
>
>
>
>   ```text
>   # devlink dev eswitch set pci/0002:1c:00.0 mode legacy
>   ```

RVU representors can be managed using devlink ports (see [Documentation/networking/devlink/devlink-port.rst](</kernel/internals/networking/devlink/devlink-port.md#rst-devlink-port>)) interface.

> - Show devlink ports of representors:
>
>
>
>   ```text
>   # devlink port
>   pci/0002:1c:00.0/0: type eth netdev Rpf1vf0 flavour physical port 0 splittable false
>   pci/0002:1c:00.0/1: type eth netdev Rpf1vf1 flavour pcivf controller 0 pfnum 1 vfnum 1 external false splittable false
>   pci/0002:1c:00.0/2: type eth netdev Rpf1vf2 flavour pcivf controller 0 pfnum 1 vfnum 2 external false splittable false
>   pci/0002:1c:00.0/3: type eth netdev Rpf1vf3 flavour pcivf controller 0 pfnum 1 vfnum 3 external false splittable false
>   ```

<a id="rst-function-attributes"></a>

## Function attributes

The RVU representor support function attributes for representors. Port function configuration of the representors are supported through devlink eswitch port.

<a id="rst-mac-address-setup"></a>

### MAC address setup

RVU representor driver support devlink port function attr mechanism to setup MAC address. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

> - To setup MAC address for port 2:
>
>
>
>   ```text
>   # devlink port function set pci/0002:1c:00.0/2 hw_addr 5c:a1:1b:5e:43:11
>   # devlink port show pci/0002:1c:00.0/2
>   pci/0002:1c:00.0/2: type eth netdev Rpf1vf2 flavour pcivf controller 0 pfnum 1 vfnum 2 external false splittable false
>   function:
>           hw_addr 5c:a1:1b:5e:43:11
>   ```

<a id="rst-tc-offload"></a>

## TC offload

The rvu representor driver implements support for offloading tc rules using port representors.

> - Drop packets with vlan id 3:
>
>
>
>   ```text
>   # tc filter add dev Rpf1vf0 protocol 802.1Q parent ffff: flower vlan_id 3 vlan_ethtype ipv4 skip_sw action drop
>   ```
>
> - Redirect packets with vlan id 5 and IPv4 packets to eth1, after stripping vlan header.:
>
>
>
>   ```text
>   # tc filter add dev Rpf1vf0 ingress protocol 802.1Q flower vlan_id 5 vlan_ethtype ipv4 skip_sw action vlan pop action mirred ingress redirect dev eth1
>   ```

---

# Mellanox ConnectX(R) mlx5 core VPI Network Driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mellanox / mlx5_

> Contents:

<a id="rst-mellanox-connectx-r-mlx5-core-vpi-network-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2019, Mellanox Technologies LTD.

**Copyright:** © 2020-2023, NVIDIA CORPORATION &amp; AFFILIATES. All rights reserved.

Contents:

- [Enabling the driver and kconfig options](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/ethernet/mellanox/mlx5/kconfig.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [Switchdev](</kernel/internals/networking/device-drivers-ethernet-mellanox-mlx5/switchdev.md>)
- [Tracepoints](</kernel/internals/networking/device-drivers-ethernet-mellanox-mlx5/tracepoints.md>)
- [Ethtool counters](</kernel/internals/networking/device-drivers-ethernet-mellanox-mlx5/counters.md>)

---

# Ethtool counters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mellanox / mlx5_

> Overview

<a id="rst-ethtool-counters"></a>

<!-- SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2023, NVIDIA CORPORATION &amp; AFFILIATES. All rights reserved.

<a id="rst-contents"></a>

## Contents

- [Overview](<#rst-overview>)

- [Groups](<#rst-groups>)

- [Types](<#rst-types>)

- [Descriptions](<#rst-descriptions>)

<a id="rst-overview"></a>

## Overview

There are several counter groups based on where the counter is being counted. In addition, each group of counters may have different counter types.

These counter groups are based on which component in a networking setup, illustrated below, that they describe:



```text
                                              ----------------------------------------
                                              |                                      |
----------------------------------------    ---------------------------------------- |
|              Hypervisor              |    |                  VM                  | |
|                                      |    |                                      | |
| -------------------  --------------- |    | -------------------  --------------- | |
| | Ethernet driver |  | RDMA driver | |    | | Ethernet driver |  | RDMA driver | | |
| -------------------  --------------- |    | -------------------  --------------- | |
|           |                 |        |    |           |                 |        | |
|           -------------------        |    |           -------------------        | |
|                   |                  |    |                   |                  |--
----------------------------------------    ----------------------------------------
                    |                                           |
        -------------               -----------------------------
        |                           |
     ------                      ------ ------ ------         ------      ------      ------
-----| PF |----------------------| VF |-| VF |-| VF |-----  --| PF |--- --| PF |--- --| PF |---
|    ------                      ------ ------ ------    |  | ------  | | ------  | | ------  |
|                                                        |  |         | |         | |         |
|                                                        |  |         | |         | |         |
|                                                        |  |         | |         | |         |
| eSwitch                                                |  | eSwitch | | eSwitch | | eSwitch |
----------------------------------------------------------  ----------- ----------- -----------
           -------------------------------------------------------------------------------
           |                                                                             |
           |                                                                             |
           | Uplink (no counters)                                                        |
           -------------------------------------------------------------------------------
                   ---------------------------------------------------------------
                   |                                                             |
                   |                                                             |
                   | MPFS (no counters)                                          |
                   ---------------------------------------------------------------
                                                 |
                                                 |
                                                 | Port
```

<a id="rst-groups"></a>

## Groups

- **Ring**

  Software counters populated by the driver stack.

- **Netdev**

  An aggregation of software ring counters.

- **vPort counters**

  Traffic counters and drops due to steering or no buffers. May indicate issues with NIC. These counters include Ethernet traffic counters (including Raw Ethernet) and RDMA/RoCE traffic counters.

- **Physical port counters**

  Counters that collect statistics about the PFs and VFs. May indicate issues with NIC, link, or network. This measuring point holds information on standardized counters like IEEE 802.3, RFC2863, RFC 2819, RFC 3635 and additional counters like flow control, FEC and more. Physical port counters are not exposed to virtual machines.

- **Priority Port Counters**

  A set of the physical port counters, per priority per port.

<a id="rst-types"></a>

## Types

Counters are divided into three types.

- **Traffic Informative Counters**

  Counters which count traffic. These counters can be used for load estimation or for general debug.

- **Traffic Acceleration Counters**

  Counters which count traffic that was accelerated by Mellanox driver or by hardware. The counters are an additional layer to the informative counter set, and the same traffic is counted in both informative and acceleration counters.

<a id="rst-accel"></a>



**[1]** Traffic acceleration counter.

- **Error Counters**

  Increment of these counters might indicate a problem. Each of these counters has an explanation and correction action.

Statistic can be fetched via the `ip link` or `ethtool` commands. `ethtool` provides more detailed information.:



```text
ip –s link show <if-name>
ethtool -S <if-name>
```

<a id="rst-descriptions"></a>

## Descriptions

XSK, PTP, and QoS counters that are similar to counters defined previously will not be separately listed. For example, `ptp_tx[i]_packets` will not be explicitly documented since `tx[i]_packets` describes the behavior of both counters, except `ptp_tx[i]_packets` is only counted when precision time protocol is used.

<a id="rst-ring-netdev-counter"></a>

### Ring / Netdev Counter

The following counters are available per ring or software port.

These counters provide information on the amount of traffic that was accelerated by the NIC. The counters are counting the accelerated traffic in addition to the standard counters which counts it (i.e. accelerated traffic is counted twice).

The counter names in the table below refers to both ring and port counters. The notation for ring counters includes the \[i\] index without the braces. The notation for port counters doesn't include the \[i\]. A counter name `rx[i]_packets` will be printed as `rx0_packets` for ring 0 and `rx_packets` for the software port.


<table>
<caption>Ring / Software Port Counter Table</caption>
<tbody>
<tr>
<td>


Counter

</td>
<td>


Description

</td>
<td>


Type

</td>
</tr>
<tr>
<td>


`rx[i]_packets`

</td>
<td>


The number of packets received on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_bytes`

</td>
<td>


The number of bytes received on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_packets`

</td>
<td>


The number of packets transmitted on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_bytes`

</td>
<td>


The number of bytes transmitted on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_recover`

</td>
<td>


The number of times the SQ was recovered.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_cqes`

</td>
<td>


Number of CQEs events on SQ issued on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_cqe_err`

</td>
<td>


The number of error CQEs encountered on the SQ for ring i.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_tso_packets`

</td>
<td>


The number of TSO packets transmitted on ring i <a id="rst-footnote-reference-1"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tso_bytes`

</td>
<td>


The number of TSO bytes transmitted on ring i <a id="rst-footnote-reference-2"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tso_inner_packets`

</td>
<td>


The number of TSO packets which are indicated to be carry internal encapsulation transmitted on ring i <a id="rst-footnote-reference-3"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tso_inner_bytes`

</td>
<td>


The number of TSO bytes which are indicated to be carry internal encapsulation transmitted on ring i <a id="rst-footnote-reference-4"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_gro_packets`

</td>
<td>


Number of received packets processed using hardware-accelerated GRO. The number of hardware GRO offloaded packets received on ring i. Only true GRO packets are counted: only packets that are in an SKB with a GRO count &gt; 1.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_gro_bytes`

</td>
<td>


Number of received bytes processed using hardware-accelerated GRO. The number of hardware GRO offloaded bytes received on ring i. Only true GRO packets are counted: only packets that are in an SKB with a GRO count &gt; 1.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_gro_skbs`

</td>
<td>


The number of GRO SKBs constructed from hardware-accelerated GRO. Only SKBs with a GRO count &gt; 1 are counted.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_gro_large_hds`

</td>
<td>


Number of receive packets using hardware-accelerated GRO that have large headers that require additional memory to be allocated.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_hds_nodata_packets`

</td>
<td>


Number of header only packets in header/data split mode <a id="rst-footnote-reference-5"></a>[1](#rst-accel).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_hds_nodata_bytes`

</td>
<td>


Number of bytes for header only packets in header/data split mode <a id="rst-footnote-reference-6"></a>[1](#rst-accel).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_hds_nosplit_packets`

</td>
<td>


Number of packets that were not split in header/data split mode. A packet will not get split when the hardware does not support its protocol splitting. An example such a protocol is ICMPv4/v6. Currently TCP and UDP with IPv4/IPv6 are supported for header/data split <a id="rst-footnote-reference-7"></a>[1](#rst-accel).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_hds_nosplit_bytes`

</td>
<td>


Number of bytes for packets that were not split in header/data split mode. A packet will not get split when the hardware does not support its protocol splitting. An example such a protocol is ICMPv4/v6. Currently TCP and UDP with IPv4/IPv6 are supported for header/data split <a id="rst-footnote-reference-8"></a>[1](#rst-accel).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_lro_packets`

</td>
<td>


The number of LRO packets received on ring i <a id="rst-footnote-reference-9"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_lro_bytes`

</td>
<td>


The number of LRO bytes received on ring i <a id="rst-footnote-reference-10"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_ecn_mark`

</td>
<td>


The number of received packets where the ECN mark was turned on.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_oversize_pkts_buffer`

</td>
<td>


The number of dropped received packets due to length which arrived to RQ and exceed software buffer size allocated by the device for incoming traffic. It might imply that the device MTU is larger than the software buffers size.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_oversize_pkts_sw_drop`

</td>
<td>


Number of received packets dropped in software because the CQE data is larger than the MTU size.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_csum_unnecessary`

</td>
<td>


Packets received with a `CHECKSUM_UNNECESSARY` on ring i <a id="rst-footnote-reference-11"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_csum_unnecessary_inner`

</td>
<td>


Packets received with inner encapsulation with a `CHECKSUM_UNNECESSARY` on ring i <a id="rst-footnote-reference-12"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_csum_none`

</td>
<td>


Packets received with a `CHECKSUM_NONE` on ring i <a id="rst-footnote-reference-13"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_csum_complete`

</td>
<td>


Packets received with a `CHECKSUM_COMPLETE` on ring i <a id="rst-footnote-reference-14"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_csum_complete_tail`

</td>
<td>


Number of received packets that had checksum calculation computed, potentially needed padding, and were able to do so with `CHECKSUM_PARTIAL`.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_csum_complete_tail_slow`

</td>
<td>


Number of received packets that need padding larger than eight bytes for the checksum.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_csum_partial`

</td>
<td>


Packets transmitted with a `CHECKSUM_PARTIAL` on ring i <a id="rst-footnote-reference-15"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_csum_partial_inner`

</td>
<td>


Packets transmitted with inner encapsulation with a `CHECKSUM_PARTIAL` on ring i <a id="rst-footnote-reference-16"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_csum_none`

</td>
<td>


Packets transmitted with no hardware checksum acceleration on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_stopped` / `tx_queue_stopped` <a id="rst-footnote-reference-17"></a>[2](#rst-ring-global)

</td>
<td>


Events where SQ was full on ring i. If this counter is increased, check the amount of buffers allocated for transmission.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_wake` / `tx_queue_wake` <a id="rst-footnote-reference-18"></a>[2](#rst-ring-global)

</td>
<td>


Events where SQ was full and has become not full on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_dropped` / `tx_queue_dropped` <a id="rst-footnote-reference-19"></a>[2](#rst-ring-global)

</td>
<td>


Packets transmitted that were dropped due to DMA mapping failure on ring i. If this counter is increased, check the amount of buffers allocated for transmission.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_nop`

</td>
<td>


The number of nop WQEs (empty WQEs) inserted to the SQ (related to ring i) due to the reach of the end of the cyclic buffer. When reaching near to the end of cyclic buffer the driver may add those empty WQEs to avoid handling a state the a WQE start in the end of the queue and ends in the beginning of the queue. This is a normal condition.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_timestamps`

</td>
<td>


Transmitted packets that were hardware timestamped at the device's DMA layer.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_added_vlan_packets`

</td>
<td>


The number of packets sent where vlan tag insertion was offloaded to the hardware.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_removed_vlan_packets`

</td>
<td>


The number of packets received where vlan tag stripping was offloaded to the hardware.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_wqe_err`

</td>
<td>


The number of wrong opcodes received on ring i.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_mpwqe_frag`

</td>
<td>


The number of WQEs that failed to allocate compound page and hence fragmented MPWQE’s (Multi Packet WQEs) were used on ring i. If this counter raise, it may suggest that there is no enough memory for large pages, the driver allocated fragmented pages. This is not abnormal condition.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_mpwqe_filler_cqes`

</td>
<td>


The number of filler CQEs events that were issued on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_mpwqe_filler_strides`

</td>
<td>


The number of strides consumed by filler CQEs on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_mpwqe_blks`

</td>
<td>


The number of send blocks processed from Multi-Packet WQEs (mpwqe).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_mpwqe_pkts`

</td>
<td>


The number of send packets processed from Multi-Packet WQEs (mpwqe).

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_cqe_compress_blks`

</td>
<td>


The number of receive blocks with CQE compression on ring i <a id="rst-footnote-reference-20"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_cqe_compress_pkts`

</td>
<td>


The number of receive packets with CQE compression on ring i <a id="rst-footnote-reference-21"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_arfs_add`

</td>
<td>


The number of aRFS flow rules added to the device for direct RQ steering on ring i <a id="rst-footnote-reference-22"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_arfs_request_in`

</td>
<td>


Number of flow rules that have been requested to move into ring i for direct RQ steering <a id="rst-footnote-reference-23"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_arfs_request_out`

</td>
<td>


Number of flow rules that have been requested to move out of ring i <a id="rst-footnote-reference-24"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_arfs_expired`

</td>
<td>


Number of flow rules that have been expired and removed <a id="rst-footnote-reference-25"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_arfs_err`

</td>
<td>


Number of flow rules that failed to be added to the flow table.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_recover`

</td>
<td>


The number of times the RQ was recovered.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_xmit_more`

</td>
<td>


The number of packets sent with `xmit_more` indication set on the skbuff (no doorbell).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`ch[i]_poll`

</td>
<td>


The number of invocations of NAPI poll of channel i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`ch[i]_arm`

</td>
<td>


The number of times the NAPI poll function completed and armed the completion queues on channel i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`ch[i]_aff_change`

</td>
<td>


The number of times the NAPI poll function explicitly stopped execution on a CPU due to a change in affinity, on channel i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`ch[i]_events`

</td>
<td>


The number of hard interrupt events on the completion queues of channel i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`ch[i]_eq_rearm`

</td>
<td>


The number of times the EQ was recovered.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`ch[i]_force_irq`

</td>
<td>


Number of times NAPI is triggered by XSK wakeups by posting a NOP to ICOSQ.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_congst_umr`

</td>
<td>


The number of times an outstanding UMR request is delayed due to congestion, on ring i.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_fast`

</td>
<td>


Number of successful fast path allocations.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_slow`

</td>
<td>


Number of slow path order-0 allocations.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_slow_high_order`

</td>
<td>


Number of slow path high order allocations.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_empty`

</td>
<td>


Counter is incremented when ptr ring is empty, so a slow path allocation was forced.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_refill`

</td>
<td>


Counter is incremented when an allocation which triggered a refill of the cache.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_alloc_waive`

</td>
<td>


Counter is incremented when pages obtained from the ptr ring that cannot be added to the cache due to a NUMA mismatch.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_recycle_cached`

</td>
<td>


Counter is incremented when recycling placed page in the page pool cache.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_recycle_cache_full`

</td>
<td>


Counter is incremented when page pool cache was full.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_recycle_ring`

</td>
<td>


Counter is incremented when page placed into the ptr ring.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_recycle_ring_full`

</td>
<td>


Counter is incremented when page released from page pool because the ptr ring was full.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pp_recycle_released_ref`

</td>
<td>


Counter is incremented when page released (and not recycled) because refcnt &gt; 1.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_xsk_buff_alloc_err`

</td>
<td>


The number of times allocating an skb or XSK buffer failed in the XSK RQ context.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_xmit`

</td>
<td>


The number of packets forwarded back to the port due to XDP program `XDP_TX` action (bouncing). these packets are not counted by other software counters. These packets are counted by physical port and vPort counters.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_mpwqe`

</td>
<td>


Number of multi-packet WQEs transmitted by the netdev and `XDP_TX`-ed by the netdev during the RQ context.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_inlnw`

</td>
<td>


Number of WQE data segments transmitted where the data could be inlined in the WQE and then `XDP_TX`-ed during the RQ context.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_nops`

</td>
<td>


Number of NOP WQEBBs (WQE building blocks) received posted to the XDP SQ.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_full`

</td>
<td>


The number of packets that should have been forwarded back to the port due to `XDP_TX` action but were dropped due to full tx queue. These packets are not counted by other software counters. These packets are counted by physical port and vPort counters. You may open more rx queues and spread traffic rx over all queues and/or increase rx ring size.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_err`

</td>
<td>


The number of times an `XDP_TX` error such as frame too long and frame too short occurred on `XDP_TX` ring of RX ring.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_tx_cqes` / `rx_xdp_tx_cqe` <a id="rst-footnote-reference-26"></a>[2](#rst-ring-global)

</td>
<td>


The number of completions received on the CQ of the `XDP_TX` ring.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_drop`

</td>
<td>


The number of packets dropped due to XDP program `XDP_DROP` action. these packets are not counted by other software counters. These packets are counted by physical port and vPort counters.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx[i]_xdp_redirect`

</td>
<td>


The number of times an XDP redirect action was triggered on ring i.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_xmit`

</td>
<td>


The number of packets redirected to the interface(due to XDP redirect). These packets are not counted by other software counters. These packets are counted by physical port and vPort counters.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_full`

</td>
<td>


The number of packets redirected to the interface(due to XDP redirect), but were dropped due to full tx queue. these packets are not counted by other software counters. you may enlarge tx queues.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_mpwqe`

</td>
<td>


Number of multi-packet WQEs offloaded onto the NIC that were `XDP_REDIRECT`-ed from other netdevs.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_inlnw`

</td>
<td>


Number of WQE data segments where the data could be inlined in the WQE where the data segments were `XDP_REDIRECT`-ed from other netdevs.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_nops`

</td>
<td>


Number of NOP WQEBBs (WQE building blocks) posted to the SQ that were `XDP_REDIRECT`-ed from other netdevs.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_err`

</td>
<td>


The number of packets redirected to the interface(due to XDP redirect) but were dropped due to error such as frame too long and frame too short.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_xdp_cqes`

</td>
<td>


The number of completions received for packets redirected to the interface(due to XDP redirect) on the CQ.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_xmit`

</td>
<td>


The number of packets transmitted using XSK zerocopy functionality.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_mpwqe`

</td>
<td>


Number of multi-packet WQEs offloaded onto the NIC that were `XDP_REDIRECT`-ed from other netdevs.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_inlnw`

</td>
<td>


Number of WQE data segments where the data could be inlined in the WQE that are transmitted using XSK zerocopy.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_full`

</td>
<td>


Number of times doorbell is rung in XSK zerocopy mode when SQ is full.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_err`

</td>
<td>


Number of errors that occurred in XSK zerocopy mode such as if the data size is larger than the MTU size.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_xsk_cqes`

</td>
<td>


Number of CQEs processed in XSK zerocopy mode.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_tls_ctx`

</td>
<td>


Number of TLS TX HW offload contexts added to device for encryption.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_tls_del`

</td>
<td>


Number of TLS TX HW offload contexts removed from device (connection closed).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_tls_pool_alloc`

</td>
<td>


Number of times a unit of work is successfully allocated in the TLS HW offload pool.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_tls_pool_free`

</td>
<td>


Number of times a unit of work is freed in the TLS HW offload pool.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_tls_ctx`

</td>
<td>


Number of TLS RX HW offload contexts added to device for decryption.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_tls_del`

</td>
<td>


Number of TLS RX HW offload contexts deleted from device (connection has finished).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_decrypted_packets`

</td>
<td>


Number of successfully decrypted RX packets which were part of a TLS stream.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_decrypted_bytes`

</td>
<td>


Number of TLS payload bytes in RX packets which were successfully decrypted.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_req_pkt`

</td>
<td>


Number of received TLS packets with a resync request.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_req_start`

</td>
<td>


Number of times the TLS async resync request was started.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_req_end`

</td>
<td>


Number of times the TLS async resync request properly ended with providing the HW tracked tcp-seq.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_req_skip`

</td>
<td>


Number of times the TLS async resync request procedure was started but not properly ended.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_res_ok`

</td>
<td>


Number of times the TLS resync response call to the driver was successfully handled.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_res_retry`

</td>
<td>


Number of times the TLS resync response call to the driver was reattempted when ICOSQ is full.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_tls_resync_res_skip`

</td>
<td>


Number of times the TLS resync response call to the driver was terminated unsuccessfully.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_tls_err`

</td>
<td>


Number of times when CQE TLS offload was problematic.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx[i]_tls_encrypted_packets`

</td>
<td>


The number of send packets that are TLS encrypted by the kernel.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_encrypted_bytes`

</td>
<td>


The number of send bytes that are TLS encrypted by the kernel.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_ooo`

</td>
<td>


Number of times out of order TLS SQE fragments were handled on ring i.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_dump_packets`

</td>
<td>


Number of TLS decrypted packets copied over from NIC over DMA.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_dump_bytes`

</td>
<td>


Number of TLS decrypted bytes copied over from NIC over DMA.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_resync_bytes`

</td>
<td>


Number of TLS bytes requested to be resynchronized in order to be decrypted.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_skip_no_sync_data`

</td>
<td>


Number of TLS send data that can safely be skipped / do not need to be decrypted.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx[i]_tls_drop_no_sync_data`

</td>
<td>


Number of TLS send data that were dropped due to retransmission of TLS data.

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`ptp_cq[i]_abort`

</td>
<td>


Number of times a CQE has to be skipped in precision time protocol due to a skew between the port timestamp and CQE timestamp being greater than 128 seconds.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`ptp_cq[i]_abort_abs_diff_ns`

</td>
<td>


Accumulation of time differences between the port timestamp and CQE timestamp when the difference is greater than 128 seconds in precision time protocol.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`ptp_cq[i]_late_cqe`

</td>
<td>


Number of times a CQE has been delivered on the PTP timestamping CQ when the CQE was not expected since a certain amount of time had elapsed where the device typically ensures not posting the CQE.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`ptp_cq[i]_lost_cqe`

</td>
<td>


Number of times a CQE is expected to not be delivered on the PTP timestamping CQE by the device due to a time delta elapsing. If such a CQE is somehow delivered, `ptp_cq[i]_late_cqe` is incremented.

</td>
<td>


Error

</td>
</tr>
</tbody>
</table>

<a id="rst-ring-global"></a>



**[2]** The corresponding ring and global counters do not share the same name (i.e. do not follow the common naming scheme).

<a id="rst-vport-counters"></a>

### vPort Counters

Counters on the NIC port that is connected to a eSwitch.


<table>
<caption>vPort Counter Table</caption>
<tbody>
<tr>
<td>


Counter

</td>
<td>


Description

</td>
<td>


Type

</td>
</tr>
<tr>
<td>


`rx_vport_unicast_packets`

</td>
<td>


Unicast packets received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_unicast_bytes`

</td>
<td>


Unicast bytes received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_unicast_packets`

</td>
<td>


Unicast packets transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_unicast_bytes`

</td>
<td>


Unicast bytes transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_multicast_packets`

</td>
<td>


Multicast packets received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_multicast_bytes`

</td>
<td>


Multicast bytes received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_multicast_packets`

</td>
<td>


Multicast packets transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_multicast_bytes`

</td>
<td>


Multicast bytes transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_broadcast_packets`

</td>
<td>


Broadcast packets received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_broadcast_bytes`

</td>
<td>


Broadcast bytes received, steered to a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_broadcast_packets`

</td>
<td>


Broadcast packets transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_vport_broadcast_bytes`

</td>
<td>


Broadcast bytes transmitted, steered from a port including Raw Ethernet QP/DPDK traffic, excluding RDMA traffic.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_vport_rdma_unicast_packets`

</td>
<td>


RDMA unicast packets received, steered to a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-27"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_vport_rdma_unicast_bytes`

</td>
<td>


RDMA unicast bytes received, steered to a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-28"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_vport_rdma_unicast_packets`

</td>
<td>


RDMA unicast packets transmitted, steered from a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-29"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_vport_rdma_unicast_bytes`

</td>
<td>


RDMA unicast bytes transmitted, steered from a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-30"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_vport_rdma_multicast_packets`

</td>
<td>


RDMA multicast packets received, steered to a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-31"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_vport_rdma_multicast_bytes`

</td>
<td>


RDMA multicast bytes received, steered to a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-32"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_vport_rdma_multicast_packets`

</td>
<td>


RDMA multicast packets transmitted, steered from a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-33"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`tx_vport_rdma_multicast_bytes`

</td>
<td>


RDMA multicast bytes transmitted, steered from a port (counters counts RoCE/UD/RC traffic) <a id="rst-footnote-reference-34"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`vport_loopback_packets`

</td>
<td>


Unicast, multicast and broadcast packets that were loop-back (received and transmitted), IB/Eth  <a id="rst-footnote-reference-35"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`vport_loopback_bytes`

</td>
<td>


Unicast, multicast and broadcast bytes that were loop-back (received and transmitted), IB/Eth  <a id="rst-footnote-reference-36"></a>[1](#rst-accel).

</td>
<td>


Acceleration

</td>
</tr>
<tr>
<td>


`rx_steer_missed_packets`

</td>
<td>


Number of packets that was received by the NIC, however was discarded because it did not match any flow in the NIC flow table.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_packets`

</td>
<td>


Representor only: packets received, that were handled by the hypervisor.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_bytes`

</td>
<td>


Representor only: bytes received, that were handled by the hypervisor.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_packets`

</td>
<td>


Representor only: packets transmitted, that were handled by the hypervisor.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_bytes`

</td>
<td>


Representor only: bytes transmitted, that were handled by the hypervisor.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`dev_internal_queue_oob`

</td>
<td>


The number of dropped packets due to lack of receive WQEs for an internal device RQ.

</td>
<td>


Error

</td>
</tr>
</tbody>
</table>

<a id="rst-physical-port-counters"></a>

### Physical Port Counters

The physical port counters are the counters on the external port connecting the adapter to the network. This measuring point holds information on standardized counters like IEEE 802.3, RFC2863, RFC 2819, RFC 3635 and additional counters like flow control, FEC and more.


<table>
<caption>Physical Port Counter Table</caption>
<tbody>
<tr>
<td>


Counter

</td>
<td>


Description

</td>
<td>


Type

</td>
</tr>
<tr>
<td>


`rx_packets_phy`

</td>
<td>


The number of packets received on the physical port. This counter doesn’t include packets that were discarded due to FCS, frame size and similar errors.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_packets_phy`

</td>
<td>


The number of packets transmitted on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_bytes_phy`

</td>
<td>


The number of bytes received on the physical port, including Ethernet header and FCS.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_bytes_phy`

</td>
<td>


The number of bytes transmitted on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_multicast_phy`

</td>
<td>


The number of multicast packets received on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_multicast_phy`

</td>
<td>


The number of multicast packets transmitted on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_broadcast_phy`

</td>
<td>


The number of broadcast packets received on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_broadcast_phy`

</td>
<td>


The number of broadcast packets transmitted on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_crc_errors_phy`

</td>
<td>


The number of dropped received packets due to FCS (Frame Check Sequence) error on the physical port. If this counter is increased in high rate, check the link quality using `rx_symbol_error_phy` and `rx_corrected_bits_phy` counters below.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_in_range_len_errors_phy`

</td>
<td>


The number of received packets dropped due to length/type errors on a physical port.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_out_of_range_len_phy`

</td>
<td>


The number of received packets dropped due to length greater than allowed on a physical port. If this counter is increasing, it implies that the peer connected to the adapter has a larger MTU configured. Using same MTU configuration shall resolve this issue.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_oversize_pkts_phy`

</td>
<td>


The number of dropped received packets due to length which exceed MTU size on a physical port. If this counter is increasing, it implies that the peer connected to the adapter has a larger MTU configured. Using same MTU configuration shall resolve this issue.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_symbol_err_phy`

</td>
<td>


The number of received packets dropped due to physical coding errors (symbol errors) on a physical port.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_mac_control_phy`

</td>
<td>


The number of MAC control packets received on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_mac_control_phy`

</td>
<td>


The number of MAC control packets transmitted on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pause_ctrl_phy`

</td>
<td>


The number of link layer pause packets received on a physical port. If this counter is increasing, it implies that the network is congested and cannot absorb the traffic coming from to the adapter.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_pause_ctrl_phy`

</td>
<td>


The number of link layer pause packets transmitted on a physical port. If this counter is increasing, it implies that the NIC is congested and cannot absorb the traffic coming from the network.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_unsupported_op_phy`

</td>
<td>


The number of MAC control packets received with unsupported opcode on a physical port.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_discards_phy`

</td>
<td>


The number of received packets dropped due to lack of buffers on a physical port. If this counter is increasing, it implies that the adapter is congested and cannot absorb the traffic coming from the network.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx_discards_phy`

</td>
<td>


The number of packets which were discarded on transmission, even no errors were detected. the drop might occur due to link in down state, head of line drop, pause from the network, etc.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx_errors_phy`

</td>
<td>


The number of transmitted packets dropped due to a length which exceed MTU size on a physical port.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_undersize_pkts_phy`

</td>
<td>


The number of received packets dropped due to length which is shorter than 64 bytes on a physical port. If this counter is increasing, it implies that the peer connected to the adapter has a non-standard MTU configured or malformed packet had arrived.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_fragments_phy`

</td>
<td>


The number of received packets dropped due to a length which is shorter than 64 bytes and has FCS error on a physical port. If this counter is increasing, it implies that the peer connected to the adapter has a non-standard MTU configured.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_jabbers_phy`

</td>
<td>


The number of received packets d due to a length which is longer than 64 bytes and had FCS error on a physical port.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_64_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 64 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_65_to_127_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 65 to 127 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_128_to_255_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 128 to 255 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_256_to_511_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 256 to 512 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_512_to_1023_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 512 to 1023 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_1024_to_1518_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 1024 to 1518 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_1519_to_2047_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 1519 to 2047 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_2048_to_4095_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 2048 to 4095 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_4096_to_8191_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 4096 to 8191 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_8192_to_10239_bytes_phy`

</td>
<td>


The number of packets received on the physical port with size of 8192 to 10239 bytes.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`link_down_events_phy`

</td>
<td>


The number of times where the link operative state changed to down. In case this counter is increasing it may imply on port flapping. You may need to replace the cable/transceiver.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`total_success_recovery_phy`

</td>
<td>


The number of total successful recovery events of any type during ports reset cycle.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_out_of_buffer`

</td>
<td>


Number of times receive queue had no software buffers allocated for the adapter's incoming traffic.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`module_bus_stuck`

</td>
<td>


The number of times that module's I<sup>2</sup>C bus (data or clock) short-wire was detected. You may need to replace the cable/transceiver.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`module_high_temp`

</td>
<td>


The number of times that the module temperature was too high. If this issue persist, you may need to check the ambient temperature or replace the cable/transceiver module.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`module_bad_shorted`

</td>
<td>


The number of times that the module cables were shorted. You may need to replace the cable/transceiver module.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`module_unplug`

</td>
<td>


The number of times that module was ejected.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_buffer_passed_thres_phy`

</td>
<td>


The number of events where the port receive buffer was over 85% full.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_pause_storm_warning_events`

</td>
<td>


The number of times the device was sending pauses for a long period of time.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_pause_storm_error_events`

</td>
<td>


The number of times the device was sending pauses for a long period of time, reaching time out and disabling transmission of pause frames. on the period where pause frames were disabled, drop could have been occurred.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx[i]_buff_alloc_err`

</td>
<td>


Failed to allocate a buffer to received packet (or SKB) on ring i.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_bits_phy`

</td>
<td>


This counter provides information on the total amount of traffic that could have been received and can be used as a guideline to measure the ratio of errored traffic in `rx_pcs_symbol_err_phy` and `rx_corrected_bits_phy`.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_pcs_symbol_err_phy`

</td>
<td>


This counter counts the number of symbol errors that wasn’t corrected by FEC correction algorithm or that FEC algorithm was not active on this interface. If this counter is increasing, it implies that the link between the NIC and the network is suffering from high BER, and that traffic is lost. You may need to replace the cable/transceiver. The error rate is the number of `rx_pcs_symbol_err_phy` divided by the number of `rx_bits_phy` on a specific time frame.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_corrected_bits_phy`

</td>
<td>


The number of corrected bits on this port according to active FEC (RS/FC). If this counter is increasing, it implies that the link between the NIC and the network is suffering from high BER. The corrected bit rate is the number of `rx_corrected_bits_phy` divided by the number of `rx_bits_phy` on a specific time frame.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_err_lane_[l]_phy`

</td>
<td>


This counter counts the number of physical raw errors per lane l index. The counter counts errors before FEC corrections. If this counter is increasing, it implies that the link between the NIC and the network is suffering from high BER, and that traffic might be lost. You may need to replace the cable/transceiver. Please check in accordance with `rx_corrected_bits_phy`.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`rx_global_pause`

</td>
<td>


The number of pause packets received on the physical port. If this counter is increasing, it implies that the network is congested and cannot absorb the traffic coming from the adapter. Note: This counter is only enabled when global pause mode is enabled.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_global_pause_duration`

</td>
<td>


The duration of pause received (in microSec) on the physical port. The counter represents the time the port did not send any traffic. If this counter is increasing, it implies that the network is congested and cannot absorb the traffic coming from the adapter. Note: This counter is only enabled when global pause mode is enabled.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_global_pause`

</td>
<td>


The number of pause packets transmitted on a physical port. If this counter is increasing, it implies that the adapter is congested and cannot absorb the traffic coming from the network. Note: This counter is only enabled when global pause mode is enabled.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_global_pause_duration`

</td>
<td>


The duration of pause transmitter (in microSec) on the physical port. Note: This counter is only enabled when global pause mode is enabled.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_global_pause_transition`

</td>
<td>


The number of times a transition from Xoff to Xon on the physical port has occurred. Note: This counter is only enabled when global pause mode is enabled.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_if_down_packets`

</td>
<td>


The number of received packets that were dropped due to interface down.

</td>
<td>


Informative

</td>
</tr>
</tbody>
</table>

<a id="rst-priority-port-counters"></a>

### Priority Port Counters

The following counters are physical port counters that are counted per L2 priority (0-7).

**Note:** `p` in the counter name represents the priority.


<table>
<caption>Priority Port Counter Table</caption>
<tbody>
<tr>
<td>


Counter

</td>
<td>


Description

</td>
<td>


Type

</td>
</tr>
<tr>
<td>


`rx_prio[p]_bytes`

</td>
<td>


The number of bytes received with priority p on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_packets`

</td>
<td>


The number of packets received with priority p on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_prio[p]_bytes`

</td>
<td>


The number of bytes transmitted on priority p on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_prio[p]_packets`

</td>
<td>


The number of packets transmitted on priority p on the physical port.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_pause`

</td>
<td>


The number of pause packets received with priority p on a physical port. If this counter is increasing, it implies that the network is congested and cannot absorb the traffic coming from the adapter. Note: This counter is available only if PFC was enabled on priority p.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_pause_duration`

</td>
<td>


The duration of pause received (in microSec) on priority p on the physical port. The counter represents the time the port did not send any traffic on this priority. If this counter is increasing, it implies that the network is congested and cannot absorb the traffic coming from the adapter. Note: This counter is available only if PFC was enabled on priority p.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_pause_transition`

</td>
<td>


The number of times a transition from Xoff to Xon on priority p on the physical port has occurred. Note: This counter is available only if PFC was enabled on priority p.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_prio[p]_pause`

</td>
<td>


The number of pause packets transmitted on priority p on a physical port. If this counter is increasing, it implies that the adapter is congested and cannot absorb the traffic coming from the network. Note: This counter is available only if PFC was enabled on priority p.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`tx_prio[p]_pause_duration`

</td>
<td>


The duration of pause transmitter (in microSec) on priority p on the physical port. Note: This counter is available only if PFC was enabled on priority p.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_buf_discard`

</td>
<td>


The number of packets discarded by device due to lack of per host receive buffers.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_cong_discard`

</td>
<td>


The number of packets discarded by device due to per host congestion.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_marked`

</td>
<td>


The number of packets ecn marked by device due to per host congestion.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`rx_prio[p]_discards`

</td>
<td>


The number of packets discarded by device due to lack of receive buffers.

</td>
<td>


Informative

</td>
</tr>
</tbody>
</table>

<a id="rst-device-counters"></a>

### Device Counters


<table>
<caption>Device Counter Table</caption>
<tbody>
<tr>
<td>


Counter

</td>
<td>


Description

</td>
<td>


Type

</td>
</tr>
<tr>
<td>


`rx_pci_signal_integrity`

</td>
<td>


Counts physical layer PCIe signal integrity errors, the number of transitions to recovery due to Framing errors and CRC (dlp and tlp). If this counter is raising, try moving the adapter card to a different slot to rule out a bad PCI slot. Validate that you are running with the latest firmware available and latest server BIOS version.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`tx_pci_signal_integrity`

</td>
<td>


Counts physical layer PCIe signal integrity errors, the number of transition to recovery initiated by the other side (moving to recovery due to getting TS/EIEOS). If this counter is raising, try moving the adapter card to a different slot to rule out a bad PCI slot. Validate that you are running with the latest firmware available and latest server BIOS version.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`outbound_pci_buffer_overflow`

</td>
<td>


The number of packets dropped due to pci buffer overflow. If this counter is raising in high rate, it might indicate that the receive traffic rate for a host is larger than the PCIe bus and therefore a congestion occurs.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`outbound_pci_stalled_rd`

</td>
<td>


The percentage (in the range 0...100) of time within the last second that the NIC had outbound non-posted reads requests but could not perform the operation due to insufficient posted credits.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`outbound_pci_stalled_wr`

</td>
<td>


The percentage (in the range 0...100) of time within the last second that the NIC had outbound posted writes requests but could not perform the operation due to insufficient posted credits.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`outbound_pci_stalled_rd_events`

</td>
<td>


The number of seconds where `outbound_pci_stalled_rd` was above 30%.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`outbound_pci_stalled_wr_events`

</td>
<td>


The number of seconds where `outbound_pci_stalled_wr` was above 30%.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`dev_out_of_buffer`

</td>
<td>


The number of times the device owned queue had not enough buffers allocated.

</td>
<td>


Error

</td>
</tr>
<tr>
<td>


`pci_bw_inbound_high`

</td>
<td>


The number of times the device crossed the high inbound pcie bandwidth threshold. To be compared to pci_bw_inbound_low to check if the device is in a congested state. If pci_bw_inbound_high == pci_bw_inbound_low then the device is not congested. If pci_bw_inbound_high &gt; pci_bw_inbound_low then the device is congested.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`pci_bw_inbound_low`

</td>
<td>


The number of times the device crossed the low inbound PCIe bandwidth threshold. To be compared to pci_bw_inbound_high to check if the device is in a congested state. If pci_bw_inbound_high == pci_bw_inbound_low then the device is not congested. If pci_bw_inbound_high &gt; pci_bw_inbound_low then the device is congested.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`pci_bw_outbound_high`

</td>
<td>


The number of times the device crossed the high outbound pcie bandwidth threshold. To be compared to pci_bw_outbound_low to check if the device is in a congested state. If pci_bw_outbound_high == pci_bw_outbound_low then the device is not congested. If pci_bw_outbound_high &gt; pci_bw_outbound_low then the device is congested.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`pci_bw_outbound_low`

</td>
<td>


The number of times the device crossed the low outbound PCIe bandwidth threshold. To be compared to pci_bw_outbound_high to check if the device is in a congested state. If pci_bw_outbound_high == pci_bw_outbound_low then the device is not congested. If pci_bw_outbound_high &gt; pci_bw_outbound_low then the device is congested.

</td>
<td>


Informative

</td>
</tr>
<tr>
<td>


`pci_bw_stale_event`

</td>
<td>


The number of times the device fired a PCIe congestion event but on query there was no change in state.

</td>
<td>


Informative

</td>
</tr>
</tbody>
</table>

---

# Enabling the driver and kconfig options

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mellanox / mlx5_

> CONFIG_MLX5_BRIDGE=(y/n)

<a id="rst-enabling-the-driver-and-kconfig-options"></a>

<!-- SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2023, NVIDIA CORPORATION &amp; AFFILIATES. All rights reserved.

mlx5 core is modular and most of the major mlx5 core driver features can be selected (compiled in/out)<br>
at build time via kernel Kconfig flags.<br>
Basic features, ethernet net device rx/tx offloads and XDP, are available with the most basic flags<br>
CONFIG\_MLX5\_CORE=y/m and CONFIG\_MLX5\_CORE\_EN=y.<br>
For the list of advanced features, please see below.

<strong>CONFIG\_MLX5\_BRIDGE=(y/n)</strong>

Enable [Ethernet Bridging (BRIDGE) offloading support](</kernel/internals/networking/device-drivers-ethernet-mellanox-mlx5/switchdev.md#rst-mlx5-bridge-offload>).<br>
This will provide the ability to add representors of mlx5 uplink and VF<br>
ports to Bridge and offloading rules for traffic between such ports.<br>
Supports VLANs (trunk and access modes).

<strong>CONFIG\_MLX5\_CORE=(y/m/n)</strong> (module mlx5\_core.ko)

The driver can be enabled by choosing CONFIG\_MLX5\_CORE=y/m in kernel config.<br>
This will provide mlx5 core driver for mlx5 ulps to interface with (mlx5e, mlx5\_ib).

<strong>CONFIG\_MLX5\_CORE\_EN=(y/n)</strong>

Choosing this option will allow basic ethernet netdevice support with all of the standard rx/tx offloads.<br>
mlx5e is the mlx5 ulp driver which provides netdevice kernel interface, when chosen, mlx5e will be<br>
built-in into mlx5\_core.ko.

<strong>CONFIG\_MLX5\_CORE\_EN\_DCB=(y/n)</strong>:

Enables [Data Center Bridging (DCB) Support](<https://enterprise-support.nvidia.com/s/article/howto-auto-config-pfc-and-ets-on-connectx-4-via-lldp-dcbx>)<a id="rst-data-center-bridging-dcb-support"></a>.

<strong>CONFIG\_MLX5\_CORE\_IPOIB=(y/n)</strong>

IPoIB offloads &amp; acceleration support.<br>
Requires CONFIG\_MLX5\_CORE\_EN to provide an accelerated interface for the rdma<br>
IPoIB ulp netdevice.

<strong>CONFIG\_MLX5\_CLS\_ACT=(y/n)</strong>

Enables offload support for TC classifier action (NET\_CLS\_ACT).<br>
Works in both native NIC mode and Switchdev SRIOV mode.<br>
Flow-based classifiers, such as those registered through<br>
`tc-flower(8)`, are processed by the device, rather than the<br>
host. Actions that would then overwrite matching classification<br>
results would then be instant due to the offload.

<strong>CONFIG\_MLX5\_EN\_ARFS=(y/n)</strong>

Enables Hardware-accelerated receive flow steering (arfs) support, and ntuple filtering.<br>
[https://enterprise-support.nvidia.com/s/article/howto-configure-arfs-on-connectx-4](<https://enterprise-support.nvidia.com/s/article/howto-configure-arfs-on-connectx-4>)

<strong>CONFIG\_MLX5\_EN\_IPSEC=(y/n)</strong>

Enables [IPSec XFRM cryptography-offload acceleration](</kernel/internals/networking/xfrm/xfrm-device.md#rst-xfrm-device>).

<strong>CONFIG\_MLX5\_MACSEC=(y/n)</strong>

Build support for MACsec cryptography-offload acceleration in the NIC.

<strong>CONFIG\_MLX5\_EN\_RXNFC=(y/n)</strong>

Enables ethtool receive network flow classification, which allows user defined<br>
flow rules to direct traffic into arbitrary rx queue via ethtool set/get\_rxnfc API.

<strong>CONFIG\_MLX5\_EN\_TLS=(y/n)</strong>

TLS cryptography-offload acceleration.

<strong>CONFIG\_MLX5\_ESWITCH=(y/n)</strong>

Ethernet SRIOV E-Switch support in ConnectX NIC. E-Switch provides internal SRIOV packet steering<br>
and switching for the enabled VFs and PF in two available modes:<br>
&nbsp;&nbsp;&nbsp;&nbsp;1\) [Legacy SRIOV mode (L2 mac vlan steering based)](<https://enterprise-support.nvidia.com/s/article/HowTo-Configure-SR-IOV-for-ConnectX-4-ConnectX-5-ConnectX-6-with-KVM-Ethernet>)<a id="rst-legacy-sriov-mode-l2-mac-vlan-steering-based"></a>.<br>
&nbsp;&nbsp;&nbsp;&nbsp;2\) [Switchdev mode (eswitch offloads)](</kernel/internals/networking/switchdev.md#rst-switchdev>).

<strong>CONFIG\_MLX5\_FPGA=(y/n)</strong>

Build support for the Innova family of network cards by Mellanox Technologies.<br>
Innova network cards are comprised of a ConnectX chip and an FPGA chip on one board.<br>
If you select this option, the mlx5\_core driver will include the Innova FPGA core and allow<br>
building sandbox-specific client drivers.

<strong>CONFIG\_MLX5\_INFINIBAND=(y/n/m)</strong> (module mlx5\_ib.ko)

Provides low-level InfiniBand/RDMA and [RoCE](<https://enterprise-support.nvidia.com/s/article/recommended-network-configuration-examples-for-roce-deployment>)<a id="rst-roce"></a> support.

<strong>CONFIG\_MLX5\_MPFS=(y/n)</strong>

Ethernet Multi-Physical Function Switch (MPFS) support in ConnectX NIC.<br>
MPFs is required for when [Multi-Host](<https://www.nvidia.com/en-us/networking/multi-host/>)<a id="rst-multi-host"></a> configuration is enabled to allow passing<br>
user configured unicast MAC addresses to the requesting PF.

<strong>CONFIG\_MLX5\_SF=(y/n)</strong>

Build support for subfunction.<br>
Subfunctons are more light weight than PCI SRIOV VFs. Choosing this option<br>
will enable support for creating subfunction devices.

<strong>CONFIG\_MLX5\_SF\_MANAGER=(y/n)</strong>

Build support for subfuction port in the NIC. A Mellanox subfunction<br>
port is managed through devlink.  A subfunction supports RDMA, netdevice<br>
and vdpa device. It is similar to a SRIOV VF but it doesn't require<br>
SRIOV support.

<strong>CONFIG\_MLX5\_SW\_STEERING=(y/n)</strong>

Build support for software-managed steering in the NIC.

<strong>CONFIG\_MLX5\_HW\_STEERING=(y/n)</strong>

Build support for hardware-managed steering in the NIC.

<strong>CONFIG\_MLX5\_TC\_CT=(y/n)</strong>

Support offloading connection tracking rules via tc ct action.

<strong>CONFIG\_MLX5\_TC\_SAMPLE=(y/n)</strong>

Support offloading sample rules via tc sample action.

<strong>CONFIG\_MLX5\_VDPA=(y/n)</strong>

Support library for Mellanox VDPA drivers. Provides code that is<br>
common for all types of VDPA drivers. The following drivers are planned:<br>
net, block.

<strong>CONFIG\_MLX5\_VDPA\_NET=(y/n)</strong>

VDPA network driver for ConnectX6 and newer. Provides offloading<br>
of virtio net datapath such that descriptors put on the ring will<br>
be executed by the hardware. It also supports a variety of stateless<br>
offloads depending on the actual device used and firmware version.

<strong>CONFIG\_MLX5\_VFIO\_PCI=(y/n)</strong>

This provides migration support for MLX5 devices using the VFIO framework.

<strong>External options</strong> ( Choose if the corresponding mlx5 feature is required )

- CONFIG\_MLXFW: When chosen, mlx5 firmware flashing support will be enabled (via devlink and ethtool).

- CONFIG\_PTP\_1588\_CLOCK: When chosen, mlx5 ptp support will be enabled

- CONFIG\_VXLAN: When chosen, mlx5 vxlan support will be enabled.

---

# Switchdev

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mellanox / mlx5_

> The mlx5 driver implements support for offloading bridge rules when in switchdev mode. Linux bridge FDBs are automatically offloaded when mlx5 switchdev representor is attached to bridge.

<a id="rst-switchdev"></a>

<!-- SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2023, NVIDIA CORPORATION &amp; AFFILIATES. All rights reserved.

<a id="rst-bridge-offload"></a>
<a id="rst-mlx5-bridge-offload"></a>

## Bridge offload

The mlx5 driver implements support for offloading bridge rules when in switchdev mode. Linux bridge FDBs are automatically offloaded when mlx5 switchdev representor is attached to bridge.

- Change device to switchdev mode:



  ```text
  $ devlink dev eswitch set pci/0000:06:00.0 mode switchdev
  ```

- Attach mlx5 switchdev representor 'enp8s0f0' to bridge netdev 'bridge1':



  ```text
  $ ip link set enp8s0f0 master bridge1
  ```

<a id="rst-vlans"></a>

### VLANs

Following bridge VLAN functions are supported by mlx5:

- VLAN filtering (including multiple VLANs per port):



  ```text
  $ ip link set bridge1 type bridge vlan_filtering 1
  $ bridge vlan add dev enp8s0f0 vid 2-3
  ```

- VLAN push on bridge ingress:



  ```text
  $ bridge vlan add dev enp8s0f0 vid 3 pvid
  ```

- VLAN pop on bridge egress:



  ```text
  $ bridge vlan add dev enp8s0f0 vid 3 untagged
  ```

<a id="rst-subfunction"></a>

## Subfunction

Subfunction which are spawned over the E-switch are created only with devlink device, and by default all the SF auxiliary devices are disabled. This will allow user to configure the SF before the SF have been fully probed, which will save time.

Usage example:

- Create SF:



  ```text
  $ devlink port add pci/0000:08:00.0 flavour pcisf pfnum 0 sfnum 11
  $ devlink port function set pci/0000:08:00.0/32768 hw_addr 00:00:00:00:00:11 state active
  ```

- Enable ETH auxiliary device:



  ```text
  $ devlink dev param set auxiliary/mlx5_core.sf.1 name enable_eth value true cmode driverinit
  ```

- Now, in order to fully probe the SF, use devlink reload:



  ```text
  $ devlink dev reload auxiliary/mlx5_core.sf.1
  ```

mlx5 supports ETH,rdma and vdpa (vnet) auxiliary devices devlink params (see [Documentation/networking/devlink/devlink-params.rst](</kernel/internals/networking/devlink/devlink-params.md#rst-devlink-params-generic>)).

mlx5 supports subfunction management using devlink port (see [Documentation/networking/devlink/devlink-port.rst](</kernel/internals/networking/devlink/devlink-port.md#rst-devlink-port>)) interface.

A subfunction has its own function capabilities and its own resources. This means a subfunction has its own dedicated queues (txq, rxq, cq, eq). These queues are neither shared nor stolen from the parent PCI function.

When a subfunction is RDMA capable, it has its own QP1, GID table, and RDMA resources neither shared nor stolen from the parent PCI function.

A subfunction has a dedicated window in PCI BAR space that is not shared with the other subfunctions or the parent PCI function. This ensures that all devices (netdev, rdma, vdpa, etc.) of the subfunction accesses only assigned PCI BAR space.

A subfunction supports eswitch representation through which it supports tc offloads. The user configures eswitch to send/receive packets from/to the subfunction port.

Subfunctions share PCI level resources such as PCI MSI-X IRQs with other subfunctions and/or with its parent PCI function.

Example mlx5 software, system, and device view:



```text
      _______
     | admin |
     | user  |----------
     |_______|         |
         |             |
     ____|____       __|______            _________________
    |         |     |         |          |                 |
    | devlink |     | tc tool |          |    user         |
    | tool    |     |_________|          | applications    |
    |_________|         |                |_________________|
          |             |                   |          |
          |             |                   |          |         Userspace
+---------|-------------|-------------------|----------|--------------------+
          |             |           +----------+   +----------+   Kernel
          |             |           |  netdev  |   | rdma dev |
          |             |           +----------+   +----------+
  (devlink port add/del |              ^               ^
   port function set)   |              |               |
          |             |              +---------------|
     _____|___          |              |        _______|_______
    |         |         |              |       | mlx5 class    |
    | devlink |   +------------+       |       |   drivers     |
    | kernel  |   | rep netdev |       |       |(mlx5_core,ib) |
    |_________|   +------------+       |       |_______________|
          |             |              |               ^
  (devlink ops)         |              |          (probe/remove)
 _________|________     |              |           ____|________
| subfunction      |    |     +---------------+   | subfunction |
| management driver|-----     | subfunction   |---|  driver     |
| (mlx5_core)      |          | auxiliary dev |   | (mlx5_core) |
|__________________|          +---------------+   |_____________|
          |                                            ^
 (sf add/del, vhca events)                             |
          |                                      (device add/del)
     _____|____                                    ____|________
    |          |                                  | subfunction |
    |  PCI NIC |--- activate/deactivate events--->| host driver |
    |__________|                                  | (mlx5_core) |
                                                  |_____________|
```

Subfunction is created using devlink port interface.

- Change device to switchdev mode:



  ```text
  $ devlink dev eswitch set pci/0000:06:00.0 mode switchdev
  ```

- Add a devlink port of subfunction flavour:



  ```text
  $ devlink port add pci/0000:06:00.0 flavour pcisf pfnum 0 sfnum 88
  pci/0000:06:00.0/32768: type eth netdev eth6 flavour pcisf controller 0 pfnum 0 sfnum 88 external false splittable false
    function:
      hw_addr 00:00:00:00:00:00 state inactive opstate detached
  ```

- Show a devlink port of the subfunction:



  ```text
  $ devlink port show pci/0000:06:00.0/32768
  pci/0000:06:00.0/32768: type eth netdev enp6s0pf0sf88 flavour pcisf pfnum 0 sfnum 88
    function:
      hw_addr 00:00:00:00:00:00 state inactive opstate detached
  ```

- Delete a devlink port of subfunction after use:



  ```text
  $ devlink port del pci/0000:06:00.0/32768
  ```

<a id="rst-function-attributes"></a>

## Function attributes

The mlx5 driver provides a mechanism to setup PCI VF/SF function attributes in a unified way for SmartNIC and non-SmartNIC.

This is supported only when the eswitch mode is set to switchdev. Port function configuration of the PCI VF/SF is supported through devlink eswitch port.

Port function attributes should be set before PCI VF/SF is enumerated by the driver.

<a id="rst-mac-address-setup"></a>

### MAC address setup

mlx5 driver support devlink port function attr mechanism to setup MAC address. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

<a id="rst-roce-capability-setup"></a>

#### RoCE capability setup

Not all mlx5 PCI devices/SFs require RoCE capability.

When RoCE capability is disabled, it saves 1 Mbytes worth of system memory per PCI devices/SF.

mlx5 driver support devlink port function attr mechanism to setup RoCE capability. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

<a id="rst-migratable-capability-setup"></a>

#### migratable capability setup

User who wants mlx5 PCI VFs to be able to perform live migration need to explicitly enable the VF migratable capability.

mlx5 driver support devlink port function attr mechanism to setup migratable capability. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

<a id="rst-ipsec-crypto-capability-setup"></a>

#### IPsec crypto capability setup

User who wants mlx5 PCI VFs to be able to perform IPsec crypto offloading need to explicitly enable the VF ipsec_crypto capability. Enabling IPsec capability for VFs is supported starting with ConnectX6dx devices and above. When a VF has IPsec capability enabled, any IPsec offloading is blocked on the PF.

mlx5 driver support devlink port function attr mechanism to setup ipsec_crypto capability. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

<a id="rst-ipsec-packet-capability-setup"></a>

#### IPsec packet capability setup

User who wants mlx5 PCI VFs to be able to perform IPsec packet offloading need to explicitly enable the VF ipsec_packet capability. Enabling IPsec capability for VFs is supported starting with ConnectX6dx devices and above. When a VF has IPsec capability enabled, any IPsec offloading is blocked on the PF.

mlx5 driver support devlink port function attr mechanism to setup ipsec_packet capability. (refer to [Documentation/networking/devlink/devlink-port.rst](/kernel/internals/networking/devlink/devlink-port.md))

<a id="rst-sf-state-setup"></a>

### SF state setup

To use the SF, the user must activate the SF using the SF function state attribute.

- Get the state of the SF identified by its unique devlink port index:



  ```text
  $ devlink port show ens2f0npf0sf88
  pci/0000:06:00.0/32768: type eth netdev ens2f0npf0sf88 flavour pcisf controller 0 pfnum 0 sfnum 88 external false splittable false
    function:
      hw_addr 00:00:00:00:88:88 state inactive opstate detached
  ```

- Activate the function and verify its state is active:



  ```text
  $ devlink port function set ens2f0npf0sf88 state active

  $ devlink port show ens2f0npf0sf88
  pci/0000:06:00.0/32768: type eth netdev ens2f0npf0sf88 flavour pcisf controller 0 pfnum 0 sfnum 88 external false splittable false
    function:
      hw_addr 00:00:00:00:88:88 state active opstate detached
  ```

Upon function activation, the PF driver instance gets the event from the device that a particular SF was activated. It's the cue to put the device on bus, probe it and instantiate the devlink instance and class specific auxiliary devices for it.

- Show the auxiliary device and port of the subfunction:



  ```text
  $ devlink dev show
  devlink dev show auxiliary/mlx5_core.sf.4

  $ devlink port show auxiliary/mlx5_core.sf.4/1
  auxiliary/mlx5_core.sf.4/1: type eth netdev p0sf88 flavour virtual port 0 splittable false

  $ rdma link show mlx5_0/1
  link mlx5_0/1 state ACTIVE physical_state LINK_UP netdev p0sf88

  $ rdma dev show
  8: rocep6s0f1: node_type ca fw 16.29.0550 node_guid 248a:0703:00b3:d113 sys_image_guid 248a:0703:00b3:d112
  13: mlx5_0: node_type ca fw 16.29.0550 node_guid 0000:00ff:fe00:8888 sys_image_guid 248a:0703:00b3:d112
  ```

- Subfunction auxiliary device and class device hierarchy:



  ```text
              mlx5_core.sf.4
       (subfunction auxiliary device)
                    /\
                   /  \
                  /    \
                 /      \
                /        \
   mlx5_core.eth.4     mlx5_core.rdma.4
  (sf eth aux dev)     (sf rdma aux dev)
      |                      |
      |                      |
   p0sf88                  mlx5_0
  (sf netdev)          (sf rdma device)
  ```

Additionally, the SF port also gets the event when the driver attaches to the auxiliary device of the subfunction. This results in changing the operational state of the function. This provides visibility to the user to decide when is it safe to delete the SF port for graceful termination of the subfunction.

- Show the SF port operational state:



  ```text
  $ devlink port show ens2f0npf0sf88
  pci/0000:06:00.0/32768: type eth netdev ens2f0npf0sf88 flavour pcisf controller 0 pfnum 0 sfnum 88 external false splittable false
    function:
      hw_addr 00:00:00:00:88:88 state active opstate attached
  ```

---

# Tracepoints

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mellanox / mlx5_

> mlx5 driver provides internal tracepoints for tracking and debugging using kernel tracepoints interfaces (refer to Documentation/trace/ftrace.rst).

<a id="rst-tracepoints"></a>

<!-- SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2023, NVIDIA CORPORATION &amp; AFFILIATES. All rights reserved.

mlx5 driver provides internal tracepoints for tracking and debugging using kernel tracepoints interfaces (refer to [Documentation/trace/ftrace.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/trace/ftrace.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)).

For the list of support mlx5 events, check /sys/kernel/tracing/events/mlx5/.

tc and eswitch offloads tracepoints:

- mlx5e_configure_flower: trace flower filter actions and cookies offloaded to mlx5:



  ```text
  $ echo mlx5:mlx5e_configure_flower >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  tc-6535  [019] ...1  2672.404466: mlx5e_configure_flower: cookie=0000000067874a55 actions= REDIRECT
  ```

- mlx5e_delete_flower: trace flower filter actions and cookies deleted from mlx5:



  ```text
  $ echo mlx5:mlx5e_delete_flower >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  tc-6569  [010] .N.1  2686.379075: mlx5e_delete_flower: cookie=0000000067874a55 actions= NULL
  ```

- mlx5e_stats_flower: trace flower stats request:



  ```text
  $ echo mlx5:mlx5e_stats_flower >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  tc-6546  [010] ...1  2679.704889: mlx5e_stats_flower: cookie=0000000060eb3d6a bytes=0 packets=0 lastused=4295560217
  ```

- mlx5e_tc_update_neigh_used_value: trace tunnel rule neigh update value offloaded to mlx5:



  ```text
  $ echo mlx5:mlx5e_tc_update_neigh_used_value >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u48:4-8806  [009] ...1 55117.882428: mlx5e_tc_update_neigh_used_value: netdev: ens1f0 IPv4: 1.1.1.10 IPv6: ::ffff:1.1.1.10 neigh_used=1
  ```

- mlx5e_rep_neigh_update: trace neigh update tasks scheduled due to neigh state change events:



  ```text
  $ echo mlx5:mlx5e_rep_neigh_update >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u48:7-2221  [009] ...1  1475.387435: mlx5e_rep_neigh_update: netdev: ens1f0 MAC: 24:8a:07:9a:17:9a IPv4: 1.1.1.10 IPv6: ::ffff:1.1.1.10 neigh_connected=1
  ```

Bridge offloads tracepoints:

- mlx5_esw_bridge_fdb_entry_init: trace bridge FDB entry offloaded to mlx5:



  ```text
  $ echo mlx5:mlx5_esw_bridge_fdb_entry_init >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u20:9-2217    [003] ...1   318.582243: mlx5_esw_bridge_fdb_entry_init: net_device=enp8s0f0_0 addr=e4:fd:05:08:00:02 vid=0 flags=0 used=0
  ```

- mlx5_esw_bridge_fdb_entry_cleanup: trace bridge FDB entry deleted from mlx5:



  ```text
  $ echo mlx5:mlx5_esw_bridge_fdb_entry_cleanup >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  ip-2581    [005] ...1   318.629871: mlx5_esw_bridge_fdb_entry_cleanup: net_device=enp8s0f0_1 addr=e4:fd:05:08:00:03 vid=0 flags=0 used=16
  ```

- mlx5_esw_bridge_fdb_entry_refresh: trace bridge FDB entry offload refreshed in mlx5:



  ```text
  $ echo mlx5:mlx5_esw_bridge_fdb_entry_refresh >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u20:8-3849    [003] ...1       466716: mlx5_esw_bridge_fdb_entry_refresh: net_device=enp8s0f0_0 addr=e4:fd:05:08:00:02 vid=3 flags=0 used=0
  ```

- mlx5_esw_bridge_vlan_create: trace bridge VLAN object add on mlx5 representor:



  ```text
  $ echo mlx5:mlx5_esw_bridge_vlan_create >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  ip-2560    [007] ...1   318.460258: mlx5_esw_bridge_vlan_create: vid=1 flags=6
  ```

- mlx5_esw_bridge_vlan_cleanup: trace bridge VLAN object delete from mlx5 representor:



  ```text
  $ echo mlx5:mlx5_esw_bridge_vlan_cleanup >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  bridge-2582    [007] ...1   318.653496: mlx5_esw_bridge_vlan_cleanup: vid=2 flags=8
  ```

- mlx5_esw_bridge_vport_init: trace mlx5 vport assigned with bridge upper device:



  ```text
  $ echo mlx5:mlx5_esw_bridge_vport_init >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  ip-2560    [007] ...1   318.458915: mlx5_esw_bridge_vport_init: vport_num=1
  ```

- mlx5_esw_bridge_vport_cleanup: trace mlx5 vport removed from bridge upper device:



  ```text
  $ echo mlx5:mlx5_esw_bridge_vport_cleanup >> set_event
  $ cat /sys/kernel/tracing/trace
  ...
  ip-5387    [000] ...1       573713: mlx5_esw_bridge_vport_cleanup: vport_num=1
  ```

Eswitch QoS tracepoints:

- mlx5_esw_vport_qos_create: trace creation of transmit scheduler arbiter for vport:



  ```text
  $ echo mlx5:mlx5_esw_vport_qos_create >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-23496   [018] .... 73136.838831: mlx5_esw_vport_qos_create: (0000:82:00.0) vport=2 tsar_ix=4 bw_share=0, max_rate=0 group=000000007b576bb3
  ```

- mlx5_esw_vport_qos_config: trace configuration of transmit scheduler arbiter for vport:



  ```text
  $ echo mlx5:mlx5_esw_vport_qos_config >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-26548   [023] .... 75754.223823: mlx5_esw_vport_qos_config: (0000:82:00.0) vport=1 tsar_ix=3 bw_share=34, max_rate=10000 group=000000007b576bb3
  ```

- mlx5_esw_vport_qos_destroy: trace deletion of transmit scheduler arbiter for vport:



  ```text
  $ echo mlx5:mlx5_esw_vport_qos_destroy >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-27418   [004] .... 76546.680901: mlx5_esw_vport_qos_destroy: (0000:82:00.0) vport=1 tsar_ix=3
  ```

- mlx5_esw_group_qos_create: trace creation of transmit scheduler arbiter for rate group:



  ```text
  $ echo mlx5:mlx5_esw_group_qos_create >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-26578   [008] .... 75776.022112: mlx5_esw_group_qos_create: (0000:82:00.0) group=000000008dac63ea tsar_ix=5
  ```

- mlx5_esw_group_qos_config: trace configuration of transmit scheduler arbiter for rate group:



  ```text
  $ echo mlx5:mlx5_esw_group_qos_config >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-27303   [020] .... 76461.455356: mlx5_esw_group_qos_config: (0000:82:00.0) group=000000008dac63ea tsar_ix=5 bw_share=100 max_rate=20000
  ```

- mlx5_esw_group_qos_destroy: trace deletion of transmit scheduler arbiter for group:



  ```text
  $ echo mlx5:mlx5_esw_group_qos_destroy >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  <...>-27418   [006] .... 76547.187258: mlx5_esw_group_qos_destroy: (0000:82:00.0) group=000000007b576bb3 tsar_ix=1
  ```

SF tracepoints:

- mlx5_sf_add: trace addition of the SF port:



  ```text
  $ echo mlx5:mlx5_sf_add >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-9363    [031] ..... 24610.188722: mlx5_sf_add: (0000:06:00.0) port_index=32768 controller=0 hw_id=0x8000 sfnum=88
  ```

- mlx5_sf_free: trace freeing of the SF port:



  ```text
  $ echo mlx5:mlx5_sf_free >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-9830    [038] ..... 26300.404749: mlx5_sf_free: (0000:06:00.0) port_index=32768 controller=0 hw_id=0x8000
  ```

- mlx5_sf_activate: trace activation of the SF port:



  ```text
  $ echo mlx5:mlx5_sf_activate >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-29841   [008] .....  3669.635095: mlx5_sf_activate: (0000:08:00.0) port_index=32768 controller=0 hw_id=0x8000
  ```

- mlx5_sf_deactivate: trace deactivation of the SF port:



  ```text
  $ echo mlx5:mlx5_sf_deactivate >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-29994   [008] .....  4015.969467: mlx5_sf_deactivate: (0000:08:00.0) port_index=32768 controller=0 hw_id=0x8000
  ```

- mlx5_sf_hwc_alloc: trace allocating of the hardware SF context:



  ```text
  $ echo mlx5:mlx5_sf_hwc_alloc >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-9775    [031] ..... 26296.385259: mlx5_sf_hwc_alloc: (0000:06:00.0) controller=0 hw_id=0x8000 sfnum=88
  ```

- mlx5_sf_hwc_free: trace freeing of the hardware SF context:



  ```text
  $ echo mlx5:mlx5_sf_hwc_free >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u128:3-9093    [046] ..... 24625.365771: mlx5_sf_hwc_free: (0000:06:00.0) hw_id=0x8000
  ```

- mlx5_sf_hwc_deferred_free: trace deferred freeing of the hardware SF context:



  ```text
  $ echo mlx5:mlx5_sf_hwc_deferred_free >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  devlink-9519    [046] ..... 24624.400271: mlx5_sf_hwc_deferred_free: (0000:06:00.0) hw_id=0x8000
  ```

- mlx5_sf_update_state: trace state updates for SF contexts:



  ```text
  $ echo mlx5:mlx5_sf_update_state >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u20:3-29490   [009] .....  4141.453530: mlx5_sf_update_state: (0000:08:00.0) port_index=32768 controller=0 hw_id=0x8000 state=2
  ```

- mlx5_sf_vhca_event: trace SF vhca event and state:



  ```text
  $ echo mlx5:mlx5_sf_vhca_event >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u128:3-9093    [046] ..... 24625.365525: mlx5_sf_vhca_event: (0000:06:00.0) hw_id=0x8000 sfnum=88 vhca_state=1
  ```

- mlx5_sf_dev_add: trace SF device add event:



  ```text
  $ echo mlx5:mlx5_sf_dev_add>> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u128:3-9093    [000] ..... 24616.524495: mlx5_sf_dev_add: (0000:06:00.0) sfdev=00000000fc5d96fd aux_id=4 hw_id=0x8000 sfnum=88
  ```

- mlx5_sf_dev_del: trace SF device delete event:



  ```text
  $ echo mlx5:mlx5_sf_dev_del >> /sys/kernel/tracing/set_event
  $ cat /sys/kernel/tracing/trace
  ...
  kworker/u128:3-9093    [044] ..... 24624.400749: mlx5_sf_dev_del: (0000:06:00.0) sfdev=00000000fc5d96fd aux_id=4 hw_id=0x8000 sfnum=88
  ```

---

# Meta Platforms Host Network Interface

_Peios Kernel / Internals / Networking / device_drivers / ethernet / meta_

> fbnic has three components stored on the flash which are provided in one PLDM image:

<a id="rst-meta-platforms-host-network-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-firmware-versions"></a>

## Firmware Versions

fbnic has three components stored on the flash which are provided in one PLDM image:

1. fw - The control firmware used to view and modify firmware settings, request firmware actions, and retrieve firmware counters outside of the data path. This is the firmware which fbnic_fw.c interacts with.

2. bootloader - The firmware which validate firmware security and control basic operations including loading and updating the firmware. This is also known as the cmrt firmware.

3. undi - This is the UEFI driver which is based on the Linux driver.

fbnic stores two copies of these three components on flash. This allows fbnic to fall back to an older version of firmware automatically in case firmware fails to boot. Version information for both is provided as running and stored. The undi is only provided in stored as it is not actively running once the Linux driver takes over.

devlink dev info provides version information for all three components. In addition to the version the hg commit hash of the build is included as a separate entry.

<a id="rst-configuration"></a>

## Configuration

<a id="rst-ringparams-ethtool-g-g"></a>

### Ringparams (ethtool -g / -G)

fbnic has two submission (host -&gt; device) rings for every completion (device -&gt; host) ring. The three ring objects together form a single "queue" as used by higher layer software (a Rx, or a Tx queue).

For Rx the two submission rings are used to pass empty pages to the NIC. Ring 0 is the Header Page Queue (HPQ), NIC will use its pages to place L2-L4 headers (or full frames if frame is not header-data split). Ring 1 is the Payload Page Queue (PPQ) and used for packet payloads. The completion ring is used to receive packet notifications / metadata. ethtool `rx` ringparam maps to the size of the completion ring, `rx-mini` to the HPQ, and `rx-jumbo` to the PPQ.

For Tx both submission rings can be used to submit packets, the completion ring carries notifications for both. fbnic uses one of the submission rings for normal traffic from the stack and the second one for XDP frames. ethtool `tx` ringparam controls both the size of the submission rings and the completion ring.

Every single entry on the HPQ and PPQ (`rx-mini`, `rx-jumbo`) corresponds to 4kB of allocated memory, while entries on the remaining rings are in units of descriptors (8B). The ideal ratio of submission and completion ring sizes will depend on the workload, as for small packets multiple packets will fit into a single page.

<a id="rst-upgrading-firmware"></a>

## Upgrading Firmware

fbnic supports updating firmware using signed PLDM images with devlink dev flash. PLDM images are written into the flash. Flashing does not interrupt the operation of the device.

On host boot the latest UEFI driver is always used, no explicit activation is required. Firmware activation is required to run new control firmware. cmrt firmware can only be activated by power cycling the NIC.

<a id="rst-health-reporters"></a>

## Health reporters

<a id="rst-fw-reporter"></a>

### fw reporter

The `fw` health reporter tracks FW crashes. Dumping the reporter will show the core dump of the most recent FW crash, and if no FW crash has happened since power cycle - a snapshot of the FW memory. Diagnose callback shows FW uptime based on the most recently received heartbeat message (the crashes are detected by checking if uptime goes down).

<a id="rst-otp-reporter"></a>

### otp reporter

OTP memory ("fuses") are used for secure boot and anti-rollback protection. The OTP memory is ECC protected, ECC errors indicate either manufacturing defect or part deteriorating with age.

<a id="rst-statistics"></a>

## Statistics

<a id="rst-tx-mac-interface"></a>

### TX MAC Interface

> - `ptp_illegal_req`: packets sent to the NIC with PTP request bit set but routed to BMC/FW
>
> - `ptp_good_ts`: packets successfully routed to MAC with PTP request bit set
>
> - `ptp_bad_ts`: packets destined for MAC with PTP request bit set but aborted because of some error (e.g., DMA read error)

<a id="rst-tx-extension-tei-interface-tti"></a>

### TX Extension (TEI) Interface (TTI)

> - `tti_cm_drop`: control messages dropped at the TX Extension (TEI) Interface because of credit starvation
>
> - `tti_frame_drop`: packets dropped at the TX Extension (TEI) Interface because of credit starvation
>
> - `tti_tbi_drop`: packets dropped at the TX BMC Interface (TBI) because of credit starvation

<a id="rst-rxb-rx-buffer-enqueue"></a>

### RXB (RX Buffer) Enqueue

> - `rxb_integrity_err[i]`: frames enqueued with integrity errors (e.g., multi-bit ECC errors) on RXB input i
>
> - `rxb_mac_err[i]`: frames enqueued with MAC end-of-frame errors (e.g., bad FCS) on RXB input i
>
> - `rxb_parser_err[i]`: frames experienced RPC parser errors
>
> - `rxb_frm_err[i]`: frames experienced signaling errors (e.g., missing end-of-packet/start-of-packet) on RXB input i
>
> - `rxb_drbo[i]_frames`: frames received at RXB input i
>
> - `rxb_drbo[i]_bytes`: bytes received at RXB input i

<a id="rst-rxb-rx-buffer-fifo"></a>

### RXB (RX Buffer) FIFO

> - `rxb_fifo[i]_drop`: transitions into the drop state on RXB pool i
>
> - `rxb_fifo[i]_dropped_frames`: frames dropped on RXB pool i
>
> - `rxb_fifo[i]_ecn`: transitions into the ECN mark state on RXB pool i
>
> - `rxb_fifo[i]_level`: current occupancy of RXB pool i

<a id="rst-rxb-rx-buffer-dequeue"></a>

### RXB (RX Buffer) Dequeue

> - `rxb_intf[i]_frames`: frames sent to the output i
>
> - `rxb_intf[i]_bytes`: bytes sent to the output i
>
> - `rxb_pbuf[i]_frames`: frames sent to output i from the perspective of internal packet buffer
>
> - `rxb_pbuf[i]_bytes`: bytes sent to output i from the perspective of internal packet buffer

<a id="rst-rpc-rx-parser"></a>

### RPC (Rx parser)

> - `rpc_unkn_etype`: frames containing unknown EtherType
>
> - `rpc_unkn_ext_hdr`: frames containing unknown IPv6 extension header
>
> - `rpc_ipv4_frag`: frames containing IPv4 fragment
>
> - `rpc_ipv6_frag`: frames containing IPv6 fragment
>
> - `rpc_ipv4_esp`: frames with IPv4 ESP encapsulation
>
> - `rpc_ipv6_esp`: frames with IPv6 ESP encapsulation
>
> - `rpc_tcp_opt_err`: frames which encountered TCP option parsing error
>
> - `rpc_out_of_hdr_err`: frames where header was larger than parsable region
>
> - `ovr_size_err`: oversized frames

<a id="rst-hardware-queues"></a>

### Hardware Queues

1. RX DMA Engine:

> - `rde_[i]_pkt_err`: packets with MAC EOP, RPC parser, RXB truncation, or RDE frame truncation errors. These error are flagged in the packet metadata because of cut-through support but the actual drop happens once PCIE/RDE is reached.
>
> - `rde_[i]_pkt_cq_drop`: packets dropped because RCQ is full
>
> - `rde_[i]_pkt_bdq_drop`: packets dropped because HPQ or PPQ ran out of host buffer

<a id="rst-pcie"></a>

### PCIe

The fbnic driver exposes PCIe hardware performance statistics through debugfs (`pcie_stats`). These statistics provide insights into PCIe transaction behavior and potential performance bottlenecks.

1. PCIe Transaction Counters:

   - **These counters track PCIe transaction activity:**

     - `pcie_ob_rd_tlp`: Outbound read Transaction Layer Packets count

     - `pcie_ob_rd_dword`: DWORDs transferred in outbound read transactions

     - `pcie_ob_wr_tlp`: Outbound write Transaction Layer Packets count

     - `pcie_ob_wr_dword`: DWORDs transferred in outbound write transactions

     - `pcie_ob_cpl_tlp`: Outbound completion TLP count

     - `pcie_ob_cpl_dword`: DWORDs transferred in outbound completion TLPs

2. PCIe Resource Monitoring:

   - **These counters indicate PCIe resource exhaustion events:**

     - `pcie_ob_rd_no_tag`: Read requests dropped due to tag unavailability

     - `pcie_ob_rd_no_cpl_cred`: Read requests dropped due to completion credit exhaustion

     - `pcie_ob_rd_no_np_cred`: Read requests dropped due to non-posted credit exhaustion

<a id="rst-xdp-length-error"></a>

### XDP Length Error:

For XDP programs without frags support, fbnic tries to make sure that MTU fits into a single buffer. If an oversized frame is received and gets fragmented, it is dropped and the following netlink counters are updated

> - `rx-length`: number of frames dropped due to lack of fragmentation support in the attached XDP program
>
> - `rx-errors`: total number of packets with errors received on the interface

---

# Hyper-V network driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / microsoft_

> This driver is compatible with Windows Server 2012 R2, 2016 and Windows 10.

<a id="rst-hyper-v-network-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-compatibility"></a>

## Compatibility

This driver is compatible with Windows Server 2012 R2, 2016 and Windows 10.

<a id="rst-features"></a>

## Features

<a id="rst-checksum-offload"></a>

### Checksum offload

> The netvsc driver supports checksum offload as long as the Hyper-V host version does. Windows Server 2016 and Azure support checksum offload for TCP and UDP for both IPv4 and IPv6. Windows Server 2012 only supports checksum offload for TCP.

<a id="rst-receive-side-scaling"></a>

### Receive Side Scaling

> Hyper-V supports receive side scaling. For TCP &amp; UDP, packets can be distributed among available queues based on IP address and port number.
>
> For TCP &amp; UDP, we can switch hash level between L3 and L4 by ethtool command. TCP/UDP over IPv4 and v6 can be set differently. The default hash level is L4. We currently only allow switching TX hash level from within the guests.
>
> On Azure, fragmented UDP packets have high loss rate with L4 hashing. Using L3 hashing is recommended in this case.
>
> For example, for UDP over IPv4 on eth0:
>
> To include UDP port numbers in hashing:
>
>
>
> ```text
> ethtool -N eth0 rx-flow-hash udp4 sdfn
> ```
>
> To exclude UDP port numbers in hashing:
>
>
>
> ```text
> ethtool -N eth0 rx-flow-hash udp4 sd
> ```
>
> To show UDP hash level:
>
>
>
> ```text
> ethtool -n eth0 rx-flow-hash udp4
> ```

<a id="rst-generic-receive-offload-aka-gro"></a>

### Generic Receive Offload, aka GRO

> The driver supports GRO and it is enabled by default. GRO coalesces like packets and significantly reduces CPU usage under heavy Rx load.

<a id="rst-large-receive-offload-lro-or-receive-side-coalescing-rsc"></a>

### Large Receive Offload (LRO), or Receive Side Coalescing (RSC)

> The driver supports LRO/RSC in the vSwitch feature. It reduces the per packet processing overhead by coalescing multiple TCP segments when possible. The feature is enabled by default on VMs running on Windows Server 2019 and later. It may be changed by ethtool command:
>
>
>
> ```text
> ethtool -K eth0 lro on
> ethtool -K eth0 lro off
> ```

<a id="rst-sr-iov-support"></a>

### SR-IOV support

> Hyper-V supports SR-IOV as a hardware acceleration option. If SR-IOV is enabled in both the vSwitch and the guest configuration, then the Virtual Function (VF) device is passed to the guest as a PCI device. In this case, both a synthetic (netvsc) and VF device are visible in the guest OS and both NIC's have the same MAC address.
>
> The VF is enslaved by netvsc device.  The netvsc driver will transparently switch the data path to the VF when it is available and up. Network state (addresses, firewall, etc) should be applied only to the netvsc device; the slave device should not be accessed directly in most cases.  The exceptions are if some special queue discipline or flow direction is desired, these should be applied directly to the VF slave device.

<a id="rst-receive-buffer"></a>

### Receive Buffer

> Packets are received into a receive area which is created when device is probed. The receive area is broken into MTU sized chunks and each may contain one or more packets. The number of receive sections may be changed via ethtool Rx ring parameters.
>
> There is a similar send buffer which is used to aggregate packets for sending.  The send area is broken into chunks, typically of 6144 bytes, each of section may contain one or more packets. Small packets are usually transmitted via copy to the send buffer. However, if the buffer is temporarily exhausted, or the packet to be transmitted is an LSO packet, the driver will provide the host with pointers to the data from the SKB. This attempts to achieve a balance between the overhead of data copy and the impact of remapping VM memory to be accessible by the host.

<a id="rst-xdp-support"></a>

### XDP support

> XDP (eXpress Data Path) is a feature that runs eBPF bytecode at the early stage when packets arrive at a NIC card. The goal is to increase performance for packet processing, reducing the overhead of SKB allocation and other upper network layers.
>
> hv_netvsc supports XDP in native mode, and transparently sets the XDP program on the associated VF NIC as well.
>
> Setting / unsetting XDP program on synthetic NIC (netvsc) propagates to VF NIC automatically. Setting / unsetting XDP program on VF NIC directly is not recommended, also not propagated to synthetic NIC, and may be overwritten by setting of synthetic NIC.
>
> XDP program cannot run with LRO (RSC) enabled, so you need to disable LRO before running XDP:
>
>
>
> ```text
> ethtool -K eth0 lro off
> ```
>
> XDP_REDIRECT action is not yet supported.

---

# Linux Base Driver for MUCSE(R) Gigabit PCI Express Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / mucse_

> Identifying Your Adapter

<a id="rst-linux-base-driver-for-mucse-r-gigabit-pci-express-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>

## Contents

- Identifying Your Adapter

<a id="rst-identifying-your-adapter"></a>

## Identifying Your Adapter

The driver is compatible with devices based on the following:

> - MUCSE(R) Ethernet Controller N210 series
>
> - MUCSE(R) Ethernet Controller N500 series

---

# Network Flow Processor (NFP) Kernel Drivers

_Peios Kernel / Internals / Networking / device_drivers / ethernet / netronome_

> Overview

<a id="rst-network-flow-processor-nfp-kernel-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

**Copyright:** © 2019, Netronome Systems, Inc.

**Copyright:** © 2022, Corigine, Inc.

<a id="rst-contents"></a>

## Contents

- [Overview](<#rst-overview>)

- [Acquiring Firmware](<#rst-acquiring-firmware>)

- [Devlink Info](<#rst-devlink-info>)

- [Configure Device](<#rst-configure-device>)

- [Statistics](<#rst-statistics>)

<a id="rst-overview"></a>

## Overview

This driver supports Netronome and Corigine's line of Network Flow Processor devices, including the NFP3800, NFP4000, NFP5000, and NFP6000 models, which are also incorporated in the companies' family of Agilio SmartNICs. The SR-IOV physical and virtual functions for these devices are supported by the driver.

<a id="rst-acquiring-firmware"></a>

## Acquiring Firmware

The NFP3800, NFP4000 and NFP6000 devices require application specific firmware to function. Application firmware can be located either on the host file system or in the device flash (if supported by management firmware).

Firmware files on the host filesystem contain card type (`AMDA-*` string), media config etc. They should be placed in `/lib/firmware/netronome` directory to load firmware from the host file system.

Firmware for basic NIC operation is available in the upstream `linux-firmware.git` repository.

A more comprehensive list of firmware can be downloaded from the [Corigine Support site](<https://www.corigine.com/DPUDownload.html>)<a id="rst-corigine-support-site"></a>.

<a id="rst-firmware-in-nvram"></a>

### Firmware in NVRAM

Recent versions of management firmware supports loading application firmware from flash when the host driver gets probed. The firmware loading policy configuration may be used to configure this feature appropriately.

Devlink or ethtool can be used to update the application firmware on the device flash by providing the appropriate `nic_AMDA*.nffw` file to the respective command. Users need to take care to write the correct firmware image for the card and media configuration to flash.

Available storage space in flash depends on the card being used.

<a id="rst-dealing-with-multiple-projects"></a>

### Dealing with multiple projects

NFP hardware is fully programmable therefore there can be different firmware images targeting different applications.

When using application firmware from host, we recommend placing actual firmware files in application-named subdirectories in `/lib/firmware/netronome` and linking the desired files, e.g.:



```text
$ tree /lib/firmware/netronome/
/lib/firmware/netronome/
├── bpf
│   ├── nic_AMDA0081-0001_1x40.nffw
│   └── nic_AMDA0081-0001_4x10.nffw
├── flower
│   ├── nic_AMDA0081-0001_1x40.nffw
│   └── nic_AMDA0081-0001_4x10.nffw
├── nic
│   ├── nic_AMDA0081-0001_1x40.nffw
│   └── nic_AMDA0081-0001_4x10.nffw
├── nic_AMDA0081-0001_1x40.nffw -> bpf/nic_AMDA0081-0001_1x40.nffw
└── nic_AMDA0081-0001_4x10.nffw -> bpf/nic_AMDA0081-0001_4x10.nffw

3 directories, 8 files
```

You may need to use hard instead of symbolic links on distributions which use old `mkinitrd` command instead of `dracut` (e.g. Ubuntu).

After changing firmware files you may need to regenerate the initramfs image. Initramfs contains drivers and firmware files your system may need to boot. Refer to the documentation of your distribution to find out how to update initramfs. Good indication of stale initramfs is system loading wrong driver or firmware on boot, but when driver is later reloaded manually everything works correctly.

<a id="rst-selecting-firmware-per-device"></a>

### Selecting firmware per device

Most commonly all cards on the system use the same type of firmware. If you want to load a specific firmware image for a specific card, you can use either the PCI bus address or serial number. The driver will print which files it's looking for when it recognizes a NFP device:



```text
nfp: Looking for firmware file in order of priority:
nfp:  netronome/serial-00-12-34-aa-bb-cc-10-ff.nffw: not found
nfp:  netronome/pci-0000:02:00.0.nffw: not found
nfp:  netronome/nic_AMDA0081-0001_1x40.nffw: found, loading...
```

In this case if file (or link) called *serial-00-12-34-aa-bb-5d-10-ff.nffw* or *pci-0000:02:00.0.nffw* is present in `/lib/firmware/netronome` this firmware file will take precedence over `nic_AMDA*` files.

Note that `serial-*` and `pci-*` files are **not** automatically included in initramfs, you will have to refer to documentation of appropriate tools to find out how to include them.

<a id="rst-running-firmware-version"></a>

### Running firmware version

The version of the loaded firmware for a particular &lt;netdev&gt; interface, (e.g. enp4s0), or an interface's port &lt;netdev port&gt; (e.g. enp4s0np0) can be displayed with the ethtool command:



```text
$ ethtool -i <netdev>
```

<a id="rst-firmware-loading-policy"></a>

### Firmware loading policy

Firmware loading policy is controlled via three HWinfo parameters stored as key value pairs in the device flash:

- **app_fw_from_flash**

  Defines which firmware should take precedence, 'Disk' (0), 'Flash' (1) or the 'Preferred' (2) firmware. When 'Preferred' is selected, the management firmware makes the decision over which firmware will be loaded by comparing versions of the flash firmware and the host supplied firmware. This variable is configurable using the 'fw_load_policy' devlink parameter.

- **abi_drv_reset**

  Defines if the driver should reset the firmware when the driver is probed, either 'Disk' (0) if firmware was found on disk, 'Always' (1) reset or 'Never' (2) reset. Note that the device is always reset on driver unload if firmware was loaded when the driver was probed. This variable is configurable using the 'reset_dev_on_drv_probe' devlink parameter.

- **abi_drv_load_ifc**

  Defines a list of PF devices allowed to load FW on the device. This variable is not currently user configurable.

<a id="rst-devlink-info"></a>

## Devlink Info

The devlink info command displays the running and stored firmware versions on the device, serial number and board information.

Devlink info command example (replace PCI address):



```text
$ devlink dev info pci/0000:03:00.0
  pci/0000:03:00.0:
    driver nfp
    serial_number CSAAMDA2001-1003000111
    versions:
        fixed:
          board.id AMDA2001-1003
          board.rev 01
          board.manufacture CSA
          board.model mozart
        running:
          fw.mgmt 22.10.0-rc3
          fw.cpld 0x1000003
          fw.app nic-22.09.0
          chip.init AMDA-2001-1003  1003000111
        stored:
          fw.bundle_id bspbundle_1003000111
          fw.mgmt 22.10.0-rc3
          fw.cpld 0x0
          chip.init AMDA-2001-1003  1003000111
```

<a id="rst-configure-device"></a>

## Configure Device

This section explains how to use Agilio SmartNICs running basic NIC firmware.

<a id="rst-configure-interface-link-speed"></a>

### Configure interface link-speed

The following steps explains how to change between 10G mode and 25G mode on Agilio CX 2x25GbE cards. The changing of port speed must be done in order, port 0 (p0) must be set to 10G before port 1 (p1) may be set to 10G.

Down the respective interface(s):



```text
$ ip link set dev <netdev port 0> down
$ ip link set dev <netdev port 1> down
```

Set interface link-speed to 10G:



```text
$ ethtool -s <netdev port 0> speed 10000
$ ethtool -s <netdev port 1> speed 10000
```

Set interface link-speed to 25G:



```text
$ ethtool -s <netdev port 0> speed 25000
$ ethtool -s <netdev port 1> speed 25000
```

Reload driver for changes to take effect:



```text
$ rmmod nfp; modprobe nfp
```

<a id="rst-configure-interface-maximum-transmission-unit-mtu"></a>

### Configure interface Maximum Transmission Unit (MTU)

The MTU of interfaces can temporarily be set using the iproute2, ip link or ifconfig tools. Note that this change will not persist. Setting this via Network Manager, or another appropriate OS configuration tool, is recommended as changes to the MTU using Network Manager can be made to persist.

Set interface MTU to 9000 bytes:



```text
$ ip link set dev <netdev port> mtu 9000
```

It is the responsibility of the user or the orchestration layer to set appropriate MTU values when handling jumbo frames or utilizing tunnels. For example, if packets sent from a VM are to be encapsulated on the card and egress a physical port, then the MTU of the VF should be set to lower than that of the physical port to account for the extra bytes added by the additional header. If a setup is expected to see fallback traffic between the SmartNIC and the kernel then the user should also ensure that the PF MTU is appropriately set to avoid unexpected drops on this path.

<a id="rst-configure-forward-error-correction-fec-modes"></a>

### Configure Forward Error Correction (FEC) modes

Agilio SmartNICs support FEC mode configuration, e.g. Auto, Firecode Base-R, ReedSolomon and Off modes. Each physical port's FEC mode can be set independently using ethtool. The supported FEC modes for an interface can be viewed using:



```text
$ ethtool <netdev>
```

The currently configured FEC mode can be viewed using:



```text
$ ethtool --show-fec <netdev>
```

To force the FEC mode for a particular port, auto-negotiation must be disabled (see the [Auto-negotiation](<#rst-auto-negotiation>) section). An example of how to set the FEC mode to Reed-Solomon is:



```text
$ ethtool --set-fec <netdev> encoding rs
```

<a id="rst-auto-negotiation"></a>

### Auto-negotiation

To change auto-negotiation settings, the link must first be put down. After the link is down, auto-negotiation can be enabled or disabled using:



```text
ethtool -s <netdev> autoneg <on|off>
```

<a id="rst-statistics"></a>

## Statistics

Following device statistics are available through the `ethtool -S` interface:


<table>
<caption>NFP device statistics</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


ID

</th>
<th>


Meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


dev_rx_discards

</td>
<td>


1

</td>
<td>


Packet can be discarded on the RX path for one of the following reasons:

> - The NIC is not in promisc mode, and the destination MAC address doesn't match the interfaces' MAC address.
>
> - The received packet is larger than the max buffer size on the host. I.e. it exceeds the Layer 3 MRU.
>
> - There is no freelist descriptor available on the host for the packet. It is likely that the NIC couldn't cache one in time.
>
> - A BPF program discarded the packet.
>
> - The datapath drop action was executed.
>
> - The MAC discarded the packet due to lack of ingress buffer space on the NIC.

</td>
</tr>
<tr>
<td>


dev_rx_errors

</td>
<td>


2

</td>
<td>


A packet can be counted (and dropped) as RX error for the following reasons:

- A problem with the VEB lookup (only when SR-IOV is used).

- A physical layer problem that causes Ethernet errors, like FCS or alignment errors. The cause is usually faulty cables or SFPs.

</td>
</tr>
<tr>
<td>


dev_rx_bytes

</td>
<td>


3

</td>
<td>


Total number of bytes received.

</td>
</tr>
<tr>
<td>


dev_rx_uc_bytes

</td>
<td>


4

</td>
<td>


Unicast bytes received.

</td>
</tr>
<tr>
<td>


dev_rx_mc_bytes

</td>
<td>


5

</td>
<td>


Multicast bytes received.

</td>
</tr>
<tr>
<td>


dev_rx_bc_bytes

</td>
<td>


6

</td>
<td>


Broadcast bytes received.

</td>
</tr>
<tr>
<td>


dev_rx_pkts

</td>
<td>


7

</td>
<td>


Total number of packets received.

</td>
</tr>
<tr>
<td>


dev_rx_mc_pkts

</td>
<td>


8

</td>
<td>


Multicast packets received.

</td>
</tr>
<tr>
<td>


dev_rx_bc_pkts

</td>
<td>


9

</td>
<td>


Broadcast packets received.

</td>
</tr>
<tr>
<td>


dev_tx_discards

</td>
<td>


10

</td>
<td>


A packet can be discarded in the TX direction if the MAC is being flow controlled and the NIC runs out of TX queue space.

</td>
</tr>
<tr>
<td>


dev_tx_errors

</td>
<td>


11

</td>
<td>


A packet can be counted as TX error (and dropped) for one for the following reasons:

- The packet is an LSO segment, but the Layer 3 or Layer 4 offset could not be determined. Therefore LSO could not continue.

- An invalid packet descriptor was received over PCIe.

- The packet Layer 3 length exceeds the device MTU.

- An error on the MAC/physical layer. Usually due to faulty cables or SFPs.

- A CTM buffer could not be allocated.

- The packet offset was incorrect and could not be fixed by the NIC.

</td>
</tr>
<tr>
<td>


dev_tx_bytes

</td>
<td>


12

</td>
<td>


Total number of bytes transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_uc_bytes

</td>
<td>


13

</td>
<td>


Unicast bytes transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_mc_bytes

</td>
<td>


14

</td>
<td>


Multicast bytes transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_bc_bytes

</td>
<td>


15

</td>
<td>


Broadcast bytes transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_pkts

</td>
<td>


16

</td>
<td>


Total number of packets transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_mc_pkts

</td>
<td>


17

</td>
<td>


Multicast packets transmitted.

</td>
</tr>
<tr>
<td>


dev_tx_bc_pkts

</td>
<td>


18

</td>
<td>


Broadcast packets transmitted.

</td>
</tr>
</tbody>
</table>

Note that statistics unknown to the driver will be displayed as `dev_unknown_stat$ID`, where `$ID` refers to the second column above.

---

# Linux Driver for the Pensando(R) Ethernet adapter family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / pensando_

> Pensando Linux Ethernet driver. Copyright(c) 2019 Pensando Systems, Inc

<a id="rst-linux-driver-for-the-pensando-r-ethernet-adapter-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Pensando Linux Ethernet driver. Copyright(c) 2019 Pensando Systems, Inc

<a id="rst-contents"></a>

## Contents

- Identifying the Adapter

- Enabling the driver

- Configuring the driver

- RDMA Support via Auxiliary Device

- Statistics

- Support

<a id="rst-identifying-the-adapter"></a>

## Identifying the Adapter

To find if one or more Pensando PCI Ethernet devices are installed on the host, check for the PCI devices:



```text
$ lspci -d 1dd8:
b5:00.0 Ethernet controller: Device 1dd8:1002
b6:00.0 Ethernet controller: Device 1dd8:1002
```

If such devices are listed as above, then the ionic.ko driver should find and configure them for use.  There should be log entries in the kernel messages such as these:



```text
$ dmesg | grep ionic
ionic 0000:b5:00.0: 126.016 Gb/s available PCIe bandwidth (8.0 GT/s PCIe x16 link)
ionic 0000:b5:00.0 enp181s0: renamed from eth0
ionic 0000:b5:00.0 enp181s0: Link up - 100 Gbps
ionic 0000:b6:00.0: 126.016 Gb/s available PCIe bandwidth (8.0 GT/s PCIe x16 link)
ionic 0000:b6:00.0 enp182s0: renamed from eth0
ionic 0000:b6:00.0 enp182s0: Link up - 100 Gbps
```

Driver and firmware version information can be gathered with either of ethtool or devlink tools:



```text
$ ethtool -i enp181s0
driver: ionic
version: 5.7.0
firmware-version: 1.8.0-28
...

$ devlink dev info pci/0000:b5:00.0
pci/0000:b5:00.0:
  driver ionic
  serial_number FLM18420073
  versions:
      fixed:
        asic.id 0x0
        asic.rev 0x0
      running:
        fw 1.8.0-28
```

See [Documentation/networking/devlink/ionic.rst](/kernel/internals/networking/devlink/ionic.md) for more information on the devlink dev info data.

<a id="rst-enabling-the-driver"></a>

## Enabling the driver

The driver is enabled via the standard kernel configuration system, using the make command:



```text
make oldconfig/menuconfig/etc.
```

The driver is located in the menu structure at:

> - **-&gt; Device Drivers**
>
>   - **-&gt; Network device support (NETDEVICES \[=y\])**
>
>     - **-&gt; Ethernet driver support**
>
>       - **-&gt; Pensando devices**
>
>         -&gt; Pensando Ethernet IONIC Support

<a id="rst-configuring-the-driver"></a>

## Configuring the Driver

<a id="rst-mtu"></a>

### MTU

Jumbo frame support is available with a maximum size of 9194 bytes.

<a id="rst-interrupt-coalescing"></a>

### Interrupt coalescing

Interrupt coalescing can be configured by changing the rx-usecs value with the "ethtool -C" command.  The rx-usecs range is 0-190.  The tx-usecs value reflects the rx-usecs value as they are tied together on the same interrupt.

<a id="rst-sr-iov"></a>

### SR-IOV

Minimal SR-IOV support is currently offered and can be enabled by setting the sysfs 'sriov_numvfs' value, if supported by your particular firmware configuration.

<a id="rst-xdp"></a>

### XDP

Support for XDP includes the basics, plus Jumbo frames, Redirect and ndo_xmit.  There is no current support for zero-copy sockets or HW offload.

<a id="rst-rdma-support-via-auxiliary-device"></a>

## RDMA Support via Auxiliary Device

The ionic driver supports RDMA (Remote Direct Memory Access) functionality through the Linux auxiliary device framework when advertised by the firmware. RDMA capability is detected during device initialization, and if supported, the ethernet driver will create an auxiliary device that allows the RDMA driver to bind and provide InfiniBand/RoCE functionality.

<a id="rst-statistics"></a>

## Statistics

<a id="rst-basic-hardware-stats"></a>

### Basic hardware stats

The commands `netstat -i`, `ip -s link show`, and `ifconfig` show a limited set of statistics taken directly from firmware.  For example:



```text
$ ip -s link show enp181s0
7: enp181s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:ae:cd:00:07:68 brd ff:ff:ff:ff:ff:ff
    RX: bytes  packets  errors  dropped overrun mcast
    414        5        0       0       0       0
    TX: bytes  packets  errors  dropped carrier collsns
    1384       18       0       0       0       0
```

<a id="rst-ethtool-s"></a>

### ethtool -S

The statistics shown from the `ethtool -S` command includes a combination of driver counters and firmware counters, including port and queue specific values. The driver values are counters computed by the driver, and the firmware values are gathered by the firmware from the port hardware and passed through the driver with no further interpretation.

Driver port specific:



```text
tx_packets: 12
tx_bytes: 964
rx_packets: 5
rx_bytes: 414
tx_tso: 0
tx_tso_bytes: 0
tx_csum_none: 12
tx_csum: 0
rx_csum_none: 0
rx_csum_complete: 3
rx_csum_error: 0
xdp_drop: 0
xdp_aborted: 0
xdp_pass: 0
xdp_tx: 0
xdp_redirect: 0
xdp_frames: 0
```

Driver queue specific:



```text
tx_0_pkts: 3
tx_0_bytes: 294
tx_0_clean: 3
tx_0_dma_map_err: 0
tx_0_linearize: 0
tx_0_frags: 0
tx_0_tso: 0
tx_0_tso_bytes: 0
tx_0_hwstamp_valid: 0
tx_0_hwstamp_invalid: 0
tx_0_csum_none: 3
tx_0_csum: 0
tx_0_vlan_inserted: 0
tx_0_xdp_frames: 0
rx_0_pkts: 2
rx_0_bytes: 120
rx_0_dma_map_err: 0
rx_0_alloc_err: 0
rx_0_csum_none: 0
rx_0_csum_complete: 0
rx_0_csum_error: 0
rx_0_hwstamp_valid: 0
rx_0_hwstamp_invalid: 0
rx_0_dropped: 0
rx_0_vlan_stripped: 0
rx_0_xdp_drop: 0
rx_0_xdp_aborted: 0
rx_0_xdp_pass: 0
rx_0_xdp_tx: 0
rx_0_xdp_redirect: 0
```

Firmware port specific:



```text
hw_tx_dropped: 0
hw_rx_dropped: 0
hw_rx_over_errors: 0
hw_rx_missed_errors: 0
hw_tx_aborted_errors: 0
frames_rx_ok: 15
frames_rx_all: 15
frames_rx_bad_fcs: 0
frames_rx_bad_all: 0
octets_rx_ok: 1290
octets_rx_all: 1290
frames_rx_unicast: 10
frames_rx_multicast: 5
frames_rx_broadcast: 0
frames_rx_pause: 0
frames_rx_bad_length: 0
frames_rx_undersized: 0
frames_rx_oversized: 0
frames_rx_fragments: 0
frames_rx_jabber: 0
frames_rx_pripause: 0
frames_rx_stomped_crc: 0
frames_rx_too_long: 0
frames_rx_vlan_good: 3
frames_rx_dropped: 0
frames_rx_less_than_64b: 0
frames_rx_64b: 4
frames_rx_65b_127b: 11
frames_rx_128b_255b: 0
frames_rx_256b_511b: 0
frames_rx_512b_1023b: 0
frames_rx_1024b_1518b: 0
frames_rx_1519b_2047b: 0
frames_rx_2048b_4095b: 0
frames_rx_4096b_8191b: 0
frames_rx_8192b_9215b: 0
frames_rx_other: 0
frames_tx_ok: 31
frames_tx_all: 31
frames_tx_bad: 0
octets_tx_ok: 2614
octets_tx_total: 2614
frames_tx_unicast: 8
frames_tx_multicast: 21
frames_tx_broadcast: 2
frames_tx_pause: 0
frames_tx_pripause: 0
frames_tx_vlan: 0
frames_tx_less_than_64b: 0
frames_tx_64b: 4
frames_tx_65b_127b: 27
frames_tx_128b_255b: 0
frames_tx_256b_511b: 0
frames_tx_512b_1023b: 0
frames_tx_1024b_1518b: 0
frames_tx_1519b_2047b: 0
frames_tx_2048b_4095b: 0
frames_tx_4096b_8191b: 0
frames_tx_8192b_9215b: 0
frames_tx_other: 0
frames_tx_pri_0: 0
frames_tx_pri_1: 0
frames_tx_pri_2: 0
frames_tx_pri_3: 0
frames_tx_pri_4: 0
frames_tx_pri_5: 0
frames_tx_pri_6: 0
frames_tx_pri_7: 0
frames_rx_pri_0: 0
frames_rx_pri_1: 0
frames_rx_pri_2: 0
frames_rx_pri_3: 0
frames_rx_pri_4: 0
frames_rx_pri_5: 0
frames_rx_pri_6: 0
frames_rx_pri_7: 0
tx_pripause_0_1us_count: 0
tx_pripause_1_1us_count: 0
tx_pripause_2_1us_count: 0
tx_pripause_3_1us_count: 0
tx_pripause_4_1us_count: 0
tx_pripause_5_1us_count: 0
tx_pripause_6_1us_count: 0
tx_pripause_7_1us_count: 0
rx_pripause_0_1us_count: 0
rx_pripause_1_1us_count: 0
rx_pripause_2_1us_count: 0
rx_pripause_3_1us_count: 0
rx_pripause_4_1us_count: 0
rx_pripause_5_1us_count: 0
rx_pripause_6_1us_count: 0
rx_pripause_7_1us_count: 0
rx_pause_1us_count: 0
frames_tx_truncated: 0
```

<a id="rst-support"></a>

## Support

For general Linux networking support, please use the netdev mailing list, which is monitored by Pensando personnel:



```text
netdev@vger.kernel.org
```

For more specific support needs, please use the Pensando driver support email:



```text
drivers@pensando.io
```

---

# RDMA Driver for the AMD Pensando(R) Ethernet adapter family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / pensando_

> AMD Pensando RDMA driver. Copyright (C) 2018-2025, Advanced Micro Devices, Inc.

<a id="rst-rdma-driver-for-the-amd-pensando-r-ethernet-adapter-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

AMD Pensando RDMA driver. Copyright (C) 2018-2025, Advanced Micro Devices, Inc.

<a id="rst-overview"></a>

## Overview

The ionic_rdma driver provides Remote Direct Memory Access functionality for AMD Pensando DSC (Distributed Services Card) devices. This driver implements RDMA capabilities as an auxiliary driver that operates in conjunction with the ionic ethernet driver.

The ionic ethernet driver detects RDMA capability during device initialization and creates auxiliary devices that the ionic_rdma driver binds to, establishing the RDMA data path and control interfaces.

<a id="rst-identifying-the-adapter"></a>

## Identifying the Adapter

See [Documentation/networking/device_drivers/ethernet/pensando/ionic.rst](/kernel/internals/networking/device-drivers-ethernet-pensando/ionic.md) for more information on identifying the adapter.

<a id="rst-enabling-the-driver"></a>

## Enabling the driver

The ionic_rdma driver depends on the ionic ethernet driver. See [Documentation/networking/device_drivers/ethernet/pensando/ionic.rst](/kernel/internals/networking/device-drivers-ethernet-pensando/ionic.md) for detailed information on enabling and configuring the ionic driver.

The ionic_rdma driver is enabled via the standard kernel configuration system, using the make command:



```text
make oldconfig/menuconfig/etc.
```

The driver is located in the menu structure at:

> - **-&gt; Device Drivers**
>
>   - **-&gt; InfiniBand support**
>
>     -&gt; AMD Pensando DSC RDMA/RoCE Support

<a id="rst-support"></a>

## Support

For general Linux RDMA support, please use the RDMA mailing list, which is monitored by AMD Pensando personnel:



```text
linux-rdma@vger.kernel.org
```

---

# PPE Ethernet Driver for Qualcomm IPQ SoC Family

_Peios Kernel / Internals / Networking / device_drivers / ethernet / qualcomm / ppe_

> Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.

<a id="rst-ppe-ethernet-driver-for-qualcomm-ipq-soc-family"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.

Author: Lei Wei &lt;[quic_leiwei@quicinc.com](<mailto:quic_leiwei@quicinc.com>)&gt;

<a id="rst-contents"></a>

## Contents

- [PPE Overview](<#rst-ppe-overview>)

- [PPE Driver Overview](<#rst-ppe-driver-overview>)

- [PPE Driver Supported SoCs](<#rst-ppe-driver-supported-socs>)

- [Enabling the Driver](<#rst-enabling-the-driver>)

- [Debugging](<#rst-debugging>)

<a id="rst-ppe-overview"></a>

## PPE Overview

IPQ (Qualcomm Internet Processor) SoC (System-on-Chip) series is Qualcomm's series of networking SoC for Wi-Fi access points. The PPE (Packet Process Engine) is the Ethernet packet process engine in the IPQ SoC.

Below is a simplified hardware diagram of IPQ9574 SoC which includes the PPE engine and other blocks which are in the SoC but outside the PPE engine. These blocks work together to enable the Ethernet for the IPQ SoC:



```text
              +------+ +------+ +------+ +------+ +------+  +------+ start +-------+
              |netdev| |netdev| |netdev| |netdev| |netdev|  |netdev|<------|PHYLINK|
              +------+ +------+ +------+ +------+ +------+  +------+ stop  +-+-+-+-+
                                            |                                | | ^
+-------+     +-------------------------+--------+----------------------+    | | |
| GCC   |     |                         |  EDMA  |                      |    | | |
+---+---+     |  PPE                    +---+----+                      |    | | |
    | clk     |                             |                           |    | | |
    +-------->| +-----------------------+------+-----+---------------+  |    | | |
              | |   Switch Core         |Port0 |     |Port7(EIP FIFO)|  |    | | |
              | |                       +---+--+     +------+--------+  |    | | |
              | |                           |               |        |  |    | | |
+-------+     | |                    +------+---------------+----+   |  |    | | |
|CMN PLL|     | | +---+ +---+ +----+ | +--------+                |   |  |    | | |
+---+---+     | | |BM | |QM | |SCH | | | L2/L3  |  .......       |   |  |    | | |
|   |         | | +---+ +---+ +----+ | +--------+                |   |  |    | | |
|   |         | |                    +------+--------------------+   |  |    | | |
|   |         | |                           |                        |  |    | | |
|   v         | | +-----+-+-----+-+-----+-+-+---+--+-----+-+-----+   |  |    | | |
| +------+    | | |Port1| |Port2| |Port3| |Port4|  |Port5| |Port6|   |  |    | | |
| |NSSCC |    | | +-----+ +-----+ +-----+ +-----+  +-----+ +-----+   |  | mac| | |
| +-+-+--+    | | |MAC0 | |MAC1 | |MAC2 | |MAC3 |  |MAC4 | |MAC5 |   |  |<---+ | |
| ^ | |clk    | | +-----+-+-----+-+-----+-+-----+--+-----+-+-----+   |  | ops  | |
| | | +------>| +----|------|-------|-------|---------|--------|-----+  |      | |
| | |         +---------------------------------------------------------+      | |
| | |                |      |       |       |         |        |               | |
| | |   MII clk      |      QSGMII               USXGMII   USXGMII             | |
| | +--------------->|      |       |       |         |        |               | |
| |                +-------------------------+ +---------+ +---------+         | |
| |125/312.5MHz clk|       (PCS0)            | | (PCS1)  | | (PCS2)  | pcs ops | |
| +----------------+       UNIPHY0           | | UNIPHY1 | | UNIPHY2 |<--------+ |
+----------------->|                         | |         | |         |           |
| 31.25MHz ref clk +-------------------------+ +---------+ +---------+           |
|                     |     |      |      |          |          |                |
|                +-----------------------------------------------------+         |
|25/50MHz ref clk| +-------------------------+    +------+   +------+  | link    |
+--------------->| |      QUAD PHY           |    | PHY4 |   | PHY5 |  |---------+
                 | +-------------------------+    +------+   +------+  | change
                 |                                                     |
                 |                       MDIO bus                      |
                 +-----------------------------------------------------+
```

The CMN (Common) PLL, NSSCC (Networking Sub System Clock Controller) and GCC (Global Clock Controller) blocks are in the SoC and act as clock providers.

The UNIPHY block is in the SoC and provides the PCS (Physical Coding Sublayer) and XPCS (10-Gigabit Physical Coding Sublayer) functions to support different interface modes between the PPE MAC and the external PHY.

This documentation focuses on the descriptions of PPE engine and the PPE driver.

The Ethernet functionality in the PPE (Packet Process Engine) is comprised of three components: the switch core, port wrapper and Ethernet DMA.

The Switch core in the IPQ9574 PPE has maximum of 6 front panel ports and two FIFO interfaces. One of the two FIFO interfaces is used for Ethernet port to host CPU communication using Ethernet DMA. The other one is used to communicate to the EIP engine which is used for IPsec offload. On the IPQ9574, the PPE includes 6 GMAC/XGMACs that can be connected with external Ethernet PHY. Switch core also includes BM (Buffer Management), QM (Queue Management) and SCH (Scheduler) modules for supporting the packet processing.

The port wrapper provides connections from the 6 GMAC/XGMACS to UNIPHY (PCS) supporting various modes such as SGMII/QSGMII/PSGMII/USXGMII/10G-BASER. There are 3 UNIPHY (PCS) instances supported on the IPQ9574.

Ethernet DMA is used to transmit and receive packets between the Ethernet subsystem and ARM host CPU.

The following lists the main blocks in the PPE engine which will be driven by this PPE driver:

- - **BM**

    BM is the hardware buffer manager for the PPE switch ports.

- - **QM**

    Queue Manager for managing the egress hardware queues of the PPE switch ports.

- - **SCH**

    The scheduler which manages the hardware traffic scheduling for the PPE switch ports.

- - **L2**

    The L2 block performs the packet bridging in the switch core. The bridge domain is represented by the VSI (Virtual Switch Instance) domain in PPE. FDB learning can be enabled based on the VSI domain and bridge forwarding occurs within the VSI domain.

- - **MAC**

    The PPE in the IPQ9574 supports up to six MACs (MAC0 to MAC5) which are corresponding to six switch ports (port1 to port6). The MAC block is connected with external PHY through the UNIPHY PCS block. Each MAC block includes the GMAC and XGMAC blocks and the switch port can select to use GMAC or XMAC through a MUX selection according to the external PHY's capability.

- - **EDMA (Ethernet DMA)**

    The Ethernet DMA is used to transmit and receive Ethernet packets between the PPE ports and the ARM cores.

The received packet on a PPE MAC port can be forwarded to another PPE MAC port. It can be also forwarded to internal switch port0 so that the packet can be delivered to the ARM cores using the Ethernet DMA (EDMA) engine. The Ethernet DMA driver will deliver the packet to the corresponding 'netdevice' interface.

The software instantiations of the PPE MAC (netdevice), PCS and external PHYs interact with the Linux PHYLINK framework to manage the connectivity between the PPE ports and the connected PHYs, and the port link states. This is also illustrated in above diagram.

<a id="rst-ppe-driver-overview"></a>

## PPE Driver Overview

PPE driver is Ethernet driver for the Qualcomm IPQ SoC. It is a single platform driver which includes the PPE part and Ethernet DMA part. The PPE part initializes and drives the various blocks in PPE switch core such as BM/QM/L2 blocks and the PPE MACs. The EDMA part drives the Ethernet DMA for packet transfer between PPE ports and ARM cores, and enables the netdevice driver for the PPE ports.

The PPE driver files in drivers/net/ethernet/qualcomm/ppe/ are listed as below:

- Makefile

- ppe.c

- ppe.h

- ppe_config.c

- ppe_config.h

- ppe_debugfs.c

- ppe_debugfs.h

- ppe_regs.h

The ppe.c file contains the main PPE platform driver and undertakes the initialization of PPE switch core blocks such as QM, BM and L2. The configuration APIs for these hardware blocks are provided in the ppe_config.c file.

The ppe.h defines the PPE device data structure which will be used by PPE driver functions.

The ppe_debugfs.c enables the PPE statistics counters such as PPE port Rx and Tx counters, CPU code counters and queue counters.

<a id="rst-ppe-driver-supported-socs"></a>

## PPE Driver Supported SoCs

The PPE driver supports the following IPQ SoC:

- IPQ9574

<a id="rst-enabling-the-driver"></a>

## Enabling the Driver

The driver is located in the menu structure at:



```text
-> Device Drivers
  -> Network device support (NETDEVICES [=y])
    -> Ethernet driver support
      -> Qualcomm devices
        -> Qualcomm Technologies, Inc. PPE Ethernet support
```

If the driver is built as a module, the module will be called qcom-ppe.

The PPE driver functionally depends on the CMN PLL and NSSCC clock controller drivers. Please make sure the dependent modules are installed before installing the PPE driver module.

<a id="rst-debugging"></a>

## Debugging

The PPE hardware counters can be accessed using debugfs interface from the `/sys/kernel/debug/ppe/` directory.

---

# SMC 9xxxx Driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / smsc_

> Revision 0.12

<a id="rst-smc-9xxxx-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Revision 0.12

3/5/96

Copyright 1996  Erik Stahlman

Released under terms of the GNU General Public License.

This file contains the instructions and caveats for my SMC9xxx driver.  You should not be using the driver without reading this file.

Things to note about installation:

> 1. The driver should work on all kernels from 1.2.13 until 1.3.71. (A kernel patch is supplied for 1.3.71 )
>
> 2. If you include this into the kernel, you might need to change some options, such as for forcing IRQ.
>
> 3. To compile as a module, run 'make'. Make will give you the appropriate options for various kernel support.
>
> 4. Loading the driver as a module:
>
>
>
>    ```text
>    use:   insmod smc9194.o
>    optional parameters:
>            io=xxxx    : your base address
>            irq=xx     : your irq
>            ifport=x   :    0 for whatever is default
>                            1 for twisted pair
>                            2 for AUI  ( or BNC on some cards )
>    ```

How to obtain the latest version?

- **FTP:**

  [ftp://fenris.campus.vt.edu/smc9/smc9-12.tar.gz](<ftp://fenris.campus.vt.edu/smc9/smc9-12.tar.gz>) [ftp://sfbox.vt.edu/filebox/F/fenris/smc9/smc9-12.tar.gz](<ftp://sfbox.vt.edu/filebox/F/fenris/smc9/smc9-12.tar.gz>)

- **Contacting me:**

  [erik@mail.vt.edu](<mailto:erik@mail.vt.edu>)

---

# Linux Driver for the Synopsys(R) Ethernet Controllers "stmmac"

_Peios Kernel / Internals / Networking / device_drivers / ethernet / stmicro_

> Authors: Giuseppe Cavallaro <peppe.cavallaro@st.com>, Alexandre Torgue <alexandre.torgue@st.com>, Jose Abreu <joabreu@synopsys.com>

<a id="rst-linux-driver-for-the-synopsys-r-ethernet-controllers-stmmac"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Authors: Giuseppe Cavallaro &lt;[peppe.cavallaro@st.com](<mailto:peppe.cavallaro@st.com>)&gt;, Alexandre Torgue &lt;[alexandre.torgue@st.com](<mailto:alexandre.torgue@st.com>)&gt;, Jose Abreu &lt;[joabreu@synopsys.com](<mailto:joabreu@synopsys.com>)&gt;

<a id="rst-contents"></a>

## Contents

- In This Release

- Feature List

- Kernel Configuration

- Command Line Parameters

- Driver Information and Notes

- Debug Information

- Support

<a id="rst-in-this-release"></a>

## In This Release

This file describes the stmmac Linux Driver for all the Synopsys(R) Ethernet Controllers.

Currently, this network device driver is for all STi embedded MAC/GMAC (i.e. 7xxx/5xxx SoCs), SPEAr (arm), Loongson1B (mips) and XILINX XC2V3000 FF1152AMT0221 D1215994A VIRTEX FPGA board. The Synopsys Ethernet QoS 5.0 IPK is also supported.

DesignWare(R) Cores Ethernet MAC 10/100/1000 Universal version 3.70a (and older) and DesignWare(R) Cores Ethernet Quality-of-Service version 4.0 (and upper) have been used for developing this driver as well as DesignWare(R) Cores XGMAC - 10G Ethernet MAC and DesignWare(R) Cores Enterprise MAC - 100G Ethernet MAC.

This driver supports both the platform bus and PCI.

This driver includes support for the following Synopsys(R) DesignWare(R) Cores Ethernet Controllers and corresponding minimum and maximum versions:


<table>
<thead>
<tr>
<th>


Controller Name

</th>
<th>


Min. Version

</th>
<th>


Max. Version

</th>
<th>


Abbrev. Name

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Ethernet MAC Universal

</td>
<td>


N/A

</td>
<td>


3.73a

</td>
<td>


GMAC

</td>
</tr>
<tr>
<td>


Ethernet Quality-of-Service

</td>
<td>


4.00a

</td>
<td>


N/A

</td>
<td>


GMAC4+

</td>
</tr>
<tr>
<td>


XGMAC - 10G Ethernet MAC

</td>
<td>


2.10a

</td>
<td>


N/A

</td>
<td>


XGMAC2+

</td>
</tr>
<tr>
<td>


XLGMAC - 100G Ethernet MAC

</td>
<td>


2.00a

</td>
<td>


N/A

</td>
<td>


XLGMAC2+

</td>
</tr>
</tbody>
</table>

For questions related to hardware requirements, refer to the documentation supplied with your Ethernet adapter. All hardware requirements listed apply to use with Linux.

<a id="rst-feature-list"></a>

## Feature List

- **The following features are available in this driver:**

  - GMII/MII/RGMII/SGMII/RMII/XGMII/XLGMII Interface

  - Half-Duplex / Full-Duplex Operation

  - Energy Efficient Ethernet (EEE)

  - IEEE 802.3x PAUSE Packets (Flow Control)

  - RMON/MIB Counters

  - IEEE 1588 Timestamping (PTP)

  - Pulse-Per-Second Output (PPS)

  - MDIO Clause 22 / Clause 45 Interface

  - MAC Loopback

  - ARP Offloading

  - Automatic CRC / PAD Insertion and Checking

  - Checksum Offload for Received and Transmitted Packets

  - Standard or Jumbo Ethernet Packets

  - Source Address Insertion / Replacement

  - VLAN TAG Insertion / Replacement / Deletion / Filtering (HASH and PERFECT)

  - Programmable TX and RX Watchdog and Coalesce Settings

  - Destination Address Filtering (PERFECT)

  - HASH Filtering (Multicast)

  - Layer 3 / Layer 4 Filtering

  - Remote Wake-Up Detection

  - Receive Side Scaling (RSS)

  - Frame Preemption for TX and RX

  - Programmable Burst Length, Threshold, Queue Size

  - Multiple Queues (up to 8)

  - Multiple Scheduling Algorithms (TX: WRR, DWRR, WFQ, SP, CBS, EST, TBS; RX: WRR, SP)

  - Flexible RX Parser

  - TCP / UDP Segmentation Offload (TSO, USO)

  - Split Header (SPH)

  - Safety Features (ECC Protection, Data Parity Protection)

  - Selftests using Ethtool

<a id="rst-kernel-configuration"></a>

## Kernel Configuration

- **The kernel configuration option is `CONFIG_STMMAC_ETH`:**

  - `CONFIG_STMMAC_PLATFORM`: is to enable the platform driver.

  - `CONFIG_STMMAC_PCI`: is to enable the pci driver.

<a id="rst-command-line-parameters"></a>

## Command Line Parameters

If the driver is built as a module the following optional parameters are used by entering them on the command line with the modprobe command using this syntax (e.g. for PCI module):



```text
modprobe stmmac_pci [<option>=<VAL1>,<VAL2>,...]
```

Driver parameters can be also passed in command line by using:



```text
stmmaceth=watchdog:100,chain_mode=1
```

The default value for each parameter is generally the recommended setting, unless otherwise noted.

<a id="rst-watchdog"></a>

### watchdog

**Valid Range:** 5000-None

**Default Value:** 5000

This parameter overrides the transmit timeout in milliseconds.

<a id="rst-debug"></a>

### debug

**Valid Range:** 0-16 (0=none,...,16=all)

**Default Value:** 0

This parameter adjusts the level of debug messages displayed in the system logs.

<a id="rst-phyaddr"></a>

### phyaddr

**Valid Range:** 0-31

**Default Value:** -1

This parameter overrides the physical address of the PHY device.

<a id="rst-flow-ctrl"></a>

### flow\_ctrl

**Valid Range:** 0-3 (0=off,1=rx,2=tx,3=rx/tx)

**Default Value:** 3

This parameter changes the default Flow Control ability.

<a id="rst-pause"></a>

### pause

**Valid Range:** 0-65535

**Default Value:** 65535

This parameter changes the default Flow Control Pause time.

<a id="rst-tc"></a>

### tc

**Valid Range:** 64-256

**Default Value:** 64

This parameter changes the default HW FIFO Threshold control value.

<a id="rst-buf-sz"></a>

### buf\_sz

**Valid Range:** 1536-16384

**Default Value:** 1536

This parameter changes the default RX DMA packet buffer size.

<a id="rst-eee-timer"></a>

### eee\_timer

**Valid Range:** 0-None

**Default Value:** 1000

This parameter changes the default LPI TX Expiration time in milliseconds.

<a id="rst-chain-mode"></a>

### chain\_mode

**Valid Range:** 0-1 (0=off,1=on)

**Default Value:** 0

This parameter changes the default mode of operation from Ring Mode to Chain Mode.

<a id="rst-driver-information-and-notes"></a>

## Driver Information and Notes

<a id="rst-transmit-process"></a>

### Transmit Process

The xmit method is invoked when the kernel needs to transmit a packet; it sets the descriptors in the ring and informs the DMA engine that there is a packet ready to be transmitted.

By default, the driver sets the `NETIF_F_SG` bit in the features field of the `net_device` structure, enabling the scatter-gather feature. This is true on chips and configurations where the checksum can be done in hardware.

Once the controller has finished transmitting the packet, timer will be scheduled to release the transmit resources.

<a id="rst-receive-process"></a>

### Receive Process

When one or more packets are received, an interrupt happens. The interrupts are not queued, so the driver has to scan all the descriptors in the ring during the receive process.

This is based on NAPI, so the interrupt handler signals only if there is work to be done, and it exits. Then the poll method will be scheduled at some future point.

The incoming packets are stored, by the DMA, in a list of pre-allocated socket buffers in order to avoid the memcpy (zero-copy).

<a id="rst-interrupt-mitigation"></a>

### Interrupt Mitigation

The driver is able to mitigate the number of its DMA interrupts using NAPI for the reception on chips older than the 3.50. New chips have an HW RX Watchdog used for this mitigation.

Mitigation parameters can be tuned by ethtool.

<a id="rst-wol"></a>

### WoL

Wake up on Lan feature through Magic and Unicast frames are supported for the GMAC, GMAC4/5 and XGMAC core.

<a id="rst-dma-descriptors"></a>

### DMA Descriptors

Driver handles both normal and alternate descriptors. The latter has been only tested on DesignWare(R) Cores Ethernet MAC Universal version 3.41a and later.

stmmac supports DMA descriptor to operate both in dual buffer (RING) and linked-list(CHAINED) mode. In RING each descriptor points to two data buffer pointers whereas in CHAINED mode they point to only one data buffer pointer. RING mode is the default.

In CHAINED mode each descriptor will have pointer to next descriptor in the list, hence creating the explicit chaining in the descriptor itself, whereas such explicit chaining is not possible in RING mode.

<a id="rst-extended-descriptors"></a>

### Extended Descriptors

The extended descriptors give us information about the Ethernet payload when it is carrying PTP packets or TCP/UDP/ICMP over IP. These are not available on GMAC Synopsys(R) chips older than the 3.50. At probe time the driver will decide if these can be actually used. This support also is mandatory for PTPv2 because the extra descriptors are used for saving the hardware timestamps and Extended Status.

<a id="rst-ethtool-support"></a>

### Ethtool Support

Ethtool is supported. For example, driver statistics (including RMON), internal errors can be taken using:



```text
ethtool -S ethX
```

Ethtool selftests are also supported. This allows to do some early sanity checks to the HW using MAC and PHY loopback mechanisms:



```text
ethtool -t ethX
```

<a id="rst-jumbo-and-segmentation-offloading"></a>

### Jumbo and Segmentation Offloading

Jumbo frames are supported and tested for the GMAC. The GSO has been also added but it's performed in software. LRO is not supported.

<a id="rst-tso-support"></a>

### TSO Support

TSO (TCP Segmentation Offload) feature is supported by GMAC &gt; 4.x and XGMAC chip family. When a packet is sent through TCP protocol, the TCP stack ensures that the SKB provided to the low level driver (stmmac in our case) matches with the maximum frame len (IP header + TCP header + payload &lt;= 1500 bytes (for MTU set to 1500)). It means that if an application using TCP want to send a packet which will have a length (after adding headers) &gt; 1514 the packet will be split in several TCP packets: The data payload is split and headers (TCP/IP ..) are added. It is done by software.

When TSO is enabled, the TCP stack doesn't care about the maximum frame length and provide SKB packet to stmmac as it is. The GMAC IP will have to perform the segmentation by it self to match with maximum frame length.

This feature can be enabled in device tree through `snps,tso` entry.

<a id="rst-energy-efficient-ethernet"></a>

### Energy Efficient Ethernet

Energy Efficient Ethernet (EEE) enables IEEE 802.3 MAC sublayer along with a family of Physical layer to operate in the Low Power Idle (LPI) mode. The EEE mode supports the IEEE 802.3 MAC operation at 100Mbps, 1000Mbps and 1Gbps.

The LPI mode allows power saving by switching off parts of the communication device functionality when there is no data to be transmitted &amp; received. The system on both the side of the link can disable some functionalities and save power during the period of low-link utilization. The MAC controls whether the system should enter or exit the LPI mode and communicate this to PHY.

As soon as the interface is opened, the driver verifies if the EEE can be supported. This is done by looking at both the DMA HW capability register and the PHY devices MCD registers.

To enter in TX LPI mode the driver needs to have a software timer that enable and disable the LPI mode when there is nothing to be transmitted.

<a id="rst-precision-time-protocol-ptp"></a>

### Precision Time Protocol (PTP)

The driver supports the IEEE 1588-2002, Precision Time Protocol (PTP), which enables precise synchronization of clocks in measurement and control systems implemented with technologies such as network communication.

In addition to the basic timestamp features mentioned in IEEE 1588-2002 Timestamps, new GMAC cores support the advanced timestamp features. IEEE 1588-2008 can be enabled when configuring the Kernel.

<a id="rst-sgmii-rgmii-support"></a>

### SGMII/RGMII Support

New GMAC devices provide own way to manage RGMII/SGMII. This information is available at run-time by looking at the HW capability register. This means that the stmmac can manage auto-negotiation and link status w/o using the PHYLIB stuff. In fact, the HW provides a subset of extended registers to restart the ANE, verify Full/Half duplex mode and Speed. Thanks to these registers, it is possible to look at the Auto-negotiated Link Parter Ability.

<a id="rst-physical"></a>

### Physical

The driver is compatible with Physical Abstraction Layer to be connected with PHY and GPHY devices.

<a id="rst-platform-information"></a>

### Platform Information

Several information can be passed through the platform and device-tree.



```text
struct plat_stmmacenet_data {
```

1. Bus identifier:



   ```text
   int bus_id;
   ```

2\) PHY Physical Address. If set to -1 the driver will pick the first PHY it finds:



```text
int phy_addr;
```

3. PHY Device Interface:



   ```text
   int interface;
   ```

4. Specific platform fields for the MDIO bus:



   ```text
   struct stmmac_mdio_bus_data *mdio_bus_data;
   ```

5. Internal DMA parameters:



   ```text
   struct stmmac_dma_cfg *dma_cfg;
   ```

6. Fixed CSR Clock Range selection:



   ```text
   int clk_csr;
   ```

7. HW uses the GMAC core:



   ```text
   int has_gmac;
   ```

8. If set the MAC will use Enhanced Descriptors:



   ```text
   int enh_desc;
   ```

9. Core is able to perform TX Checksum and/or RX Checksum in HW:



   ```text
   int tx_coe;
   int rx_coe;
   ```

11\) Some HWs are not able to perform the csum in HW for over-sized frames due to limited buffer sizes. Setting this flag the csum will be done in SW on JUMBO frames:



```text
int bugged_jumbo;
```

12. Core has the embedded power module:



    ```text
    int pmt;
    ```

13. Force DMA to use the Store and Forward mode or Threshold mode:



    ```text
    int force_sf_dma_mode;
    int force_thresh_dma_mode;
    ```

15. Force to disable the RX Watchdog feature and switch to NAPI mode:



    ```text
    int riwt_off;
    ```

16. Limit the maximum operating speed and MTU:



    ```text
    int max_speed;
    int maxmtu;
    ```

18. Number of Multicast/Unicast filters:



    ```text
    int multicast_filter_bins;
    int unicast_filter_entries;
    ```

20. Limit the maximum TX and RX FIFO size:



    ```text
    int tx_fifo_size;
    int rx_fifo_size;
    ```

21. Use the specified number of TX and RX Queues:



    ```text
    u32 rx_queues_to_use;
    u32 tx_queues_to_use;
    ```

22. Use the specified TX and RX scheduling algorithm:



    ```text
    u8 rx_sched_algorithm;
    u8 tx_sched_algorithm;
    ```

23. Internal TX and RX Queue parameters:



    ```text
    struct stmmac_rxq_cfg rx_queues_cfg[MTL_MAX_RX_QUEUES];
    struct stmmac_txq_cfg tx_queues_cfg[MTL_MAX_TX_QUEUES];
    ```

24\) This callback is used for modifying some syscfg registers (on ST SoCs) according to the link speed negotiated by the physical layer:



```text
void (*fix_mac_speed)(void *priv, unsigned int speed);
```

25\) Callbacks used for calling a custom initialization; This is sometimes necessary on some platforms (e.g. ST boxes) where the HW needs to have set some PIO lines or system cfg registers. init/exit callbacks should not use or modify platform data:



```text
int (*init)(struct platform_device *pdev, void *priv);
void (*exit)(struct platform_device *pdev, void *priv);
```

26\) Perform HW setup of the bus. For example, on some ST platforms this field is used to configure the AMBA bridge to generate more efficient STBus traffic:



```text
struct mac_device_info *(*setup)(void *priv);
void *bsp_priv;
```

27. Internal clocks and rates:



    ```text
    struct clk *stmmac_clk;
    struct clk *pclk;
    struct clk *clk_ptp_ref;
    unsigned int clk_ptp_rate;
    unsigned int clk_ref_rate;
    s32 ptp_max_adj;
    ```

28. Main reset:



    ```text
    struct reset_control *stmmac_rst;
    ```

29. AXI Internal Parameters:



    ```text
    struct stmmac_axi *axi;
    ```

30. HW uses GMAC&gt;4 cores:



    ```text
    int has_gmac4;
    ```

31. HW is sun8i based:



    ```text
    bool has_sun8i;
    ```

32. Enables TSO feature:



    ```text
    bool tso_en;
    ```

33. Enables Receive Side Scaling (RSS) feature:



    ```text
    int rss_en;
    ```

34. MAC Port selection:



    ```text
    int mac_port_sel_speed;
    ```

35. Enables TX LPI Clock Gating:



    ```text
    bool en_tx_lpi_clockgating;
    ```

36. HW uses XGMAC&gt;2.10 cores:



    ```text
    int has_xgmac;
    ```



```text
}
```

For MDIO bus data, we have:



```text
struct stmmac_mdio_bus_data {
```

1. PHY mask passed when MDIO bus is registered:



   ```text
   unsigned int phy_mask;
   ```

2. List of IRQs, one per PHY:



   ```text
   int *irqs;
   ```

3. If IRQs is NULL, use this for probed PHY:



   ```text
   int probed_phy_irq;
   ```

4. Set to true if PHY needs reset:



   ```text
   bool needs_reset;
   ```



```text
}
```

For DMA engine configuration, we have:



```text
struct stmmac_dma_cfg {
```

1. Programmable Burst Length (TX and RX):



   ```text
   int pbl;
   ```

2. If set, DMA TX / RX will use this value rather than pbl:



   ```text
   int txpbl;
   int rxpbl;
   ```

3. Enable 8xPBL:



   ```text
   bool pblx8;
   ```

4. Enable Fixed or Mixed burst:



   ```text
   int fixed_burst;
   int mixed_burst;
   ```

5. Enable Address Aligned Beats:



   ```text
   bool aal;
   ```

6. Enable Enhanced Addressing (&gt; 32 bits):



   ```text
   bool eame;
   ```



```text
}
```

For DMA AXI parameters, we have:



```text
struct stmmac_axi {
```

1. Enable AXI LPI:



   ```text
   bool axi_lpi_en;
   bool axi_xit_frm;
   ```

2. Set AXI Write / Read maximum outstanding requests:



   ```text
   u32 axi_wr_osr_lmt;
   u32 axi_rd_osr_lmt;
   ```

3. Set AXI 4KB bursts:



   ```text
   bool axi_kbbe;
   ```

4. Set AXI maximum burst length map:



   ```text
   u32 axi_blen[AXI_BLEN];
   ```

5. Set AXI Fixed burst / mixed burst:



   ```text
   bool axi_fb;
   bool axi_mb;
   ```

6. Set AXI rebuild incrx mode:



   ```text
   bool axi_rb;
   ```



```text
}
```

For the RX Queues configuration, we have:



```text
struct stmmac_rxq_cfg {
```

1. Mode to use (DCB or AVB):



   ```text
   u8 mode_to_use;
   ```

2. DMA channel to use:



   ```text
   u32 chan;
   ```

3. Packet routing, if applicable:



   ```text
   u8 pkt_route;
   ```

4. Use priority routing, and priority to route:



   ```text
   bool use_prio;
   u32 prio;
   ```



```text
}
```

For the TX Queues configuration, we have:



```text
struct stmmac_txq_cfg {
```

1. Queue weight in scheduler:



   ```text
   u32 weight;
   ```

2. Mode to use (DCB or AVB):



   ```text
   u8 mode_to_use;
   ```

3. Credit Base Shaper Parameters:



   ```text
   u32 send_slope;
   u32 idle_slope;
   u32 high_credit;
   u32 low_credit;
   ```

4. Use priority scheduling, and priority:



   ```text
   bool use_prio;
   u32 prio;
   ```



```text
}
```

<a id="rst-device-tree-information"></a>

### Device Tree Information

Please refer to the following document: Documentation/devicetree/bindings/net/snps,dwmac.yaml

<a id="rst-hw-capabilities"></a>

### HW Capabilities

Note that, starting from new chips, where it is available the HW capability register, many configurations are discovered at run-time for example to understand if EEE, HW csum, PTP, enhanced descriptor etc are actually available. As strategy adopted in this driver, the information from the HW capability register can replace what has been passed from the platform.

<a id="rst-debug-information"></a>

## Debug Information

The driver exports many information i.e. internal statistics, debug information, MAC and DMA registers etc.

These can be read in several ways depending on the type of the information actually needed.

For example a user can be use the ethtool support to get statistics: e.g. using: `ethtool -S ethX` (that shows the Management counters (MMC) if supported) or sees the MAC/DMA registers: e.g. using: `ethtool -d ethX`

Compiling the Kernel with `CONFIG_DEBUG_FS` the driver will export the following debugfs entries:

> - `descriptors_status`: To show the DMA TX/RX descriptor rings
>
> - `dma_cap`: To show the HW Capabilities

Developer can also use the `debug` module parameter to get further debug information (please see: NETIF Msg Level).

<a id="rst-support"></a>

## Support

If an issue is identified with the released source code on a supported kernel with a supported adapter, email the specific information related to the issue to [netdev@vger.kernel.org](<mailto:netdev@vger.kernel.org>)

---

# Texas Instruments K3 AM65 CPSW NUSS switchdev based ethernet driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / ti_

> In order to rename via udev:

<a id="rst-texas-instruments-k3-am65-cpsw-nuss-switchdev-based-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Version:** 1.0

<a id="rst-port-renaming"></a>

## Port renaming

In order to rename via udev:



```text
ip -d link show dev sw0p1 | grep switchid

SUBSYSTEM=="net", ACTION=="add", ATTR{phys_switch_id}==<switchid>, \
        ATTR{phys_port_name}!="", NAME="sw0$attr{phys_port_name}"
```

<a id="rst-multi-mac-mode"></a>

## Multi mac mode

- The driver is operating in multi-mac mode by default, thus working as N individual network interfaces.

<a id="rst-devlink-configuration-parameters"></a>

## Devlink configuration parameters

See [Documentation/networking/devlink/am65-nuss-cpsw-switch.rst](/kernel/internals/networking/devlink/am65-nuss-cpsw-switch.md)

<a id="rst-enabling-switch"></a>

## Enabling "switch"

The Switch mode can be enabled by configuring devlink driver parameter "switch_mode" to 1/true:



```text
devlink dev param set platform/c000000.ethernet \
name switch_mode value true cmode runtime
```

This can be done regardless of the state of Port's netdev devices - UP/DOWN, but Port's netdev devices have to be in UP before joining to the bridge to avoid overwriting of bridge configuration as CPSW switch driver completely reloads its configuration when first port changes its state to UP.

When both interfaces have joined the bridge - CPSW switch driver will enable marking packets with offload_fwd_mark flag.

All configuration is implemented via switchdev API.

<a id="rst-bridge-setup"></a>

## Bridge setup



```text
devlink dev param set platform/c000000.ethernet \
name switch_mode value true cmode runtime

ip link add name br0 type bridge
ip link set dev br0 type bridge ageing_time 1000
ip link set dev sw0p1 up
ip link set dev sw0p2 up
ip link set dev sw0p1 master br0
ip link set dev sw0p2 master br0

[*] bridge vlan add dev br0 vid 1 pvid untagged self

[*] if vlan_filtering=1. where default_pvid=1

Note. Steps [*] are mandatory.
```

<a id="rst-on-off-stp"></a>

## On/off STP



```text
ip link set dev BRDEV type bridge stp_state 1/0
```

<a id="rst-vlan-configuration"></a>

## VLAN configuration



```text
bridge vlan add dev br0 vid 1 pvid untagged self <---- add cpu port to VLAN 1
```

Note. This step is mandatory for bridge/default_pvid.

<a id="rst-add-extra-vlans"></a>

## Add extra VLANs

> 1. untagged:
>
>
>
>    ```text
>    bridge vlan add dev sw0p1 vid 100 pvid untagged master
>    bridge vlan add dev sw0p2 vid 100 pvid untagged master
>    bridge vlan add dev br0 vid 100 pvid untagged self <---- Add cpu port to VLAN100
>    ```
>
> 2. tagged:
>
>
>
>    ```text
>    bridge vlan add dev sw0p1 vid 100 master
>    bridge vlan add dev sw0p2 vid 100 master
>    bridge vlan add dev br0 vid 100 pvid tagged self <---- Add cpu port to VLAN100
>    ```

<a id="rst-fdbs"></a>

### FDBs

FDBs are automatically added on the appropriate switch port upon detection

Manually adding FDBs:



```text
bridge fdb add aa:bb:cc:dd:ee:ff dev sw0p1 master vlan 100
bridge fdb add aa:bb:cc:dd:ee:fe dev sw0p2 master <---- Add on all VLANs
```

<a id="rst-mdbs"></a>

### MDBs

MDBs are automatically added on the appropriate switch port upon detection

Manually adding MDBs:



```text
bridge mdb add dev br0 port sw0p1 grp 239.1.1.1 permanent vid 100
bridge mdb add dev br0 port sw0p1 grp 239.1.1.1 permanent <---- Add on all VLANs
```

<a id="rst-multicast-flooding"></a>

## Multicast flooding

CPU port mcast_flooding is always on

Turning flooding on/off on switch ports: bridge link set dev sw0p1 mcast_flood on/off

<a id="rst-access-and-trunk-port"></a>

## Access and Trunk port



```text
bridge vlan add dev sw0p1 vid 100 pvid untagged master
bridge vlan add dev sw0p2 vid 100 master


bridge vlan add dev br0 vid 100 self
ip link add link br0 name br0.100 type vlan id 100
```

Note. Setting PVID on Bridge device itself works only for default VLAN (default_pvid).

---

# Texas Instruments CPSW ethernet driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / ti_

> The cpsw has 3 CBS shapers for each external ports. This document describes MQPRIO and CBS Qdisc offload configuration for cpsw driver based on examples. It potentially can be used in audio video bridging (AVB) and time sensitive…

<a id="rst-texas-instruments-cpsw-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-multiqueue-cbs-mqprio"></a>

## Multiqueue &amp; CBS &amp; MQPRIO

The cpsw has 3 CBS shapers for each external ports. This document describes MQPRIO and CBS Qdisc offload configuration for cpsw driver based on examples. It potentially can be used in audio video bridging (AVB) and time sensitive networking (TSN).

The following examples were tested on AM572x EVM and BBB boards.

<a id="rst-test-setup"></a>

## Test setup

Under consideration two examples with AM572x EVM running cpsw driver in dual\_emac mode.

Several prerequisites:

- TX queues must be rated starting from txq0 that has highest priority

- Traffic classes are used starting from 0, that has highest priority

- CBS shapers should be used with rated queues

- The bandwidth for CBS shapers has to be set a little bit more then potential incoming rate, thus, rate of all incoming tx queues has to be a little less

- Real rates can differ, due to discreetness

- Map skb-priority to txq is not enough, also skb-priority to l2 prio map has to be created with ip or vconfig tool

- Any l2/socket prio (0 - 7) for classes can be used, but for simplicity default values are used: 3 and 2

- only 2 classes tested: A and B, but checked and can work with more, maximum allowed 4, but only for 3 rate can be set.

<a id="rst-test-setup-for-examples"></a>

## Test setup for examples



```text
                                    +-------------------------------+
                                    |--+                            |
                                    |  |      Workstation0          |
                                    |E |  MAC 18:03:73:66:87:42     |
+-----------------------------+  +--|t |                            |
|                    | 1  | E |  |  |h |./tsn_listener -d \         |
|  Target board:     | 0  | t |--+  |0 | 18:03:73:66:87:42 -i eth0 \|
|  AM572x EVM        | 0  | h |     |  | -s 1500                    |
|                    | 0  | 0 |     |--+                            |
|  Only 2 classes:   |Mb  +---|     +-------------------------------+
|  class A, class B  |        |
|                    |    +---|     +-------------------------------+
|                    | 1  | E |     |--+                            |
|                    | 0  | t |     |  |      Workstation1          |
|                    | 0  | h |--+  |E |  MAC 20:cf:30:85:7d:fd     |
|                    |Mb  | 1 |  +--|t |                            |
+-----------------------------+     |h |./tsn_listener -d \         |
                                    |0 | 20:cf:30:85:7d:fd -i eth0 \|
                                    |  | -s 1500                    |
                                    |--+                            |
                                    +-------------------------------+
```

<a id="rst-example-1-one-port-tx-avb-configuration-scheme-for-target-board"></a>

### Example 1: One port tx AVB configuration scheme for target board

(prints and scheme for AM572x evm, applicable for single port boards)

- tc - traffic class

- txq - transmit queue

- p - priority

- f - fifo (cpsw fifo)

- S - shaper configured



```text
+------------------------------------------------------------------+ u
| +---------------+  +---------------+  +------+ +------+          | s
| |               |  |               |  |      | |      |          | e
| | App 1         |  | App 2         |  | Apps | | Apps |          | r
| | Class A       |  | Class B       |  | Rest | | Rest |          |
| | Eth0          |  | Eth0          |  | Eth0 | | Eth1 |          | s
| | VLAN100       |  | VLAN100       |  |   |  | |   |  |          | p
| | 40 Mb/s       |  | 20 Mb/s       |  |   |  | |   |  |          | a
| | SO_PRIORITY=3 |  | SO_PRIORITY=2 |  |   |  | |   |  |          | c
| |   |           |  |   |           |  |   |  | |   |  |          | e
| +---|-----------+  +---|-----------+  +---|--+ +---|--+          |
+-----|------------------|------------------|--------|-------------+
    +-+     +------------+                  |        |
    |       |             +-----------------+     +--+
    |       |             |                       |
+---|-------|-------------|-----------------------|----------------+
| +----+ +----+ +----+ +----+                   +----+             |
| | p3 | | p2 | | p1 | | p0 |                   | p0 |             | k
| \    / \    / \    / \    /                   \    /             | e
|  \  /   \  /   \  /   \  /                     \  /              | r
|   \/     \/     \/     \/                       \/               | n
|    |     |             |                        |                | e
|    |     |       +-----+                        |                | l
|    |     |       |                              |                |
| +----+ +----+ +----+                          +----+             | s
| |tc0 | |tc1 | |tc2 |                          |tc0 |             | p
| \    / \    / \    /                          \    /             | a
|  \  /   \  /   \  /                            \  /              | c
|   \/     \/     \/                              \/               | e
|   |      |       +-----+                        |                |
|   |      |       |     |                        |                |
|   |      |       |     |                        |                |
|   |      |       |     |                        |                |
| +----+ +----+ +----+ +----+                   +----+             |
| |txq0| |txq1| |txq2| |txq3|                   |txq4|             |
| \    / \    / \    / \    /                   \    /             |
|  \  /   \  /   \  /   \  /                     \  /              |
|   \/     \/     \/     \/                       \/               |
| +-|------|------|------|--+                  +--|--------------+ |
| | |      |      |      |  | Eth0.100         |  |     Eth1     | |
+---|------|------|------|------------------------|----------------+
    |      |      |      |                        |
    p      p      p      p                        |
    3      2      0-1, 4-7  <- L2 priority        |
    |      |      |      |                        |
    |      |      |      |                        |
+---|------|------|------|------------------------|----------------+
|   |      |      |      |             |----------+                |
| +----+ +----+ +----+ +----+       +----+                         |
| |dma7| |dma6| |dma5| |dma4|       |dma3|                         |
| \    / \    / \    / \    /       \    /                         | c
|  \S /   \S /   \  /   \  /         \  /                          | p
|   \/     \/     \/     \/           \/                           | s
|   |      |      | +-----            |                            | w
|   |      |      | |                 |                            |
|   |      |      | |                 |                            | d
| +----+ +----+ +----+p            p+----+                         | r
| |    | |    | |    |o            o|    |                         | i
| | f3 | | f2 | | f0 |r            r| f0 |                         | v
| |tc0 | |tc1 | |tc2 |t            t|tc0 |                         | e
| \CBS / \CBS / \CBS /1            2\CBS /                         | r
|  \S /   \S /   \  /                \  /                          |
|   \/     \/     \/                  \/                           |
+------------------------------------------------------------------+
```

1. ```text
   // Add 4 tx queues, for interface Eth0, and 1 tx queue for Eth1
   $ ethtool -L eth0 rx 1 tx 5
   rx unmodified, ignoring
   ```

2. ```text
   // Check if num of queues is set correctly:
   $ ethtool -l eth0
   Channel parameters for eth0:
   Pre-set maximums:
   RX:             8
   TX:             8
   Other:          0
   Combined:       0
   Current hardware settings:
   RX:             1
   TX:             5
   Other:          0
   Combined:       0
   ```

3. ```text
   // TX queues must be rated starting from 0, so set bws for tx0 and tx1
   // Set rates 40 and 20 Mb/s appropriately.
   // Pay attention, real speed can differ a bit due to discreetness.
   // Leave last 2 tx queues not rated.
   $ echo 40 > /sys/class/net/eth0/queues/tx-0/tx_maxrate
   $ echo 20 > /sys/class/net/eth0/queues/tx-1/tx_maxrate
   ```

4. ```text
   // Check maximum rate of tx (cpdma) queues:
   $ cat /sys/class/net/eth0/queues/tx-*/tx_maxrate
   40
   20
   0
   0
   0
   ```

5. ```text
   // Map skb->priority to traffic class:
   // 3pri -> tc0, 2pri -> tc1, (0,1,4-7)pri -> tc2
   // Map traffic class to transmit queue:
   // tc0 -> txq0, tc1 -> txq1, tc2 -> (txq2, txq3)
   $ tc qdisc replace dev eth0 handle 100: parent root mqprio num_tc 3 \
   map 2 2 1 0 2 2 2 2 2 2 2 2 2 2 2 2 queues 1@0 1@1 2@2 hw 1
   ```

5a)



```text
// As two interface sharing same set of tx queues, assign all traffic
// coming to interface Eth1 to separate queue in order to not mix it
// with traffic from interface Eth0, so use separate txq to send
// packets to Eth1, so all prio -> tc0 and tc0 -> txq4
// Here hw 0, so here still default configuration for eth1 in hw
$ tc qdisc replace dev eth1 handle 100: parent root mqprio num_tc 1 \
map 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 queues 1@4 hw 0
```

6. ```text
   // Check classes settings
   $ tc -g class show dev eth0
   +---(100:ffe2) mqprio
   |    +---(100:3) mqprio
   |    +---(100:4) mqprio
   |
   +---(100:ffe1) mqprio
   |    +---(100:2) mqprio
   |
   +---(100:ffe0) mqprio
       +---(100:1) mqprio

   $ tc -g class show dev eth1
   +---(100:ffe0) mqprio
       +---(100:5) mqprio
   ```

7. ```text
   // Set rate for class A - 41 Mbit (tc0, txq0) using CBS Qdisc
   // Set it +1 Mb for reserve (important!)
   // here only idle slope is important, others arg are ignored
   // Pay attention, real speed can differ a bit due to discreetness
   $ tc qdisc add dev eth0 parent 100:1 cbs locredit -1438 \
   hicredit 62 sendslope -959000 idleslope 41000 offload 1
   net eth0: set FIFO3 bw = 50
   ```

8. ```text
   // Set rate for class B - 21 Mbit (tc1, txq1) using CBS Qdisc:
   // Set it +1 Mb for reserve (important!)
   $ tc qdisc add dev eth0 parent 100:2 cbs locredit -1468 \
   hicredit 65 sendslope -979000 idleslope 21000 offload 1
   net eth0: set FIFO2 bw = 30
   ```

9. ```text
   // Create vlan 100 to map sk->priority to vlan qos
   $ ip link add link eth0 name eth0.100 type vlan id 100
   8021q: 802.1Q VLAN Support v1.8
   8021q: adding VLAN 0 to HW filter on device eth0
   8021q: adding VLAN 0 to HW filter on device eth1
   net eth0: Adding vlanid 100 to vlan filter
   ```

10. ```text
    // Map skb->priority to L2 prio, 1 to 1
    $ ip link set eth0.100 type vlan \
    egress 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

11. ```text
    // Check egress map for vlan 100
    $ cat /proc/net/vlan/eth0.100
    [...]
    INGRESS priority mappings: 0:0  1:0  2:0  3:0  4:0  5:0  6:0 7:0
    EGRESS priority mappings: 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

12. ```text
    // Run your appropriate tools with socket option "SO_PRIORITY"
    // to 3 for class A and/or to 2 for class B
    // (I took at https://lore.kernel.org/r/20171017010128.22141-1-vinicius.gomes@intel.com/)
    ./tsn_talker -d 18:03:73:66:87:42 -i eth0.100 -p3 -s 1500&
    ./tsn_talker -d 18:03:73:66:87:42 -i eth0.100 -p2 -s 1500&
    ```

13. ```text
    // run your listener on workstation (should be in same vlan)
    // (I took at https://lore.kernel.org/r/20171017010128.22141-1-vinicius.gomes@intel.com/)
    ./tsn_listener -d 18:03:73:66:87:42 -i enp5s0 -s 1500
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39000 kbps
    ```

14. ```text
    // Restore default configuration if needed
    $ ip link del eth0.100
    $ tc qdisc del dev eth1 root
    $ tc qdisc del dev eth0 root
    net eth0: Prev FIFO2 is shaped
    net eth0: set FIFO3 bw = 0
    net eth0: set FIFO2 bw = 0
    $ ethtool -L eth0 rx 1 tx 1
    ```

<a id="rst-example-2-two-port-tx-avb-configuration-scheme-for-target-board"></a>

### Example 2: Two port tx AVB configuration scheme for target board

(prints and scheme for AM572x evm, for dual emac boards only)



```text
+------------------------------------------------------------------+ u
| +----------+  +----------+  +------+  +----------+  +----------+ | s
| |          |  |          |  |      |  |          |  |          | | e
| | App 1    |  | App 2    |  | Apps |  | App 3    |  | App 4    | | r
| | Class A  |  | Class B  |  | Rest |  | Class B  |  | Class A  | |
| | Eth0     |  | Eth0     |  |   |  |  | Eth1     |  | Eth1     | | s
| | VLAN100  |  | VLAN100  |  |   |  |  | VLAN100  |  | VLAN100  | | p
| | 40 Mb/s  |  | 20 Mb/s  |  |   |  |  | 10 Mb/s  |  | 30 Mb/s  | | a
| | SO_PRI=3 |  | SO_PRI=2 |  |   |  |  | SO_PRI=3 |  | SO_PRI=2 | | c
| |   |      |  |   |      |  |   |  |  |   |      |  |   |      | | e
| +---|------+  +---|------+  +---|--+  +---|------+  +---|------+ |
+-----|-------------|-------------|---------|-------------|--------+
    +-+     +-------+             |         +----------+  +----+
    |       |             +-------+------+             |       |
    |       |             |              |             |       |
+---|-------|-------------|--------------|-------------|-------|---+
| +----+ +----+ +----+ +----+          +----+ +----+ +----+ +----+ |
| | p3 | | p2 | | p1 | | p0 |          | p0 | | p1 | | p2 | | p3 | | k
| \    / \    / \    / \    /          \    / \    / \    / \    / | e
|  \  /   \  /   \  /   \  /            \  /   \  /   \  /   \  /  | r
|   \/     \/     \/     \/              \/     \/     \/     \/   | n
|   |      |             |                |             |      |   | e
|   |      |        +----+                +----+        |      |   | l
|   |      |        |                          |        |      |   |
| +----+ +----+ +----+                        +----+ +----+ +----+ | s
| |tc0 | |tc1 | |tc2 |                        |tc2 | |tc1 | |tc0 | | p
| \    / \    / \    /                        \    / \    / \    / | a
|  \  /   \  /   \  /                          \  /   \  /   \  /  | c
|   \/     \/     \/                            \/     \/     \/   | e
|   |      |       +-----+                +-----+      |       |   |
|   |      |       |     |                |     |      |       |   |
|   |      |       |     |                |     |      |       |   |
|   |      |       |     |    E      E    |     |      |       |   |
| +----+ +----+ +----+ +----+ t      t +----+ +----+ +----+ +----+ |
| |txq0| |txq1| |txq4| |txq5| h      h |txq6| |txq7| |txq3| |txq2| |
| \    / \    / \    / \    / 0      1 \    / \    / \    / \    / |
|  \  /   \  /   \  /   \  /  .      .  \  /   \  /   \  /   \  /  |
|   \/     \/     \/     \/   1      1   \/     \/     \/     \/   |
| +-|------|------|------|--+ 0      0 +-|------|------|------|--+ |
| | |      |      |      |  | 0      0 | |      |      |      |  | |
+---|------|------|------|---------------|------|------|------|----+
    |      |      |      |               |      |      |      |
    p      p      p      p               p      p      p      p
    3      2      0-1, 4-7   <-L2 pri->  0-1, 4-7      2      3
    |      |      |      |               |      |      |      |
    |      |      |      |               |      |      |      |
+---|------|------|------|---------------|------|------|------|----+
|   |      |      |      |               |      |      |      |    |
| +----+ +----+ +----+ +----+          +----+ +----+ +----+ +----+ |
| |dma7| |dma6| |dma3| |dma2|          |dma1| |dma0| |dma4| |dma5| |
| \    / \    / \    / \    /          \    / \    / \    / \    / | c
|  \S /   \S /   \  /   \  /            \  /   \  /   \S /   \S /  | p
|   \/     \/     \/     \/              \/     \/     \/     \/   | s
|   |      |      | +-----                |      |      |      |   | w
|   |      |      | |                     +----+ |      |      |   |
|   |      |      | |                          | |      |      |   | d
| +----+ +----+ +----+p                      p+----+ +----+ +----+ | r
| |    | |    | |    |o                      o|    | |    | |    | | i
| | f3 | | f2 | | f0 |r        CPSW          r| f3 | | f2 | | f0 | | v
| |tc0 | |tc1 | |tc2 |t                      t|tc0 | |tc1 | |tc2 | | e
| \CBS / \CBS / \CBS /1                      2\CBS / \CBS / \CBS / | r
|  \S /   \S /   \  /                          \S /   \S /   \  /  |
|   \/     \/     \/                            \/     \/     \/   |
+------------------------------------------------------------------+
========================================Eth==========================>
```

1. ```text
   // Add 8 tx queues, for interface Eth0, but they are common, so are accessed
   // by two interfaces Eth0 and Eth1.
   $ ethtool -L eth1 rx 1 tx 8
   rx unmodified, ignoring
   ```

2. ```text
   // Check if num of queues is set correctly:
   $ ethtool -l eth0
   Channel parameters for eth0:
   Pre-set maximums:
   RX:             8
   TX:             8
   Other:          0
   Combined:       0
   Current hardware settings:
   RX:             1
   TX:             8
   Other:          0
   Combined:       0
   ```

3. ```text
   // TX queues must be rated starting from 0, so set bws for tx0 and tx1 for Eth0
   // and for tx2 and tx3 for Eth1. That is, rates 40 and 20 Mb/s appropriately
   // for Eth0 and 30 and 10 Mb/s for Eth1.
   // Real speed can differ a bit due to discreetness
   // Leave last 4 tx queues as not rated
   $ echo 40 > /sys/class/net/eth0/queues/tx-0/tx_maxrate
   $ echo 20 > /sys/class/net/eth0/queues/tx-1/tx_maxrate
   $ echo 30 > /sys/class/net/eth1/queues/tx-2/tx_maxrate
   $ echo 10 > /sys/class/net/eth1/queues/tx-3/tx_maxrate
   ```

4. ```text
   // Check maximum rate of tx (cpdma) queues:
   $ cat /sys/class/net/eth0/queues/tx-*/tx_maxrate
   40
   20
   30
   10
   0
   0
   0
   0
   ```

5. ```text
   // Map skb->priority to traffic class for Eth0:
   // 3pri -> tc0, 2pri -> tc1, (0,1,4-7)pri -> tc2
   // Map traffic class to transmit queue:
   // tc0 -> txq0, tc1 -> txq1, tc2 -> (txq4, txq5)
   $ tc qdisc replace dev eth0 handle 100: parent root mqprio num_tc 3 \
   map 2 2 1 0 2 2 2 2 2 2 2 2 2 2 2 2 queues 1@0 1@1 2@4 hw 1
   ```

6. ```text
   // Check classes settings
   $ tc -g class show dev eth0
   +---(100:ffe2) mqprio
   |    +---(100:5) mqprio
   |    +---(100:6) mqprio
   |
   +---(100:ffe1) mqprio
   |    +---(100:2) mqprio
   |
   +---(100:ffe0) mqprio
       +---(100:1) mqprio
   ```

7. ```text
   // Set rate for class A - 41 Mbit (tc0, txq0) using CBS Qdisc for Eth0
   // here only idle slope is important, others ignored
   // Real speed can differ a bit due to discreetness
   $ tc qdisc add dev eth0 parent 100:1 cbs locredit -1470 \
   hicredit 62 sendslope -959000 idleslope 41000 offload 1
   net eth0: set FIFO3 bw = 50
   ```

8. ```text
   // Set rate for class B - 21 Mbit (tc1, txq1) using CBS Qdisc for Eth0
   $ tc qdisc add dev eth0 parent 100:2 cbs locredit -1470 \
   hicredit 65 sendslope -979000 idleslope 21000 offload 1
   net eth0: set FIFO2 bw = 30
   ```

9. ```text
   // Create vlan 100 to map sk->priority to vlan qos for Eth0
   $ ip link add link eth0 name eth0.100 type vlan id 100
   net eth0: Adding vlanid 100 to vlan filter
   ```

10. ```text
    // Map skb->priority to L2 prio for Eth0.100, one to one
    $ ip link set eth0.100 type vlan \
    egress 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

11. ```text
    // Check egress map for vlan 100
    $ cat /proc/net/vlan/eth0.100
    [...]
    INGRESS priority mappings: 0:0  1:0  2:0  3:0  4:0  5:0  6:0 7:0
    EGRESS priority mappings: 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

12. ```text
    // Map skb->priority to traffic class for Eth1:
    // 3pri -> tc0, 2pri -> tc1, (0,1,4-7)pri -> tc2
    // Map traffic class to transmit queue:
    // tc0 -> txq2, tc1 -> txq3, tc2 -> (txq6, txq7)
    $ tc qdisc replace dev eth1 handle 100: parent root mqprio num_tc 3 \
    map 2 2 1 0 2 2 2 2 2 2 2 2 2 2 2 2 queues 1@2 1@3 2@6 hw 1
    ```

13. ```text
    // Check classes settings
    $ tc -g class show dev eth1
    +---(100:ffe2) mqprio
    |    +---(100:7) mqprio
    |    +---(100:8) mqprio
    |
    +---(100:ffe1) mqprio
    |    +---(100:4) mqprio
    |
    +---(100:ffe0) mqprio
        +---(100:3) mqprio
    ```

14. ```text
    // Set rate for class A - 31 Mbit (tc0, txq2) using CBS Qdisc for Eth1
    // here only idle slope is important, others ignored, but calculated
    // for interface speed - 100Mb for eth1 port.
    // Set it +1 Mb for reserve (important!)
    $ tc qdisc add dev eth1 parent 100:3 cbs locredit -1035 \
    hicredit 465 sendslope -69000 idleslope 31000 offload 1
    net eth1: set FIFO3 bw = 31
    ```

15. ```text
    // Set rate for class B - 11 Mbit (tc1, txq3) using CBS Qdisc for Eth1
    // Set it +1 Mb for reserve (important!)
    $ tc qdisc add dev eth1 parent 100:4 cbs locredit -1335 \
    hicredit 405 sendslope -89000 idleslope 11000 offload 1
    net eth1: set FIFO2 bw = 11
    ```

16. ```text
    // Create vlan 100 to map sk->priority to vlan qos for Eth1
    $ ip link add link eth1 name eth1.100 type vlan id 100
    net eth1: Adding vlanid 100 to vlan filter
    ```

17. ```text
    // Map skb->priority to L2 prio for Eth1.100, one to one
    $ ip link set eth1.100 type vlan \
    egress 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

18. ```text
    // Check egress map for vlan 100
    $ cat /proc/net/vlan/eth1.100
    [...]
    INGRESS priority mappings: 0:0  1:0  2:0  3:0  4:0  5:0  6:0 7:0
    EGRESS priority mappings: 0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7
    ```

19. ```text
    // Run appropriate tools with socket option "SO_PRIORITY" to 3
    // for class A and to 2 for class B. For both interfaces
    ./tsn_talker -d 18:03:73:66:87:42 -i eth0.100 -p2 -s 1500&
    ./tsn_talker -d 18:03:73:66:87:42 -i eth0.100 -p3 -s 1500&
    ./tsn_talker -d 20:cf:30:85:7d:fd -i eth1.100 -p2 -s 1500&
    ./tsn_talker -d 20:cf:30:85:7d:fd -i eth1.100 -p3 -s 1500&
    ```

20. ```text
    // run your listener on workstation (should be in same vlan)
    // (I took at https://lore.kernel.org/r/20171017010128.22141-1-vinicius.gomes@intel.com/)
    ./tsn_listener -d 18:03:73:66:87:42 -i enp5s0 -s 1500
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39012 kbps
    Receiving data rate: 39000 kbps
    ```

21. ```text
    // Restore default configuration if needed
    $ ip link del eth1.100
    $ ip link del eth0.100
    $ tc qdisc del dev eth1 root
    net eth1: Prev FIFO2 is shaped
    net eth1: set FIFO3 bw = 0
    net eth1: set FIFO2 bw = 0
    $ tc qdisc del dev eth0 root
    net eth0: Prev FIFO2 is shaped
    net eth0: set FIFO3 bw = 0
    net eth0: set FIFO2 bw = 0
    $ ethtool -L eth0 rx 1 tx 1
    ```

---

# Texas Instruments CPSW switchdev based ethernet driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / ti_

> On older udev versions renaming of ethX to swXpY will not be automatically supported

<a id="rst-texas-instruments-cpsw-switchdev-based-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Version:** 2.0

<a id="rst-port-renaming"></a>

## Port renaming

On older udev versions renaming of ethX to swXpY will not be automatically supported

In order to rename via udev:



```text
ip -d link show dev sw0p1 | grep switchid

SUBSYSTEM=="net", ACTION=="add", ATTR{phys_switch_id}==<switchid>, \
        ATTR{phys_port_name}!="", NAME="sw0$attr{phys_port_name}"
```

<a id="rst-dual-mac-mode"></a>

## Dual mac mode

- The new (cpsw_new.c) driver is operating in dual-emac mode by default, thus working as 2 individual network interfaces. Main differences from legacy CPSW driver are:

> - optimized promiscuous mode: The P0_UNI_FLOOD (both ports) is enabled in addition to ALLMULTI (current port) instead of ALE_BYPASS. So, Ports in promiscuous mode will keep possibility of mcast and vlan filtering, which is provides significant benefits when ports are joined to the same bridge, but without enabling "switch" mode, or to different bridges.
>
> - learning disabled on ports as it make not too much sense for segregated ports - no forwarding in HW.
>
> - enabled basic support for devlink.
>
>
>
>   ```text
>   devlink dev show
>           platform/48484000.switch
>
>   devlink dev param show
>   platform/48484000.switch:
>   name switch_mode type driver-specific
>   values:
>           cmode runtime value false
>   name ale_bypass type driver-specific
>   values:
>           cmode runtime value false
>   ```

<a id="rst-devlink-configuration-parameters"></a>

## Devlink configuration parameters

See [Documentation/networking/devlink/ti-cpsw-switch.rst](/kernel/internals/networking/devlink/ti-cpsw-switch.md)

<a id="rst-bridging-in-dual-mac-mode"></a>

## Bridging in dual mac mode

The dual_mac mode requires two vids to be reserved for internal purposes, which, by default, equal CPSW Port numbers. As result, bridge has to be configured in vlan unaware mode or default_pvid has to be adjusted:



```text
ip link add name br0 type bridge
ip link set dev br0 type bridge vlan_filtering 0
echo 0 > /sys/class/net/br0/bridge/default_pvid
ip link set dev sw0p1 master br0
ip link set dev sw0p2 master br0
```

or:



```text
ip link add name br0 type bridge
ip link set dev br0 type bridge vlan_filtering 0
echo 100 > /sys/class/net/br0/bridge/default_pvid
ip link set dev br0 type bridge vlan_filtering 1
ip link set dev sw0p1 master br0
ip link set dev sw0p2 master br0
```

<a id="rst-enabling-switch"></a>

## Enabling "switch"

The Switch mode can be enabled by configuring devlink driver parameter "switch_mode" to 1/true:



```text
devlink dev param set platform/48484000.switch \
name switch_mode value 1 cmode runtime
```

This can be done regardless of the state of Port's netdev devices - UP/DOWN, but Port's netdev devices have to be in UP before joining to the bridge to avoid overwriting of bridge configuration as CPSW switch driver copletly reloads its configuration when first Port changes its state to UP.

When both interfaces have joined the bridge - CPSW switch driver will enable marking packets with offload_fwd_mark flag unless "ale_bypass=0"

All configuration is implemented via switchdev API.

<a id="rst-bridge-setup"></a>

## Bridge setup



```text
devlink dev param set platform/48484000.switch \
name switch_mode value 1 cmode runtime

ip link add name br0 type bridge
ip link set dev br0 type bridge ageing_time 1000
ip link set dev sw0p1 up
ip link set dev sw0p2 up
ip link set dev sw0p1 master br0
ip link set dev sw0p2 master br0

[*] bridge vlan add dev br0 vid 1 pvid untagged self

[*] if vlan_filtering=1. where default_pvid=1

Note. Steps [*] are mandatory.
```

<a id="rst-on-off-stp"></a>

## On/off STP



```text
ip link set dev BRDEV type bridge stp_state 1/0
```

<a id="rst-vlan-configuration"></a>

## VLAN configuration



```text
bridge vlan add dev br0 vid 1 pvid untagged self <---- add cpu port to VLAN 1
```

Note. This step is mandatory for bridge/default_pvid.

<a id="rst-add-extra-vlans"></a>

## Add extra VLANs

> 1. untagged:
>
>
>
>    ```text
>    bridge vlan add dev sw0p1 vid 100 pvid untagged master
>    bridge vlan add dev sw0p2 vid 100 pvid untagged master
>    bridge vlan add dev br0 vid 100 pvid untagged self <---- Add cpu port to VLAN100
>    ```
>
> 2. tagged:
>
>
>
>    ```text
>    bridge vlan add dev sw0p1 vid 100 master
>    bridge vlan add dev sw0p2 vid 100 master
>    bridge vlan add dev br0 vid 100 pvid tagged self <---- Add cpu port to VLAN100
>    ```

<a id="rst-fdbs"></a>

### FDBs

FDBs are automatically added on the appropriate switch port upon detection

Manually adding FDBs:



```text
bridge fdb add aa:bb:cc:dd:ee:ff dev sw0p1 master vlan 100
bridge fdb add aa:bb:cc:dd:ee:fe dev sw0p2 master <---- Add on all VLANs
```

<a id="rst-mdbs"></a>

### MDBs

MDBs are automatically added on the appropriate switch port upon detection

Manually adding MDBs:



```text
bridge mdb add dev br0 port sw0p1 grp 239.1.1.1 permanent vid 100
bridge mdb add dev br0 port sw0p1 grp 239.1.1.1 permanent <---- Add on all VLANs
```

<a id="rst-multicast-flooding"></a>

## Multicast flooding

CPU port mcast_flooding is always on

Turning flooding on/off on switch ports: bridge link set dev sw0p1 mcast_flood on/off

<a id="rst-access-and-trunk-port"></a>

## Access and Trunk port



```text
bridge vlan add dev sw0p1 vid 100 pvid untagged master
bridge vlan add dev sw0p2 vid 100 master


bridge vlan add dev br0 vid 100 self
ip link add link br0 name br0.100 type vlan id 100
```

Note. Setting PVID on Bridge device itself working only for default VLAN (default_pvid).

<a id="rst-nfs"></a>

## NFS

The only way for NFS to work is by chrooting to a minimal environment when switch configuration that will affect connectivity is needed. Assuming you are booting NFS with eth1 interface(the script is hacky and it's just there to prove NFS is doable).

setup.sh:



```text
#!/bin/sh
mkdir proc
mount -t proc none /proc
ifconfig br0  > /dev/null
if [ $? -ne 0 ]; then
        echo "Setting up bridge"
        ip link add name br0 type bridge
        ip link set dev br0 type bridge ageing_time 1000
        ip link set dev br0 type bridge vlan_filtering 1

        ip link set eth1 down
        ip link set eth1 name sw0p1
        ip link set dev sw0p1 up
        ip link set dev sw0p2 up
        ip link set dev sw0p2 master br0
        ip link set dev sw0p1 master br0
        bridge vlan add dev br0 vid 1 pvid untagged self
        ifconfig sw0p1 0.0.0.0
        udhchc -i br0
fi
umount /proc
```

run_nfs.sh::



```text
#!/bin/sh
mkdir /tmp/root/bin -p
mkdir /tmp/root/lib -p

cp -r /lib/ /tmp/root/
cp -r /bin/ /tmp/root/
cp /sbin/ip /tmp/root/bin
cp /sbin/bridge /tmp/root/bin
cp /sbin/ifconfig /tmp/root/bin
cp /sbin/udhcpc /tmp/root/bin
cp /path/to/setup.sh /tmp/root/bin
chroot /tmp/root/ busybox sh /bin/setup.sh

run ./run_nfs.sh
```

---

# Texas Instruments ICSSG PRUETH ethernet driver

_Peios Kernel / Internals / Networking / device_drivers / ethernet / ti_

> Every ICSSG core has two Programmable Real-Time Unit(PRUs), two auxiliary Real-Time Transfer Unit (RTUs), and two Transmit Real-Time Transfer Units (TX_PRUs). Each one of these runs its own firmware. The firmwares combnined are referred as…

<a id="rst-texas-instruments-icssg-prueth-ethernet-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Version:** 1.0

<a id="rst-icssg-firmware"></a>

## ICSSG Firmware

Every ICSSG core has two Programmable Real-Time Unit(PRUs), two auxiliary Real-Time Transfer Unit (RTUs), and two Transmit Real-Time Transfer Units (TX_PRUs). Each one of these runs its own firmware. The firmwares combnined are referred as ICSSG Firmware.

<a id="rst-firmware-statistics"></a>

## Firmware Statistics

The ICSSG firmware maintains certain statistics which are dumped by the driver via `ethtool -S <interface>`

These statistics are as follows,

> - `FW_RTU_PKT_DROP`: Diagnostic error counter which increments when RTU drops a locally injected packet due to port being disabled or rule violation.
>
> - `FW_Q0_OVERFLOW`: TX overflow counter for queue0
>
> - `FW_Q1_OVERFLOW`: TX overflow counter for queue1
>
> - `FW_Q2_OVERFLOW`: TX overflow counter for queue2
>
> - `FW_Q3_OVERFLOW`: TX overflow counter for queue3
>
> - `FW_Q4_OVERFLOW`: TX overflow counter for queue4
>
> - `FW_Q5_OVERFLOW`: TX overflow counter for queue5
>
> - `FW_Q6_OVERFLOW`: TX overflow counter for queue6
>
> - `FW_Q7_OVERFLOW`: TX overflow counter for queue7
>
> - `FW_DROPPED_PKT`: This counter is incremented when a packet is dropped at PRU because of rule violation.
>
> - `FW_RX_ERROR`: Incremented if there was a CRC error or Min/Max frame error at PRU
>
> - `FW_RX_DS_INVALID`: Incremented when RTU detects Data Status invalid condition
>
> - `FW_TX_DROPPED_PACKET`: Counter for packets dropped via TX Port
>
> - `FW_TX_TS_DROPPED_PACKET`: Counter for packets with TS flag dropped via TX Port
>
> - `FW_INF_PORT_DISABLED`: Incremented when RX frame is dropped due to port being disabled
>
> - `FW_INF_SAV`: Incremented when RX frame is dropped due to Source Address violation
>
> - `FW_INF_SA_DL`: Incremented when RX frame is dropped due to Source Address being in the denylist
>
> - `FW_INF_PORT_BLOCKED`: Incremented when RX frame is dropped due to port being blocked and frame being a special frame
>
> - `FW_INF_DROP_TAGGED` : Incremented when RX frame is dropped for being tagged
>
> - `FW_INF_DROP_PRIOTAGGED`: Incremented when RX frame is dropped for being priority tagged
>
> - `FW_INF_DROP_NOTAG`: Incremented when RX frame is dropped for being untagged
>
> - `FW_INF_DROP_NOTMEMBER`: Incremented when RX frame is dropped for port not being member of VLAN
>
> - `FW_RX_EOF_SHORT_FRMERR`: Incremented if End Of Frame (EOF) task is scheduled without seeing RX_B1
>
> - `FW_RX_B0_DROP_EARLY_EOF`: Incremented when frame is dropped due to Early EOF
>
> - `FW_TX_JUMBO_FRM_CUTOFF`: Incremented when frame is cut off to prevent packet size &gt; 2000 Bytes
>
> - `FW_RX_EXP_FRAG_Q_DROP`: Incremented when express frame is received in the same queue as the previous fragment
>
> - `FW_RX_FIFO_OVERRUN`: RX fifo overrun counter
>
> - `FW_CUT_THR_PKT`: Incremented when a packet is forwarded using Cut-Through forwarding method
>
> - `FW_HOST_RX_PKT_CNT`: Number of valid packets sent by Rx PRU to Host on PSI
>
> - `FW_HOST_TX_PKT_CNT`: Number of valid packets copied by RTU0 to Tx queues
>
> - `FW_HOST_EGRESS_Q_PRE_OVERFLOW`: Host Egress Q (Pre-emptible) Overflow Counter
>
> - `FW_HOST_EGRESS_Q_EXP_OVERFLOW`: Host Egress Q (Pre-emptible) Overflow Counter

---

# TLAN driver for Linux

_Peios Kernel / Internals / Networking / device_drivers / ethernet / ti_

> 1997-1998 Caldera, Inc.

<a id="rst-tlan-driver-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Version:** 1.14a

- **(C)** 1997-1998 Caldera, Inc.

- **(C)** 1998 James Banks

- **(C)** 1999-2001 Torben Mathiasen &lt;[tmm@image.dk](<mailto:tmm@image.dk>), [torben.mathiasen@compaq.com](<mailto:torben.mathiasen@compaq.com>)&gt;

For driver information/updates visit [http://www.compaq.com](<http://www.compaq.com>)

<a id="rst-i-supported-devices"></a>

## I. Supported Devices

> Only PCI devices will work with this driver.
>
> Supported:
>
>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Vendor ID
>
> </th>
> <th>
>
>
> Device ID
>
> </th>
> <th>
>
>
> Name
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> ae32
>
> </td>
> <td>
>
>
> Compaq Netelligent 10/100 TX PCI UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> ae34
>
> </td>
> <td>
>
>
> Compaq Netelligent 10 T PCI UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> ae35
>
> </td>
> <td>
>
>
> Compaq Integrated NetFlex 3/P
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> ae40
>
> </td>
> <td>
>
>
> Compaq Netelligent Dual 10/100 TX PCI UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> ae43
>
> </td>
> <td>
>
>
> Compaq Netelligent Integrated 10/100 TX UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> b011
>
> </td>
> <td>
>
>
> Compaq Netelligent 10/100 TX Embedded UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> b012
>
> </td>
> <td>
>
>
> Compaq Netelligent 10 T/2 PCI UTP/Coax
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> b030
>
> </td>
> <td>
>
>
> Compaq Netelligent 10/100 TX UTP
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> f130
>
> </td>
> <td>
>
>
> Compaq NetFlex 3/P
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0e11
>
> </td>
> <td>
>
>
> f150
>
> </td>
> <td>
>
>
> Compaq NetFlex 3/P
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 108d
>
> </td>
> <td>
>
>
> 0012
>
> </td>
> <td>
>
>
> Olicom OC-2325
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 108d
>
> </td>
> <td>
>
>
> 0013
>
> </td>
> <td>
>
>
> Olicom OC-2183
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 108d
>
> </td>
> <td>
>
>
> 0014
>
> </td>
> <td>
>
>
> Olicom OC-2326
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Caveats:
>
> I am not sure if 100BaseTX daughterboards (for those cards which support such things) will work.  I haven't had any solid evidence either way.
>
> However, if a card supports 100BaseTx without requiring an add on daughterboard, it should work with 100BaseTx.
>
> The "Netelligent 10 T/2 PCI UTP/Coax" (b012) device is untested, but I do not expect any problems.

<a id="rst-ii-driver-options"></a>

## II. Driver Options

> 1. You can append debug=x to the end of the insmod line to get debug messages, where x is a bit field where the bits mean the following:
>
>
>    <table>
>    <tbody>
>    <tr>
>    <td>
>
>
>    0x01
>
>    </td>
>    <td>
>
>
>    Turn on general debugging messages.
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    0x02
>
>    </td>
>    <td>
>
>
>    Turn on receive debugging messages.
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    0x04
>
>    </td>
>    <td>
>
>
>    Turn on transmit debugging messages.
>
>    </td>
>    </tr>
>    <tr>
>    <td>
>
>
>    0x08
>
>    </td>
>    <td>
>
>
>    Turn on list debugging messages.
>
>    </td>
>    </tr>
>    </tbody>
>    </table>
>
> 2. You can append aui=1 to the end of the insmod line to cause the adapter to use the AUI interface instead of the 10 Base T interface.  This is also what to do if you want to use the BNC connector on a TLAN based device.  (Setting this option on a device that does not have an AUI/BNC connector will probably cause it to not function correctly.)
>
> 3. You can set duplex=1 to force half duplex, and duplex=2 to force full duplex.
>
> 4. You can set speed=10 to force 10Mbs operation, and speed=100 to force 100Mbs operation. (I'm not sure what will happen if a card which only supports 10Mbs is forced into 100Mbs mode.)
>
> 5. You have to use speed=X duplex=Y together now. If you just do "insmod tlan.o speed=100" the driver will do Auto-Neg. To force a 10Mbps Half-Duplex link do "insmod tlan.o speed=10 duplex=1".
>
> 6. If the driver is built into the kernel, you can use the 3rd and 4th parameters to set aui and debug respectively.  For example:
>
>
>
>    ```text
>    ether=0,0,0x1,0x7,eth0
>    ```
>
>    This sets aui to 0x1 and debug to 0x7, assuming eth0 is a supported TLAN device.
>
>    The bits in the third byte are assigned as follows:
>
>    >
>    > <table>
>    > <tbody>
>    > <tr>
>    > <td>
>    >
>    >
>    > 0x01
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > aui
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > 0x02
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > use half duplex
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > 0x04
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > use full duplex
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > 0x08
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > use 10BaseT
>    >
>    > </td>
>    > </tr>
>    > <tr>
>    > <td>
>    >
>    >
>    > 0x10
>    >
>    > </td>
>    > <td>
>    >
>    >
>    > use 100BaseTx
>    >
>    > </td>
>    > </tr>
>    > </tbody>
>    > </table>
>
>    You also need to set both speed and duplex settings when forcing speeds with kernel-parameters. ether=0,0,0x12,0,eth0 will force link to 100Mbps Half-Duplex.
>
> 7. If you have more than one tlan adapter in your system, you can use the above options on a per adapter basis. To force a 100Mbit/HD link with your eth1 adapter use:
>
>
>
>    ```text
>    insmod tlan speed=0,100 duplex=0,1
>    ```
>
>    Now eth0 will use auto-neg and eth1 will be forced to 100Mbit/HD. Note that the tlan driver supports a maximum of 8 adapters.

<a id="rst-iii-things-to-try-if-you-have-problems"></a>

## III. Things to try if you have problems

> 1. Make sure your card's PCI id is among those listed in section I, above.
>
> 2. Make sure routing is correct.
>
> 3. Try forcing different speed/duplex settings

There is also a tlan mailing list which you can join by sending "subscribe tlan" in the body of an email to [majordomo@vuser.vu.union.edu](<mailto:majordomo@vuser.vu.union.edu>).

There is also a tlan website at [http://www.compaq.com](<http://www.compaq.com>)

---

# Linux Base Driver for WangXun(R) Gigabit PCI Express Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / wangxun_

> WangXun Gigabit Linux driver. Copyright (c) 2019 - 2022 Beijing WangXun Technology Co., Ltd.

<a id="rst-linux-base-driver-for-wangxun-r-gigabit-pci-express-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

WangXun Gigabit Linux driver. Copyright (c) 2019 - 2022 Beijing WangXun Technology Co., Ltd.

<a id="rst-support"></a>

## Support

> If you have problems with the software or hardware, please contact our customer support team via email at [nic-support@net-swift.com](<mailto:nic-support@net-swift.com>) or check our website at [https://www.net-swift.com](<https://www.net-swift.com>)

---

# Linux Base Virtual Function Driver for Wangxun(R) Gigabit Ethernet

_Peios Kernel / Internals / Networking / device_drivers / ethernet / wangxun_

> WangXun Gigabit Virtual Function Linux driver. Copyright(c) 2015 - 2025 Beijing WangXun Technology Co., Ltd.

<a id="rst-linux-base-virtual-function-driver-for-wangxun-r-gigabit-ethernet"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

WangXun Gigabit Virtual Function Linux driver. Copyright(c) 2015 - 2025 Beijing WangXun Technology Co., Ltd.

<a id="rst-support"></a>

## Support

For general information, go to the website at: [https://www.net-swift.com](<https://www.net-swift.com>)

If you got any problem, contact Wangxun support team via [nic-support@net-swift.com](<mailto:nic-support@net-swift.com>) and Cc: netdev.

---

# Linux Base Driver for WangXun(R) 10 Gigabit PCI Express Adapters

_Peios Kernel / Internals / Networking / device_drivers / ethernet / wangxun_

> WangXun 10 Gigabit Linux driver. Copyright (c) 2015 - 2022 Beijing WangXun Technology Co., Ltd.

<a id="rst-linux-base-driver-for-wangxun-r-10-gigabit-pci-express-adapters"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

WangXun 10 Gigabit Linux driver. Copyright (c) 2015 - 2022 Beijing WangXun Technology Co., Ltd.

<a id="rst-contents"></a>

## Contents

- Support

<a id="rst-support"></a>

## Support

If you got any problem, contact Wangxun support team via [nic-support@net-swift.com](<mailto:nic-support@net-swift.com>) and Cc: netdev.

---

# Linux Base Virtual Function Driver for Wangxun(R) 10/25/40 Gigabit Ethernet

_Peios Kernel / Internals / Networking / device_drivers / ethernet / wangxun_

> WangXun 10/25/40 Gigabit Virtual Function Linux driver. Copyright(c) 2015 - 2025 Beijing WangXun Technology Co., Ltd.

<a id="rst-linux-base-virtual-function-driver-for-wangxun-r-10-25-40-gigabit-ethernet"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

WangXun 10/25/40 Gigabit Virtual Function Linux driver. Copyright(c) 2015 - 2025 Beijing WangXun Technology Co., Ltd.

<a id="rst-support"></a>

## Support

For general information, go to the website at: [https://www.net-swift.com](<https://www.net-swift.com>)

If you got any problem, contact Wangxun support team via [nic-support@net-swift.com](<mailto:nic-support@net-swift.com>) and Cc: netdev.

---

# Fiber Distributed Data Interface (FDDI) Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / fddi_

> Contents:

<a id="rst-fiber-distributed-data-interface-fddi-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [Notes on the DEC FDDIcontroller 700 (DEFZA-xx) driver](</kernel/internals/networking/device-drivers-fddi/defza.md>)
- [SysKonnect driver - SKFP](</kernel/internals/networking/device-drivers-fddi/skfp.md>)

---

# Notes on the DEC FDDIcontroller 700 (DEFZA-xx) driver

_Peios Kernel / Internals / Networking / device_drivers / fddi_

> DEC FDDIcontroller 700 is DEC's first-generation TURBOchannel FDDI network card, designed in 1990 specifically for the DECstation 5000 model 200 workstation. The board is a single attachment station and it was manufactured in two…

<a id="rst-notes-on-the-dec-fddicontroller-700-defza-xx-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Version:** v.1.1.4

DEC FDDIcontroller 700 is DEC's first-generation TURBOchannel FDDI network card, designed in 1990 specifically for the DECstation 5000 model 200 workstation.  The board is a single attachment station and it was manufactured in two variations, both of which are supported.

First is the SAS MMF DEFZA-AA option, the original design implementing the standard MMF-PMD, however with a pair of ST connectors rather than the usual MIC connector.  The other one is the SAS ThinWire/STP DEFZA-CA option, denoted 700-C, with the network medium selectable by a switch between the DEC proprietary ThinWire-PMD using a BNC connector and the standard STP-PMD using a DE-9F connector.  This option can interface to a DECconcentrator 500 device and, in the case of the STP-PMD, also other FDDI equipment and was designed to make it easier to transition from existing IEEE 802.3 10BASE2 Ethernet and IEEE 802.5 Token Ring networks by providing means to reuse existing cabling.

This driver handles any number of cards installed in a single system. They get fddi0, fddi1, etc. interface names assigned in the order of increasing TURBOchannel slot numbers.

The board only supports DMA on the receive side.  Transmission involves the use of PIO.  As a result under a heavy transmission load there will be a significant impact on system performance.

The board supports a 64-entry CAM for matching destination addresses. Two entries are preoccupied by the Directed Beacon and Ring Purger multicast addresses and the rest is used as a multicast filter.  An all-multi mode is also supported for LLC frames and it is used if requested explicitly or if the CAM overflows.  The promiscuous mode supports separate enables for LLC and SMT frames, but this driver doesn't support changing them individually.

Known problems:

None.

To do:

5. MAC address change.  The card does not support changing the Media Access Controller's address registers but a similar effect can be achieved by adding an alias to the CAM.  There is no way to disable matching against the original address though.

7. Queueing incoming/outgoing SMT frames in the driver if the SMT receive/RMC transmit ring is full. (?)

8. Retrieving/reporting FDDI/SNMP stats.

Both success and failure reports are welcome.

Maciej W. Rozycki  &lt;[macro@orcam.me.uk](<mailto:macro@orcam.me.uk>)&gt;

---

# SysKonnect driver - SKFP

_Peios Kernel / Internals / Networking / device_drivers / fddi_

> © Copyright 1998-2000 SysKonnect,

<a id="rst-syskonnect-driver-skfp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

© Copyright 1998-2000 SysKonnect,

skfp.txt created 11-May-2000

Readme File for skfp.o v2.06

<!-- This file contains

(1) OVERVIEW
(2) SUPPORTED ADAPTERS
(3) GENERAL INFORMATION
(4) INSTALLATION
(5) INCLUSION OF THE ADAPTER IN SYSTEM START
(6) TROUBLESHOOTING
(7) FUNCTION OF THE ADAPTER LEDS
(8) HISTORY -->

<a id="rst-overview"></a>

## 1. Overview

This README explains how to use the driver 'skfp' for Linux with your network adapter.

Chapter 2: Contains a list of all network adapters that are supported by this driver.

- **Chapter 3:**

  Gives some general information.

Chapter 4: Describes common problems and solutions.

Chapter 5: Shows the changed functionality of the adapter LEDs.

Chapter 6: History of development.

<a id="rst-supported-adapters"></a>

## 2. Supported adapters

The network driver 'skfp' supports the following network adapters: SysKonnect adapters:

> - SK-5521 (SK-NET FDDI-UP)
>
> - SK-5522 (SK-NET FDDI-UP DAS)
>
> - SK-5541 (SK-NET FDDI-FP)
>
> - SK-5543 (SK-NET FDDI-LP)
>
> - SK-5544 (SK-NET FDDI-LP DAS)
>
> - SK-5821 (SK-NET FDDI-UP64)
>
> - SK-5822 (SK-NET FDDI-UP64 DAS)
>
> - SK-5841 (SK-NET FDDI-FP64)
>
> - SK-5843 (SK-NET FDDI-LP64)
>
> - SK-5844 (SK-NET FDDI-LP64 DAS)

Compaq adapters (not tested):

> - Netelligent 100 FDDI DAS Fibre SC
>
> - Netelligent 100 FDDI SAS Fibre SC
>
> - Netelligent 100 FDDI DAS UTP
>
> - Netelligent 100 FDDI SAS UTP
>
> - Netelligent 100 FDDI SAS Fibre MIC

<a id="rst-general-information"></a>

## 3. General Information

From v2.01 on, the driver is integrated in the linux kernel sources. Therefore, the installation is the same as for any other adapter supported by the kernel.

Refer to the manual of your distribution about the installation of network adapters.

Makes my life much easier :-)

<a id="rst-troubleshooting"></a>

## 4. Troubleshooting

If you run into problems during installation, check those items:

- **Problem:**

  The FDDI adapter cannot be found by the driver.

- **Reason:**

  Look in /proc/pci for the following entry:

  > 'FDDI network controller: SysKonnect SK-FDDI-PCI ...'

  If this entry exists, then the FDDI adapter has been found by the system and should be able to be used.

  If this entry does not exist or if the file '/proc/pci' is not there, then you may have a hardware problem or PCI support may not be enabled in your kernel.

  The adapter can be checked using the diagnostic program which is available from the SysKonnect web site:

  > www.syskonnect.de

  Some COMPAQ machines have a problem with PCI under Linux. This is described in the 'PCI howto' document (included in some distributions or available from the www, e.g. at 'www.linux.org') and no workaround is available.

- **Problem:**

  You want to use your computer as a router between multiple IP subnetworks (using multiple adapters), but you cannot reach computers in other subnetworks.

- **Reason:**

  Either the router's kernel is not configured for IP forwarding or there is a problem with the routing table and gateway configuration in at least one of the computers.

If your problem is not listed here, please contact our technical support for help.

You can send email to: [linux@syskonnect.de](<mailto:linux@syskonnect.de>)

When contacting our technical support, please ensure that the following information is available:

- System Manufacturer and Model

- Boards in your system

- Distribution

- Kernel version

<a id="rst-function-of-the-adapter-leds"></a>

## 5. Function of the Adapter LEDs

> The functionality of the LED's on the FDDI network adapters was changed in SMT version v2.82. With this new SMT version, the yellow LED works as a ring operational indicator. An active yellow LED indicates that the ring is down. The green LED on the adapter now works as a link indicator where an active GREEN LED indicates that the respective port has a physical connection.
>
> With versions of SMT prior to v2.82 a ring up was indicated if the yellow LED was off while the green LED(s) showed the connection status of the adapter. During a ring down the green LED was off and the yellow LED was on.
>
> All implementations indicate that a driver is not loaded if all LEDs are off.

<a id="rst-history"></a>

## 6. History

- **v2.06 (20000511) (In-Kernel version)**

  New features:

  > - 64 bit support
  >
  > - new pci dma interface
  >
  > - in kernel 2.3.99

- **v2.05 (20000217) (In-Kernel version)**

  New features:

  > - Changes for 2.3.45 kernel

- **v2.04 (20000207) (Standalone version)**

  New features:

  > - Added rx/tx byte counter

- **v2.03 (20000111) (Standalone version)**

  Problems fixed:

  > - Fixed printk statements from v2.02

- **v2.02 (991215) (Standalone version)**

  Problems fixed:

  > - Removed unnecessary output
  >
  > - Fixed path for "printver.sh" in makefile

- **v2.01 (991122) (In-Kernel version)**

  New features:

  > - Integration in Linux kernel sources
  >
  > - Support for memory mapped I/O.

- **v2.00 (991112)**

  New features:

  > - Full source released under GPL

- **v1.05 (991023)**

  Problems fixed:

  > - Compilation with kernel version 2.2.13 failed

- **v1.04 (990427)**

  Changes:

  > - New SMT module included, changing LED functionality

  Problems fixed:

  > - Synchronization on SMP machines was buggy

- **v1.03 (990325)**

  Problems fixed:

  > - Interrupt routing on SMP machines could be incorrect

- **v1.02 (990310)**

  New features:

  > - Support for kernel versions 2.2.x added
  >
  > - Kernel patch instead of private duplicate of kernel functions

- **v1.01 (980812)**

  Problems fixed:

  > Connection hangup with telnet Slow telnet connection

- **v1.00 beta 01 (980507)**

  New features:

  > None.

  Problems fixed:

  > None.

  Known limitations:

  > - tar archive instead of standard package format (rpm).
  >
  > - FDDI statistic is empty.
  >
  > - not tested with 2.1.xx kernels
  >
  > - integration in kernel not tested
  >
  > - not tested simultaneously with FDDI adapters from other vendors.
  >
  > - only X86 processors supported.
  >
  > - SBA (Synchronous Bandwidth Allocator) parameters can not be configured.
  >
  > - does not work on some COMPAQ machines. See the PCI howto document for details about this problem.
  >
  > - data corruption with kernel versions below 2.0.33.

---

# Amateur Radio Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / hamradio_

> Contents:

<a id="rst-amateur-radio-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [Linux Drivers for Baycom Modems](</kernel/internals/networking/device-drivers-hamradio/baycom.md>)
- [SCC.C - Linux driver for Z8530 based HDLC cards for AX.25](</kernel/internals/networking/device-drivers-hamradio/z8530drv.md>)

---

# Linux Drivers for Baycom Modems

_Peios Kernel / Internals / Networking / device_drivers / hamradio_

> Thomas M. Sailer, HB9JNX/AE4WA, <sailer@ife.ee.ethz.ch>

<a id="rst-linux-drivers-for-baycom-modems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Thomas M. Sailer, HB9JNX/AE4WA, &lt;[sailer@ife.ee.ethz.ch](<mailto:sailer@ife.ee.ethz.ch>)&gt;

The drivers for the baycom modems have been split into separate drivers as they did not share any code, and the driver and device names have changed.

This document describes the Linux Kernel Drivers for simple Baycom style amateur radio modems.

<a id="rst-the-following-drivers-are-available"></a>

## The following drivers are available:

- **baycom_ser_fdx:**

  This driver supports the SER12 modems either full or half duplex. Its baud rate may be changed via the `baud` module parameter, therefore it supports just about every bit bang modem on a serial port. Its devices are called bcsf0 through bcsf3. This is the recommended driver for SER12 type modems, however if you have a broken UART clone that does not have working delta status bits, you may try baycom_ser_hdx.

- **baycom_ser_hdx:**

  This is an alternative driver for SER12 type modems. It only supports half duplex, and only 1200 baud. Its devices are called bcsh0 through bcsh3. Use this driver only if baycom_ser_fdx does not work with your UART.

- **baycom_par:**

  This driver supports the par96 and picpar modems. Its devices are called bcp0 through bcp3.

- **baycom_epp:**

  This driver supports the EPP modem. Its devices are called bce0 through bce3. This driver is work-in-progress.

The following modems are supported:


<table>
<tbody>
<tr>
<td>


ser12

</td>
<td>


This is a very simple 1200 baud AFSK modem. The modem consists only of a modulator/demodulator chip, usually a TI TCM3105. The computer is responsible for regenerating the receiver bit clock, as well as for handling the HDLC protocol. The modem connects to a serial port, hence the name. Since the serial port is not used as an async serial port, the kernel driver for serial ports cannot be used, and this driver only supports standard serial hardware (8250, 16450, 16550)

</td>
</tr>
<tr>
<td>


par96

</td>
<td>


This is a modem for 9600 baud FSK compatible to the G3RUH standard. The modem does all the filtering and regenerates the receiver clock. Data is transferred from and to the PC via a shift register. The shift register is filled with 16 bits and an interrupt is signalled. The PC then empties the shift register in a burst. This modem connects to the parallel port, hence the name. The modem leaves the implementation of the HDLC protocol and the scrambler polynomial to the PC.

</td>
</tr>
<tr>
<td>


picpar

</td>
<td>


This is a redesign of the par96 modem by Henning Rech, DF9IC. The modem is protocol compatible to par96, but uses only three low power ICs and can therefore be fed from the parallel port and does not require an additional power supply. Furthermore, it incorporates a carrier detect circuitry.

</td>
</tr>
<tr>
<td>


EPP

</td>
<td>


This is a high-speed modem adaptor that connects to an enhanced parallel port.

Its target audience is users working over a high speed hub (76.8kbit/s).

</td>
</tr>
<tr>
<td>


eppfpga

</td>
<td>


This is a redesign of the EPP adaptor.

</td>
</tr>
</tbody>
</table>

All of the above modems only support half duplex communications. However, the driver supports the KISS (see below) fullduplex command. It then simply starts to send as soon as there's a packet to transmit and does not care about DCD, i.e. it starts to send even if there's someone else on the channel. This command is required by some implementations of the DAMA channel access protocol.

<a id="rst-the-interface-of-the-drivers"></a>

## The Interface of the drivers

Unlike previous drivers, these drivers are no longer character devices, but they are now true kernel network interfaces. Installation is therefore simple. Once installed, four interfaces named bc\{sf,sh,p,e\}\[0-3\] are available. sethdlc from the ax25 utilities may be used to set driver states etc. Users of userland AX.25 stacks may use the net2kiss utility (also available in the ax25 utilities package) to convert packets of a network interface to a KISS stream on a pseudo tty. There's also a patch available from me for WAMPES which allows attaching a kernel network interface directly.

<a id="rst-configuring-the-driver"></a>

## Configuring the driver

Every time a driver is inserted into the kernel, it has to know which modems it should access at which ports. This can be done with the setbaycom utility. If you are only using one modem, you can also configure the driver from the insmod command line (or by means of an option line in `/etc/modprobe.d/*.conf`).

Examples:



```text
modprobe baycom_ser_fdx mode="ser12*" iobase=0x3f8 irq=4
sethdlc -i bcsf0 -p mode "ser12*" io 0x3f8 irq 4
```

Both lines configure the first port to drive a ser12 modem at the first serial port (COM1 under DOS). The \* in the mode parameter instructs the driver to use the software DCD algorithm (see below):



```text
insmod baycom_par mode="picpar" iobase=0x378
sethdlc -i bcp0 -p mode "picpar" io 0x378
```

Both lines configure the first port to drive a picpar modem at the first parallel port (LPT1 under DOS). (Note: picpar implies hardware DCD, par96 implies software DCD).

The channel access parameters can be set with sethdlc -a or kissparms. Note that both utilities interpret the values slightly differently.

<a id="rst-hardware-dcd-versus-software-dcd"></a>

## Hardware DCD versus Software DCD

To avoid collisions on the air, the driver must know when the channel is busy. This is the task of the DCD circuitry/software. The driver may either utilise a software DCD algorithm (options=1) or use a DCD signal from the hardware (options=0).


<table>
<tbody>
<tr>
<td>


ser12

</td>
<td>


if software DCD is utilised, the radio's squelch should always be open. It is highly recommended to use the software DCD algorithm, as it is much faster than most hardware squelch circuitry. The disadvantage is a slightly higher load on the system.

</td>
</tr>
<tr>
<td>


par96

</td>
<td>


the software DCD algorithm for this type of modem is rather poor. The modem simply does not provide enough information to implement a reasonable DCD algorithm in software. Therefore, if your radio feeds the DCD input of the PAR96 modem, the use of the hardware DCD circuitry is recommended.

</td>
</tr>
<tr>
<td>


picpar

</td>
<td>


the picpar modem features a builtin DCD hardware, which is highly recommended.

</td>
</tr>
</tbody>
</table>

<a id="rst-compatibility-with-the-rest-of-the-linux-kernel"></a>

## Compatibility with the rest of the Linux kernel

The serial driver and the baycom serial drivers compete for the same hardware resources. Of course only one driver can access a given interface at a time. The serial driver grabs all interfaces it can find at startup time. Therefore the baycom drivers subsequently won't be able to access a serial port. You might therefore find it necessary to release a port owned by the serial driver with 'setserial /dev/ttyS\# uart none', where \# is the number of the interface. The baycom drivers do not reserve any ports at startup, unless one is specified on the 'insmod' command line. Another method to solve the problem is to compile all drivers as modules and leave it to kmod to load the correct driver depending on the application.

The parallel port drivers (baycom_par, baycom_epp) now use the parport subsystem to arbitrate the ports between different client drivers.

vy 73s de

Tom Sailer, [sailer@ife.ee.ethz.ch](<mailto:sailer@ife.ee.ethz.ch>)

hb9jnx @ hb9w.ampr.org

---

# SCC.C - Linux driver for Z8530 based HDLC cards for AX.25

_Peios Kernel / Internals / Networking / device_drivers / hamradio_

> This is a subset of the documentation. To use this driver you MUST have the full package from:

<a id="rst-scc-c-linux-driver-for-z8530-based-hdlc-cards-for-ax-25"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

This is a subset of the documentation. To use this driver you MUST have the full package from:

Internet:

> 1. [ftp://ftp.ccac.rwth-aachen.de/pub/jr/z8530drv-utils_3.0-3.tar.gz](<ftp://ftp.ccac.rwth-aachen.de/pub/jr/z8530drv-utils_3.0-3.tar.gz>)
>
> 2. [ftp://ftp.pspt.fi/pub/ham/linux/ax25/z8530drv-utils_3.0-3.tar.gz](<ftp://ftp.pspt.fi/pub/ham/linux/ax25/z8530drv-utils_3.0-3.tar.gz>)

Please note that the information in this document may be hopelessly outdated. A new version of the documentation, along with links to other important Linux Kernel AX.25 documentation and programs, is available on [http://yaina.de/jreuter](<http://yaina.de/jreuter>)

Copyright © 1993,2000 by Joerg Reuter DL1BKE &lt;[jreuter@yaina.de](<mailto:jreuter@yaina.de>)&gt;

portions Copyright © 1993 Guido ten Dolle PE1NNZ

for the complete copyright notice see &gt;&gt; Copying.Z8530DRV &lt;&lt;

<a id="rst-initialization-of-the-driver"></a>

## 1. Initialization of the driver

To use the driver, 3 steps must be performed:

> 1. if compiled as module: loading the module
>
> 2. Setup of hardware, MODEM and KISS parameters with sccinit
>
> 3. Attach each channel to the Linux kernel AX.25 with "ifconfig"

Unlike the versions below 2.4 this driver is a real network device driver. If you want to run xNOS instead of our fine kernel AX.25 use a 2.x version (available from above sites) or read the AX.25-HOWTO on how to emulate a KISS TNC on network device drivers.

<a id="rst-loading-the-module"></a>

## 1.1 Loading the module

- **(If you're going to compile the driver as a part of the kernel image,**

  skip this chapter and continue with 1.2)

Before you can use a module, you'll have to load it with:



```text
insmod scc.o
```

please read 'man insmod' that comes with module-init-tools.

You should include the insmod in one of the /etc/rc.d/rc.\* files, and don't forget to insert a call of sccinit after that. It will read your /etc/z8530drv.conf.

<a id="rst-etc-z8530drv-conf"></a>

## 1.2. /etc/z8530drv.conf

To setup all parameters you must run /sbin/sccinit from one of your rc.\*-files. This has to be done BEFORE you can "ifconfig" an interface. Sccinit reads the file /etc/z8530drv.conf and sets the hardware, MODEM and KISS parameters. A sample file is delivered with this package. Change it to your needs.

The file itself consists of two main sections.

<a id="rst-configuration-of-hardware-parameters"></a>

## 1.2.1 configuration of hardware parameters

The hardware setup section defines the following parameters for each Z8530:



```text
chip    1
data_a  0x300                   # data port A
ctrl_a  0x304                   # control port A
data_b  0x301                   # data port B
ctrl_b  0x305                   # control port B
irq     5                       # IRQ No. 5
pclock  4915200                 # clock
board   BAYCOM                  # hardware type
escc    no                      # enhanced SCC chip? (8580/85180/85280)
vector  0                       # latch for interrupt vector
special no                      # address of special function register
option  0                       # option to set via sfr
```

- **chip**

  - this is just a delimiter to make sccinit a bit simpler to program. A parameter has no effect.

- **data_a**

  - the address of the data port A of this Z8530 (needed)

- **ctrl_a**

  - the address of the control port A (needed)

- **data_b**

  - the address of the data port B (needed)

- **ctrl_b**

  - the address of the control port B (needed)

- **irq**

  - the used IRQ for this chip. Different chips can use different IRQs or the same. If they share an interrupt, it needs to be specified within one chip-definition only.

- **pclock  - the clock at the PCLK pin of the Z8530 (option, 4915200 is**

  default), measured in Hertz

- **board**

  - the "type" of the board:

    >
    > <table>
    > <thead>
    > <tr>
    > <th>
    >
    >
    > SCC type
    >
    > </th>
    > <th>
    >
    >
    > value
    >
    > </th>
    > </tr>
    > </thead>
    > <tbody>
    > <tr>
    > <td>
    >
    >
    > PA0HZP SCC card
    >
    > </td>
    > <td>
    >
    >
    > PA0HZP
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > EAGLE card
    >
    > </td>
    > <td>
    >
    >
    > EAGLE
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > PC100 card
    >
    > </td>
    > <td>
    >
    >
    > PC100
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > PRIMUS-PC (DG9BL) card
    >
    > </td>
    > <td>
    >
    >
    > PRIMUS
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > BayCom (U)SCC card
    >
    > </td>
    > <td>
    >
    >
    > BAYCOM
    >
    > </td>
    > </tr>
    > </tbody>
    > </table>

- **escc**

  - if you want support for ESCC chips (8580, 85180, 85280), set this to "yes" (option, defaults to "no")

- **vector**

  - address of the vector latch (aka "intack port") for PA0HZP cards. There can be only one vector latch for all chips\! (option, defaults to 0)

- **special**

  - address of the special function register on several cards. (option, defaults to 0)

option  - The value you write into that register (option, default is 0)

You can specify up to four chips (8 channels). If this is not enough, just change:



```text
#define MAXSCC 4
```

to a higher value.

<a id="rst-example-for-the-baycom-uscc"></a>

### Example for the BAYCOM USCC:



```text
chip    1
data_a  0x300                   # data port A
ctrl_a  0x304                   # control port A
data_b  0x301                   # data port B
ctrl_b  0x305                   # control port B
irq     5                       # IRQ No. 5 (#)
board   BAYCOM                  # hardware type (*)
#
# SCC chip 2
#
chip    2
data_a  0x302
ctrl_a  0x306
data_b  0x303
ctrl_b  0x307
board   BAYCOM
```

<a id="rst-an-example-for-a-pa0hzp-card"></a>

### An example for a PA0HZP card:



```text
chip 1
data_a 0x153
data_b 0x151
ctrl_a 0x152
ctrl_b 0x150
irq 9
pclock 4915200
board PA0HZP
vector 0x168
escc no
#
#
#
chip 2
data_a 0x157
data_b 0x155
ctrl_a 0x156
ctrl_b 0x154
irq 9
pclock 4915200
board PA0HZP
vector 0x168
escc no
```

<a id="rst-a-drsi-would-should-probably-work-with-this"></a>

### A DRSI would should probably work with this:

(actually: two DRSI cards...)



```text
chip 1
data_a 0x303
data_b 0x301
ctrl_a 0x302
ctrl_b 0x300
irq 7
pclock 4915200
board DRSI
escc no
#
#
#
chip 2
data_a 0x313
data_b 0x311
ctrl_a 0x312
ctrl_b 0x310
irq 7
pclock 4915200
board DRSI
escc no
```

Note that you cannot use the on-board baudrate generator off DRSI cards. Use "mode dpll" for clock source (see below).

This is based on information provided by Mike Bilow (and verified by Paul Helay)

<a id="rst-the-utility-gencfg"></a>

### The utility "gencfg"

If you only know the parameters for the PE1CHL driver for DOS, run gencfg. It will generate the correct port addresses (I hope). Its parameters are exactly the same as the ones you use with the "attach scc" command in net, except that the string "init" must not appear. Example:



```text
gencfg 2 0x150 4 2 0 1 0x168 9 4915200
```

will print a skeleton z8530drv.conf for the OptoSCC to stdout.



```text
gencfg 2 0x300 2 4 5 -4 0 7 4915200 0x10
```

does the same for the BAYCOM USCC card. In my opinion it is much easier to edit scc_config.h...

<a id="rst-channel-configuration"></a>

## 1.2.2 channel configuration

The channel definition is divided into three sub sections for each channel:

An example for scc0:



```text
# DEVICE

device scc0     # the device for the following params

# MODEM / BUFFERS

speed 1200              # the default baudrate
clock dpll              # clock source:
                        #       dpll     = normal half duplex operation
                        #       external = MODEM provides own Rx/Tx clock
                        #       divider  = use full duplex divider if
                        #                  installed (1)
mode nrzi               # HDLC encoding mode
                        #       nrzi = 1k2 MODEM, G3RUH 9k6 MODEM
                        #       nrz  = DF9IC 9k6 MODEM
                        #
bufsize 384             # size of buffers. Note that this must include
                        # the AX.25 header, not only the data field!
                        # (optional, defaults to 384)

# KISS (Layer 1)

txdelay 36              # (see chapter 1.4)
persist 64
slot    8
tail    8
fulldup 0
wait    12
min     3
maxkey  7
idle    3
maxdef  120
group   0
txoff   off
softdcd on
slip    off
```

The order WITHIN these sections is unimportant. The order OF these sections IS important. The MODEM parameters are set with the first recognized KISS parameter...

Please note that you can initialize the board only once after boot (or insmod). You can change all parameters but "mode" and "clock" later with the Sccparam program or through KISS. Just to avoid security holes...

1. this divider is usually mounted on the SCC-PBC (PA0HZP) or not present at all (BayCom). It feeds back the output of the DPLL (digital pll) as transmit clock. Using this mode without a divider installed will normally result in keying the transceiver until maxkey expires --- of course without sending anything (useful).

<a id="rst-attachment-of-a-channel-by-your-ax-25-software"></a>

## 2. Attachment of a channel by your AX.25 software

<a id="rst-kernel-ax-25"></a>

## 2.1 Kernel AX.25

To set up an AX.25 device you can simply type:



```text
ifconfig scc0 44.128.1.1 hw ax25 dl0tha-7
```

This will create a network interface with the IP number 44.128.20.107 and the callsign "dl0tha". If you do not have any IP number (yet) you can use any of the 44.128.0.0 network. Note that you do not need axattach. The purpose of axattach (like slattach) is to create a KISS network device linked to a TTY. Please read the documentation of the ax25-utils and the AX.25-HOWTO to learn how to set the parameters of the kernel AX.25.

<a id="rst-nos-net-and-tfkiss"></a>

## 2.2 NOS, NET and TFKISS

Since the TTY driver (aka KISS TNC emulation) is gone you need to emulate the old behaviour. The cost of using these programs is that you probably need to compile the kernel AX.25, regardless of whether you actually use it or not. First setup your /etc/ax25/axports, for example:



```text
9k6     dl0tha-9  9600  255 4 9600 baud port (scc3)
axlink  dl0tha-15 38400 255 4 Link to NOS
```

Now "ifconfig" the scc device:



```text
ifconfig scc3 44.128.1.1 hw ax25 dl0tha-9
```

You can now axattach a pseudo-TTY:



```text
axattach /dev/ptys0 axlink
```

and start your NOS and attach /dev/ptys0 there. The problem is that NOS is reachable only via digipeating through the kernel AX.25 (disastrous on a DAMA controlled channel). To solve this problem, configure "rxecho" to echo the incoming frames from "9k6" to "axlink" and outgoing frames from "axlink" to "9k6" and start:



```text
rxecho
```

Or simply use "kissbridge" coming with z8530drv-utils:



```text
ifconfig scc3 hw ax25 dl0tha-9
kissbridge scc3 /dev/ptys0
```

<a id="rst-adjustment-and-display-of-parameters"></a>

## 3. Adjustment and Display of parameters

<a id="rst-displaying-scc-parameters"></a>

## 3.1 Displaying SCC Parameters:

Once a SCC channel has been attached, the parameter settings and some statistic information can be shown using the param program:



```text
dl1bke-u:~$ sccstat scc0

Parameters:

speed       : 1200 baud
txdelay     : 36
persist     : 255
slottime    : 0
txtail      : 8
fulldup     : 1
waittime    : 12
mintime     : 3 sec
maxkeyup    : 7 sec
idletime    : 3 sec
maxdefer    : 120 sec
group       : 0x00
txoff       : off
softdcd     : on
SLIP        : off

Status:

HDLC                  Z8530           Interrupts         Buffers
-----------------------------------------------------------------------
Sent       :     273  RxOver :     0  RxInts :   125074  Size    :  384
Received   :    1095  TxUnder:     0  TxInts :     4684  NoSpace :    0
RxErrors   :    1591                  ExInts :    11776
TxErrors   :       0                  SpInts :     1503
Tx State   :    idle
```

The status info shown is:


<table>
<tbody>
<tr>
<td>


Sent

</td>
<td>


number of frames transmitted

</td>
</tr>
<tr>
<td>


Received

</td>
<td>


number of frames received

</td>
</tr>
<tr>
<td>


RxErrors

</td>
<td>


number of receive errors (CRC, ABORT)

</td>
</tr>
<tr>
<td>


TxErrors

</td>
<td>


number of discarded Tx frames (due to various reasons)

</td>
</tr>
<tr>
<td>


Tx State

</td>
<td>


status of the Tx interrupt handler: idle/busy/active/tail (2)

</td>
</tr>
<tr>
<td>


RxOver

</td>
<td>


number of receiver overruns

</td>
</tr>
<tr>
<td>


TxUnder

</td>
<td>


number of transmitter underruns

</td>
</tr>
<tr>
<td>


RxInts

</td>
<td>


number of receiver interrupts

</td>
</tr>
<tr>
<td>


TxInts

</td>
<td>


number of transmitter interrupts

</td>
</tr>
<tr>
<td>


EpInts

</td>
<td>


number of receiver special condition interrupts

</td>
</tr>
<tr>
<td>


SpInts

</td>
<td>


number of external/status interrupts

</td>
</tr>
<tr>
<td>


Size

</td>
<td>


maximum size of an AX.25 frame (*with* AX.25 headers\!)

</td>
</tr>
<tr>
<td>


NoSpace

</td>
<td>


number of times a buffer could not get allocated

</td>
</tr>
</tbody>
</table>

An overrun is abnormal. If lots of these occur, the product of baudrate and number of interfaces is too high for the processing power of your computer. NoSpace errors are unlikely to be caused by the driver or the kernel AX.25.

<a id="rst-setting-parameters"></a>

## 3.2 Setting Parameters

The setting of parameters of the emulated KISS TNC is done in the same way in the SCC driver. You can change parameters by using the kissparms program from the ax25-utils package or use the program "sccparam":



```text
sccparam <device> <paramname> <decimal-|hexadecimal value>
```

You can change the following parameters:


<table>
<thead>
<tr>
<th>


param

</th>
<th>


value

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


speed

</td>
<td>


1200

</td>
</tr>
<tr>
<td>


txdelay

</td>
<td>


36

</td>
</tr>
<tr>
<td>


persist

</td>
<td>


255

</td>
</tr>
<tr>
<td>


slottime

</td>
<td>


0

</td>
</tr>
<tr>
<td>


txtail

</td>
<td>


8

</td>
</tr>
<tr>
<td>


fulldup

</td>
<td>


1

</td>
</tr>
<tr>
<td>


waittime

</td>
<td>


12

</td>
</tr>
<tr>
<td>


mintime

</td>
<td>


3

</td>
</tr>
<tr>
<td>


maxkeyup

</td>
<td>


7

</td>
</tr>
<tr>
<td>


idletime

</td>
<td>


3

</td>
</tr>
<tr>
<td>


maxdefer

</td>
<td>


120

</td>
</tr>
<tr>
<td>


group

</td>
<td>


0x00

</td>
</tr>
<tr>
<td>


txoff

</td>
<td>


off

</td>
</tr>
<tr>
<td>


softdcd

</td>
<td>


on

</td>
</tr>
<tr>
<td>


SLIP

</td>
<td>


off

</td>
</tr>
</tbody>
</table>

The parameters have the following meaning:

- **speed:**

  The baudrate on this channel in bits/sec

  Example: sccparam /dev/scc3 speed 9600

- **txdelay:**

  The delay (in units of 10 ms) after keying of the transmitter, until the first byte is sent. This is usually called "TXDELAY" in a TNC.  When 0 is specified, the driver will just wait until the CTS signal is asserted. This assumes the presence of a timer or other circuitry in the MODEM and/or transmitter, that asserts CTS when the transmitter is ready for data. A normal value of this parameter is 30-36.

  Example: sccparam /dev/scc0 txd 20

- **persist:**

  This is the probability that the transmitter will be keyed when the channel is found to be free.  It is a value from 0 to 255, and the probability is (value+1)/256.  The value should be somewhere near 50-60, and should be lowered when the channel is used more heavily.

  Example: sccparam /dev/scc2 persist 20

- **slottime:**

  This is the time between samples of the channel. It is expressed in units of 10 ms.  About 200-300 ms (value 20-30) seems to be a good value.

  Example: sccparam /dev/scc0 slot 20

- **tail:**

  The time the transmitter will remain keyed after the last byte of a packet has been transferred to the SCC. This is necessary because the CRC and a flag still have to leave the SCC before the transmitter is keyed down. The value depends on the baudrate selected.  A few character times should be sufficient, e.g. 40ms at 1200 baud. (value 4) The value of this parameter is in 10 ms units.

  Example: sccparam /dev/scc2 4

- **full:**

  The full-duplex mode switch. This can be one of the following values:

  - **0:   The interface will operate in CSMA mode (the normal**

    half-duplex packet radio operation)

  - **1:   Fullduplex mode, i.e. the transmitter will be keyed at**

    any time, without checking the received carrier.  It will be unkeyed when there are no packets to be sent.

  - **2:   Like 1, but the transmitter will remain keyed, also**

    when there are no packets to be sent.  Flags will be sent in that case, until a timeout (parameter 10) occurs.

  Example: sccparam /dev/scc0 fulldup off

- **wait:**

  The initial waittime before any transmit attempt, after the frame has been queue for transmit.  This is the length of the first slot in CSMA mode.  In full duplex modes it is set to 0 for maximum performance. The value of this parameter is in 10 ms units.

  Example: sccparam /dev/scc1 wait 4

- **maxkey:**

  The maximal time the transmitter will be keyed to send packets, in seconds.  This can be useful on busy CSMA channels, to avoid "getting a bad reputation" when you are generating a lot of traffic.  After the specified time has elapsed, no new frame will be started. Instead, the trans- mitter will be switched off for a specified time (parameter min), and then the selected algorithm for keyup will be started again. The value 0 as well as "off" will disable this feature, and allow infinite transmission time.

  Example: sccparam /dev/scc0 maxk 20

- **min:**

  This is the time the transmitter will be switched off when the maximum transmission time is exceeded.

  Example: sccparam /dev/scc3 min 10

- **idle:**

  This parameter specifies the maximum idle time in full duplex 2 mode, in seconds.  When no frames have been sent for this time, the transmitter will be keyed down.  A value of 0 is has same result as the fullduplex mode 1. This parameter can be disabled.

  Example: sccparam /dev/scc2 idle off       \# transmit forever

- **maxdefer**

  This is the maximum time (in seconds) to wait for a free channel to send. When this timer expires the transmitter will be keyed IMMEDIATELY. If you love to get trouble with other users you should set this to a very low value ;-)

  Example: sccparam /dev/scc0 maxdefer 240   \# 2 minutes

- **txoff:**

  When this parameter has the value 0, the transmission of packets is enable. Otherwise it is disabled.

  Example: sccparam /dev/scc2 txoff on

- **group:**

  It is possible to build special radio equipment to use more than one frequency on the same band, e.g. using several receivers and only one transmitter that can be switched between frequencies. Also, you can connect several radios that are active on the same band.  In these cases, it is not possible, or not a good idea, to transmit on more than one frequency.  The SCC driver provides a method to lock transmitters on different interfaces, using the "param &lt;interface&gt; group &lt;x&gt;" command.  This will only work when you are using CSMA mode (parameter full = 0).

  The number &lt;x&gt; must be 0 if you want no group restrictions, and can be computed as follows to create restricted groups: &lt;x&gt; is the sum of some OCTAL numbers:


  <table>
  <tbody>
  <tr>
  <td>


  200

  </td>
  <td>


  This transmitter will only be keyed when all other transmitters in the group are off.

  </td>
  </tr>
  <tr>
  <td>


  100

  </td>
  <td>


  This transmitter will only be keyed when the carrier detect of all other interfaces in the group is off.

  </td>
  </tr>
  <tr>
  <td>


  0xx

  </td>
  <td>


  A byte that can be used to define different groups. Interfaces are in the same group, when the logical AND between their xx values is nonzero.

  </td>
  </tr>
  </tbody>
  </table>

  Examples:

  When 2 interfaces use group 201, their transmitters will never be keyed at the same time.

  When 2 interfaces use group 101, the transmitters will only key when both channels are clear at the same time.  When group 301, the transmitters will not be keyed at the same time.

  Don't forget to convert the octal numbers into decimal before you set the parameter.

  Example: (to be written)

- **softdcd:**

  use a software dcd instead of the real one... Useful for a very slow squelch.

  Example: sccparam /dev/scc0 soft on

<a id="rst-problems"></a>

## 4. Problems

If you have tx-problems with your BayCom USCC card please check the manufacturer of the 8530. SGS chips have a slightly different timing. Try Zilog...  A solution is to write to register 8 instead to the data port, but this won't work with the ESCC chips. *SIGH\!*

A very common problem is that the PTT locks until the maxkeyup timer expires, although interrupts and clock source are correct. In most cases compiling the driver with CONFIG_SCC_DELAY (set with make config) solves the problems. For more hints read the (pseudo) FAQ and the documentation coming with z8530drv-utils.

I got reports that the driver has problems on some 386-based systems. (i.e. Amstrad) Those systems have a bogus AT bus timing which will lead to delayed answers on interrupts. You can recognize these problems by looking at the output of Sccstat for the suspected port. If it shows under- and overruns you own such a system.

Delayed processing of received data: This depends on

- the kernel version

- kernel profiling compiled or not

- a high interrupt load

- a high load of the machine --- running X, Xmorph, XV and Povray, while compiling the kernel... hmm ... even with 32 MB RAM ...  ;-) Or running a named for the whole .ampr.org domain on an 8 MB box...

- using information from rxecho or kissbridge.

Kernel panics: please read /linux/README and find out if it really occurred within the scc driver.

If you cannot solve a problem, send me

- a description of the problem,

- information on your hardware (computer system, scc board, modem)

- your kernel version

- the output of cat /proc/net/z8530

<a id="rst-thor-rlc100"></a>

## 4. Thor RLC100

Mysteriously this board seems not to work with the driver. Anyone got it up-and-running?

Many thanks to Linus Torvalds and Alan Cox for including the driver in the Linux standard distribution and their support.



```text
Joerg Reuter    ampr-net: dl1bke@db0pra.ampr.org
                AX-25   : DL1BKE @ DB0ABH.#BAY.DEU.EU
                Internet: jreuter@yaina.de
                WWW     : http://yaina.de/jreuter
```

---

# Wi-Fi Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / wifi_

> Contents:

<a id="rst-wi-fi-device-drivers"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

Contents:

- [Intel(R) PRO/Wireless 2100 Driver for Linux](</kernel/internals/networking/device-drivers-wifi-intel/ipw2100.md>)
- [Intel(R) PRO/Wireless 2915ABG Driver for Linux](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/device_drivers/wifi/intel/ipw2200.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# Intel(R) PRO/Wireless 2100 Driver for Linux

_Peios Kernel / Internals / Networking / device_drivers / wifi / intel_

> Support for:

<a id="rst-intel-r-pro-wireless-2100-driver-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Support for:

- Intel(R) PRO/Wireless 2100 Network Connection

Copyright © 2003-2006, Intel Corporation

README.ipw2100

**Version:** git-1.1.5

**Date:** January 25, 2006

<!-- Index

0. IMPORTANT INFORMATION BEFORE USING THIS DRIVER
1. Introduction
2. Release git-1.1.5 Current Features
3. Command Line Parameters
4. Sysfs Helper Files
5. Radio Kill Switch
6. Dynamic Firmware
7. Power Management
8. Support
9. License -->

<a id="rst-important-information-before-using-this-driver"></a>

## 0. IMPORTANT INFORMATION BEFORE USING THIS DRIVER

Important Notice FOR ALL USERS OR DISTRIBUTORS\!\!\!\!

Intel wireless LAN adapters are engineered, manufactured, tested, and quality checked to ensure that they meet all necessary local and governmental regulatory agency requirements for the regions that they are designated and/or marked to ship into. Since wireless LANs are generally unlicensed devices that share spectrum with radars, satellites, and other licensed and unlicensed devices, it is sometimes necessary to dynamically detect, avoid, and limit usage to avoid interference with these devices. In many instances Intel is required to provide test data to prove regional and local compliance to regional and governmental regulations before certification or approval to use the product is granted. Intel's wireless LAN's EEPROM, firmware, and software driver are designed to carefully control parameters that affect radio operation and to ensure electromagnetic compliance (EMC). These parameters include, without limitation, RF power, spectrum usage, channel scanning, and human exposure.

For these reasons Intel cannot permit any manipulation by third parties of the software provided in binary format with the wireless WLAN adapters (e.g., the EEPROM and firmware). Furthermore, if you use any patches, utilities, or code with the Intel wireless LAN adapters that have been manipulated by an unauthorized party (i.e., patches, utilities, or code (including open source code modifications) which have not been validated by Intel), (i) you will be solely responsible for ensuring the regulatory compliance of the products, (ii) Intel will bear no liability, under any theory of liability for any issues associated with the modified products, including without limitation, claims under the warranty and/or issues arising from regulatory non-compliance, and (iii) Intel will not provide or be required to assist in providing support to any third parties for such modified products.

Note: Many regulatory agencies consider Wireless LAN adapters to be modules, and accordingly, condition system-level regulatory approval upon receipt and review of test data documenting that the antennas and system configuration do not cause the EMC and radio operation to be non-compliant.

The drivers available for download from SourceForge are provided as a part of a development project.  Conformance to local regulatory requirements is the responsibility of the individual developer.  As such, if you are interested in deploying or shipping a driver as part of solution intended to be used for purposes other than development, please obtain a tested driver from Intel Customer Support at:

[https://www.intel.com/support/wireless/sb/CS-006408.htm](<https://www.intel.com/support/wireless/sb/CS-006408.htm>)

<a id="rst-introduction"></a>

## 1. Introduction

This document provides a brief overview of the features supported by the IPW2100 driver project.  The main project website, where the latest development version of the driver can be found, is:

> [http://ipw2100.sourceforge.net](<http://ipw2100.sourceforge.net>)

There you can find the not only the latest releases, but also information about potential fixes and patches, as well as links to the development mailing list for the driver project.

<a id="rst-release-git-1-1-5-current-supported-features"></a>

## 2. Release git-1.1.5 Current Supported Features

- Managed (BSS) and Ad-Hoc (IBSS)

- WEP (shared key and open)

- Wireless Tools support

- 802.1x (tested with XSupplicant 1.0.1)

Enabled (but not supported) features: - Monitor/RFMon mode - WPA/WPA2

The distinction between officially supported and enabled is a reflection on the amount of validation and interoperability testing that has been performed on a given feature.

<a id="rst-command-line-parameters"></a>

## 3. Command Line Parameters

If the driver is built as a module, the following optional parameters are used by entering them on the command line with the modprobe command using this syntax:



```text
modprobe ipw2100 [<option>=<VAL1><,VAL2>...]
```

For example, to disable the radio on driver loading, enter:

> modprobe ipw2100 disable=1

The ipw2100 driver supports the following module parameters:


<table>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Example

</th>
<th>


Meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


debug

</td>
<td>


0x0-0xffffffff

</td>
<td>


debug=1024

</td>
<td>


Debug level set to 1024

</td>
</tr>
<tr>
<td>


mode

</td>
<td>


0,1,2

</td>
<td>


mode=1

</td>
<td>


AdHoc

</td>
</tr>
<tr>
<td>


channel

</td>
<td>


int

</td>
<td>


channel=3

</td>
<td>


Only valid in AdHoc or Monitor

</td>
</tr>
<tr>
<td>


associate

</td>
<td>


boolean

</td>
<td>


associate=0

</td>
<td>


Do NOT auto associate

</td>
</tr>
<tr>
<td>


disable

</td>
<td>


boolean

</td>
<td>


disable=1

</td>
<td>


Do not power the HW

</td>
</tr>
</tbody>
</table>

<a id="rst-sysfs-helper-files"></a>

## 4. Sysfs Helper Files

There are several ways to control the behavior of the driver.  Many of the general capabilities are exposed through the Wireless Tools (iwconfig).  There are a few capabilities that are exposed through entries in the Linux Sysfs.

**Driver Level**

For the driver level files, look in /sys/bus/pci/drivers/ipw2100/

> - **debug_level**
>
>   This controls the same global as the 'debug' module parameter.  For information on the various debugging levels available, run the 'dvals' script found in the driver source directory.
>
>   > [!NOTE]
>   >
>   > 'debug_level' is only enabled if CONFIG_IPW2100_DEBUG is turn on.

**Device Level**

For the device level files look in:



```text
/sys/bus/pci/drivers/ipw2100/{PCI-ID}/
```

For example:



```text
/sys/bus/pci/drivers/ipw2100/0000:02:01.0
```

For the device level files, see /sys/bus/pci/drivers/ipw2100:

> - **rf_kill**
>
>   read
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   RF kill not enabled (radio on)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   SW based RF kill active (radio off)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   2
>
>   </td>
>   <td>
>
>
>   HW based RF kill active (radio off)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   3
>
>   </td>
>   <td>
>
>
>   Both HW and SW RF kill active (radio off)
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   write
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   If SW based RF kill active, turn the radio back on
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   If radio is on, activate SW based RF kill
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   > [!NOTE]
>   >
>   > If you enable the SW based RF kill and then toggle the HW based RF kill from ON -&gt; OFF -&gt; ON, the radio will NOT come back on

<a id="rst-radio-kill-switch"></a>

## 5. Radio Kill Switch

Most laptops provide the ability for the user to physically disable the radio. Some vendors have implemented this as a physical switch that requires no software to turn the radio off and on.  On other laptops, however, the switch is controlled through a button being pressed and a software driver then making calls to turn the radio off and on.  This is referred to as a "software based RF kill switch"

See the Sysfs helper file 'rf_kill' for determining the state of the RF switch on your system.

<a id="rst-dynamic-firmware"></a>

## 6. Dynamic Firmware

As the firmware is licensed under a restricted use license, it can not be included within the kernel sources.  To enable the IPW2100 you will need a firmware image to load into the wireless NIC's processors.

You can obtain these images from &lt;[http://ipw2100.sf.net/firmware.php](<http://ipw2100.sf.net/firmware.php>)&gt;.

See INSTALL for instructions on installing the firmware.

<a id="rst-power-management"></a>

## 7. Power Management

The IPW2100 supports the configuration of the Power Save Protocol through a private wireless extension interface.  The IPW2100 supports the following different modes:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> off
>
> </td>
> <td>
>
>
> No power management.  Radio is always on.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> on
>
> </td>
> <td>
>
>
> Automatic power management
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 1-5
>
> </td>
> <td>
>
>
> Different levels of power management.  The higher the number the greater the power savings, but with an impact to packet latencies.
>
> </td>
> </tr>
> </tbody>
> </table>

Power management works by powering down the radio after a certain interval of time has passed where no packets are passed through the radio.  Once powered down, the radio remains in that state for a given period of time.  For higher power savings, the interval between last packet processed to sleep is shorter and the sleep period is longer.

When the radio is asleep, the access point sending data to the station must buffer packets at the AP until the station wakes up and requests any buffered packets.  If you have an AP that does not correctly support the PSP protocol you may experience packet loss or very poor performance while power management is enabled.  If this is the case, you will need to try and find a firmware update for your AP, or disable power management (via `iwconfig eth1 power off`)

To configure the power level on the IPW2100 you use a combination of iwconfig and iwpriv.  iwconfig is used to turn power management on, off, and set it to auto.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> iwconfig eth1 power off
>
> </td>
> <td>
>
>
> Disables radio power down
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> iwconfig eth1 power on
>
> </td>
> <td>
>
>
> Enables radio power management to last set level (defaults to AUTO)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> iwpriv eth1 set_power 0
>
> </td>
> <td>
>
>
> Sets power level to AUTO and enables power management if not previously enabled.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> iwpriv eth1 set_power 1-5
>
> </td>
> <td>
>
>
> Set the power level as specified, enabling power management if not previously enabled.
>
> </td>
> </tr>
> </tbody>
> </table>

You can view the current power level setting via:



```text
iwpriv eth1 get_power
```

It will return the current period or timeout that is configured as a string in the form of xxxx/yyyy (z) where xxxx is the timeout interval (amount of time after packet processing), yyyy is the period to sleep (amount of time to wait before powering the radio and querying the access point for buffered packets), and z is the 'power level'.  If power management is turned off the xxxx/yyyy will be replaced with 'off' -- the level reported will be the active level if `iwconfig eth1 power on` is invoked.

<a id="rst-support"></a>

## 8. Support

For general development information and support, go to:

> [http://ipw2100.sf.net/](<http://ipw2100.sf.net/>)

The ipw2100 1.1.0 driver and firmware can be downloaded from:

> [http://support.intel.com](<http://support.intel.com>)

For installation support on the ipw2100 1.1.0 driver on Linux kernels 2.6.8 or greater, email support is available from:

> [http://supportmail.intel.com](<http://supportmail.intel.com>)

<a id="rst-license"></a>

## 9. License

> Copyright © 2003 - 2006 Intel Corporation. All rights reserved.
>
> This program 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.
>
> 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.
>
> You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
>
> The full GNU General Public License is included in this distribution in the file called LICENSE.
>
> License Contact Information:
>
> James P. Ketrenos &lt;[ipw2100-admin@linux.intel.com](<mailto:ipw2100-admin@linux.intel.com>)&gt;
>
> Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497

---

# Intel(R) PRO/Wireless 2915ABG Driver for Linux

_Peios Kernel / Internals / Networking / device_drivers / wifi / intel_

> Support for:

<a id="rst-intel-r-pro-wireless-2915abg-driver-for-linux"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

Support for:

- Intel(R) PRO/Wireless 2200BG Network Connection

- Intel(R) PRO/Wireless 2915ABG Network Connection

Note: The Intel(R) PRO/Wireless 2915ABG Driver for Linux and Intel(R) PRO/Wireless 2200BG Driver for Linux is a unified driver that works on both hardware adapters listed above. In this document the Intel(R) PRO/Wireless 2915ABG Driver for Linux will be used to reference the unified driver.

Copyright © 2004-2006, Intel Corporation

README.ipw2200

**Version:** 1.1.2

**Date:** March 30, 2006

<!-- Index

0.   IMPORTANT INFORMATION BEFORE USING THIS DRIVER
1.   Introduction
1.1. Overview of features
1.2. Module parameters
1.3. Wireless Extension Private Methods
1.4. Sysfs Helper Files
1.5. Supported channels
2.   Ad-Hoc Networking
3.   Interacting with Wireless Tools
3.1. iwconfig mode
3.2. iwconfig sens
4.   About the Version Numbers
5.   Firmware installation
6.   Support
7.   License -->

<a id="rst-important-information-before-using-this-driver"></a>

## 0. IMPORTANT INFORMATION BEFORE USING THIS DRIVER

Important Notice FOR ALL USERS OR DISTRIBUTORS\!\!\!\!

Intel wireless LAN adapters are engineered, manufactured, tested, and quality checked to ensure that they meet all necessary local and governmental regulatory agency requirements for the regions that they are designated and/or marked to ship into. Since wireless LANs are generally unlicensed devices that share spectrum with radars, satellites, and other licensed and unlicensed devices, it is sometimes necessary to dynamically detect, avoid, and limit usage to avoid interference with these devices. In many instances Intel is required to provide test data to prove regional and local compliance to regional and governmental regulations before certification or approval to use the product is granted. Intel's wireless LAN's EEPROM, firmware, and software driver are designed to carefully control parameters that affect radio operation and to ensure electromagnetic compliance (EMC). These parameters include, without limitation, RF power, spectrum usage, channel scanning, and human exposure.

For these reasons Intel cannot permit any manipulation by third parties of the software provided in binary format with the wireless WLAN adapters (e.g., the EEPROM and firmware). Furthermore, if you use any patches, utilities, or code with the Intel wireless LAN adapters that have been manipulated by an unauthorized party (i.e., patches, utilities, or code (including open source code modifications) which have not been validated by Intel), (i) you will be solely responsible for ensuring the regulatory compliance of the products, (ii) Intel will bear no liability, under any theory of liability for any issues associated with the modified products, including without limitation, claims under the warranty and/or issues arising from regulatory non-compliance, and (iii) Intel will not provide or be required to assist in providing support to any third parties for such modified products.

Note: Many regulatory agencies consider Wireless LAN adapters to be modules, and accordingly, condition system-level regulatory approval upon receipt and review of test data documenting that the antennas and system configuration do not cause the EMC and radio operation to be non-compliant.

The drivers available for download from SourceForge are provided as a part of a development project.  Conformance to local regulatory requirements is the responsibility of the individual developer.  As such, if you are interested in deploying or shipping a driver as part of solution intended to be used for purposes other than development, please obtain a tested driver from Intel Customer Support at:

[http://support.intel.com](<http://support.intel.com>)

<a id="rst-introduction"></a>

## 1. Introduction

The following sections attempt to provide a brief introduction to using the Intel(R) PRO/Wireless 2915ABG Driver for Linux.

This document is not meant to be a comprehensive manual on understanding or using wireless technologies, but should be sufficient to get you moving without wires on Linux.

For information on building and installing the driver, see the INSTALL file.

<a id="rst-overview-of-features"></a>

### 1.1. Overview of Features

The current release (1.1.2) supports the following features:

- BSS mode (Infrastructure, Managed)

- IBSS mode (Ad-Hoc)

- WEP (OPEN and SHARED KEY mode)

- 802.1x EAP via wpa\_supplicant and xsupplicant

- Wireless Extension support

- Full B and G rate support (2200 and 2915)

- Full A rate support (2915 only)

- Transmit power control

- S state support (ACPI suspend/resume)

The following features are currently enabled, but not officially supported:

- WPA

- long/short preamble support

- Monitor mode (aka RFMon)

The distinction between officially supported and enabled is a reflection on the amount of validation and interoperability testing that has been performed on a given feature.

<a id="rst-command-line-parameters"></a>

### 1.2. Command Line Parameters

Like many modules used in the Linux kernel, the Intel(R) PRO/Wireless 2915ABG Driver for Linux allows configuration options to be provided as module parameters.  The most common way to specify a module parameter is via the command line.

The general form is:



```text
% modprobe ipw2200 parameter=value
```

Where the supported parameter are:

> - **associate**
>
>   Set to 0 to disable the auto scan-and-associate functionality of the driver.  If disabled, the driver will not attempt to scan for and associate to a network until it has been configured with one or more properties for the target network, for example configuring the network SSID.  Default is 0 (do not auto-associate)
>
>   Example: % modprobe ipw2200 associate=0
>
> - **auto\_create**
>
>   Set to 0 to disable the auto creation of an Ad-Hoc network matching the channel and network name parameters provided. Default is 1.
>
> - **channel**
>
>   channel number for association.  The normal method for setting the channel would be to use the standard wireless tools (i.e. `iwconfig eth1 channel 10`), but it is useful sometimes to set this while debugging.  Channel 0 means 'ANY'
>
> - **debug**
>
>   If using a debug build, this is used to control the amount of debug info is logged.  See the 'dvals' and 'load' script for more info on how to use this (the dvals and load scripts are provided as part of the ipw2200 development snapshot releases available from the SourceForge project at [http://ipw2200.sf.net](<http://ipw2200.sf.net>))
>
> - **led**
>
>   Can be used to turn on experimental LED code. 0 = Off, 1 = On.  Default is 1.
>
> - **mode**
>
>   Can be used to set the default mode of the adapter. 0 = Managed, 1 = Ad-Hoc, 2 = Monitor

<a id="rst-wireless-extension-private-methods"></a>

### 1.3. Wireless Extension Private Methods

As an interface designed to handle generic hardware, there are certain capabilities not exposed through the normal Wireless Tool interface.  As such, a provision is provided for a driver to declare custom, or private, methods.  The Intel(R) PRO/Wireless 2915ABG Driver for Linux defines several of these to configure various settings.

The general form of using the private wireless methods is:



```text
% iwpriv $IFNAME method parameters
```

Where $IFNAME is the interface name the device is registered with (typically eth1, customized via one of the various network interface name managers, such as ifrename)

The supported private methods are:

> - **get\_mode**
>
>   Can be used to report out which IEEE mode the driver is configured to support.  Example:
>
>   % iwpriv eth1 get\_mode eth1    get\_mode:802.11bg (6)
>
> - **set\_mode**
>
>   Can be used to configure which IEEE mode the driver will support.
>
>   Usage:
>
>
>
>   ```text
>   % iwpriv eth1 set_mode {mode}
>   ```
>
>   Where \{mode\} is a number in the range 1-7:
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   802.11a (2915 only)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   2
>
>   </td>
>   <td>
>
>
>   802.11b
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   3
>
>   </td>
>   <td>
>
>
>   802.11ab (2915 only)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   4
>
>   </td>
>   <td>
>
>
>   802.11g
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   5
>
>   </td>
>   <td>
>
>
>   802.11ag (2915 only)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   6
>
>   </td>
>   <td>
>
>
>   802.11bg
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   7
>
>   </td>
>   <td>
>
>
>   802.11abg (2915 only)
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
> - **get\_preamble**
>
>   Can be used to report configuration of preamble length.
>
> - **set\_preamble**
>
>   Can be used to set the configuration of preamble length:
>
>   Usage:
>
>
>
>   ```text
>   % iwpriv eth1 set_preamble {mode}
>   ```
>
>   Where \{mode\} is one of:
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   Long preamble only
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   Auto (long or short based on connection)
>
>   </td>
>   </tr>
>   </tbody>
>   </table>

<a id="rst-sysfs-helper-files"></a>

### 1.4. Sysfs Helper Files

The Linux kernel provides a pseudo file system that can be used to access various components of the operating system.  The Intel(R) PRO/Wireless 2915ABG Driver for Linux exposes several configuration parameters through this mechanism.

An entry in the sysfs can support reading and/or writing.  You can typically query the contents of a sysfs entry through the use of cat, and can set the contents via echo.  For example:



```text
% cat /sys/bus/pci/drivers/ipw2200/debug_level
```

Will report the current debug level of the driver's logging subsystem (only available if CONFIG\_IPW2200\_DEBUG was configured when the driver was built).

You can set the debug level via:



```text
% echo $VALUE > /sys/bus/pci/drivers/ipw2200/debug_level
```

Where $VALUE would be a number in the case of this sysfs entry.  The input to sysfs files does not have to be a number.  For example, the firmware loader used by hotplug utilizes sysfs entries for transferring the firmware image from user space into the driver.

The Intel(R) PRO/Wireless 2915ABG Driver for Linux exposes sysfs entries at two levels -- driver level, which apply to all instances of the driver (in the event that there are more than one device installed) and device level, which applies only to the single specific instance.

<a id="rst-driver-level-sysfs-helper-files"></a>

#### 1.4.1 Driver Level Sysfs Helper Files

For the driver level files, look in /sys/bus/pci/drivers/ipw2200/

> - **debug\_level**
>
>   This controls the same global as the 'debug' module parameter

<a id="rst-device-level-sysfs-helper-files"></a>

#### 1.4.2 Device Level Sysfs Helper Files

For the device level files, look in:



```text
/sys/bus/pci/drivers/ipw2200/{PCI-ID}/
```

For example::



```text
/sys/bus/pci/drivers/ipw2200/0000:02:01.0
```

For the device level files, see /sys/bus/pci/drivers/ipw2200:

> - **rf\_kill**
>
>   read -
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   RF kill not enabled (radio on)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   SW based RF kill active (radio off)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   2
>
>   </td>
>   <td>
>
>
>   HW based RF kill active (radio off)
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   3
>
>   </td>
>   <td>
>
>
>   Both HW and SW RF kill active (radio off)
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   write -
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   If SW based RF kill active, turn the radio back on
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   If radio is on, activate SW based RF kill
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   > [!NOTE]
>   >
>   > If you enable the SW based RF kill and then toggle the HW based RF kill from ON -&gt; OFF -&gt; ON, the radio will NOT come back on
>
> - **ucode**
>
>   read-only access to the ucode version number
>
> - **led**
>
>   read -
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   LED code disabled
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   LED code enabled
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   write -
>
>
>   <table>
>   <tbody>
>   <tr>
>   <td>
>
>
>   0
>
>   </td>
>   <td>
>
>
>   Disable LED code
>
>   </td>
>   </tr>
>   <tr>
>   <td>
>
>
>   1
>
>   </td>
>   <td>
>
>
>   Enable LED code
>
>   </td>
>   </tr>
>   </tbody>
>   </table>
>
>   > [!NOTE]
>   >
>   > The LED code has been reported to hang some systems when running ifconfig and is therefore disabled by default.

<a id="rst-supported-channels"></a>

### 1.5. Supported channels

Upon loading the Intel(R) PRO/Wireless 2915ABG Driver for Linux, a message stating the detected geography code and the number of 802.11 channels supported by the card will be displayed in the log.

The geography code corresponds to a regulatory domain as shown in the table below.

>
> <table>
> <thead>
> <tr>
> <th rowspan="2">
>
>
> Code
>
> </th>
> <th rowspan="2">
>
>
> Geography
>
> </th>
> <th colspan="2">
>
>
> Supported channels
>
> </th>
> </tr>
> <tr>
> <th>
>
>
> 802.11bg
>
> </th>
> <th>
>
>
> 802.11a
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> \---
>
> </td>
> <td>
>
>
> Restricted
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZF
>
> </td>
> <td>
>
>
> Custom US/Canada
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 8
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZD
>
> </td>
> <td>
>
>
> Rest of World
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> 0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZA
>
> </td>
> <td>
>
>
> Custom USA &amp; Europe &amp; High
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 13
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZB
>
> </td>
> <td>
>
>
> Custom NA &amp; Europe
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 13
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZC
>
> </td>
> <td>
>
>
> Custom Japan
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZM
>
> </td>
> <td>
>
>
> Custom
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZE
>
> </td>
> <td>
>
>
> Europe
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> 19
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZJ
>
> </td>
> <td>
>
>
> Custom Japan
>
> </td>
> <td>
>
>
> 14
>
> </td>
> <td>
>
>
> 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZR
>
> </td>
> <td>
>
>
> Rest of World
>
> </td>
> <td>
>
>
> 14
>
> </td>
> <td>
>
>
> 0
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZH
>
> </td>
> <td>
>
>
> High Band
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZG
>
> </td>
> <td>
>
>
> Custom Europe
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> 4
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZK
>
> </td>
> <td>
>
>
> Europe
>
> </td>
> <td>
>
>
> 13
>
> </td>
> <td>
>
>
> 24
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ZZL
>
> </td>
> <td>
>
>
> Europe
>
> </td>
> <td>
>
>
> 11
>
> </td>
> <td>
>
>
> 13
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-ad-hoc-networking"></a>

## 2.  Ad-Hoc Networking

When using a device in an Ad-Hoc network, it is useful to understand the sequence and requirements for the driver to be able to create, join, or merge networks.

The following attempts to provide enough information so that you can have a consistent experience while using the driver as a member of an Ad-Hoc network.

<a id="rst-joining-an-ad-hoc-network"></a>

### 2.1. Joining an Ad-Hoc Network

The easiest way to get onto an Ad-Hoc network is to join one that already exists.

<a id="rst-creating-an-ad-hoc-network"></a>

### 2.2. Creating an Ad-Hoc Network

An Ad-Hoc networks is created using the syntax of the Wireless tool.

For Example: iwconfig eth1 mode ad-hoc essid testing channel 2

<a id="rst-merging-ad-hoc-networks"></a>

### 2.3. Merging Ad-Hoc Networks

<a id="rst-interaction-with-wireless-tools"></a>

## 3. Interaction with Wireless Tools

<a id="rst-iwconfig-mode"></a>

### 3.1 iwconfig mode

When configuring the mode of the adapter, all run-time configured parameters are reset to the value used when the module was loaded.  This includes channels, rates, ESSID, etc.

<a id="rst-iwconfig-sens"></a>

### 3.2 iwconfig sens

The 'iwconfig ethX sens XX' command will not set the signal sensitivity threshold, as described in iwconfig documentation, but rather the number of consecutive missed beacons that will trigger handover, i.e. roaming to another access point. At the same time, it will set the disassociation threshold to 3 times the given value.

<a id="rst-about-the-version-numbers"></a>

## 4.  About the Version Numbers

Due to the nature of open source development projects, there are frequently changes being incorporated that have not gone through a complete validation process.  These changes are incorporated into development snapshot releases.

Releases are numbered with a three level scheme:

> major.minor.development

Any version where the 'development' portion is 0 (for example 1.0.0, 1.1.0, etc.) indicates a stable version that will be made available for kernel inclusion.

Any version where the 'development' portion is not a 0 (for example 1.0.1, 1.1.5, etc.) indicates a development version that is being made available for testing and cutting edge users.  The stability and functionality of the development releases are not know.  We make efforts to try and keep all snapshots reasonably stable, but due to the frequency of their release, and the desire to get those releases available as quickly as possible, unknown anomalies should be expected.

The major version number will be incremented when significant changes are made to the driver.  Currently, there are no major changes planned.

<a id="rst-firmware-installation"></a>

## 5. Firmware installation

The driver requires a firmware image, download it and extract the files under /lib/firmware (or wherever your hotplug's firmware.agent will look for firmware files)

The firmware can be downloaded from the following URL:

> [http://ipw2200.sf.net/](<http://ipw2200.sf.net/>)

<a id="rst-support"></a>

## 6. Support

For direct support of the 1.0.0 version, you can contact [http://supportmail.intel.com](<http://supportmail.intel.com>), or you can use the open source project support.

For general information and support, go to:

> [http://ipw2200.sf.net/](<http://ipw2200.sf.net/>)

<a id="rst-license"></a>

## 7. License

> Copyright © 2003 - 2006 Intel Corporation. All rights reserved.
>
> This program 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.
>
> 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.
>
> You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
>
> The full GNU General Public License is included in this distribution in the file called LICENSE.
>
> Contact Information:
>
> James P. Ketrenos &lt;[ipw2100-admin@linux.intel.com](<mailto:ipw2100-admin@linux.intel.com>)&gt;
>
> Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497

---

# WWAN Device Drivers

_Peios Kernel / Internals / Networking / device_drivers / wwan_

> Contents:

<a id="rst-wwan-device-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

Contents:

- [IOSM Driver for Intel M.2 PCIe based Modems](</kernel/internals/networking/device-drivers-wwan/iosm.md>)
- [t7xx driver for MTK PCIe based T700 5G modem](</kernel/internals/networking/device-drivers-wwan/t7xx.md>)

---

# IOSM Driver for Intel M.2 PCIe based Modems

_Peios Kernel / Internals / Networking / device_drivers / wwan_

> The IOSM (IPC over Shared Memory) driver is a WWAN PCIe host driver developed for linux or chrome platform for data exchange over PCIe interface between Host platform & Intel M.2 Modem. The driver exposes interface conforming to the MBIM…

<a id="rst-iosm-driver-for-intel-m-2-pcie-based-modems"></a>
<a id="rst-iosm-driver-doc"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<!-- Copyright (C) 2020-21 Intel Corporation -->

The IOSM (IPC over Shared Memory) driver is a WWAN PCIe host driver developed for linux or chrome platform for data exchange over PCIe interface between Host platform &amp; Intel M.2 Modem. The driver exposes interface conforming to the MBIM protocol \[1\]. Any front end application ( eg: Modem Manager) could easily manage the MBIM interface to enable data communication towards WWAN.

<a id="rst-basic-usage"></a>

## Basic usage

MBIM functions are inactive when unmanaged. The IOSM driver only provides a userspace interface MBIM "WWAN PORT" representing MBIM control channel and does not play any role in managing the functionality. It is the job of a userspace application to detect port enumeration and enable MBIM functionality.

Examples of few such userspace application are: - mbimcli (included with the libmbim \[2\] library), and - Modem Manager \[3\]

Management Applications to carry out below required actions for establishing MBIM IP session: - open the MBIM control channel - configure network connection settings - connect to network - configure IP network interface

<a id="rst-management-application-development"></a>

## Management application development

The driver and userspace interfaces are described below. The MBIM protocol is described in \[1\] Mobile Broadband Interface Model v1.0 Errata-1.

<a id="rst-mbim-control-channel-userspace-abi"></a>

### MBIM control channel userspace ABI

<a id="rst-dev-wwan0mbim0-character-device"></a>

#### /dev/wwan0mbim0 character device

The driver exposes an MBIM interface to the MBIM function by implementing MBIM WWAN Port. The userspace end of the control channel pipe is a /dev/wwan0mbim0 character device. Application shall use this interface for MBIM protocol communication.

<a id="rst-fragmentation"></a>

#### Fragmentation

The userspace application is responsible for all control message fragmentation and defragmentation as per MBIM specification.

<a id="rst-dev-wwan0mbim0-write"></a>

#### /dev/wwan0mbim0 write()

The MBIM control messages from the management application must not exceed the negotiated control message size.

<a id="rst-dev-wwan0mbim0-read"></a>

#### /dev/wwan0mbim0 read()

The management application must accept control messages of up the negotiated control message size.

<a id="rst-mbim-data-channel-userspace-abi"></a>

### MBIM data channel userspace ABI

<a id="rst-wwan0-x-network-device"></a>

#### wwan0-X network device

The IOSM driver exposes IP link interface "wwan0-X" of type "wwan" for IP traffic. Iproute network utility is used for creating "wwan0-X" network interface and for associating it with MBIM IP session. The Driver supports up to 8 IP sessions for simultaneous IP communication.

The userspace management application is responsible for creating new IP link prior to establishing MBIM IP session where the SessionId is greater than 0.

For example, creating new IP link for a MBIM IP session with SessionId 1:

> ip link add dev wwan0-1 parentdev-name wwan0 type wwan linkid 1

The driver will automatically map the "wwan0-1" network device to MBIM IP session 1.

<a id="rst-references"></a>

## References

- **\[1\] "MBIM (Mobile Broadband Interface Model) Errata-1"**

  - [https://www.usb.org/document-library/](<https://www.usb.org/document-library/>)

- **\[2\] libmbim - "a glib-based library for talking to WWAN modems and**

  devices which speak the Mobile Interface Broadband Model (MBIM) protocol" - [http://www.freedesktop.org/wiki/Software/libmbim/](<http://www.freedesktop.org/wiki/Software/libmbim/>)

- **\[3\] Modem Manager - "a DBus-activated daemon which controls mobile**

  broadband (2G/3G/4G) devices and connections" - [http://www.freedesktop.org/wiki/Software/ModemManager/](<http://www.freedesktop.org/wiki/Software/ModemManager/>)

---

# t7xx driver for MTK PCIe based T700 5G modem

_Peios Kernel / Internals / Networking / device_drivers / wwan_

> The t7xx driver is a WWAN PCIe host driver developed for linux or Chrome OS platforms for data exchange over PCIe interface between Host platform & MediaTek's T700 5G modem. The driver exposes an interface conforming to the MBIM protocol…

<a id="rst-t7xx-driver-for-mtk-pcie-based-t700-5g-modem"></a>
<a id="rst-t7xx-driver-doc"></a>

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<!-- Copyright (C) 2020-21 Intel Corporation -->

The t7xx driver is a WWAN PCIe host driver developed for linux or Chrome OS platforms for data exchange over PCIe interface between Host platform &amp; MediaTek's T700 5G modem. The driver exposes an interface conforming to the MBIM protocol \[1\]. Any front end application (e.g. Modem Manager) could easily manage the MBIM interface to enable data communication towards WWAN. The driver also provides an interface to interact with the MediaTek's modem via AT commands.

<a id="rst-basic-usage"></a>

## Basic usage

MBIM &amp; AT functions are inactive when unmanaged. The t7xx driver provides WWAN port userspace interfaces representing MBIM &amp; AT control channels and does not play any role in managing their functionality. It is the job of a userspace application to detect port enumeration and enable MBIM &amp; AT functionalities.

Examples of few such userspace applications are:

- mbimcli (included with the libmbim \[2\] library), and

- Modem Manager \[3\]

Management Applications to carry out below required actions for establishing MBIM IP session:

- open the MBIM control channel

- configure network connection settings

- connect to network

- configure IP network interface

Management Applications to carry out below required actions for send an AT command and receive response:

- open the AT control channel using a UART tool or a special user tool

<a id="rst-sysfs"></a>

## Sysfs

The driver provides sysfs interfaces to userspace.

<a id="rst-t7xx-mode"></a>

### t7xx_mode

The sysfs interface provides userspace with access to the device mode, this interface supports read and write operations.

Device mode:

- `unknown` represents that device in unknown status

- `ready` represents that device in ready status

- `reset` represents that device in reset status

- `fastboot_switching` represents that device in fastboot switching status

- `fastboot_download` represents that device in fastboot download status

- `fastboot_dump` represents that device in fastboot dump status

Read from userspace to get the current device mode.

- **::**

  $ cat /sys/bus/pci/devices/$\{bdf\}/t7xx_mode

Write from userspace to set the device mode.

- **::**

  $ echo fastboot_switching &gt; /sys/bus/pci/devices/$\{bdf\}/t7xx_mode

<a id="rst-t7xx-debug-ports"></a>

### t7xx_debug_ports

The sysfs interface provides userspace with access to enable/disable the debug ports, this interface supports read and write operations.

Debug port status:

- `1` represents enable debug ports

- `0` represents disable debug ports

Currently supported debug ports (ADB/MIPC).

Read from userspace to get the current debug ports status.

- **::**

  $ cat /sys/bus/pci/devices/$\{bdf\}/t7xx_debug_ports

Write from userspace to set the debug ports status.

- **::**

  $ echo 1 &gt; /sys/bus/pci/devices/$\{bdf\}/t7xx_debug_ports

<a id="rst-management-application-development"></a>

## Management application development

The driver and userspace interfaces are described below. The MBIM protocol is described in \[1\] Mobile Broadband Interface Model v1.0 Errata-1.

<a id="rst-mbim-control-channel-userspace-abi"></a>

### MBIM control channel userspace ABI

<a id="rst-dev-wwan0mbim0-character-device"></a>

#### /dev/wwan0mbim0 character device

The driver exposes an MBIM interface to the MBIM function by implementing MBIM WWAN Port. The userspace end of the control channel pipe is a /dev/wwan0mbim0 character device. Application shall use this interface for MBIM protocol communication.

<a id="rst-fragmentation"></a>

#### Fragmentation

The userspace application is responsible for all control message fragmentation and defragmentation as per MBIM specification.

<a id="rst-dev-wwan0mbim0-write"></a>

#### /dev/wwan0mbim0 write()

The MBIM control messages from the management application must not exceed the negotiated control message size.

<a id="rst-dev-wwan0mbim0-read"></a>

#### /dev/wwan0mbim0 read()

The management application must accept control messages of up the negotiated control message size.

<a id="rst-mbim-data-channel-userspace-abi"></a>

### MBIM data channel userspace ABI

<a id="rst-wwan0-x-network-device"></a>

#### wwan0-X network device

The t7xx driver exposes IP link interface "wwan0-X" of type "wwan" for IP traffic. Iproute network utility is used for creating "wwan0-X" network interface and for associating it with MBIM IP session.

The userspace management application is responsible for creating new IP link prior to establishing MBIM IP session where the SessionId is greater than 0.

For example, creating new IP link for a MBIM IP session with SessionId 1:

> ip link add dev wwan0-1 parentdev wwan0 type wwan linkid 1

The driver will automatically map the "wwan0-1" network device to MBIM IP session 1.

<a id="rst-at-port-userspace-abi"></a>

### AT port userspace ABI

<a id="rst-dev-wwan0at0-character-device"></a>

#### /dev/wwan0at0 character device

The driver exposes an AT port by implementing AT WWAN Port. The userspace end of the control port is a /dev/wwan0at0 character device. Application shall use this interface to issue AT commands.

<a id="rst-fastboot-port-userspace-abi"></a>

### fastboot port userspace ABI

<a id="rst-dev-wwan0fastboot0-character-device"></a>

#### /dev/wwan0fastboot0 character device

The driver exposes a fastboot protocol interface by implementing fastboot WWAN Port. The userspace end of the fastboot channel pipe is a /dev/wwan0fastboot0 character device. Application shall use this interface for fastboot protocol communication.

Please note that driver needs to be reloaded to export /dev/wwan0fastboot0 port, because device needs a cold reset after enter `fastboot_switching` mode.

<a id="rst-adb-port-userspace-abi"></a>

### ADB port userspace ABI

<a id="rst-dev-wwan0adb0-character-device"></a>

#### /dev/wwan0adb0 character device

The driver exposes a ADB protocol interface by implementing ADB WWAN Port. The userspace end of the ADB channel pipe is a /dev/wwan0adb0 character device. Application shall use this interface for ADB protocol communication.

<a id="rst-mipc-port-userspace-abi"></a>

### MIPC port userspace ABI

<a id="rst-dev-wwan0mipc0-character-device"></a>

#### /dev/wwan0mipc0 character device

The driver exposes a diagnostic interface by implementing MIPC (Modem Information Process Center) WWAN Port. The userspace end of the MIPC channel pipe is a /dev/wwan0mipc0 character device. Application shall use this interface for MTK modem diagnostic communication.

The MediaTek's T700 modem supports the 3GPP TS 27.007 \[4\] specification.

<a id="rst-references"></a>

## References

\[1\] *MBIM (Mobile Broadband Interface Model) Errata-1*

- [https://www.usb.org/document-library/](<https://www.usb.org/document-library/>)

\[2\] *libmbim "a glib-based library for talking to WWAN modems and devices which speak the Mobile Interface Broadband Model (MBIM) protocol"*

- [http://www.freedesktop.org/wiki/Software/libmbim/](<http://www.freedesktop.org/wiki/Software/libmbim/>)

\[3\] *Modem Manager "a DBus-activated daemon which controls mobile broadband (2G/3G/4G/5G) devices and connections"*

- [http://www.freedesktop.org/wiki/Software/ModemManager/](<http://www.freedesktop.org/wiki/Software/ModemManager/>)

\[4\] *Specification \# 27.007 - 3GPP*

- [https://www.3gpp.org/DynaReport/27007.htm](<https://www.3gpp.org/DynaReport/27007.htm>)

\[5\] *fastboot "a mechanism for communicating with bootloaders"*

- [https://android.googlesource.com/platform/system/core/+/refs/heads/main/fastboot/README.md](<https://android.googlesource.com/platform/system/core/+/refs/heads/main/fastboot/README.md>)

\[6\] *ADB (Android Debug Bridge) "a mechanism to keep track of Android devices and emulators instances connected to or running on a given host developer machine with ADB protocol"*

- [https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/README.md](<https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/README.md>)

---

# Linux Devlink Documentation

_Peios Kernel / Internals / Networking / devlink_

> devlink is an API to expose device information and resources not directly related to any device class, such as chip-wide/switch-ASIC-wide configuration.

<a id="rst-linux-devlink-documentation"></a>

devlink is an API to expose device information and resources not directly related to any device class, such as chip-wide/switch-ASIC-wide configuration.

<a id="rst-locking"></a>

## Locking

Driver facing APIs are currently transitioning to allow more explicit locking. Drivers can use the existing `devlink_*` set of APIs, or new APIs prefixed by `devl_*`. The older APIs handle all the locking in devlink core, but don't allow registration of most sub-objects once the main devlink object is itself registered. The newer `devl_*` APIs assume the devlink instance lock is already held. Drivers can take the instance lock by calling `devl_lock()`. It is also held all callbacks of devlink netlink commands.

Drivers are encouraged to use the devlink instance lock for their own needs.

Drivers need to be cautious when taking devlink instance lock and taking RTNL lock at the same time. Devlink instance lock needs to be taken first, only after that RTNL lock could be taken.

<a id="rst-nested-instances"></a>

## Nested instances

Some objects, like linecards or port functions, could have another devlink instances created underneath. In that case, drivers should make sure to respect following rules:

> - Lock ordering should be maintained. If driver needs to take instance lock of both nested and parent instances at the same time, devlink instance lock of the parent instance should be taken first, only then instance lock of the nested instance could be taken.
>
> - Driver should use object-specific helpers to setup the nested relationship:
>
>   - `devl_nested_devlink_set()` - called to setup devlink -&gt; nested devlink relationship (could be user for multiple nested instances.
>
>   - `devl_port_fn_devlink_set()` - called to setup port function -&gt; nested devlink relationship.
>
>   - `devlink_linecard_nested_dl_set()` - called to setup linecard -&gt; nested devlink relationship.

The nested devlink info is exposed to the userspace over object-specific attributes of devlink netlink.

<a id="rst-interface-documentation"></a>

## Interface documentation

The following pages describe various interfaces available through devlink in general.

- [Devlink DPIPE](</kernel/internals/networking/devlink/devlink-dpipe.md>)
- [Devlink E-Switch Attribute](</kernel/internals/networking/devlink/devlink-eswitch-attr.md>)
- [Devlink Flash](</kernel/internals/networking/devlink/devlink-flash.md>)
- [Devlink Health](</kernel/internals/networking/devlink/devlink-health.md>)
- [Devlink Info](</kernel/internals/networking/devlink/devlink-info.md>)
- [Devlink Line card](</kernel/internals/networking/devlink/devlink-linecard.md>)
- [Devlink Params](</kernel/internals/networking/devlink/devlink-params.md>)
- [Devlink Port](</kernel/internals/networking/devlink/devlink-port.md>)
- [Devlink Region](</kernel/internals/networking/devlink/devlink-region.md>)
- [Devlink Reload](</kernel/internals/networking/devlink/devlink-reload.md>)
- [Devlink Resource](</kernel/internals/networking/devlink/devlink-resource.md>)
- [Devlink Selftests](</kernel/internals/networking/devlink/devlink-selftests.md>)
- [Devlink Trap](</kernel/internals/networking/devlink/devlink-trap.md>)

<a id="rst-driver-specific-documentation"></a>

## Driver-specific documentation

Each driver that implements `devlink` is expected to document what parameters, info versions, and other features it supports.

- [am65-cpsw-nuss devlink support](</kernel/internals/networking/devlink/am65-nuss-cpsw-switch.md>)
- [bnxt devlink support](</kernel/internals/networking/devlink/bnxt.md>)
- [etas_es58x devlink support](</kernel/internals/networking/devlink/etas-es58x.md>)
- [hns3 devlink support](</kernel/internals/networking/devlink/hns3.md>)
- [i40e devlink support](</kernel/internals/networking/devlink/i40e.md>)
- [ice devlink support](</kernel/internals/networking/devlink/ice.md>)
- [ionic devlink support](</kernel/internals/networking/devlink/ionic.md>)
- [iosm devlink support](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/networking/devlink/iosm.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [ixgbe devlink support](</kernel/internals/networking/devlink/ixgbe.md>)
- [kvaser_pciefd devlink support](</kernel/internals/networking/devlink/kvaser-pciefd.md>)
- [kvaser_usb devlink support](</kernel/internals/networking/devlink/kvaser-usb.md>)
- [mlx4 devlink support](</kernel/internals/networking/devlink/mlx4.md>)
- [mlx5 devlink support](</kernel/internals/networking/devlink/mlx5.md>)
- [mlxsw devlink support](</kernel/internals/networking/devlink/mlxsw.md>)
- [mv88e6xxx devlink support](</kernel/internals/networking/devlink/mv88e6xxx.md>)
- [netdevsim devlink support](</kernel/internals/networking/devlink/netdevsim.md>)
- [nfp devlink support](</kernel/internals/networking/devlink/nfp.md>)
- [octeontx2 devlink support](</kernel/internals/networking/devlink/octeontx2.md>)
- [prestera devlink support](</kernel/internals/networking/devlink/prestera.md>)
- [qed devlink support](</kernel/internals/networking/devlink/qed.md>)
- [sfc devlink support](</kernel/internals/networking/devlink/sfc.md>)
- [stmmac (synopsys dwmac) devlink support](</kernel/internals/networking/devlink/stmmac.md>)
- [ti-cpsw-switch devlink support](</kernel/internals/networking/devlink/ti-cpsw-switch.md>)
- [zl3073x devlink support](</kernel/internals/networking/devlink/zl3073x.md>)

---

# am65-cpsw-nuss devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the am65-cpsw-nuss device driver.

<a id="rst-am65-cpsw-nuss-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `am65-cpsw-nuss` device driver.

<a id="rst-parameters"></a>

## Parameters

The `am65-cpsw-nuss` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`switch_mode`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Enable switch mode

</td>
</tr>
</tbody>
</table>

---

# bnxt devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the bnxt device driver.

<a id="rst-bnxt-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `bnxt` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
</tr>
<tr>
<td>


`enable_sriov`

</td>
<td>


Permanent

</td>
</tr>
<tr>
<td>


`ignore_ari`

</td>
<td>


Permanent

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_max`

</td>
<td>


Permanent

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_min`

</td>
<td>


Permanent

</td>
</tr>
<tr>
<td>


`enable_remote_dev_reset`

</td>
<td>


Runtime

</td>
</tr>
<tr>
<td>


`enable_roce`

</td>
<td>


Permanent

</td>
</tr>
</tbody>
</table>

The `bnxt` driver also implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`gre_ver_check`

</td>
<td>


Boolean

</td>
<td>


Permanent

</td>
<td>


Generic Routing Encapsulation (GRE) version check will be enabled in the device. If disabled, the device will skip the version check for incoming packets.

</td>
</tr>
</tbody>
</table>

<a id="rst-info-versions"></a>

## Info versions

The `bnxt_en` driver reports the following versions


<table>
<caption>devlink info versions implemented
   :widths: 5 5 90</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


Part number identifying the board design

</td>
</tr>
<tr>
<td>


`asic.id`

</td>
<td>


fixed

</td>
<td>


ASIC design identifier

</td>
</tr>
<tr>
<td>


`asic.rev`

</td>
<td>


fixed

</td>
<td>


ASIC design revision

</td>
</tr>
<tr>
<td>


`fw.psid`

</td>
<td>


stored, running

</td>
<td>


Firmware parameter set version of the board

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


stored, running

</td>
<td>


Overall board firmware version

</td>
</tr>
<tr>
<td>


`fw.mgmt`

</td>
<td>


stored, running

</td>
<td>


NIC hardware resource management firmware version

</td>
</tr>
<tr>
<td>


`fw.mgmt.api`

</td>
<td>


running

</td>
<td>


Minimum firmware interface spec version supported between driver and firmware

</td>
</tr>
<tr>
<td>


`fw.nsci`

</td>
<td>


stored, running

</td>
<td>


General platform management firmware version

</td>
</tr>
<tr>
<td>


`fw.roce`

</td>
<td>


stored, running

</td>
<td>


RoCE management firmware version

</td>
</tr>
</tbody>
</table>

---

# Devlink DPIPE

_Peios Kernel / Internals / Networking / devlink_

> While performing the hardware offloading process, much of the hardware specifics cannot be presented. These details are useful for debugging, and devlink-dpipe provides a standardized way to provide visibility into the offloading process.

<a id="rst-devlink-dpipe"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

While performing the hardware offloading process, much of the hardware specifics cannot be presented. These details are useful for debugging, and `devlink-dpipe` provides a standardized way to provide visibility into the offloading process.

For example, the routing longest prefix match (LPM) algorithm used by the Linux kernel may differ from the hardware implementation. The pipeline debug API (DPIPE) is aimed at providing the user visibility into the ASIC's pipeline in a generic way.

The hardware offload process is expected to be done in a way that the user should not be able to distinguish between the hardware vs. software implementation. In this process, hardware specifics are neglected. In reality those details can have lots of meaning and should be exposed in some standard way.

This problem is made even more complex when one wishes to offload the control path of the whole networking stack to a switch ASIC. Due to differences in the hardware and software models some processes cannot be represented correctly.

One example is the kernel's LPM algorithm which in many cases differs greatly to the hardware implementation. The configuration API is the same, but one cannot rely on the Forward Information Base (FIB) to look like the Level Path Compression trie (LPC-trie) in hardware.

In many situations trying to analyze systems failure solely based on the kernel's dump may not be enough. By combining this data with complementary information about the underlying hardware, this debugging can be made easier; additionally, the information can be useful when debugging performance issues.

<a id="rst-overview"></a>

## Overview

The `devlink-dpipe` interface closes this gap. The hardware's pipeline is modeled as a graph of match/action tables. Each table represents a specific hardware block. This model is not new, first being used by the P4 language.

Traditionally it has been used as an alternative model for hardware configuration, but the `devlink-dpipe` interface uses it for visibility purposes as a standard complementary tool. The system's view from `devlink-dpipe` should change according to the changes done by the standard configuration tools.

For example, it’s quite common to  implement Access Control Lists (ACL) using Ternary Content Addressable Memory (TCAM). The TCAM memory can be divided into TCAM regions. Complex TC filters can have multiple rules with different priorities and different lookup keys. On the other hand hardware TCAM regions have a predefined lookup key. Offloading the TC filter rules using TCAM engine can result in multiple TCAM regions being interconnected in a chain (which may affect the data path latency). In response to a new TC filter new tables should be created describing those regions.

<a id="rst-model"></a>

## Model

The `DPIPE` model introduces several objects:

> - headers
>
> - tables
>
> - entries

A `header` describes packet formats and provides names for fields within the packet. A `table` describes hardware blocks. An `entry` describes the actual content of a specific table.

The hardware pipeline is not port specific, but rather describes the whole ASIC. Thus it is tied to the top of the `devlink` infrastructure.

Drivers can register and unregister tables at run time, in order to support dynamic behavior. This dynamic behavior is mandatory for describing hardware blocks like TCAM regions which can be allocated and freed dynamically.

`devlink-dpipe` generally is not intended for configuration. The exception is hardware counting for a specific table.

The following commands are used to obtain the `dpipe` objects from userspace:

> - `table_get`: Receive a table's description.
>
> - `headers_get`: Receive a device's supported headers.
>
> - `entries_get`: Receive a table's current entries.
>
> - `counters_set`: Enable or disable counters on a table.

<a id="rst-table"></a>

### Table

The driver should implement the following operations for each table:

> - `matches_dump`: Dump the supported matches.
>
> - `actions_dump`: Dump the supported actions.
>
> - `entries_dump`: Dump the actual content of the table.
>
> - `counters_set_update`: Synchronize hardware with counters enabled or disabled.

<a id="rst-header-field"></a>

### Header/Field

In a similar way to P4 headers and fields are used to describe a table's behavior. There is a slight difference between the standard protocol headers and specific ASIC metadata. The protocol headers should be declared in the `devlink` core API. On the other hand ASIC meta data is driver specific and should be defined in the driver. Additionally, each driver-specific devlink documentation file should document the driver-specific `dpipe` headers it implements. The headers and fields are identified by enumeration.

In order to provide further visibility some ASIC metadata fields could be mapped to kernel objects. For example, internal router interface indexes can be directly mapped to the net device ifindex. FIB table indexes used by different Virtual Routing and Forwarding (VRF) tables can be mapped to internal routing table indexes.

<a id="rst-match"></a>

### Match

Matches are kept primitive and close to hardware operation. Match types like LPM are not supported due to the fact that this is exactly a process we wish to describe in full detail. Example of matches:

> - `field_exact`: Exact match on a specific field.
>
> - `field_exact_mask`: Exact match on a specific field after masking.
>
> - `field_range`: Match on a specific range.

The id's of the header and the field should be specified in order to identify the specific field. Furthermore, the header index should be specified in order to distinguish multiple headers of the same type in a packet (tunneling).

<a id="rst-action"></a>

### Action

Similar to match, the actions are kept primitive and close to hardware operation. For example:

> - `field_modify`: Modify the field value.
>
> - `field_inc`: Increment the field value.
>
> - `push_header`: Add a header.
>
> - `pop_header`: Remove a header.

<a id="rst-entry"></a>

### Entry

Entries of a specific table can be dumped on demand. Each eentry is identified with an index and its properties are described by a list of match/action values and specific counter. By dumping the tables content the interactions between tables can be resolved.

<a id="rst-abstraction-example"></a>

## Abstraction Example

The following is an example of the abstraction model of the L3 part of Mellanox Spectrum ASIC. The blocks are described in the order they appear in the pipeline. The table sizes in the following examples are not real hardware sizes and are provided for demonstration purposes.

<a id="rst-lpm"></a>

### LPM

The LPM algorithm can be implemented as a list of hash tables. Each hash table contains routes with the same prefix length. The root of the list is /32, and in case of a miss the hardware will continue to the next hash table. The depth of the search will affect the data path latency.

In case of a hit the entry contains information about the next stage of the pipeline which resolves the MAC address. The next stage can be either local host table for directly connected routes, or adjacency table for next-hops. The `meta.lpm_prefix` field is used to connect two LPM tables.



```text
table lpm_prefix_16 {
  size: 4096,
  counters_enabled: true,
  match: { meta.vr_id: exact,
           ipv4.dst_addr: exact_mask,
           ipv6.dst_addr: exact_mask,
           meta.lpm_prefix: exact },
  action: { meta.adj_index: set,
            meta.adj_group_size: set,
            meta.rif_port: set,
            meta.lpm_prefix: set },
}
```

<a id="rst-local-host"></a>

### Local Host

In the case of local routes the LPM lookup already resolves the egress router interface (RIF), yet the exact MAC address is not known. The local host table is a hash table combining the output interface id with destination IP address as a key. The result is the MAC address.



```text
table local_host {
  size: 4096,
  counters_enabled: true,
  match: { meta.rif_port: exact,
           ipv4.dst_addr: exact},
  action: { ethernet.daddr: set }
}
```

<a id="rst-adjacency"></a>

### Adjacency

In case of remote routes this table does the ECMP. The LPM lookup results in ECMP group size and index that serves as a global offset into this table. Concurrently a hash of the packet is generated. Based on the ECMP group size and the packet's hash a local offset is generated. Multiple LPM entries can point to the same adjacency group.



```text
table adjacency {
  size: 4096,
  counters_enabled: true,
  match: { meta.adj_index: exact,
           meta.adj_group_size: exact,
           meta.packet_hash_index: exact },
  action: { ethernet.daddr: set,
            meta.erif: set }
}
```

<a id="rst-erif"></a>

### ERIF

In case the egress RIF and destination MAC have been resolved by previous tables this table does multiple operations like TTL decrease and MTU check. Then the decision of forward/drop is taken and the port L3 statistics are updated based on the packet's type (broadcast, unicast, multicast).



```text
table erif {
  size: 800,
  counters_enabled: true,
  match: { meta.rif_port: exact,
           meta.is_l3_unicast: exact,
           meta.is_l3_broadcast: exact,
           meta.is_l3_multicast, exact },
  action: { meta.l3_drop: set,
            meta.l3_forward: set }
}
```

---

# Devlink E-Switch Attribute

_Peios Kernel / Internals / Networking / devlink_

> Devlink E-Switch supports two modes of operation: legacy and switchdev. Legacy mode operates based on traditional MAC/VLAN steering rules. Switching decisions are made based on MAC addresses, VLANs, etc. There is limited ability to offload…

<a id="rst-devlink-e-switch-attribute"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Devlink E-Switch supports two modes of operation: legacy and switchdev. Legacy mode operates based on traditional MAC/VLAN steering rules. Switching decisions are made based on MAC addresses, VLANs, etc. There is limited ability to offload switching rules to hardware.

On the other hand, switchdev mode allows for more advanced offloading capabilities of the E-Switch to hardware. In switchdev mode, more switching rules and logic can be offloaded to the hardware switch ASIC. It enables representor netdevices that represent the slow path of virtual functions (VFs) or scalable-functions (SFs) of the device. See more information about [Documentation/networking/switchdev.rst](</kernel/internals/networking/switchdev.md#rst-switchdev>) and [Documentation/networking/representors.rst](</kernel/internals/networking/representors.md#rst-representors>).

In addition, the devlink E-Switch also comes with other attributes listed in the following section.

<a id="rst-attributes-description"></a>

## Attributes Description

The following is a list of E-Switch attributes.


<table>
<caption>E-Switch attributes</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`mode`

</td>
<td>


enum

</td>
<td>


The mode of the device. The mode can be one of the following:

- `legacy` operates based on traditional MAC/VLAN steering rules.

- `switchdev` allows for more advanced offloading capabilities of the E-Switch to hardware.

- `switchdev_inactive` switchdev mode but starts inactive, doesn't allow traffic until explicitly activated. This mode is useful for orchestrators that want to prepare the device in switchdev mode but only activate it when all configurations are done.

</td>
</tr>
<tr>
<td>


`inline-mode`

</td>
<td>


enum

</td>
<td>


Some HWs need the VF driver to put part of the packet headers on the TX descriptor so the e-switch can do proper matching and steering. Support for both switchdev mode and legacy mode.

- `none` none.

- `link` L2 mode.

- `network` L3 mode.

- `transport` L4 mode.

</td>
</tr>
<tr>
<td>


`encap-mode`

</td>
<td>


enum

</td>
<td>


The encapsulation mode of the device. Support for both switchdev mode and legacy mode. The mode can be one of the following:

- `none` Disable encapsulation support.

- `basic` Enable encapsulation support.

</td>
</tr>
</tbody>
</table>

<a id="rst-example-usage"></a>

## Example Usage



```shell
# enable switchdev mode
$ devlink dev eswitch set pci/0000:08:00.0 mode switchdev

# set inline-mode and encap-mode
$ devlink dev eswitch set pci/0000:08:00.0 inline-mode none encap-mode basic

# display devlink device eswitch attributes
$ devlink dev eswitch show pci/0000:08:00.0
  pci/0000:08:00.0: mode switchdev inline-mode none encap-mode basic

# enable encap-mode with legacy mode
$ devlink dev eswitch set pci/0000:08:00.0 mode legacy inline-mode none encap-mode basic

# start switchdev mode in inactive state
$ devlink dev eswitch set pci/0000:08:00.0 mode switchdev_inactive

# setup switchdev configurations, representors, FDB entries, etc..
...

# activate switchdev mode to allow traffic
$ devlink dev eswitch set pci/0000:08:00.0 mode switchdev
```

---

# Devlink Flash

_Peios Kernel / Internals / Networking / devlink_

> The devlink-flash API allows updating device firmware. It replaces the older ethtool-flash mechanism, and doesn't require taking any networking locks in the kernel to perform the flash update. Example use:

<a id="rst-devlink-flash-1"></a>
<a id="rst-devlink-flash"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

The `devlink-flash` API allows updating device firmware. It replaces the older `ethtool-flash` mechanism, and doesn't require taking any networking locks in the kernel to perform the flash update. Example use:



```text
$ devlink dev flash pci/0000:05:00.0 file flash-boot.bin
```

Note that the file name is a path relative to the firmware loading path (usually `/lib/firmware/`). Drivers may send status updates to inform user space about the progress of the update operation.

<a id="rst-overwrite-mask"></a>

## Overwrite Mask

The `devlink-flash` command allows optionally specifying a mask indicating how the device should handle subsections of flash components when updating. This mask indicates the set of sections which are allowed to be overwritten.


<table>
<caption>List of overwrite mask bits</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_SETTINGS`

</td>
<td>


Indicates that the device should overwrite settings in the components being updated with the settings found in the provided image.

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_IDENTIFIERS`

</td>
<td>


Indicates that the device should overwrite identifiers in the components being updated with the identifiers found in the provided image. This includes MAC addresses, serial IDs, and similar device identifiers.

</td>
</tr>
</tbody>
</table>

Multiple overwrite bits may be combined and requested together. If no bits are provided, it is expected that the device only update firmware binaries in the components being updated. Settings and identifiers are expected to be preserved across the update. A device may not support every combination and the driver for such a device must reject any combination which cannot be faithfully implemented.

<a id="rst-firmware-loading"></a>

## Firmware Loading

Devices which require firmware to operate usually store it in non-volatile memory on the board, e.g. flash. Some devices store only basic firmware on the board, and the driver loads the rest from disk during probing. `devlink-info` allows users to query firmware information (loaded components and versions).

In other cases the device can both store the image on the board, load from disk, or automatically flash a new image from disk. The `fw_load_policy` devlink parameter can be used to control this behavior ([Documentation/networking/devlink/devlink-params.rst](</kernel/internals/networking/devlink/devlink-params.md#rst-devlink-params-generic>)).

On-disk firmware files are usually stored in `/lib/firmware/`.

<a id="rst-firmware-version-management"></a>

## Firmware Version Management

Drivers are expected to implement `devlink-flash` and `devlink-info` functionality, which together allow for implementing vendor-independent automated firmware update facilities.

`devlink-info` exposes the `driver` name and three version groups (`fixed`, `running`, `stored`).

The `driver` attribute and `fixed` group identify the specific device design, e.g. for looking up applicable firmware updates. This is why `serial_number` is not part of the `fixed` versions (even though it is fixed) - `fixed` versions should identify the design, not a single device.

`running` and `stored` firmware versions identify the firmware running on the device, and firmware which will be activated after reboot or device reset.

The firmware update agent is supposed to be able to follow this simple algorithm to update firmware contents, regardless of the device vendor:



```sh
# Get unique HW design identifier
$hw_id = devlink-dev-info['fixed']

# Find out which FW flash we want to use for this NIC
$want_flash_vers = some-db-backed.lookup($hw_id, 'flash')

# Update flash if necessary
if $want_flash_vers != devlink-dev-info['stored']:
    $file = some-db-backed.download($hw_id, 'flash')
    devlink-dev-flash($file)

# Find out the expected overall firmware versions
$want_fw_vers = some-db-backed.lookup($hw_id, 'all')

# Update on-disk file if necessary
if $want_fw_vers != devlink-dev-info['running']:
    $file = some-db-backed.download($hw_id, 'disk')
    write($file, '/lib/firmware/')

# Try device reset, if available
if $want_fw_vers != devlink-dev-info['running']:
   devlink-reset()

# Reboot, if reset wasn't enough
if $want_fw_vers != devlink-dev-info['running']:
   reboot()
```

Note that each reference to `devlink-dev-info` in this pseudo-code is expected to fetch up-to-date information from the kernel.

For the convenience of identifying firmware files some vendors add `bundle_id` information to the firmware versions. This meta-version covers multiple per-component versions and can be used e.g. in firmware file names (all component versions could get rather long.)

---

# Devlink Health

_Peios Kernel / Internals / Networking / devlink_

> The devlink health mechanism is targeted for Real Time Alerting, in order to know when something bad happened to a PCI device.

<a id="rst-devlink-health"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

The `devlink` health mechanism is targeted for Real Time Alerting, in order to know when something bad happened to a PCI device.

> - Provide alert debug information.
>
> - Self healing.
>
> - If problem needs vendor support, provide a way to gather all needed debugging information.

<a id="rst-overview"></a>

## Overview

The main idea is to unify and centralize driver health reports in the generic `devlink` instance and allow the user to set different attributes of the health reporting and recovery procedures.

The `devlink` health reporter: Device driver creates a "health reporter" per each error/health type. Error/Health type can be a known/generic (e.g. PCI error, fw error, rx/tx error) or unknown (driver specific). For each registered health reporter a driver can issue error/health reports asynchronously. All health reports handling is done by `devlink`. Device driver can provide specific callbacks for each "health reporter", e.g.:

> - Recovery procedures
>
> - Diagnostics procedures
>
> - Object dump procedures
>
> - Out Of Box initial parameters

Different parts of the driver can register different types of health reporters with different handlers.

<a id="rst-actions"></a>

## Actions

Once an error is reported, devlink health will perform the following actions:

> - A log is being send to the kernel trace events buffer
>
> - Health status and statistics are being updated for the reporter instance
>
> - Object dump is being taken and saved at the reporter instance (as long as auto-dump is set and there is no other dump which is already stored)
>
> - Auto recovery attempt is being done. Depends on:
>
>   - Auto-recovery configuration
>
>   - Grace period (and burst period)  vs. time passed since last recover

<a id="rst-devlink-formatted-message"></a>

## Devlink formatted message

To handle devlink health diagnose and health dump requests, devlink creates a formatted message structure `devlink_fmsg` and send it to the driver's callback to fill the data in using the devlink fmsg API.

Devlink fmsg is a mechanism to pass descriptors between drivers and devlink, in json-like format. The API allows the driver to add nested attributes such as object, object pair and value array, in addition to attributes such as name and value.

Driver should use this API to fill the fmsg context in a format which will be translated by the devlink to the netlink message later. When it needs to send the data using SKBs to the netlink layer, it fragments the data between different SKBs. In order to do this fragmentation, it uses virtual nests attributes, to avoid actual nesting use which cannot be divided between different SKBs.

<a id="rst-user-interface"></a>

## User Interface

User can access/change each reporter's parameters and driver specific callbacks via `devlink`, e.g per error type (per health reporter):

> - Configure reporter's generic parameters (like: disable/enable auto recovery)
>
> - Invoke recovery procedure
>
> - Run diagnostics
>
> - Object dump


<table>
<caption>List of devlink health interfaces</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_GET`

</td>
<td>


Retrieves status and configuration info per DEV and reporter.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_SET`

</td>
<td>


Allows reporter-related configuration setting.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_RECOVER`

</td>
<td>


Triggers reporter's recovery procedure.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_TEST`

</td>
<td>


Triggers a fake health event on the reporter. The effects of the test event in terms of recovery flow should follow closely that of a real event.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_DIAGNOSE`

</td>
<td>


Retrieves current device state related to the reporter.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_DUMP_GET`

</td>
<td>


Retrieves the last stored dump. Devlink health saves a single dump. If an dump is not already stored by devlink for this reporter, devlink generates a new dump. Dump output is defined by the reporter.

</td>
</tr>
<tr>
<td>


`DEVLINK_CMD_HEALTH_REPORTER_DUMP_CLEAR`

</td>
<td>


Clears the last saved dump file for the specified reporter.

</td>
</tr>
</tbody>
</table>

The following diagram provides a general overview of `devlink-health`:



```text
                                               netlink
                                      +--------------------------+
                                      |                          |
                                      |            +             |
                                      |            |             |
                                      +--------------------------+
                                                   |request for ops
                                                   |(diagnose,
  driver                               devlink     |recover,
                                                   |dump)
+--------+                            +--------------------------+
|        |                            |    reporter|             |
|        |                            |  +---------v----------+  |
|        |   ops execution            |  |                    |  |
|     <----------------------------------+                    |  |
|        |                            |  |                    |  |
|        |                            |  + ^------------------+  |
|        |                            |    | request for ops     |
|        |                            |    | (recover, dump)     |
|        |                            |    |                     |
|        |                            |  +-+------------------+  |
|        |     health report          |  | health handler     |  |
|        +------------------------------->                    |  |
|        |                            |  +--------------------+  |
|        |     health reporter create |                          |
|        +---------------------------->                          |
+--------+                            +--------------------------+
```

---

# Devlink Info

_Peios Kernel / Internals / Networking / devlink_

> The devlink-info mechanism enables device drivers to report device (hardware and firmware) information in a standard, extensible fashion.

<a id="rst-devlink-info"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

The `devlink-info` mechanism enables device drivers to report device (hardware and firmware) information in a standard, extensible fashion.

The original motivation for the `devlink-info` API was twofold:

> - making it possible to automate device and firmware management in a fleet of machines in a vendor-independent fashion (see also [Documentation/networking/devlink/devlink-flash.rst](</kernel/internals/networking/devlink/devlink-flash.md#rst-devlink-flash>));
>
> - name the per component FW versions (as opposed to the crowded ethtool version string).

`devlink-info` supports reporting multiple types of objects. Reporting driver versions is generally discouraged - here, and via any other Linux API.


<table>
<caption>List of top level info objects</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`driver`

</td>
<td>


Name of the currently used device driver, also available through sysfs.

</td>
</tr>
<tr>
<td>


`serial_number`

</td>
<td>


Serial number of the device.

This is usually the serial number of the ASIC, also often available in PCI config space of the device in the *Device Serial Number* capability.

The serial number should be unique per physical device. Sometimes the serial number of the device is only 48 bits long (the length of the Ethernet MAC address), and since PCI DSN is 64 bits long devices pad or encode additional information into the serial number. One example is adding port ID or PCI interface ID in the extra two bytes. Drivers should make sure to strip or normalize any such padding or interface ID, and report only the part of the serial number which uniquely identifies the hardware. In other words serial number reported for two ports of the same device or on two hosts of a multi-host device should be identical.

</td>
</tr>
<tr>
<td>


`board.serial_number`

</td>
<td>


Board serial number of the device.

This is usually the serial number of the board, often available in PCI *Vital Product Data*.

</td>
</tr>
<tr>
<td>


`fixed`

</td>
<td>


Group for hardware identifiers, and versions of components which are not field-updatable.

Versions in this section identify the device design. For example, component identifiers or the board version reported in the PCI VPD. Data in `devlink-info` should be broken into the smallest logical components, e.g. PCI VPD may concatenate various information to form the Part Number string, while in `devlink-info` all parts should be reported as separate items.

This group must not contain any frequently changing identifiers, such as serial numbers. See [Documentation/networking/devlink/devlink-flash.rst](</kernel/internals/networking/devlink/devlink-flash.md#rst-devlink-flash>) to understand why.

</td>
</tr>
<tr>
<td>


`running`

</td>
<td>


Group for information about currently running software/firmware. These versions often only update after a reboot, sometimes device reset.

</td>
</tr>
<tr>
<td>


`stored`

</td>
<td>


Group for software/firmware versions in device flash.

Stored values must update to reflect changes in the flash even if reboot has not yet occurred. If device is not capable of updating `stored` versions when new software is flashed, it must not report them.

</td>
</tr>
</tbody>
</table>

Each version can be reported at most once in each version group. Firmware components stored on the flash should feature in both the `running` and `stored` sections, if device is capable of reporting `stored` versions (see [Documentation/networking/devlink/devlink-flash.rst](</kernel/internals/networking/devlink/devlink-flash.md#rst-devlink-flash>)). In case software/firmware components are loaded from the disk (e.g. `/lib/firmware`) only the running version should be reported via the kernel API.

Please note that any security versions reported via devlink are purely informational. Devlink does not use a secure channel to communicate with the device.

<a id="rst-generic-versions"></a>

## Generic Versions

It is expected that drivers use the following generic names for exporting version information. If a generic name for a given component doesn't exist yet, driver authors should consult existing driver-specific versions and attempt reuse. As last resort, if a component is truly unique, using driver-specific names is allowed, but these should be documented in the driver-specific file.

All versions should try to use the following terminology:


<table>
<caption>List of common version suffixes</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`id`, `revision`

</td>
<td>


Identifiers of designs and revision, mostly used for hardware versions.

</td>
</tr>
<tr>
<td>


`api`

</td>
<td>


Version of API between components. API items are usually of limited value to the user, and can be inferred from other versions by the vendor, so adding API versions is generally discouraged as noise.

</td>
</tr>
<tr>
<td>


`bundle_id`

</td>
<td>


Identifier of a distribution package which was flashed onto the device. This is an attribute of a firmware package which covers multiple versions for ease of managing firmware images (see [Documentation/networking/devlink/devlink-flash.rst](</kernel/internals/networking/devlink/devlink-flash.md#rst-devlink-flash>)).

`bundle_id` can appear in both `running` and `stored` versions, but it must not be reported if any of the components covered by the `bundle_id` was changed and no longer matches the version from the bundle.

</td>
</tr>
</tbody>
</table>

<a id="rst-board-id"></a>

### board.id

Unique identifier of the board design.

<a id="rst-board-rev"></a>

### board.rev

Board design revision.

<a id="rst-asic-id"></a>

### asic.id

ASIC design identifier.

<a id="rst-asic-rev"></a>

### asic.rev

ASIC design revision/stepping.

<a id="rst-board-manufacture"></a>

### board.manufacture

An identifier of the company or the facility which produced the part.

<a id="rst-board-part-number"></a>

### board.part_number

Part number of the board and its components.

<a id="rst-fw"></a>

### fw

Overall firmware version, often representing the collection of fw.mgmt, fw.app, etc.

<a id="rst-fw-mgmt"></a>

### fw.mgmt

Control unit firmware version. This firmware is responsible for house keeping tasks, PHY control etc. but not the packet-by-packet data path operation.

<a id="rst-fw-mgmt-api"></a>

### fw.mgmt.api

Firmware interface specification version of the software interfaces between driver and firmware.

<a id="rst-fw-app"></a>

### fw.app

Data path microcode controlling high-speed packet processing.

<a id="rst-fw-undi"></a>

### fw.undi

UNDI software, may include the UEFI driver, firmware or both.

<a id="rst-fw-ncsi"></a>

### fw.ncsi

Version of the software responsible for supporting/handling the Network Controller Sideband Interface.

<a id="rst-fw-psid"></a>

### fw.psid

Unique identifier of the firmware parameter set. These are usually parameters of a particular board, defined at manufacturing time.

<a id="rst-fw-roce"></a>

### fw.roce

RoCE firmware version which is responsible for handling roce management.

<a id="rst-fw-bundle-id"></a>

### fw.bundle_id

Unique identifier of the entire firmware bundle.

<a id="rst-fw-bootloader"></a>

### fw.bootloader

Version of the bootloader.

<a id="rst-future-work"></a>

## Future work

The following extensions could be useful:

> - on-disk firmware file names - drivers list the file names of firmware they may need to load onto devices via the `MODULE_FIRMWARE()` macro. These, however, are per module, rather than per device. It'd be useful to list the names of firmware files the driver will try to load for a given device, in order of priority.

---

# Devlink Line card

_Peios Kernel / Internals / Networking / devlink_

> The devlink-linecard mechanism is targeted for manipulation of line cards that serve as a detachable PHY modules for modular switch system. Following operations are provided:

<a id="rst-devlink-line-card"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

The `devlink-linecard` mechanism is targeted for manipulation of line cards that serve as a detachable PHY modules for modular switch system. Following operations are provided:

> - Get a list of supported line card types.
>
> - Provision of a slot with specific line card type.
>
> - Get and monitor of line card state and its change.

Line card according to the type may contain one or more gearboxes to mux the lanes with certain speed to multiple ports with lanes of different speed. Line card ensures N:M mapping between the switch ASIC modules and physical front panel ports.

<a id="rst-overview"></a>

## Overview

Each line card devlink object is created by device driver, according to the physical line card slots available on the device.

Similar to splitter cable, where the device might have no way of detection of the splitter cable geometry, the device might not have a way to detect line card type. For that devices, concept of provisioning is introduced. It allows the user to:

> - Provision a line card slot with certain line card type
>
>   - Device driver would instruct the ASIC to prepare all resources accordingly. The device driver would create all instances, namely devlink port and netdevices that reside on the line card, according to the line card type
>
> - Manipulate of line card entities even without line card being physically connected or powered-up
>
> - Setup splitter cable on line card ports
>
>   - As on the ordinary ports, user may provision a splitter cable of a certain type, without the need to be physically connected to the port
>
> - Configure devlink ports and netdevices

Netdevice carrier is decided as follows:

> - Line card is not inserted or powered-down
>
>   - The carrier is always down
>
> - Line card is inserted and powered up
>
>   - The carrier is decided as for ordinary port netdevice

<a id="rst-line-card-state"></a>

## Line card state

The `devlink-linecard` mechanism supports the following line card states:

> - `unprovisioned`: Line card is not provisioned on the slot.
>
> - `unprovisioning`: Line card slot is currently being unprovisioned.
>
> - `provisioning`: Line card slot is currently in a process of being provisioned with a line card type.
>
> - `provisioning_failed`: Provisioning was not successful.
>
> - `provisioned`: Line card slot is provisioned with a type.
>
> - `active`: Line card is powered-up and active.

The following diagram provides a general overview of `devlink-linecard` state transitions:



```text
                                   +-------------------------+
                                   |                         |
+---------------------------------->      unprovisioned      |
|                                  |                         |
|                                  +--------|-------^--------+
|                                           |       |
|                                           |       |
|                                  +--------v-------|--------+
|                                  |                         |
|                                  |       provisioning      |
|                                  |                         |
|                                  +------------|------------+
|                                               |
|                 +-----------------------------+
|                 |                             |
|    +------------v------------+   +------------v------------+   +-------------------------+
|    |                         |   |                         ---->                         |
+-----   provisioning_failed   |   |       provisioned       |   |         active          |
|    |                         |   |                         <----                         |
|    +------------^------------+   +------------|------------+   +-------------------------+
|                 |                             |
|                 |                             |
|                 |                +------------v------------+
|                 |                |                         |
|                 |                |     unprovisioning      |
|                 |                |                         |
|                 |                +------------|------------+
|                 |                             |
|                 +-----------------------------+
|                                               |
+-----------------------------------------------+
```

<a id="rst-example-usage"></a>

## Example usage



```shell
$ devlink lc show [ DEV [ lc LC_INDEX ] ]
$ devlink lc set DEV lc LC_INDEX [ { type LC_TYPE | notype } ]

# Show current line card configuration and status for all slots:
$ devlink lc

# Set slot 8 to be provisioned with type "16x100G":
$ devlink lc set pci/0000:01:00.0 lc 8 type 16x100G

# Set slot 8 to be unprovisioned:
$ devlink lc set pci/0000:01:00.0 lc 8 notype
```

---

# Devlink Params

_Peios Kernel / Internals / Networking / devlink_

> devlink provides capability for a driver to expose device parameters for low level device functionality. Since devlink can operate at the device-wide level, it can be used to provide configuration that may affect multiple ports on a single…

<a id="rst-devlink-params"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`devlink` provides capability for a driver to expose device parameters for low level device functionality. Since devlink can operate at the device-wide level, it can be used to provide configuration that may affect multiple ports on a single device.

This document describes a number of generic parameters that are supported across multiple drivers. Each driver is also free to add their own parameters. Each driver must document the specific parameters they support, whether generic or not.

<a id="rst-configuration-modes"></a>

## Configuration modes

Parameters may be set in different configuration modes.


<table>
<caption>Possible configuration modes</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`runtime`

</td>
<td>


set while the driver is running, and takes effect immediately. No reset is required.

</td>
</tr>
<tr>
<td>


`driverinit`

</td>
<td>


applied while the driver initializes. Requires the user to restart the driver using the `devlink` reload command.

</td>
</tr>
<tr>
<td>


`permanent`

</td>
<td>


written to the device's non-volatile memory. A hard reset is required for it to take effect.

</td>
</tr>
</tbody>
</table>

<a id="rst-reloading"></a>

### Reloading

In order for `driverinit` parameters to take effect, the driver must support reloading via the `devlink-reload` command. This command will request a reload of the device driver.

<a id="rst-default-parameter-values"></a>

## Default parameter values

Drivers may optionally export default values for parameters of cmode `runtime` and `permanent`. For `driverinit` parameters, the last value set by the driver will be used as the default value. Drivers can also support resetting params with cmode `runtime` and `permanent` to their default values. Resetting `driverinit` params is supported by devlink core without additional driver support needed.

<a id="rst-generic-configuration-parameters"></a>
<a id="rst-devlink-params-generic"></a>

## Generic configuration parameters

The following is a list of generic configuration parameters that drivers may add. Use of generic parameters is preferred over each driver creating their own name.


<table>
<caption>List of generic parameters</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`enable_sriov`

</td>
<td>


Boolean

</td>
<td>


Enable Single Root I/O Virtualization (SRIOV) in the device.

</td>
</tr>
<tr>
<td>


`ignore_ari`

</td>
<td>


Boolean

</td>
<td>


Ignore Alternative Routing-ID Interpretation (ARI) capability. If enabled, the adapter will ignore ARI capability even when the platform has support enabled. The device will create the same number of partitions as when the platform does not support ARI.

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_max`

</td>
<td>


u32

</td>
<td>


Provides the maximum number of MSI-X interrupts that a device can create. Value is the same across all physical functions (PFs) in the device.

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_min`

</td>
<td>


u32

</td>
<td>


Provides the minimum number of MSI-X interrupts required for the device to initialize. Value is the same across all physical functions (PFs) in the device.

</td>
</tr>
<tr>
<td>


`fw_load_policy`

</td>
<td>


u8

</td>
<td>


- **Control the device's firmware loading policy.**

  - `DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_DRIVER` (0) Load firmware version preferred by the driver.

  - `DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_FLASH` (1) Load firmware currently stored in flash.

  - `DEVLINK_PARAM_FW_LOAD_POLICY_VALUE_DISK` (2) Load firmware currently available on host's disk.

</td>
</tr>
<tr>
<td>


`reset_dev_on_drv_probe`

</td>
<td>


u8

</td>
<td>


- **Controls the device's reset policy on driver probe.**

  - `DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_UNKNOWN` (0) Unknown or invalid value.

  - `DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_ALWAYS` (1) Always reset device on driver probe.

  - `DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_NEVER` (2) Never reset device on driver probe.

  - `DEVLINK_PARAM_RESET_DEV_ON_DRV_PROBE_VALUE_DISK` (3) Reset the device only if firmware can be found in the filesystem.

</td>
</tr>
<tr>
<td>


`enable_roce`

</td>
<td>


Boolean

</td>
<td>


Enable handling of RoCE traffic in the device.

</td>
</tr>
<tr>
<td>


`enable_eth`

</td>
<td>


Boolean

</td>
<td>


When enabled, the device driver will instantiate Ethernet specific auxiliary device of the devlink device.

</td>
</tr>
<tr>
<td>


`enable_rdma`

</td>
<td>


Boolean

</td>
<td>


When enabled, the device driver will instantiate RDMA specific auxiliary device of the devlink device.

</td>
</tr>
<tr>
<td>


`enable_vnet`

</td>
<td>


Boolean

</td>
<td>


When enabled, the device driver will instantiate VDPA networking specific auxiliary device of the devlink device.

</td>
</tr>
<tr>
<td>


`enable_iwarp`

</td>
<td>


Boolean

</td>
<td>


Enable handling of iWARP traffic in the device.

</td>
</tr>
<tr>
<td>


`internal_err_reset`

</td>
<td>


Boolean

</td>
<td>


When enabled, the device driver will reset the device on internal errors.

</td>
</tr>
<tr>
<td>


`max_macs`

</td>
<td>


u32

</td>
<td>


Typically macvlan, vlan net devices mac are also programmed in their parent netdevice's Function rx filter. This parameter limit the maximum number of unicast mac address filters to receive traffic from per ethernet port of this device.

</td>
</tr>
<tr>
<td>


`region_snapshot_enable`

</td>
<td>


Boolean

</td>
<td>


Enable capture of `devlink-region` snapshots.

</td>
</tr>
<tr>
<td>


`enable_remote_dev_reset`

</td>
<td>


Boolean

</td>
<td>


Enable device reset by remote host. When cleared, the device driver will NACK any attempt of other host to reset the device. This parameter is useful for setups where a device is shared by different hosts, such as multi-host setup.

</td>
</tr>
<tr>
<td>


`io_eq_size`

</td>
<td>


u32

</td>
<td>


Control the size of I/O completion EQs.

</td>
</tr>
<tr>
<td>


`event_eq_size`

</td>
<td>


u32

</td>
<td>


Control the size of asynchronous control events EQ.

</td>
</tr>
<tr>
<td>


`enable_phc`

</td>
<td>


Boolean

</td>
<td>


Enable PHC (PTP Hardware Clock) functionality in the device.

</td>
</tr>
<tr>
<td>


`clock_id`

</td>
<td>


u64

</td>
<td>


Clock ID used by the device for registering DPLL devices and pins.

</td>
</tr>
<tr>
<td>


`total_vfs`

</td>
<td>


u32

</td>
<td>


The max number of Virtual Functions (VFs) exposed by the PF. after reboot/pci reset, 'sriov_totalvfs' entry under the device's sysfs directory will report this value.

</td>
</tr>
<tr>
<td>


`num_doorbells`

</td>
<td>


u32

</td>
<td>


Controls the number of doorbells used by the device.

</td>
</tr>
<tr>
<td>


`max_mac_per_vf`

</td>
<td>


u32

</td>
<td>


Controls the maximum number of MAC address filters that can be assigned to a Virtual Function (VF).

</td>
</tr>
</tbody>
</table>

---

# Devlink Port

_Peios Kernel / Internals / Networking / devlink_

> devlink-port is a port that exists on the device. It has a logically separate ingress/egress point of the device. A devlink port can be any one of many flavours. A devlink port flavour along with port attributes describe what a port…

<a id="rst-devlink-port-1"></a>
<a id="rst-devlink-port"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`devlink-port` is a port that exists on the device. It has a logically separate ingress/egress point of the device. A devlink port can be any one of many flavours. A devlink port flavour along with port attributes describe what a port represents.

A device driver that intends to publish a devlink port sets the devlink port attributes and registers the devlink port.

Devlink port flavours are described below.


<table>
<caption>List of devlink port flavours</caption>
<tbody>
<tr>
<td>


Flavour

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_PHYSICAL`

</td>
<td>


Any kind of physical port. This can be an eswitch physical port or any other physical port on the device.

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_DSA`

</td>
<td>


This indicates a DSA interconnect port.

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_CPU`

</td>
<td>


This indicates a CPU port applicable only to DSA.

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_PCI_PF`

</td>
<td>


This indicates an eswitch port representing a port of PCI physical function (PF).

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_PCI_VF`

</td>
<td>


This indicates an eswitch port representing a port of PCI virtual function (VF).

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_PCI_SF`

</td>
<td>


This indicates an eswitch port representing a port of PCI subfunction (SF).

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_FLAVOUR_VIRTUAL`

</td>
<td>


This indicates a virtual port for the PCI virtual function.

</td>
</tr>
</tbody>
</table>

Devlink port can have a different type based on the link layer described below.


<table>
<caption>List of devlink port types</caption>
<tbody>
<tr>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_TYPE_ETH`

</td>
<td>


Driver should set this port type when a link layer of the port is Ethernet.

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_TYPE_IB`

</td>
<td>


Driver should set this port type when a link layer of the port is InfiniBand.

</td>
</tr>
<tr>
<td>


`DEVLINK_PORT_TYPE_AUTO`

</td>
<td>


This type is indicated by the user when driver should detect the port type automatically.

</td>
</tr>
</tbody>
</table>

<a id="rst-pci-controllers"></a>

## PCI controllers

In most cases a PCI device has only one controller. A controller consists of potentially multiple physical, virtual functions and subfunctions. A function consists of one or more ports. This port is represented by the devlink eswitch port.

A PCI device connected to multiple CPUs or multiple PCI root complexes or a SmartNIC, however, may have multiple controllers. For a device with multiple controllers, each controller is distinguished by a unique controller number. An eswitch is on the PCI device which supports ports of multiple controllers.

An example view of a system with two controllers:



```text
             ---------------------------------------------------------
             |                                                       |
             |           --------- ---------         ------- ------- |
-----------  |           | vf(s) | | sf(s) |         |vf(s)| |sf(s)| |
| server  |  | -------   ----/---- ---/----- ------- ---/--- ---/--- |
| pci rc  |=== | pf0 |______/________/       | pf1 |___/_______/     |
| connect |  | -------                       -------                 |
-----------  |     | controller_num=1 (no eswitch)                   |
             ------|--------------------------------------------------
             (internal wire)
                   |
             ---------------------------------------------------------
             | devlink eswitch ports and reps                        |
             | ----------------------------------------------------- |
             | |ctrl-0 | ctrl-0 | ctrl-0 | ctrl-0 | ctrl-0 |ctrl-0 | |
             | |pf0    | pf0vfN | pf0sfN | pf1    | pf1vfN |pf1sfN | |
             | ----------------------------------------------------- |
             | |ctrl-1 | ctrl-1 | ctrl-1 | ctrl-1 | ctrl-1 |ctrl-1 | |
             | |pf0    | pf0vfN | pf0sfN | pf1    | pf1vfN |pf1sfN | |
             | ----------------------------------------------------- |
             |                                                       |
             |                                                       |
-----------  |           --------- ---------         ------- ------- |
| smartNIC|  |           | vf(s) | | sf(s) |         |vf(s)| |sf(s)| |
| pci rc  |==| -------   ----/---- ---/----- ------- ---/--- ---/--- |
| connect |  | | pf0 |______/________/       | pf1 |___/_______/     |
-----------  | -------                       -------                 |
             |                                                       |
             |  local controller_num=0 (eswitch)                     |
             ---------------------------------------------------------
```

In the above example, the external controller (identified by controller number = 1) doesn't have the eswitch. Local controller (identified by controller number = 0) has the eswitch. The Devlink instance on the local controller has eswitch devlink ports for both the controllers.

<a id="rst-function-configuration"></a>

### Function configuration

Users can configure one or more function attributes before enumerating the PCI function. Usually it means, user should configure function attribute before a bus specific device for the function is created. However, when SRIOV is enabled, virtual function devices are created on the PCI bus. Hence, function attribute should be configured before binding virtual function device to the driver. For subfunctions, this means user should configure port function attribute before activating the port function.

A user may set the hardware address of the function using `devlink port function set hw_addr` command. For Ethernet port function this means a MAC address.

Users may also set the RoCE capability of the function using `devlink port function set roce` command.

Users may also set the function as migratable using `devlink port function set migratable` command.

Users may also set the IPsec crypto capability of the function using `devlink port function set ipsec_crypto` command.

Users may also set the IPsec packet capability of the function using `devlink port function set ipsec_packet` command.

Users may also set the maximum IO event queues of the function using `devlink port function set max_io_eqs` command.

<a id="rst-function-attributes"></a>

### Function attributes

<a id="rst-mac-address-setup"></a>

## MAC address setup

The configured MAC address of the PCI VF/SF will be used by netdevice and rdma device created for the PCI VF/SF.

- Get the MAC address of the VF identified by its unique devlink port index:



  ```text
  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
    function:
      hw_addr 00:00:00:00:00:00
  ```

- Set the MAC address of the VF identified by its unique devlink port index:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 hw_addr 00:11:22:33:44:55

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
    function:
      hw_addr 00:11:22:33:44:55
  ```

- Get the MAC address of the SF identified by its unique devlink port index:



  ```text
  $ devlink port show pci/0000:06:00.0/32768
  pci/0000:06:00.0/32768: type eth netdev enp6s0pf0sf88 flavour pcisf pfnum 0 sfnum 88
    function:
      hw_addr 00:00:00:00:00:00
  ```

- Set the MAC address of the SF identified by its unique devlink port index:



  ```text
  $ devlink port function set pci/0000:06:00.0/32768 hw_addr 00:00:00:00:88:88

  $ devlink port show pci/0000:06:00.0/32768
  pci/0000:06:00.0/32768: type eth netdev enp6s0pf0sf88 flavour pcisf pfnum 0 sfnum 88
    function:
      hw_addr 00:00:00:00:88:88
  ```

<a id="rst-roce-capability-setup"></a>

## RoCE capability setup

Not all PCI VFs/SFs require RoCE capability.

When RoCE capability is disabled, it saves system memory per PCI VF/SF.

When user disables RoCE capability for a VF/SF, user application cannot send or receive any RoCE packets through this VF/SF and RoCE GID table for this PCI will be empty.

When RoCE capability is disabled in the device using port function attribute, VF/SF driver cannot override it.

- Get RoCE capability of the VF device:



  ```text
  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 roce enable
  ```

- Set RoCE capability of the VF device:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 roce disable

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 roce disable
  ```

<a id="rst-migratable-capability-setup"></a>

## migratable capability setup

Live migration is the process of transferring a live virtual machine from one physical host to another without disrupting its normal operation.

User who want PCI VFs to be able to perform live migration need to explicitly enable the VF migratable capability.

When user enables migratable capability for a VF, and the HV binds the VF to VFIO driver with migration support, the user can migrate the VM with this VF from one HV to a different one.

However, when migratable capability is enable, device will disable features which cannot be migrated. Thus migratable cap can impose limitations on a VF so let the user decide.

Example of LM with migratable function configuration: - Get migratable capability of the VF device:



```text
$ devlink port show pci/0000:06:00.0/2
pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
    function:
        hw_addr 00:00:00:00:00:00 migratable disable
```

- Set migratable capability of the VF device:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 migratable enable

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 migratable enable
  ```

- Bind VF to VFIO driver with migration support:



  ```text
  $ echo <pci_id> > /sys/bus/pci/devices/0000:08:00.0/driver/unbind
  $ echo mlx5_vfio_pci > /sys/bus/pci/devices/0000:08:00.0/driver_override
  $ echo <pci_id> > /sys/bus/pci/devices/0000:08:00.0/driver/bind
  ```

Attach VF to the VM. Start the VM. Perform live migration.

<a id="rst-ipsec-crypto-capability-setup"></a>

## IPsec crypto capability setup

When user enables IPsec crypto capability for a VF, user application can offload XFRM state crypto operation (Encrypt/Decrypt) to this VF.

When IPsec crypto capability is disabled (default) for a VF, the XFRM state is processed in software by the kernel.

- Get IPsec crypto capability of the VF device:



  ```text
  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_crypto disabled
  ```

- Set IPsec crypto capability of the VF device:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 ipsec_crypto enable

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_crypto enabled
  ```

<a id="rst-ipsec-packet-capability-setup"></a>

## IPsec packet capability setup

When user enables IPsec packet capability for a VF, user application can offload XFRM state and policy crypto operation (Encrypt/Decrypt) to this VF, as well as IPsec encapsulation.

When IPsec packet capability is disabled (default) for a VF, the XFRM state and policy is processed in software by the kernel.

- Get IPsec packet capability of the VF device:



  ```text
  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_packet disabled
  ```

- Set IPsec packet capability of the VF device:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 ipsec_packet enable

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_packet enabled
  ```

<a id="rst-maximum-io-events-queues-setup"></a>

## Maximum IO events queues setup

When user sets maximum number of IO event queues for a SF or a VF, such function driver is limited to consume only enforced number of IO event queues.

IO event queues deliver events related to IO queues, including network device transmit and receive queues (txq and rxq) and RDMA Queue Pairs (QPs). For example, the number of netdevice channels and RDMA device completion vectors are derived from the function's IO event queues. Usually, the number of interrupt vectors consumed by the driver is limited by the number of IO event queues per device, as each of the IO event queues is connected to an interrupt vector.

- Get maximum IO event queues of the VF device:



  ```text
  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_packet disabled max_io_eqs 10
  ```

- Set maximum IO event queues of the VF device:



  ```text
  $ devlink port function set pci/0000:06:00.0/2 max_io_eqs 32

  $ devlink port show pci/0000:06:00.0/2
  pci/0000:06:00.0/2: type eth netdev enp6s0pf0vf1 flavour pcivf pfnum 0 vfnum 1
      function:
          hw_addr 00:00:00:00:00:00 ipsec_packet disabled max_io_eqs 32
  ```

<a id="rst-subfunction"></a>

### Subfunction

Subfunction is a lightweight function that has a parent PCI function on which it is deployed. Subfunction is created and deployed in unit of 1. Unlike SRIOV VFs, a subfunction doesn't require its own PCI virtual function. A subfunction communicates with the hardware through the parent PCI function.

To use a subfunction, 3 steps setup sequence is followed:

1. create - create a subfunction;

2. configure - configure subfunction attributes;

3. deploy - deploy the subfunction;

Subfunction management is done using devlink port user interface. User performs setup on the subfunction management device.

<a id="rst-create"></a>

## (1) Create

A subfunction is created using a devlink port interface. A user adds the subfunction by adding a devlink port of subfunction flavour. The devlink kernel code calls down to subfunction management driver (devlink ops) and asks it to create a subfunction devlink port. Driver then instantiates the subfunction port and any associated objects such as health reporters and representor netdevice.

<a id="rst-configure"></a>

## (2) Configure

A subfunction devlink port is created but it is not active yet. That means the entities are created on devlink side, the e-switch port representor is created, but the subfunction device itself is not created. A user might use e-switch port representor to do settings, putting it into bridge, adding TC rules, etc. A user might as well configure the hardware address (such as MAC address) of the subfunction while subfunction is inactive.

<a id="rst-deploy"></a>

## (3) Deploy

Once a subfunction is configured, user must activate it to use it. Upon activation, subfunction management driver asks the subfunction management device to instantiate the subfunction device on particular PCI function. A subfunction device is created on the [Documentation/driver-api/auxiliary_bus.rst](</kernel/hardware/driver-api/buses/auxiliary-bus.md#rst-auxiliary-bus>). At this point a matching subfunction driver binds to the subfunction's auxiliary device.

<a id="rst-rate-object-management"></a>

### Rate object management

Devlink provides API to manage tx rates of single devlink port or a group. This is done through rate objects, which can be one of the two types:

- **`leaf`**

  Represents a single devlink port; created/destroyed by the driver. Since leaf have 1to1 mapping to its devlink port, in user space it is referred as `pci/<bus_addr>/<port_index>`;

- **`node`**

  Represents a group of rate objects (leafs and/or nodes); created/deleted by request from the userspace; initially empty (no rate objects added). In userspace it is referred as `pci/<bus_addr>/<node_name>`, where `node_name` can be any identifier, except decimal number, to avoid collisions with leafs.

API allows to configure following rate object's parameters:

- **`tx_share`**

  Minimum TX rate value shared among all other rate objects, or rate objects that parts of the parent group, if it is a part of the same group.

- **`tx_max`**

  Maximum TX rate value.

- **`tx_priority`**

  Allows for usage of strict priority arbiter among siblings. This arbitration scheme attempts to schedule nodes based on their priority as long as the nodes remain within their bandwidth limit. The higher the priority the higher the probability that the node will get selected for scheduling.

- **`tx_weight`**

  Allows for usage of Weighted Fair Queuing arbitration scheme among siblings. This arbitration scheme can be used simultaneously with the strict priority. As a node is configured with a higher rate it gets more BW relative to its siblings. Values are relative like a percentage points, they basically tell how much BW should node take relative to its siblings.

- **`parent`**

  Parent node name. Parent node rate limits are considered as additional limits to all node children limits. `tx_max` is an upper limit for children. `tx_share` is a total bandwidth distributed among children.

- **`tc_bw`**

  Allow users to set the bandwidth allocation per traffic class on rate objects. This enables fine-grained QoS configurations by assigning a relative share value to each traffic class. The bandwidth is distributed in proportion to the share value for each class, relative to the sum of all shares. When applied to a non-leaf node, tc_bw determines how bandwidth is shared among its child elements.

`tx_priority` and `tx_weight` can be used simultaneously. In that case nodes with the same priority form a WFQ subgroup in the sibling group and arbitration among them is based on assigned weights.

Arbitration flow from the high level:

1. Choose a node, or group of nodes with the highest priority that stays within the BW limit and are not blocked. Use `tx_priority` as a parameter for this arbitration.

2. If group of nodes have the same priority perform WFQ arbitration on that subgroup. Use `tx_weight` as a parameter for this arbitration.

3. Select the winner node, and continue arbitration flow among its children, until leaf node is reached, and the winner is established.

4. If all the nodes from the highest priority sub-group are satisfied, or overused their assigned BW, move to the lower priority nodes.

Driver implementations are allowed to support both or either rate object types and setting methods of their parameters. Additionally driver implementation may export nodes/leafs and their child-parent relationships.

<a id="rst-terms-and-definitions"></a>

### Terms and Definitions


<table>
<caption>Terms and Definitions</caption>
<tbody>
<tr>
<td>


Term

</td>
<td>


Definitions

</td>
</tr>
<tr>
<td>


`PCI device`

</td>
<td>


A physical PCI device having one or more PCI buses consists of one or more PCI controllers.

</td>
</tr>
<tr>
<td>


`PCI controller`

</td>
<td>


A controller consists of potentially multiple physical functions, virtual functions and subfunctions.

</td>
</tr>
<tr>
<td>


`Port function`

</td>
<td>


An object to manage the function of a port.

</td>
</tr>
<tr>
<td>


`Subfunction`

</td>
<td>


A lightweight function that has parent PCI function on which it is deployed.

</td>
</tr>
<tr>
<td>


`Subfunction device`

</td>
<td>


A bus device of the subfunction, usually on a auxiliary bus.

</td>
</tr>
<tr>
<td>


`Subfunction driver`

</td>
<td>


A device driver for the subfunction auxiliary device.

</td>
</tr>
<tr>
<td>


`Subfunction management device`

</td>
<td>


A PCI physical function that supports subfunction management.

</td>
</tr>
<tr>
<td>


`Subfunction management driver`

</td>
<td>


A device driver for PCI physical function that supports subfunction management using devlink port interface.

</td>
</tr>
<tr>
<td>


`Subfunction host driver`

</td>
<td>


A device driver for PCI physical function that hosts subfunction devices. In most cases it is same as subfunction management driver. When subfunction is used on external controller, subfunction management and host drivers are different.

</td>
</tr>
</tbody>
</table>

---

# Devlink Region

_Peios Kernel / Internals / Networking / devlink_

> devlink regions enable access to driver defined address regions using devlink.

<a id="rst-devlink-region"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`devlink` regions enable access to driver defined address regions using devlink.

Each device can create and register its own supported address regions. The region can then be accessed via the devlink region interface.

Region snapshots are collected by the driver, and can be accessed via read or dump commands. This allows future analysis on the created snapshots. Regions may optionally support triggering snapshots on demand.

Snapshot identifiers are scoped to the devlink instance, not a region. All snapshots with the same snapshot id within a devlink instance correspond to the same event.

The major benefit to creating a region is to provide access to internal address regions that are otherwise inaccessible to the user.

Regions may also be used to provide an additional way to debug complex error states, but see also [Documentation/networking/devlink/devlink-health.rst](/kernel/internals/networking/devlink/devlink-health.md)

Regions may optionally support capturing a snapshot on demand via the `DEVLINK_CMD_REGION_NEW` netlink message. A driver wishing to allow requested snapshots must implement the `.snapshot` callback for the region in its `devlink_region_ops` structure. If snapshot id is not set in the `DEVLINK_CMD_REGION_NEW` request kernel will allocate one and send the snapshot information to user space.

Regions may optionally allow directly reading from their contents without a snapshot. Direct read requests are not atomic. In particular a read request of size 256 bytes or larger will be split into multiple chunks. If atomic access is required, use a snapshot. A driver wishing to enable this for a region should implement the `.read` callback in the `devlink_region_ops` structure. User space can request a direct read by using the `DEVLINK_ATTR_REGION_DIRECT` attribute instead of specifying a snapshot id.

<a id="rst-example-usage"></a>

## example usage



```shell
$ devlink region help
$ devlink region show [ DEV/REGION ]
$ devlink region del DEV/REGION snapshot SNAPSHOT_ID
$ devlink region dump DEV/REGION [ snapshot SNAPSHOT_ID ]
$ devlink region read DEV/REGION [ snapshot SNAPSHOT_ID ] address ADDRESS length LENGTH

# Show all of the exposed regions with region sizes:
$ devlink region show
pci/0000:00:05.0/cr-space: size 1048576 snapshot [1 2] max 8
pci/0000:00:05.0/fw-health: size 64 snapshot [1 2] max 8

# Delete a snapshot using:
$ devlink region del pci/0000:00:05.0/cr-space snapshot 1

# Request an immediate snapshot, if supported by the region
$ devlink region new pci/0000:00:05.0/cr-space
pci/0000:00:05.0/cr-space: snapshot 5

# Dump a snapshot:
$ devlink region dump pci/0000:00:05.0/fw-health snapshot 1
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30
0000000000000010 0000 0000 ffff ff04 0029 8c00 0028 8cc8
0000000000000020 0016 0bb8 0016 1720 0000 0000 c00f 3ffc
0000000000000030 bada cce5 bada cce5 bada cce5 bada cce5

# Read a specific part of a snapshot:
$ devlink region read pci/0000:00:05.0/fw-health snapshot 1 address 0 length 16
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30

# Read from the region without a snapshot
$ devlink region read pci/0000:00:05.0/fw-health address 16 length 16
0000000000000010 0000 0000 ffff ff04 0029 8c00 0028 8cc8
```

As regions are likely very device or driver specific, no generic regions are defined. See the driver-specific documentation files for information on the specific regions a driver supports.

---

# Devlink Reload

_Peios Kernel / Internals / Networking / devlink_

> devlink-reload provides mechanism to reinit driver entities, applying devlink-params and devlink-resources new values. It also provides mechanism to activate firmware.

<a id="rst-devlink-reload"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`devlink-reload` provides mechanism to reinit driver entities, applying `devlink-params` and `devlink-resources` new values. It also provides mechanism to activate firmware.

<a id="rst-reload-actions"></a>

## Reload Actions

User may select a reload action. By default `driver_reinit` action is selected.


<table>
<caption>Possible reload actions</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`driver-reinit`

</td>
<td>


Devlink driver entities re-initialization, including applying new values to devlink entities which are used during driver load which are:

- `devlink-params` in configuration mode `driverinit`

- `devlink-resources`

Other devlink entities may stay over the re-initialization:

- `devlink-health-reporter`

- `devlink-region`

The rest of the devlink entities have to be removed and readded.

</td>
</tr>
<tr>
<td>


`fw_activate`

</td>
<td>


Firmware activate. Activates new firmware if such image is stored and pending activation. If no limitation specified this action may involve firmware reset. If no new image pending this action will reload current firmware image.

</td>
</tr>
</tbody>
</table>

Note that even though user asks for a specific action, the driver implementation might require to perform another action alongside with it. For example, some driver do not support driver reinitialization being performed without fw activation. Therefore, the devlink reload command returns the list of actions which were actrually performed.

<a id="rst-reload-limits"></a>

## Reload Limits

By default reload actions are not limited and driver implementation may include reset or downtime as needed to perform the actions.

However, some drivers support action limits, which limit the action implementation to specific constraints.


<table>
<caption>Possible reload limits</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`no_reset`

</td>
<td>


No reset allowed, no down time allowed, no link flap and no configuration is lost.

</td>
</tr>
</tbody>
</table>

<a id="rst-change-namespace"></a>

## Change Namespace

The netns option allows user to be able to move devlink instances into namespaces during devlink reload operation. By default all devlink instances are created in init_net and stay there.

<a id="rst-example-usage"></a>

### example usage



```shell
$ devlink dev reload help
$ devlink dev reload DEV [ netns { PID | NAME | ID } ] [ action { driver_reinit | fw_activate } ] [ limit no_reset ]

# Run reload command for devlink driver entities re-initialization:
$ devlink dev reload pci/0000:82:00.0 action driver_reinit
reload_actions_performed:
  driver_reinit

# Run reload command to activate firmware:
# Note that mlx5 driver reloads the driver while activating firmware
$ devlink dev reload pci/0000:82:00.0 action fw_activate
reload_actions_performed:
  driver_reinit fw_activate
```

---

# Devlink Resource

_Peios Kernel / Internals / Networking / devlink_

> devlink provides the ability for drivers to register resources, which can allow administrators to see the device restrictions for a given resource, as well as how much of the given resource is currently in use. Additionally, these…

<a id="rst-devlink-resource"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

`devlink` provides the ability for drivers to register resources, which can allow administrators to see the device restrictions for a given resource, as well as how much of the given resource is currently in use. Additionally, these resources can optionally have configurable size. This could enable the administrator to limit the number of resources that are used.

For example, the `netdevsim` driver enables `/IPv4/fib` and `/IPv4/fib-rules` as resources to limit the number of IPv4 FIB entries and rules for a given device.

<a id="rst-resource-ids"></a>

## Resource Ids

Each resource is represented by an id, and contains information about its current size and related sub resources. To access a sub resource, you specify the path of the resource. For example `/IPv4/fib` is the id for the `fib` sub-resource under the `IPv4` resource.

<a id="rst-generic-resources"></a>

## Generic Resources

Generic resources are used to describe resources that can be shared by multiple device drivers and their description must be added to the following table:


<table>
<caption>List of Generic Resources</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`physical_ports`

</td>
<td>


A limited capacity of physical ports that the switch ASIC can support

</td>
</tr>
</tbody>
</table>

<a id="rst-example-usage"></a>

### example usage

The resources exposed by the driver can be observed, for example:



```shell
$devlink resource show pci/0000:03:00.0
pci/0000:03:00.0:
  name kvd size 245760 unit entry
    resources:
      name linear size 98304 occ 0 unit entry size_min 0 size_max 147456 size_gran 128
      name hash_double size 60416 unit entry size_min 32768 size_max 180224 size_gran 128
      name hash_single size 87040 unit entry size_min 65536 size_max 212992 size_gran 128
```

Some resource's size can be changed. Examples:



```shell
$devlink resource set pci/0000:03:00.0 path /kvd/hash_single size 73088
$devlink resource set pci/0000:03:00.0 path /kvd/hash_double size 74368
```

The changes do not apply immediately, this can be validated by the 'size_new' attribute, which represents the pending change in size. For example:



```shell
$devlink resource show pci/0000:03:00.0
pci/0000:03:00.0:
  name kvd size 245760 unit entry size_valid false
  resources:
    name linear size 98304 size_new 147456 occ 0 unit entry size_min 0 size_max 147456 size_gran 128
    name hash_double size 60416 unit entry size_min 32768 size_max 180224 size_gran 128
    name hash_single size 87040 unit entry size_min 65536 size_max 212992 size_gran 128
```

Note that changes in resource size may require a device reload to properly take effect.

---

# Devlink Selftests

_Peios Kernel / Internals / Networking / devlink_

> The devlink-selftests API allows executing selftests on the device.

<a id="rst-devlink-selftests"></a>

<!-- SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -->

The `devlink-selftests` API allows executing selftests on the device.

<a id="rst-tests-mask"></a>

## Tests Mask

The `devlink-selftests` command should be run with a mask indicating the tests to be executed.

<a id="rst-tests-description"></a>

## Tests Description

The following is a list of tests that drivers may execute.


<table>
<caption>List of tests</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`DEVLINK_SELFTEST_FLASH`

</td>
<td>


Devices may have the firmware on non-volatile memory on the board, e.g. flash. This particular test helps to run a flash selftest on the device. Implementation of the test is left to the driver/firmware.

</td>
</tr>
</tbody>
</table>

<a id="rst-example-usage"></a>

### example usage



```shell
# Query selftests supported on the devlink device
$ devlink dev selftests show DEV
# Query selftests supported on all devlink devices
$ devlink dev selftests show
# Executes selftests on the device
$ devlink dev selftests run DEV id flash
```

---

# Devlink Trap

_Peios Kernel / Internals / Networking / devlink_

> Devices capable of offloading the kernel's datapath and perform functions such as bridging and routing must also be able to send specific packets to the kernel (i.e., the CPU) for processing.

<a id="rst-devlink-trap"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

Devices capable of offloading the kernel's datapath and perform functions such as bridging and routing must also be able to send specific packets to the kernel (i.e., the CPU) for processing.

For example, a device acting as a multicast-aware bridge must be able to send IGMP membership reports to the kernel for processing by the bridge module. Without processing such packets, the bridge module could never populate its MDB.

As another example, consider a device acting as router which has received an IP packet with a TTL of 1. Upon routing the packet the device must send it to the kernel so that it will route it as well and generate an ICMP Time Exceeded error datagram. Without letting the kernel route such packets itself, utilities such as `traceroute` could never work.

The fundamental ability of sending certain packets to the kernel for processing is called "packet trapping".

<a id="rst-overview"></a>

## Overview

The `devlink-trap` mechanism allows capable device drivers to register their supported packet traps with `devlink` and report trapped packets to `devlink` for further analysis.

Upon receiving trapped packets, `devlink` will perform a per-trap packets and bytes accounting and potentially report the packet to user space via a netlink event along with all the provided metadata (e.g., trap reason, timestamp, input port). This is especially useful for drop traps (see [Trap Types](<#rst-trap-types>)) as it allows users to obtain further visibility into packet drops that would otherwise be invisible.

The following diagram provides a general overview of `devlink-trap`:



```text
                            Netlink event: Packet w/ metadata
                                           Or a summary of recent drops
                          ^
                          |
 Userspace                |
+---------------------------------------------------+
 Kernel                   |
                          |
                  +-------+--------+
                  |                |
                  |  drop_monitor  |
                  |                |
                  +-------^--------+
                          |
                          | Non-control traps
                          |
                     +----+----+
                     |         |      Kernel's Rx path
                     | devlink |      (non-drop traps)
                     |         |
                     +----^----+      ^
                          |           |
                          +-----------+
                          |
                  +-------+-------+
                  |               |
                  | Device driver |
                  |               |
                  +-------^-------+
 Kernel                   |
+---------------------------------------------------+
 Hardware                 |
                          | Trapped packet
                          |
                       +--+---+
                       |      |
                       | ASIC |
                       |      |
                       +------+
```

<a id="rst-trap-types-1"></a>
<a id="rst-trap-types"></a>

## Trap Types

The `devlink-trap` mechanism supports the following packet trap types:

> - `drop`: Trapped packets were dropped by the underlying device. Packets are only processed by `devlink` and not injected to the kernel's Rx path. The trap action (see [Trap Actions](<#rst-trap-actions>)) can be changed.
>
> - `exception`: Trapped packets were not forwarded as intended by the underlying device due to an exception (e.g., TTL error, missing neighbour entry) and trapped to the control plane for resolution. Packets are processed by `devlink` and injected to the kernel's Rx path. Changing the action of such traps is not allowed, as it can easily break the control plane.
>
> - `control`: Trapped packets were trapped by the device because these are control packets required for the correct functioning of the control plane. For example, ARP request and IGMP query packets. Packets are injected to the kernel's Rx path, but not reported to the kernel's drop monitor. Changing the action of such traps is not allowed, as it can easily break the control plane.

<a id="rst-trap-actions-1"></a>
<a id="rst-trap-actions"></a>

## Trap Actions

The `devlink-trap` mechanism supports the following packet trap actions:

> - `trap`: The sole copy of the packet is sent to the CPU.
>
> - `drop`: The packet is dropped by the underlying device and a copy is not sent to the CPU.
>
> - `mirror`: The packet is forwarded by the underlying device and a copy is sent to the CPU.

<a id="rst-generic-packet-traps"></a>

## Generic Packet Traps

Generic packet traps are used to describe traps that trap well-defined packets or packets that are trapped due to well-defined conditions (e.g., TTL error). Such traps can be shared by multiple device drivers and their description must be added to the following table:


<table>
<caption>List of Generic Packet Traps</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`source_mac_is_multicast`

</td>
<td>


`drop`

</td>
<td>


Traps incoming packets that the device decided to drop because of a multicast source MAC

</td>
</tr>
<tr>
<td>


`vlan_tag_mismatch`

</td>
<td>


`drop`

</td>
<td>


Traps incoming packets that the device decided to drop in case of VLAN tag mismatch: The ingress bridge port is not configured with a PVID and the packet is untagged or prio-tagged

</td>
</tr>
<tr>
<td>


`ingress_vlan_filter`

</td>
<td>


`drop`

</td>
<td>


Traps incoming packets that the device decided to drop in case they are tagged with a VLAN that is not configured on the ingress bridge port

</td>
</tr>
<tr>
<td>


`ingress_spanning_tree_filter`

</td>
<td>


`drop`

</td>
<td>


Traps incoming packets that the device decided to drop in case the STP state of the ingress bridge port is not "forwarding"

</td>
</tr>
<tr>
<td>


`port_list_is_empty`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop in case they need to be flooded (e.g., unknown unicast, unregistered multicast) and there are no ports the packets should be flooded to

</td>
</tr>
<tr>
<td>


`port_loopback_filter`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop in case after layer 2 forwarding the only port from which they should be transmitted through is the port from which they were received

</td>
</tr>
<tr>
<td>


`blackhole_route`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop in case they hit a blackhole route

</td>
</tr>
<tr>
<td>


`ttl_value_is_too_small`

</td>
<td>


`exception`

</td>
<td>


Traps unicast packets that should be forwarded by the device whose TTL was decremented to 0 or less

</td>
</tr>
<tr>
<td>


`tail_drop`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they could not be enqueued to a transmission queue which is full

</td>
</tr>
<tr>
<td>


`non_ip`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to undergo a layer 3 lookup, but are not IP or MPLS packets

</td>
</tr>
<tr>
<td>


`uc_dip_over_mc_dmac`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and they have a unicast destination IP and a multicast destination MAC

</td>
</tr>
<tr>
<td>


`dip_is_loopback_address`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and their destination IP is the loopback address (i.e., 127.0.0.0/8 and ::1/128)

</td>
</tr>
<tr>
<td>


`sip_is_mc`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and their source IP is multicast (i.e., 224.0.0.0/8 and ff::/8)

</td>
</tr>
<tr>
<td>


`sip_is_loopback_address`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and their source IP is the loopback address (i.e., 127.0.0.0/8 and ::1/128)

</td>
</tr>
<tr>
<td>


`ip_header_corrupted`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and their IP header is corrupted: wrong checksum, wrong IP version or too short Internet Header Length (IHL)

</td>
</tr>
<tr>
<td>


`ipv4_sip_is_limited_bc`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed and their source IP is limited broadcast (i.e., 255.255.255.255/32)

</td>
</tr>
<tr>
<td>


`ipv6_mc_dip_reserved_scope`

</td>
<td>


`drop`

</td>
<td>


Traps IPv6 packets that the device decided to drop because they need to be routed and their IPv6 multicast destination IP has a reserved scope (i.e., ffx0::/16)

</td>
</tr>
<tr>
<td>


`ipv6_mc_dip_interface_local_scope`

</td>
<td>


`drop`

</td>
<td>


Traps IPv6 packets that the device decided to drop because they need to be routed and their IPv6 multicast destination IP has an interface-local scope (i.e., ffx1::/16)

</td>
</tr>
<tr>
<td>


`mtu_value_is_too_small`

</td>
<td>


`exception`

</td>
<td>


Traps packets that should have been routed by the device, but were bigger than the MTU of the egress interface

</td>
</tr>
<tr>
<td>


`unresolved_neigh`

</td>
<td>


`exception`

</td>
<td>


Traps packets that did not have a matching IP neighbour after routing

</td>
</tr>
<tr>
<td>


`mc_reverse_path_forwarding`

</td>
<td>


`exception`

</td>
<td>


Traps multicast IP packets that failed reverse-path forwarding (RPF) check during multicast routing

</td>
</tr>
<tr>
<td>


`reject_route`

</td>
<td>


`exception`

</td>
<td>


Traps packets that hit reject routes (i.e., "unreachable", "prohibit")

</td>
</tr>
<tr>
<td>


`ipv4_lpm_miss`

</td>
<td>


`exception`

</td>
<td>


Traps unicast IPv4 packets that did not match any route

</td>
</tr>
<tr>
<td>


`ipv6_lpm_miss`

</td>
<td>


`exception`

</td>
<td>


Traps unicast IPv6 packets that did not match any route

</td>
</tr>
<tr>
<td>


`non_routable_packet`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they are not supposed to be routed. For example, IGMP queries can be flooded by the device in layer 2 and reach the router. Such packets should not be routed and instead dropped

</td>
</tr>
<tr>
<td>


`decap_error`

</td>
<td>


`exception`

</td>
<td>


Traps NVE and IPinIP packets that the device decided to drop because of failure during decapsulation (e.g., packet being too short, reserved bits set in VXLAN header)

</td>
</tr>
<tr>
<td>


`overlay_smac_is_mc`

</td>
<td>


`drop`

</td>
<td>


Traps NVE packets that the device decided to drop because their overlay source MAC is multicast

</td>
</tr>
<tr>
<td>


`ingress_flow_action_drop`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped during processing of ingress flow action drop

</td>
</tr>
<tr>
<td>


`egress_flow_action_drop`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped during processing of egress flow action drop

</td>
</tr>
<tr>
<td>


`stp`

</td>
<td>


`control`

</td>
<td>


Traps STP packets

</td>
</tr>
<tr>
<td>


`lacp`

</td>
<td>


`control`

</td>
<td>


Traps LACP packets

</td>
</tr>
<tr>
<td>


`lldp`

</td>
<td>


`control`

</td>
<td>


Traps LLDP packets

</td>
</tr>
<tr>
<td>


`igmp_query`

</td>
<td>


`control`

</td>
<td>


Traps IGMP Membership Query packets

</td>
</tr>
<tr>
<td>


`igmp_v1_report`

</td>
<td>


`control`

</td>
<td>


Traps IGMP Version 1 Membership Report packets

</td>
</tr>
<tr>
<td>


`igmp_v2_report`

</td>
<td>


`control`

</td>
<td>


Traps IGMP Version 2 Membership Report packets

</td>
</tr>
<tr>
<td>


`igmp_v3_report`

</td>
<td>


`control`

</td>
<td>


Traps IGMP Version 3 Membership Report packets

</td>
</tr>
<tr>
<td>


`igmp_v2_leave`

</td>
<td>


`control`

</td>
<td>


Traps IGMP Version 2 Leave Group packets

</td>
</tr>
<tr>
<td>


`mld_query`

</td>
<td>


`control`

</td>
<td>


Traps MLD Multicast Listener Query packets

</td>
</tr>
<tr>
<td>


`mld_v1_report`

</td>
<td>


`control`

</td>
<td>


Traps MLD Version 1 Multicast Listener Report packets

</td>
</tr>
<tr>
<td>


`mld_v2_report`

</td>
<td>


`control`

</td>
<td>


Traps MLD Version 2 Multicast Listener Report packets

</td>
</tr>
<tr>
<td>


`mld_v1_done`

</td>
<td>


`control`

</td>
<td>


Traps MLD Version 1 Multicast Listener Done packets

</td>
</tr>
<tr>
<td>


`ipv4_dhcp`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 DHCP packets

</td>
</tr>
<tr>
<td>


`ipv6_dhcp`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 DHCP packets

</td>
</tr>
<tr>
<td>


`arp_request`

</td>
<td>


`control`

</td>
<td>


Traps ARP request packets

</td>
</tr>
<tr>
<td>


`arp_response`

</td>
<td>


`control`

</td>
<td>


Traps ARP response packets

</td>
</tr>
<tr>
<td>


`arp_overlay`

</td>
<td>


`control`

</td>
<td>


Traps NVE-decapsulated ARP packets that reached the overlay network. This is required, for example, when the address that needs to be resolved is a local address

</td>
</tr>
<tr>
<td>


`ipv6_neigh_solicit`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 Neighbour Solicitation packets

</td>
</tr>
<tr>
<td>


`ipv6_neigh_advert`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 Neighbour Advertisement packets

</td>
</tr>
<tr>
<td>


`ipv4_bfd`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 BFD packets

</td>
</tr>
<tr>
<td>


`ipv6_bfd`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 BFD packets

</td>
</tr>
<tr>
<td>


`ipv4_ospf`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 OSPF packets

</td>
</tr>
<tr>
<td>


`ipv6_ospf`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 OSPF packets

</td>
</tr>
<tr>
<td>


`ipv4_bgp`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 BGP packets

</td>
</tr>
<tr>
<td>


`ipv6_bgp`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 BGP packets

</td>
</tr>
<tr>
<td>


`ipv4_vrrp`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 VRRP packets

</td>
</tr>
<tr>
<td>


`ipv6_vrrp`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 VRRP packets

</td>
</tr>
<tr>
<td>


`ipv4_pim`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 PIM packets

</td>
</tr>
<tr>
<td>


`ipv6_pim`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 PIM packets

</td>
</tr>
<tr>
<td>


`uc_loopback`

</td>
<td>


`control`

</td>
<td>


Traps unicast packets that need to be routed through the same layer 3 interface from which they were received. Such packets are routed by the kernel, but also cause it to potentially generate ICMP redirect packets

</td>
</tr>
<tr>
<td>


`local_route`

</td>
<td>


`control`

</td>
<td>


Traps unicast packets that hit a local route and need to be locally delivered

</td>
</tr>
<tr>
<td>


`external_route`

</td>
<td>


`control`

</td>
<td>


Traps packets that should be routed through an external interface (e.g., management interface) that does not belong to the same device (e.g., switch ASIC) as the ingress interface

</td>
</tr>
<tr>
<td>


`ipv6_uc_dip_link_local_scope`

</td>
<td>


`control`

</td>
<td>


Traps unicast IPv6 packets that need to be routed and have a destination IP address with a link-local scope (i.e., fe80::/10). The trap allows device drivers to avoid programming link-local routes, but still receive packets for local delivery

</td>
</tr>
<tr>
<td>


`ipv6_dip_all_nodes`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 packets that their destination IP address is the "All Nodes Address" (i.e., ff02::1)

</td>
</tr>
<tr>
<td>


`ipv6_dip_all_routers`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 packets that their destination IP address is the "All Routers Address" (i.e., ff02::2)

</td>
</tr>
<tr>
<td>


`ipv6_router_solicit`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 Router Solicitation packets

</td>
</tr>
<tr>
<td>


`ipv6_router_advert`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 Router Advertisement packets

</td>
</tr>
<tr>
<td>


`ipv6_redirect`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 Redirect Message packets

</td>
</tr>
<tr>
<td>


`ipv4_router_alert`

</td>
<td>


`control`

</td>
<td>


Traps IPv4 packets that need to be routed and include the Router Alert option. Such packets need to be locally delivered to raw sockets that have the IP_ROUTER_ALERT socket option set

</td>
</tr>
<tr>
<td>


`ipv6_router_alert`

</td>
<td>


`control`

</td>
<td>


Traps IPv6 packets that need to be routed and include the Router Alert option in their Hop-by-Hop extension header. Such packets need to be locally delivered to raw sockets that have the IPV6_ROUTER_ALERT socket option set

</td>
</tr>
<tr>
<td>


`ptp_event`

</td>
<td>


`control`

</td>
<td>


Traps PTP time-critical event messages (Sync, Delay_req, Pdelay_Req and Pdelay_Resp)

</td>
</tr>
<tr>
<td>


`ptp_general`

</td>
<td>


`control`

</td>
<td>


Traps PTP general messages (Announce, Follow_Up, Delay_Resp, Pdelay_Resp_Follow_Up, management and signaling)

</td>
</tr>
<tr>
<td>


`flow_action_sample`

</td>
<td>


`control`

</td>
<td>


Traps packets sampled during processing of flow action sample (e.g., via tc's sample action)

</td>
</tr>
<tr>
<td>


`flow_action_trap`

</td>
<td>


`control`

</td>
<td>


Traps packets logged during processing of flow action trap (e.g., via tc's trap action)

</td>
</tr>
<tr>
<td>


`early_drop`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to the RED (Random Early Detection) algorithm (i.e., early drops)

</td>
</tr>
<tr>
<td>


`vxlan_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the VXLAN header parsing which might be because of packet truncation or the I flag is not set.

</td>
</tr>
<tr>
<td>


`llc_snap_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the LLC+SNAP header parsing

</td>
</tr>
<tr>
<td>


`vlan_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the VLAN header parsing. Could include unexpected packet truncation.

</td>
</tr>
<tr>
<td>


`pppoe_ppp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the PPPoE+PPP header parsing. This could include finding a session ID of 0xFFFF (which is reserved and not for use), a PPPoE length which is larger than the frame received or any common error on this type of header

</td>
</tr>
<tr>
<td>


`mpls_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the MPLS header parsing which could include unexpected header truncation

</td>
</tr>
<tr>
<td>


`arp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the ARP header parsing

</td>
</tr>
<tr>
<td>


`ip_1_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the first IP header parsing. This packet trap could include packets which do not pass an IP checksum check, a header length check (a minimum of 20 bytes), which might suffer from packet truncation thus the total length field exceeds the received packet length etc

</td>
</tr>
<tr>
<td>


`ip_n_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the parsing of the last IP header (the inner one in case of an IP over IP tunnel). The same common error checking is performed here as for the ip_1_parsing trap

</td>
</tr>
<tr>
<td>


`gre_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the GRE header parsing

</td>
</tr>
<tr>
<td>


`udp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the UDP header parsing. This packet trap could include checksum errors, an improper UDP length detected (smaller than 8 bytes) or detection of header truncation.

</td>
</tr>
<tr>
<td>


`tcp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the TCP header parsing. This could include TCP checksum errors, improper combination of SYN, FIN and/or RESET etc.

</td>
</tr>
<tr>
<td>


`ipsec_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the IPSEC header parsing

</td>
</tr>
<tr>
<td>


`sctp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the SCTP header parsing. This would mean that port number 0 was used or that the header is truncated.

</td>
</tr>
<tr>
<td>


`dccp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the DCCP header parsing

</td>
</tr>
<tr>
<td>


`gtp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the GTP header parsing

</td>
</tr>
<tr>
<td>


`esp_parsing`

</td>
<td>


`drop`

</td>
<td>


Traps packets dropped due to an error in the ESP header parsing

</td>
</tr>
<tr>
<td>


`blackhole_nexthop`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop in case they hit a blackhole nexthop

</td>
</tr>
<tr>
<td>


`dmac_filter`

</td>
<td>


`drop`

</td>
<td>


Traps incoming packets that the device decided to drop because the destination MAC is not configured in the MAC table and the interface is not in promiscuous mode

</td>
</tr>
<tr>
<td>


`eapol`

</td>
<td>


`control`

</td>
<td>


Traps "Extensible Authentication Protocol over LAN" (EAPOL) packets specified in IEEE 802.1X

</td>
</tr>
<tr>
<td>


`locked_port`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they failed the locked bridge port check. That is, packets that were received via a locked port and whose \{SMAC, VID\} does not correspond to an FDB entry pointing to the port

</td>
</tr>
</tbody>
</table>

<a id="rst-driver-specific-packet-traps"></a>

## Driver-specific Packet Traps

Device drivers can register driver-specific packet traps, but these must be clearly documented. Such traps can correspond to device-specific exceptions and help debug packet drops caused by these exceptions. The following list includes links to the description of driver-specific traps registered by various device drivers:

> - [Documentation/networking/devlink/netdevsim.rst](/kernel/internals/networking/devlink/netdevsim.md)
>
> - [Documentation/networking/devlink/mlxsw.rst](/kernel/internals/networking/devlink/mlxsw.md)
>
> - [Documentation/networking/devlink/prestera.rst](/kernel/internals/networking/devlink/prestera.md)

<a id="rst-generic-packet-trap-groups-1"></a>
<a id="rst-generic-packet-trap-groups"></a>

## Generic Packet Trap Groups

Generic packet trap groups are used to aggregate logically related packet traps. These groups allow the user to batch operations such as setting the trap action of all member traps. In addition, `devlink-trap` can report aggregated per-group packets and bytes statistics, in case per-trap statistics are too narrow. The description of these groups must be added to the following table:


<table>
<caption>List of Generic Packet Trap Groups</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`l2_drops`

</td>
<td>


Contains packet traps for packets that were dropped by the device during layer 2 forwarding (i.e., bridge)

</td>
</tr>
<tr>
<td>


`l3_drops`

</td>
<td>


Contains packet traps for packets that were dropped by the device during layer 3 forwarding

</td>
</tr>
<tr>
<td>


`l3_exceptions`

</td>
<td>


Contains packet traps for packets that hit an exception (e.g., TTL error) during layer 3 forwarding

</td>
</tr>
<tr>
<td>


`buffer_drops`

</td>
<td>


Contains packet traps for packets that were dropped by the device due to an enqueue decision

</td>
</tr>
<tr>
<td>


`tunnel_drops`

</td>
<td>


Contains packet traps for packets that were dropped by the device during tunnel encapsulation / decapsulation

</td>
</tr>
<tr>
<td>


`acl_drops`

</td>
<td>


Contains packet traps for packets that were dropped by the device during ACL processing

</td>
</tr>
<tr>
<td>


`stp`

</td>
<td>


Contains packet traps for STP packets

</td>
</tr>
<tr>
<td>


`lacp`

</td>
<td>


Contains packet traps for LACP packets

</td>
</tr>
<tr>
<td>


`lldp`

</td>
<td>


Contains packet traps for LLDP packets

</td>
</tr>
<tr>
<td>


`mc_snooping`

</td>
<td>


Contains packet traps for IGMP and MLD packets required for multicast snooping

</td>
</tr>
<tr>
<td>


`dhcp`

</td>
<td>


Contains packet traps for DHCP packets

</td>
</tr>
<tr>
<td>


`neigh_discovery`

</td>
<td>


Contains packet traps for neighbour discovery packets (e.g., ARP, IPv6 ND)

</td>
</tr>
<tr>
<td>


`bfd`

</td>
<td>


Contains packet traps for BFD packets

</td>
</tr>
<tr>
<td>


`ospf`

</td>
<td>


Contains packet traps for OSPF packets

</td>
</tr>
<tr>
<td>


`bgp`

</td>
<td>


Contains packet traps for BGP packets

</td>
</tr>
<tr>
<td>


`vrrp`

</td>
<td>


Contains packet traps for VRRP packets

</td>
</tr>
<tr>
<td>


`pim`

</td>
<td>


Contains packet traps for PIM packets

</td>
</tr>
<tr>
<td>


`uc_loopback`

</td>
<td>


Contains a packet trap for unicast loopback packets (i.e., `uc_loopback`). This trap is singled-out because in cases such as one-armed router it will be constantly triggered. To limit the impact on the CPU usage, a packet trap policer with a low rate can be bound to the group without affecting other traps

</td>
</tr>
<tr>
<td>


`local_delivery`

</td>
<td>


Contains packet traps for packets that should be locally delivered after routing, but do not match more specific packet traps (e.g., `ipv4_bgp`)

</td>
</tr>
<tr>
<td>


`external_delivery`

</td>
<td>


Contains packet traps for packets that should be routed through an external interface (e.g., management interface) that does not belong to the same device (e.g., switch ASIC) as the ingress interface

</td>
</tr>
<tr>
<td>


`ipv6`

</td>
<td>


Contains packet traps for various IPv6 control packets (e.g., Router Advertisements)

</td>
</tr>
<tr>
<td>


`ptp_event`

</td>
<td>


Contains packet traps for PTP time-critical event messages (Sync, Delay_req, Pdelay_Req and Pdelay_Resp)

</td>
</tr>
<tr>
<td>


`ptp_general`

</td>
<td>


Contains packet traps for PTP general messages (Announce, Follow_Up, Delay_Resp, Pdelay_Resp_Follow_Up, management and signaling)

</td>
</tr>
<tr>
<td>


`acl_sample`

</td>
<td>


Contains packet traps for packets that were sampled by the device during ACL processing

</td>
</tr>
<tr>
<td>


`acl_trap`

</td>
<td>


Contains packet traps for packets that were trapped (logged) by the device during ACL processing

</td>
</tr>
<tr>
<td>


`parser_error_drops`

</td>
<td>


Contains packet traps for packets that were marked by the device during parsing as erroneous

</td>
</tr>
<tr>
<td>


`eapol`

</td>
<td>


Contains packet traps for "Extensible Authentication Protocol over LAN" (EAPOL) packets specified in IEEE 802.1X

</td>
</tr>
</tbody>
</table>

<a id="rst-packet-trap-policers"></a>

## Packet Trap Policers

As previously explained, the underlying device can trap certain packets to the CPU for processing. In most cases, the underlying device is capable of handling packet rates that are several orders of magnitude higher compared to those that can be handled by the CPU.

Therefore, in order to prevent the underlying device from overwhelming the CPU, devices usually include packet trap policers that are able to police the trapped packets to rates that can be handled by the CPU.

The `devlink-trap` mechanism allows capable device drivers to register their supported packet trap policers with `devlink`. The device driver can choose to associate these policers with supported packet trap groups (see [Generic Packet Trap Groups](<#rst-generic-packet-trap-groups>)) during its initialization, thereby exposing its default control plane policy to user space.

Device drivers should allow user space to change the parameters of the policers (e.g., rate, burst size) as well as the association between the policers and trap groups by implementing the relevant callbacks.

If possible, device drivers should implement a callback that allows user space to retrieve the number of packets that were dropped by the policer because its configured policy was violated.

<a id="rst-testing"></a>

## Testing

See `tools/testing/selftests/drivers/net/netdevsim/devlink_trap.sh` for a test covering the core infrastructure. Test cases should be added for any new functionality.

Device drivers should focus their tests on device-specific functionality, such as the triggering of supported packet traps.

---

# etas_es58x devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the etas_es58x device driver.

<a id="rst-etas-es58x-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `etas_es58x` device driver.

<a id="rst-info-versions"></a>

## Info versions

The `etas_es58x` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Version of the firmware running on the device. Also available through `ethtool -i` as the first member of the `firmware-version`.

</td>
</tr>
<tr>
<td>


`fw.bootloader`

</td>
<td>


running

</td>
<td>


Version of the bootloader running on the device. Also available through `ethtool -i` as the second member of the `firmware-version`.

</td>
</tr>
<tr>
<td>


`board.rev`

</td>
<td>


fixed

</td>
<td>


The hardware revision of the device.

</td>
</tr>
<tr>
<td>


`serial_number`

</td>
<td>


fixed

</td>
<td>


The USB serial number. Also available through `lsusb -v`.

</td>
</tr>
</tbody>
</table>

---

# hns3 devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the hns3 device driver.

<a id="rst-hns3-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `hns3` device driver.

The `hns3` driver supports reloading via `DEVLINK_CMD_RELOAD`.

<a id="rst-info-versions"></a>

## Info versions

The `hns3` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Used to represent the firmware version.

</td>
</tr>
<tr>
<td>


`fw.scc`

</td>
<td>


running

</td>
<td>


Used to represent the Soft Congestion Control (SSC) firmware version. SCC is a firmware component which provides multiple RDMA congestion control algorithms, including DCQCN.

</td>
</tr>
</tbody>
</table>

---

# i40e devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the i40e device driver.

<a id="rst-i40e-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `i40e` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Notes

</td>
</tr>
<tr>
<td>


`max_mac_per_vf`

</td>
<td>


runtime

</td>
<td>


Controls the maximum number of MAC addresses a VF can use on i40e devices.

By default (`0`), the driver enforces its internally calculated per-VF MAC filter limit, which is based on the number of allocated VFS.

If set to a non-zero value, this parameter acts as a strict cap: the driver will use the user-provided value instead of its internal calculation.

**Important notes:**

- This value **must be set before enabling SR-IOV**. Attempting to change it while SR-IOV is enabled will return an error.

- MAC filters are a **shared hardware resource** across all VFs. Setting a high value may cause other VFs to be starved of filters.

- This value is a **Administrative policy**. The hardware may return errors when its absolute limit is reached, regardless of the value set here.

The default value is `0` (internal calculation is used).

</td>
</tr>
</tbody>
</table>

<a id="rst-info-versions"></a>

## Info versions

The `i40e` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Example

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


K15190-000

</td>
<td>


The Product Board Assembly (PBA) identifier of the board.

</td>
</tr>
<tr>
<td>


`fw.mgmt`

</td>
<td>


running

</td>
<td>


9.130

</td>
<td>


2-digit version number of the management firmware that controls the PHY, link, etc.

</td>
</tr>
<tr>
<td>


`fw.mgmt.api`

</td>
<td>


running

</td>
<td>


1.15

</td>
<td>


2-digit version number of the API exported over the AdminQ by the management firmware. Used by the driver to identify what commands are supported.

</td>
</tr>
<tr>
<td>


`fw.mgmt.build`

</td>
<td>


running

</td>
<td>


73618

</td>
<td>


Build number of the source for the management firmware.

</td>
</tr>
<tr>
<td>


`fw.undi`

</td>
<td>


running

</td>
<td>


1.3429.0

</td>
<td>


Version of the Option ROM containing the UEFI driver. The version is reported in `major.minor.patch` format. The major version is incremented whenever a major breaking change occurs, or when the minor version would overflow. The minor version is incremented for non-breaking changes and reset to 1 when the major version is incremented. The patch version is normally 0 but is incremented when a fix is delivered as a patch against an older base Option ROM.

</td>
</tr>
<tr>
<td>


`fw.psid.api`

</td>
<td>


running

</td>
<td>


9.30

</td>
<td>


Version defining the format of the flash contents.

</td>
</tr>
<tr>
<td>


`fw.bundle_id`

</td>
<td>


running

</td>
<td>


0x8000e5f3

</td>
<td>


Unique identifier of the firmware image file that was loaded onto the device. Also referred to as the EETRACK identifier of the NVM.

</td>
</tr>
</tbody>
</table>

---

# ice devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the ice device driver.

<a id="rst-ice-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `ice` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Notes

</td>
</tr>
<tr>
<td>


`enable_roce`

</td>
<td>


runtime

</td>
<td>


mutually exclusive with `enable_iwarp`

</td>
</tr>
<tr>
<td>


`enable_iwarp`

</td>
<td>


runtime

</td>
<td>


mutually exclusive with `enable_roce`

</td>
</tr>
<tr>
<td>


`tx_scheduling_layers`

</td>
<td>


permanent

</td>
<td>


The ice hardware uses hierarchical scheduling for Tx with a fixed number of layers in the scheduling tree. Each of them are decision points. Root node represents a port, while all the leaves represent the queues. This way of configuring the Tx scheduler allows features like DCB or devlink-rate (documented below) to configure how much bandwidth is given to any given queue or group of queues, enabling fine-grained control because scheduling parameters can be configured at any given layer of the tree.

The default 9-layer tree topology was deemed best for most workloads, as it gives an optimal ratio of performance to configurability. However, for some specific cases, this 9-layer topology might not be desired. One example would be sending traffic to queues that are not a multiple of 8. Because the maximum radix is limited to 8 in 9-layer topology, the 9th queue has a different parent than the rest, and it's given more bandwidth credits. This causes a problem when the system is sending traffic to 9 queues:

tx_queue_0_packets: 24163396  
tx_queue_1_packets: 24164623  
tx_queue_2_packets: 24163188  
tx_queue_3_packets: 24163701  
tx_queue_4_packets: 24163683  
tx_queue_5_packets: 24164668  
tx_queue_6_packets: 23327200  
tx_queue_7_packets: 24163853  
tx_queue_8_packets: 91101417 &lt; Too much traffic is sent from 9th

To address this need, you can switch to a 5-layer topology, which changes the maximum topology radix to 512. With this enhancement, the performance characteristic is equal as all queues can be assigned to the same parent in the tree. The obvious drawback of this solution is a lower configuration depth of the tree.

Use the `tx_scheduling_layer` parameter with the devlink command to change the transmit scheduler topology. To use 5-layer topology, use a value of 5. For example: $ devlink dev param set pci/0000:16:00.0 name tx_scheduling_layers value 5 cmode permanent Use a value of 9 to set it back to the default value.

You must do PCI slot powercycle for the selected topology to take effect.

To verify that value has been set: $ devlink dev param show pci/0000:16:00.0 name tx_scheduling_layers

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_max`

</td>
<td>


driverinit

</td>
<td>


Set the max MSI-X that can be used by the PF, rest can be utilized for SRIOV. The range is from min value set in msix_vec_per_pf_min to 2k/number of ports.

</td>
</tr>
<tr>
<td>


`msix_vec_per_pf_min`

</td>
<td>


driverinit

</td>
<td>


Set the min MSI-X that will be used by the PF. This value inform how many MSI-X will be allocated statically. The range is from 2 to value set in msix_vec_per_pf_max.

</td>
</tr>
</tbody>
</table>


<table>
<caption>Driver specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`local_forwarding`

</td>
<td>


runtime

</td>
<td>


Controls loopback behavior by tuning scheduler bandwidth. It impacts all kinds of functions: physical, virtual and subfunctions. Supported values are:

`enabled` - loopback traffic is allowed on port

`disabled` - loopback traffic is not allowed on this port

`prioritized` - loopback traffic is prioritized on this port

Default value of `local_forwarding` parameter is `enabled`. `prioritized` provides ability to adjust loopback traffic rate to increase one port capacity at cost of the another. User needs to disable local forwarding on one of the ports in order have increased capacity on the `prioritized` port.

</td>
</tr>
</tbody>
</table>

<a id="rst-info-versions"></a>

## Info versions

The `ice` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Example

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


K65390-000

</td>
<td>


The Product Board Assembly (PBA) identifier of the board.

</td>
</tr>
<tr>
<td>


`cgu.id`

</td>
<td>


fixed

</td>
<td>


36

</td>
<td>


The Clock Generation Unit (CGU) hardware revision identifier.

</td>
</tr>
<tr>
<td>


`fw.mgmt`

</td>
<td>


running

</td>
<td>


2.1.7

</td>
<td>


3-digit version number of the management firmware running on the Embedded Management Processor of the device. It controls the PHY, link, access to device resources, etc. Intel documentation refers to this as the EMP firmware.

</td>
</tr>
<tr>
<td>


`fw.mgmt.api`

</td>
<td>


running

</td>
<td>


1.5.1

</td>
<td>


3-digit version number (major.minor.patch) of the API exported over the AdminQ by the management firmware. Used by the driver to identify what commands are supported. Historical versions of the kernel only displayed a 2-digit version number (major.minor).

</td>
</tr>
<tr>
<td>


`fw.mgmt.build`

</td>
<td>


running

</td>
<td>


0x305d955f

</td>
<td>


Unique identifier of the source for the management firmware.

</td>
</tr>
<tr>
<td>


`fw.undi`

</td>
<td>


running

</td>
<td>


1.2581.0

</td>
<td>


Version of the Option ROM containing the UEFI driver. The version is reported in `major.minor.patch` format. The major version is incremented whenever a major breaking change occurs, or when the minor version would overflow. The minor version is incremented for non-breaking changes and reset to 1 when the major version is incremented. The patch version is normally 0 but is incremented when a fix is delivered as a patch against an older base Option ROM.

</td>
</tr>
<tr>
<td>


`fw.psid.api`

</td>
<td>


running

</td>
<td>


0.80

</td>
<td>


Version defining the format of the flash contents.

</td>
</tr>
<tr>
<td>


`fw.bundle_id`

</td>
<td>


running

</td>
<td>


0x80002ec0

</td>
<td>


Unique identifier of the firmware image file that was loaded onto the device. Also referred to as the EETRACK identifier of the NVM.

</td>
</tr>
<tr>
<td>


`fw.app.name`

</td>
<td>


running

</td>
<td>


ICE OS Default Package

</td>
<td>


The name of the DDP package that is active in the device. The DDP package is loaded by the driver during initialization. Each variation of the DDP package has a unique name.

</td>
</tr>
<tr>
<td>


`fw.app`

</td>
<td>


running

</td>
<td>


1.3.1.0

</td>
<td>


The version of the DDP package that is active in the device. Note that both the name (as reported by `fw.app.name`) and version are required to uniquely identify the package.

</td>
</tr>
<tr>
<td>


`fw.app.bundle_id`

</td>
<td>


running

</td>
<td>


0xc0000001

</td>
<td>


Unique identifier for the DDP package loaded in the device. Also referred to as the DDP Track ID. Can be used to uniquely identify the specific DDP package.

</td>
</tr>
<tr>
<td>


`fw.netlist`

</td>
<td>


running

</td>
<td>


1.1.2000-6.7.0

</td>
<td>


The version of the netlist module. This module defines the device's Ethernet capabilities and default settings, and is used by the management firmware as part of managing link and device connectivity.

</td>
</tr>
<tr>
<td>


`fw.netlist.build`

</td>
<td>


running

</td>
<td>


0xee16ced7

</td>
<td>


The first 4 bytes of the hash of the netlist module contents.

</td>
</tr>
<tr>
<td>


`fw.cgu`

</td>
<td>


running

</td>
<td>


8032.16973825.6021

</td>
<td>


The version of Clock Generation Unit (CGU). Format: &lt;CGU type&gt;.&lt;configuration version&gt;.&lt;firmware version&gt;.

</td>
</tr>
</tbody>
</table>

<a id="rst-flash-update"></a>

## Flash Update

The `ice` driver implements support for flash update using the `devlink-flash` interface. It supports updating the device flash using a combined flash image that contains the `fw.mgmt`, `fw.undi`, and `fw.netlist` components.


<table>
<caption>List of supported overwrite modes</caption>
<tbody>
<tr>
<td>


Bits

</td>
<td>


Behavior

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_SETTINGS`

</td>
<td>


Do not preserve settings stored in the flash components being updated. This includes overwriting the port configuration that determines the number of physical functions the device will initialize with.

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_SETTINGS` and `DEVLINK_FLASH_OVERWRITE_IDENTIFIERS`

</td>
<td>


Do not preserve either settings or identifiers. Overwrite everything in the flash with the contents from the provided image, without performing any preservation. This includes overwriting device identifying fields such as the MAC address, VPD area, and device serial number. It is expected that this combination be used with an image customized for the specific device.

</td>
</tr>
</tbody>
</table>

The ice hardware does not support overwriting only identifiers while preserving settings, and thus `DEVLINK_FLASH_OVERWRITE_IDENTIFIERS` on its own will be rejected. If no overwrite mask is provided, the firmware will be instructed to preserve all settings and identifying fields when updating.

<a id="rst-reload"></a>

## Reload

The `ice` driver supports activating new firmware after a flash update using `DEVLINK_CMD_RELOAD` with the `DEVLINK_RELOAD_ACTION_FW_ACTIVATE` action.



```shell
$ devlink dev reload pci/0000:01:00.0 reload action fw_activate
```

The new firmware is activated by issuing a device specific Embedded Management Processor reset which requests the device to reset and reload the EMP firmware image.

The driver does not currently support reloading the driver via `DEVLINK_RELOAD_ACTION_DRIVER_REINIT`.

<a id="rst-port-split"></a>

## Port split

The `ice` driver supports port splitting only for port 0, as the FW has a predefined set of available port split options for the whole device.

A system reboot is required for port split to be applied.

The following command will select the port split option with 4 ports:



```shell
$ devlink port split pci/0000:16:00.0/0 count 4
```

The list of all available port options will be printed to dynamic debug after each `split` and `unsplit` command. The first option is the default.



```shell
ice 0000:16:00.0: Available port split options and max port speeds (Gbps):
ice 0000:16:00.0: Status  Split      Quad 0          Quad 1
ice 0000:16:00.0:         count  L0  L1  L2  L3  L4  L5  L6  L7
ice 0000:16:00.0: Active  2     100   -   -   - 100   -   -   -
ice 0000:16:00.0:         2      50   -  50   -   -   -   -   -
ice 0000:16:00.0: Pending 4      25  25  25  25   -   -   -   -
ice 0000:16:00.0:         4      25  25   -   -  25  25   -   -
ice 0000:16:00.0:         8      10  10  10  10  10  10  10  10
ice 0000:16:00.0:         1     100   -   -   -   -   -   -   -
```

There could be multiple FW port options with the same port split count. When the same port split count request is issued again, the next FW port option with the same port split count will be selected.

`devlink port unsplit` will select the option with a split count of 1. If there is no FW option available with split count 1, you will receive an error.

<a id="rst-regions"></a>

## Regions

The `ice` driver implements the following regions for accessing internal device data.


<table>
<caption>regions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`nvm-flash`

</td>
<td>


The contents of the entire flash chip, sometimes referred to as the device's Non Volatile Memory.

</td>
</tr>
<tr>
<td>


`shadow-ram`

</td>
<td>


The contents of the Shadow RAM, which is loaded from the beginning of the flash. Although the contents are primarily from the flash, this area also contains data generated during device boot which is not stored in flash.

</td>
</tr>
<tr>
<td>


`device-caps`

</td>
<td>


The contents of the device firmware's capabilities buffer. Useful to determine the current state and configuration of the device.

</td>
</tr>
</tbody>
</table>

Both the `nvm-flash` and `shadow-ram` regions can be accessed without a snapshot. The `device-caps` region requires a snapshot as the contents are sent by firmware and can't be split into separate reads.

Users can request an immediate capture of a snapshot for all three regions via the `DEVLINK_CMD_REGION_NEW` command.



```shell
$ devlink region show
pci/0000:01:00.0/nvm-flash: size 10485760 snapshot [] max 1
pci/0000:01:00.0/device-caps: size 4096 snapshot [] max 10

$ devlink region new pci/0000:01:00.0/nvm-flash snapshot 1
$ devlink region dump pci/0000:01:00.0/nvm-flash snapshot 1

$ devlink region dump pci/0000:01:00.0/nvm-flash snapshot 1
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30
0000000000000010 0000 0000 ffff ff04 0029 8c00 0028 8cc8
0000000000000020 0016 0bb8 0016 1720 0000 0000 c00f 3ffc
0000000000000030 bada cce5 bada cce5 bada cce5 bada cce5

$ devlink region read pci/0000:01:00.0/nvm-flash snapshot 1 address 0 length 16
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30

$ devlink region delete pci/0000:01:00.0/nvm-flash snapshot 1

$ devlink region new pci/0000:01:00.0/device-caps snapshot 1
$ devlink region dump pci/0000:01:00.0/device-caps snapshot 1
0000000000000000 01 00 01 00 00 00 00 00 01 00 00 00 00 00 00 00
0000000000000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000020 02 00 02 01 32 03 00 00 0a 00 00 00 25 00 00 00
0000000000000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000040 04 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
0000000000000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000060 05 00 01 00 03 00 00 00 00 00 00 00 00 00 00 00
0000000000000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000080 06 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
0000000000000090 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000000a0 08 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000000b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000000c0 12 00 01 00 01 00 00 00 01 00 01 00 00 00 00 00
00000000000000d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000000e0 13 00 01 00 00 01 00 00 00 00 00 00 00 00 00 00
00000000000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000100 14 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
0000000000000110 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000120 15 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
0000000000000130 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000140 16 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
0000000000000150 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000160 17 00 01 00 06 00 00 00 00 00 00 00 00 00 00 00
0000000000000170 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000180 18 00 01 00 01 00 00 00 01 00 00 00 08 00 00 00
0000000000000190 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000001a0 22 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00
00000000000001b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000001c0 40 00 01 00 00 08 00 00 08 00 00 00 00 00 00 00
00000000000001d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000000000001e0 41 00 01 00 00 08 00 00 00 00 00 00 00 00 00 00
00000000000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0000000000000200 42 00 01 00 00 08 00 00 00 00 00 00 00 00 00 00
0000000000000210 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

$ devlink region delete pci/0000:01:00.0/device-caps snapshot 1
```

<a id="rst-devlink-rate"></a>

## Devlink Rate

The `ice` driver implements devlink-rate API. It allows for offload of the Hierarchical QoS to the hardware. It enables user to group Virtual Functions in a tree structure and assign supported parameters: tx_share, tx_max, tx_priority and tx_weight to each node in a tree. So effectively user gains an ability to control how much bandwidth is allocated for each VF group. This is later enforced by the HW.

It is assumed that this feature is mutually exclusive with DCB performed in FW and ADQ, or any driver feature that would trigger changes in QoS, for example creation of the new traffic class. The driver will prevent DCB or ADQ configuration if user started making any changes to the nodes using devlink-rate API. To configure those features a driver reload is necessary. Correspondingly if ADQ or DCB will get configured the driver won't export hierarchy at all, or will remove the untouched hierarchy if those features are enabled after the hierarchy is exported, but before any changes are made.

This feature is also dependent on switchdev being enabled in the system. It's required because devlink-rate requires devlink-port objects to be present, and those objects are only created in switchdev mode.

If the driver is set to the switchdev mode, it will export internal hierarchy the moment VF's are created. Root of the tree is always represented by the node_0. This node can't be deleted by the user. Leaf nodes and nodes with children also can't be deleted.


<table>
<caption>Attributes supported</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`tx_max`

</td>
<td>


maximum bandwidth to be consumed by the tree Node. Rate Limit is an absolute number specifying a maximum amount of bytes a Node may consume during the course of one second. Rate limit guarantees that a link will not oversaturate the receiver on the remote end and also enforces an SLA between the subscriber and network provider.

</td>
</tr>
<tr>
<td>


`tx_share`

</td>
<td>


minimum bandwidth allocated to a tree node when it is not blocked. It specifies an absolute BW. While tx_max defines the maximum bandwidth the node may consume, the tx_share marks committed BW for the Node.

</td>
</tr>
<tr>
<td>


`tx_priority`

</td>
<td>


allows for usage of strict priority arbiter among siblings. This arbitration scheme attempts to schedule nodes based on their priority as long as the nodes remain within their bandwidth limit. Range 0-7. Nodes with priority 7 have the highest priority and are selected first, while nodes with priority 0 have the lowest priority. Nodes that have the same priority are treated equally.

</td>
</tr>
<tr>
<td>


`tx_weight`

</td>
<td>


allows for usage of Weighted Fair Queuing arbitration scheme among siblings. This arbitration scheme can be used simultaneously with the strict priority. Range 1-200. Only relative values matter for arbitration.

</td>
</tr>
</tbody>
</table>

`tx_priority` and `tx_weight` can be used simultaneously. In that case nodes with the same priority form a WFQ subgroup in the sibling group and arbitration among them is based on assigned weights.



```shell
# enable switchdev
$ devlink dev eswitch set pci/0000:4b:00.0 mode switchdev

# at this point driver should export internal hierarchy
$ echo 2 > /sys/class/net/ens785np0/device/sriov_numvfs

$ devlink port function rate show
pci/0000:4b:00.0/node_25: type node parent node_24
pci/0000:4b:00.0/node_24: type node parent node_0
pci/0000:4b:00.0/node_32: type node parent node_31
pci/0000:4b:00.0/node_31: type node parent node_30
pci/0000:4b:00.0/node_30: type node parent node_16
pci/0000:4b:00.0/node_19: type node parent node_18
pci/0000:4b:00.0/node_18: type node parent node_17
pci/0000:4b:00.0/node_17: type node parent node_16
pci/0000:4b:00.0/node_14: type node parent node_5
pci/0000:4b:00.0/node_5: type node parent node_3
pci/0000:4b:00.0/node_13: type node parent node_4
pci/0000:4b:00.0/node_12: type node parent node_4
pci/0000:4b:00.0/node_11: type node parent node_4
pci/0000:4b:00.0/node_10: type node parent node_4
pci/0000:4b:00.0/node_9: type node parent node_4
pci/0000:4b:00.0/node_8: type node parent node_4
pci/0000:4b:00.0/node_7: type node parent node_4
pci/0000:4b:00.0/node_6: type node parent node_4
pci/0000:4b:00.0/node_4: type node parent node_3
pci/0000:4b:00.0/node_3: type node parent node_16
pci/0000:4b:00.0/node_16: type node parent node_15
pci/0000:4b:00.0/node_15: type node parent node_0
pci/0000:4b:00.0/node_2: type node parent node_1
pci/0000:4b:00.0/node_1: type node parent node_0
pci/0000:4b:00.0/node_0: type node
pci/0000:4b:00.0/1: type leaf parent node_25
pci/0000:4b:00.0/2: type leaf parent node_25

# let's create some custom node
$ devlink port function rate add pci/0000:4b:00.0/node_custom parent node_0

# second custom node
$ devlink port function rate add pci/0000:4b:00.0/node_custom_1 parent node_custom

# reassign second VF to newly created branch
$ devlink port function rate set pci/0000:4b:00.0/2 parent node_custom_1

# assign tx_weight to the VF
$ devlink port function rate set pci/0000:4b:00.0/2 tx_weight 5

# assign tx_share to the VF
$ devlink port function rate set pci/0000:4b:00.0/2 tx_share 500Mbps
```

---

# ionic devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the ionic device driver.

<a id="rst-ionic-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `ionic` device driver.

<a id="rst-info-versions"></a>

## Info versions

The `ionic` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Version of firmware running on the device

</td>
</tr>
<tr>
<td>


`asic.id`

</td>
<td>


fixed

</td>
<td>


The ASIC type for this device

</td>
</tr>
<tr>
<td>


`asic.rev`

</td>
<td>


fixed

</td>
<td>


The revision of the ASIC for this device

</td>
</tr>
</tbody>
</table>

---

# iosm devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the iosm device driver.

<a id="rst-iosm-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `iosm` device driver.

<a id="rst-parameters"></a>

## Parameters

The `iosm` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`erase_full_flash`

</td>
<td>


u8

</td>
<td>


runtime

</td>
<td>


erase\_full\_flash parameter is used to check if full erase is required for the device during firmware flashing. If set, Full nand erase command will be sent to the device. By default, only conditional erase support is enabled.

</td>
</tr>
</tbody>
</table>

<a id="rst-flash-update"></a>

## Flash Update

The `iosm` driver implements support for flash update using the `devlink-flash` interface.

It supports updating the device flash using a combined flash image which contains the Bootloader images and other modem software images.

The driver uses DEVLINK\_SUPPORT\_FLASH\_UPDATE\_COMPONENT to identify type of firmware image that need to be flashed as requested by user space application. Supported firmware image types.


<table>
<caption>Firmware Image types</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`PSI RAM`

</td>
<td>


Primary Signed Image

</td>
</tr>
<tr>
<td>


`EBL`

</td>
<td>


External Bootloader

</td>
</tr>
<tr>
<td>


`FLS`

</td>
<td>


Modem Software Image

</td>
</tr>
</tbody>
</table>

PSI RAM and EBL are the RAM images which are injected to the device when the device is in BOOT ROM stage. Once this is successful, the actual modem firmware image is flashed to the device. The modem software image contains multiple files each having one secure bin file and at least one Loadmap/Region file. For flashing these files, appropriate commands are sent to the modem device along with the data required for flashing. The data like region count and address of each region has to be passed to the driver using the devlink param command.

If the device has to be fully erased before firmware flashing, user application need to set the erase\_full\_flash parameter using devlink param command. By default, conditional erase feature is supported.

<a id="rst-flash-commands"></a>

## Flash Commands:

1\) When modem is in Boot ROM stage, user can use below command to inject PSI RAM image using devlink flash command.

$ devlink dev flash pci/0000:02:00.0 file &lt;PSI\_RAM\_File\_name&gt;

2\) If user want to do a full erase, below command need to be issued to set the erase full flash param (To be set only if full erase required).

$ devlink dev param set pci/0000:02:00.0 name erase\_full\_flash value true cmode runtime

3. Inject EBL after the modem is in PSI stage.

$ devlink dev flash pci/0000:02:00.0 file &lt;EBL\_File\_name&gt;

4\) Once EBL is injected successfully, then the actual firmware flashing takes place. Below is the sequence of commands used for each of the firmware images.

- **a)** Flash secure bin file.

$ devlink dev flash pci/0000:02:00.0 file &lt;Secure\_bin\_file\_name&gt;

- **b)** Flashing the Loadmap/Region file

$ devlink dev flash pci/0000:02:00.0 file &lt;Load\_map\_file\_name&gt;

<a id="rst-regions"></a>

## Regions

The `iosm` driver supports dumping the coredump logs.

In case a firmware encounters an exception, a snapshot will be taken by the driver. Following regions are accessed for device internal data.


<table>
<caption>Regions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`report.json`

</td>
<td>


The summary of exception details logged as part of this region.

</td>
</tr>
<tr>
<td>


`coredump.fcd`

</td>
<td>


This region contains the details related to the exception occurred in the device (RAM dump).

</td>
</tr>
<tr>
<td>


`cdd.log`

</td>
<td>


This region contains the logs related to the modem CDD driver.

</td>
</tr>
<tr>
<td>


`eeprom.bin`

</td>
<td>


This region contains the eeprom logs.

</td>
</tr>
<tr>
<td>


`bootcore_trace.bin`

</td>
<td>


This region contains the current instance of bootloader logs.

</td>
</tr>
<tr>
<td>


`bootcore_prev_trace.bin`

</td>
<td>


This region contains the previous instance of bootloader logs.

</td>
</tr>
</tbody>
</table>

<a id="rst-region-commands"></a>

## Region commands

$ devlink region show

$ devlink region new pci/0000:02:00.0/report.json

$ devlink region dump pci/0000:02:00.0/report.json snapshot 0

$ devlink region del pci/0000:02:00.0/report.json snapshot 0

$ devlink region new pci/0000:02:00.0/coredump.fcd

$ devlink region dump pci/0000:02:00.0/coredump.fcd snapshot 1

$ devlink region del pci/0000:02:00.0/coredump.fcd snapshot 1

$ devlink region new pci/0000:02:00.0/cdd.log

$ devlink region dump pci/0000:02:00.0/cdd.log snapshot 2

$ devlink region del pci/0000:02:00.0/cdd.log snapshot 2

$ devlink region new pci/0000:02:00.0/eeprom.bin

$ devlink region dump pci/0000:02:00.0/eeprom.bin snapshot 3

$ devlink region del pci/0000:02:00.0/eeprom.bin snapshot 3

$ devlink region new pci/0000:02:00.0/bootcore\_trace.bin

$ devlink region dump pci/0000:02:00.0/bootcore\_trace.bin snapshot 4

$ devlink region del pci/0000:02:00.0/bootcore\_trace.bin snapshot 4

$ devlink region new pci/0000:02:00.0/bootcore\_prev\_trace.bin

$ devlink region dump pci/0000:02:00.0/bootcore\_prev\_trace.bin snapshot 5

$ devlink region del pci/0000:02:00.0/bootcore\_prev\_trace.bin snapshot 5

---

# ixgbe devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the ixgbe device driver.

<a id="rst-ixgbe-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `ixgbe` device driver.

<a id="rst-info-versions"></a>

## Info versions

Any of the versions dealing with the security presented by `devlink-info` is purely informational. Devlink does not use a secure channel to communicate with the device.

The `ixgbe` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Example

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


H49289-000

</td>
<td>


The Product Board Assembly (PBA) identifier of the board.

</td>
</tr>
<tr>
<td>


`fw.undi`

</td>
<td>


running

</td>
<td>


1.1937.0

</td>
<td>


Version of the Option ROM containing the UEFI driver. The version is reported in `major.minor.patch` format. The major version is incremented whenever a major breaking change occurs, or when the minor version would overflow. The minor version is incremented for non-breaking changes and reset to 1 when the major version is incremented. The patch version is normally 0 but is incremented when a fix is delivered as a patch against an older base Option ROM.

</td>
</tr>
<tr>
<td>


`fw.undi.srev`

</td>
<td>


running

</td>
<td>


4

</td>
<td>


Number indicating the security revision of the Option ROM.

</td>
</tr>
<tr>
<td>


`fw.bundle_id`

</td>
<td>


running

</td>
<td>


0x80000d0d

</td>
<td>


Unique identifier of the firmware image file that was loaded onto the device. Also referred to as the EETRACK identifier of the NVM.

</td>
</tr>
<tr>
<td>


`fw.mgmt.api`

</td>
<td>


running

</td>
<td>


1.5.1

</td>
<td>


3-digit version number (major.minor.patch) of the API exported over the AdminQ by the management firmware. Used by the driver to identify what commands are supported. Historical versions of the kernel only displayed a 2-digit version number (major.minor).

</td>
</tr>
<tr>
<td>


`fw.mgmt.build`

</td>
<td>


running

</td>
<td>


0x305d955f

</td>
<td>


Unique identifier of the source for the management firmware.

</td>
</tr>
<tr>
<td>


`fw.mgmt.srev`

</td>
<td>


running

</td>
<td>


3

</td>
<td>


Number indicating the security revision of the firmware.

</td>
</tr>
<tr>
<td>


`fw.psid.api`

</td>
<td>


running

</td>
<td>


0.80

</td>
<td>


Version defining the format of the flash contents.

</td>
</tr>
<tr>
<td>


`fw.netlist`

</td>
<td>


running

</td>
<td>


1.1.2000-6.7.0

</td>
<td>


The version of the netlist module. This module defines the device's Ethernet capabilities and default settings, and is used by the management firmware as part of managing link and device connectivity.

</td>
</tr>
<tr>
<td>


`fw.netlist.build`

</td>
<td>


running

</td>
<td>


0xee16ced7

</td>
<td>


The first 4 bytes of the hash of the netlist module contents.

</td>
</tr>
</tbody>
</table>

<a id="rst-flash-update"></a>

## Flash Update

The `ixgbe` driver implements support for flash update using the `devlink-flash` interface. It supports updating the device flash using a combined flash image that contains the `fw.mgmt`, `fw.undi`, and `fw.netlist` components.


<table>
<caption>List of supported overwrite modes</caption>
<tbody>
<tr>
<td>


Bits

</td>
<td>


Behavior

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_SETTINGS`

</td>
<td>


Do not preserve settings stored in the flash components being updated. This includes overwriting the port configuration that determines the number of physical functions the device will initialize with.

</td>
</tr>
<tr>
<td>


`DEVLINK_FLASH_OVERWRITE_SETTINGS` and `DEVLINK_FLASH_OVERWRITE_IDENTIFIERS`

</td>
<td>


Do not preserve either settings or identifiers. Overwrite everything in the flash with the contents from the provided image, without performing any preservation. This includes overwriting device identifying fields such as the MAC address, Vital product Data (VPD) area, and device serial number. It is expected that this combination be used with an image customized for the specific device.

</td>
</tr>
</tbody>
</table>

<a id="rst-reload"></a>

## Reload

The `ixgbe` driver supports activating new firmware after a flash update using `DEVLINK_CMD_RELOAD` with the `DEVLINK_RELOAD_ACTION_FW_ACTIVATE` action.



```shell
$ devlink dev reload pci/0000:01:00.0 reload action fw_activate
```

The new firmware is activated by issuing a device specific Embedded Management Processor reset which requests the device to reset and reload the EMP firmware image.

The driver does not currently support reloading the driver via `DEVLINK_RELOAD_ACTION_DRIVER_REINIT`.

<a id="rst-regions"></a>

## Regions

The `ixgbe` driver implements the following regions for accessing internal device data.


<table>
<caption>regions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`nvm-flash`

</td>
<td>


The contents of the entire flash chip, sometimes referred to as the device's Non Volatile Memory.

</td>
</tr>
<tr>
<td>


`shadow-ram`

</td>
<td>


The contents of the Shadow RAM, which is loaded from the beginning of the flash. Although the contents are primarily from the flash, this area also contains data generated during device boot which is not stored in flash.

</td>
</tr>
<tr>
<td>


`device-caps`

</td>
<td>


The contents of the device firmware's capabilities buffer. Useful to determine the current state and configuration of the device.

</td>
</tr>
</tbody>
</table>

Both the `nvm-flash` and `shadow-ram` regions can be accessed without a snapshot. The `device-caps` region requires a snapshot as the contents are sent by firmware and can't be split into separate reads.

Users can request an immediate capture of a snapshot for all three regions via the `DEVLINK_CMD_REGION_NEW` command.



```shell
$ devlink region show
pci/0000:01:00.0/nvm-flash: size 10485760 snapshot [] max 1
pci/0000:01:00.0/device-caps: size 4096 snapshot [] max 10

$ devlink region new pci/0000:01:00.0/nvm-flash snapshot 1

$ devlink region dump pci/0000:01:00.0/nvm-flash snapshot 1
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30
0000000000000010 0000 0000 ffff ff04 0029 8c00 0028 8cc8
0000000000000020 0016 0bb8 0016 1720 0000 0000 c00f 3ffc
0000000000000030 bada cce5 bada cce5 bada cce5 bada cce5

$ devlink region read pci/0000:01:00.0/nvm-flash snapshot 1 address 0 length 16
0000000000000000 0014 95dc 0014 9514 0035 1670 0034 db30

$ devlink region delete pci/0000:01:00.0/device-caps snapshot 1
```

---

# kvaser_pciefd devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the kvaser_pciefd device driver.

<a id="rst-kvaser-pciefd-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `kvaser_pciefd` device driver.

<a id="rst-info-versions"></a>

## Info versions

The `kvaser_pciefd` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Version of the firmware running on the device. Also available through `ethtool -i` as `firmware-version`.

</td>
</tr>
</tbody>
</table>

---

# kvaser_usb devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the kvaser_usb device driver.

<a id="rst-kvaser-usb-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `kvaser_usb` device driver.

<a id="rst-info-versions"></a>

## Info versions

The `kvaser_usb` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


Version of the firmware running on the device. Also available through `ethtool -i` as `firmware-version`.

</td>
</tr>
<tr>
<td>


`board.rev`

</td>
<td>


fixed

</td>
<td>


The device hardware revision.

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


The device EAN (product number).

</td>
</tr>
<tr>
<td>


`serial_number`

</td>
<td>


fixed

</td>
<td>


The device serial number.

</td>
</tr>
</tbody>
</table>

---

# mlx4 devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the mlx4 device driver.

<a id="rst-mlx4-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `mlx4` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
</tr>
<tr>
<td>


`internal_err_reset`

</td>
<td>


driverinit, runtime

</td>
</tr>
<tr>
<td>


`max_macs`

</td>
<td>


driverinit

</td>
</tr>
<tr>
<td>


`region_snapshot_enable`

</td>
<td>


driverinit, runtime

</td>
</tr>
</tbody>
</table>

The `mlx4` driver also implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`enable_64b_cqe_eqe`

</td>
<td>


Boolean

</td>
<td>


driverinit

</td>
<td>


Enable 64 byte CQEs/EQEs, if the FW supports it.

</td>
</tr>
<tr>
<td>


`enable_4k_uar`

</td>
<td>


Boolean

</td>
<td>


driverinit

</td>
<td>


Enable using the 4k UAR.

</td>
</tr>
</tbody>
</table>

The `mlx4` driver supports reloading via `DEVLINK_CMD_RELOAD`

<a id="rst-regions"></a>

## Regions

The `mlx4` driver supports dumping the firmware PCI crspace and health buffer during a critical firmware issue.

In case a firmware command times out, firmware getting stuck, or a non zero value on the catastrophic buffer, a snapshot will be taken by the driver.

The `cr-space` region will contain the firmware PCI crspace contents. The `fw-health` region will contain the device firmware's health buffer. Snapshots for both of these regions are taken on the same event triggers.

---

# mlx5 devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the mlx5 device driver.

<a id="rst-mlx5-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `mlx5` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Validation

</td>
<td>


Notes

</td>
</tr>
<tr>
<td>


`enable_roce`

</td>
<td>


driverinit

</td>
<td>


Boolean

</td>
<td>


If the device supports RoCE disablement, RoCE enablement state controls device support for RoCE capability. Otherwise, the control occurs in the driver stack. When RoCE is disabled at the driver level, only raw ethernet QPs are supported.

</td>
</tr>
<tr>
<td>


`io_eq_size`

</td>
<td>


driverinit

</td>
<td>


The range is between 64 and 4096.

</td>
<td>




</td>
</tr>
<tr>
<td>


`event_eq_size`

</td>
<td>


driverinit

</td>
<td>


The range is between 64 and 4096.

</td>
<td>




</td>
</tr>
<tr>
<td>


`max_macs`

</td>
<td>


driverinit

</td>
<td>


The range is between 1 and 2^31. Only power of 2 values are supported.

</td>
<td>




</td>
</tr>
<tr>
<td>


`enable_sriov`

</td>
<td>


permanent

</td>
<td>


Boolean

</td>
<td>


Applies to each physical function (PF) independently, if the device supports it. Otherwise, it applies symmetrically to all PFs.

</td>
</tr>
<tr>
<td>


`total_vfs`

</td>
<td>


permanent

</td>
<td>


The range is between 1 and a device-specific max.

</td>
<td>


Applies to each physical function (PF) independently, if the device supports it. Otherwise, it applies symmetrically to all PFs.

</td>
</tr>
</tbody>
</table>

Note: permanent parameters such as `enable_sriov` and `total_vfs` require FW reset to take effect



```bash
# setup parameters
devlink dev param set pci/0000:01:00.0 name enable_sriov value true cmode permanent
devlink dev param set pci/0000:01:00.0 name total_vfs value 8 cmode permanent

# Fw reset
devlink dev reload pci/0000:01:00.0 action fw_activate

# for PCI related config such as sriov PCI reset/rescan is required:
echo 1 >/sys/bus/pci/devices/0000:01:00.0/remove
echo 1 >/sys/bus/pci/rescan
grep ^ /sys/bus/pci/devices/0000:01:00.0/sriov_*

* - ``num_doorbells``
  - driverinit
  - This controls the number of channel doorbells used by the netdev. In all
    cases, an additional doorbell is allocated and used for non-channel
    communication (e.g. for PTP, HWS, etc.). Supported values are:

    - 0: No channel-specific doorbells, use the global one for everything.
    - [1, max_num_channels]: Spread netdev channels equally across these
      doorbells.
```

The `mlx5` driver also implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`flow_steering_mode`

</td>
<td>


string

</td>
<td>


runtime

</td>
<td>


Controls the flow steering mode of the driver

- `dmfs` Device managed flow steering. In DMFS mode, the HW steering entities are created and managed through firmware.

- `smfs` Software managed flow steering. In SMFS mode, the HW steering entities are created and manage through the driver without firmware intervention.

- `hmfs` Hardware managed flow steering. In HMFS mode, the driver is configuring steering rules directly to the HW using Work Queues with a special new type of WQE (Work Queue Element).

SMFS mode is faster and provides better rule insertion rate compared to default DMFS mode.

</td>
</tr>
<tr>
<td>


`fdb_large_groups`

</td>
<td>


u32

</td>
<td>


driverinit

</td>
<td>


Control the number of large groups (size &gt; 1) in the FDB table.

- The default value is 15, and the range is between 1 and 1024.

</td>
</tr>
<tr>
<td>


`esw_multiport`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Control MultiPort E-Switch shared fdb mode.

An experimental mode where a single E-Switch is used and all the vports and physical ports on the NIC are connected to it.

An example is to send traffic from a VF that is created on PF0 to an uplink that is natively associated with the uplink of PF1

Note: Future devices, ConnectX-8 and onward, will eventually have this as the default to allow forwarding between all NIC ports in a single E-switch environment and the dual E-switch mode will likely get deprecated.

Default: disabled

</td>
</tr>
<tr>
<td>


`esw_port_metadata`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


When applicable, disabling eswitch metadata can increase packet rate up to 20% depending on the use case and packet sizes.

Eswitch port metadata state controls whether to internally tag packets with metadata. Metadata tagging must be enabled for multi-port RoCE, failover between representors and stacked devices. By default metadata is enabled on the supported devices in E-switch. Metadata is applicable only for E-switch in switchdev mode and users may disable it when NONE of the below use cases will be in use: 1. HCA is in Dual/multi-port RoCE mode. 2. VF/SF representor bonding (Usually used for Live migration) 3. Stacked devices

When metadata is disabled, the above use cases will fail to initialize if users try to enable them.

Note: Setting this parameter does not take effect immediately. Setting must happen in legacy mode and eswitch port metadata takes effect after enabling switchdev mode.

</td>
</tr>
<tr>
<td>


`hairpin_num_queues`

</td>
<td>


u32

</td>
<td>


driverinit

</td>
<td>


We refer to a TC NIC rule that involves forwarding as "hairpin". Hairpin queues are mlx5 hardware specific implementation for hardware forwarding of such packets.

Control the number of hairpin queues.

</td>
</tr>
<tr>
<td>


`hairpin_queue_size`

</td>
<td>


u32

</td>
<td>


driverinit

</td>
<td>


Control the size (in packets) of the hairpin queues.

</td>
</tr>
<tr>
<td>


`pcie_cong_inbound_high`

</td>
<td>


u16

</td>
<td>


driverinit

</td>
<td>


High threshold configuration for PCIe congestion events. The firmware will send an event once device side inbound PCIe traffic went above the configured high threshold for a long enough period (at least 200ms).

See pci_bw_inbound_high ethtool stat.

Units are 0.01 %. Accepted values are in range \[0, 10000\]. pcie_cong_inbound_low &lt; pcie_cong_inbound_high. Default value: 9000 (Corresponds to 90%).

</td>
</tr>
<tr>
<td>


`pcie_cong_inbound_low`

</td>
<td>


u16

</td>
<td>


driverinit

</td>
<td>


Low threshold configuration for PCIe congestion events. The firmware will send an event once device side inbound PCIe traffic went below the configured low threshold, only after having been previously in a congested state.

See pci_bw_inbound_low ethtool stat.

Units are 0.01 %. Accepted values are in range \[0, 10000\]. pcie_cong_inbound_low &lt; pcie_cong_inbound_high. Default value: 7500.

</td>
</tr>
<tr>
<td>


`pcie_cong_outbound_high`

</td>
<td>


u16

</td>
<td>


driverinit

</td>
<td>


High threshold configuration for PCIe congestion events. The firmware will send an event once device side outbound PCIe traffic went above the configured high threshold for a long enough period (at least 200ms).

See pci_bw_outbound_high ethtool stat.

Units are 0.01 %. Accepted values are in range \[0, 10000\]. pcie_cong_outbound_low &lt; pcie_cong_outbound_high. Default value: 9000 (Corresponds to 90%).

</td>
</tr>
<tr>
<td>


`pcie_cong_outbound_low`

</td>
<td>


u16

</td>
<td>


driverinit

</td>
<td>


Low threshold configuration for PCIe congestion events. The firmware will send an event once device side outbound PCIe traffic went below the configured low threshold, only after having been previously in a congested state.

See pci_bw_outbound_low ethtool stat.

Units are 0.01 %. Accepted values are in range \[0, 10000\]. pcie_cong_outbound_low &lt; pcie_cong_outbound_high. Default value: 7500.

</td>
</tr>
<tr>
<td>


`cqe_compress_type`

</td>
<td>


string

</td>
<td>


permanent

</td>
<td>


Configure which mechanism/algorithm should be used by the NIC that will affect the rate (aggressiveness) of compressed CQEs depending on PCIe bus conditions and other internal NIC factors. This mode affects all queues that enable compression. \* `balanced` : Merges fewer CQEs, resulting in a moderate compression ratio but maintaining a balance between bandwidth savings and performance \* `aggressive` : Merges more CQEs into a single entry, achieving a higher compression rate and maximizing performance, particularly under high traffic loads

</td>
</tr>
<tr>
<td>


`swp_l4_csum_mode`

</td>
<td>


string

</td>
<td>


permanent

</td>
<td>


Configure how the L4 checksum is calculated by the device when using Software Parser (SWP) hints for header locations.

- `default` : Use the device's default checksum calculation mode. The driver will discover during init whether or full_csum or l4_only is in use. Setting this value explicitly from userspace is not allowed, but some firmware versions may return this value on param read.

- `full_csum` : Calculate full checksum including the pseudo-header

- `l4_only` : Calculate L4-only checksum, excluding the pseudo-header

</td>
</tr>
</tbody>
</table>

The `mlx5` driver supports reloading via `DEVLINK_CMD_RELOAD`

<a id="rst-info-versions"></a>

## Info versions

The `mlx5` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw.psid`

</td>
<td>


fixed

</td>
<td>


Used to represent the board id of the device.

</td>
</tr>
<tr>
<td>


`fw.version`

</td>
<td>


stored, running

</td>
<td>


Three digit major.minor.subminor firmware version number.

</td>
</tr>
</tbody>
</table>

<a id="rst-health-reporters"></a>

## Health reporters

<a id="rst-tx-reporter"></a>

### tx reporter

The tx reporter is responsible for reporting and recovering of the following three error scenarios:

- - **tx timeout**

    Report on kernel tx timeout detection. Recover by searching lost interrupts.

- - **tx error completion**

    Report on error tx completion. Recover by flushing the tx queue and reset it.

- - **tx PTP port timestamping CQ unhealthy**

    Report too many CQEs never delivered on port ts CQ. Recover by flushing and re-creating all PTP channels.

tx reporter also support on demand diagnose callback, on which it provides real time information of its send queues status.

User commands examples:

- Diagnose send queues status:



  ```text
  $ devlink health diagnose pci/0000:82:00.0 reporter tx
  ```

> [!NOTE]
>
> This command has valid output only when interface is up, otherwise the command has empty output.

- Show number of tx errors indicated, number of recover flows ended successfully, is autorecover enabled and graceful period from last recover:



  ```text
  $ devlink health show pci/0000:82:00.0 reporter tx
  ```

<a id="rst-rx-reporter"></a>

### rx reporter

The rx reporter is responsible for reporting and recovering of the following two error scenarios:

- - **rx queues' initialization (population) timeout**

    Population of rx queues' descriptors on ring initialization is done in napi context via triggering an irq. In case of a failure to get the minimum amount of descriptors, a timeout would occur, and descriptors could be recovered by polling the EQ (Event Queue).

- - **rx completions with errors (reported by HW on interrupt context)**

    Report on rx completion error. Recover (if needed) by flushing the related queue and reset it.

rx reporter also supports on demand diagnose callback, on which it provides real time information of its receive queues' status.

- Diagnose rx queues' status and corresponding completion queue:



  ```text
  $ devlink health diagnose pci/0000:82:00.0 reporter rx
  ```

> [!NOTE]
>
> This command has valid output only when interface is up. Otherwise, the command has empty output.

- Show number of rx errors indicated, number of recover flows ended successfully, is autorecover enabled, and graceful period from last recover:



  ```text
  $ devlink health show pci/0000:82:00.0 reporter rx
  ```

<a id="rst-fw-reporter"></a>

### fw reporter

The fw reporter implements `diagnose` and `dump` callbacks. It follows symptoms of fw error such as fw syndrome by triggering fw core dump and storing it into the dump buffer. The fw reporter diagnose command can be triggered any time by the user to check current fw status.

User commands examples:

- Check fw heath status:



  ```text
  $ devlink health diagnose pci/0000:82:00.0 reporter fw
  ```

- Read FW core dump if already stored or trigger new one:



  ```text
  $ devlink health dump show pci/0000:82:00.0 reporter fw
  ```

> [!NOTE]
>
> This command can run only on the PF which has fw tracer ownership, running it on other PF or any VF will return "Operation not permitted".

<a id="rst-fw-fatal-reporter"></a>

### fw fatal reporter

The fw fatal reporter implements `dump` and `recover` callbacks. It follows fatal errors indications by CR-space dump and recover flow. The CR-space dump uses vsc interface which is valid even if the FW command interface is not functional, which is the case in most FW fatal errors. The recover function runs recover flow which reloads the driver and triggers fw reset if needed. On firmware error, the health buffer is dumped into the dmesg. The log level is derived from the error's severity (given in health buffer).

User commands examples:

- Run fw recover flow manually:



  ```text
  $ devlink health recover pci/0000:82:00.0 reporter fw_fatal
  ```

- Read FW CR-space dump if already stored or trigger new one:



  ```text
  $ devlink health dump show pci/0000:82:00.1 reporter fw_fatal
  ```

> [!NOTE]
>
> This command can run only on PF.

<a id="rst-vnic-reporter"></a>

### vnic reporter

The vnic reporter implements only the `diagnose` callback. It is responsible for querying the vnic diagnostic counters from fw and displaying them in realtime.

Description of the vnic counters:

- - **total_error_queues**

    number of queues in an error state due to an async error or errored command.

- - **send_queue_priority_update_flow**

    number of QP/SQ priority/SL update events.

- - **cq_overrun**

    number of times CQ entered an error state due to an overflow.

- - **async_eq_overrun**

    number of times an EQ mapped to async events was overrun.

- - **comp_eq_overrun**

    number of times an EQ mapped to completion events was overrun.

- - **quota_exceeded_command**

    number of commands issued and failed due to quota exceeded.

- - **invalid_command**

    number of commands issued and failed dues to any reason other than quota exceeded.

- - **nic_receive_steering_discard**

    number of packets that completed RX flow steering but were discarded due to a mismatch in flow table.

- - **generated_pkt_steering_fail**

    number of packets generated by the VNIC experiencing unexpected steering failure (at any point in steering flow).

- - **handled_pkt_steering_fail**

    number of packets handled by the VNIC experiencing unexpected steering failure (at any point in steering flow owned by the VNIC, including the FDB for the eswitch owner).

- - **icm_consumption**

    amount of Interconnect Host Memory (ICM) consumed by the vnic in granularity of 4KB. ICM is host memory allocated by SW upon HCA request and is used for storing data structures that control HCA operation.

- - **bar_uar_access**

    number of WRITE or READ access operations to the UAR on the PCIe BAR.

- - **odp_local_triggered_page_fault**

    number of locally-triggered page-faults due to ODP.

- - **odp_remote_triggered_page_fault**

    number of remotly-triggered page-faults due to ODP.

User commands examples:

- Diagnose PF/VF vnic counters:



  ```text
  $ devlink health diagnose pci/0000:82:00.1 reporter vnic
  ```

- Diagnose representor vnic counters (performed by supplying devlink port of the representor, which can be obtained via devlink port command):



  ```text
  $ devlink health diagnose pci/0000:82:00.1/65537 reporter vnic
  ```

> [!NOTE]
>
> This command can run over all interfaces such as PF/VF and representor ports.

---

# mlxsw devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the mlxsw device driver.

<a id="rst-mlxsw-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `mlxsw` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
</tr>
<tr>
<td>


`fw_load_policy`

</td>
<td>


driverinit

</td>
</tr>
</tbody>
</table>

The `mlxsw` driver also implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`acl_region_rehash_interval`

</td>
<td>


u32

</td>
<td>


runtime

</td>
<td>


Sets an interval for periodic ACL region rehashes. The value is specified in milliseconds, with a minimum of `3000`. The value of `0` disables periodic work entirely. The first rehash will be run immediately after the value is set.

</td>
</tr>
</tbody>
</table>

The `mlxsw` driver supports reloading via `DEVLINK_CMD_RELOAD`

<a id="rst-info-versions"></a>

## Info versions

The `mlxsw` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`hw.revision`

</td>
<td>


fixed

</td>
<td>


The hardware revision for this board

</td>
</tr>
<tr>
<td>


`fw.psid`

</td>
<td>


fixed

</td>
<td>


Firmware PSID

</td>
</tr>
<tr>
<td>


`fw.version`

</td>
<td>


running

</td>
<td>


Three digit firmware version

</td>
</tr>
</tbody>
</table>

<a id="rst-line-card-auxiliary-device-info-versions"></a>

## Line card auxiliary device info versions

The `mlxsw` driver reports the following versions for line card auxiliary device


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`hw.revision`

</td>
<td>


fixed

</td>
<td>


The hardware revision for this line card

</td>
</tr>
<tr>
<td>


`ini.version`

</td>
<td>


running

</td>
<td>


Version of line card INI loaded

</td>
</tr>
<tr>
<td>


`fw.psid`

</td>
<td>


fixed

</td>
<td>


Line card device PSID

</td>
</tr>
<tr>
<td>


`fw.version`

</td>
<td>


running

</td>
<td>


Three digit firmware version of line card device

</td>
</tr>
</tbody>
</table>

<a id="rst-driver-specific-traps"></a>

## Driver-specific Traps


<table>
<caption>List of Driver-specific Traps Registered by mlxsw</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`irif_disabled`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed from a disabled router interface (RIF). This can happen during RIF dismantle, when the RIF is first disabled before being removed completely

</td>
</tr>
<tr>
<td>


`erif_disabled`

</td>
<td>


`drop`

</td>
<td>


Traps packets that the device decided to drop because they need to be routed through a disabled router interface (RIF). This can happen during RIF dismantle, when the RIF is first disabled before being removed completely

</td>
</tr>
</tbody>
</table>

---

# mv88e6xxx devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the mv88e6xxx device driver.

<a id="rst-mv88e6xxx-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `mv88e6xxx` device driver.

<a id="rst-parameters"></a>

## Parameters

The `mv88e6xxx` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`ATU_hash`

</td>
<td>


u8

</td>
<td>


runtime

</td>
<td>


Select one of four possible hashing algorithms for MAC addresses in the Address Translation Unit. A value of 3 may work better than the default of 1 when many MAC addresses have the same OUI. Only the values 0 to 3 are valid for this parameter.

</td>
</tr>
</tbody>
</table>

---

# netdevsim devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features supported by the netdevsim device driver.

<a id="rst-netdevsim-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the `devlink` features supported by the `netdevsim` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
</tr>
<tr>
<td>


`max_macs`

</td>
<td>


driverinit

</td>
</tr>
</tbody>
</table>

The `netdevsim` driver also implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`test1`

</td>
<td>


Boolean

</td>
<td>


driverinit

</td>
<td>


Test parameter used to show how a driver-specific devlink parameter can be implemented.

</td>
</tr>
</tbody>
</table>

The `netdevsim` driver supports reloading via `DEVLINK_CMD_RELOAD`

<a id="rst-regions"></a>

## Regions

The `netdevsim` driver exposes a `dummy` region as an example of how the devlink-region interfaces work. A snapshot is taken whenever the `take_snapshot` debugfs file is written to.

<a id="rst-resources"></a>

## Resources

The `netdevsim` driver exposes resources to control the number of FIB entries, FIB rule entries and nexthops that the driver will allow.



```shell
$ devlink resource set netdevsim/netdevsim0 path /IPv4/fib size 96
$ devlink resource set netdevsim/netdevsim0 path /IPv4/fib-rules size 16
$ devlink resource set netdevsim/netdevsim0 path /IPv6/fib size 64
$ devlink resource set netdevsim/netdevsim0 path /IPv6/fib-rules size 16
$ devlink resource set netdevsim/netdevsim0 path /nexthops size 16
$ devlink dev reload netdevsim/netdevsim0
```

<a id="rst-rate-objects"></a>

## Rate objects

The `netdevsim` driver supports rate objects management, which includes:

- registering/unregistering leaf rate objects per VF devlink port;

- creation/deletion node rate objects;

- setting tx_share and tx_max rate values for any rate object type;

- setting parent node for any rate object type.

Rate nodes and their parameters are exposed in `netdevsim` debugfs in RO mode. For example created rate node with name `some_group`:



```shell
$ ls /sys/kernel/debug/netdevsim/netdevsim0/rate_groups/some_group
rate_parent  tx_max  tx_share
```

Same parameters are exposed for leaf objects in corresponding ports directories. For ex.:



```shell
$ ls /sys/kernel/debug/netdevsim/netdevsim0/ports/1
dev  ethtool  rate_parent  tx_max  tx_share
```

<a id="rst-driver-specific-traps"></a>

## Driver-specific Traps


<table>
<caption>List of Driver-specific Traps Registered by netdevsim</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fid_miss`

</td>
<td>


`exception`

</td>
<td>


When a packet enters the device it is classified to a filtering identifier (FID) based on the ingress port and VLAN. This trap is used to trap packets for which a FID could not be found

</td>
</tr>
</tbody>
</table>

---

# nfp devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the nfp device driver.

<a id="rst-nfp-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `nfp` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
</tr>
<tr>
<td>


`fw_load_policy`

</td>
<td>


permanent

</td>
</tr>
<tr>
<td>


`reset_dev_on_drv_probe`

</td>
<td>


permanent

</td>
</tr>
</tbody>
</table>

<a id="rst-info-versions"></a>

## Info versions

The `nfp` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`board.id`

</td>
<td>


fixed

</td>
<td>


Identifier of the board design

</td>
</tr>
<tr>
<td>


`board.rev`

</td>
<td>


fixed

</td>
<td>


Revision of the board design

</td>
</tr>
<tr>
<td>


`board.manufacture`

</td>
<td>


fixed

</td>
<td>


Vendor of the board design

</td>
</tr>
<tr>
<td>


`board.model`

</td>
<td>


fixed

</td>
<td>


Model name of the board design

</td>
</tr>
<tr>
<td>


`board.part_number`

</td>
<td>


fixed

</td>
<td>


Part number of the board and its components

</td>
</tr>
<tr>
<td>


`fw.bundle_id`

</td>
<td>


stored, running

</td>
<td>


Firmware bundle id

</td>
</tr>
<tr>
<td>


`fw.mgmt`

</td>
<td>


stored, running

</td>
<td>


Version of the management firmware

</td>
</tr>
<tr>
<td>


`fw.cpld`

</td>
<td>


stored, running

</td>
<td>


The CPLD firmware component version

</td>
</tr>
<tr>
<td>


`fw.app`

</td>
<td>


stored, running

</td>
<td>


The APP firmware component version

</td>
</tr>
<tr>
<td>


`fw.undi`

</td>
<td>


stored, running

</td>
<td>


The UNDI firmware component version

</td>
</tr>
<tr>
<td>


`fw.ncsi`

</td>
<td>


stored, running

</td>
<td>


The NSCI firmware component version

</td>
</tr>
<tr>
<td>


`chip.init`

</td>
<td>


stored, running

</td>
<td>


The CFGR firmware component version

</td>
</tr>
</tbody>
</table>

---

# octeontx2 devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the octeontx2 AF, PF and VF device drivers.

<a id="rst-octeontx2-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `octeontx2 AF, PF and VF` device drivers.

<a id="rst-parameters"></a>

## Parameters

The `octeontx2 PF and VF` drivers implement the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`mcam_count`

</td>
<td>


u16

</td>
<td>


runtime

</td>
<td>


Select number of match CAM entries to be allocated for an interface. The same is used for ntuple filters of the interface. Supported by PF and VF drivers.

</td>
</tr>
</tbody>
</table>

The `octeontx2 AF` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`dwrr_mtu`

</td>
<td>


u32

</td>
<td>


runtime

</td>
<td>


Use to set the quantum which hardware uses for scheduling among transmit queues. Hardware uses weighted DWRR algorithm to schedule among all transmit queues.

</td>
</tr>
<tr>
<td>


`npc_mcam_high_zone_percent`

</td>
<td>


u8

</td>
<td>


runtime

</td>
<td>


Use to set the number of high priority zone entries in NPC MCAM that can be allocated by a user, out of the three priority zone categories high, mid and low.

</td>
</tr>
<tr>
<td>


`npc_def_rule_cntr`

</td>
<td>


bool

</td>
<td>


runtime

</td>
<td>


Use to enable or disable hit counters for the default rules in NPC MCAM. Its not guaranteed that counters gets enabled and mapped to all the default rules, since the counters are scarce and driver follows a best effort approach. The default rule serves as the primary packet steering rule for a specific PF or VF, based on its DMAC address which is installed by AF driver as part of its initialization. Sample command to read hit counters for default rule from debugfs is as follows, cat /sys/kernel/debug/cn10k/npc/mcam_rules

</td>
</tr>
<tr>
<td>


`nix_maxlf`

</td>
<td>


u16

</td>
<td>


runtime

</td>
<td>


Use to set the maximum number of LFs in NIX hardware block. This would be useful to increase the availability of default resources allocated to enabled LFs like MCAM entries for example.

</td>
</tr>
</tbody>
</table>

The `octeontx2 PF` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`unicast_filter_count`

</td>
<td>


u8

</td>
<td>


runtime

</td>
<td>


Set the maximum number of unicast filters that can be programmed for the device. This can be used to achieve better device resource utilization, avoiding over consumption of unused MCAM table entries.

</td>
</tr>
</tbody>
</table>

---

# prestera devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the prestera device driver.

<a id="rst-prestera-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `prestera` device driver.

<a id="rst-driver-specific-traps"></a>

## Driver-specific Traps


<table>
<caption>List of Driver-specific Traps Registered by prestera</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
</tbody>
</table>


<table>
<caption>List of Driver-specific Traps Registered by prestera</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`arp_bc`

</td>
<td>


`trap`

</td>
<td>


Traps ARP broadcast packets (both requests/responses)

</td>
</tr>
<tr>
<td>


`is_is`

</td>
<td>


`trap`

</td>
<td>


Traps IS-IS packets

</td>
</tr>
<tr>
<td>


`ospf`

</td>
<td>


`trap`

</td>
<td>


Traps OSPF packets

</td>
</tr>
<tr>
<td>


`ip_bc_mac`

</td>
<td>


`trap`

</td>
<td>


Traps IPv4 packets with broadcast DA Mac address

</td>
</tr>
<tr>
<td>


`stp`

</td>
<td>


`trap`

</td>
<td>


Traps STP BPDU

</td>
</tr>
<tr>
<td>


`lacp`

</td>
<td>


`trap`

</td>
<td>


Traps LACP packets

</td>
</tr>
<tr>
<td>


`lldp`

</td>
<td>


`trap`

</td>
<td>


Traps LLDP packets

</td>
</tr>
<tr>
<td>


`router_mc`

</td>
<td>


`trap`

</td>
<td>


Traps multicast packets

</td>
</tr>
<tr>
<td>


`vrrp`

</td>
<td>


`trap`

</td>
<td>


Traps VRRP packets

</td>
</tr>
<tr>
<td>


`dhcp`

</td>
<td>


`trap`

</td>
<td>


Traps DHCP packets

</td>
</tr>
<tr>
<td>


`mtu_error`

</td>
<td>


`trap`

</td>
<td>


Traps (exception) packets that exceeded port's MTU

</td>
</tr>
<tr>
<td>


`mac_to_me`

</td>
<td>


`trap`

</td>
<td>


Traps packets with switch-port's DA Mac address

</td>
</tr>
<tr>
<td>


`ttl_error`

</td>
<td>


`trap`

</td>
<td>


Traps (exception) IPv4 packets whose TTL exceeded

</td>
</tr>
<tr>
<td>


`ipv4_options`

</td>
<td>


`trap`

</td>
<td>


Traps (exception) packets due to the malformed IPV4 header options

</td>
</tr>
<tr>
<td>


`ip_default_route`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have no specific IP interface (IP to me) and no forwarding prefix

</td>
</tr>
<tr>
<td>


`local_route`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have been send to one of switch IP interfaces addresses

</td>
</tr>
<tr>
<td>


`ipv4_icmp_redirect`

</td>
<td>


`trap`

</td>
<td>


Traps (exception) IPV4 ICMP redirect packets

</td>
</tr>
<tr>
<td>


`arp_response`

</td>
<td>


`trap`

</td>
<td>


Traps ARP replies packets that have switch-port's DA Mac address

</td>
</tr>
<tr>
<td>


`acl_code_0`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 0 (tc pref 0)

</td>
</tr>
<tr>
<td>


`acl_code_1`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 1 (tc pref 1)

</td>
</tr>
<tr>
<td>


`acl_code_2`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 2 (tc pref 2)

</td>
</tr>
<tr>
<td>


`acl_code_3`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 3 (tc pref 3)

</td>
</tr>
<tr>
<td>


`acl_code_4`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 4 (tc pref 4)

</td>
</tr>
<tr>
<td>


`acl_code_5`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 5 (tc pref 5)

</td>
</tr>
<tr>
<td>


`acl_code_6`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 6 (tc pref 6)

</td>
</tr>
<tr>
<td>


`acl_code_7`

</td>
<td>


`trap`

</td>
<td>


Traps packets that have ACL priority set to 7 (tc pref 7)

</td>
</tr>
<tr>
<td>


`ipv4_bgp`

</td>
<td>


`trap`

</td>
<td>


Traps IPv4 BGP packets

</td>
</tr>
<tr>
<td>


`ssh`

</td>
<td>


`trap`

</td>
<td>


Traps SSH packets

</td>
</tr>
<tr>
<td>


`telnet`

</td>
<td>


`trap`

</td>
<td>


Traps Telnet packets

</td>
</tr>
<tr>
<td>


`icmp`

</td>
<td>


`trap`

</td>
<td>


Traps ICMP packets

</td>
</tr>
<tr>
<td>


`rxdma_drop`

</td>
<td>


`drop`

</td>
<td>


Drops packets (RxDMA) due to the lack of ingress buffers etc.

</td>
</tr>
<tr>
<td>


`port_no_vlan`

</td>
<td>


`drop`

</td>
<td>


Drops packets due to faulty-configured network or due to internal bug (config issue).

</td>
</tr>
<tr>
<td>


`local_port`

</td>
<td>


`drop`

</td>
<td>


Drops packets whose decision (FDB entry) is to bridge packet back to the incoming port/trunk.

</td>
</tr>
<tr>
<td>


`invalid_sa`

</td>
<td>


`drop`

</td>
<td>


Drops packets with multicast source MAC address.

</td>
</tr>
<tr>
<td>


`illegal_ip_addr`

</td>
<td>


`drop`

</td>
<td>


Drops packets with illegal SIP/DIP multicast/unicast addresses.

</td>
</tr>
<tr>
<td>


`illegal_ipv4_hdr`

</td>
<td>


`drop`

</td>
<td>


Drops packets with illegal IPV4 header.

</td>
</tr>
<tr>
<td>


`ip_uc_dip_da_mismatch`

</td>
<td>


`drop`

</td>
<td>


Drops packets with destination MAC being unicast, but destination IP address being multicast.

</td>
</tr>
<tr>
<td>


`ip_sip_is_zero`

</td>
<td>


`drop`

</td>
<td>


Drops packets with zero (0) IPV4 source address.

</td>
</tr>
<tr>
<td>


`met_red`

</td>
<td>


`drop`

</td>
<td>


Drops non-conforming packets (dropped by Ingress policer, metering drop), e.g. packet rate exceeded configured bandwidth.

</td>
</tr>
</tbody>
</table>

---

# qed devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the qed core device driver.

<a id="rst-qed-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `qed` core device driver.

<a id="rst-parameters"></a>

## Parameters

The `qed` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`iwarp_cmt`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Enable iWARP functionality for 100g devices. Note that this impacts L2 performance, and is therefore not enabled by default.

</td>
</tr>
</tbody>
</table>

---

# sfc devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the sfc device driver for the ef10 and ef100 devices.

<a id="rst-sfc-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `sfc` device driver for the ef10 and ef100 devices.

<a id="rst-info-versions"></a>

## Info versions

The `sfc` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`fw.bundle_id`

</td>
<td>


stored

</td>
<td>


Version of the firmware "bundle" image that was last used to update multiple components.

</td>
</tr>
<tr>
<td>


`fw.mgmt.suc`

</td>
<td>


running

</td>
<td>


For boards where the management function is split between multiple control units, this is the SUC control unit's firmware version.

</td>
</tr>
<tr>
<td>


`fw.mgmt.cmc`

</td>
<td>


running

</td>
<td>


For boards where the management function is split between multiple control units, this is the CMC control unit's firmware version.

</td>
</tr>
<tr>
<td>


`fpga.rev`

</td>
<td>


running

</td>
<td>


FPGA design revision.

</td>
</tr>
<tr>
<td>


`fpga.app`

</td>
<td>


running

</td>
<td>


Datapath programmable logic version.

</td>
</tr>
<tr>
<td>


`fw.app`

</td>
<td>


running

</td>
<td>


Datapath software/microcode/firmware version.

</td>
</tr>
<tr>
<td>


`coproc.boot`

</td>
<td>


running

</td>
<td>


SmartNIC application co-processor (APU) first stage boot loader version.

</td>
</tr>
<tr>
<td>


`coproc.uboot`

</td>
<td>


running

</td>
<td>


SmartNIC application co-processor (APU) co-operating system loader version.

</td>
</tr>
<tr>
<td>


`coproc.main`

</td>
<td>


running

</td>
<td>


SmartNIC application co-processor (APU) main operating system version.

</td>
</tr>
<tr>
<td>


`coproc.recovery`

</td>
<td>


running

</td>
<td>


SmartNIC application co-processor (APU) recovery operating system version.

</td>
</tr>
<tr>
<td>


`fw.exprom`

</td>
<td>


running

</td>
<td>


Expansion ROM version. For boards where the expansion ROM is split between multiple images (e.g. PXE and UEFI), this is the specifically the PXE boot ROM version.

</td>
</tr>
<tr>
<td>


`fw.uefi`

</td>
<td>


running

</td>
<td>


UEFI driver version (No UNDI support).

</td>
</tr>
</tbody>
</table>

<a id="rst-flash-update"></a>

## Flash Update

The `sfc` driver implements support for flash update using the `devlink-flash` interface. It supports updating the device flash using a combined flash image ("bundle") that contains multiple components (on ef10, typically `fw.mgmt`, `fw.app`, `fw.exprom` and `fw.uefi`).

The driver does not support any overwrite mask flags.

---

# stmmac (synopsys dwmac) devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the stmmac device driver.

<a id="rst-stmmac-synopsys-dwmac-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `stmmac` device driver.

<a id="rst-parameters"></a>

## Parameters

The `stmmac` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`phc_coarse_adj`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Enable the Coarse timestamping mode, as defined in the DWMAC TRM. A detailed explanation of this timestamping mode can be found in the Socfpga Functionnal Description \[1\].

In Coarse mode, the ptp clock is expected to be fed by a high-precision clock that is externally adjusted, and the subsecond increment used for timestamping is set to 1/ptp_clock_rate.

In Fine mode (i.e. Coarse mode == false), the ptp clock frequency is continuously adjusted, but the subsecond increment is set to 2/ptp_clock_rate.

Coarse mode is suitable for PTP Grand Master operation. If unsure, leave the parameter to False.

\[1\] [https://www.intel.com/content/www/us/en/docs/programmable/683126/21-2/functional-description-of-the-emac.html](<https://www.intel.com/content/www/us/en/docs/programmable/683126/21-2/functional-description-of-the-emac.html>)

</td>
</tr>
</tbody>
</table>

---

# ti-cpsw-switch devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the ti-cpsw-switch device driver.

<a id="rst-ti-cpsw-switch-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `ti-cpsw-switch` device driver.

<a id="rst-parameters"></a>

## Parameters

The `ti-cpsw-switch` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`ale_bypass`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Enables ALE_CONTROL(4).BYPASS mode for debugging purposes. In this mode, all packets will be sent to the host port only.

</td>
</tr>
<tr>
<td>


`switch_mode`

</td>
<td>


Boolean

</td>
<td>


runtime

</td>
<td>


Enable switch mode

</td>
</tr>
</tbody>
</table>

---

# zl3073x devlink support

_Peios Kernel / Internals / Networking / devlink_

> This document describes the devlink features implemented by the zl3073x device driver.

<a id="rst-zl3073x-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `zl3073x` device driver.

<a id="rst-parameters"></a>

## Parameters


<table>
<caption>Generic parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Mode

</td>
<td>


Notes

</td>
</tr>
<tr>
<td>


`clock_id`

</td>
<td>


driverinit

</td>
<td>


Set the clock ID that is used by the driver for registering DPLL devices and pins.

</td>
</tr>
</tbody>
</table>

<a id="rst-info-versions"></a>

## Info versions

The `zl3073x` driver reports the following versions


<table>
<caption>devlink info versions implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Example

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`asic.id`

</td>
<td>


fixed

</td>
<td>


1E94

</td>
<td>


Chip identification number

</td>
</tr>
<tr>
<td>


`asic.rev`

</td>
<td>


fixed

</td>
<td>


300

</td>
<td>


Chip revision number

</td>
</tr>
<tr>
<td>


`fw`

</td>
<td>


running

</td>
<td>


7006

</td>
<td>


Firmware version number

</td>
</tr>
<tr>
<td>


`custom_cfg`

</td>
<td>


running

</td>
<td>


1.3.0.1

</td>
<td>


Device configuration version customized by OEM

</td>
</tr>
</tbody>
</table>

<a id="rst-flash-update"></a>

## Flash Update

The `zl3073x` driver implements support for flash update using the `devlink-flash` interface. It supports updating the device flash using a combined flash image ("bundle") that contains multiple components (firmware parts and configurations).

During the flash procedure, the standard firmware interface is not available, so the driver unregisters all DPLLs and associated pins, and re-registers them once the flash procedure is complete.

The driver does not support any overwrite mask flags.

---

# Networking Diagnostics

_Peios Kernel / Internals / Networking / diagnostic_

> Reference for Networking Diagnostics.

<a id="rst-networking-diagnostics"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Diagnostic Concept for Investigating Twisted Pair Ethernet Variants at OSI Layer 1](</kernel/internals/networking/diagnostic/twisted-pair-layer1-diagnostics.md>)

---

# Diagnostic Concept for Investigating Twisted Pair Ethernet Variants at OSI Layer 1

_Peios Kernel / Internals / Networking / diagnostic_

> This documentation is designed for two primary audiences:

<a id="rst-diagnostic-concept-for-investigating-twisted-pair-ethernet-variants-at-osi-layer-1"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

This documentation is designed for two primary audiences:

1. **Users and System Administrators**: For those dealing with real-world Ethernet issues, this guide provides a practical, step-by-step troubleshooting flow to help identify and resolve common problems in Twisted Pair Ethernet at OSI Layer 1. If you're facing unstable links, speed drops, or mysterious network issues, jump right into the step-by-step guide and follow it through to find your solution.

2. **Kernel Developers**: For developers working with network drivers and PHY support, this documentation outlines the diagnostic process and highlights areas where the Linux kernel’s diagnostic interfaces could be extended or improved. By understanding the diagnostic flow, developers can better prioritize future enhancements.

<a id="rst-step-by-step-diagnostic-guide-from-linux-general-ethernet"></a>

## Step-by-Step Diagnostic Guide from Linux (General Ethernet)

This diagnostic guide covers common Ethernet troubleshooting scenarios, focusing on **link stability and detection** across different Ethernet environments, including **Single-Pair Ethernet (SPE)** and **Multi-Pair Ethernet (MPE)**, as well as power delivery technologies like **PoDL** (Power over Data Line) and **PoE** (Clause 33 PSE).

The guide is designed to help users diagnose physical layer (Layer 1) issues on systems running **Linux kernel version 6.11 or newer**, utilizing **ethtool version 6.10 or later** and **iproute2 version 6.4.0 or later**.

In this guide, we assume that users may have **limited or no access to the link partner** and will focus on diagnosing issues locally.

<a id="rst-diagnostic-scenarios"></a>

### Diagnostic Scenarios

- **Link is up and stable, but no data transfer**: If the link is stable but there are issues with data transmission, refer to the **OSI Layer 2 Troubleshooting Guide**.

- **Link is unstable**: Link resets, speed drops, or other fluctuations indicate potential issues at the hardware or physical layer.

- **No link detected**: The interface is up, but no link is established.

<a id="rst-verify-interface-status"></a>

### Verify Interface Status

Begin by verifying the status of the Ethernet interface to check if it is administratively up. Unlike `ethtool`, which provides information on the link and PHY status, it does not show the **administrative state** of the interface. To check this, you should use the `ip` command, which describes the interface state within the angle brackets `"<>"` in its output.

For example, in the output `<NO-CARRIER,BROADCAST,MULTICAST,UP>`, the important keywords are:

- **UP**: The interface is in the administrative "UP" state.

- **NO-CARRIER**: The interface is administratively up, but no physical link is detected.

If the output shows `<BROADCAST,MULTICAST>`, this indicates the interface is in the administrative "DOWN" state.

- **Command:** `ip link show dev <interface>`

- **Expected Output:**



  ```bash
  4: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 ...
     link/ether 88:14:2b:00:96:f2 brd ff:ff:ff:ff:ff:ff
  ```

- **Interpreting the Output:**

  - **Administrative UP State**:

    - If the output contains **"UP"**, the interface is administratively up, and the system is trying to establish a physical link.

    - If you also see **"NO-CARRIER"**, it means the physical link has not been detected, indicating potential Layer 1 issues like a cable fault, misconfiguration, or no connection at the link partner. In this case, proceed to the **Inspect Link Status and PHY Configuration** section.

  - **Administrative DOWN State**:

    - If the output lacks **"UP"** and shows only states like **"&lt;BROADCAST,MULTICAST&gt;"**, it means the interface is administratively down. In this case, bring the interface up using the following command:



      ```bash
      ip link set dev <interface> up
      ```

- **Next Steps**:

  - If the interface is **administratively up** but shows **NO-CARRIER**, proceed to the **Inspect Link Status and PHY Configuration** section to troubleshoot potential physical layer issues.

  - If the interface was **administratively down** and you have brought it up, ensure to **repeat this verification step** to confirm the new state of the interface before proceeding

  - **If the interface is up and the link is detected**:

    - If the output shows **"UP"** and there is **no \`NO-CARRIER\`**, the interface is administratively up, and the physical link has been successfully established. If everything is working as expected, the Layer 1 diagnostics are complete, and no further action is needed.

    - If the interface is up and the link is detected but **no data is being transferred**, the issue is likely beyond Layer 1, and you should proceed with diagnosing the higher layers of the OSI model. This may involve checking Layer 2 configurations (such as VLANs or MAC address issues), Layer 3 settings (like IP addresses, routing, or ARP), or Layer 4 and above (firewalls, services, etc.).

    - If the **link is unstable** or **frequently resetting or dropping**, this may indicate a physical layer issue such as a faulty cable, interference, or power delivery problems. In this case, proceed with the next step in this guide.

<a id="rst-inspect-link-status-and-phy-configuration"></a>

### Inspect Link Status and PHY Configuration

Use `ethtool -I` to check the link status, PHY configuration, supported link modes, and additional statistics such as the **Link Down Events** counter. This step is essential for diagnosing Layer 1 problems such as speed mismatches, duplex issues, and link instability.

For both **Single-Pair Ethernet (SPE)** and **Multi-Pair Ethernet (MPE)** devices, you will use this step to gather key details about the link. **SPE** links generally support a single speed and mode without autonegotiation (with the exception of **10BaseT1L**), while **MPE** devices typically support multiple link modes and autonegotiation.

- **Command:** `ethtool -I <interface>`

- **Example Output for SPE Interface (Non-autonegotiation)**:



  ```bash
  Settings for spe4:
      Supported ports: [ TP ]
      Supported link modes:   100baseT1/Full
      Supported pause frame use: No
      Supports auto-negotiation: No
      Supported FEC modes: Not reported
      Advertised link modes: Not applicable
      Advertised pause frame use: No
      Advertised auto-negotiation: No
      Advertised FEC modes: Not reported
      Speed: 100Mb/s
      Duplex: Full
      Auto-negotiation: off
      master-slave cfg: forced slave
      master-slave status: slave
      Port: Twisted Pair
      PHYAD: 6
      Transceiver: external
      MDI-X: Unknown
      Supports Wake-on: d
      Wake-on: d
      Link detected: yes
      SQI: 7/7
      Link Down Events: 2
  ```

- **Example Output for MPE Interface (Autonegotiation)**:



  ```bash
  Settings for eth1:
      Supported ports: [ TP    MII ]
      Supported link modes:   10baseT/Half 10baseT/Full
                              100baseT/Half 100baseT/Full
      Supported pause frame use: Symmetric Receive-only
      Supports auto-negotiation: Yes
      Supported FEC modes: Not reported
      Advertised link modes:  10baseT/Half 10baseT/Full
                              100baseT/Half 100baseT/Full
      Advertised pause frame use: Symmetric Receive-only
      Advertised auto-negotiation: Yes
      Advertised FEC modes: Not reported
      Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                           100baseT/Half 100baseT/Full
      Link partner advertised pause frame use: Symmetric Receive-only
      Link partner advertised auto-negotiation: Yes
      Link partner advertised FEC modes: Not reported
      Speed: 100Mb/s
      Duplex: Full
      Auto-negotiation: on
      Port: Twisted Pair
      PHYAD: 10
      Transceiver: internal
      MDI-X: Unknown
      Supports Wake-on: pg
      Wake-on: p
      Link detected: yes
      Link Down Events: 1
  ```

- **Next Steps**:

  - Record the output provided by `ethtool`, particularly noting the **master-slave status**, **speed**, **duplex**, and other relevant fields. This information will be useful for further analysis or troubleshooting. Once the **ethtool** output has been collected and stored, move on to the next diagnostic step.

<a id="rst-check-power-delivery-podl-or-poe"></a>

### Check Power Delivery (PoDL or PoE)

If it is known that **PoDL** or **PoE** is **not implemented** on the system, or the **PSE** (Power Sourcing Equipment) is managed by proprietary user-space software or external tools, you can skip this step. In such cases, verify power delivery through alternative methods, such as checking hardware indicators (LEDs), using multimeters, or consulting vendor-specific software for monitoring power status.

If **PoDL** or **PoE** is implemented and managed directly by Linux, follow these steps to ensure power is being delivered correctly:

- **Command:** `ethtool --show-pse <interface>`

- **Expected Output Examples**:

  1. **PSE Not Supported**:

     If no PSE is attached or the interface does not support PSE, the following output is expected:



     ```bash
     netlink error: No PSE is attached
     netlink error: Operation not supported
     ```

  2. **PoDL (Single-Pair Ethernet)**:

     When PoDL is implemented, you might see the following attributes:



     ```bash
     PSE attributes for eth1:
     PoDL PSE Admin State: enabled
     PoDL PSE Power Detection Status: delivering power
     ```

  3. **PoE (Clause 33 PSE)**:

     For standard PoE, the output may look like this:



     ```bash
     PSE attributes for eth1:
     Clause 33 PSE Admin State: enabled
     Clause 33 PSE Power Detection Status: delivering power
     Clause 33 PSE Available Power Limit: 18000
     ```

- **Adjust Power Limit (if needed)**:

  - Sometimes, the available power limit may not be sufficient for the link partner. You can increase the power limit as needed.

  - **Command:** `ethtool --set-pse <interface> c33-pse-avail-pw-limit <limit>`

    Example:



    ```bash
    ethtool --set-pse eth1 c33-pse-avail-pw-limit 18000
    ethtool --show-pse eth1
    ```

    **Expected Output** after adjusting the power limit:



    ```bash
    Clause 33 PSE Available Power Limit: 18000
    ```

- **Next Steps**:

  - **PoE or PoDL Not Used**: If **PoE** or **PoDL** is not implemented or used on the system, proceed to the next diagnostic step, as power delivery is not relevant for this setup.

  - **PoE or PoDL Controlled Externally**: If **PoE** or **PoDL** is used but is not managed by the Linux kernel's **PSE-PD** framework (i.e., it is controlled by proprietary user-space software or external tools), this part is out of scope for this documentation. Please consult vendor-specific documentation or external tools for monitoring and managing power delivery.

  - **PSE Admin State Disabled**:

    - If the `PSE Admin State:` is **disabled**, enable it by running one of the following commands:



      ```bash
      ethtool --set-pse <devname> podl-pse-admin-control enable
      ```

      or, for Clause 33 PSE (PoE):

      > ethtool --set-pse &lt;devname&gt; c33-pse-admin-control enable

    - After enabling the PSE Admin State, return to the start of the **Check Power Delivery (PoDL or PoE)** step to recheck the power delivery status.

  - **Power Not Delivered**: If the `Power Detection Status` shows something other than "delivering power" (e.g., `over current`), troubleshoot the **PSE**. Check for potential issues such as a short circuit in the cable, insufficient power delivery, or a fault in the PSE itself.

  - **Power Delivered but No Link**: If power is being delivered but no link is established, proceed with further diagnostics by performing **Cable Diagnostics** or reviewing the **Inspect Link Status and PHY Configuration** steps to identify any underlying issues with the physical link or settings.

<a id="rst-cable-diagnostics"></a>

### Cable Diagnostics

Use `ethtool` to test for physical layer issues such as cable faults. The test results can vary depending on the cable's condition, the technology in use, and the state of the link partner. The results from the cable test will help in diagnosing issues like open circuits, shorts, impedance mismatches, and noise-related problems.

- **Command:** `ethtool --cable-test <interface>`

The following are the typical outputs for **Single-Pair Ethernet (SPE)** and **Multi-Pair Ethernet (MPE)**:

- **For Single-Pair Ethernet (SPE)**: - **Expected Output (SPE)**:



  ```bash
  Cable test completed for device eth1.
  Pair A, fault length: 25.00m
  Pair A code Open Circuit
  ```

  This indicates an open circuit or cable fault at the reported distance, but results can be influenced by the link partner's state. Refer to the **"Troubleshooting Based on Cable Test Results"** section for further interpretation of these results.

- **For Multi-Pair Ethernet (MPE)**: - **Expected Output (MPE)**:



  ```bash
  Cable test completed for device eth0.
  Pair A code OK
  Pair B code OK
  Pair C code Open Circuit
  ```

  Here, Pair C is reported as having an open circuit, while Pairs A and B are functioning correctly. However, if autonegotiation is in use on Pairs A and B, the cable test may be disrupted. Refer to the **"Troubleshooting Based on Cable Test Results"** section for a detailed explanation of these issues and how to resolve them.

For detailed descriptions of the different possible cable test results, please refer to the **"Troubleshooting Based on Cable Test Results"** section.

<a id="rst-troubleshooting-based-on-cable-test-results"></a>

#### Troubleshooting Based on Cable Test Results

After running the cable test, the results can help identify specific issues in the physical connection. However, it is important to note that **cable testing results heavily depend on the capabilities and characteristics of both the local hardware and the link partner**. The accuracy and reliability of the results can vary significantly between different hardware implementations.

In some cases, this can introduce **blind spots** in the current cable testing implementation, where certain results may not accurately reflect the actual physical state of the cable. For example:

- An **Open Circuit** result might not only indicate a damaged or disconnected cable but also occur if the cable is properly attached to a powered-down link partner.

- Some PHYs may report a **Short within Pair** if the link partner is in **forced slave mode**, even though there is no actual short in the cable.

To help users interpret the results more effectively, it could be beneficial to extend the **kernel UAPI** (User API) to provide additional context or **possible variants** of issues based on the hardware’s characteristics. Since these quirks are often hardware-specific, the **kernel driver** would be an ideal source of such information. By providing flags or hints related to potential false positives for each test result, users would have a better understanding of what to verify and where to investigate further.

Until such improvements are made, users should be aware of these limitations and manually verify cable issues as needed. Physical inspections may help resolve uncertainties related to false positive results.

The results can be one of the following:

- **OK**:

  - The cable is functioning correctly, and no issues were detected.

  - **Next Steps**: If you are still experiencing issues, it might be related to higher-layer problems, such as duplex mismatches or speed negotiation, which are not physical-layer issues.

  - **Special Case for \`BaseT1\` (1000/100/10BaseT1)**: In `BaseT1` systems, an "OK" result typically also means that the link is up and likely in **slave mode**, since cable tests usually only pass in this mode. For some **10BaseT1L** PHYs, an "OK" result may occur even if the cable is too long for the PHY's configured range (for example, when the range is configured for short-distance mode).

- **Open Circuit**:

  - An **Open Circuit** result typically indicates that the cable is damaged or disconnected at the reported fault length. Consider these possibilities:

    - If the link partner is in **admin down** state or powered off, you might still get an "Open Circuit" result even if the cable is functional.

    - **Next Steps**: Inspect the cable at the fault length for visible damage or loose connections. Verify the link partner is powered on and in the correct mode.

- **Short within Pair**:

  - A **Short within Pair** indicates an unintended connection within the same pair of wires, typically caused by physical damage to the cable.

    - **Next Steps**: Replace or repair the cable and check for any physical damage or improperly crimped connectors.

- **Short to Another Pair**:

  - A **Short to Another Pair** means the wires from different pairs are shorted, which could occur due to physical damage or incorrect wiring.

    - **Next Steps**: Replace or repair the damaged cable. Inspect the cable for incorrect terminations or pinched wiring.

- **Impedance Mismatch**:

  - **Impedance Mismatch** indicates a reflection caused by an impedance discontinuity in the cable. This can happen when a part of the cable has abnormal impedance (e.g., when different cable types are spliced together or when there is a defect in the cable).

    - **Next Steps**: Check the cable quality and ensure consistent impedance throughout its length. Replace any sections of the cable that do not meet specifications.

- **Noise**:

  - **Noise** means that the Time Domain Reflectometry (TDR) test could not complete due to excessive noise on the cable, which can be caused by interference from electromagnetic sources.

    - **Next Steps**: Identify and eliminate sources of electromagnetic interference (EMI) near the cable. Consider using shielded cables or rerouting the cable away from noise sources.

- **Resolution Not Possible**:

  - **Resolution Not Possible** means that the TDR test could not detect the issue due to the resolution limitations of the test or because the fault is beyond the distance that the test can measure.

    - **Next Steps**: Inspect the cable manually if possible, or use alternative diagnostic tools that can handle greater distances or higher resolution.

- **Unknown**:

  - An **Unknown** result may occur when the test cannot classify the fault or when a specific issue is outside the scope of the tool's detection capabilities.

    - **Next Steps**: Re-run the test, verify the link partner's state, and inspect the cable manually if necessary.

<a id="rst-verify-link-partner-phy-configuration"></a>

### Verify Link Partner PHY Configuration

If the cable test passes but the link is still not functioning correctly, it’s essential to verify the configuration of the link partner’s PHY. Mismatches in speed, duplex settings, or master-slave roles can cause connection issues.

<a id="rst-autonegotiation-mismatch"></a>

#### Autonegotiation Mismatch

- If both link partners support autonegotiation, ensure that autonegotiation is enabled on both sides and that all supported link modes are advertised. A mismatch can lead to connectivity problems or sub optimal performance.

- **Quick Fix:** Reset autonegotiation to the default settings, which will advertise all default link modes:



  ```bash
  ethtool -s <interface> autoneg on
  ```

- **Command to check configuration:** `ethtool <interface>`

- **Expected Output:** Ensure that both sides advertise compatible link modes. If autonegotiation is off, verify that both link partners are configured for the same speed and duplex.

  The following example shows a case where the local PHY advertises fewer link modes than it supports. This will reduce the number of overlapping link modes with the link partner. In the worst case, there will be no common link modes, and the link will not be created:



  ```bash
  Settings for eth0:
     Supported link modes:  1000baseT/Full, 100baseT/Full
     Advertised link modes: 1000baseT/Full
     Speed: 1000Mb/s
     Duplex: Full
     Auto-negotiation: on
  ```

<a id="rst-combined-mode-mismatch-autonegotiation-on-one-side-forced-on-the-other"></a>

#### Combined Mode Mismatch (Autonegotiation on One Side, Forced on the Other)

- One possible issue occurs when one side is using **autonegotiation** (as in most modern systems), and the other side is set to a **forced link mode** (e.g., older hardware with single-speed hubs). In such cases, modern PHYs will attempt to detect the forced mode on the other side. If the link is established, you may notice:

  - **No or empty "Link partner advertised link modes"**.

  - **"Link partner advertised auto-negotiation:"** will be **"no"** or not present.

- This type of detection does not always work reliably:

  - Typically, the modern PHY will default to **Half Duplex**, even if the link partner is actually configured for **Full Duplex**.

  - Some PHYs may not work reliably if the link partner switches from one forced mode to another. In this case, only a down/up cycle may help.

- **Next Steps**: Set both sides to the same fixed speed and duplex mode to avoid potential detection issues.



  ```bash
  ethtool -s <interface> speed 1000 duplex full autoneg off
  ```

<a id="rst-master-slave-role-mismatch-baset1-and-1000baset-phys"></a>

#### Master/Slave Role Mismatch (BaseT1 and 1000BaseT PHYs)

- In **BaseT1** systems (e.g., 1000BaseT1, 100BaseT1), link establishment requires that one device is configured as **master** and the other as **slave**. A mismatch in this master-slave configuration can prevent the link from being established. However, **1000BaseT** also supports configurable master/slave roles and can face similar issues.

- **Role Preference in 1000BaseT**: The **1000BaseT** specification allows link partners to negotiate master-slave roles or role preferences during autonegotiation. Some PHYs have hardware limitations or bugs that prevent them from functioning properly in certain roles. In such cases, drivers may force these PHYs into a specific role (e.g., **forced master** or **forced slave**) or try a weaker option by setting preferences. If both link partners have the same issue and are forced into the same mode (e.g., both forced into master mode), they will not be able to establish a link.

- **Next Steps**: Ensure that one side is configured as **master** and the other as **slave** to avoid this issue, particularly when hardware limitations are involved, or try the weaker **preferred** option instead of **forced**. Check for any driver-related restrictions or forced modes.

- **Command to force master/slave mode**:



  ```bash
  ethtool -s <interface> master-slave forced-master
  ```

  or:



  ```bash
  ethtool -s <interface> master-slave forced-master speed 1000 duplex full autoneg off
  ```

- **Check the current master/slave status**:



  ```bash
  ethtool <interface>
  ```

  Example Output:



  ```bash
  master-slave cfg: forced-master
  master-slave status: master
  ```

- **Hardware Bugs and Driver Forcing**: If a known hardware issue forces the PHY into a specific mode, it’s essential to check the driver source code or hardware documentation for details. Ensure that the roles are compatible across both link partners, and if both PHYs are forced into the same mode, adjust one side accordingly to resolve the mismatch.

<a id="rst-monitor-link-resets-and-speed-drops"></a>

### Monitor Link Resets and Speed Drops

If the link is unstable, showing frequent resets or speed drops, this may indicate issues with the cable, PHY configuration, or environmental factors. While there is still no completely unified way in Linux to directly monitor downshift events or link speed changes via user space tools, both the Linux kernel logs and `ethtool` can provide valuable insights, especially if the driver supports reporting such events.

- **Monitor Kernel Logs for Link Resets and Speed Drops**:

  - The Linux kernel will print link status changes, including downshift events, in the system logs. These messages typically include speed changes, duplex mode, and downshifted link speed (if the driver supports it).

  - **Command to monitor kernel logs in real-time:**



    ```bash
    dmesg -w | grep "Link is Up\|Link is Down"
    ```

  - Example Output (if a downshift occurs):



    ```bash
    eth0: Link is Up - 100Mbps/Full (downshifted) - flow control rx/tx
    eth0: Link is Down
    ```

    This indicates that the link has been established but has downshifted from a higher speed.

  - **Note**: Not all drivers or PHYs support downshift reporting, so you may not see this information for all devices.

- **Monitor Link Down Events Using \`ethtool\`**:

  - Starting with the latest kernel and `ethtool` versions, you can track **Link Down Events** using the `ethtool -I` command. This will provide counters for link drops, helping to diagnose link instability issues if supported by the driver.

  - **Command to monitor link down events:**



    ```bash
    ethtool -I <interface>
    ```

  - Example Output (if supported):



    ```bash
    PSE attributes for eth1:
    Link Down Events: 5
    ```

    This indicates that the link has dropped 5 times. Frequent link down events may indicate cable or environmental issues that require further investigation.

- **Check Link Status and Speed**:

  - Even though downshift counts or events are not easily tracked, you can still use `ethtool` to manually check the current link speed and status.

  - **Command:** `ethtool <interface>`

  - **Expected Output:**



    ```bash
    Speed: 1000Mb/s
    Duplex: Full
    Auto-negotiation: on
    Link detected: yes
    ```

    Any inconsistencies in the expected speed or duplex setting could indicate an issue.

- **Disable Energy-Efficient Ethernet (EEE) for Diagnostics**:

  - **EEE** (Energy-Efficient Ethernet) can be a source of link instability due to transitions in and out of low-power states. For diagnostic purposes, it may be useful to **temporarily** disable EEE to determine if it is contributing to link instability. This is **not a generic recommendation** for disabling power management.

  - **Next Steps**: Disable EEE and monitor if the link becomes stable. If disabling EEE resolves the issue, report the bug so that the driver can be fixed.

  - **Command:**



    ```bash
    ethtool --set-eee <interface> eee off
    ```

  - **Important**: If disabling EEE resolves the instability, the issue should be reported to the maintainers as a bug, and the driver should be corrected to handle EEE properly without causing instability. Disabling EEE permanently should not be seen as a solution.

- **Monitor Error Counters**:

  - Use `ethtool -S <interface> --all-groups` to retrieve standardized interface statistics if the driver supports the unified interface:

  - **Command:** `ethtool -S <interface> --all-groups`

  - **Example Output (if supported)**:



    ```bash
    phydev-RxFrames: 100391
    phydev-RxErrors: 0
    phydev-TxFrames: 9
    phydev-TxErrors: 0
    ```

  - If the unified interface is not supported, use `ethtool -S <interface>` to retrieve MAC and PHY counters. Note that non-standardized PHY counter names vary by driver and must be interpreted accordingly:

  - **Command:** `ethtool -S <interface>`

  - **Example Output (if supported)**:



    ```bash
    rx_crc_errors: 123
    tx_errors: 45
    rx_frame_errors: 78
    ```

  - **Note**: If no meaningful error counters are available or if counters are not supported, you may need to rely on physical inspections (e.g., cable condition) or kernel log messages (e.g., link up/down events) to further diagnose the issue.

  - **Compare Counters**:

    - Compare the egress and ingress frame counts reported by the PHY and MAC.

    - A small difference may occur due to sampling rate differences between the MAC and PHY drivers, or if the PHY and MAC are not always fully synchronized in their UP or DOWN states.

    - Significant discrepancies indicate potential issues in the data path between the MAC and PHY.

<a id="rst-when-all-else-fails"></a>

### When All Else Fails...

So you've checked the cables, monitored the logs, disabled EEE, and still... nothing? Don’t worry, you’re not alone. Sometimes, Ethernet gremlins just don’t want to cooperate.

But before you throw in the towel (or the Ethernet cable), take a deep breath. It’s always possible that:

1. Your PHY has a unique, undocumented personality.

2. The problem is lying dormant, waiting for just the right moment to magically resolve itself (hey, it happens\!).

3. Or, it could be that the ultimate solution simply hasn’t been invented yet.

If none of the above bring you comfort, there’s one final step: contribute\! If you've uncovered new or unusual issues, or have creative diagnostic methods, feel free to share your findings and extend this documentation. Together, we can hunt down every elusive network issue - one twisted pair at a time.

Remember: sometimes the solution is just a reboot away, but if not, it’s time to dig deeper - or report that bug\!

---

# Distributed Switch Architecture

_Peios Kernel / Internals / Networking / dsa_

> Reference for Distributed Switch Architecture.

<a id="rst-distributed-switch-architecture"></a>

- [Architecture](</kernel/internals/networking/dsa/dsa.md>)
- [Broadcom RoboSwitch Ethernet switch driver](</kernel/internals/networking/dsa/b53.md>)
- [Broadcom Starfighter 2 Ethernet switch driver](</kernel/internals/networking/dsa/bcm-sf2.md>)
- [LAN9303 Ethernet switch driver](</kernel/internals/networking/dsa/lan9303.md>)
- [NXP SJA1105 switch driver](</kernel/internals/networking/dsa/sja1105.md>)
- [DSA switch configuration from userspace](</kernel/internals/networking/dsa/configuration.md>)

---

# Broadcom RoboSwitch Ethernet switch driver

_Peios Kernel / Internals / Networking / dsa_

> The Broadcom RoboSwitch Ethernet switch family is used in quite a range of xDSL router, cable modems and other multimedia devices.

<a id="rst-broadcom-roboswitch-ethernet-switch-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Broadcom RoboSwitch Ethernet switch family is used in quite a range of xDSL router, cable modems and other multimedia devices.

The actual implementation supports the devices BCM5325E, BCM5365, BCM539x, BCM53115 and BCM53125 as well as BCM63XX.

<a id="rst-implementation-details"></a>

## Implementation details

The driver is located in `drivers/net/dsa/b53/` and is implemented as a DSA driver; see `Documentation/networking/dsa/dsa.rst` for details on the subsystem and what it provides.

The switch is, if possible, configured to enable a Broadcom specific 4-bytes switch tag which gets inserted by the switch for every packet forwarded to the CPU interface, conversely, the CPU network interface should insert a similar tag for packets entering the CPU port. The tag format is described in `net/dsa/tag_brcm.c`.

The configuration of the device depends on whether or not tagging is supported.

The interface names and example network configuration are used according the configuration described in the [Configuration showcases](</kernel/internals/networking/dsa/configuration.md#rst-dsa-config-showcases>).

<a id="rst-configuration-with-tagging-support"></a>

### Configuration with tagging support

The tagging based configuration is desired. It is not specific to the b53 DSA driver and will work like all DSA drivers which supports tagging.

See [Configuration with tagging support](</kernel/internals/networking/dsa/configuration.md#rst-dsa-tagged-configuration>).

<a id="rst-configuration-without-tagging-support"></a>

### Configuration without tagging support

Older models (5325, 5365) support a different tag format that is not supported yet. 539x and 531x5 require managed mode and some special handling, which is also not yet supported. The tagging support is disabled in these cases and the switch need a different configuration.

The configuration slightly differ from the [Configuration without tagging support](</kernel/internals/networking/dsa/configuration.md#rst-dsa-vlan-configuration>).

The b53 tags the CPU port in all VLANs, since otherwise any PVID untagged VLAN programming would basically change the CPU port's default PVID and make it untagged, undesirable.

In difference to the configuration described in [Configuration without tagging support](</kernel/internals/networking/dsa/configuration.md#rst-dsa-vlan-configuration>) the default VLAN 1 has to be removed from the user interface configuration in single port and gateway configuration, while there is no need to add an extra VLAN configuration in the bridge showcase.

<a id="rst-single-port"></a>

#### single port

The configuration can only be set up via VLAN tagging and bridge setup. By default packages are tagged with vid 1:



```sh
# tag traffic on CPU port
ip link add link eth0 name eth0.1 type vlan id 1
ip link add link eth0 name eth0.2 type vlan id 2
ip link add link eth0 name eth0.3 type vlan id 3

# The conduit interface needs to be brought up before the user ports.
ip link set eth0 up
ip link set eth0.1 up
ip link set eth0.2 up
ip link set eth0.3 up

# bring up the user interfaces
ip link set wan up
ip link set lan1 up
ip link set lan2 up

# create bridge
ip link add name br0 type bridge

# activate VLAN filtering
ip link set dev br0 type bridge vlan_filtering 1

# add ports to bridges
ip link set dev wan master br0
ip link set dev lan1 master br0
ip link set dev lan2 master br0

# tag traffic on ports
bridge vlan add dev lan1 vid 2 pvid untagged
bridge vlan del dev lan1 vid 1
bridge vlan add dev lan2 vid 3 pvid untagged
bridge vlan del dev lan2 vid 1

# configure the VLANs
ip addr add 192.0.2.1/30 dev eth0.1
ip addr add 192.0.2.5/30 dev eth0.2
ip addr add 192.0.2.9/30 dev eth0.3

# bring up the bridge devices
ip link set br0 up
```

<a id="rst-bridge"></a>

#### bridge



```sh
# tag traffic on CPU port
ip link add link eth0 name eth0.1 type vlan id 1

# The conduit interface needs to be brought up before the user ports.
ip link set eth0 up
ip link set eth0.1 up

# bring up the user interfaces
ip link set wan up
ip link set lan1 up
ip link set lan2 up

# create bridge
ip link add name br0 type bridge

# activate VLAN filtering
ip link set dev br0 type bridge vlan_filtering 1

# add ports to bridge
ip link set dev wan master br0
ip link set dev lan1 master br0
ip link set dev lan2 master br0
ip link set eth0.1 master br0

# configure the bridge
ip addr add 192.0.2.129/25 dev br0

# bring up the bridge
ip link set dev br0 up
```

<a id="rst-gateway"></a>

#### gateway



```sh
# tag traffic on CPU port
ip link add link eth0 name eth0.1 type vlan id 1
ip link add link eth0 name eth0.2 type vlan id 2

# The conduit interface needs to be brought up before the user ports.
ip link set eth0 up
ip link set eth0.1 up
ip link set eth0.2 up

# bring up the user interfaces
ip link set wan up
ip link set lan1 up
ip link set lan2 up

# create bridge
ip link add name br0 type bridge

# activate VLAN filtering
ip link set dev br0 type bridge vlan_filtering 1

# add ports to bridges
ip link set dev wan master br0
ip link set eth0.1 master br0
ip link set dev lan1 master br0
ip link set dev lan2 master br0

# tag traffic on ports
bridge vlan add dev wan vid 2 pvid untagged
bridge vlan del dev wan vid 1

# configure the VLANs
ip addr add 192.0.2.1/30 dev eth0.2
ip addr add 192.0.2.129/25 dev br0

# bring up the bridge devices
ip link set br0 up
```

---

# Broadcom Starfighter 2 Ethernet switch driver

_Peios Kernel / Internals / Networking / dsa_

> Broadcom's Starfighter 2 Ethernet switch hardware block is commonly found and deployed in the following products:

<a id="rst-broadcom-starfighter-2-ethernet-switch-driver"></a>

Broadcom's Starfighter 2 Ethernet switch hardware block is commonly found and deployed in the following products:

- xDSL gateways such as BCM63138

- streaming/multimedia Set Top Box such as BCM7445

- Cable Modem/residential gateways such as BCM7145/BCM3390

The switch is typically deployed in a configuration involving between 5 to 13 ports, offering a range of built-in and customizable interfaces:

- single integrated Gigabit PHY

- quad integrated Gigabit PHY

- quad external Gigabit PHY w/ MDIO multiplexer

- integrated MoCA PHY

- several external MII/RevMII/GMII/RGMII interfaces

The switch also supports specific congestion control features which allow MoCA fail-over not to lose packets during a MoCA role re-election, as well as out of band back-pressure to the host CPU network interface when downstream interfaces are connected at a lower speed.

The switch hardware block is typically interfaced using MMIO accesses and contains a bunch of sub-blocks/registers:

- `SWITCH_CORE`: common switch registers

- `SWITCH_REG`: external interfaces switch register

- `SWITCH_MDIO`: external MDIO bus controller (there is another one in SWITCH_CORE, which is used for indirect PHY accesses)

- `SWITCH_INDIR_RW`: 64-bits wide register helper block

- `SWITCH_INTRL2_0/1`: Level-2 interrupt controllers

- `SWITCH_ACB`: Admission control block

- `SWITCH_FCB`: Fail-over control block

<a id="rst-implementation-details"></a>

## Implementation details

The driver is located in `drivers/net/dsa/bcm_sf2.c` and is implemented as a DSA driver; see `Documentation/networking/dsa/dsa.rst` for details on the subsystem and what it provides.

The SF2 switch is configured to enable a Broadcom specific 4-bytes switch tag which gets inserted by the switch for every packet forwarded to the CPU interface, conversely, the CPU network interface should insert a similar tag for packets entering the CPU port. The tag format is described in `net/dsa/tag_brcm.c`.

Overall, the SF2 driver is a fairly regular DSA driver; there are a few specifics covered below.

<a id="rst-device-tree-probing"></a>

### Device Tree probing

The DSA platform device driver is probed using a specific compatible string provided in `net/dsa/dsa.c`. The reason for that is because the DSA subsystem gets registered as a platform device driver currently. DSA will provide the needed device_node pointers which are then accessible by the switch driver setup function to setup resources such as register ranges and interrupts. This currently works very well because none of the of\_\* functions utilized by the driver require a struct device to be bound to a struct device_node, but things may change in the future.

<a id="rst-mdio-indirect-accesses"></a>

### MDIO indirect accesses

Due to a limitation in how Broadcom switches have been designed, external Broadcom switches connected to a SF2 require the use of the DSA user MDIO bus in order to properly configure them. By default, the SF2 pseudo-PHY address, and an external switch pseudo-PHY address will both be snooping for incoming MDIO transactions, since they are at the same address (30), resulting in some kind of "double" programming. Using DSA, and setting `ds->phys_mii_mask` accordingly, we selectively divert reads and writes towards external Broadcom switches pseudo-PHY addresses. Newer revisions of the SF2 hardware have introduced a configurable pseudo-PHY address which circumvents the initial design limitation.

<a id="rst-multimedia-over-coaxial-moca-interfaces"></a>

### Multimedia over CoAxial (MoCA) interfaces

MoCA interfaces are fairly specific and require the use of a firmware blob which gets loaded onto the MoCA processor(s) for packet processing. The switch hardware contains logic which will assert/de-assert link states accordingly for the MoCA interface whenever the MoCA coaxial cable gets disconnected or the firmware gets reloaded. The SF2 driver relies on such events to properly set its MoCA interface carrier state and properly report this to the networking stack.

The MoCA interfaces are supported using the PHY library's fixed PHY/emulated PHY device and the switch driver registers a `fixed_link_update` callback for such PHYs which reflects the link state obtained from the interrupt handler.

<a id="rst-power-management"></a>

### Power Management

Whenever possible, the SF2 driver tries to minimize the overall switch power consumption by applying a combination of:

- turning off internal buffers/memories

- disabling packet processing logic

- putting integrated PHYs in IDDQ/low-power

- reducing the switch core clock based on the active port count

- enabling and advertising EEE

- turning off RGMII data processing logic when the link goes down

<a id="rst-wake-on-lan"></a>

### Wake-on-LAN

Wake-on-LAN is currently implemented by utilizing the host processor Ethernet MAC controller wake-on logic. Whenever Wake-on-LAN is requested, an intersection between the user request and the supported host Ethernet interface WoL capabilities is done and the intersection result gets configured. During system-wide suspend/resume, only ports not participating in Wake-on-LAN are disabled.

---

# DSA switch configuration from userspace

_Peios Kernel / Internals / Networking / dsa_

> The DSA switch configuration is not integrated into the main userspace network configuration suites by now and has to be performed manually.

<a id="rst-dsa-switch-configuration-from-userspace"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The DSA switch configuration is not integrated into the main userspace network configuration suites by now and has to be performed manually.

<a id="rst-configuration-showcases"></a>
<a id="rst-dsa-config-showcases"></a>

## Configuration showcases

To configure a DSA switch a couple of commands need to be executed. In this documentation some common configuration scenarios are handled as showcases:

- ***single port***

  Every switch port acts as a different configurable Ethernet port

- ***bridge***

  Every switch port is part of one configurable Ethernet bridge

- ***gateway***

  Every switch port except one upstream port is part of a configurable Ethernet bridge. The upstream port acts as different configurable Ethernet port.

All configurations are performed with tools from iproute2, which is available at [https://www.kernel.org/pub/linux/utils/net/iproute2/](<https://www.kernel.org/pub/linux/utils/net/iproute2/>)

Through DSA every port of a switch is handled like a normal linux Ethernet interface. The CPU port is the switch port connected to an Ethernet MAC chip. The corresponding linux Ethernet interface is called the conduit interface. All other corresponding linux interfaces are called user interfaces.

The user interfaces depend on the conduit interface being up in order for them to send or receive traffic. Prior to kernel v5.12, the state of the conduit interface had to be managed explicitly by the user. Starting with kernel v5.12, the behavior is as follows:

- when a DSA user interface is brought up, the conduit interface is automatically brought up.

- when the conduit interface is brought down, all DSA user interfaces are automatically brought down.

In this documentation the following Ethernet interfaces are used:

- ***eth0***

  the conduit interface

- ***eth1***

  another conduit interface

- ***lan1***

  a user interface

- ***lan2***

  another user interface

- ***lan3***

  a third user interface

- ***wan***

  A user interface dedicated for upstream traffic

Further Ethernet interfaces can be configured similar. The configured IPs and networks are:

- ***single port***

  - lan1: 192.0.2.1/30 (192.0.2.0 - 192.0.2.3)

  - lan2: 192.0.2.5/30 (192.0.2.4 - 192.0.2.7)

  - lan3: 192.0.2.9/30 (192.0.2.8 - 192.0.2.11)

- ***bridge***

  - br0: 192.0.2.129/25 (192.0.2.128 - 192.0.2.255)

- ***gateway***

  - br0: 192.0.2.129/25 (192.0.2.128 - 192.0.2.255)

  - wan: 192.0.2.1/30 (192.0.2.0 - 192.0.2.3)

<a id="rst-configuration-with-tagging-support"></a>
<a id="rst-dsa-tagged-configuration"></a>

## Configuration with tagging support

The tagging based configuration is desired and supported by the majority of DSA switches. These switches are capable to tag incoming and outgoing traffic without using a VLAN based configuration.

- ***single port***



  ```sh
  # configure each interface
  ip addr add 192.0.2.1/30 dev lan1
  ip addr add 192.0.2.5/30 dev lan2
  ip addr add 192.0.2.9/30 dev lan3

  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up

  # bring up the user interfaces
  ip link set lan1 up
  ip link set lan2 up
  ip link set lan3 up
  ```

- ***bridge***



  ```sh
  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up

  # bring up the user interfaces
  ip link set lan1 up
  ip link set lan2 up
  ip link set lan3 up

  # create bridge
  ip link add name br0 type bridge

  # add ports to bridge
  ip link set dev lan1 master br0
  ip link set dev lan2 master br0
  ip link set dev lan3 master br0

  # configure the bridge
  ip addr add 192.0.2.129/25 dev br0

  # bring up the bridge
  ip link set dev br0 up
  ```

- ***gateway***



  ```sh
  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up

  # bring up the user interfaces
  ip link set wan up
  ip link set lan1 up
  ip link set lan2 up

  # configure the upstream port
  ip addr add 192.0.2.1/30 dev wan

  # create bridge
  ip link add name br0 type bridge

  # add ports to bridge
  ip link set dev lan1 master br0
  ip link set dev lan2 master br0

  # configure the bridge
  ip addr add 192.0.2.129/25 dev br0

  # bring up the bridge
  ip link set dev br0 up
  ```

<a id="rst-configuration-without-tagging-support"></a>
<a id="rst-dsa-vlan-configuration"></a>

## Configuration without tagging support

A minority of switches are not capable to use a taging protocol (DSA_TAG_PROTO_NONE). These switches can be configured by a VLAN based configuration.

- ***single port***

  The configuration can only be set up via VLAN tagging and bridge setup.



  ```sh
  # tag traffic on CPU port
  ip link add link eth0 name eth0.1 type vlan id 1
  ip link add link eth0 name eth0.2 type vlan id 2
  ip link add link eth0 name eth0.3 type vlan id 3

  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up
  ip link set eth0.1 up
  ip link set eth0.2 up
  ip link set eth0.3 up

  # bring up the user interfaces
  ip link set lan1 up
  ip link set lan2 up
  ip link set lan3 up

  # create bridge
  ip link add name br0 type bridge

  # activate VLAN filtering
  ip link set dev br0 type bridge vlan_filtering 1

  # add ports to bridges
  ip link set dev lan1 master br0
  ip link set dev lan2 master br0
  ip link set dev lan3 master br0

  # tag traffic on ports
  bridge vlan add dev lan1 vid 1 pvid untagged
  bridge vlan add dev lan2 vid 2 pvid untagged
  bridge vlan add dev lan3 vid 3 pvid untagged

  # configure the VLANs
  ip addr add 192.0.2.1/30 dev eth0.1
  ip addr add 192.0.2.5/30 dev eth0.2
  ip addr add 192.0.2.9/30 dev eth0.3

  # bring up the bridge devices
  ip link set br0 up
  ```

- ***bridge***



  ```sh
  # tag traffic on CPU port
  ip link add link eth0 name eth0.1 type vlan id 1

  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up
  ip link set eth0.1 up

  # bring up the user interfaces
  ip link set lan1 up
  ip link set lan2 up
  ip link set lan3 up

  # create bridge
  ip link add name br0 type bridge

  # activate VLAN filtering
  ip link set dev br0 type bridge vlan_filtering 1

  # add ports to bridge
  ip link set dev lan1 master br0
  ip link set dev lan2 master br0
  ip link set dev lan3 master br0
  ip link set eth0.1 master br0

  # tag traffic on ports
  bridge vlan add dev lan1 vid 1 pvid untagged
  bridge vlan add dev lan2 vid 1 pvid untagged
  bridge vlan add dev lan3 vid 1 pvid untagged

  # configure the bridge
  ip addr add 192.0.2.129/25 dev br0

  # bring up the bridge
  ip link set dev br0 up
  ```

- ***gateway***



  ```sh
  # tag traffic on CPU port
  ip link add link eth0 name eth0.1 type vlan id 1
  ip link add link eth0 name eth0.2 type vlan id 2

  # For kernels earlier than v5.12, the conduit interface needs to be
  # brought up manually before the user ports.
  ip link set eth0 up
  ip link set eth0.1 up
  ip link set eth0.2 up

  # bring up the user interfaces
  ip link set wan up
  ip link set lan1 up
  ip link set lan2 up

  # create bridge
  ip link add name br0 type bridge

  # activate VLAN filtering
  ip link set dev br0 type bridge vlan_filtering 1

  # add ports to bridges
  ip link set dev wan master br0
  ip link set eth0.1 master br0
  ip link set dev lan1 master br0
  ip link set dev lan2 master br0

  # tag traffic on ports
  bridge vlan add dev lan1 vid 1 pvid untagged
  bridge vlan add dev lan2 vid 1 pvid untagged
  bridge vlan add dev wan vid 2 pvid untagged

  # configure the VLANs
  ip addr add 192.0.2.1/30 dev eth0.2
  ip addr add 192.0.2.129/25 dev br0

  # bring up the bridge devices
  ip link set br0 up
  ```

<a id="rst-forwarding-database-fdb-management"></a>

## Forwarding database (FDB) management

The existing DSA switches do not have the necessary hardware support to keep the software FDB of the bridge in sync with the hardware tables, so the two tables are managed separately (`bridge fdb show` queries both, and depending on whether the `self` or `master` flags are being used, a `bridge fdb add` or `bridge fdb del` command acts upon entries from one or both tables).

Up until kernel v4.14, DSA only supported user space management of bridge FDB entries using the bridge bypass operations (which do not update the software FDB, just the hardware one) using the `self` flag (which is optional and can be omitted).

>
>
> ```sh
> bridge fdb add dev swp0 00:01:02:03:04:05 self static
> # or shorthand
> bridge fdb add dev swp0 00:01:02:03:04:05 static
> ```

Due to a bug, the bridge bypass FDB implementation provided by DSA did not distinguish between `static` and `local` FDB entries (`static` are meant to be forwarded, while `local` are meant to be locally terminated, i.e. sent to the host port). Instead, all FDB entries with the `self` flag (implicit or explicit) are treated by DSA as `static` even if they are `local`.

>
>
> ```sh
> # This command:
> bridge fdb add dev swp0 00:01:02:03:04:05 static
> # behaves the same for DSA as this command:
> bridge fdb add dev swp0 00:01:02:03:04:05 local
> # or shorthand, because the 'local' flag is implicit if 'static' is not
> # specified, it also behaves the same as:
> bridge fdb add dev swp0 00:01:02:03:04:05
> ```

The last command is an incorrect way of adding a static bridge FDB entry to a DSA switch using the bridge bypass operations, and works by mistake. Other drivers will treat an FDB entry added by the same command as `local` and as such, will not forward it, as opposed to DSA.

Between kernel v4.14 and v5.14, DSA has supported in parallel two modes of adding a bridge FDB entry to the switch: the bridge bypass discussed above, as well as a new mode using the `master` flag which installs FDB entries in the software bridge too.

>
>
> ```sh
> bridge fdb add dev swp0 00:01:02:03:04:05 master static
> ```

Since kernel v5.14, DSA has gained stronger integration with the bridge's software FDB, and the support for its bridge bypass FDB implementation (using the `self` flag) has been removed. This results in the following changes:

>
>
> ```sh
> # This is the only valid way of adding an FDB entry that is supported,
> # compatible with v4.14 kernels and later:
> bridge fdb add dev swp0 00:01:02:03:04:05 master static
> # This command is no longer buggy and the entry is properly treated as
> # 'local' instead of being forwarded:
> bridge fdb add dev swp0 00:01:02:03:04:05
> # This command no longer installs a static FDB entry to hardware:
> bridge fdb add dev swp0 00:01:02:03:04:05 static
> ```

Script writers are therefore encouraged to use the `master static` set of flags when working with bridge FDB entries on DSA switch interfaces.

<a id="rst-affinity-of-user-ports-to-cpu-ports"></a>

## Affinity of user ports to CPU ports

Typically, DSA switches are attached to the host via a single Ethernet interface, but in cases where the switch chip is discrete, the hardware design may permit the use of 2 or more ports connected to the host, for an increase in termination throughput.

DSA can make use of multiple CPU ports in two ways. First, it is possible to statically assign the termination traffic associated with a certain user port to be processed by a certain CPU port. This way, user space can implement custom policies of static load balancing between user ports, by spreading the affinities according to the available CPU ports.

Secondly, it is possible to perform load balancing between CPU ports on a per packet basis, rather than statically assigning user ports to CPU ports. This can be achieved by placing the DSA conduits under a LAG interface (bonding or team). DSA monitors this operation and creates a mirror of this software LAG on the CPU ports facing the physical DSA conduits that constitute the LAG slave devices.

To make use of multiple CPU ports, the firmware (device tree) description of the switch must mark all the links between CPU ports and their DSA conduits using the `ethernet` reference/phandle. At startup, only a single CPU port and DSA conduit will be used - the numerically first port from the firmware description which has an `ethernet` property. It is up to the user to configure the system for the switch to use other conduits.

DSA uses the `rtnl_link_ops` mechanism (with a "dsa" `kind`) to allow changing the DSA conduit of a user port. The `IFLA_DSA_CONDUIT` u32 netlink attribute contains the ifindex of the conduit device that handles each user device. The DSA conduit must be a valid candidate based on firmware node information, or a LAG interface which contains only slaves which are valid candidates.

Using iproute2, the following manipulations are possible:

>
>
> ```sh
> # See the DSA conduit in current use
> ip -d link show dev swp0
>     (...)
>     dsa master eth0
>
> # Static CPU port distribution
> ip link set swp0 type dsa master eth1
> ip link set swp1 type dsa master eth0
> ip link set swp2 type dsa master eth1
> ip link set swp3 type dsa master eth0
>
> # CPU ports in LAG, using explicit assignment of the DSA conduit
> ip link add bond0 type bond mode balance-xor && ip link set bond0 up
> ip link set eth1 down && ip link set eth1 master bond0
> ip link set swp0 type dsa master bond0
> ip link set swp1 type dsa master bond0
> ip link set swp2 type dsa master bond0
> ip link set swp3 type dsa master bond0
> ip link set eth0 down && ip link set eth0 master bond0
> ip -d link show dev swp0
>     (...)
>     dsa master bond0
>
> # CPU ports in LAG, relying on implicit migration of the DSA conduit
> ip link add bond0 type bond mode balance-xor && ip link set bond0 up
> ip link set eth0 down && ip link set eth0 master bond0
> ip link set eth1 down && ip link set eth1 master bond0
> ip -d link show dev swp0
>     (...)
>     dsa master bond0
> ```

Notice that in the case of CPU ports under a LAG, the use of the `IFLA_DSA_CONDUIT` netlink attribute is not strictly needed, but rather, DSA reacts to the `IFLA_MASTER` attribute change of its present conduit (`eth0`) and migrates all user ports to the new upper of `eth0`, `bond0`. Similarly, when `bond0` is destroyed using `RTM_DELLINK`, DSA migrates the user ports that were assigned to this interface to the first physical DSA conduit which is eligible, based on the firmware description (it effectively reverts to the startup configuration).

In a setup with more than 2 physical CPU ports, it is therefore possible to mix static user to CPU port assignment with LAG between DSA conduits. It is not possible to statically assign a user port towards a DSA conduit that has any upper interfaces (this includes LAG devices - the conduit must always be the LAG in this case).

Live changing of the DSA conduit (and thus CPU port) affinity of a user port is permitted, in order to allow dynamic redistribution in response to traffic.

Physical DSA conduits are allowed to join and leave at any time a LAG interface used as a DSA conduit; however, DSA will reject a LAG interface as a valid candidate for being a DSA conduit unless it has at least one physical DSA conduit as a slave device.

---

# Architecture

_Peios Kernel / Internals / Networking / dsa_

> This document describes the Distributed Switch Architecture (DSA) subsystem design principles, limitations, interactions with other subsystems, and how to develop drivers for this subsystem as well as a TODO for developers interested in…

<a id="rst-architecture"></a>

This document describes the **Distributed Switch Architecture (DSA)** subsystem design principles, limitations, interactions with other subsystems, and how to develop drivers for this subsystem as well as a TODO for developers interested in joining the effort.

<a id="rst-design-principles"></a>

## Design principles

The Distributed Switch Architecture subsystem was primarily designed to support Marvell Ethernet switches (MV88E6xxx, a.k.a. Link Street product line) using Linux, but has since evolved to support other vendors as well.

The original philosophy behind this design was to be able to use unmodified Linux tools such as bridge, iproute2, ifconfig to work transparently whether they configured/queried a switch port network device or a regular network device.

An Ethernet switch typically comprises multiple front-panel ports and one or more CPU or management ports. The DSA subsystem currently relies on the presence of a management port connected to an Ethernet controller capable of receiving Ethernet frames from the switch. This is a very common setup for all kinds of Ethernet switches found in Small Home and Office products: routers, gateways, or even top-of-rack switches. This host Ethernet controller will be later referred to as "conduit" and "cpu" in DSA terminology and code.

The D in DSA stands for Distributed, because the subsystem has been designed with the ability to configure and manage cascaded switches on top of each other using upstream and downstream Ethernet links between switches. These specific ports are referred to as "dsa" ports in DSA terminology and code. A collection of multiple switches connected to each other is called a "switch tree".

For each front-panel port, DSA creates specialized network devices which are used as controlling and data-flowing endpoints for use by the Linux networking stack. These specialized network interfaces are referred to as "user" network interfaces in DSA terminology and code.

The ideal case for using DSA is when an Ethernet switch supports a "switch tag" which is a hardware feature making the switch insert a specific tag for each Ethernet frame it receives to/from specific ports to help the management interface figure out:

- what port is this frame coming from

- what was the reason why this frame got forwarded

- how to send CPU originated traffic to specific ports

The subsystem does support switches not capable of inserting/stripping tags, but the features might be slightly limited in that case (traffic separation relies on Port-based VLAN IDs).

Note that DSA does not currently create network interfaces for the "cpu" and "dsa" ports because:

- the "cpu" port is the Ethernet switch facing side of the management controller, and as such, would create a duplication of feature, since you would get two interfaces for the same conduit: conduit netdev, and "cpu" netdev

- the "dsa" port(s) are just conduits between two or more switches, and as such cannot really be used as proper network interfaces either, only the downstream, or the top-most upstream interface makes sense with that model

NB: for the past 15 years, the DSA subsystem had been making use of the terms "master" (rather than "conduit") and "slave" (rather than "user"). These terms have been removed from the DSA codebase and phased out of the uAPI.

<a id="rst-switch-tagging-protocols"></a>

### Switch tagging protocols

DSA supports many vendor-specific tagging protocols, one software-defined tagging protocol, and a tag-less mode as well (`DSA_TAG_PROTO_NONE`).

The exact format of the tag protocol is vendor specific, but in general, they all contain something which:

- identifies which port the Ethernet frame came from/should be sent to

- provides a reason why this frame was forwarded to the management interface

All tagging protocols are in `net/dsa/tag_*.c` files and implement the methods of the `struct dsa_device_ops` structure, which are detailed below.

Tagging protocols generally fall in one of three categories:

1. The switch-specific frame header is located before the Ethernet header, shifting to the right (from the perspective of the DSA conduit's frame parser) the MAC DA, MAC SA, EtherType and the entire L2 payload.

2. The switch-specific frame header is located before the EtherType, keeping the MAC DA and MAC SA in place from the DSA conduit's perspective, but shifting the 'real' EtherType and L2 payload to the right.

3. The switch-specific frame header is located at the tail of the packet, keeping all frame headers in place and not altering the view of the packet that the DSA conduit's frame parser has.

A tagging protocol may tag all packets with switch tags of the same length, or the tag length might vary (for example packets with PTP timestamps might require an extended switch tag, or there might be one tag length on TX and a different one on RX). Either way, the tagging protocol driver must populate the `struct dsa_device_ops::needed_headroom` and/or `struct dsa_device_ops::needed_tailroom` with the length in octets of the longest switch frame header/trailer. The DSA framework will automatically adjust the MTU of the conduit interface to accommodate for this extra size in order for DSA user ports to support the standard MTU (L2 payload length) of 1500 octets. The `needed_headroom` and `needed_tailroom` properties are also used to request from the network stack, on a best-effort basis, the allocation of packets with enough extra space such that the act of pushing the switch tag on transmission of a packet does not cause it to reallocate due to lack of memory.

Even though applications are not expected to parse DSA-specific frame headers, the format on the wire of the tagging protocol represents an Application Binary Interface exposed by the kernel towards user space, for decoders such as `libpcap`. The tagging protocol driver must populate the `proto` member of `struct dsa_device_ops` with a value that uniquely describes the characteristics of the interaction required between the switch hardware and the data path driver: the offset of each bit field within the frame header and any stateful processing required to deal with the frames (as may be required for PTP timestamping).

From the perspective of the network stack, all switches within the same DSA switch tree use the same tagging protocol. In case of a packet transiting a fabric with more than one switch, the switch-specific frame header is inserted by the first switch in the fabric that the packet was received on. This header typically contains information regarding its type (whether it is a control frame that must be trapped to the CPU, or a data frame to be forwarded). Control frames should be decapsulated only by the software data path, whereas data frames might also be autonomously forwarded towards other user ports of other switches from the same fabric, and in this case, the outermost switch ports must decapsulate the packet.

Note that in certain cases, it might be the case that the tagging format used by a leaf switch (not connected directly to the CPU) is not the same as what the network stack sees. This can be seen with Marvell switch trees, where the CPU port can be configured to use either the DSA or the Ethertype DSA (EDSA) format, but the DSA links are configured to use the shorter (without Ethertype) DSA frame header, in order to reduce the autonomous packet forwarding overhead. It still remains the case that, if the DSA switch tree is configured for the EDSA tagging protocol, the operating system sees EDSA-tagged packets from the leaf switches that tagged them with the shorter DSA header. This can be done because the Marvell switch connected directly to the CPU is configured to perform tag translation between DSA and EDSA (which is simply the operation of adding or removing the `ETH_P_EDSA` EtherType and some padding octets).

It is possible to construct cascaded setups of DSA switches even if their tagging protocols are not compatible with one another. In this case, there are no DSA links in this fabric, and each switch constitutes a disjoint DSA switch tree. The DSA links are viewed as simply a pair of a DSA conduit (the out-facing port of the upstream DSA switch) and a CPU port (the in-facing port of the downstream DSA switch).

The tagging protocol of the attached DSA switch tree can be viewed through the `dsa/tagging` sysfs attribute of the DSA conduit:



```text
cat /sys/class/net/eth0/dsa/tagging
```

If the hardware and driver are capable, the tagging protocol of the DSA switch tree can be changed at runtime. This is done by writing the new tagging protocol name to the same sysfs device attribute as above (the DSA conduit and all attached switch ports must be down while doing this).

It is desirable that all tagging protocols are testable with the `dsa_loop` mockup driver, which can be attached to any network interface. The goal is that any network interface should be capable of transmitting the same packet in the same way, and the tagger should decode the same received packet in the same way regardless of the driver used for the switch control path, and the driver used for the DSA conduit.

The transmission of a packet goes through the tagger's `xmit` function. The passed `struct sk_buff *skb` has `skb->data` pointing at `skb_mac_header(skb)`, i.e. at the destination MAC address, and the passed `struct net_device *dev` represents the virtual DSA user network interface whose hardware counterpart the packet must be steered to (i.e. `swp0`). The job of this method is to prepare the skb in a way that the switch will understand what egress port the packet is for (and not deliver it towards other ports). Typically this is fulfilled by pushing a frame header. Checking for insufficient size in the skb headroom or tailroom is unnecessary provided that the `needed_headroom` and `needed_tailroom` properties were filled out properly, because DSA ensures there is enough space before calling this method.

The reception of a packet goes through the tagger's `rcv` function. The passed `struct sk_buff *skb` has `skb->data` pointing at `skb_mac_header(skb) + ETH_ALEN` octets, i.e. to where the first octet after the EtherType would have been, were this frame not tagged. The role of this method is to consume the frame header, adjust `skb->data` to really point at the first octet after the EtherType, and to change `skb->dev` to point to the virtual DSA user network interface corresponding to the physical front-facing switch port that the packet was received on.

Since tagging protocols in category 1 and 2 break software (and most often also hardware) packet dissection on the DSA conduit, features such as RPS (Receive Packet Steering) on the DSA conduit would be broken. The DSA framework deals with this by hooking into the flow dissector and shifting the offset at which the IP header is to be found in the tagged frame as seen by the DSA conduit. This behavior is automatic based on the `overhead` value of the tagging protocol. If not all packets are of equal size, the tagger can implement the `flow_dissect` method of the `struct dsa_device_ops` and override this default behavior by specifying the correct offset incurred by each individual RX packet. Tail taggers do not cause issues to the flow dissector.

Checksum offload should work with category 1 and 2 taggers when the DSA conduit driver declares NETIF_F_HW_CSUM in vlan_features and looks at csum_start and csum_offset. For those cases, DSA will shift the checksum start and offset by the tag size. If the DSA conduit driver still uses the legacy NETIF_F_IP_CSUM or NETIF_F_IPV6_CSUM in vlan_features, the offload might only work if the offload hardware already expects that specific tag (perhaps due to matching vendors). DSA user ports inherit those flags from the conduit, and it is up to the driver to correctly fall back to software checksum when the IP header is not where the hardware expects. If that check is ineffective, the packets might go to the network without a proper checksum (the checksum field will have the pseudo IP header sum). For category 3, when the offload hardware does not already expect the switch tag in use, the checksum must be calculated before any tag is inserted (i.e. inside the tagger). Otherwise, the DSA conduit would include the tail tag in the (software or hardware) checksum calculation. Then, when the tag gets stripped by the switch during transmission, it will leave an incorrect IP checksum in place.

Due to various reasons (most common being category 1 taggers being associated with DSA-unaware conduits, mangling what the conduit perceives as MAC DA), the tagging protocol may require the DSA conduit to operate in promiscuous mode, to receive all frames regardless of the value of the MAC DA. This can be done by setting the `promisc_on_conduit` property of the `struct dsa_device_ops`. Note that this assumes a DSA-unaware conduit driver, which is the norm.

<a id="rst-conduit-network-devices"></a>

### Conduit network devices

Conduit network devices are regular, unmodified Linux network device drivers for the CPU/management Ethernet interface. Such a driver might occasionally need to know whether DSA is enabled (e.g.: to enable/disable specific offload features), but the DSA subsystem has been proven to work with industry standard drivers: `e1000e,` `mv643xx_eth` etc. without having to introduce modifications to these drivers. Such network devices are also often referred to as conduit network devices since they act as a pipe between the host processor and the hardware Ethernet switch.

<a id="rst-networking-stack-hooks"></a>

### Networking stack hooks

When a conduit netdev is used with DSA, a small hook is placed in the networking stack is in order to have the DSA subsystem process the Ethernet switch specific tagging protocol. DSA accomplishes this by registering a specific (and fake) Ethernet type (later becoming `skb->protocol`) with the networking stack, this is also known as a `ptype` or `packet_type`. A typical Ethernet Frame receive sequence looks like this:

Conduit network device (e.g.: e1000e):

1. Receive interrupt fires:

   > - receive function is invoked
   >
   > - basic packet processing is done: getting length, status etc.
   >
   > - packet is prepared to be processed by the Ethernet layer by calling `eth_type_trans`

2. net/ethernet/eth.c:



   ```text
   eth_type_trans(skb, dev)
           if (dev->dsa_ptr != NULL)
                   -> skb->protocol = ETH_P_XDSA
   ```

3. drivers/net/ethernet/\*:



   ```text
   netif_receive_skb(skb)
           -> iterate over registered packet_type
                   -> invoke handler for ETH_P_XDSA, calls dsa_switch_rcv()
   ```

4. net/dsa/dsa.c:



   ```text
   -> dsa_switch_rcv()
           -> invoke switch tag specific protocol handler in 'net/dsa/tag_*.c'
   ```

5. net/dsa/tag\_\*.c:

   > - inspect and strip switch tag protocol to determine originating port
   >
   > - locate per-port network device
   >
   > - invoke `eth_type_trans()` with the DSA user network device
   >
   > - invoked `netif_receive_skb()`

Past this point, the DSA user network devices get delivered regular Ethernet frames that can be processed by the networking stack.

<a id="rst-user-network-devices"></a>

### User network devices

User network devices created by DSA are stacked on top of their conduit network device, each of these network interfaces will be responsible for being a controlling and data-flowing end-point for each front-panel port of the switch. These interfaces are specialized in order to:

- insert/remove the switch tag protocol (if it exists) when sending traffic to/from specific switch ports

- query the switch for ethtool operations: statistics, link state, Wake-on-LAN, register dumps...

- manage external/internal PHY: link, auto-negotiation, etc.

These user network devices have custom net_device_ops and ethtool_ops function pointers which allow DSA to introduce a level of layering between the networking stack/ethtool and the switch driver implementation.

Upon frame transmission from these user network devices, DSA will look up which switch tagging protocol is currently registered with these network devices and invoke a specific transmit routine which takes care of adding the relevant switch tag in the Ethernet frames.

These frames are then queued for transmission using the conduit network device `ndo_start_xmit()` function. Since they contain the appropriate switch tag, the Ethernet switch will be able to process these incoming frames from the management interface and deliver them to the physical switch port.

When using multiple CPU ports, it is possible to stack a LAG (bonding/team) device between the DSA user devices and the physical DSA conduits. The LAG device is thus also a DSA conduit, but the LAG slave devices continue to be DSA conduits as well (just with no user port assigned to them; this is needed for recovery in case the LAG DSA conduit disappears). Thus, the data path of the LAG DSA conduit is used asymmetrically. On RX, the `ETH_P_XDSA` handler, which calls `dsa_switch_rcv()`, is invoked early (on the physical DSA conduit; LAG slave). Therefore, the RX data path of the LAG DSA conduit is not used. On the other hand, TX takes place linearly: `dsa_user_xmit` calls `dsa_enqueue_skb`, which calls `dev_queue_xmit` towards the LAG DSA conduit. The latter calls `dev_queue_xmit` towards one physical DSA conduit or the other, and in both cases, the packet exits the system through a hardware path towards the switch.

<a id="rst-graphical-representation"></a>

### Graphical representation

Summarized, this is basically how DSA looks like from a network device perspective:



```text
             Unaware application
           opens and binds socket
                    |  ^
                    |  |
        +-----------v--|--------------------+
        |+------+ +------+ +------+ +------+|
        || swp0 | | swp1 | | swp2 | | swp3 ||
        |+------+-+------+-+------+-+------+|
        |          DSA switch driver        |
        +-----------------------------------+
                      |        ^
         Tag added by |        | Tag consumed by
        switch driver |        | switch driver
                      v        |
        +-----------------------------------+
        | Unmodified host interface driver  | Software
--------+-----------------------------------+------------
        |       Host interface (eth0)       | Hardware
        +-----------------------------------+
                      |        ^
      Tag consumed by |        | Tag added by
      switch hardware |        | switch hardware
                      v        |
        +-----------------------------------+
        |               Switch              |
        |+------+ +------+ +------+ +------+|
        || swp0 | | swp1 | | swp2 | | swp3 ||
        ++------+-+------+-+------+-+------++
```

<a id="rst-user-mdio-bus"></a>

### User MDIO bus

In order to be able to read to/from a switch PHY built into it, DSA creates an user MDIO bus which allows a specific switch driver to divert and intercept MDIO reads/writes towards specific PHY addresses. In most MDIO-connected switches, these functions would utilize direct or indirect PHY addressing mode to return standard MII registers from the switch builtin PHYs, allowing the PHY library and/or to return link status, link partner pages, auto-negotiation results, etc.

For Ethernet switches which have both external and internal MDIO buses, the user MII bus can be utilized to mux/demux MDIO reads and writes towards either internal or external MDIO devices this switch might be connected to: internal PHYs, external PHYs, or even external switches.

<a id="rst-data-structures"></a>

### Data structures

DSA data structures are defined in `include/net/dsa.h` as well as `net/dsa/dsa_priv.h`:

- `dsa_chip_data`: platform data configuration for a given switch device, this structure describes a switch device's parent device, its address, as well as various properties of its ports: names/labels, and finally a routing table indication (when cascading switches)

- `dsa_platform_data`: platform device configuration data which can reference a collection of dsa_chip_data structures if multiple switches are cascaded, the conduit network device this switch tree is attached to needs to be referenced

- `dsa_switch_tree`: structure assigned to the conduit network device under `dsa_ptr`, this structure references a dsa_platform_data structure as well as the tagging protocol supported by the switch tree, and which receive/transmit function hooks should be invoked, information about the directly attached switch is also provided: CPU port. Finally, a collection of dsa_switch are referenced to address individual switches in the tree.

- `dsa_switch`: structure describing a switch device in the tree, referencing a `dsa_switch_tree` as a backpointer, user network devices, conduit network device, and a reference to the backing\`\`dsa_switch_ops\`\`

- `dsa_switch_ops`: structure referencing function pointers, see below for a full description.

<a id="rst-design-limitations"></a>

## Design limitations

<a id="rst-lack-of-cpu-dsa-network-devices"></a>

### Lack of CPU/DSA network devices

DSA does not currently create user network devices for the CPU or DSA ports, as described before. This might be an issue in the following cases:

- inability to fetch switch CPU port statistics counters using ethtool, which can make it harder to debug MDIO switch connected using xMII interfaces

- inability to configure the CPU port link parameters based on the Ethernet controller capabilities attached to it: [http://patchwork.ozlabs.org/patch/509806/](<http://patchwork.ozlabs.org/patch/509806/>)

- inability to configure specific VLAN IDs / trunking VLANs between switches when using a cascaded setup

<a id="rst-common-pitfalls-using-dsa-setups"></a>

### Common pitfalls using DSA setups

Once a conduit network device is configured to use DSA (dev-&gt;dsa_ptr becomes non-NULL), and the switch behind it expects a tagging protocol, this network interface can only exclusively be used as a conduit interface. Sending packets directly through this interface (e.g.: opening a socket using this interface) will not make us go through the switch tagging protocol transmit function, so the Ethernet switch on the other end, expecting a tag will typically drop this frame.

<a id="rst-interactions-with-other-subsystems"></a>

## Interactions with other subsystems

DSA currently leverages the following subsystems:

- MDIO/PHY library: `drivers/net/phy/phy.c`, `mdio_bus.c`

- Switchdev:`net/switchdev/*`

- Device Tree for various of\_\* functions

- Devlink: `net/core/devlink.c`

<a id="rst-mdio-phy-library"></a>

### MDIO/PHY library

User network devices exposed by DSA may or may not be interfacing with PHY devices (`struct phy_device` as defined in `include/linux/phy.h)`, but the DSA subsystem deals with all possible combinations:

- internal PHY devices, built into the Ethernet switch hardware

- external PHY devices, connected via an internal or external MDIO bus

- internal PHY devices, connected via an internal MDIO bus

- special, non-autonegotiated or non MDIO-managed PHY devices: SFPs, MoCA; a.k.a fixed PHYs

The PHY configuration is done by the `dsa_user_phy_setup()` function and the logic basically looks like this:

- if Device Tree is used, the PHY device is looked up using the standard "phy-handle" property, if found, this PHY device is created and registered using `of_phy_connect()`

- if Device Tree is used and the PHY device is "fixed", that is, conforms to the definition of a non-MDIO managed PHY as defined in `Documentation/devicetree/bindings/net/fixed-link.txt`, the PHY is registered and connected transparently using the special fixed MDIO bus driver

- finally, if the PHY is built into the switch, as is very common with standalone switch packages, the PHY is probed using the user MII bus created by DSA

<a id="rst-switchdev"></a>

### SWITCHDEV

DSA directly utilizes SWITCHDEV when interfacing with the bridge layer, and more specifically with its VLAN filtering portion when configuring VLANs on top of per-port user network devices. As of today, the only SWITCHDEV objects supported by DSA are the FDB and VLAN objects.

<a id="rst-devlink"></a>

### Devlink

DSA registers one devlink device per physical switch in the fabric. For each devlink device, every physical port (i.e. user ports, CPU ports, DSA links or unused ports) is exposed as a devlink port.

DSA drivers can make use of the following devlink features:

- Regions: debugging feature which allows user space to dump driver-defined areas of hardware information in a low-level, binary format. Both global regions as well as per-port regions are supported. It is possible to export devlink regions even for pieces of data that are already exposed in some way to the standard iproute2 user space programs (ip-link, bridge), like address tables and VLAN tables. For example, this might be useful if the tables contain additional hardware-specific details which are not visible through the iproute2 abstraction, or it might be useful to inspect these tables on the non-user ports too, which are invisible to iproute2 because no network interface is registered for them.

- Params: a feature which enables user to configure certain low-level tunable knobs pertaining to the device. Drivers may implement applicable generic devlink params, or may add new device-specific devlink params.

- Resources: a monitoring feature which enables users to see the degree of utilization of certain hardware tables in the device, such as FDB, VLAN, etc.

- Shared buffers: a QoS feature for adjusting and partitioning memory and frame reservations per port and per traffic class, in the ingress and egress directions, such that low-priority bulk traffic does not impede the processing of high-priority critical traffic.

For more details, consult `Documentation/networking/devlink/`.

<a id="rst-device-tree"></a>

### Device Tree

DSA features a standardized binding which is documented in `Documentation/devicetree/bindings/net/dsa/dsa.txt`. PHY/MDIO library helper functions such as `of_get_phy_mode()`, `of_phy_connect()` are also used to query per-port PHY specific details: interface connection, MDIO bus location, etc.

<a id="rst-driver-development"></a>

## Driver development

DSA switch drivers need to implement a `dsa_switch_ops` structure which will contain the various members described below.

<a id="rst-probing-registration-and-device-lifetime"></a>

### Probing, registration and device lifetime

DSA switches are regular `device` structures on buses (be they platform, SPI, I2C, MDIO or otherwise). The DSA framework is not involved in their probing with the device core.

Switch registration from the perspective of a driver means passing a valid `struct dsa_switch` pointer to `dsa_register_switch()`, usually from the switch driver's probing function. The following members must be valid in the provided structure:

- `ds->dev`: will be used to parse the switch's OF node or platform data.

- `ds->num_ports`: will be used to create the port list for this switch, and to validate the port indices provided in the OF node.

- `ds->ops`: a pointer to the `dsa_switch_ops` structure holding the DSA method implementations.

- `ds->priv`: backpointer to a driver-private data structure which can be retrieved in all further DSA method callbacks.

In addition, the following flags in the `dsa_switch` structure may optionally be configured to obtain driver-specific behavior from the DSA core. Their behavior when set is documented through comments in `include/net/dsa.h`.

- `ds->vlan_filtering_is_global`

- `ds->needs_standalone_vlan_filtering`

- `ds->configure_vlan_while_not_filtering`

- `ds->untag_bridge_pvid`

- `ds->assisted_learning_on_cpu_port`

- `ds->mtu_enforcement_ingress`

- `ds->fdb_isolation`

Internally, DSA keeps an array of switch trees (group of switches) global to the kernel, and attaches a `dsa_switch` structure to a tree on registration. The tree ID to which the switch is attached is determined by the first u32 number of the `dsa,member` property of the switch's OF node (0 if missing). The switch ID within the tree is determined by the second u32 number of the same OF property (0 if missing). Registering multiple switches with the same switch ID and tree ID is illegal and will cause an error. Using platform data, a single switch and a single switch tree is permitted.

In case of a tree with multiple switches, probing takes place asymmetrically. The first N-1 callers of `dsa_register_switch()` only add their ports to the port list of the tree (`dst->ports`), each port having a backpointer to its associated switch (`dp->ds`). Then, these switches exit their `dsa_register_switch()` call early, because `dsa_tree_setup_routing_table()` has determined that the tree is not yet complete (not all ports referenced by DSA links are present in the tree's port list). The tree becomes complete when the last switch calls `dsa_register_switch()`, and this triggers the effective continuation of initialization (including the call to `ds->ops->setup()`) for all switches within that tree, all as part of the calling context of the last switch's probe function.

The opposite of registration takes place when calling `dsa_unregister_switch()`, which removes a switch's ports from the port list of the tree. The entire tree is torn down when the first switch unregisters.

It is mandatory for DSA switch drivers to implement the `shutdown()` callback of their respective bus, and call `dsa_switch_shutdown()` from it (a minimal version of the full teardown performed by `dsa_unregister_switch()`). The reason is that DSA keeps a reference on the conduit net device, and if the driver for the conduit device decides to unbind on shutdown, DSA's reference will block that operation from finalizing.

Either `dsa_switch_shutdown()` or `dsa_unregister_switch()` must be called, but not both, and the device driver model permits the bus' `remove()` method to be called even if `shutdown()` was already called. Therefore, drivers are expected to implement a mutual exclusion method between `remove()` and `shutdown()` by setting their drvdata to NULL after any of these has run, and checking whether the drvdata is NULL before proceeding to take any action.

After `dsa_switch_shutdown()` or `dsa_unregister_switch()` was called, no further callbacks via the provided `dsa_switch_ops` may take place, and the driver may free the data structures associated with the `dsa_switch`.

<a id="rst-switch-configuration"></a>

### Switch configuration

- `get_tag_protocol`: this is to indicate what kind of tagging protocol is supported, should be a valid value from the `dsa_tag_protocol` enum. The returned information does not have to be static; the driver is passed the CPU port number, as well as the tagging protocol of a possibly stacked upstream switch, in case there are hardware limitations in terms of supported tag formats.

- `change_tag_protocol`: when the default tagging protocol has compatibility problems with the conduit or other issues, the driver may support changing it at runtime, either through a device tree property or through sysfs. In that case, further calls to `get_tag_protocol` should report the protocol in current use.

- `setup`: setup function for the switch, this function is responsible for setting up the `dsa_switch_ops` private structure with all it needs: register maps, interrupts, mutexes, locks, etc. This function is also expected to properly configure the switch to separate all network interfaces from each other, that is, they should be isolated by the switch hardware itself, typically by creating a Port-based VLAN ID for each port and allowing only the CPU port and the specific port to be in the forwarding vector. Ports that are unused by the platform should be disabled. Past this function, the switch is expected to be fully configured and ready to serve any kind of request. It is recommended to issue a software reset of the switch during this setup function in order to avoid relying on what a previous software agent such as a bootloader/firmware may have previously configured. The method responsible for undoing any applicable allocations or operations done here is `teardown`.

- `port_setup` and `port_teardown`: methods for initialization and destruction of per-port data structures. It is mandatory for some operations such as registering and unregistering devlink port regions to be done from these methods, otherwise they are optional. A port will be torn down only if it has been previously set up. It is possible for a port to be set up during probing only to be torn down immediately afterwards, for example in case its PHY cannot be found. In this case, probing of the DSA switch continues without that particular port.

- `port_change_conduit`: method through which the affinity (association used for traffic termination purposes) between a user port and a CPU port can be changed. By default all user ports from a tree are assigned to the first available CPU port that makes sense for them (most of the times this means the user ports of a tree are all assigned to the same CPU port, except for H topologies as described in commit 2c0b03258b8b). The `port` argument represents the index of the user port, and the `conduit` argument represents the new DSA conduit `net_device`. The CPU port associated with the new conduit can be retrieved by looking at `struct dsa_port *cpu_dp = conduit->dsa_ptr`. Additionally, the conduit can also be a LAG device where all the slave devices are physical DSA conduits. LAG DSA  also have a valid `conduit->dsa_ptr` pointer, however this is not unique, but rather a duplicate of the first physical DSA conduit's (LAG slave) `dsa_ptr`. In case of a LAG DSA conduit, a further call to `port_lag_join` will be emitted separately for the physical CPU ports associated with the physical DSA conduits, requesting them to create a hardware LAG associated with the LAG interface.

<a id="rst-phy-devices-and-link-management"></a>

### PHY devices and link management

- `get_phy_flags`: Some switches are interfaced to various kinds of Ethernet PHYs, if the PHY library PHY driver needs to know about information it cannot obtain on its own (e.g.: coming from switch memory mapped registers), this function should return a 32-bit bitmask of "flags" that is private between the switch driver and the Ethernet PHY driver in `drivers/net/phy/\*`.

- `phy_read`: Function invoked by the DSA user MDIO bus when attempting to read the switch port MDIO registers. If unavailable, return 0xffff for each read. For builtin switch Ethernet PHYs, this function should allow reading the link status, auto-negotiation results, link partner pages, etc.

- `phy_write`: Function invoked by the DSA user MDIO bus when attempting to write to the switch port MDIO registers. If unavailable return a negative error code.

- `adjust_link`: Function invoked by the PHY library when a user network device is attached to a PHY device. This function is responsible for appropriately configuring the switch port link parameters: speed, duplex, pause based on what the `phy_device` is providing.

- `fixed_link_update`: Function invoked by the PHY library, and specifically by the fixed PHY driver asking the switch driver for link parameters that could not be auto-negotiated, or obtained by reading the PHY registers through MDIO. This is particularly useful for specific kinds of hardware such as QSGMII, MoCA or other kinds of non-MDIO managed PHYs where out of band link information is obtained

<a id="rst-ethtool-operations"></a>

### Ethtool operations

- `get_strings`: ethtool function used to query the driver's strings, will typically return statistics strings, private flags strings, etc.

- `get_ethtool_stats`: ethtool function used to query per-port statistics and return their values. DSA overlays user network devices general statistics: RX/TX counters from the network device, with switch driver specific statistics per port

- `get_sset_count`: ethtool function used to query the number of statistics items

- `get_wol`: ethtool function used to obtain Wake-on-LAN settings per-port, this function may for certain implementations also query the conduit network device Wake-on-LAN settings if this interface needs to participate in Wake-on-LAN

- `set_wol`: ethtool function used to configure Wake-on-LAN settings per-port, direct counterpart to set_wol with similar restrictions

- `set_eee`: ethtool function which is used to configure a switch port EEE (Green Ethernet) settings, can optionally invoke the PHY library to enable EEE at the PHY level if relevant. This function should enable EEE at the switch port MAC controller and data-processing logic

- `get_eee`: ethtool function which is used to query a switch port EEE settings, this function should return the EEE state of the switch port MAC controller and data-processing logic as well as query the PHY for its currently configured EEE settings

- `get_eeprom_len`: ethtool function returning for a given switch the EEPROM length/size in bytes

- `get_eeprom`: ethtool function returning for a given switch the EEPROM contents

- `set_eeprom`: ethtool function writing specified data to a given switch EEPROM

- `get_regs_len`: ethtool function returning the register length for a given switch

- `get_regs`: ethtool function returning the Ethernet switch internal register contents. This function might require user-land code in ethtool to pretty-print register values and registers

<a id="rst-power-management"></a>

### Power management

- `suspend`: function invoked by the DSA platform device when the system goes to suspend, should quiesce all Ethernet switch activities, but keep ports participating in Wake-on-LAN active as well as additional wake-up logic if supported

- `resume`: function invoked by the DSA platform device when the system resumes, should resume all Ethernet switch activities and re-configure the switch to be in a fully active state

- `port_enable`: function invoked by the DSA user network device ndo_open function when a port is administratively brought up, this function should fully enable a given switch port. DSA takes care of marking the port with `BR_STATE_BLOCKING` if the port is a bridge member, or `BR_STATE_FORWARDING` if it was not, and propagating these changes down to the hardware

- `port_disable`: function invoked by the DSA user network device ndo_close function when a port is administratively brought down, this function should fully disable a given switch port. DSA takes care of marking the port with `BR_STATE_DISABLED` and propagating changes to the hardware if this port is disabled while being a bridge member

<a id="rst-address-databases"></a>

### Address databases

Switching hardware is expected to have a table for FDB entries, however not all of them are active at the same time. An address database is the subset (partition) of FDB entries that is active (can be matched by address learning on RX, or FDB lookup on TX) depending on the state of the port. An address database may occasionally be called "FID" (Filtering ID) in this document, although the underlying implementation may choose whatever is available to the hardware.

For example, all ports that belong to a VLAN-unaware bridge (which is *currently* VLAN-unaware) are expected to learn source addresses in the database associated by the driver with that bridge (and not with other VLAN-unaware bridges). During forwarding and FDB lookup, a packet received on a VLAN-unaware bridge port should be able to find a VLAN-unaware FDB entry having the same MAC DA as the packet, which is present on another port member of the same bridge. At the same time, the FDB lookup process must be able to not find an FDB entry having the same MAC DA as the packet, if that entry points towards a port which is a member of a different VLAN-unaware bridge (and is therefore associated with a different address database).

Similarly, each VLAN of each offloaded VLAN-aware bridge should have an associated address database, which is shared by all ports which are members of that VLAN, but not shared by ports belonging to different bridges that are members of the same VID.

In this context, a VLAN-unaware database means that all packets are expected to match on it irrespective of VLAN ID (only MAC address lookup), whereas a VLAN-aware database means that packets are supposed to match based on the VLAN ID from the classified 802.1Q header (or the pvid if untagged).

At the bridge layer, VLAN-unaware FDB entries have the special VID value of 0, whereas VLAN-aware FDB entries have non-zero VID values. Note that a VLAN-unaware bridge may have VLAN-aware (non-zero VID) FDB entries, and a VLAN-aware bridge may have VLAN-unaware FDB entries. As in hardware, the software bridge keeps separate address databases, and offloads to hardware the FDB entries belonging to these databases, through switchdev, asynchronously relative to the moment when the databases become active or inactive.

When a user port operates in standalone mode, its driver should configure it to use a separate database called a port private database. This is different from the databases described above, and should impede operation as standalone port (packet in, packet out to the CPU port) as little as possible. For example, on ingress, it should not attempt to learn the MAC SA of ingress traffic, since learning is a bridging layer service and this is a standalone port, therefore it would consume useless space. With no address learning, the port private database should be empty in a naive implementation, and in this case, all received packets should be trivially flooded to the CPU port.

DSA (cascade) and CPU ports are also called "shared" ports because they service multiple address databases, and the database that a packet should be associated to is usually embedded in the DSA tag. This means that the CPU port may simultaneously transport packets coming from a standalone port (which were classified by hardware in one address database), and from a bridge port (which were classified to a different address database).

Switch drivers which satisfy certain criteria are able to optimize the naive configuration by removing the CPU port from the flooding domain of the switch, and just program the hardware with FDB entries pointing towards the CPU port for which it is known that software is interested in those MAC addresses. Packets which do not match a known FDB entry will not be delivered to the CPU, which will save CPU cycles required for creating an skb just to drop it.

DSA is able to perform host address filtering for the following kinds of addresses:

- Primary unicast MAC addresses of ports (`dev->dev_addr`). These are associated with the port private database of the respective user port, and the driver is notified to install them through `port_fdb_add` towards the CPU port.

- Secondary unicast and multicast MAC addresses of ports (addresses added through `dev_uc_add()` and `dev_mc_add()`). These are also associated with the port private database of the respective user port.

- Local/permanent bridge FDB entries (`BR_FDB_LOCAL`). These are the MAC addresses of the bridge ports, for which packets must be terminated locally and not forwarded. They are associated with the address database for that bridge.

- Static bridge FDB entries installed towards foreign (non-DSA) interfaces present in the same bridge as some DSA switch ports. These are also associated with the address database for that bridge.

- Dynamically learned FDB entries on foreign interfaces present in the same bridge as some DSA switch ports, only if `ds->assisted_learning_on_cpu_port` is set to true by the driver. These are associated with the address database for that bridge.

For various operations detailed below, DSA provides a `dsa_db` structure which can be of the following types:

- `DSA_DB_PORT`: the FDB (or MDB) entry to be installed or deleted belongs to the port private database of user port `db->dp`.

- `DSA_DB_BRIDGE`: the entry belongs to one of the address databases of bridge `db->bridge`. Separation between the VLAN-unaware database and the per-VID databases of this bridge is expected to be done by the driver.

- `DSA_DB_LAG`: the entry belongs to the address database of LAG `db->lag`. Note: `DSA_DB_LAG` is currently unused and may be removed in the future.

The drivers which act upon the `dsa_db` argument in `port_fdb_add`, `port_mdb_add` etc should declare `ds->fdb_isolation` as true.

DSA associates each offloaded bridge and each offloaded LAG with a one-based ID (`struct dsa_bridge :: num`, `struct dsa_lag :: id`) for the purposes of refcounting addresses on shared ports. Drivers may piggyback on DSA's numbering scheme (the ID is readable through `db->bridge.num` and `db->lag.id` or may implement their own.

Only the drivers which declare support for FDB isolation are notified of FDB entries on the CPU port belonging to `DSA_DB_PORT` databases. For compatibility/legacy reasons, `DSA_DB_BRIDGE` addresses are notified to drivers even if they do not support FDB isolation. However, `db->bridge.num` and `db->lag.id` are always set to 0 in that case (to denote the lack of isolation, for refcounting purposes).

Note that it is not mandatory for a switch driver to implement physically separate address databases for each standalone user port. Since FDB entries in the port private databases will always point to the CPU port, there is no risk for incorrect forwarding decisions. In this case, all standalone ports may share the same database, but the reference counting of host-filtered addresses (not deleting the FDB entry for a port's MAC address if it's still in use by another port) becomes the responsibility of the driver, because DSA is unaware that the port databases are in fact shared. This can be achieved by calling `dsa_fdb_present_in_other_db()` and `dsa_mdb_present_in_other_db()`. The down side is that the RX filtering lists of each user port are in fact shared, which means that user port A may accept a packet with a MAC DA it shouldn't have, only because that MAC address was in the RX filtering list of user port B. These packets will still be dropped in software, however.

<a id="rst-bridge-layer"></a>

### Bridge layer

Offloading the bridge forwarding plane is optional and handled by the methods below. They may be absent, return -EOPNOTSUPP, or `ds->max_num_bridges` may be non-zero and exceeded, and in this case, joining a bridge port is still possible, but the packet forwarding will take place in software, and the ports under a software bridge must remain configured in the same way as for standalone operation, i.e. have all bridging service functions (address learning etc) disabled, and send all received packets to the CPU port only.

Concretely, a port starts offloading the forwarding plane of a bridge once it returns success to the `port_bridge_join` method, and stops doing so after `port_bridge_leave` has been called. Offloading the bridge means autonomously learning FDB entries in accordance with the software bridge port's state, and autonomously forwarding (or flooding) received packets without CPU intervention. This is optional even when offloading a bridge port. Tagging protocol drivers are expected to call `dsa_default_offload_fwd_mark(skb)` for packets which have already been autonomously forwarded in the forwarding domain of the ingress switch port. DSA, through `dsa_port_devlink_setup()`, considers all switch ports part of the same tree ID to be part of the same bridge forwarding domain (capable of autonomous forwarding to each other).

Offloading the TX forwarding process of a bridge is a distinct concept from simply offloading its forwarding plane, and refers to the ability of certain driver and tag protocol combinations to transmit a single skb coming from the bridge device's transmit function to potentially multiple egress ports (and thereby avoid its cloning in software).

Packets for which the bridge requests this behavior are called data plane packets and have `skb->offload_fwd_mark` set to true in the tag protocol driver's `xmit` function. Data plane packets are subject to FDB lookup, hardware learning on the CPU port, and do not override the port STP state. Additionally, replication of data plane packets (multicast, flooding) is handled in hardware and the bridge driver will transmit a single skb for each packet that may or may not need replication.

When the TX forwarding offload is enabled, the tag protocol driver is responsible to inject packets into the data plane of the hardware towards the correct bridging domain (FID) that the port is a part of. The port may be VLAN-unaware, and in this case the FID must be equal to the FID used by the driver for its VLAN-unaware address database associated with that bridge. Alternatively, the bridge may be VLAN-aware, and in that case, it is guaranteed that the packet is also VLAN-tagged with the VLAN ID that the bridge processed this packet in. It is the responsibility of the hardware to untag the VID on the egress-untagged ports, or keep the tag on the egress-tagged ones.

- `port_bridge_join`: bridge layer function invoked when a given switch port is added to a bridge, this function should do what's necessary at the switch level to permit the joining port to be added to the relevant logical domain for it to ingress/egress traffic with other members of the bridge. By setting the `tx_fwd_offload` argument to true, the TX forwarding process of this bridge is also offloaded.

- `port_bridge_leave`: bridge layer function invoked when a given switch port is removed from a bridge, this function should do what's necessary at the switch level to deny the leaving port from ingress/egress traffic from the remaining bridge members.

- `port_stp_state_set`: bridge layer function invoked when a given switch port STP state is computed by the bridge layer and should be propagated to switch hardware to forward/block/learn traffic.

- `port_bridge_flags`: bridge layer function invoked when a port must configure its settings for e.g. flooding of unknown traffic or source address learning. The switch driver is responsible for initial setup of the standalone ports with address learning disabled and egress flooding of all types of traffic, then the DSA core notifies of any change to the bridge port flags when the port joins and leaves a bridge. DSA does not currently manage the bridge port flags for the CPU port. The assumption is that address learning should be statically enabled (if supported by the hardware) on the CPU port, and flooding towards the CPU port should also be enabled, due to a lack of an explicit address filtering mechanism in the DSA core.

- `port_fast_age`: bridge layer function invoked when flushing the dynamically learned FDB entries on the port is necessary. This is called when transitioning from an STP state where learning should take place to an STP state where it shouldn't, or when leaving a bridge, or when address learning is turned off via `port_bridge_flags`.

<a id="rst-bridge-vlan-filtering"></a>

### Bridge VLAN filtering

- `port_vlan_filtering`: bridge layer function invoked when the bridge gets configured for turning on or off VLAN filtering. If nothing specific needs to be done at the hardware level, this callback does not need to be implemented. When VLAN filtering is turned on, the hardware must be programmed with rejecting 802.1Q frames which have VLAN IDs outside of the programmed allowed VLAN ID map/rules.  If there is no PVID programmed into the switch port, untagged frames must be rejected as well. When turned off the switch must accept any 802.1Q frames irrespective of their VLAN ID, and untagged frames are allowed.

- `port_vlan_add`: bridge layer function invoked when a VLAN is configured (tagged or untagged) for the given switch port. The CPU port becomes a member of a VLAN only if a foreign bridge port is also a member of it (and forwarding needs to take place in software), or the VLAN is installed to the VLAN group of the bridge device itself, for termination purposes (`bridge vlan add dev br0 vid 100 self`). VLANs on shared ports are reference counted and removed when there is no user left. Drivers do not need to manually install a VLAN on the CPU port.

- `port_vlan_del`: bridge layer function invoked when a VLAN is removed from the given switch port

- `port_fdb_add`: bridge layer function invoked when the bridge wants to install a Forwarding Database entry, the switch hardware should be programmed with the specified address in the specified VLAN Id in the forwarding database associated with this VLAN ID.

- `port_fdb_del`: bridge layer function invoked when the bridge wants to remove a Forwarding Database entry, the switch hardware should be programmed to delete the specified MAC address from the specified VLAN ID if it was mapped into this port forwarding database

- `port_fdb_dump`: bridge bypass function invoked by `ndo_fdb_dump` on the physical DSA port interfaces. Since DSA does not attempt to keep in sync its hardware FDB entries with the software bridge, this method is implemented as a means to view the entries visible on user ports in the hardware database. The entries reported by this function have the `self` flag in the output of the `bridge fdb show` command.

- `port_mdb_add`: bridge layer function invoked when the bridge wants to install a multicast database entry. The switch hardware should be programmed with the specified address in the specified VLAN ID in the forwarding database associated with this VLAN ID.

- `port_mdb_del`: bridge layer function invoked when the bridge wants to remove a multicast database entry, the switch hardware should be programmed to delete the specified MAC address from the specified VLAN ID if it was mapped into this port forwarding database.

<a id="rst-link-aggregation"></a>

### Link aggregation

Link aggregation is implemented in the Linux networking stack by the bonding and team drivers, which are modeled as virtual, stackable network interfaces. DSA is capable of offloading a link aggregation group (LAG) to hardware that supports the feature, and supports bridging between physical ports and LAGs, as well as between LAGs. A bonding/team interface which holds multiple physical ports constitutes a logical port, although DSA has no explicit concept of a logical port at the moment. Due to this, events where a LAG joins/leaves a bridge are treated as if all individual physical ports that are members of that LAG join/leave the bridge. Switchdev port attributes (VLAN filtering, STP state, etc) and objects (VLANs, MDB entries) offloaded to a LAG as bridge port are treated similarly: DSA offloads the same switchdev object / port attribute on all members of the LAG. Static bridge FDB entries on a LAG are not yet supported, since the DSA driver API does not have the concept of a logical port ID.

- `port_lag_join`: function invoked when a given switch port is added to a LAG. The driver may return `-EOPNOTSUPP`, and in this case, DSA will fall back to a software implementation where all traffic from this port is sent to the CPU.

- `port_lag_leave`: function invoked when a given switch port leaves a LAG and returns to operation as a standalone port.

- `port_lag_change`: function invoked when the link state of any member of the LAG changes, and the hashing function needs rebalancing to only make use of the subset of physical LAG member ports that are up.

Drivers that benefit from having an ID associated with each offloaded LAG can optionally populate `ds->num_lag_ids` from the `dsa_switch_ops::setup` method. The LAG ID associated with a bonding/team interface can then be retrieved by a DSA switch driver using the `dsa_lag_id` function.

<a id="rst-iec-62439-2-mrp"></a>

### IEC 62439-2 (MRP)

The Media Redundancy Protocol is a topology management protocol optimized for fast fault recovery time for ring networks, which has some components implemented as a function of the bridge driver. MRP uses management PDUs (Test, Topology, LinkDown/Up, Option) sent at a multicast destination MAC address range of 01:15:4e:00:00:0x and with an EtherType of 0x88e3. Depending on the node's role in the ring (MRM: Media Redundancy Manager, MRC: Media Redundancy Client, MRA: Media Redundancy Automanager), certain MRP PDUs might need to be terminated locally and others might need to be forwarded. An MRM might also benefit from offloading to hardware the creation and transmission of certain MRP PDUs (Test).

Normally an MRP instance can be created on top of any network interface, however in the case of a device with an offloaded data path such as DSA, it is necessary for the hardware, even if it is not MRP-aware, to be able to extract the MRP PDUs from the fabric before the driver can proceed with the software implementation. DSA today has no driver which is MRP-aware, therefore it only listens for the bare minimum switchdev objects required for the software assist to work properly. The operations are detailed below.

- `port_mrp_add` and `port_mrp_del`: notifies driver when an MRP instance with a certain ring ID, priority, primary port and secondary port is created/deleted.

- `port_mrp_add_ring_role` and `port_mrp_del_ring_role`: function invoked when an MRP instance changes ring roles between MRM or MRC. This affects which MRP PDUs should be trapped to software and which should be autonomously forwarded.

<a id="rst-iec-62439-3-hsr-prp"></a>

### IEC 62439-3 (HSR/PRP)

The Parallel Redundancy Protocol (PRP) is a network redundancy protocol which works by duplicating and sequence numbering packets through two independent L2 networks (which are unaware of the PRP tail tags carried in the packets), and eliminating the duplicates at the receiver. The High-availability Seamless Redundancy (HSR) protocol is similar in concept, except all nodes that carry the redundant traffic are aware of the fact that it is HSR-tagged (because HSR uses a header with an EtherType of 0x892f) and are physically connected in a ring topology. Both HSR and PRP use supervision frames for monitoring the health of the network and for discovery of other nodes.

In Linux, both HSR and PRP are implemented in the hsr driver, which instantiates a virtual, stackable network interface with two member ports. The driver only implements the basic roles of DANH (Doubly Attached Node implementing HSR), DANP (Doubly Attached Node implementing PRP) and RedBox (allows non-HSR devices to connect to the ring via Interlink ports).

A driver which is able of offloading certain functions should declare the corresponding netdev features as indicated by the documentation at `Documentation/networking/netdev-features.rst`. Additionally, the following methods must be implemented:

- `port_hsr_join`: function invoked when a given switch port is added to a DANP/DANH. The driver may return `-EOPNOTSUPP` and in this case, DSA will fall back to a software implementation where all traffic from this port is sent to the CPU.

- `port_hsr_leave`: function invoked when a given switch port leaves a DANP/DANH and returns to normal operation as a standalone port.

Note that the `NETIF_F_HW_HSR_DUP` feature relies on transmission towards multiple ports, which is generally available whenever the tagging protocol uses the `dsa_xmit_port_mask()` helper function. If the helper is used, the HSR offload feature should also be set. The `dsa_port_simple_hsr_join()` and `dsa_port_simple_hsr_leave()` methods can be used as generic implementations of `port_hsr_join` and `port_hsr_leave`, if this is the only supported offload feature.

<a id="rst-todo"></a>

## TODO

<a id="rst-making-switchdev-and-dsa-converge-towards-an-unified-codebase"></a>

### Making SWITCHDEV and DSA converge towards an unified codebase

SWITCHDEV properly takes care of abstracting the networking stack with offload capable hardware, but does not enforce a strict switch device driver model. On the other DSA enforces a fairly strict device driver model, and deals with most of the switch specific. At some point we should envision a merger between these two subsystems and get the best of both worlds.

---

# LAN9303 Ethernet switch driver

_Peios Kernel / Internals / Networking / dsa_

> The LAN9303 is a three port 10/100 Mbps ethernet switch with integrated phys for the two external ethernet ports. The third port is an RMII/MII interface to a host conduit network interface (e.g. fixed link).

<a id="rst-lan9303-ethernet-switch-driver"></a>

The LAN9303 is a three port 10/100 Mbps ethernet switch with integrated phys for the two external ethernet ports. The third port is an RMII/MII interface to a host conduit network interface (e.g. fixed link).

<a id="rst-driver-details"></a>

## Driver details

The driver is implemented as a DSA driver, see `Documentation/networking/dsa/dsa.rst`.

See `Documentation/devicetree/bindings/net/dsa/lan9303.txt` for device tree binding.

The LAN9303 can be managed both via MDIO and I2C, both supported by this driver.

At startup the driver configures the device to provide two separate network interfaces (which is the default state of a DSA device). Due to HW limitations, no HW MAC learning takes place in this mode.

When both user ports are joined to the same bridge, the normal HW MAC learning is enabled. This means that unicast traffic is forwarded in HW. Broadcast and multicast is flooded in HW. STP is also supported in this mode. The driver support fdb/mdb operations as well, meaning IGMP snooping is supported.

If one of the user ports leave the bridge, the ports goes back to the initial separated operation.

<a id="rst-driver-limitations"></a>

## Driver limitations

> - Support for VLAN filtering is not implemented
>
> - The HW does not support VLAN-specific fdb entries

---

# NXP SJA1105 switch driver

_Peios Kernel / Internals / Networking / dsa_

> The NXP SJA1105 is a family of 10 SPI-managed automotive switches:

<a id="rst-nxp-sja1105-switch-driver"></a>

<a id="rst-overview"></a>

## Overview

The NXP SJA1105 is a family of 10 SPI-managed automotive switches:

- SJA1105E: First generation, no TTEthernet

- SJA1105T: First generation, TTEthernet

- SJA1105P: Second generation, no TTEthernet, no SGMII

- SJA1105Q: Second generation, TTEthernet, no SGMII

- SJA1105R: Second generation, no TTEthernet, SGMII

- SJA1105S: Second generation, TTEthernet, SGMII

- SJA1110A: Third generation, TTEthernet, SGMII, integrated 100base-T1 and 100base-TX PHYs

- SJA1110B: Third generation, TTEthernet, SGMII, 100base-T1, 100base-TX

- SJA1110C: Third generation, TTEthernet, SGMII, 100base-T1, 100base-TX

- SJA1110D: Third generation, TTEthernet, SGMII, 100base-T1

Being automotive parts, their configuration interface is geared towards set-and-forget use, with minimal dynamic interaction at runtime. They require a static configuration to be composed by software and packed with CRC and table headers, and sent over SPI.

The static configuration is composed of several configuration tables. Each table takes a number of entries. Some configuration tables can be (partially) reconfigured at runtime, some not. Some tables are mandatory, some not:


<table>
<thead>
<tr>
<th>


Table

</th>
<th>


Mandatory

</th>
<th>


Reconfigurable

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Schedule

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Schedule entry points

</td>
<td>


if Scheduling

</td>
<td>


no

</td>
</tr>
<tr>
<td>


VL Lookup

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


VL Policing

</td>
<td>


if VL Lookup

</td>
<td>


no

</td>
</tr>
<tr>
<td>


VL Forwarding

</td>
<td>


if VL Lookup

</td>
<td>


no

</td>
</tr>
<tr>
<td>


L2 Lookup

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


L2 Policing

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


VLAN Lookup

</td>
<td>


yes

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


L2 Forwarding

</td>
<td>


yes

</td>
<td>


partially (fully on P/Q/R/S)

</td>
</tr>
<tr>
<td>


MAC Config

</td>
<td>


yes

</td>
<td>


partially (fully on P/Q/R/S)

</td>
</tr>
<tr>
<td>


Schedule Params

</td>
<td>


if Scheduling

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Schedule Entry Points Params

</td>
<td>


if Scheduling

</td>
<td>


no

</td>
</tr>
<tr>
<td>


VL Forwarding Params

</td>
<td>


if VL Forwarding

</td>
<td>


no

</td>
</tr>
<tr>
<td>


L2 Lookup Params

</td>
<td>


no

</td>
<td>


partially (fully on P/Q/R/S)

</td>
</tr>
<tr>
<td>


L2 Forwarding Params

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


Clock Sync Params

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


AVB Params

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


General Params

</td>
<td>


yes

</td>
<td>


partially

</td>
</tr>
<tr>
<td>


Retagging

</td>
<td>


no

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


xMII Params

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
<tr>
<td>


SGMII

</td>
<td>


no

</td>
<td>


yes

</td>
</tr>
</tbody>
</table>

Also the configuration is write-only (software cannot read it back from the switch except for very few exceptions).

The driver creates a static configuration at probe time, and keeps it at all times in memory, as a shadow for the hardware state. When required to change a hardware setting, the static configuration is also updated. If that changed setting can be transmitted to the switch through the dynamic reconfiguration interface, it is; otherwise the switch is reset and reprogrammed with the updated static configuration.

<a id="rst-switching-features"></a>

## Switching features

The driver supports the configuration of L2 forwarding rules in hardware for port bridging. The forwarding, broadcast and flooding domain between ports can be restricted through two methods: either at the L2 forwarding level (isolate one bridge's ports from another's) or at the VLAN port membership level (isolate ports within the same bridge). The final forwarding decision taken by the hardware is a logical AND of these two sets of rules.

The hardware tags all traffic internally with a port-based VLAN (pvid), or it decodes the VLAN information from the 802.1Q tag. Advanced VLAN classification is not possible. Once attributed a VLAN tag, frames are checked against the port's membership rules and dropped at ingress if they don't match any VLAN. This behavior is available when switch ports join a bridge with `vlan_filtering 1`.

Normally the hardware is not configurable with respect to VLAN awareness, but by changing what TPID the switch searches 802.1Q tags for, the semantics of a bridge with `vlan_filtering 0` can be kept (accept all traffic, tagged or untagged), and therefore this mode is also supported.

Segregating the switch ports in multiple bridges is supported (e.g. 2 + 2), but all bridges should have the same level of VLAN awareness (either both have `vlan_filtering` 0, or both 1).

Topology and loop detection through STP is supported.

<a id="rst-offloads"></a>

## Offloads

<a id="rst-time-aware-scheduling"></a>

### Time-aware scheduling

The switch supports a variation of the enhancements for scheduled traffic specified in IEEE 802.1Q-2018 (formerly 802.1Qbv). This means it can be used to ensure deterministic latency for priority traffic that is sent in-band with its gate-open event in the network schedule.

This capability can be managed through the tc-taprio offload ('flags 2'). The difference compared to the software implementation of taprio is that the latter would only be able to shape traffic originated from the CPU, but not autonomously forwarded flows.

The device has 8 traffic classes, and maps incoming frames to one of them based on the VLAN PCP bits (if no VLAN is present, the port-based default is used). As described in the previous sections, depending on the value of `vlan_filtering`, the EtherType recognized by the switch as being VLAN can either be the typical 0x8100 or a custom value used internally by the driver for tagging. Therefore, the switch ignores the VLAN PCP if used in standalone or bridge mode with `vlan_filtering=0`, as it will not recognize the 0x8100 EtherType. In these modes, injecting into a particular TX queue can only be done by the DSA net devices, which populate the PCP field of the tagging header on egress. Using `vlan_filtering=1`, the behavior is the other way around: offloaded flows can be steered to TX queues based on the VLAN PCP, but the DSA net devices are no longer able to do that. To inject frames into a hardware TX queue with VLAN awareness active, it is necessary to create a VLAN sub-interface on the DSA conduit port, and send normal (0x8100) VLAN-tagged towards the switch, with the VLAN PCP bits set appropriately.

Management traffic (having DMAC 01-80-C2-xx-xx-xx or 01-19-1B-xx-xx-xx) is the notable exception: the switch always treats it with a fixed priority and disregards any VLAN PCP bits even if present. The traffic class for management traffic has a value of 7 (highest priority) at the moment, which is not configurable in the driver.

Below is an example of configuring a 500 us cyclic schedule on egress port `swp5`. The traffic class gate for management traffic (7) is open for 100 us, and the gates for all other traffic classes are open for 400 us:



```text
#!/bin/bash

set -e -u -o pipefail

NSEC_PER_SEC="1000000000"

gatemask() {
        local tc_list="$1"
        local mask=0

        for tc in ${tc_list}; do
                mask=$((${mask} | (1 << ${tc})))
        done

        printf "%02x" ${mask}
}

if ! systemctl is-active --quiet ptp4l; then
        echo "Please start the ptp4l service"
        exit
fi

now=$(phc_ctl /dev/ptp1 get | gawk '/clock time is/ { print $5; }')
# Phase-align the base time to the start of the next second.
sec=$(echo "${now}" | gawk -F. '{ print $1; }')
base_time="$(((${sec} + 1) * ${NSEC_PER_SEC}))"

tc qdisc add dev swp5 parent root handle 100 taprio \
        num_tc 8 \
        map 0 1 2 3 5 6 7 \
        queues 1@0 1@1 1@2 1@3 1@4 1@5 1@6 1@7 \
        base-time ${base_time} \
        sched-entry S $(gatemask 7) 100000 \
        sched-entry S $(gatemask "0 1 2 3 4 5 6") 400000 \
        flags 2
```

It is possible to apply the tc-taprio offload on multiple egress ports. There are hardware restrictions related to the fact that no gate event may trigger simultaneously on two ports. The driver checks the consistency of the schedules against this restriction and errors out when appropriate. Schedule analysis is needed to avoid this, which is outside the scope of the document.

<a id="rst-routing-actions-redirect-trap-drop"></a>

### Routing actions (redirect, trap, drop)

The switch is able to offload flow-based redirection of packets to a set of destination ports specified by the user. Internally, this is implemented by making use of Virtual Links, a TTEthernet concept.

The driver supports 2 types of keys for Virtual Links:

- VLAN-aware virtual links: these match on destination MAC address, VLAN ID and VLAN PCP.

- VLAN-unaware virtual links: these match on destination MAC address only.

The VLAN awareness state of the bridge (vlan_filtering) cannot be changed while there are virtual link rules installed.

Composing multiple actions inside the same rule is supported. When only routing actions are requested, the driver creates a "non-critical" virtual link. When the action list also contains tc-gate (more details below), the virtual link becomes "time-critical" (draws frame buffers from a reserved memory partition, etc).

The 3 routing actions that are supported are "trap", "drop" and "redirect".

Example 1: send frames received on swp2 with a DA of 42:be:24:9b:76:20 to the CPU and to swp3. This type of key (DA only) when the port's VLAN awareness state is off:



```text
tc qdisc add dev swp2 clsact
tc filter add dev swp2 ingress flower skip_sw dst_mac 42:be:24:9b:76:20 \
        action mirred egress redirect dev swp3 \
        action trap
```

Example 2: drop frames received on swp2 with a DA of 42:be:24:9b:76:20, a VID of 100 and a PCP of 0:



```text
tc filter add dev swp2 ingress protocol 802.1Q flower skip_sw \
        dst_mac 42:be:24:9b:76:20 vlan_id 100 vlan_prio 0 action drop
```

<a id="rst-time-based-ingress-policing"></a>

### Time-based ingress policing

The TTEthernet hardware abilities of the switch can be constrained to act similarly to the Per-Stream Filtering and Policing (PSFP) clause specified in IEEE 802.1Q-2018 (formerly 802.1Qci). This means it can be used to perform tight timing-based admission control for up to 1024 flows (identified by a tuple composed of destination MAC address, VLAN ID and VLAN PCP). Packets which are received outside their expected reception window are dropped.

This capability can be managed through the offload of the tc-gate action. As routing actions are intrinsic to virtual links in TTEthernet (which performs explicit routing of time-critical traffic and does not leave that in the hands of the FDB, flooding etc), the tc-gate action may never appear alone when asking sja1105 to offload it. One (or more) redirect or trap actions must also follow along.

Example: create a tc-taprio schedule that is phase-aligned with a tc-gate schedule (the clocks must be synchronized by a 1588 application stack, which is outside the scope of this document). No packet delivered by the sender will be dropped. Note that the reception window is larger than the transmission window (and much more so, in this example) to compensate for the packet propagation delay of the link (which can be determined by the 1588 application stack).

Receiver (sja1105):



```text
tc qdisc add dev swp2 clsact
now=$(phc_ctl /dev/ptp1 get | awk '/clock time is/ {print $5}') && \
        sec=$(echo $now | awk -F. '{print $1}') && \
        base_time="$(((sec + 2) * 1000000000))" && \
        echo "base time ${base_time}"
tc filter add dev swp2 ingress flower skip_sw \
        dst_mac 42:be:24:9b:76:20 \
        action gate base-time ${base_time} \
        sched-entry OPEN  60000 -1 -1 \
        sched-entry CLOSE 40000 -1 -1 \
        action trap
```

Sender:



```text
now=$(phc_ctl /dev/ptp0 get | awk '/clock time is/ {print $5}') && \
        sec=$(echo $now | awk -F. '{print $1}') && \
        base_time="$(((sec + 2) * 1000000000))" && \
        echo "base time ${base_time}"
tc qdisc add dev eno0 parent root taprio \
        num_tc 8 \
        map 0 1 2 3 4 5 6 7 \
        queues 1@0 1@1 1@2 1@3 1@4 1@5 1@6 1@7 \
        base-time ${base_time} \
        sched-entry S 01  50000 \
        sched-entry S 00  50000 \
        flags 2
```

The engine used to schedule the ingress gate operations is the same that the one used for the tc-taprio offload. Therefore, the restrictions regarding the fact that no two gate actions (either tc-gate or tc-taprio gates) may fire at the same time (during the same 200 ns slot) still apply.

To come in handy, it is possible to share time-triggered virtual links across more than 1 ingress port, via flow blocks. In this case, the restriction of firing at the same time does not apply because there is a single schedule in the system, that of the shared virtual link:



```text
tc qdisc add dev swp2 ingress_block 1 clsact
tc qdisc add dev swp3 ingress_block 1 clsact
tc filter add block 1 flower skip_sw dst_mac 42:be:24:9b:76:20 \
        action gate index 2 \
        base-time 0 \
        sched-entry OPEN 50000000 -1 -1 \
        sched-entry CLOSE 50000000 -1 -1 \
        action trap
```

Hardware statistics for each flow are also available ("pkts" counts the number of dropped frames, which is a sum of frames dropped due to timing violations, lack of destination ports and MTU enforcement checks). Byte-level counters are not available.

<a id="rst-limitations"></a>

## Limitations

The SJA1105 switch family always performs VLAN processing. When configured as VLAN-unaware, frames carry a different VLAN tag internally, depending on whether the port is standalone or under a VLAN-unaware bridge.

The virtual link keys are always fixed at \{MAC DA, VLAN ID, VLAN PCP\}, but the driver asks for the VLAN ID and VLAN PCP when the port is under a VLAN-aware bridge. Otherwise, it fills in the VLAN ID and PCP automatically, based on whether the port is standalone or in a VLAN-unaware bridge, and accepts only "VLAN-unaware" tc-flower keys (MAC DA).

The existing tc-flower keys that are offloaded using virtual links are no longer operational after one of the following happens:

- port was standalone and joins a bridge (VLAN-aware or VLAN-unaware)

- port is part of a bridge whose VLAN awareness state changes

- port was part of a bridge and becomes standalone

- port was standalone, but another port joins a VLAN-aware bridge and this changes the global VLAN awareness state of the bridge

The driver cannot veto all these operations, and it cannot update/remove the existing tc-flower filters either. So for proper operation, the tc-flower filters should be installed only after the forwarding configuration of the port has been made, and removed by user space before making any changes to it.

<a id="rst-device-tree-bindings-and-board-design"></a>

## Device Tree bindings and board design

This section references `Documentation/devicetree/bindings/net/dsa/nxp,sja1105.yaml` and aims to showcase some potential switch caveats.

<a id="rst-rmii-phy-role-and-out-of-band-signaling"></a>

### RMII PHY role and out-of-band signaling

In the RMII spec, the 50 MHz clock signals are either driven by the MAC or by an external oscillator (but not by the PHY). But the spec is rather loose and devices go outside it in several ways. Some PHYs go against the spec and may provide an output pin where they source the 50 MHz clock themselves, in an attempt to be helpful. On the other hand, the SJA1105 is only binary configurable - when in the RMII MAC role it will also attempt to drive the clock signal. To prevent this from happening it must be put in RMII PHY role. But doing so has some unintended consequences. In the RMII spec, the PHY can transmit extra out-of-band signals via RXD\[1:0\]. These are practically some extra code words (/J/ and /K/) sent prior to the preamble of each frame. The MAC does not have this out-of-band signaling mechanism defined by the RMII spec. So when the SJA1105 port is put in PHY role to avoid having 2 drivers on the clock signal, inevitably an RMII PHY-to-PHY connection is created. The SJA1105 emulates a PHY interface fully and generates the /J/ and /K/ symbols prior to frame preambles, which the real PHY is not expected to understand. So the PHY simply encodes the extra symbols received from the SJA1105-as-PHY onto the 100Base-Tx wire. On the other side of the wire, some link partners might discard these extra symbols, while others might choke on them and discard the entire Ethernet frames that follow along. This looks like packet loss with some link partners but not with others. The take-away is that in RMII mode, the SJA1105 must be let to drive the reference clock if connected to a PHY.

<a id="rst-rgmii-fixed-link-and-internal-delays"></a>

### RGMII fixed-link and internal delays

As mentioned in the bindings document, the second generation of devices has tunable delay lines as part of the MAC, which can be used to establish the correct RGMII timing budget. When powered up, these can shift the Rx and Tx clocks with a phase difference between 73.8 and 101.7 degrees. The catch is that the delay lines need to lock onto a clock signal with a stable frequency. This means that there must be at least 2 microseconds of silence between the clock at the old vs at the new frequency. Otherwise the lock is lost and the delay lines must be reset (powered down and back up). In RGMII the clock frequency changes with link speed (125 MHz at 1000 Mbps, 25 MHz at 100 Mbps and 2.5 MHz at 10 Mbps), and link speed might change during the AN process. In the situation where the switch port is connected through an RGMII fixed-link to a link partner whose link state life cycle is outside the control of Linux (such as a different SoC), then the delay lines would remain unlocked (and inactive) until there is manual intervention (ifdown/ifup on the switch port). The take-away is that in RGMII mode, the switch's internal delays are only reliable if the link partner never changes link speeds, or if it does, it does so in a way that is coordinated with the switch port (practically, both ends of the fixed-link are under control of the same Linux system). As to why would a fixed-link interface ever change link speeds: there are Ethernet controllers out there which come out of reset in 100 Mbps mode, and their driver inevitably needs to change the speed and clock frequency if it's required to work at gigabit.

<a id="rst-mdio-bus-and-phy-management"></a>

### MDIO bus and PHY management

The SJA1105 does not have an MDIO bus and does not perform in-band AN either. Therefore there is no link state notification coming from the switch device. A board would need to hook up the PHYs connected to the switch to any other MDIO bus available to Linux within the system (e.g. to the DSA conduit's MDIO bus). Link state management then works by the driver manually keeping in sync (over SPI commands) the MAC link speed with the settings negotiated by the PHY.

By comparison, the SJA1110 supports an MDIO slave access point over which its internal 100base-T1 PHYs can be accessed from the host. This is, however, not used by the driver, instead the internal 100base-T1 and 100base-TX PHYs are accessed through SPI commands, modeled in Linux as virtual MDIO buses.

The microcontroller attached to the SJA1110 port 0 also has an MDIO controller operating in master mode, however the driver does not support this either, since the microcontroller gets disabled when the Linux driver operates. Discrete PHYs connected to the switch ports should have their MDIO interface attached to an MDIO controller from the host system and not to the switch, similar to SJA1105.

<a id="rst-port-compatibility-matrix"></a>

### Port compatibility matrix

The SJA1105 port compatibility matrix is:


<table>
<thead>
<tr>
<th>


Port

</th>
<th>


SJA1105E/T

</th>
<th>


SJA1105P/Q

</th>
<th>


SJA1105R/S

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


xMII

</td>
</tr>
<tr>
<td>


1

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


xMII

</td>
</tr>
<tr>
<td>


2

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


xMII

</td>
</tr>
<tr>
<td>


3

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


xMII

</td>
</tr>
<tr>
<td>


4

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


SGMII

</td>
</tr>
</tbody>
</table>

The SJA1110 port compatibility matrix is:


<table>
<thead>
<tr>
<th>


Port

</th>
<th>


SJA1110A

</th>
<th>


SJA1110B

</th>
<th>


SJA1110C

</th>
<th>


SJA1110D

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0

</td>
<td>


RevMII (uC)

</td>
<td>


RevMII (uC)

</td>
<td>


RevMII (uC)

</td>
<td>


RevMII (uC)

</td>
</tr>
<tr>
<td>


1

</td>
<td>


100base-TX or SGMII

</td>
<td>


100base-TX

</td>
<td>


100base-TX

</td>
<td>


SGMII

</td>
</tr>
<tr>
<td>


2

</td>
<td>


xMII or SGMII

</td>
<td>


xMII

</td>
<td>


xMII

</td>
<td>


xMII or SGMII

</td>
</tr>
<tr>
<td>


3

</td>
<td>


xMII or SGMII or 2500base-X

</td>
<td>


xMII or SGMII or 2500base-X

</td>
<td>


xMII

</td>
<td>


SGMII or 2500base-X

</td>
</tr>
<tr>
<td>


4

</td>
<td>


SGMII or 2500base-X

</td>
<td>


SGMII or 2500base-X

</td>
<td>


SGMII or 2500base-X

</td>
<td>


SGMII or 2500base-X

</td>
</tr>
<tr>
<td>


5

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
</tr>
<tr>
<td>


6

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
</tr>
<tr>
<td>


7

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
</tr>
<tr>
<td>


8

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


n/a

</td>
<td>


n/a

</td>
</tr>
<tr>
<td>


9

</td>
<td>


100base-T1

</td>
<td>


100base-T1

</td>
<td>


n/a

</td>
<td>


n/a

</td>
</tr>
<tr>
<td>


10

</td>
<td>


100base-T1

</td>
<td>


n/a

</td>
<td>


n/a

</td>
<td>


n/a

</td>
</tr>
</tbody>
</table>

---

# mac80211_hwsim - software simulator of 802.11 radio(s) for mac80211

_Peios Kernel / Internals / Networking / mac80211_hwsim_

> This program 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.

**orphan:** 

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

<a id="rst-mac80211-hwsim-software-simulator-of-802-11-radio-s-for-mac80211"></a>

## mac80211_hwsim - software simulator of 802.11 radio(s) for mac80211

**Copyright:** © 2008, Jouni Malinen &lt;[j@w1.fi](<mailto:j@w1.fi>)&gt;

This program 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.

<a id="rst-introduction"></a>

### Introduction

mac80211_hwsim is a Linux kernel module that can be used to simulate arbitrary number of IEEE 802.11 radios for mac80211. It can be used to test most of the mac80211 functionality and user space tools (e.g., hostapd and wpa_supplicant) in a way that matches very closely with the normal case of using real WLAN hardware. From the mac80211 view point, mac80211_hwsim is yet another hardware driver, i.e., no changes to mac80211 are needed to use this testing tool.

The main goal for mac80211_hwsim is to make it easier for developers to test their code and work with new features to mac80211, hostapd, and wpa_supplicant. The simulated radios do not have the limitations of real hardware, so it is easy to generate an arbitrary test setup and always reproduce the same setup for future tests. In addition, since all radio operation is simulated, any channel can be used in tests regardless of regulatory rules.

mac80211_hwsim kernel module has a parameter 'radios' that can be used to select how many radios are simulated (default 2). This allows configuration of both very simply setups (e.g., just a single access point and a station) or large scale tests (multiple access points with hundreds of stations).

mac80211_hwsim works by tracking the current channel of each virtual radio and copying all transmitted frames to all other radios that are currently enabled and on the same channel as the transmitting radio. Software encryption in mac80211 is used so that the frames are actually encrypted over the virtual air interface to allow more complete testing of encryption.

A global monitoring netdev, hwsim\#, is created independent of mac80211. This interface can be used to monitor all transmitted frames regardless of channel.

<a id="rst-simple-example"></a>

### Simple example

This example shows how to use mac80211_hwsim to simulate two radios: one to act as an access point and the other as a station that associates with the AP. hostapd and wpa_supplicant are used to take care of WPA2-PSK authentication. In addition, hostapd is also processing access point side of association.



```text
# Build mac80211_hwsim as part of kernel configuration

# Load the module
modprobe mac80211_hwsim

# Run hostapd (AP) for wlan0
hostapd hostapd.conf

# Run wpa_supplicant (station) for wlan1
wpa_supplicant -Dnl80211 -iwlan1 -c wpa_supplicant.conf
```

More test cases are available in hostap.git: git://w1.fi/srv/git/hostap.git and mac80211_hwsim/tests subdirectory (http://w1.fi/gitweb/gitweb.cgi?p=hostap.git;a=tree;f=mac80211_hwsim/tests)

---

# mac80211_hwsim access-point configuration

_Peios Kernel / Internals / Networking / mac80211_hwsim_

> Access-point configuration for the documented mac80211_hwsim test network.

Access-point configuration for the documented mac80211_hwsim test network.


```ini
interface=wlan0
driver=nl80211

hw_mode=g
channel=1
ssid=mac80211 test

wpa=2
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
wpa_passphrase=12345678

```

---

# mac80211_hwsim station configuration

_Peios Kernel / Internals / Networking / mac80211_hwsim_

> Station configuration matching the documented mac80211_hwsim test network.

Station configuration matching the documented mac80211_hwsim test network.


```ini
ctrl_interface=/var/run/wpa_supplicant

network={
	ssid="mac80211 test"
	psk="12345678"
	key_mgmt=WPA-PSK
	proto=WPA2
	pairwise=CCMP
	group=CCMP
}

```

---

# Common Networking Struct Cachelines

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for Common Networking Struct Cachelines.

<a id="rst-common-networking-struct-cachelines"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->

- [inet_connection_sock struct fast path usage breakdown](</kernel/internals/networking/net-cachelines/inet-connection-sock.md>)
- [inet_sock struct fast path usage breakdown](</kernel/internals/networking/net-cachelines/inet-sock.md>)
- [net_device struct fast path usage breakdown](</kernel/internals/networking/net-cachelines/net-device.md>)
- [netns_ipv4 struct fast path usage breakdown](</kernel/internals/networking/net-cachelines/netns-ipv4-sysctl.md>)
- [netns_ipv4 enum fast path usage breakdown](</kernel/internals/networking/net-cachelines/snmp.md>)
- [tcp_sock struct fast path usage breakdown](</kernel/internals/networking/net-cachelines/tcp-sock.md>)

---

# inet_connection_sock struct fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for inet_connection_sock struct fast path usage breakdown.

<a id="rst-inet-connection-sock-struct-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


struct inet_sock

</td>
<td>


icsk_inet

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_init_buffer_space,tcp_init_transfer,tcp_finish_connect,tcp_connect,tcp_send_rcvq,tcp_send_syn_data

</td>
</tr>
<tr>
<td>


struct request_sock_queue

</td>
<td>


icsk_accept_queue

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct inet_bind_bucket

</td>
<td>


icsk_bind_hash

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_set_state

</td>
</tr>
<tr>
<td>


struct inet_bind2_bucket

</td>
<td>


icsk_bind2_hash

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_set_state,inet_put_port

</td>
</tr>
<tr>
<td>


struct timer_list

</td>
<td>


icsk_delack_timer

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


inet_csk_reset_xmit_timer,tcp_connect

</td>
</tr>
<tr>
<td>


struct timer_list

</td>
<td>


icsk_keepalive_timer

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_rto

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_cwnd_validate,tcp_schedule_loss_probe,tcp_connect_init,tcp_connect,tcp_write_xmit,tcp_push_one

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_rto_min

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_rto_max

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_reset_xmit_timer

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_delack_max

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_pmtu_cookie

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_sync_mss,tcp_current_mss,tcp_send_syn_data,tcp_connect_init,tcp_connect

</td>
</tr>
<tr>
<td>


struct tcp_congestion_ops

</td>
<td>


icsk_ca_ops

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_cwnd_validate,tcp_tso_segs,tcp_ca_dst_init,tcp_connect_init,tcp_connect,tcp_write_xmit

</td>
</tr>
<tr>
<td>


struct inet_connection_sock_af_ops

</td>
<td>


icsk_af_ops

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_finish_connect,tcp_send_syn_data,tcp_mtup_init,tcp_mtu_check_reprobe,tcp_mtu_probe,tcp_connect_init,tcp_connect,\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


struct tcp_ulp_ops\*

</td>
<td>


icsk_ulp_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


void\*

</td>
<td>


icsk_ulp_data

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:5

</td>
<td>


icsk_ca_state

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_cwnd_application_limited,tcp_set_ca_state,tcp_enter_cwr,tcp_tso_should_defer,tcp_mtu_probe,tcp_schedule_loss_probe,tcp_write_xmit,\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


icsk_ca_initialized

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_init_transfer,tcp_init_congestion_control,tcp_init_transfer,tcp_finish_connect,tcp_connect

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


icsk_ca_setsockopt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


icsk_ca_dst_locked

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_ca_dst_init,tcp_connect_init,tcp_connect

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


icsk_retransmits

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_connect_init,tcp_connect

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


icsk_pending

</td>
<td>


read_write

</td>
<td>




</td>
<td>


inet_csk_reset_xmit_timer,tcp_connect,tcp_check_probe_timer,\__tcp_push_pending_frames,tcp_rearm_rto,tcp_event_new_data_sent,tcp_event_new_data_sent

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


icsk_backoff

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_write_queue_purge,tcp_connect_init

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


icsk_syn_retries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


icsk_probes_out

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


icsk_ext_hdr_len

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_mtu_to_mss,tcp_mtu_to_rss,tcp_mtu_probe,tcp_write_xmit,tcp_mtu_to_mss,

</td>
</tr>
<tr>
<td>


struct icsk_ack_u8

</td>
<td>


pending

</td>
<td>


read_write

</td>
<td>


read_write

</td>
<td>


inet_csk_ack_scheduled,\__tcp_cleanup_rbuf,tcp_cleanup_rbuf,inet_csk_clear_xmit_timer,tcp_event_ack-sent,inet_csk_reset_xmit_timer

</td>
</tr>
<tr>
<td>


struct icsk_ack_u8

</td>
<td>


quick

</td>
<td>


read_write

</td>
<td>


write_mostly

</td>
<td>


tcp_dec_quickack_mode,tcp_event_ack_sent,\__tcp_transmit_skb,\__tcp_select_window,\__tcp_cleanup_rbuf

</td>
</tr>
<tr>
<td>


struct icsk_ack_u8

</td>
<td>


pingpong

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct icsk_ack_u8

</td>
<td>


retry

</td>
<td>


write_mostly

</td>
<td>


read_write

</td>
<td>


inet_csk_clear_xmit_timer,tcp_rearm_rto,tcp_event_new_data_sent,tcp_write_xmit,\__tcp_send_ack,tcp_send_ack,

</td>
</tr>
<tr>
<td>


struct icsk_ack_u8

</td>
<td>


ato

</td>
<td>


read_mostly

</td>
<td>


write_mostly

</td>
<td>


tcp_dec_quickack_mode,tcp_event_ack_sent,\__tcp_transmit_skb,\__tcp_send_ack,tcp_send_ack

</td>
</tr>
<tr>
<td>


struct icsk_ack_u32

</td>
<td>


lrcvtime

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_finish_connect,tcp_connect,tcp_event_data_sent,\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


struct icsk_ack_u16

</td>
<td>


rcv_mss

</td>
<td>


write_mostly

</td>
<td>


read_mostly

</td>
<td>


\__tcp_select_window,\__tcp_cleanup_rbuf,tcp_initialize_rcv_mss,tcp_connect_init

</td>
</tr>
<tr>
<td>


struct icsk_mtup_int

</td>
<td>


search_high

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mtup_init,tcp_sync_mss,tcp_connect_init,tcp_mtu_check_reprobe,tcp_write_xmit

</td>
</tr>
<tr>
<td>


struct icsk_mtup_int

</td>
<td>


search_low

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mtu_probe,tcp_mtu_check_reprobe,tcp_write_xmit,tcp_sync_mss,tcp_connect_init,tcp_mtup_init

</td>
</tr>
<tr>
<td>


struct icsk_mtup_u32:31

</td>
<td>


probe_size

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mtup_init,tcp_connect_init,\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


struct icsk_mtup_u32:1

</td>
<td>


enabled

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mtup_init,tcp_sync_mss,tcp_connect_init,tcp_mtu_probe,tcp_write_xmit

</td>
</tr>
<tr>
<td>


struct icsk_mtup_u32

</td>
<td>


probe_timestamp

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mtup_init,tcp_connect_init,tcp_mtu_check_reprobe,tcp_mtu_probe

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_probes_tstamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


icsk_user_timeout

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u64\[104/sizeof(u64)\]

</td>
<td>


icsk_ca_priv

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# inet_sock struct fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for inet_sock struct fast path usage breakdown.

<a id="rst-inet-sock-struct-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


struct sock

</td>
<td>


sk

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_init_buffer_space,tcp_init_transfer,tcp_finish_connect,tcp_connect,tcp_send_rcvq,tcp_send_syn_data

</td>
</tr>
<tr>
<td>


struct ipv6_pinfo\*

</td>
<td>


pinet6

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ipv6_fl_socklist\*

</td>
<td>


ipv6_fl_list

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_v6_connect,\__ip6_datagram_connect,udpv6_sendmsg,rawv6_sendmsg

</td>
</tr>
<tr>
<td>


be16

</td>
<td>


inet_sport

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


be32

</td>
<td>


inet_daddr

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_select_ident_segs

</td>
</tr>
<tr>
<td>


be32

</td>
<td>


inet_rcv_saddr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


be16

</td>
<td>


inet_dport

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


inet_num

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


be32

</td>
<td>


inet_saddr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


s16

</td>
<td>


uc_ttl

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__ip_queue_xmit/ip_select_ttl

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


cmsg_flags

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ip_options_rcu\*

</td>
<td>


inet_opt

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__ip_queue_xmit

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


inet_id

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_select_ident_segs

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


tos

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_queue_xmit

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


min_ttl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


mc_ttl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


pmtudisc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


recverr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


is_icsk

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


freebind

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


hdrincl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


mc_loop

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


transparent

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


mc_all

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


nodefrag

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


bind_address_no_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


recverr_rfc4884

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


defer_connect

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_sendmsg_fastopen

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


rcv_tos

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


convert_csum

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


uc_index

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


mc_index

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


be32

</td>
<td>


mc_addr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ip_mc_socklist\*

</td>
<td>


mc_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct inet_cork_full

</td>
<td>


cork

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


struct

</td>
<td>


local_port_range

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# net_device struct fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for net_device struct fast path usage breakdown.

<a id="rst-net-device-struct-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


Comments

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


unsigned_long:32

</td>
<td>


priv_flags

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__dev_queue_xmit(tx)

</td>
</tr>
<tr>
<td>


unsigned_long:1

</td>
<td>


lltx

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


HARD_TX_LOCK,HARD_TX_TRYLOCK,HARD_TX_UNLOCK(tx)

</td>
</tr>
<tr>
<td>


unsigned long:1

</td>
<td>


netmem_tx:1;

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


char

</td>
<td>


name\[16\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_name_node\*

</td>
<td>


name_node

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct dev_ifalias\*

</td>
<td>


ifalias

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


mem_end

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


mem_start

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


base_addr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


state

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


netif_running(dev)

</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


dev_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


napi_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


unreg_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


close_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


ptype_all

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


dev_nit_active(tx)

</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


ptype_specific

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


deliver_ptype_list_skb/\__netif_receive_skb_core(rx)

</td>
</tr>
<tr>
<td>


struct

</td>
<td>


adj_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


flags

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


\__dev_queue_xmit,\__dev_xmit_skb,ip6_output,\__ip6_finish_output(tx);ip6_rcv_core(rx)

</td>
</tr>
<tr>
<td>


xdp_features_t

</td>
<td>


xdp_features

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct net_device_ops\*

</td>
<td>


netdev_ops

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


netdev_core_pick_tx,netdev_start_xmit(tx)

</td>
</tr>
<tr>
<td>


struct xdp_metadata_ops\*

</td>
<td>


xdp_metadata_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


ifindex

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


ip6_rcv_core

</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


gflags

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


hard_header_len

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


ip6_xmit(tx);gro_list_prepare(rx)

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


mtu

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_finish_output2

</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


needed_headroom

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


LL_RESERVED_SPACE/ip_finish_output2

</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


needed_tailroom

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


features

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


HARD_TX_LOCK,netif_skb_features,sk_setup_caps(tx);netif_elide_gro(rx)

</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


hw_features

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


wanted_features

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


vlan_features

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


hw_enc_features

</td>
<td>




</td>
<td>




</td>
<td>


netif_skb_features

</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


mpls_features

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdev_features_t

</td>
<td>


gso_partial_features

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


gso_features_check

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


min_mtu

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


max_mtu

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


type

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


min_header_len

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


name_assign_type

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


group

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct net_device_stats

</td>
<td>


stats

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct net_device_core_stats\*

</td>
<td>


core_stats

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


carrier_up_count

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


carrier_down_count

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct iw_handler_def\*

</td>
<td>


wireless_handlers

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ethtool_ops\*

</td>
<td>


ethtool_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct l3mdev_ops\*

</td>
<td>


l3mdev_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ndisc_ops\*

</td>
<td>


ndisc_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct xfrmdev_ops\*

</td>
<td>


xfrmdev_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tlsdev_ops\*

</td>
<td>


tlsdev_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct header_ops\*

</td>
<td>


header_ops

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_finish_output2,ip6_finish_output2(tx)

</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


operstate

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


link_mode

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


if_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


dma

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


perm_addr\[32\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


addr_assign_type

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


addr_len

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


upper_level

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


lower_level

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


threaded

</td>
<td>




</td>
<td>




</td>
<td>


napi_poll(napi_enable,netif_set_threaded)

</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


neigh_priv_len

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


padded

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


dev_id

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_short

</td>
<td>


dev_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


spinlock_t

</td>
<td>


addr_list_lock

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


irq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_hw_addr_list

</td>
<td>


uc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_hw_addr_list

</td>
<td>


mc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_hw_addr_list

</td>
<td>


dev_addrs

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct kset\*

</td>
<td>


queues_kset

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


unlink_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


promiscuity

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


allmulti

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


uc_promisc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


nested_level

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct in_device\*

</td>
<td>


ip_ptr

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


\__in_dev_get

</td>
</tr>
<tr>
<td>


struct hlist_head

</td>
<td>


fib_nh_head

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct inet6_dev\*

</td>
<td>


ip6_ptr

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


\__in6_dev_get

</td>
</tr>
<tr>
<td>


struct vlan_info\*

</td>
<td>


vlan_info

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct dsa_port\*

</td>
<td>


dsa_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tipc_bearer\*

</td>
<td>


tipc_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


void\*

</td>
<td>


atalk_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


void\*

</td>
<td>


ax25_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct wireless_dev\*

</td>
<td>


ieee80211_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct wpan_dev\*

</td>
<td>


ieee802154_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct mpls_dev\*

</td>
<td>


mpls_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct mctp_dev\*

</td>
<td>


mctp_ptr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char\*

</td>
<td>


dev_addr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_queue\*

</td>
<td>


\_rx

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


netdev_get_rx_queue(rx)

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


num_rx_queues

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


real_num_rx_queues

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


get_rps_cpu

</td>
</tr>
<tr>
<td>


struct bpf_prog\*

</td>
<td>


xdp_prog

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


netif_elide_gro()

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


gro_flush_timeout

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


napi_complete_done

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


napi_defer_hard_irqs

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


napi_complete_done

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


gro_max_size

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


skb_gro_receive

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


gro_ipv4_max_size

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


skb_gro_receive

</td>
</tr>
<tr>
<td>


rx_handler_func_t\*

</td>
<td>


rx_handler

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__netif_receive_skb_core

</td>
</tr>
<tr>
<td>


void\*

</td>
<td>


rx_handler_data

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_queue\*

</td>
<td>


ingress_queue

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct bpf_mprog_entry

</td>
<td>


tcx_ingress

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


sch_handle_ingress

</td>
</tr>
<tr>
<td>


struct nf_hook_entries\*

</td>
<td>


nf_hooks_ingress

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_char

</td>
<td>


broadcast\[32\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct cpu_rmap\*

</td>
<td>


rx_cpu_rmap

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct hlist_node

</td>
<td>


index_hlist

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netdev_queue\*

</td>
<td>


\_tx

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


netdev_get_tx_queue(tx)

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


num_tx_queues

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


real_num_tx_queues

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


skb_tx_hash,netdev_core_pick_tx(tx)

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


tx_queue_len

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


spinlock_t

</td>
<td>


tx_global_lock

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct xdp_dev_bulk_queue__percpu\*

</td>
<td>


xdp_bulkq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct xps_dev_maps\*

</td>
<td>


xps_maps\[2\]

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__netif_set_xps_queue

</td>
</tr>
<tr>
<td>


struct bpf_mprog_entry

</td>
<td>


tcx_egress

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


sch_handle_egress

</td>
</tr>
<tr>
<td>


struct nf_hook_entries\*

</td>
<td>


nf_hooks_egress

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct hlist_head

</td>
<td>


qdisc_hash\[16\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct timer_list

</td>
<td>


watchdog_timer

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


watchdog_timeo

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


proto_down_reason

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


todo_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int__percpu\*

</td>
<td>


pcpu_refcnt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


refcount_t

</td>
<td>


dev_refcnt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct ref_tracker_dir

</td>
<td>


refcnt_tracker

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


link_watch_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


enum:8

</td>
<td>


reg_state

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


dismantle

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


rtnl_link_initilizing

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


needs_free_netdev

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


void\*priv_destructor

</td>
<td>


struct net_device

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netpoll_info\*

</td>
<td>


npinfo

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


napi_poll/napi_poll_lock

</td>
</tr>
<tr>
<td>


possible_net_t

</td>
<td>


nd_net

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


(dev_net)napi_busy_loop,tcp_v(4/6)\_rcv,ip(v6)\_rcv,ip(6)\_input,ip(6)\_input_finish

</td>
</tr>
<tr>
<td>


void\*

</td>
<td>


ml_priv

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


enum_netdev_ml_priv_type

</td>
<td>


ml_priv_type

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct pcpu_lstats__percpu\*

</td>
<td>


lstats

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


dev_lstats_add()

</td>
</tr>
<tr>
<td>


struct pcpu_sw_netstats__percpu\*

</td>
<td>


tstats

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


dev_sw_netstats_tx_add()

</td>
</tr>
<tr>
<td>


struct pcpu_dstats__percpu\*

</td>
<td>


dstats

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct garp_port\*

</td>
<td>


garp_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct mrp_port\*

</td>
<td>


mrp_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct dm_hw_stat_delta\*

</td>
<td>


dm_private

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct device

</td>
<td>


dev

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct attribute_group\*

</td>
<td>


sysfs_groups\[4\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct attribute_group\*

</td>
<td>


sysfs_rx_queue_group

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct rtnl_link_ops\*

</td>
<td>


rtnl_link_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


gso_max_size

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


sk_dst_gso_max_size

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


tso_max_size

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


gso_max_segs

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


gso_max_segs

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


tso_max_segs

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


gso_ipv4_max_size

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


sk_dst_gso_max_size

</td>
</tr>
<tr>
<td>


struct dcbnl_rtnl_ops\*

</td>
<td>


dcbnl_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


s16

</td>
<td>


num_tc

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


skb_tx_hash

</td>
</tr>
<tr>
<td>


struct netdev_tc_txq

</td>
<td>


tc_to_txq\[16\]

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


skb_tx_hash

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


prio_tc_map\[16\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


fcoe_ddp_xid

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct netprio_map\*

</td>
<td>


priomap

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct phy_device\*

</td>
<td>


phydev

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct sfp_bus\*

</td>
<td>


sfp_bus

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct lock_class_key\*

</td>
<td>


qdisc_tx_busylock

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


proto_down

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned:1

</td>
<td>


wol_enabled

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long:1

</td>
<td>


see_all_hwtstamp_requests

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long:1

</td>
<td>


change_proto_down

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long:1

</td>
<td>


netns_immutable

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long:1

</td>
<td>


fcoe_mtu

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


net_notifier_list

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct macsec_ops\*

</td>
<td>


macsec_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct udp_tunnel_nic_info\*

</td>
<td>


udp_tunnel_nic_info

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct udp_tunnel_nic\*

</td>
<td>


udp_tunnel_nic

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


xdp_zc_max_segs

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct bpf_xdp_entity

</td>
<td>


xdp_state\[3\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


dev_addr_shadow\[32\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdevice_tracker

</td>
<td>


linkwatch_dev_tracker

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdevice_tracker

</td>
<td>


watchdog_dev_tracker

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


netdevice_tracker

</td>
<td>


dev_registered_tracker

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct rtnl_hw_stats64\*

</td>
<td>


offload_xstats_l3

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct devlink_port\*

</td>
<td>


devlink_port

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct dpll_pin\*

</td>
<td>


dpll_pin

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct hlist_head

</td>
<td>


page_pools

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct dim_irq_moder\*

</td>
<td>


irq_moder

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u64

</td>
<td>


max_pacing_offload_horizon

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_napi_config\*

</td>
<td>


napi_config

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


gro_flush_timeout

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


napi_defer_hard_irqs

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct hlist_head

</td>
<td>


neighbours\[2\]

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# netns_ipv4 struct fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for netns_ipv4 struct fast path usage breakdown.

> **Peios:** Transport and driver mechanisms described here remain reference material, but any nftables/iptables, IPVS, NFQUEUE or legacy netfilter policy examples assume an upstream configuration. The Peios profile disables those policy paths and uses NTFE. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>); NTFE is permissive before its first policy generation is ingested.


<a id="rst-netns-ipv4-struct-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


struct_inet_timewait_death_row

</td>
<td>


tcp_death_row

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_udp_table\*

</td>
<td>


udp_table

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ctl_table_header\*

</td>
<td>


forw_hdr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ctl_table_header\*

</td>
<td>


frags_hdr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ctl_table_header\*

</td>
<td>


ipv4_hdr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ctl_table_header\*

</td>
<td>


route_hdr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ctl_table_header\*

</td>
<td>


xfrm4_hdr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ipv4_devconf\*

</td>
<td>


devconf_all

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ipv4_devconf\*

</td>
<td>


devconf_dflt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ip_ra_chain

</td>
<td>


ra_chain

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_mutex

</td>
<td>


ra_mutex

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_rules_ops\*

</td>
<td>


rules_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_table

</td>
<td>


fib_main

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_table

</td>
<td>


fib_default

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


fib_rules_require_fldissect

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


fib_has_custom_rules

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


fib_has_custom_local_routes

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


fib_offload_disabled

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


fib_num_tclassid_users

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_hlist_head\*

</td>
<td>


fib_table_hash

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_sock\*

</td>
<td>


fibnl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_sock\*

</td>
<td>


mc_autojoin_sk

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_inet_peer_base\*

</td>
<td>


peers

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fqdir\*

</td>
<td>


fqdir

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_icmp_echo_ignore_all

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_icmp_echo_enable_probe

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_icmp_echo_ignore_broadcasts

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_icmp_ignore_bogus_error_responses

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_icmp_errors_use_inbound_ifaddr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_icmp_ratelimit

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_icmp_ratemask

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


ip_rt_min_pmtu

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


ip_rt_mtu_expires

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


ip_rt_min_advmss

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_local_ports

</td>
<td>


ip_local_ports

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_ecn

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_ecn_fallback

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_default_ttl

</td>
<td>




</td>
<td>




</td>
<td>


ip4_dst_hoplimit/ip_select_ttl

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_no_pmtu_disc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_fwd_use_pmtu

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


ip_dst_mtu_maybe_forward/ip_skb_dst_mtu

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_fwd_update_priority

</td>
<td>




</td>
<td>




</td>
<td>


ip_forward

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_nonlocal_bind

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_autobind_reuse

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_dynaddr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_ip_early_demux

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


ip(6)\_rcv_finish_core

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_raw_l3mdev_accept

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_early_demux

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


ip(6)\_rcv_finish_core

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_udp_early_demux

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_nexthop_compat_mode

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_fwmark_reflect

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_fwmark_accept

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_l3mdev_accept

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


\__inet6_lookup_established/inet_request_bound_dev_if

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_mtu_probing

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_mtu_probe_floor

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_base_mss

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_min_snd_mss

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_mtu_to_mss(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_probe_threshold

</td>
<td>




</td>
<td>




</td>
<td>


tcp_mtu_probe(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


sysctl_tcp_probe_interval

</td>
<td>




</td>
<td>




</td>
<td>


tcp_mtu_check_reprobe(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_keepalive_time

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_keepalive_intvl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_keepalive_probes

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_syn_retries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_synack_retries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_syncookies

</td>
<td>




</td>
<td>




</td>
<td>


generated_on_syn

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_migrate_req

</td>
<td>




</td>
<td>




</td>
<td>


reuseport

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_comp_sack_nr

</td>
<td>




</td>
<td>




</td>
<td>


\__tcp_ack_snd_check

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_reordering

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_may_raise_cwnd/tcp_cong_control

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_retries1

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_retries2

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_orphan_retries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_tw_reuse

</td>
<td>




</td>
<td>




</td>
<td>


timewait_sock_ops

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


sysctl_tcp_tw_reuse_delay

</td>
<td>




</td>
<td>




</td>
<td>


timewait_sock_ops

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_fin_timeout

</td>
<td>




</td>
<td>




</td>
<td>


TCP_LAST_ACK/tcp_rcv_state_process

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


sysctl_tcp_notsent_lowat

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_notsent_lowat/tcp_stream_memory_free

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_sack

</td>
<td>




</td>
<td>




</td>
<td>


tcp_syn_options

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_window_scaling

</td>
<td>




</td>
<td>




</td>
<td>


tcp_syn_options,tcp_parse_options

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_timestamps

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_early_retrans

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_schedule_loss_probe(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


sysctl_tcp_rto_max_ms

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_recovery

</td>
<td>




</td>
<td>




</td>
<td>


tcp_fastretrans_alert

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_thin_linear_timeouts

</td>
<td>




</td>
<td>




</td>
<td>


tcp_retrans_timer(on_thin_streams)

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_slow_start_after_idle

</td>
<td>




</td>
<td>




</td>
<td>


unlikely(tcp_cwnd_validate-network-not-starved)

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_retrans_collapse

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_stdurg

</td>
<td>




</td>
<td>




</td>
<td>


unlikely(tcp_check_urg)

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_rfc1337

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_abort_on_overflow

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_fack

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_max_reordering

</td>
<td>




</td>
<td>




</td>
<td>


tcp_check_sack_reordering

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_adv_win_scale

</td>
<td>




</td>
<td>




</td>
<td>


tcp_init_buffer_space

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_dsack

</td>
<td>




</td>
<td>




</td>
<td>


partial_packet_or_retrans_in_tcp_data_queue

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_app_win

</td>
<td>




</td>
<td>




</td>
<td>


tcp_win_from_space

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_frto

</td>
<td>




</td>
<td>




</td>
<td>


tcp_enter_loss

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_nometrics_save

</td>
<td>




</td>
<td>




</td>
<td>


TCP_LAST_ACK/tcp_update_metrics

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_no_ssthresh_metrics_save

</td>
<td>




</td>
<td>




</td>
<td>


TCP_LAST_ACK/tcp\_(update/init)\_metrics

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_moderate_rcvbuf

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_rcvbuf_grow()

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


sysctl_tcp_rcvbuf_low_rtt

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_rcvbuf_grow()

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_tso_win_divisor

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_tso_should_defer(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_workaround_signed_windows

</td>
<td>




</td>
<td>




</td>
<td>


tcp_select_window

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_limit_output_bytes

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_small_queue_check(tcp_write_xmit)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_challenge_ack_limit

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_min_rtt_wlen

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_ack_update_rtt

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_min_tso_segs

</td>
<td>




</td>
<td>




</td>
<td>


unlikely(icsk_ca_ops-written)

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_tso_rtt_log

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_tso_autosize

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_autocorking

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_push/tcp_should_autocork

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_reflect_tos

</td>
<td>




</td>
<td>




</td>
<td>


tcp_v(4/6)\_send_synack

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_invalid_ratelimit

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_pacing_ss_ratio

</td>
<td>




</td>
<td>




</td>
<td>


default_cong_cont(tcp_update_pacing_rate)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_pacing_ca_ratio

</td>
<td>




</td>
<td>




</td>
<td>


default_cong_cont(tcp_update_pacing_rate)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_wmem\[3\]

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_wmem_schedule(sendmsg/sendpage)

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_rmem\[3\]

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


\__tcp_grow_window(tx),tcp_rcv_space_adjust(rx)

</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


sysctl_tcp_child_ehash_entries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


sysctl_tcp_comp_sack_delay_ns

</td>
<td>




</td>
<td>




</td>
<td>


\__tcp_ack_snd_check

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


sysctl_tcp_comp_sack_slack_ns

</td>
<td>




</td>
<td>




</td>
<td>


\__tcp_ack_snd_check

</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_max_syn_backlog

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_fastopen

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_tcp_congestion_ops

</td>
<td>


tcp_congestion_control

</td>
<td>




</td>
<td>




</td>
<td>


init_cc

</td>
</tr>
<tr>
<td>


struct_tcp_fastopen_context

</td>
<td>


tcp_fastopen_ctx

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


sysctl_tcp_fastopen_blackhole_timeout

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


tfo_active_disable_times

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


tfo_active_disable_stamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


tcp_challenge_timestamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


tcp_challenge_count

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_plb_enabled

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_plb_idle_rehash_rounds

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_plb_rehash_rounds

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_tcp_plb_suspend_rto_sec

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_tcp_plb_cong_thresh

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_udp_wmem_min

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_udp_rmem_min

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_fib_notify_on_flag_change

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_udp_l3mdev_accept

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_igmp_llm_reports

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_igmp_max_memberships

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_igmp_max_msf

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_igmp_qrv

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_ping_group_range

</td>
<td>


ping_group_range

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


dev_addr_genid

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


sysctl_udp_child_hash_entries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long\*

</td>
<td>


sysctl_local_reserved_ports

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


sysctl_ip_prot_sock

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_mr_table\*

</td>
<td>


mrt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_list_head

</td>
<td>


mr_tables

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_rules_ops\*

</td>
<td>


mr_rules_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


sysctl_fib_multipath_hash_fields

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_fib_multipath_use_neigh

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


sysctl_fib_multipath_hash_policy

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_notifier_ops\*

</td>
<td>


notifier_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


fib_seq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct_fib_notifier_ops\*

</td>
<td>


ipmr_notifier_ops

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


ipmr_seq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


atomic_t

</td>
<td>


rt_genid

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


siphash_key_t

</td>
<td>


ip_id_key

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# netns_ipv4 enum fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for netns_ipv4 enum fast path usage breakdown.

<a id="rst-netns-ipv4-enum-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


comment

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPKEEPALIVE

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_keepalive_timer

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_DELAYEDACKS

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_delack_timer_handler,tcp_delack_timer

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_DELAYEDACKLOCKED

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_delack_timer_handler,tcp_delack_timer

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPAUTOCORKING

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_push,tcp_sendmsg_locked

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFROMZEROWINDOWADV

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_select_window,tcp_transmit-skb

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPTOZEROWINDOWADV

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_select_window,tcp_transmit-skb

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPWANTZEROWINDOWADV

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_select_window,tcp_transmit-skb

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPORIGDATASENT

</td>
<td>


write_mostly

</td>
<td>




</td>
<td>


tcp_write_xmit

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHPHITS

</td>
<td>




</td>
<td>


write_mostly

</td>
<td>


tcp_rcv_established,tcp_v4_do_rcv,tcp_v6_do_rcv

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRCVCOALESCE

</td>
<td>




</td>
<td>


write_mostly

</td>
<td>


tcp_try_coalesce,tcp_queue_rcv,tcp_rcv_established

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPPUREACKS

</td>
<td>




</td>
<td>


write_mostly

</td>
<td>


tcp_ack,tcp_rcv_established

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHPACKS

</td>
<td>




</td>
<td>


write_mostly

</td>
<td>


tcp_ack,tcp_rcv_established

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDELIVERED

</td>
<td>




</td>
<td>


write_mostly

</td>
<td>


tcp_newly_delivered,tcp_ack,tcp_rcv_established

</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SYNCOOKIESSENT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SYNCOOKIESRECV

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SYNCOOKIESFAILED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_EMBRYONICRSTS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PRUNECALLED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_RCVPRUNED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_OFOPRUNED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_OUTOFWINDOWICMPS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_LOCKDROPPEDICMPS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_ARPFILTER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TIMEWAITED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TIMEWAITRECYCLED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TIMEWAITKILLED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PAWSACTIVEREJECTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PAWSESTABREJECTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_BEYOND_WINDOW

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TSECR_REJECTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PAWS_OLD_ACK

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PAWS_TW_REJECTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_DELAYEDACKLOST

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_LISTENOVERFLOWS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_LISTENDROPS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRENORECOVERY

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKRECOVERY

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKRENEGING

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKREORDER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRENOREORDER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPTSREORDER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFULLUNDO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPPARTIALUNDO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKUNDO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPLOSSUNDO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPLOSTRETRANSMIT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRENOFAILURES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKFAILURES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPLOSSFAILURES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTRETRANS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSLOWSTARTRETRANS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPTIMEOUTS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPLOSSPROBES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPLOSSPROBERECOVERY

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRENORECOVERYFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKRECOVERYFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRCVCOLLAPSED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKOLDSENT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKOFOSENT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKRECV

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKOFORECV

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTONDATA

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTONCLOSE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTONMEMORY

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTONTIMEOUT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTONLINGER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPABORTFAILED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMEMORYPRESSURES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMEMORYPRESSURESCHRONO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSACKDISCARD

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKIGNOREDOLD

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKIGNOREDNOUNDO

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSPURIOUSRTOS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMD5NOTFOUND

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMD5UNEXPECTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMD5FAILURE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SACKSHIFTED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SACKMERGED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_SACKSHIFTFALLBACK

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPBACKLOGDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_PFMEMALLOCDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMINTTLDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDEFERACCEPTDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_IPRPFILTER

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPTIMEWAITOVERFLOW

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPREQQFULLDOCOOKIES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPREQQFULLDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRETRANSFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPBACKLOGCOALESCE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPOFOQUEUE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPOFODROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPOFOMERGE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPCHALLENGEACK

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSYNCHALLENGE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENACTIVE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENACTIVEFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENPASSIVE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENPASSIVEFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENLISTENOVERFLOW

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENCOOKIEREQD

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENBLACKHOLE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_BUSYPOLLRXPACKETS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPSYNRETRANS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHYSTARTTRAINDETECT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHYSTARTTRAINCWND

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHYSTARTDELAYDETECT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPHYSTARTDELAYCWND

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDSYNRECV

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDPAWS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDSEQ

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDFINWAIT2

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDTIMEWAIT

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKSKIPPEDCHALLENGE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPWINPROBE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMTUPFAIL

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMTUPSUCCESS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDELIVEREDCE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPACKCOMPRESSED

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPZEROWINDOWDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPRCVQDROP

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPWQUEUETOOBIG

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPFASTOPENPASSIVEALTKEY

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPTIMEOUTREHASH

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDUPLICATEDATAREHASH

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKRECVSEGS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPDSACKIGNOREDDUBIOUS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMIGRATEREQSUCCESS

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


LINUX_MIB_TCPMIGRATEREQFAILURE

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_long

</td>
<td>


\__LINUX_MIB_MAX

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# tcp_sock struct fast path usage breakdown

_Peios Kernel / Internals / Networking / net_cachelines_

> Reference for tcp_sock struct fast path usage breakdown.

<a id="rst-tcp-sock-struct-fast-path-usage-breakdown"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright (C) 2023 Google LLC -->


<table>
<thead>
<tr>
<th>


Type

</th>
<th>


Name

</th>
<th>


fastpath_tx_access

</th>
<th>


fastpath_rx_access

</th>
<th>


Comments

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


struct inet_connection_sock

</td>
<td>


inet_conn

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


tcp_header_len

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_bound_to_half_wnd,tcp_current_mss(tx);tcp_rcv_established(rx)

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


gso_segs

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_xmit_size_goal

</td>
</tr>
<tr>
<td>


\__be32

</td>
<td>


pred_flags

</td>
<td>


read_write

</td>
<td>


read_mostly

</td>
<td>


tcp_select_window(tx);tcp_rcv_established(rx)

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


bytes_received

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_rcv_nxt_update(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


segs_in

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_v6_rcv(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


data_segs_in

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_v6_rcv(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_nxt

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_cleanup_rbuf,tcp_send_ack,tcp_inq_hint,tcp_transmit_skb,tcp_receive_window(tx);tcp_v6_do_rcv,tcp_rcv_established,tcp_data_queue,tcp_receive_window,tcp_rcv_nxt_update(write)(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


copied_seq

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_cleanup_rbuf,tcp_rcv_space_adjust,tcp_inq_hint

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_wup

</td>
<td>




</td>
<td>


read_write

</td>
<td>


\__tcp_cleanup_rbuf,tcp_receive_window,tcp_receive_established

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_nxt

</td>
<td>


read_write

</td>
<td>


read_mostly

</td>
<td>


tcp_rate_check_app_limited,\__tcp_transmit_skb,tcp_event_new_data_sent(write)(tx);tcp_rcv_established,tcp_ack,tcp_clean_rtx_queue(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


segs_out

</td>
<td>


read_write

</td>
<td>




</td>
<td>


\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


data_segs_out

</td>
<td>


read_write

</td>
<td>




</td>
<td>


\__tcp_transmit_skb,tcp_update_skb_after_send

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


bytes_sent

</td>
<td>


read_write

</td>
<td>




</td>
<td>


\__tcp_transmit_skb

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


bytes_acked

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_snd_una_update/tcp_ack

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


dsack_dups

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_una

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_wnd_end,tcp_urg_mode,tcp_minshall_check,tcp_cwnd_validate(tx);tcp_ack,tcp_may_update_window,tcp_clean_rtx_queue(write),tcp_ack_tstamp(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_sml

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_minshall_check,tcp_minshall_update

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_tstamp

</td>
<td>


read_write

</td>
<td>


read_write

</td>
<td>


tcp_ack

</td>
</tr>
<tr>
<td>


void \*

</td>
<td>


tcp_clean_acked

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_ack

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


lsndtime

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_slow_start_after_idle_check,tcp_event_data_sent

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


last_oow_ack_time

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


compressed_ack_rcv_nxt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


tsoffset

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_established_options(tx);tcp_fast_parse_options(rx)

</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


tsq_node

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct list_head

</td>
<td>


tsorted_sent_queue

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_update_skb_after_send

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_wl1

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_may_update_window

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_wnd

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_wnd_end,tcp_tso_should_defer(tx);tcp_fast_path_on(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


max_window

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_bound_to_half_wnd,forced_push

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


mss_cache

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_rate_check_app_limited,tcp_current_mss,tcp_sync_mss,tcp_sndbuf_expand,tcp_tso_should_defer(tx);tcp_update_pacing_rate,tcp_clean_rtx_queue(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


window_clamp

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_rcv_space_adjust,\__tcp_select_window

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_ssthresh

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


\__tcp_select_window

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


scaling_ratio

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_win_from_space

</td>
</tr>
<tr>
<td>


struct

</td>
<td>


tcp_rack

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


advmss

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_rcv_space_adjust

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


compressed_ack

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


dup_ack_counter

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


tlp_retrans

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


tcp_usec_ts

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


chrono_start

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_chrono_start/stop(tcp_write_xmit,tcp_cwnd_validate,tcp_send_syn_data)

</td>
</tr>
<tr>
<td>


u32\[3\]

</td>
<td>


chrono_stat

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_chrono_start/stop(tcp_write_xmit,tcp_cwnd_validate,tcp_send_syn_data)

</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


chrono_type

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_chrono_start/stop(tcp_write_xmit,tcp_cwnd_validate,tcp_send_syn_data)

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


rate_app_limited

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_rate_gen

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


fastopen_connect

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


fastopen_no_cookie

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


is_sack_reneg

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_skb_entail,tcp_ack

</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


fastopen_client_fail

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:4

</td>
<td>


nonagle

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_skb_entail,tcp_push_pending_frames

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


thin_lto

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


recvmsg_inq

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_recvmsg

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


repair

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_write_xmit

</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


frto

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


repair_queue

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


save_syn

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


syn_data

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


syn_fastopen

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


syn_fastopen_exp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


syn_fastopen_ch

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


syn_data_acked

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


is_cwnd_limited

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_cwnd_validate,tcp_is_cwnd_limited

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


tlp_high_seq

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_ack

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


tcp_tx_delay

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u64

</td>
<td>


tcp_wstamp_ns

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_pacing_check,tcp_tso_should_defer,tcp_update_skb_after_send

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


tcp_clock_cache

</td>
<td>


read_write

</td>
<td>


read_write

</td>
<td>


tcp_mstamp_refresh(tcp_write_xmit/tcp_rcv_space_adjust),\__tcp_transmit_skb,tcp_tso_should_defer;timer

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


tcp_mstamp

</td>
<td>


read_write

</td>
<td>


read_write

</td>
<td>


tcp_mstamp_refresh(tcp_write_xmit/tcp_rcv_space_adjust)(tx);tcp_rcv_space_adjust,tcp_rate_gen,tcp_clean_rtx_queue,tcp_ack_update_rtt/tcp_time_stamp(rx);timer

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


srtt_us

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_tso_should_defer(tx);tcp_update_pacing_rate,\__tcp_set_rto,tcp_rtt_estimator(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


mdev_us

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_rtt_estimator

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


mdev_max_us

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rttvar_us

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


\__tcp_set_rto

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rtt_seq

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_rtt_estimator

</td>
</tr>
<tr>
<td>


struct minmax

</td>
<td>


rtt_min

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_min_rtt/tcp_rate_gen,tcp_min_rtttcp_update_rtt_min

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


packets_out

</td>
<td>


read_write

</td>
<td>


read_write

</td>
<td>


tcp_packets_in_flight(tx/rx);tcp_slow_start_after_idle_check,tcp_nagle_check,tcp_rate_skb_sent,tcp_event_new_data_sent,tcp_cwnd_validate,tcp_write_xmit(tx);tcp_ack,tcp_clean_rtx_queue,tcp_update_pacing_rate(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


retrans_out

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_packets_in_flight,tcp_rate_check_app_limited

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


max_packets_out

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_cwnd_validate

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


cwnd_usage_seq

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_cwnd_validate

</td>
</tr>
<tr>
<td>


u16

</td>
<td>


urg_data

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_fast_path_check

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


ecn_flags

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_ecn_send

</td>
</tr>
<tr>
<td>


u8

</td>
<td>


keepalive_probes

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


reordering

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_sndbuf_expand

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


reord_seen

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_up

</td>
<td>


read_write

</td>
<td>


read_mostly

</td>
<td>


tcp_mark_urg,tcp_urg_mode,\__tcp_transmit_skb(tx);tcp_clean_rtx_queue(rx)

</td>
</tr>
<tr>
<td>


struct tcp_options_received

</td>
<td>


rx_opt

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_established_options(tx);tcp_fast_path_on,tcp_ack_update_window,tcp_is_sack,tcp_data_queue,tcp_rcv_established,tcp_ack_update_rtt(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_ssthresh

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_update_pacing_rate

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_cwnd

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_snd_cwnd,tcp_rate_check_app_limited,tcp_tso_should_defer(tx);tcp_update_pacing_rate

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_cwnd_cnt

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_cwnd_clamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_cwnd_used

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


snd_cwnd_stamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


prior_cwnd

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


prr_delivered

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


prr_out

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_rate_skb_sent,tcp_newly_delivered(tx);tcp_ack,tcp_rate_gen,tcp_clean_rtx_queue(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


delivered

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_rate_skb_sent, tcp_newly_delivered(tx);tcp_ack, tcp_rate_gen, tcp_clean_rtx_queue (rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


delivered_ce

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>


tcp_rate_skb_sent(tx);tcp_rate_gen(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


received_ce

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u32\[3\]

</td>
<td>


received_ecn_bytes

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:4

</td>
<td>


received_ce_pending

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u32\[3\]

</td>
<td>


delivered_ecn_bytes

</td>
<td>




</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


pkts_acked_ewma

</td>
<td>




</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


syn_ect_snt

</td>
<td>


write_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


syn_ect_rcv

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


accecn_minlen

</td>
<td>


write_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


est_ecnfield

</td>
<td>




</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


accecn_opt_demand

</td>
<td>


read_mostly

</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u8:2

</td>
<td>


prev_ecnfield

</td>
<td>




</td>
<td>


read_write

</td>
<td>




</td>
</tr>
<tr>
<td>


u64

</td>
<td>


accecn_opt_tstamp

</td>
<td>


read_write

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:4

</td>
<td>


accecn_fail_mode

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


lost

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_ack

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


app_limited

</td>
<td>


read_write

</td>
<td>


read_mostly

</td>
<td>


tcp_rate_check_app_limited,tcp_rate_skb_sent(tx);tcp_rate_gen(rx)

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


first_tx_mstamp

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_rate_skb_sent

</td>
</tr>
<tr>
<td>


u64

</td>
<td>


delivered_mstamp

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_rate_skb_sent

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rate_delivered

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_rate_gen

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rate_interval_us

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


rate_delivered,rate_app_limited

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_wnd

</td>
<td>


read_write

</td>
<td>


read_mostly

</td>
<td>


tcp_select_window,tcp_receive_window,tcp_fast_path_check

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


write_seq

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_rate_check_app_limited,tcp_write_queue_empty,tcp_skb_entail,forced_push,tcp_mark_push

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


notsent_lowat

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_stream_memory_free

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


pushed_seq

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_mark_push,forced_push

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


lost_out

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_left_out(tx);tcp_packets_in_flight(tx/rx);tcp_rate_check_app_limited(rx)

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


sacked_out

</td>
<td>


read_mostly

</td>
<td>


read_mostly

</td>
<td>


tcp_left_out(tx);tcp_packets_in_flight(tx/rx);tcp_clean_rtx_queue(rx)

</td>
</tr>
<tr>
<td>


struct hrtimer

</td>
<td>


pacing_timer

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct hrtimer

</td>
<td>


compressed_ack_timer

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct sk_buff\*

</td>
<td>


retransmit_skb_hint

</td>
<td>


read_mostly

</td>
<td>




</td>
<td>


tcp_clean_rtx_queue

</td>
</tr>
<tr>
<td>


struct rb_root

</td>
<td>


out_of_order_queue

</td>
<td>




</td>
<td>


read_mostly

</td>
<td>


tcp_data_queue,tcp_fast_path_check

</td>
</tr>
<tr>
<td>


struct sk_buff\*

</td>
<td>


ooo_last_skb

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_sack_block\[1\]

</td>
<td>


duplicate_sack

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_sack_block\[4\]

</td>
<td>


selective_acks

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_sack_block\[4\]

</td>
<td>


recv_sack_cache

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct sk_buff\*

</td>
<td>


highest_sack

</td>
<td>


read_write

</td>
<td>




</td>
<td>


tcp_event_new_data_sent

</td>
</tr>
<tr>
<td>


u32

</td>
<td>


prior_ssthresh

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


high_seq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


retrans_stamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


undo_marker

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


undo_retrans

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u64

</td>
<td>


bytes_retrans

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


total_retrans

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rto_stamp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


total_rto

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


total_rto_recoveries

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


total_rto_time

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


urg_seq

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


keepalive_time

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


unsigned_int

</td>
<td>


keepalive_intvl

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


int

</td>
<td>


linger2

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8

</td>
<td>


bpf_sock_ops_cb_flags

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u8:1

</td>
<td>


bpf_chg_cc_inprogress

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u16

</td>
<td>


timeout_rehash

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_ooopack

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


rcv_rtt_last_tsecr

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct

</td>
<td>


rcv_rtt_est

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_rcv_space_adjust,tcp_rcv_established

</td>
</tr>
<tr>
<td>


struct

</td>
<td>


rcvq_space

</td>
<td>




</td>
<td>


read_write

</td>
<td>


tcp_rcv_space_adjust

</td>
</tr>
<tr>
<td>


struct

</td>
<td>


mtu_probe

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


plb_rehash

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


u32

</td>
<td>


mtu_info

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


is_mptcp

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


smc_hs_congested

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


bool

</td>
<td>


syn_smc

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_sock_af_ops\*

</td>
<td>


af_specific

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_md5sig_info\*

</td>
<td>


md5sig_info

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct tcp_fastopen_request\*

</td>
<td>


fastopen_req

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct request_sock\*

</td>
<td>


fastopen_rsk

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


struct saved_syn\*

</td>
<td>


saved_syn

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
</tbody>
</table>

---

# Power Sourcing Equipment (PSE) Documentation

_Peios Kernel / Internals / Networking / pse-pd_

> Reference for Power Sourcing Equipment (PSE) Documentation.

<a id="rst-power-sourcing-equipment-pse-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Power Sourcing Equipment (PSE) in IEEE 802.3 Standard](</kernel/internals/networking/pse-pd/introduction.md>)
- [PSE Power Interface (PSE PI) Documentation](</kernel/internals/networking/pse-pd/pse-pi.md>)

---

# Power Sourcing Equipment (PSE) in IEEE 802.3 Standard

_Peios Kernel / Internals / Networking / pse-pd_

> Power Sourcing Equipment (PSE) is essential in networks for delivering power along with data over Ethernet cables. It usually refers to devices like switches and hubs that supply power to Powered Devices (PDs) such as IP cameras, VoIP…

<a id="rst-power-sourcing-equipment-pse-in-ieee-802-3-standard"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

Power Sourcing Equipment (PSE) is essential in networks for delivering power along with data over Ethernet cables. It usually refers to devices like switches and hubs that supply power to Powered Devices (PDs) such as IP cameras, VoIP phones, and wireless access points.

<a id="rst-pse-vs-podl-pse"></a>

## PSE vs. PoDL PSE

PSE in the IEEE 802.3 standard generally refers to equipment that provides power alongside data over Ethernet cables, typically associated with Power over Ethernet (PoE).

PoDL PSE, or Power over Data Lines PSE, specifically denotes PSEs operating with single balanced twisted-pair PHYs, as per Clause 104 of IEEE 802.3. PoDL is significant in contexts like automotive and industrial controls where power and data delivery over a single pair is advantageous.

<a id="rst-ieee-802-3-2018-addendums-and-related-clauses"></a>

## IEEE 802.3-2018 Addendums and Related Clauses

Key addenda to the IEEE 802.3-2018 standard relevant to power delivery over Ethernet are as follows:

- **802.3af (Approved in 2003-06-12)**: Known as PoE in the market, detailed in Clause 33, delivering up to 15.4W of power.

- **802.3at (Approved in 2009-09-11)**: Marketed as PoE+, enhancing PoE as covered in Clause 33, increasing power delivery to up to 30W.

- **802.3bt (Approved in 2018-09-27)**: Known as 4PPoE in the market, outlined in Clause 33. Type 3 delivers up to 60W, and Type 4 up to 100W.

- **802.3bu (Approved in 2016-12-07)**: Formerly referred to as PoDL, detailed in Clause 104. Introduces Classes 0 - 9. Class 9 PoDL PSE delivers up to \~65W

<a id="rst-kernel-naming-convention-recommendations"></a>

## Kernel Naming Convention Recommendations

For clarity and consistency within the Linux kernel's networking subsystem, the following naming conventions are recommended:

- For general PSE (PoE) code, use "c33_pse" key words. For example: `enum ethtool_c33_pse_admin_state c33_admin_control;`. This aligns with Clause 33, encompassing various PoE forms.

- For PoDL PSE - specific code, use "podl_pse". For example: `enum ethtool_podl_pse_admin_state podl_admin_control;` to differentiate PoDL PSE settings according to Clause 104.

<a id="rst-summary-of-clause-33-data-terminal-equipment-dte-power-via-media-dependent-interface-mdi"></a>

## Summary of Clause 33: Data Terminal Equipment (DTE) Power via Media Dependent Interface (MDI)

Clause 33 of the IEEE 802.3 standard defines the functional and electrical characteristics of Powered Device (PD) and Power Sourcing Equipment (PSE). These entities enable power delivery using the same generic cabling as for data transmission, integrating power with data communication for devices such as 10BASE-T, 100BASE-TX, or 1000BASE-T.

<a id="rst-summary-of-clause-104-power-over-data-lines-podl-of-single-balanced-twisted-pair-ethernet"></a>

## Summary of Clause 104: Power over Data Lines (PoDL) of Single Balanced Twisted-Pair Ethernet

Clause 104 of the IEEE 802.3 standard delineates the functional and electrical characteristics of PoDL Powered Devices (PDs) and PoDL Power Sourcing Equipment (PSEs). These are designed for use with single balanced twisted-pair Ethernet Physical Layers. In this clause, 'PSE' refers specifically to PoDL PSE, and 'PD' to PoDL PD. The key intent is to provide devices with a unified interface for both data and the power required to process this data over a single balanced twisted-pair Ethernet connection.

---

# PSE Power Interface (PSE PI) Documentation

_Peios Kernel / Internals / Networking / pse-pd_

> The Power Sourcing Equipment Power Interface (PSE PI) plays a pivotal role in the architecture of Power over Ethernet (PoE) systems. It is essentially a blueprint that outlines how one or multiple power sources are connected to the…

<a id="rst-pse-power-interface-pse-pi-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Power Sourcing Equipment Power Interface (PSE PI) plays a pivotal role in the architecture of Power over Ethernet (PoE) systems. It is essentially a blueprint that outlines how one or multiple power sources are connected to the eight-pin modular jack, commonly known as the Ethernet RJ45 port. This connection scheme is crucial for enabling the delivery of power alongside data over Ethernet cables.

<a id="rst-documentation-and-standards"></a>

## Documentation and Standards

The IEEE 802.3 standard provides detailed documentation on the PSE PI. Specifically:

- Section "33.2.3 PI pin assignments" covers the pin assignments for PoE systems that utilize two pairs for power delivery.

- Section "145.2.4 PSE PI" addresses the configuration for PoE systems that deliver power over all four pairs of an Ethernet cable.

<a id="rst-pse-pi-and-single-pair-ethernet"></a>

## PSE PI and Single Pair Ethernet

Single Pair Ethernet (SPE) represents a different approach to Ethernet connectivity, utilizing just one pair of conductors for both data and power transmission. Unlike the configurations detailed in the PSE PI for standard Ethernet, which can involve multiple power sourcing arrangements across four or two pairs of wires, SPE operates on a simpler model due to its single-pair design. As a result, the complexities of choosing between alternative pin assignments for power delivery, as described in the PSE PI for multi-pair Ethernet, are not applicable to SPE.

<a id="rst-understanding-pse-pi"></a>

## Understanding PSE PI

The Power Sourcing Equipment Power Interface (PSE PI) is a framework defining how Power Sourcing Equipment (PSE) delivers power to Powered Devices (PDs) over Ethernet cables. It details two main configurations for power delivery, known as Alternative A and Alternative B, which are distinguished not only by their method of power transmission but also by the implications for polarity and data transmission direction.

<a id="rst-alternative-a-and-b-overview"></a>

## Alternative A and B Overview

- **Alternative A:** Utilizes RJ45 conductors 1, 2, 3 and 6. In either case of networks 10/100BaseT or 1G/2G/5G/10GBaseT, the pairs used are carrying data. The power delivery's polarity in this alternative can vary based on the MDI (Medium Dependent Interface) or MDI-X (Medium Dependent Interface Crossover) configuration.

- **Alternative B:** Utilizes RJ45 conductors 4, 5, 7 and 8. In case of 10/100BaseT network the pairs used are spare pairs without data and are less influenced by data transmission direction. This is not the case for 1G/2G/5G/10GBaseT network. Alternative B includes two configurations with different polarities, known as variant X and variant S, to accommodate different network requirements and device specifications.

<a id="rst-table-145-3-pse-pinout-alternatives"></a>

## Table 145-3 PSE Pinout Alternatives

The following table outlines the pin configurations for both Alternative A and Alternative B.


<table>
<thead>
<tr>
<th>


Conductor

</th>
<th>


- **Alternative A**

  (MDI-X)

</th>
<th>


- **Alternative A**

  - **(MDI)** 

</th>
<th>


- **Alternative B**

  - **(X)** 

</th>
<th>


- **Alternative B**

  - **(S)** 

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


1

</td>
<td>


Negative V

</td>
<td>


Positive V

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


2

</td>
<td>


Negative V

</td>
<td>


Positive V

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


3

</td>
<td>


Positive V

</td>
<td>


Negative V

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


4

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


Negative V

</td>
<td>


Positive V

</td>
</tr>
<tr>
<td>


5

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


Negative V

</td>
<td>


Positive V

</td>
</tr>
<tr>
<td>


6

</td>
<td>


Positive V

</td>
<td>


Negative V

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


7

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


Positive V

</td>
<td>


Negative V

</td>
</tr>
<tr>
<td>


8

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


- <!-- empty source list item -->

</td>
<td>


Positive V

</td>
<td>


Negative V

</td>
</tr>
</tbody>
</table>

> [!NOTE]
>
> - "Positive V" and "Negative V" indicate the voltage polarity for each pin.
>
> - "-" indicates that the pin is not used for power delivery in that specific configuration.

<a id="rst-pse-pi-compatibilities"></a>

## PSE PI compatibilities

The following table outlines the compatibility between the pinout alternative and the 1000/2.5G/5G/10GBaseT in the PSE 2 pairs connection.


<table>
<thead>
<tr>
<th>


Variant

</th>
<th>


Alternative (A/B)

</th>
<th>


Power Feeding Type (Direct/Phantom)

</th>
<th>


Compatibility with 1000/2.5G/5G/10GBaseT

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


1

</td>
<td>


A

</td>
<td>


Phantom

</td>
<td>


Yes

</td>
</tr>
<tr>
<td>


2

</td>
<td>


B

</td>
<td>


Phantom

</td>
<td>


Yes

</td>
</tr>
<tr>
<td>


3

</td>
<td>


B

</td>
<td>


Direct

</td>
<td>


No

</td>
</tr>
</tbody>
</table>

> [!NOTE]
>
> - - **"Direct" indicate a variant where the power is injected directly to pairs**
>
>     without using magnetics in case of spare pairs.
>
> - - **"Phantom" indicate power path over coils/magnetics as it is done for**
>
>     Alternative A variant.

In case of PSE 4 pairs, a PSE supporting only 10/100BaseT (which mean Direct Power on pinout Alternative B) is not compatible with a 4 pairs 1000/2.5G/5G/10GBaseT.

<a id="rst-pse-power-interface-pse-pi-connection-diagram"></a>

## PSE Power Interface (PSE PI) Connection Diagram

The diagram below illustrates the connection architecture between the RJ45 port, the Ethernet PHY (Physical Layer), and the PSE PI (Power Sourcing Equipment Power Interface), demonstrating how power and data are delivered simultaneously through an Ethernet cable. The RJ45 port serves as the physical interface for these connections, with each of its eight pins connected to both the Ethernet PHY for data transmission and the PSE PI for power delivery.



```text
+--------------------------+
|                          |
|          RJ45 Port       |
|                          |
+--+--+--+--+--+--+--+--+--+                +-------------+
  1| 2| 3| 4| 5| 6| 7| 8|                   |             |
   |  |  |  |  |  |  |  o-------------------+             |
   |  |  |  |  |  |  o--|-------------------+             +<--- PSE 1
   |  |  |  |  |  o--|--|-------------------+             |
   |  |  |  |  o--|--|--|-------------------+             |
   |  |  |  o--|--|--|--|-------------------+  PSE PI     |
   |  |  o--|--|--|--|--|-------------------+             |
   |  o--|--|--|--|--|--|-------------------+             +<--- PSE 2 (optional)
   o--|--|--|--|--|--|--|-------------------+             |
   |  |  |  |  |  |  |  |                   |             |
+--+--+--+--+--+--+--+--+--+                +-------------+
|                          |
|       Ethernet PHY       |
|                          |
+--------------------------+
```

<a id="rst-simple-pse-pi-configuration-for-alternative-a"></a>

## Simple PSE PI Configuration for Alternative A

The diagram below illustrates a straightforward PSE PI (Power Sourcing Equipment Power Interface) configuration designed to support the Alternative A setup for Power over Ethernet (PoE). This implementation is tailored to provide power delivery through the data-carrying pairs of an Ethernet cable, suitable for either MDI or MDI-X configurations, albeit supporting one variation at a time.



```text
        +-------------+
        |    PSE PI   |
8  -----+                             +-------------+
7  -----+                    Rail 1   |
6  -----+------+----------------------+
5  -----+      |                      |
4  -----+      |             Rail 2   |  PSE 1
3  -----+------/         +------------+
2  -----+--+-------------/            |
1  -----+--/                          +-------------+
        |
        +-------------+
```

In this configuration:

- Pins 1 and 2, as well as pins 3 and 6, are utilized for power delivery in addition to data transmission. This aligns with the standard wiring for 10/100BaseT Ethernet networks where these pairs are used for data.

- Rail 1 and Rail 2 represent the positive and negative voltage rails, with Rail 1 connected to pins 1 and 2, and Rail 2 connected to pins 3 and 6. More advanced PSE PI configurations may include integrated or external switches to change the polarity of the voltage rails, allowing for compatibility with both MDI and MDI-X configurations.

More complex PSE PI configurations may include additional components, to support Alternative B, or to provide additional features such as power management, or additional power delivery capabilities such as 2-pair or 4-pair power delivery.



```text
        +-------------+
        |    PSE PI   |
        |        +---+
8  -----+--------+   |                 +-------------+
7  -----+--------+   |       Rail 1   |
6  -----+--------+   +-----------------+
5  -----+--------+   |                |
4  -----+--------+   |       Rail 2   |  PSE 1
3  -----+--------+   +----------------+
2  -----+--------+   |                |
1  -----+--------+   |                 +-------------+
        |        +---+
        +-------------+
```

<a id="rst-device-tree-configuration-describing-pse-pi-configurations"></a>

## Device Tree Configuration: Describing PSE PI Configurations

The necessity for a separate PSE PI node in the device tree is influenced by the intricacy of the Power over Ethernet (PoE) system's setup. Here are descriptions of both simple and complex PSE PI configurations to illustrate this decision-making process:

**Simple PSE PI Configuration:** In a straightforward scenario, the PSE PI setup involves a direct, one-to-one connection between a single PSE controller and an Ethernet port. This setup typically supports basic PoE functionality without the need for dynamic configuration or management of multiple power delivery modes. For such simple configurations, detailing the PSE PI within the existing PSE controller's node may suffice, as the system does not encompass additional complexity that warrants a separate node. The primary focus here is on the clear and direct association of power delivery to a specific Ethernet port.

**Complex PSE PI Configuration:** Contrastingly, a complex PSE PI setup may encompass multiple PSE controllers or auxiliary circuits that collectively manage power delivery to one Ethernet port. Such configurations might support a range of PoE standards and require the capability to dynamically configure power delivery based on the operational mode (e.g., PoE2 versus PoE4) or specific requirements of connected devices. In these instances, a dedicated PSE PI node becomes essential for accurately documenting the system architecture. This node would serve to detail the interactions between different PSE controllers, the support for various PoE modes, and any additional logic required to coordinate power delivery across the network infrastructure.

**Guidance:**

For simple PSE setups, including PSE PI information in the PSE controller node might suffice due to the straightforward nature of these systems. However, complex configurations, involving multiple components or advanced PoE features, benefit from a dedicated PSE PI node. This method adheres to IEEE 802.3 specifications, improving documentation clarity and ensuring accurate representation of the PoE system's complexity.

<a id="rst-pse-pi-node-essential-information"></a>

## PSE PI Node: Essential Information

The PSE PI (Power Sourcing Equipment Power Interface) node in a device tree can include several key pieces of information critical for defining the power delivery capabilities and configurations of a PoE (Power over Ethernet) system. Below is a list of such information, along with explanations for their necessity and reasons why they might not be found within a PSE controller node:

1. **Powered Pairs Configuration**

   - *Description:* Identifies the pairs used for power delivery in the Ethernet cable.

   - *Necessity:* Essential to ensure the correct pairs are powered according to the board's design.

   - *PSE Controller Node:* Typically lacks details on physical pair usage, focusing on power regulation.

2. **Polarity of Powered Pairs**

   - *Description:* Specifies the polarity (positive or negative) for each powered pair.

   - *Necessity:* Critical for safe and effective power transmission to PDs.

   - *PSE Controller Node:* Polarity management may exceed the standard functionalities of PSE controllers.

3. **PSE Cells Association**

   - *Description:* Details the association of PSE cells with Ethernet ports or pairs in multi-cell configurations.

   - *Necessity:* Allows for optimized power resource allocation in complex systems.

   - *PSE Controller Node:* Controllers may not manage cell associations directly, focusing instead on power flow regulation.

4. **Support for PoE Standards**

   - *Description:* Lists the PoE standards and configurations supported by the system.

   - *Necessity:* Ensures system compatibility with various PDs and adherence to industry standards.

   - *PSE Controller Node:* Specific capabilities may depend on the overall PSE PI design rather than the controller alone. Multiple PSE cells per PI do not necessarily imply support for multiple PoE standards.

5. **Protection Mechanisms**

   - *Description:* Outlines additional protection mechanisms, such as overcurrent protection and thermal management.

   - *Necessity:* Provides extra safety and stability, complementing PSE controller protections.

   - *PSE Controller Node:* Some protections may be implemented via board-specific hardware or algorithms external to the controller.

---

# XFRM Framework

_Peios Kernel / Internals / Networking / xfrm_

> Reference for XFRM Framework.

<a id="rst-xfrm-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [XFRM device - offloading the IPsec computations](</kernel/internals/networking/xfrm/xfrm-device.md>)
- [XFRM proc - /proc/net/xfrm\_\* files](</kernel/internals/networking/xfrm/xfrm-proc.md>)
- [XFRM sync](</kernel/internals/networking/xfrm/xfrm-sync.md>)
- [XFRM Syscall](</kernel/internals/networking/xfrm/xfrm-sysctl.md>)

---

# XFRM device - offloading the IPsec computations

_Peios Kernel / Internals / Networking / xfrm_

> Shannon Nelson <shannon.nelson@oracle.com> Leon Romanovsky <leonro@nvidia.com>

<a id="rst-xfrm-device-offloading-the-ipsec-computations"></a>
<a id="rst-xfrm-device"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Shannon Nelson &lt;[shannon.nelson@oracle.com](<mailto:shannon.nelson@oracle.com>)&gt; Leon Romanovsky &lt;[leonro@nvidia.com](<mailto:leonro@nvidia.com>)&gt;

<a id="rst-overview"></a>

## Overview

IPsec is a useful feature for securing network traffic, but the computational cost is high: a 10Gbps link can easily be brought down to under 1Gbps, depending on the traffic and link configuration. Luckily, there are NICs that offer a hardware based IPsec offload which can radically increase throughput and decrease CPU utilization.  The XFRM Device interface allows NIC drivers to offer to the stack access to the hardware offload.

Right now, there are two types of hardware offload that kernel supports:

> - IPsec crypto offload:
>
>   - NIC performs encrypt/decrypt
>
>   - Kernel does everything else
>
> - IPsec packet offload:
>
>   - NIC performs encrypt/decrypt
>
>   - NIC does encapsulation
>
>   - Kernel and NIC have SA and policy in-sync
>
>   - NIC handles the SA and policies states
>
>   - The Kernel talks to the keymanager

Userland access to the offload is typically through a system such as libreswan or KAME/raccoon, but the iproute2 'ip xfrm' command set can be handy when experimenting.  An example command might look something like this for crypto offload:



```text
ip x s add proto esp dst 14.0.0.70 src 14.0.0.52 spi 0x07 mode transport \
   reqid 0x07 replay-window 32 \
   aead 'rfc4106(gcm(aes))' 0x44434241343332312423222114131211f4f3f2f1 128 \
   sel src 14.0.0.52/24 dst 14.0.0.70/24 proto tcp \
   offload dev eth4 dir in
```

and for packet offload:



```text
ip x s add proto esp dst 14.0.0.70 src 14.0.0.52 spi 0x07 mode transport \
   reqid 0x07 replay-window 32 \
   aead 'rfc4106(gcm(aes))' 0x44434241343332312423222114131211f4f3f2f1 128 \
   sel src 14.0.0.52/24 dst 14.0.0.70/24 proto tcp \
   offload packet dev eth4 dir in

ip x p add src 14.0.0.70 dst 14.0.0.52 offload packet dev eth4 dir in
tmpl src 14.0.0.70 dst 14.0.0.52 proto esp reqid 10000 mode transport
```

Yes, that's ugly, but that's what shell scripts and/or libreswan are for.

<a id="rst-callbacks-to-implement"></a>

## Callbacks to implement



```text
/* from include/linux/netdevice.h */
struct xfrmdev_ops {
      /* Crypto and Packet offload callbacks */
      int     (*xdo_dev_state_add)(struct net_device *dev,
                                   struct xfrm_state *x,
                                   struct netlink_ext_ack *extack);
      void    (*xdo_dev_state_delete)(struct net_device *dev,
                                      struct xfrm_state *x);
      void    (*xdo_dev_state_free)(struct net_device *dev,
                                    struct xfrm_state *x);
      bool    (*xdo_dev_offload_ok) (struct sk_buff *skb,
                                     struct xfrm_state *x);
      void    (*xdo_dev_state_advance_esn) (struct xfrm_state *x);
      void    (*xdo_dev_state_update_stats) (struct xfrm_state *x);

      /* Solely packet offload callbacks */
      int     (*xdo_dev_policy_add) (struct xfrm_policy *x, struct netlink_ext_ack *extack);
      void    (*xdo_dev_policy_delete) (struct xfrm_policy *x);
      void    (*xdo_dev_policy_free) (struct xfrm_policy *x);
};
```

The NIC driver offering ipsec offload will need to implement callbacks relevant to supported offload to make the offload available to the network stack's XFRM subsystem. Additionally, the feature bits NETIF_F_HW_ESP and NETIF_F_HW_ESP_TX_CSUM will signal the availability of the offload.

<a id="rst-flow"></a>

## Flow

At probe time and before the call to register_netdev(), the driver should set up local data structures and XFRM callbacks, and set the feature bits. The XFRM code's listener will finish the setup on NETDEV_REGISTER.



```text
adapter->netdev->xfrmdev_ops = &ixgbe_xfrmdev_ops;
adapter->netdev->features |= NETIF_F_HW_ESP;
adapter->netdev->hw_enc_features |= NETIF_F_HW_ESP;
```

When new SAs are set up with a request for "offload" feature, the driver's xdo_dev_state_add() will be given the new SA to be offloaded and an indication of whether it is for Rx or Tx.  The driver should

> - verify the algorithm is supported for offloads
>
> - store the SA information (key, salt, target-ip, protocol, etc)
>
> - enable the HW offload of the SA
>
> - return status value:
>
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > 0
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > success
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > -EOPNETSUPP
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > offload not supported, try SW IPsec, not applicable for packet offload mode
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > other
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > fail the request
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>

The driver can also set an offload_handle in the SA, an opaque void pointer that can be used to convey context into the fast-path offload requests:



```text
xs->xso.offload_handle = context;
```

When the network stack is preparing an IPsec packet for an SA that has been setup for offload, it first calls into xdo_dev_offload_ok() with the skb and the intended offload state to ask the driver if the offload will serviceable.  This can check the packet information to be sure the offload can be supported (e.g. IPv4 or IPv6, no IPv4 options, etc) and return true or false to signify its support. In case driver doesn't implement this callback, the stack provides reasonable defaults.

Crypto offload mode: When ready to send, the driver needs to inspect the Tx packet for the offload information, including the opaque context, and set up the packet send accordingly:



```text
xs = xfrm_input_state(skb);
context = xs->xso.offload_handle;
set up HW for send
```

The stack has already inserted the appropriate IPsec headers in the packet data, the offload just needs to do the encryption and fix up the header values.

When a packet is received and the HW has indicated that it offloaded a decryption, the driver needs to add a reference to the decoded SA into the packet's skb.  At this point the data should be decrypted but the IPsec headers are still in the packet data; they are removed later up the stack in xfrm_input().

1. Find and hold the SA that was used to the Rx skb:



   ```text
   /* get spi, protocol, and destination IP from packet headers */
   xs = find xs from (spi, protocol, dest_IP)
   xfrm_state_hold(xs);
   ```

2. Store the state information into the skb:



   ```text
   sp = secpath_set(skb);
   if (!sp) return;
   sp->xvec[sp->len++] = xs;
   sp->olen++;
   ```

3. Indicate the success and/or error status of the offload:



   ```text
   xo = xfrm_offload(skb);
   xo->flags = CRYPTO_DONE;
   xo->status = crypto_status;
   ```

4. Hand the packet to napi_gro_receive() as usual.

In ESN mode, xdo_dev_state_advance_esn() is called from xfrm_replay_advance_esn() for RX, and xfrm_replay_overflow_offload_esn for TX. Driver will check packet seq number and update HW ESN state machine if needed.

Packet offload mode: HW adds and deletes XFRM headers. So in RX path, XFRM stack is bypassed if HW reported success. In TX path, the packet lefts kernel without extra header and not encrypted, the HW is responsible to perform it.

When the SA is removed by the user, the driver's xdo_dev_state_delete() and xdo_dev_policy_delete() are asked to disable the offload.  Later, xdo_dev_state_free() and xdo_dev_policy_free() are called from a garbage collection routine after all reference counts to the state and policy have been removed and any remaining resources can be cleared for the offload state.  How these are used by the driver will depend on specific hardware needs.

As a netdev is set to DOWN the XFRM stack's netdev listener will call xdo_dev_state_delete(), xdo_dev_policy_delete(), xdo_dev_state_free() and xdo_dev_policy_free() on any remaining offloaded states.

Outcome of HW handling packets, the XFRM core can't count hard, soft limits. The HW/driver are responsible to perform it and provide accurate data when xdo_dev_state_update_stats() is called. In case of one of these limits occuried, the driver needs to call to xfrm_state_check_expire() to make sure that XFRM performs rekeying sequence.

---

# XFRM proc - /proc/net/xfrm_* files

_Peios Kernel / Internals / Networking / xfrm_

> Masahide NAKAMURA <nakam@linux-ipv6.org>

<a id="rst-xfrm-proc-proc-net-xfrm-files"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Masahide NAKAMURA &lt;[nakam@linux-ipv6.org](<mailto:nakam@linux-ipv6.org>)&gt;

<a id="rst-transformation-statistics"></a>

## Transformation Statistics

The xfrm_proc code is a set of statistics showing numbers of packets dropped by the transformation code and why.  These counters are defined as part of the linux private MIB.  These counters can be viewed in /proc/net/xfrm_stat.

<a id="rst-inbound-errors"></a>

### Inbound errors

- **XfrmInError:**

  All errors which is not matched others

- **XfrmInBufferError:**

  No buffer is left

- **XfrmInHdrError:**

  Header error

- **XfrmInNoStates:**

  No state is found i.e. Either inbound SPI, address, or IPsec protocol at SA is wrong

- **XfrmInStateProtoError:**

  Transformation protocol specific error e.g. SA key is wrong

- **XfrmInStateModeError:**

  Transformation mode specific error

- **XfrmInStateSeqError:**

  Sequence error i.e. Sequence number is out of window

- **XfrmInStateExpired:**

  State is expired

- **XfrmInStateMismatch:**

  State has mismatch option e.g. UDP encapsulation type is mismatch

- **XfrmInStateInvalid:**

  State is invalid

- **XfrmInTmplMismatch:**

  No matching template for states e.g. Inbound SAs are correct but SP rule is wrong

- **XfrmInNoPols:**

  No policy is found for states e.g. Inbound SAs are correct but no SP is found

- **XfrmInPolBlock:**

  Policy discards

- **XfrmInPolError:**

  Policy error

- **XfrmAcquireError:**

  State hasn't been fully acquired before use

- **XfrmFwdHdrError:**

  Forward routing of a packet is not allowed

- **XfrmInStateDirError:**

  State direction mismatch (lookup found an output state on the input path, expected input or no direction)

<a id="rst-outbound-errors"></a>

### Outbound errors

- **XfrmOutError:**

  All errors which is not matched others

- **XfrmOutBundleGenError:**

  Bundle generation error

- **XfrmOutBundleCheckError:**

  Bundle check error

- **XfrmOutNoStates:**

  No state is found

- **XfrmOutStateProtoError:**

  Transformation protocol specific error

- **XfrmOutStateModeError:**

  Transformation mode specific error

- **XfrmOutStateSeqError:**

  Sequence error i.e. Sequence number overflow

- **XfrmOutStateExpired:**

  State is expired

- **XfrmOutPolBlock:**

  Policy discards

- **XfrmOutPolDead:**

  Policy is dead

- **XfrmOutPolError:**

  Policy error

- **XfrmOutStateInvalid:**

  State is invalid, perhaps expired

- **XfrmOutStateDirError:**

  State direction mismatch (lookup found an input state on the output path, expected output or no direction)

---

# XFRM sync

_Peios Kernel / Internals / Networking / xfrm_

> The sync patches work is based on initial patches from Krisztian <hidden@balabit.hu> and others and additional patches from Jamal <hadi@cyberus.ca>.

<a id="rst-xfrm-sync"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The sync patches work is based on initial patches from Krisztian &lt;[hidden@balabit.hu](<mailto:hidden@balabit.hu>)&gt; and others and additional patches from Jamal &lt;[hadi@cyberus.ca](<mailto:hadi@cyberus.ca>)&gt;.

The end goal for syncing is to be able to insert attributes + generate events so that the SA can be safely moved from one machine to another for HA purposes. The idea is to synchronize the SA so that the takeover machine can do the processing of the SA as accurate as possible if it has access to it.

We already have the ability to generate SA add/del/upd events. These patches add ability to sync and have accurate lifetime byte (to ensure proper decay of SAs) and replay counters to avoid replay attacks with as minimal loss at failover time. This way a backup stays as closely up-to-date as an active member.

Because the above items change for every packet the SA receives, it is possible for a lot of the events to be generated. For this reason, we also add a nagle-like algorithm to restrict the events. i.e we are going to set thresholds to say "let me know if the replay sequence threshold is reached or 10 secs have passed" These thresholds are set system-wide via sysctls or can be updated per SA.

The identified items that need to be synchronized are: - the lifetime byte counter note that: lifetime time limit is not important if you assume the failover machine is known ahead of time since the decay of the time countdown is not driven by packet arrival. - the replay sequence for both inbound and outbound

<a id="rst-message-structure"></a>

## 1) Message Structure

nlmsghdr:aevent_id:optional-TLVs.

The netlink message types are:

XFRM_MSG_NEWAE and XFRM_MSG_GETAE.

A XFRM_MSG_GETAE does not have TLVs.

A XFRM_MSG_NEWAE will have at least two TLVs (as is discussed further below).

aevent_id structure looks like:



```text
struct xfrm_aevent_id {
          struct xfrm_usersa_id           sa_id;
          xfrm_address_t                  saddr;
          __u32                           flags;
          __u32                           reqid;
};
```

The unique SA is identified by the combination of xfrm_usersa_id, reqid and saddr.

flags are used to indicate different things. The possible flags are:



```text
XFRM_AE_RTHR=1, /* replay threshold*/
XFRM_AE_RVAL=2, /* replay value */
XFRM_AE_LVAL=4, /* lifetime value */
XFRM_AE_ETHR=8, /* expiry timer threshold */
XFRM_AE_CR=16, /* Event cause is replay update */
XFRM_AE_CE=32, /* Event cause is timer expiry */
XFRM_AE_CU=64, /* Event cause is policy update */
```

How these flags are used is dependent on the direction of the message (kernel&lt;-&gt;user) as well the cause (config, query or event). This is described below in the different messages.

The pid will be set appropriately in netlink to recognize direction (0 to the kernel and pid = processid that created the event when going from kernel to user space)

A program needs to subscribe to multicast group XFRMNLGRP_AEVENTS to get notified of these events.

<a id="rst-tlvs-reflect-the-different-parameters"></a>

## 2) TLVS reflect the different parameters

- **a)** byte value (XFRMA_LTIME_VAL)

  This TLV carries the running/current counter for byte lifetime since last event.

- **b)** replay value (XFRMA_REPLAY_VAL)

  This TLV carries the running/current counter for replay sequence since last event.

- **c)** replay threshold (XFRMA_REPLAY_THRESH)

  This TLV carries the threshold being used by the kernel to trigger events when the replay sequence is exceeded.

- **d)** expiry timer (XFRMA_ETIMER_THRESH)

  This is a timer value in milliseconds which is used as the nagle value to rate limit the events.

<a id="rst-default-configurations-for-the-parameters"></a>

## 3) Default configurations for the parameters

By default these events should be turned off unless there is at least one listener registered to listen to the multicast group XFRMNLGRP_AEVENTS.

Programs installing SAs will need to specify the two thresholds, however, in order to not change existing applications such as racoon we also provide default threshold values for these different parameters in case they are not specified.

the two sysctls/proc entries are:

- **a)** /proc/sys/net/core/sysctl_xfrm_aevent_etime

  Used to provide default values for the XFRMA_ETIMER_THRESH in incremental units of time of 100ms. The default is 10 (1 second)

- **b)** /proc/sys/net/core/sysctl_xfrm_aevent_rseqth

  Used to provide default values for XFRMA_REPLAY_THRESH parameter in incremental packet count. The default is two packets.

<a id="rst-message-types"></a>

## 4) Message types

- **a)** XFRM_MSG_GETAE issued by user--&gt;kernel. XFRM_MSG_GETAE does not carry any TLVs.

  The response is a XFRM_MSG_NEWAE which is formatted based on what XFRM_MSG_GETAE queried for.

  The response will always have XFRMA_LTIME_VAL and XFRMA_REPLAY_VAL TLVs.

  > - if XFRM_AE_RTHR flag is set, then XFRMA_REPLAY_THRESH is also retrieved
  >
  > - if XFRM_AE_ETHR flag is set, then XFRMA_ETIMER_THRESH is also retrieved

- **b)** XFRM_MSG_NEWAE is issued by either user space to configure or kernel to announce events or respond to a XFRM_MSG_GETAE.

  - **i)** user --&gt; kernel to configure a specific SA.

    any of the values or threshold parameters can be updated by passing the appropriate TLV.

    A response is issued back to the sender in user space to indicate success or failure.

    In the case of success, additionally an event with XFRM_MSG_NEWAE is also issued to any listeners as described in iii).

  - **ii)** kernel-&gt;user direction as a response to XFRM_MSG_GETAE

    The response will always have XFRMA_LTIME_VAL and XFRMA_REPLAY_VAL TLVs.

    The threshold TLVs will be included if explicitly requested in the XFRM_MSG_GETAE message.

  - **iii)** kernel-&gt;user to report as event if someone sets any values or thresholds for an SA using XFRM_MSG_NEWAE (as described in \#i above). In such a case XFRM_AE_CU flag is set to inform the user that the change happened as a result of an update. The message will always have XFRMA_LTIME_VAL and XFRMA_REPLAY_VAL TLVs.

  - **iv)** kernel-&gt;user to report event when replay threshold or a timeout is exceeded.

In such a case either XFRM_AE_CR (replay exceeded) or XFRM_AE_CE (timeout happened) is set to inform the user what happened. Note the two flags are mutually exclusive. The message will always have XFRMA_LTIME_VAL and XFRMA_REPLAY_VAL TLVs.

<a id="rst-exceptions-to-threshold-settings"></a>

## 5) Exceptions to threshold settings

If you have an SA that is getting hit by traffic in bursts such that there is a period where the timer threshold expires with no packets seen, then an odd behavior is seen as follows: The first packet arrival after a timer expiry will trigger a timeout event; i.e we don't wait for a timeout period or a packet threshold to be reached. This is done for simplicity and efficiency reasons.

-JHS

---

# XFRM Syscall

_Peios Kernel / Internals / Networking / xfrm_

> default 30 - hard timeout in seconds for acquire requests

<a id="rst-xfrm-syscall"></a>

<a id="rst-proc-sys-net-core-xfrm-variables"></a>

## /proc/sys/net/core/xfrm\_\* Variables

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **xfrm_acq_expires - INTEGER**

  default 30 - hard timeout in seconds for acquire requests

---

# mac80211 authentication and association flows

_Peios Kernel / Internals / Networking_

> Kernel reference: mac80211 authentication and association flows.

This outlines the Linux authentication/association and
deauthentication/disassociation flows.
This can be converted into a diagram using the service
at http://www.websequencediagrams.com/

```mermaid
sequenceDiagram
    participant userspace
    participant mac80211
    participant driver
    alt authentication needed (not FT)
    userspace->>mac80211: authenticate
    alt authenticated/authenticating already
    mac80211->>driver: sta_state(AP, not-exists)
    mac80211->>driver: bss_info_changed(clear BSSID)
    else associated
    Note over mac80211,driver: like deauth/disassoc, without sending the<br/>BA session stop & deauth/disassoc frames
    end
    mac80211->>driver: config(channel, channel type)
    mac80211->>driver: bss_info_changed(set BSSID, basic rate bitmap)
    mac80211->>driver: sta_state(AP, exists)
    alt no probe request data known
    mac80211->>driver: TX directed probe request
    driver->>mac80211: RX probe response
    end
    mac80211->>driver: TX auth frame
    driver->>mac80211: RX auth frame
    alt WEP shared key auth
    mac80211->>driver: TX auth frame
    driver->>mac80211: RX auth frame
    end
    mac80211->>driver: sta_state(AP, authenticated)
    mac80211->>userspace: RX auth frame
    end
    userspace->>mac80211: associate
    alt authenticated or associated
    Note over mac80211,driver: cleanup like for authenticate
    end
    alt not previously authenticated (FT)
    mac80211->>driver: config(channel, channel type)
    mac80211->>driver: bss_info_changed(set BSSID, basic rate bitmap)
    mac80211->>driver: sta_state(AP, exists)
    mac80211->>driver: sta_state(AP, authenticated)
    end
    mac80211->>driver: TX assoc
    driver->>mac80211: RX assoc response
    Note over mac80211: init rate control
    mac80211->>driver: sta_state(AP, associated)
    alt not using WPA
    mac80211->>driver: sta_state(AP, authorized)
    end
    mac80211->>driver: set up QoS parameters
    mac80211->>driver: bss_info_changed(QoS, HT, associated with AID)
    mac80211->>userspace: associated
    Note left of userspace: associated now
    alt using WPA
    Note over userspace: do 4-way-handshake<br/>(data frames)
    userspace->>mac80211: authorized
    mac80211->>driver: sta_state(AP, authorized)
    end
    userspace->>mac80211: deauthenticate/disassociate
    mac80211->>driver: stop BA sessions
    mac80211->>driver: TX deauth/disassoc
    mac80211->>driver: flush frames
    mac80211->>driver: sta_state(AP,associated)
    mac80211->>driver: sta_state(AP,authenticated)
    mac80211->>driver: sta_state(AP,exists)
    mac80211->>driver: sta_state(AP,not-exists)
    mac80211->>driver: turn off powersave
    mac80211->>driver: bss_info_changed(clear BSSID, not associated, no QoS, ...)
    mac80211->>driver: config(channel type to non-HT)
    mac80211->>userspace: disconnected
```

---

# NFSv4.1 XDR source

_Peios Kernel / Internals / Networking / sunrpc/xdr_

> Retained NFSv4.1 XDR declarations, including their original copyright and redistribution terms.

Retained NFSv4.1 XDR declarations, including their original copyright and redistribution terms.


```c
/*
 * Copyright (c) 2010 IETF Trust and the persons identified
 * as the document authors.  All rights reserved.
 *
 * The document authors are identified in RFC 3530 and
 * RFC 5661.
 *
 * Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the
 * following conditions are met:
 *
 * - Redistributions of source code must retain the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer in the documentation and/or other
 *   materials provided with the distribution.
 *
 * - Neither the name of Internet Society, IETF or IETF
 *   Trust, nor the names of specific contributors, may be
 *   used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
 *   AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 *   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *   FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
 *   EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 *   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 *   SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 *   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 *   IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 *   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

pragma header nfs4;

/*
 * Basic typedefs for RFC 1832 data type definitions
 */
typedef hyper		int64_t;
typedef unsigned int	uint32_t;

/*
 * Basic data types
 */
typedef uint32_t	bitmap4<>;

typedef opaque		utf8string<>;
typedef utf8string	utf8str_cis;
typedef utf8string	utf8str_cs;
typedef utf8string	utf8str_mixed;

/*
 * Timeval
 */
struct nfstime4 {
	int64_t		seconds;
	uint32_t	nseconds;
};


/*
 * The following content was extracted from draft-ietf-nfsv4-delstid
 */

typedef bool            fattr4_offline;


const FATTR4_OFFLINE            = 83;


struct open_arguments4 {
  bitmap4  oa_share_access;
  bitmap4  oa_share_deny;
  bitmap4  oa_share_access_want;
  bitmap4  oa_open_claim;
  bitmap4  oa_create_mode;
};


enum open_args_share_access4 {
   OPEN_ARGS_SHARE_ACCESS_READ  = 1,
   OPEN_ARGS_SHARE_ACCESS_WRITE = 2,
   OPEN_ARGS_SHARE_ACCESS_BOTH  = 3
};


enum open_args_share_deny4 {
   OPEN_ARGS_SHARE_DENY_NONE  = 0,
   OPEN_ARGS_SHARE_DENY_READ  = 1,
   OPEN_ARGS_SHARE_DENY_WRITE = 2,
   OPEN_ARGS_SHARE_DENY_BOTH  = 3
};


enum open_args_share_access_want4 {
   OPEN_ARGS_SHARE_ACCESS_WANT_ANY_DELEG           = 3,
   OPEN_ARGS_SHARE_ACCESS_WANT_NO_DELEG            = 4,
   OPEN_ARGS_SHARE_ACCESS_WANT_CANCEL              = 5,
   OPEN_ARGS_SHARE_ACCESS_WANT_SIGNAL_DELEG_WHEN_RESRC_AVAIL
                                                   = 17,
   OPEN_ARGS_SHARE_ACCESS_WANT_PUSH_DELEG_WHEN_UNCONTENDED
                                                   = 18,
   OPEN_ARGS_SHARE_ACCESS_WANT_DELEG_TIMESTAMPS    = 20,
   OPEN_ARGS_SHARE_ACCESS_WANT_OPEN_XOR_DELEGATION = 21
};


enum open_args_open_claim4 {
   OPEN_ARGS_OPEN_CLAIM_NULL          = 0,
   OPEN_ARGS_OPEN_CLAIM_PREVIOUS      = 1,
   OPEN_ARGS_OPEN_CLAIM_DELEGATE_CUR  = 2,
   OPEN_ARGS_OPEN_CLAIM_DELEGATE_PREV = 3,
   OPEN_ARGS_OPEN_CLAIM_FH            = 4,
   OPEN_ARGS_OPEN_CLAIM_DELEG_CUR_FH  = 5,
   OPEN_ARGS_OPEN_CLAIM_DELEG_PREV_FH = 6
};


enum open_args_createmode4 {
   OPEN_ARGS_CREATEMODE_UNCHECKED4     = 0,
   OPEN_ARGS_CREATE_MODE_GUARDED       = 1,
   OPEN_ARGS_CREATEMODE_EXCLUSIVE4     = 2,
   OPEN_ARGS_CREATE_MODE_EXCLUSIVE4_1  = 3
};


typedef open_arguments4 fattr4_open_arguments;
pragma public fattr4_open_arguments;


%/*
% * Determine what OPEN supports.
% */
const FATTR4_OPEN_ARGUMENTS     = 86;




const OPEN4_RESULT_NO_OPEN_STATEID = 0x00000010;


/*
 * attributes for the delegation times being
 * cached and served by the "client"
 */
typedef nfstime4        fattr4_time_deleg_access;
typedef nfstime4        fattr4_time_deleg_modify;
pragma public 		fattr4_time_deleg_access;
pragma public		fattr4_time_deleg_modify;


%/*
% * New RECOMMENDED Attribute for
% * delegation caching of times
% */
const FATTR4_TIME_DELEG_ACCESS  = 84;
const FATTR4_TIME_DELEG_MODIFY  = 85;



/* new flags for share_access field of OPEN4args */
const OPEN4_SHARE_ACCESS_WANT_DELEG_MASK        = 0xFF00;
const OPEN4_SHARE_ACCESS_WANT_NO_PREFERENCE     = 0x0000;
const OPEN4_SHARE_ACCESS_WANT_READ_DELEG        = 0x0100;
const OPEN4_SHARE_ACCESS_WANT_WRITE_DELEG       = 0x0200;
const OPEN4_SHARE_ACCESS_WANT_ANY_DELEG         = 0x0300;
const OPEN4_SHARE_ACCESS_WANT_NO_DELEG          = 0x0400;
const OPEN4_SHARE_ACCESS_WANT_CANCEL            = 0x0500;

const OPEN4_SHARE_ACCESS_WANT_SIGNAL_DELEG_WHEN_RESRC_AVAIL = 0x10000;
const OPEN4_SHARE_ACCESS_WANT_PUSH_DELEG_WHEN_UNCONTENDED = 0x20000;
const OPEN4_SHARE_ACCESS_WANT_DELEG_TIMESTAMPS = 0x100000;
const OPEN4_SHARE_ACCESS_WANT_OPEN_XOR_DELEGATION = 0x200000;

enum open_delegation_type4 {
       OPEN_DELEGATE_NONE                  = 0,
       OPEN_DELEGATE_READ                  = 1,
       OPEN_DELEGATE_WRITE                 = 2,
       OPEN_DELEGATE_NONE_EXT              = 3, /* new to v4.1 */
       OPEN_DELEGATE_READ_ATTRS_DELEG      = 4,
       OPEN_DELEGATE_WRITE_ATTRS_DELEG     = 5
};


/*
 * The following content was extracted from draft-ietf-nfsv4-posix-acls
 */

enum aclmodel4 {
	ACL_MODEL_NFS4		= 1,
	ACL_MODEL_POSIX_DRAFT	= 2,
	ACL_MODEL_NONE		= 3
};
pragma public aclmodel4;

enum aclscope4 {
	ACL_SCOPE_FILE_OBJECT	= 1,
	ACL_SCOPE_FILE_SYSTEM	= 2,
	ACL_SCOPE_SERVER	= 3
};
pragma public aclscope4;

enum posixacetag4 {
	POSIXACE4_TAG_USER_OBJ	= 1,
	POSIXACE4_TAG_USER	= 2,
	POSIXACE4_TAG_GROUP_OBJ	= 3,
	POSIXACE4_TAG_GROUP	= 4,
	POSIXACE4_TAG_MASK	= 5,
	POSIXACE4_TAG_OTHER	= 6
};
pragma public posixacetag4;

typedef uint32_t	posixaceperm4;
pragma public posixaceperm4;

/* Bit definitions for posixaceperm4. */
const POSIXACE4_PERM_EXECUTE	= 0x00000001;
const POSIXACE4_PERM_WRITE	= 0x00000002;
const POSIXACE4_PERM_READ	= 0x00000004;

struct posixace4 {
	posixacetag4		tag;
	posixaceperm4		perm;
	utf8str_mixed		who;
};

typedef aclmodel4	fattr4_acl_trueform;
typedef aclscope4	fattr4_acl_trueform_scope;
typedef posixace4	fattr4_posix_default_acl<>;
typedef posixace4	fattr4_posix_access_acl<>;

%/*
% * New for POSIX ACL extension
% */
const FATTR4_ACL_TRUEFORM	= 89;
const FATTR4_ACL_TRUEFORM_SCOPE	= 90;
const FATTR4_POSIX_DEFAULT_ACL	= 91;
const FATTR4_POSIX_ACCESS_ACL	= 92;

```

---

# Overview

_Peios Kernel / Internals / KACS / Start here_

> KACS is the security core of Peios — an LSM inside PKM providing identity-based access control — and how it relates to MS-DTYP.

<a id="trm-3-1"></a>

The Kernel Access Control Subsystem is the security core of Peios: an LSM
within PKM providing identity-based access control in the Linux
kernel. It is the sole identity-based authorization mechanism for
managed objects. Every identity-based decision — a file open, a
registry read, an IPC connection, a signal, a token operation — passes
through one evaluation function, AccessCheck.

This chapter covers tokens ([The Token Model](</kernel/internals/kacs/tokens/the-token-model.md#trm-3-2-1>)), the Process Security Block ([The PSB Model](</kernel/internals/kacs/process-security/state-and-lifetime.md#trm-3-3-1>)),
privileges ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), impersonation ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)), binary signature verification
([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)), Process Integrity Protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)), the AccessCheck algorithm
in full ([AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>)), file enforcement ([The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md#trm-3-9-1>)), and how Peios identity is
projected onto the Linux credential model ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)).

The kernel-private storage and call-site inventory is in [LSM integration](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md#trm-3-e>): the LSM
security blobs, every registered KACS hook, and the direct metadata
entry points used by patched file-descriptor operations.

Two bodies of material that KACS owns conceptually live elsewhere in
the documentation. The binary structures — SIDs, security descriptors,
ACLs, ACEs, access masks, conditional ACE bytecode — are specified in
PCDS, because userspace tooling constructs and interprets them and has
to agree with the kernel byte for byte. The signing format a third
party would use to sign a binary with a PIP level is specified in
PSPK; this chapter describes only the verification side. What remains
here is the kernel's own behaviour: how it holds identity, and how it
decides.

<a id="trm-3-1-1"></a>

## Terminology

A **token** is a per-thread identity object held in the kernel's
credential structure, carrying a user SID, group SIDs, a privilege
bitmask, an integrity level, an impersonation level, and metadata.
Identity fields — SIDs, type, integrity level — are immutable; policy
fields — enabled privileges, enabled groups, default owner, group and
DACL — are atomically adjustable. Every thread has a token, and there
is no such thing as a null token.

A **primary token** defines a process's baseline identity and is
inherited on fork, reached through `task->real_cred`. An
**impersonation token** temporarily overrides it for access decisions
on one thread only, reached through `task->cred`.

A **LogonSession** is a kernel object representing one authentication
event: a session ID, a logon type, a user SID, an authentication
package, a logon time, and a logon SID. Tokens reference their session
by ID.

A **privilege** is a system-wide right carried on a token. Some
influence AccessCheck; others gate a standalone operation.

An **impersonation level** controls how far an identity can travel:
Anonymous, Identification, Impersonation, or Delegation. It is a
ratchet carried by every token, primary or impersonation, and only
ever goes down ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

An **integrity level** is a vertical trust classification on tokens
and objects. Numerically it is the mandatory label SID's single
sub-authority compared as an unsigned integer, so any `S-1-16-<n>`
with exactly one sub-authority is valid. In practice five standard
levels form a strict total order — Untrusted (0), Low (4096), Medium
(8192), High (12288), System (16384) — and non-standard values such as
`S-1-16-8448` appear only in SDs authored for Windows interop.
**Mandatory Integrity Control** is the constraint evaluated before the
DACL, blocking write access, and optionally read and execute, when the
caller's level is below the object's label.

**Process Integrity Protection** is a two-dimensional trust model —
type against trust level — protecting processes and objects from
insufficiently trusted callers. Unlike MIC, it revokes rights that a
privilege would otherwise have granted.

The **Process Security Block** is a per-process structure carrying PIP
identity, process mitigations, and process restrictions. It is never
affected by impersonation, which is the point of keeping it separate
from the token.

**FACS**, the File Access Control Shim, is the part of KACS that
replaces Linux DAC with security-descriptor evaluation on files. It
enforces the handle model: AccessCheck runs at open time and the
granted mask is cached on the file description, with later operations
checked against the cached mask.

An **object type** is the category of a protected resource. Each
defines a GenericMapping table translating generic rights into
object-specific ones.

The **TCB** — the components whose correct behaviour is necessary for
system security — is the Linux kernel, PKM, and the core trusted
userspace daemons: peinit, authd, and loregd.

<a id="trm-3-1-2"></a>

## Relationship to MS-DTYP

KACS is not a port of another system's security model. Tokens,
security descriptors, AccessCheck, structured SIDs, and per-thread
impersonation were chosen because they solve what Peios needs solved:
coherent identity, rich per-object access control, scoped delegation,
and integrated audit.

Those same primitives are the ones Active Directory uses, and Peios is
built to join AD domains as a first-class member — exchanging security
data with domain controllers, authenticating through Kerberos, and
enforcing policy distributed by Group Policy. That imposes binary
format compatibility, which PCDS specifies: an SD written by a Windows
domain controller and replicated through Samba is evaluated by KACS
without translation.

Format compatibility does not imply evaluator compatibility in every
corner. Given the same token, descriptor, and desired mask, KACS
generally reaches the same decision MS-DTYP describes, which is what
makes policy authored in an AD environment behave predictably here.
Where it deliberately does not, [Departures from MS-DTYP](</kernel/userspace/native/kacs/ms-dtyp-compatibility-and-divergences.md#trm-3-b>) records every departure and why.

<a id="trm-3-d-8"></a>

## Build configuration

`CONFIG_SECURITY_PKM=y` and `CONFIG_RUST=y` are required, as are
`CONFIG_STRICT_DEVMEM=y` and `CONFIG_MODULE_SIG_FORCE=y`. The last two,
and the absence of every other MAC LSM and of `CONFIG_BPF_LSM`, are
enforced at build time by `BUILD_BUG_ON` in `pkm_init` ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)): a kernel
configured without them does not compile. They were once checked at
initialisation instead, which is no refusal at all -- the LSM framework
answers a failed init with a warning and boots with the hooks
uninstalled, the opposite of what the gate intends (PEI-487). <a id="cite-abi-notes.build.configs-enforced-at-build"></a>
`CONFIG_SECURITY_SELINUX`, `_APPARMOR`, `_SMACK` and `_TOMOYO` are
additionally refused by Kconfig dependency. `CONFIG_LSM` is never
parsed.

Two further symbols gate large bodies of code:

- `CONFIG_SECURITY_PKM_KUNIT`, which compiles in the test harness and,
  in the signing path, a different and publicly known verification key
  ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)). <a id="cite-abi-notes.build.kunit-test-key"></a>
- `CONFIG_STRATAFS_FS`, without which the copy-up API of [The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>) is
  inert. <a id="cite-abi-notes.build.stratafs-gates-copy-up"></a>

## Related explanations

- [ABI status and naming differences](</kernel/userspace/native/kacs/abi-status-and-naming-differences.md>)
- [Descriptor and ACE semantics](</kernel/userspace/native/kacs/descriptor-and-ace-semantics.md>)
- [Token query semantics](</kernel/userspace/native/kacs/token-query-semantics.md>)
- [Socket ABI compatibility](</kernel/userspace/native/kacs/socket-abi-compatibility.md>)

## Calling the subsystem

The [native KACS interface reference](</kernel/userspace/native/kacs/overview.md>) collects the caller contracts and generated ABI tables.

## Topics

- [Tokens](</kernel/internals/kacs/tokens/overview.md>)
- [Process security](</kernel/internals/kacs/process-security/overview.md>)
- [Privileges](</kernel/internals/kacs/privileges/overview.md>)
- [Impersonation](</kernel/internals/kacs/impersonation/overview.md>)
- [Executable trust](</kernel/internals/kacs/executable-trust/overview.md>)
- [Access check](</kernel/internals/kacs/access-check/overview.md>)
- [File security](</kernel/internals/kacs/file-security/overview.md>)
- [Linux credentials](</kernel/internals/kacs/linux-credentials/overview.md>)
- [System V IPC](</kernel/internals/kacs/system-v-ipc/overview.md>)
- [Network objects](</kernel/internals/kacs/network-objects/overview.md>)
- [Mount namespaces](</kernel/internals/kacs/mount-namespaces/overview.md>)
- [Auditing](</kernel/internals/kacs/auditing/overview.md>)
- [Integration](</kernel/internals/kacs/integration/overview.md>)

---

# Boot and trust invariants

_Peios Kernel / Internals / KACS / Start here_

> Boot and trust invariants: behaviour and implementation of the Peios kernel.

<a id="trm-1-2"></a>

KACS depends on a kernel configuration that protects the kernel trust boundary
and installs its enforcement hooks. The supported build records that
configuration in `peios/config/pkm.fragment` and checks it with
`peios/verify-config.sh`. Kconfig and compile-time assertions impose additional
constraints. These mechanisms have different failure behaviour; a build
requirement is not an init-time check.

<a id="trm-1-2-1"></a>

## The LSM stack invariant

PKM implements KACS through the Linux Security Module framework and direct
integration points. The supported configuration uses
`CONFIG_LSM="landlock,lockdown,integrity,pkm"`. Capability hooks are implicit in
the framework. See [LSM hooks and object state](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md>)
for the registered hooks and direct callers.

<a id="trm-1-2-1-1"></a>

### What the kernel verifies

`security/pkm/Kconfig` requires security support, Rust, a 64-bit target,
`STRICT_DEVMEM` and `MODULE_SIG_FORCE`. It excludes SELinux, AppArmor, SMACK and
TOMOYO. In `security/pkm/kacs/lsm.c`, `pkm_init()` also has `BUILD_BUG_ON`
checks for those MAC LSMs, the BPF LSM, and the two hardening prerequisites.
An incompatible configuration fails to build; it is not a supported path
where the kernel boots and PKM merely declines to activate.

<a id="trm-1-2-1-2"></a>

### The required stack

The supported build disables the conflicting MAC LSMs, BPF LSM and Yama and
checks the exact LSM list. Yama's ptrace policy would introduce an independent
attach decision ahead of KACS. Landlock, lockdown and integrity remain in the
configured stack; their presence does not turn KACS into the authority for
every Linux check. Native process and object policy must be understood
alongside the particular interface's remaining checks.

<a id="trm-1-2-2"></a>

## Module signing

`CONFIG_MODULE_SIG_FORCE=y` is a PKM build prerequisite. Module loading also
has authorization checks, but possession of a loading privilege does not
waive signature verification. The signature establishes trust in executable
kernel code; it does not prove the module is free of defects.

The authoritative operational explanation is
[Module signing](</kernel/administration/admin-guide/boot/module-signing.md>),
including Peios's supported signing mechanism and load failures. Kernel
module signatures and executable PIP signatures must not be treated as an
interchangeable format or key-selection mechanism.

<a id="trm-1-2-3"></a>

## The module-loading helper

Kernel-initiated userspace helpers are subject to KACS executable verification
and the helper integrity floor. That is separate from verification of the
module subsequently requested by a helper. The executable must meet the
helper rule, and the module must independently meet module-loading policy.
See process integrity protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)) and executable verification ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)).

<a id="trm-1-2-4"></a>

## Memory access restrictions

`CONFIG_STRICT_DEVMEM=y` is a build prerequisite and limits physical-memory
access according to the architecture's implementation. It must not be
described as a universal list of accessible physical regions or as the sole
defence against process-isolation bypasses. KACS also gates relevant device
and physical-memory operations; see process integrity protection ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

The status of `/dev/kmem` follows the supported kernel's interfaces and
configuration, rather than being implied by `STRICT_DEVMEM` alone. A native
descriptor grant does not waive another check performed by the device path.

<a id="trm-1-2-5"></a>

## What the kernel will not have

The supported configuration excludes SELinux, AppArmor, SMACK, TOMOYO, BPF LSM
and Yama. The first five are also covered by PKM compile-time assertions.
Keep the distinction between configuration validation and compile-time
enforcement when changing the supported build; do not infer a universal
runtime rejection mechanism from the configuration file.

<a id="trm-1-2-6"></a>

## What about user-space hardening

Service signing and deployment policy are additional requirements. The kernel
derives executable integrity from the verified executable and applies the
rules for the particular exec path. A service being intended as part of the
trusted computing base does not itself assign a PIP tier.

Kernel integrity requirements do not establish that a complete image has the
right service binaries, signatures, descriptors or startup ordering. Those
are properties of the assembled deployment and must be checked there.

<a id="trm-1-2-7"></a>

## The invariant verification

Use the supported build entry points described in
[Building Peios](</kernel/development/start-here/building-peios.md>); they apply
and validate the Peios configuration. During PKM initialization,
`pkm_init()` initializes the Rust state, creates bootstrap tokens, constructs
the initial process security state and installs the hooks on success.
Allocation and initialization errors are separate from rejected build
configurations and are not evidence that all boot failures are fail-stop.

The initial userspace program is selected by the boot and init configuration.
The kernel's bootstrap tokens do not by themselves specify the full
prelude/peinit deployment sequence.

<a id="trm-1-2-8"></a>

## Failure modes

A rejected configuration should fail the build or its verification step.
A runtime initialization failure must be diagnosed from the actual init
return path and kernel messages. Do not assume that an ordinary LSM init
error necessarily halts the Linux boot process.

Disabling enforcement prerequisites or changing the LSM stack creates a
different kernel configuration and requires a fresh review of its security
properties. A successful boot alone does not establish that the intended
policy is active. The supported configuration checker and the runtime LSM
list exposed by securityfs provide distinct evidence.

<a id="trm-1-2-9"></a>

## Why these invariants

Native access control assumes that kernel code and data retain their
integrity. Restrictions on loading executable kernel code and accessing
physical memory help protect that boundary. The LSM configuration ensures
that the supported build includes the intended enforcement components.

These are necessary conditions for the intended system, not a proof that
there are no kernel defects or other authority paths. Interface-specific
checks and deployment validation remain relevant.

<a id="trm-1-2-10"></a>

## Where to go next

Read [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the
Linux compatibility boundaries, KACS process integrity ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)) for runtime
protection, and [Building Peios](</kernel/development/start-here/building-peios.md>)
for configuration and build validation.

---

# Tokens

_Peios Kernel / Internals / KACS / Tokens_

> Find the Peios kernel articles about tokens.

Use these articles to understand tokens in the Peios kernel.

- [The Token Model](</kernel/internals/kacs/tokens/the-token-model.md>)
- [Token Structure](</kernel/internals/kacs/tokens/token-structure.md>)
- [Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md>)
- [Token Creation](</kernel/internals/kacs/tokens/token-creation.md>)
- [Token Adjustment](</kernel/internals/kacs/tokens/token-adjustment.md>)
- [Linked Tokens and Elevation](</kernel/internals/kacs/tokens/linked-tokens-and-elevation.md>)
- [LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md>)
- [Token Access Rights](</kernel/internals/kacs/tokens/token-access-rights.md>)

---

# The Token Model

_Peios Kernel / Internals / KACS / Tokens_

> A token is a thread's identity and security policy — how it relates to Linux credentials, primary against effective, and the evaluation context.

<a id="trm-3-2-1"></a>

A token is a kernel object representing a thread's identity and
security policy: the user's SID, group memberships, privileges,
integrity level, impersonation state, claims, confinement settings,
and metadata. Every KACS-mediated access control decision evaluates
the thread's effective token. <a id="cite-token.decisions-use-effective-token"></a>

Every live userspace thread has one. <a id="cite-token.every-thread-has-one"></a> KACS-mediated authorization never
evaluates a null token — credentials that are blank, uncommitted,
kernel-only, asynchronous, or otherwise outside a meaningful userspace
evaluation context may carry no token at all, and an LSM hook that
reaches KACS with such a credential fails closed rather than evaluate
a meaningless identity. <a id="cite-token.null-credential-fails-closed"></a>

<a id="trm-3-2-1-1"></a>

## Relationship to Linux credentials

Tokens are independently allocated, reference-counted kernel objects.
A `struct cred` holds a *pointer* to the token in its LSM security
blob, not the token data itself.

That indirection is architecturally load-bearing. Linux credentials
are immutable once committed: after `commit_creds()` a `struct cred`
cannot be modified. Had token data been embedded in the credential,
every token mutation — toggling a privilege, adjusting a group — would
have required allocating a whole new credential. Keeping the token
behind a pointer lets token-internal mutations use the token's own
synchronisation and leave the credential alone.

Several thread credentials within a process may reference one token
object through `real_cred`, and a mutation to a shared token is
visible to every thread sharing it. <a id="cite-token.shared-within-process"></a> At fork the child receives an
independent deep copy, so mutations after fork are invisible across
the process boundary.

<a id="trm-3-2-1-2"></a>

## Primary and effective tokens

The `real_cred`/`cred` split on `task_struct` carries two roles.

`real_cred` is the task's **objective** identity, used when other
tasks evaluate access *to* this task. Its LSM blob points at the
**primary token** — the process's baseline identity, inherited from
the parent at fork. <a id="cite-token.real-cred-is-objective"></a>

`cred` is the task's **subjective** identity, used when this task
evaluates access to other objects. Its blob points at the **effective
token**: normally the primary token, or an impersonation token
installed by a server thread acting for a client. <a id="cite-token.cred-is-subjective"></a>

With no impersonation in play, `real_cred` and `cred` are the same
credential and resolve to the same token. Impersonation swaps `cred`
to a new credential pointing at a different token; reverting restores
`cred` to `real_cred`. <a id="cite-token.impersonation-swaps-cred-only"></a>

<a id="trm-3-2-1-3"></a>

## Evaluation context

Token evaluation — AccessCheck, privilege checks — happens only where
a meaningful subject authority exists. In task context that authority
is the effective token reached through `current_cred()`.

Linux credential substitution is authoritative for deferred work. When
a kernel path runs under credentials installed by `override_creds()`
or another subjective-credential mechanism, the token pointer in that
credential's blob travels with it and is evaluated normally. KACS does
not strip authority merely because the current task carries a
kernel-thread, workqueue, or io_uring-worker flag — the credential is
what counts, not the worker flag. <a id="cite-token.override-creds-authoritative"></a>

Authorization already cached on an object handle, such as the granted
mask on a file description, continues to use that cached authority for
post-open operations. <a id="cite-token.cached-handle-authority-persists"></a> User-originated asynchronous work that has
neither captured credentials nor cached handle authority reaches KACS
without a token-bearing credential and fails closed. <a id="cite-token.uncaptured-async-fails-closed"></a>

Kernel-originated infrastructure work running under the boot SYSTEM
credential evaluates as SYSTEM. <a id="cite-token.kernel-work-evaluates-as-system"></a> There is no separate worker-flag-based
kernel authority identity.

---

# Token Structure

_Peios Kernel / Internals / KACS / Tokens_

> Every token field by mutability class — fixed identity, adjustable privileges, one-way elevation — and what each carries.

<a id="trm-3-2-2"></a>

Token fields fall into three mutability classes. **Fixed** fields are
set at creation and never change — every security-critical identity
field is fixed. **Adjustable** fields can be modified at runtime
through the adjustment operations ([Token Adjustment](</kernel/internals/kacs/tokens/token-adjustment.md#trm-3-2-5>)). **One-way** fields can be
set or tightened but never cleared or loosened. <a id="cite-token.mutability-classes"></a>

<a id="trm-3-2-2-1"></a>

## Identity core (fixed)

| Field | Type | Description |
|---|---|---|
| `user_sid` | SID | The token's primary identity. |
| `user_deny_only` | bool | When true, the user SID matches only deny ACEs, never allow ACEs. Set at creation by CreateToken or FilterToken. True whenever `write_restricted` is true. <a id="cite-token.user-deny-only-with-write-restricted"></a> |
| `groups` | SID_AND_ATTRIBUTES[] | Group memberships. The set of SIDs is fixed at creation; the per-group attribute flags are adjustable. |
| `restricted_sids` | SID_AND_ATTRIBUTES[]? | Secondary SID list for restricted tokens, null on unrestricted ones. Set at creation by CreateToken or FilterToken. AccessCheck treats the list as presence-based: a restricting SID participates whenever it is present, and neither `SE_GROUP_ENABLED` nor `SE_GROUP_USE_FOR_DENY_ONLY` affects restricted-pass matching. <a id="cite-token.restricted-sids-presence-based"></a> |
| `write_restricted` | bool | When true, the restricted SID check applies only to write access. Set at creation by CreateToken or FilterToken. |

The **logon SID** — `S-1-5-5-X-Y`, tying the token to its
LogonSession — is not stored as a token field at all. It is derived
from the session on every read, and materialised once in `groups`
carrying `SE_GROUP_LOGON_ID`, which is where AccessCheck finds it. <a id="cite-token.logon-sid-materialised-in-groups"></a>

The group SID set is fixed at creation — adjustment never adds or
removes a SID. <a id="cite-token.group-set-fixed"></a> Individual groups can be enabled or disabled by
modifying `SE_GROUP_ENABLED`, within two limits: a mandatory group
(`SE_GROUP_MANDATORY`) cannot be disabled, and a deny-only group
(`SE_GROUP_USE_FOR_DENY_ONLY`) cannot be re-enabled. <a id="cite-token.group-toggle-limits"></a>

A token holds at most 1024 group entries including the kernel-injected
logon SID, so CreateToken accepts at most 1023 caller-supplied groups. <a id="cite-token.group-limit-1024"></a>

<a id="trm-3-2-2-2"></a>

## Token type (fixed)

| Field | Type | Description |
|---|---|---|
| `token_type` | enum | Primary or Impersonation. |
| `impersonation_level` | enum | Anonymous, Identification, Impersonation, or Delegation. On every token it is the ceiling on what may be derived from it: an impersonation token acts at this level, and a primary token bounds everything captured from, conveyed by, or duplicated out of the process carrying it ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)). |

<a id="trm-3-2-2-3"></a>

## Integrity (fixed)

| Field | Type | Description |
|---|---|---|
| `integrity_level` | uint | Numeric integrity level. Standard values are 0 (Untrusted), 4096 (Low), 8192 (Medium), 12288 (High), 16384 (System), but any unsigned integer is valid and is compared numerically against object labels. <a id="cite-token.integrity-level-any-unsigned"></a> |
| `mandatory_policy` | flags | `NO_WRITE_UP` (0x0001) and `NEW_PROCESS_MIN` (0x0002). Per-token MIC enforcement policy, set at creation. |

`mandatory_policy` is immutable: a process cannot change its own MIC
constraints at runtime, neither loosening nor tightening them. <a id="cite-token.mandatory-policy-immutable"></a> This is
a deliberate departure from MS-DTYP, where the mandatory policy is
runtime-modifiable — which reduces MIC to a constraint that stops only
processes not actively trying to bypass it. Immutability is what makes
MIC a real boundary here, and it is also what allows the impersonation
integrity ceiling ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)) to be enforced unconditionally.

<a id="trm-3-2-2-4"></a>

## Privileges (adjustable)

Each privilege on a token has four independent states.

**Present** — the privilege exists on the token. A present privilege
can be removed permanently, but no privilege can be added after
creation. <a id="cite-token.priv.no-add-after-creation"></a> **Enabled** — the privilege is currently active; only
present privileges can be enabled or disabled. <a id="cite-token.priv.enable-requires-present"></a> **Enabled by default**
— the creation-time enabled state, which adjustment can restore.
**Used** — the privilege has been exercised during this token's
lifetime; monotonic, and never cleared once set. <a id="cite-token.priv.used-is-monotonic"></a>

The lifecycle runs: present and disabled, to enabled, to used, then
optionally disabled, then optionally removed permanently. Removal
clears the privilege from the present, enabled, and enabled-by-default
states together. <a id="cite-token.priv.removal-clears-three-states"></a>

The four states are encoded as four 64-bit bitmasks, one bit per
defined privilege, which makes a privilege check constant-time and a
multi-privilege operation atomic.

<a id="trm-3-2-2-5"></a>

## Elevation (one-way)

| Field | Type | Description |
|---|---|---|
| `elevation_type` | enum | Default (non-elevated), Full (elevated), or Limited (filtered). |

A token is created as Default. <a id="cite-token.elevation-default-at-creation"></a> Only `KACS_IOC_LINK_TOKENS` sets Full
or Limited, when a linked pair is established, and once set neither
reverts to Default on that token object. <a id="cite-token.elevation-only-link-sets"></a> The role is sticky: relinking
can replace the partner but never converts Full to Limited or the
reverse. <a id="cite-token.elevation-role-sticky"></a> DuplicateToken and FilterToken produce new token objects
whose `elevation_type` starts again at Default, because a new token is
not part of any linked pair. <a id="cite-token.elevation-resets-on-derivation"></a>

Linked pairs are associated at the LogonSession level rather than
stored on individual tokens; [Linked Tokens and Elevation](</kernel/internals/kacs/tokens/linked-tokens-and-elevation.md#trm-3-2-6>) describes the pairing mechanism.

<a id="trm-3-2-2-6"></a>

## Default object security (adjustable)

| Field | Description |
|---|---|
| `owner_sid_index` | Index into `[user_sid, groups...]` selecting the default owner SID for new objects: 0 is the user SID, 1..N are `groups[0..N-1]`. The referenced SID is the user SID or a group carrying `SE_GROUP_OWNER`. <a id="cite-token.owner-index-rule"></a> |
| `primary_group_index` | Index into `[user_sid, groups...]` selecting the default primary group. The referenced SID is the user SID or any group SID on the token. <a id="cite-token.primary-group-index-rule"></a> |
| `default_dacl` | The DACL applied to objects this token creates when no explicit descriptor is supplied. It is kept as given; its generic rights are mapped through each new object's GenericMapping when it is copied into that object's descriptor. |

Storing indices rather than SID copies keeps the owner and primary
group consistent with the group array they name.

<a id="trm-3-2-2-7"></a>

## Metadata (fixed)

| Field | Type | Description |
|---|---|---|
| `token_id` | LUID | Unique identifier for this token instance. |
| `token_guid` | UUID | 128-bit identifier for this token instance, generated by the kernel at creation and immutable. Used by KMES for identity stamping and event correlation; readable through `KACS_TOKEN_CLASS_GUID` under `TOKEN_QUERY`. |
| `auth_id` | LUID | The LogonSession LUID, linking the token to the authentication event that produced it. |
| `source` | TOKEN_SOURCE | Who minted the token: an 8-character name plus a LUID. |
| `created_at` | timestamp | When the original token was minted by CreateToken. Copied unchanged by DuplicateToken, FilterToken, and `NEW_PROCESS_MIN`, so it tracks original minting rather than duplication. <a id="cite-token.created-at-tracks-minting"></a> |
| `expiration` | timestamp | When the token becomes invalid; zero means no expiry. Not enforced by AccessCheck. <a id="cite-token.expiration-not-enforced"></a> |
| `origin` | LUID | The originating LogonSession for derived tokens, such as S4U or network logon. |

<a id="trm-3-2-2-8"></a>

## Mutation tracking (adjustable)

| Field | Description |
|---|---|
| `modified_id` | Counter incremented on any token adjustment. <a id="cite-token.modified-id-bumps-on-adjustment"></a> |

Marking a privilege used is audit and accounting state rather than an
access-decision input, so it stays monotonic but does not bump
`modified_id`. Setting the elevation type is the one other mutation
that leaves the counter alone. <a id="cite-token.modified-id-exemptions"></a>

The counter is intended as a cache invalidation key — a `modified_id`
that has changed since a cached decision was taken means the decision
is stale. Nothing currently reads it for that purpose: it is
maintained on every adjustment and reported through the statistics
query class, and no cache anywhere invalidates on it. <a id="cite-token.modified-id-nothing-invalidates"></a>

<a id="trm-3-2-2-9"></a>

## Interactivity scope (adjustable)

| Field | Description |
|---|---|
| `interactivity_scope` | 0 for services, which have no interactive environment; 1 and above for interactive and remote user environments. Changing it requires `SeTcbPrivilege`. <a id="cite-token.interactivity-scope-needs-tcb"></a> |

<a id="trm-3-2-2-10"></a>

## Claims and security attributes (fixed)

| Field | Type | Description |
|---|---|---|
| `user_claims` | CLAIM_ATTRIBUTES[] | Name-value pairs from the user's directory object, fed into conditional ACE evaluation. |
| `device_claims` | CLAIM_ATTRIBUTES[] | Name-value pairs from the machine's directory object. |

<a id="trm-3-2-2-11"></a>

## LCS registry credentials (fixed)

| Field | Type | Description |
|---|---|---|
| `lcs_scope_guids` | GUID[] | Ordered private registry scope GUIDs used by LCS private hive routing. LCS checks the list in order before falling back to global hives. |
| `lcs_private_layers` | string[] | Registry layer names visible to this token even when disabled globally, using LCS layer-name syntax and matching rules. |

These are KACS-owned credential material belonging to LCS. They are
fixed at creation and copied by duplication and filtering, and
attaching them is authorized by the same trusted-minting gate as the
rest of CreateToken — only a caller holding `SeCreateTokenPrivilege`
can create a token carrying them. <a id="cite-token.lcs-credentials-fixed-and-gated"></a>

<a id="trm-3-2-2-12"></a>

## Device identity (fixed)

| Field | Type | Description |
|---|---|---|
| `device_groups` | SID_AND_ATTRIBUTES[]? | The machine's group memberships, for compound identity. |
| `restricted_device_groups` | SID_AND_ATTRIBUTES[]? | Filtered device groups for restricted tokens. |

<a id="trm-3-2-2-13"></a>

## Confinement (fixed)

| Field | Type | Description |
|---|---|---|
| `confinement_sid` | SID? | Places the token in a default-deny sandbox; null means unconfined. When set, AccessCheck switches to default-deny and access requires an explicit grant to this SID or to a SID present in `confinement_capabilities`. <a id="cite-token.confinement-sid-default-deny"></a> |
| `confinement_capabilities` | SID_AND_ATTRIBUTES[] | Declared access capabilities for a confined process, empty if none. The `attributes` field is carried for wire-format uniformity only: AccessCheck treats capability membership as presence-based and consults neither `SE_GROUP_ENABLED` nor `SE_GROUP_USE_FOR_DENY_ONLY` when matching confinement SIDs. <a id="cite-token.confinement-capabilities-presence-based"></a> |
| `isolation_boundary` | bool | Adds namespace filtering on top of confinement, making objects outside the boundary invisible rather than merely denied. Requires `confinement_sid`. Settable at creation but not enforced. <a id="cite-token.isolation-boundary-not-enforced"></a> |
| `confinement_exempt` | bool | Escape hatch: confinement restrictions are not evaluated at all. <a id="cite-token.confinement-exempt-skips-evaluation"></a> |

`ALL_APPLICATION_PACKAGES` participates only when it is present in
`confinement_capabilities`. KACS never synthesises it, and equally
never rejects an otherwise valid confined token merely because it is
present — strict confinement is expressed by the caller omitting it. <a id="cite-token.all-application-packages-not-synthesised"></a>
Deciding which capabilities a package token receives is authd's job
and policy tooling's, not the kernel's.

<a id="trm-3-2-2-14"></a>

## Audit (fixed)

| Field | Type | Description |
|---|---|---|
| `audit_policy` | u32 | Per-token audit overrides as a bitmask, fixed at creation — no adjustment operation exists. <a id="cite-token.audit-policy-fixed"></a> |

| Flag | Value | Description |
|---|---|---|
| `OBJECT_ACCESS_SUCCESS` | 0x0001 | Audit successful object access. |
| `OBJECT_ACCESS_FAILURE` | 0x0002 | Audit failed object access. |
| `PRIVILEGE_USE_SUCCESS` | 0x0004 | Audit successful privilege exercises: the privilege contributed requested bits that survive into the final granted result. <a id="cite-token.audit-policy.privilege-use-success"></a> |
| `PRIVILEGE_USE_FAILURE` | 0x0008 | Audit failed privilege exercises: the privilege contributed requested bits during evaluation, but they do not survive into the final result. <a id="cite-token.audit-policy.privilege-use-failure"></a> |

The policy is additive. It forces audit events that system-wide policy
would not generate, and cannot suppress events that system-wide policy
requires. <a id="cite-token.audit-policy-additive"></a> It follows impersonation: when service A impersonates client
B and B's token has a category enabled, operations during
impersonation are audited under B's identity. <a id="cite-token.audit-policy-follows-impersonation"></a> The creation default is
0. <a id="cite-token.audit-policy-default-zero"></a>

The audit records these categories produce describe the effective token
in their `subject.token` fields: the user SID as `sid`, the groups as
`groups` with their attribute words as the parallel `group-attributes`,
the integrity level as `integrity`, `token_id` as `id`, `auth_id` as
`auth-id`, the token type as `type` (`primary` or `impersonation`), the
impersonation level as `impersonation` (0 for a primary token), and the
projected Linux UID as `uid` ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)).

<a id="trm-3-2-2-15"></a>

## Credential projection (fixed)

| Field | Description |
|---|---|
| `projected_uid` | Linux UID for the user SID, precomputed by authd when the token is minted (PSPU [Overview](</kernel/internals/kmes/overview.md#trm-2-1>)); 65534 for the anonymous identity. <a id="cite-token.projection.anonymous-is-nobody"></a> |
| `projected_gid` | Linux primary GID, precomputed the same way; 65534 for the anonymous identity. |
| `projected_supplementary_gids` | Linux supplementary GIDs, one per group SID, precomputed the same way. |

authd computes these at token creation and they are stored on the
token; KACS never resolves a SID-to-UID mapping at runtime. <a id="cite-token.projection.precomputed-never-resolved"></a> Projection
reflects all groups regardless of enabled state, so adjusting groups
does not trigger recalculation. <a id="cite-token.projection.ignores-enabled-state"></a> [Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>) covers how the projection is
used.

<a id="trm-3-2-2-16"></a>

## Token security (adjustable)

| Field | Description |
|---|---|
| `security_descriptor` | The token's own SD, controlling who may query, adjust, duplicate, or impersonate it. <a id="cite-token.own-sd-governs-handle-ops"></a> |

<a id="trm-3-2-2-17"></a>

## Internal

| Field | Description |
|---|---|
| `refcount` | Reference count; the token is freed when the last reference drops. Not exposed to userspace. |

---

# Token Lifecycle

_Peios Kernel / Internals / KACS / Tokens_

> How tokens follow a process through fork, clone and exec — NEW_PROCESS_MIN, self-installation, bootstrap tokens and external tokens.

<a id="trm-3-2-3"></a>

<a id="trm-3-2-3-1"></a>

## Fork and clone

Every process and thread creation path goes through `clone()`, and
KACS branches on `CLONE_THREAD`.

**Without `CLONE_THREAD`** — fork or vfork — a new process is created
and the child receives an independent deep copy of the parent's
primary token. <a id="cite-token.fork.independent-copy"></a> If the parent is impersonating, the impersonation token
is not inherited: the child's effective credential is set from
`real_cred`. <a id="cite-token.fork.impersonation-not-inherited"></a> After the fork, mutations to either token are invisible
to the other. <a id="cite-token.fork.mutations-invisible-after"></a>

**With `CLONE_THREAD`** a new thread is created. Threads share the
parent's `real_cred` by reference and therefore share one primary
token object, so a privilege adjustment on it is visible to every
thread. <a id="cite-token.thread.shared-primary"></a> Each thread keeps independent impersonation state through its
own `cred`. <a id="cite-token.thread.independent-impersonation"></a> If the cloning thread is impersonating at the moment of
the clone, the impersonation token does not become the new thread's
primary or effective identity — the new thread starts with the shared
primary token as both, and may impersonate independently later. <a id="cite-token.thread.clone-starts-on-primary"></a>

<a id="trm-3-2-3-2"></a>

## Exec

The primary token survives `execve()` unchanged, with the single
exception of `NEW_PROCESS_MIN` below. <a id="cite-token.exec.primary-survives"></a> If the calling thread is
impersonating, impersonation is reverted before the new program runs;
a new program always starts with the primary token as its effective
identity. <a id="cite-token.exec.reverts-impersonation"></a>

Token assignment for services happens between fork and exec: peinit
forks, installs the service's token on the child, and the child then
execs the service binary.

<a id="trm-3-2-3-2-1"></a>

### NEW_PROCESS_MIN <a id="cite-token.new-process-min"></a>

When a token's `mandatory_policy` includes `NEW_PROCESS_MIN`, the
kernel replaces the primary token at exec time if the executable
carries an explicit, lower integrity label.

1. The executable's integrity label is read from the mandatory label
   ACE in its descriptor's SACL. A file with no label — no SACL, or no
   non-inherit-only mandatory label ACE — is **unlabelled**, and the
   token survives exec unchanged. <a id="cite-token.new-process-min.unlabelled-unchanged"></a> This is deliberately not the
   access-check rule, under which an unlabelled *object* counts as
   Medium ([Mandatory Integrity Control](</kernel/internals/kacs/access-check/mandatory-integrity-control.md#trm-3-8-3>)): an image that labels nothing would otherwise demote
   every process on it, PID 1 first, to Medium — which is exactly what
   happened before PEI-530, leaving the TCB below every High-integrity
   user and unable to convey their identity.
2. If the file's level is lower than the token's, a new token is
   created following DuplicateToken semantics — new `token_id`, new
   `token_guid`, `modified_id` initialised to the new `token_id`,
   `elevation_type` reset to Default — with `integrity_level` set to
   the file's label. Every other field — the impersonation level
   included — is copied from the source, and the original token is
   dropped. <a id="cite-token.new-process-min.lowers-to-file-label"></a>
3. If the file's level is greater than or equal to the token's,
   nothing happens and the token survives exec unchanged. <a id="cite-token.new-process-min.higher-label-unchanged"></a>

The mechanism only ever lowers integrity, so a child's level is always
at most its parent's, and only to a level the image itself claims. The
flag itself is immutable on the token, which is what prevents a process
from opting out before exec.

<a id="trm-3-2-3-3"></a>

## Self-installing a primary token

`KACS_IOC_INSTALL` commits a new primary token on the calling process.
The operation is process-wide: the kernel replaces the primary token
for the entire thread group, not just the calling thread. <a id="cite-token.install.process-wide"></a>

The handle has to carry `TOKEN_ASSIGN_PRIMARY`, the token has to be a
primary token, and the caller's *real* token has to hold
`SeAssignPrimaryTokenPrivilege` enabled — an impersonating thread's
effective token does not satisfy the gate, and the privilege is marked
used on success. <a id="cite-token.install.gates"></a> Unless that real token also
holds `SeTcbPrivilege` enabled, the token being installed has to carry
the same user SID and the same LogonSession as the caller's, or the
call fails with `EPERM`; this is what stops a non-TCB holder of
`SeAssignPrimaryTokenPrivilege` from installing an arbitrary
higher-privilege token on itself, and `SeTcbPrivilege` bypassing it is
how peinit installs service tokens with a different user SID and
LogonSession. <a id="cite-token.install.same-user-same-session-unless-tcb"></a>

A thread that is not impersonating switches both `real_cred` and
`cred` to the new primary token. A thread that is impersonating has
only `real_cred` replaced, and its active impersonation stays in
`cred` until it reverts or execs — so reverting after an install
restores the thread to the *new* primary token, not the old one. <a id="cite-token.install.impersonating-thread-keeps-cred"></a>

The calling thread installs immediately. Sibling threads converge in
their own context through queued in-kernel credential work, with no
atomic all-threads-at-once swap: during a brief transition window some
siblings may still observe the old primary token until they run their
queued work. <a id="cite-token.install.siblings-converge-asynchronously"></a> No completion barrier is exposed to the caller.

Successful installations are ordered per process. Siblings converge to the
latest successful installation in that order; older queued work must not
restore a superseded token, including when retried after an allocation
failure. Concurrent callers need not complete their syscalls in installation
order. Once exec commits its primary token, delayed pre-exec installation
work cannot replace it. <a id="cite-token.install.latest-successful-install-wins"></a>

Installation and exec credential preparation are serialised. If a successful
installation precedes exec, an execing sibling whose queued update has not
run derives its new primary token from that latest installation, applying
`NEW_PROCESS_MIN` normally. It does not derive from the sibling's stale
primary token, and does not replay the raw installed token over the derived
result afterward. If exec has already begun preparing credentials, a new
installer waits for exec to release its credential guard; a waiting sibling
remains killable so exec can finish removing the other threads. A failed
exec releases the guard without consuming a pending installation.
<a id="cite-token.install.serialized-with-exec"></a>

Such an exec also gives the new image the installed token's Linux
credentials, projected as an installation projects them ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)): uid, gid,
supplementary groups and user come from the installed token, not from the
token it replaced. A setuid or setgid binary's effective ID then applies on
top as it would to any exec. Unless the thread is impersonating, the
installed token is also the subject that decides whether that ID change is
allowed. <a id="cite-token.install.lagging-exec-takes-installed-identity"></a>

A new thread joins the same convergence rule even if it was not yet visible
when an installation selected the siblings to update. This does not change
a process fork's independent copy of the calling thread's primary token.
<a id="cite-token.install.clone-enrollment"></a>

If the installed token's user SID differs from the outgoing primary
token's, the process security descriptor is regenerated from the
default template for the new token. Otherwise the existing process
descriptor is preserved. <a id="cite-token.install.process-sd-regenerated-on-sid-change"></a>

<a id="trm-3-2-3-4"></a>

## Bootstrap tokens

Two tokens are created by PKM during kernel initialisation, before any
userspace process exists. Neither involves a syscall — the kernel
allocates the objects directly.

The **SYSTEM token** is hardcoded with user SID `S-1-5-18` (Local
System); groups `S-1-5-32-544` (BUILTIN\Administrators), `S-1-1-0`
(Everyone), `S-1-5-11` (Authenticated Users) and other well-known
SIDs; every defined privilege present and enabled; integrity level
System; token type Primary; impersonation level Delegation, the top of
the ratchet; elevation type Default; token source `PeiosKrn`;
projected UID 0; and `auth_id` set to `SYSTEM_LUID`. It is assigned to
the kernel's init task and inherited by PID 1 at exec. <a id="cite-token.bootstrap.system-token"></a>
Its `audit_policy` is `PRIVILEGE_USE_SUCCESS`, so every privilege SYSTEM
spends — at a capability gate and in an access check — is recorded as
`kacs.audit.privilege.used` ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), and tokens derived from it carry the
same policy. <a id="cite-token.bootstrap.system-token-audits-privilege-use"></a> The Anonymous
token and the query-only SYSTEM token have an audit policy of 0.

The **Anonymous token** is a global singleton with user SID `S-1-5-7`;
Everyone (`S-1-1-0`) as its only group; no privileges; integrity level
Untrusted; logon type Network; token type Impersonation; impersonation
level Anonymous; elevation type Default; token source `PeiosKrn`; and
`auth_id` set to `ANONYMOUS_LOGON_LUID`. It is effectively immutable,
having no privileges and no groups to adjust. <a id="cite-token.bootstrap.anonymous-token"></a> A peer token captured
at Anonymous level references this global object, whereas
`KACS_IOC_DUPLICATE` targeting Anonymous level creates a fresh
independent token of the same shape, because the DuplicateToken
contract requires a new object. <a id="cite-token.bootstrap.anonymous-singleton-vs-duplicate"></a>

| LUID | Value | Description |
|---|---|---|
| `SYSTEM_LUID` | 999 (0x3E7) | The SYSTEM LogonSession, created at kernel init. |
| `ANONYMOUS_LOGON_LUID` | 998 (0x3E6) | The Anonymous LogonSession, created at kernel init for Anonymous impersonation tokens. |

LogonSessions created dynamically by authd receive auto-generated
LUIDs starting at 1000; 999 and 998 are never assigned dynamically. <a id="cite-token.bootstrap.reserved-luids"></a>

The SYSTEM token carries `SeBackupPrivilege` and `SeRestorePrivilege`
present and enabled at boot. <a id="cite-token.bootstrap.system-backup-restore-present"></a> FACS passes backup and restore intent
flags into AccessCheck, which grants read and write regardless of file
DACLs — subject still to PIP. <a id="cite-token.bootstrap.backup-restore-intent-bypasses-dacl"></a> Once peinit has launched the TCB
services and early boot is complete, it disables these on child
service tokens through FilterToken.

<a id="trm-3-2-3-5"></a>

## External token replacement

A privileged process being able to replace the primary token on
another running process — peinit downgrading a pre-authd service from
SYSTEM to a purpose-built token, for instance — is designed but **not
built**. Nothing in the kernel implements it today. <a id="cite-token.external-replacement-not-built"></a>

The design uses `task_work_add()` to queue a credential swap on each
task in the target thread group, each task executing the swap in its
own context to preserve RCU safety, with an impersonating thread
having only `real_cred` replaced and its impersonation left intact.
The gates would be `SeAssignPrimaryTokenPrivilege` on the caller's
real token, `TOKEN_ASSIGN_PRIMARY` (0x0001) on the token fd,
`PROCESS_SET_INFORMATION` on the target process's descriptor, and two
constraints — the new token's user SID matching the target's current
one, and the new token belonging to the same LogonSession — both
bypassed by `SeTcbPrivilege`. The process descriptor gate puts the
target's owner in control of who can change its identity, while the
SID and LogonSession constraints stop a non-TCB holder of
`SeAssignPrimaryTokenPrivilege` assigning an arbitrary token to a
process it can reach. `SeTcbPrivilege` bypassing both is how peinit
would assign tokens with different user SIDs and LogonSessions to
child services. Per-thread queuing would leave a brief window with
some threads on the new token and some on the old, which is acceptable
only because replacement is always a downgrade.

In its absence, the mitigation for pre-authd services is privilege
removal: peinit uses FilterToken to copy the SYSTEM token with the
dangerous privileges permanently deleted and assigns that filtered
token to the service at launch. The service keeps the SYSTEM SID but
permanently lacks the ability to exercise those privileges.

---

# Token Creation

_Peios Kernel / Internals / KACS / Tokens_

> The three operations that produce a token — CreateToken from nothing, DuplicateToken from another, FilterToken for a restricted one.

<a id="trm-3-2-4"></a>

Three operations create tokens, each for a different purpose:
CreateToken mints one from nothing, DuplicateToken copies one, and
FilterToken produces a strictly weaker copy.

<a id="trm-3-2-4-1"></a>

## CreateToken

Mints a new token from scratch. The caller supplies the
security-meaningful content; the kernel generates the internal
bookkeeping and validates the structural invariants. The operation is
gated by `SeCreateTokenPrivilege`. <a id="cite-token.create.privilege-gate"></a>

The caller supplies `user_sid`, `groups` with their attributes,
privileges as `privs_present` plus `privs_enabled`, `owner_sid_index`,
`primary_group_index`, `default_dacl`, `integrity_level`,
`mandatory_policy`, `token_type`, `impersonation_level`, `auth_id`
referencing an existing LogonSession, `expiration` (0 for none),
`audit_policy`, `source` as a name plus LUID, `user_claims`,
`device_claims`, `lcs_scope_guids`, `lcs_private_layers`,
`device_groups`, `restricted_sids`, `restricted_device_groups`,
`confinement_sid`, `confinement_capabilities`, `confinement_exempt`,
`isolation_boundary`, `write_restricted`, `user_deny_only`,
`projected_uid`, `projected_gid`, `projected_supplementary_gids`,
`origin`, and `interactivity_scope`. The wire format is in [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>).

Including the well-known implicit groups is the caller's
responsibility — Everyone (`S-1-1-0`), Authenticated Users
(`S-1-5-11`), and whatever else the principal's authentication context
implies, such as `S-1-5-4` Interactive, `S-1-5-6` Service, or
`S-1-5-15` This Organization. The kernel injects none of these. The
logon SID is the sole kernel-generated group. <a id="cite-token.create.no-implicit-groups"></a>

The kernel generates `token_id` as a LUID, `token_guid`, `modified_id`
initialised to `token_id`, `created_at` as the current time,
`elevation_type` always Default, the token's own default security
descriptor ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)), and `logon_sid`, derived from the LogonSession ID
as `S-1-5-5-{id >> 32}-{id & 0xFFFFFFFF}`. <a id="cite-token.create.kernel-generated-fields"></a>

The logon SID is injected into the groups array carrying
`SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED |
SE_GROUP_LOGON_ID`, appended after the caller's groups. <a id="cite-token.create.logon-sid-appended"></a> Callers do not
include it themselves. Because the injected entry is appended,
`owner_sid_index` and `primary_group_index` are interpreted relative
to the caller-supplied groups — 0 for the user SID, 1..N for the
caller's groups — and not against the array with the logon SID in it. <a id="cite-token.create.indices-relative-to-caller-groups"></a>

Validation covers, in turn:

- that the caller holds `SeCreateTokenPrivilege`;
- that every SID is structurally well-formed; <a id="cite-token.create.validate.sids-well-formed"></a>
- that the owner SID is the user SID or a group carrying
  `SE_GROUP_OWNER`, resolved to `owner_sid_index`; <a id="cite-token.create.validate.owner-sid"></a>
- that the primary group SID is the user SID or a group on the token,
  resolved to `primary_group_index`; <a id="cite-token.create.validate.primary-group-sid"></a>
- that `auth_id` references an existing LogonSession; <a id="cite-token.create.validate.auth-id-exists"></a>
- that `user_deny_only` is true whenever `write_restricted` is; <a id="cite-token.create.validate.deny-only-with-write-restricted"></a>
- that `confinement_sid` is present whenever `isolation_boundary` is; <a id="cite-token.create.validate.isolation-needs-confinement"></a>
- that the wire format's `elevation_type` field is 0, since the kernel
  always sets Default itself; <a id="cite-token.create.validate.elevation-type-zero"></a>
- and that the caller's group count plus the injected logon SID fits
  the 1024-entry limit. <a id="cite-token.create.validate.group-limit"></a>

The optional LCS registry credential extension, when present, has to
use the version and layout of [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>), and carries at most 256 scope
GUIDs and at most 256 private layer names, with no nil scope GUID, no
duplicate scope GUIDs, no empty or overlong layer names, and no
duplicate layer names under LCS case-insensitive matching. <a id="cite-token.create.lcs-extension-limits"></a> Malformed
LCS credentials fail the whole call closed. <a id="cite-token.create.lcs-malformed-fails-closed"></a>

CreateToken accepts all four impersonation levels for a Primary token,
including Identification and Anonymous, and preserves the chosen level
and user identity. The level limits what may be derived from the token;
it does not prevent the process from acting as its own primary identity.
A peer capture takes the lower of the primary and socket levels:
Identification conveys identity without authority to act as it, while
Anonymous conveys the anonymous identity. <a id="cite-token.create.primary-levels"></a>

A minter chooses this ceiling deliberately ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)). authd uses Delegation
for verified evidence and Impersonation for attested evidence; peinit's
SYSTEM token uses Delegation. Each client may lower its level per
connection. Older kernels refused Primary tokens below Impersonation as
a migration guard; callers must not use an ignored or default Anonymous
field when they intend peers to impersonate the identity.

The kernel does not authenticate the user, look up SIDs in the
directory, resolve SID-to-UID mappings, or check that the principal
exists at all. Holding `SeCreateTokenPrivilege` is what makes the
caller trusted, and that trust is total.

The call returns a token file descriptor. Since CreateToken takes no
desired-access parameter, the returned handle always carries a cached
access mask of `TOKEN_ALL_ACCESS`. <a id="cite-token.create.returns-all-access"></a>

<a id="trm-3-2-4-2"></a>

## DuplicateToken

Creates an independent copy of an existing token, requiring
`TOKEN_DUPLICATE` access on the source. <a id="cite-token.duplicate.requires-token-duplicate"></a>

Two things may change during duplication. The **token type** may go
from primary to impersonation or the reverse. <a id="cite-token.duplicate.type-may-change"></a> The **impersonation
level** is chosen by the caller and is a ratchet: whatever the types
involved, the new level has to be equal to or lower than the source's,
and asking for more fails with `EINVAL`. <a id="cite-token.duplicate.level-ratchet"></a> A primary minted at
Delegation can be duplicated to an impersonation token at any level; a
primary at Impersonation cannot yield a Delegation-level token; an
Identification-level token cannot be duplicated up to Impersonation or
Delegation. The level only ever goes down — reaching a higher one
again means minting a fresh token with CreateToken.

Duplicating **to Primary** is how an impersonated identity becomes a
process — the server's impersonation token, converted, is what a
service manager installs on a child it launches as that client. The
result keeps the identity and the level, so a primary made from a
client captured at Impersonation is itself capped at Impersonation and
so is every process and token descended from it. The kernel refuses a
Primary result below Impersonation: a captured Identification or
Anonymous identity must not become an acting process through duplication.
This restriction applies even when the source is itself Primary. It is
separate from privileged CreateToken, which may deliberately mint a
primary with a low derivation ceiling. <a id="cite-token.duplicate.primary-result-floor"></a>

On the new token, `token_id` and `token_guid` are fresh, `modified_id`
is initialised to the new `token_id`, and `elevation_type` resets to
Default because the copy belongs to no linked pair. <a id="cite-token.duplicate.fresh-fields"></a> `token_type` and
`impersonation_level` are as the caller specified, within the rules
above. The token's own descriptor is a fresh default ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)): no
custom descriptor can be supplied at duplication time, and changing it
afterwards means using `WRITE_DAC` on the new handle. <a id="cite-token.duplicate.fresh-default-sd"></a>

Everything else is copied from the source: `user_sid`,
`user_deny_only`, `logon_sid`; `groups` with all per-group attributes;
`restricted_sids` and `write_restricted`; the privilege present,
enabled, enabled-by-default **and used** states; `integrity_level` and
`mandatory_policy`; `auth_id`, `origin`, `source`, `created_at`,
`expiration`, `audit_policy`; `interactivity_scope`; `default_dacl`,
`owner_sid_index`, `primary_group_index`; `user_claims`,
`device_claims`, `device_groups`, `restricted_device_groups`;
`lcs_scope_guids` and `lcs_private_layers`; `confinement_sid`,
`confinement_capabilities`, `confinement_exempt`; and the three
projection fields. <a id="cite-token.duplicate.copies-everything-else"></a>

One target is not a copy at all. Duplicating to **Impersonation at
Anonymous level** discards the source entirely and returns a fresh
token of the boot Anonymous shape — user SID `S-1-5-7`, Everyone as
its only group, no privileges, Untrusted integrity, and LogonSession
998 rather than the source's. <a id="cite-token.duplicate.anonymous-is-fresh-shape"></a> None of the copied-field rules above
apply to it. Assuming Anonymous is an identity boundary rather than a
level change, so the operation constructs the minimal identity instead
of narrowing the caller's.

The original token is unaffected. <a id="cite-token.duplicate.source-unaffected"></a>

<a id="trm-3-2-4-3"></a>

## FilterToken

Creates a restricted copy, requiring `TOKEN_DUPLICATE` access on the
source. <a id="cite-token.filter.requires-token-duplicate"></a> Filtering only ever weakens: there is no parameter that grants
anything.

It can **remove privileges**, deleting them permanently from the new
token by clearing them from the present, enabled, and
enabled-by-default states at once. <a id="cite-token.filter.remove-privileges"></a> It can **set groups to deny-only**,
giving them `SE_GROUP_USE_FOR_DENY_ONLY` so they block access through
deny ACEs but never grant it through allow ACEs — permanently, with no
way back. <a id="cite-token.filter.deny-only-groups"></a> It can **add restricted SIDs**, a secondary list that makes
AccessCheck evaluate the DACL twice, granting access only when the
normal SIDs and the restricted SIDs independently both pass. <a id="cite-token.filter.restricted-sids-double-evaluation"></a> And it
can **enable write-restricted mode**, limiting that second evaluation
to write operations so reads use the normal list alone; enabling it
forces `user_deny_only` true on the new token. <a id="cite-token.filter.write-restricted-forces-deny-only"></a>

Input validation is all-or-nothing — a single malformed entry means no
token is created. <a id="cite-token.filter.validation-all-or-nothing"></a> The deny-only list uses zero-based group indices
into the source's group array, and a duplicate or out-of-range index
is invalid. <a id="cite-token.filter.deny-only-index-rule"></a> The restricting SID blob has to parse exactly as the
declared packed SID list, with no truncated or trailing bytes. <a id="cite-token.filter.sid-blob-exact"></a> If the
source token is already restricted and the intersection of its
restricted SID list with the supplied list is empty, the request is
invalid and nothing is created. <a id="cite-token.filter.empty-intersection-invalid"></a>

On the new token, `token_id` and `token_guid` are fresh, `modified_id`
is initialised to the new `token_id`, and `elevation_type` resets to
Default. <a id="cite-token.filter.fresh-fields"></a> The privilege states are the source's modified by the removal
list, except that **`used` resets to 0** — unlike duplication, which
carries it across. <a id="cite-token.filter.used-resets"></a> `groups` keeps the source's SIDs with attributes
modified per the deny-only list, adding and removing nothing. <a id="cite-token.filter.groups-unchanged-except-attributes"></a>
`restricted_sids` is the supplied list, or its intersection with the
source's when the source was already restricted. <a id="cite-token.filter.restricted-sids-intersection"></a> `write_restricted` is
sticky: set if requested or if the source had it. <a id="cite-token.filter.write-restricted-sticky"></a> `user_deny_only` is
true when write-restricted is enabled and otherwise copied.
`user_sid`, `logon_sid`, `integrity_level`, `mandatory_policy`,
`token_type` and `impersonation_level` are copied, as are `auth_id`,
`origin`, `source`, `created_at`, `expiration`, `audit_policy`,
`default_dacl`, `owner_sid_index`, `primary_group_index`, the claims
and device group arrays, the LCS credentials, the confinement fields,
and the projection fields. The token's descriptor is a fresh default. <a id="cite-token.filter.copies-everything-else"></a>

---

# Token Adjustment

_Peios Kernel / Internals / KACS / Tokens_

> What can be changed on a live token — privileges, groups, interactivity scope and object-creation defaults — and what cannot.

<a id="trm-3-2-5"></a>

A live token's privileges, groups, default object-creation metadata,
and interactive session metadata can be adjusted at runtime. These are
distinct operations with separate access rights and constraint models.
All of them mutate the token object in place using atomic operations,
all become visible immediately to every thread sharing the token, and
all bump `modified_id`. <a id="cite-token.adjust.in-place-visible-bumps-modified-id"></a>

<a id="trm-3-2-5-1"></a>

## AdjustPrivileges

Requires `TOKEN_ADJUST_PRIVILEGES` on the token, and has three modes. <a id="cite-token.adjust.privs.requires-right"></a>

**Enable and disable** flips individual bits in `privileges_enabled`
for privileges present on the token. A privilege that is not present
cannot be enabled, and disabling one that is already absent is a
no-op. <a id="cite-token.adjust.privs.absent-enable-fails-disable-noop"></a> The operation activates existing privileges; it never grants
new ones.

**Reset to defaults** restores `privileges_enabled` to match
`privileges_enabled_by_default`, returning every privilege to its
creation-time state in one operation. It is encoded as a single
`kacs_priv_entry` with `luid = 0` and
`attributes = KACS_PRIV_RESET_ALL_DEFAULTS`. <a id="cite-token.adjust.privs.reset-encoding"></a> The reset touches only
`privileges_enabled`: it does not restore privileges that were removed
from `privileges_present`. <a id="cite-token.adjust.privs.reset-does-not-restore-removed"></a>

**Remove** permanently deletes a privilege, clearing its bit in
`privileges_present`, `privileges_enabled`, and
`privileges_enabled_by_default` together. Removing an already-absent
privilege is a no-op. <a id="cite-token.adjust.privs.remove-absent-noop"></a> The deletion is irreversible; nothing re-adds a
privilege to a token.

Duplicate privilege indices in one request are invalid. <a id="cite-token.adjust.privs.duplicate-indices-invalid"></a> The kernel
validates every entry before applying any change, so an invalid entry
fails the whole operation with no state change at all. <a id="cite-token.adjust.privs.all-or-nothing"></a> The caller
receives a report of each adjusted privilege's previous state. <a id="cite-token.adjust.privs.reports-previous-state"></a>

<a id="trm-3-2-5-2"></a>

## AdjustGroups

Requires `TOKEN_ADJUST_GROUPS` on the token, and has two modes. <a id="cite-token.adjust.groups.requires-right"></a>

**Enable and disable** flips `SE_GROUP_ENABLED` on individual groups,
within two constraints. A group carrying `SE_GROUP_MANDATORY`,
`SE_GROUP_USE_FOR_DENY_ONLY`, or `SE_GROUP_LOGON_ID` cannot be
adjusted **in either direction** — not enabled, not disabled, whatever
its current state; naming one in a request fails the whole call. <a id="cite-token.adjust.groups.protected-attributes-either-direction"></a> And
the user SID, when it appears in the group list, cannot be disabled,
which is the one constraint that is direction-scoped. <a id="cite-token.adjust.groups.user-sid-cannot-disable"></a>

**Reset to defaults** restores every group to its creation-time
enabled state. It restores only that state — it does not clear
`SE_GROUP_USE_FOR_DENY_ONLY` from a group that FilterToken marked
deny-only afterwards. <a id="cite-token.adjust.groups.reset-keeps-deny-only"></a>

Groups are addressed by zero-based index into the token's groups
array. A count of 0 is invalid, as is a count above 1024, as are
duplicate indices in one request. <a id="cite-token.adjust.groups.count-and-duplicate-limits"></a> Reset is encoded as a single
`kacs_group_entry` of `{ index = 0xFFFFFFFF, enable = 0 }`. <a id="cite-token.adjust.groups.reset-encoding"></a>

The caller receives the previous enabled state of every group as a
1024-bit mask encoded as sixteen 64-bit words in ascending order: word
0 covers group indices 0–63, word 1 covers 64–127, and bit `i % 64` of
word `i / 64` corresponds to group index `i`. Since group arrays cap
at 1024 entries, the mask is complete for any valid token. <a id="cite-token.adjust.groups.previous-state-mask"></a>

<a id="trm-3-2-5-3"></a>

## AdjustInteractivityScope

Requires `TOKEN_ADJUST_INTERACTIVITY_SCOPE` on the token and
`SeTcbPrivilege` on the caller's real token. <a id="cite-token.adjust.interactivity-scope.gates"></a> It changes the token's
`interactivity_scope` to a new `u32` and nothing else: the field is
metadata, and changing it grants or removes no privilege, group,
access right, label, claim, default owner, default primary group,
default DACL, or any other authorization state. <a id="cite-token.adjust.interactivity-scope.metadata-only"></a>

<a id="trm-3-2-5-4"></a>

## AdjustDefault

Requires `TOKEN_ADJUST_DEFAULT` on the token, and covers three fields. <a id="cite-token.adjust.default.requires-right"></a>

The **default DACL** applied to new objects is replaced by an RCU
pointer swap, with the old DACL freed after a grace period. The
**owner SID index** changes which SID becomes the default owner of new
objects, and has to reference the user SID or a group carrying
`SE_GROUP_OWNER`. The **primary group index** changes the default
primary group, and has to reference the user SID or any group SID on
the token. Both index updates are atomic.

All three affect future object creation only; existing objects are
untouched. <a id="cite-token.adjust.default.future-objects-only"></a> None can escalate anything, because the caller is choosing
among SIDs already on their own token.

`audit_policy` is fixed at creation, and no adjustment operation
changes it.

---

# Linked Tokens and Elevation

_Peios Kernel / Internals / KACS / Tokens_

> Two linked tokens for one principal — what the kernel does with the link, what it deliberately leaves to userspace, and the pair's lifecycle.

<a id="trm-3-2-6"></a>

At logon, authd may create two tokens for one principal and link them.
The **elevated token**, `elevation_type = Full`, carries the user's
complete identity: every group active, every assigned privilege
present and enabled. The **filtered token**,
`elevation_type = Limited`, carries the same user SID with
administrative groups set to deny-only and dangerous privileges
stripped, produced from the elevated token by FilterToken.

Both tokens belong to the same LogonSession, are both primary tokens,
and carry the same user SID. <a id="cite-token.link.pair-invariants"></a> The filtered token is installed as the
LogonSession's default; the elevated token exists but is not directly
reachable by unprivileged processes.

A token never assigned a linked-pair role has
`elevation_type = Default`. Once `KACS_IOC_LINK_TOKENS` sets a token
object to Full or Limited, that role is sticky on that object. If the
pair is later replaced or destroyed the token has no active partner
and `KACS_IOC_GET_LINKED_TOKEN` returns an error, but the token goes
on reporting its last assigned elevation type. <a id="cite-token.link.stale-partner-errors-role-persists"></a>

<a id="trm-3-2-6-1"></a>

## What KACS does

KACS provides pairing, storage, and query restriction — three
mechanisms, no policy.

**Linked pair association** registers the pair on the LogonSession, so
given either token the system can retrieve its partner. The pairing
lives at the LogonSession level and is not stored on the token
objects.

Establishing a pair is a TCB operation: the caller holds
`SeTcbPrivilege` on its **primary** token — an impersonating thread's
effective token does not satisfy it — and holds `TOKEN_DUPLICATE` on
*both* of the token handles being linked. <a id="cite-token.link.gates"></a> The two handles have to name
distinct token objects, and both have to belong to the LogonSession
named in the request, which itself has to be published. <a id="cite-token.link.handles-distinct-same-published-session"></a> The ioctl
ignores the handle it was issued on entirely; only the two named
handles matter. <a id="cite-token.link.issuing-handle-ignored"></a>

**Elevation type classification** puts `elevation_type` on each token
so a consumer can tell which side it is holding.

**Identification-level query restriction** governs what an unprivileged
caller gets when it queries a token's partner: a deep clone at
Identification impersonation level. The clone follows DuplicateToken
semantics — a new token object, a new `token_id`, `modified_id`
initialised to it, a fresh default descriptor — except that it
preserves the partner's `elevation_type`, and it is always returned
through a `TOKEN_QUERY`-only handle. <a id="cite-token.link.query-returns-identification-clone"></a> The caller can inspect the
elevated token but cannot use it for an access decision. A caller
holding `SeTcbPrivilege` receives a full handle to the actual linked
token instead. <a id="cite-token.link.tcb-gets-real-handle"></a>

Returning a copy through `TOKEN_QUERY` is a deliberate exception to
the normal access-right model, where `TOKEN_DUPLICATE` would be
expected. It holds because the returned copy is always
Identification-level: functionally a query result rather than a usable
token.

<a id="trm-3-2-6-2"></a>

## What KACS does not do

The elevation decision itself — whether this user should be allowed to
use their elevated token right now — is entirely authd's. KACS does
not gate elevation, verify credentials, or display prompts. It stores
the pair and restricts unprivileged access to it.

Beyond enforcing the LogonSession, token-type and same-user
invariants, KACS does not verify that the filtered token really is a
FilterToken-derived reduction of the elevated one. <a id="cite-token.link.no-reduction-check"></a> That correspondence
is authd's to get right.

<a id="trm-3-2-6-3"></a>

## Lifecycle

Both tokens in a pair share a LogonSession, and that session is not
destroyed while any token fd, credential, pair slot, or other
reference keeps one of its token objects live. When the last external
reference is released and only the linked-pair's own references
remain, KACS destroys the LogonSession, removes the linkage, and drops
the pair's references to both tokens. <a id="cite-token.link.pair-released-with-last-external-ref"></a> After that cleanup no token
object from the session remains live purely because it was linked.

Stale-role tokens can exist before final destruction — for instance
when `KACS_IOC_LINK_TOKENS` replaces a LogonSession's active pair
while an old token object is still held by an fd or credential. Fork
produces them too: the deep copy a child receives preserves the
parent's elevation type, so a forked child can hold a Full or Limited
token that was never linked to anything. <a id="cite-token.link.fork-preserves-elevation-type"></a> Once a
token is no longer the active member of the pair, querying its linked
token returns an error, because the partner relationship no longer
exists for it. Such survivors keep their sticky Full or Limited
elevation type: they are stale-role tokens with no active partner, not
Default tokens.

---

# LogonSessions and Revocation

_Peios Kernel / Internals / KACS / Tokens_

> The LUID-identified object every token references — how sessions are created, how they expire, and how revocation propagates.

<a id="trm-3-2-7"></a>

<a id="trm-3-2-7-1"></a>

## LogonSessions

A LogonSession is a lightweight kernel object identified by a LUID,
carried on tokens as `auth_id`. Every token references one.

authd creates a LogonSession through a KACS syscall at authentication
time, before creating the token. <a id="cite-token.session.created-before-token"></a> The object holds the LogonSession ID,
the logon type (Interactive, Network, Service, and so on), the user
SID, the authentication package name such as `Kerberos` or
`Negotiate`, and a creation timestamp. <a id="cite-token.session.fields"></a> The logon SID, `S-1-5-5-X-Y`,
is derived from the LogonSession ID. Several tokens may share one
session — linked pairs, and tokens derived by duplication. <a id="cite-token.session.shared-by-many-tokens"></a>

When the last token referencing a session is freed, the kernel
destroys the session object and emits a `kacs.session.destroyed`
event through KMES. <a id="cite-token.session.destroyed-with-last-token"></a> The last
token usually goes when a credential is freed, which happens in an RCU
callback where no record can be built, so the session is queued, still
referenced, and a kernel work item writes the event moments later and
then releases it. The session is gone at once — it no longer resolves —
but its event follows the teardown rather than coming from it, and its
header names the kernel worker that wrote it. <a id="cite-token.session.destroyed-record-deferred"></a> The event is for whatever keeps per-session state
outside the kernel — an audit pipeline, an accounting tool, an authority
that caches credentials per session. authd keeps none and does not
subscribe.

The record describes the session under `object.session`: its LUID as
`id` (the `subject.token.auth-id` of every record made under it), the
user SID as `user.sid`, the logon type as `logon-type`, the
authentication package as `auth-package`, and the creation time as
`logon-time`. The logon type is written by name — `interactive`,
`network`, `batch`, `service`, `network-cleartext`, `new-credentials`
or `remote-interactive` — and the time in realtime nanoseconds, though
the kernel holds it to whole seconds.

### Logon types

The logon type records how the issuer established the session. It
describes the situation, not the principal: one principal can hold
sessions of several types at once. Session creation rejects any value
outside this table with `-EINVAL`.

| Value | Name | The issuer asserts | Origin |
|---|---|---|---|
| 2 | Interactive | A user signed in at the machine | Local |
| 3 | Network | A client on another machine authenticated to use a service here | Remote |
| 4 | Batch | A scheduled job started | Local |
| 5 | Service | A service started | Local |
| 8 | NetworkCleartext | As Network, and the credential was presented in the clear | Remote |
| 9 | NewCredentials | The caller's local identity is unchanged, and only the credentials it presents to other machines differ | Remote |
| 10 | RemoteInteractive | A user signed in from another machine, to a terminal or a desktop | Remote |

The kernel takes the issuer's word for the type and never verifies it.
Its only use of the type is the origin column: the `CAP_SYS_BOOT`
mapping additionally requires `SeRemoteShutdownPrivilege` for a
remote-origin session. The well-known
group SIDs that let an ACE distinguish one kind of session from
another, such as `INTERACTIVE` and `NETWORK`, are placed on the token
by the issuer, not derived by the kernel from the logon type.

There is one rollback path for the case where authd creates a session
but no token ever becomes live for it:
`kacs_destroy_empty_logon_session`, which requires `SeTcbPrivilege`
and succeeds only when the session exists, has zero live tokens, has
no linked-token state, and has no other in-flight kernel references. <a id="cite-token.session.destroy-empty.gates"></a>
On success it destroys the object and emits the same
`kacs.session.destroyed` event as normal cleanup. <a id="cite-token.session.destroy-empty.emits-event"></a> A nonexistent
session fails with `-ENOENT`; one with any live token, linked-token
state, or in-flight reference fails with `-EBUSY`. <a id="cite-token.session.destroy-empty.errors"></a>

A second enumeration surface exists alongside `/proc`:
`/sys/kernel/security/kacs/sessions` lists every live session, one
line each, giving the session ID, user SID, logon type, authentication
package, and creation time. <a id="cite-token.session.securityfs-listing"></a> Each
line reads

```
logon_session_id=<u64> user_sid=<hex> logon_type=<u32> auth_package=<hex> created_at=<u64>
```

with the user SID's binary form and the package name's bytes in
lowercase hexadecimal, and `created_at` in seconds since the Unix
epoch. securityfs itself is unclassified by FACS,
so its objects sit deny-missing until the mount is given a synthesising
policy ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)); only then can the file be opened at all. On Peios,
peinit gives it one at boot that lets Authenticated Users open and
traverse. Reading it is access-checked against a
synthetic descriptor granting read to SYSTEM and Administrators, and is
PIP-checked. <a id="cite-token.session.securityfs-access-check"></a>

AccessCheck never consults `auth_id`, and the logon SID influences a
decision only because it is materialised as an ordinary group SID on
the token. <a id="cite-token.session.auth-id-not-consulted"></a> Two enforcement decisions elsewhere in the kernel do read
session state, though. Installing a primary token denies a non-TCB
caller whose target token belongs to a different
LogonSession ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). And the
`CAP_SYS_BOOT` mapping selects between `SeShutdownPrivilege` and
`SeRemoteShutdownPrivilege` by inspecting the session's logon type
([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)). `interactivity_scope` is metadata in the same way: the kernel
stores it and returns it on query, and no kernel security mechanism
evaluates it.

<a id="trm-3-2-7-2"></a>

## Expiration

The `expiration` field carries a timestamp, and AccessCheck does not
enforce it. It is informational.

Token lifetime is governed by reference counting instead: a token
exists as long as at least one reference — a process credential or an
open file descriptor — exists. <a id="cite-token.session.lifetime-by-refcount"></a>

<a id="trm-3-2-7-3"></a>

## Revocation

KACS has no token revocation primitive. There is no "invalidate token
X" syscall, and no syscall destroys a LogonSession while tokens still
reference it. <a id="cite-token.session.no-revocation-primitive"></a> `kacs_destroy_empty_logon_session` is only authd's
rollback for a session that never acquired live tokens.

Terminating a LogonSession is therefore userspace coordination. On
Peios authd does it, when asked over `/run/logon.sock` ([PGSS session termination](https://learn.peios.org/specifications/pgss/logon/ending-a-session)):

1. A caller asks authd to end the session, and authd decides whether it
   may: its own session as a person, anyone else's by an access check
   against local policy. SYSTEM's session (999), Anonymous's (998) and
   every session of logon type Service are never ended this way; a
   service is stopped through peinit.
2. authd enumerates processes whose **primary** token carries the
   target `auth_id`, by walking `/proc`, opening each process with
   `pidfd_open`, opening its primary token with
   `kacs_open_process_token` on that pidfd, and reading
   `TokenStatistics`, which includes `auth_id`. No dedicated enumeration
   syscall exists or is needed. A thread's impersonation token is not
   consulted, so a service impersonating a member of the session is not
   one of its processes.
3. authd sends each `SIGTERM` with `pidfd_send_signal`, waits up to a
   grace period (5 seconds) for them to exit, and sends `SIGKILL` to the
   survivors.
4. It walks again, since a process may have forked meanwhile, for at
   most three rounds.
5. The processes terminate, dropping their token references.
6. The last reference drops and the session object is cleaned up.

Each token handle authd opens in the walk is itself a reference to the
session, and is closed as soon as `auth_id` has been read.

Token file descriptors can be passed between processes over IPC, so a
reference held by a process outside the target session survives that
session's process termination. <a id="cite-token.session.fd-reference-survives-termination"></a> The walk finds processes running under the
session, not every process holding one of its tokens, so such a
reference keeps the session alive after authd has ended every process
in it, and authd reports nothing about it. A process that has exited
but not been reaped likewise keeps its token, and the session, until it
is reaped.

Kernel-side invalidation — a dead flag on the LogonSession object
checked during AccessCheck, so that access checks against its tokens
fail immediately — is not implemented.

---

# Token Access Rights

_Peios Kernel / Internals / KACS / Tokens_

> Tokens are securable objects — obtaining a token file descriptor, the token-specific rights, the generic mapping and the default descriptor.

<a id="trm-3-2-8"></a>

Tokens are securable objects: each has its own security descriptor,
and reaching a token means passing an AccessCheck against it. <a id="cite-token.rights.access-checked-object"></a>

<a id="trm-3-2-8-1"></a>

## Obtaining a token file descriptor

**Opening directly.** A syscall takes a pidfd — not a raw PID — and a
desired access mask. The kernel finds the target's
primary token, evaluates the caller's token against that token's
descriptor, and returns a token fd with the granted mask cached on it. <a id="cite-token.rights.open-by-pidfd"></a>
A separate variant opens a thread's impersonation token. <a id="cite-token.rights.open-thread-token"></a> Opening
another process's token additionally requires
`PROCESS_QUERY_INFORMATION` on the target process's descriptor. <a id="cite-token.rights.open-other-needs-process-query"></a>

**Opening through `/proc`.** `/proc/<pid>/token` and
`/proc/<pid>/task/<tid>/token` open a process's primary token and a
thread's effective token as a query-only handle: the fd always carries
`TOKEN_QUERY` and nothing else. Opening another process's file makes
both of the syscall's checks — `PROCESS_QUERY_INFORMATION` on the
process's descriptor, with PIP dominance, and `TOKEN_QUERY` on the
token's own descriptor — so the path reads nothing the syscall would
refuse. A process opens its own without either check. <a id="cite-token.rights.proc-token-file"></a>

The peer-token socket option (`getsockopt(SOL_KACS,
KACS_SO_PEER_TOKEN)`) is the exception: it takes no desired-access
mask, and the fd it returns always carries the fixed rights
`TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE`. <a id="cite-token.rights.peer-token-fixed-rights"></a> A token delivered
in a `KACS_SCM_TOKEN` control message carries the same three. <a id="cite-token.rights.scm-token-fixed-rights"></a>
`TOKEN_DUPLICATE` is what lets a server turn a client's identity into a
primary token for a process it launches on the client's behalf
([Token Creation](</kernel/internals/kacs/tokens/token-creation.md#trm-3-2-4>)); it is safe to hand out because the level ratchet means the
copy can never act above the level the client chose ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

**Receiving over IPC.** A token fd can be passed over a Unix socket
with `SCM_RIGHTS`. What the recipient may do is bounded by the mask
cached on the fd when it was originally opened, not by the recipient's
own identity. <a id="cite-token.rights.passed-fd-keeps-cached-mask"></a>

**Implicit self-access.** A thread has implicit access to its own
effective token for query operations, but this is not a kernel bypass.
It follows from the default token descriptor, which grants
`TOKEN_QUERY` and the adjustment rights to the token's own user SID.
The AccessCheck still runs; it simply succeeds while the descriptor
continues to grant the right. Explicitly mutating a token's own
descriptor later can revoke self-query by removing that grant. <a id="cite-token.rights.self-query-revocable"></a>

<a id="trm-3-2-8-2"></a>

## Token-specific rights

| Right | Value | Grants |
|---|---|---|
| `TOKEN_ASSIGN_PRIMARY` | 0x0001 | Install as a process's primary token. Also requires `SeAssignPrimaryTokenPrivilege` on the caller's token. <a id="cite-token.rights.assign-primary-needs-privilege"></a> |
| `TOKEN_DUPLICATE` | 0x0002 | Duplicate the token, or create a restricted copy with FilterToken. |
| `TOKEN_IMPERSONATE` | 0x0004 | Install as a thread's impersonation token. |
| `TOKEN_QUERY` | 0x0008 | Read token information: SIDs, groups, privileges, integrity, claims, source, statistics, GUID, elevation type. |
| `TOKEN_ADJUST_PRIVILEGES` | 0x0020 | Enable, disable, or permanently remove privileges. |
| `TOKEN_ADJUST_GROUPS` | 0x0040 | Enable or disable groups. |
| `TOKEN_ADJUST_DEFAULT` | 0x0080 | Change the default DACL, owner SID, and primary group SID. |
| `TOKEN_ADJUST_INTERACTIVITY_SCOPE` | 0x0100 | Change the interactivity scope. Also requires `SeTcbPrivilege`. |

Bit 0x0010, `TOKEN_QUERY_SOURCE`, is subsumed by `TOKEN_QUERY`: a
holder of 0x0008 can query source information too. <a id="cite-token.rights.query-source-subsumed"></a> The bit is not
reused for anything else, for format compatibility with MS-DTYP.

`TOKEN_ALL_ACCESS` is 0x000F01FF — the union of the token-specific
rights with `STANDARD_RIGHTS_REQUIRED`
(`DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER`, 0x000F0000). The
named rights alone OR to 0x01EF; the reserved `TOKEN_QUERY_SOURCE` bit
adds 0x0010 to reach 0x01FF. <a id="cite-token.rights.all-access-value"></a>

<a id="trm-3-2-8-3"></a>

## Generic mapping <a id="cite-token.rights.generic-mapping"></a>

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `TOKEN_QUERY \| READ_CONTROL` |
| `GENERIC_WRITE` | `TOKEN_ADJUST_PRIVILEGES \| TOKEN_ADJUST_GROUPS \| TOKEN_ADJUST_DEFAULT \| WRITE_DAC` |
| `GENERIC_EXECUTE` | `TOKEN_IMPERSONATE` |
| `GENERIC_ALL` | `TOKEN_ALL_ACCESS` (0x000F01FF) |

<a id="trm-3-2-8-4"></a>

## Standard rights

`READ_CONTROL` reads the token's own descriptor, `WRITE_DAC` modifies
its DACL, and `WRITE_OWNER` changes its owner. `DELETE` has no
practical effect on a token and is present only for uniformity across
standard rights. <a id="cite-token.rights.delete-inert"></a>

<a id="trm-3-2-8-5"></a>

## The default token descriptor <a id="cite-token.rights.default-descriptor"></a>

A newly created token receives a descriptor owned by the creating
process's user SID, with a DACL granting:

- the token's own user SID `TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES |
  TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT`;
- the creator `TOKEN_ALL_ACCESS`;
- SYSTEM (`S-1-5-18`) `TOKEN_ALL_ACCESS`;
- Administrators (`S-1-5-32-544`) `TOKEN_QUERY`.

The Administrators grant is read-only: it lets an administrator see who
any process runs as, its groups and privileges, and which logon session
it belongs to, which is what a machine-wide process listing needs.
Duplicating, impersonating, adjusting or rewriting the token still
needs the token's own grants. <a id="cite-token.rights.default-sd-administrators-query"></a>

Self-access is deliberately limited to the adjustment operations that
cannot escalate. `TOKEN_DUPLICATE`, `TOKEN_IMPERSONATE`, and
`WRITE_DAC` are not granted to the token's own subject. <a id="cite-token.rights.default-sd-no-self-escalation"></a>

That limit needs protecting in the case where the creator and the
token's own user SID are the same, which would otherwise hand the
subject `TOKEN_ALL_ACCESS` through the creator ACE. When the two SIDs
are identical the creator ACE is omitted — and the descriptor also
gains a non-inherit-only `OWNER RIGHTS` ACE suppressing the owner's
implicit `READ_CONTROL | WRITE_DAC` grant while preserving
`READ_CONTROL`. <a id="cite-token.rights.default-sd-self-created-owner-rights"></a> Without it, owner-implicit `WRITE_DAC` would let the
subject rewrite its own DACL and reintroduce exactly the escalation
that omitting the creator ACE was meant to close.

<a id="trm-3-2-8-6"></a>

## Check-at-open

The check-at-open model applies to tokens exactly as it does to files,
for the token-specific rights. AccessCheck runs once, when the token
fd is obtained; the granted mask is cached on the fd; and each of the
token ioctls verifies against that cached mask with no re-evaluation. <a id="cite-token.rights.check-at-open"></a>

The standard rights are the exception. Reading and writing a token's
own descriptor passes no cached mask at all and runs a **live**
AccessCheck on every call, so `READ_CONTROL`, `WRITE_DAC` and
`WRITE_OWNER` are re-evaluated per operation rather than snapshotted
at open. <a id="cite-token.rights.standard-rights-live-check"></a> A descriptor change therefore takes effect immediately for
those three rights, while already-opened handles keep their cached
token-specific rights.

---

# Process security

_Peios Kernel / Internals / KACS / Process security_

> Find the Peios kernel articles about process security.

Use these articles to understand process security in the Peios kernel.

- [State and lifetime](</kernel/internals/kacs/process-security/state-and-lifetime.md>)
- [PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md>)
- [Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md>)

---

# State and lifetime

_Peios Kernel / Internals / KACS / Process security_

> The per-process structure describing what a process is, independent of the principal running it.

<a id="trm-3-3-1"></a>

The Process Security Block is a per-process structure carrying
properties that describe **what the process is**, independent of the
principal running it.

Its PIP identity fields, `pip_type` and `pip_trust`, are determined by
the binary loaded at exec ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)). Its other fields — process
mitigations and process restrictions — are process policy, set by
whoever launches the process. Neither category is token identity, and
neither is determined by the principal.

Keeping the PSB separate from the token is the point. The token
describes identity and travels with impersonation: when a thread
impersonates a client, the effective token changes. The PSB describes
the process, and impersonation never touches it. <a id="cite-psb.impersonation-untouched"></a>

> The PSB is never affected by impersonation. Impersonation changes
> who the thread is acting as. It does not change what the process is.

The canonical PSB reference lives on the task's LSM security blob,
`task_struct->security`, separate from the credential that holds the
token pointer. <a id="cite-psb.canonical-on-task-blob"></a> A mirrored, non-authoritative reference is also kept in
credential security blobs, for the benefit of Linux hooks that receive
only a credential. For any task-attached credential that mirror refers
to the same PSB as the task blob, and it never defines a different
process identity. <a id="cite-psb.cred-mirror-same-psb"></a>

Credentials are swapped during impersonation, and that swap may change
the credential's token pointer — but the canonical PSB is untouched
and any credential-level mirror continues to refer to it. <a id="cite-psb.cred-swap-preserves-psb"></a>

<a id="trm-3-3-4"></a>

<a id="trm-3-3-4-1"></a>

## Fork

The child receives a copy of the parent's PSB with a single exception:
`process_guid` is not copied, and the child is given a new
kernel-generated one. <a id="cite-psb.fork.new-guid"></a> Everything else — the PIP fields, the
mitigations, and any active restrictions — is inherited, so a
Protected process's children start Protected and PIP propagates across
fork. <a id="cite-psb.fork.inherits-rest"></a>

The child also receives a new default process descriptor. Its owner is
the forking thread's **primary** token's user SID, not the
impersonation token's, even when the thread is impersonating at the
time. <a id="cite-psb.fork.sd-owner-primary-token"></a> The DACL follows the default template.

<a id="trm-3-3-4-2"></a>

## Exec

The PIP fields are reset at exec from the new binary's cryptographic
signature. A Protected parent that execs an unsigned binary loses PIP
protection: protection follows the binary, not the lineage. <a id="cite-psb.exec.pip-reset-from-binary"></a>

The mitigation flags — `lsv`, `wxp`, `tlp`, `cfif`, `cfib`, `pie`,
`sml`, `ui_access` — are not reset. They persist across exec
unchanged, so a mitigation set between fork and exec survives whatever
binary is subsequently loaded. <a id="cite-psb.exec.mitigations-persist"></a> `no_child_process` persists in the same
way: a process restricted from creating children stays restricted no
matter what it execs. <a id="cite-psb.exec.no-child-process-persists"></a>

`process_guid` is not reset either, because it identifies the process
— the scheduling entity — rather than the binary. <a id="cite-psb.exec.guid-preserved"></a>

The process descriptor is not reset. Exec preserves it unchanged. <a id="cite-psb.exec.sd-preserved"></a> It
was initialised at fork from the forking thread's primary token and
reflects the process creation context, or a later explicit management
context, rather than the binary being executed. Primary token
installation and the other explicit process-descriptor mutation paths
replace or modify it only under their own rules ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).

<a id="trm-3-3-4-3"></a>

## Clone with CLONE_THREAD

Threads share the process's PSB. <a id="cite-psb.clone-thread.shares-psb"></a> Thread creation is unaffected by
`no_child_process`, which blocks new processes only.

<a id="trm-3-3-4-4"></a>

## Relationship to AccessCheck

The PSB is not an input to AccessCheck in the general case. AccessCheck
takes a token and a descriptor and evaluates access; most PSB fields
are invisible to it.

PIP is the exception. The pipeline includes a PIP enforcement step
reading `pip_type` and `pip_trust`, which come from the PSB rather
than from any token: the enforcement layer extracts them and passes
them to AccessCheck as explicit parameters. <a id="cite-psb.accesscheck.pip-from-psb"></a>

The asymmetry between MIC and PIP follows from that. **MIC** uses the
effective token, so impersonation changes how it evaluates — which is
safe because the integrity ceiling on impersonation ([Impersonation Gates](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-2>)) prevents
escalation. **PIP** uses the PSB, so impersonation cannot change how
it evaluates — necessary because there is no impersonation gate
constraining the PIP dimensions, making the PSB the only safe source.

The process mitigations and `no_child_process` do not interact with
AccessCheck at all. Each is enforced at its own enforcement point,
independently of the access control pipeline.

---

# PSB Fields

_Peios Kernel / Internals / KACS / Process security_

> Every PSB field — the process GUID fixed at fork, the protection fields set at exec, the one-way mitigations and the UI access flag.

<a id="trm-3-3-2"></a>

<a id="trm-3-3-2-1"></a>

## Process identity (fixed at fork)

| Field | Type | Description |
|---|---|---|
| `process_guid` | UUID | 128-bit identifier for this process instance, generated by the kernel at fork and immutable for the process's lifetime. It is **not** copied from the parent — every process receives a new one. Used by KMES and kernel-internal consumers for identity stamping and event correlation. <a id="cite-psb.guid.new-and-immutable"></a> |

The process GUID is distinct from the PID. PIDs are recycled; process
GUIDs are unique within a boot, and globally unique in practice. <a id="cite-psb.guid.unique-within-boot"></a> It is
the stable correlation key that lets KMES attribute events to a
process across its whole lifetime.

<a id="trm-3-3-2-2"></a>

## Protection (set at exec, fixed)

| Field | Type | Description |
|---|---|---|
| `pip_type` | u32 | Process Integrity Protection type. Determined by the binary's cryptographic signature at exec. |
| `pip_trust` | uint | Trust tier within a PIP type; higher values can reach lower ones. Determined by the signer's identity. |

PIP fields are signing-based. At exec the kernel verifies the binary's
signature and derives both fields from the signer, using the algorithm
and key model of [Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>).

Both are plain unsigned integers rather than enumerations, and are
compared numerically. Three type values are conventional — None (0),
Protected (512) and Isolated (1024) — but only two are producible: the
key table validator accepts a key only at exactly Protected with
`PeiosTcb` trust (8192) and rejects the whole table otherwise, so
**Isolated is unreachable** and a signed binary is always
Protected/8192. <a id="cite-psb.pip.only-protected-tcb"></a> Neither None nor Isolated is defined as a named
constant in the public ABI at all. <a id="cite-psb.pip.none-isolated-absent-from-abi"></a> The parent process cannot influence the
determination at all — even a compromised peinit running as SYSTEM
cannot forge PIP protection for an unsigned binary. <a id="cite-psb.pip.parent-cannot-influence"></a> The public
verification key is compiled into the kernel image, and the kernel
only ever verifies; it never signs.

This is a deliberate departure from MS-DTYP, where the parent sets a
protection level at process creation and the kernel validates the
binary's signature against it. Peios removes the parent-controlled
half entirely: one input, one answer.

<a id="trm-3-3-2-3"></a>

## Process mitigations (one-way)

| Field | Description |
|---|---|
| `lsv` | **Library Signature Verification.** Only signed shared libraries load. When the process has `pip_type != None` the library's trust level has to be at or above the process's PIP trust; when `pip_type = None` any valid signature suffices and trust is not compared. <a id="cite-psb.lsv.trust-floor"></a> |
| `wxp` | **Write-XOR-Execute Protection.** No page is simultaneously writable and executable; W+X mappings and transitions between writable and executable are rejected. <a id="cite-psb.wxp.no-write-and-execute"></a> |
| `tlp` | **Trusted Library Paths.** Shared libraries load only from approved directory prefixes. Weaker than LSV, since it trusts the path rather than the binary. <a id="cite-psb.tlp.approved-prefixes-only"></a> |
| `cfif` | **Forward-Edge Control Flow Integrity.** Hardware indirect-branch tracking — Intel IBT, ARM BTI — is locked on and cannot be disabled by the process. Not settable: see below. |
| `cfib` | **Backward-Edge Control Flow Integrity.** The hardware shadow stack, Intel CET, is locked on and cannot be disabled by the process. <a id="cite-psb.cfib.shadow-stack-locked"></a> |
| `pie` | **Position-Independent Executable Requirement.** Non-PIE binaries are rejected at exec, so that ASLR is actually effective. <a id="cite-psb.pie.non-pie-rejected-at-exec"></a> |
| `sml` | **Speculation Mitigation Lock.** Speculation mitigations are locked on and cannot be disabled by the process. <a id="cite-psb.sml.speculation-locked"></a> |

Mitigations are inherited from the parent at fork and can be set by
syscall. They are one-way:
once set they are never cleared, and exec does not reset them — a
mitigation set by the launcher persists regardless of which binary is
loaded. <a id="cite-psb.mitigations.one-way"></a>

Do not infer an additional service policy from peinit launch: the
[source-checked peinit 0.0.12 path](/peios/using-peios/services-and-jobs/identity-and-privileges.md#token-installation-and-executable-trust)
does not make a per-service PSB mitigation request. Inherited and self-applied
flags are separate from that launcher behavior.

Setting a bit is **activation-backed**. Before a mitigation bit moves
from clear to set, KACS either activates the underlying protection for
the target process or verifies that the process already satisfies the
invariant. <a id="cite-psb.mitigations.activation-backed"></a> If any requested mitigation cannot be activated or
verified, the whole operation fails closed without mutating any bit
from that request. <a id="cite-psb.mitigations.all-or-nothing"></a> Once committed, later operations that would disable
the protection or make the process violate the invariant are rejected,
and re-requesting an already-set mitigation never weakens what is
already committed. <a id="cite-psb.mitigations.recommit-never-weakens"></a>

For the runtime memory mitigations, activation covers existing state
as well as future transitions. Enabling `wxp` fails if the process
already has a mapping that is simultaneously writable and executable,
or otherwise already violates the invariant in a way KACS can observe. <a id="cite-psb.wxp.enable-fails-on-existing-wx"></a>
Enabling `tlp` fails if the process already has a file-backed
executable mapping whose kernel-resolved path is missing,
unresolvable, outside the approved prefix cache, or otherwise
TLP-denied. <a id="cite-psb.tlp.enable-fails-on-denied-mapping"></a> Enabling `lsv` fails if the process already has a
file-backed executable mapping whose signing material is missing,
invalid, or below the required PIP trust. <a id="cite-psb.lsv.enable-fails-on-untrusted-mapping"></a> Anonymous executable
mappings are governed by `wxp` alone; `tlp` and `lsv` apply only to
file-backed ones. <a id="cite-psb.mitigations.anonymous-exec-is-wxp-only"></a>

For the architecture-backed mitigations, activation goes through the
architecture's kernel interface to place the process in the protected
state and prevent later process-controlled disablement. Enabling
`cfif`, `cfib`, or `sml` fails closed when the platform cannot make
the protection true for the target. <a id="cite-psb.mitigations.arch-fails-closed"></a>

`sml` also accepts a second route: a platform that reports speculation
as unconditionally not-affected satisfies activation by that fact
alone, with nothing to enable. <a id="cite-psb.sml.not-affected-satisfies"></a>

`cfif` cannot currently be committed at all. Activation against a live
task returns `ENODEV` unconditionally, because the kernel exposes no
userspace control surface for IBT or BTI, so the bit fails closed on
every request. <a id="cite-psb.cfif.enodev-always"></a> `cfib` works, through shadow-stack enable-and-lock,
with one restriction: enabling it on a task other than the caller
fails. <a id="cite-psb.cfib.self-only"></a>

Two mitigations are event-gated rather than retroactive: `pie` is
enforced at subsequent exec and `no_child_process` at subsequent
process creation. <a id="cite-psb.mitigations.event-gated"></a> They still follow the one-way commit rule, and have
to be set before the event they are meant to constrain.

All of this is distinct from PIP. Mitigations are policy set by the
launcher; PIP is a property of the binary determined by the kernel.

The mitigations compose deliberately: LSV ensures only signed
libraries load, WXP blocks code injection, CFIF blocks forward-edge
code reuse through indirect calls and jumps, CFIB blocks
return-oriented programming, and PIE makes ASLR effective. Together
they make exploitation dramatically harder than any one of them alone.

<a id="trm-3-3-2-4"></a>

## UI access (one-way) <a id="cite-psb.ui-access.set-once-fixed"></a>

| Field | Description |
|---|---|
| `ui_access` | Permits interaction with higher-integrity UI elements. Reserved for future desktop functionality. Set by syscall, typically by peinit between fork and exec, and fixed thereafter. |

<a id="trm-3-3-2-5"></a>

## Process restrictions (one-way)

| Field | Description |
|---|---|
| `no_child_process` | Once set, the process creates no child processes — fork, or clone without `CLONE_THREAD`. New threads are unaffected, and the flag is never cleared. <a id="cite-psb.no-child-process.blocks-fork"></a> |

Unlike the exec-time fields, this one can be set at two points. The
parent's code, running in the freshly forked child, can set it before
exec, so the new binary loads with the restriction already in place.
Or a process can restrict itself at any time during its life — after
it has finished spawning its own workers, for instance. <a id="cite-psb.no-child-process.two-set-points"></a>

<a id="trm-3-3-2-6"></a>

## The TLP cache

The approved directory prefixes for TLP live in a global kernel cache
rather than on individual PSBs: the `tlp` flag decides whether a
process is subject to enforcement, while the paths themselves are
machine-wide.

The cache is an array of absolute directory prefix byte strings
evaluated against kernel-resolved Linux path bytes, holding at most 64
entries of at most 4096 bytes each. <a id="cite-psb.tlp.cache-bounds"></a> Every prefix begins with `/` and
**ends** with `/` — so that `/usr/lib/` does not match `/usr/libevil`
— and contains no embedded NUL byte. <a id="cite-psb.tlp.prefix-slash-terminated"></a> An empty, relative,
NUL-containing, or non-slash-terminated prefix is invalid and is
rejected without mutating the existing cache, which is staged and
swapped under a mutex so a rejected update cannot leave it partly
written. <a id="cite-psb.tlp.invalid-prefix-rejected-atomically"></a>

**The cache has no production writer.** The only code that populates
it is a test helper compiled in solely under the KUnit configuration:
there is no syscall, no securityfs node, and no registry path that
fills it. <a id="cite-psb.tlp.no-production-writer"></a> In a shipping build the cache is therefore permanently
empty — and since an empty cache matches no path, enabling `tlp` on a
process denies *every* file-backed executable mapping it subsequently
attempts. <a id="cite-psb.tlp.empty-cache-denies-all"></a>

At `mmap(PROT_EXEC)` time, a process with TLP enabled has the mapped
file's current kernel-resolved backing path checked against every
approved prefix. If the path cannot be resolved, if no prefix matches,
or if the cache is empty, the mapping is rejected. <a id="cite-psb.tlp.mmap-rejects-unmatched"></a>

<a id="trm-3-3-2-7"></a>

## Reading the PSB

`/proc/<pid>/psb` gives a process's PSB as one line of text, in this
order:

```
pip_type=<u32> pip_trust=<u32> mitigations=0x<hex> process_guid=<uuid>
```

`mitigations` is the committed mitigation bitfield in at least three
hexadecimal digits, including `ui_access` and `no_child_process`, with
the bit values of [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>). `process_guid` is the 16 bytes in order,
formatted 8-4-4-4-12. <a id="cite-psb.proc.psb-file"></a>

A process reads its own without any check. Reading another process's
needs `PROCESS_QUERY_LIMITED` on its process descriptor, with
`SeDebugPrivilege` rescuing a descriptor denial as it does for every
process right, and **does not** need PIP dominance. That a process is
protected is not a secret every other refusal keeps; it is what a
caller needs to see to understand those refusals. <a id="cite-psb.proc.psb-read-access"></a>

The PSB is otherwise written only: `kacs_set_psb` sets mitigations and
returns nothing about them.

<a id="trm-3-3-2-8"></a>

## Identity virtualization (reserved) <a id="cite-psb.virtualization.reserved"></a>

| Field | Description |
|---|---|
| `virtualization` | Per-process state for setuid compatibility redirection. Not active, and implementations may omit the field until it is. |

---

# Process Security Descriptors

_Peios Kernel / Internals / KACS / Process security_

> The descriptor controlling who may operate on a process — the access rights, signal classification, what bypasses the check, and the default.

<a id="trm-3-3-3"></a>

Every process carries a security descriptor controlling who may
operate on it, stored on the PSB alongside the PIP and mitigation
fields. It replaces Linux's UID-based process access control — a
patchwork of UID comparisons and capabilities — with a single
descriptor evaluation.

<a id="trm-3-3-3-1"></a>

## Process access rights

| Right | Value | Meaning |
|---|---|---|
| `PROCESS_TERMINATE` | 0x0001 | Send signals whose default action is termination. <a id="cite-psb.right.terminate"></a> |
| `PROCESS_SIGNAL` | 0x0002 | Send informational signals whose default action is to ignore: `SIGCHLD`, `SIGURG`, `SIGWINCH`. <a id="cite-psb.right.signal"></a> |
| `PROCESS_VM_READ` | 0x0010 | Read process memory — ptrace peek, `/proc/<pid>/mem`, `process_vm_readv`. <a id="cite-psb.right.vm-read"></a> |
| `PROCESS_VM_WRITE` | 0x0020 | Write process memory — ptrace poke, `/proc/<pid>/mem`, `process_vm_writev`. Includes debugger attach. <a id="cite-psb.right.vm-write"></a> |
| `PROCESS_DUP_HANDLE` | 0x0040 | Extract file descriptors from the process through `pidfd_getfd`. <a id="cite-psb.right.dup-handle"></a> |
| `PROCESS_SET_INFORMATION` | 0x0200 | Change priority, CPU affinity, I/O priority, resource limits, process group membership where Linux permits it, timer slack, memory-placement policy or pages, and mutable `/proc/<pid>` task state — `sched`, `autogroup`, `timens_offsets`, `timerslack_ns`, `coredump_filter`, `oom_adj`, `oom_score_adj`, `make-it-fail`, `fail-nth`, `latency` and `clear_refs`, plus write intent on the coupled `uid_map`, `gid_map`, `projid_map` and `setgroups` seq files. <a id="cite-psb.right.set-information"></a> |
| `PROCESS_QUERY_INFORMATION` | 0x0400 | Inspect the process's token; read the detailed `/proc/<pid>/*` files — `cmdline`, `status`, `io`, `limits`, `sched`, `autogroup`, `timens_offsets`, `personality`, `syscall`, `latency`, `timers`, `timerslack_ns`, `mounts`, `mountinfo`, `mountstats`, `coredump_filter`, `oom_adj`, `oom_score_adj`, `loginuid`, `make-it-fail`, `fail-nth`, `seccomp_cache`, `ksm_merging_pages` and `ksm_stat` — plus read intent on the coupled `uid_map`, `gid_map`, `projid_map` and `setgroups` seq files; query Linux compatibility capability state through `capget(pid)`; and query detailed scheduler, CPU-affinity and I/O-priority state. <a id="cite-psb.right.query-information"></a> |
| `PROCESS_SUSPEND_RESUME` | 0x0800 | Send signals whose default action is to stop or continue. <a id="cite-psb.right.suspend-resume"></a> |
| `PROCESS_QUERY_LIMITED` | 0x1000 | Read basic process information: PID, process group ID, session ID, image name, state, CPU and memory usage — `stat`, `statm`, `comm`, `wchan`, `schedstat`, `cpuset`, `cgroup`, `cpu_resctrl_groups`, `oom_score`, `sessionid`, `patch_state`, `stack_depth`, `arch_status` and `psb`. This is what `ps` and `top` show, it covers `/proc/<pid>/stat`, and it is the right required for `pidfd_open()` and for `kill(pid, 0)` existence probes. <a id="cite-psb.right.query-limited"></a> |
| `READ_CONTROL` | 0x20000 | Read the process's own descriptor. |
| `WRITE_DAC` | 0x40000 | Modify the process's DACL. |
| `WRITE_OWNER` | 0x80000 | Change the descriptor's owner. |

Three `/proc` entries are not where the right names suggest.
`maps`, `fd` and `environ` are not gated by
`PROCESS_QUERY_INFORMATION`: they keep their upstream
`PTRACE_MODE_READ_FSCREDS` gating, which maps to **`PROCESS_VM_READ`**
— reading a process's memory map is treated as reading its memory,
which is defensible but is not what the right's name implies. <a id="cite-psb.proc.maps-fd-environ-are-vm-read"></a> And
`cgroup` sits in the **`PROCESS_QUERY_LIMITED`** set rather than the
detailed one. <a id="cite-psb.proc.cgroup-in-query-limited"></a>

`psb` is the process's PSB, read under `PROCESS_QUERY_LIMITED` with no
PIP dominance ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). It is the one `/proc` entry whose check is
KACS's own rather than the metadata rule's.

<a id="trm-3-3-3-2"></a>

## Signal classification <a id="cite-psb.signal.by-default-action"></a>

Each Linux signal maps to a process access right according to its
default action.

Signal 0 is not delivered at all. A `kill()`, `tkill()`, or `tgkill()`
call with signal 0 is an existence and permission probe, requiring
`PROCESS_QUERY_LIMITED` on the target plus PIP dominance. <a id="cite-psb.signal.zero-is-probe"></a>

**`PROCESS_TERMINATE`** — default action terminate, or terminate with
a core dump: <a id="cite-psb.signal.terminate-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGHUP` | 1 | Terminate | Session hangup |
| `SIGINT` | 2 | Terminate | Ctrl-C |
| `SIGQUIT` | 3 | Terminate + core | Quit request |
| `SIGILL` | 4 | Terminate + core | Illegal instruction |
| `SIGTRAP` | 5 | Terminate + core | Debug trap |
| `SIGABRT` | 6 | Terminate + core | Abort |
| `SIGBUS` | 7 | Terminate + core | Bus error |
| `SIGFPE` | 8 | Terminate + core | Floating point exception |
| `SIGKILL` | 9 | Terminate | Forced kill, cannot be caught |
| `SIGUSR1` | 10 | Terminate | User-defined |
| `SIGSEGV` | 11 | Terminate + core | Segfault |
| `SIGUSR2` | 12 | Terminate | User-defined |
| `SIGPIPE` | 13 | Terminate | Broken pipe |
| `SIGALRM` | 14 | Terminate | Alarm timer |
| `SIGTERM` | 15 | Terminate | Graceful termination request |
| `SIGSTKFLT` | 16 | Terminate | Stack fault |
| `SIGXCPU` | 24 | Terminate + core | CPU time exceeded |
| `SIGXFSZ` | 25 | Terminate + core | File size exceeded |
| `SIGVTALRM` | 26 | Terminate | Virtual timer |
| `SIGPROF` | 27 | Terminate | Profiling timer |
| `SIGIO` | 29 | Terminate | I/O possible |
| `SIGPWR` | 30 | Terminate | Power failure |
| `SIGSYS` | 31 | Terminate + core | Bad syscall |

**`PROCESS_SUSPEND_RESUME`** — default action stop or continue: <a id="cite-psb.signal.suspend-resume-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGSTOP` | 19 | Stop | Forced stop, cannot be caught |
| `SIGTSTP` | 20 | Stop | Terminal stop, Ctrl-Z |
| `SIGTTIN` | 21 | Stop | Background read from terminal |
| `SIGTTOU` | 22 | Stop | Background write to terminal |
| `SIGCONT` | 18 | Continue | Resume a stopped process |

**`PROCESS_SIGNAL`** — default action ignore: <a id="cite-psb.signal.ignore-set"></a>

| Signal | # | Default | Notes |
|---|---|---|---|
| `SIGCHLD` | 17 | Ignore | Child status change |
| `SIGURG` | 23 | Ignore | Urgent socket data |
| `SIGWINCH` | 28 | Ignore | Window resize |

The real-time signals, `SIGRTMIN` through `SIGRTMAX` (32–64), default
to terminate and therefore require `PROCESS_TERMINATE`. <a id="cite-psb.signal.realtime-terminate"></a>

<a id="trm-3-3-3-2-1"></a>

### What bypasses the check

This classification applies only to signals sent by userspace through
`kill()`, `tkill()`, and `tgkill()`. Kernel-generated signals —
hardware faults such as `SIGSEGV`, `SIGBUS` and `SIGFPE`, `SIGCHLD`
from a child exiting, `SIGPIPE` from a broken pipe — are delivered by
the kernel and bypass the process descriptor check entirely, because
the `task_kill` LSM hook does not fire for kernel-originated delivery. <a id="cite-psb.signal.kernel-generated-bypass"></a>

Terminal-generated job control signals are kernel-originated under
that rule and bypass the check the same way: `SIGINT`, `SIGQUIT` and
`SIGTSTP` from the tty driver's `isig` handling, and `SIGHUP` on
hangup. <a id="cite-psb.signal.tty-isig-bypass"></a> This is intentional. Authorization for keyboard-driven signals
is possession of the controlling terminal, which was gated by the
terminal's file descriptor at open time — so Ctrl-C reaches the whole
foreground process group even when a member of it is more privileged
or more PIP-trusted than whoever holds the terminal. A process that
cannot accept that exposure must not attach to an untrusted
controlling terminal.

The `si_uid` in a delivered signal's `siginfo_t` is the sender's
projected UID ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)), captured at send time. <a id="cite-psb.signal.si-uid-projected"></a> Like every projected
credential surface it is informational only and is not an
authorization input; `si_pid` carries the same caveat and is subject
to PID reuse besides.

<a id="trm-3-3-3-3"></a>

## Generic mapping <a id="cite-psb.generic-mapping"></a>

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `PROCESS_QUERY_INFORMATION \| PROCESS_VM_READ \| READ_CONTROL` |
| `GENERIC_WRITE` | `PROCESS_SET_INFORMATION \| PROCESS_VM_WRITE \| WRITE_DAC` |
| `GENERIC_EXECUTE` | `PROCESS_TERMINATE \| PROCESS_SUSPEND_RESUME \| PROCESS_QUERY_LIMITED` |
| `GENERIC_ALL` | every process right above, together with `READ_CONTROL`, `WRITE_DAC` and `WRITE_OWNER` |

<a id="trm-3-3-3-4"></a>

## The default process descriptor <a id="cite-psb.sd.default-template"></a>

Every process receives a default descriptor at creation:

```
Owner: <creator's primary token user SID>
Group: <creator's primary token primary group SID>
DACL:
  ALLOW  <process's own user SID>   GENERIC_ALL
  ALLOW  BUILTIN\Administrators     GENERIC_ALL
  ALLOW  SYSTEM                     GENERIC_ALL
  ALLOW  Everyone                   PROCESS_QUERY_LIMITED
```

A process can therefore do anything to itself; Administrators and
SYSTEM have full control over every process; everyone can see basic
process information, which is what makes `ps` and `top` work for all
users; and detailed inspection — token, memory, environment — is
restricted to the process itself, administrators, and SYSTEM.

A service can modify its own descriptor at runtime with
`kacs_set_sd`, which requires `WRITE_DAC` — granted to the process
itself by the default DACL. <a id="cite-psb.sd.set-sd-requires-write-dac"></a> Requesting a custom descriptor *at launch*
through a service definition is not implemented: the only descriptor
creation path always builds the default template, so every process
starts from it and any deviation is a subsequent write. <a id="cite-psb.sd.no-custom-at-launch"></a>

<a id="trm-3-3-3-5"></a>

## How PIP relates to it

PIP and the process descriptor are complementary, and both checks have
to pass. <a id="cite-psb.pip.both-checks-must-pass"></a> The descriptor controls *who* may operate on the process; PIP
controls *what trust level* is required for invasive access to a
protected one. AccessCheck evaluates the caller's token against the
target's descriptor for the requested right, and PIP evaluates the
caller's trust against the target's `pip_type` and `pip_trust` for
operations crossing the process boundary.

The two are genuinely independent. A process may have a permissive
descriptor granting Administrators `GENERIC_ALL` and still be
PIP-protected, so administrators pass the descriptor check and are
stopped only by insufficient PIP trust.

The converse — a process with no PIP protection carrying a restrictive
descriptor that denies even administrators — holds with one
qualification. When a descriptor check denies access and PIP was not
the deciding factor, an enabled `SeDebugPrivilege` on the caller
grants the access anyway and is marked used. <a id="cite-psb.sd.sedebug-overrides-denial"></a> The privilege therefore
rescues a descriptor denial while remaining unable to cross a PIP
boundary, which is exactly the split [Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md#trm-3-4-2>) describes for it.

---

# Privileges

_Peios Kernel / Internals / KACS / Privileges_

> Find the Peios kernel articles about privileges.

Use these articles to understand privileges in the Peios kernel.

- [The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md>)
- [Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md>)

---

# The Privilege Model

_Peios Kernel / Internals / KACS / Privileges_

> Rights that do not fit the subject-object model — the privilege lifecycle, the two enforcement categories, intent gating, assignment and auditing.

<a id="trm-3-4-1"></a>

Some operations do not fit the subject-object model at all. Rebooting
the machine, loading a kernel module, changing the system clock,
creating a token — these affect the system itself rather than a
specific protected resource, so there is nothing to attach a security
descriptor to. They still need authorization.

Privileges fill that gap. A privilege is the right to perform a
particular system operation, carried on the token beside the
principal's identity. Where a descriptor says "this principal may read
this file", a privilege says "this principal may shut down the
system". The descriptor lives on the object; the privilege lives on
the subject.

<a id="trm-3-4-1-1"></a>

## Lifecycle

A privilege is **assigned by policy** when authd creates the token,
resolving the principal's assignments from security policy once, at
creation. There are no runtime grants: a privilege absent at creation
can never be added later. <a id="cite-priv.lifecycle.no-runtime-grants"></a>

The privilege then sits on the token in whatever enabled state it was
created with. The kernel accepts any enabled set that is a subset of
the present set, and takes the creation-time enabled set as the
enabled-by-default set. <a id="cite-priv.enabled-subset-of-present"></a> authd issues every privilege it grants already
enabled, on the reasoning that a privilege the holder had to enable
before it worked would be a grant in name only — so the
present-but-disabled resting state exists in the model and is
reachable through AdjustPrivileges, but is not where privileges
normally start.

A privilege that has been disabled is re-activated by **explicitly
enabling** it through AdjustPrivileges.

When the privilege is **exercised**, the kernel checks that it is both
present and enabled — a single mask test against both words — permits
the operation, and records it as used. <a id="cite-priv.check.enabled-not-just-present"></a>

For a standalone gate, "exercised" means the gate accepted that bit,
and the used bit is meant to be recorded even when a later independent
check — a process descriptor, PIP, or a malformed-input test — denies
the operation afterwards. <a id="cite-priv.used.recorded-despite-later-denial"></a> Where the shared privilege helper performs
the check, it marks the bit immediately, and the impersonation gate
does the same. <a id="cite-priv.used.helper-marks-immediately"></a> Three gates mark later and therefore record nothing
when a subsequent check fails:

- token creation marks after the token has been constructed and its
  descriptor allocated, so a malformed specification leaves the bit
  unset; <a id="cite-priv.used.create-token-marks-late"></a>
- primary token installation marks after the same-user and
  same-LogonSession gate; <a id="cite-priv.used.install-marks-late"></a>
- and the `CAP_SYS_BOOT` mapping marks after the remote-shutdown
  origin gate. <a id="cite-priv.used.cap-sys-boot-marks-late"></a>

Used-state for the AccessCheck-influencing privileges follows the
provenance rules of [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>) instead.

Recording the used bit is not merely bookkeeping. Every gate treats a
failure to record it as a failure of the operation itself and returns
`EPERM` or `EACCES`. <a id="cite-priv.used.record-failure-fails-operation"></a>

Afterwards the privilege may be **disabled**, returning to rest, or
**removed permanently**, which clears it from the present, enabled,
and enabled-by-default states while preserving the `used` bit for
audit. <a id="cite-priv.remove.preserves-used-bit"></a>

<a id="trm-3-4-1-2"></a>

## Two enforcement categories

**Standalone operation gates** are the majority. They authorize
specific operations that AccessCheck does not mediate — rebooting,
loading modules, debugging processes — and the kernel simply checks
whether the calling thread's token holds the privilege present and
enabled before allowing the operation.

**AccessCheck-influencing privileges** alter the outcome of
AccessCheck itself, causing it to grant rights the object's DACL would
not grant on its own. They are evaluated inside the pipeline alongside
DACL rules, integrity policy, and confinement. There are five:
`SeSecurityPrivilege` grants `ACCESS_SYSTEM_SECURITY` for SACL access
(and doubles as a standalone gate for the audit-related Linux
capabilities); `SeTakeOwnershipPrivilege` grants `WRITE_OWNER` as a
post-DACL fallback; `SeBackupPrivilege` grants all read access;
`SeRestorePrivilege` grants all write access plus `WRITE_DAC`,
`WRITE_OWNER`, `DELETE` and `ACCESS_SYSTEM_SECURITY`; and
`SeRelabelPrivilege` loosens MIC's constraint on `WRITE_OWNER` for
non-dominant callers. <a id="cite-priv.accesscheck.five-privileges"></a> [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>) gives the exact mechanics.

<a id="trm-3-4-1-3"></a>

## Intent gating <a id="cite-priv.intent-gating"></a>

`SeBackupPrivilege` and `SeRestorePrivilege` are intent-gated. Other
AccessCheck-influencing privileges are self-scoping —
`SeSecurityPrivilege` only matters when `ACCESS_SYSTEM_SECURITY` is
requested — but backup and restore grant such broad categories of
access that evaluating them unconditionally would apply them to every
AccessCheck on the system.

AccessCheck therefore takes a `privilege_intent` parameter. A caller
passes `BACKUP_INTENT` for a backup-context operation and
`RESTORE_INTENT` for a restore-context one, and the corresponding
privilege is evaluated only when its flag is present. Without the
flag, these privileges are invisible to the pipeline.

Intent gating also keeps backup and restore *inside* the pipeline
rather than short-circuiting it, which matters because later stages —
PIP in particular — have to be able to constrain privilege-granted
access.

<a id="trm-3-4-1-4"></a>

## Assignment

Privileges are assigned by security policy, not by identity.
Membership of the Administrators group confers no privilege by itself.
Groups and privileges are orthogonal: groups determine which objects
you can reach through DACLs, privileges determine which system
operations you can perform.

An administrator defines policy — that members of Backup Operators
receive `SeBackupPrivilege` and `SeRestorePrivilege`, say. At
authentication authd resolves the principal's group memberships,
evaluates the policy against them, and creates the token carrying the
result. The kernel neither verifies nor evaluates that policy; it
trusts authd as a TCB component. The token then carries those
privileges for its whole lifetime.

<a id="trm-3-4-1-5"></a>

## Auditing

Every exercise sets the token's monotonic used state for that
privilege, and every standalone gate emits an ftrace event. <a id="cite-priv.audit.ftrace-per-standalone-gate"></a>

KMES audit events, of type `kacs.audit.privilege.used`, are emitted
only when the token's `audit_policy` opts in through
`PRIVILEGE_USE_SUCCESS` or `PRIVILEGE_USE_FAILURE`, and they come from
two places, told apart by `operation.name`.

<a id="trm-3-4-1-5-1"></a>

### In an access check

An access check records the five AccessCheck-influencing privileges,
with `operation.name` `access-check`. The event fires
when the privilege's provenance bits intersect both the mapped desired
mask and the final granted mask. For `SeSecurityPrivilege` and
`SeTakeOwnershipPrivilege` that intersection is genuinely
counterfactual — `ACCESS_SYSTEM_SECURITY` is pre-decided by the
privilege, and take-ownership contributes only when `WRITE_OWNER` was
not already granted — so an event means the privilege was load-bearing. <a id="cite-priv.audit.security-takeownership-counterfactual"></a>
Backup and restore seed their bits unconditionally, without asking
whether the DACL would have granted the same access, so their events
also fire for accesses the DACL alone would have permitted. <a id="cite-priv.audit.backup-restore-not-counterfactual"></a>

A `MAXIMUM_ALLOWED` request short-circuits this accounting entirely,
recording no used bits and emitting no `kacs.audit.privilege.used`
events for any privilege.

<a id="trm-3-4-1-5-2"></a>

### At a capability gate

A privilege that satisfies a Linux capability check is recorded too,
with `operation.name` `linux-cap`, the capability in `linux.cap` and the
privilege it mapped to in `privilege.name`, under the token's
`PRIVILEGE_USE_SUCCESS` policy. The volume-management gate the mount
paths consult in place of `CAP_SYS_ADMIN` records the same way with
`operation.name` `volume-mount` and no `linux.cap`. Such a record carries
no object, masks or contribution. <a id="cite-priv.audit.gate-record"></a>

Each gate is recorded once per process and effective token: the first
use of a capability by a process under a token is recorded, and later
uses are not, until the process acts under a token with another GUID,
when every gate counts as unused again. The set belongs to the process,
not to the token, whose used flags derived tokens copy and every process
sharing it shares. <a id="cite-priv.audit.gate-once-per-process-and-token"></a>

Only successful uses are recorded, and only those of a user process's
own capability checks: a check made with `CAP_OPT_NOAUDIT` is a probe
and records nothing, nor does a kernel thread's check, a check from
interrupt context, or a check against another process's credentials. A
check that consumes no privilege — the capabilities every process holds
and the ones none may hold — records nothing either. <a id="cite-priv.audit.gate-only-own-audited-checks"></a>

A capability check can run with spinlocks held, where a record cannot
be built, so the gate notes the use and the record is written as the
process returns to user space, or as it exits. The record therefore
follows the system call that spent the privilege rather than appearing
within it. <a id="cite-priv.audit.gate-record-deferred"></a>

The boot SYSTEM token carries `PRIVILEGE_USE_SUCCESS` ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)), so on a
stock system these records come from SYSTEM and the services running on
its token: they answer who used `SeTcbPrivilege`, and for what.

---

# Privilege Catalogue

_Peios Kernel / Internals / KACS / Privileges_

> Every Peios privilege with the bit it occupies in the token's four privilege words, grouped by what it governs.

<a id="trm-3-4-2"></a>

The complete set of Peios privileges, with the bit each occupies in
the token's four 64-bit privilege words. Format-compatible privileges
sit at their standard Windows LUID positions in bits 2–35; custom
Peios privileges are allocated downward from bit 63, so that a
privilege defined by a future AD release cannot collide with one of
ours. <a id="cite-priv.bits.luid-positions-and-downward-allocation"></a>

Enforcement classes are: **kernel standalone**, enforced at a specific
operation boundary independently of AccessCheck; **AccessCheck**,
evaluated inside the pipeline; **AccessCheck + standalone**, both;
**application-level**, checked by a userspace service rather than the
kernel; and **reserved**, allocated for format compatibility with no
enforcement point.

<a id="trm-3-4-2-1"></a>

## Identity and token management

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeCreateTokenPrivilege` | 2 | 0x4 | Kernel standalone |
| `SeAssignPrimaryTokenPrivilege` | 3 | 0x8 | Kernel standalone |
| `SeImpersonatePrivilege` | 29 | 0x20000000 | Kernel standalone |

`SeCreateTokenPrivilege` mints tokens from scratch, and only TCB
components — authd and peinit — carry it. <a id="cite-priv.catalogue.se-create-token"></a> `SeImpersonatePrivilege`
lets a service impersonate a principal other than itself, and every
service that handles requests on behalf of users needs it; it is
checked in exactly one place, the impersonation identity gate ([Impersonation Gates](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-2>)). <a id="cite-priv.catalogue.se-impersonate"></a>

`SeAssignPrimaryTokenPrivilege` gates installing a token as a
process's primary identity. <a id="cite-priv.catalogue.se-assign-primary-token"></a> Installation is **self-directed**:
`KACS_IOC_INSTALL` acts on the calling process and fans out to the
sibling threads of its own thread group. There is no mechanism for
installing a token on a different process ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). The kernel also
requires the new token to carry the same user SID and the same
LogonSession as the outgoing one, unless the caller additionally holds
`SeTcbPrivilege` ([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)). The privilege is also consulted as a *deny* gate on
the exec and credential projection paths.

<a id="trm-3-4-2-2"></a>

## Access control

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeSecurityPrivilege` | 8 | 0x100 | AccessCheck + standalone |
| `SeTakeOwnershipPrivilege` | 9 | 0x200 | AccessCheck |
| `SeBackupPrivilege` | 17 | 0x20000 | AccessCheck + standalone |
| `SeRestorePrivilege` | 18 | 0x40000 | AccessCheck + standalone |
| `SeRelabelPrivilege` | 32 | 0x1_0000_0000 | AccessCheck + standalone |
| `SeChangeNotifyPrivilege` | 23 | 0x800000 | Kernel standalone |
| `SeCreateSymbolicLinkPrivilege` | 35 | 0x8_0000_0000 | Kernel standalone |
| `SeLockParentagePrivilege` | 61 | 0x2000_0000_0000_0000 | Kernel standalone |

`SeSecurityPrivilege` reads and writes an object's SACL, and also
gates `CAP_AUDIT_CONTROL`, `CAP_MAC_ADMIN` and `CAP_AUDIT_READ`
through the capability mapping, the KMES ring buffer attach, and
supplying a SACL at object creation. <a id="cite-priv.catalogue.se-security"></a>

`SeTakeOwnershipPrivilege` takes ownership of any object regardless of
its permissions. It is the only privilege here with no standalone
enforcement point at all — it exists purely inside AccessCheck. <a id="cite-priv.catalogue.se-take-ownership"></a>

`SeBackupPrivilege` and `SeRestorePrivilege` read and write any object
regardless of the DACL. Inside AccessCheck they are intent-gated
([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)), but both are also used as plain standalone gates outside it:
restore on the descriptor replacement path when the cache is invalid
and on owner assignment to a SID the subject does not hold, and both
on the registry key backup and restore paths. <a id="cite-priv.catalogue.backup-restore-standalone-gates"></a>

`SeRelabelPrivilege` changes an object's integrity label, punching
`WRITE_OWNER` through MIC for non-dominant callers and removing the
at-or-below-own-level restriction when a label is written. <a id="cite-priv.catalogue.se-relabel"></a>

`SeChangeNotifyPrivilege` bypasses traverse checking — without it,
reaching a file requires `FILE_TRAVERSE` on every intermediate
directory. <a id="cite-priv.catalogue.se-change-notify"></a> The bypass has one exception the name does not suggest: it
is suppressed when the access carries `MAY_CHDIR`, so an explicit
`chdir` takes a full `FILE_TRAVERSE` check whether or not the caller
holds the privilege. <a id="cite-priv.change-notify.chdir-exception"></a> The privilege additionally gates
`open_by_handle_at`, which has nothing to do with traversal. <a id="cite-priv.change-notify.open-by-handle-at"></a> It is
checked once per intermediate directory on every path resolution, and
each check takes the token's mutation lock for a snapshot and then
performs a used-bit update, so the cost is O(depth) locked operations
per path walk. <a id="cite-priv.change-notify.checked-per-directory"></a>

`SeCreateSymbolicLinkPrivilege` creates symbolic links, and is
required in addition to `FILE_ADD_FILE` on the parent directory. <a id="cite-priv.catalogue.se-create-symbolic-link"></a>

`SeLockParentagePrivilege` pins a file's ancestor directories for as
long as an open of it lasts, so that nobody can rename or remove them
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-6>)). It is a Peios privilege, allocated
downward from bit 63. File servers hold it, to give Windows clients the
folder protection they expect; it blocks other people's work, so
ordinary programs do not. <a id="cite-priv.catalogue.se-lock-parentage"></a>

<a id="trm-3-4-2-3"></a>

## System operations

| Privilege | Bit | Mask | Enforcement |
|---|---:|---|---|
| `SeTcbPrivilege` | 7 | 0x80 | Kernel standalone |
| `SeLockMemoryPrivilege` | 4 | 0x10 | Kernel standalone |
| `SeIncreaseQuotaPrivilege` | 5 | 0x20 | Kernel standalone |
| `SeLoadDriverPrivilege` | 10 | 0x400 | Kernel standalone |
| `SeSystemProfilePrivilege` | 11 | 0x800 | Kernel standalone |
| `SeSystemtimePrivilege` | 12 | 0x1000 | Kernel standalone |
| `SeProfileSingleProcessPrivilege` | 13 | 0x2000 | Kernel standalone |
| `SeIncreaseBasePriorityPrivilege` | 14 | 0x4000 | Kernel standalone |
| `SeManageVolumePrivilege` | 28 | 0x10000000 | Kernel standalone <a id="cite-priv.catalogue.se-manage-volume"></a> |
| `SeShutdownPrivilege` | 19 | 0x80000 | Kernel standalone |
| `SeDebugPrivilege` | 20 | 0x100000 | Kernel standalone |
| `SeAuditPrivilege` | 21 | 0x200000 | Kernel standalone |
| `SeRemoteShutdownPrivilege` | 24 | 0x1000000 | Kernel standalone |

`SeTcbPrivilege` is the catch-all for system operations with no more
specific privilege, and only TCB services need it. It has by far the
widest reach of any privilege: fourteen Linux capability mappings,
several token operations, the mount policy paths, the central access
policy cache, LogonSession creation and destruction, removal of
mandatory resource attribute ACEs during descriptor merge, a KMES rate
limit exemption, the LCS source authentication path, and the upgrade
of a linked-token query from an Identification-level copy to the real
token at full access. <a id="cite-priv.catalogue.se-tcb"></a>

The PEI-549 block-layer change also accepts enabled `SeManageVolumePrivilege`
or `SeTcbPrivilege`, with successful privilege-use marking, for `BLKRRPART`
(partition-table rescan), `BLKPG` (partition management) and `BLKFLSBUF`
(buffer-cache flush). The caller still needs a usable block-device handle.
Administrators membership alone, or a present but disabled privilege, does
not pass this gate. Other `CAP_SYS_ADMIN` checks, including `BLKROSET`, retain
their existing TCB requirement. This change has native VM qualification;
older published kernels may still require `SeTcbPrivilege` for all three.

`SeShutdownPrivilege` shuts down or reboots the machine, mapped
through `CAP_SYS_BOOT`. <a id="cite-priv.catalogue.se-shutdown"></a> `SeRemoteShutdownPrivilege` is required *in
addition* when the request originates from a Network,
NetworkCleartext, NewCredentials, or RemoteInteractive logon. <a id="cite-priv.catalogue.se-remote-shutdown"></a>

`SeLoadDriverPrivilege` loads and unloads kernel modules through
`CAP_SYS_MODULE`. <a id="cite-priv.catalogue.se-load-driver"></a> `SeDebugPrivilege` attaches to and inspects any
process regardless of its descriptor, and does not bypass PIP ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). <a id="cite-priv.catalogue.se-debug"></a>

- `SeSystemtimePrivilege` changes the clock, <a id="cite-priv.catalogue.se-systemtime"></a>
- `SeIncreaseBasePriorityPrivilege` raises scheduling priority and
  sets CPU affinity for other processes, <a id="cite-priv.catalogue.se-increase-base-priority"></a>
- `SeIncreaseQuotaPrivilege` overrides resource limits, <a id="cite-priv.catalogue.se-increase-quota"></a>
- `SeLockMemoryPrivilege` locks pages in physical memory, <a id="cite-priv.catalogue.se-lock-memory"></a>
- and `SeAuditPrivilege` writes events to the audit log — it is what
  KMES requires for userspace event emission. <a id="cite-priv.catalogue.se-audit"></a>

`SeProfileSingleProcessPrivilege` attaches `perf_event_open()` to a
specific other process. <a id="cite-priv.catalogue.se-profile-single-process"></a> It respects PIP dominance, and own-task
profiling requires nothing. <a id="cite-priv.profile.pip-dominance-and-own-task"></a> `SeSystemProfilePrivilege` covers
system-wide profiling — per-CPU events, all-task sampling, kernel-mode
events — and does not respect PIP at the per-sample level, since
system-wide samples include PIP-protected tasks. <a id="cite-priv.catalogue.se-system-profile"></a> It is an
operator-class privilege.

Those two and `SeLoadDriverPrivilege` share one mapping: `CAP_PERFMON`
is satisfied by **any** of the three, and every one the caller holds is
marked used. <a id="cite-priv.perfmon.satisfied-by-any-of-three"></a> The two profiling privileges are otherwise disjoint
tiers.

<a id="trm-3-4-2-4"></a>

## Network

No privilege. Binding a port is an access check against the port's
reservation — a security descriptor keyed by protocol and port range —
not a privilege test; see [Port reservations](/kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1). <a id="cite-priv.network.no-port-privilege"></a>
Bit 63 was `SeBindPrivilegedPortPrivilege` until that object existed; the
bit is retired and not reused.

<a id="trm-3-4-2-5"></a>

## Directory and domain operations

| Privilege | Bit | Enforcement |
|---|---:|---|
| `SeSyncAgentPrivilege` | 26 | Application-level |
| `SeEnableDelegationPrivilege` | 27 | Application-level |
| `SeMachineAccountPrivilege` | 6 | Application-level |

`SeSyncAgentPrivilege` reads every object in the directory regardless
of per-object permissions, for AD replication agents.
`SeEnableDelegationPrivilege` marks a principal as trusted for
delegation. `SeMachineAccountPrivilege` adds computer accounts to the
domain. None has a kernel definition, which is consistent with their
being application-level — but none has a userspace definition in the
tree either, so at present nothing anywhere enforces them. <a id="cite-priv.application-level.none-enforced-anywhere"></a>

<a id="trm-3-4-2-6"></a>

## Reserved

Allocated for format compatibility so that tokens from Active
Directory environments carry them without information loss. None is
defined in the kernel and none has an enforcement point. <a id="cite-priv.reserved.no-enforcement-point"></a>

| Privilege | Bit | Reservation rationale |
|---|---:|---|
| `SeCreatePagefilePrivilege` | 15 | Absorbed into `SeTcbPrivilege`. |
| `SeCreatePermanentPrivilege` | 16 | No Linux equivalent. |
| `SeSystemEnvironmentPrivilege` | 22 | Gated by descriptors on efivar files under FACS. |
| `SeUndockPrivilege` | 25 | Server operating system. |
| `SeCreateGlobalPrivilege` | 30 | Peios has no per-LogonSession object namespaces. |
| `SeTrustedCredManAccessPrivilege` | 31 | Reserved for future secrets infrastructure. |
| `SeIncreaseWorkingSetPrivilege` | 33 | Linux does not gate memory residency hints. |
| `SeTimeZonePrivilege` | 34 | Linux does not gate timezone changes. |

<a id="trm-3-4-2-7"></a>

## Unallocated and unnamed bits

`SeCreateJobPrivilege` is allocated bit 62 and is unused: no kernel
definition exists for it and nothing consults it. <a id="cite-priv.create-job.bit-62-unused"></a> Submitting a
supervised job is not a privilege at all — it is governed by the file
Security Descriptor on the service manager's jobs socket, checked by
the kernel when a process connects (the Peinit TRM). The bit is
nevertheless included in the boot SYSTEM token's privilege set, which
covers bits 2–35 together with 61, 62 and 63, so the SYSTEM token holds
bit 62 present and enabled with no name attached to it and no gate
that consults it. <a id="cite-priv.create-job.present-in-system-token"></a>

Nothing validates a privilege mask against the allocated set. Token
creation checks only that the enabled set is a subset of the present
set, and adjustment accepts any bit index from 0 to 63. Bits 0, 1, and
36–60 — positions the catalogue does not allocate at all — can
therefore be set at creation and disabled or removed afterwards
without error, and are simply inert. <a id="cite-priv.bits.unallocated-accepted-and-inert"></a>

<a id="trm-3-4-2-8"></a>

## Default grants

`SeChangeNotifyPrivilege` is granted to every principal, as an authd
policy decision rather than a kernel one: the issuer's floor grants it
to Everyone. <a id="cite-priv.default.change-notify-to-everyone"></a> `SeCreateSymbolicLinkPrivilege`, the other traditional
default-grant privilege, is deliberately **not** in the floor: a
machine with no authd policy seed applied doesn't grant it. <a id="cite-priv.default.symlink-not-granted"></a> authd's
shipped policy seed grants it to Everyone, because build systems and
packaging tools assume it; a site can remove it there without
affecting the floor. Either can be removed from a specific token by
FilterToken.

---

# Impersonation

_Peios Kernel / Internals / KACS / Impersonation_

> Find the Peios kernel articles about impersonation.

Use these articles to understand impersonation in the Peios kernel.

- [Levels and admission](</kernel/internals/kacs/impersonation/levels-and-admission.md>)
- [State transitions](</kernel/internals/kacs/impersonation/state-transitions.md>)
- [Transport and per-message identity](</kernel/internals/kacs/impersonation/transport-and-per-message-identity.md>)

---

# Levels and admission

_Peios Kernel / Internals / KACS / Impersonation_

> The four levels at which a server thread may assume a client's identity, and what each permits.

<a id="trm-3-5-1"></a>

Impersonation lets a server thread temporarily assume a client's
identity, so that access control decisions on that thread evaluate the
client's token instead of the server's.

The client controls how far its identity can travel by setting an
impersonation level on the connection before it is established, and
the server cannot escalate beyond the level the client chose. There is
no API that bypasses that choice.

**Anonymous.** The server cannot identify the caller at all. The
connection carries no identity information: both token inspection and
impersonation yield a token whose user SID is Anonymous (`S-1-5-7`),
which carries Everyone as an enabled group and does not carry
Authenticated Users. <a id="cite-imp.anonymous.no-identity-conveyed"></a>

**Identification.** The server can identify the caller — read SIDs,
query groups, inspect privileges — but cannot act as them. An
Identification-level token is barred from AccessCheck against
resources: a server thread impersonating one and attempting to open a
file simply fails the check, with `EACCES` — the same refusal the
`kacs_access_check` syscall reports for that token. <a id="cite-imp.identification.barred-from-accesscheck"></a>

**Impersonation.** The server can act as the caller for all local
operations, including ones that cross local IPC boundaries. If service
A impersonates client B at this level and connects to local service C,
C sees B's identity — identity cascades freely across local services. <a id="cite-imp.impersonation.cascades-across-local-services"></a>
This is the default.

**Delegation.** Locally identical to Impersonation. The distinction
activates at the network boundary, where a Delegation-level token
carries authorization for the server to forward the client's identity
to services on other machines through Kerberos. <a id="cite-imp.delegation.network-boundary-only"></a> KACS enforces the
level; authd is what acts on it.

The level is set by the client through a KACS syscall on the socket
before `connect()`, and defaults to Impersonation. <a id="cite-imp.level.socket-default-impersonation"></a>

<a id="trm-3-5-1-1"></a>

## The level is a ratchet <a id="cite-imp.level.ratchet-only-down"></a>

Every token carries an impersonation level, and on every token it
means the same thing: *identity derived from this token may act at no
more than this level*. An impersonation token acts at its level. A
primary token's level is the ceiling on everything the process
carrying it can convey — what a peer captures at connect, what
`KACS_SO_PASS_TOKEN` attaches, what `KACS_IOC_DUPLICATE` produces in
either direction. <a id="cite-imp.level.primary-is-conveyance-ceiling"></a>

The level only ever goes down:

- Socket capture and `KACS_SCM_TOKEN` attach store the lower of the
  socket's level and the source token's own; <a id="cite-imp.level.capture-takes-lower"></a>
- DuplicateToken refuses a result above its source, whatever the types
  involved;
- fork, exec, `NEW_PROCESS_MIN`, FilterToken and primary installation
  copy it unchanged. <a id="cite-imp.level.derivation-copies-unchanged"></a>

The one way to a higher level is a fresh token from CreateToken, which
takes `SeCreateTokenPrivilege`. <a id="cite-imp.level.raise-only-via-create-token"></a> authd mints logon tokens at Delegation
and the bootstrap SYSTEM token is Delegation, so an identity starts at
the top and each hop can only lower it.

This is what makes the client's choice hold across any number of
hops and process boundaries. A client that connects at Impersonation
is captured at Impersonation; a server that converts that token to a
primary and launches a process with it ([Token Creation](</kernel/internals/kacs/tokens/token-creation.md#trm-3-2-4>)) produces a process
capped at Impersonation; and nothing that process captures, conveys
or duplicates can ever be Delegation — so authd, which reads the
level to decide whether to forward the client's credentials, is never
shown a Delegation flag the client did not grant. <a id="cite-imp.level.holds-across-hops"></a>

<a id="trm-3-5-2"></a>

When a server thread attempts to impersonate a client's token, two
independent checks decide whether it proceeds at the requested level.
Both have to pass. If either fails the effective level is reduced to
Identification — the movement is only ever downward.

Both gates are evaluated against the server's **primary token**
(`real_cred`), never its effective token. <a id="cite-imp.gate.evaluated-against-primary-token"></a> A server already
impersonating another client has its gates judged against its own
service identity, so a previous impersonation cannot influence the
next one.

<a id="trm-3-5-2-1"></a>

## The identity gate

The identity gate asks whether this server may impersonate this
particular user's identity. Impersonation at Impersonation or
Delegation level is permitted if either of two conditions holds.

**Same user, same restriction status** — the server's primary token
and the client's token carry the same user SID, and both are
restricted or both unrestricted. <a id="cite-imp.gate.same-user-same-restriction"></a>

**`SeImpersonatePrivilege`** — the server's primary token holds it,
enabled. <a id="cite-imp.gate.impersonate-privilege-enabled"></a>

If neither holds, the level is **silently capped to Identification**. <a id="cite-imp.gate.identity-failure-caps-silently"></a>
No error is returned: the call succeeds, and the resulting token is
merely at Identification level.

There is one hard denial. A **restricted** server impersonating an
**unrestricted** client of the same user is rejected outright with
`-EPERM` rather than capped, because that is precisely how a sandboxed
process would escape by impersonating its parent's unrestricted token. <a id="cite-imp.gate.restricted-to-unrestricted-eperm"></a>
The reverse direction, unrestricted server to restricted client, is a
harmless downgrade and takes the ordinary cap-to-Identification path. <a id="cite-imp.gate.unrestricted-to-restricted-caps"></a>

MS-DTYP includes a third condition — an origin LogonSession check
letting the session that created a token impersonate it without the
privilege. KACS drops it. A service needing to impersonate a different
user holds `SeImpersonatePrivilege`, and there are no hidden paths.

<a id="trm-3-5-2-2"></a>

## The integrity ceiling <a id="cite-imp.gate.integrity-ceiling"></a>

The integrity ceiling asks whether the client's token sits at an
integrity level the server is allowed to assume. To act at
Impersonation or Delegation level, the client token's integrity level
has to be less than or equal to the server primary token's. A
Medium-integrity server can impersonate Low or Medium clients; against
a High-integrity client the level caps to Identification.

The installed token may keep the client's literal integrity label as
identity metadata after the cap, but that preserved label authorizes
nothing, because Identification-level tokens are barred from
AccessCheck entirely. <a id="cite-imp.gate.capped-token-keeps-label"></a>

The ceiling exists because MIC evaluates the *effective* token's
integrity level for tokens that can act. Without it, a server could
impersonate a higher-integrity token and gain write access to
higher-integrity objects — integrity escalation through impersonation.

The ceiling is enforced unconditionally, regardless of privilege.
`SeImpersonatePrivilege` bypasses the identity gate and never the
ceiling. <a id="cite-imp.gate.privilege-never-bypasses-ceiling"></a> MS-DTYP allows the privilege to bypass every check including
this one; KACS does not, because `mandatory_policy` is immutable here
([Token Structure](</kernel/internals/kacs/tokens/token-structure.md#trm-3-2-2>)) and MIC is consequently a real boundary. Letting a privilege
punch through would give back exactly what that immutability buys.

<a id="trm-3-5-2-3"></a>

## Composition <a id="cite-imp.gate.composition-minimum"></a>

The two gates are independent, both are evaluated, and the effective
level is the minimum any constraint permits: start from the level the
client set on the socket, cap to Identification if the identity gate
fails, cap to Identification if the integrity ceiling fails, and the
result is the effective impersonation level.

---

# State transitions

_Peios Kernel / Internals / KACS / Impersonation_

> State transitions: behaviour and implementation of the Peios kernel.

<a id="trm-3-5-3"></a>

<a id="trm-3-5-3-1"></a>

## The sequence

**The client connects.** It optionally sets the maximum impersonation
level on the socket with `setsockopt(SOL_KACS,
KACS_SO_IMPERSONATION_LEVEL)` — the default is Impersonation; the
option may be changed at any time and bounds every capture made from
then on — and calls `connect()`. <a id="cite-imp.capture.level-changeable-bounds-later-captures"></a> The kernel's LSM hook fires on the
Unix stream connection.

**Identity is captured, both ways.** The hook examines the client
thread's effective credential together with the socket's maximum
level, derives the identity at the lower of that level and the
effective token's own ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)), and stores the result on the accepted
end. It also stores, on
the connecting end, the identity the listener captured when `listen()`
was called — so a client can read `KACS_SO_PEER_TOKEN` on its own
socket immediately after `connect()` and verify who it reached, at
Identification level unless the listener set its own level. <a id="cite-imp.capture.listener-identity-to-connecting-end"></a> The
listener's identity is what `listen()` saw; a process that inherits a
listener it did not create (from a descriptor store after a restart,
or from a broker) replaces it with its own using `setsockopt(SOL_KACS,
KACS_SO_RESTAMP)`, which is self-gated and fails with `EINVAL` on a
socket that is not listening. <a id="cite-imp.restamp.listening-socket-only"></a> Clients that connect before the restamp
see the previous holder, which is honest: that is who was listening. <a id="cite-imp.restamp.not-retroactive"></a>
Squatting a name therefore buys nothing against a client that checks —
the squatter's own identity is what it conveys. At
Anonymous, a token whose user SID is `S-1-5-7`, whose enabled groups
include Everyone, and which does not carry Authenticated Users is
stored on the socket's LSM blob, and the client's real identity is
never recorded. <a id="cite-imp.capture.anonymous-records-no-real-identity"></a> At Impersonation or Delegation, the thread's effective
token is stored — and if the connecting thread is itself
impersonating, the impersonated identity is what flows through, which
is how identity cascades across local services. <a id="cite-imp.capture.stores-effective-token"></a> At Identification, the
effective token is stored but tagged at that level.

**The server reads the peer token** with `getsockopt(SOL_KACS,
KACS_SO_PEER_TOKEN)` on the accepted connection, which opens a token fd
carrying `TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE` for the
identity in that
end's conveyed-identity register — at this point, the identity captured
at connect (see *Per-message identity* below for how the register
moves). <a id="cite-imp.peer-token.fd-access-mask"></a>
**It impersonates** by installing that fd with `KACS_IOC_IMPERSONATE`:
the kernel evaluates both gates against the server thread's primary
token, computes the effective level, and constructs a new credential
carrying the impersonation token at that level. libpeios fuses the
two steps as `peios_token_impersonate_peer` for the handler that
impersonates, works and reverts on one thread.

**Access control follows the impersonation token.** Every subsequent
AccessCheck on the thread evaluates it, and MIC uses its integrity
level. PIP continues to read the PSB, unchanged.

**The server reverts** with `kacs_revert()`, restoring the thread's
credential to `real_cred` and its service identity with it. <a id="cite-imp.revert.restores-real-cred"></a>

<a id="trm-3-5-3-2"></a>

## Anonymous

Any thread may impersonate the Anonymous identity without passing
either gate. <a id="cite-imp.anonymous.no-gates"></a> Assuming Anonymous is always a downgrade — the token has
no access beyond what is explicitly granted to `S-1-5-7` or Everyone —
so no privilege is needed, no identity gate runs, and no integrity
ceiling applies.

Anonymous tokens carry the Anonymous SID as the user SID, no
privileges, and Untrusted integrity. The socket path constructs that
minimal shape rather than preserving any part of the caller's real
identity. <a id="cite-imp.anonymous.socket-constructs-minimal-shape"></a>

<a id="trm-3-5-3-3"></a>

## Double impersonation <a id="cite-imp.double.revert-then-reimpersonate"></a>

A thread already impersonating that installs another token with
`KACS_IOC_IMPERSONATE` causes the kernel to revert internally and then
re-impersonate.
Because the gates are evaluated against the primary token, the
previous impersonation has no bearing on the new one.

<a id="trm-3-5-3-4"></a>

## Interaction with MIC and PIP

**MIC reads the effective token** for tokens permitted to act, which
is safe precisely because the integrity ceiling makes acting
impersonation safe. <a id="cite-imp.mic.reads-effective-token"></a> A thread cannot act at Impersonation or Delegation
level with a client token whose integrity exceeds the server primary
token's. When the ceiling caps the level to Identification, the
installed token may still preserve the client's literal label as
metadata, but it authorizes no resource access because
Identification-level tokens are barred from AccessCheck. An acting
impersonation token therefore preserves or lowers the server's
integrity, and a higher literal label can only ever exist on a
non-acting Identification-level token.

**PIP reads the PSB**, because there is no equivalent ceiling for it. <a id="cite-imp.pip.reads-psb-not-effective-token"></a>
PIP operates on `pip_type` and `pip_trust`, which are orthogonal to
integrity level. Reading them from the effective token would let a
process impersonate a token carrying higher PIP values and acquire
protection it has not earned.

<a id="trm-3-5-3-5"></a>

## SeImpersonatePrivilege

The privilege permits a service to impersonate arbitrary clients —
those with different user SIDs. Without it a process can impersonate
only tokens matching its own user SID and restriction status.

It is checked against the server's primary token, so a thread already
impersonating one client is judged on its real service identity. It
has to be enabled at the moment of the call. And it bypasses the
identity gate only, never the integrity ceiling.

<a id="trm-3-5-3-9"></a>

## Audit records

Every `KACS_IOC_IMPERSONATE` writes a `kacs.impersonation.started`
record through KMES ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)). Its subject is the server's token, the one
that acted, and its object is the client token: `object.token.sid`,
`.type`, `.integrity`, `.auth-id` and `.restricted`, with the level the
client token offered as `object.token.impersonation` and the level the
gate allowed as `object.token.impersonation-permitted`. The thread that
took the identity on is `emitter.thread.tid`, since impersonation is per
thread. Where the gate needed `SeImpersonatePrivilege` and used it, the
record carries `privilege.name` and `privilege.held`. <a id="cite-imp.audit.started-record"></a>

A level the gate lowered is not a failure: the record says
`outcome.success` with `impersonation-permitted` below
`impersonation`. A lowered level installs a new token, and the record's
`object.token.guid` and `object.token.id` are always the installed
token's — the client's own when the level was not lowered, the new one
when it was — so they match the header of the records the thread writes
next. <a id="cite-imp.audit.started-permitted-level"></a>

A refused impersonation is recorded too, with `outcome.errno` and, where
the kernel knows why, `outcome.reason`: `primary-token` for a primary
token (`EINVAL`), `restriction-escape` for a restricted server reaching
for an unrestricted token of its own user (`EPERM`),
`no-impersonate-access` for a handle without `TOKEN_IMPERSONATE`
(`EACCES`), and `projection-failed` when the identity could not be
projected onto the thread's credentials. A refusal before the gate
answered carries no `impersonation-permitted`. <a id="cite-imp.audit.started-records-refusals"></a>

Ending an impersonation writes `kacs.impersonation.reverted`, a
`verbose` type, so only where the emission policy ([Emission Policy](</kernel/internals/kmes/emission-policy.md#trm-2-8>)) switches it on.
The record names the
token given up in `object.token.guid` and `object.token.sid`, with the
thread's token after the revert as subject. `operation.name` says why:
`revert` for `kacs_revert`, `exec` for the revert every exec performs,
and `replaced` when a second impersonation ends the first. A revert with
no impersonation in force writes nothing, nor does the revert and
re-apply around a primary-token install, which leaves the impersonation
in place, nor does a thread that exits while impersonating. <a id="cite-imp.audit.reverted-record"></a>
Both records are best effort: a record that cannot be built does not
change the outcome of the impersonation or the revert.

## Related explanations

- [Transport and per-message identity](</kernel/internals/kacs/impersonation/transport-and-per-message-identity.md>)

---

# Transport and per-message identity

_Peios Kernel / Internals / KACS / Impersonation_

> Transport and per-message identity: behaviour and implementation of the Peios kernel.

<a id="trm-3-5-3-6"></a>

## Delegation and the network boundary

Locally, Impersonation and Delegation behave identically. The
distinction activates at the network boundary, where a
Delegation-level token carries authorization for Kerberos credential
forwarding to services on other machines.

KACS tracks the level on the token and the socket, and authd checks it
when it needs to perform Kerberos authentication for an impersonating
thread. KACS itself has no Kerberos awareness and no network
awareness: the level is a flag that authd interprets.

<a id="trm-3-5-3-7"></a>

## Per-message identity

The connect-time capture is the first entry in a per-end
**conveyed-identity register**: the peer identity associated with the
data that end has consumed so far. <a id="cite-imp.register.connect-capture-is-first-entry"></a> Identity can also travel with the
data itself, as a `KACS_SCM_TOKEN` ancillary message under the
`SOL_KACS` level, and each such message the reader's position passes
advances the register. The anchor is the read position, never arrival:
a token still queued behind unread data is not yet visible, so a
handler can never be told an identity for a request it has not read. <a id="cite-imp.register.anchored-at-read-position"></a>
`KACS_SO_PEER_TOKEN` returns a fresh fd to an immutable snapshot each
time; two calls may name different tokens, but a token never changes. <a id="cite-imp.peer-token.immutable-snapshot"></a>

**Sending.** A sender conveys identity in one of two ways, and the
receiver cannot tell them apart, because both mean the same thing —
*the kernel verified that the sender could be this identity when it
sent these bytes*:

- Automatically, with `KACS_SO_PASS_TOKEN` set on the sending end:
  every send carries the sender's effective token, derived at the
  lower of the end's impersonation level and the token's own. <a id="cite-imp.pass-token.every-send-carries-effective"></a> The derivation is cached against the
  effective token it was made from, so a run of sends under one
  identity costs one derivation. <a id="cite-imp.pass-token.derivation-cached"></a> A thread that impersonates client A,
  writes to a pooled connection, reverts and writes again conveys A for
  the first write and its own identity for the second, with no change
  to the library doing the writing.
- Explicitly, by attaching a token fd in a `KACS_SCM_TOKEN` cmsg. The
  kernel gates the attach exactly as it would gate impersonating that
  token: the fd must carry `TOKEN_IMPERSONATE`, a primary token is
  first derived to an impersonation token at the lower of the end's
  level and its own, and the
  two-gate model runs with the sender as installer. <a id="cite-imp.scm-token.gated-as-impersonation"></a> An attach the gates
  would cap below the token's own level fails with `EPERM` — an
  explicit act fails loudly where an install would silently downgrade. <a id="cite-imp.scm-token.cap-fails-eperm"></a>
  Attaching a token is therefore never more than impersonating it,
  sending, and reverting; it just avoids the install. A router
  forwarding on behalf of many clients re-attaches each client's token
  to the messages it forwards, and each downstream receiver gets a
  kernel-verified identity through the router.

Anonymous-level tokens attach without a gate, as assuming Anonymous is
always a downgrade. <a id="cite-imp.scm-token.anonymous-attaches-ungated"></a> At most one token per message. <a id="cite-imp.scm-token.one-per-message"></a>

**Receiving.** Every skb a send produces carries the conveyed token, so
a large stream write conveys the same identity on all of its
fragments. <a id="cite-imp.receive.identity-on-every-fragment"></a> A stream read stops at an identity boundary rather than
gluing bytes conveyed under different identities into one return,
which keeps the register exact even on a byte stream; on
`SOCK_SEQPACKET` one send is one message and one identity, which is
why it is the recommended type for Peios-native protocols. <a id="cite-imp.receive.read-stops-at-identity-boundary"></a> As the
reader's position passes conveyed data, the register moves to that
identity. `MSG_PEEK` neither advances the register nor consumes; a
`read()` or `splice()` that consumes data advances it just as
`recvmsg` does, because the register is kept at the point of
consumption, not where ancillary data is copied out. <a id="cite-imp.register.advances-on-consumption-only"></a>

A `KACS_SCM_TOKEN` cmsg — carrying a fresh `TOKEN_QUERY |
TOKEN_IMPERSONATE | TOKEN_DUPLICATE` fd — is delivered with a read when
the receive call
supplied room for it and the read's identity differs from the register
the reader had before the read; otherwise nothing is delivered, and
`MSG_CTRUNC` is set only when a token was due and no room was
supplied. <a id="cite-imp.cmsg.delivered-on-identity-change"></a> A handler that never reads ancillary data still has the
register: `recvmsg`, then `getsockopt(KACS_SO_PEER_TOKEN)`, gives the
identity of what it just read. <a id="cite-imp.register.getsockopt-after-read"></a> Parsing the cmsg is the path for
pipelined or concurrent consumers that need the token bound to a
particular message.

`SOCK_DGRAM` sockets carry no register — many senders share one
receiving socket — so a datagram's token is delivered with every
datagram that carries one and is never retained. <a id="cite-imp.dgram.no-register"></a>

<a id="trm-3-5-3-8"></a>

## Supported transports

Peer-token capture works on two AF_UNIX socket types. <a id="cite-imp.transport.stream-and-seqpacket"></a> `SOCK_STREAM`
is the connection-oriented byte stream, and `SOCK_SEQPACKET` is
connection-oriented with message boundaries and uses the same identity
capture model. Both follow the same lifecycle: capture at `connect()`,
read with `KACS_SO_PEER_TOKEN`, impersonate, revert — with per-message
identity layered on top as described above. `SOCK_DGRAM` supports
per-message identity only: `KACS_SO_PASS_TOKEN` and `KACS_SCM_TOKEN`
work, since a send needs no connection, and
`KACS_SO_IMPERSONATION_LEVEL` bounds them as on any socket, but there
is no register. <a id="cite-imp.dgram.per-message-identity-only"></a>

Where the register does not apply, `KACS_SO_PEER_TOKEN` reports which
case it is. On a datagram socket, or any non-Unix family, the option
fails with `EOPNOTSUPP`. <a id="cite-imp.peer-token.eopnotsupp-non-unix"></a> A `socketpair()` end is connected but starts
with an empty register — no connect happened to capture anything — so
the option fails with `ENODATA` until the peer conveys an identity,
after which the register works as on any connection. <a id="cite-imp.peer-token.socketpair-enodata"></a> A socket that is
not yet connected fails with `ENOTCONN`. <a id="cite-imp.peer-token.enotconn"></a> Pipes and FIFOs are not
sockets at all, so `getsockopt` itself fails with `ENOTSOCK` before
KACS is reached. <a id="cite-imp.peer-token.enotsock-pipes"></a>

For all of these, the universal fallback is explicit token fd
impersonation through `KACS_IOC_IMPERSONATE`, which works regardless
of how the token fd was obtained — the peer-token option, an
`SCM_RIGHTS` transfer, or any other path. <a id="cite-imp.impersonate.any-token-fd"></a>

---

# Executable trust

_Peios Kernel / Internals / KACS / Executable trust_

> Find the Peios kernel articles about executable trust.

Use these articles to understand executable trust in the Peios kernel.

- [Signature verification](</kernel/internals/kacs/executable-trust/signature-verification.md>)
- [Exec and library integrity](</kernel/internals/kacs/executable-trust/exec-and-library-integrity.md>)
- [Firmware verification](</kernel/internals/kacs/executable-trust/firmware-verification.md>)
- [Process integrity protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md>)

---

# Signature verification

_Peios Kernel / Internals / KACS / Executable trust_

> Signature verification: behaviour and implementation of the Peios kernel.

<a id="trm-3-6"></a>

Binary signing is the foundation of PIP trust determination and of
Library Signature Verification. The kernel verifies cryptographic
signatures on executable files to establish their trust level, and
signing is the *only* mechanism by which a binary acquires PIP
protection — there is no runtime API that can confer it.

This section describes verification. The signature format itself, and
what a signer has to produce, are specified in PSPK's Binary Signing
and PIP chapter. The kernel only ever verifies; it holds no private
key and contains no signing primitive.

<a id="trm-3-6-1"></a>

## The key table

The kernel carries its verification keys in a dedicated data section
of the kernel image, as an array of 1960-byte entries — a raw
1952-byte ML-DSA-65 public key, then a `u32` little-endian PIP type,
then a `u32` little-endian PIP trust — terminated by an all-zero
entry. <a id="cite-sig.key-table.entry-layout"></a>

Before any cryptographic work, the whole table is walked and
validated. A table with no all-zero terminator is rejected with
`EINVAL`, and so is a table containing any entry whose tier is not
exactly Protected (512) with `PeiosTcb` trust (8192). <a id="cite-sig.key-table.validation-einval"></a> Both rejections
fail *every* verification on the system, which is what makes the
single-tier constraint absolute rather than conventional: a key at any
other tier does not merely fail to be honoured, it disables signing
entirely. <a id="cite-sig.key-table.invalid-disables-all"></a>

The consequence is that a verified binary is always Protected/8192. <a id="cite-sig.verified-always-protected-tcb"></a>
The Isolated type (1024) is reserved and unreachable, and the
multi-key, multi-tier model the table layout anticipates would need a
change to the validator, not merely an added key. <a id="cite-sig.isolated-type-unreachable"></a>

A build configured for KUnit compiles in a different, hard-coded key
at the same tier, taken from the test vector header. <a id="cite-sig.kunit-test-key"></a> Such a kernel
trusts a publicly known key.

`/sys/kernel/security/kacs/signing_keys` lists the table: one line for
each entry before the terminator, in table order, reading

```
key_sha256=<hex> pip_type=<u32> pip_trust=<u32>
```

where the key is named by the SHA-256 of its raw 1952-byte public key, in
lowercase hexadecimal, and the type and trust are the entry's own, in
decimal. <a id="cite-sig.key-table.securityfs-listing"></a> Entries are listed as they
are, whether or not the validator would accept them, so a table that
disables signing shows why. The keys are public, so reading the file is
not access-checked; whoever can open it can read it. Like every
securityfs object, it can be opened only once the mount has a
synthesising policy, which on Peios lets Authenticated Users in.
<a id="cite-sig.key-table.securityfs-unchecked"></a>

<a id="trm-3-6-2"></a>

## Finding a signature

Verification begins by recording the file's current size. Everything
that follows is bounded by that snapshot, and the size is re-read
before the attempt returns — a file that changed size mid-verification
invalidates the whole result. <a id="cite-sig.size-snapshot-revalidated"></a>

The first four bytes decide the path. A file matching `\x7fELF` takes
the ELF path; a file shorter than four bytes, or with different magic,
goes straight to the xattr. <a id="cite-sig.magic-selects-path"></a>

On the ELF path the kernel parses the header, locates the section
header table and the section-name string table, and scans sections in
index order for one named exactly `.peios.sig`. The match is over all
eleven bytes including the terminating NUL, so a longer name with that
prefix does not match. <a id="cite-sig.elf.section-name-exact-match"></a>

**Finding the section commits the ELF path.** The moment a section
header with that name is found, the xattr is no longer consulted —
whatever happens next. <a id="cite-sig.elf.section-commits-path"></a> A wrong section type, a size other than 3310, a
range outside the file, an allocation failure, a short read, a bad
version byte, or a hash failure all yield "unsigned" rather than
falling back. <a id="cite-sig.elf.section-failures-yield-unsigned"></a> This is deliberate: without it, an attacker could craft
a malformed ELF section to force fallback to whichever path they could
more easily control.

Several *structural* ELF failures commit the path too, before any
`.peios.sig` section has been seen: a file shorter than an ELF header,
a class other than `ELFCLASS64`, a byte order other than little-endian,
an unexpected ELF version, a section header entry size other than 64,
an absent or out-of-range section-name string table index, and a
section header table or string table lying outside the recorded size. <a id="cite-sig.elf.structural-failures-commit"></a>
A 32-bit or big-endian ELF therefore cannot carry an xattr signature
at all — it is committed to the ELF path and then fails on it. The one
structural case that does *not* commit is `e_shnum == 0`, so an ELF
with no section headers falls through to the xattr normally. <a id="cite-sig.elf.no-section-headers-falls-through"></a>

The xattr path reads `security.peios.sig` and requires exactly 3310
bytes; any other size is treated as unsigned. <a id="cite-sig.xattr.exact-size"></a> The read bypasses the
LSM xattr hooks, so FACS does not mediate the verifier's own read of
the signature. <a id="cite-sig.xattr.read-bypasses-lsm-hooks"></a>

<a id="trm-3-6-3"></a>

## Hashing and verification

The message signed is a 32-byte SHA-256 content hash, computed
differently depending on where the signature was found. For an ELF
section source, the hash covers the file with the section's *contents*
replaced by zeros — the `Elf64_Shdr` entry describing it is hashed
verbatim, along with everything else. <a id="cite-sig.hash.elf-section-zeroed"></a> For an xattr source the hash
covers the entire file with no exclusions, and that applies to ELF
files reaching the xattr path as well as to non-ELF ones. <a id="cite-sig.hash.xattr-covers-whole-file"></a> Hashing
proceeds in 4 KB chunks, with the zero run emitted in
`SHA256_BLOCK_SIZE` pieces.

The kernel then verifies the 3309-byte signature against each key in
the table, in order, returning on the first success. <a id="cite-sig.verify.exhaustive-trial-in-order"></a> There is no key
identifier in the blob, so key selection is exhaustive trial and the
cost is one ML-DSA verification per key. The trust tier is a property
of *which key verified*, never of anything the signer encoded. <a id="cite-sig.tier-from-key-not-blob"></a>

Verification uses the kernel crypto signature API with the `mldsa65`
algorithm. That API exposes no context parameter, so the empty FIPS
204 context is structurally guaranteed rather than checked — a
signature made under a non-empty context simply fails to verify. <a id="cite-sig.empty-fips204-context"></a>

<a id="trm-3-6-3-1"></a>

### When verification cannot be performed

"Did not verify" and "could not be verified" are different answers and
are kept apart. The per-key verifier is tri-state: verified, did not
verify, or a negative errno meaning the check could not be made — an
unavailable ML-DSA transform, or a key the transform will not accept. <a id="cite-sig.verifier.tri-state"></a>

A negative stops the search rather than trying the remaining keys: the
failure is in the machinery, and every remaining key would meet the same
one. It then propagates out of the exec path, which **refuses the exec**
with `EACCES`. <a id="cite-sig.unverifiable.exec-eacces"></a>

That asymmetry with the ordinary unsigned path is the point. An unsigned
binary runs with no integrity label, which is legitimate. Treating an
unverifiable one the same way removes PIP from every process the system
executes, and the result is indistinguishable from a correctly working
system that has no signed binaries — so nothing surfaces it until
signing is deployed, at which point it looks like the signing rollout
broke something.

On the LSV path the same condition denies the mapping, which already
fails closed. <a id="cite-sig.unverifiable.lsv-denies"></a>

<a id="trm-3-6-3-2"></a>

### The boot-time probe <a id="cite-sig.boot-probe"></a>

A `late_initcall` allocates the transform once and, if it cannot,
emits `pr_err` and a `kacs.signature.crypto.failed` KMES event
carrying `signature.crypto-stage` `boot-probe` and the error as
`outcome.errno`, negative. The condition is then visible at boot rather than
inferred from every process running without an integrity label.

It cannot refuse to start, and two things rule that out rather than one:

- At LSM init the algorithm is not yet registered, so `crypto_alloc_sig`
  returns `ENOENT` on every boot. A probe there would fire always.
- A non-zero return from an LSM's init function is only `WARN`'d
  (`security/lsm_init.c`, `lsm_init_single`). The hooks are never added,
  so "refuse to initialise" means running with no KACS at all — worse
  than the failure it would be preventing.

Enforcement therefore lives at exec, where refusing one exec is
recoverable in a way losing the integrity boundary is not.

The probe is not `IS_ENABLED(CONFIG_CRYPTO_MLDSA)`. That option is an
unconditional `select` under `SECURITY_PKM`, which is a `bool`, so a
config test would always pass and catch nothing. Only calling the
allocator sees the ordering failure.

<a id="trm-3-6-8"></a>

## Revocation <a id="cite-sig.no-revocation"></a>

There is none. A signed binary later found to be malicious cannot be
invalidated short of removing it from the filesystem or replacing the
kernel image with a different key. No hash blocklist, no per-key
revocation, and no revocation state of any kind exists.

## Related explanations

- [Exec and library integrity](</kernel/internals/kacs/executable-trust/exec-and-library-integrity.md>)
- [Firmware verification](</kernel/internals/kacs/executable-trust/firmware-verification.md>)

---

# Exec and library integrity

_Peios Kernel / Internals / KACS / Executable trust_

> Exec and library integrity: behaviour and implementation of the Peios kernel.

<a id="trm-3-6-4"></a>

## PIP determination at exec

At `execve()` the kernel looks up and verifies the signature as above.
A verified binary takes `pip_type` and `pip_trust` from the matched
key; no signature, an invalid or unstable one, a bad signature, or no
matching key all yield None/0. <a id="cite-sig.exec.tier-from-matched-key"></a>

**Exec proceeds in every case where the question could be answered.** <a id="cite-sig.exec.proceeds-regardless"></a>
PIP is additive protection, not an execution gate: it determines trust
level, not permission to run. The one exception is a signature that
could not be verified at all, described above, which refuses the exec —
because there the question was not answered, so there is no basis on
which to assign a trust level. An
attacker who replaces a signed binary's signature with garbage costs
it PIP protection but can still execute it, subject to FACS. The
asymmetry with LSV — which *does* block unsigned libraries — is
intentional. Exec is permissive; `mmap(PROT_EXEC)` is restrictive.

Determination is transactional with exec success, in three phases. The
pending value is cleared at the top of every `bprm_creds_from_file`
invocation, staged into the task's security blob, and committed to the
process state only from `bprm_committed_creds`. <a id="cite-sig.exec.stage-then-commit"></a> An exec that fails
between staging and commit leaves the process state untouched, and the
stale pending value is cleared by the next exec or at task teardown. <a id="cite-sig.exec.failed-exec-leaves-state"></a>

Because the hook fires once per binfmt iteration and each iteration
re-stages, a `#!` script's PIP comes from the **interpreter** — the
last file processed — not from the script. <a id="cite-sig.exec.shebang-takes-interpreter"></a> A TCB-signed interpreter
runs at TCB level whatever script it executes. Symlinks need no
special handling either: the LSM hooks receive the already-resolved
target file, so a symlink inherits its target's level by construction. <a id="cite-sig.exec.symlink-resolves-to-target"></a>

Once committed, the values are fixed for the lifetime of the process
image, inherited at fork, and re-derived at the child's exec. <a id="cite-sig.exec.fixed-and-inherited"></a>

<a id="trm-3-6-5"></a>

## Content pinning

A binary that verifies to a nonzero tier has its backing inode pinned
as KACS-verified executable content before the exec result is
committed, and LSV pins on success too, before allowing the mapping. <a id="cite-sig.pin.on-verified-exec-and-lsv"></a>
Pinning closes the gap between verifying one byte image and modifying
the same inode afterwards.

If pinning fails at exec, the PIP result is **downgraded to None/0**
rather than the exec being failed or the tier being kept — the process
runs unprotected. <a id="cite-sig.pin.failure-downgrades-to-none"></a> Under LSV a pin failure denies the mapping instead. <a id="cite-sig.pin.failure-denies-lsv-mapping"></a>

A pinned inode rejects in-place content mutation even when the size
would be preserved: ordinary, positioned and append writes;
`ftruncate()` and pathname `truncate()`; and every `fallocate` mode,
including allocation-only ones, because the pin check runs before and
independently of the mode-support test. <a id="cite-sig.pin.rejects-content-mutation"></a> File ioctls that mutate
content, ranges, or allocation are rejected, and so are ioctls the
kernel cannot classify — unknown ioctls fail closed on a pinned inode. <a id="cite-sig.pin.unknown-ioctl-fails-closed"></a>
Mutation or removal of the `security.peios.sig` xattr is rejected as
well. <a id="cite-sig.pin.rejects-sig-xattr-mutation"></a>

The pin is conservative and one-way. It is set once and cleared only
when the inode is allocated or freed, never while the inode is live. <a id="cite-sig.pin.cleared-only-at-inode-lifecycle"></a>
Updating verified executable content therefore means replacing the
inode — write a new file and `rename()` over it — rather than
modifying it in place.

Unsigned, invalid, unstable, bad-signature and no-match attempts never
pin. <a id="cite-sig.pin.only-on-verified"></a>

<a id="trm-3-6-6"></a>

## Library Signature Verification

With the `lsv` mitigation enabled, `mmap()` with `PROT_EXEC` on a
file-backed mapping verifies the backing file. An unsigned file, an
invalid or unstable one, a bad signature, or no matching key all deny
the mapping with `EACCES`. <a id="cite-sig.lsv.denies-unsigned-eacces"></a> On success the library's tier is compared
against the loading process's: the image has to dominate the process,
so a Protected/PeiosTcb process can load only PeiosTcb-or-above
libraries. <a id="cite-sig.lsv.image-must-dominate-process"></a> With one key in the table this reduces to "is it signed
with the TCB key?"

The hash covers the **entire file**, not the mapped region — the whole
file is read and hashed even when only part of it is being mapped, so
the signature covers code in sections this particular mapping does not
touch. <a id="cite-sig.lsv.hashes-whole-file"></a>

`mprotect()` adding `PROT_EXEC` to a mapping that was not already
executable runs the same checks in a fixed order: WXP, then TLP, then
LSV. <a id="cite-sig.lsv.mprotect-check-order"></a> Anonymous mappings have neither a path nor a signature, so TLP
and LSV skip them and only WXP applies. <a id="cite-sig.lsv.anonymous-skips-tlp-lsv"></a>

Enabling `lsv` on a running process also re-validates its existing
executable mappings before the bit is committed ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)), so the
mitigation cannot be turned on over already-mapped unsigned code.

<a id="trm-3-6-9"></a>

## Interaction with other mechanisms

**WXP** is orthogonal: it prevents pages being writable and executable
at once, while LSV prevents unsigned executable pages. A process with
both can execute only signed code in read-only pages.

**FACS** runs independently. A signed binary in a directory the caller
cannot reach is still unreachable — the open is denied before signing
is consulted. <a id="cite-sig.facs.open-denied-before-signing"></a> Signing determines the PIP level of a binary that is
already being executed; it never grants access to one.

**PIP object protection** consumes the result: once a process carries
a tier from its binary's signature, trust labels on objects are
enforced through the AccessCheck pipeline against the `pip_type` and
`pip_trust` held in the PSB ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

---

# Firmware verification

_Peios Kernel / Internals / KACS / Executable trust_

> Firmware verification: behaviour and implementation of the Peios kernel.

<a id="trm-3-6-7"></a>

## Firmware verification

A firmware load is not an exec, so none of the above would see it —
and firmware is code that runs on a device with DMA into host memory,
which makes a tampered blob a complete compromise. KACS therefore
implements the `kernel_read_file` and `kernel_post_read_file` LSM
hooks for `READING_FIRMWARE` (`security/pkm/kacs/firmware.c`).

The signature is the ordinary PIP blob, found by the lookup above.
Firmware is never ELF, so in practice it is the `security.peios.sig`
xattr, which `peipkg` stamps at install from the `<file>.peios.sig`
sidecar the package carries ([PSPU payload entries](https://learn.peios.org/specifications/pspu/package-format-and-repository-protocol/payload-entries)). The bar is the **PeiosTcb**
tier — the same floor a usermodehelper exec must clear, since both are
the kernel choosing to run code it did not ship. A verified signature
at any other tier counts as no signature. <a id="cite-sig.firmware.peiostcb-floor"></a>

For a whole-file read, which is the common case, the post-read hook is
handed the exact bytes the loader will decompress and give to the
device, and those are what is hashed — no second read, no TOCTOU. <a id="cite-sig.firmware.post-read-hashes-loaded-bytes"></a> A
partial read (a driver pulling a window out of a large blob) only
passes through the pre-read hook, where nothing has been read yet, so
that path verifies the file through the reader probe instead. <a id="cite-sig.firmware.partial-read-uses-probe"></a> The
hash covers the compressed bytes as they sit on disk, so verification
precedes decompression. <a id="cite-sig.firmware.hashes-compressed-bytes"></a>

Policy is `CONFIG_SECURITY_PKM_FIRMWARE_SIG_ENFORCE`, overridable for
one boot with `kacs_fwsig=enforce` or `kacs_fwsig=log` on the kernel
command line; there is no runtime switch. <a id="cite-sig.firmware.cmdline-override"></a> Under `enforce` an unsigned,
tampered or under-tier file is refused with `-EPERM`; the loader logs
that against the path it was refused at, moves on to its remaining
search paths, and reports the driver an ordinary load failure. <a id="cite-sig.firmware.enforce-eperm"></a> Under `log` the
verdict goes to a rate-limited warning and the `kacs:kacs_firmware_load`
tracepoint and the load proceeds. <a id="cite-sig.firmware.log-mode"></a> **2026.8 ships in log mode**: the
firmware set is being signed for the first time, and a blob the
packaging missed has to show up as a warning rather than as a device
that silently stops probing. <a id="cite-sig.firmware.default-is-log"></a> Enforcement becomes the default once a
release has run clean.

`CONFIG_FW_UPLOAD` — a device's own sysfs update interface — is not
covered; it is `select`ed by several drivers and cannot be turned off,
and the drivers that expose it are the place to gate it if that ever
matters. The `test.fwsig` build stage exercises both modes through
`CONFIG_TEST_FIRMWARE`'s `trigger_request`, which pulls a named file
through the real loader path with no hardware.

---

# Process integrity protection

_Peios Kernel / Internals / KACS / Executable trust_

> PIP protects objects through trust label ACEs and processes through a dominance test — where it is enforced, and the limits of what it can do.

<a id="trm-3-7"></a>

PIP protects **objects** from insufficiently trusted processes through
trust label ACEs evaluated inside AccessCheck ([PIP in AccessCheck](</kernel/internals/kacs/access-check/pip-in-accesscheck.md#trm-3-8-7>)). It also
protects **processes** — their memory, their execution, their metadata
— from other processes, which is what this section covers.

Every process-to-process operation passes two independent checks, and
both have to succeed. <a id="cite-pip.two-checks-both-required"></a>

The **process descriptor check** is an ordinary AccessCheck of the
caller's token against the target's process descriptor ([Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>)). It
answers *who* may operate on the process, and it is where per-operation
granularity lives — different rights for signals, memory, and
metadata.

The **PIP dominance check** is a direct comparison of the two
processes' PSB fields. It answers *what trust level is required*. It
does not use AccessCheck, does not read a descriptor, and does not
involve the DACL pipeline at all: it is a standalone arithmetic test. <a id="cite-pip.dominance-independent-of-descriptor"></a>

The two are complementary. Object PIP protection stops a non-dominant
process opening authd's private key file; process PIP protection stops
the same process reading the key straight out of authd's memory with
ptrace, or killing authd with a signal.

<a id="trm-3-7-1"></a>

## The dominance test <a id="cite-pip.dominance-both-axes"></a>

```
pip_dominates(caller_psb, target_psb) -> bool:
    if target_psb.pip_type == None:
        return true   // Unprotected target — any caller dominates.
    return caller_psb.pip_type  >= target_psb.pip_type
       AND caller_psb.pip_trust >= target_psb.pip_trust
```

Both axes are plain unsigned integers compared numerically, not closed
enumerations — the dominance layer would happily order tiers the
signing layer cannot currently produce ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). The early return for
an unprotected target is what keeps ordinary processes universally
accessible whatever trust values a caller happens to carry. <a id="cite-pip.unprotected-target-always-dominated"></a>

Dominance is binary. A caller that does not dominate has no process
access at all, whichever operation was attempted; the descriptor
provides the granularity and PIP is the all-or-nothing gate above it. <a id="cite-pip.dominance-is-all-or-nothing"></a>

That asymmetry with the object model is deliberate. Object access has
natural categories — read, write, execute. Process access does not: a
caller that can ptrace a process can read its memory, inject code, and
effectively become it. Partial process access is not a meaningful
boundary.

<a id="trm-3-7-2"></a>

## SeDebugPrivilege <a id="cite-pip.sedebug-bypasses-descriptor-only"></a>

`SeDebugPrivilege` bypasses the descriptor check and never the
dominance check. This holds at every enforcement point, and it is
enforced structurally in two independent places: inside the descriptor
evaluation a PIP-label denial short-circuits *before* the debug
rescue is reached, and the standalone dominance test runs afterwards
with no privilege escape of any kind.

<a id="trm-3-7-3"></a>

## Where dominance is enforced

**ptrace**, in every mode. A single successful attach is equivalent to
full compromise of the target — read and write memory and registers,
single-step, inject signals, redirect execution — so a non-dominant
caller is refused whatever the mode. <a id="cite-pip.ptrace.all-modes"></a> The Linux `__ptrace_may_access`
path is patched to return the LSM's answer directly, so native UID and
capability rules no longer grant where KACS denies. <a id="cite-pip.ptrace.lsm-answer-final"></a> Direct memory
access through `/proc/<pid>/mem`, `process_vm_readv` and
`process_vm_writev` routes through the same check, so one hook covers
every memory-access vector. <a id="cite-pip.ptrace.covers-memory-vectors"></a> This is what makes in-memory secrets
genuinely unreachable: a compromised administrator cannot read an
HSM daemon's key material out of its address space.

`PTRACE_TRACEME` inverts the roles — the nominated tracer is the
subject and the caller is the target — and requires `PROCESS_VM_WRITE`
on the caller's own descriptor plus dominance by the nominated tracer. <a id="cite-pip.ptrace.traceme-inverted"></a>

Mode combinations are validated: the mutually exclusive
`PIDFD_OPEN`, `GETFD` and `PROC_QUERY` flags cannot be combined, and a
request that is neither a read nor an attach, or claims to be both, is
rejected as malformed. <a id="cite-pip.ptrace.mode-combinations-rejected"></a>

**Signal delivery**, uniformly regardless of signal type. <a id="cite-pip.signal.uniform-all-types"></a> Lifecycle
management of PIP-protected processes therefore has to go through a
process that dominates them — in practice peinit, which runs at the
highest tier.

Signalling within the same process security state is not a boundary
operation, and the exemption is **structural**: it is a pointer
comparison of the two processes' security state, tested before any
descriptor or dominance evaluation. <a id="cite-pip.signal.same-security-state-exempt"></a> It does not depend on the default
descriptor's self ACE, which is what makes `raise()`, `abort()` and
`pthread_kill()` work for restricted and confined tokens whose
AccessCheck against their own descriptor would fail. <a id="cite-pip.signal.self-signals-work-for-restricted"></a>

Multi-target sends are evaluated per target by Linux's own iteration,
so the signal reaches the permitted subset and the call succeeds if at
least one delivery happened. <a id="cite-pip.signal.multi-target-partial-success"></a> POSIX's same-session `SIGCONT` exception
is deliberately absent — the patched `check_kill_permission` returns
the KACS answer before reaching the switch that carried it — so
`SIGCONT` needs `PROCESS_SUSPEND_RESUME` plus dominance like every
other job-control signal, whatever the session. <a id="cite-pip.signal.sigcont-no-session-exception"></a>

Kernel-originated signals bypass the whole check, as described in
[Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>).

**`pidfd_open()`**, a boundary information query rather than a memory
or attach operation, needs `PROCESS_QUERY_LIMITED` plus dominance. <a id="cite-pip.pidfd-open.query-limited"></a>
**`pidfd_getfd()`** maps to `PROCESS_DUP_HANDLE` plus dominance —
extracting a descriptor from another process is a boundary crossing in
its own right. <a id="cite-pip.pidfd-getfd.dup-handle"></a>

**`/proc` metadata.** Entries that are already ptrace-gated or
memory-open-gated are covered automatically by the ptrace hook. The
rest would leak information about a protected process, so the
non-ptrace-gated entries carry their own descriptor requirement plus
dominance; [Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>) gives the mapping. <a id="cite-pip.proc.metadata-needs-descriptor-and-dominance"></a> The one exception is
`/proc/<pid>/psb`, which needs `PROCESS_QUERY_LIMITED` and no
dominance: a protected process's PIP type, trust and mitigations are
readable to whoever its descriptor lets query it ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)). <a id="cite-pip.proc.psb-exempt-from-dominance"></a> Entries stricter than a metadata
query, such as `/proc/<pid>/stack`, keep their native hardening and
are not brought under the metadata rule. <a id="cite-pip.proc.stricter-entries-keep-native"></a>

Denying access prevents reading inside `/proc/<pid>/` but does not
hide the PID: the directory name is still visible through `getdents`. <a id="cite-pip.proc.pid-visible-not-hidden"></a>
Visible-but-inaccessible is the accepted position.

`/proc` is not FACS-managed — it is a virtual filesystem with no
backing store and no xattrs — so enforcement there happens through
direct kernel checks rather than an object-backed FACS path.

**Capability metadata.** `capget()` on the current process, or on a
thread sharing its security state, is not a boundary operation. <a id="cite-pip.capget.self-and-sibling-exempt"></a>
Against another process it is a detailed information query needing
`PROCESS_QUERY_INFORMATION` plus dominance. <a id="cite-pip.capget.cross-process-query-information"></a>

**Resource limits, scheduler and placement.** Read-only `prlimit`
needs `PROCESS_QUERY_INFORMATION` plus dominance; a limit change needs
`PROCESS_SET_INFORMATION` plus dominance. <a id="cite-pip.prlimit.read-and-change"></a>

- `setpgid()` needs `PROCESS_SET_INFORMATION`; <a id="cite-pip.setpgid.set-information"></a>
- `getpgid()` and `getsid()` need `PROCESS_QUERY_LIMITED`; <a id="cite-pip.getpgid-getsid.query-limited"></a>
- the scheduler, affinity and I/O priority queries need
  `PROCESS_QUERY_INFORMATION`; <a id="cite-pip.sched-queries.query-information"></a>
- and the memory-placement mutations Linux routes through
  `task_movememory` need `PROCESS_SET_INFORMATION`. <a id="cite-pip.movememory.set-information"></a>

Setting nice, scheduler parameters and I/O priority all need
`PROCESS_SET_INFORMATION` too. <a id="cite-pip.sched-set.set-information"></a> Self-directed
versions of all of these are not boundary operations and skip both
checks. <a id="cite-pip.self-directed-skips-checks"></a>

**CPU affinity** is per-thread, so changing the caller's own thread or
a sibling in the same process is not a boundary operation. <a id="cite-pip.affinity.same-process-not-boundary"></a> Changing a
thread in a *different* process needs `PROCESS_SET_INFORMATION` plus
dominance plus `SeIncreaseBasePriorityPrivilege` — and the privilege
is checked and marked used *before* the descriptor and dominance call,
so the `SeDebugPrivilege` rescue cannot substitute for it. <a id="cite-pip.affinity.cross-process-privilege-first"></a> KACS does
not relax the kernel's native affinity validity rules: an invalid or
disallowed mask still fails. <a id="cite-pip.affinity.native-validity-preserved"></a>

**Token opens.** `kacs_open_process_token` and
`kacs_open_thread_token` need `PROCESS_QUERY_INFORMATION` plus
dominance. <a id="cite-pip.token-open.query-information"></a> Reading a process's security identity is as sensitive as
reading its memory.

**Performance monitoring.** Target-specific `perf_event_open()` on
another process can leak execution timing, branch prediction
behaviour, cache access patterns and instruction traces — side
channels that reveal cryptographic keys. It needs
`SeProfileSingleProcessPrivilege` plus `PROCESS_QUERY_INFORMATION`
plus dominance, with the privilege again checked first so the debug
rescue cannot stand in for it. <a id="cite-pip.perf.target-specific-requirements"></a> Own-task profiling is not a boundary
operation and needs no privilege. <a id="cite-pip.perf.own-task-exempt"></a> System-wide profiling, `pid == -1`,
samples every task on a CPU including protected ones, so it needs the
operator-class `SeSystemProfilePrivilege`. <a id="cite-pip.perf.system-wide-privilege"></a> Cgroup perf mode stays
under Linux's native model. <a id="cite-pip.perf.cgroup-native"></a> Because the target task is resolved after
the stock `security_perf_event_open` hook fires, this rule is enforced
through a target-resolved syscall patch rather than that hook — there
is no `security_perf_event_open` registration at all.

<a id="trm-3-7-4"></a>

## The PeiosTcb floor on kernel-initiated execs

One place PIP gates execution rather than merely labelling it. It is
not a dominance test — there is no caller to compare against — but a
threshold: a binary the kernel execs *on its own behalf* must carry at
least PeiosTcb trust, or the exec fails with `EACCES`. <a id="cite-pip.umh.peiostcb-floor"></a>

The case that motivates it is `request_module()`. When the kernel needs
a module it does not have — `get_fs_type()` on a mount, `socket()` for
an unknown protocol family, the crypto API resolving a name — it spawns
`CONFIG_MODPROBE_PATH` as a usermode helper and runs it at the kernel's
own authority. That path is a writable sysctl, which makes redirecting
`/proc/sys/kernel/modprobe` a classic escalation: point it somewhere
attacker-controlled and the next module request executes it with the
kernel behind it. The floor makes the redirection worthless on its own,
because the attacker would also have to produce a TCB-signed binary.

This is the only exec KACS refuses on integrity grounds. Everywhere
else an unsigned binary runs and simply carries no tier, because a
requesting process's own authority bounds what it can do. A
kernel-initiated exec has no such process behind it, so there is no
lesser authority to fall back to.

The floor also refuses when no tier could be derived at all, not only
when one was derived and graded too low. <a id="cite-pip.umh.refuses-underivable-tier"></a> Treating "could not establish
trust" differently from "is not trusted" would leave the check
bypassable by whatever prevented the derivation from running.

Nothing upstream identifies such an exec by the time the LSM sees it.
The helper child is created by `user_mode_thread()`, so it never
carries `PF_KTHREAD` — `kernel_execve()` rejects kernel threads
outright — and `security_kernel_module_request()` fires in the
*requesting* task, before the child exists. So `kernel/umh.c` is
patched to mark the child after `commit_creds()` and before
`kernel_execve()`, and the mark is read in the `bprm_creds_from_file`
hook. It lives in the KACS task blob rather than costing a
`task_struct` flag.

The mark is never cleared. A helper that re-execs — an interpreter for
a `#!` helper — stays under the floor rather than escaping it on the
second exec; the task exists only to be that helper. <a id="cite-pip.umh.mark-never-cleared"></a>

A refusal emits `kacs_exec` with reason `umh-not-tcb`, so it is
visible rather than presenting as an unexplained module-load failure. <a id="cite-pip.umh.audit-reason"></a>

<a id="trm-3-7-5"></a>

## Trust raising under a tracer or supervisor

Dominance is tested when a tracer attaches and when a seccomp filter is
installed, and not again. <a id="cite-pip.unsafe.dominance-tested-at-attach-only"></a> That leaves one way to end up controlling a
process one does not dominate: be attached to it, or supervising its
syscalls through seccomp user notification, when it execs a binary
whose signature would raise its label. Linux marks exactly these execs
— `LSM_UNSAFE_PTRACE` when the task is traced, `LSM_UNSAFE_NO_NEW_PRIVS`
under `no_new_privs`, which every unprivileged seccomp filter requires
— and uses them to withhold setuid gains. KACS applies the same rule to
the label: the exec goes ahead, but the staged label is **capped at
the process's current one** whenever the new label would not be
dominated by it. <a id="cite-pip.unsafe.label-capped"></a> The binary runs with the protection it can be given,
as a setuid binary runs without its setuid under `strace`.

There is no privilege exception. `SeDebugPrivilege` never bypasses
dominance, and a TCB tracer already dominates every label, so nothing
is lost by capping. An exec that does not raise the label — the common
case, and every unsigned binary — is untouched. <a id="cite-pip.unsafe.non-raising-exec-untouched"></a> A cap emits
`kacs_exec` with reason `pip-capped-unsafe` carrying the label that
was kept. <a id="cite-pip.unsafe.audit-reason"></a>

<a id="trm-3-7-6"></a>

## Raw physical memory

A process able to read `/dev/mem` could map any process's physical
pages and bypass virtual memory protections entirely, PIP included.

The defence is `CONFIG_STRICT_DEVMEM`, which restricts `/dev/mem` to
I/O regions and denies RAM access. It is not merely a recommended
build option: the LSM **refuses to initialise** unless both
`CONFIG_STRICT_DEVMEM` and `CONFIG_MODULE_SIG_FORCE` are enabled, so a
kernel configured without them does not boot with KACS at all. <a id="cite-pip.devmem.required-configs"></a> The
same initialisation gate refuses to coexist with SELinux, AppArmor,
Smack, TOMOYO or the BPF LSM. <a id="cite-pip.init.refuses-other-lsms"></a>

Placing a restrictive descriptor on `/dev/mem` and `/dev/kmem` as a
secondary defence is not implemented; nothing in the kernel handles
those paths specially. <a id="cite-pip.devmem.no-descriptor-protection"></a>

<a id="trm-3-7-7"></a>

## Limits of the guarantee

PIP operates inside the kernel's trust boundary, and three things sit
outside it.

**Kernel compromise.** A loaded module runs with unrestricted access
to all memory and kernel structures. PIP is enforced by the kernel, so
a compromised kernel voids it, and `SeLoadDriverPrivilege` is the
ceiling of every guarantee here. `CONFIG_MODULE_SIG_FORCE` is
hard-required as noted above, and module signing is itself ML-DSA-65.
Stripping `SeLoadDriverPrivilege` from every token but peinit's and the
device manager's is the other half of that defence, and is policy
rather than kernel behaviour — nothing in the kernel strips it. The
device manager holds it because loading drivers for the hardware that
appears is its job; module signature enforcement is what keeps the
privilege from meaning more than "load a module Peios built".

**Hardware access.** DMA-capable devices read and write physical
memory directly, bypassing the CPU's virtual memory system. An IOMMU
mitigates this, and configuring one is a kernel responsibility outside
KACS.

**Hypervisor-level isolation.** PIP does not offer guarantees
equivalent to hypervisor-based memory isolation. The threat model
ceiling is a non-compromised kernel.

<a id="trm-3-7-8"></a>

## Impersonation

PIP reads the PSB, never the effective token. A Protected service
impersonating a client still evaluates its own PSB for every process
boundary check, so the client's identity has no bearing on it. <a id="cite-pip.impersonation.reads-psb-not-token"></a> In the
other direction, an unprotected process impersonating a token created
for a protected one gains nothing — its PSB is still None. Since
nothing constrains the PIP dimensions the way the integrity ceiling
constrains impersonation ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)), the PSB is the only safe source.

<a id="trm-3-7-9"></a>

## Coredumps

A crashing PIP-protected process is a potential secret leak, so its
dumps must not be readable by non-dominant processes.

The implemented strategy is to disable them: a process with a nonzero
`pip_type` has its dumpable flag cleared at exec, and
`prctl(PR_SET_DUMPABLE, 1)` is refused for as long as the process
remains protected. <a id="cite-pip.coredump.disabled-for-protected"></a> Requests that keep or make it non-dumpable are
allowed, and no alternative dumpable-setting path is left ungated. <a id="cite-pip.coredump.non-dumpable-requests-allowed"></a> If
a later exec assigns None/0, normal Linux exec-time dumpability rules
apply to the new image. <a id="cite-pip.coredump.unprotected-exec-restores-rules"></a>

The alternative — a signed, high-trust crash handler receiving dump
data from the kernel and writing it under a restrictive descriptor, so
that diagnostics survive without bypassing isolation — is not
implemented. <a id="cite-pip.coredump.no-crash-handler"></a> The two are not mutually exclusive; disabling dumps is
the minimum viable position.

---

# Access check

_Peios Kernel / Internals / KACS / Access check_

> Find the Peios kernel articles about access check.

Use these articles to understand access check in the Peios kernel.

- [AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md>)
- [The DACL Walk](</kernel/internals/kacs/access-check/the-dacl-walk.md>)
- [Mandatory Integrity Control](</kernel/internals/kacs/access-check/mandatory-integrity-control.md>)
- [Restricted Tokens](</kernel/internals/kacs/access-check/restricted-tokens.md>)
- [Object ACEs and Property-Level Access](</kernel/internals/kacs/access-check/object-aces-and-property-level-access.md>)
- [Application Confinement](</kernel/internals/kacs/access-check/application-confinement.md>)
- [PIP in AccessCheck](</kernel/internals/kacs/access-check/pip-in-accesscheck.md>)
- [Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md>)
- [Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md>)
- [The Algorithm](</kernel/internals/kacs/access-check/the-algorithm.md>)

---

# AccessCheck Overview

_Peios Kernel / Internals / KACS / Access check_

> The function that connects tokens to descriptors — its two API variants, and the three state values a right can hold during evaluation.

<a id="trm-3-8-1"></a>

AccessCheck is the function that connects tokens to security
descriptors. Given a token — who is asking — a descriptor — what the
rules are — and a desired access mask — what they want to do — it
returns a verdict: which of the requested rights are granted, and
whether the request as a whole succeeds.

It is a pipeline, evaluating several layers of policy in a fixed
order. Each layer can grant or constrain access and the layers
interact: integrity policy can block what the DACL would allow,
privileges can override what the DACL denied, and confinement can
revoke what privileges granted. The order is not incidental — it is
the specification.

<a id="trm-3-8-1-1"></a>

## Two API variants

**AccessCheck** is the common case. It returns the granted access
mask, whether the request succeeded, a continuous audit mask derived
from SACL alarm ACEs, and a CAAP staging mismatch flag. <a id="cite-check.accesscheck.returns"></a> When an object
type list is supplied, success requires every listed node to pass and
the returned mask is the intersection across them. The staging
mismatch flag is set when the staged scalar result differs from the
effective scalar result, when any per-node staged grant differs from
the effective per-node grant, or when staged auditing differs from
effective auditing. <a id="cite-check.staging-flag.accesscheck"></a>

**AccessCheckResultList** is the per-property variant and requires an
object type list. <a id="cite-check.result-list.requires-tree"></a> It returns a separate verdict for each node, so a
denial on one property fails that property alone rather than the whole
request. <a id="cite-check.result-list.returns"></a> It returns the same continuous audit mask and staging
mismatch flag, with the flag set when the staged scalar result differs
from the effective one, when any node's staged granted mask differs
from that node's effective granted mask, or when staged auditing
differs from effective auditing — the scalar comparison is not
mode-branched. <a id="cite-check.staging-flag.result-list"></a> Directory services use it,
because one operation there may touch several properties with
independent access rules. Privilege-use auditing in this variant takes
the same per-node view: a privilege counts as successfully used if its
contributed bits survive on *any* node's final granted mask.

Both variants share one evaluation pipeline. Only the collection of
results differs.

## A supplied subject without a token

The separate `kacs_access_check_subject` query evaluates caller-supplied SID,
group and typed-claim facts without creating, adopting or impersonating a
token. It reuses the DACL, conditional and object-ACE evaluators. Omitted
facts stay unknown; known-empty collections and explicit claim absences
are distinct. No access fact is inherited from the caller. Explicit integrity,
trust, scoped-policy and privilege requirements return missing execution
context rather than acquiring the caller's authority.

Syscall 1028 accepts a versioned request buffer and writes a granted, denied
or missing-context result. Missing context carries no provisional grant.
The kernel copies and validates one bounded buffer; internal offsets replace
nested userspace pointers. The UAPI access header specifies layout and limits.
Malformed or excessive inputs fail the entire query without truncating facts.

Matching SACL audit ACEs require enabled `SeAuditPrivilege` on the actual
caller. `KACS_SUBJECT_NO_AUDIT` suppresses this query's records; it does not bypass mandatory
SACL labels. Audit-only missing facts matter only while auditing is active.
Records use `kacs.audit.subject.checked`: `subject` is the real caller and
`source.supplied-subject.sid` is a hypothetical assertion. An optional generic `AuditContext`
labels the guarded object without influencing policy. Detected audit
preparation or submission errors fail the query. Records are submitted before
result writeback, so a bad output pointer cannot silence requested auditing.

<a id="trm-3-8-1-2"></a>

## The three state values

Every access check tracks three masks.

**`decided`** records which bits have been resolved. It enforces
first-writer-wins within the DACL walk: once a bit is decided, no
later ACE in the same walk changes its outcome. Pipeline layers that
operate on top of the DACL result — restricted token intersection,
confinement intersection, PIP revocation, CAAP intersection — may
still revoke granted bits. Those layers narrow the result; they do not
re-open decided bits for re-evaluation through the DACL. <a id="cite-check.state.narrow-not-reopen"></a>

**`granted`** records which bits resolved to yes. During the walk it
is a subset of `decided`. Afterwards the later layers may remove bits
from it, and the final value is what the caller receives.

**`privilege_granted`** records which bits in `granted` came from a
privilege rather than from the DACL. It exists for two reasons: audit
accuracy, so that privilege-granted access is distinguishable from
DACL-granted access, and the restricted token merge, where
privilege-granted bits are restored after the intersection so that
privileges bypass the restricted pass. PIP may revoke
privilege-granted bits.

With an object type list present, each node carries its own `decided`
and `granted` pair.

---

# The DACL Walk

_Peios Kernel / Internals / KACS / Access check_

> Walking the ACEs in order under first-writer-wins — SID matching, absent and empty DACLs, owner implicit rights and MAXIMUM_ALLOWED.

<a id="trm-3-8-2"></a>

The DACL is an ordered list of ACEs, walked from first to last,
comparing each ACE's SID against the calling token's identity. The
governing principle is **first-writer-wins**: once a bit has been
resolved, granted or denied, no later ACE changes the outcome for that
bit. <a id="cite-check.dacl.first-writer-wins"></a>

An **allow** ACE whose SID matches the token grants the rights it
carries that have not yet been decided, leaving already-decided bits
untouched. <a id="cite-check.dacl.allow-grants-undecided"></a> A **deny** ACE whose SID matches denies its
not-yet-decided rights — marking them decided but not granted — and
likewise leaves decided bits alone. <a id="cite-check.dacl.deny-marks-decided"></a>

<a id="trm-3-8-2-1"></a>

## SID matching

An ACE's SID matches the token when it equals the user SID or a group
SID on the token, subject to attribute filtering.

For **allow** ACEs, only groups that are enabled and not deny-only
match. <a id="cite-check.dacl.allow-enabled-groups-only"></a> For **deny** ACEs, both enabled groups and deny-only groups
match: a deny-only group always participates in deny matching whatever
its enabled state. <a id="cite-check.dacl.deny-matches-deny-only"></a> A group with neither `SE_GROUP_ENABLED` nor
`SE_GROUP_USE_FOR_DENY_ONLY` participates in no matching at all. <a id="cite-check.dacl.inert-group"></a>

The user SID follows the same rule — when `user_deny_only` is set on
the token, it matches deny ACEs and not allow ACEs. <a id="cite-check.dacl.user-deny-only"></a>

<a id="trm-3-8-2-2"></a>

## Skipping and mapping

ACEs carrying `INHERIT_ONLY` exist purely to propagate to child
objects and are skipped by the walk. <a id="cite-check.dacl.inherit-only-skipped"></a>

At the top of the walk each ACE's access mask is mapped through
`MapGenericBits` using the same GenericMapping applied to the caller's
request. <a id="cite-check.dacl.ace-mask-mapped"></a> The mapping works on a local copy — the ACE itself is never
mutated. Mapping ACE masks at evaluation time is a deliberate
departure from MS-DTYP, and it is what makes `GENERIC_ALL` work in
central access policy recovery ACEs ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)).

Descriptors that KACS stores on its own objects reach the walk already
mapped. Every path that writes an object's descriptor — creation,
inheritance, the token's default DACL, and setting a descriptor on an
existing object — maps generic rights in the ACEs that apply to the
object, through that object type's GenericMapping. An ACE that applies
to the object and is also inherited is split, as at creation, into a
mapped ACE for the object and an inherit-only copy that keeps its
generic rights for the children it will reach. Inherit-only ACEs keep
theirs. <a id="cite-check.dacl.stored-descriptors-mapped"></a> A descriptor therefore reads back the same however it was
applied. The walk's own mapping remains for descriptors that never pass
through those paths, such as ones a caller hands to AccessCheck.

<a id="trm-3-8-2-3"></a>

## Absent and empty DACLs

If the descriptor has no DACL — `SE_DACL_PRESENT` unset — every valid
right not already decided by an earlier pipeline stage is granted. <a id="cite-check.dacl.absent-grants-valid-rights"></a> The
valid rights are bounded by `MapGenericBits(GENERIC_ALL, mapping)`
rather than by a raw `0xFFFFFFFF`. <a id="cite-check.dacl.absent-bounded-by-generic-all"></a>

If the DACL is present but holds zero ACEs, the walk grants nothing. <a id="cite-check.dacl.empty-grants-nothing"></a>
The only access an owner gets in that case comes from the implicit
rights mechanism below.

<a id="trm-3-8-2-4"></a>

## Owner implicit rights

By default the owner of an object receives `READ_CONTROL` and
`WRITE_DAC` whatever the DACL says. <a id="cite-check.dacl.owner-implicit-rights"></a> These are granted **before** the
walk begins, as the first action inside `EvaluateDACL`, and because
first-writer-wins governs the walk, no deny ACE encountered later can
override them. <a id="cite-check.dacl.owner-implicit-before-walk"></a>

`EvaluateDACL` takes a `skip_owner_implicit` parameter. The
confinement pass sets it, because confinement is an absolute
intersection with no owner bypass.

The grant is suppressed entirely if any non-inherit-only
access-control ACE in the DACL targets the `OWNER RIGHTS` SID
(`S-1-3-4`). <a id="cite-check.dacl.owner-rights-suppresses-implicit"></a> This is a pre-scan performed at the start of
`EvaluateDACL`, before the main loop, and it checks only for the SID's
presence — it does not evaluate any conditional expression on the ACE. <a id="cite-check.dacl.owner-rights-prescan-presence-only"></a>

During the walk proper, `S-1-3-4` is treated as an ordinary SID
matching the owner, at both allow and deny polarity. <a id="cite-check.dacl.owner-rights-ordinary-sid"></a> It obeys the same
rules as any other SID: an allow ACE matches only through an enabled,
non-deny-only group, and not through the user SID of a
`user_deny_only` token; a deny ACE matches through a group that is
enabled or deny-only, and through the user SID unconditionally.

Note that the *implicit* grant above is a separate rule and remains
presence-based. It is bounded by the pre-scan rather than by polarity.

The implicit grant is also bounded twice over: by the object type's
valid rights, and by what has already been decided. A pre-decision
from MIC, PIP or a privilege therefore suppresses it — a non-dominant
owner does not receive `WRITE_DAC` through this route. <a id="cite-check.dacl.owner-implicit-bounded-by-decided"></a>

<a id="trm-3-8-2-5"></a>

## MAXIMUM_ALLOWED

When the caller includes `MAXIMUM_ALLOWED` (bit 25), AccessCheck runs
the full pipeline and returns the complete set of rights that would be
granted. The bit is stripped from the desired mask before evaluation
begins. <a id="cite-check.dacl.max-allowed-stripped"></a>

Two things change. The walk runs to completion with no short-circuit,
and the returned mask is whatever the pipeline accumulated rather than
being filtered to the requested bits. <a id="cite-check.dacl.max-allowed-returns-accumulated"></a>

`MAXIMUM_ALLOWED` can be combined with specific rights:
`MAXIMUM_ALLOWED | READ_CONTROL` asks both "can I read the
descriptor?" as a success or failure and "what else could I get?" as a
mask. A pure `MAXIMUM_ALLOWED` request carrying no specific bits
always succeeds. <a id="cite-check.dacl.max-allowed-alone-succeeds"></a>

Otherwise — when the desired mask is fully decided — the walk may stop
early.

First-writer-wins applies to `MAXIMUM_ALLOWED` requests exactly as it
does to targeted ones. <a id="cite-check.dacl.max-allowed-first-writer-wins"></a> MS-DTYP treats the two differently; KACS does
not, which is what stops "what can I do?" and "can I do this?"
disagreeing on a DACL that is not in canonical order.

---

# Mandatory Integrity Control

_Peios Kernel / Internals / KACS / Access check_

> MIC restricts what the DACL is allowed to grant along a vertical trust hierarchy — the labels, the policy bits, and the algorithm.

<a id="trm-3-8-3"></a>

MIC is a mandatory constraint that restricts which rights the DACL is
allowed to grant, along a vertical trust hierarchy. It is evaluated
**before** the DACL walk, in the pre-SACL phase. <a id="cite-check.mic.before-dacl"></a>

Every token carries an integrity level, and every object may carry a
mandatory label — a `SYSTEM_MANDATORY_LABEL_ACE` in its SACL. MIC
compares the two: a caller below the object's level is blocked from
whole categories of access whatever the DACL says.

The default is **no-write-up**. A lower-integrity process can read and
execute a higher-integrity object but cannot write to it, and the
object's label may additionally block reads or execution for callers
beneath it. <a id="cite-check.mic.default-no-write-up"></a>

An object with no mandatory label ACE in its SACL — or no SACL at all
— is treated as Medium integrity with no-write-up, so Low and
Untrusted processes cannot write to unlabelled objects. <a id="cite-check.mic.unlabelled-is-medium"></a>

A caller whose level is greater than or equal to the object's label
**dominates** it, and MIC pre-decides nothing: the DACL handles
authorization normally. <a id="cite-check.mic.dominant-no-effect"></a>

<a id="trm-3-8-3-1"></a>

## What MIC does and does not touch

MIC constrains what the DACL can grant. It does not revoke what
privileges have already granted, because it mutates only `decided` and
never touches `granted` or `privilege_granted`. <a id="cite-check.mic.never-revokes-privileges"></a>

`ACCESS_SYSTEM_SECURITY` is outside its reach for a structural reason:
the bits MIC can decide are bounded by
`MapGenericBits(GENERIC_ALL, mapping)`, which does not include it. The
right is privilege-granted rather than DACL-granted, so MIC never
blocks it. <a id="cite-check.mic.access-system-security-untouched"></a> PIP is stricter and does revoke it for non-dominant callers
— explicitly ORing it into the set of bits it can take away — which is
the mechanism by which objects stay protected even from
administrators.

`SeRelabelPrivilege` has one specific interaction: it lets the DACL
grant `WRITE_OWNER` even when an integrity mismatch would otherwise
block it, so a privileged administrator can take ownership of a
higher-integrity object as the first step in modifying it. <a id="cite-check.mic.relabel-allows-write-owner"></a> The bit
granted this way is recorded under its own provenance and is
deliberately **not** part of `privilege_granted`, so it is not
restored after the restricted merge and is not preserved by the CAAP
error escape hatch. <a id="cite-check.mic.relabel-not-privilege-granted"></a>

Enforcement is gated on the token's `mandatory_policy`: with
`NO_WRITE_UP` set — the default — the rule applies, and with it clear
MIC is effectively disabled for that token. <a id="cite-check.mic.mandatory-policy-gate"></a> The field is fixed at
creation ([Token Structure](</kernel/internals/kacs/tokens/token-structure.md#trm-3-2-2>)), which is what makes MIC a boundary rather than a
suggestion.

<a id="trm-3-8-3-2"></a>

## Labels

An object's SACL may carry more than one mandatory label ACE. Only the
first non-inherit-only one is used; inherit-only labels do not apply
to the object carrying them. <a id="cite-check.mic.first-non-inherit-only-label"></a>

The SID in a mandatory label ACE has the Mandatory Label authority
(`S-1-16`) and exactly one sub-authority, and that sub-authority value
*is* the integrity level, compared as an unsigned integer. <a id="cite-check.mic.label-sid-shape"></a> Any
`S-1-16-X` is therefore valid.

| SID | Level | Name |
|---|---:|---|
| `S-1-16-0` | 0 | Untrusted |
| `S-1-16-4096` | 4096 | Low |
| `S-1-16-8192` | 8192 | Medium |
| `S-1-16-12288` | 12288 | High |
| `S-1-16-16384` | 16384 | System |

Peios tooling and authd use these five, but intermediate values such
as `S-1-16-2048` or `S-1-16-8448` are valid and compared numerically,
which is what allows Windows-originated descriptors carrying
non-standard levels to be evaluated without translation. <a id="cite-check.mic.nonstandard-levels-accepted"></a>

A label ACE whose SID falls outside the `S-1-16` authority — wrong
identifier authority, or the wrong sub-authority count — is
malformed, and so is one that is not a plain single-SID ACE. Either
causes AccessCheck to reject the whole descriptor with an error rather
than ignore the label. <a id="cite-check.mic.malformed-label-rejects-descriptor"></a>

<a id="trm-3-8-3-3"></a>

## Policy bits

| Bit | Value | Meaning |
|---|---|---|
| `SYSTEM_MANDATORY_LABEL_NO_READ_UP` | 0x00000001 | Non-dominant callers receive no read-mapped rights from the DACL. <a id="cite-check.mic.policy.no-read-up"></a> |
| `SYSTEM_MANDATORY_LABEL_NO_WRITE_UP` | 0x00000002 | Non-dominant callers receive no write-mapped rights from the DACL. <a id="cite-check.mic.policy.no-write-up"></a> |
| `SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP` | 0x00000004 | Non-dominant callers receive no execute-mapped rights from the DACL. <a id="cite-check.mic.policy.no-execute-up"></a> |

Unknown bits in a label mask are ignored. <a id="cite-check.mic.unknown-policy-bits-ignored"></a>

<a id="trm-3-8-3-4"></a>

## The algorithm <a id="cite-check.mic.algorithm"></a>

```
EnforceMIC(ace, token, mapping, &decided):

    if not (token.mandatory_policy & NO_WRITE_UP):
        return

    token_dominates = (token.integrity_level >= ace.integrity_level)

    if token_dominates:
        return

    // Non-dominant: start with read + execute, strip per label policy.
    allowed = MapGenericBits(GENERIC_READ, mapping)
            | MapGenericBits(GENERIC_EXECUTE, mapping)

    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_READ_UP:
        allowed &= ~MapGenericBits(GENERIC_READ, mapping)
    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_WRITE_UP:
        allowed &= ~MapGenericBits(GENERIC_WRITE, mapping)
    if ace.mask & SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP:
        allowed &= ~MapGenericBits(GENERIC_EXECUTE, mapping)

    // READ_CONTROL and SYNCHRONIZE are always allowed regardless of the
    // object type's GenericMapping and the label's up-strip policy — a
    // non-dominant caller can always read the descriptor and synchronize
    // on the object. Applied after the strips because a file GENERIC_READ
    // mapping folds these bits in, so NO_READ_UP would otherwise take them.
    allowed |= READ_CONTROL | SYNCHRONIZE

    // SeRelabelPrivilege: let WRITE_OWNER through MIC.
    if token.privilege_enabled(SeRelabelPrivilege):
        allowed |= WRITE_OWNER

    all_bits = MapGenericBits(GENERIC_ALL, mapping)
    decided |= all_bits & ~allowed
```

---

# Restricted Tokens

_Peios Kernel / Internals / KACS / Access check_

> The second pass a restricted token forces — when it runs, how privileges bypass it, and how owner rights and virtual groups behave in it.

<a id="trm-3-8-4"></a>

A restricted token carries a secondary SID list, the restricting SIDs.
The second pass runs whenever that list or the restricted device group
list is non-empty, and AccessCheck evaluates the DACL twice. <a id="cite-check.restricted.second-pass-trigger"></a>

The **normal pass** evaluates the DACL against the token's ordinary
identity — user SID and group SIDs — exactly as usual. The
**restricted pass** evaluates the same DACL again with SID matching
drawn only from the restricting SID list; the token's normal groups
are invisible to it. <a id="cite-check.restricted.only-restricting-sids-match"></a> Conditional membership operators — `Member_of`,
`Member_of_Any`, and their device variants — take the same restricted
view, seeing only the restricting SIDs plus any virtual groups
injected from that list. <a id="cite-check.restricted.conditional-membership-restricted"></a>

The restricting SID list is **presence-based**. A SID participates
whenever it appears in the list, and `SE_GROUP_ENABLED` and
`SE_GROUP_USE_FOR_DENY_ONLY` on those entries are ignored both for
restricted-pass SID matching and for restricted-pass non-device
conditional membership. <a id="cite-check.restricted.presence-based"></a> This matches Windows restricted-token
behaviour, where restricting SIDs are always enabled for access
checks.

Access is granted only for rights **both passes agree on** — the
intersection. <a id="cite-check.restricted.intersection"></a> The restricting list acts as a ceiling: the principal
can never receive more access than the restricting SIDs would
independently justify.

<a id="trm-3-8-4-1"></a>

## Write-restricted tokens <a id="cite-check.restricted.write-restricted"></a>

In the write-restricted variant the intersection applies only to
write-category bits, and read and execute access comes from the normal
pass alone. What counts as write is whatever the object type's
GenericMapping maps `GENERIC_WRITE` onto.

<a id="trm-3-8-4-2"></a>

## Privileges bypass the restricted pass <a id="cite-check.restricted.privileges-bypass"></a>

Rights granted by privileges are added back after the intersection.
Privileges are system-level grants from security policy rather than
from the object's DACL: token restriction reduces the identity-based
access surface, and privilege-based grants are orthogonal to it. The
bits restored are the post-PIP privilege-granted set together with the
take-ownership grant. <a id="cite-check.restricted.restored-set"></a>

<a id="trm-3-8-4-3"></a>

## Owner rights and virtual groups in the restricted pass

The restricted pass evaluates owner implicit rights independently. If
the object's owner SID appears in the restricting SID list, the pass
grants `READ_CONTROL` and `WRITE_DAC`, subject to the same `OWNER
RIGHTS` suppression pre-scan as the normal pass; if the owner SID is
not a restricting SID, no implicit rights are granted. <a id="cite-check.restricted.owner-implicit"></a>

Two virtual groups are injected on the same basis. `S-1-3-4` (`OWNER
RIGHTS`) is injected when the object's owner SID is among the
restricting SIDs, and `S-1-5-10` (`PRINCIPAL_SELF`) when `self_sid`
is. <a id="cite-check.restricted.virtual-groups"></a> This keeps the restricted pass consistent in its handling of these
well-known SIDs rather than letting them leak the unrestricted
identity.

Restricted device groups, when the token has them, are swapped in for
the restricted pass so that `Device_Member_of` and its relatives
evaluate against the restricted set rather than the unrestricted
device groups. <a id="cite-check.restricted.device-groups-swapped"></a>

## Choosing a restriction

Removing privileges without supplying restricting SIDs reduces privilege
presence without adding a restricted-SID intersection. Supplying restricting
SIDs adds another identity-based ceiling; it does not remove existing
privileges by itself. Review both choices when launching reduced-authority
work.

Write restriction limits the intersection to mapped write rights, but its
required `user_deny_only` state also changes ordinary user-SID matching.
Do not describe it as an unconditional promise that all previous reads
remain available. The user SID can match denies rather than grants.

A capability SID in a restricting list is still an ordinary SID in this
mechanism. It is not the dedicated confinement pass, which has separate
semantics and does not allow privileges to bypass its ceiling. Test the
complete intended token and object policy rather than treating either
restriction as a universal sandbox recipe.

---

# Object ACEs and Property-Level Access

_Peios Kernel / Internals / KACS / Access check_

> Per-property access control through GUID-scoped ACEs — object type lists, propagation, PRINCIPAL_SELF, and per-node results.

<a id="trm-3-8-5"></a>

An object ACE carries a GUID identifying the property or property set
its rule applies to, which is what enables per-property access control
on objects with internal structure — Active Directory objects, most
obviously. An object ACE with no GUID, meaning
`ACE_OBJECT_TYPE_PRESENT` is unset, behaves exactly like a basic ACE. <a id="cite-check.object-ace.no-guid-is-basic"></a>

<a id="trm-3-8-5-1"></a>

## Object type lists

To request property-level access the caller supplies an object type
list: a tree of GUIDs representing the properties being asked for.
Each node carries its own `decided` and `granted` pair and is resolved
independently. <a id="cite-check.object-ace.per-node-state"></a>

With no list supplied, object ACEs with GUIDs apply globally, as if
they were basic ACEs. <a id="cite-check.object-ace.no-list-applies-globally"></a> With a list supplied, every ACE that behaves
like a basic ACE — ordinary basic ACEs, and object ACEs without an
`ObjectType` GUID — applies to every node in the tree. <a id="cite-check.object-ace.basic-applies-to-all-nodes"></a> An object ACE
whose GUID does not appear anywhere in the supplied tree is silently
skipped. <a id="cite-check.object-ace.unmatched-guid-skipped"></a>

<a id="trm-3-8-5-2"></a>

## Propagation

Decisions move through the tree in four ways.

**Downward from grants.** A grant on a property set flows to every
attribute within it, each child node still applying first-writer-wins
for itself. <a id="cite-check.object-ace.grant-propagates-down"></a>

**Upward from grants.** When every attribute within a property set has
been granted the same right, that right propagates up to the set's
node. <a id="cite-check.object-ace.grant-propagates-up"></a> The propagation is a per-bit intersection, so a right reaches
the parent only if all siblings share it.

**Upward from denials.** A denial on an attribute propagates to every
ancestor regardless of what its siblings hold, and siblings are
themselves unaffected. <a id="cite-check.object-ace.denial-propagates-up"></a> Ancestors still apply first-writer-wins to the
propagated bits, so a denial cannot overturn something an ancestor had
already decided. <a id="cite-check.object-ace.denial-up-first-writer-wins"></a>

**Downward from denials.** A denial on a property set flows to every
attribute within it, again subject to first-writer-wins. <a id="cite-check.object-ace.denial-propagates-down"></a>

<a id="trm-3-8-5-3"></a>

## PRINCIPAL_SELF

`PRINCIPAL_SELF` (`S-1-5-10`) is a placeholder for the object's
associated principal. An ACE targeting it matches the caller when the
caller's token represents the same principal as the object, which the
caller establishes by passing the object's principal SID as the
`self_sid` parameter. <a id="cite-check.object-ace.principal-self-matches-self-sid"></a> With a null `self_sid`, `PRINCIPAL_SELF` ACEs
match nothing. <a id="cite-check.object-ace.principal-self-null-matches-nothing"></a>

It follows the ordinary deny-only rules: if the caller's matching SID
is deny-only, `PRINCIPAL_SELF` matches deny ACEs but not allow ACEs. <a id="cite-check.object-ace.principal-self-deny-only"></a>

<a id="trm-3-8-5-4"></a>

## Scalar and per-node results

`AccessCheck` requires every node to pass, so a denial on any one
property fails the whole request. <a id="cite-check.object-ace.scalar-requires-all-nodes"></a> `AccessCheckResultList` returns a
separate verdict per node.

The scalar result `AccessCheck` returns is the root node's granted
mask. <a id="cite-check.object-ace.scalar-is-root-mask"></a> That is equivalent to the intersection across all nodes, but by
construction rather than by computation: upward denial propagation
forces every descendant's denial into all of its ancestors' `decided`
sets, which guarantees the root's granted mask is a subset of every
node's.

<a id="trm-3-8-5-5"></a>

## Validation

Object type lists are validated strictly, at parse time.

- A supplied list is non-empty. <a id="cite-check.object-ace.list-non-empty"></a>
- Its first node is at level 0. <a id="cite-check.object-ace.list-first-node-level-zero"></a>
- There is exactly one level-0 node. <a id="cite-check.object-ace.list-one-root"></a>
- There are no level gaps, meaning no node at level N+2 following one
  at level N. <a id="cite-check.object-ace.list-no-level-gaps"></a>
- No GUID appears twice. <a id="cite-check.object-ace.list-no-duplicate-guid"></a>

These checks are stricter than MS-DTYP, which does not specify them.
They exist because a duplicate GUID makes node lookup return the wrong
node, and a level gap makes propagation undefined.

---

# Application Confinement

_Peios Kernel / Internals / KACS / Access check_

> An absolute boundary a confined token cannot cross whatever the DACL says — normal and strict confinement, and where it sits in the order.

<a id="trm-3-8-6"></a>

Confinement restricts a token's effective access to what is explicitly
granted to its confinement identity. Even where the normal DACL walk
grants access through the user SID or a group SID, the confinement
pass intersects that with what the confinement SIDs would receive on
their own, and revokes anything they cannot independently justify. <a id="cite-check.confinement.intersects-confinement-identity"></a>

A confined token carries `confinement_sid`, its confinement identity;
`confinement_capabilities`, the capability SIDs the application
declares; and `confinement_exempt`, an escape hatch that skips
confinement evaluation entirely. <a id="cite-check.confinement.exempt-skips-evaluation"></a>

The confinement SID set is `confinement_sid` together with every SID
in `confinement_capabilities`. <a id="cite-check.confinement.sid-set"></a> Capabilities are **presence-based**
identities rather than ordinary ACE-matching groups: a capability SID
participates whenever it is present, and disabling an entry or marking
it deny-only does not remove it from the confinement identity. <a id="cite-check.confinement.capabilities-presence-based"></a>

The pass also injects two confinement-scoped virtual groups.
`S-1-5-10` (`PRINCIPAL_SELF`) is injected only when `self_sid` equals
the confinement SID or one of the capability SIDs, and `S-1-3-4`
(`OWNER RIGHTS`) only when the object's owner SID does. <a id="cite-check.confinement.virtual-groups"></a> Both apply to
ACE SID matching during the confinement walk *and* to the conditional
membership operators — `Member_of`, `Member_of_Any`, and their device
and negated variants — evaluated during that pass. <a id="cite-check.confinement.virtual-groups-in-conditionals"></a>

<a id="trm-3-8-6-1"></a>

## An absolute boundary

Confinement is not overridable. Privileges do not bypass it: the
confinement merge takes no privilege-granted input at all, so backup,
restore, `SeTakeOwnershipPrivilege` and `SeSecurityPrivilege` are
alike unable to grant access the confinement check denies. <a id="cite-check.confinement.privileges-do-not-bypass"></a> Owner
implicit rights are skipped entirely, because the pass runs with
`skip_owner_implicit` set. <a id="cite-check.confinement.skips-owner-implicit"></a>

One thing does pass through: an object with a **null DACL** grants in
the confinement pass exactly as it does in the normal pass. <a id="cite-check.confinement.null-dacl-grants"></a> A null
DACL means "no discretionary restrictions", and the confinement pass
follows standard evaluation, granting all valid bits.

<a id="trm-3-8-6-2"></a>

## Strict confinement

A normal confined token carries both `ALL_APPLICATION_PACKAGES` and
`ALL_RESTRICTED_APPLICATION_PACKAGES` among its capabilities. Omitting
`ALL_APPLICATION_PACKAGES` gives strict confinement: far fewer system
objects grant to `ALL_RESTRICTED_APPLICATION_PACKAGES`, so the access
surface is much narrower. <a id="cite-check.confinement.strict-omits-all-app-packages"></a>

Strict confinement is not a separate kernel mode bit. It is derived
purely from the SID set supplied at token creation — if
`ALL_APPLICATION_PACKAGES` is absent, AccessCheck simply evaluates the
remaining confinement SIDs. The kernel never synthesises it, and never
rejects an otherwise valid confined token for carrying it. <a id="cite-check.confinement.strict-never-rejected"></a> Deciding
which capabilities a package token receives belongs to authd and
policy tooling.

<a id="trm-3-8-6-3"></a>

## Consequences worth stating

**SACL access is unreachable.** `ACCESS_SYSTEM_SECURITY` is only ever
privilege-granted, and privileges do not bypass confinement, so a
confined token cannot reach a SACL unless a confinement ACE grants the
right outright. <a id="cite-check.confinement.sacl-unreachable"></a>

**`OWNER RIGHTS` is confinement-scoped.** `S-1-3-4` matches in the
confinement pass only when the owner SID is part of the confinement
SID set.

**`PRINCIPAL_SELF` is isolated from user identity.** `S-1-5-10` is
injected only when `self_sid` matches a confinement SID — the package
SID or one of its capabilities — not when it matches the user.

**Conditional expressions still see the full token.** The confinement
pass isolates ordinary SID matching to the confinement identity, but
conditional expressions inside ACEs continue to evaluate against the
user's real groups and claims. <a id="cite-check.confinement.conditionals-see-full-token"></a> The two confinement-scoped virtual
groups are the only exception, and they follow the confinement rules
during conditional membership evaluation.

<a id="trm-3-8-6-4"></a>

## Ordering

Confinement runs **after** the restricted token merge and after its
privilege restoration. <a id="cite-check.confinement.after-restricted-merge"></a> The order is load-bearing: privileges bypass
the restricted pass but must not bypass confinement, and if
confinement ran first the privilege restoration would resurrect bits
that confinement had already blocked.

---

# PIP in AccessCheck

_Peios Kernel / Internals / KACS / Access check_

> How a trust label ACE is evaluated — the label SID, the privileges it revokes, the algorithm, and where the compared values come from.

<a id="trm-3-8-7"></a>

An object opts in to PIP protection by carrying a
`SYSTEM_PROCESS_TRUST_LABEL_ACE` in its SACL. <a id="cite-check.pip.opt-in-via-sacl-ace"></a> The ACE's SID encodes
the required type and trust, and its access mask names exactly the
rights a non-dominant caller may still have.

A caller that **dominates** — `pip_type` and `pip_trust` both greater
than or equal to the ACE's — is unrestricted by PIP. <a id="cite-check.pip.ace-dominance-test"></a> A caller that
does not dominate is limited to the ACE mask, and everything else is
denied. <a id="cite-check.pip.non-dominant-limited-to-ace-mask"></a>

Unlike MIC, PIP has **no default**. An object with no trust label is
unrestricted, reachable by any process whatever its PIP identity. <a id="cite-check.pip.no-default"></a>

<a id="trm-3-8-7-1"></a>

## The label SID

A trust label SID has the form `S-1-19-{type}-{trust}` — the Process
Trust authority, exactly two sub-authorities. <a id="cite-check.pip.label-sid-shape"></a> Both axes are compared
numerically. The conventional type values are 0 (None), 512
(Protected) and 1024 (Isolated), but they are labels rather than a
closed enum: any other numeric type is valid and compared by the same
dominance rule. <a id="cite-check.pip.nonstandard-type-accepted"></a>

A trust label SID of any other shape — wrong authority, wrong
sub-authority count — makes the descriptor malformed, and AccessCheck
rejects it outright rather than guessing. <a id="cite-check.pip.malformed-label-rejects-descriptor"></a>

Where a SACL carries more than one trust label ACE, only the first
non-inherit-only one is used; inherit-only labels do not apply to the
object carrying them. <a id="cite-check.pip.first-non-inherit-only-label"></a>

<a id="trm-3-8-7-2"></a>

## Privilege revocation

This is the critical difference from MIC. PIP does not merely
constrain what the DACL may grant — it **revokes rights privileges
already granted**. <a id="cite-check.pip.revokes-privilege-granted"></a> A non-dominant caller who used `SeBackupPrivilege`
to obtain read has those bits stripped; `SeTakeOwnershipPrivilege`'s
`WRITE_OWNER` is stripped; `SeSecurityPrivilege`'s
`ACCESS_SYSTEM_SECURITY` is stripped.

The last of those is the point. Without privilege revocation, a
non-dominant administrator holding `SeSecurityPrivilege` could read
the SACL of a PIP-protected object — and remove the trust label from
it. PIP would be self-defeating.

There is no escape hatch. PIP has no `SeRelabelPrivilege` equivalent,
and no privilege compensates for insufficient trust. It is an absolute
boundary, which is why the enforcement step explicitly ORs
`ACCESS_SYSTEM_SECURITY` into the set of bits it can take away —
that right is outside the generic mapping and would otherwise escape. <a id="cite-check.pip.revokes-access-system-security"></a>

<a id="trm-3-8-7-3"></a>

## The algorithm <a id="cite-check.pip.algorithm"></a>

```
EnforcePIP(ace, pip_type, pip_trust, mapping, &decided,
           &granted, &privilege_granted):

    // pip_type and pip_trust are the subject's process-trust context,
    // not a token field. See "Where the values come from" below.

    ace_type  = ace.sid.pip_type
    ace_trust = ace.sid.pip_trust

    caller_dominates = (pip_type  >= ace_type
                    and pip_trust >= ace_trust)

    if caller_dominates:
        return

    // Non-dominant: the ACE mask IS the allowed set.
    allowed = MapGenericBits(ace.mask, mapping)

    // Everything not explicitly allowed is denied, including
    // ACCESS_SYSTEM_SECURITY.
    all_bits = MapGenericBits(GENERIC_ALL, mapping)
             | ACCESS_SYSTEM_SECURITY
    pip_denied = all_bits & ~allowed

    decided |= pip_denied

    // Revoke privilege-granted rights.
    granted           &= ~pip_denied
    privilege_granted &= ~pip_denied
```

<a id="trm-3-8-7-4"></a>

## Where the values come from

`pip_type` and `pip_trust` are the subject's process trust context and
are never derived from a token field — the token structure has no PIP
field at all. They are passed into AccessCheck as explicit parameters
by whichever layer is enforcing. <a id="cite-check.pip.values-are-parameters"></a>

During enforcement — FACS file access, process boundaries — the values
are the subject process's PSB, set at exec from the binary's signature
([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>), [Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). <a id="cite-check.pip.enforcement-uses-psb"></a>

The `kacs_access_check` query may instead supply them through its
arguments, per axis: zero means "use the calling process's PSB value"
and a nonzero value evaluates against the supplied context. <a id="cite-check.pip.query-supplies-values-per-axis"></a> This lets
a userspace broker evaluate access under a client's trust level, in
the same way the query's token argument lets it evaluate a token other
than its own. The query is advisory and gates nothing in the kernel;
enforcement always uses the PSB. The same effective values are used
for the verdict and for the event the check emits, so an audit record
never disagrees with the decision it describes. <a id="cite-check.pip.same-values-for-verdict-and-event"></a>

The enforcement step also computes a record of which bits PIP decided.
Nothing currently consumes it — it is threaded through three
structures and exported, and no caller reads it.

---

# Central Access and Auditing Policy

_Peios Kernel / Internals / KACS / Access check_

> Policy defined once and referenced by objects — the policy structure, access and audit evaluation, the cache, and the recovery policy.

<a id="trm-3-8-8"></a>

CAAP separates policy definition from the objects it governs. A policy
is defined once, centrally; objects reference it by SID through a
`SYSTEM_SCOPED_POLICY_ID_ACE` in their SACL. <a id="cite-check.cap.reference-by-scoped-policy-ace"></a> When the policy changes,
every future AccessCheck against a referencing object uses the new
rules — already-open handles are unaffected, because the model is
check-at-open. <a id="cite-check.cap.check-at-open"></a>

It extends the Windows Central Access Policy model by adding an audit
component: each rule carries both an access restriction and an audit
requirement.

<a id="trm-3-8-8-1"></a>

## Policy structure

A policy is a named collection of rules identified by a policy SID.
Each rule carries:

An optional **applies-to condition**, a conditional expression
determining whether the rule governs this decision. It may reference
the `@Resource`, `@User`, `@Device` and `@Local` claim namespaces, but
it cannot inspect SID or device-group membership: `Member_of`,
`Member_of_Any`, `Device_Member_of`, `Device_Member_of_Any` and their
negated forms all evaluate to UNKNOWN inside `applies_to`. <a id="cite-check.cap.applies-to-membership-unknown"></a> A rule with
no condition applies to every object referencing the policy. <a id="cite-check.cap.no-condition-applies-always"></a>

A mandatory **effective DACL** — a real DACL evaluated through the
full pipeline. An optional **effective SACL**, whose audit ACEs merge
with the object's own during the audit walk. And optional **staged**
DACL and SACL, proposed replacements used for testing.

<a id="trm-3-8-8-2"></a>

## Access evaluation

The DACL result is ANDed with the normal evaluation. CAAP can only
restrict, never expand: if the object's DACL grants read and write but
the applicable rule's effective DACL grants only read, the result is
read. <a id="cite-check.cap.intersects-only"></a>

A SACL may carry several scoped policy ACEs, which makes policies
composable — and the AND semantics are what make composition safe,
since each additional policy can only narrow. <a id="cite-check.cap.multiple-scoped-policy-aces"></a> Inherit-only scoped
policy ACEs do not apply to the object carrying them and are ignored
during lookup. <a id="cite-check.cap.inherit-only-policy-ace-ignored"></a> MS-DTYP allows one scoped policy ACE per SACL; KACS
allows several.

For each scoped policy ACE, AccessCheck looks the policy up in the
kernel cache, then for every rule whose `applies_to` is TRUE or absent
evaluates the rule's effective DACL through the full pipeline —
privilege grants, MIC, PIP, the DACL walk, restricted tokens,
confinement — and intersects the result with the running total, which
starts at the normal evaluation's granted mask. <a id="cite-check.cap.rule-dacl-full-pipeline"></a>

A rule whose condition evaluates FALSE **or UNKNOWN** is skipped. <a id="cite-check.cap.unknown-condition-skips-rule"></a> That
is deliberately the opposite of the deny-ACE UNKNOWN rule: skipping is
the conservative choice here, because a rule's DACL can only narrow
what the normal DACL already granted.

If no rules apply — every condition false or unknown, or the policy
has no rules — CAAP has no effect and the normal result stands. <a id="cite-check.cap.no-applicable-rules-no-effect"></a>

The rule's DACL is evaluated with backup and restore intent **not**
passed: intent is a caller concern, not a policy concern. <a id="cite-check.cap.no-backup-restore-intent"></a> And CAAP
never recurses. A rule's synthetic descriptor has scoped policy ACEs
stripped before evaluation, so nested CAAP evaluation cannot occur
even when the original SACL carried more of them. <a id="cite-check.cap.no-recursion"></a> The synthetic
descriptor keeps the original owner and group, and preserves the MIC
and PIP labels, so a rule is evaluated against the same mandatory
constraints as the object itself. <a id="cite-check.cap.synthetic-preserves-labels"></a>

<a id="trm-3-8-8-3"></a>

## Audit evaluation

For each applicable rule carrying an effective SACL, the rule's audit
ACEs are evaluated alongside the object's own during the audit walk.
They are treated identically — if either says to audit an operation,
it is audited. <a id="cite-check.cap.sacl-merged-with-object"></a>

The SACL component is purely additive. A CAAP SACL can add audit
coverage and can never suppress auditing the object's own SACL asks
for. <a id="cite-check.cap.sacl-additive-only"></a>

<a id="trm-3-8-8-4"></a>

## The policy cache

The kernel keeps a map from policy SID to policy object, empty at
boot. Policies are pushed in through `kacs_set_caap`, which requires
`SeTcbPrivilege` — and marks it used. <a id="cite-check.cap.set-requires-tcb"></a> A non-null spec for an existing
SID replaces the policy; a null spec or zero length removes it. <a id="cite-check.cap.set-replaces-or-removes"></a>
Every call that passes the privilege gate writes a
`kacs.caap.policy.changed` record ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)) naming the caller, the policy
SID as `caap.policy.sid`, and `operation.name` `set` or `remove`, with
`outcome.success` and, when the change did not apply, `outcome.errno`. <a id="cite-check.cap.set-recorded"></a> The
policy SID's length is bounded to 8–68 bytes before parsing begins,
and until the cache has been initialised both setting and evaluating
fail with `EACCES`. <a id="cite-check.cap.uninitialised-eacces"></a>

The wire format is:

```
[version:u8 = 0x01]
[rule_count:u32le]
per rule:
  [applies_to_len:u32le][applies_to_expr bytes]     (0 = no condition)
  [effective_dacl_len:u32le][effective_dacl bytes]  (MUST NOT be 0)
  [effective_sacl_len:u32le][effective_sacl bytes]  (0 = no audit rules)
  [staged_dacl_len:u32le][staged_dacl bytes]        (0 = no staged DACL)
  [staged_sacl_len:u32le][staged_sacl bytes]        (0 = no staged SACL)
```

All lengths are little-endian `u32`. ACLs use the standard binary
format, and every ACE type valid in a DACL or SACL is permitted inside
a policy ACL. <a id="cite-check.cap.any-ace-type-permitted"></a> The `applies_to` expression is conditional ACE bytecode,
carrying the same `artx` prefix as callback ACE application data. <a id="cite-check.cap.applies-to-artx-bytecode"></a>

The limits are a spec of at most 256 KB, at most 256 rules, an
`applies_to` of at most 64 KB, and an individual ACL of at most 64 KB. <a id="cite-check.cap.limits"></a>
The version byte has to be `0x01`. <a id="cite-check.cap.version-byte"></a> Trailing bytes after the declared
rules are rejected. <a id="cite-check.cap.trailing-bytes-rejected"></a>

Validation is strict and total. Malformed or truncated `applies_to`
bytecode fails the whole call with `EINVAL` at ingestion rather than
being admitted and later treated as a runtime UNKNOWN — the structural
check happens once, at the boundary. <a id="cite-check.cap.malformed-applies-to-einval"></a> A rule with a zero-length
effective DACL fails the same way, as do truncated fields, lengths
exceeding the buffer, and invalid ACL headers. <a id="cite-check.cap.zero-length-dacl-einval"></a> `SeTcbPrivilege` is
checked before any parsing begins. <a id="cite-check.cap.tcb-checked-before-parsing"></a>

The cache is a kernel mechanism. The maintained authd implementation does
not populate it from registry or directory policy. A deployment needs an
explicit privileged loader and distribution process; the existence of
`kacs_set_caap` does not establish that either is installed. Policies loaded
after services start do not retroactively affect already-open handles.

<a id="trm-3-8-8-5"></a>

## The recovery policy

When a scoped policy ACE names a SID that is not in the cache — the loader
did not install it or the policy was removed — a hardcoded recovery policy
is used instead: `GENERIC_ALL`
to BUILTIN\Administrators, to SYSTEM, and to `OWNER RIGHTS`. <a id="cite-check.cap.recovery-policy"></a>

Those masks are stored as the literal `GENERIC_ALL` bit rather than
pre-mapped object-specific bits, and are expanded through the caller's
GenericMapping at evaluation time, so the recovery policy works
correctly for every object type. <a id="cite-check.cap.recovery-generic-all-mapped"></a>

Because CAAP is an intersection, recovery does not widen access beyond
the object's own DACL: it limits missing-policy access to callers who
also satisfy the recovery DACL. This is a fail-closed recovery mode
with administrator, SYSTEM and owner escape hatches — not a no-effect
fallback.

<a id="trm-3-8-8-6"></a>

## Errors

A rule whose DACL evaluation errors denies everything except rights
granted by privileges — in the effective and the staged evaluation
alike, and in the scalar total exactly as on every node of a
result-list check. <a id="cite-check.cap.rule-error-denies-except-privileges"></a> Preserving those is the escape hatch: an
administrator with `SeSecurityPrivilege` keeps the ability to read and
modify the SACL and remove the offending scoped policy ACE.

The escape hatch is conditional, though, and the ordering is why. PIP
runs before CAAP and may already have stripped
`ACCESS_SYSTEM_SECURITY` from the privilege-granted set for a
non-dominant caller. The hatch therefore only works for callers who
are PIP-dominant, or where the object carries no trust label. <a id="cite-check.cap.error-hatch-requires-pip-dominance"></a>

Rule evaluation swallows every error kind, including allocation
failure, so an out-of-memory condition inside a rule is reported as
"this rule denied all except privileges" rather than as `ENOMEM`. <a id="cite-check.cap.rule-error-swallowed"></a>

A rule whose SACL evaluation errors has its audit contribution
skipped, and a diagnostic event is emitted. <a id="cite-check.cap.sacl-error-skipped-diagnostic"></a>

<a id="trm-3-8-8-7"></a>

## Staging

A rule may carry staged DACLs and SACLs alongside its effective ones,
and AccessCheck evaluates both in parallel. The staged result affects
neither access nor audit; where effective and staged differ, the
difference is reported through a staging mismatch flag returned to the
caller and a diagnostic event. <a id="cite-check.cap.staged-no-effect-reports-mismatch"></a>

A rule with no staged DACL contributes its effective result to both
running totals, and a rule with no staged SACL contributes its
effective SACL to both. <a id="cite-check.cap.no-staged-uses-effective"></a>

## Planning a staged rollout

Staging supplies comparison data, not an automatic rollout service. The
following procedure requires a deployment-specific loader and observation
path; authd does not provide that workflow.

1. Preserve the effective policy and its object references. Author proposed
   staged DACL/SACL fields without replacing the effective ones.
2. Load and verify the policy on each intended machine through the privileged
   kernel interface. Distribution and object-side scoped-policy ACEs are
   separate responsibilities.
3. Exercise representative access paths and collect mismatch evidence with
   subject, object, requested rights, and effective result. Check auditing
   and observation limits before treating silence as agreement.
4. Review unexpected differences. A mismatch is neither a denial caused by
   the staged policy nor a complete list of which ACEs differ.
5. When the change is approved, replace the effective fields and verify fresh
   opens. Remove or replace staging fields deliberately. Retain the prior
   effective policy for an explicit restoration if necessary.

Staging does not version policy or revoke existing handles. The cache starts
empty at boot; a restart requires loading the intended policy again. Removing
a cached policy while objects still reference its SID activates recovery
policy rather than removing all restriction. Recovery remains an intersection
with the preceding grant, not guaranteed administrator access to everything.
The actual recovery DACL, including Owner Rights matching, is evaluated by
the pipeline; it must not be inferred from a simplified audience label.

---

# Auditing in AccessCheck

_Peios Kernel / Internals / KACS / Access check_

> Auditing is purely observational and never changes a decision — access, continuous and privilege-use auditing, and per-token policy.

<a id="trm-3-8-9"></a>

Auditing is purely observational. No audit rule affects the access
decision, and audit ACEs are evaluated after the decision is final. <a id="cite-check.auditing.observational"></a>

Three mechanisms operate inside the pipeline, emitting two families of
KMES record: `kacs.audit.access.checked` for object-access events from the SACL
walk and from token audit-policy forcing, and `kacs.audit.privilege.used` for
privilege-use events. <a id="cite-check.auditing.event-families"></a> A third family is
emitted for the CAAP conditions of [Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>): `kacs.caap.sacl.skipped` for
a rule SACL that would not parse or evaluate, and
`kacs.caap.staging.diverged` for a staged-versus-effective mismatch. <a id="cite-check.auditing.caap-diagnostic-family"></a> The event type strings and
payload schemas are in [Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>).

Event delivery happens before any result is written back to the
caller, and a failure to deliver fails the call. <a id="cite-check.auditing.delivery-before-result"></a> An audit event cannot
be suppressed by handing the syscall a bad output pointer.

<a id="trm-3-8-9-1"></a>

## Access auditing

`SYSTEM_AUDIT` ACEs in the SACL define which attempts to log. Each
carries a SID, an access mask, and success and failure flags —
`SUCCESSFUL_ACCESS_ACE_FLAG` (0x40) and `FAILED_ACCESS_ACE_FLAG`
(0x80).

An event is emitted when the ACE's SID matches the caller, its mask
overlaps the requested access, and its flags match the outcome. <a id="cite-check.auditing.audit-ace-conditions"></a>

<a id="trm-3-8-9-1-1"></a>

### On the AccessCheck syscall

Through `kacs_access_check` and `kacs_access_check_list` the descriptor
is the caller's own, SACL included. So that no process can write
kernel-origin audit records at will by supplying a SACL that matches
itself, the records a SACL generates there are written only when the
calling process's effective token holds `SeAuditPrivilege`, enabled.
Without it the check runs and answers exactly as it would otherwise,
and its SACL records are withheld; the privilege is marked used when it
admits them. <a id="cite-check.auditing.syscall-sacl-needs-audit-privilege"></a> The
privilege is the caller's, not the subject's: a daemon checking a
client through `token_fd` needs it on its own token. This is Windows'
rule for `AccessCheckAndAuditAlarm`.

The records the checked token's own audit policy forces, and
privilege-use and CAAP records, are not gated: the policy belongs to
the token, not to the caller. <a id="cite-check.auditing.syscall-policy-records-ungated"></a>

Two details matter. The SID is matched with **deny polarity** — the
broadest identity view, in which deny-only groups are visible —
because auditing should capture the widest possible picture rather
than the narrowest. <a id="cite-check.auditing.deny-polarity-matching"></a> And the overlap is tested against the
generic-mapped **requested** mask, not the final granted mask, so a
failed request is still auditable for the rights it actually asked
for. <a id="cite-check.auditing.overlap-against-requested"></a>

Conditional audit ACEs gate the event on an expression, using the same
deny-side membership polarity. An expression evaluating to UNKNOWN
emits the event: when in doubt, audit. <a id="cite-check.auditing.unknown-condition-emits"></a>

<a id="trm-3-8-9-2"></a>

## Continuous auditing

Access auditing fires once, where AccessCheck runs. Continuous
auditing covers per-operation monitoring.

`SYSTEM_ALARM` ACEs configure it. When AccessCheck evaluates an alarm
ACE whose SID matches, the ACE's mask is accumulated into a
**continuous audit mask** returned to the caller, which stores it on
the open handle and enforces it per operation. <a id="cite-check.auditing.alarm-accumulates-mask"></a> Conditional alarm ACEs
use the same deny-side polarity as conditional audit ACEs. The alarm
branch deliberately performs no overlap test against the requested
mask — an alarm ACE contributes its mask on a SID match alone. <a id="cite-check.auditing.alarm-no-overlap-test"></a>

On each later operation the enforcement point emits a
`kacs.audit.handle.used` event when the operation's normalised
required-access mask overlaps the stored mask. <a id="cite-check.auditing.continuous-event-on-overlap"></a> For FACS handles that
is the same mask used by the use-time check ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)). Where an
operation's authorization accepts any one of several rights — append
or write data, say — the required mask holds the accepted set and the
event records the subset that overlapped, as `access.matched`, beside
the whole stored mask as `access.audit-mask`. <a id="cite-check.auditing.continuous-records-overlapping-subset"></a>

Events are emitted after the per-operation decision is known, for
successful and denied attempts alike. <a id="cite-check.auditing.continuous-both-outcomes"></a> The subject and process recorded
are the **operation-time** effective token and current task, not
necessarily the ones that opened the handle. <a id="cite-check.auditing.continuous-operation-time-subject"></a> That keeps attribution
correct after a handle is passed between processes, while still using
the opener-computed mask to decide whether the handle is audited at
all.

An enforcement point that cannot construct a required continuous-audit
event fails closed. <a id="cite-check.auditing.continuous-fails-closed"></a> Transport buffering and drop accounting remain
KMES's concern ([Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)).

<a id="trm-3-8-9-3"></a>

## Privilege-use auditing

When a privilege is exercised to grant access the DACL would not have
granted independently, a privilege-use event may be emitted. This runs
after the complete pipeline — after integrity policy, confinement and
central access policy — so it reflects the final result rather than an
intermediate one. <a id="cite-check.auditing.privilege-use-after-pipeline"></a>

**Successful** privilege use means the privilege's contributed bits
survive into the final granted result. The privilege is marked used,
and an event is emitted when the token's `audit_policy` carries
`PRIVILEGE_USE_SUCCESS` (0x04). <a id="cite-check.auditing.privilege-use-success"></a> **Failed** privilege use means the
privilege contributed bits during evaluation that did not survive. The
privilege is *not* marked used, and an event is emitted under
`PRIVILEGE_USE_FAILURE` (0x08). <a id="cite-check.auditing.privilege-use-failure"></a> A privilege that contributed nothing
to the requested access produces no event either way. <a id="cite-check.auditing.privilege-use-no-contribution"></a>

With an object type list, the test is per-node: a privilege counts as
successfully used if its bits survive on *any* node's final mask. <a id="cite-check.auditing.privilege-use-per-node"></a>

A `MAXIMUM_ALLOWED` request short-circuits this stage entirely,
recording no used bits and emitting no privilege-use events at all. <a id="cite-check.auditing.max-allowed-skips-privilege-use"></a>

How counterfactual the accounting really is varies by privilege, as
[The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>) describes: `SeSecurityPrivilege` and `SeTakeOwnershipPrivilege`
contribute only where the DACL had not already granted the right,
while backup and restore seed their bits unconditionally and so also
report use for accesses the DACL alone would have permitted. <a id="cite-check.auditing.backup-restore-overreport"></a>

<a id="trm-3-8-9-4"></a>

## Per-token audit policy

A token's `audit_policy` can force events regardless of SACL content.
This runs after the SACL walk and before result computation: if the
access succeeded and the policy carries `OBJECT_ACCESS_SUCCESS`
(0x01), a success event is emitted; if it failed and the policy
carries `OBJECT_ACCESS_FAILURE` (0x02), a failure event is. <a id="cite-check.auditing.forced-events"></a>

Success here means every requested bit was granted, or that nothing
was requested at all. <a id="cite-check.auditing.forced-success-definition"></a>

These events are additive — they fire even when no SACL ACE matched —
and they carry the object identity from the audit context the caller
supplied, exactly as a SACL-triggered record does. <a id="cite-check.auditing.forced-additive"></a> The
policy is per-token, fixed at creation, and follows impersonation,
since it is read from the effective token. <a id="cite-check.auditing.policy-from-effective-token"></a>

<a id="trm-3-8-9-5"></a>

## Event contents

An event carries the **subject**, the calling token's identity —
`subject.token.sid`, `.groups` with their parallel `.group-attributes`,
`.integrity`, the token's own LUID as `.id`, its logon session as
`.auth-id`, `.type`, `.impersonation` and the projected `.uid` — and
the PIP state as `subject.pip.type` and `subject.pip.trust`; the
**object**, as `object.kind` and the fields beneath it; the **access**,
as `access.requested` and `access.granted`, with `outcome.success`;
the **trigger**, `trigger.kind` (`sacl` or `policy`) and, for `sacl`,
the matched ACE as `trigger.ace`, or for a privilege record the
`privilege.*` fields; and the **process**, as
`emitter.process.pid`, `.name` and `.executable`. <a id="cite-check.auditing.event-contents"></a>

An access record also says what the mandatory checks withheld, since
that is often the whole reason a check the DACL would allow was denied:
`access.denied-integrity` is the requested bits the object's mandatory
label denied, and `access.denied-trust` the requested bits its
process-trust label denied — every bit each denied, for a
`MAXIMUM_ALLOWED` request — and each is absent when it denied none. <a id="cite-check.auditing.mandatory-denials-recorded"></a>

The pipeline itself produces only the object-and-access half — the
matched ACE bytes, the requested and granted masks, the outcome,
whether the event was policy-forced, the privilege, and the audit
context. The subject and process halves are attached at emission time
from the resolved call context, which is also where the effective PIP
values used for the verdict are reused for attribution.

<a id="trm-3-8-9-5-1"></a>

### The object

Where the kernel makes the check itself it knows the kind of object
and writes `object.kind`: `file`, `process`, `token`, `socket` (which
covers port-reservation binds) or `ipc`. A token check also writes the
target's `object.token.id` and `object.token.guid`. Some identity is
not yet reachable where the record is built, and is absent rather than
invented: `object.file.path` on file checks, `object.process.pid` and
`object.process.guid` on process checks. A mount-namespace check writes
`object.kind` `mount-namespace` and nothing beneath it: a namespace has
no name or identifier to carry. <a id="cite-check.auditing.mount-namespace-object-kind"></a>

A check made through `kacs_access_check` names its object through the
**audit context** (`audit_context_ptr`, `audit_context_len`), the
PGSS [The event stream](</kernel/internals/ntfe/event-ring-and-delivery.md#trm-6-7>) map:

```text
{kind: "service", service: {name: "jellyfin"}}
```

The kernel validates it before running the check and fails the call
with `EINVAL` unless it is well-formed msgpack no deeper than KMES's
default nesting depth less one; its root is a map of one or two
entries with string keys; it has exactly one `kind`, a string matching
the PGSS [The snapshot](</kernel/internals/ntfe/the-snapshot.md#trm-6-3>) segment grammar `[a-z][a-z0-9]*(-[a-z0-9]+)*`; and its
only other entry is keyed by that kind and holds a non-empty map whose
keys match the same grammar. The kernel copies it into the record as
`object.kind` and `object.<kind>.*` — `object.service.name` above. A
call without an audit context writes no `object`: the kernel does not
know what was checked.

These values are the caller's claim, which the kernel copied but did
not observe. So is everything else on the syscall path: the descriptor,
and with it `trigger.ace`, is the caller's, as is any PIP type or trust
it passes. Every record of `kacs_access_check` and
`kacs_access_check_list` therefore carries `fields.attestation.userspace`
set to `true`, with or without an audit context, and a record of a check
the kernel makes itself never does. <a id="cite-check.auditing.syscall-records-asserted"></a>
A context that is anything other than this map, such as the free-form
strings earlier components passed, fails with `EINVAL`.

---

# The Algorithm

_Peios Kernel / Internals / KACS / Access check_

> How every layer composes — the definitive statement of the evaluation order, from EvaluateSecurityDescriptor down through AccessCheckCore.

<a id="trm-3-8-10"></a>

The preceding sections describe what each layer of AccessCheck does.
This one describes how they compose, and is the definitive statement
of the evaluation order.

<a id="trm-3-8-10-1"></a>

## Pipeline overview <a id="cite-check.algorithm.pipeline-order"></a>

Before the pipeline proper, two things are checked and can fail the
call outright.

- The token's own invariants are validated — a `write_restricted`
  token without `user_deny_only` is rejected as invalid. <a id="cite-check.algorithm.write-restricted-needs-deny-only"></a>
- In the orchestrator, a null descriptor is rejected and
  `AccessCheckResultList` is required to have been given an object
  type list. <a id="cite-check.algorithm.null-descriptor-rejected"></a>

A null descriptor presented by an Identification-level token
therefore fails as an invalid parameter rather than as access denied,
because the null check runs first. <a id="cite-check.algorithm.null-check-runs-first"></a>

The pipeline then runs in this order:

0. **Impersonation level gate.** An impersonation token at
   Identification level is denied immediately. <a id="cite-check.algorithm.identification-denied"></a> Anonymous tokens
   proceed through the full pipeline. <a id="cite-check.algorithm.anonymous-allowed"></a>
1. **Input validation.** Reject a descriptor with no owner. <a id="cite-check.algorithm.no-owner-rejected"></a> A null
   group SID is valid and has no direct effect on the decision. <a id="cite-check.algorithm.null-group-valid"></a>
2. **Generic mapping.** Map generic bits in the desired mask to
   object-specific bits; strip `MAXIMUM_ALLOWED`. <a id="cite-check.algorithm.desired-mask-mapped"></a>
3. **Effective privileges.** Clear the backup and restore bits when
   the corresponding intent flag is absent. <a id="cite-check.algorithm.intent-gates-backup-restore"></a> Callers of the
   userspace AccessCheck can give only these two intents.
4. **Privilege grants.** Resolve `ACCESS_SYSTEM_SECURITY`, backup and
   restore. Seed `decided`, `granted` and `privilege_granted`. <a id="cite-check.algorithm.privilege-seeding"></a>
5. **Pre-SACL walk.** Extract the mandatory integrity label, the PIP
   trust label, resource attributes and scoped policy SIDs from the
   SACL, then enforce MIC and PIP. <a id="cite-check.algorithm.pre-sacl-walk"></a>
6. **Virtual group resolution.** `S-1-3-4` and `S-1-5-10` become
   matchable where the caller is the owner or the object's principal.
7. **Tree initialisation.** Seed each node from the scalar state. <a id="cite-check.algorithm.tree-seeded-from-scalar"></a>
8. **Normal DACL evaluation.** Owner implicit rights, then the walk.
   Under the kernel-internal creator-grant intent, which only a file
   open that creates its object carries, the walk instead grants every
   right not already decided ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-10>)). Every later step
   still applies. <a id="cite-check.algorithm.creator-grant"></a>
9. **Post-DACL WRITE_OWNER override.** `SeTakeOwnershipPrivilege`
   grants `WRITE_OWNER` if the DACL did not and no mandatory
   mechanism blocked it. <a id="cite-check.algorithm.take-ownership-override"></a>
10. **Restricted token pass**, with intersection and privilege
    restoration.
11. **Confinement pass**, with absolute intersection.
12. **CAAP.** Evaluate each applicable rule's DACL through the full
    per-descriptor pipeline and intersect; collect SACLs.
13. **Privilege-use auditing.**
14. **Audit emission**, over the object's SACL and any CAAP SACLs.
15. **Result computation.**

Object type lists are validated at parse time rather than at step 1 —
non-empty, one level-0 node first, no level gaps, no duplicate GUIDs —
so a malformed list never reaches the pipeline. <a id="cite-check.algorithm.list-validated-before-pipeline"></a> Step 1 re-checks only
emptiness.

Reserved access-mask bits (`0x0CE0_0000`) are rejected wherever a mask
is mapped. <a id="cite-check.algorithm.reserved-bits-rejected"></a> That applies to the caller's desired mask *and* to every
ACE mask, so a single ACE carrying a reserved bit aborts the entire
check rather than being skipped. <a id="cite-check.algorithm.reserved-bit-ace-aborts-check"></a>

<a id="trm-3-8-10-2"></a>

## EvaluateSecurityDescriptor

Steps 0–11, called once for the normal evaluation and once per CAAP
rule with a synthetic descriptor.

```
EvaluateSecurityDescriptor(
    sd, token, pip_type, pip_trust, desired, mapping,
    object_tree, self_sid, local_claims, privilege_intent
) -> (decided, granted, privilege_granted,
      max_allowed_mode, mapped_desired, resource_attributes,
      policy_sids) | error

    // Step 0: Impersonation level gate.
    if token.token_type == Impersonation
       and token.impersonation_level == Identification:
        return ERROR_ACCESS_DENIED

    // Step 1: Input validation.
    if sd.owner is null:
        return ERROR_INVALID_SECURITY_DESCR

    // Step 2: Generic mapping.
    desired = MapGenericBits(desired, mapping)
    max_allowed_mode = (desired & MAXIMUM_ALLOWED) != 0
    desired = desired & ~MAXIMUM_ALLOWED

    // Step 3: Effective privileges.
    effective_privileges = token.privileges_enabled
    if not (privilege_intent & BACKUP_INTENT):
        effective_privileges &= ~SeBackupPrivilege
    if not (privilege_intent & RESTORE_INTENT):
        effective_privileges &= ~SeRestorePrivilege

    // Step 4: Privilege-based grants.
    decided = 0; granted = 0; privilege_granted = 0

    // ACCESS_SYSTEM_SECURITY is always decided by privilege.
    decided |= ACCESS_SYSTEM_SECURITY
    if (effective_privileges & SeSecurityPrivilege):
        granted           |= ACCESS_SYSTEM_SECURITY
        privilege_granted |= ACCESS_SYSTEM_SECURITY

    if (effective_privileges & SeBackupPrivilege):
        backup_bits = MapGenericBits(GENERIC_READ, mapping)
        decided |= backup_bits; granted |= backup_bits
        privilege_granted |= backup_bits

    if (effective_privileges & SeRestorePrivilege):
        restore_bits = MapGenericBits(GENERIC_WRITE, mapping)
                     | WRITE_DAC | WRITE_OWNER | DELETE
                     | ACCESS_SYSTEM_SECURITY
        decided |= restore_bits; granted |= restore_bits
        privilege_granted |= restore_bits

    // Restore already includes WRITE_OWNER, so when it is active
    // step 9 has nothing left to do. Step 9 is the fallback for
    // when restore is inactive and the DACL did not grant it.

    // Step 5: Pre-SACL walk. mandatory_decided records bits decided
    // by MIC and PIP, so step 9 cannot override them.
    resource_attributes = {}; policy_sids = []; mandatory_decided = 0
    PreSACLWalk(sd, token, pip_type, pip_trust, mapping,
                &decided, &granted, &privilege_granted,
                &mandatory_decided, &resource_attributes,
                &policy_sids)

    // Steps 6-8: owner implicit rights are granted first, inside
    // EvaluateDACL, and the tree is seeded from the already
    // augmented scalar state. Virtual groups are resolved per
    // lookup rather than by building an enriched token.
    EvaluateDACL(sd, token, mapping, object_tree,
                 SidMatchesToken, desired, max_allowed_mode,
                 resource_attributes, local_claims,
                 skip_owner_implicit=false,
                 &decided, &granted)

    // Step 9: Post-DACL WRITE_OWNER override.
    if (desired & WRITE_OWNER) != 0 or max_allowed_mode:
        if (effective_privileges & SeTakeOwnershipPrivilege):
            if not (mandatory_decided & WRITE_OWNER)
               and not (granted & WRITE_OWNER):
                decided |= WRITE_OWNER
                granted |= WRITE_OWNER
                privilege_granted |= WRITE_OWNER
                for each node with WRITE_OWNER ungranted:
                    node.decided |= WRITE_OWNER
                    node.granted |= WRITE_OWNER

    // Step 10: Restricted token pass.
    if token.restricted_sids or token.restricted_device_groups:
        // Restricted identity view: only restricting SIDs, plus
        // S-1-3-4 if the owner is among them and S-1-5-10 if
        // self_sid is. Restricted device groups swap in.
        // Fresh tree, zeroed state.
        EvaluateDACL(sd, restricted_view, mapping, r_tree,
                     SidInRestrictingSids, desired,
                     max_allowed_mode, resource_attributes,
                     local_claims, skip_owner_implicit=false,
                     &r_decided, &r_granted)
        if token.write_restricted:
            write_bits = MapGenericBits(GENERIC_WRITE, mapping)
            granted = (granted & ~write_bits)
                    | (granted & r_granted & write_bits)
        else:
            granted = granted & r_granted
        granted |= privilege_granted        // privileges bypass
        // Same intersection and restoration per node.

    // Step 11: Confinement pass.
    if token.confinement_sid and not token.confinement_exempt:
        // Confinement SID set: confinement_sid plus every
        // capability, presence-based. S-1-3-4 and S-1-5-10 are
        // injected only if the owner or self_sid is in that set.
        EvaluateDACL(sd, token, mapping, c_tree,
                     SidInConfinementSids, desired,
                     max_allowed_mode, resource_attributes,
                     local_claims, skip_owner_implicit=true,
                     &c_decided, &c_granted)
        granted = granted & c_granted       // no privilege bypass
        // Same absolute intersection per node.

    return (decided, granted & root-consistent state,
            privilege_granted narrowed to what survived,
            max_allowed_mode, desired, resource_attributes,
            policy_sids)
```

The returned `privilege_granted` is **narrowed** by what actually
survived the pass — it is intersected with the root's granted mask on
return, and the orchestrator narrows it again against the CAAP result. <a id="cite-check.algorithm.privilege-granted-narrowed"></a>
A privilege-granted bit that the write-restricted merge or the
confinement intersection removed is therefore no longer part of it,
which matters in two places: the CAAP error escape hatch ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)) has
fewer bits to preserve, and the audit provenance masks reflect the
narrowed set.

<a id="trm-3-8-10-3"></a>

## AccessCheckCore

The orchestrator runs steps 12 through 15.

**Step 12, CAAP.** For each scoped policy SID, look the policy up —
falling back to the recovery policy when it is absent — and for each
rule whose `applies_to` is TRUE or absent, evaluate the rule's
synthetic descriptor through `EvaluateSecurityDescriptor` and
intersect. A rule that errors denies everything except the (already
narrowed) privilege-granted bits. Staged DACLs are evaluated in
parallel into a separate running total; a rule with no staged DACL
contributes its effective result to both.

After all policies, the staged and effective totals are compared and
any difference sets the staging mismatch flag. In result-list mode a
per-node delta sets it too — and so does a scalar delta, since the
comparison is not mode-branched. <a id="cite-check.algorithm.scalar-delta-sets-flag"></a>

**Step 13, privilege-use auditing.** For each of the five provenance
masks — security, backup, restore, take-ownership and relabel:

```
success_bits = provenance & mapped_desired & granted
failure_bits = provenance & mapped_desired & ~granted
```

Nonzero `success_bits` means the privilege was load-bearing: mark it
used on the token, and emit a success event under
`PRIVILEGE_USE_SUCCESS`. Otherwise nonzero `failure_bits` means it was
exercised but did not survive: do **not** mark it used, and emit a
failure event under `PRIVILEGE_USE_FAILURE`. Both zero means no event.
In result-list mode the comparison folds across nodes — success if the
bits survive on any node, failure only if they survive on none. <a id="cite-check.algorithm.privilege-use-folds-across-nodes"></a>

The event is `kacs.audit.privilege.used`. Its `privilege.contributed`
is `provenance & mapped_desired`, its `privilege.surviving` is
`success_bits` (empty on a failure event), and its `access.requested`
and `access.granted` are the whole check's `mapped_desired` and final
`granted`, not this privilege's share of them.

The whole step is skipped in `MAXIMUM_ALLOWED` mode, so such a request
marks nothing used and emits nothing.

Note that `relabel_granted` is tracked as provenance but is
deliberately excluded from `privilege_granted` itself, so a
relabel-loosened `WRITE_OWNER` is neither restored after the
restricted merge nor preserved by the CAAP error hatch.

**Step 14, audit emission.** Walk the object's SACL, then each CAAP
effective SACL, accumulating audit events and ORing alarm masks into
the continuous audit mask. <a id="cite-check.algorithm.sacl-walk-order"></a> This is read-only with respect to
`granted`.

The staged comparison then walks the object's SACL again followed by
the staged SACLs. That second walk is driven by the **staged** granted
total rather than the effective one, so the success and failure
classification of staged audit events reflects the staged access
result — which is what makes the flag sensitive to descriptors whose
staged and effective grants differ. <a id="cite-check.algorithm.staged-audit-walk-uses-staged-grant"></a>

**Step 14b, forced auditing.** With
`success = (granted & mapped_desired) == mapped_desired or
mapped_desired == 0`, the token's `audit_policy` forces a success or
failure event additively, regardless of what the SACL matched.

**Step 15** returns the accumulated state.

<a id="trm-3-8-10-4"></a>

## The wrappers

`AccessCheck` takes the **root node's** granted mask when a tree is
present, then computes `allowed` as `mapped_desired == 0` or every
requested bit granted. <a id="cite-check.algorithm.allowed-computation"></a> The root's mask equals the intersection across
all nodes by construction rather than by computation: upward denial
propagation ([Object ACEs and Property-Level Access](</kernel/internals/kacs/access-check/object-aces-and-property-level-access.md#trm-3-8-5>)) forces every descendant's denial into all of its
ancestors, so the root can never grant what a descendant denies.

`AccessCheckResultList` requires a tree and returns a per-node granted
mask and status, each node judged against `mapped_desired`
independently.

Neither wrapper filters the returned `granted` to the requested mask. <a id="cite-check.algorithm.granted-not-filtered"></a>
Privilege seeding at step 4 ORs bits in regardless of what was asked
for, so a caller that requested only `READ_CONTROL` while holding
backup can see read bits it never requested. The file enforcement path
does filter its result; the generic query path does not. <a id="cite-check.algorithm.file-path-filters-result"></a>

<a id="trm-3-8-10-5"></a>

## Helpers

```
SidMatchesToken(sid, token, for_allow) -> bool
    if sid == token.user_sid:
        if for_allow and token.user_deny_only:
            return false
        return true
    for group in token.groups:
        if not group.enabled and not group.deny_only:
            continue
        if for_allow and group.deny_only:
            continue
        if sid == group.sid:
            return true
    return false
```

```
MapGenericBits(mask, mapping) -> ACCESS_MASK
    if mask & RESERVED_BITS: reject
    mapped = mask & ~(GENERIC_READ | GENERIC_WRITE
                    | GENERIC_EXECUTE | GENERIC_ALL)
    if mask & GENERIC_READ:    mapped |= mapping.read
    if mask & GENERIC_WRITE:   mapped |= mapping.write
    if mask & GENERIC_EXECUTE: mapped |= mapping.execute
    if mask & GENERIC_ALL:     mapped |= mapping.all
    return mapped
```

All four generic bits are cleared before any is expanded, so a mask
naming several generics maps every one of them. <a id="cite-check.algorithm.all-generics-expand"></a>

**Virtual group resolution.** There is no enrichment step producing a
modified token. `S-1-3-4` and `S-1-5-10` are resolved at each lookup
instead, in the DACL walk, the SACL walk and conditional membership
alike. <a id="cite-check.algorithm.virtual-groups-per-lookup"></a> `S-1-5-10` resolves through the ordinary polarity rules against
`self_sid`, and `S-1-3-4` through the ordinary polarity rules against
the object's owner SID. Both are computed once per walk — the owner is
fixed while the polarity is per ACE — so each carries its allow and
deny answers together.

**`EvaluateSACL`** walks in a fixed order per ACE: SID match with deny
polarity, then object-type scoping against the tree, then the
condition, then the mask overlap against `mapped_desired`. <a id="cite-check.algorithm.sacl-ace-check-order"></a> Audit ACEs
need all four; alarm ACEs deliberately skip the overlap test and
contribute their mask on a SID match alone. Inherit-only ACEs are
skipped throughout. <a id="cite-check.algorithm.sacl-inherit-only-skipped"></a>

**`synthetic_sd`** builds a CAAP rule's descriptor from the original's
owner and optional group with the rule's DACL substituted, and the
SACL copied with every scoped policy ACE stripped — which is what
prevents recursion. The MIC and PIP labels are preserved, so a rule is
evaluated under the same mandatory constraints as the object. The
control bits and the stripped SACL's revision are recomputed rather
than copied. <a id="cite-check.algorithm.synthetic-recomputes-control-bits"></a>

<a id="trm-3-8-10-6"></a>

## Provenance masks

| Variable | Set at | Meaning |
|---|---|---|
| `security_granted` | Step 4 | `SeSecurityPrivilege` granted `ACCESS_SYSTEM_SECURITY`. <a id="cite-check.algorithm.provenance.security"></a> |
| `backup_granted` | Step 4 | `SeBackupPrivilege` granted read bits. <a id="cite-check.algorithm.provenance.backup"></a> |
| `restore_granted` | Step 4 | `SeRestorePrivilege` granted write and metadata bits. <a id="cite-check.algorithm.provenance.restore"></a> |
| `take_ownership_granted` | Step 9 | `SeTakeOwnershipPrivilege` granted `WRITE_OWNER`. <a id="cite-check.algorithm.provenance.take-ownership"></a> |
| `relabel_granted` | Step 5 | `SeRelabelPrivilege` added `WRITE_OWNER` to the MIC allowed set. <a id="cite-check.algorithm.provenance.relabel"></a> |

Each records which bits that privilege contributed, and step 13
compares each against the requested mask and the final result.

---

# File security

_Peios Kernel / Internals / KACS / File security_

> Find the Peios kernel articles about file security.

Use these articles to understand file security in the Peios kernel.

- [The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md>)
- [KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md>)
- [Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md>)
- [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md>)
- [Descriptor storage and caching](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md>)
- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)
- [The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md>)
- [Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md>)
- [Byte-Range Locks](</kernel/internals/kacs/file-security/byte-range-locks.md>)
- [Leases](</kernel/internals/kacs/file-security/leases.md>)
- [Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md>)

---

# The Handle Model

_Peios Kernel / Internals / KACS / File security_

> FACS is the file-specific enforcement surface of KACS — mount policy, scope, how a handle is acquired, and stacked backing files.

<a id="trm-3-9-1"></a>

FACS, the File Access Control Shim, is the file-specific enforcement
surface of KACS. It replaces Linux DAC — UID, GID and mode-bit checks
— with security-descriptor evaluation on files.

Enforcement follows the handle pattern. AccessCheck runs once at open
time, the granted mask is cached on the file description, and later
operations test the cached mask:

```
(fd.granted & required) == required ? allow : deny
```

The mask is set once and never modified, and it is immutable for the
descriptor's whole lifetime regardless of any later descriptor change. <a id="cite-facs.handle.mask-immutable"></a>
A file's DACL can be rewritten while a process holds it open, and that
process keeps the rights it was granted. A few operations use a live
AccessCheck instead; [Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>) lists them.

A second immutable mask is stamped alongside it: the **continuous
audit mask** ([Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>)), which every use-time operation consults to
decide whether to emit a per-operation audit event. It travels with
the granted mask through every path described below. <a id="cite-facs.handle.audit-mask-stamped"></a>

<a id="trm-3-9-1-1"></a>

## Mount policy

Every mounted filesystem exposes exactly one FACS mount-policy class,
scoped to the kernel superblock object rather than to a pathname or a
bind mount — several paths or bind mounts over one superblock all
observe the same class. <a id="cite-facs.handle.policy-per-superblock"></a>

**`unmanaged`** puts the mount outside the handle model entirely: no
granted mask is stamped on its file descriptions. <a id="cite-facs.handle.unmanaged-no-mask"></a> **`facs_deny_missing`**
is FACS-managed and denies access where a descriptor is missing.
**`facs_synthesize_ephemeral`** synthesises missing descriptors and
caches them in memory only. **`facs_synthesize_persistent`**
synthesises them and writes them back immediately. The three `facs_*`
classes are the only managed ones.

The default classifier is conservative. Hardcoded pseudo-filesystems —
`/proc`, `/sys`, nullfs — are `unmanaged`. Filesystems that cannot
reliably store the canonical descriptor xattr are
`facs_synthesize_ephemeral`: ramfs, FAT, exFAT, NFS client mounts,
ISO9660, and cgroup2. StrataFS is fixed at `facs_deny_missing`. Everything else
— tmpfs, squashfs, ext4, btrfs — defaults to `facs_deny_missing`
unless a trusted policy agent adopts it.

Userspace cannot set a superblock to `unmanaged` through the public
ABI; the class is reserved for the kernel classifier and the hardcoded
rules. Attempting to set a policy on a magic-derived `unmanaged`
superblock fails with `EOPNOTSUPP`, and so does attempting to change
StrataFS's. <a id="cite-facs.handle.unmanaged-not-settable"></a>

<a id="trm-3-9-1-2"></a>

## Scope

The sole-authority claim covers local FACS-managed filesystems. It
does not cover:

- `O_PATH` descriptors, which are not managed;
- NFS client mounts, which are ephemeral-synthesising and retain dual
  authority with the server;
- `/proc`, which is unmanaged and PIP-protected; or
- `/sys`, which is unmanaged and carries a hardcoded rule instead —
  writes there require Administrators or SYSTEM, enforced against a
  built-in descriptor. <a id="cite-facs.handle.sysfs-write-builtin-descriptor"></a>

Descriptors for processes obtained through `pidfd` bypass FACS at open
as well. <a id="cite-facs.handle.pidfd-bypasses-open"></a>

<a id="trm-3-9-1-3"></a>

## Handle acquisition

A descriptor carries its granted mask through every acquisition path,
and transfer is an intentional capability-delegation mechanism.

- `dup`/`dup3` and `fork` produce the same open file description and
  therefore the same rights; <a id="cite-facs.handle.dup-fork-same-rights"></a>
- descriptors without `FD_CLOEXEC` survive exec unchanged; <a id="cite-facs.handle.exec-preserves-mask"></a>
- `SCM_RIGHTS` transfers the descriptor as a capability token, with
  possession as authorization and no re-check of the receiver's
  identity; and <a id="cite-facs.handle.scm-rights-capability"></a>
- `pidfd_getfd()` is gated by an AccessCheck for `PROCESS_DUP_HANDLE`
  against the target process, after which the caller receives the
  descriptor with its full mask. <a id="cite-facs.handle.pidfd-getfd-gate"></a>

The security boundary is at open time. Every subsequent transfer
carries the mask unchanged.

This means mandatory subject policy — MIC and PIP — is evaluated once,
at open, against the opener. <a id="cite-facs.handle.mic-pip-at-open"></a> A high-integrity process that opens a
file and passes the descriptor to a low-integrity one has effectively
delegated its access. That is the handle model: authority is on the
handle, not on the holder.

<a id="trm-3-9-1-4"></a>

## Stacked backing files

When a stacking filesystem creates a kernel-private backing file for a
managed user-visible file, the outer file's granted and continuous
audit masks are captured into the backing-file blob, and the backing
file's ordinary blob receives that exact snapshot when the provider is
opened. <a id="cite-facs.handle.backing-snapshot-captured"></a> No new AccessCheck runs against the task executing the
stacking filesystem. <a id="cite-facs.handle.backing-no-new-accesscheck"></a>

The inheritance is deliberately narrow. It is admitted only through
the kernel's typed backing-file allocation path, only from a managed
non-`O_PATH` outer file, and it retains no reference to that outer
file — only the values. <a id="cite-facs.handle.backing-admission-narrow"></a> It is not a general snapshot-cloning
mechanism.

An active StrataFS copy-up context takes precedence: a backing open
that does not match its exact object and phase does not fall back to
inherited authority. <a id="cite-facs.handle.copy-up-context-precedence"></a> When an exactly-bound copy-up backing file is
adopted by the outer descriptor, the outer snapshot is installed into
both blobs as a single transition, after which the backing file
behaves like any other stacked open.

For an OverlayFS provider, this handoff also reaches the exact private
backing files opened beneath the staged file. KACS validates the bounded
chain before changing any snapshot, then copies the original outer handle's
granted and continuous-audit masks into both blobs of every admitted file.
The handoff runs after the staged open and before publication. It does not
relax the active copy-up context's object and phase checks.

The user-visible operation is checked and continuously audited once,
against the outer handle. Immediate provider re-entry through
`security_file_permission` or `security_mmap_file` neither repeats the
caller authorization nor emits a second caller audit event. <a id="cite-facs.handle.no-duplicate-provider-check"></a> The
backing file keeps the snapshot for later descriptor-local
enforcement, including `mprotect()` after a stacked mmap, and the
`mmap_backing_file` handoff verifies that the outer, backing and
captured snapshots still agree before the provider mapping is
installed. <a id="cite-facs.handle.mmap-backing-verifies-agreement"></a>

This suppresses duplicate *KACS* authorization only. It bypasses
nothing else — not another LSM, not filesystem errors, not read-only
mounts, immutable state, quota, space, I/O, or format validation. <a id="cite-facs.handle.backing-suppresses-kacs-only"></a>

## Operational consequences

Treat a transferred descriptor as a capability carrying its established
rights. Passing it to a less privileged process does not rerun the original
open against the receiver's token. Fork can retain those open descriptions;
exec retains descriptors without close-on-exec. Review descriptor inheritance
as part of a launcher or request broker's authority design.

Changing a descriptor, token, or central policy does not retrospectively
revoke that cached file-handle grant. Conversely, losing a token privilege
does not prove an old descriptor lost its usable rights. Test changed policy
with fresh opens. Mappings have their own creation-time checks and page
permissions, not a fresh policy decision for every memory access.

An `O_PATH` handle does not carry ordinary data-access authority; descriptor
management uses its documented live checks. Append-only authority does not
authorize truncation or shared writable mapping. A remote filesystem can also
apply server-side authority after the local check. These boundaries belong
to [use-time semantics](/kernel/internals/kacs/file-security/use-time-semantics.md)
and [legacy-open compatibility](/kernel/internals/kacs/file-security/legacy-open-compatibility.md),
not a general promise that every operation consults only one immutable mask.

---

# KACS-Native Open

_Peios Kernel / Internals / KACS / File security_

> Opening a file by naming every right up front — handle modes, rights granted through the parent, share access, create dispositions, the creator's access and what the open reports.

<a id="trm-3-9-2"></a>

> [!IMPORTANT]
> The [open-interface comparison](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6) records unresolved differences and the [limited pinned-source findings](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6-1) applied here. Creator-SD rejection, the accepted create-option bits, and native-open versus SD-query no-follow behavior were checked in source; the other differences remain unresolved. No runtime test or historical release boundary is established.

`kacs_open` takes an explicit desired access mask. The caller names
every right it will need — `FILE_READ_DATA`, `FILE_WRITE_DATA`,
`WRITE_DAC`, `READ_CONTROL`, any combination — and AccessCheck
evaluates the whole requested mask at open. If every requested right
is granted the descriptor's mask is set to the requested mask; if any
is denied, the open fails. <a id="cite-facs.open.strict-all-or-nothing"></a> This is the **strict** mode, in contrast to
the legacy path's subset behaviour ([Legacy Open Compatibility](</kernel/internals/kacs/file-security/legacy-open-compatibility.md#trm-3-9-3>)).

`MAXIMUM_ALLOWED` asks for everything the caller may have. Any
concrete bits named with it have to be granted; the cached mask is
then the full computed maximum rather than the requested set. <a id="cite-facs.open.maximum-allowed-computes-max"></a>
`MAXIMUM_ALLOWED` may also be named alone. <a id="cite-facs.open.maximum-allowed-alone"></a> The maximum includes
the rights granted through the parent directory, described below, and
excludes the rights a read-only file withholds ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

A caller reads back what an open was granted with `kacs_query_open`,
which reports the cached mask, the open's share access, and whether the
file is delete-pending. <a id="cite-facs.open.query-open"></a> It is how a caller learns the result of a
`MAXIMUM_ALLOWED` open. The query needs no right: it reveals only what
the descriptor already carries. It fails with `EOPNOTSUPP` on an
unmanaged descriptor, including an `O_PATH` one.

<a id="trm-3-9-2-1"></a>

## Handle modes <a id="cite-facs.open.handle-modes"></a>

A Linux open file has a mode — readable, writable, or neither — which
the VFS uses for its own accounting, such as write access to an
executable and file leases. A native open derives that mode from the
rights it is granted: `FILE_READ_DATA` gives `FMODE_READ`, either
write right gives `FMODE_WRITE`, and `FILE_EXECUTE` gives `FMODE_EXEC`,
which enables `execveat(fd, "", ..., AT_EMPTY_PATH)`. <a id="cite-facs.open.execute-only-handle"></a>

An open granted none of these is a **control handle**: a managed
descriptor with no data mode, carrying only metadata, security or
delete rights. <a id="cite-facs.open.control-handle"></a> It can read attributes, read and change the
security descriptor, set a delete disposition, rename, and take part in
share checks. It cannot read or write the file's contents. No native
open needs to name a data right to obtain a descriptor. <a id="cite-facs.open.no-required-data-right"></a>

The mode is chosen **before** the file is opened, so that the VFS never
takes write access, read accounting or a lease break for an open that
does not hold the matching right. For an explicit mask the mode follows
the requested bits. For `MAXIMUM_ALLOWED`, KACS first evaluates the
maximum against the file's current descriptor and takes the mode from
the data rights that maximum contains. <a id="cite-facs.open.mode-before-open"></a>

The open hook then runs the authoritative check, as for every open. If
the descriptor changed between the two evaluations, the hook's result
stands. A strict request that is now denied fails as any denied open
does. A `MAXIMUM_ALLOWED` open is stamped with the new maximum, less
any data right its mode cannot exercise, so that `kacs_query_open`
never reports a right the descriptor cannot use. <a id="cite-facs.open.hook-authoritative"></a>

A `MAXIMUM_ALLOWED` open granted a write right takes write access like
any writer. Such an open of a file being executed fails with `ETXTBSY`,
and it breaks other holders' read leases.

<a id="trm-3-9-2-2"></a>

## Directories

Directory rights share bit positions with file data rights:
`FILE_LIST_DIRECTORY` is `FILE_READ_DATA` (0x0001), `FILE_ADD_FILE` is
`FILE_WRITE_DATA` (0x0002), and `FILE_ADD_SUBDIRECTORY` is
`FILE_APPEND_DATA` (0x0004). A directory open with `FILE_LIST_DIRECTORY`
is opened `FMODE_READ`; a directory open without it is a control
handle. <a id="cite-facs.open.dir-list-mode"></a>

The two write aliases are not cacheable directory handle rights,
though. `kacs_open` rejects a desired mask naming `FILE_ADD_FILE`,
`FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD` on a directory with
`EOPNOTSUPP`. <a id="cite-facs.open.dir-write-aliases-eopnotsupp"></a> Those are parent-directory authorization rights for
namespace operations, evaluated live at the operation, not rights a
handle carries.

<a id="trm-3-9-2-3"></a>

## Special nodes and symlinks

Existing FIFOs, pathname socket nodes, and character and block device
nodes on managed mounts are ordinary filesystem file objects for
authorization: the file object type, the file right mapping, and the
file GenericMapping for metadata, standard and generic rights. <a id="cite-facs.open.special-nodes-are-file-objects"></a>

A special node still has to be opened with a data right, because its
driver decides what an open without one means; a FIFO refuses it. A
native open of a special node granted no data right fails with
`EINVAL`. <a id="cite-facs.open.special-nodes-need-data-right"></a> `FILE_EXECUTE` is not a valid data substitute for them — a
`kacs_open` naming it on such a node fails closed. <a id="cite-facs.open.execute-not-valid-on-special-nodes"></a> The Linux object
implementation may still impose its own device- or
filesystem-specific denial after KACS has authorized the file object.

Symlink objects are file objects for `kacs_get_sd`, `kacs_set_sd` and
`readlink`, but they are not opened as terminal objects by
`kacs_open`. Following is the default resolution behaviour, and
`AT_SYMLINK_NOFOLLOW` fails with `ELOOP`. <a id="cite-facs.open.symlink-nofollow-eloop"></a> This differs deliberately
from `kacs_get_sd` and `kacs_set_sd`, where the same flag resolves the
symlink object itself.

<a id="trm-3-9-2-8"></a>

## Rights granted through the parent <a id="cite-facs.open.parent-grants"></a>

Two rights may be granted by the parent directory when the file's own
descriptor withholds them, as NTFS grants them (MS-FSA 2.1.5.1.2.1):

- **`DELETE`** is granted if the parent grants `FILE_DELETE_CHILD`. <a id="cite-facs.open.delete-through-parent"></a>
- **`FILE_READ_ATTRIBUTES`** is granted if the parent grants
  `FILE_LIST_DIRECTORY`. A caller who may list a directory may already
  see what its entries' attributes would show. <a id="cite-facs.open.read-attributes-through-parent"></a>

AccessCheck runs first against the file. For each of these two rights
that it does not grant, it runs again against the parent directory for
the parent right. The parent is the directory the open resolved the
file through, so for a file with several hard links it is the parent
of the link that was opened. <a id="cite-facs.open.parent-is-opened-link"></a> A `MAXIMUM_ALLOWED` open includes
whichever of the two the parent grants.

The same pair of checks governs every other operation that deletes or
reads attributes by name: unlink, rmdir and rename by path, delete on
close, superseding a file, and `stat` by path ([Use-Time
Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-2>)). <a id="cite-facs.open.delete-fallback"></a>

<a id="trm-3-9-2-9"></a>

## Share access <a id="cite-facs.open.share-access"></a>

Every open of a regular file or directory on a managed mount takes part
in NT share-mode checking ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10>)). A native open
states the sharing it allows in `kacs_open_how.share_access`, read only
when `flags` carries `KACS_OPEN_SHARE_ACCESS`:

| Value | Name | Others may open with |
|---|---|---|
| 0x1 | `KACS_FILE_SHARE_READ` | `FILE_READ_DATA` or `FILE_EXECUTE` |
| 0x2 | `KACS_FILE_SHARE_WRITE` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| 0x4 | `KACS_FILE_SHARE_DELETE` | `DELETE` |

Without the flag the open shares all three, as a legacy open does, and
`share_access` has to be zero. <a id="cite-facs.open.share-default-all"></a> An open that conflicts with
another fails with `EBUSY` and the status `KACS_STATUS_SHARING_VIOLATION`.

<a id="trm-3-9-2-4"></a>

## Create dispositions <a id="cite-facs.open.create-dispositions"></a>

| Value | Name | If it exists | If it does not |
|---|---|---|---|
| 0 | `FILE_SUPERSEDE` | Delete and recreate | Create |
| 1 | `FILE_OPEN` | Open | Fail |
| 2 | `FILE_CREATE` | Fail | Create |
| 3 | `FILE_OPEN_IF` | Open | Create |
| 4 | `FILE_OVERWRITE` | Truncate to zero | Fail |
| 5 | `FILE_OVERWRITE_IF` | Truncate to zero | Create |

`FILE_SUPERSEDE` deletes the existing name and creates a new file
under it, requiring `DELETE` on the existing file — or
`FILE_DELETE_CHILD` on the parent — together with `FILE_ADD_FILE` on
the parent. <a id="cite-facs.open.supersede-rights"></a> The existing file's other opens have to share `DELETE`,
and a read-only or delete-pending file cannot be superseded. The new
file gets a new inode and a new descriptor, inherited or
caller-supplied. The superseded pathname is broken away from the old
hardlink set and names the new inode; other pre-existing hardlinks
continue to name the old inode, and already-open descriptors still
reference it. <a id="cite-facs.open.supersede-new-inode"></a>

`FILE_OVERWRITE` truncates in place — same inode, same descriptor,
hardlinks preserved — and requires `FILE_WRITE_DATA`. <a id="cite-facs.open.overwrite-in-place"></a>

On an `unmanaged` mount, `FILE_OPEN` and `FILE_OPEN_IF` succeed and
return an unmanaged descriptor with no stamped mask rather than
failing; the creating dispositions fail with `EOPNOTSUPP`. <a id="cite-facs.open.unmanaged-create-eopnotsupp"></a>

<a id="trm-3-9-2-5"></a>

## Create options

| Value | Name | Description |
|---|---|---|
| 0x0001 | `KACS_CREATE_OPT_DIRECTORY` | The target has to be a directory. When creating, create a directory rather than a regular file; when opening an existing non-directory, fail with `ENOTDIR`. <a id="cite-facs.open.create-opt-directory"></a> |
| 0x0002 | `KACS_CREATE_OPT_DELETE_ON_CLOSE` | Mark the file for deletion when this open closes. Requires `DELETE`, which may come through the parent. |

All other bits are reserved and have to be zero; a nonzero reserved
bit fails with `EINVAL`. <a id="cite-facs.open.reserved-create-option-einval"></a>

Delete-on-close is NT's: the obligation belongs to the open, and when
the open closes the file becomes **delete-pending**. The name is removed
at the last close of any open of the file, from any process
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-3>)). <a id="cite-facs.open.delete-on-close-nt"></a> `dup()`, `fork()` and `SCM_RIGHTS`
preserve the obligation because they preserve the open file
description; it is discharged when the description's last reference
closes. <a id="cite-facs.open.delete-on-close-lineage"></a> `kacs_set_disposition` with `KACS_DISPOSITION_ON_CLOSE` sets or
clears it on an open that has `DELETE`.

Delete-on-close applies to regular files and directories. A directory
is removed only if it is empty when it is deleted. <a id="cite-facs.open.delete-on-close-directories"></a> A read-only
regular file cannot be opened with delete-on-close: the open fails with
`EPERM` and the status `KACS_STATUS_CANNOT_DELETE`.

<a id="trm-3-9-2-6"></a>

## Caller-supplied descriptors

The descriptor format and size bound are defined in [SD Structure](https://learn.peios.org/specifications/pcds/security-descriptor/structure#binary-format).

When a disposition results in a new file the caller may supply a
descriptor. A null pointer with zero length means the new file's
descriptor is inherited from the parent directory through the
inheritance algorithm. <a id="cite-facs.open.null-descriptor-inherits"></a>

Supplying one on a branch that opens an *existing* object is invalid
input rather than something silently ignored. `FILE_OPEN_IF`
resolving to an existing object fails with `EINVAL`, and so do
`FILE_OVERWRITE` and the existing-object branch of
`FILE_OVERWRITE_IF`, since those retain the existing inode and its
descriptor. <a id="cite-facs.open.supplied-on-existing-einval"></a> `FILE_OPEN` with a descriptor supplied fails with
`EOPNOTSUPP`. <a id="cite-facs.open.supplied-with-file-open-eopnotsupp"></a>

Creator-supplied descriptors are validated at create time. An owner
SID has to be the caller's own or a token group marked
`SE_GROUP_OWNER`, unless `SeRestorePrivilege` is enabled, in which
case any owner is allowed. <a id="cite-facs.open.supplied-owner-constraint"></a> A supplied SACL is treated as a full SACL
input rather than a label-only fragment, and therefore requires
`SeSecurityPrivilege`. <a id="cite-facs.open.supplied-sacl-requires-privilege"></a> If that SACL carries an explicit mandatory
label ACE, the label also has to satisfy the ordinary label-write
constraint: at or below the caller's integrity level, unless
`SeRelabelPrivilege` is held. <a id="cite-facs.open.supplied-label-constraint"></a>

Generic rights in the descriptor's ACEs are mapped to file rights when
the descriptor is stored, whether it was supplied, inherited or taken
from the token's default DACL ([The Set-Security Interface](</kernel/internals/kacs/file-security/the-set-security-interface.md#trm-3-9-6-7>)).

<a id="trm-3-9-2-10"></a>

## The creator's access <a id="cite-facs.open.creator-access"></a>

The parent's create rights authorize the creation: `FILE_ADD_FILE` or
`FILE_ADD_SUBDIRECTORY`, together with the supersede rules above. The
handle a creating open returns is then granted the access it asked
for, as in Windows, even where the new file's descriptor would not
grant it to its creator. <a id="cite-facs.open.creator-granted-requested"></a> A creator can therefore create a file with a
restrictive descriptor and still write it, in one step, and a folder
can accept files whose inherited permissions exclude the people who put
them there.

The grant replaces only the **normal discretionary pass**. The kernel
computes the new object's descriptor first, then runs the strict check
against it, with the normal DACL walk treated as granting the creator
everything. <a id="cite-facs.open.creator-normal-pass-only"></a> Every other layer still evaluates the new descriptor and
can refuse:

- the mandatory integrity label and PIP;
- the restricted-token pass;
- confinement, which stays absolute ([Application Confinement](</kernel/internals/kacs/access-check/application-confinement.md#trm-3-8-6>));
- central access and auditing policy; and
- privilege-only rights, such as `ACCESS_SYSTEM_SECURITY`.

So a low-integrity creator under an inherited high-integrity label
cannot write what it created, and a confined application cannot write
outside what its confinement identity is granted. A `MAXIMUM_ALLOWED`
creating open is granted every right of the object type that those
layers allow. A refused check rolls the creation back — the newly
created file or directory is removed — and the syscall fails. <a id="cite-facs.open.failed-check-rolls-back"></a>

The grant belongs to the creating open alone. `FILE_OPEN_IF` or
`FILE_OVERWRITE_IF` that finds an existing object is an ordinary open,
and every later open of the new object is checked against its
descriptor as normal. <a id="cite-facs.open.creator-grant-only-when-creating"></a>

<a id="trm-3-9-2-11"></a>

## Ancestor pinning

`KACS_OPEN_PIN_ANCESTORS` pins the opened file's ancestor directories:
while the open lasts, none of them can be renamed or removed by anyone
([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-6>)). It requires `SeLockParentagePrivilege` enabled;
without it the open fails with `EPERM`. <a id="cite-facs.open.pin-requires-privilege"></a>

<a id="trm-3-9-2-12"></a>

## Lease keys

With `KACS_OPEN_LEASE_KEY`, `kacs_open_how.lease_key` and `lease_fd`
identify the opener to the lease manager given by `lease_fd`. Opening a
file does not break leases that the same manager holds under the same
key ([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12>)). <a id="cite-facs.open.lease-key-exemption"></a> `lease_fd` has to be a lease-manager
descriptor, or the open fails with `EBADF`.

<a id="trm-3-9-2-7"></a>

## Modes and status

`kacs_open_how` carries no POSIX mode field, so the raw Linux inode
mode for native creation is fixed: `0600` for regular files, `0700`
for directories. <a id="cite-facs.open.fixed-create-modes"></a> These are compatibility metadata only — and if Linux
DAC ever denies an operation KACS would have authorized, the operation
fails closed.

Native creation does not create FIFOs, socket nodes, device nodes or
symlinks. <a id="cite-facs.open.no-native-special-creation"></a> Those stay on the Linux namespace APIs — `mknod()`,
`mkfifo()`, Unix `bind()` to a path — governed by the namespace hooks.
NTFS is excluded from native creation entirely. <a id="cite-facs.open.ntfs-excluded"></a>

`kacs_open_how` is size-versioned. A caller passes the size it was
built with — 32 bytes for the original layout, 56 bytes with the lease
fields — and fields beyond that size read as zero. A size below 16
bytes fails with `EINVAL`. <a id="cite-facs.open.how-size-versioned"></a> New fields are added at the end, behind a
flag, so that an existing caller's meaning never changes.

The syscall reports what happened through `status_out`: created,
opened, overwritten, or superseded. `KACS_STATUS_SUPERSEDED` is used
only when an existing object was actually replaced — a
`FILE_SUPERSEDE` that finds no target and simply creates one reports
`KACS_STATUS_CREATED`. <a id="cite-facs.open.status-superseded-only-if-replaced"></a>

When the open fails for a reason one errno cannot tell apart,
`status_out` also names the NT condition: <a id="cite-facs.open.failure-status"></a>

| Status | Errno | Condition |
|---|---|---|
| `KACS_STATUS_SHARING_VIOLATION` | `EBUSY` | Another open's share access conflicts with this one. |
| `KACS_STATUS_DELETE_PENDING` | `EBUSY` | The file is delete-pending. |
| `KACS_STATUS_CANNOT_DELETE` | `EPERM` | Delete-on-close on a read-only file. |

On any other failure `status_out` is left unwritten.

---

# Legacy Open Compatibility

_Peios Kernel / Internals / KACS / File security_

> Linux open flags cannot express WRITE_DAC or READ_CONTROL — how FACS maps them to core and compat rights, and what O_PATH does.

<a id="trm-3-9-3"></a>

> [!IMPORTANT]
> The open-interface references contain [unresolved documentation differences](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md#trm-3-d-6). Read that note alongside this page; no runtime behavior or release boundary has been established for those differences.

Linux's `open()` and `openat()` cannot express rights like `WRITE_DAC`
or `READ_CONTROL`. FACS maps the open flags to a **core** set of
required rights plus a **compat** set of POSIX-expected ones, and
evaluates both in a single AccessCheck.

<a id="trm-3-9-3-1"></a>

## Core rights <a id="cite-facs.legacy.core-rights"></a>

The core set is the minimum for a usable descriptor, and the open
fails if any of it is denied.

For regular files, device nodes, FIFOs and pathname sockets:

| Flags | Core rights |
|---|---|
| `O_RDONLY` | `FILE_READ_DATA \| FILE_READ_ATTRIBUTES` |
| `O_WRONLY` | `FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |
| `O_RDWR` | `FILE_READ_DATA \| FILE_WRITE_DATA \| FILE_READ_ATTRIBUTES` |

For directories, `O_RDONLY` gives
`FILE_READ_ATTRIBUTES | FILE_TRAVERSE`. Directory core deliberately
excludes `FILE_LIST_DIRECTORY`, so a directory opened `O_RDONLY` can
be used for `fchdir()` and `fstat()` without listing permission;
listing is a compat right. <a id="cite-facs.legacy.directory-core-excludes-list"></a>

Two modifiers apply in order. `O_APPEND` replaces `FILE_WRITE_DATA`
with `FILE_APPEND_DATA`, and `O_TRUNC` adds `FILE_WRITE_DATA`. Given
both, the replacement happens first and the re-addition second, so
core ends up with `FILE_APPEND_DATA` and `FILE_WRITE_DATA` together. <a id="cite-facs.legacy.append-trunc-order"></a>

`FILE_READ_ATTRIBUTES` is always core: a descriptor granting data
access but denying attribute reads is not openable through the legacy
APIs at all. <a id="cite-facs.legacy.read-attributes-always-core"></a>

<a id="trm-3-9-3-2"></a>

## Compat rights <a id="cite-facs.legacy.compat-rights"></a>

Requested alongside core and silently omitted where denied:
`FILE_READ_EA` for `fgetxattr()`; `READ_CONTROL` for reading the
descriptor; `FILE_WRITE_ATTRIBUTES` for `futimens()`; `FILE_WRITE_EA`
for `fsetxattr()`; `FILE_WRITE_DATA` on `O_APPEND` opens so
`ftruncate()` works where the descriptor allows it; `WRITE_DAC`,
because POSIX permits `fchmod()` on any descriptor; `WRITE_OWNER`, for
`fchown()` on the same grounds; `SYNCHRONIZE`;
`FILE_LIST_DIRECTORY`, enabling `readdir()` on directory descriptors;
and `FILE_EXECUTE`, enabling `fexecve()` on regular files.

<a id="trm-3-9-3-3"></a>

## The flow

The full requested mask is core plus compat. AccessCheck returns the
subset the descriptor allows. If every core right is present the
actual granted mask — which may include all, some or none of compat —
is stamped on the descriptor; otherwise the open fails with `EACCES`. <a id="cite-facs.legacy.core-missing-eacces"></a>

Both open paths run the same pipeline with different success
criteria. Native open is **strict**: everything requested has to be
granted. Legacy open is **subset**: only core has to be fully present.

<a id="trm-3-9-3-5"></a>

## Sharing, deletion and read-only <a id="cite-facs.legacy.share-participation"></a>

A legacy open of a regular file or directory on a managed mount takes
part in NT share-mode checking. It shares read, write and delete, so
legacy opens never conflict with each other, but it fails with `EBUSY`
where a native open has denied its class of access ([Sharing and
Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-1>)). It also fails with `EBUSY` if the file is delete-pending,
as an `O_PATH` open of a delete-pending file does. <a id="cite-facs.legacy.delete-pending-ebusy"></a>

A legacy open for writing of a read-only regular file fails with
`EACCES`, and the compat write rights are omitted from a read-only
open of one ([Special Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-2>)). <a id="cite-facs.legacy.readonly"></a>

`FILE_READ_ATTRIBUTES`, which every legacy open requires, may be
granted through the parent's `FILE_LIST_DIRECTORY` ([KACS-Native
Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

<a id="trm-3-9-3-4"></a>

## O_PATH

`O_PATH` descriptors are not FACS-managed. The VFS opens them without
calling the open hook, so they carry no granted mask and are left
unmanaged. KACS checks one thing as they open: an `O_PATH` open of a
delete-pending file fails with `EBUSY`. <a id="cite-facs.legacy.o-path-unmanaged"></a> They serve as namespace
anchors for the `*at()` syscalls.

`fstat()` and `fstatfs()` on them are allowed unconditionally. <a id="cite-facs.legacy.o-path-fstat-unconditional"></a>
`fchdir()` runs a live `FILE_TRAVERSE` check at use time. <a id="cite-facs.legacy.o-path-fchdir-live"></a> `fchmod()`,
`fchown()`, `fgetxattr()`, `fsetxattr()`, `ioctl()` and `mmap()` are
denied with `EBADF` — though `futimens()` currently has no such guard. <a id="cite-facs.legacy.o-path-ebadf"></a>
`execveat(fd, "", ..., AT_EMPTY_PATH)` has exec permission enforced by
a live AccessCheck in the bprm hook, and `kacs_get_sd` and
`kacs_set_sd` with `AT_EMPTY_PATH` likewise run live, which gives
race-free object identity without snapshot authorization. <a id="cite-facs.legacy.o-path-live-checks"></a>

That `fstat()` is unconditional means `FILE_READ_ATTRIBUTES` is not
authoritative for attribute confidentiality. In practice size,
timestamps and inode number are rarely confidential. The descriptor
itself *is* protected: `kacs_get_sd` on an `O_PATH` handle performs a
live check.

---

# Use-Time Semantics

_Peios Kernel / Internals / KACS / File security_

> Every operation on an open descriptor is a mask check against the granted mask — data, metadata, traversal, append-only, fcntl and ioctl.

<a id="trm-3-9-4"></a>

Every operation on an open descriptor is a mask check against the
granted mask, with one exception: `execveat(AT_EMPTY_PATH)` uses a
live AccessCheck. <a id="cite-facs.use.mask-check-per-operation"></a>

<a id="trm-3-9-4-1"></a>

## Data operations <a id="cite-facs.use.data-operations"></a>

| Operation | Required right |
|---|---|
| Read | `FILE_READ_DATA` |
| Sequential write, no append intent | `FILE_WRITE_DATA` |
| Append-intent write (`O_APPEND` descriptor or `RWF_APPEND`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| Positioned write, or a no-append override | `FILE_WRITE_DATA` — denied on append-only descriptors |
| Directory listing | `FILE_LIST_DIRECTORY` |
| `ftruncate` | `FILE_WRITE_DATA` |
| `fallocate` allocation (`ALLOCATE_RANGE`, with or without `KEEP_SIZE`) | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `fallocate` mutation (`PUNCH_HOLE`, `ZERO_RANGE`, `COLLAPSE_RANGE`, `INSERT_RANGE`, `UNSHARE_RANGE`, `WRITE_ZEROES`) | `FILE_WRITE_DATA` |
| `mmap PROT_READ` | `FILE_READ_DATA` |
| `mmap PROT_WRITE \| MAP_SHARED` | `FILE_WRITE_DATA` — `FILE_APPEND_DATA` alone is insufficient <a id="cite-facs.use.mmap-shared-write-needs-write-data"></a> |
| `mmap PROT_WRITE \| MAP_PRIVATE` | `FILE_READ_DATA` — copy-on-write, no write to the file <a id="cite-facs.use.mmap-private-needs-read"></a> |
| `mmap PROT_EXEC` | `FILE_EXECUTE` |
| `mprotect` | As `mmap`, for the new protection flags |
| `flock LOCK_SH` / `F_RDLCK` | `FILE_READ_DATA` |
| `flock LOCK_EX` / `F_WRLCK` | `FILE_WRITE_DATA` or `FILE_APPEND_DATA` |
| `fsync` / `fdatasync` | `SYNCHRONIZE` <a id="cite-facs.use.fsync-requires-synchronize"></a> |

A `fallocate` mode outside the supported set fails closed, and
`PUNCH_HOLE` additionally requires `KEEP_SIZE`. <a id="cite-facs.use.fallocate-unsupported-mode-fails"></a>

Reads, writes, truncation and content-changing `fallocate` on a
regular file are also checked against other opens' byte-range locks
when they are issued, and fail with `EAGAIN` on a conflict ([Byte-Range
Locks](</kernel/internals/kacs/file-security/byte-range-locks.md#trm-3-9-11-2>)). Memory-mapped access is not.

<a id="trm-3-9-4-2"></a>

## Metadata operations <a id="cite-facs.use.metadata-operations"></a>

| Operation | Required right |
|---|---|
| `stat` / `lstat` / path `statx` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent <a id="cite-facs.use.stat-through-parent"></a> |
| `fstat` / descriptor `statx` | `FILE_READ_ATTRIBUTES` |
| `fstatfs` | `FILE_READ_ATTRIBUTES` |
| path and descriptor `file_getattr` | `FILE_READ_ATTRIBUTES`; by path, also through the parent |
| path and descriptor `file_setattr` | `FILE_WRITE_ATTRIBUTES` |
| `truncate` by pathname | `FILE_WRITE_DATA` |
| `chmod` / `fchmodat` / `fchmod` | `WRITE_DAC` <a id="cite-facs.use.chmod-requires-write-dac"></a> |
| `chown` / `lchown` / `fchownat` / `fchown` | `WRITE_OWNER` <a id="cite-facs.use.chown-requires-write-owner"></a> |
| `utimensat` / `utimes` / `futimens` | `FILE_WRITE_ATTRIBUTES` |
| `getxattr` / `lgetxattr` / `fgetxattr` | `FILE_READ_EA` |
| `setxattr` / `lsetxattr` / `removexattr` / `fsetxattr` / `fremovexattr` | `FILE_WRITE_EA` |
| `listxattr` / `llistxattr` / `flistxattr` | none <a id="cite-facs.use.listxattr-needs-no-right"></a> |
| get `security.peios.sattr` | `FILE_READ_ATTRIBUTES` |
| set or remove `security.peios.sattr` | `FILE_WRITE_ATTRIBUTES` |
| `access` / `faccessat` `F_OK` | `FILE_READ_ATTRIBUTES`, or `FILE_LIST_DIRECTORY` on the parent |
| `access` / `faccessat` `R_OK` | `FILE_READ_DATA` |
| `access` / `faccessat` `W_OK` | `FILE_WRITE_DATA` |
| `access` / `faccessat` `X_OK` | `FILE_EXECUTE` |

Descriptor-based `file_getattr` and `file_setattr` with `AT_EMPTY_PATH`
retain the open file through the operation and metadata cleanup. A concurrent
close cannot invalidate an operation that has already acquired its file
reference. This also covers unsupported-operation and other error paths.

Reads and writes of the canonical descriptor xattr are denied
unconditionally through the xattr hooks — `security.peios.sd`, or
`system.ntfs_security` on NTFS. All descriptor access goes through
`kacs_get_sd` and `kacs_set_sd`. POSIX ACL xattr writes are denied
unconditionally too, with `EOPNOTSUPP` rather than `EACCES` so that
probe-then-tolerate callers behave sensibly. <a id="cite-facs.use.posix-acl-write-eopnotsupp"></a>

The special-attributes xattr, `security.peios.sattr`, is not raw
storage either: KACS answers reads and writes of it itself, with the
attribute rights above and the value format in [Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13-1>). The signature xattr, `security.peios.sig`, is governed by
[Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>).

Path-based attribute reads may be granted through the parent:
a caller who may list a directory may read the attributes of its
entries, as a native open may ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

<a id="trm-3-9-4-3"></a>

## Directory traversal <a id="cite-facs.use.directory-traversal"></a>

Path resolution checks `FILE_TRAVERSE` on managed directory
components. A token holding `SeChangeNotifyPrivilege` bypasses the
intermediate checks, including on directories whose descriptor is
missing. <a id="cite-facs.use.change-notify-bypasses-traverse"></a>

Explicit changes of the current or root directory are not intermediate
resolution: `chdir()` and `chroot()` take a live `FILE_TRAVERSE` check
on the final directory, and the privilege bypass does not apply
([Privilege Catalogue](</kernel/internals/kacs/privileges/privilege-catalogue.md#trm-3-4-2>)). <a id="cite-facs.use.chdir-chroot-live-check"></a> An ordinary `fchdir()` checks the descriptor's cached mask;
an `O_PATH` `fchdir()` runs live. <a id="cite-facs.use.fchdir-cached-mask"></a>

<a id="trm-3-9-4-4"></a>

## Watch placement <a id="cite-facs.use.watch-placement"></a>

Placing a watch — `inotify_add_watch()`, `fanotify_mark()` on an
inode, `F_NOTIFY` — is a read of the object by other means: a watch on
a directory reveals the names of its children as they come and go, a
watch on a file reports its activity. Linux gates it on read
permission, but under KACS a bare `MAY_READ` never reaches a
descriptor (read rights are decided at open), so the `path_notify`
hook checks the read-class right live against the object's own
descriptor: `FILE_LIST_DIRECTORY` for a directory, `FILE_READ_DATA`
for anything else. A denial is `EACCES`, and `SeChangeNotifyPrivilege`
does not bypass it — that privilege covers traversal, not reading. <a id="cite-facs.use.watch-change-notify-no-bypass"></a>

Mount, filesystem and mount-namespace marks are not object watches and
have no single descriptor to check. Linux requires `CAP_SYS_ADMIN` for
them, and for the fanotify permission classes (`FAN_CLASS_CONTENT`,
`FAN_CLASS_PRE_CONTENT` — the ones whose holder can veto or delay
opens and reads system-wide); the capability switchboard ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>))
resolves that to `SeTcbPrivilege`, so these are TCB-only. <a id="cite-facs.use.fanotify-mount-marks-tcb"></a> PIP
dominance is not part of the decision: a permission-event holder
intercepts opens of the *object*, never the opening process, and a
holder that is by construction TCB dominates every process anyway.

<a id="trm-3-9-4-5"></a>

## Append-only enforcement <a id="cite-facs.use.append-only-enforcement"></a>

A handle carrying `FILE_APPEND_DATA` but not `FILE_WRITE_DATA` allows
only true append-intent writes. Append intent means the effective
write position is forced to end-of-file by `O_APPEND` or per-I/O
`RWF_APPEND`, and is not negated by `RWF_NOAPPEND` on the same
operation. <a id="cite-facs.use.append-intent-definition"></a> Requesting both `RWF_APPEND` and `RWF_NOAPPEND` together
fails with `EACCES`. <a id="cite-facs.use.append-noappend-conflict-eacces"></a>

Denied on such a handle: positioned writes without effective append
intent — `pwrite64`, `pwritev`, `pwritev2` with an explicit offset,
io_uring writes with an explicit offset, and AIO writes with an
offset; any write using `RWF_NOAPPEND`, since it can negate append
semantics inherited from `O_APPEND`; shared writable `mmap` and
`mprotect` upgrades to `PROT_WRITE`; and the `fallocate` mutation
modes. <a id="cite-facs.use.append-only-denied-set"></a>

<a id="trm-3-9-4-6"></a>

## fcntl <a id="cite-facs.use.fcntl"></a>

For `F_SETFL`, KACS evaluates the mutable status flags Linux accepts —
`O_APPEND`, `O_NONBLOCK`/`O_NDELAY`, `O_DIRECT`, `O_NOATIME`.
Clearing `O_APPEND` is denied on a handle with `FILE_APPEND_DATA` but
not `FILE_WRITE_DATA`; setting it is always allowed, being a privilege
reduction. <a id="cite-facs.use.setfl-clear-append-denied"></a> Adding `O_NOATIME` requires `FILE_WRITE_ATTRIBUTES` and
clearing it is always allowed. <a id="cite-facs.use.setfl-noatime"></a> Changing only `O_NONBLOCK`, `O_NDELAY`
or `O_DIRECT` needs no KACS right, though ordinary Linux validation
still applies. <a id="cite-facs.use.setfl-flags-need-no-right"></a>

These commands are descriptor-local and require no KACS right, and
none of them widens the cached mask: `F_CREATED_QUERY`; `F_DUPFD`,
`F_DUPFD_CLOEXEC` and `F_DUPFD_QUERY`, which preserve the same file
description and mask; `F_GETFD` and `F_SETFD`; `F_GETFL`; and the
async-notification set `F_GETOWN`, `F_GETOWN_EX`, `F_GETOWNER_UIDS`,
`F_GETSIG`, `F_SETOWN`, `F_SETOWN_EX` and `F_SETSIG`, where Linux pid
and signal validation still applies. <a id="cite-facs.use.fcntl-descriptor-local"></a>

These are object-state queries or mutations, checked against the
cached mask before Linux-specific validation:

| Command | Required right |
|---|---|
| `F_GETLK` / `F_GETLK64` / `F_OFD_GETLK` | Any data right |
| `F_GETLEASE` / `F_GETDELEG` | `FILE_READ_ATTRIBUTES` |
| `F_GETPIPE_SZ` | `FILE_READ_ATTRIBUTES` |
| `F_SETPIPE_SZ` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_SEALS` | `FILE_READ_ATTRIBUTES` |
| `F_ADD_SEALS` | `FILE_WRITE_ATTRIBUTES` |
| `F_GET_RW_HINT` / `F_GET_FILE_RW_HINT` | `FILE_READ_ATTRIBUTES` |
| `F_SET_RW_HINT` / `F_SET_FILE_RW_HINT` | `FILE_WRITE_ATTRIBUTES` |

Lock, lease and delegation commands — `F_SETLK`, `F_SETLKW`,
`F_SETLK64`, `F_SETLKW64`, `F_OFD_SETLK`, `F_OFD_SETLKW`,
`F_SETLEASE`, `F_SETDELEG` — pass through the fcntl hook so that the
later file-lock hook can enforce them against normalised `F_RDLCK`,
`F_WRLCK` or `F_UNLCK` values. <a id="cite-facs.use.fcntl-lock-passthrough"></a> An unknown lock type fails closed
there.

For `F_NOTIFY`, removing a watch — a zero event mask, ignoring
`DN_MULTISHOT` — requires nothing. Installing one with any known `DN_*`
event requires `FILE_LIST_DIRECTORY`. <a id="cite-facs.use.fcntl-notify-install"></a> Unknown `DN_*` bits on a managed
descriptor fail closed. <a id="cite-facs.use.fcntl-notify-unknown-bits"></a>

Unmanaged descriptors sit outside the handle check entirely, and an
unknown fcntl command on a managed one fails closed. <a id="cite-facs.use.unknown-fcntl-fails-closed"></a>

<a id="trm-3-9-4-7"></a>

## ioctl <a id="cite-facs.use.ioctl-classification"></a>

Known ioctls are classified by required right; an unclassified one is
allowed if the descriptor carries at least one data right. The 32-bit
compat aliases take the same right as their native command, including
`FS_IOC32_GETFLAGS`, `FS_IOC32_SETFLAGS`, `FS_IOC32_GETVERSION`,
`FS_IOC32_SETVERSION` and the compat preallocation commands. <a id="cite-facs.use.ioctl-compat-aliases"></a>

**Descriptor-local**, requiring nothing: `FIOCLEX` and `FIONCLEX`,
which change close-on-exec state; `FIONBIO`, which changes nonblocking
state; and `FIOASYNC`, which changes async notification state with
Linux and fops validation still applying. <a id="cite-facs.use.ioctl-descriptor-local"></a>

**Common VFS:**

| ioctl | Required right |
|---|---|
| `FIBMAP` | `FILE_READ_DATA` |
| `FIGETBSZ` | `FILE_READ_ATTRIBUTES` |
| `FIFREEZE` / `FITHAW` | `FILE_WRITE_ATTRIBUTES` |
| `FITRIM` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSUUID` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETFSSYSFSPATH` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GETLBMD_CAP` | `FILE_READ_ATTRIBUTES` |

`FIFREEZE`, `FITHAW` and `FITRIM` mutate filesystem operational
state, and Linux's own `CAP_SYS_ADMIN` checks still apply on top. <a id="cite-facs.use.ioctl-freeze-cap-sys-admin"></a>

**File and object:**

| ioctl | Required right |
|---|---|
| `FS_IOC_FIEMAP` | `FILE_READ_DATA` |
| `FIONREAD` | `FILE_READ_DATA` on a regular file; any data right otherwise |
| `FS_IOC_GETFLAGS` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFLAGS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETVERSION` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETVERSION` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_RESVSP` / `FS_IOC_RESVSP64` | `FILE_APPEND_DATA` or `FILE_WRITE_DATA` |
| `FS_IOC_UNRESVSP` / `FS_IOC_UNRESVSP64` | `FILE_WRITE_DATA` |
| `FS_IOC_ZERO_RANGE` | `FILE_WRITE_DATA` |
| `FICLONE` / `FICLONERANGE` | `FILE_WRITE_DATA` |
| `FIDEDUPERANGE` | `FILE_WRITE_DATA` |
| `FIOQSIZE` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSGETXATTR` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_FSSETXATTR` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GETFSLABEL` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SETFSLABEL` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_PWSALT` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_POLICY_EX` | `FILE_READ_ATTRIBUTES` |
| `FS_IOC_SET_ENCRYPTION_POLICY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_ADD_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS` | `FILE_WRITE_ATTRIBUTES` |
| `FS_IOC_GET_ENCRYPTION_KEY_STATUS` | `FILE_READ_ATTRIBUTES` |
| `BLKGETSIZE64` | `FILE_READ_ATTRIBUTES` |
| `BLKFLSBUF` | `FILE_WRITE_DATA` |

On directories, `FS_IOC_GETFLAGS` and `FS_IOC_SETFLAGS` take the same
rights as on files. <a id="cite-facs.use.ioctl-flags-on-directories"></a>

Anything unclassified is allowed on any data right. For device nodes,
pipes and sockets, device-specific ioctl semantics are outside FACS
scope: the node's descriptor is the authorization boundary, and
Linux's device-specific validation may still deny. <a id="cite-facs.use.ioctl-device-semantics-out-of-scope"></a>

A pinned inode ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)) narrows all of this. Every content-, range- or
allocation-mutating ioctl is rejected on one, and so is every ioctl
the classifier does not recognise — unknown ioctls fail closed there
rather than falling back to the data-right rule.

<a id="trm-3-9-4-8"></a>

## Execution <a id="cite-facs.use.execution"></a>

Execution is nominally a two-layer check. The **mode execute bit** is
the prerequisite meaning "this file is a program", set by package
managers and `chmod +x`, applying to `execve` and `execveat` but not
to `mmap(PROT_EXEC)`. The **descriptor's `FILE_EXECUTE`** is the
access control, gating both.

KACS enforces only the second. Nothing in the kernel module tests the
execute mode bit; the prerequisite survives because Linux's own
`generic_permission()` refuses `MAY_EXEC` on a file with no execute
bit set, by way of `capable_wrt_inode_uidgid(CAP_DAC_OVERRIDE)`. <a id="cite-facs.use.exec-mode-bit-from-linux"></a> The
`+x` requirement is therefore a Linux DAC property that KACS inherits
rather than a FACS rule, and it is one of the few decisions where mode
bits still matter ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)).

For descriptor-based exec — `execveat` with `AT_EMPTY_PATH`, including
on `O_PATH` handles — a live AccessCheck for `FILE_EXECUTE` runs
against the re-opened file rather than the cached mask being consulted. <a id="cite-facs.use.execveat-live-check"></a>

---

# Descriptor storage and caching

_Peios Kernel / Internals / KACS / File security_

> Descriptor storage and caching: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-5"></a>

<a id="trm-3-9-5-1"></a>

## Xattr protection <a id="cite-facs.storage.xattr-protection"></a>

FACS intercepts every raw xattr operation on the canonical descriptor
xattr — `security.peios.sd`, or `system.ntfs_security` on NTFS — and
denies all three directions. An NTFS inode with no `$Secure` entry,
whose descriptor is an inline attribute the driver never reads, counts
as carrying no descriptor: the mount's missing-descriptor policy
decides for it, as it does for a file with no `security.peios.sd`.

**Writes** are denied: all modification goes through the set-security
interface. **Removal** is denied: a descriptor is never detached from
a file. And **reads** are denied, which is the least obvious of the
three and the most important. <a id="cite-facs.storage.xattr-read-denied"></a> The raw xattr holds the entire
descriptor including the SACL, so allowing a read under
`READ_CONTROL` alone would leak SACL content that properly requires
`ACCESS_SYSTEM_SECURITY`. All reads go through `kacs_get_sd`, which
distinguishes the two.

<a id="trm-3-9-5-2"></a>

## Caching

A validated, parsed descriptor object is cached in the inode's LSM
blob, holding immutable self-relative bytes together with a
prevalidated component layout — enough for AccessCheck readers never
to reparse untrusted storage bytes. <a id="cite-facs.storage.cache-parsed-in-inode-blob"></a>

**Readers** on the AccessCheck path use the RCU-published pointer.
Once a current entry exists, a reader does not take the inode mutex
merely to run AccessCheck. <a id="cite-facs.storage.readers-rcu-no-mutex"></a> It either completes the evaluation inside
an RCU read-side critical section, or pins the object with a refcount
while still under RCU and drops the RCU lock before doing anything
that can allocate, sleep or emit an audit event. A pin is acquired
with a non-zero refcount check and dropped afterwards.

**Writers** allocate a new object, swap the pointer atomically, and
free the old one after a grace period and after reader pins have
drained. <a id="cite-facs.storage.writers-rcu-swap"></a> No partial read is possible.

**Population** is lazy, on first access. The xattr is read through an
internal kernel path that bypasses the read-denial hook, and the
parsed result is installed by compare-and-swap; a thread that loses
the race frees its own copy. <a id="cite-facs.storage.population-lazy-cas"></a>

Both native and legacy open finish descriptor-cache resolution before
acquiring the central access policy (CAAP) cache mutex. Resolution can take
an inode security mutex, while set-security takes that inode mutex before
CAAP; acquiring them in the opposite order could deadlock an open against a
descriptor update. <a id="cite-facs.storage.open-resolves-before-caap"></a> Open retains a pin on the immutable descriptor
selected by that resolution, before releasing the protection used to select
it. The pin survives the subsequent CAAP wait and access check. Clearing or
replacing the inode's cache after selection cannot by itself cause a spurious
denial or change which descriptor this open evaluates; a later open resolves
again and can select the replacement. A missing or corrupt selected entry
still fails closed. <a id="cite-facs.storage.open-pins-selected-descriptor"></a>

Live file access checks, executable integrity-label reads, descriptor queries,
and copy-up descriptor reads also retain the immutable entry selected during
resolution until they finish evaluating or copying it. This includes the
inode-only descriptor read used by stacking filesystems. Invalidation after
selection cannot alone cause a refusal or substitute a different descriptor;
the next operation resolves again. A selected missing or corrupt descriptor
still fails closed even if another thread repairs the cache before the reader
finishes. <a id="cite-facs.storage.readers-pin-selected-descriptor"></a>

CAAP is evaluated under its own, later cache lock; the descriptor selection
and CAAP evaluation are not an atomic snapshot of both policies. The inode
mutex is not held for the access check, and CAAP is not held across lazy
descriptor population.

**Eviction** frees the cached descriptor when the inode is evicted,
through an RCU-safe callback with the same pin draining, so in-flight
permission checks complete before the object goes away. <a id="cite-facs.storage.eviction-rcu-safe"></a>

**Invalidation** happens on write, but not atomically with it. The
set-security path deliberately releases the inode security lock across
the xattr write and re-acquires it afterwards to publish the new
parsed object, because holding it across the write would invert the
`i_rwsem` ordering the access path requires. <a id="cite-facs.storage.setsd-releases-lock-across-write"></a> Two concurrent
set-security calls on one inode are therefore last-writer-wins rather
than serialised end to end, and there is a window in which the xattr
and the cache disagree. <a id="cite-facs.storage.concurrent-setsd-last-writer-wins"></a> Readers are never blocked, and no reader sees
a partially written object — the exposure is which of two racing
writes lands, not a torn state.

Invalidation is also driven from the **other end**, by the write
itself: any canonical descriptor xattr landing on an inode drops that
inode's cached entry, whoever wrote it and by whatever path. <a id="cite-facs.storage.xattr-write-drops-cache"></a> The
set-security path above then publishes the new parsed object as usual;
for anything else, the next reader re-reads the authoritative bytes.

This is keyed on the xattr rather than on the writer, because the
writer is not always the one holding the cache. A descriptor set
through a stacking filesystem reaches **two** inodes — the one the
caller named, and the real one beneath, which the write is re-entered
on. <a id="cite-facs.storage.stacking-two-inodes"></a> Only the first is refreshed by the set-security path. The second
is not merely cold: a stacking filesystem resolves and caches
descriptors during its own metadata work on an inode it has just
created, so it can hold an entry from the moment the object existed
and keep serving it after the xattr underneath has changed. Keying on
the xattr closes that without either side needing to know the other is
there.

<a id="trm-3-9-5-7"></a>

## Missing descriptors <a id="cite-facs.storage.deny-missing-denies"></a>

Under **`facs_deny_missing`**, no descriptor means deny. Two
exceptions keep the repair path open. `SeChangeNotifyPrivilege`
bypasses intermediate traverse checks including on directories with no
descriptor, though not explicit `chdir()`, `chroot()` or `fchdir()`
use-time checks. And `O_PATH` opens bypass the open hook entirely, so
a file with a missing descriptor can still be acquired as an `O_PATH`
reference — which is exactly the repair route: `open(path, O_PATH)`
then `kacs_set_sd` with `AT_EMPTY_PATH` under `SeRestorePrivilege`. <a id="cite-facs.storage.missing-repair-route"></a>

Under the **synthesise classes**, a missing descriptor is generated
from two sources in order. <a id="cite-facs.storage.synthesis-order"></a> First, **inheritance from the parent**: if
the parent has one, the inheritance algorithm runs as though a new
file were being created. Otherwise the **mount-level template**,
applied where there is no parent descriptor — typically only at the
mount root. With no template configured, the fallback grants
`GENERIC_ALL` to SYSTEM and `BUILTIN\Administrators` and
`GENERIC_READ | GENERIC_EXECUTE` to Everyone, owned by SYSTEM with
SYSTEM as group. <a id="cite-facs.storage.synthesis-fallback-descriptor"></a>

Because these files already exist, the accessor is not their creator.
Where inheritance needs creator inputs — owner, primary group, default
DACL — a synthetic system-policy creator supplies them: the template's
owner, group and DACL if one exists, the fallback's otherwise. **The
accessor's token never affects the synthesised descriptor**, and the
synthesis path takes no subject token at all. <a id="cite-facs.storage.synthesis-ignores-accessor"></a>

Inheritance is recursive — a parent whose own descriptor is missing is
synthesised first, walking toward the mount root where the template
terminates it. <a id="cite-facs.storage.synthesis-recursive"></a> The walk is bounded at 32 ancestor levels; a target
nested deeper than that below the nearest resolvable ancestor fails
closed with `EACCES` rather than synthesising. <a id="cite-facs.storage.synthesis-depth-limit"></a>

Resolution does not nest FACS inode locks. It releases the current inode's
lock before resolving an ancestor or calling the filesystem's descriptor
xattr handler, which may itself resolve a lower inode in a stacked
filesystem. Referenced dentries and immutable descriptor-cache entries keep
the inputs alive across that work. <a id="cite-facs.storage.resolution-no-nested-inode-locks"></a>

Before publishing the result, resolution reacquires the inode lock and
checks both the mount-policy generation and the inode's cache mutation
sequence. An explicit replacement or invalidation makes it discard the
obsolete result and retry, including when an empty cache was populated and
cleared or invalidated while still empty. Ordinary cached files also retry
a competing reader publication, then use the current entry. A failed reread
never makes an entry from an old policy generation current again.
<a id="cite-facs.storage.resolution-revalidates-unlocked-work"></a>

StrataFS re-reads the current provider descriptor on every check, including
when an earlier result was missing or corrupt. Concurrent reader publication
does not restart these reads: without an explicit invalidation or policy
change, N checks perform N descriptor reads (each may query size and then
bytes). A reader may reuse a result published by another reader whose read
began later than its own; an older read cannot overwrite that later result,
including a missing or corrupt result. Its own read error is still returned.
Explicit writes and policy changes continue to trigger revalidation and may
require another read. This does not alter the fixed deny-missing policy or a
handle's frozen grant. <a id="cite-facs.storage.stratafs-read-contention"></a>

An **ephemeral** synthesis is cached in the inode blob only and never
written back, leaving the original filesystem unmodified. <a id="cite-facs.storage.ephemeral-not-written-back"></a> A
**persistent** one is additionally written to the xattr so the medium
acquires durable descriptors — but never inline. <a id="cite-facs.storage.persistent-written-back"></a>

<a id="trm-3-9-5-8"></a>

## Deferred write-back <a id="cite-facs.storage.write-back-deferred"></a>

Writing the xattr takes the inode's `i_rwsem`. Synthesis may be reached
from a metadata operation whose VFS caller already holds that lock, so
inline write-back would self-deadlock even though resolution releases its
FACS inode lock around parent resolution and xattr reads. Write-back
therefore runs with no FACS or VFS lock held.

Synthesis caches the descriptor immediately and marks the entry
pending. <a id="cite-facs.storage.synthesis-marks-pending"></a> The access decision is correct from that cached value the
instant synthesis completes — correctness never depends on the xattr
reaching disk. The write-back runs later from a task-work callback
firing as the triggering syscall returns to userspace, so a persistent
descriptor is normally on disk by the time the operation that first
observed it missing returns. <a id="cite-facs.storage.write-back-task-work"></a>

A pending entry is generation-tagged exactly like an ephemeral one, so
a policy or template change before the write-back discards it and
re-synthesises; a stale pre-change descriptor is never pinned to disk.

Write-back is best-effort, and can be because the synthesised
descriptor is a deterministic function of the parent or the template —
the on-disk xattr is a cache of a recomputable value, not unique
state. If it does not happen, because the entry was evicted or the
task exited first, the identical descriptor is re-synthesised on next
access and retried. A failed or skipped write-back never fails the
operation that triggered synthesis. <a id="cite-facs.storage.write-back-best-effort"></a> Kernel threads, and a failure to
queue the callback, fall back to re-synthesis the same way.

Once written, the cached entry becomes an ordinary xattr-backed
descriptor: durable, no longer generation-tagged, never synthesised
again, and owed no further write-back. <a id="cite-facs.storage.written-back-becomes-ordinary"></a>

An ancestor synthesised only to supply inheritance inputs for a
descendant is itself pending, and persists under the same rules when
it is next accessed in its own right. <a id="cite-facs.storage.ancestor-also-persists"></a>

<a id="trm-3-9-5-9"></a>

## Corrupt descriptors <a id="cite-facs.storage.corrupt-fails-closed"></a>

A descriptor xattr that exists but fails structural validation is
corrupt, and the policy is fail-closed: deny all access, do not call
AccessCheck, and never treat a truncated DACL as an empty one.

Every encounter emits an audit event, fired exactly once per inode per
cache population rather than per access, so a hot corrupt inode does
not flood the log. <a id="cite-facs.storage.corrupt-audit-once-per-population"></a>

Recovery is a process holding `SeRestorePrivilege` calling
set-security to overwrite it. Offline repair tools can also rewrite
xattrs directly on an unmounted filesystem.

<a id="trm-3-9-5-10"></a>

## NFS client mounts <a id="cite-facs.storage.nfs-dual-authority"></a>

NFS is the one managed class where the sole-authority guarantee does
not hold. The server enforces its own access control independently:
FACS evaluates locally against a synthesised descriptor, and the
server may deny I/O that FACS allowed. A locally authorized `open()`
can therefore produce a descriptor whose `read()` calls fail. This is
inherent to network filesystems with server-side enforcement, and
nothing suppresses the server's denial.

## Related explanations

- [Mount classes and bootstrap descriptors](</kernel/internals/kacs/file-security/mount-classes-and-bootstrap-descriptors.md>)

---

# Mount classes and bootstrap descriptors

_Peios Kernel / Internals / KACS / File security_

> Mount classes and bootstrap descriptors: behaviour and implementation of the Peios kernel.

<a id="trm-3-9-5-3"></a>

## Mount policy classes

The superblock policy object carries the class ([The Handle Model](</kernel/internals/kacs/file-security/the-handle-model.md#trm-3-9-1>)) and, for
synthesise-class mounts, an optional mount-level default template.

The default classifier maps from the superblock's filesystem magic.
`PROC_SUPER_MAGIC` and `SYSFS_MAGIC` are **unmanaged**: these expose
kernel state through inode-shaped handles with no on-disk identity and
no descriptor to consult. <a id="cite-facs.storage.proc-sysfs-unmanaged"></a> `NULL_FS_MAGIC` is unmanaged too — nullfs is
the immutable, permanently empty filesystem the kernel mounts as the
mount-namespace root, with the mutable rootfs mounted on top of it. It
declares no xattr support at all, so it can never carry a descriptor,
and its single root inode is immutable and childless: nothing to stamp
and nothing to protect. <a id="cite-facs.storage.nullfs-unmanaged"></a>

`STRATAFS_SUPER_MAGIC` is fixed at **`facs_deny_missing`** for the
superblock's lifetime, because StrataFS delegates every check to
current provider objects and must never synthesise a descriptor for
its merged namespace. <a id="cite-facs.storage.stratafs-fixed-deny-missing"></a> An attempt to change it fails with
`EOPNOTSUPP`.

`RAMFS_MAGIC`, `NFS_SUPER_MAGIC`, `MSDOS_SUPER_MAGIC`,
`EXFAT_SUPER_MAGIC`, `ISOFS_SUPER_MAGIC` and `CGROUP2_SUPER_MAGIC` are
**`facs_synthesize_ephemeral`** — either no persistent backing at all,
or storage with no native descriptor slot. <a id="cite-facs.storage.ephemeral-magics"></a>

Everything else, including `TMPFS_MAGIC`, `SQUASHFS_MAGIC`,
`EXT4_SUPER_MAGIC` and `BTRFS_SUPER_MAGIC`, defaults to
**`facs_deny_missing`**. <a id="cite-facs.storage.default-deny-missing"></a> These can all carry the descriptor xattr
natively and are expected to on every inode that participates in
access checks.

`TMPFS_MAGIC` covers both userspace tmpfs mounts and the kernel-mounted
instances established before any userspace runs. The latter are not
exempt from the default; they are handled by seeding.

<a id="trm-3-9-5-4"></a>

## Kernel-internal mounts <a id="cite-facs.storage.kernel-internal-mounts"></a>

Two filesystems are mounted by the kernel before any userspace process
exists and before anything can call `kacs_set_mount_policy` or
`kacs_set_sd`: the mutable root filesystem mounted by
`init_mount_tree`, a tmpfs mounted on top of the immutable nullfs
namespace root and made `/` by `set_fs_root`; and the devtmpfs
instance mounted by `devtmpfs_init` and populated by the `kdevtmpfs`
thread.

Both are `TMPFS_MAGIC` and therefore `facs_deny_missing`, and their
root inodes are kernel-created, never passing through a
userspace-supplied artifact, so they carry no descriptor at the moment
they become reachable. To make the class viable the kernel seeds one.

The mutable root filesystem is a tmpfs whatever the command line says.
<a id="cite-facs.storage.rootfs-always-tmpfs"></a> Upstream Linux makes it a ramfs
when the command line carries `root=`, or a `rootfstype=` that does not
name tmpfs, and ramfs stores no extended attributes: the seed below
would have nowhere to go, nothing the boot archive unpacks would
inherit a descriptor, and StrataFS, which reads a provider's stored
descriptor and never a synthesised one, would refuse every view an
initramfs mounts over it. An installed system always boots with
`root=`, so the upstream rule is not followed.

The rootfs root is seeded inside `init_mount_tree`, immediately after
`vfs_kern_mount` returns and before the mount is published into
`init_mnt_ns`, with the inode's `i_rwsem` held. <a id="cite-facs.storage.rootfs-seed-timing"></a> The devtmpfs root is
seeded inside `devtmpfs_init`, after `vfs_kern_mount` and before
`kdevtmpfs` starts, likewise under `i_rwsem`. <a id="cite-facs.storage.devtmpfs-seed-timing"></a> The nullfs root is not
seeded — it is unmanaged, empty, and incapable of xattr storage. <a id="cite-facs.storage.nullfs-not-seeded"></a>

A rootfs seed that fails panics the kernel. <a id="cite-facs.storage.rootfs-seed-failure-is-fatal"></a>
A boot that went on without it would fail later, in whatever first
reached the initramfs through a StrataFS view, with nothing to connect
the refusal to its cause.

The seeded descriptor is byte-for-byte identical in both places: owner
and group SYSTEM (`S-1-5-18`), a DACL of one `ACCESS_ALLOWED` ACE
granting `GENERIC_ALL` to SYSTEM flagged
`OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE` so that inheritance
derives a child descriptor for every inode created on the mount
afterwards, and no SACL. <a id="cite-facs.storage.seeded-descriptor-contents"></a>

The writes go through the kernel-internal xattr path, bypassing both
the FACS denial hooks and the LSM setxattr permission hook. <a id="cite-facs.storage.seed-writes-bypass-hooks"></a> They
consult no token — at the point either runs there may be no meaningful
subject — and the seeded descriptor is the sole authority for the
mount until trusted userspace replaces it. They depend on nothing
beyond the LSM scaffold that allocates inode and superblock blobs.

These are not exempt from later management: trusted userspace can
overwrite the per-inode descriptor or change the superblock's class
once it holds the privileges. <a id="cite-facs.storage.seeded-mounts-still-manageable"></a>

<a id="trm-3-9-5-5"></a>

## Boot artifacts <a id="cite-facs.storage.boot-artifacts-not-seeded"></a>

A filesystem shipped as a boot artifact — a squashfs concatenated into
the initrd, a vendor squashfs delivered as a package, a flashed
partition image — defaults to `facs_deny_missing` and the kernel does
**not** seed it. These are already-populated trees the kernel cannot
extend at mount time, and in the read-only case cannot extend at all.

The obligation falls on the build pipeline, which emits
`security.peios.sd` on every inode ordinary access checks will reach.
`mksquashfs`, the ext utilities and the standard userland xattr
surfaces all preserve `security.*` natively.

An artifact without descriptors is a packaging defect. FACS treats
every missing descriptor on a `facs_deny_missing` mount as a
corruption indicator and denies. The operator path is to rebuild the
artifact, or to adopt the superblock under a synthesise class.

<a id="trm-3-9-5-6"></a>

## Administration <a id="cite-facs.storage.set-mount-policy"></a>

The privilege gate below is verified in kernel source
[`8e0e22de3a59cad506bbbf8873de456e16ad272d`](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/capability.c#L613-L637),
including its use by both [set](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L369-L380)
and [get](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/mount_policy.c#L479-L496). This is source-level
verification, not a deployed-kernel test or a historical release boundary.

Trusted userspace adopts a mounted filesystem by calling
`kacs_set_mount_policy` on a descriptor naming any object on the
target superblock; `O_PATH` descriptors are valid targets. The change
applies to the superblock, not the pathname used to reach it.

Setting a policy is volume management: the call requires
`SeManageVolumePrivilege` or `SeTcbPrivilege`, enabled, and must
successfully mark the enabled privilege as used; `kacs_get_mount_policy`
is gated the same way. <a id="cite-facs.storage.set-mount-policy-privilege"></a> Every change writes a
`kacs.mount.policy.changed` record ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)), whose subject is the caller
and which names the filesystem's type, the policy set
(`object.mount.policy`), the one it replaced
(`object.mount.policy-previous`) and the new generation
(`object.mount.policy-generation`). Every refusal is decided before the
change, so a record is always of a change made; the template is not
carried. <a id="cite-facs.storage.set-mount-policy-recorded"></a> The
public ABI accepts only the three managed classes; `unmanaged`,
unknown values, nonzero reserved flags and malformed arguments all
fail closed. <a id="cite-facs.storage.set-mount-policy-input-validation"></a> The one
policy the kernel sets on its own initiative is for a tmpfs that a token
without the privilege brought into being inside its own mount namespace,
which is stamped `synth-ephemeral` with a creator-owned template at
`sb_kern_mount` ([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)).

The optional template is accepted only with a synthesise class. <a id="cite-facs.storage.template-requires-synthesise"></a> It is
a complete self-relative descriptor rather than a subset, passes
structural validation, and is at most 65535 bytes. <a id="cite-facs.storage.template-validation"></a> A null pointer with
zero length clears it. <a id="cite-facs.storage.template-null-clears"></a> Setting `facs_deny_missing` clears it and
rejects non-empty template input. <a id="cite-facs.storage.deny-missing-clears-template"></a> Pointer and length mismatches and
invalid bytes fail before any state changes.

Policy changes are **lazy**. They do not walk the filesystem and do
not stamp anything. <a id="cite-facs.storage.policy-change-lazy"></a> The superblock carries a monotonic generation
counter, incremented on every successful policy or template
replacement. <a id="cite-facs.storage.generation-counter"></a> Missing-descriptor, ephemeral-synthetic and
not-yet-written-back persistent-synthetic cache entries record the
generation they came from and are discarded and repopulated when it
changes. <a id="cite-facs.storage.generation-discards-synthetic"></a> Xattr-backed and corrupt-descriptor caches are not made valid
by a policy change, and open file descriptions keep their immutable
masks. <a id="cite-facs.storage.policy-change-keeps-xattr-caches"></a>

---

# The Set-Security Interface

_Peios Kernel / Internals / KACS / File security_

> The single syscall all descriptor modification flows through — ownership, integrity labels, the SeRestorePrivilege bypass and mandatory attributes.

<a id="trm-3-9-6"></a>

All descriptor modification flows through one syscall. The caller
provides a file descriptor or path, a bitmask naming which components
to modify, and a self-relative descriptor blob carrying the new
values.

| Flag | Component | Required right |
|---|---|---|
| `OWNER_SECURITY_INFORMATION` | Owner SID | `WRITE_OWNER` <a id="cite-facs.set-sd.owner-requires-write-owner"></a> |
| `GROUP_SECURITY_INFORMATION` | Group SID | `WRITE_OWNER` |
| `DACL_SECURITY_INFORMATION` | Discretionary ACL | `WRITE_DAC` <a id="cite-facs.set-sd.dacl-requires-write-dac"></a> |
| `SACL_SECURITY_INFORMATION` | System ACL | `ACCESS_SYSTEM_SECURITY` <a id="cite-facs.set-sd.sacl-requires-access-system-security"></a> |
| `LABEL_SECURITY_INFORMATION` | Mandatory integrity label | `WRITE_OWNER`, plus the integrity constraints below <a id="cite-facs.set-sd.label-requires-write-owner"></a> |

The blob is validated structurally — parseable, well-formed ACEs,
valid SIDs, at most 65535 bytes. With an existing valid file security descriptor,
only the indicated components are merged into it. Unindicated components
are preserved unchanged. <a id="cite-facs.set-sd.merge-preserves-unindicated"></a>

The input is always one self-relative descriptor subset, never a raw
SID or ACL fragment. `SACL_SECURITY_INFORMATION` and
`LABEL_SECURITY_INFORMATION` cannot be combined in one call, because
both target the SACL field with incompatible meanings; the pair fails
with `EINVAL`. <a id="cite-facs.set-sd.sacl-label-exclusive"></a>

A `SACL_SECURITY_INFORMATION` write replaces the object's **entire**
SACL. <a id="cite-facs.set-sd.sacl-write-replaces-all"></a> A `LABEL_SECURITY_INFORMATION` write interprets the input SACL
as the label subset only: no SACL component removes the explicit
mandatory label and returns the object to the default unlabelled
state; a present SACL contains exactly one non-inherit-only
`SYSTEM_MANDATORY_LABEL_ACE` and nothing else; and the object's
non-label SACL ACEs are preserved. <a id="cite-facs.set-sd.label-write-subset"></a>

After merging, the result still has a non-null owner — the group SID
may be null — and a merge that would leave no owner fails. <a id="cite-facs.set-sd.owner-must-remain"></a>

MIC and PIP apply to these checks. A low-integrity caller cannot
modify a high-integrity file's descriptor even where the DACL grants
`WRITE_OWNER`. <a id="cite-facs.set-sd.mic-pip-apply"></a>

A read-only mount withholds the write along that path whatever the
descriptor grants: the call fails with `EROFS`, as every modifying
operation through a read-only bind does, and the descriptor stays
writable through any writable path to the same object. The mount is
consulted after the access check, so a caller the descriptor refuses
sees the denial rather than a read-only error that would confirm the
object exists. <a id="cite-facs.set-sd.read-only-mount-erofs"></a>

<a id="trm-3-9-6-1"></a>

## Component merging and replacement

For a file whose cached descriptor is valid, [the C dispatcher](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/sd_access.c#L197-L255) selects the merge path. The [control-bit merge](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4232-L4264) starts from the destination control value and replaces these bits from the input when their component is selected:

| Selected component | Replaced control bits |
|---|---|
| Owner | `OWNER_DEFAULTED` |
| Group | `GROUP_DEFAULTED` |
| DACL | `DACL_DEFAULTED`, `DACL_TRUSTED`, `DACL_AUTO_INHERIT_REQ`, `DACL_AUTO_INHERITED`, `DACL_PROTECTED` |
| Full SACL | `SACL_DEFAULTED`, `SACL_AUTO_INHERIT_REQ`, `SACL_AUTO_INHERITED`, `SACL_PROTECTED` |

This copies more than ACE lists, but is not byte-identical descriptor replacement. If group is not selected, [the destination group remains](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4347-L4351). The [resource-manager control byte remains the destination's](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4410-L4416), as does its `RM_CONTROL_VALID` state. A label-only merge does not replace the full-SACL control-bit set in the table.

A missing or invalid cached file security descriptor does **not** take that merge path. The dispatcher requires enabled `SeRestorePrivilege` and calls the [replacement builder](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4420-L4468), which requires owner, group and DACL selections and validates the supplied owner and label. Do not apply valid-descriptor field-retention guarantees to that repair case.

These details are source-checked against kernel commit [`8e0e22de`](https://github.com/peios/pkm/tree/8e0e22de3a59cad506bbbf8873de456e16ad272d), not a runtime-validated restore procedure.

<a id="trm-3-9-6-7"></a>

## Generic rights <a id="cite-facs.set-sd.generic-rights-mapped"></a>

Generic rights in a written DACL or SACL are mapped to file rights
before the descriptor is stored, as they are when a file is created.
An ACE that applies to the file has `GENERIC_READ`, `GENERIC_WRITE`,
`GENERIC_EXECUTE` and `GENERIC_ALL` replaced by the file rights they
stand for. An ACE that applies to the file and is also inherited is
split into a mapped ACE for the file and an inherit-only copy that
keeps the generic rights for the children it will reach. Inherit-only
ACEs are stored as given. A descriptor therefore reads back the same
whether it was supplied at creation, inherited, or set afterwards
([The DACL Walk](</kernel/internals/kacs/access-check/the-dacl-walk.md#trm-3-8-2-2>)).

The same rule applies to every object type with a set path —
registry keys, processes, tokens, System V IPC objects and the rest —
each through its own GenericMapping.

A descriptor change breaks other holders' handle caching on the file
([Leases](</kernel/internals/kacs/file-security/leases.md#trm-3-9-12-3>)).

<a id="trm-3-9-6-2"></a>

## Ownership <a id="cite-facs.set-sd.ownership"></a>

A new owner may be set only to the caller's own SID, or to a group SID
on the token carrying `SE_GROUP_OWNER`. `SeTakeOwnershipPrivilege`
allows setting ownership to the caller's own SID regardless of what
the current descriptor says, and `SeRestorePrivilege` allows any
arbitrary SID. <a id="cite-facs.set-sd.take-ownership-and-restore"></a>

<a id="trm-3-9-6-3"></a>

## Integrity labels <a id="cite-facs.set-sd.label-level-constraint"></a>

Without enabled `SeRelabelPrivilege` a caller may set a label only at or below
its own integrity level; with it, the label-level check permits any level.
Other access and validation checks still apply.

The constraint applies through **both** paths — the dedicated label
subset, and a label ACE embedded in a full SACL write. A SACL write
whose ACL contains a mandatory label ACE raising integrity above the
caller's level requires `SeRelabelPrivilege` exactly as the label path
does, even though the SACL component itself is gated only by
`ACCESS_SYSTEM_SECURITY`. <a id="cite-facs.set-sd.label-constraint-via-sacl"></a>
`SeSecurityPrivilege` or `SeRestorePrivilege` alone is not sufficient for
a label above the caller's integrity: the [label-assignment check](https://github.com/peios/pkm/blob/8e0e22de3a59cad506bbbf8873de456e16ad272d/kacs/token_runtime.rs#L4180-L4197) independently requires enabled
`SeRelabelPrivilege`.

<a id="trm-3-9-6-4"></a>

## The SeRestorePrivilege bypass

`SeRestorePrivilege` fires inside the AccessCheck pipeline, so it
bypasses the check only where `kacs_set_sd` runs a **live** one: an
`O_PATH` descriptor with `AT_EMPTY_PATH`, a pidfd, a token descriptor
with `AT_EMPTY_PATH`, or a path. <a id="cite-facs.set-sd.restore-bypass-live-only"></a> On those paths it grants every
requested right, `WRITE_OWNER`, `WRITE_DAC` and
`ACCESS_SYSTEM_SECURITY` included.

Called on an ordinary file descriptor the required rights are checked
against the cached mask instead, no AccessCheck runs, and the
privilege has no effect at all. <a id="cite-facs.set-sd.restore-no-effect-on-fd"></a> A caller needing the bypass has to use
the `O_PATH` route — which is the mechanism behind backup restoration,
administrative repair, and the missing-descriptor repair path
([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)).

<a id="trm-3-9-6-5"></a>

## Mandatory resource attributes <a id="cite-facs.set-sd.mandatory-attribute-requires-tcb"></a>

When a caller modifies the SACL, the existing and new SACLs are
compared for changes to `SYSTEM_RESOURCE_ATTRIBUTE_ACE` entries. An
existing attribute carrying `CLAIM_SECURITY_ATTRIBUTE_MANDATORY`
(0x0020) cannot be removed, nor its values modified, without
`SeTcbPrivilege` — and an attempt without it fails the entire call
rather than silently dropping the change.

<a id="trm-3-9-6-6"></a>

## Write mechanics

The updated descriptor is serialised to self-relative binary form and
written to the xattr through an internal kernel path bypassing the
denial hook, and the in-memory cache is updated. <a id="cite-facs.set-sd.write-bypasses-denial-hook"></a> An audit event is
emitted if the file's SACL carries a matching audit ACE. <a id="cite-facs.set-sd.audit-on-matching-ace"></a>

The cache update is not atomic with the xattr write; [File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>) describes
the lock ordering that forces this and the last-writer-wins window it
produces.

---

# Sharing and Deletion

_Peios Kernel / Internals / KACS / File security_

> NT share modes enforced for every process, delete-pending files, deletion and renaming through an open handle, and pinning a file's ancestors.

<a id="trm-3-9-10"></a>

KACS keeps NT's sharing and deletion rules in the kernel, for every
process. An open says which kinds of access it lets other opens have at
the same time. A file can be marked for deletion through any open that
holds `DELETE`, and is removed when the last open of it closes. Deletion
and renaming can be done through an open handle rather than by name.

These rules apply to regular files and directories on FACS-managed
mounts. <a id="cite-facs.share.scope"></a> They do not apply to device nodes, FIFOs, sockets or symbolic
links, to unmanaged mounts such as `/proc`, `/sys` and nullfs, or to
`O_PATH` descriptors, which take no part in share checks.

<a id="trm-3-9-10-1"></a>

## Share modes <a id="cite-facs.share.check"></a>

The rules are those of MS-FSA 2.1.5.1.2.1 and 2.1.5.1.2.2. Access falls
into three classes:

| Class | Rights | Share bit that admits it |
|---|---|---|
| Read | `FILE_READ_DATA`, `FILE_EXECUTE` | `FILE_SHARE_READ` |
| Write | `FILE_WRITE_DATA`, `FILE_APPEND_DATA` | `FILE_SHARE_WRITE` |
| Delete | `DELETE` | `FILE_SHARE_DELETE` |

An open whose granted access contains none of these rights takes no part
in share checking: it neither conflicts with other opens nor constrains
them. <a id="cite-facs.share.attribute-only-opens"></a> Opening for attributes or for the security descriptor is
always possible, whatever other opens deny.

An open that does take part conflicts with an existing open, and fails
with `EBUSY`, when either of them holds access of a class the other
does not share. <a id="cite-facs.share.conflict-both-ways"></a> A native open is judged by the access it was
**granted**, not what it asked for, so a `MAXIMUM_ALLOWED` open is
judged by what it received. A native open reports the conflict as
`KACS_STATUS_SHARING_VIOLATION`. A successful open registers its access
and share mode until it closes.

**Legacy opens take part.** A plain `open(2)` shares all three classes,
so legacy opens never conflict with each other. A legacy open is judged
by its mode instead of its granted mask, because its mask carries
optional compat rights it may never use: a readable open, file or
directory, holds the read class, and a writable one the write class.
<a id="cite-facs.share.legacy-opens"></a> A legacy open of a file another
open has denied to its class fails with `EBUSY`, as a native open does.

**A running program takes part.** Executing a file holds it as an open
with read access that shares read and delete but not write. This is the
NT form of Linux's refusal to write a running executable, which still
applies first, with `ETXTBSY`. A program can be replaced by renaming a
new file over its name while it runs. <a id="cite-facs.share.exec"></a>

An open's share registration lasts as long as its open file
description. A memory mapping holds the description, so a mapped file
keeps its registration after its descriptor is closed, until it is
unmapped.

<a id="trm-3-9-10-2"></a>

## Denying only what you could do yourself <a id="cite-facs.share.deny-limits"></a>

Share modes would let any reader lock others out of a file, such as a
system configuration file it can only read. KACS limits each denial to
what the opener could do itself. Where an open omits a share bit it is
not entitled to deny, that bit is silently set, and the open proceeds as
if it had shared it.

- **Denying read** follows MS-FSA. It takes effect only if the opener
  has `FILE_WRITE_DATA` on the parent directory (2.1.5.1.2.2). On the
  first open of a directory it also needs the generic write rights on
  the directory itself (2.1.5.1.2). <a id="cite-facs.share.deny-read"></a>
- **Denying write** takes effect only if the opener's descriptor grants
  it `FILE_WRITE_DATA` or `FILE_APPEND_DATA` on the object. <a id="cite-facs.share.deny-write"></a>
- **Denying delete** takes effect only if the opener could delete the
  object: `DELETE` on it, or `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.share.deny-delete"></a>

These decide whether the opener *could* exercise the right, not
whether it asked to. Each is an AccessCheck against the current
descriptor, made only for an open that omits the corresponding share
bit. An open that shares everything, which includes every legacy open,
costs nothing extra.

<a id="trm-3-9-10-7"></a>

## Overriding share modes <a id="cite-facs.share.override"></a>

Backup and restore tools have to read and replace files that others
hold open. A native open's backup and restore intents
([Privilege-Based Grants](</kernel/internals/kacs/privileges/the-privilege-model.md>)) also let it set aside other opens'
denials:

- backup intent with `SeBackupPrivilege` enabled ignores other opens'
  denial of read;
- restore intent with `SeRestorePrivilege` enabled ignores other opens'
  denial of write and delete.

The override skips only the share check. Lease breaks still happen, so
a client caching the file flushes first. The overriding open's own
share mode still binds later opens, and every override is audited. <a id="cite-facs.share.override-audited"></a>

<a id="trm-3-9-10-3"></a>

## Delete-pending files <a id="cite-facs.delete.pending"></a>

A file is **delete-pending** when it has been marked to be deleted at
its last close. Any open of the file that holds `DELETE` can set or
clear the mark with `kacs_set_disposition`. An open created with
`KACS_CREATE_OPT_DELETE_ON_CLOSE` sets it when it closes. <a id="cite-facs.delete.set-clear"></a>

While a file is delete-pending:

- its name stays in place: `stat` and directory listings still show it;
- every new open of it fails with `EBUSY`, whatever the access asked,
  including attribute-only and `O_PATH` opens; a native open reports
  `KACS_STATUS_DELETE_PENDING`; <a id="cite-facs.delete.pending-opens-fail"></a>
- unlinking or renaming it by name fails with `EBUSY`;
- a delete-pending directory accepts no new entries: creating, linking
  or renaming into it fails with `EBUSY`; and
- creating a file of the same name fails, because the name still
  exists.

When the last open of the file closes, from whichever process, the
name is removed. <a id="cite-facs.delete.last-close"></a> The removal is authorized by the token of the open
that set the mark, captured when it was set, not by whoever happens to
close last; the closing task needs no right. A removal that fails at
close, for example because a directory gained an entry, is audited,
and the file is left in place and no longer delete-pending. <a id="cite-facs.delete.close-failure-audited"></a>

The name removed is the link the marking open was opened through,
followed across any renames since. Other hard links to the file remain.
If that name is already gone by the last close, nothing more is done.

A directory is removed at its last close only if it is empty then; one
that is not stays, and the failed removal is audited. A delete-pending
directory accepts no new entries meanwhile, so it can only empty. A
read-only regular file cannot be marked unless the caller sets it aside ([Special
Attributes](</kernel/internals/kacs/file-security/special-attributes.md#trm-3-9-13>)).

<a id="trm-3-9-10-4"></a>

## The disposition call <a id="cite-facs.delete.disposition-call"></a>

`kacs_set_disposition(fd, flags)` sets a file's delete disposition
through an open handle. Its flags are those of NT's
`FILE_DISPOSITION_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_DISPOSITION_DELETE` | 0x01 | Mark the file for deletion. Without it, clear the mark. |
| `KACS_DISPOSITION_POSIX_SEMANTICS` | 0x02 | With `DELETE`: remove the name now. |
| `KACS_DISPOSITION_ON_CLOSE` | 0x08 | Set or clear this open's delete-on-close obligation instead of the file's mark. |
| `KACS_DISPOSITION_IGNORE_READONLY` | 0x10 | Delete a read-only file. Requires `FILE_WRITE_ATTRIBUTES` as well. |

The open has to hold `DELETE`, or the call fails with `EACCES`. <a id="cite-facs.delete.disposition-needs-delete"></a> The
right was checked when the handle was opened, including through the
parent; the call checks the handle's mask, not the descriptor.

**POSIX semantics** remove the name at once, as `unlink(2)` does, and
open handles carry on with the unnamed file. <a id="cite-facs.delete.posix-now"></a> This is how a
Windows client's POSIX-semantics delete, and a Peios program's "delete
this file I hold open", are carried out. A directory has to be empty,
or the call fails with `ENOTEMPTY`.

Other opens of the file were checked against this open's `DELETE` when
each was opened, so the call does not repeat the share check. A read-only
regular file without `IGNORE_READONLY` fails with `EPERM`. Calling it on
an unmanaged descriptor fails with `EOPNOTSUPP`.

<a id="trm-3-9-10-5"></a>

## Renaming through a handle <a id="cite-facs.rename.handle"></a>

`kacs_rename(fd, newdirfd, newpath, flags)` moves the link an open
handle names to `newpath`, resolved relative to `newdirfd` as by
`renameat2()`. Its flags are those of NT's `FILE_RENAME_INFORMATION_EX`:

| Flag | Value | Meaning |
|---|---|---|
| `KACS_RENAME_REPLACE_IF_EXISTS` | 0x01 | Replace an existing file at the destination. |
| `KACS_RENAME_POSIX_SEMANTICS` | 0x02 | Replace a destination file that is open, if its opens share delete. |
| `KACS_RENAME_IGNORE_READONLY` | 0x40 | Replace a read-only destination file. |

An open file's name follows renames, so the handle always names its
current link; renaming by handle cannot hit a different file that has
since taken the old name. On StrataFS the link is found from the file's
provider instead ([Stacked filesystems](#trm-3-9-10-9)). Authorization is:

- `DELETE` in the handle's granted mask, for removing the source link; <a id="cite-facs.rename.needs-delete"></a>
- a live check for `FILE_ADD_FILE`, or `FILE_ADD_SUBDIRECTORY` for a
  directory, on the destination directory; and
- where a file is replaced, a live check for `DELETE` on it or
  `FILE_DELETE_CHILD` on its parent. <a id="cite-facs.rename.replace-checks"></a>

A replaced file that is open fails the rename with `EBUSY`, unless
`POSIX_SEMANTICS` is given and all its opens share delete. A replaced
file that is delete-pending, or read-only without `IGNORE_READONLY`,
also fails. A directory is never replaced. A destination that exists
without `REPLACE_IF_EXISTS` fails with `EEXIST`. If the handle's link
has already been removed, the call fails with `ENOENT`.

<a id="trm-3-9-10-8"></a>

## Deleting and renaming by name <a id="cite-facs.share.unlink-rename-by-name"></a>

NT treats deleting a file by name as an open with `DELETE`, so the
Linux calls obey the same rules. `unlink(2)`, `rmdir(2)` and `rename(2)`
fail with `EBUSY` when the source, or a file the rename would replace:

- is held by an open that does not share delete; or
- is delete-pending.

This covers `rm`, `mv`, and editors that save by renaming a new file
over the old one. The limit on denials means that only someone who
could delete a file can stop others deleting it. Their access checks
are unchanged ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4>)). Plain deletion by name is still
immediate: the name goes at once, and open handles carry on.

<a id="trm-3-9-10-6"></a>

## Ancestor pinning <a id="cite-facs.pin.ancestors"></a>

Windows will not rename or remove a folder while a file beneath it is
open. Linux has no such rule, and Peios keeps Linux's for its own
programs. An open made with `KACS_OPEN_PIN_ANCESTORS` asks for the
Windows rule for that one file: while it is open, each directory above
it, up to the root of the mount it was opened through, is **pinned**.
A pinned directory cannot be renamed, removed, or replaced by a rename,
by any process; those calls fail with `EBUSY`. <a id="cite-facs.pin.refuses-rename-rmdir"></a>

The pin follows the link the file was opened through, and the
directories it pins are those above that link when the open was made.
It is held as a count on each directory, so many pinned files beneath
one directory pin it once each. The counts are taken in a single walk
that is repeated if a rename moves one of the directories while the
walk is in progress, and dropped when the open's description closes.
<a id="cite-facs.pin.counts"></a> The pinned file itself is not pinned: renaming or deleting it is
governed by share modes.

Pinning blocks other people's work, so it requires
`SeLockParentagePrivilege`. File servers hold it, to give the Windows
clients they serve the folder protection those clients expect from each
other. <a id="cite-facs.pin.privilege"></a>

<a id="trm-3-9-10-9"></a>

## Stacked filesystems <a id="cite-facs.share.stacked"></a>

A stacking filesystem shows files that live on another filesystem
beneath it, the **provider**. StrataFS gives every lookup of a name a
new inode of its own, so KACS keeps a file's share registrations,
delete-pending mark and pin counts on the provider's inode instead. All
routes to a file therefore see the same state: the merged view, another
StrataFS mount over the same stratum, and the stratum itself. A regular
file's open registers through the backing file that StrataFS opens on
the provider. A directory's open has no backing file, so it registers on
its provider itself. <a id="cite-facs.share.stratafs-provider"></a>

**Copy-up.** When StrataFS copies a regular file up to its writable
stratum, the file's opens move their registrations to the copy. A
directory copied up while it is open keeps its registrations and pins
on the former provider, so opens and removals made after the copy-up do
not see them. A directory present in more than one stratum cannot be
renamed in any case. <a id="cite-facs.share.stratafs-copy-up"></a>

**Renaming through a handle.** A StrataFS open's own name is the one it
was looked up by, which goes out of date when the file is renamed. The
provider is renamed in its own filesystem, which keeps its name current,
so `kacs_rename` finds the handle's link there:

1. it takes the provider's path within its stratum;
2. it looks that path up again through the mount the handle was opened
   through, and locks it as `rename(2)` would;
3. it checks that the name still reaches the same provider, retrying if
   a rename moved it meanwhile.

After a copy-up the handle names the copy. A name that a higher stratum
masks is not the handle's file, and the call fails with `ENOENT`, as it
does when the link has been removed. A file whose provider is a
read-only stratum fails with `EROFS`, as `rename(2)` does. <a id="cite-facs.rename.stratafs"></a>

**Overlayfs.** A file's opens register on its real inode through their
backing files. A directory opened through overlayfs opens its real
directory as a plain open, so the real directory sees a legacy open that
shares everything, and the native open's share mode is not enforced. <a id="cite-facs.share.overlayfs"></a>

---

# Byte-Range Locks

_Peios Kernel / Internals / KACS / File security_

> NT byte-range locks, kept by the kernel and enforced on every read and write — when they are checked, what they block, and the limit on who can block whom.

<a id="trm-3-9-11"></a>

An NT byte-range lock reserves part of a file for one open. An
exclusive lock keeps every other open from reading or writing the range;
a shared lock keeps everyone, its holder included, from writing it.
Unlike Linux's advisory `fcntl` and `flock` locks, these are
**enforced**: a read or write that conflicts with another open's lock
fails, whichever program issued it. <a id="cite-facs.lock.enforced"></a> KACS keeps them for regular files
on FACS-managed mounts; `kacs_lock` on anything else fails with
`EOPNOTSUPP`.

Linux's own locks are unchanged and independent. A program that takes
`fcntl` locks neither sees nor conflicts with byte-range locks, except
that its reads and writes are checked against them like everyone
else's.

<a id="trm-3-9-11-1"></a>

## Taking and releasing locks <a id="cite-facs.lock.call"></a>

`kacs_lock(fd, args, size)` takes or releases a lock through an open
handle. `struct kacs_lock_args` gives the range as `offset` and
`length`, the operation, and flags:

| Operation | Value | Meaning |
|---|---|---|
| `KACS_LOCK_SHARED` | 1 | Take a shared lock. |
| `KACS_LOCK_EXCLUSIVE` | 2 | Take an exclusive lock. |
| `KACS_LOCK_UNLOCK` | 3 | Release a lock this open holds over exactly this range. |
| `KACS_LOCK_CANCEL` | 4 | Cancel this open's waiting request named by `cookie`. |

The open has to hold a data right — `FILE_READ_DATA`, `FILE_WRITE_DATA`
or `FILE_APPEND_DATA` — or the call fails with `EACCES`. <a id="cite-facs.lock.needs-data-right"></a> A lock
belongs to the open file description that took it, so descriptors
duplicated from it share its locks. When the description closes, its
locks are released and its waiting requests cancelled. <a id="cite-facs.lock.owner-and-release"></a>

Lock conflicts follow MS-FSA 2.1.4.10. Two locks of different opens
conflict where their ranges overlap and either is exclusive. An open's
exclusive lock also conflicts with its own overlapping exclusive lock.
A zero-length lock is a point at its offset, and the range from offset
zero with length zero conflicts with nothing. <a id="cite-facs.lock.conflicts"></a>

A request that conflicts waits until it can be granted, unless it
carries `KACS_LOCK_FAIL_IMMEDIATELY`, in which case it fails with
`EAGAIN`. A waiting request can be interrupted by a signal (`EINTR`),
or cancelled by another thread with `KACS_LOCK_CANCEL` and the same
`cookie`, in which case it fails with `ECANCELED`. Waiting requests are
granted in the order they arrived as the conflicting locks go.
<a id="cite-facs.lock.waiting"></a> Unlocking a range this open does not hold exactly fails with `ENOLCK`.

<a id="trm-3-9-11-2"></a>

## What locks block <a id="cite-facs.lock.io-checks"></a>

Each operation that reads or changes a file's contents is checked
against the locks of **other** opens:

| Operation | Checked as |
|---|---|
| Read | A read of its range |
| Write, including append | A write of its range |
| `truncate`, `ftruncate` | A write of the range between the old and new size |
| An open that truncates | Not checked, as on Windows: `O_TRUNC`, and a native open with `OVERWRITE`, `OVERWRITE_IF` or `SUPERSEDE` |
| `fallocate` that changes contents | A write of the range it changes, to end of file for collapse and insert |

An open that truncates is let through as Windows lets an overwriting
`CreateFile` through: the locks it drops go with the data, and the
holders' later I/O is checked against what is left. <a id="cite-facs.lock.open-truncate-unchecked"></a>

An exclusive lock blocks reads and writes; a shared lock blocks writes.
A shared lock also blocks its own holder's writes. A conflicting
operation fails with `EAGAIN`; it does not wait. <a id="cite-facs.lock.io-eagain"></a>

The check covers every way of issuing these operations: `read`,
`write` and their vectored and positioned forms, `sendfile`, `splice`
and `copy_file_range`, direct I/O, AIO and io_uring.

<a id="trm-3-9-11-3"></a>

## When a lock takes effect <a id="cite-facs.lock.at-issue"></a>

An I/O is checked against the lock list when it is **issued**. Granting
a lock does not wait for I/O already admitted: an I/O that passed its
check before a conflicting lock was granted may finish after it, and
counts as having happened before the lock. This is the guarantee
Windows gives. No lock is held across the I/O itself, so asynchronous
I/O completing elsewhere needs no special treatment, and an I/O cannot
deadlock against a lock request.

A file with no byte-range locks costs one check that its lock list is
empty.

<a id="trm-3-9-11-4"></a>

## Memory mappings are not covered <a id="cite-facs.lock.mmap-excluded"></a>

Loads and stores through a memory mapping are not checked against
locks, as on Windows, where mapped views bypass byte-range locks.
Mapping a file, and changing a mapping's protection, are checked only
by the handle's rights ([Use-Time Semantics](</kernel/internals/kacs/file-security/use-time-semantics.md#trm-3-9-4-1>)).

<a id="trm-3-9-11-5"></a>

## Who can block whom <a id="cite-facs.lock.dos-limit"></a>

Enforced locks would let any reader stop others using a file. KACS
limits their reach as it limits share modes: a lock blocks other opens'
reads and writes only if the open that took it could write the file
itself, that is, if the file's descriptor grants its opener
`FILE_WRITE_DATA` or `FILE_APPEND_DATA`. A lock taken by an opener who
could not write the file still conflicts with other locks, so
cooperating readers can coordinate with it, but it blocks no I/O.

<a id="trm-3-9-11-6"></a>

## Stacked filesystems <a id="cite-facs.lock.stacked"></a>

Through StrataFS, a lock belongs to the backing file its open reaches
and is held on the provider, so it covers every route to that file. A
copy-up gives the file a new provider: locks taken before it stay with
the former provider, and I/O through the copy is not checked against
them. Locks through overlayfs are not supported, and `kacs_lock` fails
with `EOPNOTSUPP`.

---

# Leases

_Peios Kernel / Internals / KACS / File security_

> NT caching leases kept by the kernel for a lease manager such as a file server — the read, handle and write states, what breaks them, and how breaks are delivered.

<a id="trm-3-9-12"></a>

A lease lets a holder cache a file safely. Its state is any combination
of three NT caching bits:

| State | Value | The holder may cache |
|---|---|---|
| `KACS_LEASE_READ` | 0x1 | The file's contents and attributes, for reading. |
| `KACS_LEASE_HANDLE` | 0x2 | Its open handles, keeping them open after its own client has closed them. |
| `KACS_LEASE_WRITE` | 0x4 | Changes to the contents, not yet written back. |

When another open or operation would make the cached state wrong,
KACS **breaks** the lease: it tells the holder, waits for the holder to
flush and give up the state, then lets the operation proceed. A file
server holds leases on behalf of its clients and relays the breaks to
them, so a local program and a network client see a consistent file.
<a id="cite-facs.lease.purpose"></a>

Leases cover regular files and directories on FACS-managed mounts.
A directory lease can hold only read and handle caching. Below a
stacking filesystem a lease is held on the provider an open reaches
([Stacked filesystems](#trm-3-9-12-6)).

<a id="trm-3-9-12-1"></a>

## Lease managers <a id="cite-facs.lease.manager"></a>

A lease is held through a **lease manager**, created by
`kacs_create_lease_manager(flags, break_timeout_ms)`. The call returns a
descriptor; `KACS_LEASE_MANAGER_CLOEXEC` and
`KACS_LEASE_MANAGER_NONBLOCK` set close-on-exec and non-blocking
reads. Break notices for every lease the manager holds arrive on that
descriptor.

Each lease is identified by its manager and a 16-byte **key** the
manager chooses. Opens with the same key belong to one holder: an open
made with a key does not break the leases its manager holds under that
key ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-12>)). <a id="cite-facs.lease.key"></a> A file server gives each client lease
its own key, and each oplock its own unique key.

Closing the manager's last descriptor releases all its leases.

<a id="trm-3-9-12-2"></a>

## Requesting a lease <a id="cite-facs.lease.request"></a>

`kacs_lease(fd, manager_fd, args, size)` requests, changes or releases
the lease on the file `fd` refers to. The open has to have been made
with `KACS_OPEN_LEASE_KEY`, naming the same manager and the key given
in `args`; otherwise the call fails with `EINVAL`.

KACS grants as much of the requested state as current opens allow,
writes the granted state back into `args.state`, and may grant none.
<a id="cite-facs.lease.grant"></a>

- **Read** needs the open to hold a read right, and no open under
  another key to hold write access.
- **Write** needs the open to hold a write right, and no open of the
  file under another key.
- **Handle** is granted with read.

A state of zero releases the lease. A lease is also released when the
last open under its key closes, unless it holds handle caching.

<a id="trm-3-9-12-3"></a>

## What breaks a lease <a id="cite-facs.lease.break-points"></a>

Only operations from outside the holder break its lease: an operation
through an open under the lease's own key never does.

| Operation by another holder | Breaks | Reason |
|---|---|---|
| Opening the file | Write | `KACS_LEASE_BREAK_OPEN` |
| An open refused by a sharing conflict | Handle, then the open is checked again | `KACS_LEASE_BREAK_SHARING` |
| Writing the file | Read | `KACS_LEASE_BREAK_WRITE` |
| Changing its size | Read | `KACS_LEASE_BREAK_SIZE` |
| Taking a byte-range lock | Read | `KACS_LEASE_BREAK_LOCK` |
| Renaming or linking it, or renaming a directory above it | Handle | `KACS_LEASE_BREAK_NAMESPACE` |
| Deleting it, or setting its delete disposition | Handle | `KACS_LEASE_BREAK_DELETE` |
| Changing its security descriptor | Handle | `KACS_LEASE_BREAK_SECURITY` |
| Changing its attributes or extended attributes | Read | `KACS_LEASE_BREAK_ATTRIBUTES` |
| Adding, removing or renaming an entry of a leased directory | Read and handle | `KACS_LEASE_BREAK_CHILD` |

Breaking write also breaks whatever the new open could not share: a
writer breaks read as well. A broken lease falls to the state the
operation can live with, not necessarily to none.

The holder of a lease that loses only read caching can lose nothing it
has not already written, so such a break is a **notice**: the operation
does not wait for it. Every other break waits. <a id="cite-facs.lease.read-break-no-wait"></a>

Most of these are the points at which Linux breaks its own leases and
NFS delegations, and KACS's leases are entries in the same table, so
the existing break points reach them. KACS adds the others: writes and
size changes through descriptors that were already open, byte-range
locks, security changes, and sharing conflicts.

<a id="trm-3-9-12-4"></a>

## Break notices <a id="cite-facs.lease.notices"></a>

Reading a lease-manager descriptor returns break notices, each a
`struct kacs_lease_break`: the lease's key, the file's device and inode
number, the current and new state, the reason, and an epoch that counts
the lease's breaks. The descriptor is readable with `poll()` when a
notice is waiting.

Notices are never dropped. A lease has at most one break outstanding,
so a manager's queue is bounded by the number of leases it holds.
<a id="cite-facs.lease.lossless"></a>

The holder acknowledges a break with `kacs_lease`, setting
`KACS_LEASE_ACKNOWLEDGE` and a state no greater than the notice's new
state. The waiting operation then proceeds.

<a id="trm-3-9-12-5"></a>

## Timeouts <a id="cite-facs.lease.timeout"></a>

A break not acknowledged within the manager's break timeout is
completed by KACS: the lease is reduced to the new state, the waiting
operation proceeds, and the manager receives a notice with reason
`KACS_LEASE_BREAK_TIMEOUT`. The timeout is set when the manager is
created, in milliseconds, from 1 to 35 000; zero gives the default of
35 seconds, the time SMB allows a client to acknowledge a break.

An operation waiting on a break can be interrupted by a signal. Only
the waiting operation fails; the break goes on.

<a id="trm-3-9-12-6"></a>

## Stacked filesystems <a id="cite-facs.lease.stacked"></a>

Through StrataFS, a regular file's lease is held on the provider its
open reaches, so it covers every route to that file. A copy-up gives the
file a new provider: a lease taken before it stays with the former
provider, and changes made through the copy do not break it. Leases on
StrataFS directories, and on anything reached through overlayfs, are not
supported; `kacs_lease` fails with `EOPNOTSUPP`.

---

# Special Attributes

_Peios Kernel / Internals / KACS / File security_

> The read-only flag KACS enforces for every process, and the settable Created At date, kept in the special-attributes extended attribute.

<a id="trm-3-9-13"></a>

KACS keeps a file's **special attributes** in the extended attribute
`security.peios.sattr`, beside its security descriptor in
`security.peios.sd`. There are two today:

- **Read-only**, which KACS enforces for every process.
- **Created At**, a settable creation date.

<a id="trm-3-9-13-1"></a>

## Reading and writing them <a id="cite-facs.sattr.access"></a>

The attribute is read and written with the ordinary extended-attribute
calls — `getxattr`, `setxattr` and their descriptor and `*at` forms —
using `struct kacs_sattr` as the value. KACS answers these calls
itself. Reading needs `FILE_READ_ATTRIBUTES`, and writing or removing
needs `FILE_WRITE_ATTRIBUTES`, rather than the extended-attribute
rights. <a id="cite-facs.sattr.rights"></a> Through a descriptor, the right comes from the handle's
granted mask; by path, from a live check, which may grant
`FILE_READ_ATTRIBUTES` through the parent ([KACS-Native Open](</kernel/internals/kacs/file-security/kacs-native-open.md#trm-3-9-2-8>)).

| Field | Meaning |
|---|---|
| `version` | `KACS_SATTR_VERSION`, currently 1. |
| `valid` | The fields a write changes. A read sets every bit. |
| `attributes` | `KACS_SATTR_READONLY` (0x1). |
| `flags` | On a read, `KACS_SATTR_CREATED_AT_SET` if Created At is set. On a write, `KACS_SATTR_CREATED_AT_CLEAR` unsets it. |
| `created_at_sec`, `created_at_nsec` | Created At, as seconds and nanoseconds since the Unix epoch. |

A write changes only the fields its `valid` mask names and leaves the
others as they are. Two programs changing different attributes at once
therefore cannot undo each other's change. <a id="cite-facs.sattr.merge"></a> A write with an unknown
version, `valid` bit, attribute or flag, a nonzero `__pad`, a value of
the wrong size, or `XATTR_CREATE` or `XATTR_REPLACE` fails with
`EINVAL`. Removing the attribute clears read-only and unsets Created
At.

The attribute is stored only while something is set, and reading a
file that has none fails with `ENODATA`: it is not read-only, and has no
Created At.
Tools that copy extended attributes copy a stored attribute with the
rest; a copy that should keep an unset Created At has to read it and
set it on the copy.

<a id="trm-3-9-13-2"></a>

## Read-only <a id="cite-facs.sattr.readonly"></a>

Read-only protects a file against accidental change, and binds its
owner too, without anyone rewriting its permissions. It is the
attribute Windows programs set and check, and source-control tools
mark checked-in files with it.

On a regular file marked read-only, for every process: <a id="cite-facs.sattr.readonly-enforced"></a>

- An open asking `FILE_WRITE_DATA` or `FILE_APPEND_DATA` fails with
  `EACCES`. A legacy open for writing fails the same way. A
  `MAXIMUM_ALLOWED` open is granted neither right, nor
  `FILE_ADD_SUBDIRECTORY` or `FILE_DELETE_CHILD`, following MS-FSA
  2.1.5.1.2.1. `FILE_OVERWRITE` and `FILE_SUPERSEDE` fail with `EACCES`.
- `truncate` by path fails with `EACCES`.
- Deleting it fails with `EPERM`: `unlink(2)`, a rename that would
  replace it, a delete disposition, and an open with delete-on-close,
  which a native open reports as `KACS_STATUS_CANNOT_DELETE`. The
  disposition and rename calls can set this aside with their
  `IGNORE_READONLY` flags ([Sharing and Deletion](</kernel/internals/kacs/file-security/sharing-and-deletion.md#trm-3-9-10-4>)).

The check is made at open and at deletion, not on every write: a handle
opened for writing before the file was marked read-only keeps working,
as on Windows. Renaming a read-only file, and changing its other
attributes or its descriptor, are not affected. Anyone with
`FILE_WRITE_ATTRIBUTES` can clear the flag.

On a directory, read-only is kept and reported but not enforced.
Windows uses the flag on folders to mark them as customized, not to
protect them. <a id="cite-facs.sattr.readonly-directories"></a>

<a id="trm-3-9-13-3"></a>

## Created At <a id="cite-facs.sattr.created-at"></a>

Created At records when a file was created, in the sense a person or a
copy tool means: a copy can carry its original's creation date, and a
Windows client can set it. It is distinct from the filesystem's
**birth time**, which `statx` reports, which nobody can set, and which
records when this inode came into being. Birth time is the forensic
fact; Created At is the user-facing date.

While Created At has not been set, a file's creation date is its birth
time: a reader that finds no Created At, or finds
`KACS_SATTR_CREATED_AT_SET` clear, takes the date from `statx`. KACS
never changes Created At itself, and `statx` continues to report the
birth time.

---

# Linux credentials

_Peios Kernel / Internals / KACS / Linux credentials_

> Find the Peios kernel articles about linux credentials.

Use these articles to understand linux credentials in the Peios kernel.

- [DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md>)
- [setuid Behaviour](</kernel/internals/kacs/linux-credentials/setuid-behaviour.md>)
- [Netlink](</kernel/internals/kacs/linux-credentials/netlink.md>)

---

# DAC Neutralisation

_Peios Kernel / Internals / KACS / Linux credentials_

> Linux evaluates DAC before any LSM hook fires, so KACS has to neutralise it — the capability switchboard, the compatibility state and the LSM stack.

<a id="trm-3-10-2"></a>

Linux evaluates DAC — UID, GID and mode-bit checks — *before*
consulting LSM hooks. If DAC denies an operation the hook never fires,
and KACS cannot override a DAC denial: LSM hooks are restrictive, able
to further deny what DAC would allow but never to grant what DAC has
refused.

KACS therefore neutralises DAC so the hooks always fire. Every process
receives a set of Linux capabilities that bypass the DAC gates, and
those capabilities are mandatory substrate rather than grants. <a id="cite-cred.dac.every-process-gets-allow"></a>

<a id="trm-3-10-2-1"></a>

## The capability switchboard

Linux's capabilities fall into three categories, and
`security_capable()` is authoritative for all of them — the raw
capability sets on `struct cred` are compatibility-visible state that
answers nothing. <a id="cite-cred.dac.security-capable-authoritative"></a>

**ALLOW** capabilities exist to override UID-based permission checks
on operations KACS enforces through its own hooks, so DAC never blocks
something KACS will evaluate independently: <a id="cite-cred.dac.allow-set"></a>

| CAP | Name | Rationale |
|---:|---|---|
| 0 | `CAP_CHOWN` | KACS file hooks enforce. |
| 1 | `CAP_DAC_OVERRIDE` | KACS file hooks enforce. |
| 2 | `CAP_DAC_READ_SEARCH` | KACS file hooks enforce. |
| 3 | `CAP_FOWNER` | KACS file hooks enforce. |
| 4 | `CAP_FSETID` | KACS file hooks enforce. |
| 5 | `CAP_KILL` | The `task_kill` hook enforces. |
| 6 | `CAP_SETGID` | Cosmetic under KACS. |
| 7 | `CAP_SETUID` | Cosmetic under KACS. |
| 11 | `CAP_NET_BROADCAST` | Unused in modern kernels. |
| 15 | `CAP_IPC_OWNER` | KACS IPC hooks enforce. |
| 28 | `CAP_LEASE` | KACS file hooks enforce. |
| 10 | `CAP_NET_BIND_SERVICE` | The port's reservation SD decides at `socket_bind`; the Linux privileged-port floor never refuses. |

**PRIVILEGE** capabilities gate operations no other KACS hook covers,
and map to a KACS privilege: <a id="cite-cred.dac.privilege-mapped"></a>

| CAP | Name | Privilege |
|---:|---|---|
| 9 | `CAP_LINUX_IMMUTABLE` | `SeTcbPrivilege` |
| 12 | `CAP_NET_ADMIN` | `SeTcbPrivilege` |
| 13 | `CAP_NET_RAW` | `SeTcbPrivilege` |
| 14 | `CAP_IPC_LOCK` | `SeLockMemoryPrivilege` |
| 16 | `CAP_SYS_MODULE` | `SeLoadDriverPrivilege` |
| 17 | `CAP_SYS_RAWIO` | `SeTcbPrivilege` |
| 18 | `CAP_SYS_CHROOT` | `SeTcbPrivilege` |
| 19 | `CAP_SYS_PTRACE` | `SeDebugPrivilege` |
| 20 | `CAP_SYS_PACCT` | `SeTcbPrivilege` |
| 21 | `CAP_SYS_ADMIN` | `SeTcbPrivilege` (but see the mount note below) |
| 22 | `CAP_SYS_BOOT` | `SeShutdownPrivilege` |
| 23 | `CAP_SYS_NICE` | `SeIncreaseBasePriorityPrivilege` |
| 24 | `CAP_SYS_RESOURCE` | `SeIncreaseQuotaPrivilege` |
| 25 | `CAP_SYS_TIME` | `SeSystemtimePrivilege` |
| 26 | `CAP_SYS_TTY_CONFIG` | `SeTcbPrivilege` |
| 27 | `CAP_MKNOD` | `SeTcbPrivilege` |
| 29 | `CAP_AUDIT_WRITE` | `SeAuditPrivilege` |
| 30 | `CAP_AUDIT_CONTROL` | `SeSecurityPrivilege` |
| 33 | `CAP_MAC_ADMIN` | `SeSecurityPrivilege` |
| 34 | `CAP_SYSLOG` | `SeTcbPrivilege` |
| 35 | `CAP_WAKE_ALARM` | `SeTcbPrivilege` |
| 36 | `CAP_BLOCK_SUSPEND` | `SeTcbPrivilege` |
| 37 | `CAP_AUDIT_READ` | `SeSecurityPrivilege` |
| 38 | `CAP_PERFMON` | `SeSystemProfilePrivilege` **or** `SeProfileSingleProcessPrivilege` **or** `SeLoadDriverPrivilege` |
| 39 | `CAP_BPF` | `SeTcbPrivilege` |
| 40 | `CAP_CHECKPOINT_RESTORE` | `SeTcbPrivilege` |

`CAP_PERFMON` is the one **OR-mapped** entry: the Linux capability
genuinely spans several Peios privilege tiers, and no single privilege
covers everything it gates. The check succeeds if the caller holds any
of the three, and every one it holds is marked used. <a id="cite-cred.dac.perfmon-or-mapped"></a> Per-operation
enforcement then happens at the relevant syscall hook, which checks
the *specific* privilege the *specific* operation needs ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).
OR-mapping stops the capability ceiling manufacturing false denials;
it grants nothing the holder does not already have.

`CAP_SYS_ADMIN` maps to `SeTcbPrivilege` and is **not** OR-mapped, which
would be the obvious way to let administrators mount and is the wrong
one: `CAP_SYS_ADMIN` gates dozens of unrelated operations, so widening
it would hand out far more than mounting.

Mounting is handled outside the capability table instead. `may_mount()`
(`fs/namespace.c`, patched) calls `pkm_kacs_may_mount_op()`, whose first
rung accepts `SeManageVolumePrivilege` **or** `SeTcbPrivilege`, before
falling back to the ordinary `CAP_SYS_ADMIN` check. <a id="cite-cred.dac.may-mount-manage-volume"></a> In a mount
namespace the caller created for itself, a second rung admits a bind
mount, an unmount, a `pivot_root`, or a new tmpfs, proc or read-only
stratafs on the namespace's own security descriptor instead ([A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md#trm-3-13-1>)); in
the initial namespace the privilege is the only route. Every other `CAP_SYS_ADMIN` caller still needs the TCB.

It has to be asked there rather than through the `sb_mount` LSM hook:
`may_mount()`'s capability check runs *before* `security_sb_mount()`, so
an LSM is never consulted about a mount the capability check already
refused. A hook can narrow that decision; it cannot widen it.

The `CAP_SYS_ADMIN` gate on creating a namespace (`kernel/nsproxy.c`,
patched) has one carve-out of the same kind: a request for a mount
namespace alone passes without it, because the table it yields is an
object its creator owns. Any other namespace type, alone or in
combination, still needs the TCB. <a id="cite-cred.dac.mount-namespace-ungated"></a>

`CAP_SYS_BOOT` carries an extra condition the table cannot express: a
token whose logon session is of a remote origin — Network,
NetworkCleartext, NewCredentials or RemoteInteractive — additionally
requires `SeRemoteShutdownPrivilege`. <a id="cite-cred.dac.sys-boot-remote-shutdown"></a>

**DENY** capabilities are refused unconditionally, whatever privilege
the caller holds: `CAP_SETPCAP` (8) and `CAP_SETFCAP` (31), because
capabilities are dead under KACS, and `CAP_MAC_OVERRIDE` (32), because
KACS is the active LSM and must not be bypassable. <a id="cite-cred.dac.deny-set"></a>

An unmapped or unknown capability is denied by default. The
switchboard fails closed. <a id="cite-cred.dac.unmapped-denied"></a>

<a id="trm-3-10-2-2"></a>

## Compatibility state

Programs may inspect the credential capability sets with `capget()` or
`/proc/<pid>/status`, and may attempt to mutate the non-ALLOW subset
with `capset()` or `prctl()`. None of that is authoritative.

`capget()` and `/proc/<pid>/status` report the ALLOW substrate as
present in the effective, permitted and inheritable sets — reported as
`CapEff`, `CapPrm` and `CapInh`, and additionally `CapBnd`, by the proc
interface. <a id="cite-cred.dac.capget-reports-allow"></a> Non-ALLOW bits present in the
credential state may also be reported, but grant no authority.
`CapAmb` reports raw Linux ambient state; the ALLOW substrate does not
depend on ambient capabilities.

The strict invariant is that the ALLOW set is mandatory substrate and
has to survive wherever Linux capability mechanics would otherwise
drop it out from under KACS. `capset()` rejects any request clearing
an ALLOW capability from the effective, permitted or inheritable sets,
and bounding-set drops and ambient manipulation reject anything that
would clear or exclude one. <a id="cite-cred.dac.allow-set-undroppable"></a> The implementation is slightly stricter
than that: an ambient *raise* of an ALLOW capability is refused too,
not only a clear. <a id="cite-cred.dac.ambient-raise-refused"></a>

After that validation, `capset()` follows ordinary Linux ambient
behaviour — ambient bits no longer present in both the requested
permitted and inheritable sets may be cleared. Because requests
clearing ALLOW bits from permitted or inheritable are denied outright,
that intersection can never indirectly clear an existing ALLOW ambient
bit.

Direct mutation of non-ALLOW state is therefore compatibility-only. It
may change what `capget()` reports and cannot change the authority
answer for any capability-gated operation.

<a id="trm-3-10-2-3"></a>

## Neutralised native paths

Native commoncap helpers that make raw capability-subset decisions
*before* a KACS hook are neutralised where KACS has an authoritative
hook of its own. That covers the subset gates in ptrace access,
`PTRACE_TRACEME`, and `task_setnice`, `task_setscheduler` and
`task_setioprio` — each replaced by an unconditional allow, leaving
the KACS process-descriptor and PIP hooks to decide. <a id="cite-cred.dac.commoncap-neutralised"></a> Capability checks
that reach `security_capable()` directly stay under the switchboard.

For raw xattr operations the FACS metadata hooks are authoritative, so
the native security-xattr capability prechecks that would run first
are skipped. <a id="cite-cred.dac.xattr-precheck-skipped"></a> This does not revive Linux file capabilities: installing
or replacing non-empty `security.capability` data stays denied by the
dead `CAP_SETFCAP` policy, with the single exception of the
KACS-owned StrataFS clone ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)), and exec-time file-capability
grants remain suppressed. <a id="cite-cred.dac.file-caps-dead"></a> Removing stale metadata goes through the
ordinary `FILE_WRITE_EA` path.

One structural wrinkle: `security_capable()` reaches the KACS
switchboard twice — once through the patched commoncap entry point and
once through the KACS `capable` hook — so a privilege consulted this
way is marked used twice. <a id="cite-cred.dac.privilege-use-double-counted"></a> The authorization answer is unaffected; the
privilege-use accounting double-counts.

<a id="trm-3-10-2-4"></a>

## The LSM stack

MAC LSMs — SELinux, AppArmor, SMACK, TOMOYO — and the BPF LSM have to
be disabled. <a id="cite-cred.dac.mac-lsms-disabled"></a> They would independently deny operations from their own
label and policy systems, undermining KACS's claim to be the sole
identity-based authorization mechanism and FACS's to be the sole file
access authority. Non-MAC LSMs are permitted where they make no
identity-based access decision: landlock, lockdown and integrity stack
safely. <a id="cite-cred.dac.non-mac-lsms-allowed"></a> Yama is not among them and is not built: its
relational `ptrace_scope` answers every attach to a non-descendant with
"does the caller hold `CAP_SYS_PTRACE`", which the switchboard maps to
SeDebugPrivilege, so it would decide ahead of the process descriptor
and PIP dominance that [Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>) makes the ptrace authority. The same-uid
attach it exists to close cannot arise under KACS, which never grants
on uid. <a id="cite-cred.dac.yama-not-built"></a>

The check is made at initialisation and KACS refuses to activate if it
fails — but it is a **build-configuration** test rather than an
inspection of the live LSM stack. It tests whether each conflicting
LSM is enabled in the kernel config, and never parses `CONFIG_LSM` or
enumerates what is actually registered.

---

# setuid Behaviour

_Peios Kernel / Internals / KACS / Linux credentials_

> Under KACS a UID has no security properties — what the setuid syscalls do, what the setuid bit does at exec, and the compatibility gaps that remain.

<a id="trm-3-10-3"></a>

Under KACS a UID has no security properties whatever. It is not
consulted in any access decision, appears in no descriptor, and is
referenced by no ACE. It is a compatibility value stored in
`struct cred` for the sole purpose of answering `getuid()`.

<a id="trm-3-10-3-1"></a>

## The setuid syscalls

The `setuid` family — `setuid`, `setgid`, `setresuid`, `setresgid`,
`setgroups` — changes Linux credentials.

**Without `SeAssignPrimaryTokenPrivilege`**, which is the common case,
the call is a silent no-op. It returns success, and every credential
field is restored from the old credential: UIDs, GIDs, supplementary
groups, capabilities. <a id="cite-cred.setuid.unprivileged-noop"></a> Neither the credential nor the token changes,
and the process's authority before and after is identical.

The silent success preserves consistency between the visible UID and
the KACS identity. Changing the UID without changing the token would
produce subtle failures — the wrong home directory from `getpwuid()`,
for instance — for no security benefit.

**With `SeAssignPrimaryTokenPrivilege`** the design calls for the
credential change to trigger a full identity swap, redirected to authd
to obtain a token for the target UID's principal, so that both token
and credential change together.

That is not what happens. A caller holding the privilege receives
`EOPNOTSUPP` and the call **fails**. <a id="cite-cred.setuid.privileged-eopnotsupp"></a> There is no authd redirect
anywhere in the LSM. The practical effect is that the privileged path
is unavailable rather than dangerous: a TCB component cannot change
identity this way, and has to install a token directly instead
([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).

<a id="trm-3-10-3-2"></a>

## The setuid bit on exec

The filesystem setuid bit tells the kernel to change the effective UID
to the file owner's on exec.

**Without the privilege**, the Linux-visible UID and GID slots change
to the file owner's identity while the token is untouched — a cosmetic
escalation in which the process sees `geteuid() == 0` while KACS
continues to enforce the original token. <a id="cite-cred.setuid.exec-bit-cosmetic"></a> Concretely `uid` and `suid`
are set from `euid`, the GID counterparts mirror that, `fsuid` and
`fsgid` are carried over unchanged from the old credential, and the
token is cloned as-is. <a id="cite-cred.setuid.exec-bit-slot-values"></a>

**With the privilege**, the design calls for the slots *and* the token
to change — genuine escalation. As with the syscall, this is not
implemented: an exec that would change UID or GID under a token
holding `SeAssignPrimaryTokenPrivilege` returns `EOPNOTSUPP` and the
exec fails. <a id="cite-cred.setuid.exec-privileged-eopnotsupp"></a>

The asymmetry between the two mechanisms is intentional in the design.
`setuid()` is de-escalation, so leaving everything unchanged is the
safe failure mode. The setuid bit is escalation, and the target binary
expects the euid and will check it — `sudo` verifies
`geteuid() == 0` — so the euid has to change for the binary to
function at all.

| Mechanism | With privilege | Without privilege |
|---|---|---|
| `setuid()` syscall | Designed: all UIDs and token change. Actual: fails with `EOPNOTSUPP`. |  Silent no-op |
| Setuid bit on exec | Designed: euid/suid and token change. Actual: exec fails with `EOPNOTSUPP`. | euid/suid change, token unchanged |

<a id="trm-3-10-3-3"></a>

## The current_fsuid patch

The kernel calls `current_fsuid()` whenever it needs a UID for a
filesystem operation — file creation ownership, quota tracking,
keyring lookup, NFS credentials. KACS redefines it, along with
`current_fsgid()` and `current_fsuid_fsgid()`, to return the projected
value from the effective token rather than `cred->fsuid`. <a id="cite-cred.setuid.fsuid-patch"></a>

So files are created owned by the projected UID, quotas track against
it, per-user keyrings are keyed by it, and an NFS server sees the real
identity rather than UID 0. <a id="cite-cred.setuid.fsuid-consequences"></a>

<a id="trm-3-10-3-4"></a>

## Compatibility gaps

**The privilege-drop pattern.** A daemon that calls `setuid(target)`
and then checks `getuid() != target` to confirm the drop sees success
returned with the UID unchanged. This is intentional — UIDs carry no
security meaning here — and software ported to Peios should use
KACS-native token operations for privilege management instead.

**Direct capability manipulation.** Software that manipulates
capabilities with `capset()` and `capget()`, writes seccomp filters,
or inspects its own capability set may behave unexpectedly ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)).
Seccomp filters themselves install as on Linux — `no_new_privs`, or
`CAP_SYS_ADMIN` resolved to `SeTcbPrivilege` — and `no_new_privs`
keeps its Linux meaning for the one Peios gain an exec can confer:
under it, an exec cannot raise the process's PIP label ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)).

**`setfsuid()`** is a no-op for filesystem purposes, since
`current_fsuid()` ignores `cred->fsuid`; and cosmetic setuid-bit exec
transitions do not flow into the projected values either. <a id="cite-cred.setuid.setfsuid-noop"></a>

**`access()` and `faccessat()`** use the effective token rather than
the real credential — the entire native credential-override machinery
those calls normally use is compiled out. <a id="cite-cred.setuid.access-uses-effective-token"></a> The concept of a "real
identity" separate from the acting one does not exist in KACS.

**`SO_PEERCRED`** returns projected UIDs rather than token
information, and because the switchboard allows `CAP_SETUID`, cosmetic
UID forgery in `SCM_CREDENTIALS` is possible. <a id="cite-cred.setuid.so-peercred-projected"></a> Both are Linux
compatibility metadata, not peer-token authorities: a service needing
authoritative identity uses stream or seqpacket peer-token capture, or
explicit token descriptor passing ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)).

**Legacy `auditd`** records projected UIDs, so KACS audit through KMES
replaces Linux audit for security-relevant logging.

A `uid0` utility — running a program with `cred->uid` forced to 0 for
legacy programs that refuse to start otherwise — is described in the
design and does not exist in the tree. <a id="cite-cred.setuid.uid0-utility-absent"></a> The kernel-side guarantee it
would rely on does hold: `current_fsuid()` ignores `cred->uid`
entirely, so even with such a utility active, filesystem operations
would use the projected UID and files would be owned by the real user.

---

# Netlink

_Peios Kernel / Internals / KACS / Linux credentials_

> Netlink requests are authorised through the capability switchboard — both the socket opener's token and the sender's — synchronously, in the sender's own context.

<a id="trm-3-10-4"></a>

Netlink is the kernel's message interface: a process sends a request
to a kernel subsystem (routing, firewalling, audit, generic netlink
families) and the subsystem answers, or pushes notifications to
multicast groups. The kernel authorises those requests with capability
checks, and on Peios every one of them is a KACS privilege check.

<a id="trm-3-10-4-1"></a>

## Where the checks run

A request to the kernel is handled synchronously: `netlink_unicast`
delivers the message to the family's receive function inside the
sending task's own `sendmsg`, under the family's mutex. <a id="cite-cred.netlink.synchronous-delivery"></a> There is no
later context in which a message is processed, so the sender at every
check is the current thread, and audit attribution needs no capture.
Only messages between two user sockets are queued.

The netlink permission helpers — `netlink_capable`,
`netlink_ns_capable` and `netlink_net_capable`, and through them the
generic-netlink `GENL_ADMIN_PERM` and `GENL_UNS_ADMIN_PERM` operation
flags — test two subjects and require both to pass: the credential
that **opened** the netlink socket, held on the socket's file, and the
**sender**, the current thread. <a id="cite-cred.netlink.two-subject-check"></a> `netlink_allowed`, which gates binding
to a family's multicast groups and sending to another port, tests the
current thread. <a id="cite-cred.netlink.allowed-tests-sender"></a> This is Linux's own two-point rule, introduced after
CVE-2014-0181 so that a privileged program could not be turned into a
deputy by inheriting an unprivileged process's netlink socket as its
standard output.

<a id="trm-3-10-4-2"></a>

## What decides

Every one of those tests reaches `security_capable()` with a specific
credential, and the capability switchboard ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)) evaluates **that
credential's token**: `pkm_kacs_capable_in_cred_ns` looks up the token
on the credential and asks whether it holds a privilege the capability
maps to. <a id="cite-cred.netlink.evaluated-against-cred-token"></a> The opener's file credential carries the opener's token; the
current thread's credential carries the sender's effective token,
impersonation included. So a netlink request is authorised against two
KACS tokens, with the same privilege catalogue and the same fail-closed
behaviour as any other capability check — not against uid bits, and
not against a projection of the token.

The catalogue maps `CAP_NET_ADMIN`, `CAP_NET_RAW` and `CAP_SYS_ADMIN`
to `SeTcbPrivilege`. Configuring the network — adding a route, setting
an interface up, editing a firewall — is therefore a TCB operation on
Peios; an administrator's session cannot do it, and a `RTM_NEWLINK`
from an administrator is answered with `EPERM`. <a id="cite-cred.netlink.rtm-newlink-needs-tcb"></a> Audit control
(`CAP_AUDIT_CONTROL`, `CAP_AUDIT_READ`) maps to `SeSecurityPrivilege`
and audit writes (`CAP_AUDIT_WRITE`) to `SeAuditPrivilege`. Requests
that need no capability — dumps of the routing table or the link list
— are answered for any caller. <a id="cite-cred.netlink.uncapped-requests-open"></a>

<a id="trm-3-10-4-3"></a>

## What netlink carries about the sender

A netlink message's metadata (`NETLINK_CB`) records the sender's
projected UID and GID, in the same form `SO_PEERCRED` uses, and
delivers them to a receiving user socket that asked for
`SCM_CREDENTIALS` with `SO_PASSCRED`. <a id="cite-cred.netlink.cb-carries-projected-ids"></a> As everywhere on Peios, those
values are a projection for compatibility and display, not an
authorisation input ([Credential Projection](</kernel/internals/security/credentials.md#trm-3-10-1>)). Netlink between two user sockets is not
a supported identity-carrying transport: it carries the projection and
nothing more, and a program that needs the peer's token uses an
`AF_UNIX` socket ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)).

---

# System V IPC

_Peios Kernel / Internals / KACS / System V IPC_

> Find the Peios kernel articles about system v ipc.

Use these articles to understand system v ipc in the Peios kernel.

- [Objects and Their Descriptors](</kernel/internals/kacs/system-v-ipc/objects-and-their-descriptors.md>)

---

# Objects and Their Descriptors

_Peios Kernel / Internals / KACS / System V IPC_

> Every System V message queue, shared memory segment and semaphore array carries a security descriptor, stamped at creation and enforced through the LSM IPC hooks.

<a id="trm-3-11-1"></a>

System V IPC — message queues (`msgget`), shared memory segments
(`shmget`) and semaphore arrays (`semget`) — predates file descriptors
and paths: an object is named by an integer key, identified by an
integer id, and persists in the kernel until removed or reboot. Linux
protects each with a nine-bit mode in `struct ipc_perm`, checked by
`ipcperms()` against the caller's UID and GID.

On Peios that mode is inert. `CAP_IPC_OWNER` is in KACS's always-allow
set ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so `ipcperms()` never denies on the mode and always
reaches `security_ipc_permission()`; there KACS decides, against a
security descriptor the object carries. <a id="cite-sysvipc.mode-inert"></a>

<a id="trm-3-11-1-1"></a>

## The descriptor

Each object gets a descriptor when it is created, built from the
creator's effective token: owner and group from the token; the
creator's user SID, `BUILTIN\Administrators` and `SYSTEM` at
`GENERIC_ALL`. <a id="cite-sysvipc.default-descriptor"></a> It is held on the object's LSM blob for the object's
life — persisting with the object across the creator's exit, as SysV
objects do — and released when the object is removed. <a id="cite-sysvipc.descriptor-lifetime"></a>

The rights are those of `<pkm/ipc.h>`:

| Right | Grants |
|---|---|
| `KACS_IPC_READ` | `msgrcv`; `shmat` read-only; `semop` without alter; `GETVAL`, `GETPID`, `GETNCNT`, `GETZCNT`, `GETALL` |
| `KACS_IPC_WRITE` | `msgsnd`; `shmat` read-write; `semop` with alter; `SETVAL`, `SETALL` |
| `KACS_IPC_QUERY_INFORMATION` | `IPC_STAT` and the `SHM_STAT`, `MSG_STAT`, `SEM_STAT` families — together with `KACS_IPC_READ`, since Linux's own `ipcperms()` read check runs before the hook |
| `KACS_IPC_SET_INFORMATION` | `SHM_LOCK`, `SHM_UNLOCK` — `SHM_LOCK` additionally needs `SeLockMemoryPrivilege`, Linux's `CAP_IPC_LOCK` gate |
| `DELETE` | `IPC_RMID` |
| `WRITE_DAC` and `WRITE_OWNER` | `IPC_SET` — one command carries mode, uid and gid, so it needs both |
| `READ_CONTROL` | reading the descriptor with `kacs_get_sd` |

The generic mapping: `GENERIC_READ` is read plus query and
`READ_CONTROL`; `GENERIC_WRITE` is write plus set-information and
`READ_CONTROL`; `GENERIC_EXECUTE` is query and `READ_CONTROL`;
`GENERIC_ALL` is everything above. <a id="cite-sysvipc.generic-mapping"></a>

<a id="trm-3-11-1-2"></a>

## Where the checks run

`ipcperms()` runs for every data operation with the mode bits the
operation would have needed — read, write or both — and
`security_ipc_permission()` maps them to `KACS_IPC_READ` and
`KACS_IPC_WRITE` and runs AccessCheck for the caller's effective token,
under the caller's PIP context, against the object's descriptor. <a id="cite-sysvipc.data-ops-access-check"></a> The
`*get` path with an existing key goes through the same check with the
requested mode. <a id="cite-sysvipc.get-existing-key-checked"></a> The control operations go through the per-object
`shmctl`, `msgctl` and `semctl` hooks, which map the command to the
right in the table above; commands that address no object
(`IPC_INFO`, `SHM_INFO`, `MSG_INFO`, `SEM_INFO`) need nothing. <a id="cite-sysvipc.info-commands-unchecked"></a>

Linux's own ownership check on `IPC_SET` and `IPC_RMID` — that the
caller's effective UID matches the object's creator or owner, or holds
`CAP_SYS_ADMIN` — still runs first, on the projected UID, and cannot be
relaxed by the descriptor: the hooks only ever further restrict. <a id="cite-sysvipc.linux-owner-check-first"></a> So an
administrator who is not the object's creator needs both the
descriptor's `DELETE` (which the default grants Administrators) and
`SeTcbPrivilege` (what `CAP_SYS_ADMIN` maps to) to remove it. The
`uid`, `gid` and `mode` that `IPC_SET` writes remain as Linux stores
them and are what `ipcs` and `IPC_STAT` report; they are informational,
as file mode bits are under FACS.

<a id="trm-3-11-1-3"></a>

## Reading and changing a descriptor

A SysV object has no fd and no path, so `kacs_get_sd` and `kacs_set_sd`
address it by kind and id: one of `KACS_SD_AT_SYSV_SHM`,
`KACS_SD_AT_SYSV_MSG` or `KACS_SD_AT_SYSV_SEM` in `flags`, the object
id in `dirfd`, and a NULL path. <a id="cite-sysvipc.sd-addressing"></a> The object is looked up in the caller's
IPC namespace; an unknown id is `EINVAL`, and so is a removed one,
because `IPC_RMID` drops the id from the namespace in the same step
that marks the object deleted — `EIDRM` is reserved for a lookup that
races that removal and finds the object already dead. <a id="cite-sysvipc.sd-lookup-errors"></a>
Reading needs the rights the requested `SECURITY_INFORMATION` implies
(`READ_CONTROL` for owner, group and DACL; `ACCESS_SYSTEM_SECURITY`
for the SACL), changing needs `WRITE_DAC` or `WRITE_OWNER` as for any
object, and the new descriptor is merged into the existing one
component by component, as for a process descriptor ([Process Security Descriptors](</kernel/internals/kacs/process-security/process-security-descriptors.md#trm-3-3-3>)).

<a id="trm-3-11-1-4"></a>

## Names

The key namespace is claim-on-create: whoever calls `*get` with
`IPC_CREAT` on a free key owns the object, and nothing prevents a
process from claiming a key another program expected to create — the
same shape as the abstract socket namespace and `/dev/shm`. <a id="cite-sysvipc.key-claim-on-create"></a> The
descriptor protects the object once it exists; it cannot protect the
name. A program that needs a specific key uses `IPC_EXCL` and treats a
failure as a signal, and a program that needs identity-carrying
messaging uses an `AF_UNIX` socket ([Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>)): a message queue conveys no
sender identity, and `msgrcv` returns bytes and a type, nothing more.

---

# Network objects

_Peios Kernel / Internals / KACS / Network objects_

> Find the Peios kernel articles about network objects.

Use these articles to understand network objects in the Peios kernel.

- [Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md>)
- [Socket Identity](</kernel/internals/kacs/network-objects/socket-identity.md>)

---

# Port Reservations

_Peios Kernel / Internals / KACS / Network objects_

> Binding a TCP or UDP port is an access check against a reservation — a security descriptor keyed by protocol and port range, read from the registry — not a privilege test against a port number.

<a id="trm-3-12-1"></a>

Ports are a shared, unowned namespace. Linux protects it with one rule:
`bind(2)` below port 1024 needs `CAP_NET_BIND_SERVICE`, and everything
above is anyone's. That is too coarse in one direction — any privileged
process gets every low port — and absent in the other: nothing protects
8080, 3306 or 5432 from whichever process asks first.

On Peios the only thing worth authorising about a port is the **claim**
— binding a non-zero port — and it is authorised the way everything
else is: by a security descriptor. `CAP_NET_BIND_SERVICE` is in the
always-allow set ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so the Linux floor never refuses first, and
every claim reaches `security_socket_bind()`, where KACS decides. <a id="cite-net.port.floor-never-refuses"></a>

The precedent is not Linux but HTTP.sys's URL reservations on Windows:
a sparse table of namespace prefixes, each carrying a descriptor,
consulted when a name is claimed, default-permissive where nothing is
reserved. This chapter moves that model down to the port layer.

<a id="trm-3-12-1-1"></a>

## The object

A **reservation** is a selector mapped to a descriptor. The selector
names a set of protocols and an inclusive port range:

```
<proto>[,<proto>]:<lo>[-<hi>]      proto ∈ tcp | udp | *
```

`tcp:80`, `udp:53`, `tcp,udp:1-1023`, `*:8080`. Ports are decimal,
1–65535, no leading zeros, `lo <= hi`; a protocol may not repeat, so
every selector has one spelling. <a id="cite-net.port.selector-grammar"></a> The address family is deliberately not
part of the selector: a reservation covers IPv4 and IPv6 alike, or
dual-stack squatting — claiming the v6 side of a port reserved on v4 —
would bypass it. <a id="cite-net.port.family-agnostic"></a>

The rights are those of `<pkm/net.h>`:

| Right | Grants |
|---|---|
| `KACS_PORT_BIND` (`0x00000001`) | `bind(2)` to any port the selector contains |
| `READ_CONTROL` | reading the descriptor |

That is the whole mask. Editing a reservation is a registry write,
governed by the registry key's own descriptor — one edit policy for the
table — so `WRITE_DAC` and `WRITE_OWNER` inside a port descriptor mean
nothing and are never honoured. The generic mapping is `GENERIC_EXECUTE`
→ `PORT_BIND`, `GENERIC_READ` → `READ_CONTROL`, `GENERIC_WRITE` → nothing,
`GENERIC_ALL` → both. <a id="cite-net.port.generic-mapping"></a>

<a id="trm-3-12-1-2"></a>

## The table

Reservations live as **values** under one registry key:

```
Machine\System\Network\TcpIp\PortReservations\
    @                 REG_BINARY   SD     the default reservation
    tcp,udp:1-1023    REG_BINARY   SD
    tcp:80            REG_BINARY   SD
```

Each value's name is its selector and its data a self-relative
descriptor. The key's unnamed default value, `@`, is the **default
reservation**: the descriptor for every port no selector contains. <a id="cite-net.port.default-reservation"></a> The
shipped seed grants `PORT_BIND` to Everyone on `@` — an unreserved port
is anyone's, as on Windows — and to SYSTEM and the `bind-low-ports`
capability SID on `tcp,udp:1-1023`, which is the Linux convention
restated as policy. <a id="cite-net.port.shipped-seed"></a> Services then carry their own entries:
`tcp:80,443 → NT SERVICE\httpd: PORT_BIND`, which composes with
per-service SIDs so that a compromised `sshd` cannot take 443 even
though both are "privileged".

The kernel reads the key whole and **rejects it whole**. Every name must
parse, every descriptor must parse, exactly one `@` must exist, and no
two selectors of equal width may overlap — the most specific match
would be ambiguous, and the kernel refuses to guess. <a id="cite-net.port.table-all-or-nothing"></a> On any failure the
load is audited and the previous table stays in force. <a id="cite-net.port.rejected-load-keeps-previous"></a>
The rejection is recorded as `kacs.config.value.rejected` ([Audit Event Schemas](</kernel/internals/kacs/auditing/event-families-and-delivery.md#trm-3-c>)):
`config.key.path` names the key, `config.name` the value at fault where
one is, and `outcome.reason` why — `empty`, `too-large`, `bad-selector`,
`bad-descriptor`, `duplicate-default`, `missing-default` or `overlap` —
with `policy.previous-retained` true and `policy.fallback` saying whether
what stayed in force is the compiled-in table. <a id="cite-net.port.rejected-load-recorded"></a> Nested overlap,
and overlap between selectors of different widths, is how specificity
works and is accepted. <a id="cite-net.port.nested-overlap-accepted"></a>

<a id="trm-3-12-1-3"></a>

## The decision

At `bind(2)` on an `AF_INET` or `AF_INET6` socket whose protocol is TCP,
UDP or UDP-Lite:

1. If the requested port is 0 — ephemeral allocation — nothing is
   checked. Protocols no reservation covers (SCTP, raw) pass untouched. <a id="cite-net.port.ephemeral-unchecked"></a>
2. The **most specific** reservation containing `(protocol, port)` is
   selected: the one covering the fewest ports, regardless of how many
   protocols it names. None → the default reservation. <a id="cite-net.port.most-specific-match"></a>
3. The caller's effective token is evaluated against that descriptor
   for `PORT_BIND`, through the ordinary AccessCheck pipeline ([AccessCheck Overview](</kernel/internals/kacs/access-check/accesscheck-overview.md#trm-3-8-1>))
   with PIP context, privilege-use marking and audit events — a port
   descriptor may carry a SACL, and its decisions surface through the
   same KMES stream as any other object's, with `object.kind`
   `socket`. <a id="cite-net.port.access-check"></a>
4. Deny → `-EACCES`. Grant → the bind proceeds, and the caller's token is
   recorded on the socket as its **binder**. <a id="cite-net.port.deny-eacces"></a>

An explicit `bind(2)` before an outbound `connect(2)` meets the same
rule; it is not special-cased.

**Rebinding.** Binding onto a port that is already bound — with
`SO_REUSEADDR` or `SO_REUSEPORT` — is still a `bind(2)` and still meets
the reservation. <a id="cite-net.port.rebind-meets-reservation"></a> The rule beyond that is that the new binder's user SID
must equal the existing binder's, or the caller must hold
`SeTcbPrivilege`: rebind is a property of the current binding, not of
policy, and a right on the reservation that let one principal rebind
onto another's port is a thing nothing legitimately needs. <a id="cite-net.port.rebind-same-sid-or-tcb"></a> The binder
recorded on each socket is what makes that comparison local; the
comparison itself is applied where the stack resolves bind conflicts,
and Linux already applies the same-owner half of it for `SO_REUSEPORT`
by comparing the sockets' projected UIDs.

<a id="trm-3-12-1-4"></a>

## Before the registry

The table comes from the registry through the same self-configuration
path LCS uses for its own limits ([The Bootstrap Problem](</kernel/internals/lcs/bootstrap/dependencies-and-boot-sequence.md#trm-5-10-1>)): read at the first source's
registration, then watched, so a change to the key is live without a
restart. <a id="cite-net.port.table-watched-live"></a> Until the first successful load — early boot, or a registry
that never becomes available — a **compiled-in fallback** answers:
owner and group SYSTEM, one entry granting SYSTEM `PORT_BIND`, nobody
else. <a id="cite-net.port.compiled-in-fallback"></a> It is stricter than the shipped seed on purpose: nothing but
system components should be claiming ports before the registry exists.

The fallback is **replaced, never merged**. The moment the key loads it
is the sole authority; if a later load is rejected the last good table
stays, not the fallback. <a id="cite-net.port.fallback-replaced-not-merged"></a> Effective policy therefore never depends on
boot timing.

<a id="trm-3-12-1-5"></a>

## What this retired

`SeBindPrivilegedPortPrivilege` (bit 63) was the KACS privilege
`CAP_NET_BIND_SERVICE` mapped to before this object existed. A
reservation's grant is an ACE, and an ACE names a SID, not a privilege;
keeping the privilege would have been a second authorisation path
around the descriptor. It is retired and its bit is not reused. <a id="cite-net.port.privilege-retired"></a> Low
ports are granted through the capability SID on the `1-1023`
reservation, which reaches a token by confinement — peinit for a
service, or positive confinement from the authority at logon for a
user.

<a id="trm-3-12-1-6"></a>

## Tracing <a id="cite-net.port.tracing"></a>

Every decision emits `kacs:kacs_socket_bind` with reason `port-bind`:
`desired` carries `PORT_BIND`, `max_imp` carries the port, and `ret` the
verdict. Table loads emit reason `port-table`. See Appendix 3.C for the audit
events an evaluated descriptor's SACL can produce.

---

# Socket Identity

_Peios Kernel / Internals / KACS / Network objects_

> The governing identity KACS stamps on every inet socket for network policy — which token, taken when, and how the engine reads it.

<a id="trm-3-12-2"></a>

Network policy speaks of programs, and a packet carries no program. What
carries one is the socket: KACS records on every `AF_INET` and
`AF_INET6` socket the **identity that governs its traffic**, and the
network policy engine (Chapter 6, [The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)) reads it at the first judgment
of each flow. <a id="cite-net.socket.stamp-on-inet-sockets"></a> AF_UNIX sockets carry the peer-identity machinery of
[Impersonation Levels](</kernel/internals/kacs/impersonation/levels-and-admission.md#trm-3-5-1>) instead and are not stamped.

<a id="trm-3-12-2-1"></a>

## The stamp

The stamp is the caller's **effective token** — the impersonation token
during impersonation, the primary otherwise — held by a counted
reference, together with the process facts of that moment: the process
GUID ([PSB Fields](</kernel/internals/kacs/process-security/psb-fields.md#trm-3-3-2>)), the thread-group id, and the task's `comm`. <a id="cite-net.socket.stamp-contents"></a> Choosing the
effective token means a service thread acting for a client attributes
the socket to the client, exactly as file creation and audit do under
impersonation; the service's own identity is then not on the socket for
that flow.

It is taken at every act that commits the socket to a role, and the
last one governs: <a id="cite-net.socket.last-act-governs"></a>

| Act | Where |
|---|---|
| creation | `socket_post_create`; a kernel socket (`sock_create_kern`) is stamped as the **kernel's**, with no token <a id="cite-net.socket.kernel-socket-stamp"></a> |
| `bind(2)` | after the port reservation permits it ([Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1>)) |
| `listen(2)` | `socket_listen` |
| `connect(2)` | `socket_connect` |
| `accept(2)` | `sk_clone_security`: the child inherits the listener's stamp, its own reference <a id="cite-net.socket.accept-inherits"></a> |
| `KACS_SO_RESTAMP` | any state: the caller's effective identity replaces the stamp |

Restamping is what makes a hand-off well defined. A listener opened by
one program and passed to another — socket activation, a descriptor
store, a broker — is governed by whichever program last committed it,
and a program that receives a socket it did not create can say so
explicitly with `KACS_SO_RESTAMP`, self-gated like every attestation of
one's own identity. <a id="cite-net.socket.restamp-self-gated"></a> Sockets that never pass through these hooks (a task
with no token in early boot) read as *unstamped*, which the engine
treats as the kernel's and confesses. <a id="cite-net.socket.unstamped-reads-kernel"></a>

<a id="trm-3-12-2-2"></a>

## Reading it

The engine reads the stamp with `pkm_kacs_socket_owner()`
(`<linux/peios_ntfe.h>`): a counted token reference the caller releases
with `pkm_kacs_socket_owner_put()`, and a copy of the kind, GUID, pid and
comm. <a id="cite-net.socket.owner-accessor"></a> The copy is what makes the facts outlive the process; the
reference is what makes them outlive the socket — a flow keeps its
identity for its life ([The identity facts](</kernel/internals/ntfe/the-identity-facts.md#trm-6-9>)) even after the socket that started it is
gone. The fields live under their own lock, taken with bottom halves
disabled, because both the accept path and the engine's read run in
softirq context.

<a id="trm-3-12-2-3"></a>

## Final release

Once the socket's last user is gone, KACS releases the token references
and security descriptor owned by the socket. This also releases any
peer, listener, binder and send-cache references; each field owns its
own reference even when several refer to the same token. Final cleanup
can run from an RCU callback and must not sleep or acquire the locks
used to coordinate live socket users. It has exclusive ownership at
this point. References already taken by a flow or another reader remain
valid until that reader releases them. <a id="cite-net.socket.final-release-rcu-safe"></a>

<a id="trm-3-12-2-4"></a>

## Tracing <a id="cite-net.socket.tracing"></a>

Every stamp emits `kacs:kacs_socket_token` with reason `owner`; the
`max_imp` field carries the kind (1 program, 2 kernel). See Appendix
3.C.

---

# Mount namespaces

_Peios Kernel / Internals / KACS / Mount namespaces_

> Find the Peios kernel articles about mount namespaces.

Use these articles to understand mount namespaces in the Peios kernel.

- [A Private Mount Table](</kernel/internals/kacs/mount-namespaces/a-private-mount-table.md>)

---

# A Private Mount Table

_Peios Kernel / Internals / KACS / Mount namespaces_

> A mount namespace is a KACS object — any process may create one without privilege, and what it may then do to its own mount table is decided by the namespace's security descriptor, not by a capability manufactured in a user namespace.

<a id="trm-3-13-1"></a>

A mount namespace is a private copy of the kernel's mount table: the
map from directory paths to the filesystems mounted there. Linux
answers "who may change this table" with `CAP_SYS_ADMIN` in the user
namespace that owns it, and lets an unprivileged process manufacture
that capability by creating a user namespace first — which is how
bubblewrap, and every unprivileged container tool built the same way,
gets a private root.

On Peios that route leads nowhere. The capability switchboard discards
the target user namespace and answers from the token's privileges
alone ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so being root in a user namespace confers nothing, and
`CAP_SYS_ADMIN` maps to `SeTcbPrivilege`. KACS answers the question the
way it answers every other: the mount namespace is an object with a
security descriptor, and changing it is an access check. <a id="cite-mntns.object-model"></a>

<a id="trm-3-13-1-1"></a>

## The object

Every mount namespace other than the initial one carries a security
descriptor, minted in `copy_mnt_ns()` from the creating task's effective
token and released when the namespace is. <a id="cite-mntns.descriptor-lifetime"></a> The initial namespace, and the
anonymous namespaces `open_tree(OPEN_TREE_CLONE)` and `fsmount` create
for detached trees, carry none. <a id="cite-mntns.initial-has-no-descriptor"></a>

The minted descriptor names its creator and nobody else: owner and
group come from the token, and the DACL is a single allow ACE granting
the creator's user SID `GENERIC_ALL`. <a id="cite-mntns.default-descriptor"></a> `SYSTEM` and
`BUILTIN\Administrators`, which the SysV IPC and socket defaults name,
are absent on purpose — the privilege rung of the mount gate admits them
before the descriptor is read, so an ACE would only pretend the
descriptor was what let them in.

The rights are those of `<pkm/mntns.h>`:

| Right | Grants |
|---|---|
| `KACS_MNTNS_MOUNT` | changing the table: a bind mount, an unmount, `pivot_root` |
| `KACS_MNTNS_ENTER` | joining the namespace with `setns` — defined so the descriptor's meaning is fixed; no code consults it yet, and `setns` into a mount namespace still needs `SeTcbPrivilege` |
| `READ_CONTROL`, `WRITE_DAC`, `WRITE_OWNER` | the standard rights, which `KACS_MNTNS_ALL_ACCESS` includes; nothing exposes a namespace's descriptor to `kacs_get_sd` or `kacs_set_sd` yet |

The generic mapping: `GENERIC_WRITE` is `KACS_MNTNS_MOUNT` and
`WRITE_DAC`; `GENERIC_EXECUTE` is `KACS_MNTNS_ENTER` and `READ_CONTROL`;
`GENERIC_READ` is `READ_CONTROL` alone, there being nothing to read from
a namespace beyond its descriptor; `GENERIC_ALL` is
`KACS_MNTNS_ALL_ACCESS`. <a id="cite-mntns.generic-mapping"></a>

<a id="trm-3-13-1-2"></a>

## Creating one

`unshare(CLONE_NEWNS)`, and `clone` with `CLONE_NEWNS`, need no
privilege when the mount namespace is the only namespace requested. <a id="cite-mntns.create-unprivileged"></a>
Every other namespace type — and any combination that includes one —
keeps the `CAP_SYS_ADMIN` gate in `kernel/nsproxy.c`, which the
switchboard answers with `SeTcbPrivilege`. <a id="cite-mntns.other-types-stay-gated"></a> A user namespace may still be
created alongside, as upstream allows; it changes nothing about what
follows.

A table created by a task that does not hold the mount privilege
receives its mounts as *slaves* of the parent table's, exactly as
upstream does for a copy owned by a different user namespace:
propagation runs parent to child only, so whatever the creator mounts
in its own table never appears in the one it copied. <a id="cite-mntns.unprivileged-copy-is-slave"></a> A table created
with the privilege is copied as upstream copies it, peers and all.

<a id="trm-3-13-1-3"></a>

## The mount gate

`may_mount()` in `fs/namespace.c` is the gate for `mount`, `umount2`,
`pivot_root`, `open_tree(OPEN_TREE_CLONE)`, `fsmount`, `move_mount` and
`mount_setattr`, and for `fsopen` and `fspick` in `fs/fsopen.c`.
`mount_capable()` in `fs/super.c` is the second
gate a new filesystem passes, when its superblock is brought into being.
Under KACS both take the operation as an argument, with the filesystem
type where one is being created, and ask `pkm_kacs_may_mount_op()` in
three rungs, against the caller's effective token and the descriptor of
the caller's current namespace: <a id="cite-mntns.gate-rungs"></a>

1. **Privilege.** A token holding `SeManageVolumePrivilege` or
   `SeTcbPrivilege`, enabled, is admitted to every operation in every
   namespace, and the privilege is marked used. This rung is decided
   first and alone: a token that holds the privilege never reaches the
   descriptor, and a token that does not is never asked the privilege
   question, so an unprivileged caller's routine bind mount records no
   privilege refusal. <a id="cite-mntns.gate-privilege-first"></a>
2. **No descriptor.** In a namespace with no descriptor — the initial
   one — nothing else admits anything. This is the whole of the rule that
   the root table keeps: without the privilege, no process changes it. <a id="cite-mntns.root-table-privilege-only"></a>
3. **Descriptor.** Otherwise, and only for an operation the descriptor
   can admit, AccessCheck for `KACS_MNTNS_MOUNT` runs against the
   namespace's descriptor under the caller's PIP context, exactly as it
   does for a socket or a SysV object. <a id="cite-mntns.gate-descriptor-check"></a>

The operations the descriptor can admit are the ones that put no
kernel filesystem parser of an untrusted image in reach of the caller: <a id="cite-mntns.admissible-operations"></a>

| `mount(2)` shape | Gate operation | Admissible by descriptor |
|---|---|---|
| `MS_BIND`, with or without `MS_REC` | bind | yes |
| `umount2` without `MNT_FORCE` | unmount | yes |
| `pivot_root` | pivot_root | yes |
| a new `tmpfs`, `proc` or `stratafs` (`do_new_mount`) | new filesystem | yes |
| any other filesystem type | new filesystem | no |
| `MS_REMOUNT`, including `MS_REMOUNT\|MS_BIND` | other | no |
| `MS_MOVE`; `MS_SHARED`, `MS_PRIVATE`, `MS_SLAVE`, `MS_UNBINDABLE` | other | no |
| `open_tree(OPEN_TREE_CLONE)`, `fsopen`, `fspick`, `fsmount`, `move_mount`, `mount_setattr` | other | no |

The filesystem types a descriptor can admit are an allowlist KACS keeps,
and it holds exactly `tmpfs`, `proc` and `stratafs`: all three read
nothing but the caller's own mount options. tmpfs has no backing image,
proc is a view of the kernel's own state, and stratafs is a view of
directories the caller can already traverse, every access through it
decided on the providing object ([Access Check Delegation](</kernel/internals/stratafs/security/access-check-delegation.md#trm-4-6-1>)). A type that parses an image —
ext4, squashfs, iso9660, ntfs3 — is refused before the type is even
looked up. The list is an attack-surface list and not a policy knob:
who may change a table is decided by the table's descriptor alone, and
the same descriptor that admits tmpfs refuses ext4. <a id="cite-mntns.fs-type-allowlist"></a>

A stratafs stack admitted this way is read-only or absent-tolerant.
stratafs's own admission ([Mount Admission](</kernel/internals/stratafs/strata-and-mounting/mount-admission.md#trm-4-2-3>)) refuses a `create` stratum to any
caller outside the initial user namespace or without `CAP_SYS_ADMIN`,
which is `SeTcbPrivilege`, and that test runs after the gate, so an
unprivileged caller that asks for one gets `EPERM` from stratafs
whatever its table's descriptor grants. Copy-up carries no add-entry
right of its own, which is why a writable stack is authority in itself
and stays with the TCB; a private table's writable paths are tmpfs, or
bind mounts of directories the caller owns. <a id="cite-mntns.stratafs-read-only-only"></a> Admitting the type does put
stratafs's option parser and stack validation in reach of unprivileged
input for the first time; both fail closed with `EINVAL` on a relative
stratum, a duplicate, `create` combined with `ro`, an empty stack or
more than sixteen strata, and with `ENOENT` on a missing stratum not
marked `am`.

Everything in the *no* rows needs the privilege whatever the descriptor
grants, and `MNT_FORCE` additionally keeps its own `CAP_SYS_ADMIN` test
on the superblock's user namespace. A mount that the gate admits still
goes through every check upstream applies afterwards: the bind source is
looked up through the caller's own table, an unmount needs a mount
point that belongs to it, and `pivot_root` needs the propagation
conditions it always needed, which the slave copy of an unprivileged
table satisfies.

<a id="trm-3-13-1-3-1"></a>

### An unprivileged tmpfs is stamped for its creator

A fresh tmpfs is deny-missing under FACS ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)): nothing on it carries
a descriptor, so nothing on it is reachable until someone sets the
superblock's mount policy, which `kacs_set_mount_policy` reserves to the
mount privilege. That is right for the system's own overlays, which are
seeded deliberately, and it would leave a tmpfs admitted by a namespace
descriptor permanently empty. So at `sb_kern_mount`, a tmpfs brought
into being by a token that holds no mount privilege is stamped
synthesize-ephemeral with a template descriptor the kernel mints itself:
owner and group from the mounter's token, one allow ACE granting the
mounter's user SID `GENERIC_ALL` — the same shape as the namespace
descriptor. <a id="cite-mntns.unprivileged-tmpfs-stamped"></a> The policy generation moves to 1, which retires the
deny-missing default the root inode's creation cached during
`fill_super`. The mounter cannot choose the template, and a superblock
whose policy `kacs_set_mount_policy` has already set is left alone. A
privileged mounter's tmpfs is untouched: it keeps the magic default and
the mounter seeds it, as before. <a id="cite-mntns.privileged-tmpfs-untouched"></a> proc is unmanaged and needs no
stamp; a second proc mount in the same pid namespace shows the same
processes under the same per-process checks.

So a process whose whole world is a directory of its choosing is:

```
unshare(CLONE_NEWNS);
mount(dir, dir, NULL, MS_BIND, NULL);
chdir(dir);
pivot_root(".", ".");
umount2(".", MNT_DETACH);
chdir("/");
```

with no user namespace and no privilege. <a id="cite-mntns.private-root-sequence"></a> The bind makes the directory a
mount point, which `pivot_root` requires; pivoting onto the same path
stacks the old root on the new one, and detaching `.` drops it.

<a id="trm-3-13-1-4"></a>

## What the object does not change

The token never changes at `exec` ([setuid Behaviour](</kernel/internals/kacs/linux-credentials/setuid-behaviour.md#trm-3-10-3>)), so a program run inside a
private table has exactly the authority of the process that built it,
and a fake `/etc` fools nobody but its author. Every access to a file
reached through a bind mount is decided on the real object's
descriptor, so a bind mount shows a name and denies at open. The
kernel's own helpers — `modprobe` and its kin — are executed in the
initial namespace and refused unless TCB-signed ([Process Integrity Protection](</kernel/internals/kacs/executable-trust/process-integrity-protection.md#trm-3-7>)). A signed
binary's PIP tier is derived from the binary and not from the table it
was found in, and library verification, where a process enables it,
compares signatures at `mmap` rather than paths. <a id="cite-mntns.no-new-authority"></a>

<a id="trm-3-13-1-5"></a>

## Tracing

The `kacs:kacs_mntns` event records a descriptor minted at namespace
creation, each rung of the gate, and a tmpfs stamped for its creator,
with the operation code, the right asked of the descriptor where a rung
reached it, a reason from `<pkm/trace.h>` — `sd-alloc`, `sd-alloc-fail`,
`gate-privilege`, `gate-no-sd`, `gate-op-not-admitted`,
`gate-sd-decision`, `gate-pip-context`, `gate-fs-not-admitted`,
`sb-stamp`, `sb-stamp-fail` — and the verdict. <a id="cite-mntns.trace-event"></a>

---

# Auditing

_Peios Kernel / Internals / KACS / Auditing_

> Find the Peios kernel articles about auditing.

Use these articles to understand auditing in the Peios kernel.

- [Event families and delivery](</kernel/internals/kacs/auditing/event-families-and-delivery.md>)

---

# Event families and delivery

_Peios Kernel / Internals / KACS / Auditing_

> The audit records KACS emits through KMES — the event families, their shared payload records, and how they are delivered.

<a id="trm-3-c"></a>

KACS emits its audit records through KMES with origin class 2 ([Event Model](</kernel/internals/kmes/event-model.md#trm-2-2>)). <a id="cite-audit-events.origin-class-two"></a>
Each event's payload is a msgpack map whose field paths follow [PGSS field
conventions](https://learn.peios.org/specifications/pgss/events/fields/): `access.requested` is the key `requested` inside the map under
`access`, never a key containing a dot, and a value the emitter does
not have is absent rather than nil. The shared `subject` group — the
effective token's `subject.token.*`, the PIP state in `subject.pip.*`,
and the calling process as `emitter.process.{pid,name,executable}` — is
attached at emission time from the resolved call context rather than by
the evaluation pipeline ([Auditing in AccessCheck](</kernel/internals/kacs/access-check/auditing-in-accesscheck.md#trm-3-8-9>)). A process with no executable, such as a
kernel thread, has `executable` left out; the record is still written.

This appendix describes where KACS emits each event. The `.evman` fragments
in `peios/packages/data/evman/` define the payload schemas and field meanings.
Use `evman <event-type>` for an installed event definition, or `evman <field>`
for a field's type, meaning, and carrying events.

<a id="trm-3-c-1"></a>

## Event families

| Event type | Emitted by |
|---|---|
| `kacs.audit.access.checked` | The SACL walk, and token audit-policy forcing. <a id="cite-audit-events.access-audit-record"></a> |
| `kacs.audit.handle.used` | Enforcement points, per operation, against a handle's continuous audit mask. <a id="cite-audit-events.continuous-audit-record"></a> |
| `kacs.audit.privilege.used` | Privilege-use auditing, for the five AccessCheck-influencing privileges in an access check, and at a Linux capability or volume gate ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)). <a id="cite-audit-events.privilege-use-record"></a> |
| `kacs.audit.descriptor.changed` | A change to the descriptor of a file, token, process or System V IPC object (below). |
| `kacs.impersonation.started`, `kacs.impersonation.reverted` | An impersonation attempt, and the end of an impersonation ([Impersonation Lifecycle](</kernel/internals/kacs/impersonation/state-transitions.md#trm-3-5-3>)). |
| `kacs.caap.sacl.skipped`, `kacs.caap.staging.diverged` | A CAAP rule SACL that could not be parsed or evaluated; a staged result that differs from the effective one. <a id="cite-audit-events.caap-policy-diagnostic-record"></a> |
| `kacs.session.destroyed` | LogonSession teardown ([LogonSessions and Revocation](</kernel/internals/kacs/tokens/logonsessions-and-revocation.md#trm-3-2-7>)). <a id="cite-audit-events.logon-session-destroyed-record"></a> |
| `kacs.descriptor.rejected` | A descriptor xattr that exists but fails structural validation ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). <a id="cite-audit-events.corrupt-sd-record"></a> |
| `kacs.caap.policy.changed` | `kacs_set_caap` installing, replacing or removing a central access policy ([Central Access and Auditing Policy](</kernel/internals/kacs/access-check/central-access-and-auditing-policy.md#trm-3-8-8>)). |
| `kacs.mount.policy.changed` | `kacs_set_mount_policy` ([File Descriptor Storage](</kernel/internals/kacs/file-security/descriptor-storage-and-caching.md#trm-3-9-5>)). |
| `kacs.config.value.rejected` | A port reservation table refused whole ([Port Reservations](</kernel/internals/kacs/network-objects/port-reservations.md#trm-3-12-1>)). |
| `stratafs.file.copied-up` | StrataFS copy-up lifecycle and failure ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)). <a id="cite-audit-events.stratafs-copy-up-record"></a> |
| `stratafs.mutation.refused` | A StrataFS arrangement refusal. <a id="cite-audit-events.stratafs-mutation-refused-record"></a> |

`kacs.descriptor.rejected` carries `object.kind` `file` and
`outcome.reason` `corrupt`. It does not name the file by path: the
descriptor is read through internal path anchors whose mount cannot
always be resolved to an absolute path, so `object.file.path` is absent.
It names the file by `object.file.inode` and `object.file.device` (the
filesystem's `st_dev`) instead, carries the stored attribute's length as
`object.sd.length`, and carries the `subject` whose access made KACS read
the descriptor. <a id="cite-audit-events.corrupt-sd-identifies-file"></a>

KACS also writes `kacs.signature.crypto.failed` once at boot when the
signature transform is unavailable ([Binary Signature Verification](</kernel/internals/kacs/executable-trust/signature-verification.md#trm-3-6>)), carrying
`signature.crypto-stage` `boot-probe` and the negative `outcome.errno`.

The `privilege.name` field of a `kacs.audit.privilege.used` event carries a canonical
name. A record of an access check (`operation.name` `access-check`)
names one of five — `SeSecurityPrivilege`, `SeTakeOwnershipPrivilege`,
`SeBackupPrivilege`, `SeRestorePrivilege` and `SeRelabelPrivilege` —
the only privileges an access check consults. <a id="cite-audit-events.privilege-five-canonical-names"></a>
A record of a capability or volume gate (`linux-cap`, `volume-mount`)
names whichever privilege the gate spent ([The Privilege Model](</kernel/internals/kacs/privileges/the-privilege-model.md#trm-3-4-1>)). The encoder names
every defined privilege, and a bit with no name fails it closed rather
than emitting an unnamed privilege; a token holding only privileges an
access check does not consult produces no access-check record at all. <a id="cite-audit-events.privilege-encoder-fails-closed"></a>

`kacs.audit.handle.used` carries an `operation.name` naming the enforcement
point: `file.access`, `file.mmap`, `file.mprotect`, `file.permission`,
`file.write`, `file.ioctl`, `file.lock`, `file.fcntl`, `file.truncate`
and `file.fallocate`. <a id="cite-audit-events.continuous-operation-names"></a> It never carries a caller-supplied audit context: its
`object.kind` is always `file`, with the handle's absolute path in
`object.file.path` (absent only if the path cannot be resolved), and it
never sets `fields.attestation.userspace`. <a id="cite-audit-events.continuous-object-context-nil"></a>

<a id="trm-3-c-2"></a>

## Descriptor changes

`kacs.audit.descriptor.changed` records a change to the descriptor of a
file, a token, a process or a System V IPC object by a caller authorised
to make it, whether or not the change then applied. A change that
includes the SACL is always recorded, whatever either descriptor says —
so removing a file's SACL, which leaves nothing to audit the removal
itself, is still recorded. <a id="cite-audit-events.descriptor-changed-sacl-always"></a>
Any other change is recorded when the rights it needed overlap the alarm
mask on the handle it was made through. Only a file handle opened
through FACS carries such a mask, so a change made through a path, or to
a token, a process or an IPC object, is recorded only when it includes
the SACL. <a id="cite-audit-events.descriptor-changed-dacl-by-handle-mask"></a>

The record names the object by `object.kind` and its identity —
`object.file.path` where it can be resolved, `object.token.id` and
`.guid`, `object.process.guid`, or `object.ipc.type` and `.id` — and
describes the change in `object.sd`: the parts set as `components`, and
the length, SHA-256 digest and owner of the descriptor written
(`length`, `digest`, `owner`) and of the one replaced (`length-previous`,
`digest-previous`, `owner-previous`; absent where there was no stored
descriptor). `access.requested` is the rights the change needed, with the
handle's `access.granted`, `access.audit-mask` and the overlap as
`access.matched` — zero when only the SACL made the record exist — for a
change made through one. <a id="cite-audit-events.descriptor-changed-object-kinds"></a>
Registry keys have the same record as `lcs.audit.key.descriptor.changed`.

<a id="trm-3-c-3"></a>

## Delivery

Audit and privilege-use events are delivered **before** any result is
written back to the caller, and a delivery failure fails the syscall
with `EIO` or `EOPNOTSUPP`. <a id="cite-audit-events.delivered-before-result"></a> An audit event cannot be suppressed by
handing the call a bad output pointer.

Three emissions are best-effort by contrast, and drop silently rather
than failing the operation that caused them:

- `kacs.session.destroyed` where the authentication package name is
  not valid UTF-8. <a id="cite-audit-events.best-effort-logon-session-utf8"></a>
- The two StrataFS events on an over-long operation string or path. <a id="cite-audit-events.best-effort-stratafs"></a>
- Any self-emitted payload that would exceed its encoding buffer. <a id="cite-audit-events.best-effort-oversize-payload"></a>

A StrataFS record is not lost for want of memory. When the allocation
for the full record fails, a reduced record is written from a fixed
buffer instead: the same type with the stratum indices, the operation
and the outcome, and without the paths — `object.file.path-relative` and
each `stratum.path` — whose absence marks it as reduced. <a id="cite-audit-events.stratafs-reduced-record"></a>

The transport itself — ring buffer delivery, buffering and drop
accounting — is KMES's ([Ring Buffers](</kernel/internals/kmes/ring-buffers.md#trm-2-5>), [Failure Modes](</kernel/internals/kmes/failure-modes.md#trm-2-7>)).

---

# Integration

_Peios Kernel / Internals / KACS / Integration_

> Find the Peios kernel articles about integration.

Use these articles to understand integration in the Peios kernel.

- [LSM hooks and object state](</kernel/internals/kacs/integration/lsm-hooks-and-object-state.md>)

---

# LSM hooks and object state

_Peios Kernel / Internals / KACS / Integration_

> The KACS security blobs, registered Linux Security Module hooks, and direct entry points at patched file-metadata call sites.

<a id="trm-3-e"></a>

KACS registers as the `pkm` Linux Security Module. This appendix is an
implementation inventory for kernel developers: it describes the storage
and call sites behind the contracts in this chapter. These C structures
and callbacks are kernel-private, not userspace layouts or extension APIs.
The exported ABI remains in [KACS ABI Reference](</kernel/userspace/native/kacs/generated-syscall-index.md#trm-3-a>).

The inventory comes from `security/pkm/kacs/lsm.c` (`pkm_blob_sizes` and
`pkm_hooks[]`), the structures in `security/pkm/kacs/lsm_internal.h`, and the callback
implementations listed below. When changing those declarations, update
this inventory with the same change. The hook matrix preserves registration
order; each row names an actual `LSM_HOOK_INIT` entry.

<a id="trm-3-e-1"></a>

## Security-blob inventory

`pkm_blob_sizes` requests eight sized blob families. Each `lbs_*` entry
is initialized with `sizeof` the corresponding structure; Linux's LSM
infrastructure assigns its offset in the object's security storage. Byte
sizes and offsets depend on the build and are not fixed by this manual.

| LSM size entry | KACS structure | State carried |
|---|---|---|
| `lbs_cred` | `pkm_kacs_cred_security` | Token reference, shared `process_state`, projected UID/GID, and the pending descriptor used while overlayfs creates or copies up an inode. |
| `lbs_task` | `pkm_kacs_task_security` | Shared `process_state`, usermode-helper and impersonation state, the applied primary-installation epoch and thread-enrollment callback, deferred privilege-audit work, native-open/create requests, write/metadata decisions, narrowly scoped StrataFS creation, supersede and cleanup context, the deferred deletion in progress at a delete-pending file's last close, the failure status of the last native open, a handle rename in progress, and the lease keys and notes that lease breaks consult. |
| `lbs_sock` | `pkm_kacs_socket_security` | Socket descriptor, conveyed peer/listener identities, token-conveyance cache and impersonation limits, binder identity/reuse decision, and the committed socket-owner identity used by network policy. |
| `lbs_ipc` | `pkm_kacs_ipc_security` | Refcounted descriptor and lock for a System V message queue, shared-memory segment or semaphore array. |
| `lbs_file` | `pkm_kacs_file_security` | Cached `granted_access` and `continuous_audit_mask`, copy-up context and phase generation, the open's NT share registration (`nt_inode`, `nt_classes`, `nt_share`, `nt_intent`), its lease manager and key, its ancestor pin set, `managed`, `delete_on_close`, and the referenced token that will mark the file delete-pending. |
| `lbs_backing_file` | `pkm_kacs_backing_file_security` | Cached `granted_access` and `continuous_audit_mask`, the outer open's share participation and lease key, plus `managed` and `inherited`, for the explicit outer-to-backing-file snapshot transfer. |
| `lbs_inode` | `pkm_kacs_inode_security` | Lock and RCU descriptor-cache pointer, the lazily allocated NT state (`nt`: share counters, delete-pending mark, byte-range locks and leases), the cached read-only special attribute, the ancestor-pin and signed-exec pin counters, and the deferred descriptor-persistence state. Test-only members exist under `CONFIG_SECURITY_PKM_KUNIT`. |
| `lbs_superblock` | `pkm_kacs_superblock_security` | Mount-policy lock, template descriptor bytes/length, policy generation and mount policy. |

The additional `lbs_xattr_count = 1` reserves one xattr-initialization
slot. It is not a ninth object blob or a byte-size declaration.

The file blob uses separate `u8 managed` and `u8 delete_on_close`
fields. The NT state lives in `nt_file.c`, `nt_lock.c` and `nt_lease.c`,
the handle syscalls in `nt_handle.c`, pinning in `nt_pin.c`, and the
special attributes in `sattr.c`. There is no `flags` member or `KACS_FILE_FACS_MANAGED` constant.
The backing-file blob is distinct from the ordinary file blob: its
`inherited` marker records explicit adoption of the outer description's
cached grants and continuous-audit mask ([The StrataFS Copy-Up Context](</kernel/internals/stratafs/security/kacs-admission-and-object-phases.md#trm-3-9-7>)).

The task blob reaches process-wide state through its `process_state`
pointer. The refcounted `pkm_kacs_process_state` contains `process_guid`,
`pip_type`, `pip_trust`, one `u32 mitigation_bits`, the KMES rate bucket,
the `process_sd` reference and process-scoped privilege-audit bookkeeping.
It also holds `primary_lock`, `desired_primary_token` and `primary_epoch`,
which order primary-token installation across the process's threads
([Token Lifecycle](</kernel/internals/kacs/tokens/token-lifecycle.md#trm-3-2-3>)).
PIP identity and the process descriptor are not inline task-blob fields;
the process mitigations are not nine independent booleans. This shared
state is separate from the effective token used during impersonation.

The credential blob's `pending_create_sd` has the lifetime of an override
credential. Overlayfs uses it to stamp the descriptor computed for the
original object or caller/parent onto the actual created inode; credential
preparation does not inherit it into a derived credential. The task blob's
internal SD read/write depth and operation contexts similarly identify
specific kernel work; they are not caller-settable authorization flags.

<a id="trm-3-e-2"></a>

## Registered hook matrix

The current `pkm_hooks[]` table contains 100 registrations. Paths in the
last column are relative to the `pkm` source repository. A callback's
presence here identifies where KACS is called; the operation's access,
privilege and lifetime rules remain specified in the relevant chapter.

| Linux LSM hook | KACS callback | Implementation |
|---|---|---|
| `cred_prepare` | `pkm_kacs_cred_prepare` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_transfer` | `pkm_kacs_cred_transfer` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_alloc_blank` | `pkm_kacs_cred_alloc_blank` | `security/pkm/kacs/cred_lifecycle.c` |
| `cred_free` | `pkm_kacs_cred_free` | `security/pkm/kacs/cred_lifecycle.c` |
| `sb_alloc_security` | `pkm_kacs_sb_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `sb_free_security` | `pkm_kacs_sb_free_security` | `security/pkm/kacs/object_lifecycle.c` |
| `sb_kern_mount` | `pkm_kacs_sb_kern_mount` | `security/pkm/kacs/mnt_namespace.c` |
| `inode_alloc_security` | `pkm_kacs_inode_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `inode_free_security_rcu` | `pkm_kacs_inode_free_security_rcu` | `security/pkm/kacs/object_lifecycle.c` |
| `inode_getattr` | `pkm_kacs_inode_getattr` | `security/pkm/kacs/file_metadata.c` |
| `path_notify` | `pkm_kacs_path_notify` | `security/pkm/kacs/namespace.c` |
| `inode_setattr` | `pkm_kacs_inode_setattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_file_getattr` | `pkm_kacs_inode_file_getattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_file_setattr` | `pkm_kacs_inode_file_setattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_xattr_skipcap` | `pkm_kacs_inode_xattr_skipcap` | `security/pkm/kacs/file_metadata.c` |
| `inode_getxattr` | `pkm_kacs_inode_getxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_setxattr` | `pkm_kacs_inode_setxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_post_setxattr` | `pkm_kacs_inode_post_setxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_removexattr` | `pkm_kacs_inode_removexattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_listxattr` | `pkm_kacs_inode_listxattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_copy_up` | `pkm_kacs_inode_copy_up` | `security/pkm/kacs/file_metadata.c` |
| `inode_copy_up_xattr` | `pkm_kacs_inode_copy_up_xattr` | `security/pkm/kacs/file_metadata.c` |
| `inode_follow_link` | `pkm_kacs_inode_follow_link` | `security/pkm/kacs/file_metadata.c` |
| `inode_set_acl` | `pkm_kacs_inode_set_acl` | `security/pkm/kacs/file_metadata.c` |
| `inode_remove_acl` | `pkm_kacs_inode_remove_acl` | `security/pkm/kacs/file_metadata.c` |
| `inode_getsecurity` | `pkm_kacs_inode_getsecurity` | `security/pkm/kacs/file_metadata.c` |
| `inode_permission` | `pkm_kacs_inode_permission` | `security/pkm/kacs/namespace.c` |
| `inode_create` | `pkm_kacs_inode_create` | `security/pkm/kacs/namespace.c` |
| `inode_link` | `pkm_kacs_inode_link` | `security/pkm/kacs/namespace.c` |
| `inode_unlink` | `pkm_kacs_inode_unlink` | `security/pkm/kacs/namespace.c` |
| `inode_symlink` | `pkm_kacs_inode_symlink` | `security/pkm/kacs/namespace.c` |
| `inode_mkdir` | `pkm_kacs_inode_mkdir` | `security/pkm/kacs/namespace.c` |
| `inode_rmdir` | `pkm_kacs_inode_rmdir` | `security/pkm/kacs/namespace.c` |
| `inode_mknod` | `pkm_kacs_inode_mknod` | `security/pkm/kacs/namespace.c` |
| `inode_rename` | `pkm_kacs_inode_rename` | `security/pkm/kacs/namespace.c` |
| `inode_readlink` | `pkm_kacs_inode_readlink` | `security/pkm/kacs/namespace.c` |
| `inode_init_security` | `pkm_kacs_inode_init_security` | `security/pkm/kacs/namespace.c` |
| `inode_post_create_tmpfile` | `pkm_kacs_copy_up_post_create_tmpfile` | `security/pkm/kacs/copy_up.c` |
| `dentry_create_files_as` | `pkm_kacs_dentry_create_files_as` | `security/pkm/kacs/namespace.c` |
| `file_alloc_security` | `pkm_kacs_file_alloc_security` | `security/pkm/kacs/object_lifecycle.c` |
| `backing_file_alloc` | `pkm_kacs_backing_file_alloc` | `security/pkm/kacs/object_lifecycle.c` |
| `file_release` | `pkm_kacs_file_release` | `security/pkm/kacs/object_lifecycle.c` |
| `file_free_security` | `pkm_kacs_file_free_security` | `security/pkm/kacs/object_lifecycle.c` |
| `file_open` | `pkm_kacs_file_open` | `security/pkm/kacs/file_access.c` |
| `file_receive` | `pkm_kacs_file_receive` | `security/pkm/kacs/object_lifecycle.c` |
| `file_permission` | `pkm_kacs_file_permission` | `security/pkm/kacs/file_access.c` |
| `file_ioctl` | `pkm_kacs_file_ioctl` | `security/pkm/kacs/file_access.c` |
| `file_ioctl_compat` | `pkm_kacs_file_ioctl_compat` | `security/pkm/kacs/file_access.c` |
| `file_lock` | `pkm_kacs_file_lock` | `security/pkm/kacs/file_access.c` |
| `file_fcntl` | `pkm_kacs_file_fcntl` | `security/pkm/kacs/file_access.c` |
| `file_truncate` | `pkm_kacs_file_truncate` | `security/pkm/kacs/file_access.c` |
| `kernel_read_file` | `pkm_kacs_kernel_read_file` | `security/pkm/kacs/firmware.c` |
| `kernel_post_read_file` | `pkm_kacs_kernel_post_read_file` | `security/pkm/kacs/firmware.c` |
| `task_alloc` | `pkm_kacs_task_alloc` | `security/pkm/kacs/task_lifecycle.c` |
| `task_free` | `pkm_kacs_task_free` | `security/pkm/kacs/task_lifecycle.c` |
| `sk_alloc_security` | `pkm_kacs_sk_alloc_security` | `security/pkm/kacs/socket.c` |
| `sk_free_security` | `pkm_kacs_sk_free_security` | `security/pkm/kacs/socket.c` |
| `sk_clone_security` | `pkm_kacs_sk_clone_security` | `security/pkm/kacs/socket.c` |
| `socket_post_create` | `pkm_kacs_socket_post_create` | `security/pkm/kacs/socket.c` |
| `socket_bind` | `pkm_kacs_socket_bind` | `security/pkm/kacs/socket.c` |
| `socket_connect` | `pkm_kacs_socket_connect` | `security/pkm/kacs/socket.c` |
| `unix_stream_connect` | `pkm_kacs_unix_stream_connect` | `security/pkm/kacs/socket.c` |
| `unix_may_send` | `pkm_kacs_unix_may_send` | `security/pkm/kacs/socket.c` |
| `socket_listen` | `pkm_kacs_socket_listen` | `security/pkm/kacs/socket.c` |
| `ipc_permission` | `pkm_kacs_ipc_permission` | `security/pkm/kacs/ipc.c` |
| `msg_queue_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `msg_queue_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `msg_queue_msgctl` | `pkm_kacs_msg_queue_msgctl` | `security/pkm/kacs/ipc.c` |
| `shm_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `shm_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `shm_shmctl` | `pkm_kacs_shm_shmctl` | `security/pkm/kacs/ipc.c` |
| `sem_alloc_security` | `pkm_kacs_ipc_alloc_security` | `security/pkm/kacs/ipc.c` |
| `sem_free_security` | `pkm_kacs_ipc_free_security` | `security/pkm/kacs/ipc.c` |
| `sem_semctl` | `pkm_kacs_sem_semctl` | `security/pkm/kacs/ipc.c` |
| `task_kill` | `pkm_kacs_task_kill` | `security/pkm/kacs/process_access.c` |
| `ptrace_access_check` | `pkm_kacs_ptrace_access_check` | `security/pkm/kacs/process_access.c` |
| `ptrace_traceme` | `pkm_kacs_ptrace_traceme` | `security/pkm/kacs/process_access.c` |
| `task_setnice` | `pkm_kacs_task_setnice` | `security/pkm/kacs/process_access.c` |
| `task_setscheduler` | `pkm_kacs_task_setscheduler` | `security/pkm/kacs/process_access.c` |
| `task_setioprio` | `pkm_kacs_task_setioprio` | `security/pkm/kacs/process_access.c` |
| `task_setpgid` | `pkm_kacs_task_setpgid` | `security/pkm/kacs/process_access.c` |
| `task_getpgid` | `pkm_kacs_task_getpgid` | `security/pkm/kacs/process_access.c` |
| `task_getsid` | `pkm_kacs_task_getsid` | `security/pkm/kacs/process_access.c` |
| `task_getscheduler` | `pkm_kacs_task_getscheduler` | `security/pkm/kacs/process_access.c` |
| `task_getioprio` | `pkm_kacs_task_getioprio` | `security/pkm/kacs/process_access.c` |
| `task_movememory` | `pkm_kacs_task_movememory` | `security/pkm/kacs/process_access.c` |
| `task_fix_setuid` | `pkm_kacs_task_fix_setuid` | `security/pkm/kacs/cred_projection.c` |
| `task_fix_setgid` | `pkm_kacs_task_fix_setgid` | `security/pkm/kacs/cred_projection.c` |
| `task_fix_setgroups` | `pkm_kacs_task_fix_setgroups` | `security/pkm/kacs/cred_projection.c` |
| `task_prlimit` | `pkm_kacs_task_prlimit` | `security/pkm/kacs/process_access.c` |
| `capable` | `pkm_kacs_capable` | `security/pkm/kacs/capability.c` |
| `capset` | `pkm_kacs_capset` | `security/pkm/kacs/capability.c` |
| `task_prctl` | `pkm_kacs_task_prctl` | `security/pkm/kacs/psb.c` |
| `mmap_file` | `pkm_kacs_mmap_file` | `security/pkm/kacs/psb.c` |
| `mmap_backing_file` | `pkm_kacs_mmap_backing_file` | `security/pkm/kacs/object_lifecycle.c` |
| `file_mprotect` | `pkm_kacs_file_mprotect` | `security/pkm/kacs/psb.c` |
| `bprm_check_security` | `pkm_kacs_bprm_check_security` | `security/pkm/kacs/exec.c` |
| `bprm_creds_from_file` | `pkm_kacs_bprm_creds_from_file` | `security/pkm/kacs/exec.c` |
| `bprm_committing_creds` | `pkm_kacs_bprm_committing_creds` | `security/pkm/kacs/exec.c` |
| `bprm_committed_creds` | `pkm_kacs_bprm_committed_creds` | `security/pkm/kacs/exec.c` |

<a id="trm-3-e-3"></a>

## Direct file-metadata entry points

An LSM hook receives the arguments supplied by the Linux hook API. Some
file-descriptor operations also need the particular open file's cached
FACS grant. PKM's patch series therefore calls KACS directly at the
file-descriptor call site, before the later inode-level work. These
functions are declared and called directly under `CONFIG_SECURITY_PKM`;
they are not additional entries in `pkm_hooks[]` and are not dispatched
through another LSM's hook table.

| File-descriptor operation | Direct KACS entry point | Kernel call site |
|---|---|---|
| Change mode | `pkm_kacs_file_chmod` | `fs/open.c` |
| Change owner/group | `pkm_kacs_file_chown` | `fs/open.c` |
| Change timestamps through a file descriptor | `pkm_kacs_file_utimens` | `fs/utimes.c` |
| Read file attributes through a file descriptor | `pkm_kacs_file_getattr` | `fs/stat.c` |
| Read an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_get` | `fs/xattr.c` |
| Set an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_set` | `fs/xattr.c` |
| Remove an xattr through a file descriptor | `pkm_kacs_file_sd_xattr_remove` | `fs/xattr.c` |

All seven implementations are in `security/pkm/kacs/file_metadata.c`.

The NT handle semantics add direct entry points at other call sites:

| Operation | Direct KACS entry point | Kernel call site |
|---|---|---|
| An open that fails after the open hook | `pkm_kacs_file_open_failed` | `fs/open.c` |
| An `O_PATH` open, refused while delete-pending | `pkm_kacs_file_open_path` | `fs/open.c` |
| A control handle, opened with no data mode | `dentry_open_control` (VFS helper) | `fs/open.c` |
| A read or write, checked against byte-range locks | `pkm_kacs_nt_lock_check_io` | `fs/read_write.c` |
| A content-changing `fallocate` | `pkm_kacs_nt_lock_check_fallocate` | `fs/open.c` |
| Writing or removing the special attributes | `pkm_kacs_sattr_vfs_set`, `pkm_kacs_sattr_vfs_remove` | `fs/xattr.c` |
| Looking up a rename destination | `pkm_filename_parentat` (VFS helper) | `fs/namei.c` | The xattr
functions enforce the file's metadata grant as well as the separate
rules for protected SD attributes; their names do not make raw SD-xattr
access a supported security-descriptor API.

The names `security_file_setattr`, `security_file_getattr`,
`security_file_getxattr` and `security_file_setxattr` do not name hooks
provided by this kernel. In particular, do not confuse them with the
real `inode_file_getattr` and `inode_file_setattr` registrations in the
matrix: those receive a dentry and `struct file_kattr`, not the open file
whose cached grant the direct entry points consult. The metadata decision
record connects the file-level check to the later inode-level operation.
This table covers those file-metadata entry points, not every direct
KACS call in the kernel.

<a id="trm-3-e-4"></a>

## Reserved access-mask bits

`RESERVED_ACCESS_MASK_BITS` in
`security/pkm/kacs/kacs_core/access_mask.rs` is `0x0ce0_0000` (bits 21, 22, 23,
26 and 27, counting from zero). It remains a private evaluator constant,
not a new UAPI definition. [The Algorithm](</kernel/internals/kacs/access-check/the-algorithm.md#trm-3-8-10>) already specifies the public behavior:
reserved bits in a desired mask or any ACE mask reject the check, rather
than being ignored. This inventory records the implementation value
without adding another exported spelling.

---

# Crypto API

_Peios Kernel / Internals / Crypto_

> This documentation outlines the Linux kernel crypto API with its concepts, details about developing cipher implementations, employment of the API for cryptographic use cases, as well as programming examples.

<a id="rst-crypto-api"></a>

**Author:** Stephan Mueller

**Author:** Marek Vasut

This documentation outlines the Linux kernel crypto API with its concepts, details about developing cipher implementations, employment of the API for cryptographic use cases, as well as programming examples.

**Table of contents**

- [Kernel Crypto API Interface Specification](</kernel/internals/crypto/intro.md>)
- [Scatterlist Cryptographic API](</kernel/internals/crypto/api-intro.md>)
- [Kernel Crypto API Architecture](</kernel/internals/crypto/architecture.md>)
- [Asynchronous Transfers/Transforms API](</kernel/internals/crypto/async-tx-api.md>)
- [Asymmetric / Public-key Cryptography Key Type](</kernel/internals/crypto/asymmetric-keys.md>)
- [Developing Cipher Algorithms](</kernel/internals/crypto/devel-algos.md>)
- [User Space Interface](</kernel/internals/crypto/userspace-if.md>)
- [Crypto Engine](</kernel/internals/crypto/crypto-engine.md>)
- [Programming Interface](</kernel/internals/crypto/api.md>)
- [Code Examples](</kernel/internals/crypto/api-samples.md>)
- [Fast &amp; Portable DES encryption &amp; decryption](</kernel/internals/crypto/descore-readme.md>)
- [Hardware Device Driver Specific Documentation](</kernel/internals/crypto/device-drivers/index.md>)
- [Kerberos V Cryptography API](</kernel/internals/crypto/krb5.md>)
- [SHA-3 Algorithm Collection](</kernel/internals/crypto/sha3.md>)

---

# Authenticated Encryption With Associated Data (AEAD)

_Peios Kernel / Internals / Crypto_

> Reference for Authenticated Encryption With Associated Data (AEAD).

<a id="rst-authenticated-encryption-with-associated-data-aead"></a>

<a id="rst-authenticated-encryption-with-associated-data-aead-algorithm-definitions"></a>

## Authenticated Encryption With Associated Data (AEAD) Algorithm Definitions


The AEAD cipher API is used with the ciphers of type CRYPTO_ALG_TYPE_AEAD
(listed as type "aead" in /proc/crypto)

The most prominent examples for this type of encryption is GCM and CCM.
However, the kernel supports other types of AEAD ciphers which are defined
with the following cipher string:

authenc(keyed message digest, block cipher)

For example: authenc(hmac(sha256), cbc(aes))

The example code provided for the symmetric key cipher operation applies
here as well. Naturally all *skcipher* symbols must be exchanged the *aead*
pendants discussed in the following. In addition, for the AEAD operation,
the aead_request_set_ad function must be used to set the pointer to the
associated data memory location before performing the encryption or
decryption operation. Another deviation from the asynchronous block cipher
operation is that the caller should explicitly check for -EBADMSG of the
crypto_aead_decrypt. That error indicates an authentication error, i.e.
a breach in the integrity of the message. In essence, that -EBADMSG error
code is the key bonus an AEAD cipher has over "standard" block chaining
modes.

Memory Structure:

The source scatterlist must contain the concatenation of
associated data || plaintext or ciphertext.

The destination scatterlist has the same layout, except that the plaintext
(resp. ciphertext) will grow (resp. shrink) by the authentication tag size
during encryption (resp. decryption). The authentication tag is generated
during the encryption operation and appended to the ciphertext. During
decryption, the authentication tag is consumed along with the ciphertext and
used to verify the integrity of the plaintext and the associated data.

In-place encryption/decryption is enabled by using the same scatterlist
pointer for both the source and destination.

Even in the out-of-place case, space must be reserved in the destination for
the associated data, even though it won't be written to.  This makes the
in-place and out-of-place cases more consistent.  It is permissible for the
"destination" associated data to alias the "source" associated data.

As with the other scatterlist crypto APIs, zero-length scatterlist elements
are not allowed in the used part of the scatterlist.  Thus, if there is no
associated data, the first element must point to the plaintext/ciphertext.

To meet the needs of IPsec, a special quirk applies to rfc4106, rfc4309,
rfc4543, and rfc7539esp ciphers.  For these ciphers, the final 'ivsize' bytes
of the associated data buffer must contain a second copy of the IV.  This is
in addition to the copy passed to [`aead_request_set_crypt()`](#c-aead_request_set_crypt).  These two IV
copies must not differ; different implementations of the same algorithm may
behave differently in that case.  Note that the algorithm might not actually
treat the IV as associated data; nevertheless the length passed to
[`aead_request_set_ad()`](#c-aead_request_set_ad) must include it.



#### <a id="c-struct-aead_request"></a>`struct aead_request`

AEAD request

**Definition**

```c
struct aead_request {
    struct crypto_async_request base;
    unsigned int assoclen;
    unsigned int cryptlen;
    u8 *iv;
    struct scatterlist *src;
    struct scatterlist *dst;
    void *__ctx[] ;
};
```

**Members**

- `base`: Common attributes for async crypto requests
- `assoclen`: Length in bytes of associated data for authentication
- `cryptlen`: Length of data to be encrypted or decrypted
- `iv`: Initialisation vector
- `src`: Source data
- `dst`: Destination data
- `__ctx`: Start of private context data

#### <a id="c-struct-aead_alg"></a>`struct aead_alg`

AEAD cipher definition

**Definition**

```c
struct aead_alg {
    int (*setkey)(struct crypto_aead *tfm, const u8 *key, unsigned int keylen);
    int (*setauthsize)(struct crypto_aead *tfm, unsigned int authsize);
    int (*encrypt)(struct aead_request *req);
    int (*decrypt)(struct aead_request *req);
    int (*init)(struct crypto_aead *tfm);
    void (*exit)(struct crypto_aead *tfm);
    unsigned int ivsize;
    unsigned int maxauthsize;
    unsigned int chunksize;
    struct crypto_alg base;
};
```

**Members**

- `setkey`: see struct skcipher_alg
- `setauthsize`: Set authentication size for the AEAD transformation. This
  function is used to specify the consumer requested size of the
  authentication tag to be either generated by the transformation
  during encryption or the size of the authentication tag to be
  supplied during the decryption operation. This function is also
  responsible for checking the authentication tag size for
  validity.
- `encrypt`: see struct skcipher_alg
- `decrypt`: see struct skcipher_alg
- `init`: Initialize the cryptographic transformation object. This function
  is used to initialize the cryptographic transformation object.
  This function is called only once at the instantiation time, right
  after the transformation context was allocated. In case the
  cryptographic hardware has some special requirements which need to
  be handled by software, this function shall check for the precise
  requirement of the transformation and put any software fallbacks
  in place.
- `exit`: Deinitialize the cryptographic transformation object. This is a
  counterpart to **init**, used to remove various changes set in
  **init**.
- `ivsize`: see struct skcipher_alg
- `maxauthsize`: Set the maximum authentication tag size supported by the
  transformation. A transformation may support smaller tag sizes.
  As the authentication tag is a message digest to ensure the
  integrity of the encrypted data, a consumer typically wants the
  largest authentication tag possible as defined by this
  variable.
- `chunksize`: see struct skcipher_alg
- `base`: Definition of a generic crypto cipher algorithm.

**Description**

All fields except **ivsize** is mandatory and must be filled.


<a id="rst-authenticated-encryption-with-associated-data-aead-cipher-api"></a>

## Authenticated Encryption With Associated Data (AEAD) Cipher API


#### <a id="c-crypto_alloc_aead"></a>`crypto_alloc_aead()`

```c
struct crypto_aead * crypto_alloc_aead(const char *alg_name, u32 type, u32 mask)
```

allocate AEAD cipher handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  AEAD cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for an AEAD. The returned struct
crypto_aead is the cipher handle that is required for any subsequent
API invocation for that AEAD.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_aead"></a>`crypto_free_aead()`

```c
void crypto_free_aead(struct crypto_aead *tfm)
```

zeroize and free aead handle

**Parameters**

- `struct crypto_aead *tfm`: cipher handle to be freed

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_aead_ivsize"></a>`crypto_aead_ivsize()`

```c
unsigned int crypto_aead_ivsize(struct crypto_aead *tfm)
```

obtain IV size

**Parameters**

- `struct crypto_aead *tfm`: cipher handle

**Description**

The size of the IV for the aead referenced by the cipher handle is
returned. This IV size may be zero if the cipher does not need an IV.

**Return**

IV size in bytes

#### <a id="c-crypto_aead_authsize"></a>`crypto_aead_authsize()`

```c
unsigned int crypto_aead_authsize(struct crypto_aead *tfm)
```

obtain maximum authentication data size

**Parameters**

- `struct crypto_aead *tfm`: cipher handle

**Description**

The maximum size of the authentication data for the AEAD cipher referenced
by the AEAD cipher handle is returned. The authentication data size may be
zero if the cipher implements a hard-coded maximum.

The authentication data may also be known as "tag value".

**Return**

authentication data size / tag size in bytes

#### <a id="c-crypto_aead_blocksize"></a>`crypto_aead_blocksize()`

```c
unsigned int crypto_aead_blocksize(struct crypto_aead *tfm)
```

obtain block size of cipher

**Parameters**

- `struct crypto_aead *tfm`: cipher handle

**Description**

The block size for the AEAD referenced with the cipher handle is returned.
The caller may use that information to allocate appropriate memory for the
data returned by the encryption or decryption operation

**Return**

block size of cipher

#### <a id="c-crypto_aead_setkey"></a>`crypto_aead_setkey()`

```c
int crypto_aead_setkey(struct crypto_aead *tfm, const u8 *key, unsigned int keylen)
```

set key for cipher

**Parameters**

- `struct crypto_aead *tfm`: cipher handle
- `const u8 *key`: buffer holding the key
- `unsigned int keylen`: length of the key in bytes

**Description**

The caller provided key is set for the AEAD referenced by the cipher
handle.

Note, the key length determines the cipher type. Many block ciphers implement
different cipher modes depending on the key size, such as AES-128 vs AES-192
vs. AES-256. When providing a 16 byte key for an AES cipher handle, AES-128
is performed.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_aead_setauthsize"></a>`crypto_aead_setauthsize()`

```c
int crypto_aead_setauthsize(struct crypto_aead *tfm, unsigned int authsize)
```

set authentication data size

**Parameters**

- `struct crypto_aead *tfm`: cipher handle
- `unsigned int authsize`: size of the authentication data / tag in bytes

**Description**

Set the authentication data size / tag size. AEAD requires an authentication
tag (or MAC) in addition to the associated data.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_aead_encrypt"></a>`crypto_aead_encrypt()`

```c
int crypto_aead_encrypt(struct aead_request *req)
```

encrypt plaintext

**Parameters**

- `struct aead_request *req`: reference to the aead_request handle that holds all information
  needed to perform the cipher operation

**Description**

Encrypt plaintext data using the aead_request handle. That data structure
and how it is filled with data is discussed with the aead_request_*
functions.

- IMPORTANT NOTE The encryption operation creates the authentication data /

  tag. That data is concatenated with the created ciphertext.
  The ciphertext memory size is therefore the given number of
  block cipher blocks + the size defined by the
  crypto_aead_setauthsize invocation. The caller must ensure
  that sufficient memory is available for the ciphertext and
  the authentication tag.

**Return**

0 if the cipher operation was successful; \< 0 if an error occurred

#### <a id="c-crypto_aead_decrypt"></a>`crypto_aead_decrypt()`

```c
int crypto_aead_decrypt(struct aead_request *req)
```

decrypt ciphertext

**Parameters**

- `struct aead_request *req`: reference to the aead_request handle that holds all information
  needed to perform the cipher operation

**Description**

Decrypt ciphertext data using the aead_request handle. That data structure
and how it is filled with data is discussed with the aead_request_*
functions.

- IMPORTANT NOTE The caller must concatenate the ciphertext followed by the

  authentication data / tag. That authentication data / tag
  must have the size defined by the crypto_aead_setauthsize
  invocation.

**Return**

0 if the cipher operation was successful; -EBADMSG: The AEAD
cipher operation performs the authentication of the data during the
decryption operation. Therefore, the function returns this error if
the authentication of the ciphertext was unsuccessful (i.e. the
integrity of the ciphertext or the associated data was violated);
\< 0 if an error occurred.


<a id="rst-asynchronous-aead-request-handle"></a>

## Asynchronous AEAD Request Handle


The aead_request data structure contains all pointers to data required for
the AEAD cipher operation. This includes the cipher handle (which can be
used by multiple aead_request instances), pointer to plaintext and
ciphertext, asynchronous callback function, etc. It acts as a handle to the
aead_request_* API calls in a similar way as AEAD handle to the
crypto_aead_* API calls.



#### <a id="c-crypto_aead_reqsize"></a>`crypto_aead_reqsize()`

```c
unsigned int crypto_aead_reqsize(struct crypto_aead *tfm)
```

obtain size of the request data structure

**Parameters**

- `struct crypto_aead *tfm`: cipher handle

**Return**

number of bytes

#### <a id="c-aead_request_set_tfm"></a>`aead_request_set_tfm()`

```c
void aead_request_set_tfm(struct aead_request *req, struct crypto_aead *tfm)
```

update cipher handle reference in request

**Parameters**

- `struct aead_request *req`: request handle to be modified
- `struct crypto_aead *tfm`: cipher handle that shall be added to the request handle

**Description**

Allow the caller to replace the existing aead handle in the request
data structure with a different one.

#### <a id="c-aead_request_alloc"></a>`aead_request_alloc()`

```c
struct aead_request * aead_request_alloc(struct crypto_aead *tfm, gfp_t gfp)
```

allocate request data structure

**Parameters**

- `struct crypto_aead *tfm`: cipher handle to be registered with the request
- `gfp_t gfp`: memory allocation flag that is handed to kmalloc by the API call.

**Description**

Allocate the request data structure that must be used with the AEAD
encrypt and decrypt API calls. During the allocation, the provided aead
handle is registered in the request data structure.

**Return**

allocated request handle in case of success, or NULL if out of memory

#### <a id="c-aead_request_free"></a>`aead_request_free()`

```c
void aead_request_free(struct aead_request *req)
```

zeroize and free request data structure

**Parameters**

- `struct aead_request *req`: request data structure cipher handle to be freed

#### <a id="c-aead_request_set_callback"></a>`aead_request_set_callback()`

```c
void aead_request_set_callback(struct aead_request *req, u32 flags, crypto_completion_t compl, void *data)
```

set asynchronous callback function

**Parameters**

- `struct aead_request *req`: request handle
- `u32 flags`: specify zero or an ORing of the flags
  CRYPTO_TFM_REQ_MAY_BACKLOG the request queue may back log and
  increase the wait queue beyond the initial maximum size;
  CRYPTO_TFM_REQ_MAY_SLEEP the request processing may sleep
- `crypto_completion_t compl`: callback function pointer to be registered with the request handle
- `void *data`: The data pointer refers to memory that is not used by the kernel
  crypto API, but provided to the callback function for it to use. Here,
  the caller can provide a reference to memory the callback function can
  operate on. As the callback function is invoked asynchronously to the
  related functionality, it may need to access data structures of the
  related functionality which can be referenced using this pointer. The
  callback function can access the memory via the "data" field in the
  crypto_async_request data structure provided to the callback function.

**Description**

Setting the callback function that is triggered once the cipher operation
completes

The callback function is registered with the aead_request handle and
must comply with the following template:

```text
void callback_function(struct crypto_async_request *req, int error)
```

#### <a id="c-aead_request_set_crypt"></a>`aead_request_set_crypt()`

```c
void aead_request_set_crypt(struct aead_request *req, struct scatterlist *src, struct scatterlist *dst, unsigned int cryptlen, u8 *iv)
```

set data buffers

**Parameters**

- `struct aead_request *req`: request handle
- `struct scatterlist *src`: source scatter / gather list
- `struct scatterlist *dst`: destination scatter / gather list
- `unsigned int cryptlen`: number of bytes to process from **src**
- `u8 *iv`: IV for the cipher operation which must comply with the IV size defined
  by [`crypto_aead_ivsize()`](#c-crypto_aead_ivsize)

**Description**

Setting the source data and destination data scatter / gather lists which
hold the associated data concatenated with the plaintext or ciphertext. See
below for the authentication tag.

For encryption, the source is treated as the plaintext and the
destination is the ciphertext. For a decryption operation, the use is
reversed - the source is the ciphertext and the destination is the plaintext.

The memory structure for cipher operation has the following structure:

- AEAD encryption input:  assoc data || plaintext
- AEAD encryption output: assoc data || ciphertext || auth tag
- AEAD decryption input:  assoc data || ciphertext || auth tag
- AEAD decryption output: assoc data || plaintext

Albeit the kernel requires the presence of the AAD buffer, however,
the kernel does not fill the AAD buffer in the output case. If the
caller wants to have that data buffer filled, the caller must either
use an in-place cipher operation (i.e. same memory location for
input/output memory location).

#### <a id="c-aead_request_set_ad"></a>`aead_request_set_ad()`

```c
void aead_request_set_ad(struct aead_request *req, unsigned int assoclen)
```

set associated data information

**Parameters**

- `struct aead_request *req`: request handle
- `unsigned int assoclen`: number of bytes in associated data

**Description**

Setting the AD information.  This function sets the length of
the associated data.

---

# Asymmetric Cipher

_Peios Kernel / Internals / Crypto_

> Reference for Asymmetric Cipher.

<a id="rst-asymmetric-cipher"></a>

<a id="rst-asymmetric-cipher-algorithm-definitions"></a>

## Asymmetric Cipher Algorithm Definitions


#### <a id="c-struct-akcipher_request"></a>`struct akcipher_request`

public key cipher request

**Definition**

```c
struct akcipher_request {
    struct crypto_async_request base;
    struct scatterlist *src;
    struct scatterlist *dst;
    unsigned int src_len;
    unsigned int dst_len;
    void *__ctx[] ;
};
```

**Members**

- `base`: Common attributes for async crypto requests
- `src`: Source data
- `dst`: Destination data
- `src_len`: Size of the input buffer
- `dst_len`: Size of **dst** buffer
  It needs to be at least as big as the expected result
  depending on the operation.
  After operation it will be updated with the actual size of the
  result.
  In case of error where the dst sgl size was insufficient,
  it will be updated to the size required for the operation.
- `__ctx`: Start of private context data

#### <a id="c-struct-akcipher_alg"></a>`struct akcipher_alg`

generic public key cipher algorithm

**Definition**

```c
struct akcipher_alg {
    int (*encrypt)(struct akcipher_request *req);
    int (*decrypt)(struct akcipher_request *req);
    int (*set_pub_key)(struct crypto_akcipher *tfm, const void *key, unsigned int keylen);
    int (*set_priv_key)(struct crypto_akcipher *tfm, const void *key, unsigned int keylen);
    unsigned int (*max_size)(struct crypto_akcipher *tfm);
    int (*init)(struct crypto_akcipher *tfm);
    void (*exit)(struct crypto_akcipher *tfm);
    struct crypto_alg base;
};
```

**Members**

- `encrypt`: Function performs an encrypt operation as defined by public key
  algorithm. In case of error, where the dst_len was insufficient,
  the req->dst_len will be updated to the size required for the
  operation
- `decrypt`: Function performs a decrypt operation as defined by public key
  algorithm. In case of error, where the dst_len was insufficient,
  the req->dst_len will be updated to the size required for the
  operation
- `set_pub_key`: Function invokes the algorithm specific set public key
  function, which knows how to decode and interpret
  the BER encoded public key and parameters
- `set_priv_key`: Function invokes the algorithm specific set private key
  function, which knows how to decode and interpret
  the BER encoded private key and parameters
- `max_size`: Function returns dest buffer size required for a given key.
- `init`: Initialize the cryptographic transformation object.
  This function is used to initialize the cryptographic
  transformation object. This function is called only once at
  the instantiation time, right after the transformation context
  was allocated. In case the cryptographic hardware has some
  special requirements which need to be handled by software, this
  function shall check for the precise requirement of the
  transformation and put any software fallbacks in place.
- `exit`: Deinitialize the cryptographic transformation object. This is a
  counterpart to **init**, used to remove various changes set in
  **init**.
- `base`: Common crypto API algorithm data structure


<a id="rst-asymmetric-cipher-api"></a>

## Asymmetric Cipher API


The Public Key Cipher API is used with the algorithms of type
CRYPTO_ALG_TYPE_AKCIPHER (listed as type "akcipher" in /proc/crypto)



#### <a id="c-crypto_alloc_akcipher"></a>`crypto_alloc_akcipher()`

```c
struct crypto_akcipher * crypto_alloc_akcipher(const char *alg_name, u32 type, u32 mask)
```

allocate AKCIPHER tfm handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  public key algorithm e.g. "rsa"
- `u32 type`: specifies the type of the algorithm
- `u32 mask`: specifies the mask for the algorithm

**Description**

Allocate a handle for public key algorithm. The returned struct
crypto_akcipher is the handle that is required for any subsequent
API invocation for the public key operations.

**Return**

allocated handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_akcipher"></a>`crypto_free_akcipher()`

```c
void crypto_free_akcipher(struct crypto_akcipher *tfm)
```

free AKCIPHER tfm handle

**Parameters**

- `struct crypto_akcipher *tfm`: AKCIPHER tfm handle allocated with [`crypto_alloc_akcipher()`](#c-crypto_alloc_akcipher)

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_akcipher_maxsize"></a>`crypto_akcipher_maxsize()`

```c
unsigned int crypto_akcipher_maxsize(struct crypto_akcipher *tfm)
```

Get len for output buffer

**Parameters**

- `struct crypto_akcipher *tfm`: AKCIPHER tfm handle allocated with [`crypto_alloc_akcipher()`](#c-crypto_alloc_akcipher)

**Description**

Function returns the dest buffer size required for a given key.
Function assumes that the key is already set in the transformation. If this
function is called without a setkey or with a failed setkey, you will end up
in a NULL dereference.

#### <a id="c-crypto_akcipher_encrypt"></a>`crypto_akcipher_encrypt()`

```c
int crypto_akcipher_encrypt(struct akcipher_request *req)
```

Invoke public key encrypt operation

**Parameters**

- `struct akcipher_request *req`: asymmetric key request

**Description**

Function invokes the specific public key encrypt operation for a given
public key algorithm

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_akcipher_decrypt"></a>`crypto_akcipher_decrypt()`

```c
int crypto_akcipher_decrypt(struct akcipher_request *req)
```

Invoke public key decrypt operation

**Parameters**

- `struct akcipher_request *req`: asymmetric key request

**Description**

Function invokes the specific public key decrypt operation for a given
public key algorithm

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_akcipher_set_pub_key"></a>`crypto_akcipher_set_pub_key()`

```c
int crypto_akcipher_set_pub_key(struct crypto_akcipher *tfm, const void *key, unsigned int keylen)
```

Invoke set public key operation

**Parameters**

- `struct crypto_akcipher *tfm`: tfm handle
- `const void *key`: BER encoded public key, algo OID, paramlen, BER encoded
  parameters
- `unsigned int keylen`: length of the key (not including other data)

**Description**

Function invokes the algorithm specific set key function, which knows
how to decode and interpret the encoded key and parameters

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_akcipher_set_priv_key"></a>`crypto_akcipher_set_priv_key()`

```c
int crypto_akcipher_set_priv_key(struct crypto_akcipher *tfm, const void *key, unsigned int keylen)
```

Invoke set private key operation

**Parameters**

- `struct crypto_akcipher *tfm`: tfm handle
- `const void *key`: BER encoded private key, algo OID, paramlen, BER encoded
  parameters
- `unsigned int keylen`: length of the key (not including other data)

**Description**

Function invokes the algorithm specific set key function, which knows
how to decode and interpret the encoded key and parameters

**Return**

zero on success; error code in case of error


<a id="rst-asymmetric-cipher-request-handle"></a>

## Asymmetric Cipher Request Handle


#### <a id="c-akcipher_request_alloc"></a>`akcipher_request_alloc()`

```c
struct akcipher_request * akcipher_request_alloc(struct crypto_akcipher *tfm, gfp_t gfp)
```

allocates public key request

**Parameters**

- `struct crypto_akcipher *tfm`: AKCIPHER tfm handle allocated with [`crypto_alloc_akcipher()`](#c-crypto_alloc_akcipher)
- `gfp_t gfp`: allocation flags

**Return**

allocated handle in case of success or NULL in case of an error.

#### <a id="c-akcipher_request_free"></a>`akcipher_request_free()`

```c
void akcipher_request_free(struct akcipher_request *req)
```

zeroize and free public key request

**Parameters**

- `struct akcipher_request *req`: request to free

#### <a id="c-akcipher_request_set_callback"></a>`akcipher_request_set_callback()`

```c
void akcipher_request_set_callback(struct akcipher_request *req, u32 flgs, crypto_completion_t cmpl, void *data)
```

Sets an asynchronous callback.

**Parameters**

- `struct akcipher_request *req`: request that the callback will be set for
- `u32 flgs`: specify for instance if the operation may backlog
- `crypto_completion_t cmpl`: callback which will be called
- `void *data`: private data used by the caller

**Description**

Callback will be called when an asynchronous operation on a given
request is finished.

#### <a id="c-akcipher_request_set_crypt"></a>`akcipher_request_set_crypt()`

```c
void akcipher_request_set_crypt(struct akcipher_request *req, struct scatterlist *src, struct scatterlist *dst, unsigned int src_len, unsigned int dst_len)
```

Sets request parameters

**Parameters**

- `struct akcipher_request *req`: public key request
- `struct scatterlist *src`: ptr to input scatter list
- `struct scatterlist *dst`: ptr to output scatter list
- `unsigned int src_len`: size of the src input scatter list to be processed
- `unsigned int dst_len`: size of the dst output scatter list

**Description**

Sets parameters required by crypto operation

---

# Message Digest

_Peios Kernel / Internals / Crypto_

> Reference for Message Digest.

<a id="rst-message-digest"></a>

<a id="rst-message-digest-algorithm-definitions"></a>

## Message Digest Algorithm Definitions


These data structures define modular message digest algorithm
implementations, managed via `crypto_register_ahash()`,
`crypto_register_shash()`, `crypto_unregister_ahash()` and
`crypto_unregister_shash()`.



#### <a id="c-struct-ahash_alg"></a>`struct ahash_alg`

asynchronous message digest definition

**Definition**

```c
struct ahash_alg {
    int (*init)(struct ahash_request *req);
    int (*update)(struct ahash_request *req);
    int (*final)(struct ahash_request *req);
    int (*finup)(struct ahash_request *req);
    int (*digest)(struct ahash_request *req);
    int (*export)(struct ahash_request *req, void *out);
    int (*import)(struct ahash_request *req, const void *in);
    int (*export_core)(struct ahash_request *req, void *out);
    int (*import_core)(struct ahash_request *req, const void *in);
    int (*setkey)(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen);
    int (*init_tfm)(struct crypto_ahash *tfm);
    void (*exit_tfm)(struct crypto_ahash *tfm);
    int (*clone_tfm)(struct crypto_ahash *dst, struct crypto_ahash *src);
    struct hash_alg_common halg;
};
```

**Members**

- `init`:

  **\[mandatory\]** Initialize the transformation context. Intended only to initialize the
  state of the HASH transformation at the beginning. This shall fill in
  the internal structures used during the entire duration of the whole
  transformation. No data processing happens at this point. Driver code
  implementation must not use req->result.
- `update`:

  **\[mandatory\]** Push a chunk of data into the driver for transformation. This
  function actually pushes blocks of data from upper layers into the
  driver, which then passes those to the hardware as seen fit. This
  function must not finalize the HASH transformation by calculating the
  final message digest as this only adds more data into the
  transformation. This function shall not modify the transformation
  context, as this function may be called in parallel with the same
  transformation object. Data processing can happen synchronously
  \[SHASH\] or asynchronously \[AHASH\] at this point. Driver must not use
  req->result.
  For block-only algorithms, **update** must return the number
  of bytes to store in the API partial block buffer.
- `final`:

  **\[mandatory\]** Retrieve result from the driver. This function finalizes the
  transformation and retrieves the resulting hash from the driver and
  pushes it back to upper layers. No data processing happens at this
  point unless hardware requires it to finish the transformation
  (then the data buffered by the device driver is processed).
- `finup`:

  **\[optional\]** Combination of **update** and **final**. This function is effectively a
  combination of **update** and **final** calls issued in sequence. As some
  hardware cannot do **update** and **final** separately, this callback was
  added to allow such hardware to be used at least by IPsec. Data
  processing can happen synchronously \[SHASH\] or asynchronously \[AHASH\]
  at this point.
- `digest`: Combination of **init** and **update** and **final**. This function
  effectively behaves as the entire chain of operations, **init**,
  **update** and **final** issued in sequence. Just like **finup**, this was
  added for hardware which cannot do even the **finup**, but can only do
  the whole transformation in one run. Data processing can happen
  synchronously \[SHASH\] or asynchronously \[AHASH\] at this point.
- `export`: Export partial state of the transformation. This function dumps the
  entire state of the ongoing transformation into a provided block of
  data so it can be **import** 'ed back later on. This is useful in case
  you want to save partial result of the transformation after
  processing certain amount of data and reload this partial result
  multiple times later on for multiple re-use. No data processing
  happens at this point. Driver must not use req->result.
- `import`: Import partial state of the transformation. This function loads the
  entire state of the ongoing transformation from a provided block of
  data so the transformation can continue from this point onward. No
  data processing happens at this point. Driver must not use
  req->result.
- `export_core`: Export partial state without partial block.  Only defined
  for algorithms that are not block-only.
- `import_core`: Import partial state without partial block.  Only defined
  for algorithms that are not block-only.
- `setkey`: Set optional key used by the hashing algorithm. Intended to push
  optional key used by the hashing algorithm from upper layers into
  the driver. This function can store the key in the transformation
  context or can outright program it into the hardware. In the former
  case, one must be careful to program the key into the hardware at
  appropriate time and one must be careful that .`setkey()` can be
  called multiple times during the existence of the transformation
  object. Not  all hashing algorithms do implement this function as it
  is only needed for keyed message digests. SHAx/MDx/CRCx do NOT
  implement this function. HMAC(MDx)/HMAC(SHAx)/CMAC(AES) do implement
  this function. This function must be called before any other of the
  **init**, **update**, **final**, **finup**, **digest** is called. No data
  processing happens at this point.
- `init_tfm`: Initialize the cryptographic transformation object.
  This function is called only once at the instantiation
  time, right after the transformation context was
  allocated. In case the cryptographic hardware has
  some special requirements which need to be handled
  by software, this function shall check for the precise
  requirement of the transformation and put any software
  fallbacks in place.
- `exit_tfm`: Deinitialize the cryptographic transformation object.
  This is a counterpart to **init_tfm**, used to remove
  various changes set in **init_tfm**.
- `clone_tfm`: Copy transform into new object, may allocate memory.
- `halg`: see struct hash_alg_common

#### <a id="c-struct-shash_alg"></a>`struct shash_alg`

synchronous message digest definition

**Definition**

```c
struct shash_alg {
    int (*init)(struct shash_desc *desc);
    int (*update)(struct shash_desc *desc, const u8 *data, unsigned int len);
    int (*final)(struct shash_desc *desc, u8 *out);
    int (*finup)(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out);
    int (*digest)(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out);
    int (*export)(struct shash_desc *desc, void *out);
    int (*import)(struct shash_desc *desc, const void *in);
    int (*export_core)(struct shash_desc *desc, void *out);
    int (*import_core)(struct shash_desc *desc, const void *in);
    int (*setkey)(struct crypto_shash *tfm, const u8 *key, unsigned int keylen);
    int (*init_tfm)(struct crypto_shash *tfm);
    void (*exit_tfm)(struct crypto_shash *tfm);
    int (*clone_tfm)(struct crypto_shash *dst, struct crypto_shash *src);
    unsigned int descsize;
    union {
        struct HASH_ALG_COMMON;
        struct hash_alg_common halg;
    };
};
```

**Members**

- `init`: see struct ahash_alg
- `update`: see struct ahash_alg
- `final`: see struct ahash_alg
- `finup`: see struct ahash_alg
- `digest`: see struct ahash_alg
- `export`: see struct ahash_alg
- `import`: see struct ahash_alg
- `export_core`: see struct ahash_alg
- `import_core`: see struct ahash_alg
- `setkey`: see struct ahash_alg
- `init_tfm`: Initialize the cryptographic transformation object.
  This function is called only once at the instantiation
  time, right after the transformation context was
  allocated. In case the cryptographic hardware has
  some special requirements which need to be handled
  by software, this function shall check for the precise
  requirement of the transformation and put any software
  fallbacks in place.
- `exit_tfm`: Deinitialize the cryptographic transformation object.
  This is a counterpart to **init_tfm**, used to remove
  various changes set in **init_tfm**.
- `clone_tfm`: Copy transform into new object, may allocate memory.
- `descsize`: Size of the operational state for the message digest. This state
  size is the memory size that needs to be allocated for
  shash_desc.__ctx
- `{unnamed_union}`: anonymous
- `HASH_ALG_COMMON`: see struct hash_alg_common
- `halg`: see struct hash_alg_common


<a id="rst-asynchronous-message-digest-api"></a>

## Asynchronous Message Digest API


The asynchronous message digest API is used with the ciphers of type
CRYPTO_ALG_TYPE_AHASH (listed as type "ahash" in /proc/crypto)

The asynchronous cipher operation discussion provided for the
CRYPTO_ALG_TYPE_SKCIPHER API applies here as well.



#### <a id="c-crypto_alloc_ahash"></a>`crypto_alloc_ahash()`

```c
struct crypto_ahash * crypto_alloc_ahash(const char *alg_name, u32 type, u32 mask)
```

allocate ahash cipher handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  ahash cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for an ahash. The returned struct
crypto_ahash is the cipher handle that is required for any subsequent
API invocation for that ahash.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_ahash"></a>`crypto_free_ahash()`

```c
void crypto_free_ahash(struct crypto_ahash *tfm)
```

zeroize and free the ahash handle

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle to be freed

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_ahash_digestsize"></a>`crypto_ahash_digestsize()`

```c
unsigned int crypto_ahash_digestsize(struct crypto_ahash *tfm)
```

obtain message digest size

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle

**Description**

The size for the message digest created by the message digest cipher
referenced with the cipher handle is returned.

**Return**

message digest size of cipher

#### <a id="c-crypto_ahash_statesize"></a>`crypto_ahash_statesize()`

```c
unsigned int crypto_ahash_statesize(struct crypto_ahash *tfm)
```

obtain size of the ahash state

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle

**Description**

Return the size of the ahash state. With the [`crypto_ahash_export()`](#c-crypto_ahash_export)
function, the caller can export the state into a buffer whose size is
defined with this function.

**Return**

size of the ahash state

#### <a id="c-crypto_ahash_reqtfm"></a>`crypto_ahash_reqtfm()`

```c
struct crypto_ahash * crypto_ahash_reqtfm(struct ahash_request *req)
```

obtain cipher handle from request

**Parameters**

- `struct ahash_request *req`: asynchronous request handle that contains the reference to the ahash
  cipher handle

**Description**

Return the ahash cipher handle that is registered with the asynchronous
request handle ahash_request.

**Return**

ahash cipher handle

#### <a id="c-crypto_ahash_reqsize"></a>`crypto_ahash_reqsize()`

```c
unsigned int crypto_ahash_reqsize(struct crypto_ahash *tfm)
```

obtain size of the request data structure

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle

**Return**

size of the request data

#### <a id="c-crypto_ahash_setkey"></a>`crypto_ahash_setkey()`

```c
int crypto_ahash_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen)
```

set key for cipher handle

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle
- `const u8 *key`: buffer holding the key
- `unsigned int keylen`: length of the key in bytes

**Description**

The caller provided key is set for the ahash cipher. The cipher
handle must point to a keyed hash in order for this function to succeed.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_ahash_finup"></a>`crypto_ahash_finup()`

```c
int crypto_ahash_finup(struct ahash_request *req)
```

update and finalize message digest

**Parameters**

- `struct ahash_request *req`: reference to the ahash_request handle that holds all information
  needed to perform the cipher operation

**Description**

This function is a "short-hand" for the function calls of
crypto_ahash_update and crypto_ahash_final. The parameters have the same
meaning as discussed for those separate functions.

**Return**

see [`crypto_ahash_final()`](#c-crypto_ahash_final)

#### <a id="c-crypto_ahash_final"></a>`crypto_ahash_final()`

```c
int crypto_ahash_final(struct ahash_request *req)
```

calculate message digest

**Parameters**

- `struct ahash_request *req`: reference to the ahash_request handle that holds all information
  needed to perform the cipher operation

**Description**

Finalize the message digest operation and create the message digest
based on all data added to the cipher handle. The message digest is placed
into the output buffer registered with the ahash_request handle.

**Return**

0            if the message digest was successfully calculated;
-EINPROGRESS if data is fed into hardware (DMA) or queued for later;
-EBUSY       if queue is full and request should be resubmitted later;
other \< 0    if an error occurred

#### <a id="c-crypto_ahash_digest"></a>`crypto_ahash_digest()`

```c
int crypto_ahash_digest(struct ahash_request *req)
```

calculate message digest for a buffer

**Parameters**

- `struct ahash_request *req`: reference to the ahash_request handle that holds all information
  needed to perform the cipher operation

**Description**

This function is a "short-hand" for the function calls of crypto_ahash_init,
crypto_ahash_update and crypto_ahash_final. The parameters have the same
meaning as discussed for those separate three functions.

**Return**

see [`crypto_ahash_final()`](#c-crypto_ahash_final)

#### <a id="c-crypto_ahash_export"></a>`crypto_ahash_export()`

```c
int crypto_ahash_export(struct ahash_request *req, void *out)
```

extract current message digest state

**Parameters**

- `struct ahash_request *req`: reference to the ahash_request handle whose state is exported
- `void *out`: output buffer of sufficient size that can hold the hash state

**Description**

This function exports the hash state of the ahash_request handle into the
caller-allocated output buffer out which must have sufficient size (e.g. by
calling [`crypto_ahash_statesize()`](#c-crypto_ahash_statesize)).

**Return**

0 if the export was successful; \< 0 if an error occurred

#### <a id="c-crypto_ahash_import"></a>`crypto_ahash_import()`

```c
int crypto_ahash_import(struct ahash_request *req, const void *in)
```

import message digest state

**Parameters**

- `struct ahash_request *req`: reference to ahash_request handle the state is imported into
- `const void *in`: buffer holding the state

**Description**

This function imports the hash state into the ahash_request handle from the
input buffer. That buffer should have been generated with the
crypto_ahash_export function.

**Return**

0 if the import was successful; \< 0 if an error occurred

#### <a id="c-crypto_ahash_init"></a>`crypto_ahash_init()`

```c
int crypto_ahash_init(struct ahash_request *req)
```

(re)initialize message digest handle

**Parameters**

- `struct ahash_request *req`: ahash_request handle that already is initialized with all necessary
  data using the ahash_request_* API functions

**Description**

The call (re-)initializes the message digest referenced by the ahash_request
handle. Any potentially existing state created by previous operations is
discarded.

**Return**

see [`crypto_ahash_final()`](#c-crypto_ahash_final)


<a id="rst-asynchronous-hash-request-handle"></a>

## Asynchronous Hash Request Handle


The `ahash_request` data structure contains all pointers to data
required for the asynchronous cipher operation. This includes the cipher
handle (which can be used by multiple `ahash_request` instances), pointer
to plaintext and the message digest output buffer, asynchronous callback
function, etc. It acts as a handle to the ahash_request_* API calls in a
similar way as ahash handle to the crypto_ahash_* API calls.



#### <a id="c-ahash_request_set_tfm"></a>`ahash_request_set_tfm()`

```c
void ahash_request_set_tfm(struct ahash_request *req, struct crypto_ahash *tfm)
```

update cipher handle reference in request

**Parameters**

- `struct ahash_request *req`: request handle to be modified
- `struct crypto_ahash *tfm`: cipher handle that shall be added to the request handle

**Description**

Allow the caller to replace the existing ahash handle in the request
data structure with a different one.

#### <a id="c-ahash_request_alloc"></a>`ahash_request_alloc()`

```c
struct ahash_request * ahash_request_alloc(struct crypto_ahash *tfm, gfp_t gfp)
```

allocate request data structure

**Parameters**

- `struct crypto_ahash *tfm`: cipher handle to be registered with the request
- `gfp_t gfp`: memory allocation flag that is handed to kmalloc by the API call.

**Description**

Allocate the request data structure that must be used with the ahash
message digest API calls. During
the allocation, the provided ahash handle
is registered in the request data structure.

**Return**

allocated request handle in case of success, or NULL if out of memory

#### <a id="c-ahash_request_free"></a>`ahash_request_free()`

```c
void ahash_request_free(struct ahash_request *req)
```

zeroize and free the request data structure

**Parameters**

- `struct ahash_request *req`: request data structure cipher handle to be freed

#### <a id="c-ahash_request_set_callback"></a>`ahash_request_set_callback()`

```c
void ahash_request_set_callback(struct ahash_request *req, u32 flags, crypto_completion_t compl, void *data)
```

set asynchronous callback function

**Parameters**

- `struct ahash_request *req`: request handle
- `u32 flags`: specify zero or an ORing of the flags
  CRYPTO_TFM_REQ_MAY_BACKLOG the request queue may back log and
  increase the wait queue beyond the initial maximum size;
  CRYPTO_TFM_REQ_MAY_SLEEP the request processing may sleep
- `crypto_completion_t compl`: callback function pointer to be registered with the request handle
- `void *data`: The data pointer refers to memory that is not used by the kernel
  crypto API, but provided to the callback function for it to use. Here,
  the caller can provide a reference to memory the callback function can
  operate on. As the callback function is invoked asynchronously to the
  related functionality, it may need to access data structures of the
  related functionality which can be referenced using this pointer. The
  callback function can access the memory via the "data" field in the
  `crypto_async_request` data structure provided to the callback function.

**Description**

This function allows setting the callback function that is triggered once
the cipher operation completes.

The callback function is registered with the `ahash_request` handle and
must comply with the following template:

```text
void callback_function(struct crypto_async_request *req, int error)
```

#### <a id="c-ahash_request_set_crypt"></a>`ahash_request_set_crypt()`

```c
void ahash_request_set_crypt(struct ahash_request *req, struct scatterlist *src, u8 *result, unsigned int nbytes)
```

set data buffers

**Parameters**

- `struct ahash_request *req`: ahash_request handle to be updated
- `struct scatterlist *src`: source scatter/gather list
- `u8 *result`: buffer that is filled with the message digest -- the caller must
  ensure that the buffer has sufficient space by, for example, calling
  [`crypto_ahash_digestsize()`](#c-crypto_ahash_digestsize)
- `unsigned int nbytes`: number of bytes to process from the source scatter/gather list

**Description**

By using this call, the caller references the source scatter/gather list.
The source scatter/gather list points to the data the message digest is to
be calculated for.


<a id="rst-synchronous-message-digest-api"></a>

## Synchronous Message Digest API


The synchronous message digest API is used with the ciphers of type
CRYPTO_ALG_TYPE_SHASH (listed as type "shash" in /proc/crypto)

The message digest API is able to maintain state information for the
caller.

The synchronous message digest API can store user-related context in its
shash_desc request data structure.



#### <a id="c-crypto_alloc_shash"></a>`crypto_alloc_shash()`

```c
struct crypto_shash * crypto_alloc_shash(const char *alg_name, u32 type, u32 mask)
```

allocate message digest handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  message digest cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for a message digest. The returned `struct crypto_shash` is the cipher handle that is required for any subsequent
API invocation for that message digest.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_shash"></a>`crypto_free_shash()`

```c
void crypto_free_shash(struct crypto_shash *tfm)
```

zeroize and free the message digest handle

**Parameters**

- `struct crypto_shash *tfm`: cipher handle to be freed

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_shash_blocksize"></a>`crypto_shash_blocksize()`

```c
unsigned int crypto_shash_blocksize(struct crypto_shash *tfm)
```

obtain block size for cipher

**Parameters**

- `struct crypto_shash *tfm`: cipher handle

**Description**

The block size for the message digest cipher referenced with the cipher
handle is returned.

**Return**

block size of cipher

#### <a id="c-crypto_shash_digestsize"></a>`crypto_shash_digestsize()`

```c
unsigned int crypto_shash_digestsize(struct crypto_shash *tfm)
```

obtain message digest size

**Parameters**

- `struct crypto_shash *tfm`: cipher handle

**Description**

The size for the message digest created by the message digest cipher
referenced with the cipher handle is returned.

**Return**

digest size of cipher

#### <a id="c-crypto_shash_descsize"></a>`crypto_shash_descsize()`

```c
unsigned int crypto_shash_descsize(struct crypto_shash *tfm)
```

obtain the operational state size

**Parameters**

- `struct crypto_shash *tfm`: cipher handle

**Description**

The size of the operational state the cipher needs during operation is
returned for the hash referenced with the cipher handle. This size is
required to calculate the memory requirements to allow the caller allocating
sufficient memory for operational state.

The operational state is defined with struct shash_desc where the size of
that data structure is to be calculated as
sizeof(struct shash_desc) + crypto_shash_descsize(alg)

**Return**

size of the operational state

#### <a id="c-crypto_shash_setkey"></a>`crypto_shash_setkey()`

```c
int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen)
```

set key for message digest

**Parameters**

- `struct crypto_shash *tfm`: cipher handle
- `const u8 *key`: buffer holding the key
- `unsigned int keylen`: length of the key in bytes

**Description**

The caller provided key is set for the keyed message digest cipher. The
cipher handle must point to a keyed message digest cipher in order for this
function to succeed.

**Context**

Softirq or process context.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_shash_digest"></a>`crypto_shash_digest()`

```c
int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out)
```

calculate message digest for buffer

**Parameters**

- `struct shash_desc *desc`: see [`crypto_shash_final()`](#c-crypto_shash_final)
- `const u8 *data`: see [`crypto_shash_update()`](#c-crypto_shash_update)
- `unsigned int len`: see [`crypto_shash_update()`](#c-crypto_shash_update)
- `u8 *out`: see [`crypto_shash_final()`](#c-crypto_shash_final)

**Description**

This function is a "short-hand" for the function calls of crypto_shash_init,
crypto_shash_update and crypto_shash_final. The parameters have the same
meaning as discussed for those separate three functions.

**Context**

Softirq or process context.

**Return**

0 if the message digest creation was successful; \< 0 if an error
occurred

#### <a id="c-crypto_shash_export"></a>`crypto_shash_export()`

```c
int crypto_shash_export(struct shash_desc *desc, void *out)
```

extract operational state for message digest

**Parameters**

- `struct shash_desc *desc`: reference to the operational state handle whose state is exported
- `void *out`: output buffer of sufficient size that can hold the hash state

**Description**

This function exports the hash state of the operational state handle into the
caller-allocated output buffer out which must have sufficient size (e.g. by
calling crypto_shash_descsize).

**Context**

Softirq or process context.

**Return**

0 if the export creation was successful; \< 0 if an error occurred

#### <a id="c-crypto_shash_import"></a>`crypto_shash_import()`

```c
int crypto_shash_import(struct shash_desc *desc, const void *in)
```

import operational state

**Parameters**

- `struct shash_desc *desc`: reference to the operational state handle the state imported into
- `const void *in`: buffer holding the state

**Description**

This function imports the hash state into the operational state handle from
the input buffer. That buffer should have been generated with the
crypto_ahash_export function.

**Context**

Softirq or process context.

**Return**

0 if the import was successful; \< 0 if an error occurred

#### <a id="c-crypto_shash_init"></a>`crypto_shash_init()`

```c
int crypto_shash_init(struct shash_desc *desc)
```

(re)initialize message digest

**Parameters**

- `struct shash_desc *desc`: operational state handle that is already filled

**Description**

The call (re-)initializes the message digest referenced by the
operational state handle. Any potentially existing state created by
previous operations is discarded.

**Context**

Softirq or process context.

**Return**

0 if the message digest initialization was successful; \< 0 if an
error occurred

#### <a id="c-crypto_shash_finup"></a>`crypto_shash_finup()`

```c
int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out)
```

calculate message digest of buffer

**Parameters**

- `struct shash_desc *desc`: see [`crypto_shash_final()`](#c-crypto_shash_final)
- `const u8 *data`: see [`crypto_shash_update()`](#c-crypto_shash_update)
- `unsigned int len`: see [`crypto_shash_update()`](#c-crypto_shash_update)
- `u8 *out`: see [`crypto_shash_final()`](#c-crypto_shash_final)

**Description**

This function is a "short-hand" for the function calls of
crypto_shash_update and crypto_shash_final. The parameters have the same
meaning as discussed for those separate functions.

**Context**

Softirq or process context.

**Return**

0 if the message digest creation was successful; \< 0 if an error
occurred

#### <a id="c-crypto_shash_update"></a>`crypto_shash_update()`

```c
int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len)
```

add data to message digest for processing

**Parameters**

- `struct shash_desc *desc`: operational state handle that is already initialized
- `const u8 *data`: input data to be added to the message digest
- `unsigned int len`: length of the input data

**Description**

Updates the message digest state of the operational state handle.

**Context**

Softirq or process context.

**Return**

0 if the message digest update was successful; \< 0 if an error
occurred

#### <a id="c-crypto_shash_final"></a>`crypto_shash_final()`

```c
int crypto_shash_final(struct shash_desc *desc, u8 *out)
```

calculate message digest

**Parameters**

- `struct shash_desc *desc`: operational state handle that is already filled with data
- `u8 *out`: output buffer filled with the message digest

**Description**

Finalize the message digest operation and create the message digest
based on all data added to the cipher handle. The message digest is placed
into the output buffer. The caller must ensure that the output buffer is
large enough by using crypto_shash_digestsize.

**Context**

Softirq or process context.

**Return**

0 if the message digest creation was successful; \< 0 if an error
occurred

---

# Scatterlist Cryptographic API

_Peios Kernel / Internals / Crypto_

> The Scatterlist Crypto API takes page vectors (scatterlists) as arguments, and works directly on pages. In some cases (e.g. ECB mode ciphers), this will allow for pages to be encrypted in-place with no copying.

<a id="rst-scatterlist-cryptographic-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-introduction"></a>

## Introduction

The Scatterlist Crypto API takes page vectors (scatterlists) as arguments, and works directly on pages.  In some cases (e.g. ECB mode ciphers), this will allow for pages to be encrypted in-place with no copying.

One of the initial goals of this design was to readily support IPsec, so that processing can be applied to paged skb's without the need for linearization.

<a id="rst-details"></a>

## Details

At the lowest level are algorithms, which register dynamically with the API.

'Transforms' are user-instantiated objects, which maintain state, handle all of the implementation logic (e.g. manipulating page vectors) and provide an abstraction to the underlying algorithms.  However, at the user level they are very simple.

Conceptually, the API layering looks like this:



```text
[transform api]  (user interface)
[transform ops]  (per-type logic glue e.g. cipher.c, compress.c)
[algorithm api]  (for registering algorithms)
```

The idea is to make the user interface and algorithm registration API very simple, while hiding the core logic from both.  Many good ideas from existing APIs such as Cryptoapi and Nettle have been adapted for this.

The API currently supports five main types of transforms: AEAD (Authenticated Encryption with Associated Data), Block Ciphers, Ciphers, Compressors and Hashes.

Please note that Block Ciphers is somewhat of a misnomer.  It is in fact meant to support all ciphers including stream ciphers.  The difference between Block Ciphers and Ciphers is that the latter operates on exactly one block while the former can operate on an arbitrary amount of data, subject to block size requirements (i.e., non-stream ciphers can only process multiples of blocks).

Here's an example of how to use the API:



```text
#include <crypto/hash.h>
#include <linux/err.h>
#include <linux/scatterlist.h>

struct scatterlist sg[2];
char result[128];
struct crypto_ahash *tfm;
struct ahash_request *req;

tfm = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm))
        fail();

/* ... set up the scatterlists ... */

req = ahash_request_alloc(tfm, GFP_ATOMIC);
if (!req)
        fail();

ahash_request_set_callback(req, 0, NULL, NULL);
ahash_request_set_crypt(req, sg, result, 2);

if (crypto_ahash_digest(req))
        fail();

ahash_request_free(req);
crypto_free_ahash(tfm);
```

Many real examples are available in the regression test module (tcrypt.c).

<a id="rst-developer-notes"></a>

## Developer Notes

Transforms may only be allocated in user context, and cryptographic methods may only be called from softirq and user contexts.  For transforms with a setkey method it too should only be called from user context.

When using the API for ciphers, performance will be optimal if each scatterlist contains data which is a multiple of the cipher's block size (typically 8 bytes).  This prevents having to do any copying across non-aligned page fragment boundaries.

<a id="rst-adding-new-algorithms"></a>

## Adding New Algorithms

When submitting a new algorithm for inclusion, a mandatory requirement is that at least a few test vectors from known sources (preferably standards) be included.

Converting existing well known code is preferred, as it is more likely to have been reviewed and widely tested.  If submitting code from LGPL sources, please consider changing the license to GPL (see section 3 of the LGPL).

Algorithms submitted must also be generally patent-free (e.g. IDEA will not be included in the mainline until around 2011), and be based on a recognized standard and/or have been subjected to appropriate peer review.

Also check for any RFCs which may relate to the use of specific algorithms, as well as general application notes such as RFC2451 ("The ESP CBC-Mode Cipher Algorithms").

It's a good idea to avoid using lots of macros and use inlined functions instead, as gcc does a good job with inlining, while excessive use of macros can cause compilation problems on some platforms.

Also check the TODO list at the web site listed below to see what people might already be working on.

<a id="rst-bugs"></a>

## Bugs

- **Send bug reports to:**

  [linux-crypto@vger.kernel.org](<mailto:linux-crypto@vger.kernel.org>)

- **Cc:**

  Herbert Xu &lt;[herbert@gondor.apana.org.au](<mailto:herbert@gondor.apana.org.au>)&gt;, David S. Miller &lt;[davem@redhat.com](<mailto:davem@redhat.com>)&gt;

<a id="rst-further-information"></a>

## Further Information

For further patches and various updates, including the current TODO list, see: [http://gondor.apana.org.au/\~herbert/crypto/](<http://gondor.apana.org.au/~herbert/crypto/>)

<a id="rst-authors"></a>

## Authors

- James Morris

- David S. Miller

- Herbert Xu

<a id="rst-credits"></a>

## Credits

The following people provided invaluable feedback during the development of the API:

> - Alexey Kuznetzov
>
> - Rusty Russell
>
> - Herbert Valerio Riedel
>
> - Jeff Garzik
>
> - Michael Richardson
>
> - Andrew Morton
>
> - Ingo Oeser
>
> - Christoph Hellwig

Portions of this API were derived from the following projects:

> - **Kerneli Cryptoapi ([http://www.kerneli.org/](<http://www.kerneli.org/>))**
>
>   - Alexander Kjeldaas
>
>   - Herbert Valerio Riedel
>
>   - Kyle McMartin
>
>   - Jean-Luc Cooke
>
>   - David Bryson
>
>   - Clemens Fruhwirth
>
>   - Tobias Ringstrom
>
>   - Harald Welte

and;

> - **Nettle ([https://www.lysator.liu.se/\~nisse/nettle/](<https://www.lysator.liu.se/~nisse/nettle/>))**
>
>   - Niels Möller

Original developers of the crypto algorithms:

> - Dana L. How (DES)
>
> - Andrew Tridgell and Steve French (MD4)
>
> - Colin Plumb (MD5)
>
> - Steve Reid (SHA1)
>
> - Jean-Luc Cooke (SHA256, SHA384, SHA512)
>
> - Kazunori Miyazawa / USAGI (HMAC)
>
> - Matthew Skala (Twofish)
>
> - Dag Arne Osvik (Serpent)
>
> - Brian Gladman (AES)
>
> - Kartikey Mahendra Bhatt (CAST6)
>
> - Jon Oberheide (ARC4)
>
> - Jouni Malinen (Michael MIC)
>
> - NTT(Nippon Telegraph and Telephone Corporation) (Camellia)

- **SHA1 algorithm contributors:**

  - Jean-Francois Dive

- **DES algorithm contributors:**

  - Raimar Falke

  - Gisle Sælensminde

  - Niels Möller

- **Blowfish algorithm contributors:**

  - Herbert Valerio Riedel

  - Kyle McMartin

- **Twofish algorithm contributors:**

  - Werner Koch

  - Marc Mutz

- **SHA256/384/512 algorithm contributors:**

  - Andrew McDonald

  - Kyle McMartin

  - Herbert Valerio Riedel

- **AES algorithm contributors:**

  - Alexander Kjeldaas

  - Herbert Valerio Riedel

  - Kyle McMartin

  - Adam J. Richter

  - Fruhwirth Clemens (i586)

  - Linus Torvalds (i586)

- **CAST5 algorithm contributors:**

  - Kartikey Mahendra Bhatt (original developers unknown, FSF copyright).

- **TEA/XTEA algorithm contributors:**

  - Aaron Grothe

  - Michael Ringe

- **Khazad algorithm contributors:**

  - Aaron Grothe

- **Whirlpool algorithm contributors:**

  - Aaron Grothe

  - Jean-Luc Cooke

- **Anubis algorithm contributors:**

  - Aaron Grothe

- **Tiger algorithm contributors:**

  - Aaron Grothe

- **VIA PadLock contributors:**

  - Michal Ludvig

- **Camellia algorithm contributors:**

  - NTT(Nippon Telegraph and Telephone Corporation) (Camellia)

Generic scatterwalk code by Adam J. Richter &lt;[adam@yggdrasil.com](<mailto:adam@yggdrasil.com>)&gt;

Please send any credits updates or corrections to: Herbert Xu &lt;[herbert@gondor.apana.org.au](<mailto:herbert@gondor.apana.org.au>)&gt;

---

# Key-agreement Protocol Primitives (KPP)

_Peios Kernel / Internals / Crypto_

> Reference for Key-agreement Protocol Primitives (KPP).

<a id="rst-key-agreement-protocol-primitives-kpp"></a>

<a id="rst-key-agreement-protocol-primitives-kpp-cipher-algorithm-definitions"></a>

## Key-agreement Protocol Primitives (KPP) Cipher Algorithm Definitions


#### <a id="c-struct-kpp_request"></a>`struct kpp_request`

**Definition**

```c
struct kpp_request {
    struct crypto_async_request base;
    struct scatterlist *src;
    struct scatterlist *dst;
    unsigned int src_len;
    unsigned int dst_len;
    void *__ctx[] ;
};
```

**Members**

- `base`: Common attributes for async crypto requests
- `src`: Source data
- `dst`: Destination data
- `src_len`: Size of the input buffer
- `dst_len`: Size of the output buffer. It needs to be at least
  as big as the expected result depending on the operation
  After operation it will be updated with the actual size of the
  result. In case of error where the dst sgl size was insufficient,
  it will be updated to the size required for the operation.
- `__ctx`: Start of private context data

#### <a id="c-struct-crypto_kpp"></a>`struct crypto_kpp`

user-instantiated object which encapsulate algorithms and core processing logic

**Definition**

```c
struct crypto_kpp {
    unsigned int reqsize;
    struct crypto_tfm base;
};
```

**Members**

- `reqsize`: Request context size required by algorithm
  implementation
- `base`: Common crypto API algorithm data structure

#### <a id="c-struct-kpp_alg"></a>`struct kpp_alg`

generic key-agreement protocol primitives

**Definition**

```c
struct kpp_alg {
    int (*set_secret)(struct crypto_kpp *tfm, const void *buffer, unsigned int len);
    int (*generate_public_key)(struct kpp_request *req);
    int (*compute_shared_secret)(struct kpp_request *req);
    unsigned int (*max_size)(struct crypto_kpp *tfm);
    int (*init)(struct crypto_kpp *tfm);
    void (*exit)(struct crypto_kpp *tfm);
    struct crypto_alg base;
};
```

**Members**

- `set_secret`: Function invokes the protocol specific function to
  store the secret private key along with parameters.
  The implementation knows how to decode the buffer
- `generate_public_key`: Function generate the public key to be sent to the
  counterpart. In case of error, where output is not big
  enough req->dst_len will be updated to the size
  required
- `compute_shared_secret`: Function compute the shared secret as defined by
  the algorithm. The result is given back to the user.
  In case of error, where output is not big enough,
  req->dst_len will be updated to the size required
- `max_size`: Function returns the size of the output buffer
- `init`: Initialize the object. This is called only once at
  instantiation time. In case the cryptographic hardware
  needs to be initialized. Software fallback should be
  put in place here.
- `exit`: Undo everything **init** did.
- `base`: Common crypto API algorithm data structure

#### <a id="c-struct-kpp_secret"></a>`struct kpp_secret`

small header for packing secret buffer

**Definition**

```c
struct kpp_secret {
    unsigned short type;
    unsigned short len;
};
```

**Members**

- `type`: define type of secret. Each kpp type will define its own
- `len`: specify the len of the secret, include the header, that
  follows the struct


<a id="rst-key-agreement-protocol-primitives-kpp-cipher-api"></a>

## Key-agreement Protocol Primitives (KPP) Cipher API


The KPP API is used with the algorithm type
CRYPTO_ALG_TYPE_KPP (listed as type "kpp" in /proc/crypto)



#### <a id="c-crypto_alloc_kpp"></a>`crypto_alloc_kpp()`

```c
struct crypto_kpp * crypto_alloc_kpp(const char *alg_name, u32 type, u32 mask)
```

allocate KPP tfm handle

**Parameters**

- `const char *alg_name`: is the name of the kpp algorithm (e.g. "dh", "ecdh")
- `u32 type`: specifies the type of the algorithm
- `u32 mask`: specifies the mask for the algorithm

**Description**

Allocate a handle for kpp algorithm. The returned struct crypto_kpp
is required for any following API invocation

**Return**

allocated handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case of
an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_kpp"></a>`crypto_free_kpp()`

```c
void crypto_free_kpp(struct crypto_kpp *tfm)
```

free KPP tfm handle

**Parameters**

- `struct crypto_kpp *tfm`: KPP tfm handle allocated with [`crypto_alloc_kpp()`](#c-crypto_alloc_kpp)

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_kpp_set_secret"></a>`crypto_kpp_set_secret()`

```c
int crypto_kpp_set_secret(struct crypto_kpp *tfm, const void *buffer, unsigned int len)
```

Invoke kpp operation

**Parameters**

- `struct crypto_kpp *tfm`: tfm handle
- `const void *buffer`: Buffer holding the packet representation of the private
  key. The structure of the packet key depends on the particular
  KPP implementation. Packing and unpacking helpers are provided
  for ECDH and DH (see the respective header files for those
  implementations).
- `unsigned int len`: Length of the packet private key buffer.

**Description**

Function invokes the specific kpp operation for a given alg.

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_kpp_generate_public_key"></a>`crypto_kpp_generate_public_key()`

```c
int crypto_kpp_generate_public_key(struct kpp_request *req)
```

Invoke kpp operation

**Parameters**

- `struct kpp_request *req`: kpp key request

**Description**

Function invokes the specific kpp operation for generating the public part
for a given kpp algorithm.

To generate a private key, the caller should use a random number generator.
The output of the requested length serves as the private key.

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_kpp_compute_shared_secret"></a>`crypto_kpp_compute_shared_secret()`

```c
int crypto_kpp_compute_shared_secret(struct kpp_request *req)
```

Invoke kpp operation

**Parameters**

- `struct kpp_request *req`: kpp key request

**Description**

Function invokes the specific kpp operation for computing the shared secret
for a given kpp algorithm.

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_kpp_maxsize"></a>`crypto_kpp_maxsize()`

```c
unsigned int crypto_kpp_maxsize(struct crypto_kpp *tfm)
```

Get len for output buffer

**Parameters**

- `struct crypto_kpp *tfm`: KPP tfm handle allocated with [`crypto_alloc_kpp()`](#c-crypto_alloc_kpp)

**Description**

Function returns the output buffer size required for a given key.
Function assumes that the key is already set in the transformation. If this
function is called without a setkey or with a failed setkey, you will end up
in a NULL dereference.


<a id="rst-key-agreement-protocol-primitives-kpp-cipher-request-handle"></a>

## Key-agreement Protocol Primitives (KPP) Cipher Request Handle


#### <a id="c-kpp_request_alloc"></a>`kpp_request_alloc()`

```c
struct kpp_request * kpp_request_alloc(struct crypto_kpp *tfm, gfp_t gfp)
```

allocates kpp request

**Parameters**

- `struct crypto_kpp *tfm`: KPP tfm handle allocated with [`crypto_alloc_kpp()`](#c-crypto_alloc_kpp)
- `gfp_t gfp`: allocation flags

**Return**

allocated handle in case of success or NULL in case of an error.

#### <a id="c-kpp_request_free"></a>`kpp_request_free()`

```c
void kpp_request_free(struct kpp_request *req)
```

zeroize and free kpp request

**Parameters**

- `struct kpp_request *req`: request to free

#### <a id="c-kpp_request_set_callback"></a>`kpp_request_set_callback()`

```c
void kpp_request_set_callback(struct kpp_request *req, u32 flgs, crypto_completion_t cmpl, void *data)
```

Sets an asynchronous callback.

**Parameters**

- `struct kpp_request *req`: request that the callback will be set for
- `u32 flgs`: specify for instance if the operation may backlog
- `crypto_completion_t cmpl`: callback which will be called
- `void *data`: private data used by the caller

**Description**

Callback will be called when an asynchronous operation on a given
request is finished.

#### <a id="c-kpp_request_set_input"></a>`kpp_request_set_input()`

```c
void kpp_request_set_input(struct kpp_request *req, struct scatterlist *input, unsigned int input_len)
```

Sets input buffer

**Parameters**

- `struct kpp_request *req`: kpp request
- `struct scatterlist *input`: ptr to input scatter list
- `unsigned int input_len`: size of the input scatter list

**Description**

Sets parameters required by generate_public_key

#### <a id="c-kpp_request_set_output"></a>`kpp_request_set_output()`

```c
void kpp_request_set_output(struct kpp_request *req, struct scatterlist *output, unsigned int output_len)
```

Sets output buffer

**Parameters**

- `struct kpp_request *req`: kpp request
- `struct scatterlist *output`: ptr to output scatter list
- `unsigned int output_len`: size of the output scatter list

**Description**

Sets parameters required by kpp operation


<a id="rst-ecdh-helper-functions"></a>

## ECDH Helper Functions


To use ECDH with the KPP cipher API, the following data structure and
functions should be used.

The ECC curves known to the ECDH implementation are specified in this
header file.

To use ECDH with KPP, the following functions should be used to operate on
an ECDH private key. The packet private key that can be set with
the KPP API function call of crypto_kpp_set_secret.



#### <a id="c-struct-ecdh"></a>`struct ecdh`

define an ECDH private key

**Definition**

```c
struct ecdh {
    char *key;
    unsigned short key_size;
};
```

**Members**

- `key`: Private ECDH key
- `key_size`: Size of the private ECDH key

#### <a id="c-crypto_ecdh_key_len"></a>`crypto_ecdh_key_len()`

```c
unsigned int crypto_ecdh_key_len(const struct ecdh *params)
```

Obtain the size of the private ECDH key

**Parameters**

- `const struct ecdh *params`: private ECDH key

**Description**

This function returns the packet ECDH key size. A caller can use that
with the provided ECDH private key reference to obtain the required
memory size to hold a packet key.

**Return**

size of the key in bytes

#### <a id="c-crypto_ecdh_encode_key"></a>`crypto_ecdh_encode_key()`

```c
int crypto_ecdh_encode_key(char *buf, unsigned int len, const struct ecdh *p)
```

encode the private key

**Parameters**

- `char *buf`: Buffer allocated by the caller to hold the packet ECDH
  private key. The buffer should be at least crypto_ecdh_key_len
  bytes in size.
- `unsigned int len`: Length of the packet private key buffer
- `const struct ecdh *p`: Buffer with the caller-specified private key

**Description**

The ECDH implementations operate on a packet representation of the private
key.

**Return**

-EINVAL if buffer has insufficient size, 0 on success

#### <a id="c-crypto_ecdh_decode_key"></a>`crypto_ecdh_decode_key()`

```c
int crypto_ecdh_decode_key(const char *buf, unsigned int len, struct ecdh *p)
```

decode a private key

**Parameters**

- `const char *buf`: Buffer holding a packet key that should be decoded
- `unsigned int len`: Length of the packet private key buffer
- `struct ecdh *p`: Buffer allocated by the caller that is filled with the
  unpacked ECDH private key.

**Description**

The unpacking obtains the private key by pointing **p** to the correct location
in **buf**. Thus, both pointers refer to the same memory.

**Return**

-EINVAL if buffer has insufficient size, 0 on success


<a id="rst-dh-helper-functions"></a>

## DH Helper Functions


To use DH with the KPP cipher API, the following data structure and
functions should be used.

To use DH with KPP, the following functions should be used to operate on
a DH private key. The packet private key that can be set with
the KPP API function call of crypto_kpp_set_secret.



#### <a id="c-struct-dh"></a>`struct dh`

define a DH private key

**Definition**

```c
struct dh {
    const void *key;
    const void *p;
    const void *g;
    unsigned int key_size;
    unsigned int p_size;
    unsigned int g_size;
};
```

**Members**

- `key`: Private DH key
- `p`: Diffie-Hellman parameter P
- `g`: Diffie-Hellman generator G
- `key_size`: Size of the private DH key
- `p_size`: Size of DH parameter P
- `g_size`: Size of DH generator G

#### <a id="c-crypto_dh_key_len"></a>`crypto_dh_key_len()`

```c
unsigned int crypto_dh_key_len(const struct dh *params)
```

Obtain the size of the private DH key

**Parameters**

- `const struct dh *params`: private DH key

**Description**

This function returns the packet DH key size. A caller can use that
with the provided DH private key reference to obtain the required
memory size to hold a packet key.

**Return**

size of the key in bytes

#### <a id="c-crypto_dh_encode_key"></a>`crypto_dh_encode_key()`

```c
int crypto_dh_encode_key(char *buf, unsigned int len, const struct dh *params)
```

encode the private key

**Parameters**

- `char *buf`: Buffer allocated by the caller to hold the packet DH
  private key. The buffer should be at least crypto_dh_key_len
  bytes in size.
- `unsigned int len`: Length of the packet private key buffer
- `const struct dh *params`: Buffer with the caller-specified private key

**Description**

The DH implementations operate on a packet representation of the private
key.

**Return**

-EINVAL if buffer has insufficient size, 0 on success

#### <a id="c-crypto_dh_decode_key"></a>`crypto_dh_decode_key()`

```c
int crypto_dh_decode_key(const char *buf, unsigned int len, struct dh *params)
```

decode a private key

**Parameters**

- `const char *buf`: Buffer holding a packet key that should be decoded
- `unsigned int len`: Length of the packet private key buffer
- `struct dh *params`: Buffer allocated by the caller that is filled with the
  unpacked DH private key.

**Description**

The unpacking obtains the private key by pointing **p** to the correct location
in **buf**. Thus, both pointers refer to the same memory.

**Return**

-EINVAL if buffer has insufficient size, 0 on success

---

# Random Number Generator (RNG)

_Peios Kernel / Internals / Crypto_

> Reference for Random Number Generator (RNG).

<a id="rst-random-number-generator-rng"></a>

<a id="rst-random-number-algorithm-definitions"></a>

## Random Number Algorithm Definitions


#### <a id="c-struct-rng_alg"></a>`struct rng_alg`

random number generator definition

**Definition**

```c
struct rng_alg {
    int (*generate)(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen);
    int (*seed)(struct crypto_rng *tfm, const u8 *seed, unsigned int slen);
    void (*set_ent)(struct crypto_rng *tfm, const u8 *data, unsigned int len);
    unsigned int seedsize;
    struct crypto_alg base;
};
```

**Members**

- `generate`: The function defined by this variable obtains a
  random number. The random number generator transform
  must generate the random number out of the context
  provided with this call, plus any additional data
  if provided to the call.
- `seed`: Seed or reseed the random number generator.  With the
  invocation of this function call, the random number
  generator shall become ready for generation.  If the
  random number generator requires a seed for setting
  up a new state, the seed must be provided by the
  consumer while invoking this function. The required
  size of the seed is defined with **seedsize** .
- `set_ent`: Set entropy that would otherwise be obtained from
  entropy source.  Internal use only.
- `seedsize`: The seed size required for a random number generator
  initialization defined with this variable. Some
  random number generators does not require a seed
  as the seeding is implemented internally without
  the need of support by the consumer. In this case,
  the seed size is set to zero.
- `base`: Common crypto API algorithm data structure.


<a id="rst-crypto-api-random-number-api"></a>

## Crypto API Random Number API


The random number generator API is used with the ciphers of type
CRYPTO_ALG_TYPE_RNG (listed as type "rng" in /proc/crypto)



#### <a id="c-crypto_alloc_rng"></a>`crypto_alloc_rng()`

```c
struct crypto_rng * crypto_alloc_rng(const char *alg_name, u32 type, u32 mask)
```

- allocate RNG handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  message digest cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for a random number generator. The returned struct
crypto_rng is the cipher handle that is required for any subsequent
API invocation for that random number generator.

For all random number generators, this call creates a new private copy of
the random number generator that does not share a state with other
instances. The only exception is the "krng" random number generator which
is a kernel crypto API use case for the `get_random_bytes()` function of the
/dev/random driver.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_rng_alg"></a>`crypto_rng_alg()`

```c
struct rng_alg * crypto_rng_alg(struct crypto_rng *tfm)
```

obtain 'struct rng_alg' pointer from RNG handle

**Parameters**

- `struct crypto_rng *tfm`: RNG handle

**Return**

Pointer to 'struct rng_alg', derived from **tfm** RNG handle

#### <a id="c-crypto_free_rng"></a>`crypto_free_rng()`

```c
void crypto_free_rng(struct crypto_rng *tfm)
```

zeroize and free RNG handle

**Parameters**

- `struct crypto_rng *tfm`: cipher handle to be freed

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_rng_generate"></a>`crypto_rng_generate()`

```c
int crypto_rng_generate(struct crypto_rng *tfm, const u8 *src, unsigned int slen, u8 *dst, unsigned int dlen)
```

get random number

**Parameters**

- `struct crypto_rng *tfm`: cipher handle
- `const u8 *src`: Input buffer holding additional data, may be NULL
- `unsigned int slen`: Length of additional data
- `u8 *dst`: output buffer holding the random numbers
- `unsigned int dlen`: length of the output buffer

**Description**

This function fills the caller-allocated buffer with random
numbers using the random number generator referenced by the
cipher handle.

**Return**

0 function was successful; \< 0 if an error occurred

#### <a id="c-crypto_rng_get_bytes"></a>`crypto_rng_get_bytes()`

```c
int crypto_rng_get_bytes(struct crypto_rng *tfm, u8 *rdata, unsigned int dlen)
```

get random number

**Parameters**

- `struct crypto_rng *tfm`: cipher handle
- `u8 *rdata`: output buffer holding the random numbers
- `unsigned int dlen`: length of the output buffer

**Description**

This function fills the caller-allocated buffer with random numbers using the
random number generator referenced by the cipher handle.

**Return**

0 function was successful; \< 0 if an error occurred

#### <a id="c-crypto_rng_reset"></a>`crypto_rng_reset()`

```c
int crypto_rng_reset(struct crypto_rng *tfm, const u8 *seed, unsigned int slen)
```

re-initialize the RNG

**Parameters**

- `struct crypto_rng *tfm`: cipher handle
- `const u8 *seed`: seed input data
- `unsigned int slen`: length of the seed input data

**Description**

The reset function completely re-initializes the random number generator
referenced by the cipher handle by clearing the current state. The new state
is initialized with the caller provided seed or automatically, depending on
the random number generator type. (The SP800-90A DRBGs perform an automatic
seeding.) The seed is provided as a parameter to this function call. The
provided seed should have the length of the seed size defined for the random
number generator as defined by crypto_rng_seedsize.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_rng_seedsize"></a>`crypto_rng_seedsize()`

```c
int crypto_rng_seedsize(struct crypto_rng *tfm)
```

obtain seed size of RNG

**Parameters**

- `struct crypto_rng *tfm`: cipher handle

**Description**

The function returns the seed size for the random number generator
referenced by the cipher handle. This value may be zero if the random
number generator does not implement or require a reseeding. For example,
the SP800-90A DRBGs implement an automated reseeding after reaching a
pre-defined threshold.

**Return**

seed size for the random number generator

---

# Code Examples

_Peios Kernel / Internals / Crypto_

> This code encrypts some data with AES-256-XTS. For sake of example, all inputs are random bytes, the encryption is done in-place, and it's assumed the code is running in a context where it can sleep.

<a id="rst-code-examples"></a>

<a id="rst-code-example-for-symmetric-key-cipher-operation"></a>

## Code Example For Symmetric Key Cipher Operation

This code encrypts some data with AES-256-XTS.  For sake of example, all inputs are random bytes, the encryption is done in-place, and it's assumed the code is running in a context where it can sleep.



```text
static int test_skcipher(void)
{
        struct crypto_skcipher *tfm = NULL;
        struct skcipher_request *req = NULL;
        u8 *data = NULL;
        const size_t datasize = 512; /* data size in bytes */
        struct scatterlist sg;
        DECLARE_CRYPTO_WAIT(wait);
        u8 iv[16];  /* AES-256-XTS takes a 16-byte IV */
        u8 key[64]; /* AES-256-XTS takes a 64-byte key */
        int err;

        /*
         * Allocate a tfm (a transformation object) and set the key.
         *
         * In real-world use, a tfm and key are typically used for many
         * encryption/decryption operations.  But in this example, we'll just do a
         * single encryption operation with it (which is not very efficient).
         */

        tfm = crypto_alloc_skcipher("xts(aes)", 0, 0);
        if (IS_ERR(tfm)) {
                pr_err("Error allocating xts(aes) handle: %ld\n", PTR_ERR(tfm));
                return PTR_ERR(tfm);
        }

        get_random_bytes(key, sizeof(key));
        err = crypto_skcipher_setkey(tfm, key, sizeof(key));
        if (err) {
                pr_err("Error setting key: %d\n", err);
                goto out;
        }

        /* Allocate a request object */
        req = skcipher_request_alloc(tfm, GFP_KERNEL);
        if (!req) {
                err = -ENOMEM;
                goto out;
        }

        /* Prepare the input data */
        data = kmalloc(datasize, GFP_KERNEL);
        if (!data) {
                err = -ENOMEM;
                goto out;
        }
        get_random_bytes(data, datasize);

        /* Initialize the IV */
        get_random_bytes(iv, sizeof(iv));

        /*
         * Encrypt the data in-place.
         *
         * For simplicity, in this example we wait for the request to complete
         * before proceeding, even if the underlying implementation is asynchronous.
         *
         * To decrypt instead of encrypt, just change crypto_skcipher_encrypt() to
         * crypto_skcipher_decrypt().
         */
        sg_init_one(&sg, data, datasize);
        skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
                                           CRYPTO_TFM_REQ_MAY_SLEEP,
                                      crypto_req_done, &wait);
        skcipher_request_set_crypt(req, &sg, &sg, datasize, iv);
        err = crypto_wait_req(crypto_skcipher_encrypt(req), &wait);
        if (err) {
                pr_err("Error encrypting data: %d\n", err);
                goto out;
        }

        pr_debug("Encryption was successful\n");
out:
        crypto_free_skcipher(tfm);
        skcipher_request_free(req);
        kfree(data);
        return err;
}
```

<a id="rst-code-example-for-use-of-operational-state-memory-with-shash"></a>

## Code Example For Use of Operational State Memory With SHASH



```text
struct sdesc {
    struct shash_desc shash;
    char ctx[];
};

static struct sdesc *init_sdesc(struct crypto_shash *alg)
{
    struct sdesc *sdesc;
    int size;

    size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
    sdesc = kmalloc(size, GFP_KERNEL);
    if (!sdesc)
        return ERR_PTR(-ENOMEM);
    sdesc->shash.tfm = alg;
    return sdesc;
}

static int calc_hash(struct crypto_shash *alg,
             const unsigned char *data, unsigned int datalen,
             unsigned char *digest)
{
    struct sdesc *sdesc;
    int ret;

    sdesc = init_sdesc(alg);
    if (IS_ERR(sdesc)) {
        pr_info("can't alloc sdesc\n");
        return PTR_ERR(sdesc);
    }

    ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
    kfree(sdesc);
    return ret;
}

static int test_hash(const unsigned char *data, unsigned int datalen,
             unsigned char *digest)
{
    struct crypto_shash *alg;
    char *hash_alg_name = "sha1-padlock-nano";
    int ret;

    alg = crypto_alloc_shash(hash_alg_name, 0, 0);
    if (IS_ERR(alg)) {
            pr_info("can't alloc alg %s\n", hash_alg_name);
            return PTR_ERR(alg);
    }
    ret = calc_hash(alg, data, datalen, digest);
    crypto_free_shash(alg);
    return ret;
}
```

<a id="rst-code-example-for-random-number-generator-usage"></a>

## Code Example For Random Number Generator Usage



```text
static int get_random_numbers(u8 *buf, unsigned int len)
{
    struct crypto_rng *rng = NULL;
    char *drbg = "drbg_nopr_sha256"; /* Hash DRBG with SHA-256, no PR */
    int ret;

    if (!buf || !len) {
        pr_debug("No output buffer provided\n");
        return -EINVAL;
    }

    rng = crypto_alloc_rng(drbg, 0, 0);
    if (IS_ERR(rng)) {
        pr_debug("could not allocate RNG handle for %s\n", drbg);
        return PTR_ERR(rng);
    }

    ret = crypto_rng_get_bytes(rng, buf, len);
    if (ret < 0)
        pr_debug("generation of random numbers failed\n");
    else if (ret == 0)
        pr_debug("RNG returned no data");
    else
        pr_debug("RNG returned %d bytes of data\n", ret);

out:
    crypto_free_rng(rng);
    return ret;
}
```

---

# Asymmetric Signature

_Peios Kernel / Internals / Crypto_

> Reference for Asymmetric Signature.

<a id="rst-asymmetric-signature"></a>

<a id="rst-asymmetric-signature-algorithm-definitions"></a>

## Asymmetric Signature Algorithm Definitions


#### <a id="c-struct-sig_alg"></a>`struct sig_alg`

generic public key signature algorithm

**Definition**

```c
struct sig_alg {
    int (*sign)(struct crypto_sig *tfm, const void *src, unsigned int slen, void *dst, unsigned int dlen);
    int (*verify)(struct crypto_sig *tfm, const void *src, unsigned int slen, const void *digest, unsigned int dlen);
    int (*set_pub_key)(struct crypto_sig *tfm, const void *key, unsigned int keylen);
    int (*set_priv_key)(struct crypto_sig *tfm, const void *key, unsigned int keylen);
    unsigned int (*key_size)(struct crypto_sig *tfm);
    unsigned int (*digest_size)(struct crypto_sig *tfm);
    unsigned int (*max_size)(struct crypto_sig *tfm);
    int (*init)(struct crypto_sig *tfm);
    void (*exit)(struct crypto_sig *tfm);
    struct crypto_alg base;
};
```

**Members**

- `sign`: Function performs a sign operation as defined by public key
  algorithm. On success, the signature size is returned.
  Optional.
- `verify`: Function performs a complete verify operation as defined by
  public key algorithm, returning verification status. Optional.
- `set_pub_key`: Function invokes the algorithm specific set public key
  function, which knows how to decode and interpret
  the BER encoded public key and parameters. Mandatory.
- `set_priv_key`: Function invokes the algorithm specific set private key
  function, which knows how to decode and interpret
  the BER encoded private key and parameters. Optional.
- `key_size`: Function returns key size. Mandatory.
- `digest_size`: Function returns maximum digest size. Optional.
- `max_size`: Function returns maximum signature size. Optional.
- `init`: Initialize the cryptographic transformation object.
  This function is used to initialize the cryptographic
  transformation object. This function is called only once at
  the instantiation time, right after the transformation context
  was allocated. In case the cryptographic hardware has some
  special requirements which need to be handled by software, this
  function shall check for the precise requirement of the
  transformation and put any software fallbacks in place.
- `exit`: Deinitialize the cryptographic transformation object. This is a
  counterpart to **init**, used to remove various changes set in
  **init**.
- `base`: Common crypto API algorithm data structure


<a id="rst-asymmetric-signature-api"></a>

## Asymmetric Signature API


The Public Key Signature API is used with the algorithms of type
CRYPTO_ALG_TYPE_SIG (listed as type "sig" in /proc/crypto)



#### <a id="c-crypto_alloc_sig"></a>`crypto_alloc_sig()`

```c
struct crypto_sig * crypto_alloc_sig(const char *alg_name, u32 type, u32 mask)
```

allocate signature tfm handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  signing algorithm e.g. "ecdsa"
- `u32 type`: specifies the type of the algorithm
- `u32 mask`: specifies the mask for the algorithm

**Description**

Allocate a handle for public key signature algorithm. The returned struct
crypto_sig is the handle that is required for any subsequent
API invocation for signature operations.

**Return**

allocated handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_sig"></a>`crypto_free_sig()`

```c
void crypto_free_sig(struct crypto_sig *tfm)
```

free signature tfm handle

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_sig_keysize"></a>`crypto_sig_keysize()`

```c
unsigned int crypto_sig_keysize(struct crypto_sig *tfm)
```

Get key size

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)

**Description**

Function returns the key size in bits.
Function assumes that the key is already set in the transformation. If this
function is called without a setkey or with a failed setkey, you may end up
in a NULL dereference.

#### <a id="c-crypto_sig_digestsize"></a>`crypto_sig_digestsize()`

```c
unsigned int crypto_sig_digestsize(struct crypto_sig *tfm)
```

Get maximum digest size

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)

**Description**

Function returns the maximum digest size in bytes.
Function assumes that the key is already set in the transformation. If this
function is called without a setkey or with a failed setkey, you may end up
in a NULL dereference.

#### <a id="c-crypto_sig_maxsize"></a>`crypto_sig_maxsize()`

```c
unsigned int crypto_sig_maxsize(struct crypto_sig *tfm)
```

Get maximum signature size

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)

**Description**

Function returns the maximum signature size in bytes.
Function assumes that the key is already set in the transformation. If this
function is called without a setkey or with a failed setkey, you may end up
in a NULL dereference.

#### <a id="c-crypto_sig_sign"></a>`crypto_sig_sign()`

```c
int crypto_sig_sign(struct crypto_sig *tfm, const void *src, unsigned int slen, void *dst, unsigned int dlen)
```

Invoke signing operation

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)
- `const void *src`: source buffer
- `unsigned int slen`: source length
- `void *dst`: destination obuffer
- `unsigned int dlen`: destination length

**Description**

Function invokes the specific signing operation for a given algorithm

**Return**

signature size on success; error code in case of error

#### <a id="c-crypto_sig_verify"></a>`crypto_sig_verify()`

```c
int crypto_sig_verify(struct crypto_sig *tfm, const void *src, unsigned int slen, const void *digest, unsigned int dlen)
```

Invoke signature verification

**Parameters**

- `struct crypto_sig *tfm`: signature tfm handle allocated with [`crypto_alloc_sig()`](#c-crypto_alloc_sig)
- `const void *src`: source buffer
- `unsigned int slen`: source length
- `const void *digest`: digest
- `unsigned int dlen`: digest length

**Description**

Function invokes the specific signature verification operation
for a given algorithm.

**Return**

zero on verification success; error code in case of error.

#### <a id="c-crypto_sig_set_pubkey"></a>`crypto_sig_set_pubkey()`

```c
int crypto_sig_set_pubkey(struct crypto_sig *tfm, const void *key, unsigned int keylen)
```

Invoke set public key operation

**Parameters**

- `struct crypto_sig *tfm`: tfm handle
- `const void *key`: BER encoded public key, algo OID, paramlen, BER encoded
  parameters
- `unsigned int keylen`: length of the key (not including other data)

**Description**

Function invokes the algorithm specific set key function, which knows
how to decode and interpret the encoded key and parameters

**Return**

zero on success; error code in case of error

#### <a id="c-crypto_sig_set_privkey"></a>`crypto_sig_set_privkey()`

```c
int crypto_sig_set_privkey(struct crypto_sig *tfm, const void *key, unsigned int keylen)
```

Invoke set private key operation

**Parameters**

- `struct crypto_sig *tfm`: tfm handle
- `const void *key`: BER encoded private key, algo OID, paramlen, BER encoded
  parameters
- `unsigned int keylen`: length of the key (not including other data)

**Description**

Function invokes the algorithm specific set key function, which knows
how to decode and interpret the encoded key and parameters

**Return**

zero on success; error code in case of error

---

# Symmetric Key Cipher

_Peios Kernel / Internals / Crypto_

> Reference for Symmetric Key Cipher.

<a id="rst-symmetric-key-cipher"></a>

<a id="rst-block-cipher-algorithm-definitions"></a>

## Block Cipher Algorithm Definitions


These data structures define modular crypto algorithm implementations,
managed via `crypto_register_alg()` and `crypto_unregister_alg()`.



#### <a id="c-struct-cipher_alg"></a>`struct cipher_alg`

single-block symmetric ciphers definition

**Definition**

```c
struct cipher_alg {
    unsigned int cia_min_keysize;
    unsigned int cia_max_keysize;
    int (*cia_setkey)(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen);
    void (*cia_encrypt)(struct crypto_tfm *tfm, u8 *dst, const u8 *src);
    void (*cia_decrypt)(struct crypto_tfm *tfm, u8 *dst, const u8 *src);
};
```

**Members**

- `cia_min_keysize`: Minimum key size supported by the transformation. This is
  the smallest key length supported by this transformation
  algorithm. This must be set to one of the pre-defined
  values as this is not hardware specific. Possible values
  for this field can be found via git grep "_MIN_KEY_SIZE"
  include/crypto/
- `cia_max_keysize`: Maximum key size supported by the transformation. This is
  the largest key length supported by this transformation
  algorithm. This must be set to one of the pre-defined values
  as this is not hardware specific. Possible values for this
  field can be found via git grep "_MAX_KEY_SIZE"
  include/crypto/
- `cia_setkey`: Set key for the transformation. This function is used to either
  program a supplied key into the hardware or store the key in the
  transformation context for programming it later. Note that this
  function does modify the transformation context. This function
  can be called multiple times during the existence of the
  transformation object, so one must make sure the key is properly
  reprogrammed into the hardware. This function is also
  responsible for checking the key length for validity.
- `cia_encrypt`: Encrypt a single block. This function is used to encrypt a
  single block of data, which must be **cra_blocksize** big. This
  always operates on a full **cra_blocksize** and it is not possible
  to encrypt a block of smaller size. The supplied buffers must
  therefore also be at least of **cra_blocksize** size. Both the
  input and output buffers are always aligned to **cra_alignmask**.
  In case either of the input or output buffer supplied by user
  of the crypto API is not aligned to **cra_alignmask**, the crypto
  API will re-align the buffers. The re-alignment means that a
  new buffer will be allocated, the data will be copied into the
  new buffer, then the processing will happen on the new buffer,
  then the data will be copied back into the original buffer and
  finally the new buffer will be freed. In case a software
  fallback was put in place in the **cra_init** call, this function
  might need to use the fallback if the algorithm doesn't support
  all of the key sizes. In case the key was stored in
  transformation context, the key might need to be re-programmed
  into the hardware in this function. This function shall not
  modify the transformation context, as this function may be
  called in parallel with the same transformation object.
- `cia_decrypt`: Decrypt a single block. This is a reverse counterpart to
  **cia_encrypt**, and the conditions are exactly the same.

**Description**

All fields are mandatory and must be filled.

#### <a id="c-struct-crypto_alg"></a>`struct crypto_alg`

definition of a cryptograpic cipher algorithm

**Definition**

```c
struct crypto_alg {
    struct list_head cra_list;
    struct list_head cra_users;
    u32 cra_flags;
    unsigned int cra_blocksize;
    unsigned int cra_ctxsize;
    unsigned int cra_alignmask;
    unsigned int cra_reqsize;
    int cra_priority;
    refcount_t cra_refcnt;
    char cra_name[CRYPTO_MAX_ALG_NAME];
    char cra_driver_name[CRYPTO_MAX_ALG_NAME];
    const struct crypto_type *cra_type;
    union {
        struct cipher_alg cipher;
    } cra_u;
    int (*cra_init)(struct crypto_tfm *tfm);
    void (*cra_exit)(struct crypto_tfm *tfm);
    void (*cra_destroy)(struct crypto_alg *alg);
    struct module *cra_module;
};
```

**Members**

- `cra_list`: internally used
- `cra_users`: internally used
- `cra_flags`: Flags describing this transformation. See include/linux/crypto.h
  CRYPTO_ALG_* flags for the flags which go in here. Those are
  used for fine-tuning the description of the transformation
  algorithm.
- `cra_blocksize`: Minimum block size of this transformation. The size in bytes
  of the smallest possible unit which can be transformed with
  this algorithm. The users must respect this value.
  In case of HASH transformation, it is possible for a smaller
  block than **cra_blocksize** to be passed to the crypto API for
  transformation, in case of any other transformation type, an
  error will be returned upon any attempt to transform smaller
  than **cra_blocksize** chunks.
- `cra_ctxsize`: Size of the operational context of the transformation. This
  value informs the kernel crypto API about the memory size
  needed to be allocated for the transformation context.
- `cra_alignmask`: For cipher, skcipher, lskcipher, and aead algorithms this is
  1 less than the alignment, in bytes, that the algorithm
  implementation requires for input and output buffers.  When
  the crypto API is invoked with buffers that are not aligned
  to this alignment, the crypto API automatically utilizes
  appropriately aligned temporary buffers to comply with what
  the algorithm needs.  (For scatterlists this happens only if
  the algorithm uses the skcipher_walk helper functions.)  This
  misalignment handling carries a performance penalty, so it is
  preferred that algorithms do not set a nonzero alignmask.
  Also, crypto API users may wish to allocate buffers aligned
  to the alignmask of the algorithm being used, in order to
  avoid the API having to realign them.  Note: the alignmask is
  not supported for hash algorithms and is always 0 for them.
- `cra_reqsize`: Size of the request context for this algorithm.
- `cra_priority`: Priority of this transformation implementation. In case
  multiple transformations with same **cra_name** are available to
  the Crypto API, the kernel will use the one with highest
  **cra_priority**.
- `cra_refcnt`: internally used
- `cra_name`: Generic name (usable by multiple implementations) of the
  transformation algorithm. This is the name of the transformation
  itself. This field is used by the kernel when looking up the
  providers of particular transformation.
- `cra_driver_name`: Unique name of the transformation provider. This is the
  name of the provider of the transformation. This can be any
  arbitrary value, but in the usual case, this contains the
  name of the chip or provider and the name of the
  transformation algorithm.
- `cra_type`: Type of the cryptographic transformation. This is a pointer to
  struct crypto_type, which implements callbacks common for all
  transformation types. There are multiple options, such as
  `crypto_skcipher_type`, `crypto_ahash_type`, `crypto_rng_type`.
  This field might be empty. In that case, there are no common
  callbacks. This is the case for: cipher.
- `cra_u`: Callbacks implementing the transformation. This is a union of
  multiple structures. Depending on the type of transformation selected
  by **cra_type** and **cra_flags** above, the associated structure must be
  filled with callbacks. This field might be empty. This is the case
  for ahash, shash.
- `cra_u.cipher`: Union member which contains a single-block symmetric cipher
  definition. See **struct** **cipher_alg**.
- `cra_init`: Deprecated, do not use.
- `cra_exit`: Deprecated, do not use.
- `cra_destroy`: internally used
- `cra_module`: Owner of this transformation implementation. Set to THIS_MODULE

**Description**

The struct crypto_alg describes a generic Crypto API algorithm and is common
for all of the transformations. Any variable not documented here shall not
be used by a cipher implementation as it is internal to the Crypto API.


<a id="rst-symmetric-key-cipher-api"></a>

## Symmetric Key Cipher API


Symmetric key cipher API is used with the ciphers of type
CRYPTO_ALG_TYPE_SKCIPHER (listed as type "skcipher" in /proc/crypto).

Asynchronous cipher operations imply that the function invocation for a
cipher request returns immediately before the completion of the operation.
The cipher request is scheduled as a separate kernel thread and therefore
load-balanced on the different CPUs via the process scheduler. To allow
the kernel crypto API to inform the caller about the completion of a cipher
request, the caller must provide a callback function. That function is
invoked with the cipher handle when the request completes.

To support the asynchronous operation, additional information than just the
cipher handle must be supplied to the kernel crypto API. That additional
information is given by filling in the skcipher_request data structure.

For the symmetric key cipher API, the state is maintained with the tfm
cipher handle. A single tfm can be used across multiple calls and in
parallel. For asynchronous block cipher calls, context data supplied and
only used by the caller can be referenced the request data structure in
addition to the IV used for the cipher request. The maintenance of such
state information would be important for a crypto driver implementer to
have, because when calling the callback function upon completion of the
cipher operation, that callback function may need some information about
which operation just finished if it invoked multiple in parallel. This
state information is unused by the kernel crypto API.



#### <a id="c-crypto_alloc_skcipher"></a>`crypto_alloc_skcipher()`

```c
struct crypto_skcipher * crypto_alloc_skcipher(const char *alg_name, u32 type, u32 mask)
```

allocate symmetric key cipher handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  skcipher cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for an skcipher. The returned struct
crypto_skcipher is the cipher handle that is required for any subsequent
API invocation for that skcipher.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_skcipher"></a>`crypto_free_skcipher()`

```c
void crypto_free_skcipher(struct crypto_skcipher *tfm)
```

zeroize and free cipher handle

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle to be freed

**Description**

If **tfm** is a NULL or error pointer, this function does nothing.

#### <a id="c-crypto_has_skcipher"></a>`crypto_has_skcipher()`

```c
int crypto_has_skcipher(const char *alg_name, u32 type, u32 mask)
```

Search for the availability of an skcipher.

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  skcipher
- `u32 type`: specifies the type of the skcipher
- `u32 mask`: specifies the mask for the skcipher

**Return**

true when the skcipher is known to the kernel crypto API; false
otherwise

#### <a id="c-crypto_skcipher_ivsize"></a>`crypto_skcipher_ivsize()`

```c
unsigned int crypto_skcipher_ivsize(struct crypto_skcipher *tfm)
```

obtain IV size

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle

**Description**

The size of the IV for the skcipher referenced by the cipher handle is
returned. This IV size may be zero if the cipher does not need an IV.

**Return**

IV size in bytes

#### <a id="c-crypto_skcipher_blocksize"></a>`crypto_skcipher_blocksize()`

```c
unsigned int crypto_skcipher_blocksize(struct crypto_skcipher *tfm)
```

obtain block size of cipher

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle

**Description**

The block size for the skcipher referenced with the cipher handle is
returned. The caller may use that information to allocate appropriate
memory for the data returned by the encryption or decryption operation

**Return**

block size of cipher

#### <a id="c-crypto_skcipher_setkey"></a>`crypto_skcipher_setkey()`

```c
int crypto_skcipher_setkey(struct crypto_skcipher *tfm, const u8 *key, unsigned int keylen)
```

set key for cipher

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle
- `const u8 *key`: buffer holding the key
- `unsigned int keylen`: length of the key in bytes

**Description**

The caller provided key is set for the skcipher referenced by the cipher
handle.

Note, the key length determines the cipher type. Many block ciphers implement
different cipher modes depending on the key size, such as AES-128 vs AES-192
vs. AES-256. When providing a 16 byte key for an AES cipher handle, AES-128
is performed.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_skcipher_reqtfm"></a>`crypto_skcipher_reqtfm()`

```c
struct crypto_skcipher * crypto_skcipher_reqtfm(struct skcipher_request *req)
```

obtain cipher handle from request

**Parameters**

- `struct skcipher_request *req`: skcipher_request out of which the cipher handle is to be obtained

**Description**

Return the crypto_skcipher handle when furnishing an skcipher_request
data structure.

**Return**

crypto_skcipher handle

#### <a id="c-crypto_skcipher_encrypt"></a>`crypto_skcipher_encrypt()`

```c
int crypto_skcipher_encrypt(struct skcipher_request *req)
```

encrypt plaintext

**Parameters**

- `struct skcipher_request *req`: reference to the skcipher_request handle that holds all information
  needed to perform the cipher operation

**Description**

Encrypt plaintext data using the skcipher_request handle. That data
structure and how it is filled with data is discussed with the
skcipher_request_* functions.

**Return**

0 if the cipher operation was successful; \< 0 if an error occurred

#### <a id="c-crypto_skcipher_decrypt"></a>`crypto_skcipher_decrypt()`

```c
int crypto_skcipher_decrypt(struct skcipher_request *req)
```

decrypt ciphertext

**Parameters**

- `struct skcipher_request *req`: reference to the skcipher_request handle that holds all information
  needed to perform the cipher operation

**Description**

Decrypt ciphertext data using the skcipher_request handle. That data
structure and how it is filled with data is discussed with the
skcipher_request_* functions.

**Return**

0 if the cipher operation was successful; \< 0 if an error occurred


<a id="rst-symmetric-key-cipher-request-handle"></a>

## Symmetric Key Cipher Request Handle


The skcipher_request data structure contains all pointers to data
required for the symmetric key cipher operation. This includes the cipher
handle (which can be used by multiple skcipher_request instances), pointer
to plaintext and ciphertext, asynchronous callback function, etc. It acts
as a handle to the skcipher_request_* API calls in a similar way as
skcipher handle to the crypto_skcipher_* API calls.



#### <a id="c-crypto_skcipher_reqsize"></a>`crypto_skcipher_reqsize()`

```c
unsigned int crypto_skcipher_reqsize(struct crypto_skcipher *tfm)
```

obtain size of the request data structure

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle

**Return**

number of bytes

#### <a id="c-skcipher_request_set_tfm"></a>`skcipher_request_set_tfm()`

```c
void skcipher_request_set_tfm(struct skcipher_request *req, struct crypto_skcipher *tfm)
```

update cipher handle reference in request

**Parameters**

- `struct skcipher_request *req`: request handle to be modified
- `struct crypto_skcipher *tfm`: cipher handle that shall be added to the request handle

**Description**

Allow the caller to replace the existing skcipher handle in the request
data structure with a different one.

#### <a id="c-skcipher_request_alloc"></a>`skcipher_request_alloc()`

```c
struct skcipher_request * skcipher_request_alloc(struct crypto_skcipher *tfm, gfp_t gfp)
```

allocate request data structure

**Parameters**

- `struct crypto_skcipher *tfm`: cipher handle to be registered with the request
- `gfp_t gfp`: memory allocation flag that is handed to kmalloc by the API call.

**Description**

Allocate the request data structure that must be used with the skcipher
encrypt and decrypt API calls. During the allocation, the provided skcipher
handle is registered in the request data structure.

**Return**

allocated request handle in case of success, or NULL if out of memory

#### <a id="c-skcipher_request_free"></a>`skcipher_request_free()`

```c
void skcipher_request_free(struct skcipher_request *req)
```

zeroize and free request data structure

**Parameters**

- `struct skcipher_request *req`: request data structure cipher handle to be freed

#### <a id="c-skcipher_request_set_callback"></a>`skcipher_request_set_callback()`

```c
void skcipher_request_set_callback(struct skcipher_request *req, u32 flags, crypto_completion_t compl, void *data)
```

set asynchronous callback function

**Parameters**

- `struct skcipher_request *req`: request handle
- `u32 flags`: specify zero or an ORing of the flags
  CRYPTO_TFM_REQ_MAY_BACKLOG the request queue may back log and
  increase the wait queue beyond the initial maximum size;
  CRYPTO_TFM_REQ_MAY_SLEEP the request processing may sleep
- `crypto_completion_t compl`: callback function pointer to be registered with the request handle
- `void *data`: The data pointer refers to memory that is not used by the kernel
  crypto API, but provided to the callback function for it to use. Here,
  the caller can provide a reference to memory the callback function can
  operate on. As the callback function is invoked asynchronously to the
  related functionality, it may need to access data structures of the
  related functionality which can be referenced using this pointer. The
  callback function can access the memory via the "data" field in the
  crypto_async_request data structure provided to the callback function.

**Description**

This function allows setting the callback function that is triggered once the
cipher operation completes.

The callback function is registered with the skcipher_request handle and
must comply with the following template:

```text
void callback_function(struct crypto_async_request *req, int error)
```

#### <a id="c-skcipher_request_set_crypt"></a>`skcipher_request_set_crypt()`

```c
void skcipher_request_set_crypt(struct skcipher_request *req, struct scatterlist *src, struct scatterlist *dst, unsigned int cryptlen, void *iv)
```

set data buffers

**Parameters**

- `struct skcipher_request *req`: request handle
- `struct scatterlist *src`: source scatter / gather list
- `struct scatterlist *dst`: destination scatter / gather list
- `unsigned int cryptlen`: number of bytes to process from **src**
- `void *iv`: IV for the cipher operation which must comply with the IV size defined
  by crypto_skcipher_ivsize

**Description**

This function allows setting of the source data and destination data
scatter / gather lists.

For encryption, the source is treated as the plaintext and the
destination is the ciphertext. For a decryption operation, the use is
reversed - the source is the ciphertext and the destination is the plaintext.


<a id="rst-single-block-cipher-api"></a>

## Single Block Cipher API


The single block cipher API is used with the ciphers of type
CRYPTO_ALG_TYPE_CIPHER (listed as type "cipher" in /proc/crypto).

Using the single block cipher API calls, operations with the basic cipher
primitive can be implemented. These cipher primitives exclude any block
chaining operations including IV handling.

The purpose of this single block cipher API is to support the implementation
of templates or other concepts that only need to perform the cipher operation
on one block at a time. Templates invoke the underlying cipher primitive
block-wise and process either the input or the output data of these cipher
operations.



#### <a id="c-crypto_alloc_cipher"></a>`crypto_alloc_cipher()`

```c
struct crypto_cipher * crypto_alloc_cipher(const char *alg_name, u32 type, u32 mask)
```

allocate single block cipher handle

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  single block cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Description**

Allocate a cipher handle for a single block cipher. The returned struct
crypto_cipher is the cipher handle that is required for any subsequent API
invocation for that single block cipher.

**Return**

allocated cipher handle in case of success; [`IS_ERR()`](/kernel/internals/core-api/kernel-api.md#c-IS_ERR) is true in case
of an error, [`PTR_ERR()`](/kernel/internals/core-api/kernel-api.md#c-PTR_ERR) returns the error code.

#### <a id="c-crypto_free_cipher"></a>`crypto_free_cipher()`

```c
void crypto_free_cipher(struct crypto_cipher *tfm)
```

zeroize and free the single block cipher handle

**Parameters**

- `struct crypto_cipher *tfm`: cipher handle to be freed

#### <a id="c-crypto_has_cipher"></a>`crypto_has_cipher()`

```c
int crypto_has_cipher(const char *alg_name, u32 type, u32 mask)
```

Search for the availability of a single block cipher

**Parameters**

- `const char *alg_name`: is the cra_name / name or cra_driver_name / driver name of the
  single block cipher
- `u32 type`: specifies the type of the cipher
- `u32 mask`: specifies the mask for the cipher

**Return**

true when the single block cipher is known to the kernel crypto API;
false otherwise

#### <a id="c-crypto_cipher_blocksize"></a>`crypto_cipher_blocksize()`

```c
unsigned int crypto_cipher_blocksize(struct crypto_cipher *tfm)
```

obtain block size for cipher

**Parameters**

- `struct crypto_cipher *tfm`: cipher handle

**Description**

The block size for the single block cipher referenced with the cipher handle
tfm is returned. The caller may use that information to allocate appropriate
memory for the data returned by the encryption or decryption operation

**Return**

block size of cipher

#### <a id="c-crypto_cipher_setkey"></a>`crypto_cipher_setkey()`

```c
int crypto_cipher_setkey(struct crypto_cipher *tfm, const u8 *key, unsigned int keylen)
```

set key for cipher

**Parameters**

- `struct crypto_cipher *tfm`: cipher handle
- `const u8 *key`: buffer holding the key
- `unsigned int keylen`: length of the key in bytes

**Description**

The caller provided key is set for the single block cipher referenced by the
cipher handle.

Note, the key length determines the cipher type. Many block ciphers implement
different cipher modes depending on the key size, such as AES-128 vs AES-192
vs. AES-256. When providing a 16 byte key for an AES cipher handle, AES-128
is performed.

**Return**

0 if the setting of the key was successful; \< 0 if an error occurred

#### <a id="c-crypto_cipher_encrypt_one"></a>`crypto_cipher_encrypt_one()`

```c
void crypto_cipher_encrypt_one(struct crypto_cipher *tfm, u8 *dst, const u8 *src)
```

encrypt one block of plaintext

**Parameters**

- `struct crypto_cipher *tfm`: cipher handle
- `u8 *dst`: points to the buffer that will be filled with the ciphertext
- `const u8 *src`: buffer holding the plaintext to be encrypted

**Description**

Invoke the encryption operation of one block. The caller must ensure that
the plaintext and ciphertext buffers are at least one block in size.

#### <a id="c-crypto_cipher_decrypt_one"></a>`crypto_cipher_decrypt_one()`

```c
void crypto_cipher_decrypt_one(struct crypto_cipher *tfm, u8 *dst, const u8 *src)
```

decrypt one block of ciphertext

**Parameters**

- `struct crypto_cipher *tfm`: cipher handle
- `u8 *dst`: points to the buffer that will be filled with the plaintext
- `const u8 *src`: buffer holding the ciphertext to be decrypted

**Description**

Invoke the decryption operation of one block. The caller must ensure that
the plaintext and ciphertext buffers are at least one block in size.

---

# Programming Interface

_Peios Kernel / Internals / Crypto_

> Reference for Programming Interface.

<a id="rst-programming-interface"></a>

**Table of contents**

- [Symmetric Key Cipher](</kernel/internals/crypto/api-skcipher.md>)
- [Authenticated Encryption With Associated Data (AEAD)](</kernel/internals/crypto/api-aead.md>)
- [Message Digest](</kernel/internals/crypto/api-digest.md>)
- [Random Number Generator (RNG)](</kernel/internals/crypto/api-rng.md>)
- [Asymmetric Cipher](</kernel/internals/crypto/api-akcipher.md>)
- [Asymmetric Signature](</kernel/internals/crypto/api-sig.md>)
- [Key-agreement Protocol Primitives (KPP)](</kernel/internals/crypto/api-kpp.md>)

---

# Kernel Crypto API Architecture

_Peios Kernel / Internals / Crypto_

> The kernel crypto API provides different API calls for the following cipher types:

<a id="rst-kernel-crypto-api-architecture"></a>

<a id="rst-cipher-algorithm-types"></a>

## Cipher algorithm types

The kernel crypto API provides different API calls for the following cipher types:

- Symmetric ciphers

- AEAD ciphers

- Message digest, including keyed message digest

- Random number generation

- User space interface

<a id="rst-ciphers-and-templates"></a>

## Ciphers And Templates

The kernel crypto API provides implementations of single block ciphers and message digests. In addition, the kernel crypto API provides numerous "templates" that can be used in conjunction with the single block ciphers and message digests. Templates include all types of block chaining mode, the HMAC mechanism, etc.

Single block ciphers and message digests can either be directly used by a caller or invoked together with a template to form multi-block ciphers or keyed message digests.

A single block cipher may even be called with multiple templates. However, templates cannot be used without a single cipher.

See /proc/crypto and search for "name". For example:

- aes

- ecb(aes)

- cmac(aes)

- ccm(aes)

- rfc4106(gcm(aes))

- sha1

- hmac(sha1)

- authenc(hmac(sha1),cbc(aes))

In these examples, "aes" and "sha1" are the ciphers and all others are the templates.

<a id="rst-synchronous-and-asynchronous-operation"></a>

## Synchronous And Asynchronous Operation

The kernel crypto API provides synchronous and asynchronous API operations.

When using the synchronous API operation, the caller invokes a cipher operation which is performed synchronously by the kernel crypto API. That means, the caller waits until the cipher operation completes. Therefore, the kernel crypto API calls work like regular function calls. For synchronous operation, the set of API calls is small and conceptually similar to any other crypto library.

Asynchronous operation is provided by the kernel crypto API which implies that the invocation of a cipher operation will complete almost instantly. That invocation triggers the cipher operation but it does not signal its completion. Before invoking a cipher operation, the caller must provide a callback function the kernel crypto API can invoke to signal the completion of the cipher operation. Furthermore, the caller must ensure it can handle such asynchronous events by applying appropriate locking around its data. The kernel crypto API does not perform any special serialization operation to protect the caller's data integrity.

<a id="rst-crypto-api-cipher-references-and-priority"></a>

## Crypto API Cipher References And Priority

A cipher is referenced by the caller with a string. That string has the following semantics:



```text
template(single block cipher)
```

where "template" and "single block cipher" is the aforementioned template and single block cipher, respectively. If applicable, additional templates may enclose other templates, such as



```text
template1(template2(single block cipher)))
```

The kernel crypto API may provide multiple implementations of a template or a single block cipher. For example, AES on newer Intel hardware has the following implementations: AES-NI, assembler implementation, or straight C. Now, when using the string "aes" with the kernel crypto API, which cipher implementation is used? The answer to that question is the priority number assigned to each cipher implementation by the kernel crypto API. When a caller uses the string to refer to a cipher during initialization of a cipher handle, the kernel crypto API looks up all implementations providing an implementation with that name and selects the implementation with the highest priority.

Now, a caller may have the need to refer to a specific cipher implementation and thus does not want to rely on the priority-based selection. To accommodate this scenario, the kernel crypto API allows the cipher implementation to register a unique name in addition to common names. When using that unique name, a caller is therefore always sure to refer to the intended cipher implementation.

The list of available ciphers is given in /proc/crypto. However, that list does not specify all possible permutations of templates and ciphers. Each block listed in /proc/crypto may contain the following information -- if one of the components listed as follows are not applicable to a cipher, it is not displayed:

- name: the generic name of the cipher that is subject to the priority-based selection -- this name can be used by the cipher allocation API calls (all names listed above are examples for such generic names)

- driver: the unique name of the cipher -- this name can be used by the cipher allocation API calls

- module: the kernel module providing the cipher implementation (or "kernel" for statically linked ciphers)

- priority: the priority value of the cipher implementation

- refcnt: the reference count of the respective cipher (i.e. the number of current consumers of this cipher)

- selftest: specification whether the self test for the cipher passed

- type:

  - skcipher for symmetric key ciphers

  - cipher for single block ciphers that may be used with an additional template

  - shash for synchronous message digest

  - ahash for asynchronous message digest

  - aead for AEAD cipher type

  - compression for compression type transformations

  - rng for random number generator

  - kpp for a Key-agreement Protocol Primitive (KPP) cipher such as an ECDH or DH implementation

- blocksize: blocksize of cipher in bytes

- keysize: key size in bytes

- ivsize: IV size in bytes

- seedsize: required size of seed data for random number generator

- digestsize: output size of the message digest

- geniv: IV generator (obsolete)

<a id="rst-key-sizes"></a>

## Key Sizes

When allocating a cipher handle, the caller only specifies the cipher type. Symmetric ciphers, however, typically support multiple key sizes (e.g. AES-128 vs. AES-192 vs. AES-256). These key sizes are determined with the length of the provided key. Thus, the kernel crypto API does not provide a separate way to select the particular symmetric cipher key size.

<a id="rst-cipher-allocation-type-and-masks"></a>

## Cipher Allocation Type And Masks

The different cipher handle allocation functions allow the specification of a type and mask flag. Both parameters have the following meaning (and are therefore not covered in the subsequent sections).

The type flag specifies the type of the cipher algorithm. The caller usually provides a 0 when the caller wants the default handling. Otherwise, the caller may provide the following selections which match the aforementioned cipher types:

- CRYPTO_ALG_TYPE_CIPHER Single block cipher

- CRYPTO_ALG_TYPE_AEAD Authenticated Encryption with Associated Data (MAC)

- CRYPTO_ALG_TYPE_KPP Key-agreement Protocol Primitive (KPP) such as an ECDH or DH implementation

- CRYPTO_ALG_TYPE_HASH Raw message digest

- CRYPTO_ALG_TYPE_SHASH Synchronous multi-block hash

- CRYPTO_ALG_TYPE_AHASH Asynchronous multi-block hash

- CRYPTO_ALG_TYPE_RNG Random Number Generation

- CRYPTO_ALG_TYPE_AKCIPHER Asymmetric cipher

- CRYPTO_ALG_TYPE_SIG Asymmetric signature

- CRYPTO_ALG_TYPE_PCOMPRESS Enhanced version of CRYPTO_ALG_TYPE_COMPRESS allowing for segmented compression / decompression instead of performing the operation on one segment only. CRYPTO_ALG_TYPE_PCOMPRESS is intended to replace CRYPTO_ALG_TYPE_COMPRESS once existing consumers are converted.

The mask flag restricts the type of cipher. The only allowed flag is CRYPTO_ALG_ASYNC to restrict the cipher lookup function to asynchronous ciphers. Usually, a caller provides a 0 for the mask flag.

When the caller provides a mask and type specification, the caller limits the search the kernel crypto API can perform for a suitable cipher implementation for the given cipher name. That means, even when a caller uses a cipher name that exists during its initialization call, the kernel crypto API may not select it due to the used type and mask field.

<a id="rst-internal-structure-of-kernel-crypto-api"></a>

## Internal Structure of Kernel Crypto API

The kernel crypto API has an internal structure where a cipher implementation may use many layers and indirections. This section shall help to clarify how the kernel crypto API uses various components to implement the complete cipher.

The following subsections explain the internal structure based on existing cipher implementations. The first section addresses the most complex scenario where all other scenarios form a logical subset.

<a id="rst-generic-aead-cipher-structure"></a>

### Generic AEAD Cipher Structure

The following ASCII art decomposes the kernel crypto API layers when using the AEAD cipher with the automated IV generation. The shown example is used by the IPSEC layer.

For other use cases of AEAD ciphers, the ASCII art applies as well, but the caller may not use the AEAD cipher with a separate IV generator. In this case, the caller must generate the IV.

The depicted example decomposes the AEAD cipher of GCM(AES) based on the generic C implementations (gcm.c, aes-generic.c, ctr.c, ghash-generic.c, seqiv.c). The generic implementation serves as an example showing the complete logic of the kernel crypto API.

It is possible that some streamlined cipher implementations (like AES-NI) provide implementations merging aspects which in the view of the kernel crypto API cannot be decomposed into layers any more. In case of the AES-NI implementation, the CTR mode, the GHASH implementation and the AES cipher are all merged into one cipher implementation registered with the kernel crypto API. In this case, the concept described by the following ASCII art applies too. However, the decomposition of GCM into the individual sub-components by the kernel crypto API is not done any more.

Each block in the following ASCII art is an independent cipher instance obtained from the kernel crypto API. Each block is accessed by the caller or by other blocks using the API functions defined by the kernel crypto API for the cipher implementation type.

The blocks below indicate the cipher type as well as the specific logic implemented in the cipher.

The ASCII art picture also indicates the call structure, i.e. who calls which component. The arrows point to the invoked block where the caller uses the API applicable to the cipher type specified for the block.



```text
kernel crypto API                                |   IPSEC Layer
                                                 |
+-----------+                                    |
|           |            (1)
|   aead    | <-----------------------------------  esp_output
|  (seqiv)  | ---+
+-----------+    |
                 | (2)
+-----------+    |
|           | <--+                (2)
|   aead    | <-----------------------------------  esp_input
|   (gcm)   | ------------+
+-----------+             |
      | (3)               | (5)
      v                   v
+-----------+       +-----------+
|           |       |           |
|  skcipher |       |   ahash   |
|   (ctr)   | ---+  |  (ghash)  |
+-----------+    |  +-----------+
                 |
+-----------+    | (4)
|           | <--+
|   cipher  |
|   (aes)   |
+-----------+
```

The following call sequence is applicable when the IPSEC layer triggers an encryption operation with the esp_output function. During configuration, the administrator set up the use of seqiv(rfc4106(gcm(aes))) as the cipher for ESP. The following call sequence is now depicted in the ASCII art above:

1. esp_output() invokes crypto_aead_encrypt() to trigger an encryption operation of the AEAD cipher with IV generator.

   The SEQIV generates the IV.

2. Now, SEQIV uses the AEAD API function calls to invoke the associated AEAD cipher. In our case, during the instantiation of SEQIV, the cipher handle for GCM is provided to SEQIV. This means that SEQIV invokes AEAD cipher operations with the GCM cipher handle.

   During instantiation of the GCM handle, the CTR(AES) and GHASH ciphers are instantiated. The cipher handles for CTR(AES) and GHASH are retained for later use.

   The GCM implementation is responsible to invoke the CTR mode AES and the GHASH cipher in the right manner to implement the GCM specification.

3. The GCM AEAD cipher type implementation now invokes the SKCIPHER API with the instantiated CTR(AES) cipher handle.

   During instantiation of the CTR(AES) cipher, the CIPHER type implementation of AES is instantiated. The cipher handle for AES is retained.

   That means that the SKCIPHER implementation of CTR(AES) only implements the CTR block chaining mode. After performing the block chaining operation, the CIPHER implementation of AES is invoked.

4. The SKCIPHER of CTR(AES) now invokes the CIPHER API with the AES cipher handle to encrypt one block.

5. The GCM AEAD implementation also invokes the GHASH cipher implementation via the AHASH API.

When the IPSEC layer triggers the esp_input() function, the same call sequence is followed with the only difference that the operation starts with step (2).

<a id="rst-generic-block-cipher-structure"></a>

### Generic Block Cipher Structure

Generic block ciphers follow the same concept as depicted with the ASCII art picture above.

For example, CBC(AES) is implemented with cbc.c, and aes-generic.c. The ASCII art picture above applies as well with the difference that only step (4) is used and the SKCIPHER block chaining mode is CBC.

<a id="rst-generic-keyed-message-digest-structure"></a>

### Generic Keyed Message Digest Structure

Keyed message digest implementations again follow the same concept as depicted in the ASCII art picture above.

For example, HMAC(SHA256) is implemented with hmac.c and sha256_generic.c. The following ASCII art illustrates the implementation:



```text
kernel crypto API            |       Caller
                             |
+-----------+         (1)    |
|           | <------------------  some_function
|   ahash   |
|   (hmac)  | ---+
+-----------+    |
                 | (2)
+-----------+    |
|           | <--+
|   shash   |
|  (sha256) |
+-----------+
```

The following call sequence is applicable when a caller triggers an HMAC operation:

1. The AHASH API functions are invoked by the caller. The HMAC implementation performs its operation as needed.

   During initialization of the HMAC cipher, the SHASH cipher type of SHA256 is instantiated. The cipher handle for the SHA256 instance is retained.

   At one time, the HMAC implementation requires a SHA256 operation where the SHA256 cipher handle is used.

2. The HMAC instance now invokes the SHASH API with the SHA256 cipher handle to calculate the message digest.

---

# Asymmetric / Public-key Cryptography Key Type

_Peios Kernel / Internals / Crypto_

> The "asymmetric" key type is designed to be a container for the keys used in public-key cryptography, without imposing any particular restrictions on the form or mechanism of the cryptography or form of the key.

<a id="rst-asymmetric-public-key-cryptography-key-type"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

- Overview.
- Key identification.
- Accessing asymmetric keys.
  - Signature verification.
- Asymmetric key subtypes.
- Instantiation data parsers.
- Keyring link restrictions. -->

<a id="rst-overview"></a>

## Overview

The "asymmetric" key type is designed to be a container for the keys used in public-key cryptography, without imposing any particular restrictions on the form or mechanism of the cryptography or form of the key.

The asymmetric key is given a subtype that defines what sort of data is associated with the key and provides operations to describe and destroy it. However, no requirement is made that the key data actually be stored in the key.

A completely in-kernel key retention and operation subtype can be defined, but it would also be possible to provide access to cryptographic hardware (such as a TPM) that might be used to both retain the relevant key and perform operations using that key.  In such a case, the asymmetric key would then merely be an interface to the TPM driver.

Also provided is the concept of a data parser.  Data parsers are responsible for extracting information from the blobs of data passed to the instantiation function.  The first data parser that recognises the blob gets to set the subtype of the key and define the operations that can be done on that key.

A data parser may interpret the data blob as containing the bits representing a key, or it may interpret it as a reference to a key held somewhere else in the system (for example, a TPM).

<a id="rst-key-identification"></a>

## Key Identification

If a key is added with an empty name, the instantiation data parsers are given the opportunity to pre-parse a key and to determine the description the key should be given from the content of the key.

This can then be used to refer to the key, either by complete match or by partial match.  The key type may also use other criteria to refer to a key.

The asymmetric key type's match function can then perform a wider range of comparisons than just the straightforward comparison of the description with the criterion string:

> 1. If the criterion string is of the form "id:&lt;hexdigits&gt;" then the match function will examine a key's fingerprint to see if the hex digits given after the "id:" match the tail.  For instance:
>
>
>
>    ```text
>    keyctl search @s asymmetric id:5acc2142
>    ```
>
>    will match a key with fingerprint:
>
>
>
>    ```text
>    1A00 2040 7601 7889 DE11  882C 3823 04AD 5ACC 2142
>    ```
>
> 2. If the criterion string is of the form "&lt;subtype&gt;:&lt;hexdigits&gt;" then the match will match the ID as in (1), but with the added restriction that only keys of the specified subtype (e.g. tpm) will be matched.  For instance:
>
>
>
>    ```text
>    keyctl search @s asymmetric tpm:5acc2142
>    ```

Looking in /proc/keys, the last 8 hex digits of the key fingerprint are displayed, along with the subtype:



```text
1a39e171 I-----     1 perm 3f010000     0     0 asymmetric modsign.0: DSA 5acc2142 []
```

<a id="rst-accessing-asymmetric-keys"></a>

## Accessing Asymmetric Keys

For general access to asymmetric keys from within the kernel, the following inclusion is required:



```text
#include <crypto/public_key.h>
```

This gives access to functions for dealing with asymmetric / public keys. Three enums are defined there for representing public-key cryptography algorithms:



```text
enum pkey_algo
```

digest algorithms used by those:



```text
enum pkey_hash_algo
```

and key identifier representations:



```text
enum pkey_id_type
```

Note that the key type representation types are required because key identifiers from different standards aren't necessarily compatible.  For instance, PGP generates key identifiers by hashing the key data plus some PGP-specific metadata, whereas X.509 has arbitrary certificate identifiers.

The operations defined upon a key are:

> 1. Signature verification.

Other operations are possible (such as encryption) with the same key data required for verification, but not currently supported, and others (eg. decryption and signature generation) require extra key data.

<a id="rst-signature-verification"></a>

### Signature Verification

An operation is provided to perform cryptographic signature verification, using an asymmetric key to provide or to provide access to the public key:



```text
int verify_signature(const struct key *key,
                     const struct public_key_signature *sig);
```

The caller must have already obtained the key from some source and can then use it to check the signature.  The caller must have parsed the signature and transferred the relevant bits to the structure pointed to by sig:



```text
struct public_key_signature {
        u8 *digest;
        u8 digest_size;
        enum pkey_hash_algo pkey_hash_algo : 8;
        u8 nr_mpi;
        union {
                MPI mpi[2];
                ...
        };
};
```

The algorithm used must be noted in sig-&gt;pkey_hash_algo, and all the MPIs that make up the actual signature must be stored in sig-&gt;mpi\[\] and the count of MPIs placed in sig-&gt;nr_mpi.

In addition, the data must have been digested by the caller and the resulting hash must be pointed to by sig-&gt;digest and the size of the hash be placed in sig-&gt;digest_size.

The function will return 0 upon success or -EKEYREJECTED if the signature doesn't match.

The function may also return -ENOTSUPP if an unsupported public-key algorithm or public-key/hash algorithm combination is specified or the key doesn't support the operation; -EBADMSG or -ERANGE if some of the parameters have weird data; or -ENOMEM if an allocation can't be performed.  -EINVAL can be returned if the key argument is the wrong type or is incompletely set up.

<a id="rst-asymmetric-key-subtypes"></a>

## Asymmetric Key Subtypes

Asymmetric keys have a subtype that defines the set of operations that can be performed on that key and that determines what data is attached as the key payload.  The payload format is entirely at the whim of the subtype.

The subtype is selected by the key data parser and the parser must initialise the data required for it.  The asymmetric key retains a reference on the subtype module.

The subtype definition structure can be found in:



```text
#include <keys/asymmetric-subtype.h>
```

and looks like the following:



```text
struct asymmetric_key_subtype {
        struct module           *owner;
        const char              *name;

        void (*describe)(const struct key *key, struct seq_file *m);
        void (*destroy)(void *payload);
        int (*query)(const struct kernel_pkey_params *params,
                     struct kernel_pkey_query *info);
        int (*eds_op)(struct kernel_pkey_params *params,
                      const void *in, void *out);
        int (*verify_signature)(const struct key *key,
                                const struct public_key_signature *sig);
};
```

Asymmetric keys point to this with their payload\[asym_subtype\] member.

The owner and name fields should be set to the owning module and the name of the subtype.  Currently, the name is only used for print statements.

There are a number of operations defined by the subtype:

> 1. describe().
>
>    Mandatory.  This allows the subtype to display something in /proc/keys against the key.  For instance the name of the public key algorithm type could be displayed.  The key type will display the tail of the key identity string after this.
>
> 2. destroy().
>
>    Mandatory.  This should free the memory associated with the key.  The asymmetric key will look after freeing the fingerprint and releasing the reference on the subtype module.
>
> 3. query().
>
>    Mandatory.  This is a function for querying the capabilities of a key.
>
> 4. eds_op().
>
>    Optional.  This is the entry point for the encryption, decryption and signature creation operations (which are distinguished by the operation ID in the parameter struct).  The subtype may do anything it likes to implement an operation, including offloading to hardware.
>
> 5. verify_signature().
>
>    Optional.  This is the entry point for signature verification.  The subtype may do anything it likes to implement an operation, including offloading to hardware.

<a id="rst-instantiation-data-parsers"></a>

## Instantiation Data Parsers

The asymmetric key type doesn't generally want to store or to deal with a raw blob of data that holds the key data.  It would have to parse it and error check it each time it wanted to use it.  Further, the contents of the blob may have various checks that can be performed on it (eg. self-signatures, validity dates) and may contain useful data about the key (identifiers, capabilities).

Also, the blob may represent a pointer to some hardware containing the key rather than the key itself.

Examples of blob formats for which parsers could be implemented include:

> - OpenPGP packet stream \[RFC 4880\].
>
> - X.509 ASN.1 stream.
>
> - Pointer to TPM key.
>
> - Pointer to UEFI key.
>
> - PKCS\#8 private key \[RFC 5208\].
>
> - PKCS\#5 encrypted private key \[RFC 2898\].

During key instantiation each parser in the list is tried until one doesn't return -EBADMSG.

The parser definition structure can be found in:



```text
#include <keys/asymmetric-parser.h>
```

and looks like the following:



```text
struct asymmetric_key_parser {
        struct module   *owner;
        const char      *name;

        int (*parse)(struct key_preparsed_payload *prep);
};
```

The owner and name fields should be set to the owning module and the name of the parser.

There is currently only a single operation defined by the parser, and it is mandatory:

> 1. parse().
>
>    This is called to preparse the key from the key creation and update paths. In particular, it is called during the key creation \_before\_ a key is allocated, and as such, is permitted to provide the key's description in the case that the caller declines to do so.
>
>    The caller passes a pointer to the following struct with all of the fields cleared, except for data, datalen and quotalen \[see [Documentation/security/keys/core.rst](/kernel/internals/security/keys/core.md)\]:
>
>
>
>    ```text
>    struct key_preparsed_payload {
>            char            *description;
>            void            *payload[4];
>            const void      *data;
>            size_t          datalen;
>            size_t          quotalen;
>    };
>    ```
>
>    The instantiation data is in a blob pointed to by data and is datalen in size.  The parse() function is not permitted to change these two values at all, and shouldn't change any of the other values \_unless\_ they are recognise the blob format and will not return -EBADMSG to indicate it is not theirs.
>
>    If the parser is happy with the blob, it should propose a description for the key and attach it to -&gt;description, -&gt;payload\[asym_subtype\] should be set to point to the subtype to be used, -&gt;payload\[asym_crypto\] should be set to point to the initialised data for that subtype, -&gt;payload\[asym_key_ids\] should point to one or more hex fingerprints and quotalen should be updated to indicate how much quota this key should account for.
>
>    When clearing up, the data attached to -&gt;payload\[asym_key_ids\] and -&gt;description will be kfree()'d and the data attached to -&gt;payload\[asm_crypto\] will be passed to the subtype's -&gt;destroy() method to be disposed of.  A module reference for the subtype pointed to by -&gt;payload\[asym_subtype\] will be put.
>
>    If the data format is not recognised, -EBADMSG should be returned.  If it is recognised, but the key cannot for some reason be set up, some other negative error code should be returned.  On success, 0 should be returned.
>
>    The key's fingerprint string may be partially matched upon.  For a public-key algorithm such as RSA and DSA this will likely be a printable hex version of the key's fingerprint.

Functions are provided to register and unregister parsers:



```text
int register_asymmetric_key_parser(struct asymmetric_key_parser *parser);
void unregister_asymmetric_key_parser(struct asymmetric_key_parser *subtype);
```

Parsers may not have the same name.  The names are otherwise only used for displaying in debugging messages.

<a id="rst-keyring-link-restrictions"></a>

## Keyring Link Restrictions

Keyrings created from userspace using add_key can be configured to check the signature of the key being linked.  Keys without a valid signature are not allowed to link.

Several restriction methods are available:

> 1. Restrict using the kernel builtin trusted keyring
>
>    - Option string used with KEYCTL_RESTRICT_KEYRING: - "builtin_trusted"
>
>    The kernel builtin trusted keyring will be searched for the signing key. If the builtin trusted keyring is not configured, all links will be rejected.  The ca_keys kernel parameter also affects which keys are used for signature verification.
>
> 2. Restrict using the kernel builtin and secondary trusted keyrings
>
>    - Option string used with KEYCTL_RESTRICT_KEYRING: - "builtin_and_secondary_trusted"
>
>    The kernel builtin and secondary trusted keyrings will be searched for the signing key.  If the secondary trusted keyring is not configured, this restriction will behave like the "builtin_trusted" option.  The ca_keys kernel parameter also affects which keys are used for signature verification.
>
> 3. Restrict using a separate key or keyring
>
>    - Option string used with KEYCTL_RESTRICT_KEYRING: - "key_or_keyring:&lt;key or keyring serial number&gt;\[:chain\]"
>
>    Whenever a key link is requested, the link will only succeed if the key being linked is signed by one of the designated keys.  This key may be specified directly by providing a serial number for one asymmetric key, or a group of keys may be searched for the signing key by providing the serial number for a keyring.
>
>    When the "chain" option is provided at the end of the string, the keys within the destination keyring will also be searched for signing keys. This allows for verification of certificate chains by adding each certificate in order (starting closest to the root) to a keyring.  For instance, one keyring can be populated with links to a set of root certificates, with a separate, restricted keyring set up for each certificate chain to be validated:
>
>
>
>    ```text
>    # Create and populate a keyring for root certificates
>    root_id=`keyctl add keyring root-certs "" @s`
>    keyctl padd asymmetric "" $root_id < root1.cert
>    keyctl padd asymmetric "" $root_id < root2.cert
>
>    # Create and restrict a keyring for the certificate chain
>    chain_id=`keyctl add keyring chain "" @s`
>    keyctl restrict_keyring $chain_id asymmetric key_or_keyring:$root_id:chain
>
>    # Attempt to add each certificate in the chain, starting with the
>    # certificate closest to the root.
>    keyctl padd asymmetric "" $chain_id < intermediateA.cert
>    keyctl padd asymmetric "" $chain_id < intermediateB.cert
>    keyctl padd asymmetric "" $chain_id < end-entity.cert
>    ```
>
>    If the final end-entity certificate is successfully added to the "chain" keyring, we can be certain that it has a valid signing chain going back to one of the root certificates.
>
>    A single keyring can be used to verify a chain of signatures by restricting the keyring after linking the root certificate:
>
>
>
>    ```text
>    # Create a keyring for the certificate chain and add the root
>    chain2_id=`keyctl add keyring chain2 "" @s`
>    keyctl padd asymmetric "" $chain2_id < root1.cert
>
>    # Restrict the keyring that already has root1.cert linked.  The cert
>    # will remain linked by the keyring.
>    keyctl restrict_keyring $chain2_id asymmetric key_or_keyring:0:chain
>
>    # Attempt to add each certificate in the chain, starting with the
>    # certificate closest to the root.
>    keyctl padd asymmetric "" $chain2_id < intermediateA.cert
>    keyctl padd asymmetric "" $chain2_id < intermediateB.cert
>    keyctl padd asymmetric "" $chain2_id < end-entity.cert
>    ```
>
>    If the final end-entity certificate is successfully added to the "chain2" keyring, we can be certain that there is a valid signing chain going back to the root certificate that was added before the keyring was restricted.

In all of these cases, if the signing key is found the signature of the key to be linked will be verified using the signing key.  The requested key is added to the keyring only if the signature is successfully verified.  -ENOKEY is returned if the parent certificate could not be found, or -EKEYREJECTED is returned if the signature check fails or the key is blacklisted.  Other errors may be returned if the signature check could not be performed.

---

# Asynchronous Transfers/Transforms API

_Peios Kernel / Internals / Crypto_

> The async_tx API provides methods for describing a chain of asynchronous bulk memory transfers/transforms with support for inter-transactional dependencies. It is implemented as a dmaengine client that smooths over the details of different…

<a id="rst-asynchronous-transfers-transforms-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents

1. INTRODUCTION

2 GENEALOGY

3 USAGE
3.1 General format of the API
3.2 Supported operations
3.3 Descriptor management
3.4 When does the operation execute?
3.5 When does the operation complete?
3.6 Constraints
3.7 Example

4 DMAENGINE DRIVER DEVELOPER NOTES
4.1 Conformance points
4.2 "My application needs exclusive control of hardware channels"

5 SOURCE -->

<a id="rst-introduction"></a>

## 1. Introduction

The async_tx API provides methods for describing a chain of asynchronous bulk memory transfers/transforms with support for inter-transactional dependencies.  It is implemented as a dmaengine client that smooths over the details of different hardware offload engine implementations.  Code that is written to the API can optimize for asynchronous operation and the API will fit the chain of operations to the available offload resources.

<a id="rst-genealogy"></a>

## 2.Genealogy

The API was initially designed to offload the memory copy and xor-parity-calculations of the md-raid5 driver using the offload engines present in the Intel(R) Xscale series of I/O processors.  It also built on the 'dmaengine' layer developed for offloading memory copies in the network stack using Intel(R) I/OAT engines.  The following design features surfaced as a result:

1. implicit synchronous path: users of the API do not need to know if the platform they are running on has offload capabilities.  The operation will be offloaded when an engine is available and carried out in software otherwise.

2. cross channel dependency chains: the API allows a chain of dependent operations to be submitted, like xor-&gt;copy-&gt;xor in the raid5 case.  The API automatically handles cases where the transition from one operation to another implies a hardware channel switch.

3. dmaengine extensions to support multiple clients and operation types beyond 'memcpy'

<a id="rst-usage"></a>

## 3. Usage

<a id="rst-general-format-of-the-api"></a>

### 3.1 General format of the API



```text
struct dma_async_tx_descriptor *
async_<operation>(<op specific parameters>, struct async_submit_ctl *submit)
```

<a id="rst-supported-operations"></a>

### 3.2 Supported operations


<table>
<tbody>
<tr>
<td>


memcpy

</td>
<td>


memory copy between a source and a destination buffer

</td>
</tr>
<tr>
<td>


memset

</td>
<td>


fill a destination buffer with a byte value

</td>
</tr>
<tr>
<td>


xor

</td>
<td>


xor a series of source buffers and write the result to a destination buffer

</td>
</tr>
<tr>
<td>


xor_val

</td>
<td>


xor a series of source buffers and set a flag if the result is zero.  The implementation attempts to prevent writes to memory

</td>
</tr>
<tr>
<td>


pq

</td>
<td>


generate the p+q (raid6 syndrome) from a series of source buffers

</td>
</tr>
<tr>
<td>


pq_val

</td>
<td>


validate that a p and or q buffer are in sync with a given series of sources

</td>
</tr>
<tr>
<td>


datap

</td>
<td>


(raid6_datap_recov) recover a raid6 data block and the p block from the given sources

</td>
</tr>
<tr>
<td>


2data

</td>
<td>


(raid6_2data_recov) recover 2 raid6 data blocks from the given sources

</td>
</tr>
</tbody>
</table>

<a id="rst-descriptor-management"></a>

### 3.3 Descriptor management

The return value is non-NULL and points to a 'descriptor' when the operation has been queued to execute asynchronously.  Descriptors are recycled resources, under control of the offload engine driver, to be reused as operations complete.  When an application needs to submit a chain of operations it must guarantee that the descriptor is not automatically recycled before the dependency is submitted.  This requires that all descriptors be acknowledged by the application before the offload engine driver is allowed to recycle (or free) the descriptor.  A descriptor can be acked by one of the following methods:

1. setting the ASYNC_TX_ACK flag if no child operations are to be submitted

2. submitting an unacknowledged descriptor as a dependency to another async_tx call will implicitly set the acknowledged state.

3. calling async_tx_ack() on the descriptor.

<a id="rst-when-does-the-operation-execute"></a>

### 3.4 When does the operation execute?

Operations do not immediately issue after return from the async\_&lt;operation&gt; call.  Offload engine drivers batch operations to improve performance by reducing the number of mmio cycles needed to manage the channel.  Once a driver-specific threshold is met the driver automatically issues pending operations.  An application can force this event by calling async_tx_issue_pending_all().  This operates on all channels since the application has no knowledge of channel to operation mapping.

<a id="rst-when-does-the-operation-complete"></a>

### 3.5 When does the operation complete?

There are two methods for an application to learn about the completion of an operation.

1. Call dma_wait_for_async_tx().  This call causes the CPU to spin while it polls for the completion of the operation.  It handles dependency chains and issuing pending operations.

2. Specify a completion callback.  The callback routine runs in tasklet context if the offload engine driver supports interrupts, or it is called in application context if the operation is carried out synchronously in software.  The callback can be set in the call to async\_&lt;operation&gt;, or when the application needs to submit a chain of unknown length it can use the async_trigger_callback() routine to set a completion interrupt/callback at the end of the chain.

<a id="rst-constraints"></a>

### 3.6 Constraints

1. Calls to async\_&lt;operation&gt; are not permitted in IRQ context.  Other contexts are permitted provided constraint \#2 is not violated.

2. Completion callback routines cannot submit new operations.  This results in recursion in the synchronous case and spin_locks being acquired twice in the asynchronous case.

<a id="rst-example"></a>

### 3.7 Example

Perform a xor-&gt;copy-&gt;xor operation where each operation depends on the result from the previous operation:



```text
#include <linux/async_tx.h>

static void callback(void *param)
{
        complete(param);
}

#define NDISKS  2

static void run_xor_copy_xor(struct page **xor_srcs,
                             struct page *xor_dest,
                             size_t xor_len,
                             struct page *copy_src,
                             struct page *copy_dest,
                             size_t copy_len)
{
        struct dma_async_tx_descriptor *tx;
        struct async_submit_ctl submit;
        addr_conv_t addr_conv[NDISKS];
        struct completion cmp;

        init_async_submit(&submit, ASYNC_TX_XOR_DROP_DST, NULL, NULL, NULL,
                        addr_conv);
        tx = async_xor(xor_dest, xor_srcs, 0, NDISKS, xor_len, &submit);

        submit.depend_tx = tx;
        tx = async_memcpy(copy_dest, copy_src, 0, 0, copy_len, &submit);

        init_completion(&cmp);
        init_async_submit(&submit, ASYNC_TX_XOR_DROP_DST | ASYNC_TX_ACK, tx,
                        callback, &cmp, addr_conv);
        tx = async_xor(xor_dest, xor_srcs, 0, NDISKS, xor_len, &submit);

        async_tx_issue_pending_all();

        wait_for_completion(&cmp);
}
```

See include/linux/async_tx.h for more information on the flags.  See the ops_run\_\* and ops_complete\_\* routines in drivers/md/raid5.c for more implementation examples.

<a id="rst-driver-development-notes"></a>

## 4. Driver Development Notes

<a id="rst-conformance-points"></a>

### 4.1 Conformance points

There are a few conformance points required in dmaengine drivers to accommodate assumptions made by applications using the async_tx API:

1. Completion callbacks are expected to happen in tasklet context

2. dma_async_tx_descriptor fields are never manipulated in IRQ context

3. Use async_tx_run_dependencies() in the descriptor clean up path to handle submission of dependent operations

<a id="rst-my-application-needs-exclusive-control-of-hardware-channels"></a>

### 4.2 "My application needs exclusive control of hardware channels"

Primarily this requirement arises from cases where a DMA engine driver is being used to support device-to-memory operations.  A channel that is performing these operations cannot, for many platform specific reasons, be shared.  For these cases the dma_request_channel() interface is provided.

The interface is:



```text
struct dma_chan *dma_request_channel(dma_cap_mask_t mask,
                                     dma_filter_fn filter_fn,
                                     void *filter_param);
```

Where dma_filter_fn is defined as:



```text
typedef bool (*dma_filter_fn)(struct dma_chan *chan, void *filter_param);
```

When the optional 'filter_fn' parameter is set to NULL dma_request_channel simply returns the first channel that satisfies the capability mask.  Otherwise, when the mask parameter is insufficient for specifying the necessary channel, the filter_fn routine can be used to disposition the available channels in the system. The filter_fn routine is called once for each free channel in the system.  Upon seeing a suitable channel filter_fn returns DMA_ACK which flags that channel to be the return value from dma_request_channel.  A channel allocated via this interface is exclusive to the caller, until dma_release_channel() is called.

The DMA_PRIVATE capability flag is used to tag dma devices that should not be used by the general-purpose allocator.  It can be set at initialization time if it is known that a channel will always be private.  Alternatively, it is set when dma_request_channel() finds an unused "public" channel.

A couple caveats to note when implementing a driver and consumer:

1. Once a channel has been privately allocated it will no longer be considered by the general-purpose allocator even after a call to dma_release_channel().

2. Since capabilities are specified at the device level a dma_device with multiple channels will either have all channels public, or all channels private.

<a id="rst-source"></a>

### 5. Source

- **include/linux/dmaengine.h:**

  core header file for DMA drivers and api users

- **drivers/dma/dmaengine.c:**

  offload engine channel management routines

- **drivers/dma/:**

  location for offload engine drivers

- **include/linux/async_tx.h:**

  core header file for the async_tx api

- **crypto/async_tx/async_tx.c:**

  async_tx interface to dmaengine and common code

- **crypto/async_tx/async_memcpy.c:**

  copy offload

- **crypto/async_tx/async_xor.c:**

  xor and xor zero sum offload

---

# Crypto Engine

_Peios Kernel / Internals / Crypto_

> The crypto engine (CE) API is a crypto queue manager.

<a id="rst-crypto-engine"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

The crypto engine (CE) API is a crypto queue manager.

<a id="rst-requirement"></a>

## Requirement

You must put, at the start of your transform context your_tfm_ctx, the structure crypto_engine:



```text
struct your_tfm_ctx {
        struct crypto_engine engine;
        ...
};
```

The crypto engine only manages asynchronous requests in the form of crypto_async_request. It cannot know the underlying request type and thus only has access to the transform structure. It is not possible to access the context using container_of. In addition, the engine knows nothing about your structure "`struct your_tfm_ctx`". The engine assumes (requires) the placement of the known member `struct crypto_engine` at the beginning.

<a id="rst-order-of-operations"></a>

## Order of operations

You are required to obtain a struct crypto_engine via `crypto_engine_alloc_init()`. Start it via `crypto_engine_start()`. When finished with your work, shut down the engine using `crypto_engine_stop()` and destroy the engine with `crypto_engine_exit()`.

Before transferring any request, you have to fill the context enginectx by providing functions for the following:

- `prepare_cipher_request`/`prepare_hash_request`: Called before each corresponding request is performed. If some processing or other preparatory work is required, do it here.

- `unprepare_cipher_request`/`unprepare_hash_request`: Called after each request is handled. Clean up / undo what was done in the prepare function.

- `cipher_one_request`/`hash_one_request`: Handle the current request by performing the operation.

Note that these functions access the crypto_async_request structure associated with the received request. You are able to retrieve the original request by using:



```text
container_of(areq, struct yourrequesttype_request, base);
```

When your driver receives a crypto_request, you must to transfer it to the crypto engine via one of:

- crypto_transfer_aead_request_to_engine()

- crypto_transfer_akcipher_request_to_engine()

- crypto_transfer_hash_request_to_engine()

- crypto_transfer_kpp_request_to_engine()

- crypto_transfer_skcipher_request_to_engine()

At the end of the request process, a call to one of the following functions is needed:

- crypto_finalize_aead_request()

- crypto_finalize_akcipher_request()

- crypto_finalize_hash_request()

- crypto_finalize_kpp_request()

- crypto_finalize_skcipher_request()

---

# Fast & Portable DES encryption & decryption

_Peios Kernel / Internals / Crypto_

> des - fast & portable DES encryption & decryption.

<a id="rst-fast-portable-des-encryption-decryption"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- This data file has been placed in the public domain. -->

<!-- Derived from the Unicode character mappings available from
<http://www.w3.org/2003/entities/xml/>.
Processed by unicode2rstsubs.py, part of Docutils:
<https://docutils.sourceforge.io>. -->

> [!NOTE]
>
> Below is the original README file from the descore.shar package, converted to ReST format.

---

des - fast &amp; portable DES encryption &amp; decryption.

Copyright © 1992  Dana L. How

This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details.

You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Author's address: [how@isl.stanford.edu](<mailto:how@isl.stanford.edu>)

<!-- README,v 1.15 1992/05/20 00:25:32 how E -->

==&gt;&gt; To compile after untarring/unsharring, just `make` &lt;&lt;==

This package was designed with the following goals:

1. Highest possible encryption/decryption PERFORMANCE.

2. PORTABILITY to any byte-addressable host with a 32bit unsigned C type

3. Plug-compatible replacement for KERBEROS's low-level routines.

This second release includes a number of performance enhancements for register-starved machines.  My discussions with Richard Outerbridge, [71755.204@compuserve.com](<mailto:71755.204@compuserve.com>), sparked a number of these enhancements.

To more rapidly understand the code in this package, inspect desSmallFips.i (created by typing `make`) BEFORE you tackle desCode.h.  The latter is set up in a parameterized fashion so it can easily be modified by speed-daemon hackers in pursuit of that last microsecond.  You will find it more illuminating to inspect one specific implementation, and then move on to the common abstract skeleton with this one in mind.

performance comparison to other available des code which i could compile on a SPARCStation 1 (cc -O4, gcc -O2):

this code (byte-order independent):

> - 30us per encryption (options: 64k tables, no IP/FP)
>
> - 33us per encryption (options: 64k tables, FIPS standard bit ordering)
>
> - 45us per encryption (options:  2k tables, no IP/FP)
>
> - 48us per encryption (options:  2k tables, FIPS standard bit ordering)
>
> - 275us to set a new key (uses 1k of key tables)
>
>   > this has the quickest encryption/decryption routines i've seen. since i was interested in fast des filters rather than crypt(3) and password cracking, i haven't really bothered yet to speed up the key setting routine. also, i have no interest in re-implementing all the other junk in the mit kerberos des library, so i've just provided my routines with little stub interfaces so they can be used as drop-in replacements with mit's code or any of the mit- compatible packages below. (note that the first two timings above are highly variable because of cache effects).

kerberos des replacement from australia (version 1.95):

> - 53us per encryption (uses 2k of tables)
>
> - 96us to set a new key (uses 2.25k of key tables)
>
>   > so despite the author's inclusion of some of the performance improvements i had suggested to him, this package's encryption/decryption is still slower on the sparc and 68000. more specifically, 19-40% slower on the 68020 and 11-35% slower on the sparc,  depending on the compiler; in full gory detail (ALT_ECB is a libdes variant):
>   >
>   >
>   > <table>
>   > <thead>
>   > <tr>
>   > <th>
>   >
>   >
>   > compiler
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > machine
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > desCore libdes
>   >
>   > </th>
>   > <th>
>   >
>   >
>   > ALT_ECB slower by
>   >
>   > </th>
>   > </tr>
>   > </thead>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > gcc 2.1 -O2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 3/110
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 304  uS 369.5uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 461.8uS  22%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > cc      -O1
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 3/110
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 336  uS 436.6uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 399.3uS  19%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > cc      -O2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 3/110
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 360  uS 532.4uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 505.1uS  40%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > cc      -O4
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 3/110
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 365  uS 532.3uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 505.3uS  38%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > gcc 2.1 -O2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 4/50
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 48  uS  53.4uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 57.5uS  11%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > cc      -O2
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 4/50
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 48  uS  64.6uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 64.7uS  35%
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > cc      -O4
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Sun 4/50
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 48  uS  64.7uS
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > 64.9uS  35%
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>
>   >
>   > (my time measurements are not as accurate as his).
>
> > the comments in my first release of desCore on version 1.92:
> >
> > - 68us per encryption (uses 2k of tables)
> >
> > - 96us to set a new key (uses 2.25k of key tables)
> >
> >   > this is a very nice package which implements the most important of the optimizations which i did in my encryption routines. it's a bit weak on common low-level optimizations which is why it's 39%-106% slower.  because he was interested in fast crypt(3) and password-cracking applications,  he also used the same ideas to speed up the key-setting routines with impressive results. (at some point i may do the same in my package).  he also implements the rest of the mit des library.
> >   >
> >   > (code from [eay@psych.psy.uq.oz.au](<mailto:eay@psych.psy.uq.oz.au>) via comp.sources.misc)

fast crypt(3) package from denmark:

> the des routine here is buried inside a loop to do the crypt function and i didn't feel like ripping it out and measuring performance. his code takes 26 sparc instructions to compute one des iteration; above, Quick (64k) takes 21 and Small (2k) takes 37. he claims to use 280k of tables but the iteration calculation seems to use only 128k.  his tables and code are machine independent.
>
> (code from [glad@daimi.aau.dk](<mailto:glad@daimi.aau.dk>) via alt.sources or comp.sources.misc)

swedish reimplementation of Kerberos des library

> - 108us per encryption (uses 34k worth of tables)
>
> - 134us to set a new key (uses 32k of key tables to get this speed\!)
>
>   > the tables used seem to be machine-independent; he seems to have included a lot of special case code so that, e.g., `long` loads can be used instead of 4 `char` loads when the machine's architecture allows it.
>   >
>   > (code obtained from chalmers.se:pub/des)

crack 3.3c package from england:

> as in crypt above, the des routine is buried in a loop. it's also very modified for crypt.  his iteration code uses 16k of tables and appears to be slow.
>
> (code obtained from [aem@aber.ac.uk](<mailto:aem@aber.ac.uk>) via alt.sources or comp.sources.misc)

`highly optimized` and tweaked Kerberos/Athena code (byte-order dependent):

> - 165us per encryption (uses 6k worth of tables)
>
> - 478us to set a new key (uses &lt;1k of key tables)
>
>   > so despite the comments in this code, it was possible to get faster code AND smaller tables, as well as making the tables machine-independent. (code obtained from prep.ai.mit.edu)

- **UC Berkeley code (depends on machine-endedness):**

  - 226us per encryption

  - 10848us to set a new key

    > table sizes are unclear, but they don't look very small (code obtained from wuarchive.wustl.edu)

<a id="rst-motivation-and-history"></a>

## motivation and history

a while ago i wanted some des routines and the routines documented on sun's man pages either didn't exist or dumped core.  i had heard of kerberos, and knew that it used des,  so i figured i'd use its routines.  but once i got it and looked at the code,  it really set off a lot of pet peeves - it was too convoluted, the code had been written without taking advantage of the regular structure of operations such as IP, E, and FP (i.e. the author didn't sit down and think before coding), it was excessively slow,  the author had attempted to clarify the code by adding MORE statements to make the data movement more `consistent` instead of simplifying his implementation and cutting down on all data movement (in particular, his use of L1, R1, L2, R2), and it was full of idiotic `tweaks` for particular machines which failed to deliver significant speedups but which did obfuscate everything.  so i took the test data from his verification program and rewrote everything else.

a while later i ran across the great crypt(3) package mentioned above. the fact that this guy was computing 2 sboxes per table lookup rather than one (and using a MUCH larger table in the process) emboldened me to do the same - it was a trivial change from which i had been scared away by the larger table size.  in his case he didn't realize you don't need to keep the working data in TWO forms, one for easy use of half the sboxes in indexing, the other for easy use of the other half; instead you can keep it in the form for the first half and use a simple rotate to get the other half.  this means i have (almost) half the data manipulation and half the table size.  in fairness though he might be encoding something particular to crypt(3) in his tables - i didn't check.

i'm glad that i implemented it the way i did, because this C version is portable (the ifdef's are performance enhancements) and it is faster than versions hand-written in assembly for the sparc\!

<a id="rst-porting-notes"></a>

## porting notes

one thing i did not want to do was write an enormous mess which depended on endedness and other machine quirks, and which necessarily produced different code and different lookup tables for different machines.  see the kerberos code for an example of what i didn't want to do; all their endedness-specific `optimizations` obfuscate the code and in the end were slower than a simpler machine independent approach.  however, there are always some portability considerations of some kind, and i have included some options for varying numbers of register variables. perhaps some will still regard the result as a mess\!

1. i assume everything is byte addressable, although i don't actually depend on the byte order, and that bytes are 8 bits. i assume word pointers can be freely cast to and from char pointers. note that 99% of C programs make these assumptions. i always use unsigned char's if the high bit could be set.

2. the typedef `word` means a 32 bit unsigned integral type. if `unsigned long` is not 32 bits, change the typedef in desCore.h. i assume sizeof(word) == 4 EVERYWHERE.

the (worst-case) cost of my NOT doing endedness-specific optimizations in the data loading and storing code surrounding the key iterations is less than 12%.  also, there is the added benefit that the input and output work areas do not need to be word-aligned.

<a id="rst-optional-performance-optimizations"></a>

## OPTIONAL performance optimizations

1. you should define one of `i386,` `vax,` `mc68000,` or `sparc,` whichever one is closest to the capabilities of your machine. see the start of desCode.h to see exactly what this selection implies. note that if you select the wrong one, the des code will still work; these are just performance tweaks.

2. for those with functional `asm` keywords: you should change the ROR and ROL macros to use machine rotate instructions if you have them. this will save 2 instructions and a temporary per use, or about 32 to 40 instructions per en/decryption.

   note that gcc is smart enough to translate the ROL/R macros into machine rotates\!

these optimizations are all rather persnickety, yet with them you should be able to get performance equal to assembly-coding, except that:

1. with the lack of a bit rotate operator in C, rotates have to be synthesized from shifts.  so access to `asm` will speed things up if your machine has rotates, as explained above in (3) (not necessary if you use gcc).

2. if your machine has less than 12 32-bit registers i doubt your compiler will generate good code.

   `i386` tries to configure the code for a 386 by only declaring 3 registers (it appears that gcc can use ebx, esi and edi to hold register variables). however, if you like assembly coding, the 386 does have 7 32-bit registers, and if you use ALL of them, use `scaled by 8` address modes with displacement and other tricks, you can get reasonable routines for DesQuickCore... with about 250 instructions apiece.  For DesSmall... it will help to rearrange des_keymap, i.e., now the sbox \# is the high part of the index and the 6 bits of data is the low part; it helps to exchange these.

   since i have no way to conveniently test it i have not provided my shoehorned 386 version.  note that with this release of desCore, gcc is able to put everything in registers(\!), and generate about 370 instructions apiece for the DesQuickCore... routines\!

<a id="rst-coding-notes"></a>

## coding notes

the en/decryption routines each use 6 necessary register variables, with 4 being actively used at once during the inner iterations. if you don't have 4 register variables get a new machine. up to 8 more registers are used to hold constants in some configurations.

i assume that the use of a constant is more expensive than using a register:

- **a)** additionally, i have tried to put the larger constants in registers. registering priority was by the following:

  > - anything more than 12 bits (bad for RISC and CISC)
  >
  > - greater than 127 in value (can't use movq or byte immediate on CISC)
  >
  > - 9-127 (may not be able to use CISC shift immediate or add/sub quick),
  >
  > - 1-8 were never registered, being the cheapest constants.

- **b)** the compiler may be too stupid to realize table and table+256 should be assigned to different constant registers and instead repetitively do the arithmetic, so i assign these to explicit `m` register variables when possible and helpful.

i assume that indexing is cheaper or equivalent to auto increment/decrement, where the index is 7 bits unsigned or smaller. this assumption is reversed for 68k and vax.

i assume that addresses can be cheaply formed from two registers, or from a register and a small constant. for the 68000, the `two registers and small offset` form is used sparingly. all index scaling is done explicitly - no hidden shifts by log2(sizeof).

the code is written so that even a dumb compiler should never need more than one hidden temporary, increasing the chance that everything will fit in the registers. KEEP THIS MORE SUBTLE POINT IN MIND IF YOU REWRITE ANYTHING.

(actually, there are some code fragments now which do require two temps, but fixing it would either break the structure of the macros or require declaring another temporary).

<a id="rst-special-efficient-data-format"></a>

## special efficient data format

bits are manipulated in this arrangement most of the time (S7 S5 S3 S1):



```text
003130292827xxxx242322212019xxxx161514131211xxxx080706050403xxxx
```

(the x bits are still there, i'm just emphasizing where the S boxes are). bits are rotated left 4 when computing S6 S4 S2 S0:



```text
282726252423xxxx201918171615xxxx121110090807xxxx040302010031xxxx
```

the rightmost two bits are usually cleared so the lower byte can be used as an index into an sbox mapping table. the next two x'd bits are set to various values to access different parts of the tables.

how to use the routines

- **datatypes:**

  pointer to 8 byte area of type DesData used to hold keys and input/output blocks to des.

  pointer to 128 byte area of type DesKeys used to hold full 768-bit key. must be long-aligned.

- **DesQuickInit()**

  call this before using any other routine with `Quick` in its name. it generates the special 64k table these routines need.

- **DesQuickDone()**

  frees this table

- **DesMethod(m, k)**

  m points to a 128byte block, k points to an 8 byte des key which must have odd parity (or -1 is returned) and which must not be a (semi-)weak key (or -2 is returned). normally DesMethod() returns 0.

  m is filled in from k so that when one of the routines below is called with m, the routine will act like standard des en/decryption with the key k. if you use DesMethod, you supply a standard 56bit key; however, if you fill in m yourself, you will get a 768bit key - but then it won't be standard.  it's 768bits not 1024 because the least significant two bits of each byte are not used.  note that these two bits will be set to magic constants which speed up the encryption/decryption on some machines.  and yes, each byte controls a specific sbox during a specific iteration.

  you really shouldn't use the 768bit format directly;  i should provide a routine that converts 128 6-bit bytes (specified in S-box mapping order or something) into the right format for you. this would entail some byte concatenation and rotation.

- **Des\{Small\|Quick\}\{Fips\|Core\}\{Encrypt\|Decrypt\}(d, m, s)**

  performs des on the 8 bytes at s into the 8 bytes at `d. (d,s: char *)`.

  uses m as a 768bit key as explained above.

  the Encrypt\|Decrypt choice is obvious.

  Fips\|Core determines whether a completely standard FIPS initial and final permutation is done; if not, then the data is loaded and stored in a nonstandard bit order (FIPS w/o IP/FP).

  Fips slows down Quick by 10%, Small by 9%.

  Small\|Quick determines whether you use the normal routine or the crazy quick one which gobbles up 64k more of memory. Small is 50% slower then Quick, but Quick needs 32 times as much memory.  Quick is included for programs that do nothing but DES, e.g., encryption filters, etc.

<a id="rst-getting-it-to-compile-on-your-machine"></a>

## Getting it to compile on your machine

there are no machine-dependencies in the code (see porting), except perhaps the `now()` macro in desTest.c. ALL generated tables are machine independent. you should edit the Makefile with the appropriate optimization flags for your compiler (MAX optimization).

<a id="rst-speeding-up-kerberos-and-or-its-des-library"></a>

## Speeding up kerberos (and/or its des library)

note that i have included a kerberos-compatible interface in desUtil.c through the functions des_key_sched() and des_ecb_encrypt(). to use these with kerberos or kerberos-compatible code put desCore.a ahead of the kerberos-compatible library on your linker's command line. you should not need to \#include desCore.h;  just include the header file provided with the kerberos library.

<a id="rst-other-uses"></a>

## Other uses

the macros in desCode.h would be very useful for putting inline des functions in more complicated encryption routines.

---

# Developing Cipher Algorithms

_Peios Kernel / Internals / Crypto_

> There are three distinct types of registration functions in the Crypto API. One is used to register a generic cryptographic transformation, while the other two are specific to HASH transformations and COMPRESSion. We will discuss the…

<a id="rst-developing-cipher-algorithms"></a>

<a id="rst-registering-and-unregistering-transformation"></a>

## Registering And Unregistering Transformation

There are three distinct types of registration functions in the Crypto API. One is used to register a generic cryptographic transformation, while the other two are specific to HASH transformations and COMPRESSion. We will discuss the latter two in a separate chapter, here we will only look at the generic ones.

Before discussing the register functions, the data structure to be filled with each, struct crypto_alg, must be considered -- see below for a description of this data structure.

The generic registration functions can be found in include/linux/crypto.h and their definition can be seen below. The former function registers a single transformation, while the latter works on an array of transformation descriptions. The latter is useful when registering transformations in bulk, for example when a driver implements multiple transformations.



```text
int crypto_register_alg(struct crypto_alg *alg);
int crypto_register_algs(struct crypto_alg *algs, int count);
```

The counterparts to those functions are listed below.



```text
void crypto_unregister_alg(struct crypto_alg *alg);
void crypto_unregister_algs(struct crypto_alg *algs, int count);
```

The registration functions return 0 on success, or a negative errno value on failure.  crypto_register_algs() succeeds only if it successfully registered all the given algorithms; if it fails partway through, then any changes are rolled back.

The unregistration functions always succeed, so they don't have a return value.  Don't try to unregister algorithms that aren't currently registered.

<a id="rst-single-block-symmetric-ciphers-cipher"></a>

## Single-Block Symmetric Ciphers \[CIPHER\]

Example of transformations: aes, serpent, ...

This section describes the simplest of all transformation implementations, that being the CIPHER type used for symmetric ciphers. The CIPHER type is used for transformations which operate on exactly one block at a time and there are no dependencies between blocks at all.

<a id="rst-registration-specifics"></a>

### Registration specifics

The registration of \[CIPHER\] algorithm is specific in that struct crypto_alg field .cra_type is empty. The .cra_u.cipher has to be filled in with proper callbacks to implement this transformation.

See struct cipher_alg below.

<a id="rst-cipher-definition-with-struct-cipher-alg"></a>

### Cipher Definition With struct cipher_alg

Struct cipher_alg defines a single block cipher.

Here are schematics of how these functions are called when operated from other part of the kernel. Note that the .cia_setkey() call might happen before or after any of these schematics happen, but must not happen during any of these are in-flight.



```text
KEY ---.    PLAINTEXT ---.
       v                 v
 .cia_setkey() -> .cia_encrypt()
                         |
                         '-----> CIPHERTEXT
```

Please note that a pattern where .cia_setkey() is called multiple times is also valid:



```text
KEY1 --.    PLAINTEXT1 --.         KEY2 --.    PLAINTEXT2 --.
       v                 v                v                 v
 .cia_setkey() -> .cia_encrypt() -> .cia_setkey() -> .cia_encrypt()
                         |                                  |
                         '---> CIPHERTEXT1                  '---> CIPHERTEXT2
```

<a id="rst-multi-block-ciphers"></a>

## Multi-Block Ciphers

Example of transformations: cbc(aes), chacha20, ...

This section describes the multi-block cipher transformation implementations. The multi-block ciphers are used for transformations which operate on scatterlists of data supplied to the transformation functions. They output the result into a scatterlist of data as well.

<a id="rst-registration-specifics-1"></a>

### Registration Specifics

The registration of multi-block cipher algorithms is one of the most standard procedures throughout the crypto API.

Note, if a cipher implementation requires a proper alignment of data, the caller should use the functions of crypto_skcipher_alignmask() to identify a memory alignment mask. The kernel crypto API is able to process requests that are unaligned. This implies, however, additional overhead as the kernel crypto API needs to perform the realignment of the data which may imply moving of data.

<a id="rst-cipher-definition-with-struct-skcipher-alg"></a>

### Cipher Definition With struct skcipher_alg

Struct skcipher_alg defines a multi-block cipher, or more generally, a length-preserving symmetric cipher algorithm.

<a id="rst-scatterlist-handling"></a>

### Scatterlist handling

Some drivers will want to use the Generic ScatterWalk in case the hardware needs to be fed separate chunks of the scatterlist which contains the plaintext and will contain the ciphertext. Please refer to the ScatterWalk interface offered by the Linux kernel scatter / gather list implementation.

<a id="rst-hashing-hash"></a>

## Hashing \[HASH\]

Example of transformations: crc32, md5, sha1, sha256,...

<a id="rst-registering-and-unregistering-the-transformation"></a>

### Registering And Unregistering The Transformation

There are multiple ways to register a HASH transformation, depending on whether the transformation is synchronous \[SHASH\] or asynchronous \[AHASH\] and the amount of HASH transformations we are registering. You can find the prototypes defined in include/crypto/internal/hash.h:



```text
int crypto_register_ahash(struct ahash_alg *alg);

int crypto_register_shash(struct shash_alg *alg);
int crypto_register_shashes(struct shash_alg *algs, int count);
```

The respective counterparts for unregistering the HASH transformation are as follows:



```text
void crypto_unregister_ahash(struct ahash_alg *alg);

void crypto_unregister_shash(struct shash_alg *alg);
void crypto_unregister_shashes(struct shash_alg *algs, int count);
```

<a id="rst-cipher-definition-with-struct-shash-alg-and-ahash-alg"></a>

### Cipher Definition With struct shash_alg and ahash_alg

Here are schematics of how these functions are called when operated from other part of the kernel. Note that the .setkey() call might happen before or after any of these schematics happen, but must not happen during any of these are in-flight. Please note that calling .init() followed immediately by .final() is also a perfectly valid transformation.



```text
I)   DATA -----------.
                     v
      .init() -> .update() -> .final()      ! .update() might not be called
                  ^    |         |            at all in this scenario.
                  '----'         '---> HASH

II)  DATA -----------.-----------.
                     v           v
      .init() -> .update() -> .finup()      ! .update() may not be called
                  ^    |         |            at all in this scenario.
                  '----'         '---> HASH

III) DATA -----------.
                     v
                 .digest()                  ! The entire process is handled
                     |                        by the .digest() call.
                     '---------------> HASH
```

Here is a schematic of how the .export()/.import() functions are called when used from another part of the kernel.



```text
KEY--.                 DATA--.
     v                       v                  ! .update() may not be called
 .setkey() -> .init() -> .update() -> .export()   at all in this scenario.
                          ^     |         |
                          '-----'         '--> PARTIAL_HASH

----------- other transformations happen here -----------

PARTIAL_HASH--.   DATA1--.
              v          v
          .import -> .update() -> .final()     ! .update() may not be called
                      ^    |         |           at all in this scenario.
                      '----'         '--> HASH1

PARTIAL_HASH--.   DATA2-.
              v         v
          .import -> .finup()
                        |
                        '---------------> HASH2
```

Note that it is perfectly legal to "abandon" a request object: - call .init() and then (as many times) .update() - \_not\_ call any of .final(), .finup() or .export() at any point in future

In other words implementations should mind the resource allocation and clean-up. No resources related to request objects should remain allocated after a call to .init() or .update(), since there might be no chance to free them.

<a id="rst-specifics-of-asynchronous-hash-transformation"></a>

### Specifics Of Asynchronous HASH Transformation

Some of the drivers will want to use the Generic ScatterWalk in case the implementation needs to be fed separate chunks of the scatterlist which contains the input data.

---

# Kernel Crypto API Interface Specification

_Peios Kernel / Internals / Crypto_

> The kernel crypto API offers a rich set of cryptographic ciphers as well as other data transformation mechanisms and methods to invoke these. This document contains a description of the API and provides example code.

<a id="rst-kernel-crypto-api-interface-specification"></a>

<a id="rst-introduction"></a>

## Introduction

The kernel crypto API offers a rich set of cryptographic ciphers as well as other data transformation mechanisms and methods to invoke these. This document contains a description of the API and provides example code.

To understand and properly use the kernel crypto API a brief explanation of its structure is given. Based on the architecture, the API can be separated into different components. Following the architecture specification, hints to developers of ciphers are provided. Pointers to the API function call documentation are given at the end.

The kernel crypto API refers to all algorithms as "transformations". Therefore, a cipher handle variable usually has the name "tfm". Besides cryptographic operations, the kernel crypto API also knows compression transformations and handles them the same way as ciphers.

The kernel crypto API serves the following entity types:

- consumers requesting cryptographic services

- data transformation implementations (typically ciphers) that can be called by consumers using the kernel crypto API

This specification is intended for consumers of the kernel crypto API as well as for developers implementing ciphers. This API specification, however, does not discuss all API calls available to data transformation implementations (i.e. implementations of ciphers and other transformations (such as CRC or even compression algorithms) that can register with the kernel crypto API).

Note: The terms "transformation" and cipher algorithm are used interchangeably.

<a id="rst-terminology"></a>

## Terminology

The transformation implementation is an actual code or interface to hardware which implements a certain transformation with precisely defined behavior.

The transformation object (TFM) is an instance of a transformation implementation. There can be multiple transformation objects associated with a single transformation implementation. Each of those transformation objects is held by a crypto API consumer or another transformation. Transformation object is allocated when a crypto API consumer requests a transformation implementation. The consumer is then provided with a structure, which contains a transformation object (TFM).

The structure that contains transformation objects may also be referred to as a "cipher handle". Such a cipher handle is always subject to the following phases that are reflected in the API calls applicable to such a cipher handle:

1. Initialization of a cipher handle.

2. Execution of all intended cipher operations applicable for the handle where the cipher handle must be furnished to every API call.

3. Destruction of a cipher handle.

When using the initialization API calls, a cipher handle is created and returned to the consumer. Therefore, please refer to all initialization API calls that refer to the data structure type a consumer is expected to receive and subsequently to use. The initialization API calls have all the same naming conventions of crypto_alloc\*.

The transformation context is private data associated with the transformation object.

---

# Kerberos V Cryptography API

_Peios Kernel / Internals / Crypto_

> This API provides Kerberos 5-style cryptography for key derivation, encryption and checksumming for use in network filesystems and can be used to implement the low-level crypto that's needed for GSSAPI.

<a id="rst-kerberos-v-cryptography-api"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Contents:

- Overview.
  - Small Buffer.
- Encoding Type.
- Key Derivation.
  - PRF+ Calculation.
  - Kc, Ke And Ki Derivation.
- Crypto Functions.
  - Preparation Functions.
  - Encryption Mode.
  - Checksum Mode.
- The krb5enc AEAD algorithm -->

<a id="rst-overview"></a>

## Overview

This API provides Kerberos 5-style cryptography for key derivation, encryption and checksumming for use in network filesystems and can be used to implement the low-level crypto that's needed for GSSAPI.

The following crypto types are supported:



```text
KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96
KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96
KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128
KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192
KRB5_ENCTYPE_CAMELLIA128_CTS_CMAC
KRB5_ENCTYPE_CAMELLIA256_CTS_CMAC

KRB5_CKSUMTYPE_HMAC_SHA1_96_AES128
KRB5_CKSUMTYPE_HMAC_SHA1_96_AES256
KRB5_CKSUMTYPE_CMAC_CAMELLIA128
KRB5_CKSUMTYPE_CMAC_CAMELLIA256
KRB5_CKSUMTYPE_HMAC_SHA256_128_AES128
KRB5_CKSUMTYPE_HMAC_SHA384_192_AES256
```

The API can be included by:



```text
#include <crypto/krb5.h>
```

<a id="rst-small-buffer"></a>

### Small Buffer

To pass small pieces of data about, such as keys, a buffer structure is defined, giving a pointer to the data and the size of that data:



```text
struct krb5_buffer {
        unsigned int    len;
        void            *data;
};
```

<a id="rst-encoding-type"></a>

## Encoding Type

The encoding type is defined by the following structure:



```text
struct krb5_enctype {
        int             etype;
        int             ctype;
        const char      *name;
        u16             key_bytes;
        u16             key_len;
        u16             Kc_len;
        u16             Ke_len;
        u16             Ki_len;
        u16             prf_len;
        u16             block_len;
        u16             conf_len;
        u16             cksum_len;
        ...
};
```

The fields of interest to the user of the API are as follows:

> - `etype` and `ctype` indicate the protocol number for this encoding type for encryption and checksumming respectively.  They hold `KRB5_ENCTYPE_*` and `KRB5_CKSUMTYPE_*` constants.
>
> - `name` is the formal name of the encoding.
>
> - `key_len` and `key_bytes` are the input key length and the derived key length.  (I think they only differ for DES, which isn't supported here).
>
> - `Kc_len`, `Ke_len` and `Ki_len` are the sizes of the derived Kc, Ke and Ki keys.  Kc is used for in checksum mode; Ke and Ki are used in encryption mode.
>
> - `prf_len` is the size of the result from the PRF+ function calculation.
>
> - `block_len`, `conf_len` and `cksum_len` are the encryption block length, confounder length and checksum length respectively.  All three are used in encryption mode, but only the checksum length is used in checksum mode.

The encoding type is looked up by number using the following function:



```text
const struct krb5_enctype *crypto_krb5_find_enctype(u32 enctype);
```

<a id="rst-key-derivation"></a>

## Key Derivation

Once the application has selected an encryption type, the keys that will be used to do the actual crypto can be derived from the transport key.

<a id="rst-prf-calculation"></a>

### PRF+ Calculation

To aid in key derivation, a function to calculate the Kerberos GSSAPI mechanism's PRF+ is provided:



```text
int crypto_krb5_calc_PRFplus(const struct krb5_enctype *krb5,
                             const struct krb5_buffer *K,
                             unsigned int L,
                             const struct krb5_buffer *S,
                             struct krb5_buffer *result,
                             gfp_t gfp);
```

This can be used to derive the transport key from a source key plus additional data to limit its use.

<a id="rst-crypto-functions"></a>

## Crypto Functions

Once the keys have been derived, crypto can be performed on the data.  The caller must leave gaps in the buffer for the storage of the confounder (if needed) and the checksum when preparing a message for transmission.  An enum and a pair of functions are provided to aid in this:



```text
enum krb5_crypto_mode {
        KRB5_CHECKSUM_MODE,
        KRB5_ENCRYPT_MODE,
};

size_t crypto_krb5_how_much_buffer(const struct krb5_enctype *krb5,
                                   enum krb5_crypto_mode mode,
                                   size_t data_size, size_t *_offset);

size_t crypto_krb5_how_much_data(const struct krb5_enctype *krb5,
                                 enum krb5_crypto_mode mode,
                                 size_t *_buffer_size, size_t *_offset);
```

All these functions take the encoding type and an indication the mode of crypto (checksum-only or full encryption).

The first function returns how big the buffer will need to be to house a given amount of data; the second function returns how much data will fit in a buffer of a particular size, and adjusts down the size of the required buffer accordingly.  In both cases, the offset of the data within the buffer is also returned.

When a message has been received, the location and size of the data with the message can be determined by calling:



```text
void crypto_krb5_where_is_the_data(const struct krb5_enctype *krb5,
                                   enum krb5_crypto_mode mode,
                                   size_t *_offset, size_t *_len);
```

The caller provides the offset and length of the message to the function, which then alters those values to indicate the region containing the data (plus any padding).  It is up to the caller to determine how much padding there is.

<a id="rst-preparation-functions"></a>

### Preparation Functions

Two functions are provided to allocated and prepare a crypto object for use by the action functions:



```text
struct crypto_aead *
crypto_krb5_prepare_encryption(const struct krb5_enctype *krb5,
                               const struct krb5_buffer *TK,
                               u32 usage, gfp_t gfp);
struct crypto_shash *
crypto_krb5_prepare_checksum(const struct krb5_enctype *krb5,
                             const struct krb5_buffer *TK,
                             u32 usage, gfp_t gfp);
```

Both of these functions take the encoding type, the transport key and the usage value used to derive the appropriate subkey(s).  They create an appropriate crypto object, an AEAD template for encryption and a synchronous hash for checksumming, set the key(s) on it and configure it.  The caller is expected to pass these handles to the action functions below.

<a id="rst-encryption-mode"></a>

### Encryption Mode

A pair of functions are provided to encrypt and decrypt a message:



```text
ssize_t crypto_krb5_encrypt(const struct krb5_enctype *krb5,
                            struct crypto_aead *aead,
                            struct scatterlist *sg, unsigned int nr_sg,
                            size_t sg_len,
                            size_t data_offset, size_t data_len,
                            bool preconfounded);
int crypto_krb5_decrypt(const struct krb5_enctype *krb5,
                        struct crypto_aead *aead,
                        struct scatterlist *sg, unsigned int nr_sg,
                        size_t *_offset, size_t *_len);
```

In both cases, the input and output buffers are indicated by the same scatterlist.

For the encryption function, the output buffer may be larger than is needed (the amount of output generated is returned) and the location and size of the data are indicated (which must match the encoding).  If no confounder is set, the function will insert one.

For the decryption function, the offset and length of the message in buffer are supplied and these are shrunk to fit the data.  The decryption function will verify any checksums within the message and give an error if they don't match.

<a id="rst-checksum-mode"></a>

### Checksum Mode

A pair of function are provided to generate the checksum on a message and to verify that checksum:



```text
ssize_t crypto_krb5_get_mic(const struct krb5_enctype *krb5,
                            struct crypto_shash *shash,
                            const struct krb5_buffer *metadata,
                            struct scatterlist *sg, unsigned int nr_sg,
                            size_t sg_len,
                            size_t data_offset, size_t data_len);
int crypto_krb5_verify_mic(const struct krb5_enctype *krb5,
                           struct crypto_shash *shash,
                           const struct krb5_buffer *metadata,
                           struct scatterlist *sg, unsigned int nr_sg,
                           size_t *_offset, size_t *_len);
```

In both cases, the input and output buffers are indicated by the same scatterlist.  Additional metadata can be passed in which will get added to the hash before the data.

For the get_mic function, the output buffer may be larger than is needed (the amount of output generated is returned) and the location and size of the data are indicated (which must match the encoding).

For the verification function, the offset and length of the message in buffer are supplied and these are shrunk to fit the data.  An error will be returned if the checksums don't match.

<a id="rst-the-krb5enc-aead-algorithm"></a>

## The krb5enc AEAD algorithm

A template AEAD crypto algorithm, called "krb5enc", is provided that hashes the plaintext before encrypting it (the reverse of authenc).  The handle returned by `crypto_krb5_prepare_encryption()` may be one of these, but there's no requirement for the user of this API to interact with it directly.

For reference, its key format begins with a BE32 of the format number.  Only format 1 is provided and that continues with a BE32 of the Ke key length followed by a BE32 of the Ki key length, followed by the bytes from the Ke key and then the Ki key.

Using specifically ordered words means that the static test data doesn't require byteswapping.

---

# SHA-3 Algorithm Collection

_Peios Kernel / Internals / Crypto_

> Overview

<a id="rst-sha-3-algorithm-collection"></a>

<!-- SPDX-License-Identifier: GPL-2.0-or-later -->

<a id="rst-contents"></a>



<a id="rst-overview"></a>

## Overview

The SHA-3 family of algorithms, as specified in NIST FIPS-202 <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1), contains six algorithms based on the Keccak sponge function.  The differences between them are: the "rate" (how much of the state buffer gets updated with new data between invocations of the Keccak function and analogous to the "block size"), what domain separation suffix gets appended to the input data, and how much output data is extracted at the end.  The Keccak sponge function is designed such that arbitrary amounts of output can be obtained for certain algorithms.

Four digest algorithms are provided:

> - SHA3-224
>
> - SHA3-256
>
> - SHA3-384
>
> - SHA3-512

Additionally, two Extendable-Output Functions (XOFs) are provided:

> - SHAKE128
>
> - SHAKE256

The SHA-3 library API supports all six of these algorithms.  The four digest algorithms are also supported by the crypto_shash and crypto_ahash APIs.

This document describes the SHA-3 library API.

<a id="rst-digests"></a>

## Digests

The following functions compute SHA-3 digests:



```text
void sha3_224(const u8 *in, size_t in_len, u8 out[SHA3_224_DIGEST_SIZE]);
void sha3_256(const u8 *in, size_t in_len, u8 out[SHA3_256_DIGEST_SIZE]);
void sha3_384(const u8 *in, size_t in_len, u8 out[SHA3_384_DIGEST_SIZE]);
void sha3_512(const u8 *in, size_t in_len, u8 out[SHA3_512_DIGEST_SIZE]);
```

For users that need to pass in data incrementally, an incremental API is also provided.  The incremental API uses the following struct:



```text
struct sha3_ctx { ... };
```

Initialization is done with one of:



```text
void sha3_224_init(struct sha3_ctx *ctx);
void sha3_256_init(struct sha3_ctx *ctx);
void sha3_384_init(struct sha3_ctx *ctx);
void sha3_512_init(struct sha3_ctx *ctx);
```

Input data is then added with any number of calls to:



```text
void sha3_update(struct sha3_ctx *ctx, const u8 *in, size_t in_len);
```

Finally, the digest is generated using:



```text
void sha3_final(struct sha3_ctx *ctx, u8 *out);
```

which also zeroizes the context.  The length of the digest is determined by the initialization function that was called.

<a id="rst-extendable-output-functions"></a>

## Extendable-Output Functions

The following functions compute the SHA-3 extendable-output functions (XOFs):



```text
void shake128(const u8 *in, size_t in_len, u8 *out, size_t out_len);
void shake256(const u8 *in, size_t in_len, u8 *out, size_t out_len);
```

For users that need to provide the input data incrementally and/or receive the output data incrementally, an incremental API is also provided.  The incremental API uses the following struct:



```text
struct shake_ctx { ... };
```

Initialization is done with one of:



```text
void shake128_init(struct shake_ctx *ctx);
void shake256_init(struct shake_ctx *ctx);
```

Input data is then added with any number of calls to:



```text
void shake_update(struct shake_ctx *ctx, const u8 *in, size_t in_len);
```

Finally, the output data is extracted with any number of calls to:



```text
void shake_squeeze(struct shake_ctx *ctx, u8 *out, size_t out_len);
```

and telling it how much data should be extracted.  Note that performing multiple squeezes, with the output laid consecutively in a buffer, gets exactly the same output as doing a single squeeze for the combined amount over the same buffer.

More input data cannot be added after squeezing has started.

Once all the desired output has been extracted, zeroize the context:



```text
void shake_zeroize_ctx(struct shake_ctx *ctx);
```

<a id="rst-testing"></a>

## Testing

To test the SHA-3 code, use sha3_kunit (CONFIG_CRYPTO_LIB_SHA3_KUNIT_TEST).

Since the SHA-3 algorithms are FIPS-approved, when the kernel is booted in FIPS mode the SHA-3 library also performs a simple self-test.  This is purely to meet a FIPS requirement.  Normal testing done by kernel developers and integrators should use the much more comprehensive KUnit test suite instead.

<a id="rst-references"></a>

## References

<a id="rst-footnote-1"></a>



**[1]** [https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf](<https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf>)

<a id="rst-api-function-reference"></a>

## API Function Reference


#### <a id="c-struct-sha3_ctx"></a>`struct sha3_ctx`

Context for SHA3-224, SHA3-256, SHA3-384, or SHA3-512

**Definition**

```c
struct sha3_ctx {
    struct __sha3_ctx ctx;
};
```

**Members**

- `ctx`: private

#### <a id="c-sha3_zeroize_ctx"></a>`sha3_zeroize_ctx()`

```c
void sha3_zeroize_ctx(struct sha3_ctx *ctx)
```

Zeroize a SHA-3 context

**Parameters**

- `struct sha3_ctx *ctx`: The context to zeroize

**Description**

This is already called by [`sha3_final()`](#c-sha3_final).  Call this explicitly when abandoning
a context without calling [`sha3_final()`](#c-sha3_final).

#### <a id="c-struct-shake_ctx"></a>`struct shake_ctx`

Context for SHAKE128 or SHAKE256

**Definition**

```c
struct shake_ctx {
    struct __sha3_ctx ctx;
};
```

**Members**

- `ctx`: private

#### <a id="c-shake_zeroize_ctx"></a>`shake_zeroize_ctx()`

```c
void shake_zeroize_ctx(struct shake_ctx *ctx)
```

Zeroize a SHAKE context

**Parameters**

- `struct shake_ctx *ctx`: The context to zeroize

**Description**

Call this after the last squeeze.

#### <a id="c-sha3_224_init"></a>`sha3_224_init()`

```c
void sha3_224_init(struct sha3_ctx *ctx)
```

Initialize a context for SHA3-224

**Parameters**

- `struct sha3_ctx *ctx`: The context to initialize

**Description**

This begins a new SHA3-224 message digest computation.

**Context**

Any context.

#### <a id="c-sha3_256_init"></a>`sha3_256_init()`

```c
void sha3_256_init(struct sha3_ctx *ctx)
```

Initialize a context for SHA3-256

**Parameters**

- `struct sha3_ctx *ctx`: The context to initialize

**Description**

This begins a new SHA3-256 message digest computation.

**Context**

Any context.

#### <a id="c-sha3_384_init"></a>`sha3_384_init()`

```c
void sha3_384_init(struct sha3_ctx *ctx)
```

Initialize a context for SHA3-384

**Parameters**

- `struct sha3_ctx *ctx`: The context to initialize

**Description**

This begins a new SHA3-384 message digest computation.

**Context**

Any context.

#### <a id="c-sha3_512_init"></a>`sha3_512_init()`

```c
void sha3_512_init(struct sha3_ctx *ctx)
```

Initialize a context for SHA3-512

**Parameters**

- `struct sha3_ctx *ctx`: The context to initialize

**Description**

This begins a new SHA3-512 message digest computation.

**Context**

Any context.

#### <a id="c-sha3_update"></a>`sha3_update()`

```c
void sha3_update(struct sha3_ctx *ctx, const u8 *in, size_t in_len)
```

Update a SHA-3 digest context with input data

**Parameters**

- `struct sha3_ctx *ctx`: The context to update; must have been initialized
- `const u8 *in`: The input data
- `size_t in_len`: Length of the input data in bytes

**Description**

This can be called any number of times to add data to a SHA3-224, SHA3-256,
SHA3-384, or SHA3-512 digest (depending on which init function was called).

**Context**

Any context.

#### <a id="c-sha3_final"></a>`sha3_final()`

```c
void sha3_final(struct sha3_ctx *ctx, u8 *out)
```

Finish computing a SHA-3 message digest

**Parameters**

- `struct sha3_ctx *ctx`: The context to finalize; must have been initialized
- `u8 *out`: (output) The resulting SHA3-224, SHA3-256, SHA3-384, or SHA3-512
  message digest, matching the init function that was called.  Note that
  the size differs for each one; see SHA3_*_DIGEST_SIZE.

**Description**

After finishing, this zeroizes **ctx**.  So the caller does not need to do it.

**Context**

Any context.

#### <a id="c-shake128_init"></a>`shake128_init()`

```c
void shake128_init(struct shake_ctx *ctx)
```

Initialize a context for SHAKE128

**Parameters**

- `struct shake_ctx *ctx`: The context to initialize

**Description**

This begins a new SHAKE128 extendable-output function (XOF) computation.

**Context**

Any context.

#### <a id="c-shake256_init"></a>`shake256_init()`

```c
void shake256_init(struct shake_ctx *ctx)
```

Initialize a context for SHAKE256

**Parameters**

- `struct shake_ctx *ctx`: The context to initialize

**Description**

This begins a new SHAKE256 extendable-output function (XOF) computation.

**Context**

Any context.

#### <a id="c-shake_update"></a>`shake_update()`

```c
void shake_update(struct shake_ctx *ctx, const u8 *in, size_t in_len)
```

Update a SHAKE context with input data

**Parameters**

- `struct shake_ctx *ctx`: The context to update; must have been initialized
- `const u8 *in`: The input data
- `size_t in_len`: Length of the input data in bytes

**Description**

This can be called any number of times to add more input data to SHAKE128 or
SHAKE256.  This cannot be called after squeezing has begun.

**Context**

Any context.

#### <a id="c-shake_squeeze"></a>`shake_squeeze()`

```c
void shake_squeeze(struct shake_ctx *ctx, u8 *out, size_t out_len)
```

Generate output from SHAKE128 or SHAKE256

**Parameters**

- `struct shake_ctx *ctx`: The context to squeeze; must have been initialized
- `u8 *out`: Where to write the resulting output data
- `size_t out_len`: The amount of data to extract to **out** in bytes

**Description**

This may be called multiple times.  A number of consecutive squeezes laid
end-to-end will yield the same output as one big squeeze generating the same
total amount of output.  More input cannot be provided after squeezing has
begun.  After the last squeeze, call [`shake_zeroize_ctx()`](#c-shake_zeroize_ctx).

**Context**

Any context.

#### <a id="c-sha3_224"></a>`sha3_224()`

```c
void sha3_224(const u8 *in, size_t in_len, u8 out[SHA3_224_DIGEST_SIZE])
```

Compute SHA3-224 digest in one shot

**Parameters**

- `const u8 *in`: The input data to be digested
- `size_t in_len`: Length of the input data in bytes
- `u8 out[SHA3_224_DIGEST_SIZE]`: The buffer into which the digest will be stored

**Description**

Convenience function that computes a SHA3-224 digest.  Use this instead of
the incremental API if you're able to provide all the input at once.

**Context**

Any context.

#### <a id="c-sha3_256"></a>`sha3_256()`

```c
void sha3_256(const u8 *in, size_t in_len, u8 out[SHA3_256_DIGEST_SIZE])
```

Compute SHA3-256 digest in one shot

**Parameters**

- `const u8 *in`: The input data to be digested
- `size_t in_len`: Length of the input data in bytes
- `u8 out[SHA3_256_DIGEST_SIZE]`: The buffer into which the digest will be stored

**Description**

Convenience function that computes a SHA3-256 digest.  Use this instead of
the incremental API if you're able to provide all the input at once.

**Context**

Any context.

#### <a id="c-sha3_384"></a>`sha3_384()`

```c
void sha3_384(const u8 *in, size_t in_len, u8 out[SHA3_384_DIGEST_SIZE])
```

Compute SHA3-384 digest in one shot

**Parameters**

- `const u8 *in`: The input data to be digested
- `size_t in_len`: Length of the input data in bytes
- `u8 out[SHA3_384_DIGEST_SIZE]`: The buffer into which the digest will be stored

**Description**

Convenience function that computes a SHA3-384 digest.  Use this instead of
the incremental API if you're able to provide all the input at once.

**Context**

Any context.

#### <a id="c-sha3_512"></a>`sha3_512()`

```c
void sha3_512(const u8 *in, size_t in_len, u8 out[SHA3_512_DIGEST_SIZE])
```

Compute SHA3-512 digest in one shot

**Parameters**

- `const u8 *in`: The input data to be digested
- `size_t in_len`: Length of the input data in bytes
- `u8 out[SHA3_512_DIGEST_SIZE]`: The buffer into which the digest will be stored

**Description**

Convenience function that computes a SHA3-512 digest.  Use this instead of
the incremental API if you're able to provide all the input at once.

**Context**

Any context.

#### <a id="c-shake128"></a>`shake128()`

```c
void shake128(const u8 *in, size_t in_len, u8 *out, size_t out_len)
```

Compute SHAKE128 in one shot

**Parameters**

- `const u8 *in`: The input data to be used
- `size_t in_len`: Length of the input data in bytes
- `u8 *out`: The buffer into which the output will be stored
- `size_t out_len`: Length of the output to produce in bytes

**Description**

Convenience function that computes SHAKE128 in one shot.  Use this instead of
the incremental API if you're able to provide all the input at once as well
as receive all the output at once.  All output lengths are supported.

**Context**

Any context.

#### <a id="c-shake256"></a>`shake256()`

```c
void shake256(const u8 *in, size_t in_len, u8 *out, size_t out_len)
```

Compute SHAKE256 in one shot

**Parameters**

- `const u8 *in`: The input data to be used
- `size_t in_len`: Length of the input data in bytes
- `u8 *out`: The buffer into which the output will be stored
- `size_t out_len`: Length of the output to produce in bytes

**Description**

Convenience function that computes SHAKE256 in one shot.  Use this instead of
the incremental API if you're able to provide all the input at once as well
as receive all the output at once.  All output lengths are supported.

**Context**

Any context.

---

# User Space Interface

_Peios Kernel / Internals / Crypto_

> The concepts of the kernel crypto API visible to kernel space is fully applicable to the user space interface as well. Therefore, the kernel crypto API high level discussion for the in-kernel use cases applies here as well.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-user-space-interface"></a>

<a id="rst-introduction"></a>

## Introduction

The concepts of the kernel crypto API visible to kernel space is fully applicable to the user space interface as well. Therefore, the kernel crypto API high level discussion for the in-kernel use cases applies here as well.

The major difference, however, is that user space can only act as a consumer and never as a provider of a transformation or cipher algorithm.

The following covers the user space interface exported by the kernel crypto API. A working example of this description is libkcapi that can be obtained from \[1\]. That library can be used by user space applications that require cryptographic services from the kernel.

Some details of the in-kernel kernel crypto API aspects do not apply to user space, however. This includes the difference between synchronous and asynchronous invocations. The user space API call is fully synchronous.

\[1\] [https://www.chronox.de/libkcapi.html](<https://www.chronox.de/libkcapi.html>)

<a id="rst-user-space-api-general-remarks"></a>

## User Space API General Remarks

The kernel crypto API is accessible from user space. Currently, the following ciphers are accessible:

- Message digest including keyed message digest (HMAC, CMAC)

- Symmetric ciphers

- AEAD ciphers

- Random Number Generators

The interface is provided via socket type using the type AF_ALG. In addition, the setsockopt option type is SOL_ALG. In case the user space header files do not export these flags yet, use the following macros:



```text
#ifndef AF_ALG
#define AF_ALG 38
#endif
#ifndef SOL_ALG
#define SOL_ALG 279
#endif
```

A cipher is accessed with the same name as done for the in-kernel API calls. This includes the generic vs. unique naming schema for ciphers as well as the enforcement of priorities for generic names.

To interact with the kernel crypto API, a socket must be created by the user space application. User space invokes the cipher operation with the send()/write() system call family. The result of the cipher operation is obtained with the read()/recv() system call family.

The following API calls assume that the socket descriptor is already opened by the user space application and discusses only the kernel crypto API specific invocations.

To initialize the socket interface, the following sequence has to be performed by the consumer:

1. Create a socket of type AF_ALG with the struct sockaddr_alg parameter specified below for the different cipher types.

2. Invoke bind with the socket descriptor

3. Invoke accept with the socket descriptor. The accept system call returns a new file descriptor that is to be used to interact with the particular cipher instance. When invoking send/write or recv/read system calls to send data to the kernel or obtain data from the kernel, the file descriptor returned by accept must be used.

<a id="rst-in-place-cipher-operation"></a>

## In-place Cipher operation

Just like the in-kernel operation of the kernel crypto API, the user space interface allows the cipher operation in-place. That means that the input buffer used for the send/write system call and the output buffer used by the read/recv system call may be one and the same. This is of particular interest for symmetric cipher operations where a copying of the output data to its final destination can be avoided.

If a consumer on the other hand wants to maintain the plaintext and the ciphertext in different memory locations, all a consumer needs to do is to provide different memory pointers for the encryption and decryption operation.

<a id="rst-message-digest-api"></a>

## Message Digest API

The message digest type to be used for the cipher operation is selected when invoking the bind syscall. bind requires the caller to provide a filled struct sockaddr data structure. This data structure must be filled as follows:



```text
struct sockaddr_alg sa = {
    .salg_family = AF_ALG,
    .salg_type = "hash", /* this selects the hash logic in the kernel */
    .salg_name = "sha1" /* this is the cipher name */
};
```

The salg_type value "hash" applies to message digests and keyed message digests. Though, a keyed message digest is referenced by the appropriate salg_name. Please see below for the setsockopt interface that explains how the key can be set for a keyed message digest.

Using the send() system call, the application provides the data that should be processed with the message digest. The send system call allows the following flags to be specified:

- MSG_MORE: If this flag is set, the send system call acts like a message digest update function where the final hash is not yet calculated. If the flag is not set, the send system call calculates the final message digest immediately.

With the recv() system call, the application can read the message digest from the kernel crypto API. If the buffer is too small for the message digest, the flag MSG_TRUNC is set by the kernel.

In order to set a message digest key, the calling application must use the setsockopt() option of ALG_SET_KEY or ALG_SET_KEY_BY_KEY_SERIAL. If the key is not set the HMAC operation is performed without the initial HMAC state change caused by the key.

<a id="rst-symmetric-cipher-api"></a>

## Symmetric Cipher API

The operation is very similar to the message digest discussion. During initialization, the struct sockaddr data structure must be filled as follows:



```text
struct sockaddr_alg sa = {
    .salg_family = AF_ALG,
    .salg_type = "skcipher", /* this selects the symmetric cipher */
    .salg_name = "cbc(aes)" /* this is the cipher name */
};
```

Before data can be sent to the kernel using the write/send system call family, the consumer must set the key. The key setting is described with the setsockopt invocation below.

Using the sendmsg() system call, the application provides the data that should be processed for encryption or decryption. In addition, the IV is specified with the data structure provided by the sendmsg() system call.

The sendmsg system call parameter of struct msghdr is embedded into the struct cmsghdr data structure. See recv(2) and cmsg(3) for more information on how the cmsghdr data structure is used together with the send/recv system call family. That cmsghdr data structure holds the following information specified with a separate header instances:

- specification of the cipher operation type with one of these flags:

  - ALG_OP_ENCRYPT - encryption of data

  - ALG_OP_DECRYPT - decryption of data

- specification of the IV information marked with the flag ALG_SET_IV

The send system call family allows the following flag to be specified:

- MSG_MORE: If this flag is set, the send system call acts like a cipher update function where more input data is expected with a subsequent invocation of the send system call.

Note: The kernel reports -EINVAL for any unexpected data. The caller must make sure that all data matches the constraints given in /proc/crypto for the selected cipher.

With the recv() system call, the application can read the result of the cipher operation from the kernel crypto API. The output buffer must be at least as large as to hold all blocks of the encrypted or decrypted data. If the output data size is smaller, only as many blocks are returned that fit into that output buffer size.

<a id="rst-aead-cipher-api"></a>

## AEAD Cipher API

The operation is very similar to the symmetric cipher discussion. During initialization, the struct sockaddr data structure must be filled as follows:



```text
struct sockaddr_alg sa = {
    .salg_family = AF_ALG,
    .salg_type = "aead", /* this selects the symmetric cipher */
    .salg_name = "gcm(aes)" /* this is the cipher name */
};
```

Before data can be sent to the kernel using the write/send system call family, the consumer must set the key. The key setting is described with the setsockopt invocation below.

In addition, before data can be sent to the kernel using the write/send system call family, the consumer must set the authentication tag size. To set the authentication tag size, the caller must use the setsockopt invocation described below.

Using the sendmsg() system call, the application provides the data that should be processed for encryption or decryption. In addition, the IV is specified with the data structure provided by the sendmsg() system call.

The sendmsg system call parameter of struct msghdr is embedded into the struct cmsghdr data structure. See recv(2) and cmsg(3) for more information on how the cmsghdr data structure is used together with the send/recv system call family. That cmsghdr data structure holds the following information specified with a separate header instances:

- specification of the cipher operation type with one of these flags:

  - ALG_OP_ENCRYPT - encryption of data

  - ALG_OP_DECRYPT - decryption of data

- specification of the IV information marked with the flag ALG_SET_IV

- specification of the associated authentication data (AAD) with the flag ALG_SET_AEAD_ASSOCLEN. The AAD is sent to the kernel together with the plaintext / ciphertext. See below for the memory structure.

The send system call family allows the following flag to be specified:

- MSG_MORE: If this flag is set, the send system call acts like a cipher update function where more input data is expected with a subsequent invocation of the send system call.

Note: The kernel reports -EINVAL for any unexpected data. The caller must make sure that all data matches the constraints given in /proc/crypto for the selected cipher.

With the recv() system call, the application can read the result of the cipher operation from the kernel crypto API. The output buffer must be at least as large as defined with the memory structure below. If the output data size is smaller, the cipher operation is not performed.

The authenticated decryption operation may indicate an integrity error. Such breach in integrity is marked with the -EBADMSG error code.

<a id="rst-aead-memory-structure"></a>

### AEAD Memory Structure

The AEAD cipher operates with the following information that is communicated between user and kernel space as one data stream:

- plaintext or ciphertext

- associated authentication data (AAD)

- authentication tag

The sizes of the AAD and the authentication tag are provided with the sendmsg and setsockopt calls (see there). As the kernel knows the size of the entire data stream, the kernel is now able to calculate the right offsets of the data components in the data stream.

The user space caller must arrange the aforementioned information in the following order:

- AEAD encryption input: AAD \|\| plaintext

- AEAD decryption input: AAD \|\| ciphertext \|\| authentication tag

The output buffer the user space caller provides must be at least as large to hold the following data:

- AEAD encryption output: ciphertext \|\| authentication tag

- AEAD decryption output: plaintext

<a id="rst-random-number-generator-api"></a>

## Random Number Generator API

Again, the operation is very similar to the other APIs. During initialization, the struct sockaddr data structure must be filled as follows:



```text
struct sockaddr_alg sa = {
    .salg_family = AF_ALG,
    .salg_type = "rng", /* this selects the random number generator */
    .salg_name = "drbg_nopr_sha256" /* this is the RNG name */
};
```

Depending on the RNG type, the RNG must be seeded. The seed is provided using the setsockopt interface to set the key. The SP800-90A DRBGs do not require a seed, but may be seeded. The seed is also known as a *Personalization String* in NIST SP 800-90A standard.

Using the read()/recvmsg() system calls, random numbers can be obtained. The kernel generates at most 128 bytes in one call. If user space requires more data, multiple calls to read()/recvmsg() must be made.

WARNING: The user space caller may invoke the initially mentioned accept system call multiple times. In this case, the returned file descriptors have the same state.

Following CAVP testing interfaces are enabled when kernel is built with CRYPTO_USER_API_RNG_CAVP option:

- the concatenation of *Entropy* and *Nonce* can be provided to the RNG via ALG_SET_DRBG_ENTROPY setsockopt interface. Setting the entropy requires CAP_SYS_ADMIN permission.

- *Additional Data* can be provided using the send()/sendmsg() system calls, but only after the entropy has been set.

<a id="rst-zero-copy-interface"></a>

## Zero-Copy Interface

In addition to the send/write/read/recv system call family, the AF_ALG interface can be accessed with the zero-copy interface of splice/vmsplice. As the name indicates, the kernel tries to avoid a copy operation into kernel space.

The zero-copy operation requires data to be aligned at the page boundary. Non-aligned data can be used as well, but may require more operations of the kernel which would defeat the speed gains obtained from the zero-copy interface.

The system-inherent limit for the size of one zero-copy operation is 16 pages. If more data is to be sent to AF_ALG, user space must slice the input into segments with a maximum size of 16 pages.

Zero-copy can be used with the following code example (a complete working example is provided with libkcapi):



```text
int pipes[2];

pipe(pipes);
/* input data in iov */
vmsplice(pipes[1], iov, iovlen, SPLICE_F_GIFT);
/* opfd is the file descriptor returned from accept() system call */
splice(pipes[0], NULL, opfd, NULL, ret, 0);
read(opfd, out, outlen);
```

<a id="rst-setsockopt-interface"></a>

## Setsockopt Interface

In addition to the read/recv and send/write system call handling to send and retrieve data subject to the cipher operation, a consumer also needs to set the additional information for the cipher operation. This additional information is set using the setsockopt system call that must be invoked with the file descriptor of the open cipher (i.e. the file descriptor returned by the accept system call).

Each setsockopt invocation must use the level SOL_ALG.

The setsockopt interface allows setting the following data using the mentioned optname:

- ALG_SET_KEY -- Setting the key. Key setting is applicable to:

  - the skcipher cipher type (symmetric ciphers)

  - the hash cipher type (keyed message digests)

  - the AEAD cipher type

  - the RNG cipher type to provide the seed

- - **ALG_SET_KEY_BY_KEY_SERIAL -- Setting the key via keyring key_serial_t.**

    This operation behaves the same as ALG_SET_KEY. The decrypted data is copied from a keyring key, and uses that data as the key for symmetric encryption.

    The passed in key_serial_t must have the KEY\_(POS\|USR\|GRP\|OTH)\_SEARCH permission set, otherwise -EPERM is returned. Supports key types: user, logon, encrypted, and trusted.

- ALG_SET_AEAD_AUTHSIZE -- Setting the authentication tag size for AEAD ciphers. For a encryption operation, the authentication tag of the given size will be generated. For a decryption operation, the provided ciphertext is assumed to contain an authentication tag of the given size (see section about AEAD memory layout below).

- ALG_SET_DRBG_ENTROPY -- Setting the entropy of the random number generator. This option is applicable to RNG cipher type only.

<a id="rst-user-space-api-example"></a>

## User space API example

Please see \[1\] for libkcapi which provides an easy-to-use wrapper around the aforementioned Netlink kernel interface. \[1\] also contains a test application that invokes all libkcapi API calls.

\[1\] [https://www.chronox.de/libkcapi.html](<https://www.chronox.de/libkcapi.html>)

---

# Hardware Device Driver Specific Documentation

_Peios Kernel / Internals / Crypto / device_drivers_

> Reference for Hardware Device Driver Specific Documentation.

<a id="rst-hardware-device-driver-specific-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [octeontx2 devlink support](</kernel/internals/crypto/device-drivers/octeontx2.md>)

---

# octeontx2 devlink support

_Peios Kernel / Internals / Crypto / device_drivers_

> This document describes the devlink features implemented by the octeontx2 CPT device drivers.

<a id="rst-octeontx2-devlink-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes the devlink features implemented by the `octeontx2 CPT` device drivers.

<a id="rst-parameters"></a>

## Parameters

The `octeontx2` driver implements the following driver-specific parameters.


<table>
<caption>Driver-specific parameters implemented</caption>
<tbody>
<tr>
<td>


Name

</td>
<td>


Type

</td>
<td>


Mode

</td>
<td>


Description

</td>
</tr>
<tr>
<td>


`t106_mode`

</td>
<td>


u8

</td>
<td>


runtime

</td>
<td>


Used to configure CN10KA B0/CN10KB CPT to work as CN10KA A0/A1.

</td>
</tr>
</tbody>
</table>

---

# Security Documentation

_Peios Kernel / Internals / Security_

> Reference for Security Documentation.

<a id="rst-security-documentation"></a>

- [Credentials in Linux](</kernel/internals/security/credentials.md>)
- [Confidential Computing in Linux for x86 virtualization](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/security/snp-tdx-threat-model.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [IMA Template Management Mechanism](</kernel/internals/security/ima-templates.md>)
- [Kernel Keys](</kernel/internals/security/keys/index.md>)
- [Linux Security Modules: General Security Hooks for Linux](</kernel/internals/security/lsm.md>)
- [Linux Security Module Development](</kernel/internals/security/lsm-development.md>)
- [Linux Secure Attention Key (SAK) handling](</kernel/internals/security/sak.md>)
- [SCTP](</kernel/internals/security/sctp.md>)
- [Kernel Self-Protection](</kernel/internals/security/self-protection.md>)
- [SipHash - a short input PRF](</kernel/internals/security/siphash.md>)
- [Trusted Platform Module documentation](</kernel/internals/security/tpm/index.md>)
- [Digital Signature Verification API](</kernel/internals/security/digsig.md>)
- [Landlock LSM: kernel documentation](</kernel/internals/security/landlock.md>)
- [Secrets documentation](</kernel/internals/security/secrets/index.md>)
- [Integrity Policy Enforcement (IPE) - Kernel Documentation](</kernel/internals/security/ipe.md>)

---

# IMA Template Management Mechanism

_Peios Kernel / Internals / Security_

> The original ima template is fixed length, containing the filedata hash and pathname. The filedata hash is limited to 20 bytes (md5/sha1). The pathname is a null terminated string, limited to 255 characters. To overcome these limitations…

<a id="rst-ima-template-management-mechanism"></a>

<a id="rst-introduction"></a>

## Introduction

The original `ima` template is fixed length, containing the filedata hash and pathname. The filedata hash is limited to 20 bytes (md5/sha1). The pathname is a null terminated string, limited to 255 characters. To overcome these limitations and to add additional file metadata, it is necessary to extend the current version of IMA by defining additional templates. For example, information that could be possibly reported are the inode UID/GID or the LSM labels either of the inode and of the process that is accessing it.

However, the main problem to introduce this feature is that, each time a new template is defined, the functions that generate and display the measurements list would include the code for handling a new format and, thus, would significantly grow over the time.

The proposed solution solves this problem by separating the template management from the remaining IMA code. The core of this solution is the definition of two new data structures: a template descriptor, to determine which information should be included in the measurement list; a template field, to generate and display data of a given type.

Managing templates with these structures is very simple. To support a new data type, developers define the field identifier and implement two functions, init() and show(), respectively to generate and display measurement entries. Defining a new template descriptor requires specifying the template format (a string of field identifiers separated by the `|` character) through the `ima_template_fmt` kernel command line parameter. At boot time, IMA initializes the chosen template descriptor by translating the format into an array of template fields structures taken from the set of the supported ones.

After the initialization step, IMA will call `ima_alloc_init_template()` (new function defined within the patches for the new template management mechanism) to generate a new measurement entry by using the template descriptor chosen through the kernel configuration or through the newly introduced `ima_template` and `ima_template_fmt` kernel command line parameters. It is during this phase that the advantages of the new architecture are clearly shown: the latter function will not contain specific code to handle a given template but, instead, it simply calls the `init()` method of the template fields associated to the chosen template descriptor and store the result (pointer to allocated data and data length) in the measurement entry structure.

The same mechanism is employed to display measurements entries. The functions `ima[_ascii]_measurements_show()` retrieve, for each entry, the template descriptor used to produce that entry and call the show() method for each item of the array of template fields structures.

<a id="rst-supported-template-fields-and-descriptors"></a>

## Supported Template Fields and Descriptors

In the following, there is the list of supported template fields `('<identifier>': description)`, that can be used to define new template descriptors by adding their identifier to the format string (support for more data types will be added later):

> - 'd': the digest of the event (i.e. the digest of a measured file), calculated with the SHA1 or MD5 hash algorithm;
>
> - 'n': the name of the event (i.e. the file name), with size up to 255 bytes;
>
> - 'd-ng': the digest of the event, calculated with an arbitrary hash algorithm (field format: &lt;hash algo&gt;:digest);
>
> - 'd-ngv2': same as d-ng, but prefixed with the "ima" or "verity" digest type (field format: &lt;digest type&gt;:&lt;hash algo&gt;:digest);
>
> - 'd-modsig': the digest of the event without the appended modsig;
>
> - 'n-ng': the name of the event, without size limitations;
>
> - 'sig': the file signature, based on either the file's/fsverity's digest\[1\], or the EVM portable signature, if 'security.ima' contains a file hash.
>
> - 'modsig' the appended file signature;
>
> - 'buf': the buffer data that was used to generate the hash without size limitations;
>
> - 'evmsig': the EVM portable signature;
>
> - 'iuid': the inode UID;
>
> - 'igid': the inode GID;
>
> - 'imode': the inode mode;
>
> - - **'xattrnames': a list of xattr names (separated by `|`), only if the xattr is**
>
>     present;
>
> - 'xattrlengths': a list of xattr lengths (u32), only if the xattr is present;
>
> - 'xattrvalues': a list of xattr values;

Below, there is the list of defined template descriptors:

> - "ima": its format is `d|n`;
>
> - "ima-ng" (default): its format is `d-ng|n-ng`;
>
> - "ima-ngv2": its format is `d-ngv2|n-ng`;
>
> - "ima-sig": its format is `d-ng|n-ng|sig`;
>
> - "ima-sigv2": its format is `d-ngv2|n-ng|sig`;
>
> - "ima-buf": its format is `d-ng|n-ng|buf`;
>
> - "ima-modsig": its format is `d-ng|n-ng|sig|d-modsig|modsig`;
>
> - "evm-sig": its format is `d-ng|n-ng|evmsig|xattrnames|xattrlengths|xattrvalues|iuid|igid|imode`;

<a id="rst-use"></a>

## Use

To specify the template descriptor to be used to generate measurement entries, currently the following methods are supported:

> - select a template descriptor among those supported in the kernel configuration (`ima-ng` is the default choice);
>
> - specify a template descriptor name from the kernel command line through the `ima_template=` parameter;
>
> - register a new template descriptor with custom format through the kernel command line parameter `ima_template_fmt=`.

---

# SCTP

_Peios Kernel / Internals / Security_

> For security module support, three SCTP specific hooks have been implemented:

> **Peios:** The LSM examples here describe upstream interfaces and implementation choices. Peios configures `landlock,lockdown,integrity,pkm`; SELinux, Smack, AppArmor and their attribute/policy interfaces are not the active native access model. Use the native token/SD interfaces for Peios authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-sctp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-sctp-lsm-support"></a>

## SCTP LSM Support

<a id="rst-security-hooks"></a>

### Security Hooks

For security module support, three SCTP specific hooks have been implemented:



```text
security_sctp_assoc_request()
security_sctp_bind_connect()
security_sctp_sk_clone()
security_sctp_assoc_established()
```

The usage of these hooks are described below with the SELinux implementation described in the [SCTP SELinux Support](<#rst-sctp-selinux-support>) chapter.

<a id="rst-security-sctp-assoc-request"></a>

#### security_sctp_assoc_request()

Passes the `@asoc` and `@chunk->skb` of the association INIT packet to the security module. Returns 0 on success, error on failure.



```text
@asoc - pointer to sctp association structure.
@skb - pointer to skbuff of association packet.
```

<a id="rst-security-sctp-bind-connect"></a>

#### security_sctp_bind_connect()

Passes one or more ipv4/ipv6 addresses to the security module for validation based on the `@optname` that will result in either a bind or connect service as shown in the permission check tables below. Returns 0 on success, error on failure.



```text
  @sk      - Pointer to sock structure.
  @optname - Name of the option to validate.
  @address - One or more ipv4 / ipv6 addresses.
  @addrlen - The total length of address(s). This is calculated on each
             ipv4 or ipv6 address using sizeof(struct sockaddr_in) or
             sizeof(struct sockaddr_in6).

------------------------------------------------------------------
|                     BIND Type Checks                           |
|       @optname             |         @address contains         |
|----------------------------|-----------------------------------|
| SCTP_SOCKOPT_BINDX_ADD     | One or more ipv4 / ipv6 addresses |
| SCTP_PRIMARY_ADDR          | Single ipv4 or ipv6 address       |
| SCTP_SET_PEER_PRIMARY_ADDR | Single ipv4 or ipv6 address       |
------------------------------------------------------------------

------------------------------------------------------------------
|                   CONNECT Type Checks                          |
|       @optname             |         @address contains         |
|----------------------------|-----------------------------------|
| SCTP_SOCKOPT_CONNECTX      | One or more ipv4 / ipv6 addresses |
| SCTP_PARAM_ADD_IP          | One or more ipv4 / ipv6 addresses |
| SCTP_SENDMSG_CONNECT       | Single ipv4 or ipv6 address       |
| SCTP_PARAM_SET_PRIMARY     | Single ipv4 or ipv6 address       |
------------------------------------------------------------------
```

A summary of the `@optname` entries is as follows:



```text
SCTP_SOCKOPT_BINDX_ADD - Allows additional bind addresses to be
                         associated after (optionally) calling
                         bind(3).
                         sctp_bindx(3) adds a set of bind
                         addresses on a socket.

SCTP_SOCKOPT_CONNECTX - Allows the allocation of multiple
                        addresses for reaching a peer
                        (multi-homed).
                        sctp_connectx(3) initiates a connection
                        on an SCTP socket using multiple
                        destination addresses.

SCTP_SENDMSG_CONNECT  - Initiate a connection that is generated by a
                        sendmsg(2) or sctp_sendmsg(3) on a new association.

SCTP_PRIMARY_ADDR     - Set local primary address.

SCTP_SET_PEER_PRIMARY_ADDR - Request peer sets address as
                             association primary.

SCTP_PARAM_ADD_IP          - These are used when Dynamic Address
SCTP_PARAM_SET_PRIMARY     - Reconfiguration is enabled as explained below.
```

To support Dynamic Address Reconfiguration the following parameters must be enabled on both endpoints (or use the appropriate **setsockopt**(2)):



```text
/proc/sys/net/sctp/addip_enable
/proc/sys/net/sctp/addip_noauth_enable
```

then the following *\_PARAM\_*'s are sent to the peer in an ASCONF chunk when the corresponding `@optname`'s are present:



```text
      @optname                      ASCONF Parameter
     ----------                    ------------------
SCTP_SOCKOPT_BINDX_ADD     ->   SCTP_PARAM_ADD_IP
SCTP_SET_PEER_PRIMARY_ADDR ->   SCTP_PARAM_SET_PRIMARY
```

<a id="rst-security-sctp-sk-clone"></a>

#### security_sctp_sk_clone()

Called whenever a new socket is created by **accept**(2) (i.e. a TCP style socket) or when a socket is 'peeled off' e.g userspace calls **sctp_peeloff**(3).



```text
@asoc - pointer to current sctp association structure.
@sk - pointer to current sock structure.
@newsk - pointer to new sock structure.
```

<a id="rst-security-sctp-assoc-established"></a>

#### security_sctp_assoc_established()

Called when a COOKIE ACK is received, and the peer secid will be saved into `@asoc->peer_secid` for client:



```text
@asoc - pointer to sctp association structure.
@skb - pointer to skbuff of the COOKIE ACK packet.
```

<a id="rst-security-hooks-used-for-association-establishment"></a>

### Security Hooks used for Association Establishment

The following diagram shows the use of `security_sctp_bind_connect()`, `security_sctp_assoc_request()`, `security_sctp_assoc_established()` when establishing an association.



```text
     SCTP endpoint "A"                                SCTP endpoint "Z"
     =================                                =================
   sctp_sf_do_prm_asoc()
Association setup can be initiated
by a connect(2), sctp_connectx(3),
sendmsg(2) or sctp_sendmsg(3).
These will result in a call to
security_sctp_bind_connect() to
initiate an association to
SCTP peer endpoint "Z".
        INIT --------------------------------------------->
                                                  sctp_sf_do_5_1B_init()
                                                Respond to an INIT chunk.
                                            SCTP peer endpoint "A" is asking
                                            for a temporary association.
                                            Call security_sctp_assoc_request()
                                            to set the peer label if first
                                            association.
                                            If not first association, check
                                            whether allowed, IF so send:
         <----------------------------------------------- INIT ACK
         |                                  ELSE audit event and silently
         |                                       discard the packet.
         |
   COOKIE ECHO ------------------------------------------>
                                                 sctp_sf_do_5_1D_ce()
                                            Respond to an COOKIE ECHO chunk.
                                            Confirm the cookie and create a
                                            permanent association.
                                            Call security_sctp_assoc_request() to
                                            do the same as for INIT chunk Response.
         <------------------------------------------- COOKIE ACK
         |                                               |
   sctp_sf_do_5_1E_ca                                    |
Call security_sctp_assoc_established()                   |
to set the peer label.                                   |
         |                                               |
         |                               If SCTP_SOCKET_TCP or peeled off
         |                               socket security_sctp_sk_clone() is
         |                               called to clone the new socket.
         |                                               |
     ESTABLISHED                                    ESTABLISHED
         |                                               |
   ------------------------------------------------------------------
   |                     Association Established                    |
   ------------------------------------------------------------------
```

<a id="rst-sctp-selinux-support"></a>

## SCTP SELinux Support

<a id="rst-security-hooks-1"></a>

### Security Hooks

The [SCTP LSM Support](<#rst-sctp-lsm-support>) chapter above describes the following SCTP security hooks with the SELinux specifics expanded below:



```text
security_sctp_assoc_request()
security_sctp_bind_connect()
security_sctp_sk_clone()
security_sctp_assoc_established()
```

<a id="rst-security-sctp-assoc-request-1"></a>

#### security_sctp_assoc_request()

Passes the `@asoc` and `@chunk->skb` of the association INIT packet to the security module. Returns 0 on success, error on failure.



```text
@asoc - pointer to sctp association structure.
@skb - pointer to skbuff of association packet.
```

- **The security module performs the following operations:**

  IF this is the first association on `@asoc->base.sk`, then set the peer sid to that in `@skb`. This will ensure there is only one peer sid assigned to `@asoc->base.sk` that may support multiple associations.

  ELSE validate the `@asoc->base.sk peer_sid` against the `@skb peer sid` to determine whether the association should be allowed or denied.

  Set the sctp `@asoc sid` to socket's sid (from `asoc->base.sk`) with MLS portion taken from `@skb peer sid`. This will be used by SCTP TCP style sockets and peeled off connections as they cause a new socket to be generated.

  If IP security options are configured (CIPSO/CALIPSO), then the ip options are set on the socket.

<a id="rst-security-sctp-bind-connect-1"></a>

#### security_sctp_bind_connect()

Checks permissions required for ipv4/ipv6 addresses based on the `@optname` as follows:



```text
------------------------------------------------------------------
|                   BIND Permission Checks                       |
|       @optname             |         @address contains         |
|----------------------------|-----------------------------------|
| SCTP_SOCKOPT_BINDX_ADD     | One or more ipv4 / ipv6 addresses |
| SCTP_PRIMARY_ADDR          | Single ipv4 or ipv6 address       |
| SCTP_SET_PEER_PRIMARY_ADDR | Single ipv4 or ipv6 address       |
------------------------------------------------------------------

------------------------------------------------------------------
|                 CONNECT Permission Checks                      |
|       @optname             |         @address contains         |
|----------------------------|-----------------------------------|
| SCTP_SOCKOPT_CONNECTX      | One or more ipv4 / ipv6 addresses |
| SCTP_PARAM_ADD_IP          | One or more ipv4 / ipv6 addresses |
| SCTP_SENDMSG_CONNECT       | Single ipv4 or ipv6 address       |
| SCTP_PARAM_SET_PRIMARY     | Single ipv4 or ipv6 address       |
------------------------------------------------------------------
```

[SCTP LSM Support](<#rst-sctp-lsm-support>) gives a summary of the `@optname` entries and also describes ASCONF chunk processing when Dynamic Address Reconfiguration is enabled.

<a id="rst-security-sctp-sk-clone-1"></a>

#### security_sctp_sk_clone()

Called whenever a new socket is created by **accept**(2) (i.e. a TCP style socket) or when a socket is 'peeled off' e.g userspace calls **sctp_peeloff**(3). `security_sctp_sk_clone()` will set the new sockets sid and peer sid to that contained in the `@asoc sid` and `@asoc peer sid` respectively.



```text
@asoc - pointer to current sctp association structure.
@sk - pointer to current sock structure.
@newsk - pointer to new sock structure.
```

<a id="rst-security-sctp-assoc-established-1"></a>

#### security_sctp_assoc_established()

Called when a COOKIE ACK is received where it sets the connection's peer sid to that in `@skb`:



```text
@asoc - pointer to sctp association structure.
@skb - pointer to skbuff of the COOKIE ACK packet.
```

<a id="rst-policy-statements"></a>

### Policy Statements

The following class and permissions to support SCTP are available within the kernel:



```text
class sctp_socket inherits socket { node_bind }
```

whenever the following policy capability is enabled:



```text
policycap extended_socket_class;
```

SELinux SCTP support adds the `name_connect` permission for connecting to a specific port type and the `association` permission that is explained in the section below.

If userspace tools have been updated, SCTP will support the `portcon` statement as shown in the following example:



```text
portcon sctp 1024-1036 system_u:object_r:sctp_ports_t:s0
```

<a id="rst-sctp-peer-labeling"></a>

### SCTP Peer Labeling

An SCTP socket will only have one peer label assigned to it. This will be assigned during the establishment of the first association. Any further associations on this socket will have their packet peer label compared to the sockets peer label, and only if they are different will the `association` permission be validated. This is validated by checking the socket peer sid against the received packets peer sid to determine whether the association should be allowed or denied.

- **NOTES:**

  1. If peer labeling is not enabled, then the peer context will always be `SECINITSID_UNLABELED` (`unlabeled_t` in Reference Policy).

  2. As SCTP can support more than one transport address per endpoint (multi-homing) on a single socket, it is possible to configure policy and NetLabel to provide different peer labels for each of these. As the socket peer label is determined by the first associations transport address, it is recommended that all peer labels are consistent.

  3. **getpeercon**(3) may be used by userspace to retrieve the sockets peer context.

  4. While not SCTP specific, be aware when using NetLabel that if a label is assigned to a specific interface, and that interface 'goes down', then the NetLabel service will remove the entry. Therefore ensure that the network startup scripts call **netlabelctl**(8) to set the required label (see **netlabel-config**(8) helper script for details).

  5. The NetLabel SCTP peer labeling rules apply as discussed in the following set of posts tagged "netlabel" at: [https://www.paul-moore.com/blog/t](<https://www.paul-moore.com/blog/t>).

  6. CIPSO is only supported for IPv4 addressing: `socket(AF_INET, ...)` CALIPSO is only supported for IPv6 addressing: `socket(AF_INET6, ...)`

     - **Note the following when testing CIPSO/CALIPSO:**

       - **a)** CIPSO will send an ICMP packet if an SCTP packet cannot be delivered because of an invalid label.

       - **b)** CALIPSO does not send an ICMP packet, just silently discards it.

  7. IPSEC is not supported as RFC 3554 - sctp/ipsec support has not been implemented in userspace (**racoon**(8) or **ipsec_pluto**(8)), although the kernel supports SCTP/IPSEC.

---

# Kernel credentials

_Peios Kernel / Internals / Security_

> Linux credential lifetimes and their relationship to Peios tokens and access checks.

> **Peios:** This article explains Linux credential structures and their lifetimes. In Peios, native tokens, security descriptors and PIP determine authority; Unix fields and capability sets are compatibility views. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>). Examples of other LSMs describe upstream models.


<a id="rst-credentials-in-linux"></a>

By: David Howells &lt;[dhowells@redhat.com](<mailto:dhowells@redhat.com>)&gt;

<a id="rst-contents"></a>



<a id="rst-overview"></a>

## Overview

An access check relates a subject, an object and a requested operation. In
Peios, KACS evaluates native tokens, object security descriptors (SDs), enabled
privileges and, for process access, process integrity protection (PIP). A
task's Unix IDs and Linux capability sets are not substitutes for that context.

The Linux credential container remains important: `task_struct::real_cred`
is the task's objective credential set, while `task_struct::cred` is its
subjective set, used when it acts on objects. They normally agree, but trusted
kernel code can temporarily override the subjective credentials. KACS attaches
its credential security data, including a token reference and projected IDs,
through the LSM security blob. Native process state has its own lifetime and
synchronization; it is also referenced from task security data.

This does not mean that every Unix field is ignored. Accounting, network
protocols and some inherited subsystem checks still use IDs or mode bits.
For example, `/proc/sys` checks its table permissions against the current
effective UID and groups, with optional subsystem-specific permission callbacks.
Those checks coexist with native authorization where an operation has a KACS
gate. UID 0 is neither a universal bypass nor universally irrelevant.

<a id="rst-types-of-credentials"></a>

## Credential data

- **Native authority:** the effective token supplies the subject for KACS
  checks. Its identity, privileges and restrictions are distinct from numeric
  Unix IDs and stored Linux capability sets. Process SDs and PIP provide
  additional process-access constraints.
- **Unix compatibility fields:** `struct cred` retains real, effective, saved
  and filesystem IDs, supplementary groups and accounting references. The
  Peios `current_fsuid()` and `current_fsgid()` accessors use the KACS projection;
  reading `cred->fsuid` directly is not equivalent. Unix ID setters ordinarily
  preserve the existing identity; they are not a native token-installation or
  privilege-dropping interface.
- **Linux capability sets:** effective, permitted, inheritable, ambient and
  bounding sets remain represented. KACS capability checks consult the token
  or an explicit compatibility rule rather than treating these sets as native
  grants. `capset()` must retain the compatibility-allow bits in the effective,
  permitted and inheritable sets; clearing them fails. Changing other stored
  bits does not grant or remove native privileges. Bounding-set and ambient
  operations also have KACS guards.
- **Securebits:** these flags participate in inherited credential handling;
  they do not turn Unix compatibility credentials into native authority.
- **Keys and keyrings:** per-thread, per-process and session keyring references
  allow subsystems such as network filesystems to obtain authentication
  material. Key permissions and protocol credentials remain separate from a
  Peios token.

See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the
capability mapping, token-setter behaviour and configured LSMs. AF_KEY manages
networking key material through a separate socket API and is outside this
credential-container discussion.

<a id="rst-file-markings"></a>

## File markings and execution

Managed-file access uses the canonical SD (`security.peios.sd`, or
`system.ntfs_security` on NTFS3). Unix ownership, mode bits and protocol ACLs
may still be exposed, but copying those fields does not reproduce a native SD.
POSIX ACL updates are unsupported by the KACS hooks.

SUID/SGID markings and Linux file capabilities do not grant native token
privileges on `execve()`. Execution must pass file-execute and process security
baseline (PSB) checks. Verified Peios image signatures can establish a PIP
label, subject to the exec transition rules; a PIP label is not a replacement
token. Tracing and `no_new_privs` prevent raising that label above the current
one. Ordinary unsigned images may execute without a PIP label if the other
checks allow it; kernel-initiated usermode helpers require `PeiosTcb` trust.

<a id="rst-task-credentials"></a>

## Task Credentials

`struct cred` is a reference-counted container for Unix credential fields and references to groups, keys and LSM security data. Its publication rules govern the container; referenced native tokens and process-state objects also have their own lifetime and locking rules. Do not infer that every object reachable from a published credential is immutable.

Once a set of credentials has been prepared and committed, it may not be changed, barring the following exceptions:

> 1. its reference count may be changed;
>
> 2. the reference count on the group_info struct it points to may be changed;
>
> 3. the reference count on the security data it points to may be changed;
>
> 4. the reference count on any keyrings it points to may be changed;
>
> 5. any keyrings it points to may be revoked, expired or have their security attributes changed; and
>
> 6. the contents of any keyrings to which it points may be changed (the whole point of keyrings being a shared set of credentials, modifiable by anyone with appropriate access).

To alter anything in the cred struct, the copy-and-replace principle must be adhered to.  First take a copy, then alter the copy and then use RCU to change the task pointer to make it point to the new copy.  There are wrappers to aid with this (see below).

A task may only alter its \_own\_ credentials; it is no longer permitted for a task to alter another's credentials.  This means the `capset()` system call is no longer permitted to take any PID other than the one of the current process. Also `keyctl_instantiate()` and `keyctl_negate()` functions no longer permit attachment to process-specific keyrings in the requesting process as the instantiating process may need to create them.

<a id="rst-immutable-credentials"></a>

### Immutable Credentials

Once a set of credentials has been made public (by calling `commit_creds()` for example), it must be considered immutable, barring two exceptions:

> 1. The reference count may be altered.
>
> 2. While the keyring subscriptions of a set of credentials may not be changed, the keyrings subscribed to may have their contents altered.

To catch accidental credential alteration at compile time, struct task_struct has \_const\_ pointers to its credential sets, as does struct file.  Furthermore, certain functions such as `get_cred()` and `put_cred()` operate on const pointers, thus rendering casts unnecessary, but require to temporarily ditch the const qualification to be able to alter the reference count.

<a id="rst-accessing-task-credentials"></a>

### Accessing Task Credentials

A task can inspect its own current credential pointer without an RCU read-side lock. This does not remove the synchronization requirements of shared referenced objects or of a credential-changing operation. To obtain the current pointer, call:



```text
const struct cred *current_cred()
```

to get a pointer to its credentials structure, and it doesn't have to release it afterwards.

There are convenience wrappers for retrieving specific aspects of a task's credentials (the value is simply returned in each case):



```text
kuid_t current_uid(void)         Current's real UID
kgid_t current_gid(void)         Current's real GID
kuid_t current_euid(void)        Current's effective UID
kgid_t current_egid(void)        Current's effective GID
kuid_t current_fsuid(void)       Current's file access UID
kgid_t current_fsgid(void)       Current's file access GID
kernel_cap_t current_cap(void)  Current's effective capabilities
struct user_struct *current_user(void)  Current's user account
```

There are also convenience wrappers for retrieving specific associated pairs of a task's credentials:



```text
void current_uid_gid(kuid_t *, kgid_t *);
void current_euid_egid(kuid_t *, kgid_t *);
void current_fsuid_fsgid(kuid_t *, kgid_t *);
```

which return these pairs of values through their arguments after retrieving them from the current task's credentials.

In addition, there is a function for obtaining a reference on the current process's current set of credentials:



```text
const struct cred *get_current_cred(void);
```

and functions for getting references to one of the credentials that don't actually live in struct cred:



```text
struct user_struct *get_current_user(void);
struct group_info *get_current_groups(void);
```

which get references to the current process's user accounting structure and supplementary groups list respectively.

Once a reference has been obtained, it must be released with `put_cred()`, `free_uid()` or `put_group_info()` as appropriate.

<a id="rst-accessing-another-task-s-credentials"></a>

### Accessing Another Task's Credentials

While a task may access its own credentials without the need for locking, the same is not true of a task wanting to access another task's credentials.  It must use the RCU read lock and `rcu_dereference()`.

The `rcu_dereference()` is wrapped by:



```text
const struct cred *__task_cred(struct task_struct *task);
```

This should be used inside the RCU read lock, as in the following example:



```text
void foo(struct task_struct *t, struct foo_data *f)
{
        const struct cred *tcred;
        ...
        rcu_read_lock();
        tcred = __task_cred(t);
        f->uid = tcred->uid;
        f->gid = tcred->gid;
        f->groups = get_group_info(tcred->group_info);
        rcu_read_unlock();
        ...
}
```

Should it be necessary to hold another task's credentials for a long period of time, and possibly to sleep while doing so, then the caller should get a reference on them using:



```text
const struct cred *get_task_cred(struct task_struct *task);
```

This does all the RCU magic inside of it.  The caller must call put_cred() on the credentials so obtained when they're finished with.

> [!NOTE]
>
> The result of `__task_cred()` should not be passed directly to `get_cred()` as this may race with `commit_creds()`.

There are a couple of convenience functions to access bits of another task's credentials, hiding the RCU magic from the caller:



```text
kuid_t task_uid(task)            Task's real UID
kuid_t task_euid(task)           Task's effective UID
```

If the caller is holding the RCU read lock at the time anyway, then:



```text
__task_cred(task)->uid
__task_cred(task)->euid
```

should be used instead.  Similarly, if multiple aspects of a task's credentials need to be accessed, RCU read lock should be used, `__task_cred()` called, the result stored in a temporary pointer and then the credential aspects called from that before dropping the lock.  This prevents the potentially expensive RCU magic from being invoked multiple times.

Should some other single aspect of another task's credentials need to be accessed, then this can be used:



```text
task_cred_xxx(task, member)
```

where 'member' is a non-pointer member of the cred struct.  For instance:



```text
kuid_t task_cred_xxx(task, suid);
```

will retrieve 'struct cred::suid' from the task, doing the appropriate RCU magic.  This may not be used for pointer members as what they point to may disappear the moment the RCU read lock is dropped.

<a id="rst-altering-credentials"></a>

### Altering Credentials

Credential publication is performed by the task whose credentials change. Peios also has coordinated native token-installation paths; use their synchronization and authorization rules rather than writing another task's credential pointer. Copying or changing Unix fields alone does not install a native identity.

To alter the current process's credentials, a function should first prepare a new set of credentials by calling:



```text
struct cred *prepare_creds(void);
```

This allocates a duplicate of the current credentials, takes references to their shared members and calls the LSM preparation hook. It returns NULL on allocation or LSM preparation failure. It does not acquire a `cred_replace_mutex`; callers must obey the synchronization rules of the operation that is changing credentials.

The new credentials set should be altered appropriately, and any security checks and hooks done.  Both the current and the proposed sets of credentials are available for this purpose as current_cred() will return the current set still at this point.

When replacing the group list, the new list must be sorted before it is added to the credential, as a binary search is used to test for membership.  In practice, this means groups_sort() should be called before set_groups() or set_current_groups(). groups_sort() must not be called on a `struct group_info` which is shared as it may permute elements as part of the sorting process even if the array is already sorted.

When the credential set is ready, it should be committed to the current process by calling:



```text
int commit_creds(struct cred *new);
```

This updates credential-related accounting and process state, then publishes the new objective and subjective credentials with `rcu_assign_pointer()`. It notifies interested subsystems and drops the old credential references. It does not release a credential-replacement mutex.

This function is guaranteed to return 0, so that it can be tail-called at the end of such functions as `sys_setresuid()`.

Note that this function consumes the caller's reference to the new credentials. The caller should \_not\_ call `put_cred()` on the new credentials afterwards.

Furthermore, once this function has been called on a new set of credentials, those credentials may \_not\_ be changed further.

Should the security checks fail or some other error occur after `prepare_creds()` has been called, then the following function should be invoked:



```text
void abort_creds(struct cred *new);
```

This drops the reference to the uncommitted new credentials. It does not release a credential-replacement mutex.

A credential-changing operation must perform its real authorization checks before `commit_creds()`, and call `abort_creds()` on failure. There is no generic `security_alter_suid()` hook. Unix ID changes must follow the existing syscall and LSM fixup paths; native token changes must use the native token-installation path.

<a id="rst-managing-credentials"></a>

### Managing Credentials

There are some functions to help manage credentials:

> - `void put_cred(const struct cred *cred);`
>
>   > This releases a reference to the given set of credentials.  If the reference count reaches zero, the credentials will be scheduled for destruction by the RCU system.
>
> - `const struct cred *get_cred(const struct cred *cred);`
>
>   > This gets a reference on a live set of credentials, returning a pointer to that set of credentials.

<a id="rst-open-file-credentials"></a>

## Open file credentials

An opened `struct file` holds a reference to the opening credentials in
`f_cred`. The pointer remains stable for the file's lifetime, so accessing the
container does not require a fresh RCU lookup. Referenced objects retain their
own synchronization rules. Network filesystems can use these credentials when
authenticating operations to a remote server.

KACS separately records a granted-access snapshot on a managed file handle.
Later operations check the rights required by that operation; an SD change is
not general revocation of existing handles. `SCM_RIGHTS` transfers the existing
grant rather than authorizing a new open under the receiver's token. Internal
copy-up handles are rejected by the receive hook.

Do not universally substitute `f_cred` for the current subject in access checks.
Some checks deliberately use the current effective token, including the sysfs
write gate and continuous-access auditing. Follow the specific handle or
operation contract. Likewise, direct reads of `f_cred->fsuid` do not provide the
Peios projected-ID semantics of the current-credential accessors.

<a id="rst-overriding-the-vfs-s-use-of-credentials"></a>

## Overriding the VFS's use of credentials

Trusted kernel code can temporarily install subjective credentials with
`override_creds()` and restore them with `revert_creds()`. This is used by
stacking filesystems and other operations that act in a saved context. The
override must carry the correct LSM subject and obey its lifetime rules;
changing numeric UID fields alone is not a KACS subject switch.

In Peios, `access()` and `faccessat()` do not use the upstream real-UID
credential-override path: that code is excluded under `CONFIG_SECURITY_PKM`.
They perform the check in the current effective context. They therefore must
not be used as a test of what a different native token could access.

## Peios implementation details

<a id="trm-3-10-1"></a>

KACS tokens are the sole identity-based authorization mechanism, and
Linux applications do not know tokens exist. They call `getuid()`,
`getgid()` and `getgroups()`, read `/proc/self/status`, and assume
those numbers determine their access. KACS projects token identity
onto standard Linux credentials so unmodified applications work.

When a token is installed on a process, the process's Linux
credentials are set to match. <a id="cite-cred.projection.on-token-install"></a> The numbers themselves are **already on
the token**: the user SID's projected uid, the primary group SID's
projected gid, and a projected supplementary gid per group SID are all
computed by authd when the token is minted, and KACS copies them. <a id="cite-cred.projection.uid-from-token"></a>

**KACS never resolves a SID to a number itself.** It holds no directory
handle and consults nothing at install time — which is what makes
projection cheap enough to do on every credential change, and what
keeps a name-service outage from being able to change what a running
process may do.

How a SID becomes a number is therefore not KACS's rule to state, and
this chapter deliberately does not restate it. The authority is the
principal source interface's numeric scope (PSPU [Overview](</kernel/internals/kmes/overview.md#trm-2-1>)): identifiers are
**computed** — an authority grants a source a band `(base, count)` and
derives `base + r` from a relative identifier — rather than looked up
per principal, and a source's assertion outside its band is refused
rather than clamped.

`65534` does appear in KACS, but not as a "no attribute was set"
fallback: it is `ANONYMOUS_PROJECTED_ID`, what the projected-id
accessors return for the anonymous identity and for an invalid token
pointer. <a id="cite-cred.projection.anonymous-sentinel"></a> It is a sentinel for *no identity*, not a default for an
identity whose number could not be found.

The consequences are mostly convenient ones. No process runs as UID 0
unless it holds the SYSTEM token — enforced, not merely expected: a
token creation naming a projected UID of 0 with any user SID other
than `S-1-5-18` is rejected, and the projection path refuses it again
at install time. <a id="cite-cred.projection.uid0-system-only"></a> Home directories work naturally, because
`getpwuid(getuid())` returns the right answer when the UID is real and
consistent with NSS. And different services get different UIDs, which
is incidental defence in depth alongside KACS's own enforcement.

<a id="trm-3-10-1-1"></a>

## Projection is one-way <a id="cite-cred.projection.one-way"></a>

Token state flows into credential fields and never the reverse. The
projected credentials are observational compatibility data; the token
is the authority. The `setuid` family restores the old credential
rather than deriving a token from it ([setuid Behaviour](</kernel/internals/kacs/linux-credentials/setuid-behaviour.md#trm-3-10-3>)).

Projection reflects **all** groups regardless of enabled state, so
adjusting groups never triggers recalculation. <a id="cite-cred.projection.all-groups"></a>

Projected credentials reflect the **effective** token — the
impersonated one during impersonation, the primary one otherwise. <a id="cite-cred.projection.effective-token"></a> When
a service thread impersonates a client and creates a file, the file is
owned by the client's projected UID, quota is charged to the client,
and audit attributes to the client.

The two accessors deliberately disagree during impersonation.
`current_fsuid()` reads the projected UID from the *effective*
credential, so it yields the client's UID; `getuid()` reads the
*primary* credential's UID, so it yields the service's. During
impersonation `getuid()` returns the service and `current_fsuid()`
returns the client, and that is the intended behaviour rather than an
inconsistency. <a id="cite-cred.projection.getuid-vs-fsuid"></a> Only `getuid()` and `getgid()` are redirected to the
primary credential; `geteuid()` and `getegid()` keep their Linux
meaning and follow the effective credential, so during impersonation
they report the client.

One caveat applies to a credential carrying no token at all — a blank
credential, or one created before KACS initialised. `current_fsuid()`
falls back to `cred->fsuid` in that case, and the capability
switchboard denies before consulting the ALLOW list ([DAC Neutralisation](</kernel/internals/kacs/linux-credentials/dac-neutralisation.md#trm-3-10-2>)), so
Linux DAC becomes authoritative for such a task. <a id="cite-cred.projection.tokenless-dac-fallback"></a>

<a id="trm-3-10-1-2"></a>

## Precomputed values

Every token carries precomputed projected UID and GID values,
calculated by authd at creation and stored on the token. KACS never
resolves a SID-to-UID mapping at runtime; the accessors are pure field
reads.

Because SIDs are one namespace while Linux UIDs and GIDs are two,
authd allocates from a **single unified counter** across all principal
types rather than a separate one per namespace, so every SID projects
to a unique number whichever Linux namespace it lands in. A user and a
group can never collide on a number, which is what lets one SID answer
both `getuid()` and `getgid()` questions without ambiguity.

---

# Digital Signature Verification API

_Peios Kernel / Internals / Security_

> Digital signature verification API provides a method to verify digital signature. Currently digital signatures are used by the IMA/EVM integrity protection subsystem.

<a id="rst-digital-signature-verification-api"></a>

**Author:** Dmitry Kasatkin

**Date:** 06.10.2011

<!-- CONTENTS

1. Introduction
2. API
3. User-space utilities -->

<a id="rst-introduction"></a>

## Introduction

Digital signature verification API provides a method to verify digital signature. Currently digital signatures are used by the IMA/EVM integrity protection subsystem.

Digital signature verification is implemented using cut-down kernel port of GnuPG multi-precision integers (MPI) library. The kernel port provides memory allocation errors handling, has been refactored according to kernel coding style, and checkpatch.pl reported errors and warnings have been fixed.

Public key and signature consist of header and MPIs:



```text
struct pubkey_hdr {
        uint8_t         version;        /* key format version */
        time_t          timestamp;      /* key made, always 0 for now */
        uint8_t         algo;
        uint8_t         nmpi;
        char            mpi[0];
} __packed;

struct signature_hdr {
        uint8_t         version;        /* signature format version */
        time_t          timestamp;      /* signature made */
        uint8_t         algo;
        uint8_t         hash;
        uint8_t         keyid[8];
        uint8_t         nmpi;
        char            mpi[0];
} __packed;
```

keyid equals to SHA1\[12-19\] over the total key content. Signature header is used as an input to generate a signature. Such approach insures that key or signature header could not be changed. It protects timestamp from been changed and can be used for rollback protection.

<a id="rst-api"></a>

## API

API currently includes only 1 function:



```text
digsig_verify() - digital signature verification with public key


/**
* digsig_verify() - digital signature verification with public key
* @keyring:     keyring to search key in
* @sig: digital signature
* @sigen:       length of the signature
* @data:        data
* @datalen:     length of the data
* @return:      0 on success, -EINVAL otherwise
*
* Verifies data integrity against digital signature.
* Currently only RSA is supported.
* Normally hash of the content is used as a data for this function.
*
*/
int digsig_verify(struct key *keyring, const char *sig, int siglen,
                  const char *data, int datalen);
```

<a id="rst-user-space-utilities"></a>

## User-space utilities

The signing and key management utilities evm-utils provide functionality to generate signatures, to load keys into the kernel keyring. Keys can be in PEM or converted to the kernel format. When the key is added to the kernel keyring, the keyid defines the name of the key: 5D2B05FC633EE3E8 in the example below.

Here is example output of the keyctl utility:



```text
$ keyctl show
Session Keyring
-3 --alswrv      0     0  keyring: _ses
603976250 --alswrv      0    -1   \_ keyring: _uid.0
817777377 --alswrv      0     0       \_ user: kmk
891974900 --alswrv      0     0       \_ encrypted: evm-key
170323636 --alswrv      0     0       \_ keyring: _module
548221616 --alswrv      0     0       \_ keyring: _ima
128198054 --alswrv      0     0       \_ keyring: _evm

$ keyctl list 128198054
1 key in keyring:
620789745: --alswrv     0     0 user: 5D2B05FC633EE3E8
```

---

# Integrity Policy Enforcement (IPE) - Kernel Documentation

_Peios Kernel / Internals / Security_

> The original issue that prompted IPE's implementation was the creation of a locked-down system. This system would be born-secure, and have strong integrity guarantees over both the executable code, and specific data files on the system,…

> **Peios:** The LSM examples here describe upstream interfaces and implementation choices. Peios configures `landlock,lockdown,integrity,pkm`; SELinux, Smack, AppArmor and their attribute/policy interfaces are not the active native access model. Use the native token/SD interfaces for Peios authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-integrity-policy-enforcement-ipe-kernel-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

> [!NOTE]
>
> This is documentation targeted at developers, instead of administrators. If you're looking for documentation on the usage of IPE, please see [IPE admin guide](</kernel/administration/admin-guide/lsm/ipe.md>).

<a id="rst-historical-motivation"></a>

## Historical Motivation

The original issue that prompted IPE's implementation was the creation of a locked-down system. This system would be born-secure, and have strong integrity guarantees over both the executable code, and specific *data files* on the system, that were critical to its function. These specific data files would not be readable unless they passed integrity policy. A mandatory access control system would be present, and as a result, xattrs would have to be protected. This lead to a selection of what would provide the integrity claims. At the time, there were two main mechanisms considered that could guarantee integrity for the system with these requirements:

> 1. IMA + EVM Signatures
>
> 2. DM-Verity

Both options were carefully considered, however the choice to use DM-Verity over IMA+EVM as the *integrity mechanism* in the original use case of IPE was due to three main reasons:

> 1. Protection of additional attack vectors:
>
> > - With IMA+EVM, without an encryption solution, the system is vulnerable to offline attack against the aforementioned specific data files.
> >
> >   Unlike executables, read operations (like those on the protected data files), cannot be enforced to be globally integrity verified. This means there must be some form of selector to determine whether a read should enforce the integrity policy, or it should not.
> >
> >   At the time, this was done with mandatory access control labels. An IMA policy would indicate what labels required integrity verification, which presented an issue: EVM would protect the label, but if an attacker could modify filesystem offline, the attacker could wipe all the xattrs - including the SELinux labels that would be used to determine whether the file should be subject to integrity policy.
> >
> >   With DM-Verity, as the xattrs are saved as part of the Merkel tree, if offline mount occurs against the filesystem protected by dm-verity, the checksum no longer matches and the file fails to be read.
> >
> > - As userspace binaries are paged in Linux, dm-verity also offers the additional protection against a hostile block device. In such an attack, the block device reports the appropriate content for the IMA hash initially, passing the required integrity check. Then, on the page fault that accesses the real data, will report the attacker's payload. Since dm-verity will check the data when the page fault occurs (and the disk access), this attack is mitigated.
>
> 2. Performance:
>
> > - dm-verity provides integrity verification on demand as blocks are read versus requiring the entire file being read into memory for validation.
>
> 3. Simplicity of signing:
>
> > - No need for two signatures (IMA, then EVM): one signature covers an entire block device.
> >
> > - Signatures can be stored externally to the filesystem metadata.
> >
> > - The signature supports an x.509-based signing infrastructure.

The next step was to choose a *policy* to enforce the integrity mechanism. The minimum requirements for the policy were:

> 1. The policy itself must be integrity verified (preventing trivial attack against it).
>
> 2. The policy itself must be resistant to rollback attacks.
>
> 3. The policy enforcement must have a permissive-like mode.
>
> 4. The policy must be able to be updated, in its entirety, without a reboot.
>
> 5. Policy updates must be atomic.
>
> 6. The policy must support *revocations* of previously authored components.
>
> 7. The policy must be auditable, at any point-of-time.

IMA, as the only integrity policy mechanism at the time, was considered against these list of requirements, and did not fulfill all of the minimum requirements. Extending IMA to cover these requirements was considered, but ultimately discarded for a two reasons:

> 1. Regression risk; many of these changes would result in dramatic code changes to IMA, which is already present in the kernel, and therefore might impact users.
>
> 2. IMA was used in the system for measurement and attestation; separation of measurement policy from local integrity policy enforcement was considered favorable.

Due to these reasons, it was decided that a new LSM should be created, whose responsibility would be only the local integrity policy enforcement.

<a id="rst-role-and-scope"></a>

## Role and Scope

IPE, as its name implies, is fundamentally an integrity policy enforcement solution; IPE does not mandate how integrity is provided, but instead leaves that decision to the system administrator to set the security bar, via the mechanisms that they select that suit their individual needs. There are several different integrity solutions that provide a different level of security guarantees; and IPE allows sysadmins to express policy for theoretically all of them.

IPE does not have an inherent mechanism to ensure integrity on its own. Instead, there are more effective layers available for building systems that can guarantee integrity. It's important to note that the mechanism for proving integrity is independent of the policy for enforcing that integrity claim.

Therefore, IPE was designed around:

> 1. Easy integrations with integrity providers.
>
> 2. Ease of use for platform administrators/sysadmins.

<a id="rst-design-rationale"></a>

## Design Rationale:

IPE was designed after evaluating existing integrity policy solutions in other operating systems and environments. In this survey of other implementations, there were a few pitfalls identified:

> 1. Policies were not readable by humans, usually requiring a binary intermediary format.
>
> 2. A single, non-customizable action was implicitly taken as a default.
>
> 3. Debugging the policy required manual steps to determine what rule was violated.
>
> 4. Authoring a policy required an in-depth knowledge of the larger system, or operating system.

IPE attempts to avoid all of these pitfalls.

<a id="rst-policy"></a>

### Policy

<a id="rst-plain-text"></a>

#### Plain Text

IPE's policy is plain-text. This introduces slightly larger policy files than other LSMs, but solves two major problems that occurs with some integrity policy solutions on other platforms.

The first issue is one of code maintenance and duplication. To author policies, the policy has to be some form of string representation (be it structured, through XML, JSON, YAML, etcetera), to allow the policy author to understand what is being written. In a hypothetical binary policy design, a serializer is necessary to write the policy from the human readable form, to the binary form, and a deserializer is needed to interpret the binary form into a data structure in the kernel.

Eventually, another deserializer will be needed to transform the binary from back into the human-readable form with as much information preserved. This is because a user of this access control system will have to keep a lookup table of a checksum and the original file itself to try to understand what policies have been deployed on this system and what policies have not. For a single user, this may be alright, as old policies can be discarded almost immediately after the update takes hold. For users that manage computer fleets in the thousands, if not hundreds of thousands, with multiple different operating systems, and multiple different operational needs, this quickly becomes an issue, as stale policies from years ago may be present, quickly resulting in the need to recover the policy or fund extensive infrastructure to track what each policy contains.

With now three separate serializer/deserializers, maintenance becomes costly. If the policy avoids the binary format, there is only one required serializer: from the human-readable form to the data structure in kernel, saving on code maintenance, and retaining operability.

The second issue with a binary format is one of transparency. As IPE controls access based on the trust of the system's resources, it's policy must also be trusted to be changed. This is done through signatures, resulting in needing signing as a process. Signing, as a process, is typically done with a high security bar, as anything signed can be used to attack integrity enforcement systems. It is also important that, when signing something, that the signer is aware of what they are signing. A binary policy can cause obfuscation of that fact; what signers see is an opaque binary blob. A plain-text policy, on the other hand, the signers see the actual policy submitted for signing.

<a id="rst-boot-policy"></a>

### Boot Policy

IPE, if configured appropriately, is able to enforce a policy as soon as a kernel is booted and usermode starts. That implies some level of storage of the policy to apply the minute usermode starts. Generally, that storage can be handled in one of three ways:

> 1. The policy file(s) live on disk and the kernel loads the policy prior to an code path that would result in an enforcement decision.
>
> 2. The policy file(s) are passed by the bootloader to the kernel, who parses the policy.
>
> 3. There is a policy file that is compiled into the kernel that is parsed and enforced on initialization.

The first option has problems: the kernel reading files from userspace is typically discouraged and very uncommon in the kernel.

The second option also has problems: Linux supports a variety of bootloaders across its entire ecosystem - every bootloader would have to support this new methodology or there must be an independent source. It would likely result in more drastic changes to the kernel startup than necessary.

The third option is the best but it's important to be aware that the policy will take disk space against the kernel it's compiled in. It's important to keep this policy generalized enough that userspace can load a new, more complicated policy, but restrictive enough that it will not overauthorize and cause security issues.

The initramfs provides a way that this bootup path can be established. The kernel starts with a minimal policy, that trusts the initramfs only. Inside the initramfs, when the real rootfs is mounted, but not yet transferred to, it deploys and activates a policy that trusts the new root filesystem. This prevents overauthorization at any step, and keeps the kernel policy to a minimal size.

<a id="rst-startup"></a>

#### Startup

Not every system, however starts with an initramfs, so the startup policy compiled into the kernel will need some flexibility to express how trust is established for the next phase of the bootup. To this end, if we just make the compiled-in policy a full IPE policy, it allows system builders to express the first stage bootup requirements appropriately.

<a id="rst-updatable-rebootless-policy"></a>

### Updatable, Rebootless Policy

As requirements change over time (vulnerabilities are found in previously trusted applications, keys roll, etcetera). Updating a kernel to change the meet those security goals is not always a suitable option, as updates are not always risk-free, and blocking a security update leaves systems vulnerable. This means IPE requires a policy that can be completely updated (allowing revocations of existing policy) from a source external to the kernel (allowing policies to be updated without updating the kernel).

Additionally, since the kernel is stateless between invocations, and reading policy files off the disk from kernel space is a bad idea(tm), then the policy updates have to be done rebootlessly.

To allow an update from an external source, it could be potentially malicious, so this policy needs to have a way to be identified as trusted. This is done via a signature chained to a trust source in the kernel. Arbitrarily, this is  the `SYSTEM_TRUSTED_KEYRING`, a keyring that is initially populated at kernel compile-time, as this matches the expectation that the author of the compiled-in policy described above is the same entity that can deploy policy updates.

<a id="rst-anti-rollback-anti-replay"></a>

### Anti-Rollback / Anti-Replay

Over time, vulnerabilities are found and trusted resources may not be trusted anymore. IPE's policy has no exception to this. There can be instances where a mistaken policy author deploys an insecure policy, before correcting it with a secure policy.

Assuming that as soon as the insecure policy is signed, and an attacker acquires the insecure policy, IPE needs a way to prevent rollback from the secure policy update to the insecure policy update.

Initially, IPE's policy can have a policy_version that states the minimum required version across all policies that can be active on the system. This will prevent rollback while the system is live.

> [!WARNING]
>
> However, since the kernel is stateless across boots, this policy version will be reset to 0.0.0 on the next boot. System builders need to be aware of this, and ensure the new secure policies are deployed ASAP after a boot to ensure that the window of opportunity is minimal for an attacker to deploy the insecure policy.

<a id="rst-implicit-actions"></a>

### Implicit Actions:

The issue of implicit actions only becomes visible when you consider a mixed level of security bars across multiple operations in a system. For example, consider a system that has strong integrity guarantees over both the executable code, and specific *data files* on the system, that were critical to its function. In this system, three types of policies are possible:

> 1. A policy in which failure to match any rules in the policy results in the action being denied.
>
> 2. A policy in which failure to match any rules in the policy results in the action being allowed.
>
> 3. A policy in which the action taken when no rules are matched is specified by the policy author.

The first option could make a policy like this:



```text
op=EXECUTE integrity_verified=YES action=ALLOW
```

In the example system, this works well for the executables, as all executables should have integrity guarantees, without exception. The issue becomes with the second requirement about specific data files. This would result in a policy like this (assuming each line is evaluated in order):



```text
op=EXECUTE integrity_verified=YES action=ALLOW

op=READ integrity_verified=NO label=critical_t action=DENY
op=READ action=ALLOW
```

This is somewhat clear if you read the docs, understand the policy is executed in order and that the default is a denial; however, the last line effectively changes that default to an ALLOW. This is required, because in a realistic system, there are some unverified reads (imagine appending to a log file).

The second option, matching no rules results in an allow, is clearer for the specific data files:



```text
op=READ integrity_verified=NO label=critical_t action=DENY
```

And, like the first option, falls short with the execution scenario, effectively needing to override the default:



```text
op=EXECUTE integrity_verified=YES action=ALLOW
op=EXECUTE action=DENY

op=READ integrity_verified=NO label=critical_t action=DENY
```

This leaves the third option. Instead of making users be clever and override the default with an empty rule, force the end-user to consider what the appropriate default should be for their scenario and explicitly state it:



```text
DEFAULT op=EXECUTE action=DENY
op=EXECUTE integrity_verified=YES action=ALLOW

DEFAULT op=READ action=ALLOW
op=READ integrity_verified=NO label=critical_t action=DENY
```

<a id="rst-policy-debugging"></a>

### Policy Debugging:

When developing a policy, it is useful to know what line of the policy is being violated to reduce debugging costs; narrowing the scope of the investigation to the exact line that resulted in the action. Some integrity policy systems do not provide this information, instead providing the information that was used in the evaluation. This then requires a correlation with the policy to evaluate what went wrong.

Instead, IPE just emits the rule that was matched. This limits the scope of the investigation to the exact policy line (in the case of a specific rule), or the section (in the case of a DEFAULT). This decreases iteration and investigation times when policy failures are observed while evaluating policies.

IPE's policy engine is also designed in a way that it makes it obvious to a human of how to investigate a policy failure. Each line is evaluated in the sequence that is written, so the algorithm is very simple to follow for humans to recreate the steps and could have caused the failure. In other surveyed systems, optimizations occur (sorting rules, for instance) when loading the policy. In those systems, it requires multiple steps to debug, and the algorithm may not always be clear to the end-user without reading the code first.

<a id="rst-simplified-policy"></a>

### Simplified Policy:

Finally, IPE's policy is designed for sysadmins, not kernel developers. Instead of covering individual LSM hooks (or syscalls), IPE covers operations. This means instead of sysadmins needing to know that the syscalls `mmap`, `mprotect`, `execve`, and `uselib` must have rules protecting them, they must simple know that they want to restrict code execution. This limits the amount of bypasses that could occur due to a lack of knowledge of the underlying system; whereas the maintainers of IPE, being kernel developers can make the correct choice to determine whether something maps to these operations, and under what conditions.

<a id="rst-implementation-notes"></a>

## Implementation Notes

<a id="rst-anonymous-memory"></a>

### Anonymous Memory

Anonymous memory isn't treated any differently from any other access in IPE. When anonymous memory is mapped with `+X`, it still comes into the `file_mmap` or `file_mprotect` hook, but with a `NULL` file object. This is submitted to the evaluation, like any other file. However, all current trust properties will evaluate to false, as they are all file-based and the operation is not associated with a file.

> [!WARNING]
>
> This also occurs with the `kernel_load_data` hook, when the kernel is loading data from a userspace buffer that is not backed by a file. In this scenario all current trust properties will also evaluate to false.

<a id="rst-securityfs-interface"></a>

### Securityfs Interface

The per-policy securityfs tree is somewhat unique. For example, for a standard securityfs policy tree:



```text
MyPolicy
  |- active
  |- delete
  |- name
  |- pkcs7
  |- policy
  |- update
  |- version
```

The policy is stored in the `->i_private` data of the MyPolicy inode.

<a id="rst-tests"></a>

## Tests

IPE has KUnit Tests for the policy parser. Recommended kunitconfig:



```text
CONFIG_KUNIT=y
CONFIG_SECURITY=y
CONFIG_SECURITYFS=y
CONFIG_PKCS7_MESSAGE_PARSER=y
CONFIG_SYSTEM_DATA_VERIFICATION=y
CONFIG_FS_VERITY=y
CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y
CONFIG_BLOCK=y
CONFIG_MD=y
CONFIG_BLK_DEV_DM=y
CONFIG_DM_VERITY=y
CONFIG_DM_VERITY_VERIFY_ROOTHASH_SIG=y
CONFIG_NET=y
CONFIG_AUDIT=y
CONFIG_AUDITSYSCALL=y
CONFIG_BLK_DEV_INITRD=y

CONFIG_SECURITY_IPE=y
CONFIG_IPE_PROP_DM_VERITY=y
CONFIG_IPE_PROP_DM_VERITY_SIGNATURE=y
CONFIG_IPE_PROP_FS_VERITY=y
CONFIG_IPE_PROP_FS_VERITY_BUILTIN_SIG=y
CONFIG_SECURITY_IPE_KUNIT_TEST=y
```

In addition, IPE has a python based integration [test suite](<https://github.com/microsoft/ipe/tree/test-suite>)<a id="rst-test-suite"></a> that can test both user interfaces and enforcement functionalities.

---

# Landlock LSM: kernel documentation

_Peios Kernel / Internals / Security_

> Landlock's goal is to create scoped access-control (i.e. sandboxing). To harden a whole system, this feature should be available to any process, including unprivileged ones. Because such a process may be compromised or backdoored (i.e.…

<a id="rst-landlock-lsm-kernel-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<!-- Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net> -->

<!-- Copyright © 2019-2020 ANSSI -->

**Author:** Mickaël Salaün

**Date:** September 2025

Landlock's goal is to create scoped access-control (i.e. sandboxing).  To harden a whole system, this feature should be available to any process, including unprivileged ones.  Because such a process may be compromised or backdoored (i.e. untrusted), Landlock's features must be safe to use from the kernel and other processes point of view.  Landlock's interface must therefore expose a minimal attack surface.

Landlock is designed to be usable by unprivileged processes while following the system security policy enforced by other access control mechanisms (e.g. DAC, LSM).  A Landlock rule shall not interfere with other access-controls enforced on the system, only add more restrictions.

Any user can enforce Landlock rulesets on their processes.  They are merged and evaluated against inherited rulesets in a way that ensures that only more constraints can be added.

User space documentation can be found here: [Documentation/userspace-api/landlock.rst](/kernel/userspace/userspace-api/security/landlock.md).

<a id="rst-guiding-principles-for-safe-access-controls"></a>

## Guiding principles for safe access controls

- A Landlock rule shall be focused on access control on kernel objects instead of syscall filtering (i.e. syscall arguments), which is the purpose of seccomp-bpf.

- To avoid multiple kinds of side-channel attacks (e.g. leak of security policies, CPU-based attacks), Landlock rules shall not be able to programmatically communicate with user space.

- Kernel access check shall not slow down access request from unsandboxed processes.

- Computation related to Landlock operations (e.g. enforcing a ruleset) shall only impact the processes requesting them.

- Resources (e.g. file descriptors) directly obtained from the kernel by a sandboxed process shall retain their scoped accesses (at the time of resource acquisition) whatever process uses them. Cf. [File descriptor access rights](<#rst-file-descriptor-access-rights>).

- Access denials shall be logged according to system and Landlock domain configurations.  Log entries must contain information about the cause of the denial and the owner of the related security policy.  Such log generation should have a negligible performance and memory impact on allowed requests.

<a id="rst-design-choices"></a>

## Design choices

<a id="rst-inode-access-rights"></a>

### Inode access rights

All access rights are tied to an inode and what can be accessed through it. Reading the content of a directory does not imply to be allowed to read the content of a listed inode.  Indeed, a file name is local to its parent directory, and an inode can be referenced by multiple file names thanks to (hard) links.  Being able to unlink a file only has a direct impact on the directory, not the unlinked inode.  This is the reason why `LANDLOCK_ACCESS_FS_REMOVE_FILE` or `LANDLOCK_ACCESS_FS_REFER` are not allowed to be tied to files but only to directories.

<a id="rst-file-descriptor-access-rights"></a>

### File descriptor access rights

Access rights are checked and tied to file descriptors at open time.  The underlying principle is that equivalent sequences of operations should lead to the same results, when they are executed under the same Landlock domain.

Taking the `LANDLOCK_ACCESS_FS_TRUNCATE` right as an example, it may be allowed to open a file for writing without being allowed to `ftruncate` the resulting file descriptor if the related file hierarchy doesn't grant that access right.  The following sequences of operations have the same semantic and should then have the same result:

- `truncate(path);`

- `int fd = open(path, O_WRONLY); ftruncate(fd); close(fd);`

Similarly to file access modes (e.g. `O_RDWR`), Landlock access rights attached to file descriptors are retained even if they are passed between processes (e.g. through a Unix domain socket).  Such access rights will then be enforced even if the receiving process is not sandboxed by Landlock.  Indeed, this is required to keep access controls consistent over the whole system, and this avoids unattended bypasses through file descriptor passing (i.e. confused deputy attack).

<a id="rst-tests"></a>

## Tests

Userspace tests for backward compatibility, ptrace restrictions and filesystem support can be found here: [tools/testing/selftests/landlock/](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/landlock/>).

<a id="rst-kernel-structures"></a>

## Kernel structures

<a id="rst-object"></a>

### Object


#### <a id="c-struct-landlock_object_underops"></a>`struct landlock_object_underops`

Operations on an underlying object

**Definition**

```c
struct landlock_object_underops {
    void (*release)(struct landlock_object *const object) __releases(object->lock);
};
```

**Members**

- `release`: Releases the underlying object (e.g. [`iput()`](/kernel/internals/filesystems/api-summary.md#c-iput) for an inode).

#### <a id="c-struct-landlock_object"></a>`struct landlock_object`

Security blob tied to a kernel object

**Definition**

```c
struct landlock_object {
    refcount_t usage;
    spinlock_t lock;
    void *underobj;
    union {
        struct rcu_head rcu_free;
        const struct landlock_object_underops *underops;
    };
};
```

**Members**

- `usage`: This counter is used to tie an object to the rules matching
  it or to keep it alive while adding a new rule.  If this counter
  reaches zero, this struct must not be modified, but this counter can
  still be read from within an RCU read-side critical section.  When
  adding a new rule to an object with a usage counter of zero, we must
  wait until the pointer to this object is set to NULL (or recycled).
- `lock`: Protects against concurrent modifications.  This lock must be
  held from the time **usage** drops to zero until any weak references
  from **underobj** to this object have been cleaned up.

  Lock ordering: inode->i_lock nests inside this.
- `underobj`: Used when cleaning up an object and to mark an object as
  tied to its underlying kernel structure.  This pointer is protected
  by **lock**.  Cf. `landlock_release_inodes()` and `release_inode()`.
- `{unnamed_union}`: anonymous
- `rcu_free`: Enables lockless use of **usage**, **lock** and
  **underobj** from within an RCU read-side critical section.
  **rcu_free** and **underops** are only used by
  `landlock_put_object()`.
- `underops`: Enables `landlock_put_object()` to release the
  underlying object (e.g. inode).

**Description**

The goal of this structure is to enable to tie a set of ephemeral access
rights (pertaining to different domains) to a kernel object (e.g an inode)
in a safe way.  This implies to handle concurrent use and modification.

The lifetime of a [`struct landlock_object`](#c-struct-landlock_object) depends on the rules referring to
it.


<a id="rst-filesystem"></a>

### Filesystem


#### <a id="c-struct-landlock_inode_security"></a>`struct landlock_inode_security`

Inode security blob

**Definition**

```c
struct landlock_inode_security {
    struct landlock_object  *object;
};
```

**Members**

- `object`: Weak pointer to an allocated object.  All assignments of a
  new object are protected by the underlying inode->i_lock.  However,
  atomically disassociating **object** from the inode is only protected
  by **object->lock**, from the time **object**'s usage refcount drops to
  zero to the time this pointer is nulled out (cf. `release_inode()` and
  `hook_sb_delete()`).  Indeed, such disassociation doesn't require
  inode->i_lock thanks to the careful [`rcu_access_pointer()`](/kernel/internals/core-api/kernel-api.md#c-rcu_access_pointer) check
  performed by `get_inode_object()`.

**Description**

Enable to reference a [`struct landlock_object`](#c-struct-landlock_object) tied to an inode (i.e.
underlying object).

#### <a id="c-struct-landlock_file_security"></a>`struct landlock_file_security`

File security blob

**Definition**

```c
struct landlock_file_security {
        access_mask_t allowed_access;
    #ifdef CONFIG_AUDIT;
        deny_masks_t deny_masks;
        u8 fown_layer;
    #endif;
        struct landlock_cred_security fown_subject;
};
```

**Members**

- `allowed_access`: Access rights that were available at the time of
  opening the file. This is not necessarily the full set of access
  rights available at that time, but it's the necessary subset as
  needed to authorize later operations on the open file.
- `deny_masks`: Domain layer levels that deny an optional access (see
  _LANDLOCK_ACCESS_FS_OPTIONAL).
- `fown_layer`: Layer level of **fown_subject->domain** with
  LANDLOCK_SCOPE_SIGNAL.
- `fown_subject`: Landlock credential of the task that set the PID that
  may receive a signal e.g., SIGURG when writing MSG_OOB to the
  related socket.  This pointer is protected by the related
  file->f_owner->lock, as for fown_struct's members: pid, uid, and
  euid.

**Description**

This information is populated when opening a file in hook_file_open, and
tracks the relevant Landlock access rights that were available at the time
of opening the file. Other LSM hooks use these rights in order to authorize
operations on already opened files.

#### <a id="c-struct-landlock_superblock_security"></a>`struct landlock_superblock_security`

Superblock security blob

**Definition**

```c
struct landlock_superblock_security {
    atomic_long_t inode_refs;
};
```

**Members**

- `inode_refs`: Number of pending inodes (from this superblock) that
  are being released by `release_inode()`.
  Cf. struct super_block->s_fsnotify_inode_refs .

**Description**

Enable `hook_sb_delete()` to wait for concurrent calls to `release_inode()`.


<a id="rst-process-credential"></a>

### Process credential


#### <a id="c-struct-landlock_cred_security"></a>`struct landlock_cred_security`

Credential security blob

**Definition**

```c
struct landlock_cred_security {
        struct landlock_ruleset *domain;
    #ifdef CONFIG_AUDIT;
        u16 domain_exec;
        u8 log_subdomains_off : 1;
    #endif;
};
```

**Members**

- `domain`: Immutable ruleset enforced on a task.
- `domain_exec`: Bitmask identifying the domain layers that were enforced by
  the current task's executed file (i.e. no new execve(2) since
  landlock_restrict_self(2)).
- `log_subdomains_off`: Set if the domain descendants's log_status should be
  set to `LANDLOCK_LOG_DISABLED`.  This is not a landlock_hierarchy
  configuration because it applies to future descendant domains and it does
  not require a current domain.

**Description**

This structure is packed to minimize the size of struct
landlock_file_security.  However, it is always aligned in the LSM cred blob,
see `lsm_set_blob_size()`.

When updating this, also update `landlock_cred_copy()` if needed.

#### <a id="c-landlock_get_applicable_subject"></a>`landlock_get_applicable_subject()`

```c
const struct landlock_cred_security * landlock_get_applicable_subject(const struct cred *const cred, const struct access_masks masks, size_t *const handle_layer)
```

Return the subject's Landlock credential if its enforced domain applies to (i.e. handles) at least one of the access rights specified in **masks**

**Parameters**

- `const struct cred *const cred`: credential
- `const struct access_masks masks`: access masks
- `size_t *const handle_layer`: returned youngest layer handling a subset of **masks**.  Not set
  if the function returns NULL.

**Return**

landlock_cred(**cred**) if any access rights specified in **masks** is
handled, or NULL otherwise.


<a id="rst-ruleset-and-domain"></a>

### Ruleset and domain

A domain is a read-only ruleset tied to a set of subjects (i.e. tasks' credentials).  Each time a ruleset is enforced on a task, the current domain is duplicated and the ruleset is imported as a new layer of rules in the new domain.  Indeed, once in a domain, each rule is tied to a layer level.  To grant access to an object, at least one rule of each layer must allow the requested action on the object.  A task can then only transit to a new domain that is the intersection of the constraints from the current domain and those of a ruleset provided by the task.

The definition of a subject is implicit for a task sandboxing itself, which makes the reasoning much easier and helps avoid pitfalls.


#### <a id="c-struct-landlock_layer"></a>`struct landlock_layer`

Access rights for a given layer

**Definition**

```c
struct landlock_layer {
    u16 level;
    access_mask_t access;
};
```

**Members**

- `level`: Position of this layer in the layer stack.  Starts from 1.
- `access`: Bitfield of allowed actions on the kernel object.  They are
  relative to the object type (e.g. `LANDLOCK_ACTION_FS_READ`).

#### <a id="c-union-landlock_key"></a>`union landlock_key`

Key of a ruleset's red-black tree

**Definition**

```c
union landlock_key {
    struct landlock_object *object;
    uintptr_t data;
};
```

**Members**

- `object`: Pointer to identify a kernel object (e.g. an inode).
- `data`: Raw data to identify an arbitrary 32-bit value
  (e.g. a TCP port).

#### <a id="c-enum-landlock_key_type"></a>`enum landlock_key_type`

Type of [`union landlock_key`](#c-union-landlock_key)

**Constants**

- `LANDLOCK_KEY_INODE`: Type of [`landlock_ruleset.root_inode`](#c-struct-landlock_ruleset)'s node
  keys.
- `LANDLOCK_KEY_NET_PORT`: Type of [`landlock_ruleset.root_net_port`](#c-struct-landlock_ruleset)'s
  node keys.

#### <a id="c-struct-landlock_id"></a>`struct landlock_id`

Unique rule identifier for a ruleset

**Definition**

```c
struct landlock_id {
    union landlock_key key;
    const enum landlock_key_type type;
};
```

**Members**

- `key`: Identifies either a kernel object (e.g. an inode) or
  a raw value (e.g. a TCP port).
- `type`: Type of a landlock_ruleset's root tree.

#### <a id="c-struct-landlock_rule"></a>`struct landlock_rule`

Access rights tied to an object

**Definition**

```c
struct landlock_rule {
    struct rb_node node;
    union landlock_key key;
    u32 num_layers;
    struct landlock_layer layers[] ;
};
```

**Members**

- `node`: Node in the ruleset's red-black tree.
- `key`: A union to identify either a kernel object (e.g. an inode) or
  a raw data value (e.g. a network socket port). This is used as a key
  for this ruleset element.  The pointer is set once and never
  modified.  It always points to an allocated object because each rule
  increments the refcount of its object.
- `num_layers`: Number of entries in **layers**.
- `layers`: Stack of layers, from the latest to the newest, implemented
  as a flexible array member (FAM).

#### <a id="c-struct-landlock_ruleset"></a>`struct landlock_ruleset`

Landlock ruleset

**Definition**

```c
struct landlock_ruleset {
        struct rb_root root_inode;
    #if IS_ENABLED(CONFIG_INET);
        struct rb_root root_net_port;
    #endif;
        struct landlock_hierarchy *hierarchy;
        union {
            struct work_struct work_free;
            struct {
                struct mutex lock;
                refcount_t usage;
                u32 num_rules;
                u32 num_layers;
                struct access_masks access_masks[];
            };
        };
};
```

**Members**

- `root_inode`: Root of a red-black tree containing [`struct landlock_rule`](#c-struct-landlock_rule) nodes with inode object.  Once a ruleset is tied to a
  process (i.e. as a domain), this tree is immutable until **usage**
  reaches zero.
- `root_net_port`: Root of a red-black tree containing [`struct landlock_rule`](#c-struct-landlock_rule) nodes with network port. Once a ruleset is tied to a
  process (i.e. as a domain), this tree is immutable until **usage**
  reaches zero.
- `hierarchy`: Enables hierarchy identification even when a parent
  domain vanishes.  This is needed for the ptrace protection.
- `{unnamed_union}`: anonymous
- `work_free`: Enables to free a ruleset within a lockless
  section.  This is only used by
  `landlock_put_ruleset_deferred()` when **usage** reaches zero.
  The fields **lock**, **usage**, **num_rules**, **num_layers** and
  **access_masks** are then unused.
- `{unnamed_struct}`: anonymous
- `lock`: Protects against concurrent modifications of
  **root**, if **usage** is greater than zero.
- `usage`: Number of processes (i.e. domains) or file
  descriptors referencing this ruleset.
- `num_rules`: Number of non-overlapping (i.e. not for
  the same object) rules in this ruleset.
- `num_layers`: Number of layers that are used in this
  ruleset.  This enables to check that all the layers
  allow an access request.  A value of 0 identifies a
  non-merged ruleset (i.e. not a domain).
- `access_masks`: Contains the subset of filesystem and
  network actions that are restricted by a ruleset.
  A domain saves all layers of merged rulesets in a
  stack (FAM), starting from the first layer to the
  last one.  These layers are used when merging
  rulesets, for user space backward compatibility
  (i.e. future-proof), and to properly handle merged
  rulesets without overlapping access rights.  These
  layers are set once and never changed for the
  lifetime of the ruleset.

**Description**

This data structure must contain unique entries, be updatable, and quick to
match an object.

#### <a id="c-landlock_union_access_masks"></a>`landlock_union_access_masks()`

```c
struct access_masks landlock_union_access_masks(const struct landlock_ruleset *const domain)
```

Return all access rights handled in the domain

**Parameters**

- `const struct landlock_ruleset *const domain`: Landlock ruleset (used as a domain)

**Return**

an access_masks result of the OR of all the domain's access masks.



#### <a id="c-struct-landlock_details"></a>`struct landlock_details`

Domain's creation information

**Definition**

```c
struct landlock_details {
    struct pid *pid;
    uid_t uid;
    char comm[TASK_COMM_LEN];
    char exe_path[];
};
```

**Members**

- `pid`: PID of the task that initially restricted itself.  It still
  identifies the same task.  Keeping a reference to this PID ensures that
  it will not be recycled.
- `uid`: UID of the task that initially restricted itself, at creation time.
- `comm`: Command line of the task that initially restricted itself, at
  creation time.  Always NULL terminated.
- `exe_path`: Executable path of the task that initially restricted
  itself, at creation time.  Always NULL terminated, and never greater
  than LANDLOCK_PATH_MAX_SIZE.

**Description**

Rarely accessed, mainly when logging the first domain's denial.

The contained pointers are initialized at the domain creation time and never
changed again.  Contrary to most other Landlock object types, this one is
not allocated with GFP_KERNEL_ACCOUNT because its size may not be under the
caller's control (e.g. unknown exe_path) and the data is not explicitly
requested nor used by tasks.

#### <a id="c-struct-landlock_hierarchy"></a>`struct landlock_hierarchy`

Node in a domain hierarchy

**Definition**

```c
struct landlock_hierarchy {
        struct landlock_hierarchy *parent;
        refcount_t usage;
    #ifdef CONFIG_AUDIT;
        enum landlock_log_status log_status;
        atomic64_t num_denials;
        u64 id;
        const struct landlock_details *details;
        u32 log_same_exec : 1, log_new_exec : 1;
    #endif;
};
```

**Members**

- `parent`: Pointer to the parent node, or NULL if it is a root
  Landlock domain.
- `usage`: Number of potential children domains plus their parent
  domain.
- `log_status`: Whether this domain should be logged or not.  Because
  concurrent log entries may be created at the same time, it is still
  possible to have several domain records of the same domain.
- `num_denials`: Number of access requests denied by this domain.
  Masked (i.e. never logged) denials are still counted.
- `id`: Landlock domain ID, set once at domain creation time.
- `details`: Information about the related domain.
- `log_same_exec`: Set if the domain is *not* configured with
  `LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF`.  Set to true by default.
- `log_new_exec`: Set if the domain is configured with
  `LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON`.  Set to false by default.


<a id="rst-additional-documentation"></a>

## Additional documentation

- [Documentation/userspace-api/landlock.rst](/kernel/userspace/userspace-api/security/landlock.md)

- [Documentation/admin-guide/LSM/landlock.rst](/kernel/administration/admin-guide/lsm/landlock.md)

- [https://landlock.io](<https://landlock.io>)

<!-- Links -->

<a id="rst-tools-testing-selftests-landlock"></a>

---

# Linux Security Module Development

_Peios Kernel / Internals / Security_

> Based on https://lore.kernel.org/r/20071026073721.618b4778@laptopd505.fenrus.org, a new LSM is accepted into the kernel when its intent (a description of what it tries to protect against and in what cases one would expect to use it) has…

> **Peios:** The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) and the [VFS callback reference](</kernel/internals/filesystems/vfs.md>) for the Peios integration contracts.


<a id="rst-linux-security-module-development"></a>

Based on [https://lore.kernel.org/r/20071026073721.618b4778@laptopd505.fenrus.org](<https://lore.kernel.org/r/20071026073721.618b4778@laptopd505.fenrus.org>), a new LSM is accepted into the kernel when its intent (a description of what it tries to protect against and in what cases one would expect to use it) has been appropriately documented in `Documentation/admin-guide/LSM/`. This allows an LSM's code to be easily compared to its goals, and so that end users and distros can make a more informed decision about which LSMs suit their requirements.

For extensive documentation on the available LSM hook interfaces, please see `security/security.c` and associated structures:


#### <a id="c-security_free_mnt_opts"></a>`security_free_mnt_opts()`

```c
void security_free_mnt_opts(void **mnt_opts)
```

Free memory associated with mount options

**Parameters**

- `void **mnt_opts`: LSM processed mount options

**Description**

Free memory associated with **mnt_ops**.

#### <a id="c-security_sb_eat_lsm_opts"></a>`security_sb_eat_lsm_opts()`

```c
int security_sb_eat_lsm_opts(char *options, void **mnt_opts)
```

Consume LSM mount options

**Parameters**

- `char *options`: mount options
- `void **mnt_opts`: LSM processed mount options

**Description**

Eat (scan **options**) and save them in **mnt_opts**.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_sb_mnt_opts_compat"></a>`security_sb_mnt_opts_compat()`

```c
int security_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
```

Check if new mount options are allowed

**Parameters**

- `struct super_block *sb`: filesystem superblock
- `void *mnt_opts`: new mount options

**Description**

Determine if the new mount options in **mnt_opts** are allowed given the
existing mounted filesystem at **sb**.  **sb** superblock being compared.

**Return**

Returns 0 if options are compatible.

#### <a id="c-security_sb_remount"></a>`security_sb_remount()`

```c
int security_sb_remount(struct super_block *sb, void *mnt_opts)
```

Verify no incompatible mount changes during remount

**Parameters**

- `struct super_block *sb`: filesystem superblock
- `void *mnt_opts`: (re)mount options

**Description**

Extracts security system specific mount options and verifies no changes are
being made to those options.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sb_set_mnt_opts"></a>`security_sb_set_mnt_opts()`

```c
int security_sb_set_mnt_opts(struct super_block *sb, void *mnt_opts, unsigned long kern_flags, unsigned long *set_kern_flags)
```

Set the mount options for a filesystem

**Parameters**

- `struct super_block *sb`: filesystem superblock
- `void *mnt_opts`: binary mount options
- `unsigned long kern_flags`: kernel flags (in)
- `unsigned long *set_kern_flags`: kernel flags (out)

**Description**

Set the security relevant mount options used for a superblock.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_sb_clone_mnt_opts"></a>`security_sb_clone_mnt_opts()`

```c
int security_sb_clone_mnt_opts(const struct super_block *oldsb, struct super_block *newsb, unsigned long kern_flags, unsigned long *set_kern_flags)
```

Duplicate superblock mount options

**Parameters**

- `const struct super_block *oldsb`: source superblock
- `struct super_block *newsb`: destination superblock
- `unsigned long kern_flags`: kernel flags (in)
- `unsigned long *set_kern_flags`: kernel flags (out)

**Description**

Copy all security options from a given superblock to another.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_dentry_init_security"></a>`security_dentry_init_security()`

```c
int security_dentry_init_security(struct dentry *dentry, int mode, const struct qstr *name, const char **xattr_name, struct lsm_context *lsmctx)
```

Perform dentry initialization

**Parameters**

- `struct dentry *dentry`: the dentry to initialize
- `int mode`: mode used to determine resource type
- `const struct qstr *name`: name of the last path component
- `const char **xattr_name`: name of the security/LSM xattr
- `struct lsm_context *lsmctx`: pointer to the resulting LSM context

**Description**

Compute a context for a dentry as the inode is not yet available since NFSv4
has no label backed by an EA anyway.  It is important to note that
**xattr_name** does not need to be free'd by the caller, it is a static string.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_dentry_create_files_as"></a>`security_dentry_create_files_as()`

```c
int security_dentry_create_files_as(struct dentry *dentry, int mode, const struct qstr *name, const struct cred *old, struct cred *new)
```

Perform dentry initialization

**Parameters**

- `struct dentry *dentry`: the dentry to initialize
- `int mode`: mode used to determine resource type
- `const struct qstr *name`: name of the last path component
- `const struct cred *old`: creds to use for LSM context calculations
- `struct cred *new`: creds to modify

**Description**

Compute a context for a dentry as the inode is not yet available and set
that context in passed in creds so that new files are created using that
context. Context is calculated using the passed in creds and not the creds
of the caller.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_inode_init_security"></a>`security_inode_init_security()`

```c
int security_inode_init_security(struct inode *inode, struct inode *dir, const struct qstr *qstr, const initxattrs initxattrs, void *fs_data)
```

Initialize an inode's LSM context

**Parameters**

- `struct inode *inode`: the inode
- `struct inode *dir`: parent directory
- `const struct qstr *qstr`: last component of the pathname
- `const initxattrs initxattrs`: callback function to write xattrs
- `void *fs_data`: filesystem specific data

**Description**

Obtain the security attribute name suffix and value to set on a newly
created inode and set up the incore security field for the new inode.  This
hook is called by the fs code as part of the inode creation transaction and
provides for atomic labeling of the inode, unlike the post_create/mkdir/...
hooks called by the VFS.

The hook function is expected to populate the xattrs array, by calling
`lsm_get_xattr_slot()` to retrieve the slots reserved by the security module
with the lbs_xattr_count field of the lsm_blob_sizes structure.  For each
slot, the hook function should set ->name to the attribute name suffix
(e.g. selinux), to allocate ->value (will be freed by the caller) and set it
to the attribute value, to set ->value_len to the length of the value.  If
the security module does not use security attributes or does not wish to put
a security attribute on this particular inode, then it should return
-EOPNOTSUPP to skip this processing.

**Return**

Returns 0 if the LSM successfully initialized all of the inode
security attributes that are required, negative values otherwise.

#### <a id="c-security_path_mknod"></a>`security_path_mknod()`

```c
int security_path_mknod(const struct path *dir, struct dentry *dentry, umode_t mode, unsigned int dev)
```

Check if creating a special file is allowed

**Parameters**

- `const struct path *dir`: parent directory
- `struct dentry *dentry`: new file
- `umode_t mode`: new file mode
- `unsigned int dev`: device number

**Description**

Check permissions when creating a file. Note that this hook is called even
if mknod operation is being done for a regular file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_mkdir"></a>`security_path_mkdir()`

```c
int security_path_mkdir(const struct path *dir, struct dentry *dentry, umode_t mode)
```

Check if creating a new directory is allowed

**Parameters**

- `const struct path *dir`: parent directory
- `struct dentry *dentry`: new directory
- `umode_t mode`: new directory mode

**Description**

Check permissions to create a new directory in the existing directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_unlink"></a>`security_path_unlink()`

```c
int security_path_unlink(const struct path *dir, struct dentry *dentry)
```

Check if removing a hard link is allowed

**Parameters**

- `const struct path *dir`: parent directory
- `struct dentry *dentry`: file

**Description**

Check the permission to remove a hard link to a file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_path_rename"></a>`security_path_rename()`

```c
int security_path_rename(const struct path *old_dir, struct dentry *old_dentry, const struct path *new_dir, struct dentry *new_dentry, unsigned int flags)
```

Check if renaming a file is allowed

**Parameters**

- `const struct path *old_dir`: parent directory of the old file
- `struct dentry *old_dentry`: the old file
- `const struct path *new_dir`: parent directory of the new file
- `struct dentry *new_dentry`: the new file
- `unsigned int flags`: flags

**Description**

Check for permission to rename a file or directory.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_create"></a>`security_inode_create()`

```c
int security_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
```

Check if creating a file is allowed

**Parameters**

- `struct inode *dir`: the parent directory
- `struct dentry *dentry`: the file being created
- `umode_t mode`: requested file mode

**Description**

Check permission to create a regular file.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_mkdir"></a>`security_inode_mkdir()`

```c
int security_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
```

Check if creating a new directory is allowed

**Parameters**

- `struct inode *dir`: parent directory
- `struct dentry *dentry`: new directory
- `umode_t mode`: new directory mode

**Description**

Check permissions to create a new directory in the existing directory
associated with inode structure **dir**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_setattr"></a>`security_inode_setattr()`

```c
int security_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry, struct iattr *attr)
```

Check if setting file attributes is allowed

**Parameters**

- `struct mnt_idmap *idmap`: idmap of the mount
- `struct dentry *dentry`: file
- `struct iattr *attr`: new attributes

**Description**

Check permission before setting file attributes.  Note that the kernel call
to notify_change is performed from several locations, whenever file
attributes change (such as when a file is truncated, chown/chmod operations,
transferring disk quotas, etc).

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inode_listsecurity"></a>`security_inode_listsecurity()`

```c
int security_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
```

List the xattr security label names

**Parameters**

- `struct inode *inode`: inode
- `char *buffer`: buffer
- `size_t buffer_size`: size of buffer

**Description**

Copy the extended attribute names for the security labels associated with
**inode** into **buffer**.  The maximum size of **buffer** is specified by
**buffer_size**.  **buffer** may be NULL to request the size of the buffer
required.

**Return**

Returns number of bytes used/required on success.

#### <a id="c-security_inode_copy_up"></a>`security_inode_copy_up()`

```c
int security_inode_copy_up(struct dentry *src, struct cred **new)
```

Create new creds for an overlayfs copy-up op

**Parameters**

- `struct dentry *src`: union dentry of copy-up file
- `struct cred **new`: newly created creds

**Description**

A file is about to be copied up from lower layer to upper layer of overlay
filesystem. Security module can prepare a set of new creds and modify as
need be and return new creds. Caller will switch to new creds temporarily to
create new file and release newly allocated creds.

**Return**

Returns 0 on success or a negative error code on error.

#### <a id="c-security_inode_copy_up_xattr"></a>`security_inode_copy_up_xattr()`

```c
int security_inode_copy_up_xattr(struct dentry *src, const char *name)
```

Filter xattrs in an overlayfs copy-up op

**Parameters**

- `struct dentry *src`: union dentry of copy-up file
- `const char *name`: xattr name

**Description**

Filter the xattrs being copied up when a unioned file is copied up from a
lower layer to the union/overlay layer.   The caller is responsible for
reading and writing the xattrs, this hook is merely a filter.

**Return**

Returns 0 to accept the xattr, -ECANCELED to discard the xattr,
-EOPNOTSUPP if the security module does not know about attribute,
or a negative error code to abort the copy up.

#### <a id="c-security_inode_setintegrity"></a>`security_inode_setintegrity()`

```c
int security_inode_setintegrity(const struct inode *inode, enum lsm_integrity_type type, const void *value, size_t size)
```

Set the inode's integrity data

**Parameters**

- `const struct inode *inode`: inode
- `enum lsm_integrity_type type`: type of integrity, e.g. hash digest, signature, etc
- `const void *value`: the integrity value
- `size_t size`: size of the integrity value

**Description**

Register a verified integrity measurement of a inode with LSMs.
LSMs should free the previously saved data if **value** is NULL.

**Return**

Returns 0 on success, negative values on failure.

#### <a id="c-security_file_ioctl"></a>`security_file_ioctl()`

```c
int security_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
```

Check if an ioctl is allowed

**Parameters**

- `struct file *file`: associated file
- `unsigned int cmd`: ioctl cmd
- `unsigned long arg`: ioctl arguments

**Description**

Check permission for an ioctl operation on **file**.  Note that **arg** sometimes
represents a user space pointer; in other cases, it may be a simple integer
value.  When **arg** represents a user space pointer, it should never be used
by the security module.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_ioctl_compat"></a>`security_file_ioctl_compat()`

```c
int security_file_ioctl_compat(struct file *file, unsigned int cmd, unsigned long arg)
```

Check if an ioctl is allowed in compat mode

**Parameters**

- `struct file *file`: associated file
- `unsigned int cmd`: ioctl cmd
- `unsigned long arg`: ioctl arguments

**Description**

Compat version of [`security_file_ioctl()`](#c-security_file_ioctl) that correctly handles 32-bit
processes running on 64-bit kernels.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_mmap_backing_file"></a>`security_mmap_backing_file()`

```c
int security_mmap_backing_file(struct vm_area_struct *vma, struct file *backing_file, struct file *user_file)
```

Check if mmap'ing a backing file is allowed

**Parameters**

- `struct vm_area_struct *vma`: the vm_area_struct for the mmap'd region
- `struct file *backing_file`: the backing file being mmap'd
- `struct file *user_file`: the user file being mmap'd

**Description**

Check permissions for a mmap operation on a stacked filesystem.  This hook
is called after the [`security_mmap_file()`](/kernel/internals/core-api/kernel-api.md#c-security_mmap_file) and is responsible for authorizing
the mmap on **backing_file**.  It is important to note that the mmap operation
on **user_file** has already been authorized and the **vma->vm_file** has been
set to **backing_file**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_file_post_open"></a>`security_file_post_open()`

```c
int security_file_post_open(struct file *file, int mask)
```

Evaluate a file after it has been opened

**Parameters**

- `struct file *file`: the file
- `int mask`: access mask

**Description**

Evaluate an opened file and the access mask requested with `open()`. The hook
is useful for LSMs that require the file content to be available in order to
make decisions.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_cred_getsecid"></a>`security_cred_getsecid()`

```c
void security_cred_getsecid(const struct cred *c, u32 *secid)
```

Get the secid from a set of credentials

**Parameters**

- `const struct cred *c`: credentials
- `u32 *secid`: secid value

**Description**

Retrieve the security identifier of the cred structure **c**.  In case of
failure, **secid** will be set to zero.

#### <a id="c-security_cred_getlsmprop"></a>`security_cred_getlsmprop()`

```c
void security_cred_getlsmprop(const struct cred *c, struct lsm_prop *prop)
```

Get the LSM data from a set of credentials

**Parameters**

- `const struct cred *c`: credentials
- `struct lsm_prop *prop`: destination for the LSM data

**Description**

Retrieve the security data of the cred structure **c**.  In case of
failure, **prop** will be cleared.

#### <a id="c-security_kernel_read_file"></a>`security_kernel_read_file()`

```c
int security_kernel_read_file(struct file *file, enum kernel_read_file_id id, bool contents)
```

Read a file specified by userspace

**Parameters**

- `struct file *file`: file
- `enum kernel_read_file_id id`: file identifier
- `bool contents`: trust if [`security_kernel_post_read_file()`](#c-security_kernel_post_read_file) will be called

**Description**

Read a file specified by userspace.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_kernel_post_read_file"></a>`security_kernel_post_read_file()`

```c
int security_kernel_post_read_file(struct file *file, char *buf, loff_t size, enum kernel_read_file_id id)
```

Read a file specified by userspace

**Parameters**

- `struct file *file`: file
- `char *buf`: file contents
- `loff_t size`: size of file contents
- `enum kernel_read_file_id id`: file identifier

**Description**

Read a file specified by userspace.  This must be paired with a prior call
to [`security_kernel_read_file()`](#c-security_kernel_read_file) call that indicated this hook would also be
called, see [`security_kernel_read_file()`](#c-security_kernel_read_file) for more information.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_kernel_load_data"></a>`security_kernel_load_data()`

```c
int security_kernel_load_data(enum kernel_load_data_id id, bool contents)
```

Load data provided by userspace

**Parameters**

- `enum kernel_load_data_id id`: data identifier
- `bool contents`: true if [`security_kernel_post_load_data()`](#c-security_kernel_post_load_data) will be called

**Description**

Load data provided by userspace.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_kernel_post_load_data"></a>`security_kernel_post_load_data()`

```c
int security_kernel_post_load_data(char *buf, loff_t size, enum kernel_load_data_id id, char *description)
```

Load userspace data from a non-file source

**Parameters**

- `char *buf`: data
- `loff_t size`: size of data
- `enum kernel_load_data_id id`: data identifier
- `char *description`: text description of data, specific to the id value

**Description**

Load data provided by a non-file source (usually userspace buffer).  This
must be paired with a prior [`security_kernel_load_data()`](#c-security_kernel_load_data) call that indicated
this hook would also be called, see [`security_kernel_load_data()`](#c-security_kernel_load_data) for more
information.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_current_getlsmprop_subj"></a>`security_current_getlsmprop_subj()`

```c
void security_current_getlsmprop_subj(struct lsm_prop *prop)
```

Current task's subjective LSM data

**Parameters**

- `struct lsm_prop *prop`: lsm specific information

**Description**

Retrieve the subjective security identifier of the current task and return
it in **prop**.

#### <a id="c-security_task_getlsmprop_obj"></a>`security_task_getlsmprop_obj()`

```c
void security_task_getlsmprop_obj(struct task_struct *p, struct lsm_prop *prop)
```

Get a task's objective LSM data

**Parameters**

- `struct task_struct *p`: target task
- `struct lsm_prop *prop`: lsm specific information

**Description**

Retrieve the objective security identifier of the task_struct in **p** and
return it in **prop**.

#### <a id="c-security_d_instantiate"></a>`security_d_instantiate()`

```c
void security_d_instantiate(struct dentry *dentry, struct inode *inode)
```

Populate an inode's LSM state based on a dentry

**Parameters**

- `struct dentry *dentry`: dentry
- `struct inode *inode`: inode

**Description**

Fill in **inode** security information for a **dentry** if allowed.

#### <a id="c-security_ismaclabel"></a>`security_ismaclabel()`

```c
int security_ismaclabel(const char *name)
```

Check if the named attribute is a MAC label

**Parameters**

- `const char *name`: full extended attribute name

**Description**

Check if the extended attribute specified by **name** represents a MAC label.

**Return**

Returns 1 if name is a MAC attribute otherwise returns 0.

#### <a id="c-security_secid_to_secctx"></a>`security_secid_to_secctx()`

```c
int security_secid_to_secctx(u32 secid, struct lsm_context *cp)
```

Convert a secid to a secctx

**Parameters**

- `u32 secid`: secid
- `struct lsm_context *cp`: the LSM context

**Description**

Convert secid to security context.  If **cp** is NULL the length of the
result will be returned, but no data will be returned.  This
does mean that the length could change between calls to check the length and
the next call which actually allocates and returns the data.

**Return**

Return length of data on success, error on failure.

#### <a id="c-security_lsmprop_to_secctx"></a>`security_lsmprop_to_secctx()`

```c
int security_lsmprop_to_secctx(struct lsm_prop *prop, struct lsm_context *cp, int lsmid)
```

Convert a lsm_prop to a secctx

**Parameters**

- `struct lsm_prop *prop`: lsm specific information
- `struct lsm_context *cp`: the LSM context
- `int lsmid`: which security module to report

**Description**

Convert a **prop** entry to security context.  If **cp** is NULL the
length of the result will be returned. This does mean that the
length could change between calls to check the length and the
next call which actually allocates and returns the **cp**.

**lsmid** identifies which LSM should supply the context.
A value of LSM_ID_UNDEF indicates that the first LSM suppling
the hook should be used. This is used in cases where the
ID of the supplying LSM is unambiguous.

**Return**

Return length of data on success, error on failure.

#### <a id="c-security_secctx_to_secid"></a>`security_secctx_to_secid()`

```c
int security_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
```

Convert a secctx to a secid

**Parameters**

- `const char *secdata`: secctx
- `u32 seclen`: length of secctx
- `u32 *secid`: secid

**Description**

Convert security context to secid.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_release_secctx"></a>`security_release_secctx()`

```c
void security_release_secctx(struct lsm_context *cp)
```

Free a secctx buffer

**Parameters**

- `struct lsm_context *cp`: the security context

**Description**

Release the security context.

#### <a id="c-security_inode_invalidate_secctx"></a>`security_inode_invalidate_secctx()`

```c
void security_inode_invalidate_secctx(struct inode *inode)
```

Invalidate an inode's security label

**Parameters**

- `struct inode *inode`: inode

**Description**

Notify the security module that it must revalidate the security context of
an inode.

#### <a id="c-security_inode_notifysecctx"></a>`security_inode_notifysecctx()`

```c
int security_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
```

Notify the LSM of an inode's security label

**Parameters**

- `struct inode *inode`: inode
- `void *ctx`: secctx
- `u32 ctxlen`: length of secctx

**Description**

Notify the security module of what the security context of an inode should
be.  Initializes the incore security context managed by the security module
for this inode.  Example usage: NFS client invokes this hook to initialize
the security context in its incore inode to the value provided by the server
for the file when the server returned the file's attributes to the client.
Must be called with inode->i_mutex locked.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_inode_setsecctx"></a>`security_inode_setsecctx()`

```c
int security_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
```

Change the security label of an inode

**Parameters**

- `struct dentry *dentry`: inode
- `void *ctx`: secctx
- `u32 ctxlen`: length of secctx

**Description**

Change the security context of an inode.  Updates the incore security
context managed by the security module and invokes the fs code as needed
(via __vfs_setxattr_noperm) to update any backing xattrs that represent the
context.  Example usage: NFS server invokes this hook to change the security
context in its incore inode and on the backing filesystem to a value
provided by the client on a SETATTR operation.  Must be called with
inode->i_mutex locked.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_inode_getsecctx"></a>`security_inode_getsecctx()`

```c
int security_inode_getsecctx(struct inode *inode, struct lsm_context *cp)
```

Get the security label of an inode

**Parameters**

- `struct inode *inode`: inode
- `struct lsm_context *cp`: security context

**Description**

On success, returns 0 and fills out **cp** with the security context
for the given **inode**.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_unix_stream_connect"></a>`security_unix_stream_connect()`

```c
int security_unix_stream_connect(struct sock *sock, struct sock *other, struct sock *newsk)
```

Check if a AF_UNIX stream is allowed

**Parameters**

- `struct sock *sock`: originating sock
- `struct sock *other`: peer sock
- `struct sock *newsk`: new sock

**Description**

Check permissions before establishing a Unix domain stream connection
between **sock** and **other**.

The **unix_stream_connect** and **unix_may_send** hooks were necessary because
Linux provides an alternative to the conventional file name space for Unix
domain sockets.  Whereas binding and connecting to sockets in the file name
space is mediated by the typical file permissions (and caught by the mknod
and permission hooks in inode_security_ops), binding and connecting to
sockets in the abstract name space is completely unmediated.  Sufficient
control of Unix domain sockets in the abstract name space isn't possible
using only the socket layer hooks, since we need to know the actual target
socket, which is not looked up until we are inside the af_unix code.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_unix_may_send"></a>`security_unix_may_send()`

```c
int security_unix_may_send(struct socket *sock, struct socket *other)
```

Check if AF_UNIX socket can send datagrams

**Parameters**

- `struct socket *sock`: originating sock
- `struct socket *other`: peer sock

**Description**

Check permissions before connecting or sending datagrams from **sock** to
**other**.

The **unix_stream_connect** and **unix_may_send** hooks were necessary because
Linux provides an alternative to the conventional file name space for Unix
domain sockets.  Whereas binding and connecting to sockets in the file name
space is mediated by the typical file permissions (and caught by the mknod
and permission hooks in inode_security_ops), binding and connecting to
sockets in the abstract name space is completely unmediated.  Sufficient
control of Unix domain sockets in the abstract name space isn't possible
using only the socket layer hooks, since we need to know the actual target
socket, which is not looked up until we are inside the af_unix code.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_socketpair"></a>`security_socket_socketpair()`

```c
int security_socket_socketpair(struct socket *socka, struct socket *sockb)
```

Check if creating a socketpair is allowed

**Parameters**

- `struct socket *socka`: first socket
- `struct socket *sockb`: second socket

**Description**

Check permissions before creating a fresh pair of sockets.

**Return**

Returns 0 if permission is granted and the connection was
established.

#### <a id="c-security_sock_rcv_skb"></a>`security_sock_rcv_skb()`

```c
int security_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
```

Check if an incoming network packet is allowed

**Parameters**

- `struct sock *sk`: destination sock
- `struct sk_buff *skb`: incoming packet

**Description**

Check permissions on incoming network packets.  This hook is distinct from
Netfilter's IP input hooks since it is the first time that the incoming
sk_buff **skb** has been associated with a particular socket, **sk**.  Must not
sleep inside this hook because some callers hold spinlocks.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_socket_getpeersec_dgram"></a>`security_socket_getpeersec_dgram()`

```c
int security_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
```

Get the remote peer label

**Parameters**

- `struct socket *sock`: socket
- `struct sk_buff *skb`: datagram packet
- `u32 *secid`: remote peer label secid

**Description**

This hook allows the security module to provide peer socket security state
for udp sockets on a per-packet basis to userspace via getsockopt
SO_GETPEERSEC. The application must first have indicated the IP_PASSSEC
option via getsockopt. It can then retrieve the security state returned by
this hook for a packet via the SCM_SECURITY ancillary message type.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_sk_clone"></a>`security_sk_clone()`

```c
void security_sk_clone(const struct sock *sk, struct sock *newsk)
```

Clone a sock's LSM state

**Parameters**

- `const struct sock *sk`: original sock
- `struct sock *newsk`: target sock

**Description**

Clone/copy security structure.

#### <a id="c-security_sk_classify_flow"></a>`security_sk_classify_flow()`

```c
void security_sk_classify_flow(const struct sock *sk, struct flowi_common *flic)
```

Set a flow's secid based on socket

**Parameters**

- `const struct sock *sk`: original socket
- `struct flowi_common *flic`: target flow

**Description**

Set the target flow's secid to socket's secid.

#### <a id="c-security_req_classify_flow"></a>`security_req_classify_flow()`

```c
void security_req_classify_flow(const struct request_sock *req, struct flowi_common *flic)
```

Set a flow's secid based on request_sock

**Parameters**

- `const struct request_sock *req`: request_sock
- `struct flowi_common *flic`: target flow

**Description**

Sets **flic**'s secid to **req**'s secid.

#### <a id="c-security_sock_graft"></a>`security_sock_graft()`

```c
void security_sock_graft(struct sock *sk, struct socket *parent)
```

Reconcile LSM state when grafting a sock on a socket

**Parameters**

- `struct sock *sk`: sock being grafted
- `struct socket *parent`: target parent socket

**Description**

Sets **parent**'s inode secid to **sk**'s secid and update **sk** with any necessary
LSM state from **parent**.

#### <a id="c-security_inet_conn_request"></a>`security_inet_conn_request()`

```c
int security_inet_conn_request(const struct sock *sk, struct sk_buff *skb, struct request_sock *req)
```

Set request_sock state using incoming connect

**Parameters**

- `const struct sock *sk`: parent listening sock
- `struct sk_buff *skb`: incoming connection
- `struct request_sock *req`: new request_sock

**Description**

Initialize the **req** LSM state based on **sk** and the incoming connect in **skb**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_inet_conn_established"></a>`security_inet_conn_established()`

```c
void security_inet_conn_established(struct sock *sk, struct sk_buff *skb)
```

Update sock's LSM state with connection

**Parameters**

- `struct sock *sk`: sock
- `struct sk_buff *skb`: connection packet

**Description**

Update **sock**'s LSM state to represent a new connection from **skb**.

#### <a id="c-security_secmark_relabel_packet"></a>`security_secmark_relabel_packet()`

```c
int security_secmark_relabel_packet(u32 secid)
```

Check if setting a secmark is allowed

**Parameters**

- `u32 secid`: new secmark value

**Description**

Check if the process should be allowed to relabel packets to **secid**.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_secmark_refcount_inc"></a>`security_secmark_refcount_inc()`

```c
void security_secmark_refcount_inc(void)
```

Increment the secmark labeling rule count

**Parameters**

- `void`: no arguments

**Description**

Tells the LSM to increment the number of secmark labeling rules loaded.

#### <a id="c-security_secmark_refcount_dec"></a>`security_secmark_refcount_dec()`

```c
void security_secmark_refcount_dec(void)
```

Decrement the secmark labeling rule count

**Parameters**

- `void`: no arguments

**Description**

Tells the LSM to decrement the number of secmark labeling rules loaded.

#### <a id="c-security_tun_dev_alloc_security"></a>`security_tun_dev_alloc_security()`

```c
int security_tun_dev_alloc_security(void **security)
```

Allocate a LSM blob for a TUN device

**Parameters**

- `void **security`: pointer to the LSM blob

**Description**

This hook allows a module to allocate a security structure for a TUN device,
returning the pointer in **security**.

**Return**

Returns a zero on success, negative values on failure.

#### <a id="c-security_tun_dev_free_security"></a>`security_tun_dev_free_security()`

```c
void security_tun_dev_free_security(void *security)
```

Free a TUN device LSM blob

**Parameters**

- `void *security`: LSM blob

**Description**

This hook allows a module to free the security structure for a TUN device.

#### <a id="c-security_tun_dev_create"></a>`security_tun_dev_create()`

```c
int security_tun_dev_create(void)
```

Check if creating a TUN device is allowed

**Parameters**

- `void`: no arguments

**Description**

Check permissions prior to creating a new TUN device.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_tun_dev_attach_queue"></a>`security_tun_dev_attach_queue()`

```c
int security_tun_dev_attach_queue(void *security)
```

Check if attaching a TUN queue is allowed

**Parameters**

- `void *security`: TUN device LSM blob

**Description**

Check permissions prior to attaching to a TUN device queue.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_tun_dev_attach"></a>`security_tun_dev_attach()`

```c
int security_tun_dev_attach(struct sock *sk, void *security)
```

Update TUN device LSM state on attach

**Parameters**

- `struct sock *sk`: associated sock
- `void *security`: TUN device LSM blob

**Description**

This hook can be used by the module to update any security state associated
with the TUN device's sock structure.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_tun_dev_open"></a>`security_tun_dev_open()`

```c
int security_tun_dev_open(void *security)
```

Update TUN device LSM state on open

**Parameters**

- `void *security`: TUN device LSM blob

**Description**

This hook can be used by the module to update any security state associated
with the TUN device's security structure.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_sctp_assoc_request"></a>`security_sctp_assoc_request()`

```c
int security_sctp_assoc_request(struct sctp_association *asoc, struct sk_buff *skb)
```

Update the LSM on a SCTP association req

**Parameters**

- `struct sctp_association *asoc`: SCTP association
- `struct sk_buff *skb`: packet requesting the association

**Description**

Passes the **asoc** and **chunk->skb** of the association INIT packet to the LSM.

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_sctp_bind_connect"></a>`security_sctp_bind_connect()`

```c
int security_sctp_bind_connect(struct sock *sk, int optname, struct sockaddr *address, int addrlen)
```

Validate a list of addrs for a SCTP option

**Parameters**

- `struct sock *sk`: socket
- `int optname`: SCTP option to validate
- `struct sockaddr *address`: list of IP addresses to validate
- `int addrlen`: length of the address list

**Description**

Validiate permissions required for each address associated with sock **sk**.
Depending on **optname**, the addresses will be treated as either a connect or
bind service. The **addrlen** is calculated on each IPv4 and IPv6 address using
sizeof(struct sockaddr_in) or sizeof(struct sockaddr_in6).

**Return**

Returns 0 on success, error on failure.

#### <a id="c-security_sctp_sk_clone"></a>`security_sctp_sk_clone()`

```c
void security_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk, struct sock *newsk)
```

Clone a SCTP sock's LSM state

**Parameters**

- `struct sctp_association *asoc`: SCTP association
- `struct sock *sk`: original sock
- `struct sock *newsk`: target sock

**Description**

Called whenever a new socket is created by accept(2) (i.e. a TCP style
socket) or when a socket is 'peeled off' e.g userspace calls
sctp_peeloff(3).

#### <a id="c-security_sctp_assoc_established"></a>`security_sctp_assoc_established()`

```c
int security_sctp_assoc_established(struct sctp_association *asoc, struct sk_buff *skb)
```

Update LSM state when assoc established

**Parameters**

- `struct sctp_association *asoc`: SCTP association
- `struct sk_buff *skb`: packet establishing the association

**Description**

Passes the **asoc** and **chunk->skb** of the association COOKIE_ACK packet to the
security module.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ib_pkey_access"></a>`security_ib_pkey_access()`

```c
int security_ib_pkey_access(void *sec, u64 subnet_prefix, u16 pkey)
```

Check if access to an IB pkey is allowed

**Parameters**

- `void *sec`: LSM blob
- `u64 subnet_prefix`: subnet prefix of the port
- `u16 pkey`: IB pkey

**Description**

Check permission to access a pkey when modifying a QP.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ib_endport_manage_subnet"></a>`security_ib_endport_manage_subnet()`

```c
int security_ib_endport_manage_subnet(void *sec, const char *dev_name, u8 port_num)
```

Check if SMPs traffic is allowed

**Parameters**

- `void *sec`: LSM blob
- `const char *dev_name`: IB device name
- `u8 port_num`: port number

**Description**

Check permissions to send and receive SMPs on a end port.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_ib_alloc_security"></a>`security_ib_alloc_security()`

```c
int security_ib_alloc_security(void **sec)
```

Allocate an Infiniband LSM blob

**Parameters**

- `void **sec`: LSM blob

**Description**

Allocate a security structure for Infiniband objects.

**Return**

Returns 0 on success, non-zero on failure.

#### <a id="c-security_ib_free_security"></a>`security_ib_free_security()`

```c
void security_ib_free_security(void *sec)
```

Free an Infiniband LSM blob

**Parameters**

- `void *sec`: LSM blob

**Description**

Deallocate an Infiniband security structure.

#### <a id="c-security_xfrm_policy_alloc"></a>`security_xfrm_policy_alloc()`

```c
int security_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp, struct xfrm_user_sec_ctx *sec_ctx, gfp_t gfp)
```

Allocate a xfrm policy LSM blob

**Parameters**

- `struct xfrm_sec_ctx **ctxp`: xfrm security context being added to the SPD
- `struct xfrm_user_sec_ctx *sec_ctx`: security label provided by userspace
- `gfp_t gfp`: gfp flags

**Description**

Allocate a security structure to the xp->security field; the security field
is initialized to NULL when the xfrm_policy is allocated.

**Return**

Return 0 if operation was successful.

#### <a id="c-security_xfrm_policy_free"></a>`security_xfrm_policy_free()`

```c
void security_xfrm_policy_free(struct xfrm_sec_ctx *ctx)
```

Free a xfrm security context

**Parameters**

- `struct xfrm_sec_ctx *ctx`: xfrm security context

**Description**

Free LSM resources associated with **ctx**.

#### <a id="c-security_xfrm_state_alloc"></a>`security_xfrm_state_alloc()`

```c
int security_xfrm_state_alloc(struct xfrm_state *x, struct xfrm_user_sec_ctx *sec_ctx)
```

Allocate a xfrm state LSM blob

**Parameters**

- `struct xfrm_state *x`: xfrm state being added to the SAD
- `struct xfrm_user_sec_ctx *sec_ctx`: security label provided by userspace

**Description**

Allocate a security structure to the **x->security** field; the security field
is initialized to NULL when the xfrm_state is allocated. Set the context to
correspond to **sec_ctx**.

**Return**

Return 0 if operation was successful.

#### <a id="c-security_xfrm_state_delete"></a>`security_xfrm_state_delete()`

```c
int security_xfrm_state_delete(struct xfrm_state *x)
```

Check if deleting a xfrm state is allowed

**Parameters**

- `struct xfrm_state *x`: xfrm state

**Description**

Authorize deletion of x->security.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_locked_down"></a>`security_locked_down()`

```c
int security_locked_down(enum lockdown_reason what)
```

Check if a kernel feature is allowed

**Parameters**

- `enum lockdown_reason what`: requested kernel feature

**Description**

Determine whether a kernel feature that potentially enables arbitrary code
execution in kernel space should be permitted.

**Return**

Returns 0 if permission is granted.

#### <a id="c-security_bdev_alloc"></a>`security_bdev_alloc()`

```c
int security_bdev_alloc(struct block_device *bdev)
```

Allocate a block device LSM blob

**Parameters**

- `struct block_device *bdev`: block device

**Description**

Allocate and attach a security structure to **bdev->bd_security**.  The
security field is initialized to NULL when the bdev structure is
allocated.

**Return**

Return 0 if operation was successful.

#### <a id="c-security_bdev_free"></a>`security_bdev_free()`

```c
void security_bdev_free(struct block_device *bdev)
```

Free a block device's LSM blob

**Parameters**

- `struct block_device *bdev`: block device

**Description**

Deallocate the bdev security structure and set **bdev->bd_security** to NULL.

#### <a id="c-security_bdev_setintegrity"></a>`security_bdev_setintegrity()`

```c
int security_bdev_setintegrity(struct block_device *bdev, enum lsm_integrity_type type, const void *value, size_t size)
```

Set the device's integrity data

**Parameters**

- `struct block_device *bdev`: block device
- `enum lsm_integrity_type type`: type of integrity, e.g. hash digest, signature, etc
- `const void *value`: the integrity value
- `size_t size`: size of the integrity value

**Description**

Register a verified integrity measurement of a bdev with LSMs.
LSMs should free the previously saved data if **value** is NULL.
Please note that the new hook should be invoked every time the security
information is updated to keep these data current. For example, in dm-verity,
if the mapping table is reloaded and configured to use a different dm-verity
target with a new roothash and signing information, the previously stored
data in the LSM blob will become obsolete. It is crucial to re-invoke the
hook to refresh these data and ensure they are up to date. This necessity
arises from the design of device-mapper, where a device-mapper device is
first created, and then targets are subsequently loaded into it. These
targets can be modified multiple times during the device's lifetime.
Therefore, while the LSM blob is allocated during the creation of the block
device, its actual contents are not initialized at this stage and can change
substantially over time. This includes alterations from data that the LSMs
'trusts' to those they do not, making it essential to handle these changes
correctly. Failure to address this dynamic aspect could potentially allow
for bypassing LSM checks.

**Return**

Returns 0 on success, negative values on failure.

---

# Linux Security Modules: General Security Hooks for Linux

_Peios Kernel / Internals / Security_

> In March 2001, the National Security Agency (NSA) gave a presentation about Security-Enhanced Linux (SELinux) at the 2.5 Linux Kernel Summit. SELinux is an implementation of flexible and fine-grained nondiscretionary access controls in the…

> **Peios:** The LSM examples here describe upstream interfaces and implementation choices. Peios configures `landlock,lockdown,integrity,pkm`; SELinux, Smack, AppArmor and their attribute/policy interfaces are not the active native access model. Use the native token/SD interfaces for Peios authority. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-linux-security-modules-general-security-hooks-for-linux"></a>

**Author:** Stephen Smalley

**Author:** Timothy Fraser

**Author:** Chris Vance

> [!NOTE]
>
> The APIs described in this book are outdated.

<a id="rst-introduction"></a>

## Introduction

In March 2001, the National Security Agency (NSA) gave a presentation about Security-Enhanced Linux (SELinux) at the 2.5 Linux Kernel Summit. SELinux is an implementation of flexible and fine-grained nondiscretionary access controls in the Linux kernel, originally implemented as its own particular kernel patch. Several other security projects (e.g. RSBAC, Medusa) have also developed flexible access control architectures for the Linux kernel, and various projects have developed particular access control models for Linux (e.g. LIDS, DTE, SubDomain). Each project has developed and maintained its own kernel patch to support its security needs.

In response to the NSA presentation, Linus Torvalds made a set of remarks that described a security framework he would be willing to consider for inclusion in the mainstream Linux kernel. He described a general framework that would provide a set of security hooks to control operations on kernel objects and a set of opaque security fields in kernel data structures for maintaining security attributes. This framework could then be used by loadable kernel modules to implement any desired model of security. Linus also suggested the possibility of migrating the Linux capabilities code into such a module.

The Linux Security Modules (LSM) project was started by WireX to develop such a framework. LSM was a joint development effort by several security projects, including Immunix, SELinux, SGI and Janus, and several individuals, including Greg Kroah-Hartman and James Morris, to develop a Linux kernel patch that implements this framework. The work was incorporated in the mainstream in December of 2003. This technical report provides an overview of the framework and the capabilities security module.

<a id="rst-lsm-framework"></a>

## LSM Framework

The LSM framework provides a general kernel framework to support security modules. In particular, the LSM framework is primarily focused on supporting access control modules, although future development is likely to address other security needs such as sandboxing. By itself, the framework does not provide any additional security; it merely provides the infrastructure to support security modules. The LSM framework is optional, requiring `CONFIG_SECURITY` to be enabled. The capabilities logic is implemented as a security module. This capabilities module is discussed further in [LSM Capabilities Module](<#rst-lsm-capabilities-module>).

The LSM framework includes security fields in kernel data structures and calls to hook functions at critical points in the kernel code to manage the security fields and to perform access control. It also adds functions for registering security modules. An interface `/sys/kernel/security/lsm` reports a comma separated list of security modules that are active on the system.

The LSM security fields are simply `void*` pointers. The data is referred to as a blob, which may be managed by the framework or by the individual security modules that use it. Security blobs that are used by more than one security module are typically managed by the framework. For process and program execution security information, security fields are included in `struct task_struct <task_struct>` and `struct cred <cred>`. For filesystem security information, a security field is included in `struct super_block <super_block>`. For pipe, file, and socket security information, security fields are included in `struct inode <inode>` and `struct file <file>`. For System V IPC security information, security fields were added to `struct kern_ipc_perm <kern_ipc_perm>` and `struct msg_msg <msg_msg>`; additionally, the definitions for `struct msg_msg <msg_msg>`, struct msg_queue, and struct shmid_kernel were moved to header files (`include/linux/msg.h` and `include/linux/shm.h` as appropriate) to allow the security modules to use these definitions.

For packet and network device security information, security fields were added to `struct sk_buff <sk_buff>` and `struct scm_cookie <scm_cookie>`. Unlike the other security module data, the data used here is a 32-bit integer. The security modules are required to map or otherwise associate these values with real security attributes.

LSM hooks are maintained in lists. A list is maintained for each hook, and the hooks are called in the order specified by CONFIG_LSM. Detailed documentation for each hook is included in the `security/security.c` source file.

The LSM framework provides for a close approximation of general security module stacking. It defines security_add_hooks() to which each security module passes a `struct security_hooks_list <security_hooks_list>`, which are added to the lists. The LSM framework does not provide a mechanism for removing hooks that have been registered. The SELinux security module has implemented a way to remove itself, however the feature has been deprecated.

The hooks can be viewed as falling into two major categories: hooks that are used to manage the security fields and hooks that are used to perform access control. Examples of the first category of hooks include the security_inode_alloc() and security_inode_free() These hooks are used to allocate and free security structures for inode objects. An example of the second category of hooks is the security_inode_permission() hook. This hook checks permission when accessing an inode.

<a id="rst-lsm-capabilities-module"></a>

## LSM Capabilities Module

The POSIX.1e capabilities logic is maintained as a security module stored in the file `security/commoncap.c`. The capabilities module uses the order field of the `lsm_info` description to identify it as the first security module to be registered. The capabilities security module does not use the general security blobs, unlike other modules. The reasons are historical and are based on overhead, complexity and performance concerns.

---

# Linux Secure Attention Key (SAK) handling

_Peios Kernel / Internals / Security_

> An operating system's Secure Attention Key is a security tool which is provided as protection against trojan password capturing programs. It is an undefeatable way of killing all programs which could be masquerading as login applications.…

> **Peios:** Changing the SAK key requires `CAP_SYS_ADMIN`, which maps to enabled `SeTcbPrivilege`, in addition to the applicable terminal access checks. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-linux-secure-attention-key-sak-handling"></a>

**Date:** 18 March 2001

**Author:** Andrew Morton

An operating system's Secure Attention Key is a security tool which is provided as protection against trojan password capturing programs.  It is an undefeatable way of killing all programs which could be masquerading as login applications.  Users need to be taught to enter this key sequence before they log in to the system.

From the PC keyboard, Linux has two similar but different ways of providing SAK.  One is the ALT-SYSRQ-K sequence.  You shouldn't use this sequence.  It is only available if the kernel was compiled with sysrq support.

The proper way of generating a SAK is to define the key sequence using `loadkeys`.  This will work whether or not sysrq support is compiled into the kernel.

SAK works correctly when the keyboard is in raw mode.  This means that once defined, SAK will kill a running X server.  If the system is in run level 5, the X server will restart.  This is what you want to happen.

What key sequence should you use? Well, CTRL-ALT-DEL is used to reboot the machine.  CTRL-ALT-BACKSPACE is magical to the X server.  We'll choose CTRL-ALT-PAUSE.

In your rc.sysinit (or rc.local) file, add the command:



```text
echo "control alt keycode 101 = SAK" | /bin/loadkeys
```

And that's it\!  Only the superuser may reprogram the SAK key.

> [!NOTE]
>
> 1. Linux SAK is said to be not a "true SAK" as is required by systems which implement C2 level security.  This author does not know why.
>
> 2. On the PC keyboard, SAK kills all applications which have /dev/console opened.
>
>    Unfortunately this includes a number of things which you don't actually want killed.  This is because these applications are incorrectly holding /dev/console open.  Be sure to complain to your Linux distributor about this\!
>
>    You can identify processes which will be killed by SAK with the command:
>
>
>
>    ```text
>    # ls -l /proc/[0-9]*/fd/* | grep console
>    l-wx------    1 root     root           64 Mar 18 00:46 /proc/579/fd/0 -> /dev/console
>    ```
>
>    Then:
>
>
>
>    ```text
>    # ps aux|grep 579
>    root       579  0.0  0.1  1088  436 ?        S    00:43   0:00 gpm -t ps/2
>    ```
>
>    So `gpm` will be killed by SAK.  This is a bug in gpm.  It should be closing standard input.  You can work around this by finding the initscript which launches gpm and changing it thusly:
>
>    Old:
>
>
>
>    ```text
>    daemon gpm
>    ```
>
>    New:
>
>
>
>    ```text
>    daemon gpm < /dev/null
>    ```
>
>    Vixie cron also seems to have this problem, and needs the same treatment.
>
>    Also, one prominent Linux distribution has the following three lines in its rc.sysinit and rc scripts:
>
>
>
>    ```text
>    exec 3<&0
>    exec 4>&1
>    exec 5>&2
>    ```
>
>    These commands cause **all** daemons which are launched by the initscripts to have file descriptors 3, 4 and 5 attached to /dev/console.  So SAK kills them all.  A workaround is to simply delete these lines, but this may cause system management applications to malfunction - test everything well.

---

# Kernel Self-Protection

_Peios Kernel / Internals / Security_

> Kernel self-protection is the design and implementation of systems and structures within the Linux kernel to protect against security flaws in the kernel itself. This covers a wide range of issues, including removing entire classes of…

> **Peios:** The configured Peios baseline already requires integrity lockdown, strict `/dev/mem` handling and module signature enforcement. UID 0 is not universal authority; native privileges and PIP define additional boundaries. LoadPin and the alternative MAC LSMs discussed as upstream options are not the active Peios policy. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-kernel-self-protection"></a>

Kernel self-protection is the design and implementation of systems and structures within the Linux kernel to protect against security flaws in the kernel itself. This covers a wide range of issues, including removing entire classes of bugs, blocking security flaw exploitation methods, and actively detecting attack attempts. Not all topics are explored in this document, but it should serve as a reasonable starting point and answer any frequently asked questions. (Patches welcome, of course\!)

In the worst-case scenario, we assume an unprivileged local attacker has arbitrary read and write access to the kernel's memory. In many cases, bugs being exploited will not provide this level of access, but with systems in place that defend against the worst case we'll cover the more limited cases as well. A higher bar, and one that should still be kept in mind, is protecting the kernel against a \_privileged\_ local attacker, since the root user has access to a vastly increased attack surface. (Especially when they have the ability to load arbitrary kernel modules.)

The goals for successful self-protection systems would be that they are effective, on by default, require no opt-in by developers, have no performance impact, do not impede kernel debugging, and have tests. It is uncommon that all these goals can be met, but it is worth explicitly mentioning them, since these aspects need to be explored, dealt with, and/or accepted.

<a id="rst-attack-surface-reduction"></a>

## Attack Surface Reduction

The most fundamental defense against security exploits is to reduce the areas of the kernel that can be used to redirect execution. This ranges from limiting the exposed APIs available to userspace, making in-kernel APIs hard to use incorrectly, minimizing the areas of writable kernel memory, etc.

<a id="rst-strict-kernel-memory-permissions"></a>

### Strict kernel memory permissions

When all of kernel memory is writable, it becomes trivial for attacks to redirect execution flow. To reduce the availability of these targets the kernel needs to protect its memory with a tight set of permissions.

<a id="rst-executable-code-and-read-only-data-must-not-be-writable"></a>

#### Executable code and read-only data must not be writable

Any areas of the kernel with executable memory must not be writable. While this obviously includes the kernel text itself, we must consider all additional places too: kernel modules, JIT memory, etc. (There are temporary exceptions to this rule to support things like instruction alternatives, breakpoints, kprobes, etc. If these must exist in a kernel, they are implemented in a way where the memory is temporarily made writable during the update, and then returned to the original permissions.)

In support of this are `CONFIG_STRICT_KERNEL_RWX` and `CONFIG_STRICT_MODULE_RWX`, which seek to make sure that code is not writable, data is not executable, and read-only data is neither writable nor executable.

Most architectures have these options on by default and not user selectable. For some architectures like arm that wish to have these be selectable, the architecture Kconfig can select ARCH_OPTIONAL_KERNEL_RWX to enable a Kconfig prompt. `CONFIG_ARCH_OPTIONAL_KERNEL_RWX_DEFAULT` determines the default setting when ARCH_OPTIONAL_KERNEL_RWX is enabled.

<a id="rst-function-pointers-and-sensitive-variables-must-not-be-writable"></a>

#### Function pointers and sensitive variables must not be writable

Vast areas of kernel memory contain function pointers that are looked up by the kernel and used to continue execution (e.g. descriptor/vector tables, file/network/etc operation structures, etc). The number of these variables must be reduced to an absolute minimum.

Many such variables can be made read-only by setting them "const" so that they live in the .rodata section instead of the .data section of the kernel, gaining the protection of the kernel's strict memory permissions as described above.

For variables that are initialized once at `__init` time, these can be marked with the `__ro_after_init` attribute.

What remains are variables that are updated rarely (e.g. GDT). These will need another infrastructure (similar to the temporary exceptions made to kernel code mentioned above) that allow them to spend the rest of their lifetime read-only. (For example, when being updated, only the CPU thread performing the update would be given uninterruptible write access to the memory.)

<a id="rst-segregation-of-kernel-memory-from-userspace-memory"></a>

#### Segregation of kernel memory from userspace memory

The kernel must never execute userspace memory. The kernel must also never access userspace memory without explicit expectation to do so. These rules can be enforced either by support of hardware-based restrictions (x86's SMEP/SMAP, ARM's PXN/PAN) or via emulation (ARM's Memory Domains). By blocking userspace memory in this way, execution and data parsing cannot be passed to trivially-controlled userspace memory, forcing attacks to operate entirely in kernel memory.

<a id="rst-reduced-access-to-syscalls"></a>

### Reduced access to syscalls

One trivial way to eliminate many syscalls for 64-bit systems is building without `CONFIG_COMPAT`. However, this is rarely a feasible scenario.

The "seccomp" system provides an opt-in feature made available to userspace, which provides a way to reduce the number of kernel entry points available to a running process. This limits the breadth of kernel code that can be reached, possibly reducing the availability of a given bug to an attack.

An area of improvement would be creating viable ways to keep access to things like compat, user namespaces, BPF creation, and perf limited only to trusted processes. This would keep the scope of kernel entry points restricted to the more regular set of normally available to unprivileged userspace.

<a id="rst-restricting-access-to-kernel-modules"></a>

### Restricting access to kernel modules

The kernel should never allow an unprivileged user the ability to load specific kernel modules, since that would provide a facility to unexpectedly extend the available attack surface. (The on-demand loading of modules via their predefined subsystems, e.g. MODULE_ALIAS\_\*, is considered "expected" here, though additional consideration should be given even to these.) For example, loading a filesystem module via an unprivileged socket API is nonsense: only the root or physically local user should trigger filesystem module loading. (And even this can be up for debate in some scenarios.)

To protect against even privileged users, systems may need to either disable module loading entirely (e.g. monolithic kernel builds or modules_disabled sysctl), or provide signed modules (e.g. `CONFIG_MODULE_SIG_FORCE`, or dm-crypt with LoadPin), to keep from having root load arbitrary kernel code via the module loader interface.

<a id="rst-memory-integrity"></a>

## Memory integrity

There are many memory structures in the kernel that are regularly abused to gain execution control during an attack, By far the most commonly understood is that of the stack buffer overflow in which the return address stored on the stack is overwritten. Many other examples of this kind of attack exist, and protections exist to defend against them.

<a id="rst-stack-buffer-overflow"></a>

### Stack buffer overflow

The classic stack buffer overflow involves writing past the expected end of a variable stored on the stack, ultimately writing a controlled value to the stack frame's stored return address. The most widely used defense is the presence of a stack canary between the stack variables and the return address (`CONFIG_STACKPROTECTOR`), which is verified just before the function returns. Other defenses include things like shadow stacks.

<a id="rst-stack-depth-overflow"></a>

### Stack depth overflow

A less well understood attack is using a bug that triggers the kernel to consume stack memory with deep function calls or large stack allocations. With this attack it is possible to write beyond the end of the kernel's preallocated stack space and into sensitive structures. Two important changes need to be made for better protections: moving the sensitive thread_info structure elsewhere, and adding a faulting memory hole at the bottom of the stack to catch these overflows.

<a id="rst-heap-memory-integrity"></a>

### Heap memory integrity

The structures used to track heap free lists can be sanity-checked during allocation and freeing to make sure they aren't being used to manipulate other memory areas.

<a id="rst-counter-integrity"></a>

### Counter integrity

Many places in the kernel use atomic counters to track object references or perform similar lifetime management. When these counters can be made to wrap (over or under) this traditionally exposes a use-after-free flaw. By trapping atomic wrapping, this class of bug vanishes.

<a id="rst-size-calculation-overflow-detection"></a>

### Size calculation overflow detection

Similar to counter overflow, integer overflows (usually size calculations) need to be detected at runtime to kill this class of bug, which traditionally leads to being able to write past the end of kernel buffers.

<a id="rst-probabilistic-defenses"></a>

## Probabilistic defenses

While many protections can be considered deterministic (e.g. read-only memory cannot be written to), some protections provide only statistical defense, in that an attack must gather enough information about a running system to overcome the defense. While not perfect, these do provide meaningful defenses.

<a id="rst-canaries-blinding-and-other-secrets"></a>

### Canaries, blinding, and other secrets

It should be noted that things like the stack canary discussed earlier are technically statistical defenses, since they rely on a secret value, and such values may become discoverable through an information exposure flaw.

Blinding literal values for things like JITs, where the executable contents may be partially under the control of userspace, need a similar secret value.

It is critical that the secret values used must be separate (e.g. different canary per stack) and high entropy (e.g. is the RNG actually working?) in order to maximize their success.

<a id="rst-kernel-address-space-layout-randomization-kaslr"></a>

### Kernel Address Space Layout Randomization (KASLR)

Since the location of kernel memory is almost always instrumental in mounting a successful attack, making the location non-deterministic raises the difficulty of an exploit. (Note that this in turn makes the value of information exposures higher, since they may be used to discover desired memory locations.)

<a id="rst-text-and-module-base"></a>

#### Text and module base

By relocating the physical and virtual base address of the kernel at boot-time (`CONFIG_RANDOMIZE_BASE`), attacks needing kernel code will be frustrated. Additionally, offsetting the module loading base address means that even systems that load the same set of modules in the same order every boot will not share a common base address with the rest of the kernel text.

<a id="rst-stack-base"></a>

#### Stack base

If the base address of the kernel stack is not the same between processes, or even not the same between syscalls, targets on or beyond the stack become more difficult to locate.

<a id="rst-dynamic-memory-base"></a>

#### Dynamic memory base

Much of the kernel's dynamic memory (e.g. kmalloc, vmalloc, etc) ends up being relatively deterministic in layout due to the order of early-boot initializations. If the base address of these areas is not the same between boots, targeting them is frustrated, requiring an information exposure specific to the region.

<a id="rst-structure-layout"></a>

#### Structure layout

By performing a per-build randomization of the layout of sensitive structures, attacks must either be tuned to known kernel builds or expose enough kernel memory to determine structure layouts before manipulating them.

<a id="rst-preventing-information-exposures"></a>

## Preventing Information Exposures

Since the locations of sensitive structures are the primary target for attacks, it is important to defend against exposure of both kernel memory addresses and kernel memory contents (since they may contain kernel addresses or other sensitive things like canary values).

<a id="rst-kernel-addresses"></a>

### Kernel addresses

Printing kernel addresses to userspace leaks sensitive information about the kernel memory layout. Care should be exercised when using any printk specifier that prints the raw address, currently %px, %p\[ad\], (and %p\[sSb\] in certain circumstances \[\*\]).  Any file written to using one of these specifiers should be readable only by privileged processes.

Kernels 4.14 and older printed the raw address using %p. As of 4.15-rc1 addresses printed with the specifier %p are hashed before printing.

\[\*\] If KALLSYMS is enabled and symbol lookup fails, the raw address is printed. If KALLSYMS is not enabled the raw address is printed.

<a id="rst-unique-identifiers"></a>

### Unique identifiers

Kernel memory addresses must never be used as identifiers exposed to userspace. Instead, use an atomic counter, an idr, or similar unique identifier.

<a id="rst-memory-initialization"></a>

### Memory initialization

Memory copied to userspace must always be fully initialized. If not explicitly memset(), this will require changes to the compiler to make sure structure holes are cleared.

<a id="rst-memory-poisoning"></a>

### Memory poisoning

When releasing memory, it is best to poison the contents, to avoid reuse attacks that rely on the old contents of memory. E.g., clear stack on a syscall return (`CONFIG_KSTACK_ERASE`), wipe heap memory on a free. This frustrates many uninitialized variable attacks, stack content exposures, heap content exposures, and use-after-free attacks.

<a id="rst-destination-tracking"></a>

### Destination tracking

To help kill classes of bugs that result in kernel addresses being written to userspace, the destination of writes needs to be tracked. If the buffer is destined for userspace (e.g. seq_file backed `/proc` files), it should automatically censor sensitive values.

---

# SipHash - a short input PRF

_Peios Kernel / Internals / Security_

> SipHash is a cryptographically secure PRF -- a keyed hash function -- that performs very well for short inputs, hence the name. It was designed by cryptographers Daniel J. Bernstein and Jean-Philippe Aumasson. It is intended as a…

<a id="rst-siphash-a-short-input-prf"></a>

## SipHash - a short input PRF

**Author:** Written by Jason A. Donenfeld &lt;[jason@zx2c4.com](<mailto:jason@zx2c4.com>)&gt;

SipHash is a cryptographically secure PRF -- a keyed hash function -- that performs very well for short inputs, hence the name. It was designed by cryptographers Daniel J. Bernstein and Jean-Philippe Aumasson. It is intended as a replacement for some uses of: `jhash`, `md5_transform`, `sha1_transform`, and so forth.

SipHash takes a secret key filled with randomly generated numbers and either an input buffer or several input integers. It spits out an integer that is indistinguishable from random. You may then use that integer as part of secure sequence numbers, secure cookies, or mask it off for use in a hash table.

<a id="rst-generating-a-key"></a>

### Generating a key

Keys should always be generated from a cryptographically secure source of random numbers, either using get_random_bytes or get_random_once:



```text
siphash_key_t key;
get_random_bytes(&key, sizeof(key));
```

If you're not deriving your key from here, you're doing it wrong.

<a id="rst-using-the-functions"></a>

### Using the functions

There are two variants of the function, one that takes a list of integers, and one that takes a buffer:



```text
u64 siphash(const void *data, size_t len, const siphash_key_t *key);
```

And:



```text
u64 siphash_1u64(u64, const siphash_key_t *key);
u64 siphash_2u64(u64, u64, const siphash_key_t *key);
u64 siphash_3u64(u64, u64, u64, const siphash_key_t *key);
u64 siphash_4u64(u64, u64, u64, u64, const siphash_key_t *key);
u64 siphash_1u32(u32, const siphash_key_t *key);
u64 siphash_2u32(u32, u32, const siphash_key_t *key);
u64 siphash_3u32(u32, u32, u32, const siphash_key_t *key);
u64 siphash_4u32(u32, u32, u32, u32, const siphash_key_t *key);
```

If you pass the generic siphash function something of a constant length, it will constant fold at compile-time and automatically choose one of the optimized functions.

Hashtable key function usage:



```text
struct some_hashtable {
        DECLARE_HASHTABLE(hashtable, 8);
        siphash_key_t key;
};

void init_hashtable(struct some_hashtable *table)
{
        get_random_bytes(&table->key, sizeof(table->key));
}

static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
{
        return &table->hashtable[siphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
}
```

You may then iterate like usual over the returned hash bucket.

<a id="rst-security"></a>

### Security

SipHash has a very high security margin, with its 128-bit key. So long as the key is kept secret, it is impossible for an attacker to guess the outputs of the function, even if being able to observe many outputs, since 2^128 outputs is significant.

Linux implements the "2-4" variant of SipHash.

<a id="rst-struct-passing-pitfalls"></a>

### Struct-passing Pitfalls

Often times the XuY functions will not be large enough, and instead you'll want to pass a pre-filled struct to siphash. When doing this, it's important to always ensure the struct has no padding holes. The easiest way to do this is to simply arrange the members of the struct in descending order of size, and to use offsetofend() instead of sizeof() for getting the size. For performance reasons, if possible, it's probably a good thing to align the struct to the right boundary. Here's an example:



```text
const struct {
        struct in6_addr saddr;
        u32 counter;
        u16 dport;
} __aligned(SIPHASH_ALIGNMENT) combined = {
        .saddr = *(struct in6_addr *)saddr,
        .counter = counter,
        .dport = dport
};
u64 h = siphash(&combined, offsetofend(typeof(combined), dport), &secret);
```

<a id="rst-resources"></a>

### Resources

Read the SipHash paper if you're interested in learning more: [https://131002.net/siphash/siphash.pdf](<https://131002.net/siphash/siphash.pdf>)

---

<a id="rst-halfsiphash-siphash-s-insecure-younger-cousin"></a>

## HalfSipHash - SipHash's insecure younger cousin

**Author:** Written by Jason A. Donenfeld &lt;[jason@zx2c4.com](<mailto:jason@zx2c4.com>)&gt;

On the off-chance that SipHash is not fast enough for your needs, you might be able to justify using HalfSipHash, a terrifying but potentially useful possibility. HalfSipHash cuts SipHash's rounds down from "2-4" to "1-3" and, even scarier, uses an easily brute-forcable 64-bit key (with a 32-bit output) instead of SipHash's 128-bit key. However, this may appeal to some high-performance `jhash` users.

HalfSipHash support is provided through the "hsiphash" family of functions.

> [!WARNING]
>
> Do not ever use the hsiphash functions except for as a hashtable key function, and only then when you can be absolutely certain that the outputs will never be transmitted out of the kernel. This is only remotely useful over `jhash` as a means of mitigating hashtable flooding denial of service attacks.

On 64-bit kernels, the hsiphash functions actually implement SipHash-1-3, a reduced-round variant of SipHash, instead of HalfSipHash-1-3. This is because in 64-bit code, SipHash-1-3 is no slower than HalfSipHash-1-3, and can be faster. Note, this does *not* mean that in 64-bit kernels the hsiphash functions are the same as the siphash ones, or that they are secure; the hsiphash functions still use a less secure reduced-round algorithm and truncate their outputs to 32 bits.

<a id="rst-generating-a-hsiphash-key"></a>

### Generating a hsiphash key

Keys should always be generated from a cryptographically secure source of random numbers, either using get_random_bytes or get_random_once:



```text
hsiphash_key_t key;
get_random_bytes(&key, sizeof(key));
```

If you're not deriving your key from here, you're doing it wrong.

<a id="rst-using-the-hsiphash-functions"></a>

### Using the hsiphash functions

There are two variants of the function, one that takes a list of integers, and one that takes a buffer:



```text
u32 hsiphash(const void *data, size_t len, const hsiphash_key_t *key);
```

And:



```text
u32 hsiphash_1u32(u32, const hsiphash_key_t *key);
u32 hsiphash_2u32(u32, u32, const hsiphash_key_t *key);
u32 hsiphash_3u32(u32, u32, u32, const hsiphash_key_t *key);
u32 hsiphash_4u32(u32, u32, u32, u32, const hsiphash_key_t *key);
```

If you pass the generic hsiphash function something of a constant length, it will constant fold at compile-time and automatically choose one of the optimized functions.

<a id="rst-hashtable-key-function-usage"></a>

### Hashtable key function usage



```text
struct some_hashtable {
        DECLARE_HASHTABLE(hashtable, 8);
        hsiphash_key_t key;
};

void init_hashtable(struct some_hashtable *table)
{
        get_random_bytes(&table->key, sizeof(table->key));
}

static inline hlist_head *some_hashtable_bucket(struct some_hashtable *table, struct interesting_input *input)
{
        return &table->hashtable[hsiphash(input, sizeof(*input), &table->key) & (HASH_SIZE(table->hashtable) - 1)];
}
```

You may then iterate like usual over the returned hash bucket.

<a id="rst-performance"></a>

### Performance

hsiphash() is roughly 3 times slower than jhash(). For many replacements, this will not be a problem, as the hashtable lookup isn't the bottleneck. And in general, this is probably a good sacrifice to make for the security and DoS resistance of hsiphash().

---

# Confidential Computing in Linux for x86 virtualization

_Peios Kernel / Internals / Security_

> Motivation

<a id="rst-confidential-computing-in-linux-for-x86-virtualization"></a>

<a id="rst-contents"></a>



By: Elena Reshetova &lt;[elena.reshetova@intel.com](<mailto:elena.reshetova@intel.com>)&gt; and Carlos Bilbao &lt;[carlos.bilbao.osdev@gmail.com](<mailto:carlos.bilbao.osdev@gmail.com>)&gt;

<a id="rst-motivation"></a>

## Motivation

Kernel developers working on confidential computing for virtualized environments in x86 operate under a set of assumptions regarding the Linux kernel threat model that differ from the traditional view. Historically, the Linux threat model acknowledges attackers residing in userspace, as well as a limited set of external attackers that are able to interact with the kernel through various networking or limited HW-specific exposed interfaces (USB, thunderbolt). The goal of this document is to explain additional attack vectors that arise in the confidential computing space and discuss the proposed protection mechanisms for the Linux kernel.

<a id="rst-overview-and-terminology"></a>

## Overview and terminology

Confidential Computing (CoCo) is a broad term covering a wide range of security technologies that aim to protect the confidentiality and integrity of data in use (vs. data at rest or data in transit). At its core, CoCo solutions provide a Trusted Execution Environment (TEE), where secure data processing can be performed and, as a result, they are typically further classified into different subtypes depending on the SW that is intended to be run in TEE. This document focuses on a subclass of CoCo technologies that are targeting virtualized environments and allow running Virtual Machines (VM) inside TEE. From now on in this document will be referring to this subclass of CoCo as 'Confidential Computing (CoCo) for the virtualized environments (VE)'.

CoCo, in the virtualization context, refers to a set of HW and/or SW technologies that allow for stronger security guarantees for the SW running inside a CoCo VM. Namely, confidential computing allows its users to confirm the trustworthiness of all SW pieces to include in its reduced Trusted Computing Base (TCB) given its ability to attest the state of these trusted components.

While the concrete implementation details differ between technologies, all available mechanisms aim to provide increased confidentiality and integrity for the VM's guest memory and execution state (vCPU registers), more tightly controlled guest interrupt injection, as well as some additional mechanisms to control guest-host page mapping. More details on the x86-specific solutions can be found in [Intel Trust Domain Extensions (TDX)](</kernel/hardware/arch/x86/tdx.md>) and [AMD Memory Encryption](<https://www.amd.com/system/files/techdocs/sev-snp-strengthening-vm-isolation-with-integrity-protection-and-more.pdf>)<a id="rst-amd-memory-encryption"></a>.

The basic CoCo guest layout includes the host, guest, the interfaces that communicate guest and host, a platform capable of supporting CoCo VMs, and a trusted intermediary between the guest VM and the underlying platform that acts as a security manager. The host-side virtual machine monitor (VMM) typically consists of a subset of traditional VMM features and is still in charge of the guest lifecycle, i.e. create or destroy a CoCo VM, manage its access to system resources, etc. However, since it typically stays out of CoCo VM TCB, its access is limited to preserve the security objectives.

In the following diagram, the "&lt;---&gt;" lines represent bi-directional communication channels or interfaces between the CoCo security manager and the rest of the components (data flow for guest, host, hardware)



```text
+-------------------+      +-----------------------+
| CoCo guest VM     |<---->|                       |
+-------------------+      |                       |
  | Interfaces |           | CoCo security manager |
+-------------------+      |                       |
| Host VMM          |<---->|                       |
+-------------------+      |                       |
                           |                       |
+--------------------+     |                       |
| CoCo platform      |<--->|                       |
+--------------------+     +-----------------------+
```

The specific details of the CoCo security manager vastly diverge between technologies. For example, in some cases, it will be implemented in HW while in others it may be pure SW.

<a id="rst-existing-linux-kernel-threat-model"></a>

## Existing Linux kernel threat model

The overall components of the current Linux kernel threat model are:



```text
+-----------------------+      +-------------------+
|                       |<---->| Userspace         |
|                       |      +-------------------+
|   External attack     |         | Interfaces |
|       vectors         |      +-------------------+
|                       |<---->| Linux Kernel      |
|                       |      +-------------------+
+-----------------------+      +-------------------+
                               | Bootloader/BIOS   |
                               +-------------------+
                               +-------------------+
                               | HW platform       |
                               +-------------------+
```

There is also communication between the bootloader and the kernel during the boot process, but this diagram does not represent it explicitly. The "Interfaces" box represents the various interfaces that allow communication between kernel and userspace. This includes system calls, kernel APIs, device drivers, etc.

The existing Linux kernel threat model typically assumes execution on a trusted HW platform with all of the firmware and bootloaders included on its TCB. The primary attacker resides in the userspace, and all of the data coming from there is generally considered untrusted, unless userspace is privileged enough to perform trusted actions. In addition, external attackers are typically considered, including those with access to enabled external networks (e.g. Ethernet, Wireless, Bluetooth), exposed hardware interfaces (e.g. USB, Thunderbolt), and the ability to modify the contents of disks offline.

Regarding external attack vectors, it is interesting to note that in most cases external attackers will try to exploit vulnerabilities in userspace first, but that it is possible for an attacker to directly target the kernel; particularly if the host has physical access. Examples of direct kernel attacks include the vulnerabilities CVE-2019-19524, CVE-2022-0435 and CVE-2020-24490.

<a id="rst-confidential-computing-threat-model-and-its-security-objectives"></a>

## Confidential Computing threat model and its security objectives

Confidential Computing adds a new type of attacker to the above list: a potentially misbehaving host (which can also include some part of a traditional VMM or all of it), which is typically placed outside of the CoCo VM TCB due to its large SW attack surface. It is important to note that this doesn’t imply that the host or VMM are intentionally malicious, but that there exists a security value in having a small CoCo VM TCB. This new type of adversary may be viewed as a more powerful type of external attacker, as it resides locally on the same physical machine (in contrast to a remote network attacker) and has control over the guest kernel communication with most of the HW:



```text
                              +------------------------+
                              |    CoCo guest VM       |
+-----------------------+     |  +-------------------+ |
|                       |<--->|  | Userspace         | |
|                       |     |  +-------------------+ |
|   External attack     |     |     | Interfaces |     |
|       vectors         |     |  +-------------------+ |
|                       |<--->|  | Linux Kernel      | |
|                       |     |  +-------------------+ |
+-----------------------+     |  +-------------------+ |
                              |  | Bootloader/BIOS   | |
+-----------------------+     |  +-------------------+ |
|                       |<--->+------------------------+
|                       |          | Interfaces |
|                       |     +------------------------+
|     CoCo security     |<--->| Host/Host-side VMM |
|      manager          |     +------------------------+
|                       |     +------------------------+
|                       |<--->|   CoCo platform        |
+-----------------------+     +------------------------+
```

While traditionally the host has unlimited access to guest data and can leverage this access to attack the guest, the CoCo systems mitigate such attacks by adding security features like guest data confidentiality and integrity protection. This threat model assumes that those features are available and intact.

The <strong>Linux kernel CoCo VM security objectives</strong> can be summarized as follows:

1\. Preserve the confidentiality and integrity of CoCo guest's private memory and registers.

2\. Prevent privileged escalation from a host into a CoCo guest Linux kernel. While it is true that the host (and host-side VMM) requires some level of privilege to create, destroy, or pause the guest, part of the goal of preventing privileged escalation is to ensure that these operations do not provide a pathway for attackers to gain access to the guest's kernel.

The above security objectives result in two primary <strong>Linux kernel CoCo VM assets</strong>:

1. Guest kernel execution context.

2. Guest kernel private memory.

The host retains full control over the CoCo guest resources, and can deny access to them at any time. Examples of resources include CPU time, memory that the guest can consume, network bandwidth, etc. Because of this, the host Denial of Service (DoS) attacks against CoCo guests are beyond the scope of this threat model.

The <strong>Linux CoCo VM attack surface</strong> is any interface exposed from a CoCo guest Linux kernel towards an untrusted host that is not covered by the CoCo technology SW/HW protection. This includes any possible side-channels, as well as transient execution side channels. Examples of explicit (not side-channel) interfaces include accesses to port I/O, MMIO and DMA interfaces, access to PCI configuration space, VMM-specific hypercalls (towards Host-side VMM), access to shared memory pages, interrupts allowed to be injected into the guest kernel by the host, as well as CoCo technology-specific hypercalls, if present. Additionally, the host in a CoCo system typically controls the process of creating a CoCo guest: it has a method to load into a guest the firmware and bootloader images, the kernel image together with the kernel command line. All of this data should also be considered untrusted until its integrity and authenticity is established via attestation.

The table below shows a threat matrix for the CoCo guest Linux kernel but does not discuss potential mitigation strategies. The matrix refers to CoCo-specific versions of the guest, host and platform.


<table>
<caption>CoCo Linux guest kernel threat matrix</caption>
<thead>
<tr>
<th>


Threat name

</th>
<th>


Threat description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Guest malicious configuration

</td>
<td>


A misbehaving host modifies one of the following guest's configuration:

1. Guest firmware or bootloader

2. Guest kernel or module binaries

3. Guest command line parameters

This allows the host to break the integrity of the code running inside a CoCo guest, and violates the CoCo security objectives.

</td>
</tr>
<tr>
<td>


CoCo guest data attacks

</td>
<td>


A misbehaving host retains full control of the CoCo guest's data in-transit between the guest and the host-managed physical or virtual devices. This allows any attack against confidentiality, integrity or freshness of such data.

</td>
</tr>
<tr>
<td>


Malformed runtime input

</td>
<td>


A misbehaving host injects malformed input via any communication interface used by the guest's kernel code. If the code is not prepared to handle this input correctly, this can result in a host --&gt; guest kernel privilege escalation. This includes traditional side-channel and/or transient execution attack vectors.

</td>
</tr>
<tr>
<td>


Malicious runtime input

</td>
<td>


A misbehaving host injects a specific input value via any communication interface used by the guest's kernel code. The difference with the previous attack vector (malformed runtime input) is that this input is not malformed, but its value is crafted to impact the guest's kernel security. Examples of such inputs include providing a malicious time to the guest or the entropy to the guest random number generator. Additionally, the timing of such events can be an attack vector on its own, if it results in a particular guest kernel action (i.e. processing of a host-injected interrupt). resistant to supplied host input.

</td>
</tr>
</tbody>
</table>

---

# Kernel Keys

_Peios Kernel / Internals / Security / keys_

> Reference for Kernel Keys.

<a id="rst-kernel-keys"></a>

- [Kernel Key Retention Service](</kernel/internals/security/keys/core.md>)
- [Encrypted keys for the eCryptfs filesystem](</kernel/internals/security/keys/ecryptfs.md>)
- [Key Request Service](</kernel/internals/security/keys/request-key.md>)
- [Trusted and Encrypted Keys](</kernel/internals/security/keys/trusted-encrypted.md>)

---

# Kernel Key Retention Service

_Peios Kernel / Internals / Security / keys_

> This service allows cryptographic keys, authentication tokens, cross-domain user mappings, and similar to be cached in the kernel for the use of filesystems and other kernel services.

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-kernel-key-retention-service"></a>

This service allows cryptographic keys, authentication tokens, cross-domain user mappings, and similar to be cached in the kernel for the use of filesystems and other kernel services.

Keyrings are permitted; these are a special type of key that can hold links to other keys. Processes each have three standard keyring subscriptions that a kernel service can search for relevant keys.

The key service can be configured on by enabling:

> "Security options"/"Enable access key retention support" (CONFIG_KEYS)

This document has the following sections:

<a id="rst-contents"></a>



<a id="rst-key-overview"></a>

## Key Overview

In this context, keys represent units of cryptographic data, authentication tokens, keyrings, etc.. These are represented in the kernel by struct key.

Each key has a number of attributes:

> > - A serial number.
> >
> > - A type.
> >
> > - A description (for matching a key in a search).
> >
> > - Access control information.
> >
> > - An expiry time.
> >
> > - A payload.
> >
> > - State.
>
> - Each key is issued a serial number of type key_serial_t that is unique for the lifetime of that key. All serial numbers are positive non-zero 32-bit integers.
>
>   Userspace programs can use a key's serial numbers as a way to gain access to it, subject to permission checking.
>
> - Each key is of a defined "type". Types must be registered inside the kernel by a kernel service (such as a filesystem) before keys of that type can be added or used. Userspace programs cannot define new types directly.
>
>   Key types are represented in the kernel by struct key_type. This defines a number of operations that can be performed on a key of that type.
>
>   Should a type be removed from the system, all the keys of that type will be invalidated.
>
> - Each key has a description. This should be a printable string. The key type provides an operation to perform a match between the description on a key and a criterion string.
>
> - Each key has an owner user ID, a group ID and a permissions mask. These are used to control what a process may do to a key from userspace, and whether a kernel service will be able to find the key.
>
> - Each key can be set to expire at a specific time by the key type's instantiation function. Keys can also be immortal.
>
> - Each key can have a payload. This is a quantity of data that represent the actual "key". In the case of a keyring, this is a list of keys to which the keyring links; in the case of a user-defined key, it's an arbitrary blob of data.
>
>   Having a payload is not required; and the payload can, in fact, just be a value stored in the struct key itself.
>
>   When a key is instantiated, the key type's instantiation function is called with a blob of data, and that then creates the key's payload in some way.
>
>   Similarly, when userspace wants to read back the contents of the key, if permitted, another key type operation will be called to convert the key's attached payload back into a blob of data.
>
> - Each key can be in one of a number of basic states:
>
>   > - Uninstantiated. The key exists, but does not have any data attached. Keys being requested from userspace will be in this state.
>   >
>   > - Instantiated. This is the normal state. The key is fully formed, and has data attached.
>   >
>   > - Negative. This is a relatively short-lived state. The key acts as a note saying that a previous call out to userspace failed, and acts as a throttle on key lookups. A negative key can be updated to a normal state.
>   >
>   > - Expired. Keys can have lifetimes set. If their lifetime is exceeded, they traverse to this state. An expired key can be updated back to a normal state.
>   >
>   > - Revoked. A key is put in this state by userspace action. It can't be found or operated upon (apart from by unlinking it).
>   >
>   > - Dead. The key's type was unregistered, and so the key is now useless.

Keys in the last three states are subject to garbage collection.  See the section on "Garbage collection".

<a id="rst-key-service-overview"></a>

## Key Service Overview

The key service provides a number of features besides keys:

> - The key service defines three special key types:
>
>   (+) "keyring"
>
>   > Keyrings are special keys that contain a list of other keys. Keyring lists can be modified using various system calls. Keyrings should not be given a payload when created.
>
>   (+) "user"
>
>   > A key of this type has a description and a payload that are arbitrary blobs of data. These can be created, updated and read by userspace, and aren't intended for use by kernel services.
>
>   (+) "logon"
>
>   > Like a "user" key, a "logon" key has a payload that is an arbitrary blob of data. It is intended as a place to store secrets which are accessible to the kernel but not to userspace programs.
>   >
>   > The description can be arbitrary, but must be prefixed with a non-zero length string that describes the key "subclass". The subclass is separated from the rest of the description by a ':'. "logon" keys can be created and updated from userspace, but the payload is only readable from kernel space.
>
> - Each process subscribes to three keyrings: a thread-specific keyring, a process-specific keyring, and a session-specific keyring.
>
>   The thread-specific keyring is discarded from the child when any sort of clone, fork, vfork or execve occurs. A new keyring is created only when required.
>
>   The process-specific keyring is replaced with an empty one in the child on clone, fork, vfork unless CLONE_THREAD is supplied, in which case it is shared. execve also discards the process's process keyring and creates a new one.
>
>   The session-specific keyring is persistent across clone, fork, vfork and execve, even when the latter executes a set-UID or set-GID binary. A process can, however, replace its current session keyring with a new one by using PR_JOIN_SESSION_KEYRING. It is permitted to request an anonymous new one, or to attempt to create or join one of a specific name.
>
>   The ownership of the thread keyring changes when the real UID and GID of the thread changes.
>
> - Each user ID resident in the system holds two special keyrings: a user specific keyring and a default user session keyring. The default session keyring is initialised with a link to the user-specific keyring.
>
>   When a process changes its real UID, if it used to have no session key, it will be subscribed to the default session key for the new UID.
>
>   If a process attempts to access its session key when it doesn't have one, it will be subscribed to the default for its current UID.
>
> - Each user has two quotas against which the keys they own are tracked. One limits the total number of keys and keyrings, the other limits the total amount of description and payload space that can be consumed.
>
>   The user can view information on this and other statistics through procfs files.  The root user may also alter the quota limits through sysctl files (see the section "New procfs files").
>
>   Process-specific and thread-specific keyrings are not counted towards a user's quota.
>
>   If a system call that modifies a key or keyring in some way would put the user over quota, the operation is refused and error EDQUOT is returned.
>
> - There's a system call interface by which userspace programs can create and manipulate keys and keyrings.
>
> - There's a kernel interface by which services can register types and search for keys.
>
> - There's a way for the a search done from the kernel to call back to userspace to request a key that can't be found in a process's keyrings.
>
> - An optional filesystem is available through which the key database can be viewed and manipulated.

<a id="rst-key-access-permissions"></a>

## Key Access Permissions

Keys have an owner user ID, a group access ID, and a permissions mask. The mask has up to eight bits each for possessor, user, group and other access. Only six of each set of eight bits are defined. These permissions granted are:

> - View
>
>   This permits a key or keyring's attributes to be viewed - including key type and description.
>
> - Read
>
>   This permits a key's payload to be viewed or a keyring's list of linked keys.
>
> - Write
>
>   This permits a key's payload to be instantiated or updated, or it allows a link to be added to or removed from a keyring.
>
> - Search
>
>   This permits keyrings to be searched and keys to be found. Searches can only recurse into nested keyrings that have search permission set.
>
> - Link
>
>   This permits a key or keyring to be linked to. To create a link from a keyring to a key, a process must have Write permission on the keyring and Link permission on the key.
>
> - Set Attribute
>
>   This permits a key's UID, GID and permissions mask to be changed.

For changing the ownership, group ID or permissions mask, being the owner of the key or having the sysadmin capability is sufficient.

<a id="rst-selinux-support"></a>

## SELinux Support

The security class "key" has been added to SELinux so that mandatory access controls can be applied to keys created within various contexts.  This support is preliminary, and is likely to change quite significantly in the near future. Currently, all of the basic permissions explained above are provided in SELinux as well; SELinux is simply invoked after all basic permission checks have been performed.

The value of the file /proc/self/attr/keycreate influences the labeling of newly-created keys.  If the contents of that file correspond to an SELinux security context, then the key will be assigned that context.  Otherwise, the key will be assigned the current context of the task that invoked the key creation request.  Tasks must be granted explicit permission to assign a particular context to newly-created keys, using the "create" permission in the key security class.

The default keyrings associated with users will be labeled with the default context of the user if and only if the login programs have been instrumented to properly initialize keycreate during the login process.  Otherwise, they will be labeled with the context of the login program itself.

Note, however, that the default keyrings associated with the root user are labeled with the default kernel context, since they are created early in the boot process, before root has a chance to log in.

The keyrings associated with new threads are each labeled with the context of their associated thread, and both session and process keyrings are handled similarly.

<a id="rst-new-procfs-files"></a>

## New ProcFS Files

Two files have been added to procfs by which an administrator can find out about the status of the key service:

> - /proc/keys
>
>   This lists the keys that are currently viewable by the task reading the file, giving information about their type, description and permissions. It is not possible to view the payload of the key this way, though some information about it may be given.
>
>   The only keys included in the list are those that grant View permission to the reading process whether or not it possesses them.  Note that LSM security checks are still performed, and may further filter out keys that the current process is not authorised to view.
>
>   The contents of the file look like this:
>
>
>
>   ```text
>   SERIAL   FLAGS  USAGE EXPY PERM     UID   GID   TYPE      DESCRIPTION: SUMMARY
>   00000001 I-----    39 perm 1f3f0000     0     0 keyring   _uid_ses.0: 1/4
>   00000002 I-----     2 perm 1f3f0000     0     0 keyring   _uid.0: empty
>   00000007 I-----     1 perm 1f3f0000     0     0 keyring   _pid.1: empty
>   0000018d I-----     1 perm 1f3f0000     0     0 keyring   _pid.412: empty
>   000004d2 I--Q--     1 perm 1f3f0000    32    -1 keyring   _uid.32: 1/4
>   000004d3 I--Q--     3 perm 1f3f0000    32    -1 keyring   _uid_ses.32: empty
>   00000892 I--QU-     1 perm 1f000000     0     0 user      metal:copper: 0
>   00000893 I--Q-N     1  35s 1f3f0000     0     0 user      metal:silver: 0
>   00000894 I--Q--     1  10h 003f0000     0     0 user      metal:gold: 0
>   ```
>
>   The flags are:
>
>
>
>   ```text
>   I       Instantiated
>   R       Revoked
>   D       Dead
>   Q       Contributes to user's quota
>   U       Under construction by callback to userspace
>   N       Negative key
>   ```
>
> - /proc/key-users
>
>   This file lists the tracking data for each user that has at least one key on the system.  Such data includes quota information and statistics:
>
>
>
>   ```text
>   [root@andromeda root]# cat /proc/key-users
>   0:     46 45/45 1/100 13/10000
>   29:     2 2/2 2/100 40/10000
>   32:     2 2/2 2/100 40/10000
>   38:     2 2/2 2/100 40/10000
>   ```
>
>   The format of each line is:
>
>
>
>   ```text
>   <UID>:                  User ID to which this applies
>   <usage>                 Structure refcount
>   <inst>/<keys>           Total number of keys and number instantiated
>   <keys>/<max>            Key count quota
>   <bytes>/<max>           Key size quota
>   ```

Four new sysctl files have been added also for the purpose of controlling the quota limits on keys:

> - /proc/sys/kernel/keys/root_maxkeys /proc/sys/kernel/keys/root_maxbytes
>
>   These files hold the maximum number of keys that root may have and the maximum total number of bytes of data that root may have stored in those keys.
>
> - /proc/sys/kernel/keys/maxkeys /proc/sys/kernel/keys/maxbytes
>
>   These files hold the maximum number of keys that each non-root user may have and the maximum total number of bytes of data that each of those users may have stored in their keys.

Root may alter these by writing each new limit as a decimal number string to the appropriate file.

<a id="rst-userspace-system-call-interface"></a>

## Userspace System Call Interface

Userspace can manipulate keys directly through three new syscalls: add_key, request_key and keyctl. The latter provides a number of functions for manipulating keys.

When referring to a key directly, userspace programs should use the key's serial number (a positive 32-bit integer). However, there are some special values available for referring to special keys and keyrings that relate to the process making the call:



```text
CONSTANT                        VALUE   KEY REFERENCED
==============================  ======  ===========================
KEY_SPEC_THREAD_KEYRING         -1      thread-specific keyring
KEY_SPEC_PROCESS_KEYRING        -2      process-specific keyring
KEY_SPEC_SESSION_KEYRING        -3      session-specific keyring
KEY_SPEC_USER_KEYRING           -4      UID-specific keyring
KEY_SPEC_USER_SESSION_KEYRING   -5      UID-session keyring
KEY_SPEC_GROUP_KEYRING          -6      GID-specific keyring
KEY_SPEC_REQKEY_AUTH_KEY        -7      assumed request_key()
                                          authorisation key
```

The main syscalls are:

> - Create a new key of given type, description and payload and add it to the nominated keyring:
>
>
>
>   ```text
>   key_serial_t add_key(const char *type, const char *desc,
>                        const void *payload, size_t plen,
>                        key_serial_t keyring);
>   ```
>
>   If a key of the same type and description as that proposed already exists in the keyring, this will try to update it with the given payload, or it will return error EEXIST if that function is not supported by the key type. The process must also have permission to write to the key to be able to update it. The new key will have all user permissions granted and no group or third party permissions.
>
>   Otherwise, this will attempt to create a new key of the specified type and description, and to instantiate it with the supplied payload and attach it to the keyring. In this case, an error will be generated if the process does not have permission to write to the keyring.
>
>   If the key type supports it, if the description is NULL or an empty string, the key type will try and generate a description from the content of the payload.
>
>   The payload is optional, and the pointer can be NULL if not required by the type. The payload is plen in size, and plen can be zero for an empty payload.
>
>   A new keyring can be generated by setting type "keyring", the keyring name as the description (or NULL) and setting the payload to NULL.
>
>   User defined keys can be created by specifying type "user". It is recommended that a user defined key's description by prefixed with a type ID and a colon, such as "krb5tgt:" for a Kerberos 5 ticket granting ticket.
>
>   Any other type must have been registered with the kernel in advance by a kernel service such as a filesystem.
>
>   The ID of the new or updated key is returned if successful.
>
> - Search the process's keyrings for a key, potentially calling out to userspace to create it:
>
>
>
>   ```text
>   key_serial_t request_key(const char *type, const char *description,
>                            const char *callout_info,
>                            key_serial_t dest_keyring);
>   ```
>
>   This function searches all the process's keyrings in the order thread, process, session for a matching key. This works very much like KEYCTL_SEARCH, including the optional attachment of the discovered key to a keyring.
>
>   If a key cannot be found, and if callout_info is not NULL, then /sbin/request-key will be invoked in an attempt to obtain a key. The callout_info string will be passed as an argument to the program.
>
>   To link a key into the destination keyring the key must grant link permission on the key to the caller and the keyring must grant write permission.
>
>   See also [Documentation/security/keys/request-key.rst](/kernel/internals/security/keys/request-key.md).

The keyctl syscall functions are:

> - Map a special key ID to a real key ID for this process:
>
>
>
>   ```text
>   key_serial_t keyctl(KEYCTL_GET_KEYRING_ID, key_serial_t id,
>                       int create);
>   ```
>
>   The special key specified by "id" is looked up (with the key being created if necessary) and the ID of the key or keyring thus found is returned if it exists.
>
>   If the key does not yet exist, the key will be created if "create" is non-zero; and the error ENOKEY will be returned if "create" is zero.
>
> - Replace the session keyring this process subscribes to with a new one:
>
>
>
>   ```text
>   key_serial_t keyctl(KEYCTL_JOIN_SESSION_KEYRING, const char *name);
>   ```
>
>   If name is NULL, an anonymous keyring is created attached to the process as its session keyring, displacing the old session keyring.
>
>   If name is not NULL, if a keyring of that name exists, the process attempts to attach it as the session keyring, returning an error if that is not permitted; otherwise a new keyring of that name is created and attached as the session keyring.
>
>   To attach to a named keyring, the keyring must have search permission for the process's ownership.
>
>   The ID of the new session keyring is returned if successful.
>
> - Update the specified key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_UPDATE, key_serial_t key, const void *payload,
>               size_t plen);
>   ```
>
>   This will try to update the specified key with the given payload, or it will return error EOPNOTSUPP if that function is not supported by the key type. The process must also have permission to write to the key to be able to update it.
>
>   The payload is of length plen, and may be absent or empty as for add_key().
>
> - Revoke a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_REVOKE, key_serial_t key);
>   ```
>
>   This makes a key unavailable for further operations. Further attempts to use the key will be met with error EKEYREVOKED, and the key will no longer be findable.
>
> - Change the ownership of a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_CHOWN, key_serial_t key, uid_t uid, gid_t gid);
>   ```
>
>   This function permits a key's owner and group ID to be changed. Either one of uid or gid can be set to -1 to suppress that change.
>
>   Only the superuser can change a key's owner to something other than the key's current owner. Similarly, only the superuser can change a key's group ID to something other than the calling process's group ID or one of its group list members.
>
> - Change the permissions mask on a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_SETPERM, key_serial_t key, key_perm_t perm);
>   ```
>
>   This function permits the owner of a key or the superuser to change the permissions mask on a key.
>
>   Only bits the available bits are permitted; if any other bits are set, error EINVAL will be returned.
>
> - Describe a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_DESCRIBE, key_serial_t key, char *buffer,
>               size_t buflen);
>   ```
>
>   This function returns a summary of the key's attributes (but not its payload data) as a string in the buffer provided.
>
>   Unless there's an error, it always returns the amount of data it could produce, even if that's too big for the buffer, but it won't copy more than requested to userspace. If the buffer pointer is NULL then no copy will take place.
>
>   A process must have view permission on the key for this function to be successful.
>
>   If successful, a string is placed in the buffer in the following format:
>
>
>
>   ```text
>   <type>;<uid>;<gid>;<perm>;<description>
>   ```
>
>   Where type and description are strings, uid and gid are decimal, and perm is hexadecimal. A NUL character is included at the end of the string if the buffer is sufficiently big.
>
>   This can be parsed with:
>
>
>
>   ```text
>   sscanf(buffer, "%[^;];%d;%d;%o;%s", type, &uid, &gid, &mode, desc);
>   ```
>
> - Clear out a keyring:
>
>
>
>   ```text
>   long keyctl(KEYCTL_CLEAR, key_serial_t keyring);
>   ```
>
>   This function clears the list of keys attached to a keyring. The calling process must have write permission on the keyring, and it must be a keyring (or else error ENOTDIR will result).
>
>   This function can also be used to clear special kernel keyrings if they are appropriately marked if the user has CAP_SYS_ADMIN capability.  The DNS resolver cache keyring is an example of this.
>
> - Link a key into a keyring:
>
>
>
>   ```text
>   long keyctl(KEYCTL_LINK, key_serial_t keyring, key_serial_t key);
>   ```
>
>   This function creates a link from the keyring to the key. The process must have write permission on the keyring and must have link permission on the key.
>
>   Should the keyring not be a keyring, error ENOTDIR will result; and if the keyring is full, error ENFILE will result.
>
>   The link procedure checks the nesting of the keyrings, returning ELOOP if it appears too deep or EDEADLK if the link would introduce a cycle.
>
>   Any links within the keyring to keys that match the new key in terms of type and description will be discarded from the keyring as the new one is added.
>
> - Move a key from one keyring to another:
>
>
>
>   ```text
>   long keyctl(KEYCTL_MOVE,
>               key_serial_t id,
>               key_serial_t from_ring_id,
>               key_serial_t to_ring_id,
>               unsigned int flags);
>   ```
>
>   Move the key specified by "id" from the keyring specified by "from_ring_id" to the keyring specified by "to_ring_id".  If the two keyrings are the same, nothing is done.
>
>   "flags" can have KEYCTL_MOVE_EXCL set in it to cause the operation to fail with EEXIST if a matching key exists in the destination keyring, otherwise such a key will be replaced.
>
>   A process must have link permission on the key for this function to be successful and write permission on both keyrings.  Any errors that can occur from KEYCTL_LINK also apply on the destination keyring here.
>
> - Unlink a key or keyring from another keyring:
>
>
>
>   ```text
>   long keyctl(KEYCTL_UNLINK, key_serial_t keyring, key_serial_t key);
>   ```
>
>   This function looks through the keyring for the first link to the specified key, and removes it if found. Subsequent links to that key are ignored. The process must have write permission on the keyring.
>
>   If the keyring is not a keyring, error ENOTDIR will result; and if the key is not present, error ENOENT will be the result.
>
> - Search a keyring tree for a key:
>
>
>
>   ```text
>   key_serial_t keyctl(KEYCTL_SEARCH, key_serial_t keyring,
>                       const char *type, const char *description,
>                       key_serial_t dest_keyring);
>   ```
>
>   This searches the keyring tree headed by the specified keyring until a key is found that matches the type and description criteria. Each keyring is checked for keys before recursion into its children occurs.
>
>   The process must have search permission on the top level keyring, or else error EACCES will result. Only keyrings that the process has search permission on will be recursed into, and only keys and keyrings for which a process has search permission can be matched. If the specified keyring is not a keyring, ENOTDIR will result.
>
>   If the search succeeds, the function will attempt to link the found key into the destination keyring if one is supplied (non-zero ID). All the constraints applicable to KEYCTL_LINK apply in this case too.
>
>   Error ENOKEY, EKEYREVOKED or EKEYEXPIRED will be returned if the search fails. On success, the resulting key ID will be returned.
>
> - Read the payload data from a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_READ, key_serial_t keyring, char *buffer,
>               size_t buflen);
>   ```
>
>   This function attempts to read the payload data from the specified key into the buffer. The process must have read permission on the key to succeed.
>
>   The returned data will be processed for presentation by the key type. For instance, a keyring will return an array of key_serial_t entries representing the IDs of all the keys to which it is subscribed. The user defined key type will return its data as is. If a key type does not implement this function, error EOPNOTSUPP will result.
>
>   If the specified buffer is too small, then the size of the buffer required will be returned.  Note that in this case, the contents of the buffer may have been overwritten in some undefined way.
>
>   Otherwise, on success, the function will return the amount of data copied into the buffer.
>
> - Instantiate a partially constructed key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_INSTANTIATE, key_serial_t key,
>               const void *payload, size_t plen,
>               key_serial_t keyring);
>   long keyctl(KEYCTL_INSTANTIATE_IOV, key_serial_t key,
>               const struct iovec *payload_iov, unsigned ioc,
>               key_serial_t keyring);
>   ```
>
>   If the kernel calls back to userspace to complete the instantiation of a key, userspace should use this call to supply data for the key before the invoked process returns, or else the key will be marked negative automatically.
>
>   The process must have write access on the key to be able to instantiate it, and the key must be uninstantiated.
>
>   If a keyring is specified (non-zero), the key will also be linked into that keyring, however all the constraints applying in KEYCTL_LINK apply in this case too.
>
>   The payload and plen arguments describe the payload data as for add_key().
>
>   The payload_iov and ioc arguments describe the payload data in an iovec array instead of a single buffer.
>
> - Negatively instantiate a partially constructed key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_NEGATE, key_serial_t key,
>               unsigned timeout, key_serial_t keyring);
>   long keyctl(KEYCTL_REJECT, key_serial_t key,
>               unsigned timeout, unsigned error, key_serial_t keyring);
>   ```
>
>   If the kernel calls back to userspace to complete the instantiation of a key, userspace should use this call mark the key as negative before the invoked process returns if it is unable to fulfill the request.
>
>   The process must have write access on the key to be able to instantiate it, and the key must be uninstantiated.
>
>   If a keyring is specified (non-zero), the key will also be linked into that keyring, however all the constraints applying in KEYCTL_LINK apply in this case too.
>
>   If the key is rejected, future searches for it will return the specified error code until the rejected key expires.  Negating the key is the same as rejecting the key with ENOKEY as the error code.
>
> - Set the default request-key destination keyring:
>
>
>
>   ```text
>   long keyctl(KEYCTL_SET_REQKEY_KEYRING, int reqkey_defl);
>   ```
>
>   This sets the default keyring to which implicitly requested keys will be attached for this thread. reqkey_defl should be one of these constants:
>
>
>
>   ```text
>   CONSTANT                                VALUE   NEW DEFAULT KEYRING
>   ======================================  ======  =======================
>   KEY_REQKEY_DEFL_NO_CHANGE               -1      No change
>   KEY_REQKEY_DEFL_DEFAULT                 0       Default[1]
>   KEY_REQKEY_DEFL_THREAD_KEYRING          1       Thread keyring
>   KEY_REQKEY_DEFL_PROCESS_KEYRING         2       Process keyring
>   KEY_REQKEY_DEFL_SESSION_KEYRING         3       Session keyring
>   KEY_REQKEY_DEFL_USER_KEYRING            4       User keyring
>   KEY_REQKEY_DEFL_USER_SESSION_KEYRING    5       User session keyring
>   KEY_REQKEY_DEFL_GROUP_KEYRING           6       Group keyring
>   ```
>
>   The old default will be returned if successful and error EINVAL will be returned if reqkey_defl is not one of the above values.
>
>   The default keyring can be overridden by the keyring indicated to the request_key() system call.
>
>   Note that this setting is inherited across fork/exec.
>
>   \[1\] The default is: the thread keyring if there is one, otherwise the process keyring if there is one, otherwise the session keyring if there is one, otherwise the user default session keyring.
>
> - Set the timeout on a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_SET_TIMEOUT, key_serial_t key, unsigned timeout);
>   ```
>
>   This sets or clears the timeout on a key. The timeout can be 0 to clear the timeout or a number of seconds to set the expiry time that far into the future.
>
>   The process must have attribute modification access on a key to set its timeout. Timeouts may not be set with this function on negative, revoked or expired keys.
>
> - Assume the authority granted to instantiate a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_ASSUME_AUTHORITY, key_serial_t key);
>   ```
>
>   This assumes or divests the authority required to instantiate the specified key. Authority can only be assumed if the thread has the authorisation key associated with the specified key in its keyrings somewhere.
>
>   Once authority is assumed, searches for keys will also search the requester's keyrings using the requester's security label, UID, GID and groups.
>
>   If the requested authority is unavailable, error EPERM will be returned, likewise if the authority has been revoked because the target key is already instantiated.
>
>   If the specified key is 0, then any assumed authority will be divested.
>
>   The assumed authoritative key is inherited across fork and exec.
>
> - Get the LSM security context attached to a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_GET_SECURITY, key_serial_t key, char *buffer,
>               size_t buflen)
>   ```
>
>   This function returns a string that represents the LSM security context attached to a key in the buffer provided.
>
>   Unless there's an error, it always returns the amount of data it could produce, even if that's too big for the buffer, but it won't copy more than requested to userspace. If the buffer pointer is NULL then no copy will take place.
>
>   A NUL character is included at the end of the string if the buffer is sufficiently big.  This is included in the returned count.  If no LSM is in force then an empty string will be returned.
>
>   A process must have view permission on the key for this function to be successful.
>
> - Install the calling process's session keyring on its parent:
>
>
>
>   ```text
>   long keyctl(KEYCTL_SESSION_TO_PARENT);
>   ```
>
>   This functions attempts to install the calling process's session keyring on to the calling process's parent, replacing the parent's current session keyring.
>
>   The calling process must have the same ownership as its parent, the keyring must have the same ownership as the calling process, the calling process must have LINK permission on the keyring and the active LSM module mustn't deny permission, otherwise error EPERM will be returned.
>
>   Error ENOMEM will be returned if there was insufficient memory to complete the operation, otherwise 0 will be returned to indicate success.
>
>   The keyring will be replaced next time the parent process leaves the kernel and resumes executing userspace.
>
> - Invalidate a key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_INVALIDATE, key_serial_t key);
>   ```
>
>   This function marks a key as being invalidated and then wakes up the garbage collector.  The garbage collector immediately removes invalidated keys from all keyrings and deletes the key when its reference count reaches zero.
>
>   Keys that are marked invalidated become invisible to normal key operations immediately, though they are still visible in /proc/keys until deleted (they're marked with an 'i' flag).
>
>   A process must have search permission on the key for this function to be successful.
>
> - Compute a Diffie-Hellman shared secret or public key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_DH_COMPUTE, struct keyctl_dh_params *params,
>               char *buffer, size_t buflen, struct keyctl_kdf_params *kdf);
>   ```
>
>   The params struct contains serial numbers for three keys:
>
>
>
>   ```text
>   - The prime, p, known to both parties
>   - The local private key
>   - The base integer, which is either a shared generator or the
>     remote public key
>   ```
>
>   The value computed is:
>
>
>
>   ```text
>   result = base ^ private (mod prime)
>   ```
>
>   If the base is the shared generator, the result is the local public key.  If the base is the remote public key, the result is the shared secret.
>
>   If the parameter kdf is NULL, the following applies:
>
>   > - The buffer length must be at least the length of the prime, or zero.
>   >
>   > - If the buffer length is nonzero, the length of the result is returned when it is successfully calculated and copied in to the buffer. When the buffer length is zero, the minimum required buffer length is returned.
>
>   The kdf parameter allows the caller to apply a key derivation function (KDF) on the Diffie-Hellman computation where only the result of the KDF is returned to the caller. The KDF is characterized with struct keyctl_kdf_params as follows:
>
>   > - `char *hashname` specifies the NUL terminated string identifying the hash used from the kernel crypto API and applied for the KDF operation. The KDF implementation complies with SP800-56A as well as with SP800-108 (the counter KDF).
>   >
>   > - `char *otherinfo` specifies the OtherInfo data as documented in SP800-56A section 5.8.1.2. The length of the buffer is given with otherinfolen. The format of OtherInfo is defined by the caller. The otherinfo pointer may be NULL if no OtherInfo shall be used.
>
>   This function will return error EOPNOTSUPP if the key type is not supported, error ENOKEY if the key could not be found, or error EACCES if the key is not readable by the caller. In addition, the function will return EMSGSIZE when the parameter kdf is non-NULL and either the buffer length or the OtherInfo length exceeds the allowed length.
>
> - Restrict keyring linkage:
>
>
>
>   ```text
>   long keyctl(KEYCTL_RESTRICT_KEYRING, key_serial_t keyring,
>               const char *type, const char *restriction);
>   ```
>
>   An existing keyring can restrict linkage of additional keys by evaluating the contents of the key according to a restriction scheme.
>
>   "keyring" is the key ID for an existing keyring to apply a restriction to. It may be empty or may already have keys linked. Existing linked keys will remain in the keyring even if the new restriction would reject them.
>
>   "type" is a registered key type.
>
>   "restriction" is a string describing how key linkage is to be restricted. The format varies depending on the key type, and the string is passed to the lookup_restriction() function for the requested type.  It may specify a method and relevant data for the restriction such as signature verification or constraints on key payload. If the requested key type is later unregistered, no keys may be added to the keyring after the key type is removed.
>
>   To apply a keyring restriction the process must have Set Attribute permission and the keyring must not be previously restricted.
>
>   One application of restricted keyrings is to verify X.509 certificate chains or individual certificate signatures using the asymmetric key type. See [Documentation/crypto/asymmetric-keys.rst](/kernel/internals/crypto/asymmetric-keys.md) for specific restrictions applicable to the asymmetric key type.
>
> - Query an asymmetric key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_PKEY_QUERY,
>               key_serial_t key_id, unsigned long reserved,
>               const char *params,
>               struct keyctl_pkey_query *info);
>   ```
>
>   Get information about an asymmetric key.  Specific algorithms and encodings may be queried by using the `params` argument.  This is a string containing a space- or tab-separated string of key-value pairs. Currently supported keys include `enc` and `hash`.  The information is returned in the keyctl_pkey_query struct:
>
>
>
>   ```text
>   __u32   supported_ops;
>   __u32   key_size;
>   __u16   max_data_size;
>   __u16   max_sig_size;
>   __u16   max_enc_size;
>   __u16   max_dec_size;
>   __u32   __spare[10];
>   ```
>
>   `supported_ops` contains a bit mask of flags indicating which ops are supported.  This is constructed from a bitwise-OR of:
>
>
>
>   ```text
>   KEYCTL_SUPPORTS_{ENCRYPT,DECRYPT,SIGN,VERIFY}
>   ```
>
>   `key_size` indicated the size of the key in bits.
>
>   `max_*_size` indicate the maximum sizes in bytes of a blob of data to be signed, a signature blob, a blob to be encrypted and a blob to be decrypted.
>
>   `__spare[]` must be set to 0.  This is intended for future use to hand over one or more passphrases needed unlock a key.
>
>   If successful, 0 is returned.  If the key is not an asymmetric key, EOPNOTSUPP is returned.
>
> - Encrypt, decrypt, sign or verify a blob using an asymmetric key:
>
>
>
>   ```text
>   long keyctl(KEYCTL_PKEY_ENCRYPT,
>               const struct keyctl_pkey_params *params,
>               const char *info,
>               const void *in,
>               void *out);
>
>   long keyctl(KEYCTL_PKEY_DECRYPT,
>               const struct keyctl_pkey_params *params,
>               const char *info,
>               const void *in,
>               void *out);
>
>   long keyctl(KEYCTL_PKEY_SIGN,
>               const struct keyctl_pkey_params *params,
>               const char *info,
>               const void *in,
>               void *out);
>
>   long keyctl(KEYCTL_PKEY_VERIFY,
>               const struct keyctl_pkey_params *params,
>               const char *info,
>               const void *in,
>               const void *in2);
>   ```
>
>   Use an asymmetric key to perform a public-key cryptographic operation a blob of data.  For encryption and verification, the asymmetric key may only need the public parts to be available, but for decryption and signing the private parts are required also.
>
>   The parameter block pointed to by params contains a number of integer values:
>
>
>
>   ```text
>   __s32           key_id;
>   __u32           in_len;
>   __u32           out_len;
>   __u32           in2_len;
>   ```
>
>   `key_id` is the ID of the asymmetric key to be used.  `in_len` and `in2_len` indicate the amount of data in the in and in2 buffers and `out_len` indicates the size of the out buffer as appropriate for the above operations.
>
>   For a given operation, the in and out buffers are used as follows:
>
>
>
>   ```text
>   Operation ID            in,in_len       out,out_len     in2,in2_len
>   ======================= =============== =============== ===============
>   KEYCTL_PKEY_ENCRYPT     Raw data        Encrypted data  -
>   KEYCTL_PKEY_DECRYPT     Encrypted data  Raw data        -
>   KEYCTL_PKEY_SIGN        Raw data        Signature       -
>   KEYCTL_PKEY_VERIFY      Raw data        -               Signature
>   ```
>
>   `info` is a string of key=value pairs that supply supplementary information.  These include:
>
>   > - **`enc=<encoding>` The encoding of the encrypted/signature blob.  This**
>   >
>   >   can be "pkcs1" for RSASSA-PKCS1-v1.5 or RSAES-PKCS1-v1.5; "pss" for "RSASSA-PSS"; "oaep" for "RSAES-OAEP".  If omitted or is "raw", the raw output of the encryption function is specified.
>   >
>   > - **`hash=<algo>` If the data buffer contains the output of a hash**
>   >
>   >   function and the encoding includes some indication of which hash function was used, the hash function can be specified with this, eg. "hash=sha256".
>
>   The `__spare[]` space in the parameter block must be set to 0.  This is intended, amongst other things, to allow the passing of passphrases required to unlock a key.
>
>   If successful, encrypt, decrypt and sign all return the amount of data written into the output buffer.  Verification returns 0 on success.
>
> - Watch a key or keyring for changes:
>
>
>
>   ```text
>   long keyctl(KEYCTL_WATCH_KEY, key_serial_t key, int queue_fd,
>               const struct watch_notification_filter *filter);
>   ```
>
>   This will set or remove a watch for changes on the specified key or keyring.
>
>   "key" is the ID of the key to be watched.
>
>   "queue_fd" is a file descriptor referring to an open pipe which manages the buffer into which notifications will be delivered.
>
>   "filter" is either NULL to remove a watch or a filter specification to indicate what events are required from the key.
>
>   See [Documentation/core-api/watch_queue.rst](/kernel/internals/core-api/watch-queue.md) for more information.
>
>   Note that only one watch may be emplaced for any particular \{ key, queue_fd \} combination.
>
>   Notification records look like:
>
>
>
>   ```text
>   struct key_notification {
>           struct watch_notification watch;
>           __u32   key_id;
>           __u32   aux;
>   };
>   ```
>
>   In this, watch::type will be "WATCH_TYPE_KEY_NOTIFY" and subtype will be one of:
>
>
>
>   ```text
>   NOTIFY_KEY_INSTANTIATED
>   NOTIFY_KEY_UPDATED
>   NOTIFY_KEY_LINKED
>   NOTIFY_KEY_UNLINKED
>   NOTIFY_KEY_CLEARED
>   NOTIFY_KEY_REVOKED
>   NOTIFY_KEY_INVALIDATED
>   NOTIFY_KEY_SETATTR
>   ```
>
>   Where these indicate a key being instantiated/rejected, updated, a link being made in a keyring, a link being removed from a keyring, a keyring being cleared, a key being revoked, a key being invalidated or a key having one of its attributes changed (user, group, perm, timeout, restriction).
>
>   If a watched key is deleted, a basic watch_notification will be issued with "type" set to WATCH_TYPE_META and "subtype" set to watch_meta_removal_notification.  The watchpoint ID will be set in the "info" field.
>
>   This needs to be configured by enabling:
>
>   > "Provide key/keyring change notifications" (KEY_NOTIFICATIONS)

<a id="rst-kernel-services"></a>

## Kernel Services

The kernel services for key management are fairly simple to deal with. They can be broken down into two areas: keys and key types.

Dealing with keys is fairly straightforward. Firstly, the kernel service registers its type, then it searches for a key of that type. It should retain the key as long as it has need of it, and then it should release it. For a filesystem or device file, a search would probably be performed during the open call, and the key released upon close. How to deal with conflicting keys due to two different users opening the same file is left to the filesystem author to solve.

To access the key manager, the following header must be \#included:



```text
<linux/key.h>
```

Specific key types should have a header file under include/keys/ that should be used to access that type.  For keys of type "user", for example, that would be:



```text
<keys/user-type.h>
```

Note that there are two different types of pointers to keys that may be encountered:

> - struct key \*
>
>   This simply points to the key structure itself. Key structures will be at least four-byte aligned.
>
> - key_ref_t
>
>   This is equivalent to a `struct key *`, but the least significant bit is set if the caller "possesses" the key. By "possession" it is meant that the calling processes has a searchable link to the key from one of its keyrings. There are three functions for dealing with these:
>
>
>
>   ```text
>   key_ref_t make_key_ref(const struct key *key, bool possession);
>
>   struct key *key_ref_to_ptr(const key_ref_t key_ref);
>
>   bool is_key_possessed(const key_ref_t key_ref);
>   ```
>
>   The first function constructs a key reference from a key pointer and possession information (which must be true or false).
>
>   The second function retrieves the key pointer from a reference and the third retrieves the possession flag.

When accessing a key's payload contents, certain precautions must be taken to prevent access vs modification races. See the section "Notes on accessing payload contents" for more information.

> - To search for a key, call:
>
>
>
>   ```text
>   struct key *request_key(const struct key_type *type,
>                           const char *description,
>                           const char *callout_info);
>   ```
>
>   This is used to request a key or keyring with a description that matches the description specified according to the key type's match_preparse() method. This permits approximate matching to occur. If callout_string is not NULL, then /sbin/request-key will be invoked in an attempt to obtain the key from userspace. In that case, callout_string will be passed as an argument to the program.
>
>   Should the function fail error ENOKEY, EKEYEXPIRED or EKEYREVOKED will be returned.
>
>   If successful, the key will have been attached to the default keyring for implicitly obtained request-key keys, as set by KEYCTL_SET_REQKEY_KEYRING.
>
>   See also [Documentation/security/keys/request-key.rst](/kernel/internals/security/keys/request-key.md).
>
> - To search for a key in a specific domain, call:
>
>
>
>   ```text
>   struct key *request_key_tag(const struct key_type *type,
>                               const char *description,
>                               struct key_tag *domain_tag,
>                               const char *callout_info);
>   ```
>
>   This is identical to request_key(), except that a domain tag may be specifies that causes search algorithm to only match keys matching that tag.  The domain_tag may be NULL, specifying a global domain that is separate from any nominated domain.
>
> - To search for a key, passing auxiliary data to the upcaller, call:
>
>
>
>   ```text
>   struct key *request_key_with_auxdata(const struct key_type *type,
>                                        const char *description,
>                                        struct key_tag *domain_tag,
>                                        const void *callout_info,
>                                        size_t callout_len,
>                                        void *aux);
>   ```
>
>   This is identical to request_key_tag(), except that the auxiliary data is passed to the key_type-&gt;request_key() op if it exists, and the callout_info is a blob of length callout_len, if given (the length may be 0).
>
> - To search for a key under RCU conditions, call:
>
>
>
>   ```text
>   struct key *request_key_rcu(const struct key_type *type,
>                               const char *description,
>                               struct key_tag *domain_tag);
>   ```
>
>   which is similar to request_key_tag() except that it does not check for keys that are under construction and it will not call out to userspace to construct a key if it can't find a match.
>
> - When it is no longer required, the key should be released using:
>
>
>
>   ```text
>   void key_put(struct key *key);
>   ```
>
>   Or:
>
>
>
>   ```text
>   void key_ref_put(key_ref_t key_ref);
>   ```
>
>   These can be called from interrupt context. If CONFIG_KEYS is not set then the argument will not be parsed.
>
> - Extra references can be made to a key by calling one of the following functions:
>
>
>
>   ```text
>   struct key *__key_get(struct key *key);
>   struct key *key_get(struct key *key);
>   ```
>
>   Keys so references will need to be disposed of by calling key_put() when they've been finished with.  The key pointer passed in will be returned.
>
>   In the case of key_get(), if the pointer is NULL or CONFIG_KEYS is not set then the key will not be dereferenced and no increment will take place.
>
> - A key's serial number can be obtained by calling:
>
>
>
>   ```text
>   key_serial_t key_serial(struct key *key);
>   ```
>
>   If key is NULL or if CONFIG_KEYS is not set then 0 will be returned (in the latter case without parsing the argument).
>
> - If a keyring was found in the search, this can be further searched by:
>
>
>
>   ```text
>   key_ref_t keyring_search(key_ref_t keyring_ref,
>                            const struct key_type *type,
>                            const char *description,
>                            bool recurse)
>   ```
>
>   This searches the specified keyring only (recurse == false) or keyring tree (recurse == true) specified for a matching key. Error ENOKEY is returned upon failure (use IS_ERR/PTR_ERR to determine). If successful, the returned key will need to be released.
>
>   The possession attribute from the keyring reference is used to control access through the permissions mask and is propagated to the returned key reference pointer if successful.
>
> - A keyring can be created by:
>
>
>
>   ```text
>   struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
>                             const struct cred *cred,
>                             key_perm_t perm,
>                             struct key_restriction *restrict_link,
>                             unsigned long flags,
>                             struct key *dest);
>   ```
>
>   This creates a keyring with the given attributes and returns it.  If dest is not NULL, the new keyring will be linked into the keyring to which it points.  No permission checks are made upon the destination keyring.
>
>   Error EDQUOT can be returned if the keyring would overload the quota (pass KEY_ALLOC_NOT_IN_QUOTA in flags if the keyring shouldn't be accounted towards the user's quota).  Error ENOMEM can also be returned.
>
>   If restrict_link is not NULL, it should point to a structure that contains the function that will be called each time an attempt is made to link a key into the new keyring.  The structure may also contain a key pointer and an associated key type.  The function is called to check whether a key may be added into the keyring or not.  The key type is used by the garbage collector to clean up function or data pointers in this structure if the given key type is unregistered.  Callers of key_create_or_update() within the kernel can pass KEY_ALLOC_BYPASS_RESTRICTION to suppress the check. An example of using this is to manage rings of cryptographic keys that are set up when the kernel boots where userspace is also permitted to add keys - provided they can be verified by a key the kernel already has.
>
>   When called, the restriction function will be passed the keyring being added to, the key type, the payload of the key being added, and data to be used in the restriction check.  Note that when a new key is being created, this is called between payload preparsing and actual key creation.  The function should return 0 to allow the link or an error to reject it.
>
>   A convenience function, restrict_link_reject, exists to always return -EPERM to in this case.
>
> - To check the validity of a key, this function can be called:
>
>
>
>   ```text
>   int validate_key(struct key *key);
>   ```
>
>   This checks that the key in question hasn't expired or and hasn't been revoked. Should the key be invalid, error EKEYEXPIRED or EKEYREVOKED will be returned. If the key is NULL or if CONFIG_KEYS is not set then 0 will be returned (in the latter case without parsing the argument).
>
> - To register a key type, the following function should be called:
>
>
>
>   ```text
>   int register_key_type(struct key_type *type);
>   ```
>
>   This will return error EEXIST if a type of the same name is already present.
>
> - To unregister a key type, call:
>
>
>
>   ```text
>   void unregister_key_type(struct key_type *type);
>   ```

Under some circumstances, it may be desirable to deal with a bundle of keys. The facility provides access to the keyring type for managing such a bundle:



```text
struct key_type key_type_keyring;
```

This can be used with a function such as request_key() to find a specific keyring in a process's keyrings.  A keyring thus found can then be searched with keyring_search().  Note that it is not possible to use request_key() to search a specific keyring, so using keyrings in this way is of limited utility.

<a id="rst-notes-on-accessing-payload-contents"></a>

## Notes On Accessing Payload Contents

The simplest payload is just data stored in key-&gt;payload directly.  In this case, there's no need to indulge in RCU or locking when accessing the payload.

More complex payload contents must be allocated and pointers to them set in the key-&gt;payload.data\[\] array.  One of the following ways must be selected to access the data:

> 1. Unmodifiable key type.
>
>    If the key type does not have a modify method, then the key's payload can be accessed without any form of locking, provided that it's known to be instantiated (uninstantiated keys cannot be "found").
>
> 2. The key's semaphore.
>
>    The semaphore could be used to govern access to the payload and to control the payload pointer. It must be write-locked for modifications and would have to be read-locked for general access. The disadvantage of doing this is that the accessor may be required to sleep.
>
> 3. RCU.
>
>    RCU must be used when the semaphore isn't already held; if the semaphore is held then the contents can't change under you unexpectedly as the semaphore must still be used to serialise modifications to the key. The key management code takes care of this for the key type.
>
>    However, this means using:
>
>
>
>    ```text
>    rcu_read_lock() ... rcu_dereference() ... rcu_read_unlock()
>    ```
>
>    to read the pointer, and:
>
>
>
>    ```text
>    rcu_dereference() ... rcu_assign_pointer() ... call_rcu()
>    ```
>
>    to set the pointer and dispose of the old contents after a grace period. Note that only the key type should ever modify a key's payload.
>
>    Furthermore, an RCU controlled payload must hold a struct rcu_head for the use of call_rcu() and, if the payload is of variable size, the length of the payload. key-&gt;datalen cannot be relied upon to be consistent with the payload just dereferenced if the key's semaphore is not held.
>
>    Note that key-&gt;payload.data\[0\] has a shadow that is marked for \__rcu usage.  This is called key-&gt;payload.rcu_data0.  The following accessors wrap the RCU calls to this element:
>
>    - **a)** Set or change the first payload pointer:
>
>
>
>      ```text
>      rcu_assign_keypointer(struct key *key, void *data);
>      ```
>
>    - **b)** Read the first payload pointer with the key semaphore held:
>
>
>
>      ```text
>             [const] void *dereference_key_locked([const] struct key *key);
>
>      Note that the return value will inherit its constness from the key
>      parameter.  Static analysis will give an error if it things the lock
>      isn't held.
>      ```
>
>    - **c)** Read the first payload pointer with the RCU read lock held:
>
>
>
>      ```text
>      const void *dereference_key_rcu(const struct key *key);
>      ```

<a id="rst-defining-a-key-type"></a>

## Defining a Key Type

A kernel service may want to define its own key type. For instance, an AFS filesystem might want to define a Kerberos 5 ticket key type. To do this, it author fills in a key_type struct and registers it with the system.

Source files that implement key types should include the following header file:



```text
<linux/key-type.h>
```

The structure has a number of fields, some of which are mandatory:

> - `const char *name`
>
>   The name of the key type. This is used to translate a key type name supplied by userspace into a pointer to the structure.
>
> - `size_t def_datalen`
>
>   This is optional - it supplies the default payload data length as contributed to the quota. If the key type's payload is always or almost always the same size, then this is a more efficient way to do things.
>
>   The data length (and quota) on a particular key can always be changed during instantiation or update by calling:
>
>
>
>   ```text
>   int key_payload_reserve(struct key *key, size_t datalen);
>   ```
>
>   With the revised data length. Error EDQUOT will be returned if this is not viable.
>
> - `int (*vet_description)(const char *description);`
>
>   This optional method is called to vet a key description.  If the key type doesn't approve of the key description, it may return an error, otherwise it should return 0.
>
> - `int (*preparse)(struct key_preparsed_payload *prep);`
>
>   This optional method permits the key type to attempt to parse payload before a key is created (add key) or the key semaphore is taken (update or instantiate key).  The structure pointed to by prep looks like:
>
>
>
>   ```text
>   struct key_preparsed_payload {
>           char            *description;
>           union key_payload payload;
>           const void      *data;
>           size_t          datalen;
>           size_t          quotalen;
>           time_t          expiry;
>   };
>   ```
>
>   Before calling the method, the caller will fill in data and datalen with the payload blob parameters; quotalen will be filled in with the default quota size from the key type; expiry will be set to TIME_T_MAX and the rest will be cleared.
>
>   If a description can be proposed from the payload contents, that should be attached as a string to the description field.  This will be used for the key description if the caller of add_key() passes NULL or "".
>
>   The method can attach anything it likes to payload.  This is merely passed along to the instantiate() or update() operations.  If set, the expiry time will be applied to the key if it is instantiated from this data.
>
>   The method should return 0 if successful or a negative error code otherwise.
>
> - `void (*free_preparse)(struct key_preparsed_payload *prep);`
>
>   This method is only required if the preparse() method is provided, otherwise it is unused.  It cleans up anything attached to the description and payload fields of the key_preparsed_payload struct as filled in by the preparse() method.  It will always be called after preparse() returns successfully, even if instantiate() or update() succeed.
>
> - `int (*instantiate)(struct key *key, struct key_preparsed_payload *prep);`
>
>   This method is called to attach a payload to a key during construction. The payload attached need not bear any relation to the data passed to this function.
>
>   The prep-&gt;data and prep-&gt;datalen fields will define the original payload blob.  If preparse() was supplied then other fields may be filled in also.
>
>   If the amount of data attached to the key differs from the size in keytype-&gt;def_datalen, then key_payload_reserve() should be called.
>
>   This method does not have to lock the key in order to attach a payload. The fact that KEY_FLAG_INSTANTIATED is not set in key-&gt;flags prevents anything else from gaining access to the key.
>
>   It is safe to sleep in this method.
>
>   generic_key_instantiate() is provided to simply copy the data from prep-&gt;payload.data\[\] to key-&gt;payload.data\[\], with RCU-safe assignment on the first element.  It will then clear prep-&gt;payload.data\[\] so that the free_preparse method doesn't release the data.
>
> - `int (*update)(struct key *key, const void *data, size_t datalen);`
>
>   If this type of key can be updated, then this method should be provided. It is called to update a key's payload from the blob of data provided.
>
>   The prep-&gt;data and prep-&gt;datalen fields will define the original payload blob.  If preparse() was supplied then other fields may be filled in also.
>
>   key_payload_reserve() should be called if the data length might change before any changes are actually made. Note that if this succeeds, the type is committed to changing the key because it's already been altered, so all memory allocation must be done first.
>
>   The key will have its semaphore write-locked before this method is called, but this only deters other writers; any changes to the key's payload must be made under RCU conditions, and call_rcu() must be used to dispose of the old payload.
>
>   key_payload_reserve() should be called before the changes are made, but after all allocations and other potentially failing function calls are made.
>
>   It is safe to sleep in this method.
>
> - `int (*match_preparse)(struct key_match_data *match_data);`
>
>   This method is optional.  It is called when a key search is about to be performed.  It is given the following structure:
>
>
>
>   ```text
>   struct key_match_data {
>           bool (*cmp)(const struct key *key,
>                       const struct key_match_data *match_data);
>           const void      *raw_data;
>           void            *preparsed;
>           unsigned        lookup_type;
>   };
>   ```
>
>   On entry, raw_data will be pointing to the criteria to be used in matching a key by the caller and should not be modified.  `(*cmp)()` will be pointing to the default matcher function (which does an exact description match against raw_data) and lookup_type will be set to indicate a direct lookup.
>
>   The following lookup_type values are available:
>
>   > - KEYRING_SEARCH_LOOKUP_DIRECT - A direct lookup hashes the type and description to narrow down the search to a small number of keys.
>   >
>   > - KEYRING_SEARCH_LOOKUP_ITERATE - An iterative lookup walks all the keys in the keyring until one is matched.  This must be used for any search that's not doing a simple direct match on the key description.
>
>   The method may set cmp to point to a function of its choice that does some other form of match, may set lookup_type to KEYRING_SEARCH_LOOKUP_ITERATE and may attach something to the preparsed pointer for use by `(*cmp)()`. `(*cmp)()` should return true if a key matches and false otherwise.
>
>   If preparsed is set, it may be necessary to use the match_free() method to clean it up.
>
>   The method should return 0 if successful or a negative error code otherwise.
>
>   It is permitted to sleep in this method, but `(*cmp)()` may not sleep as locks will be held over it.
>
>   If match_preparse() is not provided, keys of this type will be matched exactly by their description.
>
> - `void (*match_free)(struct key_match_data *match_data);`
>
>   This method is optional.  If given, it called to clean up match_data-&gt;preparsed after a successful call to match_preparse().
>
> - `void (*revoke)(struct key *key);`
>
>   This method is optional.  It is called to discard part of the payload data upon a key being revoked.  The caller will have the key semaphore write-locked.
>
>   It is safe to sleep in this method, though care should be taken to avoid a deadlock against the key semaphore.
>
> - `void (*destroy)(struct key *key);`
>
>   This method is optional. It is called to discard the payload data on a key when it is being destroyed.
>
>   This method does not need to lock the key to access the payload; it can consider the key as being inaccessible at this time. Note that the key's type may have been changed before this function is called.
>
>   It is not safe to sleep in this method; the caller may hold spinlocks.
>
> - `void (*describe)(const struct key *key, struct seq_file *p);`
>
>   This method is optional. It is called during /proc/keys reading to summarise a key's description and payload in text form.
>
>   This method will be called with the RCU read lock held. rcu_dereference() should be used to read the payload pointer if the payload is to be accessed. key-&gt;datalen cannot be trusted to stay consistent with the contents of the payload.
>
>   The description will not change, though the key's state may.
>
>   It is not safe to sleep in this method; the RCU read lock is held by the caller.
>
> - `long (*read)(const struct key *key, char __user *buffer, size_t buflen);`
>
>   This method is optional. It is called by KEYCTL_READ to translate the key's payload into something a blob of data for userspace to deal with. Ideally, the blob should be in the same format as that passed in to the instantiate and update methods.
>
>   If successful, the blob size that could be produced should be returned rather than the size copied.
>
>   This method will be called with the key's semaphore read-locked. This will prevent the key's payload changing. It is not necessary to use RCU locking when accessing the key's payload. It is safe to sleep in this method, such as might happen when the userspace buffer is accessed.
>
> - `int (*request_key)(struct key_construction *cons, const char *op, void *aux);`
>
>   This method is optional.  If provided, request_key() and friends will invoke this function rather than upcalling to /sbin/request-key to operate upon a key of this type.
>
>   The aux parameter is as passed to request_key_async_with_auxdata() and similar or is NULL otherwise.  Also passed are the construction record for the key to be operated upon and the operation type (currently only "create").
>
>   This method is permitted to return before the upcall is complete, but the following function must be called under all circumstances to complete the instantiation process, whether or not it succeeds, whether or not there's an error:
>
>
>
>   ```text
>   void complete_request_key(struct key_construction *cons, int error);
>   ```
>
>   The error parameter should be 0 on success, -ve on error.  The construction record is destroyed by this action and the authorisation key will be revoked.  If an error is indicated, the key under construction will be negatively instantiated if it wasn't already instantiated.
>
>   If this method returns an error, that error will be returned to the caller of request_key\*().  complete_request_key() must be called prior to returning.
>
>   The key under construction and the authorisation key can be found in the key_construction struct pointed to by cons:
>
>   > - `struct key *key;`
>   >
>   >   The key under construction.
>   >
>   > - `struct key *authkey;`
>   >
>   >   The authorisation key.
>
> - `struct key_restriction *(*lookup_restriction)(const char *params);`
>
>   This optional method is used to enable userspace configuration of keyring restrictions. The restriction parameter string (not including the key type name) is passed in, and this method returns a pointer to a key_restriction structure containing the relevant functions and data to evaluate each attempted key link operation. If there is no match, -EINVAL is returned.
>
> - `asym_eds_op` and `asym_verify_signature`:
>
>
>
>   ```text
>   int (*asym_eds_op)(struct kernel_pkey_params *params,
>                      const void *in, void *out);
>   int (*asym_verify_signature)(struct kernel_pkey_params *params,
>                                const void *in, const void *in2);
>   ```
>
>   These methods are optional.  If provided the first allows a key to be used to encrypt, decrypt or sign a blob of data, and the second allows a key to verify a signature.
>
>   In all cases, the following information is provided in the params block:
>
>
>
>   ```text
>   struct kernel_pkey_params {
>           struct key      *key;
>           const char      *encoding;
>           const char      *hash_algo;
>           char            *info;
>           __u32           in_len;
>           union {
>                   __u32   out_len;
>                   __u32   in2_len;
>           };
>           enum kernel_pkey_operation op : 8;
>   };
>   ```
>
>   This includes the key to be used; a string indicating the encoding to use (for instance, "pkcs1" may be used with an RSA key to indicate RSASSA-PKCS1-v1.5 or RSAES-PKCS1-v1.5 encoding or "raw" if no encoding); the name of the hash algorithm used to generate the data for a signature (if appropriate); the sizes of the input and output (or second input) buffers; and the ID of the operation to be performed.
>
>   For a given operation ID, the input and output buffers are used as follows:
>
>
>
>   ```text
>   Operation ID            in,in_len       out,out_len     in2,in2_len
>   ======================= =============== =============== ===============
>   kernel_pkey_encrypt     Raw data        Encrypted data  -
>   kernel_pkey_decrypt     Encrypted data  Raw data        -
>   kernel_pkey_sign        Raw data        Signature       -
>   kernel_pkey_verify      Raw data        -               Signature
>   ```
>
>   asym_eds_op() deals with encryption, decryption and signature creation as specified by params-&gt;op.  Note that params-&gt;op is also set for asym_verify_signature().
>
>   Encrypting and signature creation both take raw data in the input buffer and return the encrypted result in the output buffer.  Padding may have been added if an encoding was set.  In the case of signature creation, depending on the encoding, the padding created may need to indicate the digest algorithm - the name of which should be supplied in hash_algo.
>
>   Decryption takes encrypted data in the input buffer and returns the raw data in the output buffer.  Padding will get checked and stripped off if an encoding was set.
>
>   Verification takes raw data in the input buffer and the signature in the second input buffer and checks that the one matches the other.  Padding will be validated.  Depending on the encoding, the digest algorithm used to generate the raw data may need to be indicated in hash_algo.
>
>   If successful, asym_eds_op() should return the number of bytes written into the output buffer.  asym_verify_signature() should return 0.
>
>   A variety of errors may be returned, including EOPNOTSUPP if the operation is not supported; EKEYREJECTED if verification fails; ENOPKG if the required crypto isn't available.
>
> - `asym_query`:
>
>
>
>   ```text
>   int (*asym_query)(const struct kernel_pkey_params *params,
>                     struct kernel_pkey_query *info);
>   ```
>
>   This method is optional.  If provided it allows information about the public or asymmetric key held in the key to be determined.
>
>   The parameter block is as for asym_eds_op() and co. but in_len and out_len are unused.  The encoding and hash_algo fields should be used to reduce the returned buffer/data sizes as appropriate.
>
>   If successful, the following information is filled in:
>
>
>
>   ```text
>   struct kernel_pkey_query {
>           __u32           supported_ops;
>           __u32           key_size;
>           __u16           max_data_size;
>           __u16           max_sig_size;
>           __u16           max_enc_size;
>           __u16           max_dec_size;
>   };
>   ```
>
>   The supported_ops field will contain a bitmask indicating what operations are supported by the key, including encryption of a blob, decryption of a blob, signing a blob and verifying the signature on a blob.  The following constants are defined for this:
>
>
>
>   ```text
>   KEYCTL_SUPPORTS_{ENCRYPT,DECRYPT,SIGN,VERIFY}
>   ```
>
>   The key_size field is the size of the key in bits.  max_data_size and max_sig_size are the maximum raw data and signature sizes for creation and verification of a signature; max_enc_size and max_dec_size are the maximum raw data and signature sizes for encryption and decryption.  The max\_\*\_size fields are measured in bytes.
>
>   If successful, 0 will be returned.  If the key doesn't support this, EOPNOTSUPP will be returned.

<a id="rst-request-key-callback-service"></a>

## Request-Key Callback Service

To create a new key, the kernel will attempt to execute the following command line:



```text
/sbin/request-key create <key> <uid> <gid> \
        <threadring> <processring> <sessionring> <callout_info>
```

&lt;key&gt; is the key being constructed, and the three keyrings are the process keyrings from the process that caused the search to be issued. These are included for two reasons:

> - **1  There may be an authentication token in one of the keyrings that is**
>
>   required to obtain the key, eg: a Kerberos Ticket-Granting Ticket.
>
> 2  The new key should probably be cached in one of these rings.

This program should set it UID and GID to those specified before attempting to access any more keys. It may then look around for a user specific process to hand the request off to (perhaps a path held in placed in another key by, for example, the KDE desktop manager).

The program (or whatever it calls) should finish construction of the key by calling KEYCTL_INSTANTIATE or KEYCTL_INSTANTIATE_IOV, which also permits it to cache the key in one of the keyrings (probably the session ring) before returning.  Alternatively, the key can be marked as negative with KEYCTL_NEGATE or KEYCTL_REJECT; this also permits the key to be cached in one of the keyrings.

If it returns with the key remaining in the unconstructed state, the key will be marked as being negative, it will be added to the session keyring, and an error will be returned to the key requestor.

Supplementary information may be provided from whoever or whatever invoked this service. This will be passed as the &lt;callout_info&gt; parameter. If no such information was made available, then "-" will be passed as this parameter instead.

Similarly, the kernel may attempt to update an expired or a soon to expire key by executing:



```text
/sbin/request-key update <key> <uid> <gid> \
        <threadring> <processring> <sessionring>
```

In this case, the program isn't required to actually attach the key to a ring; the rings are provided for reference.

<a id="rst-garbage-collection"></a>

## Garbage Collection

Dead keys (for which the type has been removed) will be automatically unlinked from those keyrings that point to them and deleted as soon as possible by a background garbage collector.

Similarly, revoked and expired keys will be garbage collected, but only after a certain amount of time has passed.  This time is set as a number of seconds in:



```text
/proc/sys/kernel/keys/gc_delay
```

---

# Encrypted keys for the eCryptfs filesystem

_Peios Kernel / Internals / Security / keys_

> ECryptfs is a stacked filesystem which transparently encrypts and decrypts each file using a randomly generated File Encryption Key (FEK).

<a id="rst-encrypted-keys-for-the-ecryptfs-filesystem"></a>

ECryptfs is a stacked filesystem which transparently encrypts and decrypts each file using a randomly generated File Encryption Key (FEK).

Each FEK is in turn encrypted with a File Encryption Key Encryption Key (FEKEK) either in kernel space or in user space with a daemon called 'ecryptfsd'.  In the former case the operation is performed directly by the kernel CryptoAPI using a key, the FEKEK, derived from a user prompted passphrase;  in the latter the FEK is encrypted by 'ecryptfsd' with the help of external libraries in order to support other mechanisms like public key cryptography, PKCS\#11 and TPM based operations.

The data structure defined by eCryptfs to contain information required for the FEK decryption is called authentication token and, currently, can be stored in a kernel key of the 'user' type, inserted in the user's session specific keyring by the userspace utility 'mount.ecryptfs' shipped with the package 'ecryptfs-utils'.

The 'encrypted' key type has been extended with the introduction of the new format 'ecryptfs' in order to be used in conjunction with the eCryptfs filesystem.  Encrypted keys of the newly introduced format store an authentication token in its payload with a FEKEK randomly generated by the kernel and protected by the parent master key.

In order to avoid known-plaintext attacks, the datablob obtained through commands 'keyctl print' or 'keyctl pipe' does not contain the overall authentication token, which content is well known, but only the FEKEK in encrypted form.

The eCryptfs filesystem may really benefit from using encrypted keys in that the required key can be securely generated by an Administrator and provided at boot time after the unsealing of a 'trusted' key in order to perform the mount in a controlled environment.  Another advantage is that the key is not exposed to threats of malicious software, because it is available in clear form only at kernel level.

Usage:



```text
keyctl add encrypted name "new ecryptfs key-type:master-key-name keylen" ring
keyctl add encrypted name "load hex_blob" ring
keyctl update keyid "update key-type:master-key-name"
```

Where:



```text
name:= '<16 hexadecimal characters>'
key-type:= 'trusted' | 'user'
keylen:= 64
```

Example of encrypted key usage with the eCryptfs filesystem:

Create an encrypted key "1000100010001000" of length 64 bytes with format 'ecryptfs' and save it using a previously loaded user key "test":



```text
$ keyctl add encrypted 1000100010001000 "new ecryptfs user:test 64" @u
19184530

$ keyctl print 19184530
ecryptfs user:test 64 490045d4bfe48c99f0d465fbbbb79e7500da954178e2de0697
dd85091f5450a0511219e9f7cd70dcd498038181466f78ac8d4c19504fcc72402bfc41c2
f253a41b7507ccaa4b2b03fff19a69d1cc0b16e71746473f023a95488b6edfd86f7fdd40
9d292e4bacded1258880122dd553a661

$ keyctl pipe 19184530 > ecryptfs.blob
```

Mount an eCryptfs filesystem using the created encrypted key "1000100010001000" into the '/secret' directory:



```text
$ mount -i -t ecryptfs -oecryptfs_sig=1000100010001000,\
  ecryptfs_cipher=aes,ecryptfs_key_bytes=32 /secret /secret
```

---

# Key Request Service

_Peios Kernel / Internals / Security / keys_

> The key request service is part of the key retention service (refer to Documentation/security/keys/core.rst). This document explains more fully how the requesting algorithm works.

<a id="rst-key-request-service"></a>

The key request service is part of the key retention service (refer to [Documentation/security/keys/core.rst](/kernel/internals/security/keys/core.md)).  This document explains more fully how the requesting algorithm works.

The process starts by either the kernel requesting a service by calling `request_key*()`:



```text
struct key *request_key(const struct key_type *type,
                        const char *description,
                        const char *callout_info);
```

or:



```text
struct key *request_key_tag(const struct key_type *type,
                            const char *description,
                            const struct key_tag *domain_tag,
                            const char *callout_info);
```

or:



```text
struct key *request_key_with_auxdata(const struct key_type *type,
                                     const char *description,
                                     const struct key_tag *domain_tag,
                                     const char *callout_info,
                                     size_t callout_len,
                                     void *aux);
```

or:



```text
struct key *request_key_rcu(const struct key_type *type,
                            const char *description,
                            const struct key_tag *domain_tag);
```

Or by userspace invoking the request_key system call:



```text
key_serial_t request_key(const char *type,
                         const char *description,
                         const char *callout_info,
                         key_serial_t dest_keyring);
```

The main difference between the access points is that the in-kernel interface does not need to link the key to a keyring to prevent it from being immediately destroyed.  The kernel interface returns a pointer directly to the key, and it's up to the caller to destroy the key.

The request_key_tag() call is like the in-kernel request_key(), except that it also takes a domain tag that allows keys to be separated by namespace and killed off as a group.

The request_key_with_auxdata() calls is like the request_key_tag() call, except that they permit auxiliary data to be passed to the upcaller (the default is NULL).  This is only useful for those key types that define their own upcall mechanism rather than using /sbin/request-key.

The request_key_rcu() call is like the request_key_tag() call, except that it doesn't check for keys that are under construction and doesn't attempt to construct missing keys.

The userspace interface links the key to a keyring associated with the process to prevent the key from going away, and returns the serial number of the key to the caller.

The following example assumes that the key types involved don't define their own upcall mechanisms.  If they do, then those should be substituted for the forking and execution of /sbin/request-key.

<a id="rst-the-process"></a>

## The Process

A request proceeds in the following manner:

> 1. Process A calls request_key() \[the userspace syscall calls the kernel interface\].
>
> 2. request_key() searches the process's subscribed keyrings to see if there's a suitable key there.  If there is, it returns the key.  If there isn't, and callout_info is not set, an error is returned.  Otherwise the process proceeds to the next step.
>
> 3. request_key() sees that A doesn't have the desired key yet, so it creates two things:
>
>    > - **a)** An uninstantiated key U of requested type and description.
>    >
>    > - **b)** An authorisation key V that refers to key U and notes that process A is the context in which key U should be instantiated and secured, and from which associated key requests may be satisfied.
>
> 4. request_key() then forks and executes /sbin/request-key with a new session keyring that contains a link to auth key V.
>
> 5. /sbin/request-key assumes the authority associated with key U.
>
> 6. /sbin/request-key execs an appropriate program to perform the actual instantiation.
>
> 7. The program may want to access another key from A's context (say a Kerberos TGT key).  It just requests the appropriate key, and the keyring search notes that the session keyring has auth key V in its bottom level.
>
>    This will permit it to then search the keyrings of process A with the UID, GID, groups and security info of process A as if it was process A, and come up with key W.
>
> 8. The program then does what it must to get the data with which to instantiate key U, using key W as a reference (perhaps it contacts a Kerberos server using the TGT) and then instantiates key U.
>
> 9. Upon instantiating key U, auth key V is automatically revoked so that it may not be used again.
>
> 10. The program then exits 0 and request_key() deletes key V and returns key U to the caller.

This also extends further.  If key W (step 7 above) didn't exist, key W would be created uninstantiated, another auth key (X) would be created (as per step 3) and another copy of /sbin/request-key spawned (as per step 4); but the context specified by auth key X will still be process A, as it was in auth key V.

This is because process A's keyrings can't simply be attached to /sbin/request-key at the appropriate places because (a) execve will discard two of them, and (b) it requires the same UID/GID/Groups all the way through.

<a id="rst-negative-instantiation-and-rejection"></a>

## Negative Instantiation And Rejection

Rather than instantiating a key, it is possible for the possessor of an authorisation key to negatively instantiate a key that's under construction. This is a short duration placeholder that causes any attempt at re-requesting the key while it exists to fail with error ENOKEY if negated or the specified error if rejected.

This is provided to prevent excessive repeated spawning of /sbin/request-key processes for a key that will never be obtainable.

Should the /sbin/request-key process exit anything other than 0 or die on a signal, the key under construction will be automatically negatively instantiated for a short amount of time.

<a id="rst-the-search-algorithm"></a>

## The Search Algorithm

A search of any particular keyring proceeds in the following fashion:

> 1. When the key management code searches for a key (keyring_search_rcu) it firstly calls key_permission(SEARCH) on the keyring it's starting with, if this denies permission, it doesn't search further.
>
> 2. It considers all the non-keyring keys within that keyring and, if any key matches the criteria specified, calls key_permission(SEARCH) on it to see if the key is allowed to be found.  If it is, that key is returned; if not, the search continues, and the error code is retained if of higher priority than the one currently set.
>
> 3. It then considers all the keyring-type keys in the keyring it's currently searching.  It calls key_permission(SEARCH) on each keyring, and if this grants permission, it recurses, executing steps (2) and (3) on that keyring.

The process stops immediately a valid key is found with permission granted to use it.  Any error from a previous match attempt is discarded and the key is returned.

When request_key() is invoked, if CONFIG_KEYS_REQUEST_CACHE=y, a per-task one-key cache is first checked for a match.

When search_process_keyrings() is invoked, it performs the following searches until one succeeds:

> 1. If extant, the process's thread keyring is searched.
>
> 2. If extant, the process's process keyring is searched.
>
> 3. The process's session keyring is searched.
>
> 4. If the process has assumed the authority associated with a request_key() authorisation key then:
>
>    > - **a)** If extant, the calling process's thread keyring is searched.
>    >
>    > - **b)** If extant, the calling process's process keyring is searched.
>    >
>    > - **c)** The calling process's session keyring is searched.

The moment one succeeds, all pending errors are discarded and the found key is returned.  If CONFIG_KEYS_REQUEST_CACHE=y, then that key is placed in the per-task cache, displacing the previous key.  The cache is cleared on exit or just prior to resumption of userspace.

Only if all these fail does the whole thing fail with the highest priority error.  Note that several errors may have come from LSM.

The error priority is:



```text
EKEYREVOKED > EKEYEXPIRED > ENOKEY
```

EACCES/EPERM are only returned on a direct search of a specific keyring where the basal keyring does not grant Search permission.

---

# Trusted and Encrypted Keys

_Peios Kernel / Internals / Security / keys_

> Trusted and Encrypted Keys are two new key types added to the existing kernel key ring service. Both of these new types are variable length symmetric keys, and in both cases all keys are created in the kernel, and user space sees, stores,…

<a id="rst-trusted-and-encrypted-keys"></a>

Trusted and Encrypted Keys are two new key types added to the existing kernel key ring service.  Both of these new types are variable length symmetric keys, and in both cases all keys are created in the kernel, and user space sees, stores, and loads only encrypted blobs.  Trusted Keys require the availability of a Trust Source for greater security, while Encrypted Keys can be used on any system. All user level blobs, are displayed and loaded in hex ASCII for convenience, and are integrity verified.

<a id="rst-trusted-keys-as-protected-key"></a>

## Trusted Keys as Protected key

It is the secure way of keeping the keys in the kernel key-ring as Trusted-Key, such that:

- Key-blob, an encrypted key-data, created to be stored, loaded and seen by userspace.

- Key-data, the plain-key text in the system memory, to be used by kernel space only.

Though key-data is not accessible to the user-space in plain-text, but it is in plain-text in system memory, when used in kernel space. Even though kernel-space attracts small surface attack, but with compromised kernel or side-channel attack accessing the system memory can lead to a chance of the key getting compromised/leaked.

In order to protect the key in kernel space, the concept of "protected-keys" is introduced which will act as an added layer of protection. The key-data of the protected keys is encrypted with Key-Encryption-Key(KEK), and decrypted inside the trust source boundary. The plain-key text never available out-side in the system memory. Thus, any crypto operation that is to be executed using the protected key, can only be done by the trust source, which generated the key blob.

Hence, if the protected-key is leaked or compromised, it is of no use to the hacker.

Trusted keys as protected keys, with trust source having the capability of generating:

- Key-Blob, to be loaded, stored and seen by user-space.

<a id="rst-trust-source"></a>

## Trust Source

A trust source provides the source of security for Trusted Keys.  This section lists currently supported trust sources, along with their security considerations.  Whether or not a trust source is sufficiently safe depends on the strength and correctness of its implementation, as well as the threat environment for a specific use case.  Since the kernel doesn't know what the environment is, and there is no metric of trust, it is dependent on the consumer of the Trusted Keys to determine if the trust source is sufficiently safe.

> - Root of trust for storage
>
>   1. TPM (Trusted Platform Module: hardware device)
>
>      Rooted to Storage Root Key (SRK) which never leaves the TPM that provides crypto operation to establish root of trust for storage.
>
>   2. TEE (Trusted Execution Environment: OP-TEE based on Arm TrustZone)
>
>      Rooted to Hardware Unique Key (HUK) which is generally burnt in on-chip fuses and is accessible to TEE only.
>
>   3. CAAM (Cryptographic Acceleration and Assurance Module: IP on NXP SoCs)
>
>      When High Assurance Boot (HAB) is enabled and the CAAM is in secure mode, trust is rooted to the OTPMK, a never-disclosed 256-bit key randomly generated and fused into each SoC at manufacturing time. Otherwise, a common fixed test key is used instead.
>
>   4. DCP (Data Co-Processor: crypto accelerator of various i.MX SoCs)
>
>      Rooted to a one-time programmable key (OTP) that is generally burnt in the on-chip fuses and is accessible to the DCP encryption engine only. DCP provides two keys that can be used as root of trust: the OTP key and the UNIQUE key. Default is to use the UNIQUE key, but selecting the OTP key can be done via a module parameter (dcp_use_otp_key).
>
>   5. PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
>
>      Rooted to a unique, per-LPAR key, which is derived from a system-wide, randomly generated LPAR root key. Both the per-LPAR keys and the LPAR root key are stored in hypervisor-owned secure memory at runtime, and the LPAR root key is additionally persisted in secure locations such as the processor SEEPROMs and encrypted NVRAM.
>
> - Execution isolation
>
>   1. TPM
>
>      Fixed set of operations running in isolated execution environment.
>
>   2. TEE
>
>      Customizable set of operations running in isolated execution environment verified via Secure/Trusted boot process.
>
>   3. CAAM
>
>      Fixed set of operations running in isolated execution environment.
>
>   4. DCP
>
>      Fixed set of cryptographic operations running in isolated execution environment. Only basic blob key encryption is executed there. The actual key sealing/unsealing is done on main processor/kernel space.
>
>   5. PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
>
>      Fixed set of cryptographic operations done on on-chip hardware cryptographic acceleration unit NX. Keys for wrapping and unwrapping are managed by PowerVM Platform KeyStore, which stores keys in an isolated in-memory copy in secure hypervisor memory, as well as in a persistent copy in hypervisor-encrypted NVRAM.
>
> - Optional binding to platform integrity state
>
>   > 1. TPM
>   >
>   >    Keys can be optionally sealed to specified PCR (integrity measurement) values, and only unsealed by the TPM, if PCRs and blob integrity verifications match. A loaded Trusted Key can be updated with new (future) PCR values, so keys are easily migrated to new PCR values, such as when the kernel and initramfs are updated. The same key can have many saved blobs under different PCR values, so multiple boots are easily supported.
>   >
>   > 2. TEE
>   >
>   >    Relies on Secure/Trusted boot process for platform integrity. It can be extended with TEE based measured boot process.
>   >
>   > 3. CAAM
>   >
>   >    Relies on the High Assurance Boot (HAB) mechanism of NXP SoCs for platform integrity.
>   >
>   > 4. DCP
>   >
>   >    Relies on Secure/Trusted boot process (called HAB by vendor) for platform integrity.
>   >
>   > 5. PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
>   >
>   >    Relies on secure and trusted boot process of IBM Power systems for platform integrity.
>
> - Interfaces and APIs
>
>   1. TPM
>
>      TPMs have well-documented, standardized interfaces and APIs.
>
>   2. TEE
>
>      TEEs have well-documented, standardized client interface and APIs. For more details refer to `Documentation/driver-api/tee.rst`.
>
>   3. CAAM
>
>      Interface is specific to silicon vendor.
>
>   4. DCP
>
>      Vendor-specific API that is implemented as part of the DCP crypto driver in `drivers/crypto/mxs-dcp.c`.
>
>   5. PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
>
>      Platform Keystore has well documented interfaces in PAPR document. Refer to `Documentation/arch/powerpc/papr_hcalls.rst`
>
> - Threat model
>
>   The strength and appropriateness of a particular trust source for a given purpose must be assessed when using them to protect security-relevant data.

<a id="rst-key-generation"></a>

## Key Generation

<a id="rst-trusted-keys"></a>

### Trusted Keys

New keys are created from random numbers. They are encrypted/decrypted using a child key in the storage key hierarchy. Encryption and decryption of the child key must be protected by a strong access control policy within the trust source. The random number generator in use differs according to the selected trust source:

> - TPM: hardware device based RNG
>
>   Keys are generated within the TPM. Strength of random numbers may vary from one device manufacturer to another.
>
> - TEE: OP-TEE based on Arm TrustZone based RNG
>
>   RNG is customizable as per platform needs. It can either be direct output from platform specific hardware RNG or a software based Fortuna CSPRNG which can be seeded via multiple entropy sources.
>
> - CAAM: Kernel RNG
>
>   The normal kernel random number generator is used. To seed it from the CAAM HWRNG, enable CRYPTO_DEV_FSL_CAAM_RNG_API and ensure the device is probed.
>
> - DCP (Data Co-Processor: crypto accelerator of various i.MX SoCs)
>
>   The DCP hardware device itself does not provide a dedicated RNG interface, so the kernel default RNG is used. SoCs with DCP like the i.MX6ULL do have a dedicated hardware RNG that is independent from DCP which can be enabled to back the kernel RNG.
>
> > - PKWM (PowerVM Key Wrapping Module: IBM PowerVM + Platform KeyStore)
> >
> >   The normal kernel random number generator is used to generate keys.

Users may override this by specifying `trusted.rng=kernel` on the kernel command-line to override the used RNG with the kernel's random number pool.

<a id="rst-encrypted-keys"></a>

### Encrypted Keys

Encrypted keys do not depend on a trust source, and are faster, as they use AES for encryption/decryption. New keys are created either from kernel-generated random numbers or user-provided decrypted data, and are encrypted/decrypted using a specified ‘master’ key. The ‘master’ key can either be a trusted-key or user-key type. The main disadvantage of encrypted keys is that if they are not rooted in a trusted key, they are only as secure as the user key encrypting them. The master user key should therefore be loaded in as secure a way as possible, preferably early in boot.

<a id="rst-usage"></a>

## Usage

<a id="rst-trusted-keys-usage-tpm"></a>

### Trusted Keys usage: TPM

TPM 1.2: By default, trusted keys are sealed under the SRK, which has the default authorization value (20 bytes of 0s).  This can be set at takeownership time with the TrouSerS utility: "tpm_takeownership -u -z".

TPM 2.0: The user must first create a storage key and make it persistent, so the key is available after reboot. This can be done using the following commands.

With the IBM TSS 2 stack:



```text
#> tsscreateprimary -hi o -st
Handle 80000000
#> tssevictcontrol -hi o -ho 80000000 -hp 81000001
```

Or with the Intel TSS 2 stack:



```text
#> tpm2_createprimary --hierarchy o -G rsa2048 -c key.ctxt
[...]
#> tpm2_evictcontrol -c key.ctxt 0x81000001
persistentHandle: 0x81000001
```

Usage:



```text
keyctl add trusted name "new keylen [options]" ring
keyctl add trusted name "load hex_blob [pcrlock=pcrnum]" ring
keyctl update key "update [options]"
keyctl print keyid

options:
   keyhandle=    ascii hex value of sealing key
                   TPM 1.2: default 0x40000000 (SRK)
                   TPM 2.0: no default; must be passed every time
   keyauth=      ascii hex auth for sealing key default 0x00...i
                 (40 ascii zeros)
   blobauth=     ascii hex auth for sealed data default 0x00...
                 (40 ascii zeros)
   pcrinfo=      ascii hex of PCR_INFO or PCR_INFO_LONG (no default)
   pcrlock=      pcr number to be extended to "lock" blob
   migratable=   0|1 indicating permission to reseal to new PCR values,
                 default 1 (resealing allowed)
   hash=         hash algorithm name as a string. For TPM 1.x the only
                 allowed value is sha1. For TPM 2.x the allowed values
                 are sha1, sha256, sha384, sha512 and sm3-256.
   policydigest= digest for the authorization policy. must be calculated
                 with the same hash algorithm as specified by the 'hash='
                 option.
   policyhandle= handle to an authorization policy session that defines the
                 same policy and with the same hash algorithm as was used to
                 seal the key.
```

"keyctl print" returns an ascii hex copy of the sealed key, which is in standard TPM_STORED_DATA format.  The key length for new keys are always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits), the upper limit is to fit within the 2048 bit SRK (RSA) keylength, with all necessary structure/padding.

<a id="rst-trusted-keys-usage-tee"></a>

### Trusted Keys usage: TEE

Usage:



```text
keyctl add trusted name "new keylen" ring
keyctl add trusted name "load hex_blob" ring
keyctl print keyid
```

"keyctl print" returns an ASCII hex copy of the sealed key, which is in format specific to TEE device implementation.  The key length for new keys is always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

<a id="rst-trusted-keys-usage-caam"></a>

### Trusted Keys usage: CAAM

Trusted Keys Usage:



```text
keyctl add trusted name "new keylen" ring
keyctl add trusted name "load hex_blob" ring
keyctl print keyid
```

"keyctl print" returns an ASCII hex copy of the sealed key, which is in a CAAM-specific format.  The key length for new keys is always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

Trusted Keys as Protected Keys Usage:



```text
keyctl add trusted name "new keylen pk [options]" ring
keyctl add trusted name "load hex_blob [options]" ring
keyctl print keyid

where, 'pk' is used to direct trust source to generate protected key.

options:
   key_enc_algo =      For CAAM, supported enc algo are ECB(2), CCM(1).
```

"keyctl print" returns an ASCII hex copy of the sealed key, which is in a CAAM-specific format.  The key length for new keys is always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

<a id="rst-trusted-keys-usage-dcp"></a>

### Trusted Keys usage: DCP

Usage:



```text
keyctl add trusted name "new keylen" ring
keyctl add trusted name "load hex_blob" ring
keyctl print keyid
```

"keyctl print" returns an ASCII hex copy of the sealed key, which is in format specific to this DCP key-blob implementation.  The key length for new keys is always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

<a id="rst-trusted-keys-usage-pkwm"></a>

### Trusted Keys usage: PKWM

Usage:



```text
keyctl add trusted name "new keylen [options]" ring
keyctl add trusted name "load hex_blob" ring
keyctl print keyid

options:
   wrap_flags=   ascii hex value of security policy requirement
                   0x00: no secure boot requirement (default)
                   0x01: require secure boot to be in either audit or
                         enforced mode
                   0x02: require secure boot to be in enforced mode
```

"keyctl print" returns an ASCII hex copy of the sealed key, which is in format specific to PKWM key-blob implementation.  The key length for new keys is always in bytes. Trusted Keys can be 32 - 128 bytes (256 - 1024 bits).

<a id="rst-encrypted-keys-usage"></a>

### Encrypted Keys usage

The decrypted portion of encrypted keys can contain either a simple symmetric key or a more complex structure. The format of the more complex structure is application specific, which is identified by 'format'.

Usage:



```text
keyctl add encrypted name "new [format] key-type:master-key-name keylen"
    ring
keyctl add encrypted name "new [format] key-type:master-key-name keylen
    decrypted-data" ring
keyctl add encrypted name "load hex_blob" ring
keyctl update keyid "update key-type:master-key-name"
```

Where:



```text
format:= 'default | ecryptfs | enc32'
key-type:= 'trusted' | 'user'
```

<a id="rst-examples-of-trusted-and-encrypted-key-usage"></a>

### Examples of trusted and encrypted key usage

Create and save a trusted key named "kmk" of length 32 bytes.

Note: When using a TPM 2.0 with a persistent key with handle 0x81000001, append 'keyhandle=0x81000001' to statements between quotes, such as "new 32 keyhandle=0x81000001".



```text
$ keyctl add trusted kmk "new 32" @u
440502848

$ keyctl show
Session Keyring
       -3 --alswrv    500   500  keyring: _ses
 97833714 --alswrv    500    -1   \_ keyring: _uid.500
440502848 --alswrv    500   500       \_ trusted: kmk

$ keyctl print 440502848
0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915
3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b
27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722
a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec
d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d
dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0
f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b
e4a8aea2b607ec96931e6f4d4fe563ba

$ keyctl pipe 440502848 > kmk.blob
```

Load a trusted key from the saved blob:



```text
$ keyctl add trusted kmk "load `cat kmk.blob`" @u
268728824

$ keyctl print 268728824
0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915
3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b
27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722
a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec
d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d
dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0
f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b
e4a8aea2b607ec96931e6f4d4fe563ba
```

Create and save a trusted key as protected key named "kmk" of length 32 bytes.



```text
$ keyctl add trusted kmk "new 32 pk key_enc_algo=1" @u
440502848

$ keyctl show
Session Keyring
       -3 --alswrv    500   500  keyring: _ses
 97833714 --alswrv    500    -1   \_ keyring: _uid.500
440502848 --alswrv    500   500       \_ trusted: kmk

$ keyctl print 440502848
0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915
3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b
27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722
a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec
d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d
dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0
f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b
e4a8aea2b607ec96931e6f4d4fe563ba

$ keyctl pipe 440502848 > kmk.blob
```

Load a trusted key from the saved blob:



```text
$ keyctl add trusted kmk "load `cat kmk.blob` key_enc_algo=1" @u
268728824

$ keyctl print 268728824
0101000000000000000001005d01b7e3f4a6be5709930f3b70a743cbb42e0cc95e18e915
3f60da455bbf1144ad12e4f92b452f966929f6105fd29ca28e4d4d5a031d068478bacb0b
27351119f822911b0a11ba3d3498ba6a32e50dac7f32894dd890eb9ad578e4e292c83722
a52e56a097e6a68b3f56f7a52ece0cdccba1eb62cad7d817f6dc58898b3ac15f36026fec
d568bd4a706cb60bb37be6d8f1240661199d640b66fb0fe3b079f97f450b9ef9c22c6d5d
dd379f0facd1cd020281dfa3c70ba21a3fa6fc2471dc6d13ecf8298b946f65345faa5ef0
f1f8fff03ad0acb083725535636addb08d73dedb9832da198081e5deae84bfaf0409c22b
e4a8aea2b607ec96931e6f4d4fe563ba
```

Reseal (TPM specific) a trusted key under new PCR values:



```text
$ keyctl update 268728824 "update pcrinfo=`cat pcr.blob`"
$ keyctl print 268728824
010100000000002c0002800093c35a09b70fff26e7a98ae786c641e678ec6ffb6b46d805
77c8a6377aed9d3219c6dfec4b23ffe3000001005d37d472ac8a44023fbb3d18583a4f73
d3a076c0858f6f1dcaa39ea0f119911ff03f5406df4f7f27f41da8d7194f45c9f4e00f2e
df449f266253aa3f52e55c53de147773e00f0f9aca86c64d94c95382265968c354c5eab4
9638c5ae99c89de1e0997242edfb0b501744e11ff9762dfd951cffd93227cc513384e7e6
e782c29435c7ec2edafaa2f4c1fe6e7a781b59549ff5296371b42133777dcc5b8b971610
94bc67ede19e43ddb9dc2baacad374a36feaf0314d700af0a65c164b7082401740e489c9
7ef6a24defe4846104209bf0c3eced7fa1a672ed5b125fc9d8cd88b476a658a4434644ef
df8ae9a178e9f83ba9f08d10fa47e4226b98b0702f06b3b8
```

The initial consumer of trusted keys is EVM, which at boot time needs a high quality symmetric key for HMAC protection of file metadata. The use of a trusted key provides strong guarantees that the EVM key has not been compromised by a user level problem, and when sealed to a platform integrity state, protects against boot and offline attacks. Create and save an encrypted key "evm" using the above trusted key "kmk":

option 1: omitting 'format':



```text
$ keyctl add encrypted evm "new trusted:kmk 32" @u
159771175
```

option 2: explicitly defining 'format' as 'default':



```text
$ keyctl add encrypted evm "new default trusted:kmk 32" @u
159771175

$ keyctl print 159771175
default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3
82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0
24717c64 5972dcb82ab2dde83376d82b2e3c09ffc

$ keyctl pipe 159771175 > evm.blob
```

Load an encrypted key "evm" from saved blob:



```text
$ keyctl add encrypted evm "load `cat evm.blob`" @u
831684262

$ keyctl print 831684262
default trusted:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b3
82dbbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0
24717c64 5972dcb82ab2dde83376d82b2e3c09ffc
```

Instantiate an encrypted key "evm" using user-provided decrypted data:



```text
$ evmkey=$(dd if=/dev/urandom bs=1 count=32 | xxd -c32 -p)
$ keyctl add encrypted evm "new default user:kmk 32 $evmkey" @u
794890253

$ keyctl print 794890253
default user:kmk 32 2375725ad57798846a9bbd240de8906f006e66c03af53b1b382d
bbc55be2a44616e4959430436dc4f2a7a9659aa60bb4652aeb2120f149ed197c564e0247
17c64 5972dcb82ab2dde83376d82b2e3c09ffc
```

Other uses for trusted and encrypted keys, such as for disk and file encryption are anticipated.  In particular the new format 'ecryptfs' has been defined in order to use encrypted keys to mount an eCryptfs filesystem.  More details about the usage can be found in the file `Documentation/security/keys/ecryptfs.rst`.

Another new format 'enc32' has been defined in order to support encrypted keys with payload size of 32 bytes. This will initially be used for nvdimm security but may expand to other usages that require 32 bytes payload.

<a id="rst-tpm-2-0-asn-1-key-format"></a>

### TPM 2.0 ASN.1 Key Format

The TPM 2.0 ASN.1 key format is designed to be easily recognisable, even in binary form (fixing a problem we had with the TPM 1.2 ASN.1 format) and to be extensible for additions like importable keys and policy:



```text
TPMKey ::= SEQUENCE {
    type            OBJECT IDENTIFIER
    emptyAuth       [0] EXPLICIT BOOLEAN OPTIONAL
    parent          INTEGER
    pubkey          OCTET STRING
    privkey         OCTET STRING
}
```

type is what distinguishes the key even in binary form since the OID is provided by the TCG to be unique and thus forms a recognizable binary pattern at offset 3 in the key.  The OIDs currently made available are:



```text
2.23.133.10.1.3 TPM Loadable key.  This is an asymmetric key (Usually
                RSA2048 or Elliptic Curve) which can be imported by a
                TPM2_Load() operation.

2.23.133.10.1.4 TPM Importable Key.  This is an asymmetric key (Usually
                RSA2048 or Elliptic Curve) which can be imported by a
                TPM2_Import() operation.

2.23.133.10.1.5 TPM Sealed Data.  This is a set of data (up to 128
                bytes) which is sealed by the TPM.  It usually
                represents a symmetric key and must be unsealed before
                use.
```

The trusted key code only uses the TPM Sealed Data OID.

emptyAuth is true if the key has well known authorization "".  If it is false or not present, the key requires an explicit authorization phrase.  This is used by most user space consumers to decide whether to prompt for a password.

parent represents the parent key handle, either in the 0x81 MSO space, like 0x81000001 for the RSA primary storage key.  Userspace programmes also support specifying the primary handle in the 0x40 MSO space.  If this happens the Elliptic Curve variant of the primary key using the TCG defined template will be generated on the fly into a volatile object and used as the parent.  The current kernel code only supports the 0x81 MSO form.

pubkey is the binary representation of TPM2B_PRIVATE excluding the initial TPM2B header, which can be reconstructed from the ASN.1 octet string length.

privkey is the binary representation of TPM2B_PUBLIC excluding the initial TPM2B header which can be reconstructed from the ASN.1 octed string length.

<a id="rst-dcp-blob-format"></a>

### DCP Blob Format


The Data Co-Processor (DCP) provides hardware-bound AES keys using its
AES encryption engine only. It does not provide direct key sealing/unsealing.
To make DCP hardware encryption keys usable as trust source, we define
our own custom format that uses a hardware-bound key to secure the sealing
key stored in the key blob.

Whenever a new trusted key using DCP is generated, we generate a random 128-bit
blob encryption key (BEK) and 128-bit nonce. The BEK and nonce are used to
encrypt the trusted key payload using AES-128-GCM.

The BEK itself is encrypted using the hardware-bound key using the DCP's AES
encryption engine with AES-128-ECB. The encrypted BEK, generated nonce,
BEK-encrypted payload and authentication tag make up the blob format together
with a version number, payload length and authentication tag.



#### <a id="c-struct-dcp_blob_fmt"></a>`struct dcp_blob_fmt`

DCP BLOB format.

**Definition**

```c
struct dcp_blob_fmt {
    __u8 fmt_version;
    __u8 blob_key[AES_KEYSIZE_128];
    __u8 nonce[AES_KEYSIZE_128];
    __le32 payload_len;
    __u8 payload[];
};
```

**Members**

- `fmt_version`: Format version, currently being `1`.
- `blob_key`: Random AES 128 key which is used to encrypt **payload**,
  **blob_key** itself is encrypted with OTP or UNIQUE device key in
  AES-128-ECB mode by DCP.
- `nonce`: Random nonce used for **payload** encryption.
- `payload_len`: Length of the plain text **payload**.
- `payload`: The payload itself, encrypted using AES-128-GCM and **blob_key**,
  GCM auth tag of size DCP_BLOB_AUTHLEN is attached at the end of it.

**Description**

The total size of a DCP BLOB is sizeof(struct dcp_blob_fmt) + **payload_len** +
DCP_BLOB_AUTHLEN.

---

# Secrets documentation

_Peios Kernel / Internals / Security / secrets_

> Reference for Secrets documentation.

<a id="rst-secrets-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Confidential Computing secrets](</kernel/internals/security/secrets/coco.md>)

---

# Confidential Computing secrets

_Peios Kernel / Internals / Security / secrets_

> This document describes how Confidential Computing secret injection is handled from the firmware to the operating system, in the EFI driver and the efi_secret kernel module.

<a id="rst-confidential-computing-secrets"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document describes how Confidential Computing secret injection is handled from the firmware to the operating system, in the EFI driver and the efi_secret kernel module.

<a id="rst-introduction"></a>

## Introduction

Confidential Computing (coco) hardware such as AMD SEV (Secure Encrypted Virtualization) allows guest owners to inject secrets into the VMs memory without the host/hypervisor being able to read them.  In SEV, secret injection is performed early in the VM launch process, before the guest starts running.

The efi_secret kernel module allows userspace applications to access these secrets via securityfs.

<a id="rst-secret-data-flow"></a>

## Secret data flow

The guest firmware may reserve a designated memory area for secret injection, and publish its location (base GPA and length) in the EFI configuration table under a `LINUX_EFI_COCO_SECRET_AREA_GUID` entry (`adf956ad-e98c-484c-ae11-b51c7d336447`).  This memory area should be marked by the firmware as `EFI_RESERVED_TYPE`, and therefore the kernel should not be use it for its own purposes.

During the VM's launch, the virtual machine manager may inject a secret to that area.  In AMD SEV and SEV-ES this is performed using the `KVM_SEV_LAUNCH_SECRET` command (see <a id="rst-citation-reference-1"></a>[sev](#rst-sev)).  The structure of the injected Guest Owner secret data should be a GUIDed table of secret values; the binary format is described in `drivers/virt/coco/efi_secret/efi_secret.c` under "Structure of the EFI secret area".

On kernel start, the kernel's EFI driver saves the location of the secret area (taken from the EFI configuration table) in the `efi.coco_secret` field. Later it checks if the secret area is populated: it maps the area and checks whether its content begins with `EFI_SECRET_TABLE_HEADER_GUID` (`1e74f542-71dd-4d66-963e-ef4287ff173b`).  If the secret area is populated, the EFI driver will autoload the efi_secret kernel module, which exposes the secrets to userspace applications via securityfs.  The details of the efi_secret filesystem interface are in <a id="rst-citation-reference-2"></a>[secrets-coco-abi](#rst-secrets-coco-abi).

<a id="rst-application-usage-example"></a>

## Application usage example

Consider a guest performing computations on encrypted files.  The Guest Owner provides the decryption key (= secret) using the secret injection mechanism. The guest application reads the secret from the efi_secret filesystem and proceeds to decrypt the files into memory and then performs the needed computations on the content.

In this example, the host can't read the files from the disk image because they are encrypted.  Host can't read the decryption key because it is passed using the secret injection mechanism (= secure channel). Host can't read the decrypted content from memory because it's a confidential (memory-encrypted) guest.

Here is a simple example for usage of the efi_secret module in a guest to which an EFI secret area with 4 secrets was injected during launch:



```text
# ls -la /sys/kernel/security/secrets/coco
total 0
drwxr-xr-x 2 root root 0 Jun 28 11:54 .
drwxr-xr-x 3 root root 0 Jun 28 11:54 ..
-r--r----- 1 root root 0 Jun 28 11:54 736870e5-84f0-4973-92ec-06879ce3da0b
-r--r----- 1 root root 0 Jun 28 11:54 83c83f7f-1356-4975-8b7e-d3a0b54312c6
-r--r----- 1 root root 0 Jun 28 11:54 9553f55d-3da2-43ee-ab5d-ff17f78864d2
-r--r----- 1 root root 0 Jun 28 11:54 e6f5a162-d67f-4750-a67c-5d065f2a9910

# hd /sys/kernel/security/secrets/coco/e6f5a162-d67f-4750-a67c-5d065f2a9910
00000000  74 68 65 73 65 2d 61 72  65 2d 74 68 65 2d 6b 61  |these-are-the-ka|
00000010  74 61 2d 73 65 63 72 65  74 73 00 01 02 03 04 05  |ta-secrets......|
00000020  06 07                                             |..|
00000022

# rm /sys/kernel/security/secrets/coco/e6f5a162-d67f-4750-a67c-5d065f2a9910

# ls -la /sys/kernel/security/secrets/coco
total 0
drwxr-xr-x 2 root root 0 Jun 28 11:55 .
drwxr-xr-x 3 root root 0 Jun 28 11:54 ..
-r--r----- 1 root root 0 Jun 28 11:54 736870e5-84f0-4973-92ec-06879ce3da0b
-r--r----- 1 root root 0 Jun 28 11:54 83c83f7f-1356-4975-8b7e-d3a0b54312c6
-r--r----- 1 root root 0 Jun 28 11:54 9553f55d-3da2-43ee-ab5d-ff17f78864d2
```

<a id="rst-references"></a>

## References

See <a id="rst-citation-reference-3"></a>[sev-api-spec](#rst-sev-api-spec) for more info regarding SEV `LAUNCH_SECRET` operation.

<a id="rst-sev"></a>



**[sev]** [Documentation/virt/kvm/x86/amd-memory-encryption.rst](/kernel/internals/virt/kvm-x86/amd-memory-encryption.md)

<a id="rst-secrets-coco-abi"></a>



**[secrets-coco-abi]** Documentation/ABI/testing/securityfs-secrets-coco

<a id="rst-sev-api-spec"></a>



**[sev-api-spec]** [https://www.amd.com/system/files/TechDocs/55766_SEV-KM_API_Specification.pdf](<https://www.amd.com/system/files/TechDocs/55766_SEV-KM_API_Specification.pdf>)

---

# Trusted Platform Module documentation

_Peios Kernel / Internals / Security / tpm_

> Reference for Trusted Platform Module documentation.

<a id="rst-trusted-platform-module-documentation"></a>

- [TPM Event Log](</kernel/internals/security/tpm/tpm-event-log.md>)
- [TPM Security](</kernel/internals/security/tpm/tpm-security.md>)
- [TPM FIFO interface driver](</kernel/internals/security/tpm/tpm-tis.md>)
- [Virtual TPM Proxy Driver for Linux Containers](</kernel/internals/security/tpm/tpm-vtpm-proxy.md>)
- [Virtual TPM interface for Xen](</kernel/internals/security/tpm/xen-tpmfront.md>)
- [Firmware TPM Driver](</kernel/internals/security/tpm/tpm-ftpm-tee.md>)
- [TPM CRB over FF-A Driver](</kernel/internals/security/tpm/tpm-ffa-crb.md>)

---

# TPM Security

_Peios Kernel / Internals / Security / tpm_

> The object of this document is to describe how we make the kernel's use of the TPM reasonably robust in the face of external snooping and packet alteration attacks (called passive and active interposer attack in the literature). The…

<!-- SPDX-License-Identifier: GPL-2.0-only -->

<a id="rst-tpm-security"></a>

## TPM Security

The object of this document is to describe how we make the kernel's use of the TPM reasonably robust in the face of external snooping and packet alteration attacks (called passive and active interposer attack in the literature).  The current security document is for TPM 2.0.

<a id="rst-introduction"></a>

### Introduction

The TPM is usually a discrete chip attached to a PC via some type of low bandwidth bus.  There are exceptions to this such as the Intel PTT, which is a software TPM running inside a software environment close to the CPU, which are subject to different attacks, but right at the moment, most hardened security environments require a discrete hardware TPM, which is the use case discussed here.

<a id="rst-snooping-and-alteration-attacks-against-the-bus"></a>

### Snooping and Alteration Attacks against the bus

The current state of the art for snooping the [TPM Genie](<https://www.nccgroup.trust/globalassets/about-us/us/documents/tpm-genie.pdf>) hardware interposer which is a simple external device that can be installed in a couple of seconds on any system or laptop.  Recently attacks were successfully demonstrated against the [Windows Bitlocker TPM](<https://dolosgroup.io/blog/2021/7/9/from-stolen-laptop-to-inside-the-company-network>) system. Most recently the same [attack against TPM based Linux disk encryption](<https://www.secura.com/blog/tpm-sniffing-attacks-against-non-bitlocker-targets>) schemes.  The next phase of research seems to be hacking existing devices on the bus to act as interposers, so the fact that the attacker requires physical access for a few seconds might evaporate.  However, the goal of this document is to protect TPM secrets and integrity as far as we are able in this environment and to try to insure that if we can't prevent the attack then at least we can detect it.

Unfortunately, most of the TPM functionality, including the hardware reset capability can be controlled by an attacker who has access to the bus, so we'll discuss some of the disruption possibilities below.

<a id="rst-measurement-pcr-integrity"></a>

### Measurement (PCR) Integrity

Since the attacker can send their own commands to the TPM, they can send arbitrary PCR extends and thus disrupt the measurement system, which would be an annoying denial of service attack.  However, there are two, more serious, classes of attack aimed at entities sealed to trust measurements.

1. The attacker could intercept all PCR extends coming from the system and completely substitute their own values, producing a replay of an untampered state that would cause PCR measurements to attest to a trusted state and release secrets

2. At some point in time the attacker could reset the TPM, clearing the PCRs and then send down their own measurements which would effectively overwrite the boot time measurements the TPM has already done.

The first can be thwarted by always doing HMAC protection of the PCR extend and read command meaning measurement values cannot be substituted without producing a detectable HMAC failure in the response.  However, the second can only really be detected by relying on some sort of mechanism for protection which would change over TPM reset.

<a id="rst-secrets-guarding"></a>

### Secrets Guarding

Certain information passing in and out of the TPM, such as key sealing and private key import and random number generation, is vulnerable to interception which HMAC protection alone cannot protect against, so for these types of command we must also employ request and response encryption to prevent the loss of secret information.

<a id="rst-establishing-initial-trust-with-the-tpm"></a>

### Establishing Initial Trust with the TPM

In order to provide security from the beginning, an initial shared or asymmetric secret must be established which must also be unknown to the attacker.  The most obvious avenues for this are the endorsement and storage seeds, which can be used to derive asymmetric keys. However, using these keys is difficult because the only way to pass them into the kernel would be on the command line, which requires extensive support in the boot system, and there's no guarantee that either hierarchy would not have some type of authorization.

The mechanism chosen for the Linux Kernel is to derive the primary elliptic curve key from the null seed using the standard storage seed parameters.  The null seed has two advantages: firstly the hierarchy physically cannot have an authorization, so we are always able to use it and secondly, the null seed changes across TPM resets, meaning if we establish trust on the null seed at start of day, all sessions salted with the derived key will fail if the TPM is reset and the seed changes.

Obviously using the null seed without any other prior shared secrets, we have to create and read the initial public key which could, of course, be intercepted and substituted by the bus interposer. However, the TPM has a key certification mechanism (using the EK endorsement certificate, creating an attestation identity key and certifying the null seed primary with that key) which is too complex to run within the kernel, so we keep a copy of the null primary key name, which is what is exported via sysfs so user-space can run the full certification when it boots.  The definitive guarantee here is that if the null primary key certifies correctly, you know all your TPM transactions since start of day were secure and if it doesn't, you know there's an interposer on your system (and that any secret used during boot may have been leaked).

<a id="rst-stacking-trust"></a>

### Stacking Trust

In the current null primary scenario, the TPM must be completely cleared before handing it on to the next consumer.  However the kernel hands to user-space the name of the derived null seed key which can then be verified by certification in user-space.  Therefore, this chain of name handoff can be used between the various boot components as well (via an unspecified mechanism).  For instance, grub could use the null seed scheme for security and hand the name off to the kernel in the boot area.  The kernel could make its own derivation of the key and the name and know definitively that if they differ from the handed off version that tampering has occurred.  Thus it becomes possible to chain arbitrary boot components together (UEFI to grub to kernel) via the name handoff provided each successive component knows how to collect the name and verifies it against its derived key.

<a id="rst-session-properties"></a>

### Session Properties

All TPM commands the kernel uses allow sessions.  HMAC sessions may be used to check the integrity of requests and responses and decrypt and encrypt flags may be used to shield parameters and responses.  The HMAC and encryption keys are usually derived from the shared authorization secret, but for a lot of kernel operations that is well known (and usually empty).  Thus, every HMAC session used by the kernel must be created using the null primary key as the salt key which thus provides a cryptographic input into the session key derivation.  Thus, the kernel creates the null primary key once (as a volatile TPM handle) and keeps it around in a saved context stored in tpm_chip for every in-kernel use of the TPM.  Currently, because of a lack of de-gapping in the in-kernel resource manager, the session must be created and destroyed for each operation, but, in future, a single session may also be reused for the in-kernel HMAC, encryption and decryption sessions.

<a id="rst-protection-types"></a>

### Protection Types

For every in-kernel operation we use null primary salted HMAC to protect the integrity.  Additionally, we use parameter encryption to protect key sealing and parameter decryption to protect key unsealing and random number generation.

<a id="rst-null-primary-key-certification-in-userspace"></a>

## Null Primary Key Certification in Userspace

Every TPM comes shipped with a couple of X.509 certificates for the primary endorsement key.  This document assumes that the Elliptic Curve version of the certificate exists at 01C00002, but will work equally well with the RSA certificate (at 01C00001).

The first step in the certification is primary creation using the template from the [TCG EK Credential Profile](<https://trustedcomputinggroup.org/resource/tcg-ek-credential-profile-for-tpm-family-2-0/>) which allows comparison of the generated primary key against the one in the certificate (the public key must match).  Note that generation of the EK primary requires the EK hierarchy password, but a pre-generated version of the EC primary should exist at 81010002 and a TPM2_ReadPublic() may be performed on this without needing the key authority.  Next, the certificate itself must be verified to chain back to the manufacturer root (which should be published on the manufacturer website).  Once this is done, an attestation key (AK) is generated within the TPM and it's name and the EK public key can be used to encrypt a secret using TPM2_MakeCredential.  The TPM then runs TPM2_ActivateCredential which will only recover the secret if the binding between the TPM, the EK and the AK is true. the generated AK may now be used to run a certification of the null primary key whose name the kernel has exported.  Since TPM2_MakeCredential/ActivateCredential are somewhat complicated, a more simplified process involving an externally generated private key is described below.

This process is a simplified abbreviation of the usual privacy CA based attestation process.  The assumption here is that the attestation is done by the TPM owner who thus has access to only the owner hierarchy.  The owner creates an external public/private key pair (assume elliptic curve in this case) and wraps the private key for import using an inner wrapping process and parented to the EC derived storage primary.  The TPM2_Import() is done using a parameter decryption HMAC session salted to the EK primary (which also does not require the EK key authority) meaning that the inner wrapping key is the encrypted parameter and thus the TPM will not be able to perform the import unless is possesses the certified EK so if the command succeeds and the HMAC verifies on return we know we have a loadable copy of the private key only for the certified TPM.  This key is now loaded into the TPM and the Storage primary flushed (to free up space for the null key generation).

The null EC primary is now generated using the Storage profile outlined in the [TCG TPM v2.0 Provisioning Guidance](<https://trustedcomputinggroup.org/resource/tcg-tpm-v2-0-provisioning-guidance/>); the name of this key (the hash of the public area) is computed and compared to the null seed name presented by the kernel in /sys/class/tpm/tpm0/null_name.  If the names do not match, the TPM is compromised.  If the names match, the user performs a TPM2_Certify() using the null primary as the object handle and the loaded private key as the sign handle and providing randomized qualifying data.  The signature of the returned certifyInfo is verified against the public part of the loaded private key and the qualifying data checked to prevent replay.  If all of these tests pass, the user is now assured that TPM integrity and privacy was preserved across the entire boot sequence of this kernel.

<a id="rst-tpm-genie"></a>



<a id="rst-windows-bitlocker-tpm"></a>



<a id="rst-attack-against-tpm-based-linux-disk-encryption"></a>



<a id="rst-tcg-ek-credential-profile"></a>



<a id="rst-tcg-tpm-v2-0-provisioning-guidance"></a>

---

# TPM Event Log

_Peios Kernel / Internals / Security / tpm_

> This document briefly describes what TPM log is and how it is handed over from the preboot firmware to the operating system.

<a id="rst-tpm-event-log"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document briefly describes what TPM log is and how it is handed over from the preboot firmware to the operating system.

<a id="rst-introduction"></a>

## Introduction

The preboot firmware maintains an event log that gets new entries every time something gets hashed by it to any of the PCR registers. The events are segregated by their type and contain the value of the hashed PCR register. Typically, the preboot firmware will hash the components to who execution is to be handed over or actions relevant to the boot process.

The main application for this is remote attestation and the reason why it is useful is nicely put in the very first section of \[1\]:

"Attestation is used to provide information about the platform’s state to a challenger. However, PCR contents are difficult to interpret; therefore, attestation is typically more useful when the PCR contents are accompanied by a measurement log. While not trusted on their own, the measurement log contains a richer set of information than do the PCR contents. The PCR contents are used to provide the validation of the measurement log."

<a id="rst-uefi-event-log"></a>

## UEFI event log

UEFI provided event log has a few somewhat weird quirks.

Before calling ExitBootServices() Linux EFI stub copies the event log to a custom configuration table defined by the stub itself. Unfortunately, the events generated by ExitBootServices() don't end up in the table.

The firmware provides so called final events configuration table to sort out this issue. Events gets mirrored to this table after the first time EFI_TCG2_PROTOCOL.GetEventLog() gets called.

This introduces another problem: nothing guarantees that it is not called before the Linux EFI stub gets to run. Thus, it needs to calculate and save the final events table size while the stub is still running to the custom configuration table so that the TPM driver can later on skip these events when concatenating two halves of the event log from the custom configuration table and the final events table.

<a id="rst-references"></a>

## References

- \[1\] [https://trustedcomputinggroup.org/resource/pc-client-specific-platform-firmware-profile-specification/](<https://trustedcomputinggroup.org/resource/pc-client-specific-platform-firmware-profile-specification/>)

- \[2\] The final concatenation is done in drivers/char/tpm/eventlog/efi.c

---

# TPM CRB over FF-A Driver

_Peios Kernel / Internals / Security / tpm_

> The TPM Command Response Buffer (CRB) interface is a standard TPM interface defined in the TCG PC Client Platform TPM Profile (PTP) Specification 1. The CRB provides a structured set of control registers a client uses when interacting with…

<a id="rst-tpm-crb-over-ff-a-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The TPM Command Response Buffer (CRB) interface is a standard TPM interface defined in the TCG PC Client Platform TPM Profile (PTP) Specification <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1). The CRB provides a structured set of control registers a client uses when interacting with a TPM as well as a data buffer for storing TPM commands and responses. A CRB interface can be implemented in:

- hardware registers in a discrete TPM chip

- in memory for a TPM running in isolated environment where shared memory allows a client to interact with the TPM

The Firmware Framework for Arm A-profile (FF-A) <a id="rst-footnote-reference-2"></a>[2](#rst-footnote-2) is a specification that defines interfaces and protocols for the following purposes:

- Compartmentalize firmware into software partitions that run in the Arm Secure world environment (also know as TrustZone)

- Provide a standard interface for software components in the Non-secure state, for example OS and Hypervisors, to communicate with this firmware.

A TPM can be implemented as an FF-A secure service.  This could be a firmware TPM or could potentially be a TPM service that acts as a proxy to a discrete TPM chip. An FF-A based TPM abstracts hardware details (e.g. bus controller and chip selects) away from the OS and can protect locality 4 from access by an OS.  The TCG-defined CRB interface is used by clients to interact with the TPM service.

The Arm TPM Service Command Response Buffer Interface Over FF-A <a id="rst-footnote-reference-3"></a>[3](#rst-footnote-3) specification defines FF-A messages that can be used by a client to signal when updates have been made to the CRB.

How the Linux CRB driver interacts with FF-A is summarized below:

- The tpm_crb_ffa driver registers with the FF-A subsystem in the kernel with an architected TPM service UUID defined in the CRB over FF-A spec.

- If a TPM service is discovered by FF-A, the probe() function in the tpm_crb_ffa driver runs, and the driver initializes.

- The probing and initialization of the Linux CRB driver is triggered by the discovery of a TPM advertised via ACPI.  The CRB driver can detect the type of TPM through the ACPI 'start' method.  The start method for Arm FF-A was defined in TCG ACPI v1.4 <a id="rst-footnote-reference-4"></a>[4](#rst-footnote-4).

- When the CRB driver performs its normal functions such as signaling 'start' and locality request/relinquish it invokes the tpm_crb_ffa_start() funnction in the tpm_crb_ffa driver which handles the FF-A messaging to the TPM.

<a id="rst-references"></a>

## References

<a id="rst-footnote-1"></a>



**[1]** **TCG PC Client Platform TPM Profile (PTP) Specification** [https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/](<https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/>)

<a id="rst-footnote-2"></a>



**[2]** **Arm Firmware Framework for Arm A-profile (FF-A)** [https://developer.arm.com/documentation/den0077/latest/](<https://developer.arm.com/documentation/den0077/latest/>)

<a id="rst-footnote-3"></a>



**[3]** **Arm TPM Service Command Response Buffer Interface Over FF-A** [https://developer.arm.com/documentation/den0138/latest/](<https://developer.arm.com/documentation/den0138/latest/>)

<a id="rst-footnote-4"></a>



**[4]** **TCG ACPI Specification** [https://trustedcomputinggroup.org/resource/tcg-acpi-specification/](<https://trustedcomputinggroup.org/resource/tcg-acpi-specification/>)

---

# Firmware TPM Driver

_Peios Kernel / Internals / Security / tpm_

> This document describes the firmware Trusted Platform Module (fTPM) device driver.

<a id="rst-firmware-tpm-driver"></a>

This document describes the firmware Trusted Platform Module (fTPM) device driver.

<a id="rst-introduction"></a>

## Introduction

This driver is a shim for firmware implemented in ARM's TrustZone environment. The driver allows programs to interact with the TPM in the same way they would interact with a hardware TPM.

<a id="rst-design"></a>

## Design

The driver acts as a thin layer that passes commands to and from a TPM implemented in firmware. The driver itself doesn't contain much logic and is used more like a dumb pipe between firmware and kernel/userspace.

The firmware itself is based on the following paper: [https://www.microsoft.com/en-us/research/wp-content/uploads/2017/06/ftpm1.pdf](<https://www.microsoft.com/en-us/research/wp-content/uploads/2017/06/ftpm1.pdf>)

When the driver is loaded it will expose `/dev/tpmX` character devices to userspace which will enable userspace to communicate with the firmware TPM through this device.

---

# TPM FIFO interface driver

_Peios Kernel / Internals / Security / tpm_

> TCG PTP Specification defines two interface types: FIFO and CRB. The former is based on sequenced read and write operations, and the latter is based on a buffer containing the full command or response.

<a id="rst-tpm-fifo-interface-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

TCG PTP Specification defines two interface types: FIFO and CRB. The former is based on sequenced read and write operations,  and the latter is based on a buffer containing the full command or response.

FIFO (First-In-First-Out) interface is used by the tpm_tis_core dependent drivers. Originally Linux had only a driver called tpm_tis, which covered memory mapped (aka MMIO) interface but it was later on extended to cover other physical interfaces supported by the TCG standard.

For historical reasons above the original MMIO driver is called tpm_tis and the framework for FIFO drivers is named as tpm_tis_core. The postfix "tis" in tpm_tis comes from the TPM Interface Specification, which is the hardware interface specification for TPM 1.x chips.

Communication is based on a 20 KiB buffer shared by the TPM chip through a hardware bus or memory map, depending on the physical wiring. The buffer is further split into five equal-size 4 KiB buffers, which provide equivalent sets of registers for communication between the CPU and TPM. These communication endpoints are called localities in the TCG terminology.

When the kernel wants to send commands to the TPM chip, it first reserves locality 0 by setting the requestUse bit in the TPM_ACCESS register. The bit is cleared by the chip when the access is granted. Once it completes its communication, the kernel writes the TPM_ACCESS.activeLocality bit. This informs the chip that the locality has been relinquished.

Pending localities are served in order by the chip in descending order, one at a time:

- Locality 0 has the lowest priority.

- Locality 5 has the highest priority.

Further information on the purpose and meaning of the localities can be found in section 3.2 of the TCG PC Client Platform TPM Profile Specification.

<a id="rst-references"></a>

## References

TCG PC Client Platform TPM Profile (PTP) Specification [https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/](<https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/>)

---

# Virtual TPM Proxy Driver for Linux Containers

_Peios Kernel / Internals / Security / tpm_

> This document describes the virtual Trusted Platform Module (vTPM) proxy device driver for Linux containers.

<a id="rst-virtual-tpm-proxy-driver-for-linux-containers"></a>

Authors:  
Stefan Berger &lt;[stefanb@linux.vnet.ibm.com](<mailto:stefanb@linux.vnet.ibm.com>)&gt;

This document describes the virtual Trusted Platform Module (vTPM) proxy device driver for Linux containers.

<a id="rst-introduction"></a>

## Introduction

The goal of this work is to provide TPM functionality to each Linux container. This allows programs to interact with a TPM in a container the same way they interact with a TPM on the physical system. Each container gets its own unique, emulated, software TPM.

<a id="rst-design"></a>

## Design

To make an emulated software TPM available to each container, the container management stack needs to create a device pair consisting of a client TPM character device `/dev/tpmX` (with X=0,1,2...) and a 'server side' file descriptor. The former is moved into the container by creating a character device with the appropriate major and minor numbers while the file descriptor is passed to the TPM emulator. Software inside the container can then send TPM commands using the character device and the emulator will receive the commands via the file descriptor and use it for sending back responses.

To support this, the virtual TPM proxy driver provides a device `/dev/vtpmx` that is used to create device pairs using an ioctl. The ioctl takes as an input flags for configuring the device. The flags  for example indicate whether TPM 1.2 or TPM 2 functionality is supported by the TPM emulator. The result of the ioctl are the file descriptor for the 'server side' as well as the major and minor numbers of the character device that was created. Besides that the number of the TPM character device is returned. If for example `/dev/tpm10` was created, the number (`dev_num`) 10 is returned.

Once the device has been created, the driver will immediately try to talk to the TPM. All commands from the driver can be read from the file descriptor returned by the ioctl. The commands should be responded to immediately.

<a id="rst-uapi"></a>

## UAPI


#### <a id="c-enum-vtpm_proxy_flags"></a>`enum vtpm_proxy_flags`

flags for the proxy TPM

**Constants**

- `VTPM_PROXY_FLAG_TPM2`: the proxy TPM uses TPM 2.0 protocol

#### <a id="c-struct-vtpm_proxy_new_dev"></a>`struct vtpm_proxy_new_dev`

parameter structure for the `VTPM_PROXY_IOC_NEW_DEV` ioctl

**Definition**

```c
struct vtpm_proxy_new_dev {
    __u32 flags;
    __u32 tpm_num;
    __u32 fd;
    __u32 major;
    __u32 minor;
};
```

**Members**

- `flags`: flags for the proxy TPM
- `tpm_num`: index of the TPM device
- `fd`: the file descriptor used by the proxy TPM
- `major`: the major number of the TPM device
- `minor`: the minor number of the TPM device



#### <a id="c-vtpmx_ioc_new_dev"></a>`vtpmx_ioc_new_dev()`

```c
long vtpmx_ioc_new_dev(struct file *file, unsigned int ioctl, unsigned long arg)
```

handler for the `VTPM_PROXY_IOC_NEW_DEV` ioctl

**Parameters**

- `struct file *file`: /dev/vtpmx
- `unsigned int ioctl`: the ioctl number
- `unsigned long arg`: pointer to the struct vtpmx_proxy_new_dev

**Description**

Creates an anonymous file that is used by the process acting as a TPM to
communicate with the client processes. The function will also add a new TPM
device through which data is proxied to this TPM acting process. The caller
will be provided with a file descriptor to communicate with the clients and
major and minor numbers for the TPM device.

---

# Virtual TPM interface for Xen

_Peios Kernel / Internals / Security / tpm_

> Authors: Matthew Fioravante (JHUAPL), Daniel De Graaf (NSA)

<a id="rst-virtual-tpm-interface-for-xen"></a>

Authors: Matthew Fioravante (JHUAPL), Daniel De Graaf (NSA)

This document describes the virtual Trusted Platform Module (vTPM) subsystem for Xen. The reader is assumed to have familiarity with building and installing Xen, Linux, and a basic understanding of the TPM and vTPM concepts.

<a id="rst-introduction"></a>

## Introduction

The goal of this work is to provide a TPM functionality to a virtual guest operating system (in Xen terms, a DomU).  This allows programs to interact with a TPM in a virtual system the same way they interact with a TPM on the physical system.  Each guest gets its own unique, emulated, software TPM.  However, each of the vTPM's secrets (Keys, NVRAM, etc) are managed by a vTPM Manager domain, which seals the secrets to the Physical TPM.  If the process of creating each of these domains (manager, vTPM, and guest) is trusted, the vTPM subsystem extends the chain of trust rooted in the hardware TPM to virtual machines in Xen. Each major component of vTPM is implemented as a separate domain, providing secure separation guaranteed by the hypervisor. The vTPM domains are implemented in mini-os to reduce memory and processor overhead.

This mini-os vTPM subsystem was built on top of the previous vTPM work done by IBM and Intel corporation.

<a id="rst-design-overview"></a>

## Design Overview

The architecture of vTPM is described below:



```text
+------------------+
|    Linux DomU    | ...
|       |  ^       |
|       v  |       |
|   xen-tpmfront   |
+------------------+
        |  ^
        v  |
+------------------+
| mini-os/tpmback  |
|       |  ^       |
|       v  |       |
|  vtpm-stubdom    | ...
|       |  ^       |
|       v  |       |
| mini-os/tpmfront |
+------------------+
        |  ^
        v  |
+------------------+
| mini-os/tpmback  |
|       |  ^       |
|       v  |       |
| vtpmmgr-stubdom  |
|       |  ^       |
|       v  |       |
| mini-os/tpm_tis  |
+------------------+
        |  ^
        v  |
+------------------+
|   Hardware TPM   |
+------------------+
```

- - **Linux DomU:**

    The Linux based guest that wants to use a vTPM. There may be more than one of these.

- - **xen-tpmfront.ko:**

    Linux kernel virtual TPM frontend driver. This driver provides vTPM access to a Linux-based DomU.

- - **mini-os/tpmback:**

    Mini-os TPM backend driver. The Linux frontend driver connects to this backend driver to facilitate communications between the Linux DomU and its vTPM. This driver is also used by vtpmmgr-stubdom to communicate with vtpm-stubdom.

- - **vtpm-stubdom:**

    A mini-os stub domain that implements a vTPM. There is a one to one mapping between running vtpm-stubdom instances and logical vtpms on the system. The vTPM Platform Configuration Registers (PCRs) are normally all initialized to zero.

- - **mini-os/tpmfront:**

    Mini-os TPM frontend driver. The vTPM mini-os domain vtpm-stubdom uses this driver to communicate with vtpmmgr-stubdom. This driver is also used in mini-os domains such as pv-grub that talk to the vTPM domain.

- - **vtpmmgr-stubdom:**

    A mini-os domain that implements the vTPM manager. There is only one vTPM manager and it should be running during the entire lifetime of the machine.  This domain regulates access to the physical TPM on the system and secures the persistent state of each vTPM.

- - **mini-os/tpm_tis:**

    Mini-os TPM version 1.2 TPM Interface Specification (TIS) driver. This driver used by vtpmmgr-stubdom to talk directly to the hardware TPM. Communication is facilitated by mapping hardware memory pages into vtpmmgr-stubdom.

- - **Hardware TPM:**

    The physical TPM that is soldered onto the motherboard.

<a id="rst-integration-with-xen"></a>

## Integration With Xen

Support for the vTPM driver was added in Xen using the libxl toolstack in Xen 4.3.  See the Xen documentation (docs/misc/vtpm.txt) for details on setting up the vTPM and vTPM Manager stub domains.  Once the stub domains are running, a vTPM device is set up in the same manner as a disk or network device in the domain's configuration file.

In order to use features such as IMA that require a TPM to be loaded prior to the initrd, the xen-tpmfront driver must be compiled in to the kernel.  If not using such features, the driver can be compiled as a module and will be loaded as usual.

---

# CPUFreq - CPU frequency and voltage scaling code in the Linux(TM) kernel

_Peios Kernel / Internals / CPU frequency_

> Author: Dominik Brodowski <linux@brodo.de>

<a id="rst-cpufreq-cpu-frequency-and-voltage-scaling-code-in-the-linux-tm-kernel"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Author: Dominik Brodowski  &lt;[linux@brodo.de](<mailto:linux@brodo.de>)&gt;

> Clock scaling allows you to change the clock speed of the CPUs on the fly. This is a nice method to save battery power, because the lower the clock speed, the less power the CPU consumes.

- [General description of the CPUFreq core and CPUFreq notifiers](</kernel/internals/cpu-freq/core.md>)
- [How to Implement a new CPUFreq Processor Driver](</kernel/internals/cpu-freq/cpu-drivers.md>)
- [General Description of sysfs CPUFreq Stats](</kernel/internals/cpu-freq/cpufreq-stats.md>)

<a id="rst-mailing-list"></a>

## Mailing List

There is a CPU frequency general list where you can report bugs, problems or submit patches. To post a message, send an email to [linux-pm@vger.kernel.org](<mailto:linux-pm@vger.kernel.org>).

<a id="rst-links"></a>

## Links

the FTP archives: \* [ftp://ftp.linux.org.uk/pub/linux/cpufreq/](<ftp://ftp.linux.org.uk/pub/linux/cpufreq/>)

the CPUFreq Mailing list: \* [http://vger.kernel.org/vger-lists.html\#linux-pm](<http://vger.kernel.org/vger-lists.html#linux-pm>)

Clock and voltage scaling for the SA-1100: \* [http://www.lartmaker.nl/projects/scaling](<http://www.lartmaker.nl/projects/scaling>)

---

# General description of the CPUFreq core and CPUFreq notifiers

_Peios Kernel / Internals / CPU frequency_

> Dominik Brodowski <linux@brodo.de>

<a id="rst-general-description-of-the-cpufreq-core-and-cpufreq-notifiers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Authors:**

  - Dominik Brodowski  &lt;[linux@brodo.de](<mailto:linux@brodo.de>)&gt;

  - David Kimdon &lt;[dwhedon@debian.org](<mailto:dwhedon@debian.org>)&gt;

  - Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

  - Viresh Kumar &lt;[viresh.kumar@linaro.org](<mailto:viresh.kumar@linaro.org>)&gt;

<!-- Contents:

1.  CPUFreq core and interfaces
2.  CPUFreq notifiers
3.  CPUFreq Table Generation with Operating Performance Point (OPP) -->

<a id="rst-general-information"></a>

## 1. General Information

The CPUFreq core code is located in drivers/cpufreq/cpufreq.c. This cpufreq code offers a standardized interface for the CPUFreq architecture drivers (those pieces of code that do actual frequency transitions), as well as to "notifiers". These are device drivers or other part of the kernel that need to be informed of policy changes (ex. thermal modules like ACPI) or of all frequency changes (ex. timing code) or even need to force certain speed limits (like LCD drivers on ARM architecture). Additionally, the kernel "constant" loops_per_jiffy is updated on frequency changes here.

Reference counting of the cpufreq policies is done by cpufreq_cpu_get and cpufreq_cpu_put, which make sure that the cpufreq driver is correctly registered with the core, and will not be unloaded until cpufreq_put_cpu is called. That also ensures that the respective cpufreq policy doesn't get freed while being used.

<a id="rst-cpufreq-notifiers"></a>

## 2. CPUFreq notifiers

CPUFreq notifiers conform to the standard kernel notifier interface. See linux/include/linux/notifier.h for details on notifiers.

There are two different CPUFreq notifiers - policy notifiers and transition notifiers.

<a id="rst-cpufreq-policy-notifiers"></a>

### 2.1 CPUFreq policy notifiers

These are notified when a new policy is created or removed.

The phase is specified in the second argument to the notifier.  The phase is CPUFREQ_CREATE_POLICY when the policy is first created and it is CPUFREQ_REMOVE_POLICY when the policy is removed.

The third argument, a `void *pointer`, points to a struct cpufreq_policy consisting of several values, including min, max (the lower and upper frequencies (in kHz) of the new policy).

<a id="rst-cpufreq-transition-notifiers"></a>

### 2.2 CPUFreq transition notifiers

These are notified twice for each online CPU in the policy, when the CPUfreq driver switches the CPU core frequency and this change has no any external implications.

The second argument specifies the phase - CPUFREQ_PRECHANGE or CPUFREQ_POSTCHANGE.

The third argument is a struct cpufreq_freqs with the following values:


<table>
<tbody>
<tr>
<td>


policy

</td>
<td>


a pointer to the struct cpufreq_policy

</td>
</tr>
<tr>
<td>


old

</td>
<td>


old frequency

</td>
</tr>
<tr>
<td>


new

</td>
<td>


new frequency

</td>
</tr>
<tr>
<td>


flags

</td>
<td>


flags of the cpufreq driver

</td>
</tr>
</tbody>
</table>

<a id="rst-cpufreq-table-generation-with-operating-performance-point-opp"></a>

## 3. CPUFreq Table Generation with Operating Performance Point (OPP)

For details about OPP, see [Documentation/power/opp.rst](/kernel/internals/power/opp.md)

- **dev_pm_opp_init_cpufreq_table -**

  This function provides a ready to use conversion routine to translate the OPP layer's internal information about the available frequencies into a format readily providable to cpufreq.

  > [!WARNING]
  >
  > Do not use this function in interrupt context.

  Example:



  ```text
  soc_pm_init()
  {
         /* Do things */
         r = dev_pm_opp_init_cpufreq_table(dev, &freq_table);
         if (!r)
                 policy->freq_table = freq_table;
         /* Do other things */
  }
  ```

  > [!NOTE]
  >
  > This function is available only if CONFIG_CPU_FREQ is enabled in addition to CONFIG_PM_OPP.

- **dev_pm_opp_free_cpufreq_table**

  Free up the table allocated by dev_pm_opp_init_cpufreq_table

---

# How to Implement a new CPUFreq Processor Driver

_Peios Kernel / Internals / CPU frequency_

> Authors:

<a id="rst-how-to-implement-a-new-cpufreq-processor-driver"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Authors:

> - Dominik Brodowski  &lt;[linux@brodo.de](<mailto:linux@brodo.de>)&gt;
>
> - Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;
>
> - Viresh Kumar &lt;[viresh.kumar@linaro.org](<mailto:viresh.kumar@linaro.org>)&gt;

<!-- Contents

1.   What To Do?
1.1  Initialization
1.2  Per-CPU Initialization
1.3  verify
1.4  target/target_index or setpolicy?
1.5  target/target_index
1.6  setpolicy
1.7  get_intermediate and target_intermediate
2.   Frequency Table Helpers -->

<a id="rst-what-to-do"></a>

## 1. What To Do?

So, you just got a brand-new CPU / chipset with datasheets and want to add cpufreq support for this CPU / chipset? Great. Here are some hints on what is necessary:

<a id="rst-initialization"></a>

### 1.1 Initialization

First of all, in an \__initcall level 7 (module_init()) or later function check whether this kernel runs on the right CPU and the right chipset. If so, register a struct cpufreq_driver with the CPUfreq core using cpufreq_register_driver()

What shall this struct cpufreq_driver contain?

> .name - The name of this driver.
>
> .init - A pointer to the per-policy initialization function.
>
> .verify - A pointer to a "verification" function.
>
> .setpolicy \_or\_ .fast_switch \_or\_ .target \_or\_ .target_index - See below on the differences.

And optionally

> .flags - Hints for the cpufreq core.
>
> .driver_data - cpufreq driver specific data.
>
> .get_intermediate and target_intermediate - Used to switch to stable frequency while changing CPU frequency.
>
> .get - Returns current frequency of the CPU.
>
> .bios_limit - Returns HW/BIOS max frequency limitations for the CPU.
>
> .exit - A pointer to a per-policy cleanup function called during CPU_POST_DEAD phase of cpu hotplug process.
>
> .suspend - A pointer to a per-policy suspend function which is called with interrupts disabled and \_after\_ the governor is stopped for the policy.
>
> .resume - A pointer to a per-policy resume function which is called with interrupts disabled and \_before\_ the governor is started again.
>
> .ready - A pointer to a per-policy ready function which is called after the policy is fully initialized.
>
> .attr - A pointer to a NULL-terminated list of "struct freq_attr" which allow to export values to sysfs.
>
> .boost_enabled - If set, boost frequencies are enabled.
>
> .set_boost - A pointer to a per-policy function to enable/disable boost frequencies.

<a id="rst-per-cpu-initialization"></a>

### 1.2 Per-CPU Initialization

Whenever a new CPU is registered with the device model, or after the cpufreq driver registers itself, the per-policy initialization function cpufreq_driver.init is called if no cpufreq policy existed for the CPU. Note that the .init() and .exit() routines are called only once for the policy and not for each CPU managed by the policy. It takes a `struct cpufreq_policy *policy` as argument. What to do now?

If necessary, activate the CPUfreq support on your CPU.

Then, the driver must fill in the following values:


<table>
<tbody>
<tr>
<td>


policy-&gt;cpuinfo.min_freq \_and\_ policy-&gt;cpuinfo.max_freq

</td>
<td>


the minimum and maximum frequency (in kHz) which is supported by this CPU

</td>
</tr>
<tr>
<td>


policy-&gt;cpuinfo.transition_latency

</td>
<td>


the time it takes on this CPU to switch between two frequencies in nanoseconds

</td>
</tr>
<tr>
<td>


policy-&gt;cur

</td>
<td>


The current operating frequency of this CPU (if appropriate)

</td>
</tr>
<tr>
<td>


policy-&gt;min, policy-&gt;max, policy-&gt;policy and, if necessary, policy-&gt;governor

</td>
<td>


must contain the "default policy" for this CPU. A few moments later, cpufreq_driver.verify and either cpufreq_driver.setpolicy or cpufreq_driver.target/target_index is called with these values.

</td>
</tr>
<tr>
<td>


policy-&gt;cpus

</td>
<td>


Update this with the masks of the (online + offline) CPUs that do DVFS along with this CPU (i.e.  that share clock/voltage rails with it).

</td>
</tr>
</tbody>
</table>

For setting some of these values (cpuinfo.min\[max\]\_freq, policy-&gt;min\[max\]), the frequency table helpers might be helpful. See the section 2 for more information on them.

<a id="rst-verify"></a>

### 1.3 verify

When the user decides a new policy (consisting of "policy,governor,min,max") shall be set, this policy must be validated so that incompatible values can be corrected. For verifying these values cpufreq_verify_within_limits(`struct cpufreq_policy *policy`, `unsigned int min_freq`, `unsigned int max_freq`) function might be helpful. See section 2 for details on frequency table helpers.

You need to make sure that at least one valid frequency (or operating range) is within policy-&gt;min and policy-&gt;max. If necessary, increase policy-&gt;max first, and only if this is no solution, decrease policy-&gt;min.

<a id="rst-target-or-target-index-or-setpolicy-or-fast-switch"></a>

### 1.4 target or target_index or setpolicy or fast_switch?

Most cpufreq drivers or even most cpu frequency scaling algorithms only allow the CPU frequency to be set to predefined fixed values. For these, you use the -&gt;target(), -&gt;target_index() or -&gt;fast_switch() callbacks.

Some cpufreq capable processors switch the frequency between certain limits on their own. These shall use the -&gt;setpolicy() callback.

<a id="rst-target-target-index"></a>

### 1.5. target/target_index

The target_index call has two arguments: `struct cpufreq_policy *policy`, and `unsigned int` index (into the exposed frequency table).

The CPUfreq driver must set the new frequency when called here. The actual frequency must be determined by freq_table\[index\].frequency.

It should always restore to earlier frequency (i.e. policy-&gt;restore_freq) in case of errors, even if we switched to intermediate frequency earlier.

<a id="rst-deprecated"></a>

### Deprecated

The target call has three arguments: `struct cpufreq_policy *policy`, unsigned int target_frequency, unsigned int relation.

The CPUfreq driver must set the new frequency when called here. The actual frequency must be determined using the following rules:

- keep close to "target_freq"

- policy-&gt;min &lt;= new_freq &lt;= policy-&gt;max (THIS MUST BE VALID\!\!\!)

- if relation==CPUFREQ_REL_L, try to select a new_freq higher than or equal target_freq. ("L for lowest, but no lower than")

- if relation==CPUFREQ_REL_H, try to select a new_freq lower than or equal target_freq. ("H for highest, but no higher than")

Here again the frequency table helper might assist you - see section 2 for details.

<a id="rst-fast-switch"></a>

### 1.6. fast_switch

This function is used for frequency switching from scheduler's context. Not all drivers are expected to implement it, as sleeping from within this callback isn't allowed. This callback must be highly optimized to do switching as fast as possible.

This function has two arguments: `struct cpufreq_policy *policy` and `unsigned int target_frequency`.

<a id="rst-setpolicy"></a>

### 1.7 setpolicy

The setpolicy call only takes a `struct cpufreq_policy *policy` as argument. You need to set the lower limit of the in-processor or in-chipset dynamic frequency switching to policy-&gt;min, the upper limit to policy-&gt;max, and -if supported- select a performance-oriented setting when policy-&gt;policy is CPUFREQ_POLICY_PERFORMANCE, and a powersaving-oriented setting when CPUFREQ_POLICY_POWERSAVE. Also check the reference implementation in drivers/cpufreq/longrun.c

<a id="rst-get-intermediate-and-target-intermediate"></a>

### 1.8 get_intermediate and target_intermediate

Only for drivers with target_index() and CPUFREQ_ASYNC_NOTIFICATION unset.

get_intermediate should return a stable intermediate frequency platform wants to switch to, and target_intermediate() should set CPU to that frequency, before jumping to the frequency corresponding to 'index'. Core will take care of sending notifications and driver doesn't have to handle them in target_intermediate() or target_index().

Drivers can return '0' from get_intermediate() in case they don't wish to switch to intermediate frequency for some target frequency. In that case core will directly call -&gt;target_index().

NOTE: -&gt;target_index() should restore to policy-&gt;restore_freq in case of failures as core would send notifications for that.

<a id="rst-frequency-table-helpers"></a>

## 2. Frequency Table Helpers

As most cpufreq processors only allow for being set to a few specific frequencies, a "frequency table" with some functions might assist in some work of the processor driver. Such a "frequency table" consists of an array of struct cpufreq_frequency_table entries, with driver specific values in "driver_data", the corresponding frequency in "frequency" and flags set. At the end of the table, you need to add a cpufreq_frequency_table entry with frequency set to CPUFREQ_TABLE_END. And if you want to skip one entry in the table, set the frequency to CPUFREQ_ENTRY_INVALID. The entries don't need to be in sorted in any particular order, but if they are cpufreq core will do DVFS a bit quickly for them as search for best match is faster.

The cpufreq table is verified automatically by the core if the policy contains a valid pointer in its policy-&gt;freq_table field.

cpufreq_frequency_table_verify() assures that at least one valid frequency is within policy-&gt;min and policy-&gt;max, and all other criteria are met. This is helpful for the -&gt;verify call.

cpufreq_frequency_table_target() is the corresponding frequency table helper for the -&gt;target stage. Just pass the values to this function, and this function returns the of the frequency table entry which contains the frequency the CPU shall be set to.

The following macros can be used as iterators over cpufreq_frequency_table:

cpufreq_for_each_entry(pos, table) - iterates over all entries of frequency table.

cpufreq_for_each_valid_entry(pos, table) - iterates over all entries, excluding CPUFREQ_ENTRY_INVALID frequencies. Use arguments "pos" - a `cpufreq_frequency_table *` as a loop cursor and "table" - the `cpufreq_frequency_table *` you want to iterate over.

For example:



```text
struct cpufreq_frequency_table *pos, *driver_freq_table;

cpufreq_for_each_entry(pos, driver_freq_table) {
        /* Do something with pos */
        pos->frequency = ...
}
```

If you need to work with the position of pos within driver_freq_table, do not subtract the pointers, as it is quite costly. Instead, use the macros cpufreq_for_each_entry_idx() and cpufreq_for_each_valid_entry_idx().

---

# General Description of sysfs CPUFreq Stats

_Peios Kernel / Internals / CPU frequency_

> information for users

<a id="rst-general-description-of-sysfs-cpufreq-stats"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

information for users

Author: Venkatesh Pallipadi &lt;[venkatesh.pallipadi@intel.com](<mailto:venkatesh.pallipadi@intel.com>)&gt;

<!-- Contents

1. Introduction
2. Statistics Provided (with example)
3. Configuring cpufreq-stats -->

<a id="rst-introduction"></a>

## 1. Introduction

cpufreq-stats is a driver that provides CPU frequency statistics for each CPU. These statistics are provided in /sysfs as a bunch of read_only interfaces. This interface (when configured) will appear in a separate directory under cpufreq in /sysfs (&lt;sysfs root&gt;/devices/system/cpu/cpuX/cpufreq/stats/) for each CPU. Various statistics will form read_only files under this directory.

This driver is designed to be independent of any particular cpufreq_driver that may be running on your CPU. So, it will work with any cpufreq_driver.

<a id="rst-statistics-provided-with-example"></a>

## 2. Statistics Provided (with example)

cpufreq stats provides following statistics (explained in detail below).

- time_in_state

- total_trans

- trans_table

All the statistics will be from the time the stats driver has been inserted (or the time the stats were reset) to the time when a read of a particular statistic is done. Obviously, stats driver will not have any information about the frequency transitions before the stats driver insertion.



```text
<mysystem>:/sys/devices/system/cpu/cpu0/cpufreq/stats # ls -l
total 0
drwxr-xr-x  2 root root    0 May 14 16:06 .
drwxr-xr-x  3 root root    0 May 14 15:58 ..
--w-------  1 root root 4096 May 14 16:06 reset
-r--r--r--  1 root root 4096 May 14 16:06 time_in_state
-r--r--r--  1 root root 4096 May 14 16:06 total_trans
-r--r--r--  1 root root 4096 May 14 16:06 trans_table
```

- **reset**

Write-only attribute that can be used to reset the stat counters. This can be useful for evaluating system behaviour under different governors without the need for a reboot.

- **time_in_state**

This gives the amount of time spent in each of the frequencies supported by this CPU. The cat output will have "&lt;frequency&gt; &lt;time&gt;" pair in each line, which will mean this CPU spent &lt;time&gt; usertime units of time at &lt;frequency&gt;. Output will have one line for each of the supported frequencies. usertime units here is 10mS (similar to other time exported in /proc).



```text
<mysystem>:/sys/devices/system/cpu/cpu0/cpufreq/stats # cat time_in_state
3600000 2089
3400000 136
3200000 34
3000000 67
2800000 172488
```

- **total_trans**

This gives the total number of frequency transitions on this CPU. The cat output will have a single count which is the total number of frequency transitions.



```text
<mysystem>:/sys/devices/system/cpu/cpu0/cpufreq/stats # cat total_trans
20
```

- **trans_table**

This will give a fine grained information about all the CPU frequency transitions. The cat output here is a two dimensional matrix, where an entry &lt;i,j&gt; (row i, column j) represents the count of number of transitions from Freq_i to Freq_j. Freq_i rows and Freq_j columns follow the sorting order in which the driver has provided the frequency table initially to the cpufreq core and so can be sorted (ascending or descending) or unsorted.  The output here also contains the actual freq values for each row and column for better readability.

If the transition table is bigger than PAGE_SIZE, reading this will return an -EFBIG error.



```text
<mysystem>:/sys/devices/system/cpu/cpu0/cpufreq/stats # cat trans_table
From  :    To
        :   3600000   3400000   3200000   3000000   2800000
3600000:         0         5         0         0         0
3400000:         4         0         2         0         0
3200000:         0         1         0         2         0
3000000:         0         0         1         0         3
2800000:         0         0         0         2         0
```

<a id="rst-configuring-cpufreq-stats"></a>

## 3. Configuring cpufreq-stats

To configure cpufreq-stats in your kernel:



```text
Config Main Menu
        Power management options (ACPI, APM)  --->
                CPU Frequency scaling  --->
                        [*] CPU Frequency scaling
                        [*]   CPU frequency translation statistics
```

"CPU Frequency scaling" (CONFIG_CPU_FREQ) should be enabled to configure cpufreq-stats.

"CPU frequency translation statistics" (CONFIG_CPU_FREQ_STAT) provides the statistics which includes time_in_state, total_trans and trans_table.

Once this option is enabled and your CPU supports cpufrequency, you will be able to see the CPU frequency statistics in /sysfs.

---

# Power Management

_Peios Kernel / Internals / Power_

> Reference for Power Management.

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-power-management"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [APM or ACPI?](</kernel/internals/power/apm-acpi.md>)
- [Debugging hibernation and suspend](</kernel/internals/power/basic-pm-debugging.md>)
- [Charger Manager](</kernel/internals/power/charger-manager.md>)
- [Testing suspend and resume support in device drivers](</kernel/internals/power/drivers-testing.md>)
- [Energy Model of devices](</kernel/internals/power/energy-model.md>)
- [Freezing of tasks](</kernel/internals/power/freezing-of-tasks.md>)
- [Operating Performance Points (OPP) Library](</kernel/internals/power/opp.md>)
- [PCI Power Management](</kernel/internals/power/pci.md>)
- [PM Quality Of Service Interface](</kernel/internals/power/pm-qos-interface.md>)
- [Linux power supply class](</kernel/internals/power/power-supply-class.md>)
- [Runtime Power Management Framework for I/O Devices](</kernel/internals/power/runtime-pm.md>)
- [How to get s2ram working](</kernel/internals/power/s2ram.md>)
- [Debugging Kernel Shutdown Hangs with pstore](</kernel/internals/power/shutdown-debugging.md>)
- [Interaction of Suspend code (S3) with the CPU hotplug infrastructure](</kernel/internals/power/suspend-and-cpuhotplug.md>)
- [System Suspend and Device Interrupts](</kernel/internals/power/suspend-and-interrupts.md>)
- [Using swap files with software suspend (swsusp)](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/power/swsusp-and-swap-files.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [How to use dm-crypt and swsusp together](</kernel/internals/power/swsusp-dmcrypt.md>)
- [Swap suspend](</kernel/internals/power/swsusp.md>)
- [Video issues with S3 resume](</kernel/internals/power/video.md>)
- [swsusp/S3 tricks](</kernel/internals/power/tricks.md>)
- [Documentation for userland software suspend interface](</kernel/internals/power/userland-swsusp.md>)
- [Power Capping Framework](</kernel/internals/power/powercap/powercap.md>)
- [Dynamic Thermal Power Management framework](</kernel/internals/power/powercap/dtpm.md>)
- [Regulator Consumer Driver Interface](</kernel/internals/power/regulator/consumer.md>)
- [Regulator API design notes](</kernel/internals/power/regulator/design.md>)
- [Regulator Machine Driver Interface](</kernel/internals/power/regulator/machine.md>)
- [Linux voltage and current regulator framework](</kernel/internals/power/regulator/overview.md>)
- [Regulator Driver Interface](</kernel/internals/power/regulator/regulator.md>)

---

# APM or ACPI?

_Peios Kernel / Internals / Power_

> If you have a relatively recent x86 mobile, desktop, or server system, odds are it supports either Advanced Power Management (APM) or Advanced Configuration and Power Interface (ACPI). ACPI is the newer of the two technologies and puts…

<a id="rst-apm-or-acpi"></a>

If you have a relatively recent x86 mobile, desktop, or server system, odds are it supports either Advanced Power Management (APM) or Advanced Configuration and Power Interface (ACPI).  ACPI is the newer of the two technologies and puts power management in the hands of the operating system, allowing for more intelligent power management than is possible with BIOS controlled APM.

The best way to determine which, if either, your system supports is to build a kernel with both ACPI and APM enabled (as of 2.3.x ACPI is enabled by default).  If a working ACPI implementation is found, the ACPI driver will override and disable APM, otherwise the APM driver will be used.

No, sorry, you cannot have both ACPI and APM enabled and running at once.  Some people with broken ACPI or broken APM implementations would like to use both to get a full set of working features, but you simply cannot mix and match the two.  Only one power management interface can be in control of the machine at once.  Think about it..

<a id="rst-user-space-daemons"></a>

## User-space Daemons

Both APM and ACPI rely on user-space daemons, apmd and acpid respectively, to be completely functional.  Obtain both of these daemons from your Linux distribution or from the Internet (see below) and be sure that they are started sometime in the system boot process. Go ahead and start both.  If ACPI or APM is not available on your system the associated daemon will exit gracefully.

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> apmd
>
> </td>
> <td>
>
>
> [http://ftp.debian.org/pool/main/a/apmd/](<http://ftp.debian.org/pool/main/a/apmd/>)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> acpid
>
> </td>
> <td>
>
>
> [http://acpid.sf.net/](<http://acpid.sf.net/>)
>
> </td>
> </tr>
> </tbody>
> </table>

---

# Debugging hibernation and suspend

_Peios Kernel / Internals / Power_

> 2007 Rafael J. Wysocki <rjw@sisk.pl>, GPL

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-debugging-hibernation-and-suspend"></a>

> - **(C)** 2007 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, GPL

<a id="rst-testing-hibernation-aka-suspend-to-disk-or-std"></a>

## 1. Testing hibernation (aka suspend to disk or STD)

To check if hibernation works, you can try to hibernate in the "reboot" mode:



```text
# echo reboot > /sys/power/disk
# echo disk > /sys/power/state
```

and the system should create a hibernation image, reboot, resume and get back to the command prompt where you have started the transition.  If that happens, hibernation is most likely to work correctly.  Still, you need to repeat the test at least a couple of times in a row for confidence.  \[This is necessary, because some problems only show up on a second attempt at suspending and resuming the system.\]  Moreover, hibernating in the "reboot" and "shutdown" modes causes the PM core to skip some platform-related callbacks which on ACPI systems might be necessary to make hibernation work.  Thus, if your machine fails to hibernate or resume in the "reboot" mode, you should try the "platform" mode:



```text
# echo platform > /sys/power/disk
# echo disk > /sys/power/state
```

which is the default and recommended mode of hibernation.

Unfortunately, the "platform" mode of hibernation does not work on some systems with broken BIOSes.  In such cases the "shutdown" mode of hibernation might work:



```text
# echo shutdown > /sys/power/disk
# echo disk > /sys/power/state
```

(it is similar to the "reboot" mode, but it requires you to press the power button to make the system resume).

If neither "platform" nor "shutdown" hibernation mode works, you will need to identify what goes wrong.

<a id="rst-a-test-modes-of-hibernation"></a>

### a) Test modes of hibernation

To find out why hibernation fails on your system, you can use a special testing facility available if the kernel is compiled with CONFIG_PM_DEBUG set.  Then, there is the file /sys/power/pm_test that can be used to make the hibernation core run in a test mode.  There are 5 test modes available:

- **freezer**

  - test the freezing of processes

- **devices**

  - test the freezing of processes and suspending of devices

- **platform**

  - test the freezing of processes, suspending of devices and platform global control methods <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

- **processors**

  - test the freezing of processes, suspending of devices, platform global control methods <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1) and the disabling of nonboot CPUs

- **core**

  - test the freezing of processes, suspending of devices, platform global control methods<a id="rst-footnote-reference-3"></a>[1](#rst-footnote-1), the disabling of nonboot CPUs and suspending of platform/system devices

<a id="rst-footnote-1"></a>



**[1]** the platform global control methods are only available on ACPI systems and are only tested if the hibernation mode is set to "platform"

To use one of them it is necessary to write the corresponding string to /sys/power/pm_test (eg. "devices" to test the freezing of processes and suspending devices) and issue the standard hibernation commands.  For example, to use the "devices" test mode along with the "platform" mode of hibernation, you should do the following:



```text
# echo devices > /sys/power/pm_test
# echo platform > /sys/power/disk
# echo disk > /sys/power/state
```

Then, the kernel will try to freeze processes, suspend devices, wait a few seconds (5 by default, but configurable by the suspend.pm_test_delay module parameter), resume devices and thaw processes.  If "platform" is written to /sys/power/pm_test , then after suspending devices the kernel will additionally invoke the global control methods (eg. ACPI global control methods) used to prepare the platform firmware for hibernation.  Next, it will wait a configurable number of seconds and invoke the platform (eg. ACPI) global methods used to cancel hibernation etc.

Writing "none" to /sys/power/pm_test causes the kernel to switch to the normal hibernation/suspend operations.  Also, when open for reading, /sys/power/pm_test contains a space-separated list of all available tests (including "none" that represents the normal functionality) in which the current test level is indicated by square brackets.

Generally, as you can see, each test level is more "invasive" than the previous one and the "core" level tests the hardware and drivers as deeply as possible without creating a hibernation image.  Obviously, if the "devices" test fails, the "platform" test will fail as well and so on.  Thus, as a rule of thumb, you should try the test modes starting from "freezer", through "devices", "platform" and "processors" up to "core" (repeat the test on each level a couple of times to make sure that any random factors are avoided).

If the "freezer" test fails, there is a task that cannot be frozen (in that case it usually is possible to identify the offending task by analysing the output of dmesg obtained after the failing test).  Failure at this level usually means that there is a problem with the tasks freezer subsystem that should be reported.

If the "devices" test fails, most likely there is a driver that cannot suspend or resume its device (in the latter case the system may hang or become unstable after the test, so please take that into consideration).  To find this driver, you can carry out a binary search according to the rules:

- if the test fails, unload a half of the drivers currently loaded and repeat (that would probably involve rebooting the system, so always note what drivers have been loaded before the test),

- if the test succeeds, load a half of the drivers you have unloaded most recently and repeat.

Once you have found the failing driver (there can be more than just one of them), you have to unload it every time before hibernation.  In that case please make sure to report the problem with the driver.

It is also possible that the "devices" test will still fail after you have unloaded all modules. In that case, you may want to look in your kernel configuration for the drivers that can be compiled as modules (and test again with these drivers compiled as modules).  You may also try to use some special kernel command line options such as "noapic", "noacpi" or even "acpi=off".

If the "platform" test fails, there is a problem with the handling of the platform (eg. ACPI) firmware on your system.  In that case the "platform" mode of hibernation is not likely to work.  You can try the "shutdown" mode, but that is rather a poor man's workaround.

If the "processors" test fails, the disabling/enabling of nonboot CPUs does not work (of course, this only may be an issue on SMP systems) and the problem should be reported.  In that case you can also try to switch the nonboot CPUs off and on using the /sys/devices/system/cpu/cpu\*/online sysfs attributes and see if that works.

If the "core" test fails, which means that suspending of the system/platform devices has failed (these devices are suspended on one CPU with interrupts off), the problem is most probably hardware-related and serious, so it should be reported.

A failure of any of the "platform", "processors" or "core" tests may cause your system to hang or become unstable, so please beware.  Such a failure usually indicates a serious problem that very well may be related to the hardware, but please report it anyway.

<a id="rst-b-testing-minimal-configuration"></a>

### b) Testing minimal configuration

If all of the hibernation test modes work, you can boot the system with the "init=/bin/bash" command line parameter and attempt to hibernate in the "reboot", "shutdown" and "platform" modes.  If that does not work, there probably is a problem with a driver statically compiled into the kernel and you can try to compile more drivers as modules, so that they can be tested individually.  Otherwise, there is a problem with a modular driver and you can find it by loading a half of the modules you normally use and binary searching in accordance with the algorithm: - if there are n modules loaded and the attempt to suspend and resume fails, unload n/2 of the modules and try again (that would probably involve rebooting the system), - if there are n modules loaded and the attempt to suspend and resume succeeds, load n/2 modules more and try again.

Again, if you find the offending module(s), it(they) must be unloaded every time before hibernation, and please report the problem with it(them).

<a id="rst-c-using-the-test-resume-hibernation-option"></a>

### c) Using the "test_resume" hibernation option

/sys/power/disk generally tells the kernel what to do after creating a hibernation image.  One of the available options is "test_resume" which causes the just created image to be used for immediate restoration.  Namely, after doing:



```text
# echo test_resume > /sys/power/disk
# echo disk > /sys/power/state
```

a hibernation image will be created and a resume from it will be triggered immediately without involving the platform firmware in any way.

That test can be used to check if failures to resume from hibernation are related to bad interactions with the platform firmware.  That is, if the above works every time, but resume from actual hibernation does not work or is unreliable, the platform firmware may be responsible for the failures.

On architectures and platforms that support using different kernels to restore hibernation images (that is, the kernel used to read the image from storage and load it into memory is different from the one included in the image) or support kernel address space randomization, it also can be used to check if failures to resume may be related to the differences between the restore and image kernels.

<a id="rst-d-advanced-debugging"></a>

### d) Advanced debugging

In case that hibernation does not work on your system even in the minimal configuration and compiling more drivers as modules is not practical or some modules cannot be unloaded, you can use one of the more advanced debugging techniques to find the problem.  First, if there is a serial port in your box, you can boot the kernel with the 'no_console_suspend' parameter and try to log kernel messages using the serial console.  This may provide you with some information about the reasons of the suspend (resume) failure.  Alternatively, it may be possible to use a FireWire port for debugging with firescope ([http://v3.sk/\~lkundrak/firescope/](<http://v3.sk/~lkundrak/firescope/>)).  On x86 it is also possible to use the PM_TRACE mechanism documented in [Documentation/power/s2ram.rst](/kernel/internals/power/s2ram.md) .

<a id="rst-testing-suspend-to-ram-str"></a>

## 2. Testing suspend to RAM (STR)

To verify that the STR works, it is generally more convenient to use the s2ram tool available from [http://suspend.sf.net](<http://suspend.sf.net>) and documented at [http://en.opensuse.org/SDB:Suspend_to_RAM](<http://en.opensuse.org/SDB:Suspend_to_RAM>) (S2RAM_LINK).

Namely, after writing "freezer", "devices", "platform", "processors", or "core" into /sys/power/pm_test (available if the kernel is compiled with CONFIG_PM_DEBUG set) the suspend code will work in the test mode corresponding to given string.  The STR test modes are defined in the same way as for hibernation, so please refer to Section 1 for more information about them.  In particular, the "core" test allows you to test everything except for the actual invocation of the platform firmware in order to put the system into the sleep state.

Among other things, the testing with the help of /sys/power/pm_test may allow you to identify drivers that fail to suspend or resume their devices.  They should be unloaded every time before an STR transition.

Next, you can follow the instructions at S2RAM_LINK to test the system, but if it does not work "out of the box", you may need to boot it with "init=/bin/bash" and test s2ram in the minimal configuration.  In that case, you may be able to search for failing drivers by following the procedure analogous to the one described in section 1.  If you find some failing drivers, you will have to unload them every time before an STR transition (ie. before you run s2ram), and please report the problems with them.

There is a debugfs entry which shows the suspend to RAM statistics. Here is an example of its output:



```text
# mount -t debugfs none /sys/kernel/debug
# cat /sys/kernel/debug/suspend_stats
success: 20
fail: 5
failed_freeze: 0
failed_prepare: 0
failed_suspend: 5
failed_suspend_noirq: 0
failed_resume: 0
failed_resume_noirq: 0
failures:
  last_failed_dev:      alarm
                        adc
  last_failed_errno:    -16
                        -16
  last_failed_step:     suspend
                        suspend
```

Field success means the success number of suspend to RAM, and field fail means the failure number. Others are the failure number of different steps of suspend to RAM. suspend_stats just lists the last 2 failed devices, error number and failed step of suspend.

---

# Charger Manager

_Peios Kernel / Internals / Power_

> 2011 MyungJoo Ham <myungjoo.ham@samsung.com>, GPL

<a id="rst-charger-manager"></a>

> - **(C)** 2011 MyungJoo Ham &lt;[myungjoo.ham@samsung.com](<mailto:myungjoo.ham@samsung.com>)&gt;, GPL

Charger Manager provides in-kernel battery charger management that requires temperature monitoring during suspend-to-RAM state and where each battery may have multiple chargers attached and the userland wants to look at the aggregated information of the multiple chargers.

Charger Manager is a platform_driver with power-supply-class entries. An instance of Charger Manager (a platform-device created with Charger-Manager) represents an independent battery with chargers. If there are multiple batteries with their own chargers acting independently in a system, the system may need multiple instances of Charger Manager.

<a id="rst-introduction"></a>

## 1. Introduction

Charger Manager supports the following:

- - **Support for multiple chargers (e.g., a device with USB, AC, and solar panels)**

    A system may have multiple chargers (or power sources) and some of they may be activated at the same time. Each charger may have its own power-supply-class and each power-supply-class can provide different information about the battery status. This framework aggregates charger-related information from multiple sources and shows combined information as a single power-supply-class.

- - **Support for in suspend-to-RAM polling (with suspend_again callback)**

    While the battery is being charged and the system is in suspend-to-RAM, we may need to monitor the battery health by looking at the ambient or battery temperature. We can accomplish this by waking up the system periodically. However, such a method wakes up devices unnecessarily for monitoring the battery health and tasks, and user processes that are supposed to be kept suspended. That, in turn, incurs unnecessary power consumption and slow down charging process. Or even, such peak power consumption can stop chargers in the middle of charging (external power input &lt; device power consumption), which not only affects the charging time, but the lifespan of the battery.

    Charger Manager provides a function "cm_suspend_again" that can be used as suspend_again callback of platform_suspend_ops. If the platform requires tasks other than cm_suspend_again, it may implement its own suspend_again callback that calls cm_suspend_again in the middle. Normally, the platform will need to resume and suspend some devices that are used by Charger Manager.

- - **Support for premature full-battery event handling**

    If the battery voltage drops by "fullbatt_vchkdrop_uV" after "fullbatt_vchkdrop_ms" from the full-battery event, the framework restarts charging. This check is also performed while suspended by setting wakeup time accordingly and using suspend_again.

- - **Support for uevent-notify**

    With the charger-related events, the device sends notification to users with UEVENT.

<a id="rst-global-charger-manager-data-related-with-suspend-again"></a>

## 2. Global Charger-Manager Data related with suspend_again

In order to setup Charger Manager with suspend-again feature (in-suspend monitoring), the user should provide charger_global_desc with setup_charger_manager(`struct charger_global_desc *`). This charger_global_desc data for in-suspend monitoring is global as the name suggests. Thus, the user needs to provide only once even if there are multiple batteries. If there are multiple batteries, the multiple instances of Charger Manager share the same charger_global_desc and it will manage in-suspend monitoring for all instances of Charger Manager.

The user needs to provide all the three entries to `struct charger_global_desc` properly in order to activate in-suspend monitoring:

- **`char *rtc_name;`**

  The name of rtc (e.g., "rtc0") used to wakeup the system from suspend for Charger Manager. The alarm interrupt (AIE) of the rtc should be able to wake up the system from suspend. Charger Manager saves and restores the alarm value and use the previously-defined alarm if it is going to go off earlier than Charger Manager so that Charger Manager does not interfere with previously-defined alarms.

- **`bool (*rtc_only_wakeup)(void);`**

  This callback should let CM know whether the wakeup-from-suspend is caused only by the alarm of "rtc" in the same struct. If there is any other wakeup source triggered the wakeup, it should return false. If the "rtc" is the only wakeup reason, it should return true.

- **`bool assume_timer_stops_in_suspend;`**

  if true, Charger Manager assumes that the timer (CM uses jiffies as timer) stops during suspend. Then, CM assumes that the suspend-duration is same as the alarm length.

<a id="rst-how-to-setup-suspend-again"></a>

## 3. How to setup suspend_again

Charger Manager provides a function "extern bool cm_suspend_again(void)". When cm_suspend_again is called, it monitors every battery. The suspend_ops callback of the system's platform_suspend_ops can call cm_suspend_again function to know whether Charger Manager wants to suspend again or not. If there are no other devices or tasks that want to use suspend_again feature, the platform_suspend_ops may directly refer to cm_suspend_again for its suspend_again callback.

The cm_suspend_again() returns true (meaning "I want to suspend again") if the system was woken up by Charger Manager and the polling (in-suspend monitoring) results in "normal".

<a id="rst-charger-manager-data-struct-charger-desc"></a>

## 4. Charger-Manager Data (struct charger_desc)

For each battery charged independently from other batteries (if a series of batteries are charged by a single charger, they are counted as one independent battery), an instance of Charger Manager is attached to it. The following

struct charger_desc elements:

- **`char *psy_name;`**

  The power-supply-class name of the battery. Default is "battery" if psy_name is NULL. Users can access the psy entries at "/sys/class/power_supply/\[psy_name\]/".

- **`enum polling_modes polling_mode;`**

  - **CM_POLL_DISABLE:**

    do not poll this battery.

  - **CM_POLL_ALWAYS:**

    always poll this battery.

  - **CM_POLL_EXTERNAL_POWER_ONLY:**

    poll this battery if and only if an external power source is attached.

  - **CM_POLL_CHARGING_ONLY:**

    poll this battery if and only if the battery is being charged.

- **`unsigned int fullbatt_vchkdrop_ms; / unsigned int fullbatt_vchkdrop_uV;`**

  If both have non-zero values, Charger Manager will check the battery voltage drop fullbatt_vchkdrop_ms after the battery is fully charged. If the voltage drop is over fullbatt_vchkdrop_uV, Charger Manager will try to recharge the battery by disabling and enabling chargers. Recharge with voltage drop condition only (without delay condition) is needed to be implemented with hardware interrupts from fuel gauges or charger devices/chips.

- **`unsigned int fullbatt_uV;`**

  If specified with a non-zero value, Charger Manager assumes that the battery is full (capacity = 100) if the battery is not being charged and the battery voltage is equal to or greater than fullbatt_uV.

- **`unsigned int polling_interval_ms;`**

  Required polling interval in ms. Charger Manager will poll this battery every polling_interval_ms or more frequently.

- **`enum data_source battery_present;`**

  - **CM_BATTERY_PRESENT:**

    assume that the battery exists.

  - **CM_NO_BATTERY:**

    assume that the battery does not exists.

  - **CM_FUEL_GAUGE:**

    get battery presence information from fuel gauge.

  - **CM_CHARGER_STAT:**

    get battery presence from chargers.

- **`char **psy_charger_stat;`**

  An array ending with NULL that has power-supply-class names of chargers. Each power-supply-class should provide "PRESENT" (if battery_present is "CM_CHARGER_STAT"), "ONLINE" (shows whether an external power source is attached or not), and "STATUS" (shows whether the battery is \{"FULL" or not FULL\} or \{"FULL", "Charging", "Discharging", "NotCharging"\}).

- **`int num_charger_regulators; / struct regulator_bulk_data *charger_regulators;`**

  Regulators representing the chargers in the form for regulator framework's bulk functions.

- **`char *psy_fuel_gauge;`**

  Power-supply-class name of the fuel gauge.

- **`int (*temperature_out_of_range)(int *mC); / bool measure_battery_temp;`**

  This callback returns 0 if the temperature is safe for charging, a positive number if it is too hot to charge, and a negative number if it is too cold to charge. With the variable mC, the callback returns the temperature in 1/1000 of centigrade. The source of temperature can be battery or ambient one according to the value of measure_battery_temp.

<a id="rst-other-considerations"></a>

## 5. Other Considerations

At the charger/battery-related events such as battery-pulled-out, charger-pulled-out, charger-inserted, DCIN-over/under-voltage, charger-stopped, and others critical to chargers, the system should be configured to wake up. At least the following should wake up the system from a suspend: a) charger-on/off b) external-power-in/out c) battery-in/out (while charging)

It is usually accomplished by configuring the PMIC as a wakeup source.

---

# Testing suspend and resume support in device drivers

_Peios Kernel / Internals / Power_

> 2007 Rafael J. Wysocki <rjw@sisk.pl>, GPL

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-testing-suspend-and-resume-support-in-device-drivers"></a>

> - **(C)** 2007 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, GPL

<a id="rst-preparing-the-test-system"></a>

## 1. Preparing the test system

Unfortunately, to effectively test the support for the system-wide suspend and resume transitions in a driver, it is necessary to suspend and resume a fully functional system with this driver loaded.  Moreover, that should be done several times, preferably several times in a row, and separately for hibernation (aka suspend to disk or STD) and suspend to RAM (STR), because each of these cases involves slightly different operations and different interactions with the machine's BIOS.

Of course, for this purpose the test system has to be known to suspend and resume without the driver being tested.  Thus, if possible, you should first resolve all suspend/resume-related problems in the test system before you start testing the new driver.  Please see [Documentation/power/basic-pm-debugging.rst](/kernel/internals/power/basic-pm-debugging.md) for more information about the debugging of suspend/resume functionality.

<a id="rst-testing-the-driver"></a>

## 2. Testing the driver

Once you have resolved the suspend/resume-related problems with your test system without the new driver, you are ready to test it:

- **a)** Build the driver as a module, load it and try the test modes of hibernation (see: [Documentation/power/basic-pm-debugging.rst](/kernel/internals/power/basic-pm-debugging.md), 1).

- **b)** Load the driver and attempt to hibernate in the "reboot", "shutdown" and "platform" modes (see: [Documentation/power/basic-pm-debugging.rst](/kernel/internals/power/basic-pm-debugging.md), 1).

- **c)** Compile the driver directly into the kernel and try the test modes of hibernation.

- **d)** Attempt to hibernate with the driver compiled directly into the kernel in the "reboot", "shutdown" and "platform" modes.

- **e)** Try the test modes of suspend (see: [Documentation/power/basic-pm-debugging.rst](/kernel/internals/power/basic-pm-debugging.md), 2).  \[As far as the STR tests are concerned, it should not matter whether or not the driver is built as a module.\]

- **f)** Attempt to suspend to RAM using the s2ram tool with the driver loaded (see: [Documentation/power/basic-pm-debugging.rst](/kernel/internals/power/basic-pm-debugging.md), 2).

Each of the above tests should be repeated several times and the STD tests should be mixed with the STR tests.  If any of them fails, the driver cannot be regarded as suspend/resume-safe.

---

# Energy Model of devices

_Peios Kernel / Internals / Power_

> The Energy Model (EM) framework serves as an interface between drivers knowing the power consumed by devices at various performance levels, and the kernel subsystems willing to use that information to make energy-aware decisions.

<a id="rst-energy-model-of-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## 1. Overview

The Energy Model (EM) framework serves as an interface between drivers knowing the power consumed by devices at various performance levels, and the kernel subsystems willing to use that information to make energy-aware decisions.

The source of the information about the power consumed by devices can vary greatly from one platform to another. These power costs can be estimated using devicetree data in some cases. In others, the firmware will know better. Alternatively, userspace might be best positioned. In order to avoid having each and every client subsystem re-implement support for each and every possible source of information on its own, the EM framework intervenes as an abstraction layer which standardizes the format of power cost tables in the kernel, hence enabling to avoid redundant work.

The power values might be expressed in micro-Watts or in an 'abstract scale'. Multiple subsystems might use the EM and it is up to the system integrator to check that the requirements for the power value scale types are met. An example can be found in the Energy-Aware Scheduler documentation [Documentation/scheduler/sched-energy.rst](/kernel/internals/scheduler/sched-energy.md). For some subsystems like thermal or powercap power values expressed in an 'abstract scale' might cause issues. These subsystems are more interested in estimation of power used in the past, thus the real micro-Watts might be needed. An example of these requirements can be found in the Intelligent Power Allocation in [Documentation/driver-api/thermal/power_allocator.rst](/kernel/hardware/driver-api/thermal/power-allocator.md). Kernel subsystems might implement automatic detection to check whether EM registered devices have inconsistent scale (based on EM internal flag). An important thing to keep in mind is that when the power values are expressed in an 'abstract scale' deriving real energy in micro-Joules would not be possible.

The figure below depicts an example of drivers (Arm-specific here, but the approach is applicable to any architecture) providing power costs to the EM framework, and interested clients reading the data from it:



```text
+---------------+  +-----------------+  +---------------+
| Thermal (IPA) |  | Scheduler (EAS) |  |     Other     |
+---------------+  +-----------------+  +---------------+
        |                   | em_cpu_energy()   |
        |                   | em_cpu_get()      |
        +---------+         |         +---------+
                  |         |         |
                  v         v         v
                 +---------------------+
                 |    Energy Model     |
                 |     Framework       |
                 +---------------------+
                    ^       ^       ^
                    |       |       | em_dev_register_perf_domain()
         +----------+       |       +---------+
         |                  |                 |
 +---------------+  +---------------+  +--------------+
 |  cpufreq-dt   |  |   arm_scmi    |  |    Other     |
 +---------------+  +---------------+  +--------------+
         ^                  ^                 ^
         |                  |                 |
 +--------------+   +---------------+  +--------------+
 | Device Tree  |   |   Firmware    |  |      ?       |
 +--------------+   +---------------+  +--------------+
```

In case of CPU devices the EM framework manages power cost tables per 'performance domain' in the system. A performance domain is a group of CPUs whose performance is scaled together. Performance domains generally have a 1-to-1 mapping with CPUFreq policies. All CPUs in a performance domain are required to have the same micro-architecture. CPUs in different performance domains can have different micro-architectures.

To better reflect power variation due to static power (leakage) the EM supports runtime modifications of the power values. The mechanism relies on RCU to free the modifiable EM perf_state table memory. Its user, the task scheduler, also uses RCU to access this memory. The EM framework provides API for allocating/freeing the new memory for the modifiable EM table. The old memory is freed automatically using RCU callback mechanism when there are no owners anymore for the given EM runtime table instance. This is tracked using kref mechanism. The device driver which provided the new EM at runtime, should call EM API to free it safely when it's no longer needed. The EM framework will handle the clean-up when it's possible.

The kernel code which wants to modify the EM values is protected from concurrent access using a mutex. Therefore, the device driver code must run in sleeping context when it tries to modify the EM.

With the runtime modifiable EM we switch from a 'single and during the entire runtime static EM' (system property) design to a 'single EM which can be changed during runtime according e.g. to the workload' (system and workload property) design.

It is possible also to modify the CPU performance values for each EM's performance state. Thus, the full power and performance profile (which is an exponential curve) can be changed according e.g. to the workload or system property.

<a id="rst-core-apis"></a>

## 2. Core APIs

<a id="rst-config-options"></a>

### 2.1 Config options

CONFIG_ENERGY_MODEL must be enabled to use the EM framework.

<a id="rst-registration-of-performance-domains"></a>

### 2.2 Registration of performance domains

<a id="rst-registration-of-advanced-em"></a>

#### Registration of 'advanced' EM

The 'advanced' EM gets its name due to the fact that the driver is allowed to provide a more precise power model. It's not limited to some implemented math formula in the framework (like it is in 'simple' EM case). It can better reflect the real power measurements performed for each performance state. Thus, this registration method should be preferred in case considering EM static power (leakage) is important.

Drivers are expected to register performance domains into the EM framework by calling the following API:



```text
int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states,
              struct em_data_callback *cb, cpumask_t *cpus, bool microwatts);
```

Drivers must provide a callback function returning &lt;frequency, power&gt; tuples for each performance state. The callback function provided by the driver is free to fetch data from any relevant location (DT, firmware, ...), and by any mean deemed necessary. Only for CPU devices, drivers must specify the CPUs of the performance domains using cpumask. For other devices than CPUs the last argument must be set to NULL. The last argument 'microwatts' is important to set with correct value. Kernel subsystems which use EM might rely on this flag to check if all EM devices use the same scale. If there are different scales, these subsystems might decide to return warning/error, stop working or panic. See Section 3. for an example of driver implementing this callback, or Section 2.4 for further documentation on this API

<a id="rst-registration-of-em-using-dt"></a>

#### Registration of EM using DT

The  EM can also be registered using OPP framework and information in DT "operating-points-v2". Each OPP entry in DT can be extended with a property "opp-microwatt" containing micro-Watts power value. This OPP DT property allows a platform to register EM power values which are reflecting total power (static + dynamic). These power values might be coming directly from experiments and measurements.

<a id="rst-registration-of-artificial-em"></a>

#### Registration of 'artificial' EM

There is an option to provide a custom callback for drivers missing detailed knowledge about power value for each performance state. The callback .get_cost() is optional and provides the 'cost' values used by the EAS. This is useful for platforms that only provide information on relative efficiency between CPU types, where one could use the information to create an abstract power model. But even an abstract power model can sometimes be hard to fit in, given the input power value size restrictions. The .get_cost() allows to provide the 'cost' values which reflect the efficiency of the CPUs. This would allow to provide EAS information which has different relation than what would be forced by the EM internal formulas calculating 'cost' values. To register an EM for such platform, the driver must set the flag 'microwatts' to 0, provide .get_power() callback and provide .get_cost() callback. The EM framework would handle such platform properly during registration. A flag EM_PERF_DOMAIN_ARTIFICIAL is set for such platform. Special care should be taken by other frameworks which are using EM to test and treat this flag properly.

<a id="rst-registration-of-simple-em"></a>

#### Registration of 'simple' EM

The 'simple' EM is registered using the framework helper function cpufreq_register_em_with_opp(). It implements a power model which is tied to a math formula:



```text
Power = C * V^2 * f
```

The EM which is registered using this method might not reflect correctly the physics of a real device, e.g. when static power (leakage) is important.

<a id="rst-accessing-performance-domains"></a>

### 2.3 Accessing performance domains

There are two API functions which provide the access to the energy model: em_cpu_get() which takes CPU id as an argument and em_pd_get() with device pointer as an argument. It depends on the subsystem which interface it is going to use, but in case of CPU devices both functions return the same performance domain.

Subsystems interested in the energy model of a CPU can retrieve it using the em_cpu_get() API. The energy model tables are allocated once upon creation of the performance domains, and kept in memory untouched.

The energy consumed by a performance domain can be estimated using the em_cpu_energy() API. The estimation is performed assuming that the schedutil CPUfreq governor is in use in case of CPU device. Currently this calculation is not provided for other type of devices.

More details about the above APIs can be found in `<linux/energy_model.h>` or in Section 2.5

<a id="rst-runtime-modifications"></a>

### 2.4 Runtime modifications

Drivers willing to update the EM at runtime should use the following dedicated function to allocate a new instance of the modified EM. The API is listed below:



```text
struct em_perf_table __rcu *em_table_alloc(struct em_perf_domain *pd);
```

This allows to allocate a structure which contains the new EM table with also RCU and kref needed by the EM framework. The 'struct em_perf_table' contains array 'struct em_perf_state state\[\]' which is a list of performance states in ascending order. That list must be populated by the device driver which wants to update the EM. The list of frequencies can be taken from existing EM (created during boot). The content in the 'struct em_perf_state' must be populated by the driver as well.

This is the API which does the EM update, using RCU pointers swap:



```text
int em_dev_update_perf_domain(struct device *dev,
                      struct em_perf_table __rcu *new_table);
```

Drivers must provide a pointer to the allocated and initialized new EM 'struct em_perf_table'. That new EM will be safely used inside the EM framework and will be visible to other sub-systems in the kernel (thermal, powercap). The main design goal for this API is to be fast and avoid extra calculations or memory allocations at runtime. When pre-computed EMs are available in the device driver, then it should be possible to simply reuse them with low performance overhead.

In order to free the EM, provided earlier by the driver (e.g. when the module is unloaded), there is a need to call the API:



```text
void em_table_free(struct em_perf_table __rcu *table);
```

It will allow the EM framework to safely remove the memory, when there is no other sub-system using it, e.g. EAS.

To use the power values in other sub-systems (like thermal, powercap) there is a need to call API which protects the reader and provide consistency of the EM table data:



```text
struct em_perf_state *em_perf_state_from_pd(struct em_perf_domain *pd);
```

It returns the 'struct em_perf_state' pointer which is an array of performance states in ascending order. This function must be called in the RCU read lock section (after the rcu_read_lock()). When the EM table is not needed anymore there is a need to call rcu_read_unlock(). In this way the EM safely uses the RCU read section and protects the users. It also allows the EM framework to manage the memory and free it. More details how to use it can be found in Section 3.2 in the example driver.

There is dedicated API for device drivers to calculate em_perf_state::cost values:



```text
int em_dev_compute_costs(struct device *dev, struct em_perf_state *table,
                         int nr_states);
```

These 'cost' values from EM are used in EAS. The new EM table should be passed together with the number of entries and device pointer. When the computation of the cost values is done properly the return value from the function is 0. The function takes care for right setting of inefficiency for each performance state as well. It updates em_perf_state::flags accordingly. Then such prepared new EM can be passed to the em_dev_update_perf_domain() function, which will allow to use it.

More details about the above APIs can be found in `<linux/energy_model.h>` or in Section 3.2 with an example code showing simple implementation of the updating mechanism in a device driver.

<a id="rst-description-details-of-this-api"></a>

### 2.5 Description details of this API


#### <a id="c-struct-em_perf_state"></a>`struct em_perf_state`

Performance state of a performance domain

**Definition**

```c
struct em_perf_state {
    unsigned long performance;
    unsigned long frequency;
    unsigned long power;
    unsigned long cost;
    unsigned long flags;
};
```

**Members**

- `performance`: CPU performance (capacity) at a given frequency
- `frequency`: The frequency in KHz, for consistency with CPUFreq
- `power`: The power consumed at this level (by 1 CPU or by a registered
  device). It can be a total power: static and dynamic.
- `cost`: The cost coefficient associated with this level, used during
  energy calculation. Equal to: 10 * power * max_frequency / frequency
- `flags`: see "em_perf_state flags" description below.

#### <a id="c-struct-em_perf_table"></a>`struct em_perf_table`

Performance states table

**Definition**

```c
struct em_perf_table {
    struct rcu_head rcu;
    struct kref kref;
    struct em_perf_state state[];
};
```

**Members**

- `rcu`: RCU used for safe access and destruction
- `kref`: Reference counter to track the users
- `state`: List of performance states, in ascending order

#### <a id="c-struct-em_perf_domain"></a>`struct em_perf_domain`

Performance domain

**Definition**

```c
struct em_perf_domain {
    struct em_perf_table  *em_table;
    struct list_head node;
    int id;
    int nr_perf_states;
    int min_perf_state;
    int max_perf_state;
    unsigned long flags;
    unsigned long cpus[];
};
```

**Members**

- `em_table`: Pointer to the runtime modifiable em_perf_table
- `node`: node in em_pd_list (in energy_model.c)
- `id`: A unique ID number for each performance domain
- `nr_perf_states`: Number of performance states
- `min_perf_state`: Minimum allowed Performance State index
- `max_perf_state`: Maximum allowed Performance State index
- `flags`: See "em_perf_domain flags"
- `cpus`: Cpumask covering the CPUs of the domain. It's here
  for performance reasons to avoid potential cache
  misses during energy calculations in the scheduler
  and simplifies allocating/freeing that memory region.

**Description**

In case of CPU device, a "performance domain" represents a group of CPUs
whose performance is scaled together. All CPUs of a performance domain
must have the same micro-architecture. Performance domains often have
a 1-to-1 mapping with CPUFreq policies. In case of other devices the **cpus**
field is unused.

#### <a id="c-em_pd_get_efficient_state"></a>`em_pd_get_efficient_state()`

```c
int em_pd_get_efficient_state(struct em_perf_state *table, struct em_perf_domain *pd, unsigned long max_util)
```

Get an efficient performance state from the EM

**Parameters**

- `struct em_perf_state *table`: List of performance states, in ascending order
- `struct em_perf_domain *pd`: performance domain for which this must be done
- `unsigned long max_util`: Max utilization to map with the EM

**Description**

It is called from the scheduler code quite frequently and as a consequence
doesn't implement any check.

**Return**

An efficient performance state id, high enough to meet **max_util**
requirement.

#### <a id="c-em_cpu_energy"></a>`em_cpu_energy()`

```c
unsigned long em_cpu_energy(struct em_perf_domain *pd, unsigned long max_util, unsigned long sum_util, unsigned long allowed_cpu_cap)
```

Estimates the energy consumed by the CPUs of a performance domain

**Parameters**

- `struct em_perf_domain *pd`: performance domain for which energy has to be estimated
- `unsigned long max_util`: highest utilization among CPUs of the domain
- `unsigned long sum_util`: sum of the utilization of all CPUs in the domain
- `unsigned long allowed_cpu_cap`: maximum allowed CPU capacity for the **pd**, which
  might reflect reduced frequency (due to thermal)

**Description**

This function must be used only for CPU devices. There is no validation,
i.e. if the EM is a CPU type and has cpumask allocated. It is called from
the scheduler code quite frequently and that is why there is not checks.

**Return**

the sum of the energy consumed by the CPUs of the domain assuming
a capacity state satisfying the max utilization of the domain.

#### <a id="c-em_pd_nr_perf_states"></a>`em_pd_nr_perf_states()`

```c
int em_pd_nr_perf_states(struct em_perf_domain *pd)
```

Get the number of performance states of a perf. domain

**Parameters**

- `struct em_perf_domain *pd`: performance domain for which this must be done

**Return**

the number of performance states in the performance domain table

#### <a id="c-em_perf_state_from_pd"></a>`em_perf_state_from_pd()`

```c
struct em_perf_state * em_perf_state_from_pd(struct em_perf_domain *pd)
```

Get the performance states table of perf. domain

**Parameters**

- `struct em_perf_domain *pd`: performance domain for which this must be done

**Description**

To use this function the [`rcu_read_lock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_lock) should be hold. After the usage
of the performance states table is finished, the [`rcu_read_unlock()`](/kernel/internals/core-api/kernel-api.md#c-rcu_read_unlock) should
be called.

**Return**

the pointer to performance states table of the performance domain



#### <a id="c-em_dev_update_perf_domain"></a>`em_dev_update_perf_domain()`

```c
int em_dev_update_perf_domain(struct device *dev, struct em_perf_table *new_table)
```

Update runtime EM table for a device

**Parameters**

- `struct device *dev`: Device for which the EM is to be updated
- `struct em_perf_table *new_table`: The new EM table that is going to be used from now

**Description**

Update EM runtime modifiable table for the **dev** using the provided **table**.

This function uses a mutex to serialize writers, so it must not be called
from a non-sleeping context.

Return 0 on success or an error code on failure.

#### <a id="c-em_pd_get"></a>`em_pd_get()`

```c
struct em_perf_domain * em_pd_get(struct device *dev)
```

Return the performance domain for a device

**Parameters**

- `struct device *dev`: Device to find the performance domain for

**Description**

Returns the performance domain to which **dev** belongs, or NULL if it doesn't
exist.

#### <a id="c-em_cpu_get"></a>`em_cpu_get()`

```c
struct em_perf_domain * em_cpu_get(int cpu)
```

Return the performance domain for a CPU

**Parameters**

- `int cpu`: CPU to find the performance domain for

**Description**

Returns the performance domain to which **cpu** belongs, or NULL if it doesn't
exist.

#### <a id="c-em_dev_register_perf_domain"></a>`em_dev_register_perf_domain()`

```c
int em_dev_register_perf_domain(struct device *dev, unsigned int nr_states, const struct em_data_callback *cb, const cpumask_t *cpus, bool microwatts)
```

Register the Energy Model (EM) for a device

**Parameters**

- `struct device *dev`: Device for which the EM is to register
- `unsigned int nr_states`: Number of performance states to register
- `const struct em_data_callback *cb`: Callback functions providing the data of the Energy Model
- `const cpumask_t *cpus`: Pointer to cpumask_t, which in case of a CPU device is
  obligatory. It can be taken from i.e. 'policy->cpus'. For other
  type of devices this should be set to NULL.
- `bool microwatts`: Flag indicating that the power values are in micro-Watts or
  in some other scale. It must be set properly.

**Description**

Create Energy Model tables for a performance domain using the callbacks
defined in cb.

The **microwatts** is important to set with correct value. Some kernel
sub-systems might rely on this flag and check if all devices in the EM are
using the same scale.

If multiple clients register the same performance domain, all but the first
registration will be ignored.

Return 0 on success

#### <a id="c-em_dev_register_pd_no_update"></a>`em_dev_register_pd_no_update()`

```c
int em_dev_register_pd_no_update(struct device *dev, unsigned int nr_states, const struct em_data_callback *cb, const cpumask_t *cpus, bool microwatts)
```

Register a perf domain for a device

**Parameters**

- `struct device *dev`: Device to register the PD for
- `unsigned int nr_states`: Number of performance states in the new PD
- `const struct em_data_callback *cb`: Callback functions for populating the energy model
- `const cpumask_t *cpus`: CPUs to include in the new PD (mandatory if **dev** is a CPU device)
- `bool microwatts`: Whether or not the power values in the EM will be in uW

**Description**

Like [`em_dev_register_perf_domain()`](#c-em_dev_register_perf_domain), but does not trigger a CPU capacity
update after registering the PD, even if **dev** is a CPU device.

#### <a id="c-em_dev_unregister_perf_domain"></a>`em_dev_unregister_perf_domain()`

```c
void em_dev_unregister_perf_domain(struct device *dev)
```

Unregister Energy Model (EM) for a device

**Parameters**

- `struct device *dev`: Device for which the EM is registered

**Description**

Unregister the EM for the specified **dev** (but not a CPU device).

#### <a id="c-em_dev_update_chip_binning"></a>`em_dev_update_chip_binning()`

```c
int em_dev_update_chip_binning(struct device *dev)
```

Update Energy Model after the new voltage information is present in the OPPs.

**Parameters**

- `struct device *dev`: Device for which the Energy Model has to be updated.

**Description**

This function allows to update easily the EM with new values available in
the OPP framework and DT. It can be used after the chip has been properly
verified by device drivers and the voltages adjusted for the 'chip binning'.

#### <a id="c-em_update_performance_limits"></a>`em_update_performance_limits()`

```c
int em_update_performance_limits(struct em_perf_domain *pd, unsigned long freq_min_khz, unsigned long freq_max_khz)
```

Update Energy Model with performance limits information.

**Parameters**

- `struct em_perf_domain *pd`: Performance Domain with EM that has to be updated.
- `unsigned long freq_min_khz`: New minimum allowed frequency for this device.
- `unsigned long freq_max_khz`: New maximum allowed frequency for this device.

**Description**

This function allows to update the EM with information about available
performance levels. It takes the minimum and maximum frequency in kHz
and does internal translation to performance levels.
Returns 0 on success or -EINVAL when failed.


<a id="rst-examples"></a>

## 3. Examples

<a id="rst-example-driver-with-em-registration"></a>

### 3.1 Example driver with EM registration

The CPUFreq framework supports dedicated callback for registering the EM for a given CPU(s) 'policy' object: cpufreq_driver::register_em(). That callback has to be implemented properly for a given driver, because the framework would call it at the right time during setup. This section provides a simple example of a CPUFreq driver registering a performance domain in the Energy Model framework using the (fake) 'foo' protocol. The driver implements an est_power() function to be provided to the EM framework:



```text
-> drivers/cpufreq/foo_cpufreq.c

01    static int est_power(struct device *dev, unsigned long *mW,
02                    unsigned long *KHz)
03    {
04            long freq, power;
05
06            /* Use the 'foo' protocol to ceil the frequency */
07            freq = foo_get_freq_ceil(dev, *KHz);
08            if (freq < 0)
09                    return freq;
10
11            /* Estimate the power cost for the dev at the relevant freq. */
12            power = foo_estimate_power(dev, freq);
13            if (power < 0)
14                    return power;
15
16            /* Return the values to the EM framework */
17            *mW = power;
18            *KHz = freq;
19
20            return 0;
21    }
22
23    static void foo_cpufreq_register_em(struct cpufreq_policy *policy)
24    {
25            struct em_data_callback em_cb = EM_DATA_CB(est_power);
26            struct device *cpu_dev;
27            int nr_opp;
28
29            cpu_dev = get_cpu_device(cpumask_first(policy->cpus));
30
31            /* Find the number of OPPs for this policy */
32            nr_opp = foo_get_nr_opp(policy);
33
34            /* And register the new performance domain */
35            em_dev_register_perf_domain(cpu_dev, nr_opp, &em_cb, policy->cpus,
36                                        true);
37    }
38
39    static struct cpufreq_driver foo_cpufreq_driver = {
40            .register_em = foo_cpufreq_register_em,
41    };
```

<a id="rst-example-driver-with-em-modification"></a>

### 3.2 Example driver with EM modification

This section provides a simple example of a thermal driver modifying the EM. The driver implements a foo_thermal_em_update() function. The driver is woken up periodically to check the temperature and modify the EM data:



```text
-> drivers/soc/example/example_em_mod.c

01    static void foo_get_new_em(struct foo_context *ctx)
02    {
03            struct em_perf_table __rcu *em_table;
04            struct em_perf_state *table, *new_table;
05            struct device *dev = ctx->dev;
06            struct em_perf_domain *pd;
07            unsigned long freq;
08            int i, ret;
09
10            pd = em_pd_get(dev);
11            if (!pd)
12                    return;
13
14            em_table = em_table_alloc(pd);
15            if (!em_table)
16                    return;
17
18            new_table = em_table->state;
19
20            rcu_read_lock();
21            table = em_perf_state_from_pd(pd);
22            for (i = 0; i < pd->nr_perf_states; i++) {
23                    freq = table[i].frequency;
24                    foo_get_power_perf_values(dev, freq, &new_table[i]);
25            }
26            rcu_read_unlock();
27
28            /* Calculate 'cost' values for EAS */
29            ret = em_dev_compute_costs(dev, new_table, pd->nr_perf_states);
30            if (ret) {
31                    dev_warn(dev, "EM: compute costs failed %d\n", ret);
32                    em_table_free(em_table);
33                    return;
34            }
35
36            ret = em_dev_update_perf_domain(dev, em_table);
37            if (ret) {
38                    dev_warn(dev, "EM: update failed %d\n", ret);
39                    em_table_free(em_table);
40                    return;
41            }
42
43            /*
44             * Since it's one-time-update drop the usage counter.
45             * The EM framework will later free the table when needed.
46             */
47            em_table_free(em_table);
48    }
49
50    /*
51     * Function called periodically to check the temperature and
52     * update the EM if needed
53     */
54    static void foo_thermal_em_update(struct foo_context *ctx)
55    {
56            struct device *dev = ctx->dev;
57            int cpu;
58
59            ctx->temperature = foo_get_temp(dev, ctx);
60            if (ctx->temperature < FOO_EM_UPDATE_TEMP_THRESHOLD)
61                    return;
62
63            foo_get_new_em(ctx);
64    }
```

---

# Freezing of tasks

_Peios Kernel / Internals / Power_

> 2007 Rafael J. Wysocki <rjw@sisk.pl>, GPL

<a id="rst-freezing-of-tasks"></a>

- **(C)** 2007 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, GPL

<a id="rst-i-what-is-the-freezing-of-tasks"></a>

## I. What is the freezing of tasks?

The freezing of tasks is a mechanism by which user space processes and some kernel threads are controlled during hibernation or system-wide suspend (on some architectures).

<a id="rst-ii-how-does-it-work"></a>

## II. How does it work?

There is one per-task flag (PF_NOFREEZE) and three per-task states (TASK_FROZEN, TASK_FREEZABLE and \__TASK_FREEZABLE_UNSAFE) used for that. The tasks that have PF_NOFREEZE unset (all user space tasks and some kernel threads) are regarded as 'freezable' and treated in a special way before the system enters a sleep state as well as before a hibernation image is created (hibernation is directly covered by what follows, but the description applies to system-wide suspend too).

Namely, as the first step of the hibernation procedure the function freeze_processes() (defined in kernel/power/process.c) is called.  A system-wide static key freezer_active (as opposed to a per-task flag or state) is used to indicate whether the system is to undergo a freezing operation. And freeze_processes() sets this static key.  After this, it executes try_to_freeze_tasks() that sends a fake signal to all user space processes, and wakes up all the kernel threads. All freezable tasks must react to that by calling try_to_freeze(), which results in a call to \__refrigerator() (defined in kernel/freezer.c), which changes the task's state to TASK_FROZEN, and makes it loop until it is woken by an explicit TASK_FROZEN wakeup. Then, that task is regarded as 'frozen' and so the set of functions handling this mechanism is referred to as 'the freezer' (these functions are defined in kernel/power/process.c, kernel/freezer.c &amp; include/linux/freezer.h). User space tasks are generally frozen before kernel threads.

\__refrigerator() must not be called directly.  Instead, use the try_to_freeze() function (defined in include/linux/freezer.h), that checks if the task is to be frozen and makes the task enter \__refrigerator().

For user space processes try_to_freeze() is called automatically from the signal-handling code, but the freezable kernel threads need to call it explicitly in suitable places or use the wait_event_freezable() or wait_event_freezable_timeout() macros (defined in include/linux/wait.h) that put the task to sleep (TASK_INTERRUPTIBLE) or freeze it (TASK_FROZEN) if freezer_active is set. The main loop of a freezable kernel thread may look like the following one:



```text
set_freezable();

while (true) {
        struct task_struct *tsk = NULL;

        wait_event_freezable(oom_reaper_wait, oom_reaper_list != NULL);
        spin_lock_irq(&oom_reaper_lock);
        if (oom_reaper_list != NULL) {
                tsk = oom_reaper_list;
                oom_reaper_list = tsk->oom_reaper_list;
        }
        spin_unlock_irq(&oom_reaper_lock);

        if (tsk)
                oom_reap_task(tsk);
}
```

(from mm/oom_kill.c::oom_reaper()).

If a freezable kernel thread is not put to the frozen state after the freezer has initiated a freezing operation, the freezing of tasks will fail and the entire system-wide transition will be cancelled.  For this reason, freezable kernel threads must call try_to_freeze() somewhere or use one of the wait_event_freezable() and wait_event_freezable_timeout() macros.

After the system memory state has been restored from a hibernation image and devices have been reinitialized, the function thaw_processes() is called in order to wake up each frozen task.  Then, the tasks that have been frozen leave \__refrigerator() and continue running.

<a id="rst-rationale-behind-the-functions-dealing-with-freezing-and-thawing-of-tasks"></a>

### Rationale behind the functions dealing with freezing and thawing of tasks

- **freeze_processes():**

  - freezes only userspace tasks

- **freeze_kernel_threads():**

  - freezes all tasks (including kernel threads) because we can't freeze kernel threads without freezing userspace tasks

- **thaw_kernel_threads():**

  - thaws only kernel threads; this is particularly useful if we need to do anything special in between thawing of kernel threads and thawing of userspace tasks, or if we want to postpone the thawing of userspace tasks

- **thaw_processes():**

  - thaws all tasks (including kernel threads) because we can't thaw userspace tasks without thawing kernel threads

<a id="rst-iii-which-kernel-threads-are-freezable"></a>

## III. Which kernel threads are freezable?

Kernel threads are not freezable by default.  However, a kernel thread may clear PF_NOFREEZE for itself by calling set_freezable() (the resetting of PF_NOFREEZE directly is not allowed).  From this point it is regarded as freezable and must call try_to_freeze() or variants of wait_event_freezable() in a suitable place.

<a id="rst-iv-why-do-we-do-that"></a>

## IV. Why do we do that?

Generally speaking, there is a couple of reasons to use the freezing of tasks:

1. The principal reason is to prevent filesystems from being damaged after hibernation.  At the moment we have no simple means of checkpointing filesystems, so if there are any modifications made to filesystem data and/or metadata on disks, we cannot bring them back to the state from before the modifications.  At the same time each hibernation image contains some filesystem-related information that must be consistent with the state of the on-disk data and metadata after the system memory state has been restored from the image (otherwise the filesystems will be damaged in a nasty way, usually making them almost impossible to repair).  We therefore freeze tasks that might cause the on-disk filesystems' data and metadata to be modified after the hibernation image has been created and before the system is finally powered off. The majority of these are user space processes, but if any of the kernel threads may cause something like this to happen, they have to be freezable.

2. Next, to create the hibernation image we need to free a sufficient amount of memory (approximately 50% of available RAM) and we need to do that before devices are deactivated, because we generally need them for swapping out. Then, after the memory for the image has been freed, we don't want tasks to allocate additional memory and we prevent them from doing that by freezing them earlier. \[Of course, this also means that device drivers should not allocate substantial amounts of memory from their .suspend() callbacks before hibernation, but this is a separate issue.\]

3. The third reason is to prevent user space processes and some kernel threads from interfering with the suspending and resuming of devices.  A user space process running on a second CPU while we are suspending devices may, for example, be troublesome and without the freezing of tasks we would need some safeguards against race conditions that might occur in such a case.

Although Linus Torvalds doesn't like the freezing of tasks, he said this in one of the discussions on LKML ([https://lore.kernel.org/r/alpine.LFD.0.98.0704271801020.9964@woody.linux-foundation.org](<https://lore.kernel.org/r/alpine.LFD.0.98.0704271801020.9964@woody.linux-foundation.org>)):

"RJW:&gt; Why we freeze tasks at all or why we freeze kernel threads?

Linus: In many ways, 'at all'.

I **do** realize the IO request queue issues, and that we cannot actually do s2ram with some devices in the middle of a DMA.  So we want to be able to avoid *that*, there's no question about that.  And I suspect that stopping user threads and then waiting for a sync is practically one of the easier ways to do so.

So in practice, the 'at all' may become a 'why freeze kernel threads?' and freezing user threads I don't find really objectionable."

Still, there are kernel threads that may want to be freezable.  For example, if a kernel thread that belongs to a device driver accesses the device directly, it in principle needs to know when the device is suspended, so that it doesn't try to access it at that time.  However, if the kernel thread is freezable, it will be frozen before the driver's .suspend() callback is executed and it will be thawed after the driver's .resume() callback has run, so it won't be accessing the device while it's suspended.

4. Another reason for freezing tasks is to prevent user space processes from realizing that hibernation (or suspend) operation takes place.  Ideally, user space processes should not notice that such a system-wide operation has occurred and should continue running without any problems after the restore (or resume from suspend).  Unfortunately, in the most general case this is quite difficult to achieve without the freezing of tasks.  Consider, for example, a process that depends on all CPUs being online while it's running.  Since we need to disable nonboot CPUs during the hibernation, if this process is not frozen, it may notice that the number of CPUs has changed and may start to work incorrectly because of that.

<a id="rst-v-are-there-any-problems-related-to-the-freezing-of-tasks"></a>

## V. Are there any problems related to the freezing of tasks?

Yes, there are.

First of all, the freezing of kernel threads may be tricky if they depend one on another.  For example, if kernel thread A waits for a completion (in the TASK_UNINTERRUPTIBLE state) that needs to be done by freezable kernel thread B and B is frozen in the meantime, then A will be blocked until B is thawed, which may be undesirable.  That's why kernel threads are not freezable by default.

Second, there are the following two problems related to the freezing of user space processes:

1. Putting processes into an uninterruptible sleep distorts the load average.

2. Now that we have FUSE, plus the framework for doing device drivers in userspace, it gets even more complicated because some userspace processes are now doing the sorts of things that kernel threads do ([https://lists.linux-foundation.org/pipermail/linux-pm/2007-May/012309.html](<https://lists.linux-foundation.org/pipermail/linux-pm/2007-May/012309.html>)).

The problem 1. seems to be fixable, although it hasn't been fixed so far.  The other one is more serious, but it seems that we can work around it by using hibernation (and suspend) notifiers (in that case, though, we won't be able to avoid the realization by the user space processes that the hibernation is taking place).

There are also problems that the freezing of tasks tends to expose, although they are not directly related to it.  For example, if request_firmware() is called from a device driver's .resume() routine, it will timeout and eventually fail, because the user land process that should respond to the request is frozen at this point.  So, seemingly, the failure is due to the freezing of tasks. Suppose, however, that the firmware file is located on a filesystem accessible only through another device that hasn't been resumed yet.  In that case, request_firmware() will fail regardless of whether or not the freezing of tasks is used.  Consequently, the problem is not really related to the freezing of tasks, since it generally exists anyway.

A driver must have all firmwares it may need in RAM before suspend() is called. If keeping them is not practical, for example due to their size, they must be requested early enough using the suspend notifier API described in [Documentation/driver-api/pm/notifiers.rst](/kernel/hardware/driver-api/pm/notifiers.md).

<a id="rst-vi-are-there-any-precautions-to-be-taken-to-prevent-freezing-failures"></a>

## VI. Are there any precautions to be taken to prevent freezing failures?

Yes, there are.

First of all, grabbing the 'system_transition_mutex' lock to mutually exclude a piece of code from system-wide sleep such as suspend/hibernation is not encouraged.  If possible, that piece of code must instead hook onto the suspend/hibernation notifiers to achieve mutual exclusion. Look at the CPU-Hotplug code (kernel/cpu.c) for an example.

However, if that is not feasible, and grabbing 'system_transition_mutex' is deemed necessary, it is strongly discouraged to directly call mutex\_\[un\]lock(&amp;system_transition_mutex) since that could lead to freezing failures, because if the suspend/hibernate code successfully acquired the 'system_transition_mutex' lock, and hence that other entity failed to acquire the lock, then that task would get blocked in TASK_UNINTERRUPTIBLE state. As a consequence, the freezer would not be able to freeze that task, leading to freezing failure.

However, the \[un\]lock_system_sleep() APIs are safe to use in this scenario, since they ask the freezer to skip freezing this task, since it is anyway "frozen enough" as it is blocked on 'system_transition_mutex', which will be released only after the entire suspend/hibernation sequence is complete.  So, to summarize, use \[un\]lock_system_sleep() instead of directly using mutex\_\[un\]lock(&amp;system_transition_mutex). That would prevent freezing failures.

<a id="rst-v-miscellaneous"></a>

## V. Miscellaneous

/sys/power/pm_freeze_timeout controls how long it will cost at most to freeze all user space processes or all freezable kernel threads, in unit of millisecond.  The default value is 20000, with range of unsigned integer.

---

# Operating Performance Points (OPP) Library

_Peios Kernel / Internals / Power_

> 2009-2010 Nishanth Menon <nm@ti.com>, Texas Instruments Incorporated

<a id="rst-operating-performance-points-opp-library"></a>

- **(C)** 2009-2010 Nishanth Menon &lt;[nm@ti.com](<mailto:nm@ti.com>)&gt;, Texas Instruments Incorporated

<!-- Contents

1. Introduction
2. Initial OPP List Registration
3. OPP Search Functions
4. OPP Availability Control Functions
5. OPP Data Retrieval Functions
6. Data Structures -->

<a id="rst-introduction"></a>

## 1. Introduction

<a id="rst-what-is-an-operating-performance-point-opp"></a>

### 1.1 What is an Operating Performance Point (OPP)?

Complex SoCs of today consists of a multiple sub-modules working in conjunction. In an operational system executing varied use cases, not all modules in the SoC need to function at their highest performing frequency all the time. To facilitate this, sub-modules in a SoC are grouped into domains, allowing some domains to run at lower voltage and frequency while other domains run at voltage/frequency pairs that are higher.

The set of discrete tuples consisting of frequency and voltage pairs that the device will support per domain are called Operating Performance Points or OPPs.

As an example:

Let us consider an MPU device which supports the following: \{300MHz at minimum voltage of 1V\}, \{800MHz at minimum voltage of 1.2V\}, \{1GHz at minimum voltage of 1.3V\}

We can represent these as three OPPs as the following \{Hz, uV\} tuples:

- \{300000000, 1000000\}

- \{800000000, 1200000\}

- \{1000000000, 1300000\}

<a id="rst-operating-performance-points-library"></a>

### 1.2 Operating Performance Points Library

OPP library provides a set of helper functions to organize and query the OPP information. The library is located in drivers/opp/ directory and the header is located in include/linux/pm_opp.h. OPP library can be enabled by enabling CONFIG_PM_OPP from power management menuconfig menu. Certain SoCs such as Texas Instrument's OMAP framework allows to optionally boot at a certain OPP without needing cpufreq.

Typical usage of the OPP library is as follows:



```text
(users)        -> registers a set of default OPPs              -> (library)
SoC framework  -> modifies on required cases certain OPPs      -> OPP layer
               -> queries to search/retrieve information       ->
```

OPP layer expects each domain to be represented by a unique device pointer. SoC framework registers a set of initial OPPs per device with the OPP layer. This list is expected to be an optimally small number typically around 5 per device. This initial list contains a set of OPPs that the framework expects to be safely enabled by default in the system.

<a id="rst-note-on-opp-availability"></a>

#### Note on OPP Availability

As the system proceeds to operate, SoC framework may choose to make certain OPPs available or not available on each device based on various external factors. Example usage: Thermal management or other exceptional situations where SoC framework might choose to disable a higher frequency OPP to safely continue operations until that OPP could be re-enabled if possible.

OPP library facilitates this concept in its implementation. The following operational functions operate only on available opps: dev_pm_opp_find_freq\_\{ceil, floor\}, dev_pm_opp_get_voltage, dev_pm_opp_get_freq, dev_pm_opp_get_opp_count.

dev_pm_opp_find_freq_exact is meant to be used to find the opp pointer which can then be used for dev_pm_opp_enable/disable functions to make an opp available as required.

WARNING: Users of OPP library should refresh their availability count using get_opp_count if dev_pm_opp_enable/disable functions are invoked for a device, the exact mechanism to trigger these or the notification mechanism to other dependent subsystems such as cpufreq are left to the discretion of the SoC specific framework which uses the OPP library. Similar care needs to be taken care to refresh the cpufreq table in cases of these operations.

<a id="rst-initial-opp-list-registration"></a>

## 2. Initial OPP List Registration

The SoC implementation calls dev_pm_opp_add function iteratively to add OPPs per device. It is expected that the SoC framework will register the OPP entries optimally- typical numbers range to be less than 5. The list generated by registering the OPPs is maintained by OPP library throughout the device operation. The SoC framework can subsequently control the availability of the OPPs dynamically using the dev_pm_opp_enable / disable functions.

- **dev_pm_opp_add**

  Add a new OPP for a specific domain represented by the device pointer. The OPP is defined using the frequency and voltage. Once added, the OPP is assumed to be available and control of its availability can be done with the dev_pm_opp_enable/disable functions. OPP library internally stores and manages this information in the dev_pm_opp struct. This function may be used by SoC framework to define a optimal list as per the demands of SoC usage environment.

  - **WARNING:**

    Do not use this function in interrupt context.

  Example:



  ```text
  soc_pm_init()
  {
         /* Do things */
         r = dev_pm_opp_add(mpu_dev, 1000000, 900000);
         if (!r) {
                 pr_err("%s: unable to register mpu opp(%d)\n", r);
                 goto no_cpufreq;
         }
         /* Do cpufreq things */
  no_cpufreq:
         /* Do remaining things */
  }
  ```

<a id="rst-opp-search-functions"></a>

## 3. OPP Search Functions

High level framework such as cpufreq operates on frequencies. To map the frequency back to the corresponding OPP, OPP library provides handy functions to search the OPP list that OPP library internally manages. These search functions return the matching pointer representing the opp if a match is found, else returns error. These errors are expected to be handled by standard error checks such as IS_ERR() and appropriate actions taken by the caller.

Callers of these functions shall call dev_pm_opp_put() after they have used the OPP. Otherwise the memory for the OPP will never get freed and result in memleak.

- **dev_pm_opp_find_freq_exact**

  Search for an OPP based on an *exact* frequency and availability. This function is especially useful to enable an OPP which is not available by default. Example: In a case when SoC framework detects a situation where a higher frequency could be made available, it can use this function to find the OPP prior to call the dev_pm_opp_enable to actually make it available:



  ```text
  opp = dev_pm_opp_find_freq_exact(dev, 1000000000, false);
  dev_pm_opp_put(opp);
  /* dont operate on the pointer.. just do a sanity check.. */
  if (IS_ERR(opp)) {
         pr_err("frequency not disabled!\n");
         /* trigger appropriate actions.. */
  } else {
         dev_pm_opp_enable(dev,1000000000);
  }
  ```

  - **NOTE:**

    This is the only search function that operates on OPPs which are not available.

- **dev_pm_opp_find_freq_floor**

  Search for an available OPP which is *at most* the provided frequency. This function is useful while searching for a lesser match OR operating on OPP information in the order of decreasing frequency. Example: To find the highest opp for a device:



  ```text
  freq = ULONG_MAX;
  opp = dev_pm_opp_find_freq_floor(dev, &freq);
  dev_pm_opp_put(opp);
  ```

- **dev_pm_opp_find_freq_ceil**

  Search for an available OPP which is *at least* the provided frequency. This function is useful while searching for a higher match OR operating on OPP information in the order of increasing frequency. Example 1: To find the lowest opp for a device:



  ```text
  freq = 0;
  opp = dev_pm_opp_find_freq_ceil(dev, &freq);
  dev_pm_opp_put(opp);
  ```

  Example 2: A simplified implementation of a SoC cpufreq_driver-&gt;target:



  ```text
  soc_cpufreq_target(..)
  {
         /* Do stuff like policy checks etc. */
         /* Find the best frequency match for the req */
         opp = dev_pm_opp_find_freq_ceil(dev, &freq);
         dev_pm_opp_put(opp);
         if (!IS_ERR(opp))
                 soc_switch_to_freq_voltage(freq);
         else
                 /* do something when we can't satisfy the req */
         /* do other stuff */
  }
  ```

<a id="rst-opp-availability-control-functions"></a>

## 4. OPP Availability Control Functions

A default OPP list registered with the OPP library may not cater to all possible situation. The OPP library provides a set of functions to modify the availability of a OPP within the OPP list. This allows SoC frameworks to have fine grained dynamic control of which sets of OPPs are operationally available. These functions are intended to *temporarily* remove an OPP in conditions such as thermal considerations (e.g. don't use OPPx until the temperature drops).

- **WARNING:**

  Do not use these functions in interrupt context.

- **dev_pm_opp_enable**

  Make a OPP available for operation. Example: Lets say that 1GHz OPP is to be made available only if the SoC temperature is lower than a certain threshold. The SoC framework implementation might choose to do something as follows:



  ```text
  if (cur_temp < temp_low_thresh) {
         /* Enable 1GHz if it was disabled */
         opp = dev_pm_opp_find_freq_exact(dev, 1000000000, false);
         dev_pm_opp_put(opp);
         /* just error check */
         if (!IS_ERR(opp))
                 ret = dev_pm_opp_enable(dev, 1000000000);
         else
                 goto try_something_else;
  }
  ```

- **dev_pm_opp_disable**

  Make an OPP to be not available for operation Example: Lets say that 1GHz OPP is to be disabled if the temperature exceeds a threshold value. The SoC framework implementation might choose to do something as follows:



  ```text
  if (cur_temp > temp_high_thresh) {
         /* Disable 1GHz if it was enabled */
         opp = dev_pm_opp_find_freq_exact(dev, 1000000000, true);
         dev_pm_opp_put(opp);
         /* just error check */
         if (!IS_ERR(opp))
                 ret = dev_pm_opp_disable(dev, 1000000000);
         else
                 goto try_something_else;
  }
  ```

<a id="rst-opp-data-retrieval-functions"></a>

## 5. OPP Data Retrieval Functions

Since OPP library abstracts away the OPP information, a set of functions to pull information from the dev_pm_opp structure is necessary. Once an OPP pointer is retrieved using the search functions, the following functions can be used by SoC framework to retrieve the information represented inside the OPP layer.

- **dev_pm_opp_get_voltage**

  Retrieve the voltage represented by the opp pointer. Example: At a cpufreq transition to a different frequency, SoC framework requires to set the voltage represented by the OPP using the regulator framework to the Power Management chip providing the voltage:



  ```text
  soc_switch_to_freq_voltage(freq)
  {
         /* do things */
         opp = dev_pm_opp_find_freq_ceil(dev, &freq);
         v = dev_pm_opp_get_voltage(opp);
         dev_pm_opp_put(opp);
         if (v)
                 regulator_set_voltage(.., v);
         /* do other things */
  }
  ```

- **dev_pm_opp_get_freq**

  Retrieve the freq represented by the opp pointer. Example: Lets say the SoC framework uses a couple of helper functions we could pass opp pointers instead of doing additional parameters to handle quiet a bit of data parameters:



  ```text
  soc_cpufreq_target(..)
  {
         /* do things.. */
          max_freq = ULONG_MAX;
          max_opp = dev_pm_opp_find_freq_floor(dev,&max_freq);
          requested_opp = dev_pm_opp_find_freq_ceil(dev,&freq);
          if (!IS_ERR(max_opp) && !IS_ERR(requested_opp))
                 r = soc_test_validity(max_opp, requested_opp);
          dev_pm_opp_put(max_opp);
          dev_pm_opp_put(requested_opp);
         /* do other things */
  }
  soc_test_validity(..)
  {
          if(dev_pm_opp_get_voltage(max_opp) < dev_pm_opp_get_voltage(requested_opp))
                  return -EINVAL;
          if(dev_pm_opp_get_freq(max_opp) < dev_pm_opp_get_freq(requested_opp))
                  return -EINVAL;
         /* do things.. */
  }
  ```

- **dev_pm_opp_get_opp_count**

  Retrieve the number of available opps for a device Example: Lets say a co-processor in the SoC needs to know the available frequencies in a table, the main processor can notify as following:



  ```text
  soc_notify_coproc_available_frequencies()
  {
         /* Do things */
         num_available = dev_pm_opp_get_opp_count(dev);
         speeds = kcalloc(num_available, sizeof(u32), GFP_KERNEL);
         /* populate the table in increasing order */
         freq = 0;
         while (!IS_ERR(opp = dev_pm_opp_find_freq_ceil(dev, &freq))) {
                 speeds[i] = freq;
                 freq++;
                 i++;
                 dev_pm_opp_put(opp);
         }

         soc_notify_coproc(AVAILABLE_FREQs, speeds, num_available);
         /* Do other things */
  }
  ```

<a id="rst-data-structures"></a>

## 6. Data Structures

Typically an SoC contains multiple voltage domains which are variable. Each domain is represented by a device pointer. The relationship to OPP can be represented as follows:



```text
SoC
 |- device 1
 |    |- opp 1 (availability, freq, voltage)
 |    |- opp 2 ..
 ...  ...
 |    `- opp n ..
 |- device 2
 ...
 `- device m
```

OPP library maintains a internal list that the SoC framework populates and accessed by various functions as described above. However, the structures representing the actual OPPs and domains are internal to the OPP library itself to allow for suitable abstraction reusable across systems.

- **struct dev_pm_opp**

  The internal data structure of OPP library which is used to represent an OPP. In addition to the freq, voltage, availability information, it also contains internal book keeping information required for the OPP library to operate on.  Pointer to this structure is provided back to the users such as SoC framework to be used as a identifier for OPP in the interactions with OPP layer.

  - **WARNING:**

    The struct dev_pm_opp pointer should not be parsed or modified by the users. The defaults of for an instance is populated by dev_pm_opp_add, but the availability of the OPP can be modified by dev_pm_opp_enable/disable functions.

- **struct device**

  This is used to identify a domain to the OPP layer. The nature of the device and its implementation is left to the user of OPP library such as the SoC framework.

Overall, in a simplistic view, the data structure operations is represented as following:



```text
Initialization / modification:
            +-----+        /- dev_pm_opp_enable
dev_pm_opp_add --> | opp | <-------
  |         +-----+        \- dev_pm_opp_disable
  \-------> domain_info(device)

Search functions:
             /-- dev_pm_opp_find_freq_ceil  ---\   +-----+
domain_info<---- dev_pm_opp_find_freq_exact -----> | opp |
             \-- dev_pm_opp_find_freq_floor ---/   +-----+

Retrieval functions:
+-----+     /- dev_pm_opp_get_voltage
| opp | <---
+-----+     \- dev_pm_opp_get_freq

domain_info <- dev_pm_opp_get_opp_count
```

---

# PCI Power Management

_Peios Kernel / Internals / Power_

> Copyright (c) 2010 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.

<a id="rst-pci-power-management"></a>

Copyright (c) 2010 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, Novell Inc.

An overview of concepts and the Linux kernel's interfaces related to PCI power management.  Based on previous work by Patrick Mochel &lt;[mochel@transmeta.com](<mailto:mochel@transmeta.com>)&gt; (and others).

This document only covers the aspects of power management specific to PCI devices.  For general description of the kernel's interfaces related to device power management refer to [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md) and [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md).

<!-- contents:

1. Hardware and Platform Support for PCI Power Management
2. PCI Subsystem and Device Power Management
3. PCI Device Drivers and Power Management
4. Resources -->

<a id="rst-hardware-and-platform-support-for-pci-power-management"></a>

## 1. Hardware and Platform Support for PCI Power Management

<a id="rst-native-and-platform-based-power-management"></a>

### 1.1. Native and Platform-Based Power Management

In general, power management is a feature allowing one to save energy by putting devices into states in which they draw less power (low-power states) at the price of reduced functionality or performance.

Usually, a device is put into a low-power state when it is underutilized or completely inactive.  However, when it is necessary to use the device once again, it has to be put back into the "fully functional" state (full-power state).  This may happen when there are some data for the device to handle or as a result of an external event requiring the device to be active, which may be signaled by the device itself.

PCI devices may be put into low-power states in two ways, by using the device capabilities introduced by the PCI Bus Power Management Interface Specification, or with the help of platform firmware, such as an ACPI BIOS.  In the first approach, that is referred to as the native PCI power management (native PCI PM) in what follows, the device power state is changed as a result of writing a specific value into one of its standard configuration registers.  The second approach requires the platform firmware to provide special methods that may be used by the kernel to change the device's power state.

Devices supporting the native PCI PM usually can generate wakeup signals called Power Management Events (PMEs) to let the kernel know about external events requiring the device to be active.  After receiving a PME the kernel is supposed to put the device that sent it into the full-power state.  However, the PCI Bus Power Management Interface Specification doesn't define any standard method of delivering the PME from the device to the CPU and the operating system kernel. It is assumed that the platform firmware will perform this task and therefore, even though a PCI device is set up to generate PMEs, it also may be necessary to prepare the platform firmware for notifying the CPU of the PMEs coming from the device (e.g. by generating interrupts).

In turn, if the methods provided by the platform firmware are used for changing the power state of a device, usually the platform also provides a method for preparing the device to generate wakeup signals.  In that case, however, it often also is necessary to prepare the device for generating PMEs using the native PCI PM mechanism, because the method provided by the platform depends on that.

Thus in many situations both the native and the platform-based power management mechanisms have to be used simultaneously to obtain the desired result.

<a id="rst-native-pci-power-management"></a>

### 1.2. Native PCI Power Management

The PCI Bus Power Management Interface Specification (PCI PM Spec) was introduced between the PCI 2.1 and PCI 2.2 Specifications.  It defined a standard interface for performing various operations related to power management.

The implementation of the PCI PM Spec is optional for conventional PCI devices, but it is mandatory for PCI Express devices.  If a device supports the PCI PM Spec, it has an 8 byte power management capability field in its PCI configuration space.  This field is used to describe and control the standard features related to the native PCI power management.

The PCI PM Spec defines 4 operating states for devices (D0-D3) and for buses (B0-B3).  The higher the number, the less power is drawn by the device or bus in that state.  However, the higher the number, the longer the latency for the device or bus to return to the full-power state (D0 or B0, respectively).

There are two variants of the D3 state defined by the specification.  The first one is D3hot, referred to as the software accessible D3, because devices can be programmed to go into it.  The second one, D3cold, is the state that PCI devices are in when the supply voltage (Vcc) is removed from them.  It is not possible to program a PCI device to go into D3cold, although there may be a programmable interface for putting the bus the device is on into a state in which Vcc is removed from all devices on the bus.

PCI bus power management, however, is not supported by the Linux kernel at the time of this writing and therefore it is not covered by this document.

Note that every PCI device can be in the full-power state (D0) or in D3cold, regardless of whether or not it implements the PCI PM Spec.  In addition to that, if the PCI PM Spec is implemented by the device, it must support D3hot as well as D0.  The support for the D1 and D2 power states is optional.

PCI devices supporting the PCI PM Spec can be programmed to go to any of the supported low-power states (except for D3cold).  While in D1-D3hot the standard configuration registers of the device must be accessible to software (i.e. the device is required to respond to PCI configuration accesses), although its I/O and memory spaces are then disabled.  This allows the device to be programmatically put into D0.  Thus the kernel can switch the device back and forth between D0 and the supported low-power states (except for D3cold) and the possible power state transitions the device can undergo are the following:


<table>
<tbody>
<tr>
<td>


Current State \| New State

</td>
</tr>
<tr>
<td>


D0            \| D1, D2, D3

</td>
</tr>
<tr>
<td>


D1            \| D2, D3

</td>
</tr>
<tr>
<td>


D2            \| D3

</td>
</tr>
<tr>
<td>


D1, D2, D3    \| D0

</td>
</tr>
</tbody>
</table>

The transition from D3cold to D0 occurs when the supply voltage is provided to the device (i.e. power is restored).  In that case the device returns to D0 with a full power-on reset sequence and the power-on defaults are restored to the device by hardware just as at initial power up.

PCI devices supporting the PCI PM Spec can be programmed to generate PMEs while in any power state (D0-D3), but they are not required to be capable of generating PMEs from all supported power states.  In particular, the capability of generating PMEs from D3cold is optional and depends on the presence of additional voltage (3.3Vaux) allowing the device to remain sufficiently active to generate a wakeup signal.

<a id="rst-acpi-device-power-management"></a>

### 1.3. ACPI Device Power Management

The platform firmware support for the power management of PCI devices is system-specific.  However, if the system in question is compliant with the Advanced Configuration and Power Interface (ACPI) Specification, like the majority of x86-based systems, it is supposed to implement device power management interfaces defined by the ACPI standard.

For this purpose the ACPI BIOS provides special functions called "control methods" that may be executed by the kernel to perform specific tasks, such as putting a device into a low-power state.  These control methods are encoded using special byte-code language called the ACPI Machine Language (AML) and stored in the machine's BIOS.  The kernel loads them from the BIOS and executes them as needed using an AML interpreter that translates the AML byte code into computations and memory or I/O space accesses.  This way, in theory, a BIOS writer can provide the kernel with a means to perform actions depending on the system design in a system-specific fashion.

ACPI control methods may be divided into global control methods, that are not associated with any particular devices, and device control methods, that have to be defined separately for each device supposed to be handled with the help of the platform.  This means, in particular, that ACPI device control methods can only be used to handle devices that the BIOS writer knew about in advance.  The ACPI methods used for device power management fall into that category.

The ACPI specification assumes that devices can be in one of four power states labeled as D0, D1, D2, and D3 that roughly correspond to the native PCI PM D0-D3 states (although the difference between D3hot and D3cold is not taken into account by ACPI).  Moreover, for each power state of a device there is a set of power resources that have to be enabled for the device to be put into that state.  These power resources are controlled (i.e. enabled or disabled) with the help of their own control methods, \_ON and \_OFF, that have to be defined individually for each of them.

To put a device into the ACPI power state Dx (where x is a number between 0 and 3 inclusive) the kernel is supposed to (1) enable the power resources required by the device in this state using their \_ON control methods and (2) execute the \_PSx control method defined for the device.  In addition to that, if the device is going to be put into a low-power state (D1-D3) and is supposed to generate wakeup signals from that state, the \_DSW (or \_PSW, replaced with \_DSW by ACPI 3.0) control method defined for it has to be executed before \_PSx.  Power resources that are not required by the device in the target power state and are not required any more by any other device should be disabled (by executing their \_OFF control methods).  If the current power state of the device is D3, it can only be put into D0 this way.

However, quite often the power states of devices are changed during a system-wide transition into a sleep state or back into the working state.  ACPI defines four system sleep states, S1, S2, S3, and S4, and denotes the system working state as S0.  In general, the target system sleep (or working) state determines the highest power (lowest number) state the device can be put into and the kernel is supposed to obtain this information by executing the device's \_SxD control method (where x is a number between 0 and 4 inclusive). If the device is required to wake up the system from the target sleep state, the lowest power (highest number) state it can be put into is also determined by the target state of the system.  The kernel is then supposed to use the device's \_SxW control method to obtain the number of that state.  It also is supposed to use the device's \_PRW control method to learn which power resources need to be enabled for the device to be able to generate wakeup signals.

<a id="rst-wakeup-signaling"></a>

### 1.4. Wakeup Signaling

Wakeup signals generated by PCI devices, either as native PCI PMEs, or as a result of the execution of the \_DSW (or \_PSW) ACPI control method before putting the device into a low-power state, have to be caught and handled as appropriate.  If they are sent while the system is in the working state (ACPI S0), they should be translated into interrupts so that the kernel can put the devices generating them into the full-power state and take care of the events that triggered them.  In turn, if they are sent while the system is sleeping, they should cause the system's core logic to trigger wakeup.

On ACPI-based systems wakeup signals sent by conventional PCI devices are converted into ACPI General-Purpose Events (GPEs) which are hardware signals from the system core logic generated in response to various events that need to be acted upon.  Every GPE is associated with one or more sources of potentially interesting events.  In particular, a GPE may be associated with a PCI device capable of signaling wakeup.  The information on the connections between GPEs and event sources is recorded in the system's ACPI BIOS from where it can be read by the kernel.

If a PCI device known to the system's ACPI BIOS signals wakeup, the GPE associated with it (if there is one) is triggered.  The GPEs associated with PCI bridges may also be triggered in response to a wakeup signal from one of the devices below the bridge (this also is the case for root bridges) and, for example, native PCI PMEs from devices unknown to the system's ACPI BIOS may be handled this way.

A GPE may be triggered when the system is sleeping (i.e. when it is in one of the ACPI S1-S4 states), in which case system wakeup is started by its core logic (the device that was the source of the signal causing the system wakeup to occur may be identified later).  The GPEs used in such situations are referred to as wakeup GPEs.

Usually, however, GPEs are also triggered when the system is in the working state (ACPI S0) and in that case the system's core logic generates a System Control Interrupt (SCI) to notify the kernel of the event.  Then, the SCI handler identifies the GPE that caused the interrupt to be generated which, in turn, allows the kernel to identify the source of the event (that may be a PCI device signaling wakeup).  The GPEs used for notifying the kernel of events occurring while the system is in the working state are referred to as runtime GPEs.

Unfortunately, there is no standard way of handling wakeup signals sent by conventional PCI devices on systems that are not ACPI-based, but there is one for PCI Express devices.  Namely, the PCI Express Base Specification introduced a native mechanism for converting native PCI PMEs into interrupts generated by root ports.  For conventional PCI devices native PMEs are out-of-band, so they are routed separately and they need not pass through bridges (in principle they may be routed directly to the system's core logic), but for PCI Express devices they are in-band messages that have to pass through the PCI Express hierarchy, including the root port on the path from the device to the Root Complex.  Thus it was possible to introduce a mechanism by which a root port generates an interrupt whenever it receives a PME message from one of the devices below it. The PCI Express Requester ID of the device that sent the PME message is then recorded in one of the root port's configuration registers from where it may be read by the interrupt handler allowing the device to be identified.  \[PME messages sent by PCI Express endpoints integrated with the Root Complex don't pass through root ports, but instead they cause a Root Complex Event Collector (if there is one) to generate interrupts.\]

In principle the native PCI Express PME signaling may also be used on ACPI-based systems along with the GPEs, but to use it the kernel has to ask the system's ACPI BIOS to release control of root port configuration registers.  The ACPI BIOS, however, is not required to allow the kernel to control these registers and if it doesn't do that, the kernel must not modify their contents.  Of course the native PCI Express PME signaling cannot be used by the kernel in that case.

<a id="rst-pci-subsystem-and-device-power-management"></a>

## 2. PCI Subsystem and Device Power Management

<a id="rst-device-power-management-callbacks"></a>

### 2.1. Device Power Management Callbacks

The PCI Subsystem participates in the power management of PCI devices in a number of ways.  First of all, it provides an intermediate code layer between the device power management core (PM core) and PCI device drivers. Specifically, the pm field of the PCI subsystem's struct bus_type object, pci_bus_type, points to a struct dev_pm_ops object, pci_dev_pm_ops, containing pointers to several device power management callbacks:



```text
const struct dev_pm_ops pci_dev_pm_ops = {
      .prepare = pci_pm_prepare,
      .complete = pci_pm_complete,
      .suspend = pci_pm_suspend,
      .resume = pci_pm_resume,
      .freeze = pci_pm_freeze,
      .thaw = pci_pm_thaw,
      .poweroff = pci_pm_poweroff,
      .restore = pci_pm_restore,
      .suspend_noirq = pci_pm_suspend_noirq,
      .resume_noirq = pci_pm_resume_noirq,
      .freeze_noirq = pci_pm_freeze_noirq,
      .thaw_noirq = pci_pm_thaw_noirq,
      .poweroff_noirq = pci_pm_poweroff_noirq,
      .restore_noirq = pci_pm_restore_noirq,
      .runtime_suspend = pci_pm_runtime_suspend,
      .runtime_resume = pci_pm_runtime_resume,
      .runtime_idle = pci_pm_runtime_idle,
};
```

These callbacks are executed by the PM core in various situations related to device power management and they, in turn, execute power management callbacks provided by PCI device drivers.  They also perform power management operations involving some standard configuration registers of PCI devices that device drivers need not know or care about.

The structure representing a PCI device, struct pci_dev, contains several fields that these callbacks operate on:



```text
struct pci_dev {
      ...
      pci_power_t     current_state;  /* Current operating state. */
      int             pm_cap;         /* PM capability offset in the
                                         configuration space */
      unsigned int    pme_support:5;  /* Bitmask of states from which PME#
                                         can be generated */
      unsigned int    pme_poll:1;     /* Poll device's PME status bit */
      unsigned int    d1_support:1;   /* Low power state D1 is supported */
      unsigned int    d2_support:1;   /* Low power state D2 is supported */
      unsigned int    no_d1d2:1;      /* D1 and D2 are forbidden */
      unsigned int    wakeup_prepared:1;  /* Device prepared for wake up */
      unsigned int    d3hot_delay;    /* D3hot->D0 transition time in ms */
      ...
};
```

They also indirectly use some fields of the struct device that is embedded in struct pci_dev.

<a id="rst-device-initialization"></a>

### 2.2. Device Initialization

The PCI subsystem's first task related to device power management is to prepare the device for power management and initialize the fields of struct pci_dev used for this purpose.  This happens in two functions defined in drivers/pci/, pci_pm_init() and pci_acpi_setup().

The first of these functions checks if the device supports native PCI PM and if that's the case the offset of its power management capability structure in the configuration space is stored in the pm_cap field of the device's struct pci_dev object.  Next, the function checks which PCI low-power states are supported by the device and from which low-power states the device can generate native PCI PMEs.  The power management fields of the device's struct pci_dev and the struct device embedded in it are updated accordingly and the generation of PMEs by the device is disabled.

The second function checks if the device can be prepared to signal wakeup with the help of the platform firmware, such as the ACPI BIOS.  If that is the case, the function updates the wakeup fields in struct device embedded in the device's struct pci_dev and uses the firmware-provided method to prevent the device from signaling wakeup.

At this point the device is ready for power management.  For driverless devices, however, this functionality is limited to a few basic operations carried out during system-wide transitions to a sleep state and back to the working state.

<a id="rst-runtime-device-power-management"></a>

### 2.3. Runtime Device Power Management

The PCI subsystem plays a vital role in the runtime power management of PCI devices.  For this purpose it uses the general runtime power management (runtime PM) framework described in [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md). Namely, it provides subsystem-level callbacks:



```text
pci_pm_runtime_suspend()
pci_pm_runtime_resume()
pci_pm_runtime_idle()
```

that are executed by the core runtime PM routines.  It also implements the entire mechanics necessary for handling runtime wakeup signals from PCI devices in low-power states, which at the time of this writing works for both the native PCI Express PME signaling and the ACPI GPE-based wakeup signaling described in Section 1.

First, a PCI device is put into a low-power state, or suspended, with the help of pm_schedule_suspend() or pm_runtime_suspend() which for PCI devices call pci_pm_runtime_suspend() to do the actual job.  For this to work, the device's driver has to provide a pm-&gt;runtime_suspend() callback (see below), which is run by pci_pm_runtime_suspend() as the first action.  If the driver's callback returns successfully, the device's standard configuration registers are saved, the device is prepared to generate wakeup signals and, finally, it is put into the target low-power state.

The low-power state to put the device into is the lowest-power (highest number) state from which it can signal wakeup.  The exact method of signaling wakeup is system-dependent and is determined by the PCI subsystem on the basis of the reported capabilities of the device and the platform firmware.  To prepare the device for signaling wakeup and put it into the selected low-power state, the PCI subsystem can use the platform firmware as well as the device's native PCI PM capabilities, if supported.

It is expected that the device driver's pm-&gt;runtime_suspend() callback will not attempt to prepare the device for signaling wakeup or to put it into a low-power state.  The driver ought to leave these tasks to the PCI subsystem that has all of the information necessary to perform them.

A suspended device is brought back into the "active" state, or resumed, with the help of pm_request_resume() or pm_runtime_resume() which both call pci_pm_runtime_resume() for PCI devices.  Again, this only works if the device's driver provides a pm-&gt;runtime_resume() callback (see below).  However, before the driver's callback is executed, pci_pm_runtime_resume() brings the device back into the full-power state, prevents it from signaling wakeup while in that state and restores its standard configuration registers.  Thus the driver's callback need not worry about the PCI-specific aspects of the device resume.

Note that generally pci_pm_runtime_resume() may be called in two different situations.  First, it may be called at the request of the device's driver, for example if there are some data for it to process.  Second, it may be called as a result of a wakeup signal from the device itself (this sometimes is referred to as "remote wakeup").  Of course, for this purpose the wakeup signal is handled in one of the ways described in Section 1 and finally converted into a notification for the PCI subsystem after the source device has been identified.

The pci_pm_runtime_idle() function, called for PCI devices by pm_runtime_idle() and pm_request_idle(), executes the device driver's pm-&gt;runtime_idle() callback, if defined, and if that callback doesn't return error code (or is not present at all), suspends the device with the help of pm_runtime_suspend(). Sometimes pci_pm_runtime_idle() is called automatically by the PM core (for example, it is called right after the device has just been resumed), in which cases it is expected to suspend the device if that makes sense.  Usually, however, the PCI subsystem doesn't really know if the device really can be suspended, so it lets the device's driver decide by running its pm-&gt;runtime_idle() callback.

<a id="rst-system-wide-power-transitions"></a>

### 2.4. System-Wide Power Transitions

There are a few different types of system-wide power transitions, described in [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md).  Each of them requires devices to be handled in a specific way and the PM core executes subsystem-level power management callbacks for this purpose.  They are executed in phases such that each phase involves executing the same subsystem-level callback for every device belonging to the given subsystem before the next phase begins.  These phases always run after tasks have been frozen.

<a id="rst-system-suspend"></a>

#### 2.4.1. System Suspend

When the system is going into a sleep state in which the contents of memory will be preserved, such as one of the ACPI sleep states S1-S3, the phases are:

> prepare, suspend, suspend_noirq.

The following PCI bus type's callbacks, respectively, are used in these phases:



```text
pci_pm_prepare()
pci_pm_suspend()
pci_pm_suspend_noirq()
```

The pci_pm_prepare() routine first puts the device into the "fully functional" state with the help of pm_runtime_resume().  Then, it executes the device driver's pm-&gt;prepare() callback if defined (i.e. if the driver's struct dev_pm_ops object is present and the prepare pointer in that object is valid).

The pci_pm_suspend() routine first checks if the device's driver implements legacy PCI suspend routines (see Section 3), in which case the driver's legacy suspend callback is executed, if present, and its result is returned.  Next, if the device's driver doesn't provide a struct dev_pm_ops object (containing pointers to the driver's callbacks), pci_pm_default_suspend() is called, which simply turns off the device's bus master capability and runs pcibios_disable_device() to disable it, unless the device is a bridge (PCI bridges are ignored by this routine).  Next, the device driver's pm-&gt;suspend() callback is executed, if defined, and its result is returned if it fails. Finally, pci_fixup_device() is called to apply hardware suspend quirks related to the device if necessary.

Note that the suspend phase is carried out asynchronously for PCI devices, so the pci_pm_suspend() callback may be executed in parallel for any pair of PCI devices that don't depend on each other in a known way (i.e. none of the paths in the device tree from the root bridge to a leaf device contains both of them).

The pci_pm_suspend_noirq() routine is executed after suspend_device_irqs() has been called, which means that the device driver's interrupt handler won't be invoked while this routine is running.  It first checks if the device's driver implements legacy PCI suspend routines (Section 3), in which case the legacy late suspend routine is called and its result is returned (the standard configuration registers of the device are saved if the driver's callback hasn't done that).  Second, if the device driver's struct dev_pm_ops object is not present, the device's standard configuration registers are saved and the routine returns success.  Otherwise the device driver's pm-&gt;suspend_noirq() callback is executed, if present, and its result is returned if it fails.  Next, if the device's standard configuration registers haven't been saved yet (one of the device driver's callbacks executed before might do that), pci_pm_suspend_noirq() saves them, prepares the device to signal wakeup (if necessary) and puts it into a low-power state.

The low-power state to put the device into is the lowest-power (highest number) state from which it can signal wakeup while the system is in the target sleep state.  Just like in the runtime PM case described above, the mechanism of signaling wakeup is system-dependent and determined by the PCI subsystem, which is also responsible for preparing the device to signal wakeup from the system's target sleep state as appropriate.

PCI device drivers (that don't implement legacy power management callbacks) are generally not expected to prepare devices for signaling wakeup or to put them into low-power states.  However, if one of the driver's suspend callbacks (pm-&gt;suspend() or pm-&gt;suspend_noirq()) saves the device's standard configuration registers, pci_pm_suspend_noirq() will assume that the device has been prepared to signal wakeup and put into a low-power state by the driver (the driver is then assumed to have used the helper functions provided by the PCI subsystem for this purpose).  PCI device drivers are not encouraged to do that, but in some rare cases doing that in the driver may be the optimum approach.

<a id="rst-system-resume"></a>

#### 2.4.2. System Resume

When the system is undergoing a transition from a sleep state in which the contents of memory have been preserved, such as one of the ACPI sleep states S1-S3, into the working state (ACPI S0), the phases are:

> resume_noirq, resume, complete.

The following PCI bus type's callbacks, respectively, are executed in these phases:



```text
pci_pm_resume_noirq()
pci_pm_resume()
pci_pm_complete()
```

The pci_pm_resume_noirq() routine first puts the device into the full-power state, restores its standard configuration registers and applies early resume hardware quirks related to the device, if necessary.  This is done unconditionally, regardless of whether or not the device's driver implements legacy PCI power management callbacks (this way all PCI devices are in the full-power state and their standard configuration registers have been restored when their interrupt handlers are invoked for the first time during resume, which allows the kernel to avoid problems with the handling of shared interrupts by drivers whose devices are still suspended).  If legacy PCI power management callbacks (see Section 3) are implemented by the device's driver, the legacy early resume callback is executed and its result is returned.  Otherwise, the device driver's pm-&gt;resume_noirq() callback is executed, if defined, and its result is returned.

The pci_pm_resume() routine first checks if the device's standard configuration registers have been restored and restores them if that's not the case (this only is necessary in the error path during a failing suspend).  Next, resume hardware quirks related to the device are applied, if necessary, and if the device's driver implements legacy PCI power management callbacks (see Section 3), the driver's legacy resume callback is executed and its result is returned.  Otherwise, the device's wakeup signaling mechanisms are blocked and its driver's pm-&gt;resume() callback is executed, if defined (the callback's result is then returned).

The resume phase is carried out asynchronously for PCI devices, like the suspend phase described above, which means that if two PCI devices don't depend on each other in a known way, the pci_pm_resume() routine may be executed for both of them in parallel.

The pci_pm_complete() routine only executes the device driver's pm-&gt;complete() callback, if defined.

<a id="rst-system-hibernation"></a>

#### 2.4.3. System Hibernation

System hibernation is more complicated than system suspend, because it requires a system image to be created and written into a persistent storage medium.  The image is created atomically and all devices are quiesced, or frozen, before that happens.

The freezing of devices is carried out after enough memory has been freed (at the time of this writing the image creation requires at least 50% of system RAM to be free) in the following three phases:

> prepare, freeze, freeze_noirq

that correspond to the PCI bus type's callbacks:



```text
pci_pm_prepare()
pci_pm_freeze()
pci_pm_freeze_noirq()
```

This means that the prepare phase is exactly the same as for system suspend. The other two phases, however, are different.

The pci_pm_freeze() routine is quite similar to pci_pm_suspend(), but it runs the device driver's pm-&gt;freeze() callback, if defined, instead of pm-&gt;suspend(), and it doesn't apply the suspend-related hardware quirks.  It is executed asynchronously for different PCI devices that don't depend on each other in a known way.

The pci_pm_freeze_noirq() routine, in turn, is similar to pci_pm_suspend_noirq(), but it calls the device driver's pm-&gt;freeze_noirq() routine instead of pm-&gt;suspend_noirq().  It also doesn't attempt to prepare the device for signaling wakeup and put it into a low-power state.  Still, it saves the device's standard configuration registers if they haven't been saved by one of the driver's callbacks.

Once the image has been created, it has to be saved.  However, at this point all devices are frozen and they cannot handle I/O, while their ability to handle I/O is obviously necessary for the image saving.  Thus they have to be brought back to the fully functional state and this is done in the following phases:

> thaw_noirq, thaw, complete

using the following PCI bus type's callbacks:



```text
pci_pm_thaw_noirq()
pci_pm_thaw()
pci_pm_complete()
```

respectively.

The first of them, pci_pm_thaw_noirq(), is analogous to pci_pm_resume_noirq(). It puts the device into the full power state and restores its standard configuration registers.  It also executes the device driver's pm-&gt;thaw_noirq() callback, if defined, instead of pm-&gt;resume_noirq().

The pci_pm_thaw() routine is similar to pci_pm_resume(), but it runs the device driver's pm-&gt;thaw() callback instead of pm-&gt;resume().  It is executed asynchronously for different PCI devices that don't depend on each other in a known way.

The complete phase is the same as for system resume.

After saving the image, devices need to be powered down before the system can enter the target sleep state (ACPI S4 for ACPI-based systems).  This is done in three phases:

> prepare, poweroff, poweroff_noirq

where the prepare phase is exactly the same as for system suspend.  The other two phases are analogous to the suspend and suspend_noirq phases, respectively. The PCI subsystem-level callbacks they correspond to:



```text
pci_pm_poweroff()
pci_pm_poweroff_noirq()
```

work in analogy with pci_pm_suspend() and pci_pm_suspend_noirq(), respectively, although they don't attempt to save the device's standard configuration registers.

<a id="rst-system-restore"></a>

#### 2.4.4. System Restore

System restore requires a hibernation image to be loaded into memory and the pre-hibernation memory contents to be restored before the pre-hibernation system activity can be resumed.

As described in [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md), the hibernation image is loaded into memory by a fresh instance of the kernel, called the boot kernel, which in turn is loaded and run by a boot loader in the usual way.  After the boot kernel has loaded the image, it needs to replace its own code and data with the code and data of the "hibernated" kernel stored within the image, called the image kernel.  For this purpose all devices are frozen just like before creating the image during hibernation, in the

> prepare, freeze, freeze_noirq

phases described above.  However, the devices affected by these phases are only those having drivers in the boot kernel; other devices will still be in whatever state the boot loader left them.

Should the restoration of the pre-hibernation memory contents fail, the boot kernel would go through the "thawing" procedure described above, using the thaw_noirq, thaw, and complete phases (that will only affect the devices having drivers in the boot kernel), and then continue running normally.

If the pre-hibernation memory contents are restored successfully, which is the usual situation, control is passed to the image kernel, which then becomes responsible for bringing the system back to the working state.  To achieve this, it must restore the devices' pre-hibernation functionality, which is done much like waking up from the memory sleep state, although it involves different phases:

> restore_noirq, restore, complete

The first two of these are analogous to the resume_noirq and resume phases described above, respectively, and correspond to the following PCI subsystem callbacks:



```text
pci_pm_restore_noirq()
pci_pm_restore()
```

These callbacks work in analogy with pci_pm_resume_noirq() and pci_pm_resume(), respectively, but they execute the device driver's pm-&gt;restore_noirq() and pm-&gt;restore() callbacks, if available.

The complete phase is carried out in exactly the same way as during system resume.

<a id="rst-pci-device-drivers-and-power-management"></a>

## 3. PCI Device Drivers and Power Management

<a id="rst-power-management-callbacks"></a>

### 3.1. Power Management Callbacks

PCI device drivers participate in power management by providing callbacks to be executed by the PCI subsystem's power management routines described above and by controlling the runtime power management of their devices.

At the time of this writing there are two ways to define power management callbacks for a PCI device driver, the recommended one, based on using a dev_pm_ops structure described in [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md), and the "legacy" one, in which the .suspend() and .resume() callbacks from struct pci_driver are used.  The legacy approach, however, doesn't allow one to define runtime power management callbacks and is not really suitable for any new drivers.  Therefore it is not covered by this document (refer to the source code to learn more about it).

It is recommended that all PCI device drivers define a struct dev_pm_ops object containing pointers to power management (PM) callbacks that will be executed by the PCI subsystem's PM routines in various circumstances.  A pointer to the driver's struct dev_pm_ops object has to be assigned to the driver.pm field in its struct pci_driver object.  Once that has happened, the "legacy" PM callbacks in struct pci_driver are ignored (even if they are not NULL).

The PM callbacks in struct dev_pm_ops are not mandatory and if they are not defined (i.e. the respective fields of struct dev_pm_ops are unset) the PCI subsystem will handle the device in a simplified default manner.  If they are defined, though, they are expected to behave as described in the following subsections.

<a id="rst-prepare"></a>

#### 3.1.1. prepare()

The prepare() callback is executed during system suspend, during hibernation (when a hibernation image is about to be created), during power-off after saving a hibernation image and during system restore, when a hibernation image has just been loaded into memory.

This callback is only necessary if the driver's device has children that in general may be registered at any time.  In that case the role of the prepare() callback is to prevent new children of the device from being registered until one of the resume_noirq(), thaw_noirq(), or restore_noirq() callbacks is run.

In addition to that the prepare() callback may carry out some operations preparing the device to be suspended, although it should not allocate memory (if additional memory is required to suspend the device, it has to be preallocated earlier, for example in a suspend/hibernate notifier as described in [Documentation/driver-api/pm/notifiers.rst](/kernel/hardware/driver-api/pm/notifiers.md)).

<a id="rst-suspend"></a>

#### 3.1.2. suspend()

The suspend() callback is only executed during system suspend, after prepare() callbacks have been executed for all devices in the system.

This callback is expected to quiesce the device and prepare it to be put into a low-power state by the PCI subsystem.  It is not required (in fact it even is not recommended) that a PCI driver's suspend() callback save the standard configuration registers of the device, prepare it for waking up the system, or put it into a low-power state.  All of these operations can very well be taken care of by the PCI subsystem, without the driver's participation.

However, in some rare case it is convenient to carry out these operations in a PCI driver.  Then, pci_save_state(), pci_prepare_to_sleep(), and pci_set_power_state() should be used to save the device's standard configuration registers, to prepare it for system wakeup (if necessary), and to put it into a low-power state, respectively.  Moreover, if the driver calls pci_save_state(), the PCI subsystem will not execute either pci_prepare_to_sleep(), or pci_set_power_state() for its device, so the driver is then responsible for handling the device as appropriate.

While the suspend() callback is being executed, the driver's interrupt handler can be invoked to handle an interrupt from the device, so all suspend-related operations relying on the driver's ability to handle interrupts should be carried out in this callback.

<a id="rst-suspend-noirq"></a>

#### 3.1.3. suspend_noirq()

The suspend_noirq() callback is only executed during system suspend, after suspend() callbacks have been executed for all devices in the system and after device interrupts have been disabled by the PM core.

The difference between suspend_noirq() and suspend() is that the driver's interrupt handler will not be invoked while suspend_noirq() is running.  Thus suspend_noirq() can carry out operations that would cause race conditions to arise if they were performed in suspend().

<a id="rst-freeze"></a>

#### 3.1.4. freeze()

The freeze() callback is hibernation-specific and is executed in two situations, during hibernation, after prepare() callbacks have been executed for all devices in preparation for the creation of a system image, and during restore, after a system image has been loaded into memory from persistent storage and the prepare() callbacks have been executed for all devices.

The role of this callback is analogous to the role of the suspend() callback described above.  In fact, they only need to be different in the rare cases when the driver takes the responsibility for putting the device into a low-power state.

In that cases the freeze() callback should not prepare the device system wakeup or put it into a low-power state.  Still, either it or freeze_noirq() should save the device's standard configuration registers using pci_save_state().

<a id="rst-freeze-noirq"></a>

#### 3.1.5. freeze_noirq()

The freeze_noirq() callback is hibernation-specific.  It is executed during hibernation, after prepare() and freeze() callbacks have been executed for all devices in preparation for the creation of a system image, and during restore, after a system image has been loaded into memory and after prepare() and freeze() callbacks have been executed for all devices.  It is always executed after device interrupts have been disabled by the PM core.

The role of this callback is analogous to the role of the suspend_noirq() callback described above and it very rarely is necessary to define freeze_noirq().

The difference between freeze_noirq() and freeze() is analogous to the difference between suspend_noirq() and suspend().

<a id="rst-poweroff"></a>

#### 3.1.6. poweroff()

The poweroff() callback is hibernation-specific.  It is executed when the system is about to be powered off after saving a hibernation image to a persistent storage.  prepare() callbacks are executed for all devices before poweroff() is called.

The role of this callback is analogous to the role of the suspend() and freeze() callbacks described above, although it does not need to save the contents of the device's registers.  In particular, if the driver wants to put the device into a low-power state itself instead of allowing the PCI subsystem to do that, the poweroff() callback should use pci_prepare_to_sleep() and pci_set_power_state() to prepare the device for system wakeup and to put it into a low-power state, respectively, but it need not save the device's standard configuration registers.

<a id="rst-poweroff-noirq"></a>

#### 3.1.7. poweroff_noirq()

The poweroff_noirq() callback is hibernation-specific.  It is executed after poweroff() callbacks have been executed for all devices in the system.

The role of this callback is analogous to the role of the suspend_noirq() and freeze_noirq() callbacks described above, but it does not need to save the contents of the device's registers.

The difference between poweroff_noirq() and poweroff() is analogous to the difference between suspend_noirq() and suspend().

<a id="rst-resume-noirq"></a>

#### 3.1.8. resume_noirq()

The resume_noirq() callback is only executed during system resume, after the PM core has enabled the non-boot CPUs.  The driver's interrupt handler will not be invoked while resume_noirq() is running, so this callback can carry out operations that might race with the interrupt handler.

Since the PCI subsystem unconditionally puts all devices into the full power state in the resume_noirq phase of system resume and restores their standard configuration registers, resume_noirq() is usually not necessary.  In general it should only be used for performing operations that would lead to race conditions if carried out by resume().

<a id="rst-resume"></a>

#### 3.1.9. resume()

The resume() callback is only executed during system resume, after resume_noirq() callbacks have been executed for all devices in the system and device interrupts have been enabled by the PM core.

This callback is responsible for restoring the pre-suspend configuration of the device and bringing it back to the fully functional state.  The device should be able to process I/O in a usual way after resume() has returned.

<a id="rst-thaw-noirq"></a>

#### 3.1.10. thaw_noirq()

The thaw_noirq() callback is hibernation-specific.  It is executed after a system image has been created and the non-boot CPUs have been enabled by the PM core, in the thaw_noirq phase of hibernation.  It also may be executed if the loading of a hibernation image fails during system restore (it is then executed after enabling the non-boot CPUs).  The driver's interrupt handler will not be invoked while thaw_noirq() is running.

The role of this callback is analogous to the role of resume_noirq().  The difference between these two callbacks is that thaw_noirq() is executed after freeze() and freeze_noirq(), so in general it does not need to modify the contents of the device's registers.

<a id="rst-thaw"></a>

#### 3.1.11. thaw()

The thaw() callback is hibernation-specific.  It is executed after thaw_noirq() callbacks have been executed for all devices in the system and after device interrupts have been enabled by the PM core.

This callback is responsible for restoring the pre-freeze configuration of the device, so that it will work in a usual way after thaw() has returned.

<a id="rst-restore-noirq"></a>

#### 3.1.12. restore_noirq()

The restore_noirq() callback is hibernation-specific.  It is executed in the restore_noirq phase of hibernation, when the boot kernel has passed control to the image kernel and the non-boot CPUs have been enabled by the image kernel's PM core.

This callback is analogous to resume_noirq() with the exception that it cannot make any assumption on the previous state of the device, even if the BIOS (or generally the platform firmware) is known to preserve that state over a suspend-resume cycle.

For the vast majority of PCI device drivers there is no difference between resume_noirq() and restore_noirq().

<a id="rst-restore"></a>

#### 3.1.13. restore()

The restore() callback is hibernation-specific.  It is executed after restore_noirq() callbacks have been executed for all devices in the system and after the PM core has enabled device drivers' interrupt handlers to be invoked.

This callback is analogous to resume(), just like restore_noirq() is analogous to resume_noirq().  Consequently, the difference between restore_noirq() and restore() is analogous to the difference between resume_noirq() and resume().

For the vast majority of PCI device drivers there is no difference between resume() and restore().

<a id="rst-complete"></a>

#### 3.1.14. complete()

The complete() callback is executed in the following situations:

> - during system resume, after resume() callbacks have been executed for all devices,
>
> - during hibernation, before saving the system image, after thaw() callbacks have been executed for all devices,
>
> - during system restore, when the system is going back to its pre-hibernation state, after restore() callbacks have been executed for all devices.

It also may be executed if the loading of a hibernation image into memory fails (in that case it is run after thaw() callbacks have been executed for all devices that have drivers in the boot kernel).

This callback is entirely optional, although it may be necessary if the prepare() callback performs operations that need to be reversed.

<a id="rst-runtime-suspend"></a>

#### 3.1.15. runtime_suspend()

The runtime_suspend() callback is specific to device runtime power management (runtime PM).  It is executed by the PM core's runtime PM framework when the device is about to be suspended (i.e. quiesced and put into a low-power state) at run time.

This callback is responsible for freezing the device and preparing it to be put into a low-power state, but it must allow the PCI subsystem to perform all of the PCI-specific actions necessary for suspending the device.

<a id="rst-runtime-resume"></a>

#### 3.1.16. runtime_resume()

The runtime_resume() callback is specific to device runtime PM.  It is executed by the PM core's runtime PM framework when the device is about to be resumed (i.e. put into the full-power state and programmed to process I/O normally) at run time.

This callback is responsible for restoring the normal functionality of the device after it has been put into the full-power state by the PCI subsystem. The device is expected to be able to process I/O in the usual way after runtime_resume() has returned.

<a id="rst-runtime-idle"></a>

#### 3.1.17. runtime_idle()

The runtime_idle() callback is specific to device runtime PM.  It is executed by the PM core's runtime PM framework whenever it may be desirable to suspend the device according to the PM core's information.  In particular, it is automatically executed right after runtime_resume() has returned in case the resume of the device has happened as a result of a spurious event.

This callback is optional, but if it is not implemented or if it returns 0, the PCI subsystem will call pm_runtime_suspend() for the device, which in turn will cause the driver's runtime_suspend() callback to be executed.

<a id="rst-pointing-multiple-callback-pointers-to-one-routine"></a>

#### 3.1.18. Pointing Multiple Callback Pointers to One Routine

Although in principle each of the callbacks described in the previous subsections can be defined as a separate function, it often is convenient to point two or more members of struct dev_pm_ops to the same routine.  There are a few convenience macros that can be used for this purpose.

The DEFINE_SIMPLE_DEV_PM_OPS() declares a struct dev_pm_ops object with one suspend routine pointed to by the .suspend(), .freeze(), and .poweroff() members and one resume routine pointed to by the .resume(), .thaw(), and .restore() members.  The other function pointers in this struct dev_pm_ops are unset.

The DEFINE_RUNTIME_DEV_PM_OPS() is similar to DEFINE_SIMPLE_DEV_PM_OPS(), but it additionally sets the .runtime_resume() pointer to pm_runtime_force_resume() and the .runtime_suspend() pointer to pm_runtime_force_suspend().

The SYSTEM_SLEEP_PM_OPS() can be used inside of a declaration of struct dev_pm_ops to indicate that one suspend routine is to be pointed to by the .suspend(), .freeze(), and .poweroff() members and one resume routine is to be pointed to by the .resume(), .thaw(), and .restore() members.

<a id="rst-driver-flags-for-power-management"></a>

#### 3.1.19. Driver Flags for Power Management

The PM core allows device drivers to set flags that influence the handling of power management for the devices by the core itself and by middle layer code including the PCI bus type.  The flags should be set once at the driver probe time with the help of the dev_pm_set_driver_flags() function and they should not be updated directly afterwards.

The DPM_FLAG_NO_DIRECT_COMPLETE flag prevents the PM core from using the direct-complete mechanism allowing device suspend/resume callbacks to be skipped if the device is in runtime suspend when the system suspend starts.  That also affects all of the ancestors of the device, so this flag should only be used if absolutely necessary.

The DPM_FLAG_SMART_PREPARE flag causes the PCI bus type to return a positive value from pci_pm_prepare() only if the -&gt;prepare callback provided by the driver of the device returns a positive value.  That allows the driver to opt out from using the direct-complete mechanism dynamically (whereas setting DPM_FLAG_NO_DIRECT_COMPLETE means permanent opt-out).

The DPM_FLAG_SMART_SUSPEND flag tells the PCI bus type that from the driver's perspective the device can be safely left in runtime suspend during system suspend.  That causes pci_pm_suspend(), pci_pm_freeze() and pci_pm_poweroff() to avoid resuming the device from runtime suspend unless there are PCI-specific reasons for doing that.  Also, it causes pci_pm_suspend_late/noirq() and pci_pm_poweroff_late/noirq() to return early if the device remains in runtime suspend during the "late" phase of the system-wide transition under way. Moreover, if the device is in runtime suspend in pci_pm_resume_noirq() or pci_pm_restore_noirq(), its runtime PM status will be changed to "active" (as it is going to be put into D0 going forward).

Setting the DPM_FLAG_MAY_SKIP_RESUME flag means that the driver allows its "noirq" and "early" resume callbacks to be skipped if the device can be left in suspend after a system-wide transition into the working state.  This flag is taken into consideration by the PM core along with the power.may_skip_resume status bit of the device which is set by pci_pm_suspend_noirq() in certain situations.  If the PM core determines that the driver's "noirq" and "early" resume callbacks should be skipped, the dev_pm_skip_resume() helper function will return "true" and that will cause pci_pm_resume_noirq() and pci_pm_resume_early() to return upfront without touching the device and executing the driver callbacks.

<a id="rst-device-runtime-power-management"></a>

### 3.2. Device Runtime Power Management

In addition to providing device power management callbacks PCI device drivers are responsible for controlling the runtime power management (runtime PM) of their devices.

The PCI device runtime PM is optional, but it is recommended that PCI device drivers implement it at least in the cases where there is a reliable way of verifying that the device is not used (like when the network cable is detached from an Ethernet adapter or there are no devices attached to a USB controller).

To support the PCI runtime PM the driver first needs to implement the runtime_suspend() and runtime_resume() callbacks.  It also may need to implement the runtime_idle() callback to prevent the device from being suspended again every time right after the runtime_resume() callback has returned (alternatively, the runtime_suspend() callback will have to check if the device should really be suspended and return -EAGAIN if that is not the case).

The runtime PM of PCI devices is enabled by default by the PCI core.  PCI device drivers do not need to enable it and should not attempt to do so. However, it is blocked by pci_pm_init() that runs the pm_runtime_forbid() helper function.  In addition to that, the runtime PM usage counter of each PCI device is incremented by local_pci_probe() before executing the probe callback provided by the device's driver.

If a PCI driver implements the runtime PM callbacks and intends to use the runtime PM framework provided by the PM core and the PCI subsystem, it needs to decrement the device's runtime PM usage counter in its probe callback function.  If it doesn't do that, the counter will always be different from zero for the device and it will never be runtime-suspended.  The simplest way to do that is by calling pm_runtime_put_noidle(), but if the driver wants to schedule an autosuspend right away, for example, it may call pm_runtime_put_autosuspend() instead for this purpose.  Generally, it just needs to call a function that decrements the devices usage counter from its probe routine to make runtime PM work for the device.

It is important to remember that the driver's runtime_suspend() callback may be executed right after the usage counter has been decremented, because user space may already have caused the pm_runtime_allow() helper function unblocking the runtime PM of the device to run via sysfs, so the driver must be prepared to cope with that.

The driver itself should not call pm_runtime_allow(), though.  Instead, it should let user space or some platform-specific code do that (user space can do it via sysfs as stated above), but it must be prepared to handle the runtime PM of the device correctly as soon as pm_runtime_allow() is called (which may happen at any time, even before the driver is loaded).

When the driver's remove callback runs, it has to balance the decrementation of the device's runtime PM usage counter at the probe time.  For this reason, if it has decremented the counter in its probe callback, it must run pm_runtime_get_noresume() in its remove callback.  \[Since the core carries out a runtime resume of the device and bumps up the device's usage counter before running the driver's remove callback, the runtime PM of the device is effectively disabled for the duration of the remove execution and all runtime PM helper functions incrementing the device's usage counter are then effectively equivalent to pm_runtime_get_noresume().\]

The runtime PM framework works by processing requests to suspend or resume devices, or to check if they are idle (in which cases it is reasonable to subsequently request that they be suspended).  These requests are represented by work items put into the power management workqueue, pm_wq.  Although there are a few situations in which power management requests are automatically queued by the PM core (for example, after processing a request to resume a device the PM core automatically queues a request to check if the device is idle), device drivers are generally responsible for queuing power management requests for their devices.  For this purpose they should use the runtime PM helper functions provided by the PM core, discussed in [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md).

Devices can also be suspended and resumed synchronously, without placing a request into pm_wq.  In the majority of cases this also is done by their drivers that use helper functions provided by the PM core for this purpose.

For more information on the runtime PM of devices refer to [Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md).

<a id="rst-resources"></a>

## 4. Resources

PCI Local Bus Specification, Rev. 3.0

PCI Bus Power Management Interface Specification, Rev. 1.2

Advanced Configuration and Power Interface (ACPI) Specification, Rev. 3.0b

PCI Express Base Specification, Rev. 2.0

[Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md)

[Documentation/power/runtime_pm.rst](/kernel/internals/power/runtime-pm.md)

---

# PM Quality Of Service Interface

_Peios Kernel / Internals / Power_

> This interface provides a kernel and user mode interface for registering performance expectations by drivers, subsystems and user space applications on one of the parameters.

<a id="rst-pm-quality-of-service-interface"></a>

This interface provides a kernel and user mode interface for registering performance expectations by drivers, subsystems and user space applications on one of the parameters.

- **Two different PM QoS frameworks are available:**

  - CPU latency QoS.

  - The per-device PM QoS framework provides the API to manage the per-device latency constraints and PM QoS flags.

The latency unit used in the PM QoS framework is the microsecond (usec).

<a id="rst-pm-qos-framework"></a>

## 1. PM QoS framework

A global list of CPU latency QoS requests is maintained along with an aggregated (effective) target value.  The aggregated target value is updated with changes to the request list or elements of the list.  For CPU latency QoS, the aggregated target value is simply the min of the request values held in the list elements.

Note: the aggregated target value is implemented as an atomic variable so that reading the aggregated value does not require any locking mechanism.

From kernel space the use of this interface is simple:

- **void cpu_latency_qos_add_request(handle, target_value):**

  Will insert an element into the CPU latency QoS list with the target value. Upon change to this list the new target is recomputed and any registered notifiers are called only if the target value is now different. Clients of PM QoS need to save the returned handle for future use in other PM QoS API functions.

- **void cpu_latency_qos_update_request(handle, new_target_value):**

  Will update the list element pointed to by the handle with the new target value and recompute the new aggregated target, calling the notification tree if the target is changed.

- **void cpu_latency_qos_remove_request(handle):**

  Will remove the element.  After removal it will update the aggregate target and call the notification tree if the target was changed as a result of removing the request.

- **int cpu_latency_qos_limit():**

  Returns the aggregated value for the CPU latency QoS.

- **int cpu_latency_qos_request_active(handle):**

  Returns if the request is still active, i.e. it has not been removed from the CPU latency QoS list.

From user space:

The infrastructure exposes two separate device nodes, /dev/cpu_dma_latency for the CPU latency QoS and /dev/cpu_wakeup_latency for the CPU system wakeup latency QoS.

Only processes can register a PM QoS request.  To provide for automatic cleanup of a process, the interface requires the process to register its parameter requests as follows.

To register the default PM QoS target for the CPU latency QoS, the process must open /dev/cpu_dma_latency.  To register a CPU system wakeup QoS limit, the process must open /dev/cpu_wakeup_latency.

As long as the device node is held open that process has a registered request on the parameter.

To change the requested target value, the process needs to write an s32 value to the open device node.  Alternatively, it can write a hex string for the value using the 10 char long format e.g. "0x12345678".

To remove the user mode request for a target value simply close the device node.

<a id="rst-pm-qos-per-device-latency-and-flags-framework"></a>

## 2. PM QoS per-device latency and flags framework

For each device, there are three lists of PM QoS requests. Two of them are maintained along with the aggregated targets of resume latency and active state latency tolerance (in microseconds) and the third one is for PM QoS flags. Values are updated in response to changes of the request list.

The target values of resume latency and active state latency tolerance are simply the minimum of the request values held in the parameter list elements. The PM QoS flags aggregate value is a gather (bitwise OR) of all list elements' values.  One device PM QoS flag is defined currently: PM_QOS_FLAG_NO_POWER_OFF.

Note: The aggregated target values are implemented in such a way that reading the aggregated value does not require any locking mechanism.

From kernel mode the use of this interface is the following:

- **int dev_pm_qos_add_request(device, handle, type, value):**

  Will insert an element into the list for that identified device with the target value.  Upon change to this list the new target is recomputed and any registered notifiers are called only if the target value is now different. Clients of dev_pm_qos need to save the handle for future use in other dev_pm_qos API functions.

- **int dev_pm_qos_update_request(handle, new_value):**

  Will update the list element pointed to by the handle with the new target value and recompute the new aggregated target, calling the notification trees if the target is changed.

- **int dev_pm_qos_remove_request(handle):**

  Will remove the element.  After removal it will update the aggregate target and call the notification trees if the target was changed as a result of removing the request.

- **s32 dev_pm_qos_read_value(device, type):**

  Returns the aggregated value for a given device's constraints list.

- **enum pm_qos_flags_status dev_pm_qos_flags(device, mask)**

  Check PM QoS flags of the given device against the given mask of flags. The meaning of the return values is as follows:

  > - **PM_QOS_FLAGS_ALL:**
  >
  >   All flags from the mask are set
  >
  > - **PM_QOS_FLAGS_SOME:**
  >
  >   Some flags from the mask are set
  >
  > - **PM_QOS_FLAGS_NONE:**
  >
  >   No flags from the mask are set
  >
  > - **PM_QOS_FLAGS_UNDEFINED:**
  >
  >   The device's PM QoS structure has not been initialized or the list of requests is empty.

- **int dev_pm_qos_add_ancestor_request(dev, handle, type, value)**

  Add a PM QoS request for the first direct ancestor of the given device whose power.ignore_children flag is unset (for DEV_PM_QOS_RESUME_LATENCY requests) or whose power.set_latency_tolerance callback pointer is not NULL (for DEV_PM_QOS_LATENCY_TOLERANCE requests).

- **int dev_pm_qos_expose_latency_limit(device, value)**

  Add a request to the device's PM QoS list of resume latency constraints and create a sysfs attribute pm_qos_resume_latency_us under the device's power directory allowing user space to manipulate that request.

- **void dev_pm_qos_hide_latency_limit(device)**

  Drop the request added by dev_pm_qos_expose_latency_limit() from the device's PM QoS list of resume latency constraints and remove sysfs attribute pm_qos_resume_latency_us from the device's power directory.

- **int dev_pm_qos_expose_flags(device, value)**

  Add a request to the device's PM QoS list of flags and create sysfs attribute pm_qos_no_power_off under the device's power directory allowing user space to change the value of the PM_QOS_FLAG_NO_POWER_OFF flag.

- **void dev_pm_qos_hide_flags(device)**

  Drop the request added by dev_pm_qos_expose_flags() from the device's PM QoS list of flags and remove sysfs attribute pm_qos_no_power_off from the device's power directory.

Notification mechanisms:

The per-device PM QoS framework has a per-device notification tree.

- **int dev_pm_qos_add_notifier(device, notifier, type):**

  Adds a notification callback function for the device for a particular request type.

  The callback is called when the aggregated value of the device constraints list is changed.

- **int dev_pm_qos_remove_notifier(device, notifier, type):**

  Removes the notification callback function for the device.

<a id="rst-active-state-latency-tolerance"></a>

### Active state latency tolerance

This device PM QoS type is used to support systems in which hardware may switch to energy-saving operation modes on the fly.  In those systems, if the operation mode chosen by the hardware attempts to save energy in an overly aggressive way, it may cause excess latencies to be visible to software, causing it to miss certain protocol requirements or target frame or sample rates etc.

If there is a latency tolerance control mechanism for a given device available to software, the .set_latency_tolerance callback in that device's dev_pm_info structure should be populated.  The routine pointed to by it is should implement whatever is necessary to transfer the effective requirement value to the hardware.

Whenever the effective latency tolerance changes for the device, its .set_latency_tolerance() callback will be executed and the effective value will be passed to it.  If that value is negative, which means that the list of latency tolerance requirements for the device is empty, the callback is expected to switch the underlying hardware latency tolerance control mechanism to an autonomous mode if available.  If that value is PM_QOS_LATENCY_ANY, in turn, and the hardware supports a special "no requirement" setting, the callback is expected to use it.  That allows software to prevent the hardware from automatically updating the device's latency tolerance in response to its power state changes (e.g. during transitions from D3cold to D0), which generally may be done in the autonomous latency tolerance control mode.

If .set_latency_tolerance() is present for the device, sysfs attribute pm_qos_latency_tolerance_us will be present in the devivce's power directory. Then, user space can use that attribute to specify its latency tolerance requirement for the device, if any.  Writing "any" to it means "no requirement, but do not let the hardware control latency tolerance" and writing "auto" to it allows the hardware to be switched to the autonomous mode if there are no other requirements from the kernel side in the device's list.

Kernel code can use the functions described above along with the DEV_PM_QOS_LATENCY_TOLERANCE device PM QoS type to add, remove and update latency tolerance requirements for devices.

---

# Linux power supply class

_Peios Kernel / Internals / Power_

> Power supply class used to represent battery, UPS, AC or DC power supply properties to user-space.

<a id="rst-linux-power-supply-class"></a>

<a id="rst-synopsis"></a>

## Synopsis

Power supply class used to represent battery, UPS, AC or DC power supply properties to user-space.

It defines a core set of attributes which should be applicable to (almost) every power supply out there. Attributes are available via sysfs and uevent interfaces.

Each attribute has a well-defined meaning, up to the unit of measure used. While the attributes provided are believed to be universally applicable to any power supply, specific monitoring hardware may not be able to provide them all, so any of them may be skipped.

The power supply class is extensible and allows drivers to define their own attributes.  The core attribute set is subject to the standard Linux evolution (i.e., if some attribute is found to be applicable to many power supply types or their drivers, it can be added to the core set).

It also integrates with the LED framework, for the purpose of providing typically expected feedback of battery charging/fully charged status and AC/USB power supply online status. (Note that specific details of the indication (including whether to use it at all) are fully controllable by user and/or specific machine defaults, per design principles of the LED framework.)

<a id="rst-attributes-properties"></a>

## Attributes/properties

The power supply class has a predefined set of attributes. This eliminates code duplication across drivers. The power supply class insists on reusing its predefined attributes *and* their units.

So, userspace gets a predictable set of attributes and their units for any kind of power supply, and can process/present them to a user in consistent manner. Results for different power supplies and machines are also directly comparable.

See drivers/power/supply/ds2760_battery.c for the example how to declare and handle attributes.

<a id="rst-units"></a>

## Units

Quoting include/linux/power_supply.h:

> All voltages, currents, charges, energies, time and temperatures in µV, µA, µAh, µWh, seconds and tenths of degree Celsius unless otherwise stated. It's driver's job to convert its raw values to units in which this class operates.

<a id="rst-attributes-properties-detailed"></a>

## Attributes/properties detailed


<table>
<tbody>
<tr>
<td>


**Charge/Energy/Capacity - how to not confuse**

</td>
</tr>
<tr>
<td>


**Because both "charge" (µAh) and "energy" (µWh) represents "capacity" of battery, this class distinguishes these terms. Don't mix them\!**

- - **`CHARGE_*`**

    attributes represents capacity in µAh only.

- - **`ENERGY_*`**

    attributes represents capacity in µWh only.

- - **`CAPACITY`**

    attribute represents capacity in *percents*, from 0 to 100.

</td>
</tr>
</tbody>
</table>

Postfixes:

- **\_AVG**

  *hardware* averaged value, use it if your hardware is really able to report averaged values.

- **\_NOW**

  momentary/instantaneous values.

- **STATUS**

  this attribute represents operating status (charging, full, discharging (i.e., powering a load), etc.). This corresponds to `BATTERY_STATUS_*` values, as defined in battery.h.

- **CHARGE_TYPE**

  batteries can typically charge at different rates. This defines trickle and fast charges.  For batteries that are already charged or discharging, 'n/a' can be displayed (or 'unknown', if the status is not known).

- **AUTHENTIC**

  indicates the power supply (battery or charger) connected to the platform is authentic(1) or non-authentic(0).

- **HEALTH**

  represents health of the battery. Values corresponds to POWER_SUPPLY_HEALTH\_\*, defined in battery.h.

- **VOLTAGE_OCV**

  open circuit voltage of the battery.

- **VOLTAGE_MAX_DESIGN, VOLTAGE_MIN_DESIGN**

  design values for maximal and minimal power supply voltages. Maximal/minimal means values of voltages when battery is considered "full"/"empty" at normal conditions. Yes, there is no direct relation between voltage and battery capacity, but some dumb batteries use voltage for very approximated calculation of capacity. A battery driver also can use this attribute just to inform userspace about maximal and minimal voltage thresholds of a given battery.

- **VOLTAGE_MAX, VOLTAGE_MIN**

  same as \_DESIGN voltage values except that these ones should be used if hardware could only guess (measure and retain) the thresholds of a given power supply.

- **VOLTAGE_BOOT**

  Reports the voltage measured during boot

- **CURRENT_BOOT**

  Reports the current measured during boot

- **CHARGE_FULL_DESIGN, CHARGE_EMPTY_DESIGN**

  design charge values, when battery is considered full/empty.

- **ENERGY_FULL_DESIGN, ENERGY_EMPTY_DESIGN**

  same as above but for energy.

- **CHARGE_FULL, CHARGE_EMPTY**

  These attributes mean "last remembered value of charge when battery became full/empty". They also could mean "value of charge when battery is considered full/empty at given conditions (temperature, age)". I.e., these attributes represents real thresholds, not design values.

- **ENERGY_FULL, ENERGY_EMPTY**

  same as above but for energy.

- **CHARGE_COUNTER**

  the current charge counter (in µAh).  This could easily be negative; there is no empty or full value.  It is only useful for relative, time-based measurements.

- **PRECHARGE_CURRENT**

  the maximum charge current during precharge phase of charge cycle (typically 20% of battery capacity).

- **CHARGE_TERM_CURRENT**

  Charge termination current. The charge cycle terminates when battery voltage is above recharge threshold, and charge current is below this setting (typically 10% of battery capacity).

- **CONSTANT_CHARGE_CURRENT**

  constant charge current programmed by charger.

- **CONSTANT_CHARGE_CURRENT_MAX**

  maximum charge current supported by the power supply object.

- **CONSTANT_CHARGE_VOLTAGE**

  constant charge voltage programmed by charger.

- **CONSTANT_CHARGE_VOLTAGE_MAX**

  maximum charge voltage supported by the power supply object.

- **INPUT_CURRENT_LIMIT**

  input current limit programmed by charger. Indicates the current drawn from a charging source.

- **INPUT_VOLTAGE_LIMIT**

  input voltage limit programmed by charger. Indicates the voltage limit from a charging source.

- **INPUT_POWER_LIMIT**

  input power limit programmed by charger. Indicates the power limit from a charging source.

- **CHARGE_CONTROL_LIMIT**

  current charge control limit setting

- **CHARGE_CONTROL_LIMIT_MAX**

  maximum charge control limit setting

- **CALIBRATE**

  battery or coulomb counter calibration status

- **CAPACITY**

  capacity in percents.

- **CAPACITY_ALERT_MIN**

  minimum capacity alert value in percents.

- **CAPACITY_ALERT_MAX**

  maximum capacity alert value in percents.

- **CAPACITY_LEVEL**

  capacity level. This corresponds to POWER_SUPPLY_CAPACITY_LEVEL\_\*.

- **TEMP**

  temperature of the power supply.

- **TEMP_ALERT_MIN**

  minimum battery temperature alert.

- **TEMP_ALERT_MAX**

  maximum battery temperature alert.

- **TEMP_AMBIENT**

  ambient temperature.

- **TEMP_AMBIENT_ALERT_MIN**

  minimum ambient temperature alert.

- **TEMP_AMBIENT_ALERT_MAX**

  maximum ambient temperature alert.

- **TEMP_MIN**

  minimum operatable temperature

- **TEMP_MAX**

  maximum operatable temperature

- **TIME_TO_EMPTY**

  seconds left for battery to be considered empty (i.e., while battery powers a load)

- **TIME_TO_FULL**

  seconds left for battery to be considered full (i.e., while battery is charging)

<a id="rst-battery-external-power-supply-interaction"></a>

## Battery &lt;-&gt; external power supply interaction

Often power supplies are acting as supplies and supplicants at the same time. Batteries are good example. So, batteries usually care if they're externally powered or not.

For that case, the power supply class implements a notification mechanism for batteries.

An external power supply (AC) lists supplicants (batteries) names in "supplied_to" struct member, and each power_supply_changed() call issued by an external power supply will notify supplicants via the external_power_changed callback.

<a id="rst-devicetree-battery-characteristics"></a>

## Devicetree battery characteristics

Drivers should call power_supply_get_battery_info() to obtain battery characteristics from a devicetree battery node, defined in Documentation/devicetree/bindings/power/supply/battery.yaml. This is implemented in drivers/power/supply/bq27xxx_battery.c.

Properties in struct power_supply_battery_info and their counterparts in the battery node have names corresponding to elements in enum power_supply_property, for naming consistency between sysfs attributes and battery node properties.

<a id="rst-q-a"></a>

## Q&amp;A

- **Q:**

  Where is POWER_SUPPLY_PROP_XYZ attribute?

- **A:**

  If you cannot find an attribute suitable for your driver needs, feel free to add it and send a patch along with your driver.

  The attributes available currently are the ones currently provided by the drivers written.

  Good candidates to add in future: model/part\#, cycle_time, manufacturer, etc.

- **Q:**

  I have some very specific attribute (e.g., battery color). Should I add this attribute to standard ones?

- **A:**

  Most likely, no. Such attribute can be placed in the driver itself, if it is useful. Of course, if the attribute in question is applicable to a large set of batteries, provided by many drivers, and/or comes from some general battery specification/standard, it may be a candidate to be added to the core attribute set.

- **Q:**

  Suppose my battery monitoring chip/firmware does not provide capacity in percents, but provides charge\_\{now,full,empty\}. Should I calculate percentage capacity manually, inside the driver, and register CAPACITY attribute? The same question about time_to_empty/time_to_full.

- **A:**

  Most likely, no. This class is designed to export properties which are directly measurable by the specific hardware available.

  Inferring not available properties using some heuristics or mathematical model is not a subject of work for a battery driver. Such functionality should be factored out, and in fact, apm_power, the driver to serve legacy APM API on top of the power supply class, uses a simple heuristic of approximating remaining battery capacity based on its charge, current, voltage and so on. But a full-fledged battery model is likely not a subject for the kernel at all, as it would require floating point calculations to deal with things like differential equations and Kalman filters. This is better be handled by batteryd/libbattery, yet to be written.

---

# Runtime Power Management Framework for I/O Devices

_Peios Kernel / Internals / Power_

> 2009-2011 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc.

<a id="rst-runtime-power-management-framework-for-i-o-devices"></a>

- **(C)** 2009-2011 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;, Novell Inc.

- **(C)** 2010 Alan Stern &lt;[stern@rowland.harvard.edu](<mailto:stern@rowland.harvard.edu>)&gt;

- **(C)** 2014 Intel Corp., Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

<a id="rst-introduction"></a>

## 1. Introduction

Support for runtime power management (runtime PM) of I/O devices is provided at the power management core (PM core) level by means of:

- The power management workqueue pm_wq in which bus types and device drivers can put their PM-related work items.  It is strongly recommended that pm_wq be used for queuing all work items related to runtime PM, because this allows them to be synchronized with system-wide power transitions (suspend to RAM, hibernation and resume from system sleep states).  pm_wq is declared in include/linux/pm_runtime.h and defined in kernel/power/main.c.

- A number of runtime PM fields in the 'power' member of 'struct device' (which is of the type 'struct dev_pm_info', defined in include/linux/pm.h) that can be used for synchronizing runtime PM operations with one another.

- Three device runtime PM callbacks in 'struct dev_pm_ops' (defined in include/linux/pm.h).

- A set of helper functions defined in drivers/base/power/runtime.c that can be used for carrying out runtime PM operations in such a way that the synchronization between them is taken care of by the PM core.  Bus types and device drivers are encouraged to use these functions.

The runtime PM callbacks present in 'struct dev_pm_ops', the device runtime PM fields of 'struct dev_pm_info' and the core helper functions provided for runtime PM are described below.

<a id="rst-device-runtime-pm-callbacks"></a>

## 2. Device Runtime PM Callbacks

There are three device runtime PM callbacks defined in 'struct dev_pm_ops':



```text
struct dev_pm_ops {
      ...
      int (*runtime_suspend)(struct device *dev);
      int (*runtime_resume)(struct device *dev);
      int (*runtime_idle)(struct device *dev);
      ...
};
```

The -&gt;runtime_suspend(), -&gt;runtime_resume() and -&gt;runtime_idle() callbacks are executed by the PM core for the device's subsystem that may be either of the following:

> 1. PM domain of the device, if the device's PM domain object, dev-&gt;pm_domain, is present.
>
> 2. Device type of the device, if both dev-&gt;type and dev-&gt;type-&gt;pm are present.
>
> 3. Device class of the device, if both dev-&gt;class and dev-&gt;class-&gt;pm are present.
>
> 4. Bus type of the device, if both dev-&gt;bus and dev-&gt;bus-&gt;pm are present.

If the subsystem chosen by applying the above rules doesn't provide the relevant callback, the PM core will invoke the corresponding driver callback stored in dev-&gt;driver-&gt;pm directly (if present).

The PM core always checks which callback to use in the order given above, so the priority order of callbacks from high to low is: PM domain, device type, class and bus type.  Moreover, the high-priority one will always take precedence over a low-priority one.  The PM domain, bus type, device type and class callbacks are referred to as subsystem-level callbacks in what follows.

By default, the callbacks are always invoked in process context with interrupts enabled.  However, the pm_runtime_irq_safe() helper function can be used to tell the PM core that it is safe to run the -&gt;runtime_suspend(), -&gt;runtime_resume() and -&gt;runtime_idle() callbacks for the given device in atomic context with interrupts disabled.  This implies that the callback routines in question must not block or sleep, but it also means that the synchronous helper functions listed at the end of Section 4 may be used for that device within an interrupt handler or generally in an atomic context.

The subsystem-level suspend callback, if present, is \_entirely\_ \_responsible\_ for handling the suspend of the device as appropriate, which may, but need not include executing the device driver's own -&gt;runtime_suspend() callback (from the PM core's point of view it is not necessary to implement a -&gt;runtime_suspend() callback in a device driver as long as the subsystem-level suspend callback knows what to do to handle the device).

> - Once the subsystem-level suspend callback (or the driver suspend callback, if invoked directly) has completed successfully for the given device, the PM core regards the device as suspended, which need not mean that it has been put into a low power state.  It is supposed to mean, however, that the device will not process data and will not communicate with the CPU(s) and RAM until the appropriate resume callback is executed for it.  The runtime PM status of a device after successful execution of the suspend callback is 'suspended'.
>
> - If the suspend callback returns -EBUSY or -EAGAIN, the device's runtime PM status remains 'active', which means that the device \_must\_ be fully operational afterwards.
>
> - If the suspend callback returns an error code different from -EBUSY and -EAGAIN, the PM core regards this as a fatal error and will refuse to run the helper functions described in Section 4 for the device until its status is directly set to  either 'active', or 'suspended' (the PM core provides special helper functions for this purpose).

In particular, if the driver requires remote wakeup capability (i.e. hardware mechanism allowing the device to request a change of its power state, such as PCI PME) for proper functioning and device_can_wakeup() returns 'false' for the device, then -&gt;runtime_suspend() should return -EBUSY.  On the other hand, if device_can_wakeup() returns 'true' for the device and the device is put into a low-power state during the execution of the suspend callback, it is expected that remote wakeup will be enabled for the device.  Generally, remote wakeup should be enabled for all input devices put into low-power states at run time.

The subsystem-level resume callback, if present, is **entirely responsible** for handling the resume of the device as appropriate, which may, but need not include executing the device driver's own -&gt;runtime_resume() callback (from the PM core's point of view it is not necessary to implement a -&gt;runtime_resume() callback in a device driver as long as the subsystem-level resume callback knows what to do to handle the device).

> - Once the subsystem-level resume callback (or the driver resume callback, if invoked directly) has completed successfully, the PM core regards the device as fully operational, which means that the device \_must\_ be able to complete I/O operations as needed.  The runtime PM status of the device is then 'active'.
>
> - If the resume callback returns an error code, the PM core regards this as a fatal error and will refuse to run the helper functions described in Section 4 for the device, until its status is directly set to either 'active', or 'suspended' (by means of special helper functions provided by the PM core for this purpose).

The idle callback (a subsystem-level one, if present, or the driver one) is executed by the PM core whenever the device appears to be idle, which is indicated to the PM core by two counters, the device's usage counter and the counter of 'active' children of the device.

> - If any of these counters is decreased using a helper function provided by the PM core and it turns out to be equal to zero, the other counter is checked.  If that counter also is equal to zero, the PM core executes the idle callback with the device as its argument.

The action performed by the idle callback is totally dependent on the subsystem (or driver) in question, but the expected and recommended action is to check if the device can be suspended (i.e. if all of the conditions necessary for suspending the device are satisfied) and to queue up a suspend request for the device in that case.  If there is no idle callback, or if the callback returns 0, then the PM core will attempt to carry out a runtime suspend of the device, also respecting devices configured for autosuspend.  In essence this means a call to pm_runtime_autosuspend(). To prevent this (for example, if the callback routine has started a delayed suspend), the routine must return a non-zero value.  Negative error return codes are ignored by the PM core.

The helper functions provided by the PM core, described in Section 4, guarantee that the following constraints are met with respect to runtime PM callbacks for one device:

1. The callbacks are mutually exclusive (e.g. it is forbidden to execute -&gt;runtime_suspend() in parallel with -&gt;runtime_resume() or with another instance of -&gt;runtime_suspend() for the same device) with the exception that -&gt;runtime_suspend() or -&gt;runtime_resume() can be executed in parallel with -&gt;runtime_idle() (although -&gt;runtime_idle() will not be started while any of the other callbacks is being executed for the same device).

2. -&gt;runtime_idle() and -&gt;runtime_suspend() can only be executed for 'active' devices (i.e. the PM core will only execute -&gt;runtime_idle() or -&gt;runtime_suspend() for the devices the runtime PM status of which is 'active').

3. -&gt;runtime_idle() and -&gt;runtime_suspend() can only be executed for a device the usage counter of which is equal to zero \_and\_ either the counter of 'active' children of which is equal to zero, or the 'power.ignore_children' flag of which is set.

4. -&gt;runtime_resume() can only be executed for 'suspended' devices  (i.e. the PM core will only execute -&gt;runtime_resume() for the devices the runtime PM status of which is 'suspended').

Additionally, the helper functions provided by the PM core obey the following rules:

> - If -&gt;runtime_suspend() is about to be executed or there's a pending request to execute it, -&gt;runtime_idle() will not be executed for the same device.
>
> - A request to execute or to schedule the execution of -&gt;runtime_suspend() will cancel any pending requests to execute -&gt;runtime_idle() for the same device.
>
> - If -&gt;runtime_resume() is about to be executed or there's a pending request to execute it, the other callbacks will not be executed for the same device.
>
> - A request to execute -&gt;runtime_resume() will cancel any pending or scheduled requests to execute the other callbacks for the same device, except for scheduled autosuspends.

<a id="rst-runtime-pm-device-fields"></a>

## 3. Runtime PM Device Fields

The following device runtime PM fields are present in 'struct dev_pm_info', as defined in include/linux/pm.h:

> - **`struct timer_list suspend_timer;`**
>
>   - timer used for scheduling (delayed) suspend and autosuspend requests
>
> - **`unsigned long timer_expires;`**
>
>   - timer expiration time, in jiffies (if this is different from zero, the timer is running and will expire at that time, otherwise the timer is not running)
>
> - **`struct work_struct work;`**
>
>   - work structure used for queuing up requests (i.e. work items in pm_wq)
>
> - **`wait_queue_head_t wait_queue;`**
>
>   - wait queue used if any of the helper functions needs to wait for another one to complete
>
> - **`spinlock_t lock;`**
>
>   - lock used for synchronization
>
> - **`atomic_t usage_count;`**
>
>   - the usage counter of the device
>
> - **`atomic_t child_count;`**
>
>   - the count of 'active' children of the device
>
> - **`unsigned int ignore_children;`**
>
>   - if set, the value of child_count is ignored (but still updated)
>
> - **`unsigned int disable_depth;`**
>
>   - used for disabling the helper functions (they work normally if this is equal to zero); the initial value of it is 1 (i.e. runtime PM is initially disabled for all devices)
>
> - **`int runtime_error;`**
>
>   - if set, there was a fatal error (one of the callbacks returned error code as described in Section 2), so the helper functions will not work until this flag is cleared; this is the error code returned by the failing callback
>
> - **`unsigned int idle_notification;`**
>
>   - if set, -&gt;runtime_idle() is being executed
>
> - **`unsigned int request_pending;`**
>
>   - if set, there's a pending request (i.e. a work item queued up into pm_wq)
>
> - **`enum rpm_request request;`**
>
>   - type of request that's pending (valid if request_pending is set)
>
> - **`unsigned int deferred_resume;`**
>
>   - set if -&gt;runtime_resume() is about to be run while -&gt;runtime_suspend() is being executed for that device and it is not practical to wait for the suspend to complete; means "start a resume as soon as you've suspended"
>
> - **`enum rpm_status runtime_status;`**
>
>   - the runtime PM status of the device; this field's initial value is RPM_SUSPENDED, which means that each device is initially regarded by the PM core as 'suspended', regardless of its real hardware status
>
> - **`enum rpm_status last_status;`**
>
>   - the last runtime PM status of the device captured before disabling runtime PM for it (invalid initially and when disable_depth is 0)
>
> - **`unsigned int runtime_auto;`**
>
>   - if set, indicates that the user space has allowed the device driver to power manage the device at run time via the /sys/devices/.../power/control `interface;` it may only be modified with the help of the pm_runtime_allow() and pm_runtime_forbid() helper functions
>
> - **`unsigned int no_callbacks;`**
>
>   - indicates that the device does not use the runtime PM callbacks (see Section 8); it may be modified only by the pm_runtime_no_callbacks() helper function
>
> - **`unsigned int irq_safe;`**
>
>   - indicates that the -&gt;runtime_suspend() and -&gt;runtime_resume() callbacks will be invoked with the spinlock held and interrupts disabled
>
> - **`unsigned int use_autosuspend;`**
>
>   - indicates that the device's driver supports delayed autosuspend (see Section 9); it may be modified only by the pm_runtime\{\_dont\}\_use_autosuspend() helper functions
>
> - **`unsigned int timer_autosuspends;`**
>
>   - indicates that the PM core should attempt to carry out an autosuspend when the timer expires rather than a normal suspend
>
> - **`int autosuspend_delay;`**
>
>   - the delay time (in milliseconds) to be used for autosuspend
>
> - **`unsigned long last_busy;`**
>
>   - the time (in jiffies) when the pm_runtime_mark_last_busy() helper function was last called for this device; used in calculating inactivity periods for autosuspend

All of the above fields are members of the 'power' member of 'struct device'.

<a id="rst-runtime-pm-device-helper-functions"></a>

## 4. Runtime PM Device Helper Functions

The following runtime PM helper functions are defined in drivers/base/power/runtime.c and include/linux/pm_runtime.h:

> - **`void pm_runtime_init(struct device *dev);`**
>
>   - initialize the device runtime PM fields in 'struct dev_pm_info'
>
> - **`void pm_runtime_remove(struct device *dev);`**
>
>   - make sure that the runtime PM of the device will be disabled after removing the device from device hierarchy
>
> - **`int pm_runtime_idle(struct device *dev);`**
>
>   - execute the subsystem-level idle callback for the device; returns an error code on failure, where -EINPROGRESS means that -&gt;runtime_idle() is already being executed; if there is no callback or the callback returns 0 then run pm_runtime_autosuspend(dev) and return its result
>
> - **`int pm_runtime_suspend(struct device *dev);`**
>
>   - execute the subsystem-level suspend callback for the device; returns 0 on success, 1 if the device's runtime PM status was already 'suspended', or error code on failure, where -EAGAIN or -EBUSY means it is safe to attempt to suspend the device again in future and -EACCES means that 'power.disable_depth' is different from 0
>
> - **`int pm_runtime_autosuspend(struct device *dev);`**
>
>   - same as pm_runtime_suspend() except that a call to pm_runtime_mark_last_busy() is made and an autosuspend is scheduled for the appropriate time and 0 is returned
>
> - **`int pm_runtime_resume(struct device *dev);`**
>
>   - execute the subsystem-level resume callback for the device; returns 0 on success, 1 if the device's runtime PM status is already 'active' (also if 'power.disable_depth' is nonzero, but the status was 'active' when it was changing from 0 to 1) or error code on failure, where -EAGAIN means it may be safe to attempt to resume the device again in future, but 'power.runtime_error' should be checked additionally, and -EACCES means that the callback could not be run, because 'power.disable_depth' was different from 0
>
> - **`int pm_runtime_resume_and_get(struct device *dev);`**
>
>   - run pm_runtime_resume(dev) and if successful, increment the device's usage counter; returns 0 on success (whether or not the device's runtime PM status was already 'active') or the error code from pm_runtime_resume() on failure.
>
> - **`int pm_request_idle(struct device *dev);`**
>
>   - submit a request to execute the subsystem-level idle callback for the device (the request is represented by a work item in pm_wq); returns 0 on success or error code if the request has not been queued up
>
> - **`int pm_request_autosuspend(struct device *dev);`**
>
>   - Call pm_runtime_mark_last_busy() and schedule the execution of the subsystem-level suspend callback for the device when the autosuspend delay expires
>
> - **`int pm_schedule_suspend(struct device *dev, unsigned int delay);`**
>
>   - schedule the execution of the subsystem-level suspend callback for the device in future, where 'delay' is the time to wait before queuing up a suspend work item in pm_wq, in milliseconds (if 'delay' is zero, the work item is queued up immediately); returns 0 on success, 1 if the device's PM runtime status was already 'suspended', or error code if the request hasn't been scheduled (or queued up if 'delay' is 0); if the execution of -&gt;runtime_suspend() is already scheduled and not yet expired, the new value of 'delay' will be used as the time to wait
>
> - **`int pm_request_resume(struct device *dev);`**
>
>   - submit a request to execute the subsystem-level resume callback for the device (the request is represented by a work item in pm_wq); returns 0 on success, 1 if the device's runtime PM status was already 'active', or error code if the request hasn't been queued up
>
> - **`void pm_runtime_get_noresume(struct device *dev);`**
>
>   - increment the device's usage counter
>
> - **`int pm_runtime_get(struct device *dev);`**
>
>   - increment the device's usage counter, run pm_request_resume(dev) and return its result
>
> - **`int pm_runtime_get_sync(struct device *dev);`**
>
>   - increment the device's usage counter, run pm_runtime_resume(dev) and return its result; note that it does not drop the device's usage counter on errors, so consider using pm_runtime_resume_and_get() instead of it, especially if its return value is checked by the caller, as this is likely to result in cleaner code.
>
> - **`int pm_runtime_get_if_in_use(struct device *dev);`**
>
>   - return -EINVAL if 'power.disable_depth' is nonzero; otherwise, if the runtime PM status is RPM_ACTIVE and the runtime PM usage counter is nonzero, increment the counter and return 1; otherwise return 0 without changing the counter
>
> - **`int pm_runtime_get_if_active(struct device *dev);`**
>
>   - return -EINVAL if 'power.disable_depth' is nonzero; otherwise, if the runtime PM status is RPM_ACTIVE, increment the counter and return 1; otherwise return 0 without changing the counter
>
> - **`void pm_runtime_put_noidle(struct device *dev);`**
>
>   - decrement the device's usage counter
>
> - **`int pm_runtime_put(struct device *dev);`**
>
>   - decrement the device's usage counter; if the result is 0 then run pm_request_idle(dev) and return its result
>
> - **`int pm_runtime_put_autosuspend(struct device *dev);`**
>
>   - set the power.last_busy field to the current time and decrement the device's usage counter; if the result is 0 then run pm_request_autosuspend(dev) and return its result
>
> - **`int __pm_runtime_put_autosuspend(struct device *dev);`**
>
>   - decrement the device's usage counter; if the result is 0 then run pm_request_autosuspend(dev) and return its result
>
> - **`int pm_runtime_put_sync(struct device *dev);`**
>
>   - decrement the device's usage counter; if the result is 0 then run pm_runtime_idle(dev) and return its result
>
> - **`int pm_runtime_put_sync_suspend(struct device *dev);`**
>
>   - decrement the device's usage counter; if the result is 0 then run pm_runtime_suspend(dev) and return its result
>
> - **`int pm_runtime_put_sync_autosuspend(struct device *dev);`**
>
>   - set the power.last_busy field to the current time and decrement the device's usage counter; if the result is 0 then run pm_runtime_autosuspend(dev) and return its result
>
> - **`void pm_runtime_enable(struct device *dev);`**
>
>   - decrement the device's 'power.disable_depth' field; if that field is equal to zero, the runtime PM helper functions can execute subsystem-level callbacks described in Section 2 for the device
>
> - **`int pm_runtime_disable(struct device *dev);`**
>
>   - increment the device's 'power.disable_depth' field (if the value of that field was previously zero, this prevents subsystem-level runtime PM callbacks from being run for the device), make sure that all of the pending runtime PM operations on the device are either completed or canceled; returns 1 if there was a resume request pending and it was necessary to execute the subsystem-level resume callback for the device to satisfy that request, otherwise 0 is returned
>
> - **`void pm_runtime_barrier(struct device *dev);`**
>
>   - check if there's a resume request pending for the device and resume it (synchronously) in that case, cancel any other pending runtime PM requests regarding it and wait for all runtime PM operations on it in progress to complete
>
> - **`void pm_suspend_ignore_children(struct device *dev, bool enable);`**
>
>   - set/unset the power.ignore_children flag of the device
>
> - **`int pm_runtime_set_active(struct device *dev);`**
>
>   - clear the device's 'power.runtime_error' flag, set the device's runtime PM status to 'active' and update its parent's counter of 'active' children as appropriate (it is only valid to use this function if 'power.runtime_error' is set or 'power.disable_depth' is greater than zero); it will fail and return error code if the device has a parent which is not active and the 'power.ignore_children' flag of which is unset
>
> - **`void pm_runtime_set_suspended(struct device *dev);`**
>
>   - clear the device's 'power.runtime_error' flag, set the device's runtime PM status to 'suspended' and update its parent's counter of 'active' children as appropriate (it is only valid to use this function if 'power.runtime_error' is set or 'power.disable_depth' is greater than zero)
>
> - **`bool pm_runtime_active(struct device *dev);`**
>
>   - return true if the device's runtime PM status is 'active' or its 'power.disable_depth' field is not equal to zero, or false otherwise
>
> - **`bool pm_runtime_suspended(struct device *dev);`**
>
>   - return true if the device's runtime PM status is 'suspended' and its 'power.disable_depth' field is equal to zero, or false otherwise
>
> - **`bool pm_runtime_status_suspended(struct device *dev);`**
>
>   - return true if the device's runtime PM status is 'suspended'
>
> - **`void pm_runtime_no_callbacks(struct device *dev);`**
>
>   - set the power.no_callbacks flag for the device and remove the runtime PM attributes from /sys/devices/.../power (or prevent them from being added when the device is registered)
>
> - **`void pm_runtime_irq_safe(struct device *dev);`**
>
>   - set the power.irq_safe flag for the device, causing the runtime-PM callbacks to be invoked with interrupts off
>
> - **`bool pm_runtime_is_irq_safe(struct device *dev);`**
>
>   - return true if power.irq_safe flag was set for the device, causing the runtime-PM callbacks to be invoked with interrupts off
>
> - **`void pm_runtime_mark_last_busy(struct device *dev);`**
>
>   - set the power.last_busy field to the current time
>
> - **`void pm_runtime_use_autosuspend(struct device *dev);`**
>
>   - set the power.use_autosuspend flag, enabling autosuspend delays; call pm_runtime_get_sync if the flag was previously cleared and power.autosuspend_delay is negative
>
> - **`void pm_runtime_dont_use_autosuspend(struct device *dev);`**
>
>   - clear the power.use_autosuspend flag, disabling autosuspend delays; decrement the device's usage counter if the flag was previously set and power.autosuspend_delay is negative; call pm_runtime_idle
>
> - **`void pm_runtime_set_autosuspend_delay(struct device *dev, int delay);`**
>
>   - set the power.autosuspend_delay value to 'delay' (expressed in milliseconds); if 'delay' is negative then runtime suspends are prevented; if power.use_autosuspend is set, pm_runtime_get_sync may be called or the device's usage counter may be decremented and pm_runtime_idle called depending on if power.autosuspend_delay is changed to or from a negative value; if power.use_autosuspend is clear, pm_runtime_idle is called
>
> - **`unsigned long pm_runtime_autosuspend_expiration(struct device *dev);`**
>
>   - calculate the time when the current autosuspend delay period will expire, based on power.last_busy and power.autosuspend_delay; if the delay time is 1000 ms or larger then the expiration time is rounded up to the nearest second; returns 0 if the delay period has already expired or power.use_autosuspend isn't set, otherwise returns the expiration time in jiffies

It is safe to execute the following helper functions from interrupt context:

- pm_request_idle()

- pm_request_autosuspend()

- pm_schedule_suspend()

- pm_request_resume()

- pm_runtime_get_noresume()

- pm_runtime_get()

- pm_runtime_put_noidle()

- pm_runtime_put()

- pm_runtime_put_autosuspend()

- \__pm_runtime_put_autosuspend()

- pm_runtime_enable()

- pm_suspend_ignore_children()

- pm_runtime_set_active()

- pm_runtime_set_suspended()

- pm_runtime_suspended()

- pm_runtime_mark_last_busy()

- pm_runtime_autosuspend_expiration()

If pm_runtime_irq_safe() has been called for a device then the following helper functions may also be used in interrupt context:

- pm_runtime_idle()

- pm_runtime_suspend()

- pm_runtime_autosuspend()

- pm_runtime_resume()

- pm_runtime_get_sync()

- pm_runtime_put_sync()

- pm_runtime_put_sync_suspend()

- pm_runtime_put_sync_autosuspend()

<a id="rst-runtime-pm-initialization-device-probing-and-removal"></a>

## 5. Runtime PM Initialization, Device Probing and Removal

Initially, the runtime PM is disabled for all devices, which means that the majority of the runtime PM helper functions described in Section 4 will return -EAGAIN until pm_runtime_enable() is called for the device.

In addition to that, the initial runtime PM status of all devices is 'suspended', but it need not reflect the actual physical state of the device. Thus, if the device is initially active (i.e. it is able to process I/O), its runtime PM status must be changed to 'active', with the help of pm_runtime_set_active(), before pm_runtime_enable() is called for the device.

However, if the device has a parent and the parent's runtime PM is enabled, calling pm_runtime_set_active() for the device will affect the parent, unless the parent's 'power.ignore_children' flag is set.  Namely, in that case the parent won't be able to suspend at run time, using the PM core's helper functions, as long as the child's status is 'active', even if the child's runtime PM is still disabled (i.e. pm_runtime_enable() hasn't been called for the child yet or pm_runtime_disable() has been called for it).  For this reason, once pm_runtime_set_active() has been called for the device, pm_runtime_enable() should be called for it too as soon as reasonably possible or its runtime PM status should be changed back to 'suspended' with the help of pm_runtime_set_suspended().

If the default initial runtime PM status of the device (i.e. 'suspended') reflects the actual state of the device, its bus type's or its driver's -&gt;probe() callback will likely need to wake it up using one of the PM core's helper functions described in Section 4.  In that case, pm_runtime_resume() should be used.  Of course, for this purpose the device's runtime PM has to be enabled earlier by calling pm_runtime_enable().

Note, if the device may execute pm_runtime calls during the probe (such as if it is registered with a subsystem that may call back in) then the pm_runtime_get_sync() call paired with a pm_runtime_put() call will be appropriate to ensure that the device is not put back to sleep during the probe. This can happen with systems such as the network device layer.

It may be desirable to suspend the device once -&gt;probe() has finished. Therefore the driver core uses the asynchronous pm_request_idle() to submit a request to execute the subsystem-level idle callback for the device at that time.  A driver that makes use of the runtime autosuspend feature may want to update the last busy mark before returning from -&gt;probe().

Moreover, the driver core prevents runtime PM callbacks from racing with the bus notifier callback in \__device_release_driver(), which is necessary because the notifier is used by some subsystems to carry out operations affecting the runtime PM functionality.  It does so by calling pm_runtime_get_sync() before driver_sysfs_remove() and the BUS_NOTIFY_UNBIND_DRIVER notifications.  This resumes the device if it's in the suspended state and prevents it from being suspended again while those routines are being executed.

To allow bus types and drivers to put devices into the suspended state by calling pm_runtime_suspend() from their -&gt;remove() routines, the driver core executes pm_runtime_put_sync() after running the BUS_NOTIFY_UNBIND_DRIVER notifications in \__device_release_driver().  This requires bus types and drivers to make their -&gt;remove() callbacks avoid races with runtime PM directly, but it also allows more flexibility in the handling of devices during the removal of their drivers.

Drivers in -&gt;remove() callback should undo the runtime PM changes done in -&gt;probe(). Usually this means calling pm_runtime_disable(), pm_runtime_dont_use_autosuspend() etc.

The user space can effectively disallow the driver of the device to power manage it at run time by changing the value of its /sys/devices/.../power/control attribute to "on", which causes pm_runtime_forbid() to be called.  In principle, this mechanism may also be used by the driver to effectively turn off the runtime power management of the device until the user space turns it on. Namely, during the initialization the driver can make sure that the runtime PM status of the device is 'active' and call pm_runtime_forbid().  It should be noted, however, that if the user space has already intentionally changed the value of /sys/devices/.../power/control to "auto" to allow the driver to power manage the device at run time, the driver may confuse it by using pm_runtime_forbid() this way.

<a id="rst-runtime-pm-and-system-sleep"></a>

## 6. Runtime PM and System Sleep

Runtime PM and system sleep (i.e., system suspend and hibernation, also known as suspend-to-RAM and suspend-to-disk) interact with each other in a couple of ways.  If a device is active when a system sleep starts, everything is straightforward.  But what should happen if the device is already suspended?

The device may have different wake-up settings for runtime PM and system sleep. For example, remote wake-up may be enabled for runtime suspend but disallowed for system sleep (device_may_wakeup(dev) returns 'false').  When this happens, the subsystem-level system suspend callback is responsible for changing the device's wake-up setting (it may leave that to the device driver's system suspend routine).  It may be necessary to resume the device and suspend it again in order to do so.  The same is true if the driver uses different power levels or other settings for runtime suspend and system sleep.

During system resume, the simplest approach is to bring all devices back to full power, even if they had been suspended before the system suspend began.  There are several reasons for this, including:

> - The device might need to switch power levels, wake-up settings, etc.
>
> - Remote wake-up events might have been lost by the firmware.
>
> - The device's children may need the device to be at full power in order to resume themselves.
>
> - The driver's idea of the device state may not agree with the device's physical state.  This can happen during resume from hibernation.
>
> - The device might need to be reset.
>
> - Even though the device was suspended, if its usage counter was &gt; 0 then most likely it would need a runtime resume in the near future anyway.

If the device had been suspended before the system suspend began and it's brought back to full power during resume, then its runtime PM status will have to be updated to reflect the actual post-system sleep status.  The way to do this is:

> - pm_runtime_disable(dev);
>
> - pm_runtime_set_active(dev);
>
> - pm_runtime_enable(dev);

The PM core always increments the runtime usage counter before calling the -&gt;suspend() callback and decrements it after calling the -&gt;resume() callback. Hence disabling runtime PM temporarily like this will not cause any runtime suspend attempts to be permanently lost.  If the usage count goes to zero following the return of the -&gt;resume() callback, the -&gt;runtime_idle() callback will be invoked as usual.

On some systems, however, system sleep is not entered through a global firmware or hardware operation.  Instead, all hardware components are put into low-power states directly by the kernel in a coordinated way.  Then, the system sleep state effectively follows from the states the hardware components end up in and the system is woken up from that state by a hardware interrupt or a similar mechanism entirely under the kernel's control.  As a result, the kernel never gives control away and the states of all devices during resume are precisely known to it.  If that is the case and none of the situations listed above takes place (in particular, if the system is not waking up from hibernation), it may be more efficient to leave the devices that had been suspended before the system suspend began in the suspended state.

To this end, the PM core provides a mechanism allowing some coordination between different levels of device hierarchy.  Namely, if a system suspend .prepare() callback returns a positive number for a device, that indicates to the PM core that the device appears to be runtime-suspended and its state is fine, so it may be left in runtime suspend provided that all of its descendants are also left in runtime suspend.  If that happens, the PM core will not execute any system suspend and resume callbacks for all of those devices, except for the .complete() callback, which is then entirely responsible for handling the device as appropriate.  This only applies to system suspend transitions that are not related to hibernation (see [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md) for more information).

The PM core does its best to reduce the probability of race conditions between the runtime PM and system suspend/resume (and hibernation) callbacks by carrying out the following operations:

> - During system suspend pm_runtime_get_noresume() is called for every device right before executing the subsystem-level .prepare() callback for it and pm_runtime_barrier() is called for every device right before executing the subsystem-level .suspend() callback for it.  In addition to that, the PM core disables runtime PM for every device right before executing the subsystem-level .suspend_late() callback for it.
>
> - During system resume pm_runtime_enable() and pm_runtime_put() are called for every device right after executing the subsystem-level .resume_early() callback and right after executing the subsystem-level .complete() callback for it, respectively.

<a id="rst-generic-subsystem-callbacks"></a>

## 7. Generic subsystem callbacks

Subsystems may wish to conserve code space by using the set of generic power management callbacks provided by the PM core, defined in driver/base/power/generic_ops.c:

> - **`int pm_generic_runtime_suspend(struct device *dev);`**
>
>   - invoke the -&gt;runtime_suspend() callback provided by the driver of this device and return its result, or return 0 if not defined
>
> - **`int pm_generic_runtime_resume(struct device *dev);`**
>
>   - invoke the -&gt;runtime_resume() callback provided by the driver of this device and return its result, or return 0 if not defined
>
> - **`int pm_generic_suspend(struct device *dev);`**
>
>   - if the device has not been suspended at run time, invoke the -&gt;suspend() callback provided by its driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_suspend_noirq(struct device *dev);`**
>
>   - if pm_runtime_suspended(dev) returns "false", invoke the -&gt;suspend_noirq() callback provided by the device's driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_resume(struct device *dev);`**
>
>   - invoke the -&gt;resume() callback provided by the driver of this device and, if successful, change the device's runtime PM status to 'active'
>
> - **`int pm_generic_resume_noirq(struct device *dev);`**
>
>   - invoke the -&gt;resume_noirq() callback provided by the driver of this device
>
> - **`int pm_generic_freeze(struct device *dev);`**
>
>   - if the device has not been suspended at run time, invoke the -&gt;freeze() callback provided by its driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_freeze_noirq(struct device *dev);`**
>
>   - if pm_runtime_suspended(dev) returns "false", invoke the -&gt;freeze_noirq() callback provided by the device's driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_thaw(struct device *dev);`**
>
>   - if the device has not been suspended at run time, invoke the -&gt;thaw() callback provided by its driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_thaw_noirq(struct device *dev);`**
>
>   - if pm_runtime_suspended(dev) returns "false", invoke the -&gt;thaw_noirq() callback provided by the device's driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_poweroff(struct device *dev);`**
>
>   - if the device has not been suspended at run time, invoke the -&gt;poweroff() callback provided by its driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_poweroff_noirq(struct device *dev);`**
>
>   - if pm_runtime_suspended(dev) returns "false", run the -&gt;poweroff_noirq() callback provided by the device's driver and return its result, or return 0 if not defined
>
> - **`int pm_generic_restore(struct device *dev);`**
>
>   - invoke the -&gt;restore() callback provided by the driver of this device and, if successful, change the device's runtime PM status to 'active'
>
> - **`int pm_generic_restore_noirq(struct device *dev);`**
>
>   - invoke the -&gt;restore_noirq() callback provided by the device's driver

These functions are the defaults used by the PM core if a subsystem doesn't provide its own callbacks for -&gt;runtime_idle(), -&gt;runtime_suspend(), -&gt;runtime_resume(), -&gt;suspend(), -&gt;suspend_noirq(), -&gt;resume(), -&gt;resume_noirq(), -&gt;freeze(), -&gt;freeze_noirq(), -&gt;thaw(), -&gt;thaw_noirq(), -&gt;poweroff(), -&gt;poweroff_noirq(), -&gt;restore(), -&gt;restore_noirq() in the subsystem-level dev_pm_ops structure.

Device drivers that wish to use the same function as a system suspend, freeze, poweroff and runtime suspend callback, and similarly for system resume, thaw, restore, and runtime resume, can achieve similar behaviour with the help of the DEFINE_RUNTIME_DEV_PM_OPS() defined in include/linux/pm_runtime.h (possibly setting its last argument to NULL).

<a id="rst-no-callback-devices"></a>

## 8. "No-Callback" Devices

Some "devices" are only logical sub-devices of their parent and cannot be power-managed on their own.  (The prototype example is a USB interface.  Entire USB devices can go into low-power mode or send wake-up requests, but neither is possible for individual interfaces.)  The drivers for these devices have no need of runtime PM callbacks; if the callbacks did exist, -&gt;runtime_suspend() and -&gt;runtime_resume() would always return 0 without doing anything else and -&gt;runtime_idle() would always call pm_runtime_suspend().

Subsystems can tell the PM core about these devices by calling pm_runtime_no_callbacks().  This should be done after the device structure is initialized and before it is registered (although after device registration is also okay).  The routine will set the device's power.no_callbacks flag and prevent the non-debugging runtime PM sysfs attributes from being created.

When power.no_callbacks is set, the PM core will not invoke the -&gt;runtime_idle(), -&gt;runtime_suspend(), or -&gt;runtime_resume() callbacks. Instead it will assume that suspends and resumes always succeed and that idle devices should be suspended.

As a consequence, the PM core will never directly inform the device's subsystem or driver about runtime power changes.  Instead, the driver for the device's parent must take responsibility for telling the device's driver when the parent's power state changes.

Note that, in some cases it may not be desirable for subsystems/drivers to call pm_runtime_no_callbacks() for their devices. This could be because a subset of the runtime PM callbacks needs to be implemented, a platform dependent PM domain could get attached to the device or that the device is power managed through a supplier device link. For these reasons and to avoid boilerplate code in subsystems/drivers, the PM core allows runtime PM callbacks to be unassigned. More precisely, if a callback pointer is NULL, the PM core will act as though there was a callback and it returned 0.

<a id="rst-autosuspend-or-automatically-delayed-suspends"></a>

## 9. Autosuspend, or automatically-delayed suspends

Changing a device's power state isn't free; it requires both time and energy. A device should be put in a low-power state only when there's some reason to think it will remain in that state for a substantial time.  A common heuristic says that a device which hasn't been used for a while is liable to remain unused; following this advice, drivers should not allow devices to be suspended at runtime until they have been inactive for some minimum period.  Even when the heuristic ends up being non-optimal, it will still prevent devices from "bouncing" too rapidly between low-power and full-power states.

The term "autosuspend" is an historical remnant.  It doesn't mean that the device is automatically suspended (the subsystem or driver still has to call the appropriate PM routines); rather it means that runtime suspends will automatically be delayed until the desired period of inactivity has elapsed.

Inactivity is determined based on the power.last_busy field. The desired length of the inactivity period is a matter of policy.  Subsystems can set this length initially by calling pm_runtime_set_autosuspend_delay(), but after device registration the length should be controlled by user space, using the /sys/devices/.../power/autosuspend_delay_ms attribute.

In order to use autosuspend, subsystems or drivers must call pm_runtime_use_autosuspend() (preferably before registering the device), and thereafter they should use the various `*_autosuspend()` helper functions instead of the non-autosuspend counterparts:



```text
Instead of: pm_runtime_suspend    use: pm_runtime_autosuspend;
Instead of: pm_schedule_suspend   use: pm_request_autosuspend;
Instead of: pm_runtime_put        use: pm_runtime_put_autosuspend;
Instead of: pm_runtime_put_sync   use: pm_runtime_put_sync_autosuspend.
```

Drivers may also continue to use the non-autosuspend helper functions; they will behave normally, which means sometimes taking the autosuspend delay into account (see pm_runtime_idle). The autosuspend variants of the functions also call pm_runtime_mark_last_busy().

Under some circumstances a driver or subsystem may want to prevent a device from autosuspending immediately, even though the usage counter is zero and the autosuspend delay time has expired.  If the -&gt;runtime_suspend() callback returns -EAGAIN or -EBUSY, and if the next autosuspend delay expiration time is in the future (as it normally would be if the callback invoked pm_runtime_mark_last_busy()), the PM core will automatically reschedule the autosuspend.  The -&gt;runtime_suspend() callback can't do this rescheduling itself because no suspend requests of any kind are accepted while the device is suspending (i.e., while the callback is running).

The implementation is well suited for asynchronous use in interrupt contexts. However such use inevitably involves races, because the PM core can't synchronize -&gt;runtime_suspend() callbacks with the arrival of I/O requests. This synchronization must be handled by the driver, using its private lock. Here is a schematic pseudo-code example:



```text
foo_read_or_write(struct foo_priv *foo, void *data)
{
        lock(&foo->private_lock);
        add_request_to_io_queue(foo, data);
        if (foo->num_pending_requests++ == 0)
                pm_runtime_get(&foo->dev);
        if (!foo->is_suspended)
                foo_process_next_request(foo);
        unlock(&foo->private_lock);
}

foo_io_completion(struct foo_priv *foo, void *req)
{
        lock(&foo->private_lock);
        if (--foo->num_pending_requests == 0)
                pm_runtime_put_autosuspend(&foo->dev);
        else
                foo_process_next_request(foo);
        unlock(&foo->private_lock);
        /* Send req result back to the user ... */
}

int foo_runtime_suspend(struct device *dev)
{
        struct foo_priv foo = container_of(dev, ...);
        int ret = 0;

        lock(&foo->private_lock);
        if (foo->num_pending_requests > 0) {
                ret = -EBUSY;
        } else {
                /* ... suspend the device ... */
                foo->is_suspended = 1;
        }
        unlock(&foo->private_lock);
        return ret;
}

int foo_runtime_resume(struct device *dev)
{
        struct foo_priv foo = container_of(dev, ...);

        lock(&foo->private_lock);
        /* ... resume the device ... */
        foo->is_suspended = 0;
        pm_runtime_mark_last_busy(&foo->dev);
        if (foo->num_pending_requests > 0)
                foo_process_next_request(foo);
        unlock(&foo->private_lock);
        return 0;
}
```

The important point is that after foo_io_completion() asks for an autosuspend, the foo_runtime_suspend() callback may race with foo_read_or_write(). Therefore foo_runtime_suspend() has to check whether there are any pending I/O requests (while holding the private lock) before allowing the suspend to proceed.

In addition, the power.autosuspend_delay field can be changed by user space at any time.  If a driver cares about this, it can call pm_runtime_autosuspend_expiration() from within the -&gt;runtime_suspend() callback while holding its private lock.  If the function returns a nonzero value then the delay has not yet expired and the callback should return -EAGAIN.

---

# How to get s2ram working

_Peios Kernel / Internals / Power_

> 2006 Linus Torvalds 2006 Pavel Machek

<a id="rst-how-to-get-s2ram-working"></a>

2006 Linus Torvalds 2006 Pavel Machek

1. Check suspend.sf.net, program s2ram there has long whitelist of "known ok" machines, along with tricks to use on each one.

2. If that does not help, try reading tricks.txt and video.txt. Perhaps problem is as simple as broken module, and simple module unload can fix it.

3. You can use Linus' TRACE_RESUME infrastructure, described below.

<a id="rst-using-trace-resume"></a>

## Using TRACE_RESUME

I've been working at making the machines I have able to STR, and almost always it's a driver that is buggy. Thank God for the suspend/resume debugging - the thing that Chuck tried to disable. That's often the \_only\_ way to debug these things, and it's actually pretty powerful (but time-consuming - having to insert TRACE_RESUME() markers into the device driver that doesn't resume and recompile and reboot).

Anyway, the way to debug this for people who are interested (have a machine that doesn't boot) is:

> - enable PM_DEBUG, and PM_TRACE
>
> - use a script like this:
>
>
>
>   ```text
>   #!/bin/sh
>   sync
>   echo 1 > /sys/power/pm_trace
>   echo mem > /sys/power/state
>   ```
>
>   to suspend
>
> - if it doesn't come back up (which is usually the problem), reboot by holding the power button down, and look at the dmesg output for things like:
>
>
>
>   ```text
>   Magic number: 4:156:725
>   hash matches drivers/base/power/resume.c:28
>   hash matches device 0000:01:00.0
>   ```
>
>   which means that the last trace event was just before trying to resume device 0000:01:00.0. Then figure out what driver is controlling that device (lspci and /sys/devices/pci\* is your friend), and see if you can fix it, disable it, or trace into its resume function.
>
>   If no device matches the hash (or any matches appear to be false positives), the culprit may be a device from a loadable kernel module that is not loaded until after the hash is checked. You can check the hash against the current devices again after more modules are loaded using sysfs:
>
>
>
>   ```text
>   cat /sys/power/pm_trace_dev_match
>   ```

For example, the above happens to be the VGA device on my EVO, which I used to run with "radeonfb" (it's an ATI Radeon mobility). It turns out that "radeonfb" simply cannot resume that device - it tries to set the PLL's, and it just \_hangs\_. Using the regular VGA console and letting X resume it instead works fine.

<a id="rst-note"></a>

### NOTE

pm_trace uses the system's Real Time Clock (RTC) to save the magic number. Reason for this is that the RTC is the only reliably available piece of hardware during resume operations where a value can be set that will survive a reboot.

pm_trace is not compatible with asynchronous suspend, so it turns asynchronous suspend off (which may work around timing or ordering-sensitive bugs).

Consequence is that after a resume (even if it is successful) your system clock will have a value corresponding to the magic number instead of the correct date/time\! It is therefore advisable to use a program like ntp-date or rdate to reset the correct date/time from an external time source when using this trace option.

As the clock keeps ticking it is also essential that the reboot is done quickly after the resume failure. The trace option does not use the seconds or the low order bits of the minutes of the RTC, but a too long delay will corrupt the magic value.

---

# Debugging Kernel Shutdown Hangs with pstore

_Peios Kernel / Internals / Power_

> If the system hangs while shutting down, the kernel logs may need to be retrieved to debug the issue.

<a id="rst-debugging-kernel-shutdown-hangs-with-pstore"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

If the system hangs while shutting down, the kernel logs may need to be retrieved to debug the issue.

On systems that have a UART available, it is best to configure the kernel to use this UART for kernel console output.

If a UART isn't available, the `pstore` subsystem provides a mechanism to persist this data across a system reset, allowing it to be retrieved on the next boot.

<a id="rst-kernel-configuration"></a>

## Kernel Configuration

To enable `pstore` and enable saving kernel ring buffer logs, set the following kernel configuration options:

- `CONFIG_PSTORE=y`

- `CONFIG_PSTORE_CONSOLE=y`

Additionally, enable a backend to store the data. Depending upon your platform some potential options include:

- `CONFIG_EFI_VARS_PSTORE=y`

- `CONFIG_PSTORE_RAM=y`

- `CONFIG_CHROMEOS_PSTORE=y`

- `CONFIG_PSTORE_BLK=y`

<a id="rst-kernel-command-line-parameters"></a>

## Kernel Command-line Parameters

Add these parameters to your kernel command line:

- - **`printk.always_kmsg_dump=Y`**

    - - **Forces the kernel to dump the entire message buffer to pstore during**

        shutdown

- - **`efi_pstore.pstore_disable=N`**

    - For EFI-based systems, ensures the EFI backend is active

<a id="rst-userspace-interaction-and-log-retrieval"></a>

## Userspace Interaction and Log Retrieval

On the next boot after a hang, pstore logs will be available in the pstore filesystem (`/sys/fs/pstore`) and can be retrieved by userspace.

On systemd systems, the `systemd-pstore` service will help do the following:

1. Locate pstore data in `/sys/fs/pstore`

2. Read and save it to `/var/lib/systemd/pstore`

3. Clear pstore data for the next event

---

# Interaction of Suspend code (S3) with the CPU hotplug infrastructure

_Peios Kernel / Internals / Power_

> 2011 - 2014 Srivatsa S. Bhat <srivatsa.bhat@linux.vnet.ibm.com>

<a id="rst-interaction-of-suspend-code-s3-with-the-cpu-hotplug-infrastructure"></a>

- **(C)** 2011 - 2014 Srivatsa S. Bhat &lt;[srivatsa.bhat@linux.vnet.ibm.com](<mailto:srivatsa.bhat@linux.vnet.ibm.com>)&gt;

<a id="rst-i-differences-between-cpu-hotplug-and-suspend-to-ram"></a>

## I. Differences between CPU hotplug and Suspend-to-RAM

How does the regular CPU hotplug code differ from how the Suspend-to-RAM infrastructure uses it internally? And where do they share common code?

Well, a picture is worth a thousand words... So ASCII art follows :-)

\[This depicts the current design in the kernel, and focuses only on the interactions involving the freezer and CPU hotplug and also tries to explain the locking involved. It outlines the notifications involved as well. But please note that here, only the call paths are illustrated, with the aim of describing where they take different paths and where they share code. What happens when regular CPU hotplug and Suspend-to-RAM race with each other is not depicted here.\]

On a high level, the suspend-resume cycle goes like this:



```text
|Freeze| -> |Disable nonboot| -> |Do suspend| -> |Enable nonboot| -> |Thaw |
|tasks |    |     cpus      |    |          |    |     cpus     |    |tasks|
```

More details follow:



```text
                              Suspend call path
                              -----------------

                                Write 'mem' to
                              /sys/power/state
                                  sysfs file
                                      |
                                      v
                             Acquire system_transition_mutex lock
                                      |
                                      v
                           Send PM_SUSPEND_PREPARE
                                 notifications
                                      |
                                      v
                                 Freeze tasks
                                      |
                                      |
                                      v
                            freeze_secondary_cpus()
                                 /* start */
                                      |
                                      v
                          Acquire cpu_add_remove_lock
                                      |
                                      v
                           Iterate over CURRENTLY
                                 online CPUs
                                      |
                                      |
                                      |                ----------
                                      v                          | L
           ======>               _cpu_down()                     |
          |              [This takes cpuhotplug.lock             |
Common    |               before taking down the CPU             |
 code     |               and releases it when done]             | O
          |            While it is at it, notifications          |
          |            are sent when notable events occur,       |
           ======>     by running all registered callbacks.      |
                                      |                          | O
                                      |                          |
                                      |                          |
                                      v                          |
                          Note down these cpus in                | P
                              frozen_cpus mask         ----------
                                      |
                                      v
                         Disable regular cpu hotplug
                      by increasing cpu_hotplug_disabled
                                      |
                                      v
                          Release cpu_add_remove_lock
                                      |
                                      v
                     /* freeze_secondary_cpus() complete */
                                      |
                                      v
                                 Do suspend
```

Resuming back is likewise, with the counterparts being (in the order of execution during resume):

- thaw_secondary_cpus() which involves:



  ```text
  |  Acquire cpu_add_remove_lock
  |  Decrease cpu_hotplug_disabled, thereby enabling regular cpu hotplug
  |  Call _cpu_up() [for all those cpus in the frozen_cpus mask, in a loop]
  |  Release cpu_add_remove_lock
  v
  ```

- thaw tasks

- send PM_POST_SUSPEND notifications

- Release system_transition_mutex lock.

It is to be noted here that the system_transition_mutex lock is acquired at the very beginning, when we are just starting out to suspend, and then released only after the entire cycle is complete (i.e., suspend + resume).



```text
                        Regular CPU hotplug call path
                        -----------------------------

                              Write 0 (or 1) to
                     /sys/devices/system/cpu/cpu*/online
                                  sysfs file
                                      |
                                      |
                                      v
                                  cpu_down()
                                      |
                                      v
                         Acquire cpu_add_remove_lock
                                      |
                                      v
                        If cpu_hotplug_disabled > 0
                              return gracefully
                                      |
                                      |
                                      v
           ======>                _cpu_down()
          |              [This takes cpuhotplug.lock
Common    |               before taking down the CPU
 code     |               and releases it when done]
          |            While it is at it, notifications
          |           are sent when notable events occur,
           ======>    by running all registered callbacks.
                                      |
                                      |
                                      v
                        Release cpu_add_remove_lock
                             [That's it!, for
                            regular CPU hotplug]
```

So, as can be seen from the two diagrams (the parts marked as "Common code"), regular CPU hotplug and the suspend code path converge at the \_cpu_down() and \_cpu_up() functions. They differ in the arguments passed to these functions, in that during regular CPU hotplug, 0 is passed for the 'tasks_frozen' argument. But during suspend, since the tasks are already frozen by the time the non-boot CPUs are offlined or onlined, the \_cpu\_\*() functions are called with the 'tasks_frozen' argument set to 1. \[See below for some known issues regarding this.\]

<a id="rst-important-files-and-functions-entry-points"></a>

### Important files and functions/entry points:

- kernel/power/process.c : freeze_processes(), thaw_processes()

- kernel/power/suspend.c : suspend_prepare(), suspend_enter(), suspend_finish()

- kernel/cpu.c: cpu\_\[up\|down\](), \_cpu\_\[up\|down\](), \[disable\|enable\]\_nonboot_cpus()

<a id="rst-ii-what-are-the-issues-involved-in-cpu-hotplug"></a>

### II. What are the issues involved in CPU hotplug?

There are some interesting situations involving CPU hotplug and microcode update on the CPUs, as discussed below:

\[Please bear in mind that the kernel requests the microcode images from userspace, using the request_firmware() function defined in drivers/base/firmware_loader/main.c\]

- **a.** When all the CPUs are identical:

  This is the most common situation and it is quite straightforward: we want to apply the same microcode revision to each of the CPUs. To give an example of x86, the collect_cpu_info() function defined in arch/x86/kernel/microcode_core.c helps in discovering the type of the CPU and thereby in applying the correct microcode revision to it. But note that the kernel does not maintain a common microcode image for the all CPUs, in order to handle case 'b' described below.

- **b.** When some of the CPUs are different than the rest:

  In this case since we probably need to apply different microcode revisions to different CPUs, the kernel maintains a copy of the correct microcode image for each CPU (after appropriate CPU type/model discovery using functions such as collect_cpu_info()).

- **c.** When a CPU is physically hot-unplugged and a new (and possibly different type of) CPU is hot-plugged into the system:

  In the current design of the kernel, whenever a CPU is taken offline during a regular CPU hotplug operation, upon receiving the CPU_DEAD notification (which is sent by the CPU hotplug code), the microcode update driver's callback for that event reacts by freeing the kernel's copy of the microcode image for that CPU.

  Hence, when a new CPU is brought online, since the kernel finds that it doesn't have the microcode image, it does the CPU type/model discovery afresh and then requests the userspace for the appropriate microcode image for that CPU, which is subsequently applied.

  For example, in x86, the mc_cpu_callback() function (which is the microcode update driver's callback registered for CPU hotplug events) calls microcode_update_cpu() which would call microcode_init_cpu() in this case, instead of microcode_resume_cpu() when it finds that the kernel doesn't have a valid microcode image. This ensures that the CPU type/model discovery is performed and the right microcode is applied to the CPU after getting it from userspace.

- **d.** Handling microcode update during suspend/hibernate:

  Strictly speaking, during a CPU hotplug operation which does not involve physically removing or inserting CPUs, the CPUs are not actually powered off during a CPU offline. They are just put to the lowest C-states possible. Hence, in such a case, it is not really necessary to re-apply microcode when the CPUs are brought back online, since they wouldn't have lost the image during the CPU offline operation.

  This is the usual scenario encountered during a resume after a suspend. However, in the case of hibernation, since all the CPUs are completely powered off, during restore it becomes necessary to apply the microcode images to all the CPUs.

  \[Note that we don't expect someone to physically pull out nodes and insert nodes with a different type of CPUs in-between a suspend-resume or a hibernate/restore cycle.\]

  In the current design of the kernel however, during a CPU offline operation as part of the suspend/hibernate cycle (cpuhp_tasks_frozen is set), the existing copy of microcode image in the kernel is not freed up. And during the CPU online operations (during resume/restore), since the kernel finds that it already has copies of the microcode images for all the CPUs, it just applies them to the CPUs, avoiding any re-discovery of CPU type/model and the need for validating whether the microcode revisions are right for the CPUs or not (due to the above assumption that physical CPU hotplug will not be done in-between suspend/resume or hibernate/restore cycles).

<a id="rst-iii-known-problems"></a>

## III. Known problems

Are there any known problems when regular CPU hotplug and suspend race with each other?

Yes, they are listed below:

1. When invoking regular CPU hotplug, the 'tasks_frozen' argument passed to the \_cpu_down() and \_cpu_up() functions is *always* 0. This might not reflect the true current state of the system, since the tasks could have been frozen by an out-of-band event such as a suspend operation in progress. Hence, the cpuhp_tasks_frozen variable will not reflect the frozen state and the CPU hotplug callbacks which evaluate that variable might execute the wrong code path.

2. If a regular CPU hotplug stress test happens to race with the freezer due to a suspend operation in progress at the same time, then we could hit the situation described below:

   > - A regular cpu online operation continues its journey from userspace into the kernel, since the freezing has not yet begun.
   >
   > - Then freezer gets to work and freezes userspace.
   >
   > - If cpu online has not yet completed the microcode update stuff by now, it will now start waiting on the frozen userspace in the TASK_UNINTERRUPTIBLE state, in order to get the microcode image.
   >
   > - Now the freezer continues and tries to freeze the remaining tasks. But due to this wait mentioned above, the freezer won't be able to freeze the cpu online hotplug task and hence freezing of tasks fails.

   As a result of this task freezing failure, the suspend operation gets aborted.

---

# System Suspend and Device Interrupts

_Peios Kernel / Internals / Power_

> Copyright (C) 2014 Intel Corp. Author: Rafael J. Wysocki <rafael.j.wysocki@intel.com>

<a id="rst-system-suspend-and-device-interrupts"></a>

Copyright (C) 2014 Intel Corp. Author: Rafael J. Wysocki &lt;[rafael.j.wysocki@intel.com](<mailto:rafael.j.wysocki@intel.com>)&gt;

<a id="rst-suspending-and-resuming-device-irqs"></a>

## Suspending and Resuming Device IRQs

Device interrupt request lines (IRQs) are generally disabled during system suspend after the "late" phase of suspending devices (that is, after all of the -&gt;prepare, -&gt;suspend and -&gt;suspend_late callbacks have been executed for all devices).  That is done by suspend_device_irqs().

The rationale for doing so is that after the "late" phase of device suspend there is no legitimate reason why any interrupts from suspended devices should trigger and if any devices have not been suspended properly yet, it is better to block interrupts from them anyway.  Also, in the past we had problems with interrupt handlers for shared IRQs that device drivers implementing them were not prepared for interrupts triggering after their devices had been suspended. In some cases they would attempt to access, for example, memory address spaces of suspended devices and cause unpredictable behavior to ensue as a result. Unfortunately, such problems are very difficult to debug and the introduction of suspend_device_irqs(), along with the "noirq" phase of device suspend and resume, was the only practical way to mitigate them.

Device IRQs are re-enabled during system resume, right before the "early" phase of resuming devices (that is, before starting to execute -&gt;resume_early callbacks for devices).  The function doing that is resume_device_irqs().

<a id="rst-the-irqf-no-suspend-flag"></a>

## The IRQF_NO_SUSPEND Flag

There are interrupts that can legitimately trigger during the entire system suspend-resume cycle, including the "noirq" phases of suspending and resuming devices as well as during the time when nonboot CPUs are taken offline and brought back online.  That applies to timer interrupts in the first place, but also to IPIs and to some other special-purpose interrupts.

The IRQF_NO_SUSPEND flag is used to indicate that to the IRQ subsystem when requesting a special-purpose interrupt.  It causes suspend_device_irqs() to leave the corresponding IRQ enabled so as to allow the interrupt to work as expected during the suspend-resume cycle, but does not guarantee that the interrupt will wake the system from a suspended state -- for such cases it is necessary to use enable_irq_wake().

Note that the IRQF_NO_SUSPEND flag affects the entire IRQ and not just one user of it.  Thus, if the IRQ is shared, all of the interrupt handlers installed for it will be executed as usual after suspend_device_irqs(), even if the IRQF_NO_SUSPEND flag was not passed to request_irq() (or equivalent) by some of the IRQ's users.  For this reason, using IRQF_NO_SUSPEND and IRQF_SHARED at the same time should be avoided.

<a id="rst-system-wakeup-interrupts-enable-irq-wake-and-disable-irq-wake"></a>

## System Wakeup Interrupts, enable_irq_wake() and disable_irq_wake()

System wakeup interrupts generally need to be configured to wake up the system from sleep states, especially if they are used for different purposes (e.g. as I/O interrupts) in the working state.

That may involve turning on a special signal handling logic within the platform (such as an SoC) so that signals from a given line are routed in a different way during system sleep so as to trigger a system wakeup when needed.  For example, the platform may include a dedicated interrupt controller used specifically for handling system wakeup events.  Then, if a given interrupt line is supposed to wake up the system from sleep states, the corresponding input of that interrupt controller needs to be enabled to receive signals from the line in question. After wakeup, it generally is better to disable that input to prevent the dedicated controller from triggering interrupts unnecessarily.

The IRQ subsystem provides two helper functions to be used by device drivers for those purposes.  Namely, enable_irq_wake() turns on the platform's logic for handling the given IRQ as a system wakeup interrupt line and disable_irq_wake() turns that logic off.

Calling enable_irq_wake() causes suspend_device_irqs() to treat the given IRQ in a special way.  Namely, the IRQ remains enabled, but on the first interrupt it will be disabled, marked as pending and "suspended" so that it will be re-enabled by resume_device_irqs() during the subsequent system resume.  Also the PM core is notified about the event which causes the system suspend in progress to be aborted (that doesn't have to happen immediately, but at one of the points where the suspend thread looks for pending wakeup events).

This way every interrupt from a wakeup interrupt source will either cause the system suspend currently in progress to be aborted or wake up the system if already suspended.  However, after suspend_device_irqs() interrupt handlers are not executed for system wakeup IRQs.  They are only executed for IRQF_NO_SUSPEND IRQs at that time, but those IRQs should not be configured for system wakeup using enable_irq_wake().

<a id="rst-interrupts-and-suspend-to-idle"></a>

## Interrupts and Suspend-to-Idle

Suspend-to-idle (also known as the "freeze" sleep state) is a relatively new system sleep state that works by idling all of the processors and waiting for interrupts right after the "noirq" phase of suspending devices.

Of course, this means that all of the interrupts with the IRQF_NO_SUSPEND flag set will bring CPUs out of idle while in that state, but they will not cause the IRQ subsystem to trigger a system wakeup.

System wakeup interrupts, in turn, will trigger wakeup from suspend-to-idle in analogy with what they do in the full system suspend case.  The only difference is that the wakeup from suspend-to-idle is signaled using the usual working state interrupt delivery mechanisms and doesn't require the platform to use any special interrupt handling logic for it to work.

<a id="rst-irqf-no-suspend-and-enable-irq-wake"></a>

## IRQF_NO_SUSPEND and enable_irq_wake()

There are very few valid reasons to use both enable_irq_wake() and the IRQF_NO_SUSPEND flag on the same IRQ, and it is never valid to use both for the same device.

First of all, if the IRQ is not shared, the rules for handling IRQF_NO_SUSPEND interrupts (interrupt handlers are invoked after suspend_device_irqs()) are directly at odds with the rules for handling system wakeup interrupts (interrupt handlers are not invoked after suspend_device_irqs()).

Second, both enable_irq_wake() and IRQF_NO_SUSPEND apply to entire IRQs and not to individual interrupt handlers, so sharing an IRQ between a system wakeup interrupt source and an IRQF_NO_SUSPEND interrupt source does not generally make sense.

In rare cases an IRQ can be shared between a wakeup device driver and an IRQF_NO_SUSPEND user. In order for this to be safe, the wakeup device driver must be able to discern spurious IRQs from genuine wakeup events (signalling the latter to the core with pm_system_wakeup()), must use enable_irq_wake() to ensure that the IRQ will function as a wakeup source, and must request the IRQ with IRQF_COND_SUSPEND to tell the core that it meets these requirements. If these requirements are not met, it is not valid to use IRQF_COND_SUSPEND.

---

# Using swap files with software suspend (swsusp)

_Peios Kernel / Internals / Power_

> 2006 Rafael J. Wysocki <rjw@sisk.pl>

<a id="rst-using-swap-files-with-software-suspend-swsusp"></a>

> - **(C)** 2006 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;

The Linux kernel handles swap files almost in the same way as it handles swap partitions and there are only two differences between these two types of swap areas: (1) swap files need not be contiguous, (2) the header of a swap file is not in the first block of the partition that holds it.  From the swsusp's point of view (1) is not a problem, because it is already taken care of by the swap-handling code, but (2) has to be taken into consideration.

In principle the location of a swap file's header may be determined with the help of appropriate filesystem driver.  Unfortunately, however, it requires the filesystem holding the swap file to be mounted, and if this filesystem is journaled, it cannot be mounted during resume from disk.  For this reason to identify a swap file swsusp uses the name of the partition that holds the file and the offset from the beginning of the partition at which the swap file's header is located.  For convenience, this offset is expressed in &lt;PAGE\_SIZE&gt; units.

In order to use a swap file with swsusp, you need to:

1. Create the swap file and make it active, eg.:



   ```text
   # dd if=/dev/zero of=<swap_file_path> bs=1024 count=<swap_file_size_in_k>
   # mkswap <swap_file_path>
   # swapon <swap_file_path>
   ```

2\) Use an application that will bmap the swap file with the help of the FIBMAP ioctl and determine the location of the file's swap header, as the offset, in &lt;PAGE\_SIZE&gt; units, from the beginning of the partition which holds the swap file.

3. Add the following parameters to the kernel command line:



   ```text
   resume=<swap_file_partition> resume_offset=<swap_file_offset>
   ```

where &lt;swap\_file\_partition&gt; is the partition on which the swap file is located and &lt;swap\_file\_offset&gt; is the offset of the swap header determined by the application in 2) (of course, this step may be carried out automatically by the same application that determines the swap file's header offset using the FIBMAP ioctl)

OR

Use a userland suspend application that will set the partition and offset with the help of the SNAPSHOT\_SET\_SWAP\_AREA ioctl described in [Documentation/power/userland-swsusp.rst](/kernel/internals/power/userland-swsusp.md) (this is the only method to suspend to a swap file allowing the resume to be initiated from an initrd or initramfs image).

Now, swsusp will use the swap file in the same way in which it would use a swap partition.  In particular, the swap file has to be active (ie. be present in /proc/swaps) so that it can be used for suspending.

Note that if the swap file used for suspending is deleted and recreated, the location of its header need not be the same as before.  Thus every time this happens the value of the "resume\_offset=" kernel command line parameter has to be updated.

---

# How to use dm-crypt and swsusp together

_Peios Kernel / Internals / Power_

> Author: Andreas Steinmetz <ast@domdv.de>

<a id="rst-how-to-use-dm-crypt-and-swsusp-together"></a>

Author: Andreas Steinmetz &lt;[ast@domdv.de](<mailto:ast@domdv.de>)&gt;

Some prerequisites: You know how dm-crypt works. If not, visit the following web page: [http://www.saout.de/misc/dm-crypt/](<http://www.saout.de/misc/dm-crypt/>) You have read [Documentation/power/swsusp.rst](/kernel/internals/power/swsusp.md) and understand it. You did read [Documentation/admin-guide/initrd.rst](/kernel/administration/admin-guide/boot/initrd.md) and know how an initrd works. You know how to create or how to modify an initrd.

Now your system is properly set up, your disk is encrypted except for the swap device(s) and the boot partition which may contain a mini system for crypto setup and/or rescue purposes. You may even have an initrd that does your current crypto setup already.

At this point you want to encrypt your swap, too. Still you want to be able to suspend using swsusp. This, however, means that you have to be able to either enter a passphrase or that you read the key(s) from an external device like a pcmcia flash disk or an usb stick prior to resume. So you need an initrd, that sets up dm-crypt and then asks swsusp to resume from the encrypted swap device.

The most important thing is that you set up dm-crypt in such a way that the swap device you suspend to/resume from has always the same major/minor within the initrd as well as within your running system. The easiest way to achieve this is to always set up this swap device first with dmsetup, so that it will always look like the following:



```text
brw-------  1 root root 254, 0 Jul 28 13:37 /dev/mapper/swap0
```

Now set up your kernel to use /dev/mapper/swap0 as the default resume partition, so your kernel .config contains:



```text
CONFIG_PM_STD_PARTITION="/dev/mapper/swap0"
```

Prepare your boot loader to use the initrd you will create or modify. For lilo the simplest setup looks like the following lines:



```text
image=/boot/vmlinuz
initrd=/boot/initrd.gz
label=linux
append="root=/dev/ram0 init=/linuxrc rw"
```

Finally you need to create or modify your initrd. Lets assume you create an initrd that reads the required dm-crypt setup from a pcmcia flash disk card. The card is formatted with an ext2 fs which resides on /dev/hde1 when the card is inserted. The card contains at least the encrypted swap setup in a file named "swapkey". /etc/fstab of your initrd contains something like the following:



```text
/dev/hda1   /mnt    ext3      ro                            0 0
none        /proc   proc      defaults,noatime,nodiratime   0 0
none        /sys    sysfs     defaults,noatime,nodiratime   0 0
```

/dev/hda1 contains an unencrypted mini system that sets up all of your crypto devices, again by reading the setup from the pcmcia flash disk. What follows now is a /linuxrc for your initrd that allows you to resume from encrypted swap and that continues boot with your mini system on /dev/hda1 if resume does not happen:



```text
#!/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
mount /proc
mount /sys
mapped=0
noresume=`grep -c noresume /proc/cmdline`
if [ "$*" != "" ]
then
  noresume=1
fi
dmesg -n 1
/sbin/cardmgr -q
for i in 1 2 3 4 5 6 7 8 9 0
do
  if [ -f /proc/ide/hde/media ]
  then
    usleep 500000
    mount -t ext2 -o ro /dev/hde1 /mnt
    if [ -f /mnt/swapkey ]
    then
      dmsetup create swap0 /mnt/swapkey > /dev/null 2>&1 && mapped=1
    fi
    umount /mnt
    break
  fi
  usleep 500000
done
killproc /sbin/cardmgr
dmesg -n 6
if [ $mapped = 1 ]
then
  if [ $noresume != 0 ]
  then
    mkswap /dev/mapper/swap0 > /dev/null 2>&1
  fi
  echo 254:0 > /sys/power/resume
  dmsetup remove swap0
fi
umount /sys
mount /mnt
umount /proc
cd /mnt
pivot_root . mnt
mount /proc
umount -l /mnt
umount /proc
exec chroot . /sbin/init $* < dev/console > dev/console 2>&1
```

Please don't mind the weird loop above, busybox's msh doesn't know the let statement. Now, what is happening in the script? First we have to decide if we want to try to resume, or not. We will not resume if booting with "noresume" or any parameters for init like "single" or "emergency" as boot parameters.

Then we need to set up dmcrypt with the setup data from the pcmcia flash disk. If this succeeds we need to reset the swap device if we don't want to resume. The line "echo 254:0 &gt; /sys/power/resume" then attempts to resume from the first device mapper device. Note that it is important to set the device in /sys/power/resume, regardless if resuming or not, otherwise later suspend will fail. If resume starts, script execution terminates here.

Otherwise we just remove the encrypted swap device and leave it to the mini system on /dev/hda1 to set the whole crypto up (it is up to you to modify this to your taste).

What then follows is the well known process to change the root file system and continue booting from there. I prefer to unmount the initrd prior to continue booting but it is up to you to modify this.

---

# Swap suspend

_Peios Kernel / Internals / Power_

> Some warnings, first.

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-swap-suspend"></a>

Some warnings, first.

> [!WARNING]
>
> **BIG FAT WARNING**
>
> - **If you touch anything on disk between suspend and resume...**
>
>   ...kiss your data goodbye.
>
> - **If you do resume from initrd after your filesystems are mounted...**
>
>   > ...bye bye root partition.
>
>   \[this is actually same case as above\]
>
> If you have unsupported ( ) devices using DMA, you may have some problems. If your disk driver does not support suspend... (IDE does), it may cause some problems, too. If you change kernel command line between suspend and resume, it may do something wrong. If you change your hardware while system is suspended... well, it was not good idea; but it will probably only crash.
>
> ( ) suspend/resume support is needed to make it safe.
>
> If you have any filesystems on USB devices mounted before software suspend, they won't be accessible after resume and you may lose data, as though you have unplugged the USB devices with mounted filesystems on them; see the FAQ below for details.  (This is not true for more traditional power states like "standby", which normally don't turn USB off.)

- **Swap partition:**

  You need to append resume=/dev/your_swap_partition to kernel command line or specify it using /sys/power/resume.

- **Swap file:**

  If using a swapfile you can also specify a resume offset using resume_offset=&lt;number&gt; on the kernel command line or specify it in /sys/power/resume_offset.

After preparing then you suspend by:



```text
echo shutdown > /sys/power/disk; echo disk > /sys/power/state
```

- If you feel ACPI works pretty well on your system, you might try:



  ```text
  echo platform > /sys/power/disk; echo disk > /sys/power/state
  ```

- If you would like to write hibernation image to swap and then suspend to RAM (provided your platform supports it), you can try:



  ```text
  echo suspend > /sys/power/disk; echo disk > /sys/power/state
  ```

- If you have SATA disks, you'll need recent kernels with SATA suspend support. For suspend and resume to work, make sure your disk drivers are built into kernel -- not modules. \[There's way to make suspend/resume with modular disk drivers, see FAQ, but you probably should not do that.\]

If you want to limit the suspend image size to N bytes, do:



```text
echo N > /sys/power/image_size
```

before suspend (it is limited to around 2/5 of available RAM by default).

- The resume process checks for the presence of the resume device, if found, it then checks the contents for the hibernation image signature. If both are found, it resumes the hibernation image.

- The resume process may be triggered in two ways:

  1. During lateinit:  If resume=/dev/your_swap_partition is specified on the kernel command line, lateinit runs the resume process.  If the resume device has not been probed yet, the resume process fails and bootup continues.

  2. Manually from an initrd or initramfs:  May be run from the init script by using the /sys/power/resume file.  It is vital that this be done prior to remounting any filesystems (even as read-only) otherwise data may be corrupted.

<a id="rst-article-about-goals-and-implementation-of-software-suspend-for-linux"></a>

## Article about goals and implementation of Software Suspend for Linux

Author: Gábor Kuti Last revised: 2003-10-20 by Pavel Machek

<a id="rst-idea-and-goals-to-achieve"></a>

### Idea and goals to achieve

Nowadays it is common in several laptops that they have a suspend button. It saves the state of the machine to a filesystem or to a partition and switches to standby mode. Later resuming the machine the saved state is loaded back to ram and the machine can continue its work. It has two real benefits. First we save ourselves the time machine goes down and later boots up, energy costs are real high when running from batteries. The other gain is that we don't have to interrupt our programs so processes that are calculating something for a long time shouldn't need to be written interruptible.

swsusp saves the state of the machine into active swaps and then reboots or powerdowns.  You must explicitly specify the swap partition to resume from with `resume=` kernel option. If signature is found it loads and restores saved state. If the option `noresume` is specified as a boot parameter, it skips the resuming.  If the option `hibernate=nocompress` is specified as a boot parameter, it saves hibernation image without compression.

In the meantime while the system is suspended you should not add/remove any of the hardware, write to the filesystems, etc.

<a id="rst-sleep-states-summary"></a>

## Sleep states summary

There are three different interfaces you can use, /proc/acpi should work like this:

In a really perfect world:



```text
echo 1 > /proc/acpi/sleep       # for standby
echo 2 > /proc/acpi/sleep       # for suspend to ram
echo 3 > /proc/acpi/sleep       # for suspend to ram, but with more power
                                # conservative
echo 4 > /proc/acpi/sleep       # for suspend to disk
echo 5 > /proc/acpi/sleep       # for shutdown unfriendly the system
```

and perhaps:



```text
echo 4b > /proc/acpi/sleep      # for suspend to disk via s4bios
```

<a id="rst-frequently-asked-questions"></a>

## Frequently Asked Questions

- **Q:**

  well, suspending a server is IMHO a really stupid thing, but... (Diego Zuccato):

- **A:**

  You bought new UPS for your server. How do you install it without bringing machine down? Suspend to disk, rearrange power cables, resume.

  You have your server on UPS. Power died, and UPS is indicating 30 seconds to failure. What do you do? Suspend to disk.

- **Q:**

  Maybe I'm missing something, but why don't the regular I/O paths work?

- **A:**

  We do use the regular I/O paths. However we cannot restore the data to its original location as we load it. That would create an inconsistent kernel state which would certainly result in an oops. Instead, we load the image into unused memory and then atomically copy it back to it original location. This implies, of course, a maximum image size of half the amount of memory.

  There are two solutions to this:

  - require half of memory to be free during suspend. That way you can read "new" data onto free spots, then cli and copy

  - assume we had special "polling" ide driver that only uses memory between 0-640KB. That way, I'd have to make sure that 0-640KB is free during suspending, but otherwise it would work...

  suspend2 shares this fundamental limitation, but does not include user data and disk caches into "used memory" by saving them in advance. That means that the limitation goes away in practice.

- **Q:**

  Does linux support ACPI S4?

- **A:**

  Yes. That's what echo platform &gt; /sys/power/disk does.

- **Q:**

  What is 'suspend2'?

- **A:**

  suspend2 is 'Software Suspend 2', a forked implementation of suspend-to-disk which is available as separate patches for 2.4 and 2.6 kernels from swsusp.sourceforge.net. It includes support for SMP, 4GB highmem and preemption. It also has a extensible architecture that allows for arbitrary transformations on the image (compression, encryption) and arbitrary backends for writing the image (eg to swap or an NFS share\[Work In Progress\]). Questions regarding suspend2 should be sent to the mailing list available through the suspend2 website, and not to the Linux Kernel Mailing List. We are working toward merging suspend2 into the mainline kernel.

- **Q:**

  What is the freezing of tasks and why are we using it?

- **A:**

  The freezing of tasks is a mechanism by which user space processes and some kernel threads are controlled during hibernation or system-wide suspend (on some architectures).  See freezing-of-tasks.txt for details.

- **Q:**

  What is the difference between "platform" and "shutdown"?

- **A:**

  - **shutdown:**

    save state in linux, then tell bios to powerdown

  - **platform:**

    save state in linux, then tell bios to powerdown and blink "suspended led"

  "platform" is actually right thing to do where supported, but "shutdown" is most reliable (except on ACPI systems).

- **Q:**

  I do not understand why you have such strong objections to idea of selective suspend.

- **A:**

  Do selective suspend during runtime power management, that's okay. But it's useless for suspend-to-disk. (And I do not see how you could use it for suspend-to-ram, I hope you do not want that).

  Lets see, so you suggest to

  - SUSPEND all but swap device and parents

  - Snapshot

  - Write image to disk

  - SUSPEND swap device and parents

  - Powerdown

  Oh no, that does not work, if swap device or its parents uses DMA, you've corrupted data. You'd have to do

  - SUSPEND all but swap device and parents

  - FREEZE swap device and parents

  - Snapshot

  - UNFREEZE swap device and parents

  - Write

  - SUSPEND swap device and parents

  Which means that you still need that FREEZE state, and you get more complicated code. (And I have not yet introduce details like system devices).

- **Q:**

  There don't seem to be any generally useful behavioral distinctions between SUSPEND and FREEZE.

- **A:**

  Doing SUSPEND when you are asked to do FREEZE is always correct, but it may be unnecessarily slow. If you want your driver to stay simple, slowness may not matter to you. It can always be fixed later.

  For devices like disk it does matter, you do not want to spindown for FREEZE.

- **Q:**

  After resuming, system is paging heavily, leading to very bad interactivity.

- **A:**

  Try running:



  ```text
  cat /proc/[0-9]*/maps | grep / | sed 's:.* /:/:' | sort -u | while read file
  do
    test -f "$file" && cat "$file" > /dev/null
  done
  ```

  after resume. swapoff -a; swapon -a may also be useful.

- **Q:**

  What happens to devices during swsusp? They seem to be resumed during system suspend?

- **A:**

  That's correct. We need to resume them if we want to write image to disk. Whole sequence goes like

  > **Suspend part**
  >
  > running system, user asks for suspend-to-disk
  >
  > user processes are stopped
  >
  > suspend(PMSG_FREEZE): devices are frozen so that they don't interfere with state snapshot
  >
  > state snapshot: copy of whole used memory is taken with interrupts disabled
  >
  > resume(): devices are woken up so that we can write image to swap
  >
  > write image to swap
  >
  > suspend(PMSG_SUSPEND): suspend devices so that we can power off
  >
  > turn the power off
  >
  > **Resume part**
  >
  > (is actually pretty similar)
  >
  > running system, user asks for suspend-to-disk
  >
  > user processes are stopped (in common case there are none, but with resume-from-initrd, no one knows)
  >
  > read image from disk
  >
  > suspend(PMSG_FREEZE): devices are frozen so that they don't interfere with image restoration
  >
  > image restoration: rewrite memory with image
  >
  > resume(): devices are woken up so that system can continue
  >
  > thaw all user processes

- **Q:**

  What is this 'Encrypt suspend image' for?

- **A:**

  First of all: it is not a replacement for dm-crypt encrypted swap. It cannot protect your computer while it is suspended. Instead it does protect from leaking sensitive data after resume from suspend.

  Think of the following: you suspend while an application is running that keeps sensitive data in memory. The application itself prevents the data from being swapped out. Suspend, however, must write these data to swap to be able to resume later on. Without suspend encryption your sensitive data are then stored in plaintext on disk.  This means that after resume your sensitive data are accessible to all applications having direct access to the swap device which was used for suspend. If you don't need swap after resume these data can remain on disk virtually forever. Thus it can happen that your system gets broken in weeks later and sensitive data which you thought were encrypted and protected are retrieved and stolen from the swap device. To prevent this situation you should use 'Encrypt suspend image'.

  During suspend a temporary key is created and this key is used to encrypt the data written to disk. When, during resume, the data was read back into memory the temporary key is destroyed which simply means that all data written to disk during suspend are then inaccessible so they can't be stolen later on.  The only thing that you must then take care of is that you call 'mkswap' for the swap partition used for suspend as early as possible during regular boot. This asserts that any temporary key from an oopsed suspend or from a failed or aborted resume is erased from the swap device.

  As a rule of thumb use encrypted swap to protect your data while your system is shut down or suspended. Additionally use the encrypted suspend image to prevent sensitive data from being stolen after resume.

- **Q:**

  Can I suspend to a swap file?

- **A:**

  Generally, yes, you can.  However, it requires you to use the "resume=" and "resume_offset=" kernel command line parameters, so the resume from a swap file cannot be initiated from an initrd or initramfs image.  See swsusp-and-swap-files.txt for details.

- **Q:**

  Is there a maximum system RAM size that is supported by swsusp?

- **A:**

  It should work okay with highmem.

- **Q:**

  Does swsusp (to disk) use only one swap partition or can it use multiple swap partitions (aggregate them into one logical space)?

- **A:**

  Only one swap partition, sorry.

- **Q:**

  If my application(s) causes lots of memory &amp; swap space to be used (over half of the total system RAM), is it correct that it is likely to be useless to try to suspend to disk while that app is running?

- **A:**

  No, it should work okay, as long as your app does not mlock() it. Just prepare big enough swap partition.

- **Q:**

  What information is useful for debugging suspend-to-disk problems?

- **A:**

  Well, last messages on the screen are always useful. If something is broken, it is usually some kernel driver, therefore trying with as little as possible modules loaded helps a lot. I also prefer people to suspend from console, preferably without X running. Booting with init=/bin/bash, then swapon and starting suspend sequence manually usually does the trick. Then it is good idea to try with latest vanilla kernel.

- **Q:**

  How can distributions ship a swsusp-supporting kernel with modular disk drivers (especially SATA)?

- **A:**

  Well, it can be done, load the drivers, then do echo into /sys/power/resume file from initrd. Be sure not to mount anything, not even read-only mount, or you are going to lose your data.

- **Q:**

  How do I make suspend more verbose?

- **A:**

  If you want to see any non-error kernel messages on the virtual terminal the kernel switches to during suspend, you have to set the kernel console loglevel to at least 4 (KERN_WARNING), for example by doing:



  ```text
  # save the old loglevel
  read LOGLEVEL DUMMY < /proc/sys/kernel/printk
  # set the loglevel so we see the progress bar.
  # if the level is higher than needed, we leave it alone.
  if [ $LOGLEVEL -lt 5 ]; then
          echo 5 > /proc/sys/kernel/printk
          fi

  IMG_SZ=0
  read IMG_SZ < /sys/power/image_size
  echo -n disk > /sys/power/state
  RET=$?
  #
  # the logic here is:
  # if image_size > 0 (without kernel support, IMG_SZ will be zero),
  # then try again with image_size set to zero.
  if [ $RET -ne 0 -a $IMG_SZ -ne 0 ]; then # try again with minimal image size
          echo 0 > /sys/power/image_size
          echo -n disk > /sys/power/state
          RET=$?
  fi

  # restore previous loglevel
  echo $LOGLEVEL > /proc/sys/kernel/printk
  exit $RET
  ```

- **Q:**

  Is this true that if I have a mounted filesystem on a USB device and I suspend to disk, I can lose data unless the filesystem has been mounted with "sync"?

- **A:**

  That's right ... if you disconnect that device, you may lose data. In fact, even with "-o sync" you can lose data if your programs have information in buffers they haven't written out to a disk you disconnect, or if you disconnect before the device finished saving data you wrote.

  Software suspend normally powers down USB controllers, which is equivalent to disconnecting all USB devices attached to your system.

  Your system might well support low-power modes for its USB controllers while the system is asleep, maintaining the connection, using true sleep modes like "suspend-to-RAM" or "standby".  (Don't write "disk" to the /sys/power/state file; write "standby" or "mem".)  We've not seen any hardware that can use these modes through software suspend, although in theory some systems might support "platform" modes that won't break the USB connections.

  Remember that it's always a bad idea to unplug a disk drive containing a mounted filesystem.  That's true even when your system is asleep\!  The safest thing is to unmount all filesystems on removable media (such USB, Firewire, CompactFlash, MMC, external SATA, or even IDE hotplug bays) before suspending; then remount them after resuming.

  There is a work-around for this problem.  For more information, see [Documentation/driver-api/usb/persist.rst](/kernel/hardware/driver-api/usb/persist.md).

- **Q:**

  Can I suspend-to-disk using a swap partition under LVM?

- **A:**

  Yes and No.  You can suspend successfully, but the kernel will not be able to resume on its own.  You need an initramfs that can recognize the resume situation, activate the logical volume containing the swap volume (but not touch any filesystems\!), and eventually call:



  ```text
  echo -n "$major:$minor" > /sys/power/resume
  ```

  where $major and $minor are the respective major and minor device numbers of the swap volume.

  uswsusp works with LVM, too.  See [http://suspend.sourceforge.net/](<http://suspend.sourceforge.net/>)

- **Q:**

  I upgraded the kernel from 2.6.15 to 2.6.16. Both kernels were compiled with the similar configuration files. Anyway I found that suspend to disk (and resume) is much slower on 2.6.16 compared to 2.6.15. Any idea for why that might happen or how can I speed it up?

- **A:**

  This is because the size of the suspend image is now greater than for 2.6.15 (by saving more data we can get more responsive system after resume).

  There's the /sys/power/image_size knob that controls the size of the image.  If you set it to 0 (eg. by echo 0 &gt; /sys/power/image_size as root), the 2.6.15 behavior should be restored.  If it is still too slow, take a look at suspend.sf.net -- userland suspend is faster and supports LZF compression to speed it up further.

---

# swsusp/S3 tricks

_Peios Kernel / Internals / Power_

> Pavel Machek <pavel@ucw.cz>

<a id="rst-swsusp-s3-tricks"></a>

Pavel Machek &lt;[pavel@ucw.cz](<mailto:pavel@ucw.cz>)&gt;

If you want to trick swsusp/S3 into working, you might want to try:

- go with minimal config, turn off drivers like USB, AGP you don't really need

- turn off APIC and preempt

- use ext2. At least it has working fsck. \[If something seems to go wrong, force fsck when you have a chance\]

- turn off modules

- use vga text console, shut down X. \[If you really want X, you might want to try vesafb later\]

- try running as few processes as possible, preferably go to single user mode.

- due to video issues, swsusp should be easier to get working than S3. Try that first.

When you make it work, try to find out what exactly was it that broke suspend, and preferably fix that.

---

# Documentation for userland software suspend interface

_Peios Kernel / Internals / Power_

> 2006 Rafael J. Wysocki <rjw@sisk.pl>

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-documentation-for-userland-software-suspend-interface"></a>

> - **(C)** 2006 Rafael J. Wysocki &lt;[rjw@sisk.pl](<mailto:rjw@sisk.pl>)&gt;

First, the warnings at the beginning of swsusp.txt still apply.

Second, you should read the FAQ in swsusp.txt \_now\_ if you have not done it already.

Now, to use the userland interface for software suspend you need special utilities that will read/write the system memory snapshot from/to the kernel.  Such utilities are available, for example, from &lt;[http://suspend.sourceforge.net](<http://suspend.sourceforge.net>)&gt;.  You may want to have a look at them if you are going to develop your own suspend/resume utilities.

The interface consists of a character device providing the open(), release(), read(), and write() operations as well as several ioctl() commands defined in include/linux/suspend_ioctls.h .  The major and minor numbers of the device are, respectively, 10 and 231, and they can be read from /sys/class/misc/snapshot/dev.

The device can be open either for reading or for writing.  If open for reading, it is considered to be in the suspend mode.  Otherwise it is assumed to be in the resume mode.  The device cannot be open for simultaneous reading and writing.  It is also impossible to have the device open more than once at a time.

Even opening the device has side effects. Data structures are allocated, and PM_HIBERNATION_PREPARE / PM_RESTORE_PREPARE chains are called.

The ioctl() commands recognized by the device are:

- **SNAPSHOT_FREEZE**

  freeze user space processes (the current process is not frozen); this is required for SNAPSHOT_CREATE_IMAGE and SNAPSHOT_ATOMIC_RESTORE to succeed

- **SNAPSHOT_UNFREEZE**

  thaw user space processes frozen by SNAPSHOT_FREEZE

- **SNAPSHOT_CREATE_IMAGE**

  create a snapshot of the system memory; the last argument of ioctl() should be a pointer to an int variable, the value of which will indicate whether the call returned after creating the snapshot (1) or after restoring the system memory state from it (0) (after resume the system finds itself finishing the SNAPSHOT_CREATE_IMAGE ioctl() again); after the snapshot has been created the read() operation can be used to transfer it out of the kernel

- **SNAPSHOT_ATOMIC_RESTORE**

  restore the system memory state from the uploaded snapshot image; before calling it you should transfer the system memory snapshot back to the kernel using the write() operation; this call will not succeed if the snapshot image is not available to the kernel

- **SNAPSHOT_FREE**

  free memory allocated for the snapshot image

- **SNAPSHOT_PREF_IMAGE_SIZE**

  set the preferred maximum size of the image (the kernel will do its best to ensure the image size will not exceed this number, but if it turns out to be impossible, the kernel will create the smallest image possible)

- **SNAPSHOT_GET_IMAGE_SIZE**

  return the actual size of the hibernation image (the last argument should be a pointer to a loff_t variable that will contain the result if the call is successful)

- **SNAPSHOT_AVAIL_SWAP_SIZE**

  return the amount of available swap in bytes (the last argument should be a pointer to a loff_t variable that will contain the result if the call is successful)

- **SNAPSHOT_ALLOC_SWAP_PAGE**

  allocate a swap page from the resume partition (the last argument should be a pointer to a loff_t variable that will contain the swap page offset if the call is successful)

- **SNAPSHOT_FREE_SWAP_PAGES**

  free all swap pages allocated by SNAPSHOT_ALLOC_SWAP_PAGE

- **SNAPSHOT_SET_SWAP_AREA**

  set the resume partition and the offset (in &lt;PAGE_SIZE&gt; units) from the beginning of the partition at which the swap header is located (the last ioctl() argument should point to a struct resume_swap_area, as defined in kernel/power/suspend_ioctls.h, containing the resume device specification and the offset); for swap partitions the offset is always 0, but it is different from zero for swap files (see [Documentation/power/swsusp-and-swap-files.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/power/swsusp-and-swap-files.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) for details).

- **SNAPSHOT_PLATFORM_SUPPORT**

  enable/disable the hibernation platform support, depending on the argument value (enable, if the argument is nonzero)

- **SNAPSHOT_POWER_OFF**

  make the kernel transition the system to the hibernation state (eg. ACPI S4) using the platform (eg. ACPI) driver

- **SNAPSHOT_S2RAM**

  suspend to RAM; using this call causes the kernel to immediately enter the suspend-to-RAM state, so this call must always be preceded by the SNAPSHOT_FREEZE call and it is also necessary to use the SNAPSHOT_UNFREEZE call after the system wakes up.  This call is needed to implement the suspend-to-both mechanism in which the suspend image is first created, as though the system had been suspended to disk, and then the system is suspended to RAM (this makes it possible to resume the system from RAM if there's enough battery power or restore its state on the basis of the saved suspend image otherwise)

The device's read() operation can be used to transfer the snapshot image from the kernel.  It has the following limitations:

- you cannot read() more than one virtual memory page at a time

- read()s across page boundaries are impossible (ie. if you read() 1/2 of a page in the previous call, you will only be able to read() **at most** 1/2 of the page in the next call)

The device's write() operation is used for uploading the system memory snapshot into the kernel.  It has the same limitations as the read() operation.

The release() operation frees all memory allocated for the snapshot image and all swap pages allocated with SNAPSHOT_ALLOC_SWAP_PAGE (if any). Thus it is not necessary to use either SNAPSHOT_FREE or SNAPSHOT_FREE_SWAP_PAGES before closing the device (in fact it will also unfreeze user space processes frozen by SNAPSHOT_UNFREEZE if they are still frozen when the device is being closed).

Currently it is assumed that the userland utilities reading/writing the snapshot image from/to the kernel will use a swap partition, called the resume partition, or a swap file as storage space (if a swap file is used, the resume partition is the partition that holds this file).  However, this is not really required, as they can use, for example, a special (blank) suspend partition or a file on a partition that is unmounted before SNAPSHOT_CREATE_IMAGE and mounted afterwards.

These utilities MUST NOT make any assumptions regarding the ordering of data within the snapshot image.  The contents of the image are entirely owned by the kernel and its structure may be changed in future kernel releases.

The snapshot image MUST be written to the kernel unaltered (ie. all of the image data, metadata and header MUST be written in \_exactly\_ the same amount, form and order in which they have been read).  Otherwise, the behavior of the resumed system may be totally unpredictable.

While executing SNAPSHOT_ATOMIC_RESTORE the kernel checks if the structure of the snapshot image is consistent with the information stored in the image header.  If any inconsistencies are detected, SNAPSHOT_ATOMIC_RESTORE will not succeed.  Still, this is not a fool-proof mechanism and the userland utilities using the interface SHOULD use additional means, such as checksums, to ensure the integrity of the snapshot image.

The suspending and resuming utilities MUST lock themselves in memory, preferably using mlockall(), before calling SNAPSHOT_FREEZE.

The suspending utility MUST check the value stored by SNAPSHOT_CREATE_IMAGE in the memory location pointed to by the last argument of ioctl() and proceed in accordance with it:

1. If the value is 1 (ie. the system memory snapshot has just been created and the system is ready for saving it):

   - **(a)** The suspending utility MUST NOT close the snapshot device \_unless\_ the whole suspend procedure is to be cancelled, in which case, if the snapshot image has already been saved, the suspending utility SHOULD destroy it, preferably by zapping its header.  If the suspend is not to be cancelled, the system MUST be powered off or rebooted after the snapshot image has been saved.

   - **(b)** The suspending utility SHOULD NOT attempt to perform any file system operations (including reads) on the file systems that were mounted before SNAPSHOT_CREATE_IMAGE has been called.  However, it MAY mount a file system that was not mounted at that time and perform some operations on it (eg. use it for saving the image).

2. If the value is 0 (ie. the system state has just been restored from the snapshot image), the suspending utility MUST close the snapshot device.  Afterwards it will be treated as a regular userland process, so it need not exit.

The resuming utility SHOULD NOT attempt to mount any file systems that could be mounted before suspend and SHOULD NOT attempt to perform any operations involving such file systems.

For details, please refer to the source code.

---

# Video issues with S3 resume

_Peios Kernel / Internals / Power_

> 2003-2006, Pavel Machek

<a id="rst-video-issues-with-s3-resume"></a>

2003-2006, Pavel Machek

During S3 resume, hardware needs to be reinitialized. For most devices, this is easy, and kernel driver knows how to do it. Unfortunately there's one exception: video card. Those are usually initialized by BIOS, and kernel does not have enough information to boot video card. (Kernel usually does not even contain video card driver -- vesafb and vgacon are widely used).

This is not problem for swsusp, because during swsusp resume, BIOS is run normally so video card is normally initialized. It should not be problem for S1 standby, because hardware should retain its state over that.

We either have to run video BIOS during early resume, or interpret it using vbetool later, or maybe nothing is necessary on particular system because video state is preserved. Unfortunately different methods work on different systems, and no known method suits all of them.

Userland application called s2ram has been developed; it contains long whitelist of systems, and automatically selects working method for a given system. It can be downloaded from CVS at www.sf.net/projects/suspend . If you get a system that is not in the whitelist, please try to find a working solution, and submit whitelist entry so that work does not need to be repeated.

Currently, VBE_SAVE method (6 below) works on most systems. Unfortunately, vbetool only runs after userland is resumed, so it makes debugging of early resume problems hard/impossible. Methods that do not rely on userland are preferable.

<a id="rst-details"></a>

## Details

There are a few types of systems where video works after S3 resume:

1. systems where video state is preserved over S3.

2. systems where it is possible to call the video BIOS during S3 resume. Unfortunately, it is not correct to call the video BIOS at that point, but it happens to work on some machines. Use acpi_sleep=s3_bios.

3. systems that initialize video card into vga text mode and where the BIOS works well enough to be able to set video mode. Use acpi_sleep=s3_mode on these.

4. on some systems s3_bios kicks video into text mode, and acpi_sleep=s3_bios,s3_mode is needed.

5. radeon systems, where X can soft-boot your video card. You'll need a new enough X, and a plain text console (no vesafb or radeonfb). See [http://www.doesi.gmxhome.de/linux/tm800s3/s3.html](<http://www.doesi.gmxhome.de/linux/tm800s3/s3.html>) for more information. Alternatively, you should use vbetool (6) instead.

6. other radeon systems, where vbetool is enough to bring system back to life. It needs text console to be working. Do vbetool vbestate save &gt; /tmp/delme; echo 3 &gt; /proc/acpi/sleep; vbetool post; vbetool vbestate restore &lt; /tmp/delme; setfont &lt;whatever&gt;, and your video should work.

7. on some systems, it is possible to boot most of kernel, and then POSTing bios works. Ole Rohne has patch to do just that at [http://dev.gentoo.org/\~marineam/patch-radeonfb-2.6.11-rc2-mm2](<http://dev.gentoo.org/~marineam/patch-radeonfb-2.6.11-rc2-mm2>).

8. on some systems, you can use the video_post utility and or do echo 3 &gt; /sys/power/state  &amp;&amp; /usr/sbin/video_post - which will initialize the display in console mode. If you are in X, you can switch to a virtual terminal and back to X using  CTRL+ALT+F1 - CTRL+ALT+F7 to get the display working in graphical mode again.

Now, if you pass acpi_sleep=something, and it does not work with your bios, you'll get a hard crash during resume. Be careful. Also it is safest to do your experiments with plain old VGA console. The vesafb and radeonfb (etc) drivers have a tendency to crash the machine during resume.

You may have a system where none of above works. At that point you either invent another ugly hack that works, or write proper driver for your video card (good luck getting docs :-(). Maybe suspending from X (proper X, knowing your hardware, not XF68_FBcon) might have better chance of working.

Table of known working notebooks:


<table>
<thead>
<tr>
<th>


Model

</th>
<th>


hack (or "how to do it")

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Acer Aspire 1406LC

</td>
<td>


ole's late BIOS init (7), turn off DRI

</td>
</tr>
<tr>
<td>


Acer TM 230

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


Acer TM 242FX

</td>
<td>


vbetool (6)

</td>
</tr>
<tr>
<td>


Acer TM C110

</td>
<td>


video_post (8)

</td>
</tr>
<tr>
<td>


Acer TM C300

</td>
<td>


vga=normal (only suspend on console, not in X), vbetool (6) or video_post (8)

</td>
</tr>
<tr>
<td>


Acer TM 4052LCi

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


Acer TM 636Lci

</td>
<td>


s3_bios,s3_mode (4)

</td>
</tr>
<tr>
<td>


Acer TM 650 (Radeon M7)

</td>
<td>


vga=normal plus boot-radeon (5) gets text console back

</td>
</tr>
<tr>
<td>


Acer TM 660

</td>
<td>


??? <a id="rst-footnote-reference-1"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Acer TM 800

</td>
<td>


vga=normal, X patches, see webpage (5) or vbetool (6)

</td>
</tr>
<tr>
<td>


Acer TM 803

</td>
<td>


vga=normal, X patches, see webpage (5) or vbetool (6)

</td>
</tr>
<tr>
<td>


Acer TM 803LCi

</td>
<td>


vga=normal, vbetool (6)

</td>
</tr>
<tr>
<td>


Arima W730a

</td>
<td>


vbetool needed (6)

</td>
</tr>
<tr>
<td>


Asus L2400D

</td>
<td>


s3_mode (3) <a id="rst-footnote-reference-2"></a>[2](#rst-f2) (S1 also works OK)

</td>
</tr>
<tr>
<td>


Asus L3350M (SiS 740)

</td>
<td>


6. <!-- empty source list item -->

</td>
</tr>
<tr>
<td>


Asus L3800C (Radeon M7)

</td>
<td>


s3_bios (2) (S1 also works OK)

</td>
</tr>
<tr>
<td>


Asus M6887Ne

</td>
<td>


vga=normal, s3_bios (2), use radeon driver instead of fglrx in x.org

</td>
</tr>
<tr>
<td>


Athlon64 desktop prototype

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


Compal CL-50

</td>
<td>


??? <a id="rst-footnote-reference-3"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Compaq Armada E500 - P3-700

</td>
<td>


none (1) (S1 also works OK)

</td>
</tr>
<tr>
<td>


Compaq Evo N620c

</td>
<td>


vga=normal, s3_bios (2)

</td>
</tr>
<tr>
<td>


Dell 600m, ATI R250 Lf

</td>
<td>


none (1), but needs xorg-x11-6.8.1.902-1

</td>
</tr>
<tr>
<td>


Dell D600, ATI RV250

</td>
<td>


vga=normal and X, or try vbestate (6)

</td>
</tr>
<tr>
<td>


Dell D610

</td>
<td>


vga=normal and X (possibly vbestate (6) too, but not tested)

</td>
</tr>
<tr>
<td>


Dell Inspiron 4000

</td>
<td>


??? <a id="rst-footnote-reference-4"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Dell Inspiron 500m

</td>
<td>


??? <a id="rst-footnote-reference-5"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Dell Inspiron 510m

</td>
<td>


???

</td>
</tr>
<tr>
<td>


Dell Inspiron 5150

</td>
<td>


vbetool needed (6)

</td>
</tr>
<tr>
<td>


Dell Inspiron 600m

</td>
<td>


??? <a id="rst-footnote-reference-6"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Dell Inspiron 8200

</td>
<td>


??? <a id="rst-footnote-reference-7"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Dell Inspiron 8500

</td>
<td>


??? <a id="rst-footnote-reference-8"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Dell Inspiron 8600

</td>
<td>


??? <a id="rst-footnote-reference-9"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


eMachines athlon64 machines

</td>
<td>


vbetool needed (6) (someone please get me model \#s)

</td>
</tr>
<tr>
<td>


HP NC6000

</td>
<td>


s3_bios, may not use radeonfb (2); or vbetool (6)

</td>
</tr>
<tr>
<td>


HP NX7000

</td>
<td>


??? <a id="rst-footnote-reference-10"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


HP Pavilion ZD7000

</td>
<td>


vbetool post needed, need open-source nv driver for X

</td>
</tr>
<tr>
<td>


HP Omnibook XE3 athlon version

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


HP Omnibook XE3GC

</td>
<td>


none (1), video is S3 Savage/IX-MV

</td>
</tr>
<tr>
<td>


HP Omnibook XE3L-GF

</td>
<td>


vbetool (6)

</td>
</tr>
<tr>
<td>


HP Omnibook 5150

</td>
<td>


none (1), (S1 also works OK)

</td>
</tr>
<tr>
<td>


IBM TP T20, model 2647-44G

</td>
<td>


none (1), video is S3 Inc. 86C270-294 Savage/IX-MV, vesafb gets "interesting" but X work.

</td>
</tr>
<tr>
<td>


IBM TP A31 / Type 2652-M5G

</td>
<td>


s3_mode (3) \[works ok with BIOS 1.04 2002-08-23, but not at all with BIOS 1.11 2004-11-05 :-(\]

</td>
</tr>
<tr>
<td>


IBM TP R32 / Type 2658-MMG

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


IBM TP R40 2722B3G

</td>
<td>


??? <a id="rst-footnote-reference-11"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


IBM TP R50p / Type 1832-22U

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


IBM TP R51

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


IBM TP T30      236681A

</td>
<td>


??? <a id="rst-footnote-reference-12"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


IBM TP T40 / Type 2373-MU4

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


IBM TP T40p

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


IBM TP R40p

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


IBM TP T41p

</td>
<td>


s3_bios (2), switch to X after resume

</td>
</tr>
<tr>
<td>


IBM TP T42

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


IBM ThinkPad T42p (2373-GTG)

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


IBM TP X20

</td>
<td>


??? <a id="rst-footnote-reference-13"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


IBM TP X30

</td>
<td>


s3_bios, s3_mode (4)

</td>
</tr>
<tr>
<td>


IBM TP X31 / Type 2672-XXH

</td>
<td>


none (1), use radeontool ([http://fdd.com/software/radeon/](<http://fdd.com/software/radeon/>)) to turn off backlight.

</td>
</tr>
<tr>
<td>


IBM TP X32

</td>
<td>


none (1), but backlight is on and video is trashed after long suspend. s3_bios, s3_mode (4) works too. Perhaps that gets better results?

</td>
</tr>
<tr>
<td>


IBM Thinkpad X40 Type 2371-7JG

</td>
<td>


s3_bios,s3_mode (4)

</td>
</tr>
<tr>
<td>


IBM TP 600e

</td>
<td>


none(1), but a switch to console and back to X is needed

</td>
</tr>
<tr>
<td>


Medion MD4220

</td>
<td>


??? <a id="rst-footnote-reference-14"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Samsung P35

</td>
<td>


vbetool needed (6)

</td>
</tr>
<tr>
<td>


Sharp PC-AR10 (ATI rage)

</td>
<td>


none (1), backlight does not switch off

</td>
</tr>
<tr>
<td>


Sony Vaio PCG-C1VRX/K

</td>
<td>


s3_bios (2)

</td>
</tr>
<tr>
<td>


Sony Vaio PCG-F403

</td>
<td>


??? <a id="rst-footnote-reference-15"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Sony Vaio PCG-GRT995MP

</td>
<td>


none (1), works with 'nv' X driver

</td>
</tr>
<tr>
<td>


Sony Vaio PCG-GR7/K

</td>
<td>


none (1), but needs radeonfb, use radeontool ([http://fdd.com/software/radeon/](<http://fdd.com/software/radeon/>)) to turn off backlight.

</td>
</tr>
<tr>
<td>


Sony Vaio PCG-N505SN

</td>
<td>


??? <a id="rst-footnote-reference-16"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Sony Vaio vgn-s260

</td>
<td>


X or boot-radeon can init it (5)

</td>
</tr>
<tr>
<td>


Sony Vaio vgn-S580BH

</td>
<td>


vga=normal, but suspend from X. Console will be blank unless you return to X.

</td>
</tr>
<tr>
<td>


Sony Vaio vgn-FS115B

</td>
<td>


s3_bios (2),s3_mode (4)

</td>
</tr>
<tr>
<td>


Toshiba Libretto L5

</td>
<td>


none (1)

</td>
</tr>
<tr>
<td>


Toshiba Libretto 100CT/110CT

</td>
<td>


vbetool (6)

</td>
</tr>
<tr>
<td>


Toshiba Portege 3020CT

</td>
<td>


s3_mode (3)

</td>
</tr>
<tr>
<td>


Toshiba Satellite 4030CDT

</td>
<td>


s3_mode (3) (S1 also works OK)

</td>
</tr>
<tr>
<td>


Toshiba Satellite 4080XCDT

</td>
<td>


s3_mode (3) (S1 also works OK)

</td>
</tr>
<tr>
<td>


Toshiba Satellite 4090XCDT

</td>
<td>


??? <a id="rst-footnote-reference-17"></a>[1](#rst-f1)

</td>
</tr>
<tr>
<td>


Toshiba Satellite P10-554

</td>
<td>


s3_bios,s3_mode (4) <a id="rst-footnote-reference-18"></a>[3](#rst-f3)

</td>
</tr>
<tr>
<td>


Toshiba M30

</td>
<td>


2. xor X with nvidia driver using internal AGP

</td>
</tr>
<tr>
<td>


Uniwill 244IIO

</td>
<td>


??? <a id="rst-footnote-reference-19"></a>[1](#rst-f1)

</td>
</tr>
</tbody>
</table>

<a id="rst-known-working-desktop-systems"></a>

## Known working desktop systems


<table>
<thead>
<tr>
<th>


Mainboard

</th>
<th>


Graphics card

</th>
<th>


hack (or "how to do it")

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Asus A7V8X

</td>
<td>


nVidia RIVA TNT2 model 64

</td>
<td>


s3_bios,s3_mode (4)

</td>
</tr>
</tbody>
</table>

<a id="rst-f1"></a>



**[1]** from [https://wiki.ubuntu.com/HoaryPMResults](<https://wiki.ubuntu.com/HoaryPMResults>), not sure which options to use. If you know, please tell me.

<a id="rst-f2"></a>



**[2]** To be tested with a newer kernel.

<a id="rst-f3"></a>



**[3]** Not with SMP kernel, UP only.

---

# Dynamic Thermal Power Management framework

_Peios Kernel / Internals / Power / powercap_

> On the embedded world, the complexity of the SoC leads to an increasing number of hotspots which need to be monitored and mitigated as a whole in order to prevent the temperature to go above the normative and legally stated 'skin…

<a id="rst-dynamic-thermal-power-management-framework"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

On the embedded world, the complexity of the SoC leads to an increasing number of hotspots which need to be monitored and mitigated as a whole in order to prevent the temperature to go above the normative and legally stated 'skin temperature'.

Another aspect is to sustain the performance for a given power budget, for example virtual reality where the user can feel dizziness if the performance is capped while a big CPU is processing something else. Or reduce the battery charging because the dissipated power is too high compared with the power consumed by other devices.

The user space is the most adequate place to dynamically act on the different devices by limiting their power given an application profile: it has the knowledge of the platform.

The Dynamic Thermal Power Management (DTPM) is a technique acting on the device power by limiting and/or balancing a power budget among different devices.

The DTPM framework provides an unified interface to act on the device power.

<a id="rst-overview"></a>

## Overview

The DTPM framework relies on the powercap framework to create the powercap entries in the sysfs directory and implement the backend driver to do the connection with the power manageable device.

The DTPM is a tree representation describing the power constraints shared between devices, not their physical positions.

The nodes of the tree are a virtual description aggregating the power characteristics of the children nodes and their power limitations.

The leaves of the tree are the real power manageable devices.

For instance:



```text
SoC
 |
 `-- pkg
      |
      |-- pd0 (cpu0-3)
      |
      `-- pd1 (cpu4-5)
```

The pkg power will be the sum of pd0 and pd1 power numbers:



```text
SoC (400mW - 3100mW)
 |
 `-- pkg (400mW - 3100mW)
      |
      |-- pd0 (100mW - 700mW)
      |
      `-- pd1 (300mW - 2400mW)
```

When the nodes are inserted in the tree, their power characteristics are propagated to the parents:



```text
SoC (600mW - 5900mW)
 |
 |-- pkg (400mW - 3100mW)
 |    |
 |    |-- pd0 (100mW - 700mW)
 |    |
 |    `-- pd1 (300mW - 2400mW)
 |
 `-- pd2 (200mW - 2800mW)
```

Each node have a weight on a 2^10 basis reflecting the percentage of power consumption along the siblings:



```text
SoC (w=1024)
 |
 |-- pkg (w=538)
 |    |
 |    |-- pd0 (w=231)
 |    |
 |    `-- pd1 (w=794)
 |
 `-- pd2 (w=486)

 Note the sum of weights at the same level are equal to 1024.
```

When a power limitation is applied to a node, then it is distributed along the children given their weights. For example, if we set a power limitation of 3200mW at the 'SoC' root node, the resulting tree will be:



```text
SoC (w=1024) <--- power_limit = 3200mW
 |
 |-- pkg (w=538) --> power_limit = 1681mW
 |    |
 |    |-- pd0 (w=231) --> power_limit = 378mW
 |    |
 |    `-- pd1 (w=794) --> power_limit = 1303mW
 |
 `-- pd2 (w=486) --> power_limit = 1519mW
```

<a id="rst-flat-description"></a>

### Flat description

A root node is created and it is the parent of all the nodes. This description is the simplest one and it is supposed to give to user space a flat representation of all the devices supporting the power limitation without any power limitation distribution.

<a id="rst-hierarchical-description"></a>

### Hierarchical description

The different devices supporting the power limitation are represented hierarchically. There is one root node, all intermediate nodes are grouping the child nodes which can be intermediate nodes also or real devices.

The intermediate nodes aggregate the power information and allows to set the power limit given the weight of the nodes.

<a id="rst-user-space-api"></a>

## User space API

As stated in the overview, the DTPM framework is built on top of the powercap framework. Thus the sysfs interface is the same, please refer to the powercap documentation for further details.

> - power_uw: Instantaneous power consumption. If the node is an intermediate node, then the power consumption will be the sum of all children power consumption.
>
> - max_power_range_uw: The power range resulting of the maximum power minus the minimum power.
>
> - name: The name of the node. This is implementation dependent. Even if it is not recommended for the user space, several nodes can have the same name.
>
> - constraint_X_name: The name of the constraint.
>
> - constraint_X_max_power_uw: The maximum power limit to be applicable to the node.
>
> - constraint_X_power_limit_uw: The power limit to be applied to the node. If the value contained in constraint_X_max_power_uw is set, the constraint will be removed.
>
> - constraint_X_time_window_us: The meaning of this file will depend on the constraint number.

<a id="rst-constraints"></a>

### Constraints

> - Constraint 0: The power limitation is immediately applied, without limitation in time.

<a id="rst-kernel-api"></a>

## Kernel API

<a id="rst-overview-1"></a>

### Overview

The DTPM framework has no power limiting backend support. It is generic and provides a set of API to let the different drivers to implement the backend part for the power limitation and create the power constraints tree.

It is up to the platform to provide the initialization function to allocate and link the different nodes of the tree.

A special macro has the role of declaring a node and the corresponding initialization function via a description structure. This one contains an optional parent field allowing to hook different devices to an already existing tree at boot time.

For instance:



```text
struct dtpm_descr my_descr = {
        .name = "my_name",
        .init = my_init_func,
};

DTPM_DECLARE(my_descr);
```

The nodes of the DTPM tree are described with dtpm structure. The steps to add a new power limitable device is done in three steps:

> - Allocate the dtpm node
>
> - Set the power number of the dtpm node
>
> - Register the dtpm node

The registration of the dtpm node is done with the powercap ops. Basically, it must implements the callbacks to get and set the power and the limit.

Alternatively, if the node to be inserted is an intermediate one, then a simple function to insert it as a future parent is available.

If a device has its power characteristics changing, then the tree must be updated with the new power numbers and weights.

<a id="rst-nomenclature"></a>

### Nomenclature

> - dtpm_alloc() : Allocate and initialize a dtpm structure
>
> - dtpm_register() : Add the dtpm node to the tree
>
> - dtpm_unregister() : Remove the dtpm node from the tree
>
> - dtpm_update_power() : Update the power characteristics of the dtpm node

---

# Power Capping Framework

_Peios Kernel / Internals / Power / powercap_

> The power capping framework provides a consistent interface between the kernel and the user space that allows power capping drivers to expose the settings to user space in a uniform way.

<a id="rst-power-capping-framework"></a>

The power capping framework provides a consistent interface between the kernel and the user space that allows power capping drivers to expose the settings to user space in a uniform way.

<a id="rst-terminology"></a>

## Terminology

The framework exposes power capping devices to user space via sysfs in the form of a tree of objects. The objects at the root level of the tree represent 'control types', which correspond to different methods of power capping.  For example, the intel-rapl control type represents the Intel "Running Average Power Limit" (RAPL) technology, whereas the 'idle-injection' control type corresponds to the use of idle injection for controlling power.

Power zones represent different parts of the system, which can be controlled and monitored using the power capping method determined by the control type the given zone belongs to. They each contain attributes for monitoring power, as well as controls represented in the form of power constraints.  If the parts of the system represented by different power zones are hierarchical (that is, one bigger part consists of multiple smaller parts that each have their own power controls), those power zones may also be organized in a hierarchy with one parent power zone containing multiple subzones and so on to reflect the power control topology of the system.  In that case, it is possible to apply power capping to a set of devices together using the parent power zone and if more fine grained control is required, it can be applied through the subzones.

Example sysfs interface tree:



```text
/sys/devices/virtual/powercap
└──intel-rapl
    ├──intel-rapl:0
    │   ├──constraint_0_name
    │   ├──constraint_0_power_limit_uw
    │   ├──constraint_0_time_window_us
    │   ├──constraint_1_name
    │   ├──constraint_1_power_limit_uw
    │   ├──constraint_1_time_window_us
    │   ├──device -> ../../intel-rapl
    │   ├──energy_uj
    │   ├──intel-rapl:0:0
    │   │   ├──constraint_0_name
    │   │   ├──constraint_0_power_limit_uw
    │   │   ├──constraint_0_time_window_us
    │   │   ├──constraint_1_name
    │   │   ├──constraint_1_power_limit_uw
    │   │   ├──constraint_1_time_window_us
    │   │   ├──device -> ../../intel-rapl:0
    │   │   ├──energy_uj
    │   │   ├──max_energy_range_uj
    │   │   ├──name
    │   │   ├──enabled
    │   │   ├──power
    │   │   │   ├──async
    │   │   │   []
    │   │   ├──subsystem -> ../../../../../../class/power_cap
    │   │   └──uevent
    │   ├──intel-rapl:0:1
    │   │   ├──constraint_0_name
    │   │   ├──constraint_0_power_limit_uw
    │   │   ├──constraint_0_time_window_us
    │   │   ├──constraint_1_name
    │   │   ├──constraint_1_power_limit_uw
    │   │   ├──constraint_1_time_window_us
    │   │   ├──device -> ../../intel-rapl:0
    │   │   ├──energy_uj
    │   │   ├──max_energy_range_uj
    │   │   ├──name
    │   │   ├──enabled
    │   │   ├──power
    │   │   │   ├──async
    │   │   │   []
    │   │   ├──subsystem -> ../../../../../../class/power_cap
    │   │   └──uevent
    │   ├──max_energy_range_uj
    │   ├──max_power_range_uw
    │   ├──name
    │   ├──enabled
    │   ├──power
    │   │   ├──async
    │   │   []
    │   ├──subsystem -> ../../../../../class/power_cap
    │   ├──enabled
    │   ├──uevent
    ├──intel-rapl:1
    │   ├──constraint_0_name
    │   ├──constraint_0_power_limit_uw
    │   ├──constraint_0_time_window_us
    │   ├──constraint_1_name
    │   ├──constraint_1_power_limit_uw
    │   ├──constraint_1_time_window_us
    │   ├──device -> ../../intel-rapl
    │   ├──energy_uj
    │   ├──intel-rapl:1:0
    │   │   ├──constraint_0_name
    │   │   ├──constraint_0_power_limit_uw
    │   │   ├──constraint_0_time_window_us
    │   │   ├──constraint_1_name
    │   │   ├──constraint_1_power_limit_uw
    │   │   ├──constraint_1_time_window_us
    │   │   ├──device -> ../../intel-rapl:1
    │   │   ├──energy_uj
    │   │   ├──max_energy_range_uj
    │   │   ├──name
    │   │   ├──enabled
    │   │   ├──power
    │   │   │   ├──async
    │   │   │   []
    │   │   ├──subsystem -> ../../../../../../class/power_cap
    │   │   └──uevent
    │   ├──intel-rapl:1:1
    │   │   ├──constraint_0_name
    │   │   ├──constraint_0_power_limit_uw
    │   │   ├──constraint_0_time_window_us
    │   │   ├──constraint_1_name
    │   │   ├──constraint_1_power_limit_uw
    │   │   ├──constraint_1_time_window_us
    │   │   ├──device -> ../../intel-rapl:1
    │   │   ├──energy_uj
    │   │   ├──max_energy_range_uj
    │   │   ├──name
    │   │   ├──enabled
    │   │   ├──power
    │   │   │   ├──async
    │   │   │   []
    │   │   ├──subsystem -> ../../../../../../class/power_cap
    │   │   └──uevent
    │   ├──max_energy_range_uj
    │   ├──max_power_range_uw
    │   ├──name
    │   ├──enabled
    │   ├──power
    │   │   ├──async
    │   │   []
    │   ├──subsystem -> ../../../../../class/power_cap
    │   ├──uevent
    ├──power
    │   ├──async
    │   []
    ├──subsystem -> ../../../../class/power_cap
    ├──enabled
    └──uevent
```

The above example illustrates a case in which the Intel RAPL technology, available in Intel® IA-64 and IA-32 Processor Architectures, is used. There is one control type called intel-rapl which contains two power zones, intel-rapl:0 and intel-rapl:1, representing CPU packages.  Each of these power zones contains two subzones, intel-rapl:j:0 and intel-rapl:j:1 (j = 0, 1), representing the "core" and the "uncore" parts of the given CPU package, respectively.  All of the zones and subzones contain energy monitoring attributes (energy_uj, max_energy_range_uj) and constraint attributes (constraint\_\*) allowing controls to be applied (the constraints in the 'package' power zones apply to the whole CPU packages and the subzone constraints only apply to the respective parts of the given package individually). Since Intel RAPL doesn't provide instantaneous power value, there is no power_uw attribute.

In addition to that, each power zone contains a name attribute, allowing the part of the system represented by that zone to be identified. For example:



```text
cat /sys/class/power_cap/intel-rapl/intel-rapl:0/name
```

<a id="rst-package-0"></a>

### package-0

Depending on different power zones, the Intel RAPL technology allows one or multiple constraints like short term, long term and peak power, with different time windows to be applied to each power zone. All the zones contain attributes representing the constraint names, power limits and the sizes of the time windows. Note that time window is not applicable to peak power. Here, constraint_j\_\* attributes correspond to the jth constraint (j = 0,1,2).

For example:



```text
constraint_0_name
constraint_0_power_limit_uw
constraint_0_time_window_us
constraint_1_name
constraint_1_power_limit_uw
constraint_1_time_window_us
constraint_2_name
constraint_2_power_limit_uw
constraint_2_time_window_us
```

<a id="rst-power-zone-attributes"></a>

## Power Zone Attributes

<a id="rst-monitoring-attributes"></a>

### Monitoring attributes

- **energy_uj (rw)**

  Current energy counter in micro joules. Write "0" to reset. If the counter can not be reset, then this attribute is read only.

- **max_energy_range_uj (ro)**

  Range of the above energy counter in micro-joules.

- **power_uw (ro)**

  Current power in micro watts.

- **max_power_range_uw (ro)**

  Range of the above power value in micro-watts.

- **name (ro)**

  Name of this power zone.

It is possible that some domains have both power ranges and energy counter ranges; however, only one is mandatory.

<a id="rst-constraints"></a>

### Constraints

- **constraint_X_power_limit_uw (rw)**

  Power limit in micro watts, which should be applicable for the time window specified by "constraint_X_time_window_us".

- **constraint_X_time_window_us (rw)**

  Time window in micro seconds.

- **constraint_X_name (ro)**

  An optional name of the constraint

- **constraint_X_max_power_uw(ro)**

  Maximum allowed power in micro watts.

- **constraint_X_min_power_uw(ro)**

  Minimum allowed power in micro watts.

- **constraint_X_max_time_window_us(ro)**

  Maximum allowed time window in micro seconds.

- **constraint_X_min_time_window_us(ro)**

  Minimum allowed time window in micro seconds.

Except power_limit_uw and time_window_us other fields are optional.

<a id="rst-common-zone-and-control-type-attributes"></a>

### Common zone and control type attributes

enabled (rw): Enable/Disable controls at zone level or for all zones using a control type.

<a id="rst-power-cap-client-driver-interface"></a>

## Power Cap Client Driver Interface

The API summary:

Call powercap_register_control_type() to register control type object. Call powercap_register_zone() to register a power zone (under a given control type), either as a top-level power zone or as a subzone of another power zone registered earlier. The number of constraints in a power zone and the corresponding callbacks have to be defined prior to calling powercap_register_zone() to register that zone.

To Free a power zone call powercap_unregister_zone(). To free a control type object call powercap_unregister_control_type(). Detailed API can be generated using kernel-doc on include/linux/powercap.h.

---

# Regulator Consumer Driver Interface

_Peios Kernel / Internals / Power / regulator_

> This text describes the regulator interface for consumer device drivers. Please see overview.txt for a description of the terms used in this text.

<a id="rst-regulator-consumer-driver-interface"></a>

This text describes the regulator interface for consumer device drivers. Please see overview.txt for a description of the terms used in this text.

<a id="rst-consumer-regulator-access-static-dynamic-drivers"></a>

## 1. Consumer Regulator Access (static &amp; dynamic drivers)

A consumer driver can get access to its supply regulator by calling



```text
regulator = regulator_get(dev, "Vcc");
```

The consumer passes in its struct device pointer and power supply ID. The core then finds the correct regulator by consulting a machine specific lookup table. If the lookup is successful then this call will return a pointer to the struct regulator that supplies this consumer.

To release the regulator the consumer driver should call



```text
regulator_put(regulator);
```

Consumers can be supplied by more than one regulator e.g. codec consumer with analog and digital supplies by means of bulk operations



```text
struct regulator_bulk_data supplies[2];

supplies[0].supply = "Vcc"; /* digital core */
supplies[1].supply = "Avdd"; /* analog */

ret = regulator_bulk_get(dev, ARRAY_SIZE(supplies), supplies);

// convenience helper to call regulator_put() on multiple regulators
regulator_bulk_free(ARRAY_SIZE(supplies), supplies);
```

The regulator access functions regulator_get() and regulator_put() will usually be called in your device drivers probe() and remove() respectively.

<a id="rst-regulator-output-enable-disable-static-dynamic-drivers"></a>

## 2. Regulator Output Enable &amp; Disable (static &amp; dynamic drivers)

A consumer can enable its power supply by calling:



```text
int regulator_enable(regulator);
```

- **NOTE:**

  The supply may already be enabled before regulator_enable() is called. This may happen if the consumer shares the regulator or the regulator has been previously enabled by bootloader or kernel board initialization code.

A consumer can determine if a regulator is enabled by calling:



```text
int regulator_is_enabled(regulator);
```

This will return &gt; zero when the regulator is enabled.

A set of regulators can be enabled with a single bulk operation



```text
int regulator_bulk_enable(int num_consumers,
                          struct regulator_bulk_data *consumers);
```

A consumer can disable its supply when no longer needed by calling:



```text
int regulator_disable(regulator);
```

Or a number of them



```text
int regulator_bulk_disable(int num_consumers,
                           struct regulator_bulk_data *consumers);
```

- **NOTE:**

  This may not disable the supply if it's shared with other consumers. The regulator will only be disabled when the enabled reference count is zero.

Finally, a regulator can be forcefully disabled in the case of an emergency:



```text
int regulator_force_disable(regulator);
```

This operation is also supported for multiple regulators



```text
int regulator_bulk_force_disable(int num_consumers,
                                 struct regulator_bulk_data *consumers);
```

- **NOTE:**

  this will immediately and forcefully shutdown the regulator output. All consumers will be powered off.

<a id="rst-regulator-voltage-control-status-dynamic-drivers"></a>

## 3. Regulator Voltage Control &amp; Status (dynamic drivers)

Some consumer drivers need to be able to dynamically change their supply voltage to match system operating points. e.g. CPUfreq drivers can scale voltage along with frequency to save power, SD drivers may need to select the correct card voltage, etc.

Consumers can control their supply voltage by calling:



```text
int regulator_set_voltage(regulator, min_uV, max_uV);
```

Where min_uV and max_uV are the minimum and maximum acceptable voltages in microvolts.

NOTE: this can be called when the regulator is enabled or disabled. If called when enabled, then the voltage changes instantly, otherwise the voltage configuration changes and the voltage is physically set when the regulator is next enabled.

The regulators configured voltage output can be found by calling:



```text
int regulator_get_voltage(regulator);
```

- **NOTE:**

  get_voltage() will return the configured output voltage whether the regulator is enabled or disabled and should NOT be used to determine regulator output state. However this can be used in conjunction with is_enabled() to determine the regulator physical output voltage.

<a id="rst-regulator-current-limit-control-status-dynamic-drivers"></a>

## 4. Regulator Current Limit Control &amp; Status (dynamic drivers)

Some consumer drivers need to be able to dynamically change their supply current limit to match system operating points. e.g. LCD backlight driver can change the current limit to vary the backlight brightness, USB drivers may want to set the limit to 500mA when supplying power.

Consumers can control their supply current limit by calling:



```text
int regulator_set_current_limit(regulator, min_uA, max_uA);
```

Where min_uA and max_uA are the minimum and maximum acceptable current limit in microamps.

- **NOTE:**

  this can be called when the regulator is enabled or disabled. If called when enabled, then the current limit changes instantly, otherwise the current limit configuration changes and the current limit is physically set when the regulator is next enabled.

A regulators current limit can be found by calling:



```text
int regulator_get_current_limit(regulator);
```

- **NOTE:**

  get_current_limit() will return the current limit whether the regulator is enabled or disabled and should not be used to determine regulator current load.

<a id="rst-regulator-operating-mode-control-status-dynamic-drivers"></a>

## 5. Regulator Operating Mode Control &amp; Status (dynamic drivers)

Some consumers can further save system power by changing the operating mode of their supply regulator to be more efficient when the consumers operating state changes. e.g. consumer driver is idle and subsequently draws less current

Regulator operating mode can be changed indirectly or directly.

<a id="rst-indirect-operating-mode-control"></a>

### Indirect operating mode control.

Consumer drivers can request a change in their supply regulator operating mode by calling:



```text
int regulator_set_load(struct regulator *regulator, int load_uA);
```

This will cause the core to recalculate the total load on the regulator (based on all its consumers) and change operating mode (if necessary and permitted) to best match the current operating load.

The load_uA value can be determined from the consumer's datasheet. e.g. most datasheets have tables showing the maximum current consumed in certain situations.

Most consumers will use indirect operating mode control since they have no knowledge of the regulator or whether the regulator is shared with other consumers.

<a id="rst-direct-operating-mode-control"></a>

### Direct operating mode control.

Bespoke or tightly coupled drivers may want to directly control regulator operating mode depending on their operating point. This can be achieved by calling:



```text
int regulator_set_mode(struct regulator *regulator, unsigned int mode);
unsigned int regulator_get_mode(struct regulator *regulator);
```

Direct mode will only be used by consumers that *know* about the regulator and are not sharing the regulator with other consumers.

<a id="rst-regulator-events"></a>

## 6. Regulator Events

Regulators can notify consumers of external events. Events could be received by consumers under regulator stress or failure conditions.

Consumers can register interest in regulator events by calling:



```text
int regulator_register_notifier(struct regulator *regulator,
                                struct notifier_block *nb);
```

Consumers can unregister interest by calling:



```text
int regulator_unregister_notifier(struct regulator *regulator,
                                  struct notifier_block *nb);
```

Regulators use the kernel notifier framework to send event to their interested consumers.

<a id="rst-regulator-direct-register-access"></a>

## 7. Regulator Direct Register Access

Some kinds of power management hardware or firmware are designed such that they need to do low-level hardware access to regulators, with no involvement from the kernel. Examples of such devices are:

- clocksource with a voltage-controlled oscillator and control logic to change the supply voltage over I2C to achieve a desired output clock rate

- thermal management firmware that can issue an arbitrary I2C transaction to perform system poweroff during overtemperature conditions

To set up such a device/firmware, various parameters like I2C address of the regulator, addresses of various regulator registers etc. need to be configured to it. The regulator framework provides the following helpers for querying these details.

Bus-specific details, like I2C addresses or transfer rates are handled by the regmap framework. To get the regulator's regmap (if supported), use:



```text
struct regmap *regulator_get_regmap(struct regulator *regulator);
```

To obtain the hardware register offset and bitmask for the regulator's voltage selector register, use:



```text
int regulator_get_hardware_vsel_register(struct regulator *regulator,
                                         unsigned *vsel_reg,
                                         unsigned *vsel_mask);
```

To convert a regulator framework voltage selector code (used by regulator_list_voltage) to a hardware-specific voltage selector that can be directly written to the voltage selector register, use:



```text
int regulator_list_hardware_vsel(struct regulator *regulator,
                                 unsigned selector);
```

To access the hardware for enabling/disabling the regulator, consumers must use regulator_get_exclusive(), as it can't work if there's more than one consumer. To enable/disable regulator use:



```text
int regulator_hardware_enable(struct regulator *regulator, bool enable);
```

---

# Regulator API design notes

_Peios Kernel / Internals / Power / regulator_

> This document provides a brief, partially structured, overview of some of the design considerations which impact the regulator API design.

<a id="rst-regulator-api-design-notes"></a>

This document provides a brief, partially structured, overview of some of the design considerations which impact the regulator API design.

<a id="rst-safety"></a>

## Safety

> - Errors in regulator configuration can have very serious consequences for the system, potentially including lasting hardware damage.
>
> - It is not possible to automatically determine the power configuration of the system - software-equivalent variants of the same chip may have different power requirements, and not all components with power requirements are visible to software.

> [!NOTE]
>
> The API should make no changes to the hardware state unless it has specific knowledge that these changes are safe to perform on this particular system.

<a id="rst-consumer-use-cases"></a>

## Consumer use cases

> - The overwhelming majority of devices in a system will have no requirement to do any runtime configuration of their power beyond being able to turn it on or off.
>
> - Many of the power supplies in the system will be shared between many different consumers.

> [!NOTE]
>
> The consumer API should be structured so that these use cases are very easy to handle and so that consumers will work with shared supplies without any additional effort.

---

# Regulator Machine Driver Interface

_Peios Kernel / Internals / Power / regulator_

> The regulator machine driver interface is intended for board/machine specific initialisation code to configure the regulator subsystem.

<a id="rst-regulator-machine-driver-interface"></a>

The regulator machine driver interface is intended for board/machine specific initialisation code to configure the regulator subsystem.

Consider the following machine:



```text
Regulator-1 -+-> Regulator-2 --> [Consumer A @ 1.8 - 2.0V]
             |
             +-> [Consumer B @ 3.3V]
```

The drivers for consumers A &amp; B must be mapped to the correct regulator in order to control their power supplies. This mapping can be achieved in machine initialisation code by creating a struct regulator_consumer_supply for each regulator:



```text
struct regulator_consumer_supply {
      const char *dev_name;   /* consumer dev_name() */
      const char *supply;     /* consumer supply - e.g. "vcc" */
};
```

e.g. for the machine above:



```text
static struct regulator_consumer_supply regulator1_consumers[] = {
      REGULATOR_SUPPLY("Vcc", "consumer B"),
};

static struct regulator_consumer_supply regulator2_consumers[] = {
      REGULATOR_SUPPLY("Vcc", "consumer A"),
};
```

This maps Regulator-1 to the 'Vcc' supply for Consumer B and maps Regulator-2 to the 'Vcc' supply for Consumer A.

Constraints can now be registered by defining a struct regulator_init_data for each regulator power domain. This structure also maps the consumers to their supply regulators:



```text
static struct regulator_init_data regulator1_data = {
      .constraints = {
              .name = "Regulator-1",
              .min_uV = 3300000,
              .max_uV = 3300000,
              .valid_modes_mask = REGULATOR_MODE_NORMAL,
      },
      .num_consumer_supplies = ARRAY_SIZE(regulator1_consumers),
      .consumer_supplies = regulator1_consumers,
};
```

The name field should be set to something that is usefully descriptive for the board for configuration of supplies for other regulators and for use in logging and other diagnostic output.  Normally the name used for the supply rail in the schematic is a good choice.  If no name is provided then the subsystem will choose one.

Regulator-1 supplies power to Regulator-2. This relationship must be registered with the core so that Regulator-1 is also enabled when Consumer A enables its supply (Regulator-2). The supply regulator is set by the supply_regulator field below and co:



```text
static struct regulator_init_data regulator2_data = {
      .supply_regulator = "Regulator-1",
      .constraints = {
              .min_uV = 1800000,
              .max_uV = 2000000,
              .valid_ops_mask = REGULATOR_CHANGE_VOLTAGE,
              .valid_modes_mask = REGULATOR_MODE_NORMAL,
      },
      .num_consumer_supplies = ARRAY_SIZE(regulator2_consumers),
      .consumer_supplies = regulator2_consumers,
};
```

Finally the regulator devices must be registered in the usual manner:



```text
static struct platform_device regulator_devices[] = {
      {
              .name = "regulator",
              .id = DCDC_1,
              .dev = {
                      .platform_data = &regulator1_data,
              },
      },
      {
              .name = "regulator",
              .id = DCDC_2,
              .dev = {
                      .platform_data = &regulator2_data,
              },
      },
};
/* register regulator 1 device */
platform_device_register(&regulator_devices[0]);

/* register regulator 2 device */
platform_device_register(&regulator_devices[1]);
```

---

# Linux voltage and current regulator framework

_Peios Kernel / Internals / Power / regulator_

> This framework is designed to provide a standard kernel interface to control voltage and current regulators.

<a id="rst-linux-voltage-and-current-regulator-framework"></a>

<a id="rst-about"></a>

## About

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).

- **(C)** 2008  Wolfson Microelectronics PLC.

Author: Liam Girdwood &lt;[lrg@slimlogic.co.uk](<mailto:lrg@slimlogic.co.uk>)&gt;

<a id="rst-nomenclature"></a>

## Nomenclature

Some terms used in this document:

> - - **Regulator**
>
>     - Electronic device that supplies power to other devices. Most regulators can enable and disable their output while some can control their output voltage and or current.
>
>       Input Voltage -&gt; Regulator -&gt; Output Voltage
>
> - - **PMIC**
>
>     - Power Management IC. An IC that contains numerous regulators and often contains other subsystems.
>
> - - **Consumer**
>
>     - Electronic device that is supplied power by a regulator. Consumers can be classified into two types:-
>
>       Static: consumer does not change its supply voltage or current limit. It only needs to enable or disable its power supply. Its supply voltage is set by the hardware, bootloader, firmware or kernel board initialisation code.
>
>       Dynamic: consumer needs to change its supply voltage or current limit to meet operation demands.
>
> - - **Power Domain**
>
>     - Electronic circuit that is supplied its input power by the output power of a regulator, switch or by another power domain.
>
>       The supply regulator may be behind a switch(s). i.e.:
>
>
>
>       ```text
>       Regulator -+-> Switch-1 -+-> Switch-2 --> [Consumer A]
>                  |             |
>                  |             +-> [Consumer B], [Consumer C]
>                  |
>                  +-> [Consumer D], [Consumer E]
>       ```
>
>       That is one regulator and three power domains:
>
>       - Domain 1: Switch-1, Consumers D &amp; E.
>
>       - Domain 2: Switch-2, Consumers B &amp; C.
>
>       - Domain 3: Consumer A.
>
>       and this represents a "supplies" relationship:
>
>       Domain-1 --&gt; Domain-2 --&gt; Domain-3.
>
>       A power domain may have regulators that are supplied power by other regulators. i.e.:
>
>
>
>       ```text
>       Regulator-1 -+-> Regulator-2 -+-> [Consumer A]
>                    |
>                    +-> [Consumer B]
>       ```
>
>       This gives us two regulators and two power domains:
>
>       - Domain 1: Regulator-2, Consumer B.
>
>       - Domain 2: Consumer A.
>
>       and a "supplies" relationship:
>
>       Domain-1 --&gt; Domain-2
>
> - - **Constraints**
>
>     - Constraints are used to define power levels for performance and hardware protection. Constraints exist at three levels:
>
>       Regulator Level: This is defined by the regulator hardware operating parameters and is specified in the regulator datasheet. i.e.
>
>       > - voltage output is in the range 800mV -&gt; 3500mV.
>       >
>       > - regulator current output limit is 20mA @ 5V but is 10mA @ 10V.
>
>       Power Domain Level: This is defined in software by kernel level board initialisation code. It is used to constrain a power domain to a particular power range. i.e.
>
>       > - Domain-1 voltage is 3300mV
>       >
>       > - Domain-2 voltage is 1400mV -&gt; 1600mV
>       >
>       > - Domain-3 current limit is 0mA -&gt; 20mA.
>
>       Consumer Level: This is defined by consumer drivers dynamically setting voltage or current limit levels.
>
>       e.g. a consumer backlight driver asks for a current increase from 5mA to 10mA to increase LCD illumination. This passes to through the levels as follows :-
>
>       Consumer: need to increase LCD brightness. Lookup and request next current mA value in brightness table (the consumer driver could be used on several different personalities based upon the same reference device).
>
>       Power Domain: is the new current limit within the domain operating limits for this domain and system state (e.g. battery power, USB power)
>
>       Regulator Domains: is the new current limit within the regulator operating parameters for input/output voltage.
>
>       If the regulator request passes all the constraint tests then the new regulator value is applied.

<a id="rst-design"></a>

## Design

The framework is designed and targeted at SoC based devices but may also be relevant to non SoC devices and is split into the following four interfaces:-

> 1. Consumer driver interface.
>
>    This uses a similar API to the kernel clock interface in that consumer drivers can get and put a regulator (like they can with clocks atm) and get/set voltage, current limit, mode, enable and disable. This should allow consumers complete control over their supply voltage and current limit. This also compiles out if not in use so drivers can be reused in systems with no regulator based power control.
>
>    > See [Documentation/power/regulator/consumer.rst](/kernel/internals/power/regulator/consumer.md)
>
> 2. Regulator driver interface.
>
>    This allows regulator drivers to register their regulators and provide operations to the core. It also has a notifier call chain for propagating regulator events to clients.
>
>    > See [Documentation/power/regulator/regulator.rst](/kernel/internals/power/regulator/regulator.md)
>
> 3. Machine interface.
>
>    This interface is for machine specific code and allows the creation of voltage/current domains (with constraints) for each regulator. It can provide regulator constraints that will prevent device damage through overvoltage or overcurrent caused by buggy client drivers. It also allows the creation of a regulator tree whereby some regulators are supplied by others (similar to a clock tree).
>
>    > See [Documentation/power/regulator/machine.rst](/kernel/internals/power/regulator/machine.md)
>
> 4. Userspace ABI.
>
>    The framework also exports a lot of useful voltage/current/opmode data to userspace via sysfs. This could be used to help monitor device power consumption and status.
>
>    > See Documentation/ABI/testing/sysfs-class-regulator

---

# Regulator Driver Interface

_Peios Kernel / Internals / Power / regulator_

> The regulator driver interface is relatively simple and designed to allow regulator drivers to register their services with the core framework.

<a id="rst-regulator-driver-interface"></a>

The regulator driver interface is relatively simple and designed to allow regulator drivers to register their services with the core framework.

<a id="rst-registration"></a>

## Registration

Drivers can register a regulator by calling:



```text
struct regulator_dev *regulator_register(struct regulator_desc *regulator_desc,
                                         const struct regulator_config *config);
```

This will register the regulator's capabilities and operations to the regulator core.

Regulators can be unregistered by calling:



```text
void regulator_unregister(struct regulator_dev *rdev);
```

<a id="rst-regulator-events"></a>

## Regulator Events

Regulators can send events (e.g. overtemperature, undervoltage, etc) to consumer drivers by calling:



```text
int regulator_notifier_call_chain(struct regulator_dev *rdev,
                                  unsigned long event, void *data);
```

---

# Virtualization Support

_Peios Kernel / Internals / Virtualisation_

> Reference for Virtualization Support.

<a id="rst-virtualization-support"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [KVM](</kernel/internals/virt/kvm/index.md>)
- [UML HowTo](</kernel/internals/virt/uml/user-mode-linux-howto-v2.md>)
- [Paravirt_ops](</kernel/internals/virt/paravirt-ops.md>)
- [Guest halt polling](</kernel/internals/virt/guest-halt-polling.md>)
- [Nitro Enclaves](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/virt/ne_overview.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [ACRN Hypervisor](</kernel/internals/virt/acrn/index.md>)
- [The Definitive SEV Guest API Documentation](</kernel/internals/virt/coco/sev-guest.md>)
- [TDX Guest API Documentation](</kernel/internals/virt/coco/tdx-guest.md>)
- [Hyper-V Enlightenments](</kernel/internals/virt/hyperv/index.md>)

---

# Guest halt polling

_Peios Kernel / Internals / Virtualisation_

> The cpuidle_haltpoll driver, with the haltpoll governor, allows the guest vcpus to poll for a specified amount of time before halting.

<a id="rst-guest-halt-polling"></a>

The cpuidle_haltpoll driver, with the haltpoll governor, allows the guest vcpus to poll for a specified amount of time before halting.

This provides the following benefits to host side polling:

> 1. The POLL flag is set while polling is performed, which allows a remote vCPU to avoid sending an IPI (and the associated cost of handling the IPI) when performing a wakeup.
>
> 2. The VM-exit cost can be avoided.

The downside of guest side polling is that polling is performed even with other runnable tasks in the host.

The basic logic as follows: A global value, guest_halt_poll_ns, is configured by the user, indicating the maximum amount of time polling is allowed. This value is fixed.

Each vcpu has an adjustable guest_halt_poll_ns ("per-cpu guest_halt_poll_ns"), which is adjusted by the algorithm in response to events (explained below).

<a id="rst-module-parameters"></a>

## Module Parameters

The haltpoll governor has 5 tunable module parameters:

1. guest_halt_poll_ns:

Maximum amount of time, in nanoseconds, that polling is performed before halting.

Default: 200000

2. guest_halt_poll_shrink:

Division factor used to shrink per-cpu guest_halt_poll_ns when wakeup event occurs after the global guest_halt_poll_ns.

Default: 2

3. guest_halt_poll_grow:

Multiplication factor used to grow per-cpu guest_halt_poll_ns when event occurs after per-cpu guest_halt_poll_ns but before global guest_halt_poll_ns.

Default: 2

4. guest_halt_poll_grow_start:

The per-cpu guest_halt_poll_ns eventually reaches zero in case of an idle system. This value sets the initial per-cpu guest_halt_poll_ns when growing. This can be increased from 10000, to avoid misses during the initial growth stage:

10k, 20k, 40k, ... (example assumes guest_halt_poll_grow=2).

Default: 50000

5. guest_halt_poll_allow_shrink:

Bool parameter which allows shrinking. Set to N to avoid it (per-cpu guest_halt_poll_ns will remain high once achieves global guest_halt_poll_ns value).

Default: Y

The module parameters can be set from the sysfs files in:



```text
/sys/module/haltpoll/parameters/
```

<a id="rst-further-notes"></a>

## Further Notes

- Care should be taken when setting the guest_halt_poll_ns parameter as a large value has the potential to drive the cpu usage to 100% on a machine which would be almost entirely idle otherwise.

---

# Nitro Enclaves

_Peios Kernel / Internals / Virtualisation_

> Nitro Enclaves (NE) is a new Amazon Elastic Compute Cloud (EC2) capability that allows customers to carve out isolated compute environments within EC2 instances [1].

<a id="rst-nitro-enclaves"></a>

<a id="rst-overview"></a>

## Overview

<!-- SPDX-License-Identifier: GPL-2.0 -->

Nitro Enclaves (NE) is a new Amazon Elastic Compute Cloud (EC2) capability that allows customers to carve out isolated compute environments within EC2 instances \[1\].

For example, an application that processes sensitive data and runs in a VM, can be separated from other applications running in the same VM. This application then runs in a separate VM than the primary VM, namely an enclave. It runs alongside the VM that spawned it. This setup matches low latency applications needs.

The current supported architectures for the NE kernel driver, available in the upstream Linux kernel, are x86 and ARM64.

The resources that are allocated for the enclave, such as memory and CPUs, are carved out of the primary VM. Each enclave is mapped to a process running in the primary VM, that communicates with the NE kernel driver via an ioctl interface.

In this sense, there are two components:

1\. An enclave abstraction process - a user space process running in the primary VM guest that uses the provided ioctl interface of the NE driver to spawn an enclave VM (that's 2 below).

There is a NE emulated PCI device exposed to the primary VM. The driver for this new PCI device is included in the NE driver.

The ioctl logic is mapped to PCI device commands e.g. the NE\_START\_ENCLAVE ioctl maps to an enclave start PCI command. The PCI device commands are then translated into  actions taken on the hypervisor side; that's the Nitro hypervisor running on the host where the primary VM is running. The Nitro hypervisor is based on core KVM technology.

2\. The enclave itself - a VM running on the same host as the primary VM that spawned it. Memory and CPUs are carved out of the primary VM and are dedicated for the enclave VM. An enclave does not have persistent storage attached.

The memory regions carved out of the primary VM and given to an enclave need to be aligned 2 MiB / 1 GiB physically contiguous memory regions (or multiple of this size e.g. 8 MiB). The memory can be allocated e.g. by using hugetlbfs from user space \[2\]\[3\]\[7\]. The memory size for an enclave needs to be at least 64 MiB. The enclave memory and CPUs need to be from the same NUMA node.

An enclave runs on dedicated cores. CPU 0 and its CPU siblings need to remain available for the primary VM. A CPU pool has to be set for NE purposes by an user with admin capability. See the cpu list section from the kernel documentation \[4\] for how a CPU pool format looks.

An enclave communicates with the primary VM via a local communication channel, using virtio-vsock \[5\]. The primary VM has virtio-pci vsock emulated device, while the enclave VM has a virtio-mmio vsock emulated device. The vsock device uses eventfd for signaling. The enclave VM sees the usual interfaces - local APIC and IOAPIC - to get interrupts from virtio-vsock device. The virtio-mmio device is placed in memory below the typical 4 GiB.

The application that runs in the enclave needs to be packaged in an enclave image together with the OS ( e.g. kernel, ramdisk, init ) that will run in the enclave VM. The enclave VM has its own kernel and follows the standard Linux boot protocol \[6\]\[8\].

The kernel bzImage, the kernel command line, the ramdisk(s) are part of the Enclave Image Format (EIF); plus an EIF header including metadata such as magic number, eif version, image size and CRC.

Hash values are computed for the entire enclave image (EIF), the kernel and ramdisk(s). That's used, for example, to check that the enclave image that is loaded in the enclave VM is the one that was intended to be run.

These crypto measurements are included in a signed attestation document generated by the Nitro Hypervisor and further used to prove the identity of the enclave; KMS is an example of service that NE is integrated with and that checks the attestation doc.

The enclave image (EIF) is loaded in the enclave memory at offset 8 MiB. The init process in the enclave connects to the vsock CID of the primary VM and a predefined port - 9000 - to send a heartbeat value - 0xb7. This mechanism is used to check in the primary VM that the enclave has booted. The CID of the primary VM is 3.

If the enclave VM crashes or gracefully exits, an interrupt event is received by the NE driver. This event is sent further to the user space enclave process running in the primary VM via a poll notification mechanism. Then the user space enclave process can exit.

\[1\] [https://aws.amazon.com/ec2/nitro/nitro-enclaves/](<https://aws.amazon.com/ec2/nitro/nitro-enclaves/>) \[2\] [https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html](<https://www.kernel.org/doc/html/latest/admin-guide/mm/hugetlbpage.html>) \[3\] [https://lwn.net/Articles/807108/](<https://lwn.net/Articles/807108/>) \[4\] [https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html](<https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html>) \[5\] [https://man7.org/linux/man-pages/man7/vsock.7.html](<https://man7.org/linux/man-pages/man7/vsock.7.html>) \[6\] [https://www.kernel.org/doc/html/latest/x86/boot.html](<https://www.kernel.org/doc/html/latest/x86/boot.html>) \[7\] [https://www.kernel.org/doc/html/latest/arm64/hugetlbpage.html](<https://www.kernel.org/doc/html/latest/arm64/hugetlbpage.html>) \[8\] [https://www.kernel.org/doc/html/latest/arm64/booting.html](<https://www.kernel.org/doc/html/latest/arm64/booting.html>)

---

# Paravirt_ops

_Peios Kernel / Internals / Virtualisation_

> Linux provides support for different hypervisor virtualization technologies. Historically, different binary kernels would be required in order to support different hypervisors; this restriction was removed with pv_ops. Linux pv_ops is a…

<a id="rst-paravirt-ops"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Linux provides support for different hypervisor virtualization technologies. Historically, different binary kernels would be required in order to support different hypervisors; this restriction was removed with pv_ops. Linux pv_ops is a virtualization API which enables support for different hypervisors. It allows each hypervisor to override critical operations and allows a single kernel binary to run on all supported execution environments including native machine -- without any hypervisors.

pv_ops provides a set of function pointers which represent operations corresponding to low-level critical instructions and high-level functionalities in various areas. pv_ops allows for optimizations at run time by enabling binary patching of the low-level critical operations at boot time.

pv_ops operations are classified into three categories:

- - **simple indirect call**

    These operations correspond to high-level functionality where it is known that the overhead of indirect call isn't very important.

- - **indirect call which allows optimization with binary patch**

    Usually these operations correspond to low-level critical instructions. They are called frequently and are performance critical. The overhead is very important.

- - **a set of macros for hand written assembly code**

    Hand written assembly codes (.S files) also need paravirtualization because they include sensitive instructions or some code paths in them are very performance critical.

---

# ACRN Hypervisor

_Peios Kernel / Internals / Virtualisation / acrn_

> Reference for ACRN Hypervisor.

<a id="rst-acrn-hypervisor"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [ACRN Hypervisor Introduction](</kernel/internals/virt/acrn/introduction.md>)
- [I/O request handling](</kernel/internals/virt/acrn/io-request.md>)
- [ACRN CPUID bits](</kernel/internals/virt/acrn/cpuid.md>)

---

# ACRN CPUID bits

_Peios Kernel / Internals / Virtualisation / acrn_

> A guest VM running on an ACRN hypervisor can check some of its features using CPUID.

<a id="rst-acrn-cpuid-bits"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

A guest VM running on an ACRN hypervisor can check some of its features using CPUID.

ACRN cpuid functions are:

function: 0x40000000

returns:



```text
eax = 0x40000010
ebx = 0x4e524341
ecx = 0x4e524341
edx = 0x4e524341
```

Note that this value in ebx, ecx and edx corresponds to the string "ACRNACRNACRN". The value in eax corresponds to the maximum cpuid function present in this leaf, and will be updated if more functions are added in the future.

function: define ACRN_CPUID_FEATURES (0x40000001)

returns:



```text
ebx, ecx, edx
eax = an OR'ed group of (1 << flag)
```

where `flag` is defined as below:


<table>
<thead>
<tr>
<th>


flag

</th>
<th>


value

</th>
<th>


meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


ACRN_FEATURE_PRIVILEGED_VM

</td>
<td>


0

</td>
<td>


guest VM is a privileged VM

</td>
</tr>
</tbody>
</table>

function: 0x40000010

returns:



```text
ebx, ecx, edx
eax = (Virtual) TSC frequency in kHz.
```

---

# ACRN Hypervisor Introduction

_Peios Kernel / Internals / Virtualisation / acrn_

> The ACRN Hypervisor is a Type 1 hypervisor, running directly on bare-metal hardware. It has a privileged management VM, called Service VM, to manage User VMs and do I/O emulation.

<a id="rst-acrn-hypervisor-introduction"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The ACRN Hypervisor is a Type 1 hypervisor, running directly on bare-metal hardware. It has a privileged management VM, called Service VM, to manage User VMs and do I/O emulation.

ACRN userspace is an application running in the Service VM that emulates devices for a User VM based on command line configurations. ACRN Hypervisor Service Module (HSM) is a kernel module in the Service VM which provides hypervisor services to the ACRN userspace.

Below figure shows the architecture.



```text
              Service VM                    User VM
    +----------------------------+  |  +------------------+
    |        +--------------+    |  |  |                  |
    |        |ACRN userspace|    |  |  |                  |
    |        +--------------+    |  |  |                  |
    |-----------------ioctl------|  |  |                  |   ...
    |kernel space   +----------+ |  |  |                  |
    |               |   HSM    | |  |  | Drivers          |
    |               +----------+ |  |  |                  |
    +--------------------|-------+  |  +------------------+
+---------------------hypercall----------------------------------------+
|                         ACRN Hypervisor                              |
+----------------------------------------------------------------------+
|                          Hardware                                    |
+----------------------------------------------------------------------+
```

ACRN userspace allocates memory for the User VM, configures and initializes the devices used by the User VM, loads the virtual bootloader, initializes the virtual CPU state and handles I/O request accesses from the User VM. It uses ioctls to communicate with the HSM. HSM implements hypervisor services by interacting with the ACRN Hypervisor via hypercalls. HSM exports a char device interface (/dev/acrn_hsm) to userspace.

The ACRN hypervisor is open for contribution from anyone. The source repo is available at [https://github.com/projectacrn/acrn-hypervisor](<https://github.com/projectacrn/acrn-hypervisor>).

---

# I/O request handling

_Peios Kernel / Internals / Virtualisation / acrn_

> An I/O request of a User VM, which is constructed by the hypervisor, is distributed by the ACRN Hypervisor Service Module to an I/O client corresponding to the address range of the I/O request. Details of I/O request handling are described…

<a id="rst-i-o-request-handling"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

An I/O request of a User VM, which is constructed by the hypervisor, is distributed by the ACRN Hypervisor Service Module to an I/O client corresponding to the address range of the I/O request. Details of I/O request handling are described in the following sections.

<a id="rst-i-o-request"></a>

## 1. I/O request

For each User VM, there is a shared 4-KByte memory region used for I/O requests communication between the hypervisor and Service VM. An I/O request is a 256-byte structure buffer, which is 'struct acrn_io_request', that is filled by an I/O handler of the hypervisor when a trapped I/O access happens in a User VM. ACRN userspace in the Service VM first allocates a 4-KByte page and passes the GPA (Guest Physical Address) of the buffer to the hypervisor. The buffer is used as an array of 16 I/O request slots with each I/O request slot being 256 bytes. This array is indexed by vCPU ID.

<a id="rst-i-o-clients"></a>

## 2. I/O clients

An I/O client is responsible for handling User VM I/O requests whose accessed GPA falls in a certain range. Multiple I/O clients can be associated with each User VM. There is a special client associated with each User VM, called the default client, that handles all I/O requests that do not fit into the range of any other clients. The ACRN userspace acts as the default client for each User VM.

Below illustration shows the relationship between I/O requests shared buffer, I/O requests and I/O clients.



```text
+------------------------------------------------------+
|                                       Service VM     |
|+--------------------------------------------------+  |
||      +----------------------------------------+  |  |
||      | shared page            ACRN userspace  |  |  |
||      |    +-----------------+  +------------+ |  |  |
||   +----+->| acrn_io_request |<-+  default   | |  |  |
||   |  | |  +-----------------+  | I/O client | |  |  |
||   |  | |  |       ...       |  +------------+ |  |  |
||   |  | |  +-----------------+                 |  |  |
||   |  +-|--------------------------------------+  |  |
||---|----|-----------------------------------------|  |
||   |    |                             kernel      |  |
||   |    |            +----------------------+     |  |
||   |    |            | +-------------+  HSM |     |  |
||   |    +--------------+             |      |     |  |
||   |                 | | I/O clients |      |     |  |
||   |                 | |             |      |     |  |
||   |                 | +-------------+      |     |  |
||   |                 +----------------------+     |  |
|+---|----------------------------------------------+  |
+----|-------------------------------------------------+
     |
+----|-------------------------------------------------+
|  +-+-----------+                                     |
|  | I/O handler |              ACRN Hypervisor        |
|  +-------------+                                     |
+------------------------------------------------------+
```

<a id="rst-i-o-request-state-transition"></a>

## 3. I/O request state transition

The state transitions of an ACRN I/O request are as follows.



```text
FREE -> PENDING -> PROCESSING -> COMPLETE -> FREE -> ...
```

- FREE: this I/O request slot is empty

- PENDING: a valid I/O request is pending in this slot

- PROCESSING: the I/O request is being processed

- COMPLETE: the I/O request has been processed

An I/O request in COMPLETE or FREE state is owned by the hypervisor. HSM and ACRN userspace are in charge of processing the others.

<a id="rst-processing-flow-of-i-o-requests"></a>

## 4. Processing flow of I/O requests

- **a.** The I/O handler of the hypervisor will fill an I/O request with PENDING state when a trapped I/O access happens in a User VM.

- **b.** The hypervisor makes an upcall, which is a notification interrupt, to the Service VM.

- **c.** The upcall handler schedules a worker to dispatch I/O requests.

- **d.** The worker looks for the PENDING I/O requests, assigns them to different registered clients based on the address of the I/O accesses, updates their state to PROCESSING, and notifies the corresponding client to handle.

- **e.** The notified client handles the assigned I/O requests.

- **f.** The HSM updates I/O requests states to COMPLETE and notifies the hypervisor of the completion via hypercalls.

---

# The Definitive SEV Guest API Documentation

_Peios Kernel / Internals / Virtualisation / coco_

> The SEV API is a set of ioctls that are used by the guest or hypervisor to get or set a certain aspect of the SEV virtual machine. The ioctls belong to the following classes:

<a id="rst-the-definitive-sev-guest-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-general-description"></a>

## 1. General description

The SEV API is a set of ioctls that are used by the guest or hypervisor to get or set a certain aspect of the SEV virtual machine. The ioctls belong to the following classes:

> - Hypervisor ioctls: These query and set global attributes which affect the whole SEV firmware.  These ioctl are used by platform provisioning tools.
>
> - Guest ioctls: These query and set attributes of the SEV virtual machine.

<a id="rst-api-description"></a>

## 2. API description

This section describes ioctls that is used for querying the SEV guest report from the SEV firmware. For each ioctl, the following information is provided along with a description:

> - **Technology:**
>
>   which SEV technology provides this ioctl. SEV, SEV-ES, SEV-SNP or all.
>
> - **Type:**
>
>   hypervisor or guest. The ioctl can be used inside the guest or the hypervisor.
>
> - **Parameters:**
>
>   what parameters are accepted by the ioctl.
>
> - **Returns:**
>
>   the return value.  General error numbers (-ENOMEM, -EINVAL) are not detailed, but errors with specific meanings are.

The guest ioctl should be issued on a file descriptor of the /dev/sev-guest device.  The ioctl accepts struct snp_user_guest_request. The input and output structure is specified through the req_data and resp_data field respectively. If the ioctl fails to execute due to a firmware error, then the fw_error code will be set, otherwise fw_error will be set to -1.

The firmware checks that the message sequence counter is one greater than the guests message sequence counter. If guest driver fails to increment message counter (e.g. counter overflow), then -EIO will be returned.



```text
struct snp_guest_request_ioctl {
        /* Message version number */
        __u32 msg_version;

        /* Request and response structure address */
        __u64 req_data;
        __u64 resp_data;

        /* bits[63:32]: VMM error code, bits[31:0] firmware error code (see psp-sev.h) */
        union {
                __u64 exitinfo2;
                struct {
                        __u32 fw_error;
                        __u32 vmm_error;
                };
        };
};
```

The host ioctls are issued to a file descriptor of the /dev/sev device. The ioctl accepts the command ID/input structure documented below.



```text
struct sev_issue_cmd {
        /* Command ID */
        __u32 cmd;

        /* Command request structure */
        __u64 data;

        /* Firmware error code on failure (see psp-sev.h) */
        __u32 error;
};
```

<a id="rst-snp-get-report"></a>

### 2.1 SNP_GET_REPORT

**Technology:** sev-snp

**Type:** guest ioctl

**Parameters (in):** struct snp_report_req

**Returns (out):** struct snp_report_resp on success, -negative on error

The SNP_GET_REPORT ioctl can be used to query the attestation report from the SEV-SNP firmware. The ioctl uses the SNP_GUEST_REQUEST (MSG_REPORT_REQ) command provided by the SEV-SNP firmware to query the attestation report.

On success, the snp_report_resp.data will contains the report. The report contain the format described in the SEV-SNP specification. See the SEV-SNP specification for further details.

<a id="rst-snp-get-derived-key"></a>

### 2.2 SNP_GET_DERIVED_KEY

**Technology:** sev-snp

**Type:** guest ioctl

**Parameters (in):** struct snp_derived_key_req

**Returns (out):** struct snp_derived_key_resp on success, -negative on error

The SNP_GET_DERIVED_KEY ioctl can be used to get a key derive from a root key. The derived key can be used by the guest for any purpose, such as sealing keys or communicating with external entities.

The ioctl uses the SNP_GUEST_REQUEST (MSG_KEY_REQ) command provided by the SEV-SNP firmware to derive the key. See SEV-SNP specification for further details on the various fields passed in the key derivation request.

On success, the snp_derived_key_resp.data contains the derived key value. See the SEV-SNP specification for further details.

<a id="rst-snp-get-ext-report"></a>

### 2.3 SNP_GET_EXT_REPORT

**Technology:** sev-snp

**Type:** guest ioctl

**Parameters (in/out):** struct snp_ext_report_req

**Returns (out):** struct snp_report_resp on success, -negative on error

The SNP_GET_EXT_REPORT ioctl is similar to the SNP_GET_REPORT. The difference is related to the additional certificate data that is returned with the report. The certificate data returned is being provided by the hypervisor through the SNP_SET_EXT_CONFIG.

The ioctl uses the SNP_GUEST_REQUEST (MSG_REPORT_REQ) command provided by the SEV-SNP firmware to get the attestation report.

On success, the snp_ext_report_resp.data will contain the attestation report and snp_ext_report_req.certs_address will contain the certificate blob. If the length of the blob is smaller than expected then snp_ext_report_req.certs_len will be updated with the expected value.

See GHCB specification for further detail on how to parse the certificate blob.

<a id="rst-snp-platform-status"></a>

### 2.4 SNP_PLATFORM_STATUS

**Technology:** sev-snp

**Type:** hypervisor ioctl cmd

**Parameters (out):** struct sev_user_data_snp_status

**Returns (out):** 0 on success, -negative on error

The SNP_PLATFORM_STATUS command is used to query the SNP platform status. The status includes API major, minor version and more. See the SEV-SNP specification for further details.

<a id="rst-snp-commit"></a>

### 2.5 SNP_COMMIT

**Technology:** sev-snp

**Type:** hypervisor ioctl cmd

**Returns (out):** 0 on success, -negative on error

SNP_COMMIT is used to commit the currently installed firmware using the SEV-SNP firmware SNP_COMMIT command. This prevents roll-back to a previously committed firmware version. This will also update the reported TCB to match that of the currently installed firmware.

<a id="rst-snp-set-config"></a>

### 2.6 SNP_SET_CONFIG

**Technology:** sev-snp

**Type:** hypervisor ioctl cmd

**Parameters (in):** struct sev_user_data_snp_config

**Returns (out):** 0 on success, -negative on error

SNP_SET_CONFIG is used to set the system-wide configuration such as reported TCB version in the attestation report. The command is similar to SNP_CONFIG command defined in the SEV-SNP spec. The current values of the firmware parameters affected by this command can be queried via SNP_PLATFORM_STATUS.

<a id="rst-snp-vlek-load"></a>

### 2.7 SNP_VLEK_LOAD

**Technology:** sev-snp

**Type:** hypervisor ioctl cmd

**Parameters (in):** struct sev_user_data_snp_vlek_load

**Returns (out):** 0 on success, -negative on error

When requesting an attestation report a guest is able to specify whether it wants SNP firmware to sign the report using either a Versioned Chip Endorsement Key (VCEK), which is derived from chip-unique secrets, or a Versioned Loaded Endorsement Key (VLEK) which is obtained from an AMD Key Derivation Service (KDS) and derived from seeds allocated to enrolled cloud service providers.

In the case of VLEK keys, the SNP_VLEK_LOAD SNP command is used to load them into the system after obtaining them from the KDS, and corresponds closely to the SNP_VLEK_LOAD firmware command specified in the SEV-SNP spec.

<a id="rst-sev-snp-cpuid-enforcement"></a>

## 3. SEV-SNP CPUID Enforcement

SEV-SNP guests can access a special page that contains a table of CPUID values that have been validated by the PSP as part of the SNP_LAUNCH_UPDATE firmware command. It provides the following assurances regarding the validity of CPUID values:

> - Its address is obtained via bootloader/firmware (via CC blob), and those binaries will be measured as part of the SEV-SNP attestation report.
>
> - Its initial state will be encrypted/pvalidated, so attempts to modify it during run-time will result in garbage being written, or \#VC exceptions being generated due to changes in validation state if the hypervisor tries to swap the backing page.
>
> - Attempts to bypass PSP checks by the hypervisor by using a normal page, or a non-CPUID encrypted page will change the measurement provided by the SEV-SNP attestation report.
>
> - The CPUID page contents are *not* measured, but attempts to modify the expected contents of a CPUID page as part of guest initialization will be gated by the PSP CPUID enforcement policy checks performed on the page during SNP_LAUNCH_UPDATE, and noticeable later if the guest owner implements their own checks of the CPUID values.

It is important to note that this last assurance is only useful if the kernel has taken care to make use of the SEV-SNP CPUID throughout all stages of boot. Otherwise, guest owner attestation provides no assurance that the kernel wasn't fed incorrect values at some point during boot.

<a id="rst-sev-guest-driver-communication-key"></a>

## 4. SEV Guest Driver Communication Key

Communication between an SEV guest and the SEV firmware in the AMD Secure Processor (ASP, aka PSP) is protected by a VM Platform Communication Key (VMPCK). By default, the sev-guest driver uses the VMPCK associated with the VM Privilege Level (VMPL) at which the guest is running. Should this key be wiped by the sev-guest driver (see the driver for reasons why a VMPCK can be wiped), a different key can be used by reloading the sev-guest driver and specifying the desired key using the vmpck_id module parameter.

<a id="rst-reference"></a>

### Reference

SEV-SNP and GHCB specification: developer.amd.com/sev

The driver is based on SEV-SNP firmware spec 0.9 and GHCB spec version 2.0.

---

# TDX Guest API Documentation

_Peios Kernel / Internals / Virtualisation / coco_

> The TDX guest driver exposes IOCTL interfaces via the /dev/tdx-guest misc device to allow userspace to get certain TDX guest-specific details.

<a id="rst-tdx-guest-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-general-description"></a>

## 1. General description

The TDX guest driver exposes IOCTL interfaces via the /dev/tdx-guest misc device to allow userspace to get certain TDX guest-specific details.

<a id="rst-api-description"></a>

## 2. API description

In this section, for each supported IOCTL, the following information is provided along with a generic description.

**Input parameters:** Parameters passed to the IOCTL and related details.

**Output:** Details about output data and return value (with details about the non common error values).

<a id="rst-tdx-cmd-get-report0"></a>

### 2.1 TDX_CMD_GET_REPORT0

**Input parameters:** struct tdx_report_req

**Output:** Upon successful execution, TDREPORT data is copied to tdx_report_req.tdreport and return 0. Return -EINVAL for invalid operands, -EIO on TDCALL failure or standard error number on other common failures.

The TDX_CMD_GET_REPORT0 IOCTL can be used by the attestation software to get the TDREPORT0 (a.k.a. TDREPORT subtype 0) from the TDX module using TDCALL\[TDG.MR.REPORT\].

A subtype index is added at the end of this IOCTL CMD to uniquely identify the subtype-specific TDREPORT request. Although the subtype option is mentioned in the TDX Module v1.0 specification, section titled "TDG.MR.REPORT", it is not currently used, and it expects this value to be 0. So to keep the IOCTL implementation simple, the subtype option was not included as part of the input ABI. However, in the future, if the TDX Module supports more than one subtype, a new IOCTL CMD will be created to handle it. To keep the IOCTL naming consistent, a subtype index is added as part of the IOCTL CMD.

<a id="rst-reference"></a>

### Reference

TDX reference material is collected here:

[https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html](<https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html>)

The driver is based on TDX module specification v1.0 and TDX GHCI specification v1.0.

---

# Hyper-V Enlightenments

_Peios Kernel / Internals / Virtualisation / hyperv_

> Reference for Hyper-V Enlightenments.

<a id="rst-hyper-v-enlightenments"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Overview](</kernel/internals/virt/hyperv/overview.md>)
- [VMBus](</kernel/internals/virt/hyperv/vmbus.md>)
- [Clocks and Timers](</kernel/internals/virt/hyperv/clocks.md>)
- [PCI pass-thru devices](</kernel/internals/virt/hyperv/vpci.md>)
- [Hibernating Guest VMs](</kernel/internals/virt/hyperv/hibernation.md>)
- [Confidential Computing VMs](</kernel/internals/virt/hyperv/coco.md>)

---

# Clocks and Timers

_Peios Kernel / Internals / Virtualisation / hyperv_

> On arm64, Hyper-V virtualizes the ARMv8 architectural system counter and timer. Guest VMs use this virtualized hardware as the Linux clocksource and clockevents via the standard arm_arch_timer.c driver, just as they would on bare metal.…

<a id="rst-clocks-and-timers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-arm64"></a>

## arm64

On arm64, Hyper-V virtualizes the ARMv8 architectural system counter and timer. Guest VMs use this virtualized hardware as the Linux clocksource and clockevents via the standard arm_arch_timer.c driver, just as they would on bare metal. Linux vDSO support for the architectural system counter is functional in guest VMs on Hyper-V. While Hyper-V also provides a synthetic system clock and four synthetic per-CPU timers as described in the TLFS, they are not used by the Linux kernel in a Hyper-V guest on arm64.  However, older versions of Hyper-V for arm64 only partially virtualize the ARMv8 architectural timer, such that the timer does not generate interrupts in the VM. Because of this limitation, running current Linux kernel versions on these older Hyper-V versions requires an out-of-tree patch to use the Hyper-V synthetic clocks/timers instead.

<a id="rst-x86-x64"></a>

## x86/x64

On x86/x64, Hyper-V provides guest VMs with a synthetic system clock and four synthetic per-CPU timers as described in the TLFS. Hyper-V also provides access to the virtualized TSC via the RDTSC and related instructions. These TSC instructions do not trap to the hypervisor and so provide excellent performance in a VM. Hyper-V performs TSC calibration, and provides the TSC frequency to the guest VM via a synthetic MSR.  Hyper-V initialization code in Linux reads this MSR to get the frequency, so it skips TSC calibration and sets tsc_reliable. Hyper-V provides virtualized versions of the PIT (in Hyper-V  Generation 1 VMs only), local APIC timer, and RTC. Hyper-V does not provide a virtualized HPET in guest VMs.

The Hyper-V synthetic system clock can be read via a synthetic MSR, but this access traps to the hypervisor. As a faster alternative, the guest can configure a memory page to be shared between the guest and the hypervisor.  Hyper-V populates this memory page with a 64-bit scale value and offset value. To read the synthetic clock value, the guest reads the TSC and then applies the scale and offset as described in the Hyper-V TLFS. The resulting value advances at a constant 10 MHz frequency. In the case of a live migration to a host with a different TSC frequency, Hyper-V adjusts the scale and offset values in the shared page so that the 10 MHz frequency is maintained.

Starting with Windows Server 2022 Hyper-V, Hyper-V uses hardware support for TSC frequency scaling to enable live migration of VMs across Hyper-V hosts where the TSC frequency may be different. When a Linux guest detects that this Hyper-V functionality is available, it prefers to use Linux's standard TSC-based clocksource. Otherwise, it uses the clocksource for the Hyper-V synthetic system clock implemented via the shared page (identified as "hyperv_clocksource_tsc_page").

The Hyper-V synthetic system clock is available to user space via vDSO, and gettimeofday() and related system calls can execute entirely in user space.  The vDSO is implemented by mapping the shared page with scale and offset values into user space.  User space code performs the same algorithm of reading the TSC and applying the scale and offset to get the constant 10 MHz clock.

Linux clockevents are based on Hyper-V synthetic timer 0 (stimer0). While Hyper-V offers 4 synthetic timers for each CPU, Linux only uses timer 0. In older versions of Hyper-V, an interrupt from stimer0 results in a VMBus control message that is demultiplexed by vmbus_isr() as described in the [Documentation/virt/hyperv/vmbus.rst](/kernel/internals/virt/hyperv/vmbus.md) documentation. In newer versions of Hyper-V, stimer0 interrupts can be mapped to an architectural interrupt, which is referred to as "Direct Mode". Linux prefers to use Direct Mode when available. Since x86/x64 doesn't support per-CPU interrupts, Direct Mode statically allocates an x86 interrupt vector (HYPERV_STIMER0_VECTOR) across all CPUs and explicitly codes it to call the stimer0 interrupt handler. Hence interrupts from stimer0 are recorded on the "HVS" line in /proc/interrupts rather than being associated with a Linux IRQ. Clockevents based on the virtualized PIT and local APIC timer also work, but Hyper-V stimer0 is preferred.

The driver for the Hyper-V synthetic system clock and timers is drivers/clocksource/hyperv_timer.c.

---

# Confidential Computing VMs

_Peios Kernel / Internals / Virtualisation / hyperv_

> Hyper-V can create and run Linux guests that are Confidential Computing (CoCo) VMs. Such VMs cooperate with the physical processor to better protect the confidentiality and integrity of data in the VM's memory, even in the face of a…

<a id="rst-confidential-computing-vms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Hyper-V can create and run Linux guests that are Confidential Computing (CoCo) VMs. Such VMs cooperate with the physical processor to better protect the confidentiality and integrity of data in the VM's memory, even in the face of a hypervisor/VMM that has been compromised and may behave maliciously. CoCo VMs on Hyper-V share the generic CoCo VM threat model and security objectives described in [Documentation/security/snp-tdx-threat-model.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/security/snp-tdx-threat-model.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92). Note that Hyper-V specific code in Linux refers to CoCo VMs as "isolated VMs" or "isolation VMs".

A Linux CoCo VM on Hyper-V requires the cooperation and interaction of the following:

- Physical hardware with a processor that supports CoCo VMs

- The hardware runs a version of Windows/Hyper-V with support for CoCo VMs

- The VM runs a version of Linux that supports being a CoCo VM

The physical hardware requirements are as follows:

- AMD processor with SEV-SNP. Hyper-V does not run guest VMs with AMD SME, SEV, or SEV-ES encryption, and such encryption is not sufficient for a CoCo VM on Hyper-V.

- Intel processor with TDX

To create a CoCo VM, the "Isolated VM" attribute must be specified to Hyper-V when the VM is created. A VM cannot be changed from a CoCo VM to a normal VM, or vice versa, after it is created.

<a id="rst-operational-modes"></a>

## Operational Modes

Hyper-V CoCo VMs can run in two modes. The mode is selected when the VM is created and cannot be changed during the life of the VM.

- Fully-enlightened mode. In this mode, the guest operating system is enlightened to understand and manage all aspects of running as a CoCo VM.

- Paravisor mode. In this mode, a paravisor layer between the guest and the host provides some operations needed to run as a CoCo VM. The guest operating system can have fewer CoCo enlightenments than is required in the fully-enlightened case.

Conceptually, fully-enlightened mode and paravisor mode may be treated as points on a spectrum spanning the degree of guest enlightenment needed to run as a CoCo VM. Fully-enlightened mode is one end of the spectrum. A full implementation of paravisor mode is the other end of the spectrum, where all aspects of running as a CoCo VM are handled by the paravisor, and a normal guest OS with no knowledge of memory encryption or other aspects of CoCo VMs can run successfully. However, the Hyper-V implementation of paravisor mode does not go this far, and is somewhere in the middle of the spectrum. Some aspects of CoCo VMs are handled by the Hyper-V paravisor while the guest OS must be enlightened for other aspects. Unfortunately, there is no standardized enumeration of feature/functions that might be provided in the paravisor, and there is no standardized mechanism for a guest OS to query the paravisor for the feature/functions it provides. The understanding of what the paravisor provides is hard-coded in the guest OS.

Paravisor mode has similarities to the [Coconut project](<https://github.com/coconut-svsm/svsm>), which aims to provide a limited paravisor to provide services to the guest such as a virtual TPM. However, the Hyper-V paravisor generally handles more aspects of CoCo VMs than is currently envisioned for Coconut, and so is further toward the "no guest enlightenments required" end of the spectrum.

<a id="rst-coconut-project"></a>



In the CoCo VM threat model, the paravisor is in the guest security domain and must be trusted by the guest OS. By implication, the hypervisor/VMM must protect itself against a potentially malicious paravisor just like it protects against a potentially malicious guest.

The hardware architectural approach to fully-enlightened vs. paravisor mode varies depending on the underlying processor.

- With AMD SEV-SNP processors, in fully-enlightened mode the guest OS runs in VMPL 0 and has full control of the guest context. In paravisor mode, the guest OS runs in VMPL 2 and the paravisor runs in VMPL 0. The paravisor running in VMPL 0 has privileges that the guest OS in VMPL 2 does not have. Certain operations require the guest to invoke the paravisor. Furthermore, in paravisor mode the guest OS operates in "virtual Top Of Memory" (vTOM) mode as defined by the SEV-SNP architecture. This mode simplifies guest management of memory encryption when a paravisor is used.

- With Intel TDX processor, in fully-enlightened mode the guest OS runs in an L1 VM. In paravisor mode, TD partitioning is used. The paravisor runs in the L1 VM, and the guest OS runs in a nested L2 VM.

Hyper-V exposes a synthetic MSR to guests that describes the CoCo mode. This MSR indicates if the underlying processor uses AMD SEV-SNP or Intel TDX, and whether a paravisor is being used. It is straightforward to build a single kernel image that can boot and run properly on either architecture, and in either mode.

<a id="rst-paravisor-effects"></a>

## Paravisor Effects

Running in paravisor mode affects the following areas of generic Linux kernel CoCo VM functionality:

- Initial guest memory setup. When a new VM is created in paravisor mode, the paravisor runs first and sets up the guest physical memory as encrypted. The guest Linux does normal memory initialization, except for explicitly marking appropriate ranges as decrypted (shared). In paravisor mode, Linux does not perform the early boot memory setup steps that are particularly tricky with AMD SEV-SNP in fully-enlightened mode.

- \#VC/\#VE exception handling. In paravisor mode, Hyper-V configures the guest CoCo VM to route \#VC and \#VE exceptions to VMPL 0 and the L1 VM, respectively, and not the guest Linux. Consequently, these exception handlers do not run in the guest Linux and are not a required enlightenment for a Linux guest in paravisor mode.

- CPUID flags. Both AMD SEV-SNP and Intel TDX provide a CPUID flag in the guest indicating that the VM is operating with the respective hardware support. While these CPUID flags are visible in fully-enlightened CoCo VMs, the paravisor filters out these flags and the guest Linux does not see them. Throughout the Linux kernel, explicitly testing these flags has mostly been eliminated in favor of the cc_platform_has() function, with the goal of abstracting the differences between SEV-SNP and TDX. But the cc_platform_has() abstraction also allows the Hyper-V paravisor configuration to selectively enable aspects of CoCo VM functionality even when the CPUID flags are not set. The exception is early boot memory setup on SEV-SNP, which tests the CPUID SEV-SNP flag. But not having the flag in Hyper-V paravisor mode VM achieves the desired effect or not running SEV-SNP specific early boot memory setup.

- Device emulation. In paravisor mode, the Hyper-V paravisor provides emulation of devices such as the IO-APIC and TPM. Because the emulation happens in the paravisor in the guest context (instead of the hypervisor/VMM context), MMIO accesses to these devices must be encrypted references instead of the decrypted references that would be used in a fully-enlightened CoCo VM. The \__ioremap_caller() function has been enhanced to make a callback to check whether a particular address range should be treated as encrypted (private). See the "is_private_mmio" callback.

- Encrypt/decrypt memory transitions. In a CoCo VM, transitioning guest memory between encrypted and decrypted requires coordinating with the hypervisor/VMM. This is done via callbacks invoked from \__set_memory_enc_pgtable(). In fully-enlightened mode, the normal SEV-SNP and TDX implementations of these callbacks are used. In paravisor mode, a Hyper-V specific set of callbacks is used. These callbacks invoke the paravisor so that the paravisor can coordinate the transitions and inform the hypervisor as necessary. See hv_vtom_init() where these callback are set up.

- Interrupt injection. In fully enlightened mode, a malicious hypervisor could inject interrupts into the guest OS at times that violate x86/x64 architectural rules. For full protection, the guest OS should include enlightenments that use the interrupt injection management features provided by CoCo-capable processors. In paravisor mode, the paravisor mediates interrupt injection into the guest OS, and ensures that the guest OS only sees interrupts that are "legal". The paravisor uses the interrupt injection management features provided by the CoCo-capable physical processor, thereby masking these complexities from the guest OS.

<a id="rst-hyper-v-hypercalls"></a>

## Hyper-V Hypercalls

When in fully-enlightened mode, hypercalls made by the Linux guest are routed directly to the hypervisor, just as in a non-CoCo VM. But in paravisor mode, normal hypercalls trap to the paravisor first, which may in turn invoke the hypervisor. But the paravisor is idiosyncratic in this regard, and a few hypercalls made by the Linux guest must always be routed directly to the hypervisor. These hypercall sites test for a paravisor being present, and use a special invocation sequence. See hv_post_message(), for example.

<a id="rst-guest-communication-with-hyper-v"></a>

## Guest communication with Hyper-V

Separate from the generic Linux kernel handling of memory encryption in Linux CoCo VMs, Hyper-V has VMBus and VMBus devices that communicate using memory shared between the Linux guest and the host. This shared memory must be marked decrypted to enable communication. Furthermore, since the threat model includes a compromised and potentially malicious host, the guest must guard against leaking any unintended data to the host through this shared memory.

These Hyper-V and VMBus memory pages are marked as decrypted:

- VMBus monitor pages

- Synthetic interrupt controller (SynIC) related pages (unless supplied by the paravisor)

- Per-cpu hypercall input and output pages (unless running with a paravisor)

- VMBus ring buffers. The direct mapping is marked decrypted in \__vmbus_establish_gpadl(). The secondary mapping created in hv_ringbuffer_init() must also include the "decrypted" attribute.

When the guest writes data to memory that is shared with the host, it must ensure that only the intended data is written. Padding or unused fields must be initialized to zeros before copying into the shared memory so that random kernel data is not inadvertently given to the host.

Similarly, when the guest reads memory that is shared with the host, it must validate the data before acting on it so that a malicious host cannot induce the guest to expose unintended data. Doing such validation can be tricky because the host can modify the shared memory areas even while or after validation is performed. For messages passed from the host to the guest in a VMBus ring buffer, the length of the message is validated, and the message is copied into a temporary (encrypted) buffer for further validation and processing. The copying adds a small amount of overhead, but is the only way to protect against a malicious host. See hv_pkt_iter_first().

Many drivers for VMBus devices have been "hardened" by adding code to fully validate messages received over VMBus, instead of assuming that Hyper-V is acting cooperatively. Such drivers are marked as "allowed_in_isolated" in the vmbus_devs\[\] table. Other drivers for VMBus devices that are not needed in a CoCo VM have not been hardened, and they are not allowed to load in a CoCo VM. See vmbus_is_valid_offer() where such devices are excluded.

Two VMBus devices depend on the Hyper-V host to do DMA data transfers: storvsc for disk I/O and netvsc for network I/O. storvsc uses the normal Linux kernel DMA APIs, and so bounce buffering through decrypted swiotlb memory is done implicitly. netvsc has two modes for data transfers. The first mode goes through send and receive buffer space that is explicitly allocated by the netvsc driver, and is used for most smaller packets. These send and receive buffers are marked decrypted by \__vmbus_establish_gpadl(). Because the netvsc driver explicitly copies packets to/from these buffers, the equivalent of bounce buffering between encrypted and decrypted memory is already part of the data path. The second mode uses the normal Linux kernel DMA APIs, and is bounce buffered through swiotlb memory implicitly like in storvsc.

Finally, the VMBus virtual PCI driver needs special handling in a CoCo VM. Linux PCI device drivers access PCI config space using standard APIs provided by the Linux PCI subsystem. On Hyper-V, these functions directly access MMIO space, and the access traps to Hyper-V for emulation. But in CoCo VMs, memory encryption prevents Hyper-V from reading the guest instruction stream to emulate the access. So in a CoCo VM, these functions must make a hypercall with arguments explicitly describing the access. See \_hv_pcifront_read_config() and \_hv_pcifront_write_config() and the "use_calls" flag indicating to use hypercalls.

<a id="rst-confidential-vmbus"></a>

## Confidential VMBus

The confidential VMBus enables the confidential guest not to interact with the untrusted host partition and the untrusted hypervisor. Instead, the guest relies on the trusted paravisor to communicate with the devices processing sensitive data. The hardware (SNP or TDX) encrypts the guest memory and the register state while measuring the paravisor image using the platform security processor to ensure trusted and confidential computing.

Confidential VMBus provides a secure communication channel between the guest and the paravisor, ensuring that sensitive data is protected from hypervisor- level access through memory encryption and register state isolation.

Confidential VMBus is an extension of Confidential Computing (CoCo) VMs (a.k.a. "Isolated" VMs in Hyper-V terminology). Without Confidential VMBus, guest VMBus device drivers (the "VSC"s in VMBus terminology) communicate with VMBus servers (the VSPs) running on the Hyper-V host. The communication must be through memory that has been decrypted so the host can access it. With Confidential VMBus, one or more of the VSPs reside in the trusted paravisor layer in the guest VM. Since the paravisor layer also operates in encrypted memory, the memory used for communication with such VSPs does not need to be decrypted and thereby exposed to the Hyper-V host. The paravisor is responsible for communicating securely with the Hyper-V host as necessary.

The data is transferred directly between the VM and a vPCI device (a.k.a. a PCI pass-thru device, see [PCI pass-thru devices](</kernel/internals/virt/hyperv/vpci.md>)) that is directly assigned to VTL2 and that supports encrypted memory. In such a case, neither the host partition nor the hypervisor has any access to the data. The guest needs to establish a VMBus connection only with the paravisor for the channels that process sensitive data, and the paravisor abstracts the details of communicating with the specific devices away providing the guest with the well-established VSP (Virtual Service Provider) interface that has had support in the Hyper-V drivers for a decade.

In the case the device does not support encrypted memory, the paravisor provides bounce-buffering, and although the data is not encrypted, the backing pages aren't mapped into the host partition through SLAT. While not impossible, it becomes much more difficult for the host partition to exfiltrate the data than it would be with a conventional VMBus connection where the host partition has direct access to the memory used for communication.

Here is the data flow for a conventional VMBus connection (`C` stands for the client or VSC, `S` for the server or VSP, the `DEVICE` is a physical one, might be with multiple virtual functions):



```text
+---- GUEST ----+       +----- DEVICE ----+        +----- HOST -----+
|               |       |                 |        |                |
|               |       |                 |        |                |
|               |       |                 ==========                |
|               |       |                 |        |                |
|               |       |                 |        |                |
|               |       |                 |        |                |
+----- C -------+       +-----------------+        +------- S ------+
       ||                                                   ||
       ||                                                   ||
+------||------------------ VMBus --------------------------||------+
|                     Interrupts, MMIO                              |
+-------------------------------------------------------------------+
```

and the Confidential VMBus connection:



```text
+---- GUEST --------------- VTL0 ------+               +-- DEVICE --+
|                                      |               |            |
| +- PARAVISOR --------- VTL2 -----+   |               |            |
| |     +-- VMBus Relay ------+    ====+================            |
| |     |   Interrupts, MMIO  |    |   |               |            |
| |     +-------- S ----------+    |   |               +------------+
| |               ||               |   |
| +---------+     ||               |   |
| |  Linux  |     ||    OpenHCL    |   |
| |  kernel |     ||               |   |
| +---- C --+-----||---------------+   |
|       ||        ||                   |
+-------++------- C -------------------+               +------------+
        ||                                             |    HOST    |
        ||                                             +---- S -----+
+-------||----------------- VMBus ---------------------------||-----+
|                     Interrupts, MMIO                              |
+-------------------------------------------------------------------+
```

An implementation of the VMBus relay that offers the Confidential VMBus channels is available in the OpenVMM project as a part of the OpenHCL paravisor. Please refer to

> - [https://openvmm.dev/](<https://openvmm.dev/>), and
>
> - [https://github.com/microsoft/openvmm](<https://github.com/microsoft/openvmm>)

for more information about the OpenHCL paravisor.

A guest that is running with a paravisor must determine at runtime if Confidential VMBus is supported by the current paravisor. The x86_64-specific approach relies on the CPUID Virtualization Stack leaf; the ARM64 implementation is expected to support the Confidential VMBus unconditionally when running ARM CCA guests.

Confidential VMBus is a characteristic of the VMBus connection as a whole, and of each VMBus channel that is created. When a Confidential VMBus connection is established, the paravisor provides the guest the message-passing path that is used for VMBus device creation and deletion, and it provides a per-CPU synthetic interrupt controller (SynIC) just like the SynIC that is offered by the Hyper-V host. Each VMBus device that is offered to the guest indicates the degree to which it participates in Confidential VMBus. The offer indicates if the device uses encrypted ring buffers, and if the device uses encrypted memory for DMA that is done outside the ring buffer. These settings may be different for different devices using the same Confidential VMBus connection.

Although these settings are separate, in practice it'll always be encrypted ring buffer only, or both encrypted ring buffer and external data. If a channel is offered by the paravisor with confidential VMBus, the ring buffer can always be encrypted since it's strictly for communication between the VTL2 paravisor and the VTL0 guest. However, other memory regions are often used for e.g. DMA, so they need to be accessible by the underlying hardware, and must be unencrypted (unless the device supports encrypted memory). Currently, there are not any VSPs in OpenHCL that support encrypted external memory, but future versions are expected to enable this capability.

Because some devices on a Confidential VMBus may require decrypted ring buffers and DMA transfers, the guest must interact with two SynICs -- the one provided by the paravisor and the one provided by the Hyper-V host when Confidential VMBus is not offered. Interrupts are always signaled by the paravisor SynIC, but the guest must check for messages and for channel interrupts on both SynICs.

In the case of a confidential VMBus, regular SynIC access by the guest is intercepted by the paravisor (this includes various MSRs such as the SIMP and SIEFP, as well as hypercalls like HvPostMessage and HvSignalEvent). If the guest actually wants to communicate with the hypervisor, it has to use special mechanisms (GHCB page on SNP, or tdcall on TDX). Messages can be of either kind: with confidential VMBus, messages use the paravisor SynIC, and if the guest chose to communicate directly to the hypervisor, they use the hypervisor SynIC. For interrupt signaling, some channels may be running on the host (non-confidential, using the VMBus relay) and use the hypervisor SynIC, and some on the paravisor and use its SynIC. The RelIDs are coordinated by the OpenHCL VMBus server and are guaranteed to be unique regardless of whether the channel originated on the host or the paravisor.

<a id="rst-load-unaligned-zeropad"></a>

## load_unaligned_zeropad()

When transitioning memory between encrypted and decrypted, the caller of set_memory_encrypted() or set_memory_decrypted() is responsible for ensuring the memory isn't in use and isn't referenced while the transition is in progress. The transition has multiple steps, and includes interaction with the Hyper-V host. The memory is in an inconsistent state until all steps are complete. A reference while the state is inconsistent could result in an exception that can't be cleanly fixed up.

However, the kernel load_unaligned_zeropad() mechanism may make stray references that can't be prevented by the caller of set_memory_encrypted() or set_memory_decrypted(), so there's specific code in the \#VC or \#VE exception handler to fixup this case. But a CoCo VM running on Hyper-V may be configured to run with a paravisor, with the \#VC or \#VE exception routed to the paravisor. There's no architectural way to forward the exceptions back to the guest kernel, and in such a case, the load_unaligned_zeropad() fixup code in the \#VC/\#VE handlers doesn't run.

To avoid this problem, the Hyper-V specific functions for notifying the hypervisor of the transition mark pages as "not present" while a transition is in progress. If load_unaligned_zeropad() causes a stray reference, a normal page fault is generated instead of \#VC or \#VE, and the page-fault- based handlers for load_unaligned_zeropad() fixup the reference. When the encrypted/decrypted transition is complete, the pages are marked as "present" again. See hv_vtom_clear_present() and hv_vtom_set_host_visibility().

---

# Hibernating Guest VMs

_Peios Kernel / Internals / Virtualisation / hyperv_

> Linux supports the ability to hibernate itself in order to save power. Hibernation is sometimes called suspend-to-disk, as it writes a memory image to disk and puts the hardware into the lowest possible power state. Upon resume from…

> **Peios:** The Peios profile forces integrity lockdown. Hibernation is unavailable under that policy, and kernel replacement must satisfy the kexec signature/lockdown path. The optional upstream mechanisms and test recipes below do not override those checks. Native privilege checks also apply. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-hibernating-guest-vms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-background"></a>

## Background

Linux supports the ability to hibernate itself in order to save power. Hibernation is sometimes called suspend-to-disk, as it writes a memory image to disk and puts the hardware into the lowest possible power state. Upon resume from hibernation, the hardware is restarted and the memory image is restored from disk so that it can resume execution where it left off. See the "Hibernation" section of [Documentation/admin-guide/pm/sleep-states.rst](/kernel/administration/admin-guide/pm/sleep-states.md).

Hibernation is usually done on devices with a single user, such as a personal laptop. For example, the laptop goes into hibernation when the cover is closed, and resumes when the cover is opened again. Hibernation and resume happen on the same hardware, and Linux kernel code orchestrating the hibernation steps assumes that the hardware configuration is not changed while in the hibernated state.

Hibernation can be initiated within Linux by writing "disk" to /sys/power/state or by invoking the reboot system call with the appropriate arguments. This functionality may be wrapped by user space commands such "systemctl hibernate" that are run directly from a command line or in response to events such as the laptop lid closing.

<a id="rst-considerations-for-guest-vm-hibernation"></a>

## Considerations for Guest VM Hibernation

Linux guests on Hyper-V can also be hibernated, in which case the hardware is the virtual hardware provided by Hyper-V to the guest VM. Only the targeted guest VM is hibernated, while other guest VMs and the underlying Hyper-V host continue to run normally. While the underlying Windows Hyper-V and physical hardware on which it is running might also be hibernated using hibernation functionality in the Windows host, host hibernation and its impact on guest VMs is not in scope for this documentation.

Resuming a hibernated guest VM can be more challenging than with physical hardware because VMs make it very easy to change the hardware configuration between the hibernation and resume. Even when the resume is done on the same VM that hibernated, the memory size might be changed, or virtual NICs or SCSI controllers might be added or removed. Virtual PCI devices assigned to the VM might be added or removed. Most such changes cause the resume steps to fail, though adding a new virtual NIC, SCSI controller, or vPCI device should work.

Additional complexity can ensue because the disks of the hibernated VM can be moved to another newly created VM that otherwise has the same virtual hardware configuration. While it is desirable for resume from hibernation to succeed after such a move, there are challenges. See details on this scenario and its limitations in the "Resuming on a Different VM" section below.

Hyper-V also provides ways to move a VM from one Hyper-V host to another. Hyper-V tries to ensure processor model and Hyper-V version compatibility using VM Configuration Versions, and prevents moves to a host that isn't compatible. Linux adapts to host and processor differences by detecting them at boot time, but such detection is not done when resuming execution in the hibernation image. If a VM is hibernated on one host, then resumed on a host with a different processor model or Hyper-V version, settings recorded in the hibernation image may not match the new host. Because Linux does not detect such mismatches when resuming the hibernation image, undefined behavior and failures could result.

<a id="rst-enabling-guest-vm-hibernation"></a>

## Enabling Guest VM Hibernation

Hibernation of a Hyper-V guest VM is disabled by default because hibernation is incompatible with memory hot-add, as provided by the Hyper-V balloon driver. If hot-add is used and the VM hibernates, it hibernates with more memory than it started with. But when the VM resumes from hibernation, Hyper-V gives the VM only the originally assigned memory, and the memory size mismatch causes resume to fail.

To enable a Hyper-V VM for hibernation, the Hyper-V administrator must enable the ACPI virtual S4 sleep state in the ACPI configuration that Hyper-V provides to the guest VM. Such enablement is accomplished by modifying a WMI property of the VM, the steps for which are outside the scope of this documentation but are available on the web. Enablement is treated as the indicator that the administrator prioritizes Linux hibernation in the VM over hot-add, so the Hyper-V balloon driver in Linux disables hot-add. Enablement is indicated if the contents of /sys/power/disk contains "platform" as an option. The enablement is also visible in /sys/bus/vmbus/hibernation. See function hv_is_hibernation_supported().

Linux supports ACPI sleep states on x86, but not on arm64. So Linux guest VM hibernation is not available on Hyper-V for arm64.

<a id="rst-initiating-guest-vm-hibernation"></a>

## Initiating Guest VM Hibernation

Guest VMs can self-initiate hibernation using the standard Linux methods of writing "disk" to /sys/power/state or the reboot system call. As an additional layer, Linux guests on Hyper-V support the "Shutdown" integration service, via which a Hyper-V administrator can tell a Linux VM to hibernate using a command outside the VM. The command generates a request to the Hyper-V shutdown driver in Linux, which sends the uevent "EVENT=hibernate". See kernel functions shutdown_onchannelcallback() and send_hibernate_uevent(). A udev rule must be provided in the VM that handles this event and initiates hibernation.

<a id="rst-handling-vmbus-devices-during-hibernation-resume"></a>

## Handling VMBus Devices During Hibernation &amp; Resume

The VMBus bus driver, and the individual VMBus device drivers, implement suspend and resume functions that are called as part of the Linux orchestration of hibernation and of resuming from hibernation. The overall approach is to leave in place the data structures for the primary VMBus channels and their associated Linux devices, such as SCSI controllers and others, so that they are captured in the hibernation image. This approach allows any state associated with the device to be persisted across the hibernation/resume. When the VM resumes, the devices are re-offered by Hyper-V and are connected to the data structures that already exist in the resumed hibernation image.

VMBus devices are identified by class and instance GUID. (See section "VMBus device creation/deletion" in [Documentation/virt/hyperv/vmbus.rst](/kernel/internals/virt/hyperv/vmbus.md).) Upon resume from hibernation, the resume functions expect that the devices offered by Hyper-V have the same class/instance GUIDs as the devices present at the time of hibernation. Having the same class/instance GUIDs allows the offered devices to be matched to the primary VMBus channel data structures in the memory of the now resumed hibernation image. If any devices are offered that don't match primary VMBus channel data structures that already exist, they are processed normally as newly added devices. If primary VMBus channels that exist in the resumed hibernation image are not matched with a device offered in the resumed VM, the resume sequence waits for 10 seconds, then proceeds. But the unmatched device is likely to cause errors in the resumed VM.

When resuming existing primary VMBus channels, the newly offered relids might be different because relids can change on each VM boot, even if the VM configuration hasn't changed. The VMBus bus driver resume function matches the class/instance GUIDs, and updates the relids in case they have changed.

VMBus sub-channels are not persisted in the hibernation image. Each VMBus device driver's suspend function must close any sub-channels prior to hibernation. Closing a sub-channel causes Hyper-V to send a RESCIND_CHANNELOFFER message, which Linux processes by freeing the channel data structures so that all vestiges of the sub-channel are removed. By contrast, primary channels are marked closed and their ring buffers are freed, but Hyper-V does not send a rescind message, so the channel data structure continues to exist. Upon resume, the device driver's resume function re-allocates the ring buffer and re-opens the existing channel. It then communicates with Hyper-V to re-open sub-channels from scratch.

The Linux ends of Hyper-V sockets are forced closed at the time of hibernation. The guest can't force closing the host end of the socket, but any host-side actions on the host end will produce an error.

VMBus devices use the same suspend function for the "freeze" and the "poweroff" phases, and the same resume function for the "thaw" and "restore" phases. See the "Entering Hibernation" section of [Documentation/driver-api/pm/devices.rst](/kernel/hardware/driver-api/pm/devices.md) for the sequencing of the phases.

<a id="rst-detailed-hibernation-sequence"></a>

## Detailed Hibernation Sequence

1. The Linux power management (PM) subsystem prepares for hibernation by freezing user space processes and allocating memory to hold the hibernation image.

2. As part of the "freeze" phase, Linux PM calls the "suspend" function for each VMBus device in turn. As described above, this function removes sub-channels, and leaves the primary channel in a closed state.

3. Linux PM calls the "suspend" function for the VMBus bus, which closes any Hyper-V socket channels and unloads the top-level VMBus connection with the Hyper-V host.

4. Linux PM disables non-boot CPUs, creates the hibernation image in the previously allocated memory, then re-enables non-boot CPUs. The hibernation image contains the memory data structures for the closed primary channels, but no sub-channels.

5. As part of the "thaw" phase, Linux PM calls the "resume" function for the VMBus bus, which re-establishes the top-level VMBus connection and requests that Hyper-V re-offer the VMBus devices. As offers are received for the primary channels, the relids are updated as previously described.

6. Linux PM calls the "resume" function for each VMBus device. Each device re-opens its primary channel, and communicates with Hyper-V to re-establish sub-channels if appropriate. The sub-channels are re-created as new channels since they were previously removed entirely in Step 2.

7. With VMBus devices now working again, Linux PM writes the hibernation image from memory to disk.

8. Linux PM repeats Steps 2 and 3 above as part of the "poweroff" phase. VMBus channels are closed and the top-level VMBus connection is unloaded.

9. Linux PM disables non-boot CPUs, and then enters ACPI sleep state S4. Hibernation is now complete.

<a id="rst-detailed-resume-sequence"></a>

## Detailed Resume Sequence

1. The guest VM boots into a fresh Linux OS instance. During boot, the top-level VMBus connection is established, and synthetic devices are enabled. This happens via the normal paths that don't involve hibernation.

2. Linux PM hibernation code reads swap space is to find and read the hibernation image into memory. If there is no hibernation image, then this boot becomes a normal boot.

3. If this is a resume from hibernation, the "freeze" phase is used to shutdown VMBus devices and unload the top-level VMBus connection in the running fresh OS instance, just like Steps 2 and 3 in the hibernation sequence.

4. Linux PM disables non-boot CPUs, and transfers control to the read-in hibernation image. In the now-running hibernation image, non-boot CPUs are restarted.

5. As part of the "resume" phase, Linux PM repeats Steps 5 and 6 from the hibernation sequence. The top-level VMBus connection is re-established, and offers are received and matched to primary channels in the image. Relids are updated. VMBus device resume functions re-open primary channels and re-create sub-channels.

6. Linux PM exits the hibernation resume sequence and the VM is now running normally from the hibernation image.

<a id="rst-key-value-pair-kvp-pseudo-device-anomalies"></a>

## Key-Value Pair (KVP) Pseudo-Device Anomalies

The VMBus KVP device behaves differently from other pseudo-devices offered by Hyper-V.  When the KVP primary channel is closed, Hyper-V sends a rescind message, which causes all vestiges of the device to be removed. But Hyper-V then re-offers the device, causing it to be newly re-created. The removal and re-creation occurs during the "freeze" phase of hibernation, so the hibernation image contains the re-created KVP device. Similar behavior occurs during the "freeze" phase of the resume sequence while still in the fresh OS instance. But in both cases, the top-level VMBus connection is subsequently unloaded, which causes the device to be discarded on the Hyper-V side. So no harm is done and everything still works.

<a id="rst-virtual-pci-devices"></a>

## Virtual PCI devices

Virtual PCI devices are physical PCI devices that are mapped directly into the VM's physical address space so the VM can interact directly with the hardware. vPCI devices include those accessed via what Hyper-V calls "Discrete Device Assignment" (DDA), as well as SR-IOV NIC Virtual Functions (VF) devices. See [Documentation/virt/hyperv/vpci.rst](/kernel/internals/virt/hyperv/vpci.md).

Hyper-V DDA devices are offered to guest VMs after the top-level VMBus connection is established, just like VMBus synthetic devices. They are statically assigned to the VM, and their instance GUIDs don't change unless the Hyper-V administrator makes changes to the configuration. DDA devices are represented in Linux as virtual PCI devices that have a VMBus identity as well as a PCI identity. Consequently, Linux guest hibernation first handles DDA devices as VMBus devices in order to manage the VMBus channel. But then they are also handled as PCI devices using the hibernation functions implemented by their native PCI driver.

SR-IOV NIC VFs also have a VMBus identity as well as a PCI identity, and overall are processed similarly to DDA devices. A difference is that VFs are not offered to the VM during initial boot of the VM. Instead, the VMBus synthetic NIC driver first starts operating and communicates to Hyper-V that it is prepared to accept a VF, and then the VF offer is made. However, the VMBus connection might later be unloaded and then re-established without the VM being rebooted, as happens in Steps 3 and 5 in the Detailed Hibernation Sequence above and in the Detailed Resume Sequence. In such a case, the VFs likely became part of the VM during initial boot, so when the VMBus connection is re-established, the VFs are offered on the re-established connection without intervention by the synthetic NIC driver.

<a id="rst-uio-devices"></a>

## UIO Devices

A VMBus device can be exposed to user space using the Hyper-V UIO driver (uio_hv_generic.c) so that a user space driver can control and operate the device. However, the VMBus UIO driver does not support the suspend and resume operations needed for hibernation. If a VMBus device is configured to use the UIO driver, hibernating the VM fails and Linux continues to run normally. The most common use of the Hyper-V UIO driver is for DPDK networking, but there are other uses as well.

<a id="rst-resuming-on-a-different-vm"></a>

## Resuming on a Different VM

This scenario occurs in the Azure public cloud in that a hibernated customer VM only exists as saved configuration and disks -- the VM no longer exists on any Hyper-V host. When the customer VM is resumed, a new Hyper-V VM with identical configuration is created, likely on a different Hyper-V host. That new Hyper-V VM becomes the resumed customer VM, and the steps the Linux kernel takes to resume from the hibernation image must work in that new VM.

While the disks and their contents are preserved from the original VM, the Hyper-V-provided VMBus instance GUIDs of the disk controllers and other synthetic devices would typically be different. The difference would cause the resume from hibernation to fail, so several things are done to solve this problem:

- For VMBus synthetic devices that support only a single instance, Hyper-V always assigns the same instance GUIDs. For example, the Hyper-V mouse, the shutdown pseudo-device, the time sync pseudo device, etc., always have the same instance GUID, both for local Hyper-V installs as well as in the Azure cloud.

- VMBus synthetic SCSI controllers may have multiple instances in a VM, and in the general case instance GUIDs vary from VM to VM. However, Azure VMs always have exactly two synthetic SCSI controllers, and Azure code overrides the normal Hyper-V behavior so these controllers are always assigned the same two instance GUIDs. Consequently, when a customer VM is resumed on a newly created VM, the instance GUIDs match. But this guarantee does not hold for local Hyper-V installs.

- Similarly, VMBus synthetic NICs may have multiple instances in a VM, and the instance GUIDs vary from VM to VM. Again, Azure code overrides the normal Hyper-V behavior so that the instance GUID of a synthetic NIC in a customer VM does not change, even if the customer VM is deallocated or hibernated, and then re-constituted on a newly created VM. As with SCSI controllers, this behavior does not hold for local Hyper-V installs.

- vPCI devices do not have the same instance GUIDs when resuming from hibernation on a newly created VM. Consequently, Azure does not support hibernation for VMs that have DDA devices such as NVMe controllers or GPUs. For SR-IOV NIC VFs, Azure removes the VF from the VM before it hibernates so that the hibernation image does not contain a VF device. When the VM is resumed it instantiates a new VF, rather than trying to match against a VF that is present in the hibernation image. Because Azure must remove any VFs before initiating hibernation, Azure VM hibernation must be initiated externally from the Azure Portal or Azure CLI, which in turn uses the Shutdown integration service to tell Linux to do the hibernation. If hibernation is self-initiated within the Azure VM, VFs remain in the hibernation image, and are not resumed properly.

In summary, Azure takes special actions to remove VFs and to ensure that VMBus device instance GUIDs match on a new/different VM, allowing hibernation to work for most general-purpose Azure VMs sizes. While similar special actions could be taken when resuming on a different VM on a local Hyper-V install, orchestrating such actions is not provided out-of-the-box by local Hyper-V and so requires custom scripting.

---

# Overview

_Peios Kernel / Internals / Virtualisation / hyperv_

> The Linux kernel contains a variety of code for running as a fully enlightened guest on Microsoft's Hyper-V hypervisor. Hyper-V consists primarily of a bare-metal hypervisor plus a virtual machine management service running in the parent…

<a id="rst-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The Linux kernel contains a variety of code for running as a fully enlightened guest on Microsoft's Hyper-V hypervisor.  Hyper-V consists primarily of a bare-metal hypervisor plus a virtual machine management service running in the parent partition (roughly equivalent to KVM and QEMU, for example).  Guest VMs run in child partitions.  In this documentation, references to Hyper-V usually encompass both the hypervisor and the VMM service without making a distinction about which functionality is provided by which component.

Hyper-V runs on x86/x64 and arm64 architectures, and Linux guests are supported on both.  The functionality and behavior of Hyper-V is generally the same on both architectures unless noted otherwise.

<a id="rst-linux-guest-communication-with-hyper-v"></a>

## Linux Guest Communication with Hyper-V

Linux guests communicate with Hyper-V in four different ways:

- Implicit traps: As defined by the x86/x64 or arm64 architecture, some guest actions trap to Hyper-V.  Hyper-V emulates the action and returns control to the guest.  This behavior is generally invisible to the Linux kernel.

- Explicit hypercalls: Linux makes an explicit function call to Hyper-V, passing parameters.  Hyper-V performs the requested action and returns control to the caller.  Parameters are passed in processor registers or in memory shared between the Linux guest and Hyper-V.   On x86/x64, hypercalls use a Hyper-V specific calling sequence.  On arm64, hypercalls use the ARM standard SMCCC calling sequence.

- Synthetic register access: Hyper-V implements a variety of synthetic registers.  On x86/x64 these registers appear as MSRs in the guest, and the Linux kernel can read or write these MSRs using the normal mechanisms defined by the x86/x64 architecture.  On arm64, these synthetic registers must be accessed using explicit hypercalls.

- VMBus: VMBus is a higher-level software construct that is built on the other 3 mechanisms.  It is a message passing interface between the Hyper-V host and the Linux guest.  It uses memory that is shared between Hyper-V and the guest, along with various signaling mechanisms.

The first three communication mechanisms are documented in the [Hyper-V Top Level Functional Spec (TLFS)](<https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/tlfs/tlfs>).  The TLFS describes general Hyper-V functionality and provides details on the hypercalls and synthetic registers.  The TLFS is currently written for the x86/x64 architecture only.

<a id="rst-hyper-v-top-level-functional-spec-tlfs"></a>



VMBus is not documented.  This documentation provides a high-level overview of VMBus and how it works, but the details can be discerned only from the code.

<a id="rst-sharing-memory"></a>

## Sharing Memory

Many aspects are communication between Hyper-V and Linux are based on sharing memory.  Such sharing is generally accomplished as follows:

- Linux allocates memory from its physical address space using standard Linux mechanisms.

- Linux tells Hyper-V the guest physical address (GPA) of the allocated memory.  Many shared areas are kept to 1 page so that a single GPA is sufficient.   Larger shared areas require a list of GPAs, which usually do not need to be contiguous in the guest physical address space.  How Hyper-V is told about the GPA or list of GPAs varies.  In some cases, a single GPA is written to a synthetic register.  In other cases, a GPA or list of GPAs is sent in a VMBus message.

- Hyper-V translates the GPAs into "real" physical memory addresses, and creates a virtual mapping that it can use to access the memory.

- Linux can later revoke sharing it has previously established by telling Hyper-V to set the shared GPA to zero.

Hyper-V operates with a page size of 4 Kbytes. GPAs communicated to Hyper-V may be in the form of page numbers, and always describe a range of 4 Kbytes.  Since the Linux guest page size on x86/x64 is also 4 Kbytes, the mapping from guest page to Hyper-V page is 1-to-1. On arm64, Hyper-V supports guests with 4/16/64 Kbyte pages as defined by the arm64 architecture.   If Linux is using 16 or 64 Kbyte pages, Linux code must be careful to communicate with Hyper-V only in terms of 4 Kbyte pages.  HV_HYP_PAGE_SIZE and related macros are used in code that communicates with Hyper-V so that it works correctly in all configurations.

As described in the TLFS, a few memory pages shared between Hyper-V and the Linux guest are "overlay" pages.  With overlay pages, Linux uses the usual approach of allocating guest memory and telling Hyper-V the GPA of the allocated memory.  But Hyper-V then replaces that physical memory page with a page it has allocated, and the original physical memory page is no longer accessible in the guest VM.  Linux may access the memory normally as if it were the memory that it originally allocated.  The "overlay" behavior is visible only because the contents of the page (as seen by Linux) change at the time that Linux originally establishes the sharing and the overlay page is inserted.  Similarly, the contents change if Linux revokes the sharing, in which case Hyper-V removes the overlay page, and the guest page originally allocated by Linux becomes visible again.

Before Linux does a kexec to a kdump kernel or any other kernel, memory shared with Hyper-V should be revoked.  Hyper-V could modify a shared page or remove an overlay page after the new kernel is using the page for a different purpose, corrupting the new kernel. Hyper-V does not provide a single "set everything" operation to guest VMs, so Linux code must individually revoke all sharing before doing kexec.   See hv_kexec_handler() and hv_crash_handler().  But the crash/panic path still has holes in cleanup because some shared pages are set using per-CPU synthetic registers and there's no mechanism to revoke the shared pages for CPUs other than the CPU running the panic path.

<a id="rst-cpu-management"></a>

## CPU Management

Hyper-V does not have a ability to hot-add or hot-remove a CPU from a running VM.  However, Windows Server 2019 Hyper-V and earlier versions may provide guests with ACPI tables that indicate more CPUs than are actually present in the VM.  As is normal, Linux treats these additional CPUs as potential hot-add CPUs, and reports them as such even though Hyper-V will never actually hot-add them. Starting in Windows Server 2022 Hyper-V, the ACPI tables reflect only the CPUs actually present in the VM, so Linux does not report any hot-add CPUs.

A Linux guest CPU may be taken offline using the normal Linux mechanisms, provided no VMBus channel interrupts are assigned to the CPU.  See the section on VMBus Interrupts for more details on how VMBus channel interrupts can be re-assigned to permit taking a CPU offline.

<a id="rst-bit-and-64-bit"></a>

## 32-bit and 64-bit

On x86/x64, Hyper-V supports 32-bit and 64-bit guests, and Linux will build and run in either version. While the 32-bit version is expected to work, it is used rarely and may suffer from undetected regressions.

On arm64, Hyper-V supports only 64-bit guests.

<a id="rst-endian-ness"></a>

## Endian-ness

All communication between Hyper-V and guest VMs uses Little-Endian format on both x86/x64 and arm64.  Big-endian format on arm64 is not supported by Hyper-V, and Linux code does not use endian-ness macros when accessing data shared with Hyper-V.

<a id="rst-versioning"></a>

## Versioning

Current Linux kernels operate correctly with older versions of Hyper-V back to Windows Server 2012 Hyper-V. Support for running on the original Hyper-V release in Windows Server 2008/2008 R2 has been removed.

A Linux guest on Hyper-V outputs in dmesg the version of Hyper-V it is running on.  This version is in the form of a Windows build number and is for display purposes only. Linux code does not test this version number at runtime to determine available features and functionality. Hyper-V indicates feature/function availability via flags in synthetic MSRs that Hyper-V provides to the guest, and the guest code tests these flags.

VMBus has its own protocol version that is negotiated during the initial VMBus connection from the guest to Hyper-V. This version number is also output to dmesg during boot.  This version number is checked in a few places in the code to determine if specific functionality is present.

Furthermore, each synthetic device on VMBus also has a protocol version that is separate from the VMBus protocol version. Device drivers for these synthetic devices typically negotiate the device protocol version, and may test that protocol version to determine if specific device functionality is present.

<a id="rst-code-packaging"></a>

## Code Packaging

Hyper-V related code appears in the Linux kernel code tree in three main areas:

1. drivers/hv

2. arch/x86/hyperv and arch/arm64/hyperv

3. individual device driver areas such as drivers/scsi, drivers/net, drivers/clocksource, etc.

A few miscellaneous files appear elsewhere. See the full list under "Hyper-V/Azure CORE AND DRIVERS" and "DRM DRIVER FOR HYPERV SYNTHETIC VIDEO DEVICE" in the MAINTAINERS file.

The code in \#1 and \#2 is built only when CONFIG_HYPERV is set. Similarly, the code for most Hyper-V related drivers is built only when CONFIG_HYPERV is set.

Most Hyper-V related code in \#1 and \#3 can be built as a module. The architecture specific code in \#2 must be built-in.  Also, drivers/hv/hv_common.c is low-level code that is common across architectures and must be built-in.

---

# VMBus

_Peios Kernel / Internals / Virtualisation / hyperv_

> VMBus is a software construct provided by Hyper-V to guest VMs. It consists of a control path and common facilities used by synthetic devices that Hyper-V presents to guest VMs. The control path is used to offer synthetic devices to the…

<a id="rst-vmbus"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

VMBus is a software construct provided by Hyper-V to guest VMs.  It consists of a control path and common facilities used by synthetic devices that Hyper-V presents to guest VMs.   The control path is used to offer synthetic devices to the guest VM and, in some cases, to rescind those devices.   The common facilities include software channels for communicating between the device driver in the guest VM and the synthetic device implementation that is part of Hyper-V, and signaling primitives to allow Hyper-V and the guest to interrupt each other.

VMBus is modeled in Linux as a bus, with the expected /sys/bus/vmbus entry in a running Linux guest.  The VMBus driver (drivers/hv/vmbus_drv.c) establishes the VMBus control path with the Hyper-V host, then registers itself as a Linux bus driver.  It implements the standard bus functions for adding and removing devices to/from the bus.

Most synthetic devices offered by Hyper-V have a corresponding Linux device driver.  These devices include:

- SCSI controller

- NIC

- Graphics frame buffer

- Keyboard

- Mouse

- PCI device pass-thru

- Heartbeat

- Time Sync

- Shutdown

- Memory balloon

- Key/Value Pair (KVP) exchange with Hyper-V

- Hyper-V online backup (a.k.a. VSS)

Guest VMs may have multiple instances of the synthetic SCSI controller, synthetic NIC, and PCI pass-thru devices.  Other synthetic devices are limited to a single instance per VM.  Not listed above are a small number of synthetic devices offered by Hyper-V that are used only by Windows guests and for which Linux does not have a driver.

Hyper-V uses the terms "VSP" and "VSC" in describing synthetic devices.  "VSP" refers to the Hyper-V code that implements a particular synthetic device, while "VSC" refers to the driver for the device in the guest VM.  For example, the Linux driver for the synthetic NIC is referred to as "netvsc" and the Linux driver for the synthetic SCSI controller is "storvsc".  These drivers contain functions with names like "storvsc_connect_to_vsp".

<a id="rst-vmbus-channels"></a>

## VMBus channels

An instance of a synthetic device uses VMBus channels to communicate between the VSP and the VSC.  Channels are bi-directional and used for passing messages.   Most synthetic devices use a single channel, but the synthetic SCSI controller and synthetic NIC may use multiple channels to achieve higher performance and greater parallelism.

Each channel consists of two ring buffers.  These are classic ring buffers from a university data structures textbook.  If the read and writes pointers are equal, the ring buffer is considered to be empty, so a full ring buffer always has at least one byte unused. The "in" ring buffer is for messages from the Hyper-V host to the guest, and the "out" ring buffer is for messages from the guest to the Hyper-V host.  In Linux, the "in" and "out" designations are as viewed by the guest side.  The ring buffers are memory that is shared between the guest and the host, and they follow the standard paradigm where the memory is allocated by the guest, with the list of GPAs that make up the ring buffer communicated to the host.  Each ring buffer consists of a header page (4 Kbytes) with the read and write indices and some control flags, followed by the memory for the actual ring.  The size of the ring is determined by the VSC in the guest and is specific to each synthetic device.   The list of GPAs making up the ring is communicated to the Hyper-V host over the VMBus control path as a GPA Descriptor List (GPADL).  See function vmbus_establish_gpadl().

Each ring buffer is mapped into contiguous Linux kernel virtual space in three parts:  1) the 4 Kbyte header page, 2) the memory that makes up the ring itself, and 3) a second mapping of the memory that makes up the ring itself.  Because (2) and (3) are contiguous in kernel virtual space, the code that copies data to and from the ring buffer need not be concerned with ring buffer wrap-around. Once a copy operation has completed, the read or write index may need to be reset to point back into the first mapping, but the actual data copy does not need to be broken into two parts.  This approach also allows complex data structures to be easily accessed directly in the ring without handling wrap-around.

On arm64 with page sizes &gt; 4 Kbytes, the header page must still be passed to Hyper-V as a 4 Kbyte area.  But the memory for the actual ring must be aligned to PAGE_SIZE and have a size that is a multiple of PAGE_SIZE so that the duplicate mapping trick can be done.  Hence a portion of the header page is unused and not communicated to Hyper-V.  This case is handled by vmbus_establish_gpadl().

Hyper-V enforces a limit on the aggregate amount of guest memory that can be shared with the host via GPADLs.  This limit ensures that a rogue guest can't force the consumption of excessive host resources.  For Windows Server 2019 and later, this limit is approximately 1280 Mbytes.  For versions prior to Windows Server 2019, the limit is approximately 384 Mbytes.

<a id="rst-vmbus-channel-messages"></a>

## VMBus channel messages

All messages sent in a VMBus channel have a standard header that includes the message length, the offset of the message payload, some flags, and a transactionID.  The portion of the message after the header is unique to each VSP/VSC pair.

Messages follow one of two patterns:

- Unidirectional:  Either side sends a message and does not expect a response message

- Request/response:  One side (usually the guest) sends a message and expects a response

The transactionID (a.k.a. "requestID") is for matching requests &amp; responses.  Some synthetic devices allow multiple requests to be in- flight simultaneously, so the guest specifies a transactionID when sending a request.  Hyper-V sends back the same transactionID in the matching response.

Messages passed between the VSP and VSC are control messages.  For example, a message sent from the storvsc driver might be "execute this SCSI command".   If a message also implies some data transfer between the guest and the Hyper-V host, the actual data to be transferred may be embedded with the control message, or it may be specified as a separate data buffer that the Hyper-V host will access as a DMA operation.  The former case is used when the size of the data is small and the cost of copying the data to and from the ring buffer is minimal.  For example, time sync messages from the Hyper-V host to the guest contain the actual time value.  When the data is larger, a separate data buffer is used.  In this case, the control message contains a list of GPAs that describe the data buffer.  For example, the storvsc driver uses this approach to specify the data buffers to/from which disk I/O is done.

Three functions exist to send VMBus channel messages:

1. vmbus_sendpacket():  Control-only messages and messages with embedded data -- no GPAs

2. vmbus_sendpacket_pagebuffer(): Message with list of GPAs identifying data to transfer.  An offset and length is associated with each GPA so that multiple discontinuous areas of guest memory can be targeted.

3. vmbus_sendpacket_mpb_desc(): Message with list of GPAs identifying data to transfer.  A single offset and length is associated with a list of GPAs.  The GPAs must describe a single logical area of guest memory to be targeted.

Historically, Linux guests have trusted Hyper-V to send well-formed and valid messages, and Linux drivers for synthetic devices did not fully validate messages.  With the introduction of processor technologies that fully encrypt guest memory and that allow the guest to not trust the hypervisor (AMD SEV-SNP, Intel TDX), trusting the Hyper-V host is no longer a valid assumption.  The drivers for VMBus synthetic devices are being updated to fully validate any values read from memory that is shared with Hyper-V, which includes messages from VMBus devices.  To facilitate such validation, messages read by the guest from the "in" ring buffer are copied to a temporary buffer that is not shared with Hyper-V.  Validation is performed in this temporary buffer without the risk of Hyper-V maliciously modifying the message after it is validated but before it is used.

<a id="rst-synthetic-interrupt-controller-synic"></a>

## Synthetic Interrupt Controller (synic)

Hyper-V provides each guest CPU with a synthetic interrupt controller that is used by VMBus for host-guest communication. While each synic defines 16 synthetic interrupts (SINT), Linux uses only one of the 16 (VMBUS_MESSAGE_SINT). All interrupts related to communication between the Hyper-V host and a guest CPU use that SINT.

The SINT is mapped to a single per-CPU architectural interrupt (i.e, an 8-bit x86/x64 interrupt vector, or an arm64 PPI INTID). Because each CPU in the guest has a synic and may receive VMBus interrupts, they are best modeled in Linux as per-CPU interrupts. This model works well on arm64 where a single per-CPU Linux IRQ is allocated for VMBUS_MESSAGE_SINT. This IRQ appears in /proc/interrupts as an IRQ labelled "Hyper-V VMbus". Since x86/x64 lacks support for per-CPU IRQs, an x86 interrupt vector is statically allocated (HYPERVISOR_CALLBACK_VECTOR) across all CPUs and explicitly coded to call vmbus_isr(). In this case, there's no Linux IRQ, and the interrupts are visible in aggregate in /proc/interrupts on the "HYP" line.

The synic provides the means to demultiplex the architectural interrupt into one or more logical interrupts and route the logical interrupt to the proper VMBus handler in Linux. This demultiplexing is done by vmbus_isr() and related functions that access synic data structures.

The synic is not modeled in Linux as an irq chip or irq domain, and the demultiplexed logical interrupts are not Linux IRQs. As such, they don't appear in /proc/interrupts or /proc/irq. The CPU affinity for one of these logical interrupts is controlled via an entry under /sys/bus/vmbus as described below.

<a id="rst-vmbus-interrupts"></a>

## VMBus interrupts

VMBus provides a mechanism for the guest to interrupt the host when the guest has queued new messages in a ring buffer.  The host expects that the guest will send an interrupt only when an "out" ring buffer transitions from empty to non-empty.  If the guest sends interrupts at other times, the host deems such interrupts to be unnecessary.  If a guest sends an excessive number of unnecessary interrupts, the host may throttle that guest by suspending its execution for a few seconds to prevent a denial-of-service attack.

Similarly, the host will interrupt the guest via the synic when it sends a new message on the VMBus control path, or when a VMBus channel "in" ring buffer transitions from empty to non-empty due to the host inserting a new VMBus channel message. The control message stream and each VMBus channel "in" ring buffer are separate logical interrupts that are demultiplexed by vmbus_isr(). It demultiplexes by first checking for channel interrupts by calling vmbus_chan_sched(), which looks at a synic bitmap to determine which channels have pending interrupts on this CPU. If multiple channels have pending interrupts for this CPU, they are processed sequentially.  When all channel interrupts have been processed, vmbus_isr() checks for and processes any messages received on the VMBus control path.

The guest CPU that a VMBus channel will interrupt is selected by the guest when the channel is created, and the host is informed of that selection.  VMBus devices are broadly grouped into two categories:

1. "Slow" devices that need only one VMBus channel.  The devices (such as keyboard, mouse, heartbeat, and timesync) generate relatively few interrupts.  Their VMBus channels are all assigned to interrupt the VMBUS_CONNECT_CPU, which is always CPU 0.

2. "High speed" devices that may use multiple VMBus channels for higher parallelism and performance.  These devices include the synthetic SCSI controller and synthetic NIC.  Their VMBus channels interrupts are assigned to CPUs that are spread out among the available CPUs in the VM so that interrupts on multiple channels can be processed in parallel.

The assignment of VMBus channel interrupts to CPUs is done in the function init_vp_index().  This assignment is done outside of the normal Linux interrupt affinity mechanism, so the interrupts are neither "unmanaged" nor "managed" interrupts.

The CPU that a VMBus channel will interrupt can be seen in /sys/bus/vmbus/devices/&lt;deviceGUID&gt;/ channels/&lt;channelRelID&gt;/cpu. When running on later versions of Hyper-V, the CPU can be changed by writing a new value to this sysfs entry. Because VMBus channel interrupts are not Linux IRQs, there are no entries in /proc/interrupts or /proc/irq corresponding to individual VMBus channel interrupts.

An online CPU in a Linux guest may not be taken offline if it has VMBus channel interrupts assigned to it. Starting in kernel v6.15, any such interrupts are automatically reassigned to some other CPU at the time of offlining. The "other" CPU is chosen by the implementation and is not load balanced or otherwise intelligently determined. If the CPU is onlined again, channel interrupts previously assigned to it are not moved back. As a result, after multiple CPUs have been offlined, and perhaps onlined again, the interrupt-to-CPU mapping may be scrambled and non-optimal. In such a case, optimal assignments must be re-established manually. For kernels v6.14 and earlier, any conflicting channel interrupts must first be manually reassigned to another CPU as described above. Then when no channel interrupts are assigned to the CPU, it can be taken offline.

The VMBus channel interrupt handling code is designed to work correctly even if an interrupt is received on a CPU other than the CPU assigned to the channel.  Specifically, the code does not use CPU-based exclusion for correctness.  In normal operation, Hyper-V will interrupt the assigned CPU.  But when the CPU assigned to a channel is being changed via sysfs, the guest doesn't know exactly when Hyper-V will make the transition.  The code must work correctly even if there is a time lag before Hyper-V starts interrupting the new CPU.  See comments in target_cpu_store().

<a id="rst-vmbus-device-creation-deletion"></a>

## VMBus device creation/deletion

Hyper-V and the Linux guest have a separate message-passing path that is used for synthetic device creation and deletion. This path does not use a VMBus channel.  See vmbus_post_msg() and vmbus_on_msg_dpc().

The first step is for the guest to connect to the generic Hyper-V VMBus mechanism.  As part of establishing this connection, the guest and Hyper-V agree on a VMBus protocol version they will use.  This negotiation allows newer Linux kernels to run on older Hyper-V versions, and vice versa.

The guest then tells Hyper-V to "send offers".  Hyper-V sends an offer message to the guest for each synthetic device that the VM is configured to have. Each VMBus device type has a fixed GUID known as the "class ID", and each VMBus device instance is also identified by a GUID. The offer message from Hyper-V contains both GUIDs to uniquely (within the VM) identify the device. There is one offer message for each device instance, so a VM with two synthetic NICs will get two offers messages with the NIC class ID. The ordering of offer messages can vary from boot-to-boot and must not be assumed to be consistent in Linux code. Offer messages may also arrive long after Linux has initially booted because Hyper-V supports adding devices, such as synthetic NICs, to running VMs. A new offer message is processed by vmbus_process_offer(), which indirectly invokes vmbus_add_channel_work().

Upon receipt of an offer message, the guest identifies the device type based on the class ID, and invokes the correct driver to set up the device.  Driver/device matching is performed using the standard Linux mechanism.

The device driver probe function opens the primary VMBus channel to the corresponding VSP. It allocates guest memory for the channel ring buffers and shares the ring buffer with the Hyper-V host by giving the host a list of GPAs for the ring buffer memory.  See vmbus_establish_gpadl().

Once the ring buffer is set up, the device driver and VSP exchange setup messages via the primary channel.  These messages may include negotiating the device protocol version to be used between the Linux VSC and the VSP on the Hyper-V host.  The setup messages may also include creating additional VMBus channels, which are somewhat mis-named as "sub-channels" since they are functionally equivalent to the primary channel once they are created.

Finally, the device driver may create entries in /dev as with any device driver.

The Hyper-V host can send a "rescind" message to the guest to remove a device that was previously offered. Linux drivers must handle such a rescind message at any time. Rescinding a device invokes the device driver "remove" function to cleanly shut down the device and remove it. Once a synthetic device is rescinded, neither Hyper-V nor Linux retains any state about its previous existence. Such a device might be re-added later, in which case it is treated as an entirely new device. See vmbus_onoffer_rescind().

For some devices, such as the KVP device, Hyper-V automatically sends a rescind message when the primary channel is closed, likely as a result of unbinding the device from its driver. The rescind causes Linux to remove the device. But then Hyper-V immediately reoffers the device to the guest, causing a new instance of the device to be created in Linux. For other devices, such as the synthetic SCSI and NIC devices, closing the primary channel does *not* result in Hyper-V sending a rescind message. The device continues to exist in Linux on the VMBus, but with no driver bound to it. The same driver or a new driver can subsequently be bound to the existing instance of the device.

---

# PCI pass-thru devices

_Peios Kernel / Internals / Virtualisation / hyperv_

> In a Hyper-V guest VM, PCI pass-thru devices (also called virtual PCI devices, or vPCI devices) are physical PCI devices that are mapped directly into the VM's physical address space. Guest device drivers can interact directly with the…

<a id="rst-pci-pass-thru-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

In a Hyper-V guest VM, PCI pass-thru devices (also called virtual PCI devices, or vPCI devices) are physical PCI devices that are mapped directly into the VM's physical address space. Guest device drivers can interact directly with the hardware without intermediation by the host hypervisor.  This approach provides higher bandwidth access to the device with lower latency, compared with devices that are virtualized by the hypervisor.  The device should appear to the guest just as it would when running on bare metal, so no changes are required to the Linux device drivers for the device.

Hyper-V terminology for vPCI devices is "Discrete Device Assignment" (DDA).  Public documentation for Hyper-V DDA is available here: [DDA](<https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/plan/plan-for-deploying-devices-using-discrete-device-assignment>)

<a id="rst-dda"></a>



DDA is typically used for storage controllers, such as NVMe, and for GPUs.  A similar mechanism for NICs is called SR-IOV and produces the same benefits by allowing a guest device driver to interact directly with the hardware.  See Hyper-V public documentation here: [SR-IOV](<https://learn.microsoft.com/en-us/windows-hardware/drivers/network/overview-of-single-root-i-o-virtualization--sr-iov->)

<a id="rst-sr-iov"></a>



This discussion of vPCI devices includes DDA and SR-IOV devices.

<a id="rst-device-presentation"></a>

## Device Presentation

Hyper-V provides full PCI functionality for a vPCI device when it is operating, so the Linux device driver for the device can be used unchanged, provided it uses the correct Linux kernel APIs for accessing PCI config space and for other integration with Linux.  But the initial detection of the PCI device and its integration with the Linux PCI subsystem must use Hyper-V specific mechanisms.  Consequently, vPCI devices on Hyper-V have a dual identity.  They are initially presented to Linux guests as VMBus devices via the standard VMBus "offer" mechanism, so they have a VMBus identity and appear under /sys/bus/vmbus/devices.  The VMBus vPCI driver in Linux at drivers/pci/controller/pci-hyperv.c handles a newly introduced vPCI device by fabricating a PCI bus topology and creating all the normal PCI device data structures in Linux that would exist if the PCI device were discovered via ACPI on a bare- metal system.  Once those data structures are set up, the device also has a normal PCI identity in Linux, and the normal Linux device driver for the vPCI device can function as if it were running in Linux on bare-metal.  Because vPCI devices are presented dynamically through the VMBus offer mechanism, they do not appear in the Linux guest's ACPI tables.  vPCI devices may be added to a VM or removed from a VM at any time during the life of the VM, and not just during initial boot.

With this approach, the vPCI device is a VMBus device and a PCI device at the same time.  In response to the VMBus offer message, the hv_pci_probe() function runs and establishes a VMBus connection to the vPCI VSP on the Hyper-V host.  That connection has a single VMBus channel.  The channel is used to exchange messages with the vPCI VSP for the purpose of setting up and configuring the vPCI device in Linux.  Once the device is fully configured in Linux as a PCI device, the VMBus channel is used only if Linux changes the vCPU to be interrupted in the guest, or if the vPCI device is removed from the VM while the VM is running.  The ongoing operation of the device happens directly between the Linux device driver for the device and the hardware, with VMBus and the VMBus channel playing no role.

<a id="rst-pci-device-setup"></a>

## PCI Device Setup

PCI device setup follows a sequence that Hyper-V originally created for Windows guests, and that can be ill-suited for Linux guests due to differences in the overall structure of the Linux PCI subsystem compared with Windows.  Nonetheless, with a bit of hackery in the Hyper-V virtual PCI driver for Linux, the virtual PCI device is setup in Linux so that generic Linux PCI subsystem code and the Linux driver for the device "just work".

Each vPCI device is set up in Linux to be in its own PCI domain with a host bridge.  The PCI domainID is derived from bytes 4 and 5 of the instance GUID assigned to the VMBus vPCI device.  The Hyper-V host does not guarantee that these bytes are unique, so hv_pci_probe() has an algorithm to resolve collisions.  The collision resolution is intended to be stable across reboots of the same VM so that the PCI domainIDs don't change, as the domainID appears in the user space configuration of some devices.

hv_pci_probe() allocates a guest MMIO range to be used as PCI config space for the device.  This MMIO range is communicated to the Hyper-V host over the VMBus channel as part of telling the host that the device is ready to enter d0.  See hv_pci_enter_d0().  When the guest subsequently accesses this MMIO range, the Hyper-V host intercepts the accesses and maps them to the physical device PCI config space.

hv_pci_probe() also gets BAR information for the device from the Hyper-V host, and uses this information to allocate MMIO space for the BARs.  That MMIO space is then setup to be associated with the host bridge so that it works when generic PCI subsystem code in Linux processes the BARs.

Finally, hv_pci_probe() creates the root PCI bus.  At this point the Hyper-V virtual PCI driver hackery is done, and the normal Linux PCI machinery for scanning the root bus works to detect the device, to perform driver matching, and to initialize the driver and device.

<a id="rst-pci-device-removal"></a>

## PCI Device Removal

A Hyper-V host may initiate removal of a vPCI device from a guest VM at any time during the life of the VM.  The removal is instigated by an admin action taken on the Hyper-V host and is not under the control of the guest OS.

A guest VM is notified of the removal by an unsolicited "Eject" message sent from the host to the guest over the VMBus channel associated with the vPCI device.  Upon receipt of such a message, the Hyper-V virtual PCI driver in Linux asynchronously invokes Linux kernel PCI subsystem calls to shutdown and remove the device.  When those calls are complete, an "Ejection Complete" message is sent back to Hyper-V over the VMBus channel indicating that the device has been removed.  At this point, Hyper-V sends a VMBus rescind message to the Linux guest, which the VMBus driver in Linux processes by removing the VMBus identity for the device.  Once that processing is complete, all vestiges of the device having been present are gone from the Linux kernel.  The rescind message also indicates to the guest that Hyper-V has stopped providing support for the vPCI device in the guest.  If the guest were to attempt to access that device's MMIO space, it would be an invalid reference. Hypercalls affecting the device return errors, and any further messages sent in the VMBus channel are ignored.

After sending the Eject message, Hyper-V allows the guest VM 60 seconds to cleanly shutdown the device and respond with Ejection Complete before sending the VMBus rescind message.  If for any reason the Eject steps don't complete within the allowed 60 seconds, the Hyper-V host forcibly performs the rescind steps, which will likely result in cascading errors in the guest because the device is now no longer present from the guest standpoint and accessing the device MMIO space will fail.

Because ejection is asynchronous and can happen at any point during the guest VM lifecycle, proper synchronization in the Hyper-V virtual PCI driver is very tricky.  Ejection has been observed even before a newly offered vPCI device has been fully setup.  The Hyper-V virtual PCI driver has been updated several times over the years to fix race conditions when ejections happen at inopportune times. Care must be taken when modifying this code to prevent re-introducing such problems. See comments in the code.

<a id="rst-interrupt-assignment"></a>

## Interrupt Assignment

The Hyper-V virtual PCI driver supports vPCI devices using MSI, multi-MSI, or MSI-X.  Assigning the guest vCPU that will receive the interrupt for a particular MSI or MSI-X message is complex because of the way the Linux setup of IRQs maps onto the Hyper-V interfaces.  For the single-MSI and MSI-X cases, Linux calls hv_compse_msi_msg() twice, with the first call containing a dummy vCPU and the second call containing the real vCPU.  Furthermore, hv_irq_unmask() is finally called (on x86) or the GICD registers are set (on arm64) to specify the real vCPU again.  Each of these three calls interact with Hyper-V, which must decide which physical CPU should receive the interrupt before it is forwarded to the guest VM. Unfortunately, the Hyper-V decision-making process is a bit limited, and can result in concentrating the physical interrupts on a single CPU, causing a performance bottleneck. See details about how this is resolved in the extensive comment above the function hv_compose_msi_req_get_cpu().

The Hyper-V virtual PCI driver implements the irq_chip.irq_compose_msi_msg function as hv_compose_msi_msg(). Unfortunately, on Hyper-V the implementation requires sending a VMBus message to the Hyper-V host and awaiting an interrupt indicating receipt of a reply message.  Since irq_chip.irq_compose_msi_msg can be called with IRQ locks held, it doesn't work to do the normal sleep until awakened by the interrupt. Instead hv_compose_msi_msg() must send the VMBus message, and then poll for the completion message. As further complexity, the vPCI device could be ejected/rescinded while the polling is in progress, so this scenario must be detected as well.  See comments in the code regarding this very tricky area.

Most of the code in the Hyper-V virtual PCI driver (pci- hyperv.c) applies to Hyper-V and Linux guests running on x86 and on arm64 architectures.  But there are differences in how interrupt assignments are managed.  On x86, the Hyper-V virtual PCI driver in the guest must make a hypercall to tell Hyper-V which guest vCPU should be interrupted by each MSI/MSI-X interrupt, and the x86 interrupt vector number that the x86_vector IRQ domain has picked for the interrupt.  This hypercall is made by hv_arch_irq_unmask().  On arm64, the Hyper-V virtual PCI driver manages the allocation of an SPI for each MSI/MSI-X interrupt.  The Hyper-V virtual PCI driver stores the allocated SPI in the architectural GICD registers, which Hyper-V emulates, so no hypercall is necessary as with x86.  Hyper-V does not support using LPIs for vPCI devices in arm64 guest VMs because it does not emulate a GICv3 ITS.

The Hyper-V virtual PCI driver in Linux supports vPCI devices whose drivers create managed or unmanaged Linux IRQs.  If the smp_affinity for an unmanaged IRQ is updated via the /proc/irq interface, the Hyper-V virtual PCI driver is called to tell the Hyper-V host to change the interrupt targeting and everything works properly.  However, on x86 if the x86_vector IRQ domain needs to reassign an interrupt vector due to running out of vectors on a CPU, there's no path to inform the Hyper-V host of the change, and things break.  Fortunately, guest VMs operate in a constrained device environment where using all the vectors on a CPU doesn't happen. Since such a problem is only a theoretical concern rather than a practical concern, it has been left unaddressed.

<a id="rst-dma"></a>

## DMA

By default, Hyper-V pins all guest VM memory in the host when the VM is created, and programs the physical IOMMU to allow the VM to have DMA access to all its memory.  Hence it is safe to assign PCI devices to the VM, and allow the guest operating system to program the DMA transfers.  The physical IOMMU prevents a malicious guest from initiating DMA to memory belonging to the host or to other VMs on the host. From the Linux guest standpoint, such DMA transfers are in "direct" mode since Hyper-V does not provide a virtual IOMMU in the guest.

Hyper-V assumes that physical PCI devices always perform cache-coherent DMA.  When running on x86, this behavior is required by the architecture.  When running on arm64, the architecture allows for both cache-coherent and non-cache-coherent devices, with the behavior of each device specified in the ACPI DSDT.  But when a PCI device is assigned to a guest VM, that device does not appear in the DSDT, so the Hyper-V VMBus driver propagates cache-coherency information from the VMBus node in the ACPI DSDT to all VMBus devices, including vPCI devices (since they have a dual identity as a VMBus device and as a PCI device).  See vmbus_dma_configure(). Current Hyper-V versions always indicate that the VMBus is cache coherent, so vPCI devices on arm64 always get marked as cache coherent and the CPU does not perform any sync operations as part of dma_map/unmap\_\*() calls.

<a id="rst-vpci-protocol-versions"></a>

## vPCI protocol versions

As previously described, during vPCI device setup and teardown messages are passed over a VMBus channel between the Hyper-V host and the Hyper-v vPCI driver in the Linux guest.  Some messages have been revised in newer versions of Hyper-V, so the guest and host must agree on the vPCI protocol version to be used.  The version is negotiated when communication over the VMBus channel is first established.  See hv_pci_protocol_negotiation(). Newer versions of the protocol extend support to VMs with more than 64 vCPUs, and provide additional information about the vPCI device, such as the guest virtual NUMA node to which it is most closely affined in the underlying hardware.

<a id="rst-guest-numa-node-affinity"></a>

## Guest NUMA node affinity

When the vPCI protocol version provides it, the guest NUMA node affinity of the vPCI device is stored as part of the Linux device information for subsequent use by the Linux driver. See hv_pci_assign_numa_node().  If the negotiated protocol version does not support the host providing NUMA affinity information, the Linux guest defaults the device NUMA node to 0.  But even when the negotiated protocol version includes NUMA affinity information, the ability of the host to provide such information depends on certain host configuration options.  If the guest receives NUMA node value "0", it could mean NUMA node 0, or it could mean "no information is available". Unfortunately it is not possible to distinguish the two cases from the guest side.

<a id="rst-pci-config-space-access-in-a-coco-vm"></a>

## PCI config space access in a CoCo VM

Linux PCI device drivers access PCI config space using a standard set of functions provided by the Linux PCI subsystem. In Hyper-V guests these standard functions map to functions hv_pcifront_read_config() and hv_pcifront_write_config() in the Hyper-V virtual PCI driver.  In normal VMs, these hv_pcifront\_\*() functions directly access the PCI config space, and the accesses trap to Hyper-V to be handled. But in CoCo VMs, memory encryption prevents Hyper-V from reading the guest instruction stream to emulate the access, so the hv_pcifront\_\*() functions must invoke hypercalls with explicit arguments describing the access to be made.

<a id="rst-config-block-back-channel"></a>

## Config Block back-channel

The Hyper-V host and Hyper-V virtual PCI driver in Linux together implement a non-standard back-channel communication path between the host and guest.  The back-channel path uses messages sent over the VMBus channel associated with the vPCI device.  The functions hyperv_read_cfg_blk() and hyperv_write_cfg_blk() are the primary interfaces provided to other parts of the Linux kernel.  As of this writing, these interfaces are used only by the Mellanox mlx5 driver to pass diagnostic data to a Hyper-V host running in the Azure public cloud.  The functions hyperv_read_cfg_blk() and hyperv_write_cfg_blk() are implemented in a separate module (pci-hyperv-intf.c, under CONFIG_PCI_HYPERV_INTERFACE) that effectively stubs them out when running in non-Hyper-V environments.

---

# KVM

_Peios Kernel / Internals / Virtualisation / kvm_

> Reference for KVM.

<a id="rst-kvm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [The Definitive KVM (Kernel-based Virtual Machine) API Documentation](</kernel/internals/virt/kvm/api.md>)
- [Devices](</kernel/internals/virt/kvm-devices/index.md>)
- [ARM](</kernel/internals/virt/kvm-arm/index.md>)
- [KVM for s390 systems](</kernel/internals/virt/kvm-s390/index.md>)
- [The PPC KVM paravirtual interface](</kernel/internals/virt/kvm/ppc-pv.md>)
- [KVM for x86 systems](</kernel/internals/virt/kvm-x86/index.md>)
- [KVM for LoongArch systems](</kernel/internals/virt/kvm-loongarch/index.md>)
- [KVM Lock Overview](</kernel/internals/virt/kvm/locking.md>)
- [KVM VCPU Requests](</kernel/internals/virt/kvm/vcpu-requests.md>)
- [The KVM halt polling system](</kernel/internals/virt/kvm/halt-polling.md>)
- [Review checklist for kvm patches](</kernel/internals/virt/kvm/review-checklist.md>)

---

# The Definitive KVM (Kernel-based Virtual Machine) API Documentation

_Peios Kernel / Internals / Virtualisation / kvm_

> The kvm API is centered around different kinds of file descriptors and ioctls that can be issued to these file descriptors. An initial open("/dev/kvm") obtains a handle to the kvm subsystem; this handle can be used to issue system ioctls.…

> **Peios:** Linux capability names in this interface retain their API meaning, but KACS evaluates them through native token privileges or compatibility rules. UID 0, `setcap` and Unix mode bits do not independently grant native authority. Object access and PIP checks remain additional constraints where applicable. See [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>) for the mapping and exceptions.


<a id="rst-the-definitive-kvm-kernel-based-virtual-machine-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-general-description"></a>

## 1. General description

The kvm API is centered around different kinds of file descriptors and ioctls that can be issued to these file descriptors.  An initial open("/dev/kvm") obtains a handle to the kvm subsystem; this handle can be used to issue system ioctls.  A KVM_CREATE_VM ioctl on this handle will create a VM file descriptor which can be used to issue VM ioctls.  A KVM_CREATE_VCPU or KVM_CREATE_DEVICE ioctl on a VM fd will create a virtual cpu or device and return a file descriptor pointing to the new resource.

In other words, the kvm API is a set of ioctls that are issued to different kinds of file descriptor in order to control various aspects of a virtual machine.  Depending on the file descriptor that accepts them, ioctls belong to the following classes:

> - System ioctls: These query and set global attributes which affect the whole kvm subsystem.  In addition a system ioctl is used to create virtual machines.
>
> - VM ioctls: These query and set attributes that affect an entire virtual machine, for example memory layout.  In addition a VM ioctl is used to create virtual cpus (vcpus) and devices.
>
>   VM ioctls must be issued from the same process (address space) that was used to create the VM.
>
> - vcpu ioctls: These query and set attributes that control the operation of a single virtual cpu.
>
>   vcpu ioctls should be issued from the same thread that was used to create the vcpu, except for asynchronous vcpu ioctl that are marked as such in the documentation.  Otherwise, the first ioctl after switching threads could see a performance impact.
>
> - device ioctls: These query and set attributes that control the operation of a single device.
>
>   device ioctls must be issued from the same process (address space) that was used to create the VM.

While most ioctls are specific to one kind of file descriptor, in some cases the same ioctl can belong to more than one class.

The KVM API grew over time.  For this reason, KVM defines many constants of the form `KVM_CAP_*`, each corresponding to a set of functionality provided by one or more ioctls.  Availability of these "capabilities" can be checked with [KVM_CHECK_EXTENSION](<#rst-kvm-check-extension>).  Some capabilities also need to be enabled for VMs or VCPUs where their functionality is desired (see [6. Capabilities that can be enabled on vCPUs](<#rst-cap-enable>) and [7. Capabilities that can be enabled on VMs](<#rst-cap-enable-vm>)).

<a id="rst-restrictions"></a>

## 2. Restrictions

In general file descriptors can be migrated among processes by means of fork() and the SCM_RIGHTS facility of unix domain socket.  These kinds of tricks are explicitly not supported by kvm.  While they will not cause harm to the host, their actual behavior is not guaranteed by the API.  See "General description" for details on the ioctl usage model that is supported by KVM.

It is important to note that although VM ioctls may only be issued from the process that created the VM, a VM's lifecycle is associated with its file descriptor, not its creator (process).  In other words, the VM and its resources, *including the associated address space*, are not freed until the last reference to the VM's file descriptor has been released. For example, if fork() is issued after ioctl(KVM_CREATE_VM), the VM will not be freed until both the parent (original) process and its child have put their references to the VM's file descriptor.

Because a VM's resources are not freed until the last reference to its file descriptor is released, creating additional references to a VM via fork(), dup(), etc... without careful consideration is strongly discouraged and may have unwanted side effects, e.g. memory allocated by and on behalf of the VM's process may not be freed/unaccounted when the VM is shut down.

<a id="rst-extensions"></a>

## 3. Extensions

As of Linux 2.6.22, the KVM ABI has been stabilized: no backward incompatible change are allowed.  However, there is an extension facility that allows backward-compatible extensions to the API to be queried and used.

The extension mechanism is not based on the Linux version number. Instead, kvm defines extension identifiers and a facility to query whether a particular extension identifier is available.  If it is, a set of ioctls is available for application use.

<a id="rst-api-description"></a>

## 4. API description

This section describes ioctls that can be used to control kvm guests. For each ioctl, the following information is provided along with a description:

> - **Capability:**
>
>   which KVM extension provides this ioctl.  Can be 'basic', which means that is will be provided by any kernel that supports API version 12 (see [KVM_GET_API_VERSION](<#rst-kvm-get-api-version>)), or a KVM_CAP_xyz constant that can be checked with [KVM_CHECK_EXTENSION](<#rst-kvm-check-extension>).
>
> - **Architectures:**
>
>   which instruction set architectures provide this ioctl. x86 includes both i386 and x86_64.
>
> - **Type:**
>
>   system, vm, or vcpu.
>
> - **Parameters:**
>
>   what parameters are accepted by the ioctl.
>
> - **Returns:**
>
>   the return value.  General error numbers (EBADF, ENOMEM, EINVAL) are not detailed, but errors with specific meanings are.

<a id="rst-kvm-get-api-version-1"></a>
<a id="rst-kvm-get-api-version"></a>

### 4.1 KVM_GET_API_VERSION

**Capability:** basic

**Architectures:** all

**Type:** system ioctl

**Parameters:** none

**Returns:** the constant KVM_API_VERSION (=12)

This identifies the API version as the stable kvm API. It is not expected that this number will change.  However, Linux 2.6.20 and 2.6.21 report earlier versions; these are not documented and not supported.  Applications should refuse to run if KVM_GET_API_VERSION returns a value other than 12.  If this check passes, all ioctls described as 'basic' will be available.

<a id="rst-kvm-create-vm"></a>

### 4.2 KVM_CREATE_VM

**Capability:** basic

**Architectures:** all

**Type:** system ioctl

**Parameters:** machine type identifier (KVM_VM\_\*)

**Returns:** a VM fd that can be used to control the new virtual machine.

The new VM has no virtual cpus and no memory. You probably want to use 0 as machine type.

<a id="rst-x86"></a>

#### X86:

Supported X86 VM types can be queried via KVM_CAP_VM_TYPES.

<a id="rst-s390"></a>

#### S390:

In order to create user controlled virtual machines on S390, check KVM_CAP_S390_UCONTROL and use the flag KVM_VM_S390_UCONTROL as privileged user (CAP_SYS_ADMIN).

<a id="rst-mips"></a>

#### MIPS:

To use hardware assisted virtualization on MIPS (VZ ASE) rather than the default trap &amp; emulate implementation (which changes the virtual memory layout to fit in user mode), check KVM_CAP_MIPS_VZ and use the flag KVM_VM_MIPS_VZ.

<a id="rst-arm64"></a>

#### ARM64:

On arm64, the physical address size for a VM (IPA Size limit) is limited to 40bits by default. The limit can be configured if the host supports the extension KVM_CAP_ARM_VM_IPA_SIZE. When supported, use KVM_VM_TYPE_ARM_IPA_SIZE(IPA_Bits) to set the size in the machine type identifier, where IPA_Bits is the maximum width of any physical address used by the VM. The IPA_Bits is encoded in bits\[7-0\] of the machine type identifier.

e.g, to configure a guest to use 48bit physical address size:



```text
vm_fd = ioctl(dev_fd, KVM_CREATE_VM, KVM_VM_TYPE_ARM_IPA_SIZE(48));
```

The requested size (IPA_Bits) must be:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Implies default size, 40bits (for backward compatibility)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> N
>
> </td>
> <td>
>
>
> Implies N bits, where N is a positive integer such that, 32 &lt;= N &lt;= Host_IPA_Limit
>
> </td>
> </tr>
> </tbody>
> </table>

Host_IPA_Limit is the maximum possible value for IPA_Bits on the host and is dependent on the CPU capability and the kernel configuration. The limit can be retrieved using KVM_CAP_ARM_VM_IPA_SIZE of the KVM_CHECK_EXTENSION ioctl() at run-time.

Creation of the VM will fail if the requested IPA size (whether it is implicit or explicit) is unsupported on the host.

Please note that configuring the IPA size does not affect the capability exposed by the guest CPUs in ID_AA64MMFR0_EL1\[PARange\]. It only affects size of the address translated by the stage2 level (guest physical to host physical address translations).

<a id="rst-kvm-get-msr-index-list-kvm-get-msr-feature-index-list"></a>

### 4.3 KVM_GET_MSR_INDEX_LIST, KVM_GET_MSR_FEATURE_INDEX_LIST

**Capability:** basic, KVM_CAP_GET_MSR_FEATURES for KVM_GET_MSR_FEATURE_INDEX_LIST

**Architectures:** x86

**Type:** system ioctl

**Parameters:** struct kvm_msr_list (in/out)

**Returns:** 0 on success; -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EFAULT
>
> </td>
> <td>
>
>
> the msr index list cannot be read from or written to
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> E2BIG
>
> </td>
> <td>
>
>
> the msr index list is too big to fit in the array specified by the user.
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_msr_list {
      __u32 nmsrs; /* number of msrs in entries */
      __u32 indices[0];
};
```

The user fills in the size of the indices array in nmsrs, and in return kvm adjusts nmsrs to reflect the actual number of msrs and fills in the indices array with their numbers.

KVM_GET_MSR_INDEX_LIST returns the guest msrs that are supported.  The list varies by kvm version and host processor, but does not change otherwise.

Note: if kvm indicates supports MCE (KVM_CAP_MCE), then the MCE bank MSRs are not returned in the MSR list, as different vcpus can have a different number of banks, as set via the KVM_X86_SETUP_MCE ioctl.

KVM_GET_MSR_FEATURE_INDEX_LIST returns the list of MSRs that can be passed to the KVM_GET_MSRS system ioctl.  This lets userspace probe host capabilities and processor features that are exposed via MSRs (e.g., VMX capabilities). This list also varies by kvm version and host processor, but does not change otherwise.

<a id="rst-kvm-check-extension-1"></a>
<a id="rst-kvm-check-extension"></a>

### 4.4 KVM_CHECK_EXTENSION

**Capability:** basic, KVM_CAP_CHECK_EXTENSION_VM for vm ioctl

**Architectures:** all

**Type:** system ioctl, vm ioctl

**Parameters:** extension identifier (KVM_CAP\_\*)

**Returns:** 0 if unsupported; 1 (or some other positive integer) if supported

The API allows the application to query about extensions to the core kvm API.  Userspace passes an extension identifier (an integer) and receives an integer that describes the extension availability. Generally 0 means no and 1 means yes, but some extensions may report additional information in the integer return value.

Based on their initialization different VMs may have different capabilities. It is thus encouraged to use the vm ioctl to query for capabilities (available with KVM_CAP_CHECK_EXTENSION_VM on the vm fd)

<a id="rst-kvm-get-vcpu-mmap-size"></a>

### 4.5 KVM_GET_VCPU_MMAP_SIZE

**Capability:** basic

**Architectures:** all

**Type:** system ioctl

**Parameters:** none

**Returns:** size of vcpu mmap area, in bytes

The KVM_RUN ioctl (cf.) communicates with userspace via a shared memory region.  This ioctl returns the size of that region.  See the KVM_RUN documentation for details.

Besides the size of the KVM_RUN communication region, other areas of the VCPU file descriptor can be mmap-ed, including:

- if KVM_CAP_COALESCED_MMIO is available, a page at KVM_COALESCED_MMIO_PAGE_OFFSET \* PAGE_SIZE; for historical reasons, this page is included in the result of KVM_GET_VCPU_MMAP_SIZE. KVM_CAP_COALESCED_MMIO is not documented yet.

- if KVM_CAP_DIRTY_LOG_RING is available, a number of pages at KVM_DIRTY_LOG_PAGE_OFFSET \* PAGE_SIZE.  For more information on KVM_CAP_DIRTY_LOG_RING, see [7. Capabilities that can be enabled on VMs](<#rst-kvm-cap-dirty-log-ring>).

<a id="rst-kvm-create-vcpu"></a>

### 4.7 KVM_CREATE_VCPU

**Capability:** basic

**Architectures:** all

**Type:** vm ioctl

**Parameters:** vcpu id (apic id on x86)

**Returns:** vcpu fd on success, -1 on error

This API adds a vcpu to a virtual machine. No more than max_vcpus may be added. The vcpu id is an integer in the range \[0, max_vcpu_id).

The recommended max_vcpus value can be retrieved using the KVM_CAP_NR_VCPUS of the KVM_CHECK_EXTENSION ioctl() at run-time. The maximum possible value for max_vcpus can be retrieved using the KVM_CAP_MAX_VCPUS of the KVM_CHECK_EXTENSION ioctl() at run-time.

If the KVM_CAP_NR_VCPUS does not exist, you should assume that max_vcpus is 4 cpus max. If the KVM_CAP_MAX_VCPUS does not exist, you should assume that max_vcpus is same as the value returned from KVM_CAP_NR_VCPUS.

The maximum possible value for max_vcpu_id can be retrieved using the KVM_CAP_MAX_VCPU_ID of the KVM_CHECK_EXTENSION ioctl() at run-time.

If the KVM_CAP_MAX_VCPU_ID does not exist, you should assume that max_vcpu_id is the same as the value returned from KVM_CAP_MAX_VCPUS.

On powerpc using book3s_hv mode, the vcpus are mapped onto virtual threads in one or more virtual CPU cores.  (This is because the hardware requires all the hardware threads in a CPU core to be in the same partition.)  The KVM_CAP_PPC_SMT capability indicates the number of vcpus per virtual core (vcore).  The vcore id is obtained by dividing the vcpu id by the number of vcpus per vcore.  The vcpus in a given vcore will always be in the same physical core as each other (though that might be a different physical core from time to time). Userspace can control the threading (SMT) mode of the guest by its allocation of vcpu ids.  For example, if userspace wants single-threaded guest vcpus, it should make all vcpu ids be a multiple of the number of vcpus per vcore.

For virtual cpus that have been created with S390 user controlled virtual machines, the resulting vcpu fd can be memory mapped at page offset KVM_S390_SIE_PAGE_OFFSET in order to obtain a memory map of the virtual cpu's hardware control block.

<a id="rst-kvm-get-dirty-log"></a>

### 4.8 KVM_GET_DIRTY_LOG

**Capability:** basic

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_dirty_log (in/out)

**Returns:** 0 on success, -1 on error



```text
/* for KVM_GET_DIRTY_LOG */
struct kvm_dirty_log {
      __u32 slot;
      __u32 padding;
      union {
              void __user *dirty_bitmap; /* one bit per page */
              __u64 padding;
      };
};
```

Given a memory slot, return a bitmap containing any pages dirtied since the last call to this ioctl.  Bit 0 is the first page in the memory slot.  Ensure the entire structure is cleared to avoid padding issues.

If KVM_CAP_MULTI_ADDRESS_SPACE is available, bits 16-31 of slot field specifies the address space for which you want to return the dirty bitmap.  See KVM_SET_USER_MEMORY_REGION for details on the usage of slot field.

The bits in the dirty bitmap are cleared before the ioctl returns, unless KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled.  For more information, see the description of the capability.

Note that the Xen shared_info page, if configured, shall always be assumed to be dirty. KVM will not explicitly mark it such.

<a id="rst-kvm-run"></a>

### 4.10 KVM_RUN

**Capability:** basic

**Architectures:** all

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EINTR
>
> </td>
> <td>
>
>
> an unmasked signal is pending
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOEXEC
>
> </td>
> <td>
>
>
> the vcpu hasn't been initialized or the guest tried to execute instructions from device memory (arm64)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOSYS
>
> </td>
> <td>
>
>
> data abort outside memslots with no syndrome info and KVM_CAP_ARM_NISV_TO_USER not enabled (arm64)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EPERM
>
> </td>
> <td>
>
>
> SVE feature set but not finalized (arm64)
>
> </td>
> </tr>
> </tbody>
> </table>

This ioctl is used to run a guest virtual cpu.  While there are no explicit parameters, there is an implicit parameter block that can be obtained by mmap()ing the vcpu fd at offset 0, with the size given by KVM_GET_VCPU_MMAP_SIZE.  The parameter block is formatted as a 'struct kvm_run' (see below).

<a id="rst-kvm-get-regs"></a>

### 4.11 KVM_GET_REGS

**Capability:** basic

**Architectures:** all except arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_regs (out)

**Returns:** 0 on success, -1 on error

Reads the general purpose registers from the vcpu.



```text
/* x86 */
struct kvm_regs {
      /* out (KVM_GET_REGS) / in (KVM_SET_REGS) */
      __u64 rax, rbx, rcx, rdx;
      __u64 rsi, rdi, rsp, rbp;
      __u64 r8,  r9,  r10, r11;
      __u64 r12, r13, r14, r15;
      __u64 rip, rflags;
};

/* mips */
struct kvm_regs {
      /* out (KVM_GET_REGS) / in (KVM_SET_REGS) */
      __u64 gpr[32];
      __u64 hi;
      __u64 lo;
      __u64 pc;
};

/* LoongArch */
struct kvm_regs {
      /* out (KVM_GET_REGS) / in (KVM_SET_REGS) */
      unsigned long gpr[32];
      unsigned long pc;
};
```

<a id="rst-kvm-set-regs"></a>

### 4.12 KVM_SET_REGS

**Capability:** basic

**Architectures:** all except arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_regs (in)

**Returns:** 0 on success, -1 on error

Writes the general purpose registers into the vcpu.

See KVM_GET_REGS for the data structure.

<a id="rst-kvm-get-sregs"></a>

### 4.13 KVM_GET_SREGS

**Capability:** basic

**Architectures:** x86, ppc

**Type:** vcpu ioctl

**Parameters:** struct kvm_sregs (out)

**Returns:** 0 on success, -1 on error

Reads special registers from the vcpu.



```text
/* x86 */
struct kvm_sregs {
      struct kvm_segment cs, ds, es, fs, gs, ss;
      struct kvm_segment tr, ldt;
      struct kvm_dtable gdt, idt;
      __u64 cr0, cr2, cr3, cr4, cr8;
      __u64 efer;
      __u64 apic_base;
      __u64 interrupt_bitmap[(KVM_NR_INTERRUPTS + 63) / 64];
};

/* ppc -- see arch/powerpc/include/uapi/asm/kvm.h */
```

interrupt_bitmap is a bitmap of pending external interrupts.  At most one bit may be set.  This interrupt has been acknowledged by the APIC but not yet injected into the cpu core.

<a id="rst-kvm-set-sregs"></a>

### 4.14 KVM_SET_SREGS

**Capability:** basic

**Architectures:** x86, ppc

**Type:** vcpu ioctl

**Parameters:** struct kvm_sregs (in)

**Returns:** 0 on success, -1 on error

Writes special registers into the vcpu.  See KVM_GET_SREGS for the data structures.

<a id="rst-kvm-translate"></a>

### 4.15 KVM_TRANSLATE

**Capability:** basic

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_translation (in/out)

**Returns:** 0 on success, -1 on error

Translates a virtual address according to the vcpu's current address translation mode.



```text
struct kvm_translation {
      /* in */
      __u64 linear_address;

      /* out */
      __u64 physical_address;
      __u8  valid;
      __u8  writeable;
      __u8  usermode;
      __u8  pad[5];
};
```

<a id="rst-kvm-interrupt"></a>

### 4.16 KVM_INTERRUPT

**Capability:** basic

**Architectures:** x86, ppc, mips, riscv, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_interrupt (in)

**Returns:** 0 on success, negative on failure.

Queues a hardware interrupt vector to be injected.



```text
/* for KVM_INTERRUPT */
struct kvm_interrupt {
      /* in */
      __u32 irq;
};
```

<a id="rst-x86-1"></a>

#### X86:

**Returns:** 
<table>
<tbody>
<tr>
<td>


0

</td>
<td>


on success,

</td>
</tr>
<tr>
<td>


-EEXIST

</td>
<td>


if an interrupt is already enqueued

</td>
</tr>
<tr>
<td>


-EINVAL

</td>
<td>


the irq number is invalid

</td>
</tr>
<tr>
<td>


-ENXIO

</td>
<td>


if the PIC is in the kernel

</td>
</tr>
<tr>
<td>


-EFAULT

</td>
<td>


if the pointer is invalid

</td>
</tr>
</tbody>
</table>

Note 'irq' is an interrupt vector, not an interrupt pin or line. This ioctl is useful if the in-kernel PIC is not used.

<a id="rst-ppc"></a>

#### PPC:

Queues an external interrupt to be injected. This ioctl is overloaded with 3 different irq values:

- **a)** KVM_INTERRUPT_SET

  This injects an edge type external interrupt into the guest once it's ready to receive interrupts. When injected, the interrupt is done.

- **b)** KVM_INTERRUPT_UNSET

  This unsets any pending interrupt.

  Only available with KVM_CAP_PPC_UNSET_IRQ.

- **c)** KVM_INTERRUPT_SET_LEVEL

  This injects a level type external interrupt into the guest context. The interrupt stays pending until a specific ioctl with KVM_INTERRUPT_UNSET is triggered.

  Only available with KVM_CAP_PPC_IRQ_LEVEL.

Note that any value for 'irq' other than the ones stated above is invalid and incurs unexpected behavior.

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-mips-1"></a>

#### MIPS:

Queues an external interrupt to be injected into the virtual CPU. A negative interrupt number dequeues the interrupt.

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-risc-v"></a>

#### RISC-V:

Queues an external interrupt to be injected into the virtual CPU. This ioctl is overloaded with 2 different irq values:

- **a)** KVM_INTERRUPT_SET

  This sets external interrupt for a virtual CPU and it will receive once it is ready.

- **b)** KVM_INTERRUPT_UNSET

  This clears pending external interrupt for a virtual CPU.

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-loongarch"></a>

#### LOONGARCH:

Queues an external interrupt to be injected into the virtual CPU. A negative interrupt number dequeues the interrupt.

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-kvm-get-msrs"></a>

### 4.18 KVM_GET_MSRS

**Capability:** basic (vcpu), KVM_CAP_GET_MSR_FEATURES (system)

**Architectures:** x86

**Type:** system ioctl, vcpu ioctl

**Parameters:** struct kvm_msrs (in/out)

**Returns:** number of msrs successfully returned; -1 on error

When used as a system ioctl: Reads the values of MSR-based features that are available for the VM.  This is similar to KVM_GET_SUPPORTED_CPUID, but it returns MSR indices and values. The list of msr-based features can be obtained using KVM_GET_MSR_FEATURE_INDEX_LIST in a system ioctl.

When used as a vcpu ioctl: Reads model-specific registers from the vcpu.  Supported msr indices can be obtained using KVM_GET_MSR_INDEX_LIST in a system ioctl.



```text
struct kvm_msrs {
      __u32 nmsrs; /* number of msrs in entries */
      __u32 pad;

      struct kvm_msr_entry entries[0];
};

struct kvm_msr_entry {
      __u32 index;
      __u32 reserved;
      __u64 data;
};
```

Application code should set the 'nmsrs' member (which indicates the size of the entries array) and the 'index' member of each array entry. kvm will fill in the 'data' member.

<a id="rst-kvm-set-msrs"></a>

### 4.19 KVM_SET_MSRS

**Capability:** basic

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_msrs (in)

**Returns:** number of msrs successfully set (see below), -1 on error

Writes model-specific registers to the vcpu.  See KVM_GET_MSRS for the data structures.

Application code should set the 'nmsrs' member (which indicates the size of the entries array), and the 'index' and 'data' members of each array entry.

It tries to set the MSRs in array entries\[\] one by one. If setting an MSR fails, e.g., due to setting reserved bits, the MSR isn't supported/emulated by KVM, etc..., it stops processing the MSR list and returns the number of MSRs that have been set successfully.

<a id="rst-kvm-set-cpuid"></a>

### 4.20 KVM_SET_CPUID

**Capability:** basic

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_cpuid (in)

**Returns:** 0 on success, -1 on error

Defines the vcpu responses to the cpuid instruction.  Applications should use the KVM_SET_CPUID2 ioctl if available.

- **Caveat emptor:**

  - If this IOCTL fails, KVM gives no guarantees that previous valid CPUID configuration (if there is) is not corrupted. Userspace can get a copy of the resulting CPUID configuration through KVM_GET_CPUID2 in case.

  - Using KVM_SET_CPUID\{,2\} after KVM_RUN, i.e. changing the guest vCPU model after running the guest, may cause guest instability.

  - Using heterogeneous CPUID configurations, modulo APIC IDs, topology, etc... may cause guest instability.



```text
struct kvm_cpuid_entry {
      __u32 function;
      __u32 eax;
      __u32 ebx;
      __u32 ecx;
      __u32 edx;
      __u32 padding;
};

/* for KVM_SET_CPUID */
struct kvm_cpuid {
      __u32 nent;
      __u32 padding;
      struct kvm_cpuid_entry entries[0];
};
```

<a id="rst-kvm-set-signal-mask"></a>

### 4.21 KVM_SET_SIGNAL_MASK

**Capability:** basic

**Architectures:** all

**Type:** vcpu ioctl

**Parameters:** struct kvm_signal_mask (in)

**Returns:** 0 on success, -1 on error

Defines which signals are blocked during execution of KVM_RUN.  This signal mask temporarily overrides the threads signal mask.  Any unblocked signal received (except SIGKILL and SIGSTOP, which retain their traditional behaviour) will cause KVM_RUN to return with -EINTR.

Note the signal will only be delivered if not blocked by the original signal mask.



```text
/* for KVM_SET_SIGNAL_MASK */
struct kvm_signal_mask {
      __u32 len;
      __u8  sigset[0];
};
```

<a id="rst-kvm-get-fpu"></a>

### 4.22 KVM_GET_FPU

**Capability:** basic

**Architectures:** x86, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_fpu (out)

**Returns:** 0 on success, -1 on error

Reads the floating point state from the vcpu.



```text
/* x86: for KVM_GET_FPU and KVM_SET_FPU */
struct kvm_fpu {
      __u8  fpr[8][16];
      __u16 fcw;
      __u16 fsw;
      __u8  ftwx;  /* in fxsave format */
      __u8  pad1;
      __u16 last_opcode;
      __u64 last_ip;
      __u64 last_dp;
      __u8  xmm[16][16];
      __u32 mxcsr;
      __u32 pad2;
};

/* LoongArch: for KVM_GET_FPU and KVM_SET_FPU */
struct kvm_fpu {
      __u32 fcsr;
      __u64 fcc;
      struct kvm_fpureg {
              __u64 val64[4];
      }fpr[32];
};
```

<a id="rst-kvm-set-fpu"></a>

### 4.23 KVM_SET_FPU

**Capability:** basic

**Architectures:** x86, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_fpu (in)

**Returns:** 0 on success, -1 on error

Writes the floating point state to the vcpu.



```text
/* x86: for KVM_GET_FPU and KVM_SET_FPU */
struct kvm_fpu {
      __u8  fpr[8][16];
      __u16 fcw;
      __u16 fsw;
      __u8  ftwx;  /* in fxsave format */
      __u8  pad1;
      __u16 last_opcode;
      __u64 last_ip;
      __u64 last_dp;
      __u8  xmm[16][16];
      __u32 mxcsr;
      __u32 pad2;
};

/* LoongArch: for KVM_GET_FPU and KVM_SET_FPU */
struct kvm_fpu {
      __u32 fcsr;
      __u64 fcc;
      struct kvm_fpureg {
              __u64 val64[4];
      }fpr[32];
};
```

<a id="rst-kvm-create-irqchip"></a>

### 4.24 KVM_CREATE_IRQCHIP

**Capability:** KVM_CAP_IRQCHIP, KVM_CAP_S390_IRQCHIP (s390)

**Architectures:** x86, arm64, s390

**Type:** vm ioctl

**Parameters:** none

**Returns:** 0 on success, -1 on error

Creates an interrupt controller model in the kernel. On x86, creates a virtual ioapic, a virtual PIC (two PICs, nested), and sets up future vcpus to have a local APIC.  IRQ routing for GSIs 0-15 is set to both PIC and IOAPIC; GSI 16-23 only go to the IOAPIC. On arm64, a GICv2 is created. Any other GIC versions require the usage of KVM_CREATE_DEVICE, which also supports creating a GICv2.  Using KVM_CREATE_DEVICE is preferred over KVM_CREATE_IRQCHIP for GICv2. On s390, a dummy irq routing table is created.

Note that on s390 the KVM_CAP_S390_IRQCHIP vm capability needs to be enabled before KVM_CREATE_IRQCHIP can be used.

<a id="rst-kvm-irq-line"></a>

### 4.25 KVM_IRQ_LINE

**Capability:** KVM_CAP_IRQCHIP

**Architectures:** x86, arm64

**Type:** vm ioctl

**Parameters:** struct kvm_irq_level

**Returns:** 0 on success, -1 on error

Sets the level of a GSI input to the interrupt controller model in the kernel. On some architectures it is required that an interrupt controller model has been previously created with KVM_CREATE_IRQCHIP.  Note that edge-triggered interrupts require the level to be set to 1 and then back to 0.

On real hardware, interrupt pins can be active-low or active-high.  This does not matter for the level field of struct kvm_irq_level: 1 always means active (asserted), 0 means inactive (deasserted).

x86 allows the operating system to program the interrupt polarity (active-low/active-high) for level-triggered interrupts, and KVM used to consider the polarity.  However, due to bitrot in the handling of active-low interrupts, the above convention is now valid on x86 too. This is signaled by KVM_CAP_X86_IOAPIC_POLARITY_IGNORED.  Userspace should not present interrupts to the guest as active-low unless this capability is present (or unless it is not using the in-kernel irqchip, of course).

arm64 can signal an interrupt either at the CPU level, or at the in-kernel irqchip (GIC), and for in-kernel irqchip can tell the GIC to use PPIs designated for specific cpus.  The irq field is interpreted like this:



```text
bits:  |  31 ... 28  | 27 ... 24 | 23  ... 16 | 15 ... 0 |
field: | vcpu2_index | irq_type  | vcpu_index |  irq_id  |
```

The irq_type field has the following values:

- - **KVM_ARM_IRQ_TYPE_CPU:**

    out-of-kernel GIC: irq_id 0 is IRQ, irq_id 1 is FIQ

- - **KVM_ARM_IRQ_TYPE_SPI:**

    in-kernel GIC: SPI, irq_id between 32 and 1019 (incl.) (the vcpu_index field is ignored)

- - **KVM_ARM_IRQ_TYPE_PPI:**

    in-kernel GIC: PPI, irq_id between 16 and 31 (incl.)

(The irq_id field thus corresponds nicely to the IRQ ID in the ARM GIC specs)

In both cases, level is used to assert/deassert the line.

When KVM_CAP_ARM_IRQ_LINE_LAYOUT_2 is supported, the target vcpu is identified as (256 \* vcpu2_index + vcpu_index). Otherwise, vcpu2_index must be zero.

Note that on arm64, the KVM_CAP_IRQCHIP capability only conditions injection of interrupts for the in-kernel irqchip. KVM_IRQ_LINE can always be used for a userspace interrupt controller.



```text
struct kvm_irq_level {
      union {
              __u32 irq;     /* GSI */
              __s32 status;  /* not used for KVM_IRQ_LEVEL */
      };
      __u32 level;           /* 0 or 1 */
};
```

<a id="rst-kvm-get-irqchip"></a>

### 4.26 KVM_GET_IRQCHIP

**Capability:** KVM_CAP_IRQCHIP

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_irqchip (in/out)

**Returns:** 0 on success, -1 on error

Reads the state of a kernel interrupt controller created with KVM_CREATE_IRQCHIP into a buffer provided by the caller.



```text
struct kvm_irqchip {
      __u32 chip_id;  /* 0 = PIC1, 1 = PIC2, 2 = IOAPIC */
      __u32 pad;
      union {
              char dummy[512];  /* reserving space */
              struct kvm_pic_state pic;
              struct kvm_ioapic_state ioapic;
      } chip;
};
```

<a id="rst-kvm-set-irqchip"></a>

### 4.27 KVM_SET_IRQCHIP

**Capability:** KVM_CAP_IRQCHIP

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_irqchip (in)

**Returns:** 0 on success, -1 on error

Sets the state of a kernel interrupt controller created with KVM_CREATE_IRQCHIP from a buffer provided by the caller.



```text
struct kvm_irqchip {
      __u32 chip_id;  /* 0 = PIC1, 1 = PIC2, 2 = IOAPIC */
      __u32 pad;
      union {
              char dummy[512];  /* reserving space */
              struct kvm_pic_state pic;
              struct kvm_ioapic_state ioapic;
      } chip;
};
```

<a id="rst-kvm-xen-hvm-config"></a>

### 4.28 KVM_XEN_HVM_CONFIG

**Capability:** KVM_CAP_XEN_HVM

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_xen_hvm_config (in)

**Returns:** 0 on success, -1 on error

Sets the MSR that the Xen HVM guest uses to initialize its hypercall page, and provides the starting address and size of the hypercall blobs in userspace.  When the guest writes the MSR, kvm copies one page of a blob (32- or 64-bit, depending on the vcpu mode) to guest memory.

The MSR index must be in the range \[0x40000000, 0x4fffffff\], i.e. must reside in the range that is unofficially reserved for use by hypervisors.  The min/max values are enumerated via KVM_XEN_MSR_MIN_INDEX and KVM_XEN_MSR_MAX_INDEX.



```text
struct kvm_xen_hvm_config {
      __u32 flags;
      __u32 msr;
      __u64 blob_addr_32;
      __u64 blob_addr_64;
      __u8 blob_size_32;
      __u8 blob_size_64;
      __u8 pad2[30];
};
```

If certain flags are returned from the KVM_CAP_XEN_HVM check, they may be set in the flags field of this ioctl:

The KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL flag requests KVM to generate the contents of the hypercall page automatically; hypercalls will be intercepted and passed to userspace through KVM_EXIT_XEN.  In this case, all of the blob size and address fields must be zero.

The KVM_XEN_HVM_CONFIG_EVTCHN_SEND flag indicates to KVM that userspace will always use the KVM_XEN_HVM_EVTCHN_SEND ioctl to deliver event channel interrupts rather than manipulating the guest's shared_info structures directly. This, in turn, may allow KVM to enable features such as intercepting the SCHEDOP_poll hypercall to accelerate PV spinlock operation for the guest. Userspace may still use the ioctl to deliver events if it was advertised, even if userspace does not send this indication that it will always do so

No other flags are currently valid in the struct kvm_xen_hvm_config.

<a id="rst-kvm-get-clock"></a>

### 4.29 KVM_GET_CLOCK

**Capability:** KVM_CAP_ADJUST_CLOCK

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_clock_data (out)

**Returns:** 0 on success, -1 on error

Gets the current timestamp of kvmclock as seen by the current guest. In conjunction with KVM_SET_CLOCK, it is used to ensure monotonicity on scenarios such as migration.

When KVM_CAP_ADJUST_CLOCK is passed to KVM_CHECK_EXTENSION, it returns the set of bits that KVM can return in struct kvm_clock_data's flag member.

The following flags are defined:

- **KVM_CLOCK_TSC_STABLE**

  If set, the returned value is the exact kvmclock value seen by all VCPUs at the instant when KVM_GET_CLOCK was called. If clear, the returned value is simply CLOCK_MONOTONIC plus a constant offset; the offset can be modified with KVM_SET_CLOCK.  KVM will try to make all VCPUs follow this clock, but the exact value read by each VCPU could differ, because the host TSC is not stable.

- **KVM_CLOCK_REALTIME**

  If set, the `realtime` field in the kvm_clock_data structure is populated with the value of the host's real time clocksource at the instant when KVM_GET_CLOCK was called. If clear, the `realtime` field does not contain a value.

- **KVM_CLOCK_HOST_TSC**

  If set, the `host_tsc` field in the kvm_clock_data structure is populated with the value of the host's timestamp counter (TSC) at the instant when KVM_GET_CLOCK was called. If clear, the `host_tsc` field does not contain a value.



```text
struct kvm_clock_data {
      __u64 clock;  /* kvmclock current value */
      __u32 flags;
      __u32 pad0;
      __u64 realtime;
      __u64 host_tsc;
      __u32 pad[4];
};
```

<a id="rst-kvm-set-clock"></a>

### 4.30 KVM_SET_CLOCK

**Capability:** KVM_CAP_ADJUST_CLOCK

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_clock_data (in)

**Returns:** 0 on success, -1 on error

Sets the current timestamp of kvmclock to the value specified in its parameter. In conjunction with KVM_GET_CLOCK, it is used to ensure monotonicity on scenarios such as migration.

The following flags can be passed:

- **KVM_CLOCK_REALTIME**

  If set, KVM will compare the value of the `realtime` field with the value of the host's real time clocksource at the instant when KVM_SET_CLOCK was called. The difference in elapsed time is added to the final kvmclock value that will be provided to guests.

Other flags returned by `KVM_GET_CLOCK` are accepted but ignored.



```text
struct kvm_clock_data {
      __u64 clock;  /* kvmclock current value */
      __u32 flags;
      __u32 pad0;
      __u64 realtime;
      __u64 host_tsc;
      __u32 pad[4];
};
```

<a id="rst-kvm-get-vcpu-events"></a>

### 4.31 KVM_GET_VCPU_EVENTS

**Capability:** KVM_CAP_VCPU_EVENTS

**Extended by:** KVM_CAP_INTR_SHADOW

**Architectures:** x86, arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_vcpu_events (out)

**Returns:** 0 on success, -1 on error

<a id="rst-x86-2"></a>

#### X86:

Gets currently pending exceptions, interrupts, and NMIs as well as related states of the vcpu.



```text
struct kvm_vcpu_events {
      struct {
              __u8 injected;
              __u8 nr;
              __u8 has_error_code;
              __u8 pending;
              __u32 error_code;
      } exception;
      struct {
              __u8 injected;
              __u8 nr;
              __u8 soft;
              __u8 shadow;
      } interrupt;
      struct {
              __u8 injected;
              __u8 pending;
              __u8 masked;
              __u8 pad;
      } nmi;
      __u32 sipi_vector;
      __u32 flags;
      struct {
              __u8 smm;
              __u8 pending;
              __u8 smm_inside_nmi;
              __u8 latched_init;
      } smi;
      __u8 reserved[27];
      __u8 exception_has_payload;
      __u64 exception_payload;
};
```

The following bits are defined in the flags field:

- KVM_VCPUEVENT_VALID_SHADOW may be set to signal that interrupt.shadow contains a valid state.

- KVM_VCPUEVENT_VALID_SMM may be set to signal that smi contains a valid state.

- KVM_VCPUEVENT_VALID_PAYLOAD may be set to signal that the exception_has_payload, exception_payload, and exception.pending fields contain a valid state. This bit will be set whenever KVM_CAP_EXCEPTION_PAYLOAD is enabled.

- KVM_VCPUEVENT_VALID_TRIPLE_FAULT may be set to signal that the triple_fault_pending field contains a valid state. This bit will be set whenever KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled.

<a id="rst-arm64-1"></a>

#### ARM64:

If the guest accesses a device that is being emulated by the host kernel in such a way that a real device would generate a physical SError, KVM may make a virtual SError pending for that VCPU. This system error interrupt remains pending until the guest takes the exception by unmasking PSTATE.A.

Running the VCPU may cause it to take a pending SError, or make an access that causes an SError to become pending. The event's description is only valid while the VPCU is not running.

This API provides a way to read and write the pending 'event' state that is not visible to the guest. To save, restore or migrate a VCPU the struct representing the state can be read then written using this GET/SET API, along with the other guest-visible registers. It is not possible to 'cancel' an SError that has been made pending.

A device being emulated in user-space may also wish to generate an SError. To do this the events structure can be populated by user-space. The current state should be read first, to ensure no existing SError is pending. If an existing SError is pending, the architecture's 'Multiple SError interrupts' rules should be followed. (2.5.3 of DDI0587.a "ARM Reliability, Availability, and Serviceability (RAS) Specification").

SError exceptions always have an ESR value. Some CPUs have the ability to specify what the virtual SError's ESR value should be. These systems will advertise KVM_CAP_ARM_INJECT_SERROR_ESR. In this case exception.has_esr will always have a non-zero value when read, and the agent making an SError pending should specify the ISS field in the lower 24 bits of exception.serror_esr. If the system supports KVM_CAP_ARM_INJECT_SERROR_ESR, but user-space sets the events with exception.has_esr as zero, KVM will choose an ESR.

Specifying exception.has_esr on a system that does not support it will return -EINVAL. Setting anything other than the lower 24bits of exception.serror_esr will return -EINVAL.

It is not possible to read back a pending external abort (injected via KVM_SET_VCPU_EVENTS or otherwise) because such an exception is always delivered directly to the virtual CPU).

Calling this ioctl on a vCPU that hasn't been initialized will return -ENOEXEC.



```text
struct kvm_vcpu_events {
      struct {
              __u8 serror_pending;
              __u8 serror_has_esr;
              __u8 ext_dabt_pending;
              /* Align it to 8 bytes */
              __u8 pad[5];
              __u64 serror_esr;
      } exception;
      __u32 reserved[12];
};
```

<a id="rst-kvm-set-vcpu-events"></a>

### 4.32 KVM_SET_VCPU_EVENTS

**Capability:** KVM_CAP_VCPU_EVENTS

**Extended by:** KVM_CAP_INTR_SHADOW

**Architectures:** x86, arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_vcpu_events (in)

**Returns:** 0 on success, -1 on error

<a id="rst-x86-3"></a>

#### X86:

Set pending exceptions, interrupts, and NMIs as well as related states of the vcpu.

See KVM_GET_VCPU_EVENTS for the data structure.

Fields that may be modified asynchronously by running VCPUs can be excluded from the update. These fields are nmi.pending, sipi_vector, smi.smm, smi.pending. Keep the corresponding bits in the flags field cleared to suppress overwriting the current in-kernel state. The bits are:


<table>
<tbody>
<tr>
<td>


KVM_VCPUEVENT_VALID_NMI_PENDING

</td>
<td>


transfer nmi.pending to the kernel

</td>
</tr>
<tr>
<td>


KVM_VCPUEVENT_VALID_SIPI_VECTOR

</td>
<td>


transfer sipi_vector

</td>
</tr>
<tr>
<td>


KVM_VCPUEVENT_VALID_SMM

</td>
<td>


transfer the smi sub-struct.

</td>
</tr>
</tbody>
</table>

If KVM_CAP_INTR_SHADOW is available, KVM_VCPUEVENT_VALID_SHADOW can be set in the flags field to signal that interrupt.shadow contains a valid state and shall be written into the VCPU.

KVM_VCPUEVENT_VALID_SMM can only be set if KVM_CAP_X86_SMM is available.

If KVM_CAP_EXCEPTION_PAYLOAD is enabled, KVM_VCPUEVENT_VALID_PAYLOAD can be set in the flags field to signal that the exception_has_payload, exception_payload, and exception.pending fields contain a valid state and shall be written into the VCPU.

If KVM_CAP_X86_TRIPLE_FAULT_EVENT is enabled, KVM_VCPUEVENT_VALID_TRIPLE_FAULT can be set in flags field to signal that the triple_fault field contains a valid state and shall be written into the VCPU.

<a id="rst-arm64-2"></a>

#### ARM64:

User space may need to inject several types of events to the guest.

Set the pending SError exception state for this VCPU. It is not possible to 'cancel' an Serror that has been made pending.

If the guest performed an access to I/O memory which could not be handled by userspace, for example because of missing instruction syndrome decode information or because there is no device mapped at the accessed IPA, then userspace can ask the kernel to inject an external abort using the address from the exiting fault on the VCPU. It is a programming error to set ext_dabt_pending after an exit which was not either KVM_EXIT_MMIO, KVM_EXIT_ARM_NISV, or KVM_EXIT_ARM_LDST64B. This feature is only available if the system supports KVM_CAP_ARM_INJECT_EXT_DABT. This is a helper which provides commonality in how userspace reports accesses for the above cases to guests, across different userspace implementations. Nevertheless, userspace can still emulate all Arm exceptions by manipulating individual registers using the KVM_SET_ONE_REG API.

See KVM_GET_VCPU_EVENTS for the data structure.

Calling this ioctl on a vCPU that hasn't been initialized will return -ENOEXEC.

<a id="rst-kvm-get-debugregs"></a>

### 4.33 KVM_GET_DEBUGREGS

**Capability:** KVM_CAP_DEBUGREGS

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_debugregs (out)

**Returns:** 0 on success, -1 on error

Reads debug registers from the vcpu.



```text
struct kvm_debugregs {
      __u64 db[4];
      __u64 dr6;
      __u64 dr7;
      __u64 flags;
      __u64 reserved[9];
};
```

<a id="rst-kvm-set-debugregs"></a>

### 4.34 KVM_SET_DEBUGREGS

**Capability:** KVM_CAP_DEBUGREGS

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_debugregs (in)

**Returns:** 0 on success, -1 on error

Writes debug registers into the vcpu.

See KVM_GET_DEBUGREGS for the data structure. The flags field is unused yet and must be cleared on entry.

<a id="rst-kvm-set-user-memory-region"></a>

### 4.35 KVM_SET_USER_MEMORY_REGION

**Capability:** KVM_CAP_USER_MEMORY

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_userspace_memory_region (in)

**Returns:** 0 on success, -1 on error



```text
struct kvm_userspace_memory_region {
      __u32 slot;
      __u32 flags;
      __u64 guest_phys_addr;
      __u64 memory_size; /* bytes */
      __u64 userspace_addr; /* start of the userspace allocated memory */
};

/* for kvm_userspace_memory_region::flags */
#define KVM_MEM_LOG_DIRTY_PAGES       (1UL << 0)
#define KVM_MEM_READONLY      (1UL << 1)
```

This ioctl allows the user to create, modify or delete a guest physical memory slot.  Bits 0-15 of "slot" specify the slot id and this value should be less than the maximum number of user memory slots supported per VM.  The maximum allowed slots can be queried using KVM_CAP_NR_MEMSLOTS. Slots may not overlap in guest physical address space.

If KVM_CAP_MULTI_ADDRESS_SPACE is available, bits 16-31 of "slot" specifies the address space which is being modified.  They must be less than the value that KVM_CHECK_EXTENSION returns for the KVM_CAP_MULTI_ADDRESS_SPACE capability.  Slots in separate address spaces are unrelated; the restriction on overlapping slots only applies within each address space.

Deleting a slot is done by passing zero for memory_size.  When changing an existing slot, it may be moved in the guest physical memory space, or its flags may be modified, but it may not be resized.

Memory for the region is taken starting at the address denoted by the field userspace_addr, which must point at user addressable memory for the entire memory slot size.  Any object may back this memory, including anonymous memory, ordinary files, and hugetlbfs.  Changes in the backing of the memory region are automatically reflected into the guest. For example, an mmap() that affects the region will be made visible immediately.  Another example is madvise(MADV_DROP).

On architectures that support a form of address tagging, userspace_addr must be an untagged address.

It is recommended that the lower 21 bits of guest_phys_addr and userspace_addr be identical.  This allows large pages in the guest to be backed by large pages in the host.

The flags field supports two flags: KVM_MEM_LOG_DIRTY_PAGES and KVM_MEM_READONLY.  The former can be set to instruct KVM to keep track of writes to memory within the slot.  See KVM_GET_DIRTY_LOG ioctl to know how to use it.  The latter can be set, if KVM_CAP_READONLY_MEM capability allows it, to make a new slot read-only.  In this case, writes to this memory will be posted to userspace as KVM_EXIT_MMIO exits.

For TDX guest, deleting/moving memory region loses guest memory contents. Read only region isn't supported.  Only as-id 0 is supported.

Note: On arm64, a write generated by the page-table walker (to update the Access and Dirty flags, for example) never results in a KVM_EXIT_MMIO exit when the slot has the KVM_MEM_READONLY flag. This is because KVM cannot provide the data that would be written by the page-table walker, making it impossible to emulate the access. Instead, an abort (data abort if the cause of the page-table update was a load or a store, instruction abort if it was an instruction fetch) is injected in the guest.

<a id="rst-s390-1"></a>

#### S390:

Returns -EINVAL or -EEXIST if the VM has the KVM_VM_S390_UCONTROL flag set. Returns -EINVAL if called on a protected VM.

<a id="rst-kvm-set-tss-addr"></a>

### 4.36 KVM_SET_TSS_ADDR

**Capability:** KVM_CAP_SET_TSS_ADDR

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** unsigned long tss_address (in)

**Returns:** 0 on success, -1 on error

This ioctl defines the physical address of a three-page region in the guest physical address space.  The region must be within the first 4GB of the guest physical address space and must not conflict with any memory slot or any mmio address.  The guest may malfunction if it accesses this memory region.

This ioctl is required on Intel-based hosts.  This is needed on Intel hardware because of a quirk in the virtualization implementation (see the internals documentation when it pops into existence).

<a id="rst-kvm-enable-cap-1"></a>
<a id="rst-kvm-enable-cap"></a>

### 4.37 KVM_ENABLE_CAP

**Capability:** KVM_CAP_ENABLE_CAP

**Architectures:** mips, ppc, s390, x86, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_enable_cap (in)

**Returns:** 0 on success; -1 on error

**Capability:** KVM_CAP_ENABLE_CAP_VM

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_enable_cap (in)

**Returns:** 0 on success; -1 on error

> [!NOTE]
>
> Not all extensions are enabled by default. Using this ioctl the application can enable an extension, making it available to the guest.

On systems that do not support this ioctl, it always fails. On systems that do support it, it only works for extensions that are supported for enablement.

To check if a capability can be enabled, the KVM_CHECK_EXTENSION ioctl should be used.



```text
struct kvm_enable_cap {
     /* in */
     __u32 cap;
```

The capability that is supposed to get enabled.



```text
__u32 flags;
```

A bitfield indicating future enhancements. Has to be 0 for now.



```text
__u64 args[4];
```

Arguments for enabling a feature. If a feature needs initial values to function properly, this is the place to put them.



```text
     __u8  pad[64];
};
```

The vcpu ioctl should be used for vcpu-specific capabilities, the vm ioctl for vm-wide capabilities.

<a id="rst-kvm-get-mp-state"></a>

### 4.38 KVM_GET_MP_STATE

**Capability:** KVM_CAP_MP_STATE

**Architectures:** x86, s390, arm64, riscv, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_mp_state (out)

**Returns:** 0 on success; -1 on error



```text
struct kvm_mp_state {
      __u32 mp_state;
};
```

Returns the vcpu's current "multiprocessing state" (though also valid on uniprocessor guests).

Possible values are:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> KVM_MP_STATE_RUNNABLE
>
> </td>
> <td>
>
>
> the vcpu is currently running \[x86,arm64,riscv,loongarch\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_UNINITIALIZED
>
> </td>
> <td>
>
>
> the vcpu is an application processor (AP) which has not yet received an INIT signal \[x86\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_INIT_RECEIVED
>
> </td>
> <td>
>
>
> the vcpu has received an INIT signal, and is now ready for a SIPI \[x86\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_HALTED
>
> </td>
> <td>
>
>
> the vcpu has executed a HLT instruction and is waiting for an interrupt \[x86\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_SIPI_RECEIVED
>
> </td>
> <td>
>
>
> the vcpu has just received a SIPI (vector accessible via KVM_GET_VCPU_EVENTS) \[x86\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_STOPPED
>
> </td>
> <td>
>
>
> the vcpu is stopped \[s390,arm64,riscv\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_CHECK_STOP
>
> </td>
> <td>
>
>
> the vcpu is in a special error state \[s390\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_OPERATING
>
> </td>
> <td>
>
>
> the vcpu is operating (running or halted) \[s390\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_LOAD
>
> </td>
> <td>
>
>
> the vcpu is in a special load/startup state \[s390\]
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MP_STATE_SUSPENDED
>
> </td>
> <td>
>
>
> the vcpu is in a suspend state and is waiting for a wakeup event \[arm64\]
>
> </td>
> </tr>
> </tbody>
> </table>

On x86, this ioctl is only useful after KVM_CREATE_IRQCHIP. Without an in-kernel irqchip, the multiprocessing state must be maintained by userspace on these architectures.

<a id="rst-for-arm64"></a>

#### For arm64:

If a vCPU is in the KVM_MP_STATE_SUSPENDED state, KVM will emulate the architectural execution of a WFI instruction.

If a wakeup event is recognized, KVM will exit to userspace with a KVM_SYSTEM_EVENT exit, where the event type is KVM_SYSTEM_EVENT_WAKEUP. If userspace wants to honor the wakeup, it must set the vCPU's MP state to KVM_MP_STATE_RUNNABLE. If it does not, KVM will continue to await a wakeup event in subsequent calls to KVM_RUN.

> [!WARNING]
>
> If userspace intends to keep the vCPU in a SUSPENDED state, it is strongly recommended that userspace take action to suppress the wakeup event (such as masking an interrupt). Otherwise, subsequent calls to KVM_RUN will immediately exit with a KVM_SYSTEM_EVENT_WAKEUP event and inadvertently waste CPU cycles.
>
> Additionally, if userspace takes action to suppress a wakeup event, it is strongly recommended that it also restores the vCPU to its original state when the vCPU is made RUNNABLE again. For example, if userspace masked a pending interrupt to suppress the wakeup, the interrupt should be unmasked before returning control to the guest.

<a id="rst-for-riscv"></a>

#### For riscv:

The only states that are valid are KVM_MP_STATE_STOPPED and KVM_MP_STATE_RUNNABLE which reflect if the vcpu is paused or not.

On LoongArch, only the KVM_MP_STATE_RUNNABLE state is used to reflect whether the vcpu is runnable.

<a id="rst-kvm-set-mp-state"></a>

### 4.39 KVM_SET_MP_STATE

**Capability:** KVM_CAP_MP_STATE

**Architectures:** x86, s390, arm64, riscv, loongarch

**Type:** vcpu ioctl

**Parameters:** struct kvm_mp_state (in)

**Returns:** 0 on success; -1 on error

Sets the vcpu's current "multiprocessing state"; see KVM_GET_MP_STATE for arguments.

On x86, this ioctl is only useful after KVM_CREATE_IRQCHIP. Without an in-kernel irqchip, the multiprocessing state must be maintained by userspace on these architectures.

<a id="rst-for-arm64-riscv"></a>

#### For arm64/riscv:

The only states that are valid are KVM_MP_STATE_STOPPED and KVM_MP_STATE_RUNNABLE which reflect if the vcpu should be paused or not.

On LoongArch, only the KVM_MP_STATE_RUNNABLE state is used to reflect whether the vcpu is runnable.

<a id="rst-kvm-set-identity-map-addr"></a>

### 4.40 KVM_SET_IDENTITY_MAP_ADDR

**Capability:** KVM_CAP_SET_IDENTITY_MAP_ADDR

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** unsigned long identity (in)

**Returns:** 0 on success, -1 on error

This ioctl defines the physical address of a one-page region in the guest physical address space.  The region must be within the first 4GB of the guest physical address space and must not conflict with any memory slot or any mmio address.  The guest may malfunction if it accesses this memory region.

Setting the address to 0 will result in resetting the address to its default (0xfffbc000).

This ioctl is required on Intel-based hosts.  This is needed on Intel hardware because of a quirk in the virtualization implementation (see the internals documentation when it pops into existence).

Fails if any VCPU has already been created.

<a id="rst-kvm-set-boot-cpu-id"></a>

### 4.41 KVM_SET_BOOT_CPU_ID

**Capability:** KVM_CAP_SET_BOOT_CPU_ID

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** unsigned long vcpu_id

**Returns:** 0 on success, -1 on error

Define which vcpu is the Bootstrap Processor (BSP).  Values are the same as the vcpu id in KVM_CREATE_VCPU.  If this ioctl is not called, the default is vcpu 0. This ioctl has to be called before vcpu creation, otherwise it will return EBUSY error.

<a id="rst-kvm-get-xsave"></a>

### 4.42 KVM_GET_XSAVE

**Capability:** KVM_CAP_XSAVE

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xsave (out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_xsave {
      __u32 region[1024];
      __u32 extra[0];
};
```

This ioctl would copy current vcpu's xsave struct to the userspace.

<a id="rst-kvm-set-xsave"></a>

### 4.43 KVM_SET_XSAVE

**Capability:** KVM_CAP_XSAVE and KVM_CAP_XSAVE2

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xsave (in)

**Returns:** 0 on success, -1 on error



```text
struct kvm_xsave {
      __u32 region[1024];
      __u32 extra[0];
};
```

This ioctl would copy userspace's xsave struct to the kernel. It copies as many bytes as are returned by KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2), when invoked on the vm file descriptor. The size value returned by KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) will always be at least 4096. Currently, it is only greater than 4096 if a dynamic feature has been enabled with `arch_prctl()`, but this may change in the future.

The offsets of the state save areas in struct kvm_xsave follow the contents of CPUID leaf 0xD on the host.

<a id="rst-kvm-get-xcrs"></a>

### 4.44 KVM_GET_XCRS

**Capability:** KVM_CAP_XCRS

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xcrs (out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_xcr {
      __u32 xcr;
      __u32 reserved;
      __u64 value;
};

struct kvm_xcrs {
      __u32 nr_xcrs;
      __u32 flags;
      struct kvm_xcr xcrs[KVM_MAX_XCRS];
      __u64 padding[16];
};
```

This ioctl would copy current vcpu's xcrs to the userspace.

<a id="rst-kvm-set-xcrs"></a>

### 4.45 KVM_SET_XCRS

**Capability:** KVM_CAP_XCRS

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xcrs (in)

**Returns:** 0 on success, -1 on error



```text
struct kvm_xcr {
      __u32 xcr;
      __u32 reserved;
      __u64 value;
};

struct kvm_xcrs {
      __u32 nr_xcrs;
      __u32 flags;
      struct kvm_xcr xcrs[KVM_MAX_XCRS];
      __u64 padding[16];
};
```

This ioctl would set vcpu's xcr to the value userspace specified.

<a id="rst-kvm-get-supported-cpuid"></a>

### 4.46 KVM_GET_SUPPORTED_CPUID

**Capability:** KVM_CAP_EXT_CPUID

**Architectures:** x86

**Type:** system ioctl

**Parameters:** struct kvm_cpuid2 (in/out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_cpuid2 {
      __u32 nent;
      __u32 padding;
      struct kvm_cpuid_entry2 entries[0];
};

#define KVM_CPUID_FLAG_SIGNIFCANT_INDEX               BIT(0)
#define KVM_CPUID_FLAG_STATEFUL_FUNC          BIT(1) /* deprecated */
#define KVM_CPUID_FLAG_STATE_READ_NEXT                BIT(2) /* deprecated */

struct kvm_cpuid_entry2 {
      __u32 function;
      __u32 index;
      __u32 flags;
      __u32 eax;
      __u32 ebx;
      __u32 ecx;
      __u32 edx;
      __u32 padding[3];
};
```

This ioctl returns x86 cpuid features which are supported by both the hardware and kvm in its default configuration.  Userspace can use the information returned by this ioctl to construct cpuid information (for KVM_SET_CPUID2) that is consistent with hardware, kernel, and userspace capabilities, and with user requirements (for example, the user may wish to constrain cpuid to emulate older hardware, or for feature consistency across a cluster).

Dynamically-enabled feature bits need to be requested with `arch_prctl()` before calling this ioctl. Feature bits that have not been requested are excluded from the result.

Note that certain capabilities, such as KVM_CAP_X86_DISABLE_EXITS, may expose cpuid features (e.g. MONITOR) which are not supported by kvm in its default configuration. If userspace enables such capabilities, it is responsible for modifying the results of this ioctl appropriately.

Userspace invokes KVM_GET_SUPPORTED_CPUID by passing a kvm_cpuid2 structure with the 'nent' field indicating the number of entries in the variable-size array 'entries'.  If the number of entries is too low to describe the cpu capabilities, an error (E2BIG) is returned.  If the number is too high, the 'nent' field is adjusted and an error (ENOMEM) is returned.  If the number is just right, the 'nent' field is adjusted to the number of valid entries in the 'entries' array, which is then filled.

The entries returned are the host cpuid as returned by the cpuid instruction, with unknown or unsupported features masked out.  Some features (for example, x2apic), may not be present in the host cpu, but are exposed by kvm if it can emulate them efficiently. The fields in each entry are defined as follows:

> - **function:**
>
>   the eax value used to obtain the entry
>
> - **index:**
>
>   the ecx value used to obtain the entry (for entries that are affected by ecx)
>
> - **flags:**
>
>   > an OR of zero or more of the following:
>   >
>   > > - **KVM_CPUID_FLAG_SIGNIFCANT_INDEX:**
>   > >
>   > >   if the index field is valid
>
>   - **eax, ebx, ecx, edx:**
>
>     the values returned by the cpuid instruction for this function/index combination

x2APIC (CPUID leaf 1, ecx\[21) and TSC deadline timer (CPUID leaf 1, ecx\[24\]) may be returned as true, but they depend on KVM_CREATE_IRQCHIP for in-kernel emulation of the local APIC.  TSC deadline timer support is also reported via:



```text
ioctl(KVM_CHECK_EXTENSION, KVM_CAP_TSC_DEADLINE_TIMER)
```

if that returns true and you use KVM_CREATE_IRQCHIP, or if you emulate the feature in userspace, then you can enable the feature for KVM_SET_CPUID2.

Enabling x2APIC in KVM_SET_CPUID2 requires KVM_CREATE_IRQCHIP as KVM doesn't support forwarding x2APIC MSR accesses to userspace, i.e. KVM does not support emulating x2APIC in userspace.

<a id="rst-kvm-ppc-get-pvinfo"></a>

### 4.47 KVM_PPC_GET_PVINFO

**Capability:** KVM_CAP_PPC_GET_PVINFO

**Architectures:** ppc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_pvinfo (out)

**Returns:** 0 on success, \!0 on error



```text
struct kvm_ppc_pvinfo {
      __u32 flags;
      __u32 hcall[4];
      __u8  pad[108];
};
```

This ioctl fetches PV specific information that need to be passed to the guest using the device tree or other means from vm context.

The hcall array defines 4 instructions that make up a hypercall.

If any additional field gets added to this structure later on, a bit for that additional piece of information will be set in the flags bitmap.

The flags bitmap is defined as:



```text
/* the host supports the ePAPR idle hcall
#define KVM_PPC_PVINFO_FLAGS_EV_IDLE   (1<<0)
```

<a id="rst-kvm-set-gsi-routing"></a>

### 4.52 KVM_SET_GSI_ROUTING

**Capability:** KVM_CAP_IRQ_ROUTING

**Architectures:** x86 s390 arm64

**Type:** vm ioctl

**Parameters:** struct kvm_irq_routing (in)

**Returns:** 0 on success, -1 on error

Sets the GSI routing table entries, overwriting any previously set entries.

On arm64, GSI routing has the following limitation:

- GSI routing does not apply to KVM_IRQ_LINE but only to KVM_IRQFD.



```text
struct kvm_irq_routing {
      __u32 nr;
      __u32 flags;
      struct kvm_irq_routing_entry entries[0];
};
```

No flags are specified so far, the corresponding field must be set to zero.



```text
struct kvm_irq_routing_entry {
      __u32 gsi;
      __u32 type;
      __u32 flags;
      __u32 pad;
      union {
              struct kvm_irq_routing_irqchip irqchip;
              struct kvm_irq_routing_msi msi;
              struct kvm_irq_routing_s390_adapter adapter;
              struct kvm_irq_routing_hv_sint hv_sint;
              struct kvm_irq_routing_xen_evtchn xen_evtchn;
              __u32 pad[8];
      } u;
};

/* gsi routing entry types */
#define KVM_IRQ_ROUTING_IRQCHIP 1
#define KVM_IRQ_ROUTING_MSI 2
#define KVM_IRQ_ROUTING_S390_ADAPTER 3
#define KVM_IRQ_ROUTING_HV_SINT 4
#define KVM_IRQ_ROUTING_XEN_EVTCHN 5
```

On s390, adding a KVM_IRQ_ROUTING_S390_ADAPTER is rejected on ucontrol VMs with error -EINVAL.

flags:

- KVM_MSI_VALID_DEVID: used along with KVM_IRQ_ROUTING_MSI routing entry type, specifies that the devid field contains a valid value.  The per-VM KVM_CAP_MSI_DEVID capability advertises the requirement to provide the device ID.  If this capability is not available, userspace should never set the KVM_MSI_VALID_DEVID flag as the ioctl might fail.

- zero otherwise



```text
struct kvm_irq_routing_irqchip {
      __u32 irqchip;
      __u32 pin;
};

struct kvm_irq_routing_msi {
      __u32 address_lo;
      __u32 address_hi;
      __u32 data;
      union {
              __u32 pad;
              __u32 devid;
      };
};
```

If KVM_MSI_VALID_DEVID is set, devid contains a unique device identifier for the device that wrote the MSI message.  For PCI, this is usually a BDF identifier in the lower 16 bits.

On x86, address_hi is ignored unless the KVM_X2APIC_API_USE_32BIT_IDS feature of KVM_CAP_X2APIC_API capability is enabled.  If it is enabled, address_hi bits 31-8 provide bits 31-8 of the destination id.  Bits 7-0 of address_hi must be zero.



```text
struct kvm_irq_routing_s390_adapter {
      __u64 ind_addr;
      __u64 summary_addr;
      __u64 ind_offset;
      __u32 summary_offset;
      __u32 adapter_id;
};

struct kvm_irq_routing_hv_sint {
      __u32 vcpu;
      __u32 sint;
};

struct kvm_irq_routing_xen_evtchn {
      __u32 port;
      __u32 vcpu;
      __u32 priority;
};
```

When KVM_CAP_XEN_HVM includes the KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL bit in its indication of supported features, routing to Xen event channels is supported. Although the priority field is present, only the value KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL is supported, which means delivery by 2 level event channels. FIFO event channel support may be added in the future.

<a id="rst-kvm-set-tsc-khz"></a>

### 4.55 KVM_SET_TSC_KHZ

**Capability:** KVM_CAP_TSC_CONTROL / KVM_CAP_VM_TSC_CONTROL

**Architectures:** x86

**Type:** vcpu ioctl / vm ioctl

**Parameters:** virtual tsc_khz

**Returns:** 0 on success, -1 on error

Specifies the tsc frequency for the virtual machine. The unit of the frequency is KHz.

If the KVM_CAP_VM_TSC_CONTROL capability is advertised, this can also be used as a vm ioctl to set the initial tsc frequency of subsequently created vCPUs.  Note, the vm ioctl is only allowed prior to creating vCPUs.

For TSC protected Confidential Computing (CoCo) VMs where TSC frequency is configured once at VM scope and remains unchanged during VM's lifetime, the vm ioctl should be used to configure the TSC frequency and the vcpu ioctl is not supported.

Example of such CoCo VMs: TDX guests.

<a id="rst-kvm-get-tsc-khz"></a>

### 4.56 KVM_GET_TSC_KHZ

**Capability:** KVM_CAP_GET_TSC_KHZ / KVM_CAP_VM_TSC_CONTROL

**Architectures:** x86

**Type:** vcpu ioctl / vm ioctl

**Parameters:** none

**Returns:** virtual tsc-khz on success, negative value on error

Returns the tsc frequency of the guest. The unit of the return value is KHz. If the host has unstable tsc this ioctl returns -EIO instead as an error.

<a id="rst-kvm-get-lapic"></a>

### 4.57 KVM_GET_LAPIC

**Capability:** KVM_CAP_IRQCHIP

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_lapic_state (out)

**Returns:** 0 on success, -1 on error



```text
#define KVM_APIC_REG_SIZE 0x400
struct kvm_lapic_state {
      char regs[KVM_APIC_REG_SIZE];
};
```

Reads the Local APIC registers and copies them into the input argument.  The data format and layout are the same as documented in the architecture manual.

If KVM_X2APIC_API_USE_32BIT_IDS feature of KVM_CAP_X2APIC_API is enabled, then the format of APIC_ID register depends on the APIC mode (reported by MSR_IA32_APICBASE) of its VCPU.  x2APIC stores APIC ID in the APIC_ID register (bytes 32-35).  xAPIC only allows an 8-bit APIC ID which is stored in bits 31-24 of the APIC register, or equivalently in byte 35 of struct kvm_lapic_state's regs field.  KVM_GET_LAPIC must then be called after MSR_IA32_APICBASE has been set with KVM_SET_MSR.

If KVM_X2APIC_API_USE_32BIT_IDS feature is disabled, struct kvm_lapic_state always uses xAPIC format.

<a id="rst-kvm-set-lapic"></a>

### 4.58 KVM_SET_LAPIC

**Capability:** KVM_CAP_IRQCHIP

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_lapic_state (in)

**Returns:** 0 on success, -1 on error



```text
#define KVM_APIC_REG_SIZE 0x400
struct kvm_lapic_state {
      char regs[KVM_APIC_REG_SIZE];
};
```

Copies the input argument into the Local APIC registers.  The data format and layout are the same as documented in the architecture manual.

The format of the APIC ID register (bytes 32-35 of struct kvm_lapic_state's regs field) depends on the state of the KVM_CAP_X2APIC_API capability. See the note in KVM_GET_LAPIC.

<a id="rst-kvm-ioeventfd"></a>

### 4.59 KVM_IOEVENTFD

**Capability:** KVM_CAP_IOEVENTFD

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_ioeventfd (in)

**Returns:** 0 on success, \!0 on error

This ioctl attaches or detaches an ioeventfd to a legal pio/mmio address within the guest.  A guest write in the registered address will signal the provided event instead of triggering an exit.



```text
struct kvm_ioeventfd {
      __u64 datamatch;
      __u64 addr;        /* legal pio/mmio address */
      __u32 len;         /* 0, 1, 2, 4, or 8 bytes    */
      __s32 fd;
      __u32 flags;
      __u8  pad[36];
};
```

For the special case of virtio-ccw devices on s390, the ioevent is matched to a subchannel/virtqueue tuple instead.

The following flags are defined:



```text
#define KVM_IOEVENTFD_FLAG_DATAMATCH (1 << kvm_ioeventfd_flag_nr_datamatch)
#define KVM_IOEVENTFD_FLAG_PIO       (1 << kvm_ioeventfd_flag_nr_pio)
#define KVM_IOEVENTFD_FLAG_DEASSIGN  (1 << kvm_ioeventfd_flag_nr_deassign)
#define KVM_IOEVENTFD_FLAG_VIRTIO_CCW_NOTIFY \
      (1 << kvm_ioeventfd_flag_nr_virtio_ccw_notify)
```

If datamatch flag is set, the event will be signaled only if the written value to the registered address is equal to datamatch in struct kvm_ioeventfd.

For virtio-ccw devices, addr contains the subchannel id and datamatch the virtqueue index.

With KVM_CAP_IOEVENTFD_ANY_LENGTH, a zero length ioeventfd is allowed, and the kernel will ignore the length of guest write and may get a faster vmexit. The speedup may only apply to specific architectures, but the ioeventfd will work anyway.

<a id="rst-kvm-dirty-tlb"></a>

### 4.60 KVM_DIRTY_TLB

**Capability:** KVM_CAP_SW_TLB

**Architectures:** ppc

**Type:** vcpu ioctl

**Parameters:** struct kvm_dirty_tlb (in)

**Returns:** 0 on success, -1 on error



```text
struct kvm_dirty_tlb {
      __u64 bitmap;
      __u32 num_dirty;
};
```

This must be called whenever userspace has changed an entry in the shared TLB, prior to calling KVM_RUN on the associated vcpu.

The "bitmap" field is the userspace address of an array.  This array consists of a number of bits, equal to the total number of TLB entries as determined by the last successful call to `KVM_ENABLE_CAP(KVM_CAP_SW_TLB)`, rounded up to the nearest multiple of 64.

Each bit corresponds to one TLB entry, ordered the same as in the shared TLB array.

The array is little-endian: the bit 0 is the least significant bit of the first byte, bit 8 is the least significant bit of the second byte, etc. This avoids any complications with differing word sizes.

The "num_dirty" field is a performance hint for KVM to determine whether it should skip processing the bitmap and just invalidate everything.  It must be set to the number of set bits in the bitmap.

<a id="rst-kvm-create-spapr-tce"></a>

### 4.62 KVM_CREATE_SPAPR_TCE

**Capability:** KVM_CAP_SPAPR_TCE

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** struct kvm_create_spapr_tce (in)

**Returns:** file descriptor for manipulating the created TCE table

This creates a virtual TCE (translation control entry) table, which is an IOMMU for PAPR-style virtual I/O.  It is used to translate logical addresses used in virtual I/O into guest physical addresses, and provides a scatter/gather capability for PAPR virtual I/O.



```text
/* for KVM_CAP_SPAPR_TCE */
struct kvm_create_spapr_tce {
      __u64 liobn;
      __u32 window_size;
};
```

The liobn field gives the logical IO bus number for which to create a TCE table.  The window_size field specifies the size of the DMA window which this TCE table will translate - the table will contain one 64 bit TCE entry for every 4kiB of the DMA window.

When the guest issues an H_PUT_TCE hcall on a liobn for which a TCE table has been created using this ioctl(), the kernel will handle it in real mode, updating the TCE table.  H_PUT_TCE calls for other liobns will cause a vm exit and must be handled by userspace.

The return value is a file descriptor which can be passed to mmap(2) to map the created TCE table into userspace.  This lets userspace read the entries written by kernel-handled H_PUT_TCE calls, and also lets userspace update the TCE table directly which is useful in some circumstances.

<a id="rst-kvm-nmi"></a>

### 4.64 KVM_NMI

**Capability:** KVM_CAP_USER_NMI

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0 on success, -1 on error

Queues an NMI on the thread's vcpu.  Note this is well defined only when KVM_CREATE_IRQCHIP has not been called, since this is an interface between the virtual cpu core and virtual local APIC.  After KVM_CREATE_IRQCHIP has been called, this interface is completely emulated within the kernel.

To use this to emulate the LINT1 input with KVM_CREATE_IRQCHIP, use the following algorithm:

> - pause the vcpu
>
> - read the local APIC's state (KVM_GET_LAPIC)
>
> - check whether changing LINT1 will queue an NMI (see the LVT entry for LINT1)
>
> - if so, issue KVM_NMI
>
> - resume the vcpu

Some guests configure the LINT1 NMI input to cause a panic, aiding in debugging.

<a id="rst-kvm-s390-ucas-map"></a>

### 4.65 KVM_S390_UCAS_MAP

**Capability:** KVM_CAP_S390_UCONTROL

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** struct kvm_s390_ucas_mapping (in)

**Returns:** 0 in case of success

The parameter is defined like this:



```text
struct kvm_s390_ucas_mapping {
        __u64 user_addr;
        __u64 vcpu_addr;
        __u64 length;
};
```

This ioctl maps the memory at "user_addr" with the length "length" to the vcpu's address space starting at "vcpu_addr". All parameters need to be aligned by 1 megabyte.

<a id="rst-kvm-s390-ucas-unmap"></a>

### 4.66 KVM_S390_UCAS_UNMAP

**Capability:** KVM_CAP_S390_UCONTROL

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** struct kvm_s390_ucas_mapping (in)

**Returns:** 0 in case of success

The parameter is defined like this:



```text
struct kvm_s390_ucas_mapping {
        __u64 user_addr;
        __u64 vcpu_addr;
        __u64 length;
};
```

This ioctl unmaps the memory in the vcpu's address space starting at "vcpu_addr" with the length "length". The field "user_addr" is ignored. All parameters need to be aligned by 1 megabyte.

<a id="rst-kvm-s390-vcpu-fault"></a>

### 4.67 KVM_S390_VCPU_FAULT

**Capability:** KVM_CAP_S390_UCONTROL

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** vcpu absolute address (in)

**Returns:** 0 in case of success

This call creates a page table entry on the virtual cpu's address space (for user controlled virtual machines) or the virtual machine's address space (for regular virtual machines). This only works for minor faults, thus it's recommended to access subject memory page via the user page table upfront. This is useful to handle validity intercepts for user controlled virtual machines to fault in the virtual cpu's lowcore pages prior to calling the KVM_RUN ioctl.

<a id="rst-kvm-set-one-reg"></a>

### 4.68 KVM_SET_ONE_REG

**Capability:** KVM_CAP_ONE_REG

**Architectures:** all

**Type:** vcpu ioctl

**Parameters:** struct kvm_one_reg (in)

**Returns:** 0 on success, negative value on failure

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENOENT
>
> </td>
> <td>
>
>
> no such register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> invalid register ID, or no such register or used with VMs in protected virtualization mode on s390
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EPERM
>
> </td>
> <td>
>
>
> (arm64) register access not allowed before vcpu finalization
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EBUSY
>
> </td>
> <td>
>
>
> (riscv) changing register value not allowed after the vcpu has run at least once
>
> </td>
> </tr>
> </tbody>
> </table>

(These error codes are indicative only: do not rely on a specific error code being returned in a specific situation.)



```text
 struct kvm_one_reg {
      __u64 id;
      __u64 addr;
};
```

Using this ioctl, a single vcpu register can be set to a specific value defined by user space with the passed in struct kvm_one_reg, where id refers to the register identifier as described below and addr is a pointer to a variable with the respective size. There can be architecture agnostic and architecture specific registers. Each have their own range of operation and their own constants and width. To keep track of the implemented registers, find a list below:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Arch
>
> </th>
> <th>
>
>
> Register
>
> </th>
> <th>
>
>
> Width (bits)
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_HIOR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IAC1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IAC2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IAC3
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IAC4
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAC1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAC2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DABR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PURR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SPURR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DSISR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_AMR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_UAMOR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCR0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCR1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCRA
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCR2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCRS
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMCR3
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SIAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SDAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SIER
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SIER2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SIER3
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC1
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC2
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC3
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC4
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC5
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC6
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC7
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PMC8
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_FPR0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_FPR31
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VR0
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VR31
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VSR0
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VSR31
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_FPSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VSCR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VPA_ADDR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VPA_SLB
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VPA_DTL
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_EPCR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_EPR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TCR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_OR_TSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_CLEAR_TSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS0
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS1
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS7_3
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS4
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MAS6
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_MMUCFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB0CFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB1CFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB2CFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB3CFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB0PS
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB1PS
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB2PS
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TLB3PS
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_EPTCFG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_ICP_STATE
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VP_STATE
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TB_OFFSET
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SPMC1
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SPMC2
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IAMR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TFHAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TFIAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TEXASR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_FSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PSPB
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_EBBHR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_EBBRR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_BESCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DPDES
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAWR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAWRX
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_CIABR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_IC
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VTB
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_CSIGR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TACR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TCSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PID
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_ACOP
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_VRSAVE
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_LPCR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_LPCR_64
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PPR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_ARCH_COMPAT
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DABRX
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_WORT
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_SPRG9
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DBSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TIDR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PSSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DEC_EXPIRY
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_PTCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_HASHKEYR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_HASHPKEYR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAWR1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DAWRX1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_DEXCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_GPR0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_GPR31
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_VSR0
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_VSR63
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_CR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_LR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_CTR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_FPSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_AMR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_PPR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_VRSAVE
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_VSCR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_DSCR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_TAR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PPC
>
> </td>
> <td>
>
>
> KVM_REG_PPC_TM_XER
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_R0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ...
>
> </td>
> <td>
>
>
>
>
> </td>
> <td>
>
>
>
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_R31
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_HI
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_LO
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_PC
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_INDEX
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_ENTRYLO0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_ENTRYLO1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONTEXT
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONTEXTCONFIG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_USERLOCAL
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_XCONTEXTCONFIG
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PAGEMASK
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PAGEGRAIN
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_SEGCTL0
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_SEGCTL1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_SEGCTL2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PWBASE
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PWFIELD
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PWSIZE
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_WIRED
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PWCTL
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_HWRENA
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_BADVADDR
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_BADINSTR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_BADINSTRP
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_COUNT
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_ENTRYHI
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_COMPARE
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_STATUS
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_INTCTL
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CAUSE
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_EPC
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_PRID
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_EBASE
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG1
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG2
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG3
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG4
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG5
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_CONFIG7
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_XCONTEXT
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_ERROREPC
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH1
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH2
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH3
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH4
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH5
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_KSCRATCH6
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_CP0_MAAR(0..63)
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_COUNT_CTL
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_COUNT_RESUME
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_COUNT_HZ
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_FPR_32(0..31)
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_FPR_64(0..31)
>
> </td>
> <td>
>
>
> 64
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_VEC_128(0..31)
>
> </td>
> <td>
>
>
> 128
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_FCR_IR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_FCR_CSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_MSA_IR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> MIPS
>
> </td>
> <td>
>
>
> KVM_REG_MIPS_MSA_CSR
>
> </td>
> <td>
>
>
> 32
>
> </td>
> </tr>
> </tbody>
> </table>

ARM registers are mapped using the lower 32 bits.  The upper 16 of that is the register group type, or coprocessor number:

ARM core registers have the following id bit patterns:



```text
0x4020 0000 0010 <index into the kvm_regs struct:16>
```

ARM 32-bit CP15 registers have the following id bit patterns:



```text
0x4020 0000 000F <zero:1> <crn:4> <crm:4> <opc1:4> <opc2:3>
```

ARM 64-bit CP15 registers have the following id bit patterns:



```text
0x4030 0000 000F <zero:1> <zero:4> <crm:4> <opc1:4> <zero:3>
```

ARM CCSIDR registers are demultiplexed by CSSELR value:



```text
0x4020 0000 0011 00 <csselr:8>
```

ARM 32-bit VFP control registers have the following id bit patterns:



```text
0x4020 0000 0012 1 <regno:12>
```

ARM 64-bit FP registers have the following id bit patterns:



```text
0x4030 0000 0012 0 <regno:12>
```

ARM firmware pseudo-registers have the following bit pattern:



```text
0x4030 0000 0014 <regno:16>
```

arm64 registers are mapped using the lower 32 bits. The upper 16 of that is the register group type, or coprocessor number:

arm64 core/FP-SIMD registers have the following id bit patterns. Note that the size of the access is variable, as the kvm_regs structure contains elements ranging from 32 to 128 bits. The index is a 32bit value in the kvm_regs structure seen as a 32bit array:



```text
0x60x0 0000 0010 <index into the kvm_regs struct:16>
```

Specifically:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Bits

</th>
<th>


kvm_regs member

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x6030 0000 0010 0000

</td>
<td>


X0

</td>
<td>


64

</td>
<td>


regs.regs\[0\]

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0002

</td>
<td>


X1

</td>
<td>


64

</td>
<td>


regs.regs\[1\]

</td>
</tr>
<tr>
<td>


...

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


0x6030 0000 0010 003c

</td>
<td>


X30

</td>
<td>


64

</td>
<td>


regs.regs\[30\]

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 003e

</td>
<td>


SP

</td>
<td>


64

</td>
<td>


regs.sp

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0040

</td>
<td>


PC

</td>
<td>


64

</td>
<td>


regs.pc

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0042

</td>
<td>


PSTATE

</td>
<td>


64

</td>
<td>


regs.pstate

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0044

</td>
<td>


SP_EL1

</td>
<td>


64

</td>
<td>


sp_el1

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0046

</td>
<td>


ELR_EL1

</td>
<td>


64

</td>
<td>


elr_el1

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0048

</td>
<td>


SPSR_EL1

</td>
<td>


64

</td>
<td>


spsr\[KVM_SPSR_EL1\] (alias SPSR_SVC)

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 004a

</td>
<td>


SPSR_ABT

</td>
<td>


64

</td>
<td>


spsr\[KVM_SPSR_ABT\]

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 004c

</td>
<td>


SPSR_UND

</td>
<td>


64

</td>
<td>


spsr\[KVM_SPSR_UND\]

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 004e

</td>
<td>


SPSR_IRQ

</td>
<td>


64

</td>
<td>


spsr\[KVM_SPSR_IRQ\]

</td>
</tr>
<tr>
<td>


0x6030 0000 0010 0050

</td>
<td>


SPSR_FIQ

</td>
<td>


64

</td>
<td>


spsr\[KVM_SPSR_FIQ\]

</td>
</tr>
<tr>
<td>


0x6040 0000 0010 0054

</td>
<td>


V0

</td>
<td>


128

</td>
<td>


fp_regs.vregs\[0\]    <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1)

</td>
</tr>
<tr>
<td>


0x6040 0000 0010 0058

</td>
<td>


V1

</td>
<td>


128

</td>
<td>


fp_regs.vregs\[1\]    <a id="rst-footnote-reference-2"></a>[1](#rst-footnote-1)

</td>
</tr>
<tr>
<td>


...

</td>
<td>




</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


0x6040 0000 0010 00d0

</td>
<td>


V31

</td>
<td>


128

</td>
<td>


fp_regs.vregs\[31\]   <a id="rst-footnote-reference-3"></a>[1](#rst-footnote-1)

</td>
</tr>
<tr>
<td>


0x6020 0000 0010 00d4

</td>
<td>


FPSR

</td>
<td>


32

</td>
<td>


fp_regs.fpsr

</td>
</tr>
<tr>
<td>


0x6020 0000 0010 00d5

</td>
<td>


FPCR

</td>
<td>


32

</td>
<td>


fp_regs.fpcr

</td>
</tr>
</tbody>
</table>

<a id="rst-footnote-1"></a>



**[1]** These encodings are not accepted for SVE-enabled vcpus.  See [4.82 KVM_ARM_VCPU_INIT](<#rst-kvm-arm-vcpu-init>).

The equivalent register content can be accessed via bits \[127:0\] of the corresponding SVE Zn registers instead for vcpus that have SVE enabled (see below).

arm64 CCSIDR registers are demultiplexed by CSSELR value:



```text
0x6020 0000 0011 00 <csselr:8>
```

arm64 system registers have the following id bit patterns:



```text
0x6030 0000 0013 <op0:2> <op1:3> <crn:4> <crm:4> <op2:3>
```

> [!WARNING]
>
> Two system register IDs do not follow the specified pattern.  These are KVM_REG_ARM_TIMER_CVAL and KVM_REG_ARM_TIMER_CNT, which map to system registers CNTV_CVAL_EL0 and CNTVCT_EL0 respectively.  These two had their values accidentally swapped, which means TIMER_CVAL is derived from the register encoding for CNTVCT_EL0 and TIMER_CNT is derived from the register encoding for CNTV_CVAL_EL0.  As this is API, it must remain this way.

arm64 firmware pseudo-registers have the following bit pattern:



```text
0x6030 0000 0014 <regno:16>
```

arm64 SVE registers have the following bit patterns:



```text
0x6080 0000 0015 00 <n:5> <slice:5>   Zn bits[2048*slice + 2047 : 2048*slice]
0x6050 0000 0015 04 <n:4> <slice:5>   Pn bits[256*slice + 255 : 256*slice]
0x6050 0000 0015 060 <slice:5>        FFR bits[256*slice + 255 : 256*slice]
0x6060 0000 0015 ffff                 KVM_REG_ARM64_SVE_VLS pseudo-register
```

Access to register IDs where 2048 \* slice &gt;= 128 \* max_vq will fail with ENOENT.  max_vq is the vcpu's maximum supported vector length in 128-bit quadwords: see <a id="rst-footnote-reference-4"></a>[2](#rst-footnote-2) below.

These registers are only accessible on vcpus for which SVE is enabled. See KVM_ARM_VCPU_INIT for details.

In addition, except for KVM_REG_ARM64_SVE_VLS, these registers are not accessible until the vcpu's SVE configuration has been finalized using KVM_ARM_VCPU_FINALIZE(KVM_ARM_VCPU_SVE).  See KVM_ARM_VCPU_INIT and KVM_ARM_VCPU_FINALIZE for more information about this procedure.

KVM_REG_ARM64_SVE_VLS is a pseudo-register that allows the set of vector lengths supported by the vcpu to be discovered and configured by userspace.  When transferred to or from user memory via KVM_GET_ONE_REG or KVM_SET_ONE_REG, the value of this register is of type \__u64\[KVM_ARM64_SVE_VLS_WORDS\], and encodes the set of vector lengths as follows:



```text
__u64 vector_lengths[KVM_ARM64_SVE_VLS_WORDS];

if (vq >= SVE_VQ_MIN && vq <= SVE_VQ_MAX &&
    ((vector_lengths[(vq - KVM_ARM64_SVE_VQ_MIN) / 64] >>
              ((vq - KVM_ARM64_SVE_VQ_MIN) % 64)) & 1))
      /* Vector length vq * 16 bytes supported */
else
      /* Vector length vq * 16 bytes not supported */
```

<a id="rst-footnote-2"></a>



**[2]** The maximum value vq for which the above condition is true is max_vq.  This is the maximum vector length available to the guest on this vcpu, and determines which register slices are visible through this ioctl interface.

(See [Documentation/arch/arm64/sve.rst](/kernel/hardware/arch/arm64/sve.md) for an explanation of the "vq" nomenclature.)

KVM_REG_ARM64_SVE_VLS is only accessible after KVM_ARM_VCPU_INIT. KVM_ARM_VCPU_INIT initialises it to the best set of vector lengths that the host supports.

Userspace may subsequently modify it if desired until the vcpu's SVE configuration is finalized using KVM_ARM_VCPU_FINALIZE(KVM_ARM_VCPU_SVE).

Apart from simply removing all vector lengths from the host set that exceed some value, support for arbitrarily chosen sets of vector lengths is hardware-dependent and may not be available.  Attempting to configure an invalid set of vector lengths via KVM_SET_ONE_REG will fail with EINVAL.

After the vcpu's SVE configuration is finalized, further attempts to write this register will fail with EPERM.

arm64 bitmap feature firmware pseudo-registers have the following bit pattern:



```text
0x6030 0000 0016 <regno:16>
```

The bitmap feature firmware registers exposes the hypercall services that are available for userspace to configure. The set bits corresponds to the services that are available for the guests to access. By default, KVM sets all the supported bits during VM initialization. The userspace can discover the available services via KVM_GET_ONE_REG, and write back the bitmap corresponding to the features that it wishes guests to see via KVM_SET_ONE_REG.

Note: These registers are immutable once any of the vCPUs of the VM has run at least once. A KVM_SET_ONE_REG in such a scenario will return a -EBUSY to userspace.

(See [Documentation/virt/kvm/arm/hypercalls.rst](/kernel/internals/virt/kvm-arm/hypercalls.md) for more details.)

MIPS registers are mapped using the lower 32 bits.  The upper 16 of that is the register group type:

MIPS core registers (see above) have the following id bit patterns:



```text
0x7030 0000 0000 <reg:16>
```

MIPS CP0 registers (see KVM_REG_MIPS_CP0\_\* above) have the following id bit patterns depending on whether they're 32-bit or 64-bit registers:



```text
0x7020 0000 0001 00 <reg:5> <sel:3>   (32-bit)
0x7030 0000 0001 00 <reg:5> <sel:3>   (64-bit)
```

Note: KVM_REG_MIPS_CP0_ENTRYLO0 and KVM_REG_MIPS_CP0_ENTRYLO1 are the MIPS64 versions of the EntryLo registers regardless of the word size of the host hardware, host kernel, guest, and whether XPA is present in the guest, i.e. with the RI and XI bits (if they exist) in bits 63 and 62 respectively, and the PFNX field starting at bit 30.

MIPS MAARs (see KVM_REG_MIPS_CP0_MAAR(\*) above) have the following id bit patterns:



```text
0x7030 0000 0001 01 <reg:8>
```

MIPS KVM control registers (see above) have the following id bit patterns:



```text
0x7030 0000 0002 <reg:16>
```

MIPS FPU registers (see KVM_REG_MIPS_FPR\_\{32,64\}() above) have the following id bit patterns depending on the size of the register being accessed. They are always accessed according to the current guest FPU mode (Status.FR and Config5.FRE), i.e. as the guest would see them, and they become unpredictable if the guest FPU mode is changed. MIPS SIMD Architecture (MSA) vector registers (see KVM_REG_MIPS_VEC_128() above) have similar patterns as they overlap the FPU registers:



```text
0x7020 0000 0003 00 <0:3> <reg:5> (32-bit FPU registers)
0x7030 0000 0003 00 <0:3> <reg:5> (64-bit FPU registers)
0x7040 0000 0003 00 <0:3> <reg:5> (128-bit MSA vector registers)
```

MIPS FPU control registers (see KVM_REG_MIPS_FCR\_\{IR,CSR\} above) have the following id bit patterns:



```text
0x7020 0000 0003 01 <0:3> <reg:5>
```

MIPS MSA control registers (see KVM_REG_MIPS_MSA\_\{IR,CSR\} above) have the following id bit patterns:



```text
0x7020 0000 0003 02 <0:3> <reg:5>
```

RISC-V registers are mapped using the lower 32 bits. The upper 8 bits of that is the register group type.

RISC-V config registers are meant for configuring a Guest VCPU and it has the following id bit patterns:



```text
0x8020 0000 01 <index into the kvm_riscv_config struct:24> (32bit Host)
0x8030 0000 01 <index into the kvm_riscv_config struct:24> (64bit Host)
```

Following are the RISC-V config registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x80x0 0000 0100 0000

</td>
<td>


isa

</td>
<td>


ISA feature bitmap of Guest VCPU

</td>
</tr>
</tbody>
</table>

The isa config register can be read anytime but can only be written before a Guest VCPU runs. It will have ISA feature bits matching underlying host set by default.

RISC-V core registers represent the general execution state of a Guest VCPU and it has the following id bit patterns:



```text
0x8020 0000 02 <index into the kvm_riscv_core struct:24> (32bit Host)
0x8030 0000 02 <index into the kvm_riscv_core struct:24> (64bit Host)
```

Following are the RISC-V core registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x80x0 0000 0200 0000

</td>
<td>


regs.pc

</td>
<td>


Program counter

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0001

</td>
<td>


regs.ra

</td>
<td>


Return address

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0002

</td>
<td>


regs.sp

</td>
<td>


Stack pointer

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0003

</td>
<td>


regs.gp

</td>
<td>


Global pointer

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0004

</td>
<td>


regs.tp

</td>
<td>


Task pointer

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0005

</td>
<td>


regs.t0

</td>
<td>


Caller saved register 0

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0006

</td>
<td>


regs.t1

</td>
<td>


Caller saved register 1

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0007

</td>
<td>


regs.t2

</td>
<td>


Caller saved register 2

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0008

</td>
<td>


regs.s0

</td>
<td>


Callee saved register 0

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0009

</td>
<td>


regs.s1

</td>
<td>


Callee saved register 1

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000a

</td>
<td>


regs.a0

</td>
<td>


Function argument (or return value) 0

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000b

</td>
<td>


regs.a1

</td>
<td>


Function argument (or return value) 1

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000c

</td>
<td>


regs.a2

</td>
<td>


Function argument 2

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000d

</td>
<td>


regs.a3

</td>
<td>


Function argument 3

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000e

</td>
<td>


regs.a4

</td>
<td>


Function argument 4

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 000f

</td>
<td>


regs.a5

</td>
<td>


Function argument 5

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0010

</td>
<td>


regs.a6

</td>
<td>


Function argument 6

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0011

</td>
<td>


regs.a7

</td>
<td>


Function argument 7

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0012

</td>
<td>


regs.s2

</td>
<td>


Callee saved register 2

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0013

</td>
<td>


regs.s3

</td>
<td>


Callee saved register 3

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0014

</td>
<td>


regs.s4

</td>
<td>


Callee saved register 4

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0015

</td>
<td>


regs.s5

</td>
<td>


Callee saved register 5

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0016

</td>
<td>


regs.s6

</td>
<td>


Callee saved register 6

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0017

</td>
<td>


regs.s7

</td>
<td>


Callee saved register 7

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0018

</td>
<td>


regs.s8

</td>
<td>


Callee saved register 8

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0019

</td>
<td>


regs.s9

</td>
<td>


Callee saved register 9

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001a

</td>
<td>


regs.s10

</td>
<td>


Callee saved register 10

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001b

</td>
<td>


regs.s11

</td>
<td>


Callee saved register 11

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001c

</td>
<td>


regs.t3

</td>
<td>


Caller saved register 3

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001d

</td>
<td>


regs.t4

</td>
<td>


Caller saved register 4

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001e

</td>
<td>


regs.t5

</td>
<td>


Caller saved register 5

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 001f

</td>
<td>


regs.t6

</td>
<td>


Caller saved register 6

</td>
</tr>
<tr>
<td>


0x80x0 0000 0200 0020

</td>
<td>


mode

</td>
<td>


Privilege mode (1 = S-mode or 0 = U-mode)

</td>
</tr>
</tbody>
</table>

RISC-V csr registers represent the supervisor mode control/status registers of a Guest VCPU and it has the following id bit patterns:



```text
0x8020 0000 03 <index into the kvm_riscv_csr struct:24> (32bit Host)
0x8030 0000 03 <index into the kvm_riscv_csr struct:24> (64bit Host)
```

Following are the RISC-V csr registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x80x0 0000 0300 0000

</td>
<td>


sstatus

</td>
<td>


Supervisor status

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0001

</td>
<td>


sie

</td>
<td>


Supervisor interrupt enable

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0002

</td>
<td>


stvec

</td>
<td>


Supervisor trap vector base

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0003

</td>
<td>


sscratch

</td>
<td>


Supervisor scratch register

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0004

</td>
<td>


sepc

</td>
<td>


Supervisor exception program counter

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0005

</td>
<td>


scause

</td>
<td>


Supervisor trap cause

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0006

</td>
<td>


stval

</td>
<td>


Supervisor bad address or instruction

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0007

</td>
<td>


sip

</td>
<td>


Supervisor interrupt pending

</td>
</tr>
<tr>
<td>


0x80x0 0000 0300 0008

</td>
<td>


satp

</td>
<td>


Supervisor address translation and protection

</td>
</tr>
</tbody>
</table>

RISC-V timer registers represent the timer state of a Guest VCPU and it has the following id bit patterns:



```text
0x8030 0000 04 <index into the kvm_riscv_timer struct:24>
```

Following are the RISC-V timer registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x8030 0000 0400 0000

</td>
<td>


frequency

</td>
<td>


Time base frequency (read-only)

</td>
</tr>
<tr>
<td>


0x8030 0000 0400 0001

</td>
<td>


time

</td>
<td>


Time value visible to Guest

</td>
</tr>
<tr>
<td>


0x8030 0000 0400 0002

</td>
<td>


compare

</td>
<td>


Time compare programmed by Guest

</td>
</tr>
<tr>
<td>


0x8030 0000 0400 0003

</td>
<td>


state

</td>
<td>


Time compare state (1 = ON or 0 = OFF)

</td>
</tr>
</tbody>
</table>

RISC-V F-extension registers represent the single precision floating point state of a Guest VCPU and it has the following id bit patterns:



```text
0x8020 0000 05 <index into the __riscv_f_ext_state struct:24>
```

Following are the RISC-V F-extension registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x8020 0000 0500 0000

</td>
<td>


f\[0\]

</td>
<td>


Floating point register 0

</td>
</tr>
<tr>
<td>


...

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


0x8020 0000 0500 001f

</td>
<td>


f\[31\]

</td>
<td>


Floating point register 31

</td>
</tr>
<tr>
<td>


0x8020 0000 0500 0020

</td>
<td>


fcsr

</td>
<td>


Floating point control and status register

</td>
</tr>
</tbody>
</table>

RISC-V D-extension registers represent the double precision floating point state of a Guest VCPU and it has the following id bit patterns:



```text
0x8020 0000 06 <index into the __riscv_d_ext_state struct:24> (fcsr)
0x8030 0000 06 <index into the __riscv_d_ext_state struct:24> (non-fcsr)
```

Following are the RISC-V D-extension registers:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x8030 0000 0600 0000

</td>
<td>


f\[0\]

</td>
<td>


Floating point register 0

</td>
</tr>
<tr>
<td>


...

</td>
<td>




</td>
<td>




</td>
</tr>
<tr>
<td>


0x8030 0000 0600 001f

</td>
<td>


f\[31\]

</td>
<td>


Floating point register 31

</td>
</tr>
<tr>
<td>


0x8020 0000 0600 0020

</td>
<td>


fcsr

</td>
<td>


Floating point control and status register

</td>
</tr>
</tbody>
</table>

LoongArch registers are mapped using the lower 32 bits. The upper 16 bits of that is the register group type.

LoongArch csr registers are used to control guest cpu or get status of guest cpu, and they have the following id bit patterns:



```text
0x9030 0000 0001 00 <reg:5> <sel:3>   (64-bit)
```

LoongArch KVM control registers are used to implement some new defined functions such as set vcpu counter or reset vcpu, and they have the following id bit patterns:



```text
0x9030 0000 0002 <reg:16>
```

- **x86 MSR registers have the following id bit patterns::**

  0x2030 0002 &lt;msr number:32&gt;

Following are the KVM-defined registers for x86:


<table>
<thead>
<tr>
<th>


Encoding

</th>
<th>


Register

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


0x2030 0003 0000 0000

</td>
<td>


SSP

</td>
<td>


Shadow Stack Pointer

</td>
</tr>
</tbody>
</table>

<a id="rst-kvm-get-one-reg"></a>

### 4.69 KVM_GET_ONE_REG

**Capability:** KVM_CAP_ONE_REG

**Architectures:** all

**Type:** vcpu ioctl

**Parameters:** struct kvm_one_reg (in and out)

**Returns:** 0 on success, negative value on failure

Errors include:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENOENT
>
> </td>
> <td>
>
>
> no such register
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> invalid register ID, or no such register or used with VMs in protected virtualization mode on s390
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EPERM
>
> </td>
> <td>
>
>
> (arm64) register access not allowed before vcpu finalization
>
> </td>
> </tr>
> </tbody>
> </table>

(These error codes are indicative only: do not rely on a specific error code being returned in a specific situation.)

This ioctl allows to receive the value of a single register implemented in a vcpu. The register to read is indicated by the "id" field of the kvm_one_reg struct passed in. On success, the register value can be found at the memory location pointed to by "addr".

The list of registers accessible using this interface is identical to the list in 4.68.

<a id="rst-kvm-kvmclock-ctrl"></a>

### 4.70 KVM_KVMCLOCK_CTRL

**Capability:** KVM_CAP_KVMCLOCK_CTRL

**Architectures:** Any that implement pvclocks (currently x86 only)

**Type:** vcpu ioctl

**Parameters:** None

**Returns:** 0 on success, -1 on error

This ioctl sets a flag accessible to the guest indicating that the specified vCPU has been paused by the host userspace.

The host will set a flag in the pvclock structure that is checked from the soft lockup watchdog.  The flag is part of the pvclock structure that is shared between guest and host, specifically the second bit of the flags field of the pvclock_vcpu_time_info structure.  It will be set exclusively by the host and read/cleared exclusively by the guest.  The guest operation of checking and clearing the flag must be an atomic operation so load-link/store-conditional, or equivalent must be used.  There are two cases where the guest will clear the flag: when the soft lockup watchdog timer resets itself or when a soft lockup is detected.  This ioctl can be called any time after pausing the vcpu, but before it is resumed.

<a id="rst-kvm-signal-msi"></a>

### 4.71 KVM_SIGNAL_MSI

**Capability:** KVM_CAP_SIGNAL_MSI

**Architectures:** x86 arm64

**Type:** vm ioctl

**Parameters:** struct kvm_msi (in)

**Returns:** &gt;0 on delivery, 0 if guest blocked the MSI, and -1 on error

Directly inject a MSI message. Only valid with in-kernel irqchip that handles MSI messages.



```text
struct kvm_msi {
      __u32 address_lo;
      __u32 address_hi;
      __u32 data;
      __u32 flags;
      __u32 devid;
      __u8  pad[12];
};
```

- **flags:**

  KVM_MSI_VALID_DEVID: devid contains a valid value.  The per-VM KVM_CAP_MSI_DEVID capability advertises the requirement to provide the device ID.  If this capability is not available, userspace should never set the KVM_MSI_VALID_DEVID flag as the ioctl might fail.

If KVM_MSI_VALID_DEVID is set, devid contains a unique device identifier for the device that wrote the MSI message.  For PCI, this is usually a BDF identifier in the lower 16 bits.

On x86, address_hi is ignored unless the KVM_X2APIC_API_USE_32BIT_IDS feature of KVM_CAP_X2APIC_API capability is enabled.  If it is enabled, address_hi bits 31-8 provide bits 31-8 of the destination id.  Bits 7-0 of address_hi must be zero.

<a id="rst-kvm-create-pit2"></a>

### 4.71 KVM_CREATE_PIT2

**Capability:** KVM_CAP_PIT2

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_pit_config (in)

**Returns:** 0 on success, -1 on error

Creates an in-kernel device model for the i8254 PIT. This call is only valid after enabling in-kernel irqchip support via KVM_CREATE_IRQCHIP. The following parameters have to be passed:



```text
struct kvm_pit_config {
      __u32 flags;
      __u32 pad[15];
};
```

Valid flags are:



```text
#define KVM_PIT_SPEAKER_DUMMY     1 /* emulate speaker port stub */
```

PIT timer interrupts may use a per-VM kernel thread for injection. If it exists, this thread will have a name of the following pattern:



```text
kvm-pit/<owner-process-pid>
```

When running a guest with elevated priorities, the scheduling parameters of this thread may have to be adjusted accordingly.

This IOCTL replaces the obsolete KVM_CREATE_PIT.

<a id="rst-kvm-get-pit2"></a>

### 4.72 KVM_GET_PIT2

**Capability:** KVM_CAP_PIT_STATE2

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_pit_state2 (out)

**Returns:** 0 on success, -1 on error

Retrieves the state of the in-kernel PIT model. Only valid after KVM_CREATE_PIT2. The state is returned in the following structure:



```text
struct kvm_pit_state2 {
      struct kvm_pit_channel_state channels[3];
      __u32 flags;
      __u32 reserved[9];
};
```

Valid flags are:



```text
/* disable PIT in HPET legacy mode */
#define KVM_PIT_FLAGS_HPET_LEGACY     0x00000001
/* speaker port data bit enabled */
#define KVM_PIT_FLAGS_SPEAKER_DATA_ON 0x00000002
```

This IOCTL replaces the obsolete KVM_GET_PIT.

<a id="rst-kvm-set-pit2"></a>

### 4.73 KVM_SET_PIT2

**Capability:** KVM_CAP_PIT_STATE2

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_pit_state2 (in)

**Returns:** 0 on success, -1 on error

Sets the state of the in-kernel PIT model. Only valid after KVM_CREATE_PIT2. See KVM_GET_PIT2 for details on struct kvm_pit_state2.

> [!TIP]
>
> `KVM_SET_PIT2` strictly adheres to the spec of Intel 8254 PIT.  For example, a `count` value of 0 in `struct kvm_pit_channel_state` is interpreted as 65536, which is the maximum count value. Refer to [Intel 8254 programmable interval timer](<https://www.scs.stanford.edu/10wi-cs140/pintos/specs/8254.pdf>)<a id="rst-intel-8254-programmable-interval-timer"></a>.

This IOCTL replaces the obsolete KVM_SET_PIT.

<a id="rst-kvm-ppc-get-smmu-info"></a>

### 4.74 KVM_PPC_GET_SMMU_INFO

**Capability:** KVM_CAP_PPC_GET_SMMU_INFO

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** None

**Returns:** 0 on success, -1 on error

This populates and returns a structure describing the features of the "Server" class MMU emulation supported by KVM. This can in turn be used by userspace to generate the appropriate device-tree properties for the guest operating system.

The structure contains some global information, followed by an array of supported segment page sizes:



```text
struct kvm_ppc_smmu_info {
       __u64 flags;
       __u32 slb_size;
       __u32 pad;
       struct kvm_ppc_one_seg_page_size sps[KVM_PPC_PAGE_SIZES_MAX_SZ];
};
```

The supported flags are:

> - - **KVM_PPC_PAGE_SIZES_REAL:**
>
>     When that flag is set, guest page sizes must "fit" the backing store page sizes. When not set, any page size in the list can be used regardless of how they are backed by userspace.
>
> - - **KVM_PPC_1T_SEGMENTS**
>
>     The emulated MMU supports 1T segments in addition to the standard 256M ones.
>
> - - **KVM_PPC_NO_HASH**
>
>     This flag indicates that HPT guests are not supported by KVM, thus all guests must use radix MMU mode.

The "slb_size" field indicates how many SLB entries are supported

The "sps" array contains 8 entries indicating the supported base page sizes for a segment in increasing order. Each entry is defined as follow:



```text
struct kvm_ppc_one_seg_page_size {
     __u32 page_shift;       /* Base page shift of segment (or 0) */
     __u32 slb_enc;          /* SLB encoding for BookS */
     struct kvm_ppc_one_page_size enc[KVM_PPC_PAGE_SIZES_MAX_SZ];
};
```

An entry with a "page_shift" of 0 is unused. Because the array is organized in increasing order, a lookup can stop when encountering such an entry.

The "slb_enc" field provides the encoding to use in the SLB for the page size. The bits are in positions such as the value can directly be OR'ed into the "vsid" argument of the slbmte instruction.

The "enc" array is a list which for each of those segment base page size provides the list of supported actual page sizes (which can be only larger or equal to the base page size), along with the corresponding encoding in the hash PTE. Similarly, the array is 8 entries sorted by increasing sizes and an entry with a "0" shift is an empty entry and a terminator:



```text
struct kvm_ppc_one_page_size {
     __u32 page_shift;       /* Page shift (or 0) */
     __u32 pte_enc;          /* Encoding in the HPTE (>>12) */
};
```

The "pte_enc" field provides a value that can OR'ed into the hash PTE's RPN field (ie, it needs to be shifted left by 12 to OR it into the hash PTE second double word).

<a id="rst-kvm-irqfd"></a>

### 4.75 KVM_IRQFD

**Capability:** KVM_CAP_IRQFD

**Architectures:** x86 s390 arm64

**Type:** vm ioctl

**Parameters:** struct kvm_irqfd (in)

**Returns:** 0 on success, -1 on error

Allows setting an eventfd to directly trigger a guest interrupt. kvm_irqfd.fd specifies the file descriptor to use as the eventfd and kvm_irqfd.gsi specifies the irqchip pin toggled by this event.  When an event is triggered on the eventfd, an interrupt is injected into the guest using the specified gsi pin.  The irqfd is removed using the KVM_IRQFD_FLAG_DEASSIGN flag, specifying both kvm_irqfd.fd and kvm_irqfd.gsi.

With KVM_CAP_IRQFD_RESAMPLE, KVM_IRQFD supports a de-assert and notify mechanism allowing emulation of level-triggered, irqfd-based interrupts.  When KVM_IRQFD_FLAG_RESAMPLE is set the user must pass an additional eventfd in the kvm_irqfd.resamplefd field.  When operating in resample mode, posting of an interrupt through kvm_irq.fd asserts the specified gsi in the irqchip.  When the irqchip is resampled, such as from an EOI, the gsi is de-asserted and the user is notified via kvm_irqfd.resamplefd.  It is the user's responsibility to re-queue the interrupt if the device making use of it still requires service. Note that closing the resamplefd is not sufficient to disable the irqfd.  The KVM_IRQFD_FLAG_RESAMPLE is only necessary on assignment and need not be specified with KVM_IRQFD_FLAG_DEASSIGN.

On arm64, gsi routing being supported, the following can happen:

- in case no routing entry is associated to this gsi, injection fails

- in case the gsi is associated to an irqchip routing entry, irqchip.pin + 32 corresponds to the injected SPI ID.

- in case the gsi is associated to an MSI routing entry, the MSI message and device ID are translated into an LPI (support restricted to GICv3 ITS in-kernel emulation).

<a id="rst-kvm-ppc-allocate-htab"></a>

### 4.76 KVM_PPC_ALLOCATE_HTAB

**Capability:** KVM_CAP_PPC_ALLOC_HTAB

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** Pointer to u32 containing hash table order (in/out)

**Returns:** 0 on success, -1 on error

This requests the host kernel to allocate an MMU hash table for a guest using the PAPR paravirtualization interface.  This only does anything if the kernel is configured to use the Book 3S HV style of virtualization.  Otherwise the capability doesn't exist and the ioctl returns an ENOTTY error.  The rest of this description assumes Book 3S HV.

There must be no vcpus running when this ioctl is called; if there are, it will do nothing and return an EBUSY error.

The parameter is a pointer to a 32-bit unsigned integer variable containing the order (log base 2) of the desired size of the hash table, which must be between 18 and 46.  On successful return from the ioctl, the value will not be changed by the kernel.

If no hash table has been allocated when any vcpu is asked to run (with the KVM_RUN ioctl), the host kernel will allocate a default-sized hash table (16 MB).

If this ioctl is called when a hash table has already been allocated, with a different order from the existing hash table, the existing hash table will be freed and a new one allocated.  If this is ioctl is called when a hash table has already been allocated of the same order as specified, the kernel will clear out the existing hash table (zero all HPTEs).  In either case, if the guest is using the virtualized real-mode area (VRMA) facility, the kernel will re-create the VMRA HPTEs on the next KVM_RUN of any vcpu.

<a id="rst-kvm-s390-interrupt"></a>

### 4.77 KVM_S390_INTERRUPT

**Capability:** basic

**Architectures:** s390

**Type:** vm ioctl, vcpu ioctl

**Parameters:** struct kvm_s390_interrupt (in)

**Returns:** 0 on success, -1 on error

Allows to inject an interrupt to the guest. Interrupts can be floating (vm ioctl) or per cpu (vcpu ioctl), depending on the interrupt type.

Interrupt parameters are passed via kvm_s390_interrupt:



```text
struct kvm_s390_interrupt {
      __u32 type;
      __u32 parm;
      __u64 parm64;
};
```

type can be one of the following:

- **KVM_S390_SIGP_STOP (vcpu)**

  - sigp stop; optional flags in parm

- **KVM_S390_PROGRAM_INT (vcpu)**

  - program check; code in parm

- **KVM_S390_SIGP_SET_PREFIX (vcpu)**

  - sigp set prefix; prefix address in parm

- **KVM_S390_RESTART (vcpu)**

  - restart

- **KVM_S390_INT_CLOCK_COMP (vcpu)**

  - clock comparator interrupt

- **KVM_S390_INT_CPU_TIMER (vcpu)**

  - CPU timer interrupt

- **KVM_S390_INT_VIRTIO (vm)**

  - virtio external interrupt; external interrupt parameters in parm and parm64

- **KVM_S390_INT_SERVICE (vm)**

  - sclp external interrupt; sclp parameter in parm

- **KVM_S390_INT_EMERGENCY (vcpu)**

  - sigp emergency; source cpu in parm

- **KVM_S390_INT_EXTERNAL_CALL (vcpu)**

  - sigp external call; source cpu in parm

- **KVM_S390_INT_IO(ai,cssid,ssid,schid) (vm)**

  - compound value to indicate an I/O interrupt (ai - adapter interrupt; cssid,ssid,schid - subchannel); I/O interruption parameters in parm (subchannel) and parm64 (intparm, interruption subclass)

- **KVM_S390_MCHK (vm, vcpu)**

  - machine check interrupt; cr 14 bits in parm, machine check interrupt code in parm64 (note that machine checks needing further payload are not supported by this ioctl)

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-kvm-ppc-get-htab-fd"></a>

### 4.78 KVM_PPC_GET_HTAB_FD

**Capability:** KVM_CAP_PPC_HTAB_FD

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** Pointer to struct kvm_get_htab_fd (in)

**Returns:** file descriptor number (&gt;= 0) on success, -1 on error

This returns a file descriptor that can be used either to read out the entries in the guest's hashed page table (HPT), or to write entries to initialize the HPT.  The returned fd can only be written to if the KVM_GET_HTAB_WRITE bit is set in the flags field of the argument, and can only be read if that bit is clear.  The argument struct looks like this:



```text
/* For KVM_PPC_GET_HTAB_FD */
struct kvm_get_htab_fd {
      __u64   flags;
      __u64   start_index;
      __u64   reserved[2];
};

/* Values for kvm_get_htab_fd.flags */
#define KVM_GET_HTAB_BOLTED_ONLY      ((__u64)0x1)
#define KVM_GET_HTAB_WRITE            ((__u64)0x2)
```

The 'start_index' field gives the index in the HPT of the entry at which to start reading.  It is ignored when writing.

Reads on the fd will initially supply information about all "interesting" HPT entries.  Interesting entries are those with the bolted bit set, if the KVM_GET_HTAB_BOLTED_ONLY bit is set, otherwise all entries.  When the end of the HPT is reached, the read() will return.  If read() is called again on the fd, it will start again from the beginning of the HPT, but will only return HPT entries that have changed since they were last read.

Data read or written is structured as a header (8 bytes) followed by a series of valid HPT entries (16 bytes) each.  The header indicates how many valid HPT entries there are and how many invalid entries follow the valid entries.  The invalid entries are not represented explicitly in the stream.  The header format is:



```text
struct kvm_get_htab_header {
      __u32   index;
      __u16   n_valid;
      __u16   n_invalid;
};
```

Writes to the fd create HPT entries starting at the index given in the header; first 'n_valid' valid entries with contents from the data written, then 'n_invalid' invalid entries, invalidating any previously valid entries found.

<a id="rst-kvm-create-device"></a>

### 4.79 KVM_CREATE_DEVICE

**Capability:** KVM_CAP_DEVICE_CTRL

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_create_device (in/out)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENODEV
>
> </td>
> <td>
>
>
> The device type is unknown or unsupported
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EEXIST
>
> </td>
> <td>
>
>
> Device already created, and this type of device may not be instantiated multiple times
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Other error conditions may be defined by individual device types or have their standard meanings.

Creates an emulated device in the kernel.  The file descriptor returned in fd can be used with KVM_SET/GET/HAS_DEVICE_ATTR.

If the KVM_CREATE_DEVICE_TEST flag is set, only test whether the device type is supported (not necessarily whether it can be created in the current vm).

Individual devices should not define flags.  Attributes should be used for specifying any behavior that is not implied by the device type number.



```text
struct kvm_create_device {
      __u32   type;   /* in: KVM_DEV_TYPE_xxx */
      __u32   fd;     /* out: device handle */
      __u32   flags;  /* in: KVM_CREATE_DEVICE_xxx */
};
```

<a id="rst-kvm-set-device-attr-kvm-get-device-attr"></a>

### 4.80 KVM_SET_DEVICE_ATTR/KVM_GET_DEVICE_ATTR

**Capability:** KVM_CAP_DEVICE_CTRL, KVM_CAP_VM_ATTRIBUTES for vm device, KVM_CAP_VCPU_ATTRIBUTES for vcpu device KVM_CAP_SYS_ATTRIBUTES for system (/dev/kvm) device (no set)

**Architectures:** x86, arm64, s390

**Type:** device ioctl, vm ioctl, vcpu ioctl

**Parameters:** struct kvm_device_attr

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENXIO
>
> </td>
> <td>
>
>
> The group or attribute is unknown/unsupported for this device or hardware support is missing.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EPERM
>
> </td>
> <td>
>
>
> The attribute cannot (currently) be accessed this way (e.g. read-only attribute, or attribute that only makes sense when the device is in a different state)
>
> </td>
> </tr>
> </tbody>
> </table>
>
> Other error conditions may be defined by individual device types.

Gets/sets a specified piece of device configuration and/or state.  The semantics are device-specific.  See individual device documentation in the "devices" directory.  As with ONE_REG, the size of the data transferred is defined by the particular attribute.



```text
struct kvm_device_attr {
      __u32   flags;          /* no flags currently defined */
      __u32   group;          /* device-defined */
      __u64   attr;           /* group-defined */
      __u64   addr;           /* userspace address of attr data */
};
```

<a id="rst-kvm-has-device-attr"></a>

### 4.81 KVM_HAS_DEVICE_ATTR

**Capability:** KVM_CAP_DEVICE_CTRL, KVM_CAP_VM_ATTRIBUTES for vm device, KVM_CAP_VCPU_ATTRIBUTES for vcpu device KVM_CAP_SYS_ATTRIBUTES for system (/dev/kvm) device

**Type:** device ioctl, vm ioctl, vcpu ioctl

**Parameters:** struct kvm_device_attr

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENXIO
>
> </td>
> <td>
>
>
> The group or attribute is unknown/unsupported for this device or hardware support is missing.
>
> </td>
> </tr>
> </tbody>
> </table>

Tests whether a device supports a particular attribute.  A successful return indicates the attribute is implemented.  It does not necessarily indicate that the attribute can be read or written in the device's current state.  "addr" is ignored.

<a id="rst-kvm-arm-vcpu-init-1"></a>
<a id="rst-kvm-arm-vcpu-init"></a>

### 4.82 KVM_ARM_VCPU_INIT

**Capability:** basic

**Architectures:** arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_vcpu_init (in)

**Returns:** 0 on success; -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> the target is unknown, or the combination of features is invalid.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOENT
>
> </td>
> <td>
>
>
> a features bit specified is unknown.
>
> </td>
> </tr>
> </tbody>
> </table>

This tells KVM what type of CPU to present to the guest, and what optional features it should have.  This will cause a reset of the cpu registers to their initial values.  If this is not called, KVM_RUN will return ENOEXEC for that vcpu.

- **The initial values are defined as:**

  - - **Processor state:**

      - AArch64: EL1h, D, A, I and F bits set. All other bits are cleared.

      - AArch32: SVC, A, I and F bits set. All other bits are cleared.

  - General Purpose registers, including PC and SP: set to 0

  - FPSIMD/NEON registers: set to 0

  - SVE registers: set to 0

  - System registers: Reset to their architecturally defined values as for a warm reset to EL1 (resp. SVC) or EL2 (in the case of EL2 being enabled).

Note that because some registers reflect machine topology, all vcpus should be created before this ioctl is invoked.

Userspace can call this function multiple times for a given vcpu, including after the vcpu has been run. This will reset the vcpu to its initial state. All calls to this function after the initial call must use the same target and same set of feature flags, otherwise EINVAL will be returned.

Possible features:

> - KVM_ARM_VCPU_POWER_OFF: Starts the CPU in a power-off state. Depends on KVM_CAP_ARM_PSCI.  If not set, the CPU will be powered on and execute guest code when KVM_RUN is called.
>
> - KVM_ARM_VCPU_EL1_32BIT: Starts the CPU in a 32bit mode. Depends on KVM_CAP_ARM_EL1_32BIT (arm64 only).
>
> - KVM_ARM_VCPU_PSCI_0_2: Emulate PSCI v0.2 (or a future revision backward compatible with v0.2) for the CPU. Depends on KVM_CAP_ARM_PSCI_0_2.
>
> - KVM_ARM_VCPU_PMU_V3: Emulate PMUv3 for the CPU. Depends on KVM_CAP_ARM_PMU_V3.
>
> - KVM_ARM_VCPU_PTRAUTH_ADDRESS: Enables Address Pointer authentication for arm64 only. Depends on KVM_CAP_ARM_PTRAUTH_ADDRESS. If KVM_CAP_ARM_PTRAUTH_ADDRESS and KVM_CAP_ARM_PTRAUTH_GENERIC are both present, then both KVM_ARM_VCPU_PTRAUTH_ADDRESS and KVM_ARM_VCPU_PTRAUTH_GENERIC must be requested or neither must be requested.
>
> - KVM_ARM_VCPU_PTRAUTH_GENERIC: Enables Generic Pointer authentication for arm64 only. Depends on KVM_CAP_ARM_PTRAUTH_GENERIC. If KVM_CAP_ARM_PTRAUTH_ADDRESS and KVM_CAP_ARM_PTRAUTH_GENERIC are both present, then both KVM_ARM_VCPU_PTRAUTH_ADDRESS and KVM_ARM_VCPU_PTRAUTH_GENERIC must be requested or neither must be requested.
>
> - KVM_ARM_VCPU_SVE: Enables SVE for the CPU (arm64 only). Depends on KVM_CAP_ARM_SVE. Requires KVM_ARM_VCPU_FINALIZE(KVM_ARM_VCPU_SVE):
>
>   > - After KVM_ARM_VCPU_INIT:
>   >
>   >   > - KVM_REG_ARM64_SVE_VLS may be read using KVM_GET_ONE_REG: the initial value of this pseudo-register indicates the best set of vector lengths possible for a vcpu on this host.
>   >
>   > - Before KVM_ARM_VCPU_FINALIZE(KVM_ARM_VCPU_SVE):
>   >
>   >   > - KVM_RUN and KVM_GET_REG_LIST are not available;
>   >   >
>   >   > - KVM_GET_ONE_REG and KVM_SET_ONE_REG cannot be used to access the scalable architectural SVE registers KVM_REG_ARM64_SVE_ZREG(), KVM_REG_ARM64_SVE_PREG() or KVM_REG_ARM64_SVE_FFR;
>   >   >
>   >   > - KVM_REG_ARM64_SVE_VLS may optionally be written using KVM_SET_ONE_REG, to modify the set of vector lengths available for the vcpu.
>   >
>   > - After KVM_ARM_VCPU_FINALIZE(KVM_ARM_VCPU_SVE):
>   >
>   >   > - the KVM_REG_ARM64_SVE_VLS pseudo-register is immutable, and can no longer be written using KVM_SET_ONE_REG.
>
> - KVM_ARM_VCPU_HAS_EL2: Enable Nested Virtualisation support, booting the guest from EL2 instead of EL1. Depends on KVM_CAP_ARM_EL2. The VM is running with HCR_EL2.E2H being RES1 (VHE) unless KVM_ARM_VCPU_HAS_EL2_E2H0 is also set.
>
> - KVM_ARM_VCPU_HAS_EL2_E2H0: Restrict Nested Virtualisation support to HCR_EL2.E2H being RES0 (non-VHE). Depends on KVM_CAP_ARM_EL2_E2H0. KVM_ARM_VCPU_HAS_EL2 must also be set.

<a id="rst-kvm-arm-preferred-target"></a>

### 4.83 KVM_ARM_PREFERRED_TARGET

**Capability:** basic

**Architectures:** arm64

**Type:** vm ioctl

**Parameters:** struct kvm_vcpu_init (out)

**Returns:** 0 on success; -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENODEV
>
> </td>
> <td>
>
>
> no preferred target available for the host
>
> </td>
> </tr>
> </tbody>
> </table>

This queries KVM for preferred CPU target type which can be emulated by KVM on underlying host.

The ioctl returns struct kvm_vcpu_init instance containing information about preferred CPU target type and recommended features for it.  The kvm_vcpu_init-&gt;features bitmap returned will have feature bits set if the preferred target recommends setting these features, but this is not mandatory.

The information returned by this ioctl can be used to prepare an instance of struct kvm_vcpu_init for KVM_ARM_VCPU_INIT ioctl which will result in VCPU matching underlying host.

<a id="rst-kvm-get-reg-list"></a>

### 4.84 KVM_GET_REG_LIST

**Capability:** basic

**Architectures:** arm64, mips, riscv, x86 (if KVM_CAP_ONE_REG)

**Type:** vcpu ioctl

**Parameters:** struct kvm_reg_list (in/out)

**Returns:** 0 on success; -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> E2BIG
>
> </td>
> <td>
>
>
> the reg index list is too big to fit in the array specified by the user (the number required will be written into n).
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_reg_list {
      __u64 n; /* number of registers in reg[] */
      __u64 reg[0];
};
```

This ioctl returns the guest registers that are supported for the KVM_GET_ONE_REG/KVM_SET_ONE_REG calls.

Note that s390 does not support KVM_GET_REG_LIST for historical reasons (read: nobody cared).  The set of registers in kernels 4.x and newer is:

- KVM_REG_S390_TODPR

- KVM_REG_S390_EPOCHDIFF

- KVM_REG_S390_CPU_TIMER

- KVM_REG_S390_CLOCK_COMP

- KVM_REG_S390_PFTOKEN

- KVM_REG_S390_PFCOMPARE

- KVM_REG_S390_PFSELECT

- KVM_REG_S390_PP

- KVM_REG_S390_GBEA

Note, for x86, all MSRs enumerated by KVM_GET_MSR_INDEX_LIST are supported as type KVM_X86_REG_TYPE_MSR, but are NOT enumerated via KVM_GET_REG_LIST.

<a id="rst-kvm-arm-set-device-addr-deprecated"></a>

### 4.85 KVM_ARM_SET_DEVICE_ADDR (deprecated)

**Capability:** KVM_CAP_ARM_SET_DEVICE_ADDR

**Architectures:** arm64

**Type:** vm ioctl

**Parameters:** struct kvm_arm_device_address (in)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENODEV
>
> </td>
> <td>
>
>
> The device id is unknown
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENXIO
>
> </td>
> <td>
>
>
> Device not supported on current system
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EEXIST
>
> </td>
> <td>
>
>
> Address already set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> E2BIG
>
> </td>
> <td>
>
>
> Address outside guest physical address space
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EBUSY
>
> </td>
> <td>
>
>
> Address overlaps with other device range
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_arm_device_addr {
      __u64 id;
      __u64 addr;
};
```

Specify a device address in the guest's physical address space where guests can access emulated or directly exposed devices, which the host kernel needs to know about. The id field is an architecture specific identifier for a specific device.

arm64 divides the id field into two parts, a device id and an address type id specific to the individual device:



```text
bits:  | 63        ...       32 | 31    ...    16 | 15    ...    0 |
field: |        0x00000000      |     device id   |  addr type id  |
```

arm64 currently only require this when using the in-kernel GIC support for the hardware VGIC features, using KVM_ARM_DEVICE_VGIC_V2 as the device id.  When setting the base address for the guest's mapping of the VGIC virtual CPU and distributor interface, the ioctl must be called after calling KVM_CREATE_IRQCHIP, but before calling KVM_RUN on any of the VCPUs.  Calling this ioctl twice for any of the base addresses will return -EEXIST.

Note, this IOCTL is deprecated and the more flexible SET/GET_DEVICE_ATTR API should be used instead.

<a id="rst-kvm-ppc-rtas-define-token"></a>

### 4.86 KVM_PPC_RTAS_DEFINE_TOKEN

**Capability:** KVM_CAP_PPC_RTAS

**Architectures:** ppc

**Type:** vm ioctl

**Parameters:** struct kvm_rtas_token_args

**Returns:** 0 on success, -1 on error

Defines a token value for a RTAS (Run Time Abstraction Services) service in order to allow it to be handled in the kernel.  The argument struct gives the name of the service, which must be the name of a service that has a kernel-side implementation.  If the token value is non-zero, it will be associated with that service, and subsequent RTAS calls by the guest specifying that token will be handled by the kernel.  If the token value is 0, then any token associated with the service will be forgotten, and subsequent RTAS calls by the guest for that service will be passed to userspace to be handled.

<a id="rst-kvm-set-guest-debug"></a>

### 4.87 KVM_SET_GUEST_DEBUG

**Capability:** KVM_CAP_SET_GUEST_DEBUG

**Architectures:** x86, s390, ppc, arm64

**Type:** vcpu ioctl

**Parameters:** struct kvm_guest_debug (in)

**Returns:** 0 on success; -1 on error



```text
struct kvm_guest_debug {
     __u32 control;
     __u32 pad;
     struct kvm_guest_debug_arch arch;
};
```

Set up the processor specific debug registers and configure vcpu for handling guest debug events. There are two parts to the structure, the first a control bitfield indicates the type of debug events to handle when running. Common control bits are:

> - KVM_GUESTDBG_ENABLE:        guest debugging is enabled
>
> - KVM_GUESTDBG_SINGLESTEP:    the next run should single-step

The top 16 bits of the control field are architecture specific control flags which can include the following:

> - KVM_GUESTDBG_USE_SW_BP:     using software breakpoints \[x86, arm64\]
>
> - KVM_GUESTDBG_USE_HW_BP:     using hardware breakpoints \[x86, s390\]
>
> - KVM_GUESTDBG_USE_HW:        using hardware debug events \[arm64\]
>
> - KVM_GUESTDBG_INJECT_DB:     inject DB type exception \[x86\]
>
> - KVM_GUESTDBG_INJECT_BP:     inject BP type exception \[x86\]
>
> - KVM_GUESTDBG_EXIT_PENDING:  trigger an immediate guest exit \[s390\]
>
> - KVM_GUESTDBG_BLOCKIRQ:      avoid injecting interrupts/NMI/SMI \[x86\]

For example KVM_GUESTDBG_USE_SW_BP indicates that software breakpoints are enabled in memory so we need to ensure breakpoint exceptions are correctly trapped and the KVM run loop exits at the breakpoint and not running off into the normal guest vector. For KVM_GUESTDBG_USE_HW_BP we need to ensure the guest vCPUs architecture specific registers are updated to the correct (supplied) values.

The second part of the structure is architecture specific and typically contains a set of debug registers.

For arm64 the number of debug registers is implementation defined and can be determined by querying the KVM_CAP_GUEST_DEBUG_HW_BPS and KVM_CAP_GUEST_DEBUG_HW_WPS capabilities which return a positive number indicating the number of supported registers.

For ppc, the KVM_CAP_PPC_GUEST_DEBUG_SSTEP capability indicates whether the single-step debug event (KVM_GUESTDBG_SINGLESTEP) is supported.

Also when supported, KVM_CAP_SET_GUEST_DEBUG2 capability indicates the supported KVM_GUESTDBG\_\* bits in the control field.

When debug events exit the main run loop with the reason KVM_EXIT_DEBUG with the kvm_debug_exit_arch part of the kvm_run structure containing architecture specific debug information.

<a id="rst-kvm-get-emulated-cpuid"></a>

### 4.88 KVM_GET_EMULATED_CPUID

**Capability:** KVM_CAP_EXT_EMUL_CPUID

**Architectures:** x86

**Type:** system ioctl

**Parameters:** struct kvm_cpuid2 (in/out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_cpuid2 {
      __u32 nent;
      __u32 flags;
      struct kvm_cpuid_entry2 entries[0];
};
```

The member 'flags' is used for passing flags from userspace.



```text
#define KVM_CPUID_FLAG_SIGNIFCANT_INDEX               BIT(0)
#define KVM_CPUID_FLAG_STATEFUL_FUNC          BIT(1) /* deprecated */
#define KVM_CPUID_FLAG_STATE_READ_NEXT                BIT(2) /* deprecated */

struct kvm_cpuid_entry2 {
      __u32 function;
      __u32 index;
      __u32 flags;
      __u32 eax;
      __u32 ebx;
      __u32 ecx;
      __u32 edx;
      __u32 padding[3];
};
```

This ioctl returns x86 cpuid features which are emulated by kvm.Userspace can use the information returned by this ioctl to query which features are emulated by kvm instead of being present natively.

Userspace invokes KVM_GET_EMULATED_CPUID by passing a kvm_cpuid2 structure with the 'nent' field indicating the number of entries in the variable-size array 'entries'. If the number of entries is too low to describe the cpu capabilities, an error (E2BIG) is returned. If the number is too high, the 'nent' field is adjusted and an error (ENOMEM) is returned. If the number is just right, the 'nent' field is adjusted to the number of valid entries in the 'entries' array, which is then filled.

The entries returned are the set CPUID bits of the respective features which kvm emulates, as returned by the CPUID instruction, with unknown or unsupported feature bits cleared.

Features like x2apic, for example, may not be present in the host cpu but are exposed by kvm in KVM_GET_SUPPORTED_CPUID because they can be emulated efficiently and thus not included here.

The fields in each entry are defined as follows:

> - **function:**
>
>   the eax value used to obtain the entry
>
> - **index:**
>
>   the ecx value used to obtain the entry (for entries that are affected by ecx)
>
> - **flags:**
>
>   > an OR of zero or more of the following:
>   >
>   > > - **KVM_CPUID_FLAG_SIGNIFCANT_INDEX:**
>   > >
>   > >   if the index field is valid
>
>   eax, ebx, ecx, edx:
>
>   > the values returned by the cpuid instruction for this function/index combination

<a id="rst-kvm-s390-mem-op"></a>

### 4.89 KVM_S390_MEM_OP

**Capability:** KVM_CAP_S390_MEM_OP, KVM_CAP_S390_PROTECTED, KVM_CAP_S390_MEM_OP_EXTENSION

**Architectures:** s390

**Type:** vm ioctl, vcpu ioctl

**Parameters:** struct kvm_s390_mem_op (in)

**Returns:** = 0 on success, &lt; 0 on generic error (e.g. -EFAULT or -ENOMEM), 16 bit program exception code if the access causes such an exception

Read or write data from/to the VM's memory. The KVM_CAP_S390_MEM_OP_EXTENSION capability specifies what functionality is supported.

Parameters are specified via the following structure:



```text
struct kvm_s390_mem_op {
      __u64 gaddr;            /* the guest address */
      __u64 flags;            /* flags */
      __u32 size;             /* amount of bytes */
      __u32 op;               /* type of operation */
      __u64 buf;              /* buffer in userspace */
      union {
              struct {
                      __u8 ar;        /* the access register number */
                      __u8 key;       /* access key, ignored if flag unset */
                      __u8 pad1[6];   /* ignored */
                      __u64 old_addr; /* ignored if flag unset */
              };
              __u32 sida_offset; /* offset into the sida */
              __u8 reserved[32]; /* ignored */
      };
};
```

The start address of the memory region has to be specified in the "gaddr" field, and the length of the region in the "size" field (which must not be 0). The maximum value for "size" can be obtained by checking the KVM_CAP_S390_MEM_OP capability. "buf" is the buffer supplied by the userspace application where the read data should be written to for a read access, or where the data that should be written is stored for a write access.  The "reserved" field is meant for future extensions. Reserved and unused values are ignored. Future extension that add members must introduce new flags.

The type of operation is specified in the "op" field. Flags modifying their behavior can be set in the "flags" field. Undefined flag bits must be set to 0.

- **Possible operations are:**

  - `KVM_S390_MEMOP_LOGICAL_READ`

  - `KVM_S390_MEMOP_LOGICAL_WRITE`

  - `KVM_S390_MEMOP_ABSOLUTE_READ`

  - `KVM_S390_MEMOP_ABSOLUTE_WRITE`

  - `KVM_S390_MEMOP_SIDA_READ`

  - `KVM_S390_MEMOP_SIDA_WRITE`

  - `KVM_S390_MEMOP_ABSOLUTE_CMPXCHG`

<a id="rst-logical-read-write"></a>

#### Logical read/write:

Access logical memory, i.e. translate the given guest address to an absolute address given the state of the VCPU and use the absolute address as target of the access. "ar" designates the access register number to be used; the valid range is 0..15. Logical accesses are permitted for the VCPU ioctl only. Logical accesses are permitted for non-protected guests only.

- **Supported flags:**

  - `KVM_S390_MEMOP_F_CHECK_ONLY`

  - `KVM_S390_MEMOP_F_INJECT_EXCEPTION`

  - `KVM_S390_MEMOP_F_SKEY_PROTECTION`

The KVM_S390_MEMOP_F_CHECK_ONLY flag can be set to check whether the corresponding memory access would cause an access exception; however, no actual access to the data in memory at the destination is performed. In this case, "buf" is unused and can be NULL.

In case an access exception occurred during the access (or would occur in case of KVM_S390_MEMOP_F_CHECK_ONLY), the ioctl returns a positive error number indicating the type of exception. This exception is also raised directly at the corresponding VCPU if the flag KVM_S390_MEMOP_F_INJECT_EXCEPTION is set. On protection exceptions, unless specified otherwise, the injected translation-exception identifier (TEID) indicates suppression.

If the KVM_S390_MEMOP_F_SKEY_PROTECTION flag is set, storage key protection is also in effect and may cause exceptions if accesses are prohibited given the access key designated by "key"; the valid range is 0..15. KVM_S390_MEMOP_F_SKEY_PROTECTION is available if KVM_CAP_S390_MEM_OP_EXTENSION is &gt; 0. Since the accessed memory may span multiple pages and those pages might have different storage keys, it is possible that a protection exception occurs after memory has been modified. In this case, if the exception is injected, the TEID does not indicate suppression.

<a id="rst-absolute-read-write"></a>

#### Absolute read/write:

Access absolute memory. This operation is intended to be used with the KVM_S390_MEMOP_F_SKEY_PROTECTION flag, to allow accessing memory and performing the checks required for storage key protection as one operation (as opposed to user space getting the storage keys, performing the checks, and accessing memory thereafter, which could lead to a delay between check and access). Absolute accesses are permitted for the VM ioctl if KVM_CAP_S390_MEM_OP_EXTENSION has the KVM_S390_MEMOP_EXTENSION_CAP_BASE bit set. Currently absolute accesses are not permitted for VCPU ioctls. Absolute accesses are permitted for non-protected guests only.

- **Supported flags:**

  - `KVM_S390_MEMOP_F_CHECK_ONLY`

  - `KVM_S390_MEMOP_F_SKEY_PROTECTION`

The semantics of the flags common with logical accesses are as for logical accesses.

<a id="rst-absolute-cmpxchg"></a>

#### Absolute cmpxchg:

Perform cmpxchg on absolute guest memory. Intended for use with the KVM_S390_MEMOP_F_SKEY_PROTECTION flag. Instead of doing an unconditional write, the access occurs only if the target location contains the value pointed to by "old_addr". This is performed as an atomic cmpxchg with the length specified by the "size" parameter. "size" must be a power of two up to and including 16. If the exchange did not take place because the target value doesn't match the old value, the value "old_addr" points to is replaced by the target value. User space can tell if an exchange took place by checking if this replacement occurred. The cmpxchg op is permitted for the VM ioctl if KVM_CAP_S390_MEM_OP_EXTENSION has flag KVM_S390_MEMOP_EXTENSION_CAP_CMPXCHG set.

- **Supported flags:**

  - `KVM_S390_MEMOP_F_SKEY_PROTECTION`

<a id="rst-sida-read-write"></a>

#### SIDA read/write:

Access the secure instruction data area which contains memory operands necessary for instruction emulation for protected guests. SIDA accesses are available if the KVM_CAP_S390_PROTECTED capability is available. SIDA accesses are permitted for the VCPU ioctl only. SIDA accesses are permitted for protected guests only.

No flags are supported.

<a id="rst-kvm-s390-get-skeys"></a>

### 4.90 KVM_S390_GET_SKEYS

**Capability:** KVM_CAP_S390_SKEYS

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_skeys

**Returns:** 0 on success, KVM_S390_GET_SKEYS_NONE if guest is not using storage keys, negative value on error

This ioctl is used to get guest storage key values on the s390 architecture. The ioctl takes parameters via the kvm_s390_skeys struct:



```text
struct kvm_s390_skeys {
      __u64 start_gfn;
      __u64 count;
      __u64 skeydata_addr;
      __u32 flags;
      __u32 reserved[9];
};
```

The start_gfn field is the number of the first guest frame whose storage keys you want to get.

The count field is the number of consecutive frames (starting from start_gfn) whose storage keys to get. The count field must be at least 1 and the maximum allowed value is defined as KVM_S390_SKEYS_MAX. Values outside this range will cause the ioctl to return -EINVAL.

The skeydata_addr field is the address to a buffer large enough to hold count bytes. This buffer will be filled with storage key data by the ioctl.

<a id="rst-kvm-s390-set-skeys"></a>

### 4.91 KVM_S390_SET_SKEYS

**Capability:** KVM_CAP_S390_SKEYS

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_skeys

**Returns:** 0 on success, negative value on error

This ioctl is used to set guest storage key values on the s390 architecture. The ioctl takes parameters via the kvm_s390_skeys struct. See section on KVM_S390_GET_SKEYS for struct definition.

The start_gfn field is the number of the first guest frame whose storage keys you want to set.

The count field is the number of consecutive frames (starting from start_gfn) whose storage keys to get. The count field must be at least 1 and the maximum allowed value is defined as KVM_S390_SKEYS_MAX. Values outside this range will cause the ioctl to return -EINVAL.

The skeydata_addr field is the address to a buffer containing count bytes of storage keys. Each byte in the buffer will be set as the storage key for a single frame starting at start_gfn for count frames.

Note: If any architecturally invalid key value is found in the given data then the ioctl will return -EINVAL.

<a id="rst-kvm-s390-irq"></a>

### 4.92 KVM_S390_IRQ

**Capability:** KVM_CAP_S390_INJECT_IRQ

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** struct kvm_s390_irq (in)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> interrupt type is invalid type is KVM_S390_SIGP_STOP and flag parameter is invalid value, type is KVM_S390_INT_EXTERNAL_CALL and code is bigger than the maximum of VCPUs
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EBUSY
>
> </td>
> <td>
>
>
> type is KVM_S390_SIGP_SET_PREFIX and vcpu is not stopped, type is KVM_S390_SIGP_STOP and a stop irq is already pending, type is KVM_S390_INT_EXTERNAL_CALL and an external call interrupt is already pending
>
> </td>
> </tr>
> </tbody>
> </table>

Allows to inject an interrupt to the guest.

Using struct kvm_s390_irq as a parameter allows to inject additional payload which is not possible via KVM_S390_INTERRUPT.

Interrupt parameters are passed via kvm_s390_irq:



```text
struct kvm_s390_irq {
      __u64 type;
      union {
              struct kvm_s390_io_info io;
              struct kvm_s390_ext_info ext;
              struct kvm_s390_pgm_info pgm;
              struct kvm_s390_emerg_info emerg;
              struct kvm_s390_extcall_info extcall;
              struct kvm_s390_prefix_info prefix;
              struct kvm_s390_stop_info stop;
              struct kvm_s390_mchk_info mchk;
              char reserved[64];
      } u;
};
```

type can be one of the following:

- KVM_S390_SIGP_STOP - sigp stop; parameter in .stop

- KVM_S390_PROGRAM_INT - program check; parameters in .pgm

- KVM_S390_SIGP_SET_PREFIX - sigp set prefix; parameters in .prefix

- KVM_S390_RESTART - restart; no parameters

- KVM_S390_INT_CLOCK_COMP - clock comparator interrupt; no parameters

- KVM_S390_INT_CPU_TIMER - CPU timer interrupt; no parameters

- KVM_S390_INT_EMERGENCY - sigp emergency; parameters in .emerg

- KVM_S390_INT_EXTERNAL_CALL - sigp external call; parameters in .extcall

- KVM_S390_MCHK - machine check interrupt; parameters in .mchk

This is an asynchronous vcpu ioctl and can be invoked from any thread.

<a id="rst-kvm-s390-get-irq-state"></a>

### 4.94 KVM_S390_GET_IRQ_STATE

**Capability:** KVM_CAP_S390_IRQ_STATE

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** struct kvm_s390_irq_state (out)

**Returns:** &gt;= number of bytes copied into buffer, -EINVAL if buffer size is 0, -ENOBUFS if buffer size is too small to fit all pending interrupts, -EFAULT if the buffer address was invalid

This ioctl allows userspace to retrieve the complete state of all currently pending interrupts in a single buffer. Use cases include migration and introspection. The parameter structure contains the address of a userspace buffer and its length:



```text
struct kvm_s390_irq_state {
      __u64 buf;
      __u32 flags;        /* will stay unused for compatibility reasons */
      __u32 len;
      __u32 reserved[4];  /* will stay unused for compatibility reasons */
};
```

Userspace passes in the above struct and for each pending interrupt a struct kvm_s390_irq is copied to the provided buffer.

The structure contains a flags and a reserved field for future extensions. As the kernel never checked for flags == 0 and QEMU never pre-zeroed flags and reserved, these fields can not be used in the future without breaking compatibility.

If -ENOBUFS is returned the buffer provided was too small and userspace may retry with a bigger buffer.

<a id="rst-kvm-s390-set-irq-state"></a>

### 4.95 KVM_S390_SET_IRQ_STATE

**Capability:** KVM_CAP_S390_IRQ_STATE

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** struct kvm_s390_irq_state (in)

**Returns:** 0 on success, -EFAULT if the buffer address was invalid, -EINVAL for an invalid buffer length (see below), -EBUSY if there were already interrupts pending, errors occurring when actually injecting the interrupt. See KVM_S390_IRQ.

This ioctl allows userspace to set the complete state of all cpu-local interrupts currently pending for the vcpu. It is intended for restoring interrupt state after a migration. The input parameter is a userspace buffer containing a struct kvm_s390_irq_state:



```text
struct kvm_s390_irq_state {
      __u64 buf;
      __u32 flags;        /* will stay unused for compatibility reasons */
      __u32 len;
      __u32 reserved[4];  /* will stay unused for compatibility reasons */
};
```

The restrictions for flags and reserved apply as well. (see KVM_S390_GET_IRQ_STATE)

The userspace memory referenced by buf contains a struct kvm_s390_irq for each interrupt to be injected into the guest. If one of the interrupts could not be injected for some reason the ioctl aborts.

len must be a multiple of sizeof(struct kvm_s390_irq). It must be &gt; 0 and it must not exceed (max_vcpus + 32) \* sizeof(struct kvm_s390_irq), which is the maximum number of possibly pending cpu-local interrupts.

<a id="rst-kvm-smi"></a>

### 4.96 KVM_SMI

**Capability:** KVM_CAP_X86_SMM

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0 on success, -1 on error

Queues an SMI on the thread's vcpu.

<a id="rst-kvm-x86-set-msr-filter"></a>

### 4.97 KVM_X86_SET_MSR_FILTER

**Capability:** KVM_CAP_X86_MSR_FILTER

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_msr_filter

**Returns:** 0 on success, &lt; 0 on error



```text
struct kvm_msr_filter_range {
#define KVM_MSR_FILTER_READ  (1 << 0)
#define KVM_MSR_FILTER_WRITE (1 << 1)
      __u32 flags;
      __u32 nmsrs; /* number of msrs in bitmap */
      __u32 base;  /* MSR index the bitmap starts at */
      __u8 *bitmap; /* a 1 bit allows the operations in flags, 0 denies */
};

#define KVM_MSR_FILTER_MAX_RANGES 16
struct kvm_msr_filter {
#define KVM_MSR_FILTER_DEFAULT_ALLOW (0 << 0)
#define KVM_MSR_FILTER_DEFAULT_DENY  (1 << 0)
      __u32 flags;
      struct kvm_msr_filter_range ranges[KVM_MSR_FILTER_MAX_RANGES];
};
```

flags values for `struct kvm_msr_filter_range`:

`KVM_MSR_FILTER_READ`

> Filter read accesses to MSRs using the given bitmap. A 0 in the bitmap indicates that read accesses should be denied, while a 1 indicates that a read for a particular MSR should be allowed regardless of the default filter action.

`KVM_MSR_FILTER_WRITE`

> Filter write accesses to MSRs using the given bitmap. A 0 in the bitmap indicates that write accesses should be denied, while a 1 indicates that a write for a particular MSR should be allowed regardless of the default filter action.

flags values for `struct kvm_msr_filter`:

`KVM_MSR_FILTER_DEFAULT_ALLOW`

> If no filter range matches an MSR index that is getting accessed, KVM will allow accesses to all MSRs by default.

`KVM_MSR_FILTER_DEFAULT_DENY`

> If no filter range matches an MSR index that is getting accessed, KVM will deny accesses to all MSRs by default.

This ioctl allows userspace to define up to 16 bitmaps of MSR ranges to deny guest MSR accesses that would normally be allowed by KVM.  If an MSR is not covered by a specific range, the "default" filtering behavior applies.  Each bitmap range covers MSRs from \[base .. base+nmsrs).

If an MSR access is denied by userspace, the resulting KVM behavior depends on whether or not KVM_CAP_X86_USER_SPACE_MSR's KVM_MSR_EXIT_REASON_FILTER is enabled.  If KVM_MSR_EXIT_REASON_FILTER is enabled, KVM will exit to userspace on denied accesses, i.e. userspace effectively intercepts the MSR access.  If KVM_MSR_EXIT_REASON_FILTER is not enabled, KVM will inject a \#GP into the guest on denied accesses.  Note, if an MSR access is denied during emulation of MSR load/stores during VMX transitions, KVM ignores KVM_MSR_EXIT_REASON_FILTER. See the below warning for full details.

If an MSR access is allowed by userspace, KVM will emulate and/or virtualize the access in accordance with the vCPU model.  Note, KVM may still ultimately inject a \#GP if an access is allowed by userspace, e.g. if KVM doesn't support the MSR, or to follow architectural behavior for the MSR.

By default, KVM operates in KVM_MSR_FILTER_DEFAULT_ALLOW mode with no MSR range filters.

Calling this ioctl with an empty set of ranges (all nmsrs == 0) disables MSR filtering. In that mode, `KVM_MSR_FILTER_DEFAULT_DENY` is invalid and causes an error.

> [!WARNING]
>
> MSR accesses that are side effects of instruction execution (emulated or native) are not filtered as hardware does not honor MSR bitmaps outside of RDMSR and WRMSR, and KVM mimics that behavior when emulating instructions to avoid pointless divergence from hardware.  E.g. RDPID reads MSR_TSC_AUX, SYSENTER reads the SYSENTER MSRs, etc.
>
> MSRs that are loaded/stored via dedicated VMCS fields are not filtered as part of VM-Enter/VM-Exit emulation.
>
> MSRs that are loaded/store via VMX's load/store lists \_are\_ filtered as part of VM-Enter/VM-Exit emulation.  If an MSR access is denied on VM-Enter, KVM synthesizes a consistency check VM-Exit(EXIT_REASON_MSR_LOAD_FAIL).  If an MSR access is denied on VM-Exit, KVM synthesizes a VM-Abort.  In short, KVM extends Intel's architectural list of MSRs that cannot be loaded/saved via the VM-Enter/VM-Exit MSR list.  It is platform owner's responsibility to to communicate any such restrictions to their end users.
>
> x2APIC MSR accesses cannot be filtered (KVM silently ignores filters that cover any x2APIC MSRs).

Note, invoking this ioctl while a vCPU is running is inherently racy.  However, KVM does guarantee that vCPUs will see either the previous filter or the new filter, e.g. MSRs with identical settings in both the old and new filter will have deterministic behavior.

Similarly, if userspace wishes to intercept on denied accesses, KVM_MSR_EXIT_REASON_FILTER must be enabled before activating any filters, and left enabled until after all filters are deactivated.  Failure to do so may result in KVM injecting a \#GP instead of exiting to userspace.

<a id="rst-kvm-create-spapr-tce-64"></a>

### 4.98 KVM_CREATE_SPAPR_TCE_64

**Capability:** KVM_CAP_SPAPR_TCE_64

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** struct kvm_create_spapr_tce_64 (in)

**Returns:** file descriptor for manipulating the created TCE table

This is an extension for KVM_CAP_SPAPR_TCE which only supports 32bit windows, described in 4.62 KVM_CREATE_SPAPR_TCE

This capability uses extended struct in ioctl interface:



```text
/* for KVM_CAP_SPAPR_TCE_64 */
struct kvm_create_spapr_tce_64 {
      __u64 liobn;
      __u32 page_shift;
      __u32 flags;
      __u64 offset;   /* in pages */
      __u64 size;     /* in pages */
};
```

The aim of extension is to support an additional bigger DMA window with a variable page size. KVM_CREATE_SPAPR_TCE_64 receives a 64bit window size, an IOMMU page shift and a bus offset of the corresponding DMA window, @size and @offset are numbers of IOMMU pages.

@flags are not used at the moment.

The rest of functionality is identical to KVM_CREATE_SPAPR_TCE.

<a id="rst-kvm-reinject-control"></a>

### 4.99 KVM_REINJECT_CONTROL

**Capability:** KVM_CAP_REINJECT_CONTROL

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_reinject_control (in)

**Returns:** 0 on success, -EFAULT if struct kvm_reinject_control cannot be read, -ENXIO if KVM_CREATE_PIT or KVM_CREATE_PIT2 didn't succeed earlier.

i8254 (PIT) has two modes, reinject and \!reinject.  The default is reinject, where KVM queues elapsed i8254 ticks and monitors completion of interrupt from vector(s) that i8254 injects.  Reinject mode dequeues a tick and injects its interrupt whenever there isn't a pending interrupt from i8254. \!reinject mode injects an interrupt as soon as a tick arrives.



```text
struct kvm_reinject_control {
      __u8 pit_reinject;
      __u8 reserved[31];
};
```

pit_reinject = 0 (\!reinject mode) is recommended, unless running an old operating system that uses the PIT for timing (e.g. Linux 2.4.x).

<a id="rst-kvm-ppc-configure-v3-mmu"></a>

### 4.100 KVM_PPC_CONFIGURE_V3_MMU

**Capability:** KVM_CAP_PPC_MMU_RADIX or KVM_CAP_PPC_MMU_HASH_V3

**Architectures:** ppc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_mmuv3_cfg (in)

**Returns:** 0 on success, -EFAULT if struct kvm_ppc_mmuv3_cfg cannot be read, -EINVAL if the configuration is invalid

This ioctl controls whether the guest will use radix or HPT (hashed page table) translation, and sets the pointer to the process table for the guest.



```text
struct kvm_ppc_mmuv3_cfg {
      __u64   flags;
      __u64   process_table;
};
```

There are two bits that can be set in flags; KVM_PPC_MMUV3_RADIX and KVM_PPC_MMUV3_GTSE.  KVM_PPC_MMUV3_RADIX, if set, configures the guest to use radix tree translation, and if clear, to use HPT translation. KVM_PPC_MMUV3_GTSE, if set and if KVM permits it, configures the guest to be able to use the global TLB and SLB invalidation instructions; if clear, the guest may not use these instructions.

The process_table field specifies the address and size of the guest process table, which is in the guest's space.  This field is formatted as the second doubleword of the partition table entry, as defined in the Power ISA V3.00, Book III section 5.7.6.1.

<a id="rst-kvm-ppc-get-rmmu-info"></a>

### 4.101 KVM_PPC_GET_RMMU_INFO

**Capability:** KVM_CAP_PPC_MMU_RADIX

**Architectures:** ppc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_rmmu_info (out)

**Returns:** 0 on success, -EFAULT if struct kvm_ppc_rmmu_info cannot be written, -EINVAL if no useful information can be returned

This ioctl returns a structure containing two things: (a) a list containing supported radix tree geometries, and (b) a list that maps page sizes to put in the "AP" (actual page size) field for the tlbie (TLB invalidate entry) instruction.



```text
struct kvm_ppc_rmmu_info {
      struct kvm_ppc_radix_geom {
              __u8    page_shift;
              __u8    level_bits[4];
              __u8    pad[3];
      }       geometries[8];
      __u32   ap_encodings[8];
};
```

The geometries\[\] field gives up to 8 supported geometries for the radix page table, in terms of the log base 2 of the smallest page size, and the number of bits indexed at each level of the tree, from the PTE level up to the PGD level in that order.  Any unused entries will have 0 in the page_shift field.

The ap_encodings gives the supported page sizes and their AP field encodings, encoded with the AP value in the top 3 bits and the log base 2 of the page size in the bottom 6 bits.

<a id="rst-kvm-ppc-resize-hpt-prepare"></a>

### 4.102 KVM_PPC_RESIZE_HPT_PREPARE

**Capability:** KVM_CAP_SPAPR_RESIZE_HPT

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_resize_hpt (in)

**Returns:** 0 on successful completion, &gt;0 if a new HPT is being prepared, the value is an estimated number of milliseconds until preparation is complete, -EFAULT if struct kvm_reinject_control cannot be read, -EINVAL if the supplied shift or flags are invalid, -ENOMEM if unable to allocate the new HPT,

Used to implement the PAPR extension for runtime resizing of a guest's Hashed Page Table (HPT).  Specifically this starts, stops or monitors the preparation of a new potential HPT for the guest, essentially implementing the H_RESIZE_HPT_PREPARE hypercall.



```text
struct kvm_ppc_resize_hpt {
      __u64 flags;
      __u32 shift;
      __u32 pad;
};
```

If called with shift &gt; 0 when there is no pending HPT for the guest, this begins preparation of a new pending HPT of size 2^(shift) bytes. It then returns a positive integer with the estimated number of milliseconds until preparation is complete.

If called when there is a pending HPT whose size does not match that requested in the parameters, discards the existing pending HPT and creates a new one as above.

If called when there is a pending HPT of the size requested, will:

> - If preparation of the pending HPT is already complete, return 0
>
> - If preparation of the pending HPT has failed, return an error code, then discard the pending HPT.
>
> - If preparation of the pending HPT is still in progress, return an estimated number of milliseconds until preparation is complete.

If called with shift == 0, discards any currently pending HPT and returns 0 (i.e. cancels any in-progress preparation).

flags is reserved for future expansion, currently setting any bits in flags will result in an -EINVAL.

Normally this will be called repeatedly with the same parameters until it returns &lt;= 0.  The first call will initiate preparation, subsequent ones will monitor preparation until it completes or fails.

<a id="rst-kvm-ppc-resize-hpt-commit"></a>

### 4.103 KVM_PPC_RESIZE_HPT_COMMIT

**Capability:** KVM_CAP_SPAPR_RESIZE_HPT

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_resize_hpt (in)

**Returns:** 0 on successful completion, -EFAULT if struct kvm_reinject_control cannot be read, -EINVAL if the supplied shift or flags are invalid, -ENXIO is there is no pending HPT, or the pending HPT doesn't have the requested size, -EBUSY if the pending HPT is not fully prepared, -ENOSPC if there was a hash collision when moving existing HPT entries to the new HPT, -EIO on other error conditions

Used to implement the PAPR extension for runtime resizing of a guest's Hashed Page Table (HPT).  Specifically this requests that the guest be transferred to working with the new HPT, essentially implementing the H_RESIZE_HPT_COMMIT hypercall.



```text
struct kvm_ppc_resize_hpt {
      __u64 flags;
      __u32 shift;
      __u32 pad;
};
```

This should only be called after KVM_PPC_RESIZE_HPT_PREPARE has returned 0 with the same parameters.  In other cases KVM_PPC_RESIZE_HPT_COMMIT will return an error (usually -ENXIO or -EBUSY, though others may be possible if the preparation was started, but failed).

This will have undefined effects on the guest if it has not already placed itself in a quiescent state where no vcpu will make MMU enabled memory accesses.

On successful completion, the pending HPT will become the guest's active HPT and the previous HPT will be discarded.

On failure, the guest will still be operating on its previous HPT.

<a id="rst-kvm-x86-get-mce-cap-supported"></a>

### 4.104 KVM_X86_GET_MCE_CAP_SUPPORTED

**Capability:** KVM_CAP_MCE

**Architectures:** x86

**Type:** system ioctl

**Parameters:** u64 mce_cap (out)

**Returns:** 0 on success, -1 on error

Returns supported MCE capabilities. The u64 mce_cap parameter has the same format as the MSR_IA32_MCG_CAP register. Supported capabilities will have the corresponding bits set.

<a id="rst-kvm-x86-setup-mce"></a>

### 4.105 KVM_X86_SETUP_MCE

**Capability:** KVM_CAP_MCE

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** u64 mcg_cap (in)

**Returns:** 0 on success, -EFAULT if u64 mcg_cap cannot be read, -EINVAL if the requested number of banks is invalid, -EINVAL if requested MCE capability is not supported.

Initializes MCE support for use. The u64 mcg_cap parameter has the same format as the MSR_IA32_MCG_CAP register and specifies which capabilities should be enabled. The maximum supported number of error-reporting banks can be retrieved when checking for KVM_CAP_MCE. The supported capabilities can be retrieved with KVM_X86_GET_MCE_CAP_SUPPORTED.

<a id="rst-kvm-x86-set-mce"></a>

### 4.106 KVM_X86_SET_MCE

**Capability:** KVM_CAP_MCE

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_x86_mce (in)

**Returns:** 0 on success, -EFAULT if struct kvm_x86_mce cannot be read, -EINVAL if the bank number is invalid, -EINVAL if VAL bit is not set in status field.

Inject a machine check error (MCE) into the guest. The input parameter is:



```text
struct kvm_x86_mce {
      __u64 status;
      __u64 addr;
      __u64 misc;
      __u64 mcg_status;
      __u8 bank;
      __u8 pad1[7];
      __u64 pad2[3];
};
```

If the MCE being reported is an uncorrected error, KVM will inject it as an MCE exception into the guest. If the guest MCG_STATUS register reports that an MCE is in progress, KVM causes an KVM_EXIT_SHUTDOWN vmexit.

Otherwise, if the MCE is a corrected error, KVM will just store it in the corresponding bank (provided this bank is not holding a previously reported uncorrected error).

<a id="rst-kvm-s390-get-cmma-bits"></a>

### 4.107 KVM_S390_GET_CMMA_BITS

**Capability:** KVM_CAP_S390_CMMA_MIGRATION

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_cmma_log (in, out)

**Returns:** 0 on success, a negative value on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENOMEM
>
> </td>
> <td>
>
>
> not enough memory can be allocated to complete the task
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENXIO
>
> </td>
> <td>
>
>
> if CMMA is not enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> if KVM_S390_CMMA_PEEK is not set but migration mode was not enabled
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> if KVM_S390_CMMA_PEEK is not set but dirty tracking has been disabled (and thus migration mode was automatically disabled)
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EFAULT
>
> </td>
> <td>
>
>
> if the userspace address is invalid or if no page table is present for the addresses (e.g. when using hugepages).
>
> </td>
> </tr>
> </tbody>
> </table>

This ioctl is used to get the values of the CMMA bits on the s390 architecture. It is meant to be used in two scenarios:

- During live migration to save the CMMA values. Live migration needs to be enabled via the KVM_REQ_START_MIGRATION VM property.

- To non-destructively peek at the CMMA values, with the flag KVM_S390_CMMA_PEEK set.

The ioctl takes parameters via the kvm_s390_cmma_log struct. The desired values are written to a buffer whose location is indicated via the "values" member in the kvm_s390_cmma_log struct.  The values in the input struct are also updated as needed.

Each CMMA value takes up one byte.



```text
struct kvm_s390_cmma_log {
      __u64 start_gfn;
      __u32 count;
      __u32 flags;
      union {
              __u64 remaining;
              __u64 mask;
      };
      __u64 values;
};
```

start_gfn is the number of the first guest frame whose CMMA values are to be retrieved,

count is the length of the buffer in bytes,

values points to the buffer where the result will be written to.

If count is greater than KVM_S390_SKEYS_MAX, then it is considered to be KVM_S390_SKEYS_MAX. KVM_S390_SKEYS_MAX is re-used for consistency with other ioctls.

The result is written in the buffer pointed to by the field values, and the values of the input parameter are updated as follows.

Depending on the flags, different actions are performed. The only supported flag so far is KVM_S390_CMMA_PEEK.

The default behaviour if KVM_S390_CMMA_PEEK is not set is: start_gfn will indicate the first page frame whose CMMA bits were dirty. It is not necessarily the same as the one passed as input, as clean pages are skipped.

count will indicate the number of bytes actually written in the buffer. It can (and very often will) be smaller than the input value, since the buffer is only filled until 16 bytes of clean values are found (which are then not copied in the buffer). Since a CMMA migration block needs the base address and the length, for a total of 16 bytes, we will send back some clean data if there is some dirty data afterwards, as long as the size of the clean data does not exceed the size of the header. This allows to minimize the amount of data to be saved or transferred over the network at the expense of more roundtrips to userspace. The next invocation of the ioctl will skip over all the clean values, saving potentially more than just the 16 bytes we found.

If KVM_S390_CMMA_PEEK is set: the existing storage attributes are read even when not in migration mode, and no other action is performed;

the output start_gfn will be equal to the input start_gfn,

the output count will be equal to the input count, except if the end of memory has been reached.

In both cases: the field "remaining" will indicate the total number of dirty CMMA values still remaining, or 0 if KVM_S390_CMMA_PEEK is set and migration mode is not enabled.

mask is unused.

values points to the userspace buffer where the result will be stored.

<a id="rst-kvm-s390-set-cmma-bits"></a>

### 4.108 KVM_S390_SET_CMMA_BITS

**Capability:** KVM_CAP_S390_CMMA_MIGRATION

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_cmma_log (in)

**Returns:** 0 on success, a negative value on error

This ioctl is used to set the values of the CMMA bits on the s390 architecture. It is meant to be used during live migration to restore the CMMA values, but there are no restrictions on its use. The ioctl takes parameters via the kvm_s390_cmma_values struct. Each CMMA value takes up one byte.



```text
struct kvm_s390_cmma_log {
      __u64 start_gfn;
      __u32 count;
      __u32 flags;
      union {
              __u64 remaining;
              __u64 mask;
      };
      __u64 values;
};
```

start_gfn indicates the starting guest frame number,

count indicates how many values are to be considered in the buffer,

flags is not used and must be 0.

mask indicates which PGSTE bits are to be considered.

remaining is not used.

values points to the buffer in userspace where to store the values.

This ioctl can fail with -ENOMEM if not enough memory can be allocated to complete the task, with -ENXIO if CMMA is not enabled, with -EINVAL if the count field is too large (e.g. more than KVM_S390_CMMA_SIZE_MAX) or if the flags field was not 0, with -EFAULT if the userspace address is invalid, if invalid pages are written to (e.g. after the end of memory) or if no page table is present for the addresses (e.g. when using hugepages).

<a id="rst-kvm-ppc-get-cpu-char"></a>

### 4.109 KVM_PPC_GET_CPU_CHAR

**Capability:** KVM_CAP_PPC_GET_CPU_CHAR

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** struct kvm_ppc_cpu_char (out)

**Returns:** 0 on successful completion, -EFAULT if struct kvm_ppc_cpu_char cannot be written

This ioctl gives userspace information about certain characteristics of the CPU relating to speculative execution of instructions and possible information leakage resulting from speculative execution (see CVE-2017-5715, CVE-2017-5753 and CVE-2017-5754).  The information is returned in struct kvm_ppc_cpu_char, which looks like this:



```text
struct kvm_ppc_cpu_char {
      __u64   character;              /* characteristics of the CPU */
      __u64   behaviour;              /* recommended software behaviour */
      __u64   character_mask;         /* valid bits in character */
      __u64   behaviour_mask;         /* valid bits in behaviour */
};
```

For extensibility, the character_mask and behaviour_mask fields indicate which bits of character and behaviour have been filled in by the kernel.  If the set of defined bits is extended in future then userspace will be able to tell whether it is running on a kernel that knows about the new bits.

The character field describes attributes of the CPU which can help with preventing inadvertent information disclosure - specifically, whether there is an instruction to flash-invalidate the L1 data cache (ori 30,30,0 or mtspr SPRN_TRIG2,rN), whether the L1 data cache is set to a mode where entries can only be used by the thread that created them, whether the bcctr\[l\] instruction prevents speculation, and whether a speculation barrier instruction (ori 31,31,0) is provided.

The behaviour field describes actions that software should take to prevent inadvertent information disclosure, and thus describes which vulnerabilities the hardware is subject to; specifically whether the L1 data cache should be flushed when returning to user mode from the kernel, and whether a speculation barrier should be placed between an array bounds check and the array access.

These fields use the same bit definitions as the new H_GET_CPU_CHARACTERISTICS hypercall.

<a id="rst-kvm-memory-encrypt-op"></a>

### 4.110 KVM_MEMORY_ENCRYPT_OP

**Capability:** basic

**Architectures:** x86

**Type:** vm ioctl, vcpu ioctl

**Parameters:** an opaque platform specific structure (in/out)

**Returns:** 0 on success; -1 on error

If the platform supports creating encrypted VMs then this ioctl can be used for issuing platform-specific memory encryption commands to manage those encrypted VMs.

Currently, this ioctl is used for issuing both Secure Encrypted Virtualization (SEV) commands on AMD Processors and Trusted Domain Extensions (TDX) commands on Intel Processors.  The detailed commands are defined in [Documentation/virt/kvm/x86/amd-memory-encryption.rst](/kernel/internals/virt/kvm-x86/amd-memory-encryption.md) and [Documentation/virt/kvm/x86/intel-tdx.rst](/kernel/internals/virt/kvm-x86/intel-tdx.md).

<a id="rst-kvm-memory-encrypt-reg-region"></a>

### 4.111 KVM_MEMORY_ENCRYPT_REG_REGION

**Capability:** basic

**Architectures:** x86

**Type:** system

**Parameters:** struct kvm_enc_region (in)

**Returns:** 0 on success; -1 on error

This ioctl can be used to register a guest memory region which may contain encrypted data (e.g. guest RAM, SMRAM etc).

It is used in the SEV-enabled guest. When encryption is enabled, a guest memory region may contain encrypted data. The SEV memory encryption engine uses a tweak such that two identical plaintext pages, each at different locations will have differing ciphertexts. So swapping or moving ciphertext of those pages will not result in plaintext being swapped. So relocating (or migrating) physical backing pages for the SEV guest will require some additional steps.

Note: The current SEV key management spec does not provide commands to swap or migrate (move) ciphertext pages. Hence, for now we pin the guest memory region registered with the ioctl.

<a id="rst-kvm-memory-encrypt-unreg-region"></a>

### 4.112 KVM_MEMORY_ENCRYPT_UNREG_REGION

**Capability:** basic

**Architectures:** x86

**Type:** system

**Parameters:** struct kvm_enc_region (in)

**Returns:** 0 on success; -1 on error

This ioctl can be used to unregister the guest memory region registered with KVM_MEMORY_ENCRYPT_REG_REGION ioctl above.

<a id="rst-kvm-hyperv-eventfd"></a>

### 4.113 KVM_HYPERV_EVENTFD

**Capability:** KVM_CAP_HYPERV_EVENTFD

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_hyperv_eventfd (in)

This ioctl (un)registers an eventfd to receive notifications from the guest on the specified Hyper-V connection id through the SIGNAL_EVENT hypercall, without causing a user exit.  SIGNAL_EVENT hypercall with non-zero event flag number (bits 24-31) still triggers a KVM_EXIT_HYPERV_HCALL user exit.



```text
struct kvm_hyperv_eventfd {
      __u32 conn_id;
      __s32 fd;
      __u32 flags;
      __u32 padding[3];
};
```

The conn_id field should fit within 24 bits:



```text
#define KVM_HYPERV_CONN_ID_MASK               0x00ffffff
```

The acceptable values for the flags field are:



```text
#define KVM_HYPERV_EVENTFD_DEASSIGN   (1 << 0)
```

**Returns:** 0 on success, -EINVAL if conn_id or flags is outside the allowed range, -ENOENT on deassign if the conn_id isn't registered, -EEXIST on assign if the conn_id is already registered

<a id="rst-kvm-get-nested-state"></a>

### 4.114 KVM_GET_NESTED_STATE

**Capability:** KVM_CAP_NESTED_STATE

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_nested_state (in/out)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> E2BIG
>
> </td>
> <td>
>
>
> the total state size exceeds the value of 'size' specified by the user; the size required will be written into size.
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_nested_state {
      __u16 flags;
      __u16 format;
      __u32 size;

      union {
              struct kvm_vmx_nested_state_hdr vmx;
              struct kvm_svm_nested_state_hdr svm;

              /* Pad the header to 128 bytes.  */
              __u8 pad[120];
      } hdr;

      union {
              struct kvm_vmx_nested_state_data vmx[0];
              struct kvm_svm_nested_state_data svm[0];
      } data;
};

#define KVM_STATE_NESTED_GUEST_MODE           0x00000001
#define KVM_STATE_NESTED_RUN_PENDING          0x00000002
#define KVM_STATE_NESTED_EVMCS                0x00000004

#define KVM_STATE_NESTED_FORMAT_VMX           0
#define KVM_STATE_NESTED_FORMAT_SVM           1

#define KVM_STATE_NESTED_VMX_VMCS_SIZE        0x1000

#define KVM_STATE_NESTED_VMX_SMM_GUEST_MODE   0x00000001
#define KVM_STATE_NESTED_VMX_SMM_VMXON        0x00000002

#define KVM_STATE_VMX_PREEMPTION_TIMER_DEADLINE 0x00000001

struct kvm_vmx_nested_state_hdr {
      __u64 vmxon_pa;
      __u64 vmcs12_pa;

      struct {
              __u16 flags;
      } smm;

      __u32 flags;
      __u64 preemption_timer_deadline;
};

struct kvm_vmx_nested_state_data {
      __u8 vmcs12[KVM_STATE_NESTED_VMX_VMCS_SIZE];
      __u8 shadow_vmcs12[KVM_STATE_NESTED_VMX_VMCS_SIZE];
};
```

This ioctl copies the vcpu's nested virtualization state from the kernel to userspace.

The maximum size of the state can be retrieved by passing KVM_CAP_NESTED_STATE to the KVM_CHECK_EXTENSION ioctl().

<a id="rst-kvm-set-nested-state"></a>

### 4.115 KVM_SET_NESTED_STATE

**Capability:** KVM_CAP_NESTED_STATE

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_nested_state (in)

**Returns:** 0 on success, -1 on error

This copies the vcpu's kvm_nested_state struct from userspace to the kernel. For the definition of struct kvm_nested_state, see KVM_GET_NESTED_STATE.

<a id="rst-kvm-un-register-coalesced-mmio"></a>

### 4.116 KVM\_(UN)REGISTER_COALESCED_MMIO

**Capability:** KVM_CAP_COALESCED_MMIO (for coalesced mmio) KVM_CAP_COALESCED_PIO (for coalesced pio)

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_coalesced_mmio_zone

**Returns:** 0 on success, &lt; 0 on error

Coalesced I/O is a performance optimization that defers hardware register write emulation so that userspace exits are avoided.  It is typically used to reduce the overhead of emulating frequently accessed hardware registers.

When a hardware register is configured for coalesced I/O, write accesses do not exit to userspace and their value is recorded in a ring buffer that is shared between kernel and userspace.

Coalesced I/O is used if one or more write accesses to a hardware register can be deferred until a read or a write to another hardware register on the same device.  This last access will cause a vmexit and userspace will process accesses from the ring buffer before emulating it. That will avoid exiting to userspace on repeated writes.

Coalesced pio is based on coalesced mmio. There is little difference between coalesced mmio and pio except that coalesced pio records accesses to I/O ports.

<a id="rst-kvm-clear-dirty-log"></a>

### 4.117 KVM_CLEAR_DIRTY_LOG

**Capability:** KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2

**Architectures:** x86, arm64, mips

**Type:** vm ioctl

**Parameters:** struct kvm_clear_dirty_log (in)

**Returns:** 0 on success, -1 on error



```text
/* for KVM_CLEAR_DIRTY_LOG */
struct kvm_clear_dirty_log {
      __u32 slot;
      __u32 num_pages;
      __u64 first_page;
      union {
              void __user *dirty_bitmap; /* one bit per page */
              __u64 padding;
      };
};
```

The ioctl clears the dirty status of pages in a memory slot, according to the bitmap that is passed in struct kvm_clear_dirty_log's dirty_bitmap field.  Bit 0 of the bitmap corresponds to page "first_page" in the memory slot, and num_pages is the size in bits of the input bitmap. first_page must be a multiple of 64; num_pages must also be a multiple of 64 unless first_page + num_pages is the size of the memory slot.  For each bit that is set in the input bitmap, the corresponding page is marked "clean" in KVM's dirty bitmap, and dirty tracking is re-enabled for that page (for example via write-protection, or by clearing the dirty bit in a page table entry).

If KVM_CAP_MULTI_ADDRESS_SPACE is available, bits 16-31 of slot field specifies the address space for which you want to clear the dirty status.  See KVM_SET_USER_MEMORY_REGION for details on the usage of slot field.

This ioctl is mostly useful when KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is enabled; for more information, see the description of the capability. However, it can always be used as long as KVM_CHECK_EXTENSION confirms that KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is present.

<a id="rst-kvm-get-supported-hv-cpuid"></a>

### 4.118 KVM_GET_SUPPORTED_HV_CPUID

**Capability:** KVM_CAP_HYPERV_CPUID (vcpu), KVM_CAP_SYS_HYPERV_CPUID (system)

**Architectures:** x86

**Type:** system ioctl, vcpu ioctl

**Parameters:** struct kvm_cpuid2 (in/out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_cpuid2 {
      __u32 nent;
      __u32 padding;
      struct kvm_cpuid_entry2 entries[0];
};

struct kvm_cpuid_entry2 {
      __u32 function;
      __u32 index;
      __u32 flags;
      __u32 eax;
      __u32 ebx;
      __u32 ecx;
      __u32 edx;
      __u32 padding[3];
};
```

This ioctl returns x86 cpuid features leaves related to Hyper-V emulation in KVM.  Userspace can use the information returned by this ioctl to construct cpuid information presented to guests consuming Hyper-V enlightenments (e.g. Windows or Hyper-V guests).

CPUID feature leaves returned by this ioctl are defined by Hyper-V Top Level Functional Specification (TLFS). These leaves can't be obtained with KVM_GET_SUPPORTED_CPUID ioctl because some of them intersect with KVM feature leaves (0x40000000, 0x40000001).

Currently, the following list of CPUID leaves are returned:

> - HYPERV_CPUID_VENDOR_AND_MAX_FUNCTIONS
>
> - HYPERV_CPUID_INTERFACE
>
> - HYPERV_CPUID_VERSION
>
> - HYPERV_CPUID_FEATURES
>
> - HYPERV_CPUID_ENLIGHTMENT_INFO
>
> - HYPERV_CPUID_IMPLEMENT_LIMITS
>
> - HYPERV_CPUID_NESTED_FEATURES
>
> - HYPERV_CPUID_SYNDBG_VENDOR_AND_MAX_FUNCTIONS
>
> - HYPERV_CPUID_SYNDBG_INTERFACE
>
> - HYPERV_CPUID_SYNDBG_PLATFORM_CAPABILITIES

Userspace invokes KVM_GET_SUPPORTED_HV_CPUID by passing a kvm_cpuid2 structure with the 'nent' field indicating the number of entries in the variable-size array 'entries'.  If the number of entries is too low to describe all Hyper-V feature leaves, an error (E2BIG) is returned. If the number is more or equal to the number of Hyper-V feature leaves, the 'nent' field is adjusted to the number of valid entries in the 'entries' array, which is then filled.

'index' and 'flags' fields in 'struct kvm_cpuid_entry2' are currently reserved, userspace should not expect to get any particular value there.

Note, vcpu version of KVM_GET_SUPPORTED_HV_CPUID is currently deprecated. Unlike system ioctl which exposes all supported feature bits unconditionally, vcpu version has the following quirks:

- HYPERV_CPUID_NESTED_FEATURES leaf and HV_X64_ENLIGHTENED_VMCS_RECOMMENDED feature bit are only exposed when Enlightened VMCS was previously enabled on the corresponding vCPU (KVM_CAP_HYPERV_ENLIGHTENED_VMCS).

- HV_STIMER_DIRECT_MODE_AVAILABLE bit is only exposed with in-kernel LAPIC. (presumes KVM_CREATE_IRQCHIP has already been called).

<a id="rst-kvm-arm-vcpu-finalize"></a>

### 4.119 KVM_ARM_VCPU_FINALIZE

**Architectures:** arm64

**Type:** vcpu ioctl

**Parameters:** int feature (in)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EPERM
>
> </td>
> <td>
>
>
> feature not enabled, needs configuration, or already finalized
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> feature unknown or not present
>
> </td>
> </tr>
> </tbody>
> </table>

Recognised values for feature:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> arm64
>
> </td>
> <td>
>
>
> KVM_ARM_VCPU_SVE (requires KVM_CAP_ARM_SVE)
>
> </td>
> </tr>
> </tbody>
> </table>

Finalizes the configuration of the specified vcpu feature.

The vcpu must already have been initialised, enabling the affected feature, by means of a successful [KVM_ARM_VCPU_INIT](<#rst-kvm-arm-vcpu-init>) call with the appropriate flag set in features\[\].

For affected vcpu features, this is a mandatory step that must be performed before the vcpu is fully usable.

Between KVM_ARM_VCPU_INIT and KVM_ARM_VCPU_FINALIZE, the feature may be configured by use of ioctls such as KVM_SET_ONE_REG.  The exact configuration that should be performed and how to do it are feature-dependent.

Other calls that depend on a particular feature being finalized, such as KVM_RUN, KVM_GET_REG_LIST, KVM_GET_ONE_REG and KVM_SET_ONE_REG, will fail with -EPERM unless the feature has already been finalized by means of a KVM_ARM_VCPU_FINALIZE call.

See KVM_ARM_VCPU_INIT for details of vcpu features that require finalization using this ioctl.

<a id="rst-kvm-set-pmu-event-filter"></a>

### 4.120 KVM_SET_PMU_EVENT_FILTER

**Capability:** KVM_CAP_PMU_EVENT_FILTER

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_pmu_event_filter (in)

**Returns:** 0 on success, -1 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EFAULT
>
> </td>
> <td>
>
>
> args\[0\] cannot be accessed
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> args\[0\] contains invalid data in the filter or filter events
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> E2BIG
>
> </td>
> <td>
>
>
> nevents is too large
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EBUSY
>
> </td>
> <td>
>
>
> not enough memory to allocate the filter
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_pmu_event_filter {
      __u32 action;
      __u32 nevents;
      __u32 fixed_counter_bitmap;
      __u32 flags;
      __u32 pad[4];
      __u64 events[0];
};
```

This ioctl restricts the set of PMU events the guest can program by limiting which event select and unit mask combinations are permitted.

The argument holds a list of filter events which will be allowed or denied.

Filter events only control general purpose counters; fixed purpose counters are controlled by the fixed_counter_bitmap.

Valid values for 'flags':



```text
``0``
```

To use this mode, clear the 'flags' field.

In this mode each event will contain an event select + unit mask.

When the guest attempts to program the PMU the guest's event select + unit mask is compared against the filter events to determine whether the guest should have access.

`KVM_PMU_EVENT_FLAG_MASKED_EVENTS` :Capability: KVM_CAP_PMU_EVENT_MASKED_EVENTS

In this mode each filter event will contain an event select, mask, match, and exclude value.  To encode a masked event use:



```text
KVM_PMU_ENCODE_MASKED_ENTRY()
```

An encoded event will follow this layout:



```text
Bits   Description
----   -----------
7:0    event select (low bits)
15:8   umask match
31:16  unused
35:32  event select (high bits)
36:54  unused
55     exclude bit
63:56  umask mask
```

When the guest attempts to program the PMU, these steps are followed in determining if the guest should have access:

> 1. Match the event select from the guest against the filter events.
>
> 2. If a match is found, match the guest's unit mask to the mask and match values of the included filter events. I.e. (unit mask &amp; mask) == match &amp;&amp; \!exclude.
>
> 3. If a match is found, match the guest's unit mask to the mask and match values of the excluded filter events. I.e. (unit mask &amp; mask) == match &amp;&amp; exclude.
>
> 4. - **a.** If an included match is found and an excluded match is not found, filter the event.
>
>    - **b.** For everything else, do not filter the event.
>
> 5. - **a.** If the event is filtered and it's an allow list, allow the guest to program the event.
>
>    - **b.** If the event is filtered and it's a deny list, do not allow the guest to program the event.

When setting a new pmu event filter, -EINVAL will be returned if any of the unused fields are set or if any of the high bits (35:32) in the event select are set when called on Intel.

Valid values for 'action':



```text
#define KVM_PMU_EVENT_ALLOW 0
#define KVM_PMU_EVENT_DENY 1
```

Via this API, KVM userspace can also control the behavior of the VM's fixed counters (if any) by configuring the "action" and "fixed_counter_bitmap" fields.

Specifically, KVM follows the following pseudo-code when determining whether to allow the guest FixCtr\[i\] to count its pre-defined fixed event:



```text
FixCtr[i]_is_allowed = (action == ALLOW) && (bitmap & BIT(i)) ||
  (action == DENY) && !(bitmap & BIT(i));
FixCtr[i]_is_denied = !FixCtr[i]_is_allowed;
```

KVM always consumes fixed_counter_bitmap, it's userspace's responsibility to ensure fixed_counter_bitmap is set correctly, e.g. if userspace wants to define a filter that only affects general purpose counters.

Note, the "events" field also applies to fixed counters' hardcoded event_select and unit_mask values.  "fixed_counter_bitmap" has higher priority than "events" if there is a contradiction between the two.

<a id="rst-kvm-ppc-svm-off"></a>

### 4.121 KVM_PPC_SVM_OFF

**Capability:** basic

**Architectures:** powerpc

**Type:** vm ioctl

**Parameters:** none

**Returns:** 0 on successful completion,

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> if ultravisor failed to terminate the secure guest
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOMEM
>
> </td>
> <td>
>
>
> if hypervisor failed to allocate new radix page tables for guest
>
> </td>
> </tr>
> </tbody>
> </table>

This ioctl is used to turn off the secure mode of the guest or transition the guest from secure mode to normal mode. This is invoked when the guest is reset. This has no effect if called for a normal guest.

This ioctl issues an ultravisor call to terminate the secure guest, unpins the VPA pages and releases all the device pages that are used to track the secure pages by hypervisor.

<a id="rst-kvm-s390-normal-reset"></a>

### 4.122 KVM_S390_NORMAL_RESET

**Capability:** KVM_CAP_S390_VCPU_RESETS

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0

This ioctl resets VCPU registers and control structures according to the cpu reset definition in the POP (Principles Of Operation).

<a id="rst-kvm-s390-initial-reset"></a>

### 4.123 KVM_S390_INITIAL_RESET

**Capability:** basic

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0

This ioctl resets VCPU registers and control structures according to the initial cpu reset definition in the POP. However, the cpu is not put into ESA mode. This reset is a superset of the normal reset.

<a id="rst-kvm-s390-clear-reset"></a>

### 4.124 KVM_S390_CLEAR_RESET

**Capability:** KVM_CAP_S390_VCPU_RESETS

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0

This ioctl resets VCPU registers and control structures according to the clear cpu reset definition in the POP. However, the cpu is not put into ESA mode. This reset is a superset of the initial reset.

<a id="rst-kvm-s390-pv-command"></a>

### 4.125 KVM_S390_PV_COMMAND

**Capability:** KVM_CAP_S390_PROTECTED

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_pv_cmd

**Returns:** 0 on success, &lt; 0 on error



```text
struct kvm_pv_cmd {
      __u32 cmd;      /* Command to be executed */
      __u16 rc;       /* Ultravisor return code */
      __u16 rrc;      /* Ultravisor return reason code */
      __u64 data;     /* Data or address */
      __u32 flags;    /* flags for future extensions. Must be 0 for now */
      __u32 reserved[3];
};
```

**Ultravisor return codes** The Ultravisor return (reason) codes are provided by the kernel if a Ultravisor call has been executed to achieve the results expected by the command. Therefore they are independent of the IOCTL return code. If KVM changes `rc`, its value will always be greater than 0 hence setting it to 0 before issuing a PV command is advised to be able to detect a change of `rc`.

**cmd values:**

- **KVM_PV_ENABLE**

  Allocate memory and register the VM with the Ultravisor, thereby donating memory to the Ultravisor that will become inaccessible to KVM. All existing CPUs are converted to protected ones. After this command has succeeded, any CPU added via hotplug will become protected during its creation as well.

  Errors:


  <table>
  <tbody>
  <tr>
  <td>


  EINTR

  </td>
  <td>


  an unmasked signal is pending

  </td>
  </tr>
  </tbody>
  </table>

- **KVM_PV_DISABLE**

  Deregister the VM from the Ultravisor and reclaim the memory that had been donated to the Ultravisor, making it usable by the kernel again. All registered VCPUs are converted back to non-protected ones. If a previous protected VM had been prepared for asynchronous teardown with KVM_PV_ASYNC_CLEANUP_PREPARE and not subsequently torn down with KVM_PV_ASYNC_CLEANUP_PERFORM, it will be torn down in this call together with the current protected VM.

- **KVM_PV_VM_SET_SEC_PARMS**

  Pass the image header from VM memory to the Ultravisor in preparation of image unpacking and verification.

- **KVM_PV_VM_UNPACK**

  Unpack (protect and decrypt) a page of the encrypted boot image.

- **KVM_PV_VM_VERIFY**

  Verify the integrity of the unpacked image. Only if this succeeds, KVM is allowed to start protected VCPUs.

- **KVM_PV_INFO**

  **Capability:** KVM_CAP_S390_PROTECTED_DUMP

  Presents an API that provides Ultravisor related data to userspace via subcommands. len_max is the size of the user space buffer, len_written is KVM's indication of how much bytes of that buffer were actually written to. len_written can be used to determine the valid fields if more response fields are added in the future.



  ```text
  enum pv_cmd_info_id {
     KVM_PV_INFO_VM,
     KVM_PV_INFO_DUMP,
  };

  struct kvm_s390_pv_info_header {
     __u32 id;
     __u32 len_max;
     __u32 len_written;
     __u32 reserved;
  };

  struct kvm_s390_pv_info {
     struct kvm_s390_pv_info_header header;
     struct kvm_s390_pv_info_dump dump;
     struct kvm_s390_pv_info_vm vm;
  };
  ```

**subcommands:**

> - **KVM_PV_INFO_VM**
>
>   This subcommand provides basic Ultravisor information for PV hosts. These values are likely also exported as files in the sysfs firmware UV query interface but they are more easily available to programs in this API.
>
>   The installed calls and feature_indication members provide the installed UV calls and the UV's other feature indications.
>
>   The max\_\* members provide information about the maximum number of PV vcpus, PV guests and PV guest memory size.
>
>
>
>   ```text
>   struct kvm_s390_pv_info_vm {
>     __u64 inst_calls_list[4];
>     __u64 max_cpus;
>     __u64 max_guests;
>     __u64 max_guest_addr;
>     __u64 feature_indication;
>   };
>   ```
>
> - **KVM_PV_INFO_DUMP**
>
>   This subcommand provides information related to dumping PV guests.
>
>
>
>   ```text
>   struct kvm_s390_pv_info_dump {
>     __u64 dump_cpu_buffer_len;
>     __u64 dump_config_mem_buffer_per_1m;
>     __u64 dump_config_finalize_len;
>   };
>   ```

- **KVM_PV_DUMP**

  **Capability:** KVM_CAP_S390_PROTECTED_DUMP

  Presents an API that provides calls which facilitate dumping a protected VM.



  ```text
  struct kvm_s390_pv_dmp {
    __u64 subcmd;
    __u64 buff_addr;
    __u64 buff_len;
    __u64 gaddr;              /* For dump storage state */
  };
  ```

  **subcommands:**

  - **KVM_PV_DUMP_INIT**

    Initializes the dump process of a protected VM. If this call does not succeed all other subcommands will fail with -EINVAL. This subcommand will return -EINVAL if a dump process has not yet been completed.

    Not all PV vms can be dumped, the owner needs to set `dump allowed` PCF bit 34 in the SE header to allow dumping.

  - **KVM_PV_DUMP_CONFIG_STOR_STATE**

    Stores `buff_len` bytes of tweak component values starting with the 1MB block specified by the absolute guest address (`gaddr`). `buff_len` needs to be `conf_dump_storage_state_len` aligned and at least &gt;= the `conf_dump_storage_state_len` value provided by the dump uv_info data. buff_user might be written to even if an error rc is returned. For instance if we encounter a fault after writing the first page of data.

  - **KVM_PV_DUMP_COMPLETE**

    If the subcommand succeeds it completes the dump process and lets KVM_PV_DUMP_INIT be called again.

    On success `conf_dump_finalize_len` bytes of completion data will be stored to the `buff_addr`. The completion data contains a key derivation seed, IV, tweak nonce and encryption keys as well as an authentication tag all of which are needed to decrypt the dump at a later time.

- **KVM_PV_ASYNC_CLEANUP_PREPARE**

  **Capability:** KVM_CAP_S390_PROTECTED_ASYNC_DISABLE

  Prepare the current protected VM for asynchronous teardown. Most resources used by the current protected VM will be set aside for a subsequent asynchronous teardown. The current protected VM will then resume execution immediately as non-protected. There can be at most one protected VM prepared for asynchronous teardown at any time. If a protected VM had already been prepared for teardown without subsequently calling KVM_PV_ASYNC_CLEANUP_PERFORM, this call will fail. In that case, the userspace process should issue a normal KVM_PV_DISABLE. The resources set aside with this call will need to be cleaned up with a subsequent call to KVM_PV_ASYNC_CLEANUP_PERFORM or KVM_PV_DISABLE, otherwise they will be cleaned up when KVM terminates. KVM_PV_ASYNC_CLEANUP_PREPARE can be called again as soon as cleanup starts, i.e. before KVM_PV_ASYNC_CLEANUP_PERFORM finishes.

- **KVM_PV_ASYNC_CLEANUP_PERFORM**

  **Capability:** KVM_CAP_S390_PROTECTED_ASYNC_DISABLE

  Tear down the protected VM previously prepared for teardown with KVM_PV_ASYNC_CLEANUP_PREPARE. The resources that had been set aside will be freed during the execution of this command. This PV command should ideally be issued by userspace from a separate thread. If a fatal signal is received (or the process terminates naturally), the command will terminate immediately without completing, and the normal KVM shutdown procedure will take care of cleaning up all remaining protected VMs, including the ones whose teardown was interrupted by process termination.

<a id="rst-kvm-xen-hvm-set-attr"></a>

### 4.126 KVM_XEN_HVM_SET_ATTR

**Capability:** KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_xen_hvm_attr

**Returns:** 0 on success, &lt; 0 on error



```text
struct kvm_xen_hvm_attr {
      __u16 type;
      __u16 pad[3];
      union {
              __u8 long_mode;
              __u8 vector;
              __u8 runstate_update_flag;
              union {
                      __u64 gfn;
                      __u64 hva;
              } shared_info;
              struct {
                      __u32 send_port;
                      __u32 type; /* EVTCHNSTAT_ipi / EVTCHNSTAT_interdomain */
                      __u32 flags;
                      union {
                              struct {
                                      __u32 port;
                                      __u32 vcpu;
                                      __u32 priority;
                              } port;
                              struct {
                                      __u32 port; /* Zero for eventfd */
                                      __s32 fd;
                              } eventfd;
                              __u32 padding[4];
                      } deliver;
              } evtchn;
              __u32 xen_version;
              __u64 pad[8];
      } u;
};
```

type values:

- **KVM_XEN_ATTR_TYPE_LONG_MODE**

  Sets the ABI mode of the VM to 32-bit or 64-bit (long mode). This determines the layout of the shared_info page exposed to the VM.

- **KVM_XEN_ATTR_TYPE_SHARED_INFO**

  Sets the guest physical frame number at which the Xen shared_info page resides. Note that although Xen places vcpu_info for the first 32 vCPUs in the shared_info page, KVM does not automatically do so and instead requires that KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO or KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA be used explicitly even when the vcpu_info for a given vCPU resides at the "default" location in the shared_info page. This is because KVM may not be aware of the Xen CPU id which is used as the index into the vcpu_info\[\] array, so may know the correct default location.

  Note that the shared_info page may be constantly written to by KVM; it contains the event channel bitmap used to deliver interrupts to a Xen guest, amongst other things. It is exempt from dirty tracking mechanisms — KVM will not explicitly mark the page as dirty each time an event channel interrupt is delivered to the guest\! Thus, userspace should always assume that the designated GFN is dirty if any vCPU has been running or any event channel interrupts can be routed to the guest.

  Setting the gfn to KVM_XEN_INVALID_GFN will disable the shared_info page.

- **KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA**

  If the KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA flag is also set in the Xen capabilities, then this attribute may be used to set the userspace address at which the shared_info page resides, which will always be fixed in the VMM regardless of where it is mapped in guest physical address space. This attribute should be used in preference to KVM_XEN_ATTR_TYPE_SHARED_INFO as it avoids unnecessary invalidation of an internal cache when the page is re-mapped in guest physical address space.

  Setting the hva to zero will disable the shared_info page.

- **KVM_XEN_ATTR_TYPE_UPCALL_VECTOR**

  Sets the exception vector used to deliver Xen event channel upcalls. This is the HVM-wide vector injected directly by the hypervisor (not through the local APIC), typically configured by a guest via HVM_PARAM_CALLBACK_IRQ. This can be disabled again (e.g. for guest SHUTDOWN_soft_reset) by setting it to zero.

- **KVM_XEN_ATTR_TYPE_EVTCHN**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_EVTCHN_SEND features. It configures an outbound port number for interception of EVTCHNOP_send requests from the guest. A given sending port number may be directed back to a specified vCPU (by APIC ID) / port / priority on the guest, or to trigger events on an eventfd. The vCPU and priority can be changed by setting KVM_XEN_EVTCHN_UPDATE in a subsequent call, but other fields cannot change for a given sending port. A port mapping is removed by using KVM_XEN_EVTCHN_DEASSIGN in the flags field. Passing KVM_XEN_EVTCHN_RESET in the flags field removes all interception of outbound event channels. The values of the flags field are mutually exclusive and cannot be combined as a bitmask.

- **KVM_XEN_ATTR_TYPE_XEN_VERSION**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_EVTCHN_SEND features. It configures the 32-bit version code returned to the guest when it invokes the XENVER_version call; typically (XEN_MAJOR &lt;&lt; 16 \| XEN_MINOR). PV Xen guests will often use this to as a dummy hypercall to trigger event channel delivery, so responding within the kernel without exiting to userspace is beneficial.

- **KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG. It enables the XEN_RUNSTATE_UPDATE flag which allows guest vCPUs to safely read other vCPUs' vcpu_runstate_info. Xen guests enable this feature via the VMASST_TYPE_runstate_update_flag of the HYPERVISOR_vm_assist hypercall.

<a id="rst-kvm-xen-hvm-get-attr"></a>

### 4.127 KVM_XEN_HVM_GET_ATTR

**Capability:** KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_xen_hvm_attr

**Returns:** 0 on success, &lt; 0 on error

Allows Xen VM attributes to be read. For the structure and types, see KVM_XEN_HVM_SET_ATTR above. The KVM_XEN_ATTR_TYPE_EVTCHN attribute cannot be read.

<a id="rst-kvm-xen-vcpu-set-attr"></a>

### 4.128 KVM_XEN_VCPU_SET_ATTR

**Capability:** KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xen_vcpu_attr

**Returns:** 0 on success, &lt; 0 on error



```text
struct kvm_xen_vcpu_attr {
      __u16 type;
      __u16 pad[3];
      union {
              __u64 gpa;
              __u64 pad[4];
              struct {
                      __u64 state;
                      __u64 state_entry_time;
                      __u64 time_running;
                      __u64 time_runnable;
                      __u64 time_blocked;
                      __u64 time_offline;
              } runstate;
              __u32 vcpu_id;
              struct {
                      __u32 port;
                      __u32 priority;
                      __u64 expires_ns;
              } timer;
              __u8 vector;
      } u;
};
```

type values:

- **KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO**

  Sets the guest physical address of the vcpu_info for a given vCPU. As with the shared_info page for the VM, the corresponding page may be dirtied at any time if event channel interrupt delivery is enabled, so userspace should always assume that the page is dirty without relying on dirty logging. Setting the gpa to KVM_XEN_INVALID_GPA will disable the vcpu_info.

- **KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA**

  If the KVM_XEN_HVM_CONFIG_SHARED_INFO_HVA flag is also set in the Xen capabilities, then this attribute may be used to set the userspace address of the vcpu_info for a given vCPU. It should only be used when the vcpu_info resides at the "default" location in the shared_info page. In this case it is safe to assume the userspace address will not change, because the shared_info page is an overlay on guest memory and remains at a fixed host address regardless of where it is mapped in guest physical address space and hence unnecessary invalidation of an internal cache may be avoided if the guest memory layout is modified. If the vcpu_info does not reside at the "default" location then it is not guaranteed to remain at the same host address and hence the aforementioned cache invalidation is required.

- **KVM_XEN_VCPU_ATTR_TYPE_VCPU_TIME_INFO**

  Sets the guest physical address of an additional pvclock structure for a given vCPU. This is typically used for guest vsyscall support. Setting the gpa to KVM_XEN_INVALID_GPA will disable the structure.

- **KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR**

  Sets the guest physical address of the vcpu_runstate_info for a given vCPU. This is how a Xen guest tracks CPU state such as steal time. Setting the gpa to KVM_XEN_INVALID_GPA will disable the runstate area.

- **KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_CURRENT**

  Sets the runstate (RUNSTATE_running/\_runnable/\_blocked/\_offline) of the given vCPU from the .u.runstate.state member of the structure. KVM automatically accounts running and runnable time but blocked and offline states are only entered explicitly.

- **KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_DATA**

  Sets all fields of the vCPU runstate data from the .u.runstate member of the structure, including the current runstate. The state_entry_time must equal the sum of the other four times.

- **KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST**

  This *adds* the contents of the .u.runstate members of the structure to the corresponding members of the given vCPU's runstate data, thus permitting atomic adjustments to the runstate times. The adjustment to the state_entry_time must equal the sum of the adjustments to the other four times. The state field must be set to -1, or to a valid runstate value (RUNSTATE_running, RUNSTATE_runnable, RUNSTATE_blocked or RUNSTATE_offline) to set the current accounted state as of the adjusted state_entry_time.

- **KVM_XEN_VCPU_ATTR_TYPE_VCPU_ID**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_EVTCHN_SEND features. It sets the Xen vCPU ID of the given vCPU, to allow timer-related VCPU operations to be intercepted by KVM.

- **KVM_XEN_VCPU_ATTR_TYPE_TIMER**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_EVTCHN_SEND features. It sets the event channel port/priority for the VIRQ_TIMER of the vCPU, as well as allowing a pending timer to be saved/restored. Setting the timer port to zero disables kernel handling of the singleshot timer.

- **KVM_XEN_VCPU_ATTR_TYPE_UPCALL_VECTOR**

  This attribute is available when the KVM_CAP_XEN_HVM ioctl indicates support for KVM_XEN_HVM_CONFIG_EVTCHN_SEND features. It sets the per-vCPU local APIC upcall vector, configured by a Xen guest with the HVMOP_set_evtchn_upcall_vector hypercall. This is typically used by Windows guests, and is distinct from the HVM-wide upcall vector configured with HVM_PARAM_CALLBACK_IRQ. It is disabled by setting the vector to zero.

<a id="rst-kvm-xen-vcpu-get-attr"></a>

### 4.129 KVM_XEN_VCPU_GET_ATTR

**Capability:** KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_SHARED_INFO

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xen_vcpu_attr

**Returns:** 0 on success, &lt; 0 on error

Allows Xen vCPU attributes to be read. For the structure and types, see KVM_XEN_VCPU_SET_ATTR above.

The KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADJUST type may not be used with the KVM_XEN_VCPU_GET_ATTR ioctl.

<a id="rst-kvm-arm-mte-copy-tags"></a>

### 4.130 KVM_ARM_MTE_COPY_TAGS

**Capability:** KVM_CAP_ARM_MTE

**Architectures:** arm64

**Type:** vm ioctl

**Parameters:** struct kvm_arm_copy_mte_tags

**Returns:** number of bytes copied, &lt; 0 on error (-EINVAL for incorrect arguments, -EFAULT if memory cannot be accessed).



```text
struct kvm_arm_copy_mte_tags {
      __u64 guest_ipa;
      __u64 length;
      void __user *addr;
      __u64 flags;
      __u64 reserved[2];
};
```

Copies Memory Tagging Extension (MTE) tags to/from guest tag memory. The `guest_ipa` and `length` fields must be `PAGE_SIZE` aligned. `length` must not be bigger than 2^31 - PAGE_SIZE bytes. The `addr` field must point to a buffer which the tags will be copied to or from.

`flags` specifies the direction of copy, either `KVM_ARM_TAGS_TO_GUEST` or `KVM_ARM_TAGS_FROM_GUEST`.

The size of the buffer to store the tags is `(length / 16)` bytes (granules in MTE are 16 bytes long). Each byte contains a single tag value. This matches the format of `PTRACE_PEEKMTETAGS` and `PTRACE_POKEMTETAGS`.

If an error occurs before any data is copied then a negative error code is returned. If some tags have been copied before an error occurs then the number of bytes successfully copied is returned. If the call completes successfully then `length` is returned.

<a id="rst-kvm-get-sregs2"></a>

### 4.131 KVM_GET_SREGS2

**Capability:** KVM_CAP_SREGS2

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_sregs2 (out)

**Returns:** 0 on success, -1 on error

Reads special registers from the vcpu. This ioctl (when supported) replaces the KVM_GET_SREGS.



```text
struct kvm_sregs2 {
        /* out (KVM_GET_SREGS2) / in (KVM_SET_SREGS2) */
        struct kvm_segment cs, ds, es, fs, gs, ss;
        struct kvm_segment tr, ldt;
        struct kvm_dtable gdt, idt;
        __u64 cr0, cr2, cr3, cr4, cr8;
        __u64 efer;
        __u64 apic_base;
        __u64 flags;
        __u64 pdptrs[4];
};
```

flags values for `kvm_sregs2`:

`KVM_SREGS2_FLAGS_PDPTRS_VALID`

> Indicates that the struct contains valid PDPTR values.

<a id="rst-kvm-set-sregs2"></a>

### 4.132 KVM_SET_SREGS2

**Capability:** KVM_CAP_SREGS2

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_sregs2 (in)

**Returns:** 0 on success, -1 on error

Writes special registers into the vcpu. See KVM_GET_SREGS2 for the data structures. This ioctl (when supported) replaces the KVM_SET_SREGS.

<a id="rst-kvm-get-stats-fd"></a>

### 4.133 KVM_GET_STATS_FD

**Capability:** KVM_CAP_STATS_BINARY_FD

**Architectures:** all

**Type:** vm ioctl, vcpu ioctl

**Parameters:** none

**Returns:** statistics file descriptor on success, &lt; 0 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> ENOMEM
>
> </td>
> <td>
>
>
> if the fd could not be created due to lack of memory
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EMFILE
>
> </td>
> <td>
>
>
> if the number of opened files exceeds the limit
>
> </td>
> </tr>
> </tbody>
> </table>

The returned file descriptor can be used to read VM/vCPU statistics data in binary format. The data in the file descriptor consists of four blocks organized as follows:


<table>
<tbody>
<tr>
<td>


Header

</td>
</tr>
<tr>
<td>


id string

</td>
</tr>
<tr>
<td>


Descriptors

</td>
</tr>
<tr>
<td>


Stats Data

</td>
</tr>
</tbody>
</table>

Apart from the header starting at offset 0, please be aware that it is not guaranteed that the four blocks are adjacent or in the above order; the offsets of the id, descriptors and data blocks are found in the header.  However, all four blocks are aligned to 64 bit offsets in the file and they do not overlap.

All blocks except the data block are immutable.  Userspace can read them only one time after retrieving the file descriptor, and then use `pread` or `lseek` to read the statistics repeatedly.

All data is in system endianness.

The format of the header is as follows:



```text
struct kvm_stats_header {
        __u32 flags;
        __u32 name_size;
        __u32 num_desc;
        __u32 id_offset;
        __u32 desc_offset;
        __u32 data_offset;
};
```

The `flags` field is not used at the moment. It is always read as 0.

The `name_size` field is the size (in byte) of the statistics name string (including trailing '0') which is contained in the "id string" block and appended at the end of every descriptor.

The `num_desc` field is the number of descriptors that are included in the descriptor block.  (The actual number of values in the data block may be larger, since each descriptor may comprise more than one value).

The `id_offset` field is the offset of the id string from the start of the file indicated by the file descriptor. It is a multiple of 8.

The `desc_offset` field is the offset of the Descriptors block from the start of the file indicated by the file descriptor. It is a multiple of 8.

The `data_offset` field is the offset of the Stats Data block from the start of the file indicated by the file descriptor. It is a multiple of 8.

The id string block contains a string which identifies the file descriptor on which KVM_GET_STATS_FD was invoked.  The size of the block, including the trailing `'\0'`, is indicated by the `name_size` field in the header.

The descriptors block is only needed to be read once for the lifetime of the file descriptor contains a sequence of `struct kvm_stats_desc`, each followed by a string of size `name_size`.



```text
#define KVM_STATS_TYPE_SHIFT            0
#define KVM_STATS_TYPE_MASK             (0xF << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_CUMULATIVE       (0x0 << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_INSTANT          (0x1 << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_PEAK             (0x2 << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_LINEAR_HIST      (0x3 << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_LOG_HIST         (0x4 << KVM_STATS_TYPE_SHIFT)
#define KVM_STATS_TYPE_MAX              KVM_STATS_TYPE_LOG_HIST

#define KVM_STATS_UNIT_SHIFT            4
#define KVM_STATS_UNIT_MASK             (0xF << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_NONE             (0x0 << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_BYTES            (0x1 << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_SECONDS          (0x2 << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_CYCLES           (0x3 << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_BOOLEAN          (0x4 << KVM_STATS_UNIT_SHIFT)
#define KVM_STATS_UNIT_MAX              KVM_STATS_UNIT_BOOLEAN

#define KVM_STATS_BASE_SHIFT            8
#define KVM_STATS_BASE_MASK             (0xF << KVM_STATS_BASE_SHIFT)
#define KVM_STATS_BASE_POW10            (0x0 << KVM_STATS_BASE_SHIFT)
#define KVM_STATS_BASE_POW2             (0x1 << KVM_STATS_BASE_SHIFT)
#define KVM_STATS_BASE_MAX              KVM_STATS_BASE_POW2

struct kvm_stats_desc {
        __u32 flags;
        __s16 exponent;
        __u16 size;
        __u32 offset;
        __u32 bucket_size;
        char name[];
};
```

The `flags` field contains the type and unit of the statistics data described by this descriptor. Its endianness is CPU native. The following flags are supported:

Bits 0-3 of `flags` encode the type:

> - `KVM_STATS_TYPE_CUMULATIVE` The statistics reports a cumulative count. The value of data can only be increased. Most of the counters used in KVM are of this type. The corresponding `size` field for this type is always 1. All cumulative statistics data are read/write.
>
> - `KVM_STATS_TYPE_INSTANT` The statistics reports an instantaneous value. Its value can be increased or decreased. This type is usually used as a measurement of some resources, like the number of dirty pages, the number of large pages, etc. All instant statistics are read only. The corresponding `size` field for this type is always 1.
>
> - `KVM_STATS_TYPE_PEAK` The statistics data reports a peak value, for example the maximum number of items in a hash table bucket, the longest time waited and so on. The value of data can only be increased. The corresponding `size` field for this type is always 1.
>
> - `KVM_STATS_TYPE_LINEAR_HIST` The statistic is reported as a linear histogram. The number of buckets is specified by the `size` field. The size of buckets is specified by the `hist_param` field. The range of the Nth bucket (1 &lt;= N &lt; `size`) is \[```hist_param``*(N-1), ``hist_param``*N), while the range of the last bucket is [``hist_param``*(``size```-1), +INF). (+INF means positive infinity value.)
>
> - `KVM_STATS_TYPE_LOG_HIST` The statistic is reported as a logarithmic histogram. The number of buckets is specified by the `size` field. The range of the first bucket is \[0, 1), while the range of the last bucket is \[pow(2, `size`-2), +INF). Otherwise, The Nth bucket (1 &lt; N &lt; `size`) covers \[pow(2, N-2), pow(2, N-1)).

Bits 4-7 of `flags` encode the unit:

> - `KVM_STATS_UNIT_NONE` There is no unit for the value of statistics data. This usually means that the value is a simple counter of an event.
>
> - `KVM_STATS_UNIT_BYTES` It indicates that the statistics data is used to measure memory size, in the unit of Byte, KiByte, MiByte, GiByte, etc. The unit of the data is determined by the `exponent` field in the descriptor.
>
> - `KVM_STATS_UNIT_SECONDS` It indicates that the statistics data is used to measure time or latency.
>
> - `KVM_STATS_UNIT_CYCLES` It indicates that the statistics data is used to measure CPU clock cycles.
>
> - `KVM_STATS_UNIT_BOOLEAN` It indicates that the statistic will always be either 0 or 1.  Boolean statistics of "peak" type will never go back from 1 to 0.  Boolean statistics can be linear histograms (with two buckets) but not logarithmic histograms.

Note that, in the case of histograms, the unit applies to the bucket ranges, while the bucket value indicates how many samples fell in the bucket's range.

Bits 8-11 of `flags`, together with `exponent`, encode the scale of the unit:

> - `KVM_STATS_BASE_POW10` The scale is based on power of 10. It is used for measurement of time and CPU clock cycles.  For example, an exponent of -9 can be used with `KVM_STATS_UNIT_SECONDS` to express that the unit is nanoseconds.
>
> - `KVM_STATS_BASE_POW2` The scale is based on power of 2. It is used for measurement of memory size. For example, an exponent of 20 can be used with `KVM_STATS_UNIT_BYTES` to express that the unit is MiB.

The `size` field is the number of values of this statistics data. Its value is usually 1 for most of simple statistics. 1 means it contains an unsigned 64bit data.

The `offset` field is the offset from the start of Data Block to the start of the corresponding statistics data.

The `bucket_size` field is used as a parameter for histogram statistics data. It is only used by linear histogram statistics data, specifying the size of a bucket in the unit expressed by bits 4-11 of `flags` together with `exponent`.

The `name` field is the name string of the statistics data. The name string starts at the end of `struct kvm_stats_desc`.  The maximum length including the trailing `'\0'`, is indicated by `name_size` in the header.

The Stats Data block contains an array of 64-bit values in the same order as the descriptors in Descriptors block.

<a id="rst-kvm-get-xsave2"></a>

### 4.134 KVM_GET_XSAVE2

**Capability:** KVM_CAP_XSAVE2

**Architectures:** x86

**Type:** vcpu ioctl

**Parameters:** struct kvm_xsave (out)

**Returns:** 0 on success, -1 on error



```text
struct kvm_xsave {
      __u32 region[1024];
      __u32 extra[0];
};
```

This ioctl would copy current vcpu's xsave struct to the userspace. It copies as many bytes as are returned by KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) when invoked on the vm file descriptor. The size value returned by KVM_CHECK_EXTENSION(KVM_CAP_XSAVE2) will always be at least 4096. Currently, it is only greater than 4096 if a dynamic feature has been enabled with `arch_prctl()`, but this may change in the future.

The offsets of the state save areas in struct kvm_xsave follow the contents of CPUID leaf 0xD on the host.

<a id="rst-kvm-xen-hvm-evtchn-send"></a>

### 4.135 KVM_XEN_HVM_EVTCHN_SEND

**Capability:** KVM_CAP_XEN_HVM / KVM_XEN_HVM_CONFIG_EVTCHN_SEND

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_irq_routing_xen_evtchn

**Returns:** 0 on success, &lt; 0 on error



```text
struct kvm_irq_routing_xen_evtchn {
     __u32 port;
     __u32 vcpu;
     __u32 priority;
};
```

This ioctl injects an event channel interrupt directly to the guest vCPU.

<a id="rst-kvm-s390-pv-cpu-command"></a>

### 4.136 KVM_S390_PV_CPU_COMMAND

**Capability:** KVM_CAP_S390_PROTECTED_DUMP

**Architectures:** s390

**Type:** vcpu ioctl

**Parameters:** none

**Returns:** 0 on success, &lt; 0 on error

This ioctl closely mirrors `KVM_S390_PV_COMMAND` but handles requests for vcpus. It re-uses the kvm_s390_pv_dmp struct and hence also shares the command ids.

**command:**

- **KVM_PV_DUMP**

  Presents an API that provides calls which facilitate dumping a vcpu of a protected VM.

**subcommand:**

- **KVM_PV_DUMP_CPU**

  Provides encrypted dump data like register values. The length of the returned data is provided by uv_info.guest_cpu_stor_len.

<a id="rst-kvm-s390-zpci-op"></a>

### 4.137 KVM_S390_ZPCI_OP

**Capability:** KVM_CAP_S390_ZPCI_OP

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_zpci_op (in)

**Returns:** 0 on success, &lt;0 on error

Used to manage hardware-assisted virtualization features for zPCI devices.

Parameters are specified via the following structure:



```text
struct kvm_s390_zpci_op {
      /* in */
      __u32 fh;               /* target device */
      __u8  op;               /* operation to perform */
      __u8  pad[3];
      union {
              /* for KVM_S390_ZPCIOP_REG_AEN */
              struct {
                      __u64 ibv;      /* Guest addr of interrupt bit vector */
                      __u64 sb;       /* Guest addr of summary bit */
                      __u32 flags;
                      __u32 noi;      /* Number of interrupts */
                      __u8 isc;       /* Guest interrupt subclass */
                      __u8 sbo;       /* Offset of guest summary bit vector */
                      __u16 pad;
              } reg_aen;
              __u64 reserved[8];
      } u;
};
```

The type of operation is specified in the "op" field. KVM_S390_ZPCIOP_REG_AEN is used to register the VM for adapter event notification interpretation, which will allow firmware delivery of adapter events directly to the vm, with KVM providing a backup delivery mechanism; KVM_S390_ZPCIOP_DEREG_AEN is used to subsequently disable interpretation of adapter event notifications.

The target zPCI function must also be specified via the "fh" field.  For the KVM_S390_ZPCIOP_REG_AEN operation, additional information to establish firmware delivery must be provided via the "reg_aen" struct.

The "pad" and "reserved" fields may be used for future extensions and should be set to 0s by userspace.

<a id="rst-kvm-arm-set-counter-offset"></a>

### 4.138 KVM_ARM_SET_COUNTER_OFFSET

**Capability:** KVM_CAP_COUNTER_OFFSET

**Architectures:** arm64

**Type:** vm ioctl

**Parameters:** struct kvm_arm_counter_offset (in)

**Returns:** 0 on success, &lt; 0 on error

This capability indicates that userspace is able to apply a single VM-wide offset to both the virtual and physical counters as viewed by the guest using the KVM_ARM_SET_CNT_OFFSET ioctl and the following data structure:



```text
struct kvm_arm_counter_offset {
        __u64 counter_offset;
        __u64 reserved;
};
```

The offset describes a number of counter cycles that are subtracted from both virtual and physical counter views (similar to the effects of the CNTVOFF_EL2 and CNTPOFF_EL2 system registers, but only global). The offset always applies to all vcpus (already created or created after this ioctl) for this VM.

It is userspace's responsibility to compute the offset based, for example, on previous values of the guest counters.

Any value other than 0 for the "reserved" field may result in an error (-EINVAL) being returned. This ioctl can also return -EBUSY if any vcpu ioctl is issued concurrently.

Note that using this ioctl results in KVM ignoring subsequent userspace writes to the CNTVCT_EL0 and CNTPCT_EL0 registers using the SET_ONE_REG interface. No error will be returned, but the resulting offset will not be applied.

<a id="rst-kvm-arm-get-reg-writable-masks-1"></a>
<a id="rst-kvm-arm-get-reg-writable-masks"></a>

### 4.139 KVM_ARM_GET_REG_WRITABLE_MASKS

**Capability:** KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES

**Architectures:** arm64

**Type:** vm ioctl

**Parameters:** struct reg_mask_range (in/out)

**Returns:** 0 on success, &lt; 0 on error



```text
#define KVM_ARM_FEATURE_ID_RANGE        0
#define KVM_ARM_FEATURE_ID_RANGE_SIZE   (3 * 8 * 8)

struct reg_mask_range {
        __u64 addr;             /* Pointer to mask array */
        __u32 range;            /* Requested range */
        __u32 reserved[13];
};
```

This ioctl copies the writable masks for a selected range of registers to userspace.

The `addr` field is a pointer to the destination array where KVM copies the writable masks.

The `range` field indicates the requested range of registers. `KVM_CHECK_EXTENSION` for the `KVM_CAP_ARM_SUPPORTED_REG_MASK_RANGES` capability returns the supported ranges, expressed as a set of flags. Each flag's bit index represents a possible value for the `range` field. All other values are reserved for future use and KVM may return an error.

The `reserved[13]` array is reserved for future use and should be 0, or KVM may return an error.

<a id="rst-kvm-arm-feature-id-range-0"></a>

#### KVM_ARM_FEATURE_ID_RANGE (0)

The Feature ID range is defined as the AArch64 System register space with op0==3, op1==\{0, 1, 3\}, CRn==0, CRm==\{0-7\}, op2==\{0-7\}.

The mask returned array pointed to by `addr` is indexed by the macro `ARM64_FEATURE_ID_RANGE_IDX(op0, op1, crn, crm, op2)`, allowing userspace to know what fields can be changed for the system register described by `op0, op1, crn, crm, op2`. KVM rejects ID register values that describe a superset of the features supported by the system.

<a id="rst-kvm-set-user-memory-region2"></a>

### 4.140 KVM_SET_USER_MEMORY_REGION2

**Capability:** KVM_CAP_USER_MEMORY2

**Architectures:** all

**Type:** vm ioctl

**Parameters:** struct kvm_userspace_memory_region2 (in)

**Returns:** 0 on success, -1 on error

KVM_SET_USER_MEMORY_REGION2 is an extension to KVM_SET_USER_MEMORY_REGION that allows mapping guest_memfd memory into a guest.  All fields shared with KVM_SET_USER_MEMORY_REGION identically.  Userspace can set KVM_MEM_GUEST_MEMFD in flags to have KVM bind the memory region to a given guest_memfd range of \[guest_memfd_offset, guest_memfd_offset + memory_size\].  The target guest_memfd must point at a file created via KVM_CREATE_GUEST_MEMFD on the current VM, and the target range must not be bound to any other memory region.  All standard bounds checks apply (use common sense).



```text
struct kvm_userspace_memory_region2 {
      __u32 slot;
      __u32 flags;
      __u64 guest_phys_addr;
      __u64 memory_size; /* bytes */
      __u64 userspace_addr; /* start of the userspace allocated memory */
      __u64 guest_memfd_offset;
      __u32 guest_memfd;
      __u32 pad1;
      __u64 pad2[14];
};
```

A KVM_MEM_GUEST_MEMFD region \_must\_ have a valid guest_memfd (private memory) and userspace_addr (shared memory).  However, "valid" for userspace_addr simply means that the address itself must be a legal userspace address.  The backing mapping for userspace_addr is not required to be valid/populated at the time of KVM_SET_USER_MEMORY_REGION2, e.g. shared memory can be lazily mapped/allocated on-demand.

When mapping a gfn into the guest, KVM selects shared vs. private, i.e consumes userspace_addr vs. guest_memfd, based on the gfn's KVM_MEMORY_ATTRIBUTE_PRIVATE state.  At VM creation time, all memory is shared, i.e. the PRIVATE attribute is '0' for all gfns.  Userspace can control whether memory is shared/private by toggling KVM_MEMORY_ATTRIBUTE_PRIVATE via KVM_SET_MEMORY_ATTRIBUTES as needed.

<a id="rst-s390-2"></a>

#### S390:

Returns -EINVAL if the VM has the KVM_VM_S390_UCONTROL flag set. Returns -EINVAL if called on a protected VM.

<a id="rst-kvm-set-memory-attributes"></a>

### 4.141 KVM_SET_MEMORY_ATTRIBUTES

**Capability:** KVM_CAP_MEMORY_ATTRIBUTES

**Architectures:** x86

**Type:** vm ioctl

**Parameters:** struct kvm_memory_attributes (in)

**Returns:** 0 on success, &lt;0 on error

KVM_SET_MEMORY_ATTRIBUTES allows userspace to set memory attributes for a range of guest physical memory.



```text
struct kvm_memory_attributes {
      __u64 address;
      __u64 size;
      __u64 attributes;
      __u64 flags;
};

#define KVM_MEMORY_ATTRIBUTE_PRIVATE           (1ULL << 3)
```

The address and size must be page aligned.  The supported attributes can be retrieved via ioctl(KVM_CHECK_EXTENSION) on KVM_CAP_MEMORY_ATTRIBUTES.  If executed on a VM, KVM_CAP_MEMORY_ATTRIBUTES precisely returns the attributes supported by that VM.  If executed at system scope, KVM_CAP_MEMORY_ATTRIBUTES returns all attributes supported by KVM.  The only attribute defined at this time is KVM_MEMORY_ATTRIBUTE_PRIVATE, which marks the associated gfn as being guest private memory.

Note, there is no "get" API.  Userspace is responsible for explicitly tracking the state of a gfn/page as needed.

The "flags" field is reserved for future extensions and must be '0'.

<a id="rst-kvm-create-guest-memfd"></a>

### 4.142 KVM_CREATE_GUEST_MEMFD

**Capability:** KVM_CAP_GUEST_MEMFD

**Architectures:** none

**Type:** vm ioctl

**Parameters:** struct kvm_create_guest_memfd(in)

**Returns:** A file descriptor on success, &lt;0 on error

KVM_CREATE_GUEST_MEMFD creates an anonymous file and returns a file descriptor that refers to it.  guest_memfd files are roughly analogous to files created via memfd_create(), e.g. guest_memfd files live in RAM, have volatile storage, and are automatically released when the last reference is dropped.  Unlike "regular" memfd_create() files, guest_memfd files are bound to their owning virtual machine (see below), cannot be mapped, read, or written by userspace, and cannot be resized  (guest_memfd files do however support PUNCH_HOLE).



```text
struct kvm_create_guest_memfd {
      __u64 size;
      __u64 flags;
      __u64 reserved[6];
};
```

Conceptually, the inode backing a guest_memfd file represents physical memory, i.e. is coupled to the virtual machine as a thing, not to a "struct kvm".  The file itself, which is bound to a "struct kvm", is that instance's view of the underlying memory, e.g. effectively provides the translation of guest addresses to host memory.  This allows for use cases where multiple KVM structures are used to manage a single virtual machine, e.g. when performing intrahost migration of a virtual machine.

KVM currently only supports mapping guest_memfd via KVM_SET_USER_MEMORY_REGION2, and more specifically via the guest_memfd and guest_memfd_offset fields in "struct kvm_userspace_memory_region2", where guest_memfd_offset is the offset into the guest_memfd instance.  For a given guest_memfd file, there can be at most one mapping per page, i.e. binding multiple memory regions to a single guest_memfd range is not allowed (any number of memory regions can be bound to a single guest_memfd file, but the bound ranges must not overlap).

The capability KVM_CAP_GUEST_MEMFD_FLAGS enumerates the `flags` that can be specified via KVM_CREATE_GUEST_MEMFD.  Currently defined flags:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> GUEST_MEMFD_FLAG_MMAP
>
> </td>
> <td>
>
>
> Enable using mmap() on the guest_memfd file descriptor.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> GUEST_MEMFD_FLAG_INIT_SHARED
>
> </td>
> <td>
>
>
> Make all memory in the file shared during KVM_CREATE_GUEST_MEMFD (memory files created without INIT_SHARED will be marked private). Shared memory can be faulted into host userspace page tables. Private memory cannot.
>
> </td>
> </tr>
> </tbody>
> </table>

When the KVM MMU performs a PFN lookup to service a guest fault and the backing guest_memfd has the GUEST_MEMFD_FLAG_MMAP set, then the fault will always be consumed from guest_memfd, regardless of whether it is a shared or a private fault.

See KVM_SET_USER_MEMORY_REGION2 for additional details.

<a id="rst-kvm-pre-fault-memory"></a>

### 4.143 KVM_PRE_FAULT_MEMORY

**Capability:** KVM_CAP_PRE_FAULT_MEMORY

**Architectures:** none

**Type:** vcpu ioctl

**Parameters:** struct kvm_pre_fault_memory (in/out)

**Returns:** 0 if at least one page is processed, &lt; 0 on error

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> EINVAL
>
> </td>
> <td>
>
>
> The specified `gpa` and `size` were invalid (e.g. not page aligned, causes an overflow, or size is zero).
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOENT
>
> </td>
> <td>
>
>
> The specified `gpa` is outside defined memslots.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EINTR
>
> </td>
> <td>
>
>
> An unmasked signal is pending and no page was processed.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EFAULT
>
> </td>
> <td>
>
>
> The parameter address was invalid.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EOPNOTSUPP
>
> </td>
> <td>
>
>
> Mapping memory for a GPA is unsupported by the hypervisor, and/or for the current vCPU state/mode.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EIO
>
> </td>
> <td>
>
>
> unexpected error conditions (also causes a WARN)
>
> </td>
> </tr>
> </tbody>
> </table>



```text
struct kvm_pre_fault_memory {
      /* in/out */
      __u64 gpa;
      __u64 size;
      /* in */
      __u64 flags;
      __u64 padding[5];
};
```

KVM_PRE_FAULT_MEMORY populates KVM's stage-2 page tables used to map memory for the current vCPU state.  KVM maps memory as if the vCPU generated a stage-2 read page fault, e.g. faults in memory as needed, but doesn't break CoW.  However, KVM does not mark any newly created stage-2 PTE as Accessed.

In the case of confidential VM types where there is an initial set up of private guest memory before the guest is 'finalized'/measured, this ioctl should only be issued after completing all the necessary setup to put the guest into a 'finalized' state so that the above semantics can be reliably ensured.

In some cases, multiple vCPUs might share the page tables.  In this case, the ioctl can be called in parallel.

When the ioctl returns, the input values are updated to point to the remaining range.  If `size` &gt; 0 on return, the caller can just issue the ioctl again with the same `struct kvm_map_memory` argument.

Shadow page tables cannot support this ioctl because they are indexed by virtual address or nested guest physical address. Calling this ioctl when the guest is using shadow page tables (for example because it is running a nested guest with nested page tables) will fail with `EOPNOTSUPP` even if `KVM_CHECK_EXTENSION` reports the capability to be present.

`flags` must currently be zero.

<a id="rst-kvm-s390-keyop"></a>

### 4.144 KVM_S390_KEYOP

**Capability:** KVM_CAP_S390_KEYOP

**Architectures:** s390

**Type:** vm ioctl

**Parameters:** struct kvm_s390_keyop (in/out)

**Returns:** 0 in case of success, &lt; 0 on error

The specified key operation is performed on the given guest address. The previous storage key (or the relevant part thereof) will be returned in `key`.



```text
struct kvm_s390_keyop {
      __u64 guest_addr;
      __u8  key;
      __u8  operation;
};
```

Currently supported values for `operation`:

- **KVM_S390_KEYOP_ISKE**

  Returns the storage key for the guest address `guest_addr` in `key`.

- **KVM_S390_KEYOP_RRBE**

  Resets the reference bit for the guest address `guest_addr`, returning the R and C bits of the old storage key in `key`; the remaining fields of the storage key will be set to 0.

- **KVM_S390_KEYOP_SSKE**

  Sets the storage key for the guest address `guest_addr` to the key specified in `key`, returning the previous value in `key`.

<a id="rst-the-kvm-run-structure"></a>
<a id="rst-kvm-run-1"></a>

## 5. The kvm_run structure

Application code obtains a pointer to the kvm_run structure by mmap()ing a vcpu fd.  From that point, application code can control execution by changing fields in kvm_run prior to calling the KVM_RUN ioctl, and obtain information about the reason KVM_RUN returned by looking up structure members.



```text
struct kvm_run {
      /* in */
      __u8 request_interrupt_window;
```

Request that KVM_RUN return when it becomes possible to inject external interrupts into the guest.  Useful in conjunction with KVM_INTERRUPT.



```text
__u8 immediate_exit;
```

This field is polled once when KVM_RUN starts; if non-zero, KVM_RUN exits immediately, returning -EINTR.  In the common scenario where a signal is used to "kick" a VCPU out of KVM_RUN, this field can be used to avoid usage of KVM_SET_SIGNAL_MASK, which has worse scalability. Rather than blocking the signal outside KVM_RUN, userspace can set up a signal handler that sets run-&gt;immediate_exit to a non-zero value.

This field is ignored if KVM_CAP_IMMEDIATE_EXIT is not available.



```text
__u8 padding1[6];

/* out */
__u32 exit_reason;
```

When KVM_RUN has returned successfully (return value 0), this informs application code why KVM_RUN has returned.  Allowable values for this field are detailed below.



```text
__u8 ready_for_interrupt_injection;
```

If request_interrupt_window has been specified, this field indicates an interrupt can be injected now with KVM_INTERRUPT.



```text
__u8 if_flag;
```

The value of the current interrupt flag.  Only valid if in-kernel local APIC is not used.



```text
__u16 flags;
```

More architecture-specific flags detailing state of the VCPU that may affect the device's behavior. Current defined flags:



```text
/* x86, set if the VCPU is in system management mode */
#define KVM_RUN_X86_SMM          (1 << 0)
/* x86, set if bus lock detected in VM */
#define KVM_RUN_X86_BUS_LOCK     (1 << 1)
/* x86, set if the VCPU is executing a nested (L2) guest */
#define KVM_RUN_X86_GUEST_MODE   (1 << 2)

/* arm64, set for KVM_EXIT_DEBUG */
#define KVM_DEBUG_ARCH_HSR_HIGH_VALID  (1 << 0)
```



```text
/* in (pre_kvm_run), out (post_kvm_run) */
__u64 cr8;
```

The value of the cr8 register.  Only valid if in-kernel local APIC is not used.  Both input and output.



```text
__u64 apic_base;
```

The value of the APIC BASE msr.  Only valid if in-kernel local APIC is not used.  Both input and output.



```text
union {
        /* KVM_EXIT_UNKNOWN */
        struct {
                __u64 hardware_exit_reason;
        } hw;
```

If exit_reason is KVM_EXIT_UNKNOWN, the vcpu has exited due to unknown reasons.  Further architecture-specific information is available in hardware_exit_reason.



```text
/* KVM_EXIT_FAIL_ENTRY */
struct {
        __u64 hardware_entry_failure_reason;
        __u32 cpu; /* if KVM_LAST_CPU */
} fail_entry;
```

If exit_reason is KVM_EXIT_FAIL_ENTRY, the vcpu could not be run due to unknown reasons.  Further architecture-specific information is available in hardware_entry_failure_reason.



```text
/* KVM_EXIT_EXCEPTION */
struct {
        __u32 exception;
        __u32 error_code;
} ex;
```

Unused.



```text
              /* KVM_EXIT_IO */
              struct {
#define KVM_EXIT_IO_IN  0
#define KVM_EXIT_IO_OUT 1
                      __u8 direction;
                      __u8 size; /* bytes */
                      __u16 port;
                      __u32 count;
                      __u64 data_offset; /* relative to kvm_run start */
              } io;
```

If exit_reason is KVM_EXIT_IO, then the vcpu has executed a port I/O instruction which could not be satisfied by kvm. data_offset describes where the data is located (KVM_EXIT_IO_OUT) or where kvm expects application code to place the data for the next KVM_RUN invocation (KVM_EXIT_IO_IN).  Data format is a packed array.



```text
/* KVM_EXIT_DEBUG */
struct {
        struct kvm_debug_exit_arch arch;
} debug;
```

If the exit_reason is KVM_EXIT_DEBUG, then a vcpu is processing a debug event for which architecture specific information is returned.



```text
/* KVM_EXIT_MMIO */
struct {
        __u64 phys_addr;
        __u8  data[8];
        __u32 len;
        __u8  is_write;
} mmio;
```

If exit_reason is KVM_EXIT_MMIO, then the vcpu has executed a memory-mapped I/O instruction which could not be satisfied by kvm.  The 'data' member contains the written data if 'is_write' is true, and should be filled by application code otherwise.

The 'data' member contains, in its first 'len' bytes, the value as it would appear if the VCPU performed a load or store of the appropriate width directly to the byte array.

> [!NOTE]
>
> For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR, KVM_EXIT_XEN, KVM_EXIT_EPR, KVM_EXIT_HYPERCALL, KVM_EXIT_TDX, KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR the corresponding operations are complete (and guest state is consistent) only after userspace has re-entered the kernel with KVM_RUN.  The kernel side will first finish incomplete operations and then check for pending signals.
>
> The pending state of the operation is not preserved in state which is visible to userspace, thus userspace should ensure that the operation is completed before performing a live migration.  Userspace can re-enter the guest with an unmasked signal pending or with the immediate_exit field set to complete pending operations without allowing any further instructions to be executed.



```text
/* KVM_EXIT_HYPERCALL */
struct {
        __u64 nr;
        __u64 args[6];
        __u64 ret;
        __u64 flags;
} hypercall;
```

It is strongly recommended that userspace use `KVM_EXIT_IO` (x86) or `KVM_EXIT_MMIO` (all except s390) to implement functionality that requires a guest to interact with host userspace.

> [!NOTE]
>
> KVM_EXIT_IO is significantly faster than KVM_EXIT_MMIO.

<a id="rst-for-arm64-1"></a>

### For arm64:

SMCCC exits can be enabled depending on the configuration of the SMCCC filter. See the [Documentation/virt/kvm/devices/vm.rst](/kernel/internals/virt/kvm-devices/vm.md) `KVM_ARM_SMCCC_FILTER` for more details.

`nr` contains the function ID of the guest's SMCCC call. Userspace is expected to use the `KVM_GET_ONE_REG` ioctl to retrieve the call parameters from the vCPU's GPRs.

- **Definition of `flags`:**

  - `KVM_HYPERCALL_EXIT_SMC`: Indicates that the guest used the SMC conduit to initiate the SMCCC call. If this bit is 0 then the guest used the HVC conduit for the SMCCC call.

  - `KVM_HYPERCALL_EXIT_16BIT`: Indicates that the guest used a 16bit instruction to initiate the SMCCC call. If this bit is 0 then the guest used a 32bit instruction. An AArch64 guest always has this bit set to 0.

At the point of exit, PC points to the instruction immediately following the trapping instruction.



```text
/* KVM_EXIT_TPR_ACCESS */
struct {
        __u64 rip;
        __u32 is_write;
        __u32 pad;
} tpr_access;
```

To be documented (KVM_TPR_ACCESS_REPORTING).



```text
/* KVM_EXIT_S390_SIEIC */
struct {
        __u8 icptcode;
        __u64 mask; /* psw upper half */
        __u64 addr; /* psw lower half */
        __u16 ipa;
        __u32 ipb;
} s390_sieic;
```

s390 specific.



```text
              /* KVM_EXIT_S390_RESET */
#define KVM_S390_RESET_POR       1
#define KVM_S390_RESET_CLEAR     2
#define KVM_S390_RESET_SUBSYSTEM 4
#define KVM_S390_RESET_CPU_INIT  8
#define KVM_S390_RESET_IPL       16
              __u64 s390_reset_flags;
```

s390 specific.



```text
/* KVM_EXIT_S390_UCONTROL */
struct {
        __u64 trans_exc_code;
        __u32 pgm_code;
} s390_ucontrol;
```

s390 specific. A page fault has occurred for a user controlled virtual machine (KVM_VM_S390_UNCONTROL) on its host page table that cannot be resolved by the kernel. The program code and the translation exception code that were placed in the cpu's lowcore are presented here as defined by the z Architecture Principles of Operation Book in the Chapter for Dynamic Address Translation (DAT)



```text
/* KVM_EXIT_DCR */
struct {
        __u32 dcrn;
        __u32 data;
        __u8  is_write;
} dcr;
```

Deprecated - was used for 440 KVM.



```text
/* KVM_EXIT_OSI */
struct {
        __u64 gprs[32];
} osi;
```

MOL uses a special hypercall interface it calls 'OSI'. To enable it, we catch hypercalls and exit with this exit struct that contains all the guest gprs.

If exit_reason is KVM_EXIT_OSI, then the vcpu has triggered such a hypercall. Userspace can now handle the hypercall and when it's done modify the gprs as necessary. Upon guest entry all guest GPRs will then be replaced by the values in this struct.



```text
/* KVM_EXIT_PAPR_HCALL */
struct {
        __u64 nr;
        __u64 ret;
        __u64 args[9];
} papr_hcall;
```

This is used on 64-bit PowerPC when emulating a pSeries partition, e.g. with the 'pseries' machine type in qemu.  It occurs when the guest does a hypercall using the 'sc 1' instruction.  The 'nr' field contains the hypercall number (from the guest R3), and 'args' contains the arguments (from the guest R4 - R12).  Userspace should put the return code in 'ret' and any extra returned values in args\[\]. The possible hypercalls are defined in the Power Architecture Platform Requirements (PAPR) document available from www.power.org (free developer registration required to access it).



```text
/* KVM_EXIT_S390_TSCH */
struct {
        __u16 subchannel_id;
        __u16 subchannel_nr;
        __u32 io_int_parm;
        __u32 io_int_word;
        __u32 ipb;
        __u8 dequeued;
} s390_tsch;
```

s390 specific. This exit occurs when KVM_CAP_S390_CSS_SUPPORT has been enabled and TEST SUBCHANNEL was intercepted. If dequeued is set, a pending I/O interrupt for the target subchannel has been dequeued and subchannel_id, subchannel_nr, io_int_parm and io_int_word contain the parameters for that interrupt. ipb is needed for instruction parameter decoding.



```text
/* KVM_EXIT_EPR */
struct {
        __u32 epr;
} epr;
```

On FSL BookE PowerPC chips, the interrupt controller has a fast patch interrupt acknowledge path to the core. When the core successfully delivers an interrupt, it automatically populates the EPR register with the interrupt vector number and acknowledges the interrupt inside the interrupt controller.

In case the interrupt controller lives in user space, we need to do the interrupt acknowledge cycle through it to fetch the next to be delivered interrupt vector using this exit.

It gets triggered whenever both KVM_CAP_PPC_EPR are enabled and an external interrupt has just been delivered into the guest. User space should put the acknowledged interrupt vector into the 'epr' field.



```text
              /* KVM_EXIT_SYSTEM_EVENT */
              struct {
#define KVM_SYSTEM_EVENT_SHUTDOWN       1
#define KVM_SYSTEM_EVENT_RESET          2
#define KVM_SYSTEM_EVENT_CRASH          3
#define KVM_SYSTEM_EVENT_WAKEUP         4
#define KVM_SYSTEM_EVENT_SUSPEND        5
#define KVM_SYSTEM_EVENT_SEV_TERM       6
#define KVM_SYSTEM_EVENT_TDX_FATAL      7
                      __u32 type;
                      __u32 ndata;
                      __u64 data[16];
              } system_event;
```

If exit_reason is KVM_EXIT_SYSTEM_EVENT then the vcpu has triggered a system-level event using some architecture specific mechanism (hypercall or some special instruction). In case of ARM64, this is triggered using HVC instruction based PSCI call from the vcpu.

The 'type' field describes the system-level event type. Valid values for 'type' are:

> - KVM_SYSTEM_EVENT_SHUTDOWN -- the guest has requested a shutdown of the VM. Userspace is not obliged to honour this, and if it does honour this does not need to destroy the VM synchronously (ie it may call KVM_RUN again before shutdown finally occurs).
>
> - KVM_SYSTEM_EVENT_RESET -- the guest has requested a reset of the VM. As with SHUTDOWN, userspace can choose to ignore the request, or to schedule the reset to occur in the future and may call KVM_RUN again.
>
> - KVM_SYSTEM_EVENT_CRASH -- the guest crash occurred and the guest has requested a crash condition maintenance. Userspace can choose to ignore the request, or to gather VM memory core dump and/or reset/shutdown of the VM.
>
> - KVM_SYSTEM_EVENT_SEV_TERM -- an AMD SEV guest requested termination. The guest physical address of the guest's GHCB is stored in `data[0]`.
>
> - KVM_SYSTEM_EVENT_TDX_FATAL -- a TDX guest reported a fatal error state. KVM doesn't do any parsing or conversion, it just dumps 16 general-purpose registers to userspace, in ascending order of the 4-bit indices for x86-64 general-purpose registers in instruction encoding, as defined in the Intel SDM.
>
> - KVM_SYSTEM_EVENT_WAKEUP -- the exiting vCPU is in a suspended state and KVM has recognized a wakeup event. Userspace may honor this event by marking the exiting vCPU as runnable, or deny it and call KVM_RUN again.
>
> - KVM_SYSTEM_EVENT_SUSPEND -- the guest has requested a suspension of the VM.

If KVM_CAP_SYSTEM_EVENT_DATA is present, the 'data' field can contain architecture specific information for the system-level event.  Only the first `ndata` items (possibly zero) of the data array are valid.

> - for arm64, data\[0\] is set to KVM_SYSTEM_EVENT_RESET_FLAG_PSCI_RESET2 if the guest issued a SYSTEM_RESET2 call according to v1.1 of the PSCI specification.
>
> - for arm64, data\[0\] is set to KVM_SYSTEM_EVENT_SHUTDOWN_FLAG_PSCI_OFF2 if the guest issued a SYSTEM_OFF2 call according to v1.3 of the PSCI specification.
>
> - for RISC-V, data\[0\] is set to the value of the second argument of the `sbi_system_reset` call.

Previous versions of Linux defined a `flags` member in this struct.  The field is now aliased to `data[0]`.  Userspace can assume that it is only written if ndata is greater than 0.

<a id="rst-for-arm-arm64"></a>

### For arm/arm64:

KVM_SYSTEM_EVENT_SUSPEND exits are enabled with the KVM_CAP_ARM_SYSTEM_SUSPEND VM capability. If a guest invokes the PSCI SYSTEM_SUSPEND function, KVM will exit to userspace with this event type.

It is the sole responsibility of userspace to implement the PSCI SYSTEM_SUSPEND call according to ARM DEN0022D.b 5.19 "SYSTEM_SUSPEND". KVM does not change the vCPU's state before exiting to userspace, so the call parameters are left in-place in the vCPU registers.

Userspace is \_required\_ to take action for such an exit. It must either:

> - Honor the guest request to suspend the VM. Userspace can request in-kernel emulation of suspension by setting the calling vCPU's state to KVM_MP_STATE_SUSPENDED. Userspace must configure the vCPU's state according to the parameters passed to the PSCI function when the calling vCPU is resumed. See ARM DEN0022D.b 5.19.1 "Intended use" for details on the function parameters.
>
> - Deny the guest request to suspend the VM. See ARM DEN0022D.b 5.19.2 "Caller responsibilities" for possible return values.

Hibernation using the PSCI SYSTEM_OFF2 call is enabled when PSCI v1.3 is enabled. If a guest invokes the PSCI SYSTEM_OFF2 function, KVM will exit to userspace with the KVM_SYSTEM_EVENT_SHUTDOWN event type and with data\[0\] set to KVM_SYSTEM_EVENT_SHUTDOWN_FLAG_PSCI_OFF2. The only supported hibernate type for the SYSTEM_OFF2 function is HIBERNATE_OFF.



```text
/* KVM_EXIT_IOAPIC_EOI */
struct {
        __u8 vector;
} eoi;
```

Indicates that the VCPU's in-kernel local APIC received an EOI for a level-triggered IOAPIC interrupt.  This exit only triggers when the IOAPIC is implemented in userspace (i.e. KVM_CAP_SPLIT_IRQCHIP is enabled); the userspace IOAPIC should process the EOI and retrigger the interrupt if it is still asserted.  Vector is the LAPIC interrupt vector for which the EOI was received.



```text
              struct kvm_hyperv_exit {
#define KVM_EXIT_HYPERV_SYNIC          1
#define KVM_EXIT_HYPERV_HCALL          2
#define KVM_EXIT_HYPERV_SYNDBG         3
                      __u32 type;
                      __u32 pad1;
                      union {
                              struct {
                                      __u32 msr;
                                      __u32 pad2;
                                      __u64 control;
                                      __u64 evt_page;
                                      __u64 msg_page;
                              } synic;
                              struct {
                                      __u64 input;
                                      __u64 result;
                                      __u64 params[2];
                              } hcall;
                              struct {
                                      __u32 msr;
                                      __u32 pad2;
                                      __u64 control;
                                      __u64 status;
                                      __u64 send_page;
                                      __u64 recv_page;
                                      __u64 pending_page;
                              } syndbg;
                      } u;
              };
              /* KVM_EXIT_HYPERV */
              struct kvm_hyperv_exit hyperv;
```

Indicates that the VCPU exits into userspace to process some tasks related to Hyper-V emulation.

Valid values for 'type' are:

> - KVM_EXIT_HYPERV_SYNIC -- synchronously notify user-space about

Hyper-V SynIC state change. Notification is used to remap SynIC event/message pages and to enable/disable SynIC messages/events processing in userspace.

> - KVM_EXIT_HYPERV_SYNDBG -- synchronously notify user-space about

Hyper-V Synthetic debugger state change. Notification is used to either update the pending_page location or to send a control command (send the buffer located in send_page or recv a buffer to recv_page).



```text
/* KVM_EXIT_ARM_NISV / KVM_EXIT_ARM_LDST64B */
struct {
        __u64 esr_iss;
        __u64 fault_ipa;
} arm_nisv;
```

- KVM_EXIT_ARM_NISV:

Used on arm64 systems. If a guest accesses memory not in a memslot, KVM will typically return to userspace and ask it to do MMIO emulation on its behalf. However, for certain classes of instructions, no instruction decode (direction, length of memory access) is provided, and fetching and decoding the instruction from the VM is overly complicated to live in the kernel.

Historically, when this situation occurred, KVM would print a warning and kill the VM. KVM assumed that if the guest accessed non-memslot memory, it was trying to do I/O, which just couldn't be emulated, and the warning message was phrased accordingly. However, what happened more often was that a guest bug caused access outside the guest memory areas which should lead to a more meaningful warning message and an external abort in the guest, if the access did not fall within an I/O window.

Userspace implementations can query for KVM_CAP_ARM_NISV_TO_USER, and enable this capability at VM creation. Once this is done, these types of errors will instead return to userspace with KVM_EXIT_ARM_NISV, with the valid bits from the ESR_EL2 in the esr_iss field, and the faulting IPA in the fault_ipa field. Userspace can either fix up the access if it's actually an I/O access by decoding the instruction from guest memory (if it's very brave) and continue executing the guest, or it can decide to suspend, dump, or restart the guest.

Note that KVM does not skip the faulting instruction as it does for KVM_EXIT_MMIO, but userspace has to emulate any change to the processing state if it decides to decode and emulate the instruction.

This feature isn't available to protected VMs, as userspace does not have access to the state that is required to perform the emulation. Instead, a data abort exception is directly injected in the guest. Note that although KVM_CAP_ARM_NISV_TO_USER will be reported if queried outside of a protected VM context, the feature will not be exposed if queried on a protected VM file descriptor.

- KVM_EXIT_ARM_LDST64B:

Used on arm64 systems. When a guest using a LD64B, ST64B, ST64BV, ST64BV0, outside of a memslot, KVM will return to userspace with KVM_EXIT_ARM_LDST64B, exposing the relevant ESR_EL2 information and faulting IPA, similarly to KVM_EXIT_ARM_NISV.

Userspace is supposed to fully emulate the instructions, which includes:

> - fetch of the operands for a store, including ACCDATA_EL1 in the case of a ST64BV0 instruction
>
> - deal with the endianness if the guest is big-endian
>
> - emulate the access, including the delivery of an exception if the access didn't succeed
>
> - provide a return value in the case of ST64BV/ST64BV0
>
> - return the data in the case of a load
>
> - increment PC if the instruction was successfully executed

Note that there is no expectation of performance for this emulation, as it involves a large number of interaction with the guest state. It is, however, expected that the instruction's semantics are preserved, specially the single-copy atomicity property of the 64 byte access.

This exit reason must be handled if userspace sets ID_AA64ISAR1_EL1.LS64 to a non-zero value, indicating that FEAT_LS64\* is enabled.



```text
/* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
struct {
        __u8 error; /* user -> kernel */
        __u8 pad[7];
        __u32 reason; /* kernel -> user */
        __u32 index; /* kernel -> user */
        __u64 data; /* kernel <-> user */
} msr;
```

Used on x86 systems. When the VM capability KVM_CAP_X86_USER_SPACE_MSR is enabled, MSR accesses to registers that would invoke a \#GP by KVM kernel code may instead trigger a KVM_EXIT_X86_RDMSR exit for reads and KVM_EXIT_X86_WRMSR exit for writes.

The "reason" field specifies why the MSR interception occurred. Userspace will only receive MSR exits when a particular reason was requested during through ENABLE_CAP. Currently valid exit reasons are:


<table>
<tbody>
<tr>
<td>


KVM_MSR_EXIT_REASON_UNKNOWN

</td>
<td>


access to MSR that is unknown to KVM

</td>
</tr>
<tr>
<td>


KVM_MSR_EXIT_REASON_INVAL

</td>
<td>


access to invalid MSRs or reserved bits

</td>
</tr>
<tr>
<td>


KVM_MSR_EXIT_REASON_FILTER

</td>
<td>


access blocked by KVM_X86_SET_MSR_FILTER

</td>
</tr>
</tbody>
</table>

For KVM_EXIT_X86_RDMSR, the "index" field tells userspace which MSR the guest wants to read. To respond to this request with a successful read, userspace writes the respective data into the "data" field and must continue guest execution to ensure the read data is transferred into guest register state.

If the RDMSR request was unsuccessful, userspace indicates that with a "1" in the "error" field. This will inject a \#GP into the guest when the VCPU is executed again.

For KVM_EXIT_X86_WRMSR, the "index" field tells userspace which MSR the guest wants to write. Once finished processing the event, userspace must continue vCPU execution. If the MSR write was unsuccessful, userspace also sets the "error" field to "1".

See KVM_X86_SET_MSR_FILTER for details on the interaction with MSR filtering.



```text
              struct kvm_xen_exit {
#define KVM_EXIT_XEN_HCALL          1
                      __u32 type;
                      union {
                              struct {
                                      __u32 longmode;
                                      __u32 cpl;
                                      __u64 input;
                                      __u64 result;
                                      __u64 params[6];
                              } hcall;
                      } u;
              };
              /* KVM_EXIT_XEN */
              struct kvm_hyperv_exit xen;
```

Indicates that the VCPU exits into userspace to process some tasks related to Xen emulation.

Valid values for 'type' are:

> - KVM_EXIT_XEN_HCALL -- synchronously notify user-space about Xen hypercall. Userspace is expected to place the hypercall result into the appropriate field before invoking KVM_RUN again.



```text
/* KVM_EXIT_RISCV_SBI */
struct {
        unsigned long extension_id;
        unsigned long function_id;
        unsigned long args[6];
        unsigned long ret[2];
} riscv_sbi;
```

If exit reason is KVM_EXIT_RISCV_SBI then it indicates that the VCPU has done a SBI call which is not handled by KVM RISC-V kernel module. The details of the SBI call are available in 'riscv_sbi' member of kvm_run structure. The 'extension_id' field of 'riscv_sbi' represents SBI extension ID whereas the 'function_id' field represents function ID of given SBI extension. The 'args' array field of 'riscv_sbi' represents parameters for the SBI call and 'ret' array field represents return values. The userspace should update the return values of SBI call before resuming the VCPU. For more details on RISC-V SBI spec refer, [https://github.com/riscv/riscv-sbi-doc](<https://github.com/riscv/riscv-sbi-doc>).



```text
              /* KVM_EXIT_MEMORY_FAULT */
              struct {
#define KVM_MEMORY_EXIT_FLAG_PRIVATE  (1ULL << 3)
                      __u64 flags;
                      __u64 gpa;
                      __u64 size;
              } memory_fault;
```

KVM_EXIT_MEMORY_FAULT indicates the vCPU has encountered a memory fault that could not be resolved by KVM.  The 'gpa' and 'size' (in bytes) describe the guest physical address range \[gpa, gpa + size) of the fault.  The 'flags' field describes properties of the faulting access that are likely pertinent:

> - KVM_MEMORY_EXIT_FLAG_PRIVATE - When set, indicates the memory fault occurred on a private memory access.  When clear, indicates the fault occurred on a shared access.

Note\!  KVM_EXIT_MEMORY_FAULT is unique among all KVM exit reasons in that it accompanies a return code of '-1', not '0'\!  errno will always be set to EFAULT or EHWPOISON when KVM exits with KVM_EXIT_MEMORY_FAULT, userspace should assume kvm_run.exit_reason is stale/undefined for all other error numbers.



```text
  /* KVM_EXIT_NOTIFY */
  struct {
#define KVM_NOTIFY_CONTEXT_INVALID    (1 << 0)
    __u32 flags;
  } notify;
```

Used on x86 systems. When the VM capability KVM_CAP_X86_NOTIFY_VMEXIT is enabled, a VM exit generated if no event window occurs in VM non-root mode for a specified amount of time. Once KVM_X86_NOTIFY_VMEXIT_USER is set when enabling the cap, it would exit to userspace with the exit reason KVM_EXIT_NOTIFY for further handling. The "flags" field contains more detailed info.

The valid value for 'flags' is:

> - KVM_NOTIFY_CONTEXT_INVALID -- the VM context is corrupted and not valid in VMCS. It would run into unknown result if resume the target VM.



```text
/* KVM_EXIT_TDX */
struct {
        __u64 flags;
        __u64 nr;
        union {
                struct {
                        u64 ret;
                        u64 data[5];
                } unknown;
                struct {
                        u64 ret;
                        u64 gpa;
                        u64 size;
                } get_quote;
                struct {
                        u64 ret;
                        u64 leaf;
                        u64 r11, r12, r13, r14;
                } get_tdvmcall_info;
                struct {
                        u64 ret;
                        u64 vector;
                } setup_event_notify;
        };
} tdx;
```

Process a TDVMCALL from the guest.  KVM forwards select TDVMCALL based on the Guest-Hypervisor Communication Interface (GHCI) specification; KVM bridges these requests to the userspace VMM with minimal changes, placing the inputs in the union and copying them back to the guest on re-entry.

Flags are currently always zero, whereas `nr` contains the TDVMCALL number from register R11.  The remaining field of the union provide the inputs and outputs of the TDVMCALL.  Currently the following values of `nr` are defined:

> - `TDVMCALL_GET_QUOTE`: the guest has requested to generate a TD-Quote signed by a service hosting TD-Quoting Enclave operating on the host. Parameters and return value are in the `get_quote` field of the union. The `gpa` field and `size` specify the guest physical address (without the shared bit set) and the size of a shared-memory buffer, in which the TDX guest passes a TD Report.  The `ret` field represents the return value of the GetQuote request.  When the request has been queued successfully, the TDX guest can poll the status field in the shared-memory area to check whether the Quote generation is completed or not. When completed, the generated Quote is returned via the same buffer.
>
> - `TDVMCALL_GET_TD_VM_CALL_INFO`: the guest has requested the support status of TDVMCALLs.  The output values for the given leaf should be placed in fields from `r11` to `r14` of the `get_tdvmcall_info` field of the union.
>
> - `TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT`: the guest has requested to set up a notification interrupt for vector `vector`.

KVM may add support for more values in the future that may cause a userspace exit, even without calls to `KVM_ENABLE_CAP` or similar.  In this case, it will enter with output fields already valid; in the common case, the `unknown.ret` field of the union will be `TDVMCALL_STATUS_SUBFUNC_UNSUPPORTED`. Userspace need not do anything if it does not wish to support a TDVMCALL.



```text
              /* KVM_EXIT_ARM_SEA */
              struct {
#define KVM_EXIT_ARM_SEA_FLAG_GPA_VALID   (1ULL << 0)
                      __u64 flags;
                      __u64 esr;
                      __u64 gva;
                      __u64 gpa;
              } arm_sea;
```

Used on arm64 systems. When the VM capability `KVM_CAP_ARM_SEA_TO_USER` is enabled, a KVM exits to userspace if a guest access causes a synchronous external abort (SEA) and the host APEI fails to handle the SEA.

`esr` is set to a sanitized value of ESR_EL2 from the exception taken to KVM, consisting of the following fields:

> - `ESR_EL2.EC`
>
> - `ESR_EL2.IL`
>
> - `ESR_EL2.FnV`
>
> - `ESR_EL2.EA`
>
> - `ESR_EL2.CM`
>
> - `ESR_EL2.WNR`
>
> - `ESR_EL2.FSC`
>
> - `ESR_EL2.SET` (when FEAT_RAS is implemented for the VM)

`gva` is set to the value of FAR_EL2 from the exception taken to KVM when `ESR_EL2.FnV == 0`. Otherwise, the value of `gva` is unknown.

`gpa` is set to the faulting IPA from the exception taken to KVM when the `KVM_EXIT_ARM_SEA_FLAG_GPA_VALID` flag is set. Otherwise, the value of `gpa` is unknown.



```text
        /* Fix the size of the union. */
        char padding[256];
};

/*
 * shared registers between kvm and userspace.
 * kvm_valid_regs specifies the register classes set by the host
 * kvm_dirty_regs specified the register classes dirtied by userspace
 * struct kvm_sync_regs is architecture specific, as well as the
 * bits for kvm_valid_regs and kvm_dirty_regs
 */
__u64 kvm_valid_regs;
__u64 kvm_dirty_regs;
union {
        struct kvm_sync_regs regs;
        char padding[SYNC_REGS_SIZE_BYTES];
} s;
```

If KVM_CAP_SYNC_REGS is defined, these fields allow userspace to access certain guest registers without having to call SET/GET\_\*REGS. Thus we can avoid some system call overhead if userspace has to handle the exit. Userspace can query the validity of the structure by checking kvm_valid_regs for specific bits. These bits are architecture specific and usually define the validity of a groups of registers. (e.g. one bit for general purpose registers)

Please note that the kernel is allowed to use the kvm_run structure as the primary storage for certain register types. Therefore, the kernel may use the values in kvm_run even if the corresponding bit in kvm_dirty_regs is not set.



```text
/* KVM_EXIT_SNP_REQ_CERTS */
struct kvm_exit_snp_req_certs {
        __u64 gpa;
        __u64 npages;
        __u64 ret;
};
```

KVM_EXIT_SNP_REQ_CERTS indicates an SEV-SNP guest with certificate-fetching enabled (see KVM_SEV_SNP_ENABLE_REQ_CERTS) has generated an Extended Guest Request NAE \#VMGEXIT (SNP_GUEST_REQUEST) with message type MSG_REPORT_REQ, i.e. has requested an attestation report from firmware, and would like the certificate data corresponding to the attestation report signature to be provided by the hypervisor as part of the request.

To allow for userspace to provide the certificate, the 'gpa' and 'npages' are forwarded verbatim from the guest request (the RAX and RBX GHCB fields respectively).  'ret' is not an "output" from KVM, and is always '0' on exit.  KVM verifies the 'gpa' is 4KiB aligned prior to exiting to userspace, but otherwise the information from the guest isn't validated.

Upon the next KVM_RUN, e.g. after userspace has serviced the request (or not), KVM will complete the \#VMGEXIT, using the 'ret' field to determine whether to signal success or failure to the guest, and on failure, what reason code will be communicated via SW_EXITINFO2.  If 'ret' is set to an unsupported value (see the table below), KVM_RUN will fail with -EINVAL.  For a 'ret' of 'ENOSPC', KVM also consumes the 'npages' field, i.e. userspace can use the field to inform the guest of the number of pages needed to hold all the certificate data.

The supported 'ret' values and their respective SW_EXITINFO2 encodings:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> 0x0, i.e. success.  KVM will emit an SNP_GUEST_REQUEST command to SNP firmware.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> ENOSPC
>
> </td>
> <td>
>
>
> 0x0000000100000000, i.e. not enough guest pages to hold the certificate table and certificate data.  KVM will also set the RBX field in the GHBC to 'npages'.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EAGAIN
>
> </td>
> <td>
>
>
> 0x0000000200000000, i.e. the host is busy and the guest should retry the request.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> EIO
>
> </td>
> <td>
>
>
> 0xffffffff00000000, for all other errors (this return code is a KVM-defined hypervisor value, as allowed by the GHCB)
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-capabilities-that-can-be-enabled-on-vcpus"></a>
<a id="rst-cap-enable"></a>

## 6. Capabilities that can be enabled on vCPUs

There are certain capabilities that change the behavior of the virtual CPU or the virtual machine when enabled. To enable them, please see [4.37 KVM_ENABLE_CAP](<#rst-kvm-enable-cap>).

Below you can find a list of capabilities and what their effect on the vCPU or the virtual machine is when enabling them.

The following information is provided along with the description:

> - **Architectures:**
>
>   which instruction set architectures provide this ioctl. x86 includes both i386 and x86_64.
>
> - **Target:**
>
>   whether this is a per-vcpu or per-vm capability.
>
> - **Parameters:**
>
>   what parameters are accepted by the capability.
>
> - **Returns:**
>
>   the return value.  General error numbers (EBADF, ENOMEM, EINVAL) are not detailed, but errors with specific meanings are.

<a id="rst-kvm-cap-ppc-osi"></a>

### 6.1 KVM_CAP_PPC_OSI

**Architectures:** ppc

**Target:** vcpu

**Parameters:** none

**Returns:** 0 on success; -1 on error

This capability enables interception of OSI hypercalls that otherwise would be treated as normal system calls to be injected into the guest. OSI hypercalls were invented by Mac-on-Linux to have a standardized communication mechanism between the guest and the host.

When this capability is enabled, KVM_EXIT_OSI can occur.

<a id="rst-kvm-cap-ppc-papr"></a>

### 6.2 KVM_CAP_PPC_PAPR

**Architectures:** ppc

**Target:** vcpu

**Parameters:** none

**Returns:** 0 on success; -1 on error

This capability enables interception of PAPR hypercalls. PAPR hypercalls are done using the hypercall instruction "sc 1".

It also sets the guest privilege level to "supervisor" mode. Usually the guest runs in "hypervisor" privilege mode with a few missing features.

In addition to the above, it changes the semantics of SDR1. In this mode, the HTAB address part of SDR1 contains an HVA instead of a GPA, as PAPR keeps the HTAB invisible to the guest.

When this capability is enabled, KVM_EXIT_PAPR_HCALL can occur.

<a id="rst-kvm-cap-sw-tlb"></a>

### 6.3 KVM_CAP_SW_TLB

**Architectures:** ppc

**Target:** vcpu

**Parameters:** args\[0\] is the address of a struct kvm_config_tlb

**Returns:** 0 on success; -1 on error



```text
struct kvm_config_tlb {
      __u64 params;
      __u64 array;
      __u32 mmu_type;
      __u32 array_len;
};
```

Configures the virtual CPU's TLB array, establishing a shared memory area between userspace and KVM.  The "params" and "array" fields are userspace addresses of mmu-type-specific data structures.  The "array_len" field is an safety mechanism, and should be set to the size in bytes of the memory that userspace has reserved for the array.  It must be at least the size dictated by "mmu_type" and "params".

While KVM_RUN is active, the shared region is under control of KVM.  Its contents are undefined, and any modification by userspace results in boundedly undefined behavior.

On return from KVM_RUN, the shared region will reflect the current state of the guest's TLB.  If userspace makes any changes, it must call KVM_DIRTY_TLB to tell KVM which entries have been changed, prior to calling KVM_RUN again on this vcpu.

For mmu types KVM_MMU_FSL_BOOKE_NOHV and KVM_MMU_FSL_BOOKE_HV:

> - The "params" field is of type "struct kvm_book3e_206_tlb_params".
>
> - The "array" field points to an array of type "struct kvm_book3e_206_tlb_entry".
>
> - The array consists of all entries in the first TLB, followed by all entries in the second TLB.
>
> - Within a TLB, entries are ordered first by increasing set number.  Within a set, entries are ordered by way (increasing ESEL).
>
> - The hash for determining set number in TLB0 is: (MAS2 &gt;&gt; 12) &amp; (num_sets - 1) where "num_sets" is the tlb_sizes\[\] value divided by the tlb_ways\[\] value.
>
> - The tsize field of mas1 shall be set to 4K on TLB0, even though the hardware ignores this value for TLB0.

<a id="rst-kvm-cap-s390-css-support"></a>

### 6.4 KVM_CAP_S390_CSS_SUPPORT

**Architectures:** s390

**Target:** vcpu

**Parameters:** none

**Returns:** 0 on success; -1 on error

This capability enables support for handling of channel I/O instructions.

TEST PENDING INTERRUPTION and the interrupt portion of TEST SUBCHANNEL are handled in-kernel, while the other I/O instructions are passed to userspace.

When this capability is enabled, KVM_EXIT_S390_TSCH will occur on TEST SUBCHANNEL intercepts.

Note that even though this capability is enabled per-vcpu, the complete virtual machine is affected.

<a id="rst-kvm-cap-ppc-epr"></a>

### 6.5 KVM_CAP_PPC_EPR

**Architectures:** ppc

**Target:** vcpu

**Parameters:** args\[0\] defines whether the proxy facility is active

**Returns:** 0 on success; -1 on error

This capability enables or disables the delivery of interrupts through the external proxy facility.

When enabled (args\[0\] \!= 0), every time the guest gets an external interrupt delivered, it automatically exits into user space with a KVM_EXIT_EPR exit to receive the topmost interrupt vector.

When disabled (args\[0\] == 0), behavior is as if this facility is unsupported.

When this capability is enabled, KVM_EXIT_EPR can occur.

<a id="rst-kvm-cap-irq-mpic"></a>

### 6.6 KVM_CAP_IRQ_MPIC

**Architectures:** ppc

**Parameters:** args\[0\] is the MPIC device fd; args\[1\] is the MPIC CPU number for this vcpu

This capability connects the vcpu to an in-kernel MPIC device.

<a id="rst-kvm-cap-irq-xics"></a>

### 6.7 KVM_CAP_IRQ_XICS

**Architectures:** ppc

**Target:** vcpu

**Parameters:** args\[0\] is the XICS device fd; args\[1\] is the XICS CPU number (server ID) for this vcpu

This capability connects the vcpu to an in-kernel XICS device.

<a id="rst-kvm-cap-s390-irqchip"></a>

### 6.8 KVM_CAP_S390_IRQCHIP

**Architectures:** s390

**Target:** vm

**Parameters:** none

This capability enables the in-kernel irqchip for s390. Please refer to "4.24 KVM_CREATE_IRQCHIP" for details.

<a id="rst-kvm-cap-mips-fpu"></a>

### 6.9 KVM_CAP_MIPS_FPU

**Architectures:** mips

**Target:** vcpu

**Parameters:** args\[0\] is reserved for future use (should be 0).

This capability allows the use of the host Floating Point Unit by the guest. It allows the Config1.FP bit to be set to enable the FPU in the guest. Once this is done the `KVM_REG_MIPS_FPR_*` and `KVM_REG_MIPS_FCR_*` registers can be accessed (depending on the current guest FPU register mode), and the Status.FR, Config5.FRE bits are accessible via the KVM API and also from the guest, depending on them being supported by the FPU.

<a id="rst-kvm-cap-mips-msa"></a>

### 6.10 KVM_CAP_MIPS_MSA

**Architectures:** mips

**Target:** vcpu

**Parameters:** args\[0\] is reserved for future use (should be 0).

This capability allows the use of the MIPS SIMD Architecture (MSA) by the guest. It allows the Config3.MSAP bit to be set to enable the use of MSA by the guest. Once this is done the `KVM_REG_MIPS_VEC_*` and `KVM_REG_MIPS_MSA_*` registers can be accessed, and the Config5.MSAEn bit is accessible via the KVM API and also from the guest.

<a id="rst-kvm-cap-sync-regs"></a>

### 6.74 KVM_CAP_SYNC_REGS

**Architectures:** s390, x86

**Target:** s390: always enabled, x86: vcpu

**Parameters:** none

**Returns:** x86: KVM_CHECK_EXTENSION returns a bit-array indicating which register sets are supported (bitfields defined in arch/x86/include/uapi/asm/kvm.h).

As described above in the kvm_sync_regs struct info in section [5. The kvm_run structure](<#rst-kvm-run-1>), KVM_CAP_SYNC_REGS "allow\[s\] userspace to access certain guest registers without having to call SET/GET\_\*REGS". This reduces overhead by eliminating repeated ioctl calls for setting and/or getting register values. This is particularly important when userspace is making synchronous guest state modifications, e.g. when emulating and/or intercepting instructions in userspace.

For s390 specifics, please refer to the source code.

For x86:

- the register sets to be copied out to kvm_run are selectable by userspace (rather that all sets being copied out for every exit).

- vcpu_events are available in addition to regs and sregs.

For x86, the 'kvm_valid_regs' field of struct kvm_run is overloaded to function as an input bit-array field set by userspace to indicate the specific register sets to be copied out on the next exit.

To indicate when userspace has modified values that should be copied into the vCPU, the all architecture bitarray field, 'kvm_dirty_regs' must be set. This is done using the same bitflags as for the 'kvm_valid_regs' field. If the dirty bit is not set, then the register set values will not be copied into the vCPU even if they've been modified.

Unused bitfields in the bitarrays must be set to zero.



```text
struct kvm_sync_regs {
      struct kvm_regs regs;
      struct kvm_sregs sregs;
      struct kvm_vcpu_events events;
};
```

<a id="rst-kvm-cap-ppc-irq-xive"></a>

### 6.75 KVM_CAP_PPC_IRQ_XIVE

**Architectures:** ppc

**Target:** vcpu

**Parameters:** args\[0\] is the XIVE device fd; args\[1\] is the XIVE CPU number (server ID) for this vcpu

This capability connects the vcpu to an in-kernel XIVE device.

<a id="rst-kvm-cap-hyperv-synic"></a>

### 6.76 KVM_CAP_HYPERV_SYNIC

**Architectures:** x86

**Target:** vcpu

This capability, if KVM_CHECK_EXTENSION indicates that it is available, means that the kernel has an implementation of the Hyper-V Synthetic interrupt controller(SynIC). Hyper-V SynIC is used to support Windows Hyper-V based guest paravirt drivers(VMBus).

In order to use SynIC, it has to be activated by setting this capability via KVM_ENABLE_CAP ioctl on the vcpu fd. Note that this will disable the use of APIC hardware virtualization even if supported by the CPU, as it's incompatible with SynIC auto-EOI behavior.

<a id="rst-kvm-cap-hyperv-synic2"></a>

### 6.77 KVM_CAP_HYPERV_SYNIC2

**Architectures:** x86

**Target:** vcpu

This capability enables a newer version of Hyper-V Synthetic interrupt controller (SynIC).  The only difference with KVM_CAP_HYPERV_SYNIC is that KVM doesn't clear SynIC message and event flags pages when they are enabled by writing to the respective MSRs.

<a id="rst-kvm-cap-hyperv-direct-tlbflush"></a>

### 6.78 KVM_CAP_HYPERV_DIRECT_TLBFLUSH

**Architectures:** x86

**Target:** vcpu

This capability indicates that KVM running on top of Hyper-V hypervisor enables Direct TLB flush for its guests meaning that TLB flush hypercalls are handled by Level 0 hypervisor (Hyper-V) bypassing KVM. Due to the different ABI for hypercall parameters between Hyper-V and KVM, enabling this capability effectively disables all hypercall handling by KVM (as some KVM hypercall may be mistakenly treated as TLB flush hypercalls by Hyper-V) so userspace should disable KVM identification in CPUID and only exposes Hyper-V identification. In this case, guest thinks it's running on Hyper-V and only use Hyper-V hypercalls.

<a id="rst-kvm-cap-hyperv-enforce-cpuid"></a>

### 6.79 KVM_CAP_HYPERV_ENFORCE_CPUID

**Architectures:** x86

**Target:** vcpu

When enabled, KVM will disable emulated Hyper-V features provided to the guest according to the bits Hyper-V CPUID feature leaves. Otherwise, all currently implemented Hyper-V features are provided unconditionally when Hyper-V identification is set in the HYPERV_CPUID_INTERFACE (0x40000001) leaf.

<a id="rst-kvm-cap-enforce-pv-feature-cpuid"></a>

### 6.80 KVM_CAP_ENFORCE_PV_FEATURE_CPUID

**Architectures:** x86

**Target:** vcpu

When enabled, KVM will disable paravirtual features provided to the guest according to the bits in the KVM_CPUID_FEATURES CPUID leaf (0x40000001). Otherwise, a guest may use the paravirtual features regardless of what has actually been exposed through the CPUID leaf.

<a id="rst-capabilities-that-can-be-enabled-on-vms"></a>
<a id="rst-cap-enable-vm"></a>
<a id="rst-kvm-cap-dirty-log-ring"></a>

## 7. Capabilities that can be enabled on VMs

There are certain capabilities that change the behavior of the virtual machine when enabled. To enable them, please see section [4.37 KVM_ENABLE_CAP](<#rst-kvm-enable-cap>). Below you can find a list of capabilities and what their effect on the VM is when enabling them.

The following information is provided along with the description:

> - **Architectures:**
>
>   which instruction set architectures provide this ioctl. x86 includes both i386 and x86_64.
>
> - **Parameters:**
>
>   what parameters are accepted by the capability.
>
> - **Returns:**
>
>   the return value.  General error numbers (EBADF, ENOMEM, EINVAL) are not detailed, but errors with specific meanings are.

<a id="rst-kvm-cap-ppc-enable-hcall"></a>

### 7.1 KVM_CAP_PPC_ENABLE_HCALL

**Architectures:** ppc

**Parameters:** args\[0\] is the sPAPR hcall number; args\[1\] is 0 to disable, 1 to enable in-kernel handling

This capability controls whether individual sPAPR hypercalls (hcalls) get handled by the kernel or not.  Enabling or disabling in-kernel handling of an hcall is effective across the VM.  On creation, an initial set of hcalls are enabled for in-kernel handling, which consists of those hcalls for which in-kernel handlers were implemented before this capability was implemented.  If disabled, the kernel will not to attempt to handle the hcall, but will always exit to userspace to handle it.  Note that it may not make sense to enable some and disable others of a group of related hcalls, but KVM does not prevent userspace from doing that.

If the hcall number specified is not one that has an in-kernel implementation, the KVM_ENABLE_CAP ioctl will fail with an EINVAL error.

<a id="rst-kvm-cap-s390-user-sigp"></a>

### 7.2 KVM_CAP_S390_USER_SIGP

**Architectures:** s390

**Parameters:** none

This capability controls which SIGP orders will be handled completely in user space. With this capability enabled, all fast orders will be handled completely in the kernel:

- SENSE

- SENSE RUNNING

- EXTERNAL CALL

- EMERGENCY SIGNAL

- CONDITIONAL EMERGENCY SIGNAL

All other orders will be handled completely in user space.

Only privileged operation exceptions will be checked for in the kernel (or even in the hardware prior to interception). If this capability is not enabled, the old way of handling SIGP orders is used (partially in kernel and user space).

<a id="rst-kvm-cap-s390-vector-registers"></a>

### 7.3 KVM_CAP_S390_VECTOR_REGISTERS

**Architectures:** s390

**Parameters:** none

**Returns:** 0 on success, negative value on error

Allows use of the vector registers introduced with z13 processor, and provides for the synchronization between host and user space.  Will return -EINVAL if the machine does not support vectors.

<a id="rst-kvm-cap-s390-user-stsi"></a>

### 7.4 KVM_CAP_S390_USER_STSI

**Architectures:** s390

**Parameters:** none

This capability allows post-handlers for the STSI instruction. After initial handling in the kernel, KVM exits to user space with KVM_EXIT_S390_STSI to allow user space to insert further data.

Before exiting to userspace, kvm handlers should fill in s390_stsi field of vcpu-&gt;run:



```text
struct {
      __u64 addr;
      __u8 ar;
      __u8 reserved;
      __u8 fc;
      __u8 sel1;
      __u16 sel2;
} s390_stsi;

@addr - guest address of STSI SYSIB
@fc   - function code
@sel1 - selector 1
@sel2 - selector 2
@ar   - access register number
```

KVM handlers should exit to userspace with rc = -EREMOTE.

<a id="rst-kvm-cap-split-irqchip"></a>

### 7.5 KVM_CAP_SPLIT_IRQCHIP

**Architectures:** x86

**Parameters:** args\[0\] - number of routes reserved for userspace IOAPICs

**Returns:** 0 on success, -1 on error

Create a local apic for each processor in the kernel. This can be used instead of KVM_CREATE_IRQCHIP if the userspace VMM wishes to emulate the IOAPIC and PIC (and also the PIT, even though this has to be enabled separately).

This capability also enables in kernel routing of interrupt requests; when KVM_CAP_SPLIT_IRQCHIP only routes of KVM_IRQ_ROUTING_MSI type are used in the IRQ routing table.  The first args\[0\] MSI routes are reserved for the IOAPIC pins.  Whenever the LAPIC receives an EOI for these routes, a KVM_EXIT_IOAPIC_EOI vmexit will be reported to userspace.

Fails if VCPU has already been created, or if the irqchip is already in the kernel (i.e. KVM_CREATE_IRQCHIP has already been called).

<a id="rst-kvm-cap-s390-ri"></a>

### 7.6 KVM_CAP_S390_RI

**Architectures:** s390

**Parameters:** none

Allows use of runtime-instrumentation introduced with zEC12 processor. Will return -EINVAL if the machine does not support runtime-instrumentation. Will return -EBUSY if a VCPU has already been created.

<a id="rst-kvm-cap-x2apic-api"></a>

### 7.7 KVM_CAP_X2APIC_API

**Architectures:** x86

**Parameters:** args\[0\] - features that should be enabled

**Returns:** 0 on success, -EINVAL when args\[0\] contains invalid features

Valid feature flags in args\[0\] are:



```text
#define KVM_X2APIC_API_USE_32BIT_IDS                          (1ULL << 0)
#define KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK                (1ULL << 1)
#define KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST              (1ULL << 2)
#define KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST             (1ULL << 3)
```

Enabling KVM_X2APIC_API_USE_32BIT_IDS changes the behavior of KVM_SET_GSI_ROUTING, KVM_SIGNAL_MSI, KVM_SET_LAPIC, and KVM_GET_LAPIC, allowing the use of 32-bit APIC IDs.  See KVM_CAP_X2APIC_API in their respective sections.

KVM_X2APIC_API_DISABLE_BROADCAST_QUIRK must be enabled for x2APIC to work in logical mode or with more than 255 VCPUs.  Otherwise, KVM treats 0xff as a broadcast even in x2APIC mode in order to support physical x2APIC without interrupt remapping.  This is undesirable in logical mode, where 0xff represents CPUs 0-7 in cluster 0.

Setting KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST instructs KVM to enable Suppress EOI Broadcasts.  KVM will advertise support for Suppress EOI Broadcast to the guest and suppress LAPIC EOI broadcasts when the guest sets the Suppress EOI Broadcast bit in the SPIV register.  This flag is supported only when using a split IRQCHIP.

Setting KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST disables support for Suppress EOI Broadcasts entirely, i.e. instructs KVM to NOT advertise support to the guest.

Modern VMMs should either enable KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST or KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST.  If not, legacy quirky behavior will be used by KVM: in split IRQCHIP mode, KVM will advertise support for Suppress EOI Broadcasts but not actually suppress EOI broadcasts; for in-kernel IRQCHIP mode, KVM will not advertise support for Suppress EOI Broadcasts.

Setting both KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST and KVM_X2APIC_DISABLE_SUPPRESS_EOI_BROADCAST will fail with an EINVAL error, as will setting KVM_X2APIC_ENABLE_SUPPRESS_EOI_BROADCAST without a split IRCHIP.

<a id="rst-kvm-cap-s390-user-instr0"></a>

### 7.8 KVM_CAP_S390_USER_INSTR0

**Architectures:** s390

**Parameters:** none

With this capability enabled, the illegal instruction 0x0000 (2 bytes) will be intercepted and forwarded to user space. User space can use this mechanism e.g. to realize 2-byte software breakpoints. The kernel will not inject an operating exception for these instructions, user space has to take care of that.

This capability can be enabled dynamically even if VCPUs were already created and are running.

<a id="rst-kvm-cap-s390-gs"></a>

### 7.9 KVM_CAP_S390_GS

**Architectures:** s390

**Parameters:** none

**Returns:** 0 on success; -EINVAL if the machine does not support guarded storage; -EBUSY if a VCPU has already been created.

Allows use of guarded storage for the KVM guest.

<a id="rst-kvm-cap-s390-ais"></a>

### 7.10 KVM_CAP_S390_AIS

**Architectures:** s390

**Parameters:** none

Allow use of adapter-interruption suppression. :Returns: 0 on success; -EBUSY if a VCPU has already been created.

<a id="rst-kvm-cap-ppc-smt"></a>

### 7.11 KVM_CAP_PPC_SMT

**Architectures:** ppc

**Parameters:** vsmt_mode, flags

Enabling this capability on a VM provides userspace with a way to set the desired virtual SMT mode (i.e. the number of virtual CPUs per virtual core).  The virtual SMT mode, vsmt_mode, must be a power of 2 between 1 and 8.  On POWER8, vsmt_mode must also be no greater than the number of threads per subcore for the host.  Currently flags must be 0.  A successful call to enable this capability will result in vsmt_mode being returned when the KVM_CAP_PPC_SMT capability is subsequently queried for the VM.  This capability is only supported by HV KVM, and can only be set before any VCPUs have been created. The KVM_CAP_PPC_SMT_POSSIBLE capability indicates which virtual SMT modes are available.

<a id="rst-kvm-cap-ppc-fwnmi"></a>

### 7.12 KVM_CAP_PPC_FWNMI

**Architectures:** ppc

**Parameters:** none

With this capability a machine check exception in the guest address space will cause KVM to exit the guest with NMI exit reason. This enables QEMU to build error log and branch to guest kernel registered machine check handling routine. Without this capability KVM will branch to guests' 0x200 interrupt vector.

<a id="rst-kvm-cap-x86-disable-exits"></a>

### 7.13 KVM_CAP_X86_DISABLE_EXITS

**Architectures:** x86

**Parameters:** args\[0\] defines which exits are disabled

**Returns:** 0 on success, -EINVAL when args\[0\] contains invalid exits or if any vCPUs have already been created

Valid bits in args\[0\] are:



```text
#define KVM_X86_DISABLE_EXITS_MWAIT            (1 << 0)
#define KVM_X86_DISABLE_EXITS_HLT              (1 << 1)
#define KVM_X86_DISABLE_EXITS_PAUSE            (1 << 2)
#define KVM_X86_DISABLE_EXITS_CSTATE           (1 << 3)
#define KVM_X86_DISABLE_EXITS_APERFMPERF       (1 << 4)
```

Enabling this capability on a VM provides userspace with a way to no longer intercept some instructions for improved latency in some workloads, and is suggested when vCPUs are associated to dedicated physical CPUs.  More bits can be added in the future; userspace can just pass the KVM_CHECK_EXTENSION result to KVM_ENABLE_CAP to disable all such vmexits.

Do not enable KVM_FEATURE_PV_UNHALT if you disable HLT exits.

Virtualizing the `IA32_APERF` and `IA32_MPERF` MSRs requires more than just disabling APERF/MPERF exits. While both Intel and AMD document strict usage conditions for these MSRs--emphasizing that only the ratio of their deltas over a time interval (T0 to T1) is architecturally defined--simply passing through the MSRs can still produce an incorrect ratio.

This erroneous ratio can occur if, between T0 and T1:

1. The vCPU thread migrates between logical processors.

2. Live migration or suspend/resume operations take place.

3. Another task shares the vCPU's logical processor.

4. C-states lower than C0 are emulated (e.g., via HLT interception).

5. The guest TSC frequency doesn't match the host TSC frequency.

Due to these complexities, KVM does not automatically associate this passthrough capability with the guest CPUID bit, `CPUID.6:ECX.APERFMPERF[bit 0]`. Userspace VMMs that deem this mechanism adequate for virtualizing the `IA32_APERF` and `IA32_MPERF` MSRs must set the guest CPUID bit explicitly.

<a id="rst-kvm-cap-s390-hpage-1m"></a>

### 7.14 KVM_CAP_S390_HPAGE_1M

**Architectures:** s390

**Parameters:** none

**Returns:** 0 on success, -EINVAL if hpage module parameter was not set or cmma is enabled, or the VM has the KVM_VM_S390_UCONTROL flag set

With this capability the KVM support for memory backing with 1m pages through hugetlbfs can be enabled for a VM. After the capability is enabled, cmma can't be enabled anymore and pfmfi and the storage key interpretation are disabled. If cmma has already been enabled or the hpage module parameter is not set to 1, -EINVAL is returned.

While it is generally possible to create a huge page backed VM without this capability, the VM will not be able to run.

<a id="rst-kvm-cap-msr-platform-info"></a>

### 7.15 KVM_CAP_MSR_PLATFORM_INFO

**Architectures:** x86

**Parameters:** args\[0\] whether feature should be enabled or not

With this capability, a guest may read the MSR_PLATFORM_INFO MSR. Otherwise, a \#GP would be raised when the guest tries to access. Currently, this capability does not enable write permissions of this MSR for the guest.

<a id="rst-kvm-cap-ppc-nested-hv"></a>

### 7.16 KVM_CAP_PPC_NESTED_HV

**Architectures:** ppc

**Parameters:** none

**Returns:** 0 on success, -EINVAL when the implementation doesn't support nested-HV virtualization.

HV-KVM on POWER9 and later systems allows for "nested-HV" virtualization, which provides a way for a guest VM to run guests that can run using the CPU's supervisor mode (privileged non-hypervisor state).  Enabling this capability on a VM depends on the CPU having the necessary functionality and on the facility being enabled with a kvm-hv module parameter.

<a id="rst-kvm-cap-exception-payload"></a>

### 7.17 KVM_CAP_EXCEPTION_PAYLOAD

**Architectures:** x86

**Parameters:** args\[0\] whether feature should be enabled or not

With this capability enabled, CR2 will not be modified prior to the emulated VM-exit when L1 intercepts a \#PF exception that occurs in L2. Similarly, for kvm-intel only, DR6 will not be modified prior to the emulated VM-exit when L1 intercepts a \#DB exception that occurs in L2. As a result, when KVM_GET_VCPU_EVENTS reports a pending \#PF (or \#DB) exception for L2, exception.has_payload will be set and the faulting address (or the new DR6 bits\*) will be reported in the exception_payload field. Similarly, when userspace injects a \#PF (or \#DB) into L2 using KVM_SET_VCPU_EVENTS, it is expected to set exception.has_payload and to put the faulting address - or the new DR6 bits<a id="rst-footnote-reference-5"></a>[3](#rst-footnote-3) - in the exception_payload field.

This capability also enables exception.pending in struct kvm_vcpu_events, which allows userspace to distinguish between pending and injected exceptions.

<a id="rst-footnote-3"></a>



**[3]** For the new DR6 bits, note that bit 16 is set iff the \#DB exception will clear DR6.RTM.

<a id="rst-kvm-cap-manual-dirty-log-protect2"></a>

### 7.18 KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2

**Architectures:** x86, arm64, mips

**Parameters:** args\[0\] whether feature should be enabled or not

Valid flags are:



```text
#define KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE   (1 << 0)
#define KVM_DIRTY_LOG_INITIALLY_SET           (1 << 1)
```

With KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE is set, KVM_GET_DIRTY_LOG will not automatically clear and write-protect all pages that are returned as dirty. Rather, userspace will have to do this operation separately using KVM_CLEAR_DIRTY_LOG.

At the cost of a slightly more complicated operation, this provides better scalability and responsiveness for two reasons.  First, KVM_CLEAR_DIRTY_LOG ioctl can operate on a 64-page granularity rather than requiring to sync a full memslot; this ensures that KVM does not take spinlocks for an extended period of time.  Second, in some cases a large amount of time can pass between a call to KVM_GET_DIRTY_LOG and userspace actually using the data in the page.  Pages can be modified during this time, which is inefficient for both the guest and userspace: the guest will incur a higher penalty due to write protection faults, while userspace can see false reports of dirty pages.  Manual reprotection helps reducing this time, improving guest performance and reducing the number of dirty log false positives.

With KVM_DIRTY_LOG_INITIALLY_SET set, all the bits of the dirty bitmap will be initialized to 1 when created.  This also improves performance because dirty logging can be enabled gradually in small chunks on the first call to KVM_CLEAR_DIRTY_LOG.  KVM_DIRTY_LOG_INITIALLY_SET depends on KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE (it is also only available on x86, arm64 and riscv for now).

KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 was previously available under the name KVM_CAP_MANUAL_DIRTY_LOG_PROTECT, but the implementation had bugs that make it hard or impossible to use it correctly.  The availability of KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 signals that those bugs are fixed. Userspace should not try to use KVM_CAP_MANUAL_DIRTY_LOG_PROTECT.

<a id="rst-kvm-cap-ppc-secure-guest"></a>

### 7.19 KVM_CAP_PPC_SECURE_GUEST

**Architectures:** ppc

This capability indicates that KVM is running on a host that has ultravisor firmware and thus can support a secure guest.  On such a system, a guest can ask the ultravisor to make it a secure guest, one whose memory is inaccessible to the host except for pages which are explicitly requested to be shared with the host.  The ultravisor notifies KVM when a guest requests to become a secure guest, and KVM has the opportunity to veto the transition.

If present, this capability can be enabled for a VM, meaning that KVM will allow the transition to secure guest mode.  Otherwise KVM will veto the transition.

<a id="rst-kvm-cap-halt-poll"></a>

### 7.20 KVM_CAP_HALT_POLL

**Architectures:** all

**Target:** VM

**Parameters:** args\[0\] is the maximum poll time in nanoseconds

**Returns:** 0 on success; -1 on error

KVM_CAP_HALT_POLL overrides the kvm.halt_poll_ns module parameter to set the maximum halt-polling time for all vCPUs in the target VM. This capability can be invoked at any time and any number of times to dynamically change the maximum halt-polling time.

See [Documentation/virt/kvm/halt-polling.rst](/kernel/internals/virt/kvm/halt-polling.md) for more information on halt polling.

<a id="rst-kvm-cap-x86-user-space-msr"></a>

### 7.21 KVM_CAP_X86_USER_SPACE_MSR

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] contains the mask of KVM_MSR_EXIT_REASON\_\* events to report

**Returns:** 0 on success; -1 on error

This capability allows userspace to intercept RDMSR and WRMSR instructions if access to an MSR is denied.  By default, KVM injects \#GP on denied accesses.

When a guest requests to read or write an MSR, KVM may not implement all MSRs that are relevant to a respective system. It also does not differentiate by CPU type.

To allow more fine grained control over MSR handling, userspace may enable this capability. With it enabled, MSR accesses that match the mask specified in args\[0\] and would trigger a \#GP inside the guest will instead trigger KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR exit notifications.  Userspace can then implement model specific MSR handling and/or user notifications to inform a user that an MSR was not emulated/virtualized by KVM.

The valid mask flags are:


<table>
<tbody>
<tr>
<td>


KVM_MSR_EXIT_REASON_UNKNOWN

</td>
<td>


intercept accesses to unknown (to KVM) MSRs

</td>
</tr>
<tr>
<td>


KVM_MSR_EXIT_REASON_INVAL

</td>
<td>


intercept accesses that are architecturally invalid according to the vCPU model and/or mode

</td>
</tr>
<tr>
<td>


KVM_MSR_EXIT_REASON_FILTER

</td>
<td>


intercept accesses that are denied by userspace via KVM_X86_SET_MSR_FILTER

</td>
</tr>
</tbody>
</table>

<a id="rst-kvm-cap-x86-bus-lock-exit"></a>

### 7.22 KVM_CAP_X86_BUS_LOCK_EXIT

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] defines the policy used when bus locks detected in guest

**Returns:** 0 on success, -EINVAL when args\[0\] contains invalid bits

Valid bits in args\[0\] are:



```text
#define KVM_BUS_LOCK_DETECTION_OFF      (1 << 0)
#define KVM_BUS_LOCK_DETECTION_EXIT     (1 << 1)
```

Enabling this capability on a VM provides userspace with a way to select a policy to handle the bus locks detected in guest. Userspace can obtain the supported modes from the result of KVM_CHECK_EXTENSION and define it through the KVM_ENABLE_CAP. The supported modes are mutually-exclusive.

This capability allows userspace to force VM exits on bus locks detected in the guest, irrespective whether or not the host has enabled split-lock detection (which triggers an \#AC exception that KVM intercepts). This capability is intended to mitigate attacks where a malicious/buggy guest can exploit bus locks to degrade the performance of the whole system.

If KVM_BUS_LOCK_DETECTION_OFF is set, KVM doesn't force guest bus locks to VM exit, although the host kernel's split-lock \#AC detection still applies, if enabled.

If KVM_BUS_LOCK_DETECTION_EXIT is set, KVM enables a CPU feature that ensures bus locks in the guest trigger a VM exit, and KVM exits to userspace for all such VM exits, e.g. to allow userspace to throttle the offending guest and/or apply some other policy-based mitigation. When exiting to userspace, KVM sets KVM_RUN_X86_BUS_LOCK in vcpu-run-&gt;flags, and conditionally sets the exit_reason to KVM_EXIT_X86_BUS_LOCK.

Due to differences in the underlying hardware implementation, the vCPU's RIP at the time of exit diverges between Intel and AMD.  On Intel hosts, RIP points at the next instruction, i.e. the exit is trap-like.  On AMD hosts, RIP points at the offending instruction, i.e. the exit is fault-like.

Note\! Detected bus locks may be coincident with other exits to userspace, i.e. KVM_RUN_X86_BUS_LOCK should be checked regardless of the primary exit reason if userspace wants to take action on all detected bus locks.

<a id="rst-kvm-cap-ppc-dawr1"></a>

### 7.23 KVM_CAP_PPC_DAWR1

**Architectures:** ppc

**Parameters:** none

**Returns:** 0 on success, -EINVAL when CPU doesn't support 2nd DAWR

This capability can be used to check / enable 2nd DAWR feature provided by POWER10 processor.

<a id="rst-kvm-cap-vm-copy-enc-context-from"></a>

### 7.24 KVM_CAP_VM_COPY_ENC_CONTEXT_FROM

**Architectures:** x86 SEV enabled

**Type:** vm

**Parameters:** args\[0\] is the fd of the source vm

**Returns:** 0 on success; ENOTTY on error

This capability enables userspace to copy encryption context from the vm indicated by the fd to the vm this is called on.

This is intended to support in-guest workloads scheduled by the host. This allows the in-guest workload to maintain its own NPTs and keeps the two vms from accidentally clobbering each other with interrupts and the like (separate APIC/MSRs/etc).

<a id="rst-kvm-cap-sgx-attribute"></a>

### 7.25 KVM_CAP_SGX_ATTRIBUTE

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] is a file handle of a SGX attribute file in securityfs

**Returns:** 0 on success, -EINVAL if the file handle is invalid or if a requested attribute is not supported by KVM.

KVM_CAP_SGX_ATTRIBUTE enables a userspace VMM to grant a VM access to one or more privileged enclave attributes.  args\[0\] must hold a file handle to a valid SGX attribute file corresponding to an attribute that is supported/restricted by KVM (currently only PROVISIONKEY).

The SGX subsystem restricts access to a subset of enclave attributes to provide additional security for an uncompromised kernel, e.g. use of the PROVISIONKEY is restricted to deter malware from using the PROVISIONKEY to obtain a stable system fingerprint.  To prevent userspace from circumventing such restrictions by running an enclave in a VM, KVM prevents access to privileged attributes by default.

See [Documentation/arch/x86/sgx.rst](/kernel/hardware/arch/x86/sgx.md) for more details.

<a id="rst-kvm-cap-exit-on-emulation-failure"></a>

### 7.27 KVM_CAP_EXIT_ON_EMULATION_FAILURE

**Architectures:** x86

**Parameters:** args\[0\] whether the feature should be enabled or not

When this capability is enabled, an emulation failure will result in an exit to userspace with KVM_INTERNAL_ERROR (except when the emulator was invoked to handle a VMware backdoor instruction). Furthermore, KVM will now provide up to 15 instruction bytes for any exit to userspace resulting from an emulation failure.  When these exits to userspace occur use the emulation_failure struct instead of the internal struct.  They both have the same layout, but the emulation_failure struct matches the content better.  It also explicitly defines the 'flags' field which is used to describe the fields in the struct that are valid (ie: if KVM_INTERNAL_ERROR_EMULATION_FLAG_INSTRUCTION_BYTES is set in the 'flags' field then both 'insn_size' and 'insn_bytes' have valid data in them.)

<a id="rst-kvm-cap-arm-mte"></a>

### 7.28 KVM_CAP_ARM_MTE

**Architectures:** arm64

**Parameters:** none

This capability indicates that KVM (and the hardware) supports exposing the Memory Tagging Extensions (MTE) to the guest. It must also be enabled by the VMM before creating any VCPUs to allow the guest access. Note that MTE is only available to a guest running in AArch64 mode and enabling this capability will cause attempts to create AArch32 VCPUs to fail.

When enabled the guest is able to access tags associated with any memory given to the guest. KVM will ensure that the tags are maintained during swap or hibernation of the host; however the VMM needs to manually save/restore the tags as appropriate if the VM is migrated.

When this capability is enabled all memory in memslots must be mapped as `MAP_ANONYMOUS` or with a RAM-based file mapping (`tmpfs`, `memfd`), attempts to create a memslot with an invalid mmap will result in an -EINVAL return.

When enabled the VMM may make use of the `KVM_ARM_MTE_COPY_TAGS` ioctl to perform a bulk copy of tags to/from the guest.

<a id="rst-kvm-cap-vm-move-enc-context-from"></a>

### 7.29 KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM

**Architectures:** x86 SEV enabled

**Type:** vm

**Parameters:** args\[0\] is the fd of the source vm

**Returns:** 0 on success

This capability enables userspace to migrate the encryption context from the VM indicated by the fd to the VM this is called on.

This is intended to support intra-host migration of VMs between userspace VMMs, upgrading the VMM process without interrupting the guest.

<a id="rst-kvm-cap-disable-quirks2"></a>

### 7.31 KVM_CAP_DISABLE_QUIRKS2

**Parameters:** args\[0\] - set of KVM quirks to disable

**Architectures:** x86

**Type:** vm

This capability, if enabled, will cause KVM to disable some behavior quirks.

Calling KVM_CHECK_EXTENSION for this capability returns a bitmask of quirks that can be disabled in KVM.

The argument to KVM_ENABLE_CAP for this capability is a bitmask of quirks to disable, and must be a subset of the bitmask returned by KVM_CHECK_EXTENSION.

The valid bits in cap.args\[0\] are:


<table>
<tbody>
<tr>
<td>


KVM_X86_QUIRK_LINT0_REENABLED

</td>
<td>


By default, the reset value for the LVT LINT0 register is 0x700 (APIC_MODE_EXTINT). When this quirk is disabled, the reset value is 0x10000 (APIC_LVT_MASKED).

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_CD_NW_CLEARED

</td>
<td>


By default, KVM clears CR0.CD and CR0.NW on AMD CPUs to workaround buggy guest firmware that runs in perpetuity with CR0.CD, i.e. with caches in "no fill" mode.

When this quirk is disabled, KVM does not change the value of CR0.CD and CR0.NW.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_LAPIC_MMIO_HOLE

</td>
<td>


By default, the MMIO LAPIC interface is available even when configured for x2APIC mode. When this quirk is disabled, KVM disables the MMIO LAPIC interface if the LAPIC is in x2APIC mode.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_OUT_7E_INC_RIP

</td>
<td>


By default, KVM pre-increments %rip before exiting to userspace for an OUT instruction to port 0x7e. When this quirk is disabled, KVM does not pre-increment %rip before exiting to userspace.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT

</td>
<td>


When this quirk is disabled, KVM sets CPUID.01H:ECX\[bit 3\] (MONITOR/MWAIT) if IA32_MISC_ENABLE\[bit 18\] (MWAIT) is set. Additionally, when this quirk is disabled, KVM clears CPUID.01H:ECX\[bit 3\] if IA32_MISC_ENABLE\[bit 18\] is cleared.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_FIX_HYPERCALL_INSN

</td>
<td>


By default, KVM rewrites guest VMMCALL/VMCALL instructions to match the vendor's hypercall instruction for the system. When this quirk is disabled, KVM will no longer rewrite invalid guest hypercall instructions. Executing the incorrect hypercall instruction will generate a \#UD within the guest.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_MWAIT_NEVER_UD_FAULTS

</td>
<td>


By default, KVM emulates MONITOR/MWAIT (if they are intercepted) as NOPs regardless of whether or not MONITOR/MWAIT are supported according to guest CPUID.  When this quirk is disabled and KVM_X86_DISABLE_EXITS_MWAIT is not set (MONITOR/MWAIT are intercepted), KVM will inject a \#UD on MONITOR/MWAIT if they're unsupported per guest CPUID.  Note, KVM will modify MONITOR/MWAIT support in guest CPUID on writes to MISC_ENABLE if KVM_X86_QUIRK_MISC_ENABLE_NO_MWAIT is disabled.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_SLOT_ZAP_ALL

</td>
<td>


By default, for KVM_X86_DEFAULT_VM VMs, KVM invalidates all SPTEs in all memslots and address spaces when a memslot is deleted or moved.  When this quirk is disabled (or the VM type isn't KVM_X86_DEFAULT_VM), KVM only ensures the backing memory of the deleted or moved memslot isn't reachable, i.e KVM \_may\_ invalidate only SPTEs related to the memslot.

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_STUFF_FEATURE_MSRS

</td>
<td>


By default, at vCPU creation, KVM sets the vCPU's MSR_IA32_PERF_CAPABILITIES (0x345), MSR_IA32_ARCH_CAPABILITIES (0x10a), MSR_PLATFORM_INFO (0xce), and all VMX MSRs (0x480..0x492) to the maximal capabilities supported by KVM.  KVM also sets MSR_IA32_UCODE_REV (0x8b) to an arbitrary value (which is different for Intel vs. AMD).  Lastly, when guest CPUID is set (by userspace), KVM modifies select VMX MSR fields to force consistency between guest CPUID and L2's effective ISA.  When this quirk is disabled, KVM zeroes the vCPU's MSR values (with two exceptions, see below), i.e. treats the feature MSRs like CPUID leaves and gives userspace full control of the vCPU model definition.  This quirk does not affect VMX MSRs CR0/CR4_FIXED1 (0x487 and 0x489), as KVM does now allow them to be set by userspace (KVM sets them based on guest CPUID, for safety purposes).

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_IGNORE_GUEST_PAT

</td>
<td>


By default, on Intel platforms, KVM ignores guest PAT and forces the effective memory type to WB in EPT.  The quirk is not available on Intel platforms which are incapable of safely honoring guest PAT (i.e., without CPU self-snoop, KVM always ignores guest PAT and forces effective memory type to WB).  It is also ignored on AMD platforms or, on Intel, when a VM has non-coherent DMA devices assigned; KVM always honors guest PAT in such case. The quirk is needed to avoid slowdowns on certain Intel Xeon platforms (e.g. ICX, SPR) where self-snoop feature is supported but UC is slow enough to cause issues with some older guests that use UC instead of WC to map the video RAM. Userspace can disable the quirk to honor guest PAT if it knows that there is no such guest software, for example if it does not expose a bochs graphics device (which is known to have had a buggy driver).

</td>
</tr>
<tr>
<td>


KVM_X86_QUIRK_VMCS12_ALLOW_FREEZE_IN_SMM

</td>
<td>


By default, KVM relaxes the consistency check for GUEST_IA32_DEBUGCTL in vmcs12 to allow FREEZE_IN_SMM to be set.  When this quirk is disabled, KVM requires this bit to be cleared.  Note that the vmcs02 bit is still completely controlled by the host, regardless of the quirk setting.

</td>
</tr>
</tbody>
</table>

<a id="rst-kvm-cap-max-vcpu-id"></a>

### 7.32 KVM_CAP_MAX_VCPU_ID

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] - maximum APIC ID value set for current VM

**Returns:** 0 on success, -EINVAL if args\[0\] is beyond KVM_MAX_VCPU_IDS supported in KVM or if it has been set.

This capability allows userspace to specify maximum possible APIC ID assigned for current VM session prior to the creation of vCPUs, saving memory for data structures indexed by the APIC ID.  Userspace is able to calculate the limit to APIC ID values from designated CPU topology.

The value can be changed only until KVM_ENABLE_CAP is set to a nonzero value or until a vCPU is created.  Upon creation of the first vCPU, if the value was set to zero or KVM_ENABLE_CAP was not invoked, KVM uses the return value of KVM_CHECK_EXTENSION(KVM_CAP_MAX_VCPU_ID) as the maximum APIC ID.

<a id="rst-kvm-cap-x86-notify-vmexit"></a>

### 7.33 KVM_CAP_X86_NOTIFY_VMEXIT

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] is the value of notify window as well as some flags

**Returns:** 0 on success, -EINVAL if args\[0\] contains invalid flags or notify VM exit is unsupported.

Bits 63:32 of args\[0\] are used for notify window. Bits 31:0 of args\[0\] are for some flags. Valid bits are:



```text
#define KVM_X86_NOTIFY_VMEXIT_ENABLED    (1 << 0)
#define KVM_X86_NOTIFY_VMEXIT_USER       (1 << 1)
```

This capability allows userspace to configure the notify VM exit on/off in per-VM scope during VM creation. Notify VM exit is disabled by default. When userspace sets KVM_X86_NOTIFY_VMEXIT_ENABLED bit in args\[0\], VMM will enable this feature with the notify window provided, which will generate a VM exit if no event window occurs in VM non-root mode for a specified of time (notify window).

If KVM_X86_NOTIFY_VMEXIT_USER is set in args\[0\], upon notify VM exits happen, KVM would exit to userspace for handling.

This capability is aimed to mitigate the threat that malicious VMs can cause CPU stuck (due to event windows don't open up) and make the CPU unavailable to host or other VMs.

<a id="rst-kvm-cap-x86-apic-bus-cycles-ns"></a>

### 7.35 KVM_CAP_X86_APIC_BUS_CYCLES_NS

**Architectures:** x86

**Target:** VM

**Parameters:** args\[0\] is the desired APIC bus clock rate, in nanoseconds

**Returns:** 0 on success, -EINVAL if args\[0\] contains an invalid value for the frequency or if any vCPUs have been created, -ENXIO if a virtual local APIC has not been created using KVM_CREATE_IRQCHIP.

This capability sets the VM's APIC bus clock frequency, used by KVM's in-kernel virtual APIC when emulating APIC timers.  KVM's default value can be retrieved by KVM_CHECK_EXTENSION.

Note: Userspace is responsible for correctly configuring CPUID 0x15, a.k.a. the core crystal clock frequency, if a non-zero CPUID 0x15 is exposed to the guest.

<a id="rst-kvm-cap-dirty-log-ring-kvm-cap-dirty-log-ring-acq-rel"></a>

### 7.36 KVM_CAP_DIRTY_LOG_RING/KVM_CAP_DIRTY_LOG_RING_ACQ_REL

**Architectures:** x86, arm64, riscv

**Type:** vm

**Parameters:** args\[0\] - size of the dirty log ring

KVM is capable of tracking dirty memory using ring buffers that are mmapped into userspace; there is one dirty ring per vcpu.

The dirty ring is available to userspace as an array of `struct kvm_dirty_gfn`.  Each dirty entry is defined as:



```text
struct kvm_dirty_gfn {
        __u32 flags;
        __u32 slot; /* as_id | slot_id */
        __u64 offset;
};
```

The following values are defined for the flags field to define the current state of the entry:



```text
#define KVM_DIRTY_GFN_F_DIRTY           BIT(0)
#define KVM_DIRTY_GFN_F_RESET           BIT(1)
#define KVM_DIRTY_GFN_F_MASK            0x3
```

Userspace should call KVM_ENABLE_CAP ioctl right after KVM_CREATE_VM ioctl to enable this capability for the new guest and set the size of the rings.  Enabling the capability is only allowed before creating any vCPU, and the size of the ring must be a power of two.  The larger the ring buffer, the less likely the ring is full and the VM is forced to exit to userspace. The optimal size depends on the workload, but it is recommended that it be at least 64 KiB (4096 entries).

Just like for dirty page bitmaps, the buffer tracks writes to all user memory regions for which the KVM_MEM_LOG_DIRTY_PAGES flag was set in KVM_SET_USER_MEMORY_REGION.  Once a memory region is registered with the flag set, userspace can start harvesting dirty pages from the ring buffer.

An entry in the ring buffer can be unused (flag bits `00`), dirty (flag bits `01`) or harvested (flag bits `1X`).  The state machine for the entry is as follows:



```text
     dirtied         harvested        reset
00 -----------> 01 -------------> 1X -------+
 ^                                          |
 |                                          |
 +------------------------------------------+
```

To harvest the dirty pages, userspace accesses the mmapped ring buffer to read the dirty GFNs.  If the flags has the DIRTY bit set (at this stage the RESET bit must be cleared), then it means this GFN is a dirty GFN. The userspace should harvest this GFN and mark the flags from state `01b` to `1Xb` (bit 0 will be ignored by KVM, but bit 1 must be set to show that this GFN is harvested and waiting for a reset), and move on to the next GFN.  The userspace should continue to do this until the flags of a GFN have the DIRTY bit cleared, meaning that it has harvested all the dirty GFNs that were available.

Note that on weakly ordered architectures, userspace accesses to the ring buffer (and more specifically the 'flags' field) must be ordered, using load-acquire/store-release accessors when available, or any other memory barrier that will ensure this ordering.

It's not necessary for userspace to harvest the all dirty GFNs at once. However it must collect the dirty GFNs in sequence, i.e., the userspace program cannot skip one dirty GFN to collect the one next to it.

After processing one or more entries in the ring buffer, userspace calls the VM ioctl KVM_RESET_DIRTY_RINGS to notify the kernel about it, so that the kernel will reprotect those collected GFNs. Therefore, the ioctl must be called *before* reading the content of the dirty pages.

The dirty ring can get full.  When it happens, the KVM_RUN of the vcpu will return with exit reason KVM_EXIT_DIRTY_RING_FULL.

The dirty ring interface has a major difference comparing to the KVM_GET_DIRTY_LOG interface in that, when reading the dirty ring from userspace, it's still possible that the kernel has not yet flushed the processor's dirty page buffers into the kernel buffer (with dirty bitmaps, the flushing is done by the KVM_GET_DIRTY_LOG ioctl).  To achieve that, one needs to kick the vcpu out of KVM_RUN using a signal.  The resulting vmexit ensures that all dirty GFNs are flushed to the dirty rings.

NOTE: KVM_CAP_DIRTY_LOG_RING_ACQ_REL is the only capability that should be exposed by weakly ordered architecture, in order to indicate the additional memory ordering requirements imposed on userspace when reading the state of an entry and mutating it from DIRTY to HARVESTED. Architecture with TSO-like ordering (such as x86) are allowed to expose both KVM_CAP_DIRTY_LOG_RING and KVM_CAP_DIRTY_LOG_RING_ACQ_REL to userspace.

After enabling the dirty rings, the userspace needs to detect the capability of KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP to see whether the ring structures can be backed by per-slot bitmaps. With this capability advertised, it means the architecture can dirty guest pages without vcpu/ring context, so that some of the dirty information will still be maintained in the bitmap structure. KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP can't be enabled if the capability of KVM_CAP_DIRTY_LOG_RING_ACQ_REL hasn't been enabled, or any memslot has been existing.

Note that the bitmap here is only a backup of the ring structure. The use of the ring and bitmap combination is only beneficial if there is only a very small amount of memory that is dirtied out of vcpu/ring context. Otherwise, the stand-alone per-slot bitmap mechanism needs to be considered.

To collect dirty bits in the backup bitmap, userspace can use the same KVM_GET_DIRTY_LOG ioctl. KVM_CLEAR_DIRTY_LOG isn't needed as long as all the generation of the dirty bits is done in a single pass. Collecting the dirty bitmap should be the very last thing that the VMM does before considering the state as complete. VMM needs to ensure that the dirty state is final and avoid missing dirty pages from another ioctl ordered after the bitmap collection.

NOTE: Multiple examples of using the backup bitmap: (1) save vgic/its tables through command KVM_DEV_ARM\_\{VGIC_GRP_CTRL, ITS_SAVE_TABLES\} on KVM device "kvm-arm-vgic-its". (2) restore vgic/its tables through command KVM_DEV_ARM\_\{VGIC_GRP_CTRL, ITS_RESTORE_TABLES\} on KVM device "kvm-arm-vgic-its". VGICv3 LPI pending status is restored. (3) save vgic3 pending table through KVM_DEV_ARM_VGIC\_\{GRP_CTRL, SAVE_PENDING_TABLES\} command on KVM device "kvm-arm-vgic-v3".

<a id="rst-kvm-cap-pmu-capability"></a>

### 7.37 KVM_CAP_PMU_CAPABILITY

**Architectures:** x86

**Type:** vm

**Parameters:** arg\[0\] is bitmask of PMU virtualization capabilities.

**Returns:** 0 on success, -EINVAL when arg\[0\] contains invalid bits

This capability alters PMU virtualization in KVM.

Calling KVM_CHECK_EXTENSION for this capability returns a bitmask of PMU virtualization capabilities that can be adjusted on a VM.

The argument to KVM_ENABLE_CAP is also a bitmask and selects specific PMU virtualization capabilities to be applied to the VM.  This can only be invoked on a VM prior to the creation of VCPUs.

At this time, KVM_PMU_CAP_DISABLE is the only capability.  Setting this capability will disable PMU virtualization for that VM.  Usermode should adjust CPUID leaf 0xA to reflect that the PMU is disabled.

<a id="rst-kvm-cap-vm-disable-nx-huge-pages"></a>

### 7.38 KVM_CAP_VM_DISABLE_NX_HUGE_PAGES

**Architectures:** x86

**Type:** vm

**Parameters:** arg\[0\] must be 0.

**Returns:** 0 on success, -EPERM if the userspace process does not have CAP_SYS_BOOT, -EINVAL if args\[0\] is not 0 or any vCPUs have been created.

This capability disables the NX huge pages mitigation for iTLB MULTIHIT.

The capability has no effect if the nx_huge_pages module parameter is not set.

This capability may only be set before any vCPUs are created.

<a id="rst-kvm-cap-arm-eager-split-chunk-size"></a>

### 7.39 KVM_CAP_ARM_EAGER_SPLIT_CHUNK_SIZE

**Architectures:** arm64

**Type:** vm

**Parameters:** arg\[0\] is the new split chunk size.

**Returns:** 0 on success, -EINVAL if any memslot was already created.

This capability sets the chunk size used in Eager Page Splitting.

Eager Page Splitting improves the performance of dirty-logging (used in live migrations) when guest memory is backed by huge-pages.  It avoids splitting huge-pages (into PAGE_SIZE pages) on fault, by doing it eagerly when enabling dirty logging (with the KVM_MEM_LOG_DIRTY_PAGES flag for a memory region), or when using KVM_CLEAR_DIRTY_LOG.

The chunk size specifies how many pages to break at a time, using a single allocation for each chunk. Bigger the chunk size, more pages need to be allocated ahead of time.

The chunk size needs to be a valid block size. The list of acceptable block sizes is exposed in KVM_CAP_ARM_SUPPORTED_BLOCK_SIZES as a 64-bit bitmap (each bit describing a block size). The default value is 0, to disable the eager page splitting.

<a id="rst-kvm-cap-exit-hypercall"></a>

### 7.40 KVM_CAP_EXIT_HYPERCALL

**Architectures:** x86

**Type:** vm

This capability, if enabled, will cause KVM to exit to userspace with KVM_EXIT_HYPERCALL exit reason to process some hypercalls.

Calling KVM_CHECK_EXTENSION for this capability will return a bitmask of hypercalls that can be configured to exit to userspace. Right now, the only such hypercall is KVM_HC_MAP_GPA_RANGE.

The argument to KVM_ENABLE_CAP is also a bitmask, and must be a subset of the result of KVM_CHECK_EXTENSION.  KVM will forward to userspace the hypercalls whose corresponding bit is in the argument, and return ENOSYS for the others.

<a id="rst-kvm-cap-arm-system-suspend"></a>

### 7.41 KVM_CAP_ARM_SYSTEM_SUSPEND

**Architectures:** arm64

**Type:** vm

When enabled, KVM will exit to userspace with KVM_EXIT_SYSTEM_EVENT of type KVM_SYSTEM_EVENT_SUSPEND to process the guest suspend request.

<a id="rst-kvm-cap-arm-writable-imp-id-regs"></a>

### 7.42 KVM_CAP_ARM_WRITABLE_IMP_ID_REGS

**Architectures:** arm64

**Target:** VM

**Parameters:** None

**Returns:** 0 on success, -EINVAL if vCPUs have been created before enabling this capability.

This capability changes the behavior of the registers that identify a PE implementation of the Arm architecture: MIDR_EL1, REVIDR_EL1, and AIDR_EL1. By default, these registers are visible to userspace but treated as invariant.

When this capability is enabled, KVM allows userspace to change the aforementioned registers before the first KVM_RUN. These registers are VM scoped, meaning that the same set of values are presented on all vCPUs in a given VM.

<a id="rst-kvm-cap-riscv-mp-state-reset"></a>

### 7.43 KVM_CAP_RISCV_MP_STATE_RESET

**Architectures:** riscv

**Type:** VM

**Parameters:** None

**Returns:** 0 on success, -EINVAL if arg\[0\] is not zero

When this capability is enabled, KVM resets the VCPU when setting MP_STATE_INIT_RECEIVED through IOCTL.  The original MP_STATE is preserved.

<a id="rst-kvm-cap-arm-cacheable-pfnmap-supported"></a>

### 7.44 KVM_CAP_ARM_CACHEABLE_PFNMAP_SUPPORTED

**Architectures:** arm64

**Target:** VM

**Parameters:** None

This capability indicate to the userspace whether a PFNMAP memory region can be safely mapped as cacheable. This relies on the presence of force write back (FWB) feature support on the hardware.

<a id="rst-kvm-cap-arm-sea-to-user"></a>

### 7.45 KVM_CAP_ARM_SEA_TO_USER

**Architecture:** arm64

**Target:** VM

**Parameters:** none

**Returns:** 0 on success, -EINVAL if unsupported.

When this capability is enabled, KVM may exit to userspace for SEAs taken to EL2 resulting from a guest access. See `KVM_EXIT_ARM_SEA` for more information.

<a id="rst-kvm-cap-s390-user-operexec"></a>

### 7.46 KVM_CAP_S390_USER_OPEREXEC

**Architectures:** s390

**Parameters:** none

When this capability is enabled KVM forwards all operation exceptions that it doesn't handle itself to user space. This also includes the 0x0000 instructions managed by KVM_CAP_S390_USER_INSTR0. This is helpful if user space wants to emulate instructions which are not (yet) implemented in hardware.

This capability can be enabled dynamically even if VCPUs were already created and are running.

<a id="rst-other-capabilities"></a>

## 8. Other capabilities.

This section lists capabilities that give information about other features of the KVM implementation.

<a id="rst-kvm-cap-ppc-hwrng"></a>

### 8.1 KVM_CAP_PPC_HWRNG

**Architectures:** ppc

This capability, if KVM_CHECK_EXTENSION indicates that it is available, means that the kernel has an implementation of the H_RANDOM hypercall backed by a hardware random-number generator. If present, the kernel H_RANDOM handler can be enabled for guest use with the KVM_CAP_PPC_ENABLE_HCALL capability.

<a id="rst-kvm-cap-ppc-mmu-radix"></a>

### 8.3 KVM_CAP_PPC_MMU_RADIX

**Architectures:** ppc

This capability, if KVM_CHECK_EXTENSION indicates that it is available, means that the kernel can support guests using the radix MMU defined in Power ISA V3.00 (as implemented in the POWER9 processor).

<a id="rst-kvm-cap-ppc-mmu-hash-v3"></a>

### 8.4 KVM_CAP_PPC_MMU_HASH_V3

**Architectures:** ppc

This capability, if KVM_CHECK_EXTENSION indicates that it is available, means that the kernel can support guests using the hashed page table MMU defined in Power ISA V3.00 (as implemented in the POWER9 processor), including in-memory segment tables.

<a id="rst-kvm-cap-mips-vz"></a>

### 8.5 KVM_CAP_MIPS_VZ

**Architectures:** mips

This capability, if KVM_CHECK_EXTENSION on the main kvm handle indicates that it is available, means that full hardware assisted virtualization capabilities of the hardware are available for use through KVM. An appropriate KVM_VM_MIPS\_\* type must be passed to KVM_CREATE_VM to create a VM which utilises it.

If KVM_CHECK_EXTENSION on a kvm VM handle indicates that this capability is available, it means that the VM is using full hardware assisted virtualization capabilities of the hardware. This is useful to check after creating a VM with KVM_VM_MIPS_DEFAULT.

The value returned by KVM_CHECK_EXTENSION should be compared against known values (see below). All other values are reserved. This is to allow for the possibility of other hardware assisted virtualization implementations which may be incompatible with the MIPS VZ ASE.


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


The trap &amp; emulate implementation is in use to run guest code in user mode. Guest virtual memory segments are rearranged to fit the guest in the user mode address space.

</td>
</tr>
<tr>
<td>


1

</td>
<td>


The MIPS VZ ASE is in use, providing full hardware assisted virtualization, including standard guest virtual memory segments.

</td>
</tr>
</tbody>
</table>

<a id="rst-kvm-cap-mips-64bit"></a>

### 8.7 KVM_CAP_MIPS_64BIT

**Architectures:** mips

This capability indicates the supported architecture type of the guest, i.e. the supported register and address width.

The values returned when this capability is checked by KVM_CHECK_EXTENSION on a kvm VM handle correspond roughly to the CP0_Config.AT register field, and should be checked specifically against known values (see below). All other values are reserved.


<table>
<tbody>
<tr>
<td>


0

</td>
<td>


MIPS32 or microMIPS32. Both registers and addresses are 32-bits wide. It will only be possible to run 32-bit guest code.

</td>
</tr>
<tr>
<td>


1

</td>
<td>


MIPS64 or microMIPS64 with access only to 32-bit compatibility segments. Registers are 64-bits wide, but addresses are 32-bits wide. 64-bit guest code may run but cannot access MIPS64 memory segments. It will also be possible to run 32-bit guest code.

</td>
</tr>
<tr>
<td>


2

</td>
<td>


MIPS64 or microMIPS64 with access to all address segments. Both registers and addresses are 64-bits wide. It will be possible to run 64-bit or 32-bit guest code.

</td>
</tr>
</tbody>
</table>

<a id="rst-kvm-cap-arm-user-irq"></a>

### 8.9 KVM_CAP_ARM_USER_IRQ

**Architectures:** arm64

This capability, if KVM_CHECK_EXTENSION indicates that it is available, means that if userspace creates a VM without an in-kernel interrupt controller, it will be notified of changes to the output level of in-kernel emulated devices, which can generate virtual interrupts, presented to the VM. For such VMs, on every return to userspace, the kernel updates the vcpu's run-&gt;s.regs.device_irq_level field to represent the actual output level of the device.

Whenever kvm detects a change in the device output level, kvm guarantees at least one return to userspace before running the VM.  This exit could either be a KVM_EXIT_INTR or any other exit event, like KVM_EXIT_MMIO. This way, userspace can always sample the device output level and re-compute the state of the userspace interrupt controller.  Userspace should always check the state of run-&gt;s.regs.device_irq_level on every kvm exit. The value in run-&gt;s.regs.device_irq_level can represent both level and edge triggered interrupt signals, depending on the device.  Edge triggered interrupt signals will exit to userspace with the bit in run-&gt;s.regs.device_irq_level set exactly once per edge signal.

The field run-&gt;s.regs.device_irq_level is available independent of run-&gt;kvm_valid_regs or run-&gt;kvm_dirty_regs bits.

If KVM_CAP_ARM_USER_IRQ is supported, the KVM_CHECK_EXTENSION ioctl returns a number larger than 0 indicating the version of this capability is implemented and thereby which bits in run-&gt;s.regs.device_irq_level can signal values.

Currently the following bits are defined for the device_irq_level bitmap:



```text
KVM_CAP_ARM_USER_IRQ >= 1:

  KVM_ARM_DEV_EL1_VTIMER -  EL1 virtual timer
  KVM_ARM_DEV_EL1_PTIMER -  EL1 physical timer
  KVM_ARM_DEV_PMU        -  ARM PMU overflow interrupt signal
```

Future versions of kvm may implement additional events. These will get indicated by returning a higher number from KVM_CHECK_EXTENSION and will be listed above.

<a id="rst-kvm-cap-ppc-smt-possible"></a>

### 8.10 KVM_CAP_PPC_SMT_POSSIBLE

**Architectures:** ppc

Querying this capability returns a bitmap indicating the possible virtual SMT modes that can be set using KVM_CAP_PPC_SMT.  If bit N (counting from the right) is set, then a virtual SMT mode of 2^N is available.

<a id="rst-kvm-cap-hyperv-vp-index"></a>

### 8.12 KVM_CAP_HYPERV_VP_INDEX

**Architectures:** x86

This capability indicates that userspace can load HV_X64_MSR_VP_INDEX msr.  Its value is used to denote the target vcpu for a SynIC interrupt.  For compatibility, KVM initializes this msr to KVM's internal vcpu index.  When this capability is absent, userspace can still query this msr's value.

<a id="rst-kvm-cap-s390-ais-migration"></a>

### 8.13 KVM_CAP_S390_AIS_MIGRATION

**Architectures:** s390

This capability indicates if the flic device will be able to get/set the AIS states for migration via the KVM_DEV_FLIC_AISM_ALL attribute and allows to discover this without having to create a flic device.

<a id="rst-kvm-cap-s390-psw"></a>

### 8.14 KVM_CAP_S390_PSW

**Architectures:** s390

This capability indicates that the PSW is exposed via the kvm_run structure.

<a id="rst-kvm-cap-s390-gmap"></a>

### 8.15 KVM_CAP_S390_GMAP

**Architectures:** s390

This capability indicates that the user space memory used as guest mapping can be anywhere in the user memory address space, as long as the memory slots are aligned and sized to a segment (1MB) boundary.

<a id="rst-kvm-cap-s390-cow"></a>

### 8.16 KVM_CAP_S390_COW

**Architectures:** s390

This capability indicates that the user space memory used as guest mapping can use copy-on-write semantics as well as dirty pages tracking via read-only page tables.

<a id="rst-kvm-cap-s390-bpb"></a>

### 8.17 KVM_CAP_S390_BPB

**Architectures:** s390

This capability indicates that kvm will implement the interfaces to handle reset, migration and nested KVM for branch prediction blocking. The stfle facility 82 should not be provided to the guest without this capability.

<a id="rst-kvm-cap-hyperv-tlbflush"></a>

### 8.18 KVM_CAP_HYPERV_TLBFLUSH

**Architectures:** x86

This capability indicates that KVM supports paravirtualized Hyper-V TLB Flush hypercalls: HvFlushVirtualAddressSpace, HvFlushVirtualAddressSpaceEx, HvFlushVirtualAddressList, HvFlushVirtualAddressListEx.

<a id="rst-kvm-cap-arm-inject-serror-esr"></a>

### 8.19 KVM_CAP_ARM_INJECT_SERROR_ESR

**Architectures:** arm64

This capability indicates that userspace can specify (via the KVM_SET_VCPU_EVENTS ioctl) the syndrome value reported to the guest when it takes a virtual SError interrupt exception. If KVM advertises this capability, userspace can only specify the ISS field for the ESR syndrome. Other parts of the ESR, such as the EC are generated by the CPU when the exception is taken. If this virtual SError is taken to EL1 using AArch64, this value will be reported in the ISS field of ESR_ELx.

See KVM_CAP_VCPU_EVENTS for more details.

<a id="rst-kvm-cap-hyperv-send-ipi"></a>

### 8.20 KVM_CAP_HYPERV_SEND_IPI

**Architectures:** x86

This capability indicates that KVM supports paravirtualized Hyper-V IPI send hypercalls: HvCallSendSyntheticClusterIpi, HvCallSendSyntheticClusterIpiEx.

<a id="rst-kvm-cap-s390-vcpu-resets"></a>

### 8.22 KVM_CAP_S390_VCPU_RESETS

**Architectures:** s390

This capability indicates that the KVM_S390_NORMAL_RESET and KVM_S390_CLEAR_RESET ioctls are available.

<a id="rst-kvm-cap-s390-protected"></a>

### 8.23 KVM_CAP_S390_PROTECTED

**Architectures:** s390

This capability indicates that the Ultravisor has been initialized and KVM can therefore start protected VMs. This capability governs the KVM_S390_PV_COMMAND ioctl and the KVM_MP_STATE_LOAD MP_STATE. KVM_SET_MP_STATE can fail for protected guests when the state change is invalid.

<a id="rst-kvm-cap-steal-time"></a>

### 8.24 KVM_CAP_STEAL_TIME

**Architectures:** arm64, x86

This capability indicates that KVM supports steal time accounting. When steal time accounting is supported it may be enabled with architecture-specific interfaces.  This capability and the architecture- specific interfaces must be consistent, i.e. if one says the feature is supported, than the other should as well and vice versa.  For arm64 see [Documentation/virt/kvm/devices/vcpu.rst](/kernel/internals/virt/kvm-devices/vcpu.md) "KVM_ARM_VCPU_PVTIME_CTRL". For x86 see [Documentation/virt/kvm/x86/msr.rst](/kernel/internals/virt/kvm-x86/msr.md) "MSR_KVM_STEAL_TIME".

<a id="rst-kvm-cap-s390-diag318"></a>

### 8.25 KVM_CAP_S390_DIAG318

**Architectures:** s390

This capability enables a guest to set information about its control program (i.e. guest kernel type and version). The information is helpful during system/firmware service events, providing additional data about the guest environments running on the machine.

The information is associated with the DIAGNOSE 0x318 instruction, which sets an 8-byte value consisting of a one-byte Control Program Name Code (CPNC) and a 7-byte Control Program Version Code (CPVC). The CPNC determines what environment the control program is running in (e.g. Linux, z/VM...), and the CPVC is used for information specific to OS (e.g. Linux version, Linux distribution...)

If this capability is available, then the CPNC and CPVC can be synchronized between KVM and userspace via the sync regs mechanism (KVM_SYNC_DIAG318).

<a id="rst-kvm-cap-x86-user-space-msr-1"></a>

### 8.26 KVM_CAP_X86_USER_SPACE_MSR

**Architectures:** x86

This capability indicates that KVM supports deflection of MSR reads and writes to user space. It can be enabled on a VM level. If enabled, MSR accesses that would usually trigger a \#GP by KVM into the guest will instead get bounced to user space through the KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR exit notifications.

<a id="rst-kvm-cap-x86-msr-filter"></a>

### 8.27 KVM_CAP_X86_MSR_FILTER

**Architectures:** x86

This capability indicates that KVM supports that accesses to user defined MSRs may be rejected. With this capability exposed, KVM exports new VM ioctl KVM_X86_SET_MSR_FILTER which user space can call to specify bitmaps of MSR ranges that KVM should deny access to.

In combination with KVM_CAP_X86_USER_SPACE_MSR, this allows user space to trap and emulate MSRs that are outside of the scope of KVM as well as limit the attack surface on KVM's MSR emulation code.

<a id="rst-kvm-cap-xen-hvm"></a>

### 8.30 KVM_CAP_XEN_HVM

**Architectures:** x86

This capability indicates the features that Xen supports for hosting Xen PVHVM guests. Valid flags are:



```text
#define KVM_XEN_HVM_CONFIG_HYPERCALL_MSR              (1 << 0)
#define KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL            (1 << 1)
#define KVM_XEN_HVM_CONFIG_SHARED_INFO                (1 << 2)
#define KVM_XEN_HVM_CONFIG_RUNSTATE                   (1 << 3)
#define KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL              (1 << 4)
#define KVM_XEN_HVM_CONFIG_EVTCHN_SEND                (1 << 5)
#define KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG       (1 << 6)
#define KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE       (1 << 7)
```

The KVM_XEN_HVM_CONFIG_HYPERCALL_MSR flag indicates that the KVM_XEN_HVM_CONFIG ioctl is available, for the guest to set its hypercall page.

If KVM_XEN_HVM_CONFIG_INTERCEPT_HCALL is also set, the same flag may also be provided in the flags to KVM_XEN_HVM_CONFIG, without providing hypercall page contents, to request that KVM generate hypercall page content automatically and also enable interception of guest hypercalls with KVM_EXIT_XEN.

The KVM_XEN_HVM_CONFIG_SHARED_INFO flag indicates the availability of the KVM_XEN_HVM_SET_ATTR, KVM_XEN_HVM_GET_ATTR, KVM_XEN_VCPU_SET_ATTR and KVM_XEN_VCPU_GET_ATTR ioctls, as well as the delivery of exception vectors for event channel upcalls when the evtchn_upcall_pending field of a vcpu's vcpu_info is set.

The KVM_XEN_HVM_CONFIG_RUNSTATE flag indicates that the runstate-related features KVM_XEN_VCPU_ATTR_TYPE_RUNSTATE_ADDR/\_CURRENT/\_DATA/\_ADJUST are supported by the KVM_XEN_VCPU_SET_ATTR/KVM_XEN_VCPU_GET_ATTR ioctls.

The KVM_XEN_HVM_CONFIG_EVTCHN_2LEVEL flag indicates that IRQ routing entries of the type KVM_IRQ_ROUTING_XEN_EVTCHN are supported, with the priority field set to indicate 2 level event channel delivery.

The KVM_XEN_HVM_CONFIG_EVTCHN_SEND flag indicates that KVM supports injecting event channel events directly into the guest with the KVM_XEN_HVM_EVTCHN_SEND ioctl. It also indicates support for the KVM_XEN_ATTR_TYPE_EVTCHN/XEN_VERSION HVM attributes and the KVM_XEN_VCPU_ATTR_TYPE_VCPU_ID/TIMER/UPCALL_VECTOR vCPU attributes. related to event channel delivery, timers, and the XENVER_version interception.

The KVM_XEN_HVM_CONFIG_RUNSTATE_UPDATE_FLAG flag indicates that KVM supports the KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG attribute in the KVM_XEN_SET_ATTR and KVM_XEN_GET_ATTR ioctls. This controls whether KVM will set the XEN_RUNSTATE_UPDATE flag in guest memory mapped vcpu_runstate_info during updates of the runstate information. Note that versions of KVM which support the RUNSTATE feature above, but not the RUNSTATE_UPDATE_FLAG feature, will always set the XEN_RUNSTATE_UPDATE flag when updating the guest structure, which is perhaps counterintuitive. When this flag is advertised, KVM will behave more correctly, not using the XEN_RUNSTATE_UPDATE flag until/unless specifically enabled (by the guest making the hypercall, causing the VMM to enable the KVM_XEN_ATTR_TYPE_RUNSTATE_UPDATE_FLAG attribute).

The KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE flag indicates that KVM supports clearing the PVCLOCK_TSC_STABLE_BIT flag in Xen pvclock sources. This will be done when the KVM_CAP_XEN_HVM ioctl sets the KVM_XEN_HVM_CONFIG_PVCLOCK_TSC_UNSTABLE flag.

<a id="rst-kvm-cap-spapr-multitce"></a>

### 8.31 KVM_CAP_SPAPR_MULTITCE

**Architectures:** ppc

**Type:** vm

This capability means the kernel is capable of handling hypercalls H_PUT_TCE_INDIRECT and H_STUFF_TCE without passing those into the user space. This significantly accelerates DMA operations for PPC KVM guests. User space should expect that its handlers for these hypercalls are not going to be called if user space previously registered LIOBN in KVM (via KVM_CREATE_SPAPR_TCE or similar calls).

In order to enable H_PUT_TCE_INDIRECT and H_STUFF_TCE use in the guest, user space might have to advertise it for the guest. For example, IBM pSeries (sPAPR) guest starts using them if "hcall-multi-tce" is present in the "ibm,hypertas-functions" device-tree property.

The hypercalls mentioned above may or may not be processed successfully in the kernel based fast path. If they can not be handled by the kernel, they will get passed on to user space. So user space still has to have an implementation for these despite the in kernel acceleration.

This capability is always enabled.

<a id="rst-kvm-cap-ptp-kvm"></a>

### 8.32 KVM_CAP_PTP_KVM

**Architectures:** arm64

This capability indicates that the KVM virtual PTP service is supported in the host. A VMM can check whether the service is available to the guest on migration.

<a id="rst-kvm-cap-s390-protected-dump"></a>

### 8.37 KVM_CAP_S390_PROTECTED_DUMP

**Architectures:** s390

**Type:** vm

This capability indicates that KVM and the Ultravisor support dumping PV guests. The `KVM_PV_DUMP` command is available for the `KVM_S390_PV_COMMAND` ioctl and the `KVM_PV_INFO` command provides dump related UV data. Also the vcpu ioctl `KVM_S390_PV_CPU_COMMAND` is available and supports the `KVM_PV_DUMP_CPU` subcommand.

<a id="rst-kvm-cap-s390-cpu-topology"></a>

### 8.39 KVM_CAP_S390_CPU_TOPOLOGY

**Architectures:** s390

**Type:** vm

This capability indicates that KVM will provide the S390 CPU Topology facility which consist of the interpretation of the PTF instruction for the function code 2 along with interception and forwarding of both the PTF instruction with function codes 0 or 1 and the STSI(15,1,x) instruction to the userland hypervisor.

The stfle facility 11, CPU Topology facility, should not be indicated to the guest without this capability.

When this capability is present, KVM provides a new attribute group on vm fd, KVM_S390_VM_CPU_TOPOLOGY. This new attribute allows to get, set or clear the Modified Change Topology Report (MTCR) bit of the SCA through the kvm_device_attr structure.

When getting the Modified Change Topology Report value, the attr-&gt;addr must point to a byte where the value will be stored or retrieved from.

<a id="rst-kvm-cap-vm-types"></a>

### 8.41 KVM_CAP_VM_TYPES

**Architectures:** x86

**Type:** system ioctl

This capability returns a bitmap of support VM types.  The 1-setting of bit @n means the VM type with value @n is supported.  Possible values of @n are:



```text
#define KVM_X86_DEFAULT_VM    0
#define KVM_X86_SW_PROTECTED_VM       1
#define KVM_X86_SEV_VM        2
#define KVM_X86_SEV_ES_VM     3
```

Note, KVM_X86_SW_PROTECTED_VM is currently only for development and testing. Do not use KVM_X86_SW_PROTECTED_VM for "real" VMs, and especially not in production.  The behavior and effective ABI for software-protected VMs is unstable.

<a id="rst-kvm-cap-ppc-rpt-invalidate"></a>

### 8.42 KVM_CAP_PPC_RPT_INVALIDATE

**Architectures:** ppc

This capability indicates that the kernel is capable of handling H_RPT_INVALIDATE hcall.

In order to enable the use of H_RPT_INVALIDATE in the guest, user space might have to advertise it for the guest. For example, IBM pSeries (sPAPR) guest starts using it if "hcall-rpt-invalidate" is present in the "ibm,hypertas-functions" device-tree property.

This capability is enabled for hypervisors on platforms like POWER9 that support radix MMU.

<a id="rst-kvm-cap-ppc-ail-mode-3"></a>

### 8.43 KVM_CAP_PPC_AIL_MODE_3

**Architectures:** ppc

This capability indicates that the kernel supports the mode 3 setting for the "Address Translation Mode on Interrupt" aka "Alternate Interrupt Location" resource that is controlled with the H_SET_MODE hypercall.

This capability allows a guest kernel to use a better-performance mode for handling interrupts and system calls.

<a id="rst-kvm-cap-memory-fault-info"></a>

### 8.44 KVM_CAP_MEMORY_FAULT_INFO

**Architectures:** x86

The presence of this capability indicates that KVM_RUN will fill kvm_run.memory_fault if KVM cannot resolve a guest page fault VM-Exit, e.g. if there is a valid memslot but no backing VMA for the corresponding host virtual address.

The information in kvm_run.memory_fault is valid if and only if KVM_RUN returns an error with errno=EFAULT or errno=EHWPOISON *and* kvm_run.exit_reason is set to KVM_EXIT_MEMORY_FAULT.

Note: Userspaces which attempt to resolve memory faults so that they can retry KVM_RUN are encouraged to guard against repeatedly receiving the same error/annotated fault.

See KVM_EXIT_MEMORY_FAULT for more information.

<a id="rst-kvm-cap-x86-guest-mode"></a>

### 8.45 KVM_CAP_X86_GUEST_MODE

**Architectures:** x86

The presence of this capability indicates that KVM_RUN will update the KVM_RUN_X86_GUEST_MODE bit in kvm_run.flags to indicate whether the vCPU was executing nested guest code when it exited.

<a id="rst-kvm-cap-s390-keyop"></a>

### 8.46 KVM_CAP_S390_KEYOP

**Architectures:** s390

The presence of this capability indicates that the KVM_S390_KEYOP ioctl is available.

KVM exits with the register state of either the L1 or L2 guest depending on which executed at the time of an exit. Userspace must take care to differentiate between these cases.

<a id="rst-known-kvm-api-problems"></a>

## 9. Known KVM API problems

In some cases, KVM's API has some inconsistencies or common pitfalls that userspace need to be aware of.  This section details some of these issues.

Most of them are architecture specific, so the section is split by architecture.

<a id="rst-x86-4"></a>

### 9.1. x86

<a id="rst-kvm-get-supported-cpuid-issues"></a>

#### `KVM_GET_SUPPORTED_CPUID` issues

In general, `KVM_GET_SUPPORTED_CPUID` is designed so that it is possible to take its result and pass it directly to `KVM_SET_CPUID2`.  This section documents some cases in which that requires some care.

<a id="rst-local-apic-features"></a>

##### Local APIC features

CPU\[EAX=1\]:ECX\[21\] (X2APIC) is reported by `KVM_GET_SUPPORTED_CPUID`, but it can only be enabled if `KVM_CREATE_IRQCHIP` or `KVM_ENABLE_CAP(KVM_CAP_IRQCHIP_SPLIT)` are used to enable in-kernel emulation of the local APIC.

The same is true for the `KVM_FEATURE_PV_UNHALT` paravirtualized feature.

On older versions of Linux, CPU\[EAX=1\]:ECX\[24\] (TSC_DEADLINE) is not reported by `KVM_GET_SUPPORTED_CPUID`, but it can be enabled if `KVM_CAP_TSC_DEADLINE_TIMER` is present and the kernel has enabled in-kernel emulation of the local APIC. On newer versions, `KVM_GET_SUPPORTED_CPUID` does report the bit as available.

<a id="rst-cpu-topology"></a>

##### CPU topology

Several CPUID values include topology information for the host CPU: 0x0b and 0x1f for Intel systems, 0x8000001e for AMD systems.  Different versions of KVM return different values for this information and userspace should not rely on it.  Currently they return all zeroes.

If userspace wishes to set up a guest topology, it should be careful that the values of these three leaves differ for each CPU.  In particular, the APIC ID is found in EDX for all subleaves of 0x0b and 0x1f, and in EAX for 0x8000001e; the latter also encodes the core id and node id in bits 7:0 of EBX and ECX respectively.

<a id="rst-obsolete-ioctls-and-capabilities"></a>

#### Obsolete ioctls and capabilities

KVM_CAP_DISABLE_QUIRKS does not let userspace know which quirks are actually available.  Use `KVM_CHECK_EXTENSION(KVM_CAP_DISABLE_QUIRKS2)` instead if available.

<a id="rst-ordering-of-kvm-get-kvm-set-ioctls"></a>

#### Ordering of KVM_GET\_\*/KVM_SET\_\* ioctls

TBD

---

# The KVM halt polling system

_Peios Kernel / Internals / Virtualisation / kvm_

> The KVM halt polling system provides a feature within KVM whereby the latency of a guest can, under some circumstances, be reduced by polling in the host for some time period after the guest has elected to no longer run by cedeing. That…

<a id="rst-the-kvm-halt-polling-system"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The KVM halt polling system provides a feature within KVM whereby the latency of a guest can, under some circumstances, be reduced by polling in the host for some time period after the guest has elected to no longer run by cedeing. That is, when a guest vcpu has ceded, or in the case of powerpc when all of the vcpus of a single vcore have ceded, the host kernel polls for wakeup conditions before giving up the cpu to the scheduler in order to let something else run.

Polling provides a latency advantage in cases where the guest can be run again very quickly by at least saving us a trip through the scheduler, normally on the order of a few micro-seconds, although performance benefits are workload dependent. In the event that no wakeup source arrives during the polling interval or some other task on the runqueue is runnable the scheduler is invoked. Thus halt polling is especially useful on workloads with very short wakeup periods where the time spent halt polling is minimised and the time savings of not invoking the scheduler are distinguishable.

The generic halt polling code is implemented in:

> virt/kvm/kvm_main.c: kvm_vcpu_block()

The powerpc kvm-hv specific case is implemented in:

> arch/powerpc/kvm/book3s_hv.c: kvmppc_vcore_blocked()

<a id="rst-halt-polling-interval"></a>

## Halt Polling Interval

The maximum time for which to poll before invoking the scheduler, referred to as the halt polling interval, is increased and decreased based on the perceived effectiveness of the polling in an attempt to limit pointless polling. This value is stored in either the vcpu struct:

> kvm_vcpu-&gt;halt_poll_ns

or in the case of powerpc kvm-hv, in the vcore struct:

> kvmppc_vcore-&gt;halt_poll_ns

Thus this is a per vcpu (or vcore) value.

During polling if a wakeup source is received within the halt polling interval, the interval is left unchanged. In the event that a wakeup source isn't received during the polling interval (and thus schedule is invoked) there are two options, either the polling interval and total block time\[0\] were less than the global max polling interval (see module params below), or the total block time was greater than the global max polling interval.

In the event that both the polling interval and total block time were less than the global max polling interval then the polling interval can be increased in the hope that next time during the longer polling interval the wake up source will be received while the host is polling and the latency benefits will be received. The polling interval is grown in the function grow_halt_poll_ns() and is multiplied by the module parameters halt_poll_ns_grow and halt_poll_ns_grow_start.

In the event that the total block time was greater than the global max polling interval then the host will never poll for long enough (limited by the global max) to wakeup during the polling interval so it may as well be shrunk in order to avoid pointless polling. The polling interval is shrunk in the function shrink_halt_poll_ns() and is divided by the module parameter halt_poll_ns_shrink, or set to 0 iff halt_poll_ns_shrink == 0.

It is worth noting that this adjustment process attempts to hone in on some steady state polling interval but will only really do a good job for wakeups which come at an approximately constant rate, otherwise there will be constant adjustment of the polling interval.

- **\[0\] total block time:**

  the time between when the halt polling function is invoked and a wakeup source received (irrespective of whether the scheduler is invoked within that function).

<a id="rst-module-parameters"></a>

## Module Parameters

The kvm module has 4 tunable module parameters to adjust the global max polling interval, the initial value (to grow from 0), and the rate at which the polling interval is grown and shrunk. These variables are defined in include/linux/kvm_host.h and as module parameters in virt/kvm/kvm_main.c, or arch/powerpc/kvm/book3s_hv.c in the powerpc kvm-hv case.


<table>
<tbody>
<tr>
<td>


Module Parameter

</td>
<td>


Description

</td>
<td>


Default Value

</td>
</tr>
<tr>
<td>


halt_poll_ns

</td>
<td>


The global max polling interval which defines the ceiling value of the polling interval for each vcpu.

</td>
<td>


KVM_HALT_POLL_NS_DEFAULT

(per arch value)

</td>
</tr>
<tr>
<td>


halt_poll_ns_grow

</td>
<td>


The value by which the halt polling interval is multiplied in the grow_halt_poll_ns() function.

</td>
<td>


2

</td>
</tr>
<tr>
<td>


halt_poll_ns_grow_start

</td>
<td>


The initial value to grow to from zero in the grow_halt_poll_ns() function.

</td>
<td>


10000

</td>
</tr>
<tr>
<td>


halt_poll_ns_shrink

</td>
<td>


The value by which the halt polling interval is divided in the shrink_halt_poll_ns() function.

</td>
<td>


2

</td>
</tr>
</tbody>
</table>

These module parameters can be set from the sysfs files in:

> /sys/module/kvm/parameters/

- **Note: these module parameters are system-wide values and are not able to**

  be tuned on a per vm basis.

Any changes to these parameters will be picked up by new and existing vCPUs the next time they halt, with the notable exception of VMs using KVM_CAP_HALT_POLL (see next section).

<a id="rst-kvm-cap-halt-poll"></a>

## KVM_CAP_HALT_POLL

KVM_CAP_HALT_POLL is a VM capability that allows userspace to override halt_poll_ns on a per-VM basis. VMs using KVM_CAP_HALT_POLL ignore halt_poll_ns completely (but still obey halt_poll_ns_grow, halt_poll_ns_grow_start, and halt_poll_ns_shrink).

See [Documentation/virt/kvm/api.rst](/kernel/internals/virt/kvm/api.md) for more information on this capability.

<a id="rst-further-notes"></a>

## Further Notes

- Care should be taken when setting the halt_poll_ns module parameter as a large value has the potential to drive the cpu usage to 100% on a machine which would be almost entirely idle otherwise. This is because even if a guest has wakeups during which very little work is done and which are quite far apart, if the period is shorter than the global max polling interval (halt_poll_ns) then the host will always poll for the entire block time and thus cpu utilisation will go to 100%.

- Halt polling essentially presents a trade-off between power usage and latency and the module parameters should be used to tune the affinity for this. Idle cpu time is essentially converted to host kernel time with the aim of decreasing latency when entering the guest.

- Halt polling will only be conducted by the host when no other tasks are runnable on that cpu, otherwise the polling will cease immediately and schedule will be invoked to allow that other task to run. Thus this doesn't allow a guest to cause denial of service of the cpu.

---

# KVM Lock Overview

_Peios Kernel / Internals / Virtualisation / kvm_

> The acquisition orders for mutexes are as follows:

<a id="rst-kvm-lock-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-acquisition-orders"></a>

## 1. Acquisition Orders

The acquisition orders for mutexes are as follows:

- cpus_read_lock() is taken outside kvm_lock

- kvm_usage_lock is taken outside cpus_read_lock()

- kvm-&gt;lock is taken outside vcpu-&gt;mutex

- kvm-&gt;lock is taken outside kvm-&gt;slots_lock and kvm-&gt;irq_lock

- vcpu-&gt;mutex is taken outside kvm-&gt;slots_lock and kvm-&gt;slots_arch_lock

- kvm-&gt;slots_lock is taken outside kvm-&gt;irq_lock, though acquiring them together is quite rare.

- kvm-&gt;mn_active_invalidate_count ensures that pairs of invalidate_range_start() and invalidate_range_end() callbacks use the same memslots array.  kvm-&gt;slots_lock and kvm-&gt;slots_arch_lock are taken on the waiting side when modifying memslots, so MMU notifiers must not take either kvm-&gt;slots_lock or kvm-&gt;slots_arch_lock.

cpus_read_lock() vs kvm_lock:

- Taking cpus_read_lock() outside of kvm_lock is problematic, despite that being the official ordering, as it is quite easy to unknowingly trigger cpus_read_lock() while holding kvm_lock.  Use caution when walking vm_list, e.g. avoid complex operations when possible.

For SRCU:

- `synchronize_srcu(&kvm->srcu)` is called inside critical sections for kvm-&gt;lock, vcpu-&gt;mutex and kvm-&gt;slots_lock.  These locks \_cannot\_ be taken inside a kvm-&gt;srcu read-side critical section; that is, the following is broken:



  ```text
  srcu_read_lock(&kvm->srcu);
  mutex_lock(&kvm->slots_lock);
  ```

- kvm-&gt;slots_arch_lock instead is released before the call to `synchronize_srcu()`.  It \_can\_ therefore be taken inside a kvm-&gt;srcu read-side critical section, for example while processing a vmexit.

On x86:

- vcpu-&gt;mutex is taken outside kvm-&gt;arch.hyperv.hv_lock and kvm-&gt;arch.xen.xen_lock

- kvm-&gt;arch.mmu_lock is an rwlock; critical sections for kvm-&gt;arch.tdp_mmu_pages_lock and kvm-&gt;arch.mmu_unsync_pages_lock must also take kvm-&gt;arch.mmu_lock

Everything else is a leaf: no other lock is taken inside the critical sections.

<a id="rst-exception"></a>

## 2. Exception

Fast page fault:

Fast page fault is the fast path which fixes the guest page fault out of the mmu-lock on x86. Currently, the page fault can be fast in one of the following two cases:

1. Access Tracking: The SPTE is not present, but it is marked for access tracking. That means we need to restore the saved R/X bits. This is described in more detail later below.

2. Write-Protection: The SPTE is present and the fault is caused by write-protect. That means we just need to change the W bit of the spte.

What we use to avoid all the races is the Host-writable bit and MMU-writable bit on the spte:

- Host-writable means the gfn is writable in the host kernel page tables and in its KVM memslot.

- MMU-writable means the gfn is writable in the guest's mmu and it is not write-protected by shadow page write-protection.

On fast page fault path, we will use cmpxchg to atomically set the spte W bit if spte.HOST_WRITEABLE = 1 and spte.WRITE_PROTECT = 1, to restore the saved R/X bits if for an access-traced spte, or both. This is safe because whenever changing these bits can be detected by cmpxchg.

But we need carefully check these cases:

1. The mapping from gfn to pfn

The mapping from gfn to pfn may be changed since we can only ensure the pfn is not changed during cmpxchg. This is a ABA problem, for example, below case will happen:


<table>
<tbody>
<tr>
<td colspan="2">


At the beginning:



```text
gpte = gfn1
gfn1 is mapped to pfn1 on host
spte is the shadow page table entry corresponding with gpte and
spte = pfn1
```

</td>
</tr>
<tr>
<td colspan="2">


On fast page fault path:

</td>
</tr>
<tr>
<td>


CPU 0:

</td>
<td>


CPU 1:

</td>
</tr>
<tr>
<td>




```text
old_spte = *spte;
```

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>


pfn1 is swapped out:



```text
spte = 0;
```

pfn1 is re-alloced for gfn2.

gpte is changed to point to gfn2 by the guest:



```text
spte = pfn1;
```

</td>
</tr>
<tr>
<td colspan="2">




```text
if (cmpxchg(spte, old_spte, old_spte+W)
    mark_page_dirty(vcpu->kvm, gfn1)
         OOPS!!!
```

</td>
</tr>
</tbody>
</table>

We dirty-log for gfn1, that means gfn2 is lost in dirty-bitmap.

For direct sp, we can easily avoid it since the spte of direct sp is fixed to gfn.  For indirect sp, we disabled fast page fault for simplicity.

A solution for indirect sp could be to pin the gfn before the cmpxchg.  After the pinning:

- We have held the refcount of pfn; that means the pfn can not be freed and be reused for another gfn.

- The pfn is writable and therefore it cannot be shared between different gfns by KSM.

Then, we can ensure the dirty bitmaps is correctly set for a gfn.

2. Dirty bit tracking

In the original code, the spte can be fast updated (non-atomically) if the spte is read-only and the Accessed bit has already been set since the Accessed bit and Dirty bit can not be lost.

But it is not true after fast page fault since the spte can be marked writable between reading spte and updating spte. Like below case:


<table>
<tbody>
<tr>
<td colspan="2">


At the beginning:



```text
spte.W = 0
spte.Accessed = 1
```

</td>
</tr>
<tr>
<td>


CPU 0:

</td>
<td>


CPU 1:

</td>
</tr>
<tr>
<td>


In mmu_spte_update():



```text
old_spte = *spte;


/* 'if' condition is satisfied. */
if (old_spte.Accessed == 1 &&
     old_spte.W == 0)
   spte = new_spte;
```

</td>
<td>




</td>
</tr>
<tr>
<td>




</td>
<td>


on fast page fault path:



```text
spte.W = 1
```

memory write on the spte:



```text
spte.Dirty = 1
```

</td>
</tr>
<tr>
<td>




```text
else
  old_spte = xchg(spte, new_spte);
if (old_spte.Accessed &&
    !new_spte.Accessed)
  flush = true;
if (old_spte.Dirty &&
    !new_spte.Dirty)
  flush = true;
  OOPS!!!
```

</td>
<td>




</td>
</tr>
</tbody>
</table>

The Dirty bit is lost in this case.

In order to avoid this kind of issue, we always treat the spte as "volatile" if it can be updated out of mmu-lock \[see spte_needs_atomic_update()\]; it means the spte is always atomically updated in this case.

3. flush tlbs due to spte updated

If the spte is updated from writable to read-only, we should flush all TLBs, otherwise rmap_write_protect will find a read-only spte, even though the writable spte might be cached on a CPU's TLB.

As mentioned before, the spte can be updated to writable out of mmu-lock on fast page fault path. In order to easily audit the path, we see if TLBs needing to be flushed caused this reason in mmu_spte_update() since this is a common function to update spte (present -&gt; present).

Since the spte is "volatile" if it can be updated out of mmu-lock, we always atomically update the spte and the race caused by fast page fault can be avoided. See the comments in spte_needs_atomic_update() and mmu_spte_update().

Lockless Access Tracking:

This is used for Intel CPUs that are using EPT but do not support the EPT A/D bits. In this case, PTEs are tagged as A/D disabled (using ignored bits), and when the KVM MMU notifier is called to track accesses to a page (via kvm_mmu_notifier_clear_flush_young), it marks the PTE not-present in hardware by clearing the RWX bits in the PTE and storing the original R &amp; X bits in more unused/ignored bits. When the VM tries to access the page later on, a fault is generated and the fast page fault mechanism described above is used to atomically restore the PTE to a Present state. The W bit is not saved when the PTE is marked for access tracking and during restoration to the Present state, the W bit is set depending on whether or not it was a write access. If it wasn't, then the W bit will remain clear until a write access happens, at which time it will be set using the Dirty tracking mechanism described above.

<a id="rst-reference"></a>

## 3. Reference

<a id="rst-kvm-lock"></a>

### `kvm_lock`

**Type:** mutex

**Arch:** any

**Protects:** - vm_list

<a id="rst-kvm-usage-lock"></a>

### `kvm_usage_lock`

**Type:** mutex

**Arch:** any

**Protects:** - kvm_usage_count

- hardware virtualization enable/disable

**Comment:** Exists to allow taking cpus_read_lock() while kvm_usage_count is protected, which simplifies the virtualization enabling logic.

<a id="rst-kvm-mn-invalidate-lock"></a>

### `kvm->mn_invalidate_lock`

**Type:** spinlock_t

**Arch:** any

**Protects:** mn_active_invalidate_count, mn_memslots_update_rcuwait

<a id="rst-kvm-arch-tsc-write-lock"></a>

### `kvm_arch::tsc_write_lock`

**Type:** raw_spinlock_t

**Arch:** x86

**Protects:** - kvm_arch::\{last_tsc_write,last_tsc_nsec,last_tsc_offset\}

- tsc offset in vmcb

**Comment:** 'raw' because updating the tsc offsets must not be preempted.

<a id="rst-kvm-mmu-lock"></a>

### `kvm->mmu_lock`

**Type:** spinlock_t or rwlock_t

**Arch:** any

**Protects:** -shadow page/shadow tlb entry

**Comment:** it is a spinlock since it is used in mmu notifier.

<a id="rst-kvm-srcu"></a>

### `kvm->srcu`

**Type:** srcu lock

**Arch:** any

**Protects:** - kvm-&gt;memslots

- kvm-&gt;buses

**Comment:** The srcu read lock must be held while accessing memslots (e.g. when using gfn_to\_\* functions) and while accessing in-kernel MMIO/PIO address-&gt;device structure mapping (kvm-&gt;buses). The srcu index can be stored in kvm_vcpu-&gt;srcu_idx per vcpu if it is needed by multiple functions.

<a id="rst-kvm-slots-arch-lock"></a>

### `kvm->slots_arch_lock`

**Type:** mutex

**Arch:** any (only needed on x86 though)

**Protects:** any arch-specific fields of memslots that have to be modified in a `kvm->srcu` read-side critical section.

**Comment:** must be held before reading the pointer to the current memslots, until after all changes to the memslots are complete

<a id="rst-wakeup-vcpus-on-cpu-lock"></a>

### `wakeup_vcpus_on_cpu_lock`

**Type:** spinlock_t

**Arch:** x86

**Protects:** wakeup_vcpus_on_cpu

**Comment:** This is a per-CPU lock and it is used for VT-d posted-interrupts. When VT-d posted-interrupts are supported and the VM has assigned devices, we put the blocked vCPU on the list blocked_vcpu_on_cpu protected by blocked_vcpu_on_cpu_lock. When VT-d hardware issues wakeup notification event since external interrupts from the assigned devices happens, we will find the vCPU on the list to wakeup.

<a id="rst-vendor-module-lock"></a>

### `vendor_module_lock`

**Type:** mutex

**Arch:** x86

**Protects:** loading a vendor module (kvm_amd or kvm_intel)

**Comment:** Exists because using kvm_lock leads to deadlock.  kvm_lock is taken in notifiers, e.g. \__kvmclock_cpufreq_notifier(), that may be invoked while cpu_hotplug_lock is held, e.g. from cpufreq_boost_trigger_state(), and many operations need to take cpu_hotplug_lock when loading a vendor module, e.g. updating static calls.

---

# The PPC KVM paravirtual interface

_Peios Kernel / Internals / Virtualisation / kvm_

> The basic execution principle by which KVM on PowerPC works is to run all kernel space code in PR=1 which is user space. This way we trap all privileged instructions and can emulate them accordingly.

<a id="rst-the-ppc-kvm-paravirtual-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The basic execution principle by which KVM on PowerPC works is to run all kernel space code in PR=1 which is user space. This way we trap all privileged instructions and can emulate them accordingly.

Unfortunately that is also the downfall. There are quite some privileged instructions that needlessly return us to the hypervisor even though they could be handled differently.

This is what the PPC PV interface helps with. It takes privileged instructions and transforms them into unprivileged ones with some help from the hypervisor. This cuts down virtualization costs by about 50% on some of my benchmarks.

The code for that interface can be found in arch/powerpc/kernel/kvm\*

<a id="rst-querying-for-existence"></a>

## Querying for existence

To find out if we're running on KVM or not, we leverage the device tree. When Linux is running on KVM, a node /hypervisor exists. That node contains a compatible property with the value "linux,kvm".

Once you determined you're running under a PV capable KVM, you can now use hypercalls as described below.

<a id="rst-kvm-hypercalls"></a>

## KVM hypercalls

Inside the device tree's /hypervisor node there's a property called 'hypercall-instructions'. This property contains at most 4 opcodes that make up the hypercall. To call a hypercall, just call these instructions.

The parameters are as follows:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Register
>
> </th>
> <th>
>
>
> IN
>
> </th>
> <th>
>
>
> OUT
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> r0
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> <td>
>
>
> volatile
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r3
>
> </td>
> <td>
>
>
> 1st parameter
>
> </td>
> <td>
>
>
> Return code
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r4
>
> </td>
> <td>
>
>
> 2nd parameter
>
> </td>
> <td>
>
>
> 1st output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r5
>
> </td>
> <td>
>
>
> 3rd parameter
>
> </td>
> <td>
>
>
> 2nd output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r6
>
> </td>
> <td>
>
>
> 4th parameter
>
> </td>
> <td>
>
>
> 3rd output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r7
>
> </td>
> <td>
>
>
> 5th parameter
>
> </td>
> <td>
>
>
> 4th output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r8
>
> </td>
> <td>
>
>
> 6th parameter
>
> </td>
> <td>
>
>
> 5th output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r9
>
> </td>
> <td>
>
>
> 7th parameter
>
> </td>
> <td>
>
>
> 6th output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r10
>
> </td>
> <td>
>
>
> 8th parameter
>
> </td>
> <td>
>
>
> 7th output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r11
>
> </td>
> <td>
>
>
> hypercall number
>
> </td>
> <td>
>
>
> 8th output value
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> r12
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> <td>
>
>
> volatile
>
> </td>
> </tr>
> </tbody>
> </table>

Hypercall definitions are shared in generic code, so the same hypercall numbers apply for x86 and powerpc alike with the exception that each KVM hypercall also needs to be ORed with the KVM vendor code which is (42 &lt;&lt; 16).

Return codes can be as follows:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Code
>
> </th>
> <th>
>
>
> Meaning
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Success
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 12
>
> </td>
> <td>
>
>
> Hypercall not implemented
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> &lt;0
>
> </td>
> <td>
>
>
> Error
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-the-magic-page"></a>

## The magic page

To enable communication between the hypervisor and guest there is a new shared page that contains parts of supervisor visible register state. The guest can map this shared page using the KVM hypercall KVM_HC_PPC_MAP_MAGIC_PAGE.

With this hypercall issued the guest always gets the magic page mapped at the desired location. The first parameter indicates the effective address when the MMU is enabled. The second parameter indicates the address in real mode, if applicable to the target. For now, we always map the page to -4096. This way we can access it using absolute load and store functions. The following instruction reads the first field of the magic page:



```text
ld      rX, -4096(0)
```

The interface is designed to be extensible should there be need later to add additional registers to the magic page. If you add fields to the magic page, also define a new hypercall feature to indicate that the host can give you more registers. Only if the host supports the additional features, make use of them.

The magic page layout is described by struct kvm_vcpu_arch_shared in arch/powerpc/include/uapi/asm/kvm_para.h.

<a id="rst-magic-page-features"></a>

## Magic page features

When mapping the magic page using the KVM hypercall KVM_HC_PPC_MAP_MAGIC_PAGE, a second return value is passed to the guest. This second return value contains a bitmap of available features inside the magic page.

The following enhancements to the magic page are currently available:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> KVM_MAGIC_FEAT_SR
>
> </td>
> <td>
>
>
> Maps SR registers r/w in the magic page
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> KVM_MAGIC_FEAT_MAS0_TO_SPRG7
>
> </td>
> <td>
>
>
> Maps MASn, ESR, PIR and high SPRGs
>
> </td>
> </tr>
> </tbody>
> </table>

For enhanced features in the magic page, please check for the existence of the feature before using them\!

<a id="rst-magic-page-flags"></a>

## Magic page flags

In addition to features that indicate whether a host is capable of a particular feature we also have a channel for a guest to tell the host whether it's capable of something. This is what we call "flags".

Flags are passed to the host in the low 12 bits of the Effective Address.

The following flags are currently available for a guest to expose:

> MAGIC_PAGE_FLAG_NOT_MAPPED_NX Guest handles NX bits correctly wrt magic page

<a id="rst-msr-bits"></a>

## MSR bits

The MSR contains bits that require hypervisor intervention and bits that do not require direct hypervisor intervention because they only get interpreted when entering the guest or don't have any impact on the hypervisor's behavior.

The following bits are safe to be set inside the guest:

> - MSR_EE
>
> - MSR_RI

If any other bit changes in the MSR, please still use mtmsr(d).

<a id="rst-patched-instructions"></a>

## Patched instructions

The "ld" and "std" instructions are transformed to "lwz" and "stw" instructions respectively on 32-bit systems with an added offset of 4 to accommodate for big endianness.

The following is a list of mapping the Linux kernel performs when running as guest. Implementing any of those mappings is optional, as the instruction traps also act on the shared page. So calling privileged instructions still works as before.


<table>
<thead>
<tr>
<th>


From

</th>
<th>


To

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


mfmsr   rX

</td>
<td>


ld      rX, magic_page-&gt;msr

</td>
</tr>
<tr>
<td>


mfsprg  rX, 0

</td>
<td>


ld      rX, magic_page-&gt;sprg0

</td>
</tr>
<tr>
<td>


mfsprg  rX, 1

</td>
<td>


ld      rX, magic_page-&gt;sprg1

</td>
</tr>
<tr>
<td>


mfsprg  rX, 2

</td>
<td>


ld      rX, magic_page-&gt;sprg2

</td>
</tr>
<tr>
<td>


mfsprg  rX, 3

</td>
<td>


ld      rX, magic_page-&gt;sprg3

</td>
</tr>
<tr>
<td>


mfsrr0  rX

</td>
<td>


ld      rX, magic_page-&gt;srr0

</td>
</tr>
<tr>
<td>


mfsrr1  rX

</td>
<td>


ld      rX, magic_page-&gt;srr1

</td>
</tr>
<tr>
<td>


mfdar   rX

</td>
<td>


ld      rX, magic_page-&gt;dar

</td>
</tr>
<tr>
<td>


mfdsisr rX

</td>
<td>


lwz     rX, magic_page-&gt;dsisr

</td>
</tr>
<tr>
<td>


mtmsr   rX

</td>
<td>


std     rX, magic_page-&gt;msr

</td>
</tr>
<tr>
<td>


mtsprg  0, rX

</td>
<td>


std     rX, magic_page-&gt;sprg0

</td>
</tr>
<tr>
<td>


mtsprg  1, rX

</td>
<td>


std     rX, magic_page-&gt;sprg1

</td>
</tr>
<tr>
<td>


mtsprg  2, rX

</td>
<td>


std     rX, magic_page-&gt;sprg2

</td>
</tr>
<tr>
<td>


mtsprg  3, rX

</td>
<td>


std     rX, magic_page-&gt;sprg3

</td>
</tr>
<tr>
<td>


mtsrr0  rX

</td>
<td>


std     rX, magic_page-&gt;srr0

</td>
</tr>
<tr>
<td>


mtsrr1  rX

</td>
<td>


std     rX, magic_page-&gt;srr1

</td>
</tr>
<tr>
<td>


mtdar   rX

</td>
<td>


std     rX, magic_page-&gt;dar

</td>
</tr>
<tr>
<td>


mtdsisr rX

</td>
<td>


stw     rX, magic_page-&gt;dsisr

</td>
</tr>
<tr>
<td>


tlbsync

</td>
<td>


nop

</td>
</tr>
<tr>
<td>


mtmsrd  rX, 0

</td>
<td>


b       &lt;special mtmsr section&gt;

</td>
</tr>
<tr>
<td>


mtmsr   rX

</td>
<td>


b       &lt;special mtmsr section&gt;

</td>
</tr>
<tr>
<td>


mtmsrd  rX, 1

</td>
<td>


b       &lt;special mtmsrd section&gt;

</td>
</tr>
<tr>
<td>


\[Book3S only\]

</td>
<td>




</td>
</tr>
<tr>
<td>


mtsrin  rX, rY

</td>
<td>


b       &lt;special mtsrin section&gt;

</td>
</tr>
<tr>
<td>


\[BookE only\]

</td>
<td>




</td>
</tr>
<tr>
<td>


wrteei  \[0\|1\]

</td>
<td>


b       &lt;special wrteei section&gt;

</td>
</tr>
</tbody>
</table>

Some instructions require more logic to determine what's going on than a load or store instruction can deliver. To enable patching of those, we keep some RAM around where we can live translate instructions to. What happens is the following:

> 1. copy emulation code to memory
>
> 2. patch that code to fit the emulated instruction
>
> 3. patch that code to return to the original pc + 4
>
> 4. patch the original instruction to branch to the new code

That way we can inject an arbitrary amount of code as replacement for a single instruction. This allows us to check for pending interrupts when setting EE=1 for example.

<a id="rst-hypercall-abis-in-kvm-on-powerpc"></a>

## Hypercall ABIs in KVM on PowerPC

1. KVM hypercalls (ePAPR)

These are ePAPR compliant hypercall implementation (mentioned above). Even generic hypercalls are implemented here, like the ePAPR idle hcall. These are available on all targets.

2. PAPR hypercalls

PAPR hypercalls are needed to run server PowerPC PAPR guests (-M pseries in QEMU). These are the same hypercalls that pHyp, the POWER hypervisor, implements. Some of them are handled in the kernel, some are handled in user space. This is only available on book3s_64.

3. OSI hypercalls

Mac-on-Linux is another user of KVM on PowerPC, which has its own hypercall (long before KVM). This is supported to maintain compatibility. All these hypercalls get forwarded to user space. This is only useful on book3s_32, but can be used with book3s_64 as well.

---

# Review checklist for kvm patches

_Peios Kernel / Internals / Virtualisation / kvm_

> The patch must follow Documentation/process/coding-style.rst and Documentation/process/submitting-patches.rst.

<a id="rst-review-checklist-for-kvm-patches"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

1. The patch must follow [Documentation/process/coding-style.rst](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/process/coding-style.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) and [Documentation/process/submitting-patches.rst](/kernel/development/process/submitting-patches.md).

2. Patches should be against kvm.git master or next branches.

3. If the patch introduces or modifies a new userspace API: - the API must be documented in [Documentation/virt/kvm/api.rst](/kernel/internals/virt/kvm/api.md) - the API must be discoverable using KVM_CHECK_EXTENSION

4. New state must include support for save/restore.

5. New features must default to off (userspace should explicitly request them). Performance improvements can and should default to on.

6. New cpu features should be exposed via KVM_GET_SUPPORTED_CPUID2, or its equivalent for non-x86 architectures

7. The feature should be testable (see below).

8. Changes should be vendor neutral when possible.  Changes to common code are better than duplicating changes to vendor code.

9. Similarly, prefer changes to arch independent code than to arch dependent code.

10. User/kernel interfaces and guest/host interfaces must be 64-bit clean (all variables and sizes naturally aligned on 64-bit; use specific types only - u64 rather than ulong).

11. New guest visible features must either be documented in a hardware manual or be accompanied by documentation.

<a id="rst-testing-of-kvm-code"></a>

## Testing of KVM code

All features contributed to KVM, and in many cases bugfixes too, should be accompanied by some kind of tests and/or enablement in open source guests and VMMs.  KVM is covered by multiple test suites:

- ***Selftests***

  These are low level tests that allow granular testing of kernel APIs. This includes API failure scenarios, invoking APIs after specific guest instructions, and testing multiple calls to `KVM_CREATE_VM` within a single test.  They are included in the kernel tree at `tools/testing/selftests/kvm`.

- **`kvm-unit-tests`**

  A collection of small guests that test CPU and emulated device features from a guest's perspective.  They run under QEMU or `kvmtool`, and are generally not KVM-specific: they can be run with any accelerator that QEMU support or even on bare metal, making it possible to compare behavior across hypervisors and processor families.

- **Functional test suites**

  Various sets of functional tests exist, such as QEMU's `tests/functional` suite and [avocado-vt](<https://avocado-vt.readthedocs.io/en/latest/>). These typically involve running a full operating system in a virtual machine.

The best testing approach depends on the feature's complexity and operation. Here are some examples and guidelines:

- **New instructions (no new registers or APIs)**

  The corresponding CPU features (if applicable) should be made available in QEMU.  If the instructions require emulation support or other code in KVM, it is worth adding coverage to `kvm-unit-tests` or selftests; the latter can be a better choice if the instructions relate to an API that already has good selftest coverage.

- **New hardware features (new registers, no new APIs)**

  These should be tested via `kvm-unit-tests`; this more or less implies supporting them in QEMU and/or `kvmtool`.  In some cases selftests can be used instead, similar to the previous case, or specifically to test corner cases in guest state save/restore.

- **Bug fixes and performance improvements**

  These usually do not introduce new APIs, but it's worth sharing any benchmarks and tests that will validate your contribution, ideally in the form of regression tests.  Tests and benchmarks can be included in either `kvm-unit-tests` or selftests, depending on the specifics of your change.  Selftests are especially useful for regression tests because they are included directly in Linux's tree.

- **Large scale internal changes**

  While it's difficult to provide a single policy, you should ensure that the changed code is covered by either `kvm-unit-tests` or selftests. In some cases the affected code is run for any guests and functional tests suffice.  Explain your testing process in the cover letter, as that can help identify gaps in existing test suites.

- **New APIs**

  It is important to demonstrate your use case.  This can be as simple as explaining that the feature is already in use on bare metal, or it can be a proof-of-concept implementation in userspace.  The latter need not be open source, though that is of course preferable for easier testing. Selftests should test corner cases of the APIs, and should also cover basic host and guest operation if no open source VMM uses the feature.

- **Bigger features, usually spanning host and guest**

  These should be supported by Linux guests, with limited exceptions for Hyper-V features that are testable on Windows guests.  It is strongly suggested that the feature be usable with an open source host VMM, such as at least one of QEMU or crosvm, and guest firmware.  Selftests should test at least API error cases.  Guest operation can be covered by either selftests of `kvm-unit-tests` (this is especially important for paravirtualized and Windows-only features).  Strong selftest coverage can also be a replacement for implementation in an open source VMM, but this is generally not recommended.

Following the above suggestions for testing in selftests and `kvm-unit-tests` will make it easier for the maintainers to review and accept your code.  In fact, even before you contribute your changes upstream it will make it easier for you to develop for KVM.

Of course, the KVM maintainers reserve the right to require more tests, though they may also waive the requirement from time to time.

---

# KVM VCPU Requests

_Peios Kernel / Internals / Virtualisation / kvm_

> KVM supports an internal API enabling threads to request a VCPU thread to perform some activity. For example, a thread may request a VCPU to flush its TLB with a VCPU request. The API consists of the following functions:

<a id="rst-kvm-vcpu-requests"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

KVM supports an internal API enabling threads to request a VCPU thread to perform some activity.  For example, a thread may request a VCPU to flush its TLB with a VCPU request.  The API consists of the following functions:



```text
/* Check if any requests are pending for VCPU @vcpu. */
bool kvm_request_pending(struct kvm_vcpu *vcpu);

/* Check if VCPU @vcpu has request @req pending. */
bool kvm_test_request(int req, struct kvm_vcpu *vcpu);

/* Clear request @req for VCPU @vcpu. */
void kvm_clear_request(int req, struct kvm_vcpu *vcpu);

/*
 * Check if VCPU @vcpu has request @req pending. When the request is
 * pending it will be cleared and a memory barrier, which pairs with
 * another in kvm_make_request(), will be issued.
 */
bool kvm_check_request(int req, struct kvm_vcpu *vcpu);

/*
 * Make request @req of VCPU @vcpu. Issues a memory barrier, which pairs
 * with another in kvm_check_request(), prior to setting the request.
 */
void kvm_make_request(int req, struct kvm_vcpu *vcpu);

/* Make request @req of all VCPUs of the VM with struct kvm @kvm. */
bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req);
```

Typically a requester wants the VCPU to perform the activity as soon as possible after making the request.  This means most requests (kvm_make_request() calls) are followed by a call to kvm_vcpu_kick(), and kvm_make_all_cpus_request() has the kicking of all VCPUs built into it.

<a id="rst-vcpu-kicks"></a>

### VCPU Kicks

The goal of a VCPU kick is to bring a VCPU thread out of guest mode in order to perform some KVM maintenance.  To do so, an IPI is sent, forcing a guest mode exit.  However, a VCPU thread may not be in guest mode at the time of the kick.  Therefore, depending on the mode and state of the VCPU thread, there are two other actions a kick may take.  All three actions are listed below:

1. Send an IPI.  This forces a guest mode exit.

2. Waking a sleeping VCPU.  Sleeping VCPUs are VCPU threads outside guest mode that wait on waitqueues.  Waking them removes the threads from the waitqueues, allowing the threads to run again.  This behavior may be suppressed, see KVM_REQUEST_NO_WAKEUP below.

3. Nothing.  When the VCPU is not in guest mode and the VCPU thread is not sleeping, then there is nothing to do.

<a id="rst-vcpu-mode"></a>

### VCPU Mode

VCPUs have a mode state, `vcpu->mode`, that is used to track whether the guest is running in guest mode or not, as well as some specific outside guest mode states.  The architecture may use `vcpu->mode` to ensure VCPU requests are seen by VCPUs (see "Ensuring Requests Are Seen"), as well as to avoid sending unnecessary IPIs (see "IPI Reduction"), and even to ensure IPI acknowledgements are waited upon (see "Waiting for Acknowledgements").  The following modes are defined:

OUTSIDE_GUEST_MODE

> The VCPU thread is outside guest mode.

IN_GUEST_MODE

> The VCPU thread is in guest mode.

EXITING_GUEST_MODE

> The VCPU thread is transitioning from IN_GUEST_MODE to OUTSIDE_GUEST_MODE.

READING_SHADOW_PAGE_TABLES

> The VCPU thread is outside guest mode, but it wants the sender of certain VCPU requests, namely KVM_REQ_TLB_FLUSH, to wait until the VCPU thread is done reading the page tables.

<a id="rst-vcpu-request-internals"></a>

## VCPU Request Internals

VCPU requests are simply bit indices of the `vcpu->requests` bitmap. This means general bitops, like those documented in <a id="rst-citation-reference-1"></a>[atomic-ops](#rst-atomic-ops) could also be used, e.g.



```text
clear_bit(KVM_REQ_UNBLOCK & KVM_REQUEST_MASK, &vcpu->requests);
```

However, VCPU request users should refrain from doing so, as it would break the abstraction.  The first 8 bits are reserved for architecture independent requests; all additional bits are available for architecture dependent requests.

<a id="rst-architecture-independent-requests"></a>

### Architecture Independent Requests

KVM_REQ_TLB_FLUSH

> KVM's common MMU notifier may need to flush all of a guest's TLB entries, calling kvm_flush_remote_tlbs() to do so.  Architectures that choose to use the common kvm_flush_remote_tlbs() implementation will need to handle this VCPU request.

KVM_REQ_VM_DEAD

> This request informs all VCPUs that the VM is dead and unusable, e.g. due to fatal error or because the VM's state has been intentionally destroyed.

KVM_REQ_UNBLOCK

> This request informs the vCPU to exit kvm_vcpu_block.  It is used for example from timer handlers that run on the host on behalf of a vCPU, or in order to update the interrupt routing and ensure that assigned devices will wake up the vCPU.

KVM_REQ_OUTSIDE_GUEST_MODE

> This "request" ensures the target vCPU has exited guest mode prior to the sender of the request continuing on.  No action needs be taken by the target, and so no request is actually logged for the target.  This request is similar to a "kick", but unlike a kick it guarantees the vCPU has actually exited guest mode.  A kick only guarantees the vCPU will exit at some point in the future, e.g. a previous kick may have started the process, but there's no guarantee the to-be-kicked vCPU has fully exited guest mode.

<a id="rst-kvm-request-mask"></a>

### KVM_REQUEST_MASK

VCPU requests should be masked by KVM_REQUEST_MASK before using them with bitops.  This is because only the lower 8 bits are used to represent the request's number.  The upper bits are used as flags.  Currently only two flags are defined.

<a id="rst-vcpu-request-flags"></a>

### VCPU Request Flags

KVM_REQUEST_NO_WAKEUP

> This flag is applied to requests that only need immediate attention from VCPUs running in guest mode.  That is, sleeping VCPUs do not need to be awakened for these requests.  Sleeping VCPUs will handle the requests when they are awakened later for some other reason.

KVM_REQUEST_WAIT

> When requests with this flag are made with kvm_make_all_cpus_request(), then the caller will wait for each VCPU to acknowledge its IPI before proceeding.  This flag only applies to VCPUs that would receive IPIs. If, for example, the VCPU is sleeping, so no IPI is necessary, then the requesting thread does not wait.  This means that this flag may be safely combined with KVM_REQUEST_NO_WAKEUP.  See "Waiting for Acknowledgements" for more information about requests with KVM_REQUEST_WAIT.

<a id="rst-vcpu-requests-with-associated-state"></a>

## VCPU Requests with Associated State

Requesters that want the receiving VCPU to handle new state need to ensure the newly written state is observable to the receiving VCPU thread's CPU by the time it observes the request.  This means a write memory barrier must be inserted after writing the new state and before setting the VCPU request bit.  Additionally, on the receiving VCPU thread's side, a corresponding read barrier must be inserted after reading the request bit and before proceeding to read the new state associated with it.  See scenario 3, Message and Flag, of <a id="rst-citation-reference-2"></a>[lwn-mb](#rst-lwn-mb) and the kernel documentation <a id="rst-citation-reference-3"></a>[memory-barriers](#rst-memory-barriers).

The pair of functions, kvm_check_request() and kvm_make_request(), provide the memory barriers, allowing this requirement to be handled internally by the API.

<a id="rst-ensuring-requests-are-seen"></a>

## Ensuring Requests Are Seen

When making requests to VCPUs, we want to avoid the receiving VCPU executing in guest mode for an arbitrary long time without handling the request.  We can be sure this won't happen as long as we ensure the VCPU thread checks kvm_request_pending() before entering guest mode and that a kick will send an IPI to force an exit from guest mode when necessary. Extra care must be taken to cover the period after the VCPU thread's last kvm_request_pending() check and before it has entered guest mode, as kick IPIs will only trigger guest mode exits for VCPU threads that are in guest mode or at least have already disabled interrupts in order to prepare to enter guest mode.  This means that an optimized implementation (see "IPI Reduction") must be certain when it's safe to not send the IPI.  One solution, which all architectures except s390 apply, is to:

- set `vcpu->mode` to IN_GUEST_MODE between disabling the interrupts and the last kvm_request_pending() check;

- enable interrupts atomically when entering the guest.

This solution also requires memory barriers to be placed carefully in both the requesting thread and the receiving VCPU.  With the memory barriers we can exclude the possibility of a VCPU thread observing \!kvm_request_pending() on its last check and then not receiving an IPI for the next request made of it, even if the request is made immediately after the check.  This is done by way of the Dekker memory barrier pattern (scenario 10 of <a id="rst-citation-reference-4"></a>[lwn-mb](#rst-lwn-mb)).  As the Dekker pattern requires two variables, this solution pairs `vcpu->mode` with `vcpu->requests`.  Substituting them into the pattern gives:



```text
CPU1                                    CPU2
=================                       =================
local_irq_disable();
WRITE_ONCE(vcpu->mode, IN_GUEST_MODE);  kvm_make_request(REQ, vcpu);
smp_mb();                               smp_mb();
if (kvm_request_pending(vcpu)) {        if (READ_ONCE(vcpu->mode) ==
                                            IN_GUEST_MODE) {
    ...abort guest entry...                 ...send IPI...
}                                       }
```

As stated above, the IPI is only useful for VCPU threads in guest mode or that have already disabled interrupts.  This is why this specific case of the Dekker pattern has been extended to disable interrupts before setting `vcpu->mode` to IN_GUEST_MODE.  WRITE_ONCE() and READ_ONCE() are used to pedantically implement the memory barrier pattern, guaranteeing the compiler doesn't interfere with `vcpu->mode`'s carefully planned accesses.

<a id="rst-ipi-reduction"></a>

### IPI Reduction

As only one IPI is needed to get a VCPU to check for any/all requests, then they may be coalesced.  This is easily done by having the first IPI sending kick also change the VCPU mode to something \!IN_GUEST_MODE.  The transitional state, EXITING_GUEST_MODE, is used for this purpose.

<a id="rst-waiting-for-acknowledgements"></a>

### Waiting for Acknowledgements

Some requests, those with the KVM_REQUEST_WAIT flag set, require IPIs to be sent, and the acknowledgements to be waited upon, even when the target VCPU threads are in modes other than IN_GUEST_MODE.  For example, one case is when a target VCPU thread is in READING_SHADOW_PAGE_TABLES mode, which is set after disabling interrupts.  To support these cases, the KVM_REQUEST_WAIT flag changes the condition for sending an IPI from checking that the VCPU is IN_GUEST_MODE to checking that it is not OUTSIDE_GUEST_MODE.

<a id="rst-request-less-vcpu-kicks"></a>

### Request-less VCPU Kicks

As the determination of whether or not to send an IPI depends on the two-variable Dekker memory barrier pattern, then it's clear that request-less VCPU kicks are almost never correct.  Without the assurance that a non-IPI generating kick will still result in an action by the receiving VCPU, as the final kvm_request_pending() check does for request-accompanying kicks, then the kick may not do anything useful at all.  If, for instance, a request-less kick was made to a VCPU that was just about to set its mode to IN_GUEST_MODE, meaning no IPI is sent, then the VCPU thread may continue its entry without actually having done whatever it was the kick was meant to initiate.

One exception is x86's posted interrupt mechanism.  In this case, however, even the request-less VCPU kick is coupled with the same local_irq_disable() + smp_mb() pattern described above; the ON bit (Outstanding Notification) in the posted interrupt descriptor takes the role of `vcpu->requests`.  When sending a posted interrupt, PIR.ON is set before reading `vcpu->mode`; dually, in the VCPU thread, vmx_sync_pir_to_irr() reads PIR after setting `vcpu->mode` to IN_GUEST_MODE.

<a id="rst-additional-considerations"></a>

## Additional Considerations

<a id="rst-sleeping-vcpus"></a>

### Sleeping VCPUs

VCPU threads may need to consider requests before and/or after calling functions that may put them to sleep, e.g. kvm_vcpu_block().  Whether they do or not, and, if they do, which requests need consideration, is architecture dependent.  kvm_vcpu_block() calls kvm_arch_vcpu_runnable() to check if it should awaken.  One reason to do so is to provide architectures a function where requests may be checked if necessary.

<a id="rst-references"></a>

## References

<a id="rst-atomic-ops"></a>



**[atomic-ops]** [Documentation/atomic_bitops.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/atomic_bitops.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92) and [Documentation/atomic_t.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/atomic_t.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)

<a id="rst-memory-barriers"></a>



**[memory-barriers]** [Documentation/memory-barriers.txt](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/memory-barriers.txt?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92)

<a id="rst-lwn-mb"></a>



**[lwn-mb]** [https://lwn.net/Articles/573436/](<https://lwn.net/Articles/573436/>)

---

# ARM

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> Reference for ARM.

<a id="rst-arm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [ARM firmware pseudo-registers interface](</kernel/internals/virt/kvm-arm/fw-pseudo-registers.md>)
- [Internal ABI between the kernel and HYP](</kernel/internals/virt/kvm-arm/hyp-abi.md>)
- [KVM/arm64-specific hypercalls exposed to guests](</kernel/internals/virt/kvm-arm/hypercalls.md>)
- [Paravirtualized time support for arm64](</kernel/internals/virt/kvm-arm/pvtime.md>)
- [PTP_KVM support for arm/arm64](</kernel/internals/virt/kvm-arm/ptp-kvm.md>)
- [vCPU feature selection on arm64](</kernel/internals/virt/kvm-arm/vcpu-features.md>)

---

# ARM firmware pseudo-registers interface

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> KVM handles the hypercall services as requested by the guests. New hypercall services are regularly made available by the ARM specification or by KVM (as vendor services) if they make sense from a virtualization point of view.

<a id="rst-arm-firmware-pseudo-registers-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

KVM handles the hypercall services as requested by the guests. New hypercall services are regularly made available by the ARM specification or by KVM (as vendor services) if they make sense from a virtualization point of view.

This means that a guest booted on two different versions of KVM can observe two different "firmware" revisions. This could cause issues if a given guest is tied to a particular version of a hypercall service, or if a migration causes a different version to be exposed out of the blue to an unsuspecting guest.

In order to remedy this situation, KVM exposes a set of "firmware pseudo-registers" that can be manipulated using the GET/SET_ONE_REG interface. These registers can be saved/restored by userspace, and set to a convenient value as required.

The following registers are defined:

- KVM_REG_ARM_PSCI_VERSION:

  KVM implements the PSCI (Power State Coordination Interface) specification in order to provide services such as CPU on/off, reset and power-off to the guest.

  - Only valid if the vcpu has the KVM_ARM_VCPU_PSCI_0_2 feature set (and thus has already been initialized)

  - Returns the current PSCI version on GET_ONE_REG (defaulting to the highest PSCI version implemented by KVM and compatible with v0.2)

  - Allows any PSCI version implemented by KVM and compatible with v0.2 to be set with SET_ONE_REG

  - Affects the whole VM (even if the register view is per-vcpu)

- - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_1:**

    Holds the state of the firmware support to mitigate CVE-2017-5715, as offered by KVM to the guest via a HVC call. The workaround is described under SMCCC_ARCH_WORKAROUND_1 in \[1\].

  Accepted values are:

  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_1_NOT_AVAIL:**
  >
  >   KVM does not offer firmware support for the workaround. The mitigation status for the guest is unknown.
  >
  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_1_AVAIL:**
  >
  >   The workaround HVC call is available to the guest and required for the mitigation.
  >
  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_1_NOT_REQUIRED:**
  >
  >   The workaround HVC call is available to the guest, but it is not needed on this VCPU.

- - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2:**

    Holds the state of the firmware support to mitigate CVE-2018-3639, as offered by KVM to the guest via a HVC call. The workaround is described under SMCCC_ARCH_WORKAROUND_2 in <a id="rst-footnote-reference-1"></a>[1](#rst-footnote-1).

  Accepted values are:

  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_NOT_AVAIL:**
  >
  >   A workaround is not available. KVM does not offer firmware support for the workaround.
  >
  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_UNKNOWN:**
  >
  >   The workaround state is unknown. KVM does not offer firmware support for the workaround.
  >
  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_AVAIL:**
  >
  >   The workaround is available, and can be disabled by a vCPU. If KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_ENABLED is set, it is active for this vCPU.
  >
  > - **KVM_REG_ARM_SMCCC_ARCH_WORKAROUND_2_NOT_REQUIRED:**
  >
  >   The workaround is always active on this vCPU or it is not needed.

<a id="rst-bitmap-feature-firmware-registers"></a>

## Bitmap Feature Firmware Registers

Contrary to the above registers, the following registers exposes the hypercall services in the form of a feature-bitmap to the userspace. This bitmap is translated to the services that are available to the guest. There is a register defined per service call owner and can be accessed via GET/SET_ONE_REG interface.

By default, these registers are set with the upper limit of the features that are supported. This way userspace can discover all the usable hypercall services via GET_ONE_REG. The user-space can write-back the desired bitmap back via SET_ONE_REG. The features for the registers that are untouched, probably because userspace isn't aware of them, will be exposed as is to the guest.

Note that KVM will not allow the userspace to configure the registers anymore once any of the vCPUs has run at least once. Instead, it will return a -EBUSY.

The pseudo-firmware bitmap register are as follows:

- - **KVM_REG_ARM_STD_BMAP:**

    Controls the bitmap of the ARM Standard Secure Service Calls.

  The following bits are accepted:

  > - **Bit-0: KVM_REG_ARM_STD_BIT_TRNG_V1_0:**
  >
  >   The bit represents the services offered under v1.0 of ARM True Random Number Generator (TRNG) specification, ARM DEN0098.

- - **KVM_REG_ARM_STD_HYP_BMAP:**

    Controls the bitmap of the ARM Standard Hypervisor Service Calls.

  The following bits are accepted:

  > - **Bit-0: KVM_REG_ARM_STD_HYP_BIT_PV_TIME:**
  >
  >   The bit represents the Paravirtualized Time service as represented by ARM DEN0057A.

- - **KVM_REG_ARM_VENDOR_HYP_BMAP:**

    Controls the bitmap of the Vendor specific Hypervisor Service Calls\[0-63\].

  The following bits are accepted:

  > - **Bit-0: KVM_REG_ARM_VENDOR_HYP_BIT_FUNC_FEAT**
  >
  >   The bit represents the ARM_SMCCC_VENDOR_HYP_KVM_FEATURES_FUNC_ID and ARM_SMCCC_VENDOR_HYP_CALL_UID_FUNC_ID function-ids.
  >
  > - **Bit-1: KVM_REG_ARM_VENDOR_HYP_BIT_PTP:**
  >
  >   The bit represents the Precision Time Protocol KVM service.

- - **KVM_REG_ARM_VENDOR_HYP_BMAP_2:**

    Controls the bitmap of the Vendor specific Hypervisor Service Calls\[64-127\].

  The following bits are accepted:

  > - **Bit-0: KVM_REG_ARM_VENDOR_HYP_BIT_DISCOVER_IMPL_VER**
  >
  >   This represents the ARM_SMCCC_VENDOR_HYP_KVM_DISCOVER_IMPL_VER_FUNC_ID function-id. This is reset to 0.
  >
  > - **Bit-1: KVM_REG_ARM_VENDOR_HYP_BIT_DISCOVER_IMPL_CPUS**
  >
  >   This represents the ARM_SMCCC_VENDOR_HYP_KVM_DISCOVER_IMPL_CPUS_FUNC_ID function-id. This is reset to 0.

Errors:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -ENOENT
>
> </td>
> <td>
>
>
> Unknown register accessed.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EBUSY
>
> </td>
> <td>
>
>
> Attempt a 'write' to the register after the VM has started.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EINVAL
>
> </td>
> <td>
>
>
> Invalid bitmap written to the register.
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-footnote-1"></a>



**[1]** [https://developer.arm.com/-/media/developer/pdf/ARM_DEN_0070A_Firmware_interfaces_for_mitigating_CVE-2017-5715.pdf](<https://developer.arm.com/-/media/developer/pdf/ARM_DEN_0070A_Firmware_interfaces_for_mitigating_CVE-2017-5715.pdf>)

---

# Internal ABI between the kernel and HYP

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> This file documents the interaction between the Linux kernel and the hypervisor layer when running Linux as a hypervisor (for example KVM). It doesn't cover the interaction of the kernel with the hypervisor when running as a guest (under…

<a id="rst-internal-abi-between-the-kernel-and-hyp"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This file documents the interaction between the Linux kernel and the hypervisor layer when running Linux as a hypervisor (for example KVM). It doesn't cover the interaction of the kernel with the hypervisor when running as a guest (under Xen, KVM or any other hypervisor), or any hypervisor-specific interaction when the kernel is used as a host.

Note: KVM/arm has been removed from the kernel. The API described here is still valid though, as it allows the kernel to kexec when booted at HYP. It can also be used by a hypervisor other than KVM if necessary.

On arm and arm64 (without VHE), the kernel doesn't run in hypervisor mode, but still needs to interact with it, allowing a built-in hypervisor to be either installed or torn down.

In order to achieve this, the kernel must be booted at HYP (arm) or EL2 (arm64), allowing it to install a set of stubs before dropping to SVC/EL1. These stubs are accessible by using a 'hvc \#0' instruction, and only act on individual CPUs.

Unless specified otherwise, any built-in hypervisor must implement these functions (see arch/arm\{,64\}/include/asm/virt.h):

- 

  ```text
  r0/x0 = HVC_SET_VECTORS
  r1/x1 = vectors
  ```

  Set HVBAR/VBAR_EL2 to 'vectors' to enable a hypervisor. 'vectors' must be a physical address, and respect the alignment requirements of the architecture. Only implemented by the initial stubs, not by Linux hypervisors.

- 

  ```text
  r0/x0 = HVC_RESET_VECTORS
  ```

  Turn HYP/EL2 MMU off, and reset HVBAR/VBAR_EL2 to the initials stubs' exception vector value. This effectively disables an existing hypervisor.

- 

  ```text
  r0/x0 = HVC_SOFT_RESTART
  r1/x1 = restart address
  x2 = x0's value when entering the next payload (arm64)
  x3 = x1's value when entering the next payload (arm64)
  x4 = x2's value when entering the next payload (arm64)
  ```

  Mask all exceptions, disable the MMU, clear I+D bits, move the arguments into place (arm64 only), and jump to the restart address while at HYP/EL2. This hypercall is not expected to return to its caller.

- 

  ```text
  x0 = HVC_FINALISE_EL2 (arm64 only)
  ```

  Finish configuring EL2 depending on the command-line options, including an attempt to upgrade the kernel's exception level from EL1 to EL2 by enabling the VHE mode. This is conditioned by the CPU supporting VHE, the EL2 MMU being off, and VHE not being disabled by any other means (command line option, for example).

Any other value of r0/x0 triggers a hypervisor-specific handling, which is not documented here.

The return value of a stub hypercall is held by r0/x0, and is 0 on success, and HVC_STUB_ERR on error. A stub hypercall is allowed to clobber any of the caller-saved registers (x0-x18 on arm64, r0-r3 and ip on arm). It is thus recommended to use a function call to perform the hypercall.

---

# KVM/arm64-specific hypercalls exposed to guests

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> This file documents the KVM/arm64-specific hypercalls which may be exposed by KVM/arm64 to guest operating systems. These hypercalls are issued using the HVC instruction according to version 1.1 of the Arm SMC Calling Convention…

<a id="rst-kvm-arm64-specific-hypercalls-exposed-to-guests"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This file documents the KVM/arm64-specific hypercalls which may be exposed by KVM/arm64 to guest operating systems. These hypercalls are issued using the HVC instruction according to version 1.1 of the Arm SMC Calling Convention (DEN0028/C):

[https://developer.arm.com/docs/den0028/c](<https://developer.arm.com/docs/den0028/c>)

All KVM/arm64-specific hypercalls are allocated within the "Vendor Specific Hypervisor Service Call" range with a UID of `28b46fb6-2ec5-11e9-a9ca-4b564d003a74`. This UID should be queried by the guest using the standard "Call UID" function for the service range in order to determine that the KVM/arm64-specific hypercalls are available.

<a id="rst-arm-smccc-vendor-hyp-kvm-features-func-id"></a>

## `ARM_SMCCC_VENDOR_HYP_KVM_FEATURES_FUNC_ID`

Provides a discovery mechanism for other KVM/arm64 hypercalls.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Mandatory for the KVM/arm64 UID

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC32

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0x86000000

</td>
</tr>
<tr>
<td>


Arguments:

</td>
<td colspan="3">


None

</td>
</tr>
<tr>
<td rowspan="4">


Return Values:

</td>
<td>


(uint32)

</td>
<td>


R0

</td>
<td>


Bitmap of available function numbers 0-31

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R1

</td>
<td>


Bitmap of available function numbers 32-63

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R2

</td>
<td>


Bitmap of available function numbers 64-95

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R3

</td>
<td>


Bitmap of available function numbers 96-127

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-vendor-hyp-kvm-ptp-func-id"></a>

## `ARM_SMCCC_VENDOR_HYP_KVM_PTP_FUNC_ID`

See [ptp_kvm.rst](/kernel/internals/virt/kvm-arm/ptp-kvm.md)

<a id="rst-arm-smccc-kvm-func-hyp-meminfo"></a>

## `ARM_SMCCC_KVM_FUNC_HYP_MEMINFO`

Query the memory protection parameters for a pKVM protected virtual machine.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional; pKVM protected guests only.

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000002

</td>
</tr>
<tr>
<td rowspan="3">


Arguments:

</td>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


Return Values:

</td>
<td>


(int64)

</td>
<td>


R0

</td>
<td>


`INVALID_PARAMETER (-3)` on error, else memory protection granule in bytes

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-kvm-func-mem-share"></a>

## `ARM_SMCCC_KVM_FUNC_MEM_SHARE`

Share a region of memory with the KVM host, granting it read, write and execute permissions. The size of the region is equal to the memory protection granule advertised by `ARM_SMCCC_KVM_FUNC_HYP_MEMINFO`.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional; pKVM protected guests only.

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000003

</td>
</tr>
<tr>
<td rowspan="3">


Arguments:

</td>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


Base IPA of memory region to share

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td rowspan="2">


Return Values:

</td>
<td rowspan="2">


(int64)

</td>
<td rowspan="2">


R0

</td>
<td>


`SUCCESS (0)`

</td>
</tr>
<tr>
<td>


`INVALID_PARAMETER (-3)`

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-kvm-func-mem-unshare"></a>

## `ARM_SMCCC_KVM_FUNC_MEM_UNSHARE`

Revoke access permission from the KVM host to a memory region previously shared with `ARM_SMCCC_KVM_FUNC_MEM_SHARE`. The size of the region is equal to the memory protection granule advertised by `ARM_SMCCC_KVM_FUNC_HYP_MEMINFO`.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional; pKVM protected guests only.

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000004

</td>
</tr>
<tr>
<td rowspan="3">


Arguments:

</td>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


Base IPA of memory region to unshare

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td rowspan="2">


Return Values:

</td>
<td rowspan="2">


(int64)

</td>
<td rowspan="2">


R0

</td>
<td>


`SUCCESS (0)`

</td>
</tr>
<tr>
<td>


`INVALID_PARAMETER (-3)`

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-kvm-func-mmio-guard"></a>

## `ARM_SMCCC_KVM_FUNC_MMIO_GUARD`

Request that a given memory region is handled as MMIO by the hypervisor, allowing accesses to this region to be emulated by the KVM host. The size of the region is equal to the memory protection granule advertised by `ARM_SMCCC_KVM_FUNC_HYP_MEMINFO`.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional; pKVM protected guests only.

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000007

</td>
</tr>
<tr>
<td rowspan="3">


Arguments:

</td>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


Base IPA of MMIO memory region

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td rowspan="2">


Return Values:

</td>
<td rowspan="2">


(int64)

</td>
<td rowspan="2">


R0

</td>
<td>


`SUCCESS (0)`

</td>
</tr>
<tr>
<td>


`INVALID_PARAMETER (-3)`

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-vendor-hyp-kvm-discover-impl-ver-func-id"></a>

## `ARM_SMCCC_VENDOR_HYP_KVM_DISCOVER_IMPL_VER_FUNC_ID`

Request the target CPU implementation version information and the number of target implementations for the Guest VM.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional;  KVM/ARM64 Guests only

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000040

</td>
</tr>
<tr>
<td>


Arguments:

</td>
<td colspan="3">


None

</td>
</tr>
<tr>
<td rowspan="7">


Return Values:

</td>
<td rowspan="2">


(int64)

</td>
<td rowspan="2">


R0

</td>
<td>


`SUCCESS (0)`

</td>
</tr>
<tr>
<td>


`NOT_SUPPORTED (-1)`

</td>
</tr>
<tr>
<td rowspan="3">


(uint64)

</td>
<td rowspan="3">


R1

</td>
<td>


Bits \[63:32\] Reserved/Must be zero

</td>
</tr>
<tr>
<td>


Bits \[31:16\] Major version

</td>
</tr>
<tr>
<td>


Bits \[15:0\] Minor version

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Number of target implementations

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
</tbody>
</table>

<a id="rst-arm-smccc-vendor-hyp-kvm-discover-impl-cpus-func-id"></a>

## `ARM_SMCCC_VENDOR_HYP_KVM_DISCOVER_IMPL_CPUS_FUNC_ID`

Request the target CPU implementation information for the Guest VM. The Guest kernel will use this information to enable the associated errata.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional;  KVM/ARM64 Guests only

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC64

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0xC6000041

</td>
</tr>
<tr>
<td rowspan="3">


Arguments:

</td>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


selected implementation index

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


Reserved / Must be zero

</td>
</tr>
<tr>
<td rowspan="5">


Return Values:

</td>
<td rowspan="2">


(int64)

</td>
<td rowspan="2">


R0

</td>
<td>


`SUCCESS (0)`

</td>
</tr>
<tr>
<td>


`INVALID_PARAMETER (-3)`

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R1

</td>
<td>


MIDR_EL1 of the selected implementation

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R2

</td>
<td>


REVIDR_EL1 of the selected implementation

</td>
</tr>
<tr>
<td>


(uint64)

</td>
<td>


R3

</td>
<td>


AIDR_EL1  of the selected implementation

</td>
</tr>
</tbody>
</table>

---

# PTP_KVM support for arm/arm64

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> PTP_KVM is used for high precision time sync between host and guests. It relies on transferring the wall clock and counter value from the host to the guest using a KVM-specific hypercall.

<a id="rst-ptp-kvm-support-for-arm-arm64"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

PTP_KVM is used for high precision time sync between host and guests. It relies on transferring the wall clock and counter value from the host to the guest using a KVM-specific hypercall.

<a id="rst-arm-smccc-vendor-hyp-kvm-ptp-func-id"></a>

## `ARM_SMCCC_VENDOR_HYP_KVM_PTP_FUNC_ID`

Retrieve current time information for the specific counter. There are no endianness restrictions.


<table>
<tbody>
<tr>
<td>


Presence:

</td>
<td colspan="3">


Optional

</td>
</tr>
<tr>
<td>


Calling convention:

</td>
<td colspan="3">


HVC32

</td>
</tr>
<tr>
<td>


Function ID:

</td>
<td>


(uint32)

</td>
<td colspan="2">


0x86000001

</td>
</tr>
<tr>
<td rowspan="2">


Arguments:

</td>
<td rowspan="2">


(uint32)

</td>
<td rowspan="2">


R1

</td>
<td>


`KVM_PTP_VIRT_COUNTER (0)`

</td>
</tr>
<tr>
<td>


`KVM_PTP_PHYS_COUNTER (1)`

</td>
</tr>
<tr>
<td rowspan="4">


Return Values:

</td>
<td>


(int32)

</td>
<td>


R0

</td>
<td>


`NOT_SUPPORTED (-1)` on error, else upper 32 bits of wall clock time

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R1

</td>
<td>


Lower 32 bits of wall clock time

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R2

</td>
<td>


Upper 32 bits of counter

</td>
</tr>
<tr>
<td>


(uint32)

</td>
<td>


R3

</td>
<td>


Lower 32 bits of counter

</td>
</tr>
</tbody>
</table>

---

# Paravirtualized time support for arm64

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> Arm specification DEN0057/A defines a standard for paravirtualised time support for AArch64 guests:

<a id="rst-paravirtualized-time-support-for-arm64"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Arm specification DEN0057/A defines a standard for paravirtualised time support for AArch64 guests:

[https://developer.arm.com/docs/den0057/a](<https://developer.arm.com/docs/den0057/a>)

KVM/arm64 implements the stolen time part of this specification by providing some hypervisor service calls to support a paravirtualized guest obtaining a view of the amount of time stolen from its execution.

Two new SMCCC compatible hypercalls are defined:

- PV_TIME_FEATURES: 0xC5000020

- PV_TIME_ST:       0xC5000021

These are only available in the SMC64/HVC64 calling convention as paravirtualized time is not available to 32 bit Arm guests. The existence of the PV_TIME_FEATURES hypercall should be probed using the SMCCC 1.1 ARCH_FEATURES mechanism before calling it.

PV_TIME_FEATURES

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> Function ID:
>
> </td>
> <td>
>
>
> (uint32)
>
> </td>
> <td>
>
>
> 0xC5000020
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> PV_call_id:
>
> </td>
> <td>
>
>
> (uint32)
>
> </td>
> <td>
>
>
> The function to query for support. Currently only PV_TIME_ST is supported.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Return value:
>
> </td>
> <td>
>
>
> (int64)
>
> </td>
> <td>
>
>
> NOT_SUPPORTED (-1) or SUCCESS (0) if the relevant PV-time feature is supported by the hypervisor.
>
> </td>
> </tr>
> </tbody>
> </table>

PV_TIME_ST

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> Function ID:
>
> </td>
> <td>
>
>
> (uint32)
>
> </td>
> <td>
>
>
> 0xC5000021
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> Return value:
>
> </td>
> <td>
>
>
> (int64)
>
> </td>
> <td>
>
>
> IPA of the stolen time data structure for this VCPU. On failure: NOT_SUPPORTED (-1)
>
> </td>
> </tr>
> </tbody>
> </table>

The IPA returned by PV_TIME_ST should be mapped by the guest as normal memory with inner and outer write back caching attributes, in the inner shareable domain. A total of 16 bytes from the IPA returned are guaranteed to be meaningfully filled by the hypervisor (see structure below).

PV_TIME_ST returns the structure for the calling VCPU.

<a id="rst-stolen-time"></a>

## Stolen Time

The structure pointed to by the PV_TIME_ST hypercall is as follows:


<table>
<thead>
<tr>
<th>


Field

</th>
<th>


Byte Length

</th>
<th>


Byte Offset

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Revision

</td>
<td>


4

</td>
<td>


0

</td>
<td>


Must be 0 for version 1.0

</td>
</tr>
<tr>
<td>


Attributes

</td>
<td>


4

</td>
<td>


4

</td>
<td>


Must be 0

</td>
</tr>
<tr>
<td>


Stolen time

</td>
<td>


8

</td>
<td>


8

</td>
<td>


Stolen time in unsigned nanoseconds indicating how much time this VCPU thread was involuntarily not running on a physical CPU.

</td>
</tr>
</tbody>
</table>

All values in the structure are stored little-endian.

The structure will be updated by the hypervisor prior to scheduling a VCPU. It will be present within a reserved region of the normal memory given to the guest. The guest should not attempt to write into this memory. There is a structure per VCPU of the guest.

It is advisable that one or more 64k pages are set aside for the purpose of these structures and not used for other purposes, this enables the guest to map the region using 64k pages and avoids conflicting attributes with other memory.

For the user space interface see [Documentation/virt/kvm/devices/vcpu.rst](</kernel/internals/virt/kvm-devices/vcpu.md#rst-kvm-arm-vcpu-pvtime-ctrl>).

---

# vCPU feature selection on arm64

_Peios Kernel / Internals / Virtualisation / kvm / arm_

> KVM/arm64 provides two mechanisms that allow userspace to configure the CPU features presented to the guest.

<a id="rst-vcpu-feature-selection-on-arm64"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

KVM/arm64 provides two mechanisms that allow userspace to configure the CPU features presented to the guest.

<a id="rst-kvm-arm-vcpu-init"></a>

## KVM_ARM_VCPU_INIT

The `KVM_ARM_VCPU_INIT` ioctl accepts a bitmap of feature flags (`struct kvm_vcpu_init::features`). Features enabled by this interface are *opt-in* and may change/extend UAPI. See [KVM_ARM_VCPU_INIT](<#rst-kvm-arm-vcpu-init>) for complete documentation of the features controlled by the ioctl.

Otherwise, all CPU features supported by KVM are described by the architected ID registers.

<a id="rst-the-id-registers"></a>

## The ID Registers

The Arm architecture specifies a range of *ID Registers* that describe the set of architectural features supported by the CPU implementation. KVM initializes the guest's ID registers to the maximum set of CPU features supported by the system. The ID register values may be VM-scoped in KVM, meaning that the values could be shared for all vCPUs in a VM.

KVM allows userspace to *opt-out* of certain CPU features described by the ID registers by writing values to them via the `KVM_SET_ONE_REG` ioctl. The ID registers are mutable until the VM has started, i.e. userspace has called `KVM_RUN` on at least one vCPU in the VM. Userspace can discover what fields are mutable in the ID registers using the `KVM_ARM_GET_REG_WRITABLE_MASKS`. See the [ioctl documentation](</kernel/internals/virt/kvm/api.md#rst-kvm-arm-get-reg-writable-masks>) for more details.

Userspace is allowed to *limit* or *mask* CPU features according to the rules outlined by the architecture in DDI0487J.a D19.1.3 'Principles of the ID scheme for fields in ID register'. KVM does not allow ID register values that exceed the capabilities of the system.

> [!WARNING]
>
> It is **strongly recommended** that userspace modify the ID register values before accessing the rest of the vCPU's CPU register state. KVM may use the ID register values to control feature emulation. Interleaving ID register modification with other system register accesses may lead to unpredictable behavior.

---

# Devices

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Reference for Devices.

<a id="rst-devices"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [ARM Virtual Interrupt Translation Service (ITS)](</kernel/internals/virt/kvm-devices/arm-vgic-its.md>)
- [ARM Virtual Generic Interrupt Controller v2 (VGIC)](</kernel/internals/virt/kvm-devices/arm-vgic.md>)
- [ARM Virtual Generic Interrupt Controller v3 and later (VGICv3)](</kernel/internals/virt/kvm-devices/arm-vgic-v3.md>)
- [MPIC interrupt controller](</kernel/internals/virt/kvm-devices/mpic.md>)
- [FLIC (floating interrupt controller)](</kernel/internals/virt/kvm-devices/s390-flic.md>)
- [Generic vcpu interface](</kernel/internals/virt/kvm-devices/vcpu.md>)
- [VFIO virtual device](</kernel/internals/virt/kvm-devices/vfio.md>)
- [Generic vm interface](</kernel/internals/virt/kvm-devices/vm.md>)
- [XICS interrupt controller](</kernel/internals/virt/kvm-devices/xics.md>)
- [POWER9 eXternal Interrupt Virtualization Engine (XIVE Gen1)](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/virt/kvm/devices/xive.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# ARM Virtual Interrupt Translation Service (ITS)

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> KVM_DEV_TYPE_ARM_VGIC_ITS ARM Interrupt Translation Service Controller

<a id="rst-arm-virtual-interrupt-translation-service-its"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Device types supported:**

  KVM_DEV_TYPE_ARM_VGIC_ITS    ARM Interrupt Translation Service Controller

The ITS allows MSI(-X) interrupts to be injected into guests. This extension is optional.  Creating a virtual ITS controller also requires a host GICv3 (see arm-vgic-v3.txt), but does not depend on having physical ITS controllers.

There can be multiple ITS controllers per guest, each of them has to have a separate, non-overlapping MMIO region.

<a id="rst-groups"></a>

## Groups

<a id="rst-kvm-dev-arm-vgic-grp-addr"></a>

### KVM_DEV_ARM_VGIC_GRP_ADDR

> - **Attributes:**
>
>   - **KVM_VGIC_ITS_ADDR_TYPE (rw, 64-bit)**
>
>     Base address in the guest physical address space of the GICv3 ITS control register frame. This address needs to be 64K aligned and the region covers 128K.
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -E2BIG
> >
> > </td>
> > <td>
> >
> >
> > Address outside of addressable IPA range
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Incorrectly aligned address
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EEXIST
> >
> > </td>
> > <td>
> >
> >
> > Address already configured
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid user pointer for attr-&gt;addr.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -ENODEV
> >
> > </td>
> > <td>
> >
> >
> > Incorrect attribute or the ITS is not supported.
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

<a id="rst-kvm-dev-arm-vgic-grp-ctrl"></a>

### KVM_DEV_ARM_VGIC_GRP_CTRL

> - **Attributes:**
>
>   - **KVM_DEV_ARM_VGIC_CTRL_INIT**
>
>     request the initialization of the ITS, no additional parameter in kvm_device_attr.addr.
>
>   - **KVM_DEV_ARM_ITS_CTRL_RESET**
>
>     reset the ITS, no additional parameter in kvm_device_attr.addr. See "ITS Reset State" section.
>
>   - **KVM_DEV_ARM_ITS_SAVE_TABLES**
>
>     save the ITS table data into guest RAM, at the location provisioned by the guest in corresponding registers/table entries. Should userspace require a form of dirty tracking to identify which pages are modified by the saving process, it should use a bitmap even if using another mechanism to track the memory dirtied by the vCPUs.
>
>     The layout of the tables in guest memory defines an ABI. The entries are laid out in little endian format as described in the last paragraph.
>
>   - **KVM_DEV_ARM_ITS_RESTORE_TABLES**
>
>     restore the ITS tables from guest RAM to ITS internal structures.
>
>     The GICV3 must be restored before the ITS and all ITS registers but the GITS_CTLR must be restored before restoring the ITS tables.
>
>     The GITS_IIDR read-only register must also be restored before calling KVM_DEV_ARM_ITS_RESTORE_TABLES as the IIDR revision field encodes the ABI revision.
>
>     The expected ordering when restoring the GICv3/ITS is described in section "ITS Restore Sequence".
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -ENXIO
> >
> > </td>
> > <td>
> >
> >
> > ITS not properly configured as required prior to setting this attribute
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -ENOMEM
> >
> > </td>
> > <td>
> >
> >
> > Memory shortage when allocating ITS internal data
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Inconsistent restored data
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid guest ram access
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EBUSY
> >
> > </td>
> > <td>
> >
> >
> > One or more VCPUS are running
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EACCES
> >
> > </td>
> > <td>
> >
> >
> > The virtual ITS is backed by a physical GICv4 ITS, and the state is not available without GICv4.1
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

<a id="rst-kvm-dev-arm-vgic-grp-its-regs"></a>

### KVM_DEV_ARM_VGIC_GRP_ITS_REGS

> - **Attributes:**
>
>   The attr field of kvm_device_attr encodes the offset of the ITS register, relative to the ITS control frame base address (ITS_base).
>
>   kvm_device_attr.addr points to a \__u64 value whatever the width of the addressed register (32/64 bits). 64 bit registers can only be accessed with full length.
>
>   Writes to read-only registers are ignored by the kernel except for:
>
>   - GITS_CREADR. It must be restored otherwise commands in the queue will be re-executed after restoring CWRITER. GITS_CREADR must be restored before restoring the GITS_CTLR which is likely to enable the ITS. Also it must be restored after GITS_CBASER since a write to GITS_CBASER resets GITS_CREADR.
>
>   - GITS_IIDR. The Revision field encodes the table layout ABI revision. In the future we might implement direct injection of virtual LPIs. This will require an upgrade of the table layout and an evolution of the ABI. GITS_IIDR must be restored before calling KVM_DEV_ARM_ITS_RESTORE_TABLES.
>
>   For other registers, getting or setting a register has the same effect as reading/writing the register on real hardware.
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -ENXIO
> >
> > </td>
> > <td>
> >
> >
> > Offset does not correspond to any supported register
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid user pointer for attr-&gt;addr
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Offset is not 64-bit aligned
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EBUSY
> >
> > </td>
> > <td>
> >
> >
> > one or more VCPUS are running
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

<a id="rst-its-restore-sequence"></a>

### ITS Restore Sequence:

The following ordering must be followed when restoring the GIC, ITS, and KVM_IRQFD assignments:

- **a)** restore all guest memory and create vcpus

- **b)** restore all redistributors

- **c)** provide the ITS base address (KVM_DEV_ARM_VGIC_GRP_ADDR)

- **d)** restore the ITS in the following order:

  > 1. Restore GITS_CBASER
  >
  > 2. Restore all other `GITS_` registers, except GITS_CTLR\!
  >
  > 3. Load the ITS table data (KVM_DEV_ARM_ITS_RESTORE_TABLES)
  >
  > 4. Restore GITS_CTLR

- **e)** restore KVM_IRQFD assignments for MSIs

Then vcpus can be started.

<a id="rst-its-table-abi-rev0"></a>

### ITS Table ABI REV0:

> Revision 0 of the ABI only supports the features of a virtual GICv3, and does not support a virtual GICv4 with support for direct injection of virtual interrupts for nested hypervisors.
>
> The device table and ITT are indexed by the DeviceID and EventID, respectively. The collection table is not indexed by CollectionID, and the entries in the collection are listed in no particular order. All entries are 8 bytes.
>
> Device Table Entry (DTE):
>
>
>
> ```text
> bits:     | 63| 62 ... 49 | 48 ... 5 | 4 ... 0 |
> values:   | V |   next    | ITT_addr |  Size   |
> ```
>
> where:
>
> - V indicates whether the entry is valid. If not, other fields are not meaningful.
>
> - next: equals to 0 if this entry is the last one; otherwise it corresponds to the DeviceID offset to the next DTE, capped by 2^14 -1.
>
> - ITT_addr matches bits \[51:8\] of the ITT address (256 Byte aligned).
>
> - Size specifies the supported number of bits for the EventID, minus one
>
> Collection Table Entry (CTE):
>
>
>
> ```text
> bits:     | 63| 62 ..  52  | 51 ... 16 | 15  ...   0 |
> values:   | V |    RES0    |  RDBase   |    ICID     |
> ```
>
> where:
>
> - V indicates whether the entry is valid. If not, other fields are not meaningful.
>
> - RES0: reserved field with Should-Be-Zero-or-Preserved behavior.
>
> - RDBase is the PE number (GICR_TYPER.Processor_Number semantic),
>
> - ICID is the collection ID
>
> Interrupt Translation Entry (ITE):
>
>
>
> ```text
> bits:     | 63 ... 48 | 47 ... 16 | 15 ... 0 |
> values:   |    next   |   pINTID  |  ICID    |
> ```
>
> where:
>
> - next: equals to 0 if this entry is the last one; otherwise it corresponds to the EventID offset to the next ITE capped by 2^16 -1.
>
> - pINTID is the physical LPI ID; if zero, it means the entry is not valid and other fields are not meaningful.
>
> - ICID is the collection ID

<a id="rst-its-reset-state"></a>

### ITS Reset State:

RESET returns the ITS to the same state that it was when first created and initialized. When the RESET command returns, the following things are guaranteed:

- The ITS is not enabled and quiescent GITS_CTLR.Enabled = 0 .Quiescent=1

- There is no internally cached state

- No collection or device table are used GITS_BASER&lt;n&gt;.Valid = 0

- GITS_CBASER = 0, GITS_CREADR = 0, GITS_CWRITER = 0

- The ABI version is unchanged and remains the one set when the ITS device was first created.

---

# ARM Virtual Generic Interrupt Controller v3 and later (VGICv3)

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> KVM_DEV_TYPE_ARM_VGIC_V3 ARM Generic Interrupt Controller v3.0

<a id="rst-arm-virtual-generic-interrupt-controller-v3-and-later-vgicv3"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Device types supported:**

  - KVM_DEV_TYPE_ARM_VGIC_V3     ARM Generic Interrupt Controller v3.0

Only one VGIC instance may be instantiated through this API.  The created VGIC will act as the VM interrupt controller, requiring emulated user-space devices to inject interrupts to the VGIC instead of directly to CPUs.  It is not possible to create both a GICv3 and GICv2 on the same VM.

Creating a guest GICv3 device requires a host GICv3 host, or a GICv5 host with support for FEAT_GCIE_LEGACY.

- **Groups:**

  - **KVM_DEV_ARM_VGIC_GRP_ADDR**

    Attributes:

    > - **KVM_VGIC_V3_ADDR_TYPE_DIST (rw, 64-bit)**
    >
    >   Base address in the guest physical address space of the GICv3 distributor register mappings. Only valid for KVM_DEV_TYPE_ARM_VGIC_V3. This address needs to be 64K aligned and the region covers 64 KByte.
    >
    > - **KVM_VGIC_V3_ADDR_TYPE_REDIST (rw, 64-bit)**
    >
    >   Base address in the guest physical address space of the GICv3 redistributor register mappings. There are two 64K pages for each VCPU and all of the redistributor pages are contiguous. Only valid for KVM_DEV_TYPE_ARM_VGIC_V3. This address needs to be 64K aligned.
    >
    > - **KVM_VGIC_V3_ADDR_TYPE_REDIST_REGION (rw, 64-bit)**
    >
    >   The attribute data pointed to by kvm_device_attr.addr is a \__u64 value:
    >
    >
    >
    >   ```text
    >   bits:     | 63   ....  52  |  51   ....   16 | 15 - 12  |11 - 0
    >   values:   |     count      |       base      |  flags   | index
    >   ```
    >
    >   - index encodes the unique redistributor region index
    >
    >   - flags: reserved for future use, currently 0
    >
    >   - base field encodes bits \[51:16\] of the guest physical base address of the first redistributor in the region.
    >
    >   - count encodes the number of redistributors in the region. Must be greater than 0.
    >
    >   There are two 64K pages for each redistributor in the region and redistributors are laid out contiguously within the region. Regions are filled with redistributors in the index order. The sum of all region count fields must be greater than or equal to the number of VCPUs. Redistributor regions must be registered in the incremental index order, starting from index 0.
    >
    >   The characteristics of a specific redistributor region can be read by presetting the index field in the attr data. Only valid for KVM_DEV_TYPE_ARM_VGIC_V3.

  It is invalid to mix calls with KVM_VGIC_V3_ADDR_TYPE_REDIST and KVM_VGIC_V3_ADDR_TYPE_REDIST_REGION attributes.

  Note that to obtain reproducible results (the same VCPU being associated with the same redistributor across a save/restore operation), VCPU creation order, redistributor region creation order as well as the respective interleaves of VCPU and region creation MUST be preserved.  Any change in either ordering may result in a different vcpu_id/redistributor association, resulting in a VM that will fail to run at restore time.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -E2BIG
  >
  > </td>
  > <td>
  >
  >
  > Address outside of addressable IPA range
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Incorrectly aligned address, bad redistributor region count/index, mixed redistributor region attribute usage
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EEXIST
  >
  > </td>
  > <td>
  >
  >
  > Address already configured
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENOENT
  >
  > </td>
  > <td>
  >
  >
  > Attempt to read the characteristics of a non existing redistributor region
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > The group or attribute is unknown/unsupported for this device or hardware support is missing.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EFAULT
  >
  > </td>
  > <td>
  >
  >
  > Invalid user pointer for attr-&gt;addr.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > Attempt to write a register that is read-only after initialization
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_DIST_REGS, KVM_DEV_ARM_VGIC_GRP_REDIST_REGS**

    Attributes:

    > The attr field of kvm_device_attr encodes two values:
    >
    >
    >
    > ```text
    > bits:     | 63   ....  32  |  31   ....    0 |
    > values:   |      mpidr     |      offset     |
    > ```
    >
    > All distributor regs are (rw, 32-bit) and kvm_device_attr.addr points to a \__u32 value.  64-bit registers must be accessed by separately accessing the lower and higher word.
    >
    > Writes to read-only registers are ignored by the kernel.
    >
    > KVM_DEV_ARM_VGIC_GRP_DIST_REGS accesses the main distributor registers. KVM_DEV_ARM_VGIC_GRP_REDIST_REGS accesses the redistributor of the CPU specified by the mpidr.
    >
    > The offset is relative to the "\[Re\]Distributor base address" as defined in the GICv3/4 specs.  Getting or setting such a register has the same effect as reading or writing the register on real hardware, except for the following registers: GICD_STATUSR, GICR_STATUSR, GICD_ISPENDR, GICR_ISPENDR0, GICD_ICPENDR, and GICR_ICPENDR0.  These registers behave differently when accessed via this interface compared to their architecturally defined behavior to allow software a full view of the VGIC's internal state.
    >
    > The mpidr field is used to specify which redistributor is accessed.  The mpidr is ignored for the distributor.
    >
    > The mpidr encoding is based on the affinity information in the architecture defined MPIDR, and the field is encoded as follows:
    >
    >
    >
    > ```text
    > | 63 .... 56 | 55 .... 48 | 47 .... 40 | 39 .... 32 |
    > |    Aff3    |    Aff2    |    Aff1    |    Aff0    |
    > ```
    >
    > Note that distributor fields are not banked, but return the same value regardless of the mpidr used to access the register.
    >
    > Userspace is allowed to write the following register fields prior to initialization of the VGIC:
    >
    > > - GICD_IIDR.Revision
    > >
    > > - GICD_TYPER2.nASSGIcap
    >
    > GICD_IIDR.Revision is updated when the KVM implementation is changed in a way directly observable by the guest or userspace.  Userspace should read GICD_IIDR from KVM and write back the read value to confirm its expected behavior is aligned with the KVM implementation.  Userspace should set GICD_IIDR before setting any other registers to ensure the expected behavior.
    >
    > GICD_TYPER2.nASSGIcap allows userspace to control the support of SGIs without an active state. At VGIC creation the field resets to the maximum capability of the system. Userspace is expected to read the field to determine the supported value(s) before writing to the field.
    >
    > The GICD_STATUSR and GICR_STATUSR registers are architecturally defined such that a write of a clear bit has no effect, whereas a write with a set bit clears that value.  To allow userspace to freely set the values of these two registers, setting the attributes with the register offsets for these two registers simply sets the non-reserved bits to the value written.
    >
    > Accesses (reads and writes) to the GICD_ISPENDR register region and GICR_ISPENDR0 registers get/set the value of the latched pending state for the interrupts.
    >
    > This is identical to the value returned by a guest read from ISPENDR for an edge triggered interrupt, but may differ for level triggered interrupts. For edge triggered interrupts, once an interrupt becomes pending (whether because of an edge detected on the input line or because of a guest write to ISPENDR) this state is "latched", and only cleared when either the interrupt is activated or when the guest writes to ICPENDR. A level triggered interrupt may be pending either because the level input is held high by a device, or because of a guest write to the ISPENDR register. Only ISPENDR writes are latched; if the device lowers the line level then the interrupt is no longer pending unless the guest also wrote to ISPENDR, and conversely writes to ICPENDR or activations of the interrupt do not clear the pending status if the line level is still being held high.  (These rules are documented in the GICv3 specification descriptions of the ICPENDR and ISPENDR registers.) For a level triggered interrupt the value accessed here is that of the latch which is set by ISPENDR and cleared by ICPENDR or interrupt activation, whereas the value returned by a guest read from ISPENDR is the logical OR of the latch value and the input line level.
    >
    > Raw access to the latch state is provided to userspace so that it can save and restore the entire GIC internal state (which is defined by the combination of the current input line level and the latch state, and cannot be deduced from purely the line level and the value of the ISPENDR registers).
    >
    > Accesses to GICD_ICPENDR register region and GICR_ICPENDR0 registers have RAZ/WI semantics, meaning that reads always return 0 and writes are always ignored.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > Getting or setting this register is not yet supported
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > One or more VCPUs are running
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_CPU_SYSREGS**

    Attributes:

    > The attr field of kvm_device_attr encodes two values:
    >
    >
    >
    > ```text
    > bits:     | 63      ....       32 | 31  ....  16 | 15  ....  0 |
    > values:   |         mpidr         |      RES     |    instr    |
    > ```
    >
    > The mpidr field encodes the CPU ID based on the affinity information in the architecture defined MPIDR, and the field is encoded as follows:
    >
    >
    >
    > ```text
    > | 63 .... 56 | 55 .... 48 | 47 .... 40 | 39 .... 32 |
    > |    Aff3    |    Aff2    |    Aff1    |    Aff0    |
    > ```
    >
    > The instr field encodes the system register to access based on the fields defined in the A64 instruction set encoding for system register access (RES means the bits are reserved for future use and should be zero):
    >
    >
    >
    > ```text
    > | 15 ... 14 | 13 ... 11 | 10 ... 7 | 6 ... 3 | 2 ... 0 |
    > |   Op 0    |    Op1    |    CRn   |   CRm   |   Op2   |
    > ```
    >
    > All system regs accessed through this API are (rw, 64-bit) and kvm_device_attr.addr points to a \__u64 value.
    >
    > KVM_DEV_ARM_VGIC_GRP_CPU_SYSREGS accesses the CPU interface registers for the CPU specified by the mpidr field.
    >
    > The available registers are:
    >
    >
    > <table>
    > <tbody>
    > <tr>
    > <td>
    >
    >
    > ICC_PMR_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_BPR0_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP0R0_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP0R1_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements at least 6 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP0R2_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP0R3_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP1R0_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP1R1_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements at least 6 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP1R2_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_AP1R3_EL1
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_BPR1_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_CTLR_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_SRE_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_IGRPEN0_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_IGRPEN1_EL1
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > </tbody>
    > </table>
    >
    > When EL2 is available for the guest, these registers are also available:
    >
    >
    > <table>
    > <tbody>
    > <tr>
    > <td>
    >
    >
    > ICH_AP0R0_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP0R1_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements at least 6 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP0R2_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP0R3_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP1R0_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP1R1_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements at least 6 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP1R2_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_AP1R3_EL2
    >
    > </td>
    > <td>
    >
    >
    > when the host implements 7 bits of priority
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_HCR_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICC_SRE_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_VTR_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_VMCR_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR0_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR1_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR2_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR3_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR4_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR5_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR6_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR7_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR8_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR9_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR10_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR11_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR12_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR13_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR14_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > <tr>
    > <td>
    >
    >
    > ICH_LR15_EL2
    >
    > </td>
    > <td>
    >
    >
    >
    >
    > </td>
    > </tr>
    > </tbody>
    > </table>
    >
    > CPU interface registers are only described using the AArch64 encoding.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > Getting or setting this register is not supported
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > VCPU is running
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Invalid mpidr or register value supplied
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_NR_IRQS**

    Attributes:

    > A value describing the number of interrupts (SGI, PPI and SPI) for this GIC instance, ranging from 64 to 1024, in increments of 32.
    >
    > kvm_device_attr.addr points to a \__u32 value.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Value set is out of the expected range
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > Value has already be set.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_CTRL**

    Attributes:

    > - **KVM_DEV_ARM_VGIC_CTRL_INIT**
    >
    >   request the initialization of the VGIC, no additional parameter in kvm_device_attr.addr. Must be called after all VCPUs have been created.
    >
    > - **KVM_DEV_ARM_VGIC_SAVE_PENDING_TABLES**
    >
    >   save all LPI pending bits into guest RAM pending tables.
    >
    >   The first kB of the pending table is not altered by this operation.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > VGIC not properly configured as required prior to calling this attribute
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENODEV
  >
  > </td>
  > <td>
  >
  >
  > no online VCPU
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENOMEM
  >
  > </td>
  > <td>
  >
  >
  > memory shortage when allocating vgic internal data
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EFAULT
  >
  > </td>
  > <td>
  >
  >
  > Invalid guest ram access
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > One or more VCPUS are running
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_LEVEL_INFO**

    Attributes:

    > The attr field of kvm_device_attr encodes the following values:
    >
    >
    >
    > ```text
    > bits:     | 63      ....       32 | 31   ....    10 | 9  ....  0 |
    > values:   |         mpidr         |      info       |   vINTID   |
    > ```
    >
    > The vINTID specifies which set of IRQs is reported on.
    >
    > The info field specifies which information userspace wants to get or set using this interface.  Currently we support the following info values:
    >
    > > - **VGIC_LEVEL_INFO_LINE_LEVEL:**
    > >
    > >   Get/Set the input level of the IRQ line for a set of 32 contiguously numbered interrupts.
    > >
    > >   vINTID must be a multiple of 32.
    > >
    > >   kvm_device_attr.addr points to a \__u32 value which will contain a bitmap where a set bit means the interrupt level is asserted.
    > >
    > >   Bit\[n\] indicates the status for interrupt vINTID + n.
    >
    > SGIs and any interrupt with a higher ID than the number of interrupts supported, will be RAZ/WI.  LPIs are always edge-triggered and are therefore not supported by this interface.
    >
    > PPIs are reported per VCPU as specified in the mpidr field, and SPIs are reported with the same value regardless of the mpidr specified.
    >
    > The mpidr field encodes the CPU ID based on the affinity information in the architecture defined MPIDR, and the field is encoded as follows:
    >
    >
    >
    > ```text
    > | 63 .... 56 | 55 .... 48 | 47 .... 40 | 39 .... 32 |
    > |    Aff3    |    Aff2    |    Aff1    |    Aff0    |
    > ```

  - **Errors:**


    <table>
    <tbody>
    <tr>
    <td>


    -EINVAL

    </td>
    <td>


    vINTID is not multiple of 32 or info field is not VGIC_LEVEL_INFO_LINE_LEVEL

    </td>
    </tr>
    </tbody>
    </table>

  - **KVM_DEV_ARM_VGIC_GRP_MAINT_IRQ**

    Attributes:

    > The attr field of kvm_device_attr encodes the following values:
    >
    > > bits:     \| 31   ....    5 \| 4  ....  0 \| values:   \|      RES0      \|   vINTID   \|
    >
    > The vINTID specifies which interrupt is generated when the vGIC must generate a maintenance interrupt. This must be a PPI.

---

# ARM Virtual Generic Interrupt Controller v2 (VGIC)

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Device types supported:

<a id="rst-arm-virtual-generic-interrupt-controller-v2-vgic"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Device types supported:

> - KVM_DEV_TYPE_ARM_VGIC_V2     ARM Generic Interrupt Controller v2.0

Only one VGIC instance may be instantiated through either this API or the legacy KVM_CREATE_IRQCHIP API.  The created VGIC will act as the VM interrupt controller, requiring emulated user-space devices to inject interrupts to the VGIC instead of directly to CPUs.

GICv3 implementations with hardware compatibility support allow creating a guest GICv2 through this interface.  For information on creating a guest GICv3 device and guest ITS devices, see arm-vgic-v3.txt.  It is not possible to create both a GICv3 and GICv2 device on the same VM.

- **Groups:**

  - **KVM_DEV_ARM_VGIC_GRP_ADDR**

    Attributes:

    > - **KVM_VGIC_V2_ADDR_TYPE_DIST (rw, 64-bit)**
    >
    >   Base address in the guest physical address space of the GIC distributor register mappings. Only valid for KVM_DEV_TYPE_ARM_VGIC_V2. This address needs to be 4K aligned and the region covers 4 KByte.
    >
    > - **KVM_VGIC_V2_ADDR_TYPE_CPU (rw, 64-bit)**
    >
    >   Base address in the guest physical address space of the GIC virtual cpu interface register mappings. Only valid for KVM_DEV_TYPE_ARM_VGIC_V2. This address needs to be 4K aligned and the region covers 8 KByte.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -E2BIG
  >
  > </td>
  > <td>
  >
  >
  > Address outside of addressable IPA range
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Incorrectly aligned address
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EEXIST
  >
  > </td>
  > <td>
  >
  >
  > Address already configured
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > The group or attribute is unknown/unsupported for this device or hardware support is missing.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EFAULT
  >
  > </td>
  > <td>
  >
  >
  > Invalid user pointer for attr-&gt;addr.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_DIST_REGS**

    Attributes:

    > The attr field of kvm_device_attr encodes two values:
    >
    >
    >
    > ```text
    > bits:     | 63   ....  40 | 39 ..  32  |  31   ....    0 |
    > values:   |    reserved   | vcpu_index |      offset     |
    > ```
    >
    > All distributor regs are (rw, 32-bit)
    >
    > The offset is relative to the "Distributor base address" as defined in the GICv2 specs.  Getting or setting such a register has the same effect as reading or writing the register on the actual hardware from the cpu whose index is specified with the vcpu_index field.  Note that most distributor fields are not banked, but return the same value regardless of the vcpu_index used to access the register.
    >
    > GICD_IIDR.Revision is updated when the KVM implementation of an emulated GICv2 is changed in a way directly observable by the guest or userspace. Userspace should read GICD_IIDR from KVM and write back the read value to confirm its expected behavior is aligned with the KVM implementation. Userspace should set GICD_IIDR before setting any other registers (both KVM_DEV_ARM_VGIC_GRP_DIST_REGS and KVM_DEV_ARM_VGIC_GRP_CPU_REGS) to ensure the expected behavior. Unless GICD_IIDR has been set from userspace, writes to the interrupt group registers (GICD_IGROUPR) are ignored.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > Getting or setting this register is not yet supported
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > One or more VCPUs are running
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Invalid vcpu_index supplied
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_CPU_REGS**

    Attributes:

    > The attr field of kvm_device_attr encodes two values:
    >
    >
    >
    > ```text
    > bits:     | 63   ....  40 | 39 ..  32  |  31   ....    0 |
    > values:   |    reserved   | vcpu_index |      offset     |
    > ```
    >
    > All CPU interface regs are (rw, 32-bit)
    >
    > The offset specifies the offset from the "CPU interface base address" as defined in the GICv2 specs.  Getting or setting such a register has the same effect as reading or writing the register on the actual hardware.
    >
    > The Active Priorities Registers APRn are implementation defined, so we set a fixed format for our implementation that fits with the model of a "GICv2 implementation without the security extensions" which we present to the guest.  This interface always exposes four register APR\[0-3\] describing the maximum possible 128 preemption levels.  The semantics of the register indicate if any interrupts in a given preemption level are in the active state by setting the corresponding bit.
    >
    > Thus, preemption level X has one or more active interrupts if and only if:
    >
    > > APRn\[X mod 32\] == 0b1,  where n = X / 32
    >
    > Bits for undefined preemption levels are RAZ/WI.
    >
    > Note that this differs from a CPU's view of the APRs on hardware in which a GIC without the security extensions expose group 0 and group 1 active priorities in separate register groups, whereas we show a combined view similar to GICv2's GICH_APR.
    >
    > For historical reasons and to provide ABI compatibility with userspace we export the GICC_PMR register in the format of the GICH_VMCR.VMPriMask field in the lower 5 bits of a word, meaning that userspace must always use the lower 5 bits to communicate with the KVM device and must shift the value left by 3 places to obtain the actual priority mask level.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > Getting or setting this register is not yet supported
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > One or more VCPUs are running
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Invalid vcpu_index supplied
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_NR_IRQS**

    Attributes:

    > A value describing the number of interrupts (SGI, PPI and SPI) for this GIC instance, ranging from 64 to 1024, in increments of 32.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Value set is out of the expected range
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > Value has already be set, or GIC has already been initialized with default values.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

  - **KVM_DEV_ARM_VGIC_GRP_CTRL**

    Attributes:

    > - **KVM_DEV_ARM_VGIC_CTRL_INIT**
    >
    >   request the initialization of the VGIC or ITS, no additional parameter in kvm_device_attr.addr.

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -ENXIO
  >
  > </td>
  > <td>
  >
  >
  > VGIC not properly configured as required prior to calling this attribute
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENODEV
  >
  > </td>
  > <td>
  >
  >
  > no online VCPU
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -ENOMEM
  >
  > </td>
  > <td>
  >
  >
  > memory shortage when allocating vgic internal data
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

---

# MPIC interrupt controller

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Device types supported:

<a id="rst-mpic-interrupt-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Device types supported:

> - KVM_DEV_TYPE_FSL_MPIC_20     Freescale MPIC v2.0
>
> - KVM_DEV_TYPE_FSL_MPIC_42     Freescale MPIC v4.2

Only one MPIC instance, of any type, may be instantiated.  The created MPIC will act as the system interrupt controller, connecting to each vcpu's interrupt inputs.

- **Groups:**

  - **KVM_DEV_MPIC_GRP_MISC**

    Attributes:

    > - **KVM_DEV_MPIC_BASE_ADDR (rw, 64-bit)**
    >
    >   Base address of the 256 KiB MPIC register space.  Must be naturally aligned.  A value of zero disables the mapping. Reset value is zero.

  - **KVM_DEV_MPIC_GRP_REGISTER (rw, 32-bit)**

    Access an MPIC register, as if the access were made from the guest. "attr" is the byte offset into the MPIC register space.  Accesses must be 4-byte aligned.

    MSIs may be signaled by using this attribute group to write to the relevant MSIIR.

  - **KVM_DEV_MPIC_GRP_IRQ_ACTIVE (rw, 32-bit)**

    IRQ input line for each standard openpic source.  0 is inactive and 1 is active, regardless of interrupt sense.

    For edge-triggered interrupts:  Writing 1 is considered an activating edge, and writing 0 is ignored.  Reading returns 1 if a previously signaled edge has not been acknowledged, and 0 otherwise.

    "attr" is the IRQ number.  IRQ numbers for standard sources are the byte offset of the relevant IVPR from EIVPR0, divided by 32.

IRQ Routing:

> The MPIC emulation supports IRQ routing. Only a single MPIC device can be instantiated. Once that device has been created, it's available as irqchip id 0.
>
> This irqchip 0 has 256 interrupt pins, which expose the interrupts in the main array of interrupt sources (a.k.a. "SRC" interrupts).
>
> The numbering is the same as the MPIC device tree binding -- based on the register offset from the beginning of the sources array, without regard to any subdivisions in chip documentation such as "internal" or "external" interrupts.
>
> Access to non-SRC interrupts is not implemented through IRQ routing mechanisms.

---

# FLIC (floating interrupt controller)

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> FLIC handles floating (non per-cpu) interrupts, i.e. I/O, service and some machine check interruptions. All interrupts are stored in a per-vm list of pending interrupts. FLIC performs operations on this list.

<a id="rst-flic-floating-interrupt-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

FLIC handles floating (non per-cpu) interrupts, i.e. I/O, service and some machine check interruptions. All interrupts are stored in a per-vm list of pending interrupts. FLIC performs operations on this list.

Only one FLIC instance may be instantiated.

FLIC provides support to - add interrupts (KVM_DEV_FLIC_ENQUEUE) - inspect currently pending interrupts (KVM_FLIC_GET_ALL_IRQS) - purge all pending floating interrupts (KVM_DEV_FLIC_CLEAR_IRQS) - purge one pending floating I/O interrupt (KVM_DEV_FLIC_CLEAR_IO_IRQ) - enable/disable for the guest transparent async page faults - register and modify adapter interrupt sources (KVM_DEV_FLIC_ADAPTER\_\*) - modify AIS (adapter-interruption-suppression) mode state (KVM_DEV_FLIC_AISM) - inject adapter interrupts on a specified adapter (KVM_DEV_FLIC_AIRQ_INJECT) - get/set all AIS mode states (KVM_DEV_FLIC_AISM_ALL)

- **Groups:**

  - **KVM_DEV_FLIC_ENQUEUE**

    Passes a buffer and length into the kernel which are then injected into the list of pending interrupts. attr-&gt;addr contains the pointer to the buffer and attr-&gt;attr contains the length of the buffer. The format of the data structure kvm_s390_irq as it is copied from userspace is defined in usr/include/linux/kvm.h.

  - **KVM_DEV_FLIC_GET_ALL_IRQS**

    Copies all floating interrupts into a buffer provided by userspace. When the buffer is too small it returns -ENOMEM, which is the indication for userspace to try again with a bigger buffer.

    -ENOBUFS is returned when the allocation of a kernelspace buffer has failed.

    -EFAULT is returned when copying data to userspace failed. All interrupts remain pending, i.e. are not deleted from the list of currently pending interrupts. attr-&gt;addr contains the userspace address of the buffer into which all interrupt data will be copied. attr-&gt;attr contains the size of the buffer in bytes.

  - **KVM_DEV_FLIC_CLEAR_IRQS**

    Simply deletes all elements from the list of currently pending floating interrupts.  No interrupts are injected into the guest.

  - **KVM_DEV_FLIC_CLEAR_IO_IRQ**

    Deletes one (if any) I/O interrupt for a subchannel identified by the subsystem identification word passed via the buffer specified by attr-&gt;addr (address) and attr-&gt;attr (length).

  - **KVM_DEV_FLIC_APF_ENABLE**

    Enables async page faults for the guest. So in case of a major page fault the host is allowed to handle this async and continues the guest.

    -EINVAL is returned when called on the FLIC of a ucontrol VM.

  - **KVM_DEV_FLIC_APF_DISABLE_WAIT**

    Disables async page faults for the guest and waits until already pending async page faults are done. This is necessary to trigger a completion interrupt for every init interrupt before migrating the interrupt list.

    -EINVAL is returned when called on the FLIC of a ucontrol VM.

  - **KVM_DEV_FLIC_ADAPTER_REGISTER**

    > Register an I/O adapter interrupt source. Takes a kvm_s390_io_adapter describing the adapter to register:
    >
    >
    >
    > ```text
    > struct kvm_s390_io_adapter {
    >         __u32 id;
    >         __u8 isc;
    >         __u8 maskable;
    >         __u8 swap;
    >         __u8 flags;
    > };
    > ```

    id contains the unique id for the adapter, isc the I/O interruption subclass to use, maskable whether this adapter may be masked (interrupts turned off), swap whether the indicators need to be byte swapped, and flags contains further characteristics of the adapter.

    Currently defined values for 'flags' are:

    - KVM_S390_ADAPTER_SUPPRESSIBLE: adapter is subject to AIS (adapter-interrupt-suppression) facility. This flag only has an effect if the AIS capability is enabled.

    Unknown flag values are ignored.

  - **KVM_DEV_FLIC_ADAPTER_MODIFY**

    Modifies attributes of an existing I/O adapter interrupt source. Takes a kvm_s390_io_adapter_req specifying the adapter and the operation:



    ```text
    struct kvm_s390_io_adapter_req {
            __u32 id;
            __u8 type;
            __u8 mask;
            __u16 pad0;
            __u64 addr;
    };
    ```

    id specifies the adapter and type the operation. The supported operations are:

    - **KVM_S390_IO_ADAPTER_MASK**

      mask or unmask the adapter, as specified in mask

    - **KVM_S390_IO_ADAPTER_MAP**

      This is now a no-op. The mapping is purely done by the irq route.

    - **KVM_S390_IO_ADAPTER_UNMAP**

      This is now a no-op. The mapping is purely done by the irq route.

  - **KVM_DEV_FLIC_AISM**

    modify the adapter-interruption-suppression mode for a given isc if the AIS capability is enabled. Takes a kvm_s390_ais_req describing:



    ```text
    struct kvm_s390_ais_req {
            __u8 isc;
            __u16 mode;
    };
    ```

    isc contains the target I/O interruption subclass, mode the target adapter-interruption-suppression mode. The following modes are currently supported:

    - KVM_S390_AIS_MODE_ALL: ALL-Interruptions Mode, i.e. airq injection is always allowed;

    - KVM_S390_AIS_MODE_SINGLE: SINGLE-Interruption Mode, i.e. airq injection is only allowed once and the following adapter interrupts will be suppressed until the mode is set again to ALL-Interruptions or SINGLE-Interruption mode.

  - **KVM_DEV_FLIC_AIRQ_INJECT**

    Inject adapter interrupts on a specified adapter. attr-&gt;attr contains the unique id for the adapter, which allows for adapter-specific checks and actions. For adapters subject to AIS, handle the airq injection suppression for an isc according to the adapter-interruption-suppression mode on condition that the AIS capability is enabled.

  - **KVM_DEV_FLIC_AISM_ALL**

    Gets or sets the adapter-interruption-suppression mode for all ISCs. Takes a kvm_s390_ais_all describing:



    ```text
    struct kvm_s390_ais_all {
           __u8 simm; /* Single-Interruption-Mode mask */
           __u8 nimm; /* No-Interruption-Mode mask *
    };
    ```

    simm contains Single-Interruption-Mode mask for all ISCs, nimm contains No-Interruption-Mode mask for all ISCs. Each bit in simm and nimm corresponds to an ISC (MSB0 bit 0 to ISC 0 and so on). The combination of simm bit and nimm bit presents AIS mode for a ISC.

    KVM_DEV_FLIC_AISM_ALL is indicated by KVM_CAP_S390_AIS_MIGRATION.

Note: The KVM_SET_DEVICE_ATTR/KVM_GET_DEVICE_ATTR device ioctls executed on FLIC with an unknown group or attribute gives the error code EINVAL (instead of ENXIO, as specified in the API documentation). It is not possible to conclude that a FLIC operation is unavailable based on the error code resulting from a usage attempt.

> [!NOTE]
>
> The KVM_DEV_FLIC_CLEAR_IO_IRQ ioctl will return EINVAL in case a zero schid is specified.

---

# Generic vcpu interface

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> The virtual cpu "device" also accepts the ioctls KVM_SET_DEVICE_ATTR, KVM_GET_DEVICE_ATTR, and KVM_HAS_DEVICE_ATTR. The interface uses the same struct kvm_device_attr as other devices, but targets VCPU-wide settings and controls.

<a id="rst-generic-vcpu-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The virtual cpu "device" also accepts the ioctls KVM_SET_DEVICE_ATTR, KVM_GET_DEVICE_ATTR, and KVM_HAS_DEVICE_ATTR. The interface uses the same struct kvm_device_attr as other devices, but targets VCPU-wide settings and controls.

The groups and attributes per virtual cpu, if any, are architecture specific.

<a id="rst-group-kvm-arm-vcpu-pmu-v3-ctrl"></a>

## 1. GROUP: KVM_ARM_VCPU_PMU_V3_CTRL

**Architectures:** ARM64

<a id="rst-attribute-kvm-arm-vcpu-pmu-v3-irq"></a>

### 1.1. ATTRIBUTE: KVM_ARM_VCPU_PMU_V3_IRQ

**Parameters:** in kvm_device_attr.addr the address for PMU overflow interrupt is a pointer to an int

Returns:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -EBUSY
>
> </td>
> <td>
>
>
> The PMU overflow interrupt is already set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EFAULT
>
> </td>
> <td>
>
>
> Error reading interrupt number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ENXIO
>
> </td>
> <td>
>
>
> PMUv3 not supported or the overflow interrupt not set when attempting to get it
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ENODEV
>
> </td>
> <td>
>
>
> KVM_ARM_VCPU_PMU_V3 feature missing from VCPU
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EINVAL
>
> </td>
> <td>
>
>
> Invalid PMU overflow interrupt number supplied or trying to set the IRQ number without using an in-kernel irqchip.
>
> </td>
> </tr>
> </tbody>
> </table>

A value describing the PMUv3 (Performance Monitor Unit v3) overflow interrupt number for this vcpu. This interrupt could be a PPI or SPI, but the interrupt type must be same for each vcpu. As a PPI, the interrupt number is the same for all vcpus, while as an SPI it must be a separate number per vcpu.

<a id="rst-attribute-kvm-arm-vcpu-pmu-v3-init"></a>

### 1.2 ATTRIBUTE: KVM_ARM_VCPU_PMU_V3_INIT

**Parameters:** no additional parameter in kvm_device_attr.addr

Returns:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -EEXIST
>
> </td>
> <td>
>
>
> Interrupt number already used
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ENODEV
>
> </td>
> <td>
>
>
> PMUv3 not supported or GIC not initialized
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ENXIO
>
> </td>
> <td>
>
>
> PMUv3 not supported, missing VCPU feature or interrupt number not set
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EBUSY
>
> </td>
> <td>
>
>
> PMUv3 already initialized
>
> </td>
> </tr>
> </tbody>
> </table>

Request the initialization of the PMUv3.  If using the PMUv3 with an in-kernel virtual GIC implementation, this must be done after initializing the in-kernel irqchip.

<a id="rst-attribute-kvm-arm-vcpu-pmu-v3-filter"></a>

### 1.3 ATTRIBUTE: KVM_ARM_VCPU_PMU_V3_FILTER

**Parameters:** in kvm_device_attr.addr the address for a PMU event filter is a pointer to a struct kvm_pmu_event_filter

**Returns:** 
<table>
<tbody>
<tr>
<td>


-ENODEV

</td>
<td>


PMUv3 not supported or GIC not initialized

</td>
</tr>
<tr>
<td>


-ENXIO

</td>
<td>


PMUv3 not properly configured or in-kernel irqchip not configured as required prior to calling this attribute

</td>
</tr>
<tr>
<td>


-EBUSY

</td>
<td>


PMUv3 already initialized or a VCPU has already run

</td>
</tr>
<tr>
<td>


-EINVAL

</td>
<td>


Invalid filter range

</td>
</tr>
</tbody>
</table>

Request the installation of a PMU event filter described as follows:



```text
struct kvm_pmu_event_filter {
        __u16       base_event;
        __u16       nevents;

#define KVM_PMU_EVENT_ALLOW 0
#define KVM_PMU_EVENT_DENY  1

        __u8        action;
        __u8        pad[3];
};
```

A filter range is defined as the range \[@base_event, @base_event + @nevents), together with an @action (KVM_PMU_EVENT_ALLOW or KVM_PMU_EVENT_DENY). The first registered range defines the global policy (global ALLOW if the first @action is DENY, global DENY if the first @action is ALLOW). Multiple ranges can be programmed, and must fit within the event space defined by the PMU architecture (10 bits on ARMv8.0, 16 bits from ARMv8.1 onwards).

Note: "Cancelling" a filter by registering the opposite action for the same range doesn't change the default action. For example, installing an ALLOW filter for event range \[0:10) as the first filter and then applying a DENY action for the same range will leave the whole range as disabled.

Restrictions: Event 0 (SW_INCR) is never filtered, as it doesn't count a hardware event. Filtering event 0x1E (CHAIN) has no effect either, as it isn't strictly speaking an event. Filtering the cycle counter is possible using event 0x11 (CPU_CYCLES).

<a id="rst-attribute-kvm-arm-vcpu-pmu-v3-set-pmu"></a>

### 1.4 ATTRIBUTE: KVM_ARM_VCPU_PMU_V3_SET_PMU

**Parameters:** in kvm_device_attr.addr the address to an int representing the PMU identifier.

**Returns:** 
<table>
<tbody>
<tr>
<td>


-EBUSY

</td>
<td>


PMUv3 already initialized, a VCPU has already run or an event filter has already been set

</td>
</tr>
<tr>
<td>


-EFAULT

</td>
<td>


Error accessing the PMU identifier

</td>
</tr>
<tr>
<td>


-ENXIO

</td>
<td>


PMU not found

</td>
</tr>
<tr>
<td>


-ENODEV

</td>
<td>


PMUv3 not supported or GIC not initialized

</td>
</tr>
<tr>
<td>


-ENOMEM

</td>
<td>


Could not allocate memory

</td>
</tr>
</tbody>
</table>

Request that the VCPU uses the specified hardware PMU when creating guest events for the purpose of PMU emulation. The PMU identifier can be read from the "type" file for the desired PMU instance under /sys/devices (or, equivalent, /sys/bus/even_source). This attribute is particularly useful on heterogeneous systems where there are at least two CPU PMUs on the system. The PMU that is set for one VCPU will be used by all the other VCPUs. It isn't possible to set a PMU if a PMU event filter is already present.

Note that KVM will not make any attempts to run the VCPU on the physical CPUs associated with the PMU specified by this attribute. This is entirely left to userspace. However, attempting to run the VCPU on a physical CPU not supported by the PMU will fail and KVM_RUN will return with exit_reason = KVM_EXIT_FAIL_ENTRY and populate the fail_entry struct by setting hardare_entry_failure_reason field to KVM_EXIT_FAIL_ENTRY_CPU_UNSUPPORTED and the cpu field to the processor id.

<a id="rst-attribute-kvm-arm-vcpu-pmu-v3-set-nr-counters"></a>

### 1.5 ATTRIBUTE: KVM_ARM_VCPU_PMU_V3_SET_NR_COUNTERS

**Parameters:** in kvm_device_attr.addr the address to an unsigned int representing the maximum value taken by PMCR_EL0.N

**Returns:** 
<table>
<tbody>
<tr>
<td>


-EBUSY

</td>
<td>


PMUv3 already initialized, a VCPU has already run or an event filter has already been set

</td>
</tr>
<tr>
<td>


-EFAULT

</td>
<td>


Error accessing the value pointed to by addr

</td>
</tr>
<tr>
<td>


-ENODEV

</td>
<td>


PMUv3 not supported or GIC not initialized

</td>
</tr>
<tr>
<td>


-EINVAL

</td>
<td>


No PMUv3 explicitly selected, or value of N out of range

</td>
</tr>
</tbody>
</table>

Set the number of implemented event counters in the virtual PMU. This mandates that a PMU has explicitly been selected via KVM_ARM_VCPU_PMU_V3_SET_PMU, and will fail when no PMU has been explicitly selected, or the number of counters is out of range for the selected PMU. Selecting a new PMU cancels the effect of setting this attribute.

<a id="rst-group-kvm-arm-vcpu-timer-ctrl"></a>

## 2. GROUP: KVM_ARM_VCPU_TIMER_CTRL

**Architectures:** ARM64

<a id="rst-attributes-kvm-arm-vcpu-timer-irq-vtimer-ptimer-hvtimer-hptimer"></a>

### 2.1. ATTRIBUTES: KVM_ARM_VCPU_TIMER_IRQ\_\{VTIMER,PTIMER,HVTIMER,HPTIMER\}

**Parameters:** in kvm_device_attr.addr the address for the timer interrupt is a pointer to an int

Returns:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -EINVAL
>
> </td>
> <td>
>
>
> Invalid timer interrupt number
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EBUSY
>
> </td>
> <td>
>
>
> One or more VCPUs has already run
>
> </td>
> </tr>
> </tbody>
> </table>

A value describing the architected timer interrupt number when connected to an in-kernel virtual GIC.  These must be a PPI (16 &lt;= intid &lt; 32).  Setting the attribute overrides the default values (see below).


<table>
<tbody>
<tr>
<td>


KVM_ARM_VCPU_TIMER_IRQ_VTIMER

</td>
<td>


The EL1 virtual timer intid (default: 27)

</td>
</tr>
<tr>
<td>


KVM_ARM_VCPU_TIMER_IRQ_PTIMER

</td>
<td>


The EL1 physical timer intid (default: 30)

</td>
</tr>
<tr>
<td>


KVM_ARM_VCPU_TIMER_IRQ_HVTIMER

</td>
<td>


The EL2 virtual timer intid (default: 28)

</td>
</tr>
<tr>
<td>


KVM_ARM_VCPU_TIMER_IRQ_HPTIMER

</td>
<td>


The EL2 physical timer intid (default: 26)

</td>
</tr>
</tbody>
</table>

Setting the same PPI for different timers will prevent the VCPUs from running. Setting the interrupt number on a VCPU configures all VCPUs created at that time to use the number provided for a given timer, overwriting any previously configured values on other VCPUs.  Userspace should configure the interrupt numbers on at least one VCPU after creating all VCPUs and before running any VCPUs.

<a id="rst-group-kvm-arm-vcpu-pvtime-ctrl"></a>
<a id="rst-kvm-arm-vcpu-pvtime-ctrl"></a>

## 3. GROUP: KVM_ARM_VCPU_PVTIME_CTRL

**Architectures:** ARM64

<a id="rst-attribute-kvm-arm-vcpu-pvtime-ipa"></a>

### 3.1 ATTRIBUTE: KVM_ARM_VCPU_PVTIME_IPA

**Parameters:** 64-bit base address

Returns:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -ENXIO
>
> </td>
> <td>
>
>
> Stolen time not implemented
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EEXIST
>
> </td>
> <td>
>
>
> Base address already set for this VCPU
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -EINVAL
>
> </td>
> <td>
>
>
> Base address not 64 byte aligned
>
> </td>
> </tr>
> </tbody>
> </table>

Specifies the base address of the stolen time structure for this VCPU. The base address must be 64 byte aligned and exist within a valid guest memory region. See [Documentation/virt/kvm/arm/pvtime.rst](/kernel/internals/virt/kvm-arm/pvtime.md) for more information including the layout of the stolen time structure.

<a id="rst-group-kvm-vcpu-tsc-ctrl"></a>

## 4. GROUP: KVM_VCPU_TSC_CTRL

**Architectures:** x86

4.1 ATTRIBUTE: KVM_VCPU_TSC_OFFSET

**Parameters:** 64-bit unsigned TSC offset

Returns:

>
> <table>
> <tbody>
> <tr>
> <td>
>
>
> -EFAULT
>
> </td>
> <td>
>
>
> Error reading/writing the provided parameter address.
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -ENXIO
>
> </td>
> <td>
>
>
> Attribute not supported
>
> </td>
> </tr>
> </tbody>
> </table>

Specifies the guest's TSC offset relative to the host's TSC. The guest's TSC is then derived by the following equation:

> guest_tsc = host_tsc + KVM_VCPU_TSC_OFFSET

This attribute is useful to adjust the guest's TSC on live migration, so that the TSC counts the time during which the VM was paused. The following describes a possible algorithm to use for this purpose.

From the source VMM process:

1. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (tsc_src), kvmclock nanoseconds (guest_src), and host CLOCK_REALTIME nanoseconds (host_src).

2. Read the KVM_VCPU_TSC_OFFSET attribute for every vCPU to record the guest TSC offset (ofs_src\[i\]).

3. Invoke the KVM_GET_TSC_KHZ ioctl to record the frequency of the guest's TSC (freq).

From the destination VMM process:

4. Invoke the KVM_SET_CLOCK ioctl, providing the source nanoseconds from kvmclock (guest_src) and CLOCK_REALTIME (host_src) in their respective fields.  Ensure that the KVM_CLOCK_REALTIME flag is set in the provided structure.

   KVM will advance the VM's kvmclock to account for elapsed time since recording the clock values.  Note that this will cause problems in the guest (e.g., timeouts) unless CLOCK_REALTIME is synchronized between the source and destination, and a reasonably short time passes between the source pausing the VMs and the destination executing steps 4-7.

5. Invoke the KVM_GET_CLOCK ioctl to record the host TSC (tsc_dest) and kvmclock nanoseconds (guest_dest).

6. Adjust the guest TSC offsets for every vCPU to account for (1) time elapsed since recording state and (2) difference in TSCs between the source and destination machine:

   - **ofs_dst\[i\] = ofs_src\[i\] -**

     (guest_src - guest_dest) \* freq + (tsc_src - tsc_dest)

   ("ofs\[i\] + tsc - guest \* freq" is the guest TSC value corresponding to a time of 0 in kvmclock.  The above formula ensures that it is the same on the destination as it was on the source).

7. Write the KVM_VCPU_TSC_OFFSET attribute for every vCPU with the respective value derived in the previous step.

---

# VFIO virtual device

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Device types supported:

<a id="rst-vfio-virtual-device"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Device types supported:

> - KVM_DEV_TYPE_VFIO

Only one VFIO instance may be created per VM.  The created device tracks VFIO files (group or device) in use by the VM and features of those groups/devices important to the correctness and acceleration of the VM.  As groups/devices are enabled and disabled for use by the VM, KVM should be updated about their presence.  When registered with KVM, a reference to the VFIO file is held by KVM.

- **Groups:**

  - **KVM_DEV_VFIO_FILE**

    alias: KVM_DEV_VFIO_GROUP

- **KVM_DEV_VFIO_FILE attributes:**

  - **KVM_DEV_VFIO_FILE_ADD: Add a VFIO file (group/device) to VFIO-KVM device**

    tracking

    kvm_device_attr.addr points to an int32_t file descriptor for the VFIO file.

  - **KVM_DEV_VFIO_FILE_DEL: Remove a VFIO file (group/device) from VFIO-KVM**

    device tracking

    kvm_device_attr.addr points to an int32_t file descriptor for the VFIO file.

- **KVM_DEV_VFIO_GROUP (legacy kvm device group restricted to the handling of VFIO group fd):**

  KVM_DEV_VFIO_GROUP_ADD: same as KVM_DEV_VFIO_FILE_ADD for group fd only

  KVM_DEV_VFIO_GROUP_DEL: same as KVM_DEV_VFIO_FILE_DEL for group fd only

  - **KVM_DEV_VFIO_GROUP_SET_SPAPR_TCE: attaches a guest visible TCE table**

    allocated by sPAPR KVM. kvm_device_attr.addr points to a struct:



    ```text
    struct kvm_vfio_spapr_tce {
            __s32   groupfd;
            __s32   tablefd;
    };
    ```

    where:

    - @groupfd is a file descriptor for a VFIO group;

    - @tablefd is a file descriptor for a TCE table allocated via KVM_CREATE_SPAPR_TCE.

The FILE/GROUP_ADD operation above should be invoked prior to accessing the device file descriptor via VFIO_GROUP_GET_DEVICE_FD in order to support drivers which require a kvm pointer to be set in their .open_device() callback.  It is the same for device file descriptor via character device open which gets device access via VFIO_DEVICE_BIND_IOMMUFD.  For such file descriptors, FILE_ADD should be invoked before VFIO_DEVICE_BIND_IOMMUFD to support the drivers mentioned in prior sentence as well.

---

# Generic vm interface

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> The virtual machine "device" also accepts the ioctls KVM_SET_DEVICE_ATTR, KVM_GET_DEVICE_ATTR, and KVM_HAS_DEVICE_ATTR. The interface uses the same struct kvm_device_attr as other devices, but targets VM-wide settings and controls.

<a id="rst-generic-vm-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The virtual machine "device" also accepts the ioctls KVM_SET_DEVICE_ATTR, KVM_GET_DEVICE_ATTR, and KVM_HAS_DEVICE_ATTR. The interface uses the same struct kvm_device_attr as other devices, but targets VM-wide settings and controls.

The groups and attributes per virtual machine, if any, are architecture specific.

<a id="rst-group-kvm-s390-vm-mem-ctrl"></a>

## 1. GROUP: KVM_S390_VM_MEM_CTRL

**Architectures:** s390

<a id="rst-attribute-kvm-s390-vm-mem-enable-cmma"></a>

### 1.1. ATTRIBUTE: KVM_S390_VM_MEM_ENABLE_CMMA

**Parameters:** none

**Returns:** -EBUSY if a vcpu is already defined, otherwise 0

Enables Collaborative Memory Management Assist (CMMA) for the virtual machine.

<a id="rst-attribute-kvm-s390-vm-mem-clr-cmma"></a>

### 1.2. ATTRIBUTE: KVM_S390_VM_MEM_CLR_CMMA

**Parameters:** none

**Returns:** -EINVAL if CMMA was not enabled; 0 otherwise

Clear the CMMA status for all guest pages, so any pages the guest marked as unused are again used any may not be reclaimed by the host.

<a id="rst-attribute-kvm-s390-vm-mem-limit-size"></a>

### 1.3. ATTRIBUTE KVM_S390_VM_MEM_LIMIT_SIZE

**Parameters:** in attr-&gt;addr the address for the new limit of guest memory

**Returns:** -EFAULT if the given address is not accessible; -EINVAL if the virtual machine is of type UCONTROL; -E2BIG if the given guest memory is to big for that machine; -EBUSY if a vcpu is already defined; -ENOMEM if not enough memory is available for a new shadow guest mapping; 0 otherwise.

Allows userspace to query the actual limit and set a new limit for the maximum guest memory size. The limit will be rounded up to 2048 MB, 4096 GB, 8192 TB respectively, as this limit is governed by the number of page table levels. In the case that there is no limit we will set the limit to KVM_S390_NO_MEM_LIMIT (U64_MAX).

<a id="rst-group-kvm-s390-vm-cpu-model"></a>

## 2. GROUP: KVM_S390_VM_CPU_MODEL

**Architectures:** s390

<a id="rst-attribute-kvm-s390-vm-cpu-machine-r-o"></a>

### 2.1. ATTRIBUTE: KVM_S390_VM_CPU_MACHINE (r/o)

Allows user space to retrieve machine and kvm specific cpu related information:



```text
struct kvm_s390_vm_cpu_machine {
     __u64 cpuid;           # CPUID of host
     __u32 ibc;             # IBC level range offered by host
     __u8  pad[4];
     __u64 fac_mask[256];   # set of cpu facilities enabled by KVM
     __u64 fac_list[256];   # set of cpu facilities offered by host
}
```

**Parameters:** address of buffer to store the machine related cpu data of type struct kvm_s390_vm_cpu_machine\*

**Returns:** -EFAULT if the given address is not accessible from kernel space; -ENOMEM if not enough memory is available to process the ioctl; 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-cpu-processor-r-w"></a>

## 2.2. ATTRIBUTE: KVM_S390_VM_CPU_PROCESSOR (r/w)

Allows user space to retrieve or request to change cpu related information for a vcpu:



```text
struct kvm_s390_vm_cpu_processor {
     __u64 cpuid;           # CPUID currently (to be) used by this vcpu
     __u16 ibc;             # IBC level currently (to be) used by this vcpu
     __u8  pad[6];
     __u64 fac_list[256];   # set of cpu facilities currently (to be) used
                            # by this vcpu
}
```

KVM does not enforce or limit the cpu model data in any form. Take the information retrieved by means of KVM_S390_VM_CPU_MACHINE as hint for reasonable configuration setups. Instruction interceptions triggered by additionally set facility bits that are not handled by KVM need to by implemented in the VM driver code.

**Parameters:** address of buffer to store/set the processor related cpu data of type struct kvm_s390_vm_cpu_processor\*.

**Returns:** -EBUSY in case 1 or more vcpus are already activated (only in write case); -EFAULT if the given address is not accessible from kernel space; -ENOMEM if not enough memory is available to process the ioctl; 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-cpu-machine-feat-r-o"></a>
<a id="rst-kvm-s390-vm-cpu-machine-feat"></a>

### 2.3. ATTRIBUTE: KVM_S390_VM_CPU_MACHINE_FEAT (r/o)

Allows user space to retrieve available cpu features. A feature is available if provided by the hardware and supported by kvm. In theory, cpu features could even be completely emulated by kvm.



```text
struct kvm_s390_vm_cpu_feat {
      __u64 feat[16]; # Bitmap (1 = feature available), MSB 0 bit numbering
};
```

**Parameters:** address of a buffer to load the feature list from.

**Returns:** -EFAULT if the given address is not accessible from kernel space; 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-cpu-processor-feat-r-w"></a>

### 2.4. ATTRIBUTE: KVM_S390_VM_CPU_PROCESSOR_FEAT (r/w)

Allows user space to retrieve or change enabled cpu features for all VCPUs of a VM. Features that are not available cannot be enabled.

See [2.3. ATTRIBUTE: KVM_S390_VM_CPU_MACHINE_FEAT (r/o)](<#rst-kvm-s390-vm-cpu-machine-feat>) for a description of the parameter struct.

**Parameters:** address of a buffer to store/load the feature list from.

**Returns:** -EFAULT if the given address is not accessible from kernel space; -EINVAL if a cpu feature that is not available is to be enabled; -EBUSY if at least one VCPU has already been defined; 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-cpu-machine-subfunc-r-o"></a>
<a id="rst-kvm-s390-vm-cpu-machine-subfunc"></a>

### 2.5. ATTRIBUTE: KVM_S390_VM_CPU_MACHINE_SUBFUNC (r/o)

Allows user space to retrieve available cpu subfunctions without any filtering done by a set IBC. These subfunctions are indicated to the guest VCPU via query or "test bit" subfunctions and used e.g. by cpacf functions, plo and ptff.

A subfunction block is only valid if KVM_S390_VM_CPU_MACHINE contains the STFL(E) bit introducing the affected instruction. If the affected instruction indicates subfunctions via a "query subfunction", the response block is contained in the returned struct. If the affected instruction indicates subfunctions via a "test bit" mechanism, the subfunction codes are contained in the returned struct in MSB 0 bit numbering.



```text
struct kvm_s390_vm_cpu_subfunc {
     u8 plo[32];           # always valid (ESA/390 feature)
     u8 ptff[16];          # valid with TOD-clock steering
     u8 kmac[16];          # valid with Message-Security-Assist
     u8 kmc[16];           # valid with Message-Security-Assist
     u8 km[16];            # valid with Message-Security-Assist
     u8 kimd[16];          # valid with Message-Security-Assist
     u8 klmd[16];          # valid with Message-Security-Assist
     u8 pckmo[16];         # valid with Message-Security-Assist-Extension 3
     u8 kmctr[16];         # valid with Message-Security-Assist-Extension 4
     u8 kmf[16];           # valid with Message-Security-Assist-Extension 4
     u8 kmo[16];           # valid with Message-Security-Assist-Extension 4
     u8 pcc[16];           # valid with Message-Security-Assist-Extension 4
     u8 ppno[16];          # valid with Message-Security-Assist-Extension 5
     u8 kma[16];           # valid with Message-Security-Assist-Extension 8
     u8 kdsa[16];          # valid with Message-Security-Assist-Extension 9
     u8 reserved[1792];    # reserved for future instructions
};
```

**Parameters:** address of a buffer to load the subfunction blocks from.

**Returns:** -EFAULT if the given address is not accessible from kernel space; 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-cpu-processor-subfunc-r-w"></a>

### 2.6. ATTRIBUTE: KVM_S390_VM_CPU_PROCESSOR_SUBFUNC (r/w)

Allows user space to retrieve or change cpu subfunctions to be indicated for all VCPUs of a VM. This attribute will only be available if kernel and hardware support are in place.

The kernel uses the configured subfunction blocks for indication to the guest. A subfunction block will only be used if the associated STFL(E) bit has not been disabled by user space (so the instruction to be queried is actually available for the guest).

As long as no data has been written, a read will fail. The IBC will be used to determine available subfunctions in this case, this will guarantee backward compatibility.

See [2.5. ATTRIBUTE: KVM_S390_VM_CPU_MACHINE_SUBFUNC (r/o)](<#rst-kvm-s390-vm-cpu-machine-subfunc>) for a description of the parameter struct.

**Parameters:** address of a buffer to store/load the subfunction blocks from.

**Returns:** -EFAULT if the given address is not accessible from kernel space; -EINVAL when reading, if there was no write yet; -EBUSY if at least one VCPU has already been defined; 0 in case of success.

<a id="rst-group-kvm-s390-vm-tod"></a>

## 3. GROUP: KVM_S390_VM_TOD

**Architectures:** s390

<a id="rst-attribute-kvm-s390-vm-tod-high"></a>

### 3.1. ATTRIBUTE: KVM_S390_VM_TOD_HIGH

Allows user space to set/get the TOD clock extension (u8) (superseded by KVM_S390_VM_TOD_EXT).

**Parameters:** address of a buffer in user space to store the data (u8) to

**Returns:** -EFAULT if the given address is not accessible from kernel space; -EINVAL if setting the TOD clock extension to \!= 0 is not supported -EOPNOTSUPP for a PV guest (TOD managed by the ultravisor)

<a id="rst-attribute-kvm-s390-vm-tod-low"></a>

### 3.2. ATTRIBUTE: KVM_S390_VM_TOD_LOW

Allows user space to set/get bits 0-63 of the TOD clock register as defined in the POP (u64).

**Parameters:** address of a buffer in user space to store the data (u64) to

**Returns:** -EFAULT if the given address is not accessible from kernel space -EOPNOTSUPP for a PV guest (TOD managed by the ultravisor)

<a id="rst-attribute-kvm-s390-vm-tod-ext"></a>

### 3.3. ATTRIBUTE: KVM_S390_VM_TOD_EXT

Allows user space to set/get bits 0-63 of the TOD clock register as defined in the POP (u64). If the guest CPU model supports the TOD clock extension (u8), it also allows user space to get/set it. If the guest CPU model does not support it, it is stored as 0 and not allowed to be set to a value \!= 0.

**Parameters:** address of a buffer in user space to store the data (kvm_s390_vm_tod_clock) to

**Returns:** -EFAULT if the given address is not accessible from kernel space; -EINVAL if setting the TOD clock extension to \!= 0 is not supported -EOPNOTSUPP for a PV guest (TOD managed by the ultravisor)

<a id="rst-group-kvm-s390-vm-crypto"></a>

## 4. GROUP: KVM_S390_VM_CRYPTO

**Architectures:** s390

<a id="rst-attribute-kvm-s390-vm-crypto-enable-aes-kw-w-o"></a>

### 4.1. ATTRIBUTE: KVM_S390_VM_CRYPTO_ENABLE_AES_KW (w/o)

Allows user space to enable aes key wrapping, including generating a new wrapping key.

**Parameters:** none

**Returns:** 0

<a id="rst-attribute-kvm-s390-vm-crypto-enable-dea-kw-w-o"></a>

### 4.2. ATTRIBUTE: KVM_S390_VM_CRYPTO_ENABLE_DEA_KW (w/o)

Allows user space to enable dea key wrapping, including generating a new wrapping key.

**Parameters:** none

**Returns:** 0

<a id="rst-attribute-kvm-s390-vm-crypto-disable-aes-kw-w-o"></a>

### 4.3. ATTRIBUTE: KVM_S390_VM_CRYPTO_DISABLE_AES_KW (w/o)

Allows user space to disable aes key wrapping, clearing the wrapping key.

**Parameters:** none

**Returns:** 0

<a id="rst-attribute-kvm-s390-vm-crypto-disable-dea-kw-w-o"></a>

### 4.4. ATTRIBUTE: KVM_S390_VM_CRYPTO_DISABLE_DEA_KW (w/o)

Allows user space to disable dea key wrapping, clearing the wrapping key.

**Parameters:** none

**Returns:** 0

<a id="rst-group-kvm-s390-vm-migration"></a>

## 5. GROUP: KVM_S390_VM_MIGRATION

**Architectures:** s390

<a id="rst-attribute-kvm-s390-vm-migration-stop-w-o"></a>

### 5.1. ATTRIBUTE: KVM_S390_VM_MIGRATION_STOP (w/o)

Allows userspace to stop migration mode, needed for PGSTE migration. Setting this attribute when migration mode is not active will have no effects.

**Parameters:** none

**Returns:** 0

<a id="rst-attribute-kvm-s390-vm-migration-start-w-o"></a>

### 5.2. ATTRIBUTE: KVM_S390_VM_MIGRATION_START (w/o)

Allows userspace to start migration mode, needed for PGSTE migration. Setting this attribute when migration mode is already active will have no effects.

Dirty tracking must be enabled on all memslots, else -EINVAL is returned. When dirty tracking is disabled on any memslot, migration mode is automatically stopped.

**Parameters:** none

**Returns:** -ENOMEM if there is not enough free memory to start migration mode; -EINVAL if the state of the VM is invalid (e.g. no memory defined); 0 in case of success.

<a id="rst-attribute-kvm-s390-vm-migration-status-r-o"></a>

### 5.3. ATTRIBUTE: KVM_S390_VM_MIGRATION_STATUS (r/o)

Allows userspace to query the status of migration mode.

**Parameters:** address of a buffer in user space to store the data (u64) to; the data itself is either 0 if migration mode is disabled or 1 if it is enabled

**Returns:** -EFAULT if the given address is not accessible from kernel space; 0 in case of success.

<a id="rst-group-kvm-arm-vm-smccc-ctrl"></a>

## 6. GROUP: KVM_ARM_VM_SMCCC_CTRL

**Architectures:** arm64

<a id="rst-attribute-kvm-arm-vm-smccc-filter-w-o"></a>

### 6.1. ATTRIBUTE: KVM_ARM_VM_SMCCC_FILTER (w/o)

**Parameters:** Pointer to a `struct kvm_smccc_filter`

**Returns:** 
<table>
<tbody>
<tr>
<td>


EEXIST

</td>
<td>


Range intersects with a previously inserted or reserved range

</td>
</tr>
<tr>
<td>


EBUSY

</td>
<td>


A vCPU in the VM has already run

</td>
</tr>
<tr>
<td>


EINVAL

</td>
<td>


Invalid filter configuration

</td>
</tr>
<tr>
<td>


ENOMEM

</td>
<td>


Failed to allocate memory for the in-kernel representation of the SMCCC filter

</td>
</tr>
</tbody>
</table>

Requests the installation of an SMCCC call filter described as follows:



```text
enum kvm_smccc_filter_action {
        KVM_SMCCC_FILTER_HANDLE = 0,
        KVM_SMCCC_FILTER_DENY,
        KVM_SMCCC_FILTER_FWD_TO_USER,
};

struct kvm_smccc_filter {
        __u32 base;
        __u32 nr_functions;
        __u8 action;
        __u8 pad[15];
};
```

The filter is defined as a set of non-overlapping ranges. Each range defines an action to be applied to SMCCC calls within the range. Userspace can insert multiple ranges into the filter by using successive calls to this attribute.

The default configuration of KVM is such that all implemented SMCCC calls are allowed. Thus, the SMCCC filter can be defined sparsely by userspace, only describing ranges that modify the default behavior.

The range expressed by `struct kvm_smccc_filter` is \[`base`, `base + nr_functions`). The range is not allowed to wrap, i.e. userspace cannot rely on `base + nr_functions` overflowing.

The SMCCC filter applies to both SMC and HVC calls initiated by the guest. The SMCCC filter gates the in-kernel emulation of SMCCC calls and as such takes effect before other interfaces that interact with SMCCC calls (e.g. hypercall bitmap registers).

Actions:

> - `KVM_SMCCC_FILTER_HANDLE`: Allows the guest SMCCC call to be handled in-kernel. It is strongly recommended that userspace *not* explicitly describe the allowed SMCCC call ranges.
>
> - `KVM_SMCCC_FILTER_DENY`: Rejects the guest SMCCC call in-kernel and returns to the guest.
>
> - `KVM_SMCCC_FILTER_FWD_TO_USER`: The guest SMCCC call is forwarded to userspace with an exit reason of `KVM_EXIT_HYPERCALL`.

The `pad` field is reserved for future use and must be zero. KVM may return `-EINVAL` if the field is nonzero.

KVM reserves the 'Arm Architecture Calls' range of function IDs and will reject attempts to define a filter for any portion of these ranges:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Start
>
> </th>
> <th>
>
>
> End (inclusive)
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0x8000_0000
>
> </td>
> <td>
>
>
> 0x8000_FFFF
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> 0xC000_0000
>
> </td>
> <td>
>
>
> 0xC000_FFFF
>
> </td>
> </tr>
> </tbody>
> </table>

---

# XICS interrupt controller

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Device type supported: KVM_DEV_TYPE_XICS

<a id="rst-xics-interrupt-controller"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Device type supported: KVM_DEV_TYPE_XICS

- **Groups:**

  1. - **KVM_DEV_XICS_GRP_SOURCES**

       Attributes:

       > One per interrupt source, indexed by the source number.

  2. - **KVM_DEV_XICS_GRP_CTRL**

       Attributes:

       > 2.1 KVM_DEV_XICS_NR_SERVERS (write only)

  The kvm_device_attr.addr points to a \__u32 value which is the number of interrupt server numbers (ie, highest possible vcpu id plus one).

  Errors:

  >
  > <table>
  > <tbody>
  > <tr>
  > <td>
  >
  >
  > -EINVAL
  >
  > </td>
  > <td>
  >
  >
  > Value greater than KVM_MAX_VCPU_IDS.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EFAULT
  >
  > </td>
  > <td>
  >
  >
  > Invalid user pointer for attr-&gt;addr.
  >
  > </td>
  > </tr>
  > <tr>
  > <td>
  >
  >
  > -EBUSY
  >
  > </td>
  > <td>
  >
  >
  > A vcpu is already connected to the device.
  >
  > </td>
  > </tr>
  > </tbody>
  > </table>

This device emulates the XICS (eXternal Interrupt Controller Specification) defined in PAPR.  The XICS has a set of interrupt sources, each identified by a 20-bit source number, and a set of Interrupt Control Presentation (ICP) entities, also called "servers", each associated with a virtual CPU.

The ICP entities are created by enabling the KVM_CAP_IRQ_ARCH capability for each vcpu, specifying KVM_CAP_IRQ_XICS in args\[0\] and the interrupt server number (i.e. the vcpu number from the XICS's point of view) in args\[1\] of the kvm_enable_cap struct.  Each ICP has 64 bits of state which can be read and written using the KVM_GET_ONE_REG and KVM_SET_ONE_REG ioctls on the vcpu.  The 64 bit state word has the following bitfields, starting at the least-significant end of the word:

- Unused, 16 bits

- Pending interrupt priority, 8 bits Zero is the highest priority, 255 means no interrupt is pending.

- Pending IPI (inter-processor interrupt) priority, 8 bits Zero is the highest priority, 255 means no IPI is pending.

- Pending interrupt source number, 24 bits Zero means no interrupt pending, 2 means an IPI is pending

- Current processor priority, 8 bits Zero is the highest priority, meaning no interrupts can be delivered, and 255 is the lowest priority.

Each source has 64 bits of state that can be read and written using the KVM_GET_DEVICE_ATTR and KVM_SET_DEVICE_ATTR ioctls, specifying the KVM_DEV_XICS_GRP_SOURCES attribute group, with the attribute number being the interrupt source number.  The 64 bit state word has the following bitfields, starting from the least-significant end of the word:

- Destination (server number), 32 bits

  This specifies where the interrupt should be sent, and is the interrupt server number specified for the destination vcpu.

- Priority, 8 bits

  This is the priority specified for this interrupt source, where 0 is the highest priority and 255 is the lowest.  An interrupt with a priority of 255 will never be delivered.

- Level sensitive flag, 1 bit

  This bit is 1 for a level-sensitive interrupt source, or 0 for edge-sensitive (or MSI).

- Masked flag, 1 bit

  This bit is set to 1 if the interrupt is masked (cannot be delivered regardless of its priority), for example by the ibm,int-off RTAS call, or 0 if it is not masked.

- Pending flag, 1 bit

  This bit is 1 if the source has a pending interrupt, otherwise 0.

Only one XICS instance may be created per VM.

---

# POWER9 eXternal Interrupt Virtualization Engine (XIVE Gen1)

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> KVM_DEV_TYPE_XIVE POWER9 XIVE Interrupt Controller generation 1

<a id="rst-power9-external-interrupt-virtualization-engine-xive-gen1"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **Device types supported:**

  - KVM\_DEV\_TYPE\_XIVE     POWER9 XIVE Interrupt Controller generation 1

This device acts as a VM interrupt controller. It provides the KVM interface to configure the interrupt sources of a VM in the underlying POWER9 XIVE interrupt controller.

Only one XIVE instance may be instantiated. A guest XIVE device requires a POWER9 host and the guest OS should have support for the XIVE native exploitation interrupt mode. If not, it should run using the legacy interrupt mode, referred as XICS (POWER7/8).

- Device Mappings

  The KVM device exposes different MMIO ranges of the XIVE HW which are required for interrupt management. These are exposed to the guest in VMAs populated with a custom VM fault handler.

  1. Thread Interrupt Management Area (TIMA)

  Each thread has an associated Thread Interrupt Management context composed of a set of registers. These registers let the thread handle priority management and interrupt acknowledgment. The most important are :

  > - Interrupt Pending Buffer     (IPB)
  >
  > - Current Processor Priority   (CPPR)
  >
  > - Notification Source Register (NSR)

  They are exposed to software in four different pages each proposing a view with a different privilege. The first page is for the physical thread context and the second for the hypervisor. Only the third (operating system) and the fourth (user level) are exposed the guest.

  2. Event State Buffer (ESB)

  Each source is associated with an Event State Buffer (ESB) with either a pair of even/odd pair of pages which provides commands to manage the source: to trigger, to EOI, to turn off the source for instance.

  3. Device pass-through

  When a device is passed-through into the guest, the source interrupts are from a different HW controller (PHB4) and the ESB pages exposed to the guest should accommodate this change.

  The passthru\_irq helpers, kvmppc\_xive\_set\_mapped() and kvmppc\_xive\_clr\_mapped() are called when the device HW irqs are mapped into or unmapped from the guest IRQ number space. The KVM device extends these helpers to clear the ESB pages of the guest IRQ number being mapped and then lets the VM fault handler repopulate. The handler will insert the ESB page corresponding to the HW interrupt of the device being passed-through or the initial IPI ESB page if the device has being removed.

  The ESB remapping is fully transparent to the guest and the OS device driver. All handling is done within VFIO and the above helpers in KVM-PPC.

- Groups:

1. - **KVM\_DEV\_XIVE\_GRP\_CTRL**

     Provides global controls on the device

> - **Attributes:**
>
>   1.1 KVM\_DEV\_XIVE\_RESET (write only) Resets the interrupt controller configuration for sources and event queues. To be used by kexec and kdump.
>
>   Errors: none
>
>   1.2 KVM\_DEV\_XIVE\_EQ\_SYNC (write only) Sync all the sources and queues and mark the EQ pages dirty. This to make sure that a consistent memory state is captured when migrating the VM.
>
>   Errors: none
>
>   1.3 KVM\_DEV\_XIVE\_NR\_SERVERS (write only) The kvm\_device\_attr.addr points to a \_\_u32 value which is the number of interrupt server numbers (ie, highest possible vcpu id plus one).
>
>   Errors:
>
>   >
>   > <table>
>   > <tbody>
>   > <tr>
>   > <td>
>   >
>   >
>   > -EINVAL
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Value greater than KVM\_MAX\_VCPU\_IDS.
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > -EFAULT
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > Invalid user pointer for attr-&gt;addr.
>   >
>   > </td>
>   > </tr>
>   > <tr>
>   > <td>
>   >
>   >
>   > -EBUSY
>   >
>   > </td>
>   > <td>
>   >
>   >
>   > A vCPU is already connected to the device.
>   >
>   > </td>
>   > </tr>
>   > </tbody>
>   > </table>

2. - **KVM\_DEV\_XIVE\_GRP\_SOURCE (write only)**

     Initializes a new source in the XIVE device and mask it.

> - **Attributes:**
>
>   Interrupt source number  (64-bit)
>
> The kvm\_device\_attr.addr points to a \_\_u64 value:
>
>
>
> ```text
> bits:     | 63   ....  2 |   1   |   0
> values:   |    unused    | level | type
> ```
>
> - type:  0:MSI 1:LSI
>
> - level: assertion level in case of an LSI.
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -E2BIG
> >
> > </td>
> > <td>
> >
> >
> > Interrupt source number is out of range
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -ENOMEM
> >
> > </td>
> > <td>
> >
> >
> > Could not create a new source block
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid user pointer for attr-&gt;addr.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -ENXIO
> >
> > </td>
> > <td>
> >
> >
> > Could not allocate underlying HW interrupt
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

3. - **KVM\_DEV\_XIVE\_GRP\_SOURCE\_CONFIG (write only)**

     Configures source targeting

> - **Attributes:**
>
>   Interrupt source number  (64-bit)
>
> The kvm\_device\_attr.addr points to a \_\_u64 value:
>
>
>
> ```text
> bits:     | 63   ....  33 |  32  | 31 .. 3 |  2 .. 0
> values:   |    eisn       | mask |  server | priority
> ```
>
> - priority: 0-7 interrupt priority level
>
> - server: CPU number chosen to handle the interrupt
>
> - mask: mask flag (unused)
>
> - eisn: Effective Interrupt Source Number
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -ENOENT
> >
> > </td>
> > <td>
> >
> >
> > Unknown source number
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Not initialized source number
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid priority
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid CPU number.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid user pointer for attr-&gt;addr.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -ENXIO
> >
> > </td>
> > <td>
> >
> >
> > CPU event queues not configured or configuration of the underlying HW interrupt failed
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EBUSY
> >
> > </td>
> > <td>
> >
> >
> > No CPU available to serve interrupt
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

4. - **KVM\_DEV\_XIVE\_GRP\_EQ\_CONFIG (read-write)**

     Configures an event queue of a CPU

> - **Attributes:**
>
>   EQ descriptor identifier (64-bit)
>
> The EQ descriptor identifier is a tuple (server, priority):
>
>
>
> ```text
> bits:     | 63   ....  32 | 31 .. 3 |  2 .. 0
> values:   |    unused     |  server | priority
> ```
>
> The kvm\_device\_attr.addr points to:
>
>
>
> ```text
> struct kvm_ppc_xive_eq {
>     __u32 flags;
>     __u32 qshift;
>     __u64 qaddr;
>     __u32 qtoggle;
>     __u32 qindex;
>     __u8  pad[40];
> };
> ```
>
> - - **flags: queue flags**
>
>     - **KVM\_XIVE\_EQ\_ALWAYS\_NOTIFY (required)**
>
>       forces notification without using the coalescing mechanism provided by the XIVE END ESBs.
>
> - qshift: queue size (power of 2)
>
> - qaddr: real address of queue
>
> - qtoggle: current queue toggle bit
>
> - qindex: current queue index
>
> - pad: reserved for future use
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -ENOENT
> >
> > </td>
> > <td>
> >
> >
> > Invalid CPU number
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid priority
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid flags
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid queue size
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Invalid queue address
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EFAULT
> >
> > </td>
> > <td>
> >
> >
> > Invalid user pointer for attr-&gt;addr.
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EIO
> >
> > </td>
> > <td>
> >
> >
> > Configuration of the underlying HW failed
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

5. - **KVM\_DEV\_XIVE\_GRP\_SOURCE\_SYNC (write only)**

     Synchronize the source to flush event notifications

> - **Attributes:**
>
>   Interrupt source number  (64-bit)
>
> Errors:
>
> >
> > <table>
> > <tbody>
> > <tr>
> > <td>
> >
> >
> > -ENOENT
> >
> > </td>
> > <td>
> >
> >
> > Unknown source number
> >
> > </td>
> > </tr>
> > <tr>
> > <td>
> >
> >
> > -EINVAL
> >
> > </td>
> > <td>
> >
> >
> > Not initialized source number
> >
> > </td>
> > </tr>
> > </tbody>
> > </table>

- VCPU state

  The XIVE IC maintains VP interrupt state in an internal structure called the NVT. When a VP is not dispatched on a HW processor thread, this structure can be updated by HW if the VP is the target of an event notification.

  It is important for migration to capture the cached IPB from the NVT as it synthesizes the priorities of the pending interrupts. We capture a bit more to report debug information.

  KVM\_REG\_PPC\_VP\_STATE (2 \* 64bits):



  ```text
  bits:     |  63  ....  32  |  31  ....  0  |
  values:   |   TIMA word0   |   TIMA word1  |
  bits:     | 127       ..........       64  |
  values:   |            unused              |
  ```

- Migration:

  Saving the state of a VM using the XIVE native exploitation mode should follow a specific sequence. When the VM is stopped :

  1. Mask all sources (PQ=01) to stop the flow of events.

  2\. Sync the XIVE device with the KVM control KVM\_DEV\_XIVE\_EQ\_SYNC to flush any in-flight event notification and to stabilize the EQs. At this stage, the EQ pages are marked dirty to make sure they are transferred in the migration sequence.

  3\. Capture the state of the source targeting, the EQs configuration and the state of thread interrupt context registers.

  Restore is similar:

  1. Restore the EQ configuration. As targeting depends on it.

  2. Restore targeting

  3. Restore the thread interrupt contexts

  4. Restore the source states

  5. Let the vCPU run

---

# KVM device bindings

_Peios Kernel / Internals / Virtualisation / kvm / devices_

> Kernel reference: KVM device bindings.

This directory contains specific device bindings for KVM\_CAP\_DEVICE\_CTRL.

---

# KVM for LoongArch systems

_Peios Kernel / Internals / Virtualisation / kvm / loongarch_

> Reference for KVM for LoongArch systems.

<a id="rst-kvm-for-loongarch-systems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [The LoongArch paravirtual interface](</kernel/internals/virt/kvm-loongarch/hypercalls.md>)

---

# The LoongArch paravirtual interface

_Peios Kernel / Internals / Virtualisation / kvm / loongarch_

> KVM hypercalls use the HVCL instruction with code 0x100 and the hypercall number is put in a0. Up to five arguments may be placed in registers a1 - a5. The return value is placed in v0 (an alias of a0).

<a id="rst-the-loongarch-paravirtual-interface"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

KVM hypercalls use the HVCL instruction with code 0x100 and the hypercall number is put in a0. Up to five arguments may be placed in registers a1 - a5. The return value is placed in v0 (an alias of a0).

Source code for this interface can be found in arch/loongarch/kvm\*.

<a id="rst-querying-for-existence"></a>

## Querying for existence

To determine if the host is running on KVM, we can utilize the cpucfg() function at index CPUCFG_KVM_BASE (0x40000000).

The CPUCFG_KVM_BASE range, spanning from 0x40000000 to 0x400000FF, The CPUCFG_KVM_BASE range between 0x40000000 - 0x400000FF is marked as reserved. Consequently, all current and future processors will not implement any feature within this range.

On a KVM-virtualized Linux system, a read operation on cpucfg() at index CPUCFG_KVM_BASE (0x40000000) returns the magic string 'KVM0'.

Once you have determined that your host is running on a paravirtualization- capable KVM, you may now use hypercalls as described below.

<a id="rst-kvm-hypercall-abi"></a>

## KVM hypercall ABI

The KVM hypercall ABI is simple, with one scratch register a0 (v0) and at most five generic registers (a1 - a5) used as input parameters. The FP (Floating- point) and vector registers are not utilized as input registers and must remain unmodified during a hypercall.

Hypercall functions can be inlined as it only uses one scratch register.

The parameters are as follows:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Register
>
> </th>
> <th>
>
>
> IN
>
> </th>
> <th>
>
>
> OUT
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> a0
>
> </td>
> <td>
>
>
> function number
>
> </td>
> <td>
>
>
> Return  code
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> a1
>
> </td>
> <td>
>
>
> 1st     parameter
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> a2
>
> </td>
> <td>
>
>
> 2nd     parameter
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> a3
>
> </td>
> <td>
>
>
> 3rd     parameter
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> a4
>
> </td>
> <td>
>
>
> 4th     parameter
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> a5
>
> </td>
> <td>
>
>
> 5th     parameter
>
> </td>
> <td>
>
>
> - <!-- empty source list item -->
>
> </td>
> </tr>
> </tbody>
> </table>

The return codes may be one of the following:

>
> <table>
> <thead>
> <tr>
> <th>
>
>
> Code
>
> </th>
> <th>
>
>
> Meaning
>
> </th>
> </tr>
> </thead>
> <tbody>
> <tr>
> <td>
>
>
> 0
>
> </td>
> <td>
>
>
> Success
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -1
>
> </td>
> <td>
>
>
> Hypercall not implemented
>
> </td>
> </tr>
> <tr>
> <td>
>
>
> -2
>
> </td>
> <td>
>
>
> Bad Hypercall parameter
>
> </td>
> </tr>
> </tbody>
> </table>

<a id="rst-kvm-hypercalls-documentation"></a>

## KVM Hypercalls Documentation

The template for each hypercall is as follows:

1. Hypercall name

2. Purpose

<a id="rst-kvm-hcall-func-ipi"></a>

### 1. KVM_HCALL_FUNC_IPI

**Purpose:** Send IPIs to multiple vCPUs.

- a0: KVM_HCALL_FUNC_IPI

- a1: Lower part of the bitmap for destination physical CPUIDs

- a2: Higher part of the bitmap for destination physical CPUIDs

- a3: The lowest physical CPUID in the bitmap

The hypercall lets a guest send multiple IPIs (Inter-Process Interrupts) with at most 128 destinations per hypercall. The destinations are represented in a bitmap contained in the first two input registers (a1 and a2).

Bit 0 of a1 corresponds to the physical CPUID in the third input register (a3) and bit 1 corresponds to the physical CPUID in a3+1, and so on.

PV IPI on LoongArch includes both PV IPI multicast sending and PV IPI receiving, and SWI is used for PV IPI inject since there is no VM-exits accessing SWI registers.

---

# KVM for s390 systems

_Peios Kernel / Internals / Virtualisation / kvm / s390_

> Reference for KVM for s390 systems.

<a id="rst-kvm-for-s390-systems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [The s390 DIAGNOSE call on KVM](</kernel/internals/virt/kvm-s390/s390-diag.md>)
- [s390 (IBM Z) Ultravisor and Protected VMs](</kernel/internals/virt/kvm-s390/s390-pv.md>)
- [s390 (IBM Z) Boot/IPL of Protected VMs](</kernel/internals/virt/kvm-s390/s390-pv-boot.md>)
- [s390 (IBM Z) Protected Virtualization dumps](</kernel/internals/virt/kvm-s390/s390-pv-dump.md>)

---

# The s390 DIAGNOSE call on KVM

_Peios Kernel / Internals / Virtualisation / kvm / s390_

> KVM on s390 supports the DIAGNOSE call for making hypercalls, both for native hypercalls and for selected hypercalls found on other s390 hypervisors.

<a id="rst-the-s390-diagnose-call-on-kvm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

KVM on s390 supports the DIAGNOSE call for making hypercalls, both for native hypercalls and for selected hypercalls found on other s390 hypervisors.

Note that bits are numbered as by the usual s390 convention (most significant bit on the left).

<a id="rst-general-remarks"></a>

## General remarks

DIAGNOSE calls by the guest cause a mandatory intercept. This implies all supported DIAGNOSE calls need to be handled by either KVM or its userspace.

All DIAGNOSE calls supported by KVM use the RS-a format:



```text
--------------------------------------
|  '83'  | R1 | R3 | B2 |     D2     |
--------------------------------------
0        8    12   16   20           31
```

The second-operand address (obtained by the base/displacement calculation) is not used to address data. Instead, bits 48-63 of this address specify the function code, and bits 0-47 are ignored.

The supported DIAGNOSE function codes vary by the userspace used. For DIAGNOSE function codes not specific to KVM, please refer to the documentation for the s390 hypervisors defining them.

<a id="rst-diagnose-function-code-x-500-kvm-functions"></a>

## DIAGNOSE function code 'X'500' - KVM functions

If the function code specifies 0x500, various KVM-specific functions are performed, including virtio functions.

General register 1 contains the subfunction code. Supported subfunctions depend on KVM's userspace. Regarding virtio subfunctions, generally userspace provides either s390-virtio (subcodes 0-2) or virtio-ccw (subcode 3).

Upon completion of the DIAGNOSE instruction, general register 2 contains the function's return code, which is either a return code or a subcode specific value.

If the specified subfunction is not supported, a SPECIFICATION exception will be triggered.

- **Subcode 0 - s390-virtio notification and early console printk**

  Handled by userspace.

- **Subcode 1 - s390-virtio reset**

  Handled by userspace.

- **Subcode 2 - s390-virtio set status**

  Handled by userspace.

- **Subcode 3 - virtio-ccw notification**

  Handled by either userspace or KVM (ioeventfd case).

  General register 2 contains a subchannel-identification word denoting the subchannel of the virtio-ccw proxy device to be notified.

  General register 3 contains the number of the virtqueue to be notified.

  General register 4 contains a 64bit identifier for KVM usage (the kvm_io_bus cookie). If general register 4 does not contain a valid identifier, it is ignored.

  After completion of the DIAGNOSE call, general register 2 may contain a 64bit identifier (in the kvm_io_bus cookie case), or a negative error value, if an internal error occurred.

  See also the virtio standard for a discussion of this hypercall.

- **Subcode 4 - storage-limit**

  Handled by userspace.

  After completion of the DIAGNOSE call, general register 2 will contain the storage limit: the maximum physical address that might be used for storage throughout the lifetime of the VM.

  The storage limit does not indicate currently usable storage, it may include holes, standby storage and areas reserved for other means, such as memory hotplug or virtio-mem devices. Other interfaces for detecting actually usable storage, such as SCLP, must be used in conjunction with this subfunction.

  Note that the storage limit can be larger, but never smaller than the maximum storage address indicated by SCLP via the "maximum storage increment" and the "increment size".

<a id="rst-diagnose-function-code-x-501-kvm-breakpoint"></a>

## DIAGNOSE function code 'X'501 - KVM breakpoint

If the function code specifies 0x501, breakpoint functions may be performed. This function code is handled by userspace.

This diagnose function code has no subfunctions and uses no parameters.

<a id="rst-diagnose-function-code-x-9c-voluntary-time-slice-yield"></a>

## DIAGNOSE function code 'X'9C - Voluntary Time Slice Yield

General register 1 contains the target CPU address.

In a guest of a hypervisor like LPAR, KVM or z/VM using shared host CPUs, DIAGNOSE with function code 0x9c may improve system performance by yielding the host CPU on which the guest CPU is running to be assigned to another guest CPU, preferably the logical CPU containing the specified target CPU.

<a id="rst-diag-x-9c-forwarding"></a>

### DIAG 'X'9C forwarding

The guest may send a DIAGNOSE 0x9c in order to yield to a certain other vcpu. An example is a Linux guest that tries to yield to the vcpu that is currently holding a spinlock, but not running.

However, on the host the real cpu backing the vcpu may itself not be running. Forwarding the DIAGNOSE 0x9c initially sent by the guest to yield to the backing cpu will hopefully cause that cpu, and thus subsequently the guest's vcpu, to be scheduled.

- **diag9c_forwarding_hz**

  KVM kernel parameter allowing to specify the maximum number of DIAGNOSE 0x9c forwarding per second in the purpose of avoiding a DIAGNOSE 0x9c forwarding storm. A value of 0 turns the forwarding off.

---

# s390 (IBM Z) Boot/IPL of Protected VMs

_Peios Kernel / Internals / Virtualisation / kvm / s390_

> The memory of Protected Virtual Machines (PVMs) is not accessible to I/O or the hypervisor. In those cases where the hypervisor needs to access the memory of a PVM, that memory must be made accessible. Memory made accessible to the…

<a id="rst-s390-ibm-z-boot-ipl-of-protected-vms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>

## Summary

The memory of Protected Virtual Machines (PVMs) is not accessible to I/O or the hypervisor. In those cases where the hypervisor needs to access the memory of a PVM, that memory must be made accessible. Memory made accessible to the hypervisor will be encrypted. See [Documentation/virt/kvm/s390/s390-pv.rst](/kernel/internals/virt/kvm-s390/s390-pv.md) for details."

On IPL (boot) a small plaintext bootloader is started, which provides information about the encrypted components and necessary metadata to KVM to decrypt the protected virtual machine.

Based on this data, KVM will make the protected virtual machine known to the Ultravisor (UV) and instruct it to secure the memory of the PVM, decrypt the components and verify the data and address list hashes, to ensure integrity. Afterwards KVM can run the PVM via the SIE instruction which the UV will intercept and execute on KVM's behalf.

As the guest image is just like an opaque kernel image that does the switch into PV mode itself, the user can load encrypted guest executables and data via every available method (network, dasd, scsi, direct kernel, ...) without the need to change the boot process.

<a id="rst-diag308"></a>

## Diag308

This diagnose instruction is the basic mechanism to handle IPL and related operations for virtual machines. The VM can set and retrieve IPL information blocks, that specify the IPL method/devices and request VM memory and subsystem resets, as well as IPLs.

For PVMs this concept has been extended with new subcodes:

Subcode 8: Set an IPL Information Block of type 5 (information block for PVMs) Subcode 9: Store the saved block in guest memory Subcode 10: Move into Protected Virtualization mode

The new PV load-device-specific-parameters field specifies all data that is necessary to move into PV mode.

- PV Header origin

- PV Header length

- - **List of Components composed of**

    - AES-XTS Tweak prefix

    - Origin

    - Size

The PV header contains the keys and hashes, which the UV will use to decrypt and verify the PV, as well as control flags and a start PSW.

The components are for instance an encrypted kernel, kernel parameters and initrd. The components are decrypted by the UV.

After the initial import of the encrypted data, all defined pages will contain the guest content. All non-specified pages will start out as zero pages on first access.

When running in protected virtualization mode, some subcodes will result in exceptions or return error codes.

Subcodes 4 and 7, which specify operations that do not clear the guest memory, will result in specification exceptions. This is because the UV will clear all memory when a secure VM is removed, and therefore non-clearing IPL subcodes are not allowed.

Subcodes 8, 9, 10 will result in specification exceptions. Re-IPL into a protected mode is only possible via a detour into non protected mode.

<a id="rst-keys"></a>

## Keys

Every CEC will have a unique public key to enable tooling to build encrypted images. See  [s390-tools](<https://github.com/ibm-s390-linux/s390-tools/>)<a id="rst-s390-tools"></a> for the tooling.

---

# s390 (IBM Z) Protected Virtualization dumps

_Peios Kernel / Internals / Virtualisation / kvm / s390_

> Dumping a VM is an essential tool for debugging problems inside it. This is especially true when a protected VM runs into trouble as there's no way to access its memory and registers from the outside while it's running.

<a id="rst-s390-ibm-z-protected-virtualization-dumps"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>

## Summary

Dumping a VM is an essential tool for debugging problems inside it. This is especially true when a protected VM runs into trouble as there's no way to access its memory and registers from the outside while it's running.

However when dumping a protected VM we need to maintain its confidentiality until the dump is in the hands of the VM owner who should be the only one capable of analysing it.

The confidentiality of the VM dump is ensured by the Ultravisor who provides an interface to KVM over which encrypted CPU and memory data can be requested. The encryption is based on the Customer Communication Key which is the key that's used to encrypt VM data in a way that the customer is able to decrypt.

<a id="rst-dump-process"></a>

## Dump process

A dump is done in 3 steps:

**Initiation**

This step initializes the dump process, generates cryptographic seeds and extracts dump keys with which the VM dump data will be encrypted.

**Data gathering**

Currently there are two types of data that can be gathered from a VM: the memory and the vcpu state.

The vcpu state contains all the important registers, general, floating point, vector, control and tod/timers of a vcpu. The vcpu dump can contain incomplete data if a vcpu is dumped while an instruction is emulated with help of the hypervisor. This is indicated by a flag bit in the dump data. For the same reason it is very important to not only write out the encrypted vcpu state, but also the unencrypted state from the hypervisor.

The memory state is further divided into the encrypted memory and its metadata comprised of the encryption tweaks and status flags. The encrypted memory can simply be read once it has been exported. The time of the export does not matter as no re-encryption is needed. Memory that has been swapped out and hence was exported can be read from the swap and written to the dump target without need for any special actions.

The tweaks / status flags for the exported pages need to be requested from the Ultravisor.

**Finalization**

The finalization step will provide the data needed to be able to decrypt the vcpu and memory data and end the dump process. When this step completes successfully a new dump initiation can be started.

---

# s390 (IBM Z) Ultravisor and Protected VMs

_Peios Kernel / Internals / Virtualisation / kvm / s390_

> Protected virtual machines (PVM) are KVM VMs that do not allow KVM to access VM state like guest memory or guest registers. Instead, the PVMs are mostly managed by a new entity called Ultravisor (UV). The UV provides an API that can be…

<a id="rst-s390-ibm-z-ultravisor-and-protected-vms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-summary"></a>

## Summary

Protected virtual machines (PVM) are KVM VMs that do not allow KVM to access VM state like guest memory or guest registers. Instead, the PVMs are mostly managed by a new entity called Ultravisor (UV). The UV provides an API that can be used by PVMs and KVM to request management actions.

Each guest starts in non-protected mode and then may make a request to transition into protected mode. On transition, KVM registers the guest and its VCPUs with the Ultravisor and prepares everything for running it.

The Ultravisor will secure and decrypt the guest's boot memory (i.e. kernel/initrd). It will safeguard state changes like VCPU starts/stops and injected interrupts while the guest is running.

As access to the guest's state, such as the SIE state description, is normally needed to be able to run a VM, some changes have been made in the behavior of the SIE instruction. A new format 4 state description has been introduced, where some fields have different meanings for a PVM. SIE exits are minimized as much as possible to improve speed and reduce exposed guest state.

<a id="rst-interrupt-injection"></a>

## Interrupt injection

Interrupt injection is safeguarded by the Ultravisor. As KVM doesn't have access to the VCPUs' lowcores, injection is handled via the format 4 state description.

Machine check, external, IO and restart interruptions each can be injected on SIE entry via a bit in the interrupt injection control field (offset 0x54). If the guest cpu is not enabled for the interrupt at the time of injection, a validity interception is recognized. The format 4 state description contains fields in the interception data block where data associated with the interrupt can be transported.

Program and Service Call exceptions have another layer of safeguarding; they can only be injected for instructions that have been intercepted into KVM. The exceptions need to be a valid outcome of an instruction emulation by KVM, e.g. we can never inject a addressing exception as they are reported by SIE since KVM has no access to the guest memory.

<a id="rst-mask-notification-interceptions"></a>

## Mask notification interceptions

KVM cannot intercept lctl(g) and lpsw(e) anymore in order to be notified when a PVM enables a certain class of interrupt.  As a replacement, two new interception codes have been introduced: One indicating that the contents of CRs 0, 6, or 14 have been changed, indicating different interruption subclasses; and one indicating that PSW bit 13 has been changed, indicating that a machine check intervention was requested and those are now enabled.

<a id="rst-instruction-emulation"></a>

## Instruction emulation

With the format 4 state description for PVMs, the SIE instruction already interprets more instructions than it does with format 2. It is not able to interpret every instruction, but needs to hand some tasks to KVM; therefore, the SIE and the ultravisor safeguard emulation inputs and outputs.

The control structures associated with SIE provide the Secure Instruction Data Area (SIDA), the Interception Parameters (IP) and the Secure Interception General Register Save Area.  Guest GRs and most of the instruction data, such as I/O data structures, are filtered. Instruction data is copied to and from the SIDA when needed.  Guest GRs are put into / retrieved from the Secure Interception General Register Save Area.

Only GR values needed to emulate an instruction will be copied into this save area and the real register numbers will be hidden.

The Interception Parameters state description field still contains the bytes of the instruction text, but with pre-set register values instead of the actual ones. I.e. each instruction always uses the same instruction text, in order not to leak guest instruction text. This also implies that the register content that a guest had in r&lt;n&gt; may be in r&lt;m&gt; from the hypervisor's point of view.

The Secure Instruction Data Area contains instruction storage data. Instruction data, i.e. data being referenced by an instruction like the SCCB for sclp, is moved via the SIDA. When an instruction is intercepted, the SIE will only allow data and program interrupts for this instruction to be moved to the guest via the two data areas discussed before. Other data is either ignored or results in validity interceptions.

<a id="rst-instruction-emulation-interceptions"></a>

## Instruction emulation interceptions

There are two types of SIE secure instruction intercepts: the normal and the notification type. Normal secure instruction intercepts will make the guest pending for instruction completion of the intercepted instruction type, i.e. on SIE entry it is attempted to complete emulation of the instruction with the data provided by KVM. That might be a program exception or instruction completion.

The notification type intercepts inform KVM about guest environment changes due to guest instruction interpretation. Such an interception is recognized, for example, for the store prefix instruction to provide the new lowcore location. On SIE reentry, any KVM data in the data areas is ignored and execution continues as if the guest instruction had completed. For that reason KVM is not allowed to inject a program interrupt.

<a id="rst-links"></a>

## Links

[KVM Forum 2019 presentation](<https://static.sched.com/hosted_files/kvmforum2019/3b/ibm_protected_vms_s390x.pdf>)<a id="rst-kvm-forum-2019-presentation"></a>

---

# KVM for x86 systems

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> Reference for KVM for x86 systems.

<a id="rst-kvm-for-x86-systems"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Secure Encrypted Virtualization (SEV)](</kernel/internals/virt/kvm-x86/amd-memory-encryption.md>)
- [KVM CPUID bits](</kernel/internals/virt/kvm-x86/cpuid.md>)
- [Known limitations of CPU virtualization](</kernel/internals/virt/kvm-x86/errata.md>)
- [Linux KVM Hypercall](</kernel/internals/virt/kvm-x86/hypercalls.md>)
- [Intel Trust Domain Extensions (TDX)](</kernel/internals/virt/kvm-x86/intel-tdx.md>)
- [The x86 kvm shadow mmu](</kernel/internals/virt/kvm-x86/mmu.md>)
- [KVM-specific MSRs](</kernel/internals/virt/kvm-x86/msr.md>)
- [Nested VMX](</kernel/internals/virt/kvm-x86/nested-vmx.md>)
- [Running nested guests with KVM](</kernel/internals/virt/kvm-x86/running-nested-guests.md>)
- [Timekeeping Virtualization for X86-Based Architectures](</kernel/internals/virt/kvm-x86/timekeeping.md>)

---

# Secure Encrypted Virtualization (SEV)

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> Secure Encrypted Virtualization (SEV) is a feature found on AMD processors.

<a id="rst-secure-encrypted-virtualization-sev"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

Secure Encrypted Virtualization (SEV) is a feature found on AMD processors.

SEV is an extension to the AMD-V architecture which supports running virtual machines (VMs) under the control of a hypervisor. When enabled, the memory contents of a VM will be transparently encrypted with a key unique to that VM.

The hypervisor can determine the SEV support through the CPUID instruction. The CPUID function 0x8000001f reports information related to SEV:



```text
0x8000001f[eax]:
                Bit[1]  indicates support for SEV
    ...
          [ecx]:
                Bits[31:0]  Number of encrypted guests supported simultaneously
```

If support for SEV is present, MSR 0xc001_0010 (MSR_AMD64_SYSCFG) and MSR 0xc001_0015 (MSR_K7_HWCR) can be used to determine if it can be enabled:



```text
0xc001_0010:
        Bit[23]    1 = memory encryption can be enabled
                   0 = memory encryption can not be enabled

0xc001_0015:
        Bit[0]     1 = memory encryption can be enabled
                   0 = memory encryption can not be enabled
```

When SEV support is available, it can be enabled in a specific VM by setting the SEV bit before executing VMRUN.:



```text
VMCB[0x90]:
        Bit[1]      1 = SEV is enabled
                    0 = SEV is disabled
```

SEV hardware uses ASIDs to associate a memory encryption key with a VM. Hence, the ASID for the SEV-enabled guests must be from 1 to a maximum value defined in the CPUID 0x8000001f\[ecx\] field.

<a id="rst-the-kvm-memory-encrypt-op-ioctl"></a>

## The KVM_MEMORY_ENCRYPT_OP ioctl

The main ioctl to access SEV is KVM_MEMORY_ENCRYPT_OP, which operates on the VM file descriptor.  If the argument to KVM_MEMORY_ENCRYPT_OP is NULL, the ioctl returns 0 if SEV is enabled and `ENOTTY` if it is disabled (on some older versions of Linux, the ioctl tries to run normally even with a NULL argument, and therefore will likely return `EFAULT` instead of zero if SEV is enabled).  If non-NULL, the argument to KVM_MEMORY_ENCRYPT_OP must be a struct kvm_sev_cmd:



```text
struct kvm_sev_cmd {
        __u32 id;
        __u64 data;
        __u32 error;
        __u32 sev_fd;
};
```

The `id` field contains the subcommand, and the `data` field points to another struct containing arguments specific to command.  The `sev_fd` should point to a file descriptor that is opened on the `/dev/sev` device, if needed (see individual commands).

On output, `error` is zero on success, or an error code.  Error codes are defined in `<linux/psp-dev.h>`.

KVM implements the following commands to support common lifecycle events of SEV guests, such as launching, running, snapshotting, migrating and decommissioning.

<a id="rst-kvm-sev-init2"></a>

### 1. KVM_SEV_INIT2

The KVM_SEV_INIT2 command is used by the hypervisor to initialize the SEV platform context. In a typical workflow, this command should be the first command issued.

For this command to be accepted, either KVM_X86_SEV_VM or KVM_X86_SEV_ES_VM must have been passed to the KVM_CREATE_VM ioctl.  A virtual machine created with those machine types in turn cannot be run until KVM_SEV_INIT2 is invoked.

Parameters: struct kvm_sev_init (in)

Returns: 0 on success, -negative on error



```text
struct kvm_sev_init {
        __u64 vmsa_features;  /* initial value of features field in VMSA */
        __u32 flags;          /* must be 0 */
        __u16 ghcb_version;   /* maximum guest GHCB version allowed */
        __u16 pad1;
        __u32 pad2[8];
};
```

It is an error if the hypervisor does not support any of the bits that are set in `flags` or `vmsa_features`.  `vmsa_features` must be 0 for SEV virtual machines, as they do not have a VMSA.

`ghcb_version` must be 0 for SEV virtual machines, as they do not issue GHCB requests. If `ghcb_version` is 0 for any other guest type, then the maximum allowed guest GHCB protocol will default to version 2.

This command replaces the deprecated KVM_SEV_INIT and KVM_SEV_ES_INIT commands. The commands did not have any parameters (the `` `data` `` field was unused) and only work for the KVM_X86_DEFAULT_VM machine type (0).

They behave as if:

- the VM type is KVM_X86_SEV_VM for KVM_SEV_INIT, or KVM_X86_SEV_ES_VM for KVM_SEV_ES_INIT

- the `flags` and `vmsa_features` fields of `struct kvm_sev_init` are set to zero, and `ghcb_version` is set to 0 for KVM_SEV_INIT and 1 for KVM_SEV_ES_INIT.

If the `KVM_X86_SEV_VMSA_FEATURES` attribute does not exist, the hypervisor only supports KVM_SEV_INIT and KVM_SEV_ES_INIT.  In that case, note that KVM_SEV_ES_INIT might set the debug swap VMSA feature (bit 5) depending on the value of the `debug_swap` parameter of `kvm-amd.ko`.

<a id="rst-kvm-sev-launch-start"></a>

### 2. KVM_SEV_LAUNCH_START

The KVM_SEV_LAUNCH_START command is used for creating the memory encryption context. To create the encryption context, user must provide a guest policy, the owner's public Diffie-Hellman (PDH) key and session information.

Parameters: struct  kvm_sev_launch_start (in/out)

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_start {
        __u32 handle;           /* if zero then firmware creates a new handle */
        __u32 policy;           /* guest's policy */

        __u64 dh_uaddr;         /* userspace address pointing to the guest owner's PDH key */
        __u32 dh_len;

        __u64 session_addr;     /* userspace address which points to the guest session information */
        __u32 session_len;
};
```

On success, the 'handle' field contains a new handle and on error, a negative value.

KVM_SEV_LAUNCH_START requires the `sev_fd` field to be valid.

For more details, see SEV spec Section 6.2.

<a id="rst-kvm-sev-launch-update-data"></a>

### 3. KVM_SEV_LAUNCH_UPDATE_DATA

The KVM_SEV_LAUNCH_UPDATE_DATA is used for encrypting a memory region. It also calculates a measurement of the memory contents. The measurement is a signature of the memory contents that can be sent to the guest owner as an attestation that the memory was encrypted correctly by the firmware.

Parameters (in): struct  kvm_sev_launch_update_data

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_update {
        __u64 uaddr;    /* userspace address to be encrypted (must be 16-byte aligned) */
        __u32 len;      /* length of the data to be encrypted (must be 16-byte aligned) */
};
```

For more details, see SEV spec Section 6.3.

<a id="rst-kvm-sev-launch-measure"></a>

### 4. KVM_SEV_LAUNCH_MEASURE

The KVM_SEV_LAUNCH_MEASURE command is used to retrieve the measurement of the data encrypted by the KVM_SEV_LAUNCH_UPDATE_DATA command. The guest owner may wait to provide the guest with confidential information until it can verify the measurement. Since the guest owner knows the initial contents of the guest at boot, the measurement can be verified by comparing it to what the guest owner expects.

If len is zero on entry, the measurement blob length is written to len and uaddr is unused.

Parameters (in): struct  kvm_sev_launch_measure

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_measure {
        __u64 uaddr;    /* where to copy the measurement */
        __u32 len;      /* length of measurement blob */
};
```

For more details on the measurement verification flow, see SEV spec Section 6.4.

<a id="rst-kvm-sev-launch-finish"></a>

### 5. KVM_SEV_LAUNCH_FINISH

After completion of the launch flow, the KVM_SEV_LAUNCH_FINISH command can be issued to make the guest ready for the execution.

Returns: 0 on success, -negative on error

<a id="rst-kvm-sev-guest-status"></a>

### 6. KVM_SEV_GUEST_STATUS

The KVM_SEV_GUEST_STATUS command is used to retrieve status information about a SEV-enabled guest.

Parameters (out): struct kvm_sev_guest_status

Returns: 0 on success, -negative on error



```text
struct kvm_sev_guest_status {
        __u32 handle;   /* guest handle */
        __u32 policy;   /* guest policy */
        __u8 state;     /* guest state (see enum below) */
};
```

SEV guest state:



```text
enum {
SEV_STATE_INVALID = 0;
SEV_STATE_LAUNCHING,    /* guest is currently being launched */
SEV_STATE_SECRET,       /* guest is being launched and ready to accept the ciphertext data */
SEV_STATE_RUNNING,      /* guest is fully launched and running */
SEV_STATE_RECEIVING,    /* guest is being migrated in from another SEV machine */
SEV_STATE_SENDING       /* guest is getting migrated out to another SEV machine */
};
```

<a id="rst-kvm-sev-dbg-decrypt"></a>

### 7. KVM_SEV_DBG_DECRYPT

The KVM_SEV_DEBUG_DECRYPT command can be used by the hypervisor to request the firmware to decrypt the data at the given memory region.

Parameters (in): struct kvm_sev_dbg

Returns: 0 on success, -negative on error



```text
struct kvm_sev_dbg {
        __u64 src_uaddr;        /* userspace address of data to decrypt */
        __u64 dst_uaddr;        /* userspace address of destination */
        __u32 len;              /* length of memory region to decrypt */
};
```

The command returns an error if the guest policy does not allow debugging.

<a id="rst-kvm-sev-dbg-encrypt"></a>

### 8. KVM_SEV_DBG_ENCRYPT

The KVM_SEV_DEBUG_ENCRYPT command can be used by the hypervisor to request the firmware to encrypt the data at the given memory region.

Parameters (in): struct kvm_sev_dbg

Returns: 0 on success, -negative on error



```text
struct kvm_sev_dbg {
        __u64 src_uaddr;        /* userspace address of data to encrypt */
        __u64 dst_uaddr;        /* userspace address of destination */
        __u32 len;              /* length of memory region to encrypt */
};
```

The command returns an error if the guest policy does not allow debugging.

<a id="rst-kvm-sev-launch-secret"></a>

### 9. KVM_SEV_LAUNCH_SECRET

The KVM_SEV_LAUNCH_SECRET command can be used by the hypervisor to inject secret data after the measurement has been validated by the guest owner.

Parameters (in): struct kvm_sev_launch_secret

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_secret {
        __u64 hdr_uaddr;        /* userspace address containing the packet header */
        __u32 hdr_len;

        __u64 guest_uaddr;      /* the guest memory region where the secret should be injected */
        __u32 guest_len;

        __u64 trans_uaddr;      /* the hypervisor memory region which contains the secret */
        __u32 trans_len;
};
```

<a id="rst-kvm-sev-get-attestation-report"></a>

### 10. KVM_SEV_GET_ATTESTATION_REPORT

The KVM_SEV_GET_ATTESTATION_REPORT command can be used by the hypervisor to query the attestation report containing the SHA-256 digest of the guest memory and VMSA passed through the KVM_SEV_LAUNCH commands and signed with the PEK. The digest returned by the command should match the digest used by the guest owner with the KVM_SEV_LAUNCH_MEASURE.

If len is zero on entry, the measurement blob length is written to len and uaddr is unused.

Parameters (in): struct kvm_sev_attestation

Returns: 0 on success, -negative on error



```text
struct kvm_sev_attestation_report {
        __u8 mnonce[16];        /* A random mnonce that will be placed in the report */

        __u64 uaddr;            /* userspace address where the report should be copied */
        __u32 len;
};
```

<a id="rst-kvm-sev-send-start"></a>

### 11. KVM_SEV_SEND_START

The KVM_SEV_SEND_START command can be used by the hypervisor to create an outgoing guest encryption context.

If session_len is zero on entry, the length of the guest session information is written to session_len and all other fields are not used.

Parameters (in): struct kvm_sev_send_start

Returns: 0 on success, -negative on error



```text
struct kvm_sev_send_start {
        __u32 policy;                 /* guest policy */

        __u64 pdh_cert_uaddr;         /* platform Diffie-Hellman certificate */
        __u32 pdh_cert_len;

        __u64 plat_certs_uaddr;        /* platform certificate chain */
        __u32 plat_certs_len;

        __u64 amd_certs_uaddr;        /* AMD certificate */
        __u32 amd_certs_len;

        __u64 session_uaddr;          /* Guest session information */
        __u32 session_len;
};
```

<a id="rst-kvm-sev-send-update-data"></a>

### 12. KVM_SEV_SEND_UPDATE_DATA

The KVM_SEV_SEND_UPDATE_DATA command can be used by the hypervisor to encrypt the outgoing guest memory region with the encryption context creating using KVM_SEV_SEND_START.

If hdr_len or trans_len are zero on entry, the length of the packet header and transport region are written to hdr_len and trans_len respectively, and all other fields are not used.

Parameters (in): struct kvm_sev_send_update_data

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_send_update_data {
        __u64 hdr_uaddr;        /* userspace address containing the packet header */
        __u32 hdr_len;

        __u64 guest_uaddr;      /* the source memory region to be encrypted */
        __u32 guest_len;

        __u64 trans_uaddr;      /* the destination memory region  */
        __u32 trans_len;
};
```

<a id="rst-kvm-sev-send-finish"></a>

### 13. KVM_SEV_SEND_FINISH

After completion of the migration flow, the KVM_SEV_SEND_FINISH command can be issued by the hypervisor to delete the encryption context.

Returns: 0 on success, -negative on error

<a id="rst-kvm-sev-send-cancel"></a>

### 14. KVM_SEV_SEND_CANCEL

After completion of SEND_START, but before SEND_FINISH, the source VMM can issue the SEND_CANCEL command to stop a migration. This is necessary so that a cancelled migration can restart with a new target later.

Returns: 0 on success, -negative on error

<a id="rst-kvm-sev-receive-start"></a>

### 15. KVM_SEV_RECEIVE_START

The KVM_SEV_RECEIVE_START command is used for creating the memory encryption context for an incoming SEV guest. To create the encryption context, the user must provide a guest policy, the platform public Diffie-Hellman (PDH) key and session information.

Parameters: struct  kvm_sev_receive_start (in/out)

Returns: 0 on success, -negative on error



```text
struct kvm_sev_receive_start {
        __u32 handle;           /* if zero then firmware creates a new handle */
        __u32 policy;           /* guest's policy */

        __u64 pdh_uaddr;        /* userspace address pointing to the PDH key */
        __u32 pdh_len;

        __u64 session_uaddr;    /* userspace address which points to the guest session information */
        __u32 session_len;
};
```

On success, the 'handle' field contains a new handle and on error, a negative value.

For more details, see SEV spec Section 6.12.

<a id="rst-kvm-sev-receive-update-data"></a>

### 16. KVM_SEV_RECEIVE_UPDATE_DATA

The KVM_SEV_RECEIVE_UPDATE_DATA command can be used by the hypervisor to copy the incoming buffers into the guest memory region with encryption context created during the KVM_SEV_RECEIVE_START.

Parameters (in): struct kvm_sev_receive_update_data

Returns: 0 on success, -negative on error



```text
struct kvm_sev_launch_receive_update_data {
        __u64 hdr_uaddr;        /* userspace address containing the packet header */
        __u32 hdr_len;

        __u64 guest_uaddr;      /* the destination guest memory region */
        __u32 guest_len;

        __u64 trans_uaddr;      /* the incoming buffer memory region  */
        __u32 trans_len;
};
```

<a id="rst-kvm-sev-receive-finish"></a>

### 17. KVM_SEV_RECEIVE_FINISH

After completion of the migration flow, the KVM_SEV_RECEIVE_FINISH command can be issued by the hypervisor to make the guest ready for execution.

Returns: 0 on success, -negative on error

<a id="rst-kvm-sev-snp-launch-start"></a>

### 18. KVM_SEV_SNP_LAUNCH_START

The KVM_SNP_LAUNCH_START command is used for creating the memory encryption context for the SEV-SNP guest. It must be called prior to issuing KVM_SEV_SNP_LAUNCH_UPDATE or KVM_SEV_SNP_LAUNCH_FINISH;

Parameters (in): struct  kvm_sev_snp_launch_start

Returns: 0 on success, -negative on error



```text
struct kvm_sev_snp_launch_start {
        __u64 policy;           /* Guest policy to use. */
        __u8 gosvw[16];         /* Guest OS visible workarounds. */
        __u16 flags;            /* Must be zero. */
        __u8 pad0[6];
        __u64 pad1[4];
};
```

See SNP_LAUNCH_START in the SEV-SNP specification <a id="rst-citation-reference-1"></a>[snp-fw-abi](#rst-snp-fw-abi) for further details on the input parameters in `struct kvm_sev_snp_launch_start`.

<a id="rst-kvm-sev-snp-launch-update"></a>

### 19. KVM_SEV_SNP_LAUNCH_UPDATE

The KVM_SEV_SNP_LAUNCH_UPDATE command is used for loading userspace-provided data into a guest GPA range, measuring the contents into the SNP guest context created by KVM_SEV_SNP_LAUNCH_START, and then encrypting/validating that GPA range so that it will be immediately readable using the encryption key associated with the guest context once it is booted, after which point it can attest the measurement associated with its context before unlocking any secrets.

It is required that the GPA ranges initialized by this command have had the KVM_MEMORY_ATTRIBUTE_PRIVATE attribute set in advance. See the documentation for KVM_SET_MEMORY_ATTRIBUTES for more details on this aspect.

Upon success, this command is not guaranteed to have processed the entire range requested. Instead, the `gfn_start`, `uaddr`, and `len` fields of `struct kvm_sev_snp_launch_update` will be updated to correspond to the remaining range that has yet to be processed. The caller should continue calling this command until those fields indicate the entire range has been processed, e.g. `len` is 0, `gfn_start` is equal to the last GFN in the range plus 1, and `uaddr` is the last byte of the userspace-provided source buffer address plus 1. In the case where `type` is KVM_SEV_SNP_PAGE_TYPE_ZERO, `uaddr` will be ignored completely.

Parameters (in): struct  kvm_sev_snp_launch_update

Returns: 0 on success, &lt; 0 on error, -EAGAIN if caller should retry



```text
struct kvm_sev_snp_launch_update {
        __u64 gfn_start;        /* Guest page number to load/encrypt data into. */
        __u64 uaddr;            /* 4k-aligned address of data to be loaded/encrypted. */
        __u64 len;              /* 4k-aligned length in bytes to copy into guest memory.*/
        __u8 type;              /* The type of the guest pages being initialized. */
        __u8 pad0;
        __u16 flags;            /* Must be zero. */
        __u32 pad1;
        __u64 pad2[4];

};
```

where the allowed values for page_type are \#define'd as:



```text
KVM_SEV_SNP_PAGE_TYPE_NORMAL
KVM_SEV_SNP_PAGE_TYPE_ZERO
KVM_SEV_SNP_PAGE_TYPE_UNMEASURED
KVM_SEV_SNP_PAGE_TYPE_SECRETS
KVM_SEV_SNP_PAGE_TYPE_CPUID
```

See the SEV-SNP spec <a id="rst-citation-reference-2"></a>[snp-fw-abi](#rst-snp-fw-abi) for further details on how each page type is used/measured.

<a id="rst-kvm-sev-snp-launch-finish"></a>

### 20. KVM_SEV_SNP_LAUNCH_FINISH

After completion of the SNP guest launch flow, the KVM_SEV_SNP_LAUNCH_FINISH command can be issued to make the guest ready for execution.

Parameters (in): struct kvm_sev_snp_launch_finish

Returns: 0 on success, -negative on error



```text
struct kvm_sev_snp_launch_finish {
        __u64 id_block_uaddr;
        __u64 id_auth_uaddr;
        __u8 id_block_en;
        __u8 auth_key_en;
        __u8 vcek_disabled;
        __u8 host_data[32];
        __u8 pad0[3];
        __u16 flags;                    /* Must be zero */
        __u64 pad1[4];
};
```

See SNP_LAUNCH_FINISH in the SEV-SNP specification <a id="rst-citation-reference-3"></a>[snp-fw-abi](#rst-snp-fw-abi) for further details on the input parameters in `struct kvm_sev_snp_launch_finish`.

<a id="rst-kvm-sev-snp-enable-req-certs"></a>

### 21. KVM_SEV_SNP_ENABLE_REQ_CERTS

The KVM_SEV_SNP_ENABLE_REQ_CERTS command will configure KVM to exit to userspace with a `KVM_EXIT_SNP_REQ_CERTS` exit type as part of handling a guest attestation report, which will to allow userspace to provide a certificate corresponding to the endorsement key used by firmware to sign that attestation report.

Returns: 0 on success, -negative on error

NOTE: The endorsement key used by firmware may change as a result of management activities like updating SEV-SNP firmware or loading new endorsement keys, so some care should be taken to keep the returned certificate data in sync with the actual endorsement key in use by firmware at the time the attestation request is sent to SNP firmware. The recommended scheme to do this is to use file locking (e.g. via fcntl()'s F_OFD_SETLK) in the following manner:

> - Prior to obtaining/providing certificate data as part of servicing an exit type of `KVM_EXIT_SNP_REQ_CERTS`, the VMM should obtain a shared/read or exclusive/write lock on the certificate blob file before reading it and returning it to KVM, and continue to hold the lock until the attestation request is actually sent to firmware. To facilitate this, the VMM can set the `immediate_exit` flag of kvm_run just after supplying the certificate data, and just before resuming the vCPU. This will ensure the vCPU will exit again to userspace with `-EINTR` after it finishes fetching the attestation request from firmware, at which point the VMM can safely drop the file lock.
>
> - Tools/libraries that perform updates to SNP firmware TCB values or endorsement keys (e.g. via /dev/sev interfaces such as `SNP_COMMIT`, `SNP_SET_CONFIG`, or `SNP_VLEK_LOAD`, see [Documentation/virt/coco/sev-guest.rst](/kernel/internals/virt/coco/sev-guest.md) for more details) in such a way that the certificate blob needs to be updated, should similarly take an exclusive lock on the certificate blob for the duration of any updates to endorsement keys or the certificate blob contents to ensure that VMMs using the above scheme will not return certificate blob data that is out of sync with the endorsement key used by firmware at the time the attestation request is actually issued.

This scheme is recommended so that tools can use a fairly generic/natural approach to synchronizing firmware/certificate updates via file-locking, which should make it easier to maintain interoperability across tools/VMMs/vendors.

<a id="rst-device-attribute-api"></a>

## Device attribute API

Attributes of the SEV implementation can be retrieved through the `KVM_HAS_DEVICE_ATTR` and `KVM_GET_DEVICE_ATTR` ioctls on the `/dev/kvm` device node, using group `KVM_X86_GRP_SEV`.

The following attributes are currently implemented:

- `KVM_X86_SEV_VMSA_FEATURES`: return the set of all bits that are accepted in the `vmsa_features` of `KVM_SEV_INIT2`.

- `KVM_X86_SEV_SNP_REQ_CERTS`: return a value of 1 if the kernel supports the `KVM_EXIT_SNP_REQ_CERTS` exit, which allows for fetching endorsement key certificates from userspace for each SNP attestation request the guest issues.

<a id="rst-firmware-management"></a>

## Firmware Management

The SEV guest key management is handled by a separate processor called the AMD Secure Processor (AMD-SP). Firmware running inside the AMD-SP provides a secure key management interface to perform common hypervisor activities such as encrypting bootstrap code, snapshot, migrating and debugging the guest. For more information, see the SEV Key Management spec <a id="rst-citation-reference-4"></a>[api-spec](#rst-api-spec)

The AMD-SP firmware can be initialized either by using its own non-volatile storage or the OS can manage the NV storage for the firmware using parameter `init_ex_path` of the `ccp` module. If the file specified by `init_ex_path` does not exist or is invalid, the OS will create or override the file with PSP non-volatile storage.

<a id="rst-references"></a>

## References

See <a id="rst-citation-reference-5"></a>[white-paper](#rst-white-paper), <a id="rst-citation-reference-6"></a>[api-spec](#rst-api-spec), <a id="rst-citation-reference-7"></a>[amd-apm](#rst-amd-apm), <a id="rst-citation-reference-8"></a>[kvm-forum](#rst-kvm-forum), and <a id="rst-citation-reference-9"></a>[snp-fw-abi](#rst-snp-fw-abi) for more info.

<a id="rst-white-paper"></a>



**[white-paper]** [https://developer.amd.com/wordpress/media/2013/12/AMD_Memory_Encryption_Whitepaper_v7-Public.pdf](<https://developer.amd.com/wordpress/media/2013/12/AMD_Memory_Encryption_Whitepaper_v7-Public.pdf>)

<a id="rst-api-spec"></a>



**[api-spec]** [https://support.amd.com/TechDocs/55766_SEV-KM_API_Specification.pdf](<https://support.amd.com/TechDocs/55766_SEV-KM_API_Specification.pdf>)

<a id="rst-amd-apm"></a>



**[amd-apm]** [https://support.amd.com/TechDocs/24593.pdf](<https://support.amd.com/TechDocs/24593.pdf>) (section 15.34)

<a id="rst-kvm-forum"></a>



**[kvm-forum]** [https://www.linux-kvm.org/images/7/74/02x08A-Thomas_Lendacky-AMDs_Virtualizatoin_Memory_Encryption_Technology.pdf](<https://www.linux-kvm.org/images/7/74/02x08A-Thomas_Lendacky-AMDs_Virtualizatoin_Memory_Encryption_Technology.pdf>)

<a id="rst-snp-fw-abi"></a>



**[snp-fw-abi]** [https://www.amd.com/system/files/TechDocs/56860.pdf](<https://www.amd.com/system/files/TechDocs/56860.pdf>)

---

# KVM CPUID bits

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> A guest running on a kvm host, can check some of its features using cpuid. This is not always guaranteed to work, since userspace can mask-out some, or even all KVM-related cpuid features before launching a guest.

<a id="rst-kvm-cpuid-bits"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Glauber Costa &lt;[glommer@gmail.com](<mailto:glommer@gmail.com>)&gt;

A guest running on a kvm host, can check some of its features using cpuid. This is not always guaranteed to work, since userspace can mask-out some, or even all KVM-related cpuid features before launching a guest.

KVM cpuid functions are:

function: KVM_CPUID_SIGNATURE (0x40000000)

returns:



```text
eax = 0x40000001
ebx = 0x4b4d564b
ecx = 0x564b4d56
edx = 0x4d
```

Note that this value in ebx, ecx and edx corresponds to the string "KVMKVMKVM". The value in eax corresponds to the maximum cpuid function present in this leaf, and will be updated if more functions are added in the future. Note also that old hosts set eax value to 0x0. This should be interpreted as if the value was 0x40000001. This function queries the presence of KVM cpuid leafs.

function: define KVM_CPUID_FEATURES (0x40000001)

returns:



```text
ebx, ecx
eax = an OR'ed group of (1 << flag)
```

where `flag` is defined as below:


<table>
<thead>
<tr>
<th>


flag

</th>
<th>


value

</th>
<th>


meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


KVM_FEATURE_CLOCKSOURCE

</td>
<td>


0

</td>
<td>


kvmclock available at msrs 0x11 and 0x12

</td>
</tr>
<tr>
<td>


KVM_FEATURE_NOP_IO_DELAY

</td>
<td>


1

</td>
<td>


not necessary to perform delays on PIO operations

</td>
</tr>
<tr>
<td>


KVM_FEATURE_MMU_OP

</td>
<td>


2

</td>
<td>


deprecated

</td>
</tr>
<tr>
<td>


KVM_FEATURE_CLOCKSOURCE2

</td>
<td>


3

</td>
<td>


kvmclock available at msrs 0x4b564d00 and 0x4b564d01

</td>
</tr>
<tr>
<td>


KVM_FEATURE_ASYNC_PF

</td>
<td>


4

</td>
<td>


async pf can be enabled by writing to msr 0x4b564d02

</td>
</tr>
<tr>
<td>


KVM_FEATURE_STEAL_TIME

</td>
<td>


5

</td>
<td>


steal time can be enabled by writing to msr 0x4b564d03

</td>
</tr>
<tr>
<td>


KVM_FEATURE_PV_EOI

</td>
<td>


6

</td>
<td>


paravirtualized end of interrupt handler can be enabled by writing to msr 0x4b564d04

</td>
</tr>
<tr>
<td>


KVM_FEATURE_PV_UNHALT

</td>
<td>


7

</td>
<td>


guest checks this feature bit before enabling paravirtualized spinlock support

</td>
</tr>
<tr>
<td>


KVM_FEATURE_PV_TLB_FLUSH

</td>
<td>


9

</td>
<td>


guest checks this feature bit before enabling paravirtualized tlb flush

</td>
</tr>
<tr>
<td>


KVM_FEATURE_ASYNC_PF_VMEXIT

</td>
<td>


10

</td>
<td>


paravirtualized async PF VM EXIT can be enabled by setting bit 2 when writing to msr 0x4b564d02

</td>
</tr>
<tr>
<td>


KVM_FEATURE_PV_SEND_IPI

</td>
<td>


11

</td>
<td>


guest checks this feature bit before enabling paravirtualized send IPIs

</td>
</tr>
<tr>
<td>


KVM_FEATURE_POLL_CONTROL

</td>
<td>


12

</td>
<td>


host-side polling on HLT can be disabled by writing to msr 0x4b564d05.

</td>
</tr>
<tr>
<td>


KVM_FEATURE_PV_SCHED_YIELD

</td>
<td>


13

</td>
<td>


guest checks this feature bit before using paravirtualized sched yield.

</td>
</tr>
<tr>
<td>


KVM_FEATURE_ASYNC_PF_INT

</td>
<td>


14

</td>
<td>


guest checks this feature bit before using the second async pf control msr 0x4b564d06 and async pf acknowledgment msr 0x4b564d07.

</td>
</tr>
<tr>
<td>


KVM_FEATURE_MSI_EXT_DEST_ID

</td>
<td>


15

</td>
<td>


guest checks this feature bit before using extended destination ID bits in MSI address bits 11-5.

</td>
</tr>
<tr>
<td>


KVM_FEATURE_HC_MAP_GPA_RANGE

</td>
<td>


16

</td>
<td>


guest checks this feature bit before using the map gpa range hypercall to notify the page state change

</td>
</tr>
<tr>
<td>


KVM_FEATURE_MIGRATION_CONTROL

</td>
<td>


17

</td>
<td>


guest checks this feature bit before using MSR_KVM_MIGRATION_CONTROL

</td>
</tr>
<tr>
<td>


KVM_FEATURE_CLOCKSOURCE_STABLE_BIT

</td>
<td>


24

</td>
<td>


host will warn if no guest-side per-cpu warps are expected in kvmclock

</td>
</tr>
</tbody>
</table>



```text
edx = an OR'ed group of (1 << flag)
```

Where `flag` here is defined as below:


<table>
<thead>
<tr>
<th>


flag

</th>
<th>


value

</th>
<th>


meaning

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


KVM_HINTS_REALTIME

</td>
<td>


0

</td>
<td>


guest checks this feature bit to determine that vCPUs are never preempted for an unlimited time allowing optimizations

</td>
</tr>
</tbody>
</table>

---

# Known limitations of CPU virtualization

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> Whenever perfect emulation of a CPU feature is impossible or too hard, KVM has to choose between not implementing the feature at all or introducing behavioral differences between virtual machines and bare metal systems.

<a id="rst-known-limitations-of-cpu-virtualization"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

Whenever perfect emulation of a CPU feature is impossible or too hard, KVM has to choose between not implementing the feature at all or introducing behavioral differences between virtual machines and bare metal systems.

This file documents some of the known limitations that KVM has in virtualizing CPU features.

<a id="rst-x86"></a>

## x86

<a id="rst-kvm-get-supported-cpuid-issues"></a>

### `KVM_GET_SUPPORTED_CPUID` issues

<a id="rst-x87-features"></a>

#### x87 features

Unlike most other CPUID feature bits, CPUID\[EAX=7,ECX=0\]:EBX\[6\] (FDP_EXCPTN_ONLY) and CPUID\[EAX=7,ECX=0\]:EBX\]13\] (ZERO_FCS_FDS) are clear if the features are present and set if the features are not present.

Clearing these bits in CPUID has no effect on the operation of the guest; if these bits are set on hardware, the features will not be present on any virtual machine that runs on that hardware.

**Workaround:** It is recommended to always set these bits in guest CPUID. Note however that any software (e.g `WIN87EM.DLL`) expecting these features to be present likely predates these CPUID feature bits, and therefore doesn't know to check for them anyway.

<a id="rst-kvm-set-vcpu-events-issue"></a>

### `KVM_SET_VCPU_EVENTS` issue

Invalid KVM_SET_VCPU_EVENTS input with respect to error codes *may* result in failed VM-Entry on Intel CPUs.  Pre-CET Intel CPUs require that exception injection through the VMCS correctly set the "error code valid" flag, e.g. require the flag be set when injecting a \#GP, clear when injecting a \#UD, clear when injecting a soft exception, etc.  Intel CPUs that enumerate IA32_VMX_BASIC\[56\] as '1' relax VMX's consistency checks, and AMD CPUs have no restrictions whatsoever.  KVM_SET_VCPU_EVENTS doesn't sanity check the vector versus "has_error_code", i.e. KVM's ABI follows AMD behavior.

<a id="rst-nested-virtualization-features"></a>

### Nested virtualization features

On AMD CPUs, when GIF is cleared, \#DB exceptions or traps due to a breakpoint register match are ignored and discarded by the CPU. The CPU relies on the VMM to fully virtualize this behavior, even when vGIF is enabled for the guest (i.e. vGIF=0 does not cause the CPU to drop \#DBs when the guest is running). KVM does not virtualize this behavior as the complexity is unjustified given the rarity of the use case. One way to handle this would be for KVM to intercept the \#DB, temporarily disable the breakpoint, single-step over the instruction, then re-enable the breakpoint.

<a id="rst-x2apic"></a>

### x2APIC

When KVM_X2APIC_API_USE_32BIT_IDS is enabled, KVM activates a hack/quirk that allows sending events to a single vCPU using its x2APIC ID even if the target vCPU has legacy xAPIC enabled, e.g. to bring up hotplugged vCPUs via INIT-SIPI on VMs with &gt; 255 vCPUs.  A side effect of the quirk is that, if multiple vCPUs have the same physical APIC ID, KVM will deliver events targeting that APIC ID only to the vCPU with the lowest vCPU ID.  If KVM_X2APIC_API_USE_32BIT_IDS is not enabled, KVM follows x86 architecture when processing interrupts (all vCPUs matching the target APIC ID receive the interrupt).

<a id="rst-mtrrs"></a>

### MTRRs

KVM does not virtualize guest MTRR memory types.  KVM emulates accesses to MTRR MSRs, i.e. \{RD,WR\}MSR in the guest will behave as expected, but KVM does not honor guest MTRRs when determining the effective memory type, and instead treats all of guest memory as having Writeback (WB) MTRRs.

<a id="rst-cr0-cd"></a>

### CR0.CD

KVM does not virtualize CR0.CD on Intel CPUs.  Similar to MTRR MSRs, KVM emulates CR0.CD accesses so that loads and stores from/to CR0 behave as expected, but setting CR0.CD=1 has no impact on the cachaeability of guest memory.

Note, this erratum does not affect AMD CPUs, which fully virtualize CR0.CD in hardware, i.e. put the CPU caches into "no fill" mode when CR0.CD=1, even when running in the guest.

---

# Linux KVM Hypercall

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> KVM Hypercalls have a three-byte sequence of either the vmcall or the vmmcall instruction. The hypervisor can replace it with instructions that are guaranteed to be supported.

<a id="rst-linux-kvm-hypercall"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- **X86:**

  KVM Hypercalls have a three-byte sequence of either the vmcall or the vmmcall instruction. The hypervisor can replace it with instructions that are guaranteed to be supported.

  Up to four arguments may be passed in rbx, rcx, rdx, and rsi respectively. The hypercall number should be placed in rax and the return value will be placed in rax.  No other registers will be clobbered unless explicitly stated by the particular hypercall.

- **S390:**

  R2-R7 are used for parameters 1-6. In addition, R1 is used for hypercall number. The return value is written to R2.

  S390 uses diagnose instruction as hypercall (0x500) along with hypercall number in R1.

  For further information on the S390 diagnose call as supported by KVM, refer to [Documentation/virt/kvm/s390/s390-diag.rst](/kernel/internals/virt/kvm-s390/s390-diag.md).

- **PowerPC:**

  It uses R3-R10 and hypercall number in R11. R4-R11 are used as output registers. Return value is placed in R3.

  KVM hypercalls uses 4 byte opcode, that are patched with 'hypercall-instructions' property inside the device tree's /hypervisor node. For more information refer to [Documentation/virt/kvm/ppc-pv.rst](/kernel/internals/virt/kvm/ppc-pv.md)

- **MIPS:**

  KVM hypercalls use the HYPCALL instruction with code 0 and the hypercall number in $2 (v0). Up to four arguments may be placed in $4-$7 (a0-a3) and the return value is placed in $2 (v0).

<a id="rst-kvm-hypercalls-documentation"></a>

## KVM Hypercalls Documentation

The template for each hypercall is: 1. Hypercall name. 2. Architecture(s) 3. Status (deprecated, obsolete, active) 4. Purpose

<a id="rst-kvm-hc-vapic-poll-irq"></a>

### 1. KVM_HC_VAPIC_POLL_IRQ

**Architecture:** x86

**Status:** active

**Purpose:** Trigger guest exit so that the host can check for pending interrupts on reentry.

<a id="rst-kvm-hc-mmu-op"></a>

### 2. KVM_HC_MMU_OP

**Architecture:** x86

**Status:** deprecated.

**Purpose:** Support MMU operations such as writing to PTE, flushing TLB, release PT.

<a id="rst-kvm-hc-features"></a>

### 3. KVM_HC_FEATURES

**Architecture:** PPC

**Status:** active

**Purpose:** Expose hypercall availability to the guest. On x86 platforms, cpuid used to enumerate which hypercalls are available. On PPC, either device tree based lookup ( which is also what EPAPR dictates) OR KVM specific enumeration mechanism (which is this hypercall) can be used.

<a id="rst-kvm-hc-ppc-map-magic-page"></a>

### 4. KVM_HC_PPC_MAP_MAGIC_PAGE

**Architecture:** PPC

**Status:** active

**Purpose:** To enable communication between the hypervisor and guest there is a shared page that contains parts of supervisor visible register state. The guest can map this shared page to access its supervisor register through memory using this hypercall.

<a id="rst-kvm-hc-kick-cpu"></a>

### 5. KVM_HC_KICK_CPU

**Architecture:** x86

**Status:** active

**Purpose:** Hypercall used to wakeup a vcpu from HLT state

**Usage example:** A vcpu of a paravirtualized guest that is busywaiting in guest kernel mode for an event to occur (ex: a spinlock to become available) can execute HLT instruction once it has busy-waited for more than a threshold time-interval. Execution of HLT instruction would cause the hypervisor to put the vcpu to sleep until occurrence of an appropriate event. Another vcpu of the same guest can wakeup the sleeping vcpu by issuing KVM_HC_KICK_CPU hypercall, specifying APIC ID (a1) of the vcpu to be woken up. An additional argument (a0) is used in the hypercall for future use.

<a id="rst-kvm-hc-clock-pairing"></a>

### 6. KVM_HC_CLOCK_PAIRING

**Architecture:** x86

**Status:** active

**Purpose:** Hypercall used to synchronize host and guest clocks.

Usage:

a0: guest physical address where host copies "struct kvm_clock_offset" structure.

a1: clock_type, ATM only KVM_CLOCK_PAIRING_WALLCLOCK (0) is supported (corresponding to the host's CLOCK_REALTIME clock).

>
>
> ```text
> struct kvm_clock_pairing {
>         __s64 sec;
>         __s64 nsec;
>         __u64 tsc;
>         __u32 flags;
>         __u32 pad[9];
> };
> ```
>
> - **Where:**
>
>   - sec: seconds from clock_type clock.
>
>   - nsec: nanoseconds from clock_type clock.
>
>   - tsc: guest TSC value used to calculate sec/nsec pair
>
>   - flags: flags, unused (0) at the moment.

The hypercall lets a guest compute a precise timestamp across host and guest.  The guest can use the returned TSC value to compute the CLOCK_REALTIME for its clock, at the same instant.

Returns KVM_EOPNOTSUPP if the host does not use TSC clocksource, or if clock type is different than KVM_CLOCK_PAIRING_WALLCLOCK.

<a id="rst-kvm-hc-send-ipi"></a>

### 7. KVM_HC_SEND_IPI

**Architecture:** x86

**Status:** active

**Purpose:** Send IPIs to multiple vCPUs.

- a0: lower part of the bitmap of destination APIC IDs

- a1: higher part of the bitmap of destination APIC IDs

- a2: the lowest APIC ID in bitmap

- a3: APIC ICR

The hypercall lets a guest send multicast IPIs, with at most 128 128 destinations per hypercall in 64-bit mode and 64 vCPUs per hypercall in 32-bit mode.  The destinations are represented by a bitmap contained in the first two arguments (a0 and a1). Bit 0 of a0 corresponds to the APIC ID in the third argument (a2), bit 1 corresponds to the APIC ID a2+1, and so on.

Returns the number of CPUs to which the IPIs were delivered successfully.

<a id="rst-kvm-hc-sched-yield"></a>

### 8. KVM_HC_SCHED_YIELD

**Architecture:** x86

**Status:** active

**Purpose:** Hypercall used to yield if the IPI target vCPU is preempted

a0: destination APIC ID

**Usage example:** When sending a call-function IPI-many to vCPUs, yield if any of the IPI target vCPUs was preempted.

<a id="rst-kvm-hc-map-gpa-range"></a>

### 9. KVM_HC_MAP_GPA_RANGE

**Architecture:** x86

**Status:** active

**Purpose:** Request KVM to map a GPA range with the specified attributes.

a0: the guest physical address of the start page a1: the number of (4kb) pages (must be contiguous in GPA space) a2: attributes

> - **Where 'attributes' :**
>
>   - bits  3:0 - preferred page size encoding 0 = 4kb, 1 = 2mb, 2 = 1gb, etc...
>
>   - bit     4 - plaintext = 0, encrypted = 1
>
>   - bits 63:5 - reserved (must be zero)

**Implementation note**: this hypercall is implemented in userspace via the KVM_CAP_EXIT_HYPERCALL capability. Userspace must enable that capability before advertising KVM_FEATURE_HC_MAP_GPA_RANGE in the guest CPUID.  In addition, if the guest supports KVM_FEATURE_MIGRATION_CONTROL, userspace must also set up an MSR filter to process writes to MSR_KVM_MIGRATION_CONTROL.

---

# Intel Trust Domain Extensions (TDX)

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> Intel's Trust Domain Extensions (TDX) protect confidential guest VMs from the host and physical attacks. A CPU-attested software module called 'the TDX module' runs inside a new CPU isolated range to provide the functionalities to manage…

<a id="rst-intel-trust-domain-extensions-tdx"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

Intel's Trust Domain Extensions (TDX) protect confidential guest VMs from the host and physical attacks.  A CPU-attested software module called 'the TDX module' runs inside a new CPU isolated range to provide the functionalities to manage and run protected VMs, a.k.a, TDX guests or TDs.

Please refer to \[1\] for the whitepaper, specifications and other resources.

This documentation describes TDX-specific KVM ABIs.  The TDX module needs to be initialized before it can be used by KVM to run any TDX guests.  The host core-kernel provides the support of initializing the TDX module, which is described in the [Documentation/arch/x86/tdx.rst](/kernel/hardware/arch/x86/tdx.md).

<a id="rst-api-description"></a>

## API description

<a id="rst-kvm-memory-encrypt-op"></a>

### KVM_MEMORY_ENCRYPT_OP

**Type:** vm ioctl, vcpu ioctl

For TDX operations, KVM_MEMORY_ENCRYPT_OP is re-purposed to be generic ioctl with TDX specific sub-ioctl() commands.



```text
/* Trust Domain Extensions sub-ioctl() commands. */
enum kvm_tdx_cmd_id {
        KVM_TDX_CAPABILITIES = 0,
        KVM_TDX_INIT_VM,
        KVM_TDX_INIT_VCPU,
        KVM_TDX_INIT_MEM_REGION,
        KVM_TDX_FINALIZE_VM,
        KVM_TDX_GET_CPUID,

        KVM_TDX_CMD_NR_MAX,
};

struct kvm_tdx_cmd {
      /* enum kvm_tdx_cmd_id */
      __u32 id;
      /* flags for sub-command. If sub-command doesn't use this, set zero. */
      __u32 flags;
      /*
       * data for each sub-command. An immediate or a pointer to the actual
       * data in process virtual address.  If sub-command doesn't use it,
       * set zero.
       */
      __u64 data;
      /*
       * Auxiliary error code.  The sub-command may return TDX SEAMCALL
       * status code in addition to -Exxx.
       */
      __u64 hw_error;
};
```

<a id="rst-kvm-tdx-capabilities"></a>

### KVM_TDX_CAPABILITIES

**Type:** vm ioctl

**Returns:** 0 on success, &lt;0 on error

Return the TDX capabilities that current KVM supports with the specific TDX module loaded in the system.  It reports what features/capabilities are allowed to be configured to the TDX guest.

- id: KVM_TDX_CAPABILITIES

- flags: must be 0

- data: pointer to struct kvm_tdx_capabilities

- hw_error: must be 0



```text
struct kvm_tdx_capabilities {
      __u64 supported_attrs;
      __u64 supported_xfam;

      /* TDG.VP.VMCALL hypercalls executed in kernel and forwarded to
       * userspace, respectively
       */
      __u64 kernel_tdvmcallinfo_1_r11;
      __u64 user_tdvmcallinfo_1_r11;

      /* TDG.VP.VMCALL instruction executions subfunctions executed in kernel
       * and forwarded to userspace, respectively
       */
      __u64 kernel_tdvmcallinfo_1_r12;
      __u64 user_tdvmcallinfo_1_r12;

      __u64 reserved[250];

      /* Configurable CPUID bits for userspace */
      struct kvm_cpuid2 cpuid;
};
```

<a id="rst-kvm-tdx-init-vm"></a>

### KVM_TDX_INIT_VM

**Type:** vm ioctl

**Returns:** 0 on success, &lt;0 on error

Perform TDX specific VM initialization.  This needs to be called after KVM_CREATE_VM and before creating any VCPUs.

- id: KVM_TDX_INIT_VM

- flags: must be 0

- data: pointer to struct kvm_tdx_init_vm

- hw_error: must be 0



```text
struct kvm_tdx_init_vm {
        __u64 attributes;
        __u64 xfam;
        __u64 mrconfigid[6];          /* sha384 digest */
        __u64 mrowner[6];             /* sha384 digest */
        __u64 mrownerconfig[6];       /* sha384 digest */

        /* The total space for TD_PARAMS before the CPUIDs is 256 bytes */
        __u64 reserved[12];

      /*
       * Call KVM_TDX_INIT_VM before vcpu creation, thus before
       * KVM_SET_CPUID2.
       * This configuration supersedes KVM_SET_CPUID2s for VCPUs because the
       * TDX module directly virtualizes those CPUIDs without VMM.  The user
       * space VMM, e.g. qemu, should make KVM_SET_CPUID2 consistent with
       * those values.  If it doesn't, KVM may have wrong idea of vCPUIDs of
       * the guest, and KVM may wrongly emulate CPUIDs or MSRs that the TDX
       * module doesn't virtualize.
       */
        struct kvm_cpuid2 cpuid;
};
```

<a id="rst-kvm-tdx-init-vcpu"></a>

### KVM_TDX_INIT_VCPU

**Type:** vcpu ioctl

**Returns:** 0 on success, &lt;0 on error

Perform TDX specific VCPU initialization.

- id: KVM_TDX_INIT_VCPU

- flags: must be 0

- data: initial value of the guest TD VCPU RCX

- hw_error: must be 0

<a id="rst-kvm-tdx-init-mem-region"></a>

### KVM_TDX_INIT_MEM_REGION

**Type:** vcpu ioctl

**Returns:** 0 on success, &lt;0 on error

Initialize @nr_pages TDX guest private memory starting from @gpa with userspace provided data from @source_addr. @source_addr must be PAGE_SIZE-aligned.

Note, before calling this sub command, memory attribute of the range \[gpa, gpa + nr_pages\] needs to be private.  Userspace can use KVM_SET_MEMORY_ATTRIBUTES to set the attribute.

If KVM_TDX_MEASURE_MEMORY_REGION flag is specified, it also extends measurement.

- id: KVM_TDX_INIT_MEM_REGION

- flags: currently only KVM_TDX_MEASURE_MEMORY_REGION is defined

- data: pointer to struct kvm_tdx_init_mem_region

- hw_error: must be 0



```text
#define KVM_TDX_MEASURE_MEMORY_REGION   (1UL << 0)

struct kvm_tdx_init_mem_region {
        __u64 source_addr;
        __u64 gpa;
        __u64 nr_pages;
};
```

<a id="rst-kvm-tdx-finalize-vm"></a>

### KVM_TDX_FINALIZE_VM

**Type:** vm ioctl

**Returns:** 0 on success, &lt;0 on error

Complete measurement of the initial TD contents and mark it ready to run.

- id: KVM_TDX_FINALIZE_VM

- flags: must be 0

- data: must be 0

- hw_error: must be 0

<a id="rst-kvm-tdx-get-cpuid"></a>

### KVM_TDX_GET_CPUID

**Type:** vcpu ioctl

**Returns:** 0 on success, &lt;0 on error

Get the CPUID values that the TDX module virtualizes for the TD guest. When it returns -E2BIG, the user space should allocate a larger buffer and retry. The minimum buffer size is updated in the nent field of the struct kvm_cpuid2.

- id: KVM_TDX_GET_CPUID

- flags: must be 0

- data: pointer to struct kvm_cpuid2 (in/out)

- hw_error: must be 0 (out)



```text
struct kvm_cpuid2 {
        __u32 nent;
        __u32 padding;
        struct kvm_cpuid_entry2 entries[0];
};

struct kvm_cpuid_entry2 {
        __u32 function;
        __u32 index;
        __u32 flags;
        __u32 eax;
        __u32 ebx;
        __u32 ecx;
        __u32 edx;
        __u32 padding[3];
};
```

<a id="rst-kvm-tdx-creation-flow"></a>

## KVM TDX creation flow

In addition to the standard KVM flow, new TDX ioctls need to be called.  The control flow is as follows:

1. Check system wide capability

   - KVM_CAP_VM_TYPES: Check if VM type is supported and if KVM_X86_TDX_VM is supported.

2. Create VM

   - KVM_CREATE_VM

   - KVM_TDX_CAPABILITIES: Query TDX capabilities for creating TDX guests.

   - KVM_CHECK_EXTENSION(KVM_CAP_MAX_VCPUS): Query maximum VCPUs the TD can support at VM level (TDX has its own limitation on this).

   - KVM_SET_TSC_KHZ: Configure TD's TSC frequency if a different TSC frequency than host is desired.  This is Optional.

   - KVM_TDX_INIT_VM: Pass TDX specific VM parameters.

3. Create VCPU

   - KVM_CREATE_VCPU

   - KVM_TDX_INIT_VCPU: Pass TDX specific VCPU parameters.

   - KVM_SET_CPUID2: Configure TD's CPUIDs.

   - KVM_SET_MSRS: Configure TD's MSRs.

4. Initialize initial guest memory

   - Prepare content of initial guest memory.

   - KVM_TDX_INIT_MEM_REGION: Add initial guest memory.

   - KVM_TDX_FINALIZE_VM: Finalize the measurement of the TDX guest.

5. Run VCPU

<a id="rst-references"></a>

## References

[https://www.intel.com/content/www/us/en/developer/tools/trust-domain-extensions/documentation.html](<https://www.intel.com/content/www/us/en/developer/tools/trust-domain-extensions/documentation.html>)

---

# The x86 kvm shadow mmu

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> The mmu (in arch/x86/kvm, files mmu.[ch] and paging_tmpl.h) is responsible for presenting a standard x86 mmu to the guest, while translating guest physical addresses to host physical addresses.

<a id="rst-the-x86-kvm-shadow-mmu"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

The mmu (in arch/x86/kvm, files mmu.\[ch\] and paging_tmpl.h) is responsible for presenting a standard x86 mmu to the guest, while translating guest physical addresses to host physical addresses.

The mmu code attempts to satisfy the following requirements:

- - **correctness:**

    the guest should not be able to determine that it is running on an emulated mmu except for timing (we attempt to comply with the specification, not emulate the characteristics of a particular implementation such as tlb size)

- - **security:**

    the guest must not be able to touch host memory not assigned to it

- - **performance:**

    minimize the performance penalty imposed by the mmu

- - **scaling:**

    need to scale to large memory and large vcpu guests

- - **hardware:**

    support the full range of x86 virtualization hardware

- - **integration:**

    Linux memory management code must be in control of guest memory so that swapping, page migration, page merging, transparent hugepages, and similar features work without change

- - **dirty tracking:**

    report writes to guest memory to enable live migration and framebuffer-based displays

- - **footprint:**

    keep the amount of pinned kernel memory low (most memory should be shrinkable)

- - **reliability:**

    avoid multipage or GFP_ATOMIC allocations

<a id="rst-acronyms"></a>

## Acronyms


<table>
<tbody>
<tr>
<td>


pfn

</td>
<td>


host page frame number

</td>
</tr>
<tr>
<td>


hpa

</td>
<td>


host physical address

</td>
</tr>
<tr>
<td>


hva

</td>
<td>


host virtual address

</td>
</tr>
<tr>
<td>


gfn

</td>
<td>


guest frame number

</td>
</tr>
<tr>
<td>


gpa

</td>
<td>


guest physical address

</td>
</tr>
<tr>
<td>


gva

</td>
<td>


guest virtual address

</td>
</tr>
<tr>
<td>


ngpa

</td>
<td>


nested guest physical address

</td>
</tr>
<tr>
<td>


ngva

</td>
<td>


nested guest virtual address

</td>
</tr>
<tr>
<td>


pte

</td>
<td>


page table entry (used also to refer generically to paging structure entries)

</td>
</tr>
<tr>
<td>


gpte

</td>
<td>


guest pte (referring to gfns)

</td>
</tr>
<tr>
<td>


spte

</td>
<td>


shadow pte (referring to pfns)

</td>
</tr>
<tr>
<td>


tdp

</td>
<td>


two dimensional paging (vendor neutral term for NPT and EPT)

</td>
</tr>
</tbody>
</table>

<a id="rst-virtual-and-real-hardware-supported"></a>

## Virtual and real hardware supported

The mmu supports first-generation mmu hardware, which allows an atomic switch of the current paging mode and cr3 during guest entry, as well as two-dimensional paging (AMD's NPT and Intel's EPT).  The emulated hardware it exposes is the traditional 2/3/4 level x86 mmu, with support for global pages, pae, pse, pse36, cr0.wp, and 1GB pages. Emulated hardware also able to expose NPT capable hardware on NPT capable hosts.

<a id="rst-translation"></a>

## Translation

The primary job of the mmu is to program the processor's mmu to translate addresses for the guest.  Different translations are required at different times:

- when guest paging is disabled, we translate guest physical addresses to host physical addresses (gpa-&gt;hpa)

- when guest paging is enabled, we translate guest virtual addresses, to guest physical addresses, to host physical addresses (gva-&gt;gpa-&gt;hpa)

- when the guest launches a guest of its own, we translate nested guest virtual addresses, to nested guest physical addresses, to guest physical addresses, to host physical addresses (ngva-&gt;ngpa-&gt;gpa-&gt;hpa)

The primary challenge is to encode between 1 and 3 translations into hardware that support only 1 (traditional) and 2 (tdp) translations.  When the number of required translations matches the hardware, the mmu operates in direct mode; otherwise it operates in shadow mode (see below).

<a id="rst-memory"></a>

## Memory

Guest memory (gpa) is part of the user address space of the process that is using kvm.  Userspace defines the translation between guest addresses and user addresses (gpa-&gt;hva); note that two gpas may alias to the same hva, but not vice versa.

These hvas may be backed using any method available to the host: anonymous memory, file backed memory, and device memory.  Memory might be paged by the host at any time.

<a id="rst-events"></a>

## Events

The mmu is driven by events, some from the guest, some from the host.

Guest generated events:

- writes to control registers (especially cr3)

- invlpg/invlpga instruction execution

- access to missing or protected translations

Host generated events:

- changes in the gpa-&gt;hpa translation (either through gpa-&gt;hva changes or through hva-&gt;hpa changes)

- memory pressure (the shrinker)

<a id="rst-shadow-pages"></a>

## Shadow pages

The principal data structure is the shadow page, 'struct kvm_mmu_page'.  A shadow page contains 512 sptes, which can be either leaf or nonleaf sptes.  A shadow page may contain a mix of leaf and nonleaf sptes.

A nonleaf spte allows the hardware mmu to reach the leaf pages and is not related to a translation directly.  It points to other shadow pages.

A leaf spte corresponds to either one or two translations encoded into one paging structure entry.  These are always the lowest level of the translation stack, with optional higher level translations left to NPT/EPT. Leaf ptes point at guest pages.

The following table shows translations encoded by leaf ptes, with higher-level translations in parentheses:

> Non-nested guests:
>
>
>
> ```text
> nonpaging:     gpa->hpa
> paging:        gva->gpa->hpa
> paging, tdp:   (gva->)gpa->hpa
> ```
>
> Nested guests:
>
>
>
> ```text
> non-tdp:       ngva->gpa->hpa  (*)
> tdp:           (ngva->)ngpa->gpa->hpa
>
> (*) the guest hypervisor will encode the ngva->gpa translation into its page
>     tables if npt is not present
> ```

- **Shadow pages contain the following information:**

  - **role.level:**

    The level in the shadow paging hierarchy that this shadow page belongs to. 1=4k sptes, 2=2M sptes, 3=1G sptes, etc.

  - **role.direct:**

    If set, leaf sptes reachable from this page are for a linear range. Examples include real mode translation, large guest pages backed by small host pages, and gpa-&gt;hpa translations when NPT or EPT is active. The linear range starts at (gfn &lt;&lt; PAGE_SHIFT) and its size is determined by role.level (2MB for first level, 1GB for second level, 0.5TB for third level, 256TB for fourth level) If clear, this page corresponds to a guest page table denoted by the gfn field.

  - **role.quadrant:**

    When role.has_4_byte_gpte=1, the guest uses 32-bit gptes while the host uses 64-bit sptes.  That means a guest page table contains more ptes than the host, so multiple shadow pages are needed to shadow one guest page. For first-level shadow pages, role.quadrant can be 0 or 1 and denotes the first or second 512-gpte block in the guest page table.  For second-level page tables, each 32-bit gpte is converted to two 64-bit sptes (since each first-level guest page is shadowed by two first-level shadow pages) so role.quadrant takes values in the range 0..3.  Each quadrant maps 1GB virtual address space.

  - **role.access:**

    Inherited guest access permissions from the parent ptes in the form uwx. Note execute permission is positive, not negative.

  - **role.invalid:**

    The page is invalid and should not be used.  It is a root page that is currently pinned (by a cpu hardware register pointing to it); once it is unpinned it will be destroyed.

  - **role.has_4_byte_gpte:**

    Reflects the size of the guest PTE for which the page is valid, i.e. '0' if direct map or 64-bit gptes are in use, '1' if 32-bit gptes are in use.

  - **role.efer_nx:**

    Contains the value of efer.nx for which the page is valid.

  - **role.cr0_wp:**

    Contains the value of cr0.wp for which the page is valid.

  - **role.smep_andnot_wp:**

    Contains the value of cr4.smep &amp;&amp; \!cr0.wp for which the page is valid (pages for which this is true are different from other pages; see the treatment of cr0.wp=0 below).

  - **role.smap_andnot_wp:**

    Contains the value of cr4.smap &amp;&amp; \!cr0.wp for which the page is valid (pages for which this is true are different from other pages; see the treatment of cr0.wp=0 below).

  - **role.smm:**

    Is 1 if the page is valid in system management mode.  This field determines which of the kvm_memslots array was used to build this shadow page; it is also used to go back from a struct kvm_mmu_page to a memslot, through the kvm_memslots_for_spte_role macro and \__gfn_to_memslot.

  - **role.ad_disabled:**

    Is 1 if the MMU instance cannot use A/D bits.  EPT did not have A/D bits before Haswell; shadow EPT page tables also cannot use A/D bits if the L1 hypervisor does not enable them.

  - **role.guest_mode:**

    Indicates the shadow page is created for a nested guest.

  - **role.passthrough:**

    The page is not backed by a guest page table, but its first entry points to one.  This is set if NPT uses 5-level page tables (host CR4.LA57=1) and is shadowing L1's 4-level NPT (L1 CR4.LA57=0).

  - **mmu_valid_gen:**

    The MMU generation of this page, used to fast zap of all MMU pages within a VM without blocking vCPUs too long. Specifically, KVM updates the per-VM valid MMU generation which causes the mismatch of mmu_valid_gen for each mmu page. This makes all existing MMU pages obsolete. Obsolete pages can't be used. Therefore, vCPUs must load a new, valid root before re-entering the guest. The MMU generation is only ever '0' or '1'. Note, the TDP MMU doesn't use this field as non-root TDP MMU pages are reachable only from their owning root. Thus it suffices for TDP MMU to use role.invalid in root pages to invalidate all MMU pages.

  - **gfn:**

    Either the guest page table containing the translations shadowed by this page, or the base page frame for linear translations.  See role.direct.

  - **spt:**

    A pageful of 64-bit sptes containing the translations for this page. Accessed by both kvm and hardware. The page pointed to by spt will have its page-&gt;private pointing back at the shadow page structure. sptes in spt point either at guest pages, or at lower-level shadow pages. Specifically, if sp1 and sp2 are shadow pages, then sp1-&gt;spt\[n\] may point at \__pa(sp2-&gt;spt).  sp2 will point back at sp1 through parent_pte. The spt array forms a DAG structure with the shadow page as a node, and guest pages as leaves.

  - **shadowed_translation:**

    An array of 512 shadow translation entries, one for each present pte. Used to perform a reverse map from a pte to a gfn as well as its access permission. When role.direct is set, the shadow_translation array is not allocated. This is because the gfn contained in any element of this array can be calculated from the gfn field when used.  In addition, when role.direct is set, KVM does not track access permission for each of the gfn. See role.direct and gfn.

  - **root_count / tdp_mmu_root_count:**

    root_count is a reference counter for root shadow pages in Shadow MMU. vCPUs elevate the refcount when getting a shadow page that will be used as a root page, i.e. page that will be loaded into hardware directly (CR3, PDPTRs, nCR3 EPTP). Root pages cannot be destroyed while their refcount is non-zero. See role.invalid. tdp_mmu_root_count is similar but exclusively used in TDP MMU as an atomic refcount.

  - **parent_ptes:**

    The reverse mapping for the pte/ptes pointing at this page's spt. If parent_ptes bit 0 is zero, only one spte points at this page and parent_ptes points at this single spte, otherwise, there exists multiple sptes pointing at this page and (parent_ptes &amp; \~0x1) points at a data structure with a list of parent sptes.

  - **ptep:**

    The kernel virtual address of the SPTE that points at this shadow page. Used exclusively by the TDP MMU, this field is a union with parent_ptes.

  - **unsync:**

    If true, then the translations in this page may not match the guest's translation.  This is equivalent to the state of the tlb when a pte is changed but before the tlb entry is flushed.  Accordingly, unsync ptes are synchronized when the guest executes invlpg or flushes its tlb by other means.  Valid for leaf pages.

  - **unsync_children:**

    How many sptes in the page point at pages that are unsync (or have unsynchronized children).

  - **unsync_child_bitmap:**

    A bitmap indicating which sptes in spt point (directly or indirectly) at pages that may be unsynchronized.  Used to quickly locate all unsynchronized pages reachable from a given page.

  - **clear_spte_count:**

    Only present on 32-bit hosts, where a 64-bit spte cannot be written atomically.  The reader uses this while running out of the MMU lock to detect in-progress updates and retry them until the writer has finished the write.

  - **write_flooding_count:**

    A guest may write to a page table many times, causing a lot of emulations if the page needs to be write-protected (see "Synchronized and unsynchronized pages" below).  Leaf pages can be unsynchronized so that they do not trigger frequent emulation, but this is not possible for non-leafs.  This field counts the number of emulations since the last time the page table was actually used; if emulation is triggered too frequently on this page, KVM will unmap the page to avoid emulation in the future.

  - **tdp_mmu_page:**

    Is 1 if the shadow page is a TDP MMU page. This variable is used to bifurcate the control flows for KVM when walking any data structure that may contain pages from both TDP MMU and shadow MMU.

<a id="rst-reverse-map"></a>

## Reverse map

The mmu maintains a reverse mapping whereby all ptes mapping a page can be reached given its gfn.  This is used, for example, when swapping out a page.

<a id="rst-synchronized-and-unsynchronized-pages"></a>

## Synchronized and unsynchronized pages

The guest uses two events to synchronize its tlb and page tables: tlb flushes and page invalidations (invlpg).

A tlb flush means that we need to synchronize all sptes reachable from the guest's cr3.  This is expensive, so we keep all guest page tables write protected, and synchronize sptes to gptes when a gpte is written.

A special case is when a guest page table is reachable from the current guest cr3.  In this case, the guest is obliged to issue an invlpg instruction before using the translation.  We take advantage of that by removing write protection from the guest page, and allowing the guest to modify it freely. We synchronize modified gptes when the guest invokes invlpg.  This reduces the amount of emulation we have to do when the guest modifies multiple gptes, or when the a guest page is no longer used as a page table and is used for random guest data.

As a side effect we have to resynchronize all reachable unsynchronized shadow pages on a tlb flush.

<a id="rst-reaction-to-events"></a>

## Reaction to events

- guest page fault (or npt page fault, or ept violation)

This is the most complicated event.  The cause of a page fault can be:

> - a true guest fault (the guest translation won't allow the access) (\*)
>
> - access to a missing translation
>
> - access to a protected translation - when logging dirty pages, memory is write protected - synchronized shadow pages are write protected (\*)
>
> - access to untranslatable memory (mmio)
>
> (\*) not applicable in direct mode

Handling a page fault is performed as follows:

> - if the RSV bit of the error code is set, the page fault is caused by guest accessing MMIO and cached MMIO information is available.
>
>   - walk shadow page table
>
>   - check for valid generation number in the spte (see "Fast invalidation of MMIO sptes" below)
>
>   - cache the information to vcpu-&gt;arch.mmio_gva, vcpu-&gt;arch.mmio_access and vcpu-&gt;arch.mmio_gfn, and call the emulator
>
> - If both P bit and R/W bit of error code are set, this could possibly be handled as a "fast page fault" (fixed without taking the MMU lock).  See the description in [Documentation/virt/kvm/locking.rst](/kernel/internals/virt/kvm/locking.md).
>
> - if needed, walk the guest page tables to determine the guest translation (gva-&gt;gpa or ngpa-&gt;gpa)
>
>   - if permissions are insufficient, reflect the fault back to the guest
>
> - determine the host page
>
>   - if this is an mmio request, there is no host page; cache the info to vcpu-&gt;arch.mmio_gva, vcpu-&gt;arch.mmio_access and vcpu-&gt;arch.mmio_gfn
>
> - walk the shadow page table to find the spte for the translation, instantiating missing intermediate page tables as necessary
>
>   - If this is an mmio request, cache the mmio info to the spte and set some reserved bit on the spte (see callers of kvm_mmu_set_mmio_spte_mask)
>
> - try to unsynchronize the page
>
>   - if successful, we can let the guest continue and modify the gpte
>
> - emulate the instruction
>
>   - if failed, unshadow the page and let the guest continue
>
> - update any translations that were modified by the instruction

invlpg handling:

> - walk the shadow page hierarchy and drop affected translations
>
> - try to reinstantiate the indicated translation in the hope that the guest will use it in the near future

Guest control register updates:

- mov to cr3

  - look up new shadow roots

  - synchronize newly reachable shadow pages

- mov to cr0/cr4/efer

  - set up mmu context for new paging mode

  - look up new shadow roots

  - synchronize newly reachable shadow pages

Host translation updates:

> - mmu notifier called with updated hva
>
> - look up affected sptes through reverse map
>
> - drop (or update) translations

<a id="rst-emulating-cr0-wp"></a>

## Emulating cr0.wp

If tdp is not enabled, the host must keep cr0.wp=1 so page write protection works for the guest kernel, not guest userspace.  When the guest cr0.wp=1, this does not present a problem.  However when the guest cr0.wp=0, we cannot map the permissions for gpte.u=1, gpte.w=0 to any spte (the semantics require allowing any guest kernel access plus user read access).

We handle this by mapping the permissions to two possible sptes, depending on fault type:

- kernel write fault: spte.u=0, spte.w=1 (allows full kernel access, disallows user access)

- read fault: spte.u=1, spte.w=0 (allows full read access, disallows kernel write access)

(user write faults generate a \#PF)

In the first case there are two additional complications:

- if CR4.SMEP is enabled: since we've turned the page into a kernel page, the kernel may now execute it.  We handle this by also setting spte.nx. If we get a user fetch or read fault, we'll change spte.u=1 and spte.nx=gpte.nx back.  For this to work, KVM forces EFER.NX to 1 when shadow paging is in use.

- if CR4.SMAP is disabled: since the page has been changed to a kernel page, it can not be reused when CR4.SMAP is enabled. We set CR4.SMAP &amp;&amp; \!CR0.WP into shadow page's role to avoid this case. Note, here we do not care the case that CR4.SMAP is enabled since KVM will directly inject \#PF to guest due to failed permission check.

To prevent an spte that was converted into a kernel page with cr0.wp=0 from being written by the kernel after cr0.wp has changed to 1, we make the value of cr0.wp part of the page role.  This means that an spte created with one value of cr0.wp cannot be used when cr0.wp has a different value - it will simply be missed by the shadow page lookup code.  A similar issue exists when an spte created with cr0.wp=0 and cr4.smep=0 is used after changing cr4.smep to 1.  To avoid this, the value of \!cr0.wp &amp;&amp; cr4.smep is also made a part of the page role.

<a id="rst-large-pages"></a>

## Large pages

The mmu supports all combinations of large and small guest and host pages. Supported page sizes include 4k, 2M, 4M, and 1G.  4M pages are treated as two separate 2M pages, on both guest and host, since the mmu always uses PAE paging.

To instantiate a large spte, four constraints must be satisfied:

- the spte must point to a large host page

- the guest pte must be a large pte of at least equivalent size (if tdp is enabled, there is no guest pte and this condition is satisfied)

- if the spte will be writeable, the large page frame may not overlap any write-protected pages

- the guest page must be wholly contained by a single memory slot

To check the last two conditions, the mmu maintains a -&gt;disallow_lpage set of arrays for each memory slot and large page size.  Every write protected page causes its disallow_lpage to be incremented, thus preventing instantiation of a large spte.  The frames at the end of an unaligned memory slot have artificially inflated -&gt;disallow_lpages so they can never be instantiated.

<a id="rst-fast-invalidation-of-mmio-sptes"></a>

## Fast invalidation of MMIO sptes

As mentioned in "Reaction to events" above, kvm will cache MMIO information in leaf sptes.  When a new memslot is added or an existing memslot is changed, this information may become stale and needs to be invalidated.  This also needs to hold the MMU lock while walking all shadow pages, and is made more scalable with a similar technique.

MMIO sptes have a few spare bits, which are used to store a generation number.  The global generation number is stored in kvm_memslots(kvm)-&gt;generation, and increased whenever guest memory info changes.

When KVM finds an MMIO spte, it checks the generation number of the spte. If the generation number of the spte does not equal the global generation number, it will ignore the cached MMIO information and handle the page fault through the slow path.

Since only 18 bits are used to store generation-number on mmio spte, all pages are zapped when there is an overflow.

Unfortunately, a single memory access might access kvm_memslots(kvm) multiple times, the last one happening when the generation number is retrieved and stored into the MMIO spte.  Thus, the MMIO spte might be created based on out-of-date information, but with an up-to-date generation number.

To avoid this, the generation number is incremented again after synchronize_srcu returns; thus, bit 63 of kvm_memslots(kvm)-&gt;generation set to 1 only during a memslot update, while some SRCU readers might be using the old copy.  We do not want to use an MMIO sptes created with an odd generation number, and we can do this without losing a bit in the MMIO spte.  The "update in-progress" bit of the generation is not stored in MMIO spte, and is so is implicitly zero when the generation is extracted out of the spte.  If KVM is unlucky and creates an MMIO spte while an update is in-progress, the next access to the spte will always be a cache miss.  For example, a subsequent access during the update window will miss due to the in-progress flag diverging, while an access after the update window closes will have a higher generation number (as compared to the spte).

<a id="rst-further-reading"></a>

## Further reading

- NPT presentation from KVM Forum 2008 [https://www.linux-kvm.org/images/c/c8/KvmForum2008%24kdf2008_21.pdf](<https://www.linux-kvm.org/images/c/c8/KvmForum2008%24kdf2008_21.pdf>)

---

# KVM-specific MSRs

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> KVM makes use of some custom MSRs to service some requests.

<a id="rst-kvm-specific-msrs"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Glauber Costa &lt;[glommer@redhat.com](<mailto:glommer@redhat.com>)&gt;, Red Hat Inc, 2010

KVM makes use of some custom MSRs to service some requests.

Custom MSRs have a range reserved for them, that goes from 0x4b564d00 to 0x4b564dff. There are MSRs outside this area, but they are deprecated and their use is discouraged.

<a id="rst-custom-msr-list"></a>

## Custom MSR list

The current supported Custom MSR list is:

- **MSR_KVM_WALL_CLOCK_NEW:**

  0x4b564d00

- **data:**

  4-byte alignment physical address of a memory area which must be in guest RAM. This memory is expected to hold a copy of the following structure:



  ```text
  struct pvclock_wall_clock {
         u32   version;
         u32   sec;
         u32   nsec;
   } __attribute__((__packed__));
  ```

  whose data will be filled in by the hypervisor. The hypervisor is only guaranteed to update this data at the moment of MSR write. Users that want to reliably query this information more than once have to write more than once to this MSR. Fields have the following meanings:

  - **version:**

    guest has to check version before and after grabbing time information and check that they are both equal and even. An odd version indicates an in-progress update.

  - **sec:**

    number of seconds for wallclock at time of boot.

  - **nsec:**

    number of nanoseconds for wallclock at time of boot.

  In order to get the current wallclock time, the system_time from MSR_KVM_SYSTEM_TIME_NEW needs to be added.

  Note that although MSRs are per-CPU entities, the effect of this particular MSR is global.

  Availability of this MSR must be checked via bit 3 in 0x4000001 cpuid leaf prior to usage.

- **MSR_KVM_SYSTEM_TIME_NEW:**

  0x4b564d01

- **data:**

  4-byte aligned physical address of a memory area which must be in guest RAM, plus an enable bit in bit 0. This memory is expected to hold a copy of the following structure:



  ```text
  struct pvclock_vcpu_time_info {
        u32   version;
        u32   pad0;
        u64   tsc_timestamp;
        u64   system_time;
        u32   tsc_to_system_mul;
        s8    tsc_shift;
        u8    flags;
        u8    pad[2];
  } __attribute__((__packed__)); /* 32 bytes */
  ```

  whose data will be filled in by the hypervisor periodically. Only one write, or registration, is needed for each VCPU. The interval between updates of this structure is arbitrary and implementation-dependent. The hypervisor may update this structure at any time it sees fit until anything with bit0 == 0 is written to it.

  Fields have the following meanings:

  - **version:**

    guest has to check version before and after grabbing time information and check that they are both equal and even. An odd version indicates an in-progress update.

  - **tsc_timestamp:**

    the tsc value at the current VCPU at the time of the update of this structure. Guests can subtract this value from current tsc to derive a notion of elapsed time since the structure update.

  - **system_time:**

    a host notion of monotonic time, including sleep time at the time this structure was last updated. Unit is nanoseconds.

  - **tsc_to_system_mul:**

    multiplier to be used when converting tsc-related quantity to nanoseconds

  - **tsc_shift:**

    shift to be used when converting tsc-related quantity to nanoseconds. This shift will ensure that multiplication with tsc_to_system_mul does not overflow. A positive value denotes a left shift, a negative value a right shift.

    The conversion from tsc to nanoseconds involves an additional right shift by 32 bits. With this information, guests can derive per-CPU time by doing:



    ```text
    time = (current_tsc - tsc_timestamp)
    if (tsc_shift >= 0)
            time <<= tsc_shift;
    else
            time >>= -tsc_shift;
    time = (time * tsc_to_system_mul) >> 32
    time = time + system_time
    ```

  - **flags:**

    bits in this field indicate extended capabilities coordinated between the guest and the hypervisor. Availability of specific flags has to be checked in 0x40000001 cpuid leaf. Current flags are:


    <table>
    <tbody>
    <tr>
    <td>


    flag bit

    </td>
    <td>


    cpuid bit

    </td>
    <td>


    meaning

    </td>
    </tr>
    <tr>
    <td>


    0

    </td>
    <td>


    24

    </td>
    <td>


    time measures taken across multiple cpus are guaranteed to be monotonic

    </td>
    </tr>
    <tr>
    <td>


    1

    </td>
    <td>


    N/A

    </td>
    <td>


    guest vcpu has been paused by the host See 4.70 in api.txt

    </td>
    </tr>
    </tbody>
    </table>

  Availability of this MSR must be checked via bit 3 in 0x4000001 cpuid leaf prior to usage.

- **MSR_KVM_WALL_CLOCK:**

  0x11

- **data and functioning:**

  same as MSR_KVM_WALL_CLOCK_NEW. Use that instead.

  This MSR falls outside the reserved KVM range and may be removed in the future. Its usage is deprecated.

  Availability of this MSR must be checked via bit 0 in 0x4000001 cpuid leaf prior to usage.

- **MSR_KVM_SYSTEM_TIME:**

  0x12

- **data and functioning:**

  same as MSR_KVM_SYSTEM_TIME_NEW. Use that instead.

  This MSR falls outside the reserved KVM range and may be removed in the future. Its usage is deprecated.

  Availability of this MSR must be checked via bit 0 in 0x4000001 cpuid leaf prior to usage.

  The suggested algorithm for detecting kvmclock presence is then:



  ```text
  if (!kvm_para_available())    /* refer to cpuid.txt */
          return NON_PRESENT;

  flags = cpuid_eax(0x40000001);
  if (flags & 3) {
          msr_kvm_system_time = MSR_KVM_SYSTEM_TIME_NEW;
          msr_kvm_wall_clock = MSR_KVM_WALL_CLOCK_NEW;
          return PRESENT;
  } else if (flags & 0) {
          msr_kvm_system_time = MSR_KVM_SYSTEM_TIME;
          msr_kvm_wall_clock = MSR_KVM_WALL_CLOCK;
          return PRESENT;
  } else
          return NON_PRESENT;
  ```

- **MSR_KVM_ASYNC_PF_EN:**

  0x4b564d02

- **data:**

  Asynchronous page fault (APF) control MSR.

  Bits 63-6 hold 64-byte aligned physical address of a 64 byte memory area which must be in guest RAM. This memory is expected to hold the following structure:



  ```text
  struct kvm_vcpu_pv_apf_data {
        /* Used for 'page not present' events delivered via #PF */
        __u32 flags;

        /* Used for 'page ready' events delivered via interrupt notification */
        __u32 token;

        __u8 pad[56];
  };
  ```

  Bits 5-4 of the MSR are reserved and should be zero. Bit 0 is set to 1 when asynchronous page faults are enabled on the vcpu, 0 when disabled. Bit 1 is 1 if asynchronous page faults can be injected when vcpu is in cpl == 0. Bit 2 is 1 if asynchronous page faults are delivered to L1 as \#PF vmexits.  Bit 2 can be set only if KVM_FEATURE_ASYNC_PF_VMEXIT is present in CPUID. Bit 3 enables interrupt based delivery of 'page ready' events. Bit 3 can only be set if KVM_FEATURE_ASYNC_PF_INT is present in CPUID.

  'Page not present' events are currently always delivered as synthetic \#PF exception. During delivery of these events APF CR2 register contains a token that will be used to notify the guest when missing page becomes available. Also, to make it possible to distinguish between real \#PF and APF, first 4 bytes of 64 byte memory location ('flags') will be written to by the hypervisor at the time of injection. Only first bit of 'flags' is currently supported, when set, it indicates that the guest is dealing with asynchronous 'page not present' event. If during a page fault APF 'flags' is '0' it means that this is regular page fault. Guest is supposed to clear 'flags' when it is done handling \#PF exception so the next event can be delivered.

  Note, since APF 'page not present' events use the same exception vector as regular page fault, guest must reset 'flags' to '0' before it does something that can generate normal page fault.

  Bytes 4-7 of 64 byte memory location ('token') will be written to by the hypervisor at the time of APF 'page ready' event injection. The content of these bytes is a token which was previously delivered in CR2 as 'page not present' event. The event indicates the page is now available. Guest is supposed to write '0' to 'token' when it is done handling 'page ready' event and to write '1' to MSR_KVM_ASYNC_PF_ACK after clearing the location; writing to the MSR forces KVM to re-scan its queue and deliver the next pending notification.

  Note, MSR_KVM_ASYNC_PF_INT MSR specifying the interrupt vector for 'page ready' APF delivery needs to be written to before enabling APF mechanism in MSR_KVM_ASYNC_PF_EN or interrupt \#0 can get injected. The MSR is available if KVM_FEATURE_ASYNC_PF_INT is present in CPUID.

  Note, previously, 'page ready' events were delivered via the same \#PF exception as 'page not present' events but this is now deprecated. If bit 3 (interrupt based delivery) is not set APF events are not delivered.

  If APF is disabled while there are outstanding APFs, they will not be delivered.

  Currently 'page ready' APF events will be always delivered on the same vcpu as 'page not present' event was, but guest should not rely on that.

- **MSR_KVM_STEAL_TIME:**

  0x4b564d03

- **data:**

  64-byte alignment physical address of a memory area which must be in guest RAM, plus an enable bit in bit 0. This memory is expected to hold a copy of the following structure:



  ```text
  struct kvm_steal_time {
        __u64 steal;
        __u32 version;
        __u32 flags;
        __u8  preempted;
        __u8  u8_pad[3];
        __u32 pad[11];
  }
  ```

  whose data will be filled in by the hypervisor periodically. Only one write, or registration, is needed for each VCPU. The interval between updates of this structure is arbitrary and implementation-dependent. The hypervisor may update this structure at any time it sees fit until anything with bit0 == 0 is written to it. Guest is required to make sure this structure is initialized to zero.

  Fields have the following meanings:

  - **version:**

    a sequence counter. In other words, guest has to check this field before and after grabbing time information and make sure they are both equal and even. An odd version indicates an in-progress update.

  - **flags:**

    At this point, always zero. May be used to indicate changes in this structure in the future.

  - **steal:**

    the amount of time in which this vCPU did not run, in nanoseconds. Time during which the vcpu is idle, will not be reported as steal time.

  - **preempted:**

    indicate the vCPU who owns this struct is running or not. Non-zero values mean the vCPU has been preempted. Zero means the vCPU is not preempted. NOTE, it is always zero if the the hypervisor doesn't support this field.

- **MSR_KVM_EOI_EN:**

  0x4b564d04

- **data:**

  Bit 0 is 1 when PV end of interrupt is enabled on the vcpu; 0 when disabled.  Bit 1 is reserved and must be zero.  When PV end of interrupt is enabled (bit 0 set), bits 63-2 hold a 4-byte aligned physical address of a 4 byte memory area which must be in guest RAM and must be zeroed.

  The first, least significant bit of 4 byte memory location will be written to by the hypervisor, typically at the time of interrupt injection.  Value of 1 means that guest can skip writing EOI to the apic (using MSR or MMIO write); instead, it is sufficient to signal EOI by clearing the bit in guest memory - this location will later be polled by the hypervisor. Value of 0 means that the EOI write is required.

  It is always safe for the guest to ignore the optimization and perform the APIC EOI write anyway.

  Hypervisor is guaranteed to only modify this least significant bit while in the current VCPU context, this means that guest does not need to use either lock prefix or memory ordering primitives to synchronise with the hypervisor.

  However, hypervisor can set and clear this memory bit at any time: therefore to make sure hypervisor does not interrupt the guest and clear the least significant bit in the memory area in the window between guest testing it to detect whether it can skip EOI apic write and between guest clearing it to signal EOI to the hypervisor, guest must both read the least significant bit in the memory area and clear it using a single CPU instruction, such as test and clear, or compare and exchange.

- **MSR_KVM_POLL_CONTROL:**

  0x4b564d05

  Control host-side polling.

- **data:**

  Bit 0 enables (1) or disables (0) host-side HLT polling logic.

  KVM guests can request the host not to poll on HLT, for example if they are performing polling themselves.

- **MSR_KVM_ASYNC_PF_INT:**

  0x4b564d06

- **data:**

  Second asynchronous page fault (APF) control MSR.

  Bits 0-7: APIC vector for delivery of 'page ready' APF events. Bits 8-63: Reserved

  Interrupt vector for asynchnonous 'page ready' notifications delivery. The vector has to be set up before asynchronous page fault mechanism is enabled in MSR_KVM_ASYNC_PF_EN.  The MSR is only available if KVM_FEATURE_ASYNC_PF_INT is present in CPUID.

- **MSR_KVM_ASYNC_PF_ACK:**

  0x4b564d07

- **data:**

  Asynchronous page fault (APF) acknowledgment.

  When the guest is done processing 'page ready' APF event and 'token' field in 'struct kvm_vcpu_pv_apf_data' is cleared it is supposed to write '1' to bit 0 of the MSR, this causes the host to re-scan its queue and check if there are more notifications pending. The MSR is available if KVM_FEATURE_ASYNC_PF_INT is present in CPUID.

- **MSR_KVM_MIGRATION_CONTROL:**

  0x4b564d08

- **data:**

  This MSR is available if KVM_FEATURE_MIGRATION_CONTROL is present in CPUID.  Bit 0 represents whether live migration of the guest is allowed.

  When a guest is started, bit 0 will be 0 if the guest has encrypted memory and 1 if the guest does not have encrypted memory.  If the guest is communicating page encryption status to the host using the `KVM_HC_MAP_GPA_RANGE` hypercall, it can set bit 0 in this MSR to allow live migration of the guest.

---

# Nested VMX

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> On Intel processors, KVM uses Intel's VMX (Virtual-Machine eXtensions) to easily and efficiently run guest operating systems. Normally, these guests cannot themselves be hypervisors running their own guests, because in VMX, guests cannot…

<a id="rst-nested-vmx"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-overview"></a>

## Overview

On Intel processors, KVM uses Intel's VMX (Virtual-Machine eXtensions) to easily and efficiently run guest operating systems. Normally, these guests *cannot* themselves be hypervisors running their own guests, because in VMX, guests cannot use VMX instructions.

The "Nested VMX" feature adds this missing capability - of running guest hypervisors (which use VMX) with their own nested guests. It does so by allowing a guest to use VMX instructions, and correctly and efficiently emulating them using the single level of VMX available in the hardware.

We describe in much greater detail the theory behind the nested VMX feature, its implementation and its performance characteristics, in the OSDI 2010 paper "The Turtles Project: Design and Implementation of Nested Virtualization", available at:

> [https://www.usenix.org/events/osdi10/tech/full_papers/Ben-Yehuda.pdf](<https://www.usenix.org/events/osdi10/tech/full_papers/Ben-Yehuda.pdf>)

<a id="rst-terminology"></a>

## Terminology

Single-level virtualization has two levels - the host (KVM) and the guests. In nested virtualization, we have three levels: The host (KVM), which we call L0, the guest hypervisor, which we call L1, and its nested guest, which we call L2.

<a id="rst-running-nested-vmx"></a>

## Running nested VMX

The nested VMX feature is enabled by default since Linux kernel v4.20. For older Linux kernel, it can be enabled by giving the "nested=1" option to the kvm-intel module.

No modifications are required to user space (qemu). However, qemu's default emulated CPU type (qemu64) does not list the "VMX" CPU feature, so it must be explicitly enabled, by giving qemu one of the following options:

> - cpu host              (emulated CPU has all features of the real CPU)
>
> - cpu qemu64,+vmx       (add just the vmx feature to a named CPU type)

<a id="rst-abis"></a>

## ABIs

Nested VMX aims to present a standard and (eventually) fully-functional VMX implementation for the a guest hypervisor to use. As such, the official specification of the ABI that it provides is Intel's VMX specification, namely volume 3B of their "Intel 64 and IA-32 Architectures Software Developer's Manual". Not all of VMX's features are currently fully supported, but the goal is to eventually support them all, starting with the VMX features which are used in practice by popular hypervisors (KVM and others).

As a VMX implementation, nested VMX presents a VMCS structure to L1. As mandated by the spec, other than the two fields revision_id and abort, this structure is *opaque* to its user, who is not supposed to know or care about its internal structure. Rather, the structure is accessed through the VMREAD and VMWRITE instructions. Still, for debugging purposes, KVM developers might be interested to know the internals of this structure; This is struct vmcs12 from arch/x86/kvm/vmx.c.

The name "vmcs12" refers to the VMCS that L1 builds for L2. In the code we also have "vmcs01", the VMCS that L0 built for L1, and "vmcs02" is the VMCS which L0 builds to actually run L2 - how this is done is explained in the aforementioned paper.

For convenience, we repeat the content of struct vmcs12 here. If the internals of this structure changes, this can break live migration across KVM versions. VMCS12_REVISION (from vmx.c) should be changed if struct vmcs12 or its inner struct shadow_vmcs is ever changed.



```text
typedef u64 natural_width;
struct __packed vmcs12 {
        /* According to the Intel spec, a VMCS region must start with
         * these two user-visible fields */
        u32 revision_id;
        u32 abort;

        u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
        u32 padding[7]; /* room for future expansion */

        u64 io_bitmap_a;
        u64 io_bitmap_b;
        u64 msr_bitmap;
        u64 vm_exit_msr_store_addr;
        u64 vm_exit_msr_load_addr;
        u64 vm_entry_msr_load_addr;
        u64 tsc_offset;
        u64 virtual_apic_page_addr;
        u64 apic_access_addr;
        u64 ept_pointer;
        u64 guest_physical_address;
        u64 vmcs_link_pointer;
        u64 guest_ia32_debugctl;
        u64 guest_ia32_pat;
        u64 guest_ia32_efer;
        u64 guest_pdptr0;
        u64 guest_pdptr1;
        u64 guest_pdptr2;
        u64 guest_pdptr3;
        u64 host_ia32_pat;
        u64 host_ia32_efer;
        u64 padding64[8]; /* room for future expansion */
        natural_width cr0_guest_host_mask;
        natural_width cr4_guest_host_mask;
        natural_width cr0_read_shadow;
        natural_width cr4_read_shadow;
        natural_width dead_space[4]; /* Last remnants of cr3_target_value[0-3]. */
        natural_width exit_qualification;
        natural_width guest_linear_address;
        natural_width guest_cr0;
        natural_width guest_cr3;
        natural_width guest_cr4;
        natural_width guest_es_base;
        natural_width guest_cs_base;
        natural_width guest_ss_base;
        natural_width guest_ds_base;
        natural_width guest_fs_base;
        natural_width guest_gs_base;
        natural_width guest_ldtr_base;
        natural_width guest_tr_base;
        natural_width guest_gdtr_base;
        natural_width guest_idtr_base;
        natural_width guest_dr7;
        natural_width guest_rsp;
        natural_width guest_rip;
        natural_width guest_rflags;
        natural_width guest_pending_dbg_exceptions;
        natural_width guest_sysenter_esp;
        natural_width guest_sysenter_eip;
        natural_width host_cr0;
        natural_width host_cr3;
        natural_width host_cr4;
        natural_width host_fs_base;
        natural_width host_gs_base;
        natural_width host_tr_base;
        natural_width host_gdtr_base;
        natural_width host_idtr_base;
        natural_width host_ia32_sysenter_esp;
        natural_width host_ia32_sysenter_eip;
        natural_width host_rsp;
        natural_width host_rip;
        natural_width paddingl[8]; /* room for future expansion */
        u32 pin_based_vm_exec_control;
        u32 cpu_based_vm_exec_control;
        u32 exception_bitmap;
        u32 page_fault_error_code_mask;
        u32 page_fault_error_code_match;
        u32 cr3_target_count;
        u32 vm_exit_controls;
        u32 vm_exit_msr_store_count;
        u32 vm_exit_msr_load_count;
        u32 vm_entry_controls;
        u32 vm_entry_msr_load_count;
        u32 vm_entry_intr_info_field;
        u32 vm_entry_exception_error_code;
        u32 vm_entry_instruction_len;
        u32 tpr_threshold;
        u32 secondary_vm_exec_control;
        u32 vm_instruction_error;
        u32 vm_exit_reason;
        u32 vm_exit_intr_info;
        u32 vm_exit_intr_error_code;
        u32 idt_vectoring_info_field;
        u32 idt_vectoring_error_code;
        u32 vm_exit_instruction_len;
        u32 vmx_instruction_info;
        u32 guest_es_limit;
        u32 guest_cs_limit;
        u32 guest_ss_limit;
        u32 guest_ds_limit;
        u32 guest_fs_limit;
        u32 guest_gs_limit;
        u32 guest_ldtr_limit;
        u32 guest_tr_limit;
        u32 guest_gdtr_limit;
        u32 guest_idtr_limit;
        u32 guest_es_ar_bytes;
        u32 guest_cs_ar_bytes;
        u32 guest_ss_ar_bytes;
        u32 guest_ds_ar_bytes;
        u32 guest_fs_ar_bytes;
        u32 guest_gs_ar_bytes;
        u32 guest_ldtr_ar_bytes;
        u32 guest_tr_ar_bytes;
        u32 guest_interruptibility_info;
        u32 guest_activity_state;
        u32 guest_sysenter_cs;
        u32 host_ia32_sysenter_cs;
        u32 padding32[8]; /* room for future expansion */
        u16 virtual_processor_id;
        u16 guest_es_selector;
        u16 guest_cs_selector;
        u16 guest_ss_selector;
        u16 guest_ds_selector;
        u16 guest_fs_selector;
        u16 guest_gs_selector;
        u16 guest_ldtr_selector;
        u16 guest_tr_selector;
        u16 host_es_selector;
        u16 host_cs_selector;
        u16 host_ss_selector;
        u16 host_ds_selector;
        u16 host_fs_selector;
        u16 host_gs_selector;
        u16 host_tr_selector;
};
```

<a id="rst-authors"></a>

## Authors

- **These patches were written by:**

  - Abel Gordon, abelg &lt;at&gt; il.ibm.com

  - Nadav Har'El, nyh &lt;at&gt; il.ibm.com

  - Orit Wasserman, oritw &lt;at&gt; il.ibm.com

  - Ben-Ami Yassor, benami &lt;at&gt; il.ibm.com

  - Muli Ben-Yehuda, muli &lt;at&gt; il.ibm.com

- **With contributions by:**

  - Anthony Liguori, aliguori &lt;at&gt; us.ibm.com

  - Mike Day, mdday &lt;at&gt; us.ibm.com

  - Michael Factor, factor &lt;at&gt; il.ibm.com

  - Zvi Dubitzky, dubi &lt;at&gt; il.ibm.com

- **And valuable reviews by:**

  - Avi Kivity, avi &lt;at&gt; redhat.com

  - Gleb Natapov, gleb &lt;at&gt; redhat.com

  - Marcelo Tosatti, mtosatti &lt;at&gt; redhat.com

  - Kevin Tian, kevin.tian &lt;at&gt; intel.com

  - and others.

---

# Running nested guests with KVM

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> A nested guest is the ability to run a guest inside another guest (it can be KVM-based or a different hypervisor). The straightforward example is a KVM guest that in turn runs on a KVM guest (the rest of this document is built on this…

<a id="rst-running-nested-guests-with-kvm"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

A nested guest is the ability to run a guest inside another guest (it can be KVM-based or a different hypervisor).  The straightforward example is a KVM guest that in turn runs on a KVM guest (the rest of this document is built on this example):



```text
        .----------------.  .----------------.
        |                |  |                |
        |      L2        |  |      L2        |
        | (Nested Guest) |  | (Nested Guest) |
        |                |  |                |
        |----------------'--'----------------|
        |                                    |
        |       L1 (Guest Hypervisor)        |
        |          KVM (/dev/kvm)            |
        |                                    |
.------------------------------------------------------.
|                 L0 (Host Hypervisor)                 |
|                    KVM (/dev/kvm)                    |
|------------------------------------------------------|
|        Hardware (with virtualization extensions)     |
'------------------------------------------------------'
```

Terminology:

- L0 – level-0; the bare metal host, running KVM

- L1 – level-1 guest; a VM running on L0; also called the "guest hypervisor", as it itself is capable of running KVM.

- L2 – level-2 guest; a VM running on L1, this is the "nested guest"

> [!NOTE]
>
> The above diagram is modelled after the x86 architecture; s390x, ppc64 and other architectures are likely to have a different design for nesting.
>
> For example, s390x always has an LPAR (LogicalPARtition) hypervisor running on bare metal, adding another layer and resulting in at least four levels in a nested setup — L0 (bare metal, running the LPAR hypervisor), L1 (host hypervisor), L2 (guest hypervisor), L3 (nested guest).
>
> This document will stick with the three-level terminology (L0, L1, and L2) for all architectures; and will largely focus on x86.

<a id="rst-use-cases"></a>

## Use Cases

There are several scenarios where nested KVM can be useful, to name a few:

- As a developer, you want to test your software on different operating systems (OSes).  Instead of renting multiple VMs from a Cloud Provider, using nested KVM lets you rent a large enough "guest hypervisor" (level-1 guest).  This in turn allows you to create multiple nested guests (level-2 guests), running different OSes, on which you can develop and test your software.

- Live migration of "guest hypervisors" and their nested guests, for load balancing, disaster recovery, etc.

- VM image creation tools (e.g. `virt-install`,  etc) often run their own VM, and users expect these to work inside a VM.

- Some OSes use virtualization internally for security (e.g. to let applications run safely in isolation).

<a id="rst-enabling-nested-x86"></a>

## Enabling "nested" (x86)

From Linux kernel v4.20 onwards, the `nested` KVM parameter is enabled by default for Intel and AMD.  (Though your Linux distribution might override this default.)

In case you are running a Linux kernel older than v4.19, to enable nesting, set the `nested` KVM module parameter to `Y` or `1`.  To persist this setting across reboots, you can add it in a config file, as shown below:

1. On the bare metal host (L0), list the kernel modules and ensure that the KVM modules:



   ```text
   $ lsmod | grep -i kvm
   kvm_intel             133627  0
   kvm                   435079  1 kvm_intel
   ```

2. Show information for `kvm_intel` module:



   ```text
   $ modinfo kvm_intel | grep -i nested
   parm:           nested:bool
   ```

3. For the nested KVM configuration to persist across reboots, place the below in `/etc/modprobed/kvm_intel.conf` (create the file if it doesn't exist):



   ```text
   $ cat /etc/modprobe.d/kvm_intel.conf
   options kvm-intel nested=y
   ```

4. Unload and re-load the KVM Intel module:



   ```text
   $ sudo rmmod kvm-intel
   $ sudo modprobe kvm-intel
   ```

5. Verify if the `nested` parameter for KVM is enabled:



   ```text
   $ cat /sys/module/kvm_intel/parameters/nested
   Y
   ```

For AMD hosts, the process is the same as above, except that the module name is `kvm-amd`.

<a id="rst-additional-nested-related-kernel-parameters-x86"></a>

## Additional nested-related kernel parameters (x86)

If your hardware is sufficiently advanced (Intel Haswell processor or higher, which has newer hardware virt extensions), the following additional features will also be enabled by default: "Shadow VMCS (Virtual Machine Control Structure)", APIC Virtualization on your bare metal host (L0).  Parameters for Intel hosts:



```text
$ cat /sys/module/kvm_intel/parameters/enable_shadow_vmcs
Y

$ cat /sys/module/kvm_intel/parameters/enable_apicv
Y

$ cat /sys/module/kvm_intel/parameters/ept
Y
```

> [!NOTE]
>
> If you suspect your L2 (i.e. nested guest) is running slower, ensure the above are enabled (particularly `enable_shadow_vmcs` and `ept`).

<a id="rst-starting-a-nested-guest-x86"></a>

## Starting a nested guest (x86)

Once your bare metal host (L0) is configured for nesting, you should be able to start an L1 guest with:



```text
$ qemu-kvm -cpu host [...]
```

The above will pass through the host CPU's capabilities as-is to the guest, or for better live migration compatibility, use a named CPU model supported by QEMU. e.g.:



```text
$ qemu-kvm -cpu Haswell-noTSX-IBRS,vmx=on
```

then the guest hypervisor will subsequently be capable of running a nested guest with accelerated KVM.

<a id="rst-enabling-nested-s390x"></a>

## Enabling "nested" (s390x)

1. On the host hypervisor (L0), enable the `nested` parameter on s390x:



   ```text
   $ rmmod kvm
   $ modprobe kvm nested=1
   ```

> [!NOTE]
>
> On s390x, the kernel parameter `hpage` is mutually exclusive with the `nested` parameter — i.e. to be able to enable `nested`, the `hpage` parameter *must* be disabled.

2. The guest hypervisor (L1) must be provided with the `sie` CPU feature — with QEMU, this can be done by using "host passthrough" (via the command-line `-cpu host`).

3. Now the KVM module can be loaded in the L1 (guest hypervisor):



   ```text
   $ modprobe kvm
   ```

<a id="rst-live-migration-with-nested-kvm"></a>

## Live migration with nested KVM

Migrating an L1 guest, with a  *live* nested guest in it, to another bare metal host, works as of Linux kernel 5.3 and QEMU 4.2.0 for Intel x86 systems, and even on older versions for s390x.

On AMD systems, once an L1 guest has started an L2 guest, the L1 guest should no longer be migrated or saved (refer to QEMU documentation on "savevm"/"loadvm") until the L2 guest shuts down.  Attempting to migrate or save-and-load an L1 guest while an L2 guest is running will result in undefined behavior.  You might see a `kernel BUG!` entry in `dmesg`, a kernel 'oops', or an outright kernel panic.  Such a migrated or loaded L1 guest can no longer be considered stable or secure, and must be restarted. Migrating an L1 guest merely configured to support nesting, while not actually running L2 guests, is expected to function normally even on AMD systems but may fail once guests are started.

Migrating an L2 guest is always expected to succeed, so all the following scenarios should work even on AMD systems:

- Migrating a nested guest (L2) to another L1 guest on the *same* bare metal host.

- Migrating a nested guest (L2) to another L1 guest on a *different* bare metal host.

- Migrating a nested guest (L2) to a bare metal host.

<a id="rst-reporting-bugs-from-nested-setups"></a>

## Reporting bugs from nested setups

Debugging "nested" problems can involve sifting through log files across L0, L1 and L2; this can result in tedious back-n-forth between the bug reporter and the bug fixer.

- Mention that you are in a "nested" setup.  If you are running any kind of "nesting" at all, say so.  Unfortunately, this needs to be called out because when reporting bugs, people tend to forget to even *mention* that they're using nested virtualization.

- Ensure you are actually running KVM on KVM.  Sometimes people do not have KVM enabled for their guest hypervisor (L1), which results in them running with pure emulation or what QEMU calls it as "TCG", but they think they're running nested KVM.  Thus confusing "nested Virt" (which could also mean, QEMU on KVM) with "nested KVM" (KVM on KVM).

<a id="rst-information-to-collect-generic"></a>

### Information to collect (generic)

The following is not an exhaustive list, but a very good starting point:

> - Kernel, libvirt, and QEMU version from L0
>
> - Kernel, libvirt and QEMU version from L1
>
> - QEMU command-line of L1 -- when using libvirt, you'll find it here: `/var/log/libvirt/qemu/instance.log`
>
> - QEMU command-line of L2 -- as above, when using libvirt, get the complete libvirt-generated QEMU command-line
>
> - `cat /sys/cpuinfo` from L0
>
> - `cat /sys/cpuinfo` from L1
>
> - `lscpu` from L0
>
> - `lscpu` from L1
>
> - Full `dmesg` output from L0
>
> - Full `dmesg` output from L1

<a id="rst-x86-specific-info-to-collect"></a>

### x86-specific info to collect

Both the below commands, `x86info` and `dmidecode`, should be available on most Linux distributions with the same name:

> - Output of: `x86info -a` from L0
>
> - Output of: `x86info -a` from L1
>
> - Output of: `dmidecode` from L0
>
> - Output of: `dmidecode` from L1

<a id="rst-s390x-specific-info-to-collect"></a>

### s390x-specific info to collect

Along with the earlier mentioned generic details, the below is also recommended:

> - `/proc/sysinfo` from L1; this will also include the info from L0

---

# Timekeeping Virtualization for X86-Based Architectures

_Peios Kernel / Internals / Virtualisation / kvm / x86_

> One of the most complicated parts of the X86 platform, and specifically, the virtualization of this platform is the plethora of timing devices available and the complexity of emulating those devices. In addition, virtualization of time…

<a id="rst-timekeeping-virtualization-for-x86-based-architectures"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

**Author:** Zachary Amsden &lt;[zamsden@redhat.com](<mailto:zamsden@redhat.com>)&gt;

**Copyright:** - **(c)** 2010, Red Hat.  All rights reserved.

<!-- Contents

1) Overview
2) Timing Devices
3) TSC Hardware
4) Virtualization Problems -->

<a id="rst-overview"></a>

## 1. Overview

One of the most complicated parts of the X86 platform, and specifically, the virtualization of this platform is the plethora of timing devices available and the complexity of emulating those devices.  In addition, virtualization of time introduces a new set of challenges because it introduces a multiplexed division of time beyond the control of the guest CPU.

First, we will describe the various timekeeping hardware available, then present some of the problems which arise and solutions available, giving specific recommendations for certain classes of KVM guests.

The purpose of this document is to collect data and information relevant to timekeeping which may be difficult to find elsewhere, specifically, information relevant to KVM and hardware-based virtualization.

<a id="rst-timing-devices"></a>

## 2. Timing Devices

First we discuss the basic hardware devices available.  TSC and the related KVM clock are special enough to warrant a full exposition and are described in the following section.

<a id="rst-i8254-pit"></a>

### 2.1. i8254 - PIT

One of the first timer devices available is the programmable interrupt timer, or PIT.  The PIT has a fixed frequency 1.193182 MHz base clock and three channels which can be programmed to deliver periodic or one-shot interrupts. These three channels can be configured in different modes and have individual counters.  Channel 1 and 2 were not available for general use in the original IBM PC, and historically were connected to control RAM refresh and the PC speaker.  Now the PIT is typically integrated as part of an emulated chipset and a separate physical PIT is not used.

The PIT uses I/O ports 0x40 - 0x43.  Access to the 16-bit counters is done using single or multiple byte access to the I/O ports.  There are 6 modes available, but not all modes are available to all timers, as only timer 2 has a connected gate input, required for modes 1 and 5.  The gate line is controlled by port 61h, bit 0, as illustrated in the following diagram:



```text
--------------             ----------------
|            |           |                |
|  1.1932 MHz|---------->| CLOCK      OUT | ---------> IRQ 0
|    Clock   |   |       |                |
--------------   |    +->| GATE  TIMER 0  |
                 |        ----------------
                 |
                 |        ----------------
                 |       |                |
                 |------>| CLOCK      OUT | ---------> 66.3 KHZ DRAM
                 |       |                |            (aka /dev/null)
                 |    +->| GATE  TIMER 1  |
                 |        ----------------
                 |
                 |        ----------------
                 |       |                |
                 |------>| CLOCK      OUT | ---------> Port 61h, bit 5
                         |                |      |
Port 61h, bit 0 -------->| GATE  TIMER 2  |       \_.----   ____
                          ----------------         _|    )--|LPF|---Speaker
                                                  / *----   \___/
Port 61h, bit 1 ---------------------------------/
```

The timer modes are now described.

- **Mode 0: Single Timeout.**

  This is a one-shot software timeout that counts down when the gate is high (always true for timers 0 and 1).  When the count reaches zero, the output goes high.

- **Mode 1: Triggered One-shot.**

  The output is initially set high.  When the gate line is set high, a countdown is initiated (which does not stop if the gate is lowered), during which the output is set low.  When the count reaches zero, the output goes high.

- **Mode 2: Rate Generator.**

  The output is initially set high.  When the countdown reaches 1, the output goes low for one count and then returns high.  The value is reloaded and the countdown automatically resumes.  If the gate line goes low, the count is halted.  If the output is low when the gate is lowered, the output automatically goes high (this only affects timer 2).

- **Mode 3: Square Wave.**

  This generates a high / low square wave.  The count determines the length of the pulse, which alternates between high and low when zero is reached.  The count only proceeds when gate is high and is automatically reloaded on reaching zero.  The count is decremented twice at each clock to generate a full high / low cycle at the full periodic rate. If the count is even, the clock remains high for N/2 counts and low for N/2 counts; if the clock is odd, the clock is high for (N+1)/2 counts and low for (N-1)/2 counts.  Only even values are latched by the counter, so odd values are not observed when reading.  This is the intended mode for timer 2, which generates sine-like tones by low-pass filtering the square wave output.

- **Mode 4: Software Strobe.**

  After programming this mode and loading the counter, the output remains high until the counter reaches zero.  Then the output goes low for 1 clock cycle and returns high.  The counter is not reloaded. Counting only occurs when gate is high.

- **Mode 5: Hardware Strobe.**

  After programming and loading the counter, the output remains high.  When the gate is raised, a countdown is initiated (which does not stop if the gate is lowered).  When the counter reaches zero, the output goes low for 1 clock cycle and then returns high.  The counter is not reloaded.

In addition to normal binary counting, the PIT supports BCD counting.  The command port, 0x43 is used to set the counter and mode for each of the three timers.

PIT commands, issued to port 0x43, using the following bit encoding:



```text
Bit 7-4: Command (See table below)
Bit 3-1: Mode (000 = Mode 0, 101 = Mode 5, 11X = undefined)
Bit 0  : Binary (0) / BCD (1)
```

Command table:



```text
0000 - Latch Timer 0 count for port 0x40
      sample and hold the count to be read in port 0x40;
      additional commands ignored until counter is read;
      mode bits ignored.

0001 - Set Timer 0 LSB mode for port 0x40
      set timer to read LSB only and force MSB to zero;
      mode bits set timer mode

0010 - Set Timer 0 MSB mode for port 0x40
      set timer to read MSB only and force LSB to zero;
      mode bits set timer mode

0011 - Set Timer 0 16-bit mode for port 0x40
      set timer to read / write LSB first, then MSB;
      mode bits set timer mode

0100 - Latch Timer 1 count for port 0x41 - as described above
0101 - Set Timer 1 LSB mode for port 0x41 - as described above
0110 - Set Timer 1 MSB mode for port 0x41 - as described above
0111 - Set Timer 1 16-bit mode for port 0x41 - as described above

1000 - Latch Timer 2 count for port 0x42 - as described above
1001 - Set Timer 2 LSB mode for port 0x42 - as described above
1010 - Set Timer 2 MSB mode for port 0x42 - as described above
1011 - Set Timer 2 16-bit mode for port 0x42 as described above

1101 - General counter latch
      Latch combination of counters into corresponding ports
      Bit 3 = Counter 2
      Bit 2 = Counter 1
      Bit 1 = Counter 0
      Bit 0 = Unused

1110 - Latch timer status
      Latch combination of counter mode into corresponding ports
      Bit 3 = Counter 2
      Bit 2 = Counter 1
      Bit 1 = Counter 0

      The output of ports 0x40-0x42 following this command will be:

      Bit 7 = Output pin
      Bit 6 = Count loaded (0 if timer has expired)
      Bit 5-4 = Read / Write mode
          01 = MSB only
          10 = LSB only
          11 = LSB / MSB (16-bit)
      Bit 3-1 = Mode
      Bit 0 = Binary (0) / BCD mode (1)
```

<a id="rst-rtc"></a>

### 2.2. RTC

The second device which was available in the original PC was the MC146818 real time clock.  The original device is now obsolete, and usually emulated by the system chipset, sometimes by an HPET and some frankenstein IRQ routing.

The RTC is accessed through CMOS variables, which uses an index register to control which bytes are read.  Since there is only one index register, read of the CMOS and read of the RTC require lock protection (in addition, it is dangerous to allow userspace utilities such as hwclock to have direct RTC access, as they could corrupt kernel reads and writes of CMOS memory).

The RTC generates an interrupt which is usually routed to IRQ 8.  The interrupt can function as a periodic timer, an additional once a day alarm, and can issue interrupts after an update of the CMOS registers by the MC146818 is complete. The type of interrupt is signalled in the RTC status registers.

The RTC will update the current time fields by battery power even while the system is off.  The current time fields should not be read while an update is in progress, as indicated in the status register.

The clock uses a 32.768kHz crystal, so bits 6-4 of register A should be programmed to a 32kHz divider if the RTC is to count seconds.

This is the RAM map originally used for the RTC/CMOS:



```text
Location    Size    Description
------------------------------------------
00h         byte    Current second (BCD)
01h         byte    Seconds alarm (BCD)
02h         byte    Current minute (BCD)
03h         byte    Minutes alarm (BCD)
04h         byte    Current hour (BCD)
05h         byte    Hours alarm (BCD)
06h         byte    Current day of week (BCD)
07h         byte    Current day of month (BCD)
08h         byte    Current month (BCD)
09h         byte    Current year (BCD)
0Ah         byte    Register A
                     bit 7   = Update in progress
                     bit 6-4 = Divider for clock
                                000 = 4.194 MHz
                                001 = 1.049 MHz
                                010 = 32 kHz
                                10X = test modes
                                110 = reset / disable
                                111 = reset / disable
                     bit 3-0 = Rate selection for periodic interrupt
                                000 = periodic timer disabled
                                001 = 3.90625 uS
                                010 = 7.8125 uS
                                011 = .122070 mS
                                100 = .244141 mS
                                   ...
                               1101 = 125 mS
                               1110 = 250 mS
                               1111 = 500 mS
0Bh         byte    Register B
                     bit 7   = Run (0) / Halt (1)
                     bit 6   = Periodic interrupt enable
                     bit 5   = Alarm interrupt enable
                     bit 4   = Update-ended interrupt enable
                     bit 3   = Square wave interrupt enable
                     bit 2   = BCD calendar (0) / Binary (1)
                     bit 1   = 12-hour mode (0) / 24-hour mode (1)
                     bit 0   = 0 (DST off) / 1 (DST enabled)
OCh         byte    Register C (read only)
                     bit 7   = interrupt request flag (IRQF)
                     bit 6   = periodic interrupt flag (PF)
                     bit 5   = alarm interrupt flag (AF)
                     bit 4   = update interrupt flag (UF)
                     bit 3-0 = reserved
ODh         byte    Register D (read only)
                     bit 7   = RTC has power
                     bit 6-0 = reserved
32h         byte    Current century BCD (*)
(*) location vendor specific and now determined from ACPI global tables
```

<a id="rst-apic"></a>

### 2.3. APIC

On Pentium and later processors, an on-board timer is available to each CPU as part of the Advanced Programmable Interrupt Controller.  The APIC is accessed through memory-mapped registers and provides interrupt service to each CPU, used for IPIs and local timer interrupts.

Although in theory the APIC is a safe and stable source for local interrupts, in practice, many bugs and glitches have occurred due to the special nature of the APIC CPU-local memory-mapped hardware.  Beware that CPU errata may affect the use of the APIC and that workarounds may be required.  In addition, some of these workarounds pose unique constraints for virtualization - requiring either extra overhead incurred from extra reads of memory-mapped I/O or additional functionality that may be more computationally expensive to implement.

Since the APIC is documented quite well in the Intel and AMD manuals, we will avoid repetition of the detail here.  It should be pointed out that the APIC timer is programmed through the LVT (local vector timer) register, is capable of one-shot or periodic operation, and is based on the bus clock divided down by the programmable divider register.

<a id="rst-hpet"></a>

### 2.4. HPET

HPET is quite complex, and was originally intended to replace the PIT / RTC support of the X86 PC.  It remains to be seen whether that will be the case, as the de facto standard of PC hardware is to emulate these older devices.  Some systems designated as legacy free may support only the HPET as a hardware timer device.

The HPET spec is rather loose and vague, requiring at least 3 hardware timers, but allowing implementation freedom to support many more.  It also imposes no fixed rate on the timer frequency, but does impose some extremal values on frequency, error and slew.

In general, the HPET is recommended as a high precision (compared to PIT /RTC) time source which is independent of local variation (as there is only one HPET in any given system).  The HPET is also memory-mapped, and its presence is indicated through ACPI tables by the BIOS.

Detailed specification of the HPET is beyond the current scope of this document, as it is also very well documented elsewhere.

<a id="rst-offboard-timers"></a>

### 2.5. Offboard Timers

Several cards, both proprietary (watchdog boards) and commonplace (e1000) have timing chips built into the cards which may have registers which are accessible to kernel or user drivers.  To the author's knowledge, using these to generate a clocksource for a Linux or other kernel has not yet been attempted and is in general frowned upon as not playing by the agreed rules of the game.  Such a timer device would require additional support to be virtualized properly and is not considered important at this time as no known operating system does this.

<a id="rst-tsc-hardware"></a>

## 3. TSC Hardware

The TSC or time stamp counter is relatively simple in theory; it counts instruction cycles issued by the processor, which can be used as a measure of time.  In practice, due to a number of problems, it is the most complicated timekeeping device to use.

The TSC is represented internally as a 64-bit MSR which can be read with the RDMSR, RDTSC, or RDTSCP (when available) instructions.  In the past, hardware limitations made it possible to write the TSC, but generally on old hardware it was only possible to write the low 32-bits of the 64-bit counter, and the upper 32-bits of the counter were cleared.  Now, however, on Intel processors family 0Fh, for models 3, 4 and 6, and family 06h, models e and f, this restriction has been lifted and all 64-bits are writable.  On AMD systems, the ability to write the TSC MSR is not an architectural guarantee.

The TSC is accessible from CPL-0 and conditionally, for CPL &gt; 0 software by means of the CR4.TSD bit, which when enabled, disables CPL &gt; 0 TSC access.

Some vendors have implemented an additional instruction, RDTSCP, which returns atomically not just the TSC, but an indicator which corresponds to the processor number.  This can be used to index into an array of TSC variables to determine offset information in SMP systems where TSCs are not synchronized. The presence of this instruction must be determined by consulting CPUID feature bits.

Both VMX and SVM provide extension fields in the virtualization hardware which allows the guest visible TSC to be offset by a constant.  Newer implementations promise to allow the TSC to additionally be scaled, but this hardware is not yet widely available.

<a id="rst-tsc-synchronization"></a>

### 3.1. TSC synchronization

The TSC is a CPU-local clock in most implementations.  This means, on SMP platforms, the TSCs of different CPUs may start at different times depending on when the CPUs are powered on.  Generally, CPUs on the same die will share the same clock, however, this is not always the case.

The BIOS may attempt to resynchronize the TSCs during the poweron process and the operating system or other system software may attempt to do this as well. Several hardware limitations make the problem worse - if it is not possible to write the full 64-bits of the TSC, it may be impossible to match the TSC in newly arriving CPUs to that of the rest of the system, resulting in unsynchronized TSCs.  This may be done by BIOS or system software, but in practice, getting a perfectly synchronized TSC will not be possible unless all values are read from the same clock, which generally only is possible on single socket systems or those with special hardware support.

<a id="rst-tsc-and-cpu-hotplug"></a>

### 3.2. TSC and CPU hotplug

As touched on already, CPUs which arrive later than the boot time of the system may not have a TSC value that is synchronized with the rest of the system. Either system software, BIOS, or SMM code may actually try to establish the TSC to a value matching the rest of the system, but a perfect match is usually not a guarantee.  This can have the effect of bringing a system from a state where TSC is synchronized back to a state where TSC synchronization flaws, however small, may be exposed to the OS and any virtualization environment.

<a id="rst-tsc-and-multi-socket-numa"></a>

### 3.3. TSC and multi-socket / NUMA

Multi-socket systems, especially large multi-socket systems are likely to have individual clocksources rather than a single, universally distributed clock. Since these clocks are driven by different crystals, they will not have perfectly matched frequency, and temperature and electrical variations will cause the CPU clocks, and thus the TSCs to drift over time.  Depending on the exact clock and bus design, the drift may or may not be fixed in absolute error, and may accumulate over time.

In addition, very large systems may deliberately slew the clocks of individual cores.  This technique, known as spread-spectrum clocking, reduces EMI at the clock frequency and harmonics of it, which may be required to pass FCC standards for telecommunications and computer equipment.

It is recommended not to trust the TSCs to remain synchronized on NUMA or multiple socket systems for these reasons.

<a id="rst-tsc-and-c-states"></a>

### 3.4. TSC and C-states

C-states, or idling states of the processor, especially C1E and deeper sleep states may be problematic for TSC as well.  The TSC may stop advancing in such a state, resulting in a TSC which is behind that of other CPUs when execution is resumed.  Such CPUs must be detected and flagged by the operating system based on CPU and chipset identifications.

The TSC in such a case may be corrected by catching it up to a known external clocksource.

<a id="rst-tsc-frequency-change-p-states"></a>

### 3.5. TSC frequency change / P-states

To make things slightly more interesting, some CPUs may change frequency.  They may or may not run the TSC at the same rate, and because the frequency change may be staggered or slewed, at some points in time, the TSC rate may not be known other than falling within a range of values.  In this case, the TSC will not be a stable time source, and must be calibrated against a known, stable, external clock to be a usable source of time.

Whether the TSC runs at a constant rate or scales with the P-state is model dependent and must be determined by inspecting CPUID, chipset or vendor specific MSR fields.

In addition, some vendors have known bugs where the P-state is actually compensated for properly during normal operation, but when the processor is inactive, the P-state may be raised temporarily to service cache misses from other processors.  In such cases, the TSC on halted CPUs could advance faster than that of non-halted processors.  AMD Turion processors are known to have this problem.

<a id="rst-tsc-and-stpclk-t-states"></a>

### 3.6. TSC and STPCLK / T-states

External signals given to the processor may also have the effect of stopping the TSC.  This is typically done for thermal emergency power control to prevent an overheating condition, and typically, there is no way to detect that this condition has happened.

<a id="rst-tsc-virtualization-vmx"></a>

### 3.7. TSC virtualization - VMX

VMX provides conditional trapping of RDTSC, RDMSR, WRMSR and RDTSCP instructions, which is enough for full virtualization of TSC in any manner.  In addition, VMX allows passing through the host TSC plus an additional TSC_OFFSET field specified in the VMCS.  Special instructions must be used to read and write the VMCS field.

<a id="rst-tsc-virtualization-svm"></a>

### 3.8. TSC virtualization - SVM

SVM provides conditional trapping of RDTSC, RDMSR, WRMSR and RDTSCP instructions, which is enough for full virtualization of TSC in any manner.  In addition, SVM allows passing through the host TSC plus an additional offset field specified in the SVM control block.

<a id="rst-tsc-feature-bits-in-linux"></a>

### 3.9. TSC feature bits in Linux

In summary, there is no way to guarantee the TSC remains in perfect synchronization unless it is explicitly guaranteed by the architecture.  Even if so, the TSCs in multi-sockets or NUMA systems may still run independently despite being locally consistent.

The following feature bits are used by Linux to signal various TSC attributes, but they can only be taken to be meaningful for UP or single node systems.


<table>
<tbody>
<tr>
<td>


X86_FEATURE_TSC

</td>
<td>


The TSC is available in hardware

</td>
</tr>
<tr>
<td>


X86_FEATURE_RDTSCP

</td>
<td>


The RDTSCP instruction is available

</td>
</tr>
<tr>
<td>


X86_FEATURE_CONSTANT_TSC

</td>
<td>


The TSC rate is unchanged with P-states

</td>
</tr>
<tr>
<td>


X86_FEATURE_NONSTOP_TSC

</td>
<td>


The TSC does not stop in C-states

</td>
</tr>
<tr>
<td>


X86_FEATURE_TSC_RELIABLE

</td>
<td>


TSC sync checks are skipped (VMware)

</td>
</tr>
</tbody>
</table>

<a id="rst-virtualization-problems"></a>

## 4. Virtualization Problems

Timekeeping is especially problematic for virtualization because a number of challenges arise.  The most obvious problem is that time is now shared between the host and, potentially, a number of virtual machines.  Thus the virtual operating system does not run with 100% usage of the CPU, despite the fact that it may very well make that assumption.  It may expect it to remain true to very exacting bounds when interrupt sources are disabled, but in reality only its virtual interrupt sources are disabled, and the machine may still be preempted at any time.  This causes problems as the passage of real time, the injection of machine interrupts and the associated clock sources are no longer completely synchronized with real time.

This same problem can occur on native hardware to a degree, as SMM mode may steal cycles from the naturally on X86 systems when SMM mode is used by the BIOS, but not in such an extreme fashion.  However, the fact that SMM mode may cause similar problems to virtualization makes it a good justification for solving many of these problems on bare metal.

<a id="rst-interrupt-clocking"></a>

### 4.1. Interrupt clocking

One of the most immediate problems that occurs with legacy operating systems is that the system timekeeping routines are often designed to keep track of time by counting periodic interrupts.  These interrupts may come from the PIT or the RTC, but the problem is the same: the host virtualization engine may not be able to deliver the proper number of interrupts per second, and so guest time may fall behind.  This is especially problematic if a high interrupt rate is selected, such as 1000 HZ, which is unfortunately the default for many Linux guests.

There are three approaches to solving this problem; first, it may be possible to simply ignore it.  Guests which have a separate time source for tracking 'wall clock' or 'real time' may not need any adjustment of their interrupts to maintain proper time.  If this is not sufficient, it may be necessary to inject additional interrupts into the guest in order to increase the effective interrupt rate.  This approach leads to complications in extreme conditions, where host load or guest lag is too much to compensate for, and thus another solution to the problem has risen: the guest may need to become aware of lost ticks and compensate for them internally.  Although promising in theory, the implementation of this policy in Linux has been extremely error prone, and a number of buggy variants of lost tick compensation are distributed across commonly used Linux systems.

Windows uses periodic RTC clocking as a means of keeping time internally, and thus requires interrupt slewing to keep proper time.  It does use a low enough rate (ed: is it 18.2 Hz?) however that it has not yet been a problem in practice.

<a id="rst-tsc-sampling-and-serialization"></a>

### 4.2. TSC sampling and serialization

As the highest precision time source available, the cycle counter of the CPU has aroused much interest from developers.  As explained above, this timer has many problems unique to its nature as a local, potentially unstable and potentially unsynchronized source.  One issue which is not unique to the TSC, but is highlighted because of its very precise nature is sampling delay.  By definition, the counter, once read is already old.  However, it is also possible for the counter to be read ahead of the actual use of the result. This is a consequence of the superscalar execution of the instruction stream, which may execute instructions out of order.  Such execution is called non-serialized.  Forcing serialized execution is necessary for precise measurement with the TSC, and requires a serializing instruction, such as CPUID or an MSR read.

Since CPUID may actually be virtualized by a trap and emulate mechanism, this serialization can pose a performance issue for hardware virtualization.  An accurate time stamp counter reading may therefore not always be available, and it may be necessary for an implementation to guard against "backwards" reads of the TSC as seen from other CPUs, even in an otherwise perfectly synchronized system.

<a id="rst-timespec-aliasing"></a>

### 4.3. Timespec aliasing

Additionally, this lack of serialization from the TSC poses another challenge when using results of the TSC when measured against another time source.  As the TSC is much higher precision, many possible values of the TSC may be read while another clock is still expressing the same value.

That is, you may read (T,T+10) while external clock C maintains the same value. Due to non-serialized reads, you may actually end up with a range which fluctuates - from (T-1.. T+10).  Thus, any time calculated from a TSC, but calibrated against an external value may have a range of valid values. Re-calibrating this computation may actually cause time, as computed after the calibration, to go backwards, compared with time computed before the calibration.

This problem is particularly pronounced with an internal time source in Linux, the kernel time, which is expressed in the theoretically high resolution timespec - but which advances in much larger granularity intervals, sometimes at the rate of jiffies, and possibly in catchup modes, at a much larger step.

This aliasing requires care in the computation and recalibration of kvmclock and any other values derived from TSC computation (such as TSC virtualization itself).

<a id="rst-migration"></a>

### 4.4. Migration

Migration of a virtual machine raises problems for timekeeping in two ways. First, the migration itself may take time, during which interrupts cannot be delivered, and after which, the guest time may need to be caught up.  NTP may be able to help to some degree here, as the clock correction required is typically small enough to fall in the NTP-correctable window.

An additional concern is that timers based off the TSC (or HPET, if the raw bus clock is exposed) may now be running at different rates, requiring compensation in some way in the hypervisor by virtualizing these timers.  In addition, migrating to a faster machine may preclude the use of a passthrough TSC, as a faster clock cannot be made visible to a guest without the potential of time advancing faster than usual.  A slower clock is less of a problem, as it can always be caught up to the original rate.  KVM clock avoids these problems by simply storing multipliers and offsets against the TSC for the guest to convert back into nanosecond resolution values.

<a id="rst-scheduling"></a>

### 4.5. Scheduling

Since scheduling may be based on precise timing and firing of interrupts, the scheduling algorithms of an operating system may be adversely affected by virtualization.  In theory, the effect is random and should be universally distributed, but in contrived as well as real scenarios (guest device access, causes of virtualization exits, possible context switch), this may not always be the case.  The effect of this has not been well studied.

In an attempt to work around this, several implementations have provided a paravirtualized scheduler clock, which reveals the true amount of CPU time for which a virtual machine has been running.

<a id="rst-watchdogs"></a>

### 4.6. Watchdogs

Watchdog timers, such as the lock detector in Linux may fire accidentally when running under hardware virtualization due to timer interrupts being delayed or misinterpretation of the passage of real time.  Usually, these warnings are spurious and can be ignored, but in some circumstances it may be necessary to disable such detection.

<a id="rst-delays-and-precision-timing"></a>

### 4.7. Delays and precision timing

Precise timing and delays may not be possible in a virtualized system.  This can happen if the system is controlling physical hardware, or issues delays to compensate for slower I/O to and from devices.  The first issue is not solvable in general for a virtualized system; hardware control software can't be adequately virtualized without a full real-time operating system, which would require an RT aware virtualization platform.

The second issue may cause performance problems, but this is unlikely to be a significant issue.  In many cases these delays may be eliminated through configuration or paravirtualization.

<a id="rst-covert-channels-and-leaks"></a>

### 4.8. Covert channels and leaks

In addition to the above problems, time information will inevitably leak to the guest about the host in anything but a perfect implementation of virtualized time.  This may allow the guest to infer the presence of a hypervisor (as in a red-pill type detection), and it may allow information to leak between guests by using CPU utilization itself as a signalling channel.  Preventing such problems would require completely isolated virtual time which may not track real time any longer.  This may be useful in certain security or QA contexts, but in general isn't recommended for real-world deployment scenarios.

---

# UML HowTo

_Peios Kernel / Internals / Virtualisation / uml_

> Introduction

> **Peios:** This is an upstream UML host/guest workflow, not the configured Peios kernel build. Host-side `sudo`, `setcap` and ownership recipes assume a Linux host with that authority model. They do not grant native authority when run on Peios. See [Building Peios](</kernel/development/start-here/building-peios.md>).


<a id="rst-uml-howto"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

<a id="rst-contents"></a>



<a id="rst-introduction"></a>

## Introduction

Welcome to User Mode Linux

User Mode Linux is the first Open Source virtualization platform (first release date 1991) and second virtualization platform for an x86 PC.

<a id="rst-how-is-uml-different-from-a-vm-using-virtualization-package-x"></a>

### How is UML Different from a VM using Virtualization package X?

We have come to assume that virtualization also means some level of hardware emulation. In fact, it does not. As long as a virtualization package provides the OS with devices which the OS can recognize and has a driver for, the devices do not need to emulate real hardware. Most OSes today have built-in support for a number of "fake" devices used only under virtualization. User Mode Linux takes this concept to the ultimate extreme - there is not a single real device in sight. It is 100% artificial or if we use the correct term 100% paravirtual. All UML devices are abstract concepts which map onto something provided by the host - files, sockets, pipes, etc.

The other major difference between UML and various virtualization packages is that there is a distinct difference between the way the UML kernel and the UML programs operate. The UML kernel is just a process running on Linux - same as any other program. It can be run by an unprivileged user and it does not require anything in terms of special CPU features. The UML userspace, however, is a bit different. The Linux kernel on the host machine assists UML in intercepting everything the program running on a UML instance is trying to do and making the UML kernel handle all of its requests. This is different from other virtualization packages which do not make any difference between the guest kernel and guest programs. This difference results in a number of advantages and disadvantages of UML over let's say QEMU which we will cover later in this document.

<a id="rst-why-would-i-want-user-mode-linux"></a>

### Why Would I Want User Mode Linux?

- If User Mode Linux kernel crashes, your host kernel is still fine. It is not accelerated in any way (vhost, kvm, etc) and it is not trying to access any devices directly.  It is, in fact, a process like any other.

- You can run a usermode kernel as a non-root user (you may need to arrange appropriate permissions for some devices).

- You can run a very small VM with a minimal footprint for a specific task (for example 32M or less).

- You can get extremely high performance for anything which is a "kernel specific task" such as forwarding, firewalling, etc while still being isolated from the host kernel.

- You can play with kernel concepts without breaking things.

- You are not bound by "emulating" hardware, so you can try weird and wonderful concepts which are very difficult to support when emulating real hardware such as time travel and making your system clock dependent on what UML does (very useful for things like tests).

- It's fun.

<a id="rst-why-not-to-run-uml"></a>

### Why not to run UML

- The syscall interception technique used by UML makes it inherently slower for any userspace applications. While it can do kernel tasks on par with most other virtualization packages, its userspace is **slow**. The root cause is that UML has a very high cost of creating new processes and threads (something most Unix/Linux applications take for granted).

- UML is strictly uniprocessor at present. If you want to run an application which needs many CPUs to function, it is clearly the wrong choice.

<a id="rst-building-a-uml-instance"></a>

## Building a UML instance

There is no UML installer in any distribution. While you can use off the shelf install media to install into a blank VM using a virtualization package, there is no UML equivalent. You have to use appropriate tools on your host to build a viable filesystem image.

This is extremely easy on Debian - you can do it using debootstrap. It is also easy on OpenWRT - the build process can build UML images. All other distros - YMMV.

<a id="rst-creating-an-image"></a>

### Creating an image

Create a sparse raw disk image:



```text
# dd if=/dev/zero of=disk_image_name bs=1 count=1 seek=16G
```

This will create a 16G disk image. The OS will initially allocate only one block and will allocate more as they are written by UML. As of kernel version 4.19 UML fully supports TRIM (as usually used by flash drives). Using TRIM inside the UML image by specifying discard as a mount option or by running `tune2fs -o discard /dev/ubdXX` will request UML to return any unused blocks to the OS.

Create a filesystem on the disk image and mount it:



```text
# mkfs.ext4 ./disk_image_name && mount ./disk_image_name /mnt
```

This example uses ext4, any other filesystem such as ext3, btrfs, xfs, jfs, etc will work too.

Create a minimal OS installation on the mounted filesystem:



```text
# debootstrap buster /mnt http://deb.debian.org/debian
```

debootstrap does not set up the root password, fstab, hostname or anything related to networking. It is up to the user to do that.

Set the root password - the easiest way to do that is to chroot into the mounted image:



```text
# chroot /mnt
# passwd
# exit
```

<a id="rst-edit-key-system-files"></a>

### Edit key system files

UML block devices are called ubds. The fstab created by debootstrap will be empty and it needs an entry for the root file system:



```text
/dev/ubd0   ext4    discard,errors=remount-ro  0       1
```

The image hostname will be set to the same as the host on which you are creating its image. It is a good idea to change that to avoid "Oh, bummer, I rebooted the wrong machine".

UML supports vector I/O high performance network devices which have support for some standard virtual network encapsulations like Ethernet over GRE and Ethernet over L2TPv3. These are called vecX.

When vector network devices are in use, `/etc/network/interfaces` will need entries like:



```text
# vector UML network devices
auto vec0
iface vec0 inet dhcp
```

We now have a UML image which is nearly ready to run, all we need is a UML kernel and modules for it.

Most distributions have a UML package. Even if you intend to use your own kernel, testing the image with a stock one is always a good start. These packages come with a set of modules which should be copied to the target filesystem. The location is distribution dependent. For Debian these reside under /usr/lib/uml/modules. Copy recursively the content of this directory to the mounted UML filesystem:



```text
# cp -rax /usr/lib/uml/modules /mnt/lib/modules
```

If you have compiled your own kernel, you need to use the usual "install modules to a location" procedure by running:



```text
# make INSTALL_MOD_PATH=/mnt/lib/modules modules_install
```

This will install modules into /mnt/lib/modules/$(KERNELRELEASE). To specify the full module installation path, use:



```text
# make MODLIB=/mnt/lib/modules modules_install
```

At this point the image is ready to be brought up.

<a id="rst-setting-up-uml-networking"></a>

## Setting Up UML Networking

UML networking is designed to emulate an Ethernet connection. This connection may be either point-to-point (similar to a connection between machines using a back-to-back cable) or a connection to a switch. UML supports a wide variety of means to build these connections to all of: local machine, remote machine(s), local and remote UML and other VM instances.


<table>
<thead>
<tr>
<th>


Transport

</th>
<th>


Type

</th>
<th>


Capabilities

</th>
<th>


Throughput

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


tap

</td>
<td>


vector

</td>
<td>


checksum, tso

</td>
<td>


&gt; 8Gbit

</td>
</tr>
<tr>
<td>


hybrid

</td>
<td>


vector

</td>
<td>


checksum, tso, multipacket rx

</td>
<td>


&gt; 6GBit

</td>
</tr>
<tr>
<td>


raw

</td>
<td>


vector

</td>
<td>


checksum, tso, multipacket rx, tx"

</td>
<td>


&gt; 6GBit

</td>
</tr>
<tr>
<td>


EoGRE

</td>
<td>


vector

</td>
<td>


multipacket rx, tx

</td>
<td>


&gt; 3Gbit

</td>
</tr>
<tr>
<td>


Eol2tpv3

</td>
<td>


vector

</td>
<td>


multipacket rx, tx

</td>
<td>


&gt; 3Gbit

</td>
</tr>
<tr>
<td>


bess

</td>
<td>


vector

</td>
<td>


multipacket rx, tx

</td>
<td>


&gt; 3Gbit

</td>
</tr>
<tr>
<td>


fd

</td>
<td>


vector

</td>
<td>


dependent on fd type

</td>
<td>


varies

</td>
</tr>
<tr>
<td>


vde

</td>
<td>


vector

</td>
<td>


dep. on VDE VPN: Virt.Net Locator

</td>
<td>


varies

</td>
</tr>
</tbody>
</table>

- All transports which have tso and checksum offloads can deliver speeds approaching 10G on TCP streams.

- All transports which have multi-packet rx and/or tx can deliver pps rates of up to 1Mps or more.

- GRE and L2TPv3 allow connections to all of: local machine, remote machines, remote network devices and remote UML instances.

<a id="rst-network-configuration-privileges"></a>

### Network configuration privileges

The majority of the supported networking modes need `root` privileges. For example, for vector transports, `root` privilege is required to fire an ioctl to setup the tun interface and/or use raw sockets where needed.

This can be achieved by granting the user a particular capability instead of running UML as root.  In case of vector transport, a user can add the capability `CAP_NET_ADMIN` or `CAP_NET_RAW` to the uml binary. Thenceforth, UML can be run with normal user privilges, along with full networking.

For example:



```text
# sudo setcap cap_net_raw,cap_net_admin+ep linux
```

<a id="rst-configuring-vector-transports"></a>

### Configuring vector transports

All vector transports support a similar syntax:

If X is the interface number as in vec0, vec1, vec2, etc, the general syntax for options is:



```text
vecX:transport="Transport Name",option=value,option=value,...,option=value
```

<a id="rst-common-options"></a>

#### Common options

These options are common for all transports:

- `depth=int` - sets the queue depth for vector IO. This is the amount of packets UML will attempt to read or write in a single system call. The default number is 64 and is generally sufficient for most applications that need throughput in the 2-4 Gbit range. Higher speeds may require larger values.

- `mac=XX:XX:XX:XX:XX` - sets the interface MAC address value.

- `gro=[0,1]` - sets GRO off or on. Enables receive/transmit offloads. The effect of this option depends on the host side support in the transport which is being configured. In most cases it will enable TCP segmentation and RX/TX checksumming offloads. The setting must be identical on the host side and the UML side. The UML kernel will produce warnings if it is not. For example, GRO is enabled by default on local machine interfaces (e.g. veth pairs, bridge, etc), so it should be enabled in UML in the corresponding UML transports (raw, tap, hybrid) in order for networking to operate correctly.

- `mtu=int` - sets the interface MTU

- `headroom=int` - adjusts the default headroom (32 bytes) reserved if a packet will need to be re-encapsulated into for instance VXLAN.

- `vec=0` - disable multipacket IO and fall back to packet at a time mode

<a id="rst-shared-options"></a>

#### Shared Options

- `ifname=str` Transports which bind to a local network interface have a shared option - the name of the interface to bind to.

- `src, dst, src_port, dst_port` - all transports which use sockets which have the notion of source and destination and/or source port and destination port use these to specify them.

- `v6=[0,1]` to specify if a v6 connection is desired for all transports which operate over IP. Additionally, for transports that have some differences in the way they operate over v4 and v6 (for example EoL2TPv3), sets the correct mode of operation. In the absence of this option, the socket type is determined based on what do the src and dst arguments resolve/parse to.

<a id="rst-tap-transport"></a>

#### tap transport

Example:



```text
vecX:transport=tap,ifname=tap0,depth=128,gro=1
```

This will connect vec0 to tap0 on the host. Tap0 must already exist (for example created using tunctl) and UP.

tap0 can be configured as a point-to-point interface and given an IP address so that UML can talk to the host. Alternatively, it is possible to connect UML to a tap interface which is connected to a bridge.

While tap relies on the vector infrastructure, it is not a true vector transport at this point, because Linux does not support multi-packet IO on tap file descriptors for normal userspace apps like UML. This is a privilege which is offered only to something which can hook up to it at kernel level via specialized interfaces like vhost-net. A vhost-net like helper for UML is planned at some point in the future.

Privileges required: tap transport requires either:

- tap interface to exist and be created persistent and owned by the UML user using tunctl. Example `tunctl -u uml-user -t tap0`

- binary to have `CAP_NET_ADMIN` privilege

<a id="rst-hybrid-transport"></a>

#### hybrid transport

Example:



```text
vecX:transport=hybrid,ifname=tap0,depth=128,gro=1
```

This is an experimental/demo transport which couples tap for transmit and a raw socket for receive. The raw socket allows multi-packet receive resulting in significantly higher packet rates than normal tap.

Privileges required: hybrid requires `CAP_NET_RAW` capability by the UML user as well as the requirements for the tap transport.

<a id="rst-raw-socket-transport"></a>

#### raw socket transport

Example:



```text
vecX:transport=raw,ifname=p-veth0,depth=128,gro=1
```

This transport uses vector IO on raw sockets. While you can bind to any interface including a physical one, the most common use it to bind to the "peer" side of a veth pair with the other side configured on the host.

Example host configuration for Debian:

**/etc/network/interfaces**:



```text
auto veth0
iface veth0 inet static
     address 192.168.4.1
     netmask 255.255.255.252
     broadcast 192.168.4.3
     pre-up ip link add veth0 type veth peer name p-veth0 && \
       ifconfig p-veth0 up
```

UML can now bind to p-veth0 like this:



```text
vec0:transport=raw,ifname=p-veth0,depth=128,gro=1
```

If the UML guest is configured with 192.168.4.2 and netmask 255.255.255.0 it can talk to the host on 192.168.4.1

The raw transport also provides some support for offloading some of the filtering to the host. The two options to control it are:

- `bpffile=str` filename of raw bpf code to be loaded as a socket filter

- `bpfflash=int` 0/1 allow loading of bpf from inside User Mode Linux. This option allows the use of the ethtool load firmware command to load bpf code.

In either case the bpf code is loaded into the host kernel. While this is presently limited to legacy bpf syntax (not ebpf), it is still a security risk. It is not recommended to allow this unless the User Mode Linux instance is considered trusted.

Privileges required: raw socket transport requires `CAP_NET_RAW` capability.

<a id="rst-gre-socket-transport"></a>

#### GRE socket transport

Example:



```text
vecX:transport=gre,src=$src_host,dst=$dst_host
```

This will configure an Ethernet over `GRE` (aka `GRETAP` or `GREIRB`) tunnel which will connect the UML instance to a `GRE` endpoint at host dst_host. `GRE` supports the following additional options:

- `rx_key=int` - GRE 32-bit integer key for rx packets, if set, `txkey` must be set too

- `tx_key=int` - GRE 32-bit integer key for tx packets, if set `rx_key` must be set too

- `sequence=[0,1]` - enable GRE sequence

- `pin_sequence=[0,1]` - pretend that the sequence is always reset on each packet (needed to interoperate with some really broken implementations)

- `v6=[0,1]` - force IPv4 or IPv6 sockets respectively

- GRE checksum is not presently supported

GRE has a number of caveats:

- You can use only one GRE connection per IP address. There is no way to multiplex connections as each GRE tunnel is terminated directly on the UML instance.

- The key is not really a security feature. While it was intended as such its "security" is laughable. It is, however, a useful feature to ensure that the tunnel is not misconfigured.

An example configuration for a Linux host with a local address of 192.168.128.1 to connect to a UML instance at 192.168.129.1

**/etc/network/interfaces**:



```text
auto gt0
iface gt0 inet static
 address 10.0.0.1
 netmask 255.255.255.0
 broadcast 10.0.0.255
 mtu 1500
 pre-up ip link add gt0 type gretap local 192.168.128.1 \
        remote 192.168.129.1 || true
 down ip link del gt0 || true
```

Additionally, GRE has been tested versus a variety of network equipment.

Privileges required: GRE requires `CAP_NET_RAW`

<a id="rst-l2tpv3-socket-transport"></a>

#### l2tpv3 socket transport

\_Warning\_. L2TPv3 has a "bug". It is the "bug" known as "has more options than GNU ls". While it has some advantages, there are usually easier (and less verbose) ways to connect a UML instance to something. For example, most devices which support L2TPv3 also support GRE.

Example:



```text
vec0:transport=l2tpv3,udp=1,src=$src_host,dst=$dst_host,srcport=$src_port,dstport=$dst_port,depth=128,rx_session=0xffffffff,tx_session=0xffff
```

This will configure an Ethernet over L2TPv3 fixed tunnel which will connect the UML instance to a L2TPv3 endpoint at host $dst_host using the L2TPv3 UDP flavour and UDP destination port $dst_port.

L2TPv3 always requires the following additional options:

- `rx_session=int` - l2tpv3 32-bit integer session for rx packets

- `tx_session=int` - l2tpv3 32-bit integer session for tx packets

As the tunnel is fixed these are not negotiated and they are preconfigured on both ends.

Additionally, L2TPv3 supports the following optional parameters.

- `rx_cookie=int` - l2tpv3 32-bit integer cookie for rx packets - same functionality as GRE key, more to prevent misconfiguration than provide actual security

- `tx_cookie=int` - l2tpv3 32-bit integer cookie for tx packets

- `cookie64=[0,1]` - use 64-bit cookies instead of 32-bit.

- `counter=[0,1]` - enable l2tpv3 counter

- `pin_counter=[0,1]` - pretend that the counter is always reset on each packet (needed to interoperate with some really broken implementations)

- `v6=[0,1]` - force v6 sockets

- `udp=[0,1]` - use raw sockets (0) or UDP (1) version of the protocol

L2TPv3 has a number of caveats:

- you can use only one connection per IP address in raw mode. There is no way to multiplex connections as each L2TPv3 tunnel is terminated directly on the UML instance. UDP mode can use different ports for this purpose.

Here is an example of how to configure a Linux host to connect to UML via L2TPv3:

**/etc/network/interfaces**:



```text
auto l2tp1
iface l2tp1 inet static
 address 192.168.126.1
 netmask 255.255.255.0
 broadcast 192.168.126.255
 mtu 1500
 pre-up ip l2tp add tunnel remote 127.0.0.1 \
        local 127.0.0.1 encap udp tunnel_id 2 \
        peer_tunnel_id 2 udp_sport 1706 udp_dport 1707 && \
        ip l2tp add session name l2tp1 tunnel_id 2 \
        session_id 0xffffffff peer_session_id 0xffffffff
 down ip l2tp del session tunnel_id 2 session_id 0xffffffff && \
        ip l2tp del tunnel tunnel_id 2
```

Privileges required: L2TPv3 requires `CAP_NET_RAW` for raw IP mode and no special privileges for the UDP mode.

<a id="rst-bess-socket-transport"></a>

#### BESS socket transport

BESS is a high performance modular network switch.

[https://github.com/NetSys/bess](<https://github.com/NetSys/bess>)

It has support for a simple sequential packet socket mode which in the more recent versions is using vector IO for high performance.

Example:



```text
vecX:transport=bess,src=$unix_src,dst=$unix_dst
```

This will configure a BESS transport using the unix_src Unix domain socket address as source and unix_dst socket address as destination.

For BESS configuration and how to allocate a BESS Unix domain socket port please see the BESS documentation.

[https://github.com/NetSys/bess/wiki/Built-In-Modules-and-Ports](<https://github.com/NetSys/bess/wiki/Built-In-Modules-and-Ports>)

BESS transport does not require any special privileges.

<a id="rst-vde-vector-transport"></a>

#### VDE vector transport

Virtual Distributed Ethernet (VDE) is a project whose main goal is to provide a highly flexible support for virtual networking.

[http://wiki.virtualsquare.org/\#/tutorials/vdebasics](<http://wiki.virtualsquare.org/#/tutorials/vdebasics>)

Common usages of VDE include fast prototyping and teaching.

Examples:

> `vecX:transport=vde,vnl=tap://tap0`

use tap0

> `vecX:transport=vde,vnl=slirp://`

use slirp

> `vec0:transport=vde,vnl=vde:///tmp/switch`

connect to a vde switch

> `vecX:transport=\"vde,vnl=cmd://ssh remote.host //tmp/sshlirp\"`

connect to a remote slirp (instant VPN: convert ssh to VPN, it uses sshlirp) [https://github.com/virtualsquare/sshlirp](<https://github.com/virtualsquare/sshlirp>)

> `vec0:transport=vde,vnl=vxvde://234.0.0.1`

connect to a local area cloud (all the UML nodes using the same multicast address running on hosts in the same multicast domain (LAN) will be automagically connected together to a virtual LAN.

<a id="rst-running-uml"></a>

## Running UML

This section assumes that either the user-mode-linux package from the distribution or a custom built kernel has been installed on the host.

These add an executable called linux to the system. This is the UML kernel. It can be run just like any other executable. It will take most normal linux kernel arguments as command line arguments.  Additionally, it will need some UML-specific arguments in order to do something useful.

<a id="rst-arguments"></a>

### Arguments

<a id="rst-mandatory-arguments"></a>

#### Mandatory Arguments:

- `mem=int[K,M,G]` - amount of memory. By default in bytes. It will also accept K, M or G qualifiers.

- `ubdX[s,d,c,t]=` virtual disk specification. This is not really mandatory, but it is likely to be needed in nearly all cases so we can specify a root file system. The simplest possible image specification is the name of the image file for the filesystem (created using one of the methods described in [Creating an image](<#rst-creating-an-image>)).

  - UBD devices support copy on write (COW). The changes are kept in a separate file which can be discarded allowing a rollback to the original pristine image.  If COW is desired, the UBD image is specified as: `cow_file,master_image`. Example:`ubd0=Filesystem.cow,Filesystem.img`

  - UBD devices can be set to use synchronous IO. Any writes are immediately flushed to disk. This is done by adding `s` after the `ubdX` specification.

  - UBD performs some heuristics on devices specified as a single filename to make sure that a COW file has not been specified as the image. To turn them off, use the `d` flag after `ubdX`.

  - UBD supports TRIM - asking the Host OS to reclaim any unused blocks in the image. To turn it off, specify the `t` flag after `ubdX`.

- `root=` root device - most likely `/dev/ubd0` (this is a Linux filesystem image)

<a id="rst-important-optional-arguments"></a>

#### Important Optional Arguments

If UML is run as "linux" with no extra arguments, it will try to start an xterm for every console configured inside the image (up to 6 in most Linux distributions). Each console is started inside an xterm. This makes it nice and easy to use UML on a host with a GUI. It is, however, the wrong approach if UML is to be used as a testing harness or run in a text-only environment.

In order to change this behaviour we need to specify an alternative console and wire it to one of the supported "line" channels. For this we need to map a console to use something different from the default xterm.

Example which will divert console number 1 to stdin/stdout:



```text
con1=fd:0,fd:1
```

UML supports a wide variety of serial line channels which are specified using the following syntax

> conX=channel_type:options\[,channel_type:options\]

If the channel specification contains two parts separated by comma, the first one is input, the second one output.

- The null channel - Discard all input or output. Example `con=null` will set all consoles to null by default.

- The fd channel - use file descriptor numbers for input/output. Example: `con1=fd:0,fd:1.`

- The port channel - start a telnet server on TCP port number. Example: `con1=port:4321`.  The host must have /usr/sbin/in.telnetd (usually part of a telnetd package) and the port-helper from the UML utilities (see the information for the xterm channel below).  UML will not boot until a client connects.

- The pty and pts channels - use system pty/pts.

- The tty channel - bind to an existing system tty. Example: `con1=/dev/tty8` will make UML use the host 8th console (usually unused).

- The xterm channel - this is the default - bring up an xterm on this channel and direct IO to it. Note that in order for xterm to work, the host must have the UML distribution package installed. This usually contains the port-helper and other utilities needed for UML to communicate with the xterm. Alternatively, these need to be complied and installed from source. All options applicable to consoles also apply to UML serial lines which are presented as ttyS inside UML.

<a id="rst-starting-uml"></a>

### Starting UML

We can now run UML.



```text
# linux mem=2048M umid=TEST \
 ubd0=Filesystem.img \
 vec0:transport=tap,ifname=tap0,depth=128,gro=1 \
 root=/dev/ubda con=null con0=null,fd:2 con1=fd:0,fd:1
```

This will run an instance with `2048M RAM` and try to use the image file called `Filesystem.img` as root. It will connect to the host using tap0. All consoles except `con1` will be disabled and console 1 will use standard input/output making it appear in the same terminal it was started.

<a id="rst-logging-in"></a>

### Logging in

If you have not set up a password when generating the image, you will have to shut down the UML instance, mount the image, chroot into it and set it - as described in the Generating an Image section.  If the password is already set, you can just log in.

<a id="rst-the-uml-management-console"></a>

### The UML Management Console

In addition to managing the image from "the inside" using normal sysadmin tools, it is possible to perform a number of low-level operations using the UML management console. The UML management console is a low-level interface to the kernel on a running UML instance, somewhat like the i386 SysRq interface. Since there is a full-blown operating system under UML, there is much greater flexibility possible than with the SysRq mechanism.

There are a number of things you can do with the mconsole interface:

- get the kernel version

- add and remove devices

- halt or reboot the machine

- Send SysRq commands

- Pause and resume the UML

- Inspect processes running inside UML

- Inspect UML internal /proc state

You need the mconsole client (uml_mconsole) which is a part of the UML tools package available in most Linux distritions.

You also need `CONFIG_MCONSOLE` (under 'General Setup') enabled in the UML kernel.  When you boot UML, you'll see a line like:



```text
mconsole initialized on /home/jdike/.uml/umlNJ32yL/mconsole
```

If you specify a unique machine id on the UML command line, i.e. `umid=debian`, you'll see this:



```text
mconsole initialized on /home/jdike/.uml/debian/mconsole
```

That file is the socket that uml_mconsole will use to communicate with UML.  Run it with either the umid or the full path as its argument:



```text
# uml_mconsole debian
```

or

> \# uml_mconsole /home/jdike/.uml/debian/mconsole

You'll get a prompt, at which you can run one of these commands:

- version

- help

- halt

- reboot

- config

- remove

- sysrq

- help

- cad

- stop

- go

- proc

- stack

<a id="rst-version"></a>

#### version

This command takes no arguments.  It prints the UML version:



```text
(mconsole)  version
OK Linux OpenWrt 4.14.106 #0 Tue Mar 19 08:19:41 2019 x86_64
```

There are a couple actual uses for this.  It's a simple no-op which can be used to check that a UML is running.  It's also a way of sending a device interrupt to the UML. UML mconsole is treated internally as a UML device.

<a id="rst-help"></a>

#### help

This command takes no arguments. It prints a short help screen with the supported mconsole commands.

<a id="rst-halt-and-reboot"></a>

#### halt and reboot

These commands take no arguments.  They shut the machine down immediately, with no syncing of disks and no clean shutdown of userspace.  So, they are pretty close to crashing the machine:



```text
(mconsole)  halt
OK
```

<a id="rst-config"></a>

#### config

"config" adds a new device to the virtual machine. This is supported by most UML device drivers. It takes one argument, which is the device to add, with the same syntax as the kernel command line:



```text
(mconsole) config ubd3=/home/jdike/incoming/roots/root_fs_debian22
```

<a id="rst-remove"></a>

#### remove

"remove" deletes a device from the system.  Its argument is just the name of the device to be removed. The device must be idle in whatever sense the driver considers necessary.  In the case of the ubd driver, the removed block device must not be mounted, swapped on, or otherwise open, and in the case of the network driver, the device must be down:



```text
(mconsole)  remove ubd3
```

<a id="rst-sysrq"></a>

#### sysrq

This command takes one argument, which is a single letter.  It calls the generic kernel's SysRq driver, which does whatever is called for by that argument.  See the SysRq documentation in [Documentation/admin-guide/sysrq.rst](/kernel/administration/admin-guide/diagnostics/sysrq.md) in your favorite kernel tree to see what letters are valid and what they do.

<a id="rst-cad"></a>

#### cad

This invokes the `Ctl-Alt-Del` action in the running image.  What exactly this ends up doing is up to init, systemd, etc.  Normally, it reboots the machine.

<a id="rst-stop"></a>

#### stop

This puts the UML in a loop reading mconsole requests until a 'go' mconsole command is received. This is very useful as a debugging/snapshotting tool.

<a id="rst-go"></a>

#### go

This resumes a UML after being paused by a 'stop' command. Note that when the UML has resumed, TCP connections may have timed out and if the UML is paused for a long period of time, crond might go a little crazy, running all the jobs it didn't do earlier.

<a id="rst-proc"></a>

#### proc

This takes one argument - the name of a file in /proc which is printed to the mconsole standard output

<a id="rst-stack"></a>

#### stack

This takes one argument - the pid number of a process. Its stack is printed to a standard output.

<a id="rst-advanced-uml-topics"></a>

## Advanced UML Topics

<a id="rst-sharing-filesystems-between-virtual-machines"></a>

### Sharing Filesystems between Virtual Machines

Don't attempt to share filesystems simply by booting two UMLs from the same file.  That's the same thing as booting two physical machines from a shared disk.  It will result in filesystem corruption.

<a id="rst-using-layered-block-devices"></a>

#### Using layered block devices

The way to share a filesystem between two virtual machines is to use the copy-on-write (COW) layering capability of the ubd block driver. Any changed blocks are stored in the private COW file, while reads come from either device - the private one if the requested block is valid in it, the shared one if not.  Using this scheme, the majority of data which is unchanged is shared between an arbitrary number of virtual machines, each of which has a much smaller file containing the changes that it has made.  With a large number of UMLs booting from a large root filesystem, this leads to a huge disk space saving.

Sharing file system data will also help performance, since the host will be able to cache the shared data using a much smaller amount of memory, so UML disk requests will be served from the host's memory rather than its disks.  There is a major caveat in doing this on multisocket NUMA machines.  On such hardware, running many UML instances with a shared master image and COW changes may cause issues like NMIs from excess of inter-socket traffic.

If you are running UML on high-end hardware like this, make sure to bind UML to a set of logical CPUs residing on the same socket using the `taskset` command or have a look at the "tuning" section.

To add a copy-on-write layer to an existing block device file, simply add the name of the COW file to the appropriate ubd switch:



```text
ubd0=root_fs_cow,root_fs_debian_22
```

where `root_fs_cow` is the private COW file and `root_fs_debian_22` is the existing shared filesystem.  The COW file need not exist.  If it doesn't, the driver will create and initialize it.

<a id="rst-disk-usage"></a>

#### Disk Usage

UML has TRIM support which will release any unused space in its disk image files to the underlying OS. It is important to use either ls -ls or du to verify the actual file size.

<a id="rst-cow-validity"></a>

#### COW validity.

Any changes to the master image will invalidate all COW files. If this happens, UML will *NOT* automatically delete any of the COW files and will refuse to boot. In this case the only solution is to either restore the old image (including its last modified timestamp) or remove all COW files which will result in their recreation. Any changes in the COW files will be lost.

<a id="rst-cows-can-moo-uml-moo-merging-a-cow-file-with-its-backing-file"></a>

#### Cows can moo - uml_moo : Merging a COW file with its backing file

Depending on how you use UML and COW devices, it may be advisable to merge the changes in the COW file into the backing file every once in a while.

The utility that does this is uml_moo.  Its usage is:



```text
uml_moo COW_file new_backing_file
```

There's no need to specify the backing file since that information is already in the COW file header.  If you're paranoid, boot the new merged file, and if you're happy with it, move it over the old backing file.

`uml_moo` creates a new backing file by default as a safety measure. It also has a destructive merge option which will merge the COW file directly into its current backing file.  This is really only usable when the backing file only has one COW file associated with it.  If there are multiple COWs associated with a backing file, a -d merge of one of them will invalidate all of the others.  However, it is convenient if you're short of disk space, and it should also be noticeably faster than a non-destructive merge.

`uml_moo` is installed with the UML distribution packages and is available as a part of UML utilities.

<a id="rst-host-file-access"></a>

### Host file access

If you want to access files on the host machine from inside UML, you can treat it as a separate machine and either nfs mount directories from the host or copy files into the virtual machine with scp. However, since UML is running on the host, it can access those files just like any other process and make them available inside the virtual machine without the need to use the network. This is possible with the hostfs virtual filesystem.  With it, you can mount a host directory into the UML filesystem and access the files contained in it just as you would on the host.

*SECURITY WARNING*

Hostfs without any parameters to the UML Image will allow the image to mount any part of the host filesystem and write to it. Always confine hostfs to a specific "harmless" directory (for example `/var/tmp`) if running UML. This is especially important if UML is being run as root.

<a id="rst-using-hostfs"></a>

#### Using hostfs

To begin with, make sure that hostfs is available inside the virtual machine with:



```text
# cat /proc/filesystems
```

`hostfs` should be listed.  If it's not, either rebuild the kernel with hostfs configured into it or make sure that hostfs is built as a module and available inside the virtual machine, and insmod it.

Now all you need to do is run mount:



```text
# mount none /mnt/host -t hostfs
```

will mount the host's `/` on the virtual machine's `/mnt/host`. If you don't want to mount the host root directory, then you can specify a subdirectory to mount with the -o switch to mount:



```text
# mount none /mnt/home -t hostfs -o /home
```

will mount the host's /home on the virtual machine's /mnt/home.

<a id="rst-hostfs-as-the-root-filesystem"></a>

#### hostfs as the root filesystem

It's possible to boot from a directory hierarchy on the host using hostfs rather than using the standard filesystem in a file. To start, you need that hierarchy.  The easiest way is to loop mount an existing root_fs file:



```text
#  mount root_fs uml_root_dir -o loop
```

You need to change the filesystem type of `/` in `etc/fstab` to be 'hostfs', so that line looks like this:



```text
/dev/ubd/0       /        hostfs      defaults          1   1
```

Then you need to chown to yourself all the files in that directory that are owned by root.  This worked for me:



```text
#  find . -uid 0 -exec chown jdike {} \;
```

Next, make sure that your UML kernel has hostfs compiled in, not as a module.  Then run UML with the boot device pointing at that directory:



```text
ubd0=/path/to/uml/root/directory
```

UML should then boot as it does normally.

<a id="rst-hostfs-caveats"></a>

#### Hostfs Caveats

Hostfs does not support keeping track of host filesystem changes on the host (outside UML). As a result, if a file is changed without UML's knowledge, UML will not know about it and its own in-memory cache of the file may be corrupt. While it is possible to fix this, it is not something which is being worked on at present.

<a id="rst-tuning-uml"></a>

### Tuning UML

UML at present is strictly uniprocessor. It will, however spin up a number of threads to handle various functions.

The UBD driver, SIGIO and the MMU emulation do that. If the system is idle, these threads will be migrated to other processors on a SMP host. This, unfortunately, will usually result in LOWER performance because of all of the cache/memory synchronization traffic between cores. As a result, UML will usually benefit from being pinned on a single CPU, especially on a large system. This can result in performance differences of 5 times or higher on some benchmarks.

Similarly, on large multi-node NUMA systems UML will benefit if all of its memory is allocated from the same NUMA node it will run on. The OS will *NOT* do that by default. In order to do that, the sysadmin needs to create a suitable tmpfs ramdisk bound to a particular node and use that as the source for UML RAM allocation by specifying it in the TMP or TEMP environment variables. UML will look at the values of `TMPDIR`, `TMP` or `TEMP` for that. If that fails, it will look for shmfs mounted under `/dev/shm`. If everything else fails use `/tmp/` regardless of the filesystem type used for it:



```text
mount -t tmpfs -ompol=bind:X none /mnt/tmpfs-nodeX
TEMP=/mnt/tmpfs-nodeX taskset -cX linux options options options..
```

<a id="rst-contributing-to-uml-and-developing-with-uml"></a>

## Contributing to UML and Developing with UML

UML is an excellent platform to develop new Linux kernel concepts - filesystems, devices, virtualization, etc. It provides unrivalled opportunities to create and test them without being constrained to emulating specific hardware.

Example - want to try how Linux will work with 4096 "proper" network devices?

Not an issue with UML. At the same time, this is something which is difficult with other virtualization packages - they are constrained by the number of devices allowed on the hardware bus they are trying to emulate (for example 16 on a PCI bus in qemu).

If you have something to contribute such as a patch, a bugfix, a new feature, please send it to `linux-um@lists.infradead.org`.

Please follow all standard Linux patch guidelines such as cc-ing relevant maintainers and run `./scripts/checkpatch.pl` on your patch. For more details see `Documentation/process/submitting-patches.rst`

Note - the list does not accept HTML or attachments, all emails must be formatted as plain text.

Developing always goes hand in hand with debugging. First of all, you can always run UML under gdb and there will be a whole section later on on how to do that. That, however, is not the only way to debug a Linux kernel. Quite often adding tracing statements and/or using UML specific approaches such as ptracing the UML kernel process are significantly more informative.

<a id="rst-tracing-uml"></a>

### Tracing UML

When running, UML consists of a main kernel thread and a number of helper threads. The ones of interest for tracing are NOT the ones that are already ptraced by UML as a part of its MMU emulation.

These are usually the first three threads visible in a ps display. The one with the lowest PID number and using most CPU is usually the kernel thread. The other threads are the disk (ubd) device helper thread and the SIGIO helper thread. Running ptrace on this thread usually results in the following picture:



```text
host$ strace -p 16566
--- SIGIO {si_signo=SIGIO, si_code=POLL_IN, si_band=65} ---
epoll_wait(4, [{EPOLLIN, {u32=3721159424, u64=3721159424}}], 64, 0) = 1
epoll_wait(4, [], 64, 0)                = 0
rt_sigreturn({mask=[PIPE]})             = 16967
ptrace(PTRACE_GETREGS, 16967, NULL, 0xd5f34f38) = 0
ptrace(PTRACE_GETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=832}]) = 0
ptrace(PTRACE_GETSIGINFO, 16967, NULL, {si_signo=SIGTRAP, si_code=0x85, si_pid=16967, si_uid=0}) = 0
ptrace(PTRACE_SETREGS, 16967, NULL, 0xd5f34f38) = 0
ptrace(PTRACE_SETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=2696}]) = 0
ptrace(PTRACE_SYSEMU, 16967, NULL, 0)   = 0
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_TRAPPED, si_pid=16967, si_uid=0, si_status=SIGTRAP, si_utime=65, si_stime=89} ---
wait4(16967, [{WIFSTOPPED(s) && WSTOPSIG(s) == SIGTRAP | 0x80}], WSTOPPED|__WALL, NULL) = 16967
ptrace(PTRACE_GETREGS, 16967, NULL, 0xd5f34f38) = 0
ptrace(PTRACE_GETREGSET, 16967, NT_X86_XSTATE, [{iov_base=0xd5f35010, iov_len=832}]) = 0
ptrace(PTRACE_GETSIGINFO, 16967, NULL, {si_signo=SIGTRAP, si_code=0x85, si_pid=16967, si_uid=0}) = 0
timer_settime(0, 0, {it_interval={tv_sec=0, tv_nsec=0}, it_value={tv_sec=0, tv_nsec=2830912}}, NULL) = 0
getpid()                                = 16566
clock_nanosleep(CLOCK_MONOTONIC, 0, {tv_sec=1, tv_nsec=0}, NULL) = ? ERESTART_RESTARTBLOCK (Interrupted by signal)
--- SIGALRM {si_signo=SIGALRM, si_code=SI_TIMER, si_timerid=0, si_overrun=0, si_value={int=1631716592, ptr=0x614204f0}} ---
rt_sigreturn({mask=[PIPE]})             = -1 EINTR (Interrupted system call)
```

This is a typical picture from a mostly idle UML instance.

- UML interrupt controller uses epoll - this is UML waiting for IO interrupts:

  > epoll_wait(4, \[\{EPOLLIN, \{u32=3721159424, u64=3721159424\}\}\], 64, 0) = 1

- The sequence of ptrace calls is part of MMU emulation and running the UML userspace.

- `timer_settime` is part of the UML high res timer subsystem mapping timer requests from inside UML onto the host high resolution timers.

- `clock_nanosleep` is UML going into idle (similar to the way a PC will execute an ACPI idle).

As you can see UML will generate quite a bit of output even in idle. The output can be very informative when observing IO. It shows the actual IO calls, their arguments and returns values.

<a id="rst-kernel-debugging"></a>

### Kernel debugging

You can run UML under gdb now, though it will not necessarily agree to be started under it. If you are trying to track a runtime bug, it is much better to attach gdb to a running UML instance and let UML run.

Assuming the same PID number as in the previous example, this would be:



```text
# gdb -p 16566
```

This will STOP the UML instance, so you must enter `cont` at the GDB command line to request it to continue. It may be a good idea to make this into a gdb script and pass it to gdb as an argument.

<a id="rst-developing-device-drivers"></a>

### Developing Device Drivers

Nearly all UML drivers are monolithic. While it is possible to build a UML driver as a kernel module, that limits the possible functionality to in-kernel only and non-UML specific.  The reason for this is that in order to really leverage UML, one needs to write a piece of userspace code which maps driver concepts onto actual userspace host calls.

This forms the so-called "user" portion of the driver. While it can reuse a lot of kernel concepts, it is generally just another piece of userspace code. This portion needs some matching "kernel" code which resides inside the UML image and which implements the Linux kernel part.

*Note: There are very few limitations in the way "kernel" and "user" interact*.

UML does not have a strictly defined kernel-to-host API. It does not try to emulate a specific architecture or bus. UML's "kernel" and "user" can share memory, code and interact as needed to implement whatever design the software developer has in mind. The only limitations are purely technical. Due to a lot of functions and variables having the same names, the developer should be careful which includes and libraries they are trying to refer to.

As a result a lot of userspace code consists of simple wrappers. E.g. `os_close_file()` is just a wrapper around `close()` which ensures that the userspace function close does not clash with similarly named function(s) in the kernel part.

<a id="rst-using-uml-as-a-test-platform"></a>

### Using UML as a Test Platform

UML is an excellent test platform for device driver development. As with most things UML, "some user assembly may be required". It is up to the user to build their emulation environment. UML at present provides only the kernel infrastructure.

Part of this infrastructure is the ability to load and parse fdt device tree blobs as used in Arm or Open Firmware platforms. These are supplied as an optional extra argument to the kernel command line:



```text
dtb=filename
```

The device tree is loaded and parsed at boottime and is accessible by drivers which query it. At this moment in time this facility is intended solely for development purposes. UML's own devices do not query the device tree.

<a id="rst-security-considerations"></a>

#### Security Considerations

Drivers or any new functionality should default to not accepting arbitrary filename, bpf code or other parameters which can affect the host from inside the UML instance. For example, specifying the socket used for IPC communication between a driver and the host at the UML command line is OK security-wise. Allowing it as a loadable module parameter isn't.

If such functionality is desirable for a particular application (e.g. loading BPF "firmware" for raw socket network transports), it should be off by default and should be explicitly turned on as a command line parameter at startup.

Even with this in mind, the level of isolation between UML and the host is relatively weak. If the UML userspace is allowed to load arbitrary kernel drivers, an attacker can use this to break out of UML. Thus, if UML is used in a production application, it is recommended that all modules are loaded at boot and kernel module loading is disabled afterwards.

---

# Accounting

_Peios Kernel / Internals / Accounting_

> Reference for Accounting.

<a id="rst-accounting"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [Control Groupstats](</kernel/internals/accounting/cgroupstats.md>)
- [Delay accounting](</kernel/internals/accounting/delay-accounting.md>)
- [PSI - Pressure Stall Information](</kernel/internals/accounting/psi.md>)
- [Per-task statistics interface](</kernel/internals/accounting/taskstats.md>)
- [The struct taskstats](</kernel/internals/accounting/taskstats-struct.md>)

---

# Control Groupstats

_Peios Kernel / Internals / Accounting_

> Control Groupstats is inspired by the discussion at https://lore.kernel.org/r/461CF883.2030308@sw.ru and implements per cgroup statistics as suggested by Andrew Morton in…

<a id="rst-control-groupstats"></a>

Control Groupstats is inspired by the discussion at [https://lore.kernel.org/r/461CF883.2030308@sw.ru](<https://lore.kernel.org/r/461CF883.2030308@sw.ru>) and implements per cgroup statistics as suggested by Andrew Morton in [https://lore.kernel.org/r/20070411114927.1277d7c9.akpm@linux-foundation.org](<https://lore.kernel.org/r/20070411114927.1277d7c9.akpm@linux-foundation.org>).

Per cgroup statistics infrastructure re-uses code from the taskstats interface. A new set of cgroup operations are registered with commands and attributes specific to cgroups. It should be very easy to extend per cgroup statistics, by adding members to the cgroupstats structure.

The current model for cgroupstats is a pull, a push model (to post statistics on interesting events), should be very easy to add. Currently user space requests for statistics by passing the cgroup path. Statistics about the state of all the tasks in the cgroup is returned to user space.

NOTE: We currently rely on delay accounting for extracting information about tasks blocked on I/O. If CONFIG_TASK_DELAY_ACCT is disabled, this information will not be available.

To extract cgroup statistics a utility very similar to getdelays.c has been developed, the sample output of the utility is shown below:



```text
~/balbir/cgroupstats # ./getdelays  -C "/sys/fs/cgroup/a"
sleeping 1, blocked 0, running 1, stopped 0, uninterruptible 0
~/balbir/cgroupstats # ./getdelays  -C "/sys/fs/cgroup"
sleeping 155, blocked 0, running 1, stopped 0, uninterruptible 2
```

---

# Delay accounting

_Peios Kernel / Internals / Accounting_

> Tasks encounter delays in execution when they wait for some kernel resource to become available e.g. a runnable task may wait for a free CPU to run on.

<a id="rst-delay-accounting"></a>

Tasks encounter delays in execution when they wait for some kernel resource to become available e.g. a runnable task may wait for a free CPU to run on.

The per-task delay accounting functionality measures the delays experienced by a task while

- **a)** waiting for a CPU (while being runnable)

- **b)** completion of synchronous block I/O initiated by the task

- **c)** swapping in pages

- **d)** memory reclaim

- **e)** thrashing

- **f)** direct compact

- **g)** write-protect copy

- **h)** IRQ/SOFTIRQ

and makes these statistics available to userspace through the taskstats interface.

Such delays provide feedback for setting a task's cpu priority, io priority and rss limit values appropriately. Long delays for important tasks could be a trigger for raising its corresponding priority.

The functionality, through its use of the taskstats interface, also provides delay statistics aggregated for all tasks (or threads) belonging to a thread group (corresponding to a traditional Unix process). This is a commonly needed aggregation that is more efficiently done by the kernel.

Userspace utilities, particularly resource management applications, can also aggregate delay statistics into arbitrary groups. To enable this, delay statistics of a task are available both during its lifetime as well as on its exit, ensuring continuous and complete monitoring can be done.

<a id="rst-interface"></a>

## Interface

Delay accounting uses the taskstats interface which is described in detail in a separate document in this directory. Taskstats returns a generic data structure to userspace corresponding to per-pid and per-tgid statistics. The delay accounting functionality populates specific fields of this structure. See

> include/uapi/linux/taskstats.h

for a description of the fields pertaining to delay accounting. It will generally be in the form of counters returning the cumulative delay seen for cpu, sync block I/O, swapin, memory reclaim, thrash page cache, direct compact, write-protect copy, IRQ/SOFTIRQ etc.

Taking the difference of two successive readings of a given counter (say cpu_delay_total) for a task will give the delay experienced by the task waiting for the corresponding resource in that interval.

When a task exits, records containing the per-task statistics are sent to userspace without requiring a command. If it is the last exiting task of a thread group, the per-tgid statistics are also sent. More details are given in the taskstats interface description.

The getdelays.c userspace utility in tools/accounting directory allows simple commands to be run and the corresponding delay statistics to be displayed. It also serves as an example of using the taskstats interface.

<a id="rst-usage"></a>

## Usage

Compile the kernel with:



```text
CONFIG_TASK_DELAY_ACCT=y
CONFIG_TASKSTATS=y
```

Delay accounting is disabled by default at boot up. To enable, add:



```text
delayacct
```

to the kernel boot options. The rest of the instructions below assume this has been done. Alternatively, use sysctl kernel.task_delayacct to switch the state at runtime. Note however that only tasks started after enabling it will have delayacct information.

After the system has booted up, use a utility similar to  getdelays.c to access the delays seen by a given task or a task group (tgid). The utility also allows a given command to be executed and the corresponding delays to be seen.

General format of the getdelays command:



```text
getdelays [-dilv] [-t tgid] [-p pid]
```

Get delays, since system boot, for pid 10:



```text
# ./getdelays -d -p 10
(output similar to next case)
```

Get sum and peak of delays, since system boot, for all pids with tgid 242:



```text
bash-4.4# ./getdelays -d -t 242
print delayacct stats ON
TGID    242


CPU         count     real total  virtual total    delay total  delay average      delay max      delay min      delay max timestamp
               46      188000000      192348334        4098012          0.089ms     0.429260ms     0.051205ms    2026-01-15T15:06:58
IO          count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
SWAP        count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
RECLAIM     count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
THRASHING   count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
COMPACT     count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
WPCOPY      count    delay total  delay average      delay max      delay min      delay max timestamp
              182       19413338          0.107ms     0.547353ms     0.022462ms    2026-01-15T15:05:24
IRQ         count    delay total  delay average      delay max      delay min      delay max timestamp
                0              0          0.000ms     0.000000ms     0.000000ms                    N/A
```

Get IO accounting for pid 1, it works only with -p:



```text
# ./getdelays -i -p 1
printing IO accounting
linuxrc: read=65536, write=0, cancelled_write=0
```

The above command can be used with -v to get more debug information.

After the system starts, use `delaytop` to get the system-wide delay information, which includes system-wide PSI information and Top-N high-latency tasks. Note: PSI support requires `CONFIG_PSI=y` and `psi=1` for full functionality.

`delaytop` is an interactive tool for monitoring system pressure and task delays. It supports multiple sorting options, display modes, and real-time keyboard controls.

Basic usage with default settings (sorts by CPU delay, shows top 20 tasks, refreshes every 2 seconds):



```text
bash# ./delaytop
System Pressure Information: (avg10/avg60vg300/total)
CPU some:       0.0%/   0.0%/   0.0%/  106137(ms)
CPU full:       0.0%/   0.0%/   0.0%/       0(ms)
Memory full:    0.0%/   0.0%/   0.0%/       0(ms)
Memory some:    0.0%/   0.0%/   0.0%/       0(ms)
IO full:        0.0%/   0.0%/   0.0%/    2240(ms)
IO some:        0.0%/   0.0%/   0.0%/    2783(ms)
IRQ full:       0.0%/   0.0%/   0.0%/       0(ms)
[o]sort [M]memverbose [q]quit
Top 20 processes (sorted by cpu delay):
        PID      TGID  COMMAND           CPU(ms)   IO(ms)  IRQ(ms)  MEM(ms)
------------------------------------------------------------------------
        110       110  kworker/15:0H-s   27.91     0.00     0.00     0.00
        57        57  cpuhp/7            3.18     0.00     0.00     0.00
        99        99  cpuhp/14           2.97     0.00     0.00     0.00
        51        51  cpuhp/6            0.90     0.00     0.00     0.00
        44        44  kworker/4:0H-sy    0.80     0.00     0.00     0.00
        60        60  ksoftirqd/7        0.74     0.00     0.00     0.00
        76        76  idle_inject/10     0.31     0.00     0.00     0.00
        100       100  idle_inject/14     0.30     0.00     0.00     0.00
        1309      1309  systemsettings     0.29     0.00     0.00     0.00
        45        45  cpuhp/5            0.22     0.00     0.00     0.00
        63        63  cpuhp/8            0.20     0.00     0.00     0.00
        87        87  cpuhp/12           0.18     0.00     0.00     0.00
        93        93  cpuhp/13           0.17     0.00     0.00     0.00
        1265      1265  acpid              0.17     0.00     0.00     0.00
        1552      1552  sshd               0.17     0.00     0.00     0.00
        2584      2584  sddm-helper        0.16     0.00     0.00     0.00
        1284      1284  rtkit-daemon       0.15     0.00     0.00     0.00
        1326      1326  nde-netfilter      0.14     0.00     0.00     0.00
        27        27  cpuhp/2            0.13     0.00     0.00     0.00
        631       631  kworker/11:2-rc    0.11     0.00     0.00     0.00
```

Interactive keyboard controls during runtime:



```text
o - Select sort field (CPU, IO, IRQ, Memory, etc.)
M - Toggle display mode (Default/Memory Verbose)
q - Quit
```

Available sort fields(use -s/--sort or interactive command):



```text
cpu(c)       - CPU delay
blkio(i)     - I/O delay
irq(q)       - IRQ delay
mem(m)       - Total memory delay
swapin(s)    - Swapin delay (memory verbose mode only)
freepages(r) - Freepages reclaim delay (memory verbose mode only)
thrashing(t) - Thrashing delay (memory verbose mode only)
compact(p)   - Compaction delay (memory verbose mode only)
wpcopy(w)    - Write page copy delay (memory verbose mode only)
```

Advanced usage examples:



```text
# ./delaytop -s blkio
Sorted by IO delay

# ./delaytop -s mem -M
Sorted by memory delay in memory verbose mode

# ./delaytop -p pid
Print delayacct stats

# ./delaytop -P num
Display the top N tasks

# ./delaytop -n num
Set delaytop refresh frequency (num times)

# ./delaytop -d secs
Specify refresh interval as secs
```

---

# PSI - Pressure Stall Information

_Peios Kernel / Internals / Accounting_

> When CPU, memory or IO devices are contended, workloads experience latency spikes, throughput losses, and run the risk of OOM kills.

> **Peios:** Interface availability and resource limits do not grant native access. Peios applies descriptor/handle checks, its sysfs write gate and mapped privilege checks where applicable. Read inherited privileged/unprivileged terminology with [Peios kernel behaviour](</kernel/introduction/peios-behaviour.md>).


<a id="rst-psi-pressure-stall-information"></a>
<a id="rst-psi"></a>

**Date:** April, 2018

**Author:** Johannes Weiner &lt;[hannes@cmpxchg.org](<mailto:hannes@cmpxchg.org>)&gt;

When CPU, memory or IO devices are contended, workloads experience latency spikes, throughput losses, and run the risk of OOM kills.

Without an accurate measure of such contention, users are forced to either play it safe and under-utilize their hardware resources, or roll the dice and frequently suffer the disruptions resulting from excessive overcommit.

The psi feature identifies and quantifies the disruptions caused by such resource crunches and the time impact it has on complex workloads or even entire systems.

Having an accurate measure of productivity losses caused by resource scarcity aids users in sizing workloads to hardware--or provisioning hardware according to workload demand.

As psi aggregates this information in realtime, systems can be managed dynamically using techniques such as load shedding, migrating jobs to other systems or data centers, or strategically pausing or killing low priority or restartable batch jobs.

This allows maximizing hardware utilization without sacrificing workload health or risking major disruptions such as OOM kills.

<a id="rst-pressure-interface"></a>

## Pressure interface

Pressure information for each resource is exported through the respective file in /proc/pressure/ -- cpu, memory, and io.

The format is as such:



```text
some avg10=0.00 avg60=0.00 avg300=0.00 total=0
full avg10=0.00 avg60=0.00 avg300=0.00 total=0
```

The "some" line indicates the share of time in which at least some tasks are stalled on a given resource.

The "full" line indicates the share of time in which all non-idle tasks are stalled on a given resource simultaneously. In this state actual CPU cycles are going to waste, and a workload that spends extended time in this state is considered to be thrashing. This has severe impact on performance, and it's useful to distinguish this situation from a state where some tasks are stalled but the CPU is still doing productive work. As such, time spent in this subset of the stall state is tracked separately and exported in the "full" averages.

CPU full is undefined at the system level, but has been reported since 5.13, so it is set to zero for backward compatibility.

The ratios (in %) are tracked as recent trends over ten, sixty, and three hundred second windows, which gives insight into short term events as well as medium and long term trends. The total absolute stall time (in us) is tracked and exported as well, to allow detection of latency spikes which wouldn't necessarily make a dent in the time averages, or to average trends over custom time frames.

<a id="rst-monitoring-for-pressure-thresholds"></a>

## Monitoring for pressure thresholds

Users can register triggers and use poll() to be woken up when resource pressure exceeds certain thresholds.

A trigger describes the maximum cumulative stall time over a specific time window, e.g. 100ms of total stall time within any 500ms window to generate a wakeup event.

To register a trigger user has to open psi interface file under /proc/pressure/ representing the resource to be monitored and write the desired threshold and time window. The open file descriptor should be used to wait for trigger events using select(), poll() or epoll(). The following format is used:



```text
<some|full> <stall amount in us> <time window in us>
```

For example writing "some 150000 1000000" into /proc/pressure/memory would add 150ms threshold for partial memory stall measured within 1sec time window. Writing "full 50000 1000000" into /proc/pressure/io would add 50ms threshold for full io stall measured within 1sec time window.

Triggers can be set on more than one psi metric and more than one trigger for the same psi metric can be specified. However for each trigger a separate file descriptor is required to be able to poll it separately from others, therefore for each trigger a separate open() syscall should be made even when opening the same psi interface file. Write operations to a file descriptor with an already existing psi trigger will fail with EBUSY.

Monitors activate only when system enters stall state for the monitored psi metric and deactivates upon exit from the stall state. While system is in the stall state psi signal growth is monitored at a rate of 10 times per tracking window.

The kernel accepts window sizes ranging from 500ms to 10s, therefore min monitoring update interval is 50ms and max is 1s. Min limit is set to prevent overly frequent polling. Max limit is chosen as a high enough number after which monitors are most likely not needed and psi averages can be used instead.

Unprivileged users can also create monitors, with the only limitation that the window size must be a multiple of 2s, in order to prevent excessive resource usage.

When activated, psi monitor stays active for at least the duration of one tracking window to avoid repeated activations/deactivations when system is bouncing in and out of the stall state.

Notifications to the userspace are rate-limited to one per tracking window.

The trigger will de-register when the file descriptor used to define the trigger  is closed.

<a id="rst-userspace-monitor-usage-example"></a>

## Userspace monitor usage example



```text
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <poll.h>
#include <string.h>
#include <unistd.h>

/*
 * Monitor memory partial stall with 1s tracking window size
 * and 150ms threshold.
 */
int main() {
      const char trig[] = "some 150000 1000000";
      struct pollfd fds;
      int n;

      fds.fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK);
      if (fds.fd < 0) {
              printf("/proc/pressure/memory open error: %s\n",
                      strerror(errno));
              return 1;
      }
      fds.events = POLLPRI;

      if (write(fds.fd, trig, strlen(trig) + 1) < 0) {
              printf("/proc/pressure/memory write error: %s\n",
                      strerror(errno));
              return 1;
      }

      printf("waiting for events...\n");
      while (1) {
              n = poll(&fds, 1, -1);
              if (n < 0) {
                      printf("poll error: %s\n", strerror(errno));
                      return 1;
              }
              if (fds.revents & POLLERR) {
                      printf("got POLLERR, event source is gone\n");
                      return 0;
              }
              if (fds.revents & POLLPRI) {
                      printf("event triggered!\n");
              } else {
                      printf("unknown event received: 0x%x\n", fds.revents);
                      return 1;
              }
      }

      return 0;
}
```

<a id="rst-cgroup2-interface"></a>

## Cgroup2 interface

In a system with a CONFIG_CGROUPS=y kernel and the cgroup2 filesystem mounted, pressure stall information is also tracked for tasks grouped into cgroups. Each subdirectory in the cgroupfs mountpoint contains cpu.pressure, memory.pressure, and io.pressure files; the format is the same as the /proc/pressure/ files.

Per-cgroup psi monitors can be specified and used the same way as system-wide ones.

---

# The struct taskstats

_Peios Kernel / Internals / Accounting_

> This document contains an explanation of the struct taskstats fields.

<a id="rst-the-struct-taskstats"></a>

This document contains an explanation of the struct taskstats fields.

There are three different groups of fields in the struct taskstats:

1. - **Common and basic accounting fields**

     If CONFIG_TASKSTATS is set, the taskstats interface is enabled and the common fields and basic accounting fields are collected for delivery at do_exit() of a task.

2. - **Delay accounting fields**

     These fields are placed between:



     ```text
     /* Delay accounting fields start */
     ```

     and:



     ```text
     /* Delay accounting fields end */
     ```

     Their values are collected if CONFIG_TASK_DELAY_ACCT is set.

3. - **Extended accounting fields**

     These fields are placed between:



     ```text
     /* Extended accounting fields start */
     ```

     and:



     ```text
     /* Extended accounting fields end */
     ```

     Their values are collected if CONFIG_TASK_XACCT is set.

4. Per-task and per-thread context switch count statistics

5. Time accounting for SMT machines

6. Extended delay accounting fields for memory reclaim

Future extension should add fields to the end of the taskstats struct, and should not change the relative position of each field within the struct.



```text
struct taskstats {
```

1. Common and basic accounting fields:



   ```text
   /* The version number of this struct. This field is always set to
    * TASKSTATS_VERSION, which is defined in <linux/taskstats.h>.
    * Each time the struct is changed, the value should be incremented.
    */
   __u16   version;

   /* The exit code of a task. */
   __u32   ac_exitcode;            /* Exit status */

   /* The accounting flags of a task as defined in <linux/acct.h>
    * Defined values are AFORK, ASU, ACOMPAT, ACORE, and AXSIG.
    */
   __u8    ac_flag;                /* Record flags */

   /* The value of task_nice() of a task. */
   __u8    ac_nice;                /* task_nice */

   /* The name of the command that started this task. */
   char    ac_comm[TS_COMM_LEN];   /* Command name */

   /* The scheduling discipline as set in task->policy field. */
   __u8    ac_sched;               /* Scheduling discipline */

   __u8    ac_pad[3];
   __u32   ac_uid;                 /* User ID */
   __u32   ac_gid;                 /* Group ID */
   __u32   ac_pid;                 /* Process ID */
   __u32   ac_ppid;                /* Parent process ID */

   /* The time when a task begins, in [secs] since 1970. */
   __u32   ac_btime;               /* Begin time [sec since 1970] */

   /* The elapsed time of a task, in [usec]. */
   __u64   ac_etime;               /* Elapsed time [usec] */

   /* The user CPU time of a task, in [usec]. */
   __u64   ac_utime;               /* User CPU time [usec] */

   /* The system CPU time of a task, in [usec]. */
   __u64   ac_stime;               /* System CPU time [usec] */

   /* The minor page fault count of a task, as set in task->min_flt. */
   __u64   ac_minflt;              /* Minor Page Fault Count */

   /* The major page fault count of a task, as set in task->maj_flt. */
   __u64   ac_majflt;              /* Major Page Fault Count */
   ```

2. Delay accounting fields:



   ```text
   /* Delay accounting fields start
    *
    * All values, until the comment "Delay accounting fields end" are
    * available only if delay accounting is enabled, even though the last
    * few fields are not delays
    *
    * xxx_count is the number of delay values recorded
    * xxx_delay_total is the corresponding cumulative delay in nanoseconds
    *
    * xxx_delay_total wraps around to zero on overflow
    * xxx_count incremented regardless of overflow
    */

   /* Delay waiting for cpu, while runnable
    * count, delay_total NOT updated atomically
    */
   __u64   cpu_count;
   __u64   cpu_delay_total;

   /* Following four fields atomically updated using task->delays->lock */

   /* Delay waiting for synchronous block I/O to complete
    * does not account for delays in I/O submission
    */
   __u64   blkio_count;
   __u64   blkio_delay_total;

   /* Delay waiting for page fault I/O (swap in only) */
   __u64   swapin_count;
   __u64   swapin_delay_total;

   /* cpu "wall-clock" running time
    * On some architectures, value will adjust for cpu time stolen
    * from the kernel in involuntary waits due to virtualization.
    * Value is cumulative, in nanoseconds, without a corresponding count
    * and wraps around to zero silently on overflow
    */
   __u64   cpu_run_real_total;

   /* cpu "virtual" running time
    * Uses time intervals seen by the kernel i.e. no adjustment
    * for kernel's involuntary waits due to virtualization.
    * Value is cumulative, in nanoseconds, without a corresponding count
    * and wraps around to zero silently on overflow
    */
   __u64   cpu_run_virtual_total;
   /* Delay accounting fields end */
   /* version 1 ends here */
   ```

3. Extended accounting fields:



   ```text
   /* Extended accounting fields start */

   /* Accumulated RSS usage in duration of a task, in MBytes-usecs.
    * The current rss usage is added to this counter every time
    * a tick is charged to a task's system time. So, at the end we
    * will have memory usage multiplied by system time. Thus an
    * average usage per system time unit can be calculated.
    */
   __u64   coremem;                /* accumulated RSS usage in MB-usec */

   /* Accumulated virtual memory usage in duration of a task.
    * Same as acct_rss_mem1 above except that we keep track of VM usage.
    */
   __u64   virtmem;                /* accumulated VM usage in MB-usec */

   /* High watermark of RSS usage in duration of a task, in KBytes. */
   __u64   hiwater_rss;            /* High-watermark of RSS usage */

   /* High watermark of VM  usage in duration of a task, in KBytes. */
   __u64   hiwater_vm;             /* High-water virtual memory usage */

   /* The following four fields are I/O statistics of a task. */
   __u64   read_char;              /* bytes read */
   __u64   write_char;             /* bytes written */
   __u64   read_syscalls;          /* read syscalls */
   __u64   write_syscalls;         /* write syscalls */

   /* Extended accounting fields end */
   ```

4. Per-task and per-thread statistics:



   ```text
   __u64   nvcsw;                  /* Context voluntary switch counter */
   __u64   nivcsw;                 /* Context involuntary switch counter */
   ```

5. Time accounting for SMT machines:



   ```text
   __u64   ac_utimescaled;         /* utime scaled on frequency etc */
   __u64   ac_stimescaled;         /* stime scaled on frequency etc */
   __u64   cpu_scaled_run_real_total; /* scaled cpu_run_real_total */
   ```

6. Extended delay accounting fields for memory reclaim:



   ```text
   /* Delay waiting for memory reclaim */
   __u64   freepages_count;
   __u64   freepages_delay_total;
   ```



```text
}
```

---

# Per-task statistics interface

_Peios Kernel / Internals / Accounting_

> Taskstats is a netlink-based interface for sending per-task and per-process statistics from the kernel to userspace.

<a id="rst-per-task-statistics-interface"></a>

Taskstats is a netlink-based interface for sending per-task and per-process statistics from the kernel to userspace.

Taskstats was designed for the following benefits:

- efficiently provide statistics during lifetime of a task and on its exit

- unified interface for multiple accounting subsystems

- extensibility for use by future accounting patches

<a id="rst-terminology"></a>

## Terminology

"pid", "tid" and "task" are used interchangeably and refer to the standard Linux task defined by struct task_struct.  per-pid stats are the same as per-task stats.

"tgid", "process" and "thread group" are used interchangeably and refer to the tasks that share an mm_struct i.e. the traditional Unix process. Despite the use of tgid, there is no special treatment for the task that is thread group leader - a process is deemed alive as long as it has any task belonging to it.

<a id="rst-usage"></a>

## Usage

To get statistics during a task's lifetime, userspace opens a unicast netlink socket (NETLINK_GENERIC family) and sends commands specifying a pid or a tgid. The response contains statistics for a task (if pid is specified) or the sum of statistics for all tasks of the process (if tgid is specified).

To obtain statistics for tasks which are exiting, the userspace listener sends a register command and specifies a cpumask. Whenever a task exits on one of the cpus in the cpumask, its per-pid statistics are sent to the registered listener. Using cpumasks allows the data received by one listener to be limited and assists in flow control over the netlink interface and is explained in more detail below.

If the exiting task is the last thread exiting its thread group, an additional record containing the per-tgid stats is also sent to userspace. The latter contains the sum of per-pid stats for all threads in the thread group, both past and present.

getdelays.c is a simple utility demonstrating usage of the taskstats interface for reporting delay accounting statistics. Users can register cpumasks, send commands and process responses, listen for per-tid/tgid exit data, write the data received to a file and do basic flow control by increasing receive buffer sizes.

<a id="rst-interface"></a>

## Interface

The user-kernel interface is encapsulated in include/linux/taskstats.h

To avoid this documentation becoming obsolete as the interface evolves, only an outline of the current version is given. taskstats.h always overrides the description here.

struct taskstats is the common accounting structure for both per-pid and per-tgid data. It is versioned and can be extended by each accounting subsystem that is added to the kernel. The fields and their semantics are defined in the taskstats.h file.

The data exchanged between user and kernel space is a netlink message belonging to the NETLINK_GENERIC family and using the netlink attributes interface. The messages are in the format:



```text
+----------+- - -+-------------+-------------------+
| nlmsghdr | Pad |  genlmsghdr | taskstats payload |
+----------+- - -+-------------+-------------------+
```

The taskstats payload is one of the following three kinds:

1. Commands: Sent from user to kernel. Commands to get data on a pid/tgid consist of one attribute, of type TASKSTATS_CMD_ATTR_PID/TGID, containing a u32 pid or tgid in the attribute payload. The pid/tgid denotes the task/process for which userspace wants statistics.

   Commands to register/deregister interest in exit data from a set of cpus consist of one attribute, of type TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK and contain a cpumask in the attribute payload. The cpumask is specified as an ascii string of comma-separated cpu ranges e.g. to listen to exit data from cpus 1,2,3,5,7,8 the cpumask would be "1-3,5,7-8". If userspace forgets to deregister interest in cpus before closing the listening socket, the kernel cleans up its interest set over time. However, for the sake of efficiency, an explicit deregistration is advisable.

2. Response for a command: sent from the kernel in response to a userspace command. The payload is a series of three attributes of type:

   - **a)** TASKSTATS_TYPE_AGGR_PID/TGID: attribute containing no payload but indicates a pid/tgid will be followed by some stats.

   - **b)** TASKSTATS_TYPE_PID/TGID: attribute whose payload is the pid/tgid whose stats are being returned.

   - **c)** TASKSTATS_TYPE_STATS: attribute with a struct taskstats as payload. The same structure is used for both per-pid and per-tgid stats.

3. New message sent by kernel whenever a task exits. The payload consists of a series of attributes of the following type:

   - **a)** TASKSTATS_TYPE_AGGR_PID: indicates next two attributes will be pid+stats

   - **b)** TASKSTATS_TYPE_PID: contains exiting task's pid

   - **c)** TASKSTATS_TYPE_STATS: contains the exiting task's per-pid stats

   - **d)** TASKSTATS_TYPE_AGGR_TGID: indicates next two attributes will be tgid+stats

   - **e)** TASKSTATS_TYPE_TGID: contains tgid of process to which task belongs

   - **f)** TASKSTATS_TYPE_STATS: contains the per-tgid stats for exiting task's process

<a id="rst-per-tgid-stats"></a>

## per-tgid stats

Taskstats provides per-process stats, in addition to per-task stats, since resource management is often done at a process granularity and aggregating task stats in userspace alone is inefficient and potentially inaccurate (due to lack of atomicity).

However, maintaining per-process, in addition to per-task stats, within the kernel has space and time overheads. To address this, the taskstats code accumulates each exiting task's statistics into a process-wide data structure. When the last task of a process exits, the process level data accumulated also gets sent to userspace (along with the per-task data).

When a user queries to get per-tgid data, the sum of all other live threads in the group is added up and added to the accumulated total for previously exited threads of the same thread group.

<a id="rst-extending-taskstats"></a>

## Extending taskstats

There are two ways to extend the taskstats interface to export more per-task/process stats as patches to collect them get added to the kernel in future:

1. Adding more fields to the end of the existing struct taskstats. Backward compatibility is ensured by the version number within the structure. Userspace will use only the fields of the struct that correspond to the version its using.

2. Defining separate statistic structs and using the netlink attributes interface to return them. Since userspace processes each netlink attribute independently, it can always ignore attributes whose type it does not understand (because it is using an older version of the interface).

Choosing between 1. and 2. is a matter of trading off flexibility and overhead. If only a few fields need to be added, then 1. is the preferable path since the kernel and userspace don't need to incur the overhead of processing new netlink attributes. But if the new fields expand the existing struct too much, requiring disparate userspace accounting utilities to unnecessarily receive large structures whose fields are of no interest, then extending the attributes structure would be worthwhile.

<a id="rst-flow-control-for-taskstats"></a>

## Flow control for taskstats

When the rate of task exits becomes large, a listener may not be able to keep up with the kernel's rate of sending per-tid/tgid exit data leading to data loss. This possibility gets compounded when the taskstats structure gets extended and the number of cpus grows large.

To avoid losing statistics, userspace should do one or more of the following:

- increase the receive buffer sizes for the netlink sockets opened by listeners to receive exit data.

- create more listeners and reduce the number of cpus being listened to by each listener. In the extreme case, there could be one listener for each cpu. Users may also consider setting the cpu affinity of the listener to the subset of cpus to which it listens, especially if they are listening to just one cpu.

Despite these measures, if the userspace receives ENOBUFS error messages indicated overflow of receive buffers, it should take measures to handle the loss of data.

---

# Timers

_Peios Kernel / Internals / Timers_

> Reference for Timers.

<a id="rst-timers"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

- [High resolution timers and dynamic ticks design notes](</kernel/internals/timers/highres.md>)
- [High Precision Event Timer Driver for Linux](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/timers/hpet.rst?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)
- [hrtimers - subsystem for high-resolution kernel timers](</kernel/internals/timers/hrtimers.md>)
- [NO_HZ: Reducing Scheduling-Clock Ticks](</kernel/internals/timers/no-hz.md>)
- [Clock sources, Clock events, sched_clock() and delay timers](</kernel/internals/timers/timekeeping.md>)
- [Delay and sleep mechanisms](</kernel/internals/timers/delay-sleep-functions.md>)

---

# Delay and sleep mechanisms

_Peios Kernel / Internals / Timers_

> This document seeks to answer the common question: "What is the RightWay (TM) to insert a delay?"

<a id="rst-delay-and-sleep-mechanisms"></a>

<!-- SPDX-License-Identifier: GPL-2.0 -->

This document seeks to answer the common question: "What is the RightWay (TM) to insert a delay?"

This question is most often faced by driver writers who have to deal with hardware delays and who may not be the most intimately familiar with the inner workings of the Linux Kernel.

The following table gives a rough overview about the existing function 'families' and their limitations. This overview table does not replace the reading of the function description before usage\!


<table>
<thead>
<tr>
<th>




</th>
<th>


`*delay()`

</th>
<th>


`usleep_range*()`

</th>
<th>


`*sleep()`

</th>
<th>


`fsleep()`

</th>
</tr>
<tr>
<th>




</th>
<th>


busy-wait loop

</th>
<th>


hrtimers based

</th>
<th>


timer list timers based

</th>
<th>


combines the others

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


Usage in atomic Context

</td>
<td>


yes

</td>
<td>


no

</td>
<td>


no

</td>
<td>


no

</td>
</tr>
<tr>
<td>


precise on "short intervals"

</td>
<td>


yes

</td>
<td>


yes

</td>
<td>


depends

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


precise on "long intervals"

</td>
<td>


Do not use\!

</td>
<td>


yes

</td>
<td>


max 12.5% slack

</td>
<td>


yes

</td>
</tr>
<tr>
<td>


interruptible variant

</td>
<td>


no

</td>
<td>


yes

</td>
<td>


yes

</td>
<td>


no

</td>
</tr>
</tbody>
</table>

A generic advice for non atomic contexts could be:

1. Use `fsleep()` whenever unsure (as it combines all the advantages of the others)

2. Use `*sleep()` whenever possible

3. Use `usleep_range*()` whenever accuracy of `*sleep()` is not sufficient

4. Use `*delay()` for very, very short delays

Find some more detailed information about the function 'families' in the next sections.

<a id="rst-delay-family-of-functions"></a>

## `*delay()` family of functions

These functions use the jiffy estimation of clock speed and will busy wait for enough loop cycles to achieve the desired delay. udelay() is the basic implementation and ndelay() as well as mdelay() are variants.

These functions are mainly used to add a delay in atomic context. Please make sure to ask yourself before adding a delay in atomic context: Is this really required?


#### <a id="c-udelay"></a>`udelay()`

```c
void udelay(unsigned long usec)
```

Inserting a delay based on microseconds with busy waiting

**Parameters**

- `unsigned long usec`: requested delay in microseconds

**Description**

When delaying in an atomic context [`ndelay()`](#c-ndelay), [`udelay()`](#c-udelay) and [`mdelay()`](#c-mdelay) are the
only valid variants of delaying/sleeping to go with.

When inserting delays in non atomic context which are shorter than the time
which is required to queue e.g. an hrtimer and to enter then the scheduler,
it is also valuable to use [`udelay()`](#c-udelay). But it is not simple to specify a
generic threshold for this which will fit for all systems. An approximation
is a threshold for all delays up to 10 microseconds.

When having a delay which is larger than the architecture specific
`MAX_UDELAY_MS` value, please make sure [`mdelay()`](#c-mdelay) is used. Otherwise a overflow
risk is given.

Please note that [`ndelay()`](#c-ndelay), [`udelay()`](#c-udelay) and [`mdelay()`](#c-mdelay) may return early for several
reasons (https://lists.openwall.net/linux-kernel/2011/01/09/56):

1. computed loops_per_jiffy too low (due to the time taken to execute the
   timer interrupt.)
1. cache behaviour affecting the time it takes to execute the loop function.
1. CPU clock rate changes.

#### <a id="c-ndelay"></a>`ndelay()`

```c
void ndelay(unsigned long nsec)
```

Inserting a delay based on nanoseconds with busy waiting

**Parameters**

- `unsigned long nsec`: requested delay in nanoseconds

**Description**

See [`udelay()`](#c-udelay) for basic information about [`ndelay()`](#c-ndelay) and it's variants.



#### <a id="c-mdelay"></a>`mdelay()`

```c
mdelay(n)
```

Inserting a delay based on milliseconds with busy waiting

**Parameters**

- `n`: requested delay in milliseconds

**Description**

See [`udelay()`](#c-udelay) for basic information about [`mdelay()`](#c-mdelay) and it's variants.

Please double check, whether [`mdelay()`](#c-mdelay) is the right way to go or whether a
refactoring of the code is the better variant to be able to use [`msleep()`](#c-msleep)
instead.


<a id="rst-usleep-range-and-sleep-family-of-functions"></a>

## `usleep_range*()` and `*sleep()` family of functions

These functions use hrtimers or timer list timers to provide the requested sleeping duration. In order to decide which function is the right one to use, take some basic information into account:

1. hrtimers are more expensive as they are using an rb-tree (instead of hashing)

2. hrtimers are more expensive when the requested sleeping duration is the first timer which means real hardware has to be programmed

3. timer list timers always provide some sort of slack as they are jiffy based

The generic advice is repeated here:

1. Use `fsleep()` whenever unsure (as it combines all the advantages of the others)

2. Use `*sleep()` whenever possible

3. Use `usleep_range*()` whenever accuracy of `*sleep()` is not sufficient

First check fsleep() function description and to learn more about accuracy, please check msleep() function description.

<a id="rst-usleep-range"></a>

### `usleep_range*()`


#### <a id="c-usleep_range"></a>`usleep_range()`

```c
void usleep_range(unsigned long min, unsigned long max)
```

Sleep for an approximate time

**Parameters**

- `unsigned long min`: Minimum time in microseconds to sleep
- `unsigned long max`: Maximum time in microseconds to sleep

**Description**

For basic information please refer to [`usleep_range_state()`](#c-usleep_range_state).

The task will be in the state TASK_UNINTERRUPTIBLE during the sleep.

#### <a id="c-usleep_range_idle"></a>`usleep_range_idle()`

```c
void usleep_range_idle(unsigned long min, unsigned long max)
```

Sleep for an approximate time with idle time accounting

**Parameters**

- `unsigned long min`: Minimum time in microseconds to sleep
- `unsigned long max`: Maximum time in microseconds to sleep

**Description**

For basic information please refer to [`usleep_range_state()`](#c-usleep_range_state).

The sleeping task has the state TASK_IDLE during the sleep to prevent
contribution to the load average.



#### <a id="c-usleep_range_state"></a>`usleep_range_state()`

```c
void usleep_range_state(unsigned long min, unsigned long max, unsigned int state)
```

Sleep for an approximate time in a given state

**Parameters**

- `unsigned long min`: Minimum time in usecs to sleep
- `unsigned long max`: Maximum time in usecs to sleep
- `unsigned int state`: State of the current task that will be while sleeping

**Description**

[`usleep_range_state()`](#c-usleep_range_state) sleeps at least for the minimum specified time but not
longer than the maximum specified amount of time. The range might reduce
power usage by allowing hrtimers to coalesce an already scheduled interrupt
with this hrtimer. In the worst case, an interrupt is scheduled for the upper
bound.

The sleeping task is set to the specified state before starting the sleep.

In non-atomic context where the exact wakeup time is flexible, use
[`usleep_range()`](#c-usleep_range) or its variants instead of [`udelay()`](#c-udelay). The sleep improves
responsiveness by avoiding the CPU-hogging busy-wait of [`udelay()`](#c-udelay).


<a id="rst-sleep"></a>

### `*sleep()`


#### <a id="c-msleep"></a>`msleep()`

```c
void msleep(unsigned int msecs)
```

sleep safely even with waitqueue interruptions

**Parameters**

- `unsigned int msecs`: Requested sleep duration in milliseconds

**Description**

[`msleep()`](#c-msleep) uses jiffy based timeouts for the sleep duration. Because of the
design of the timer wheel, the maximum additional percentage delay (slack) is
12.5%. This is only valid for timers which will end up in level 1 or a higher
level of the timer wheel. For explanation of those 12.5% please check the
detailed description about the basics of the timer wheel.

The slack of timers which will end up in level 0 depends on sleep duration
(msecs) and HZ configuration and can be calculated in the following way (with
the timer wheel design restriction that the slack is not less than 12.5%):

`slack = MSECS_PER_TICK / msecs`

When the allowed slack of the callsite is known, the calculation could be
turned around to find the minimal allowed sleep duration to meet the
constraints. For example:

* `HZ=1000` with `slack=25%`: `MSECS_PER_TICK / slack = 1 / (1/4) = 4`:
  all sleep durations greater or equal 4ms will meet the constraints.
* `HZ=1000` with `slack=12.5%`: `MSECS_PER_TICK / slack = 1 / (1/8) = 8`:
  all sleep durations greater or equal 8ms will meet the constraints.
* `HZ=250` with `slack=25%`: `MSECS_PER_TICK / slack = 4 / (1/4) = 16`:
  all sleep durations greater or equal 16ms will meet the constraints.
* `HZ=250` with `slack=12.5%`: `MSECS_PER_TICK / slack = 4 / (1/8) = 32`:
  all sleep durations greater or equal 32ms will meet the constraints.

See also the signal aware variant [`msleep_interruptible()`](#c-msleep_interruptible).

#### <a id="c-msleep_interruptible"></a>`msleep_interruptible()`

```c
unsigned long msleep_interruptible(unsigned int msecs)
```

sleep waiting for signals

**Parameters**

- `unsigned int msecs`: Requested sleep duration in milliseconds

**Description**

See [`msleep()`](#c-msleep) for some basic information.

The difference between [`msleep()`](#c-msleep) and [`msleep_interruptible()`](#c-msleep_interruptible) is that the sleep
could be interrupted by a signal delivery and then returns early.

**Return**

The remaining time of the sleep duration transformed to msecs (see
`schedule_timeout()` for details).



#### <a id="c-ssleep"></a>`ssleep()`

```c
void ssleep(unsigned int seconds)
```

wrapper for seconds around msleep

**Parameters**

- `unsigned int seconds`: Requested sleep duration in seconds

**Description**

Please refer to [`msleep()`](#c-msleep) for detailed information.

#### <a id="c-fsleep"></a>`fsleep()`

```c
void fsleep(unsigned long usecs)
```

flexible sleep which autoselects the best mechanism

**Parameters**

- `unsigned long usecs`: requested sleep duration in microseconds

**Description**

`flseep()` selects the best mechanism that will provide maximum 25% slack
to the requested sleep duration. Therefore it uses:

* [`udelay()`](#c-udelay) loop for sleep durations \<= 10 microseconds to avoid hrtimer
  overhead for really short sleep durations.
* [`usleep_range()`](#c-usleep_range) for sleep durations which would lead with the usage of
  [`msleep()`](#c-msleep) to a slack larger than 25%. This depends on the granularity of
  jiffies.
* [`msleep()`](#c-msleep) for all other sleep durations.

**Note**

When `CONFIG_HIGH_RES_TIMERS` is not set, all sleeps are processed with
the granularity of jiffies and the slack might exceed 25% especially for
short sleep durations.

---

# High resolution timers and dynamic ticks design notes

_Peios Kernel / Internals / Timers_

> Further information can be found in the paper of the OLS 2006 talk "hrtimers and beyond". The paper is part of the OLS 2006 Proceedings Volume 1, which can be found on the OLS website:…

<a id="rst-high-resolution-timers-and-dynamic-ticks-design-notes"></a>

Further information can be found in the paper of the OLS 2006 talk "hrtimers and beyond". The paper is part of the OLS 2006 Proceedings Volume 1, which can be found on the OLS website: [https://www.kernel.org/doc/ols/2006/ols2006v1-pages-333-346.pdf](<https://www.kernel.org/doc/ols/2006/ols2006v1-pages-333-346.pdf>)

The slides to this talk are available from: [http://www.cs.columbia.edu/\~nahum/w6998/papers/ols2006-hrtimers-slides.pdf](<http://www.cs.columbia.edu/~nahum/w6998/papers/ols2006-hrtimers-slides.pdf>)

The slides contain five figures (pages 2, 15, 18, 20, 22), which illustrate the changes in the time(r) related Linux subsystems. Figure \#1 (p. 2) shows the design of the Linux time(r) system before hrtimers and other building blocks got merged into mainline.

Note: the paper and the slides are talking about "clock event source", while we switched to the name "clock event devices" in meantime.

The design contains the following basic building blocks:

- hrtimer base infrastructure

- timeofday and clock source management

- clock event management

- high resolution timer functionality

- dynamic ticks

<a id="rst-hrtimer-base-infrastructure"></a>

## hrtimer base infrastructure

The hrtimer base infrastructure was merged into the 2.6.16 kernel. Details of the base implementation are covered in [Documentation/timers/hrtimers.rst](/kernel/internals/timers/hrtimers.md). See also figure \#2 (OLS slides p. 15)

The main differences to the timer wheel, which holds the armed timer_list type timers are:

> - time ordered enqueueing into a rb-tree
>
> - independent of ticks (the processing is based on nanoseconds)

<a id="rst-timeofday-and-clock-source-management"></a>

## timeofday and clock source management

John Stultz's Generic Time Of Day (GTOD) framework moves a large portion of code out of the architecture-specific areas into a generic management framework, as illustrated in figure \#3 (OLS slides p. 18). The architecture specific portion is reduced to the low level hardware details of the clock sources, which are registered in the framework and selected on a quality based decision. The low level code provides hardware setup and readout routines and initializes data structures, which are used by the generic time keeping code to convert the clock ticks to nanosecond based time values. All other time keeping related functionality is moved into the generic code. The GTOD base patch got merged into the 2.6.18 kernel.

Further information about the Generic Time Of Day framework is available in the OLS 2005 Proceedings Volume 1:

> [http://www.linuxsymposium.org/2005/linuxsymposium_procv1.pdf](<http://www.linuxsymposium.org/2005/linuxsymposium_procv1.pdf>)

The paper "We Are Not Getting Any Younger: A New Approach to Time and Timers" was written by J. Stultz, D.V. Hart, &amp; N. Aravamudan.

Figure \#3 (OLS slides p.18) illustrates the transformation.

<a id="rst-clock-event-management"></a>

## clock event management

While clock sources provide read access to the monotonically increasing time value, clock event devices are used to schedule the next event interrupt(s). The next event is currently defined to be periodic, with its period defined at compile time. The setup and selection of the event device for various event driven functionalities is hardwired into the architecture dependent code. This results in duplicated code across all architectures and makes it extremely difficult to change the configuration of the system to use event interrupt devices other than those already built into the architecture. Another implication of the current design is that it is necessary to touch all the architecture-specific implementations in order to provide new functionality like high resolution timers or dynamic ticks.

The clock events subsystem tries to address this problem by providing a generic solution to manage clock event devices and their usage for the various clock event driven kernel functionalities. The goal of the clock event subsystem is to minimize the clock event related architecture dependent code to the pure hardware related handling and to allow easy addition and utilization of new clock event devices. It also minimizes the duplicated code across the architectures as it provides generic functionality down to the interrupt service handler, which is almost inherently hardware dependent.

Clock event devices are registered either by the architecture dependent boot code or at module insertion time. Each clock event device fills a data structure with clock-specific property parameters and callback functions. The clock event management decides, by using the specified property parameters, the set of system functions a clock event device will be used to support. This includes the distinction of per-CPU and per-system global event devices.

System-level global event devices are used for the Linux periodic tick. Per-CPU event devices are used to provide local CPU functionality such as process accounting, profiling, and high resolution timers.

The management layer assigns one or more of the following functions to a clock event device:

> - system global periodic tick (jiffies update)
>
> - cpu local update_process_times
>
> - cpu local profiling
>
> - cpu local next event interrupt (non periodic mode)

The clock event device delegates the selection of those timer interrupt related functions completely to the management layer. The clock management layer stores a function pointer in the device description structure, which has to be called from the hardware level handler. This removes a lot of duplicated code from the architecture specific timer interrupt handlers and hands the control over the clock event devices and the assignment of timer interrupt related functionality to the core code.

The clock event layer API is rather small. Aside from the clock event device registration interface it provides functions to schedule the next event interrupt, clock event device notification service and support for suspend and resume.

The framework adds about 700 lines of code which results in a 2KB increase of the kernel binary size. The conversion of i386 removes about 100 lines of code. The binary size decrease is in the range of 400 byte. We believe that the increase of flexibility and the avoidance of duplicated code across architectures justifies the slight increase of the binary size.

The conversion of an architecture has no functional impact, but allows to utilize the high resolution and dynamic tick functionalities without any change to the clock event device and timer interrupt code. After the conversion the enabling of high resolution timers and dynamic ticks is simply provided by adding the kernel/time/Kconfig file to the architecture specific Kconfig and adding the dynamic tick specific calls to the idle routine (a total of 3 lines added to the idle function and the Kconfig file)

Figure \#4 (OLS slides p.20) illustrates the transformation.

<a id="rst-high-resolution-timer-functionality"></a>

## high resolution timer functionality

During system boot it is not possible to use the high resolution timer functionality, while making it possible would be difficult and would serve no useful function. The initialization of the clock event device framework, the clock source framework (GTOD) and hrtimers itself has to be done and appropriate clock sources and clock event devices have to be registered before the high resolution functionality can work. Up to the point where hrtimers are initialized, the system works in the usual low resolution periodic mode. The clock source and the clock event device layers provide notification functions which inform hrtimers about availability of new hardware. hrtimers validates the usability of the registered clock sources and clock event devices before switching to high resolution mode. This ensures also that a kernel which is configured for high resolution timers can run on a system which lacks the necessary hardware support.

The high resolution timer code does not support SMP machines which have only global clock event devices. The support of such hardware would involve IPI calls when an interrupt happens. The overhead would be much larger than the benefit. This is the reason why we currently disable high resolution and dynamic ticks on i386 SMP systems which stop the local APIC in C3 power state. A workaround is available as an idea, but the problem has not been tackled yet.

The time ordered insertion of timers provides all the infrastructure to decide whether the event device has to be reprogrammed when a timer is added. The decision is made per timer base and synchronized across per-cpu timer bases in a support function. The design allows the system to utilize separate per-CPU clock event devices for the per-CPU timer bases, but currently only one reprogrammable clock event device per-CPU is utilized.

When the timer interrupt happens, the next event interrupt handler is called from the clock event distribution code and moves expired timers from the red-black tree to a separate double linked list and invokes the softirq handler. An additional mode field in the hrtimer structure allows the system to execute callback functions directly from the next event interrupt handler. This is restricted to code which can safely be executed in the hard interrupt context. This applies, for example, to the common case of a wakeup function as used by nanosleep. The advantage of executing the handler in the interrupt context is the avoidance of up to two context switches - from the interrupted context to the softirq and to the task which is woken up by the expired timer.

Once a system has switched to high resolution mode, the periodic tick is switched off. This disables the per system global periodic clock event device - e.g. the PIT on i386 SMP systems.

The periodic tick functionality is provided by an per-cpu hrtimer. The callback function is executed in the next event interrupt context and updates jiffies and calls update_process_times and profiling. The implementation of the hrtimer based periodic tick is designed to be extended with dynamic tick functionality. This allows to use a single clock event device to schedule high resolution timer and periodic events (jiffies tick, profiling, process accounting) on UP systems. This has been proved to work with the PIT on i386 and the Incrementer on PPC.

The softirq for running the hrtimer queues and executing the callbacks has been separated from the tick bound timer softirq to allow accurate delivery of high resolution timer signals which are used by itimer and POSIX interval timers. The execution of this softirq can still be delayed by other softirqs, but the overall latencies have been significantly improved by this separation.

Figure \#5 (OLS slides p.22) illustrates the transformation.

<a id="rst-dynamic-ticks"></a>

## dynamic ticks

Dynamic ticks are the logical consequence of the hrtimer based periodic tick replacement (sched_tick). The functionality of the sched_tick hrtimer is extended by three functions:

- hrtimer_stop_sched_tick

- hrtimer_restart_sched_tick

- hrtimer_update_jiffies

hrtimer_stop_sched_tick() is called when a CPU goes into idle state. The code evaluates the next scheduled timer event (from both hrtimers and the timer wheel) and in case that the next event is further away than the next tick it reprograms the sched_tick to this future event, to allow longer idle sleeps without worthless interruption by the periodic tick. The function is also called when an interrupt happens during the idle period, which does not cause a reschedule. The call is necessary as the interrupt handler might have armed a new timer whose expiry time is before the time which was identified as the nearest event in the previous call to hrtimer_stop_sched_tick.

hrtimer_restart_sched_tick() is called when the CPU leaves the idle state before it calls schedule(). hrtimer_restart_sched_tick() resumes the periodic tick, which is kept active until the next call to hrtimer_stop_sched_tick().

hrtimer_update_jiffies() is called from irq_enter() when an interrupt happens in the idle period to make sure that jiffies are up to date and the interrupt handler has not to deal with an eventually stale jiffy value.

The dynamic tick feature provides statistical values which are exported to userspace via /proc/stat and can be made available for enhanced power management control.

The implementation leaves room for further development like full tickless systems, where the time slice is controlled by the scheduler, variable frequency profiling, and a complete removal of jiffies in the future.

Aside the current initial submission of i386 support, the patchset has been extended to x86_64 and ARM already. Initial (work in progress) support is also available for MIPS and PowerPC.

> Thomas, Ingo

---

# High Precision Event Timer Driver for Linux

_Peios Kernel / Internals / Timers_

> The High Precision Event Timer (HPET) hardware follows a specification by Intel and Microsoft, revision 1.

<a id="rst-high-precision-event-timer-driver-for-linux"></a>

The High Precision Event Timer (HPET) hardware follows a specification by Intel and Microsoft, revision 1.

Each HPET has one fixed-rate counter (at 10+ MHz, hence "High Precision") and up to 32 comparators.  Normally three or more comparators are provided, each of which can generate oneshot interrupts and at least one of which has additional hardware to support periodic interrupts.  The comparators are also called "timers", which can be misleading since usually timers are independent of each other ... these share a counter, complicating resets.

HPET devices can support two interrupt routing modes.  In one mode, the comparators are additional interrupt sources with no particular system role.  Many x86 BIOS writers don't route HPET interrupts at all, which prevents use of that mode.  They support the other "legacy replacement" mode where the first two comparators block interrupts from 8254 timers and from the RTC.

The driver supports detection of HPET driver allocation and initialization of the HPET before the driver module\_init routine is called.  This enables platform code which uses timer 0 or 1 as the main timer to intercept HPET initialization.  An example of this initialization can be found in arch/x86/kernel/hpet.c.

The driver provides a userspace API which resembles the API found in the RTC driver framework.  An example user space program is provided in [file:samples/timers/hpet\_example.c](<https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/samples/timers/hpet_example.c?id=9021cc14f7d98b4a1d2c932f52c5343d4d0f6b92>)

---

# hrtimers - subsystem for high-resolution kernel timers

_Peios Kernel / Internals / Timers_

> This patch introduces a new subsystem for high-resolution kernel timers.

<a id="rst-hrtimers-subsystem-for-high-resolution-kernel-timers"></a>

This patch introduces a new subsystem for high-resolution kernel timers.

One might ask the question: we already have a timer subsystem (kernel/timers.c), why do we need two timer subsystems? After a lot of back and forth trying to integrate high-resolution and high-precision features into the existing timer framework, and after testing various such high-resolution timer implementations in practice, we came to the conclusion that the timer wheel code is fundamentally not suitable for such an approach. We initially didn't believe this ('there must be a way to solve this'), and spent a considerable effort trying to integrate things into the timer wheel, but we failed. In hindsight, there are several reasons why such integration is hard/impossible:

- the forced handling of low-resolution and high-resolution timers in the same way leads to a lot of compromises, macro magic and \#ifdef mess. The timers.c code is very "tightly coded" around jiffies and 32-bitness assumptions, and has been honed and micro-optimized for a relatively narrow use case (jiffies in a relatively narrow HZ range) for many years - and thus even small extensions to it easily break the wheel concept, leading to even worse compromises. The timer wheel code is very good and tight code, there's zero problems with it in its current usage - but it is simply not suitable to be extended for high-res timers.

- the unpredictable \[O(N)\] overhead of cascading leads to delays which necessitate a more complex handling of high resolution timers, which in turn decreases robustness. Such a design still leads to rather large timing inaccuracies. Cascading is a fundamental property of the timer wheel concept, it cannot be 'designed out' without inevitably degrading other portions of the timers.c code in an unacceptable way.

- the implementation of the current posix-timer subsystem on top of the timer wheel has already introduced a quite complex handling of the required readjusting of absolute CLOCK_REALTIME timers at settimeofday or NTP time - further underlying our experience by example: that the timer wheel data structure is too rigid for high-res timers.

- the timer wheel code is most optimal for use cases which can be identified as "timeouts". Such timeouts are usually set up to cover error conditions in various I/O paths, such as networking and block I/O. The vast majority of those timers never expire and are rarely recascaded because the expected correct event arrives in time so they can be removed from the timer wheel before any further processing of them becomes necessary. Thus the users of these timeouts can accept the granularity and precision tradeoffs of the timer wheel, and largely expect the timer subsystem to have near-zero overhead. Accurate timing for them is not a core purpose - in fact most of the timeout values used are ad-hoc. For them it is at most a necessary evil to guarantee the processing of actual timeout completions (because most of the timeouts are deleted before completion), which should thus be as cheap and unintrusive as possible.

The primary users of precision timers are user-space applications that utilize nanosleep, posix-timers and itimer interfaces. Also, in-kernel users like drivers and subsystems which require precise timed events (e.g. multimedia) can benefit from the availability of a separate high-resolution timer subsystem as well.

While this subsystem does not offer high-resolution clock sources just yet, the hrtimer subsystem can be easily extended with high-resolution clock capabilities, and patches for that exist and are maturing quickly. The increasing demand for realtime and multimedia applications along with other potential users for precise timers gives another reason to separate the "timeout" and "precise timer" subsystems.

Another potential benefit is that such a separation allows even more special-purpose optimization of the existing timer wheel for the low resolution and low precision use cases - once the precision-sensitive APIs are separated from the timer wheel and are migrated over to hrtimers. E.g. we could decrease the frequency of the timeout subsystem from 250 Hz to 100 HZ (or even smaller).

<a id="rst-hrtimer-subsystem-implementation-details"></a>

## hrtimer subsystem implementation details

the basic design considerations were:

- simplicity

- data structure not bound to jiffies or any other granularity. All the kernel logic works at 64-bit nanoseconds resolution - no compromises.

- simplification of existing, timing related kernel code

another basic requirement was the immediate enqueueing and ordering of timers at activation time. After looking at several possible solutions such as radix trees and hashes, we chose the red black tree as the basic data structure. Rbtrees are available as a library in the kernel and are used in various performance-critical areas of e.g. memory management and file systems. The rbtree is solely used for time sorted ordering, while a separate list is used to give the expiry code fast access to the queued timers, without having to walk the rbtree.

(This separate list is also useful for later when we'll introduce high-resolution clocks, where we need separate pending and expired queues while keeping the time-order intact.)

Time-ordered enqueueing is not purely for the purposes of high-resolution clocks though, it also simplifies the handling of absolute timers based on a low-resolution CLOCK_REALTIME. The existing implementation needed to keep an extra list of all armed absolute CLOCK_REALTIME timers along with complex locking. In case of settimeofday and NTP, all the timers (\!) had to be dequeued, the time-changing code had to fix them up one by one, and all of them had to be enqueued again. The time-ordered enqueueing and the storage of the expiry time in absolute time units removes all this complex and poorly scaling code from the posix-timer implementation - the clock can simply be set without having to touch the rbtree. This also makes the handling of posix-timers simpler in general.

The locking and per-CPU behavior of hrtimers was mostly taken from the existing timer wheel code, as it is mature and well suited. Sharing code was not really a win, due to the different data structures. Also, the hrtimer functions now have clearer behavior and clearer names - such as hrtimer_try_to_cancel() and hrtimer_cancel() \[which are roughly equivalent to timer_delete() and timer_delete_sync()\] - so there's no direct 1:1 mapping between them on the algorithmic level, and thus no real potential for code sharing either.

Basic data types: every time value, absolute or relative, is in a special nanosecond-resolution 64bit type: ktime_t. (Originally, the kernel-internal representation of ktime_t values and operations was implemented via macros and inline functions, and could be switched between a "hybrid union" type and a plain "scalar" 64bit nanoseconds representation (at compile time). This was abandoned in the context of the Y2038 work.)

<a id="rst-hrtimers-rounding-of-timer-values"></a>

## hrtimers - rounding of timer values

the hrtimer code will round timer events to lower-resolution clocks because it has to. Otherwise it will do no artificial rounding at all.

one question is, what resolution value should be returned to the user by the clock_getres() interface. This will return whatever real resolution a given clock has - be it low-res, high-res, or artificially-low-res.

<a id="rst-hrtimers-testing-and-verification"></a>

## hrtimers - testing and verification

We used the high-resolution clock subsystem on top of hrtimers to verify the hrtimer implementation details in praxis, and we also ran the posix timer tests in order to ensure specification compliance. We also ran tests on low-resolution clocks.

The hrtimer patch converts the following kernel functionality to use hrtimers:

> - nanosleep
>
> - itimers
>
> - posix-timers

The conversion of nanosleep and posix-timers enabled the unification of nanosleep and clock_nanosleep.

The code was successfully compiled for the following platforms:

> i386, x86_64, ARM, PPC, PPC64, IA64

The code was run-tested on the following platforms:

> i386(UP/SMP), x86_64(UP/SMP), ARM, PPC

hrtimers were also integrated into the -rt tree, along with a hrtimers-based high-resolution clock implementation, so the hrtimers code got a healthy amount of testing and use in practice.

> Thomas Gleixner, Ingo Molnar

---

# NO_HZ: Reducing Scheduling-Clock Ticks

_Peios Kernel / Internals / Timers_

> This document describes Kconfig options and boot parameters that can reduce the number of scheduling-clock interrupts, thereby improving energy efficiency and reducing OS jitter. Reducing OS jitter is important for some types of…

<a id="rst-no-hz-reducing-scheduling-clock-ticks"></a>

This document describes Kconfig options and boot parameters that can reduce the number of scheduling-clock interrupts, thereby improving energy efficiency and reducing OS jitter.  Reducing OS jitter is important for some types of computationally intensive high-performance computing (HPC) applications and for real-time applications.

There are three main ways of managing scheduling-clock interrupts (also known as "scheduling-clock ticks" or simply "ticks"):

1. Never omit scheduling-clock ticks (CONFIG_HZ_PERIODIC=y or CONFIG_NO_HZ=n for older kernels).  You normally will -not- want to choose this option.

2. Omit scheduling-clock ticks on idle CPUs (CONFIG_NO_HZ_IDLE=y or CONFIG_NO_HZ=y for older kernels).  This is the most common approach, and should be the default.

3. Omit scheduling-clock ticks on CPUs that are either idle or that have only one runnable task (CONFIG_NO_HZ_FULL=y).  Unless you are running realtime applications or certain types of HPC workloads, you will normally -not- want this option.

These three cases are described in the following three sections, followed by a third section on RCU-specific considerations, a fourth section discussing testing, and a fifth and final section listing known issues.

<a id="rst-never-omit-scheduling-clock-ticks"></a>

## Never Omit Scheduling-Clock Ticks

Very old versions of Linux from the 1990s and the very early 2000s are incapable of omitting scheduling-clock ticks.  It turns out that there are some situations where this old-school approach is still the right approach, for example, in heavy workloads with lots of tasks that use short bursts of CPU, where there are very frequent idle periods, but where these idle periods are also quite short (tens or hundreds of microseconds).  For these types of workloads, scheduling clock interrupts will normally be delivered any way because there will frequently be multiple runnable tasks per CPU.  In these cases, attempting to turn off the scheduling clock interrupt will have no effect other than increasing the overhead of switching to and from idle and transitioning between user and kernel execution.

This mode of operation can be selected using CONFIG_HZ_PERIODIC=y (or CONFIG_NO_HZ=n for older kernels).

However, if you are instead running a light workload with long idle periods, failing to omit scheduling-clock interrupts will result in excessive power consumption.  This is especially bad on battery-powered devices, where it results in extremely short battery lifetimes.  If you are running light workloads, you should therefore read the following section.

In addition, if you are running either a real-time workload or an HPC workload with short iterations, the scheduling-clock interrupts can degrade your applications performance.  If this describes your workload, you should read the following two sections.

<a id="rst-omit-scheduling-clock-ticks-for-idle-cpus"></a>

## Omit Scheduling-Clock Ticks For Idle CPUs

If a CPU is idle, there is little point in sending it a scheduling-clock interrupt.  After all, the primary purpose of a scheduling-clock interrupt is to force a busy CPU to shift its attention among multiple duties, and an idle CPU has no duties to shift its attention among.

An idle CPU that is not receiving scheduling-clock interrupts is said to be "dyntick-idle", "in dyntick-idle mode", "in nohz mode", or "running tickless".  The remainder of this document will use "dyntick-idle mode".

The CONFIG_NO_HZ_IDLE=y Kconfig option causes the kernel to avoid sending scheduling-clock interrupts to idle CPUs, which is critically important both to battery-powered devices and to highly virtualized mainframes. A battery-powered device running a CONFIG_HZ_PERIODIC=y kernel would drain its battery very quickly, easily 2-3 times as fast as would the same device running a CONFIG_NO_HZ_IDLE=y kernel.  A mainframe running 1,500 OS instances might find that half of its CPU time was consumed by unnecessary scheduling-clock interrupts.  In these situations, there is strong motivation to avoid sending scheduling-clock interrupts to idle CPUs.  That said, dyntick-idle mode is not free:

1. It increases the number of instructions executed on the path to and from the idle loop.

2. On many architectures, dyntick-idle mode also increases the number of expensive clock-reprogramming operations.

Therefore, systems with aggressive real-time response constraints often run CONFIG_HZ_PERIODIC=y kernels (or CONFIG_NO_HZ=n for older kernels) in order to avoid degrading from-idle transition latencies.

There is also a boot parameter "nohz=" that can be used to disable dyntick-idle mode in CONFIG_NO_HZ_IDLE=y kernels by specifying "nohz=off". By default, CONFIG_NO_HZ_IDLE=y kernels boot with "nohz=on", enabling dyntick-idle mode.

<a id="rst-omit-scheduling-clock-ticks-for-cpus-with-only-one-runnable-task"></a>

## Omit Scheduling-Clock Ticks For CPUs With Only One Runnable Task

If a CPU has only one runnable task, there is little point in sending it a scheduling-clock interrupt because there is no other task to switch to. Note that omitting scheduling-clock ticks for CPUs with only one runnable task implies also omitting them for idle CPUs.

The CONFIG_NO_HZ_FULL=y Kconfig option causes the kernel to avoid sending scheduling-clock interrupts to CPUs with a single runnable task, and such CPUs are said to be "adaptive-ticks CPUs".  This is important for applications with aggressive real-time response constraints because it allows them to improve their worst-case response times by the maximum duration of a scheduling-clock interrupt.  It is also important for computationally intensive short-iteration workloads:  If any CPU is delayed during a given iteration, all the other CPUs will be forced to wait idle while the delayed CPU finishes.  Thus, the delay is multiplied by one less than the number of CPUs.  In these situations, there is again strong motivation to avoid sending scheduling-clock interrupts.

By default, no CPU will be an adaptive-ticks CPU.  The "nohz_full=" boot parameter specifies the adaptive-ticks CPUs.  For example, "nohz_full=1,6-8" says that CPUs 1, 6, 7, and 8 are to be adaptive-ticks CPUs.  Note that you are prohibited from marking all of the CPUs as adaptive-tick CPUs:  At least one non-adaptive-tick CPU must remain online to handle timekeeping tasks in order to ensure that system calls like gettimeofday() returns accurate values on adaptive-tick CPUs. (This is not an issue for CONFIG_NO_HZ_IDLE=y because there are no running user processes to observe slight drifts in clock rate.) Note that this means that your system must have at least two CPUs in order for CONFIG_NO_HZ_FULL=y to do anything for you.

Finally, adaptive-ticks CPUs must have their RCU callbacks offloaded. This is covered in the "RCU IMPLICATIONS" section below.

Normally, a CPU remains in adaptive-ticks mode as long as possible. In particular, transitioning to kernel mode does not automatically change the mode.  Instead, the CPU will exit adaptive-ticks mode only if needed, for example, if that CPU enqueues an RCU callback.

Just as with dyntick-idle mode, the benefits of adaptive-tick mode do not come for free:

1. CONFIG_NO_HZ_FULL selects CONFIG_NO_HZ_COMMON, so you cannot run adaptive ticks without also running dyntick idle.  This dependency extends down into the implementation, so that all of the costs of CONFIG_NO_HZ_IDLE are also incurred by CONFIG_NO_HZ_FULL.

2. The user/kernel transitions are slightly more expensive due to the need to inform kernel subsystems (such as RCU) about the change in mode.

3. POSIX CPU timers prevent CPUs from entering adaptive-tick mode. Real-time applications needing to take actions based on CPU time consumption need to use other means of doing so.

4. If there are more perf events pending than the hardware can accommodate, they are normally round-robined so as to collect all of them over time.  Adaptive-tick mode may prevent this round-robining from happening.  This will likely be fixed by preventing CPUs with large numbers of perf events pending from entering adaptive-tick mode.

5. Scheduler statistics for adaptive-tick CPUs may be computed slightly differently than those for non-adaptive-tick CPUs. This might in turn perturb load-balancing of real-time tasks.

Although improvements are expected over time, adaptive ticks is quite useful for many types of real-time and compute-intensive applications. However, the drawbacks listed above mean that adaptive ticks should not (yet) be enabled by default.

<a id="rst-rcu-implications"></a>

## RCU Implications

There are situations in which idle CPUs cannot be permitted to enter either dyntick-idle mode or adaptive-tick mode, the most common being when that CPU has RCU callbacks pending.

Avoid this by offloading RCU callback processing to "rcuo" kthreads using the CONFIG_RCU_NOCB_CPU=y Kconfig option.  The specific CPUs to offload may be selected using The "rcu_nocbs=" kernel boot parameter, which takes a comma-separated list of CPUs and CPU ranges, for example, "1,3-5" selects CPUs 1, 3, 4, and 5.  Note that CPUs specified by the "nohz_full" kernel boot parameter are also offloaded.

The offloaded CPUs will never queue RCU callbacks, and therefore RCU never prevents offloaded CPUs from entering either dyntick-idle mode or adaptive-tick mode.  That said, note that it is up to userspace to pin the "rcuo" kthreads to specific CPUs if desired.  Otherwise, the scheduler will decide where to run them, which might or might not be where you want them to run.

<a id="rst-testing"></a>

## Testing

So you enable all the OS-jitter features described in this document, but do not see any change in your workload's behavior.  Is this because your workload isn't affected that much by OS jitter, or is it because something else is in the way?  This section helps answer this question by providing a simple OS-jitter test suite, which is available on branch master of the following git archive:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/dynticks-testing.git

Clone this archive and follow the instructions in the README file. This test procedure will produce a trace that will allow you to evaluate whether or not you have succeeded in removing OS jitter from your system. If this trace shows that you have removed OS jitter as much as is possible, then you can conclude that your workload is not all that sensitive to OS jitter.

Note: this test requires that your system have at least two CPUs. We do not currently have a good way to remove OS jitter from single-CPU systems.

<a id="rst-known-issues"></a>

## Known Issues

- Dyntick-idle slows transitions to and from idle slightly. In practice, this has not been a problem except for the most aggressive real-time workloads, which have the option of disabling dyntick-idle mode, an option that most of them take.  However, some workloads will no doubt want to use adaptive ticks to eliminate scheduling-clock interrupt latencies.  Here are some options for these workloads:

  - **a.** Use PMQOS from userspace to inform the kernel of your latency requirements (preferred).

  - **b.** On x86 systems, use the "idle=mwait" boot parameter.

  c.      On x86 systems, use the "intel_idle.max_cstate=" to limit \`       the maximum C-state depth.

  - **d.** On x86 systems, use the "idle=poll" boot parameter. However, please note that use of this parameter can cause your CPU to overheat, which may cause thermal throttling to degrade your latencies -- and that this degradation can be even worse than that of dyntick-idle.  Furthermore, this parameter effectively disables Turbo Mode on Intel CPUs, which can significantly reduce maximum performance.

- Adaptive-ticks slows user/kernel transitions slightly. This is not expected to be a problem for computationally intensive workloads, which have few such transitions.  Careful benchmarking will be required to determine whether or not other workloads are significantly affected by this effect.

- Adaptive-ticks does not do anything unless there is only one runnable task for a given CPU, even though there are a number of other situations where the scheduling-clock tick is not needed.  To give but one example, consider a CPU that has one runnable high-priority SCHED_FIFO task and an arbitrary number of low-priority SCHED_OTHER tasks.  In this case, the CPU is required to run the SCHED_FIFO task until it either blocks or some other higher-priority task awakens on (or is assigned to) this CPU, so there is no point in sending a scheduling-clock interrupt to this CPU.  However, the current implementation nevertheless sends scheduling-clock interrupts to CPUs having a single runnable SCHED_FIFO task and multiple runnable SCHED_OTHER tasks, even though these interrupts are unnecessary.

  And even when there are multiple runnable tasks on a given CPU, there is little point in interrupting that CPU until the current running task's timeslice expires, which is almost always way longer than the time of the next scheduling-clock interrupt.

  Better handling of these sorts of situations is future work.

- A reboot is required to reconfigure both adaptive idle and RCU callback offloading.  Runtime reconfiguration could be provided if needed, however, due to the complexity of reconfiguring RCU at runtime, there would need to be an earthshakingly good reason. Especially given that you have the straightforward option of simply offloading RCU callbacks from all CPUs and pinning them where you want them whenever you want them pinned.

- Additional configuration is required to deal with other sources of OS jitter, including interrupts and system-utility tasks and processes.  This configuration normally involves binding interrupts and tasks to particular CPUs.

- Some sources of OS jitter can currently be eliminated only by constraining the workload.  For example, the only way to eliminate OS jitter due to global TLB shootdowns is to avoid the unmapping operations (such as kernel module unload operations) that result in these shootdowns.  For another example, page faults and TLB misses can be reduced (and in some cases eliminated) by using huge pages and by constraining the amount of memory used by the application.  Pre-faulting the working set can also be helpful, especially when combined with the mlock() and mlockall() system calls.

- Unless all CPUs are idle, at least one CPU must keep the scheduling-clock interrupt going in order to support accurate timekeeping.

- If there might potentially be some adaptive-ticks CPUs, there will be at least one CPU keeping the scheduling-clock interrupt going, even if all CPUs are otherwise idle.

  Better handling of this situation is ongoing work.

- Some process-handling operations still require the occasional scheduling-clock tick.  These operations include calculating CPU load, maintaining sched average, computing CFS entity vruntime, computing avenrun, and carrying out load balancing.  They are currently accommodated by scheduling-clock tick every second or so.  On-going work will eliminate the need even for these infrequent scheduling-clock ticks.

---

# Clock sources, Clock events, sched_clock() and delay timers

_Peios Kernel / Internals / Timers_

> This document tries to briefly explain some basic kernel timekeeping abstractions. It partly pertains to the drivers usually found in drivers/clocksource in the kernel tree, but the code may be spread out across the kernel.

<a id="rst-clock-sources-clock-events-sched-clock-and-delay-timers"></a>

This document tries to briefly explain some basic kernel timekeeping abstractions. It partly pertains to the drivers usually found in drivers/clocksource in the kernel tree, but the code may be spread out across the kernel.

If you grep through the kernel source you will find a number of architecture- specific implementations of clock sources, clockevents and several likewise architecture-specific overrides of the sched_clock() function and some delay timers.

To provide timekeeping for your platform, the clock source provides the basic timeline, whereas clock events shoot interrupts on certain points on this timeline, providing facilities such as high-resolution timers. sched_clock() is used for scheduling and timestamping, and delay timers provide an accurate delay source using hardware counters.

<a id="rst-clock-sources"></a>

## Clock sources

The purpose of the clock source is to provide a timeline for the system that tells you where you are in time. For example issuing the command 'date' on a Linux system will eventually read the clock source to determine exactly what time it is.

Typically the clock source is a monotonic, atomic counter which will provide n bits which count from 0 to (2^n)-1 and then wraps around to 0 and start over. It will ideally NEVER stop ticking as long as the system is running. It may stop during system suspend.

The clock source shall have as high resolution as possible, and the frequency shall be as stable and correct as possible as compared to a real-world wall clock. It should not move unpredictably back and forth in time or miss a few cycles here and there.

It must be immune to the kind of effects that occur in hardware where e.g. the counter register is read in two phases on the bus lowest 16 bits first and the higher 16 bits in a second bus cycle with the counter bits potentially being updated in between leading to the risk of very strange values from the counter.

When the wall-clock accuracy of the clock source isn't satisfactory, there are various quirks and layers in the timekeeping code for e.g. synchronizing the user-visible time to RTC clocks in the system or against networked time servers using NTP, but all they do basically is update an offset against the clock source, which provides the fundamental timeline for the system. These measures does not affect the clock source per se, they only adapt the system to the shortcomings of it.

The clock source struct shall provide means to translate the provided counter into a nanosecond value as an unsigned long long (unsigned 64 bit) number. Since this operation may be invoked very often, doing this in a strict mathematical sense is not desirable: instead the number is taken as close as possible to a nanosecond value using only the arithmetic operations multiply and shift, so in clocksource_cyc2ns() you find:

> ns \~= (clocksource \* mult) &gt;&gt; shift

You will find a number of helper functions in the clock source code intended to aid in providing these mult and shift values, such as clocksource_khz2mult(), clocksource_hz2mult() that help determine the mult factor from a fixed shift, and clocksource_register_hz() and clocksource_register_khz() which will help out assigning both shift and mult factors using the frequency of the clock source as the only input.

For real simple clock sources accessed from a single I/O memory location there is nowadays even clocksource_mmio_init() which will take a memory location, bit width, a parameter telling whether the counter in the register counts up or down, and the timer clock rate, and then conjure all necessary parameters.

Since a 32-bit counter at say 100 MHz will wrap around to zero after some 43 seconds, the code handling the clock source will have to compensate for this. That is the reason why the clock source struct also contains a 'mask' member telling how many bits of the source are valid. This way the timekeeping code knows when the counter will wrap around and can insert the necessary compensation code on both sides of the wrap point so that the system timeline remains monotonic.

<a id="rst-clock-events"></a>

## Clock events

Clock events are the conceptual reverse of clock sources: they take a desired time specification value and calculate the values to poke into hardware timer registers.

Clock events are orthogonal to clock sources. The same hardware and register range may be used for the clock event, but it is essentially a different thing. The hardware driving clock events has to be able to fire interrupts, so as to trigger events on the system timeline. On an SMP system, it is ideal (and customary) to have one such event driving timer per CPU core, so that each core can trigger events independently of any other core.

You will notice that the clock event device code is based on the same basic idea about translating counters to nanoseconds using mult and shift arithmetic, and you find the same family of helper functions again for assigning these values. The clock event driver does not need a 'mask' attribute however: the system will not try to plan events beyond the time horizon of the clock event.

<a id="rst-sched-clock"></a>

## sched_clock()

In addition to the clock sources and clock events there is a special weak function in the kernel called sched_clock(). This function shall return the number of nanoseconds since the system was started. An architecture may or may not provide an implementation of sched_clock() on its own. If a local implementation is not provided, the system jiffy counter will be used as sched_clock().

As the name suggests, sched_clock() is used for scheduling the system, determining the absolute timeslice for a certain process in the CFS scheduler for example. It is also used for printk timestamps when you have selected to include time information in printk for things like bootcharts.

Compared to clock sources, sched_clock() has to be very fast: it is called much more often, especially by the scheduler. If you have to do trade-offs between accuracy compared to the clock source, you may sacrifice accuracy for speed in sched_clock(). It however requires some of the same basic characteristics as the clock source, i.e. it should be monotonic.

The sched_clock() function may wrap only on unsigned long long boundaries, i.e. after 64 bits. Since this is a nanosecond value this will mean it wraps after circa 585 years. (For most practical systems this means "never".)

If an architecture does not provide its own implementation of this function, it will fall back to using jiffies, making its maximum resolution 1/HZ of the jiffy frequency for the architecture. This will affect scheduling accuracy and will likely show up in system benchmarks.

The clock driving sched_clock() may stop or reset to zero during system suspend/sleep. This does not matter to the function it serves of scheduling events on the system. However it may result in interesting timestamps in printk().

The sched_clock() function should be callable in any context, IRQ- and NMI-safe and return a sane value in any context.

Some architectures may have a limited set of time sources and lack a nice counter to derive a 64-bit nanosecond value, so for example on the ARM architecture, special helper functions have been created to provide a sched_clock() nanosecond base from a 16- or 32-bit counter. Sometimes the same counter that is also used as clock source is used for this purpose.

On SMP systems, it is crucial for performance that sched_clock() can be called independently on each CPU without any synchronization performance hits. Some hardware (such as the x86 TSC) will cause the sched_clock() function to drift between the CPUs on the system. The kernel can work around this by enabling the CONFIG_HAVE_UNSTABLE_SCHED_CLOCK option. This is another aspect that makes sched_clock() different from the ordinary clock source.

<a id="rst-delay-timers-some-architectures-only"></a>

## Delay timers (some architectures only)

On systems with variable CPU frequency, the various kernel delay() functions will sometimes behave strangely. Basically these delays usually use a hard loop to delay a certain number of jiffy fractions using a "lpj" (loops per jiffy) value, calibrated on boot.

Let's hope that your system is running on maximum frequency when this value is calibrated: as an effect when the frequency is geared down to half the full frequency, any delay() will be twice as long. Usually this does not hurt, as you're commonly requesting that amount of delay *or more*. But basically the semantics are quite unpredictable on such systems.

Enter timer-based delays. Using these, a timer read may be used instead of a hard-coded loop for providing the desired delay.

This is done by declaring a struct delay_timer and assigning the appropriate function pointers and rate settings for this delay timer.

This is available on some architectures like OpenRISC or ARM.
